app

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

commit ad8aece558f2d9b37ad4bb3dac9e1e2cfc62f751
parent 845fc9b2304f29a01fbab5ebcedebaea02dfc312
Author: triesap <tyson@radroots.org>
Date:   Mon,  5 Oct 2026 23:28:05 +0000

web: implement tolerant verified food reader (HCP-024)

- Verify bounded NIP-01 members with Applesauce before food classification.
- Partition raw markers and preserve tolerant exact food values and exclusions.
- Bound incoming media diagnostics without adding an image pipeline.
- Replay pinned Rust reader fixtures and exercise invalid input boundaries.

Diffstat:
Aweb/src/lib/contracts/food-availability-v1/media.ts | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/contracts/food-availability-v1/partition.ts | 29+++++++++++++++++++++++++++++
Aweb/src/lib/contracts/food-availability-v1/read.ts | 281+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/contracts/food-availability-v1/text.ts | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/nostr/verified-envelope.ts | 166+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/conformance/food-reader.test.ts | 151++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/food-reader.test.ts | 386+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 1210 insertions(+), 0 deletions(-)

diff --git a/web/src/lib/contracts/food-availability-v1/media.ts b/web/src/lib/contracts/food-availability-v1/media.ts @@ -0,0 +1,148 @@ +import { boundedUtf8 } from './text.ts'; +export type ImageDiagnostic = + | 'food_image_shape_invalid' + | 'food_image_url_invalid' + | 'food_image_dimensions_missing' + | 'food_image_dimensions_invalid' + | 'food_image_duplicate_url' + | 'food_image_duplicate_digest' + | 'food_image_count_exceeded'; +export type InboundImage = Readonly<{ + raw_tag: readonly string[]; + url: string | null; + dimensions: Readonly<{ width: number; height: number }> | null; + diagnostics: readonly ImageDiagnostic[]; + qualifies: boolean; +}>; +function structuralUrl(value: string): URL | undefined { + if ( + !boundedUtf8(value, 4096) || + !value.includes('://') || + /[\p{White_Space}\p{Cc}\p{Cf}]/u.test(value) + ) + return undefined; + try { + const url = new URL(value); + if ( + !['http:', 'https:'].includes(url.protocol) || + url.username || + url.password + ) + return undefined; + const rest = value.slice(value.indexOf('://') + 3); + const end = rest.search(/[/?#]/u); + const authority = end < 0 ? rest : rest.slice(0, end); + if (!authority || authority.includes('@')) return undefined; + const suffix = end < 0 ? '' : rest.slice(end); + const path = suffix.split(/[?#]/u)[0]; + if (!path.startsWith('/')) return undefined; + let host: string; + if (authority.startsWith('[')) { + const close = authority.indexOf(']'); + if (close < 0) return undefined; + const after = authority.slice(close + 1); + if (after && !after.startsWith(':')) return undefined; + host = authority.slice(1, close); + } else { + const colon = authority.lastIndexOf(':'); + host = colon < 0 ? authority : authority.slice(0, colon); + if (host.includes(':')) return undefined; + } + if ( + !host || + Array.from(host).some((character) => character.codePointAt(0)! > 127) + ) + return undefined; + const ip = + url.hostname.startsWith('[') || + /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/u.test(url.hostname); + if ( + !ip && + (host.length > 253 || + !host + .split('.') + .every( + (label) => + label.length <= 63 && + /^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/u.test(label) + )) + ) + return undefined; + return url; + } catch { + return undefined; + } +} +function dimension(value: string): number | undefined { + if ( + value.length === 0 || + value.length > 10 || + !/^[1-9][0-9]*$/u.test(value) || + (value.length === 10 && value > '4294967295') + ) + return undefined; + return Number(value); +} +function dimensions(value: string): { width: number; height: number } | null { + if (value.length > 21) return null; + const parts = value.split('x'); + if (parts.length !== 2) return null; + const width = dimension(parts[0]); + const height = dimension(parts[1]); + return width === undefined || height === undefined ? null : { width, height }; +} +function digest(url: URL): string | undefined { + // Public tolerant reader extracts only a structural root Blossom hash path. + // Query/fragment do not change the path; no download or byte proof occurs. + const match = /^\/([0-9a-f]{64})(?:\.([a-zA-Z0-9_.-]+))?$/u.exec( + url.pathname + ); + if ( + !match || + (match[2] && match[2].split('.').some((part) => part.length === 0)) + ) + return undefined; + return match[1]; +} +export function projectImages(tags: readonly (readonly string[])[]): Readonly<{ + images: readonly InboundImage[]; + diagnostics: readonly ImageDiagnostic[]; +}> { + const bounded = tags.slice(0, 64); + const images: InboundImage[] = bounded.map((tag, index) => { + const row: ImageDiagnostic[] = []; + if (tag.length !== 3) row.push('food_image_shape_invalid'); + const parsed = tag[1] === undefined ? undefined : structuralUrl(tag[1]); + if (!parsed) row.push('food_image_url_invalid'); + const size = tag[2] === undefined ? null : dimensions(tag[2]); + if (tag[2] === undefined) row.push('food_image_dimensions_missing'); + else if (!size) row.push('food_image_dimensions_invalid'); + const previous = bounded.slice(0, index); + if (tag[1] !== undefined) { + if (previous.some((old) => old[1] === tag[1])) + row.push('food_image_duplicate_url'); + const hash = parsed ? digest(parsed) : undefined; + if ( + hash && + previous.some((old) => { + const url = old[1] === undefined ? undefined : structuralUrl(old[1]); + return url !== undefined && digest(url) === hash; + }) + ) + row.push('food_image_duplicate_digest'); + } + return { + raw_tag: [...tag], + url: parsed ? tag[1] : null, + dimensions: size, + diagnostics: row, + qualifies: row.length === 0 + }; + }); + const overflow: ImageDiagnostic[] = + tags.length > 64 ? ['food_image_count_exceeded'] : []; + return { + images, + diagnostics: [...overflow, ...images.flatMap((image) => image.diagnostics)] + }; +} diff --git a/web/src/lib/contracts/food-availability-v1/partition.ts b/web/src/lib/contracts/food-availability-v1/partition.ts @@ -0,0 +1,29 @@ +export type ClassifiedPartition = + | 'focused_food_availability' + | 'operational_listing' + | 'generic_nip99' + | 'ambiguous'; +// Raw tag-name presence counts even when a marker has no value. +// This pure classifier alone makes no event-verification or admission claim. +export function markerPartition( + tags: readonly (readonly string[])[] +): ClassifiedPartition { + let focused = false; + let operational = false; + for (const tag of tags) { + if (tag[0] === 'radroots:price_unit' || tag[0] === 'radroots:quantity') + focused = true; + if ( + tag[0] === 'radroots:primary_bin' || + tag[0] === 'radroots:bin' || + tag[0] === 'radroots:price' + ) + operational = true; + if (focused && operational) return 'ambiguous'; + } + return focused + ? 'focused_food_availability' + : operational + ? 'operational_listing' + : 'generic_nip99'; +} diff --git a/web/src/lib/contracts/food-availability-v1/read.ts b/web/src/lib/contracts/food-availability-v1/read.ts @@ -0,0 +1,281 @@ +import { markerPartition } from './partition.ts'; +import { + projectImages, + type InboundImage, + type ImageDiagnostic +} from './media.ts'; +import { + boundedUtf8, + foodContentPresent, + foodIdentifierValid, + foodTextValid, + incomingAmount +} from './text.ts'; +import { + foodCurrency, + foodUnit, + type FoodPrice, + type FoodQuantity +} from './values.ts'; +import { + boundedEnvelopeNumbers, + foodPublishedAt +} from '../../nostr/envelope-bounds.ts'; +import { + boundedEnvelopeTags, + verifyEnvelope, + verifiedEnvelopeSnapshot, + type VerifiedEnvelope +} from '../../nostr/verified-envelope.ts'; +export type FoodParts = Readonly<{ + kind: number; + created_at: number; + content: string; + tags: readonly (readonly string[])[]; +}>; +export type FoodProjection = Readonly<{ + content: string; + identifier: string; + title: string; + summary: string; + published_at: number; + location: string; + price: FoodPrice; + quantity: FoodQuantity | null; + status: 'active' | 'sold'; + images: readonly InboundImage[]; + diagnostics: readonly ImageDiagnostic[]; +}>; +export type FoodError = Readonly<{ code: string; message: string }>; +export type FoodProjectionOutcome = + | Readonly<{ outcome: 'focused'; projection: FoodProjection }> + | Readonly<{ + outcome: 'excluded'; + partition: 'operational_listing' | 'generic_nip99'; + }> + | Readonly<{ outcome: 'rejected'; error: FoodError }>; +export type FoodAdmission = + | Readonly<{ + outcome: 'admitted'; + event_id: string; + verified: VerifiedEnvelope; + projection: FoodProjection; + }> + | Readonly<{ + outcome: 'excluded'; + event_id: string; + verified: VerifiedEnvelope; + partition: 'operational_listing' | 'generic_nip99'; + }> + | Readonly<{ outcome: 'rejected'; error: FoodError }>; +const prohibited = [ + 'buyer', + 'checkout', + 'delivery', + 'exception', + 'group', + 'invite', + 'order', + 'payment', + 'pickup', + 'proof', + 'provenance', + 'receipt', + 'route', + 'route_stop', + 'task' +]; +function rejected(code: string, message: string): FoodProjectionOutcome { + return { outcome: 'rejected', error: { code, message } }; +} +// Pure untrusted-parts projection for contract conformance. Its result carries +// no event id or verified proof and cannot substitute for readFoodEvent admission. +export function projectFoodParts(event: FoodParts): FoodProjectionOutcome { + if (!boundedEnvelopeNumbers(event.kind, event.created_at)) + return rejected( + 'envelope_invalid', + 'invalid or unsupported bounded NIP-01 envelope' + ); + if (!boundedUtf8(event.content, 262144) || !boundedEnvelopeTags(event.tags)) + return rejected( + 'envelope_invalid', + 'invalid or unsupported bounded NIP-01 envelope' + ); + if (event.kind !== 30402) + return rejected( + 'invalid_kind', + `FoodAvailability event kind must be 30402, got ${event.kind}` + ); + const partition = markerPartition(event.tags); + if (partition === 'ambiguous') + return rejected( + 'food_profile_ambiguous', + 'classified listing mixes focused and operational markers' + ); + if (partition !== 'focused_food_availability') + return { outcome: 'excluded', partition }; + for (const tag of event.tags) + if (prohibited.includes(tag[0])) + return rejected( + 'prohibited_capability', + `FoodAvailability tag \`${tag[0]}\` is a prohibited capability` + ); + const matching = (name: string) => + event.tags.filter((tag) => tag[0] === name); + const names = ['d', 'title', 'summary', 'published_at', 'location', 'status']; + for (const name of names) { + const tags = matching(name); + if (tags.length !== 1 || tags[0].length !== 2) + return rejected( + 'food_tag_invalid', + 'FoodAvailability core tag shape is invalid' + ); + } + const [identifier, title, summary, publishedValue, location, status] = + names.map((name) => matching(name)[0][1]); + if (!foodContentPresent(event.content)) + return rejected( + 'food_content_missing', + 'FoodAvailability content must be non-whitespace' + ); + if (!boundedUtf8(event.content, 131072)) + return rejected( + 'food_content_too_large', + 'FoodAvailability content exceeds 131072 bytes' + ); + if (!foodIdentifierValid(identifier)) + return rejected( + 'food_identifier_invalid', + 'FoodAvailability identifier must be nonempty and contain no whitespace, control, or format characters' + ); + if (!foodTextValid(title) || !foodTextValid(summary)) + return rejected( + 'food_text_invalid', + 'FoodAvailability text must be trimmed, nonempty, and contain no control or format characters' + ); + const publishedAt = foodPublishedAt(publishedValue); + if (publishedAt === undefined) + return rejected( + 'food_published_at_invalid', + 'FoodAvailability published_at must be a canonical nonzero u64 timestamp' + ); + if (publishedAt > event.created_at) + return rejected( + 'food_published_at_future', + `FoodAvailability published_at ${publishedAt} exceeds created_at ${event.created_at}` + ); + if (!foodTextValid(location)) + return rejected( + 'food_text_invalid', + 'FoodAvailability text must be trimmed, nonempty, and contain no control or format characters' + ); + const prices = matching('price'); + if (prices.length !== 1) + return rejected( + 'price_invalid', + 'FoodAvailability price must be a canonical unsigned decimal with at most 28 digits' + ); + if (prices[0].length > 3) + return rejected( + 'price_frequency_forbidden', + 'FoodAvailability price frequency is forbidden' + ); + const amount = + prices[0].length === 3 ? incomingAmount(prices[0][1]) : undefined; + if (amount === undefined) + return rejected( + 'price_invalid', + 'FoodAvailability price must be a canonical unsigned decimal with at most 28 digits' + ); + const currency = foodCurrency( + prices[0][2].length === 3 && /^[a-zA-Z]{3}$/u.test(prices[0][2]) + ? prices[0][2].toUpperCase() + : '' + ); + if (currency === undefined) + return rejected( + 'price_currency_invalid', + 'FoodAvailability price currency must be three uppercase ASCII letters' + ); + const units = matching('radroots:price_unit'); + if (units.length === 0) + return rejected( + 'price_unit_missing', + 'FoodAvailability price unit is missing' + ); + const unit = + units.length === 1 && units[0].length === 2 + ? foodUnit(units[0][1]) + : undefined; + if (unit === undefined) + return rejected( + 'price_unit_invalid', + 'FoodAvailability price unit is not governed' + ); + const quantities = matching('radroots:quantity'); + let quantity: FoodQuantity | null = null; + if (quantities.length > 0) { + const tag = quantities[0]; + const value = + quantities.length === 1 && tag.length === 3 + ? incomingAmount(tag[1]) + : undefined; + if (value === undefined || foodUnit(tag[2]) !== unit) + return rejected( + 'quantity_invalid', + 'FoodAvailability quantity must be canonical and use the price unit' + ); + if (value === '0') + return rejected( + 'quantity_zero', + 'FoodAvailability quantity must be positive' + ); + quantity = { amount: value, unit }; + } + if (status !== 'active' && status !== 'sold') + return rejected( + 'food_status_invalid', + 'FoodAvailability status must be active or sold' + ); + const media = projectImages(matching('image')); + return { + outcome: 'focused', + projection: { + content: event.content, + identifier, + title, + summary, + published_at: publishedAt, + location, + price: { amount, currency, unit }, + quantity, + status, + images: media.images, + diagnostics: media.diagnostics + } + }; +} +export function readFoodEvent(raw: unknown): FoodAdmission { + const result = verifyEnvelope(raw); + if (!result.ok) return { outcome: 'rejected', error: result.error }; + const event = verifiedEnvelopeSnapshot(result.value); + if (!event) + return { + outcome: 'rejected', + error: { + code: 'envelope_invalid', + message: 'invalid verified envelope proof' + } + }; + const projected = projectFoodParts(event); + if (projected.outcome === 'focused') + return { + outcome: 'admitted', + event_id: event.id, + verified: result.value, + projection: projected.projection + }; + if (projected.outcome === 'excluded') + return { ...projected, event_id: event.id, verified: result.value }; + return projected; +} diff --git a/web/src/lib/contracts/food-availability-v1/text.ts b/web/src/lib/contracts/food-availability-v1/text.ts @@ -0,0 +1,49 @@ +import { canonicalFoodAmount, type CanonicalFoodAmount } from './values.ts'; +const encoder = new TextEncoder(); +export function boundedUtf8(value: string, maximum: number): boolean { + return ( + value.length <= maximum && + value.isWellFormed() && + encoder.encode(value).length <= maximum + ); +} +export function foodTextValid(value: string): boolean { + return ( + value.length > 0 && + boundedUtf8(value, 4096) && + !/[\p{Cc}\p{Cf}]/u.test(value) && + !/^\p{White_Space}|\p{White_Space}$/u.test(value) + ); +} +export function foodIdentifierValid(value: string): boolean { + return ( + value.length > 0 && + boundedUtf8(value, 512) && + !/[\p{White_Space}\p{Cc}\p{Cf}]/u.test(value) + ); +} +export function foodContentPresent(value: string): boolean { + // Rust contract whitespace also includes U+001C..U+001F. + return Array.from(value).some( + (character) => + !/\p{White_Space}/u.test(character) && + !(character.codePointAt(0)! >= 28 && character.codePointAt(0)! <= 31) + ); +} +export function incomingAmount(value: string): CanonicalFoodAmount | undefined { + if ( + value.length === 0 || + value.length > 29 || + !/^[0-9]+(?:\.[0-9]+)?$/u.test(value) + ) + return undefined; + if (value.length - (value.includes('.') ? 1 : 0) > 28) return undefined; + const [integer, fraction] = value.split('.'); + let start = 0; + while (start < integer.length && integer[start] === '0') start++; + const whole = integer.slice(start) || '0'; + let end = fraction?.length ?? 0; + while (end > 0 && fraction?.[end - 1] === '0') end--; + const tail = fraction?.slice(0, end); + return canonicalFoodAmount(tail ? `${whole}.${tail}` : whole); +} diff --git a/web/src/lib/nostr/verified-envelope.ts b/web/src/lib/nostr/verified-envelope.ts @@ -0,0 +1,166 @@ +import { + getEventHash, + verifyEvent, + type NostrEvent +} from 'applesauce-core/helpers'; +import { boundedEnvelopeNumbers } from './envelope-bounds.ts'; +import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts'; + +declare const verified: unique symbol; +export type VerifiedEnvelope = Readonly<{ readonly [verified]: true }>; +export type EnvelopeFailure = Readonly<{ + code: 'envelope_invalid' | 'event_id_mismatch' | 'signature_invalid'; + message: string; +}>; +// Weak ownership bounds lifetime to callers. Retained bytes cannot be mutated +// through detached snapshots, nor forged by a type assertion or SDK cache flag. +const snapshots = new WeakMap<VerifiedEnvelope, string>(); +const invalid: EnvelopeFailure = Object.freeze({ + code: 'envelope_invalid', + message: 'invalid or unsupported bounded NIP-01 envelope' +}); +export function boundedEnvelopeTags(tags: unknown): tags is string[][] { + if (!Array.isArray(tags) || tags.length > 1024) return false; + let elements = 0; + let bytes = 0; + const encoder = new TextEncoder(); + for (const tag of tags) { + if ( + !Array.isArray(tag) || + tag.length === 0 || + typeof tag[0] !== 'string' || + tag[0].length === 0 || + /\p{Cc}/u.test(tag[0]) + ) + return false; + elements += tag.length; + if (elements > 4096) return false; + for (const element of tag) { + if (typeof element !== 'string' || !boundedUtf8(element, 4096)) + return false; + bytes += encoder.encode(element).length; + if (bytes > 131072) return false; + } + } + return true; +} +export function verifyEnvelope( + raw: unknown +): + | Readonly<{ ok: true; value: VerifiedEnvelope }> + | Readonly<{ ok: false; error: EnvelopeFailure }> { + if (typeof raw !== 'string' || !boundedUtf8(raw, 262144)) + return { ok: false, error: invalid }; + try { + // Parse a fresh bounded JSON object: caller getters and cached SDK symbols + // never cross verification. Generic SDK helpers own hashing and crypto. + const unsupportedNumbers = new WeakMap<object, boolean>(); + const event: unknown = JSON.parse( + raw, + function ( + this: object, + key: string, + value: unknown, + context?: { source?: string } + ) { + if ( + (key === 'kind' || key === 'created_at') && + typeof value === 'number' && + (context?.source === undefined || !/^[0-9]+$/u.test(context.source)) + ) + unsupportedNumbers.set(this, true); + if ( + !key.isWellFormed() || + (typeof value === 'string' && !value.isWellFormed()) + ) + throw new Error('Invalid Unicode in bounded envelope'); + if (typeof value === 'number' && !Number.isFinite(value)) + throw new Error('Nonfinite number in bounded envelope'); + return value; + } + ); + if ( + typeof event !== 'object' || + event === null || + Array.isArray(event) || + !('id' in event) || + !('pubkey' in event) || + !('sig' in event) || + !('kind' in event) || + !('created_at' in event) || + !('tags' in event) || + !('content' in event) + ) + return { ok: false, error: invalid }; + if ( + typeof event.id !== 'string' || + !/^[0-9a-f]{64}$/u.test(event.id) || + typeof event.pubkey !== 'string' || + !/^[0-9a-f]{64}$/u.test(event.pubkey) || + typeof event.sig !== 'string' || + !/^[0-9a-f]{128}$/u.test(event.sig) || + !boundedEnvelopeNumbers(event.kind, event.created_at) || + !boundedEnvelopeTags(event.tags) || + typeof event.content !== 'string' || + !boundedUtf8(event.content, 131072) + ) + return { ok: false, error: invalid }; + if (unsupportedNumbers.has(event)) return { ok: false, error: invalid }; + const fields = event as Record<string, unknown>; + let extraFields = 0; + let extraBytes = 0; + const encoder = new TextEncoder(); + for (const name in fields) { + if ( + [ + 'id', + 'pubkey', + 'sig', + 'kind', + 'created_at', + 'tags', + 'content' + ].includes(name) + ) + continue; + extraFields++; + const encoded = JSON.stringify(fields[name]); + if (!name.isWellFormed() || encoded === undefined) + return { ok: false, error: invalid }; + extraBytes += + encoder.encode(JSON.stringify(name)).length + + 1 + + encoder.encode(encoded).length; + if (extraFields > 64 || extraBytes > 65536) + return { ok: false, error: invalid }; + } + const candidate = event as NostrEvent; + if (getEventHash(candidate) !== candidate.id) + return { + ok: false, + error: { + code: 'event_id_mismatch', + message: 'NIP-01 event id does not match canonical content' + } + }; + if (!verifyEvent(candidate)) + return { + ok: false, + error: { + code: 'signature_invalid', + message: 'invalid NIP-01 event signature' + } + }; + const token = Object.freeze({}) as VerifiedEnvelope; + snapshots.set(token, raw); + return { ok: true, value: token }; + } catch { + return { ok: false, error: invalid }; + } +} +export function verifiedEnvelopeSnapshot( + token: VerifiedEnvelope +): NostrEvent | undefined { + const raw = snapshots.get(token); + return raw === undefined ? undefined : (JSON.parse(raw) as NostrEvent); +} diff --git a/web/tests/conformance/food-reader.test.ts b/web/tests/conformance/food-reader.test.ts @@ -0,0 +1,151 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import test from 'node:test'; +import { readFoodEvent } from '../../src/lib/contracts/food-availability-v1/read.ts'; +import { + verifyEnvelope, + verifiedEnvelopeSnapshot +} from '../../src/lib/nostr/verified-envelope.ts'; + +interface Vector { + id: string; + kind: string; + expected: Record<string, unknown>; + signed_wires: Record<string, string>; +} +const corpus = JSON.parse( + await readFile( + new URL( + '../../../contracts/interop/food_availability/corpus.v1.json', + import.meta.url + ), + 'utf8' + ) +) as { vectors: Vector[] }; +for (const row of corpus.vectors) { + if (!row.signed_wires.event) continue; + void test(`pinned Rust reader outcome: ${row.id}`, () => { + const actual = readFoodEvent(row.signed_wires.event); + const expected = row.expected; + if ('error' in expected) { + assert.equal(actual.outcome, 'rejected'); + if (actual.outcome === 'rejected') + assert.deepEqual(actual.error, expected.error); + } else if ('projection' in expected) { + assert.equal(actual.outcome, 'admitted'); + if (actual.outcome === 'admitted') { + assert.equal(actual.event_id, expected.event_id); + assert.deepEqual(actual.projection, expected.projection); + } + } else if ('partition' in expected) { + assert.equal(actual.outcome, 'excluded'); + if (actual.outcome === 'excluded') { + assert.equal(actual.event_id, expected.event_id); + assert.equal(actual.partition, expected.partition); + } + } else { + assert.equal(actual.outcome, 'admitted'); + if (actual.outcome === 'admitted') { + assert.equal(actual.event_id, expected.event_id); + assert.equal(actual.projection.images.length, expected.image_count); + assert.deepEqual( + actual.projection.images[0].raw_tag, + expected.first_raw_tag + ); + assert.deepEqual( + actual.projection.images.at(-1)?.raw_tag, + expected.last_raw_tag + ); + assert.deepEqual(actual.projection.diagnostics, expected.diagnostics); + } + } + }); +} +void test('all public signed wires cross actual SDK verification; detached snapshots cannot change retained proof', () => { + let checked = 0; + for (const row of corpus.vectors) + for (const raw of Object.values(row.signed_wires)) { + const result = verifyEnvelope(raw); + if (row.id.endsWith('_031')) { + assert.equal(result.ok, false); + } else { + assert.equal(result.ok, true, row.id); + if (result.ok) { + const a = verifiedEnvelopeSnapshot(result.value)!; + a.tags.length = 0; + a.content = 'mutated'; + a.created_at = 0; + assert.deepEqual( + verifiedEnvelopeSnapshot(result.value), + JSON.parse(raw), + row.id + ); + assert.equal(verifiedEnvelopeSnapshot({} as never), undefined); + } + } + checked++; + } + assert.equal(checked, 36); +}); + +const sample = corpus.vectors.find((row) => row.id.endsWith('_014'))! + .signed_wires.event; +void test('root numeric spelling cannot be laundered by JSON numeric rounding', () => { + for (const spelling of [ + '1700000060.0', + '1.700000060e9', + '1700000060.00000000001' + ]) { + const altered = sample.replace( + /"created_at":\s*[0-9]+/u, + `"created_at":${spelling}` + ); + assert.notEqual(altered, sample); + assert.equal(verifyEnvelope(altered).ok, false, spelling); + } + const altered = sample.replace(/"kind":\s*30402/u, '"kind":30402.0'); + assert.notEqual(altered, sample); + assert.equal(verifyEnvelope(altered).ok, false); +}); +void test('root numeric source is separate from nested unknown extension fields', () => { + const altered = sample.replace( + /\}$/u, + ',"extension":{"kind":1.0,"created_at":2e0}}' + ); + assert.equal(verifyEnvelope(altered).ok, true); +}); +void test('extra-field counts and serialized key/value byte charge match pinned wire limits', () => { + const original = JSON.parse(sample) as Record<string, unknown>; + const tooMany = { + ...original, + ...Object.fromEntries(Array.from({ length: 65 }, (_, i) => [`x${i}`, 0])) + }; + assert.equal(verifyEnvelope(JSON.stringify(tooMany)).ok, false); + const value = 'x'.repeat(65536 - 6); // JSON key \"x\": plus JSON value quotes = six bytes. + assert.equal( + verifyEnvelope(JSON.stringify({ ...original, x: value })).ok, + true + ); + assert.equal( + verifyEnvelope(JSON.stringify({ ...original, x: value + 'x' })).ok, + false + ); + const maximum = { + ...original, + ...Object.fromEntries(Array.from({ length: 64 }, (_, i) => [`x${i}`, 0])) + }; + assert.equal(verifyEnvelope(JSON.stringify(maximum)).ok, true); +}); + +void test('parsed nonfinite extras and ill formed Unicode are rejected before verified proof', () => { + for (const suffix of [ + '"extension":1e309', + '"extension":{"value":-1e309}', + '"extension":"\\ud800"', + '"\\ud800":0' + ]) { + const altered = sample.replace(/\}$/u, `,` + suffix + '}'); + assert.notEqual(altered, sample); + assert.equal(verifyEnvelope(altered).ok, false, suffix); + } +}); diff --git a/web/tests/unit/food-reader.test.ts b/web/tests/unit/food-reader.test.ts @@ -0,0 +1,386 @@ +import { describe, expect, it } from 'vitest'; +import { markerPartition } from '../../src/lib/contracts/food-availability-v1/partition.ts'; +import { + projectFoodParts, + readFoodEvent +} from '../../src/lib/contracts/food-availability-v1/read.ts'; +import { incomingAmount } from '../../src/lib/contracts/food-availability-v1/text.ts'; +import { projectImages } from '../../src/lib/contracts/food-availability-v1/media.ts'; +import { verifyEnvelope } from '../../src/lib/nostr/verified-envelope.ts'; + +const base = { + kind: 30402, + created_at: 1700000060, + content: 'Food this week.', + tags: [ + ['d', 'carrots'], + ['title', 'Carrots'], + ['summary', 'Fresh carrots'], + ['published_at', '1700000000'], + ['location', 'Victoria'], + ['price', '003.500', 'cad'], + ['radroots:price_unit', 'lb'], + ['status', 'active'] + ] +}; +function changed(name: string, value: string[]) { + return { + ...base, + tags: base.tags.map((tag) => (tag[0] === name ? value : [...tag])) + }; +} +function code(value: ReturnType<typeof projectFoodParts>) { + return value.outcome === 'rejected' ? value.error.code : value.outcome; +} +describe('raw marker partition precedes shape and focused-domain checks', () => { + for (const name of ['radroots:price_unit', 'radroots:quantity']) + it(name, () => + expect(markerPartition([[name]])).toBe('focused_food_availability') + ); + for (const name of ['radroots:primary_bin', 'radroots:bin', 'radroots:price']) + it(name, () => { + expect(markerPartition([[name]])).toBe('operational_listing'); + expect( + code(projectFoodParts({ ...base, tags: [[name], ['delivery']] })) + ).toBe('excluded'); + expect( + code( + projectFoodParts({ ...base, tags: [[name], ['radroots:quantity']] }) + ) + ).toBe('food_profile_ambiguous'); + }); + it('exact names only and empty tags', () => + expect( + markerPartition([[], ['Radroots:quantity'], ['radroots:quantity ']]) + ).toBe('generic_nip99')); + it('unknown core fields never prevent generic exclusion', () => + expect( + code( + projectFoodParts({ + ...base, + tags: [ + ['status', 'unknown'], + ['price', 'bad'] + ] + }) + ) + ).toBe('excluded')); +}); +describe('tolerant values retain precision and unknown versus zero', () => { + for (const [input, expected] of [ + ['000.000', '0'], + ['003.500', '3.5'], + ['0000000000000000000000000001', '1'], + ['9999999999999999999999999999', '9999999999999999999999999999'] + ]) + it(input, () => expect(incomingAmount(input)).toBe(expected)); + for (const input of [ + '', + '.1', + '1.', + '+1', + '-1', + '1e3', + '1,000', + ' 1', + '١', + '0'.repeat(29), + '1.2.3' + ]) + it('rejects ' + input, () => expect(incomingAmount(input)).toBeUndefined()); + it('normalizes inbound only', () => { + const r = projectFoodParts(base); + expect(r.outcome).toBe('focused'); + if (r.outcome === 'focused') { + expect(r.projection.price).toEqual({ + amount: '3.5', + currency: 'CAD', + unit: 'lb' + }); + expect(r.projection.quantity).toBeNull(); + } + }); + for (const status of ['withdrawn', 'ACTIVE', 'unknown', '']) + it('unknown status ' + status, () => + expect( + code(projectFoodParts(changed('status', ['status', status]))) + ).toBe('food_status_invalid') + ); + it('zero price is valid while quantity zero is not missing', () => { + expect( + code(projectFoodParts(changed('price', ['price', '0', 'CAD']))) + ).toBe('focused'); + expect( + code( + projectFoodParts({ + ...base, + tags: [...base.tags, ['radroots:quantity', '000.0', 'lb']] + }) + ) + ).toBe('quantity_zero'); + }); + it('bad quantity cannot become zero or missing', () => + expect( + code( + projectFoodParts({ + ...base, + tags: [...base.tags, ['radroots:quantity', 'bad', 'lb']] + }) + ) + ).toBe('quantity_invalid')); + it('singleton shape checks precede invalid content', () => + expect( + code( + projectFoodParts({ + ...base, + content: '', + tags: [...base.tags, ['title', 'duplicate']] + }) + ) + ).toBe('food_tag_invalid')); + it('unsafe numeric time and unsupported publication time fail', () => { + expect( + code( + projectFoodParts({ + ...base, + created_at: Number('18446744073709551615') + }) + ) + ).toBe('envelope_invalid'); + expect( + code( + projectFoodParts( + changed('published_at', ['published_at', '18446744073709551615']) + ) + ) + ).toBe('food_published_at_invalid'); + }); + for (const value of [ + '\ufeffCarrots', + 'Carrots\u200b', + 'Carrots\n', + ' Carrots', + 'Carrots\u0085' + ]) + it('rejects invalid text ' + JSON.stringify(value), () => + expect(code(projectFoodParts(changed('title', ['title', value])))).toBe( + 'food_text_invalid' + ) + ); + it('identifier is byte bounded without imposing text trimming', () => + expect(code(projectFoodParts(changed('d', ['d', 'é'.repeat(257)])))).toBe( + 'food_identifier_invalid' + )); +}); +describe('bounded incoming image diagnostics are structural only', () => { + const hash = 'a'.repeat(64); + it('first64 and ordered overflow diagnosis', () => { + const r = projectImages( + Array.from({ length: 65 }, (_, i) => [ + 'image', + `https://media.example/${i.toString(16).padStart(64, '0')}.webp`, + '800x600' + ]) + ); + expect(r.images).toHaveLength(64); + expect(r.diagnostics).toEqual(['food_image_count_exceeded']); + }); + it('raw duplicates and digest duplicates differ', () => { + const r = projectImages([ + ['image', `https://a.example/${hash}.png`, '1x1'], + ['image', `https://b.example/${hash}.webp`, '1x1'], + ['image', 'bad', '01x1'], + ['image', 'bad'] + ]); + expect(r.images[1].diagnostics).toEqual(['food_image_duplicate_digest']); + expect(r.images[3].diagnostics).toEqual([ + 'food_image_shape_invalid', + 'food_image_url_invalid', + 'food_image_dimensions_missing', + 'food_image_duplicate_url' + ]); + }); + for (const url of [ + 'https://user:pass@a.example/a', + 'https://a.example', + 'https://é.example/a', + 'https://a..example/a', + 'javascript:alert(1)', + 'https://a.example/\u200ba' + ]) + it('rejects URL ' + url, () => + expect(projectImages([['image', url, '1x1']]).images[0].url).toBeNull() + ); + for (const dims of ['0x1', '01x1', '1X1', '4294967296x1', '1x1x1']) + it('rejects dimensions ' + dims, () => + expect( + projectImages([['image', 'https://a.example/a', dims]]).images[0] + .dimensions + ).toBeNull() + ); + it('accepts full u32 dimensions', () => + expect( + projectImages([['image', 'https://a.example/a', '4294967295x1']]) + .images[0].dimensions + ).toEqual({ width: 4294967295, height: 1 })); +}); +describe('raw input has no implied verification trust', () => { + for (const raw of [ + undefined, + {}, + 'null', + '[]', + '{', + ' '.repeat(262145), + '"\\ud800"' + ]) + it('rejects malformed bounded envelope', () => + expect(verifyEnvelope(raw).ok).toBe(false)); + it('invalid signature is rejected before generic/operational classification', () => + expect( + readFoodEvent( + JSON.stringify({ + id: '0'.repeat(64), + pubkey: '0'.repeat(64), + sig: '0'.repeat(128), + created_at: 1, + kind: 30402, + content: '', + tags: [['radroots:bin']] + }) + ).outcome + ).toBe('rejected')); +}); + +describe('exact shared reader text and numeric boundaries', () => { + it('content maximum uses UTF8 bytes and never prototype form limits', () => { + expect( + code(projectFoodParts({ ...base, content: 'a'.repeat(131072) })) + ).toBe('focused'); + expect( + code(projectFoodParts({ ...base, content: 'é'.repeat(65537) })) + ).toBe('food_content_too_large'); + }); + it('all contract whitespace is missing while internal content controls are preserved', () => { + expect( + code(projectFoodParts({ ...base, content: '\u001c\u001f\u0085' })) + ).toBe('food_content_missing'); + expect(code(projectFoodParts({ ...base, content: 'a\u0000b' }))).toBe( + 'focused' + ); + }); + it('text byte limit and identifiers do not use display character counts', () => { + expect( + code(projectFoodParts(changed('title', ['title', 'é'.repeat(2048)]))) + ).toBe('focused'); + expect( + code(projectFoodParts(changed('title', ['title', 'é'.repeat(2049)]))) + ).toBe('envelope_invalid'); + expect(code(projectFoodParts(changed('d', ['d', 'é'.repeat(256)])))).toBe( + 'focused' + ); + }); + for (const input of ['0', '01', '+1', '1e3', '1700000061']) + it('publication ' + input, () => + expect( + code(projectFoodParts(changed('published_at', ['published_at', input]))) + ).toBe( + input === '1700000061' + ? 'food_published_at_future' + : 'food_published_at_invalid' + ) + ); + for (const input of ['cad', 'cAd', 'AAA']) + it('actual inbound ASCII currency ' + input, () => + expect( + code(projectFoodParts(changed('price', ['price', '1', input]))) + ).toBe('focused') + ); + for (const input of ['CA', 'CAD', '12A', 'CA D']) + it('reject currency ' + input, () => + expect( + code(projectFoodParts(changed('price', ['price', '1', input]))) + ).toBe('price_currency_invalid') + ); + it('unit values are exact and quantity does not normalize case or mismatched units', () => { + expect( + code( + projectFoodParts( + changed('radroots:price_unit', ['radroots:price_unit', 'LB']) + ) + ) + ).toBe('price_unit_invalid'); + expect( + code( + projectFoodParts({ + ...base, + tags: [...base.tags, ['radroots:quantity', '1', 'kg']] + }) + ) + ).toBe('quantity_invalid'); + }); + it('duplicate quantity is invalid even when both match', () => + expect( + code( + projectFoodParts({ + ...base, + tags: [ + ...base.tags, + ['radroots:quantity', '1', 'lb'], + ['radroots:quantity', '1', 'lb'] + ] + }) + ) + ).toBe('quantity_invalid')); + it('ill formed Unicode cannot pass through UTF8 replacement', () => { + expect(code(projectFoodParts(changed('d', ['d', '\ud800'])))).toBe( + 'envelope_invalid' + ); + expect(code(projectFoodParts(changed('title', ['title', '\ud800'])))).toBe( + 'envelope_invalid' + ); + }); +}); + +it('bounded constant errors cannot be altered through a prior rejection', () => { + const prior = verifyEnvelope('null'); + if (!prior.ok) + expect(() => { + (prior.error as { message: string }).message = 'unbounded replacement'; + }).toThrow(); + const next = verifyEnvelope('null'); + if (!next.ok) + expect(next.error).toEqual({ + code: 'envelope_invalid', + message: 'invalid or unsupported bounded NIP-01 envelope' + }); +}); + +describe('direct pure parts remain bounded before marker/value scans', () => { + it('tag count limit is enforced before generic exclusion', () => + expect( + code( + projectFoodParts({ + ...base, + tags: Array.from({ length: 1025 }, () => ['t', 'food']) + }) + ) + ).toBe('envelope_invalid')); + it('raw content work cap is separate from shared content limit', () => + expect( + code(projectFoodParts({ ...base, content: 'x'.repeat(262145) })) + ).toBe('envelope_invalid')); + it('tag byte and total element limits precede profile checks', () => { + expect( + code(projectFoodParts({ ...base, tags: [['t', 'é'.repeat(2049)]] })) + ).toBe('envelope_invalid'); + expect( + code( + projectFoodParts({ + ...base, + tags: [['t', ...Array.from({ length: 4096 }, () => 'x')]] + }) + ) + ).toBe('envelope_invalid'); + }); +});