app

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

commit 8b0b6195cbe3822d9b4d9ebd93c9c3fb696892e8
parent 2ee2c20e9404425dacccd08e312327191aad4458
Author: triesap <tyson@radroots.org>
Date:   Wed,  7 Oct 2026 07:56:44 +0000

messages: prepare explicit inbox preference changes durably (HCP-065)

- Preview exact replacements with current owner, known base and fixed targets.
- Preserve existing entries and require explicit removal of unsupported extras.
- Capture consent in typed preference operations under owner locks and quota.
- Verify head conflicts, original replay and real IndexedDB preparation.

Diffstat:
Aweb/src/lib/messaging/inbox-setup.ts | 334+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/persistence/inbox-preference-operations.ts | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/harness/inbox-setup.ts | 172+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/inbox-setup.spec.ts | 269+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/inbox-setup.test.ts | 299+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 1133 insertions(+), 0 deletions(-)

diff --git a/web/src/lib/messaging/inbox-setup.ts b/web/src/lib/messaging/inbox-setup.ts @@ -0,0 +1,334 @@ +import { exactLocalFields } from '../contracts/local-records.ts'; +import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts'; +import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts'; +import { inspectLocalTemplate } from '../nostr/local-template.ts'; +import { + inboxPreferenceSnapshot, + inboxPreferenceWire +} from '../nostr/inbox-preferences.ts'; +import { + canonicalRelayOrigin, + readRelayPolicy, + publicRelayTargets, + inboxRelayTargets, + type RelayPolicy +} from '../config/relays.ts'; +import { + identityMessagingOwnership, + type IdentitySession +} from '../runtime/identity-session.ts'; +import { + decodePublicRecord, + type PublicRecordHandle +} from '../persistence/records.ts'; +import { canonicalLocalId } from '../private-handles.ts'; +import { + inboxResolutionSnapshot, + inboxResolverCurrentAfterSample, + type InboxResolver +} from './resolve-inbox.ts'; + +declare const reviewBrand: unique symbol; +export type InboxSetupReview = Readonly<{ [reviewBrand]: true }>; +type Preview = { + author: string; + originalWire: string | null; + baseId: string | null; + wire: string; + hash: string; + policyFingerprint: string; + selectedInboxes: string[]; + destinations: string[]; + removedTagIndices: number[]; + removedExtraFields: string[]; + globalEffect: string; +}; +type Saved = Readonly<{ + identity: IdentitySession; + session: symbol; + policy: RelayPolicy; + previewWire: string; +}>; +const reviews = new WeakMap<InboxSetupReview, Saved>(); +const globalEffect = + 'This replaces your public inbox preference for other clients. Relay acceptance and readback are still required; this review does not publish.'; +function base(resolver: InboxResolver, policy: RelayPolicy, owner: string) { + const resolution = inboxResolutionSnapshot(resolver), + discovery = publicRelayTargets(policy, 'read'); + if ( + resolution.author !== owner || + resolution.coverage !== 'bounded-eose' || + resolution.status === 'inconclusive' || + discovery.length === 0 || + discovery.length !== resolution.sources.length || + !discovery.every((origin) => + resolution.sources.some( + (row) => row.source === origin && row.state === 'eose' + ) + ) + ) + return undefined; + if (resolution.status === 'missing') + return !resolution.head && !resolution.knownBase + ? { wire: null, id: null, createdAt: undefined } + : undefined; + const head = resolution.head && inboxPreferenceSnapshot(resolution.head), + wire = resolution.head && inboxPreferenceWire(resolution.head); + return head && + wire && + head.author === owner && + head.id === resolution.knownBase?.id + ? { wire, id: head.id, createdAt: head.createdAt } + : undefined; +} +// Explicit source review only. The clock is an internal observation port like +// the resolver clock; production uses actual wall time, tests control it. No +// caller event extras enter the canonical signing contract implicitly. +export async function reviewInboxSetup( + identity: IdentitySession, + resolver: InboxResolver, + policy: RelayPolicy, + raw: unknown, + observeNow: () => number = () => Math.floor(Date.now() / 1000) +): Promise< + | Readonly<{ status: 'review'; review: InboxSetupReview }> + | Readonly<{ status: 'blocked'; reason: string }> +> { + try { + const capture = identityMessagingOwnership(identity), + manifest = readRelayPolicy(policy); + if ( + !capture || + !capture.current() || + !manifest.messagingEnabled || + !manifest.postingEnabled + ) + return { status: 'blocked', reason: 'unavailable' }; + const previous = base(resolver, policy, capture.owner); + if (!previous || typeof raw !== 'string' || !boundedUtf8(raw, 65536)) + return { status: 'blocked', reason: 'unavailable' }; + const input: unknown = JSON.parse(raw); + if ( + !exactLocalFields(input, [ + 'selectedInboxes', + 'removeTagIndices', + 'removeExtraFields', + 'createdAt' + ]) || + !Array.isArray(input.selectedInboxes) || + input.selectedInboxes.length < 1 || + input.selectedInboxes.length > 3 || + !Array.isArray(input.removeTagIndices) || + !Array.isArray(input.removeExtraFields) + ) + return { status: 'blocked', reason: 'invalid_selection' }; + const time = safeUnsignedInteger(input.createdAt), + now = safeUnsignedInteger(observeNow()); + if ( + time === undefined || + now !== time || + (previous.createdAt !== undefined && time <= previous.createdAt) + ) + return { status: 'blocked', reason: 'clock_conflict' }; + const selected: string[] = []; + function appendSelected(value: string) { + selected.push(value); + } + for (const value of input.selectedInboxes as unknown[]) { + if ( + typeof value !== 'string' || + selected.includes(value) || + !inboxRelayTargets(policy, [value], 'read').includes(value) || + !inboxRelayTargets(policy, [value], 'write').includes(value) + ) + return { status: 'blocked', reason: 'invalid_selection' }; + appendSelected(value); + } + const old = + previous.wire === null + ? undefined + : (JSON.parse(previous.wire) as { tags: string[][]; content: string }); + const tags = old?.tags ?? []; + const removeTags: number[] = [], + removeFields: string[] = []; + function appendTagIndex(value: number) { + removeTags.push(value); + } + function appendField(value: string) { + removeFields.push(value); + } + if ( + input.removeTagIndices.length > tags.length || + input.removeExtraFields.length > 64 + ) + return { status: 'blocked', reason: 'invalid_selection' }; + for (const index of input.removeTagIndices as unknown[]) { + if ( + typeof index !== 'number' || + safeUnsignedInteger(index) === undefined || + index >= tags.length || + removeTags.includes(index) + ) + return { status: 'blocked', reason: 'invalid_selection' }; + appendTagIndex(index); + } + const standard = [ + 'id', + 'sig', + 'pubkey', + 'kind', + 'created_at', + 'tags', + 'content' + ]; + const extras: string[] = []; + function appendExtra(value: string) { + extras.push(value); + } + if (old) + for (const key in old) if (!standard.includes(key)) appendExtra(key); + for (const key of input.removeExtraFields as unknown[]) { + if ( + typeof key !== 'string' || + !extras.includes(key) || + removeFields.includes(key) + ) + return { status: 'blocked', reason: 'invalid_selection' }; + appendField(key); + } + // Unsigned extra fields cannot survive the existing exact five-field signer. + // Block until the owner chooses every removal; retaining only the old source + // would not constitute preservation in the outgoing replacement. + if (extras.some((key) => !removeFields.includes(key))) + return { status: 'blocked', reason: 'unsupported_extra_fields' }; + let nextTags = tags.filter((_tag, index) => !removeTags.includes(index)); + for (const origin of selected) + if ( + !nextTags.some( + (tag) => tag.length === 2 && tag[0] === 'relay' && tag[1] === origin + ) + ) + nextTags = nextTags.concat([['relay', origin]]); + // Reuse the public preference grammar without signing a synthetic event: + // every retained relay tag must remain a canonical advertised origin. Other + // tags/content/order/duplicates survive unchanged, including >3 advertisements. + if ( + nextTags.some( + (tag) => + tag[0] === 'relay' && + (tag.length !== 2 || !canonicalRelayOrigin(tag[1])) + ) + ) + return { status: 'blocked', reason: 'unsupported_profile' }; + const wire = JSON.stringify({ + pubkey: capture.owner, + kind: 10050, + created_at: time, + tags: nextTags, + content: old?.content ?? '' + }); + const template = inspectLocalTemplate(wire, capture.owner, 10050), + destinations = publicRelayTargets(policy, 'write'); + if (!template || destinations.length === 0) + return { status: 'blocked', reason: 'unsupported_profile' }; + const digest = await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(JSON.stringify(manifest)) + ); + const policyFingerprint = Array.from(new Uint8Array(digest), (value) => + value.toString(16).padStart(2, '0') + ).join(''); + if (!capture.current() || !inboxResolverCurrentAfterSample(resolver)) + return { status: 'blocked', reason: 'unavailable' }; + const preview: Preview = { + author: capture.owner, + originalWire: previous.wire, + baseId: previous.id, + wire, + hash: template.hash, + policyFingerprint, + selectedInboxes: selected, + destinations: destinations.slice(), + removedTagIndices: removeTags, + removedExtraFields: removeFields, + globalEffect + }; + const review = Object.freeze({}) as InboxSetupReview; + reviews.set(review, { + identity, + session: capture.session, + policy, + previewWire: JSON.stringify(preview) + }); + return { status: 'review', review }; + } catch { + return { status: 'blocked', reason: 'unavailable' }; + } +} +export function inboxSetupPreview( + review: InboxSetupReview +): Preview | undefined { + const saved = reviews.get(review); + return saved ? (JSON.parse(saved.previewWire) as Preview) : undefined; +} +export type InboxSetupCapture = + | Readonly<{ status: 'captured'; record: PublicRecordHandle; owner: string }> + | Readonly<{ status: 'invalid' | 'conflict' | 'unavailable' }>; +// No effect permission: this exact reviewed record must be durably admitted +// before later signing/publication. Fresh lookup is bounded knowledge, never CAS. +export function captureInboxSetup( + review: InboxSetupReview, + resolver: InboxResolver, + command: unknown, + consent: unknown +): InboxSetupCapture { + try { + const saved = reviews.get(review), + id = canonicalLocalId(command); + if (!saved || !id || consent !== 'reviewed_global_inbox_replacement') + return { status: 'invalid' }; + const preview = JSON.parse(saved.previewWire) as Preview, + capture = identityMessagingOwnership(saved.identity); + if ( + !capture || + capture.owner !== preview.author || + capture.session !== saved.session + ) + return { status: 'unavailable' }; + const current = base(resolver, saved.policy, preview.author); + if (!current) return { status: 'unavailable' }; + if (current.id !== preview.baseId || current.wire !== preview.originalWire) + return { status: 'conflict' }; + const record = decodePublicRecord( + JSON.stringify({ + schema: 1, + family: 'preference_operation', + owner: preview.author, + id, + revision: 0, + source: { type: 'inbox_head', wire: preview.originalWire }, + consent: 'explicit_review', + capture: { + kind: 10050, + wire: preview.wire, + hash: preview.hash, + targets: preview.destinations, + policyFingerprint: preview.policyFingerprint + }, + artifact: null, + receipts: [] + }), + preview.author, + id + ); + if ( + !record.ok || + !capture.current() || + !inboxResolverCurrentAfterSample(resolver) + ) + return { status: 'unavailable' }; + return { status: 'captured', record: record.value, owner: preview.author }; + } catch { + return { status: 'unavailable' }; + } +} diff --git a/web/src/lib/persistence/inbox-preference-operations.ts b/web/src/lib/persistence/inbox-preference-operations.ts @@ -0,0 +1,59 @@ +import { + captureInboxSetup, + type InboxSetupReview +} from '../messaging/inbox-setup.ts'; +import type { InboxResolver } from '../messaging/resolve-inbox.ts'; +import type { PublicRecordHandle } from './records.ts'; +import { + claimPublicOperation, + publicQuotaOwner, + type PublicQuotaRepository, + type PublicQuotaFailure +} from './quota.ts'; +export type InboxPreferenceSave = + | Readonly<{ status: 'saved' | 'existing'; record: PublicRecordHandle }> + | Readonly<{ + status: + 'invalid' | 'unavailable' | 'conflict' | 'busy' | PublicQuotaFailure; + }>; +// Preparation only; exact preference store/CAS/quota remains in its existing +// owner. No extension or network await occurs inside the short transaction. +export async function saveInboxPreferenceOperation( + repository: PublicQuotaRepository, + review: InboxSetupReview, + resolver: InboxResolver, + command: unknown, + consent: unknown +): Promise<InboxPreferenceSave> { + try { + const initial = captureInboxSetup(review, resolver, command, consent); + if (initial.status !== 'captured') return initial; + if (publicQuotaOwner(repository) !== initial.owner) + return { status: 'invalid_scope' }; + if (typeof window === 'undefined' || !navigator.locks?.request) + return { status: 'unavailable' }; + return await navigator.locks.request( + 'harvestcircle:owner:' + initial.owner, + { mode: 'exclusive', ifAvailable: true }, + async (lock): Promise<InboxPreferenceSave> => { + if (!lock) return { status: 'busy' }; + const fresh = captureInboxSetup(review, resolver, command, consent); + if (fresh.status !== 'captured') return fresh; + if (publicQuotaOwner(repository) !== fresh.owner) + return { status: 'invalid_scope' }; + const claimed = await claimPublicOperation( + repository, + command, + fresh.record + ); + if (!claimed.ok) return { status: claimed.reason }; + return { + status: claimed.value.state === 'created' ? 'saved' : 'existing', + record: claimed.value.record + }; + } + ); + } catch { + return { status: 'unavailable' }; + } +} diff --git a/web/tests/e2e/harness/inbox-setup.ts b/web/tests/e2e/harness/inbox-setup.ts @@ -0,0 +1,172 @@ +import { finalizeEvent } from 'applesauce-core/helpers'; +import { validateRelayPolicy } from '../../../src/lib/config/relays.ts'; +import { + createPublicScheduler, + createPublicRun, + openInboxRequest, + closePublicScheduler +} from '../../../src/lib/nostr/request-scope.ts'; +import { createInboxResolver } from '../../../src/lib/messaging/resolve-inbox.ts'; +import { + createIdentitySession, + connectIdentity, + probeIdentityMessaging, + disconnectIdentity +} from '../../../src/lib/runtime/identity-session.ts'; +export { + reviewInboxSetup, + inboxSetupPreview, + captureInboxSetup +} from '../../../src/lib/messaging/inbox-setup.ts'; +export { saveInboxPreferenceOperation } from '../../../src/lib/persistence/inbox-preference-operations.ts'; +export { + openBrowserDatabase, + closeBrowserDatabase +} from '../../../src/lib/persistence/database.ts'; +export { + createPublicQuotaRepository, + inspectPublicStorage, + publicInventorySnapshot +} from '../../../src/lib/persistence/quota.ts'; +export { + publicRecordSnapshot, + publicRecordWire +} from '../../../src/lib/persistence/records.ts'; +export const discovery = 'wss://discovery.example.org', + inbox = 'wss://inbox.example.org'; +export function fixturePolicy() { + return validateRelayPolicy( + JSON.stringify({ + schemaVersion: 1, + public: [{ origin: discovery, read: true, write: true, nip50: false }], + inbox: [{ origin: inbox, read: true, write: true }], + postingEnabled: true, + messagingEnabled: true, + operatorDenylist: [] + }) + )!; +} +// Actual SDK identity/discovery ownership with controlled transport/echo provider; +// source fixture only, never a real extension, inbox or retention qualification. +export async function makeSetupFixture( + tags: string[][] = [ + ['relay', 'wss://old.example.org'], + ['unknown', 'keep'], + ['unknown', 'keep'] + ], + extra: Record<string, unknown> = {}, + missing = false +) { + const key = crypto.getRandomValues(new Uint8Array(32)); + const event = finalizeEvent( + { kind: 10050, created_at: 100, tags, content: 'existing public content' }, + key + ); + const newerEvent = finalizeEvent( + { kind: 10050, created_at: 101, tags, content: 'concurrent preference' }, + key + ); + key.fill(0); + const identity = createIdentitySession(), + prior = Object.getOwnPropertyDescriptor(globalThis, 'window'); + const made = typeof window === 'undefined'; + if (made) + Object.defineProperty(globalThis, 'window', { + configurable: true, + value: {} + }); + const priorProvider = Object.getOwnPropertyDescriptor(window, 'nostr'); + let signs = 0, + keys = 0; + Object.defineProperty(window, 'nostr', { + configurable: true, + value: { + getPublicKey: () => { + keys++; + return Promise.resolve(event.pubkey); + }, + signEvent: () => { + signs++; + return Promise.reject(new Error('unexpected preference signature')); + }, + nip44: { + encrypt: (_peer: string, text: string) => + Promise.resolve('fixture:' + text), + decrypt: (_peer: string, text: string) => Promise.resolve(text.slice(8)) + } + } + }); + await connectIdentity(identity); + await probeIdentityMessaging(identity, 'reviewed_self_copy'); + const schedulers: ReturnType<typeof createPublicScheduler>[] = []; + function resolve( + currentEvent: typeof event | null = missing ? null : { ...event, ...extra }, + complete = true + ) { + let current = true; + const scheduler = createPublicScheduler({ + now: () => 0, + schedule: () => () => {} + }); + schedulers.push(scheduler); + const run = createPublicRun(scheduler, fixturePolicy()); + const resolver = createInboxResolver( + run, + event.pubkey, + (next) => + openInboxRequest( + run, + event.pubkey, + (sink) => { + if (currentEvent !== null) + sink({ + type: 'EVENT', + from: discovery, + id: 'fixture', + event: currentEvent + }); + if (complete) + sink({ type: 'EOSE', from: discovery, id: 'fixture' }); + return () => {}; + }, + next + ), + () => current + ); + return { + resolver, + stale: () => { + current = false; + } + }; + } + const own = resolve(); + return { + identity, + owner: event.pubkey, + event, + newerEvent, + own, + resolve, + counts: () => ({ signs, keys }), + close() { + disconnectIdentity(identity); + for (const s of schedulers) closePublicScheduler(s); + if (priorProvider) Object.defineProperty(window, 'nostr', priorProvider); + else Reflect.deleteProperty(window, 'nostr'); + if (made) { + if (prior) Object.defineProperty(globalThis, 'window', prior); + else Reflect.deleteProperty(globalThis, 'window'); + } + } + }; +} +export function setupInput(overrides: Record<string, unknown> = {}) { + return JSON.stringify({ + selectedInboxes: [inbox], + removeTagIndices: [], + removeExtraFields: [], + createdAt: 101, + ...overrides + }); +} diff --git a/web/tests/e2e/inbox-setup.spec.ts b/web/tests/e2e/inbox-setup.spec.ts @@ -0,0 +1,269 @@ +import { test, expect } 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 Setup from './harness/inbox-setup.ts'; +import type { BrowserDatabase } from '../../src/lib/persistence/database.ts'; +import type { PublicQuotaRepository } from '../../src/lib/persistence/quota.ts'; +import type { InboxSetupReview } from '../../src/lib/messaging/inbox-setup.ts'; +declare global { + interface Window { + hcp065: typeof Setup; + hcp065Fixture: Awaited<ReturnType<typeof Setup.makeSetupFixture>>; + hcp065Db: BrowserDatabase; + hcp065Repo: PublicQuotaRepository; + hcp065Review: InboxSetupReview; + } +} +let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string; +test.beforeAll(async () => { + server = await createStaticHarness(); + const entry = fileURLToPath( + new URL('./harness/inbox-setup.ts', import.meta.url) + ); + const result = await build({ + configFile: false, + logLevel: 'silent', + build: { + write: false, + minify: false, + lib: { entry, name: 'hcp065', formats: ['iife'] } + } + }); + const output = Array.isArray(result) ? result[0] : result; + if (!('output' in output)) throw new Error('missing fixture output'); + const chunks = output.output.filter((x) => x.type === 'chunk'); + expect(chunks).toHaveLength(1); + bundle = chunks[0].code; + console.log( + JSON.stringify({ + fixture: 'HCP065_ACTUAL_SDK_OWNERS_AND_REAL_IDB_WEB_LOCKS', + bundleSha256: createHash('sha256').update(bundle).digest('hex'), + moduleIds: Object.keys(chunks[0].modules), + qualification: + 'controlled local Chromium/source only; no real extension/relay/client/retention qualification' + }) + ); +}); +test.afterAll(async () => server.close()); +test.beforeEach(async ({ page }) => { + await page.goto(server.url + '/search'); + await page.addScriptTag({ content: bundle }); + await page.evaluate(async () => { + const s = window.hcp065; + window.hcp065Fixture = await s.makeSetupFixture(); + const opened = await s.openBrowserDatabase(); + if (opened.state !== 'ready') throw new Error(opened.reason); + window.hcp065Db = opened.owner; + const repo = s.createPublicQuotaRepository( + opened.owner, + window.hcp065Fixture.owner + ); + if (!repo) throw new Error('missing owner repository'); + window.hcp065Repo = repo; + }); +}); +test.afterEach(async ({ page }) => { + if (!page.isClosed()) + await page.evaluate(() => { + window.hcp065Fixture?.close(); + if (window.hcp065Db) window.hcp065.closeBrowserDatabase(window.hcp065Db); + }); +}); +test('Connect and review alone write nothing; explicit durable capture equals the exact preview', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const s = window.hcp065, + f = window.hcp065Fixture, + review = await s.reviewInboxSetup( + f.identity, + f.own.resolver, + s.fixturePolicy(), + s.setupInput(), + () => 101 + ); + if (review.status !== 'review') throw new Error(review.reason); + const preview = s.inboxSetupPreview(review.review)!, + before = await s.inspectPublicStorage(window.hcp065Repo); + const count = before.ok + ? s.publicInventorySnapshot(window.hcp065Repo, before.value)?.rows.length + : -1; + const id = crypto.randomUUID(), + saved = await s.saveInboxPreferenceOperation( + window.hcp065Repo, + review.review, + f.own.resolver, + id, + 'reviewed_global_inbox_replacement' + ); + return { + count, + preview, + status: saved.status, + row: + saved.status === 'saved' + ? s.publicRecordSnapshot(saved.record, f.owner, id) + : null, + counts: f.counts() + }; + }); + expect(r.count).toBe(0); + expect(r.status).toBe('saved'); + expect(r.row?.family).toBe('preference_operation'); + if (r.row?.family === 'preference_operation') { + expect(r.row.capture.wire).toBe(r.preview.wire); + expect(r.row.source.wire).toBe(r.preview.originalWire); + expect(r.row.capture.targets).toEqual(r.preview.destinations); + expect(r.row.artifact).toBeNull(); + expect(r.row.receipts).toEqual([]); + } + expect(r.counts.signs).toBe(0); +}); +test('same command replay retains original; conflicting preview never overwrites it', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const s = window.hcp065, + f = window.hcp065Fixture, + id = crypto.randomUUID(); + const first = await s.reviewInboxSetup( + f.identity, + f.own.resolver, + s.fixturePolicy(), + s.setupInput(), + () => 101 + ); + if (first.status !== 'review') throw new Error(first.reason); + const a = await s.saveInboxPreferenceOperation( + window.hcp065Repo, + first.review, + f.own.resolver, + id, + 'reviewed_global_inbox_replacement' + ), + b = await s.saveInboxPreferenceOperation( + window.hcp065Repo, + first.review, + f.own.resolver, + id, + 'reviewed_global_inbox_replacement' + ); + const different = await s.reviewInboxSetup( + f.identity, + f.own.resolver, + s.fixturePolicy(), + s.setupInput({ createdAt: 102 }), + () => 102 + ); + if (different.status !== 'review') throw new Error(different.reason); + const c = await s.saveInboxPreferenceOperation( + window.hcp065Repo, + different.review, + f.own.resolver, + id, + 'reviewed_global_inbox_replacement' + ); + return { + a: a.status, + b: b.status, + c: c.status, + original: + a.status === 'saved' ? s.publicRecordWire(a.record, f.owner, id) : null, + retained: + b.status === 'existing' + ? s.publicRecordWire(b.record, f.owner, id) + : null, + counts: f.counts() + }; + }); + expect(r.a).toBe('saved'); + expect(r.b).toBe('existing'); + expect(r.c).toBe('conflict'); + expect(r.retained).toBe(r.original); + expect(r.counts.signs).toBe(0); +}); +test('changed known head prevents durable admission before any extension or publication effect', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const s = window.hcp065, + f = window.hcp065Fixture, + r = await s.reviewInboxSetup( + f.identity, + f.own.resolver, + s.fixturePolicy(), + s.setupInput(), + () => 101 + ); + if (r.status !== 'review') throw new Error(r.reason); + const fresh = f.resolve(f.newerEvent); + const saved = await s.saveInboxPreferenceOperation( + window.hcp065Repo, + r.review, + fresh.resolver, + crypto.randomUUID(), + 'reviewed_global_inbox_replacement' + ); + const inv = await s.inspectPublicStorage(window.hcp065Repo); + return { + status: saved.status, + count: inv.ok + ? s.publicInventorySnapshot(window.hcp065Repo, inv.value)?.rows.length + : -1, + counts: f.counts() + }; + }); + expect(r.status).toBe('conflict'); + expect(r.count).toBe(0); + expect(r.counts.signs).toBe(0); +}); +test('missing Web Locks or consent keeps browse usable and creates no preference', async ({ + page +}) => { + const r = await page.evaluate(async () => { + const s = window.hcp065, + f = window.hcp065Fixture, + r = await s.reviewInboxSetup( + f.identity, + f.own.resolver, + s.fixturePolicy(), + s.setupInput(), + () => 101 + ); + if (r.status !== 'review') throw new Error(r.reason); + const denied = await s.saveInboxPreferenceOperation( + window.hcp065Repo, + r.review, + f.own.resolver, + crypto.randomUUID(), + 'connect' + ); + Object.defineProperty(navigator, 'locks', { + configurable: true, + value: undefined + }); + const unsupported = await s.saveInboxPreferenceOperation( + window.hcp065Repo, + r.review, + f.own.resolver, + crypto.randomUUID(), + 'reviewed_global_inbox_replacement' + ); + const inv = await s.inspectPublicStorage(window.hcp065Repo); + return { + denied: denied.status, + unsupported: unsupported.status, + count: inv.ok + ? s.publicInventorySnapshot(window.hcp065Repo, inv.value)?.rows.length + : -1 + }; + }); + expect(r).toEqual({ + denied: 'invalid', + unsupported: 'unavailable', + count: 0 + }); + expect(page.url()).toContain('/search'); +}); diff --git a/web/tests/unit/inbox-setup.test.ts b/web/tests/unit/inbox-setup.test.ts @@ -0,0 +1,299 @@ +import { it, expect } from 'vitest'; +import { + makeSetupFixture, + fixturePolicy, + setupInput, + inbox, + discovery, + reviewInboxSetup, + inboxSetupPreview, + captureInboxSetup, + publicRecordSnapshot +} from '../e2e/harness/inbox-setup.ts'; +import { createIdentitySession } from '../../src/lib/runtime/identity-session.ts'; +import type { InboxSetupReview } from '../../src/lib/messaging/inbox-setup.ts'; +async function reviewed( + f: Awaited<ReturnType<typeof makeSetupFixture>>, + input = setupInput() +) { + const r = await reviewInboxSetup( + f.identity, + f.own.resolver, + fixturePolicy(), + input, + () => 101 + ); + if (r.status !== 'review') throw new Error(r.reason); + return r.review; +} +it('Connect alone creates no preference; exact preview captures preserved duplicate and unknown entries', async () => { + const f = await makeSetupFixture(); + try { + const before = f.counts(), + review = await reviewed(f), + view = inboxSetupPreview(review)!; + expect(view.author).toBe(f.owner); + expect(view.destinations).toEqual([discovery]); + expect(view.selectedInboxes).toEqual([inbox]); + expect((JSON.parse(view.wire) as { tags: string[][] }).tags).toEqual([ + ...f.event.tags, + ['relay', inbox] + ]); + expect((JSON.parse(view.wire) as { content: string }).content).toBe( + f.event.content + ); + expect(view.globalEffect).toContain('other clients'); + expect(f.counts()).toEqual(before); + const absent = captureInboxSetup( + review, + f.own.resolver, + crypto.randomUUID(), + 'connect' + ); + expect(absent.status).toBe('invalid'); + const id = crypto.randomUUID(), + capture = captureInboxSetup( + review, + f.own.resolver, + id, + 'reviewed_global_inbox_replacement' + ); + expect(capture.status).toBe('captured'); + if (capture.status !== 'captured') return; + const row = publicRecordSnapshot(capture.record, f.owner, id)!; + expect(row.family).toBe('preference_operation'); + if (row.family !== 'preference_operation') return; + expect(row.source.wire).toBe(view.originalWire); + expect(row.capture.wire).toBe(view.wire); + expect(row.capture.hash).toBe(view.hash); + expect(row.capture.targets).toEqual(view.destinations); + expect(row.consent).toBe('explicit_review'); + expect(row.artifact).toBeNull(); + expect(row.receipts).toEqual([]); + expect(f.counts()).toEqual(before); + } finally { + f.close(); + } +}); +it('more than three existing advertisements are never silently truncated', async () => { + const tags = [1, 2, 3, 4, 5].map((n) => [ + 'relay', + 'wss://old' + n + '.example.org' + ]); + const f = await makeSetupFixture(tags); + try { + const view = inboxSetupPreview(await reviewed(f))!; + expect((JSON.parse(view.wire) as { tags: string[][] }).tags).toEqual([ + ...tags, + ['relay', inbox] + ]); + } finally { + f.close(); + } +}); +it('unknown root fields block canonical replacement unless owner explicitly removes each field', async () => { + const f = await makeSetupFixture(undefined, { + unknown: { nested: ['keep'] }, + another: 'keep' + }); + try { + expect( + ( + await reviewInboxSetup( + f.identity, + f.own.resolver, + fixturePolicy(), + setupInput(), + () => 101 + ) + ).status + ).toBe('blocked'); + expect( + ( + await reviewInboxSetup( + f.identity, + f.own.resolver, + fixturePolicy(), + setupInput({ removeExtraFields: ['unknown'] }), + () => 101 + ) + ).status + ).toBe('blocked'); + const view = inboxSetupPreview( + await reviewed( + f, + setupInput({ removeExtraFields: ['unknown', 'another'] }) + ) + )!; + expect( + (JSON.parse(view.originalWire!) as Record<string, unknown>).unknown + ).toEqual({ + nested: ['keep'] + }); + expect(view.removedExtraFields).toEqual(['unknown', 'another']); + expect(JSON.parse(view.wire)).not.toHaveProperty('unknown'); + } finally { + f.close(); + } +}); +it('malformed relay entries require explicit removal and retain every unrelated unknown tag', async () => { + const tags = [ + ['relay', 'https://bad.example.org'], + ['unknown', 'keep'], + ['relay', 'wss://old.example.org'] + ]; + const f = await makeSetupFixture(tags); + try { + expect( + ( + await reviewInboxSetup( + f.identity, + f.own.resolver, + fixturePolicy(), + setupInput(), + () => 101 + ) + ).status + ).toBe('blocked'); + const view = inboxSetupPreview( + await reviewed(f, setupInput({ removeTagIndices: [0] })) + )!; + expect(view.removedTagIndices).toEqual([0]); + expect((JSON.parse(view.wire) as { tags: string[][] }).tags).toEqual([ + tags[1], + tags[2], + ['relay', inbox] + ]); + } finally { + f.close(); + } +}); +it('known-head change conflicts rather than authorizing stale global replacement', async () => { + const f = await makeSetupFixture(); + try { + const review = await reviewed(f), + fresh = f.resolve(f.newerEvent); + expect( + captureInboxSetup( + review, + fresh.resolver, + crypto.randomUUID(), + 'reviewed_global_inbox_replacement' + ).status + ).toBe('conflict'); + } finally { + f.close(); + } +}); +it('missing bounded observation can capture null base but partial discovery cannot', async () => { + const f = await makeSetupFixture(undefined, {}, true); + try { + const review = await reviewed(f), + id = crypto.randomUUID(), + r = captureInboxSetup( + review, + f.own.resolver, + id, + 'reviewed_global_inbox_replacement' + ); + expect(r.status).toBe('captured'); + if (r.status === 'captured') { + const row = publicRecordSnapshot(r.record, f.owner, id)!; + if (row.family === 'preference_operation') + expect(row.source.wire).toBeNull(); + } + const incomplete = f.resolve(null, false); + expect( + ( + await reviewInboxSetup( + f.identity, + incomplete.resolver, + fixturePolicy(), + setupInput(), + () => 101 + ) + ).status + ).toBe('blocked'); + } finally { + f.close(); + } +}); +it('detached preview cannot retarget frozen capture and forged reviews cannot capture', async () => { + const f = await makeSetupFixture(); + try { + const review = await reviewed(f), + view = inboxSetupPreview(review)!; + view.destinations.push('wss://hint.example.org'); + view.selectedInboxes.length = 0; + view.removedExtraFields.push('not_selected'); + const id = crypto.randomUUID(), + r = captureInboxSetup( + review, + f.own.resolver, + id, + 'reviewed_global_inbox_replacement' + ); + expect(r.status).toBe('captured'); + if (r.status === 'captured') { + const row = publicRecordSnapshot(r.record, f.owner, id)!; + if (row.family === 'preference_operation') + expect(row.capture.targets).toEqual([discovery]); + } + expect( + captureInboxSetup( + {} as InboxSetupReview, + f.own.resolver, + id, + 'reviewed_global_inbox_replacement' + ).status + ).toBe('invalid'); + } finally { + f.close(); + } +}); +it('stale owner or resolver, unsupported clock and unapproved target cannot capture', async () => { + const f = await makeSetupFixture(); + try { + for (const changes of [ + { createdAt: 100 }, + { createdAt: Number.MAX_SAFE_INTEGER + 1 }, + { selectedInboxes: ['wss://hint.example.org'] }, + { removeTagIndices: [999] }, + { removeExtraFields: ['absent'] } + ]) + expect( + ( + await reviewInboxSetup( + f.identity, + f.own.resolver, + fixturePolicy(), + setupInput(changes), + () => 101 + ) + ).status + ).toBe('blocked'); + expect( + ( + await reviewInboxSetup( + createIdentitySession(), + f.own.resolver, + fixturePolicy(), + setupInput(), + () => 101 + ) + ).status + ).toBe('blocked'); + const review = await reviewed(f); + f.own.stale(); + expect( + captureInboxSetup( + review, + f.own.resolver, + crypto.randomUUID(), + 'reviewed_global_inbox_replacement' + ).status + ).toBe('unavailable'); + } finally { + f.close(); + } +});