commit 4fb97073cb391ee8fa3c7061442dc6b257e48553
parent 77ae2b955047360b9b38ce9b65677799bb0a99b1
Author: triesap <tyson@radroots.org>
Date: Wed, 7 Oct 2026 01:04:03 +0000
identity: bind extension responses to immutable approved templates (HCP-053)
- Capture reviewed public operations behind immutable scoped signing approvals
- Reconstruct and verify exact returned fields without provider cache authority
- Fence actual SDK signing through shared admission and fresh owner checks
- Verify hostile mutations, cached signatures and revoked responses in real tests
Diffstat:
6 files changed, 975 insertions(+), 2 deletions(-)
diff --git a/web/src/lib/nostr/approved-signing.ts b/web/src/lib/nostr/approved-signing.ts
@@ -0,0 +1,186 @@
+import type { UnsignedEvent } from 'applesauce-core/helpers';
+import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
+import {
+ publicRecordSnapshot,
+ type PublicRecordHandle
+} from '../persistence/records.ts';
+import {
+ bindCapturedArtifact,
+ type CapturedArtifact
+} from '../persistence/artifact-records.ts';
+import { inspectLocalTemplate } from './local-template.ts';
+import { boundedEnvelopeNumbers } from './envelope-bounds.ts';
+
+declare const approvalBrand: unique symbol;
+export type ApprovedPublicSigning = Readonly<{ [approvalBrand]: true }>;
+type Capture = Readonly<{
+ owner: string;
+ id: string;
+ revision: number;
+ wire: string;
+ hash: string;
+}>;
+const approvals = new WeakMap<ApprovedPublicSigning, Capture>();
+// Internal captured-operation capability. This is neither a raw UI template
+// signer nor current IDB/CAS, inbox-readiness, transport or publication proof.
+// Later operation controllers own those obligations. Private seal13/AUTH22242
+// approvals require their separate typed owners; plaintext14 is never admitted.
+export function approveCapturedPublicSigning(
+ record: PublicRecordHandle,
+ owner: unknown,
+ id: unknown,
+ review: unknown
+): ApprovedPublicSigning | undefined {
+ if (review !== 'reviewed_captured_operation') return undefined;
+ const row = publicRecordSnapshot(record, owner, id);
+ if (!row || row.family === 'public_draft' || row.artifact !== null)
+ return undefined;
+ const template = inspectLocalTemplate(
+ row.capture.wire,
+ row.owner,
+ row.capture.kind
+ );
+ if (!template || template.hash !== row.capture.hash) return undefined;
+ // Retain primitive canonical wire/hash independently, never caller arrays.
+ const token = Object.freeze({}) as ApprovedPublicSigning;
+ approvals.set(token, {
+ owner: row.owner,
+ id: row.id,
+ revision: row.revision,
+ wire: row.capture.wire,
+ hash: row.capture.hash
+ });
+ return token;
+}
+export function approvedSigningIdentity(
+ approval: ApprovedPublicSigning
+): Readonly<{ owner: string; id: string; revision: number }> | undefined {
+ const saved = approvals.get(approval);
+ return saved
+ ? { owner: saved.owner, id: saved.id, revision: saved.revision }
+ : undefined;
+}
+// Each acquisition is a disposable fresh JSON copy. No retained template or
+// mutable SDK verification symbol ever crosses the provider boundary.
+export function disposableApprovedTemplate(
+ approval: ApprovedPublicSigning
+): UnsignedEvent | undefined {
+ const saved = approvals.get(approval);
+ return saved ? (JSON.parse(saved.wire) as UnsignedEvent) : undefined;
+}
+function own(value: object, name: string): unknown {
+ const descriptor = Object.getOwnPropertyDescriptor(value, name);
+ return descriptor && 'value' in descriptor ? descriptor.value : undefined;
+}
+// Bounded reconstruction, using only own data fields and indexed array entries.
+// Do not spread/serialize the response, enumerate extras, invoke toJSON, acquire
+// accessor values, or follow provider-controlled iterators and cache symbols.
+function signedWire(raw: unknown): string | undefined {
+ try {
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
+ return undefined;
+ const id = own(raw, 'id'),
+ pubkey = own(raw, 'pubkey'),
+ sig = own(raw, 'sig'),
+ numbers = boundedEnvelopeNumbers(
+ own(raw, 'kind'),
+ own(raw, 'created_at')
+ ),
+ content = own(raw, 'content'),
+ sourceTags = own(raw, 'tags');
+ if (
+ typeof id !== 'string' ||
+ !/^[0-9a-f]{64}$/.test(id) ||
+ typeof pubkey !== 'string' ||
+ !/^[0-9a-f]{64}$/.test(pubkey) ||
+ typeof sig !== 'string' ||
+ !/^[0-9a-f]{128}$/.test(sig) ||
+ !numbers ||
+ typeof content !== 'string' ||
+ !boundedUtf8(content, 131072) ||
+ !Array.isArray(sourceTags)
+ )
+ return undefined;
+ const count = own(sourceTags, 'length');
+ if (
+ typeof count !== 'number' ||
+ !Number.isSafeInteger(count) ||
+ count < 0 ||
+ count > 1024
+ )
+ return undefined;
+ const tags: string[][] = [];
+ let elements = 0,
+ bytes = 0;
+ const encoder = new TextEncoder();
+ for (let i = 0; i < count; i++) {
+ const source = own(sourceTags, String(i));
+ if (!Array.isArray(source)) return undefined;
+ const length = own(source, 'length');
+ if (
+ typeof length !== 'number' ||
+ !Number.isSafeInteger(length) ||
+ length <= 0 ||
+ length > 4096 - elements
+ )
+ return undefined;
+ elements += length;
+ const tag: string[] = [];
+ function append(value: string) {
+ tag.push(value);
+ }
+ for (let j = 0; j < length; j++) {
+ const value = own(source, String(j));
+ if (
+ typeof value !== 'string' ||
+ !boundedUtf8(value, 4096) ||
+ (j === 0 && (value.length === 0 || /\p{Cc}/u.test(value)))
+ )
+ return undefined;
+ bytes += encoder.encode(value).length;
+ if (bytes > 131072) return undefined;
+ append(value);
+ }
+ tags.push(tag);
+ }
+ return JSON.stringify({
+ id,
+ pubkey,
+ kind: numbers.kind,
+ created_at: numbers.created_at,
+ tags,
+ content,
+ sig
+ });
+ } catch {
+ return undefined;
+ }
+}
+export function bindApprovedResponse(
+ approval: ApprovedPublicSigning,
+ response: unknown
+): CapturedArtifact | undefined {
+ const saved = approvals.get(approval);
+ if (!saved) return undefined;
+ const wire = signedWire(response);
+ if (!wire) return undefined;
+ const returned = JSON.parse(wire) as UnsignedEvent;
+ const original = JSON.parse(saved.wire) as UnsignedEvent;
+ if (
+ returned.pubkey !== original.pubkey ||
+ returned.kind !== original.kind ||
+ returned.created_at !== original.created_at ||
+ returned.content !== original.content ||
+ JSON.stringify(returned.tags) !== JSON.stringify(original.tags)
+ )
+ return undefined;
+ // Reparse into a fresh SDK-verification object: no provider cache survives.
+ // Hash and signature must both verify, independently of field comparison.
+ const bound = bindCapturedArtifact(
+ wire,
+ saved.owner,
+ original.kind,
+ saved.hash
+ );
+ return bound.ok ? bound.value : undefined;
+}
diff --git a/web/src/lib/nostr/extension.ts b/web/src/lib/nostr/extension.ts
@@ -5,6 +5,25 @@ import {
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 {
+ approvedSigningIdentity,
+ disposableApprovedTemplate,
+ bindApprovedResponse,
+ type ApprovedPublicSigning
+} from './approved-signing.ts';
+import type { CapturedArtifact } from '../persistence/artifact-records.ts';
+
+export type ApprovedSignResult =
+ | Readonly<{ status: 'signed'; artifact: CapturedArtifact }>
+ | Readonly<{
+ status:
+ | 'invalid_approval'
+ | 'unavailable'
+ | 'busy'
+ | 'stale'
+ | 'refused'
+ | 'mismatch';
+ }>;
import {
browserExtensionScheduler,
@@ -46,6 +65,7 @@ type Controller = {
connect(): Promise<ExtensionSnapshot>;
recheck(): Promise<ExtensionSnapshot>;
probe(review: unknown): Promise<ExtensionSnapshot>;
+ sign(approval: ApprovedPublicSigning): Promise<ApprovedSignResult>;
};
const adapters = new WeakMap<ExtensionAdapter, Controller>();
function present(): Readonly<{ signingCandidate: boolean }> | undefined {
@@ -102,6 +122,7 @@ export function createExtensionAdapter(): ExtensionAdapter {
'not_probed';
let reason: ExtensionGuestReason = 'disconnected';
let pending: 'connect' | 'recheck' | 'probe' | null = null;
+ let signing = false;
let generation = Symbol(),
cancelled = false;
function snapshot(): ExtensionSnapshot {
@@ -130,7 +151,7 @@ export function createExtensionAdapter(): ExtensionAdapter {
action: ExtensionAction | undefined
) => Promise<void>
): Promise<ExtensionSnapshot> {
- if (pending) return { ...snapshot(), admission: 'busy' };
+ if (pending || signing) return { ...snapshot(), admission: 'busy' };
let busy = false;
const original = generation;
pending = action;
@@ -331,8 +352,76 @@ export function createExtensionAdapter(): ExtensionAdapter {
messaging = 'capable';
});
}
+ async function sign(
+ approval: ApprovedPublicSigning
+ ): Promise<ApprovedSignResult> {
+ const captured = approvedSigningIdentity(approval);
+ if (!captured) return { status: 'invalid_approval' };
+ if (pending || signing) return { status: 'busy' };
+ if (
+ !key ||
+ key !== captured.owner ||
+ !signingCandidate ||
+ typeof window === 'undefined'
+ )
+ return { status: 'unavailable' };
+ const original = generation,
+ owner = key;
+ const current = () =>
+ generation === original && !cancelled && key === owner;
+ signing = true;
+ try {
+ const scheduler = browserExtensionScheduler();
+ if (!scheduler) return { status: 'unavailable' };
+ const admitted = await runExtensionAction(
+ scheduler,
+ { owner, session: original, operation: Symbol() },
+ current,
+ async (action): Promise<ApprovedSignResult> => {
+ const before = await freshKey(current, action);
+ if (!current()) return { status: 'stale' };
+ if (before !== owner) {
+ guest(before ? 'changed_key' : 'invalid_key');
+ return { status: 'stale' };
+ }
+ const disposable = disposableApprovedTemplate(approval);
+ if (!disposable) return { status: 'invalid_approval' };
+ const signer = new ExtensionSigner();
+ const response: unknown = await invokeExtension(action, 'sign', () =>
+ signer.signEvent(disposable)
+ );
+ if (!current()) return { status: 'stale' };
+ const artifact = bindApprovedResponse(approval, response);
+ if (!artifact) return { status: 'mismatch' };
+ const after = await freshKey(current, action);
+ if (!current()) return { status: 'stale' };
+ if (after !== owner) {
+ guest(after ? 'changed_key' : 'invalid_key');
+ return { status: 'stale' };
+ }
+ return { status: 'signed', artifact };
+ }
+ );
+ if (admitted.status === 'busy') return { status: 'busy' };
+ if (!current()) return { status: 'stale' };
+ return 'value' in admitted && admitted.value
+ ? admitted.value
+ : { status: admitted.status === 'denied' ? 'refused' : 'stale' };
+ } catch {
+ return { status: current() ? 'refused' : 'stale' };
+ } finally {
+ signing = false;
+ }
+ }
const adapter = Object.freeze({}) as ExtensionAdapter;
- adapters.set(adapter, { snapshot, disconnect, connect, recheck, probe });
+ adapters.set(adapter, {
+ snapshot,
+ disconnect,
+ connect,
+ recheck,
+ probe,
+ sign
+ });
return adapter;
}
export function extensionSnapshot(
@@ -376,3 +465,14 @@ export function probeExtensionAdapter(
Promise.resolve({ state: 'guest', reason: 'unavailable' })
);
}
+// Internal operation capability only. UI identity sessions do not expose this
+// adapter or an unrestricted raw-event signing/publishing function.
+export function signApprovedExtensionAdapter(
+ adapter: ExtensionAdapter,
+ approval: ApprovedPublicSigning
+): Promise<ApprovedSignResult> {
+ return (
+ adapters.get(adapter)?.sign(approval) ??
+ Promise.resolve({ status: 'unavailable' })
+ );
+}
diff --git a/web/tests/e2e/approved-signing.spec.ts b/web/tests/e2e/approved-signing.spec.ts
@@ -0,0 +1,263 @@
+import { expect, test, 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 Signing from './harness/approved-signing.ts';
+import type { ApprovedPublicSigning } from '../../src/lib/nostr/approved-signing.ts';
+import type {
+ ExtensionAdapter,
+ ApprovedSignResult
+} from '../../src/lib/nostr/extension.ts';
+declare global {
+ interface Window {
+ hcp053: typeof Signing;
+ hcp053Fixture: ReturnType<typeof Signing.makeFixture>;
+ hcp053Adapter: ExtensionAdapter;
+ hcp053Approval: ApprovedPublicSigning;
+ hcp053Mode: Signing.Mode;
+ hcp053Calls: string[];
+ hcp053Release: () => void;
+ hcp053Task: Promise<ApprovedSignResult>;
+ }
+}
+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('./harness/approved-signing.ts', import.meta.url)
+ ),
+ name: 'hcp053',
+ 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);
+ const moduleIds = Object.keys(chunks[0].modules);
+ expect(moduleIds.some((id) => id.includes('extension-signer'))).toBe(true);
+ expect(
+ moduleIds.filter((id) =>
+ /\/(?:private-key-signer|password-signer|nostr-connect-signer)\.[cm]?[jt]s(?:$|\?)/.test(
+ id
+ )
+ )
+ ).toEqual([]);
+ bundle = chunks[0].code;
+ console.log(
+ JSON.stringify({
+ fixture: 'HCP053_CONTROLLED_PROVIDER_ACTUAL_SDK_CRYPTO',
+ moduleIds,
+ bundleSha256: createHash('sha256').update(bundle).digest('hex'),
+ claim:
+ 'controlled provider source evidence only, no real extension qualification'
+ })
+ );
+});
+test.afterAll(async () => server.close());
+async function load(page: Page) {
+ await page.goto(server.url);
+ await page.addScriptTag({ content: bundle });
+ await page.evaluate(async () => {
+ const s = window.hcp053,
+ f = s.makeFixture();
+ window.hcp053Fixture = f;
+ window.hcp053Mode = 'exact';
+ window.hcp053Calls = [];
+ window.nostr = {
+ getPublicKey: () => {
+ window.hcp053Calls.push('key');
+ return Promise.resolve(f.owner);
+ },
+ signEvent: (template: Parameters<typeof f.sign>[0]) => {
+ window.hcp053Calls.push('sign');
+ return Promise.resolve(f.sign(template, window.hcp053Mode));
+ }
+ };
+ window.hcp053Adapter = s.createExtensionAdapter();
+ await s.connectExtensionAdapter(window.hcp053Adapter);
+ const a = s.approveCapturedPublicSigning(
+ f.record,
+ f.owner,
+ f.id,
+ 'reviewed_captured_operation'
+ );
+ if (!a) throw new Error('missing fixture approval');
+ window.hcp053Approval = a;
+ window.hcp053Calls = [];
+ });
+}
+test.afterEach(async ({ page }) => {
+ await page.evaluate(() => window.hcp053Fixture?.close());
+});
+test('exact actual SDK response returns immutable artifact and never publishes/stores', async ({
+ page
+}) => {
+ await load(page);
+ const value = await page.evaluate(async () => {
+ const s = window.hcp053,
+ result = await s.signApprovedExtensionAdapter(
+ window.hcp053Adapter,
+ window.hcp053Approval
+ );
+ return {
+ status: result.status,
+ author:
+ result.status === 'signed'
+ ? s.capturedArtifactSnapshot(result.artifact)?.author
+ : null,
+ expected: window.hcp053Fixture.owner,
+ calls: window.hcp053Calls
+ };
+ });
+ expect(value.status).toBe('signed');
+ expect(value.author).toBe(value.expected);
+ expect(value.calls).toEqual(['key', 'sign', 'key']);
+});
+for (const mode of [
+ 'author',
+ 'kind',
+ 'time',
+ 'tags',
+ 'content',
+ 'cached',
+ 'mutate',
+ 'denied'
+] as const)
+ test(`actual SDK hostile ${mode} is finite and returns no artifact`, async ({
+ page
+ }) => {
+ await load(page);
+ await page.evaluate((mode) => {
+ window.hcp053Mode = mode;
+ }, mode);
+ expect(
+ await page.evaluate(
+ async () =>
+ (
+ await window.hcp053.signApprovedExtensionAdapter(
+ window.hcp053Adapter,
+ window.hcp053Approval
+ )
+ ).status
+ )
+ ).toBe(mode === 'denied' ? 'refused' : 'mismatch');
+ });
+test('unsettled signing retains shared slot and disconnect fences late exact response', async ({
+ page
+}) => {
+ await load(page);
+ await page.evaluate(() => {
+ const f = window.hcp053Fixture;
+ window.nostr = {
+ getPublicKey: () => {
+ window.hcp053Calls.push('key');
+ return Promise.resolve(f.owner);
+ },
+ signEvent: (template: Parameters<typeof f.sign>[0]) => {
+ window.hcp053Calls.push('sign');
+ return new Promise((resolve) => {
+ window.hcp053Release = () => resolve(f.sign(template));
+ });
+ }
+ };
+ window.hcp053Task = window.hcp053.signApprovedExtensionAdapter(
+ window.hcp053Adapter,
+ window.hcp053Approval
+ );
+ });
+ await expect
+ .poll(() => page.evaluate(() => window.hcp053Calls))
+ .toEqual(['key', 'sign']);
+ expect(
+ await page.evaluate(
+ async () =>
+ (
+ await window.hcp053.signApprovedExtensionAdapter(
+ window.hcp053Adapter,
+ window.hcp053Approval
+ )
+ ).status
+ )
+ ).toBe('busy');
+ await page.evaluate(() =>
+ window.hcp053.disconnectExtensionAdapter(window.hcp053Adapter)
+ );
+ expect(
+ await page.evaluate(
+ async () =>
+ (
+ await window.hcp053.connectExtensionAdapter(
+ window.hcp053.createExtensionAdapter()
+ )
+ ).admission
+ )
+ ).toBe('busy');
+ expect(
+ await page.evaluate(async () => {
+ window.hcp053Release();
+ return (await window.hcp053Task).status;
+ })
+ ).toBe('stale');
+ expect(
+ await page.evaluate(() =>
+ window.hcp053.extensionSnapshot(window.hcp053Adapter)
+ )
+ ).toEqual({ state: 'guest', reason: 'disconnected' });
+ expect(await page.evaluate(() => window.hcp053Calls)).toEqual([
+ 'key',
+ 'sign'
+ ]);
+});
+for (const phase of ['before', 'after'] as const)
+ test(`fresh ${phase} owner change prevents artifact admission`, async ({
+ page
+ }) => {
+ await load(page);
+ const outcome = await page.evaluate(async (phase) => {
+ const s = window.hcp053,
+ f = window.hcp053Fixture,
+ other = s.makeFixture();
+ let keys = 0;
+ try {
+ window.nostr = {
+ getPublicKey: () => {
+ window.hcp053Calls.push('key');
+ keys++;
+ return Promise.resolve(
+ phase === 'before' || keys > 1 ? other.owner : f.owner
+ );
+ },
+ signEvent: (template: Parameters<typeof f.sign>[0]) => {
+ window.hcp053Calls.push('sign');
+ return Promise.resolve(f.sign(template));
+ }
+ };
+ const result = await s.signApprovedExtensionAdapter(
+ window.hcp053Adapter,
+ window.hcp053Approval
+ );
+ return {
+ status: result.status,
+ calls: window.hcp053Calls,
+ snapshot: s.extensionSnapshot(window.hcp053Adapter)
+ };
+ } finally {
+ other.close();
+ }
+ }, phase);
+ expect(outcome.status).toBe('stale');
+ expect(outcome.calls).toEqual(
+ phase === 'before' ? ['key'] : ['key', 'sign', 'key']
+ );
+ expect(outcome.snapshot).toEqual({ state: 'guest', reason: 'changed_key' });
+ });
diff --git a/web/tests/e2e/harness/approved-signing.ts b/web/tests/e2e/harness/approved-signing.ts
@@ -0,0 +1,143 @@
+import {
+ finalizeEvent,
+ getEventHash,
+ verifiedSymbol,
+ type EventTemplate
+} from 'applesauce-core/helpers';
+import {
+ decodePublicRecord,
+ publicRecordSnapshot
+} from '../../../src/lib/persistence/records.ts';
+import { capturedArtifactSnapshot } from '../../../src/lib/persistence/artifact-records.ts';
+import {
+ approveCapturedPublicSigning,
+ disposableApprovedTemplate,
+ bindApprovedResponse
+} from '../../../src/lib/nostr/approved-signing.ts';
+export {
+ createExtensionAdapter,
+ connectExtensionAdapter,
+ disconnectExtensionAdapter,
+ signApprovedExtensionAdapter,
+ extensionSnapshot
+} from '../../../src/lib/nostr/extension.ts';
+export {
+ approveCapturedPublicSigning,
+ disposableApprovedTemplate,
+ bindApprovedResponse,
+ capturedArtifactSnapshot,
+ publicRecordSnapshot
+};
+export type Mode =
+ | 'exact'
+ | 'author'
+ | 'kind'
+ | 'time'
+ | 'tags'
+ | 'content'
+ | 'cached'
+ | 'mutate'
+ | 'denied';
+// Test-only ephemeral cryptographic material. No literal key, persistence, log,
+// production dependency or named-extension qualification is introduced.
+export function makeFixture(kind: 30402 | 5 | 10050 = 30402) {
+ const key = crypto.getRandomValues(new Uint8Array(32));
+ const source = finalizeEvent(
+ {
+ kind: kind === 10050 ? 10050 : 30402,
+ created_at: 100,
+ tags:
+ kind === 10050
+ ? []
+ : [
+ ['d', 'fixture'],
+ ['published_at', '100']
+ ],
+ content: 'public fixture source'
+ },
+ key
+ );
+ const template = {
+ pubkey: source.pubkey,
+ kind,
+ created_at: 101,
+ tags:
+ kind === 5
+ ? [
+ ['e', source.id],
+ ['a', `30402:${source.pubkey}:fixture`]
+ ]
+ : kind === 10050
+ ? []
+ : [
+ ['d', 'fixture'],
+ ['published_at', '100']
+ ],
+ content: 'public fixture operation'
+ };
+ const id = crypto.randomUUID();
+ const row = {
+ schema: 1,
+ family: kind === 10050 ? 'preference_operation' : 'public_operation',
+ owner: source.pubkey,
+ id,
+ revision: 0,
+ ...(kind === 10050 ? { consent: 'explicit_review' } : {}),
+ source: {
+ type: kind === 10050 ? 'inbox_head' : 'public_head',
+ wire: JSON.stringify(source)
+ },
+ capture: {
+ kind,
+ wire: JSON.stringify(template),
+ hash: getEventHash(template),
+ targets: ['wss://one.example.org'],
+ policyFingerprint: 'a'.repeat(64)
+ },
+ artifact: null,
+ receipts: []
+ };
+ const record = decodePublicRecord(JSON.stringify(row), row.owner, id);
+ if (!record.ok) {
+ key.fill(0);
+ throw new Error('invalid test fixture');
+ }
+ return {
+ record: record.value,
+ owner: row.owner,
+ id,
+ template,
+ sign(input: EventTemplate, mode: Mode = 'exact') {
+ if (mode === 'denied') throw new Error('test-only refusal');
+ const copy = { ...input, tags: input.tags.map((tag) => [...tag]) };
+ if (mode === 'kind') copy.kind = 1;
+ if (mode === 'time') copy.created_at++;
+ if (mode === 'tags' || mode === 'mutate')
+ copy.tags.push(['changed', 'fixture']);
+ if (mode === 'content') copy.content += ' changed';
+ if (mode === 'mutate') {
+ input.tags.push(['provider', 'mutation']);
+ input.content = 'changed disposable copy';
+ }
+ if (mode === 'author') {
+ const other = crypto.getRandomValues(new Uint8Array(32));
+ try {
+ return finalizeEvent(copy, other);
+ } finally {
+ other.fill(0);
+ }
+ }
+ const event = finalizeEvent(copy, key);
+ if (mode === 'cached') event.sig = '0'.repeat(128);
+ // A hostile provider can return the SDK's mutable cached verification flag.
+ Object.defineProperty(event, verifiedSymbol, {
+ value: true,
+ configurable: true
+ });
+ return event;
+ },
+ close() {
+ key.fill(0);
+ }
+ };
+}
diff --git a/web/tests/integration/approved-signing.test.ts b/web/tests/integration/approved-signing.test.ts
@@ -0,0 +1,27 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ createExtensionAdapter,
+ signApprovedExtensionAdapter
+} from '../../src/lib/nostr/extension.ts';
+import {
+ approveCapturedPublicSigning,
+ type ApprovedPublicSigning
+} from '../../src/lib/nostr/approved-signing.ts';
+await test('approved signing import/SSR and forged approval have no provider or storage effect', async () => {
+ assert.equal(typeof window, 'undefined');
+ const adapter = createExtensionAdapter();
+ assert.equal(
+ approveCapturedPublicSigning(
+ {} as never,
+ '',
+ '',
+ 'reviewed_captured_operation'
+ ),
+ undefined
+ );
+ assert.deepEqual(
+ await signApprovedExtensionAdapter(adapter, {} as ApprovedPublicSigning),
+ { status: 'invalid_approval' }
+ );
+});
diff --git a/web/tests/unit/approved-signing.test.ts b/web/tests/unit/approved-signing.test.ts
@@ -0,0 +1,254 @@
+import { describe, expect, it } from 'vitest';
+import { getEventHash } from 'applesauce-core/helpers';
+import { verifyEnvelope } from '../../src/lib/nostr/verified-envelope.ts';
+import { decodePublicRecord } from '../../src/lib/persistence/records.ts';
+import {
+ makeFixture,
+ approveCapturedPublicSigning,
+ disposableApprovedTemplate,
+ bindApprovedResponse,
+ capturedArtifactSnapshot,
+ publicRecordSnapshot
+} from '../e2e/harness/approved-signing.ts';
+import type { ApprovedPublicSigning } from '../../src/lib/nostr/approved-signing.ts';
+import type { PublicRecordHandle } from '../../src/lib/persistence/records.ts';
+function approved(f: ReturnType<typeof makeFixture>) {
+ const value = approveCapturedPublicSigning(
+ f.record,
+ f.owner,
+ f.id,
+ 'reviewed_captured_operation'
+ );
+ if (!value) throw new Error('missing approved fixture');
+ return value;
+}
+describe('immutable approved signer responses', () => {
+ it('rejects a revoked response Proxy without throwing beyond the finite boundary', () => {
+ const f = makeFixture();
+ try {
+ const a = approved(f),
+ revoked = Proxy.revocable({}, {});
+ revoked.revoke();
+ expect(() => bindApprovedResponse(a, revoked.proxy)).not.toThrow();
+ expect(bindApprovedResponse(a, revoked.proxy)).toBeUndefined();
+ } finally {
+ f.close();
+ }
+ });
+ for (const kind of [30402, 5, 10050] as const)
+ it(`admits genuine exact signed ${kind} from a captured reviewed operation`, () => {
+ const f = makeFixture(kind);
+ try {
+ const a = approved(f),
+ copy = disposableApprovedTemplate(a);
+ if (!copy) throw new Error('missing copy');
+ const artifact = bindApprovedResponse(a, f.sign(copy));
+ expect(artifact).toBeDefined();
+ expect(artifact && capturedArtifactSnapshot(artifact)?.hash).toBe(
+ getEventHash(f.template)
+ );
+ expect(artifact && capturedArtifactSnapshot(artifact)?.author).toBe(
+ f.owner
+ );
+ } finally {
+ f.close();
+ }
+ });
+ for (const mode of [
+ 'author',
+ 'kind',
+ 'time',
+ 'tags',
+ 'content',
+ 'cached',
+ 'mutate'
+ ] as const)
+ it(`rejects hostile ${mode} even with a mutable verified cache flag`, () => {
+ const f = makeFixture();
+ try {
+ const a = approved(f),
+ copy = disposableApprovedTemplate(a);
+ if (!copy) throw new Error('missing copy');
+ const response = f.sign(copy, mode);
+ expect(verifyEnvelope(JSON.stringify(response)).ok).toBe(
+ mode !== 'cached'
+ );
+ expect(bindApprovedResponse(a, response)).toBeUndefined();
+ expect(disposableApprovedTemplate(a)).toEqual(f.template);
+ } finally {
+ f.close();
+ }
+ });
+ it('retains independent original despite mutable caller snapshots and disposable references', () => {
+ const f = makeFixture();
+ try {
+ const a = approved(f),
+ copy = disposableApprovedTemplate(a);
+ if (!copy) throw new Error('missing copy');
+ copy.tags.push(['changed']);
+ copy.content = 'changed';
+ const snapshot = publicRecordSnapshot(f.record, f.owner, f.id);
+ if (snapshot && snapshot.family !== 'public_draft')
+ Object.assign(snapshot.capture, { wire: '{}' });
+ expect(disposableApprovedTemplate(a)).toEqual(f.template);
+ expect(bindApprovedResponse(a, f.sign(f.template))).toBeDefined();
+ } finally {
+ f.close();
+ }
+ });
+ it('requires genuine owner/id scoped record and explicit review', () => {
+ const f = makeFixture();
+ try {
+ expect(
+ approveCapturedPublicSigning(f.record, f.owner, f.id, undefined)
+ ).toBeUndefined();
+ expect(
+ approveCapturedPublicSigning(
+ f.record,
+ f.owner,
+ crypto.randomUUID(),
+ 'reviewed_captured_operation'
+ )
+ ).toBeUndefined();
+ expect(
+ approveCapturedPublicSigning(
+ {} as PublicRecordHandle,
+ f.owner,
+ f.id,
+ 'reviewed_captured_operation'
+ )
+ ).toBeUndefined();
+ expect(
+ disposableApprovedTemplate({} as ApprovedPublicSigning)
+ ).toBeUndefined();
+ expect(
+ bindApprovedResponse({} as ApprovedPublicSigning, f.sign(f.template))
+ ).toBeUndefined();
+ } finally {
+ f.close();
+ }
+ });
+ it('reconstructs own primitive fields without calling getters, toJSON or tag iterators', () => {
+ const f = makeFixture();
+ try {
+ const a = approved(f),
+ event = f.sign(f.template);
+ let touched = 0;
+ Object.defineProperty(event, 'toJSON', {
+ value: () => {
+ touched++;
+ throw new Error('test-only');
+ }
+ });
+ Object.defineProperty(event.tags, Symbol.iterator, {
+ value: () => {
+ touched++;
+ throw new Error('test-only');
+ }
+ });
+ expect(bindApprovedResponse(a, event)).toBeDefined();
+ Object.defineProperty(event, 'content', {
+ get: () => {
+ touched++;
+ return f.template.content;
+ }
+ });
+ expect(bindApprovedResponse(a, event)).toBeUndefined();
+ expect(touched).toBe(0);
+ } finally {
+ f.close();
+ }
+ });
+ it('rejects draft or already signed records and another owner without creating sign authority', () => {
+ const f = makeFixture(),
+ other = makeFixture();
+ try {
+ expect(
+ approveCapturedPublicSigning(
+ f.record,
+ other.owner,
+ f.id,
+ 'reviewed_captured_operation'
+ )
+ ).toBeUndefined();
+ const row = publicRecordSnapshot(f.record, f.owner, f.id);
+ if (!row || row.family === 'public_draft')
+ throw new Error('missing operation');
+ const event = f.sign(f.template);
+ const signed = decodePublicRecord(
+ JSON.stringify({
+ ...row,
+ artifact: { eventId: event.id, wire: JSON.stringify(event) }
+ }),
+ f.owner,
+ f.id
+ );
+ expect(signed.ok).toBe(true);
+ if (signed.ok)
+ expect(
+ approveCapturedPublicSigning(
+ signed.value,
+ f.owner,
+ f.id,
+ 'reviewed_captured_operation'
+ )
+ ).toBeUndefined();
+ const draft = decodePublicRecord(
+ JSON.stringify({
+ schema: 1,
+ family: 'public_draft',
+ owner: f.owner,
+ id: f.id,
+ revision: 0,
+ savedAtMilliseconds: 0,
+ form: {
+ title: '',
+ description: '',
+ location: '',
+ amount: '',
+ currency: '',
+ unit: '',
+ quantity: '',
+ contactType: '',
+ contactValue: ''
+ }
+ }),
+ f.owner,
+ f.id
+ );
+ expect(draft.ok).toBe(true);
+ if (draft.ok)
+ expect(
+ approveCapturedPublicSigning(
+ draft.value,
+ f.owner,
+ f.id,
+ 'reviewed_captured_operation'
+ )
+ ).toBeUndefined();
+ } finally {
+ f.close();
+ other.close();
+ }
+ });
+ it('bounds huge/sparse/malformed tags and rejects unsupported numbers before encoding', () => {
+ const f = makeFixture();
+ try {
+ const a = approved(f),
+ event = f.sign(f.template);
+ for (const value of [
+ null,
+ [],
+ { ...event, tags: Array(1025) },
+ { ...event, tags: [Array(4097)] },
+ { ...event, created_at: -0 },
+ { ...event, kind: NaN },
+ { ...event, content: 'x'.repeat(131073) },
+ { ...event, tags: [['x', '\ud800']] }
+ ])
+ expect(bindApprovedResponse(a, value)).toBeUndefined();
+ } finally {
+ f.close();
+ }
+ });
+});