app

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

commit 22c04a3780867bb6e10afa1a69fd659b8aa2b30b
parent ec6b02f162eb70d7c0980c75bef663bd991b9ec7
Author: triesap <tyson@radroots.org>
Date:   Thu, 15 Oct 2026 01:10:21 +0000

web: Bind access qualification to genuine probe evidence

- Issue opaque access only from current original or recovered source and native custody.
- Fence journal proofs with actual read, network admission and cleanup claim identities.
- Preserve covered removal continuity and existing cleanup and product budgets.
- Exercise real AUTH, native failures, physical close and foreground inbox behavior.

Diffstat:
Aweb/src/lib/messaging/inbox-access-qualification.ts | 490+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/src/lib/nostr/inbox-access.ts | 24++++++++++++++++++++++++
Mweb/src/lib/nostr/private-publisher.ts | 220++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mweb/src/lib/persistence/inbox-probe-cleanup.ts | 24+++++++++++++++++++++---
Mweb/src/lib/persistence/inbox-probes.ts | 25+++++++++++++++++++++++--
Aweb/tests/e2e/harness/inbox-access-qualification.ts | 221+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/e2e/harness/inbox-probe-retry.ts | 1+
Aweb/tests/e2e/inbox-access-qualification.spec.ts | 1375+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/provenance/output.test.mjs | 2++
Aweb/tests/unit/inbox-access-qualification.test.ts | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tools/check-output.mjs | 26++++++++++++++++----------
11 files changed, 2517 insertions(+), 16 deletions(-)

