commit e331d91e9687d31cebf842aeb5aa4c91e12a4021
parent 26dd4f59ae0a147f498a5e073f7c6ccbd3ee320d
Author: triesap <tyson@radroots.org>
Date: Thu, 8 Oct 2026 20:03:56 +0000
messages: qualify nested encoded-size limits (HCP-079)
- Measure genuine self and peer envelope layers from one immutable rumor.
- Verify UTF-8 and serialization boundaries without truncating trusted text.
- Check stock NIP-44 padding and detached signed JSON size admission.
- Keep fixture keys ephemeral and preserve native inputs and dependency pins.
Diffstat:
4 files changed, 433 insertions(+), 2 deletions(-)
diff --git a/web/tests/conformance/nested-envelope-sizes.test.ts b/web/tests/conformance/nested-envelope-sizes.test.ts
@@ -0,0 +1,204 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ generateSecretKey,
+ getPublicKey,
+ finalizeEvent
+} from 'applesauce-core/helpers';
+import { nip44 } from 'applesauce-core/helpers/encryption';
+import { buildCanonicalPairRumor } from '../../src/lib/nostr/rumor-template.ts';
+import { verifyOutboundLayerData } from '../../src/lib/nostr/outbound-envelope-layers.ts';
+const bytes = (value: string) => new TextEncoder().encode(value).length;
+function input(peer: string, content: string) {
+ return JSON.stringify({
+ recipients: [{ public_key: peer, relay_url: null }],
+ content,
+ reply_to: null,
+ subject: null
+ });
+}
+await test('4096 UTF8 body boundaries and serialization overhead reject unchanged originals, never truncate', () => {
+ const secret = generateSecretKey(),
+ peerSecret = generateSecretKey();
+ try {
+ const owner = getPublicKey(secret),
+ peer = getPublicKey(peerSecret);
+ const cases = [
+ ['ASCII', 'x'.repeat(4096)],
+ ['BMP', 'é'.repeat(2048)],
+ ['astral', '😀'.repeat(1024)]
+ ];
+ for (const [label, body] of cases) {
+ const raw = input(peer, body),
+ rumor = buildCanonicalPairRumor(raw, owner, 1700000000);
+ assert.equal(bytes(body), 4096);
+ assert.ok(rumor, label);
+ assert.equal(rumor.content, body);
+ assert.ok(bytes(JSON.stringify(rumor)) <= 8192);
+ assert.equal(
+ buildCanonicalPairRumor(input(peer, body + 'x'), owner, 1700000000),
+ undefined
+ );
+ assert.equal(raw, input(peer, body));
+ }
+ for (const body of [
+ '\ud800',
+ '\udc00',
+ '"'.repeat(4096),
+ '\\'.repeat(4096),
+ '\n'.repeat(4096),
+ '\u0001'.repeat(4096)
+ ]) {
+ const raw = input(peer, body);
+ assert.equal(buildCanonicalPairRumor(raw, owner, 1700000000), undefined);
+ assert.equal(raw, input(peer, body));
+ }
+ } finally {
+ secret.fill(0);
+ peerSecret.fill(0);
+ }
+});
+await test('stock SDK padding steps are measured from actual standard payloads and roundtrip without extended mode', () => {
+ const secret = generateSecretKey(),
+ peerSecret = generateSecretKey();
+ let conversation: Uint8Array | undefined;
+ try {
+ conversation = nip44.v2.utils.getConversationKey(
+ secret,
+ getPublicKey(peerSecret)
+ );
+ const rows = [];
+ for (const [size, expected] of [
+ [32, 132],
+ [33, 176],
+ [256, 432],
+ [257, 516],
+ [4096, 5552],
+ [4097, 6916],
+ [8192, 11012],
+ [8193, 13744],
+ [16384, 21936],
+ [16385, 27396]
+ ]) {
+ const plain = 'x'.repeat(size),
+ cipher = nip44.v2.encrypt(plain, conversation);
+ assert.equal(bytes(cipher), expected);
+ assert.equal(nip44.v2.decrypt(cipher, conversation), plain);
+ rows.push({
+ plaintext_utf8: size,
+ ciphertext_utf8: bytes(cipher),
+ mode: 'stock_standard_v2_primitive_only'
+ });
+ }
+ console.log(
+ JSON.stringify({
+ fixture: 'HCP079_ACTUAL_STOCK_PADDING_NOT_PRODUCT_ADMISSION',
+ rows
+ })
+ );
+ } finally {
+ conversation?.fill(0);
+ secret.fill(0);
+ peerSecret.fill(0);
+ }
+});
+await test('valid signed detached serialized seal and outer exact caps accept, plus one rejects before admission', () => {
+ const secret = generateSecretKey(),
+ peerSecret = generateSecretKey(),
+ outerSecret = generateSecretKey();
+ let conversation: Uint8Array | undefined,
+ outerConversation: Uint8Array | undefined;
+ try {
+ const owner = getPublicKey(secret),
+ peer = getPublicKey(peerSecret),
+ rumor = buildCanonicalPairRumor(
+ input(peer, 'bounded fixture'),
+ owner,
+ 1700000000
+ );
+ assert.ok(rumor);
+ const original = JSON.stringify(rumor);
+ conversation = nip44.v2.utils.getConversationKey(secret, peer);
+ const seal = finalizeEvent(
+ {
+ kind: 13,
+ created_at: 1699999000,
+ tags: [],
+ content: nip44.v2.encrypt(original, conversation)
+ },
+ secret
+ ),
+ sealWire = JSON.stringify(seal);
+ outerConversation = nip44.v2.utils.getConversationKey(outerSecret, peer);
+ const outer = finalizeEvent(
+ {
+ kind: 1059,
+ created_at: 1699998000,
+ tags: [['p', peer]],
+ content: nip44.v2.encrypt(sealWire, outerConversation)
+ },
+ outerSecret
+ ),
+ outerWire = JSON.stringify(outer);
+ assert.equal(nip44.v2.decrypt(seal.content, conversation), original);
+ assert.equal(nip44.v2.decrypt(outer.content, outerConversation), sealWire);
+ // Valid JSON whitespace changes serialized admission bytes, not signed data.
+ // These detached fixtures do NOT claim factory custody or genuine maxima.
+ const atSeal = sealWire + ' '.repeat(16384 - bytes(sealWire)),
+ atOuter = outerWire + ' '.repeat(32768 - bytes(outerWire));
+ assert.equal(bytes(atSeal), 16384);
+ assert.equal(bytes(atOuter), 32768);
+ assert.equal(
+ verifyOutboundLayerData(
+ original,
+ original,
+ atSeal,
+ atOuter,
+ owner,
+ peer,
+ 'peer'
+ ),
+ true
+ );
+ assert.equal(
+ verifyOutboundLayerData(
+ original,
+ original,
+ atSeal + ' ',
+ atOuter,
+ owner,
+ peer,
+ 'peer'
+ ),
+ false
+ );
+ assert.equal(
+ verifyOutboundLayerData(
+ original,
+ original,
+ atSeal,
+ atOuter + ' ',
+ owner,
+ peer,
+ 'peer'
+ ),
+ false
+ );
+ console.log(
+ JSON.stringify({
+ fixture:
+ 'HCP079_DETACHED_SIGNED_RAW_JSON_BOUNDARIES_NOT_FACTORY_MAXIMA',
+ seal_utf8: bytes(atSeal),
+ outer_utf8: bytes(atOuter),
+ seal_plus_one_rejected: true,
+ outer_plus_one_rejected: true
+ })
+ );
+ } finally {
+ conversation?.fill(0);
+ outerConversation?.fill(0);
+ secret.fill(0);
+ peerSecret.fill(0);
+ outerSecret.fill(0);
+ }
+});
diff --git a/web/tests/e2e/harness/giftwrap-builder.ts b/web/tests/e2e/harness/giftwrap-builder.ts
@@ -69,7 +69,9 @@ export type Mode =
| 'stop_capability_after_key';
// Ephemeral source-only provider: actual stock SDK encryption/signature and real
// Chromium IDB/WebLocks. No installed extension/relay/client qualification.
-export async function makeFixture() {
+export async function makeFixture(
+ inputText: unknown = 'Private seal sentinel'
+) {
const secret = generateSecretKey(),
peerSecret = generateSecretKey(),
owner = getPublicKey(secret),
@@ -230,7 +232,7 @@ export async function makeFixture() {
const plan = captureEnquiryRumor(
identity,
context,
- 'Private seal sentinel',
+ inputText,
Math.floor(reservationTime / 1000)
);
if (!plan) throw Error('missing plan');
@@ -264,6 +266,13 @@ export async function makeFixture() {
peer,
identity,
reserved,
+ textPlan: (text: unknown) =>
+ captureEnquiryRumor(
+ identity,
+ context,
+ text,
+ Math.floor(Date.now() / 1000)
+ ),
async reserveAgain() {
const result = await reserveSendIdentity(
repository,
diff --git a/web/tests/e2e/harness/nested-envelope-sizes.ts b/web/tests/e2e/harness/nested-envelope-sizes.ts
@@ -0,0 +1,7 @@
+export * from './giftwrap-builder.ts';
+export * from '../../../src/lib/messaging/envelope-preparation.ts';
+export { reservedSendRumorWire } from '../../../src/lib/messaging/send-identity.ts';
+export {
+ rumorPlanSnapshot,
+ stopRumorPlan
+} from '../../../src/lib/messaging/rumor-plan.ts';
diff --git a/web/tests/e2e/nested-envelope-sizes.spec.ts b/web/tests/e2e/nested-envelope-sizes.spec.ts
@@ -0,0 +1,211 @@
+import { test, expect, type Page } from '@playwright/test';
+import { build } from 'vite';
+import { fileURLToPath } from 'node:url';
+import { createStaticHarness } from '../integration/harness/static.ts';
+import type * as Sizes from './harness/nested-envelope-sizes.ts';
+declare global {
+ interface Window {
+ hcp079: typeof Sizes;
+ }
+}
+let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string;
+test.beforeAll(async () => {
+ server = await createStaticHarness();
+ const built = await build({
+ configFile: false,
+ logLevel: 'silent',
+ build: {
+ write: false,
+ minify: false,
+ lib: {
+ entry: fileURLToPath(
+ new URL('./harness/nested-envelope-sizes.ts', import.meta.url)
+ ),
+ name: 'hcp079',
+ formats: ['iife']
+ }
+ }
+ });
+ const output = Array.isArray(built) ? built[0] : built;
+ if (!('output' in output)) throw Error('missing bundle');
+ const chunks = output.output.filter((x) => x.type === 'chunk');
+ expect(chunks).toHaveLength(1);
+ bundle = chunks[0].code;
+});
+test.afterAll(async () => server.close());
+async function load(page: Page) {
+ await page.goto(server.url + '/search');
+ await page.addScriptTag({ content: bundle });
+}
+for (const shape of [
+ 'ASCII',
+ 'BMP',
+ 'astral',
+ 'maximum_escaped_rumor'
+] as const)
+ test(`${shape}: actual genuine pair measures every encoded layer and keeps one original`, async ({
+ page
+ }) => {
+ await load(page);
+ const result = await page.evaluate(async (shape) => {
+ const s = window.hcp079,
+ bytes = (value: string) => new TextEncoder().encode(value).length;
+ let fixture = await s.makeFixture();
+ try {
+ const initial = s.reservedSendRumorWire(fixture.reserved);
+ if (!initial) throw Error('missing original');
+ const before = fixture.counts();
+ let text: string;
+ function inspect(text: string) {
+ const plan = fixture.textPlan(text);
+ if (!plan) return undefined;
+ try {
+ return s.rumorPlanSnapshot(plan);
+ } finally {
+ s.stopRumorPlan(plan);
+ }
+ }
+ if (shape === 'maximum_escaped_rumor') {
+ let low = 0,
+ high = 4096;
+ while (low < high) {
+ const middle = Math.ceil((low + high) / 2);
+ if (inspect('\u0001'.repeat(middle))) low = middle;
+ else high = middle - 1;
+ }
+ text = '\u0001'.repeat(low);
+ for (let rest = 0; rest < 6; rest++) {
+ if (inspect(text + 'x')) text += 'x';
+ else break;
+ }
+ const top = inspect(text);
+ if (!top || bytes(top.wire) !== 8192)
+ throw Error('maximum rumor not reached');
+ } else {
+ const first = JSON.parse(initial) as { content: string };
+ const overhead =
+ bytes(first.content) - bytes('Private seal sentinel'),
+ remaining = 4096 - overhead;
+ const width = shape === 'ASCII' ? 1 : shape === 'BMP' ? 2 : 4,
+ character = shape === 'ASCII' ? 'x' : shape === 'BMP' ? 'é' : '😀';
+ text =
+ character.repeat(Math.floor(remaining / width)) +
+ 'x'.repeat(remaining % width);
+ }
+ const accepted = inspect(text),
+ rejected = inspect(text + 'x');
+ if (!accepted) throw Error('missing maximum plan');
+ const unchanged =
+ JSON.stringify(before) === JSON.stringify(fixture.counts()) &&
+ s.reservedSendRumorWire(fixture.reserved) === initial;
+ const planning = {
+ accepted: true,
+ plusOneRejected: !rejected,
+ noSDK: unchanged
+ };
+ fixture.close();
+ fixture = await s.makeFixture(text);
+ const original = s.reservedSendRumorWire(fixture.reserved);
+ if (!original) throw Error('missing new original');
+ const rumor = JSON.parse(original) as {
+ id: string;
+ created_at: number;
+ content: string;
+ tags: string[][];
+ };
+ const pair = s.captureEnvelopePreparation(
+ fixture.identity,
+ fixture.reserved,
+ 'reviewed_envelope_pair'
+ );
+ if (!pair) throw Error('missing pair');
+ const started = fixture.counts();
+ const self = await s.prepareEnvelopeRole(
+ pair,
+ 'self',
+ 'reviewed_pair_role'
+ ),
+ peer = await s.prepareEnvelopeRole(
+ pair,
+ 'peer',
+ 'reviewed_pair_role'
+ ),
+ complete = s.envelopePreparationSnapshot(pair);
+ if (!complete?.self || !complete.peer) throw Error('pair incomplete');
+ const rows = [];
+ for (const role of ['self', 'peer'] as const) {
+ const outer = role === 'self' ? complete.self : complete.peer,
+ sealWire = fixture.decryptWrap(outer.wire, role),
+ seal = JSON.parse(sealWire) as { content: string },
+ wrap = JSON.parse(outer.wire) as {
+ content: string;
+ tags: string[][];
+ };
+ rows.push({
+ role,
+ body_utf8: bytes(rumor.content),
+ rumor_utf8: bytes(original),
+ seal_ciphertext_utf8: bytes(seal.content),
+ signed_seal_utf8: bytes(sealWire),
+ outer_ciphertext_utf8: bytes(wrap.content),
+ signed_outer_utf8: bytes(outer.wire),
+ equal: fixture.decrypt(sealWire, role).equal,
+ sameHash: outer.rumorHash === rumor.id,
+ target:
+ wrap.tags[0]?.[1] ===
+ (role === 'self' ? fixture.owner : fixture.peer),
+ soleTarget: wrap.tags.length === 1 && wrap.tags[0]?.length === 2
+ });
+ }
+ const counts = fixture.counts();
+ return {
+ planning,
+ self: self.status,
+ peer: peer.status,
+ originalUnchanged:
+ s.reservedSendRumorWire(fixture.reserved) === original,
+ signs: counts.signs - started.signs,
+ encrypts: counts.encrypts - started.encrypts,
+ rows
+ };
+ } finally {
+ fixture.close();
+ }
+ }, shape);
+ expect(result.planning).toEqual({
+ accepted: true,
+ plusOneRejected: true,
+ noSDK: true
+ });
+ expect(result).toMatchObject({
+ self: 'prepared',
+ peer: 'complete',
+ originalUnchanged: true,
+ signs: 2,
+ encrypts: 2
+ });
+ expect(result.rows).toHaveLength(2);
+ for (const row of result.rows) {
+ expect(row).toMatchObject({
+ equal: true,
+ sameHash: true,
+ target: true,
+ soleTarget: true
+ });
+ expect(row.body_utf8).toBeLessThanOrEqual(4096);
+ expect(row.rumor_utf8).toBeLessThanOrEqual(8192);
+ expect(row.signed_seal_utf8).toBeLessThanOrEqual(16384);
+ expect(row.signed_outer_utf8).toBeLessThanOrEqual(32768);
+ if (shape === 'maximum_escaped_rumor') {
+ expect(row.rumor_utf8).toBe(8192);
+ expect(row.seal_ciphertext_utf8).toBe(11012);
+ } else expect(row.body_utf8).toBe(4096);
+ }
+ console.log(
+ JSON.stringify({
+ fixture: 'HCP079_ACTUAL_GENUINE_FACTORY_NESTED_MEASUREMENTS',
+ shape,
+ rows: result.rows
+ })
+ );
+ });