app

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

commit 547813797c84dcee167ecc0f7db2c8670688acf0
parent dcd277990ae12610c82162619422ffdcdb4c1f42
Author: triesap <tyson@radroots.org>
Date:   Fri,  9 Oct 2026 21:16:48 +0000

messages: capture a product enquiry to the verified publisher (HCP-106)

Diffstat:
Mweb/src/lib/catalog/product-view.ts | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/components/ProductEnquiry.svelte | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/messaging/product-enquiry.ts | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/src/routes/products/[naddr=naddr]/+page.svelte | 12++++++++----
Aweb/tests/e2e/harness/product-enquiry-panel.svelte | 27+++++++++++++++++++++++++++
Aweb/tests/e2e/harness/product-enquiry.ts | 203+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/e2e/product-details.spec.ts | 4+++-
Aweb/tests/e2e/product-enquiry.spec.ts | 515+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/provenance/output.test.mjs | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Aweb/tests/unit/product-enquiry.test.ts | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tools/check-output.mjs | 313+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
11 files changed, 1386 insertions(+), 103 deletions(-)

diff --git a/web/src/lib/catalog/product-view.ts b/web/src/lib/catalog/product-view.ts @@ -9,6 +9,7 @@ import { publicViewProjectionAvailable, publicViewRunCurrent, publicViewOwnsRun, + publicViewKnownEvidence, subscribePublicView, type PublicView } from '../runtime/public-runtime.ts'; @@ -22,6 +23,7 @@ import { import { createPublicHeadCandidate, publicHeadSnapshot, + publicHeadEnvelope, selectPublicHead, type PublicHead } from './heads.ts'; @@ -38,6 +40,7 @@ import { type PublisherView } from './publishers.ts'; import type { FoodProjection } from '../contracts/food-availability-v1/read.ts'; +import type { VerifiedEnvelope } from '../nostr/verified-envelope.ts'; import type { WallClock } from './clock-policy.ts'; import type { ForegroundSchedule } from './search-view.ts'; export type ProductViewSnapshot = Readonly<{ @@ -63,8 +66,14 @@ declare const productBrand: unique symbol; export type ProductView = Readonly<{ readonly [productBrand]: true }>; interface Owner { snapshot: () => ProductViewSnapshot; + listing: () => ProductListingOwnership | undefined; close: () => void; } +export type ProductListingOwnership = Readonly<{ + proof: VerifiedEnvelope; + available: () => boolean; + current: () => boolean; +}>; const owners = new WeakMap<ProductView, Owner>(); function ownerOf(token: ProductView): Owner { const owner = owners.get(token); @@ -188,7 +197,36 @@ export function createProductView( const token = Object.freeze({}) as ProductView; owners.set(token, { snapshot, + listing() { + const observed = snapshot(); + if (observed.outcome !== 'active' || observed.lastKnown || !head) return; + const selected = publicViewKnownEvidence(view, head).head; + const metadata = publicHeadSnapshot(selected); + if ( + metadata.id !== observed.eventId || + metadata.pubkey !== reference.pubkey || + metadata.identifier !== reference.identifier + ) + return; + return { + proof: publicHeadEnvelope(selected), + available: () => + !closed && + publicViewOwnsRun(view, run) && + publicViewProjectionAvailable(view), + current() { + const actual = snapshot(); + return ( + !closed && + actual.outcome === 'active' && + !actual.lastKnown && + actual.eventId === metadata.id + ); + } + }; + }, close() { + const notifyTerminal = !closed; closed = true; const previous = cancel; cancel = undefined; @@ -205,6 +243,12 @@ export function createProductView( } catch { error = true; } + if (notifyTerminal) + try { + onUpdate(snapshot()); + } catch { + /* Terminal observer cannot prevent original revocation/cleanup. */ + } if (error) throw Error('product_view_close_failed'); } }); @@ -269,3 +313,10 @@ export function productViewSnapshot(token: ProductView): ProductViewSnapshot { export function closeProductView(token: ProductView): void { ownerOf(token).close(); } +// Only the original current view resolves the observed signed proof. Detached +// UI snapshots cannot create this witness or select another author/version. +export function productViewListingOwnership( + token: ProductView +): ProductListingOwnership | undefined { + return owners.get(token)?.listing(); +} diff --git a/web/src/lib/components/ProductEnquiry.svelte b/web/src/lib/components/ProductEnquiry.svelte @@ -0,0 +1,101 @@ +<script module lang="ts"> + declare function setInterval( + callback: () => void, + milliseconds: number + ): number; + declare function clearInterval(timer: number): void; +</script> + +<script lang="ts"> + import { onMount, untrack } from 'svelte'; + import type { + ProductView, + ProductViewSnapshot + } from '../catalog/product-view.ts'; + import { + captureProductEnquiry, + productEnquirySnapshot, + updateProductEnquiry, + closeProductEnquiry, + type ProductEnquiry + } from '../messaging/product-enquiry.ts'; + import Button from './primitives/Button.svelte'; + let { + view, + observation, + oncapture + }: { + view: ProductView; + observation?: ProductViewSnapshot; + oncapture?: (draft: ProductEnquiry) => void; + } = $props(); + let draft = $state.raw<ProductEnquiry | undefined>(), + captured = $state<ReturnType<typeof productEnquirySnapshot>>(); + onMount(() => { + const timer = setInterval(() => { + if (draft) captured = productEnquirySnapshot(draft); + }, 250); + return () => clearInterval(timer); + }); + $effect(() => { + const original = view; + return () => + untrack(() => { + void original; + if (draft) closeProductEnquiry(draft); + draft = undefined; + captured = undefined; + }); + }); + $effect(() => { + void observation; + if (draft) captured = productEnquirySnapshot(draft); + }); + function open() { + if (draft) closeProductEnquiry(draft); + draft = captureProductEnquiry(view, 'reviewed_product_enquiry'); + captured = draft ? productEnquirySnapshot(draft) : undefined; + if (draft) oncapture?.(draft); + } + function edit(value: string) { + if (!draft) return; + if (updateProductEnquiry(draft, value, 'reviewed_product_enquiry_edit')) + captured = productEnquirySnapshot(draft); + } +</script> + +{#if captured} + <section class="stack" aria-label="Product request"> + <h2>Message about {captured.title}</h2> + <p>Publisher: <code>{captured.peer}</code></p> + <p>Advertised price (seller assertion): {captured.advertisedPrice}</p> + <label + >Your message<textarea + value={captured.text} + oninput={(event) => edit(event.currentTarget.value)}></textarea></label + > + <details> + <summary>Included product references</summary> + <p>Product: <code>nostr:{captured.naddr}</code></p> + <p>Viewed listing: <code>nostr:{captured.nevent}</code></p> + </details> + <p>Not yet saved. Unsent text is lost when this page closes.</p> + {#if !captured.listingCurrent}<p role="status"> + Listing status needs review. Your unsent text is kept in memory. + </p>{/if} + <p> + This is a message, not a confirmed order. It does not reserve the food. + </p> + <Button label="Send request" disabled={true} /> + <p> + Connect and prepare your inbox to send a request. No message has been + sent. + </p> + </section> +{:else} + <Button + label="Message seller" + onclick={open} + disabled={observation?.outcome !== 'active' || observation.lastKnown} + /> +{/if} diff --git a/web/src/lib/messaging/product-enquiry.ts b/web/src/lib/messaging/product-enquiry.ts @@ -0,0 +1,132 @@ +import { + productViewListingOwnership, + type ProductView +} from '../catalog/product-view.ts'; +import { + captureEnquiryContext, + enquiryContextSnapshot, + buildEnquiryMessage, + type EnquiryContextSnapshot +} from './enquiry-context.ts'; +import { openInboxConversation, type InboxView } from './inbox-view.ts'; +import type { MessageWireParts } from '../contracts/message-v1/index.ts'; + +declare const enquiryBrand: unique symbol; +export type ProductEnquiry = Readonly<{ readonly [enquiryBrand]: true }>; +type Snapshot = EnquiryContextSnapshot & + Readonly<{ + text: string; + memoryOnly: true; + saved: false; + listingCurrent: boolean; + }>; +type Owner = { + snapshot(): Snapshot | undefined; + message(): MessageWireParts | undefined; + update(text: unknown, review: unknown): boolean; + reuse(view: InboxView, review: unknown): Promise<string | undefined>; + close(): void; +}; +const owners = new WeakMap<ProductEnquiry, Owner>(); + +// A guest may capture and edit a memory-only draft. This is neither identity, +// inbox readiness nor Send authority, and performs no network/native/SDK call. +export function captureProductEnquiry( + view: ProductView, + review: unknown +): ProductEnquiry | undefined { + if (typeof window === 'undefined' || review !== 'reviewed_product_enquiry') + return; + const listing = productViewListingOwnership(view); + if (!listing?.current()) return; + const context = captureEnquiryContext(listing.proof); + const observed = context && enquiryContextSnapshot(context); + if (!context || !observed || observed.status !== 'active') return; + let active = true, + text = `Hello, I am interested in ${JSON.stringify(observed.title)}. Is it available?`; + if (!buildEnquiryMessage(context, text)) return; + function close() { + active = false; + text = ''; + } + function current() { + if (!active || !listing!.available()) { + close(); + return false; + } + return true; + } + const token = Object.freeze({}) as ProductEnquiry; + owners.set(token, { + snapshot() { + return current() + ? { + ...observed, + text, + memoryOnly: true, + saved: false, + listingCurrent: listing.current() + } + : undefined; + }, + message() { + return current() && listing.current() + ? buildEnquiryMessage(context, text) + : undefined; + }, + update(value, permission) { + if ( + permission !== 'reviewed_product_enquiry_edit' || + !current() || + typeof value !== 'string' || + !buildEnquiryMessage(context, value) + ) + return false; + text = value; + return true; + }, + async reuse(inbox, permission) { + if ( + permission !== 'reviewed_product_enquiry_conversation' || + !current() || + !listing.current() + ) + return; + const path = await openInboxConversation( + inbox, + observed.peer, + 'reviewed_admitted_conversation_navigation' + ); + return current() && listing.current() ? path : undefined; + }, + close + }); + return token; +} +export function productEnquirySnapshot( + token: ProductEnquiry +): Snapshot | undefined { + return owners.get(token)?.snapshot(); +} +export function productEnquiryMessage( + token: ProductEnquiry +): MessageWireParts | undefined { + return owners.get(token)?.message(); +} +export function updateProductEnquiry( + token: ProductEnquiry, + text: unknown, + review: unknown +): boolean { + return owners.get(token)?.update(text, review) ?? false; +} +export function reuseProductEnquiryConversation( + token: ProductEnquiry, + view: InboxView, + review: unknown +): Promise<string | undefined> { + return owners.get(token)?.reuse(view, review) ?? Promise.resolve(undefined); +} +export function closeProductEnquiry(token: ProductEnquiry): void { + owners.get(token)?.close(); +} diff --git a/web/src/routes/products/[naddr=naddr]/+page.svelte b/web/src/routes/products/[naddr=naddr]/+page.svelte @@ -24,11 +24,13 @@ import PublisherIdentity from '../../../lib/components/PublisherIdentity.svelte'; import Disclosure from '../../../lib/components/primitives/Disclosure.svelte'; import Button from '../../../lib/components/primitives/Button.svelte'; + import ProductEnquiry from '../../../lib/components/ProductEnquiry.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>(); + let productOwner = $state.raw<ProductView | undefined>(); const reference = $derived(decodeProductReference(page.params.naddr)); const contact = $derived(readPublicContact(result?.food?.content)); let disposed = false; @@ -56,6 +58,7 @@ const selected = reference, shared = runtime; result = undefined; + productOwner = undefined; copyNotice = undefined; if (!selected || !shared) return; let active = true, @@ -71,6 +74,7 @@ if (active && !disposed) result = value; } ); + productOwner = owner; error = undefined; } catch { error = 'Food sources are unavailable.'; @@ -140,10 +144,10 @@ {#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} + {#if productOwner}<ProductEnquiry + view={productOwner} + observation={result} + />{/if}{/if} <Disclosure summary="Listing and source details"> {#if result.eventId}<p> Listing version: <code>{result.eventId}</code> diff --git a/web/tests/e2e/harness/product-enquiry-panel.svelte b/web/tests/e2e/harness/product-enquiry-panel.svelte @@ -0,0 +1,27 @@ +<script lang="ts"> + import ProductEnquiry from '../../../src/lib/components/ProductEnquiry.svelte'; + import type { + ProductView, + ProductViewSnapshot + } from '../../../src/lib/catalog/product-view.ts'; + import type { ProductEnquiry as Draft } from '../../../src/lib/messaging/product-enquiry.ts'; + let { + view, + observe, + capture + }: { + view: ProductView; + observe: (callback: (value: ProductViewSnapshot) => void) => () => void; + capture: (draft: Draft) => void; + } = $props(); + let observation = $state.raw<ProductViewSnapshot | undefined>(); + $effect(() => + observe((value) => { + observation = value; + }) + ); +</script> + +<section data-enquiry-fixture> + <ProductEnquiry {view} {observation} oncapture={capture} /> +</section> diff --git a/web/tests/e2e/harness/product-enquiry.ts b/web/tests/e2e/harness/product-enquiry.ts @@ -0,0 +1,203 @@ +import { mount, unmount, tick } from 'svelte'; +import Panel from './product-enquiry-panel.svelte'; +import { renderFixture as renderThread } from './conversation-thread.ts'; +import { validateRelayPolicy } from '../../../src/lib/config/relays.ts'; +import { + createPublicRuntimeContext, + mountPublicRuntime, + createPublicView, + closePublicRuntime +} from '../../../src/lib/runtime/public-runtime.ts'; +import { + createProductView, + productViewSnapshot, + closeProductView, + type ProductViewSnapshot +} from '../../../src/lib/catalog/product-view.ts'; +import { encodeProductReference } from '../../../src/lib/nostr/references.ts'; +import { getPublicKey } from 'applesauce-core/helpers'; +import { + captureProductEnquiry, + productEnquirySnapshot, + productEnquiryMessage, + updateProductEnquiry, + reuseProductEnquiryConversation, + closeProductEnquiry, + type ProductEnquiry +} from '../../../src/lib/messaging/product-enquiry.ts'; +import type { InboxView } from '../../../src/lib/messaging/inbox-view.ts'; +export { beforeNavigate, goto } from './conversation-thread.ts'; + +export async function renderFixture(existing = false) { + const thread = existing ? await renderThread('inbound') : undefined; + if (thread) { + await thread.checkSetup(); + if (!(await thread.unlock())) throw Error('original pair unavailable'); + } + const preparationCounts = thread?.delta() ?? { + decrypts: 0, + signs: 0, + encrypts: 0 + }; + const policy = validateRelayPolicy( + JSON.stringify({ + schemaVersion: 1, + public: [ + { + origin: 'wss://discovery.example.org', + read: true, + write: false, + nip50: false + } + ], + inbox: [], + postingEnabled: false, + messagingEnabled: false, + operatorDenylist: [] + }) + ); + if (!policy) throw Error('invalid fixed test policy'); + const context = createPublicRuntimeContext(); + let offset = 0; + const runtime = mountPublicRuntime(context, policy, { + now: () => performance.now() + offset, + schedule(callback, delay) { + const timer = setTimeout(callback, delay); + return () => clearTimeout(timer); + } + }); + if (!runtime) throw Error('original runtime unavailable'); + const reference = encodeProductReference({ + kind: 30402, + pubkey: getPublicKey(new Uint8Array(32).fill(84)), + identifier: 'carrots' + }); + if (!reference) throw Error('invalid public coordinate'); + const observers = new Set<(value: ProductViewSnapshot) => void>(); + const view = createProductView( + createPublicView(runtime), + reference, + { nowSeconds: () => 1700000200 }, + (value) => { + for (const callback of observers) callback(value); + } + ); + const target = document.createElement('div'); + document.body.append(target); + let draft: ProductEnquiry | undefined; + const mounted = mount(Panel, { + target, + props: { + view, + observe(callback: (value: ProductViewSnapshot) => void) { + observers.add(callback); + callback(productViewSnapshot(view)); + return () => { + observers.delete(callback); + }; + }, + capture(value: ProductEnquiry) { + draft = value; + } + } + }); + function capture(review: unknown = 'reviewed_product_enquiry') { + const captured = captureProductEnquiry(view, review); + if (captured) { + if (draft) closeProductEnquiry(draft); + draft = captured; + } + return !!captured; + } + let closed = false; + return { + viewSnapshot: () => productViewSnapshot(view), + capture, + snapshot: () => draft && productEnquirySnapshot(draft), + message: () => draft && productEnquiryMessage(draft), + update: (text: string) => + !!draft && + updateProductEnquiry(draft, text, 'reviewed_product_enquiry_edit'), + native: () => + thread + ? thread.native() + : Promise.resolve({ received: [], pairs: [], sends: [] }), + delta: () => { + const actual = thread?.delta() ?? { decrypts: 0, signs: 0, encrypts: 0 }; + return { + decrypts: actual.decrypts - preparationCounts.decrypts, + signs: actual.signs - preparationCounts.signs, + encrypts: actual.encrypts - preparationCounts.encrypts + }; + }, + knownPath: () => (thread ? '/messages/' + thread.knownId : undefined), + reuse: () => + draft && thread + ? reuseProductEnquiryConversation( + draft, + thread.controller, + 'reviewed_product_enquiry_conversation' + ) + : Promise.resolve(undefined), + async copied() { + const fake = {} as ProductEnquiry; + return { + view: !!captureProductEnquiry({ ...view }, 'reviewed_product_enquiry'), + snapshot: productEnquirySnapshot(fake), + message: productEnquiryMessage(fake), + update: updateProductEnquiry( + fake, + 'forged', + 'reviewed_product_enquiry_edit' + ), + reuse: + draft && + (await reuseProductEnquiryConversation( + draft, + {} as InboxView, + 'reviewed_product_enquiry_conversation' + )) + }; + }, + async unreviewed() { + return { + capture: !!captureProductEnquiry(view, undefined), + update: !!draft && updateProductEnquiry(draft, 'unreviewed', undefined), + reuse: + draft && + thread && + (await reuseProductEnquiryConversation( + draft, + thread.controller, + undefined + )) + }; + }, + async persistentText() { + const native = thread ? await thread.native() : undefined; + return JSON.stringify({ + url: location.href, + local: { ...localStorage }, + session: { ...sessionStorage }, + native + }); + }, + advance() { + offset += 15001; + }, + async closeView() { + closeProductView(view); + await tick(); + }, + async close() { + if (closed) return; + closed = true; + if (draft) closeProductEnquiry(draft); + closeProductView(view); + closePublicRuntime(context); + await unmount(mounted); + target.remove(); + await thread?.close(); + } + }; +} diff --git a/web/tests/e2e/product-details.spec.ts b/web/tests/e2e/product-details.spec.ts @@ -298,7 +298,9 @@ test('real product reload renders verified facts, safe guest contact, explicit c page.getByRole('button', { name: 'Message seller', exact: true }) ).toBeDisabled(); await expect( - page.getByText('In-app messaging is unavailable during development.') + page.getByText( + 'This is last-known information. The listing status check is incomplete.' + ) ).toBeVisible(); await expect( page.getByRole('button', { name: 'Manage listing' }) diff --git a/web/tests/e2e/product-enquiry.spec.ts b/web/tests/e2e/product-enquiry.spec.ts @@ -0,0 +1,515 @@ +import { test, expect, type Page } from '@playwright/test'; +import { build } from 'vite'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; +import { fileURLToPath } from 'node:url'; +import { once } from 'node:events'; +import { WebSocketServer } from 'ws'; +import { finalizeEvent, getPublicKey } from 'applesauce-core/helpers'; +import { createStaticHarness } from '../integration/harness/static.ts'; +import type * as Fixture from './harness/product-enquiry.ts'; +declare global { + interface Window { + hcp106: typeof Fixture; + hcp106Fixture: Awaited<ReturnType<typeof Fixture.renderFixture>>; + } +} +let server: Awaited<ReturnType<typeof createStaticHarness>>, + sockets: WebSocketServer, + endpoint: string, + bundle: string; +type Mode = + | 'normal' + | 'missing' + | 'wrong_author' + | 'wrong_coordinate' + | 'invalid_signature' + | 'sold' + | 'deleted' + | 'partial'; +let mode: Mode = 'normal', + requests: unknown[][] = [], + events: unknown[][] = []; +const secret = new Uint8Array(32).fill(84), + otherSecret = new Uint8Array(32).fill(90), + peer = getPublicKey(secret); +function listing(createdAt = 1700000060) { + const event = finalizeEvent( + { + kind: 30402, + created_at: createdAt, + content: 'Independently signed carrots', + tags: [ + ['d', mode === 'wrong_coordinate' ? 'apples' : 'carrots'], + ['title', 'Verified carrots'], + ['summary', 'Actual signed listing'], + ['published_at', '1700000000'], + ['location', 'Victoria'], + ['price', '3.5', 'CAD'], + ['radroots:price_unit', 'lb'], + ['status', mode === 'sold' ? 'sold' : 'active'] + ] + }, + mode === 'wrong_author' ? otherSecret : secret + ); + return mode === 'invalid_signature' + ? { ...event, sig: '0'.repeat(128) } + : event; +} +test.beforeAll(async () => { + server = await createStaticHarness(); + sockets = new WebSocketServer({ + host: '127.0.0.1', + port: 0, + maxPayload: 65536 + }); + await once(sockets, 'listening'); + const address = sockets.address(); + if (!address || typeof address === 'string') throw Error('no loopback'); + endpoint = 'ws://127.0.0.1:' + address.port; + sockets.on('connection', (socket) => + socket.on('message', (bytes) => { + const raw = Buffer.isBuffer(bytes) + ? bytes + : Array.isArray(bytes) + ? Buffer.concat(bytes) + : Buffer.from(bytes); + const frame = JSON.parse(raw.toString()) as unknown[]; + if (frame[0] === 'EVENT') { + events.push(frame); + return; + } + if (frame[0] !== 'REQ') return; + requests.push(frame); + const filters = frame.slice(2) as { kinds?: number[]; ids?: string[] }[]; + const send = () => { + if (mode !== 'missing') { + if (filters.some((f) => f.kinds?.includes(0))) + socket.send( + JSON.stringify([ + 'EVENT', + frame[1], + finalizeEvent( + { + kind: 0, + created_at: 1700000060, + tags: [], + content: JSON.stringify({ name: 'Another display name' }) + }, + secret + ) + ]) + ); + if (filters.some((f) => f.kinds?.includes(30402))) { + const exact = filters.find((f) => f.ids)?.ids; + const event = exact?.includes(listing(1700000050).id) + ? listing(1700000050) + : listing(); + socket.send(JSON.stringify(['EVENT', frame[1], event])); + } + if (mode === 'deleted' && filters.some((f) => f.kinds?.includes(5))) + socket.send( + JSON.stringify([ + 'EVENT', + frame[1], + finalizeEvent( + { + kind: 5, + created_at: 1700000070, + tags: [['a', '30402:' + peer + ':carrots']], + content: '' + }, + secret + ) + ]) + ); + } + if (!( + mode === 'partial' && + filters.some((filter) => filter.kinds?.includes(5)) + )) + socket.send(JSON.stringify(['EOSE', frame[1]])); + }; + send(); + }) + ); + const result = await build({ + configFile: false, + logLevel: 'silent', + plugins: [svelte({ configFile: false })], + resolve: { + conditions: ['browser'], + alias: { + '$app/navigation': fileURLToPath( + new URL('./harness/product-enquiry.ts', import.meta.url) + ) + } + }, + build: { + write: false, + minify: false, + lib: { + entry: fileURLToPath( + new URL('./harness/product-enquiry.ts', import.meta.url) + ), + name: 'hcp106', + formats: ['iife'] + } + } + }); + const output = Array.isArray(result) ? result[0] : result; + if (!('output' in output)) throw Error('no bundle'); + const chunks = output.output.filter((row) => row.type === 'chunk'); + expect(chunks).toHaveLength(1); + bundle = chunks[0].code; +}); +test.afterAll(async () => { + for (const socket of sockets.clients) socket.terminate(); + await new Promise<void>((resolve) => sockets.close(() => resolve())); + await server.close(); +}); +test.beforeEach(async ({ page }) => { + mode = 'normal'; + requests = []; + events = []; + await page.addInitScript( + ({ endpoint }) => { + const Native = window.WebSocket; + window.WebSocket = class extends Native { + constructor(url: string | URL, protocols?: string | string[]) { + if ( + ![ + 'wss://discovery.example.org', + 'wss://archive.example.org', + 'wss://peer.example.org' + ].includes(new URL(String(url)).origin) + ) + throw Error('unapproved destination'); + super(endpoint, protocols); + } + }; + }, + { endpoint } + ); + await page.goto(server.url + '/search'); + await page.addScriptTag({ content: bundle }); +}); + +test.afterEach(async ({ page }) => { + if (!page.isClosed()) + await page.evaluate(() => window.hcp106Fixture?.close()); +}); +async function ready(page: Page, existing = false) { + await page.evaluate(async (existing) => { + window.hcp106Fixture = await window.hcp106.renderFixture(existing); + }, existing); + await expect(page.locator('[data-enquiry-fixture]')).toBeVisible(); + if (existing) + await expect + .poll(() => + page.evaluate(async () => + (await window.hcp106Fixture.native()).received.every( + (row) => + (JSON.parse((row as { wire: string }).wire) as { read: unknown }) + .read !== null + ) + ) + ) + .toBe(true); + await expect + .poll(() => + page.evaluate(() => window.hcp106Fixture.viewSnapshot().outcome) + ) + .not.toBe('checking'); +} +const panel = (page: Page) => page.locator('[data-enquiry-fixture]'); +const open = (page: Page) => + panel(page) + .getByRole('button', { name: 'Message seller', exact: true }) + .click(); +test('explicit guest enquiry captures the signed publisher and readable viewed context without connection or Send', async ({ + page +}) => { + await ready(page); + const before = requests.length; + await expect( + panel(page).getByRole('textbox', { name: 'Your message', exact: true }) + ).toHaveCount(0); + await open(page); + await expect( + panel(page).getByRole('textbox', { name: 'Your message', exact: true }) + ).toBeVisible(); + await expect(panel(page)).toContainText('Verified carrots'); + await expect(panel(page)).toContainText(peer); + await expect(panel(page)).toContainText('not a confirmed order'); + expect(await page.evaluate(() => window.hcp106Fixture.snapshot()?.peer)).toBe( + peer + ); + expect(requests).toHaveLength(before); + expect(events).toEqual([]); + expect(await page.evaluate(() => window.hcp106Fixture.delta())).toEqual({ + decrypts: 0, + signs: 0, + encrypts: 0 + }); +}); +test('exact canonical coordinate and signed listing version survive capture and the first message has no parent', async ({ + page +}) => { + await ready(page); + await open(page); + const actual = await page.evaluate(() => ({ + snapshot: window.hcp106Fixture.snapshot(), + message: window.hcp106Fixture.message() + })); + expect(actual.snapshot?.eventId).toBe(listing().id); + expect(actual.message?.tags).toEqual([['p', peer]]); + expect(actual.message?.content).toContain('nostr:' + actual.snapshot?.naddr); + expect(actual.message?.content).toContain('nostr:' + actual.snapshot?.nevent); + expect(actual.message?.content).toContain('3.5 CAD/lb'); + expect(actual.message?.content).toContain('not a confirmed order'); + expect( + actual.message?.tags.some((tag) => + ['e', 'a', 'q', 'order', 'thread'].includes(tag[0]) + ) + ).toBe(false); + expect(events).toEqual([]); +}); +test('editable amount timing and fake recipient assertions never change the publisher references or inventory', async ({ + page +}) => { + await ready(page, true); + const before = await page.evaluate(() => window.hcp106Fixture.native()); + await open(page); + const text = '2 kg Thursday. Send to ' + getPublicKey(otherSecret); + await panel(page) + .getByRole('textbox', { name: 'Your message', exact: true }) + .fill(text); + const message = await page.evaluate(() => window.hcp106Fixture.message()); + expect(message?.tags).toEqual([['p', peer]]); + expect(message?.content).toContain(text); + expect(message?.content).toContain('nostr:'); + expect(await page.evaluate(() => window.hcp106Fixture.native())).toEqual( + before + ); + expect(await page.evaluate(() => window.hcp106Fixture.delta())).toEqual({ + decrypts: 0, + signs: 0, + encrypts: 0 + }); + expect(events).toEqual([]); +}); +test('a display name never becomes recipient authority or creates a shop route', async ({ + page +}) => { + await ready(page); + await open(page); + expect( + await page.evaluate(() => window.hcp106Fixture.message()?.tags) + ).toEqual([['p', peer]]); + expect( + await panel(page) + .locator('a[href*="/shops/"],a[href*="/profiles/"]') + .count() + ).toBe(0); + expect(events).toEqual([]); +}); +test('only an actual admitted original pair can be explicitly reused without a new UUID or message parent', async ({ + page +}) => { + await ready(page, true); + const before = await page.evaluate(() => window.hcp106Fixture.native()); + await open(page); + expect(await page.evaluate(() => window.hcp106Fixture.reuse())).toBe( + await page.evaluate(() => window.hcp106Fixture.knownPath()) + ); + expect(await page.evaluate(() => window.hcp106Fixture.native())).toEqual( + before + ); + expect( + await page.evaluate(() => window.hcp106Fixture.message()?.tags) + ).toEqual([['p', peer]]); + expect(events).toEqual([]); +}); +test('copied view enquiry and inbox tokens cannot borrow publisher private draft or conversation authority', async ({ + page +}) => { + await ready(page, true); + await open(page); + const before = await page.evaluate(() => window.hcp106Fixture.native()); + expect(await page.evaluate(() => window.hcp106Fixture.copied())).toEqual({ + view: false, + snapshot: undefined, + message: undefined, + update: false, + reuse: undefined + }); + expect(await page.evaluate(() => window.hcp106Fixture.native())).toEqual( + before + ); + expect(events).toEqual([]); +}); +test('unreviewed capture editing and reuse do not change the original memory-only draft', async ({ + page +}) => { + await ready(page, true); + await open(page); + const before = await page.evaluate(() => window.hcp106Fixture.snapshot()); + expect(await page.evaluate(() => window.hcp106Fixture.unreviewed())).toEqual({ + capture: false, + update: false, + reuse: undefined + }); + expect(await page.evaluate(() => window.hcp106Fixture.snapshot())).toEqual( + before + ); + expect(events).toEqual([]); +}); +test('private draft text is absent from URLs local storage and actual native persistence', async ({ + page +}) => { + await ready(page, true); + await open(page); + const text = 'PRIVATE HCP106 guest enquiry zebra'; + await panel(page) + .getByRole('textbox', { name: 'Your message', exact: true }) + .fill(text); + expect( + await page.evaluate(() => window.hcp106Fixture.persistentText()) + ).not.toContain(text); + expect(events).toEqual([]); +}); +test('closing the original product view invalidates its draft and cannot produce a later message', async ({ + page +}) => { + await ready(page); + await open(page); + await page.evaluate(() => window.hcp106Fixture.closeView()); + expect( + await page.evaluate(() => window.hcp106Fixture.snapshot()) + ).toBeUndefined(); + expect( + await page.evaluate(() => window.hcp106Fixture.message()) + ).toBeUndefined(); + expect(await page.evaluate(() => window.hcp106Fixture.update('late'))).toBe( + false + ); + expect(events).toEqual([]); +}); +for (const rejection of [ + 'missing', + 'wrong_author', + 'wrong_coordinate', + 'invalid_signature', + 'sold', + 'deleted' +] as const) + test( + 'unavailable or untrusted listing cannot allocate an enquiry: ' + rejection, + async ({ page }) => { + mode = rejection; + await ready(page); + expect(await page.evaluate(() => window.hcp106Fixture.capture())).toBe( + false + ); + expect( + await page.evaluate(() => window.hcp106Fixture.message()) + ).toBeUndefined(); + await expect( + panel(page).getByRole('textbox', { name: 'Your message', exact: true }) + ).toHaveCount(0); + expect(events).toEqual([]); + } + ); +test('incomplete deletion coverage is not silently admitted as current enquiry context', async ({ + page +}) => { + mode = 'partial'; + await ready(page); + await page.evaluate(() => window.hcp106Fixture.advance()); + expect( + await page.evaluate(() => window.hcp106Fixture.viewSnapshot().lastKnown) + ).toBe(true); + expect(await page.evaluate(() => window.hcp106Fixture.capture())).toBe(false); + expect(events).toEqual([]); +}); + +test('original Close revokes mounted private guest text and request controls without side effects', async ({ + page +}) => { + await ready(page, true); + await open(page); + const text = 'PRIVATE HCP106 terminal guest text'; + await panel(page) + .getByRole('textbox', { name: 'Your message', exact: true }) + .fill(text); + const before = await page.evaluate(async () => ({ + native: await window.hcp106Fixture.native(), + delta: window.hcp106Fixture.delta() + })); + const queryCount = requests.length; + await page.evaluate(() => window.hcp106Fixture.closeView()); + expect( + await page.evaluate(() => window.hcp106Fixture.message()) + ).toBeUndefined(); + expect( + await panel(page) + .getByRole('textbox', { name: 'Your message', exact: true }) + .count() + ).toBe(0); + expect( + await panel(page) + .getByRole('button', { name: 'Send request', exact: true }) + .count() + ).toBe(0); + expect(await panel(page).textContent()).not.toContain(text); + expect(await panel(page).textContent()).not.toContain('Viewed listing:'); + expect( + await page.evaluate(async () => ({ + native: await window.hcp106Fixture.native(), + delta: window.hcp106Fixture.delta() + })) + ).toEqual(before); + expect(requests).toHaveLength(queryCount); + expect(events).toEqual([]); +}); + +test('ordinary original finite run expiry preserves an already captured unsent guest draft', async ({ + page +}) => { + await ready(page); + await open(page); + const text = 'PRIVATE HCP106 unsent after finite run'; + await panel(page) + .getByRole('textbox', { name: 'Your message', exact: true }) + .fill(text); + const queryCount = requests.length; + await page.evaluate(() => window.hcp106Fixture.advance()); + expect(await page.evaluate(() => window.hcp106Fixture.snapshot()?.text)).toBe( + text + ); + expect( + await page.evaluate(() => window.hcp106Fixture.snapshot()?.listingCurrent) + ).toBe(false); + expect( + await page.evaluate(() => window.hcp106Fixture.message()) + ).toBeUndefined(); + await expect( + panel(page).getByRole('textbox', { name: 'Your message', exact: true }) + ).toHaveValue(text); + await expect(panel(page)).toContainText( + 'Listing status needs review. Your unsent text is kept in memory.' + ); + expect( + await page.evaluate(() => + window.hcp106Fixture.update('Still editing after expiry') + ) + ).toBe(true); + await expect( + panel(page).getByRole('textbox', { name: 'Your message', exact: true }) + ).toHaveValue('Still editing after expiry'); + expect( + await page.evaluate(() => window.hcp106Fixture.message()) + ).toBeUndefined(); + expect(requests).toHaveLength(queryCount); + expect(events).toEqual([]); +}); diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs @@ -61,6 +61,20 @@ import { auditOutput } from '../../tools/check-output.mjs'; sha256: '93e21d162901af304f2a142acc7ddce87f7826421735d8a3af4ae281744ab3a0' } }; + // Exact accepted HCP105 public product producers, frozen before enquiry. + // Restore only this public-only graph; current output retains HCP106 source. + const historicalPublicProduct = { + 'src/routes/products/[naddr=naddr]/+page.svelte': { + source: + "<script lang=\"ts\">\n import { getContext, onMount } from 'svelte';\n import { page } from '$app/state';\n import {\n PUBLIC_RUNTIME_CONTEXT,\n publicRuntimeReady,\n createPublicView,\n disposePublicView,\n type PublicView,\n type PublicRuntime,\n type PublicRuntimeContext\n } from '../../../lib/runtime/public-runtime.ts';\n import {\n createProductView,\n closeProductView,\n type ProductView,\n type ProductViewSnapshot\n } from '../../../lib/catalog/product-view.ts';\n import { decodeProductReference } from '../../../lib/nostr/references.ts';\n import { readPublicContact } from '../../../lib/contracts/food-availability-v1/contact-read.ts';\n import { copyProductReference } from '../../../lib/navigation-copy.ts';\n import { internalHref, navigationHref } from '../../../lib/navigation-url.ts';\n import ListingFacts from '../../../lib/components/ListingFacts.svelte';\n import PublisherIdentity from '../../../lib/components/PublisherIdentity.svelte';\n import Disclosure from '../../../lib/components/primitives/Disclosure.svelte';\n import Button from '../../../lib/components/primitives/Button.svelte';\n const context = getContext<PublicRuntimeContext>(PUBLIC_RUNTIME_CONTEXT);\n let runtime = $state.raw<PublicRuntime | undefined>(),\n result = $state.raw<ProductViewSnapshot | undefined>(),\n error = $state<string | undefined>(),\n copyNotice = $state<string | undefined>();\n const reference = $derived(decodeProductReference(page.params.naddr));\n const contact = $derived(readPublicContact(result?.food?.content));\n let disposed = false;\n onMount(() => {\n const unavailable = () => {\n if (!disposed) error = 'Food sources are unavailable.';\n };\n try {\n void publicRuntimeReady(context)\n .then((value) => {\n if (!disposed) {\n runtime = value;\n if (!value) unavailable();\n }\n })\n .catch(unavailable);\n } catch {\n unavailable();\n }\n return () => {\n disposed = true;\n };\n });\n $effect(() => {\n const selected = reference,\n shared = runtime;\n result = undefined;\n copyNotice = undefined;\n if (!selected || !shared) return;\n let active = true,\n acquired: PublicView | undefined,\n owner: ProductView | undefined;\n try {\n acquired = createPublicView(shared);\n owner = createProductView(\n acquired,\n selected.naddr,\n { nowSeconds: () => Math.floor(Date.now() / 1000) },\n (value) => {\n if (active && !disposed) result = value;\n }\n );\n error = undefined;\n } catch {\n error = 'Food sources are unavailable.';\n if (acquired)\n try {\n disposePublicView(acquired);\n } catch {\n /* Shared runtime keeps a failed disposer retryable. */\n }\n }\n return () => {\n active = false;\n if (owner) closeProductView(owner);\n };\n });\n async function copyLink() {\n const selected = reference;\n if (!selected) return;\n const copied = await copyProductReference(selected.naddr, page.url.origin);\n if (!disposed && reference?.naddr === selected.naddr)\n copyNotice = copied\n ? 'Link copied.'\n : 'Copy was unavailable. Select the public link below.';\n }\n</script>\n\n<svelte:head\n ><title>{result?.food?.title ?? 'Food'} — HarvestCircle</title></svelte:head\n>\n<div class=\"page page--reading stack\">\n <a href={internalHref('/search')}>Search food</a>\n <h1>{result?.food?.title ?? 'Food'}</h1>\n {#if !reference}<p class=\"notice\">This food reference is invalid.</p>\n {:else if error || result?.outcome === 'unavailable'}<p class=\"notice\">\n Food sources are unavailable.\n </p>\n {:else if !result || result.outcome === 'checking'}<p>\n Checking food sources…\n </p>\n {:else if result.outcome === 'unobserved'}<p class=\"notice\">\n This listing was not observed in the sources checked. It may be\n unavailable or missing from these sources.\n </p>\n {:else if result.outcome === 'withdrawn'}<p class=\"notice\">\n This listing was withdrawn by its publisher.\n </p>\n {:else if result.outcome === 'unsupported'}<p class=\"notice\">\n The latest known listing uses an unsupported food format.\n </p>\n {:else if result.outcome === 'future_quarantined' || result.outcome === 'clock_unavailable'}<p\n class=\"notice\"\n >\n Listing time could not be confirmed. Food details are unavailable.\n </p>{/if}\n {#if result}\n <PublisherIdentity publisher={result.publisher} />\n {#if result.lastKnown}<p class=\"notice\">\n This is last-known information. The listing status check is incomplete.\n </p>{/if}\n {#if result.food && result.createdAt !== undefined}<ListingFacts\n food={result.food}\n createdAt={result.createdAt}\n />{/if}\n {#if result.outcome === 'sold'}<p class=\"notice\">\n The seller marked this listing sold.\n </p>{/if}\n {#if result.outcome === 'active'}<p>\n Confirm availability with the seller.\n </p>\n <Button label=\"Message seller\" disabled={true} />\n <p class=\"notice\">\n In-app messaging is unavailable during development.\n </p>{/if}\n <Disclosure summary=\"Listing and source details\">\n {#if result.eventId}<p>\n Listing version: <code>{result.eventId}</code>\n </p>{/if}\n {#each result.sources as source (source.result.context)}<p>\n {source.kind}: {source.state}. Coverage: {source.result.coverage}.\n </p>\n {#each source.result.sources as relay (relay.source)}<p>\n {relay.source}: {relay.state}.\n </p>{/each}{/each}\n <p>\n These bounded checks do not prove complete coverage or current stock.\n </p>\n </Disclosure>\n {#if contact && result.outcome === 'active'}<Disclosure\n summary=\"Other contact details\"\n ><a href={navigationHref(contact.href)}>{contact.href}</a></Disclosure\n >{/if}\n {/if}\n {#if reference}<Button label=\"Copy link\" onclick={copyLink} /><a\n href={internalHref(`/products/${reference.naddr}`)}>Public food link</a\n >{/if}\n {#if copyNotice}<p role=\"status\">{copyNotice}</p>{/if}\n</div>\n", + sha256: '1869d4dc32ea794d5ee5c1d6cc6b4aac94483482d18cff0562c0cb10087b5278' + }, + 'src/lib/catalog/product-view.ts': { + source: + "import { PUBLIC_QUERY_BUDGETS } from '../config/budgets.ts';\nimport {\n decodeProductReference,\n type ProductReference\n} from '../nostr/references.ts';\nimport {\n beginPublicViewRun,\n disposePublicView,\n publicViewProjectionAvailable,\n publicViewRunCurrent,\n publicViewOwnsRun,\n subscribePublicView,\n type PublicView\n} from '../runtime/public-runtime.ts';\nimport {\n publicRequestScopeSnapshot,\n publicRunSnapshot,\n closePublicRequest,\n disposePublicRun,\n type PublicRequest\n} from '../nostr/request-scope.ts';\nimport {\n createPublicHeadCandidate,\n publicHeadSnapshot,\n selectPublicHead,\n type PublicHead\n} from './heads.ts';\nimport {\n createPublicViewHeadResolver,\n headResolutionSnapshot,\n resolveHeads,\n closeHeadResolver\n} from './resolve-head.ts';\nimport {\n createPublisherViews,\n readPublisherPage,\n publisherSnapshot,\n type PublisherView\n} from './publishers.ts';\nimport type { FoodProjection } from '../contracts/food-availability-v1/read.ts';\nimport type { WallClock } from './clock-policy.ts';\nimport type { ForegroundSchedule } from './search-view.ts';\nexport type ProductViewSnapshot = Readonly<{\n reference: ProductReference;\n outcome:\n | 'checking'\n | 'unobserved'\n | 'unavailable'\n | 'active'\n | 'sold'\n | 'withdrawn'\n | 'unsupported'\n | 'future_quarantined'\n | 'clock_unavailable';\n food: FoodProjection | undefined;\n eventId: string | undefined;\n createdAt: number | undefined;\n publisher: PublisherView;\n lastKnown: boolean;\n sources: readonly ReturnType<typeof publicRequestScopeSnapshot>[];\n}>;\ndeclare const productBrand: unique symbol;\nexport type ProductView = Readonly<{ readonly [productBrand]: true }>;\ninterface Owner {\n snapshot: () => ProductViewSnapshot;\n close: () => void;\n}\nconst owners = new WeakMap<ProductView, Owner>();\nfunction ownerOf(token: ProductView): Owner {\n const owner = owners.get(token);\n if (!owner) throw Error('product_view_invalid');\n return owner;\n}\nfunction foreground(callback: () => void, delay: number): () => void {\n const timer = setTimeout(() => {\n callback();\n }, delay);\n return () => {\n clearTimeout(timer);\n };\n}\n// One explicit route read, one coordinate, shared run/request budgets. No forged\n// seed, independent cache, relay hints, automatic refresh or additional deadline.\nexport function createProductView(\n view: PublicView,\n value: unknown,\n clock: WallClock,\n onUpdate: (value: ProductViewSnapshot) => void,\n schedule: ForegroundSchedule = foreground\n): ProductView {\n const decoded = decodeProductReference(value);\n if (!decoded) throw Error('product_reference_invalid');\n const reference = decoded;\n const run = beginPublicViewRun(view),\n resolver = createPublicViewHeadResolver(view, run, clock),\n publishers = createPublisherViews(view, clock);\n let closed = false,\n failed = false,\n head: PublicHead | undefined,\n cancel: (() => void) | undefined;\n const requests = new Map<PublicRequest, true>();\n const current = () => !closed && publicViewRunCurrent(view, run);\n function snapshot(): ProductViewSnapshot {\n const available =\n !closed &&\n publicViewProjectionAvailable(view) &&\n publicViewOwnsRun(view, run);\n const row = available ? headResolutionSnapshot(resolver)[0] : undefined;\n let scopes = Array.from(requests.keys(), publicRequestScopeSnapshot);\n for (const scope of [row?.headSources, row?.deletionSources])\n if (\n scope &&\n !scopes.some((s) => s.result.context === scope.result.context)\n )\n scopes = scopes.concat(scope);\n const complete =\n !failed &&\n scopes.length > 0 &&\n scopes.every(\n (s) => s.state === 'eose' && s.result.coverage === 'bounded-eose'\n );\n let outcome: ProductViewSnapshot['outcome'];\n if (!available) outcome = 'unavailable';\n else if (row?.deletion.outcome === 'suppressed') outcome = 'withdrawn';\n else if (\n row?.state.display === 'future_quarantined' ||\n row?.state.display === 'clock_unavailable'\n )\n outcome = row.state.display;\n else if (row?.state.display === 'unsupported') outcome = 'unsupported';\n else if (row?.state.food) outcome = row.state.food.status;\n else if (\n !row &&\n (failed ||\n (scopes.length > 0 &&\n scopes.every(\n (scope) =>\n scope.result.sources.length > 0 &&\n scope.result.sources.every(\n (source) =>\n source.state === 'error' || source.state === 'closed'\n )\n )))\n )\n outcome = 'unavailable';\n else\n outcome =\n current() && scopes.some((s) => s.state === 'active')\n ? 'checking'\n : 'unobserved';\n const publisher = publisherSnapshot(publishers, reference.pubkey);\n const stillAvailable =\n !closed &&\n publicViewProjectionAvailable(view) &&\n publicViewOwnsRun(view, run);\n return {\n reference: { ...reference },\n outcome: stillAvailable ? outcome : 'unavailable',\n food: stillAvailable ? row?.state.food : undefined,\n eventId: stillAvailable ? row?.state.head.id : undefined,\n createdAt: stillAvailable ? row?.state.head.created_at : undefined,\n publisher: stillAvailable\n ? publisher\n : {\n pubkey: reference.pubkey,\n label: reference.pubkey,\n assertedName: false\n },\n lastKnown: !stillAvailable || !complete || (row?.lastKnown ?? true),\n sources: scopes\n };\n }\n function publish() {\n const value = snapshot();\n if (!closed && publicViewOwnsRun(view, run)) onUpdate(value);\n }\n function queue() {\n if (!current() || publicRunSnapshot(run).activeRequests === 0) return;\n const next = schedule(() => {\n if (closed || !publicViewOwnsRun(view, run)) return;\n cancel = undefined;\n publish();\n queue();\n }, 250);\n if (current()) cancel = next;\n else next();\n }\n const token = Object.freeze({}) as ProductView;\n owners.set(token, {\n snapshot,\n close() {\n closed = true;\n const previous = cancel;\n cancel = undefined;\n previous?.();\n let error = false;\n try {\n closeHeadResolver(resolver);\n } catch {\n error = true;\n }\n try {\n if (publicViewOwnsRun(view, run)) disposePublicView(view);\n else disposePublicRun(run);\n } catch {\n error = true;\n }\n if (error) throw Error('product_view_close_failed');\n }\n });\n try {\n const filter =\n reference.identifier === ''\n ? {\n kinds: [30402],\n authors: [reference.pubkey],\n limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay\n }\n : {\n kinds: [30402],\n authors: [reference.pubkey],\n '#d': [reference.identifier],\n limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay\n };\n const request = subscribePublicView(\n view,\n run,\n 'head',\n [filter],\n (proof) => {\n if (!current()) return;\n const candidate = createPublicHeadCandidate(proof);\n if (!candidate) return;\n const next = publicHeadSnapshot(candidate);\n if (\n next.kind !== 30402 ||\n next.pubkey !== reference.pubkey ||\n next.identifier !== reference.identifier\n )\n return;\n head = selectPublicHead(head, candidate).head;\n try {\n resolveHeads(resolver, [head]);\n if (current())\n for (const request of readPublisherPage(publishers, run, [\n reference.pubkey\n ]))\n requests.set(request, true);\n } catch {\n failed = true;\n }\n }\n );\n requests.set(request, true);\n if (publicRequestScopeSnapshot(request).result.sources.length === 0) {\n failed = true;\n closePublicRequest(request);\n }\n } catch {\n failed = true;\n }\n publish();\n queue();\n return token;\n}\nexport function productViewSnapshot(token: ProductView): ProductViewSnapshot {\n return ownerOf(token).snapshot();\n}\nexport function closeProductView(token: ProductView): void {\n ownerOf(token).close();\n}\n", + sha256: 'e3739170e3c700246a80c1358c7b96541a5cbf1e4c26905e6ca60537adfce9cf' + } + }; const base = await mkdtemp(path.join(os.tmpdir(), 'hc actual output ')); let setupReady = false; /** @param {import('node:test').TestContext} t */ @@ -214,6 +228,13 @@ import { auditOutput } from '../../tools/check-output.mjs'; ); await writeFile(path.join(f.web, name), value.source); } + for (const [name, value] of Object.entries(historicalPublicProduct)) { + assert.equal( + createHash('sha256').update(value.source).digest('hex'), + value.sha256 + ); + await writeFile(path.join(f.web, name), value.source); + } await copyDependencies(t, base, f.web); await refresh(f); compile(t, f.web); @@ -305,7 +326,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; 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, 52); + assert.equal(files.length, 55); // 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( @@ -428,7 +449,16 @@ import { auditOutput } from '../../tools/check-output.mjs'; 'reply-missing-navigation', 'reply-missing-handles', 'context-resolver-dynamic', - 'context-resolver-entry' + 'context-resolver-entry', + 'enquiry-view-dynamic', + 'enquiry-view-entry', + 'enquiry-setup-dynamic', + 'enquiry-setup-entry', + 'enquiry-gate-dynamic', + 'enquiry-gate-entry', + 'enquiry-root-missing-gate', + 'enquiry-root-missing-css', + 'enquiry-root-extra-css' ]) await check( 'actual inbox list compiler rejects ' + mutation, @@ -442,15 +472,41 @@ import { auditOutput } from '../../tools/check-output.mjs'; const entry = Object.entries(manifest).find( ([, row]) => row.name === - (mutation.startsWith('context-') - ? 'resolve-head' - : mutation.startsWith('thread-') || - mutation.startsWith('reply-') - ? 'nodes/5' - : 'InboxStatus') + (mutation.startsWith('enquiry-view-') + ? 'inbox-view' + : mutation.startsWith('enquiry-setup-') + ? 'inbox-setup-view' + : mutation.startsWith('enquiry-gate-') + ? 'CapabilityGate' + : mutation.startsWith('enquiry-root-') + ? 'nodes/0' + : mutation.startsWith('context-') + ? 'resolve-head' + : mutation.startsWith('thread-') || + mutation.startsWith('reply-') + ? 'nodes/5' + : 'InboxStatus') ); assert.ok(entry); const [, row] = entry; + if (mutation === 'enquiry-root-missing-css') row.css = []; + if (mutation === 'enquiry-root-extra-css') + row.css = [...row.css, row.css[0]]; + if ( + mutation.startsWith('enquiry-') && + mutation.endsWith('-dynamic') + ) + row.dynamicImports = []; + if ( + mutation.startsWith('enquiry-') && + mutation.endsWith('-entry') + ) + row.isEntry = true; + if (mutation === 'enquiry-root-missing-gate') + row.imports = row.imports.filter( + (/** @type {string} */ value) => + manifest[value].name !== 'CapabilityGate' + ); if (mutation === 'context-resolver-dynamic') row.dynamicImports = []; if (mutation === 'context-resolver-entry') row.isEntry = true; @@ -543,7 +599,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; assert.ok(Buffer.byteLength(expanded) > 64 * 1024); await writeFile(file, expanded); await refresh(f); - assert.equal((await f.audit()).length, 52); + assert.equal((await f.audit()).length, 55); } ); @@ -1038,6 +1094,9 @@ import { auditOutput } from '../../tools/check-output.mjs'; for (const producer of [ 'src/routes/products/[naddr=naddr]/+page.svelte', 'src/lib/catalog/product-view.ts', + 'src/lib/components/ProductEnquiry.svelte', + 'src/lib/messaging/product-enquiry.ts', + 'src/lib/messaging/enquiry-context.ts', 'src/lib/components/ListingFacts.svelte', 'src/lib/components/PublisherIdentity.svelte', 'src/lib/contracts/food-availability-v1/contact-read.ts', @@ -1094,7 +1153,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; } await writeFile(file, JSON.stringify(manifest)); if (mutation === 'permuted-edges') - assert.equal((await f.audit()).length, 52); + assert.equal((await f.audit()).length, 55); else await assert.rejects(f.audit, /compiler|references/); } ); diff --git a/web/tests/unit/product-enquiry.test.ts b/web/tests/unit/product-enquiry.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest'; +import { + captureProductEnquiry, + productEnquirySnapshot, + productEnquiryMessage, + updateProductEnquiry, + reuseProductEnquiryConversation, + closeProductEnquiry, + type ProductEnquiry +} from '../../src/lib/messaging/product-enquiry.ts'; +import type { ProductView } from '../../src/lib/catalog/product-view.ts'; +import type { InboxView } from '../../src/lib/messaging/inbox-view.ts'; + +describe('product enquiry does not borrow detached public or private authority', () => { + it('SSR cannot capture a product enquiry from a scalar or copied view', () => { + expect( + captureProductEnquiry({} as ProductView, 'reviewed_product_enquiry') + ).toBeUndefined(); + }); + it('unreviewed capture cannot allocate a private draft', () => { + expect(captureProductEnquiry({} as ProductView, undefined)).toBeUndefined(); + }); + it('a copied enquiry cannot expose private text or a recipient', () => { + expect(productEnquirySnapshot({} as ProductEnquiry)).toBeUndefined(); + }); + it('a copied enquiry cannot build an initial private message', () => { + expect(productEnquiryMessage({} as ProductEnquiry)).toBeUndefined(); + }); + it('a fake draft cannot store text or acquire Send authority', () => { + expect( + updateProductEnquiry( + {} as ProductEnquiry, + 'Send to another key', + 'reviewed_product_enquiry_edit' + ) + ).toBe(false); + }); + it('a fake product or inbox cannot allocate an arbitrary peer conversation', async () => { + expect( + await reuseProductEnquiryConversation( + {} as ProductEnquiry, + {} as InboxView, + 'reviewed_product_enquiry_conversation' + ) + ).toBeUndefined(); + }); + it('closing an unknown draft is safe and cannot revive a message', () => { + const draft = {} as ProductEnquiry; + closeProductEnquiry(draft); + expect(productEnquiryMessage(draft)).toBeUndefined(); + }); +}); diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs @@ -401,33 +401,63 @@ async function productPresentationAdmission(web) { 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': - 'fa2e27d72b82b6bef73693cf93f19614e61ea51ebd11eb40d8ca4ec723f0c14e', - 'src/lib/catalog/publishers.ts': - 'a6795a35ebbf97246e22235df1ca868432e2cccfb26a38f0ebdf4524911192e6', - 'src/lib/catalog/resolve-head.ts': - '4f1c9f144164580da038d127ab463f9f8ba6b20e882fc31151cb29850782d633' - }; + const hasEnquiry = route.includes( + '../../../lib/components/ProductEnquiry.svelte' + ); + const producers = hasEnquiry + ? { + 'src/routes/products/[naddr=naddr]/+page.svelte': + '970f716e5f31bb0a7e463db84876d4f4b0801979e0893ef69fbeed1b17d69b0f', + 'src/lib/catalog/product-view.ts': + 'e608bcc5b7918366e2daabd5f5270cabf0ded22e1bbfd413d26450387ebac171', + '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': + 'fa2e27d72b82b6bef73693cf93f19614e61ea51ebd11eb40d8ca4ec723f0c14e', + 'src/lib/catalog/publishers.ts': + 'a6795a35ebbf97246e22235df1ca868432e2cccfb26a38f0ebdf4524911192e6', + 'src/lib/catalog/resolve-head.ts': + '4f1c9f144164580da038d127ab463f9f8ba6b20e882fc31151cb29850782d633', + 'src/lib/components/ProductEnquiry.svelte': + '4935f091aa4db3b79b681e4bfdda4547b6654a87adee897b1da25abd17c03290', + 'src/lib/messaging/product-enquiry.ts': + 'fdabb058bd42b253d24e0cb2b0a27fb24ef1c65bdc1783e298d1098185e345f4', + 'src/lib/messaging/enquiry-context.ts': + 'fc00bb77f601427fb73defc0c758332c3465c2d583bfa1f7b996f808f508b735' + } + : { + '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': + 'fa2e27d72b82b6bef73693cf93f19614e61ea51ebd11eb40d8ca4ec723f0c14e', + '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; + return hasEnquiry ? 'enquiry' : true; } // This exact reviewed producer set owns the shared presentation/runtime split. // A successor changes these identities only with new compiler qualification. @@ -654,6 +684,7 @@ export async function auditOutput(webDirectory) { hasFullRoutes && hasPublicRuntime && (await productPresentationAdmission(web)); + const hasProductEnquiry = hasProductPresentation === 'enquiry'; const hasPreferencePublication = hasPublicRuntime && (await preferencePublicationAdmission(web)); const hasInboxSetup = @@ -710,6 +741,9 @@ export async function auditOutput(webDirectory) { names.add(name); if (hasProductPresentation) names.add('publishers'); if (hasInboxSetup) names.add('private-handles'); + if (hasProductEnquiry) + for (const name of ['inbox-view', 'inbox-setup-view', 'CapabilityGate']) + names.add(name); if (hasInboxPresentation) for (const name of ['InboxStatus', 'InboxSetup', 'read', 'resolve-head']) names.add(name); @@ -926,12 +960,14 @@ export async function auditOutput(webDirectory) { const identityDependencies = [ [ 'view-context', - [ - ...(hasPreferencePublication ? [] : ['public-key']), - identityCompilerModule, - 'client', - 'Button' - ] + hasProductEnquiry + ? [identityCompilerModule] + : [ + ...(hasPreferencePublication ? [] : ['public-key']), + identityCompilerModule, + 'client', + 'Button' + ] ], [ identityCompilerModule, @@ -983,16 +1019,18 @@ export async function auditOutput(webDirectory) { const [, gate] = requiredRecord('AccountGate'); equal( gate.imports, - (hasInboxPresentation - ? ['client', 'view-context', 'InboxSetup'] - : [ - 'public-key', - 'private-handles', - 'public-runtime', - 'client', - 'Button', - 'view-context' - ] + (hasProductEnquiry + ? ['client', 'CapabilityGate', 'view-context', 'InboxSetup'] + : hasInboxPresentation + ? ['client', 'view-context', 'InboxSetup'] + : [ + 'public-key', + 'private-handles', + 'public-runtime', + 'client', + 'Button', + 'view-context' + ] ).map((name) => requiredRecord(name)[0]), 'Invalid owned inbox compiler dependencies' ); @@ -1028,56 +1066,143 @@ export async function auditOutput(webDirectory) { return row; }; /** @type {[string,string[]][]} */ - const dependencies = [ - [ - 'InboxStatus', - [ - 'public-key', - 'private-handles', - 'public-runtime', - 'references', - 'client', - 'Button', - 'navigation', - 'view-context', - 'InboxSetup', - 'read' - ] - ], - [ - 'InboxSetup', - [ - 'public-key', - 'private-handles', - 'public-runtime', - 'client', - 'Button', - 'view-context' - ] - ], - ['read', ['public-runtime']], - ['nodes/4', ['client', 'AccountGate', 'InboxStatus']], - [ - 'nodes/5', - [ - 'public-key', - 'private-handles', - 'public-runtime', - 'references', - 'client', - 'Button', - 'client.svelte', - 'navigation', - 'state', - 'view-context', - 'legacy', - 'InboxSetup', - 'InboxStatus', - 'resolve-head' + const dependencies = hasProductEnquiry + ? [ + [ + 'InboxStatus', + [ + 'public-runtime', + 'client', + 'Button', + 'navigation', + 'CapabilityGate', + 'view-context', + 'inbox-setup-view', + 'InboxSetup', + 'inbox-view' + ] + ], + [ + 'InboxSetup', + [ + 'public-runtime', + 'client', + 'Button', + 'view-context', + 'inbox-setup-view' + ] + ], + ['read', ['public-runtime']], + ['nodes/4', ['client', 'AccountGate', 'InboxStatus']], + [ + 'nodes/5', + [ + 'public-key', + 'private-handles', + 'public-runtime', + 'references', + 'client', + 'Button', + 'client.svelte', + 'navigation', + 'state', + 'view-context', + 'legacy', + 'inbox-setup-view', + 'inbox-view', + 'InboxStatus', + 'resolve-head' + ] + ], + ['resolve-head', ['public-runtime', 'Button', 'read']], + [ + 'inbox-view', + [ + 'public-key', + 'private-handles', + 'public-runtime', + 'references', + 'Button', + 'inbox-setup-view', + 'read' + ] + ], + [ + 'inbox-setup-view', + [ + 'public-key', + 'private-handles', + 'public-runtime', + 'Button', + 'view-context' + ] + ], + ['CapabilityGate', ['client', 'Button']], + [ + 'nodes/0', + [ + 'public-key', + 'public-runtime', + 'client', + 'Button', + 'client.svelte', + 'state', + 'CapabilityGate', + 'Disclosure', + 'view-context' + ] + ] ] - ], - ['resolve-head', ['public-runtime', 'Button', 'read']] - ]; + : [ + [ + 'InboxStatus', + [ + 'public-key', + 'private-handles', + 'public-runtime', + 'references', + 'client', + 'Button', + 'navigation', + 'view-context', + 'InboxSetup', + 'read' + ] + ], + [ + 'InboxSetup', + [ + 'public-key', + 'private-handles', + 'public-runtime', + 'client', + 'Button', + 'view-context' + ] + ], + ['read', ['public-runtime']], + ['nodes/4', ['client', 'AccountGate', 'InboxStatus']], + [ + 'nodes/5', + [ + 'public-key', + 'private-handles', + 'public-runtime', + 'references', + 'client', + 'Button', + 'client.svelte', + 'navigation', + 'state', + 'view-context', + 'legacy', + 'InboxSetup', + 'InboxStatus', + 'resolve-head' + ] + ], + ['resolve-head', ['public-runtime', 'Button', 'read']] + ]; for (const [name, imports] of dependencies) { const [key, row] = entry(name); equal( @@ -1091,10 +1216,21 @@ export async function auditOutput(webDirectory) { ); if (name.startsWith('nodes/')) { if ( + hasProductEnquiry && + name === 'nodes/0' && + (row.css?.length !== 1 || + !/^_app\/immutable\/assets\/0\.[A-Za-z0-9_-]+\.css$/.test( + row.css[0] + )) + ) + throw new Error( + 'Invalid owned inbox presentation compiler entry role' + ); + if ( row.src !== key || row.isEntry !== true || row.isDynamicEntry !== undefined || - row.css !== undefined + (!(hasProductEnquiry && name === 'nodes/0') && row.css !== undefined) ) throw new Error( 'Invalid owned inbox presentation compiler entry role' @@ -1154,7 +1290,8 @@ export async function auditOutput(webDirectory) { 'state', 'Disclosure', 'publishers', - ...(hasInboxPresentation ? ['resolve-head'] : []) + ...(hasInboxPresentation ? ['resolve-head'] : []), + ...(hasProductEnquiry ? ['inbox-view'] : []) ] : hasPublicRuntime === 'public_identity' ? [