app

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

commit 3844f831c0bce0c9e76829bc6425d513a542dc03
parent 8b0b6195cbe3822d9b4d9ebd93c9c3fb696892e8
Author: triesap <tyson@radroots.org>
Date:   Wed,  7 Oct 2026 09:04:02 +0000

messages: sign persist and publish the reviewed preference (HCP-066)

- Acknowledge one-attempt signing markers and exact signed10050 before EVENT.
- Bind explicit stored retries to the original artifact and current owner/head.
- Bound fixed-target publication and retain failed release controls for cleanup.
- Verify source with real IndexedDB/Web Locks and SDK loopback regressions.

Diffstat:
Aweb/src/lib/messaging/inbox-setup-operation.ts | 362+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/src/lib/messaging/inbox-setup.ts | 26++++++++++++++++++++++++++
Aweb/src/lib/nostr/inbox-preference-publication.ts | 157+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/nostr/inbox-preference-publisher.ts | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/src/lib/nostr/public-pool.ts | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mweb/src/lib/persistence/artifact-records.ts | 19+++++++++++++++++++
Mweb/src/lib/persistence/quota.ts | 19+++++++++++++++++++
Mweb/src/lib/runtime/effect-ownership.ts | 78+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Aweb/tests/e2e/harness/inbox-preference-publisher.ts | 243+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/inbox-preference-publisher.spec.ts | 524+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/integration/inbox-preference-publisher.test.ts | 15+++++++++++++++
Mweb/tests/provenance/output.test.mjs | 7++++++-
Aweb/tests/unit/inbox-preference-publisher.test.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tools/check-output.mjs | 56++++++++++++++++++++++++++++++++++++++++++++++++--------
14 files changed, 1789 insertions(+), 26 deletions(-)

