app

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

commit a83bb81ef99647ad5a2483da126ef311e0353402
parent 90762e7b75cff35a72ece3dc3c922b3e3421101c
Author: triesap <tyson@radroots.org>
Date:   Fri,  9 Oct 2026 05:50:53 +0000

messages: validate room membership and inbound archive role (HCP-092)

Diffstat:
Aweb/src/lib/messaging/admit-conversation.ts | 130+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/harness/room-admission.ts | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/room-admission.spec.ts | 194+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/room-admission.test.ts | 153+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 629 insertions(+), 0 deletions(-)

diff --git a/web/src/lib/messaging/admit-conversation.ts b/web/src/lib/messaging/admit-conversation.ts @@ -0,0 +1,130 @@ +import { buildCanonicalPairRumor } from '../nostr/rumor-template.ts'; +import { canonicalPublicKey } from '../contracts/public-key.ts'; +import { exactLocalFields } from '../contracts/local-records.ts'; +import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts'; +import { + messageFromWireParts, + messageToWireParts +} from '../contracts/message-v1/index.ts'; +import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts'; +import { + receivedNestedEnvelopeSnapshot, + type ReceivedNestedEnvelope +} from '../nostr/unwrap-admission.ts'; + +export type ConversationRole = 'inbound' | 'self_archive'; +export type ConversationData = Readonly<{ + owner: string; + peer: string; + sender: string; + recipient: string; + role: ConversationRole; + rumorId: string; + createdAt: number; + content: string; + subject: string | null; + replyTo: string | null; +}>; +// Detached inspection grants no sender authentication or effect permission. +// Only the actual SDK nested-custody issuer below admits a current room. +export function inspectConversationData( + raw: unknown, + expectedOwner: unknown, + expectedRole: unknown +): ConversationData | undefined { + const owner = canonicalPublicKey(expectedOwner); + if ( + !owner || + (expectedRole !== 'inbound' && expectedRole !== 'self_archive') || + typeof raw !== 'string' || + !boundedUtf8(raw, 8192) + ) + return undefined; + try { + const rumor: unknown = JSON.parse(raw); + if ( + !exactLocalFields(rumor, [ + 'id', + 'pubkey', + 'created_at', + 'kind', + 'tags', + 'content' + ]) || + rumor.kind !== 14 || + typeof rumor.id !== 'string' || + !/^[0-9a-f]{64}$/u.test(rumor.id) || + safeUnsignedInteger(rumor.created_at) === undefined + ) + return undefined; + const sender = canonicalPublicKey(rumor.pubkey); + if (!sender) return undefined; + const parts = { kind: 14, tags: rumor.tags, content: rumor.content }; + const decoded = messageFromWireParts(JSON.stringify(parts)); + if (!decoded || decoded.recipients.length !== 1) return undefined; + const recipient = decoded.recipients[0].public_key; + if (sender === recipient || (owner !== sender && owner !== recipient)) + return undefined; + const canonical = messageToWireParts(JSON.stringify(decoded)); + if (!canonical || JSON.stringify(canonical) !== JSON.stringify(parts)) + return undefined; + const template = buildCanonicalPairRumor( + JSON.stringify(decoded), + sender, + rumor.created_at + ); + if (!template || template.id !== rumor.id) return undefined; + const role = sender === owner ? 'self_archive' : 'inbound'; + if (role !== expectedRole) return undefined; + return { + owner, + peer: sender === owner ? recipient : sender, + sender, + recipient, + role, + rumorId: rumor.id, + createdAt: template.created_at, + content: canonical.content, + subject: decoded.subject, + // Private parent hash only; no hint, URL or public lookup is authorized. + replyTo: decoded.reply_to?.id ?? null + }; + } catch { + return undefined; + } +} + +declare const conversationBrand: unique symbol; +export type AdmittedConversation = Readonly<{ [conversationBrand]: true }>; +const rooms = new WeakMap< + AdmittedConversation, + { nested: ReceivedNestedEnvelope; role: ConversationRole } +>(); +// Outer disposable pubkey, body contacts and relay hints are never participants. +// The original inner recipient remains unchanged for self archives. No cache, +// persistent projection, send/readiness authority or reply action is minted. +export function admitReceivedConversation( + envelope: ReceivedNestedEnvelope, + expectedRole: unknown +): AdmittedConversation | undefined { + const nested = receivedNestedEnvelopeSnapshot(envelope); + if (!nested) return undefined; + const data = inspectConversationData( + nested.rumorWire, + nested.owner, + expectedRole + ); + if (!data || !receivedNestedEnvelopeSnapshot(envelope)) return undefined; + const token = Object.freeze({}) as AdmittedConversation; + rooms.set(token, { nested: envelope, role: data.role }); + return token; +} +export function conversationSnapshot( + token: AdmittedConversation +): ConversationData | undefined { + const saved = rooms.get(token); + const nested = saved && receivedNestedEnvelopeSnapshot(saved.nested); + return nested && saved + ? inspectConversationData(nested.rumorWire, nested.owner, saved.role) + : undefined; +} diff --git a/web/tests/e2e/harness/room-admission.ts b/web/tests/e2e/harness/room-admission.ts @@ -0,0 +1,152 @@ +import { + getPublicKey, + getEventHash, + finalizeEvent, + type UnsignedEvent +} from 'applesauce-core/helpers'; +import { nip44 } from 'applesauce-core/helpers/encryption'; +import { makeFixture as makeRecoveryFixture } from './resume-preparation.ts'; +import { + createPrivateSession, + closePrivateSession +} from '../../../src/lib/runtime/private-session.ts'; +import { + admitInboxEnvelope, + retainInboxEnvelope +} from '../../../src/lib/persistence/inbox-envelope-repository.ts'; +import { + captureReceivedUnwrap, + unwrapReceivedEnvelope, + stopReceivedUnwrap, + type ReceivedUnwrap, + type ReceivedNestedEnvelope +} from '../../../src/lib/nostr/unwrap-admission.ts'; +import { + admitReceivedConversation, + conversationSnapshot, + type AdmittedConversation +} from '../../../src/lib/messaging/admit-conversation.ts'; +type Scenario = + | 'inbound' + | 'self_archive' + | 'third_party' + | 'hostile_text' + | 'missing_parent'; +export async function makeFixture(scenario: Scenario = 'inbound') { + const f = await makeRecoveryFixture(), + privateSession = await createPrivateSession( + f.identity, + 'reviewed_private_session' + ); + if (!privateSession) throw Error('missing genuine private session'); + const ownerSecret = new Uint8Array(32).fill(83), + peerSecret = new Uint8Array(32).fill(84), + outerSecret = new Uint8Array(32).fill(85), + other = getPublicKey(outerSecret); + const senderSecret = scenario === 'self_archive' ? ownerSecret : peerSecret, + sender = getPublicKey(senderSecret), + recipient = + scenario === 'self_archive' + ? f.peer + : scenario === 'third_party' + ? other + : f.owner; + const tags: string[][] = [['p', recipient]]; + if (scenario === 'hostile_text') tags.push(['subject', other]); + if (scenario === 'missing_parent') + tags.push(['e', 'a'.repeat(64), 'wss://untrusted.example.org']); + const template: UnsignedEvent = { + pubkey: sender, + kind: 14, + created_at: 1700000000, + tags, + content: + scenario === 'hostile_text' + ? `Contact ${other} https://untrusted.example.org` + : 'Actual encrypted room fixture' + }, + 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(senderSecret, f.owner, JSON.stringify(rumor)) + }, + senderSecret + ); + const outer = finalizeEvent( + { + kind: 1059, + created_at: 1699999800, + tags: [['p', f.owner]], + content: encrypt(outerSecret, f.owner, JSON.stringify(seal)) + }, + outerSecret + ); + ownerSecret.fill(0); + peerSecret.fill(0); + outerSecret.fill(0); + const admitted = admitInboxEnvelope( + JSON.stringify(outer), + f.owner, + 'wss://archive.example.org', + 100 + ); + if (!admitted) throw Error('missing signed addressed outer'); + const saved = await retainInboxEnvelope( + f.repository, + privateSession, + admitted + ); + if (saved.status !== 'retained') throw Error('no actual retained cipher'); + let reader: ReceivedUnwrap | undefined, + nested: ReceivedNestedEnvelope | undefined, + room: AdmittedConversation | undefined; + return { + ...f, + other, + rumorId: rumor.id, + async unlock() { + reader = captureReceivedUnwrap( + f.repository, + f.identity, + outer.id, + 'reviewed_inbox_unlock' + ); + if (!reader) return 'invalid'; + const result = await unwrapReceivedEnvelope(reader); + if (result.status === 'authenticated') nested = result.envelope; + return result.status; + }, + admit(role: unknown) { + room = nested && admitReceivedConversation(nested, role); + return room && conversationSnapshot(room); + }, + snapshot() { + return room && conversationSnapshot(room); + }, + forged() { + return admitReceivedConversation({} as ReceivedNestedEnvelope, 'inbound'); + }, + copied() { + return room && conversationSnapshot({ ...room }); + }, + stop() { + if (reader) stopReceivedUnwrap(reader); + }, + close() { + if (reader) stopReceivedUnwrap(reader); + closePrivateSession(privateSession); + f.close(); + } + }; +} diff --git a/web/tests/e2e/room-admission.spec.ts b/web/tests/e2e/room-admission.spec.ts @@ -0,0 +1,194 @@ +import { test, expect } from '@playwright/test'; +import { build } from 'vite'; +import { fileURLToPath } from 'node:url'; +import { createStaticHarness } from '../integration/harness/static.ts'; +import type * as Fixture from './harness/room-admission.ts'; +declare global { + interface Window { + hcp092: typeof Fixture; + hcp092Fixture: Awaited<ReturnType<typeof Fixture.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/room-admission.ts', import.meta.url) + ), + name: 'hcp092', + formats: ['iife'] + } + } + }); + const output = Array.isArray(result) ? result[0] : result; + if (!('output' in output)) throw Error('bundle missing'); + const chunks = output.output.filter((x) => x.type === 'chunk'); + expect(chunks).toHaveLength(1); + bundle = chunks[0].code; +}); +test.afterAll(async () => { + await server.close(); +}); +test.beforeEach(async ({ page }) => { + await page.goto(server.url + '/search'); + await page.addScriptTag({ content: bundle }); +}); +test.afterEach(async ({ page }) => { + if (!page.isClosed()) + await page.evaluate(() => window.hcp092Fixture?.close()); +}); +test('actual SDK-authenticated inbound selects sender and rejects forged or copied room custody', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = (window.hcp092Fixture = await window.hcp092.makeFixture()); + const unlocked = await f.unlock(); + return { + unlocked, + room: f.admit('inbound'), + peer: f.peer, + owner: f.owner, + forged: f.forged(), + copied: f.copied(), + id: f.rumorId + }; + }); + expect(r.unlocked).toBe('authenticated'); + expect(r.room).toMatchObject({ + owner: r.owner, + peer: r.peer, + sender: r.peer, + recipient: r.owner, + role: 'inbound', + rumorId: r.id + }); + expect(r.forged).toBeUndefined(); + expect(r.copied).toBeUndefined(); +}); +test('actual authenticated self archive preserves original peer recipient and rumor id', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = (window.hcp092Fixture = + await window.hcp092.makeFixture('self_archive')); + return { + unlocked: await f.unlock(), + room: f.admit('self_archive'), + owner: f.owner, + peer: f.peer, + id: f.rumorId + }; + }); + expect(r.unlocked).toBe('authenticated'); + expect(r.room).toMatchObject({ + owner: r.owner, + sender: r.owner, + recipient: r.peer, + peer: r.peer, + role: 'self_archive', + rumorId: r.id + }); +}); +test('actual signed decrypted third-party rumor cannot admit connected owner room', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = (window.hcp092Fixture = + await window.hcp092.makeFixture('third_party')); + return { unlocked: await f.unlock(), room: f.admit('inbound') }; + }); + expect(r.unlocked).toBe('authenticated'); + expect(r.room).toBeUndefined(); +}); +test('explicit expected role mismatch cannot reinterpret a valid inbound as archive', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = (window.hcp092Fixture = await window.hcp092.makeFixture()); + return { + unlocked: await f.unlock(), + wrong: f.admit('self_archive'), + right: f.admit('inbound') + }; + }); + expect(r.unlocked).toBe('authenticated'); + expect(r.wrong).toBeUndefined(); + expect(r.right?.role).toBe('inbound'); +}); +test('body URL and subject never retarget actual authenticated peer', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = (window.hcp092Fixture = + await window.hcp092.makeFixture('hostile_text')); + return { + unlocked: await f.unlock(), + room: f.admit('inbound'), + peer: f.peer, + other: f.other + }; + }); + expect(r.unlocked).toBe('authenticated'); + expect(r.room?.peer).toBe(r.peer); + expect(r.room?.peer).not.toBe(r.other); +}); +test('missing private parent and untrusted hint cause zero public or private socket lookups', async ({ + page +}) => { + const requests: string[] = []; + const sockets: string[] = []; + page.on('request', (request) => requests.push(request.url())); + page.on('websocket', (socket) => sockets.push(socket.url())); + const r = await page.evaluate(async () => { + const f = (window.hcp092Fixture = + await window.hcp092.makeFixture('missing_parent')); + return { unlocked: await f.unlock(), room: f.admit('inbound') }; + }); + expect(r.unlocked).toBe('authenticated'); + expect(r.room?.replyTo).toBe('a'.repeat(64)); + expect(requests).toEqual([]); + expect(sockets).toEqual([]); +}); +test('logout removes current genuine room custody and prevents readmission', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = (window.hcp092Fixture = await window.hcp092.makeFixture()); + await f.unlock(); + const before = f.admit('inbound'); + f.disconnect(); + return { before, after: f.snapshot(), again: f.admit('inbound') }; + }); + expect(r.before).toBeDefined(); + expect(r.after).toBeUndefined(); + expect(r.again).toBeUndefined(); +}); +test('Stop revokes original nested-dependent room proof without cancelling already settled SDK work', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = (window.hcp092Fixture = await window.hcp092.makeFixture()); + await f.unlock(); + const before = f.admit('inbound'), + counts = f.counts(); + f.stop(); + return { + before, + after: f.snapshot(), + again: f.admit('inbound'), + counts, + afterCounts: f.counts() + }; + }); + expect(r.before).toBeDefined(); + expect(r.after).toBeUndefined(); + expect(r.again).toBeUndefined(); + expect(r.afterCounts).toEqual(r.counts); +}); diff --git a/web/tests/unit/room-admission.test.ts b/web/tests/unit/room-admission.test.ts @@ -0,0 +1,153 @@ +import { describe, it, expect } from 'vitest'; +import { + getPublicKey, + getEventHash, + type UnsignedEvent +} from 'applesauce-core/helpers'; +import { + inspectConversationData, + admitReceivedConversation, + conversationSnapshot +} from '../../src/lib/messaging/admit-conversation.ts'; +import type { ReceivedNestedEnvelope } from '../../src/lib/nostr/unwrap-admission.ts'; +const owner = getPublicKey(new Uint8Array(32).fill(83)), + peer = getPublicKey(new Uint8Array(32).fill(84)), + other = getPublicKey(new Uint8Array(32).fill(85)); +function rumor( + sender = peer, + recipient = owner, + content = 'Untrusted plain text', + extra: string[][] = [] +) { + const template: UnsignedEvent = { + pubkey: sender, + kind: 14, + created_at: 1700000000, + tags: [['p', recipient], ...extra], + content + }; + return JSON.stringify({ id: getEventHash(template), ...template }); +} +describe('detached exact room inspection grants no authenticated custody', () => { + it('inbound owner membership selects authenticated sender as peer', () => + expect(inspectConversationData(rumor(), owner, 'inbound')).toMatchObject({ + owner, + peer, + sender: peer, + recipient: owner, + role: 'inbound' + })); + it('self archive retains original recipient instead of changing rumor room', () => + expect( + inspectConversationData(rumor(owner, peer), owner, 'self_archive') + ).toMatchObject({ + owner, + peer, + sender: owner, + recipient: peer, + role: 'self_archive' + })); + it('third party rumor excludes connected account', () => + expect( + inspectConversationData(rumor(peer, other), owner, 'inbound') + ).toBeUndefined()); + it('group and duplicate-recipient fanout are rejected', () => { + expect( + inspectConversationData( + rumor(peer, owner, 'text', [['p', other]]), + owner, + 'inbound' + ) + ).toBeUndefined(); + expect( + inspectConversationData( + rumor(peer, owner, 'text', [['p', owner]]), + owner, + 'inbound' + ) + ).toBeUndefined(); + }); + it('self request has no other participant', () => + expect( + inspectConversationData(rumor(owner, owner), owner, 'self_archive') + ).toBeUndefined()); + it('expected inbound/archive role must match actual authenticated sender', () => { + expect( + inspectConversationData(rumor(), owner, 'self_archive') + ).toBeUndefined(); + expect( + inspectConversationData(rumor(owner, peer), owner, 'inbound') + ).toBeUndefined(); + expect( + inspectConversationData(rumor(), owner, 'automatic') + ).toBeUndefined(); + }); + it('subject URLs and body contact strings cannot select another peer', () => + expect( + inspectConversationData( + rumor(peer, owner, `Contact ${other} https://untrusted.example.org`, [ + ['subject', other] + ]), + owner, + 'inbound' + ) + ).toMatchObject({ peer, sender: peer })); + it('unknown parent remains a detached private hash without public lookup', () => + expect( + inspectConversationData( + rumor(peer, owner, 'text', [ + ['e', 'a'.repeat(64), 'wss://untrusted.example.org'] + ]), + owner, + 'inbound' + ) + ).toMatchObject({ peer, replyTo: 'a'.repeat(64) })); + it('fresh rumor hash is required before room inspection', () => { + const row = JSON.parse(rumor()) as Record<string, unknown>; + expect( + inspectConversationData( + JSON.stringify({ ...row, id: '0'.repeat(64) }), + owner, + 'inbound' + ) + ).toBeUndefined(); + }); + it('malformed and caller object values are isolated', () => { + expect(inspectConversationData('{}', owner, 'inbound')).toBeUndefined(); + expect( + inspectConversationData(JSON.parse(rumor()) as unknown, owner, 'inbound') + ).toBeUndefined(); + expect(inspectConversationData(rumor(), other, 'inbound')).toBeUndefined(); + expect(inspectConversationData(rumor(), owner, 'inbound')).toBeDefined(); + }); + it('unsupported tags and signed rumor cannot become room data', () => { + expect( + inspectConversationData( + rumor(peer, owner, 'text', [['file', 'https://untrusted.example.org']]), + owner, + 'inbound' + ) + ).toBeUndefined(); + const row = JSON.parse(rumor()) as Record<string, unknown>; + expect( + inspectConversationData( + JSON.stringify({ ...row, sig: '0'.repeat(128) }), + owner, + 'inbound' + ) + ).toBeUndefined(); + }); + it('structural nested objects and copied detached rooms grant no proof', () => { + const fake = {} as ReceivedNestedEnvelope; + expect(admitReceivedConversation(fake, 'inbound')).toBeUndefined(); + expect( + conversationSnapshot( + inspectConversationData( + rumor(), + owner, + 'inbound' + ) as unknown as Parameters<typeof conversationSnapshot>[0] + ) + ).toBeUndefined(); + }); +});