app

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

commit bd1348e67dd0618eb29f0f30f50d2379a342fdc7
parent 9f9bcc1ce0df6e058251b729446b1575fa353781
Author: triesap <tyson@radroots.org>
Date:   Fri,  9 Oct 2026 13:47:00 +0000

web: wire inbox connection enablement and unlock states (HCP-101)

- Mount genuine owner-bound inbox setup, capability and unlock controls
- Require explicit bounded decryption and qualified history checks
- Retry original failed disposal and reflect revoked current access
- Verify private compiler admission with longer host test allowances

Diffstat:
Mweb/package.json | 4++--
Aweb/src/lib/components/InboxStatus.svelte | 231+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/src/lib/messaging/inbox-setup-view.ts | 83++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mweb/src/lib/messaging/inbox-sync.ts | 38++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/messaging/inbox-view.ts | 587+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/src/routes/messages/+page.svelte | 8+++++++-
Aweb/tests/e2e/harness/inbox-view-panel.svelte | 7+++++++
Aweb/tests/e2e/harness/inbox-view.ts | 174+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/inbox-view.spec.ts | 486+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/provenance/output.test.mjs | 79++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Aweb/tests/unit/inbox-view.test.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/unit/style-contract.test.ts | 2+-
Mweb/tests/unit/verification.test.ts | 4++--
Mweb/tools/check-output.mjs | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mweb/vitest.config.ts | 3++-
15 files changed, 1857 insertions(+), 23 deletions(-)

