app

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

commit 0a9ac653393a4ed505aafe5670bc838230f01f91
parent 46f3c1dbb4c8fea6ddc964c76cf573e874dc7ef8
Author: triesap <tyson@radroots.org>
Date:   Sun, 11 Oct 2026 14:38:01 +0000

test: qualify hostile nested input and cache boundaries (HCP-131)

- Verify finite nested hash, signature and malformed input controls.
- Reject cached verification flags and forged private cache handles.
- Prove private events stay outside owned public state.
- Preserve genuine browser custody and separate operator qualification.

Diffstat:
Aweb/tests/conformance/private-hostile.test.ts | 286+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/private-cache-scope.test.ts | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 393 insertions(+), 0 deletions(-)

diff --git a/web/tests/conformance/private-hostile.test.ts b/web/tests/conformance/private-hostile.test.ts @@ -0,0 +1,286 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { + generateSecretKey, + getPublicKey, + getEventHash, + finalizeEvent, + verifyEvent, + verifiedSymbol, + type UnsignedEvent +} from 'applesauce-core/helpers'; +import { nip44 } from 'applesauce-core/helpers/encryption'; +import { verifyReceivedLayerData } from '../../src/lib/nostr/unwrap-admission.ts'; +import { verifyEnvelope } from '../../src/lib/nostr/verified-envelope.ts'; +import { + getPublicStore, + insertPublicEnvelope, + publicStoreEnvelope, + publicStoreRetention, + closePublicStore +} from '../../src/lib/nostr/public-store.ts'; +function fixture() { + const keys = [generateSecretKey(), generateSecretKey(), generateSecretKey()]; + const sender = getPublicKey(keys[0]), + owner = getPublicKey(keys[1]), + other = getPublicKey(keys[2]); + const template: UnsignedEvent = { + pubkey: sender, + kind: 14, + created_at: 1700000000, + tags: [['p', owner]], + content: 'Private hostile-input qualification canary' + }; + const rumor = { id: getEventHash(template), ...template }; + function encrypt(key: Uint8Array, target: string, plain: string) { + const conversation = nip44.v2.utils.getConversationKey(key, target); + try { + return nip44.v2.encrypt(plain, conversation); + } finally { + conversation.fill(0); + } + } + const seal = finalizeEvent( + { + kind: 13, + created_at: 1699999900, + tags: [], + content: encrypt(keys[0], owner, JSON.stringify(rumor)) + }, + keys[0] + ); + const outer = finalizeEvent( + { + kind: 1059, + created_at: 1699999800, + tags: [['p', owner]], + content: encrypt(keys[2], owner, JSON.stringify(seal)) + }, + keys[2] + ); + const wire = [outer, seal, rumor].map((value) => JSON.stringify(value)); + const check = (values: readonly unknown[], expected: unknown = owner) => + verifyReceivedLayerData(values[0], values[1], values[2], expected); + return { + keys, + sender, + owner, + other, + rumor, + seal, + outer, + wire, + check, + close: () => keys.forEach((key) => key.fill(0)) + }; +} +await test('finite adversarial nested matrix refuses altered IDs, signatures, author, target, schema and numeric spelling while preserving the next valid candidate', () => { + const f = fixture(); + try { + assert.equal(f.check(f.wire), true); + const candidates: { label: string; layer: number; value: string }[] = []; + for (const [index, original] of [f.outer, f.seal, f.rumor].entries()) { + const raw = JSON.stringify(original); + for (const [field, value] of [ + ['id', '0'.repeat(64)], + ['pubkey', f.owner], + ['kind', 15], + ['content', 'altered plaintext or ciphertext'], + ['created_at', 1700000001], + ['verified', true] + ] as const) + candidates.push({ + label: `${index}:${field}`, + layer: index, + value: JSON.stringify({ ...original, [field]: value }) + }); + candidates.push({ + label: `${index}:duplicate`, + layer: index, + value: raw.replace('"kind":', '"kind":1,"kind":') + }); + const escapedDuplicate = raw.replace('"kind":', '"k\\u0069nd":1,"kind":'); + assert.notEqual(escapedDuplicate, raw); + assert.deepEqual(JSON.parse(escapedDuplicate), JSON.parse(raw)); + candidates.push({ + label: `${index}:escaped-duplicate`, + layer: index, + value: escapedDuplicate + }); + candidates.push({ + label: `${index}:numeric-spelling`, + layer: index, + value: raw.replace(/"created_at":([0-9]+)/u, '"created_at":$1.0') + }); + candidates.push({ + label: `${index}:invalid-json`, + layer: index, + value: raw.slice(0, -1) + }); + } + for (const [index, original] of [f.outer, f.seal].entries()) + candidates.push({ + label: `${index}:signature`, + layer: index, + value: JSON.stringify({ ...original, sig: '0'.repeat(128) }) + }); + candidates.push({ + label: 'outer:valid-wrong-destination', + layer: 0, + value: JSON.stringify( + finalizeEvent({ ...f.outer, tags: [['p', f.sender]] }, f.keys[2]) + ) + }); + candidates.push({ + label: 'seal:valid-other-signer', + layer: 1, + value: JSON.stringify(finalizeEvent({ ...f.seal }, f.keys[1])) + }); + candidates.push({ + label: 'seal:valid-metadata', + layer: 1, + value: JSON.stringify( + finalizeEvent({ ...f.seal, tags: [['subject', 'private']] }, f.keys[0]) + ) + }); + for (const [label, tags, kind] of [ + [ + 'group', + [ + ['p', f.owner], + ['p', f.other] + ], + 14 + ], + [ + 'duplicate-peer', + [ + ['p', f.owner], + ['p', f.owner] + ], + 14 + ], + ['self-request', [['p', f.sender]], 14], + [ + 'file', + [ + ['p', f.owner], + ['file', 'https://example.org/a'] + ], + 15 + ], + [ + 'unknown-tag', + [ + ['p', f.owner], + ['order', 'unsupported'] + ], + 14 + ] + ] as const) { + const changed: UnsignedEvent = { + ...f.rumor, + kind, + tags: tags.map((row) => [...row]) + }; + candidates.push({ + label, + layer: 2, + value: JSON.stringify({ ...changed, id: getEventHash(changed) }) + }); + } + assert.equal(candidates.length, 40); + for (const row of candidates) { + const values = [...f.wire]; + values[row.layer] = row.value; + assert.equal(f.check(values), false, row.label); + assert.equal(f.check(f.wire), true, `valid after ${row.label}`); + } + assert.equal(f.check(f.wire, f.other), false); + assert.equal(f.check(f.wire, { toString: () => f.owner }), false); + } finally { + f.close(); + } +}); +await test('actual SDK cached verified symbols and caller objects cannot replace fresh private layer parsing', () => { + const f = fixture(); + try { + for (const [index, original] of [f.outer, f.seal].entries()) { + const cached = { + ...original, + tags: original.tags.map((tag) => [...tag]) + }; + assert.equal(verifyEvent(cached), true); + assert.equal( + (cached as unknown as Record<symbol, unknown>)[verifiedSymbol], + true + ); + cached.content += 'A'; + assert.equal(verifyEvent(cached), true); + const values: unknown[] = [...f.wire]; + values[index] = JSON.stringify(cached); + assert.equal(f.check(values), false); + values[index] = cached; + assert.equal(f.check(values), false); + } + let calls = 0; + const value = { + toJSON() { + calls++; + return f.rumor; + }, + toString() { + calls++; + return f.wire[2]; + } + }; + assert.equal(f.check([f.wire[0], f.wire[1], value]), false); + assert.equal(calls, 0); + assert.equal(f.check(f.wire), true); + } finally { + f.close(); + } +}); +await test('actual owned public SDK store refuses signed private kinds before retention and remains usable for public inventory', () => { + const f = fixture(), + oldWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'); + Object.defineProperty(globalThis, 'window', { + configurable: true, + value: {} + }); + let store: ReturnType<typeof getPublicStore> = undefined; + try { + store = getPublicStore(); + assert.ok(store); + const before = publicStoreRetention(store); + const events = [f.outer, f.seal, finalizeEvent({ ...f.rumor }, f.keys[0])]; + for (const event of events) { + const proof = verifyEnvelope(JSON.stringify(event)); + assert.equal(proof.ok, true); + if (!proof.ok) throw new Error('invalid real signed control'); + assert.equal(insertPublicEnvelope(store, proof.value), 'not_public'); + assert.equal(publicStoreEnvelope(store, event.id), undefined); + assert.deepEqual(publicStoreRetention(store), before); + } + const publicEvent = finalizeEvent( + { + kind: 10050, + created_at: 1700000000, + tags: [['relay', 'wss://inbox.example.org']], + content: '' + }, + f.keys[0] + ); + const publicProof = verifyEnvelope(JSON.stringify(publicEvent)); + assert.equal(publicProof.ok, true); + if (!publicProof.ok) throw new Error('invalid public control'); + assert.equal(insertPublicEnvelope(store, publicProof.value), 'accepted'); + assert.ok(publicStoreEnvelope(store, publicEvent.id)); + assert.equal(f.check(f.wire), true); + } finally { + if (store) closePublicStore(store); + if (oldWindow) Object.defineProperty(globalThis, 'window', oldWindow); + else Reflect.deleteProperty(globalThis, 'window'); + f.close(); + } +}); diff --git a/web/tests/unit/private-cache-scope.test.ts b/web/tests/unit/private-cache-scope.test.ts @@ -0,0 +1,107 @@ +import { expect, it } from 'vitest'; +import { + getPrivateCacheScope, + retainPrivateCacheWire, + privateCacheWire, + privateCacheSnapshot, + clearPrivateCacheScope, + closePrivateCacheScope, + type PrivateCacheScope +} from '../../src/lib/nostr/private-cache-scope.ts'; +import { + acceptUnlockedConversation, + readUnlockedMessages, + unlockedSessionSnapshot, + unlockedSessionOwnership, + unlockedConversationCurrent, + type UnlockedSession +} from '../../src/lib/messaging/unlocked-session.ts'; +import { + receivedNestedEnvelopeSnapshot, + receivedNestedEnvelopeOwnership, + type ReceivedNestedEnvelope +} from '../../src/lib/nostr/unwrap-admission.ts'; +import { + conversationSnapshot, + conversationOwnership, + type AdmittedConversation +} from '../../src/lib/messaging/admit-conversation.ts'; +import type { PrivateSession } from '../../src/lib/runtime/private-session.ts'; +it('detached data, imported verification marks, getters and proxy copies cannot mint private cache or nested room custody', () => { + let inspected = 0; + const getter = Object.defineProperty({}, 'owner', { + get() { + inspected++; + return '0'.repeat(64); + } + }); + const proxy = new Proxy( + {}, + { + get() { + inspected++; + throw new Error('untrusted getter'); + } + } + ); + const revoked = Proxy.revocable({}, {}); + revoked.revoke(); + const data = { + owner: '0'.repeat(64), + peer: '1'.repeat(64), + rumorId: '2'.repeat(64), + content: 'Detached private-data canary', + verified: true + }; + const candidates = [ + {}, + Object.freeze({}), + { ...data }, + Object.freeze({ ...data }), + JSON.parse(JSON.stringify(data)) as object, + Object.create(data) as object, + { [Symbol.for('verified')]: true }, + getter, + proxy, + revoked.proxy + ]; + expect(candidates).toHaveLength(10); + expect(typeof window).toBe('undefined'); + for (const candidate of candidates) { + const cache = candidate as PrivateCacheScope, + unlocked = candidate as UnlockedSession; + const nested = candidate as ReceivedNestedEnvelope, + room = candidate as AdmittedConversation; + expect( + getPrivateCacheScope(candidate as PrivateSession, 'projection_ownership') + ).toBeUndefined(); + expect( + getPrivateCacheScope(candidate as PrivateSession, 'raw_ciphertext') + ).toBeUndefined(); + for (const action of [ + () => retainPrivateCacheWire(cache, data.rumorId, JSON.stringify(data)), + () => privateCacheWire(cache, data.rumorId), + () => privateCacheSnapshot(cache), + () => clearPrivateCacheScope(cache), + () => closePrivateCacheScope(cache) + ]) + expect(action).toThrow('private_cache_invalid'); + expect(acceptUnlockedConversation(unlocked, room)).toBe('rejected'); + expect(readUnlockedMessages(unlocked)).toEqual({ + status: 'rejected', + messages: [] + }); + expect(unlockedSessionSnapshot(unlocked)).toEqual({ + closed: true, + count: 0, + bytes: 0 + }); + expect(unlockedSessionOwnership(unlocked)).toBeUndefined(); + expect(unlockedConversationCurrent(unlocked, room)).toBe(false); + expect(receivedNestedEnvelopeSnapshot(nested)).toBeUndefined(); + expect(receivedNestedEnvelopeOwnership(nested)).toBeUndefined(); + expect(conversationSnapshot(room)).toBeUndefined(); + expect(conversationOwnership(room)).toBeUndefined(); + } + expect(inspected).toBe(0); +});