diff --git a/web/src/lib/messaging/inbox-setup-operation.ts b/web/src/lib/messaging/inbox-setup-operation.ts @@ -0,0 +1,362 @@ +import { + captureInboxSetup, + inboxSetupRecordCurrent, + type InboxSetupReview +} from './inbox-setup.ts'; +import type { InboxResolver } from './resolve-inbox.ts'; +import { + publicRelayTargets, + readRelayPolicy, + type RelayPolicy +} from '../config/relays.ts'; +import { canonicalLocalId } from '../private-handles.ts'; +import { + identityMessagingOwnership, + captureIdentityPublicOperation, + identityPublicOperationOwnership, + signIdentityPublicOperation, + stopIdentityPublicOperation, + recheckIdentityOwner, + subscribeIdentityInvalidation, + type IdentitySession, + type IdentityPublicOperation +} from '../runtime/identity-session.ts'; +import { + runCapturedPublicEffect, + type PublicEffectLease +} from '../runtime/effect-ownership.ts'; +import { + publicRecordSnapshot, + decodePublicRecord, + type PublicRecordHandle +} from '../persistence/records.ts'; +import { + loadPreferenceOperation, + commitPublicOperationTransition, + observePublicOperationTransition, + publicQuotaOwner, + type PublicQuotaRepository +} from '../persistence/quota.ts'; +import { + preparePreferenceSigningTransition, + preparePublicArtifactTransition, + type PublicOperationTransition +} from '../persistence/artifact-records.ts'; +import { getPublicPool } from '../nostr/public-pool.ts'; +import { + authorizeStoredInboxPreference, + preferencePolicyFingerprint +} from '../nostr/inbox-preference-publication.ts'; +import { + publishInboxPreference, + type PreferencePublicationResult +} from '../nostr/inbox-preference-publisher.ts'; +declare const actionBrand: unique symbol; +export type InboxPreferenceAction = Readonly<{ [actionBrand]: true }>; +type Lookup = () => Promise<InboxResolver>; +type Saved = Readonly<{ + repository: PublicQuotaRepository; + identity: IdentitySession; + policy: RelayPolicy; + original: PublicRecordHandle; + operation: IdentityPublicOperation; + id: string; + actionId: string; + lookup: Lookup; + retry: boolean; + control: AbortController; + running(): boolean; + markRunning(): void; +}>; +const actions = new WeakMap<InboxPreferenceAction, Saved>(); +type Prepared = + | Readonly<{ status: 'prepared'; action: InboxPreferenceAction }> + | Readonly<{ status: 'invalid' | 'unavailable' | 'conflict' | 'unknown' }>; +function retain( + repository: PublicQuotaRepository, + identity: IdentitySession, + policy: RelayPolicy, + original: PublicRecordHandle, + id: string, + lookup: Lookup, + retry: boolean +): Prepared { + const operation = captureIdentityPublicOperation( + identity, + original, + id, + 'reviewed_captured_operation' + ); + if (!operation || typeof lookup !== 'function') + return { status: 'unavailable' }; + let used = false; + const action = Object.freeze({}) as InboxPreferenceAction; + actions.set(action, { + repository, + identity, + policy, + original, + operation, + id, + actionId: crypto.randomUUID(), + lookup, + retry, + control: new AbortController(), + running: () => used, + markRunning: () => { + used = true; + } + }); + return { status: 'prepared', action }; +} +// Original opaque065 review only. This does not auto-run after connect/setup. +export async function beginInboxPreferenceOperation( + repository: PublicQuotaRepository, + identity: IdentitySession, + policy: RelayPolicy, + review: InboxSetupReview, + command: unknown, + lookup: Lookup, + consent: unknown +): Promise<Prepared> { + try { + const id = canonicalLocalId(command), + owner = identityMessagingOwnership(identity); + if (!id || !owner || publicQuotaOwner(repository) !== owner.owner) + return { status: 'unavailable' }; + const resolver = await lookup(), + captured = captureInboxSetup(review, resolver, id, consent); + if (captured.status !== 'captured') return captured; + if (captured.owner !== owner.owner || !owner.current()) + return { status: 'unavailable' }; + return retain( + repository, + identity, + policy, + captured.record, + id, + lookup, + false + ); + } catch { + return { status: 'unavailable' }; + } +} +// Explicit reload review of the actual stored signed operation, with full +// original capture retained. Unsigned uncertainty cannot become a fresh plan. +export async function resumeInboxPreferenceOperation( + repository: PublicQuotaRepository, + identity: IdentitySession, + policy: RelayPolicy, + command: unknown, + lookup: Lookup, + consent: unknown +): Promise<Prepared> { + try { + if (consent !== 'reviewed_stored_inbox_preference') + return { status: 'invalid' }; + const id = canonicalLocalId(command); + await recheckIdentityOwner(identity); + const owner = identityMessagingOwnership(identity); + if (!id || !owner || publicQuotaOwner(repository) !== owner.owner) + return { status: 'unavailable' }; + const read = await loadPreferenceOperation(repository, id); + if (!read.ok) return { status: 'unavailable' }; + const row = publicRecordSnapshot(read.value, owner.owner, id); + if (row?.family !== 'preference_operation') return { status: 'invalid' }; + if (row.revision < 2 || !row.artifact) return { status: 'unknown' }; + const manifest = readRelayPolicy(policy), + fingerprint = await preferencePolicyFingerprint(policy), + resolver = await lookup(); + if ( + !manifest.messagingEnabled || + !manifest.postingEnabled || + row.capture.policyFingerprint !== fingerprint || + JSON.stringify(row.capture.targets) !== + JSON.stringify(publicRelayTargets(policy, 'write')) || + !inboxSetupRecordCurrent(read.value, owner.owner, id, resolver, policy) || + !owner.current() + ) + return { status: 'conflict' }; + // Historical original signing wire for lease matching only; never written + // back, never a reset. The effect runner uses the actual stored artifact. + const original = decodePublicRecord( + JSON.stringify({ ...row, revision: 0, artifact: null, receipts: [] }), + owner.owner, + id + ); + return original.ok + ? retain(repository, identity, policy, original.value, id, lookup, true) + : { status: 'invalid' }; + } catch { + return { status: 'unavailable' }; + } +} +async function acknowledged( + repository: PublicQuotaRepository, + transition: PublicOperationTransition +): Promise<boolean> { + const result = await commitPublicOperationTransition(repository, transition); + return ( + result.ok && + (await observePublicOperationTransition(repository, transition)).state === + 'committed' + ); +} +async function knownBase(saved: Saved): Promise<(() => boolean) | undefined> { + const owner = identityMessagingOwnership(saved.identity); + const operation = identityPublicOperationOwnership( + saved.identity, + saved.operation + ); + if (!owner || !operation || saved.control.signal.aborted) return undefined; + const stored = await loadPreferenceOperation(saved.repository, saved.id); + if (!stored.ok) return undefined; + const resolver = await saved.lookup(); + const current = () => + !saved.control.signal.aborted && + operation.current() && + owner.current() && + inboxSetupRecordCurrent( + stored.value, + owner.owner, + saved.id, + resolver, + saved.policy + ); + return current() ? current : undefined; +} +export async function runInboxPreferenceOperation( + action: InboxPreferenceAction +): Promise<PreferencePublicationResult> { + const saved = actions.get(action); + if (!saved) return { status: 'invalid' }; + if (saved.running() || saved.control.signal.aborted) + return { status: 'stopped' }; + saved.markRunning(); + const capture = identityPublicOperationOwnership( + saved.identity, + saved.operation + ); + if (!capture) return { status: 'stopped' }; + const messagingOwner = identityMessagingOwnership(saved.identity); + if ( + !messagingOwner || + messagingOwner.owner !== capture.owner || + messagingOwner.session !== capture.session + ) + return { status: 'stopped' }; + if (!capture.current() || saved.control.signal.aborted) + return { status: 'stopped' }; + const invalidate = subscribeIdentityInvalidation(saved.identity, () => { + // Notifications also describe pending/completed observations. Only actual + // owner/capability/generation loss cancels this original explicit action. + if (!capture.current() || !messagingOwner.current()) saved.control.abort(); + }); + try { + const result = await runCapturedPublicEffect<PreferencePublicationResult>( + saved.repository, + saved.original, + saved.id, + { + ...capture, + current: () => capture.current() && !saved.control.signal.aborted + }, + saved.retry + ? 'reviewed_stored_preference_retry' + : 'reviewed_prepared_preference_operation', + async (lease: PublicEffectLease, claimed: PublicRecordHandle) => { + if (!(await knownBase(saved))) return { status: 'stopped' }; + const row = publicRecordSnapshot(claimed, capture.owner, saved.id); + if (row?.family !== 'preference_operation') + return { status: 'invalid' }; + const manifest = readRelayPolicy(saved.policy); + if ( + !manifest.messagingEnabled || + !manifest.postingEnabled || + row.capture.policyFingerprint !== + (await preferencePolicyFingerprint(saved.policy)) || + JSON.stringify(row.capture.targets) !== + JSON.stringify(publicRelayTargets(saved.policy, 'write')) + ) + return { status: 'stopped' }; + if (!capture.current() || saved.control.signal.aborted) + return { status: 'stopped' }; + if (!row.artifact) { + const marker = preparePreferenceSigningTransition( + claimed, + capture.owner, + saved.id + ); + if ( + !marker.ok || + !(await acknowledged(saved.repository, marker.value)) + ) + return { status: 'storage_failed' }; + if (!(await knownBase(saved))) return { status: 'stopped' }; + const signed = await signIdentityPublicOperation( + saved.identity, + saved.operation, + lease + ); + if (signed.status !== 'signed') return { status: 'stopped' }; + const pending = await loadPreferenceOperation( + saved.repository, + saved.id + ); + if (!pending.ok) return { status: 'storage_failed' }; + if (!capture.current() || saved.control.signal.aborted) + return { status: 'stopped' }; + const transition = preparePublicArtifactTransition( + pending.value, + capture.owner, + saved.id, + signed.artifact + ); + if ( + !transition.ok || + !(await acknowledged(saved.repository, transition.value)) + ) + return { status: 'storage_failed' }; + } + if (saved.control.signal.aborted || !capture.current()) + return { status: 'stopped' }; + const pool = getPublicPool(saved.policy); + if (!pool) return { status: 'stopped' }; + return await publishInboxPreference( + saved.repository, + capture.owner, + saved.id, + saved.actionId, + pool, + saved.policy, + saved.control.signal, + () => + authorizeStoredInboxPreference( + saved.repository, + saved.identity, + saved.operation, + lease, + saved.original, + saved.id, + saved.policy, + () => knownBase(saved) + ) + ); + } + ); + return result.status === 'completed' ? result.value : { status: 'stopped' }; + } catch { + return { status: 'stopped' }; + } finally { + invalidate(); + } +} +export function stopInboxPreferenceOperation( + action: InboxPreferenceAction +): void { + const saved = actions.get(action); + if (!saved) return; + saved.control.abort(); + stopIdentityPublicOperation(saved.identity, saved.operation); +} diff --git a/web/src/lib/messaging/inbox-setup.ts b/web/src/lib/messaging/inbox-setup.ts @@ -19,6 +19,7 @@ import { } from '../runtime/identity-session.ts'; import { decodePublicRecord, + publicRecordSnapshot, type PublicRecordHandle } from '../persistence/records.ts'; import { canonicalLocalId } from '../private-handles.ts'; @@ -332,3 +333,28 @@ export function captureInboxSetup( return { status: 'unavailable' }; } } +// Informational known-base fence only, never a signing or network capability. +// Exact already-published artifact is an allowed observation on explicit resume; +// competing/partial observations still block. This is not a global CAS. +export function inboxSetupRecordCurrent( + record: PublicRecordHandle, + owner: string, + id: string, + resolver: InboxResolver, + policy: RelayPolicy +): boolean { + try { + const row = publicRecordSnapshot(record, owner, id), + observed = base(resolver, policy, owner); + if (!row || row.family !== 'preference_operation' || !observed) + return false; + const matches = + observed.wire === row.source.wire || + (row.artifact !== null && + observed.id === row.artifact.eventId && + observed.wire === row.artifact.wire); + return matches && inboxResolverCurrentAfterSample(resolver); + } catch { + return false; + } +} diff --git a/web/src/lib/nostr/inbox-preference-publication.ts b/web/src/lib/nostr/inbox-preference-publication.ts @@ -0,0 +1,157 @@ +import type { NostrEvent } from 'applesauce-core/helpers'; +import { + publicRelayTargets, + readRelayPolicy, + type RelayPolicy +} from '../config/relays.ts'; +import { + identityMessagingOwnership, + identityPublicOperationOwnership, + recheckIdentityOwner, + type IdentitySession, + type IdentityPublicOperation +} from '../runtime/identity-session.ts'; +import { + publicEffectLeaseCurrent, + type PublicEffectLease +} from '../runtime/effect-ownership.ts'; +import { + loadPreferenceOperation, + type PublicQuotaRepository +} from '../persistence/quota.ts'; +import { + publicRecordSnapshot, + publicRecordWire, + type PublicRecordHandle +} from '../persistence/records.ts'; +declare const publicationBrand: unique symbol; +export type PreferencePublication = Readonly<{ [publicationBrand]: true }>; +type Saved = Readonly<{ + policy: RelayPolicy; + wire: string; + eventId: string; + origins: readonly string[]; + current(): boolean; +}>; +const publications = new WeakMap<PreferencePublication, Saved>(); +// Internal exact policy observation, not a Nostr cryptographic replacement. +export async function preferencePolicyFingerprint( + policy: RelayPolicy +): Promise<string> { + const hash = await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(JSON.stringify(readRelayPolicy(policy))) + ); + return Array.from(new Uint8Array(hash), (byte) => + byte.toString(16).padStart(2, '0') + ).join(''); +} +// Only a genuine current identity operation and original lease can acquire this +// one-attempt capability from actual acknowledged storage. No caller event wire. +// beforeEffect is an internal bounded lookup port; its final fence is retained. +export async function authorizeStoredInboxPreference( + repository: PublicQuotaRepository, + identity: IdentitySession, + operation: IdentityPublicOperation, + lease: PublicEffectLease, + original: PublicRecordHandle, + id: string, + policy: RelayPolicy, + beforeEffect: () => Promise<(() => boolean) | undefined> +): Promise<PreferencePublication | undefined> { + try { + if (typeof window === 'undefined') return undefined; + const capture = identityPublicOperationOwnership(identity, operation); + const messageOwner = identityMessagingOwnership(identity); + if ( + !capture || + !messageOwner || + capture.owner !== messageOwner.owner || + capture.session !== messageOwner.session + ) + return undefined; + const originalWire = publicRecordWire(original, capture.owner, id), + row = publicRecordSnapshot(original, capture.owner, id); + if ( + !originalWire || + row?.family !== 'preference_operation' || + row.revision !== 0 || + row.capture.kind !== 10050 + ) + return undefined; + const authority = { + owner: capture.owner, + id, + recordWire: originalWire, + session: capture.session + }; + const fingerprint = await preferencePolicyFingerprint(policy), + manifest = readRelayPolicy(policy), + targets = publicRelayTargets(policy, 'write'); + if ( + !manifest.messagingEnabled || + !manifest.postingEnabled || + fingerprint !== row.capture.policyFingerprint || + JSON.stringify(targets) !== JSON.stringify(row.capture.targets) + ) + return undefined; + const read = await loadPreferenceOperation(repository, id); + if (!read.ok) return undefined; + const stored = publicRecordSnapshot(read.value, capture.owner, id); + if ( + stored?.family !== 'preference_operation' || + stored.revision < 2 || + !stored.artifact || + JSON.stringify(stored.capture) !== JSON.stringify(row.capture) || + JSON.stringify(stored.source) !== JSON.stringify(row.source) || + stored.consent !== row.consent + ) + return undefined; + const headCurrent = await beforeEffect(); + if (!headCurrent) return undefined; + await recheckIdentityOwner(identity); + const current = () => + capture.current() && + messageOwner.current() && + headCurrent() && + publicEffectLeaseCurrent(lease, authority); + if (!current()) return undefined; + const token = Object.freeze({}) as PreferencePublication; + publications.set(token, { + policy, + wire: stored.artifact.wire, + eventId: stored.artifact.eventId, + origins: [...stored.capture.targets], + current + }); + return token; + } catch { + return undefined; + } +} +// Detached metadata never grants permission. Pool consumes the original token. +export function preferencePublicationSnapshot(token: PreferencePublication) { + const saved = publications.get(token); + return saved + ? { eventId: saved.eventId, origins: [...saved.origins] } + : undefined; +} +export function takePreferencePublication( + token: PreferencePublication, + policy: RelayPolicy, + origin: string +): Readonly<{ event: NostrEvent; current(): boolean }> | undefined { + const saved = publications.get(token); + if (!saved) return undefined; + publications.delete(token); + if ( + saved.policy !== policy || + !saved.origins.includes(origin) || + !saved.current() + ) + return undefined; + return { + event: JSON.parse(saved.wire) as NostrEvent, + current: saved.current + }; +} diff --git a/web/src/lib/nostr/inbox-preference-publisher.ts b/web/src/lib/nostr/inbox-preference-publisher.ts @@ -0,0 +1,111 @@ +import { PUBLIC_PUBLICATION_BUDGETS } from '../config/budgets.ts'; +import type { RelayPolicy } from '../config/relays.ts'; +import { + publishPublicPreferenceAttempt, + type PublicPool +} from './public-pool.ts'; +import type { PreferencePublication } from './inbox-preference-publication.ts'; +import { canonicalLocalId } from '../private-handles.ts'; +import { + loadPreferenceOperation, + commitPublicOperationTransition, + type PublicQuotaRepository +} from '../persistence/quota.ts'; +import { preparePublicReceiptTransition } from '../persistence/artifact-records.ts'; +import { publicRecordSnapshot } from '../persistence/records.ts'; +export type PreferencePublicationResult = Readonly<{ + status: + 'completed' | 'stopped' | 'storage_failed' | 'invalid' | 'needs_action'; +}>; +// One explicitly resumed finite action. Caller owns the real current identity, +// known-base lookup and opaque authorization, never arbitrary event templates. +export async function publishInboxPreference( + repository: PublicQuotaRepository, + owner: string, + id: string, + actionId: string, + pool: PublicPool, + policy: RelayPolicy, + signal: AbortSignal, + authorize: () => Promise<PreferencePublication | undefined> +): Promise<PreferencePublicationResult> { + if (!canonicalLocalId(actionId)) return { status: 'invalid' }; + const started = performance.now(); + const initial = await loadPreferenceOperation(repository, id); + if (!initial.ok) return { status: 'storage_failed' }; + const row = publicRecordSnapshot(initial.value, owner, id); + if ( + row?.family !== 'preference_operation' || + !row.artifact || + row.revision < 2 + ) + return { status: 'invalid' }; + for (const origin of row.capture.targets) { + if ( + row.receipts.some( + (fact) => + fact.origin === origin && + fact.eventId === row.artifact!.eventId && + fact.status === 'accepted' + ) + ) + continue; + for ( + let attempt = 1; + attempt <= PUBLIC_PUBLICATION_BUDGETS.attemptsPerTargetAction; + attempt++ + ) { + if ( + signal.aborted || + performance.now() - started >= + PUBLIC_PUBLICATION_BUDGETS.networkActionMilliseconds + ) + return { status: 'stopped' }; + const permission = await authorize(); + const remaining = + PUBLIC_PUBLICATION_BUDGETS.networkActionMilliseconds - + (performance.now() - started); + if (!permission || signal.aborted || remaining <= 0) + return { status: 'stopped' }; + const result = await publishPublicPreferenceAttempt( + pool, + permission, + policy, + origin, + signal, + remaining + ); + const read = await loadPreferenceOperation(repository, id); + if (!read.ok) return { status: 'storage_failed' }; + const transition = preparePublicReceiptTransition( + read.value, + owner, + id, + JSON.stringify({ + actionId, + origin, + role: 'preference', + attempt, + eventId: row.artifact.eventId, + status: result.status, + observedAtMilliseconds: Date.now(), + readbackWire: null + }) + ); + if ( + !transition.ok || + !(await commitPublicOperationTransition(repository, transition.value)) + .ok + ) + return { status: 'storage_failed' }; + if (result.status === 'accepted') break; + if (result.status !== 'timed_out') + return { + status: result.status === 'stopped' ? 'stopped' : 'needs_action' + }; + if (attempt === PUBLIC_PUBLICATION_BUDGETS.attemptsPerTargetAction) + return { status: 'needs_action' }; + } + } + return { status: 'completed' }; +} diff --git a/web/src/lib/nostr/public-pool.ts b/web/src/lib/nostr/public-pool.ts @@ -7,6 +7,13 @@ import { } from '../config/relays.ts'; import type { PublicFilter, PublicPoolMessage } from './exports.ts'; import { requireNip50Source } from './search-sources.ts'; +import { + takePreferencePublication, + type PreferencePublication +} from './inbox-preference-publication.ts'; +export type PreferenceAttemptResult = Readonly<{ + status: 'accepted' | 'refused' | 'timed_out' | 'unknown' | 'stopped'; +}>; declare const ownedPool: unique symbol; export type PublicPool = Readonly<{ readonly [ownedPool]: true }>; @@ -21,6 +28,12 @@ interface Owner { sampleSource?: string ) => () => void; readonly close: () => void; + readonly preference: ( + permission: PreferencePublication, + origin: string, + signal: AbortSignal, + remaining: number + ) => Promise<PreferenceAttemptResult>; } const owners = new WeakMap<PublicPool, Owner>(); let lifetime: Owner | undefined; @@ -44,11 +57,121 @@ export function getPublicPool( const active = new Map<() => void, true>(); let closed = false; let cleanupComplete = false; + let publicationCleanupRequired = false; const owner: Owner = { policy, token, origins, closed: () => closed, + async preference(permission, origin, signal, remaining) { + const admitted = takePreferencePublication(permission, policy, origin); + if ( + closed || + publicationCleanupRequired || + !admitted || + signal.aborted || + !Number.isFinite(remaining) || + remaining <= 0 || + remaining > 45000 + ) + return { status: 'stopped' }; + return await new Promise<PreferenceAttemptResult>((resolve) => { + let ended = false; + let release = () => {}; + let fenceTimer: ReturnType<typeof setTimeout> | undefined; + function finish(status: PreferenceAttemptResult['status']) { + if (ended) return; + ended = true; + clearTimeout(timer); + if (fenceTimer !== undefined) clearTimeout(fenceTimer); + signal.removeEventListener('abort', stopped); + try { + release(); + } catch { + publicationCleanupRequired = true; + status = 'unknown'; + } + resolve({ status }); + } + function stopped() { + if (ended) { + release(); + return; + } + finish('stopped'); + } + function fence() { + if (ended) return; + if (closed || signal.aborted || !admitted!.current()) { + finish('stopped'); + return; + } + fenceTimer = setTimeout(() => fence(), 50); + } + signal.addEventListener('abort', stopped, { once: true }); + // Arm our finite deadline before subscribing. The SDK uses the same + // response shape for its timer and a relay refusal saying "Timeout"; + // only this owned deadline supplies retryable timeout evidence. + const relay = sdk.relay(origin); + const timeout = + Number.isFinite(relay.eventTimeout) && relay.eventTimeout > 0 + ? Math.min(remaining, relay.eventTimeout) + : remaining; + const timer = setTimeout(() => finish('timed_out'), timeout); + try { + if (!admitted.current() || signal.aborted) { + finish('stopped'); + return; + } + // This SDK invocation is an attempted effect. Stop cannot reverse an + // already emitted/buffered EVENT, but teardown schedules no new one. + const subscription = relay.event(admitted.event, 'EVENT').subscribe({ + next(response) { + if (ended) return; + if ( + (response.from !== origin && response.from !== origin + '/') || + typeof response.ok !== 'boolean' + ) { + finish('unknown'); + return; + } + if (response.ok) finish('accepted'); + else if (response.message === 'Timeout') finish('unknown'); + else if ( + typeof response.message === 'string' && + response.message.startsWith('auth-required:') + ) + finish('unknown'); + else finish('refused'); + }, + error: () => finish('unknown'), + complete: () => { + if (!ended) finish('unknown'); + } + }); + const stop = () => { + subscription.unsubscribe(); + active.delete(stop); + }; + release = () => { + stop(); + active.delete(stopped); + }; + active.set(stopped, true); + if (ended) { + try { + release(); + } catch { + publicationCleanupRequired = true; + } + } else { + fence(); + } + } catch { + finish('unknown'); + } + }); + }, subscribe(filters, onMessage, sampleSource) { if (closed) throw new Error('public_pool_closed'); let release = () => {}; @@ -99,8 +222,8 @@ export function getPublicPool( } catch { failed = true; } - cleanupComplete = !failed; - if (failed) throw new Error('public_pool_close_failed'); + cleanupComplete = !failed && active.size === 0; + if (!cleanupComplete) throw new Error('public_pool_close_failed'); } }; owners.set(token, owner); @@ -151,3 +274,21 @@ export function subscribePublicPool( export function closePublicPool(token: PublicPool): void { ownerOf(token).close(); } +// Narrow once-only preference capability; no raw event, arbitrary SDK options, +// AUTH or general UI publisher. Pool remains the anonymous lifetime owner. +export function publishPublicPreferenceAttempt( + token: PublicPool, + permission: PreferencePublication, + policy: RelayPolicy, + origin: string, + signal: AbortSignal, + remaining: number +): Promise<PreferenceAttemptResult> { + try { + const owner = ownerOf(token); + if (owner.policy !== policy) return Promise.resolve({ status: 'stopped' }); + return owner.preference(permission, origin, signal, remaining); + } catch { + return Promise.resolve({ status: 'unknown' }); + } +} diff --git a/web/src/lib/persistence/artifact-records.ts b/web/src/lib/persistence/artifact-records.ts @@ -136,6 +136,25 @@ function retain( }); return { ok: true, value: token }; } +// A durable one-attempt marker, not a known refusal or a retry permission. +// Lost unsigned revision1 remains uncertain; it can never be reset by this API. +export function preparePreferenceSigningTransition( + record: PublicRecordHandle, + owner: unknown, + id: unknown +): Result<PublicOperationTransition> { + const base = baseOf(record, owner, id); + if ( + !base || + base.row.family !== 'preference_operation' || + base.row.capture.kind !== 10050 || + base.row.revision !== 0 || + base.row.artifact !== null || + base.row.receipts.length !== 0 + ) + return failed('invalid_record'); + return retain(base, { ...base.row, revision: 1 }); +} export function preparePublicArtifactTransition( record: PublicRecordHandle, owner: unknown, diff --git a/web/src/lib/persistence/quota.ts b/web/src/lib/persistence/quota.ts @@ -481,6 +481,25 @@ export function commitPublicCleanup( // No signer/network await exists inside this transaction. It consumes only a // genuine immutable typed transition captured before storage acquisition. +// Exact owner-scoped actual stored preference, not a caller's structural row. +// Read is bounded by the same complete quota/codec scan and transaction ack. +export function loadPreferenceOperation( + repository: PublicQuotaRepository, + expectedId: unknown +): Promise<PublicQuotaResult<PublicRecordHandle>> { + const scope = scopeOf(repository), + id = canonicalLocalId(expectedId); + if (!scope) return Promise.resolve(failed('invalid_scope')); + if (!id) return Promise.resolve(failed('invalid_record')); + return transaction(scope, 'readonly', (rows) => { + const row = rows.find( + (row) => row.store === 'preference_operations' && row.record.id === id + ); + if (!row) return failed('invalid_record'); + const decoded = decodePublicRecord(row.wire, scope.owner, id); + return decoded.ok ? decoded : failed('corrupt_record'); + }); +} export function commitPublicOperationTransition( repository: PublicQuotaRepository, handle: PublicOperationTransition diff --git a/web/src/lib/runtime/effect-ownership.ts b/web/src/lib/runtime/effect-ownership.ts @@ -7,6 +7,7 @@ import { } from '../persistence/records.ts'; import { claimPublicOperation, + loadPreferenceOperation, publicQuotaOwner, type PublicQuotaRepository, type PublicQuotaFailure @@ -60,7 +61,7 @@ export async function runCapturedPublicEffect<T>( expectedId: unknown, input: PublicEffectCapture, review: unknown, - work: (lease: PublicEffectLease) => Promise<T> + work: (lease: PublicEffectLease, stored: PublicRecordHandle) => Promise<T> ): Promise<PublicEffectResult<T>> { try { const owner = canonicalPublicKey(input?.owner), @@ -72,7 +73,9 @@ export async function runCapturedPublicEffect<T>( const recordWire = owner && id ? publicRecordWire(handle, owner, id) : undefined; if ( - review !== 'reviewed_captured_operation' || + (review !== 'reviewed_captured_operation' && + review !== 'reviewed_prepared_preference_operation' && + review !== 'reviewed_stored_preference_retry') || !owner || !id || !row || @@ -85,6 +88,13 @@ export async function runCapturedPublicEffect<T>( typeof work !== 'function' ) return { status: 'invalid' }; + const preferenceMode = review !== 'reviewed_captured_operation'; + const storedRetry = review === 'reviewed_stored_preference_retry'; + if ( + preferenceMode && + (row.family !== 'preference_operation' || row.capture.kind !== 10050) + ) + return { status: 'invalid' }; if (typeof window === 'undefined' || !navigator.locks?.request) return { status: 'unavailable' }; if (publicQuotaOwner(repository) !== owner) @@ -95,23 +105,56 @@ export async function runCapturedPublicEffect<T>( async (lock): Promise<PublicEffectResult<T>> => { if (!lock) return { status: 'busy' }; if (!fresh()) return { status: 'stopped' }; - const claimed = await claimPublicOperation(repository, id, handle); + async function claimOriginal() { + if (!storedRetry) + return await claimPublicOperation(repository, id, handle); + const loaded = await loadPreferenceOperation(repository, id); + if (!loaded.ok) return loaded; + const stored = publicRecordSnapshot(loaded.value, owner, id); + if ( + stored?.family !== 'preference_operation' || + row?.family !== 'preference_operation' || + JSON.stringify(stored.capture) !== JSON.stringify(row.capture) || + JSON.stringify(stored.source) !== JSON.stringify(row.source) || + stored.consent !== row.consent + ) + return { ok: false as const, reason: 'conflict' as const }; + return { + ok: true as const, + value: { state: 'existing' as const, record: loaded.value } + }; + } + const claimed = await claimOriginal(); if (!claimed.ok) return claimed.reason === 'unknown_completion' ? { status: 'unknown', record: handle } : { status: claimed.reason }; const original = claimed.value.record; + if (storedRetry && claimed.value.state !== 'existing') + return { status: 'unknown', record: original }; if (claimed.value.state === 'existing') { const stored = publicRecordSnapshot(original, owner, id); - return { - status: - stored && - stored.family !== 'public_draft' && - stored.artifact !== null - ? 'retained' - : 'unknown', - record: original - }; + const prepared = + preferenceMode && + !storedRetry && + stored?.family === 'preference_operation' && + stored.revision === 0 && + stored.artifact === null; + const retry = + storedRetry && + stored?.family === 'preference_operation' && + stored.revision >= 2 && + stored.artifact !== null; + if (!prepared && !retry) + return { + status: + stored && + stored.family !== 'public_draft' && + stored.artifact !== null + ? 'retained' + : 'unknown', + record: original + }; } let phase: State = 'active', closed = false, @@ -148,7 +191,11 @@ export async function runCapturedPublicEffect<T>( authority: Authority, invoke: () => Promise<V> ): Promise<JobResult<V>> { - if (!matches(authority) || typeof invoke !== 'function') + if ( + storedRetry || + !matches(authority) || + typeof invoke !== 'function' + ) return { status: 'invalid' }; if (!accepting || !current()) return { status: phase === 'unknown' ? 'unknown' : 'stopped' }; @@ -177,7 +224,8 @@ export async function runCapturedPublicEffect<T>( call, stop, mark() { - if (started || !outstanding() || !current()) return false; + if (storedRetry || started || !outstanding() || !current()) + return false; started = true; return true; }, @@ -194,7 +242,7 @@ export async function runCapturedPublicEffect<T>( if (!current()) return { status: 'stopped' }; let value: T; try { - value = await work(lease); + value = await work(lease, original); } catch { stop(); return { diff --git a/web/tests/e2e/harness/inbox-preference-publisher.ts b/web/tests/e2e/harness/inbox-preference-publisher.ts @@ -0,0 +1,243 @@ +import { makeFixture } from './approved-signing.ts'; +import { Relay } from 'applesauce-relay/relay'; +export { + getPublicPool, + closePublicPool +} from '../../../src/lib/nostr/public-pool.ts'; +import { publicRecordSnapshot } from '../../../src/lib/persistence/records.ts'; +import { + createIdentitySession, + connectIdentity, + probeIdentityMessaging, + disconnectIdentity +} from '../../../src/lib/runtime/identity-session.ts'; +import { + createPublicScheduler, + createPublicRun, + openInboxRequest, + closePublicScheduler +} from '../../../src/lib/nostr/request-scope.ts'; +import { createInboxResolver } from '../../../src/lib/messaging/resolve-inbox.ts'; +import { fixturePolicy, discovery, setupInput } from './inbox-setup.ts'; +export { fixturePolicy, discovery, setupInput }; +export { + createIdentitySession, + connectIdentity, + probeIdentityMessaging, + disconnectIdentity +}; +export { + reviewInboxSetup, + inboxSetupPreview +} from '../../../src/lib/messaging/inbox-setup.ts'; +export { saveInboxPreferenceOperation } from '../../../src/lib/persistence/inbox-preference-operations.ts'; +export { + beginInboxPreferenceOperation, + resumeInboxPreferenceOperation, + runInboxPreferenceOperation, + stopInboxPreferenceOperation +} from '../../../src/lib/messaging/inbox-setup-operation.ts'; +export { + openBrowserDatabase, + closeBrowserDatabase +} from '../../../src/lib/persistence/database.ts'; +export { + createPublicQuotaRepository, + loadPreferenceOperation +} from '../../../src/lib/persistence/quota.ts'; +export { publicRecordSnapshot }; +export async function makePublisherFixture() { + const fixture = makeFixture(10050), + original = publicRecordSnapshot(fixture.record, fixture.owner, fixture.id)!; + if (original.family !== 'preference_operation' || !original.source.wire) + throw new Error('missing source'); + const source = JSON.parse(original.source.wire) as ReturnType< + typeof fixture.sign + >; + const identity = createIdentitySession(); + let observedOwner = fixture.owner, + signs = 0; + let beforeSign: (() => Promise<void>) | undefined; + const prior = Object.getOwnPropertyDescriptor(window, 'nostr'); + Object.defineProperty(window, 'nostr', { + configurable: true, + value: { + getPublicKey: () => Promise.resolve(observedOwner), + signEvent: async (input: Parameters<typeof fixture.sign>[0]) => { + signs++; + await beforeSign?.(); + return fixture.sign(input); + }, + nip44: { + encrypt: (_peer: string, text: string) => + Promise.resolve('fixture:' + text), + decrypt: (_peer: string, text: string) => Promise.resolve(text.slice(8)) + } + } + }); + await connectIdentity(identity); + await probeIdentityMessaging(identity, 'reviewed_self_copy'); + const policy = fixturePolicy(), + schedulers: ReturnType<typeof createPublicScheduler>[] = []; + function resolve(event = source, complete = true) { + const scheduler = createPublicScheduler({ + now: () => 0, + schedule: () => () => {} + }); + schedulers.push(scheduler); + const run = createPublicRun(scheduler, policy); + return createInboxResolver( + run, + fixture.owner, + (next) => + openInboxRequest( + run, + fixture.owner, + (sink) => { + sink({ type: 'EVENT', from: discovery, id: 'fixture', event }); + if (complete) + sink({ type: 'EOSE', from: discovery, id: 'fixture' }); + return () => {}; + }, + next + ), + () => true + ); + } + return { + identity, + policy, + owner: fixture.owner, + resolve, + signs: () => signs, + beforeSign(callback: () => Promise<void>) { + beforeSign = callback; + }, + changeOwner() { + const other = makeFixture(10050); + try { + observedOwner = other.owner; + } finally { + other.close(); + } + }, + competing() { + return fixture.sign({ + ...fixture.template, + created_at: 102, + content: 'concurrent preference' + }); + }, + close() { + disconnectIdentity(identity); + for (const scheduler of schedulers) closePublicScheduler(scheduler); + fixture.close(); + if (prior) Object.defineProperty(window, 'nostr', prior); + else Reflect.deleteProperty(window, 'nostr'); + } + }; +} +// Test-only fault at the real IDB write boundary; no mock database/production port. +export function failPreferenceWrite(revision: number) { + const original = Reflect.get<IDBObjectStore, 'put'>( + IDBObjectStore.prototype, + 'put' + ); + IDBObjectStore.prototype.put = function (value: unknown, key?: IDBValidKey) { + if ( + this.name === 'preference_operations' && + typeof value === 'object' && + value && + 'wire' in value && + typeof value.wire === 'string' + ) { + const row = JSON.parse(value.wire) as { revision: number }; + if (row.revision === revision) { + IDBObjectStore.prototype.put = original; + this.transaction.abort(); + throw new Error('controlled IDB abort'); + } + } + return original.call(this, value, key); + }; + return () => { + IDBObjectStore.prototype.put = original; + }; +} +// Actual transaction-complete and native SDK transport-send ordering only. +// Delegates both APIs unchanged; no delayed send or database substitute. +export function installEffectTrace() { + const events: string[] = []; + const put = Reflect.get<IDBObjectStore, 'put'>( + IDBObjectStore.prototype, + 'put' + ); + const send = Reflect.get<WebSocket, 'send'>(WebSocket.prototype, 'send'); + IDBObjectStore.prototype.put = function (value: unknown, key?: IDBValidKey) { + if ( + this.name === 'preference_operations' && + typeof value === 'object' && + value && + 'wire' in value && + typeof value.wire === 'string' + ) { + const revision = (JSON.parse(value.wire) as { revision: number }) + .revision; + this.transaction.addEventListener( + 'complete', + () => events.push('ack:' + revision), + { once: true } + ); + } + return put.call(this, value, key); + }; + WebSocket.prototype.send = function (data: Parameters<WebSocket['send']>[0]) { + if ( + typeof data === 'string' && + (JSON.parse(data) as unknown[])[0] === 'EVENT' + ) + events.push('EVENT'); + return send.call(this, data); + }; + return { + events: () => [...events], + restore() { + IDBObjectStore.prototype.put = put; + WebSocket.prototype.send = send; + } + }; +} +// Retain the actual SDK observable/subscription; only its owned release is +// faulted. No fake ACK, transport, signature, database or production option. +export function installUnsubscribeFailure() { + const event = Reflect.get<Relay, 'event'>(Relay.prototype, 'event'); + let fail = true; + Relay.prototype.event = function (...args: Parameters<Relay['event']>) { + const observable = event.call(this, ...args); + observable.subscribe = new Proxy(observable.subscribe.bind(observable), { + apply(subscribe, receiver, argumentsList) { + const subscription = Reflect.apply( + subscribe, + receiver, + argumentsList + ) as ReturnType<typeof subscribe>; + const release = subscription.unsubscribe.bind(subscription); + subscription.unsubscribe = () => { + if (fail) throw new Error('controlled owned release failure'); + release(); + }; + return subscription; + } + }); + return observable; + }; + return { + allowRelease() { + fail = false; + }, + restore() { + fail = false; + Relay.prototype.event = event; + } + }; +} diff --git a/web/tests/e2e/inbox-preference-publisher.spec.ts b/web/tests/e2e/inbox-preference-publisher.spec.ts @@ -0,0 +1,524 @@ +import { test, expect } from '@playwright/test'; +import { build } from 'vite'; +import { fileURLToPath } from 'node:url'; +import { createHash } from 'node:crypto'; +import { once } from 'node:events'; +import { WebSocketServer } from 'ws'; +import { createStaticHarness } from '../integration/harness/static.ts'; +import type * as Fixture from './harness/inbox-preference-publisher.ts'; +import type { PublicQuotaRepository } from '../../src/lib/persistence/quota.ts'; +import type { BrowserDatabase } from '../../src/lib/persistence/database.ts'; +import type { InboxPreferenceAction } from '../../src/lib/messaging/inbox-setup-operation.ts'; +declare global { + interface Window { + hcp066: typeof Fixture; + hcp066Fixture: Awaited<ReturnType<typeof Fixture.makePublisherFixture>>; + hcp066Repo: PublicQuotaRepository; + hcp066Db: BrowserDatabase; + hcp066Action: InboxPreferenceAction; + hcp066Id: string; + hcp066Restore?: () => void; + hcp066Trace: ReturnType<typeof Fixture.installEffectTrace>; + hcp066ReleaseFault?: ReturnType<typeof Fixture.installUnsubscribeFailure>; + hcp066Run?: Promise<{ status: string }>; + } +} +let server: Awaited<ReturnType<typeof createStaticHarness>>, + socketServer: WebSocketServer, + bundle: string, + endpoint: string; +let frames: string[] = [], + response: 'accepted' | 'refused' | 'silent' | 'timeout-refusal' = 'accepted'; +test.beforeAll(async () => { + server = await createStaticHarness(); + socketServer = new WebSocketServer({ + host: '127.0.0.1', + port: 0, + maxPayload: 65536 + }); + await once(socketServer, 'listening'); + const address = socketServer.address(); + if (!address || typeof address === 'string') + throw new Error('missing loopback'); + endpoint = 'ws://127.0.0.1:' + address.port; + socketServer.on('connection', (socket) => + socket.on('message', (bytes) => { + const raw = Buffer.isBuffer(bytes) + ? bytes.toString() + : Array.isArray(bytes) + ? Buffer.concat(bytes).toString() + : Buffer.from(bytes).toString(), + frame = JSON.parse(raw) as [string, { id: string }]; + if (frame[0] === 'EVENT') { + frames.push(raw); + if (response === 'silent') return; + socket.send( + JSON.stringify([ + 'OK', + frame[1].id, + response === 'accepted', + response === 'accepted' + ? '' + : response === 'timeout-refusal' + ? 'Timeout' + : 'blocked: controlled refusal' + ]) + ); + } + }) + ); + const result = await build({ + configFile: false, + logLevel: 'silent', + build: { + write: false, + minify: false, + lib: { + entry: fileURLToPath( + new URL('./harness/inbox-preference-publisher.ts', import.meta.url) + ), + name: 'hcp066', + formats: ['iife'] + } + } + }); + const output = Array.isArray(result) ? result[0] : result; + if (!('output' in output)) throw new Error('missing output'); + const chunks = output.output.filter((x) => x.type === 'chunk'); + expect(chunks).toHaveLength(1); + bundle = chunks[0].code; + console.log( + JSON.stringify({ + fixture: 'HCP066_ACTUAL_SDK_REAL_IDB_WEBLOCK_LOOPBACK', + bundleSha256: createHash('sha256').update(bundle).digest('hex'), + moduleIds: Object.keys(chunks[0].modules), + qualification: + 'controlled local source only; no real extension/operator/retention/client qualification' + }) + ); +}); +test.afterAll(async () => { + for (const socket of socketServer.clients) socket.terminate(); + await new Promise<void>((resolve) => socketServer.close(() => resolve())); + await server.close(); +}); +test.beforeEach(async ({ page }) => { + frames = []; + response = 'accepted'; + await page.addInitScript( + ({ endpoint }) => { + const Native = window.WebSocket; + class LoopbackSocket extends Native { + constructor(url: string | URL, protocols?: string | string[]) { + if (String(url) !== 'wss://discovery.example.org/') + throw new Error('unexpected fixture destination'); + super(endpoint, protocols); + } + } + window.WebSocket = LoopbackSocket; + }, + { endpoint } + ); + await page.goto(server.url + '/search'); + await page.addScriptTag({ content: bundle }); + await page.evaluate(async () => { + const s = window.hcp066, + f = await s.makePublisherFixture(); + window.hcp066Fixture = f; + const opened = await s.openBrowserDatabase(); + if (opened.state !== 'ready') throw new Error(opened.reason); + window.hcp066Db = opened.owner; + const repo = s.createPublicQuotaRepository(opened.owner, f.owner); + if (!repo) throw new Error('missing repo'); + window.hcp066Repo = repo; + const reviewed = await s.reviewInboxSetup( + f.identity, + f.resolve(), + f.policy, + s.setupInput(), + () => 101 + ); + if (reviewed.status !== 'review') throw new Error(reviewed.reason); + const id = crypto.randomUUID(); + window.hcp066Id = id; + await s.saveInboxPreferenceOperation( + repo, + reviewed.review, + f.resolve(), + id, + 'reviewed_global_inbox_replacement' + ); + const action = await s.beginInboxPreferenceOperation( + repo, + f.identity, + f.policy, + reviewed.review, + id, + () => Promise.resolve(f.resolve()), + 'reviewed_global_inbox_replacement' + ); + if (action.status !== 'prepared') throw new Error(action.status); + window.hcp066Action = action.action; + }); +}); +test.afterEach(async ({ page }) => { + if (!page.isClosed()) + await page.evaluate(() => { + window.hcp066Restore?.(); + window.hcp066Trace?.restore(); + window.hcp066ReleaseFault?.restore(); + window.hcp066Fixture?.close(); + if (window.hcp066Db) window.hcp066.closeBrowserDatabase(window.hcp066Db); + }); +}); +test('actual marker is acknowledged before signing and exact artifact before the first SDK EVENT', async ({ + page +}) => { + const result = await page.evaluate(async () => { + const s = window.hcp066, + f = window.hcp066Fixture; + window.hcp066Trace = s.installEffectTrace(); + let marker = -1; + f.beforeSign(async () => { + const stored = await s.loadPreferenceOperation( + window.hcp066Repo, + window.hcp066Id + ); + if (stored.ok) + marker = s.publicRecordSnapshot( + stored.value, + f.owner, + window.hcp066Id + )!.revision; + }); + const result = await s.runInboxPreferenceOperation(window.hcp066Action); + const stored = await s.loadPreferenceOperation( + window.hcp066Repo, + window.hcp066Id + ); + return { + status: result.status, + marker, + trace: window.hcp066Trace.events(), + signs: f.signs(), + row: stored.ok + ? s.publicRecordSnapshot(stored.value, f.owner, window.hcp066Id) + : null + }; + }); + expect(result.status).toBe('completed'); + expect(result.marker).toBe(1); + expect(result.signs).toBe(1); + expect(result.trace.indexOf('ack:2')).toBeGreaterThan(-1); + expect(result.trace.indexOf('EVENT')).toBeGreaterThan( + result.trace.indexOf('ack:2') + ); + expect(frames).toHaveLength(1); + expect(JSON.parse(frames[0]) as unknown[]).toEqual([ + 'EVENT', + JSON.parse( + result.row!.family !== 'public_draft' ? result.row!.artifact!.wire : '' + ) as unknown + ]); + expect( + result.row!.family !== 'public_draft' && result.row!.receipts[0].status + ).toBe('accepted'); +}); +for (const revision of [1, 2]) + test(`real IDB abort at revision ${revision} prevents EVENT and unknown attempt cannot sign again`, async ({ + page + }) => { + const result = await page.evaluate(async (revision) => { + const s = window.hcp066, + f = window.hcp066Fixture; + window.hcp066Restore = s.failPreferenceWrite(revision); + const first = await s.runInboxPreferenceOperation(window.hcp066Action); + const resume = await s.resumeInboxPreferenceOperation( + window.hcp066Repo, + f.identity, + f.policy, + window.hcp066Id, + () => Promise.resolve(f.resolve()), + 'reviewed_stored_inbox_preference' + ); + if (revision === 2 && resume.status === 'prepared') + await s.runInboxPreferenceOperation(resume.action); + const stored = await s.loadPreferenceOperation( + window.hcp066Repo, + window.hcp066Id + ); + return { + status: first.status, + signs: f.signs(), + revision: stored.ok + ? s.publicRecordSnapshot(stored.value, f.owner, window.hcp066Id)! + .revision + : -1 + }; + }, revision); + expect(result.status).toBe('storage_failed'); + expect(result.signs).toBe(revision === 1 ? 0 : 1); + expect(result.revision).toBe(revision - 1); + expect(frames).toHaveLength(0); + }); +test('late changed extension owner keeps unsigned uncertainty and never publishes', async ({ + page +}) => { + const result = await page.evaluate(async () => { + const s = window.hcp066, + f = window.hcp066Fixture; + f.beforeSign(() => { + f.changeOwner(); + return Promise.resolve(); + }); + const result = await s.runInboxPreferenceOperation(window.hcp066Action); + const stored = await s.loadPreferenceOperation( + window.hcp066Repo, + window.hcp066Id + ); + return { + status: result.status, + signs: f.signs(), + row: stored.ok + ? s.publicRecordSnapshot(stored.value, f.owner, window.hcp066Id) + : null + }; + }); + expect(result.status).not.toBe('completed'); + expect(result.signs).toBe(1); + expect(result.row!.revision).toBe(1); + expect( + result.row!.family !== 'public_draft' && result.row!.artifact + ).toBeNull(); + expect(frames).toHaveLength(0); +}); +test('explicit stored retry sends the identical artifact without a second signature; accepted targets are skipped', async ({ + page +}) => { + response = 'refused'; + await page.evaluate(() => + window.hcp066.runInboxPreferenceOperation(window.hcp066Action) + ); + expect(frames).toHaveLength(1); + response = 'accepted'; + const retry = async () => + page.evaluate(async () => { + const s = window.hcp066, + f = window.hcp066Fixture; + s.disconnectIdentity(f.identity); + const identity = s.createIdentitySession(); + await s.connectIdentity(identity); + await s.probeIdentityMessaging(identity, 'reviewed_self_copy'); + const prepared = await s.resumeInboxPreferenceOperation( + window.hcp066Repo, + identity, + f.policy, + window.hcp066Id, + () => Promise.resolve(f.resolve()), + 'reviewed_stored_inbox_preference' + ); + if (prepared.status !== 'prepared') throw new Error(prepared.status); + const result = { + result: (await s.runInboxPreferenceOperation(prepared.action)).status, + signs: f.signs() + }; + s.disconnectIdentity(identity); + return result; + }); + expect(await retry()).toEqual({ result: 'completed', signs: 1 }); + expect(frames).toHaveLength(2); + expect(frames[1]).toBe(frames[0]); + expect(await retry()).toEqual({ result: 'completed', signs: 1 }); + expect(frames).toHaveLength(2); +}); +test('Stop during the actual permission wait prevents publication and preserves uncertainty', async ({ + page +}) => { + const result = await page.evaluate(async () => { + const s = window.hcp066, + f = window.hcp066Fixture; + f.beforeSign(() => { + s.stopInboxPreferenceOperation(window.hcp066Action); + return Promise.resolve(); + }); + const result = await s.runInboxPreferenceOperation(window.hcp066Action); + const row = await s.loadPreferenceOperation( + window.hcp066Repo, + window.hcp066Id + ); + return { + status: result.status, + signs: f.signs(), + revision: row.ok + ? s.publicRecordSnapshot(row.value, f.owner, window.hcp066Id)!.revision + : -1 + }; + }); + expect(result).toEqual({ status: 'stopped', signs: 1, revision: 1 }); + expect(frames).toHaveLength(0); +}); +test('competing and incomplete preference observations block explicit stored resume', async ({ + page +}) => { + response = 'refused'; + await page.evaluate(() => + window.hcp066.runInboxPreferenceOperation(window.hcp066Action) + ); + const result = await page.evaluate(async () => { + const s = window.hcp066, + f = window.hcp066Fixture; + const competing = await s.resumeInboxPreferenceOperation( + window.hcp066Repo, + f.identity, + f.policy, + window.hcp066Id, + () => Promise.resolve(f.resolve(f.competing())), + 'reviewed_stored_inbox_preference' + ); + const partial = await s.resumeInboxPreferenceOperation( + window.hcp066Repo, + f.identity, + f.policy, + window.hcp066Id, + () => Promise.resolve(f.resolve(undefined, false)), + 'reviewed_stored_inbox_preference' + ); + return [competing.status, partial.status, f.signs()]; + }); + expect(result).toEqual(['conflict', 'conflict', 1]); + expect(frames).toHaveLength(1); +}); +test('actual SDK timeouts allow only three explicit same-artifact attempts and retain each named fact', async ({ + page +}) => { + test.setTimeout(45000); + response = 'silent'; + const result = await page.evaluate(async () => { + const s = window.hcp066, + f = window.hcp066Fixture; + const result = await s.runInboxPreferenceOperation(window.hcp066Action); + const row = await s.loadPreferenceOperation( + window.hcp066Repo, + window.hcp066Id + ); + const snapshot = row.ok + ? s.publicRecordSnapshot(row.value, f.owner, window.hcp066Id) + : null; + return { + status: result.status, + signs: f.signs(), + receipts: + snapshot && snapshot.family !== 'public_draft' ? snapshot.receipts : [] + }; + }); + expect(result.status).toBe('needs_action'); + expect(result.signs).toBe(1); + expect(frames).toHaveLength(3); + expect(new Set(frames).size).toBe(1); + expect( + result.receipts.map((row) => [row.origin, row.attempt, row.status]) + ).toEqual( + [1, 2, 3].map((attempt) => [ + 'wss://discovery.example.org', + attempt, + 'timed_out' + ]) + ); +}); +test('Stop during the actual policy digest prevents even a new durable signing marker', async ({ + page +}) => { + const result = await page.evaluate(async () => { + const s = window.hcp066, + f = window.hcp066Fixture; + const original = Reflect.get<SubtleCrypto, 'digest'>( + crypto.subtle, + 'digest' + ); + crypto.subtle.digest = async function ( + ...args: Parameters<SubtleCrypto['digest']> + ) { + const buffer = await original.call(this, ...args); + s.stopInboxPreferenceOperation(window.hcp066Action); + return buffer; + }; + try { + const result = await s.runInboxPreferenceOperation(window.hcp066Action); + const read = await s.loadPreferenceOperation( + window.hcp066Repo, + window.hcp066Id + ); + return { + status: result.status, + signs: f.signs(), + revision: read.ok + ? s.publicRecordSnapshot(read.value, f.owner, window.hcp066Id)! + .revision + : -1 + }; + } finally { + crypto.subtle.digest = original; + } + }); + expect(result).toEqual({ status: 'stopped', signs: 0, revision: 0 }); + expect(frames).toHaveLength(0); +}); +test('a real relay refusal worded Timeout is ambiguous evidence and never automatically retried', async ({ + page +}) => { + response = 'timeout-refusal'; + const result = await page.evaluate(async () => { + const s = window.hcp066, + f = window.hcp066Fixture; + const result = await s.runInboxPreferenceOperation(window.hcp066Action); + const read = await s.loadPreferenceOperation( + window.hcp066Repo, + window.hcp066Id + ); + const row = read.ok + ? s.publicRecordSnapshot(read.value, f.owner, window.hcp066Id) + : null; + return { + status: result.status, + signs: f.signs(), + receipts: + row && row.family !== 'public_draft' + ? row.receipts.map((fact) => fact.status) + : [] + }; + }); + expect(result).toEqual({ + status: 'needs_action', + signs: 1, + receipts: ['unknown'] + }); + expect(frames).toHaveLength(1); +}); +test('pending real publication release failure blocks terminal cleanup until the same control is released', async ({ + page +}) => { + response = 'silent'; + await page.evaluate(() => { + const s = window.hcp066; + window.hcp066ReleaseFault = s.installUnsubscribeFailure(); + window.hcp066Run = s.runInboxPreferenceOperation(window.hcp066Action); + }); + await expect.poll(() => frames.length).toBe(1); + const result = await page.evaluate(async () => { + const s = window.hcp066, + pool = s.getPublicPool(window.hcp066Fixture.policy)!; + let firstFailed = false; + try { + s.closePublicPool(pool); + } catch { + firstFailed = true; + } + window.hcp066ReleaseFault!.allowRelease(); + s.closePublicPool(pool); + s.closePublicPool(pool); + return { firstFailed, status: (await window.hcp066Run)!.status }; + }); + expect(result.firstFailed).toBe(true); + expect(result.status).not.toBe('completed'); + expect(frames).toHaveLength(1); +}); diff --git a/web/tests/integration/inbox-preference-publisher.test.ts b/web/tests/integration/inbox-preference-publisher.test.ts @@ -0,0 +1,15 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { + runInboxPreferenceOperation, + stopInboxPreferenceOperation +} from '../../src/lib/messaging/inbox-setup-operation.ts'; +import { preferencePublicationSnapshot } from '../../src/lib/nostr/inbox-preference-publication.ts'; +await test('SSR and forged preference controls expose no arbitrary event publisher or effects', async () => { + assert.equal(typeof window, 'undefined'); + assert.deepEqual(await runInboxPreferenceOperation({} as never), { + status: 'invalid' + }); + assert.equal(preferencePublicationSnapshot({} as never), undefined); + assert.doesNotThrow(() => stopInboxPreferenceOperation({} as never)); +}); diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs @@ -564,8 +564,13 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { assert.ok(entry, 'Missing observed compiler role: ' + name); return entry; }; + const identityCompilerRole = Object.values(manifest).some( + (record) => record.name === 'identity-session' + ) + ? 'identity-session' + : 'heads'; const [identityKey, identity] = find('view-context'), - [headsKey, heads] = find('heads'); + [headsKey, heads] = find(identityCompilerRole); if (mutation === 'missing-view') delete manifest[identityKey]; if (mutation === 'missing-heads') delete manifest[headsKey]; if (mutation === 'extra-view-field') identity.dynamicImports = []; diff --git a/web/tests/unit/inbox-preference-publisher.test.ts b/web/tests/unit/inbox-preference-publisher.test.ts @@ -0,0 +1,53 @@ +import { it, expect } from 'vitest'; +import { makeFixture } from '../e2e/harness/approved-signing.ts'; +import { + preparePreferenceSigningTransition, + publicTransitionSnapshot +} from '../../src/lib/persistence/artifact-records.ts'; +import { + decodePublicRecord, + publicRecordSnapshot +} from '../../src/lib/persistence/records.ts'; +it('acknowledged preference signing marker preserves the complete original capture and cannot be reset', () => { + const f = makeFixture(10050); + try { + const result = preparePreferenceSigningTransition(f.record, f.owner, f.id); + expect(result.ok).toBe(true); + if (!result.ok) return; + const next = publicTransitionSnapshot(result.value, f.owner, f.id)!; + const decoded = decodePublicRecord(next.nextWire, f.owner, f.id); + expect(decoded.ok).toBe(true); + if (!decoded.ok) return; + const original = publicRecordSnapshot(f.record, f.owner, f.id)!; + const marked = publicRecordSnapshot(decoded.value, f.owner, f.id)!; + expect(marked).toEqual({ ...original, revision: 1 }); + expect( + preparePreferenceSigningTransition(decoded.value, f.owner, f.id).ok + ).toBe(false); + } finally { + f.close(); + } +}); +it('marker rejects food, withdrawal, foreign owner and forged handles', () => { + for (const kind of [30402, 5] as const) { + const f = makeFixture(kind); + try { + expect( + preparePreferenceSigningTransition(f.record, f.owner, f.id).ok + ).toBe(false); + } finally { + f.close(); + } + } + const f = makeFixture(10050); + try { + expect( + preparePreferenceSigningTransition(f.record, '0'.repeat(64), f.id).ok + ).toBe(false); + expect( + preparePreferenceSigningTransition({} as never, f.owner, f.id).ok + ).toBe(false); + } finally { + f.close(); + } +}); diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs @@ -459,6 +459,27 @@ async function searchPresentationAdmission(web) { } return true; } +// HCP066 exact owned preference port changes the shared compiler chunk name. +// Preserve the full module/path/output rejection policy; no arbitrary admission. +/** @param {string} web */ +async function preferencePublicationAdmission(web) { + const pool = await readOwned(web, 'src/lib/nostr/public-pool.ts'); + if (!pool.toString().includes("'./inbox-preference-publication.ts'")) + return false; + const producers = { + 'src/lib/nostr/public-pool.ts': + 'd5054acecd074a36e68d39e1f69c86cdde6480339c7f4bf901ece151a2b6a5b7', + 'src/lib/nostr/inbox-preference-publication.ts': + 'fbad642340732bf7cf92905010af314829b80cc7b134121396f14e9bb8e765cc' + }; + 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 preference publication source'); + } + return true; +} /** @param {string} webDirectory */ export async function auditOutput(webDirectory) { const web = path.resolve(webDirectory); @@ -560,6 +581,11 @@ export async function auditOutput(webDirectory) { hasFullRoutes && hasPublicRuntime && (await productPresentationAdmission(web)); + const hasPreferencePublication = + hasPublicRuntime && (await preferencePublicationAdmission(web)); + const identityCompilerModule = hasPreferencePublication + ? 'identity-session' + : 'heads'; // Admit compiler-owned module identities, not arbitrary extensions/copy roots. const names = new Set([ 'entry/app', @@ -597,7 +623,7 @@ export async function auditOutput(webDirectory) { ...(hasSearchPresentation ? ['Disclosure', 'navigation'] : ['dist']), 'negentropy', ...(hasPublicRuntime === 'public_identity' - ? ['view-context', 'heads'] + ? ['view-context', identityCompilerModule] : ['budgets']) ]) names.add(name); @@ -741,7 +767,7 @@ export async function auditOutput(webDirectory) { equal( sdk.imports, hasPublicRuntime === 'public_identity' - ? [requiredRecord('heads')[0], dist[0]] + ? [requiredRecord(identityCompilerModule)[0], dist[0]] : [dist[0]], 'Invalid owned SDK compiler dependency' ); @@ -772,7 +798,13 @@ export async function auditOutput(webDirectory) { equal( dist[1].imports, (hasPublicRuntime === 'public_identity' - ? ['public-key', 'preload-helper', 'heads', 'client', 'Button'] + ? [ + 'public-key', + 'preload-helper', + identityCompilerModule, + 'client', + 'Button' + ] : [ 'rolldown-runtime', 'preload-helper', @@ -797,8 +829,16 @@ export async function auditOutput(webDirectory) { if (hasPublicRuntime === 'public_identity') { /** @type {[string, string[]][]} */ const identityDependencies = [ - ['view-context', ['public-key', 'heads', 'client', 'Button']], - ['heads', ['public-key', 'Button']] + [ + 'view-context', + [ + ...(hasPreferencePublication ? [] : ['public-key']), + identityCompilerModule, + 'client', + 'Button' + ] + ], + [identityCompilerModule, ['public-key', 'Button']] ]; for (const [name, dependencies] of identityDependencies) { const [key, record] = requiredRecord(name); @@ -854,7 +894,7 @@ export async function auditOutput(webDirectory) { equal( publisher.imports, (hasPublicRuntime === 'public_identity' - ? ['public-key', 'heads', 'Disclosure', 'Button'] + ? ['public-key', identityCompilerModule, 'Disclosure', 'Button'] : ['public-key', 'Disclosure', 'budgets'] ).map((name) => entry(name)[0]), 'Invalid owned product publisher compiler dependencies' @@ -865,7 +905,7 @@ export async function auditOutput(webDirectory) { ? [ 'public-key', 'references', - 'heads', + identityCompilerModule, 'Disclosure', 'client', 'Button', @@ -892,7 +932,7 @@ export async function auditOutput(webDirectory) { (hasPublicRuntime === 'public_identity' ? [ 'references', - 'heads', + identityCompilerModule, 'Disclosure', 'client', 'Button',