commit abab6f250b3cff13c3b9f5b156a76d1dd802a54f
parent 4612662f19e4c75e507cf7a55bcc94f76742009e
Author: triesap <tyson@radroots.org>
Date: Wed, 7 Oct 2026 11:08:29 +0000
messages: implement explicit connection-scoped NIP-42 authentication (HCP-068)
- Bind reviewed AUTH admission and verified responses to the genuine private connection.
- Serialize permission jobs and freshly recheck SDK ownership before signing and AUTH.
- Bound challenge responses and preserve physical cleanup and outstanding permission ownership.
- Verify protocol faults, unchanged dependency resolution and independent source acceptance.
Diffstat:
9 files changed, 1237 insertions(+), 4 deletions(-)
diff --git a/web/package.json b/web/package.json
@@ -26,7 +26,8 @@
"@scure/base": "1.1.1",
"applesauce-core": "6.2.0",
"applesauce-relay": "6.2.1",
- "applesauce-signers": "6.2.3"
+ "applesauce-signers": "6.2.3",
+ "rxjs": "7.8.2"
},
"devDependencies": {
"@eslint/js": "10.0.1",
diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml
@@ -222,6 +222,9 @@ importers:
applesauce-signers:
specifier: 6.2.3
version: 6.2.3(@capacitor/core@7.6.9)(typescript@6.0.3)
+ rxjs:
+ specifier: 7.8.2
+ version: 7.8.2
devDependencies:
'@eslint/js':
specifier: 10.0.1
diff --git a/web/src/lib/config/budgets.ts b/web/src/lib/config/budgets.ts
@@ -17,6 +17,12 @@ export const PRIVATE_TRANSPORT_BUDGETS = Object.freeze({
envelopeBytes: 32768
});
+// Original M06/M07 authority: responses are counted before permission work,
+// per actual connection and explicit action, never renewed by challenge churn.
+export const PRIVATE_AUTH_BUDGETS = Object.freeze({
+ responsesPerConnectionAction: 2
+});
+
// Approved public-run admission limits shared by all primary/auxiliary sources.
// Logical post-parse work accounting; no WebSocket preallocation guarantee.
const publicDeliveryLimit = 2000;
diff --git a/web/src/lib/nostr/inbox-auth.ts b/web/src/lib/nostr/inbox-auth.ts
@@ -0,0 +1,267 @@
+import { ExtensionSigner } from 'applesauce-signers';
+import { getEventHash, type UnsignedEvent } from 'applesauce-core/helpers';
+import { verifyEnvelope } from './verified-envelope.ts';
+import {
+ beginPrivateAuthConnection,
+ privateAuthChallenge,
+ privateAuthStopped,
+ reservePrivateAuthResponse,
+ sendPrivateAuthResponse,
+ closePrivateAuthConnection,
+ type PrivatePool,
+ type PrivateAuthChallenge
+} from './private-pool.ts';
+import {
+ browserExtensionScheduler,
+ runExtensionAction,
+ callExtension
+} from './extension-scheduler.ts';
+declare const authBrand: unique symbol;
+export type InboxAuthAction = Readonly<{ [authBrand]: true }>;
+type State = {
+ snapshot(): { state: string; responses: number };
+ run(): Promise<Readonly<{ status: string }>>;
+ close(): void;
+};
+const actions = new WeakMap<InboxAuthAction, State>();
+declare const admissionBrand: unique symbol;
+declare const responseBrand: unique symbol;
+export type InboxAuthAdmission = Readonly<{ [admissionBrand]: true }>;
+export type GuardedInboxAuthResponse = Readonly<{ [responseBrand]: true }>;
+const admissions = new WeakMap<
+ InboxAuthAdmission,
+ Readonly<{ pool: PrivatePool; origin: string }>
+>();
+const signedResponses = new WeakMap<
+ GuardedInboxAuthResponse,
+ Readonly<{ proof: PrivateAuthChallenge; wire: string; current(): boolean }>
+>();
+// Read/consume ports cannot manufacture approval. Only the lexical reviewed
+// action and actual scheduler continuation create these genuine capabilities.
+export function takeInboxAuthAdmission(
+ token: InboxAuthAdmission,
+ pool: PrivatePool,
+ origin: string
+): boolean {
+ const saved = admissions.get(token);
+ if (!saved || saved.pool !== pool || saved.origin !== origin) return false;
+ admissions.delete(token);
+ return true;
+}
+export function takeGuardedInboxAuthResponse(
+ token: GuardedInboxAuthResponse,
+ proof: PrivateAuthChallenge
+): string | undefined {
+ const saved = signedResponses.get(token);
+ if (!saved || saved.proof !== proof || !saved.current() || !proof.current())
+ return undefined;
+ signedResponses.delete(token);
+ return saved.wire;
+}
+export async function beginInboxAuthentication(
+ pool: PrivatePool,
+ origin: string,
+ review: unknown
+): Promise<InboxAuthAction | undefined> {
+ if (typeof window === 'undefined' || review !== 'reviewed_connection_auth')
+ return undefined;
+ const admission = Object.freeze({}) as InboxAuthAdmission;
+ admissions.set(admission, { pool, origin });
+ const acquired = await beginPrivateAuthConnection(pool, origin, admission);
+ if (!acquired) return undefined;
+ const connection = acquired;
+ const token = Object.freeze({}) as InboxAuthAction;
+ let busy = false,
+ responses = 0;
+ let phase: 'waiting' | 'accepted' | 'refused' | 'unknown' | 'stopped' =
+ 'waiting';
+ function close() {
+ phase = 'stopped';
+ closePrivateAuthConnection(connection);
+ }
+ function own(value: object, name: string): unknown {
+ const field = Object.getOwnPropertyDescriptor(value, name);
+ return field && 'value' in field ? field.value : undefined;
+ }
+ // Fixed seven-field response reconstruction never invokes provider getters,
+ // iterators/toJSON or mutable cached SDK signature markers.
+ function bindResponse(
+ template: UnsignedEvent,
+ response: unknown
+ ): string | undefined {
+ try {
+ if (!response || typeof response !== 'object' || Array.isArray(response))
+ return undefined;
+ for (const name of ['pubkey', 'kind', 'created_at', 'content'] as const)
+ if (own(response, name) !== template[name]) return undefined;
+ const tags = own(response, 'tags');
+ if (!Array.isArray(tags) || own(tags, 'length') !== 2) return undefined;
+ for (let i = 0; i < 2; i++) {
+ const tag = own(tags, String(i));
+ if (
+ !Array.isArray(tag) ||
+ own(tag, 'length') !== 2 ||
+ own(tag, '0') !== template.tags[i][0] ||
+ own(tag, '1') !== template.tags[i][1]
+ )
+ return undefined;
+ }
+ const id = own(response, 'id'),
+ sig = own(response, 'sig');
+ if (
+ typeof id !== 'string' ||
+ typeof sig !== 'string' ||
+ id !== getEventHash(template)
+ )
+ return undefined;
+ const wire = JSON.stringify({ ...template, id, sig });
+ return verifyEnvelope(wire).ok ? wire : undefined;
+ } catch {
+ return undefined;
+ }
+ }
+ async function run(): Promise<Readonly<{ status: string }>> {
+ if (busy) return { status: 'busy' };
+ const proof = privateAuthChallenge(connection),
+ scheduler = browserExtensionScheduler();
+ if (
+ !proof ||
+ !scheduler ||
+ ['refused', 'unknown', 'stopped'].includes(phase)
+ )
+ return { status: 'stopped' };
+ busy = true;
+ try {
+ const result = await runExtensionAction(
+ scheduler,
+ { owner: proof.owner, session: proof.session, operation: Symbol() },
+ () => proof.current() && phase !== 'stopped',
+ async (job) => {
+ if (!reservePrivateAuthResponse(connection, proof))
+ return { status: 'stopped' };
+ responses++;
+ const signer = new ExtensionSigner();
+ const key = await callExtension(job, 'key', () =>
+ new ExtensionSigner().getPublicKey()
+ );
+ if (
+ key.status !== 'settled' ||
+ !key.current ||
+ key.value !== proof.owner ||
+ !proof.current()
+ ) {
+ close();
+ return { status: 'stopped' };
+ }
+ const time = Math.floor(Date.now() / 1000);
+ if (!Number.isSafeInteger(time) || time < 0 || !proof.current()) {
+ close();
+ return { status: 'stopped' };
+ }
+ const template: UnsignedEvent = {
+ pubkey: proof.owner,
+ kind: 22242,
+ created_at: time,
+ tags: [
+ ['relay', proof.relay],
+ ['challenge', proof.challenge]
+ ],
+ content: ''
+ };
+ const response = await callExtension(job, 'auth', () =>
+ signer.signEvent(
+ JSON.parse(JSON.stringify(template)) as UnsignedEvent
+ )
+ );
+ if (
+ response.status !== 'settled' ||
+ !response.current ||
+ !proof.current()
+ ) {
+ close();
+ return {
+ status: response.status === 'denied' ? 'denied' : 'stopped'
+ };
+ }
+ const wire = bindResponse(template, response.value);
+ if (!wire || !proof.current()) {
+ close();
+ return { status: 'invalid_response' };
+ }
+ // The provider can change its selected identity during signing. Fresh
+ // actual SDK key evidence is required again before the AUTH effect.
+ const effectKey = await callExtension(job, 'key', () =>
+ new ExtensionSigner().getPublicKey()
+ );
+ if (
+ effectKey.status !== 'settled' ||
+ !effectKey.current ||
+ effectKey.value !== proof.owner ||
+ !proof.current()
+ ) {
+ close();
+ return { status: 'stopped' };
+ }
+ const approved = Object.freeze({}) as GuardedInboxAuthResponse;
+ signedResponses.set(approved, {
+ proof,
+ wire,
+ current: () => proof.current() && phase !== 'stopped'
+ });
+ const status = await sendPrivateAuthResponse(
+ connection,
+ proof,
+ approved
+ );
+ phase =
+ status === 'accepted'
+ ? 'accepted'
+ : status === 'refused'
+ ? 'refused'
+ : status === 'unknown'
+ ? 'unknown'
+ : 'stopped';
+ return { status };
+ }
+ );
+ return 'value' in result &&
+ result.value &&
+ (result.status === 'completed' ||
+ result.value.status === 'refused' ||
+ result.value.status === 'unknown')
+ ? result.value
+ : { status: result.status };
+ } finally {
+ busy = false;
+ }
+ }
+ actions.set(token, {
+ run,
+ close,
+ snapshot: () => ({
+ state:
+ privateAuthStopped(connection) &&
+ phase !== 'refused' &&
+ phase !== 'unknown'
+ ? 'stopped'
+ : busy
+ ? 'signing'
+ : privateAuthChallenge(connection)
+ ? 'challenge'
+ : phase,
+ responses
+ })
+ });
+ return token;
+}
+export function inboxAuthSnapshot(action: InboxAuthAction) {
+ return actions.get(action)?.snapshot();
+}
+export function closeInboxAuthentication(action: InboxAuthAction): void {
+ actions.get(action)?.close();
+}
+export function respondInboxAuthentication(
+ action: InboxAuthAction
+): Promise<Readonly<{ status: string }>> {
+ return actions.get(action)?.run() ?? Promise.resolve({ status: 'invalid' });
+}
diff --git a/web/src/lib/nostr/private-pool.ts b/web/src/lib/nostr/private-pool.ts
@@ -1,6 +1,22 @@
import { createScopedRelayPool } from './pool-factory.ts';
+import { NEVER } from 'rxjs';
+import {
+ takeInboxAuthAdmission,
+ takeGuardedInboxAuthResponse,
+ type InboxAuthAdmission,
+ type GuardedInboxAuthResponse
+} from './inbox-auth.ts';
+import {
+ verifyEnvelope,
+ verifiedEnvelopeSnapshot,
+ boundedEnvelopeTags
+} from './verified-envelope.ts';
import { readRelayPolicy, type RelayPolicy } from '../config/relays.ts';
-import { PRIVATE_TRANSPORT_BUDGETS, RELAY_BUDGETS } from '../config/budgets.ts';
+import {
+ PRIVATE_TRANSPORT_BUDGETS,
+ PRIVATE_AUTH_BUDGETS,
+ RELAY_BUDGETS
+} from '../config/budgets.ts';
import {
privateSessionOwnership,
subscribePrivateSessionClose,
@@ -30,12 +46,37 @@ type Owner = {
token: PrivatePool;
closed(): boolean;
cleaned(): boolean;
+ auth(
+ origin: string,
+ admission: InboxAuthAdmission
+ ): Promise<PrivateAuthConnection | undefined>;
subscribe(
limit: number,
listener: (message: PrivatePageMessage) => void
): () => void;
close(): void;
};
+declare const connectionBrand: unique symbol;
+export type PrivateAuthConnection = Readonly<{ [connectionBrand]: true }>;
+export type PrivateAuthChallenge = Readonly<{
+ owner: string;
+ session: symbol;
+ connection: symbol;
+ relay: string;
+ challenge: string;
+ current(): boolean;
+}>;
+type AuthControl = {
+ challenge(): PrivateAuthChallenge | undefined;
+ stopped(): boolean;
+ reserve(proof: PrivateAuthChallenge): boolean;
+ send(
+ proof: PrivateAuthChallenge,
+ response: GuardedInboxAuthResponse
+ ): Promise<'accepted' | 'refused' | 'unknown' | 'stopped'>;
+ close(): void;
+};
+const authConnections = new WeakMap<PrivateAuthConnection, AuthControl>();
const pools = new WeakMap<PrivatePool, Owner>();
let lifetime: Owner | undefined;
// Fixed scope selection is not authenticated owner10050 membership/readiness.
@@ -46,8 +87,9 @@ export function getPrivatePool(
selected: readonly string[]
): PrivatePool | undefined {
if (typeof window === 'undefined') return undefined;
- const capture = privateSessionOwnership(session);
- if (!capture) throw new Error('private_session_invalid');
+ const captured = privateSessionOwnership(session);
+ if (!captured) throw new Error('private_session_invalid');
+ const capture = captured;
const manifest = readRelayPolicy(policy);
if (!manifest.messagingEnabled) throw new Error('private_pool_disabled');
const length = Array.isArray(selected) ? selected.length : 0;
@@ -88,6 +130,7 @@ export function getPrivatePool(
cleanupRequired = false;
let active = () => {};
let off = () => {};
+ const authCleanup = new Map<string, () => void>();
const owner: Owner = {
session,
policy,
@@ -95,6 +138,213 @@ export function getPrivatePool(
token,
closed: () => closed,
cleaned: () => cleaned,
+ async auth(origin, admission) {
+ if (
+ closed ||
+ cleanupRequired ||
+ !origins.includes(origin) ||
+ authCleanup.has(origin) ||
+ !capture.current()
+ )
+ return undefined;
+ if (!takeInboxAuthAdmission(admission, owner.token, origin))
+ return undefined;
+ // Reserve before any provider job. No duplicate reviewed action may reset
+ // a live connection's response admission counter.
+ let stopped = false,
+ responded = false,
+ responses = 0,
+ challenge: string | undefined;
+ let generation: symbol | undefined;
+ const proofs = new WeakMap<PrivateAuthChallenge, true>();
+ let reservation: PrivateAuthChallenge | undefined;
+ let sent = false;
+ const releases = new Map<symbol, () => void>();
+ function cleanup() {
+ stopped = true;
+ challenge = undefined;
+ generation = undefined;
+ let failed = false;
+ for (const release of releases.values()) {
+ try {
+ release();
+ } catch {
+ failed = true;
+ }
+ }
+ if (failed) throw new Error('private_auth_cleanup_required');
+ }
+ authCleanup.set(origin, cleanup);
+ const halt = () => {
+ if (stopped) return;
+ stopped = true;
+ try {
+ owner.close();
+ } catch {
+ /* Actual control retained for retry. */
+ }
+ };
+ if (
+ !(await recheckPrivateSession(session)) ||
+ closed ||
+ stopped ||
+ !capture.current()
+ ) {
+ halt();
+ return undefined;
+ }
+ const relay = sdk.relay(origin);
+ const token = Object.freeze({}) as PrivateAuthConnection;
+ // A private page may already own this actual SDK connection. Its open$
+ // Subject does not replay; initialize from its genuine connected state.
+ if (relay.connected$.value) generation = Symbol();
+ function current() {
+ return (
+ !stopped && !closed && capture.current() && generation !== undefined
+ );
+ }
+ const control: AuthControl = {
+ stopped: () => !current(),
+ challenge() {
+ if (!current() || challenge === undefined || responded)
+ return undefined;
+ const exact = challenge,
+ stamp = generation!;
+ const proof: PrivateAuthChallenge = {
+ owner: capture.owner,
+ session: capture.session,
+ connection: stamp,
+ relay: relay.url,
+ challenge: exact,
+ current: () =>
+ current() && generation === stamp && challenge === exact
+ };
+ proofs.set(proof, true);
+ return proof;
+ },
+ reserve(proof) {
+ if (
+ !proofs.has(proof) ||
+ reservation !== undefined ||
+ !proof.current() ||
+ !current() ||
+ responded ||
+ proof.connection !== generation ||
+ proof.challenge !== challenge ||
+ responses >= PRIVATE_AUTH_BUDGETS.responsesPerConnectionAction
+ )
+ return false;
+ responses++;
+ reservation = proof;
+ sent = false;
+ return true;
+ },
+ async send(proof, approved) {
+ const wire = takeGuardedInboxAuthResponse(approved, proof);
+ const verified = verifyEnvelope(wire);
+ const event = verified.ok
+ ? verifiedEnvelopeSnapshot(verified.value)
+ : undefined;
+ if (
+ !proofs.has(proof) ||
+ reservation !== proof ||
+ sent ||
+ !event ||
+ event.kind !== 22242 ||
+ event.pubkey !== capture.owner ||
+ event.content !== '' ||
+ JSON.stringify(event.tags) !==
+ JSON.stringify([
+ ['relay', relay.url],
+ ['challenge', proof.challenge]
+ ]) ||
+ !proof.current() ||
+ !current() ||
+ proof.connection !== generation ||
+ proof.challenge !== challenge
+ )
+ return 'stopped';
+ try {
+ sent = true;
+ const response = await relay.auth(event);
+ if (!proof.current() || !current()) return 'stopped';
+ if (response.ok) {
+ responded = true;
+ return 'accepted';
+ }
+ const outcome =
+ response.message === 'Timeout' ? 'unknown' : 'refused';
+ halt();
+ return outcome;
+ } catch {
+ halt();
+ return 'unknown';
+ }
+ },
+ close: () => owner.close()
+ };
+ authConnections.set(token, control);
+ const opened = relay.open$.subscribe(() => {
+ if (!stopped && !closed && capture.current()) generation = Symbol();
+ });
+ releases.set(Symbol(), () => opened.unsubscribe());
+ const lost = relay.close$.subscribe(halt);
+ releases.set(Symbol(), () => lost.unsubscribe());
+ const closing = relay.closing$.subscribe(halt);
+ releases.set(Symbol(), () => closing.unsubscribe());
+ const challenges = relay.challenge$.subscribe((next: unknown) => {
+ if (stopped || closed || !capture.current()) {
+ halt();
+ return;
+ }
+ if (next === null) return;
+ if (
+ typeof next !== 'string' ||
+ !next ||
+ !boundedEnvelopeTags([
+ ['relay', relay.url],
+ ['challenge', next]
+ ]) ||
+ !generation
+ ) {
+ halt();
+ return;
+ }
+ if (next === challenge) return;
+ if (
+ responses >= PRIVATE_AUTH_BUDGETS.responsesPerConnectionAction ||
+ (challenge !== undefined && !responded)
+ ) {
+ halt();
+ return;
+ }
+ challenge = next;
+ responded = false;
+ reservation = undefined;
+ });
+ releases.set(Symbol(), () => challenges.unsubscribe());
+ if (closed || stopped || !capture.current()) {
+ cleanup();
+ owner.close();
+ return undefined;
+ }
+ // Official Observable filter input holds the watchTower without emitting
+ // a filter/REQ. Its own CLOSE at teardown is ordinary SDK control cleanup.
+ const hold = relay
+ .req(NEVER, {
+ waitForAuth: false,
+ reconnect: false,
+ resubscribe: false
+ })
+ .subscribe({ error: halt, complete: halt });
+ releases.set(Symbol(), () => hold.unsubscribe());
+ if (closed || stopped || !capture.current()) {
+ cleanup();
+ owner.close();
+ return undefined;
+ }
+ return token;
+ },
subscribe(limit, listener) {
if (closed || !capture.current()) {
owner.close();
@@ -252,6 +502,13 @@ export function getPrivatePool(
} catch {
failed = true;
}
+ for (const cleanup of authCleanup.values()) {
+ try {
+ cleanup();
+ } catch {
+ failed = true;
+ }
+ }
try {
sdk.close();
} catch {
@@ -300,3 +557,39 @@ export function subscribePrivatePage(
export function closePrivatePool(token: PrivatePool): void {
ownerOf(token).close();
}
+export function beginPrivateAuthConnection(
+ pool: PrivatePool,
+ origin: string,
+ admission: InboxAuthAdmission
+): Promise<PrivateAuthConnection | undefined> {
+ return ownerOf(pool).auth(origin, admission);
+}
+export function privateAuthChallenge(
+ connection: PrivateAuthConnection
+): PrivateAuthChallenge | undefined {
+ return authConnections.get(connection)?.challenge();
+}
+export function privateAuthStopped(connection: PrivateAuthConnection): boolean {
+ return authConnections.get(connection)?.stopped() ?? true;
+}
+export function reservePrivateAuthResponse(
+ connection: PrivateAuthConnection,
+ proof: PrivateAuthChallenge
+): boolean {
+ return authConnections.get(connection)?.reserve(proof) ?? false;
+}
+export function sendPrivateAuthResponse(
+ connection: PrivateAuthConnection,
+ proof: PrivateAuthChallenge,
+ response: GuardedInboxAuthResponse
+) {
+ return (
+ authConnections.get(connection)?.send(proof, response) ??
+ Promise.resolve('stopped' as const)
+ );
+}
+export function closePrivateAuthConnection(
+ connection: PrivateAuthConnection
+): void {
+ authConnections.get(connection)?.close();
+}
diff --git a/web/tests/e2e/harness/inbox-auth.ts b/web/tests/e2e/harness/inbox-auth.ts
@@ -0,0 +1,153 @@
+import { makeFixture } from './approved-signing.ts';
+import { fixturePolicy, inbox } from './inbox-setup.ts';
+import {
+ createIdentitySession,
+ connectIdentity,
+ probeIdentityMessaging,
+ disconnectIdentity
+} from '../../../src/lib/runtime/identity-session.ts';
+import {
+ createPrivateSession,
+ closePrivateSession
+} from '../../../src/lib/runtime/private-session.ts';
+import {
+ getPrivatePool,
+ beginPrivateAuthConnection,
+ privateAuthChallenge,
+ reservePrivateAuthResponse,
+ sendPrivateAuthResponse,
+ subscribePrivatePage
+} from '../../../src/lib/nostr/private-pool.ts';
+import { RelayPool } from 'applesauce-relay';
+export {
+ beginInboxAuthentication,
+ respondInboxAuthentication,
+ inboxAuthSnapshot,
+ closeInboxAuthentication
+} from '../../../src/lib/nostr/inbox-auth.ts';
+export {
+ browserExtensionScheduler,
+ extensionSchedulerSnapshot
+} from '../../../src/lib/nostr/extension-scheduler.ts';
+export {
+ getPublicPool,
+ subscribePublicPool,
+ closePublicPool
+} from '../../../src/lib/nostr/public-pool.ts';
+export { inbox, fixturePolicy };
+export async function makeAuthFixture() {
+ const fixture = makeFixture(10050),
+ identity = createIdentitySession();
+ let mode: 'exact' | 'author' | 'relay' | 'challenge' | 'cached' | 'denied' =
+ 'exact',
+ signs = 0,
+ changed = false;
+ let before = () => Promise.resolve();
+ Object.defineProperty(window, 'nostr', {
+ configurable: true,
+ value: {
+ getPublicKey: () =>
+ Promise.resolve(changed ? 'f'.repeat(64) : fixture.owner),
+ signEvent: async (input: Parameters<typeof fixture.sign>[0]) => {
+ signs++;
+ await before();
+ if (mode === 'relay') input.tags[0][1] = 'wss://wrong.example.org/';
+ if (mode === 'challenge') input.tags[1][1] = 'wrong';
+ return fixture.sign(
+ input,
+ mode === 'relay' || mode === 'challenge' ? 'exact' : mode
+ );
+ },
+ nip44: {
+ encrypt: (_peer: string, value: string) =>
+ Promise.resolve('fixture:' + value),
+ decrypt: (_peer: string, value: string) =>
+ Promise.resolve(value.slice(8))
+ }
+ }
+ });
+ await connectIdentity(identity);
+ await probeIdentityMessaging(identity, 'reviewed_self_copy');
+ const session = await createPrivateSession(
+ identity,
+ 'reviewed_private_session'
+ );
+ if (!session) throw new Error('missing genuine private session');
+ const policy = fixturePolicy(),
+ pool = getPrivatePool(session, policy, [inbox]);
+ if (!pool) throw new Error('missing private pool');
+ return {
+ pool,
+ policy,
+ owner: fixture.owner,
+ signs: () => signs,
+ mode: (next: typeof mode) => {
+ mode = next;
+ },
+ beforeSign: (next: typeof before) => {
+ before = next;
+ },
+ changeOwner: () => {
+ changed = true;
+ },
+ logout: () => disconnectIdentity(identity),
+ reopen: () => getPrivatePool(session, policy, [inbox]),
+ startPage: () => subscribePrivatePage(pool, 1, () => {}),
+ async rawPortBypass() {
+ const connection = (await Reflect.apply(
+ beginPrivateAuthConnection,
+ undefined,
+ [pool, inbox]
+ )) as Awaited<ReturnType<typeof beginPrivateAuthConnection>>;
+ if (!connection) return 'blocked';
+ for (let i = 0; i < 100; i++) {
+ const proof = privateAuthChallenge(connection);
+ if (proof) {
+ if (!reservePrivateAuthResponse(connection, proof)) return 'blocked';
+ const event = fixture.sign({
+ kind: 22242,
+ created_at: Math.floor(Date.now() / 1000),
+ tags: [
+ ['relay', proof.relay],
+ ['challenge', proof.challenge]
+ ],
+ content: ''
+ });
+ return (await Reflect.apply(sendPrivateAuthResponse, undefined, [
+ connection,
+ proof,
+ JSON.stringify(event)
+ ])) as string;
+ }
+ await new Promise<void>((resolve) => setTimeout(resolve, 10));
+ }
+ throw new Error('missing real challenge for bypass test');
+ },
+ close: () => {
+ closePrivateSession(session);
+ disconnectIdentity(identity);
+ fixture.close();
+ }
+ };
+}
+export function installCloseFailure() {
+ const original = Reflect.get<RelayPool, 'close'>(
+ RelayPool.prototype,
+ 'close'
+ );
+ let failing = true;
+ RelayPool.prototype.close = function (
+ ...args: Parameters<RelayPool['close']>
+ ) {
+ if (failing) throw new Error('controlled physical cleanup fault');
+ return original.apply(this, args);
+ };
+ return {
+ allow: () => {
+ failing = false;
+ },
+ restore: () => {
+ RelayPool.prototype.close = original;
+ }
+ };
+}
diff --git a/web/tests/e2e/inbox-auth.spec.ts b/web/tests/e2e/inbox-auth.spec.ts
@@ -0,0 +1,470 @@
+import { test, expect } from '@playwright/test';
+import { build } from 'vite';
+import { fileURLToPath } from 'node:url';
+import { once } from 'node:events';
+import { WebSocketServer } from 'ws';
+import { createStaticHarness } from '../integration/harness/static.ts';
+import type * as Fixture from './harness/inbox-auth.ts';
+declare global {
+ interface Window {
+ hcp068: typeof Fixture;
+ hcp068Fixture: Awaited<ReturnType<typeof Fixture.makeAuthFixture>>;
+ hcp068Action: NonNullable<
+ Awaited<ReturnType<typeof Fixture.beginInboxAuthentication>>
+ >;
+ hcp068Run?: Promise<{ status: string }>;
+ hcp068Settle?: () => void;
+ }
+}
+let server: Awaited<ReturnType<typeof createStaticHarness>>,
+ sockets: WebSocketServer,
+ endpoint: string,
+ bundle: string;
+let frames: unknown[][] = [],
+ accept = true,
+ holdPage = false;
+test.beforeAll(async () => {
+ server = await createStaticHarness();
+ sockets = new WebSocketServer({
+ host: '127.0.0.1',
+ port: 0,
+ maxPayload: 65536
+ });
+ await once(sockets, 'listening');
+ const address = sockets.address();
+ if (!address || typeof address === 'string')
+ throw new Error('missing loopback');
+ endpoint = 'ws://127.0.0.1:' + address.port;
+ sockets.on('connection', (socket) => {
+ socket.send(JSON.stringify(['AUTH', 'challenge-one']));
+ socket.on('message', (bytes) => {
+ const raw = Buffer.isBuffer(bytes)
+ ? bytes
+ : Array.isArray(bytes)
+ ? Buffer.concat(bytes)
+ : Buffer.from(bytes);
+ const frame = JSON.parse(raw.toString()) as unknown[];
+ frames.push(frame);
+ if (frame[0] === 'AUTH')
+ socket.send(
+ JSON.stringify([
+ 'OK',
+ (frame[1] as { id: string }).id,
+ accept,
+ accept ? '' : 'blocked: refusal'
+ ])
+ );
+ if (frame[0] === 'REQ' && !holdPage)
+ socket.send(JSON.stringify(['EOSE', frame[1]]));
+ });
+ });
+ const result = await build({
+ configFile: false,
+ logLevel: 'silent',
+ build: {
+ write: false,
+ minify: false,
+ lib: {
+ entry: fileURLToPath(
+ new URL('./harness/inbox-auth.ts', import.meta.url)
+ ),
+ name: 'hcp068',
+ formats: ['iife']
+ }
+ }
+ });
+ const output = Array.isArray(result) ? result[0] : result;
+ if (!('output' in output)) throw new Error('missing bundle');
+ const chunks = output.output.filter((x) => x.type === 'chunk');
+ expect(chunks).toHaveLength(1);
+ bundle = chunks[0].code;
+});
+test.afterAll(async () => {
+ for (const socket of sockets.clients) socket.terminate();
+ await new Promise<void>((resolve) => sockets.close(() => resolve()));
+ await server.close();
+});
+test.beforeEach(async ({ page }) => {
+ frames = [];
+ accept = true;
+ holdPage = false;
+ await page.addInitScript(
+ ({ endpoint }) => {
+ const Native = window.WebSocket;
+ window.WebSocket = class extends Native {
+ constructor(url: string | URL, protocols?: string | string[]) {
+ if (
+ ![
+ 'wss://inbox.example.org/',
+ 'wss://discovery.example.org/'
+ ].includes(String(url))
+ )
+ throw new Error('unexpected fixture destination');
+ super(endpoint, protocols);
+ }
+ };
+ },
+ { endpoint }
+ );
+ await page.goto(server.url + '/search');
+ await page.addScriptTag({ content: bundle });
+ await page.evaluate(async () => {
+ window.hcp068Fixture = await window.hcp068.makeAuthFixture();
+ const action = await window.hcp068.beginInboxAuthentication(
+ window.hcp068Fixture.pool,
+ window.hcp068.inbox,
+ 'reviewed_connection_auth'
+ );
+ if (!action) throw new Error('missing AUTH action');
+ window.hcp068Action = action;
+ });
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.state
+ )
+ )
+ .toBe('challenge');
+});
+test.afterEach(async ({ page }) => {
+ if (!page.isClosed())
+ await page.evaluate(() => {
+ window.hcp068Settle?.();
+ window.hcp068Fixture.close();
+ });
+});
+test('genuine SDK connection waits without REQ or EVENT and exact signed22242 uses AUTH only', async ({
+ page
+}) => {
+ expect(frames).toHaveLength(0);
+ const result = await page.evaluate(async () => ({
+ result: await window.hcp068.respondInboxAuthentication(window.hcp068Action),
+ owner: window.hcp068Fixture.owner,
+ signs: window.hcp068Fixture.signs()
+ }));
+ expect(result.result.status).toBe('accepted');
+ expect(result.signs).toBe(1);
+ expect(frames).toHaveLength(1);
+ expect(frames[0][0]).toBe('AUTH');
+ expect(frames[0][1]).toMatchObject({
+ kind: 22242,
+ pubkey: result.owner,
+ content: '',
+ tags: [
+ ['relay', 'wss://inbox.example.org/'],
+ ['challenge', 'challenge-one']
+ ]
+ });
+});
+for (const mode of [
+ 'relay',
+ 'challenge',
+ 'author',
+ 'cached',
+ 'denied'
+] as const)
+ test(`actual provider ${mode} response never reaches AUTH`, async ({
+ page
+ }) => {
+ const result = await page.evaluate(async (mode) => {
+ window.hcp068Fixture.mode(mode);
+ return window.hcp068.respondInboxAuthentication(window.hcp068Action);
+ }, mode);
+ expect(result.status).not.toBe('accepted');
+ expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(0);
+ });
+test('real refusal pauses without retry', async ({ page }) => {
+ accept = false;
+ expect(
+ await page.evaluate(() =>
+ window.hcp068.respondInboxAuthentication(window.hcp068Action)
+ )
+ ).toEqual({ status: 'refused' });
+ await page.evaluate(() =>
+ window.hcp068.respondInboxAuthentication(window.hcp068Action)
+ );
+ expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(1);
+});
+test('two genuine changing challenges admit two responses and the third closes the scope', async ({
+ page
+}) => {
+ await page.evaluate(() =>
+ window.hcp068.respondInboxAuthentication(window.hcp068Action)
+ );
+ for (const socket of sockets.clients)
+ socket.send(JSON.stringify(['AUTH', 'challenge-two']));
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.state
+ )
+ )
+ .toBe('challenge');
+ await page.evaluate(() =>
+ window.hcp068.respondInboxAuthentication(window.hcp068Action)
+ );
+ for (const socket of sockets.clients)
+ socket.send(JSON.stringify(['AUTH', 'challenge-three']));
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.state
+ )
+ )
+ .toBe('stopped');
+ await page.evaluate(() =>
+ window.hcp068.respondInboxAuthentication(window.hcp068Action)
+ );
+ expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(2);
+ expect(await page.evaluate(() => window.hcp068Fixture.signs())).toBe(2);
+});
+for (const stop of ['stop', 'logout', 'socket'] as const)
+ test(`actual pending signer retains shared slot through ${stop} and cannot send late AUTH`, async ({
+ page
+ }) => {
+ await page.evaluate(() => {
+ window.hcp068Fixture.beforeSign(
+ () =>
+ new Promise<void>((resolve) => {
+ window.hcp068Settle = resolve;
+ })
+ );
+ window.hcp068Run = window.hcp068.respondInboxAuthentication(
+ window.hcp068Action
+ );
+ });
+ await expect
+ .poll(() => page.evaluate(() => window.hcp068Fixture.signs()))
+ .toBe(1);
+ if (stop === 'socket') for (const socket of sockets.clients) socket.close();
+ else
+ await page.evaluate((stop) => {
+ if (stop === 'logout') window.hcp068Fixture.logout();
+ else window.hcp068.closeInboxAuthentication(window.hcp068Action);
+ }, stop);
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.state
+ )
+ )
+ .toBe('stopped');
+ expect(
+ await page.evaluate(
+ () =>
+ window.hcp068.extensionSchedulerSnapshot(
+ window.hcp068.browserExtensionScheduler()!
+ ).state
+ )
+ ).toBe('active');
+ const result = await page.evaluate(async () => {
+ window.hcp068Settle!();
+ return window.hcp068Run;
+ });
+ expect(result?.status).not.toBe('accepted');
+ expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(0);
+ expect(
+ await page.evaluate(
+ () =>
+ window.hcp068.extensionSchedulerSnapshot(
+ window.hcp068.browserExtensionScheduler()!
+ ).state
+ )
+ ).toBe('idle');
+ });
+test('unsolicited public challenges never sign and public reads survive private Stop', async ({
+ page
+}) => {
+ const result = await page.evaluate(async () => {
+ const s = window.hcp068,
+ f = window.hcp068Fixture;
+ s.closeInboxAuthentication(window.hcp068Action);
+ const pool = s.getPublicPool(f.policy)!;
+ let release = () => {};
+ await new Promise<void>((resolve) => {
+ release = s.subscribePublicPool(
+ pool,
+ [{ kinds: [30402], limit: 1 }],
+ (message) => {
+ if (message.type === 'EOSE') resolve();
+ }
+ );
+ });
+ release();
+ s.closePublicPool(pool);
+ return f.signs();
+ });
+ expect(result).toBe(0);
+ expect(frames.some((x) => x[0] === 'REQ')).toBe(true);
+ expect(frames.some((x) => x[0] === 'AUTH' || x[0] === 'EVENT')).toBe(false);
+});
+test('replacement during an outstanding SDK signer stops without rebinding the response', async ({
+ page
+}) => {
+ await page.evaluate(() => {
+ window.hcp068Fixture.beforeSign(
+ () =>
+ new Promise<void>((resolve) => {
+ window.hcp068Settle = resolve;
+ })
+ );
+ window.hcp068Run = window.hcp068.respondInboxAuthentication(
+ window.hcp068Action
+ );
+ });
+ await expect
+ .poll(() => page.evaluate(() => window.hcp068Fixture.signs()))
+ .toBe(1);
+ for (const socket of sockets.clients)
+ socket.send(JSON.stringify(['AUTH', 'replacement']));
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.state
+ )
+ )
+ .toBe('stopped');
+ const result = await page.evaluate(async () => {
+ window.hcp068Settle!();
+ return window.hcp068Run;
+ });
+ expect(result?.status).not.toBe('accepted');
+ expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(0);
+});
+test('fresh SDK owner mismatch stops before the signer', async ({ page }) => {
+ const result = await page.evaluate(async () => {
+ window.hcp068Fixture.changeOwner();
+ const result = await window.hcp068.respondInboxAuthentication(
+ window.hcp068Action
+ );
+ return { result, signs: window.hcp068Fixture.signs() };
+ });
+ expect(result.result.status).not.toBe('accepted');
+ expect(result.signs).toBe(0);
+ expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(0);
+});
+test('oversized genuine challenge stops bounded post-parse work without prompting', async ({
+ page
+}) => {
+ for (const socket of sockets.clients)
+ socket.send(JSON.stringify(['AUTH', 'x'.repeat(4097)]));
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.state
+ )
+ )
+ .toBe('stopped');
+ expect(await page.evaluate(() => window.hcp068Fixture.signs())).toBe(0);
+});
+test('new physical connection and explicit action do not inherit accepted scope', async ({
+ page
+}) => {
+ await page.evaluate(() =>
+ window.hcp068.respondInboxAuthentication(window.hcp068Action)
+ );
+ await page.evaluate(async () => {
+ window.hcp068Fixture.close();
+ window.hcp068Fixture = await window.hcp068.makeAuthFixture();
+ const action = await window.hcp068.beginInboxAuthentication(
+ window.hcp068Fixture.pool,
+ window.hcp068.inbox,
+ 'reviewed_connection_auth'
+ );
+ if (!action) throw new Error('missing fresh action');
+ window.hcp068Action = action;
+ });
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.state
+ )
+ )
+ .toBe('challenge');
+ expect(
+ await page.evaluate(
+ () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.responses
+ )
+ ).toBe(0);
+ await page.evaluate(() =>
+ window.hcp068.respondInboxAuthentication(window.hcp068Action)
+ );
+ expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(2);
+ expect(await page.evaluate(() => window.hcp068Fixture.signs())).toBe(1);
+});
+test('failed physical close retains unavailable ownership until the same cleanup retries', async ({
+ page
+}) => {
+ const result = await page.evaluate(() => {
+ const s = window.hcp068,
+ fault = s.installCloseFailure();
+ let closeFailed = false,
+ reopenFailed = false;
+ try {
+ try {
+ s.closeInboxAuthentication(window.hcp068Action);
+ } catch {
+ closeFailed = true;
+ }
+ try {
+ window.hcp068Fixture.reopen();
+ } catch {
+ reopenFailed = true;
+ }
+ fault.allow();
+ s.closeInboxAuthentication(window.hcp068Action);
+ return { closeFailed, reopenFailed, signs: window.hcp068Fixture.signs() };
+ } finally {
+ fault.restore();
+ }
+ });
+ expect(result).toEqual({ closeFailed: true, reopenFailed: true, signs: 0 });
+});
+test('raw private AUTH ports cannot bypass explicit review and guarded signing', async ({
+ page
+}) => {
+ const status = await page.evaluate(async () => {
+ window.hcp068Fixture.close();
+ window.hcp068Fixture = await window.hcp068.makeAuthFixture();
+ return window.hcp068Fixture.rawPortBypass();
+ });
+ expect(status).not.toBe('accepted');
+ expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(0);
+});
+test('late extension owner change during signing prevents the AUTH effect', async ({
+ page
+}) => {
+ const result = await page.evaluate(async () => {
+ window.hcp068Fixture.beforeSign(() => {
+ window.hcp068Fixture.changeOwner();
+ return Promise.resolve();
+ });
+ return window.hcp068.respondInboxAuthentication(window.hcp068Action);
+ });
+ expect(result.status).not.toBe('accepted');
+ expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(0);
+});
+test('reviewed AUTH uses the same genuine already-open private page connection', async ({
+ page
+}) => {
+ holdPage = true;
+ await page.evaluate(async () => {
+ window.hcp068Fixture.close();
+ window.hcp068Fixture = await window.hcp068.makeAuthFixture();
+ window.hcp068Fixture.startPage();
+ });
+ await expect.poll(() => frames.filter((x) => x[0] === 'REQ').length).toBe(1);
+ const result = await page.evaluate(async () => {
+ const action = await window.hcp068.beginInboxAuthentication(
+ window.hcp068Fixture.pool,
+ window.hcp068.inbox,
+ 'reviewed_connection_auth'
+ );
+ if (!action) return { status: 'missing' };
+ window.hcp068Action = action;
+ return window.hcp068.respondInboxAuthentication(action);
+ });
+ expect(result.status).toBe('accepted');
+ expect(frames.filter((x) => x[0] === 'REQ')).toHaveLength(1);
+ expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(1);
+});
diff --git a/web/tests/integration/inbox-auth.test.ts b/web/tests/integration/inbox-auth.test.ts
@@ -0,0 +1,20 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ beginInboxAuthentication,
+ respondInboxAuthentication
+} from '../../src/lib/nostr/inbox-auth.ts';
+void test('SSR AUTH admits no private connection, extension or forged action', async () => {
+ assert.equal(typeof window, 'undefined');
+ assert.equal(
+ await beginInboxAuthentication(
+ {} as never,
+ 'wss://inbox.example.org',
+ 'reviewed_connection_auth'
+ ),
+ undefined
+ );
+ assert.deepEqual(await respondInboxAuthentication({} as never), {
+ status: 'invalid'
+ });
+});
diff --git a/web/tests/unit/inbox-auth.test.ts b/web/tests/unit/inbox-auth.test.ts
@@ -0,0 +1,20 @@
+import { describe, it, expect } from 'vitest';
+import { PRIVATE_AUTH_BUDGETS } from '../../src/lib/config/budgets.ts';
+import {
+ inboxAuthSnapshot,
+ respondInboxAuthentication,
+ closeInboxAuthentication
+} from '../../src/lib/nostr/inbox-auth.ts';
+describe('connection AUTH admission', () => {
+ it('retains the exact two-response authority', () => {
+ expect(PRIVATE_AUTH_BUDGETS.responsesPerConnectionAction).toBe(2);
+ });
+ it('forged actions never become signer or transport authority', async () => {
+ const forged = {} as never;
+ expect(inboxAuthSnapshot(forged)).toBeUndefined();
+ expect(await respondInboxAuthentication(forged)).toEqual({
+ status: 'invalid'
+ });
+ expect(() => closeInboxAuthentication(forged)).not.toThrow();
+ });
+});