app

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

commit 51f20b37d4219e185fb7146277f3e1eaca5d32e4
parent e481b041f69402b94ab00c64b02fca56a1f4b748
Author: triesap <tyson@radroots.org>
Date:   Tue,  6 Oct 2026 20:38:07 +0000

web: wire product details with truthful enquiry readiness (HCP-044)

- Resolve verified product heads with scoped lifecycle ownership.
- Render plain food facts, asserted publishers and safe public contact.
- Copy canonical public links and preserve truthful capability gates.
- Verify lifecycle, provenance, browser behavior and output boundaries.

Diffstat:
Aweb/src/lib/catalog/product-view.ts | 271+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/components/ListingFacts.svelte | 24++++++++++++++++++++++++
Aweb/src/lib/components/PublisherIdentity.svelte | 13+++++++++++++
Aweb/src/lib/contracts/food-availability-v1/contact-read.ts | 18++++++++++++++++++
Aweb/src/lib/navigation-copy.ts | 30++++++++++++++++++++++++++++++
Mweb/src/lib/runtime/public-runtime.ts | 5+++++
Mweb/src/routes/products/[naddr=naddr]/+page.svelte | 171+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Aweb/tests/e2e/product-details.spec.ts | 374+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/integration/product-view.test.ts | 200+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/provenance/output.test.mjs | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mweb/tests/provenance/source-boundaries.test.mjs | 51++++++++++++++++++++++++++++++++++++++++++++++++++-
Aweb/tests/unit/components/product-details.test.ts | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/contact-read.test.ts | 28++++++++++++++++++++++++++++
Aweb/tests/unit/navigation-copy.test.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/product-view.test.ts | 397+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/unit/public-runtime.test.ts | 25+++++++++++++++++++++++++
Mweb/tests/unit/route-inventory.test.ts | 8++++++--
Mweb/tools/check-output.mjs | 103++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mweb/tools/source-boundaries.mjs | 45+++++++++++++++++++++++++++++++++++++++++++--
19 files changed, 2011 insertions(+), 11 deletions(-)

