app

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

commit bc6ef3a082d9c7a10bd022116382a55b393c83ed
parent 769125b310c4d4fc3b796d2b2ec6f9f6ed36c2b1
Author: triesap <tyson@radroots.org>
Date:   Tue,  6 Oct 2026 07:00:31 +0000

web: Validate public and private relay policy manifests (HCP-027)

- Admit bounded public JSON into an immutable relay policy owner.
- Cap separate roles and reject unsafe origins and unknown configuration.
- Intersect inbox preferences and preserve separate deployment effect flags.
- Fail launch preparation when actual production relay inputs are missing.

Diffstat:
Mweb/package.json | 3++-
Aweb/src/lib/config/budgets.ts | 3+++
Aweb/src/lib/config/deployment-relays.ts | 18++++++++++++++++++
Aweb/src/lib/config/relays.ts | 259+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/relay-config.test.ts | 293+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tools/check-launch-relays.mjs | 12++++++++++++
6 files changed, 587 insertions(+), 1 deletion(-)

diff --git a/web/package.json b/web/package.json @@ -18,7 +18,8 @@ "test:conformance": "corepack pnpm build && node --test tests/conformance/*.test.ts", "test:integration": "corepack pnpm build && node --test --test-timeout=10000 tests/integration/*.test.ts", "test:e2e": "corepack pnpm build && playwright test", - "test:conformance:oracle": "node tools/check-food-interop.mjs" + "test:conformance:oracle": "node tools/check-food-interop.mjs", + "check:launch-relays": "node tools/check-source.mjs && node tools/check-launch-relays.mjs" }, "dependencies": { "@noble/curves": "1.2.0", diff --git a/web/src/lib/config/budgets.ts b/web/src/lib/config/budgets.ts @@ -0,0 +1,3 @@ +// Browser relay scopes are independent; these are application admission caps, +// not a DNS policy, native transport limit or browser memory guarantee. +export const RELAY_BUDGETS = Object.freeze({ public: 3, inbox: 3 }); diff --git a/web/src/lib/config/deployment-relays.ts b/web/src/lib/config/deployment-relays.ts @@ -0,0 +1,18 @@ +import { validateRelayPolicy } from './relays.ts'; + +// No production endpoints/operators have been approved. Keep source development +// possible without guessing egress; the explicit launch-input command rejects +// these empty sets. Operation consumers must enforce the two separate flags. +const policy = validateRelayPolicy( + JSON.stringify({ + schemaVersion: 1, + public: [], + inbox: [], + postingEnabled: false, + messagingEnabled: false, + operatorDenylist: [] + }) +); +if (!policy) throw new Error('relay_policy_invalid'); + +export const deploymentRelayPolicy = policy; diff --git a/web/src/lib/config/relays.ts b/web/src/lib/config/relays.ts @@ -0,0 +1,259 @@ +import { canonicalPublicKey } from '../contracts/public-key.ts'; +import { RELAY_BUDGETS } from './budgets.ts'; + +export interface PublicRelay { + readonly origin: string; + readonly read: boolean; + readonly write: boolean; + readonly nip50: boolean; +} +export interface InboxRelay { + readonly origin: string; + readonly read: boolean; + readonly write: boolean; +} +export interface RelayManifest { + readonly schemaVersion: 1; + readonly public: readonly PublicRelay[]; + readonly inbox: readonly InboxRelay[]; + readonly postingEnabled: boolean; + readonly messagingEnabled: boolean; + readonly operatorDenylist: readonly string[]; +} + +declare const admittedPolicy: unique symbol; +export type RelayPolicy = Readonly<{ readonly [admittedPolicy]: true }>; +// Only this owner retains the admitted JSON. Detached views cannot change egress. +const snapshots = new WeakMap<RelayPolicy, string>(); +function fields( + value: unknown, + names: readonly string[] +): value is Record<string, unknown> { + if (!value || typeof value !== 'object' || Array.isArray(value)) return false; + let count = 0; + for (const key in value) { + if (!names.includes(key)) return false; + count++; + } + return count === names.length; +} + +function publicAddress(host: string): boolean { + if (host.startsWith('[')) { + // Canonical global-unicast IPv6 only; mapped IPv4, local, multicast and + // unspecified forms fail closed. This is literal admission, never DNS or + // IP-at-connect enforcement (the browser owns connection resolution). + const head = host.slice(1, -1).split(':'); + const first = Number.parseInt(head[0], 16); + return ( + first >= 0x2000 && + first <= 0x3fff && + !(first === 0x2001 && ['db8', '0', '2', '10', '20'].includes(head[1])) + ); + } + if (/^[0-9.]+$/.test(host)) { + const [a, b, c] = host.split('.').map(Number); + return ( + a !== 0 && + a !== 10 && + a !== 127 && + a < 224 && + !(a === 100 && b >= 64 && b <= 127) && + !(a === 169 && b === 254) && + !(a === 172 && b >= 16 && b <= 31) && + !(a === 192 && [0, 168].includes(b)) && + !(a === 198 && ([18, 19].includes(b) || (b === 51 && c === 100))) && + !(a === 203 && b === 0 && c === 113) + ); + } + const labels = host.split('.'); + return ( + labels.length >= 2 && + host.length <= 253 && + labels.every((label) => + /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label) + ) && + !/(?:^|\.)(?:localhost|local|internal|invalid|test|example|onion)$/.test( + host + ) && + !host.endsWith('.home.arpa') + ); +} + +export function canonicalRelayOrigin(value: unknown): string | undefined { + if ( + typeof value !== 'string' || + value.length > 8192 || + !value.isWellFormed() || + !/^wss:\/\//.test(value) || + /[\s\\%\p{Cc}\p{Cf}]/u.test(value) + ) + return undefined; + try { + const url = new URL(value); + // A canonical origin has no userinfo, resource path, query or fragment, + // case/port normalization, percent encoding or trailing slash aliases. + if ( + url.origin !== value || + url.username || + url.password || + url.port === '0' || + !publicAddress(url.hostname) + ) + return undefined; + return url.origin; + } catch { + return undefined; + } +} + +function publicRelays(value: unknown): readonly PublicRelay[] | undefined { + if (!Array.isArray(value) || value.length > RELAY_BUDGETS.public) + return undefined; + const rows = (value as unknown[]).map((entry) => { + if (!fields(entry, ['origin', 'read', 'write', 'nip50'])) return undefined; + const { origin: rawOrigin, read, write, nip50 } = entry; + const origin = canonicalRelayOrigin(rawOrigin); + if ( + !origin || + typeof read !== 'boolean' || + typeof write !== 'boolean' || + typeof nip50 !== 'boolean' || + (!read && !write) || + (nip50 && !read) + ) + return undefined; + return { origin, read, write, nip50 }; + }); + if ( + rows.some((row) => !row) || + rows.some((row, index) => + rows.some((other, j) => index !== j && row?.origin === other?.origin) + ) + ) + return undefined; + return rows as readonly PublicRelay[]; +} +function inboxRelays(value: unknown): readonly InboxRelay[] | undefined { + if (!Array.isArray(value) || value.length > RELAY_BUDGETS.inbox) + return undefined; + const rows = (value as unknown[]).map((entry) => { + if (!fields(entry, ['origin', 'read', 'write'])) return undefined; + const { origin: rawOrigin, read, write } = entry; + const origin = canonicalRelayOrigin(rawOrigin); + if ( + !origin || + typeof read !== 'boolean' || + typeof write !== 'boolean' || + (!read && !write) + ) + return undefined; + return { origin, read, write }; + }); + if ( + rows.some((row) => !row) || + rows.some((row, index) => + rows.some((other, j) => index !== j && row?.origin === other?.origin) + ) + ) + return undefined; + return rows as readonly InboxRelay[]; +} + +// Accept bounded JSON, as with verified event ingress. Executable objects, +// getters, symbols, caller prototypes and post-admission mutations stay outside. +// 64 KiB bounds this public configuration parser; it is not a transport budget. +export function validateRelayPolicy(raw: unknown): RelayPolicy | undefined { + if ( + typeof raw !== 'string' || + raw.length > 65536 || + !raw.isWellFormed() || + new TextEncoder().encode(raw).length > 65536 + ) + return undefined; + try { + const row: unknown = JSON.parse(raw); + if ( + !fields(row, [ + 'schemaVersion', + 'public', + 'inbox', + 'postingEnabled', + 'messagingEnabled', + 'operatorDenylist' + ]) || + row.schemaVersion !== 1 || + typeof row.postingEnabled !== 'boolean' || + typeof row.messagingEnabled !== 'boolean' || + !Array.isArray(row.operatorDenylist) + ) + return undefined; + const publicEntries = publicRelays(row.public); + const inboxEntries = inboxRelays(row.inbox); + if (!publicEntries || !inboxEntries) return undefined; + const denylist = (row.operatorDenylist as unknown[]).map( + canonicalPublicKey + ); + if ( + denylist.some((key) => !key) || + denylist.some((key, index) => denylist.indexOf(key) !== index) + ) + return undefined; + const token = Object.freeze({}) as RelayPolicy; + snapshots.set( + token, + JSON.stringify({ + schemaVersion: 1, + public: publicEntries, + inbox: inboxEntries, + postingEnabled: row.postingEnabled, + messagingEnabled: row.messagingEnabled, + operatorDenylist: denylist + }) + ); + return token; + } catch { + return undefined; + } +} + +export function readRelayPolicy(policy: RelayPolicy): RelayManifest { + const raw = snapshots.get(policy); + if (!raw) throw new Error('relay_policy_invalid'); + return JSON.parse(raw) as RelayManifest; +} +// Fixed public sources never accept hints. Private targets additionally need +// verified recipient preferences; intersection does not authenticate kind10050. +// Callers get detached target arrays and cannot mutate the retained policy. +export function publicRelayTargets( + policy: RelayPolicy, + operation: 'read' | 'write' +): readonly string[] { + return readRelayPolicy(policy) + .public.filter((entry) => entry[operation]) + .map((entry) => entry.origin); +} +export function inboxRelayTargets( + policy: RelayPolicy, + recipientPreferences: readonly string[], + operation: 'read' | 'write' +): readonly string[] { + return readRelayPolicy(policy) + .inbox.filter( + (entry) => entry[operation] && recipientPreferences.includes(entry.origin) + ) + .map((entry) => entry.origin); +} +// Source launch-input preparation only. Operator/retention/independent-client +// qualification and real permissions remain separate mandatory gates. +export function requireLaunchRelayPolicy(policy: RelayPolicy): RelayPolicy { + const manifest = readRelayPolicy(policy); + if ( + !manifest.public.some((relay) => relay.read) || + !manifest.public.some(({ write }) => write) || + !manifest.inbox.some((relay) => relay.read) || + !manifest.inbox.some(({ write }) => write) + ) + throw new Error('relay_launch_inputs_missing'); + return policy; +} diff --git a/web/tests/unit/relay-config.test.ts b/web/tests/unit/relay-config.test.ts @@ -0,0 +1,293 @@ +import { describe, expect, it } from 'vitest'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { + canonicalRelayOrigin, + validateRelayPolicy, + readRelayPolicy, + type RelayPolicy, + requireLaunchRelayPolicy, + publicRelayTargets, + inboxRelayTargets +} from '../../src/lib/config/relays.ts'; +import { deploymentRelayPolicy } from '../../src/lib/config/deployment-relays.ts'; + +const admit = (value: unknown) => validateRelayPolicy(JSON.stringify(value)); +const publicRelay = (origin = 'wss://public.example.org') => ({ + origin, + read: true, + write: true, + nip50: false +}); +const inboxRelay = (origin = 'wss://inbox.example.org') => ({ + origin, + read: true, + write: true +}); +const input = () => ({ + schemaVersion: 1, + public: [publicRelay()], + inbox: [inboxRelay()], + postingEnabled: true, + messagingEnabled: true, + operatorDenylist: [] +}); + +describe('fixed relay policy', () => { + it('admits canonical WSS origins and explicit optional NIP50 capability', () => { + expect(canonicalRelayOrigin('wss://relay.example.org:8443')).toBe( + 'wss://relay.example.org:8443' + ); + const value = input(); + value.public[0].nip50 = true; + expect(readRelayPolicy(admit(value)!).public[0].nip50).toBe(true); + }); + it.each([ + '', + 'ws://relay.example.org', + 'https://relay.example.org', + '//relay.example.org', + ' wss://relay.example.org', + 'wss://relay.example.org\n', + 'wss://relay.example.org\\x', + 'wss://user:password@relay.example.org', + 'wss://@relay.example.org', + 'wss://relay.example.org/path', + 'wss://relay.example.org?token=private', + 'wss://relay.example.org#fragment', + 'WSS://RELAY.EXAMPLE.ORG', + 'wss://relay.example.org/', + 'wss://relay.example.org:443', + 'wss://relay.example.org:0', + 'wss://relay.example.org:65536', + 'wss://relay%2eexample.org', + 'wss://relay.example.org\u0000', + 'wss://localhost', + 'wss://sub.localhost', + 'wss://relay.local', + 'wss://relay.internal', + 'wss://relay.home.arpa', + 'wss://relay.test', + 'wss://127.0.0.1', + 'wss://127.1', + 'wss://2130706433', + 'wss://0x7f000001', + 'wss://10.1.2.3', + 'wss://172.16.0.1', + 'wss://192.168.0.1', + 'wss://169.254.169.254', + 'wss://100.64.0.1', + 'wss://0.0.0.0', + 'wss://224.0.0.1', + 'wss://[::1]', + 'wss://[::]', + 'wss://[fc00::1]', + 'wss://[fe80::1]', + 'wss://[::ffff:127.0.0.1]', + 'wss://[ff02::1]', + 'wss://singlelabel', + 'wss://relay.example.org.', + 'wss://-bad.example.org', + 'wss://relay.example.org\ud800', + 'wss://' + 'a'.repeat(8193) + ])('rejects malformed, credential or private-network origin %s', (origin) => { + expect(canonicalRelayOrigin(origin)).toBeUndefined(); + expect( + admit({ ...input(), public: [publicRelay(origin)] }) + ).toBeUndefined(); + }); + it('admits public address literals without claiming DNS or connect-time enforcement', () => { + expect(canonicalRelayOrigin('wss://8.8.8.8')).toBe('wss://8.8.8.8'); + expect(canonicalRelayOrigin('wss://[2606:4700:4700::1111]')).toBe( + 'wss://[2606:4700:4700::1111]' + ); + }); + it('caps each role independently at three, permits the same origin in separate roles', () => { + const value = input(); + value.public = [1, 2, 3].map((n) => + publicRelay(`wss://public${n}.example.org`) + ); + value.inbox = value.public.map(({ origin }) => inboxRelay(origin)); + expect(readRelayPolicy(admit(value)!).inbox).toHaveLength(3); + expect( + admit({ + ...value, + public: [...value.public, publicRelay()] + }) + ).toBeUndefined(); + expect( + admit({ ...value, inbox: [...value.inbox, inboxRelay()] }) + ).toBeUndefined(); + expect( + admit({ + ...input(), + public: [publicRelay(), publicRelay()] + }) + ).toBeUndefined(); + expect( + admit({ ...input(), inbox: [inboxRelay(), inboxRelay()] }) + ).toBeUndefined(); + }); + it('rejects unknown fields and wrong schema, array and flag types without echoing secrets', () => { + for (const value of [ + null, + [], + { ...input(), schemaVersion: 2 }, + { ...input(), token: 'private' }, + { ...input(), postingEnabled: 1 }, + { ...input(), messagingEnabled: 'true' }, + { ...input(), public: {} }, + { ...input(), operatorDenylist: ['private'] }, + { ...input(), public: [{ ...publicRelay(), auth: true }] }, + { ...input(), inbox: [{ ...inboxRelay(), nip50: false }] }, + { ...input(), public: [{ ...publicRelay(), read: false, nip50: true }] }, + { ...input(), public: [{ ...publicRelay(), read: false, write: false }] } + ]) + expect(admit(value)).toBeUndefined(); + }); + it('validates denylist keys and preserves an immutable token with detached views', () => { + const key = + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'; + const value = { ...input(), operatorDenylist: [key] }; + const admitted = admit(value)!; + value.public[0].origin = 'wss://outside.example.org'; + value.operatorDenylist.push('bad'); + expect(readRelayPolicy(admitted).public[0].origin).toBe( + 'wss://public.example.org' + ); + expect(readRelayPolicy(admitted).operatorDenylist).toEqual([key]); + expect(Object.isFrozen(admitted)).toBe(true); + + expect(admit({ ...input(), operatorDenylist: [key, key] })).toBeUndefined(); + expect( + admit({ ...input(), operatorDenylist: ['f'.repeat(64)] }) + ).toBeUndefined(); + }); + it('rejects inherited fields, symbols and accessors without invoking getters', () => { + let reads = 0; + const getter = { ...input() }; + Object.defineProperty(getter, 'public', { + get: () => { + reads++; + return []; + }, + enumerable: true + }); + expect(validateRelayPolicy(getter)).toBeUndefined(); + expect(reads).toBe(0); + expect(validateRelayPolicy(Object.create(input()))).toBeUndefined(); + expect( + validateRelayPolicy({ ...input(), [Symbol('credential')]: 'private' }) + ).toBeUndefined(); + }); + it('ignores public hints and intersects inbox targets with approved recipient preferences', () => { + const policy = admit(input())!; + expect(publicRelayTargets(policy, 'read')).toEqual([ + 'wss://public.example.org' + ]); + expect( + inboxRelayTargets( + policy, + [ + 'wss://outside.example.org', + 'wss://inbox.example.org', + 'wss://inbox.example.org' + ], + 'write' + ) + ).toEqual(['wss://inbox.example.org']); + expect( + inboxRelayTargets(policy, ['wss://outside.example.org'], 'write') + ).toEqual([]); + expect(inboxRelayTargets(policy, [], 'read')).toEqual([]); + const readOnly = admit({ + ...input(), + inbox: [{ ...inboxRelay(), write: false }] + })!; + expect( + inboxRelayTargets(readOnly, ['wss://inbox.example.org'], 'write') + ).toEqual([]); + }); + it('keeps separate effect flags disabled and production inputs empty until approved', () => { + expect(readRelayPolicy(deploymentRelayPolicy).public).toEqual([]); + expect(readRelayPolicy(deploymentRelayPolicy).inbox).toEqual([]); + expect(readRelayPolicy(deploymentRelayPolicy).postingEnabled).toBe(false); + expect(readRelayPolicy(deploymentRelayPolicy).messagingEnabled).toBe(false); + expect(() => requireLaunchRelayPolicy(deploymentRelayPolicy)).toThrow( + 'relay_launch_inputs_missing' + ); + expect(requireLaunchRelayPolicy(admit(input())!)).toBeDefined(); + expect(() => requireLaunchRelayPolicy({} as RelayPolicy)).toThrow( + 'relay_policy_invalid' + ); + expect( + admit({ ...input(), public: [publicRelay('wss://127.0.0.1')] }) + ).toBeUndefined(); + }); + it('bounds JSON admission and rejects malformed or non-JSON inputs', () => { + for (const raw of [ + '{', + 'null', + '[]', + '"policy"', + ' '.repeat(65537), + JSON.stringify({ ...input(), operatorDenylist: ['é'.repeat(33000)] }) + ]) + expect(validateRelayPolicy(raw)).toBeUndefined(); + expect(validateRelayPolicy(input())).toBeUndefined(); + }); + it('keeps retained egress unchanged after detached manifest and target mutations', () => { + const token = admit(input())!; + const view = readRelayPolicy(token); + (view.public as unknown as { origin: string }[])[0].origin = + 'wss://outside.example.org'; + (view.operatorDenylist as string[]).push('changed'); + const targets = publicRelayTargets(token, 'read') as string[]; + targets.push('wss://outside.example.org'); + expect(publicRelayTargets(token, 'read')).toEqual([ + 'wss://public.example.org' + ]); + expect(readRelayPolicy(token).operatorDenylist).toEqual([]); + expect(() => publicRelayTargets({} as RelayPolicy, 'read')).toThrow( + 'relay_policy_invalid' + ); + }); + it('preserves separate posting and messaging deployment flags', () => { + const token = admit({ + ...input(), + postingEnabled: false, + messagingEnabled: true + })!; + expect(readRelayPolicy(token).postingEnabled).toBe(false); + expect(readRelayPolicy(token).messagingEnabled).toBe(true); + }); + it('rejects inactive or secret-bearing inbox role data', () => { + expect( + admit({ + ...input(), + inbox: [{ ...inboxRelay(), read: false, write: false }] + }) + ).toBeUndefined(); + expect( + admit({ ...input(), inbox: [{ ...inboxRelay(), credential: 'private' }] }) + ).toBeUndefined(); + expect( + admit({ ...input(), public: [{ ...publicRelay(), write: 'true' }] }) + ).toBeUndefined(); + }); + it('actually fails the explicit launch preparation command on missing deployed inputs', () => { + const result = spawnSync( + process.execPath, + ['tools/check-launch-relays.mjs'], + { + cwd: fileURLToPath(new URL('../../', import.meta.url)), + encoding: 'utf8', + timeout: 10000 + } + ); + expect(result.error).toBeUndefined(); + expect(result.status).toBe(1); + expect(result.stderr).toContain('relay_launch_inputs_missing'); + expect(result.stdout).not.toContain('PASS'); + }); +}); diff --git a/web/tools/check-launch-relays.mjs b/web/tools/check-launch-relays.mjs @@ -0,0 +1,12 @@ +import { deploymentRelayPolicy } from '../src/lib/config/deployment-relays.ts'; +import { requireLaunchRelayPolicy } from '../src/lib/config/relays.ts'; + +try { + requireLaunchRelayPolicy(deploymentRelayPolicy); + console.log( + 'Relay launch inputs admitted; operator qualification remains required' + ); +} catch { + console.error('relay_launch_inputs_missing'); + process.exitCode = 1; +}