app

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

commit f7788d47c28a9949dd7581d48617140ff630a9f3
parent ad8aece558f2d9b37ad4bb3dac9e1e2cfc62f751
Author: triesap <tyson@radroots.org>
Date:   Tue,  6 Oct 2026 00:33:05 +0000

availability: implement the strict text-only food template builder (HCP-025)

- Build strict unsigned Food parts with stable identity and managed times
- Derive Unicode-safe summaries and snapshot explicitly public contact fields
- Consume website templates through the pinned Rust codec without signing
- Install fixture dependencies offline and invoke the pinned compiler directly

Diffstat:
Mcontracts/interop/food_availability/oracle/src/main.rs | 130++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcontracts/interop/food_availability/provenance.v1.json | 4++--
Aweb/src/lib/contracts/food-availability-v1/contact.ts | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/contracts/food-availability-v1/write.ts | 173+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/conformance/food-writer-cases.ts | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/conformance/food-writer.test.ts | 32++++++++++++++++++++++++++++++++
Mweb/tests/e2e/notices.spec.ts | 15+++++++++------
Mweb/tests/e2e/primitives.spec.ts | 15+++++++++------
Mweb/tests/e2e/search-form.spec.ts | 15+++++++++------
Mweb/tests/e2e/shell.spec.ts | 15+++++++++------
Aweb/tests/unit/food-writer.test.ts | 298+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
11 files changed, 806 insertions(+), 27 deletions(-)

