app

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

commit 9f9bcc1ce0df6e058251b729446b1575fa353781
parent 72aca8414f66e5cf2e44558273ce7d5fd986afe1
Author: triesap <tyson@radroots.org>
Date:   Fri,  9 Oct 2026 12:36:54 +0000

messages: resolve owner-local conversation navigation (HCP-100)

- Require genuine original owner generation for private local UUID resolution
- Map admitted exchanges without treating navigation as a read action
- Preserve generic private routes and safe unavailable inbox navigation
- Verify detached custody, shared pair rooms and exact compiler dependency sets

Diffstat:
Aweb/src/lib/messaging/conversation-directory.ts | 177+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/src/lib/persistence/message-metadata.ts | 59++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mweb/src/routes/messages/[conversationId=local_id]/+page.svelte | 74+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Aweb/tests/e2e/conversation-directory.spec.ts | 325+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/harness/conversation-directory.ts | 127+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/e2e/harness/message-metadata.ts | 16++++++++++++++--
Mweb/tests/provenance/output.test.mjs | 44++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/conversation-directory.test.ts | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/unit/route-inventory.test.ts | 16++++++++--------
Mweb/tools/check-output.mjs | 12++++++++----
10 files changed, 885 insertions(+), 20 deletions(-)

diff --git a/web/src/lib/messaging/conversation-directory.ts b/web/src/lib/messaging/conversation-directory.ts @@ -0,0 +1,177 @@ +import { canonicalLocalId } from '../private-handles.ts'; +import { + privateSessionOwnership, + subscribePrivateSessionClose, + type PrivateSession +} from '../runtime/private-session.ts'; +import { + messageMetadataOwnership, + messageMetadataSnapshot, + rememberMessageConversation, + type MessageMetadata +} from '../persistence/message-metadata.ts'; +import type { AdmittedConversation } from './admit-conversation.ts'; +declare const directoryBrand: unique symbol; +export type ConversationDirectory = Readonly<{ [directoryBrand]: true }>; +export const CONVERSATION_DIRECTORY_CONTEXT = + 'harvestcircle_conversation_directory'; +type Resolution = + | Readonly<{ status: 'unavailable' }> + | Readonly<{ + status: 'resolved'; + owner: string; + peer: string; + conversationId: string; + href: string; + }>; +type Remembered = + | Awaited<ReturnType<typeof rememberMessageConversation>> + | Readonly<{ status: 'unavailable' }>; +type Controller = { + resolve(id: unknown): Promise<Resolution>; + remember(room: AdmittedConversation, review: unknown): Promise<Remembered>; + subscribe(listener: () => void): () => void; + close(): void; +}; +const directories = new WeakMap<ConversationDirectory, Controller>(); +const unavailable = (): Resolution => ({ status: 'unavailable' }); +// Pure syntax projection, never authorization. Owner/peer/product/body do not +// occur in the path; IDs from another browser may have no local mapping. +export function canonicalConversationHref(id: unknown): string | undefined { + const valid = canonicalLocalId(id); + return valid ? '/messages/' + valid : undefined; +} +export function captureConversationDirectory( + session: PrivateSession, + metadata: MessageMetadata, + review: unknown +): ConversationDirectory | undefined { + if ( + typeof window === 'undefined' || + review !== 'reviewed_conversation_directory' + ) + return; + const privateOwner = privateSessionOwnership(session), + localOwner = messageMetadataOwnership(metadata); + if ( + !privateOwner?.current() || + !localOwner?.current() || + privateOwner.owner !== localOwner.owner || + privateOwner.session !== localOwner.session + ) + return; + const original = privateOwner, + local = localOwner; + let closed = false, + off = () => {}; + const listeners = new Map<symbol, () => void>(); + const token = Object.freeze({}) as ConversationDirectory; + function close() { + if (closed) return; + closed = true; + off(); + directories.set(token, { + resolve: () => Promise.resolve(unavailable()), + remember: () => Promise.resolve({ status: 'unavailable' }), + subscribe: () => () => {}, + close: () => {} + }); + for (const listener of listeners.values()) { + try { + listener(); + } catch { + /* Presentation observer cannot retain private custody. */ + } + } + listeners.clear(); + } + function current() { + if (closed || !original.current() || !local.current()) { + close(); + return false; + } + return true; + } + directories.set(token, { + async resolve(id) { + const canonical = canonicalLocalId(id), + href = canonicalConversationHref(id); + if (!canonical || !href || !current()) return unavailable(); + try { + const snapshot = await messageMetadataSnapshot(metadata); + if ( + !current() || + snapshot.status !== 'ready' || + snapshot.owner !== original.owner + ) + return unavailable(); + const pair = snapshot.pairs.find((row) => row.id === canonical); + return pair + ? { + status: 'resolved', + owner: original.owner, + peer: pair.peer, + conversationId: canonical, + href + } + : unavailable(); + } catch { + return unavailable(); + } + }, + async remember(room, reviewed) { + if (!current()) return { status: 'unavailable' }; + const result = await rememberMessageConversation( + metadata, + room, + reviewed + ); + // A settled native write on an expired owner cannot disclose a room. + return current() ? result : { status: 'unavailable' }; + }, + subscribe(listener) { + if (!current()) return () => {}; + const key = Symbol(); + listeners.set(key, listener); + return () => { + listeners.delete(key); + }; + }, + close + }); + off = subscribePrivateSessionClose(session, close); + return current() ? token : undefined; +} +// Read-only lookup of genuine owner metadata. Returned peer is a local +// projection, never cryptographic room/reply permission or navigation effects. +export function resolveLocalConversation( + directory: ConversationDirectory, + id: unknown +): Promise<Resolution> { + return ( + directories.get(directory)?.resolve(id) ?? Promise.resolve(unavailable()) + ); +} +// Explicit admitted cached exchange only; copied snapshots/unknown GET cannot +// create a mapping. Product compose admission is wired by its later slice. +export function rememberAdmittedConversation( + directory: ConversationDirectory, + room: AdmittedConversation, + review: unknown +): Promise<Remembered> { + return ( + directories.get(directory)?.remember(room, review) ?? + Promise.resolve({ status: 'unavailable' }) + ); +} +export function subscribeConversationDirectory( + directory: ConversationDirectory, + listener: () => void +): () => void { + return directories.get(directory)?.subscribe(listener) ?? (() => {}); +} +export function closeConversationDirectory( + directory: ConversationDirectory +): void { + directories.get(directory)?.close(); +} diff --git a/web/src/lib/persistence/message-metadata.ts b/web/src/lib/persistence/message-metadata.ts @@ -93,10 +93,22 @@ type Display = }>; type Controller = { snapshot(): Promise<Snapshot>; - display(room: AdmittedConversation, review: unknown): Promise<Display>; + display( + room: AdmittedConversation, + review: unknown, + markRead?: boolean + ): Promise<Display>; messages(): ReturnType<typeof readUnlockedMessages>; close(): void; }; +const metadataOwnerships = new WeakMap< + MessageMetadata, + Readonly<{ + owner: string; + session: symbol; + current(): boolean; + }> +>(); const controllers = new WeakMap<MessageMetadata, Controller>(); const failed = (reason: Failure): Result<never> => ({ ok: false, reason }); function cipherRow( @@ -308,6 +320,7 @@ export function captureMessageMetadata( function close() { if (closed) return; closed = true; + metadataOwnerships.delete(token); off(); controllers.set(token, { snapshot: () => Promise.resolve<Snapshot>({ status: 'stopped' }), @@ -358,11 +371,15 @@ export function captureMessageMetadata( } async function display( room: AdmittedConversation, - review: unknown + review: unknown, + markRead = true ): Promise<Display> { if (!scope.current()) return { status: 'stopped' }; if ( - review !== 'displayed_message' || + review !== + (markRead + ? 'displayed_message' + : 'reviewed_admitted_conversation_navigation') || !unlockedConversationCurrent(unlocked, room) ) return { status: 'invalid' }; @@ -406,7 +423,7 @@ export function captureMessageMetadata( if (row.record.read && row.record.read.rumorHash !== data.rumorId) return { status: 'conflict' }; let pair = loaded.value.pairs.find((x) => x.peer === data.peer); - const existed = !!row.record.read && !!pair; + const existed = !!pair && (!markRead || !!row.record.read); if (!pair) { const id = newLocalId(); if (!id) return { status: 'unavailable' }; @@ -422,7 +439,7 @@ export function captureMessageMetadata( } const selected = pair; let nextWire = row.wire; - if (!row.record.read) { + if (markRead && !row.record.read) { const now = Date.now(); if ( safeUnsignedInteger(now) === undefined || @@ -539,6 +556,11 @@ export function captureMessageMetadata( : { status: 'closed', messages: [] }, close }); + metadataOwnerships.set(token, { + owner, + session: generation, + current: scope.current + }); off = subscribePrivateSessionClose(session, close); return scope.current() ? token : undefined; } @@ -568,3 +590,30 @@ export function markDisplayedMessage( Promise.resolve({ status: 'invalid' }) ); } + +// Genuine original metadata custody only. Detached snapshot pairs and owner +// strings cannot substitute for this token/generation when navigating. +export function messageMetadataOwnership(scope: MessageMetadata) { + const owned = metadataOwnerships.get(scope); + if (!owned?.current()) return; + // Detached observation: caller mutation cannot rebind the private stored + // owner/generation or original current check used by later admission. + return { + owner: owned.owner, + session: owned.session, + current: () => owned.current() + }; +} +// Admitted exchange may establish a room without treating navigation as read. +// It retains the original cached-room proof, owner lock, full-wire CAS and +// native completion/readback path; unknown route lookup never calls it. +export function rememberMessageConversation( + scope: MessageMetadata, + room: AdmittedConversation, + review: unknown +): Promise<Display> { + return ( + controllers.get(scope)?.display(room, review, false) ?? + Promise.resolve({ status: 'invalid' }) + ); +} diff --git a/web/src/routes/messages/[conversationId=local_id]/+page.svelte b/web/src/routes/messages/[conversationId=local_id]/+page.svelte @@ -1,5 +1,77 @@ <script lang="ts"> + import { getContext, onMount } from 'svelte'; + import { page } from '$app/state'; import AccountGate from '../../../lib/components/AccountGate.svelte'; + import { + CONVERSATION_DIRECTORY_CONTEXT, + resolveLocalConversation, + subscribeConversationDirectory, + type ConversationDirectory + } from '../../../lib/messaging/conversation-directory.ts'; + import { + IDENTITY_VIEW_CONTEXT, + identityViewMatchesOwner, + subscribeIdentityView, + type IdentityViewContext + } from '../../../lib/runtime/view-context.ts'; + const directory = getContext<ConversationDirectory | undefined>( + CONVERSATION_DIRECTORY_CONTEXT + ); + const identity = getContext<IdentityViewContext>(IDENTITY_VIEW_CONTEXT); + let resolved = $state(false), + mounted = $state(false); + let generation = 0; + async function refresh(conversationId = page.params.conversationId) { + const original = ++generation; + resolved = false; + if (!directory || !mounted) return; + const result = await resolveLocalConversation(directory, conversationId); + if (original !== generation || !mounted) return; + resolved = + result.status === 'resolved' && + identityViewMatchesOwner(identity, result.owner); + } + onMount(() => { + mounted = true; + const offIdentity = subscribeIdentityView(identity, () => { + void refresh(); + }); + const offDirectory = directory + ? subscribeConversationDirectory(directory, () => { + void refresh(); + }) + : () => {}; + void refresh(); + return () => { + mounted = false; + generation++; + offIdentity(); + offDirectory(); + }; + }); + $effect(() => { + const conversationId = page.params.conversationId; + if (mounted) void refresh(conversationId); + }); </script> -<AccountGate /> +<svelte:head> + {#if resolved} + <title>HarvestCircle</title><meta name="robots" content="noindex" /> + {/if} +</svelte:head> +{#if resolved} + <div class="page page--reading stack"> + <h1>Conversation</h1> + <p>Unlock message contents to read this conversation.</p> + </div> +{:else} + <AccountGate /> + <div class="page page--reading stack"> + <p> + This conversation is unavailable until it is unlocked in the matching + browser and account. + </p> + </div> +{/if} +<div class="page page--reading"><a href="/messages">Back to messages</a></div> diff --git a/web/tests/e2e/conversation-directory.spec.ts b/web/tests/e2e/conversation-directory.spec.ts @@ -0,0 +1,325 @@ +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/conversation-directory.ts'; +declare global { + interface Window { + hcp100: typeof Fixture; + hcp100Fixture: 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/conversation-directory.ts', import.meta.url) + ), + name: 'hcp100', + 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 }); + await page.evaluate(async () => { + window.hcp100Fixture = await window.hcp100.makeFixture(); + await window.hcp100Fixture.ready(); + }); +}); +test.afterEach(async ({ page }) => { + if (!page.isClosed()) + await page.evaluate(() => window.hcp100Fixture?.close()); +}); +const missing = '12345678-1234-4234-8234-123456789abc'; +test('directory capture and unknown GET are inert and never mark an unread rumor read', async ({ + page +}) => { + const r = await page.evaluate(async (id) => { + const f = window.hcp100Fixture; + const before = await f.rawMetadata(), + counts = f.counts(); + const captured = f.capture(); + const result = await f.resolve(id); + return { + captured, + result, + before, + after: await f.rawMetadata(), + counts, + afterCounts: f.counts(), + unread: await f.unread() + }; + }, missing); + expect(r.captured).toBe(true); + expect(r.result).toEqual({ status: 'unavailable' }); + expect(r.after).toEqual(r.before); + expect(r.afterCounts).toEqual(r.counts); + expect(r.unread).toMatchObject({ count: 1 }); +}); +test('only explicitly reviewed admitted exchange creates a random owner mapping without read or SDK effects', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp100Fixture; + f.capture(); + const counts = f.counts(); + const save = await f.remember(); + const raw = await f.rawMetadata(); + return { + save, + raw, + unread: await f.unread(), + counts, + afterCounts: f.counts() + }; + }); + expect(r.save).toMatchObject({ status: 'saved' }); + expect(r.raw.pairs).toHaveLength(1); + expect(r.unread).toMatchObject({ count: 1 }); + expect(r.afterCounts).toEqual(r.counts); + const row = r.raw.pairs[0] as { owner: string; id: string; wire: string }; + expect(row.id).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ + ); + expect(Object.keys(JSON.parse(row.wire) as object).sort()).toEqual( + ['schema', 'family', 'owner', 'id', 'peer'].sort() + ); +}); +test('known route lookup reads original owner metadata without new writes prompts or hidden publication', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp100Fixture; + f.capture(); + const saved = await f.remember(); + const raw = await f.rawMetadata(); + const id = (raw.pairs[0] as { id: string }).id; + const counts = f.counts(); + return { + saved, + id, + result: await f.resolve(id), + before: raw, + after: await f.rawMetadata(), + counts, + afterCounts: f.counts(), + owner: f.owner, + peer: f.peer + }; + }); + expect(r.result).toEqual({ + status: 'resolved', + owner: r.owner, + peer: r.peer, + conversationId: r.id, + href: '/messages/' + r.id + }); + expect(r.after).toEqual(r.before); + expect(r.afterCounts).toEqual(r.counts); +}); +test('two distinct actual encrypted product contexts share one participant-pair room', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp100Fixture; + f.capture(); + const first = await f.product('About carrots: two kilograms'), + second = await f.product('About apples: pickup tomorrow'); + return { + first, + second, + raw: await f.rawMetadata(), + messages: f.messages() + }; + }); + expect(r.first).toMatchObject({ status: 'saved' }); + expect(r.second).toMatchObject({ status: 'existing' }); + expect(r.raw.pairs).toHaveLength(1); + expect(r.messages).toMatchObject({ status: 'ready' }); + const messages = ( + r.messages as { messages: readonly { content: string }[] } + ).messages.map((x) => x.content); + expect(messages).toContain('About carrots: two kilograms'); + expect(messages).toContain('About apples: pickup tomorrow'); +}); +test('a genuine other account cannot infer an existing UUID peer or owner metadata', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp100Fixture; + f.capture(); + await f.remember(); + const raw = await f.rawMetadata(); + return await f.otherOwner((raw.pairs[0] as { id: string }).id); + }); + expect(r).toEqual({ status: 'unavailable' }); +}); +test('copied directory and copied room cannot authorize reading or mapping creation', async ({ + page +}) => { + const r = await page.evaluate(async (id) => { + const f = window.hcp100Fixture; + f.capture(); + const raw = await f.rawMetadata(); + return { + copied: await f.copied(id), + forged: await f.forgedRoom(), + before: raw, + after: await f.rawMetadata() + }; + }, missing); + expect(r.copied).toEqual({ status: 'unavailable' }); + expect(r.forged).toEqual({ status: 'invalid' }); + expect(r.after).toEqual(r.before); +}); +test('missing explicit mapping review never creates a substitute or marks read', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp100Fixture; + f.capture(); + const raw = await f.rawMetadata(); + return { + result: await f.remember('unreviewed'), + before: raw, + after: await f.rawMetadata(), + unread: await f.unread() + }; + }); + expect(r.result).toEqual({ status: 'invalid' }); + expect(r.after).toEqual(r.before); + expect(r.unread).toMatchObject({ count: 1 }); +}); +test('original owner logout invalidates lookup and admitted creation without returning metadata', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const f = window.hcp100Fixture; + f.capture(); + await f.remember(); + const raw = await f.rawMetadata(); + const id = (raw.pairs[0] as { id: string }).id; + f.disconnect(); + return { + resolve: await f.resolve(id), + remember: await f.remember(), + before: raw, + after: await f.rawMetadata() + }; + }); + expect(r.resolve).toEqual({ status: 'unavailable' }); + expect(r.remember).toEqual({ status: 'unavailable' }); + expect(r.after).toEqual(r.before); +}); +test('corrupt native mapping fails safely without peer metadata or automatic reset', async ({ + page +}) => { + const r = await page.evaluate(async (id) => { + const f = window.hcp100Fixture; + f.capture(); + await f.corruptPair(); + const raw = await f.rawMetadata(); + return { + resolve: await f.resolve(id), + before: raw, + after: await f.rawMetadata() + }; + }, missing); + expect(r.resolve).toEqual({ status: 'unavailable' }); + expect(r.after).toEqual(r.before); +}); +test('same handle in another actual browser storage context is unavailable without substitution', async ({ + page, + browser +}) => { + const id = await page.evaluate(async () => { + const f = window.hcp100Fixture; + f.capture(); + await f.remember(); + return ((await f.rawMetadata()).pairs[0] as { id: string }).id; + }); + const context = await browser.newContext(); + try { + const other = await context.newPage(); + await other.goto(server.url + '/search'); + await other.addScriptTag({ content: bundle }); + const r = await other.evaluate(async (id) => { + const f = await window.hcp100.makeFixture(); + try { + await f.ready(); + f.capture(); + return { result: await f.resolve(id), raw: await f.rawMetadata() }; + } finally { + f.close(); + } + }, id); + expect(r.result).toEqual({ status: 'unavailable' }); + expect(r.raw.pairs).toEqual([]); + } finally { + await context.close(); + } +}); +test('direct private reload has generic gates title noindex and a safe inbox link without recipient inference', async ({ + page +}) => { + await page.goto(server.url + '/messages/' + missing); + await expect( + page.getByRole('heading', { name: 'Connect or unlock' }) + ).toBeVisible(); + await expect( + page.getByRole('link', { name: 'Back to messages' }) + ).toHaveAttribute('href', '/messages'); + await expect(page).toHaveTitle('HarvestCircle'); + await expect(page.locator('meta[name="robots"]')).toHaveAttribute( + 'content', + 'noindex' + ); + await expect(page.locator('body')).not.toContainText( + 'Actual encrypted room fixture' + ); + expect(page.url()).toBe(server.url + '/messages/' + missing); +}); + +test('mutated detached observation cannot import original metadata into a genuine same-owner foreign generation', async ({ + page +}) => { + const r = await page.evaluate(() => + window.hcp100Fixture.mutatedGenerationObservation() + ); + console.log( + JSON.stringify({ + fixture: 'HCP100_GENUINE_OBSERVATION_REBIND', + sameOwner: r.sameOwner, + differentGeneration: r.differentGeneration, + foreignAccepted: r.foreignAccepted, + originalAccepted: r.originalAccepted, + rememberedStatus: r.remembered.status, + actualPairs: r.raw.pairs.length, + qualification: 'SOURCE_FIXTURE_NOT_OPERATOR_AUTHORITY' + }) + ); + expect(r.sameOwner).toBe(true); + expect(r.differentGeneration).toBe(true); + expect(r.foreignAccepted).toBe(false); + expect(r.originalAccepted).toBe(true); + expect(r.remembered).toEqual({ status: 'unavailable' }); + expect(r.raw.pairs).toEqual([]); +}); diff --git a/web/tests/e2e/harness/conversation-directory.ts b/web/tests/e2e/harness/conversation-directory.ts @@ -0,0 +1,127 @@ +import { messageMetadataOwnership } from '../../../src/lib/persistence/message-metadata.ts'; +import { privateSessionOwnership } from '../../../src/lib/runtime/private-session.ts'; +import { makeFixture as makeMetadataFixture } from './message-metadata.ts'; +import { + captureConversationDirectory, + resolveLocalConversation, + rememberAdmittedConversation, + closeConversationDirectory, + type ConversationDirectory +} from '../../../src/lib/messaging/conversation-directory.ts'; +import type { AdmittedConversation } from '../../../src/lib/messaging/admit-conversation.ts'; +export async function makeFixture(initialise = true) { + const f = await makeMetadataFixture('inbound', initialise); + let directory: ConversationDirectory | undefined; + let otherDirectory: ConversationDirectory | undefined; + return { + ...f, + async ready() { + if ((await f.unlock()) !== 'authenticated') + throw Error('no genuine nested admission'); + if ( + !f.admit('inbound') || + !f.captureCache() || + f.cache() !== 'added' || + !(await f.captureMetadata()) + ) + throw Error('no genuine original room/cache/metadata'); + }, + capture(review: unknown = 'reviewed_conversation_directory') { + const { privateSession, metadata } = f.navigationInputs(); + directory = + metadata && + captureConversationDirectory(privateSession, metadata, review); + return !!directory; + }, + resolve(id: unknown) { + return directory + ? resolveLocalConversation(directory, id) + : Promise.resolve({ status: 'unavailable' }); + }, + remember(review: unknown = 'reviewed_admitted_conversation_navigation') { + const { room } = f.navigationInputs(); + return directory && room + ? rememberAdmittedConversation(directory, room, review) + : Promise.resolve({ status: 'unavailable' }); + }, + forgedRoom() { + return directory + ? rememberAdmittedConversation( + directory, + {} as AdmittedConversation, + 'reviewed_admitted_conversation_navigation' + ) + : Promise.resolve({ status: 'unavailable' }); + }, + copied(id: unknown) { + return directory + ? resolveLocalConversation({ ...directory }, id) + : Promise.resolve({ status: 'unavailable' }); + }, + async otherOwner(id: unknown) { + const input = await f.otherNavigationInputs(); + if (!input.privateSession || !input.metadata) + throw Error('no genuine other owner metadata'); + otherDirectory = captureConversationDirectory( + input.privateSession, + input.metadata, + 'reviewed_conversation_directory' + ); + if (!otherDirectory) throw Error('no genuine other directory'); + return await resolveLocalConversation(otherDirectory, id); + }, + async mutatedGenerationObservation() { + const input = f.navigationInputs(); + if (!input.metadata || !input.room) + throw Error('no genuine original metadata/room'); + await f.otherGeneration(); + const foreign = f.foreignNavigationSession(); + if (!foreign) throw Error('no genuine second live same-owner session'); + const local = messageMetadataOwnership(input.metadata), + peer = privateSessionOwnership(foreign); + if (!local || !peer || !peer.current() || !local.current()) + throw Error('no genuine current observations'); + const sameOwner = local.owner === peer.owner, + differentGeneration = local.session !== peer.session; + Reflect.set(local, 'session', peer.session); + Reflect.set(local, 'current', () => true); + const imported = captureConversationDirectory( + foreign, + input.metadata, + 'reviewed_conversation_directory' + ); + const original = captureConversationDirectory( + input.privateSession, + input.metadata, + 'reviewed_conversation_directory' + ); + const remembered = imported + ? await rememberAdmittedConversation( + imported, + input.room, + 'reviewed_admitted_conversation_navigation' + ) + : { status: 'unavailable' }; + if (imported) closeConversationDirectory(imported); + if (original) closeConversationDirectory(original); + return { + sameOwner, + differentGeneration, + foreignAccepted: !!imported, + originalAccepted: !!original, + remembered, + raw: await f.rawMetadata() + }; + }, + async product(text: string) { + await f.anotherWrap(true, text); + if (f.cache() !== 'added') throw Error('no genuine second product rumor'); + return await this.remember(); + }, + close() { + if (directory) closeConversationDirectory(directory); + if (otherDirectory) closeConversationDirectory(otherDirectory); + f.close(); + } + }; +} diff --git a/web/tests/e2e/harness/message-metadata.ts b/web/tests/e2e/harness/message-metadata.ts @@ -154,6 +154,7 @@ export async function makeFixture( let rawCache: PrivateCacheScope | undefined; let database: BrowserDatabase | undefined, metadata: MessageMetadata | undefined; + let otherMetadata: MessageMetadata | undefined; let otherPrivateSession: Awaited<ReturnType<typeof createPrivateSession>>; let otherIdentity: ReturnType<typeof createIdentitySession> | undefined; return { @@ -415,6 +416,7 @@ export async function makeFixture( 'reviewed_local_message_metadata' ); if (!m) throw Error('no genuine other metadata'); + otherMetadata = m; return await messageMetadataSnapshot(m); }, async wrongGenerationMetadata() { @@ -523,11 +525,21 @@ export async function makeFixture( IDBDatabase.prototype.transaction = original; }; }, - async anotherWrap(lateOld = false) { + foreignNavigationSession() { + return otherPrivateSession; + }, + navigationInputs() { + return { privateSession, metadata, room }; + }, + async otherNavigationInputs() { + await this.otherOwnerMetadata(); + return { privateSession: otherPrivateSession, metadata: otherMetadata }; + }, + async anotherWrap(lateOld = false, productText?: string) { const selectedTemplate = { ...template, created_at: 1, - content: 'Late old actual encrypted rumor' + content: productText ?? 'Late old actual encrypted rumor' }, selectedRumor = lateOld ? { id: getEventHash(selectedTemplate), ...selectedTemplate } diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs @@ -46,6 +46,14 @@ import { auditOutput } from '../../tools/check-output.mjs'; source: '<script lang="ts">\n import Button from \'./primitives/Button.svelte\';\n</script>\n\n<svelte:head>\n <title>HarvestCircle</title>\n <meta name="robots" content="noindex" />\n</svelte:head>\n<div class="page page--reading stack">\n <h1>Connect or unlock</h1>\n <p>Connect an extension and unlock your account to continue.</p>\n <p class="notice">Account access is unavailable during development.</p>\n <div class="cluster">\n <Button label="Connect extension" disabled />\n <Button label="Unlock" disabled />\n </div>\n</div>\n', sha256: 'd5f90fb4b9af50037ed19dde626552e82df67017a39408bdbdeff1e712c10fbd' + }, + // Historical public-only variants must also restore their original private + // shell. The successor route imports owned identity context, which those + // historical roots never provided. Current actual-output cases retain it. + 'src/routes/messages/[conversationId=local_id]/+page.svelte': { + source: + '<script lang="ts">\n import AccountGate from \'../../../lib/components/AccountGate.svelte\';\n</script>\n\n<AccountGate />\n', + sha256: '93e21d162901af304f2a142acc7ddce87f7826421735d8a3af4ae281744ab3a0' } }; const base = await mkdtemp(path.join(os.tmpdir(), 'hc actual output ')); @@ -905,6 +913,42 @@ import { auditOutput } from '../../tools/check-output.mjs'; ); } for (const mutation of [ + 'permuted-edges', + 'extra-edge', + 'duplicate-edge' + ]) { + await check( + 'product compiler dependency order: ' + 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 find = (/** @type {string} */ name) => { + const row = Object.entries(manifest).find( + ([, v]) => v.name === name + ); + assert.ok(row); + return row; + }; + for (const name of ['nodes/7', 'nodes/9']) { + const row = find(name)[1]; + row.imports = [...row.imports].reverse(); + if (mutation === 'extra-edge') + row.imports = row.imports.concat(find('AccountGate')[0]); + if (mutation === 'duplicate-edge') + row.imports = row.imports.concat(row.imports[0]); + } + await writeFile(file, JSON.stringify(manifest)); + if (mutation === 'permuted-edges') + assert.equal((await f.audit()).length, 48); + else await assert.rejects(f.audit, /compiler|references/); + } + ); + } + for (const mutation of [ 'missing-publishers', 'publisher-budget', 'publisher-shared', diff --git a/web/tests/unit/conversation-directory.test.ts b/web/tests/unit/conversation-directory.test.ts @@ -0,0 +1,55 @@ +import { test, expect } from 'vitest'; +import { + canonicalConversationHref, + captureConversationDirectory, + resolveLocalConversation, + rememberAdmittedConversation, + type ConversationDirectory +} from '../../src/lib/messaging/conversation-directory.ts'; +import type { PrivateSession } from '../../src/lib/runtime/private-session.ts'; +import type { MessageMetadata } from '../../src/lib/persistence/message-metadata.ts'; +import type { AdmittedConversation } from '../../src/lib/messaging/admit-conversation.ts'; +const id = '12345678-1234-4234-8234-123456789abc'; +test('only the canonical random UUID occurs in the private URL', () => + expect(canonicalConversationHref(id)).toBe('/messages/' + id)); +test('uppercase UUID is not normalized into a private lookup', () => + expect(canonicalConversationHref(id.toUpperCase())).toBeUndefined()); +test('a nonrandom UUID does not become a conversation handle', () => + expect( + canonicalConversationHref(id.replace('-4234-', '-1234-')) + ).toBeUndefined()); +test('peer keys and product coordinates never form conversation paths', () => { + for (const value of ['a'.repeat(64), 'naddr1product', '/messages/' + id]) + expect(canonicalConversationHref(value)).toBeUndefined(); +}); +test('query fragments and malformed tails are rejected in their entirety', () => { + for (const value of [ + id + '?peer=' + 'b'.repeat(64), + id + '#context', + id + '/', + null, + {} + ]) + expect(canonicalConversationHref(value)).toBeUndefined(); +}); +test('SSR and scalar/copy ownership cannot construct a private directory', () => { + expect( + captureConversationDirectory( + {} as PrivateSession, + {} as MessageMetadata, + 'reviewed_conversation_directory' + ) + ).toBeUndefined(); +}); +test('copied directory lookup is safely unavailable without inferred metadata', async () => + expect( + await resolveLocalConversation({} as ConversationDirectory, id) + ).toEqual({ status: 'unavailable' })); +test('unknown token and copied room cannot create a substitute conversation', async () => + expect( + await rememberAdmittedConversation( + {} as ConversationDirectory, + {} as AdmittedConversation, + 'reviewed_admitted_conversation_navigation' + ) + ).toEqual({ status: 'unavailable' })); diff --git a/web/tests/unit/route-inventory.test.ts b/web/tests/unit/route-inventory.test.ts @@ -53,19 +53,19 @@ describe('approved route inventory', () => { }); describe('thin protected route SSR', () => { - for (const [name, component] of Object.entries({ - Sell, - Selling, - Draft, - Edit, - Messages, - Conversation + for (const [name, renderComponent] of Object.entries({ + Sell: () => render(Sell), + Selling: () => render(Selling), + Draft: () => render(Draft), + Edit: () => render(Edit), + Messages: () => render(Messages), + Conversation: () => render(Conversation) })) { it( name + ' renders only a generic unavailable connection/unlock gate without browser effects', () => { - const output = render(component); + const output = renderComponent(); expect(output.head).toContain('<title>HarvestCircle</title>'); expect(output.head).toMatch(/name="robots" content="noindex"/); expect(output.body).toContain('Connect or unlock'); diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs @@ -985,7 +985,7 @@ export async function auditOutput(webDirectory) { 'Invalid owned product publisher compiler dependencies' ); equal( - entry('nodes/7')[1].imports, + entry('nodes/7')[1].imports?.toSorted(), (hasInboxSetup ? [ 'public-key', @@ -1021,11 +1021,13 @@ export async function auditOutput(webDirectory) { 'Button', 'publishers' ] - ).map((name) => entry(name)[0]), + ) + .map((name) => entry(name)[0]) + .sort(), 'Invalid owned product compiler dependencies' ); equal( - entry('nodes/9')[1].imports, + entry('nodes/9')[1].imports?.toSorted(), (hasInboxSetup ? [ 'references', @@ -1064,7 +1066,9 @@ export async function auditOutput(webDirectory) { 'routes', 'publishers' ] - ).map((name) => entry(name)[0]), + ) + .map((name) => entry(name)[0]) + .sort(), 'Invalid owned search product compiler dependencies' ); if (