commit 50ca422bdb3b63a6e8dff20b2e41f9baa826f44c
parent e9f2ae8721b550e41d4e1142e81c78a56fc914df
Author: triesap <tyson@radroots.org>
Date: Tue, 6 Oct 2026 23:44:03 +0000
identity: implement explicit extension connection and capability states (HCP-051)
- Pin inspected Applesauce signers and isolate the browser extension adapter.
- Validate fresh owner keys and fence disconnected or late capability results.
- Require reviewed self-copy probes and downgrade removed encryption methods.
- Verify SSR and browser regressions with current locked offline fixtures.
Diffstat:
10 files changed, 1130 insertions(+), 10 deletions(-)
diff --git a/web/package.json b/web/package.json
@@ -25,7 +25,8 @@
"@noble/curves": "1.2.0",
"@scure/base": "1.1.1",
"applesauce-core": "6.2.0",
- "applesauce-relay": "6.2.1"
+ "applesauce-relay": "6.2.1",
+ "applesauce-signers": "6.2.3"
},
"devDependencies": {
"@eslint/js": "10.0.1",
diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml
@@ -219,6 +219,9 @@ importers:
applesauce-relay:
specifier: 6.2.1
version: 6.2.1(typescript@6.0.3)
+ applesauce-signers:
+ specifier: 6.2.3
+ version: 6.2.3(@capacitor/core@7.6.9)(typescript@6.0.3)
devDependencies:
'@eslint/js':
specifier: 10.0.1
@@ -294,6 +297,12 @@ packages:
integrity: sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==
}
+ '@capacitor/core@7.6.9':
+ resolution:
+ {
+ integrity: sha512-4DOh/xySC9S5ryhUIqpOppasIyi2WiTdF0JuZ/2DEs+vf5eunRzHDdNYBp1snA3faHciTw/3SVGXfR+WkYxsMA==
+ }
+
'@eslint-community/eslint-utils@4.10.1':
resolution:
{
@@ -477,6 +486,12 @@ packages:
}
engines: { node: '>= 20.19.0' }
+ '@noble/secp256k1@3.2.0':
+ resolution:
+ {
+ integrity: sha512-Z3ZAWOTxJ0EuTuZTi7Y69iK7GgrLHh8sgm45lVDhg/b3Nk1TpAiKhick2KkZisHuupeepSkyIydN/J459SdX1w==
+ }
+
'@opentelemetry/api@1.9.1':
resolution:
{
@@ -657,6 +672,12 @@ packages:
integrity: sha512-ZxOhsSyxYwLJj3pLZCefNitxsj093tb2vq90mp2txoYeBqbcjDjqFhyM8eUjq/uFm6zJ+mUuqxlS2FkuSY1MTA==
}
+ '@scure/base@2.4.0':
+ resolution:
+ {
+ integrity: sha512-thZ1TuJwFwBblOhgsjDKvvGirBxNp+wSvY/DR6tJBJOTDhdAAcHJ8Vbr2eFnqaxeca4+t0i9KBf+uHYGWwZORg==
+ }
+
'@scure/bip32@1.3.1':
resolution:
{
@@ -912,6 +933,12 @@ packages:
integrity: sha512-YIUHEtL2Fl5FZjeKYe/IuwL3OnMUNP2j4ydSr3iZDeHEZSEda4d1PoChefiNhtjE/U/F5OBHEbAX1zCHRZoxpg==
}
+ applesauce-signers@6.2.3:
+ resolution:
+ {
+ integrity: sha512-VP2iupFtD00IOmRfzuFm4rY7MPcgTFhXzpYYcqEUIpdLUU5t5do56nNkMXRgciy+XmDmdFMCi5uxWkSFoMWrmg==
+ }
+
aria-query@5.3.1:
resolution:
{
@@ -1551,6 +1578,14 @@ packages:
integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==
}
+ nostr-signer-capacitor-plugin@0.0.5:
+ resolution:
+ {
+ integrity: sha512-/EvqWz71HZ5cWmzvfXWTm48AWZtbeZDbOg3vLwXyXPjnIp1DR7Wurww/Mo41ORNu1DNPlqH20l7kIXKO6vR5og==
+ }
+ peerDependencies:
+ '@capacitor/core': ^7.0.0
+
nostr-tools@2.19.4:
resolution:
{
@@ -2083,6 +2118,11 @@ snapshots:
hashery: 1.5.1
keyv: 5.6.0
+ '@capacitor/core@7.6.9':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
'@eslint-community/eslint-utils@4.10.1(eslint@10.12.0)':
dependencies:
eslint: 10.12.0
@@ -2176,6 +2216,8 @@ snapshots:
'@noble/hashes@2.4.0': {}
+ '@noble/secp256k1@3.2.0': {}
+
'@opentelemetry/api@1.9.1': {}
'@oxc-project/types@0.152.0': {}
@@ -2235,6 +2277,8 @@ snapshots:
'@scure/base@1.1.1': {}
+ '@scure/base@2.4.0': {}
+
'@scure/bip32@1.3.1':
dependencies:
'@noble/curves': 1.1.0
@@ -2443,6 +2487,21 @@ snapshots:
- supports-color
- typescript
+ applesauce-signers@6.2.3(@capacitor/core@7.6.9)(typescript@6.0.3):
+ dependencies:
+ '@noble/secp256k1': 3.2.0
+ '@scure/base': 2.4.0
+ applesauce-core: 6.2.0(typescript@6.0.3)
+ debug: 4.4.3
+ nanoid: 5.1.16
+ rxjs: 7.8.2
+ optionalDependencies:
+ nostr-signer-capacitor-plugin: 0.0.5(@capacitor/core@7.6.9)
+ transitivePeerDependencies:
+ - '@capacitor/core'
+ - supports-color
+ - typescript
+
aria-query@5.3.1: {}
assertion-error@2.0.1: {}
@@ -2766,6 +2825,11 @@ snapshots:
natural-compare@1.4.0: {}
+ nostr-signer-capacitor-plugin@0.0.5(@capacitor/core@7.6.9):
+ dependencies:
+ '@capacitor/core': 7.6.9
+ optional: true
+
nostr-tools@2.19.4(typescript@6.0.3):
dependencies:
'@noble/ciphers': 0.5.3
diff --git a/web/src/lib/nostr/extension.ts b/web/src/lib/nostr/extension.ts
@@ -0,0 +1,315 @@
+import {
+ ExtensionSigner,
+ ExtensionMissingError
+} from 'applesauce-signers/signers/extension-signer';
+import { canonicalPublicKey } from '../contracts/public-key.ts';
+import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
+import { PUBLIC_INGRESS_BUDGETS } from '../config/budgets.ts';
+
+declare const adapterBrand: unique symbol;
+export type ExtensionAdapter = Readonly<{ [adapterBrand]: true }>;
+export type ExtensionGuestReason =
+ | 'disconnected'
+ | 'missing'
+ | 'refused'
+ | 'invalid_key'
+ | 'changed_key'
+ | 'unavailable';
+export type ExtensionSnapshot =
+ | Readonly<{ state: 'guest'; reason: ExtensionGuestReason }>
+ | Readonly<{ state: 'pending'; action: 'connect' | 'recheck' | 'probe' }>
+ | Readonly<{
+ state: 'connected';
+ publicKey: string;
+ signingCandidate: boolean;
+ messaging: 'not_probed' | 'unsupported' | 'refused' | 'capable';
+ }>;
+
+declare global {
+ interface Window {
+ nostr?: unknown;
+ }
+}
+type Controller = {
+ snapshot(): ExtensionSnapshot;
+ disconnect(): void;
+ connect(): Promise<ExtensionSnapshot>;
+ recheck(): Promise<ExtensionSnapshot>;
+ probe(review: unknown): Promise<ExtensionSnapshot>;
+};
+const adapters = new WeakMap<ExtensionAdapter, Controller>();
+function present(): Readonly<{ signingCandidate: boolean }> | undefined {
+ if (typeof window === 'undefined') return undefined;
+ const provider: unknown = window.nostr;
+ if (
+ (typeof provider !== 'object' && typeof provider !== 'function') ||
+ provider === null
+ )
+ return undefined;
+ const value = provider as { getPublicKey?: unknown; signEvent?: unknown };
+ return typeof value.getPublicKey === 'function'
+ ? { signingCandidate: typeof value.signEvent === 'function' }
+ : undefined;
+}
+async function freshKey(current: () => boolean): 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());
+}
+// Lexically owned per-adapter state; no mutable opaque receiver, browser handle
+// or imported signer escapes through the WeakMap/controller boundary.
+export function createExtensionAdapter(): ExtensionAdapter {
+ let key: string | null = null,
+ signingCandidate = false;
+ let messaging: 'not_probed' | 'unsupported' | 'refused' | 'capable' =
+ 'not_probed';
+ let reason: ExtensionGuestReason = 'disconnected';
+ let pending: 'connect' | 'recheck' | 'probe' | null = null;
+ let generation = {},
+ cancelled = false;
+ function snapshot(): ExtensionSnapshot {
+ if (pending && !cancelled) return { state: 'pending', action: pending };
+ return key
+ ? { state: 'connected', publicKey: key, signingCandidate, messaging }
+ : { state: 'guest', reason };
+ }
+ function guest(nextReason: ExtensionGuestReason) {
+ key = null;
+ signingCandidate = false;
+ messaging = 'not_probed';
+ reason = nextReason;
+ }
+ function disconnect() {
+ generation = {};
+ cancelled = true;
+ guest(
+ 'disconnected'
+ ); /* Retain pending slot until actual promise settlement. */
+ }
+ async function run(
+ action: 'connect' | 'recheck' | 'probe',
+ work: (current: () => boolean) => Promise<void>
+ ): Promise<ExtensionSnapshot> {
+ if (pending) return snapshot();
+ const original = generation;
+ pending = action;
+ cancelled = false;
+ const current = () => generation === original && !cancelled;
+ try {
+ await work(current);
+ } catch (error) {
+ if (current())
+ guest(error instanceof ExtensionMissingError ? 'missing' : 'refused');
+ } finally {
+ pending = null;
+ }
+ return snapshot();
+ }
+ function connect(): Promise<ExtensionSnapshot> {
+ return run('connect', async (current) => {
+ if (typeof window === 'undefined') {
+ guest('unavailable');
+ return;
+ }
+ const candidate = present();
+ if (!current()) return;
+ if (!candidate) {
+ guest('missing');
+ return;
+ }
+ const owner = await freshKey(current);
+ if (!current()) return;
+ if (!owner) {
+ guest('invalid_key');
+ return;
+ }
+ if (key && owner !== key) {
+ guest('changed_key');
+ return;
+ }
+ const resolvedCandidate = present();
+ if (!current()) return;
+ if (!resolvedCandidate) {
+ guest('missing');
+ return;
+ }
+ key = owner;
+ signingCandidate = resolvedCandidate.signingCandidate;
+ messaging = 'not_probed';
+ });
+ }
+ function recheck(): Promise<ExtensionSnapshot> {
+ if (!key) return Promise.resolve(snapshot());
+ return run('recheck', async (current) => {
+ const owner = await freshKey(current);
+ if (!current()) return;
+ if (!owner) {
+ guest('invalid_key');
+ return;
+ }
+ if (owner !== key) {
+ guest('changed_key');
+ return;
+ }
+ const candidate = present();
+ if (!current()) return;
+ if (!candidate) {
+ guest('missing');
+ return;
+ }
+ signingCandidate = candidate.signingCandidate;
+ if (messaging === 'capable') {
+ const cipher = new ExtensionSigner().nip44;
+ if (!current()) return;
+ if (!cipher) {
+ messaging = 'unsupported';
+ return;
+ }
+ const encrypt = cipher.encrypt;
+ if (!current()) return;
+ const decrypt = cipher.decrypt;
+ if (!current()) return;
+ if (typeof encrypt !== 'function' || typeof decrypt !== 'function')
+ messaging = 'unsupported';
+ }
+ });
+ }
+ function probe(review: unknown): Promise<ExtensionSnapshot> {
+ if (!key || review !== 'reviewed_self_copy')
+ return Promise.resolve(snapshot());
+ return run('probe', async (current) => {
+ const owner = key;
+ if (!owner) return;
+ const checked = await freshKey(current);
+ if (!current()) return;
+ if (checked !== owner) {
+ guest(checked ? 'changed_key' : 'invalid_key');
+ return;
+ }
+ const signer = new ExtensionSigner(),
+ cipher = signer.nip44;
+ if (!current()) return;
+ if (!cipher) {
+ messaging = 'unsupported';
+ return;
+ }
+ const encryptMethod = cipher.encrypt;
+ if (!current()) return;
+ const decryptMethod = cipher.decrypt;
+ if (!current()) return;
+ if (
+ typeof encryptMethod !== 'function' ||
+ typeof decryptMethod !== 'function'
+ ) {
+ messaging = 'unsupported';
+ return;
+ }
+ const encrypt = encryptMethod.bind(cipher);
+ if (!current()) return;
+ const decrypt = decryptMethod.bind(cipher);
+ if (!current()) return;
+ const text = 'HarvestCircle self-copy check:' + crypto.randomUUID();
+ let encrypted: unknown, decrypted: unknown;
+ try {
+ if (!current()) return;
+ encrypted = await encrypt(owner, text);
+ if (!current()) return;
+ if (
+ typeof encrypted !== 'string' ||
+ !boundedUtf8(encrypted, PUBLIC_INGRESS_BUDGETS.eventBytes)
+ ) {
+ messaging = 'refused';
+ return;
+ }
+ if (!current()) return;
+ decrypted = await decrypt(owner, encrypted);
+ } catch {
+ if (current()) messaging = 'refused';
+ return;
+ }
+ if (!current()) return;
+ if (decrypted !== text) {
+ messaging = 'refused';
+ return;
+ }
+ const after = await freshKey(current);
+ if (!current()) return;
+ if (after !== owner) {
+ guest(after ? 'changed_key' : 'invalid_key');
+ return;
+ }
+ const candidate = present();
+ if (!current()) return;
+ if (!candidate) {
+ guest('missing');
+ return;
+ }
+ signingCandidate = candidate.signingCandidate;
+ const finalCipher = new ExtensionSigner().nip44;
+ if (!current()) return;
+ if (!finalCipher) {
+ messaging = 'unsupported';
+ return;
+ }
+ const finalEncrypt = finalCipher.encrypt;
+ if (!current()) return;
+ const finalDecrypt = finalCipher.decrypt;
+ if (!current()) return;
+ if (
+ typeof finalEncrypt !== 'function' ||
+ typeof finalDecrypt !== 'function'
+ ) {
+ messaging = 'unsupported';
+ return;
+ }
+ messaging = 'capable';
+ });
+ }
+ const adapter = Object.freeze({}) as ExtensionAdapter;
+ adapters.set(adapter, { snapshot, disconnect, connect, recheck, probe });
+ return adapter;
+}
+export function extensionSnapshot(
+ adapter: ExtensionAdapter
+): ExtensionSnapshot {
+ return (
+ adapters.get(adapter)?.snapshot() ?? {
+ state: 'guest',
+ reason: 'unavailable'
+ }
+ );
+}
+export function disconnectExtensionAdapter(adapter: ExtensionAdapter): void {
+ adapters.get(adapter)?.disconnect();
+}
+// Explicit action methods only; constructor/import never request an extension.
+export function connectExtensionAdapter(
+ adapter: ExtensionAdapter
+): Promise<ExtensionSnapshot> {
+ return (
+ adapters.get(adapter)?.connect() ??
+ Promise.resolve({ state: 'guest', reason: 'unavailable' })
+ );
+}
+export function recheckExtensionAdapter(
+ adapter: ExtensionAdapter
+): Promise<ExtensionSnapshot> {
+ return (
+ adapters.get(adapter)?.recheck() ??
+ Promise.resolve({ state: 'guest', reason: 'unavailable' })
+ );
+}
+// Only reviewed disposable self-copy text. No caller body, NIP04 fallback, signer
+// object, setup, EVENT or AUTH is exposed. Signing shapes are candidates only.
+export function probeExtensionAdapter(
+ adapter: ExtensionAdapter,
+ review: unknown
+): Promise<ExtensionSnapshot> {
+ return (
+ adapters.get(adapter)?.probe(review) ??
+ Promise.resolve({ state: 'guest', reason: 'unavailable' })
+ );
+}
diff --git a/web/src/lib/runtime/identity-session.ts b/web/src/lib/runtime/identity-session.ts
@@ -0,0 +1,73 @@
+import {
+ createExtensionAdapter,
+ extensionSnapshot,
+ connectExtensionAdapter,
+ recheckExtensionAdapter,
+ probeExtensionAdapter,
+ disconnectExtensionAdapter,
+ type ExtensionAdapter,
+ type ExtensionGuestReason
+} from '../nostr/extension.ts';
+
+declare const sessionBrand: unique symbol;
+export type IdentitySession = Readonly<{ [sessionBrand]: true }>;
+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';
+ }>;
+// 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>();
+export function createIdentitySession(): IdentitySession {
+ const session = Object.freeze({}) as 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);
+ if (snapshot.state !== 'connected') return { ...snapshot };
+ return {
+ state:
+ snapshot.messaging === 'capable' && snapshot.signingCandidate
+ ? 'messaging_capable'
+ : snapshot.signingCandidate
+ ? 'signing_only'
+ : 'connected',
+ publicKey: snapshot.publicKey,
+ messaging: snapshot.messaging
+ };
+}
+export async function connectIdentity(
+ session: IdentitySession
+): Promise<IdentitySnapshot> {
+ const adapter = sessions.get(session);
+ if (adapter) await connectExtensionAdapter(adapter);
+ return identitySessionSnapshot(session);
+}
+export async function recheckIdentityOwner(
+ session: IdentitySession
+): Promise<IdentitySnapshot> {
+ const adapter = sessions.get(session);
+ if (adapter) await recheckExtensionAdapter(adapter);
+ return identitySessionSnapshot(session);
+}
+export async function probeIdentityMessaging(
+ session: IdentitySession,
+ review: unknown
+): Promise<IdentitySnapshot> {
+ const adapter = sessions.get(session);
+ if (adapter) await probeExtensionAdapter(adapter, review);
+ return identitySessionSnapshot(session);
+}
+export function disconnectIdentity(session: IdentitySession): void {
+ const adapter = sessions.get(session);
+ if (adapter) disconnectExtensionAdapter(adapter);
+}
diff --git a/web/tests/e2e/extension.spec.ts b/web/tests/e2e/extension.spec.ts
@@ -0,0 +1,544 @@
+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 Identity from '../../src/lib/runtime/identity-session.ts';
+declare global {
+ interface Window {
+ hcp051: typeof Identity;
+ hcp051Session: Identity.IdentitySession;
+ hcp051Counts: {
+ keys: number;
+ signs: number;
+ encrypts: number;
+ decrypts: number;
+ };
+ hcp051Key: string;
+ hcp051Release: () => void;
+ }
+}
+const owner =
+ '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798';
+const peer = 'c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5';
+let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string;
+test.beforeAll(async () => {
+ server = await createStaticHarness();
+ const source = fileURLToPath(
+ new URL('../../src/lib/runtime/identity-session.ts', import.meta.url)
+ );
+ const result = await build({
+ configFile: false,
+ logLevel: 'silent',
+ build: {
+ write: false,
+ minify: false,
+ lib: { entry: source, name: 'hcp051', 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.filter((id) =>
+ /(?:^|\/)node_modules\/(?:@capacitor\/core|nostr-signer-capacitor-plugin)(?:\/|$)|\/(?:private-key-signer|password-signer|nostr-connect-signer)\.[cm]?[jt]s(?:$|\?)/.test(
+ id
+ )
+ )
+ ).toEqual([]);
+ expect(moduleIds.some((id) => id.includes('extension-signer'))).toBe(true);
+ bundle = chunks[0].code;
+ console.log(
+ JSON.stringify({
+ moduleIds,
+ fixture: 'HCP051_ACTUAL_EXTENSION_SIGNER_CONTROLLED_PROVIDER',
+ bundleSha256: createHash('sha256').update(bundle).digest('hex'),
+ claim:
+ 'real Chromium and installed SDK; controlled provider is not named real extension qualification'
+ })
+ );
+});
+test.afterAll(async () => server.close());
+async function load(
+ page: Page,
+ mode:
+ | 'signing'
+ | 'messaging'
+ | 'missing'
+ | 'denied'
+ | 'invalid'
+ | 'pending'
+ | 'connected' = 'signing'
+) {
+ await page.goto(server.url + '/search');
+ await page.evaluate(
+ ({ owner, mode }) => {
+ window.hcp051Counts = { keys: 0, signs: 0, encrypts: 0, decrypts: 0 };
+ window.hcp051Key = owner;
+ const provider: {
+ getPublicKey: () => Promise<string>;
+ signEvent?: () => Promise<never>;
+ nip44?: {
+ encrypt: (key: string, body: string) => Promise<string>;
+ decrypt: (key: string, body: string) => Promise<string>;
+ };
+ } = {
+ async getPublicKey() {
+ window.hcp051Counts.keys++;
+ if (mode === 'denied') throw new Error('controlled provider refusal');
+ if (mode === 'invalid') return 'f'.repeat(64);
+ if (mode === 'pending')
+ await new Promise<void>((resolve) => {
+ window.hcp051Release = resolve;
+ });
+ return window.hcp051Key;
+ }
+ };
+ if (mode !== 'connected')
+ provider.signEvent = () => {
+ window.hcp051Counts.signs++;
+ return Promise.reject(new Error('Connect must never sign'));
+ };
+ if (mode === 'messaging')
+ provider.nip44 = {
+ encrypt(key, body) {
+ window.hcp051Counts.encrypts++;
+ if (key !== window.hcp051Key)
+ return Promise.reject(new Error('wrong self key'));
+ return Promise.resolve('controlled:' + body);
+ },
+ decrypt(key, body) {
+ window.hcp051Counts.decrypts++;
+ if (key !== window.hcp051Key)
+ return Promise.reject(new Error('wrong self key'));
+ return Promise.resolve(body.replace(/^controlled:/, ''));
+ }
+ };
+ Object.defineProperty(window, 'nostr', {
+ configurable: true,
+ value: mode === 'missing' ? undefined : provider
+ });
+ },
+ { owner, mode }
+ );
+ await page.addScriptTag({ content: bundle });
+ await page.evaluate(() => {
+ window.hcp051Session = window.hcp051.createIdentitySession();
+ });
+}
+async function connect(page: Page) {
+ return page.evaluate(() =>
+ window.hcp051.connectIdentity(window.hcp051Session)
+ );
+}
+test('load and construction are inert; explicit Connect obtains key once without signing or probing', async ({
+ page
+}) => {
+ await load(page);
+ expect(await page.evaluate(() => window.hcp051Counts)).toEqual({
+ keys: 0,
+ signs: 0,
+ encrypts: 0,
+ decrypts: 0
+ });
+ expect(await connect(page)).toMatchObject({
+ state: 'signing_only',
+ publicKey: owner
+ });
+ expect(await page.evaluate(() => window.hcp051Counts)).toEqual({
+ keys: 1,
+ signs: 0,
+ encrypts: 0,
+ decrypts: 0
+ });
+});
+for (const [mode, reason] of [
+ ['missing', 'missing'],
+ ['denied', 'refused'],
+ ['invalid', 'invalid_key']
+] as const)
+ test(`${mode} provider leaves guest with safe finite diagnostics`, async ({
+ page
+ }) => {
+ await load(page, mode);
+ expect(await connect(page)).toEqual({ state: 'guest', reason });
+ expect(
+ await page.evaluate(
+ () => window.hcp051Counts.signs + window.hcp051Counts.encrypts
+ )
+ ).toBe(0);
+ });
+test('key-only connected state does not promise signing or messaging', async ({
+ page
+}) => {
+ await load(page, 'connected');
+ expect(await connect(page)).toMatchObject({
+ state: 'connected',
+ publicKey: owner
+ });
+});
+test('fresh SDK instance detects changed provider key despite the original signer cache', async ({
+ page
+}) => {
+ await load(page);
+ await connect(page);
+ await page.evaluate((peer) => {
+ window.hcp051Key = peer;
+ }, peer);
+ expect(
+ await page.evaluate(() =>
+ window.hcp051.recheckIdentityOwner(window.hcp051Session)
+ )
+ ).toEqual({ state: 'guest', reason: 'changed_key' });
+ expect(await page.evaluate(() => window.hcp051Counts.keys)).toBe(2);
+});
+test('messaging method presence does not probe; explicit reviewed self-copy is required', async ({
+ page
+}) => {
+ await load(page, 'messaging');
+ expect(await connect(page)).toMatchObject({ state: 'signing_only' });
+ expect(
+ await page.evaluate(() =>
+ window.hcp051.probeIdentityMessaging(window.hcp051Session, 'unreviewed')
+ )
+ ).toMatchObject({ state: 'signing_only' });
+ expect(await page.evaluate(() => window.hcp051Counts.encrypts)).toBe(0);
+ expect(
+ await page.evaluate(() =>
+ window.hcp051.probeIdentityMessaging(
+ window.hcp051Session,
+ 'reviewed_self_copy'
+ )
+ )
+ ).toMatchObject({ state: 'messaging_capable', publicKey: owner });
+ expect(await page.evaluate(() => window.hcp051Counts)).toEqual({
+ keys: 3,
+ signs: 0,
+ encrypts: 1,
+ decrypts: 1
+ });
+});
+test('late pending connection cannot restore a disconnected owner and original slot is retained', async ({
+ page
+}) => {
+ await load(page, 'pending');
+ const waiting = connect(page);
+ await expect
+ .poll(() => page.evaluate(() => window.hcp051Counts.keys))
+ .toBe(1);
+ await page.evaluate(() =>
+ window.hcp051.disconnectIdentity(window.hcp051Session)
+ );
+ expect(await connect(page)).toEqual({
+ state: 'guest',
+ reason: 'disconnected'
+ });
+ expect(await page.evaluate(() => window.hcp051Counts.keys)).toBe(1);
+ await page.evaluate(() => window.hcp051Release());
+ expect(await waiting).toEqual({ state: 'guest', reason: 'disconnected' });
+});
+test('missing NIP44 and refusal keep signing-only; no legacy encryption or automatic action', async ({
+ page
+}) => {
+ await load(page);
+ await connect(page);
+ expect(
+ await page.evaluate(() =>
+ window.hcp051.probeIdentityMessaging(
+ window.hcp051Session,
+ 'reviewed_self_copy'
+ )
+ )
+ ).toMatchObject({ state: 'signing_only' });
+ expect(await page.evaluate(() => window.hcp051Counts.encrypts)).toBe(0);
+});
+
+test('reviewed encryption refusal retains public signing candidate with safe messaging refusal state', async ({
+ page
+}) => {
+ await load(page, 'messaging');
+ await connect(page);
+ await page.evaluate(() => {
+ const provider = (
+ window as unknown as {
+ nostr: { nip44: { encrypt: () => Promise<never> } };
+ }
+ ).nostr;
+ provider.nip44.encrypt = () => {
+ window.hcp051Counts.encrypts++;
+ return Promise.reject(
+ new Error('controlled private refusal text must not be exposed')
+ );
+ };
+ });
+ const state = await page.evaluate(() =>
+ window.hcp051.probeIdentityMessaging(
+ window.hcp051Session,
+ 'reviewed_self_copy'
+ )
+ );
+ expect(state).toMatchObject({
+ state: 'signing_only',
+ publicKey: owner,
+ messaging: 'refused'
+ });
+ expect(JSON.stringify(state)).not.toContain('controlled private');
+ expect(await page.evaluate(() => window.hcp051Counts.decrypts)).toBe(0);
+});
+test('disconnect during pending encryption keeps slot and prevents later decrypt or capability resurrection', async ({
+ page
+}) => {
+ await load(page, 'messaging');
+ await connect(page);
+ await page.evaluate(() => {
+ const provider = (
+ window as unknown as {
+ nostr: {
+ nip44: { encrypt: (key: string, body: string) => Promise<string> };
+ };
+ }
+ ).nostr;
+ provider.nip44.encrypt = (_key, body) => {
+ window.hcp051Counts.encrypts++;
+ return new Promise((resolve) => {
+ window.hcp051Release = () => resolve('controlled:' + body);
+ });
+ };
+ });
+ const pending = page.evaluate(() =>
+ window.hcp051.probeIdentityMessaging(
+ window.hcp051Session,
+ 'reviewed_self_copy'
+ )
+ );
+ await expect
+ .poll(() => page.evaluate(() => window.hcp051Counts.encrypts))
+ .toBe(1);
+ await page.evaluate(() =>
+ window.hcp051.disconnectIdentity(window.hcp051Session)
+ );
+ expect(await connect(page)).toEqual({
+ state: 'guest',
+ reason: 'disconnected'
+ });
+ await page.evaluate(() => window.hcp051Release());
+ expect(await pending).toEqual({ state: 'guest', reason: 'disconnected' });
+ expect(await page.evaluate(() => window.hcp051Counts.decrypts)).toBe(0);
+});
+test('repeat Connect detects a changed owner instead of silently adopting it', async ({
+ page
+}) => {
+ await load(page);
+ await connect(page);
+ await page.evaluate((peer) => {
+ window.hcp051Key = peer;
+ }, peer);
+ expect(await connect(page)).toEqual({
+ state: 'guest',
+ reason: 'changed_key'
+ });
+});
+
+for (const property of ['nostr', 'getPublicKey', 'signEvent'] as const)
+ test(`reentrant ${property} inspection disconnects before any new key request`, async ({
+ page
+ }) => {
+ await load(page);
+ await page.evaluate((property) => {
+ const provider = window.nostr as {
+ getPublicKey: () => Promise<string>;
+ signEvent: () => Promise<never>;
+ };
+ const value = property === 'nostr' ? provider : provider[property];
+ Object.defineProperty(
+ property === 'nostr' ? window : provider,
+ property,
+ {
+ configurable: true,
+ get() {
+ window.hcp051.disconnectIdentity(window.hcp051Session);
+ return value;
+ }
+ }
+ );
+ }, property);
+ expect(await connect(page)).toEqual({
+ state: 'guest',
+ reason: 'disconnected'
+ });
+ expect(await page.evaluate(() => window.hcp051Counts.keys)).toBe(0);
+ });
+
+for (const property of ['nip44', 'encrypt', 'decrypt'] as const)
+ test(`reentrant ${property} inspection disconnects before any new encryption`, async ({
+ page
+ }) => {
+ await load(page, 'messaging');
+ await connect(page);
+ await page.evaluate((property) => {
+ const provider = window.nostr as {
+ nip44: {
+ encrypt: (key: string, body: string) => Promise<string>;
+ decrypt: (key: string, body: string) => Promise<string>;
+ };
+ };
+ const cipher = provider.nip44;
+ const value = property === 'nip44' ? cipher : cipher[property];
+ Object.defineProperty(
+ property === 'nip44' ? provider : cipher,
+ property,
+ {
+ configurable: true,
+ get() {
+ window.hcp051.disconnectIdentity(window.hcp051Session);
+ return value;
+ }
+ }
+ );
+ }, property);
+ expect(
+ await page.evaluate(() =>
+ window.hcp051.probeIdentityMessaging(
+ window.hcp051Session,
+ 'reviewed_self_copy'
+ )
+ )
+ ).toEqual({ state: 'guest', reason: 'disconnected' });
+ expect(await page.evaluate(() => window.hcp051Counts.encrypts)).toBe(0);
+ expect(await page.evaluate(() => window.hcp051Counts.decrypts)).toBe(0);
+ });
+
+test('Connect refreshes signing shape after awaited provider key resolution', async ({
+ page
+}) => {
+ await load(page, 'pending');
+ const waiting = connect(page);
+ await expect
+ .poll(() => page.evaluate(() => window.hcp051Counts.keys))
+ .toBe(1);
+ await page.evaluate(() => {
+ const provider = window.nostr as { signEvent?: unknown };
+ delete provider.signEvent;
+ window.hcp051Release();
+ });
+ expect(await waiting).toMatchObject({ state: 'connected', publicKey: owner });
+});
+
+test('reentrant recheck shape inspection cannot restore a disconnected capability', async ({
+ page
+}) => {
+ await load(page);
+ await connect(page);
+ await page.evaluate(() => {
+ const provider = window.nostr as { signEvent: () => Promise<never> };
+ const value = provider.signEvent;
+ Object.defineProperty(provider, 'signEvent', {
+ get() {
+ window.hcp051.disconnectIdentity(window.hcp051Session);
+ return value;
+ }
+ });
+ });
+ expect(
+ await page.evaluate(() =>
+ window.hcp051.recheckIdentityOwner(window.hcp051Session)
+ )
+ ).toEqual({ state: 'guest', reason: 'disconnected' });
+});
+
+for (const property of ['nip44', 'encrypt', 'decrypt'] as const)
+ test(`same-key recheck downgrades removed ${property} without automatic reprobe`, async ({
+ page
+ }) => {
+ await load(page, 'messaging');
+ await connect(page);
+ expect(
+ await page.evaluate(() =>
+ window.hcp051.probeIdentityMessaging(
+ window.hcp051Session,
+ 'reviewed_self_copy'
+ )
+ )
+ ).toMatchObject({ state: 'messaging_capable' });
+ await page.evaluate((property) => {
+ const provider = window.nostr as {
+ nip44?: { encrypt?: unknown; decrypt?: unknown };
+ };
+ if (property === 'nip44') delete provider.nip44;
+ else if (provider.nip44) delete provider.nip44[property];
+ }, property);
+ expect(
+ await page.evaluate(() =>
+ window.hcp051.recheckIdentityOwner(window.hcp051Session)
+ )
+ ).toMatchObject({
+ state: 'signing_only',
+ publicKey: owner,
+ messaging: 'unsupported'
+ });
+ expect(await page.evaluate(() => window.hcp051Counts.encrypts)).toBe(1);
+ expect(await page.evaluate(() => window.hcp051Counts.decrypts)).toBe(1);
+ });
+
+test('disconnect inside an already admitted SDK key call rejects its result without another effect', async ({
+ page
+}) => {
+ await load(page);
+ await page.evaluate(() => {
+ const provider = window.nostr as { getPublicKey: () => Promise<string> };
+ provider.getPublicKey = () => {
+ window.hcp051Counts.keys++;
+ window.hcp051.disconnectIdentity(window.hcp051Session);
+ return Promise.resolve(window.hcp051Key);
+ };
+ });
+ expect(await connect(page)).toEqual({
+ state: 'guest',
+ reason: 'disconnected'
+ });
+ expect(await page.evaluate(() => window.hcp051Counts)).toEqual({
+ keys: 1,
+ signs: 0,
+ encrypts: 0,
+ decrypts: 0
+ });
+});
+
+for (const property of ['nip44', 'signEvent'] as const)
+ test(`final probe key response removes ${property} before capability publication`, async ({
+ page
+ }) => {
+ await load(page, 'messaging');
+ await connect(page);
+ await page.evaluate((property) => {
+ const provider = window.nostr as {
+ getPublicKey: () => Promise<string>;
+ nip44?: unknown;
+ signEvent?: unknown;
+ };
+ provider.getPublicKey = () => {
+ window.hcp051Counts.keys++;
+ if (window.hcp051Counts.keys === 3) delete provider[property];
+ return Promise.resolve(window.hcp051Key);
+ };
+ }, property);
+ const result = await page.evaluate(() =>
+ window.hcp051.probeIdentityMessaging(
+ window.hcp051Session,
+ 'reviewed_self_copy'
+ )
+ );
+ expect(result).toMatchObject(
+ property === 'nip44'
+ ? { state: 'signing_only', messaging: 'unsupported' }
+ : { state: 'connected' }
+ );
+ expect(await page.evaluate(() => window.hcp051Counts)).toEqual({
+ keys: 3,
+ signs: 0,
+ encrypts: 1,
+ decrypts: 1
+ });
+ });
diff --git a/web/tests/e2e/product-details.spec.ts b/web/tests/e2e/product-details.spec.ts
@@ -43,9 +43,10 @@ test.beforeAll(async () => {
capsule,
checkout
]);
- await cp(path.join(capsule, 'web/src'), path.join(web, 'src'), {
- recursive: true
- });
+ for (const relative of ['package.json', 'pnpm-lock.yaml', 'src'])
+ await cp(path.join(capsule, 'web', relative), path.join(web, relative), {
+ recursive: true
+ });
const identities: { path: string; sha256: string }[] = [];
async function identify(dir: string, prefix = '') {
for (const entry of await readdir(dir, { withFileTypes: true })) {
@@ -78,9 +79,21 @@ test.beforeAll(async () => {
path.join(web, 'src/lib/config/deployment-relays.ts'),
policy
);
+ const sourceStore = execFileSync('corepack', ['pnpm', 'store', 'path'], {
+ cwd: path.join(capsule, 'web')
+ })
+ .toString()
+ .trim();
const installed = execFileSync(
'corepack',
- ['pnpm', 'install', '--offline', '--frozen-lockfile'],
+ [
+ 'pnpm',
+ 'install',
+ '--offline',
+ '--frozen-lockfile',
+ '--store-dir',
+ path.dirname(sourceStore)
+ ],
{ cwd: web, timeout: 90000 }
).toString();
const sourceAudit = execFileSync(
@@ -100,6 +113,7 @@ test.beforeAll(async () => {
identities,
policy,
policySha256: createHash('sha256').update(policy).digest('hex'),
+ sourceStore,
installed,
sourceAudit,
compiled
diff --git a/web/tests/e2e/search-form.spec.ts b/web/tests/e2e/search-form.spec.ts
@@ -59,9 +59,21 @@ test.beforeAll(async () => {
);
// Runtime store metadata is volume-specific; install the exact locked graph
// into this disposable clone without a network or lock-repair fallback.
+ const sourceStore = execFileSync('corepack', ['pnpm', 'store', 'path'], {
+ cwd: path.join(capsule, 'web')
+ })
+ .toString()
+ .trim();
const installed = execFileSync(
'corepack',
- ['pnpm', 'install', '--offline', '--frozen-lockfile'],
+ [
+ 'pnpm',
+ 'install',
+ '--offline',
+ '--frozen-lockfile',
+ '--store-dir',
+ path.dirname(sourceStore)
+ ],
{ cwd: path.join(checkout, 'web'), stdio: 'pipe', timeout: 90_000 }
);
const sourceAudit = execFileSync(
@@ -143,6 +155,7 @@ test.beforeAll(async () => {
retention:
'HASHLOGS_ONLY: disposable compiled fixture output is removed after tests',
payload: await payload(path.join(checkout, 'web/build')),
+ sourceStore,
installed: installed.toString(),
compiled: compiled.toString(),
metadata: JSON.parse(
diff --git a/web/tests/e2e/search-results.spec.ts b/web/tests/e2e/search-results.spec.ts
@@ -42,9 +42,10 @@ test.beforeAll(async () => {
capsule,
checkout
]);
- await cp(path.join(capsule, 'web/src'), path.join(web, 'src'), {
- recursive: true
- });
+ for (const relative of ['package.json', 'pnpm-lock.yaml', 'src'])
+ await cp(path.join(capsule, 'web', relative), path.join(web, relative), {
+ recursive: true
+ });
const identities: { path: string; sha256: string }[] = [];
async function identify(dir: string, prefix = '') {
for (const entry of await readdir(dir, { withFileTypes: true })) {
@@ -77,9 +78,21 @@ test.beforeAll(async () => {
path.join(web, 'src/lib/config/deployment-relays.ts'),
policy
);
+ const sourceStore = execFileSync('corepack', ['pnpm', 'store', 'path'], {
+ cwd: path.join(capsule, 'web')
+ })
+ .toString()
+ .trim();
const installed = execFileSync(
'corepack',
- ['pnpm', 'install', '--offline', '--frozen-lockfile'],
+ [
+ 'pnpm',
+ 'install',
+ '--offline',
+ '--frozen-lockfile',
+ '--store-dir',
+ path.dirname(sourceStore)
+ ],
{ cwd: web, timeout: 90000 }
).toString();
const sourceAudit = execFileSync(
@@ -99,6 +112,7 @@ test.beforeAll(async () => {
identities,
policy,
policySha256: createHash('sha256').update(policy).digest('hex'),
+ sourceStore,
installed,
sourceAudit,
compiled
diff --git a/web/tests/integration/extension.test.ts b/web/tests/integration/extension.test.ts
@@ -0,0 +1,21 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+// Actual module imports and adapter construction are inert under SSR. No browser
+// provider, native storage, signer request or process-global user is created.
+import {
+ createIdentitySession,
+ identitySessionSnapshot,
+ connectIdentity
+} from '../../src/lib/runtime/identity-session.ts';
+await test('actual signer dependency/runtime imports and SSR construction perform no extension action', async () => {
+ assert.equal(typeof window, 'undefined');
+ const session = createIdentitySession();
+ assert.deepEqual(identitySessionSnapshot(session), {
+ state: 'guest',
+ reason: 'disconnected'
+ });
+ assert.deepEqual(await connectIdentity(session), {
+ state: 'guest',
+ reason: 'unavailable'
+ });
+});
diff --git a/web/tests/unit/identity-session.test.ts b/web/tests/unit/identity-session.test.ts
@@ -0,0 +1,61 @@
+import { expect, it } from 'vitest';
+import {
+ createIdentitySession,
+ identitySessionSnapshot,
+ connectIdentity,
+ disconnectIdentity,
+ recheckIdentityOwner,
+ probeIdentityMessaging,
+ type IdentitySession
+} from '../../src/lib/runtime/identity-session.ts';
+it('new session is disconnected guest and exports no signer or key custody', () => {
+ const session = createIdentitySession();
+ expect(identitySessionSnapshot(session)).toEqual({
+ state: 'guest',
+ reason: 'disconnected'
+ });
+ expect(Object.keys(session)).toEqual([]);
+});
+it('session snapshots are detached and fabricated handles are unavailable', () => {
+ const session = createIdentitySession();
+ const view = identitySessionSnapshot(session);
+ (view as { reason: string }).reason = 'changed';
+ expect(identitySessionSnapshot(session)).toEqual({
+ state: 'guest',
+ reason: 'disconnected'
+ });
+ expect(identitySessionSnapshot({} as IdentitySession)).toEqual({
+ state: 'guest',
+ reason: 'unavailable'
+ });
+});
+it('SSR explicit connect stays guest without window or storage', async () => {
+ const session = createIdentitySession();
+ expect(await connectIdentity(session)).toEqual({
+ state: 'guest',
+ reason: 'unavailable'
+ });
+});
+it('disconnected owner recheck does not infer remembered authority', async () => {
+ const session = createIdentitySession();
+ expect(await recheckIdentityOwner(session)).toEqual({
+ state: 'guest',
+ reason: 'disconnected'
+ });
+});
+it('unreviewed encryption probe refuses before any capability action', async () => {
+ const session = createIdentitySession();
+ expect(await probeIdentityMessaging(session, 'unreviewed')).toEqual({
+ state: 'guest',
+ reason: 'disconnected'
+ });
+});
+it('disconnect is idempotent and does not retain a key', () => {
+ const session = createIdentitySession();
+ disconnectIdentity(session);
+ disconnectIdentity(session);
+ expect(identitySessionSnapshot(session)).toEqual({
+ state: 'guest',
+ reason: 'disconnected'
+ });
+});