app

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

commit 6023db01169aa82cb6fe68ca94e1a73750247e72
parent c25fae87ba8f92b80c70e11e5244600d4eca0586
Author: triesap <tyson@radroots.org>
Date:   Wed,  7 Oct 2026 02:16:51 +0000

web: invalidate sessions and reconcile late extension results (HCP-055)

- Bind public operations to immutable original captures and nonreviving sessions.
- Fence route changes, input changes, logout, Stop and expired waits.
- Retain verified late artifacts for explicit original operation review.
- Cover real SDK timing and account changes with browser regressions.

Diffstat:
Mweb/src/lib/nostr/extension.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++------------
Mweb/src/lib/runtime/identity-session.ts | 227+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/runtime/late-results.ts | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/harness/late-results.ts | 18++++++++++++++++++
Aweb/tests/e2e/late-results.spec.ts | 592+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/integration/late-results.test.ts | 35+++++++++++++++++++++++++++++++++++
Mweb/tests/unit/identity-session.test.ts | 22++++++++++++++++++++++
Aweb/tests/unit/late-results.test.ts | 166+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 1205 insertions(+), 12 deletions(-)

diff --git a/web/src/lib/nostr/extension.ts b/web/src/lib/nostr/extension.ts @@ -13,6 +13,10 @@ import { } from './approved-signing.ts'; import type { CapturedArtifact } from '../persistence/artifact-records.ts'; import { + bindLatePublicResponse, + type LatePublicArtifact +} from '../runtime/late-results.ts'; +import { callOwnedExtension, publicEffectLeaseCurrent, publicEffectSnapshot, @@ -23,11 +27,11 @@ import { export type ApprovedSignResult = | Readonly<{ status: 'signed'; artifact: CapturedArtifact }> + | Readonly<{ status: 'unknown'; late?: LatePublicArtifact }> | Readonly<{ status: | 'invalid_approval' | 'invalid_ownership' - | 'unknown' | 'unavailable' | 'busy' | 'stale' @@ -39,6 +43,7 @@ import { browserExtensionScheduler, runExtensionAction, callExtension, + markExtensionWaitExpired, type ExtensionAction, type ExtensionCallKind } from './extension-scheduler.ts'; @@ -76,6 +81,7 @@ type Controller = { recheck(): Promise<ExtensionSnapshot>; probe(review: unknown): Promise<ExtensionSnapshot>; capture(): PublicEffectCapture | undefined; + expire(approval: ApprovedPublicSigning, lease: PublicEffectLease): void; sign( approval: ApprovedPublicSigning, lease: PublicEffectLease @@ -137,6 +143,11 @@ export function createExtensionAdapter(): ExtensionAdapter { let reason: ExtensionGuestReason = 'disconnected'; let pending: 'connect' | 'recheck' | 'probe' | null = null; let signing = false; + let activeSigning: Readonly<{ + approval: ApprovedPublicSigning; + lease: PublicEffectLease; + action: ExtensionAction; + }> | null = null; let generation = Symbol(), cancelled = false; function snapshot(): ExtensionSnapshot { @@ -146,6 +157,9 @@ export function createExtensionAdapter(): ExtensionAdapter { : { state: 'guest', reason }; } function guest(nextReason: ExtensionGuestReason) { + // An observed account loss cannot later revive an old capture, including + // a reconnect to the same key. Rotate before clearing the observed owner. + if (key !== null) generation = Symbol(); key = null; signingCandidate = false; messaging = 'not_probed'; @@ -396,6 +410,12 @@ export function createExtensionAdapter(): ExtensionAdapter { key === owner && publicEffectLeaseCurrent(lease, authority); signing = true; + let late: LatePublicArtifact | undefined; + function lost(): ApprovedSignResult { + return publicEffectSnapshot(lease)?.state === 'unknown' + ? { status: 'unknown', ...(late ? { late } : {}) } + : { status: 'stale' }; + } try { const owned = await callOwnedExtension( lease, @@ -408,6 +428,7 @@ export function createExtensionAdapter(): ExtensionAdapter { { owner, session: original, operation: Symbol() }, current, async (action): Promise<ApprovedSignResult> => { + activeSigning = { approval, lease, action }; const before = await freshKey(current, action); if (!current()) return { status: 'stale' }; if (before !== owner) { @@ -422,7 +443,14 @@ export function createExtensionAdapter(): ExtensionAdapter { const response: unknown = await invokeExtension( action, 'sign', - () => signer.signEvent(disposable) + async () => { + const raw: unknown = await signer.signEvent(disposable); + // Retain only bounded independently verified original public + // fields inside the actual admitted SDK callback, even after + // its owner/view/wait generation was invalidated. No new call. + late = bindLatePublicResponse(approval, raw, original); + return raw; + } ); if (!current()) return { status: 'stale' }; const artifact = bindApprovedResponse(approval, response); @@ -444,14 +472,9 @@ export function createExtensionAdapter(): ExtensionAdapter { } ); if (owned.status === 'settled') - return owned.current - ? owned.value - : { - status: - publicEffectSnapshot(lease)?.state === 'unknown' - ? 'unknown' - : 'stale' - }; + return owned.current ? owned.value : lost(); + if (owned.status === 'unknown') + return { status: 'unknown', ...(late ? { late } : {}) }; return { status: owned.status === 'invalid' @@ -461,8 +484,9 @@ export function createExtensionAdapter(): ExtensionAdapter { : owned.status }; } catch { - return { status: current() ? 'refused' : 'stale' }; + return current() ? { status: 'refused' } : lost(); } finally { + activeSigning = null; signing = false; } } @@ -483,7 +507,11 @@ export function createExtensionAdapter(): ExtensionAdapter { current: () => generation === original && !cancelled && key === owner }; }, - sign + sign, + expire(approval, lease) { + if (activeSigning?.approval === approval && activeSigning.lease === lease) + markExtensionWaitExpired(activeSigning.action); + } }); return adapter; } @@ -545,3 +573,12 @@ export function extensionOwnershipCapture( ): PublicEffectCapture | undefined { return adapters.get(adapter)?.capture(); } +// Internal exact original operation port. Expiry pauses the real scheduler; +// neither this method nor a UI timeout pretends to cancel the SDK promise. +export function markApprovedSigningWaitExpired( + adapter: ExtensionAdapter, + approval: ApprovedPublicSigning, + lease: PublicEffectLease +): void { + adapters.get(adapter)?.expire(approval, lease); +} diff --git a/web/src/lib/runtime/identity-session.ts b/web/src/lib/runtime/identity-session.ts @@ -5,10 +5,35 @@ import { recheckExtensionAdapter, probeExtensionAdapter, disconnectExtensionAdapter, + extensionOwnershipCapture, + signApprovedExtensionAdapter, + markApprovedSigningWaitExpired, + type ApprovedSignResult, type ExtensionAdapter, type ExtensionSnapshot, type ExtensionGuestReason } from '../nostr/extension.ts'; +import { approveCapturedPublicSigning } from '../nostr/approved-signing.ts'; +import { + publicRecordSnapshot, + publicRecordWire, + type PublicRecordHandle +} from '../persistence/records.ts'; +import { + stopPublicEffect, + type PublicEffectLease, + type PublicEffectCapture +} from './effect-ownership.ts'; +import { + bindLatePublicResponse, + latePublicResultIdentity, + reviewLatePublicArtifact, + type LatePublicArtifact +} from './late-results.ts'; +import { + capturedArtifactSnapshot, + type CapturedArtifact +} from '../persistence/artifact-records.ts'; declare const sessionBrand: unique symbol; export type IdentitySession = Readonly<{ [sessionBrand]: true }>; @@ -25,9 +50,40 @@ export type IdentitySnapshot = ( // Per-client opaque session, never a module-global server user. A public key is // an extension observation, not installed-account or publishing authorization. const sessions = new WeakMap<IdentitySession, ExtensionAdapter>(); +type ViewController = { stamp(): symbol; invalidate(): void }; +const views = new WeakMap<IdentitySession, ViewController>(); +declare const operationBrand: unique symbol; +export type IdentityPublicOperation = Readonly<{ [operationBrand]: true }>; +type OperationController = { + session: IdentitySession; + ownership(): PublicEffectCapture | undefined; + sign(lease: PublicEffectLease): Promise<ApprovedSignResult>; + stop(expired: boolean): void; + snapshot(): Readonly<{ + owner: string; + id: string; + revision: number; + hash: string; + current: boolean; + lateAvailable: boolean; + outcome: ApprovedSignResult['status'] | 'not_started' | 'pending'; + }>; + review( + record: PublicRecordHandle, + review: unknown + ): CapturedArtifact | undefined; +}; +const operations = new WeakMap<IdentityPublicOperation, OperationController>(); export function createIdentitySession(): IdentitySession { const session = Object.freeze({}) as IdentitySession; sessions.set(session, createExtensionAdapter()); + let stamp = Symbol(); + views.set(session, { + stamp: () => stamp, + invalidate() { + stamp = Symbol(); + } + }); return session; } function mapIdentitySnapshot(snapshot: ExtensionSnapshot): IdentitySnapshot { @@ -80,6 +136,177 @@ export async function probeIdentityMessaging( return identitySessionSnapshot(session); } export function disconnectIdentity(session: IdentitySession): void { + views.get(session)?.invalidate(); const adapter = sessions.get(session); if (adapter) disconnectExtensionAdapter(adapter); } +// Explicit route/input lifecycle event. No draft, DB, reconnect or SDK effect. +export function invalidateIdentityOperations(session: IdentitySession): void { + views.get(session)?.invalidate(); +} +// Internal public operation capability, never an unrestricted UI template signer. +// Current-head/inbox/IDB preparation and publication retain their typed owners. +export function captureIdentityPublicOperation( + session: IdentitySession, + record: PublicRecordHandle, + id: unknown, + review: unknown +): IdentityPublicOperation | undefined { + const adapter = sessions.get(session), + view = views.get(session); + const captured = adapter && extensionOwnershipCapture(adapter); + if (!adapter || !view || !captured) return undefined; + const row = publicRecordSnapshot(record, captured.owner, id), + recordWire = publicRecordWire(record, captured.owner, id); + const approval = approveCapturedPublicSigning( + record, + captured.owner, + id, + review + ); + if ( + !row || + !recordWire || + !approval || + row.family === 'public_draft' || + row.revision !== 0 + ) + return undefined; + const owner = row.owner, + command = row.id, + epoch = view.stamp(), + originalSession = captured.session; + let stopped = false, + pending = false; + let lease: PublicEffectLease | undefined, + late: LatePublicArtifact | undefined; + let outcome: ApprovedSignResult['status'] | 'not_started' | 'pending' = + 'not_started'; + const current = () => + !stopped && view.stamp() === epoch && captured.current(); + const token = Object.freeze({}) as IdentityPublicOperation; + operations.set(token, { + session, + ownership: () => + current() ? { owner, session: originalSession, current } : undefined, + async sign(originalLease) { + if (pending) return { status: 'busy' }; + if (!current()) return { status: 'stale' }; + pending = true; + lease = originalLease; + outcome = 'pending'; + try { + let result = await signApprovedExtensionAdapter( + adapter, + approval, + originalLease + ); + // The adapter's promise can settle before this continuation runs. + // Recheck this view before disclosing a normal signed result. + if (result.status === 'signed' && !current()) { + const artifact = capturedArtifactSnapshot(result.artifact); + const originalLate = + artifact && + bindLatePublicResponse( + approval, + JSON.parse(artifact.wire), + originalSession + ); + result = originalLate + ? { status: 'unknown', late: originalLate } + : { status: 'unknown' }; + } + outcome = result.status; + if (result.status === 'unknown' && result.late) { + const original = latePublicResultIdentity(result.late); + if ( + original?.owner === owner && + original.id === command && + original.recordWire === recordWire && + original.session === originalSession + ) + late = result.late; + } + // Only disclosure/explicit original-operation review can obtain a late + // artifact. A normal signing result never returns it after invalidation. + return result.status === 'unknown' ? { status: 'unknown' } : result; + } finally { + pending = false; + lease = undefined; + } + }, + stop(expired) { + stopped = true; + if (lease) { + if (expired) markApprovedSigningWaitExpired(adapter, approval, lease); + stopPublicEffect(lease); + } + }, + snapshot: () => ({ + owner, + id: command, + revision: row.revision, + hash: row.capture.hash, + current: current(), + lateAvailable: late !== undefined, + outcome + }), + review(original, consent) { + const observed = extensionSnapshot(adapter); + return late && + observed.state === 'connected' && + observed.publicKey === owner + ? reviewLatePublicArtifact(late, original, owner, command, consent) + : undefined; + } + }); + return token; +} +function operationOf(session: IdentitySession, token: IdentityPublicOperation) { + const operation = operations.get(token); + return operation?.session === session ? operation : undefined; +} +export function identityPublicOperationOwnership( + session: IdentitySession, + operation: IdentityPublicOperation +): PublicEffectCapture | undefined { + return operationOf(session, operation)?.ownership(); +} +export function identityPublicOperationSnapshot( + session: IdentitySession, + operation: IdentityPublicOperation +) { + return operationOf(session, operation)?.snapshot(); +} +export function signIdentityPublicOperation( + session: IdentitySession, + operation: IdentityPublicOperation, + lease: PublicEffectLease +): Promise<ApprovedSignResult> { + return ( + operationOf(session, operation)?.sign(lease) ?? + Promise.resolve({ status: 'invalid_approval' }) + ); +} +export function stopIdentityPublicOperation( + session: IdentitySession, + operation: IdentityPublicOperation +): void { + operationOf(session, operation)?.stop(false); +} +// UI supplies expiry; existing scheduler owns its actual pending promise. +export function expireIdentityPublicOperationWait( + session: IdentitySession, + operation: IdentityPublicOperation +): void { + operationOf(session, operation)?.stop(true); +} +// Pure same-author original review, not fresh author/CAS/resume/publish proof. +export function reviewIdentityLatePublicArtifact( + session: IdentitySession, + operation: IdentityPublicOperation, + original: PublicRecordHandle, + review: unknown +): CapturedArtifact | undefined { + return operationOf(session, operation)?.review(original, review); +} diff --git a/web/src/lib/runtime/late-results.ts b/web/src/lib/runtime/late-results.ts @@ -0,0 +1,96 @@ +import { + approvedSigningIdentity, + bindApprovedResponse, + type ApprovedPublicSigning +} from '../nostr/approved-signing.ts'; +import { + capturedArtifactSnapshot, + type CapturedArtifact +} from '../persistence/artifact-records.ts'; +import { + publicRecordWire, + type PublicRecordHandle +} from '../persistence/records.ts'; + +declare const lateBrand: unique symbol; +export type LatePublicArtifact = Readonly<{ [lateBrand]: true }>; +type Saved = Readonly<{ + owner: string; + id: string; + revision: number; + recordWire: string; + session: symbol; + hash: string; + artifact: CapturedArtifact; +}>; +const results = new WeakMap<LatePublicArtifact, Saved>(); +// Pure exact public binding, not proof of SDK admission or current authority. +// The real adapter retains raw responses inside an admitted signature callback. +// Its same-job verified artifact may be reclassified if the identity continuation +// loses freshness. Provider objects and mutable verification caches never survive. +export function bindLatePublicResponse( + approval: ApprovedPublicSigning, + response: unknown, + session: unknown +): LatePublicArtifact | undefined { + const identity = approvedSigningIdentity(approval); + if (!identity || typeof session !== 'symbol') return undefined; + const artifact = bindApprovedResponse(approval, response), + view = artifact && capturedArtifactSnapshot(artifact); + if (!artifact || !view) return undefined; + const token = Object.freeze({}) as LatePublicArtifact; + results.set(token, { + owner: identity.owner, + id: identity.id, + revision: identity.revision, + recordWire: identity.recordWire, + session, + hash: view.hash, + artifact + }); + return token; +} +// Internal original-authority metadata. This does not revive a session or lease. +export function latePublicResultIdentity(token: LatePublicArtifact) { + const saved = results.get(token); + return saved + ? { + owner: saved.owner, + id: saved.id, + revision: saved.revision, + recordWire: saved.recordWire, + session: saved.session + } + : undefined; +} +export function latePublicResultSnapshot(token: LatePublicArtifact) { + const saved = results.get(token); + return saved + ? { + owner: saved.owner, + id: saved.id, + revision: saved.revision, + hash: saved.hash + } + : undefined; +} +// Namespace-scoped mechanical review only. The session owner separately checks +// observed author; fresh resume/readiness/IDB CAS and publication remain distinct. +export function reviewLatePublicArtifact( + token: LatePublicArtifact, + original: PublicRecordHandle, + owner: unknown, + id: unknown, + review: unknown +): CapturedArtifact | undefined { + const saved = results.get(token); + if ( + !saved || + review !== 'review_original_late_artifact' || + owner !== saved.owner || + id !== saved.id || + publicRecordWire(original, owner, id) !== saved.recordWire + ) + return undefined; + return saved.artifact; +} diff --git a/web/tests/e2e/harness/late-results.ts b/web/tests/e2e/harness/late-results.ts @@ -0,0 +1,18 @@ +export { makeFixture } from './approved-signing.ts'; +export * from '../../../src/lib/runtime/identity-session.ts'; +export { latePublicResultSnapshot } from '../../../src/lib/runtime/late-results.ts'; +export { runCapturedPublicEffect } from '../../../src/lib/runtime/effect-ownership.ts'; +export { + createPublicQuotaRepository, + inspectPublicStorage, + publicInventorySnapshot +} from '../../../src/lib/persistence/quota.ts'; +export { + openBrowserDatabase, + closeBrowserDatabase +} from '../../../src/lib/persistence/database.ts'; +export { + publicRecordWire, + publicRecordSnapshot +} from '../../../src/lib/persistence/records.ts'; +export { capturedArtifactSnapshot } from '../../../src/lib/persistence/artifact-records.ts'; diff --git a/web/tests/e2e/late-results.spec.ts b/web/tests/e2e/late-results.spec.ts @@ -0,0 +1,592 @@ +import { test, expect, type Page } from '@playwright/test'; +import { build } from 'vite'; +import { fileURLToPath } from 'node:url'; +import { createHash } from 'node:crypto'; +import { createStaticHarness } from '../integration/harness/static.ts'; +import type * as Late from './harness/late-results.ts'; +import type * as Legacy from '../../src/lib/nostr/extension.ts'; +import type { ApprovedSignResult } from '../../src/lib/nostr/extension.ts'; +import type { PublicEffectResult } from '../../src/lib/runtime/effect-ownership.ts'; +declare global { + interface Window { + hcp055: typeof Late; + hcp055Fixture: ReturnType<typeof Late.makeFixture>; + hcp055Other: ReturnType<typeof Late.makeFixture>; + hcp055Legacy: typeof Legacy; + hcp055Session: Late.IdentitySession; + hcp055Operation: Late.IdentityPublicOperation; + hcp055Database: Parameters<typeof Late.closeBrowserDatabase>[0]; + hcp055Repository: ReturnType<typeof Late.createPublicQuotaRepository> & {}; + hcp055Release(): void; + hcp055Started(): void; + hcp055Inner: ApprovedSignResult; + hcp055Counts: { keys: number; signs: number; work: number }; + hcp055Task: Promise<PublicEffectResult<unknown>>; + } +} +let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string; +test.beforeAll(async () => { + server = await createStaticHarness(); + const legacyOnly = process.env.HARVESTCIRCLE_HCP055_LEGACY_RED === '1'; + const result = await build({ + configFile: false, + logLevel: 'silent', + build: { + write: false, + minify: false, + lib: { + entry: fileURLToPath( + new URL( + legacyOnly + ? '../../src/lib/nostr/extension.ts' + : './harness/late-results.ts', + import.meta.url + ) + ), + name: legacyOnly ? 'hcp055Legacy' : 'hcp055', + formats: ['iife'] + } + } + }); + const output = Array.isArray(result) ? result[0] : result; + if (!('output' in output)) throw new Error('missing bundle'); + const chunks = output.output.filter((item) => item.type === 'chunk'); + expect(chunks).toHaveLength(1); + bundle = chunks[0].code; + console.log( + JSON.stringify({ + fixture: 'HCP055_ACTUAL_SDK_IDB_ORIGINAL_LATE_REVIEW', + bundleSha256: createHash('sha256').update(bundle).digest('hex'), + moduleIds: Object.keys(chunks[0].modules), + qualification: + 'controlled local Chromium and genuine SDK; no named extension/UI publication/real relay claim' + }) + ); +}); +test.afterAll(async () => server.close()); +test.afterEach(async ({ page }) => { + await page.evaluate(() => { + window.hcp055Fixture?.close(); + window.hcp055Other?.close(); + if (window.hcp055Database) + window.hcp055.closeBrowserDatabase(window.hcp055Database); + }); +}); +test('legacy adapter capture never revives after observed account loss and same-author reconnect', async ({ + page +}) => { + await page.goto(server.url + '/search'); + const result = await build({ + configFile: false, + logLevel: 'silent', + build: { + write: false, + minify: false, + lib: { + entry: fileURLToPath( + new URL('../../src/lib/nostr/extension.ts', import.meta.url) + ), + name: 'hcp055Legacy', + formats: ['iife'] + } + } + }); + const output = Array.isArray(result) ? result[0] : result; + if (!('output' in output)) throw new Error('missing legacy bundle'); + const chunks = output.output.filter((item) => item.type === 'chunk'); + expect(chunks).toHaveLength(1); + await page.addScriptTag({ content: chunks[0].code }); + const observed = await page.evaluate(async () => { + const s = window.hcp055Legacy; + const owner = + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'; + const other = + 'c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5'; + const adapter = s.createExtensionAdapter(); + window.nostr = { getPublicKey: () => Promise.resolve(owner) }; + await s.connectExtensionAdapter(adapter); + const original = s.extensionOwnershipCapture(adapter)!; + window.nostr = { getPublicKey: () => Promise.resolve(other) }; + await s.recheckExtensionAdapter(adapter); + const lost = original.current(); + window.nostr = { getPublicKey: () => Promise.resolve(owner) }; + await s.connectExtensionAdapter(adapter); + return { lost, revived: original.current() }; + }); + expect(observed).toEqual({ lost: false, revived: false }); +}); +async function load(page: Page) { + await page.goto(server.url + '/search'); + await page.addScriptTag({ content: bundle }); + await page.evaluate(async () => { + const s = window.hcp055, + f = s.makeFixture(); + window.hcp055Fixture = f; + window.hcp055Other = s.makeFixture(); + window.hcp055Counts = { keys: 0, signs: 0, work: 0 }; + window.nostr = { + getPublicKey: () => { + window.hcp055Counts.keys++; + return Promise.resolve(f.owner); + }, + signEvent: (template: Parameters<typeof f.sign>[0]) => { + window.hcp055Counts.signs++; + return Promise.resolve(f.sign(template)); + } + }; + const session = s.createIdentitySession(); + window.hcp055Session = session; + await s.connectIdentity(session); + const operation = s.captureIdentityPublicOperation( + session, + f.record, + f.id, + 'reviewed_captured_operation' + ); + if (!operation) throw new Error('invalid operation'); + window.hcp055Operation = operation; + const db = await s.openBrowserDatabase(); + if (db.state !== 'ready') throw new Error(db.reason); + window.hcp055Database = db.owner; + const repo = s.createPublicQuotaRepository(db.owner, f.owner); + if (!repo) throw new Error('invalid repository'); + window.hcp055Repository = repo; + const input = document.createElement('input'); + input.id = 'hcp055-input'; + input.value = f.template.content; + input.oninput = () => s.invalidateIdentityOperations(session); + document.body.append(input); + window.hcp055Counts = { keys: 0, signs: 0, work: 0 }; + }); +} +async function begin( + page: Page, + forgotten = false, + mode: 'exact' | 'content' | 'cached' = 'exact' +) { + await page.evaluate( + ({ forgotten, mode }) => { + const s = window.hcp055, + f = window.hcp055Fixture; + const started = new Promise<void>((resolve) => { + window.hcp055Started = resolve; + }); + window.nostr = { + getPublicKey: () => { + window.hcp055Counts.keys++; + return Promise.resolve(f.owner); + }, + signEvent: (template: Parameters<typeof f.sign>[0]) => { + window.hcp055Counts.signs++; + window.hcp055Started(); + return new Promise((resolve) => { + window.hcp055Release = () => resolve(f.sign(template, mode)); + }); + } + }; + const ownership = s.identityPublicOperationOwnership( + window.hcp055Session, + window.hcp055Operation + ); + if (!ownership) throw new Error('missing ownership'); + window.hcp055Task = s.runCapturedPublicEffect( + window.hcp055Repository, + f.record, + f.id, + ownership, + 'reviewed_captured_operation', + async (lease) => { + window.hcp055Counts.work++; + const task = s.signIdentityPublicOperation( + window.hcp055Session, + window.hcp055Operation, + lease + ); + if (forgotten) { + void task.then((result) => { + window.hcp055Inner = result; + }); + await started; + return 'forgotten'; + } + const result = await task; + window.hcp055Inner = result; + return result; + } + ); + }, + { forgotten, mode } + ); + await expect + .poll(() => page.evaluate(() => window.hcp055Counts.signs)) + .toBe(1); +} +async function settle(page: Page) { + await page.evaluate(() => window.hcp055Release()); + expect( + await page.evaluate(async () => (await window.hcp055Task).status) + ).toBe('unknown'); + await expect + .poll(() => page.evaluate(() => window.hcp055Inner?.status)) + .toBe('unknown'); + expect(await page.evaluate(() => 'artifact' in window.hcp055Inner)).toBe( + false + ); + expect(await page.evaluate(() => window.hcp055Counts.signs)).toBe(1); +} +async function reviewed(page: Page, consent = 'review_original_late_artifact') { + return page.evaluate((consent) => { + const s = window.hcp055, + f = window.hcp055Fixture; + const artifact = s.reviewIdentityLatePublicArtifact( + window.hcp055Session, + window.hcp055Operation, + f.record, + consent + ); + return artifact ? s.capturedArtifactSnapshot(artifact) : undefined; + }, consent); +} +test('logout during approval retains exact original late result; foreign author cannot review or replay it', async ({ + page +}) => { + await load(page); + await begin(page); + await page.evaluate(() => + window.hcp055.disconnectIdentity(window.hcp055Session) + ); + await settle(page); + expect(await reviewed(page)).toBeUndefined(); + const after = await page.evaluate(async () => { + const s = window.hcp055, + f = window.hcp055Other; + window.nostr = { + getPublicKey: () => { + window.hcp055Counts.keys++; + return Promise.resolve(f.owner); + }, + signEvent: () => { + window.hcp055Counts.signs++; + throw new Error('unexpected replay'); + } + }; + await s.connectIdentity(window.hcp055Session); + return { + view: s.identityPublicOperationSnapshot( + window.hcp055Session, + window.hcp055Operation + ), + identity: s.identitySessionSnapshot(window.hcp055Session), + counts: window.hcp055Counts + }; + }); + expect(after.view).toMatchObject({ + current: false, + lateAvailable: true, + outcome: 'unknown' + }); + expect(after.identity).toMatchObject({ + publicKey: await page.evaluate(() => window.hcp055Other.owner) + }); + expect(after.counts.signs).toBe(1); + expect(await reviewed(page)).toBeUndefined(); +}); +for (const change of ['route', 'input'] as const) + test(`${change} invalidation fences pending work and keeps original capture unchanged`, async ({ + page + }) => { + await load(page); + const original = await page.evaluate(() => { + const s = window.hcp055, + f = window.hcp055Fixture; + return s.publicRecordWire(f.record, f.owner, f.id); + }); + await begin(page); + if (change === 'input') + await page.locator('#hcp055-input').fill('new public input'); + else + await page.evaluate(() => { + history.pushState({}, '', '/settings'); + window.hcp055.invalidateIdentityOperations(window.hcp055Session); + }); + await settle(page); + const state = await page.evaluate(async () => { + const s = window.hcp055, + f = window.hcp055Fixture, + inventory = await s.inspectPublicStorage(window.hcp055Repository); + return { + view: s.identityPublicOperationSnapshot( + window.hcp055Session, + window.hcp055Operation + ), + wire: s.publicRecordWire(f.record, f.owner, f.id), + count: inventory.ok + ? s.publicInventorySnapshot(window.hcp055Repository, inventory.value) + ?.rows.length + : -1, + calls: window.hcp055Counts + }; + }); + expect(state.wire).toBe(original); + expect(state.count).toBe(1); + expect(state.view).toMatchObject({ + current: false, + lateAvailable: true, + outcome: 'unknown' + }); + expect(state.calls).toEqual({ keys: 1, signs: 1, work: 1 }); + expect(await reviewed(page, 'unreviewed')).toBeUndefined(); + expect(await reviewed(page)).toBeDefined(); + }); +for (const action of ['stop', 'wait_expiry'] as const) + test(`${action} keeps actual prompt reserved and late artifact requires review`, async ({ + page + }) => { + await load(page); + await begin(page); + await page.evaluate((action) => { + const s = window.hcp055; + if (action === 'stop') + s.stopIdentityPublicOperation( + window.hcp055Session, + window.hcp055Operation + ); + else + s.expireIdentityPublicOperationWait( + window.hcp055Session, + window.hcp055Operation + ); + }, action); + const busy = await page.evaluate( + async () => + ( + await window.hcp055.connectIdentity( + window.hcp055.createIdentitySession() + ) + ).admission + ); + expect(busy).toBe('busy'); + await settle(page); + expect(await page.evaluate(() => window.hcp055Counts)).toEqual({ + keys: 1, + signs: 1, + work: 1 + }); + expect(await reviewed(page, 'unreviewed')).toBeUndefined(); + expect(await reviewed(page)).toBeDefined(); + }); +test('forgotten operation retains original late review and never becomes a fresh draft', async ({ + page +}) => { + await load(page); + await begin(page, true); + await settle(page); + const before = await page.evaluate(() => ({ ...window.hcp055Counts })); + expect(await reviewed(page)).toBeDefined(); + const after = await page.evaluate(async () => { + const s = window.hcp055, + read = await s.inspectPublicStorage(window.hcp055Repository); + return { + calls: window.hcp055Counts, + rows: read.ok + ? s.publicInventorySnapshot(window.hcp055Repository, read.value)?.rows + : [] + }; + }); + expect(after.calls).toEqual(before); + expect(after.rows).toHaveLength(1); + expect(after.rows?.[0].id).toBe( + await page.evaluate(() => window.hcp055Fixture.id) + ); +}); +for (const mode of ['content', 'cached'] as const) + test(`invalid late ${mode} response cannot become a review capability`, async ({ + page + }) => { + await load(page); + await begin(page, false, mode); + await page.evaluate(() => + window.hcp055.invalidateIdentityOperations(window.hcp055Session) + ); + await settle(page); + expect(await reviewed(page)).toBeUndefined(); + expect( + await page.evaluate( + () => + window.hcp055.identityPublicOperationSnapshot( + window.hcp055Session, + window.hcp055Operation + )?.lateAvailable + ) + ).toBe(false); + }); +test('account loss then same-author reconnect cannot revive an original operation generation', async ({ + page +}) => { + await load(page); + await page.evaluate(async () => { + const s = window.hcp055, + other = window.hcp055Other; + window.nostr = { getPublicKey: () => Promise.resolve(other.owner) }; + await s.recheckIdentityOwner(window.hcp055Session); + }); + const old = await page.evaluate(() => + window.hcp055.identityPublicOperationSnapshot( + window.hcp055Session, + window.hcp055Operation + ) + ); + expect(old?.current).toBe(false); + const reconnected = await page.evaluate(async () => { + const s = window.hcp055, + f = window.hcp055Fixture; + window.nostr = { + getPublicKey: () => Promise.resolve(f.owner), + signEvent: () => { + window.hcp055Counts.signs++; + throw new Error('unexpected replay'); + } + }; + await s.connectIdentity(window.hcp055Session); + return s.identityPublicOperationSnapshot( + window.hcp055Session, + window.hcp055Operation + ); + }); + expect(reconnected?.current).toBe(false); + expect(await page.evaluate(() => window.hcp055Counts.signs)).toBe(0); +}); +test('same-author explicit review after reconnect returns only the original verified artifact with zero effects', async ({ + page +}) => { + await load(page); + await begin(page); + await page.evaluate(() => + window.hcp055.disconnectIdentity(window.hcp055Session) + ); + await settle(page); + await page.evaluate(async () => { + const s = window.hcp055, + f = window.hcp055Fixture; + window.nostr = { + getPublicKey: () => { + window.hcp055Counts.keys++; + return Promise.resolve(f.owner); + }, + signEvent: () => { + window.hcp055Counts.signs++; + throw new Error('unexpected new signature'); + } + }; + await s.connectIdentity(window.hcp055Session); + }); + const before = await page.evaluate(() => ({ ...window.hcp055Counts })); + const artifact = await reviewed(page); + expect(artifact?.author).toBe( + await page.evaluate(() => window.hcp055Fixture.owner) + ); + expect(artifact?.hash).toBe( + await page.evaluate(() => { + const s = window.hcp055, + f = window.hcp055Fixture, + row = s.publicRecordSnapshot(f.record, f.owner, f.id); + return row && row.family !== 'public_draft' ? row.capture.hash : null; + }) + ); + expect(await page.evaluate(() => window.hcp055Counts)).toEqual(before); + expect( + await page.evaluate( + () => + window.hcp055.identityPublicOperationSnapshot( + window.hcp055Session, + window.hcp055Operation + )?.current + ) + ).toBe(false); +}); +test('identity continuation cannot publish a signed artifact after its view was invalidated', async ({ + page +}) => { + let exercised = 0; + for (let depth = 0; depth <= 32; depth++) { + await load(page); + const observed = await page.evaluate(async (depth) => { + const s = window.hcp055, + f = window.hcp055Fixture; + let keys = 0, + beforeInvalidation: string | undefined; + window.nostr = { + getPublicKey: () => { + keys++; + if (keys === 2) { + let remaining = depth; + const advance = () => { + if (remaining-- > 0) queueMicrotask(advance); + else { + beforeInvalidation = s.identityPublicOperationSnapshot( + window.hcp055Session, + window.hcp055Operation + )?.outcome; + s.invalidateIdentityOperations(window.hcp055Session); + } + }; + queueMicrotask(advance); + } + return Promise.resolve(f.owner); + }, + signEvent: (template: Parameters<typeof f.sign>[0]) => + Promise.resolve(f.sign(template)) + }; + const ownership = s.identityPublicOperationOwnership( + window.hcp055Session, + window.hcp055Operation + )!; + let inner: ApprovedSignResult | undefined; + await s.runCapturedPublicEffect( + window.hcp055Repository, + f.record, + f.id, + ownership, + 'reviewed_captured_operation', + async (lease) => { + inner = await s.signIdentityPublicOperation( + window.hcp055Session, + window.hcp055Operation, + lease + ); + return inner; + } + ); + const result = { + depth, + beforeInvalidation, + inner: inner?.status, + hasArtifact: inner !== undefined && 'artifact' in inner, + reviewed: + s.reviewIdentityLatePublicArtifact( + window.hcp055Session, + window.hcp055Operation, + f.record, + 'review_original_late_artifact' + ) !== undefined, + view: s.identityPublicOperationSnapshot( + window.hcp055Session, + window.hcp055Operation + ) + }; + f.close(); + window.hcp055Other.close(); + s.closeBrowserDatabase(window.hcp055Database); + return result; + }, depth); + if (observed.beforeInvalidation === 'pending') { + exercised++; + expect(observed, `actual microtask depth ${depth}`).not.toMatchObject({ + inner: 'signed' + }); + expect(observed.hasArtifact).toBe(false); + expect(observed.reviewed).toBe(true); + } + } + expect(exercised).toBeGreaterThan(0); +}); diff --git a/web/tests/integration/late-results.test.ts b/web/tests/integration/late-results.test.ts @@ -0,0 +1,35 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + createIdentitySession, + captureIdentityPublicOperation, + identityPublicOperationOwnership, + invalidateIdentityOperations, + reviewIdentityLatePublicArtifact, + type IdentityPublicOperation +} from '../../src/lib/runtime/identity-session.ts'; +await test('late-result/session modules remain inert and forged SSR operations have no capability', () => { + assert.equal(typeof window, 'undefined'); + const session = createIdentitySession(); + const fake = {} as IdentityPublicOperation; + assert.equal( + captureIdentityPublicOperation( + session, + {} as never, + '', + 'reviewed_captured_operation' + ), + undefined + ); + assert.equal(identityPublicOperationOwnership(session, fake), undefined); + invalidateIdentityOperations(session); + assert.equal( + reviewIdentityLatePublicArtifact( + session, + fake, + {} as never, + 'review_original_late_artifact' + ), + undefined + ); +}); diff --git a/web/tests/unit/identity-session.test.ts b/web/tests/unit/identity-session.test.ts @@ -6,8 +6,30 @@ import { disconnectIdentity, recheckIdentityOwner, probeIdentityMessaging, + captureIdentityPublicOperation, + identityPublicOperationOwnership, + invalidateIdentityOperations, + type IdentityPublicOperation, type IdentitySession } from '../../src/lib/runtime/identity-session.ts'; +it('forged or disconnected original operation cannot acquire a session ownership context', () => { + const session = createIdentitySession(); + expect( + captureIdentityPublicOperation( + session, + {} as never, + '', + 'reviewed_captured_operation' + ) + ).toBeUndefined(); + expect( + identityPublicOperationOwnership(session, {} as IdentityPublicOperation) + ).toBeUndefined(); + invalidateIdentityOperations(session); + expect( + identityPublicOperationOwnership(session, {} as IdentityPublicOperation) + ).toBeUndefined(); +}); it('new session is disconnected guest and exports no signer or key custody', () => { const session = createIdentitySession(); expect(identitySessionSnapshot(session)).toEqual({ diff --git a/web/tests/unit/late-results.test.ts b/web/tests/unit/late-results.test.ts @@ -0,0 +1,166 @@ +import { describe, it, expect } from 'vitest'; +import { + makeFixture, + approveCapturedPublicSigning, + capturedArtifactSnapshot, + publicRecordSnapshot +} from '../e2e/harness/approved-signing.ts'; +import { decodePublicRecord } from '../../src/lib/persistence/records.ts'; +import { + bindLatePublicResponse, + latePublicResultSnapshot, + reviewLatePublicArtifact, + type LatePublicArtifact +} from '../../src/lib/runtime/late-results.ts'; +describe('original public late-result review', () => { + for (const kind of [30402, 5, 10050] as const) + it(`retains exact verified ${kind} only against its original captured operation`, () => { + const f = makeFixture(kind); + try { + const approval = approveCapturedPublicSigning( + f.record, + f.owner, + f.id, + 'reviewed_captured_operation' + )!; + const signed = f.sign(f.template), + late = bindLatePublicResponse(approval, signed, Symbol())!; + expect(latePublicResultSnapshot(late)).toMatchObject({ + owner: f.owner, + id: f.id, + revision: 0 + }); + expect( + reviewLatePublicArtifact(late, f.record, f.owner, f.id, 'unreviewed') + ).toBeUndefined(); + const reviewed = reviewLatePublicArtifact( + late, + f.record, + f.owner, + f.id, + 'review_original_late_artifact' + ); + expect( + reviewed && JSON.parse(capturedArtifactSnapshot(reviewed)!.wire) + ).toEqual(JSON.parse(JSON.stringify(signed))); + } finally { + f.close(); + } + }); + it('changed full record or owner/ID cannot reinterpret the original result', () => { + const f = makeFixture(); + try { + const approval = approveCapturedPublicSigning( + f.record, + f.owner, + f.id, + 'reviewed_captured_operation' + )!; + const late = bindLatePublicResponse( + approval, + f.sign(f.template), + Symbol() + )!; + const row = publicRecordSnapshot(f.record, f.owner, f.id)!; + if (row.family === 'public_draft') throw new Error('invalid fixture'); + const changed = decodePublicRecord( + JSON.stringify({ + ...row, + capture: { ...row.capture, targets: ['wss://other.example.org'] } + }), + f.owner, + f.id + ); + expect(changed.ok).toBe(true); + expect( + changed.ok && + reviewLatePublicArtifact( + late, + changed.value, + f.owner, + f.id, + 'review_original_late_artifact' + ) + ).toBeUndefined(); + expect( + reviewLatePublicArtifact( + late, + f.record, + f.owner, + crypto.randomUUID(), + 'review_original_late_artifact' + ) + ).toBeUndefined(); + expect( + reviewLatePublicArtifact( + late, + f.record, + '', + f.id, + 'review_original_late_artifact' + ) + ).toBeUndefined(); + } finally { + f.close(); + } + }); + for (const mode of ['content', 'cached', 'author'] as const) + it(`rejects late ${mode} response despite SDK verification cache`, () => { + const f = makeFixture(); + try { + const approval = approveCapturedPublicSigning( + f.record, + f.owner, + f.id, + 'reviewed_captured_operation' + )!; + expect( + bindLatePublicResponse(approval, f.sign(f.template, mode), Symbol()) + ).toBeUndefined(); + } finally { + f.close(); + } + }); + it('fake tokens and mutated disclosure cannot convey artifact authority', () => { + const f = makeFixture(); + try { + expect( + latePublicResultSnapshot({} as LatePublicArtifact) + ).toBeUndefined(); + expect( + reviewLatePublicArtifact( + {} as LatePublicArtifact, + f.record, + f.owner, + f.id, + 'review_original_late_artifact' + ) + ).toBeUndefined(); + const approval = approveCapturedPublicSigning( + f.record, + f.owner, + f.id, + 'reviewed_captured_operation' + )!; + const late = bindLatePublicResponse( + approval, + f.sign(f.template), + Symbol() + )!; + const view = latePublicResultSnapshot(late)!; + (view as { id: string }).id = crypto.randomUUID(); + expect(latePublicResultSnapshot(late)?.id).toBe(f.id); + expect( + reviewLatePublicArtifact( + late, + f.record, + f.owner, + f.id, + 'review_original_late_artifact' + ) + ).toBeDefined(); + } finally { + f.close(); + } + }); +});