app

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

commit 1c07aca935b7ef41e527d12b3ae94bfb37cdc0fa
parent b1cf3410c8bc3bdc12d977adcee7e653b65e1121
Author: triesap <tyson@radroots.org>
Date:   Mon,  5 Oct 2026 16:15:32 +0000

web: centralize public product reference handling (HCP-017)

- Decode and encode bounded kind-30402 references with qualified Applesauce exports.
- Preserve raw UTF8 identifiers and BOMs while rejecting malformed or unsupported bytes.
- Match canonical public keys to the pinned Rust oracle through a restricted upstream primitive.
- Verify route builders, reference matching and narrow import admissions without network effects.

Diffstat:
Mweb/package.json | 5+++++
Mweb/pnpm-lock.yaml | 172+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/contracts/public-key.ts | 14++++++++++++++
Aweb/src/lib/nostr/references.ts | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/routes.ts | 14++++++++++++++
Aweb/src/params/naddr.ts | 5+++++
Mweb/tests/provenance/source-boundaries.test.mjs | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/public-key.test.ts | 24++++++++++++++++++++++++
Aweb/tests/unit/reference-oracle.json | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/references.test.ts | 183+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tools/source-boundaries.mjs | 31++++++++++++++++++++++++++++++-
11 files changed, 737 insertions(+), 1 deletion(-)