diff --git a/contracts/interop/food_availability/oracle/src/main.rs b/contracts/interop/food_availability/oracle/src/main.rs @@ -340,6 +340,128 @@ fn encoded() -> String { serde_json::to_string_pretty(&generate()).unwrap() + "\n" } +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct WebTemplate { + id: String, + created_at: u64, + wire_parts: WebParts, + summary: String, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct WebParts { + kind: u32, + content: String, + tags: Vec<Vec<String>>, +} + +fn consume_template(template: &WebTemplate) -> Result<Value, String> { + if template.id.is_empty() + || template.id.len() > 128 + || template.created_at > 9_007_199_254_740_991 + || template.wire_parts.kind != 30402 + || template.wire_parts.content.len() > 16 * 1024 + || template.wire_parts.tags.len() > 9 + { + return Err("unsupported bounded website template".into()); + } + let value = |name: &str| -> Result<&str, String> { + let tags = template + .wire_parts + .tags + .iter() + .filter(|tag| tag.first().is_some_and(|key| key == name)) + .collect::<Vec<_>>(); + match tags.as_slice() { + [tag] if tag.len() == 2 => Ok(tag[1].as_str()), + _ => Err("invalid website singleton tag".into()), + } + }; + let price_tags = template + .wire_parts + .tags + .iter() + .filter(|tag| tag.first().is_some_and(|key| key == "price")) + .collect::<Vec<_>>(); + let price = match price_tags.as_slice() { + [tag] if tag.len() == 3 => *tag, + _ => return Err("invalid website price tag".into()), + }; + let quantity_tags = template + .wire_parts + .tags + .iter() + .filter(|tag| tag.first().is_some_and(|key| key == "radroots:quantity")) + .collect::<Vec<_>>(); + let quantity = match quantity_tags.as_slice() { + [] => None, + [tag] if tag.len() == 3 => Some( + FoodQuantity::new( + &tag[1], + FoodUnit::parse(&tag[2]).map_err(|error| error.to_string())?, + ) + .map_err(|error| error.to_string())?, + ), + _ => return Err("invalid website quantity tag".into()), + }; + if value("summary")? != template.summary { + return Err("website review summary differs from public template".into()); + } + // Actual pinned public constructors and codec consume the website fields. + // No synthetic signature, signer, native runtime or private key is involved. + let details = FoodAvailabilityDetails::new(FoodAvailabilityDetailsParts { + content: FoodContent::new(&template.wire_parts.content) + .map_err(|error| error.to_string())?, + identifier: FoodIdentifier::parse(value("d")?).map_err(|error| error.to_string())?, + title: FoodText::new(value("title")?).map_err(|error| error.to_string())?, + summary: FoodText::new(value("summary")?).map_err(|error| error.to_string())?, + published_at: FoodPublishedAt::parse(value("published_at")?) + .map_err(|error| error.to_string())?, + location: FoodText::new(value("location")?).map_err(|error| error.to_string())?, + price: FoodPrice::new( + &price[1], + FoodCurrency::parse(&price[2]).map_err(|error| error.to_string())?, + FoodUnit::parse(value("radroots:price_unit")?).map_err(|error| error.to_string())?, + ) + .map_err(|error| error.to_string())?, + quantity, + status: FoodAvailabilityStatus::parse(value("status")?) + .map_err(|error| error.to_string())?, + images: Vec::new(), + }) + .map_err(|error| error.to_string())?; + let actual = authored_food_availability_to_wire_parts(&details, template.created_at) + .map_err(|error| error.to_string())?; + if actual.kind != template.wire_parts.kind + || actual.content != template.wire_parts.content + || actual.tags != template.wire_parts.tags + { + return Err("website wire parts differ from actual pinned Rust codec".into()); + } + Ok( + json!({"id":template.id,"result":"accepted","wire_parts":{"kind":actual.kind,"content":actual.content,"tags":actual.tags}}), + ) +} + +fn consume_templates(path: &Path) -> Value { + let metadata = fs::symlink_metadata(path).expect("website input metadata"); + assert!(metadata.file_type().is_file() && metadata.len() <= 1024 * 1024); + let raw = fs::read(path).expect("website input read"); + assert_eq!(u64::try_from(raw.len()).unwrap(), metadata.len()); + let templates: Vec<WebTemplate> = + serde_json::from_slice(&raw).expect("website template schema"); + assert!(!templates.is_empty() && templates.len() <= 32); + let results = templates + .iter() + .map(|template| { + consume_template(template) + .unwrap_or_else(|error| panic!("website template rejected: {error}")) + }) + .collect::<Vec<_>>(); + json!({"revision":REVISION,"source":"actual_public_food_constructors_and_unsigned_codec","signing":"NOT_RUN_NO_KEYS","templates":results}) +} + fn main() { let args: Vec<_> = std::env::args().skip(1).collect(); match args.as_slice() { @@ -351,7 +473,13 @@ fn main() { assert_eq!(encoded(), expected, "checked corpus is stale"); println!("PASS40 pinned public Rust vectors and exact generated bytes; no signing"); } - _ => panic!("expected exactly --emit or --check"), + [mode, path] if mode == "--consume-web" => { + println!( + "{}", + serde_json::to_string_pretty(&consume_templates(Path::new(path))).unwrap() + ); + } + _ => panic!("expected --emit, --check or --consume-web <bounded-json-file>"), } } diff --git a/contracts/interop/food_availability/provenance.v1.json b/contracts/interop/food_availability/provenance.v1.json @@ -38,8 +38,8 @@ }, { "path": "oracle/src/main.rs", - "sha256": "27fb65604b2608af700b09862d6845be967c9a70e75196cc29d98a07e54f6c3d", - "bytes": 16278 + "sha256": "fd2ea8f79c72c17a682e9f27fe020e91933475c2a7218937da60fbb2d42e2432", + "bytes": 21448 } ], "workspace": "isolated; immutable public Git dependencies; no sibling/private/native runtime dependency", diff --git a/web/src/lib/contracts/food-availability-v1/contact.ts b/web/src/lib/contracts/food-availability-v1/contact.ts @@ -0,0 +1,76 @@ +import { navigationHref } from '../../navigation-url.ts'; +import { boundedUtf8 } from './text.ts'; +export type PublicContactInput = Readonly<{ + type: 'email' | 'phone' | 'https'; + value: string; + public: true; +}>; +export type PublicContact = Readonly<{ + type: 'email' | 'phone' | 'https'; + href: string; +}>; +function email(value: string): boolean { + // Deliberately bounded ASCII mailbox input, without headers or URI queries. + if ( + value.length > 254 || + /[?#%]/u.test(value) || + !/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9.-]+$/u.test(value) + ) + return false; + const [local, domain] = value.split('@'); + return ( + local.length <= 64 && + !local.startsWith('.') && + !local.endsWith('.') && + !local.includes('..') && + domain + .split('.') + .every( + (label) => + label.length <= 63 && + /^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/u.test(label) + ) + ); +} +export function publicContact(input: unknown): PublicContact | undefined { + if ( + typeof input !== 'object' || + input === null || + Array.isArray(input) || + !('public' in input) || + !('type' in input) || + !('value' in input) + ) + return undefined; + // Access known scalar fields once before validating or composing a URI. + const { public: disclosed, type, value } = input; + if ( + disclosed !== true || + typeof value !== 'string' || + !boundedUtf8(value, 8192) + ) + return undefined; + try { + if ( + /[\p{White_Space}\p{Cc}\p{Cf}]/u.test(value) || + /[\p{Cc}\p{Cf}]/u.test(decodeURIComponent(value)) + ) + return undefined; + } catch { + return undefined; + } + let href: string; + if (type === 'email') { + if (!email(value)) return undefined; + href = `mailto:${value}`; + } else if (type === 'phone') { + if (!/^\+[1-9][0-9]{1,14}$/u.test(value)) return undefined; + href = `tel:${value}`; + } else if (type === 'https') { + if (!/^https:\/\//u.test(value)) return undefined; + href = value; + } else return undefined; + const safe = navigationHref(href); + if (safe === undefined) return undefined; + return { type, href: safe }; +} diff --git a/web/src/lib/contracts/food-availability-v1/write.ts b/web/src/lib/contracts/food-availability-v1/write.ts @@ -0,0 +1,173 @@ +import { publicContact, type PublicContactInput } from './contact.ts'; +import { foodPrice, foodQuantity } from './values.ts'; +import { + boundedUtf8, + foodTextValid, + foodIdentifierValid, + foodContentPresent +} from './text.ts'; +import { + boundedEnvelopeNumbers, + safeUnsignedInteger +} from '../../nostr/envelope-bounds.ts'; +export type FoodDraft = Readonly<{ + identifier: string; + title: string; + description: string; + location: string; + amount: string; + currency: string; + unit: string; + quantity?: string; + published_at: number; + created_at: number; + status: 'active' | 'sold'; + contact?: PublicContactInput; +}>; +export type UnsignedFoodParts = Readonly<{ + kind: 30402; + content: string; + tags: readonly (readonly string[])[]; +}>; +export type FoodDraftErrorCode = + | 'identifier_invalid' + | 'title_invalid' + | 'location_invalid' + | 'description_invalid' + | 'summary_invalid' + | 'price_invalid' + | 'quantity_invalid' + | 'timestamp_invalid' + | 'status_invalid' + | 'contact_invalid' + | 'wire_too_large'; +export type FoodBuildResult = + | Readonly<{ ok: true; wire_parts: UnsignedFoodParts; summary: string }> + | Readonly<{ + ok: false; + error: Readonly<{ code: FoodDraftErrorCode; message: string }>; + }>; +function failure(code: FoodDraftErrorCode): FoodBuildResult { + return { + ok: false, + error: { + code, + message: + 'Public food draft does not satisfy the selected field or size limit' + } + }; +} +function text(value: string, maximum: number): boolean { + return ( + typeof value === 'string' && + foodTextValid(value) && + Array.from(value).length <= maximum + ); +} +function normalizedDescription(value: string): string { + return value.split('\r\n').join('\n').split('\r').join('\n').trim(); +} +function summary(value: string): string { + // The signed content retains its normalized line layout. Only this derived + // review field collapses whitespace; complete Unicode code points survive. + return Array.from( + Array.from(value) + .map((character) => + /\p{White_Space}/u.test(character) ? ' ' : character + ) + .join('') + .split(' ') + .filter((word) => word.length > 0) + .join(' ') + ) + .slice(0, 240) + .join('') + .trimEnd(); +} +export function buildFoodTemplate(input: FoodDraft): FoodBuildResult { + // Snapshot only known fields once; accessors cannot swap validated values. + const { + identifier, + title, + description: sourceDescription, + location, + amount, + currency, + unit, + quantity: sourceQuantity, + published_at, + created_at, + status, + contact: sourceContact + } = input; + if (typeof identifier !== 'string' || !foodIdentifierValid(identifier)) + return failure('identifier_invalid'); + if (!text(title, 160)) return failure('title_invalid'); + if (!text(location, 160)) return failure('location_invalid'); + if ( + typeof sourceDescription !== 'string' || + !boundedUtf8(sourceDescription, 16384) + ) + return failure('description_invalid'); + const description = normalizedDescription(sourceDescription); + if (!foodContentPresent(description)) return failure('description_invalid'); + const derived = summary(description); + if (!foodTextValid(derived)) return failure('summary_invalid'); + const price = foodPrice(amount, currency, unit); + if (price === undefined) return failure('price_invalid'); + const quantity = + sourceQuantity === undefined + ? undefined + : foodQuantity(sourceQuantity, unit); + if (sourceQuantity !== undefined && quantity === undefined) + return failure('quantity_invalid'); + const numbers = boundedEnvelopeNumbers(30402, created_at); + const publishedAt = safeUnsignedInteger(published_at); + if ( + numbers === undefined || + publishedAt === undefined || + publishedAt === 0 || + publishedAt > numbers.created_at + ) + return failure('timestamp_invalid'); + if (status !== 'active' && status !== 'sold') + return failure('status_invalid'); + const contact = + sourceContact === undefined ? undefined : publicContact(sourceContact); + if (sourceContact !== undefined && contact === undefined) + return failure('contact_invalid'); + const content = + description + + (contact === undefined ? '' : `\n\nPublic contact: ${contact.href}`); + if (!boundedUtf8(content, 16384)) return failure('description_invalid'); + const tags: readonly (readonly string[])[] = [ + ['d', identifier], + ['title', title], + ['summary', derived], + ['published_at', String(publishedAt)], + ['location', location], + ['price', price.amount, price.currency], + ['radroots:price_unit', price.unit], + ...(quantity === undefined + ? [] + : [['radroots:quantity', quantity.amount, quantity.unit]]), + ['status', status] + ]; + // Bound the prospective compact signed envelope using fixed-size public hex + // placeholders. No signature, key, image or caller extra is manufactured. + const maximumWire = JSON.stringify({ + id: '0'.repeat(64), + pubkey: '0'.repeat(64), + created_at: numbers.created_at, + kind: 30402, + tags, + content, + sig: '0'.repeat(128) + }); + if (!boundedUtf8(maximumWire, 262144)) return failure('wire_too_large'); + return { + ok: true, + wire_parts: { kind: 30402, content, tags }, + summary: derived + }; +} diff --git a/web/tests/conformance/food-writer-cases.ts b/web/tests/conformance/food-writer-cases.ts @@ -0,0 +1,60 @@ +import { + buildFoodTemplate, + type FoodDraft +} from '../../src/lib/contracts/food-availability-v1/write.ts'; +import { foodUnits } from '../../src/lib/contracts/food-availability-v1/values.ts'; +const base: FoodDraft = { + identifier: 'writer-fixed-id', + title: 'Fresh food', + description: 'Fresh food available locally.', + location: 'Victoria', + published_at: 1700000000, + created_at: 1700000060, + amount: '9999999999999999999999999999', + currency: 'CAD', + unit: 'g', + quantity: '10', + status: 'active' +}; +const drafts: readonly FoodDraft[] = [ + ...foodUnits.map((unit) => ({ ...base, unit, identifier: `writer-${unit}` })), + { + ...base, + identifier: 'writer-free-unspecified', + amount: '0', + quantity: undefined + }, + { ...base, identifier: 'writer-sold', status: 'sold' }, + { + ...base, + identifier: 'writer-unicode', + title: '🥕', + description: '🥕'.repeat(241), + contact: { + type: 'https', + value: 'https://farm.example/contact', + public: true + } + }, + { + ...base, + identifier: 'writer-email', + contact: { type: 'email', value: 'seller@example.com', public: true } + }, + { + ...base, + identifier: 'writer-phone', + contact: { type: 'phone', value: '+12505550123', public: true } + }, + { ...base, identifier: 'writer-max-content', description: 'x'.repeat(16384) } +]; +export const webTemplates = drafts.map((draft, index) => { + const result = buildFoodTemplate(draft); + if (!result.ok) throw new Error(result.error.code); + return { + id: `web_writer_${index.toString().padStart(3, '0')}`, + created_at: draft.created_at, + wire_parts: result.wire_parts, + summary: result.summary + }; +}); diff --git a/web/tests/conformance/food-writer.test.ts b/web/tests/conformance/food-writer.test.ts @@ -0,0 +1,32 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { webTemplates } from './food-writer-cases.ts'; +import { projectFoodParts } from '../../src/lib/contracts/food-availability-v1/read.ts'; +for (const row of webTemplates) + void test(`strict website template source: ${row.id}`, () => { + const projected = projectFoodParts({ + ...row.wire_parts, + created_at: row.created_at + }); + assert.equal(projected.outcome, 'focused'); + if (projected.outcome === 'focused') { + assert.equal(projected.projection.summary, row.summary); + assert.deepEqual(projected.projection.images, []); + } + assert.deepEqual( + row.wire_parts.tags.map((tag) => tag[0]), + [ + 'd', + 'title', + 'summary', + 'published_at', + 'location', + 'price', + 'radroots:price_unit', + ...(row.wire_parts.tags.some((t) => t[0] === 'radroots:quantity') + ? ['radroots:quantity'] + : []), + 'status' + ] + ); + }); diff --git a/web/tests/e2e/notices.spec.ts b/web/tests/e2e/notices.spec.ts @@ -56,10 +56,12 @@ test.beforeAll(async () => { path.join(checkout, 'web/src/routes/+page.svelte'), fixture.replaceAll('../../../src/lib/', '../lib/') ); - await cp( - path.join(capsule, 'web/node_modules'), - path.join(checkout, 'web/node_modules'), - { recursive: true, verbatimSymlinks: true } + // Runtime store metadata is volume-specific; install the exact locked graph + // into this disposable clone without a network or lock-repair fallback. + const installed = execFileSync( + 'corepack', + ['pnpm', 'install', '--offline', '--frozen-lockfile'], + { cwd: path.join(checkout, 'web'), stdio: 'pipe', timeout: 90_000 } ); const sourceAudit = execFileSync( process.execPath, @@ -90,8 +92,8 @@ test.beforeAll(async () => { cwd: path.join(checkout, 'web') }); const compiled = execFileSync( - 'corepack', - ['pnpm', 'exec', 'vite', 'build'], + process.execPath, + ['node_modules/vite/bin/vite.js', 'build'], { cwd: path.join(checkout, 'web'), stdio: 'pipe', @@ -143,6 +145,7 @@ test.beforeAll(async () => { retention: 'HASHLOGS_ONLY: disposable compiled fixture output is removed after tests', payload: await payload(path.join(checkout, 'web/build')), + installed: installed.toString(), compiled: compiled.toString(), metadata: JSON.parse( await readFile( diff --git a/web/tests/e2e/primitives.spec.ts b/web/tests/e2e/primitives.spec.ts @@ -49,10 +49,12 @@ test.beforeAll(async () => { path.join(checkout, 'web/src/routes/+page.svelte'), fixture.replaceAll('../../../src/lib/', '../lib/') ); - await cp( - path.join(capsule, 'web/node_modules'), - path.join(checkout, 'web/node_modules'), - { recursive: true, verbatimSymlinks: true } + // Runtime store metadata is volume-specific; install the exact locked graph + // into this disposable clone without a network or lock-repair fallback. + const installed = execFileSync( + 'corepack', + ['pnpm', 'install', '--offline', '--frozen-lockfile'], + { cwd: path.join(checkout, 'web'), stdio: 'pipe', timeout: 90_000 } ); const sourceAudit = execFileSync( process.execPath, @@ -85,8 +87,8 @@ test.beforeAll(async () => { cwd: path.join(checkout, 'web') }); const compiled = execFileSync( - 'corepack', - ['pnpm', 'exec', 'vite', 'build'], + process.execPath, + ['node_modules/vite/bin/vite.js', 'build'], { cwd: path.join(checkout, 'web'), stdio: 'pipe', @@ -126,6 +128,7 @@ test.beforeAll(async () => { ) .digest('hex'), payload: await payload(path.join(checkout, 'web/build')), + installed: installed.toString(), compiled: compiled.toString(), metadata: JSON.parse( await readFile( diff --git a/web/tests/e2e/search-form.spec.ts b/web/tests/e2e/search-form.spec.ts @@ -55,10 +55,12 @@ test.beforeAll(async () => { path.join(checkout, 'web/src/routes/+page.svelte'), fixture.replaceAll('../../../src/lib/', '../lib/') ); - await cp( - path.join(capsule, 'web/node_modules'), - path.join(checkout, 'web/node_modules'), - { recursive: true, verbatimSymlinks: true } + // Runtime store metadata is volume-specific; install the exact locked graph + // into this disposable clone without a network or lock-repair fallback. + const installed = execFileSync( + 'corepack', + ['pnpm', 'install', '--offline', '--frozen-lockfile'], + { cwd: path.join(checkout, 'web'), stdio: 'pipe', timeout: 90_000 } ); const sourceAudit = execFileSync( process.execPath, @@ -86,8 +88,8 @@ test.beforeAll(async () => { cwd: path.join(checkout, 'web') }); const compiled = execFileSync( - 'corepack', - ['pnpm', 'exec', 'vite', 'build'], + process.execPath, + ['node_modules/vite/bin/vite.js', 'build'], { cwd: path.join(checkout, 'web'), stdio: 'pipe', @@ -139,6 +141,7 @@ test.beforeAll(async () => { retention: 'HASHLOGS_ONLY: disposable compiled fixture output is removed after tests', payload: await payload(path.join(checkout, 'web/build')), + installed: installed.toString(), compiled: compiled.toString(), metadata: JSON.parse( await readFile( diff --git a/web/tests/e2e/shell.spec.ts b/web/tests/e2e/shell.spec.ts @@ -52,10 +52,12 @@ test.beforeAll(async () => { path.join(checkout, 'web/src/routes/+page.svelte'), fixture.replaceAll('../../../src/lib/', '../lib/') ); - await cp( - path.join(capsule, 'web/node_modules'), - path.join(checkout, 'web/node_modules'), - { recursive: true, verbatimSymlinks: true } + // Runtime store metadata is volume-specific; install the exact locked graph + // into this disposable clone without a network or lock-repair fallback. + const installed = execFileSync( + 'corepack', + ['pnpm', 'install', '--offline', '--frozen-lockfile'], + { cwd: path.join(checkout, 'web'), stdio: 'pipe', timeout: 90_000 } ); const fixtureLayout = '<script lang="ts">import "../theme.css"; import "../app.css"; import type { Snippet } from "svelte"; let { children }: { children: Snippet } = $props();</script>{@render children()}'; @@ -102,8 +104,8 @@ test.beforeAll(async () => { cwd: path.join(checkout, 'web') }); const compiled = execFileSync( - 'corepack', - ['pnpm', 'exec', 'vite', 'build'], + process.execPath, + ['node_modules/vite/bin/vite.js', 'build'], { cwd: path.join(checkout, 'web'), stdio: 'pipe', @@ -148,6 +150,7 @@ test.beforeAll(async () => { compiledLayout: fixtureLayout, derivedTargets, payload: await payload(path.join(checkout, 'web/build')), + installed: installed.toString(), compiled: compiled.toString(), metadata: JSON.parse( await readFile( diff --git a/web/tests/unit/food-writer.test.ts b/web/tests/unit/food-writer.test.ts @@ -0,0 +1,298 @@ +import { describe, expect, it } from 'vitest'; +import { + buildFoodTemplate, + type FoodDraft +} from '../../src/lib/contracts/food-availability-v1/write.ts'; +import { publicContact } from '../../src/lib/contracts/food-availability-v1/contact.ts'; +import { foodUnits } from '../../src/lib/contracts/food-availability-v1/values.ts'; +const draft: FoodDraft = { + identifier: 'fixed-draft-id', + title: 'Carrots', + description: 'Fresh carrots.\nCollected locally.', + location: 'Victoria', + created_at: 1700000060, + published_at: 1700000000, + amount: '3.5', + currency: 'CAD', + unit: 'lb', + quantity: '10', + status: 'active' +}; +function valid(value: FoodDraft) { + const result = buildFoodTemplate(value); + expect(result.ok).toBe(true); + if (!result.ok) throw new Error(result.error.code); + return result; +} +describe('known fields are read once before validation', () => { + it('title getter cannot replace the validated title', () => { + let reads = 0; + const r = valid({ + ...draft, + get title() { + return ++reads === 1 ? 'Carrots' : 'x'.repeat(161); + } + }); + expect(reads).toBe(1); + expect(r.wire_parts.tags[1]).toEqual(['title', 'Carrots']); + }); + it('description getter cannot replace the bounded description', () => { + let reads = 0; + const r = valid({ + ...draft, + get description() { + return ++reads === 1 ? 'Carrots' : 'x'.repeat(20000); + } + }); + expect(reads).toBe(1); + expect(r.wire_parts.content).toBe('Carrots'); + }); + it('contact getter and its fields cannot replace validated contact', () => { + let contacts = 0; + let values = 0; + const r = valid({ + ...draft, + get contact() { + contacts++; + return { + type: 'email' as const, + public: true as const, + get value() { + return ++values === 1 + ? 'seller@example.com' + : 'attacker?body=private@example.com'; + } + }; + } + }); + expect(contacts).toBe(1); + expect(values).toBe(1); + expect(r.wire_parts.content).toBe( + draft.description + '\n\nPublic contact: mailto:seller@example.com' + ); + }); + it('public contact snapshots disclosure and type once', () => { + let types = 0; + let disclosures = 0; + expect( + publicContact({ + get public() { + disclosures++; + return true; + }, + get type() { + return ++types === 1 ? 'email' : 'phone'; + }, + value: 'seller@example.com' + }) + ).toEqual({ type: 'email', href: 'mailto:seller@example.com' }); + expect(types).toBe(1); + expect(disclosures).toBe(1); + }); +}); +describe('strict text-only authored Food templates', () => { + for (const unit of foodUnits) + it(unit, () => { + const r = valid({ ...draft, unit }); + expect(r.wire_parts.kind).toBe(30402); + expect(r.wire_parts.tags).toEqual([ + ['d', 'fixed-draft-id'], + ['title', 'Carrots'], + ['summary', 'Fresh carrots. Collected locally.'], + ['published_at', '1700000000'], + ['location', 'Victoria'], + ['price', '3.5', 'CAD'], + ['radroots:price_unit', unit], + ['radroots:quantity', '10', unit], + ['status', 'active'] + ]); + }); + it('stable identity/publication time is not inferred from changed title', () => { + const a = valid(draft); + const b = valid({ + ...draft, + title: 'New title', + created_at: 1700000070, + status: 'sold' + }); + expect(a.wire_parts.tags[0]).toEqual(b.wire_parts.tags[0]); + expect(a.wire_parts.tags[3]).toEqual(b.wire_parts.tags[3]); + }); + it('summary is derived and visible with whole Unicode code points', () => { + const r = valid({ ...draft, description: '😀'.repeat(241) }); + expect(r.summary).toBe('😀'.repeat(240)); + expect(r.summary.isWellFormed()).toBe(true); + expect(r.wire_parts.tags[2]).toEqual(['summary', r.summary]); + }); + it('fresh draft line endings normalize without changing already signed data', () => { + const r = valid({ ...draft, description: ' Fresh\r\ncarrots.\rHere. ' }); + expect(r.wire_parts.content).toBe('Fresh\ncarrots.\nHere.'); + expect(r.summary).toBe('Fresh carrots. Here.'); + }); + it('zero price and absent quantity differ from quantity zero', () => { + const r = valid({ ...draft, amount: '0', quantity: undefined }); + expect(r.wire_parts.tags.find((t) => t[0] === 'price')).toEqual([ + 'price', + '0', + 'CAD' + ]); + expect(r.wire_parts.tags.some((t) => t[0] === 'radroots:quantity')).toBe( + false + ); + expect(buildFoodTemplate({ ...draft, quantity: '0' }).ok).toBe(false); + }); + it('canonical28digit amount remains exact', () => + expect( + valid({ + ...draft, + amount: '9999999999999999999999999999' + }).wire_parts.tags.find((t) => t[0] === 'price')?.[1] + ).toBe('9999999999999999999999999999')); + for (const amount of ['003.500', '1.0', '+1', '1e3', '1,000', '1'.repeat(29)]) + it('rejects authored amount ' + amount, () => + expect(buildFoodTemplate({ ...draft, amount }).ok).toBe(false) + ); + for (const value of [ + { currency: 'cad' }, + { unit: 'lbs' }, + { quantity: '-1' }, + { identifier: '' }, + { identifier: 'x y' }, + { identifier: 'x'.repeat(513) }, + { status: 'withdrawn' }, + { created_at: Number('18446744073709551615') }, + { published_at: 1700000061 }, + { published_at: 0 }, + { title: ' x' }, + { title: 'x\u200b' }, + { title: '😀'.repeat(161) }, + { location: 'x'.repeat(161) }, + { description: '' }, + { description: 'x'.repeat(16385) } + ]) + it('rejects invalid draft ' + JSON.stringify(value), () => + expect(buildFoodTemplate({ ...draft, ...value } as FoodDraft).ok).toBe( + false + ) + ); + it('actual160codepoint titles and locations plus16KiB content are admitted', () => { + const r = valid({ + ...draft, + title: '😀'.repeat(160), + location: 'é'.repeat(160), + description: 'x'.repeat(16384) + }); + expect(new TextEncoder().encode(r.wire_parts.content)).toHaveLength(16384); + }); + it('contact block participates in composed16KiB budget', () => + expect( + buildFoodTemplate({ + ...draft, + description: 'x'.repeat(16380), + contact: { type: 'email', value: 'seller@example.com', public: true } + }).ok + ).toBe(false)); + it('only explicitly public contact composes into content', () => { + const r = valid({ + ...draft, + contact: { type: 'email', value: 'seller@example.com', public: true } + }); + expect(r.wire_parts.content).toBe( + draft.description + '\n\nPublic contact: mailto:seller@example.com' + ); + expect( + r.wire_parts.tags.some((t) => + ['contact', 'image', 'contract'].includes(t[0]) + ) + ).toBe(false); + expect( + buildFoodTemplate({ + ...draft, + contact: { + type: 'email', + value: 'seller@example.com', + public: false + } as never + }).ok + ).toBe(false); + }); + it('private enquiry/subject/recipient extras never enter the public event', () => { + const r = valid({ + ...draft, + privateEnquiry: 'PRIVATE ENQUIRY', + subject: 'PRIVATE SUBJECT', + recipient: 'PRIVATE RECIPIENT', + summary: 'PRIVATE SUMMARY', + images: ['https://secret.example/image'] + } as FoodDraft); + expect(JSON.stringify(r.wire_parts)).not.toContain('PRIVATE'); + expect(JSON.stringify(r.wire_parts)).not.toContain('secret.example'); + expect(r.summary).toBe('Fresh carrots. Collected locally.'); + }); +}); +describe('dedicated optional public-contact fields', () => { + for (const input of [ + { type: 'email', value: 'seller+food@example.com', public: true }, + { type: 'phone', value: '+12505550123', public: true }, + { type: 'https', value: 'https://farm.example/contact', public: true } + ]) + it('allowed ' + input.type, () => + expect(publicContact(input as never)).toBeDefined() + ); + for (const input of [ + { type: 'email', value: 'seller@example.com?body=private', public: true }, + { type: 'email', value: 'a\nb@example.com', public: true }, + { type: 'email', value: 'missing-domain', public: true }, + { type: 'phone', value: '555 HELP', public: true }, + { type: 'phone', value: '+0', public: true }, + { type: 'https', value: 'http://farm.example/contact', public: true }, + { + type: 'https', + value: 'https://user:pass@farm.example/contact', + public: true + }, + { type: 'https', value: 'javascript:alert(1)', public: true }, + { type: 'https', value: 'https://farm.example/%0a', public: true }, + { type: 'https', value: 'https://farm.example/contact', public: false }, + { type: 'other', value: 'private prose', public: true } + ]) + it('rejects ' + JSON.stringify(input), () => + expect(publicContact(input as never)).toBeUndefined() + ); + it('absence stays absent', () => + expect(publicContact(undefined)).toBeUndefined()); +}); + +describe('contact recipient and visible URI preservation', () => { + for (const value of [ + 'foo?subject=x@example.com', + 'foo#bar@example.com', + 'foo%3Fbar@example.com', + 'foo%0abar@example.com' + ]) + it('reject mailbox URI syntax ' + value, () => + expect( + publicContact({ type: 'email', value, public: true }) + ).toBeUndefined() + ); + for (const value of [ + 'https://farm\u200b.example/contact', + 'https://farm.example/%E2%80%8Bcontact' + ]) + it('reject URL format character ' + value, () => + expect( + publicContact({ type: 'https', value, public: true }) + ).toBeUndefined() + ); + it('normal mailbox preserves its exact recipient with no header/fragment', () => { + const contact = publicContact({ + type: 'email', + value: 'seller+food@example.com', + public: true + })!; + const parsed = new URL(contact.href); + expect(parsed.pathname).toBe('seller+food@example.com'); + expect(parsed.search).toBe(''); + expect(parsed.hash).toBe(''); + }); +});