commit a7f9a61c7ea54fe8ee60f0e8100dbfbaa4f32f20
parent 4622502fd189a6f21f6ec5031aa0973ab70cb087
Author: triesap <tyson@radroots.org>
Date: Wed, 7 Oct 2026 12:13:14 +0000
test: qualify the inbox policy using loopback protocol fixtures (HCP-069)
- Verify AUTH independently from disposable gift-wrap authors in a test-only relay policy.
- Exercise actual SDK recipient reads, sender archive and backdated encrypted wraps.
- Reject anonymous or wrong-recipient reads and surface incompatible author policy.
- Preserve disabled production inboxes and separate real operator qualification.
Diffstat:
4 files changed, 643 insertions(+), 0 deletions(-)
diff --git a/web/tests/e2e/harness/inbox-policy.ts b/web/tests/e2e/harness/inbox-policy.ts
@@ -0,0 +1,131 @@
+import { Relay } from 'applesauce-relay';
+import { PrivateKeySigner } from 'applesauce-signers';
+import { getEventHash, type NostrEvent } from 'applesauce-core/helpers';
+import { NEVER, firstValueFrom, filter, take, toArray } from 'rxjs';
+
+// Test-owned actual SDK cryptography/transport, never a product signer or relay.
+const url = 'wss://inbox.example.org/';
+export async function makePolicyFixture() {
+ const sender = new PrivateKeySigner(),
+ recipient = new PrivateKeySigner();
+ const owner = await sender.getPublicKey(),
+ peer = await recipient.getPublicKey();
+ const now = Math.floor(Date.now() / 1000);
+ const rumorFields = {
+ kind: 14,
+ pubkey: owner,
+ created_at: now,
+ tags: [['p', peer]],
+ content: 'loopback policy fixture'
+ };
+ const rumor = { ...rumorFields, id: getEventHash(rumorFields) };
+ async function wrap(destination: string) {
+ const seal = await sender.signEvent({
+ kind: 13,
+ created_at: now - 300,
+ tags: [],
+ content: await sender.nip44.encrypt(destination, JSON.stringify(rumor))
+ });
+ const disposable = new PrivateKeySigner();
+ try {
+ return await disposable.signEvent({
+ kind: 1059,
+ created_at: now - 48 * 3600 - 300,
+ tags: [['p', destination]],
+ content: await disposable.nip44.encrypt(
+ destination,
+ JSON.stringify(seal)
+ )
+ });
+ } finally {
+ disposable.key.fill(0);
+ }
+ }
+ const wraps = { recipient: await wrap(peer), archive: await wrap(owner) };
+ async function client(signer: PrivateKeySigner, authenticate: boolean) {
+ const relay = new Relay(url, {
+ keepAlive: 0,
+ enablePing: false,
+ requestReconnect: 0,
+ publishRetry: { count: 0 }
+ });
+ const hold = relay
+ .req(NEVER, { waitForAuth: false, reconnect: false, resubscribe: false })
+ .subscribe();
+ const challenge = await firstValueFrom(
+ relay.challenge$.pipe(
+ filter((v): v is string => typeof v === 'string'),
+ take(1)
+ )
+ );
+ if (authenticate) {
+ const event = await signer.signEvent({
+ kind: 22242,
+ created_at: now,
+ tags: [
+ ['relay', url],
+ ['challenge', challenge]
+ ],
+ content: ''
+ });
+ const result = await relay.auth(event);
+ if (!result.ok) throw new Error('fixture AUTH refused');
+ }
+ return {
+ relay,
+ close() {
+ hold.unsubscribe();
+ relay.close();
+ }
+ };
+ }
+ const clients: Awaited<ReturnType<typeof client>>[] = [];
+ async function connect(which: 'sender' | 'recipient', authenticate = true) {
+ const c = await client(
+ which === 'sender' ? sender : recipient,
+ authenticate
+ );
+ clients.push(c);
+ return c;
+ }
+ async function read(c: Awaited<ReturnType<typeof client>>, target: string) {
+ try {
+ const events = await firstValueFrom(
+ c.relay
+ .request(
+ { kinds: [1059], '#p': [target], limit: 200 },
+ {
+ waitForAuth: false,
+ reconnect: false,
+ resubscribe: false,
+ timeout: 2000
+ }
+ )
+ .pipe(toArray())
+ );
+ return { status: 'complete', ids: events.map((e) => e.id) };
+ } catch {
+ return { status: 'refused', ids: [] };
+ }
+ }
+ async function write(
+ c: Awaited<ReturnType<typeof client>>,
+ event: NostrEvent
+ ) {
+ const result = await firstValueFrom(c.relay.event(event, 'EVENT'));
+ return { accepted: result.ok };
+ }
+ return {
+ owner,
+ peer,
+ wraps,
+ connect,
+ read,
+ write,
+ close() {
+ for (const c of clients) c.close();
+ sender.key.fill(0);
+ recipient.key.fill(0);
+ }
+ };
+}
diff --git a/web/tests/e2e/inbox-policy.spec.ts b/web/tests/e2e/inbox-policy.spec.ts
@@ -0,0 +1,209 @@
+import { test, expect } from '@playwright/test';
+import { build } from 'vite';
+import { fileURLToPath } from 'node:url';
+import { once } from 'node:events';
+import { WebSocketServer, WebSocket } from 'ws';
+import { createStaticHarness } from '../integration/harness/static.ts';
+import { createInboxPolicy } from '../integration/harness/inbox-policy.ts';
+import type * as Fixture from './harness/inbox-policy.ts';
+declare global {
+ interface Window {
+ hcp069: typeof Fixture;
+ hcp069Fixture: Awaited<ReturnType<typeof Fixture.makePolicyFixture>>;
+ }
+}
+let server: Awaited<ReturnType<typeof createStaticHarness>>,
+ sockets: WebSocketServer,
+ endpoint: string,
+ bundle: string;
+let policy: ReturnType<typeof createInboxPolicy>;
+let verbs: string[] = [];
+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) => {
+ const connection = policy.connect('loopback-challenge');
+ socket.send(JSON.stringify(['AUTH', 'loopback-challenge']));
+ socket.on('message', (bytes) => {
+ const raw = Buffer.isBuffer(bytes)
+ ? bytes
+ : Array.isArray(bytes)
+ ? Buffer.concat(bytes)
+ : Buffer.from(bytes);
+ const text = raw.toString();
+ try {
+ const frame: unknown = JSON.parse(text);
+ if (Array.isArray(frame) && typeof frame[0] === 'string')
+ verbs.push(frame[0]);
+ } catch {
+ // Malformed fixture peers still reach the bounded policy NOTICE below.
+ }
+ for (const response of connection.frame(text))
+ socket.send(JSON.stringify(response));
+ });
+ socket.on('close', () => connection.close());
+ });
+ const result = await build({
+ configFile: false,
+ logLevel: 'silent',
+ build: {
+ write: false,
+ minify: false,
+ lib: {
+ entry: fileURLToPath(
+ new URL('./harness/inbox-policy.ts', import.meta.url)
+ ),
+ name: 'hcp069',
+ 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 }) => {
+ policy = createInboxPolicy({
+ now: Math.floor(Date.now() / 1000),
+ retentionSeconds: 30 * 86400
+ });
+ verbs = [];
+ await page.addInitScript(
+ ({ endpoint }) => {
+ const Native = window.WebSocket;
+ window.WebSocket = class extends Native {
+ constructor(url: string | URL, protocols?: string | string[]) {
+ if (String(url) !== 'wss://inbox.example.org/')
+ 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.hcp069Fixture = await window.hcp069.makePolicyFixture();
+ });
+});
+test.afterEach(async ({ page }) => {
+ if (!page.isClosed()) await page.evaluate(() => window.hcp069Fixture.close());
+});
+test('actual SDK accepts separately signed recipient/self wraps and recipient-only backdated reads', async ({
+ page
+}) => {
+ const result = await page.evaluate(async () => {
+ const f = window.hcp069Fixture,
+ sender = await f.connect('sender'),
+ recipient = await f.connect('recipient');
+ return {
+ owner: f.owner,
+ peer: f.peer,
+ wraps: f.wraps,
+ toPeer: await f.write(sender, f.wraps.recipient),
+ toSelf: await f.write(sender, f.wraps.archive),
+ wrong: await f.read(sender, f.peer),
+ archive: await f.read(sender, f.owner),
+ inbox: await f.read(recipient, f.peer)
+ };
+ });
+ expect(result.wraps.recipient.pubkey).not.toBe(result.owner);
+ expect(result.wraps.archive.pubkey).not.toBe(result.owner);
+ expect(result.wraps.archive.pubkey).not.toBe(result.wraps.recipient.pubkey);
+ expect(result.toPeer.accepted).toBe(true);
+ expect(result.toSelf.accepted).toBe(true);
+ expect(result.wrong.status).toBe('refused');
+ expect(result.wrong.ids).toEqual([]);
+ expect(result.archive.ids).toEqual([result.wraps.archive.id]);
+ expect(result.inbox.ids).toEqual([result.wraps.recipient.id]);
+ expect(result.wraps.recipient.created_at).toBeLessThanOrEqual(
+ Math.floor(Date.now() / 1000) - 48 * 3600 - 300
+ );
+ expect(policy.size()).toBe(2);
+ expect(verbs.filter((v) => v === 'AUTH')).toHaveLength(2);
+ expect(verbs.filter((v) => v === 'EVENT')).toHaveLength(2);
+});
+test('anonymous p-target request is refused rather than an empty successful inbox', async ({
+ page
+}) => {
+ const result = await page.evaluate(async () => {
+ const f = window.hcp069Fixture,
+ c = await f.connect('recipient', false);
+ return f.read(c, f.peer);
+ });
+ expect(result).toEqual({ status: 'refused', ids: [] });
+ expect(verbs.filter((v) => v === 'AUTH')).toHaveLength(0);
+ expect(verbs.filter((v) => v === 'REQ')).toHaveLength(1);
+});
+test('actual SDK surfaces incompatible outer-author write policy with no alternate publication', async ({
+ page
+}) => {
+ policy = createInboxPolicy({
+ now: Math.floor(Date.now() / 1000),
+ retentionSeconds: 30 * 86400,
+ requireOuterAuthor: true
+ });
+ const result = await page.evaluate(async () => {
+ const f = window.hcp069Fixture,
+ c = await f.connect('sender');
+ return f.write(c, f.wraps.recipient);
+ });
+ expect(result.accepted).toBe(false);
+ expect(policy.size()).toBe(0);
+ expect(verbs.filter((v) => v === 'EVENT')).toHaveLength(1);
+});
+
+test('malformed loopback peer frame is isolated before a normal SDK write', async ({
+ page
+}) => {
+ const peer = new WebSocket(endpoint);
+ try {
+ await once(peer, 'open');
+ const reply = new Promise<unknown>((resolve, reject) => {
+ const timer = setTimeout(
+ () => reject(new Error('fixture NOTICE missing')),
+ 2000
+ );
+ peer.on('message', (bytes) => {
+ const raw = Buffer.isBuffer(bytes)
+ ? bytes
+ : Array.isArray(bytes)
+ ? Buffer.concat(bytes)
+ : Buffer.from(bytes);
+ const value: unknown = JSON.parse(raw.toString());
+ if (Array.isArray(value) && value[0] === 'NOTICE') {
+ clearTimeout(timer);
+ resolve(value);
+ }
+ });
+ });
+ peer.send('{');
+ expect(await reply).toEqual(['NOTICE', 'invalid: fixture frame']);
+ } finally {
+ peer.terminate();
+ }
+ const result = await page.evaluate(async () => {
+ const f = window.hcp069Fixture,
+ c = await f.connect('sender');
+ return f.write(c, f.wraps.recipient);
+ });
+ expect(result.accepted).toBe(true);
+ expect(policy.size()).toBe(1);
+});
diff --git a/web/tests/integration/harness/inbox-policy.ts b/web/tests/integration/harness/inbox-policy.ts
@@ -0,0 +1,168 @@
+import {
+ verifyEnvelope,
+ verifiedEnvelopeSnapshot
+} from '../../../src/lib/nostr/verified-envelope.ts';
+import {
+ PRIVATE_AUTH_BUDGETS,
+ PRIVATE_TRANSPORT_BUDGETS
+} from '../../../src/lib/config/budgets.ts';
+import type { NostrEvent } from 'applesauce-core/helpers';
+
+export const fixtureRelay = 'wss://inbox.example.org/';
+// Expected-policy loopback model, never a deployment/operator/retention claim.
+// Clock and declared retention are explicit test inputs. Genuine SDK signatures
+// are verified afresh across JSON; the relay cannot inspect encrypted senders.
+export function createInboxPolicy(options: {
+ now: number;
+ retentionSeconds: number;
+ requireOuterAuthor?: boolean;
+}) {
+ if (
+ !Number.isSafeInteger(options.now) ||
+ options.now < 0 ||
+ !Number.isSafeInteger(options.retentionSeconds) ||
+ options.retentionSeconds < 48 * 3600 + 300
+ )
+ throw new Error('invalid fixture policy');
+ const events = new Map<string, NostrEvent>();
+ let bytes = 0;
+ function event(value: unknown): NostrEvent | undefined {
+ const wire = JSON.stringify(value);
+ if (
+ typeof wire !== 'string' ||
+ new TextEncoder().encode(wire).length >
+ PRIVATE_TRANSPORT_BUDGETS.envelopeBytes
+ )
+ return undefined;
+ const verified = verifyEnvelope(wire);
+ return verified.ok ? verifiedEnvelopeSnapshot(verified.value) : undefined;
+ }
+ return {
+ size: () => events.size,
+ connect(challenge: string) {
+ let owner: string | undefined,
+ closed = false,
+ responses = 0;
+ return {
+ close() {
+ closed = true;
+ owner = undefined;
+ },
+ frame(raw: string): unknown[][] {
+ if (closed) return [['NOTICE', 'closed: fixture connection']];
+ let frame: unknown;
+ try {
+ if (new TextEncoder().encode(raw).length > 65536)
+ throw new Error('fixture frame too large');
+ frame = JSON.parse(raw);
+ } catch {
+ return [['NOTICE', 'invalid: fixture frame']];
+ }
+ if (!Array.isArray(frame))
+ return [['NOTICE', 'invalid: fixture frame']];
+ if (frame[0] === 'AUTH' || frame[0] === 'EVENT') {
+ const e = event(frame[1]),
+ id = e?.id ?? '';
+ if (frame.length !== 2)
+ return [['OK', id, false, 'invalid: fixture envelope']];
+ if (frame[0] === 'AUTH') {
+ owner = undefined;
+ responses++;
+ if (
+ !e ||
+ responses > PRIVATE_AUTH_BUDGETS.responsesPerConnectionAction ||
+ e.kind !== 22242 ||
+ e.content !== '' ||
+ e.tags.length !== 2 ||
+ !e.tags.some(
+ (t) =>
+ t.length === 2 && t[0] === 'relay' && t[1] === fixtureRelay
+ ) ||
+ !e.tags.some(
+ (t) =>
+ t.length === 2 && t[0] === 'challenge' && t[1] === challenge
+ )
+ )
+ return [['OK', id, false, 'restricted: invalid AUTH']];
+ owner = e.pubkey;
+ return [['OK', id, true, '']];
+ }
+ if (!owner)
+ return [['OK', id, false, 'auth-required: fixture inbox']];
+ if (
+ !e ||
+ e.kind !== 1059 ||
+ e.content.length === 0 ||
+ e.tags.length !== 1 ||
+ e.tags[0].length !== 2 ||
+ e.tags[0][0] !== 'p' ||
+ !/^[0-9a-f]{64}$/u.test(e.tags[0][1]) ||
+ e.created_at < options.now - options.retentionSeconds ||
+ e.created_at > options.now + 300 ||
+ (options.requireOuterAuthor && e.pubkey !== owner)
+ )
+ return [
+ ['OK', id, false, 'restricted: unsupported outer envelope']
+ ];
+ if (events.has(e.id)) return [['OK', id, true, '']];
+ const size = new TextEncoder().encode(JSON.stringify(e)).length;
+ if (
+ events.size >= PRIVATE_TRANSPORT_BUDGETS.deliveries ||
+ bytes + size > PRIVATE_TRANSPORT_BUDGETS.processedBytes
+ )
+ return [['OK', id, false, 'restricted: fixture capacity']];
+ events.set(e.id, e);
+ bytes += size;
+ return [['OK', id, true, '']];
+ }
+ if (frame[0] === 'CLOSE') return [];
+ if (
+ frame[0] !== 'REQ' ||
+ typeof frame[1] !== 'string' ||
+ frame[1].length > 64
+ )
+ return [['NOTICE', 'invalid: fixture request']];
+ const id = frame[1],
+ query: unknown = frame[2];
+ if (!owner) return [['CLOSED', id, 'auth-required: fixture inbox']];
+ if (
+ frame.length !== 3 ||
+ !query ||
+ typeof query !== 'object' ||
+ Array.isArray(query)
+ )
+ return [['CLOSED', id, 'restricted: recipient-only']];
+ const q = query as Record<string, unknown>;
+ if (
+ Object.keys(q).length !== 3 ||
+ !Array.isArray(q.kinds) ||
+ q.kinds.length !== 1 ||
+ q.kinds[0] !== 1059 ||
+ !Array.isArray(q['#p']) ||
+ q['#p'].length !== 1 ||
+ q['#p'][0] !== owner ||
+ typeof q.limit !== 'number' ||
+ !Number.isSafeInteger(q.limit) ||
+ q.limit < 1 ||
+ q.limit > PRIVATE_TRANSPORT_BUDGETS.requestedPerRelay
+ )
+ return [['CLOSED', id, 'restricted: recipient-only']];
+ const rows = [...events.values()]
+ .filter((e) => e.tags[0][1] === owner)
+ .sort(
+ (a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id)
+ )
+ .slice(0, q.limit);
+ return [
+ ...rows.map((e) => [
+ 'EVENT',
+ id,
+ JSON.parse(JSON.stringify(e)) as unknown
+ ]),
+ ['EOSE', id]
+ ];
+ }
+ };
+ }
+ };
+}
diff --git a/web/tests/integration/inbox-policy.test.ts b/web/tests/integration/inbox-policy.test.ts
@@ -0,0 +1,135 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { PrivateKeySigner } from 'applesauce-signers';
+import { createInboxPolicy, fixtureRelay } from './harness/inbox-policy.ts';
+
+const now = 1800000000;
+async function inputs() {
+ const owner = new PrivateKeySigner(),
+ outer = new PrivateKeySigner(),
+ peer = new PrivateKeySigner();
+ const author = await owner.getPublicKey(),
+ recipient = await peer.getPublicKey();
+ const auth = await owner.signEvent({
+ kind: 22242,
+ created_at: now,
+ tags: [
+ ['relay', fixtureRelay],
+ ['challenge', 'challenge']
+ ],
+ content: ''
+ });
+ const wrap = await outer.signEvent({
+ kind: 1059,
+ created_at: now - 48 * 3600 - 300,
+ tags: [['p', recipient]],
+ content: 'opaque policy fixture ciphertext'
+ });
+ return {
+ owner,
+ outer,
+ peer,
+ author,
+ recipient,
+ auth,
+ wrap,
+ close() {
+ owner.key.fill(0);
+ outer.key.fill(0);
+ peer.key.fill(0);
+ }
+ };
+}
+void test('expected policy independently verifies AUTH and disposable outer author', async () => {
+ const x = await inputs();
+ try {
+ const policy = createInboxPolicy({ now, retentionSeconds: 30 * 86400 }),
+ connection = policy.connect('challenge');
+ assert.deepEqual(connection.frame(JSON.stringify(['AUTH', x.auth])), [
+ ['OK', x.auth.id, true, '']
+ ]);
+ assert.notEqual(x.wrap.pubkey, x.author);
+ assert.deepEqual(connection.frame(JSON.stringify(['EVENT', x.wrap])), [
+ ['OK', x.wrap.id, true, '']
+ ]);
+ assert.equal(policy.size(), 1);
+ assert.deepEqual(
+ connection.frame(
+ JSON.stringify([
+ 'REQ',
+ 'wrong',
+ { kinds: [1059], '#p': [x.recipient], limit: 200 }
+ ])
+ ),
+ [['CLOSED', 'wrong', 'restricted: recipient-only']]
+ );
+ connection.close();
+ assert.deepEqual(connection.frame(JSON.stringify(['EVENT', x.wrap])), [
+ ['NOTICE', 'closed: fixture connection']
+ ]);
+ } finally {
+ x.close();
+ }
+});
+void test('invalid signature, wrong AUTH binding and plaintext kinds fail closed without admission', async () => {
+ const x = await inputs();
+ try {
+ const policy = createInboxPolicy({ now, retentionSeconds: 30 * 86400 }),
+ c = policy.connect('challenge');
+ assert.equal(
+ c.frame(
+ JSON.stringify(['AUTH', { ...x.auth, sig: '0'.repeat(128) }])
+ )[0][2],
+ false
+ );
+ const wrong = await x.owner.signEvent({
+ ...x.auth,
+ tags: [
+ ['relay', 'wss://wrong.example.org/'],
+ ['challenge', 'challenge']
+ ]
+ });
+ assert.equal(c.frame(JSON.stringify(['AUTH', wrong]))[0][2], false);
+ assert.equal(c.frame(JSON.stringify(['EVENT', x.wrap]))[0][2], false);
+ const fresh = policy.connect('challenge');
+ fresh.frame(JSON.stringify(['AUTH', x.auth]));
+ for (const kind of [13, 14]) {
+ const plaintext = await x.owner.signEvent({
+ kind,
+ created_at: now,
+ tags: [],
+ content: 'unsupported plaintext fixture'
+ });
+ assert.equal(
+ fresh.frame(JSON.stringify(['EVENT', plaintext]))[0][2],
+ false
+ );
+ }
+ assert.equal(
+ fresh.frame(
+ JSON.stringify(['EVENT', { ...x.wrap, sig: '0'.repeat(128) }])
+ )[0][2],
+ false
+ );
+ assert.deepEqual(fresh.frame('{'), [['NOTICE', 'invalid: fixture frame']]);
+ assert.equal(policy.size(), 0);
+ } finally {
+ x.close();
+ }
+});
+void test('modeled restrictive author policy exposes disposable-wrap refusal', async () => {
+ const x = await inputs();
+ try {
+ const p = createInboxPolicy({
+ now,
+ retentionSeconds: 30 * 86400,
+ requireOuterAuthor: true
+ }),
+ c = p.connect('challenge');
+ c.frame(JSON.stringify(['AUTH', x.auth]));
+ assert.equal(c.frame(JSON.stringify(['EVENT', x.wrap]))[0][2], false);
+ assert.equal(p.size(), 0);
+ } finally {
+ x.close();
+ }
+});