diff --git a/web/package.json b/web/package.json @@ -14,9 +14,9 @@ "build": "node tools/check-source.mjs && node tools/build-info.mjs && vite build && node tools/check-output.mjs", "check": "node tools/check-source.mjs && svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --fail-on-warnings", "lint": "node tools/check-source.mjs && svelte-kit sync && eslint . --max-warnings 0 && prettier --check .", - "test:unit": "node tools/check-source.mjs && svelte-kit sync && vitest run --config vitest.config.ts && node --test --test-concurrency=1 --test-timeout=120000 tests/provenance/*.test.mjs", + "test:unit": "node tools/check-source.mjs && svelte-kit sync && vitest run --config vitest.config.ts && node --test --test-concurrency=1 --test-timeout=1800000 tests/provenance/*.test.mjs", "test:conformance": "corepack pnpm build && node --test tests/conformance/*.test.ts", - "test:integration": "corepack pnpm build && node --test --test-timeout=120000 tests/integration/*.test.ts", + "test:integration": "corepack pnpm build && node --test --test-timeout=1800000 tests/integration/*.test.ts", "test:e2e": "corepack pnpm build && playwright test", "test:conformance:oracle": "node tools/check-food-interop.mjs", "check:launch-relays": "node tools/check-source.mjs && node tools/check-launch-relays.mjs" diff --git a/web/src/lib/components/InboxStatus.svelte b/web/src/lib/components/InboxStatus.svelte @@ -0,0 +1,231 @@ +<script lang="ts"> + import { getContext, onMount } from 'svelte'; + import CapabilityGate from './CapabilityGate.svelte'; + import InboxSetup from './InboxSetup.svelte'; + import Button from './primitives/Button.svelte'; + import { + IDENTITY_VIEW_CONTEXT, + identityViewSnapshot, + identityViewSession, + subscribeIdentityView, + connectIdentityView, + probeIdentityViewMessaging, + disconnectIdentityView, + type IdentityViewContext + } from '../runtime/view-context.ts'; + import { + PUBLIC_RUNTIME_CONTEXT, + publicRuntimeReady, + type PublicRuntimeContext, + type PublicRuntime + } from '../runtime/public-runtime.ts'; + import { + createRuntimeInboxSetupView, + closeInboxSetupView + } from '../messaging/inbox-setup-view.ts'; + import { + createInboxView, + inboxViewSnapshot, + inboxViewSetup, + subscribeInboxView, + unlockInboxView, + checkInboxView, + readNewInboxView, + stopInboxView, + closeInboxView, + type InboxView + } from '../messaging/inbox-view.ts'; + let { controller }: { controller?: InboxView } = $props(); + const identityContext = getContext<IdentityViewContext>( + IDENTITY_VIEW_CONTEXT + ), + publicContext = getContext<PublicRuntimeContext>(PUBLIC_RUNTIME_CONTEXT); + let identity = $state(identityViewSnapshot(identityContext)), + panel = $state(inboxViewSnapshot(undefined)), + owned = $state.raw<InboxView | undefined>(); + let runtime: PublicRuntime | undefined, + off = () => {}; + const setup = $derived(inboxViewSetup(owned)); + onMount(() => { + let disposed = false; + function acquire() { + if (disposed) return; + identity = identityViewSnapshot(identityContext); + if (owned && inboxViewSnapshot(owned).owner) return; + off(); + if (owned && !controller) { + const oldSetup = inboxViewSetup(owned); + closeInboxView(owned); + if (oldSetup) closeInboxSetupView(oldSetup); + } + owned = controller; + if ( + !owned && + runtime && + identity.identity.state === 'messaging_capable' + ) { + const session = identityViewSession(identityContext), + originalSetup = createRuntimeInboxSetupView(identityContext, runtime); + if (session && originalSetup) { + owned = createInboxView({ identity: session, setup: originalSetup }); + if (!owned) closeInboxSetupView(originalSetup); + } + } + panel = inboxViewSnapshot(owned); + off = subscribeInboxView(owned, (next) => { + panel = next; + }); + } + const identityOff = identityContext + ? subscribeIdentityView(identityContext, acquire) + : () => {}; + acquire(); + if (!controller && publicContext) + void publicRuntimeReady(publicContext) + .then((value) => { + if (disposed) return; + runtime = value; + acquire(); + }) + .catch(() => { + /* Keep genuine unavailable state. */ + }); + return () => { + disposed = true; + identityOff(); + off(); + if (owned && !controller) { + const originalSetup = inboxViewSetup(owned); + closeInboxView(owned); + if (originalSetup) closeInboxSetupView(originalSetup); + } + }; + }); + const effectiveIdentity = $derived( + panel.owner ? panel.identity : identity.identity + ); + const reasons: Record<string, string> = { + access_unavailable: + 'Inbox access has not been qualified and exercised. Unlocked local copies do not prove a successful relay check.', + storage_unavailable: + 'Browser storage is unavailable. Your inbox has not been checked.', + unavailable: + 'The message check could not complete. Existing encrypted copies are preserved.', + elapsed: + 'The bounded inbox check reached its active work limit. Existing encrypted copies are preserved.', + budget: + 'The bounded inbox check reached its item or size limit. Continue only after reviewing the limit.', + declined: + 'Your extension did not approve decryption. Choose Read new messages to try another explicit batch.', + refused: + 'Your extension did not approve decryption. Choose Read new messages to try another explicit batch.', + stopped: 'Messages are locked. Existing encrypted copies are preserved.', + wait_expired: + 'Decryption is paused. Wait for the original extension request to settle before another explicit batch.' + }; + const checked = $derived( + panel.lastCheckedAt === null + ? null + : new Date(panel.lastCheckedAt).toLocaleTimeString() + ); +</script> + +<svelte:head + ><title>HarvestCircle</title><meta + name="robots" + content="noindex" + /></svelte:head +> +<div class="page page--reading stack"> + <h1> + {effectiveIdentity.state === 'guest' || + effectiveIdentity.state === 'pending' + ? 'Connect or unlock' + : 'Messages'} + </h1> + {#if panel.cleanupRequired}<p class="notice"> + Private resource cleanup is incomplete. Wait before reconnecting or + starting another message action. + </p>{/if} + <CapabilityGate + identity={effectiveIdentity} + required="messaging" + focusTarget="protected" + onconnect={identity.mounted + ? () => connectIdentityView(identityContext) + : undefined} + onprobe={identity.mounted + ? () => probeIdentityViewMessaging(identityContext, 'reviewed_self_copy') + : undefined} + ondisconnect={() => disconnectIdentityView(identityContext)} + /> + {#if panel.state === 'locked' || panel.state === 'unlocking'} + <h2>Unlock your messages</h2> + <p> + Your extension will be asked to decrypt your messages. Each explicit batch + checks up to 20 encrypted envelopes and may require two decryption + approvals for each envelope. Further batches need another explicit action. + </p> + <Button + label="Unlock messages" + disabled={!owned || panel.busy} + onclick={() => { + if (owned) void unlockInboxView(owned, 'reviewed_messages_unlock'); + }} + /> + {/if} + {#if panel.state === 'partial' || panel.state === 'ready' || panel.state === 'empty' || panel.state === 'unlocking'} + <p role="status" aria-live="polite"> + {panel.state === 'unlocking' + ? 'Waiting for your explicit extension approvals.' + : panel.state === 'empty' + ? 'No messages found in the checked inbox history.' + : panel.state === 'partial' + ? 'Your unlocked local messages are available with limitations.' + : 'Messages are unlocked. Check here for replies.'} + </p> + {#if panel.reason}<p class="notice"> + {reasons[panel.reason] ?? + 'The check is partial. Existing encrypted copies are preserved; review the limitation before continuing.'} + </p>{/if} + <Button + label="Check for messages" + disabled={!owned || panel.busy} + onclick={() => { + if (owned) void checkInboxView(owned, 'reviewed_foreground_inbox'); + }} + /> + {#if checked}<p> + Last checked at {checked}. This was a bounded foreground check, not + complete inbox history. + </p>{/if} + {#if panel.queued > 0} + <p> + {panel.queued} encrypted envelopes await an explicit decryption batch. Your + extension will be asked to decrypt them; up to 20 envelopes are attempted + per batch. + </p> + <Button + label={'Read new messages (' + panel.queued + ')'} + disabled={!owned || panel.busy} + onclick={() => { + if (owned) void readNewInboxView(owned, 'reviewed_decrypt_batch'); + }} + /> + {/if} + <h2>Message requests</h2> + <h2>Conversations</h2> + <Button + label="Lock messages" + disabled={!owned} + onclick={() => { + if (owned) stopInboxView(owned); + }} + /> + {/if} + {#key setup}<InboxSetup controller={setup} />{/key} + <p> + Check here for replies. This prototype does not send push or email + notifications. + </p> +</div> diff --git a/web/src/lib/messaging/inbox-setup-view.ts b/web/src/lib/messaging/inbox-setup-view.ts @@ -100,6 +100,17 @@ type Inputs = Readonly<{ close?(): void; }>; type Controller = { + ownership(): + | Readonly<{ + identity: IdentitySession; + policy: RelayPolicy; + session: PrivateSession | undefined; + resolver: InboxResolver | undefined; + observeAccess: ObserveInboxAccess | undefined; + current(): boolean; + }> + | undefined; + observe(): void; snapshot(): InboxSetupViewSnapshot; subscribe(listener: (state: InboxSetupViewSnapshot) => void): () => void; check(): Promise<void>; @@ -148,6 +159,7 @@ export function createInboxSetupView( }, epoch = 0, closed = false; + let pendingClose: (() => void)[] | undefined; let resolver: InboxResolver | undefined, review: InboxSetupReview | undefined, action: InboxPreferenceAction | undefined, @@ -243,6 +255,21 @@ export function createInboxSetupView( if (!capture.current()) stop(); }); views.set(token, { + ownership: () => + current() + ? { + identity: input.identity, + policy: input.policy, + session, + resolver, + observeAccess: input.observeAccess, + current: () => current() + } + : undefined, + observe() { + if (current() && !state.busy && state.status === 'lookup_incomplete') + inspect(); + }, snapshot, subscribe(listener) { const id = Symbol(); @@ -435,15 +462,44 @@ export function createInboxSetupView( }), stop, close() { - if (closed) return; - closed = true; - stop(); - invalidate(); - if (resolver) closeInboxResolver(resolver); - if (session) closePrivateSession(session); - if (database) closeBrowserDatabase(database); - input.close?.(); - listeners.clear(); + if (!pendingClose) { + closed = true; + const originalResolver = resolver, + originalReader = reader, + originalSession = session, + originalDatabase = database; + pendingClose = [ + stop, + invalidate, + () => { + if (originalReader) closeInboxReadback(originalReader); + }, + () => { + if (originalResolver) closeInboxResolver(originalResolver); + }, + () => { + if (originalSession && !closePrivateSession(originalSession)) + throw Error('private_cleanup_required'); + }, + () => { + if (originalDatabase) closeBrowserDatabase(originalDatabase); + }, + () => input.close?.(), + () => listeners.clear() + ]; + } + let unfinished = Array.from<() => void>([]); + for (const cleanup of pendingClose) { + try { + cleanup(); + } catch { + unfinished = unfinished.concat(cleanup); + } + } + pendingClose = unfinished; + // Closed admission and completed disposal are separate facts. A failed + // original cleanup remains owned and retryable after invalidation. + if (unfinished.length > 0) throw Error('inbox_setup_cleanup_required'); } }); return token; @@ -531,3 +587,12 @@ export function stopInboxSetupView(view: InboxSetupView | undefined): void { export function closeInboxSetupView(view: InboxSetupView | undefined): void { if (view) views.get(view)?.close(); } + +// Detached original-token observation for trusted page orchestration. Neither +// its scalar fields nor mutation of this fresh object changes stored custody. +export function inboxSetupViewOwnership(view: InboxSetupView | undefined) { + return view && views.get(view)?.ownership(); +} +export function observeInboxSetupView(view: InboxSetupView | undefined): void { + if (view) views.get(view)?.observe(); +} diff --git a/web/src/lib/messaging/inbox-sync.ts b/web/src/lib/messaging/inbox-sync.ts @@ -70,6 +70,7 @@ export type InboxHistoryOwnership = Readonly<{ type Controller = { history(): InboxHistoryOwnership | undefined; start(review: unknown): boolean; + refresh(review: unknown, previousOuterCheck?: unknown): boolean; stop(): void; snapshot(): Snapshot; }; @@ -319,6 +320,32 @@ export function captureInboxSync( }); } ingress.set(token, { + refresh(reviewed, previousOuterCheck) { + if ( + reviewed !== 'reviewed_foreground_inbox' || + !current() || + stopped || + failed || + state !== 'live' || + backfill !== 'complete' || + pending !== 0 + ) + return false; + const plan = outerHistoryPlan( + Math.floor(Date.now() / 1000), + previousOuterCheck + ); + if (!current()) return false; + backfill = 'running'; + try { + release(); + release = subscribePrivateHistory(pool, plan.overlap.since, receive); + return true; + } catch { + pause('backfill_unavailable'); + return false; + } + }, history() { return current() && !stopped && @@ -425,3 +452,14 @@ export function inboxSyncHistoryOwnership( ): InboxHistoryOwnership | undefined { return ingress.get(token)?.history(); } + +// Repeating a checked foreground window requires the same original current +// access/live owner and a fresh explicit review. No recreated live subscription, +// automatic AUTH/retry, decryption or copied snapshot authority. +export function refreshInboxSync( + token: InboxSync, + review: unknown, + previousOuterCheck?: unknown +): boolean { + return ingress.get(token)?.refresh(review, previousOuterCheck) ?? false; +} diff --git a/web/src/lib/messaging/inbox-view.ts b/web/src/lib/messaging/inbox-view.ts @@ -0,0 +1,587 @@ +import { + identityMessagingOwnership, + identitySessionSnapshot, + subscribeIdentityInvalidation, + type IdentitySession, + type IdentitySnapshot +} from '../runtime/identity-session.ts'; +import { + privateSessionOwnership, + subscribePrivateSessionClose, + closePrivateSession, + type PrivateSession +} from '../runtime/private-session.ts'; +import { + inboxSetupViewOwnership, + inboxSetupViewSnapshot, + subscribeInboxSetupView, + closeInboxSetupView, + unlockInboxSetupView, + observeInboxSetupView, + type InboxSetupView +} from './inbox-setup-view.ts'; +import { + openBrowserDatabase, + closeBrowserDatabase, + type BrowserDatabase +} from '../persistence/database.ts'; +import { + createPrivateStorageRepository, + type PrivateStorageRepository +} from '../persistence/private-storage.ts'; +import { + captureUnlockedSession, + closeUnlockedSession, + readUnlockedMessages, + type UnlockedSession +} from './unlocked-session.ts'; +import { + captureDecryptionQueue, + refreshDecryptionQueue, + runDecryptionBatch, + decryptionQueueSnapshot, + stopDecryptionQueue, + type DecryptionQueue +} from './decryption-queue.ts'; +import { + captureInboxSync, + startInboxSync, + refreshInboxSync, + inboxSyncSnapshot, + inboxSyncHistoryOwnership, + stopInboxSync, + type InboxSync +} from './inbox-sync.ts'; +import { messagingReadinessSnapshot } from './readiness.ts'; +declare const inboxViewBrand: unique symbol; +export type InboxView = Readonly<{ [inboxViewBrand]: true }>; +export type InboxViewSnapshot = Readonly<{ + state: string; + reason: string | null; + busy: boolean; + owner?: string; + identity: IdentitySnapshot; + queued: number; + count: number; + lastCheckedAt: number | null; + historyComplete: false; + cleanupRequired: boolean; +}>; +type Inputs = Readonly<{ identity: IdentitySession; setup: InboxSetupView }>; +type Controller = { + snapshot(): InboxViewSnapshot; + setup(): InboxSetupView | undefined; + subscribe(listener: (view: InboxViewSnapshot) => void): () => void; + unlock(review: unknown): Promise<boolean>; + check(review: unknown): Promise<boolean>; + read(review: unknown): Promise<boolean>; + stop(): void; + close(): boolean; +}; +const views = new WeakMap<InboxView, Controller>(); +const unavailable = (): InboxViewSnapshot => ({ + state: 'unavailable', + reason: null, + busy: false, + identity: { state: 'guest', reason: 'unavailable' }, + queued: 0, + count: 0, + lastCheckedAt: null, + historyComplete: false, + cleanupRequired: false +}); +// The original setup/identity objects, not their copied readiness projections, +// own this per-page orchestration. Mounting/subscribing never prompts or sends. +export function createInboxView(input: Inputs): InboxView | undefined { + if (typeof window === 'undefined') return; + const original = identityMessagingOwnership(input.identity), + setup = inboxSetupViewOwnership(input.setup); + if ( + !original?.current() || + !setup?.current() || + setup.identity !== input.identity + ) + return; + const capture = original, + token = Object.freeze({}) as InboxView; + let closed = false, + busy = false, + epoch = 0, + reason: string | null = null, + lastCheckedAt: number | null = null, + checkPending = false, + sampling = false, + refreshedRetained = -1; + let session: PrivateSession | undefined, + database: BrowserDatabase | undefined, + repository: PrivateStorageRepository | undefined, + unlocked: UnlockedSession | undefined, + queue: DecryptionQueue | undefined, + sync: InboxSync | undefined; + let off = () => {}, + privateOff = () => {}, + setupOff = () => {}, + pendingCleanup = Array.from<() => void>([]); + const listeners = new Map<symbol, (view: InboxViewSnapshot) => void>(); + function current(generation = epoch) { + const owner = inboxSetupViewOwnership(input.setup); + return ( + !closed && + generation === epoch && + capture.current() && + owner?.identity === input.identity && + owner.current() + ); + } + function privateCurrent() { + const owner = session && privateSessionOwnership(session); + return ( + !!owner?.current() && + owner.owner === capture.owner && + owner.session === capture.session && + current() + ); + } + function snapshot(): InboxViewSnapshot { + if (!current()) + return { ...unavailable(), cleanupRequired: pendingCleanup.length > 0 }; + const identity = identitySessionSnapshot(input.identity), + setupState = inboxSetupViewSnapshot(input.setup); + if (!privateCurrent() || !unlocked || !queue) + return { + ...unavailable(), + owner: capture.owner, + identity, + state: busy + ? 'unlocking' + : [ + 'compatible', + 'compatible_existing', + 'access_unavailable', + 'verified' + ].includes(setupState.status) + ? 'locked' + : 'setup', + reason, + busy: busy || setupState.busy + }; + const cached = readUnlockedMessages(unlocked), + decrypt = decryptionQueueSnapshot(queue), + transport = sync && inboxSyncSnapshot(sync); + const scope = inboxSetupViewOwnership(input.setup); + const exercised = + !!scope?.resolver && + messagingReadinessSnapshot( + input.identity, + session, + scope.policy, + scope.resolver, + undefined, + scope.observeAccess + ).ownAccess === 'qualified_exercised'; + if (!privateCurrent()) return unavailable(); + const partial = + reason !== null || + !exercised || + cached.status !== 'ready' || + decrypt.state === 'paused' || + transport?.state === 'needs_action' || + transport?.state === 'stopped'; + const checked = + lastCheckedAt !== null && !!sync && !!inboxSyncHistoryOwnership(sync); + return { + state: + busy || decrypt.busy + ? 'unlocking' + : partial + ? 'partial' + : checked && decrypt.queued === 0 && cached.messages.length === 0 + ? 'empty' + : 'ready', + reason: + reason ?? + decrypt.reason ?? + transport?.reason ?? + (!exercised ? 'access_unavailable' : null), + busy: busy || decrypt.busy || setupState.busy, + owner: capture.owner, + identity, + queued: decrypt.queued, + count: cached.messages.length, + lastCheckedAt, + historyComplete: false, + cleanupRequired: pendingCleanup.length > 0 + }; + } + function notify() { + for (const listener of listeners.values()) + try { + listener(snapshot()); + } catch { + /* Isolate presentation. */ + } + } + function releasePrivate() { + privateOff(); + privateOff = () => {}; + const originalQueue = queue, + originalSync = sync, + originalUnlocked = unlocked, + originalSession = session, + originalDatabase = database; + const tasks = pendingCleanup.concat([ + () => { + if (originalQueue) stopDecryptionQueue(originalQueue); + }, + () => { + if (originalSync) stopInboxSync(originalSync); + }, + () => { + if (originalUnlocked) closeUnlockedSession(originalUnlocked); + }, + () => { + if (originalSession && !closePrivateSession(originalSession)) + throw Error('private_cleanup_required'); + }, + () => { + if (originalDatabase) closeBrowserDatabase(originalDatabase); + } + ]); + pendingCleanup = []; + for (const cleanup of tasks) + try { + cleanup(); + } catch { + pendingCleanup = pendingCleanup.concat(cleanup); + } + if (pendingCleanup.length > 0) reason = 'cleanup_required'; + queue = undefined; + sync = undefined; + unlocked = undefined; + session = undefined; + repository = undefined; + database = undefined; + lastCheckedAt = null; + checkPending = false; + } + function stop() { + epoch++; + reason = 'stopped'; + releasePrivate(); + busy = false; + notify(); + } + async function sample() { + if (sampling || closed) return; + if (!current()) { + notify(); + return; + } + observeInboxSetupView(input.setup); + if (!queue || !privateCurrent()) { + notify(); + return; + } + sampling = true; + const generation = epoch; + try { + const transport = sync && inboxSyncSnapshot(sync); + // Read native ciphertext only after actual ingress changes, never on + // every idle presentation tick and never as automatic SDK decryption. + if ( + transport && + transport.pending === 0 && + transport.retained !== refreshedRetained && + !decryptionQueueSnapshot(queue).busy + ) { + const retained = transport.retained; + const refreshed = await refreshDecryptionQueue(queue); + if (!current(generation) || !privateCurrent()) return; + refreshedRetained = retained; + if (!refreshed) { + notify(); + return; + } + } + if (!current(generation) || !privateCurrent()) return; + if ( + checkPending && + sync && + transport?.backfill === 'complete' && + transport.pending === 0 && + inboxSyncHistoryOwnership(sync)?.current() + ) { + const checked = Date.now(); + if ( + current(generation) && + privateCurrent() && + inboxSyncHistoryOwnership(sync)?.current() + ) { + lastCheckedAt = checked; + checkPending = false; + } + } + notify(); + } catch { + if (current(generation)) { + reason = 'unavailable'; + notify(); + } + } finally { + sampling = false; + } + } + async function read(reviewed: unknown) { + if ( + reviewed !== 'reviewed_decrypt_batch' || + busy || + !queue || + !privateCurrent() + ) + return false; + busy = true; + reason = null; + const generation = epoch; + notify(); + try { + const result = await runDecryptionBatch(queue, reviewed); + if (!current(generation) || !privateCurrent()) return false; + return result; + } finally { + if (current(generation)) { + busy = false; + notify(); + } + } + } + async function unlock(reviewed: unknown) { + if (reviewed !== 'reviewed_messages_unlock' || busy || !current()) + return false; + if (queue && privateCurrent()) return await read('reviewed_decrypt_batch'); + const setupState = inboxSetupViewSnapshot(input.setup); + if ( + ![ + 'compatible', + 'compatible_existing', + 'access_unavailable', + 'verified' + ].includes(setupState.status) + ) + return false; + busy = true; + reason = null; + const generation = epoch; + notify(); + try { + await unlockInboxSetupView(input.setup); + if (!current(generation)) return false; + const original = inboxSetupViewOwnership(input.setup), + acquired = original?.session, + owner = acquired && privateSessionOwnership(acquired); + if ( + !original?.resolver || + !acquired || + !owner?.current() || + owner.owner !== capture.owner || + owner.session !== capture.session || + !original.current() + ) + return false; + session = acquired; + const opened = await openBrowserDatabase(); + if (!current(generation) || !privateCurrent()) { + if (opened.state === 'ready') closeBrowserDatabase(opened.owner); + return false; + } + if (opened.state !== 'ready') { + reason = 'storage_unavailable'; + return false; + } + database = opened.owner; + repository = createPrivateStorageRepository(database, capture.owner); + unlocked = captureUnlockedSession(session, reviewed); + queue = + repository && + unlocked && + captureDecryptionQueue( + repository, + session, + input.identity, + unlocked, + 'reviewed_inbox_unlock' + ); + if (!queue) { + reason = 'unavailable'; + return false; + } + privateOff = subscribePrivateSessionClose(session, () => { + epoch++; + releasePrivate(); + busy = false; + notify(); + if (pendingCleanup.length > 0) + queueMicrotask(() => { + releasePrivate(); + notify(); + }); + }); + if (!privateCurrent()) return false; + const result = await runDecryptionBatch(queue, 'reviewed_decrypt_batch'); + if (!current(generation) || !privateCurrent()) return false; + return result; + } catch { + if (current(generation)) reason = 'unavailable'; + return false; + } finally { + if (current(generation)) { + busy = false; + notify(); + } + } + } + async function check(reviewed: unknown) { + if ( + reviewed !== 'reviewed_foreground_inbox' || + busy || + !privateCurrent() || + !session || + !repository || + !unlocked + ) + return false; + const scope = inboxSetupViewOwnership(input.setup); + if (!scope?.resolver || !scope.current() || !scope.observeAccess) { + reason = 'access_unavailable'; + notify(); + return false; + } + reason = null; + if (sync) { + if ( + !refreshInboxSync( + sync, + reviewed, + lastCheckedAt === null ? undefined : Math.floor(lastCheckedAt / 1000) + ) + ) { + reason = inboxSyncSnapshot(sync)?.reason ?? 'check_incomplete'; + notify(); + return false; + } + } else { + sync = captureInboxSync( + repository, + session, + scope.policy, + scope.resolver, + unlocked, + scope.observeAccess, + reviewed + ); + if (!sync || !startInboxSync(sync, reviewed)) { + reason = 'access_unavailable'; + notify(); + return false; + } + } + checkPending = true; + notify(); + await sample(); + return privateCurrent(); + } + views.set(token, { + snapshot, + setup: () => (current() ? input.setup : undefined), + subscribe(listener) { + const key = Symbol(); + listeners.set(key, listener); + listener(snapshot()); + return () => { + listeners.delete(key); + }; + }, + unlock, + check, + read, + stop, + close() { + if (!closed) { + closed = true; + epoch++; + clearInterval(timer); + off(); + setupOff(); + } + releasePrivate(); + // Cleanup retains the original genuine setup independently of current + // admission. Logout hides effect access, while disposal still closes + // its identity observer, database and runtime public-view owner. + try { + closeInboxSetupView(input.setup); + } catch { + pendingCleanup = pendingCleanup.concat(() => + closeInboxSetupView(input.setup) + ); + } + listeners.clear(); + return pendingCleanup.length === 0; + } + }); + off = subscribeIdentityInvalidation(input.identity, () => { + if (!capture.current()) { + epoch++; + releasePrivate(); + busy = false; + notify(); + } + }); + setupOff = subscribeInboxSetupView(input.setup, notify); + const timer = setInterval(() => { + void sample(); + }, 200); + if (!current()) { + views.get(token)?.close(); + return; + } + return token; +} +export function inboxViewSnapshot( + token: InboxView | undefined +): InboxViewSnapshot { + return (token && views.get(token)?.snapshot()) || unavailable(); +} +export function inboxViewSetup( + token: InboxView | undefined +): InboxSetupView | undefined { + return token && views.get(token)?.setup(); +} +export function subscribeInboxView( + token: InboxView | undefined, + listener: (view: InboxViewSnapshot) => void +): () => void { + return (token && views.get(token)?.subscribe(listener)) || (() => {}); +} +export function unlockInboxView( + token: InboxView, + review: unknown +): Promise<boolean> { + return views.get(token)?.unlock(review) ?? Promise.resolve(false); +} +export function checkInboxView( + token: InboxView, + review: unknown +): Promise<boolean> { + return views.get(token)?.check(review) ?? Promise.resolve(false); +} +export function readNewInboxView( + token: InboxView, + review: unknown +): Promise<boolean> { + return views.get(token)?.read(review) ?? Promise.resolve(false); +} +export function stopInboxView(token: InboxView): void { + views.get(token)?.stop(); +} +export function closeInboxView(token: InboxView): boolean { + return views.get(token)?.close() ?? true; +} diff --git a/web/src/routes/messages/+page.svelte b/web/src/routes/messages/+page.svelte @@ -1,5 +1,11 @@ <script lang="ts"> + import { onMount } from 'svelte'; import AccountGate from '../../lib/components/AccountGate.svelte'; + import InboxStatus from '../../lib/components/InboxStatus.svelte'; + let mounted = $state(false); + onMount(() => { + mounted = true; + }); </script> -<AccountGate /> +{#if mounted}<InboxStatus />{:else}<AccountGate />{/if} diff --git a/web/tests/e2e/harness/inbox-view-panel.svelte b/web/tests/e2e/harness/inbox-view-panel.svelte @@ -0,0 +1,7 @@ +<script lang="ts"> + import InboxStatus from '../../../src/lib/components/InboxStatus.svelte'; + import type { InboxView } from '../../../src/lib/messaging/inbox-view.ts'; + let { controller }: { controller: InboxView } = $props(); +</script> + +<InboxStatus {controller} /> diff --git a/web/tests/e2e/harness/inbox-view.ts b/web/tests/e2e/harness/inbox-view.ts @@ -0,0 +1,174 @@ +import { mount, unmount } from 'svelte'; +import Panel from './inbox-view-panel.svelte'; +import { makeFixture as makeQueueFixture } from './decryption-queue.ts'; +import { makeSetupFixture, fixturePolicy, inbox } from './inbox-setup.ts'; +import { + createInboxSetupView, + checkInboxSetupView, + inboxSetupViewSnapshot, + inboxSetupViewOwnership, + closeInboxSetupView +} from '../../../src/lib/messaging/inbox-setup-view.ts'; +import { + createInboxView, + inboxViewSnapshot, + unlockInboxView, + checkInboxView, + readNewInboxView, + stopInboxView, + closeInboxView +} from '../../../src/lib/messaging/inbox-view.ts'; +import { + readRelayPolicy, + validateRelayPolicy +} from '../../../src/lib/config/relays.ts'; +import { identityMessagingOwnership } from '../../../src/lib/runtime/identity-session.ts'; +export { makeSetupFixture, inboxViewSnapshot }; +export async function renderFixture(count = 21, qualified = false) { + const f = await makeQueueFixture(count); + const policy = validateRelayPolicy( + JSON.stringify({ + ...readRelayPolicy(f.context.policy), + messagingEnabled: true + }) + ); + if (!policy) throw Error('missing controlled policy'); + let access = true, + closedSetups = 0, + failSetupCleanup = false; + const original = identityMessagingOwnership(f.identity); + if (!original) throw Error('missing original fixture identity'); + const setup = createInboxSetupView({ + identity: f.identity, + policy, + close: () => { + closedSetups++; + if (failSetupCleanup && closedSetups === 1) + throw Error('controlled original setup disposal failure'); + }, + lookup: () => Promise.resolve(f.context.own), + observeAccess: qualified + ? (context) => ({ + ...context, + receive: 'qualified_exercised', + archive: 'qualified_exercised', + current: () => access && original.current() + }) + : undefined + }); + if (!setup) throw Error('missing original setup'); + const controller = createInboxView({ identity: f.identity, setup }); + if (!controller) throw Error('missing original inbox view'); + const target = document.createElement('div'); + document.body.append(target); + const mounted = mount(Panel, { target, props: { controller } }); + const baseline = f.counts(); + return { + controller, + setup, + snapshot: () => inboxViewSnapshot(controller), + setupSnapshot: () => inboxSetupViewSnapshot(setup), + closeInvalidatedPage() { + f.disconnect(); + const closed = closeInboxView(controller); + return { + closed, + closedSetups, + setupStatus: inboxSetupViewSnapshot(setup).status + }; + }, + retryFailedSetupClose() { + failSetupCleanup = true; + const first = closeInboxView(controller); + const incomplete = inboxViewSnapshot(controller).cleanupRequired; + const second = closeInboxView(controller); + return { + first, + incomplete, + second, + closedSetups, + cleanupRequired: inboxViewSnapshot(controller).cleanupRequired + }; + }, + checkSetup: () => checkInboxSetupView(setup), + unlock: (review: unknown = 'reviewed_messages_unlock') => + unlockInboxView(controller, review), + check: (review: unknown = 'reviewed_foreground_inbox') => + checkInboxView(controller, review), + next: (review: unknown = 'reviewed_decrypt_batch') => + readNewInboxView(controller, review), + delta: () => ({ + keys: f.counts().keys - baseline.keys, + decrypts: f.counts().decrypts - baseline.decrypts, + encrypts: f.counts().encrypts - baseline.encrypts, + signs: f.counts().signs - baseline.signs + }), + encryptedUnchanged: () => f.encryptedUnchanged(), + pending: () => f.pending(), + settle: () => f.settle(), + mode: f.mode, + scheduler: () => f.scheduler(), + logout: () => f.disconnect(), + revokeAccess: () => { + access = false; + }, + stop: () => stopInboxView(controller), + copied: async () => ({ + unlock: await unlockInboxView( + { ...controller }, + 'reviewed_messages_unlock' + ), + check: await checkInboxView( + { ...controller }, + 'reviewed_foreground_inbox' + ), + next: await readNewInboxView({ ...controller }, 'reviewed_decrypt_batch') + }), + mutateOwnership() { + const first = inboxSetupViewOwnership(setup); + if (!first) throw Error('missing genuine observed ownership'); + Reflect.set(first, 'identity', {}); + Reflect.set(first, 'current', () => false); + const second = inboxSetupViewOwnership(setup); + return !!second && second.identity === f.identity && second.current(); + }, + async close() { + f.settle(); + closeInboxView(controller); + closeInboxSetupView(setup); + await unmount(mounted); + f.close(); + target.remove(); + } + }; +} +export async function renderSetupFixture( + mode: 'missing' | 'incomplete' | 'compatible' = 'missing' +) { + const f = await makeSetupFixture([['relay', inbox]], {}, mode === 'missing'); + const setup = createInboxSetupView({ + identity: f.identity, + policy: fixturePolicy(), + lookup: () => + Promise.resolve(f.resolve(undefined, mode !== 'incomplete').resolver) + }); + if (!setup) throw Error('missing setup'); + const controller = createInboxView({ identity: f.identity, setup }); + if (!controller) throw Error('missing view'); + const target = document.createElement('div'); + document.body.append(target); + const mounted = mount(Panel, { target, props: { controller } }); + return { + controller, + setup, + snapshot: () => inboxViewSnapshot(controller), + counts: f.counts, + async close() { + closeInboxView(controller); + closeInboxSetupView(setup); + await unmount(mounted); + f.close(); + target.remove(); + } + }; +} diff --git a/web/tests/e2e/inbox-view.spec.ts b/web/tests/e2e/inbox-view.spec.ts @@ -0,0 +1,486 @@ +import { test, expect } from '@playwright/test'; +import { build } from 'vite'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; +import { fileURLToPath } from 'node:url'; +import { once } from 'node:events'; +import { WebSocketServer } from 'ws'; +import { createStaticHarness } from '../integration/harness/static.ts'; +import type * as Fixture from './harness/inbox-view.ts'; +declare global { + interface Window { + hcp101: typeof Fixture; + hcp101Fixture: Awaited<ReturnType<typeof Fixture.renderFixture>>; + hcp101SetupFixture: Awaited<ReturnType<typeof Fixture.renderSetupFixture>>; + hcp101Provider?: Awaited<ReturnType<typeof Fixture.makeSetupFixture>>; + hcp101Pending?: Promise<boolean>; + } +} +let server: Awaited<ReturnType<typeof createStaticHarness>>, + sockets: WebSocketServer, + endpoint: string, + bundle: string; +let requests: unknown[][] = [], + closes: unknown[][] = [], + events: unknown[][] = []; +test.beforeAll(async () => { + server = await createStaticHarness(); + sockets = new WebSocketServer({ + host: '127.0.0.1', + port: 0, + maxPayload: 65536 + }); + await once(sockets, 'listening'); + const address = sockets.address(); + if (!address || typeof address === 'string') + throw Error('loopback unavailable'); + endpoint = 'ws://127.0.0.1:' + address.port; + sockets.on('connection', (socket) => + socket.on('message', (bytes) => { + const raw = Buffer.isBuffer(bytes) + ? bytes + : Array.isArray(bytes) + ? Buffer.concat(bytes) + : Buffer.from(bytes), + frame = JSON.parse(raw.toString()) as unknown[]; + if (frame[0] === 'CLOSE') closes.push(frame); + if (frame[0] === 'EVENT') events.push(frame); + if (frame[0] === 'REQ') { + requests.push(frame); + socket.send(JSON.stringify(['EOSE', frame[1]])); + } + }) + ); + const result = await build({ + configFile: false, + logLevel: 'silent', + plugins: [svelte({ configFile: false })], + resolve: { conditions: ['browser'] }, + build: { + write: false, + minify: false, + lib: { + entry: fileURLToPath( + new URL('./harness/inbox-view.ts', import.meta.url) + ), + name: 'hcp101', + formats: ['iife'] + } + } + }); + const output = Array.isArray(result) ? result[0] : result; + if (!('output' in output)) throw Error('missing bundle'); + const chunks = output.output.filter((row) => row.type === 'chunk'); + expect(chunks).toHaveLength(1); + bundle = chunks[0].code; +}); +test('original setup cleanup survives actual identity invalidation before page closure', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp101Fixture = await window.hcp101.renderFixture(0); + }); + const observed = await page.evaluate(() => + window.hcp101Fixture.closeInvalidatedPage() + ); + console.log('actual original setup cleanup', JSON.stringify(observed)); + expect(observed.closedSetups).toBe(1); + expect(observed.setupStatus).toBe('closed'); + expect(observed.closed).toBe(true); + expect(events).toEqual([]); + expect(requests).toEqual([]); +}); +test.afterAll(async () => { + for (const socket of sockets.clients) socket.terminate(); + await new Promise<void>((resolve) => sockets.close(() => resolve())); + await server.close(); +}); +test.beforeEach(async ({ page }) => { + requests = []; + closes = []; + events = []; + await page.addInitScript( + ({ endpoint }) => { + const Native = window.WebSocket; + window.WebSocket = class extends Native { + constructor(url: string | URL, protocols?: string | string[]) { + if ( + ![ + 'wss://archive.example.org', + 'wss://discovery.example.org' + ].includes(new URL(String(url)).origin) + ) + throw Error('unapproved destination'); + super(endpoint, protocols); + } + }; + }, + { endpoint } + ); + await page.goto(server.url + '/search'); + await page.addScriptTag({ content: bundle }); +}); +test.afterEach(async ({ page }) => { + if (!page.isClosed()) + await page.evaluate(async () => { + window.hcp101Fixture?.settle(); + await window.hcp101Pending; + await window.hcp101Fixture?.close(); + await window.hcp101SetupFixture?.close(); + window.hcp101Provider?.close(); + }); +}); +test('failed original setup disposal remains incomplete until actual retained cleanup is retried', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp101Fixture = await window.hcp101.renderFixture(0); + }); + const observed = await page.evaluate(() => + window.hcp101Fixture.retryFailedSetupClose() + ); + console.log( + 'actual failed original setup disposal', + JSON.stringify(observed) + ); + expect(observed.first).toBe(false); + expect(observed.incomplete).toBe(true); + expect(observed.second).toBe(true); + expect(observed.closedSetups).toBe(2); + expect(observed.cleanupRequired).toBe(false); + expect(events).toEqual([]); + expect(requests).toEqual([]); +}); +test('revoked original exercised access becomes partial while preserving the actual earlier checked time', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp101Fixture = await window.hcp101.renderFixture(0, true); + await window.hcp101Fixture.checkSetup(); + await window.hcp101Fixture.unlock(); + await window.hcp101Fixture.check(); + }); + await expect + .poll(() => page.evaluate(() => window.hcp101Fixture.snapshot().state)) + .toBe('empty'); + const before = await page.evaluate( + () => window.hcp101Fixture.snapshot().lastCheckedAt + ); + const observed = await page.evaluate(() => { + window.hcp101Fixture.revokeAccess(); + return window.hcp101Fixture.snapshot(); + }); + console.log( + 'actual revoked original exercised access', + JSON.stringify(observed) + ); + expect(observed.state).toBe('partial'); + expect(observed.reason).toBe('access_unavailable'); + expect(observed.lastCheckedAt).toBe(before); + expect(events).toEqual([]); +}); +test('actual production guest connection publishes no event and cannot claim an empty inbox', async ({ + page +}) => { + await page.goto(server.url + '/messages'); + await page.addScriptTag({ content: bundle }); + await expect( + page + .locator('#main-content') + .getByRole('button', { name: 'Connect extension' }) + ).toBeVisible(); + await expect( + page + .locator('#main-content') + .getByText('No messages found in the checked inbox history.') + ).toHaveCount(0); + await expect( + page.locator('#main-content').getByText(/^Last checked/) + ).toHaveCount(0); + expect(events).toEqual([]); + expect(requests).toEqual([]); + await expect(page).toHaveTitle('HarvestCircle'); + await expect(page.locator('meta[name="robots"]')).toHaveCount(1); +}); +test('actual missing NIP44 encrypt capability is explanatory and never an empty inbox', async ({ + page +}) => { + await page.goto(server.url + '/messages'); + await page.addScriptTag({ content: bundle }); + await page.evaluate(async () => { + window.hcp101Provider = await window.hcp101.makeSetupFixture(); + const provider = window.nostr as + { nip44?: { encrypt?: unknown } } | undefined; + if (provider?.nip44) Reflect.deleteProperty(provider.nip44, 'encrypt'); + }); + const main = page.locator('#main-content'); + await main.getByRole('button', { name: 'Connect extension' }).click(); + await main.getByRole('button', { name: 'Check messaging support' }).click(); + await expect( + main.getByText( + 'This extension does not support the required message encryption.' + ) + ).toBeVisible(); + await expect( + main.getByText('No messages found in the checked inbox history.') + ).toHaveCount(0); + expect(events).toEqual([]); + expect(requests).toEqual([]); +}); +test('existing genuine signed preference offers an explicit disclosed unlock without replacement or send', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp101Fixture = await window.hcp101.renderFixture(21); + }); + await page.getByRole('button', { name: 'Check current preference' }).click(); + await expect( + page.getByRole('button', { name: 'Unlock messages', exact: true }) + ).toBeVisible(); + await expect( + page.getByText(/Your extension will be asked to decrypt/) + ).toBeVisible(); + await expect( + page.getByRole('button', { name: 'Enable inbox', exact: true }) + ).toHaveCount(0); + expect(await page.evaluate(() => window.hcp101Fixture.delta())).toMatchObject( + { decrypts: 0, signs: 0, encrypts: 0 } + ); + expect(events).toEqual([]); + expect(requests).toEqual([]); +}); +test('actual missing preference is setup and completed absence never becomes an empty message list', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp101SetupFixture = + await window.hcp101.renderSetupFixture('missing'); + }); + await page.getByRole('button', { name: 'Check current preference' }).click(); + await expect( + page.getByText( + 'No preference was observed in this completed bounded lookup. This does not prove global absence.' + ) + ).toBeVisible(); + expect( + await page.evaluate(() => window.hcp101SetupFixture.snapshot().state) + ).toBe('setup'); + await expect( + page.getByText('No messages found in the checked inbox history.') + ).toHaveCount(0); + await expect(page.getByText(/^Last checked/)).toHaveCount(0); + expect(events).toEqual([]); +}); +test('incomplete actual preference lookup stays unknown without unlock, checked time or fabricated absence', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp101SetupFixture = + await window.hcp101.renderSetupFixture('incomplete'); + }); + await page.getByRole('button', { name: 'Check current preference' }).click(); + await expect( + page.getByText( + 'The lookup is incomplete. Your current inbox preference is unknown.' + ) + ).toBeVisible(); + await expect( + page.getByRole('button', { name: 'Unlock messages', exact: true }) + ).toHaveCount(0); + await expect(page.getByText(/^Last checked/)).toHaveCount(0); + expect( + await page.evaluate(() => window.hcp101SetupFixture.counts().signs) + ).toBe(0); + expect(events).toEqual([]); +}); +test('explicit original Unlock processes20 actual encrypted envelopes and waits for a second review for21st', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp101Fixture = await window.hcp101.renderFixture(21); + await window.hcp101Fixture.checkSetup(); + }); + await page + .getByRole('button', { name: 'Unlock messages', exact: true }) + .click(); + await expect + .poll(() => page.evaluate(() => window.hcp101Fixture.snapshot().queued)) + .toBe(1); + expect(await page.evaluate(() => window.hcp101Fixture.delta())).toMatchObject( + { decrypts: 40, signs: 0, encrypts: 0 } + ); + await expect( + page.getByRole('button', { name: 'Read new messages (1)', exact: true }) + ).toBeVisible(); + expect( + await page.evaluate(() => window.hcp101Fixture.encryptedUnchanged()) + ).toBe(true); + await expect(page.getByText(/^Last checked/)).toHaveCount(0); + expect(events).toEqual([]); + expect(requests).toEqual([]); +}); +test('a further explicit decrypt batch consumes only the remaining envelope and cannot send or rewrite', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp101Fixture = await window.hcp101.renderFixture(21); + await window.hcp101Fixture.checkSetup(); + await window.hcp101Fixture.unlock(); + }); + await page + .getByRole('button', { name: 'Read new messages (1)', exact: true }) + .click(); + await expect + .poll(() => page.evaluate(() => window.hcp101Fixture.snapshot().queued)) + .toBe(0); + expect(await page.evaluate(() => window.hcp101Fixture.delta())).toMatchObject( + { decrypts: 42, signs: 0, encrypts: 0 } + ); + expect( + await page.evaluate(() => window.hcp101Fixture.encryptedUnchanged()) + ).toBe(true); + await expect( + page.getByRole('button', { name: /^Read new messages/ }) + ).toHaveCount(0); + expect(events).toEqual([]); +}); +test('unqualified real access remains partial and Check cannot mint checked time, empty state or private REQ', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp101Fixture = await window.hcp101.renderFixture(0, false); + await window.hcp101Fixture.checkSetup(); + await window.hcp101Fixture.unlock(); + }); + await page + .getByRole('button', { name: 'Check for messages', exact: true }) + .click(); + expect( + await page.evaluate(() => window.hcp101Fixture.snapshot()) + ).toMatchObject({ + state: 'partial', + lastCheckedAt: null, + count: 0, + queued: 0 + }); + await expect( + page.getByText('No messages found in the checked inbox history.') + ).toHaveCount(0); + await expect(page.getByText(/^Last checked/)).toHaveCount(0); + expect(requests).toEqual([]); + expect(events).toEqual([]); +}); +test('only actual controlled qualified live-before-finite completion supplies a bounded empty state and checked time', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp101Fixture = await window.hcp101.renderFixture(0, true); + await window.hcp101Fixture.checkSetup(); + await window.hcp101Fixture.unlock(); + }); + expect( + await page.evaluate(() => window.hcp101Fixture.snapshot().lastCheckedAt) + ).toBeNull(); + await page + .getByRole('button', { name: 'Check for messages', exact: true }) + .click(); + await expect( + page.getByText('No messages found in the checked inbox history.') + ).toBeVisible(); + await expect(page.getByText(/^Last checked/)).toBeVisible(); + expect(requests.length).toBe(3); + expect((requests[0][2] as { limit: number }).limit).toBe(0); + expect((requests[1][2] as { limit: number }).limit).toBe(200); + expect((requests[2][2] as { limit: number }).limit).toBe(200); + expect(await page.evaluate(() => window.hcp101Fixture.delta())).toMatchObject( + { decrypts: 0, signs: 0, encrypts: 0 } + ); + expect(events).toEqual([]); +}); +test('copied page tokens and mutable detached setup observations cannot acquire or change original custody', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp101Fixture = await window.hcp101.renderFixture(0); + }); + expect(await page.evaluate(() => window.hcp101Fixture.copied())).toEqual({ + unlock: false, + check: false, + next: false + }); + expect( + await page.evaluate(() => window.hcp101Fixture.mutateOwnership()) + ).toBe(true); + expect(await page.evaluate(() => window.hcp101Fixture.delta())).toMatchObject( + { decrypts: 0, signs: 0, encrypts: 0 } + ); + expect(events).toEqual([]); + expect(requests).toEqual([]); +}); +test('logout during held actual extension decryption clears presentation and prevents late cached admission', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp101Fixture = await window.hcp101.renderFixture(1); + await window.hcp101Fixture.checkSetup(); + window.hcp101Fixture.mode('hold_decrypt'); + window.hcp101Pending = window.hcp101Fixture.unlock(); + }); + await expect + .poll(() => page.evaluate(() => window.hcp101Fixture.pending())) + .toBe(true); + await page.evaluate(() => window.hcp101Fixture.logout()); + expect( + await page.evaluate(() => window.hcp101Fixture.snapshot()) + ).toMatchObject({ + state: 'unavailable', + count: 0, + queued: 0, + lastCheckedAt: null + }); + expect( + await page.evaluate(() => window.hcp101Fixture.scheduler()?.state) + ).toBe('active'); + await page.evaluate(async () => { + window.hcp101Fixture.settle(); + await window.hcp101Pending; + }); + expect(await page.evaluate(() => window.hcp101Fixture.snapshot().count)).toBe( + 0 + ); + expect(events).toEqual([]); + expect(requests).toEqual([]); +}); +test('a second explicit qualified Check performs fresh finite requests while preserving original live ownership', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp101Fixture = await window.hcp101.renderFixture(0, true); + await window.hcp101Fixture.checkSetup(); + await window.hcp101Fixture.unlock(); + await window.hcp101Fixture.check(); + }); + await expect + .poll(() => page.evaluate(() => window.hcp101Fixture.snapshot().state)) + .toBe('empty'); + expect(requests.length).toBe(3); + const before = await page.evaluate( + () => window.hcp101Fixture.snapshot().lastCheckedAt + ); + await page + .getByRole('button', { name: 'Check for messages', exact: true }) + .click(); + await expect.poll(() => requests.length).toBe(5); + await expect + .poll(() => page.evaluate(() => window.hcp101Fixture.snapshot().state)) + .toBe('empty'); + expect(closes.length).toBeGreaterThanOrEqual(4); + expect( + await page.evaluate(() => window.hcp101Fixture.snapshot().lastCheckedAt) + ).toBeGreaterThanOrEqual(before!); + expect((requests[3][2] as { limit: number }).limit).toBe(200); + expect((requests[4][2] as { limit: number }).limit).toBe(200); + expect(await page.evaluate(() => window.hcp101Fixture.delta())).toMatchObject( + { decrypts: 0, signs: 0, encrypts: 0 } + ); + expect(events).toEqual([]); +}); diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs @@ -21,8 +21,8 @@ import { fileURLToPath } from 'node:url'; import { generateBuildInfo } from '../../tools/build-info.mjs'; import { auditOutput } from '../../tools/check-output.mjs'; -// Slow-host verification allows600s for each setup/copy/compiler/audit test. -// Vite children keep300s; admission checks keep120s within their1800s group. +// Slow-host verification allows1800s for each setup/copy/compiler/audit test. +// Vite children and admission checks keep1800s within their1800s group. // Serial top-level tests keep compatibility work out of the mutation budget. { const source = fileURLToPath(new URL('../../../', import.meta.url)); @@ -50,6 +50,11 @@ import { auditOutput } from '../../tools/check-output.mjs'; // 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/+page.svelte': { + source: + '<script lang="ts">\n import AccountGate from \'../../lib/components/AccountGate.svelte\';\n</script>\n\n<AccountGate />\n', + sha256: '23547dcfa10e85865e31b66c31ea0d043592e3c316c94da2d74bdf2dd419b38a' + }, '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', @@ -300,7 +305,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; const f = await fixture(t); const files = await f.audit(); // Exact eleven-route module/page/static admission; CSS stays once-imported. - assert.equal(files.length, 48); + assert.equal(files.length, 50); // The actual SDK payload crosses the reader scratch boundary; a reused // scratch buffer must still preserve every compiler/static byte exactly. const sizes = await Promise.all( @@ -335,6 +340,70 @@ import { auditOutput } from '../../tools/check-output.mjs'; } ); + for (const sourceName of [ + 'src/routes/messages/+page.svelte', + 'src/lib/components/InboxStatus.svelte', + 'src/lib/messaging/inbox-view.ts', + 'src/lib/messaging/inbox-sync.ts', + 'src/lib/messaging/decryption-queue.ts' + ]) + await check( + 'linked inbox presentation requires exact owned source ' + + sourceName, + async (t) => { + const f = await fixture(t), + file = path.join(f.web, sourceName); + await writeFile( + file, + (await readFile(file, 'utf8')) + + '\n// changed presentation source\n' + ); + // Match the actual altered source identity before probing the + // independent exact producer pin. The stale identity guard stays. + await refresh(f); + await assert.rejects(f.audit, /inbox presentation source/); + } + ); + for (const mutation of [ + 'missing-unlocked', + 'extra-private-edge', + 'missing-private-edge', + 'private-dynamic', + 'publisher-extra-edge' + ]) + await check( + 'actual inbox compiler rejects ' + mutation, + async (t) => { + const f = await fixture(t), + file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const manifest = JSON.parse(await readFile(file, 'utf8')); + const find = (/** @type {string} */ name) => { + const row = Object.entries(manifest).find( + ([, v]) => v.name === name + ); + assert.ok(row); + return row; + }; + const [key, row] = find('unlocked-session'); + if (mutation === 'missing-unlocked') delete manifest[key]; + if (mutation === 'extra-private-edge') + row.imports = row.imports.concat(find('references')[0]); + if (mutation === 'missing-private-edge') + row.imports = row.imports.slice(1); + if (mutation === 'private-dynamic') + row.dynamicImports = [find('read')[0]]; + if (mutation === 'publisher-extra-edge') + find('publishers')[1].imports = find( + 'publishers' + )[1].imports.concat(find('references')[0]); + await writeFile(file, JSON.stringify(manifest)); + await assert.rejects(f.audit, /compiler|references/); + } + ); + for (const name of [ 'components/InboxSetup.svelte', 'messaging/inbox-setup-view.ts', @@ -392,7 +461,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; assert.ok(Buffer.byteLength(expanded) > 64 * 1024); await writeFile(file, expanded); await refresh(f); - assert.equal((await f.audit()).length, 48); + assert.equal((await f.audit()).length, 50); } ); @@ -943,7 +1012,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; } await writeFile(file, JSON.stringify(manifest)); if (mutation === 'permuted-edges') - assert.equal((await f.audit()).length, 48); + assert.equal((await f.audit()).length, 50); else await assert.rejects(f.audit, /compiler|references/); } ); diff --git a/web/tests/unit/inbox-view.test.ts b/web/tests/unit/inbox-view.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest'; +import { + createInboxView, + inboxViewSnapshot, + unlockInboxView, + checkInboxView, + readNewInboxView, + inboxViewSetup, + closeInboxView, + type InboxView +} from '../../src/lib/messaging/inbox-view.ts'; +import { createIdentitySession } from '../../src/lib/runtime/identity-session.ts'; +import type { InboxSetupView } from '../../src/lib/messaging/inbox-setup-view.ts'; +describe('inbox page requires original browser owners', () => { + it('SSR capture cannot create effects from a copied setup', () => { + expect( + createInboxView({ + identity: createIdentitySession(), + setup: {} as InboxSetupView + }) + ).toBeUndefined(); + }); + it('forged scalar tokens never return an owner, checked time or empty inbox', () => { + const value = inboxViewSnapshot({} as InboxView); + expect(value.state).toBe('unavailable'); + expect(value.lastCheckedAt).toBeNull(); + expect(value.owner).toBeUndefined(); + expect(value.count).toBe(0); + }); + it('copied observations are not an inbox controller', () => { + const value = inboxViewSnapshot(undefined); + expect(inboxViewSnapshot({ ...value } as unknown as InboxView).state).toBe( + 'unavailable' + ); + expect( + inboxViewSetup({ ...value } as unknown as InboxView) + ).toBeUndefined(); + }); + it('a forged unlock cannot acquire extension or native database effects', async () => { + expect( + await unlockInboxView({} as InboxView, 'reviewed_messages_unlock') + ).toBe(false); + }); + it('a forged check cannot issue a relay request or checked timestamp', async () => { + expect( + await checkInboxView({} as InboxView, 'reviewed_foreground_inbox') + ).toBe(false); + expect(inboxViewSnapshot({} as InboxView).lastCheckedAt).toBeNull(); + }); + it('forged continuation cannot approve any decrypt batch', async () => { + expect( + await readNewInboxView({} as InboxView, 'reviewed_decrypt_batch') + ).toBe(false); + }); + it('copied or absent owners cannot expose the shared setup token', () => { + expect(inboxViewSetup(undefined)).toBeUndefined(); + expect(inboxViewSetup({} as InboxView)).toBeUndefined(); + }); + it('closing an unknown owner is inert and cannot turn it into a ready inbox', () => { + closeInboxView({} as InboxView); + expect(inboxViewSnapshot({} as InboxView).state).toBe('unavailable'); + }); +}); diff --git a/web/tests/unit/style-contract.test.ts b/web/tests/unit/style-contract.test.ts @@ -100,7 +100,7 @@ async function audit(extra: { name: string; content: string }) { const result = spawnSync(process.execPath, ['tools/check-source.mjs'], { cwd: directory, encoding: 'utf8', - timeout: 8000 + timeout: 1_800_000 }); expect(result.error).toBeUndefined(); return result; diff --git a/web/tests/unit/verification.test.ts b/web/tests/unit/verification.test.ts @@ -10,7 +10,7 @@ const execute = (args: string[]) => spawnSync(process.execPath, args, { cwd: root, encoding: 'utf8', - timeout: 30_000 + timeout: 1_800_000 }); describe('verification rejects invalid inputs', () => { @@ -48,7 +48,7 @@ describe('verification rejects invalid inputs', () => { } finally { await rm(directory, { recursive: true }); } - }, 40_000); + }, 1_800_000); it('rejects deliberate JavaScript and Svelte lint violations', async () => { const eslint = new ESLint({ cwd: root }); diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs @@ -488,7 +488,7 @@ async function inboxSetupAdmission(web) { 'src/lib/components/InboxSetup.svelte': 'b6ee2ecccd3ad3e192a56b6d03178bdf222c60dcc0bcb8e2ce7b09dda3bb3bf0', 'src/lib/messaging/inbox-setup-view.ts': - '26bf9a653c9b09ff9e7466b4b219d5292e6313b93b84db188a8b2f4f5cd979e4', + '7559ec04394624a8275280027c031b90d0a62b78f94aec3933df6f3b50077450', 'src/lib/runtime/view-context.ts': 'e2329113e29db35e983270217c47d38a44d4e0491fd710395e008786b5ae7033' }; @@ -500,6 +500,33 @@ async function inboxSetupAdmission(web) { } return true; } +/** @param {string} web */ +async function inboxPresentationAdmission(web) { + const route = await readOwned(web, 'src/routes/messages/+page.svelte'); + if (!route.toString().includes("'../../lib/components/InboxStatus.svelte'")) + return false; + const producers = { + 'src/routes/messages/+page.svelte': + '8279a92770f38858e197e790839bc98b4d7889214ebecdf47e542d632afbc84f', + 'src/lib/components/InboxStatus.svelte': + '605b92b9f8bb45ffb01ea4682869a37ec5b673a20a0deb7d9385ab659673f27f', + 'src/lib/messaging/inbox-view.ts': + '008feb690302c8d9bf563581bd7eb071e619da7da1e56a12108d6560888e3c2c', + 'src/lib/messaging/inbox-sync.ts': + '84f9b3bb165a81878bb281c51d245aff7eb06a0fa55b857a49b13d0cb1cff8ae', + 'src/lib/messaging/inbox-setup-view.ts': + '7559ec04394624a8275280027c031b90d0a62b78f94aec3933df6f3b50077450', + 'src/lib/messaging/decryption-queue.ts': + '07661a883ee360e9fd7bd411893d637fd6b4b70aecb20101b826fe41b7ca4810' + }; + for (const [name, pin] of Object.entries(producers)) { + const bytes = await readOwned(web, name); + publicText(bytes); + if (createHash('sha256').update(bytes).digest('hex') !== pin) + throw new Error('Invalid owned inbox presentation source'); + } + return true; +} /** @param {string} webDirectory */ export async function auditOutput(webDirectory) { const web = path.resolve(webDirectory); @@ -607,6 +634,8 @@ export async function auditOutput(webDirectory) { hasFullRoutes && hasPublicRuntime === 'public_identity' && (await inboxSetupAdmission(web)); + const hasInboxPresentation = + hasInboxSetup && (await inboxPresentationAdmission(web)); const identityCompilerModule = hasInboxSetup ? 'public-runtime' : hasPreferencePublication @@ -655,6 +684,8 @@ export async function auditOutput(webDirectory) { names.add(name); if (hasProductPresentation) names.add('publishers'); if (hasInboxSetup) names.add('private-handles'); + if (hasInboxPresentation) + for (const name of ['unlocked-session', 'read']) names.add(name); const admitted = new Map([['build-info.json', expectedMetadata]]); const seen = new Set(); for (const [key, record] of Object.entries(manifest)) { @@ -959,6 +990,77 @@ export async function auditOutput(webDirectory) { throw new Error('Invalid owned SDK compiler chunk'); } } + if (hasInboxPresentation) { + const records = Object.entries(manifest); + const entry = (/** @type {string} */ name) => { + const row = records.find(([, r]) => r.name === name); + if (!row) throw new Error('Missing inbox compiler module'); + return row; + }; + /** @type {[string,string[]][]} */ + const dependencies = [ + [ + 'unlocked-session', + [ + 'public-key', + 'private-handles', + 'public-runtime', + 'Button', + 'AccountGate' + ] + ], + ['read', ['public-runtime']], + [ + 'nodes/4', + [ + 'public-key', + 'public-runtime', + 'references', + 'client', + 'Button', + 'view-context', + 'AccountGate', + 'unlocked-session', + 'read' + ] + ], + [ + 'nodes/5', + [ + 'public-key', + 'public-runtime', + 'client', + 'Button', + 'client.svelte', + 'state', + 'view-context', + 'AccountGate', + 'unlocked-session' + ] + ] + ]; + for (const [name, imports] of dependencies) { + const [key, row] = entry(name); + equal( + (row.imports ?? []).toSorted(), + imports.map((value) => entry(value)[0]).sort(), + 'Invalid owned inbox presentation compiler dependencies' + ); + if (row.dynamicImports !== undefined) + throw new Error( + 'Invalid owned inbox presentation compiler dynamic imports' + ); + if (!name.startsWith('nodes/')) { + if ( + !/^_[A-Za-z0-9_-]+\.js$/.test(key) || + Object.keys(row).some( + (field) => !['file', 'name', 'imports'].includes(field) + ) + ) + throw new Error('Invalid owned inbox presentation compiler identity'); + } + } + } if (hasProductPresentation) { const records = Object.entries(manifest); const entry = (/** @type {string} */ name) => { @@ -977,7 +1079,12 @@ export async function auditOutput(webDirectory) { equal( publisher.imports, (hasInboxSetup - ? ['public-key', identityCompilerModule, 'Button'] + ? [ + 'public-key', + identityCompilerModule, + 'Button', + ...(hasInboxPresentation ? ['read'] : []) + ] : hasPublicRuntime === 'public_identity' ? ['public-key', identityCompilerModule, 'Disclosure', 'Button'] : ['public-key', 'Disclosure', 'budgets'] diff --git a/web/vitest.config.ts b/web/vitest.config.ts @@ -7,7 +7,8 @@ export default defineConfig({ test: { environment: 'node', fileParallelism: false, - testTimeout: 600_000, + testTimeout: 1_800_000, + hookTimeout: 1_800_000, include: ['tests/unit/**/*.test.ts'], setupFiles: ['tests/unit/ssr-effects.ts'], passWithNoTests: false