diff --git a/web/package.json b/web/package.json @@ -19,6 +19,11 @@ "test:integration": "corepack pnpm build && node --test --test-timeout=10000 tests/integration/*.test.ts", "test:e2e": "corepack pnpm build && playwright test" }, + "dependencies": { + "@noble/curves": "1.2.0", + "@scure/base": "1.1.1", + "applesauce-core": "6.2.0" + }, "devDependencies": { "@eslint/js": "10.0.1", "@opentelemetry/api": "1.9.1", diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml @@ -206,6 +206,16 @@ settings: importers: .: + dependencies: + '@noble/curves': + specifier: 1.2.0 + version: 1.2.0 + '@scure/base': + specifier: 1.1.1 + version: 1.1.1 + applesauce-core: + specifier: 6.2.0 + version: 6.2.0(typescript@6.0.3) devDependencies: '@eslint/js': specifier: 10.0.1 @@ -425,6 +435,38 @@ packages: integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA== } + '@noble/ciphers@0.5.3': + resolution: + { + integrity: sha512-B0+6IIHiqEs3BPMT0hcRmHvEj2QHOLu+uwt+tqDDeVd0oyVzh7BPrDcPjRnV1PV/5LaknXJJQvOuRGR0zQJz+w== + } + + '@noble/curves@1.1.0': + resolution: + { + integrity: sha512-091oBExgENk/kGj3AZmtBDMpxQPDtxQABR2B9lb1JbVTs6ytdzZNwvhxQ4MWasRNEzlbEH8jCWFCwhF/Obj5AA== + } + + '@noble/curves@1.2.0': + resolution: + { + integrity: sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw== + } + + '@noble/hashes@1.3.1': + resolution: + { + integrity: sha512-EbqwksQwz9xDRGfDST86whPBgM65E0OH/pCgqW0GBVzO22bNE+NuIbeTb714+IfSjU3aRk47EUvXIb5bTsenKA== + } + engines: { node: '>= 16' } + + '@noble/hashes@1.3.2': + resolution: + { + integrity: sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ== + } + engines: { node: '>= 16' } + '@opentelemetry/api@1.9.1': resolution: { @@ -599,6 +641,24 @@ packages: integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw== } + '@scure/base@1.1.1': + resolution: + { + integrity: sha512-ZxOhsSyxYwLJj3pLZCefNitxsj093tb2vq90mp2txoYeBqbcjDjqFhyM8eUjq/uFm6zJ+mUuqxlS2FkuSY1MTA== + } + + '@scure/bip32@1.3.1': + resolution: + { + integrity: sha512-osvveYtyzdEVbt3OfwwXFr4P2iVBL5u1Q3q4ONBfDY/UpOuXmOlbgwc1xECEboY8wIays8Yt6onaWMUdUbfl0A== + } + + '@scure/bip39@1.2.1': + resolution: + { + integrity: sha512-Z3/Fsz1yr904dduJD0NpiyRHhRYHdcnyh73FZWiV+/qhWi83wNJ3NWolYqCEN+ZWsUz2TWwajJggcRE9r1zUYg== + } + '@standard-schema/spec@1.1.0': resolution: { @@ -830,6 +890,12 @@ packages: integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw== } + applesauce-core@6.2.0: + resolution: + { + integrity: sha512-O6AlVyzqcuIhTOIuexm6UWmx7mRIa2D98gJP7K7vFGf90YdtvSH78AsKQWZXJ0Pk/K14at+9zkwfCkFr7ghgNw== + } + aria-query@5.3.1: resolution: { @@ -1175,6 +1241,12 @@ packages: } engines: { node: '>=18' } + hash-sum@2.0.0: + resolution: + { + integrity: sha512-WdZTbAByD+pHfl/g9QSsBIIwy8IT+EsPiKDs0KNX+zSHhdDLFKdZu0BQHljvO+0QI/BasbMSUa8wYNCZTvhslg== + } + hashery@1.5.1: resolution: { @@ -1449,12 +1521,37 @@ packages: engines: { node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1 } hasBin: true + nanoid@5.1.16: + resolution: + { + integrity: sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ== + } + engines: { node: ^18 || >=20 } + hasBin: true + natural-compare@1.4.0: resolution: { integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw== } + nostr-tools@2.19.4: + resolution: + { + integrity: sha512-qVLfoTpZegNYRJo5j+Oi6RPu0AwLP6jcvzcB3ySMnIT5DrAGNXfs5HNBspB/2HiGfH3GY+v6yXkTtcKSBQZwSg== + } + peerDependencies: + typescript: '>=5.0.0' + peerDependenciesMeta: + typescript: + optional: true + + nostr-wasm@0.1.0: + resolution: + { + integrity: sha512-78BTryCLcLYv96ONU8Ws3Q1JzjlAt+43pWQhIl86xZmWeegYCNLPml7yQ+gG3vR6V5h4XGj+TxO+SS5dsThQIA== + } + obug@2.2.1: resolution: { @@ -1627,6 +1724,12 @@ packages: engines: { node: ^20.19.0 || >=22.12.0 } hasBin: true + rxjs@7.8.2: + resolution: + { + integrity: sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA== + } + sade@1.8.1: resolution: { @@ -1743,6 +1846,12 @@ packages: peerDependencies: typescript: '>=4.8.4' + tslib@2.8.1: + resolution: + { + integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w== + } + type-check@0.4.0: resolution: { @@ -2035,6 +2144,20 @@ snapshots: '@keyv/serialize@1.1.1': {} + '@noble/ciphers@0.5.3': {} + + '@noble/curves@1.1.0': + dependencies: + '@noble/hashes': 1.3.1 + + '@noble/curves@1.2.0': + dependencies: + '@noble/hashes': 1.3.2 + + '@noble/hashes@1.3.1': {} + + '@noble/hashes@1.3.2': {} + '@opentelemetry/api@1.9.1': {} '@oxc-project/types@0.152.0': {} @@ -2092,6 +2215,19 @@ snapshots: '@rolldown/pluginutils@1.0.1': {} + '@scure/base@1.1.1': {} + + '@scure/bip32@1.3.1': + dependencies: + '@noble/curves': 1.1.0 + '@noble/hashes': 1.3.1 + '@scure/base': 1.1.1 + + '@scure/bip39@1.2.1': + dependencies: + '@noble/hashes': 1.3.1 + '@scure/base': 1.1.1 + '@standard-schema/spec@1.1.0': {} '@sveltejs/acorn-typescript@1.0.13(acorn@8.18.0)': @@ -2266,6 +2402,18 @@ snapshots: json-schema-traverse: 0.4.1 uri-js: 4.4.1 + applesauce-core@6.2.0(typescript@6.0.3): + dependencies: + debug: 4.4.3 + fast-deep-equal: 3.1.3 + hash-sum: 2.0.0 + nanoid: 5.1.16 + nostr-tools: 2.19.4(typescript@6.0.3) + rxjs: 7.8.2 + transitivePeerDependencies: + - supports-color + - typescript + aria-query@5.3.1: {} assertion-error@2.0.1: {} @@ -2465,6 +2613,8 @@ snapshots: globals@16.5.0: {} + hash-sum@2.0.0: {} + hashery@1.5.1: dependencies: hookified: 1.15.1 @@ -2583,8 +2733,24 @@ snapshots: nanoid@3.3.19: {} + nanoid@5.1.16: {} + natural-compare@1.4.0: {} + nostr-tools@2.19.4(typescript@6.0.3): + dependencies: + '@noble/ciphers': 0.5.3 + '@noble/curves': 1.2.0 + '@noble/hashes': 1.3.1 + '@scure/base': 1.1.1 + '@scure/bip32': 1.3.1 + '@scure/bip39': 1.2.1 + nostr-wasm: 0.1.0 + optionalDependencies: + typescript: 6.0.3 + + nostr-wasm@0.1.0: {} + obug@2.2.1: {} optionator@0.9.4: @@ -2682,6 +2848,10 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.2.12 '@rolldown/binding-win32-x64-msvc': 1.2.12 + rxjs@7.8.2: + dependencies: + tslib: 2.8.1 + sade@1.8.1: dependencies: mri: 1.2.0 @@ -2764,6 +2934,8 @@ snapshots: dependencies: typescript: 6.0.3 + tslib@2.8.1: {} + type-check@0.4.0: dependencies: prelude-ls: 1.2.1 diff --git a/web/src/lib/contracts/public-key.ts b/web/src/lib/contracts/public-key.ts @@ -0,0 +1,14 @@ +import { secp256k1 } from '@noble/curves/secp256k1'; + +// Admission matches the pinned Radroots x-only public-key type. This module +// validates public data only; it never generates keys, signs or derives secrets. +export function canonicalPublicKey(value: unknown): string | undefined { + if (typeof value !== 'string' || !/^[0-9a-f]{64}$/.test(value)) + return undefined; + try { + secp256k1.ProjectivePoint.fromHex('02' + value); + return value; + } catch { + return undefined; + } +} diff --git a/web/src/lib/nostr/references.ts b/web/src/lib/nostr/references.ts @@ -0,0 +1,107 @@ +import { decodePointer, naddrEncode } from 'applesauce-core/helpers/pointers'; +import { bech32 } from '@scure/base'; +import { canonicalPublicKey } from '../contracts/public-key'; + +const maximumRouteBytes = 2048; +const encoder = new TextEncoder(); +const strictIdentifier = new TextDecoder('utf-8', { + fatal: true, + ignoreBOM: true +}); + +export type ProductCoordinate = Readonly<{ + kind: 30402; + pubkey: string; + identifier: string; +}>; +export type ProductReference = ProductCoordinate & Readonly<{ naddr: string }>; + +function boundedText(value: unknown): value is string { + return ( + typeof value === 'string' && + value.length > 0 && + value.length <= maximumRouteBytes && + value.isWellFormed() && + encoder.encode(value).length <= maximumRouteBytes + ); +} + +// Applesauce owns semantic pointer decoding. This bounded preflight checks the +// first identifier's raw bytes because its selected decoder replaces malformed +// UTF8 and removes one leading BOM. Unknown well-framed TLVs remain ignorable. +function identifierBytes(value: string): Uint8Array { + const { prefix, words } = bech32.decode(value, maximumRouteBytes); + if (prefix !== 'naddr') throw new Error('Unsupported reference'); + const bytes = Uint8Array.from(bech32.fromWords(words)); + let identifier: Uint8Array | undefined; + for (let offset = 0; offset < bytes.length;) { + if (offset + 2 > bytes.length) throw new Error('Truncated reference'); + const type = bytes[offset]; + const length = bytes[offset + 1]; + const end = offset + 2 + length; + if (end > bytes.length) throw new Error('Truncated reference'); + if (type === 0 && identifier === undefined) + identifier = bytes.slice(offset + 2, end); + offset = end; + } + if (identifier === undefined) throw new Error('Missing identifier'); + return identifier; +} + +export function decodeProductReference( + value: unknown +): ProductReference | undefined { + if ( + !boundedText(value) || + !/^[a-zA-Z0-9]+$/.test(value) || + (value !== value.toLowerCase() && value !== value.toUpperCase()) + ) + return undefined; + try { + const originalBytes = identifierBytes(value); + const identifier = strictIdentifier.decode(originalBytes); + const decoded = decodePointer(value); + if (decoded.type !== 'naddr' || decoded.data.kind !== 30402) + return undefined; + const pubkey = canonicalPublicKey(decoded.data.pubkey); + if (pubkey === undefined) return undefined; + // The only accepted mismatch is the inspected upstream decoder's removal + // of exactly the first leading BOM. Keep the byte-derived identifier. + const expected = identifier.startsWith('\ufeff') + ? identifier.slice(1) + : identifier; + if (decoded.data.identifier !== expected) return undefined; + const naddr = naddrEncode({ kind: 30402, pubkey, identifier }); + if (!boundedText(naddr)) return undefined; + const encodedBytes = identifierBytes(naddr); + if ( + encodedBytes.length !== originalBytes.length || + encodedBytes.some((byte, index) => byte !== originalBytes[index]) + ) + return undefined; + return { kind: 30402, pubkey, identifier, naddr }; + } catch { + return undefined; + } +} + +export function encodeProductReference( + value: Readonly<{ kind: number; pubkey: string; identifier: string }> +): string | undefined { + if ( + value.kind !== 30402 || + canonicalPublicKey(value.pubkey) === undefined || + typeof value.identifier !== 'string' || + !value.identifier.isWellFormed() || + value.identifier.length > 255 || + encoder.encode(value.identifier).length > 255 + ) + return undefined; + try { + const encoded = naddrEncode(value); + const decoded = decodeProductReference(encoded); + return decoded?.identifier === value.identifier ? decoded.naddr : undefined; + } catch { + return undefined; + } +} diff --git a/web/src/lib/routes.ts b/web/src/lib/routes.ts @@ -0,0 +1,14 @@ +import { decodeProductReference } from './nostr/references'; +import { internalHref } from './navigation-url'; + +export function productHref(input: unknown): string | undefined { + const reference = decodeProductReference(input); + return reference === undefined + ? undefined + : internalHref(`/products/${reference.naddr}`); +} + +export function productEditHref(input: unknown): string | undefined { + const href = productHref(input); + return href === undefined ? undefined : internalHref(`${href}/edit`); +} diff --git a/web/src/params/naddr.ts b/web/src/params/naddr.ts @@ -0,0 +1,5 @@ +import { decodeProductReference } from '../lib/nostr/references'; + +export function match(value: string): boolean { + return decodeProductReference(value) !== undefined; +} diff --git a/web/tests/provenance/source-boundaries.test.mjs b/web/tests/provenance/source-boundaries.test.mjs @@ -96,6 +96,73 @@ const reject = (result, diagnostic) => { assert.match(result.stderr, diagnostic); }; +test('admits only exact public-key and reference primitive consumers', async () => { + await fixture(async ({ directory, put, execute }) => { + await confineSvelte(directory); + const { cp } = await import('node:fs/promises'); + for (const name of ['@noble/curves', '@scure/base', 'applesauce-core']) { + const destination = path.join(directory, 'node_modules', name); + await mkdir(path.dirname(destination), { recursive: true }); + await cp( + await realpath(path.join(root, 'node_modules', name)), + destination, + { + recursive: true + } + ); + } + for (const name of [ + 'src/lib/contracts/public-key.ts', + 'src/lib/nostr/references.ts' + ]) + await put(name, await readFile(path.join(root, name), 'utf8')); + const result = execute(); + assert.equal(result.status, 0, result.stdout + result.stderr); + }); +}); + +for (const [name, content] of [ + [ + 'src/lib/other.ts', + "import { secp256k1 } from '@noble/curves/secp256k1'; export const value = secp256k1;" + ], + [ + 'src/lib/nostr/other.ts', + "import { bech32 } from '@scure/base'; export const value = bech32;" + ], + [ + 'src/lib/contracts/public-key.ts', + "import { secp256k1 } from '@noble/curves/secp256k1'; export const value = secp256k1;" + ], + [ + 'src/lib/contracts/public-key.ts', + "import { schnorr } from '@noble/curves/secp256k1'; export const value = schnorr;" + ], + [ + 'src/lib/nostr/references.ts', + "import { base64 } from '@scure/base'; export const value = base64;" + ] +]) + test(`rejects broad or altered primitive access ${name} ${content}`, async () => { + await fixture(async ({ put, execute }) => { + await put(name, content); + reject(execute(), /forbidden production import/); + }); + }); + +test('rejects primitive pin drift at the reviewed consumer', async () => { + await fixture(async ({ put, execute, pkg }) => { + await put( + 'src/lib/contracts/public-key.ts', + await readFile(path.join(root, 'src/lib/contracts/public-key.ts'), 'utf8') + ); + /** @type {Record<string, string>} */ (pkg.dependencies)['@noble/curves'] = + '1.1.0'; + await put('package.json', JSON.stringify(pkg)); + reject(execute(), /forbidden production import/); + }); +}); + for (const [name, content, diagnostic] of [ [ 'native extension import', diff --git a/web/tests/unit/public-key.test.ts b/web/tests/unit/public-key.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest'; +import { canonicalPublicKey } from '../../src/lib/contracts/public-key'; +import oracle from './reference-oracle.json'; + +describe('exact public Rust key admission', () => { + for (const row of oracle.key_cases) + it(row.pubkey, () => { + expect(canonicalPublicKey(row.pubkey)).toBe( + row.accepted ? row.pubkey : undefined + ); + }); + it('rejects noncanonical and unbounded input', () => { + const key = oracle.key_cases[0].pubkey; + for (const value of [ + null, + {}, + key.toUpperCase(), + ` ${key}`, + key + '0', + 'a'.repeat(10000) + ]) + expect(canonicalPublicKey(value)).toBeUndefined(); + }); +}); diff --git a/web/tests/unit/reference-oracle.json b/web/tests/unit/reference-oracle.json @@ -0,0 +1,116 @@ +{ + "coordinate_cases": [ + { + "canonical": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:", + "identifier": "", + "input": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:", + "kind": 30402, + "pubkey": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + }, + { + "canonical": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:Carrots:菜", + "identifier": "Carrots:菜", + "input": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:Carrots:菜", + "kind": 30402, + "pubkey": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + }, + { + "canonical": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:CARROTS:菜", + "identifier": "CARROTS:菜", + "input": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:CARROTS:菜", + "kind": 30402, + "pubkey": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + }, + { + "canonical": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:café", + "identifier": "café", + "input": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:café", + "kind": 30402, + "pubkey": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + }, + { + "canonical": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:café", + "identifier": "café", + "input": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:café", + "kind": 30402, + "pubkey": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + }, + { + "canonical": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:Carrots:菜", + "identifier": "Carrots:菜", + "input": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:Carrots:菜", + "kind": 30402, + "pubkey": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + }, + { + "canonical": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:Carrots:菜", + "identifier": "Carrots:菜", + "input": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:Carrots:菜", + "kind": 30402, + "pubkey": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + }, + { + "canonical": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:�", + "identifier": "�", + "input": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:�", + "kind": 30402, + "pubkey": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + }, + { + "canonical": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798: white space ", + "identifier": " white space ", + "input": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798: white space ", + "kind": 30402, + "pubkey": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + }, + { + "canonical": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:\u0000", + "identifier": "\u0000", + "input": "30402:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798:\u0000", + "kind": 30402, + "pubkey": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + } + ], + "key_cases": [ + { + "accepted": true, + "pubkey": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + }, + { + "accepted": false, + "pubkey": "0000000000000000000000000000000000000000000000000000000000000000" + }, + { + "accepted": false, + "pubkey": "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + }, + { + "accepted": true, + "pubkey": "0000000000000000000000000000000000000000000000000000000000000001" + }, + { + "accepted": true, + "pubkey": "0000000000000000000000000000000000000000000000000000000000000002" + }, + { + "accepted": true, + "pubkey": "0000000000000000000000000000000000000000000000000000000000000003" + }, + { + "accepted": false, + "pubkey": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f" + }, + { + "accepted": false, + "pubkey": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2e" + } + ], + "oracle": { + "apis": [ + "radroots_identity::PublicKey::from_hex", + "radroots_event::id::Nip01Coordinate::parse" + ], + "repository": "https://github.com/radrootslabs/lib", + "revision": "189c49b74b4bafc142b00b76b296477931139e72" + } +} diff --git a/web/tests/unit/references.test.ts b/web/tests/unit/references.test.ts @@ -0,0 +1,183 @@ +import { describe, expect, it, vi } from 'vitest'; +import * as pointers from 'applesauce-core/helpers/pointers'; +import { bech32 } from '@scure/base'; +import { + decodeProductReference, + encodeProductReference +} from '../../src/lib/nostr/references'; +import { productHref, productEditHref } from '../../src/lib/routes'; +import { match } from '../../src/params/naddr'; +import oracle from './reference-oracle.json'; + +// Instrument the actual export; its implementation and decoded results remain +// real. Native ESM namespaces themselves are immutable and cannot be spied on. +vi.mock('applesauce-core/helpers/pointers', { spy: true }); + +const pubkey = oracle.key_cases[0].pubkey; +const encode = (identifier: string, kind = 30402) => + pointers.naddrEncode({ + kind, + pubkey, + identifier, + relays: ['wss://example.invalid'] + }); +const raw = (input: string) => { + const decoded = bech32.decode(input, 2048); + return Uint8Array.from(bech32.fromWords(decoded.words)); +}; +const wrap = (data: Uint8Array) => + bech32.encode('naddr', bech32.toWords(data), 2048); + +describe('bounded exact product references', () => { + for (const row of oracle.coordinate_cases) + it(`Rust raw identifier ${JSON.stringify(row.identifier)}`, () => { + const input = encode(row.identifier); + const result = decodeProductReference(input); + expect(result).toEqual({ + kind: 30402, + pubkey, + identifier: row.identifier, + naddr: pointers.naddrEncode({ + kind: 30402, + pubkey, + identifier: row.identifier + }) + }); + expect( + encodeProductReference({ + kind: 30402, + pubkey, + identifier: row.identifier + }) + ).toBe(result?.naddr); + expect(decodeProductReference(result?.naddr)?.identifier).toBe( + row.identifier + ); + expect(productHref(input)).toBe(`/products/${result?.naddr}`); + expect(productEditHref(input)).toBe(`/products/${result?.naddr}/edit`); + expect(match(input)).toBe(true); + expect(decodeProductReference(input.toUpperCase())).toEqual(result); + }); + it('ignores unknown framed TLVs and uses the selected decoder first identifier', () => { + const bytes = raw(encode('Carrots:菜')); + const changed = wrap(Uint8Array.from([99, 3, 1, 2, 3, ...bytes, 0, 1, 65])); + expect(decodeProductReference(changed)?.identifier).toBe('Carrots:菜'); + expect(decodeProductReference(changed)?.naddr).toBe( + encodeProductReference({ kind: 30402, pubkey, identifier: 'Carrots:菜' }) + ); + }); + it('rejects malformed UTF8 instead of replacement, but accepts actual U+FFFD', () => { + const bytes = raw(encode('a')); + for (const invalid of [ + [0xff], + [0xc0, 0xaf], + [0xed, 0xa0, 0x80], + [0xf4, 0x90, 0x80, 0x80], + [0xe2, 0x82] + ]) { + const input = wrap( + Uint8Array.from([0, invalid.length, ...invalid, ...bytes.slice(3)]) + ); + expect(decodeProductReference(input)).toBeUndefined(); + } + expect(decodeProductReference(encode('\ufffd'))?.identifier).toBe('\ufffd'); + }); + it('rejects truncated TLV framing including malformed unknown TLVs', () => { + const bytes = raw(encode('a')); + for (const suffix of [[99], [99, 2, 1]]) + expect( + decodeProductReference(wrap(Uint8Array.from([...bytes, ...suffix]))) + ).toBeUndefined(); + }); + it('admits exactly 2048 bytes and rejects overflow before decoding', () => { + const bytes = [...raw(encode('Carrots:菜'))]; + // 1272 payload bytes encode to 2036 words plus the prefix/checksum:2048. + while (bytes.length < 1272) { + const length = Math.min(255, 1272 - bytes.length - 2); + bytes.push(99, length, ...Array.from({ length }, () => 0)); + } + const input = wrap(Uint8Array.from(bytes)); + expect(new TextEncoder().encode(input).length).toBe(2048); + expect(decodeProductReference(input)?.identifier).toBe('Carrots:菜'); + const spy = vi.spyOn(pointers, 'decodePointer'); + spy.mockClear(); + try { + expect(decodeProductReference(input + 'q')).toBeUndefined(); + expect(spy).not.toHaveBeenCalled(); + } finally { + spy.mockRestore(); + } + }); + it('bounds before Applesauce decoding', () => { + const spy = vi.spyOn(pointers, 'decodePointer'); + try { + for (const input of [ + 'naddr1' + 'q'.repeat(2043), + '菜'.repeat(683), + 'naddr1' + '\ud800', + null, + {}, + '' + ]) + expect(decodeProductReference(input)).toBeUndefined(); + expect(spy).not.toHaveBeenCalled(); + } finally { + spy.mockRestore(); + } + }); + it('rejects unsupported/mixed-case/bad keys and never fetches', () => { + const value = encode('a'); + const bad = [ + value.slice(0, 7).toUpperCase() + value.slice(7), + value + 'q', + encode('a', 1), + pointers.naddrEncode({ + kind: 30402, + pubkey: '0'.repeat(64), + identifier: 'a' + }), + pointers.naddrEncode({ + kind: 30402, + pubkey: 'f'.repeat(64), + identifier: 'a' + }), + 'https://example.invalid/', + `nostr:${value}` + ]; + const fetchSpy = vi.spyOn(globalThis, 'fetch'); + try { + for (const input of bad) { + expect(decodeProductReference(input)).toBeUndefined(); + expect(productHref(input)).toBeUndefined(); + expect(productEditHref(input)).toBeUndefined(); + expect(match(input)).toBe(false); + } + expect(fetchSpy).not.toHaveBeenCalled(); + } finally { + fetchSpy.mockRestore(); + } + }); + it('does not truncate unencodable identifier bytes or repair invalid input', () => { + for (const identifier of ['x'.repeat(256), '菜'.repeat(86), '\ud800']) + expect( + encodeProductReference({ kind: 30402, pubkey, identifier }) + ).toBeUndefined(); + expect( + encodeProductReference({ kind: 1, pubkey, identifier: 'a' }) + ).toBeUndefined(); + expect( + encodeProductReference({ + kind: 30402, + pubkey: pubkey.toUpperCase(), + identifier: 'a' + }) + ).toBeUndefined(); + expect( + encodeProductReference({ + kind: 30402, + pubkey, + identifier: 'x'.repeat(255) + }) + ).toBeDefined(); + }); +}); diff --git a/web/tools/source-boundaries.mjs b/web/tools/source-boundaries.mjs @@ -1307,6 +1307,35 @@ export async function auditSource(root) { 'unrestricted Svelte raw-render module access is forbidden' ); const actualImport = actualName + specifier.slice(packageName.length); + // These upstream primitives have no blanket runtime-package admission. + // Only the exact reviewed pure adapters and exact package exports/pins may + // use them. Source changes require a new independent review of this scope. + const primitiveAdmissions = { + '@noble/curves': { + version: '1.2.0', + import: '@noble/curves/secp256k1', + file: 'src/lib/contracts/public-key.ts', + sha256: + 'd36d4001c2f4835e24d50f00460a35c9cf9fa6b86cc3b4a6937d8b4e10afdeb9' + }, + '@scure/base': { + version: '1.1.1', + import: '@scure/base', + file: 'src/lib/nostr/references.ts', + sha256: + 'b6a2ee32e89b60410bd84f5bbf2adc464d4f9d4d29b6a067e75927540b006ac4' + } + }; + const primitive = Object.hasOwn(primitiveAdmissions, actualName) + ? primitiveAdmissions[actualName] + : undefined; + const admittedPrimitive = + primitive !== undefined && + declared === primitive.version && + actualImport === primitive.import && + relative(root, file) === primitive.file && + createHash('sha256').update(files.get(file)).digest('hex') === + primitive.sha256; if ( (actualName === '@sveltejs/kit' && !['@sveltejs/kit', '@sveltejs/kit/hooks'].includes(actualImport)) || @@ -1322,7 +1351,7 @@ export async function auditSource(root) { ) complain(file, 'Applesauce imports belong in lib/nostr'); if ( - !runtimePackages.has(actualName) || + (!runtimePackages.has(actualName) && !admittedPrimitive) || typeof declared !== 'string' || /^(file:|link:|workspace:|git|https?:|\.\.?\/)/.test(declared) )