app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

commit d330d89347a7b6d83a4562477253a1923dd6e2af
parent 81142cb775c0e4b2d48033a238e979793824d59a
Author: triesap <tyson@radroots.org>
Date:   Wed,  7 Oct 2026 20:04:41 +0000

messages: build disposable recipient-targeted gift wraps (HCP-076)

- Bind exact recipient wrapping to genuine current sender seals
- Confine SDK disposable keys to reviewed construction with cleanup
- Verify seven signed fields and exclude private helper data
- Qualify key scope and actual peer and self ciphertext in Chromium

Diffstat:
Aweb/src/lib/nostr/giftwrap-builder.ts | 159+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/giftwrap-builder.spec.ts | 257+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/harness/giftwrap-builder.ts | 307+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/integration/search-view.test.ts | 20++++++++++++++++++--
Mweb/tests/provenance/output.test.mjs | 2901+++++++++++++++++++++++++++++++++++++++++--------------------------------------
Mweb/tests/provenance/source-boundaries.test.mjs | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/giftwrap-builder.test.ts | 260+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tools/source-boundaries.mjs | 50+++++++++++++++++++++++++++++++++++++++++++++++++-
8 files changed, 2662 insertions(+), 1384 deletions(-)

diff --git a/web/src/lib/nostr/giftwrap-builder.ts b/web/src/lib/nostr/giftwrap-builder.ts @@ -0,0 +1,159 @@ +import { + generateSecretKey, + getPublicKey, + finalizeEvent, + getEventHash, + type UnsignedEvent +} from 'applesauce-core/helpers'; +import { nip44 } from 'applesauce-core/helpers/encryption'; +import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts'; +import { safeUnsignedInteger } from './envelope-bounds.ts'; +import { verifyEnvelope } from './verified-envelope.ts'; +import { + privateSealSnapshot, + type PrivateRecipientSeal +} from './seal-builder.ts'; + +declare const giftwrapBrand: unique symbol; +export type PrivateGiftwrap = Readonly<{ [giftwrapBrand]: true }>; +type Saved = Readonly<{ + owner: string; + peer: string; + destination: string; + role: 'peer' | 'self'; + command: string; + rumorHash: string; + kind: 1059; + wire: string; + seal: PrivateRecipientSeal; +}>; +const wraps = new WeakMap<PrivateGiftwrap, Saved>(); +function own(value: object, name: string): unknown { + const descriptor = Object.getOwnPropertyDescriptor(value, name); + return descriptor && 'value' in descriptor ? descriptor.value : undefined; +} +// Only genuine current sender seals enter this lower-level construction. It +// grants no readiness, durable preparation receipt, nested admission or Send. +// All secret primitives below are public pinned Applesauce exports. Disposable +// keys are local to this synchronous factory; they never become identity keys. +export function buildPrivateGiftwrap( + seal: PrivateRecipientSeal, + review: unknown +): PrivateGiftwrap | undefined { + if (typeof window === 'undefined' || review !== 'reviewed_private_wrap') + return undefined; + const record = privateSealSnapshot(seal); + if ( + !record || + !boundedUtf8(record.wire, 16384) || + record.destination !== (record.role === 'self' ? record.owner : record.peer) + ) + return undefined; + let secret: Uint8Array | undefined, conversation: Uint8Array | undefined; + try { + const milliseconds = safeUnsignedInteger(Date.now()); + if (milliseconds === undefined || !privateSealSnapshot(seal)) + return undefined; + const random = crypto.getRandomValues(new Uint32Array(1))[0], + time = Math.max(0, Math.floor(milliseconds / 1000) - (random % 3600)); + if (!privateSealSnapshot(seal)) return undefined; + secret = generateSecretKey(); + if (!privateSealSnapshot(seal)) return undefined; + const author = getPublicKey(secret); + conversation = nip44.v2.utils.getConversationKey( + secret, + record.destination + ); + if (!privateSealSnapshot(seal)) return undefined; + const content = nip44.v2.encrypt(record.wire, conversation); + if (!privateSealSnapshot(seal)) return undefined; + const captured = JSON.stringify({ + pubkey: author, + kind: 1059, + created_at: time, + tags: [['p', record.destination]], + content + }); + const response = finalizeEvent( + JSON.parse(captured) as UnsignedEvent, + secret + ), + id = own(response, 'id'), + sig = own(response, 'sig'), + tags = own(response, 'tags'); + if ( + own(response, 'pubkey') !== author || + own(response, 'kind') !== 1059 || + own(response, 'created_at') !== time || + own(response, 'content') !== content || + !Array.isArray(tags) || + own(tags, 'length') !== 1 + ) + return undefined; + const target = own(tags, '0'); + if ( + !Array.isArray(target) || + own(target, 'length') !== 2 || + own(target, '0') !== 'p' || + own(target, '1') !== record.destination || + typeof id !== 'string' || + typeof sig !== 'string' || + id !== getEventHash(JSON.parse(captured) as UnsignedEvent) + ) + return undefined; + // Explicit fields discard SDK verification/cache symbols and extra data. + // Parse and verify a fresh wire, independently of the SDK result object. + const wire = JSON.stringify({ + pubkey: author, + kind: 1059, + created_at: time, + tags: [['p', record.destination]], + content, + id, + sig + }); + if ( + !boundedUtf8(wire, 32768) || + !verifyEnvelope(wire).ok || + !privateSealSnapshot(seal) + ) + return undefined; + const token = Object.freeze({}) as PrivateGiftwrap; + wraps.set(token, { + owner: record.owner, + peer: record.peer, + destination: record.destination, + role: record.role, + command: record.command, + rumorHash: record.rumorHash, + kind: 1059, + wire, + seal + }); + return token; + } catch { + return undefined; + } finally { + // Directly owned byte buffers only. The SDK/engine may allocate other + // buffers; this does not promise complete browser-memory zeroization. + conversation?.fill(0); + secret?.fill(0); + } +} +export function privateGiftwrapSnapshot( + token: PrivateGiftwrap +): Readonly<Omit<Saved, 'seal'>> | undefined { + const saved = wraps.get(token); + return saved && privateSealSnapshot(saved.seal) + ? { + owner: saved.owner, + peer: saved.peer, + destination: saved.destination, + role: saved.role, + command: saved.command, + rumorHash: saved.rumorHash, + kind: 1059, + wire: saved.wire + } + : undefined; +} diff --git a/web/tests/e2e/giftwrap-builder.spec.ts b/web/tests/e2e/giftwrap-builder.spec.ts @@ -0,0 +1,257 @@ +import { expect, test, type Page } from '@playwright/test'; +import { build } from 'vite'; +import { fileURLToPath } from 'node:url'; +import { createHash } from 'node:crypto'; +import { createStaticHarness } from '../integration/harness/static.ts'; +import type * as Wraps from './harness/giftwrap-builder.ts'; +declare global { + interface Window { + hcp076: typeof Wraps; + hcp076Fixture: Awaited<ReturnType<typeof Wraps.makeFixture>>; + } +} +let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string; +test.beforeAll(async () => { + server = await createStaticHarness(); + const result = await build({ + configFile: false, + logLevel: 'silent', + build: { + write: false, + minify: false, + lib: { + entry: fileURLToPath( + new URL('./harness/giftwrap-builder.ts', import.meta.url) + ), + name: 'hcp076', + formats: ['iife'] + } + } + }); + const output = Array.isArray(result) ? result[0] : result; + 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; + console.log( + JSON.stringify({ + fixture: 'HCP076_ACTUAL_SDK_WRAPPER_CRYPTO', + bundleSha256: createHash('sha256').update(bundle).digest('hex'), + moduleIds: Object.keys(chunks[0].modules), + qualification: + 'Controlled SDK provider and real IDB/WebLocks; not installed extensions/relay/clientQ' + }) + ); +}); +test.afterAll(async () => server.close()); +async function load(page: Page) { + await page.goto(server.url + '/search'); + await page.addScriptTag({ content: bundle }); + await page.evaluate(async () => { + window.hcp076Fixture = await window.hcp076.makeFixture(); + }); +} +for (const role of ['peer', 'self'] as const) + test(`actual ${role}1059 decrypts to exact sender seal and original same rumor`, async ({ + page + }) => { + await load(page); + const result = await page.evaluate(async (role) => { + const f = window.hcp076Fixture, + s = window.hcp076; + try { + const op = f.operation(role); + if (!op) throw Error('missing operation'); + const seal = await s.buildPrivateSeal(op); + if (seal.status !== 'sealed') throw Error('missing seal'); + const inner = s.privateSealSnapshot(seal.seal)!; + const before = f.counts(), + token = s.buildPrivateGiftwrap(seal.seal, 'reviewed_private_wrap'); + if (!token) throw Error('missing wrap'); + const saved = s.privateGiftwrapSnapshot(token)!, + outer = JSON.parse(saved.wire) as { + kind: number; + tags: string[][]; + pubkey: string; + created_at: number; + }; + const plain = f.decryptWrap(saved.wire, role), + decrypted = f.decrypt(plain, role), + stored = await f.stored(); + return { + kind: outer.kind, + tags: outer.tags, + target: inner.destination, + exactSeal: plain === inner.wire, + sameRumor: decrypted.equal, + disposable: outer.pubkey !== f.owner && outer.pubkey !== f.peer, + seven: Object.keys(outer).length, + changedCalls: JSON.stringify(before) !== JSON.stringify(f.counts()), + noPlain: + !saved.wire.includes('sentinel') && !stored.includes('sentinel'), + bounded: new TextEncoder().encode(saved.wire).length <= 32768, + time: outer.created_at, + now: Math.floor(Date.now() / 1000), + role: saved.role, + owner: saved.owner, + peer: saved.peer + }; + } finally { + f.close(); + } + }, role); + expect(result.kind).toBe(1059); + expect(result.tags).toEqual([['p', result.target]]); + expect(result.exactSeal).toBe(true); + expect(result.sameRumor).toBe(true); + expect(result.disposable).toBe(true); + expect(result.seven).toBe(7); + expect(result.changedCalls).toBe(false); + expect(result.noPlain).toBe(true); + expect(result.bounded).toBe(true); + expect(result.time).toBeLessThanOrEqual(result.now); + expect(result.time).toBeGreaterThanOrEqual(result.now - 3600); + expect(result.role).toBe(role); + }); +test('distinct disposable wrappers preserve the exact original seal without retargeting or identity effects', async ({ + page +}) => { + await load(page); + const result = await page.evaluate(async () => { + const f = window.hcp076Fixture, + s = window.hcp076; + try { + const seal = await s.buildPrivateSeal(f.operation()!); + if (seal.status !== 'sealed') throw Error('missing seal'); + const before = f.counts(), + a = s.privateGiftwrapSnapshot( + s.buildPrivateGiftwrap(seal.seal, 'reviewed_private_wrap')! + )!, + b = s.privateGiftwrapSnapshot( + s.buildPrivateGiftwrap(seal.seal, 'reviewed_private_wrap')! + )!; + const ae = JSON.parse(a.wire) as { id: string; pubkey: string }, + be = JSON.parse(b.wire) as { id: string; pubkey: string }; + return { + fresh: ae.pubkey !== be.pubkey && ae.id !== be.id, + equal: f.decryptWrap(a.wire, 'peer') === f.decryptWrap(b.wire, 'peer'), + sameBinding: + a.command === b.command && + a.rumorHash === b.rumorHash && + a.destination === b.destination, + calls: JSON.stringify(before) === JSON.stringify(f.counts()) + }; + } finally { + f.close(); + } + }); + expect(result).toEqual({ + fresh: true, + equal: true, + sameBinding: true, + calls: true + }); +}); +test('wrong review, cast/copy wire and stopped genuine operation do not mint wrappers', async ({ + page +}) => { + await load(page); + const result = await page.evaluate(async () => { + const f = window.hcp076Fixture, + s = window.hcp076; + try { + const op = f.operation()!, + seal = await s.buildPrivateSeal(op); + if (seal.status !== 'sealed') throw Error('missing seal'); + const snapshot = s.privateSealSnapshot(seal.seal)!; + const wrong = s.buildPrivateGiftwrap(seal.seal, 'connect'), + cast = s.buildPrivateGiftwrap( + snapshot as unknown as typeof seal.seal, + 'reviewed_private_wrap' + ); + s.stopPrivateSeal(op); + const stopped = s.buildPrivateGiftwrap( + seal.seal, + 'reviewed_private_wrap' + ); + return { + wrong: wrong === undefined, + cast: cast === undefined, + stopped: stopped === undefined + }; + } finally { + f.close(); + } + }); + expect(result).toEqual({ wrong: true, cast: true, stopped: true }); +}); +test('disconnect removes wrapper lifetime access and cannot turn ciphertext metadata into a token', async ({ + page +}) => { + await load(page); + const result = await page.evaluate(async () => { + const f = window.hcp076Fixture, + s = window.hcp076; + try { + const seal = await s.buildPrivateSeal(f.operation()!); + if (seal.status !== 'sealed') throw Error('missing seal'); + const wrap = s.buildPrivateGiftwrap(seal.seal, 'reviewed_private_wrap')!, + saved = s.privateGiftwrapSnapshot(wrap)!; + const cast = s.privateGiftwrapSnapshot(saved as unknown as typeof wrap); + f.disconnect(); + return { + cast: cast === undefined, + stale: s.privateGiftwrapSnapshot(wrap) === undefined, + noResume: + s.buildPrivateGiftwrap(seal.seal, 'reviewed_private_wrap') === + undefined + }; + } finally { + f.close(); + } + }); + expect(result).toEqual({ cast: true, stale: true, noResume: true }); +}); + +test('peer and self outer copies preserve one genuine reserved rumor and route only to that pair', async ({ + page +}) => { + await load(page); + const result = await page.evaluate(async () => { + const f = window.hcp076Fixture, + s = window.hcp076; + try { + const selfSeal = await s.buildPrivateSeal(f.operation('self')!), + peerSeal = await s.buildPrivateSeal(f.operation('peer')!); + if (selfSeal.status !== 'sealed' || peerSeal.status !== 'sealed') + throw Error('missing pair seals'); + const self = s.privateGiftwrapSnapshot( + s.buildPrivateGiftwrap(selfSeal.seal, 'reviewed_private_wrap')! + )!, + peer = s.privateGiftwrapSnapshot( + s.buildPrivateGiftwrap(peerSeal.seal, 'reviewed_private_wrap')! + )!; + const selfInner = f.decryptWrap(self.wire, 'self'), + peerInner = f.decryptWrap(peer.wire, 'peer'); + return { + selfEqual: f.decrypt(selfInner, 'self').equal, + peerEqual: f.decrypt(peerInner, 'peer').equal, + same: + self.rumorHash === peer.rumorHash && self.command === peer.command, + targets: self.destination === f.owner && peer.destination === f.peer, + roles: self.role === 'self' && peer.role === 'peer', + distinct: self.wire !== peer.wire + }; + } finally { + f.close(); + } + }); + expect(result).toEqual({ + selfEqual: true, + peerEqual: true, + same: true, + targets: true, + roles: true, + distinct: true + }); +}); diff --git a/web/tests/e2e/harness/giftwrap-builder.ts b/web/tests/e2e/harness/giftwrap-builder.ts @@ -0,0 +1,307 @@ +import { + buildPrivateGiftwrap, + privateGiftwrapSnapshot +} from '../../../src/lib/nostr/giftwrap-builder.ts'; +export { buildPrivateGiftwrap, privateGiftwrapSnapshot }; +import { + finalizeEvent, + generateSecretKey, + getPublicKey, + verifiedSymbol, + type UnsignedEvent +} from 'applesauce-core/helpers'; +import { nip44 } from 'applesauce-core/helpers/encryption'; +import { verifyEnvelope } from '../../../src/lib/nostr/verified-envelope.ts'; +import { captureEnquiryContext } from '../../../src/lib/messaging/enquiry-context.ts'; +import { captureEnquiryRumor } from '../../../src/lib/messaging/rumor-plan.ts'; +import { + openBrowserDatabase, + closeBrowserDatabase, + browserDatabaseTransaction +} from '../../../src/lib/persistence/database.ts'; +import { createPrivateSendReservationRepository } from '../../../src/lib/persistence/private-send-reservations.ts'; +import { + reserveSendIdentity, + reservedSendRumorWire +} from '../../../src/lib/messaging/send-identity.ts'; +import { + createIdentitySession, + connectIdentity, + probeIdentityMessaging, + identitySessionSnapshot, + disconnectIdentity +} from '../../../src/lib/runtime/identity-session.ts'; +import { + capturePrivateSealOperation, + buildPrivateSeal, + stopPrivateSeal, + expirePrivateSealWait, + privateSealSnapshot +} from '../../../src/lib/nostr/seal-builder.ts'; +import { + browserExtensionScheduler, + extensionSchedulerSnapshot +} from '../../../src/lib/nostr/extension-scheduler.ts'; +export { + capturePrivateSealOperation, + buildPrivateSeal, + stopPrivateSeal, + expirePrivateSealWait, + privateSealSnapshot +}; +export type Mode = + | 'normal' + | 'wrong_cipher' + | 'wrong_author' + | 'wrong_tags' + | 'wrong_time' + | 'cached_bad_id' + | 'missing' + | 'declined' + | 'changed_key' + | 'hold_encrypt' + | 'hold_sign' + | 'getter_reentry' + | 'stop_capability_getter' + | '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() { + const secret = generateSecretKey(), + peerSecret = generateSecretKey(), + owner = getPublicKey(secret), + peer = getPublicKey(peerSecret); + let mode: Mode = 'normal', + keys = 0, + encrypts = 0, + signs = 0, + capabilityReads = 0, + reentrantReads = 0, + postStopEncrypts = 0, + getterStopped = false, + watched: ReturnType<typeof capturePrivateSealOperation>, + release: (() => void) | undefined; + function encryptTo(target: string, text: string) { + const conversation = nip44.v2.utils.getConversationKey(secret, target); + try { + return nip44.v2.encrypt(text, conversation); + } finally { + conversation.fill(0); + } + } + function sign(template: UnsignedEvent) { + const input = + mode === 'wrong_cipher' + ? { ...template, content: encryptTo(peer, 'different immutable rumor') } + : mode === 'wrong_tags' + ? { ...template, tags: [['client', 'leak']] } + : mode === 'wrong_time' + ? { ...template, created_at: template.created_at + 1 } + : template; + const signed = finalizeEvent( + input, + mode === 'wrong_author' ? peerSecret : secret + ); + return mode === 'cached_bad_id' + ? { ...signed, id: '0'.repeat(64), [verifiedSymbol]: true } + : { + ...signed, + plaintext: 'never retained sentinel', + toJSON: () => { + throw Error('unexpected provider conversion'); + } + }; + } + const provider = { + getPublicKey: () => { + keys++; + return Promise.resolve(mode === 'changed_key' ? peer : owner); + }, + signEvent: (template: UnsignedEvent) => { + signs++; + return mode === 'hold_sign' + ? new Promise<ReturnType<typeof sign>>((resolve) => { + release = () => resolve(sign(template)); + }) + : Promise.resolve(sign(template)); + }, + get nip44() { + capabilityReads++; + if ( + watched && + (mode === 'stop_capability_getter' || + (mode === 'stop_capability_after_key' && capabilityReads === 2)) + ) { + stopPrivateSeal(watched); + return undefined; + } + return mode === 'missing' + ? undefined + : { + get encrypt() { + const scheduler = browserExtensionScheduler(), + slot = scheduler && extensionSchedulerSnapshot(scheduler); + if ( + mode === 'getter_reentry' && + watched && + slot && + slot.state === 'active' && + slot.pending === 'encrypt' + ) { + reentrantReads++; + getterStopped = true; + stopPrivateSeal(watched); + } + return (target: string, text: string) => { + encrypts++; + if (getterStopped) postStopEncrypts++; + if (mode === 'declined') + return Promise.reject(Error('private failure must not leak')); + if (mode === 'hold_encrypt') + return new Promise<string>((resolve) => { + release = () => resolve(encryptTo(target, text)); + }); + return Promise.resolve(encryptTo(target, text)); + }; + }, + decrypt: (target: string, cipher: string) => { + const conversation = nip44.v2.utils.getConversationKey( + secret, + target + ); + try { + return Promise.resolve(nip44.v2.decrypt(cipher, conversation)); + } finally { + conversation.fill(0); + } + } + }; + } + }; + Object.defineProperty(window, 'nostr', { + configurable: true, + value: provider + }); + const identity = createIdentitySession(); + await connectIdentity(identity); + await probeIdentityMessaging(identity, 'reviewed_self_copy'); + const food = finalizeEvent( + { + kind: 30402, + created_at: 1700000060, + content: 'Public carrots', + tags: [ + ['d', 'carrots'], + ['title', 'Carrots'], + ['summary', 'Fresh carrots'], + ['published_at', '1700000000'], + ['location', 'Victoria'], + ['price', '3.5', 'CAD'], + ['radroots:price_unit', 'lb'], + ['status', 'active'] + ] + }, + peerSecret + ); + const proof = verifyEnvelope(JSON.stringify(food)); + if (!proof.ok) throw Error('invalid public fixture'); + const context = captureEnquiryContext(proof.value); + if (!context) throw Error('invalid context'); + const plan = captureEnquiryRumor( + identity, + context, + 'Private seal sentinel', + Math.floor(Date.now() / 1000) + ); + if (!plan) throw Error('missing plan'); + const opened = await openBrowserDatabase(); + if (opened.state !== 'ready') throw Error('missing database'); + const database = opened.owner, + repository = createPrivateSendReservationRepository(database, owner); + if (!repository) throw Error('missing repository'); + const reservation = await reserveSendIdentity( + repository, + identity, + '12345678-1234-4234-8234-123456789abc', + plan, + 'reviewed_private_intent' + ); + if (reservation.status !== 'reserved') throw Error('missing reservation'); + const reserved = reservation.identity; + const original = reservedSendRumorWire(reserved); + return { + owner, + peer, + identity, + reserved, + operation: ( + role: unknown = 'peer', + review: unknown = 'reviewed_private_seal' + ) => { + watched = capturePrivateSealOperation(identity, reserved, role, review); + return watched; + }, + mode: (value: Mode) => { + mode = value; + capabilityReads = 0; + }, + counts: () => ({ keys, encrypts, signs, reentrantReads, postStopEncrypts }), + identityState: () => identitySessionSnapshot(identity).state, + settle: () => { + release?.(); + }, + slot: () => { + const scheduler = browserExtensionScheduler(); + return scheduler ? extensionSchedulerSnapshot(scheduler) : undefined; + }, + disconnect: () => disconnectIdentity(identity), + async stored() { + const tx = browserDatabaseTransaction( + database, + ['private_sends'], + 'readonly' + ), + request = tx.objectStore('private_sends').getAll(); + return await new Promise<string>((resolve, reject) => { + tx.addEventListener('complete', () => + resolve(JSON.stringify(request.result)) + ); + tx.addEventListener('abort', () => reject(Error('inspection aborted'))); + }); + }, + decryptWrap(wire: string, role: 'peer' | 'self') { + const wrap = JSON.parse(wire) as { pubkey: string; content: string }; + const conversation = nip44.v2.utils.getConversationKey( + role === 'peer' ? peerSecret : secret, + wrap.pubkey + ); + try { + return nip44.v2.decrypt(wrap.content, conversation); + } finally { + conversation.fill(0); + } + }, + decrypt(wire: string, role: 'peer' | 'self') { + const seal = JSON.parse(wire) as { content: string }; + const conversation = nip44.v2.utils.getConversationKey( + role === 'peer' ? peerSecret : secret, + owner + ); + try { + return { + equal: nip44.v2.decrypt(seal.content, conversation) === original, + seal + }; + } finally { + conversation.fill(0); + } + }, + close() { + disconnectIdentity(identity); + closeBrowserDatabase(database); + secret.fill(0); + peerSecret.fill(0); + delete window.nostr; + } + }; +} diff --git a/web/tests/integration/search-view.test.ts b/web/tests/integration/search-view.test.ts @@ -70,6 +70,7 @@ await test('actual SDK foreground search publishes genuine rows and metadata and port: 0, maxPayload: 65536 }); + let releaseLast: (() => void) | undefined; const sockets: WebSocket[] = [], filters: Record<string, unknown>[] = []; server.on('connection', (socket) => { @@ -104,8 +105,18 @@ await test('actual SDK foreground search publishes genuine rows and metadata and matches(v.pubkey, v.tags.find((t) => t[0] === 'd')![1]) ) : []; - for (const value of values) + for (const [index, value] of values.entries()) { + // Real delivery can expose20 visible rows before the21st is admitted. + // Hold that final discovery event to test both pagination states. + if (kind === 30402 && !queries[0].authors && index === 20) { + releaseLast = () => { + socket.send(JSON.stringify(['EVENT', id, value])); + socket.send(JSON.stringify(['EOSE', id])); + }; + return; + } socket.send(JSON.stringify(['EVENT', id, value])); + } socket.send(JSON.stringify(['EOSE', id])); }); }); @@ -167,7 +178,12 @@ await test('actual SDK foreground search publishes genuine rows and metadata and await new Promise((resolve) => setTimeout(resolve, 10)); const first = searchViewSnapshot(owner)!; assert.equal(first.listings.length, 20); - assert.equal(first.hasMore, true); + assert.equal(first.hasMore, false); + assert.equal(typeof releaseLast, 'function'); + releaseLast!(); + for (let n = 0; n < 300 && !searchViewSnapshot(owner)?.hasMore; n++) + await new Promise((resolve) => setTimeout(resolve, 10)); + assert.equal(searchViewSnapshot(owner)!.hasMore, true); assert.deepEqual( first.listings.map((v) => v.eventId), listings.slice(0, 20).map((v) => v.id) diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs @@ -15,16 +15,16 @@ import { } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; +import { performance } from 'node:perf_hooks'; import { test } from 'node:test'; import { fileURLToPath } from 'node:url'; import { generateBuildInfo } from '../../tools/build-info.mjs'; import { auditOutput } from '../../tools/check-output.mjs'; -// Allow bounded setup/copy time for 123 checks and two real compilations. -// Admission checks get 10 seconds; cold compiler work gets 60 seconds. -await test('actual output qualification', { timeout: 180000 }, async (t) => { - /** @param {string} name @param {(context: import('node:test').TestContext) => Promise<void>} run @param {number} [timeout] */ - const check = (name, run, timeout = 10000) => t.test(name, { timeout }, run); +// Five real compilations have separate120s setup/copy/compiler/audit bounds. +// Each Vite child keeps60s; admission checks keep10s within their180s group. +// Serial top-level tests keep compatibility work out of the mutation budget. +{ const source = fileURLToPath(new URL('../../../', import.meta.url)); // Exact HCP043 product shell bytes, immutable compatibility evidence only. const historicalProduct = @@ -49,1371 +49,1502 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { } }; const base = await mkdtemp(path.join(os.tmpdir(), 'hc actual output ')); - t.after(() => rm(base, { recursive: true, force: true })); - /** @param {string} root @param {string[]} args */ - const git = (root, ...args) => - execFileSync('git', ['-C', root, ...args], { - env: Object.fromEntries( - Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')) - ), - encoding: 'utf8' - }); - // Compile actual current source once in isolation. No install/native subprocess. - for (const name of git( - source, - 'ls-files', - '--cached', - '--others', - '--exclude-standard', - '-z', - '--', - 'web', - '.gitignore', - 'core/Cargo.lock', - 'radroots.lib.source-lock.v1.toml' - ) - .split('\0') - .filter(Boolean)) { - const stat = await lstat(path.join(source, name)); - assert.ok( - stat.isFile() && stat.nlink === 1 && stat.size <= 8 * 1024 * 1024, - 'Only safe actual source fixture inputs' - ); - await mkdir(path.dirname(path.join(base, name)), { recursive: true }); - await writeFile( - path.join(base, name), - await readFile(path.join(source, name)) - ); + let setupReady = false; + /** @param {import('node:test').TestContext} t */ + function active(t) { + if (t.signal.aborted) throw new Error('Output fixture test aborted'); } - git(base, 'init', '-q'); - git(base, 'add', '.'); - git( - base, - '-c', - 'user.name=Output Test', - '-c', - 'user.email=output@example.invalid', - 'commit', - '-qm', - 'actual inputs' - ); - await cp( - path.join(source, 'web/node_modules'), - path.join(base, 'web/node_modules'), - { recursive: true, verbatimSymlinks: true } - ); - await generateBuildInfo(path.join(base, 'web')); - execFileSync( - process.execPath, - [path.join(source, 'web/node_modules/vite/bin/vite.js'), 'build'], - { cwd: path.join(base, 'web'), stdio: 'pipe', timeout: 60000 } - ); - /** @param {import('node:test').TestContext} t */ - async function fixture(t) { - const root = await realpath( - await mkdtemp(path.join(os.tmpdir(), 'hc output mutation ')) - ); - t.after(() => rm(root, { recursive: true, force: true })); - // Audit consumers use actual client/prerendered/build bytes and all source - // inputs. Server output and generated development/type caches are not audit - // inputs; avoid copying them for every mutation under the fixed deadline. - const excluded = new Set([ - path.join(base, 'web/node_modules'), - path.join(base, 'web/.svelte-kit/output/server'), - path.join(base, 'web/.svelte-kit/generated'), - path.join(base, 'web/.svelte-kit/types') - ]); - await cp(base, root, { - recursive: true, - filter: (name) => !excluded.has(name) - }); - const web = path.join(root, 'web'); - return { root, web, audit: () => auditOutput(web) }; + function ready(t) { + active(t); + assert.ok(setupReady, 'Actual output setup must complete before consumers'); } - await check( - 'actual compiled payload passes and build dispatch invokes the guard last', - async (t) => { - const f = await fixture(t); - const files = await f.audit(); - // Exact eleven-route module/page/static admission; CSS stays once-imported. - assert.equal(files.length, 48); - // The actual SDK payload crosses the reader scratch boundary; a reused - // scratch buffer must still preserve every compiler/static byte exactly. - const sizes = await Promise.all( - files - .filter((name) => name.endsWith('.js')) - .map( - async (name) => (await lstat(path.join(f.web, 'build', name))).size - ) - ); - assert.ok(sizes.some((bytes) => bytes > 64 * 1024)); - assert.ok(files.includes('search.html')); - assert.equal(files.filter((name) => name.endsWith('.css')).length, 1); - assert.ok( - files.some((name) => - /^_app\/immutable\/assets\/[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.css$/.test( - name - ) - ) - ); - assert.ok(files.includes('200.html')); - const pkg = JSON.parse( - await readFile(path.join(f.web, 'package.json'), 'utf8') - ); - assert.match( - pkg.scripts.build, - /vite build && node tools\/check-output\.mjs$/ + try { + /** @param {string} root @param {string[]} args */ + const git = (root, ...args) => + execFileSync('git', ['-C', root, ...args], { + env: Object.fromEntries( + Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')) + ), + encoding: 'utf8' + }); + /** @param {import('node:test').TestContext} t */ + async function fixture(t) { + ready(t); + const root = await realpath( + await mkdtemp(path.join(os.tmpdir(), 'hc output mutation ')) ); + t.after(() => rm(root, { recursive: true, force: true })); + // Audit consumers use actual client/prerendered/build bytes and all source + // inputs. Server output and generated development/type caches are not audit + // inputs; avoid copying them for every mutation under the fixed deadline. + const excluded = new Set([ + path.join(base, 'web/node_modules'), + path.join(base, 'web/.svelte-kit/output/server'), + path.join(base, 'web/.svelte-kit/generated'), + path.join(base, 'web/.svelte-kit/types') + ]); + await cp(base, root, { + recursive: true, + filter: (name) => !excluded.has(name) + }); + active(t); + const web = path.join(root, 'web'); + return { root, web, audit: () => auditOutput(web) }; } - ); - await check( - 'public-only owned lifecycle remains independently compilable', - async (t) => { - const f = await fixture(t); - for (const [name, value] of Object.entries(historicalPublicOnly)) { - assert.equal( - createHash('sha256').update(value.source).digest('hex'), - value.sha256 - ); - await writeFile(path.join(f.web, name), value.source); - } + /** @param {{root: string, web: string}} f */ + async function refresh(f) { + git(f.root, 'add', '--', 'web/src'); + await generateBuildInfo(f.web); + const bytes = await readFile(path.join(f.web, 'static/build-info.json')); + for (const name of [ + 'build/build-info.json', + '.svelte-kit/output/client/build-info.json' + ]) + await writeFile(path.join(f.web, name), bytes); + } + + const sdkKey = + 'node_modules/.pnpm/applesauce-relay@6.2.1_typescript@6.0.3/node_modules/applesauce-relay/dist/negentropy.js'; + /** @param {import('node:test').TestContext} t @param {string} from @param {string} web */ + async function copyDependencies(t, from, web) { + active(t); + const start = performance.now(); await cp( - path.join(base, 'web/node_modules'), - path.join(f.web, 'node_modules'), - { recursive: true, verbatimSymlinks: true } - ); - await refresh(f); - execFileSync( - process.execPath, - [path.join(source, 'web/node_modules/vite/bin/vite.js'), 'build'], - { cwd: f.web, stdio: 'pipe', timeout: 60000 } - ); - const manifest = JSON.parse( - await readFile( - path.join(f.web, '.svelte-kit/output/client/.vite/manifest.json'), - 'utf8' - ) - ); - assert.ok( - !Object.values(manifest).some( - (record) => record.name === 'view-context' - ) + path.join(from, 'web/node_modules'), + path.join(web, 'node_modules'), + { + recursive: true, + verbatimSymlinks: true + } ); - assert.ok( - Object.values(manifest).some((record) => record.name === 'budgets') + active(t); + t.diagnostic( + `actual dependency copy milliseconds: ${performance.now() - start}` ); - assert.equal((await f.audit()).length, 47); - }, - 60000 - ); - /** @param {{root: string, web: string}} f */ - async function refresh(f) { - git(f.root, 'add', '--', 'web/src'); - await generateBuildInfo(f.web); - const bytes = await readFile(path.join(f.web, 'static/build-info.json')); - for (const name of [ - 'build/build-info.json', - '.svelte-kit/output/client/build-info.json' - ]) - await writeFile(path.join(f.web, name), bytes); - } - for (const name of [ - 'components/InboxSetup.svelte', - 'messaging/inbox-setup-view.ts', - 'runtime/view-context.ts' - ]) - await check( - 'linked inbox setup requires exact owned source ' + name, - async (t) => { - const f = await fixture(t); - const file = path.join(f.web, 'src/lib', name); - await writeFile( - file, - (await readFile(file, 'utf8')) + '\n// changed source\n' - ); - await refresh(f); - await assert.rejects(f.audit, /inbox compiler source/); - } - ); - for (const name of [ - 'private-handles', - 'public-runtime', - 'AccountGate', - 'Disclosure' - ]) - await check( - 'linked inbox setup rejects changed exact compiler edge ' + name, - async (t) => { - const f = await fixture(t); - const file = path.join( - f.web, - '.svelte-kit/output/client/.vite/manifest.json' + } + /** @param {import('node:test').TestContext} t @param {string} web */ + function compile(t, web) { + active(t); + const start = performance.now(); + try { + execFileSync( + process.execPath, + [path.join(source, 'web/node_modules/vite/bin/vite.js'), 'build'], + { cwd: web, stdio: 'pipe', timeout: 60000 } ); - const manifest = JSON.parse(await readFile(file, 'utf8')); - const entry = Object.entries(manifest).find( - ([, row]) => row.name === name + active(t); + } finally { + t.diagnostic( + `actual Vite compilation milliseconds: ${performance.now() - start}` ); - assert.ok(entry, 'Missing actual linked inbox compiler role'); - entry[1].imports = ['forged-compiler-edge']; - await writeFile(file, JSON.stringify(manifest)); - await assert.rejects(f.audit, /compiler/); } - ); - await check( - 'owned root preserves its lifecycle across a 64 KiB read boundary', - async (t) => { - const f = await fixture(t); - const file = path.join(f.web, 'src/routes/+layout.svelte'); - const layout = await readFile(file, 'utf8'); - // A large harmless comment after the real lifecycle must not overwrite its - // first read chunk when the file reader reuses a scratch buffer. - const expanded = layout.replace( - '</script>', - '/*' + 'owned reader boundary '.repeat(4000) + '*/\n</script>' - ); - assert.ok(Buffer.byteLength(expanded) > 64 * 1024); - await writeFile(file, expanded); - await refresh(f); - assert.equal((await f.audit()).length, 48); } - ); - const sdkKey = - 'node_modules/.pnpm/applesauce-relay@6.2.1_typescript@6.0.3/node_modules/applesauce-relay/dist/negentropy.js'; - await check( - 'predecessor SDK graph remains qualified with the historical search form fixture', - async (t) => { - const f = await fixture(t); - // This historical graph predates identity activation. Restore its - // immutable public-only producers before compiling the former routes. - for (const [name, value] of Object.entries(historicalPublicOnly)) - await writeFile(path.join(f.web, name), value.source); - // Immutable former route bytes are a labelled verification variant only. - const historical = - "<script lang=\"ts\">\n import { page } from '$app/state';\n import SearchForm from '../../lib/components/SearchForm.svelte';\n import {\n normalizePublicQuery,\n queryErrorMessage,\n readPublicQuery\n } from '../../lib/catalog/query-input';\n import type { PublicQuery } from '../../lib/catalog/query-input';\n import { searchHref } from '../../lib/routes';\n import { internalHref } from '../../lib/navigation-url';\n let query = $state<PublicQuery>(normalizePublicQuery(''));\n let error = $state<string | undefined>();\n $effect(() => {\n query = readPublicQuery(page.url);\n error = undefined;\n });\n function search(input: string) {\n const next = normalizePublicQuery(input);\n if (!next.ok) {\n error = queryErrorMessage(next.error);\n return;\n }\n error = undefined;\n const target = internalHref(searchHref(next.text));\n if (target === undefined) {\n error = queryErrorMessage('invalid_query');\n return;\n }\n globalThis.location.assign(target);\n }\n</script>\n\n<svelte:head><title>Search food \u2014 HarvestCircle</title></svelte:head>\n<div class=\"page page--reading stack\">\n <h1>Search food</h1>\n <SearchForm\n onsubmit={search}\n initialValue={query.ok ? query.text : ''}\n error={error ?? (query.ok ? undefined : queryErrorMessage(query.error))}\n />\n <p class=\"notice\">Search data is unavailable during development.</p>\n</div>\n"; - await writeFile( - path.join(f.web, 'src/routes/search/+page.svelte'), - historical - ); - await writeFile( - path.join(f.web, 'src/routes/products/[naddr=naddr]/+page.svelte'), - historicalProduct - ); - await refresh(f); - await cp( - path.join(base, 'web/node_modules'), - path.join(f.web, 'node_modules'), - { recursive: true, verbatimSymlinks: true } - ); - execFileSync( - process.execPath, - [path.join(source, 'web/node_modules/vite/bin/vite.js'), 'build'], - { cwd: f.web, stdio: 'pipe', timeout: 60000 } - ); - const manifest = JSON.parse( - await readFile( - path.join(f.web, '.svelte-kit/output/client/.vite/manifest.json'), - 'utf8' - ) - ); - assert.ok( - Object.values(manifest).some((record) => record.name === 'dist') - ); - assert.ok( - !Object.values(manifest).some( - (record) => - record.name === 'Disclosure' || record.name === 'navigation' - ) - ); - assert.equal((await f.audit()).length, 45); - }, - 60000 - ); - await check( - 'HCP043 search graph remains qualified with the exact historical product shell', - async (t) => { - const f = await fixture(t); - for (const [name, value] of Object.entries(historicalPublicOnly)) - await writeFile(path.join(f.web, name), value.source); - await writeFile( - path.join(f.web, 'src/routes/products/[naddr=naddr]/+page.svelte'), - historicalProduct - ); - await refresh(f); - await cp( - path.join(base, 'web/node_modules'), - path.join(f.web, 'node_modules'), - { recursive: true, verbatimSymlinks: true } - ); - execFileSync( - process.execPath, - [path.join(source, 'web/node_modules/vite/bin/vite.js'), 'build'], - { cwd: f.web, stdio: 'pipe', timeout: 60000 } - ); - assert.equal((await f.audit()).length, 46); - }, - 60000 - ); - for (const mutation of [ - 'unknown-name', - 'missing-public-key', - 'missing-dist', - 'missing-negentropy', - 'missing-root-edge', - 'random-key', - 'wrong-src', - 'wrong-version', - 'wrong-peer', - 'wrong-basename', - 'wrong-dynamic-flag', - 'entry-flag', - 'css', - 'wrong-import', - 'chunk-src', - 'chunk-entry' - ]) - await check( - 'owned root SDK compiler admission rejects ' + mutation, + await test( + 'actual output fixture setup', + { timeout: 120000 }, async (t) => { - const f = await fixture(t); - const file = path.join( - f.web, - '.svelte-kit/output/client/.vite/manifest.json' - ); - const m = JSON.parse(await readFile(file, 'utf8')); - const root = Object.values(m).find((v) => v.name === 'nodes/0'); - const dist = Object.entries(m).find( - ([, v]) => - v.name === - (Object.values(m).some((row) => row.name === 'public-runtime') - ? 'public-runtime' - : 'Disclosure') - ); - assert.ok(m[sdkKey] && root && dist, 'Actual successor SDK identities'); - if (mutation === 'unknown-name') m[sdkKey].name = 'unapproved-sdk'; - if ( - mutation.startsWith('missing-') && - mutation !== 'missing-root-edge' - ) { - const entry = Object.entries(m).find( - ([, v]) => - v.name === - (mutation === 'missing-dist' ? dist[1].name : mutation.slice(8)) + // Compile actual current source once in isolation. No install/native subprocess. + for (const name of git( + source, + 'ls-files', + '--cached', + '--others', + '--exclude-standard', + '-z', + '--', + 'web', + '.gitignore', + 'core/Cargo.lock', + 'radroots.lib.source-lock.v1.toml' + ) + .split('\0') + .filter(Boolean)) { + const stat = await lstat(path.join(source, name)); + assert.ok( + stat.isFile() && stat.nlink === 1 && stat.size <= 8 * 1024 * 1024, + 'Only safe actual source fixture inputs' ); - assert.ok(entry); - delete m[entry[0]]; - } - if (mutation === 'missing-root-edge') dist[1].dynamicImports = []; - if ( - [ - 'random-key', - 'wrong-version', - 'wrong-peer', - 'wrong-basename' - ].includes(mutation) - ) { - const next = - mutation === 'random-key' - ? '_HCrandom.js' - : sdkKey.replace( - mutation === 'wrong-version' - ? '6.2.1' - : mutation === 'wrong-peer' - ? '6.0.3' - : 'negentropy.js', - mutation === 'wrong-basename' ? 'other.js' : '0.0.0' - ); - m[next] = m[sdkKey]; - delete m[sdkKey]; - m[next].src = next; - dist[1].dynamicImports = dist[1].dynamicImports.map( - (/** @type {string} */ k) => (k === sdkKey ? next : k) + await mkdir(path.dirname(path.join(base, name)), { recursive: true }); + await writeFile( + path.join(base, name), + await readFile(path.join(source, name)) ); } - if (mutation === 'wrong-src') m[sdkKey].src = '_HCwrong.js'; - if (mutation === 'wrong-dynamic-flag') m[sdkKey].isDynamicEntry = false; - if (mutation === 'entry-flag') m[sdkKey].isEntry = false; - if (mutation === 'css') m[sdkKey].css = []; - if (mutation === 'wrong-import') - m[sdkKey].imports = [ - Object.keys(m).find((k) => m[k].name === 'public-key') - ]; - if (mutation === 'chunk-src') dist[1].src = dist[0]; - if (mutation === 'chunk-entry') dist[1].isEntry = false; - await writeFile(file, JSON.stringify(m)); - await assert.rejects(f.audit, /compiler|runtime/i); - } - ); - for (const mutation of [ - 'copied-files-only', - 'comment-only', - 'string-only', - 'shadowed', - 'rebound', - 'aliased', - 'missing-cleanup', - 'missing-context', - 'wrong-context' - ]) - await check('root runtime activation rejects ' + mutation, async (t) => { - const f = await fixture(t); - const file = path.join(f.web, 'src/routes/+layout.svelte'); - let layout = await readFile(file, 'utf8'); - if ( - ['copied-files-only', 'comment-only', 'string-only'].includes(mutation) - ) { - const script = layout.slice( - layout.indexOf('>') + 1, - layout.indexOf('</script>') + git(base, 'init', '-q'); + git(base, 'add', '.'); + git( + base, + '-c', + 'user.name=Output Test', + '-c', + 'user.email=output@example.invalid', + 'commit', + '-qm', + 'actual inputs' ); - layout = - '<script lang="ts">' + - (mutation === 'comment-only' - ? '/*' + script + '*/' - : mutation === 'string-only' - ? 'const text = ' + JSON.stringify(script) + ';' - : '') + - '</script><main>Controlled root</main>'; + await copyDependencies(t, source, path.join(base, 'web')); + await generateBuildInfo(path.join(base, 'web')); + compile(t, path.join(base, 'web')); + setupReady = true; } - if (mutation === 'shadowed') - layout = layout.replace( - 'onMount(() => {', - 'onMount((publicContext) => {' - ); - if (mutation === 'rebound') - layout = layout.replace('const publicContext', 'let publicContext'); - if (mutation === 'aliased') - layout = layout - .replace( - ' mountPublicRuntime,', - ' mountPublicRuntime as otherMount,' - ) - .replace( - 'mountPublicRuntime(publicContext)', - 'otherMount(publicContext)' + ); + await test( + 'public-only owned lifecycle remains independently compilable', + { timeout: 120000 }, + async (t) => { + const f = await fixture(t); + for (const [name, value] of Object.entries(historicalPublicOnly)) { + assert.equal( + createHash('sha256').update(value.source).digest('hex'), + value.sha256 ); - if (mutation === 'missing-cleanup') - layout = layout.replace( - 'return () => closePublicRuntime(publicContext);', - 'return () => {};' - ); - if (mutation === 'missing-context') - layout = layout.replace( - 'setContext(PUBLIC_RUNTIME_CONTEXT, publicContext);', - '' - ); - if (mutation === 'wrong-context') - layout = layout.replace( - 'closePublicRuntime(publicContext)', - 'closePublicRuntime({})' - ); - await writeFile(file, layout); - await refresh(f); - await assert.rejects(f.audit, /compiler|runtime/i); - }); - for (const mutation of [ - 'missing-mount', - 'missing-subscription', - 'missing-unsubscribe', - 'missing-close', - 'wrong-context', - 'duplicate-context', - 'extra-mount', - 'aliased-mount', - 'shadowed', - 'missing-context', - 'rebound-context' - ]) - await check('owned identity lifecycle rejects ' + mutation, async (t) => { - const f = await fixture(t); - const file = path.join(f.web, 'src/routes/+layout.svelte'); - const original = await readFile(file, 'utf8'); - let layout = original; - assert.ok(layout.includes('mountIdentityView(identityContext);')); - if (mutation === 'missing-mount') - layout = layout.replace('mountIdentityView(identityContext);', ''); - if (mutation === 'missing-subscription') - layout = layout.replace( - 'subscribeIdentityView(identityContext,', - 'subscribeIdentityView({},' - ); - if (mutation === 'missing-unsubscribe') - layout = layout.replace(' off();', ''); - if (mutation === 'missing-close') - layout = layout.replace('closeIdentityView(identityContext);', ''); - if (mutation === 'wrong-context') - layout = layout.replace( - 'closeIdentityView(identityContext)', - 'closeIdentityView({})' - ); - if (mutation === 'duplicate-context') - layout = layout.replace( - 'const identityContext = createIdentityViewContext();', - 'const identityContext = createIdentityViewContext(); const other = createIdentityViewContext();' - ); - if (mutation === 'extra-mount') - layout = layout.replace( - 'mountIdentityView(identityContext);', - 'mountIdentityView(identityContext); mountIdentityView(identityContext);' - ); - if (mutation === 'aliased-mount') - layout = layout - .replace( - ' mountIdentityView,', - ' mountIdentityView as otherMount,' + await writeFile(path.join(f.web, name), value.source); + } + await copyDependencies(t, base, f.web); + await refresh(f); + compile(t, f.web); + const manifest = JSON.parse( + await readFile( + path.join(f.web, '.svelte-kit/output/client/.vite/manifest.json'), + 'utf8' ) - .replace( - 'mountIdentityView(identityContext);', - 'otherMount(identityContext);' - ); - if (mutation === 'shadowed') - layout = layout.replace( - 'const off = subscribeIdentityView', - 'const identityContext = {}; const off = subscribeIdentityView' ); - if (mutation === 'missing-context') - layout = layout.replace( - 'setContext(IDENTITY_VIEW_CONTEXT, identityContext);', - '' + assert.ok( + !Object.values(manifest).some( + (record) => record.name === 'view-context' + ) ); - if (mutation === 'rebound-context') - layout = layout.replace( - 'const identityContext =', - 'let identityContext =' + assert.ok( + Object.values(manifest).some((record) => record.name === 'budgets') ); - assert.notEqual(layout, original); - await writeFile(file, layout); - await refresh(f); - await assert.rejects(f.audit, /Invalid owned root runtime activation/); - }); - for (const mutation of [ - 'missing-view', - 'missing-heads', - 'extra-view-field', - 'wrong-view-imports', - 'wrong-heads-imports', - 'missing-root-edge', - 'missing-gate-edge' - ]) - await check( - 'owned identity compiler topology rejects ' + mutation, - async (t) => { - const f = await fixture(t), - file = path.join( - f.web, - '.svelte-kit/output/client/.vite/manifest.json' - ); - const manifest = JSON.parse(await readFile(file, 'utf8')); - /** @param {string} name */ - const find = (name) => { - const entry = Object.entries(manifest).find( - ([, record]) => record.name === name - ); - assert.ok(entry, 'Missing observed compiler role: ' + name); - return entry; - }; - const identityCompilerRole = Object.values(manifest).some( - (record) => record.name === 'identity-session' - ) - ? 'identity-session' - : Object.values(manifest).some( - (record) => record.name === 'public-runtime' - ) - ? 'public-runtime' - : 'heads'; - const [identityKey, identity] = find('view-context'), - [headsKey, heads] = find(identityCompilerRole); - if (mutation === 'missing-view') delete manifest[identityKey]; - if (mutation === 'missing-heads') delete manifest[headsKey]; - if (mutation === 'extra-view-field') identity.dynamicImports = []; - if (mutation === 'wrong-view-imports') identity.imports = []; - if (mutation === 'wrong-heads-imports') heads.imports = []; - if ( - mutation === 'missing-root-edge' || - mutation === 'missing-gate-edge' - ) { - const [, consumer] = find( - mutation === 'missing-root-edge' ? 'nodes/0' : 'AccountGate' - ); - consumer.imports = consumer.imports.filter( - /** @param {string} dependency */ - (dependency) => dependency !== identityKey - ); - } - await writeFile(file, JSON.stringify(manifest)); - await assert.rejects(f.audit, /compiler/i); + assert.equal((await f.audit()).length, 47); } ); - for (const name of [ - 'runtime/public-runtime.ts', - 'nostr/request-scope.ts', - 'nostr/public-pool.ts', - 'nostr/public-store.ts', - 'nostr/request-result.ts', - 'nostr/ingress.ts', - 'nostr/verified-envelope.ts', - 'nostr/envelope-bounds.ts', - 'nostr/exports.ts', - 'catalog/observations.ts', - 'config/budgets.ts', - 'config/relays.ts', - 'config/deployment-relays.ts' - ]) - await check('root runtime admission requires owned ' + name, async (t) => { - const f = await fixture(t); - await rm(path.join(f.web, 'src/lib', name)); - await refresh(f); - await assert.rejects(f.audit); - }); - for (const routeSource of ['search/+page.svelte', 'messages/+page.svelte']) - await check( - routeSource + - ' admission requires its owned source and exact module/page counterparts', + await test( + 'predecessor SDK graph remains qualified with the historical search form fixture', + { timeout: 120000 }, async (t) => { const f = await fixture(t); - const source = path.join(f.web, 'src/routes', routeSource); - const original = await readFile(source); - await rm(source); - git(f.root, 'add', '--', 'web/src/routes/' + routeSource); - await generateBuildInfo(f.web); - const metadata = await readFile( - path.join(f.web, 'static/build-info.json') - ); - await writeFile(path.join(f.web, 'build/build-info.json'), metadata); + // This historical graph predates identity activation. Restore its + // immutable public-only producers before compiling the former routes. + for (const [name, value] of Object.entries(historicalPublicOnly)) + await writeFile(path.join(f.web, name), value.source); + // Immutable former route bytes are a labelled verification variant only. + const historical = + "<script lang=\"ts\">\n import { page } from '$app/state';\n import SearchForm from '../../lib/components/SearchForm.svelte';\n import {\n normalizePublicQuery,\n queryErrorMessage,\n readPublicQuery\n } from '../../lib/catalog/query-input';\n import type { PublicQuery } from '../../lib/catalog/query-input';\n import { searchHref } from '../../lib/routes';\n import { internalHref } from '../../lib/navigation-url';\n let query = $state<PublicQuery>(normalizePublicQuery(''));\n let error = $state<string | undefined>();\n $effect(() => {\n query = readPublicQuery(page.url);\n error = undefined;\n });\n function search(input: string) {\n const next = normalizePublicQuery(input);\n if (!next.ok) {\n error = queryErrorMessage(next.error);\n return;\n }\n error = undefined;\n const target = internalHref(searchHref(next.text));\n if (target === undefined) {\n error = queryErrorMessage('invalid_query');\n return;\n }\n globalThis.location.assign(target);\n }\n</script>\n\n<svelte:head><title>Search food \u2014 HarvestCircle</title></svelte:head>\n<div class=\"page page--reading stack\">\n <h1>Search food</h1>\n <SearchForm\n onsubmit={search}\n initialValue={query.ok ? query.text : ''}\n error={error ?? (query.ok ? undefined : queryErrorMessage(query.error))}\n />\n <p class=\"notice\">Search data is unavailable during development.</p>\n</div>\n"; await writeFile( - path.join(f.web, '.svelte-kit/output/client/build-info.json'), - metadata - ); - await assert.rejects(f.audit, /Undeclared compiler module/); - await writeFile(source, original); - } - ); - for (const mutation of [ - 'unknown-name', - 'duplicate', - 'missing-module', - 'missing-page', - 'changed-page' - ]) { - await check( - 'exact search compiler admission rejects ' + mutation, - async (t) => { - const f = await fixture(t); - const file = path.join( - f.web, - '.svelte-kit/output/client/.vite/manifest.json' - ); - const manifest = JSON.parse(await readFile(file, 'utf8')); - const entry = Object.entries(manifest).find( - ([, record]) => record.name === 'routes' - ); - assert.ok(entry, 'The actual shared routes module must exist'); - const [key, module] = entry; - if (mutation === 'unknown-name') module.name = 'unapproved-routes'; - if (mutation === 'duplicate') manifest.duplicate = { ...module }; - if (mutation === 'missing-module') delete manifest[key]; - if (mutation === 'missing-page') - await rm(path.join(f.web, 'build/search.html')); - if (mutation === 'changed-page') - await writeFile( - path.join(f.web, 'build/search.html'), - '<h1>Different source</h1>' - ); - await writeFile(file, JSON.stringify(manifest)); - await assert.rejects(f.audit); - } - ); - } - for (const mutation of ['missing', 'changed']) { - await check('full-route static robots rejects ' + mutation, async (t) => { - const f = await fixture(t); - const target = path.join(f.web, 'build/robots.txt'); - if (mutation === 'missing') await rm(target); - else await writeFile(target, 'User-agent: *\nAllow: /\n'); - await assert.rejects(f.audit); - }); - } - await check( - 'full-route compiler rejects an unowned thirteenth node', - async (t) => { - const f = await fixture(t); - const file = path.join( - f.web, - '.svelte-kit/output/client/.vite/manifest.json' - ); - const manifest = JSON.parse(await readFile(file, 'utf8')); - const entry = Object.entries(manifest).find( - ([, record]) => record.name === 'nodes/12' - ); - assert.ok(entry); - entry[1].name = 'nodes/13'; - await writeFile(file, JSON.stringify(manifest)); - await assert.rejects(f.audit, /Undeclared compiler module/); - } - ); - await check( - 'actual shared budgets chunk has owned consumers and counterpart', - async (t) => { - const f = await fixture(t); - const manifest = JSON.parse( - await readFile( - path.join(f.web, '.svelte-kit/output/client/.vite/manifest.json'), - 'utf8' - ) - ); - const entries = Object.entries(manifest).filter( - ([, record]) => record.name === 'Button' - ); - assert.equal(entries.length, 1); - const [key, budget] = entries[0]; - assert.deepEqual(Object.keys(budget).sort(), ['file', 'imports', 'name']); - const client = Object.entries(manifest).find( - ([, record]) => record.name === 'client' - ); - assert.ok(client); - assert.deepEqual(budget.imports, [client[0]]); - for (const name of [ - Object.values(manifest).some((row) => row.name === 'public-runtime') - ? 'public-runtime' - : 'Disclosure', - 'nodes/9', - 'routes' - ]) - assert.ok( - Object.values(manifest) - .find((record) => record.name === name) - .imports.includes(key) + path.join(f.web, 'src/routes/search/+page.svelte'), + historical ); - assert.deepEqual( - await readFile(path.join(f.web, 'build', budget.file)), - await readFile( - path.join(f.web, '.svelte-kit/output/client', budget.file) - ) - ); - assert.ok((await f.audit()).includes(budget.file)); - } - ); - for (const producer of [ - 'src/routes/products/[naddr=naddr]/+page.svelte', - 'src/lib/catalog/product-view.ts', - 'src/lib/components/ListingFacts.svelte', - 'src/lib/components/PublisherIdentity.svelte', - 'src/lib/contracts/food-availability-v1/contact-read.ts', - 'src/lib/navigation-copy.ts', - 'src/lib/runtime/public-runtime.ts', - 'src/lib/catalog/publishers.ts', - 'src/lib/catalog/resolve-head.ts' - ]) { - await check( - 'real product compiler rejects changed owned producer ' + producer, - async (t) => { - const f = await fixture(t); await writeFile( - path.join(f.web, producer), - (await readFile(path.join(f.web, producer), 'utf8')) + - '\n// source mutation\n' + path.join(f.web, 'src/routes/products/[naddr=naddr]/+page.svelte'), + historicalProduct ); await refresh(f); - await assert.rejects( - f.audit, - /Invalid owned product presentation source/ - ); - } - ); - } - for (const mutation of [ - 'missing-publishers', - 'publisher-budget', - 'publisher-shared', - 'publisher-dynamic', - 'product-shared', - 'product-publisher', - 'product-budget', - 'product-dynamic', - 'search-publisher' - ]) { - await check('real product compiler rejects ' + mutation, async (t) => { - const f = await fixture(t), - file = path.join( - f.web, - '.svelte-kit/output/client/.vite/manifest.json' + await copyDependencies(t, base, f.web); + compile(t, f.web); + const manifest = JSON.parse( + await readFile( + path.join(f.web, '.svelte-kit/output/client/.vite/manifest.json'), + 'utf8' + ) ); - const manifest = JSON.parse(await readFile(file, 'utf8')); - const records = Object.entries(manifest); - const find = (/** @type {string} */ name) => { - const row = records.find(([, v]) => v.name === name); - assert.ok(row); - return row; - }; - const [publisherKey, publisher] = find('publishers'); - if (mutation === 'missing-publishers') delete manifest[publisherKey]; - else if (mutation === 'publisher-dynamic') - publisher.dynamicImports = [find('client-entry')[0]]; - else if (mutation === 'product-dynamic') - find('nodes/7')[1].dynamicImports = [find('client-entry')[0]]; - else if ( - mutation === 'publisher-budget' || - mutation === 'publisher-shared' - ) - publisher.imports = publisher.imports.filter( - (/** @type {string} */ key) => - key !== - find( - mutation === 'publisher-budget' - ? 'Button' - : Object.values(manifest).some( - (row) => row.name === 'public-runtime' - ) - ? 'public-runtime' - : 'Disclosure' - )[0] + assert.ok( + Object.values(manifest).some((record) => record.name === 'dist') ); - else { - const target = mutation === 'search-publisher' ? 'nodes/9' : 'nodes/7'; - const dependency = - mutation === 'product-shared' - ? 'Disclosure' - : mutation === 'product-budget' - ? 'Button' - : 'publishers'; - find(target)[1].imports = find(target)[1].imports.filter( - (/** @type {string} */ key) => key !== find(dependency)[0] + assert.ok( + !Object.values(manifest).some( + (record) => + record.name === 'Disclosure' || record.name === 'navigation' + ) ); + assert.equal((await f.audit()).length, 45); } - await writeFile(file, JSON.stringify(manifest)); - await assert.rejects(f.audit, /compiler|budgets/); - }); - } - for (const producer of [ - 'src/routes/search/+page.svelte', - 'src/lib/catalog/search-view.ts', - 'src/lib/components/ListingRow.svelte', - 'src/lib/components/SourceStatus.svelte', - 'src/lib/navigation-scroll.ts', - 'src/lib/components/primitives/Disclosure.svelte' - ]) { - await check( - 'real search compiler rejects changed owned producer ' + producer, + ); + await test( + 'HCP043 search graph remains qualified with the exact historical product shell', + { timeout: 120000 }, async (t) => { const f = await fixture(t); + for (const [name, value] of Object.entries(historicalPublicOnly)) + await writeFile(path.join(f.web, name), value.source); await writeFile( - path.join(f.web, producer), - (await readFile(path.join(f.web, producer), 'utf8')) + - '\n// source mutation\n' + path.join(f.web, 'src/routes/products/[naddr=naddr]/+page.svelte'), + historicalProduct ); await refresh(f); - await assert.rejects( - f.audit, - /Invalid owned search presentation source/ - ); + await copyDependencies(t, base, f.web); + compile(t, f.web); + assert.equal((await f.audit()).length, 46); } ); - } - for (const mutation of [ - 'missing-shared', - 'missing-navigation', - 'root-edge', - 'search-edge', - 'budget-edge', - 'negentropy-edge', - 'sdk-backedge', - 'navigation-edge', - 'navigation-import', - 'navigation-dynamic', - 'shared-import' - ]) { - await check('real search compiler rejects ' + mutation, async (t) => { - const f = await fixture(t); - const file = path.join( - f.web, - '.svelte-kit/output/client/.vite/manifest.json' - ); - const manifest = JSON.parse(await readFile(file, 'utf8')); - const records = Object.entries(manifest); - const find = (/** @type {string} */ name) => { - const entry = records.find(([, v]) => v.name === name); - assert.ok(entry, 'Missing actual compiler record ' + name); - return entry; - }; - const [sharedKey, shared] = find( - Object.values(manifest).some((row) => row.name === 'public-runtime') - ? 'public-runtime' - : 'Disclosure' - ); - const [budgetKey] = find('Button'); - if (mutation === 'missing-shared') delete manifest[sharedKey]; - else if (mutation === 'missing-navigation') - delete manifest[find('navigation')[0]]; - else if (mutation === 'root-edge') - find('nodes/0')[1].imports = find('nodes/0')[1].imports.filter( - (/** @type {string} */ k) => k !== sharedKey - ); - else if (mutation === 'search-edge') - find('nodes/9')[1].imports = find('nodes/9')[1].imports.filter( - (/** @type {string} */ k) => k !== sharedKey - ); - else if (mutation === 'budget-edge') - shared.imports = shared.imports.filter( - (/** @type {string} */ k) => k !== budgetKey + await test( + 'actual output qualification', + { timeout: 180000 }, + async (t) => { + /** @param {string} name @param {(context: import('node:test').TestContext) => Promise<void>} run @param {number} [timeout] */ + const check = (name, run, timeout = 10000) => + t.test(name, { timeout }, run); + await check( + 'actual compiled payload passes and build dispatch invokes the guard last', + async (t) => { + const f = await fixture(t); + const files = await f.audit(); + // Exact eleven-route module/page/static admission; CSS stays once-imported. + assert.equal(files.length, 48); + // The actual SDK payload crosses the reader scratch boundary; a reused + // scratch buffer must still preserve every compiler/static byte exactly. + const sizes = await Promise.all( + files + .filter((name) => name.endsWith('.js')) + .map( + async (name) => + (await lstat(path.join(f.web, 'build', name))).size + ) + ); + assert.ok(sizes.some((bytes) => bytes > 64 * 1024)); + assert.ok(files.includes('search.html')); + assert.equal( + files.filter((name) => name.endsWith('.css')).length, + 1 + ); + assert.ok( + files.some((name) => + /^_app\/immutable\/assets\/[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.css$/.test( + name + ) + ) + ); + assert.ok(files.includes('200.html')); + const pkg = JSON.parse( + await readFile(path.join(f.web, 'package.json'), 'utf8') + ); + assert.match( + pkg.scripts.build, + /vite build && node tools\/check-output\.mjs$/ + ); + } ); - else if (mutation === 'sdk-backedge') find('negentropy')[1].imports = []; - else if (mutation === 'navigation-edge') - find('nodes/9')[1].imports = find('nodes/9')[1].imports.filter( - (/** @type {string} */ k) => k !== find('navigation')[0] + + for (const name of [ + 'components/InboxSetup.svelte', + 'messaging/inbox-setup-view.ts', + 'runtime/view-context.ts' + ]) + await check( + 'linked inbox setup requires exact owned source ' + name, + async (t) => { + const f = await fixture(t); + const file = path.join(f.web, 'src/lib', name); + await writeFile( + file, + (await readFile(file, 'utf8')) + '\n// changed source\n' + ); + await refresh(f); + await assert.rejects(f.audit, /inbox compiler source/); + } + ); + for (const name of [ + 'private-handles', + 'public-runtime', + 'AccountGate', + 'Disclosure' + ]) + await check( + 'linked inbox setup rejects changed exact compiler edge ' + name, + async (t) => { + const f = await fixture(t); + const file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const manifest = JSON.parse(await readFile(file, 'utf8')); + const entry = Object.entries(manifest).find( + ([, row]) => row.name === name + ); + assert.ok(entry, 'Missing actual linked inbox compiler role'); + entry[1].imports = ['forged-compiler-edge']; + await writeFile(file, JSON.stringify(manifest)); + await assert.rejects(f.audit, /compiler/); + } + ); + await check( + 'owned root preserves its lifecycle across a 64 KiB read boundary', + async (t) => { + const f = await fixture(t); + const file = path.join(f.web, 'src/routes/+layout.svelte'); + const layout = await readFile(file, 'utf8'); + // A large harmless comment after the real lifecycle must not overwrite its + // first read chunk when the file reader reuses a scratch buffer. + const expanded = layout.replace( + '</script>', + '/*' + 'owned reader boundary '.repeat(4000) + '*/\n</script>' + ); + assert.ok(Buffer.byteLength(expanded) > 64 * 1024); + await writeFile(file, expanded); + await refresh(f); + assert.equal((await f.audit()).length, 48); + } ); - else if (mutation === 'navigation-import') - find('navigation')[1].imports = [find('client')[0]]; - else if (mutation === 'navigation-dynamic') - find('navigation')[1].dynamicImports = [find('client-entry')[0]]; - else if (mutation === 'shared-import') - shared.imports = shared.imports.filter( - (/** @type {string} */ k) => k !== find('public-key')[0] + + for (const mutation of [ + 'unknown-name', + 'missing-public-key', + 'missing-dist', + 'missing-negentropy', + 'missing-root-edge', + 'random-key', + 'wrong-src', + 'wrong-version', + 'wrong-peer', + 'wrong-basename', + 'wrong-dynamic-flag', + 'entry-flag', + 'css', + 'wrong-import', + 'chunk-src', + 'chunk-entry' + ]) + await check( + 'owned root SDK compiler admission rejects ' + mutation, + async (t) => { + const f = await fixture(t); + const file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const m = JSON.parse(await readFile(file, 'utf8')); + const root = Object.values(m).find((v) => v.name === 'nodes/0'); + const dist = Object.entries(m).find( + ([, v]) => + v.name === + (Object.values(m).some((row) => row.name === 'public-runtime') + ? 'public-runtime' + : 'Disclosure') + ); + assert.ok( + m[sdkKey] && root && dist, + 'Actual successor SDK identities' + ); + if (mutation === 'unknown-name') + m[sdkKey].name = 'unapproved-sdk'; + if ( + mutation.startsWith('missing-') && + mutation !== 'missing-root-edge' + ) { + const entry = Object.entries(m).find( + ([, v]) => + v.name === + (mutation === 'missing-dist' + ? dist[1].name + : mutation.slice(8)) + ); + assert.ok(entry); + delete m[entry[0]]; + } + if (mutation === 'missing-root-edge') dist[1].dynamicImports = []; + if ( + [ + 'random-key', + 'wrong-version', + 'wrong-peer', + 'wrong-basename' + ].includes(mutation) + ) { + const next = + mutation === 'random-key' + ? '_HCrandom.js' + : sdkKey.replace( + mutation === 'wrong-version' + ? '6.2.1' + : mutation === 'wrong-peer' + ? '6.0.3' + : 'negentropy.js', + mutation === 'wrong-basename' ? 'other.js' : '0.0.0' + ); + m[next] = m[sdkKey]; + delete m[sdkKey]; + m[next].src = next; + dist[1].dynamicImports = dist[1].dynamicImports.map( + (/** @type {string} */ k) => (k === sdkKey ? next : k) + ); + } + if (mutation === 'wrong-src') m[sdkKey].src = '_HCwrong.js'; + if (mutation === 'wrong-dynamic-flag') + m[sdkKey].isDynamicEntry = false; + if (mutation === 'entry-flag') m[sdkKey].isEntry = false; + if (mutation === 'css') m[sdkKey].css = []; + if (mutation === 'wrong-import') + m[sdkKey].imports = [ + Object.keys(m).find((k) => m[k].name === 'public-key') + ]; + if (mutation === 'chunk-src') dist[1].src = dist[0]; + if (mutation === 'chunk-entry') dist[1].isEntry = false; + await writeFile(file, JSON.stringify(m)); + await assert.rejects(f.audit, /compiler|runtime/i); + } + ); + for (const mutation of [ + 'copied-files-only', + 'comment-only', + 'string-only', + 'shadowed', + 'rebound', + 'aliased', + 'missing-cleanup', + 'missing-context', + 'wrong-context' + ]) + await check( + 'root runtime activation rejects ' + mutation, + async (t) => { + const f = await fixture(t); + const file = path.join(f.web, 'src/routes/+layout.svelte'); + let layout = await readFile(file, 'utf8'); + if ( + ['copied-files-only', 'comment-only', 'string-only'].includes( + mutation + ) + ) { + const script = layout.slice( + layout.indexOf('>') + 1, + layout.indexOf('</script>') + ); + layout = + '<script lang="ts">' + + (mutation === 'comment-only' + ? '/*' + script + '*/' + : mutation === 'string-only' + ? 'const text = ' + JSON.stringify(script) + ';' + : '') + + '</script><main>Controlled root</main>'; + } + if (mutation === 'shadowed') + layout = layout.replace( + 'onMount(() => {', + 'onMount((publicContext) => {' + ); + if (mutation === 'rebound') + layout = layout.replace( + 'const publicContext', + 'let publicContext' + ); + if (mutation === 'aliased') + layout = layout + .replace( + ' mountPublicRuntime,', + ' mountPublicRuntime as otherMount,' + ) + .replace( + 'mountPublicRuntime(publicContext)', + 'otherMount(publicContext)' + ); + if (mutation === 'missing-cleanup') + layout = layout.replace( + 'return () => closePublicRuntime(publicContext);', + 'return () => {};' + ); + if (mutation === 'missing-context') + layout = layout.replace( + 'setContext(PUBLIC_RUNTIME_CONTEXT, publicContext);', + '' + ); + if (mutation === 'wrong-context') + layout = layout.replace( + 'closePublicRuntime(publicContext)', + 'closePublicRuntime({})' + ); + await writeFile(file, layout); + await refresh(f); + await assert.rejects(f.audit, /compiler|runtime/i); + } + ); + for (const mutation of [ + 'missing-mount', + 'missing-subscription', + 'missing-unsubscribe', + 'missing-close', + 'wrong-context', + 'duplicate-context', + 'extra-mount', + 'aliased-mount', + 'shadowed', + 'missing-context', + 'rebound-context' + ]) + await check( + 'owned identity lifecycle rejects ' + mutation, + async (t) => { + const f = await fixture(t); + const file = path.join(f.web, 'src/routes/+layout.svelte'); + const original = await readFile(file, 'utf8'); + let layout = original; + assert.ok(layout.includes('mountIdentityView(identityContext);')); + if (mutation === 'missing-mount') + layout = layout.replace( + 'mountIdentityView(identityContext);', + '' + ); + if (mutation === 'missing-subscription') + layout = layout.replace( + 'subscribeIdentityView(identityContext,', + 'subscribeIdentityView({},' + ); + if (mutation === 'missing-unsubscribe') + layout = layout.replace(' off();', ''); + if (mutation === 'missing-close') + layout = layout.replace( + 'closeIdentityView(identityContext);', + '' + ); + if (mutation === 'wrong-context') + layout = layout.replace( + 'closeIdentityView(identityContext)', + 'closeIdentityView({})' + ); + if (mutation === 'duplicate-context') + layout = layout.replace( + 'const identityContext = createIdentityViewContext();', + 'const identityContext = createIdentityViewContext(); const other = createIdentityViewContext();' + ); + if (mutation === 'extra-mount') + layout = layout.replace( + 'mountIdentityView(identityContext);', + 'mountIdentityView(identityContext); mountIdentityView(identityContext);' + ); + if (mutation === 'aliased-mount') + layout = layout + .replace( + ' mountIdentityView,', + ' mountIdentityView as otherMount,' + ) + .replace( + 'mountIdentityView(identityContext);', + 'otherMount(identityContext);' + ); + if (mutation === 'shadowed') + layout = layout.replace( + 'const off = subscribeIdentityView', + 'const identityContext = {}; const off = subscribeIdentityView' + ); + if (mutation === 'missing-context') + layout = layout.replace( + 'setContext(IDENTITY_VIEW_CONTEXT, identityContext);', + '' + ); + if (mutation === 'rebound-context') + layout = layout.replace( + 'const identityContext =', + 'let identityContext =' + ); + assert.notEqual(layout, original); + await writeFile(file, layout); + await refresh(f); + await assert.rejects( + f.audit, + /Invalid owned root runtime activation/ + ); + } + ); + for (const mutation of [ + 'missing-view', + 'missing-heads', + 'extra-view-field', + 'wrong-view-imports', + 'wrong-heads-imports', + 'missing-root-edge', + 'missing-gate-edge' + ]) + await check( + 'owned identity compiler topology rejects ' + mutation, + async (t) => { + const f = await fixture(t), + file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const manifest = JSON.parse(await readFile(file, 'utf8')); + /** @param {string} name */ + const find = (name) => { + const entry = Object.entries(manifest).find( + ([, record]) => record.name === name + ); + assert.ok(entry, 'Missing observed compiler role: ' + name); + return entry; + }; + const identityCompilerRole = Object.values(manifest).some( + (record) => record.name === 'identity-session' + ) + ? 'identity-session' + : Object.values(manifest).some( + (record) => record.name === 'public-runtime' + ) + ? 'public-runtime' + : 'heads'; + const [identityKey, identity] = find('view-context'), + [headsKey, heads] = find(identityCompilerRole); + if (mutation === 'missing-view') delete manifest[identityKey]; + if (mutation === 'missing-heads') delete manifest[headsKey]; + if (mutation === 'extra-view-field') identity.dynamicImports = []; + if (mutation === 'wrong-view-imports') identity.imports = []; + if (mutation === 'wrong-heads-imports') heads.imports = []; + if ( + mutation === 'missing-root-edge' || + mutation === 'missing-gate-edge' + ) { + const [, consumer] = find( + mutation === 'missing-root-edge' ? 'nodes/0' : 'AccountGate' + ); + consumer.imports = consumer.imports.filter( + /** @param {string} dependency */ + (dependency) => dependency !== identityKey + ); + } + await writeFile(file, JSON.stringify(manifest)); + await assert.rejects(f.audit, /compiler/i); + } + ); + for (const name of [ + 'runtime/public-runtime.ts', + 'nostr/request-scope.ts', + 'nostr/public-pool.ts', + 'nostr/public-store.ts', + 'nostr/request-result.ts', + 'nostr/ingress.ts', + 'nostr/verified-envelope.ts', + 'nostr/envelope-bounds.ts', + 'nostr/exports.ts', + 'catalog/observations.ts', + 'config/budgets.ts', + 'config/relays.ts', + 'config/deployment-relays.ts' + ]) + await check( + 'root runtime admission requires owned ' + name, + async (t) => { + const f = await fixture(t); + await rm(path.join(f.web, 'src/lib', name)); + await refresh(f); + await assert.rejects(f.audit); + } + ); + for (const routeSource of [ + 'search/+page.svelte', + 'messages/+page.svelte' + ]) + await check( + routeSource + + ' admission requires its owned source and exact module/page counterparts', + async (t) => { + const f = await fixture(t); + const source = path.join(f.web, 'src/routes', routeSource); + const original = await readFile(source); + await rm(source); + git(f.root, 'add', '--', 'web/src/routes/' + routeSource); + await generateBuildInfo(f.web); + const metadata = await readFile( + path.join(f.web, 'static/build-info.json') + ); + await writeFile( + path.join(f.web, 'build/build-info.json'), + metadata + ); + await writeFile( + path.join(f.web, '.svelte-kit/output/client/build-info.json'), + metadata + ); + await assert.rejects(f.audit, /Undeclared compiler module/); + await writeFile(source, original); + } + ); + for (const mutation of [ + 'unknown-name', + 'duplicate', + 'missing-module', + 'missing-page', + 'changed-page' + ]) { + await check( + 'exact search compiler admission rejects ' + mutation, + async (t) => { + const f = await fixture(t); + const file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const manifest = JSON.parse(await readFile(file, 'utf8')); + const entry = Object.entries(manifest).find( + ([, record]) => record.name === 'routes' + ); + assert.ok(entry, 'The actual shared routes module must exist'); + const [key, module] = entry; + if (mutation === 'unknown-name') + module.name = 'unapproved-routes'; + if (mutation === 'duplicate') manifest.duplicate = { ...module }; + if (mutation === 'missing-module') delete manifest[key]; + if (mutation === 'missing-page') + await rm(path.join(f.web, 'build/search.html')); + if (mutation === 'changed-page') + await writeFile( + path.join(f.web, 'build/search.html'), + '<h1>Different source</h1>' + ); + await writeFile(file, JSON.stringify(manifest)); + await assert.rejects(f.audit); + } + ); + } + for (const mutation of ['missing', 'changed']) { + await check( + 'full-route static robots rejects ' + mutation, + async (t) => { + const f = await fixture(t); + const target = path.join(f.web, 'build/robots.txt'); + if (mutation === 'missing') await rm(target); + else await writeFile(target, 'User-agent: *\nAllow: /\n'); + await assert.rejects(f.audit); + } + ); + } + await check( + 'full-route compiler rejects an unowned thirteenth node', + async (t) => { + const f = await fixture(t); + const file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const manifest = JSON.parse(await readFile(file, 'utf8')); + const entry = Object.entries(manifest).find( + ([, record]) => record.name === 'nodes/12' + ); + assert.ok(entry); + entry[1].name = 'nodes/13'; + await writeFile(file, JSON.stringify(manifest)); + await assert.rejects(f.audit, /Undeclared compiler module/); + } ); - else shared.dynamicImports = []; - await writeFile(file, JSON.stringify(manifest)); - await assert.rejects(f.audit, /compiler|SDK|budgets/); - }); - } - for (const mutation of [ - 'unknown-name', - 'duplicate', - 'missing-module', - 'extra-field', - 'missing-root-edge', - 'missing-routes-edge', - 'missing-counterpart', - 'changed-counterpart' - ]) { - await check('budgets module fails closed: ' + mutation, async (t) => { - const f = await fixture(t); - const file = path.join( - f.web, - '.svelte-kit/output/client/.vite/manifest.json' - ); - const manifest = JSON.parse(await readFile(file, 'utf8')); - const entry = Object.entries(manifest).find( - ([, record]) => record.name === 'Button' - ); - assert.ok(entry); - const [key, budget] = entry; - if (mutation === 'unknown-name') budget.name = 'unapproved-budgets'; - if (mutation === 'duplicate') manifest['_HCduplicate.js'] = { ...budget }; - if (mutation === 'missing-module') delete manifest[key]; - if (mutation === 'extra-field') budget.dynamicImports = []; - if ( - mutation === 'missing-root-edge' || - mutation === 'missing-routes-edge' - ) { - const name = mutation === 'missing-root-edge' ? 'nodes/9' : 'routes'; - const consumer = Object.values(manifest).find( - (record) => record.name === name + await check( + 'actual shared budgets chunk has owned consumers and counterpart', + async (t) => { + const f = await fixture(t); + const manifest = JSON.parse( + await readFile( + path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ), + 'utf8' + ) + ); + const entries = Object.entries(manifest).filter( + ([, record]) => record.name === 'Button' + ); + assert.equal(entries.length, 1); + const [key, budget] = entries[0]; + assert.deepEqual(Object.keys(budget).sort(), [ + 'file', + 'imports', + 'name' + ]); + const client = Object.entries(manifest).find( + ([, record]) => record.name === 'client' + ); + assert.ok(client); + assert.deepEqual(budget.imports, [client[0]]); + for (const name of [ + Object.values(manifest).some( + (row) => row.name === 'public-runtime' + ) + ? 'public-runtime' + : 'Disclosure', + 'nodes/9', + 'routes' + ]) + assert.ok( + Object.values(manifest) + .find((record) => record.name === name) + .imports.includes(key) + ); + assert.deepEqual( + await readFile(path.join(f.web, 'build', budget.file)), + await readFile( + path.join(f.web, '.svelte-kit/output/client', budget.file) + ) + ); + assert.ok((await f.audit()).includes(budget.file)); + } ); - consumer.imports = consumer.imports.filter( - /** @param {string} dependency */ - (dependency) => dependency !== key + for (const producer of [ + 'src/routes/products/[naddr=naddr]/+page.svelte', + 'src/lib/catalog/product-view.ts', + 'src/lib/components/ListingFacts.svelte', + 'src/lib/components/PublisherIdentity.svelte', + 'src/lib/contracts/food-availability-v1/contact-read.ts', + 'src/lib/navigation-copy.ts', + 'src/lib/runtime/public-runtime.ts', + 'src/lib/catalog/publishers.ts', + 'src/lib/catalog/resolve-head.ts' + ]) { + await check( + 'real product compiler rejects changed owned producer ' + producer, + async (t) => { + const f = await fixture(t); + await writeFile( + path.join(f.web, producer), + (await readFile(path.join(f.web, producer), 'utf8')) + + '\n// source mutation\n' + ); + await refresh(f); + await assert.rejects( + f.audit, + /Invalid owned product presentation source/ + ); + } + ); + } + for (const mutation of [ + 'missing-publishers', + 'publisher-budget', + 'publisher-shared', + 'publisher-dynamic', + 'product-shared', + 'product-publisher', + 'product-budget', + 'product-dynamic', + 'search-publisher' + ]) { + await check( + 'real product compiler rejects ' + mutation, + async (t) => { + const f = await fixture(t), + file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const manifest = JSON.parse(await readFile(file, 'utf8')); + const records = Object.entries(manifest); + const find = (/** @type {string} */ name) => { + const row = records.find(([, v]) => v.name === name); + assert.ok(row); + return row; + }; + const [publisherKey, publisher] = find('publishers'); + if (mutation === 'missing-publishers') + delete manifest[publisherKey]; + else if (mutation === 'publisher-dynamic') + publisher.dynamicImports = [find('client-entry')[0]]; + else if (mutation === 'product-dynamic') + find('nodes/7')[1].dynamicImports = [find('client-entry')[0]]; + else if ( + mutation === 'publisher-budget' || + mutation === 'publisher-shared' + ) + publisher.imports = publisher.imports.filter( + (/** @type {string} */ key) => + key !== + find( + mutation === 'publisher-budget' + ? 'Button' + : Object.values(manifest).some( + (row) => row.name === 'public-runtime' + ) + ? 'public-runtime' + : 'Disclosure' + )[0] + ); + else { + const target = + mutation === 'search-publisher' ? 'nodes/9' : 'nodes/7'; + const dependency = + mutation === 'product-shared' + ? 'Disclosure' + : mutation === 'product-budget' + ? 'Button' + : 'publishers'; + find(target)[1].imports = find(target)[1].imports.filter( + (/** @type {string} */ key) => key !== find(dependency)[0] + ); + } + await writeFile(file, JSON.stringify(manifest)); + await assert.rejects(f.audit, /compiler|budgets/); + } + ); + } + for (const producer of [ + 'src/routes/search/+page.svelte', + 'src/lib/catalog/search-view.ts', + 'src/lib/components/ListingRow.svelte', + 'src/lib/components/SourceStatus.svelte', + 'src/lib/navigation-scroll.ts', + 'src/lib/components/primitives/Disclosure.svelte' + ]) { + await check( + 'real search compiler rejects changed owned producer ' + producer, + async (t) => { + const f = await fixture(t); + await writeFile( + path.join(f.web, producer), + (await readFile(path.join(f.web, producer), 'utf8')) + + '\n// source mutation\n' + ); + await refresh(f); + await assert.rejects( + f.audit, + /Invalid owned search presentation source/ + ); + } + ); + } + for (const mutation of [ + 'missing-shared', + 'missing-navigation', + 'root-edge', + 'search-edge', + 'budget-edge', + 'negentropy-edge', + 'sdk-backedge', + 'navigation-edge', + 'navigation-import', + 'navigation-dynamic', + 'shared-import' + ]) { + await check('real search compiler rejects ' + mutation, async (t) => { + const f = await fixture(t); + const file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const manifest = JSON.parse(await readFile(file, 'utf8')); + const records = Object.entries(manifest); + const find = (/** @type {string} */ name) => { + const entry = records.find(([, v]) => v.name === name); + assert.ok(entry, 'Missing actual compiler record ' + name); + return entry; + }; + const [sharedKey, shared] = find( + Object.values(manifest).some( + (row) => row.name === 'public-runtime' + ) + ? 'public-runtime' + : 'Disclosure' + ); + const [budgetKey] = find('Button'); + if (mutation === 'missing-shared') delete manifest[sharedKey]; + else if (mutation === 'missing-navigation') + delete manifest[find('navigation')[0]]; + else if (mutation === 'root-edge') + find('nodes/0')[1].imports = find('nodes/0')[1].imports.filter( + (/** @type {string} */ k) => k !== sharedKey + ); + else if (mutation === 'search-edge') + find('nodes/9')[1].imports = find('nodes/9')[1].imports.filter( + (/** @type {string} */ k) => k !== sharedKey + ); + else if (mutation === 'budget-edge') + shared.imports = shared.imports.filter( + (/** @type {string} */ k) => k !== budgetKey + ); + else if (mutation === 'sdk-backedge') + find('negentropy')[1].imports = []; + else if (mutation === 'navigation-edge') + find('nodes/9')[1].imports = find('nodes/9')[1].imports.filter( + (/** @type {string} */ k) => k !== find('navigation')[0] + ); + else if (mutation === 'navigation-import') + find('navigation')[1].imports = [find('client')[0]]; + else if (mutation === 'navigation-dynamic') + find('navigation')[1].dynamicImports = [find('client-entry')[0]]; + else if (mutation === 'shared-import') + shared.imports = shared.imports.filter( + (/** @type {string} */ k) => k !== find('public-key')[0] + ); + else shared.dynamicImports = []; + await writeFile(file, JSON.stringify(manifest)); + await assert.rejects(f.audit, /compiler|SDK|budgets/); + }); + } + for (const mutation of [ + 'unknown-name', + 'duplicate', + 'missing-module', + 'extra-field', + 'missing-root-edge', + 'missing-routes-edge', + 'missing-counterpart', + 'changed-counterpart' + ]) { + await check('budgets module fails closed: ' + mutation, async (t) => { + const f = await fixture(t); + const file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const manifest = JSON.parse(await readFile(file, 'utf8')); + const entry = Object.entries(manifest).find( + ([, record]) => record.name === 'Button' + ); + assert.ok(entry); + const [key, budget] = entry; + if (mutation === 'unknown-name') budget.name = 'unapproved-budgets'; + if (mutation === 'duplicate') + manifest['_HCduplicate.js'] = { ...budget }; + if (mutation === 'missing-module') delete manifest[key]; + if (mutation === 'extra-field') budget.dynamicImports = []; + if ( + mutation === 'missing-root-edge' || + mutation === 'missing-routes-edge' + ) { + const name = + mutation === 'missing-root-edge' ? 'nodes/9' : 'routes'; + const consumer = Object.values(manifest).find( + (record) => record.name === name + ); + consumer.imports = consumer.imports.filter( + /** @param {string} dependency */ + (dependency) => dependency !== key + ); + } + if (mutation === 'missing-counterpart') + await rm(path.join(f.web, 'build', budget.file)); + if (mutation === 'changed-counterpart') + await writeFile( + path.join(f.web, 'build', budget.file), + 'changed counterpart' + ); + await writeFile(file, JSON.stringify(manifest)); + await assert.rejects( + f.audit, + /Undeclared compiler module|Unresolved compiler import|Invalid owned budgets compiler|Static output inventory mismatch|Static output differs from owned compiler input/ + ); + }); + } + await check( + 'actual route-state compiler module has an owned client counterpart', + async (t) => { + const f = await fixture(t); + const manifest = JSON.parse( + await readFile( + path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ), + 'utf8' + ) + ); + const entries = Object.entries(manifest).filter( + ([, record]) => record.name === 'state' + ); + assert.equal(entries.length, 1); + const [key, state] = entries[0]; + assert.match(key, /^_[A-Za-z0-9_-]+\.js$/); + assert.ok( + state.imports.some( + /** @param {string} dependency */ + (dependency) => manifest[dependency].name === 'client.svelte' + ) + ); + assert.deepEqual( + await readFile(path.join(f.web, 'build', state.file)), + await readFile( + path.join(f.web, '.svelte-kit/output/client', state.file) + ) + ); + assert.ok((await f.audit()).includes(state.file)); + } ); - } - if (mutation === 'missing-counterpart') - await rm(path.join(f.web, 'build', budget.file)); - if (mutation === 'changed-counterpart') - await writeFile( - path.join(f.web, 'build', budget.file), - 'changed counterpart' + for (const mutation of [ + 'unknown-name', + 'duplicate-state', + 'missing-counterpart', + 'changed-counterpart' + ]) { + await check('state module fails closed: ' + mutation, async (t) => { + const f = await fixture(t); + const file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const manifest = JSON.parse(await readFile(file, 'utf8')); + const state = Object.values(manifest).find( + (record) => record.name === 'state' + ); + assert.ok( + state, + 'The actual route-state module must exist before mutation' + ); + if (mutation === 'unknown-name') state.name = 'state-unapproved'; + if (mutation === 'duplicate-state') + manifest['_HCduplicate.js'] = { ...state }; + if (mutation === 'missing-counterpart') + await rm(path.join(f.web, 'build', state.file)); + if (mutation === 'changed-counterpart') + await writeFile( + path.join(f.web, 'build', state.file), + Buffer.concat([ + await readFile(path.join(f.web, 'build', state.file)), + Buffer.from('changed counterpart') + ]) + ); + await writeFile(file, JSON.stringify(manifest)); + await assert.rejects( + f.audit, + mutation.endsWith('name') || mutation === 'duplicate-state' + ? /Undeclared compiler module/ + : /Static output inventory mismatch|Static output differs from owned compiler input/ + ); + }); + } + await check( + 'actual shared Button compiler module has an owned client counterpart', + async (t) => { + const f = await fixture(t); + const manifest = JSON.parse( + await readFile( + path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ), + 'utf8' + ) + ); + const entries = Object.entries(manifest).filter( + ([, record]) => record.name === 'Button' + ); + assert.equal(entries.length, 1); + const [key, button] = entries[0]; + assert.match(key, /^_[A-Za-z0-9_-]+\.js$/); + assert.ok( + button.imports.some( + /** @param {string} dependency */ + (dependency) => manifest[dependency].name === 'client' + ) + ); + for (const consumer of ['nodes/0', 'nodes/2']) { + assert.ok( + Object.values(manifest).some( + (record) => + record.name === consumer && record.imports.includes(key) + ) + ); + } + assert.deepEqual( + await readFile(path.join(f.web, 'build', button.file)), + await readFile( + path.join(f.web, '.svelte-kit/output/client', button.file) + ) + ); + assert.ok((await f.audit()).includes(button.file)); + } ); - await writeFile(file, JSON.stringify(manifest)); - await assert.rejects( - f.audit, - /Undeclared compiler module|Unresolved compiler import|Invalid owned budgets compiler|Static output inventory mismatch|Static output differs from owned compiler input/ - ); - }); - } - await check( - 'actual route-state compiler module has an owned client counterpart', - async (t) => { - const f = await fixture(t); - const manifest = JSON.parse( - await readFile( - path.join(f.web, '.svelte-kit/output/client/.vite/manifest.json'), - 'utf8' - ) - ); - const entries = Object.entries(manifest).filter( - ([, record]) => record.name === 'state' - ); - assert.equal(entries.length, 1); - const [key, state] = entries[0]; - assert.match(key, /^_[A-Za-z0-9_-]+\.js$/); - assert.ok( - state.imports.some( - /** @param {string} dependency */ - (dependency) => manifest[dependency].name === 'client.svelte' - ) - ); - assert.deepEqual( - await readFile(path.join(f.web, 'build', state.file)), - await readFile( - path.join(f.web, '.svelte-kit/output/client', state.file) - ) - ); - assert.ok((await f.audit()).includes(state.file)); - } - ); - for (const mutation of [ - 'unknown-name', - 'duplicate-state', - 'missing-counterpart', - 'changed-counterpart' - ]) { - await check('state module fails closed: ' + mutation, async (t) => { - const f = await fixture(t); - const file = path.join( - f.web, - '.svelte-kit/output/client/.vite/manifest.json' - ); - const manifest = JSON.parse(await readFile(file, 'utf8')); - const state = Object.values(manifest).find( - (record) => record.name === 'state' - ); - assert.ok( - state, - 'The actual route-state module must exist before mutation' - ); - if (mutation === 'unknown-name') state.name = 'state-unapproved'; - if (mutation === 'duplicate-state') - manifest['_HCduplicate.js'] = { ...state }; - if (mutation === 'missing-counterpart') - await rm(path.join(f.web, 'build', state.file)); - if (mutation === 'changed-counterpart') - await writeFile( - path.join(f.web, 'build', state.file), - Buffer.concat([ - await readFile(path.join(f.web, 'build', state.file)), - Buffer.from('changed counterpart') - ]) + for (const mutation of [ + 'unknown-name', + 'duplicate-Button', + 'missing-counterpart', + 'changed-counterpart' + ]) { + await check('Button module fails closed: ' + mutation, async (t) => { + const f = await fixture(t); + const file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const manifest = JSON.parse(await readFile(file, 'utf8')); + const state = Object.values(manifest).find( + (record) => record.name === 'Button' + ); + assert.ok( + state, + 'The actual shared Button module must exist before mutation' + ); + if (mutation === 'unknown-name') state.name = 'Button-unapproved'; + if (mutation === 'duplicate-Button') + manifest['_HCduplicate.js'] = { ...state }; + if (mutation === 'missing-counterpart') + await rm(path.join(f.web, 'build', state.file)); + if (mutation === 'changed-counterpart') + await writeFile( + path.join(f.web, 'build', state.file), + Buffer.concat([ + await readFile(path.join(f.web, 'build', state.file)), + Buffer.from('changed counterpart') + ]) + ); + await writeFile(file, JSON.stringify(manifest)); + await assert.rejects( + f.audit, + mutation.endsWith('name') || mutation === 'duplicate-Button' + ? /Undeclared compiler module/ + : /Static output inventory mismatch|Static output differs from owned compiler input/ + ); + }); + } + for (const name of [ + 'notes.txt', + '_app/immutable/chunks/innocent.ABC12345.js', + 'docs/parent.html', + 'state.css', + 'source.map', + 'contracts/vector.json' + ]) { + await check( + `undeclared copied output is rejected: ${name}`, + async (t) => { + const f = await fixture(t); + const file = path.join(f.web, 'build', name); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, 'ordinary public text'); + await assert.rejects(f.audit); + } + ); + } + for (const payload of [ + Buffer.from('SQLite format 3\0'), + Buffer.from([0x7f, 0x45, 0x4c, 0x46]), + Buffer.from([0xcf, 0xfa, 0xed, 0xfe]), + Buffer.from('PK\x03\x04'), + Buffer.from('MZnative'), + Buffer.from('generated UniFFI bindings'), + Buffer.from('HC_TEST_ONLY_SECRET'), + Buffer.from('nsec1' + 'a'.repeat(60)), + Buffer.from('-----BEGIN PRIVATE KEY-----'), + Buffer.from('private_transcript: controlled disclosure'), + Buffer.from('class TestSigner {}') + ]) { + await check( + `manifest-admitted contamination ${payload.subarray(0, 18).toString('hex')}`, + async (t) => { + const f = await fixture(t); + const manifest = JSON.parse( + await readFile( + path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ), + 'utf8' + ) + ); + const name = Object.values(manifest).find( + (entry) => entry.name === 'client' + ).file; + // Poison both sides: byte mapping alone does not qualify contents. + for (const directory of ['build', '.svelte-kit/output/client']) + await writeFile(path.join(f.web, directory, name), payload); + await assert.rejects(f.audit, /contamination|binary|text/); + } + ); + } + for (const name of [ + 'index.html', + '200.html', + '_app/version.json', + 'build-info.json' + ]) { + await check(`missing/tampered owned output: ${name}`, async (t) => { + const f = await fixture(t); + const file = path.join(f.web, 'build', name); + const original = await readFile(file); + await rm(file); + await assert.rejects(f.audit); + await writeFile( + file, + Buffer.concat([original, Buffer.from('tampered')]) + ); + await assert.rejects(f.audit); + }); + } + for (const mutation of [ + 'unknown', + 'private', + 'revision', + 'dirty', + 'lock', + 'config', + 'source', + 'generated' + ]) { + await check(`provenance fails closed: ${mutation}`, async (t) => { + const f = await fixture(t); + const metadata = JSON.parse( + await readFile(path.join(f.web, 'build/build-info.json'), 'utf8') + ); + if (mutation === 'unknown') metadata.web_source.unknown = 'extra'; + if (mutation === 'private') + metadata.private_transcript = 'controlled disclosure'; + if (mutation === 'revision') + metadata.web_source.revision = 'a'.repeat(40); + if (mutation === 'dirty') + metadata.web_source.dirty = !metadata.web_source.dirty; + if (mutation === 'lock') + await writeFile( + path.join(f.web, 'pnpm-lock.yaml'), + 'changed lock' + ); + if (mutation === 'config') + await writeFile( + path.join(f.web, 'vite.config.ts'), + 'changed config' + ); + if (mutation === 'source') + await writeFile( + path.join(f.web, 'src/app.html'), + 'changed source' + ); + if (mutation === 'generated') + git(f.root, 'add', '-f', 'web/static/build-info.json'); + if ( + ['unknown', 'private', 'revision', 'dirty'].includes(mutation) + ) { + for (const directory of [ + 'build', + 'static', + '.svelte-kit/output/client' + ]) + await writeFile( + path.join(f.web, directory, 'build-info.json'), + JSON.stringify(metadata) + ); + } + await assert.rejects(f.audit); + }); + } + for (const kind of [ + 'symlink', + 'hardlink', + 'fifo', + 'directory', + 'oversize', + 'parent' + ]) { + await check(`unsafe output refuses ${kind} promptly`, async (t) => { + const f = await fixture(t); + const file = path.join(f.web, 'build/index.html'); + await rm(file); + if (kind === 'symlink') await symlink('../src/app.html', file); + if (kind === 'hardlink') + await link(path.join(f.web, 'src/app.html'), file); + if (kind === 'fifo') execFileSync('mkfifo', [file]); + if (kind === 'directory') await mkdir(file); + if (kind === 'oversize') + await writeFile(file, Buffer.alloc(8 * 1024 * 1024 + 1)); + if (kind === 'parent') { + await rm(path.join(f.web, 'build'), { recursive: true }); + await symlink( + path.join(base, 'web/build'), + path.join(f.web, 'build') + ); + } + await assert.rejects(f.audit); + }); + } + await check( + 'compiler manifest cannot authorize arbitrary resources, escapes or unresolved imports', + async (t) => { + const f = await fixture(t); + const file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const original = await readFile(file, 'utf8'); + for (const mutation of [ + 'extra', + 'escape', + 'reference', + 'unknown' + ]) { + const manifest = JSON.parse(original); + const record = Object.values(manifest)[0]; + if (mutation === 'extra') + manifest.extra = { + name: 'provider', + file: '_app/immutable/chunks/provider.ABC12345.js' + }; + if (mutation === 'escape') record.file = '../outside.js'; + if (mutation === 'reference') record.imports = ['absent']; + if (mutation === 'unknown') record.secret = 'private'; + await writeFile(file, JSON.stringify(manifest)); + await assert.rejects(f.audit); + } + } ); - await writeFile(file, JSON.stringify(manifest)); - await assert.rejects( - f.audit, - mutation.endsWith('name') || mutation === 'duplicate-state' - ? /Undeclared compiler module/ - : /Static output inventory mismatch|Static output differs from owned compiler input/ - ); - }); - } - await check( - 'actual shared Button compiler module has an owned client counterpart', - async (t) => { - const f = await fixture(t); - const manifest = JSON.parse( - await readFile( - path.join(f.web, '.svelte-kit/output/client/.vite/manifest.json'), - 'utf8' - ) - ); - const entries = Object.entries(manifest).filter( - ([, record]) => record.name === 'Button' - ); - assert.equal(entries.length, 1); - const [key, button] = entries[0]; - assert.match(key, /^_[A-Za-z0-9_-]+\.js$/); - assert.ok( - button.imports.some( - /** @param {string} dependency */ - (dependency) => manifest[dependency].name === 'client' - ) - ); - for (const consumer of ['nodes/0', 'nodes/2']) { - assert.ok( - Object.values(manifest).some( - (record) => record.name === consumer && record.imports.includes(key) - ) + + await check( + 'generated provenance must remain ignored even when freshly regenerated', + async (t) => { + const f = await fixture(t); + await writeFile(path.join(f.web, '.gitignore'), ''); + await generateBuildInfo(f.web); + await assert.rejects(f.audit, /must be ignored/); + } ); - } - assert.deepEqual( - await readFile(path.join(f.web, 'build', button.file)), - await readFile( - path.join(f.web, '.svelte-kit/output/client', button.file) - ) - ); - assert.ok((await f.audit()).includes(button.file)); - } - ); - for (const mutation of [ - 'unknown-name', - 'duplicate-Button', - 'missing-counterpart', - 'changed-counterpart' - ]) { - await check('Button module fails closed: ' + mutation, async (t) => { - const f = await fixture(t); - const file = path.join( - f.web, - '.svelte-kit/output/client/.vite/manifest.json' - ); - const manifest = JSON.parse(await readFile(file, 'utf8')); - const state = Object.values(manifest).find( - (record) => record.name === 'Button' - ); - assert.ok( - state, - 'The actual shared Button module must exist before mutation' - ); - if (mutation === 'unknown-name') state.name = 'Button-unapproved'; - if (mutation === 'duplicate-Button') - manifest['_HCduplicate.js'] = { ...state }; - if (mutation === 'missing-counterpart') - await rm(path.join(f.web, 'build', state.file)); - if (mutation === 'changed-counterpart') - await writeFile( - path.join(f.web, 'build', state.file), - Buffer.concat([ - await readFile(path.join(f.web, 'build', state.file)), - Buffer.from('changed counterpart') - ]) + for (const name of [ + 'static/build-info.json', + '.svelte-kit/output/client/.vite/manifest.json', + '.svelte-kit/output/prerendered/pages/index.html', + '.svelte-kit/output/prerendered/pages/search.html', + 'src/routes/search/+page.svelte', + 'static/robots.txt', + '.svelte-kit/output/prerendered/pages/messages.html' + ]) { + for (const kind of ['fifo', 'symlink', 'hardlink']) { + await check( + `unsafe compiler/static counterpart ${name}: ${kind}`, + async (t) => { + const f = await fixture(t); + const file = path.join(f.web, name); + await rm(file); + if (kind === 'fifo') execFileSync('mkfifo', [file]); + if (kind === 'symlink') + await symlink(path.join(base, 'web/src/app.html'), file); + if (kind === 'hardlink') + await link(path.join(f.web, 'src/app.html'), file); + await assert.rejects(f.audit); + } + ); + } + } + await check( + 'empty output directory and excessive depth are rejected', + async (t) => { + const f = await fixture(t); + await mkdir(path.join(f.web, 'build/extra')); + await assert.rejects(f.audit); + await rm(path.join(f.web, 'build/extra'), { recursive: true }); + await mkdir(path.join(f.web, 'build/a/b/c/d/e/f/g/h/i'), { + recursive: true + }); + await assert.rejects(f.audit); + } ); - await writeFile(file, JSON.stringify(manifest)); - await assert.rejects( - f.audit, - mutation.endsWith('name') || mutation === 'duplicate-Button' - ? /Undeclared compiler module/ - : /Static output inventory mismatch|Static output differs from owned compiler input/ - ); - }); - } - for (const name of [ - 'notes.txt', - '_app/immutable/chunks/innocent.ABC12345.js', - 'docs/parent.html', - 'state.css', - 'source.map', - 'contracts/vector.json' - ]) { - await check(`undeclared copied output is rejected: ${name}`, async (t) => { - const f = await fixture(t); - const file = path.join(f.web, 'build', name); - await mkdir(path.dirname(file), { recursive: true }); - await writeFile(file, 'ordinary public text'); - await assert.rejects(f.audit); - }); - } - for (const payload of [ - Buffer.from('SQLite format 3\0'), - Buffer.from([0x7f, 0x45, 0x4c, 0x46]), - Buffer.from([0xcf, 0xfa, 0xed, 0xfe]), - Buffer.from('PK\x03\x04'), - Buffer.from('MZnative'), - Buffer.from('generated UniFFI bindings'), - Buffer.from('HC_TEST_ONLY_SECRET'), - Buffer.from('nsec1' + 'a'.repeat(60)), - Buffer.from('-----BEGIN PRIVATE KEY-----'), - Buffer.from('private_transcript: controlled disclosure'), - Buffer.from('class TestSigner {}') - ]) { - await check( - `manifest-admitted contamination ${payload.subarray(0, 18).toString('hex')}`, - async (t) => { - const f = await fixture(t); - const manifest = JSON.parse( - await readFile( - path.join(f.web, '.svelte-kit/output/client/.vite/manifest.json'), - 'utf8' - ) + await check( + 'forged public output failures do not echo private poisoned bytes', + async (t) => { + const f = await fixture(t); + const marker = 'CONTROLLED_SENSITIVE_DO_NOT_ECHO'; + const file = path.join(f.web, 'static/build-info.json'); + await writeFile(file, marker); + await assert.rejects( + f.audit, + (error) => !String(error).includes(marker) + ); + } ); - const name = Object.values(manifest).find( - (entry) => entry.name === 'client' - ).file; - // Poison both sides: byte mapping alone does not qualify contents. - for (const directory of ['build', '.svelte-kit/output/client']) - await writeFile(path.join(f.web, directory, name), payload); - await assert.rejects(f.audit, /contamination|binary|text/); - } - ); - } - for (const name of [ - 'index.html', - '200.html', - '_app/version.json', - 'build-info.json' - ]) { - await check(`missing/tampered owned output: ${name}`, async (t) => { - const f = await fixture(t); - const file = path.join(f.web, 'build', name); - const original = await readFile(file); - await rm(file); - await assert.rejects(f.audit); - await writeFile(file, Buffer.concat([original, Buffer.from('tampered')])); - await assert.rejects(f.audit); - }); - } - for (const mutation of [ - 'unknown', - 'private', - 'revision', - 'dirty', - 'lock', - 'config', - 'source', - 'generated' - ]) { - await check(`provenance fails closed: ${mutation}`, async (t) => { - const f = await fixture(t); - const metadata = JSON.parse( - await readFile(path.join(f.web, 'build/build-info.json'), 'utf8') - ); - if (mutation === 'unknown') metadata.web_source.unknown = 'extra'; - if (mutation === 'private') - metadata.private_transcript = 'controlled disclosure'; - if (mutation === 'revision') - metadata.web_source.revision = 'a'.repeat(40); - if (mutation === 'dirty') - metadata.web_source.dirty = !metadata.web_source.dirty; - if (mutation === 'lock') - await writeFile(path.join(f.web, 'pnpm-lock.yaml'), 'changed lock'); - if (mutation === 'config') - await writeFile(path.join(f.web, 'vite.config.ts'), 'changed config'); - if (mutation === 'source') - await writeFile(path.join(f.web, 'src/app.html'), 'changed source'); - if (mutation === 'generated') - git(f.root, 'add', '-f', 'web/static/build-info.json'); - if (['unknown', 'private', 'revision', 'dirty'].includes(mutation)) { - for (const directory of [ - 'build', - 'static', - '.svelte-kit/output/client' - ]) - await writeFile( - path.join(f.web, directory, 'build-info.json'), - JSON.stringify(metadata) - ); - } - await assert.rejects(f.audit); - }); - } - for (const kind of [ - 'symlink', - 'hardlink', - 'fifo', - 'directory', - 'oversize', - 'parent' - ]) { - await check(`unsafe output refuses ${kind} promptly`, async (t) => { - const f = await fixture(t); - const file = path.join(f.web, 'build/index.html'); - await rm(file); - if (kind === 'symlink') await symlink('../src/app.html', file); - if (kind === 'hardlink') - await link(path.join(f.web, 'src/app.html'), file); - if (kind === 'fifo') execFileSync('mkfifo', [file]); - if (kind === 'directory') await mkdir(file); - if (kind === 'oversize') - await writeFile(file, Buffer.alloc(8 * 1024 * 1024 + 1)); - if (kind === 'parent') { - await rm(path.join(f.web, 'build'), { recursive: true }); - await symlink(path.join(base, 'web/build'), path.join(f.web, 'build')); - } - await assert.rejects(f.audit); - }); - } - await check( - 'compiler manifest cannot authorize arbitrary resources, escapes or unresolved imports', - async (t) => { - const f = await fixture(t); - const file = path.join( - f.web, - '.svelte-kit/output/client/.vite/manifest.json' - ); - const original = await readFile(file, 'utf8'); - for (const mutation of ['extra', 'escape', 'reference', 'unknown']) { - const manifest = JSON.parse(original); - const record = Object.values(manifest)[0]; - if (mutation === 'extra') - manifest.extra = { - name: 'provider', - file: '_app/immutable/chunks/provider.ABC12345.js' - }; - if (mutation === 'escape') record.file = '../outside.js'; - if (mutation === 'reference') record.imports = ['absent']; - if (mutation === 'unknown') record.secret = 'private'; - await writeFile(file, JSON.stringify(manifest)); - await assert.rejects(f.audit); - } - } - ); - - await check( - 'generated provenance must remain ignored even when freshly regenerated', - async (t) => { - const f = await fixture(t); - await writeFile(path.join(f.web, '.gitignore'), ''); - await generateBuildInfo(f.web); - await assert.rejects(f.audit, /must be ignored/); - } - ); - for (const name of [ - 'static/build-info.json', - '.svelte-kit/output/client/.vite/manifest.json', - '.svelte-kit/output/prerendered/pages/index.html', - '.svelte-kit/output/prerendered/pages/search.html', - 'src/routes/search/+page.svelte', - 'static/robots.txt', - '.svelte-kit/output/prerendered/pages/messages.html' - ]) { - for (const kind of ['fifo', 'symlink', 'hardlink']) { - await check( - `unsafe compiler/static counterpart ${name}: ${kind}`, - async (t) => { - const f = await fixture(t); - const file = path.join(f.web, name); - await rm(file); - if (kind === 'fifo') execFileSync('mkfifo', [file]); - if (kind === 'symlink') - await symlink(path.join(base, 'web/src/app.html'), file); - if (kind === 'hardlink') - await link(path.join(f.web, 'src/app.html'), file); - await assert.rejects(f.audit); - } - ); - } - } - await check( - 'empty output directory and excessive depth are rejected', - async (t) => { - const f = await fixture(t); - await mkdir(path.join(f.web, 'build/extra')); - await assert.rejects(f.audit); - await rm(path.join(f.web, 'build/extra'), { recursive: true }); - await mkdir(path.join(f.web, 'build/a/b/c/d/e/f/g/h/i'), { - recursive: true - }); - await assert.rejects(f.audit); - } - ); - await check( - 'forged public output failures do not echo private poisoned bytes', - async (t) => { - const f = await fixture(t); - const marker = 'CONTROLLED_SENSITIVE_DO_NOT_ECHO'; - const file = path.join(f.web, 'static/build-info.json'); - await writeFile(file, marker); - await assert.rejects(f.audit, (error) => !String(error).includes(marker)); - } - ); - await check( - 'output entry and aggregate-byte bounds reject oversized inventories', - async (t) => { - const f = await fixture(t); - for (let i = 0; i < 513; i++) - await writeFile(path.join(f.web, 'build', `tiny-${i}.js`), 'x'); - // Confine the actual audit's allocation measurement to a fresh child; - // prior source/output fixture copies must not enter this baseline/peak. - const measurement = JSON.parse( - execFileSync( - process.execPath, - [ - '--input-type=module', - '-e', - ` + await check( + 'output entry and aggregate-byte bounds reject oversized inventories', + async (t) => { + const f = await fixture(t); + for (let i = 0; i < 513; i++) + await writeFile(path.join(f.web, 'build', `tiny-${i}.js`), 'x'); + // Confine the actual audit's allocation measurement to a fresh child; + // prior source/output fixture copies must not enter this baseline/peak. + const measurement = JSON.parse( + execFileSync( + process.execPath, + [ + '--input-type=module', + '-e', + ` const { auditOutput } = await import(process.argv[2]); const baseline = process.memoryUsage().arrayBuffers; let peak = baseline, rejection; @@ -1425,70 +1556,78 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { if (rejection !== 'Unbounded output inventory') throw new Error('Unexpected inventory measurement rejection'); process.stdout.write(JSON.stringify({ baseline, peak, growth: peak - baseline, rejection })); `, - f.web, - new URL('../../tools/check-output.mjs', import.meta.url).href - ], - { cwd: f.web, encoding: 'utf8', timeout: 8000, maxBuffer: 4096 } - ) - ); - assert.deepEqual(Object.keys(measurement).sort(), [ - 'baseline', - 'growth', - 'peak', - 'rejection' - ]); - assert.equal(measurement.rejection, 'Unbounded output inventory'); - for (const name of ['baseline', 'peak', 'growth']) - assert.ok( - Number.isSafeInteger(measurement[name]) && measurement[name] >= 0 + f.web, + new URL('../../tools/check-output.mjs', import.meta.url).href + ], + { cwd: f.web, encoding: 'utf8', timeout: 8000, maxBuffer: 4096 } + ) + ); + assert.deepEqual(Object.keys(measurement).sort(), [ + 'baseline', + 'growth', + 'peak', + 'rejection' + ]); + assert.equal(measurement.rejection, 'Unbounded output inventory'); + for (const name of ['baseline', 'peak', 'growth']) + assert.ok( + Number.isSafeInteger(measurement[name]) && + measurement[name] >= 0 + ); + assert.equal( + measurement.growth, + measurement.peak - measurement.baseline + ); + t.diagnostic( + 'isolated actual inventory buffers: ' + + JSON.stringify(measurement) + ); + assert.ok( + measurement.growth < 64 * 1024 * 1024, + 'Tiny files must not retain a maximum-sized buffer per entry: ' + + JSON.stringify(measurement) + ); + for (let i = 0; i < 513; i++) + await rm(path.join(f.web, 'build', `tiny-${i}.js`)); + for (let i = 0; i < 33; i++) + await writeFile( + path.join(f.web, 'build', `large-${i}.js`), + Buffer.alloc(1024 * 1024, 97) + ); + await assert.rejects(f.audit, /Unbounded output bytes/); + } ); - assert.equal(measurement.growth, measurement.peak - measurement.baseline); - t.diagnostic( - 'isolated actual inventory buffers: ' + JSON.stringify(measurement) - ); - assert.ok( - measurement.growth < 64 * 1024 * 1024, - 'Tiny files must not retain a maximum-sized buffer per entry: ' + - JSON.stringify(measurement) - ); - for (let i = 0; i < 513; i++) - await rm(path.join(f.web, 'build', `tiny-${i}.js`)); - for (let i = 0; i < 33; i++) + } + ); + await test( + 'actual compiler admits nonempty approved theme/app CSS', + { timeout: 120000 }, + async (t) => { + ready(t); + const layout = path.join(base, 'web/src/routes/+layout.svelte'); await writeFile( - path.join(f.web, 'build', `large-${i}.js`), - Buffer.alloc(1024 * 1024, 97) + layout, + (await readFile(layout, 'utf8')).replace( + '<script lang="ts">', + "<script lang=\"ts\">\n import '../theme.css';\n import '../app.css';" + ) ); - await assert.rejects(f.audit, /Unbounded output bytes/); - } - ); - await check( - 'actual compiler admits nonempty approved theme/app CSS', - async () => { - const layout = path.join(base, 'web/src/routes/+layout.svelte'); - await writeFile( - layout, - (await readFile(layout, 'utf8')).replace( - '<script lang="ts">', - "<script lang=\"ts\">\n import '../theme.css';\n import '../app.css';" - ) - ); - await writeFile( - path.join(base, 'web/src/theme.css'), - ':root { --hc-accent: #336633; }\n' - ); - await writeFile( - path.join(base, 'web/src/app.css'), - 'main { color: var(--hc-accent); }\n' - ); - await generateBuildInfo(path.join(base, 'web')); - execFileSync( - process.execPath, - [path.join(source, 'web/node_modules/vite/bin/vite.js'), 'build'], - { cwd: path.join(base, 'web'), stdio: 'pipe', timeout: 60000 } - ); - const files = await auditOutput(await realpath(path.join(base, 'web'))); - assert.ok(files.some((name) => name.endsWith('.css'))); - }, - 60000 - ); -}); + await writeFile( + path.join(base, 'web/src/theme.css'), + ':root { --hc-accent: #336633; }\n' + ); + await writeFile( + path.join(base, 'web/src/app.css'), + 'main { color: var(--hc-accent); }\n' + ); + await generateBuildInfo(path.join(base, 'web')); + compile(t, path.join(base, 'web')); + const files = await auditOutput(await realpath(path.join(base, 'web'))); + assert.ok(files.some((name) => name.endsWith('.css'))); + } + ); + } finally { + // Await the complete serial sequence before reclaiming its shared build. + await rm(base, { recursive: true, force: true }); + } +} diff --git a/web/tests/provenance/source-boundaries.test.mjs b/web/tests/provenance/source-boundaries.test.mjs @@ -2098,3 +2098,95 @@ test('history scroll owner rejects malformed values without coercion or SSR effe else Reflect.deleteProperty(globalThis, 'window'); } }); + +test( + 'HCP076 allows only the byte-pinned disposable gift-wrap producer and rejects key escape or copied construction', + { timeout: 30000 }, + async () => { + await fixture(async ({ directory, put, execute }) => { + await confineSvelte(directory); + const { cp } = await import('node:fs/promises'); + for (const name of [ + 'applesauce-core', + 'applesauce-signers', + 'applesauce-relay', + 'rxjs', + '@noble/curves', + '@scure/base' + ]) { + const destination = path.join(directory, 'node_modules', name); + await mkdir(path.dirname(destination), { recursive: true }); + await cp( + await realpath(path.join(root, 'node_modules', name)), + destination, + { recursive: true } + ); + } + await cp(path.join(root, 'src/lib'), path.join(directory, 'src/lib'), { + recursive: true + }); + const name = 'src/lib/nostr/giftwrap-builder.ts', + source = await readFile(path.join(root, name), 'utf8'); + assert.equal(execute().status, 0); + for (const alteration of [ + source + '\nexport const secret = generateSecretKey();', + source.replace('secret?.fill(0);', '// cleanup removed'), + source.replace('kind: 1059,', 'kind: 14,'), + source.replace( + "tags: [['p', record.destination]],", + "tags: [['p', record.peer], ['subject', 'leak']]," + ), + source.replace( + "review !== 'reviewed_private_wrap'", + "review !== 'connect'" + ), + source.replace("'applesauce-core/helpers'", "'nostr-tools/pure'") + ]) { + await put(name, alteration); + reject(execute(), /gift-wrap construction source identity/); + } + await put(name, source); + await put('src/lib/nostr/copied-giftwrap-builder.ts', source); + reject(execute(), /credential API/); + }); + } +); +test( + 'HCP076 rejects production key generation and secret access through named, aliased, namespace and bracket APIs outside the exact wrapper', + { timeout: 30000 }, + async () => { + await fixture(async ({ directory, put, execute }) => { + await confineSvelte(directory); + const { cp } = await import('node:fs/promises'); + await cp( + await realpath(path.join(root, 'node_modules/applesauce-core')), + path.join(directory, 'node_modules/applesauce-core'), + { recursive: true } + ); + for (const source of [ + "import * as sdk from 'applesauce-core/helpers'; const {'getPublicKey':read}=sdk; export const value=read;", + "import * as sdk from 'applesauce-core/helpers'; const {['getPublicKey']:read}=sdk; export const value=read;" + ]) { + await put('src/lib/nostr/other.ts', source); + assert.equal(execute().status, 0); + } + for (const source of [ + "import {generateSecretKey} from 'applesauce-core/helpers'; export const key=generateSecretKey();", + "import {generateSecretKey as createKey} from 'applesauce-core/helpers'; export const key=createKey();", + "import * as sdk from 'applesauce-core/helpers'; export const key=sdk.generateSecretKey();", + "import * as sdk from 'applesauce-core/helpers'; export const create=sdk['generateSecretKey'];", + "import * as sdk from 'applesauce-core/helpers'; const {'generateSecretKey':create}=sdk; export const key=create();", + "import * as sdk from 'applesauce-core/helpers'; const {['generateSecretKey']:create}=sdk; export const key=create();", + "import * as sdk from 'applesauce-core/helpers'; const {['generate'+'SecretKey']:create}=sdk; export const key=create();", + "import * as sdk from 'applesauce-core/helpers'; const method=['generate','SecretKey'].join(''); const {[method]:create}=sdk; export const key=create();", + "export const key = provider['getSecretKey'];", + "provider['setSecretKey'](input);", + "const {'getSecretKey':read}=provider; export const key=read();", + "const {'setSecretKey':save}=provider; save(input);" + ]) { + await put('src/lib/nostr/other.ts', source); + reject(execute(), /credential API/); + } + }); + } +); diff --git a/web/tests/unit/giftwrap-builder.test.ts b/web/tests/unit/giftwrap-builder.test.ts @@ -0,0 +1,260 @@ +import { afterEach, expect, it, vi } from 'vitest'; +import { nip44 } from 'applesauce-core/helpers/encryption'; +import { verifyEnvelope } from '../../src/lib/nostr/verified-envelope.ts'; +import type { PrivateRecipientSeal } from '../../src/lib/nostr/seal-builder.ts'; +const state = vi.hoisted(() => ({ + seals: new WeakMap<object, Record<string, unknown>>(), + keys: [] as Uint8Array[], + fixtureKeys: [] as Uint8Array[], + conversations: [] as Uint8Array[], + fail: false, + response: 'normal' +})); +vi.mock('../../src/lib/nostr/seal-builder.ts', () => ({ + privateSealSnapshot: (token: object) => state.seals.get(token) +})); +vi.mock('applesauce-core/helpers', async (original) => { + const sdk = await original<typeof import('applesauce-core/helpers')>(); + return { + ...sdk, + generateSecretKey: () => { + const key = sdk.generateSecretKey(); + state.keys.push(key); + return key; + }, + finalizeEvent: (...args: Parameters<typeof sdk.finalizeEvent>) => { + if (state.fail) throw Error('secret exception must not escape'); + const signed = sdk.finalizeEvent(...args); + if (state.response === 'extra') + return { + ...signed, + plaintext: 'private helper sentinel', + toJSON: () => { + throw Error('unexpected object conversion'); + } + }; + if (state.response === 'wrong_target') + return sdk.finalizeEvent( + { ...args[0], tags: [['p', signed.pubkey]] }, + args[1] + ); + if (state.response === 'cached_bad_id') + return { ...signed, id: '0'.repeat(64), [sdk.verifiedSymbol]: true }; + return signed; + } + }; +}); +vi.mock('applesauce-core/helpers/encryption', async (original) => { + const sdk = + await original<typeof import('applesauce-core/helpers/encryption')>(); + return { + ...sdk, + nip44: { + ...sdk.nip44, + v2: { + ...sdk.nip44.v2, + utils: { + ...sdk.nip44.v2.utils, + getConversationKey: ( + ...args: Parameters<typeof sdk.nip44.v2.utils.getConversationKey> + ) => { + const key = sdk.nip44.v2.utils.getConversationKey(...args); + state.conversations.push(key); + return key; + } + } + } + } + }; +}); +import { generateSecretKey, getPublicKey } from 'applesauce-core/helpers'; +import { + buildPrivateGiftwrap, + privateGiftwrapSnapshot, + type PrivateGiftwrap +} from '../../src/lib/nostr/giftwrap-builder.ts'; +// Unit-only input port substitution checks crypto cleanup; real genuine token +// admission and nested decryption are separately exercised in Chromium. +function fixture(role: 'peer' | 'self' = 'peer') { + const key = generateSecretKey(), + owner = getPublicKey(key), + peerKey = generateSecretKey(), + peer = getPublicKey(peerKey); + state.fixtureKeys.push(key, peerKey); + const seal = Object.freeze({}) as PrivateRecipientSeal; + const record = { + owner, + peer, + destination: role === 'self' ? owner : peer, + role, + command: 'local intent', + rumorHash: 'a'.repeat(64), + wire: '{"encryptedSeal":"unit input port only"}' + }; + state.seals.set(seal, record); + state.keys.length = 0; + return { seal, record, key }; +} +afterEach(() => { + for (const key of [ + ...state.keys, + ...state.fixtureKeys, + ...state.conversations + ]) + key.fill(0); + state.fixtureKeys.length = 0; + state.conversations.length = 0; + state.keys.length = 0; + state.fail = false; + state.response = 'normal'; + vi.unstubAllGlobals(); +}); +it('requires genuine seal ownership and literal review before generating a key', () => { + vi.stubGlobal('window', {}); + expect( + buildPrivateGiftwrap({} as PrivateRecipientSeal, 'reviewed_private_wrap') + ).toBeUndefined(); + const f = fixture(); + expect(buildPrivateGiftwrap(f.seal, 'connect')).toBeUndefined(); + expect(state.keys).toHaveLength(0); + f.key.fill(0); + expect(privateGiftwrapSnapshot({} as PrivateGiftwrap)).toBeUndefined(); +}); +it('does not construct browser wrappers during SSR', () => { + const f = fixture(); + expect(buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap')).toBeUndefined(); + expect(state.keys).toHaveLength(0); + f.key.fill(0); +}); +it('uses a fresh disposable author and exact one-target1059 with only signed fields', () => { + vi.stubGlobal('window', {}); + const f = fixture('self'), + token = buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap'); + expect(token).toBeDefined(); + const saved = privateGiftwrapSnapshot(token!), + event = JSON.parse(saved!.wire) as { + kind: number; + tags: string[][]; + pubkey: string; + created_at: number; + content: string; + }; + expect(event.kind).toBe(1059); + expect(event.tags).toEqual([['p', f.record.owner]]); + expect(event.pubkey).not.toBe(f.record.owner); + expect(event.pubkey).not.toBe(f.record.peer); + expect(Object.keys(event).sort()).toEqual([ + 'content', + 'created_at', + 'id', + 'kind', + 'pubkey', + 'sig', + 'tags' + ]); + expect(verifyEnvelope(saved!.wire).ok).toBe(true); + expect(event.created_at).toBeLessThanOrEqual(Math.floor(Date.now() / 1000)); + expect(event.created_at).toBeGreaterThanOrEqual( + Math.floor(Date.now() / 1000) - 3600 + ); + expect(saved!.wire).not.toContain('encryptedSeal'); + expect(state.keys).toHaveLength(1); + expect(state.keys[0].every((x) => x === 0)).toBe(true); + expect(state.conversations).toHaveLength(1); + expect(state.conversations[0].every((x) => x === 0)).toBe(true); + f.key.fill(0); +}); +it('clears the directly owned ephemeral key even when the SDK signer throws', () => { + vi.stubGlobal('window', {}); + const f = fixture(); + state.fail = true; + expect(buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap')).toBeUndefined(); + expect(state.keys).toHaveLength(1); + expect(state.keys[0].every((x) => x === 0)).toBe(true); + expect(state.conversations).toHaveLength(1); + expect(state.conversations[0].every((x) => x === 0)).toBe(true); + f.key.fill(0); +}); +it('does not return a wrapper after original ownership changes inside SDK key generation', () => { + vi.stubGlobal('window', {}); + const f = fixture(); + const random = crypto.getRandomValues.bind(crypto); + let calls = 0; + const spy = vi.spyOn(crypto, 'getRandomValues').mockImplementation((( + v: Uint8Array<ArrayBuffer> + ) => { + calls++; + if (calls === 2) state.seals.delete(f.seal); + return random(v); + }) as typeof crypto.getRandomValues); + try { + expect( + buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap') + ).toBeUndefined(); + expect(state.keys.every((k) => k.every((x) => x === 0))).toBe(true); + } finally { + spy.mockRestore(); + f.key.fill(0); + } +}); +it('detached wrapper metadata and casts cannot mint tokens; invalidation removes snapshot access', () => { + vi.stubGlobal('window', {}); + const f = fixture(), + token = buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap'); + expect(token).toBeDefined(); + const saved = privateGiftwrapSnapshot(token!); + expect( + privateGiftwrapSnapshot(saved as unknown as PrivateGiftwrap) + ).toBeUndefined(); + state.seals.delete(f.seal); + expect(privateGiftwrapSnapshot(token!)).toBeUndefined(); + f.key.fill(0); +}); +it('fresh peer wrappers have distinct authors and ciphertext without exposing key material', () => { + vi.stubGlobal('window', {}); + const f = fixture(), + first = buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap'), + second = buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap'); + const a = JSON.parse(privateGiftwrapSnapshot(first!)!.wire) as { + pubkey: string; + content: string; + }, + b = JSON.parse(privateGiftwrapSnapshot(second!)!.wire) as { + pubkey: string; + content: string; + }; + expect(a.pubkey).not.toBe(b.pubkey); + expect(a.content).not.toBe(b.content); + expect(state.keys).toHaveLength(2); + expect(state.keys.every((k) => k.every((x) => x === 0))).toBe(true); + // Both peer payloads use actual stock SDK NIP44; inner proof belongs077. + expect(typeof nip44.v2.decrypt).toBe('function'); + f.key.fill(0); +}); + +it('discards SDK extra plaintext and hostile conversion rather than spreading the returned object', () => { + vi.stubGlobal('window', {}); + const f = fixture(); + state.response = 'extra'; + const token = buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap'); + expect(token).toBeDefined(); + const wire = privateGiftwrapSnapshot(token!)!.wire; + expect(wire).not.toContain('sentinel'); + expect(Object.keys(JSON.parse(wire) as Record<string, unknown>)).toHaveLength( + 7 + ); + f.key.fill(0); +}); +for (const response of ['wrong_target', 'cached_bad_id'] as const) + it(`rejects actual SDK ${response} response despite valid signature or cached verification`, () => { + vi.stubGlobal('window', {}); + const f = fixture(); + state.response = response; + expect( + buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap') + ).toBeUndefined(); + expect(state.keys).toHaveLength(1); + expect(state.keys[0].every((x) => x === 0)).toBe(true); + expect(state.conversations[0].every((x) => x === 0)).toBe(true); + f.key.fill(0); + }); diff --git a/web/tools/source-boundaries.mjs b/web/tools/source-boundaries.mjs @@ -1547,6 +1547,20 @@ export async function auditSource(root) { complain(file, `unresolved production import ${specifier}`); } } + // Sole protocol-key exception: the complete independently reviewed wrapper + // source is byte-pinned, not merely whitelisted by filename. Any key escape, + // altered import/role/tag/lifetime or copied producer fails closed until a + // successor explicitly requalifies the changed implementation and this pin. + const giftwrapFile = path.join(root, 'src/lib/nostr/giftwrap-builder.ts'); + const giftwrapTrusted = + files.has(giftwrapFile) && + createHash('sha256').update(files.get(giftwrapFile)).digest('hex') === + '7f22b02cc21bb2cfaca4d984ea3fe94ed92420aad8235901d1819880396fe245'; + if (files.has(giftwrapFile) && !giftwrapTrusted) + complain( + giftwrapFile, + 'gift-wrap construction source identity does not match reviewed pin' + ); const visibilityFile = path.join(root, 'src/lib/runtime/dispose.ts'); const visibilityTrusted = files.has(visibilityFile) && @@ -2159,7 +2173,12 @@ export async function auditSource(root) { 'mockSigner', 'testProvider', 'mockProvider' - ].includes(node.text) + ].includes(node.text) && + !( + node.text === 'generateSecretKey' && + file === giftwrapFile && + giftwrapTrusted + ) ) complain( file, @@ -2287,6 +2306,35 @@ export async function auditSource(root) { ) complain(file, 'raw markup document writers are forbidden'); } + if ( + ts.isBindingElement(node) && + node.propertyName && + (() => { + const computed = ts.isComputedPropertyName(node.propertyName); + const name = computed + ? node.propertyName.expression + : node.propertyName; + return ( + (computed && !ts.isStringLiteralLike(name)) || + (ts.isStringLiteralLike(name) && + ['generateSecretKey', 'getSecretKey', 'setSecretKey'].includes( + name.text + )) + ); + })() + ) + complain( + file, + 'indirect production credential API binding is forbidden' + ); + if ( + ts.isElementAccessExpression(node) && + ts.isStringLiteralLike(node.argumentExpression) && + ['generateSecretKey', 'getSecretKey', 'setSecretKey'].includes( + node.argumentExpression.text + ) + ) + complain(file, 'indirect production credential API is forbidden'); const accessedMethod = ts.isPropertyAccessExpression(node) ? node.name.text : ts.isElementAccessExpression(node) &&