diff --git a/web/src/lib/messaging/inbox-access-qualification.ts b/web/src/lib/messaging/inbox-access-qualification.ts @@ -0,0 +1,490 @@ +import type { RelayPolicy } from '../config/relays.ts'; +import { + inboxOperatorQualificationSnapshot, + inboxOperatorQualificationWire, + type InboxOperatorQualification +} from '../config/inbox-operators.ts'; +import { + inboxAccessConstructionBinding, + inboxAccessControllerSnapshot, + subscribeInboxAccessControllerClose, + type InboxAccessController +} from './inbox-access-controller.ts'; +import type { OwnInboxAccessContext, ObserveInboxAccess } from './readiness.ts'; +import { + captureInboxProbeCleanupSelection, + inboxProbeCleanupSelectionBinding, + type InboxProbeNonceAcknowledgement +} from '../persistence/inbox-probes.ts'; +import { + inboxProbeRemovalAcknowledgementBinding, + type InboxProbeRemovalAcknowledgement +} from '../persistence/inbox-probe-cleanup.ts'; +import { + captureInboxProbeQualificationFence, + inboxProbeQualificationFenceCurrent, + inboxProbeCleanupReady +} from '../nostr/private-publisher.ts'; +import { + privateSessionOwnership, + recheckPrivateSession, + subscribePrivateSessionClose, + withIdlePrivateLocalStorage, + type PrivateSession +} from '../runtime/private-session.ts'; +import { + observePrivateRecord, + privateStorageOwner, + type PrivateStorageRepository, + type PrivateStorageFailure +} from '../persistence/private-storage.ts'; +import { privateRecordWire } from '../persistence/private-records.ts'; + +declare const qualificationBrand: unique symbol; +export type InboxAccessQualification = Readonly<{ [qualificationBrand]: true }>; +export type InboxAccessQualificationResult = Readonly<{ + status: 'qualified' | 'invalid' | 'busy' | 'stopped' | PrivateStorageFailure; + qualification?: InboxAccessQualification; +}>; +type Metadata = Readonly<{ + owner: string; + command: string; + eventId: string; + preferenceId: string; + readTargets: readonly string[]; + archiveTargets: readonly string[]; + operatorWire: string; +}>; +type Scope = Metadata & + Readonly<{ + repository: PrivateStorageRepository; + session: PrivateSession; + policy: RelayPolicy; + access: InboxAccessController; + operator: InboxOperatorQualification; + identitySession: symbol; + authority: 'source_fixture' | 'operator'; + current(): boolean; + }>; +type Action = Readonly<{ + scope: Scope; + current(): boolean; + pending(): boolean; + result(): InboxAccessQualification | undefined; + begin(): boolean; + finish(): void; + stop(): void; + issue(): InboxAccessQualification; +}>; +const actions = new WeakMap<object, Action>(); +const qualifications = new WeakMap<InboxAccessQualification, Action>(); +function same(a: readonly string[], b: readonly string[]) { + return a.length === b.length && a.every((value, index) => value === b[index]); +} +function makeScope( + repository: PrivateStorageRepository, + session: PrivateSession, + policy: RelayPolicy, + access: InboxAccessController, + operator: InboxOperatorQualification, + metadata: Metadata +): Scope | undefined { + const actual = inboxAccessConstructionBinding(access, session, policy), + owner = privateSessionOwnership(session), + declaration = inboxOperatorQualificationSnapshot(operator); + if ( + !actual || + !owner || + !declaration || + declaration.authority === 'unconfigured' || + privateStorageOwner(repository) !== metadata.owner || + owner.owner !== metadata.owner || + actual.owner !== metadata.owner || + actual.session !== owner.session || + actual.preferenceId !== metadata.preferenceId || + !same(actual.readTargets, metadata.readTargets) || + !same(actual.archiveTargets, metadata.archiveTargets) || + inboxOperatorQualificationWire(operator, policy) !== metadata.operatorWire + ) + return undefined; + const targets = Array.from( + new Set([...actual.readTargets, ...actual.archiveTargets]) + ); + if ( + !targets.every((origin) => { + const row = declaration.relays.find((value) => value.origin === origin); + return ( + row && + row.auth !== 'unsupported' && + row.recipientRead === 'supported' && + row.namedArchiveAck === 'supported' && + row.exactReadback === 'supported' && + row.retention === 'operator_defined' + ); + }) + ) + return undefined; + function current() { + const snapshot = inboxAccessControllerSnapshot(access); + return ( + actual!.current() && + owner!.current() && + inboxOperatorQualificationWire(operator, policy) === + metadata.operatorWire && + !!snapshot && + !snapshot.busy && + !snapshot.cleanupRequired && + snapshot.state !== 'stopped' && + targets.every((origin) => { + const required = declaration!.relays.find( + (value) => value.origin === origin + )!, + auth = snapshot.auth.find((value) => value.origin === origin); + return required.auth === 'explicit_required' + ? auth?.state === 'accepted' + : !auth || auth.state === 'accepted'; + }) && + actual!.current() && + owner!.current() + ); + } + return current() + ? { + ...metadata, + readTargets: metadata.readTargets.slice(), + archiveTargets: metadata.archiveTargets.slice(), + repository, + session, + policy, + access, + operator, + identitySession: owner.session, + authority: declaration.authority, + current + } + : undefined; +} +function compatible(action: Action, scope: Scope) { + const saved = action.scope; + return ( + saved.repository === scope.repository && + saved.session === scope.session && + saved.policy === scope.policy && + saved.access === scope.access && + saved.operator === scope.operator && + saved.command === scope.command && + saved.eventId === scope.eventId && + saved.operatorWire === scope.operatorWire + ); +} +// The currentness port is created only by the two authenticated factories below; +// no caller currentness, epoch or coverage callback enters this private owner. +function createAction(scope: Scope, sourceCurrent: () => boolean): Action { + let stopped = false, + pending = false, + token: InboxAccessQualification | undefined; + const listeners = new Map<symbol, () => void>(); + function current() { + return !stopped && scope.current() && sourceCurrent(); + } + function stop() { + stopped = true; + for (const [id, off] of listeners) { + off(); + listeners.delete(id); + } + } + const saved: Action = { + scope, + current, + pending: () => pending, + result: () => token, + begin() { + if (pending || !current()) return false; + pending = true; + return true; + }, + finish() { + pending = false; + }, + stop, + issue() { + token ??= Object.freeze({}) as InboxAccessQualification; + qualifications.set(token, saved); + return token; + } + }; + listeners.set(Symbol(), subscribePrivateSessionClose(scope.session, stop)); + listeners.set( + Symbol(), + subscribeInboxAccessControllerClose(scope.access, stop) + ); + if (!current()) stop(); + return saved; +} +function result(action: Action): InboxAccessQualificationResult | undefined { + const token = action.result(); + if (!action.current()) return { status: 'stopped' }; + if (token) return { status: 'qualified', qualification: token }; + if (action.pending()) return { status: 'busy' }; + return undefined; +} + +// Explicit qualification, without a new probe, network attempt or native write. +export async function qualifyInboxAccess( + repository: PrivateStorageRepository, + session: PrivateSession, + policy: RelayPolicy, + access: InboxAccessController, + operator: InboxOperatorQualification, + nonce: InboxProbeNonceAcknowledgement, + observations: unknown, + review: unknown +): Promise<InboxAccessQualificationResult> { + if ( + typeof window === 'undefined' || + review !== 'reviewed_qualify_inbox_access' + ) + return { status: 'invalid' }; + try { + const selection = captureInboxProbeCleanupSelection( + repository, + session, + policy, + nonce, + observations, + 'reviewed_inbox_probe_cleanup_selection' + ), + binding = + selection && + inboxProbeCleanupSelectionBinding( + selection, + repository, + session, + policy + ); + if ( + !selection || + !binding || + binding.access !== access || + binding.operator !== operator + ) + return { status: 'invalid_scope' }; + const scope = makeScope(repository, session, policy, access, operator, { + owner: binding.record.owner, + command: binding.record.id, + eventId: binding.record.self!.eventId, + preferenceId: binding.record.binding.preferenceId, + readTargets: binding.record.binding.readTargets, + archiveTargets: binding.record.binding.archiveTargets, + operatorWire: binding.record.binding.operatorWire + }); + if (!scope) return { status: 'invalid_scope' }; + let action = actions.get(nonce); + if (action && !compatible(action, scope)) + return { status: 'invalid_scope' }; + if (!action) { + const fence = captureInboxProbeQualificationFence( + repository, + session, + policy, + selection + ); + if (!fence) { + // A later append must not let this same old nonce resample authority. + actions.set( + nonce, + createAction(scope, () => false) + ); + return { status: 'stopped' }; + } + action = createAction(scope, () => + inboxProbeQualificationFenceCurrent(fence) + ); + actions.set(nonce, action); + } + const cached = result(action); + if (cached) return cached; + const saved = action; + if (!saved.begin()) return { status: saved.current() ? 'busy' : 'stopped' }; + try { + if (!navigator.locks?.request) return { status: 'unavailable' }; + return await navigator.locks.request( + 'harvestcircle:owner:' + scope.owner, + { mode: 'exclusive', ifAvailable: true }, + async (lock): Promise<InboxAccessQualificationResult> => { + if (!lock) return { status: 'busy' }; + if (!saved.current()) return { status: 'stopped' }; + if (!inboxProbeCleanupReady(repository, session, policy, selection)) + return { status: saved.current() ? 'busy' : 'stopped' }; + if (!(await recheckPrivateSession(session)) || !saved.current()) + return { status: saved.current() ? 'busy' : 'stopped' }; + const job = + await withIdlePrivateLocalStorage<InboxAccessQualificationResult>( + session, + async () => { + if (!saved.current()) return { status: 'stopped' }; + if (!binding.begin()) return { status: 'busy' }; + try { + const native = await observePrivateRecord( + repository, + 'private_sends', + scope.command + ); + if (!native.ok) return { status: native.reason }; + if (!saved.current()) return { status: 'stopped' }; + if ( + native.value.wire !== binding.wire || + privateRecordWire( + native.value.handle, + scope.owner, + scope.command + ) !== binding.wire + ) + return { status: 'conflict' }; + if (!saved.current()) return { status: 'stopped' }; + return { status: 'qualified', qualification: saved.issue() }; + } finally { + binding.finish(); + } + } + ); + if (!saved.current()) return { status: 'stopped' }; + return job.ok ? job.value : { status: 'busy' }; + } + ); + } finally { + saved.finish(); + } + } catch { + return { status: 'unknown_completion' }; + } +} + +// This path consumes source-authenticated pre-disposal admission coverage as +// well as actual successful native removal. Mere genuine cleanup is insufficient. +export function qualifyRemovedInboxAccess( + repository: PrivateStorageRepository, + session: PrivateSession, + policy: RelayPolicy, + access: InboxAccessController, + operator: InboxOperatorQualification, + removal: InboxProbeRemovalAcknowledgement, + review: unknown +): InboxAccessQualificationResult { + if ( + typeof window === 'undefined' || + review !== 'reviewed_qualify_inbox_access' + ) + return { status: 'invalid' }; + try { + const binding = inboxProbeRemovalAcknowledgementBinding( + removal, + repository, + session, + policy + ), + coverage = binding?.qualification; + if ( + !binding || + !coverage || + binding.access !== access || + binding.operator !== operator || + coverage.access !== access || + coverage.operator !== operator || + !coverage.current() + ) + return { status: 'invalid_scope' }; + const scope = makeScope( + repository, + session, + policy, + access, + operator, + binding + ); + if (!scope) return { status: 'invalid_scope' }; + let action = actions.get(removal); + if (action && !compatible(action, scope)) + return { status: 'invalid_scope' }; + if (!action) { + action = createAction(scope, () => { + const fresh = inboxProbeRemovalAcknowledgementBinding( + removal, + repository, + session, + policy + ); + return ( + !!fresh?.qualification && + fresh.access === access && + fresh.operator === operator && + fresh.qualification.current() && + fresh.current() + ); + }); + actions.set(removal, action); + } + const cached = result(action); + if (cached) return cached; + return action.current() + ? { status: 'qualified', qualification: action.issue() } + : { status: 'stopped' }; + } catch { + return { status: 'invalid' }; + } +} + +export function inboxAccessQualificationSnapshot( + token: InboxAccessQualification +) { + const saved = qualifications.get(token); + return saved?.current() + ? { + owner: saved.scope.owner, + command: saved.scope.command, + preferenceId: saved.scope.preferenceId, + authority: saved.scope.authority, + sourceOnly: true + } + : undefined; +} +export function stopInboxAccessQualification( + token: InboxAccessQualification +): void { + qualifications.get(token)?.stop(); +} +// Existing projections receive only an informational view of a genuine proof. +// No public object or caller current callback can enter the qualification map. +export function observeQualifiedInboxAccess( + token: InboxAccessQualification +): ObserveInboxAccess { + return (context: OwnInboxAccessContext) => { + try { + const saved = qualifications.get(token); + if (!saved?.current()) return undefined; + const scope = saved.scope; + if ( + context.owner !== scope.owner || + context.session !== scope.identitySession || + context.preferenceId !== scope.preferenceId || + !same(scope.readTargets, context.readTargets) || + !same(scope.archiveTargets, context.archiveTargets) || + !saved.current() + ) + return undefined; + return { + owner: scope.owner, + session: scope.identitySession, + preferenceId: scope.preferenceId, + readTargets: scope.readTargets.slice(), + archiveTargets: scope.archiveTargets.slice(), + receive: 'qualified_exercised', + archive: 'qualified_exercised', + current: saved.current + }; + } catch { + return undefined; + } + }; +} diff --git a/web/src/lib/nostr/inbox-access.ts b/web/src/lib/nostr/inbox-access.ts @@ -395,6 +395,30 @@ export function inboxProbeActionOwner( : undefined; } +// The original reserved action, never an equal decoded declaration, supplies +// the opaque operator association used by later access qualification. +export function inboxProbeOperatorBinding( + identity: InboxProbeIdentity, + repository: PrivateStorageRepository, + session: PrivateSession, + policy: RelayPolicy +): InboxOperatorQualification | undefined { + const saved = identities.get(identity), + action = saved && actions.get(saved.access), + result = action?.result(); + return saved && + action && + action.repository === repository && + action.session === session && + action.policy === policy && + result && + 'identity' in result && + result.identity === identity && + inboxProbePolicyMatches(identity, session, policy) + ? action.operator + : undefined; +} + // Detached inspection only. Actual SDK decryption and original native/current // associations are necessary to issue a recovered probe capability. export function inboxProbeRumorMatches( diff --git a/web/src/lib/nostr/private-publisher.ts b/web/src/lib/nostr/private-publisher.ts @@ -41,6 +41,7 @@ import { type PrivateStorageRepository } from '../persistence/private-storage.ts'; import type { PairedDeliveryContext } from '../messaging/prepare-send.ts'; +import type { PrivateAccessProbeReceipt } from '../persistence/private-records.ts'; import { inboxRoutePlanSnapshot, recheckInboxRoutePlan @@ -105,6 +106,9 @@ function networkMeter(probe: boolean) { // Probe-only causal obligations survive finish and controller replacement. // The existing three origins/three combined attempts bound this map to nine. const pendingArchives = new Map<string, true>(); + let admissionGeneration = 0, + lastAdmission: string | undefined, + lastReadAdmission: string | undefined; let used = 0, running = false, broken = false, @@ -122,6 +126,41 @@ function networkMeter(probe: boolean) { current: () => !broken, idle: () => !running, archivesApplied: () => pendingArchives.size === 0, + generation: () => admissionGeneration, + coveredGeneration( + nonceReadReceipt: string, + receipts: readonly string[] + ): number | undefined { + if (!probe || !lastAdmission || !lastReadAdmission) return undefined; + const read = JSON.parse(nonceReadReceipt) as PrivateAccessProbeReceipt; + // A later archive cannot hide a real read without its own nonce proof. + // This receipt comes only from the selected nonce's genuine read effect. + if ( + read.role !== 'access_readback' || + JSON.stringify([ + read.actionId, + read.role, + read.origin, + read.eventId, + read.attempt + ]) !== lastReadAdmission + ) + return undefined; + for (const wire of receipts) { + const fact = JSON.parse(wire) as PrivateAccessProbeReceipt; + if ( + JSON.stringify([ + fact.actionId, + fact.role, + fact.origin, + fact.eventId, + fact.attempt + ]) === lastAdmission + ) + return admissionGeneration; + } + return undefined; + }, applyArchive( action: string, origin: string, @@ -162,6 +201,17 @@ function networkMeter(probe: boolean) { const start = clock(); if (start === undefined) return undefined; counts.set(key, count + 1); + if (probe) { + admissionGeneration++; + lastAdmission = JSON.stringify([ + actionId, + role, + origin, + eventId, + count + 1 + ]); + if (role === 'access_readback') lastReadAdmission = lastAdmission; + } if (probe && role === 'access_archive') pendingArchives.set( JSON.stringify([actionId, origin, eventId, count + 1]), @@ -517,6 +567,7 @@ type ProbeMeterOwner = { meter: ProbeMeter; current(): boolean; held(): boolean; + claimIdentity(): symbol; claim(): boolean; release(): void; retain( @@ -576,7 +627,8 @@ function probeMeter( (replace && !privatePoolProbeRetryIdle(session, policy)) ) return undefined; - let held = false; + let held = false, + claimIdentity = Symbol(); // At most one original and one recovered identity per actual controller. // This is the same bounded command entry, never a historical identity list. const identities = new Map< @@ -592,9 +644,11 @@ function probeMeter( meter, current, held: () => held, + claimIdentity: () => claimIdentity, claim() { if (held) return false; held = true; + claimIdentity = Symbol(); return true; }, release() { @@ -648,6 +702,155 @@ type CleanupLease = Readonly<{ }>; const cleanupLeases = new WeakMap<InboxProbeCleanupLease, CleanupLease>(); +declare const qualificationFenceBrand: unique symbol; +export type InboxProbeQualificationFence = Readonly<{ + [qualificationFenceBrand]: true; +}>; +const qualificationFences = new WeakMap< + InboxProbeQualificationFence, + Readonly<{ current(): boolean }> +>(); +type QualifiedRemoval = Readonly<{ + repository: PrivateStorageRepository; + session: PrivateSession; + policy: RelayPolicy; + binding: NonNullable<ReturnType<typeof inboxProbeCleanupSelectionBinding>>; + scope: NonNullable<ReturnType<typeof inboxAccessConstructionBinding>>; +}>; +const qualifiedRemovals = new WeakMap< + PrivateProbeRemovalProof, + QualifiedRemoval +>(); + +// Source admissions and their native-applied effects cover this exact command. +// Ordinary pool/SDK activity is deliberately absent from issued currentness. +function qualificationBinding( + repository: PrivateStorageRepository, + session: PrivateSession, + policy: RelayPolicy, + selection: InboxProbeCleanupSelection, + lease?: CleanupLease +) { + const binding = inboxProbeCleanupSelectionBinding( + selection, + repository, + session, + policy + ); + if (!binding) return undefined; + const entry = commandMeters.get(session)?.get(binding.record.id), + action = identityActions.get(binding.identity), + scope = inboxAccessConstructionBinding(binding.access, session, policy); + if ( + !entry || + !action || + !scope || + entry.access !== binding.access || + action.repository !== repository || + action.session !== session || + action.policy !== policy || + action.meter !== entry.meter || + action.original !== entry.original || + entry.original !== probeImmutable(binding.record) || + entry.held() !== !!lease || + (lease && (lease.entry !== entry || lease.selection !== selection)) || + !entry.meter.idle() || + !entry.meter.archivesApplied() || + !entry.meter.current() + ) + return undefined; + const generation = entry.meter.coveredGeneration( + binding.nonceReadReceipt, + binding.admissions() + ); + if ( + generation === undefined || + !binding.current() || + !scope.current() || + entry.meter.generation() !== generation || + commandMeters.get(session)?.get(binding.record.id) !== entry || + entry.held() !== !!lease || + !entry.meter.idle() || + !entry.meter.archivesApplied() + ) + return undefined; + return { binding, entry, scope, generation }; +} + +export function captureInboxProbeQualificationFence( + repository: PrivateStorageRepository, + session: PrivateSession, + policy: RelayPolicy, + selection: InboxProbeCleanupSelection +): InboxProbeQualificationFence | undefined { + try { + const captured = qualificationBinding( + repository, + session, + policy, + selection + ); + if (!captured) return undefined; + // A real cleanup claim retires this journal fence even if native deletion + // later aborts. Release restores cleanup eligibility, never an old proof. + const claimIdentity = captured.entry.claimIdentity(); + const token = Object.freeze({}) as InboxProbeQualificationFence; + qualificationFences.set(token, { + current() { + const actual = qualificationBinding( + repository, + session, + policy, + selection + ); + return ( + !!actual && + actual.entry === captured.entry && + actual.entry.claimIdentity() === claimIdentity && + actual.generation === captured.generation && + actual.binding.wire === captured.binding.wire && + actual.binding.operator === captured.binding.operator && + actual.binding.access === captured.binding.access + ); + } + }); + return token; + } catch { + return undefined; + } +} +export function inboxProbeQualificationFenceCurrent( + token: InboxProbeQualificationFence +): boolean { + try { + return qualificationFences.get(token)?.current() ?? false; + } catch { + return false; + } +} + +// Only actual successful native retirement records this optional historical +// source coverage. A genuine unqualified cleanup retains its original behavior. +export function inboxProbeQualifiedRemovalBinding( + proof: PrivateProbeRemovalProof, + repository: PrivateStorageRepository, + session: PrivateSession, + policy: RelayPolicy +) { + const saved = qualifiedRemovals.get(proof); + return saved?.repository === repository && + saved.session === session && + saved.policy === policy && + saved.scope.current() + ? { + access: saved.binding.access, + operator: saved.binding.operator, + wire: saved.binding.wire, + current: saved.scope.current + } + : undefined; +} + // Only genuine native-applied source evidence can discharge an actual charge. // This works after controller loss without creating current network authority. export function reconcileInboxProbeArchiveAdmission( @@ -813,6 +1016,13 @@ export function retireInboxProbeCleanupLease( !saved.current() ) return false; + const coverage = qualificationBinding( + saved.repository, + saved.session, + saved.policy, + saved.selection, + saved + ); if (!retireInboxProbeCleanupSelection(saved.selection, proof)) return false; saved.entry.dispose(saved.session, saved.policy); // Deliberate nonce disposal invalidates old ACKs, not this actual C7 scope. @@ -825,6 +1035,14 @@ export function retireInboxProbeCleanupLease( ) return false; commandMeters.get(saved.session)!.delete(saved.command); + if (coverage && coverage.entry.meter.generation() === coverage.generation) + qualifiedRemovals.set(proof, { + repository: saved.repository, + session: saved.session, + policy: saved.policy, + binding: coverage.binding, + scope: coverage.scope + }); saved.markRetired(); cleanupLeases.delete(lease); return true; diff --git a/web/src/lib/persistence/inbox-probe-cleanup.ts b/web/src/lib/persistence/inbox-probe-cleanup.ts @@ -1,14 +1,17 @@ import type { RelayPolicy } from '../config/relays.ts'; +import type { InboxOperatorQualification } from '../config/inbox-operators.ts'; import { inboxAccessConstructionBinding, - subscribeInboxAccessControllerClose + subscribeInboxAccessControllerClose, + type InboxAccessController } from '../messaging/inbox-access-controller.ts'; import { acquireInboxProbeCleanupLease, inboxProbeCleanupReady, inboxProbeCleanupLeaseCurrent, releaseInboxProbeCleanupLease, - retireInboxProbeCleanupLease + retireInboxProbeCleanupLease, + inboxProbeQualifiedRemovalBinding } from '../nostr/private-publisher.ts'; import { privateSessionOwnership, @@ -28,7 +31,8 @@ import { observePrivateRecord, removePrivateInboxProbe, type PrivateStorageRepository, - type PrivateStorageFailure + type PrivateStorageFailure, + type PrivateProbeRemovalProof } from './private-storage.ts'; declare const cleanupBrand: unique symbol; @@ -72,6 +76,9 @@ const removals = new WeakMap< repository: PrivateStorageRepository; session: PrivateSession; policy: RelayPolicy; + access: InboxAccessController; + operator: InboxOperatorQualification; + nativeProof: PrivateProbeRemovalProof; owner: string; command: string; eventId: string; @@ -275,6 +282,9 @@ export async function captureInboxProbeCleanup( repository, session, policy, + access: selected.access, + operator: selected.operator, + nativeProof: removed.value, owner: selected.record.owner, command: selected.record.id, eventId: selected.record.self!.eventId, @@ -359,6 +369,14 @@ export function inboxProbeRemovalAcknowledgementBinding( saved.current() ? { owner: saved.owner, + access: saved.access, + operator: saved.operator, + qualification: inboxProbeQualifiedRemovalBinding( + saved.nativeProof, + repository, + session, + policy + ), command: saved.command, eventId: saved.eventId, preferenceId: saved.preferenceId, diff --git a/web/src/lib/persistence/inbox-probes.ts b/web/src/lib/persistence/inbox-probes.ts @@ -32,6 +32,7 @@ import { inboxProbeRumorWire, inboxProbeReservationHandle, inboxProbeActionOwner, + inboxProbeOperatorBinding, stopInboxProbeIdentity, type InboxProbeIdentity } from '../nostr/inbox-access.ts'; @@ -1236,6 +1237,9 @@ type CleanupSelection = Readonly<{ policy: RelayPolicy; operation: NonceOperation; access: InboxAccessController; + operator: InboxOperatorQualification; + nonceReadReceipt: string; + admissions(): readonly string[]; record: PrivateAccessProbe; wire: string; current(): boolean; @@ -1363,8 +1367,17 @@ export function captureInboxProbeCleanupSelection( saved.source === 'construction' ? inboxProbeActionOwner(saved.identity, session, policy) : saved.access, - scope = access && inboxAccessConstructionBinding(access, session, policy); - if (!access || !scope) return undefined; + scope = access && inboxAccessConstructionBinding(access, session, policy), + operator = + saved.source === 'construction' + ? inboxProbeOperatorBinding( + saved.identity, + repository, + session, + policy + ) + : saved.operator; + if (!access || !scope || !operator) return undefined; function current() { return ( operation!.lineage.active() && @@ -1381,6 +1394,11 @@ export function captureInboxProbeCleanupSelection( policy, operation, access, + operator, + nonceReadReceipt: inboxProbeReadbackAttemptEvidence( + operation.observation + )!.receiptWire, + admissions: () => Array.from(positives.keys()), record: JSON.parse(JSON.stringify(record)) as PrivateAccessProbe, wire, current @@ -1410,6 +1428,9 @@ export function inboxProbeCleanupSelectionBinding( identity: saved.operation.lineage.identity, source: acknowledgements.get(saved.operation.acknowledgement)!.source, access: saved.access, + operator: saved.operator, + nonceReadReceipt: saved.nonceReadReceipt, + admissions: saved.admissions, nonce: saved.operation.acknowledgementToken()!, record: JSON.parse(JSON.stringify(saved.record)) as PrivateAccessProbe, wire: saved.wire, diff --git a/web/tests/e2e/harness/inbox-access-qualification.ts b/web/tests/e2e/harness/inbox-access-qualification.ts @@ -0,0 +1,221 @@ +import { makeCleanupFixture } from './inbox-probe-cleanup.ts'; +import { + validateInboxOperatorQualification, + inboxOperatorQualificationSnapshot +} from '../../../src/lib/config/inbox-operators.ts'; +import { + captureInboxProbeNonceReader, + captureRecoveredInboxProbeNonceReader, + readInboxProbeNonce, + readRecoveredInboxProbeNonce +} from '../../../src/lib/nostr/self-recovery-reader.ts'; +import { + commitInboxProbeNonceVerification, + type InboxProbeNonceAcknowledgement +} from '../../../src/lib/persistence/inbox-probes.ts'; +import { + qualifyInboxAccess, + qualifyRemovedInboxAccess, + observeQualifiedInboxAccess, + inboxAccessQualificationSnapshot, + type InboxAccessQualification +} from '../../../src/lib/messaging/inbox-access-qualification.ts'; +import { inboxAccessConstructionBinding } from '../../../src/lib/messaging/inbox-access-controller.ts'; +import { + createPublicView, + beginPublicViewRun, + disposePublicView +} from '../../../src/lib/runtime/public-runtime.ts'; +import { + resolveInboxPreference, + settleInboxResolver +} from '../../../src/lib/messaging/resolve-inbox.ts'; +import { captureUnlockedSession } from '../../../src/lib/messaging/unlocked-session.ts'; +import { + captureInboxSync, + startInboxSync, + stopInboxSync, + inboxSyncSnapshot, + type InboxSync +} from '../../../src/lib/messaging/inbox-sync.ts'; +export { + validateInboxOperatorQualification, + inboxOperatorQualificationWire +} from '../../../src/lib/config/inbox-operators.ts'; +export { + validateRelayPolicy, + readRelayPolicy +} from '../../../src/lib/config/relays.ts'; +export * from './inbox-probe-cleanup.ts'; +export * from '../../../src/lib/messaging/inbox-access-qualification.ts'; +export { + captureInboxSync, + inboxSyncSnapshot, + startInboxSync, + stopInboxSync +} from '../../../src/lib/messaging/inbox-sync.ts'; +export { captureUnlockedSession } from '../../../src/lib/messaging/unlocked-session.ts'; +export { closePrivateSession } from '../../../src/lib/runtime/private-session.ts'; +export async function makeQualificationFixture(authRequired = false) { + const base = await makeCleanupFixture(); + if (authRequired) { + const wire = inboxOperatorQualificationSnapshot(base.host.qualification)!; + const operator = validateInboxOperatorQualification( + JSON.stringify({ + ...wire, + relays: wire.relays.map((relay) => + relay.origin === 'wss://inbox.example.org' + ? { ...relay, auth: 'explicit_required' } + : relay + ) + }) + ); + if (!operator) + throw Error('actual explicitly required operator declaration'); + base.host.qualification = operator; + } + let qualification: InboxAccessQualification | undefined; + let latestNonce: InboxProbeNonceAcknowledgement | undefined; + let latestObservations: ReturnType<typeof base.observations> | undefined; + let sync: InboxSync | undefined; + const views: ReturnType<typeof createPublicView>[] = []; + return { + ...base, + qualification: () => qualification, + async renewQualificationNonce(recovered: boolean, origin: string) { + const observation = await (recovered + ? base.read(origin) + : base.originalRead(origin)); + if (!observation || observation.status !== 'readback') + throw Error('actual later readback'); + if ((await base.appendRead(observation)).status !== 'saved') + throw Error('actual later read append'); + const a = base.actors(); + const verified = recovered + ? await readRecoveredInboxProbeNonce( + captureRecoveredInboxProbeNonceReader( + base.repository, + a.identity, + a.session, + base.host.policy, + observation, + 'reviewed_inbox_probe_nonce_decryption' + )! + ) + : await readInboxProbeNonce( + captureInboxProbeNonceReader( + base.repository, + a.identity, + a.session, + base.host.policy, + observation, + 'reviewed_inbox_probe_nonce_decryption' + )! + ); + if (!('proof' in verified)) throw Error('actual later nonce proof'); + const saved = await commitInboxProbeNonceVerification( + base.repository, + a.session, + base.host.policy, + verified.proof + ); + if (!saved.acknowledgement) throw Error('actual later nonce native fact'); + latestNonce = saved.acknowledgement; + latestObservations = [...base.observations(), observation]; + return saved.status; + }, + async startOwnInbox() { + if (!qualification) throw Error('actual qualification missing'); + const runtime = base.sharedPublicRuntime(); + const a = base.actors(), + view = createPublicView(runtime), + resolver = resolveInboxPreference( + view, + beginPublicViewRun(view), + base.host.owner + ); + views.push(view); + await settleInboxResolver(resolver); + const unlocked = captureUnlockedSession( + a.session, + 'reviewed_messages_unlock' + ); + if (!unlocked) throw Error('actual unlocked scope'); + sync = captureInboxSync( + base.repository, + a.session, + base.host.policy, + resolver, + unlocked, + observeQualifiedInboxAccess(qualification), + 'reviewed_foreground_inbox' + ); + return !!sync && startInboxSync(sync, 'reviewed_foreground_inbox'); + }, + syncSnapshot: () => sync && inboxSyncSnapshot(sync), + stopOwnInbox() { + if (sync) stopInboxSync(sync); + }, + close() { + if (sync) stopInboxSync(sync); + for (const view of views) disposePublicView(view); + base.close(); + }, + context() { + const a = base.actors(), + scope = inboxAccessConstructionBinding( + a.access, + a.session, + base.host.policy + ); + if (!scope) throw Error('actual C7 scope missing'); + return { + owner: scope.owner, + session: scope.session, + preferenceId: scope.preferenceId, + readTargets: scope.readTargets.slice(), + archiveTargets: scope.archiveTargets.slice() + }; + }, + async qualifyAccess( + observations = latestObservations ?? base.observations() + ) { + const a = base.actors(), + result = await qualifyInboxAccess( + base.repository, + a.session, + base.host.policy, + a.access, + base.host.qualification, + latestNonce ?? base.nonce()!, + observations, + 'reviewed_qualify_inbox_access' + ); + if (result.qualification) qualification = result.qualification; + return result; + }, + qualifyRemoved() { + const a = base.actors(), + result = qualifyRemovedInboxAccess( + base.repository, + a.session, + base.host.policy, + a.access, + base.host.qualification, + base.removal()!, + 'reviewed_qualify_inbox_access' + ); + if (result.qualification) qualification = result.qualification; + return result; + }, + snapshot: () => + qualification && inboxAccessQualificationSnapshot(qualification), + observation( + context: Parameters<ReturnType<typeof observeQualifiedInboxAccess>>[0] + ) { + return ( + qualification && observeQualifiedInboxAccess(qualification)(context) + ); + } + }; +} diff --git a/web/tests/e2e/harness/inbox-probe-retry.ts b/web/tests/e2e/harness/inbox-probe-retry.ts @@ -158,6 +158,7 @@ export async function makeRetryFixture() { host, repository, actors: currentActor, + sharedPublicRuntime: () => runtime, originalIdentity: () => originalIdentity, originalAck: () => originalAck, proof: () => proof, diff --git a/web/tests/e2e/inbox-access-qualification.spec.ts b/web/tests/e2e/inbox-access-qualification.spec.ts @@ -0,0 +1,1375 @@ +import { test, expect, type Page } from '@playwright/test'; +import { build } from 'vite'; +import { once } from 'node:events'; +import { fileURLToPath } from 'node:url'; +import { WebSocketServer, type WebSocket } from 'ws'; +import { createStaticHarness } from '../integration/harness/static.ts'; +import type * as Fixture from './harness/inbox-access-qualification.ts'; +import type { PrivateAccessProbe } from '../../src/lib/persistence/private-records.ts'; +declare global { + interface Window { + qa: typeof Fixture; + qaFixture: Awaited<ReturnType<typeof Fixture.makeQualificationFixture>>; + qaPending?: Promise<unknown>; + qaRestore?: () => void; + qaFinishAttempt?: () => Promise<string>; + qaRelease?: () => void; + qaCloseMode?: 'hold' | 'fail'; + qaHeldClose?: (() => void)[]; + qaCloseCalls?: number; + } +} +let server: Awaited<ReturnType<typeof createStaticHarness>>, + sockets: WebSocketServer, + endpoint: string, + bundle: string, + head = ''; +let ackMode: 'accept' | 'refuse' | 'hold' = 'accept'; +let authMode: 'accept' | 'refuse' | 'hold' = 'accept'; +let holdRead = false, + challenge = false; +const origins = [ + 'wss://inbox.example.org', + 'wss://peer.example.org', + 'wss://archive.example.org' + ], + physical = new Set<WebSocket>(), + physicalOrigins = new WeakMap<WebSocket, string>(), + archived = new Map<string, unknown>(), + frames: { origin: string; frame: 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('actual loopback endpoint'); + endpoint = 'ws://127.0.0.1:' + address.port; + sockets.on('connection', (socket, request) => { + physical.add(socket); + socket.on('close', () => physical.delete(socket)); + const origin = new URL(request.url!, 'http://127.0.0.1').searchParams.get( + 'origin' + )!; + physicalOrigins.set(socket, origin); + if (challenge && origin !== 'wss://discovery.example.org') + socket.send(JSON.stringify(['AUTH', 's5a-source-challenge'])); + 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 (frames.length >= 1000) throw Error('controlled fixture frame bound'); + frames.push({ origin, frame }); + if (frame[0] === 'REQ') { + const filter = frame[2] as { kinds?: number[]; ids?: string[] }; + if (filter.kinds?.includes(10050) && head) + socket.send(JSON.stringify(['EVENT', frame[1], JSON.parse(head)])); + if (filter.kinds?.includes(1059)) { + if (holdRead) return; + const event = archived.get(JSON.stringify([origin, filter.ids?.[0]])); + if (event) socket.send(JSON.stringify(['EVENT', frame[1], event])); + } + socket.send(JSON.stringify(['EOSE', frame[1]])); + } else if (frame[0] === 'AUTH') { + const event = frame[1] as { id: string }; + if (authMode !== 'hold') + socket.send( + JSON.stringify([ + 'OK', + event.id, + authMode === 'accept', + 'controlled auth response' + ]) + ); + } else if (frame[0] === 'EVENT') { + const event = frame[1] as { id: string }; + if (ackMode === 'accept') + archived.set(JSON.stringify([origin, event.id]), event); + if (ackMode !== 'hold') + socket.send( + JSON.stringify([ + 'OK', + event.id, + ackMode === 'accept', + 'controlled refusal' + ]) + ); + } + }); + }); + const result = await build({ + configFile: false, + logLevel: 'silent', + build: { + write: false, + minify: false, + lib: { + entry: fileURLToPath( + new URL('./harness/inbox-access-qualification.ts', import.meta.url) + ), + name: 'qa', + formats: ['iife'] + } + } + }); + const output = Array.isArray(result) ? result[0] : result; + if (!('output' in output)) throw Error('actual compiled nonce-facts harness'); + const chunks = output.output.filter((x) => x.type === 'chunk'); + expect(chunks).toHaveLength(1); + bundle = chunks[0].code; +}); +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 }, testInfo) => { + await expect.poll(() => physical.size).toBe(0); + ackMode = 'accept'; + authMode = 'accept'; + holdRead = false; + challenge = false; + archived.clear(); + frames.length = 0; + head = ''; + await page.addInitScript( + ({ endpoint, origins }) => { + const Native = window.WebSocket; + window.WebSocket = class extends Native { + constructor(url: string | URL, protocols?: string | string[]) { + const origin = new URL(String(url)).origin; + if (!['wss://discovery.example.org', ...origins].includes(origin)) + throw Error('unapproved fixture origin'); + super(endpoint + '/?origin=' + encodeURIComponent(origin), protocols); + } + override close(code?: number, reason?: string) { + window.qaCloseCalls = (window.qaCloseCalls ?? 0) + 1; + if (window.qaCloseMode === 'fail') + throw Error('actual controlled physical close failure'); + if (window.qaCloseMode === 'hold') + (window.qaHeldClose ??= []).push(() => super.close(code, reason)); + else super.close(code, reason); + } + }; + }, + { endpoint, origins } + ); + await page.goto(server.url + '/search'); + await page.addScriptTag({ content: bundle }); + head = await page.evaluate( + async ({ origins, authRequired }) => { + window.qaFixture = await window.qa.makeQualificationFixture(authRequired); + return window.qaFixture.host.preferenceWire(origins); + }, + { origins, authRequired: testInfo.title.includes('required AUTH') } + ); + await page.evaluate(async () => { + const f = window.qaFixture; + await f.open(); + if ((await f.prepareOriginal()).status !== 'prepared') + throw Error('actual original S3/R1'); + }); +}); +test.afterEach(async ({ page }) => { + if (!page.isClosed()) + await page.evaluate(async () => { + window.qaRestore?.(); + window.qaCloseMode = undefined; + for (const release of window.qaHeldClose ?? []) release(); + window.qaRelease?.(); + window.qaFixture.host.mode('normal'); + window.qaFixture.host.settle(); + window.qaFixture.close(); + await window.qaPending; + }); +}); + +async function prepare(page: Page, recovered: boolean) { + expect( + await page.evaluate( + async (recovered) => (await window.qaFixture.qualify(recovered)).status, + recovered + ) + ).toBe('saved'); +} +for (const recovered of [false, true]) { + for (const mode of ['hold', 'fail'] as const) + test(`${recovered ? 'REC' : 'original'} qualification respects actual ${mode} physical cleanup without implicit retries`, async ({ + page + }) => { + await prepare(page, recovered); + await page.evaluate(async () => { + const f = window.qaFixture, + pool = window.qa.getPrivatePool( + f.actors().session, + f.host.policy, + ['wss://inbox.example.org'], + Object.freeze({}), + 'receive' + ); + if (!pool) throw Error('actual independent receive scope'); + const auth = await window.qa.beginInboxAuthentication( + pool, + 'wss://inbox.example.org', + 'reviewed_connection_auth' + ); + if (!auth) throw Error('actual independent AUTH connection'); + window.qaRelease = () => { + window.qa.closeInboxAuthentication(auth); + window.qa.closePrivatePool(pool); + }; + }); + await expect + .poll(() => + [...physical].some( + (socket) => + physicalOrigins.get(socket) === 'wss://inbox.example.org' + ) + ) + .toBe(true); + const result = await page.evaluate(async (mode) => { + const f = window.qaFixture; + window.qaCloseMode = mode; + let failed = false; + try { + window.qaRelease!(); + } catch { + failed = true; + } + const before = f.host.counts(), + closes = window.qaCloseCalls ?? 0, + held = window.qaHeldClose?.length ?? 0, + hook = f.nativeFault('read_loss'); + try { + const result = await f.qualifyAccess(); + return { + status: result.status, + current: !!window.qa.inboxProbeNonceAcknowledgementBinding( + f.repository, + f.actors().session, + f.nonce()!, + f.host.policy + ), + before, + after: f.host.counts(), + closes, + afterCloses: window.qaCloseCalls ?? 0, + held, + afterHeld: window.qaHeldClose?.length ?? 0, + failed, + native: hook.counts() + }; + } finally { + hook.restore(); + } + }, mode); + expect(result.status).toBe('busy'); + expect(result.current).toBe(true); + expect(result.after).toEqual(result.before); + expect(result.native.readonly).toBe(0); + expect(result.afterCloses).toBe(result.closes); + expect(result.afterHeld).toBe(result.held); + if (mode === 'fail') expect(result.failed).toBe(true); + else expect(result.held).toBeGreaterThan(0); + await page.evaluate(() => { + window.qaCloseMode = undefined; + for (const release of window.qaHeldClose ?? []) release(); + try { + window.qaRelease!(); + } catch (error) { + if ( + !(error instanceof Error) || + ![ + 'private_pool_close_pending', + 'private_pool_close_failed' + ].includes(error.message) + ) + throw error; + } + }); + await expect + .poll(() => page.evaluate(() => window.qaFixture.idle())) + .toBe(true); + expect( + await page.evaluate( + async () => (await window.qaFixture.qualifyAccess()).status + ) + ).toBe('qualified'); + }); + for (const foreign of [ + 'operator', + 'policy', + 'controller', + 'session', + 'repository' + ] as const) + test(`${recovered ? 'REC' : 'original'} removed qualification rejects different genuine or copied ${foreign} with no effects`, async ({ + page + }) => { + await prepare(page, recovered); + const result = await page.evaluate(async (foreign) => { + const f = window.qaFixture; + if (!(await f.select()) || (await f.remove()).status !== 'removed') + throw Error('actual reviewed removal'); + const a = f.actors(), + other = + foreign === 'controller' + ? { + access: (await f.replaceController())!, + session: a.session, + close() {} + } + : foreign === 'session' + ? await f.alternateController(true) + : undefined, + opened = + foreign === 'repository' + ? await window.qa.openBrowserDatabase() + : undefined, + repository = + opened?.state === 'ready' + ? window.qa.createPrivateStorageRepository( + opened.owner, + f.host.owner + )! + : f.repository, + policy = + foreign === 'policy' + ? window.qa.validateRelayPolicy( + JSON.stringify(window.qa.readRelayPolicy(f.host.policy)) + )! + : f.host.policy, + operator = + foreign === 'operator' + ? window.qa.validateInboxOperatorQualification( + window.qa.inboxOperatorQualificationWire( + f.host.qualification, + f.host.policy + )! + )! + : f.host.qualification, + before = f.host.counts(), + hook = f.nativeFault('read_loss'); + try { + const result = window.qa.qualifyRemovedInboxAccess( + repository, + other?.session ?? a.session, + policy, + other?.access ?? a.access, + operator, + f.removal()!, + 'reviewed_qualify_inbox_access' + ); + return { + status: result.status, + before, + after: f.host.counts(), + native: hook.counts() + }; + } finally { + hook.restore(); + other?.close(); + if (opened?.state === 'ready') + window.qa.closeBrowserDatabase(opened.owner); + } + }, foreign); + expect(result.status).toBe('invalid_scope'); + expect(result.after).toEqual(result.before); + expect(result.native.readonly).toBe(0); + expect(result.native.deletes).toBe(0); + }); + for (const forged of ['nonce', 'observations'] as const) + test(`${recovered ? 'REC' : 'original'} copied genuine ${forged} cannot substitute for applied source provenance`, async ({ + page + }) => { + await prepare(page, recovered); + const result = await page.evaluate(async (forged) => { + const f = window.qaFixture, + a = f.actors(), + before = f.host.counts(), + hook = f.nativeFault('read_loss'); + try { + const result = await window.qa.qualifyInboxAccess( + f.repository, + a.session, + f.host.policy, + a.access, + f.host.qualification, + forged === 'nonce' ? { ...f.nonce()! } : f.nonce()!, + forged === 'observations' + ? f.observations().map((x) => ({ ...x })) + : f.observations(), + 'reviewed_qualify_inbox_access' + ); + return { + status: result.status, + before, + after: f.host.counts(), + native: hook.counts() + }; + } finally { + hook.restore(); + } + }, forged); + expect(result.status).toBe('invalid_scope'); + expect(result.after).toEqual(result.before); + expect(result.native.readonly).toBe(0); + }); + test(`${recovered ? 'REC' : 'original'} a copied genuine removal cannot issue access and the exact real removal remains eligible`, async ({ + page + }) => { + await prepare(page, recovered); + const result = await page.evaluate(async () => { + const f = window.qaFixture, + a = f.actors(); + if (!(await f.select()) || (await f.remove()).status !== 'removed') + throw Error('actual successful reviewed removal'); + const before = f.host.counts(), + forged = window.qa.qualifyRemovedInboxAccess( + f.repository, + a.session, + f.host.policy, + a.access, + f.host.qualification, + { ...f.removal()! }, + 'reviewed_qualify_inbox_access' + ), + genuine = f.qualifyRemoved(); + return { + forged: forged.status, + genuine: genuine.status, + before, + after: f.host.counts() + }; + }); + expect(result.forged).toBe('invalid_scope'); + expect(result.genuine).toBe('qualified'); + expect(result.after).toEqual(result.before); + }); + test(`${recovered ? 'REC' : 'original'} wrong fresh owner key cannot qualify`, async ({ + page + }) => { + await prepare(page, recovered); + const result = await page.evaluate(async () => { + const f = window.qaFixture, + before = f.host.counts(), + hook = f.nativeFault('read_loss'); + f.host.mode('wrong_key'); + try { + const result = await f.qualifyAccess(); + return { + status: result.status, + before, + after: f.host.counts(), + native: hook.counts() + }; + } finally { + f.host.mode('normal'); + hook.restore(); + } + }); + expect(result.status).toBe('stopped'); + expect(result.after).toEqual({ + ...result.before, + keys: result.before.keys + 1 + }); + expect(result.native.readonly).toBe(0); + }); + test(`${recovered ? 'REC' : 'original'} explicit qualification Stop prevents reuse of the same genuine nonce`, async ({ + page + }) => { + await prepare(page, recovered); + const result = await page.evaluate(async () => { + const f = window.qaFixture, + first = await f.qualifyAccess(), + token = first.qualification!, + context = f.context(), + before = f.host.counts(); + window.qa.stopInboxAccessQualification(token); + const again = await f.qualifyAccess(); + return { + current: + window.qa.observeQualifiedInboxAccess(token)(context)?.current() ?? + false, + snapshot: window.qa.inboxAccessQualificationSnapshot(token), + status: again.status, + before, + after: f.host.counts() + }; + }); + expect(result).toMatchObject({ current: false, status: 'stopped' }); + expect(result.snapshot).toBeUndefined(); + expect(result.after).toEqual(result.before); + }); + test(`${recovered ? 'REC' : 'original'} unrelated actual SDK local storage work does not invalidate issued access`, async ({ + page + }) => { + await prepare(page, recovered); + const result = await page.evaluate(async () => { + const f = window.qaFixture; + await f.qualifyAccess(); + const context = f.context(), + before = f.host.counts(); + const during = await f.withHeld('SDK', async () => ({ + current: f.observation(context)?.current(), + status: (await f.qualifyAccess()).status + })); + return { + during, + afterCurrent: f.observation(context)?.current(), + before, + after: f.host.counts() + }; + }); + expect(result).toMatchObject({ + during: { current: true, status: 'qualified' }, + afterCurrent: true + }); + expect(result.after).toEqual(result.before); + }); + for (const lane of ['archive', 'read'] as const) + test(`${recovered ? 'REC' : 'original'} later actual selected ${lane} immediately and permanently invalidates issued access`, async ({ + page + }) => { + await prepare(page, recovered); + expect( + await page.evaluate( + async () => (await window.qaFixture.qualifyAccess()).status + ) + ).toBe('qualified'); + const mark = traffic().length; + if (lane === 'archive') ackMode = 'hold'; + else holdRead = true; + await page.evaluate( + ({ recovered, lane }) => { + const f = window.qaFixture; + window.qaPending = + lane === 'archive' + ? recovered + ? f.publish('wss://peer.example.org') + : f.originalPublish('wss://peer.example.org') + : recovered + ? f.read('wss://peer.example.org') + : f.originalRead('wss://peer.example.org'); + }, + { recovered, lane } + ); + await expect.poll(() => traffic().length).toBeGreaterThan(mark); + const during = await page.evaluate(async () => { + const f = window.qaFixture, + before = f.host.counts(), + result = await f.qualifyAccess(); + return { + status: result.status, + current: f.observation(f.context())?.current() ?? false, + before, + after: f.host.counts() + }; + }); + expect(during.status).toBe('stopped'); + expect(during.current).toBe(false); + expect(during.after).toEqual(during.before); + const actual = traffic() + .slice(mark) + .find((x) => x.frame[0] === (lane === 'archive' ? 'EVENT' : 'REQ'))!; + for (const socket of physical) + if (physicalOrigins.get(socket) === actual.origin) { + if (lane === 'archive') { + const event = actual.frame[1] as { id: string }; + archived.set(JSON.stringify([actual.origin, event.id]), event); + socket.send( + JSON.stringify([ + 'OK', + event.id, + true, + 'actual held archive accepted' + ]) + ); + } else socket.send(JSON.stringify(['EOSE', actual.frame[1]])); + } + const final = await page.evaluate(async () => { + const attempt = (await window.qaPending) as { status: string }; + const f = window.qaFixture, + before = f.host.counts(), + again = await f.qualifyAccess(); + return { + attempt: attempt.status, + status: again.status, + current: f.observation(f.context())?.current() ?? false, + before, + after: f.host.counts() + }; + }); + expect(final.attempt).toBe(lane === 'archive' ? 'accepted' : 'empty'); + expect(final.status).toBe('stopped'); + expect(final.current).toBe(false); + expect(final.after).toEqual(final.before); + }); + test(`${recovered ? 'REC' : 'original'} unapplied archive blocks first qualification and later append cannot revive that input`, async ({ + page + }) => { + await prepare(page, recovered); + const result = await page.evaluate(async (recovered) => { + const f = window.qaFixture, + archive = await (recovered + ? f.publish('wss://peer.example.org') + : f.originalPublish('wss://peer.example.org')); + if (!archive || archive.status !== 'accepted') + throw Error('actual accepted archive'); + const before = f.host.counts(), + first = await f.qualifyAccess(), + after = f.host.counts(), + appended = await f.append(archive), + again = await f.qualifyAccess([...f.observations(), archive]); + return { + first: first.status, + again: again.status, + appended: appended.status, + before, + after + }; + }, recovered); + expect(result).toMatchObject({ + first: 'stopped', + again: 'stopped', + appended: 'saved' + }); + expect(result.after).toEqual(result.before); + }); + test(`${recovered ? 'REC' : 'original'} an actual cleanup lease and aborted delete permanently retire the issued journal fence`, async ({ + page + }) => { + await prepare(page, recovered); + const result = await page.evaluate(async () => { + const f = window.qaFixture, + first = await f.qualifyAccess(), + old = window.qa.observeQualifiedInboxAccess(first.qualification!)( + f.context() + )!; + if (!(await f.select())) throw Error('actual selected cleanup'); + const hook = f.nativeFault('abort'); + try { + const removal = await f.remove(), + before = f.host.counts(), + current = old.current(), + again = await f.qualifyAccess(); + const rows = (await f.host.stored()).length; + return { + removed: removal.status, + counts: hook.counts(), + current, + again: again.status, + before, + after: f.host.counts(), + rows + }; + } finally { + hook.restore(); + } + }); + expect(result.removed).toBe('aborted'); + expect(result.counts).toMatchObject({ + deletes: 1, + completes: 0, + aborts: 1 + }); + expect(result.rows).toBe(1); + expect(result.current).toBe(false); + expect(result.again).toBe('stopped'); + expect(result.after).toEqual(result.before); + }); + for (const mode of ['accept', 'refuse', 'hold'] as const) + test(`${recovered ? 'REC' : 'original'} required AUTH ${mode} uses actual C7 response and challenge currentness`, async ({ + page + }) => { + await prepare(page, recovered); + const before = await page.evaluate(() => window.qaFixture.host.counts()); + expect( + await page.evaluate( + async () => (await window.qaFixture.qualifyAccess()).status + ) + ).toBe('invalid_scope'); + expect(await page.evaluate(() => window.qaFixture.host.counts())).toEqual( + before + ); + challenge = true; + expect(['waiting', 'challenge']).toContain( + await page.evaluate(async () => + window.qa.authenticateInboxAccess( + window.qaFixture.actors().access, + 'wss://inbox.example.org', + 'reviewed_inbox_connection_auth' + ) + ) + ); + for (const socket of physical) + if (physicalOrigins.get(socket) === 'wss://inbox.example.org') + socket.send(JSON.stringify(['AUTH', 's5a-source-challenge'])); + await expect + .poll(() => + page.evaluate( + () => + window.qa + .inboxAccessControllerSnapshot(window.qaFixture.actors().access) + ?.auth.find((x) => x.origin === 'wss://inbox.example.org') + ?.state + ) + ) + .toBe('challenge'); + expect( + await page.evaluate( + async () => (await window.qaFixture.qualifyAccess()).status + ) + ).toBe('invalid_scope'); + authMode = mode; + await page.evaluate(() => { + window.qaPending = window.qa.respondInboxAccessAuthentication( + window.qaFixture.actors().access, + 'wss://inbox.example.org', + 'reviewed_inbox_auth_response' + ); + }); + await expect + .poll(() => frames.filter((x) => x.frame[0] === 'AUTH').length) + .toBe(1); + if (mode === 'hold') { + expect( + await page.evaluate( + async () => (await window.qaFixture.qualifyAccess()).status + ) + ).toBe('invalid_scope'); + // Complete this exact held response on its actual connection. + const sent = frames.find((x) => x.frame[0] === 'AUTH')!, + event = sent.frame[1] as { id: string }; + for (const socket of physical) + if (physicalOrigins.get(socket) === sent.origin) + socket.send( + JSON.stringify([ + 'OK', + event.id, + true, + 'controlled held auth accepted' + ]) + ); + } + expect(await page.evaluate(async () => await window.qaPending)).toBe( + mode === 'refuse' ? 'refused' : 'accepted' + ); + const result = await page.evaluate(async () => { + const f = window.qaFixture, + before = f.host.counts(), + q = await f.qualifyAccess(); + return { + status: q.status, + before, + after: f.host.counts(), + current: f.observation(f.context())?.current() + }; + }); + if (mode === 'refuse') { + expect(result.status).toBe('invalid_scope'); + expect(result.after).toEqual(result.before); + } else { + expect(result.status).toBe('qualified'); + expect(result.current).toBe(true); + for (const socket of physical) + if (physicalOrigins.get(socket) === 'wss://inbox.example.org') + socket.send(JSON.stringify(['AUTH', 's5a-new-real-challenge'])); + await expect + .poll(() => + page.evaluate( + () => + window.qa.inboxAccessControllerSnapshot( + window.qaFixture.actors().access + )?.auth[0]?.state + ) + ) + .toBe('challenge'); + expect( + await page.evaluate( + () => + window.qaFixture + .observation(window.qaFixture.context()) + ?.current() ?? false + ) + ).toBe(false); + } + }); + for (const held of ['lock', 'SDK'] as const) + test(`${recovered ? 'REC' : 'original'} actual ${held} contention refuses before provider and permits an explicit retry`, async ({ + page + }) => { + await prepare(page, recovered); + const result = await page.evaluate(async (held) => { + const f = window.qaFixture, + before = f.host.counts(), + hook = f.nativeFault('read_loss'); + try { + const denied = await f.withHeld(held, () => f.qualifyAccess()), + during = hook.counts(), + after = f.host.counts(), + retry = await f.qualifyAccess(); + return { + status: denied.status, + before, + after, + during, + retry: retry.status + }; + } finally { + hook.restore(); + } + }, held); + expect(result.status).toBe('busy'); + expect(result.after).toEqual(result.before); + expect(result.during.readonly).toBe(0); + expect(result.retry).toBe('qualified'); + }); + for (const kind of [ + 'missing', + 'changed', + 'corrupt_tail', + 'alias', + 'foreign_tail' + ] as const) + test(`${recovered ? 'REC' : 'original'} actual native ${kind} is checked before qualification`, async ({ + page + }) => { + await prepare(page, recovered); + const result = await page.evaluate(async (kind) => { + const f = window.qaFixture, + row = (await f.host.stored()).find((x) => x.id === f.command())!; + if (kind === 'missing') await f.removeFixtureRow(); + else if (kind === 'changed') { + const record = JSON.parse(row.wire) as PrivateAccessProbe; + await f.host.inject([ + { + ...row, + wire: JSON.stringify({ ...record, revision: record.revision + 1 }) + } + ]); + } else if (kind === 'alias') + await f.host.inject([{ ...row, id: crypto.randomUUID() }]); + else + await f.host.inject([ + { + owner: kind === 'foreign_tail' ? 'f'.repeat(64) : f.host.owner, + id: crypto.randomUUID(), + wire: '{' + } + ]); + const rows = await f.host.stored(), + before = f.host.counts(), + result = await f.qualifyAccess(), + after = f.host.counts(); + return { + status: result.status, + before, + after, + unchanged: + JSON.stringify(rows) === JSON.stringify(await f.host.stored()) + }; + }, kind); + if (kind === 'foreign_tail') expect(result.status).toBe('qualified'); + else expect(result.status).not.toBe('qualified'); + expect(result.after).toEqual({ + ...result.before, + keys: result.before.keys + 1 + }); + expect(result.unchanged).toBe(true); + }); + for (const at of ['provider', 'native'] as const) + for (const loss of ['head', 'controller', 'session'] as const) + test(`${recovered ? 'REC' : 'original'} genuine ${loss} loss at ${at} cannot issue access`, async ({ + page + }) => { + await prepare(page, recovered); + const result = await page.evaluate( + async ({ at, loss }) => { + const f = window.qaFixture, + a = f.actors(); + let losses = 0; + const lose = () => { + losses++; + if (loss === 'head') a.churnHead(); + else if (loss === 'session') + window.qa.closePrivateSession(a.session); + else f.stop(); + }; + const off = + at === 'provider' ? f.host.keyCallback(1, lose) : undefined; + const hook = + at === 'native' ? f.nativeFault('read_loss', lose) : undefined; + const before = f.host.counts(); + try { + const result = await f.qualifyAccess(); + return { + status: result.status, + before, + after: f.host.counts(), + losses, + native: hook?.counts() + }; + } finally { + off?.(); + hook?.restore(); + } + }, + { at, loss } + ); + expect(result.losses).toBe(1); + expect(result.status).not.toBe('qualified'); + expect(result.after).toEqual({ + ...result.before, + keys: result.before.keys + 1 + }); + if (at === 'native') expect(result.native?.deletes).toBe(0); + }); + test(`${recovered ? 'REC' : 'original'} actual native qualification read abort cannot issue access`, async ({ + page + }) => { + await prepare(page, recovered); + const result = await page.evaluate(async () => { + const f = window.qaFixture, + hook = f.nativeFault('initial_read_abort'); + try { + const result = await f.qualifyAccess(); + return { status: result.status, counts: hook.counts() }; + } finally { + hook.restore(); + } + }); + expect(result.status).not.toBe('qualified'); + expect(result.counts.readonly).toBe(1); + expect(result.counts.deletes).toBe(0); + }); + test(`${recovered ? 'REC' : 'original'} held fresh key serializes reentry and controller stop fences late settlement`, async ({ + page + }) => { + await prepare(page, recovered); + await page.evaluate(() => { + const f = window.qaFixture; + f.host.mode('hold_key'); + window.qaPending = f.qualifyAccess(); + }); + await expect + .poll(() => page.evaluate(() => window.qaFixture.host.waiting())) + .toBe('key'); + const during = await page.evaluate(async () => { + const f = window.qaFixture, + before = f.host.counts(), + second = await f.qualifyAccess(); + f.stop(); + f.host.settle(); + const first = await window.qaPending; + return { before, after: f.host.counts(), second: second.status, first }; + }); + expect(during.second).toBe('busy'); + expect(during.after).toEqual(during.before); + expect(during.first).toMatchObject({ status: 'stopped' }); + }); + for (const foreign of ['controller', 'session', 'repository'] as const) + test(`${recovered ? 'REC' : 'original'} different genuine ${foreign} cannot consume source qualification`, async ({ + page + }) => { + await prepare(page, recovered); + const result = await page.evaluate(async (foreign) => { + const f = window.qaFixture, + a = f.actors(), + other = + foreign === 'controller' + ? { + access: (await f.replaceController())!, + session: a.session, + close() {} + } + : foreign === 'session' + ? await f.alternateController(true) + : undefined, + opened = + foreign === 'repository' + ? await window.qa.openBrowserDatabase() + : undefined; + const repository = + opened?.state === 'ready' + ? window.qa.createPrivateStorageRepository( + opened.owner, + f.host.owner + )! + : f.repository; + const before = f.host.counts(), + hook = f.nativeFault('read_loss'); + try { + const result = await window.qa.qualifyInboxAccess( + repository, + other?.session ?? a.session, + f.host.policy, + other?.access ?? a.access, + f.host.qualification, + f.nonce()!, + f.observations(), + 'reviewed_qualify_inbox_access' + ); + return { + status: result.status, + before, + after: f.host.counts(), + native: hook.counts() + }; + } finally { + hook.restore(); + other?.close(); + if (opened?.state === 'ready') + window.qa.closeBrowserDatabase(opened.owner); + } + }, foreign); + expect(result.status).toBe('invalid_scope'); + expect(result.after).toEqual(result.before); + expect(result.native.readonly).toBe(0); + }); + test(`${recovered ? 'REC' : 'original'} a genuinely later applied read and distinct nonce restores access within the original meter`, async ({ + page + }) => { + await prepare(page, recovered); + archived.clear(); + expect( + await page.evaluate(async (recovered) => { + const f = window.qaFixture; + return ( + await (recovered + ? f.read('wss://inbox.example.org') + : f.originalRead('wss://inbox.example.org')) + )?.status; + }, recovered) + ).toBe('empty'); + expect( + await page.evaluate( + async () => (await window.qaFixture.qualifyAccess()).status + ) + ).toBe('stopped'); + // Restore only the actual signed archived event, through a real accepted EVENT. + expect( + await page.evaluate(async (recovered) => { + const f = window.qaFixture, + archive = await (recovered + ? f.publish('wss://peer.example.org') + : f.originalPublish('wss://peer.example.org')); + if (!archive) throw Error('actual remaining archive attempt'); + return (await f.append(archive)).status; + }, recovered) + ).toBe('saved'); + expect( + await page.evaluate( + async (recovered) => + window.qaFixture.renewQualificationNonce( + recovered, + 'wss://peer.example.org' + ), + recovered + ) + ).toBe('saved'); + expect( + await page.evaluate( + async () => (await window.qaFixture.qualifyAccess()).status + ) + ).toBe('qualified'); + }); + for (const afterRemoval of [false, true]) + test(`${recovered ? 'REC' : 'original'} later applied archive cannot mask an unaccounted read ${afterRemoval ? 'through removal' : 'before first qualification'}`, async ({ + page + }) => { + await prepare(page, recovered); + archived.clear(); + const result = await page.evaluate( + async ({ recovered, afterRemoval }) => { + const f = window.qaFixture, + read = await (recovered + ? f.read('wss://peer.example.org') + : f.originalRead('wss://peer.example.org')), + archive = await (recovered + ? f.publish('wss://archive.example.org') + : f.originalPublish('wss://archive.example.org')); + if (!archive || archive.status !== 'accepted') + throw Error('actual later accepted archive'); + const appended = await f.append(archive), + observations = [...f.observations(), archive], + before = f.host.counts(); + let status: string; + let removed: string | undefined; + if (afterRemoval) { + if ( + !(await f.select( + 'reviewed_inbox_probe_cleanup_selection', + observations + )) + ) + throw Error('actual selection with later archive'); + removed = (await f.remove()).status; + status = f.qualifyRemoved().status; + } else status = (await f.qualifyAccess(observations)).status; + return { + read: read?.status, + appended: appended.status, + status, + removed, + coverage: !!f.removalBinding()?.qualification, + before, + after: f.host.counts() + }; + }, + { recovered, afterRemoval } + ); + expect(result.read).toBe('empty'); + expect(result.appended).toBe('saved'); + if (afterRemoval) { + expect(result.removed).toBe('removed'); + expect(result.coverage).toBe(false); + expect(result.status).toBe('invalid_scope'); + } else { + expect(result.status).toBe('stopped'); + expect(result.after).toEqual(result.before); + } + }); + test(`${recovered ? 'REC' : 'original'} actual retained journal qualifies with one fresh key and no crypto/network/write`, async ({ + page + }) => { + await prepare(page, recovered); + const beforeTraffic = traffic().length; + const result = await page.evaluate(async () => { + const f = window.qaFixture, + before = f.host.counts(), + rows = await f.host.stored(), + first = await f.qualifyAccess(), + token = first.qualification!, + context = f.context(), + observation = f.observation(context), + after = f.host.counts(), + again = await f.qualifyAccess(); + return { + status: first.status, + before, + after, + repeated: f.host.counts(), + same: again.qualification === token, + current: observation?.current(), + snapshot: f.snapshot(), + unchanged: + JSON.stringify(rows) === JSON.stringify(await f.host.stored()), + copied: !!window.qa.observeQualifiedInboxAccess({ ...token })(context) + }; + }); + expect(result.status).toBe('qualified'); + expect(result.after).toEqual({ + ...result.before, + keys: result.before.keys + 1 + }); + expect(result.repeated).toEqual(result.after); + expect(result).toMatchObject({ + same: true, + current: true, + unchanged: true, + copied: false, + snapshot: { authority: 'source_fixture', sourceOnly: true } + }); + expect(traffic().length).toBe(beforeTraffic); + }); + test(`${recovered ? 'REC' : 'original'} actual successful cleanup preserves independent qualified coverage`, async ({ + page + }) => { + await prepare(page, recovered); + const result = await page.evaluate(async () => { + const f = window.qaFixture, + initial = await f.qualifyAccess(), + old = window.qa.observeQualifiedInboxAccess(initial.qualification!)( + f.context() + )!; + if (!(await f.select())) throw Error('actual cleanup selection'); + const removed = await f.remove(), + before = f.host.counts(), + qualified = f.qualifyRemoved(), + after = f.host.counts(); + return { + removed: removed.status, + status: qualified.status, + before, + after, + old: old.current(), + current: f.observation(f.context())?.current(), + native: (await f.host.stored()).length, + coverage: !!f.removalBinding()?.qualification + }; + }); + expect(result).toMatchObject({ + removed: 'removed', + status: 'qualified', + old: false, + current: true, + native: 0, + coverage: true + }); + expect(result.after).toEqual(result.before); + }); + for (const beforeFirst of [false, true]) + test(`${recovered ? 'REC' : 'original'} unjournaled read gap ${beforeFirst ? 'before first issuance' : 'after issuance'} never revives access through cleanup`, async ({ + page + }) => { + await prepare(page, recovered); + if (!beforeFirst) + expect( + await page.evaluate( + async () => (await window.qaFixture.qualifyAccess()).status + ) + ).toBe('qualified'); + archived.clear(); + const result = await page.evaluate(async (recovered) => { + const f = window.qaFixture, + rows = await f.host.stored(), + read = await (recovered + ? f.read('wss://peer.example.org') + : f.originalRead('wss://peer.example.org')), + before = f.host.counts(), + qualified = await f.qualifyAccess(), + after = f.host.counts(), + unchanged = + JSON.stringify(rows) === JSON.stringify(await f.host.stored()); + if (!(await f.select())) + throw Error('genuine C3B cleanup still eligible'); + const removal = await f.remove(), + postBefore = f.host.counts(), + post = f.qualifyRemoved(), + postAfter = f.host.counts(); + return { + read: read?.status, + status: qualified.status, + before, + after, + unchanged, + removed: removal.status, + post: post.status, + postBefore, + postAfter, + coverage: !!f.removalBinding()?.qualification, + rows: (await f.host.stored()).length + }; + }, recovered); + expect(result).toMatchObject({ + read: 'empty', + status: 'stopped', + unchanged: true, + removed: 'removed', + post: 'invalid_scope', + coverage: false, + rows: 0 + }); + expect(result.after).toEqual(result.before); + expect(result.postAfter).toEqual(result.postBefore); + }); + for (const removedPath of [false, true]) + test(`${recovered ? 'REC' : 'original'} ${removedPath ? 'removed' : 'journal'} genuine qualification survives its own actual foreground inbox`, async ({ + page + }) => { + await prepare(page, recovered); + expect( + await page.evaluate(async (removedPath) => { + const f = window.qaFixture; + if (!removedPath) return (await f.qualifyAccess()).status; + if (!(await f.select()) || (await f.remove()).status !== 'removed') + throw Error('actual own-inbox reviewed removal'); + return f.qualifyRemoved().status; + }, removedPath) + ).toBe('qualified'); + expect( + await page.evaluate(async () => await window.qaFixture.startOwnInbox()) + ).toBe(true); + await expect + .poll( + async () => + await page.evaluate(() => window.qaFixture.syncSnapshot()?.state) + ) + .toBe('live'); + expect( + await page.evaluate(() => + window.qaFixture.observation(window.qaFixture.context())?.current() + ) + ).toBe(true); + expect(traffic().some((x) => x.frame[0] === 'REQ')).toBe(true); + const firstStop = await page.evaluate(() => { + try { + window.qaFixture.stopOwnInbox(); + return 'closed'; + } catch (error) { + if ( + error instanceof Error && + error.message === 'private_inbox_cleanup_required' + ) + return 'physical_close_pending'; + throw error; + } + }); + if (firstStop === 'physical_close_pending') { + await expect + .poll( + () => + Array.from(physical).filter( + (socket) => + physicalOrigins.get(socket) !== 'wss://discovery.example.org' + ).length + ) + .toBe(0); + await page.evaluate(() => window.qaFixture.stopOwnInbox()); + } + }); + for (const kind of ['operator', 'policy'] as const) + test(`${recovered ? 'REC' : 'original'} same-wire copied ${kind} is not qualification provenance`, async ({ + page + }) => { + await prepare(page, recovered); + const result = await page.evaluate(async (kind) => { + const f = window.qaFixture, + a = f.actors(), + before = f.host.counts(), + policy = + kind === 'policy' + ? window.qa.validateRelayPolicy( + JSON.stringify(window.qa.readRelayPolicy(f.host.policy)) + )! + : f.host.policy, + operator = + kind === 'operator' + ? window.qa.validateInboxOperatorQualification( + window.qa.inboxOperatorQualificationWire( + f.host.qualification, + f.host.policy + )! + )! + : f.host.qualification, + result = await window.qa.qualifyInboxAccess( + f.repository, + a.session, + policy, + a.access, + operator, + f.nonce()!, + f.observations(), + 'reviewed_qualify_inbox_access' + ); + return { status: result.status, before, after: f.host.counts() }; + }, kind); + expect(result.status).toBe('invalid_scope'); + expect(result.after).toEqual(result.before); + }); +} + +const traffic = () => + frames.filter( + (x) => + x.origin !== 'wss://discovery.example.org' && + ['EVENT', 'REQ', 'AUTH'].includes(String(x.frame[0])) + ); diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs @@ -615,6 +615,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; 'src/lib/persistence/private-storage.ts', 'src/lib/persistence/inbox-probes.ts', 'src/lib/persistence/inbox-probe-cleanup.ts', + 'src/lib/messaging/inbox-access-qualification.ts', 'src/lib/persistence/private-records.ts' ]) { for (const change of ['changed', 'missing']) { @@ -1973,6 +1974,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; 'src/lib/nostr/private-publisher.ts', 'src/lib/persistence/inbox-probes.ts', 'src/lib/persistence/inbox-probe-cleanup.ts', + 'src/lib/messaging/inbox-access-qualification.ts', 'src/lib/nostr/inbox-access.ts', 'src/lib/nostr/seal-builder.ts', 'src/lib/nostr/giftwrap-builder.ts', diff --git a/web/tests/unit/inbox-access-qualification.test.ts b/web/tests/unit/inbox-access-qualification.test.ts @@ -0,0 +1,125 @@ +import { afterEach, expect, it, vi } from 'vitest'; +afterEach(() => vi.unstubAllGlobals()); +for (const browser of [false, true]) + it(`cold ${browser ? 'browser-shaped' : 'SSR'} access qualification rejects forged provenance before all effects`, async () => { + vi.resetModules(); + let effects = 0; + const trap = () => { + effects++; + throw Error('unadmitted qualification effect'); + }; + if (browser) { + vi.stubGlobal('window', { + get nostr() { + return trap(); + } + }); + vi.stubGlobal('navigator', { + get locks() { + return trap(); + } + }); + vi.stubGlobal('indexedDB', { open: trap }); + vi.stubGlobal('WebSocket', trap); + } + const q = + await import('../../src/lib/messaging/inbox-access-qualification.ts'), + p = await import('../../src/lib/nostr/private-publisher.ts'), + a = await import('../../src/lib/nostr/inbox-access.ts'); + type Args = Parameters<typeof q.qualifyInboxAccess>; + const repository = {} as Args[0], + session = {} as Args[1], + policy = {} as Args[2], + access = {} as Args[3], + operator = {} as Args[4]; + const context = { + get owner(): string { + return trap(); + }, + get session(): symbol { + return trap(); + }, + get preferenceId(): string { + return trap(); + }, + get readTargets(): string[] { + return trap(); + }, + get archiveTargets(): string[] { + return trap(); + } + }; + for (const value of [ + undefined, + null, + false, + 0, + '', + Symbol(), + {}, + { status: 'qualified', current: () => true, authority: 'operator' }, + { status: 'removed', qualification: {}, generation: 1 } + ]) { + expect( + ( + await q.qualifyInboxAccess( + repository, + session, + policy, + access, + operator, + value as Args[5], + [], + 'reviewed_qualify_inbox_access' + ) + ).qualification + ).toBeUndefined(); + expect( + q.qualifyRemovedInboxAccess( + repository, + session, + policy, + access, + operator, + value as Parameters<typeof q.qualifyRemovedInboxAccess>[5], + 'reviewed_qualify_inbox_access' + ).qualification + ).toBeUndefined(); + const token = value as Parameters< + typeof q.observeQualifiedInboxAccess + >[0]; + expect(q.observeQualifiedInboxAccess(token)(context)).toBeUndefined(); + expect(q.inboxAccessQualificationSnapshot(token)).toBeUndefined(); + q.stopInboxAccessQualification(token); + expect( + p.captureInboxProbeQualificationFence( + repository, + session, + policy, + value as Parameters<typeof p.captureInboxProbeQualificationFence>[3] + ) + ).toBeUndefined(); + expect( + p.inboxProbeQualificationFenceCurrent( + value as Parameters<typeof p.inboxProbeQualificationFenceCurrent>[0] + ) + ).toBe(false); + expect( + p.inboxProbeQualifiedRemovalBinding( + value as Parameters<typeof p.inboxProbeQualifiedRemovalBinding>[0], + repository, + session, + policy + ) + ).toBeUndefined(); + expect( + a.inboxProbeOperatorBinding( + value as Parameters<typeof a.inboxProbeOperatorBinding>[0], + repository, + session, + policy + ) + ).toBeUndefined(); + } + expect(effects).toBe(0); + }); diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs @@ -319,17 +319,19 @@ async function operationalFlagsAdmission(web) { 'src/lib/nostr/self-recovery-reader.ts': 'e6bd782a80dedc2b8b0e5650f717af3e9516c4e66d15f2361b73adcb2763a3d5', 'src/lib/nostr/private-publisher.ts': - '13fba9d8c93e6c530d97bbac79debc60892069daaee47cabd879e3aa7ab4910a', + 'f79623b5a9561358a2d75ff1bdd15c7d85c723d3f0007a8edb17d7b56eaa8310', 'src/lib/nostr/private-pool.ts': '2ed123596f26bedb8aab5ec7694be6e264616429e00f745f1614c83f52de9825', 'src/lib/nostr/inbox-ingress.ts': 'f860a094a8ba767585124c795d44b7620064f73a5b3a0170041c581c0fc64ecb', 'src/lib/persistence/inbox-probes.ts': - '3c891f5a540f2cae07bed29a53f73feb8cacc0bef3a75c8c22acb015c4b519fa', + '7d16f44c6fb8ec1168e6c93b669ca3eb404529e8b1783e29694a182db7649cc7', 'src/lib/persistence/inbox-probe-cleanup.ts': - '44a7988b4a52e0a2c5971d7d9ee3c268ffa316d14c920cf2fb75be0d5a7fc375', + 'bfc24be3530471cccd01d387ed2b38a6534eb6493ce850ba9711cc3cfa77e6d9', + 'src/lib/messaging/inbox-access-qualification.ts': + 'f936a1507661eaa9f760b7f1b9775fac4893ad6d1f61b27c72eee0ffbf7990a3', 'src/lib/nostr/inbox-access.ts': - '16eef55d0ffcf2c3291573ddcb0b6a1432bb77abce0017a69e9b6f82414609a7', + '2d9ba6c6ef1e11a1296ab377fd35c4b3e6fdff22de3f97cc85cfe0fc15baa015', 'src/lib/nostr/seal-builder.ts': '3ccc967cc348e63857243ff6f0302c1a68da2afe85ca2c37e00d5a894785fc53', 'src/lib/nostr/giftwrap-builder.ts': @@ -599,17 +601,19 @@ async function privacyDataAdmission(web) { 'src/lib/nostr/self-recovery-reader.ts': 'e6bd782a80dedc2b8b0e5650f717af3e9516c4e66d15f2361b73adcb2763a3d5', 'src/lib/nostr/private-publisher.ts': - '13fba9d8c93e6c530d97bbac79debc60892069daaee47cabd879e3aa7ab4910a', + 'f79623b5a9561358a2d75ff1bdd15c7d85c723d3f0007a8edb17d7b56eaa8310', 'src/lib/nostr/private-pool.ts': '2ed123596f26bedb8aab5ec7694be6e264616429e00f745f1614c83f52de9825', 'src/lib/nostr/inbox-ingress.ts': 'f860a094a8ba767585124c795d44b7620064f73a5b3a0170041c581c0fc64ecb', 'src/lib/persistence/inbox-probes.ts': - '3c891f5a540f2cae07bed29a53f73feb8cacc0bef3a75c8c22acb015c4b519fa', + '7d16f44c6fb8ec1168e6c93b669ca3eb404529e8b1783e29694a182db7649cc7', 'src/lib/persistence/inbox-probe-cleanup.ts': - '44a7988b4a52e0a2c5971d7d9ee3c268ffa316d14c920cf2fb75be0d5a7fc375', + 'bfc24be3530471cccd01d387ed2b38a6534eb6493ce850ba9711cc3cfa77e6d9', + 'src/lib/messaging/inbox-access-qualification.ts': + 'f936a1507661eaa9f760b7f1b9775fac4893ad6d1f61b27c72eee0ffbf7990a3', 'src/lib/nostr/inbox-access.ts': - '16eef55d0ffcf2c3291573ddcb0b6a1432bb77abce0017a69e9b6f82414609a7', + '2d9ba6c6ef1e11a1296ab377fd35c4b3e6fdff22de3f97cc85cfe0fc15baa015', 'src/lib/nostr/seal-builder.ts': '3ccc967cc348e63857243ff6f0302c1a68da2afe85ca2c37e00d5a894785fc53', 'src/lib/nostr/giftwrap-builder.ts': @@ -2175,9 +2179,11 @@ async function inboxProbeStorageAdmission(web) { 'src/lib/persistence/private-storage.ts': '9cdac5a1f00678d83bdf4a9b7bfb7c8bd04dc234afb140fc19e0156ad4a064a3', 'src/lib/persistence/inbox-probes.ts': - '3c891f5a540f2cae07bed29a53f73feb8cacc0bef3a75c8c22acb015c4b519fa', + '7d16f44c6fb8ec1168e6c93b669ca3eb404529e8b1783e29694a182db7649cc7', 'src/lib/persistence/inbox-probe-cleanup.ts': - '44a7988b4a52e0a2c5971d7d9ee3c268ffa316d14c920cf2fb75be0d5a7fc375' + 'bfc24be3530471cccd01d387ed2b38a6534eb6493ce850ba9711cc3cfa77e6d9', + 'src/lib/messaging/inbox-access-qualification.ts': + 'f936a1507661eaa9f760b7f1b9775fac4893ad6d1f61b27c72eee0ffbf7990a3' }; for (const [name, pin] of Object.entries(producers)) { const bytes = await readOwned(web, name);