diff --git a/web/src/lib/catalog/product-view.ts b/web/src/lib/catalog/product-view.ts @@ -0,0 +1,271 @@ +import { PUBLIC_QUERY_BUDGETS } from '../config/budgets.ts'; +import { + decodeProductReference, + type ProductReference +} from '../nostr/references.ts'; +import { + beginPublicViewRun, + disposePublicView, + publicViewProjectionAvailable, + publicViewRunCurrent, + publicViewOwnsRun, + subscribePublicView, + type PublicView +} from '../runtime/public-runtime.ts'; +import { + publicRequestScopeSnapshot, + publicRunSnapshot, + closePublicRequest, + disposePublicRun, + type PublicRequest +} from '../nostr/request-scope.ts'; +import { + createPublicHeadCandidate, + publicHeadSnapshot, + selectPublicHead, + type PublicHead +} from './heads.ts'; +import { + createPublicViewHeadResolver, + headResolutionSnapshot, + resolveHeads, + closeHeadResolver +} from './resolve-head.ts'; +import { + createPublisherViews, + readPublisherPage, + publisherSnapshot, + type PublisherView +} from './publishers.ts'; +import type { FoodProjection } from '../contracts/food-availability-v1/read.ts'; +import type { WallClock } from './clock-policy.ts'; +import type { ForegroundSchedule } from './search-view.ts'; +export type ProductViewSnapshot = Readonly<{ + reference: ProductReference; + outcome: + | 'checking' + | 'unobserved' + | 'unavailable' + | 'active' + | 'sold' + | 'withdrawn' + | 'unsupported' + | 'future_quarantined' + | 'clock_unavailable'; + food: FoodProjection | undefined; + eventId: string | undefined; + createdAt: number | undefined; + publisher: PublisherView; + lastKnown: boolean; + sources: readonly ReturnType<typeof publicRequestScopeSnapshot>[]; +}>; +declare const productBrand: unique symbol; +export type ProductView = Readonly<{ readonly [productBrand]: true }>; +interface Owner { + snapshot: () => ProductViewSnapshot; + close: () => void; +} +const owners = new WeakMap<ProductView, Owner>(); +function ownerOf(token: ProductView): Owner { + const owner = owners.get(token); + if (!owner) throw Error('product_view_invalid'); + return owner; +} +function foreground(callback: () => void, delay: number): () => void { + const timer = setTimeout(() => { + callback(); + }, delay); + return () => { + clearTimeout(timer); + }; +} +// One explicit route read, one coordinate, shared run/request budgets. No forged +// seed, independent cache, relay hints, automatic refresh or additional deadline. +export function createProductView( + view: PublicView, + value: unknown, + clock: WallClock, + onUpdate: (value: ProductViewSnapshot) => void, + schedule: ForegroundSchedule = foreground +): ProductView { + const decoded = decodeProductReference(value); + if (!decoded) throw Error('product_reference_invalid'); + const reference = decoded; + const run = beginPublicViewRun(view), + resolver = createPublicViewHeadResolver(view, run, clock), + publishers = createPublisherViews(view, clock); + let closed = false, + failed = false, + head: PublicHead | undefined, + cancel: (() => void) | undefined; + const requests = new Map<PublicRequest, true>(); + const current = () => !closed && publicViewRunCurrent(view, run); + function snapshot(): ProductViewSnapshot { + const available = + !closed && + publicViewProjectionAvailable(view) && + publicViewOwnsRun(view, run); + const row = available ? headResolutionSnapshot(resolver)[0] : undefined; + let scopes = Array.from(requests.keys(), publicRequestScopeSnapshot); + for (const scope of [row?.headSources, row?.deletionSources]) + if ( + scope && + !scopes.some((s) => s.result.context === scope.result.context) + ) + scopes = scopes.concat(scope); + const complete = + !failed && + scopes.length > 0 && + scopes.every( + (s) => s.state === 'eose' && s.result.coverage === 'bounded-eose' + ); + let outcome: ProductViewSnapshot['outcome']; + if (!available) outcome = 'unavailable'; + else if (row?.deletion.outcome === 'suppressed') outcome = 'withdrawn'; + else if ( + row?.state.display === 'future_quarantined' || + row?.state.display === 'clock_unavailable' + ) + outcome = row.state.display; + else if (row?.state.display === 'unsupported') outcome = 'unsupported'; + else if (row?.state.food) outcome = row.state.food.status; + else if ( + !row && + (failed || + (scopes.length > 0 && + scopes.every( + (scope) => + scope.result.sources.length > 0 && + scope.result.sources.every( + (source) => + source.state === 'error' || source.state === 'closed' + ) + ))) + ) + outcome = 'unavailable'; + else + outcome = + current() && scopes.some((s) => s.state === 'active') + ? 'checking' + : 'unobserved'; + const publisher = publisherSnapshot(publishers, reference.pubkey); + const stillAvailable = + !closed && + publicViewProjectionAvailable(view) && + publicViewOwnsRun(view, run); + return { + reference: { ...reference }, + outcome: stillAvailable ? outcome : 'unavailable', + food: stillAvailable ? row?.state.food : undefined, + eventId: stillAvailable ? row?.state.head.id : undefined, + createdAt: stillAvailable ? row?.state.head.created_at : undefined, + publisher: stillAvailable + ? publisher + : { + pubkey: reference.pubkey, + label: reference.pubkey, + assertedName: false + }, + lastKnown: !stillAvailable || !complete || (row?.lastKnown ?? true), + sources: scopes + }; + } + function publish() { + const value = snapshot(); + if (!closed && publicViewOwnsRun(view, run)) onUpdate(value); + } + function queue() { + if (!current() || publicRunSnapshot(run).activeRequests === 0) return; + const next = schedule(() => { + if (closed || !publicViewOwnsRun(view, run)) return; + cancel = undefined; + publish(); + queue(); + }, 250); + if (current()) cancel = next; + else next(); + } + const token = Object.freeze({}) as ProductView; + owners.set(token, { + snapshot, + close() { + closed = true; + const previous = cancel; + cancel = undefined; + previous?.(); + let error = false; + try { + closeHeadResolver(resolver); + } catch { + error = true; + } + try { + if (publicViewOwnsRun(view, run)) disposePublicView(view); + else disposePublicRun(run); + } catch { + error = true; + } + if (error) throw Error('product_view_close_failed'); + } + }); + try { + const filter = + reference.identifier === '' + ? { + kinds: [30402], + authors: [reference.pubkey], + limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay + } + : { + kinds: [30402], + authors: [reference.pubkey], + '#d': [reference.identifier], + limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay + }; + const request = subscribePublicView( + view, + run, + 'head', + [filter], + (proof) => { + if (!current()) return; + const candidate = createPublicHeadCandidate(proof); + if (!candidate) return; + const next = publicHeadSnapshot(candidate); + if ( + next.kind !== 30402 || + next.pubkey !== reference.pubkey || + next.identifier !== reference.identifier + ) + return; + head = selectPublicHead(head, candidate).head; + try { + resolveHeads(resolver, [head]); + if (current()) + for (const request of readPublisherPage(publishers, run, [ + reference.pubkey + ])) + requests.set(request, true); + } catch { + failed = true; + } + } + ); + requests.set(request, true); + if (publicRequestScopeSnapshot(request).result.sources.length === 0) { + failed = true; + closePublicRequest(request); + } + } catch { + failed = true; + } + publish(); + queue(); + return token; +} +export function productViewSnapshot(token: ProductView): ProductViewSnapshot { + return ownerOf(token).snapshot(); +} +export function closeProductView(token: ProductView): void { + ownerOf(token).close(); +} diff --git a/web/src/lib/components/ListingFacts.svelte b/web/src/lib/components/ListingFacts.svelte @@ -0,0 +1,24 @@ +<script lang="ts"> + import type { FoodProjection } from '../contracts/food-availability-v1/read.ts'; + let { food, createdAt }: { food: FoodProjection; createdAt: number } = + $props(); + function timestamp(seconds: number): string { + const milliseconds = seconds * 1000; + return Number.isFinite(milliseconds) && + Math.abs(milliseconds) <= 8640000000000000 + ? new Date(milliseconds).toISOString() + : `${seconds} seconds since the Unix epoch`; + } +</script> + +<div class="stack"> + <p>{food.price.currency} {food.price.amount} / {food.price.unit}</p> + <p>Public pickup area: {food.location}</p> + {#if food.quantity}<p> + Advertised quantity: {food.quantity.amount} + {food.quantity.unit} + </p>{:else}<p>Advertised quantity not specified</p>{/if} + <p>Seller's status: {food.status === 'sold' ? 'Sold' : 'Available'}</p> + <p>Seller updated: {timestamp(createdAt)}</p> + <p>{food.content}</p> +</div> diff --git a/web/src/lib/components/PublisherIdentity.svelte b/web/src/lib/components/PublisherIdentity.svelte @@ -0,0 +1,13 @@ +<script lang="ts"> + import type { PublisherView } from '../catalog/publishers.ts'; + import Disclosure from './primitives/Disclosure.svelte'; + let { publisher }: { publisher: PublisherView } = $props(); +</script> + +<p>{publisher.label}</p> +<Disclosure summary="Publisher identity"> + {#if publisher.assertedName}<p> + This name is asserted by the publisher. + </p>{/if} + <p>Publisher key: <code>{publisher.pubkey}</code></p> +</Disclosure> diff --git a/web/src/lib/contracts/food-availability-v1/contact-read.ts b/web/src/lib/contracts/food-availability-v1/contact-read.ts @@ -0,0 +1,18 @@ +import { publicContact, type PublicContact } from './contact.ts'; +// The writer's dedicated public disclosure is a final block, not prose scanning. +export function readPublicContact(content: unknown): PublicContact | undefined { + if (typeof content !== 'string') return undefined; + const marker = '\n\nPublic contact: '; + const at = content.lastIndexOf(marker); + if (at < 0) return undefined; + const href = content.slice(at + marker.length); + const type = href.startsWith('mailto:') + ? 'email' + : href.startsWith('tel:') + ? 'phone' + : 'https'; + const value = + type === 'email' ? href.slice(7) : type === 'phone' ? href.slice(4) : href; + const contact = publicContact({ type, value, public: true }); + return contact?.href === href ? contact : undefined; +} diff --git a/web/src/lib/navigation-copy.ts b/web/src/lib/navigation-copy.ts @@ -0,0 +1,30 @@ +import { decodeProductReference } from './nostr/references.ts'; +// Explicit click callers alone use this public, hint-free coordinate action. +export async function copyProductReference( + value: unknown, + origin: unknown +): Promise<boolean> { + const reference = decodeProductReference(value); + if (!reference || typeof origin !== 'string' || origin.length > 2048) + return false; + try { + const host = new URL(origin); + if ( + host.origin !== origin || + host.username || + host.password || + (host.protocol !== 'https:' && + !( + host.protocol === 'http:' && + ['127.0.0.1', 'localhost', '[::1]'].includes(host.hostname) + )) + ) + return false; + await navigator.clipboard.writeText( + `${host.origin}/products/${reference.naddr}` + ); + return true; + } catch { + return false; + } +} diff --git a/web/src/lib/runtime/public-runtime.ts b/web/src/lib/runtime/public-runtime.ts @@ -317,6 +317,11 @@ export function publicViewRunCurrent( ): boolean { return viewOf(view).current(run) && publicRunSnapshot(run).active; } +// Ownership survives an ordinary deadline so a foreground owner can publish +// its terminal result once. Supersession/disposal/shared closure revoke it. +export function publicViewOwnsRun(view: PublicView, run: PublicRun): boolean { + return viewOf(view).current(run); +} export function disposePublicView(view: PublicView): void { if (!viewOf(view).dispose()) throw new Error('public_view_close_failed'); } diff --git a/web/src/routes/products/[naddr=naddr]/+page.svelte b/web/src/routes/products/[naddr=naddr]/+page.svelte @@ -1,5 +1,170 @@ -<svelte:head><title>Food — HarvestCircle</title></svelte:head> +<script lang="ts"> + import { getContext, onMount } from 'svelte'; + import { page } from '$app/state'; + import { + PUBLIC_RUNTIME_CONTEXT, + publicRuntimeReady, + createPublicView, + disposePublicView, + type PublicView, + type PublicRuntime, + type PublicRuntimeContext + } from '../../../lib/runtime/public-runtime.ts'; + import { + createProductView, + closeProductView, + type ProductView, + type ProductViewSnapshot + } from '../../../lib/catalog/product-view.ts'; + import { decodeProductReference } from '../../../lib/nostr/references.ts'; + import { readPublicContact } from '../../../lib/contracts/food-availability-v1/contact-read.ts'; + import { copyProductReference } from '../../../lib/navigation-copy.ts'; + import { internalHref, navigationHref } from '../../../lib/navigation-url.ts'; + import ListingFacts from '../../../lib/components/ListingFacts.svelte'; + import PublisherIdentity from '../../../lib/components/PublisherIdentity.svelte'; + import Disclosure from '../../../lib/components/primitives/Disclosure.svelte'; + import Button from '../../../lib/components/primitives/Button.svelte'; + const context = getContext<PublicRuntimeContext>(PUBLIC_RUNTIME_CONTEXT); + let runtime = $state.raw<PublicRuntime | undefined>(), + result = $state.raw<ProductViewSnapshot | undefined>(), + error = $state<string | undefined>(), + copyNotice = $state<string | undefined>(); + const reference = $derived(decodeProductReference(page.params.naddr)); + const contact = $derived(readPublicContact(result?.food?.content)); + let disposed = false; + onMount(() => { + const unavailable = () => { + if (!disposed) error = 'Food sources are unavailable.'; + }; + try { + void publicRuntimeReady(context) + .then((value) => { + if (!disposed) { + runtime = value; + if (!value) unavailable(); + } + }) + .catch(unavailable); + } catch { + unavailable(); + } + return () => { + disposed = true; + }; + }); + $effect(() => { + const selected = reference, + shared = runtime; + result = undefined; + copyNotice = undefined; + if (!selected || !shared) return; + let active = true, + acquired: PublicView | undefined, + owner: ProductView | undefined; + try { + acquired = createPublicView(shared); + owner = createProductView( + acquired, + selected.naddr, + { nowSeconds: () => Math.floor(Date.now() / 1000) }, + (value) => { + if (active && !disposed) result = value; + } + ); + error = undefined; + } catch { + error = 'Food sources are unavailable.'; + if (acquired) + try { + disposePublicView(acquired); + } catch { + /* Shared runtime keeps a failed disposer retryable. */ + } + } + return () => { + active = false; + if (owner) closeProductView(owner); + }; + }); + async function copyLink() { + const selected = reference; + if (!selected) return; + const copied = await copyProductReference(selected.naddr, page.url.origin); + if (!disposed && reference?.naddr === selected.naddr) + copyNotice = copied + ? 'Link copied.' + : 'Copy was unavailable. Select the public link below.'; + } +</script> + +<svelte:head + ><title>{result?.food?.title ?? 'Food'} — HarvestCircle</title></svelte:head +> <div class="page page--reading stack"> - <h1>Food</h1> - <p class="notice">Food details are unavailable during development.</p> + <a href={internalHref('/search')}>Search food</a> + <h1>{result?.food?.title ?? 'Food'}</h1> + {#if !reference}<p class="notice">This food reference is invalid.</p> + {:else if error || result?.outcome === 'unavailable'}<p class="notice"> + Food sources are unavailable. + </p> + {:else if !result || result.outcome === 'checking'}<p> + Checking food sources… + </p> + {:else if result.outcome === 'unobserved'}<p class="notice"> + This listing was not observed in the sources checked. It may be + unavailable or missing from these sources. + </p> + {:else if result.outcome === 'withdrawn'}<p class="notice"> + This listing was withdrawn by its publisher. + </p> + {:else if result.outcome === 'unsupported'}<p class="notice"> + The latest known listing uses an unsupported food format. + </p> + {:else if result.outcome === 'future_quarantined' || result.outcome === 'clock_unavailable'}<p + class="notice" + > + Listing time could not be confirmed. Food details are unavailable. + </p>{/if} + {#if result} + <PublisherIdentity publisher={result.publisher} /> + {#if result.lastKnown}<p class="notice"> + This is last-known information. The listing status check is incomplete. + </p>{/if} + {#if result.food && result.createdAt !== undefined}<ListingFacts + food={result.food} + createdAt={result.createdAt} + />{/if} + {#if result.outcome === 'sold'}<p class="notice"> + The seller marked this listing sold. + </p>{/if} + {#if result.outcome === 'active'}<p> + Confirm availability with the seller. + </p> + <Button label="Message seller" disabled={true} /> + <p class="notice"> + In-app messaging is unavailable during development. + </p>{/if} + <Disclosure summary="Listing and source details"> + {#if result.eventId}<p> + Listing version: <code>{result.eventId}</code> + </p>{/if} + {#each result.sources as source (source.result.context)}<p> + {source.kind}: {source.state}. Coverage: {source.result.coverage}. + </p> + {#each source.result.sources as relay (relay.source)}<p> + {relay.source}: {relay.state}. + </p>{/each}{/each} + <p> + These bounded checks do not prove complete coverage or current stock. + </p> + </Disclosure> + {#if contact && result.outcome === 'active'}<Disclosure + summary="Other contact details" + ><a href={navigationHref(contact.href)}>{contact.href}</a></Disclosure + >{/if} + {/if} + {#if reference}<Button label="Copy link" onclick={copyLink} /><a + href={internalHref(`/products/${reference.naddr}`)}>Public food link</a + >{/if} + {#if copyNotice}<p role="status">{copyNotice}</p>{/if} </div> diff --git a/web/tests/e2e/product-details.spec.ts b/web/tests/e2e/product-details.spec.ts @@ -0,0 +1,374 @@ +import { expect, test } from '@playwright/test'; +import { createHash } from 'node:crypto'; +import { execFileSync } from 'node:child_process'; +import { + cp, + mkdtemp, + readFile, + readdir, + rm, + writeFile +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { once } from 'node:events'; +import { naddrEncode } from 'applesauce-core/helpers/pointers'; +import { finalizeEvent } from 'applesauce-core/helpers'; +import WebSocket, { WebSocketServer, type RawData } from 'ws'; +function wireText(bytes: RawData): string { + const buffer = Array.isArray(bytes) + ? Buffer.concat(bytes) + : Buffer.isBuffer(bytes) + ? bytes + : Buffer.from(bytes); + return buffer.toString('utf8'); +} +import { createStaticHarness } from '../integration/harness/static.ts'; +const capsule = fileURLToPath(new URL('../../../', import.meta.url)); +let directory: string; +let server: Awaited<ReturnType<typeof createStaticHarness>>; +// Verification fixture: compile exact primary source, deriving only its fixed +// deployment allowlist. Never alter the primary output or production policy. +test.beforeAll(async () => { + test.setTimeout(120000); + directory = await mkdtemp(path.join(tmpdir(), 'hcp044-details-')); + try { + const checkout = path.join(directory, 'checkout'), + web = path.join(checkout, 'web'); + execFileSync('git', [ + 'clone', + '--quiet', + '--no-hardlinks', + capsule, + checkout + ]); + await cp(path.join(capsule, 'web/src'), path.join(web, 'src'), { + recursive: true + }); + const identities: { path: string; sha256: string }[] = []; + async function identify(dir: string, prefix = '') { + for (const entry of await readdir(dir, { withFileTypes: true })) { + const relative = prefix + entry.name; + if (entry.isDirectory()) + await identify(path.join(dir, entry.name), relative + '/'); + else + identities.push({ + path: relative, + sha256: createHash('sha256') + .update(await readFile(path.join(dir, entry.name))) + .digest('hex') + }); + } + } + await identify(path.join(web, 'src')); + await cp( + path.join(capsule, 'web/tools/source-boundaries.mjs'), + path.join(web, 'tools/source-boundaries.mjs') + ); + identities.push({ + path: 'tools/source-boundaries.mjs', + sha256: createHash('sha256') + .update(await readFile(path.join(web, 'tools/source-boundaries.mjs'))) + .digest('hex') + }); + const policy = + "import { validateRelayPolicy } from './relays.ts'; const policy=validateRelayPolicy(JSON.stringify({schemaVersion:1,public:[{origin:'wss://one.example.org',read:true,write:false,nip50:false},{origin:'wss://failed.example.org',read:true,write:false,nip50:false}],inbox:[],postingEnabled:false,messagingEnabled:false,operatorDenylist:[]})); if(!policy) throw new Error('fixture_policy'); export const deploymentRelayPolicy=policy;"; + await writeFile( + path.join(web, 'src/lib/config/deployment-relays.ts'), + policy + ); + const installed = execFileSync( + 'corepack', + ['pnpm', 'install', '--offline', '--frozen-lockfile'], + { cwd: web, timeout: 90000 } + ).toString(); + const sourceAudit = execFileSync( + process.execPath, + ['tools/check-source.mjs'], + { cwd: web } + ).toString(); + execFileSync(process.execPath, ['tools/build-info.mjs'], { cwd: web }); + const compiled = execFileSync( + process.execPath, + ['node_modules/vite/bin/vite.js', 'build'], + { cwd: web, timeout: 90000 } + ).toString(); + console.log( + JSON.stringify({ + fixture: 'HCP044_TEST_ONLY_FIXED_POLICY', + identities, + policy, + policySha256: createHash('sha256').update(policy).digest('hex'), + installed, + sourceAudit, + compiled + }) + ); + server = await createStaticHarness({ buildRoot: path.join(web, 'build') }); + } catch (error) { + await rm(directory, { recursive: true, force: true }); + throw error; + } +}); +test.afterAll(async () => { + if (server) await server.close(); + if (directory) await rm(directory, { recursive: true, force: true }); +}); +test('real product reload renders verified facts, safe guest contact, explicit copy and truthful capability/status gates', async ({ + browser +}) => { + const corpus = JSON.parse( + await readFile( + path.join(capsule, 'contracts/interop/food_availability/corpus.v1.json'), + 'utf8' + ) + ) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; + const base = JSON.parse( + corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous + ) as { tags: string[][]; content: string; created_at: number }; + const key = crypto.getRandomValues(new Uint8Array(32)); + const listings = ['active', 'sold', 'withdrawn', 'unsupported', 'future'].map( + (status, n) => + finalizeEvent( + { + kind: 30402, + created_at: + status === 'future' + ? Math.floor(Date.now() / 1000) + 36000 + : base.created_at - n, + tags: + status === 'unsupported' + ? [ + ['d', status], + ['title', 'Other format'] + ] + : [ + ...base.tags.map((t) => + t[0] === 'd' + ? ['d', status] + : t[0] === 'title' + ? ['title', `Carrots ${status}`] + : t[0] === 'status' + ? ['status', status === 'sold' ? 'sold' : 'active'] + : [...t] + ), + ['image', 'https://tracking.example.org/image.png'] + ], + content: + '<img src=https://tracking.example.org> Contact only if supplied.\n\nPublic contact: https://contact.example.org/collect' + }, + key + ) + ); + const withdrawn = listings[2]; + const deletion = finalizeEvent( + { + kind: 5, + created_at: base.created_at + 1, + tags: [['e', withdrawn.id]], + content: '' + }, + key + ); + const profile = finalizeEvent( + { + kind: 0, + created_at: base.created_at, + tags: [], + content: JSON.stringify({ + display_name: '<img src=https://tracking.example.org>' + }) + }, + key + ); + key.fill(0); + const relay = new WebSocketServer({ + host: '127.0.0.1', + port: 0, + maxPayload: 65536 + }); + const queries: Record<string, unknown>[] = [], + closed: string[] = []; + relay.on('connection', (socket) => { + socket.on('message', (bytes) => { + const frame = JSON.parse(wireText(bytes)) as unknown[]; + if (frame[0] === 'CLOSE') { + closed.push(String(frame[1])); + return; + } + if (frame[0] !== 'REQ') return; + const id = String(frame[1]), + filters = frame.slice(2) as Record<string, unknown>[]; + queries.push(...filters); + const kind = (filters[0].kinds as number[])[0]; + const values = + kind === 0 + ? [profile] + : kind === 30402 + ? listings.filter((v) => + filters.some( + (f) => + (!f.authors || + (f.authors as string[]).includes(v.pubkey)) && + (!f['#d'] || + (f['#d'] as string[]).includes( + v.tags.find((t) => t[0] === 'd')![1] + )) && + (!f.until || v.created_at <= Number(f.until)) + ) + ) + : kind === 5 + ? [deletion] + : []; + for (const value of values) + socket.send(JSON.stringify(['EVENT', id, value])); + socket.send(JSON.stringify(['EOSE', id])); + }); + }); + await once(relay, 'listening'); + const address = relay.address(); + if (!address || typeof address === 'string') throw Error('fixture_port'); + const context = await browser.newContext({ + viewport: { width: 320, height: 700 }, + permissions: ['clipboard-read', 'clipboard-write'] + }), + bridges: WebSocket[] = [], + external: string[] = [], + failures: string[] = []; + try { + await context.route('**/*', (route) => { + if (new URL(route.request().url()).origin === server.url) + return route.continue(); + external.push(route.request().url()); + return route.abort(); + }); + await context.routeWebSocket('**/*', (route) => { + if (new URL(route.url()).hostname === 'failed.example.org') { + route.onMessage((message) => { + const frame = JSON.parse(String(message)) as unknown[]; + if (frame[0] === 'REQ') + route.send( + JSON.stringify(['CLOSED', frame[1], 'fixture source unavailable']) + ); + }); + return; + } + expect(new URL(route.url()).hostname).toBe('one.example.org'); + const bridge = new WebSocket(`ws://127.0.0.1:${address.port}`); + bridges.push(bridge); + const pending: (string | Buffer)[] = []; + bridge.on('open', () => { + for (const message of pending.splice(0)) bridge.send(message); + }); + bridge.on('message', (bytes) => route.send(wireText(bytes))); + route.onMessage((message) => { + if (bridge.readyState === WebSocket.OPEN) bridge.send(message); + else pending.push(message); + }); + route.onClose(() => { + bridge.close(); + }); + }); + const page = await context.newPage(); + page.on('pageerror', (e) => failures.push(e.message)); + const coordinate = (identifier: string) => + naddrEncode({ kind: 30402, pubkey: listings[0].pubkey, identifier }); + const href = (identifier: string) => + server.url + '/products/' + coordinate(identifier); + await page.goto(href('active')); + await expect( + page.getByRole('heading', { name: 'Carrots active', exact: true }) + ).toBeVisible(); + await expect( + page.getByRole('button', { name: 'Message seller', exact: true }) + ).toBeDisabled(); + await expect( + page.getByText('In-app messaging is unavailable during development.') + ).toBeVisible(); + await expect( + page.getByRole('button', { name: 'Manage listing' }) + ).toHaveCount(0); + await expect(page.locator('img,iframe,textarea')).toHaveCount(0); + await page.getByText('Publisher identity', { exact: true }).click(); + await expect(page.getByText(profile.pubkey, { exact: true })).toBeVisible(); + await page.getByText('Other contact details', { exact: true }).click(); + await expect( + page.getByRole('link', { + name: 'https://contact.example.org/collect', + exact: true + }) + ).toHaveAttribute('href', 'https://contact.example.org/collect'); + await page.getByRole('button', { name: 'Copy link', exact: true }).click(); + await expect(page.getByRole('status')).toHaveText('Link copied.'); + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe( + href('active') + ); + // Test-only anchor exercises Kit client parameter navigation on the actual + // component; survival proves this transition did not reload the document. + await page.evaluate((target) => { + const link = document.createElement('a'); + link.href = target; + link.textContent = 'Fixture next food'; + link.id = 'fixture-client-transition'; + document.body.append(link); + }, href('sold')); + await page + .getByRole('link', { name: 'Fixture next food', exact: true }) + .click(); + await expect( + page.getByText('The seller marked this listing sold.', { exact: true }) + ).toBeVisible(); + await expect(page.locator('#fixture-client-transition')).toHaveCount(1); + await page.goBack(); + await expect( + page.getByRole('heading', { name: 'Carrots active', exact: true }) + ).toBeVisible(); + await page.reload(); + await expect( + page.getByRole('heading', { name: 'Carrots active', exact: true }) + ).toBeVisible(); + for (const [identifier, notice] of [ + ['sold', 'The seller marked this listing sold.'], + ['withdrawn', 'This listing was withdrawn by its publisher.'], + [ + 'unsupported', + 'The latest known listing uses an unsupported food format.' + ], + [ + 'future', + 'Listing time could not be confirmed. Food details are unavailable.' + ], + [ + 'unobserved', + 'This listing was not observed in the sources checked. It may be unavailable or missing from these sources.' + ] + ]) { + await page.goto(href(identifier)); + await expect(page.getByText(notice, { exact: true })).toBeVisible(); + await expect( + page.getByRole('button', { name: 'Message seller', exact: true }) + ).toHaveCount(0); + } + await page.goto(server.url + '/products/invalid-reference'); + await expect(page.getByText('Not Found', { exact: true })).toBeVisible(); + expect(external).toEqual([]); + expect(failures).toEqual([]); + expect(await page.evaluate(() => 'nostr' in window)).toBe(false); + console.log( + JSON.stringify({ + fixture: 'HCP044_GENUINE_LOOPBACK_DETAIL', + queries, + external, + failures + }) + ); + } finally { + await context.close(); + for (const bridge of bridges) bridge.terminate(); + for (const socket of relay.clients) socket.terminate(); + await new Promise<void>((resolve, reject) => + relay.close((e) => (e ? reject(e) : resolve())) + ); + } +}); diff --git a/web/tests/integration/product-view.test.ts b/web/tests/integration/product-view.test.ts @@ -0,0 +1,200 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { once } from 'node:events'; +import { readFile } from 'node:fs/promises'; +import { finalizeEvent } from 'applesauce-core/helpers'; +import WebSocket, { WebSocketServer } from 'ws'; +import { validateRelayPolicy } from '../../src/lib/config/relays.ts'; +import { + createPublicRuntimeContext, + mountPublicRuntime, + createPublicView, + closePublicRuntime +} from '../../src/lib/runtime/public-runtime.ts'; +import { + createProductView, + productViewSnapshot, + closeProductView +} from '../../src/lib/catalog/product-view.ts'; +import { encodeProductReference } from '../../src/lib/nostr/references.ts'; +await test('actual SDK direct coordinate detail publishes genuine facts and asserted metadata with bounded teardown', async () => { + const corpus = JSON.parse( + await readFile( + new URL( + '../../../contracts/interop/food_availability/corpus.v1.json', + import.meta.url + ), + 'utf8' + ) + ) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; + const base = JSON.parse( + corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous + ) as { tags: string[][]; content: string; created_at: number }; + const keys: Uint8Array[] = []; + const listings = Array.from({ length: 21 }, (_, n) => { + const key = crypto.getRandomValues(new Uint8Array(32)); + keys.push(key); + return finalizeEvent( + { + kind: 30402, + created_at: base.created_at - n, + tags: base.tags.map((t) => + t[0] === 'd' ? ['d', `listing_${n}`] : [...t] + ), + content: base.content + }, + key + ); + }); + const profiles = keys.map((key, n) => + finalizeEvent( + { + kind: 0, + created_at: base.created_at, + tags: [], + content: JSON.stringify({ + display_name: `<script>Farmer ${n}</script>`, + pubkey: 'forged', + nip05: 'identity@example.org', + picture: 'https://tracking.example.org' + }) + }, + key + ) + ); + for (const key of keys) key.fill(0); + const origin = 'wss://one.example.org', + server = new WebSocketServer({ + host: '127.0.0.1', + port: 0, + maxPayload: 65536 + }); + const sockets: WebSocket[] = [], + filters: Record<string, unknown>[] = []; + server.on('connection', (socket) => { + sockets.push(socket); + socket.on('message', (bytes) => { + const buffer = Array.isArray(bytes) + ? Buffer.concat(bytes) + : Buffer.isBuffer(bytes) + ? bytes + : Buffer.from(bytes); + const frame = JSON.parse(buffer.toString('utf8')) as unknown[]; + if (frame[0] !== 'REQ') return; + const id = String(frame[1]), + queries = frame.slice(2) as Record<string, unknown>[]; + filters.push(...queries); + const kind = (queries[0].kinds as number[])[0]; + const matches = (pubkey: string, identifier?: string) => + queries.some((q) => { + const authors = q.authors as string[] | undefined; + return ( + !authors || + (authors.includes(pubkey) && + (identifier === undefined || + (q['#d'] as string[]).includes(identifier))) + ); + }); + const values = + kind === 0 + ? profiles.filter((v) => matches(v.pubkey)) + : kind === 30402 + ? listings.filter((v) => + matches(v.pubkey, v.tags.find((t) => t[0] === 'd')![1]) + ) + : []; + for (const value of values) + socket.send(JSON.stringify(['EVENT', id, value])); + socket.send(JSON.stringify(['EOSE', id])); + }); + }); + await once(server, 'listening'); + const address = server.address(); + assert.ok(address && typeof address !== 'string'); + const port = address.port; + const oldWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'), + oldSocket = globalThis.WebSocket; + class FixtureSocket extends WebSocket { + constructor(url: string | URL) { + assert.equal(String(url).replace(/\/$/, ''), origin); + super(`ws://127.0.0.1:${port}`); + } + } + Object.defineProperty(globalThis, 'window', { + configurable: true, + value: {} + }); + globalThis.WebSocket = + FixtureSocket as unknown as typeof globalThis.WebSocket; + const context = createPublicRuntimeContext(); + try { + const policy = validateRelayPolicy( + JSON.stringify({ + schemaVersion: 1, + public: [{ origin, read: true, write: false, nip50: false }], + inbox: [], + postingEnabled: false, + messagingEnabled: false, + operatorDenylist: [] + }) + )!; + const view = createPublicView(mountPublicRuntime(context, policy)!); + const updates: string[] = []; + const target = listings[0]; + const naddr = encodeProductReference({ + kind: 30402, + pubkey: target.pubkey, + identifier: target.tags.find((t) => t[0] === 'd')![1] + })!; + const owner = createProductView( + view, + naddr, + { nowSeconds: () => base.created_at + 10 }, + (snapshot) => updates.push(snapshot.outcome) + ); + for ( + let n = 0; + n < 300 && + (!productViewSnapshot(owner).publisher.assertedName || + productViewSnapshot(owner).outcome !== 'active'); + n++ + ) + await new Promise((resolve) => setTimeout(resolve, 10)); + const first = productViewSnapshot(owner); + assert.equal(first.outcome, 'active'); + assert.equal(first.eventId, target.id); + assert.equal( + first.food?.title, + base.tags.find((t) => t[0] === 'title')![1] + ); + assert.equal(first.publisher.pubkey, target.pubkey); + assert.equal(first.publisher.assertedName, true); + for (let n = 0; n < 300 && !updates.includes('active'); n++) + await new Promise((resolve) => setTimeout(resolve, 10)); + assert.ok(updates.includes('active')); + assert.ok(filters.length >= 3); + assert.ok( + filters.every( + (f) => + Array.isArray(f.authors) && + (f.authors as string[]).length === 1 && + (f.authors as string[])[0] === target.pubkey + ) + ); + closeProductView(owner); + const settled = filters.length; + await new Promise((resolve) => setTimeout(resolve, 300)); + assert.equal(filters.length, settled); + assert.equal(productViewSnapshot(owner).outcome, 'unavailable'); + } finally { + closePublicRuntime(context); + for (const key of keys) key.fill(0); + globalThis.WebSocket = oldSocket; + if (oldWindow) Object.defineProperty(globalThis, 'window', oldWindow); + else delete (globalThis as { window?: unknown }).window; + for (const socket of sockets) socket.terminate(); + await new Promise<void>((resolve, reject) => + server.close((e) => (e ? reject(e) : resolve())) + ); + } +}); diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs @@ -25,6 +25,9 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { /** @param {string} name @param {(context: import('node:test').TestContext) => Promise<void>} run @param {number} [timeout] */ const check = (name, run, timeout = 10000) => t.test(name, { timeout }, run); const source = fileURLToPath(new URL('../../../', import.meta.url)); + // Exact HCP043 product shell bytes, immutable compatibility evidence only. + const historicalProduct = + '<svelte:head><title>Food — HarvestCircle</title></svelte:head>\n<div class="page page--reading stack">\n <h1>Food</h1>\n <p class="notice">Food details are unavailable during development.</p>\n</div>\n'; const base = await mkdtemp(path.join(os.tmpdir(), 'hc actual output ')); t.after(() => rm(base, { recursive: true, force: true })); /** @param {string} root @param {string[]} args */ @@ -114,7 +117,7 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { const f = await fixture(t); const files = await f.audit(); // Exact eleven-route module/page/static admission; CSS stays once-imported. - assert.equal(files.length, 46); + assert.equal(files.length, 47); // The actual SDK payload crosses the reader scratch boundary; a reused // scratch buffer must still preserve every compiler/static byte exactly. const sizes = await Promise.all( @@ -170,7 +173,7 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { assert.ok(Buffer.byteLength(expanded) > 64 * 1024); await writeFile(file, expanded); await refresh(f); - assert.equal((await f.audit()).length, 46); + assert.equal((await f.audit()).length, 47); } ); const sdkKey = @@ -186,6 +189,10 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { path.join(f.web, 'src/routes/search/+page.svelte'), historical ); + await writeFile( + path.join(f.web, 'src/routes/products/[naddr=naddr]/+page.svelte'), + historicalProduct + ); await refresh(f); await cp( path.join(base, 'web/node_modules'), @@ -216,6 +223,29 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { }, 60000 ); + await check( + 'HCP043 search graph remains qualified with the exact historical product shell', + async (t) => { + const f = await fixture(t); + await writeFile( + path.join(f.web, 'src/routes/products/[naddr=naddr]/+page.svelte'), + historicalProduct + ); + await refresh(f); + await cp( + path.join(base, 'web/node_modules'), + path.join(f.web, 'node_modules'), + { recursive: true, verbatimSymlinks: true } + ); + execFileSync( + process.execPath, + [path.join(source, 'web/node_modules/vite/bin/vite.js'), 'build'], + { cwd: f.web, stdio: 'pipe', timeout: 60000 } + ); + assert.equal((await f.audit()).length, 46); + }, + 60000 + ); for (const mutation of [ 'unknown-name', 'missing-public-key', @@ -506,6 +536,89 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { } ); for (const producer of [ + 'src/routes/products/[naddr=naddr]/+page.svelte', + 'src/lib/catalog/product-view.ts', + 'src/lib/components/ListingFacts.svelte', + 'src/lib/components/PublisherIdentity.svelte', + 'src/lib/contracts/food-availability-v1/contact-read.ts', + 'src/lib/navigation-copy.ts', + 'src/lib/runtime/public-runtime.ts', + 'src/lib/catalog/publishers.ts', + 'src/lib/catalog/resolve-head.ts' + ]) { + await check( + 'real product compiler rejects changed owned producer ' + producer, + async (t) => { + const f = await fixture(t); + await writeFile( + path.join(f.web, producer), + (await readFile(path.join(f.web, producer), 'utf8')) + + '\n// source mutation\n' + ); + await refresh(f); + await assert.rejects( + f.audit, + /Invalid owned product presentation source/ + ); + } + ); + } + for (const mutation of [ + 'missing-publishers', + 'publisher-budget', + 'publisher-shared', + 'publisher-dynamic', + 'product-shared', + 'product-publisher', + 'product-budget', + 'product-dynamic', + 'search-publisher' + ]) { + await check('real product compiler rejects ' + mutation, async (t) => { + const f = await fixture(t), + file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const manifest = JSON.parse(await readFile(file, 'utf8')); + const records = Object.entries(manifest); + const find = (/** @type {string} */ name) => { + const row = records.find(([, v]) => v.name === name); + assert.ok(row); + return row; + }; + const [publisherKey, publisher] = find('publishers'); + if (mutation === 'missing-publishers') delete manifest[publisherKey]; + else if (mutation === 'publisher-dynamic') + publisher.dynamicImports = [find('client-entry')[0]]; + else if (mutation === 'product-dynamic') + find('nodes/7')[1].dynamicImports = [find('client-entry')[0]]; + else if ( + mutation === 'publisher-budget' || + mutation === 'publisher-shared' + ) + publisher.imports = publisher.imports.filter( + (/** @type {string} */ key) => + key !== + find(mutation === 'publisher-budget' ? 'budgets' : 'Disclosure')[0] + ); + else { + const target = mutation === 'search-publisher' ? 'nodes/9' : 'nodes/7'; + const dependency = + mutation === 'product-shared' + ? 'Disclosure' + : mutation === 'product-budget' + ? 'budgets' + : 'publishers'; + find(target)[1].imports = find(target)[1].imports.filter( + (/** @type {string} */ key) => key !== find(dependency)[0] + ); + } + await writeFile(file, JSON.stringify(manifest)); + await assert.rejects(f.audit, /compiler|budgets/); + }); + } + for (const producer of [ 'src/routes/search/+page.svelte', 'src/lib/catalog/search-view.ts', 'src/lib/components/ListingRow.svelte', diff --git a/web/tests/provenance/source-boundaries.test.mjs b/web/tests/provenance/source-boundaries.test.mjs @@ -16,6 +16,55 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { test } from 'node:test'; +test('HCP044 clipboard access is confined to the exact public copy producer', 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', + 'src/lib/navigation-copy.ts' + ]) + await put(name, await readFile(path.join(root, name), 'utf8')); + assert.equal(execute().status, 0); + for (const code of [ + "navigator.clipboard.writeText('bad');", + 'const clipboard=navigator.clipboard;clipboard.writeText("bad");', + 'navigator.clipboard.readText();', + 'navigator["clipboard"].writeText("bad");', + 'const owner=navigator;owner.clipboard.writeText("bad");', + 'globalThis.navigator.clipboard.writeText("bad");', + 'globalThis["navigator"].clipboard.writeText("bad");', + 'window.navigator.clipboard.writeText("bad");' + ]) { + await put('src/routes/+page.ts', code); + assert.notEqual(execute().status, 0, code); + } + await put('src/routes/+page.ts', 'export const value=1;'); + const helper = await readFile( + path.join(root, 'src/lib/navigation-copy.ts'), + 'utf8' + ); + await put( + 'src/lib/navigation-copy.ts', + helper + '\n navigator.clipboard.readText();' + ); + assert.notEqual(execute().status, 0); + await put('src/lib/navigation-copy.ts', helper); + await put('src/lib/copied.ts', helper); + assert.notEqual(execute().status, 0); + }); +}); + const root = fileURLToPath(new URL('../../', import.meta.url)); /** @typedef {{directory: string, put: (name: string, content: string | Uint8Array) => Promise<void>, execute: (args?: string[]) => import('node:child_process').SpawnSyncReturns<string>, pkg: Record<string, unknown>}} Fixture */ /** @param {(context: Fixture) => Promise<void>} run */ @@ -985,7 +1034,7 @@ test('approved navigator capabilities and plain model flags remain admitted', as await fixture(async ({ put, execute }) => { await put( 'src/routes/+page.ts', - 'const model = { serviceWorker: false }; export const disabled = model.serviceWorker; export function online() { return navigator.onLine; } export function estimate() { return navigator.storage.estimate(); } export function copy(value: string) { return window.navigator.clipboard.writeText(value); }' + 'const model = { serviceWorker: false }; export const disabled = model.serviceWorker; export function online() { return navigator.onLine; } export function estimate() { return navigator.storage.estimate(); }' ); const result = execute(); assert.equal(result.status, 0, result.stderr); diff --git a/web/tests/unit/components/product-details.test.ts b/web/tests/unit/components/product-details.test.ts @@ -0,0 +1,79 @@ +import { readFileSync } from 'node:fs'; +import { render } from 'svelte/server'; +import { describe, expect, it, vi } from 'vitest'; +import { incomingAmount } from '../../../src/lib/contracts/food-availability-v1/text.ts'; +import ListingFacts from '../../../src/lib/components/ListingFacts.svelte'; +import PublisherIdentity from '../../../src/lib/components/PublisherIdentity.svelte'; +import Product from '../../../src/routes/products/[naddr=naddr]/+page.svelte'; +import { encodeProductReference } from '../../../src/lib/nostr/references.ts'; +import { + projectFoodParts, + type FoodParts +} from '../../../src/lib/contracts/food-availability-v1/read.ts'; +const host = vi.hoisted(() => ({ + params: { naddr: 'invalid' }, + url: new URL('https://harvest.example/products/invalid') +})); +vi.mock('$app/state', () => ({ page: host })); +const corpus = JSON.parse( + readFileSync( + new URL( + '../../../../contracts/interop/food_availability/corpus.v1.json', + import.meta.url + ), + 'utf8' + ) +) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; +const event = JSON.parse( + corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous +) as FoodParts; +const projected = projectFoodParts(event); +if (projected.outcome !== 'focused') throw Error('fixture food'); +describe('truthful public detail presentation', () => { + it('renders escaped exact advertised values without remote media or link discovery', () => { + const food = { + ...projected.projection, + content: '<img src=https://track.example> mailto:private@example.org', + price: { + ...projected.projection.price, + amount: incomingAmount('4.0000000000000000000001')! + }, + quantity: null + }; + const result = render(ListingFacts, { + props: { food, createdAt: 999999999999999 } + }).body; + expect(result).toContain('4.0000000000000000000001'); + expect(result).toContain('Advertised quantity not specified'); + expect(result).toContain('&lt;img'); + expect(result).toContain('seconds since the Unix epoch'); + expect(result).not.toMatch(/<img|<a|<iframe|<script/); + }); + it('discloses asserted name and key without managed identity or farm certification', () => { + const publisher = { + pubkey: 'ab'.repeat(32), + label: '<img src=https://track.example>', + assertedName: true + }; + const result = render(PublisherIdentity, { props: { publisher } }).body; + expect(result).toContain(publisher.pubkey); + expect(result).toContain('asserted by the publisher'); + expect(result).toContain('&lt;img'); + expect(result).not.toMatch(/<img|<a|verified farm|Manage listing/); + }); + it('distinguishes invalid from valid checking SSR without reads or fabricated facts', () => { + host.params.naddr = 'invalid'; + expect(render(Product).body).toContain('This food reference is invalid.'); + host.params.naddr = encodeProductReference({ + kind: 30402, + pubkey: 'ab'.repeat(32), + identifier: 'carrots' + })!; + const result = render(Product).body; + expect(result).toContain('Checking food sources'); + expect(result).toContain('Copy link'); + expect(result).not.toMatch( + /<img|mailto:|tel:|Message seller|Manage listing|Cedar Farm/ + ); + }); +}); diff --git a/web/tests/unit/contact-read.test.ts b/web/tests/unit/contact-read.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest'; +import { readPublicContact } from '../../src/lib/contracts/food-availability-v1/contact-read.ts'; +describe('dedicated optional public contact', () => { + it('accepts only the writer final block with canonical safe contact', () => { + for (const href of [ + 'mailto:seller@example.org', + 'tel:+12025550123', + 'https://example.org/contact' + ]) + expect( + readPublicContact(`Carrots\n\nPublic contact: ${href}`)?.href + ).toBe(href); + }); + it('never infers prose, unsafe or malformed contact', () => { + for (const content of [ + undefined, + {}, + 'https://example.org', + 'Public contact: mailto:seller@example.org', + 'Carrots\n\nPublic contact: javascript:alert(1)', + 'Carrots\n\nPublic contact: https://example.org\nOther text', + 'Carrots\n\nPublic contact: mailto:a@example.org?subject=secret', + 'Carrots\n\nPublic contact: https://user:pass@example.org', + 'Carrots\n\nPublic contact: https://example.org/%0a' + ]) + expect(readPublicContact(content)).toBeUndefined(); + }); +}); diff --git a/web/tests/unit/navigation-copy.test.ts b/web/tests/unit/navigation-copy.test.ts @@ -0,0 +1,63 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { copyProductReference } from '../../src/lib/navigation-copy.ts'; +import { encodeProductReference } from '../../src/lib/nostr/references.ts'; +afterEach(() => vi.unstubAllGlobals()); +describe('explicit product reference copy', () => { + it('copies only canonical public route and reports actual success', async () => { + const writeText = vi.fn().mockResolvedValue(undefined); + vi.stubGlobal('navigator', { clipboard: { writeText } }); + const naddr = encodeProductReference({ + kind: 30402, + pubkey: 'ab'.repeat(32), + identifier: 'carrots' + })!; + expect( + await copyProductReference(naddr.toUpperCase(), 'https://harvest.example') + ).toBe(true); + expect(writeText).toHaveBeenCalledExactlyOnceWith( + `https://harvest.example/products/${naddr}` + ); + }); + it('reports denial/unavailable and rejects invalid input before effects', async () => { + const writeText = vi.fn().mockRejectedValue(new Error('denied')); + vi.stubGlobal('navigator', { clipboard: { writeText } }); + expect( + await copyProductReference( + 'https://bad.example', + 'https://harvest.example' + ) + ).toBe(false); + expect(writeText).not.toHaveBeenCalled(); + const naddr = encodeProductReference({ + kind: 30402, + pubkey: 'ab'.repeat(32), + identifier: 'carrots' + })!; + expect(await copyProductReference(naddr, 'https://harvest.example')).toBe( + false + ); + vi.stubGlobal('navigator', undefined); + expect(await copyProductReference(naddr, 'https://harvest.example')).toBe( + false + ); + }); + it('rejects noncanonical, credential, remote HTTP and javascript origins before copying', async () => { + const writeText = vi.fn(); + vi.stubGlobal('navigator', { clipboard: { writeText } }); + const naddr = encodeProductReference({ + kind: 30402, + pubkey: 'ab'.repeat(32), + identifier: 'carrots' + })!; + for (const origin of [ + 'https://host.example/', + 'https://user:pass@host.example', + 'http://host.example', + 'javascript:alert(1)', + 'https://host.example?secret=1', + undefined + ]) + expect(await copyProductReference(naddr, origin)).toBe(false); + expect(writeText).not.toHaveBeenCalled(); + }); +}); diff --git a/web/tests/unit/product-view.test.ts b/web/tests/unit/product-view.test.ts @@ -0,0 +1,397 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { finalizeEvent } from 'applesauce-core/helpers'; +import type { PublicPoolMessage } from '../../src/lib/nostr/exports.ts'; +import type { RequestClock } from '../../src/lib/nostr/request-scope.ts'; +let product: typeof import('../../src/lib/catalog/product-view.ts'); +let runtime: typeof import('../../src/lib/runtime/public-runtime.ts'); +let context: ReturnType<typeof runtime.createPublicRuntimeContext>; +const keys: Uint8Array[] = []; +beforeEach(async () => { + vi.resetModules(); + vi.stubGlobal('window', {}); + product = await import('../../src/lib/catalog/product-view.ts'); + runtime = await import('../../src/lib/runtime/public-runtime.ts'); +}); +afterEach(() => { + if (context) runtime.closePublicRuntime(context); + for (const key of keys.splice(0)) key.fill(0); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); +const corpus = JSON.parse( + readFileSync( + new URL( + '../../../contracts/interop/food_availability/corpus.v1.json', + import.meta.url + ), + 'utf8' + ) +) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; +const base = JSON.parse( + corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous +) as { tags: string[][]; content: string; created_at: number }; +async function fixture(nip50 = false, sourceCount = 1, throws = false) { + const { RelayPool } = await import('applesauce-relay/pool'); + const { validateRelayPolicy } = + await import('../../src/lib/config/relays.ts'); + const channels: { + emit: (value: PublicPoolMessage) => void; + stopped: () => boolean; + }[] = []; + const provider = vi.spyOn(RelayPool.prototype, 'req').mockImplementation( + () => + ({ + subscribe(subscriber: { next?: (value: PublicPoolMessage) => void }) { + let stopped = false; + channels.push({ + emit: (value: PublicPoolMessage) => { + if (!stopped) subscriber.next?.(value); + }, + stopped: () => stopped + }); + return { + get closed() { + return stopped; + }, + unsubscribe() { + stopped = true; + } + }; + } + }) as unknown as ReturnType<InstanceType<typeof RelayPool>['req']> + ); + const origin = 'wss://one.example.org'; + const policy = validateRelayPolicy( + JSON.stringify({ + schemaVersion: 1, + public: Array.from({ length: sourceCount }, (_, n) => ({ + origin: n === 0 ? origin : `wss://source${n}.example.org`, + read: true, + write: false, + nip50 + })), + inbox: [], + postingEnabled: false, + messagingEnabled: false, + operatorDenylist: [] + }) + )!; + const key = crypto.getRandomValues(new Uint8Array(32)); + keys.push(key); + const wire = ( + title = 'Carrots', + d?: string, + time = base.created_at, + content = base.content + ) => + finalizeEvent( + { + kind: 30402, + created_at: time, + content, + tags: base.tags.map((tag) => + tag[0] === 'title' + ? ['title', title] + : tag[0] === 'd' && d !== undefined + ? ['d', d] + : [...tag] + ) + }, + key + ); + let now = 0; + const timers = new Map<() => void, { at: number; callback: () => void }>(); + const clock: RequestClock = { + now: () => { + return now; + }, + schedule: (callback, delay) => { + const cancel = () => { + timers.delete(cancel); + }; + timers.set(cancel, { at: now + delay, callback }); + return cancel; + } + }; + if (throws) + provider.mockImplementation(() => { + throw Error('fixture provider denied'); + }); + context = runtime.createPublicRuntimeContext(); + const owner = runtime.mountPublicRuntime(context, policy, clock)!; + const view = runtime.createPublicView(owner); + let onWall = () => {}; + const wallClock = { + nowSeconds: () => { + onWall(); + return base.created_at + 10; + } + }; + const { encodeProductReference } = + await import('../../src/lib/nostr/references.ts'); + const initial = wire(); + const naddr = encodeProductReference({ + kind: 30402, + pubkey: initial.pubkey, + identifier: initial.tags.find((t) => t[0] === 'd')![1] + })!; + const observer = new Map<() => void, () => void>(); + const schedule = (callback: () => void) => { + const cancel = () => { + observer.delete(cancel); + }; + observer.set(cancel, callback); + return cancel; + }; + const updated: ReturnType<typeof product.productViewSnapshot>[] = []; + const token = product.createProductView( + view, + naddr, + wallClock, + (value) => updated.push(value), + schedule + ); + return { + token, + armWall: (callback: () => void) => { + onWall = callback; + }, + naddr, + view, + provider, + channels, + wire, + initial, + updated, + observer, + emit: (i: number, event: ReturnType<typeof wire>) => + channels[i].emit({ type: 'EVENT', id: 'fixture', from: origin, event }), + eose: (i: number) => + channels[i].emit({ type: 'EOSE', id: 'fixture', from: origin }), + snapshot: () => product.productViewSnapshot(token), + tick: () => { + const pending = [...observer.values()]; + observer.clear(); + for (const callback of pending) callback(); + }, + fail: (i: number) => + channels[i].emit({ + type: 'CLOSED', + id: 'fixture', + from: origin, + reason: 'fixture failure' + }), + advance: () => { + now = 16000; + for (const timer of [...timers.values()]) timer.callback(); + } + }; +} +describe('genuine direct coordinate product view', () => { + it('rechecks publication ownership after a snapshot clock creates a successor', async () => { + const f = await fixture(); + f.emit(0, f.initial); + const profileIndex = f.provider.mock.calls.findIndex((call) => + JSON.stringify(call[1]).includes('[0]') + ); + expect(profileIndex).toBeGreaterThan(0); + f.emit( + profileIndex, + finalizeEvent( + { + kind: 0, + created_at: base.created_at, + tags: [], + content: JSON.stringify({ display_name: 'Actual asserted publisher' }) + }, + keys.at(-1)! + ) + ); + const previous = f.updated.length; + let successor: ReturnType<typeof product.createProductView> | undefined; + f.armWall(() => { + f.armWall(() => {}); + successor = product.createProductView( + f.view, + f.naddr, + { nowSeconds: () => base.created_at + 10 }, + () => {}, + () => () => {} + ); + }); + f.tick(); + expect(successor).toBeDefined(); + expect(f.updated.length).toBe(previous); + expect(f.snapshot().outcome).toBe('unavailable'); + expect(f.snapshot().food).toBeUndefined(); + product.closeProductView(f.token); + expect(product.productViewSnapshot(successor!).outcome).toBe('checking'); + product.closeProductView(successor!); + }); + + it('reports zero qualified sources unavailable without relay delivery or polling', async () => { + const f = await fixture(false, 0); + expect(f.snapshot().outcome).toBe('unavailable'); + expect(f.snapshot().sources[0]?.result.sources).toEqual([]); + expect(f.observer.size).toBe(0); + expect(f.channels.every((c) => c.stopped())).toBe(true); + }); + it('ignores superseded retained callbacks and old cleanup cannot close successor view work', async () => { + const f = await fixture(); + const pending = [...f.observer.values()]; + const count = f.updated.length; + const nextUpdates: ReturnType<typeof product.productViewSnapshot>[] = []; + const next = product.createProductView( + f.view, + f.naddr, + { nowSeconds: () => base.created_at + 10 }, + (value) => nextUpdates.push(value), + () => () => {} + ); + for (const callback of pending) callback(); + expect(f.updated.length).toBe(count); + const channel = f.channels.at(-1)!; + expect(channel.stopped()).toBe(false); + product.closeProductView(f.token); + expect(channel.stopped()).toBe(false); + expect(product.productViewSnapshot(next).outcome).toBe('checking'); + expect(nextUpdates.length).toBe(1); + product.closeProductView(next); + expect(channel.stopped()).toBe(true); + }); + it('reports initial provider failure unavailable without retries', async () => { + const f = await fixture(false, 1, true); + expect(f.snapshot().outcome).toBe('unavailable'); + expect(f.updated.at(-1)?.outcome).toBe('unavailable'); + expect(f.observer.size).toBe(0); + expect(f.provider).toHaveBeenCalledTimes(1); + }); + + it('publishes terminal deadline state once and never restarts reads', async () => { + const f = await fixture(); + expect(f.updated.at(-1)?.outcome).toBe('checking'); + const calls = f.provider.mock.calls.length; + f.advance(); + f.tick(); + expect(f.updated.at(-1)?.outcome).toBe('unobserved'); + expect(f.updated.at(-1)?.lastKnown).toBe(true); + expect(f.observer.size).toBe(0); + expect(f.provider.mock.calls.length).toBe(calls); + }); + it('distinguishes failed sources from bounded empty observation', async () => { + const f = await fixture(); + f.fail(0); + f.tick(); + expect(f.snapshot().outcome).toBe('unavailable'); + expect(f.updated.at(-1)?.outcome).toBe('unavailable'); + }); + + it('distinguishes bounded unobserved from invalid before effects', async () => { + const f = await fixture(); + expect(f.snapshot().outcome).toBe('checking'); + const calls = f.provider.mock.calls.length; + expect(() => + product.createProductView( + f.view, + 'bad', + { nowSeconds: () => 0 }, + () => {} + ) + ).toThrow('product_reference_invalid'); + expect(f.provider.mock.calls.length).toBe(calls); + f.eose(0); + expect(f.snapshot().outcome).toBe('unobserved'); + expect(f.snapshot().lastKnown).toBe(true); + product.closeProductView(f.token); + expect(f.observer.size).toBe(0); + }); + it('admits only actual exact coordinates and latest unsupported never revives older food', async () => { + const f = await fixture(); + f.emit(0, f.wire('Other', 'other')); + expect(f.snapshot().outcome).toBe('checking'); + f.emit(0, f.initial); + expect(f.snapshot().outcome).toBe('active'); + expect(f.snapshot().food?.title).toBe('Carrots'); + const key = keys.at(-1)!; + const unsupported = finalizeEvent( + { + kind: 30402, + created_at: base.created_at + 1, + content: 'other format', + tags: [ + ['d', f.initial.tags.find((t) => t[0] === 'd')![1]], + ['title', 'Unsupported'] + ] + }, + key + ); + f.emit(0, unsupported); + f.emit(0, f.initial); + expect(f.snapshot().outcome).toBe('unsupported'); + expect(f.snapshot().food).toBeUndefined(); + expect(f.snapshot().eventId).toBe(unsupported.id); + }); + it('shows sold, future quarantine and authorized deletion without fabricated actions', async () => { + const f = await fixture(); + const key = keys.at(-1)!; + const sold = finalizeEvent( + { + kind: 30402, + created_at: base.created_at + 1, + content: base.content, + tags: base.tags.map((t) => + t[0] === 'status' ? ['status', 'sold'] : [...t] + ) + }, + key + ); + f.emit(0, sold); + expect(f.snapshot().outcome).toBe('sold'); + expect(f.snapshot().food?.status).toBe('sold'); + const deletion = finalizeEvent( + { + kind: 5, + created_at: base.created_at + 2, + content: '', + tags: [['e', sold.id]] + }, + key + ); + const deletionIndex = f.provider.mock.calls.findIndex((c) => + JSON.stringify(c[1]).includes('[5]') + ); + expect(deletionIndex).toBeGreaterThan(0); + f.emit(deletionIndex, deletion); + expect(f.snapshot().outcome).toBe('withdrawn'); + expect(f.snapshot().food).toBeUndefined(); + const future = f.wire('Future', undefined, base.created_at + 36000); + f.emit(0, future); + expect(f.snapshot().outcome).toBe('future_quarantined'); + expect(f.snapshot().food).toBeUndefined(); + }); + it('preserves uncertainty and scoped cleanup without closing another public view', async () => { + const f = await fixture(); + f.emit(0, f.initial); + f.fail(0); + expect(f.snapshot().lastKnown).toBe(true); + const retained = runtime.publicRuntime(context)!; + const other = runtime.createPublicView(retained); + const otherRun = runtime.beginPublicViewRun(other); + const calls = f.provider.mock.calls.length; + product.closeProductView(f.token); + expect(f.observer.size).toBe(0); + expect(f.channels.every((c) => c.stopped())).toBe(true); + expect(runtime.publicViewRunCurrent(other, otherRun)).toBe(true); + f.channels[0].emit({ + type: 'EVENT', + id: 'fixture', + from: 'wss://one.example.org', + event: f.initial + }); + f.tick(); + expect(f.provider.mock.calls.length).toBe(calls); + expect(f.snapshot().outcome).toBe('unavailable'); + runtime.disposePublicView(other); + }); +}); diff --git a/web/tests/unit/public-runtime.test.ts b/web/tests/unit/public-runtime.test.ts @@ -10,6 +10,31 @@ afterEach(() => { vi.unstubAllGlobals(); }); describe('root public runtime context', () => { + it('keeps terminal run ownership separate from activity and revokes superseded or disposed ownership', () => { + vi.stubGlobal('window', {}); + let now = 0; + const context = runtime.createPublicRuntimeContext(); + const owner = runtime.mountPublicRuntime(context, undefined, { + now: () => now, + schedule: () => () => {} + })!; + const view = runtime.createPublicView(owner), + other = runtime.createPublicView(owner), + run = runtime.beginPublicViewRun(view); + try { + now = 16000; + expect(runtime.publicViewRunCurrent(view, run)).toBe(false); + expect(runtime.publicViewOwnsRun(view, run)).toBe(true); + expect(runtime.publicViewOwnsRun(other, run)).toBe(false); + const next = runtime.beginPublicViewRun(view); + expect(runtime.publicViewOwnsRun(view, run)).toBe(false); + expect(runtime.publicViewOwnsRun(view, next)).toBe(true); + runtime.disposePublicView(view); + expect(runtime.publicViewOwnsRun(view, next)).toBe(false); + } finally { + runtime.closePublicRuntime(context); + } + }); it('reserves the view generation across synchronous run-creation clock reentry', () => { vi.stubGlobal('window', {}); const context = runtime.createPublicRuntimeContext(); diff --git a/web/tests/unit/route-inventory.test.ts b/web/tests/unit/route-inventory.test.ts @@ -22,7 +22,8 @@ import { prerender as conversationPrerender } from '../../src/routes/messages/[c const errorState = vi.hoisted(() => ({ status: 404, - error: { message: 'PRIVATE_TEST_ONLY' } + error: { message: 'PRIVATE_TEST_ONLY' }, + params: { naddr: 'invalid-reference' } })); vi.mock('$app/state', () => ({ page: errorState })); @@ -91,13 +92,16 @@ describe('thin protected route SSR', () => { ]).toEqual([false, false, false, false]); }); it('public shells honestly disclose unavailable content without invented listings or support', () => { - for (const component of [Product, About, Privacy]) { + for (const component of [About, Privacy]) { const output = render(component); expect(output.body).toContain('unavailable during development.'); expect(output.body).not.toMatch(/<form|<textarea|<input|mailto:|tel:/); expect(output.head).not.toContain('noindex'); } expect(render(About).body).toContain('id="help"'); + const details = render(Product); + expect(details.body).toContain('This food reference is invalid.'); + expect(details.body).not.toMatch(/<form|<textarea|<input|mailto:|tel:/); }); for (const status of [404, 500]) { it( diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs @@ -297,6 +297,40 @@ async function hasOwnedPublicRuntime(web) { publicText(await readOwned(web, 'src/lib/' + name)); return true; } +/** @param {string} web */ +async function productPresentationAdmission(web) { + const route = publicText( + await readOwned(web, 'src/routes/products/[naddr=naddr]/+page.svelte') + ); + if (!route.includes('../../../lib/catalog/product-view.ts')) return false; + const producers = { + 'src/routes/products/[naddr=naddr]/+page.svelte': + '1869d4dc32ea794d5ee5c1d6cc6b4aac94483482d18cff0562c0cb10087b5278', + 'src/lib/catalog/product-view.ts': + 'e3739170e3c700246a80c1358c7b96541a5cbf1e4c26905e6ca60537adfce9cf', + 'src/lib/components/ListingFacts.svelte': + '65d009b4940e7ced61347919689877da9473a2a66a44f61cc5e7bd0b2d217215', + 'src/lib/components/PublisherIdentity.svelte': + '90b156e2401d40079ee559d65ce66ec09ecc4246bc80cfdfc5def0e21e8ce9ff', + 'src/lib/contracts/food-availability-v1/contact-read.ts': + '18f812812c15858768223d929bcea9d7eae5154612747016ccd17864c229420a', + 'src/lib/navigation-copy.ts': + '1a17eac4b355d8a3fb2b55b3fe1bc856cc3b3bce07434836d708b68407686f20', + 'src/lib/runtime/public-runtime.ts': + 'f1b1b7b58fdd33d844831e05f5ee84f7195b7ab097d6fdd3934847e697814f90', + 'src/lib/catalog/publishers.ts': + 'a6795a35ebbf97246e22235df1ca868432e2cccfb26a38f0ebdf4524911192e6', + 'src/lib/catalog/resolve-head.ts': + '4f1c9f144164580da038d127ab463f9f8ba6b20e882fc31151cb29850782d633' + }; + for (const [name, pin] of Object.entries(producers)) { + const bytes = await readOwned(web, name); + publicText(bytes); + if (createHash('sha256').update(bytes).digest('hex') !== pin) + throw new Error('Invalid owned product presentation source'); + } + return true; +} // This exact reviewed producer set owns the shared presentation/runtime split. // A successor changes these identities only with new compiler qualification. /** @param {string} web */ @@ -424,6 +458,10 @@ export async function auditOutput(webDirectory) { throw new Error('Incomplete owned root runtime routes'); const hasSearchPresentation = hasSearch && hasPublicRuntime && (await searchPresentationAdmission(web)); + const hasProductPresentation = + hasFullRoutes && + hasPublicRuntime && + (await productPresentationAdmission(web)); // Admit compiler-owned module identities, not arbitrary extensions/copy roots. const names = new Set([ 'entry/app', @@ -463,6 +501,7 @@ export async function auditOutput(webDirectory) { 'budgets' ]) names.add(name); + if (hasProductPresentation) names.add('publishers'); const admitted = new Map([['build-info.json', expectedMetadata]]); const seen = new Set(); for (const [key, record] of Object.entries(manifest)) { @@ -563,7 +602,12 @@ export async function auditOutput(webDirectory) { ) throw new Error('Invalid owned budgets compiler identity'); for (const consumer of hasSearchPresentation - ? ['Disclosure', 'nodes/9', 'routes'] + ? [ + 'Disclosure', + 'nodes/9', + 'routes', + ...(hasProductPresentation ? ['nodes/7', 'publishers'] : []) + ] : ['nodes/0', 'routes']) { if (!requiredRecord(consumer)[1].imports?.includes(budgetKey)) throw new Error('Invalid owned budgets compiler edge'); @@ -640,6 +684,63 @@ export async function auditOutput(webDirectory) { throw new Error('Invalid owned SDK compiler chunk'); } } + if (hasProductPresentation) { + const records = Object.entries(manifest); + const entry = (/** @type {string} */ name) => { + const row = records.find(([, r]) => r.name === name); + if (!row) throw new Error('Missing product compiler module'); + return row; + }; + const [publisherKey, publisher] = entry('publishers'); + if ( + !/^_[A-Za-z0-9_-]+\.js$/.test(publisherKey) || + Object.keys(publisher).some( + (field) => !['file', 'name', 'imports'].includes(field) + ) + ) + throw new Error('Invalid owned product compiler identity'); + equal( + publisher.imports, + ['public-key', 'Disclosure', 'budgets'].map((name) => entry(name)[0]), + 'Invalid owned product publisher compiler dependencies' + ); + equal( + entry('nodes/7')[1].imports, + [ + 'rolldown-runtime', + 'references', + 'Disclosure', + 'client', + 'budgets', + 'client.svelte', + 'state', + 'Button', + 'publishers' + ].map((name) => entry(name)[0]), + 'Invalid owned product compiler dependencies' + ); + equal( + entry('nodes/9')[1].imports, + [ + 'references', + 'Disclosure', + 'client', + 'budgets', + 'client.svelte', + 'navigation', + 'state', + 'Button', + 'routes', + 'publishers' + ].map((name) => entry(name)[0]), + 'Invalid owned search product compiler dependencies' + ); + if ( + entry('nodes/7')[1].dynamicImports !== undefined || + entry('nodes/9')[1].dynamicImports !== undefined + ) + throw new Error('Invalid owned product compiler dynamic imports'); + } if (hasFullRoutes) { const robots = await readOwned(web, 'static/robots.txt'); publicText(robots); diff --git a/web/tools/source-boundaries.mjs b/web/tools/source-boundaries.mjs @@ -117,7 +117,8 @@ function mutationAdmission( ast, report, identity = () => null, - reviewedScroll = false + reviewedScroll = false, + reviewedCopy = false ) { // Bind this admitted AST only, without libs, module resolution, file reads, // config loading or evaluation. Symbols distinguish aliases and shadowing. @@ -839,6 +840,35 @@ function mutationAdmission( !(ts.isCallExpression(node.parent) && node.parent.expression === node) ) report('escaped goto capability is forbidden'); + if ( + name === 'clipboard' && + (global(node.expression, ['navigator']) || + ((ts.isPropertyAccessExpression(node.expression) || + ts.isElementAccessExpression(node.expression)) && + member(node.expression) === 'navigator' && + ts.isIdentifier(node.expression.expression) && + ['window', 'globalThis', 'self'].includes( + node.expression.expression.text + ) && + !checker.getSymbolAtLocation(node.expression.expression) + ?.declarations?.length)) + ) { + const action = node.parent; + const call = action.parent; + if ( + !reviewedCopy || + !global(node.expression, ['navigator']) || + !ts.isPropertyAccessExpression(action) || + action.expression !== node || + action.name.text !== 'writeText' || + !ts.isCallExpression(call) || + call.expression !== action || + call.arguments.length !== 1 + ) + report( + 'clipboard capability requires the exact reviewed public copy action' + ); + } if (location(node) && !locationUse(node)) report('opaque Location capability is forbidden'); if ( @@ -1487,6 +1517,16 @@ export async function auditSource(root) { complain(file, `unresolved production import ${specifier}`); } } + const copyFile = path.join(root, 'src/lib/navigation-copy.ts'); + const copyTrusted = + files.has(copyFile) && + createHash('sha256').update(files.get(copyFile)).digest('hex') === + '1a17eac4b355d8a3fb2b55b3fe1bc856cc3b3bce07434836d708b68407686f20'; + if (files.has(copyFile) && !copyTrusted) + complain( + copyFile, + 'copy helper source identity does not match reviewed pin' + ); const scrollFile = path.join(root, 'src/lib/navigation-scroll.ts'); const scrollTrusted = files.has(scrollFile) && @@ -1990,7 +2030,8 @@ export async function auditSource(root) { : null : exportIdentity(target, exported); }, - file === scrollFile && scrollTrusted + file === scrollFile && scrollTrusted, + file === copyFile && copyTrusted ); if (ast.referencedFiles.length || ast.typeReferenceDirectives.length) complain(file, 'source reference directives are forbidden');