app

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

commit 77ae2b955047360b9b38ce9b65677799bb0a99b1
parent 130a60f7e3edb809ca2fd7a2f872f9f62530a6f1
Author: triesap <tyson@radroots.org>
Date:   Wed,  7 Oct 2026 00:31:54 +0000

identity: serialize HarvestCircle extension interactions (HCP-052)

- Share one browser permission slot across explicit captured actions.
- Retain unsettled calls through refusal, stop and UI wait expiration.
- Expose busy admission without changing cached identity capabilities.
- Verify late results, cross-session retries and inert SSR imports.

Diffstat:
Aweb/src/lib/nostr/extension-scheduler.ts | 232+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/src/lib/nostr/extension.ts | 101++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mweb/src/lib/runtime/identity-session.ts | 36++++++++++++++++++++++++------------
Aweb/tests/e2e/extension-scheduler.spec.ts | 281+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/e2e/extension.spec.ts | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Aweb/tests/integration/extension-scheduler.test.ts | 18++++++++++++++++++
Aweb/tests/unit/extension-scheduler.test.ts | 364+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 1115 insertions(+), 33 deletions(-)

diff --git a/web/src/lib/nostr/extension-scheduler.ts b/web/src/lib/nostr/extension-scheduler.ts @@ -0,0 +1,232 @@ +import { canonicalPublicKey } from '../contracts/public-key.ts'; + +declare const schedulerBrand: unique symbol; +declare const actionBrand: unique symbol; +export type ExtensionScheduler = Readonly<{ [schedulerBrand]: true }>; +export type ExtensionAction = Readonly<{ [actionBrand]: true }>; +export type ExtensionCallKind = 'key' | 'sign' | 'encrypt' | 'decrypt' | 'auth'; +export type ExtensionCapture = Readonly<{ + owner: string | null; + session: symbol; + operation: symbol; +}>; +type Phase = 'active' | 'denied' | 'stopped' | 'wait_expired'; +export type ExtensionCallResult<T> = + | Readonly<{ + status: 'settled'; + value: T; + current: boolean; + capture: ExtensionCapture; + }> + | Readonly<{ + status: 'invalid' | 'busy' | 'denied' | 'stopped' | 'wait_expired'; + }>; +export type ExtensionActionResult<T> = + | Readonly<{ + status: 'completed' | 'denied' | 'stopped' | 'wait_expired'; + capture: ExtensionCapture; + value?: T; + }> + | Readonly<{ status: 'invalid' | 'busy' }>; +export type ExtensionSchedulerSnapshot = + | Readonly<{ state: 'idle' | 'unavailable' }> + | Readonly<{ + state: 'active'; + pending: ExtensionCallKind | null; + phase: Phase; + }>; +type ActionController = { + call<T>( + kind: ExtensionCallKind, + invoke: () => Promise<T> + ): Promise<ExtensionCallResult<T>>; + stop(): void; + expire(): void; +}; +type SchedulerController = { + run<T>( + capture: ExtensionCapture, + current: () => boolean, + work: (action: ExtensionAction) => Promise<T> + ): Promise<ExtensionActionResult<T>>; + snapshot(): ExtensionSchedulerSnapshot; +}; +const schedulers = new WeakMap<ExtensionScheduler, SchedulerController>(); +const actions = new WeakMap<ExtensionAction, ActionController>(); +// A page-local permission slot, not a server account or cross-tab lock. No +// accessor is called at module load; page destruction ends this realm's state. +let browserScheduler: ExtensionScheduler | undefined; +export function browserExtensionScheduler(): ExtensionScheduler | undefined { + if (typeof window === 'undefined') return undefined; + browserScheduler ??= createExtensionScheduler(); + return browserScheduler; +} +export function createExtensionScheduler(): ExtensionScheduler { + let occupied = false; + let view: () => ExtensionSchedulerSnapshot = () => ({ state: 'idle' }); + async function run<T>( + input: ExtensionCapture, + fresh: () => boolean, + work: (action: ExtensionAction) => Promise<T> + ): Promise<ExtensionActionResult<T>> { + if (occupied) return { status: 'busy' }; + // Reserve before reading an external capture or invoking freshness. Neither + // a getter nor a reentrant callback can admit a second action. + occupied = true; + let phase: Phase = 'active', + closed = false, + accepting = true; + let pending: ExtensionCallKind | null = null; + let settlement: Promise<unknown> | null = null; + function outstanding(): Promise<unknown> | null { + return settlement; + } + view = () => ({ state: 'active', pending, phase }); + function current() { + if (closed || phase !== 'active') return false; + let valid = false; + try { + valid = fresh() === true; + } catch { + /* finite stopped state */ + } + if (!valid && phase === 'active') phase = 'stopped'; + return !closed && phase === 'active' && valid; + } + try { + if (!input || typeof fresh !== 'function' || typeof work !== 'function') + return { status: 'invalid' }; + const owner = input.owner, + session = input.session, + operation = input.operation; + if ( + (owner !== null && + (typeof owner !== 'string' || canonicalPublicKey(owner) !== owner)) || + typeof session !== 'symbol' || + typeof operation !== 'symbol' + ) + return { status: 'invalid' }; + // The authoritative capture consists only of immutable lexical primitives. + // Each outward result is a fresh detached copy, never the retained input. + const capture = (): ExtensionCapture => ({ owner, session, operation }); + const action = Object.freeze({}) as ExtensionAction; + async function call<V>( + kind: ExtensionCallKind, + invoke: () => Promise<V> + ): Promise<ExtensionCallResult<V>> { + if (!accepting) return { status: 'stopped' }; + if (!current()) + return { + status: closed ? 'stopped' : phase === 'active' ? 'stopped' : phase + }; + if (pending) return { status: 'busy' }; + if ( + !['key', 'sign', 'encrypt', 'decrypt', 'auth'].includes(kind) || + typeof invoke !== 'function' + ) + return { status: 'invalid' }; + // Mark admission before even the callback's synchronous prefix. The + // SDK invocation itself may read provider getters and cannot be revoked. + pending = kind; + const task = (async (): Promise<ExtensionCallResult<V>> => { + try { + const value = await invoke(); + return { + status: 'settled', + value, + current: current(), + capture: capture() + }; + } catch { + if (current()) phase = 'denied'; + return { status: phase === 'active' ? 'denied' : phase }; + } finally { + pending = null; + } + })(); + settlement = task; + try { + return await task; + } finally { + if (settlement === task) settlement = null; + } + } + actions.set(action, { + call, + stop() { + if (!closed) phase = 'stopped'; + }, + expire() { + if (!closed && phase === 'active' && pending) phase = 'wait_expired'; + } + }); + if (!current()) return { status: 'stopped', capture: capture() }; + let value: T | undefined; + try { + value = await work(action); + } catch { + if (current()) phase = 'denied'; + } + // Even an unawaited admitted call retains the shared slot. No timeout, + // disconnect, batch return or rejection can pretend it was cancelled. + accepting = false; + const waiting = outstanding(); + if (waiting) await waiting; + const valid = current(); + return { + status: valid ? 'completed' : phase === 'active' ? 'stopped' : phase, + capture: capture(), + value + }; + } catch { + return { status: 'invalid' }; + } finally { + accepting = false; + const waiting = outstanding(); + if (waiting) await waiting; + closed = true; + occupied = false; + view = () => ({ state: 'idle' }); + } + } + const scheduler = Object.freeze({}) as ExtensionScheduler; + schedulers.set(scheduler, { run, snapshot: () => view() }); + return scheduler; +} +// Low-level orchestration ports only. No signer, event publisher, permission +// fallback or automatic action is created by the scheduler. Product owners must +// independently validate templates/results before persistence or delivery. +export function runExtensionAction<T>( + scheduler: ExtensionScheduler, + capture: ExtensionCapture, + current: () => boolean, + work: (action: ExtensionAction) => Promise<T> +): Promise<ExtensionActionResult<T>> { + return ( + schedulers.get(scheduler)?.run(capture, current, work) ?? + Promise.resolve({ status: 'invalid' }) + ); +} +export function callExtension<T>( + action: ExtensionAction, + kind: ExtensionCallKind, + invoke: () => Promise<T> +): Promise<ExtensionCallResult<T>> { + return ( + actions.get(action)?.call(kind, invoke) ?? + Promise.resolve({ status: 'invalid' }) + ); +} +export function stopExtensionAction(action: ExtensionAction): void { + actions.get(action)?.stop(); +} +// The UI supplies its wait-expiration event. This marks slow/pending, pauses the +// batch, and leaves the real promise reserved; it establishes no cancellation. +export function markExtensionWaitExpired(action: ExtensionAction): void { + actions.get(action)?.expire(); +} +export function extensionSchedulerSnapshot( + scheduler: ExtensionScheduler +): ExtensionSchedulerSnapshot { + return schedulers.get(scheduler)?.snapshot() ?? { state: 'unavailable' }; +} diff --git a/web/src/lib/nostr/extension.ts b/web/src/lib/nostr/extension.ts @@ -6,6 +6,14 @@ import { canonicalPublicKey } from '../contracts/public-key.ts'; import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts'; import { PUBLIC_INGRESS_BUDGETS } from '../config/budgets.ts'; +import { + browserExtensionScheduler, + runExtensionAction, + callExtension, + type ExtensionAction, + type ExtensionCallKind +} from './extension-scheduler.ts'; + declare const adapterBrand: unique symbol; export type ExtensionAdapter = Readonly<{ [adapterBrand]: true }>; export type ExtensionGuestReason = @@ -15,7 +23,7 @@ export type ExtensionGuestReason = | 'invalid_key' | 'changed_key' | 'unavailable'; -export type ExtensionSnapshot = +export type ExtensionSnapshot = ( | Readonly<{ state: 'guest'; reason: ExtensionGuestReason }> | Readonly<{ state: 'pending'; action: 'connect' | 'recheck' | 'probe' }> | Readonly<{ @@ -23,7 +31,9 @@ export type ExtensionSnapshot = publicKey: string; signingCandidate: boolean; messaging: 'not_probed' | 'unsupported' | 'refused' | 'capable'; - }>; + }> +) & + Readonly<{ admission?: 'busy' }>; declare global { interface Window { @@ -51,13 +61,37 @@ function present(): Readonly<{ signingCandidate: boolean }> | undefined { ? { signingCandidate: typeof value.signEvent === 'function' } : undefined; } -async function freshKey(current: () => boolean): Promise<string | undefined> { +async function invokeExtension<T>( + action: ExtensionAction | undefined, + kind: ExtensionCallKind, + work: () => Promise<T> +): Promise<T> { + if (!action) throw new Error('extension_unavailable'); + let missing = false; + const result = await callExtension(action, kind, async () => { + try { + return await work(); + } catch (error) { + missing = error instanceof ExtensionMissingError; + throw error; + } + }); + if (result.status === 'settled' && result.current) return result.value; + if (missing) throw new ExtensionMissingError('extension_missing'); + throw new Error('extension_' + result.status); +} +async function freshKey( + current: () => boolean, + action: ExtensionAction | undefined +): Promise<string | undefined> { if (!current()) return undefined; const signer = new ExtensionSigner(); // This SDK invocation admits one NIP-07 call. Its internal getters and // permission wait cannot universally be interrupted; callers fence the result. if (!current()) return undefined; - return canonicalPublicKey(await signer.getPublicKey()); + return canonicalPublicKey( + await invokeExtension(action, 'key', () => signer.getPublicKey()) + ); } // Lexically owned per-adapter state; no mutable opaque receiver, browser handle // or imported signer escapes through the WeakMap/controller boundary. @@ -68,7 +102,7 @@ export function createExtensionAdapter(): ExtensionAdapter { 'not_probed'; let reason: ExtensionGuestReason = 'disconnected'; let pending: 'connect' | 'recheck' | 'probe' | null = null; - let generation = {}, + let generation = Symbol(), cancelled = false; function snapshot(): ExtensionSnapshot { if (pending && !cancelled) return { state: 'pending', action: pending }; @@ -83,7 +117,7 @@ export function createExtensionAdapter(): ExtensionAdapter { reason = nextReason; } function disconnect() { - generation = {}; + generation = Symbol(); cancelled = true; guest( 'disconnected' @@ -91,25 +125,50 @@ export function createExtensionAdapter(): ExtensionAdapter { } async function run( action: 'connect' | 'recheck' | 'probe', - work: (current: () => boolean) => Promise<void> + work: ( + current: () => boolean, + action: ExtensionAction | undefined + ) => Promise<void> ): Promise<ExtensionSnapshot> { - if (pending) return snapshot(); + if (pending) return { ...snapshot(), admission: 'busy' }; + let busy = false; const original = generation; pending = action; cancelled = false; const current = () => generation === original && !cancelled; try { - await work(current); + const scheduler = browserExtensionScheduler(); + if (scheduler) { + // One shared page slot for all sessions and effect kinds. Busy performs + // no provider work and never schedules an automatic retry. + const admitted = await runExtensionAction( + scheduler, + { owner: key, session: original, operation: Symbol() }, + current, + async (lease) => { + try { + await work(current, lease); + } catch (error) { + if (current()) + guest( + error instanceof ExtensionMissingError ? 'missing' : 'refused' + ); + throw error; + } + } + ); + busy = admitted.status === 'busy'; + } else await work(current, undefined); } catch (error) { if (current()) guest(error instanceof ExtensionMissingError ? 'missing' : 'refused'); } finally { pending = null; } - return snapshot(); + return busy ? { ...snapshot(), admission: 'busy' } : snapshot(); } function connect(): Promise<ExtensionSnapshot> { - return run('connect', async (current) => { + return run('connect', async (current, action) => { if (typeof window === 'undefined') { guest('unavailable'); return; @@ -120,7 +179,7 @@ export function createExtensionAdapter(): ExtensionAdapter { guest('missing'); return; } - const owner = await freshKey(current); + const owner = await freshKey(current, action); if (!current()) return; if (!owner) { guest('invalid_key'); @@ -143,8 +202,8 @@ export function createExtensionAdapter(): ExtensionAdapter { } function recheck(): Promise<ExtensionSnapshot> { if (!key) return Promise.resolve(snapshot()); - return run('recheck', async (current) => { - const owner = await freshKey(current); + return run('recheck', async (current, action) => { + const owner = await freshKey(current, action); if (!current()) return; if (!owner) { guest('invalid_key'); @@ -180,10 +239,10 @@ export function createExtensionAdapter(): ExtensionAdapter { function probe(review: unknown): Promise<ExtensionSnapshot> { if (!key || review !== 'reviewed_self_copy') return Promise.resolve(snapshot()); - return run('probe', async (current) => { + return run('probe', async (current, action) => { const owner = key; if (!owner) return; - const checked = await freshKey(current); + const checked = await freshKey(current, action); if (!current()) return; if (checked !== owner) { guest(checked ? 'changed_key' : 'invalid_key'); @@ -215,7 +274,9 @@ export function createExtensionAdapter(): ExtensionAdapter { let encrypted: unknown, decrypted: unknown; try { if (!current()) return; - encrypted = await encrypt(owner, text); + encrypted = await invokeExtension(action, 'encrypt', () => + encrypt(owner, text) + ); if (!current()) return; if ( typeof encrypted !== 'string' || @@ -225,7 +286,9 @@ export function createExtensionAdapter(): ExtensionAdapter { return; } if (!current()) return; - decrypted = await decrypt(owner, encrypted); + decrypted = await invokeExtension(action, 'decrypt', () => + decrypt(owner, encrypted as string) + ); } catch { if (current()) messaging = 'refused'; return; @@ -235,7 +298,7 @@ export function createExtensionAdapter(): ExtensionAdapter { messaging = 'refused'; return; } - const after = await freshKey(current); + const after = await freshKey(current, action); if (!current()) return; if (after !== owner) { guest(after ? 'changed_key' : 'invalid_key'); diff --git a/web/src/lib/runtime/identity-session.ts b/web/src/lib/runtime/identity-session.ts @@ -6,19 +6,22 @@ import { probeExtensionAdapter, disconnectExtensionAdapter, type ExtensionAdapter, + type ExtensionSnapshot, type ExtensionGuestReason } from '../nostr/extension.ts'; declare const sessionBrand: unique symbol; export type IdentitySession = Readonly<{ [sessionBrand]: true }>; -export type IdentitySnapshot = +export type IdentitySnapshot = ( | Readonly<{ state: 'guest'; reason: ExtensionGuestReason }> | Readonly<{ state: 'pending'; action: 'connect' | 'recheck' | 'probe' }> | Readonly<{ state: 'connected' | 'signing_only' | 'messaging_capable'; publicKey: string; messaging: 'not_probed' | 'unsupported' | 'refused' | 'capable'; - }>; + }> +) & + Readonly<{ admission?: 'busy' }>; // 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>(); @@ -27,14 +30,9 @@ export function createIdentitySession(): IdentitySession { sessions.set(session, createExtensionAdapter()); return session; } -export function identitySessionSnapshot( - session: IdentitySession -): IdentitySnapshot { - const adapter = sessions.get(session); - if (!adapter) return { state: 'guest', reason: 'unavailable' }; - const snapshot = extensionSnapshot(adapter); +function mapIdentitySnapshot(snapshot: ExtensionSnapshot): IdentitySnapshot { if (snapshot.state !== 'connected') return { ...snapshot }; - return { + const state: IdentitySnapshot = { state: snapshot.messaging === 'capable' && snapshot.signingCandidate ? 'messaging_capable' @@ -44,19 +42,32 @@ export function identitySessionSnapshot( publicKey: snapshot.publicKey, messaging: snapshot.messaging }; + return snapshot.admission === 'busy' + ? { ...state, admission: 'busy' } + : state; +} +export function identitySessionSnapshot( + session: IdentitySession +): IdentitySnapshot { + const adapter = sessions.get(session); + return adapter + ? mapIdentitySnapshot(extensionSnapshot(adapter)) + : { state: 'guest', reason: 'unavailable' }; } export async function connectIdentity( session: IdentitySession ): Promise<IdentitySnapshot> { const adapter = sessions.get(session); - if (adapter) await connectExtensionAdapter(adapter); + if (adapter) + return mapIdentitySnapshot(await connectExtensionAdapter(adapter)); return identitySessionSnapshot(session); } export async function recheckIdentityOwner( session: IdentitySession ): Promise<IdentitySnapshot> { const adapter = sessions.get(session); - if (adapter) await recheckExtensionAdapter(adapter); + if (adapter) + return mapIdentitySnapshot(await recheckExtensionAdapter(adapter)); return identitySessionSnapshot(session); } export async function probeIdentityMessaging( @@ -64,7 +75,8 @@ export async function probeIdentityMessaging( review: unknown ): Promise<IdentitySnapshot> { const adapter = sessions.get(session); - if (adapter) await probeExtensionAdapter(adapter, review); + if (adapter) + return mapIdentitySnapshot(await probeExtensionAdapter(adapter, review)); return identitySessionSnapshot(session); } export function disconnectIdentity(session: IdentitySession): void { diff --git a/web/tests/e2e/extension-scheduler.spec.ts b/web/tests/e2e/extension-scheduler.spec.ts @@ -0,0 +1,281 @@ +import { expect, test } 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 Scheduler from '../../src/lib/nostr/extension-scheduler.ts'; +declare global { + interface Window { + hcp052: typeof Scheduler; + hcp052Scheduler: Scheduler.ExtensionScheduler; + hcp052Action: Scheduler.ExtensionAction; + hcp052Task: Promise<Scheduler.ExtensionActionResult<unknown>>; + hcp052Release: (value: string) => void; + hcp052Calls: string[]; + } +} +const owner = + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'; +let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string; +test.beforeAll(async () => { + server = await createStaticHarness(); + const result = await build({ + configFile: false, + logLevel: 'silent', + build: { + write: false, + minify: false, + lib: { + entry: fileURLToPath( + new URL('../../src/lib/nostr/extension-scheduler.ts', import.meta.url) + ), + name: 'hcp052', + formats: ['iife'] + } + } + }); + const output = Array.isArray(result) ? result[0] : result; + if (!('output' in output)) throw new Error('missing bundle'); + const chunks = output.output.filter((v) => v.type === 'chunk'); + expect(chunks).toHaveLength(1); + bundle = chunks[0].code; + console.log( + JSON.stringify({ + fixture: 'HCP052_ACTUAL_SCHEDULER_CONTROLLED_CALLS', + moduleIds: Object.keys(chunks[0].modules), + bundleSha256: createHash('sha256').update(bundle).digest('hex'), + claim: + 'actual Chromium and current scheduler; no real extension qualification' + }) + ); +}); +test.afterAll(async () => await Promise.resolve(server.close())); +test.beforeEach(async ({ page }) => { + await page.goto(server.url + '/search'); + await page.addScriptTag({ content: bundle }); + await page.evaluate(() => { + window.hcp052Scheduler = window.hcp052.browserExtensionScheduler()!; + window.hcp052Calls = []; + }); +}); +test('load and shared accessor request no extension permission', async ({ + page +}) => { + expect( + await page.evaluate(() => ({ + calls: window.hcp052Calls, + same: + window.hcp052.browserExtensionScheduler() === window.hcp052Scheduler, + snapshot: window.hcp052.extensionSchedulerSnapshot(window.hcp052Scheduler) + })) + ).toEqual({ calls: [], same: true, snapshot: { state: 'idle' } }); +}); +test('one explicit batch serializes all five call kinds and blocks competing actions', async ({ + page +}) => { + await page.evaluate((owner) => { + window.hcp052Task = window.hcp052.runExtensionAction( + window.hcp052Scheduler, + { owner, session: Symbol(), operation: Symbol() }, + () => true, + async (a) => { + const key = await window.hcp052.callExtension(a, 'key', () => { + window.hcp052Calls.push('key'); + return new Promise<string>((resolve) => { + window.hcp052Release = resolve; + }); + }); + for (const kind of ['sign', 'encrypt', 'decrypt', 'auth'] as const) + await window.hcp052.callExtension(a, kind, async () => { + window.hcp052Calls.push(kind); + return await Promise.resolve(kind); + }); + return key; + } + ); + }, owner); + expect( + await page.evaluate( + (owner) => + window.hcp052.runExtensionAction( + window.hcp052Scheduler, + { owner, session: Symbol(), operation: Symbol() }, + () => true, + async () => { + window.hcp052Calls.push('competing'); + + await Promise.resolve(); + } + ), + owner + ) + ).toEqual({ status: 'busy' }); + await page.evaluate((owner) => window.hcp052Release(owner), owner); + expect(await page.evaluate(() => window.hcp052Task)).toMatchObject({ + status: 'completed', + value: { status: 'settled', current: true, value: owner } + }); + expect(await page.evaluate(() => window.hcp052Calls)).toEqual([ + 'key', + 'sign', + 'encrypt', + 'decrypt', + 'auth' + ]); +}); +test('UI timeout retains slot, original capture and late signature without next AUTH', async ({ + page +}) => { + await page.evaluate((owner) => { + window.hcp052Task = window.hcp052.runExtensionAction( + window.hcp052Scheduler, + { owner, session: Symbol(), operation: Symbol() }, + () => true, + async (a) => { + window.hcp052Action = a; + const signed = await window.hcp052.callExtension( + a, + 'sign', + () => + new Promise<string>((resolve) => { + window.hcp052Calls.push('sign'); + window.hcp052Release = resolve; + }) + ); + const auth = await window.hcp052.callExtension(a, 'auth', async () => { + window.hcp052Calls.push('auth'); + return await Promise.resolve('unused'); + }); + return { signed, auth }; + } + ); + window.hcp052.markExtensionWaitExpired(window.hcp052Action); + }, owner); + expect( + await page.evaluate(() => + window.hcp052.extensionSchedulerSnapshot(window.hcp052Scheduler) + ) + ).toEqual({ state: 'active', phase: 'wait_expired', pending: 'sign' }); + expect( + await page.evaluate( + (owner) => + window.hcp052.runExtensionAction( + window.hcp052Scheduler, + { owner, session: Symbol(), operation: Symbol() }, + () => true, + async () => { + window.hcp052Calls.push('unexpected'); + + await Promise.resolve(); + } + ), + owner + ) + ).toEqual({ status: 'busy' }); + await page.evaluate(() => window.hcp052Release('controlled late signature')); + expect(await page.evaluate(() => window.hcp052Task)).toMatchObject({ + status: 'wait_expired', + capture: { owner }, + value: { + signed: { + status: 'settled', + current: false, + value: 'controlled late signature', + capture: { owner } + }, + auth: { status: 'wait_expired' } + } + }); + expect(await page.evaluate(() => window.hcp052Calls)).toEqual(['sign']); +}); +test('decrypt denial pauses batch with safe finite outcome and no automatic resume', async ({ + page +}) => { + const outcome = await page.evaluate( + (owner) => + window.hcp052.runExtensionAction( + window.hcp052Scheduler, + { owner, session: Symbol(), operation: Symbol() }, + () => true, + async (a) => { + const denied = await window.hcp052.callExtension( + a, + 'decrypt', + async () => { + window.hcp052Calls.push('decrypt'); + await Promise.resolve(); + throw new Error('controlled private body'); + } + ); + const next = await window.hcp052.callExtension( + a, + 'sign', + async () => { + window.hcp052Calls.push('sign'); + return await Promise.resolve('unused'); + } + ); + return { denied, next }; + } + ), + owner + ); + expect(outcome).toMatchObject({ + status: 'denied', + value: { denied: { status: 'denied' }, next: { status: 'denied' } } + }); + expect(JSON.stringify(outcome)).not.toContain('controlled private body'); + expect(await page.evaluate(() => window.hcp052Calls)).toEqual(['decrypt']); +}); +test('local stop and forgotten await retain shared browser scheduler until settlement', async ({ + page +}) => { + await page.evaluate((owner) => { + window.hcp052Task = window.hcp052.runExtensionAction( + window.hcp052Scheduler, + { owner, session: Symbol(), operation: Symbol() }, + () => true, + async (a) => { + window.hcp052Action = a; + void window.hcp052.callExtension( + a, + 'encrypt', + () => + new Promise<string>((resolve) => { + window.hcp052Calls.push('encrypt'); + window.hcp052Release = resolve; + }) + ); + window.hcp052.stopExtensionAction(a); + + await Promise.resolve(); + } + ); + }, owner); + expect( + await page.evaluate( + (owner) => + window.hcp052.runExtensionAction( + window.hcp052.browserExtensionScheduler()!, + { owner, session: Symbol(), operation: Symbol() }, + () => true, + async () => { + window.hcp052Calls.push('unexpected'); + + await Promise.resolve(); + } + ), + owner + ) + ).toEqual({ status: 'busy' }); + await page.evaluate(() => window.hcp052Release('late cipher')); + expect(await page.evaluate(() => window.hcp052Task)).toMatchObject({ + status: 'stopped' + }); + expect( + await page.evaluate(() => + window.hcp052.extensionSchedulerSnapshot(window.hcp052Scheduler) + ) + ).toEqual({ state: 'idle' }); + expect(await page.evaluate(() => window.hcp052Calls)).toEqual(['encrypt']); +}); diff --git a/web/tests/e2e/extension.spec.ts b/web/tests/e2e/extension.spec.ts @@ -16,6 +16,8 @@ declare global { }; hcp051Key: string; hcp051Release: () => void; + hcp051Other: Identity.IdentitySession; + hcp051Task: Promise<Identity.IdentitySnapshot>; } } const owner = @@ -233,7 +235,8 @@ test('late pending connection cannot restore a disconnected owner and original s ); expect(await connect(page)).toEqual({ state: 'guest', - reason: 'disconnected' + reason: 'disconnected', + admission: 'busy' }); expect(await page.evaluate(() => window.hcp051Counts.keys)).toBe(1); await page.evaluate(() => window.hcp051Release()); @@ -321,7 +324,8 @@ test('disconnect during pending encryption keeps slot and prevents later decrypt ); expect(await connect(page)).toEqual({ state: 'guest', - reason: 'disconnected' + reason: 'disconnected', + admission: 'busy' }); await page.evaluate(() => window.hcp051Release()); expect(await pending).toEqual({ state: 'guest', reason: 'disconnected' }); @@ -542,3 +546,111 @@ for (const property of ['nip44', 'signEvent'] as const) decrypts: 1 }); }); + +// HCP052: disconnected and busy callers cannot release or misreport the slot. +test('cross-session busy Connect retains slot and exposes explicit retry after settlement', async ({ + page +}) => { + await load(page, 'pending'); + await page.evaluate(() => { + window.hcp051Task = window.hcp051.connectIdentity(window.hcp051Session); + }); + await expect + .poll(() => page.evaluate(() => window.hcp051Counts.keys)) + .toBe(1); + const busy = await page.evaluate(async () => { + window.hcp051.disconnectIdentity(window.hcp051Session); + window.hcp051Other = window.hcp051.createIdentitySession(); + return await window.hcp051.connectIdentity(window.hcp051Other); + }); + expect(busy).toEqual({ + state: 'guest', + reason: 'disconnected', + admission: 'busy' + }); + expect( + await page.evaluate(() => + window.hcp051.identitySessionSnapshot(window.hcp051Other) + ) + ).toEqual({ state: 'guest', reason: 'disconnected' }); + expect(await page.evaluate(() => window.hcp051Counts.keys)).toBe(1); + await page.evaluate(() => window.hcp051Release()); + expect(await page.evaluate(() => window.hcp051Task)).toEqual({ + state: 'guest', + reason: 'disconnected' + }); + expect(await page.evaluate(() => window.hcp051Counts.keys)).toBe(1); + await page.evaluate(() => { + const provider = window.nostr as { getPublicKey: () => Promise<string> }; + provider.getPublicKey = () => { + window.hcp051Counts.keys++; + return Promise.resolve(window.hcp051Key); + }; + }); + expect( + await page.evaluate(() => window.hcp051.connectIdentity(window.hcp051Other)) + ).toMatchObject({ state: 'signing_only', publicKey: owner }); + expect(await page.evaluate(() => window.hcp051Counts.keys)).toBe(2); +}); +test('busy owner recheck and probe preserve capabilities without claiming a fresh owner check', async ({ + page +}) => { + await load(page, 'messaging'); + await connect(page); + await page.evaluate(async () => { + window.hcp051Other = window.hcp051.createIdentitySession(); + await window.hcp051.connectIdentity(window.hcp051Other); + const provider = window.nostr as { getPublicKey: () => Promise<string> }; + provider.getPublicKey = async () => { + window.hcp051Counts.keys++; + await new Promise<void>((resolve) => { + window.hcp051Release = resolve; + }); + return window.hcp051Key; + }; + window.hcp051Task = window.hcp051.recheckIdentityOwner( + window.hcp051Session + ); + }); + await expect + .poll(() => page.evaluate(() => window.hcp051Counts.keys)) + .toBe(3); + expect( + await page.evaluate(() => + window.hcp051.recheckIdentityOwner(window.hcp051Other) + ) + ).toMatchObject({ + state: 'signing_only', + publicKey: owner, + admission: 'busy' + }); + expect( + await page.evaluate(() => + window.hcp051.probeIdentityMessaging( + window.hcp051Other, + 'reviewed_self_copy' + ) + ) + ).toMatchObject({ + state: 'signing_only', + publicKey: owner, + admission: 'busy' + }); + expect(await page.evaluate(() => window.hcp051Counts)).toEqual({ + keys: 3, + signs: 0, + encrypts: 0, + decrypts: 0 + }); + expect( + await page.evaluate(() => + window.hcp051.identitySessionSnapshot(window.hcp051Other) + ) + ).toEqual({ + state: 'signing_only', + publicKey: owner, + messaging: 'not_probed' + }); + await page.evaluate(() => window.hcp051Release()); + await page.evaluate(() => window.hcp051Task); +}); diff --git a/web/tests/integration/extension-scheduler.test.ts b/web/tests/integration/extension-scheduler.test.ts @@ -0,0 +1,18 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + browserExtensionScheduler, + createExtensionScheduler, + extensionSchedulerSnapshot +} from '../../src/lib/nostr/extension-scheduler.ts'; +await test('actual scheduler and extension imports stay inert in Node SSR', async () => { + assert.equal(typeof window, 'undefined'); + assert.equal(browserExtensionScheduler(), undefined); + const identity = await import('../../src/lib/runtime/identity-session.ts'); + const scheduler = createExtensionScheduler(); + assert.deepEqual(extensionSchedulerSnapshot(scheduler), { state: 'idle' }); + assert.deepEqual( + identity.identitySessionSnapshot(identity.createIdentitySession()), + { state: 'guest', reason: 'disconnected' } + ); +}); diff --git a/web/tests/unit/extension-scheduler.test.ts b/web/tests/unit/extension-scheduler.test.ts @@ -0,0 +1,364 @@ +import { expect, it } from 'vitest'; +import { + createExtensionScheduler, + browserExtensionScheduler, + runExtensionAction, + callExtension, + stopExtensionAction, + markExtensionWaitExpired, + extensionSchedulerSnapshot, + type ExtensionAction, + type ExtensionScheduler +} from '../../src/lib/nostr/extension-scheduler.ts'; +const owner = + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'; +function capture() { + return { owner, session: Symbol(), operation: Symbol() }; +} +function deferred<T>() { + let resolve!: (value: T) => void; + const promise = new Promise<T>((r) => { + resolve = r; + }); + return { promise, resolve }; +} +it('SSR construction is inert and no browser-global scheduler is created', () => { + expect(browserExtensionScheduler()).toBeUndefined(); + expect(extensionSchedulerSnapshot(createExtensionScheduler())).toEqual({ + state: 'idle' + }); +}); +it('sign/decrypt overlap reports busy without a call or automatic retry', async () => { + const scheduler = createExtensionScheduler(), + gate = deferred<string>(); + let calls = 0; + const first = runExtensionAction( + scheduler, + capture(), + () => true, + (a) => + callExtension(a, 'sign', () => { + calls++; + return gate.promise; + }) + ); + expect( + await runExtensionAction( + scheduler, + capture(), + () => true, + (a) => + callExtension(a, 'decrypt', () => { + calls++; + return Promise.resolve('text'); + }) + ) + ).toEqual({ status: 'busy' }); + expect(calls).toBe(1); + gate.resolve('signature'); + await first; + expect(calls).toBe(1); + expect( + ( + await runExtensionAction( + scheduler, + capture(), + () => true, + (a) => + callExtension(a, 'decrypt', () => { + calls++; + return Promise.resolve('text'); + }) + ) + ).status + ).toBe('completed'); + expect(calls).toBe(2); +}); +it('denial pauses the original batch across decrypt/sign/encrypt/AUTH', async () => { + const scheduler = createExtensionScheduler(); + let calls = 0; + const result = await runExtensionAction( + scheduler, + capture(), + () => true, + async (a) => { + expect( + await callExtension(a, 'decrypt', () => { + calls++; + return Promise.reject(new Error('private refusal prose')); + }) + ).toEqual({ status: 'denied' }); + for (const kind of ['sign', 'encrypt', 'auth'] as const) + expect( + await callExtension(a, kind, () => { + calls++; + return Promise.resolve('unused'); + }) + ).toEqual({ status: 'denied' }); + } + ); + expect(result.status).toBe('denied'); + expect(calls).toBe(1); + expect(JSON.stringify(result)).not.toContain('private refusal prose'); +}); +it('wait expiration preserves a late original result and holds the pending slot', async () => { + const scheduler = createExtensionScheduler(), + gate = deferred<string>(), + original = capture(); + let action!: ExtensionAction; + const task = runExtensionAction( + scheduler, + original, + () => true, + (a) => { + action = a; + return callExtension(a, 'sign', () => gate.promise); + } + ); + markExtensionWaitExpired(action); + expect(extensionSchedulerSnapshot(scheduler)).toMatchObject({ + state: 'active', + pending: 'sign', + phase: 'wait_expired' + }); + expect( + await runExtensionAction( + scheduler, + capture(), + () => true, + () => Promise.resolve('unexpected') + ) + ).toEqual({ status: 'busy' }); + gate.resolve('late signature'); + const result = await task; + expect(result).toMatchObject({ + status: 'wait_expired', + capture: original, + value: { + status: 'settled', + current: false, + value: 'late signature', + capture: original + } + }); + expect(extensionSchedulerSnapshot(scheduler)).toEqual({ state: 'idle' }); +}); +it('stop retains a forgotten await and rejects further effects until actual settlement', async () => { + const scheduler = createExtensionScheduler(), + gate = deferred<string>(); + let action!: ExtensionAction, + settled = false; + const task = runExtensionAction( + scheduler, + capture(), + () => true, + (a) => { + action = a; + void callExtension(a, 'key', () => gate.promise); + return Promise.resolve('work returned'); + } + ).then((v) => { + settled = true; + return v; + }); + stopExtensionAction(action); + await Promise.resolve(); + await Promise.resolve(); + expect(settled).toBe(false); + expect( + await runExtensionAction( + scheduler, + capture(), + () => true, + () => Promise.resolve('unused') + ) + ).toEqual({ status: 'busy' }); + expect( + await callExtension(action, 'auth', () => Promise.resolve('unused')) + ).toEqual({ status: 'stopped' }); + gate.resolve('late key'); + expect((await task).status).toBe('stopped'); +}); +it('within-action parallel calls cannot overlap, and sequential calls retain capture', async () => { + const scheduler = createExtensionScheduler(), + gate = deferred<string>(); + let calls = 0; + await runExtensionAction( + scheduler, + capture(), + () => true, + async (a) => { + const first = callExtension(a, 'encrypt', () => { + calls++; + return gate.promise; + }); + expect( + await callExtension(a, 'decrypt', () => { + calls++; + return Promise.resolve('unused'); + }) + ).toEqual({ status: 'busy' }); + gate.resolve('cipher'); + expect((await first).status).toBe('settled'); + expect( + ( + await callExtension(a, 'decrypt', () => { + calls++; + return Promise.resolve('plain'); + }) + ).status + ).toBe('settled'); + } + ); + expect(calls).toBe(2); +}); +it('freshness invalidation prevents new effects and marks admitted late results stale', async () => { + const scheduler = createExtensionScheduler(), + gate = deferred<string>(); + let current = true, + calls = 0; + const task = runExtensionAction( + scheduler, + capture(), + () => current, + async (a) => { + const value = await callExtension(a, 'key', () => gate.promise); + expect( + await callExtension(a, 'auth', () => { + calls++; + return Promise.resolve('unused'); + }) + ).toEqual({ status: 'stopped' }); + return value; + } + ); + current = false; + gate.resolve(owner); + expect(await task).toMatchObject({ + status: 'stopped', + value: { current: false, value: owner } + }); + expect(calls).toBe(0); +}); +it('fabricated handles and invalid captures have zero effects; snapshots are detached', async () => { + let calls = 0; + const scheduler = createExtensionScheduler(); + expect( + await runExtensionAction( + {} as ExtensionScheduler, + capture(), + () => true, + () => { + calls++; + return Promise.resolve(); + } + ) + ).toEqual({ status: 'invalid' }); + expect( + await runExtensionAction( + scheduler, + { ...capture(), owner: 'invalid' }, + () => true, + () => { + calls++; + return Promise.resolve(); + } + ) + ).toEqual({ status: 'invalid' }); + expect( + await callExtension({} as ExtensionAction, 'key', () => { + calls++; + return Promise.resolve(); + }) + ).toEqual({ status: 'invalid' }); + const snapshot = extensionSchedulerSnapshot(scheduler); + (snapshot as { state: string }).state = 'changed'; + expect(extensionSchedulerSnapshot(scheduler)).toEqual({ state: 'idle' }); + expect(calls).toBe(0); +}); +it('reentrant freshness callback cannot admit a competing action', async () => { + const scheduler = createExtensionScheduler(); + let competitor: Promise<unknown> | undefined, + calls = 0; + await runExtensionAction( + scheduler, + capture(), + () => { + competitor ??= runExtensionAction( + scheduler, + capture(), + () => true, + () => { + calls++; + return Promise.resolve(); + } + ); + return true; + }, + (a) => callExtension(a, 'key', () => Promise.resolve(owner)) + ); + expect(await competitor).toEqual({ status: 'busy' }); + expect(calls).toBe(0); +}); +it('input and returned capture mutation cannot change the retained original', async () => { + const original = capture(), + expected = { ...original }; + const result = await runExtensionAction( + createExtensionScheduler(), + original, + () => true, + async (a) => { + original.owner = 'changed'; + const first = await callExtension(a, 'key', () => Promise.resolve(owner)); + if (first.status === 'settled') + (first.capture as { owner: string }).owner = 'changed again'; + return callExtension(a, 'sign', () => Promise.resolve('signature')); + } + ); + expect(result).toMatchObject({ + capture: expected, + value: { capture: expected } + }); +}); +it('undefined owner is invalid even with genuine session and operation symbols', async () => { + let calls = 0; + expect( + await runExtensionAction( + createExtensionScheduler(), + { ...capture(), owner: undefined } as never, + () => true, + () => { + calls++; + return Promise.resolve(); + } + ) + ).toEqual({ status: 'invalid' }); + expect(calls).toBe(0); +}); +it('completed work cannot schedule another call through a leaked action while forgotten work settles', async () => { + const scheduler = createExtensionScheduler(), + gate = deferred<string>(); + let action!: ExtensionAction, + calls = 0; + const task = runExtensionAction( + scheduler, + capture(), + () => true, + (a) => { + action = a; + void callExtension(a, 'sign', () => gate.promise); + return Promise.resolve(); + } + ); + await Promise.resolve(); + await Promise.resolve(); + expect( + await callExtension(action, 'auth', () => { + calls++; + return Promise.resolve('unused'); + }) + ).toEqual({ status: 'stopped' }); + gate.resolve('late'); + await task; + expect(calls).toBe(0); +});