app

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

commit ad243e60d819ec37f5242ecb2089a1d2dcaa255e
parent f410e0bebdca9506740708e4bf21823eaf0d6412
Author: triesap <tyson@radroots.org>
Date:   Sun, 11 Oct 2026 02:22:06 +0000

web: implement reversible local public hiding (HCP-122)

- Bind hides to the current extension account and IndexedDB completion.
- Enforce publisher visibility before public detail and profile requests.
- Preserve publication receipts and expose explicit privacy Undo.
- Verify deny policy, conflicts, aborts and account transitions in Chromium.

Diffstat:
Mweb/src/lib/catalog/product-view.ts | 26++++++++++++++++++++++++++
Mweb/src/lib/catalog/search-run.ts | 20+++++++++++++++++---
Mweb/src/lib/catalog/search-view.ts | 9++++++++-
Aweb/src/lib/components/PublisherHide.svelte | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/persistence/local-public-hides.ts | 514+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/src/lib/publishing/selling-view.ts | 14++++++++++++--
Mweb/src/lib/runtime/identity-session.ts | 22++++++++++++++++++++++
Mweb/src/lib/runtime/public-runtime.ts | 61++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mweb/src/routes/+layout.svelte | 18++++++++++++++++--
Mweb/src/routes/privacy/+page.svelte | 91++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mweb/src/routes/products/[naddr=naddr]/+page.svelte | 7+++++++
Mweb/tests/e2e/capability-gate.spec.ts | 3+++
Aweb/tests/e2e/harness/public-hides-panel.svelte | 35+++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/harness/public-hides.ts | 478+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/public-hides.spec.ts | 505+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/integration/loopback.test.ts | 12++++++++++++
Mweb/tests/provenance/output.test.mjs | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Aweb/tests/unit/public-hides.test.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/unit/route-inventory.test.ts | 10+++++++---
Mweb/tools/check-output.mjs | 572++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
20 files changed, 2653 insertions(+), 40 deletions(-)

diff --git a/web/src/lib/catalog/product-view.ts b/web/src/lib/catalog/product-view.ts @@ -10,6 +10,8 @@ import { publicViewRunCurrent, publicViewOwnsRun, publicViewKnownEvidence, + publicViewPublisherAllowed, + subscribePublicViewVisibility, subscribePublicView, type PublicView } from '../runtime/public-runtime.ts'; @@ -73,6 +75,7 @@ const acknowledgements = new WeakMap< { view: ProductView; current(this: void): boolean } >(); interface Owner { + publisherProof: () => VerifiedEnvelope | undefined; snapshot: () => ProductViewSnapshot; listing: ( acknowledgement?: ProductStatusAcknowledgement @@ -123,6 +126,7 @@ export function createProductView( function snapshot(): ProductViewSnapshot { const available = !closed && + publicViewPublisherAllowed(view, reference.pubkey) && publicViewProjectionAvailable(view) && publicViewOwnsRun(view, run); const row = available ? headResolutionSnapshot(resolver)[0] : undefined; @@ -171,6 +175,7 @@ export function createProductView( const publisher = publisherSnapshot(publishers, reference.pubkey); const stillAvailable = !closed && + publicViewPublisherAllowed(view, reference.pubkey) && publicViewProjectionAvailable(view) && publicViewOwnsRun(view, run); return { @@ -206,6 +211,7 @@ export function createProductView( else next(); } const token = Object.freeze({}) as ProductView; + const offVisibility = subscribePublicViewVisibility(view, publish); function coverageKey(observed: ProductViewSnapshot) { return JSON.stringify({ runCurrent: publicViewRunCurrent(view, run), @@ -225,6 +231,18 @@ export function createProductView( } owners.set(token, { snapshot, + publisherProof() { + const observed = snapshot(); + if ( + !head || + closed || + observed.eventId !== publicHeadSnapshot(head).id || + !publicViewOwnsRun(view, run) || + !publicViewProjectionAvailable(view) + ) + return; + return publicHeadEnvelope(head); + }, acknowledge(review) { const observed = snapshot(); if ( @@ -288,6 +306,7 @@ export function createProductView( close() { const notifyTerminal = !closed; closed = true; + offVisibility(); const previous = cancel; cancel = undefined; previous?.(); @@ -313,6 +332,8 @@ export function createProductView( } }); try { + if (!publicViewPublisherAllowed(view, reference.pubkey)) + throw Error('public_content_unavailable'); const filter = reference.identifier === '' ? { @@ -370,6 +391,11 @@ export function createProductView( export function productViewSnapshot(token: ProductView): ProductViewSnapshot { return ownerOf(token).snapshot(); } +export function productViewPublisherProof( + token: ProductView +): VerifiedEnvelope | undefined { + return owners.get(token)?.publisherProof(); +} export function closeProductView(token: ProductView): void { ownerOf(token).close(); } diff --git a/web/src/lib/catalog/search-run.ts b/web/src/lib/catalog/search-run.ts @@ -30,6 +30,7 @@ import { publicViewRunCurrent, publicViewProjectionAvailable, publicViewNip50Sources, + publicViewPublisherAllowed, subscribePublicView, disposePublicView, type PublicView @@ -321,7 +322,10 @@ export function beginFoodSearch( session.bindModel(model); requireCurrent(session); session.resolved(seed); - if (seed.length) resolveHeads(model, seed); + const admitted = seed.filter((head) => + publicViewPublisherAllowed(owner.view, publicHeadSnapshot(head).pubkey) + ); + if (admitted.length) resolveHeads(model, admitted); requireCurrent(session); return token; } catch { @@ -510,7 +514,11 @@ export function foodSearchSnapshot( if (ownedRun && model) { const active = publicViewRunCurrent(owner.view, ownedRun); if (!current(session)) return undefined; - const pending = session.pending(); + const pending = session + .pending() + .filter((head) => + publicViewPublisherAllowed(owner.view, publicHeadSnapshot(head).pubkey) + ); if (pending.length) { try { if (active) resolveHeads(model, pending); @@ -550,7 +558,13 @@ export function foodSearchSnapshot( ); const continuation = session.continuation().snapshot(), page = localSearchPage( - available && matched?.ok ? orderFoodRows(matched.rows) : [], + available && matched?.ok + ? orderFoodRows( + matched.rows.filter((row) => + publicViewPublisherAllowed(owner.view, row.state.head.pubkey) + ) + ) + : [], session.pages() ); const listings = new Map<string, ListingView>(); diff --git a/web/src/lib/catalog/search-view.ts b/web/src/lib/catalog/search-view.ts @@ -1,4 +1,7 @@ -import type { PublicView } from '../runtime/public-runtime.ts'; +import { + subscribePublicViewVisibility, + type PublicView +} from '../runtime/public-runtime.ts'; import type { PublicHead } from './heads.ts'; import type { WallClock } from './clock-policy.ts'; import type { SearchSnapshot } from './search-state.ts'; @@ -98,6 +101,9 @@ export function createSearchView( if (updated?.run?.active && updated.run.activeRequests > 0) queue(token); } const token = Object.freeze({}) as SearchView; + const offVisibility = subscribePublicViewVisibility(view, () => { + if (!closed && generation) publish(generation); + }); owners.set(token, { start(query, known) { requireOpen(); @@ -142,6 +148,7 @@ export function createSearchView( snapshot: () => foodSearchSnapshot(coordinator), close() { closed = true; + offVisibility(); stop(); closeFoodSearchCoordinator(coordinator); generation = undefined; diff --git a/web/src/lib/components/PublisherHide.svelte b/web/src/lib/components/PublisherHide.svelte @@ -0,0 +1,82 @@ +<script lang="ts"> + import { getContext, onMount } from 'svelte'; + import Button from './primitives/Button.svelte'; + import { + productViewPublisherProof, + type ProductView + } from '../catalog/product-view.ts'; + import { + LOCAL_PUBLIC_HIDES_CONTEXT, + PUBLIC_HIDE_DISCLOSURE, + localPublicHidesSnapshot, + subscribeLocalPublicHides, + hideLocalPublicPublisher, + type LocalPublicHides + } from '../persistence/local-public-hides.ts'; + let { view }: { view: ProductView } = $props(); + const hides = getContext<LocalPublicHides | undefined>( + LOCAL_PUBLIC_HIDES_CONTEXT + ); + let snapshot = $state.raw( + hides ? localPublicHidesSnapshot(hides) : { state: 'guest' as const } + ); + let busy = $state(false), + notice = $state<string | undefined>(); + let alive = false; + onMount(() => { + alive = true; + const off = hides + ? subscribeLocalPublicHides(hides, () => { + snapshot = localPublicHidesSnapshot(hides); + }) + : () => {}; + if (hides) snapshot = localPublicHidesSnapshot(hides); + return () => { + alive = false; + off(); + }; + }); + async function hide() { + const selected = view; + const proof = productViewPublisherProof(selected); + if (!hides || !proof || busy || snapshot.state !== 'ready') return; + busy = true; + const result = await hideLocalPublicPublisher( + hides, + proof, + 'reviewed_local_public_hide' + ); + if (!alive || view !== selected) return; + busy = false; + const current = localPublicHidesSnapshot(hides); + if ( + current.state !== 'ready' || + snapshot.state !== 'ready' || + current.owner !== snapshot.owner + ) { + notice = undefined; + return; + } + notice = + result.status === 'saved' || result.status === 'existing' + ? 'Publisher hidden in this browser. Undo is available in Privacy.' + : 'The hide was not confirmed. Existing local data has not been reset; review Privacy before trying again.'; + } +</script> + +<div class="stack"> + <p>{PUBLIC_HIDE_DISCLOSURE}</p> + {#if snapshot.state === 'ready'} + <Button label="Hide publisher locally" onclick={hide} disabled={busy} /> + {:else if snapshot.state === 'guest'} + <p>Connect to use account-local publisher controls.</p> + {:else if snapshot.state === 'loading'} + <p>Checking local publisher preferences…</p> + {:else} + <p class="notice"> + Local preferences could not be checked. You can browse public food; + existing local data has not been reset. + </p> + {/if} + {#if notice}<p role="status">{notice}</p>{/if} +</div> diff --git a/web/src/lib/persistence/local-public-hides.ts b/web/src/lib/persistence/local-public-hides.ts @@ -0,0 +1,514 @@ +import { canonicalPublicKey } from '../contracts/public-key.ts'; +import { exactLocalFields } from '../contracts/local-records.ts'; +import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts'; +import { + verifiedEnvelopeSnapshot, + type VerifiedEnvelope +} from '../nostr/verified-envelope.ts'; +import { + identityLocalOwnership, + subscribeIdentityInvalidation +} from '../runtime/identity-session.ts'; +import { + identityViewSession, + subscribeIdentityView, + type IdentityViewContext +} from '../runtime/view-context.ts'; +import { + openBrowserDatabase, + closeBrowserDatabase, + browserDatabaseState, + browserDatabaseTransaction, + type BrowserDatabase +} from './database.ts'; + +declare const hidesBrand: unique symbol; +export type LocalPublicHides = Readonly<{ [hidesBrand]: true }>; +export const LOCAL_PUBLIC_HIDES_CONTEXT = 'harvestcircle_local_public_hides'; +export const PUBLIC_HIDE_DISCLOSURE = + 'Hiding a publisher is local to this account in this browser. It does not delete listings, remote copies or your publication receipts, and sends no public report. Undo restores eligible listings; operator policy still applies. Browser storage is not a backup.'; +type Failure = + | 'invalid' + | 'stopped' + | 'busy' + | 'unavailable' + | 'aborted' + | 'unknown_completion' + | 'corrupt_record' + | 'conflict' + | 'capacity'; +export type PublicHidesSnapshot = + | Readonly<{ state: 'guest' | 'loading' }> + | Readonly<{ state: 'unavailable'; reason?: Failure }> + | Readonly<{ + state: 'ready'; + owner: string; + revision: number; + publishers: readonly string[]; + }>; +type Result<T> = + Readonly<{ ok: true; value: T }> | Readonly<{ ok: false; reason: Failure }>; +type Row = { + schema: 1; + family: 'public_hides'; + owner: string; + id: 'public_hides'; + revision: number; + publishers: string[]; +}; +type Stored = { row: Row; wire: string | null }; +type Scope = { owner: string; database: BrowserDatabase; current(): boolean }; +export type PublicHideResult = Readonly<{ + status: 'saved' | 'existing' | Failure; +}>; +type Controller = { + snapshot(): PublicHidesSnapshot; + mount(): Promise<void>; + refresh(): Promise<void>; + hide(proof: VerifiedEnvelope, review: unknown): Promise<PublicHideResult>; + undo(publisher: unknown, review: unknown): Promise<PublicHideResult>; + subscribe(listener: () => void): () => void; + close(): void; +}; +const controllers = new WeakMap<LocalPublicHides, Controller>(); +const failed = (reason: Failure): Result<never> => ({ ok: false, reason }); +function decode(value: unknown, owner: string): Stored | undefined { + if (value === undefined) + return { + row: { + schema: 1, + family: 'public_hides', + owner, + id: 'public_hides', + revision: 0, + publishers: [] + }, + wire: null + }; + if ( + !exactLocalFields(value, ['owner', 'id', 'wire']) || + value.owner !== owner || + value.id !== 'public_hides' || + typeof value.wire !== 'string' || + new TextEncoder().encode(value.wire).length > + LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes + ) + return; + let row: unknown; + try { + row = JSON.parse(value.wire); + } catch { + return; + } + if ( + !exactLocalFields(row, [ + 'schema', + 'family', + 'owner', + 'id', + 'revision', + 'publishers' + ]) || + row.schema !== 1 || + row.family !== 'public_hides' || + row.owner !== owner || + row.id !== 'public_hides' || + !Number.isSafeInteger(row.revision) || + typeof row.revision !== 'number' || + row.revision < 1 || + !Array.isArray(row.publishers) || + row.publishers.length > LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes || + row.publishers.some( + (key: unknown) => + typeof key !== 'string' || canonicalPublicKey(key) !== key + ) || + new Set(row.publishers).size !== row.publishers.length || + row.publishers.some( + (key: string, index: number, publishers: string[]) => + index > 0 && key <= publishers[index - 1] + ) + ) + return; + const admitted: Row = { + schema: 1, + family: 'public_hides', + owner, + id: 'public_hides', + revision: row.revision, + publishers: row.publishers.slice() as string[] + }; + return JSON.stringify(admitted) === value.wire + ? { row: admitted, wire: value.wire } + : undefined; +} +// One fixed owner/key record, with bounded publisher entries. This avoids +// scanning or adopting future private-block preferences in the same store. +function transaction<T>( + scope: Scope, + mode: 'readonly' | 'readwrite', + apply: (stored: Stored, tx: IDBTransaction) => Result<T> +): Promise<Result<T>> { + if (!scope.current()) return Promise.resolve(failed('stopped')); + let tx: IDBTransaction; + try { + tx = browserDatabaseTransaction( + scope.database, + ['local_preferences'], + mode + ); + } catch { + return Promise.resolve(failed('unavailable')); + } + return new Promise((resolve) => { + let result: Result<T> | undefined; + const refuse = (reason: Failure) => { + result = failed(reason); + try { + tx.abort(); + } catch { + result = failed('unknown_completion'); + } + }; + tx.addEventListener('complete', () => + resolve( + scope.current() + ? (result ?? failed('unknown_completion')) + : failed('stopped') + ) + ); + tx.addEventListener('abort', () => + resolve( + !scope.current() + ? failed('stopped') + : result && !result.ok && result.reason !== 'unknown_completion' + ? result + : failed('aborted') + ) + ); + try { + const request = tx + .objectStore('local_preferences') + .get([scope.owner, 'public_hides']); + request.addEventListener('success', () => { + if (!scope.current()) { + refuse('stopped'); + return; + } + try { + const row = decode(request.result, scope.owner); + if (!row) { + refuse('corrupt_record'); + return; + } + result = apply(row, tx); + if (!result.ok) refuse(result.reason); + } catch { + refuse('aborted'); + } + }); + } catch { + refuse('aborted'); + } + }); +} +// Construction has no browser effect and holds no server-global account state. +export function createLocalPublicHides( + context: IdentityViewContext +): LocalPublicHides { + const token = Object.freeze({}) as LocalPublicHides; + const listeners = new Map<symbol, () => void>(); + let state: PublicHidesSnapshot, + mounted = false, + closed = false; + state = { state: 'guest' }; + let scope: Scope | undefined, + generation = Symbol(), + cancel: AbortController | undefined; + let offIdentity = () => {}, + offInvalidation = () => {}; + function notify() { + for (const listener of listeners.values()) { + try { + listener(); + } catch { + /* Isolate presentation. */ + } + } + } + function retire() { + generation = Symbol(); + cancel?.abort(); + cancel = undefined; + offInvalidation(); + offInvalidation = () => {}; + if (scope) closeBrowserDatabase(scope.database); + scope = undefined; + state = { state: 'guest' }; + } + function snapshot(): PublicHidesSnapshot { + if (closed) return { state: 'unavailable', reason: 'stopped' }; + if (scope && !scope.current()) { + const session = identityViewSession(context); + const connected = session && identityLocalOwnership(session)?.current(); + retire(); + if (connected) state = { state: 'unavailable', reason: 'unavailable' }; + notify(); + } + return state.state === 'ready' + ? { ...state, publishers: state.publishers.slice() } + : { ...state }; + } + async function refresh() { + retire(); + notify(); + if (!mounted || closed) return; + const session = identityViewSession(context), + capture = session && identityLocalOwnership(session); + if (!session || !capture?.current()) return; + const original = generation; + const current = () => + !closed && + mounted && + original === generation && + identityViewSession(context) === session && + capture.current(); + state = { state: 'loading' }; + notify(); + cancel = new AbortController(); + offInvalidation = subscribeIdentityInvalidation(session, () => { + retire(); + notify(); + }); + const opened = await openBrowserDatabase(cancel.signal); + if (!current()) { + if (opened.state === 'ready') closeBrowserDatabase(opened.owner); + return; + } + if (opened.state !== 'ready') { + state = { state: 'unavailable', reason: 'unavailable' }; + notify(); + return; + } + const acquired: Scope = { + owner: capture.owner, + database: opened.owner, + current: () => + current() && browserDatabaseState(opened.owner).state === 'ready' + }; + scope = acquired; + const read = await transaction(acquired, 'readonly', (stored) => ({ + ok: true, + value: stored + })); + if (!acquired.current()) return; + state = read.ok + ? { + state: 'ready', + owner: acquired.owner, + revision: read.value.row.revision, + publishers: read.value.row.publishers.slice() + } + : { state: 'unavailable', reason: read.reason }; + notify(); + } + async function change( + publisher: string, + hidden: boolean, + original: Scope + ): Promise<PublicHideResult> { + if (!original.current()) return { status: 'stopped' }; + if (!navigator.locks?.request) return { status: 'unavailable' }; + try { + return await navigator.locks.request( + 'harvestcircle:owner:' + original.owner, + { mode: 'exclusive', ifAvailable: true }, + async (lock) => { + if (!lock) return { status: 'busy' as const }; + if (!original.current()) return { status: 'stopped' as const }; + const loaded = await transaction(original, 'readonly', (stored) => ({ + ok: true, + value: stored + })); + if (!original.current()) return { status: 'stopped' as const }; + if (!loaded.ok) return { status: loaded.reason }; + const before = loaded.value; + if (before.row.publishers.includes(publisher) === hidden) { + // Another controller may have acknowledged this complete native + // row. Reconcile all preferences without another write/revision. + state = { + state: 'ready', + owner: original.owner, + revision: before.row.revision, + publishers: before.row.publishers.slice() + }; + notify(); + return { status: 'existing' as const }; + } + if ( + before.row.revision >= Number.MAX_SAFE_INTEGER || + (hidden && + before.row.publishers.length >= + LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes) + ) + return { status: 'capacity' as const }; + const next: Row = { + ...before.row, + revision: before.row.revision + 1, + publishers: hidden + ? before.row.publishers.concat(publisher).sort() + : before.row.publishers.filter((key) => key !== publisher) + }; + const wire = JSON.stringify(next); + const written = await transaction<boolean>( + original, + 'readwrite', + (stored, tx) => { + if (stored.wire !== before.wire) return failed('conflict'); + tx.objectStore('local_preferences').put({ + owner: original.owner, + id: 'public_hides', + wire + }); + return { ok: true, value: true }; + } + ); + if (!original.current()) return { status: 'stopped' as const }; + if (!written.ok) return { status: written.reason }; + const readback = await transaction( + original, + 'readonly', + (stored) => ({ ok: true, value: stored }) + ); + if (!original.current()) return { status: 'stopped' as const }; + if (!readback.ok) return { status: 'unknown_completion' as const }; + if (readback.value.wire !== wire) + return { status: 'conflict' as const }; + state = { + state: 'ready', + owner: original.owner, + revision: next.revision, + publishers: next.publishers.slice() + }; + notify(); + return { status: 'saved' as const }; + } + ); + } catch { + return { status: original.current() ? 'unknown_completion' : 'stopped' }; + } + } + controllers.set(token, { + snapshot, + async mount() { + if (closed || mounted || typeof window === 'undefined') return; + mounted = true; + // Subscribe before initial load; pending/guest transitions revoke the + // previous generation before an asynchronous open can expose its rows. + let initial = true; + offIdentity = subscribeIdentityView(context, () => { + if (initial) { + initial = false; + return; + } + void refresh(); + }); + await refresh(); + }, + refresh, + async hide(proof, review) { + const event = verifiedEnvelopeSnapshot(proof); + if ( + !event || + event.kind !== 30402 || + !canonicalPublicKey(event.pubkey) || + review !== 'reviewed_local_public_hide' + ) + return { status: 'invalid' }; + const original = scope; + if (!original || state.state !== 'ready') + return { status: 'unavailable' }; + return change(event.pubkey, true, original); + }, + async undo(publisher, review) { + const key = canonicalPublicKey(publisher); + if (!key || review !== 'reviewed_local_public_undo') + return { status: 'invalid' }; + const original = scope; + if (!original || state.state !== 'ready') + return { status: 'unavailable' }; + if (!state.publishers.includes(key)) return { status: 'invalid' }; + return change(key, false, original); + }, + subscribe(listener) { + if (closed) return () => {}; + const id = Symbol(); + listeners.set(id, listener); + return () => { + listeners.delete(id); + }; + }, + close() { + if (closed) return; + closed = true; + offIdentity(); + retire(); + notify(); + listeners.clear(); + } + }); + return token; +} +export function localPublicHidesSnapshot( + token: LocalPublicHides +): PublicHidesSnapshot { + return controllers.get(token)?.snapshot() ?? { state: 'unavailable' }; +} +export function localPublicPublisherAllowed( + token: LocalPublicHides, + publisher: string +): boolean { + const owned = controllers.get(token); + if (!owned) return false; + const state = owned.snapshot(); + return state.state === 'loading' || + (state.state === 'unavailable' && state.reason === 'stopped') + ? false + : state.state !== 'ready' || !state.publishers.includes(publisher); +} +export function mountLocalPublicHides(token: LocalPublicHides): Promise<void> { + return controllers.get(token)?.mount() ?? Promise.resolve(); +} +export function refreshLocalPublicHides( + token: LocalPublicHides +): Promise<void> { + return controllers.get(token)?.refresh() ?? Promise.resolve(); +} +export function subscribeLocalPublicHides( + token: LocalPublicHides, + listener: () => void +): () => void { + return controllers.get(token)?.subscribe(listener) ?? (() => {}); +} +export function hideLocalPublicPublisher( + token: LocalPublicHides, + proof: VerifiedEnvelope, + review: unknown +): Promise<PublicHideResult> { + return ( + controllers.get(token)?.hide(proof, review) ?? + Promise.resolve({ status: 'invalid' }) + ); +} +export function undoLocalPublicPublisher( + token: LocalPublicHides, + publisher: unknown, + review: unknown +): Promise<PublicHideResult> { + return ( + controllers.get(token)?.undo(publisher, review) ?? + Promise.resolve({ status: 'invalid' }) + ); +} +export function closeLocalPublicHides(token: LocalPublicHides): void { + controllers.get(token)?.close(); +} diff --git a/web/src/lib/publishing/selling-view.ts b/web/src/lib/publishing/selling-view.ts @@ -52,6 +52,8 @@ import { publicViewOwnsRun, publicViewProjectionAvailable, publicViewRunCurrent, + publicViewPublisherAllowed, + subscribePublicViewVisibility, type PublicRuntime, type PublicView } from '../runtime/public-runtime.ts'; @@ -133,6 +135,7 @@ export async function openSellingView( let resolver: HeadResolver | undefined, discovery: PublicRequest | undefined; let timer: ReturnType<typeof setTimeout> | undefined; let offIdentity = () => {}; + let offVisibility = () => {}; let local: SellingSnapshot['local'] = 'unavailable'; let remote: SellingSnapshot['remote'] = runtime ? 'checking' : 'unavailable'; const listeners = new Map<symbol, () => void>(); @@ -159,6 +162,7 @@ export async function openSellingView( if (!alive) return; alive = false; offIdentity(); + offVisibility(); if (timer !== undefined) clearTimeout(timer); for (const view of operationViews) closeListingOperationView(view); try { @@ -204,7 +208,9 @@ export async function openSellingView( const known = remoteByIdentifier.get(group.food.identifier); const food = known?.state.food ?? group.food; const suppressed = known?.deletion.outcome === 'suppressed'; - const href = hrefFor(food.identifier); + const hidden = + publicView && !publicViewPublisherAllowed(publicView, owner ?? ''); + const href = hidden ? undefined : hrefFor(food.identifier); const canEdit = !!( href && group.supportedEventId && @@ -226,7 +232,9 @@ export async function openSellingView( ? 'Marked sold' : 'Marked available' : 'Saved public operation; current availability unconfirmed', - provenance: 'Local publication evidence · Remote discovery is bounded', + provenance: hidden + ? 'Public source hidden here · Local publication evidence retained' + : 'Local publication evidence · Remote discovery is bounded', ...(href ? { href } : {}), ...(canEdit ? { editHref: internalHref(`${href}/edit`) } : {}), ...(group.attention && @@ -243,6 +251,7 @@ export async function openSellingView( for (const row of remoteByIdentifier.values()) { if ( !row.state.food || + (publicView && !publicViewPublisherAllowed(publicView, owner ?? '')) || row.state.head.pubkey !== owner || row.state.display !== 'focused_known' || row.deletion.outcome === 'suppressed' @@ -472,6 +481,7 @@ export async function openSellingView( if (runtime) { try { publicView = createPublicView(runtime); + offVisibility = subscribePublicViewVisibility(publicView, notify); run = beginPublicViewRun(publicView); resolver = createPublicViewHeadResolver(publicView, run, { nowSeconds: () => Math.floor(Date.now() / 1000) diff --git a/web/src/lib/runtime/identity-session.ts b/web/src/lib/runtime/identity-session.ts @@ -150,6 +150,28 @@ export function identityMessagingOwnership( const adapter = sessions.get(session); return adapter && extensionMessagingOwnershipCapture(adapter); } +// Local account metadata uses the original observed extension generation. This +// grants no signing, messaging, installed account or network effect authority. +export function identityLocalOwnership(session: IdentitySession) { + const observed = identitySessionSnapshot(session); + if (!('publicKey' in observed)) return; + const adapter = sessions.get(session); + const captured = adapter && extensionOwnershipCapture(adapter); + return ( + captured && { + owner: captured.owner, + session: captured.session, + current: () => { + const state = identitySessionSnapshot(session); + return ( + captured.current() && + 'publicKey' in state && + state.publicKey === captured.owner + ); + } + } + ); +} export function subscribeIdentityInvalidation( session: IdentitySession, listener: () => void diff --git a/web/src/lib/runtime/public-runtime.ts b/web/src/lib/runtime/public-runtime.ts @@ -1,5 +1,10 @@ import { deploymentRelayPolicy } from '../config/deployment-relays.ts'; -import type { RelayPolicy } from '../config/relays.ts'; +import { readRelayPolicy, type RelayPolicy } from '../config/relays.ts'; +import { + localPublicPublisherAllowed, + subscribeLocalPublicHides, + type LocalPublicHides +} from '../persistence/local-public-hides.ts'; import { qualifiedNip50Sources } from '../nostr/search-sources.ts'; import { getPublicPool, @@ -38,7 +43,10 @@ import { type PublicHead } from '../catalog/heads.ts'; import type { KnownPublicEvidence } from '../catalog/retention.ts'; -import type { VerifiedEnvelope } from '../nostr/verified-envelope.ts'; +import { + verifiedEnvelopeSnapshot, + type VerifiedEnvelope +} from '../nostr/verified-envelope.ts'; declare const contextBrand: unique symbol; declare const runtimeBrand: unique symbol; declare const viewBrand: unique symbol; @@ -74,6 +82,7 @@ interface ViewOwner { readonly settleWith: (refresh: () => void) => void; readonly dispose: () => boolean; } +const runtimeHides = new WeakMap<RuntimeOwner, LocalPublicHides>(); const contexts = new WeakMap<PublicRuntimeContext, ContextOwner>(), runtimes = new WeakMap<PublicRuntime, RuntimeOwner>(), views = new WeakMap<PublicView, ViewOwner>(); @@ -323,6 +332,38 @@ export function createPublicView(runtime: PublicRuntime): PublicView { shared.views.set(token, () => owner.dispose()); return token; } +// Root-lifetime original local preference custody, never detached UI keys. +export function bindPublicRuntimeHides( + runtime: PublicRuntime, + hides: LocalPublicHides +): void { + const owner = runtimeOf(runtime); + if (runtimeHides.has(owner) && runtimeHides.get(owner) !== hides) + throw Error('public_visibility_already_bound'); + runtimeHides.set(owner, hides); +} +function publisherAllowed(owner: RuntimeOwner, publisher: string): boolean { + return ( + !owner.closed() && + !readRelayPolicy(owner.policy).operatorDenylist.includes(publisher) && + (!runtimeHides.has(owner) || + localPublicPublisherAllowed(runtimeHides.get(owner)!, publisher)) + ); +} +export function publicViewPublisherAllowed( + view: PublicView, + publisher: string +): boolean { + const owner = viewOf(view); + return publisherAllowed(owner.runtime, publisher); +} +export function subscribePublicViewVisibility( + view: PublicView, + listener: () => void +): () => void { + const hides = runtimeHides.get(viewOf(view).runtime); + return hides ? subscribeLocalPublicHides(hides, listener) : () => {}; +} export function beginPublicViewRun(view: PublicView): PublicRun { return viewOf(view).begin(); } @@ -352,7 +393,18 @@ export function subscribePublicView( if (!owner.current(run)) throw new Error('public_view_run_inactive'); // Copy the request template once before SDK effects; caller mutations cannot // retarget this request. Product filter builders remain HCP038 and later. - const frozen = JSON.stringify(filters); + const copied = JSON.parse(JSON.stringify(filters)) as PublicFilter[]; + const admitted = copied.flatMap((filter) => { + if (!filter.authors) return [filter]; + const authors = filter.authors.filter((author) => + publisherAllowed(owner.runtime, author) + ); + return authors.length ? [{ ...filter, authors }] : []; + }); + // Refuse known denied author-specific actions before SDK request creation. + // Broad discovery still charges verified ingress before publisher admission. + if (!admitted.length) throw Error('public_content_unavailable'); + const frozen = JSON.stringify(admitted); return openPublicRequest( run, kind, @@ -365,6 +417,9 @@ export function subscribePublicView( ), (event) => { if (!owner.current(run)) return; + const received = verifiedEnvelopeSnapshot(event); + if (!received || !publisherAllowed(owner.runtime, received.pubkey)) + return; const result = insertPublicEnvelope(owner.runtime.store, event); if (result === 'limit' || result === 'rejected' || result === 'closed') { owner.runtime.invalidateProjection(); diff --git a/web/src/routes/+layout.svelte b/web/src/routes/+layout.svelte @@ -6,6 +6,7 @@ createPublicRuntimeContext, mountPublicRuntime, closePublicRuntime, + bindPublicRuntimeHides, PUBLIC_RUNTIME_CONTEXT } from '../lib/runtime/public-runtime.ts'; import { page } from '$app/state'; @@ -21,7 +22,15 @@ closeIdentityView, invalidateIdentityView } from '../lib/runtime/view-context.ts'; + import { + createLocalPublicHides, + mountLocalPublicHides, + closeLocalPublicHides, + LOCAL_PUBLIC_HIDES_CONTEXT + } from '../lib/persistence/local-public-hides.ts'; const identityContext = createIdentityViewContext(); + const publicHides = createLocalPublicHides(identityContext); + setContext(LOCAL_PUBLIC_HIDES_CONTEXT, publicHides); setContext(IDENTITY_VIEW_CONTEXT, identityContext); let identityView = $state(identityViewSnapshot(identityContext)); $effect(() => { @@ -50,8 +59,13 @@ const publicContext = createPublicRuntimeContext(); setContext(PUBLIC_RUNTIME_CONTEXT, publicContext); onMount(() => { - mountPublicRuntime(publicContext); - return () => closePublicRuntime(publicContext); + const runtime = mountPublicRuntime(publicContext); + if (runtime) bindPublicRuntimeHides(runtime, publicHides); + void mountLocalPublicHides(publicHides); + return () => { + closeLocalPublicHides(publicHides); + closePublicRuntime(publicContext); + }; }); onMount(() => { const off = subscribeIdentityView(identityContext, (next) => { diff --git a/web/src/routes/privacy/+page.svelte b/web/src/routes/privacy/+page.svelte @@ -1,5 +1,94 @@ +<script lang="ts"> + import { getContext, onMount } from 'svelte'; + import Button from '../../lib/components/primitives/Button.svelte'; + import { + LOCAL_PUBLIC_HIDES_CONTEXT, + PUBLIC_HIDE_DISCLOSURE, + localPublicHidesSnapshot, + subscribeLocalPublicHides, + undoLocalPublicPublisher, + type LocalPublicHides + } from '../../lib/persistence/local-public-hides.ts'; + const hides = getContext<LocalPublicHides | undefined>( + LOCAL_PUBLIC_HIDES_CONTEXT + ); + let snapshot = $state.raw( + hides ? localPublicHidesSnapshot(hides) : { state: 'guest' as const } + ); + let notice = $state<string | undefined>(), + busy = $state(false); + let alive = false; + onMount(() => { + alive = true; + const off = hides + ? subscribeLocalPublicHides(hides, () => { + snapshot = localPublicHidesSnapshot(hides); + notice = undefined; + }) + : () => {}; + if (hides) snapshot = localPublicHidesSnapshot(hides); + return () => { + alive = false; + off(); + }; + }); + async function undo(publisher: string) { + if (!hides || busy || snapshot.state !== 'ready') return; + const owner = snapshot.owner; + busy = true; + const result = await undoLocalPublicPublisher( + hides, + publisher, + 'reviewed_local_public_undo' + ); + if (!alive) return; + busy = false; + const current = localPublicHidesSnapshot(hides); + if (current.state !== 'ready' || current.owner !== owner) return; + notice = + result.status === 'saved' || result.status === 'existing' + ? 'Hide undone. Eligible public listings can be shown again; operator policy still applies.' + : 'Undo was not confirmed. Existing local data has not been reset.'; + } +</script> + <svelte:head><title>Privacy — HarvestCircle</title></svelte:head> <div class="page page--reading stack"> <h1>Privacy</h1> - <p class="notice">Privacy information is unavailable during development.</p> + <p> + Listings are public. Relay queries can reveal your search or publisher + interest; search URLs may remain in browser history and hosting logs. This + prototype uses no tracking analytics. + </p> + <p>{PUBLIC_HIDE_DISCLOSURE}</p> + <h2>Local publisher controls</h2> + {#if snapshot.state === 'ready'} + {#if snapshot.publishers.length} + <ul class="stack"> + {#each snapshot.publishers as publisher (publisher)} + <li class="stack"> + <p class="key">{publisher}</p> + <Button + label="Undo hide" + onclick={() => undo(publisher)} + disabled={busy} + /> + </li> + {/each} + </ul> + {:else}<p>No publishers hidden for this account in this browser.</p>{/if} + {:else if snapshot.state === 'guest'} + <p> + Connect to review your account-local publisher preferences. Guest browsing + does not expose an account inventory. + </p> + {:else if snapshot.state === 'loading'} + <p>Checking local publisher preferences…</p> + {:else} + <p class="notice"> + Local preferences could not be checked. You can still browse public food. + Existing local data has not been reset; previous hides are unconfirmed. + </p> + {/if} + {#if notice}<p role="status">{notice}</p>{/if} </div> diff --git a/web/src/routes/products/[naddr=naddr]/+page.svelte b/web/src/routes/products/[naddr=naddr]/+page.svelte @@ -25,6 +25,7 @@ import Disclosure from '../../../lib/components/primitives/Disclosure.svelte'; import Button from '../../../lib/components/primitives/Button.svelte'; import ProductEnquiry from '../../../lib/components/ProductEnquiry.svelte'; + import PublisherHide from '../../../lib/components/PublisherHide.svelte'; const context = getContext<PublicRuntimeContext>(PUBLIC_RUNTIME_CONTEXT); let runtime = $state.raw<PublicRuntime | undefined>(), result = $state.raw<ProductViewSnapshot | undefined>(), @@ -149,6 +150,11 @@ view={productOwner} observation={result} />{/if} + {#if productOwner && result.eventId} + <Disclosure summary="Publisher controls" + ><PublisherHide view={productOwner} /></Disclosure + > + {/if} <Disclosure summary="Listing and source details"> {#if result.eventId}<p> Listing version: <code>{result.eventId}</code> @@ -172,4 +178,5 @@ href={internalHref(`/products/${reference.naddr}`)}>Public food link</a >{/if} {#if copyNotice}<p role="status">{copyNotice}</p>{/if} + <a href={internalHref('/privacy')}>Privacy and local publisher controls</a> </div> diff --git a/web/tests/e2e/capability-gate.spec.ts b/web/tests/e2e/capability-gate.spec.ts @@ -304,6 +304,9 @@ test.describe('actual shared inline capability component', () => { for (const name of [ 'src/lib/components/CapabilityGate.svelte', 'src/lib/runtime/view-context.ts', + 'src/lib/runtime/identity-session.ts', + 'src/lib/runtime/public-runtime.ts', + 'src/lib/persistence/local-public-hides.ts', 'src/lib/components/AppShell.svelte', 'src/lib/components/AccountGate.svelte', 'src/lib/components/InboxSetup.svelte', diff --git a/web/tests/e2e/harness/public-hides-panel.svelte b/web/tests/e2e/harness/public-hides-panel.svelte @@ -0,0 +1,35 @@ +<script lang="ts"> + import { onMount } from 'svelte'; + import PublisherHide from '../../../src/lib/components/PublisherHide.svelte'; + import ListingRow from '../../../src/lib/components/ListingRow.svelte'; + import Privacy from '../../../src/routes/privacy/+page.svelte'; + import type { createFixture } from './public-hides.ts'; + let { fixture }: { fixture: Awaited<ReturnType<typeof createFixture>> } = + $props(); + let view = $state.raw<ReturnType<typeof fixture.view>>(), + observation = $state.raw<ReturnType<typeof fixture.publicSnapshot>>(), + results = $state.raw<ReturnType<typeof fixture.searchSnapshot>>(); + onMount(() => { + view = fixture.view(); + observation = fixture.publicSnapshot(); + results = fixture.searchSnapshot(); + return fixture.subscribe(() => { + view = fixture.view(); + observation = fixture.publicSnapshot(); + results = fixture.searchSnapshot(); + }); + }); +</script> + +<section class="page page--reading stack"> + {#if observation?.food}<h2>{observation.food.title}</h2>{/if} + {#if view}<PublisherHide {view} />{/if} + <div data-public-search> + <ul> + {#each results?.listings ?? [] as listing (listing.href)}<li> + <ListingRow {listing} /> + </li>{/each} + </ul> + </div> + <Privacy /> +</section> diff --git a/web/tests/e2e/harness/public-hides.ts b/web/tests/e2e/harness/public-hides.ts @@ -0,0 +1,478 @@ +// HC_TEST_ONLY_RELAY: actual owner/IndexedDB/public SDK over loopback, no live Q. +import { mount, unmount } from 'svelte'; +import Panel from './public-hides-panel.svelte'; +import { makeFixture } from './approved-signing.ts'; +import { createFixture as publicationFixture } from './listing-operation-view.ts'; +import { + openSellingView, + sellingViewSnapshot, + closeSellingView +} from '../../../src/lib/publishing/selling-view.ts'; +import { fixturePolicy } from './inbox-setup.ts'; +import { + validateRelayPolicy, + readRelayPolicy +} from '../../../src/lib/config/relays.ts'; +import { + createIdentityViewContext, + mountIdentityView, + connectIdentityView, + closeIdentityView +} from '../../../src/lib/runtime/view-context.ts'; +import { + createPublicRuntimeContext, + mountPublicRuntime, + bindPublicRuntimeHides, + createPublicView, + closePublicRuntime +} from '../../../src/lib/runtime/public-runtime.ts'; +import { + createLocalPublicHides, + mountLocalPublicHides, + refreshLocalPublicHides, + localPublicHidesSnapshot, + hideLocalPublicPublisher, + undoLocalPublicPublisher, + closeLocalPublicHides, + LOCAL_PUBLIC_HIDES_CONTEXT +} from '../../../src/lib/persistence/local-public-hides.ts'; +import { + createProductView, + productViewSnapshot, + productViewPublisherProof, + closeProductView, + type ProductView +} from '../../../src/lib/catalog/product-view.ts'; +import { + createSearchView, + startSearchView, + searchViewSnapshot, + closeSearchView, + type SearchView +} from '../../../src/lib/catalog/search-view.ts'; +import { buildFoodTemplate } from '../../../src/lib/contracts/food-availability-v1/write.ts'; +import { encodeProductReference } from '../../../src/lib/nostr/references.ts'; +import { + verifyEnvelope, + type VerifiedEnvelope +} from '../../../src/lib/nostr/verified-envelope.ts'; +import { + openBrowserDatabase, + closeBrowserDatabase, + browserDatabaseTransaction +} from '../../../src/lib/persistence/database.ts'; + +export async function createFixture(denied = false, retained = false) { + const signer = makeFixture(), + second = makeFixture(); + const prior = Object.getOwnPropertyDescriptor(window, 'nostr'); + const original = retained ? await publicationFixture() : undefined; + if (original && (await original.signed()) !== 'prepared') + throw Error('original native signed operation missing'); + const retainedRow = await original?.row(); + const owner = original?.owner ?? signer.owner; + Object.defineProperty(window, 'nostr', { + configurable: true, + value: { getPublicKey: () => Promise.resolve(owner) } + }); + const context = createIdentityViewContext(); + mountIdentityView(context); + await connectIdentityView(context); + const hides = createLocalPublicHides(context); + await mountLocalPublicHides(hides); + const publicContext = createPublicRuntimeContext(); + const manifest = readRelayPolicy(fixturePolicy()); + const policy = validateRelayPolicy( + JSON.stringify({ + ...manifest, + operatorDenylist: denied ? [signer.owner] : [] + }) + ); + if (!policy) throw Error('fixture policy missing'); + const runtime = mountPublicRuntime(publicContext, policy); + if (!runtime) throw Error('original public runtime missing'); + bindPublicRuntimeHides(runtime, hides); + const now = Math.floor(Date.now() / 1000); + const built = buildFoodTemplate({ + identifier: 'visible-carrots', + title: 'Visible carrots', + description: 'Public plain text only', + location: 'Farm', + amount: '3', + currency: 'CAD', + unit: 'each', + created_at: now, + published_at: now, + status: 'active' + }); + if (!built.ok) throw Error('fixture food invalid'); + const event = retainedRow?.artifact + ? (JSON.parse(retainedRow.artifact.wire) as ReturnType<typeof signer.sign>) + : signer.sign({ + kind: 30402, + created_at: now, + tags: built.wire_parts.tags.map((tag) => [...tag]), + content: built.wire_parts.content + }); + const reference = encodeProductReference({ + kind: 30402, + pubkey: event.pubkey, + identifier: event.tags.find((tag) => tag[0] === 'd')?.[1] ?? '' + }); + if (!reference) throw Error('fixture reference missing'); + const proof = verifyEnvelope(JSON.stringify(event)); + if (!proof.ok) throw Error('actual verified publisher missing'); + const opened = await openBrowserDatabase(); + if (opened.state !== 'ready') throw Error(opened.reason); + const database = opened.owner; + const listeners = new Map<symbol, () => void>(); + let product: ProductView | undefined, search: SearchView | undefined; + let panel: ReturnType<typeof mount> | undefined, + target: HTMLElement | undefined; + const notify = () => { + for (const listener of listeners.values()) listener(); + }; + const fixture = { + events: [event], + view: () => product, + publicSnapshot: () => product && productViewSnapshot(product), + searchSnapshot: () => search && searchViewSnapshot(search), + hidesSnapshot: () => localPublicHidesSnapshot(hides), + subscribe(listener: () => void) { + const id = Symbol(); + listeners.set(id, listener); + return () => { + listeners.delete(id); + }; + }, + read() { + if (product) closeProductView(product); + product = createProductView( + createPublicView(runtime), + reference, + { nowSeconds: () => Math.floor(Date.now() / 1000) }, + notify + ); + notify(); + }, + search() { + if (search) closeSearchView(search); + search = createSearchView( + createPublicView(runtime), + { nowSeconds: () => Math.floor(Date.now() / 1000) }, + notify + ); + startSearchView(search, 'carrots'); + }, + async render() { + if (!product) fixture.read(); + if (panel) await unmount(panel); + target?.remove(); + target = document.createElement('div'); + target.id = 'hcp122-panel'; + document.body.append(target); + panel = mount(Panel, { + target, + props: { fixture }, + context: new Map([[LOCAL_PUBLIC_HIDES_CONTEXT, hides]]) + }); + }, + hide() { + return hideLocalPublicPublisher( + hides, + product + ? (productViewPublisherProof(product) ?? proof.value) + : proof.value, + 'reviewed_local_public_hide' + ); + }, + fake() { + return hideLocalPublicPublisher( + hides, + { pubkey: event.pubkey } as unknown as VerifiedEnvelope, + 'reviewed_local_public_hide' + ); + }, + refresh() { + return refreshLocalPublicHides(hides); + }, + async concurrentPreference(hidden: boolean) { + const other = createLocalPublicHides(context); + await mountLocalPublicHides(other); + try { + const otherEvent = second.sign({ + kind: event.kind, + created_at: event.created_at, + tags: event.tags.map((tag) => [...tag]), + content: event.content + }); + const otherProof = verifyEnvelope(JSON.stringify(otherEvent)); + if (!otherProof.ok) throw Error('other genuine publisher missing'); + const unrelated = await hideLocalPublicPublisher( + other, + otherProof.value, + 'reviewed_local_public_hide' + ); + if (unrelated.status !== 'saved') throw Error('other hide missing'); + const changed = hidden + ? await hideLocalPublicPublisher( + other, + proof.value, + 'reviewed_local_public_hide' + ) + : await undoLocalPublicPublisher( + other, + event.pubkey, + 'reviewed_local_public_undo' + ); + if (changed.status !== 'saved') + throw Error('concurrent preference missing'); + return { + snapshot: localPublicHidesSnapshot(other), + rows: await fixture.rows() + }; + } finally { + closeLocalPublicHides(other); + } + }, + undo() { + return undoLocalPublicPublisher( + hides, + event.pubkey, + 'reviewed_local_public_undo' + ); + }, + async rows() { + const tx = browserDatabaseTransaction( + database, + ['local_preferences'], + 'readonly' + ); + return new Promise<unknown[]>((resolve, reject) => { + const request = tx + .objectStore('local_preferences') + .index('by_owner') + .getAll(owner); + tx.addEventListener('complete', () => + resolve(request.result as unknown[]) + ); + tx.addEventListener('abort', () => + reject(Error('native read aborted')) + ); + }); + }, + async corrupt() { + const tx = browserDatabaseTransaction( + database, + ['local_preferences'], + 'readwrite' + ); + tx.objectStore('local_preferences').put({ + owner: signer.owner, + id: 'public_hides', + wire: 'corrupt local metadata' + }); + await new Promise<void>((resolve, reject) => { + tx.addEventListener('complete', () => resolve()); + tx.addEventListener('abort', () => + reject(Error('native write aborted')) + ); + }); + }, + nativeRecord() { + return original?.row(); + }, + async sellingSnapshot() { + const view = await openSellingView(context, runtime); + if (!view) throw Error('original owner selling view missing'); + try { + const snapshot = sellingViewSnapshot(view); + return ( + snapshot && { + ...snapshot, + attention: snapshot.attention.map((row) => ({ + ...row, + operations: row.operations.map(() => 'original_operation_view') + })) + } + ); + } finally { + closeSellingView(view); + } + }, + async abortWrite() { + const native = Reflect.get<IDBDatabase, 'transaction'>( + IDBDatabase.prototype, + 'transaction' + ); + let injected = false; + IDBDatabase.prototype.transaction = function ( + ...args: Parameters<typeof native> + ) { + const tx = native.apply(this, args); + if ( + !injected && + this.name === 'harvestcircle_browser' && + args[1] === 'readwrite' + ) { + injected = true; + tx.abort(); + } + return tx; + }; + try { + return await fixture.hide(); + } finally { + IDBDatabase.prototype.transaction = native; + } + }, + async conflictWrite() { + const native = Reflect.get<IDBDatabase, 'transaction'>( + IDBDatabase.prototype, + 'transaction' + ); + let injected = false; + IDBDatabase.prototype.transaction = function ( + ...args: Parameters<typeof native> + ) { + if ( + !injected && + this.name === 'harvestcircle_browser' && + args[1] === 'readwrite' + ) { + injected = true; + const concurrent = native.call( + this, + ['local_preferences'], + 'readwrite' + ); + concurrent.objectStore('local_preferences').put({ + owner: signer.owner, + id: 'public_hides', + wire: JSON.stringify({ + schema: 1, + family: 'public_hides', + owner: signer.owner, + id: 'public_hides', + revision: 1, + publishers: [second.owner] + }) + }); + } + return native.apply(this, args); + }; + try { + return await fixture.hide(); + } finally { + IDBDatabase.prototype.transaction = native; + } + }, + async failReadback() { + const native = Reflect.get<IDBDatabase, 'transaction'>( + IDBDatabase.prototype, + 'transaction' + ); + let reads = 0; + IDBDatabase.prototype.transaction = function ( + ...args: Parameters<typeof native> + ) { + if ( + this.name === 'harvestcircle_browser' && + args[1] === 'readonly' && + ++reads === 2 + ) + throw new DOMException( + 'controlled readback failure', + 'SecurityError' + ); + return native.apply(this, args); + }; + try { + return await fixture.hide(); + } finally { + IDBDatabase.prototype.transaction = native; + } + }, + async denyStorage() { + const native = Reflect.get<IDBFactory, 'open'>( + IDBFactory.prototype, + 'open' + ); + IDBFactory.prototype.open = () => { + throw new DOMException('controlled denied open', 'SecurityError'); + }; + try { + await refreshLocalPublicHides(hides); + return localPublicHidesSnapshot(hides); + } finally { + IDBFactory.prototype.open = native; + } + }, + async switchOwner() { + Object.defineProperty(window, 'nostr', { + configurable: true, + value: { getPublicKey: () => Promise.resolve(second.owner) } + }); + await connectIdentityView(context); + }, + async reconnect() { + // Delay only the lock callback to exercise a real account-generation + // transition during an admitted local action, before any IDB mutation. + const native = navigator.locks.request.bind(navigator.locks); + const descriptor = Object.getOwnPropertyDescriptor( + navigator.locks, + 'request' + ); + let release: (() => void) | undefined; + const gate = new Promise<void>((resolve) => { + release = resolve; + }); + const wrapper = ( + name: string, + options: LockOptions, + callback: LockGrantedCallback<unknown> + ) => + native(name, options, async (lock) => { + await gate; + return callback(lock); + }); + Object.defineProperty(navigator.locks, 'request', { + configurable: true, + value: wrapper + }); + try { + const pending = undoLocalPublicPublisher( + hides, + event.pubkey, + 'reviewed_local_public_undo' + ); + await connectIdentityView(context); + release?.(); + const result = await pending; + await refreshLocalPublicHides(hides); + return result; + } finally { + release?.(); + if (descriptor) + Object.defineProperty(navigator.locks, 'request', descriptor); + else Reflect.deleteProperty(navigator.locks, 'request'); + } + }, + async close() { + if (panel) await unmount(panel); + target?.remove(); + if (product) closeProductView(product); + if (search) closeSearchView(search); + closeLocalPublicHides(hides); + closeIdentityView(context); + closePublicRuntime(publicContext); + closeBrowserDatabase(database); + signer.close(); + second.close(); + original?.close(); + if (prior) Object.defineProperty(window, 'nostr', prior); + else Reflect.deleteProperty(window, 'nostr'); + } + }; + return fixture; +} diff --git a/web/tests/e2e/public-hides.spec.ts b/web/tests/e2e/public-hides.spec.ts @@ -0,0 +1,505 @@ +import { expect, test, 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 type { NostrEvent } from 'applesauce-core/helpers'; +import { createStaticHarness } from '../integration/harness/static.ts'; +import type * as Fixture from './harness/public-hides.ts'; +declare global { + interface Window { + hcp122: typeof Fixture; + hcp122Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>; + } +} +let server: Awaited<ReturnType<typeof createStaticHarness>>, + sockets: WebSocketServer, + endpoint: string, + bundle: string | undefined; +let events: NostrEvent[] = [], + effects = 0; +let queries: { authors?: string[]; kinds?: number[] }[] = []; +test.beforeAll(async () => { + server = await createStaticHarness(); + sockets = new WebSocketServer({ + host: '127.0.0.1', + port: 0, + maxPayload: 262144 + }); + await once(sockets, 'listening'); + const address = sockets.address(); + if (!address || typeof address === 'string') throw Error('loopback missing'); + 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' || frame[0] === 'AUTH') { + effects++; + return; + } + if (frame[0] !== 'REQ') return; + const filters = frame.slice(2) as { + authors?: string[]; + kinds?: number[]; + '#d'?: string[]; + }[]; + queries.push(...filters); + for (const event of events) + if ( + filters.some( + (filter) => + (!filter.kinds || filter.kinds.includes(event.kind)) && + (!filter.authors || filter.authors.includes(event.pubkey)) && + (!filter['#d'] || + event.tags.some( + (tag) => tag[0] === 'd' && filter['#d']!.includes(tag[1]) + )) + ) + ) + socket.send(JSON.stringify(['EVENT', frame[1], event])); + socket.send(JSON.stringify(['EOSE', frame[1]])); + }) + ); +}); +test.afterAll(async () => { + for (const socket of sockets?.clients ?? []) socket.terminate(); + if (sockets) + await new Promise<void>((resolve, reject) => + sockets.close((error) => (error ? reject(error) : resolve())) + ); + await server?.close(); +}); +test.beforeEach(async ({ page }) => { + events = []; + effects = 0; + queries = []; + 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://inbox.example.org'].includes( + new URL(url.toString()).origin + ) + ) + throw Error('no live relay permission'); + super(endpoint, protocols); + } + }; + }, endpoint); +}); +test.afterEach(async ({ page }) => { + await page.evaluate(async () => { + await window.hcp122Fixture?.close(); + }); +}); +async function start(page: Page, denied = false, retained = false) { + await page.goto(server.url + '/privacy'); + if (!bundle) { + const built = await build({ + configFile: false, + plugins: [svelte({ configFile: false })], + resolve: { conditions: ['browser'] }, + logLevel: 'silent', + build: { + write: false, + minify: false, + lib: { + entry: fileURLToPath( + new URL('./harness/public-hides.ts', import.meta.url) + ), + name: 'hcp122', + formats: ['iife'] + } + } + }); + const result = Array.isArray(built) ? built[0] : built; + if (!('output' in result)) throw Error('fixture bundle missing'); + const chunks = result.output.filter((row) => row.type === 'chunk'); + expect(chunks).toHaveLength(1); + bundle = chunks[0].code; + } + await page.addScriptTag({ content: bundle }); + events = await page.evaluate( + async ({ denied, retained }) => { + window.hcp122Fixture = await window.hcp122.createFixture( + denied, + retained + ); + return window.hcp122Fixture.events; + }, + { denied, retained } + ); + await page.evaluate(() => window.hcp122Fixture.render()); +} +test('HCP122 SSR privacy states local hide consequences without private inventory', async ({ + page +}) => { + await page.goto(server.url + '/privacy'); + // Immediate body assertion is a real pre-producer failure, not a future-module collection failure. + expect(await page.locator('main').innerText()).toContain( + 'Hiding a publisher is local' + ); + await expect(page.getByRole('button', { name: /Undo hide/ })).toHaveCount(0); + expect(queries).toEqual([]); + expect(effects).toBe(0); +}); +test('HCP122 acknowledged hide persists native owner data and Undo restores eligible source', async ({ + page +}) => { + await start(page); + await expect(page.locator('#hcp122-panel')).toContainText('Visible carrots'); + await page + .locator('#hcp122-panel') + .getByRole('button', { name: 'Hide publisher locally', exact: true }) + .click(); + await expect(page.locator('#hcp122-panel')).toContainText( + 'Publisher hidden in this browser' + ); + expect(await page.evaluate(() => window.hcp122Fixture.rows())).toHaveLength( + 1 + ); + await page.evaluate(() => window.hcp122Fixture.refresh()); + expect( + await page.evaluate(() => window.hcp122Fixture.publicSnapshot()) + ).toMatchObject({ outcome: 'unavailable', food: undefined }); + const before = queries.length; + await page.evaluate(() => window.hcp122Fixture.read()); + expect(queries).toHaveLength(before); + await page + .locator('#hcp122-panel') + .getByRole('button', { name: /Undo hide/ }) + .click(); + await expect(page.locator('#hcp122-panel')).toContainText('Hide undone'); + await page.evaluate(() => window.hcp122Fixture.read()); + await expect + .poll(() => + page.evaluate(() => window.hcp122Fixture.publicSnapshot()?.food?.title) + ) + .toBe('Visible carrots'); + expect(effects).toBe(0); +}); +test('HCP122 operator-denied canonical detail emits no head deletion or profile query', async ({ + page +}) => { + await start(page, true); + await page.evaluate(() => window.hcp122Fixture.read()); + expect( + await page.evaluate(() => window.hcp122Fixture.publicSnapshot()) + ).toMatchObject({ outcome: 'unavailable', food: undefined }); + expect(queries).toEqual([]); + expect(effects).toBe(0); +}); +test('HCP122 broad search excludes verified denied publisher before auxiliary profile lookup', async ({ + page +}) => { + await start(page, true); + await page.evaluate(() => window.hcp122Fixture.search()); + await expect + .poll(() => + page.evaluate(() => window.hcp122Fixture.searchSnapshot()?.refresh) + ) + .toBe('bounded-eose'); + expect( + await page.evaluate(() => window.hcp122Fixture.searchSnapshot()?.listings) + ).toEqual([]); + expect( + queries.some((query) => query.authors?.includes(events[0].pubkey)) + ).toBe(false); + expect(effects).toBe(0); +}); +test('HCP122 local hide updates an already settled search and Undo restores its eligible row', async ({ + page +}) => { + await start(page); + await page.evaluate(() => window.hcp122Fixture.search()); + const results = page.locator('#hcp122-panel [data-public-search]'); + await expect(results).toContainText('Visible carrots'); + await page + .locator('#hcp122-panel') + .getByRole('button', { name: 'Hide publisher locally', exact: true }) + .click(); + await expect(results).not.toContainText('Visible carrots'); + const before = queries.length; + await page + .locator('#hcp122-panel') + .getByRole('button', { name: /Undo hide/ }) + .click(); + await expect(results).toContainText('Visible carrots'); + expect(queries).toHaveLength(before); + expect(effects).toBe(0); +}); +test('HCP122 Undo of a retained local hide cannot override operator denial or fetch that publisher', async ({ + page +}) => { + await start(page, true); + expect(await page.evaluate(() => window.hcp122Fixture.hide())).toEqual({ + status: 'saved' + }); + await page + .locator('#hcp122-panel') + .getByRole('button', { name: /Undo hide/ }) + .click(); + await page.evaluate(() => window.hcp122Fixture.read()); + expect( + await page.evaluate(() => window.hcp122Fixture.publicSnapshot()) + ).toMatchObject({ outcome: 'unavailable', food: undefined }); + expect(queries).toEqual([]); + expect(effects).toBe(0); +}); +test('HCP122 detached render publisher cannot authorize local hide or automatic public report', async ({ + page +}) => { + await start(page); + expect(await page.evaluate(() => window.hcp122Fixture.fake())).toEqual({ + status: 'invalid' + }); + expect(await page.evaluate(() => window.hcp122Fixture.rows())).toEqual([]); + expect(effects).toBe(0); +}); +test('HCP122 actual account switch retires the old owner inventory without removing stored facts', async ({ + page +}) => { + await start(page); + await page.evaluate(() => window.hcp122Fixture.hide()); + const before = await page.evaluate(() => window.hcp122Fixture.rows()); + await page.evaluate(() => window.hcp122Fixture.switchOwner()); + expect( + await page.evaluate(() => window.hcp122Fixture.hidesSnapshot()) + ).toEqual({ state: 'guest' }); + expect(await page.evaluate(() => window.hcp122Fixture.rows())).toEqual( + before + ); + await expect( + page.locator('#hcp122-panel').getByRole('button', { name: /Undo hide/ }) + ).toHaveCount(0); + expect(effects).toBe(0); +}); +test('HCP122 hiding an own public source preserves original signed operation and delivery receipts', async ({ + page +}) => { + await start(page, false, true); + const before = await page.evaluate(() => window.hcp122Fixture.nativeRecord()); + expect(before).toBeDefined(); + expect((before as { artifact?: unknown }).artifact).toBeDefined(); + await page.evaluate(() => window.hcp122Fixture.hide()); + expect( + await page.evaluate(() => window.hcp122Fixture.nativeRecord()) + ).toEqual(before); + const own = await page.evaluate(() => window.hcp122Fixture.sellingSnapshot()); + expect(own?.attention).toHaveLength(1); + expect(own?.attention[0].provenance).toContain( + 'Local publication evidence retained' + ); + expect(own?.attention[0].href).toBeUndefined(); + expect(effects).toBe(0); +}); +test('HCP122 corrupt local preference is retained and never replaced with an empty inventory', async ({ + page +}) => { + await start(page); + await page.evaluate(() => window.hcp122Fixture.corrupt()); + await page.evaluate(() => window.hcp122Fixture.refresh()); + expect( + await page.evaluate(() => window.hcp122Fixture.hidesSnapshot()) + ).toEqual({ state: 'unavailable', reason: 'corrupt_record' }); + expect(await page.evaluate(() => window.hcp122Fixture.rows())).toHaveLength( + 1 + ); + expect(effects).toBe(0); +}); +test('HCP122 actual native transaction abort gives no Saved or empty-data replacement', async ({ + page +}) => { + await start(page); + expect(await page.evaluate(() => window.hcp122Fixture.abortWrite())).toEqual({ + status: 'aborted' + }); + expect(await page.evaluate(() => window.hcp122Fixture.rows())).toEqual([]); + expect( + await page.evaluate(() => window.hcp122Fixture.hidesSnapshot()) + ).toMatchObject({ state: 'ready', publishers: [] }); + expect(effects).toBe(0); +}); +test('HCP122 failed readback after actual write completion stays unknown until explicit native reconciliation', async ({ + page +}) => { + await start(page); + expect( + await page.evaluate(() => window.hcp122Fixture.failReadback()) + ).toEqual({ status: 'unknown_completion' }); + expect(await page.evaluate(() => window.hcp122Fixture.rows())).toHaveLength( + 1 + ); + expect( + await page.evaluate(() => window.hcp122Fixture.hidesSnapshot()) + ).toMatchObject({ state: 'ready', publishers: [] }); + await page.evaluate(() => window.hcp122Fixture.refresh()); + expect( + await page.evaluate(() => window.hcp122Fixture.hidesSnapshot()) + ).toMatchObject({ state: 'ready', publishers: [events[0].pubkey] }); + expect(effects).toBe(0); +}); +test('HCP122 a concurrent full-wire native write causes conflict without overwriting another preference', async ({ + page +}) => { + await start(page); + expect( + await page.evaluate(() => window.hcp122Fixture.conflictWrite()) + ).toEqual({ status: 'conflict' }); + const rows = await page.evaluate(() => window.hcp122Fixture.rows()); + expect(rows).toHaveLength(1); + expect( + (JSON.parse((rows[0] as { wire: string }).wire) as { publishers: string[] }) + .publishers + ).not.toContain(events[0].pubkey); + expect(effects).toBe(0); +}); +test('HCP122 denied storage leaves browse-only with honest unconfirmed preferences', async ({ + page +}) => { + await start(page); + expect(await page.evaluate(() => window.hcp122Fixture.denyStorage())).toEqual( + { state: 'unavailable', reason: 'unavailable' } + ); + await expect(page.locator('#hcp122-panel')).toContainText( + 'previous hides are unconfirmed' + ); + await expect( + page + .locator('#hcp122-panel') + .getByRole('button', { name: 'Hide publisher locally', exact: true }) + ).toHaveCount(0); + expect(effects).toBe(0); +}); +test('HCP122 original generation is revoked after same-author reconnect and new custody reopens exact facts', async ({ + page +}) => { + await start(page); + await page.evaluate(() => window.hcp122Fixture.hide()); + const before = await page.evaluate(() => window.hcp122Fixture.rows()); + expect(await page.evaluate(() => window.hcp122Fixture.reconnect())).toEqual({ + status: 'stopped' + }); + expect(await page.evaluate(() => window.hcp122Fixture.rows())).toEqual( + before + ); + expect( + await page.evaluate(() => window.hcp122Fixture.hidesSnapshot()) + ).toMatchObject({ state: 'ready', publishers: [events[0].pubkey] }); + expect(effects).toBe(0); +}); +for (const width of [320, 1024]) + test(`HCP122 ${width}px local hide and Undo are separately visible and operable`, async ({ + page + }) => { + await page.setViewportSize({ width, height: 800 }); + await start(page); + await page + .locator('#hcp122-panel') + .getByRole('button', { name: 'Hide publisher locally', exact: true }) + .click(); + await expect( + page.locator('#hcp122-panel').getByRole('button', { name: /Undo hide/ }) + ).toBeVisible(); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth > window.innerWidth + ) + ).toBe(false); + expect(effects).toBe(0); + }); + +test('HCP122 existing hide reconciles the complete native row changed by another controller', async ({ + page +}) => { + await start(page); + await expect + .poll(() => + page.evaluate(() => window.hcp122Fixture.publicSnapshot()?.food?.title) + ) + .toBe('Visible carrots'); + await page.evaluate(() => window.hcp122Fixture.search()); + await expect(page.locator('[data-public-search]')).toContainText( + 'Visible carrots' + ); + const before = await page.evaluate(() => + window.hcp122Fixture.hidesSnapshot() + ); + expect(before).toMatchObject({ state: 'ready', revision: 0, publishers: [] }); + const concurrent = await page.evaluate(() => + window.hcp122Fixture.concurrentPreference(true) + ); + expect( + await page.evaluate(() => window.hcp122Fixture.hidesSnapshot()) + ).toEqual(before); + expect(await page.evaluate(() => window.hcp122Fixture.hide())).toEqual({ + status: 'existing' + }); + // Immediate actual-state assertion gives a real regression, without waiting for a UI deadline. + expect( + await page.evaluate(() => window.hcp122Fixture.hidesSnapshot()) + ).toEqual(concurrent.snapshot); + expect(await page.evaluate(() => window.hcp122Fixture.rows())).toEqual( + concurrent.rows + ); + expect(concurrent.snapshot).toMatchObject({ state: 'ready', revision: 2 }); + await expect( + page.locator('#hcp122-panel').getByRole('button', { name: /Undo hide/ }) + ).toHaveCount(2); + await expect(page.locator('[data-public-search]')).not.toContainText( + 'Visible carrots' + ); + expect( + await page.evaluate(() => window.hcp122Fixture.publicSnapshot()) + ).toMatchObject({ outcome: 'unavailable', food: undefined }); + expect(effects).toBe(0); +}); +test('HCP122 existing Undo reconciles the full native row while preserving an unrelated hide', async ({ + page +}) => { + await start(page); + await expect + .poll(() => + page.evaluate(() => window.hcp122Fixture.publicSnapshot()?.food?.title) + ) + .toBe('Visible carrots'); + expect(await page.evaluate(() => window.hcp122Fixture.hide())).toEqual({ + status: 'saved' + }); + const before = await page.evaluate(() => + window.hcp122Fixture.hidesSnapshot() + ); + const concurrent = await page.evaluate(() => + window.hcp122Fixture.concurrentPreference(false) + ); + expect( + await page.evaluate(() => window.hcp122Fixture.hidesSnapshot()) + ).toEqual(before); + expect(await page.evaluate(() => window.hcp122Fixture.undo())).toEqual({ + status: 'existing' + }); + expect( + await page.evaluate(() => window.hcp122Fixture.hidesSnapshot()) + ).toEqual(concurrent.snapshot); + expect(await page.evaluate(() => window.hcp122Fixture.rows())).toEqual( + concurrent.rows + ); + expect(concurrent.snapshot).toMatchObject({ state: 'ready', revision: 3 }); + await expect( + page.locator('#hcp122-panel').getByRole('button', { name: /Undo hide/ }) + ).toHaveCount(1); + await page.evaluate(() => window.hcp122Fixture.read()); + await expect + .poll(() => + page.evaluate(() => window.hcp122Fixture.publicSnapshot()?.food?.title) + ) + .toBe('Visible carrots'); + expect(effects).toBe(0); +}); diff --git a/web/tests/integration/loopback.test.ts b/web/tests/integration/loopback.test.ts @@ -96,6 +96,18 @@ await test('navigation fallback serves actual separate output and preserves miss assert.notEqual(search, fallback); assert.match(search, /<title>Search food — HarvestCircle<\/title>/); assert.match(search, /Search sources are unavailable\./); + const privacy = prerendered.get('/privacy'); + assert.ok(privacy); + assert.match(privacy, /Hiding a publisher is local/); + assert.match( + privacy, + /does not delete listings, remote copies or your publication receipts/ + ); + assert.match( + privacy, + /Guest browsing\s+does not expose an account inventory/ + ); + assert.doesNotMatch(privacy, /Undo hide|[0-9a-f]{64}/); const document = { accept: 'text/html', 'sec-fetch-dest': 'document' }; const server = await createStaticHarness(); try { diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs @@ -130,6 +130,62 @@ import { auditOutput } from '../../tools/check-output.mjs'; /** @param {string} web */ async function restoreHistoricalPublicProducers(web) { for (const [name, value] of Object.entries({ + ...{ + 'src/lib/runtime/identity-session.ts': { + source: + "import {\n createExtensionAdapter,\n extensionSnapshot,\n connectExtensionAdapter,\n recheckExtensionAdapter,\n probeExtensionAdapter,\n disconnectExtensionAdapter,\n extensionOwnershipCapture,\n extensionMessagingOwnershipCapture,\n subscribeExtensionInvalidation,\n signApprovedExtensionAdapter,\n markApprovedSigningWaitExpired,\n type ApprovedSignResult,\n type ExtensionAdapter,\n type ExtensionSnapshot,\n type ExtensionGuestReason\n} from '../nostr/extension.ts';\nimport { approveCapturedPublicSigning } from '../nostr/approved-signing.ts';\nimport {\n publicRecordSnapshot,\n publicRecordWire,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport {\n stopPublicEffect,\n type PublicEffectLease,\n type PublicEffectCapture\n} from './effect-ownership.ts';\nimport {\n bindLatePublicResponse,\n latePublicResultIdentity,\n reviewLatePublicArtifact,\n type LatePublicArtifact\n} from './late-results.ts';\nimport {\n capturedArtifactSnapshot,\n type CapturedArtifact\n} from '../persistence/artifact-records.ts';\n\ndeclare const sessionBrand: unique symbol;\nexport type IdentitySession = Readonly<{ [sessionBrand]: true }>;\nexport type IdentitySnapshot = (\n | Readonly<{ state: 'guest'; reason: ExtensionGuestReason }>\n | Readonly<{ state: 'pending'; action: 'connect' | 'recheck' | 'probe' }>\n | Readonly<{\n state: 'connected' | 'signing_only' | 'messaging_capable';\n publicKey: string;\n messaging: 'not_probed' | 'unsupported' | 'refused' | 'capable';\n }>\n) &\n Readonly<{ admission?: 'busy' }>;\n// Per-client opaque session, never a module-global server user. A public key is\n// an extension observation, not installed-account or publishing authorization.\nconst sessions = new WeakMap<IdentitySession, ExtensionAdapter>();\ntype ViewController = { stamp(): symbol; invalidate(): void };\nconst views = new WeakMap<IdentitySession, ViewController>();\ndeclare const operationBrand: unique symbol;\nexport type IdentityPublicOperation = Readonly<{ [operationBrand]: true }>;\ntype OperationController = {\n session: IdentitySession;\n ownership(): PublicEffectCapture | undefined;\n sign(lease: PublicEffectLease): Promise<ApprovedSignResult>;\n stop(expired: boolean): void;\n snapshot(): Readonly<{\n owner: string;\n id: string;\n revision: number;\n hash: string;\n current: boolean;\n lateAvailable: boolean;\n outcome: ApprovedSignResult['status'] | 'not_started' | 'pending';\n }>;\n review(\n record: PublicRecordHandle,\n review: unknown\n ): CapturedArtifact | undefined;\n};\nconst operations = new WeakMap<IdentityPublicOperation, OperationController>();\nexport function createIdentitySession(): IdentitySession {\n const session = Object.freeze({}) as IdentitySession;\n sessions.set(session, createExtensionAdapter());\n let stamp = Symbol();\n views.set(session, {\n stamp: () => stamp,\n invalidate() {\n stamp = Symbol();\n }\n });\n return session;\n}\nfunction mapIdentitySnapshot(snapshot: ExtensionSnapshot): IdentitySnapshot {\n if (snapshot.state !== 'connected') return { ...snapshot };\n const state: IdentitySnapshot = {\n state:\n snapshot.messaging === 'capable' && snapshot.signingCandidate\n ? 'messaging_capable'\n : snapshot.signingCandidate\n ? 'signing_only'\n : 'connected',\n publicKey: snapshot.publicKey,\n messaging: snapshot.messaging\n };\n return snapshot.admission === 'busy'\n ? { ...state, admission: 'busy' }\n : state;\n}\nexport function identitySessionSnapshot(\n session: IdentitySession\n): IdentitySnapshot {\n const adapter = sessions.get(session);\n return adapter\n ? mapIdentitySnapshot(extensionSnapshot(adapter))\n : { state: 'guest', reason: 'unavailable' };\n}\nexport async function connectIdentity(\n session: IdentitySession\n): Promise<IdentitySnapshot> {\n const adapter = sessions.get(session);\n if (adapter)\n return mapIdentitySnapshot(await connectExtensionAdapter(adapter));\n return identitySessionSnapshot(session);\n}\nexport async function recheckIdentityOwner(\n session: IdentitySession\n): Promise<IdentitySnapshot> {\n const adapter = sessions.get(session);\n if (adapter)\n return mapIdentitySnapshot(await recheckExtensionAdapter(adapter));\n return identitySessionSnapshot(session);\n}\nexport async function probeIdentityMessaging(\n session: IdentitySession,\n review: unknown\n): Promise<IdentitySnapshot> {\n const adapter = sessions.get(session);\n if (adapter)\n return mapIdentitySnapshot(await probeExtensionAdapter(adapter, review));\n return identitySessionSnapshot(session);\n}\nexport function disconnectIdentity(session: IdentitySession): void {\n views.get(session)?.invalidate();\n const adapter = sessions.get(session);\n if (adapter) disconnectExtensionAdapter(adapter);\n}\n// Internal messaging lifecycle ports. Captured observation is not an inbox\n// configuration, AUTH, private store or publication permission.\nexport function identityMessagingOwnership(\n session: IdentitySession\n): PublicEffectCapture | undefined {\n const adapter = sessions.get(session);\n return adapter && extensionMessagingOwnershipCapture(adapter);\n}\nexport function subscribeIdentityInvalidation(\n session: IdentitySession,\n listener: () => void\n): () => void {\n const adapter = sessions.get(session);\n return adapter ? subscribeExtensionInvalidation(adapter, listener) : () => {};\n}\n// Explicit route/input lifecycle event. No draft, DB, reconnect or SDK effect.\nexport function invalidateIdentityOperations(session: IdentitySession): void {\n views.get(session)?.invalidate();\n}\n// Internal public operation capability, never an unrestricted UI template signer.\n// Current-head/inbox/IDB preparation and publication retain their typed owners.\nexport function captureIdentityPublicOperation(\n session: IdentitySession,\n record: PublicRecordHandle,\n id: unknown,\n review: unknown\n): IdentityPublicOperation | undefined {\n const adapter = sessions.get(session),\n view = views.get(session);\n const captured = adapter && extensionOwnershipCapture(adapter);\n if (!adapter || !view || !captured) return undefined;\n const row = publicRecordSnapshot(record, captured.owner, id),\n recordWire = publicRecordWire(record, captured.owner, id);\n const approval = approveCapturedPublicSigning(\n record,\n captured.owner,\n id,\n review\n );\n if (\n !row ||\n !recordWire ||\n !approval ||\n row.family === 'public_draft' ||\n row.revision !== 0\n )\n return undefined;\n const owner = row.owner,\n command = row.id,\n epoch = view.stamp(),\n originalSession = captured.session;\n let stopped = false,\n pending = false;\n let lease: PublicEffectLease | undefined,\n late: LatePublicArtifact | undefined;\n let outcome: ApprovedSignResult['status'] | 'not_started' | 'pending' =\n 'not_started';\n const current = () =>\n !stopped && view.stamp() === epoch && captured.current();\n const token = Object.freeze({}) as IdentityPublicOperation;\n operations.set(token, {\n session,\n ownership: () =>\n current() ? { owner, session: originalSession, current } : undefined,\n async sign(originalLease) {\n if (pending) return { status: 'busy' };\n if (!current()) return { status: 'stale' };\n pending = true;\n lease = originalLease;\n outcome = 'pending';\n try {\n let result = await signApprovedExtensionAdapter(\n adapter,\n approval,\n originalLease\n );\n // The adapter's promise can settle before this continuation runs.\n // Recheck this view before disclosing a normal signed result.\n if (result.status === 'signed' && !current()) {\n const artifact = capturedArtifactSnapshot(result.artifact);\n const originalLate =\n artifact &&\n bindLatePublicResponse(\n approval,\n JSON.parse(artifact.wire),\n originalSession\n );\n result = originalLate\n ? { status: 'unknown', late: originalLate }\n : { status: 'unknown' };\n }\n outcome = result.status;\n if (result.status === 'unknown' && result.late) {\n const original = latePublicResultIdentity(result.late);\n if (\n original?.owner === owner &&\n original.id === command &&\n original.recordWire === recordWire &&\n original.session === originalSession\n )\n late = result.late;\n }\n // Only disclosure/explicit original-operation review can obtain a late\n // artifact. A normal signing result never returns it after invalidation.\n return result.status === 'unknown' ? { status: 'unknown' } : result;\n } finally {\n pending = false;\n lease = undefined;\n }\n },\n stop(expired) {\n stopped = true;\n if (lease) {\n if (expired) markApprovedSigningWaitExpired(adapter, approval, lease);\n stopPublicEffect(lease);\n }\n },\n snapshot: () => ({\n owner,\n id: command,\n revision: row.revision,\n hash: row.capture.hash,\n current: current(),\n lateAvailable: late !== undefined,\n outcome\n }),\n review(original, consent) {\n const observed = extensionSnapshot(adapter);\n return late &&\n observed.state === 'connected' &&\n observed.publicKey === owner\n ? reviewLatePublicArtifact(late, original, owner, command, consent)\n : undefined;\n }\n });\n return token;\n}\nfunction operationOf(session: IdentitySession, token: IdentityPublicOperation) {\n const operation = operations.get(token);\n return operation?.session === session ? operation : undefined;\n}\nexport function identityPublicOperationOwnership(\n session: IdentitySession,\n operation: IdentityPublicOperation\n): PublicEffectCapture | undefined {\n return operationOf(session, operation)?.ownership();\n}\nexport function identityPublicOperationSnapshot(\n session: IdentitySession,\n operation: IdentityPublicOperation\n) {\n return operationOf(session, operation)?.snapshot();\n}\nexport function signIdentityPublicOperation(\n session: IdentitySession,\n operation: IdentityPublicOperation,\n lease: PublicEffectLease\n): Promise<ApprovedSignResult> {\n return (\n operationOf(session, operation)?.sign(lease) ??\n Promise.resolve({ status: 'invalid_approval' })\n );\n}\nexport function stopIdentityPublicOperation(\n session: IdentitySession,\n operation: IdentityPublicOperation\n): void {\n operationOf(session, operation)?.stop(false);\n}\n// UI supplies expiry; existing scheduler owns its actual pending promise.\nexport function expireIdentityPublicOperationWait(\n session: IdentitySession,\n operation: IdentityPublicOperation\n): void {\n operationOf(session, operation)?.stop(true);\n}\n// Pure same-author original review, not fresh author/CAS/resume/publish proof.\nexport function reviewIdentityLatePublicArtifact(\n session: IdentitySession,\n operation: IdentityPublicOperation,\n original: PublicRecordHandle,\n review: unknown\n): CapturedArtifact | undefined {\n return operationOf(session, operation)?.review(original, review);\n}\n", + sha256: + '0efc6bfdea0bbcb4e6b22e2b5b9008db2b78df259d751f3557e92eedaf245274' + }, + 'src/lib/runtime/public-runtime.ts': { + source: + "import { deploymentRelayPolicy } from '../config/deployment-relays.ts';\nimport type { RelayPolicy } from '../config/relays.ts';\nimport { qualifiedNip50Sources } from '../nostr/search-sources.ts';\nimport {\n getPublicPool,\n subscribePublicPool,\n closePublicPool,\n type PublicPool\n} from '../nostr/public-pool.ts';\nimport {\n getPublicStore,\n insertPublicEnvelope,\n closePublicStore,\n publicStoreRetention,\n publicStoreKnownEvidence,\n publicStoreEnvelope,\n type PublicStore\n} from '../nostr/public-store.ts';\nimport {\n createPublicScheduler,\n createPublicRun,\n openPublicRequest,\n openInboxRequest,\n disposePublicRun,\n closePublicScheduler,\n publicRunSnapshot,\n type PublicScheduler,\n type PublicRun,\n type PublicRequest,\n type RequestKind,\n type RequestClock\n} from '../nostr/request-scope.ts';\nimport type { PublicFilter } from '../nostr/exports.ts';\nimport { inboxPreferenceQueries } from '../nostr/inbox-queries.ts';\nimport {\n publicHeadEnvelope,\n publicHeadSnapshot,\n type PublicHead\n} from '../catalog/heads.ts';\nimport type { KnownPublicEvidence } from '../catalog/retention.ts';\nimport type { VerifiedEnvelope } from '../nostr/verified-envelope.ts';\ndeclare const contextBrand: unique symbol;\ndeclare const runtimeBrand: unique symbol;\ndeclare const viewBrand: unique symbol;\nexport type PublicRuntimeContext = Readonly<{ readonly [contextBrand]: true }>;\nexport type PublicRuntime = Readonly<{ readonly [runtimeBrand]: true }>;\nexport type PublicView = Readonly<{ readonly [viewBrand]: true }>;\nexport const PUBLIC_RUNTIME_CONTEXT = 'harvestcircle_public_runtime';\ninterface RuntimeOwner {\n readonly pool: PublicPool;\n readonly store: PublicStore;\n readonly scheduler: PublicScheduler;\n readonly policy: RelayPolicy;\n readonly views: Map<PublicView, () => boolean>;\n readonly closed: () => boolean;\n readonly projectionValid: (retry?: boolean) => boolean;\n readonly invalidateProjection: () => void;\n readonly close: () => void;\n}\ninterface ContextOwner {\n readonly value: () => PublicRuntime | undefined;\n readonly mount: (\n policy: RelayPolicy,\n clock?: RequestClock\n ) => PublicRuntime | undefined;\n readonly ready: Promise<PublicRuntime | undefined>;\n readonly close: () => void;\n}\ninterface ViewOwner {\n readonly runtime: RuntimeOwner;\n readonly begin: () => PublicRun;\n readonly current: (run: PublicRun) => boolean;\n readonly settling: () => boolean;\n readonly settleWith: (refresh: () => void) => void;\n readonly dispose: () => boolean;\n}\nconst contexts = new WeakMap<PublicRuntimeContext, ContextOwner>(),\n runtimes = new WeakMap<PublicRuntime, RuntimeOwner>(),\n views = new WeakMap<PublicView, ViewOwner>();\nlet browserContext: PublicRuntimeContext | undefined;\nfunction contextOf(token: PublicRuntimeContext): ContextOwner {\n const owner = contexts.get(token);\n if (!owner) throw new Error('public_runtime_context_invalid');\n return owner;\n}\nfunction runtimeOf(token: PublicRuntime): RuntimeOwner {\n const owner = runtimes.get(token);\n if (!owner) throw new Error('public_runtime_invalid');\n if (owner.closed()) throw new Error('public_runtime_closed');\n return owner;\n}\nfunction viewOf(token: PublicView): ViewOwner {\n const owner = views.get(token);\n if (!owner) throw new Error('public_view_invalid');\n return owner;\n}\n// Context construction is SSR-pure. Root onMount acquires the browser lifetime;\n// children can await readiness even when their onMount runs before the root's.\nexport function createPublicRuntimeContext(): PublicRuntimeContext {\n let value: PublicRuntime | undefined,\n closed = false;\n let ready: (value: PublicRuntime | undefined) => void = () => {};\n let selectedClock: RequestClock | undefined;\n const promise = new Promise<PublicRuntime | undefined>((resolve) => {\n ready = resolve;\n });\n const owner: ContextOwner = {\n value: () => (closed ? undefined : value),\n ready: promise,\n mount(policy, clock) {\n if (closed) throw new Error('public_runtime_closed');\n if (typeof window === 'undefined') return undefined;\n if (value) {\n const prior = runtimes.get(value);\n if (!prior || prior.policy !== policy)\n throw new Error('public_runtime_policy_changed');\n if (clock !== selectedClock)\n throw new Error('public_runtime_clock_changed');\n return value;\n }\n if (browserContext && browserContext !== contextToken)\n throw new Error('public_runtime_owner_changed');\n const pool = getPublicPool(policy),\n store = getPublicStore();\n if (!pool || !store) return undefined;\n const scheduler = createPublicScheduler(clock),\n registered = new Map<PublicView, () => boolean>();\n let terminal = false,\n invalidated = false,\n invalidating = false;\n const token = Object.freeze({}) as PublicRuntime;\n const runtime: RuntimeOwner = {\n pool,\n store,\n scheduler,\n policy,\n views: registered,\n closed: () => terminal,\n projectionValid(retry = true) {\n const retained = publicStoreRetention(store);\n if (retained.stopped || (!terminal && retained.closed))\n invalidated = true;\n // A settler reads the terminal flag without recursively retrying its\n // own disposal. The outer cleanup loop keeps failed controls live.\n if (invalidated && retry) runtime.invalidateProjection();\n return !invalidated;\n },\n invalidateProjection() {\n invalidated = true;\n if (invalidating) return;\n invalidating = true;\n let failed = false;\n try {\n for (const dispose of registered.values())\n if (!dispose()) failed = true;\n } finally {\n invalidating = false;\n }\n if (failed) throw new Error('public_projection_close_failed');\n },\n close() {\n terminal = true;\n let failed = false;\n for (const dispose of registered.values())\n if (!dispose()) failed = true;\n // Reentrant or failed settlement cannot preserve a coherent projection\n // across store teardown. Terminal uncertainty clears every view.\n if (failed) invalidated = true;\n try {\n closePublicScheduler(scheduler);\n } catch {\n failed = true;\n }\n try {\n closePublicPool(pool);\n } catch {\n failed = true;\n }\n try {\n closePublicStore(store);\n } catch {\n failed = true;\n }\n if (failed) throw new Error('public_runtime_close_failed');\n }\n };\n runtimes.set(token, runtime);\n value = token;\n browserContext = contextToken;\n selectedClock = clock;\n ready(token);\n return token;\n },\n close() {\n closed = true;\n ready(undefined);\n if (value) {\n const runtime = runtimes.get(value);\n if (runtime) runtime.close();\n }\n }\n };\n const contextToken = Object.freeze({}) as PublicRuntimeContext;\n contexts.set(contextToken, owner);\n return contextToken;\n}\nexport function publicRuntime(\n context: PublicRuntimeContext\n): PublicRuntime | undefined {\n return contextOf(context).value();\n}\nexport function publicRuntimeReady(\n context: PublicRuntimeContext\n): Promise<PublicRuntime | undefined> {\n return contextOf(context).ready;\n}\n// Original runtime policy observation only, never a pool or effect capability.\nexport function publicRuntimePolicy(\n runtime: PublicRuntime\n): RelayPolicy | undefined {\n try {\n const owner = runtimeOf(runtime);\n return !owner.closed() && owner.projectionValid()\n ? owner.policy\n : undefined;\n } catch {\n return;\n }\n}\nexport function mountPublicRuntime(\n context: PublicRuntimeContext,\n policy: RelayPolicy = deploymentRelayPolicy,\n clock?: RequestClock\n): PublicRuntime | undefined {\n return contextOf(context).mount(policy, clock);\n}\nexport function closePublicRuntime(context: PublicRuntimeContext): void {\n contextOf(context).close();\n}\nexport function createPublicView(runtime: PublicRuntime): PublicView {\n const shared = runtimeOf(runtime);\n if (!shared.projectionValid())\n throw new Error('public_projection_unavailable');\n const token = Object.freeze({}) as PublicView;\n let run: PublicRun | undefined,\n disposed = false;\n let generation = 0,\n settler: (() => void) | undefined,\n settling = false;\n function settle() {\n const refresh = settler;\n settler = undefined; // Detach before any caller-controlled clock reentry.\n if (!refresh) return;\n settling = true;\n try {\n refresh?.();\n } catch (error) {\n if (!settler) settler = refresh;\n throw error;\n } finally {\n settling = false;\n }\n }\n const owner: ViewOwner = {\n runtime: shared,\n begin() {\n if (disposed || shared.closed() || !shared.projectionValid())\n throw new Error('public_view_closed');\n const operation = ++generation,\n previous = run;\n // Generation reserves the transition; keep failed old controls retryable.\n try {\n settle();\n } finally {\n if (previous) disposePublicRun(previous);\n }\n if (\n operation !== generation ||\n disposed ||\n shared.closed() ||\n !shared.projectionValid()\n )\n throw new Error('public_view_run_superseded');\n const candidate = createPublicRun(shared.scheduler, shared.policy);\n // Run creation samples the injected clock. It may synchronously start a\n // newer view generation before returning; never overwrite that owner.\n if (\n operation !== generation ||\n disposed ||\n shared.closed() ||\n !shared.projectionValid()\n ) {\n disposePublicRun(candidate);\n throw new Error('public_view_run_superseded');\n }\n run = candidate;\n return run;\n },\n settling: () => settling,\n settleWith(refresh) {\n const previous = settler;\n settler = refresh;\n previous?.();\n },\n current(candidate) {\n return !disposed && !shared.closed() && run === candidate;\n },\n dispose() {\n disposed = true;\n generation++;\n if (settling) return false;\n try {\n settle();\n if (run) disposePublicRun(run);\n shared.views.delete(token);\n return true;\n } catch {\n return false;\n }\n }\n };\n views.set(token, owner);\n shared.views.set(token, () => owner.dispose());\n return token;\n}\nexport function beginPublicViewRun(view: PublicView): PublicRun {\n return viewOf(view).begin();\n}\nexport function publicViewRunCurrent(\n view: PublicView,\n run: PublicRun\n): boolean {\n return viewOf(view).current(run) && publicRunSnapshot(run).active;\n}\n// Ownership survives an ordinary deadline so a foreground owner can publish\n// its terminal result once. Supersession/disposal/shared closure revoke it.\nexport function publicViewOwnsRun(view: PublicView, run: PublicRun): boolean {\n return viewOf(view).current(run);\n}\nexport function disposePublicView(view: PublicView): void {\n if (!viewOf(view).dispose()) throw new Error('public_view_close_failed');\n}\nexport function subscribePublicView(\n view: PublicView,\n run: PublicRun,\n kind: RequestKind,\n filters: readonly PublicFilter[],\n onVerified: (event: VerifiedEnvelope) => void,\n sampleSource?: string\n): PublicRequest {\n const owner = viewOf(view);\n if (!owner.current(run)) throw new Error('public_view_run_inactive');\n // Copy the request template once before SDK effects; caller mutations cannot\n // retarget this request. Product filter builders remain HCP038 and later.\n const frozen = JSON.stringify(filters);\n return openPublicRequest(\n run,\n kind,\n (next) =>\n subscribePublicPool(\n owner.runtime.pool,\n JSON.parse(frozen) as PublicFilter[],\n next,\n sampleSource\n ),\n (event) => {\n if (!owner.current(run)) return;\n const result = insertPublicEnvelope(owner.runtime.store, event);\n if (result === 'limit' || result === 'rejected' || result === 'closed') {\n owner.runtime.invalidateProjection();\n return;\n }\n if (\n (result === 'accepted' || result === 'duplicate') &&\n owner.current(run)\n )\n onVerified(event);\n },\n sampleSource\n );\n}\n\nexport function publicViewNip50Sources(view: PublicView): readonly string[] {\n return qualifiedNip50Sources(viewOf(view).runtime.policy);\n}\n\n// Public metadata, dedicated ownership: no preference enters the food store.\n// Fixed anonymous origins, clocks, scheduler and aggregate ingress stay shared.\nexport function subscribeInboxPreference(\n view: PublicView,\n run: PublicRun,\n author: unknown,\n onVerified: (event: VerifiedEnvelope, inboxSource?: string) => void\n): PublicRequest {\n const owner = viewOf(view),\n filters = inboxPreferenceQueries(author);\n if (!owner.current(run)) throw new Error('public_view_run_inactive');\n return openInboxRequest(\n run,\n author,\n (next) => subscribePublicPool(owner.runtime.pool, filters, next),\n (event, inboxSource) => {\n if (owner.current(run)) onVerified(event, inboxSource);\n }\n );\n}\n\n// Capacity invalidation differs from ordinary teardown: last-known snapshots\n// remain available on normal close, while a breached working set clears all views.\nexport function publicViewProjectionAvailable(view: PublicView): boolean {\n const owner = viewOf(view);\n return owner.runtime.projectionValid(!owner.settling());\n}\nexport function publicViewKnownEvidence(\n view: PublicView,\n head: PublicHead\n): KnownPublicEvidence {\n return publicStoreKnownEvidence(viewOf(view).runtime.store, head);\n}\nexport function retainPublicViewHeads(\n view: PublicView,\n run: PublicRun,\n heads: readonly PublicHead[]\n): boolean {\n const owner = viewOf(view);\n if (!owner.current(run) || !owner.runtime.projectionValid()) return false;\n const active = publicRunSnapshot(run).active;\n if (!owner.current(run) || !owner.runtime.projectionValid()) return false;\n if (!active) {\n // Inactive materialization cannot install or charge another event. Require\n // every genuine head to have already passed the shared retained cache.\n for (const head of heads) {\n if (\n !publicStoreEnvelope(owner.runtime.store, publicHeadSnapshot(head).id)\n )\n throw new Error('public_view_uncached_head');\n }\n return owner.current(run) && owner.runtime.projectionValid();\n }\n for (const head of heads) {\n const result = insertPublicEnvelope(\n owner.runtime.store,\n publicHeadEnvelope(head)\n );\n if (result !== 'accepted' && result !== 'duplicate') {\n owner.runtime.invalidateProjection();\n return false;\n }\n }\n return owner.runtime.projectionValid();\n}\n\n// Trusted model binding holds only the current projection for this view.\n// Replacement/disposal settles it while retained shared lifecycle proof is live.\nexport function settlePublicViewProjection(\n view: PublicView,\n refresh: () => void\n): void {\n viewOf(view).settleWith(refresh);\n}\n", + sha256: + '8d2b840e94448b55642b1481d12785ed76d326735a4461e9795f57a98e8d2530' + }, + '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 publicViewKnownEvidence,\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 publicHeadEnvelope,\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 { VerifiedEnvelope } from '../nostr/verified-envelope.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 }>;\ndeclare const acknowledgementBrand: unique symbol;\nexport type ProductStatusAcknowledgement = Readonly<{\n readonly [acknowledgementBrand]: true;\n}>;\nconst acknowledgements = new WeakMap<\n ProductStatusAcknowledgement,\n { view: ProductView; current(this: void): boolean }\n>();\ninterface Owner {\n snapshot: () => ProductViewSnapshot;\n listing: (\n acknowledgement?: ProductStatusAcknowledgement\n ) => ProductListingOwnership | undefined;\n acknowledge: (review: unknown) => ProductStatusAcknowledgement | undefined;\n close: () => void;\n}\nexport type ProductListingOwnership = Readonly<{\n proof: VerifiedEnvelope;\n available: () => boolean;\n current: () => boolean;\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 function coverageKey(observed: ProductViewSnapshot) {\n return JSON.stringify({\n runCurrent: publicViewRunCurrent(view, run),\n outcome: observed.outcome,\n eventId: observed.eventId,\n lastKnown: observed.lastKnown,\n sources: observed.sources.map((scope) => ({\n context: scope.result.context,\n state: scope.state,\n coverage: scope.result.coverage,\n sources: scope.result.sources.map(({ source, state }) => ({\n source,\n state\n }))\n }))\n });\n }\n owners.set(token, {\n snapshot,\n acknowledge(review) {\n const observed = snapshot();\n if (\n review !== 'reviewed_last_known_listing' ||\n observed.outcome !== 'active' ||\n !observed.lastKnown ||\n !observed.eventId ||\n !head ||\n closed\n )\n return;\n const key = coverageKey(observed);\n const consent = Object.freeze({}) as ProductStatusAcknowledgement;\n acknowledgements.set(consent, {\n view: token,\n current: () =>\n !closed &&\n publicViewOwnsRun(view, run) &&\n publicViewProjectionAvailable(view) &&\n coverageKey(snapshot()) === key\n });\n return consent;\n },\n listing(acknowledgement) {\n const observed = snapshot();\n const capturedConsent =\n acknowledgement && acknowledgements.get(acknowledgement);\n const consent =\n capturedConsent?.view === token ? capturedConsent.current : undefined;\n if (\n observed.outcome !== 'active' ||\n (observed.lastKnown && !consent?.()) ||\n !head\n )\n return;\n const selected = publicViewKnownEvidence(view, head).head;\n const metadata = publicHeadSnapshot(selected);\n if (\n metadata.id !== observed.eventId ||\n metadata.pubkey !== reference.pubkey ||\n metadata.identifier !== reference.identifier\n )\n return;\n return {\n proof: publicHeadEnvelope(selected),\n available: () =>\n !closed &&\n publicViewOwnsRun(view, run) &&\n publicViewProjectionAvailable(view),\n current() {\n const actual = snapshot();\n return (\n !closed &&\n actual.outcome === 'active' &&\n (!actual.lastKnown || !!consent?.()) &&\n actual.eventId === metadata.id\n );\n }\n };\n },\n close() {\n const notifyTerminal = !closed;\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 (notifyTerminal)\n try {\n onUpdate(snapshot());\n } catch {\n /* Terminal observer cannot prevent original revocation/cleanup. */\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// Only the original current view resolves the observed signed proof. Detached\n// UI snapshots cannot create this witness or select another author/version.\nexport function productViewListingOwnership(\n token: ProductView,\n acknowledgement?: ProductStatusAcknowledgement\n): ProductListingOwnership | undefined {\n return owners.get(token)?.listing(acknowledgement);\n}\nexport function acknowledgeProductViewUncertainty(\n token: ProductView,\n review: unknown\n): ProductStatusAcknowledgement | undefined {\n return owners.get(token)?.acknowledge(review);\n}\n", + sha256: + 'c2562d1470282c758889e9855f7e7e6c32a6b2eb090e4dace2e94fdfdb6d8363' + }, + 'src/lib/catalog/search-run.ts': { + source: + "import {\n orderFoodRows,\n listingView,\n type ListingView\n} from './listing-view.ts';\nimport {\n createPublisherViews,\n readPublisherPage,\n publisherSnapshot,\n type PublisherViews\n} from './publishers.ts';\nimport {\n PUBLIC_QUERY_BUDGETS,\n PUBLIC_SEARCH_BUDGETS,\n PUBLIC_SEARCH_RUN_BUDGETS\n} from '../config/budgets.ts';\nimport type { PublicFilter } from '../nostr/exports.ts';\nimport { headResolutionQueries } from '../nostr/product-queries.ts';\nimport {\n publicRunSnapshot,\n publicRunObservations,\n publicRequestScopeSnapshot,\n closePublicRequest,\n cancelPublicRun,\n type PublicRun,\n type PublicRequest\n} from '../nostr/request-scope.ts';\nimport {\n beginPublicViewRun,\n publicViewRunCurrent,\n publicViewProjectionAvailable,\n publicViewNip50Sources,\n subscribePublicView,\n disposePublicView,\n type PublicView\n} from '../runtime/public-runtime.ts';\nimport {\n createPublicHeadCandidate,\n publicHeadKey,\n publicHeadSnapshot,\n selectPublicHead,\n type PublicHead\n} from './heads.ts';\nimport { normalizePublicQuery } from './query-input.ts';\nimport {\n createPublicViewHeadResolver,\n resolveHeads,\n resolveKnownHeads,\n headResolutionSnapshot,\n type HeadResolver\n} from './resolve-head.ts';\nimport { searchResolvedFood } from './search-match.ts';\nimport {\n searchRefreshState,\n type SearchScope,\n type SearchSnapshot\n} from './search-state.ts';\nimport type { WallClock } from './clock-policy.ts';\nimport { nip50SearchQuery } from '../nostr/search-query.ts';\nimport {\n chronologicalSearchQuery,\n requireChronologicalSearchQuery\n} from '../nostr/chronological-query.ts';\nimport {\n createChronologicalContinuation,\n localSearchPage,\n type ChronologicalContinuation,\n type ChronologicalWindow\n} from './continuation.ts';\ndeclare const coordinatorBrand: unique symbol;\ndeclare const generationBrand: unique symbol;\nexport type FoodSearchCoordinator = Readonly<{\n readonly [coordinatorBrand]: true;\n}>;\nexport type FoodSearchRun = Readonly<{ readonly [generationBrand]: true }>;\ninterface Coordinator {\n readonly view: PublicView;\n readonly publishers: PublisherViews;\n readonly clock: WallClock;\n readonly current: () => FoodSearchRun | undefined;\n readonly reserve: (token: FoodSearchRun) => void;\n readonly closed: () => boolean;\n readonly close: () => void;\n}\ninterface Session {\n readonly coordinator: Coordinator;\n readonly token: FoodSearchRun;\n readonly query: string;\n readonly heads: () => readonly PublicHead[];\n readonly pending: () => readonly PublicHead[];\n readonly resolved: (heads: readonly PublicHead[]) => void;\n readonly remember: (head: PublicHead) => boolean;\n readonly requests: () => readonly PublicRequest[];\n readonly track: (request: PublicRequest) => void;\n readonly reserveSource: () => void;\n readonly reserveSample: () => void;\n readonly continuation: () => ChronologicalContinuation;\n readonly bindContinuation: (value: ChronologicalContinuation) => void;\n readonly chronological: () => readonly (readonly [\n PublicRequest,\n ChronologicalWindow\n ])[];\n readonly trackChronological: (\n request: PublicRequest,\n window: ChronologicalWindow\n ) => void;\n readonly pages: () => number;\n readonly showMore: () => void;\n readonly run: () => PublicRun | undefined;\n readonly bindRun: (run: PublicRun) => void;\n readonly model: () => HeadResolver | undefined;\n readonly bindModel: (model: HeadResolver) => void;\n readonly flags: () => Readonly<{\n cancelled: boolean;\n failed: boolean;\n capped: boolean;\n }>;\n readonly cap: () => void;\n readonly fail: () => void;\n readonly cancel: () => void;\n}\nconst coordinators = new WeakMap<FoodSearchCoordinator, Coordinator>();\nconst viewCoordinators = new WeakMap<\n PublicView,\n Readonly<{ clock: WallClock; token: FoodSearchCoordinator }>\n>();\nconst sessions = new WeakMap<FoodSearchRun, Session>();\nfunction coordinatorOf(token: FoodSearchCoordinator): Coordinator {\n const owner = coordinators.get(token);\n if (!owner) throw new Error('food_search_coordinator_invalid');\n return owner;\n}\nfunction sessionOf(token: FoodSearchRun): Session {\n const session = sessions.get(token);\n if (!session) throw new Error('food_search_invalid');\n return session;\n}\nfunction current(session: Session): boolean {\n return (\n !session.coordinator.closed() &&\n session.coordinator.current() === session.token\n );\n}\nfunction requireCurrent(session: Session): void {\n if (!current(session)) throw new Error('food_search_superseded');\n}\n// All mutation stays in lexical plain-model owners; callers get opaque handles\n// and detached snapshots, never map-returned mutable records or SDK objects.\nfunction createSession(\n coordinator: Coordinator,\n token: FoodSearchRun,\n query: string,\n seed: readonly PublicHead[],\n fallback: HeadResolver | undefined\n): Session {\n const heads = new Map(seed.map((head) => [publicHeadKey(head), head]));\n const resolved = new Map<string, true>();\n const requests = new Map<PublicRequest, true>();\n let run: PublicRun | undefined,\n model = fallback;\n let cancelled = false,\n failed = false,\n capped = false;\n let attempts = 0;\n let sampleRounds = 0;\n let chronological = createChronologicalContinuation(),\n pages = 1;\n const windows = new Map<PublicRequest, ChronologicalWindow>();\n return {\n coordinator,\n token,\n query,\n heads: () => Array.from(heads.values()),\n pending: () =>\n Array.from(heads.values()).filter(\n (head) => !resolved.has(publicHeadKey(head))\n ),\n resolved: (values) => {\n for (const head of values) resolved.set(publicHeadKey(head), true);\n },\n remember(head) {\n const key = publicHeadKey(head);\n if (\n !heads.has(key) &&\n heads.size >= PUBLIC_QUERY_BUDGETS.coordinatesPerRun\n ) {\n capped = true;\n return false;\n }\n heads.set(key, selectPublicHead(heads.get(key), head).head);\n return true;\n },\n requests: () => Array.from(requests.keys()),\n track: (request) => {\n requests.set(request, true);\n },\n reserveSource() {\n if (attempts >= PUBLIC_SEARCH_RUN_BUDGETS.primaryScopes) {\n capped = true;\n throw new Error('food_search_primary_limit');\n }\n attempts++;\n },\n reserveSample() {\n if (sampleRounds >= PUBLIC_SEARCH_RUN_BUDGETS.nip50Rounds)\n throw new Error('food_search_sample_round_limit');\n sampleRounds++;\n },\n continuation: () => chronological,\n bindContinuation: (value) => {\n chronological = value;\n },\n chronological: () => Array.from(windows.entries()),\n trackChronological: (request, window) => {\n windows.set(request, window);\n },\n pages: () => pages,\n showMore: () => {\n pages = Math.min(\n Math.ceil(\n PUBLIC_QUERY_BUDGETS.coordinatesPerRun /\n PUBLIC_SEARCH_BUDGETS.pageRows\n ),\n pages + 1\n );\n },\n run: () => run,\n bindRun: (value) => {\n run = value;\n },\n model: () => model,\n bindModel: (value) => {\n model = value;\n },\n flags: () => ({ cancelled, failed, capped }),\n cap: () => {\n capped = true;\n },\n fail: () => {\n failed = true;\n },\n cancel() {\n cancelled = true;\n if (run) cancelPublicRun(run);\n }\n };\n}\nexport function createFoodSearchCoordinator(\n view: PublicView,\n clock: WallClock\n): FoodSearchCoordinator {\n publicViewProjectionAvailable(view);\n if (typeof clock.nowSeconds !== 'function')\n throw new Error('food_search_clock_invalid');\n const existing = viewCoordinators.get(view);\n if (existing) {\n if (existing.clock !== clock) throw new Error('food_search_clock_changed');\n return existing.token;\n }\n const token = Object.freeze({}) as FoodSearchCoordinator;\n let generation: FoodSearchRun | undefined,\n closed = false;\n coordinators.set(token, {\n view,\n publishers: createPublisherViews(view, clock),\n clock,\n current: () => generation,\n reserve: (value) => {\n generation = value;\n },\n closed: () => closed,\n close() {\n closed = true;\n // Preserve failed cleanup controls; repeated disposal retries the view.\n disposePublicView(view);\n generation = undefined;\n }\n });\n viewCoordinators.set(view, { clock, token });\n return token;\n}\nexport function beginFoodSearch(\n coordinator: FoodSearchCoordinator,\n input: unknown,\n known: readonly PublicHead[] = []\n): FoodSearchRun {\n const owner = coordinatorOf(coordinator);\n if (owner.closed()) throw new Error('food_search_closed');\n const query = normalizePublicQuery(input);\n if (!query.ok) throw new Error(query.error);\n // Complete seed validation precedes clocks, cache and run effects.\n headResolutionQueries(known);\n const previousToken = owner.current();\n const previous =\n previousToken === undefined ? undefined : sessionOf(previousToken);\n const heads = new Map(\n previous?.heads().map((head) => [publicHeadKey(head), head])\n );\n for (const head of known) {\n const key = publicHeadKey(head);\n heads.set(key, selectPublicHead(heads.get(key), head).head);\n }\n if (heads.size > PUBLIC_QUERY_BUDGETS.coordinatesPerRun)\n throw new Error('head_resolver_coordinate_limit');\n const token = Object.freeze({}) as FoodSearchRun;\n const seed = Array.from(heads.values());\n const session = createSession(\n owner,\n token,\n query.text,\n seed,\n previous?.model()\n );\n sessions.set(token, session);\n owner.reserve(token); // Reserve before previous settlement or injected clocks.\n try {\n const run = beginPublicViewRun(owner.view);\n session.bindRun(run);\n requireCurrent(session);\n const model = createPublicViewHeadResolver(owner.view, run, owner.clock);\n session.bindModel(model);\n requireCurrent(session);\n session.resolved(seed);\n if (seed.length) resolveHeads(model, seed);\n requireCurrent(session);\n return token;\n } catch {\n if (!current(session)) throw new Error('food_search_superseded');\n session.fail();\n const run = session.run();\n if (run) {\n try {\n cancelPublicRun(run);\n } catch {\n /* Still owned, retryable. */\n }\n }\n throw new Error('food_search_start_failed');\n }\n}\nexport function foodSearchRequestOwner(token: FoodSearchRun): PublicRun {\n const session = sessionOf(token);\n requireCurrent(session);\n const run = session.run();\n if (!run || !publicViewRunCurrent(session.coordinator.view, run))\n throw new Error('food_search_inactive');\n requireCurrent(session);\n return run;\n}\n// Filter strategies remain separate; primary sources and all auxiliaries share\n// one genuine anonymous run rather than creating transport or budget owners.\nexport function subscribeFoodSearch(\n token: FoodSearchRun,\n filters: readonly PublicFilter[]\n): PublicRequest {\n if (filters.some((filter) => 'search' in filter))\n throw new Error('food_search_sample_required');\n const session = sessionOf(token);\n requireCurrent(session);\n refreshChronological(session);\n requireCurrent(session);\n const selected = requireChronologicalSearchQuery(\n filters,\n session.continuation().snapshot().until\n );\n let window: ChronologicalWindow;\n try {\n window = session.continuation().begin();\n } catch (error) {\n if (\n error instanceof Error &&\n error.message === 'food_search_chronological_window_limit'\n )\n session.cap();\n throw error;\n }\n try {\n const request = subscribeSearchSource(token, selected, undefined, window);\n session.trackChronological(request, window);\n return request;\n } catch (error) {\n window.finish(false, 'partial');\n throw error;\n }\n}\nfunction subscribeSearchSource(\n token: FoodSearchRun,\n filters: readonly PublicFilter[],\n sampleSource?: string,\n chronologicalWindow?: ChronologicalWindow\n): PublicRequest {\n const session = sessionOf(token),\n run = foodSearchRequestOwner(token);\n session.reserveSource(); // Reservation precedes SDK effects and never refunds.\n let request: PublicRequest;\n try {\n request = subscribePublicView(\n session.coordinator.view,\n run,\n 'search',\n filters,\n (proof) => {\n // Admission already includes a valid inclusive tail that stopped ingress.\n if (!current(session)) return;\n const head = createPublicHeadCandidate(proof);\n if (!head || publicHeadSnapshot(head).kind !== 30402) return;\n chronologicalWindow?.observe(head);\n if (!session.remember(head)) cancelPublicRun(run);\n },\n sampleSource\n );\n } catch {\n if (current(session)) session.fail();\n throw new Error('food_search_request_failed');\n }\n session.track(request);\n if (!current(session)) {\n closePublicRequest(request);\n throw new Error('food_search_superseded');\n }\n return request;\n}\n\nexport function sampleFoodSearch(\n token: FoodSearchRun\n): readonly PublicRequest[] {\n const session = sessionOf(token);\n requireCurrent(session);\n const filters = nip50SearchQuery(session.query);\n if (!filters.length) return [];\n const sources = publicViewNip50Sources(session.coordinator.view);\n if (!sources.length) return [];\n session.reserveSample(); // Failed attempts cannot recreate the relevance round.\n const samples = new Map<PublicRequest, true>();\n for (const source of sources) {\n requireCurrent(session);\n try {\n samples.set(subscribeSearchSource(token, filters, source), true);\n } catch {\n // A refused/failed source cannot discard other candidates or the fallback.\n requireCurrent(session);\n session.fail();\n }\n }\n return Array.from(samples.keys());\n}\nfunction refreshChronological(session: Session): void {\n for (const [request, window] of session.chronological()) {\n const scope = publicRequestScopeSnapshot(request);\n if (scope.state === 'active') continue;\n window.finish(\n scope.result.sources.some(\n (source) => source.candidates >= PUBLIC_QUERY_BUDGETS.requestedPerRelay\n ),\n scope.state === 'eose' && scope.result.coverage === 'bounded-eose'\n ? 'bounded-eose'\n : 'partial',\n scope.result.sources.map((source) => ({\n source: source.source,\n saturated: source.candidates >= PUBLIC_QUERY_BUDGETS.requestedPerRelay,\n eventIds: publicRunObservations(session.run()!, request)\n .filter((row) => row.source === source.source && row.kind === 30402)\n .map((row) => row.eventId)\n }))\n );\n }\n}\nexport function chronologicalFoodSearch(token: FoodSearchRun): PublicRequest {\n const session = sessionOf(token);\n requireCurrent(session);\n refreshChronological(session);\n requireCurrent(session);\n return subscribeFoodSearch(\n token,\n chronologicalSearchQuery(session.continuation().snapshot().until)\n );\n}\nexport function showMoreFoodSearch(token: FoodSearchRun): void {\n const session = sessionOf(token);\n requireCurrent(session);\n session.showMore();\n}\nexport function searchOlderFoodSearch(\n coordinator: FoodSearchCoordinator\n): FoodSearchRun {\n const owner = coordinatorOf(coordinator),\n previous = owner.current();\n if (!previous || owner.closed()) throw new Error('food_search_inactive');\n const session = sessionOf(previous);\n const snapshot = foodSearchSnapshot(coordinator);\n requireCurrent(session);\n if (!snapshot?.available) throw new Error('food_search_unavailable');\n const next = session.continuation().restart();\n const token = beginFoodSearch(coordinator, session.query);\n const successor = sessionOf(token);\n requireCurrent(successor);\n successor.bindContinuation(next);\n chronologicalFoodSearch(token);\n return token;\n}\nexport function foodSearchSnapshot(\n coordinator: FoodSearchCoordinator\n): SearchSnapshot<FoodSearchRun> | undefined {\n const owner = coordinatorOf(coordinator),\n token = owner.current();\n if (owner.closed() || token === undefined) return undefined;\n const session = sessionOf(token),\n model = session.model(),\n ownedRun = session.run();\n if (ownedRun && model) {\n const active = publicViewRunCurrent(owner.view, ownedRun);\n if (!current(session)) return undefined;\n const pending = session.pending();\n if (pending.length) {\n try {\n if (active) resolveHeads(model, pending);\n else resolveKnownHeads(model, pending);\n session.resolved(pending);\n } catch {\n session.fail();\n }\n }\n }\n refreshChronological(session);\n const raw = model ? headResolutionSnapshot(model) : [];\n const matched = model ? searchResolvedFood(model, session.query) : undefined;\n const scopes = new Map<object, SearchScope>();\n for (const request of session.requests()) {\n const scope = publicRequestScopeSnapshot(request);\n scopes.set(scope.result.context, scope);\n }\n for (const row of raw)\n for (const scope of [row.headSources, row.deletionSources])\n if (scope) scopes.set(scope.result.context, scope);\n const available =\n publicViewProjectionAvailable(owner.view) &&\n (matched?.ok ? matched.available : true);\n const run = ownedRun ? publicRunSnapshot(ownedRun) : undefined;\n // Model/run clocks may synchronously supersede or dispose this generation.\n if (!current(session)) return undefined;\n const sources = Array.from(scopes.values()),\n flags = session.flags();\n const refresh = searchRefreshState(\n available,\n run,\n sources,\n flags.cancelled,\n flags.failed,\n flags.capped\n );\n const continuation = session.continuation().snapshot(),\n page = localSearchPage(\n available && matched?.ok ? orderFoodRows(matched.rows) : [],\n session.pages()\n );\n const listings = new Map<string, ListingView>();\n for (const row of page.rows) {\n const value = listingView(\n row,\n publisherSnapshot(owner.publishers, row.state.head.pubkey)\n );\n if (value) listings.set(value.eventId, value);\n }\n if (!current(session)) return undefined;\n return {\n generation: token,\n query: session.query,\n refresh:\n continuation.gap && refresh === 'bounded-eose' ? 'partial' : refresh,\n available,\n rows: page.rows,\n listings: Array.from(listings.values()),\n hasMore: page.hasMore,\n continuation,\n scopes: sources,\n run,\n definitiveAbsence: false\n };\n}\n// Explicit auxiliary work for the current local page. Show more itself stays\n// local; snapshots never schedule profile transport or prompt a signer.\nexport function resolveFoodSearchPublishers(\n token: FoodSearchRun\n): readonly PublicRequest[] {\n const session = sessionOf(token);\n requireCurrent(session);\n const snapshot = foodSearchSnapshot(\n viewCoordinators.get(session.coordinator.view)!.token\n );\n requireCurrent(session);\n if (!snapshot?.available) throw new Error('food_search_unavailable');\n const run = foodSearchRequestOwner(token);\n const page = snapshot.rows.slice(\n (session.pages() - 1) * PUBLIC_SEARCH_BUDGETS.pageRows,\n session.pages() * PUBLIC_SEARCH_BUDGETS.pageRows\n );\n try {\n const requests = readPublisherPage(\n session.coordinator.publishers,\n run,\n page.map((row) => row.state.head.pubkey),\n session.pages()\n );\n for (const request of requests) session.track(request);\n requireCurrent(session);\n return requests;\n } catch (error) {\n if (current(session)) session.fail();\n throw error;\n }\n}\nexport function cancelFoodSearch(token: FoodSearchRun): void {\n const session = sessionOf(token);\n requireCurrent(session);\n session.cancel();\n}\nexport function closeFoodSearchCoordinator(\n coordinator: FoodSearchCoordinator\n): void {\n coordinatorOf(coordinator).close();\n}\n", + sha256: + 'e625fdaa5d2a698737491566e8e30f6ba3eb5c54a2573f7d0f204f15bcd0e36b' + }, + 'src/lib/catalog/search-view.ts': { + source: + "import type { PublicView } from '../runtime/public-runtime.ts';\nimport type { PublicHead } from './heads.ts';\nimport type { WallClock } from './clock-policy.ts';\nimport type { SearchSnapshot } from './search-state.ts';\nimport {\n createFoodSearchCoordinator,\n beginFoodSearch,\n sampleFoodSearch,\n chronologicalFoodSearch,\n foodSearchSnapshot,\n resolveFoodSearchPublishers,\n showMoreFoodSearch,\n searchOlderFoodSearch,\n closeFoodSearchCoordinator,\n type FoodSearchRun\n} from './search-run.ts';\nexport type SearchViewSnapshot = SearchSnapshot<FoodSearchRun>;\nexport type ForegroundSchedule = (\n callback: () => void,\n delay: number\n) => () => void;\ndeclare const viewBrand: unique symbol;\nexport type SearchView = Readonly<{ readonly [viewBrand]: true }>;\ninterface Owner {\n readonly start: (query: unknown, known: readonly PublicHead[]) => void;\n readonly more: () => void;\n readonly older: () => void;\n readonly snapshot: () => SearchViewSnapshot | undefined;\n readonly close: () => void;\n}\nconst owners = new WeakMap<SearchView, Owner>();\nfunction ownerOf(view: SearchView): Owner {\n const owner = owners.get(view);\n if (!owner) throw Error('search_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// This owner observes a finite public run; it never creates a background poll,\n// transport, shared cache or new deadline. Explicit actions alone restart runs.\nexport function createSearchView(\n view: PublicView,\n clock: WallClock,\n onUpdate: (value: SearchViewSnapshot) => void,\n schedule: ForegroundSchedule = foreground\n): SearchView {\n const coordinator = createFoodSearchCoordinator(view, clock);\n let generation: FoodSearchRun | undefined,\n cancel: (() => void) | undefined,\n closed = false;\n function stop() {\n const previous = cancel;\n cancel = undefined;\n previous?.();\n }\n function current(token: FoodSearchRun) {\n return !closed && generation === token;\n }\n function requireOpen() {\n if (closed) throw Error('search_view_closed');\n }\n function publish(token: FoodSearchRun) {\n const value = foodSearchSnapshot(coordinator);\n if (value && current(token) && value.generation === token) onUpdate(value);\n return value;\n }\n function queue(token: FoodSearchRun) {\n if (!current(token)) return;\n const value = foodSearchSnapshot(coordinator);\n if (!value?.run?.active || !current(token)) return;\n const pending = schedule(() => {\n if (!current(token)) return;\n cancel = undefined;\n observe(token);\n }, 250);\n if (current(token)) cancel = pending;\n else pending();\n }\n function observe(token: FoodSearchRun) {\n if (!current(token)) return;\n const value = foodSearchSnapshot(coordinator);\n if (!value || !current(token)) return;\n if (value.run?.active && value.available && value.listings.length) {\n try {\n resolveFoodSearchPublishers(token);\n } catch {\n /* Failed metadata retains key fallback and source uncertainty. */\n }\n }\n if (!current(token)) return;\n const updated = publish(token);\n if (updated?.run?.active && updated.run.activeRequests > 0) queue(token);\n }\n const token = Object.freeze({}) as SearchView;\n owners.set(token, {\n start(query, known) {\n requireOpen();\n // Coordinator validates the complete query and seeds before any effects;\n // a rejected edit cannot cancel a previously accepted foreground observer.\n const next = beginFoodSearch(coordinator, query, known);\n stop();\n generation = next;\n try {\n sampleFoodSearch(next);\n } catch {\n /* Retain ordinary chronological fallback. */\n }\n if (!current(next)) return;\n try {\n chronologicalFoodSearch(next);\n } catch {\n /* Snapshot reports the actual failed source; known rows survive. */\n }\n if (current(next)) {\n publish(next);\n queue(next);\n }\n },\n more() {\n requireOpen();\n if (!generation) throw Error('search_view_inactive');\n const next = generation;\n showMoreFoodSearch(next);\n stop();\n publish(next);\n queue(next);\n },\n older() {\n requireOpen();\n const next = searchOlderFoodSearch(coordinator);\n stop();\n generation = next;\n publish(next);\n queue(next);\n },\n snapshot: () => foodSearchSnapshot(coordinator),\n close() {\n closed = true;\n stop();\n closeFoodSearchCoordinator(coordinator);\n generation = undefined;\n }\n });\n return token;\n}\nexport function startSearchView(\n view: SearchView,\n query: unknown,\n known: readonly PublicHead[] = []\n): void {\n ownerOf(view).start(query, known);\n}\nexport function moreSearchView(view: SearchView): void {\n ownerOf(view).more();\n}\nexport function olderSearchView(view: SearchView): void {\n ownerOf(view).older();\n}\nexport function searchViewSnapshot(\n view: SearchView\n): SearchViewSnapshot | undefined {\n return ownerOf(view).snapshot();\n}\nexport function closeSearchView(view: SearchView): void {\n ownerOf(view).close();\n}\n", + sha256: + '398cc2db59fb78d33df8cb8ce59d4e10a84feb3842709f2a7047033424798768' + }, + 'src/lib/publishing/selling-view.ts': { + source: + "import {\n identityViewSession,\n identityViewMatchesOwner,\n subscribeIdentityView,\n type IdentityViewContext\n} from '../runtime/view-context.ts';\nimport { identitySessionSnapshot } from '../runtime/identity-session.ts';\nimport {\n openBrowserDatabase,\n closeBrowserDatabase,\n type BrowserDatabase\n} from '../persistence/database.ts';\nimport {\n createPublicPublicationRepository,\n publicPublicationDraftRepository,\n publicPublicationQuotaRepository,\n readPublicListingIntent\n} from '../persistence/public-publications.ts';\nimport { listPublicDrafts } from '../persistence/drafts.ts';\nimport {\n inspectPublicStorage,\n publicInventorySnapshot\n} from '../persistence/quota.ts';\nimport { publicRecordSnapshot } from '../persistence/records.ts';\nimport { inspectLocalTemplate } from '../nostr/local-template.ts';\nimport {\n verifyEnvelope,\n verifiedEnvelopeSnapshot\n} from '../nostr/verified-envelope.ts';\nimport { encodeProductReference } from '../nostr/references.ts';\nimport { internalHref } from '../navigation-url.ts';\nimport {\n projectFoodParts,\n type FoodProjection\n} from '../contracts/food-availability-v1/read.ts';\nimport {\n readListingOperationView,\n listingOperationSnapshot,\n closeListingOperationView,\n type ListingOperationView\n} from './listing-operation-view.ts';\nimport {\n openOwnedEditSource,\n ownedEditSourceSnapshot,\n closeOwnedEditSource\n} from './edit-source.ts';\nimport {\n createPublicView,\n beginPublicViewRun,\n subscribePublicView,\n disposePublicView,\n publicViewOwnsRun,\n publicViewProjectionAvailable,\n publicViewRunCurrent,\n type PublicRuntime,\n type PublicView\n} from '../runtime/public-runtime.ts';\nimport {\n createPublicHeadCandidate,\n publicHeadKey,\n publicHeadSnapshot,\n selectPublicHead,\n type PublicHead\n} from '../catalog/heads.ts';\nimport {\n createPublicViewHeadResolver,\n resolveHeads,\n headResolutionSnapshot,\n closeHeadResolver,\n type HeadResolver\n} from '../catalog/resolve-head.ts';\nimport {\n publicRequestScopeSnapshot,\n publicRunSnapshot,\n type PublicRequest,\n type PublicRun\n} from '../nostr/request-scope.ts';\nimport { PUBLIC_QUERY_BUDGETS } from '../config/budgets.ts';\n\ndeclare const viewBrand: unique symbol;\nexport type SellingView = Readonly<{ [viewBrand]: true }>;\nexport type SellingRow = Readonly<{\n key: string;\n title: string;\n status: string;\n provenance: string;\n href?: string;\n editHref?: string;\n draftHref?: string;\n operations: readonly ListingOperationView[];\n}>;\nexport type SellingSnapshot = Readonly<{\n attention: readonly SellingRow[];\n drafts: readonly SellingRow[];\n listings: readonly SellingRow[];\n remote: 'checking' | 'bounded' | 'partial' | 'unavailable';\n local: 'ready' | 'unavailable';\n}>;\ntype Controller = {\n snapshot(): SellingSnapshot | undefined;\n subscribe(listener: () => void): () => void;\n close(): void;\n};\ntype Group = {\n key: string;\n food: FoodProjection;\n createdAt: number;\n eventId: string;\n removal: boolean;\n operations: ListingOperationView[];\n attention: boolean;\n supportedEventId?: string;\n draftId?: string;\n};\nconst views = new WeakMap<SellingView, Controller>();\nconst active = new WeakMap<IdentityViewContext, Controller>();\n\n// Account-local presentation only. Neither a row, link nor operation disclosure\n// grants signing, delivery, adopted-source or current-head permission.\nexport async function openSellingView(\n context: IdentityViewContext,\n runtime?: PublicRuntime\n): Promise<SellingView | undefined> {\n const identity = identityViewSession(context);\n const observed = identity && identitySessionSnapshot(identity);\n const owner =\n observed && 'publicKey' in observed ? observed.publicKey : undefined;\n if (!identity || !owner || !identityViewMatchesOwner(context, owner)) return;\n active.get(context)?.close();\n let alive = true,\n database: BrowserDatabase | undefined;\n let publicView: PublicView | undefined, run: PublicRun | undefined;\n let resolver: HeadResolver | undefined, discovery: PublicRequest | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let offIdentity = () => {};\n let local: SellingSnapshot['local'] = 'unavailable';\n let remote: SellingSnapshot['remote'] = runtime ? 'checking' : 'unavailable';\n const listeners = new Map<symbol, () => void>();\n const groups = new Map<string, Group>();\n const draftRows = new Map<string, SellingRow>();\n let operationViews = Array.from<ListingOperationView>([]);\n const heads = new Map<string, PublicHead>();\n const linkedDrafts = new Map<string, true>();\n const current = () =>\n alive &&\n active.get(context) === controller &&\n identityViewSession(context) === identity &&\n identityViewMatchesOwner(context, owner);\n function notify() {\n for (const listener of listeners.values()) {\n try {\n listener();\n } catch {\n /* Presentation cannot interrupt owned cleanup. */\n }\n }\n }\n function close() {\n if (!alive) return;\n alive = false;\n offIdentity();\n if (timer !== undefined) clearTimeout(timer);\n for (const view of operationViews) closeListingOperationView(view);\n try {\n if (resolver) closeHeadResolver(resolver);\n } finally {\n try {\n if (publicView) disposePublicView(publicView);\n } finally {\n if (database) closeBrowserDatabase(database);\n }\n }\n if (active.get(context) === controller) active.delete(context);\n groups.clear();\n draftRows.clear();\n heads.clear();\n notify();\n listeners.clear();\n }\n const hrefFor = (identifier: string) => {\n const naddr = encodeProductReference({\n kind: 30402,\n pubkey: owner,\n identifier\n });\n return naddr ? internalHref(`/products/${naddr}`) : undefined;\n };\n function snapshot(): SellingSnapshot | undefined {\n if (!current()) return;\n let attention = Array.from<SellingRow>([]),\n listings = Array.from<SellingRow>([]);\n const rows =\n resolver &&\n publicView &&\n run &&\n publicViewOwnsRun(publicView, run) &&\n publicViewProjectionAvailable(publicView)\n ? headResolutionSnapshot(resolver)\n : [];\n const remoteByIdentifier = new Map(\n rows.map((row) => [row.state.head.identifier, row])\n );\n for (const group of groups.values()) {\n const known = remoteByIdentifier.get(group.food.identifier);\n const food = known?.state.food ?? group.food;\n const suppressed = known?.deletion.outcome === 'suppressed';\n const href = hrefFor(food.identifier);\n const canEdit = !!(\n href &&\n group.supportedEventId &&\n !group.removal &&\n !suppressed &&\n (!known ||\n (known.state.head.id === group.supportedEventId &&\n known.state.display === 'focused_known'))\n );\n const row: SellingRow = {\n key: group.key,\n title: food.title,\n status: group.removal\n ? 'Removal request retained locally'\n : suppressed\n ? 'Listing no longer shown; delivery records retained'\n : known?.state.food\n ? food.status === 'sold'\n ? 'Marked sold'\n : 'Marked available'\n : 'Saved public operation; current availability unconfirmed',\n provenance: 'Local publication evidence \u00b7 Remote discovery is bounded',\n ...(href ? { href } : {}),\n ...(canEdit ? { editHref: internalHref(`${href}/edit`) } : {}),\n ...(group.attention &&\n group.draftId &&\n draftRows.get(group.draftId)?.draftHref\n ? { draftHref: draftRows.get(group.draftId)?.draftHref }\n : {}),\n operations: group.operations.slice()\n };\n if (group.attention) attention = attention.concat(row);\n else listings = listings.concat(row);\n remoteByIdentifier.delete(group.food.identifier);\n }\n for (const row of remoteByIdentifier.values()) {\n if (\n !row.state.food ||\n row.state.head.pubkey !== owner ||\n row.state.display !== 'focused_known' ||\n row.deletion.outcome === 'suppressed'\n )\n continue;\n const href = hrefFor(row.state.food.identifier);\n if (!href) continue;\n listings = listings.concat({\n key: row.key,\n title: row.state.food.title,\n status:\n row.state.food.status === 'sold' ? 'Marked sold' : 'Marked available',\n provenance:\n 'Bounded remote discovery \u00b7 Read-only; no supported retained prototype source',\n href,\n operations: []\n });\n }\n return {\n attention,\n drafts: Array.from(draftRows, ([id, row]) =>\n linkedDrafts.has(id) ? undefined : row\n ).filter((row): row is SellingRow => !!row),\n listings,\n local,\n remote\n };\n }\n const controller: Controller = {\n snapshot,\n subscribe(listener) {\n const stamp = Symbol();\n listeners.set(stamp, listener);\n return () => {\n listeners.delete(stamp);\n };\n },\n close\n };\n active.set(context, controller);\n offIdentity = subscribeIdentityView(context, () => {\n if (!current()) close();\n });\n try {\n const opened = await openBrowserDatabase();\n if (opened.state !== 'ready') {\n close();\n return;\n }\n if (!current()) {\n closeBrowserDatabase(opened.owner);\n close();\n return;\n }\n database = opened.owner;\n const repository = createPublicPublicationRepository(database, owner);\n const drafts = repository && publicPublicationDraftRepository(repository);\n const quota = repository && publicPublicationQuotaRepository(repository);\n if (!repository || !drafts || !quota) {\n close();\n return;\n }\n const saved = await listPublicDrafts(drafts);\n if (!current() || !saved.ok) {\n close();\n return;\n }\n for (const draft of saved.value) {\n const href = internalHref(`/selling/drafts/${draft.id}`);\n if (href)\n draftRows.set(draft.id, {\n key: `draft:${draft.id}`,\n title: draft.form.title || 'Untitled draft',\n status: 'Saved in this browser \u00b7 Not published',\n provenance: 'Local draft',\n draftHref: href,\n operations: []\n });\n }\n const inspected = await inspectPublicStorage(quota);\n if (!current() || !inspected.ok) {\n close();\n return;\n }\n const inventory = publicInventorySnapshot(quota, inspected.value);\n if (!inventory) {\n close();\n return;\n }\n for (const item of inventory.rows) {\n if (item.family !== 'public_operation') continue;\n const read = await readPublicListingIntent(repository, item.id);\n if (!current() || read.status !== 'found') {\n close();\n return;\n }\n const record = publicRecordSnapshot(read.record, owner, item.id);\n if (!record || record.family !== 'public_operation') {\n close();\n return;\n }\n if (record.capture.kind !== 30402 && record.capture.kind !== 5) continue;\n const template = inspectLocalTemplate(\n record.capture.wire,\n owner,\n record.capture.kind\n );\n const base =\n record.capture.kind === 5 && record.source.type === 'public_head'\n ? verifyEnvelope(record.source.wire)\n : undefined;\n const source = base?.ok ? verifiedEnvelopeSnapshot(base.value) : template;\n const projected = source && projectFoodParts(source);\n if (!template || !projected || projected.outcome !== 'focused') continue;\n const key = JSON.stringify([\n 30402,\n owner,\n projected.projection.identifier\n ]);\n const presented = await readListingOperationView(\n repository,\n identity,\n item.id\n );\n if (!current() || presented.status !== 'found') {\n if (presented.status === 'found')\n closeListingOperationView(presented.view);\n close();\n return;\n }\n operationViews = operationViews.concat(presented.view);\n const facts = listingOperationSnapshot(presented.view);\n if (!facts) {\n close();\n return;\n }\n let group = groups.get(key);\n if (!group) {\n group = {\n key,\n food: projected.projection,\n createdAt: template.created_at,\n eventId: record.capture.hash,\n removal: template.kind === 5,\n attention: false,\n operations: [],\n ...(record.source.type === 'draft'\n ? { draftId: record.source.id }\n : {})\n };\n groups.set(key, group);\n }\n if (\n template.created_at > group.createdAt ||\n (template.created_at === group.createdAt &&\n record.capture.hash < group.eventId)\n ) {\n group = {\n ...group,\n food: projected.projection,\n createdAt: template.created_at,\n eventId: record.capture.hash,\n removal: template.kind === 5,\n ...(record.source.type === 'draft'\n ? { draftId: record.source.id }\n : {})\n };\n }\n group = {\n ...group,\n operations: group.operations.concat(presented.view),\n attention:\n group.attention ||\n facts.needsAction ||\n !record.artifact ||\n facts.targets.some(\n (target) => !target.accepted || target.readback !== 'confirmed'\n )\n };\n groups.set(key, group);\n const capturedSource = record.source;\n if (\n capturedSource.type === 'draft' &&\n saved.value.some(\n (draft) =>\n draft.id === capturedSource.id &&\n draft.revision === capturedSource.revision\n )\n )\n linkedDrafts.set(capturedSource.id, true);\n if (record.artifact && record.capture.kind === 30402) {\n const proof = verifyEnvelope(record.artifact.wire);\n const head = proof.ok && createPublicHeadCandidate(proof.value);\n if (head) {\n const prior = heads.get(publicHeadKey(head));\n heads.set(publicHeadKey(head), selectPublicHead(prior, head).head);\n }\n }\n }\n // Reuse the original retained-source verifier without starting a network\n // run or adopting a remote source. Edit's route performs its own fresh\n // independent current-head checks; this metadata grants no effect custody.\n for (const group of groups.values()) {\n if (group.attention && group.draftId && draftRows.has(group.draftId))\n linkedDrafts.set(group.draftId, true);\n const naddr = encodeProductReference({\n kind: 30402,\n pubkey: owner,\n identifier: group.food.identifier\n });\n const source =\n naddr && (await openOwnedEditSource(repository, context, naddr));\n if (!current()) {\n if (source) closeOwnedEditSource(source);\n close();\n return;\n }\n const supported = source ? ownedEditSourceSnapshot(source) : undefined;\n if (supported)\n groups.set(group.key, {\n ...group,\n supportedEventId: supported.sourceEventId\n });\n if (source) closeOwnedEditSource(source);\n }\n local = 'ready';\n if (runtime) {\n try {\n publicView = createPublicView(runtime);\n run = beginPublicViewRun(publicView);\n resolver = createPublicViewHeadResolver(publicView, run, {\n nowSeconds: () => Math.floor(Date.now() / 1000)\n });\n discovery = subscribePublicView(\n publicView,\n run,\n 'head',\n [\n {\n kinds: [30402],\n authors: [owner],\n limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay\n }\n ],\n (proof) => {\n if (!current()) return;\n const head = createPublicHeadCandidate(proof);\n if (!head || publicHeadSnapshot(head).pubkey !== owner) return;\n const key = publicHeadKey(head);\n if (\n !heads.has(key) &&\n heads.size >= PUBLIC_QUERY_BUDGETS.coordinatesPerRun\n )\n return;\n heads.set(key, selectPublicHead(heads.get(key), head).head);\n }\n );\n function observe() {\n if (!current()) return;\n if (\n !publicView ||\n !run ||\n !resolver ||\n !discovery ||\n !publicViewOwnsRun(publicView, run) ||\n !publicViewProjectionAvailable(publicView)\n ) {\n remote = 'unavailable';\n notify();\n return;\n }\n try {\n if (publicViewRunCurrent(publicView, run))\n resolveHeads(\n resolver,\n Array.from(heads.values()).slice(\n 0,\n PUBLIC_QUERY_BUDGETS.coordinatesPerRun\n )\n );\n const rows = headResolutionSnapshot(resolver);\n const source = publicRequestScopeSnapshot(discovery);\n remote =\n source.state === 'eose' &&\n source.result.coverage === 'bounded-eose' &&\n rows.every((row) => row.coverage === 'bounded-eose')\n ? 'bounded'\n : publicRunSnapshot(run).activeRequests > 0\n ? 'checking'\n : 'partial';\n } catch {\n remote = 'partial';\n }\n notify();\n if (\n current() &&\n publicRunSnapshot(run).active &&\n publicRunSnapshot(run).activeRequests > 0\n )\n timer = setTimeout(observe, 250);\n }\n observe();\n } catch {\n remote = 'unavailable';\n }\n }\n if (!current()) {\n close();\n return;\n }\n const token = Object.freeze({}) as SellingView;\n views.set(token, controller);\n return token;\n } catch {\n close();\n return;\n }\n}\nexport function sellingViewSnapshot(\n view: SellingView\n): SellingSnapshot | undefined {\n return views.get(view)?.snapshot();\n}\nexport function subscribeSellingView(\n view: SellingView,\n listener: () => void\n): () => void {\n return views.get(view)?.subscribe(listener) ?? (() => {});\n}\nexport function closeSellingView(view: SellingView): void {\n views.get(view)?.close();\n}\n", + sha256: + 'a9e896db6f0485699c069ee31eb20a6c5476095d0ffef1160aa76cc64a364dc2' + }, + 'src/routes/+layout.svelte': { + source: + "<script lang=\"ts\">\n import '../theme.css';\n import '../app.css';\n import { onMount, setContext, type Snippet } from 'svelte';\n import {\n createPublicRuntimeContext,\n mountPublicRuntime,\n closePublicRuntime,\n PUBLIC_RUNTIME_CONTEXT\n } from '../lib/runtime/public-runtime.ts';\n import { page } from '$app/state';\n import AppShell from '../lib/components/AppShell.svelte';\n import {\n createIdentityViewContext,\n IDENTITY_VIEW_CONTEXT,\n identityViewSnapshot,\n mountIdentityView,\n subscribeIdentityView,\n connectIdentityView,\n disconnectIdentityView,\n closeIdentityView,\n invalidateIdentityView\n } from '../lib/runtime/view-context.ts';\n const identityContext = createIdentityViewContext();\n setContext(IDENTITY_VIEW_CONTEXT, identityContext);\n let identityView = $state(identityViewSnapshot(identityContext));\n $effect(() => {\n if (page.url.pathname) invalidateIdentityView(identityContext);\n });\n function connect() {\n return connectIdentityView(identityContext);\n }\n function disconnect() {\n disconnectIdentityView(identityContext);\n }\n const shellIdentity = $derived(\n identityView.identity.state === 'guest' ||\n identityView.identity.state === 'pending'\n ? {\n kind: 'guest' as const,\n onconnect: identityView.mounted ? connect : undefined\n }\n : {\n kind: 'connected' as const,\n publicKey: identityView.identity.publicKey,\n ondisconnect: disconnect\n }\n );\n\n const publicContext = createPublicRuntimeContext();\n setContext(PUBLIC_RUNTIME_CONTEXT, publicContext);\n onMount(() => {\n mountPublicRuntime(publicContext);\n return () => closePublicRuntime(publicContext);\n });\n onMount(() => {\n const off = subscribeIdentityView(identityContext, (next) => {\n identityView = next;\n });\n mountIdentityView(identityContext);\n return () => {\n off();\n closeIdentityView(identityContext);\n };\n });\n\n let { children }: { children: Snippet } = $props();\n</script>\n\n<AppShell\n identity={shellIdentity}\n capability={identityView.identity}\n ondisconnect={disconnect}\n currentPath={page.url.pathname}\n availableRoutes={[\n '/search',\n '/sell',\n '/selling',\n '/messages',\n '/about',\n '/privacy'\n ]}\n>\n {@render children()}\n</AppShell>\n", + sha256: + 'b935e9c00c736107139d37020cf9590f2e51440991ac89c2eb47bba1aabe13a2' + }, + '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 import ProductEnquiry from '../../../lib/components/ProductEnquiry.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 let productOwner = $state.raw<ProductView | 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 productOwner = 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 productOwner = owner;\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'} \u2014 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\u2026\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 {/if}\n {#if productOwner}<ProductEnquiry\n view={productOwner}\n observation={result}\n />{/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: + 'e63a2c8b3833966a36e4d97aef7726ff3d087703cc9b475e7f52f5478fed5ce7' + }, + 'src/routes/privacy/+page.svelte': { + source: + '<svelte:head><title>Privacy \u2014 HarvestCircle</title></svelte:head>\n<div class="page page--reading stack">\n <h1>Privacy</h1>\n <p class="notice">Privacy information is unavailable during development.</p>\n</div>\n', + sha256: + '1766ce7a732264f24a82b3a7a1e999a3496cc57af8ce3f9624a32c8c37527454' + } + }, ...historicalPublicProducerClosure, ...historicalWithdrawalProducerClosure, 'src/routes/selling/+page.svelte': { @@ -589,7 +645,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, 53); + assert.equal(files.length, 54); // 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( @@ -873,10 +929,36 @@ 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, 53); + assert.equal((await f.audit()).length, 54); } ); + for (const comment of [ + '/*#__PURE__*/', + '/*@vite-ignore*/', + '/*webpackChunkName: "hidden"*/', + '// ordinary line comment\n' + ]) + await check( + 'root rejects trailing annotation or unsupported trivia ' + comment, + async (t) => { + const f = await fixture(t); + const file = path.join(f.web, 'src/routes/+layout.svelte'); + const root = await readFile(file, 'utf8'); + const changed = root.replace( + '</script>', + comment + '\n</script>' + ); + assert.notEqual(changed, root); + await writeFile(file, changed); + await refresh(f); + await assert.rejects( + f.audit, + /Invalid owned root runtime activation/ + ); + } + ); + for (const mutation of [ 'unknown-name', 'missing-references', @@ -1030,10 +1112,15 @@ import { auditOutput } from '../../tools/check-output.mjs'; 'otherMount(publicContext)' ); if (mutation === 'missing-cleanup') - layout = layout.replace( - 'return () => closePublicRuntime(publicContext);', - 'return () => {};' - ); + layout = layout.includes('closeLocalPublicHides(publicHides)') + ? layout.replace( + ' closePublicRuntime(publicContext);', + '' + ) + : layout.replace( + 'return () => closePublicRuntime(publicContext);', + 'return () => {};' + ); if (mutation === 'missing-context') layout = layout.replace( 'setContext(PUBLIC_RUNTIME_CONTEXT, publicContext);', @@ -1044,9 +1131,17 @@ import { auditOutput } from '../../tools/check-output.mjs'; 'closePublicRuntime(publicContext)', 'closePublicRuntime({})' ); + assert.notEqual( + layout, + await readFile(file, 'utf8'), + 'Actual hostile root mutation must change the source' + ); await writeFile(file, layout); await refresh(f); - await assert.rejects(f.audit, /compiler|runtime/i); + await assert.rejects( + f.audit, + /compiler|runtime|Invalid owned listing editor source/i + ); } ); for (const mutation of [ @@ -1471,7 +1566,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; await refresh(f); await assert.rejects( f.audit, - /Invalid owned listing editor source/ + /Invalid owned listing editor source|Invalid owned public hiding source/ ); } ); @@ -1493,7 +1588,37 @@ import { auditOutput } from '../../tools/check-output.mjs'; await refresh(f); await assert.rejects( f.audit, - /Invalid owned selling workspace source/ + /Invalid owned selling workspace source|Invalid owned public hiding source/ + ); + } + ); + } + for (const producer of [ + 'src/lib/runtime/identity-session.ts', + 'src/lib/persistence/local-public-hides.ts', + 'src/lib/runtime/public-runtime.ts', + 'src/lib/catalog/product-view.ts', + 'src/lib/catalog/search-run.ts', + 'src/lib/catalog/search-view.ts', + 'src/lib/publishing/selling-view.ts', + 'src/routes/+layout.svelte', + 'src/routes/products/[naddr=naddr]/+page.svelte', + 'src/routes/privacy/+page.svelte', + 'src/lib/components/PublisherHide.svelte' + ]) { + await check( + 'public hiding 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// public hiding source mutation\n' + ); + await refresh(f); + await assert.rejects( + f.audit, + /Invalid owned (public hiding source|root runtime activation)/ ); } ); @@ -1516,7 +1641,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; await refresh(f); await assert.rejects( f.audit, - /Invalid owned listing editor activation/ + /Invalid owned listing editor activation|Invalid owned public hiding source/ ); } ); @@ -1552,8 +1677,8 @@ import { auditOutput } from '../../tools/check-output.mjs'; await assert.rejects( f.audit, producer === 'src/lib/runtime/public-runtime.ts' - ? /Invalid owned (product presentation|listing editor) source/ - : /Invalid owned product presentation source/ + ? /Invalid owned (product presentation|listing editor) source|Invalid owned public hiding source/ + : /Invalid owned product presentation source|Invalid owned public hiding source/ ); } ); @@ -1731,7 +1856,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; await refresh(f); await assert.rejects( f.audit, - /Invalid owned search presentation source/ + /Invalid owned search presentation source|Invalid owned public hiding source/ ); } ); @@ -2349,13 +2474,9 @@ import { auditOutput } from '../../tools/check-output.mjs'; async (t) => { ready(t); const layout = path.join(base, 'web/src/routes/+layout.svelte'); - await writeFile( - layout, - (await readFile(layout, 'utf8')).replace( - '<script lang="ts">', - "<script lang=\"ts\">\n import '../theme.css';\n import '../app.css';" - ) - ); + const root = await readFile(layout, 'utf8'); + assert.equal(root.split("import '../theme.css';").length - 1, 1); + assert.equal(root.split("import '../app.css';").length - 1, 1); await writeFile( path.join(base, 'web/src/theme.css'), ':root { --hc-accent: #336633; }\n' diff --git a/web/tests/unit/public-hides.test.ts b/web/tests/unit/public-hides.test.ts @@ -0,0 +1,53 @@ +import { expect, test } from 'vitest'; +import { + createLocalPublicHides, + localPublicHidesSnapshot, + localPublicPublisherAllowed, + hideLocalPublicPublisher, + undoLocalPublicPublisher, + closeLocalPublicHides, + type LocalPublicHides +} from '../../src/lib/persistence/local-public-hides.ts'; +import { createIdentityViewContext } from '../../src/lib/runtime/view-context.ts'; +import type { VerifiedEnvelope } from '../../src/lib/nostr/verified-envelope.ts'; + +test('SSR construction exposes no owner inventory and acquires no storage', () => { + const hides = createLocalPublicHides(createIdentityViewContext()); + expect(localPublicHidesSnapshot(hides)).toEqual({ state: 'guest' }); + expect(localPublicPublisherAllowed(hides, 'a'.repeat(64))).toBe(true); + closeLocalPublicHides(hides); +}); + +for (const copied of [undefined, null, {}, { state: 'ready', publishers: [] }]) + test(`copied local hide token has no account custody: ${JSON.stringify(copied)}`, async () => { + const token = copied as LocalPublicHides; + expect(localPublicHidesSnapshot(token)).toEqual({ state: 'unavailable' }); + expect(localPublicPublisherAllowed(token, 'a'.repeat(64))).toBe(false); + expect( + await hideLocalPublicPublisher( + token, + {} as VerifiedEnvelope, + 'reviewed_local_public_hide' + ) + ).toEqual({ status: 'invalid' }); + expect( + await undoLocalPublicPublisher( + token, + 'a'.repeat(64), + 'reviewed_local_public_undo' + ) + ).toEqual({ status: 'invalid' }); + expect(() => closeLocalPublicHides(token)).not.toThrow(); + }); + +test('a connected-looking render snapshot cannot substitute for a verified publisher', async () => { + const hides = createLocalPublicHides(createIdentityViewContext()); + expect( + await hideLocalPublicPublisher( + hides, + { pubkey: 'a'.repeat(64) } as unknown as VerifiedEnvelope, + 'reviewed_local_public_hide' + ) + ).toEqual({ status: 'invalid' }); + closeLocalPublicHides(hides); +}); diff --git a/web/tests/unit/route-inventory.test.ts b/web/tests/unit/route-inventory.test.ts @@ -150,12 +150,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 [About, Privacy]) { - const output = render(component); - expect(output.body).toContain('unavailable during development.'); + for (const output of [render(About), render(Privacy)]) { expect(output.body).not.toMatch(/<form|<textarea|<input|mailto:|tel:/); expect(output.head).not.toContain('noindex'); } + expect(render(About).body).toContain('unavailable during development.'); + expect(render(Privacy).body).toContain('Hiding a publisher is local'); + expect(render(Privacy).body.replace(/\s+/g, ' ')).toContain( + 'Guest browsing does not expose an account inventory' + ); + expect(render(Privacy).body).not.toMatch(/Undo hide|[0-9a-f]{64}/); expect(render(About).body).toContain('id="help"'); const details = render(Product); expect(details.body).toContain('This food reference is invalid.'); diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs @@ -166,10 +166,172 @@ function objectKeys(value, keys) { } const sdkNegentropy = 'node_modules/.pnpm/applesauce-relay@6.2.1_typescript@6.0.3/node_modules/applesauce-relay/dist/negentropy.js'; +// Keep every root byte except ordinary trailing instance-script trivia. This +// preserves the owned reader-boundary positive without erasing annotations, +// changing executable source, or normalizing the template or script attributes. +/** @param {Buffer} bytes */ +export function publicHideRootIdentity(bytes) { + const layout = publicText(bytes); + const component = parseSvelte(layout); + if (!component.instance || component.module) + throw new Error('Invalid owned root runtime activation'); + const { start, end } = component.instance.content; + const script = layout.slice(start, end); + const source = ts.createSourceFile( + 'root.ts', + script, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TS + ); + /** @type {unknown} */ + const diagnostics = Reflect.get(source, 'parseDiagnostics'); + if ( + !Array.isArray(diagnostics) || + diagnostics.length || + !source.statements.length + ) + throw new Error('Invalid owned root runtime activation'); + const last = source.statements[source.statements.length - 1].end; + const scanner = ts.createScanner( + ts.ScriptTarget.Latest, + false, + ts.LanguageVariant.Standard, + script.slice(last) + ); + for ( + let token = scanner.scan(); + token !== ts.SyntaxKind.EndOfFileToken; + token = scanner.scan() + ) { + if ( + token === ts.SyntaxKind.WhitespaceTrivia || + token === ts.SyntaxKind.NewLineTrivia + ) + continue; + if ( + token !== ts.SyntaxKind.MultiLineCommentTrivia || + !scanner.getTokenText().endsWith('*/') || + /[@#<]|PURE|NO_SIDE_EFFECTS|vite|webpack|sourceMappingURL|sourceURL/.test( + scanner.getTokenText() + ) + ) + throw new Error('Invalid owned root runtime activation'); + } + return createHash('sha256') + .update( + JSON.stringify([ + layout.slice(0, start), + script.slice(0, last), + layout.slice(end) + ]) + ) + .digest('hex'); +} // Compiler admission follows actual root bindings, never copied files or text // matches. This is the deliberately fixed lifecycle shape owned by HCP032. /** @param {string} web */ +async function publicHidingAdmission(web) { + const root = publicText(await readOwned(web, 'src/routes/+layout.svelte')); + if (!root.includes('../lib/persistence/local-public-hides.ts')) return false; + /** @type {Record<string,string>} */ + const producers = { + 'src/routes/sell/+page.svelte': + '97f22f9a0309621e9acb5f1b328d3376bc9c5affbe5a7ea1b85ece76097b9c08', + 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte': + '1df59a753fbef2bc2ebf77890a79cbd3d7a5bb0dcef34c219df1b5e8043cf787', + 'src/routes/products/[naddr=naddr]/edit/+page.svelte': + '09c3a6bde766045319cd36a00a82ca565f9f3b5cd5322982be9482836f312998', + 'src/lib/components/ListingEditor.svelte': + '060f4863f6f4f2a4fb1471bb0d5eeedf31ab13b5c83d894f47757cf5a68099e6', + 'src/lib/publishing/listing-editor.ts': + 'fe067bc1609f783aeee8ad5a0f3178cff50cae81085377b2bbec7874b5f4349d', + 'src/lib/components/ListingReview.svelte': + 'deee41ca6c60b346afc7ed5e62e3101ee03b04fdd2a9aa8fa3f3dec585e3863b', + 'src/lib/publishing/editor-workflow.ts': + 'c87e4f46793fd9beeedb5027cdbb06d533cf7e5df7378c030355c4608738e0f6', + 'src/lib/components/ConflictNotice.svelte': + 'f0a71cab9e8f1f12a3421402e3bc3b2f96c2ddb35ad8949c6e9599b850c3a17c', + 'src/lib/publishing/edit-source.ts': + '1432a8ada3d822cc9f634d40a7847a4d6d02c202ecfe59a9634543d57202f56b', + 'src/lib/publishing/prepare-listing.ts': + '00b922e8b0bfc73cf5ac59857472e8dd627c8df62d28f1c646c5d7c76ce5ede9', + 'src/lib/publishing/new-listing-readiness.ts': + 'ba76be4d7309b1a6beb0c8e0f19b89f2595049e94709486b79eff38953e68893', + 'src/lib/runtime/public-runtime.ts': + '679aa4cd51a1dfdc81459bdfccb29441ac60edfa8b1ddd579425787c85b5cff4', + 'src/lib/persistence/public-publications.ts': + 'be99c4114fb32880e0a9b48ab3593645532853fb4166fb506f398416db41a194', + 'src/lib/persistence/quota.ts': + 'e261a7c9c81d0685021663639b1bb543192e65580edb64fa58ccbb9a4a04cc95', + 'src/lib/publishing/revise-listing.ts': + '1f03d43f460feb12a02489226131ec2f7b95df5f534fcbb0b49ccc686a1b0c06', + 'src/lib/publishing/mark-sold.ts': + '80beaf8ad38b396154d5556e50e2cf5cd9f327bcdbc05f0db1ce190bf29f7234', + 'src/lib/components/ConfirmPanel.svelte': + '9e25745303bdf408a14df5153a28e9579bfa019ab083225acb7d874e93a17d59', + 'src/lib/nostr/listing-publisher.ts': + '10032c32482a766158d8a69027056e6a822a16b5f68ab9754b0f1cf42d0608f9', + 'src/lib/publishing/withdraw-listing.ts': + '168064a7ce271f8342c7b7cbbf996bd96f8968e405eee0bb3e3dba1bdaf346fb', + 'src/lib/publishing/sign-listing.ts': + 'a1c123c40a190699b57378c5569fcbbfbc5e23ab4d4c0df499ca40ff82fe1a10', + 'src/lib/persistence/artifact-records.ts': + 'e3b235c5aaf19558b557feb6e17a35b2b1de39c1aa49cb2ef14084d670138d16', + 'src/lib/publishing/listing-operation-view.ts': + '07f94625c0231a62f25c1db98c9459f8939c32505453633b58d2f72a894858ce', + 'src/lib/components/OperationStatus.svelte': + 'ca3a007899996f6331fadd2ead4c55dc7116c273626ecd2f36bcd4701065ae5f', + 'src/lib/runtime/effect-ownership.ts': + 'a181d1fa8b18d45b3e143de19af4dfdaab91779ac44df972d22e7fada645778b', + 'src/lib/nostr/public-pool.ts': + '220b0b9ca0cea20c1a2e1a08a82fc4b68a1ba4dd6ffff1f45154b54735233806', + 'src/lib/persistence/public-receipts.ts': + '10743a9d855c4f573eb42ca90a13c550dee9620e4ad3aac322858c696152e564', + 'src/routes/selling/+page.svelte': + '65d982bdf3f625a38b6c886a31a2a699c92e9231636debc16d501e78d7c8faa0', + 'src/lib/components/SellingRow.svelte': + 'ce00de1bd033860b9c0a85a49c90c8a4d5b8a8223cfd5c0872572e548e79331d', + 'src/lib/publishing/selling-view.ts': + '7d1f07c5b128512d3ed19a73409f1c64ada9988d77ac9bf60799352261797f5b', + 'src/lib/runtime/identity-session.ts': + '7d665f6872bdc780f1f2b56245730adcc90f32cf1fed6997f7e2e44ea2447b49', + 'src/lib/persistence/local-public-hides.ts': + '4f0e64ed0fabbe9f86014a0512e7dbd3c81711f28ca2c626e2dafa5cda349f83', + 'src/lib/catalog/product-view.ts': + '3558230c9f7cd17666e27c032de4ba6f30d2fb6b4d54149a69e5b8f5dc5d5363', + 'src/lib/catalog/search-run.ts': + '213a58cf897456a0dc0e99e46594cba013952ff08212802fb471f0d323c38573', + 'src/lib/catalog/search-view.ts': + 'bc4d0160574084a547d54d5ca582b15382f44d4649c255743ebdb4c8b398f795', + 'src/routes/+layout.svelte': + '969a6cd6e25c3da845e897b68298800079b9e5caa8fff5967ed4d231b28b1523', + 'src/routes/products/[naddr=naddr]/+page.svelte': + 'd3afe029ad6ed6384a300ad6719f32c324a1841271eddf9baee5b8f31f54e680', + 'src/routes/privacy/+page.svelte': + '48a01a3fba97ae6a21a5bf20383d42fd67fb8e5320bd35b266a4d9c771dccad7', + 'src/lib/components/PublisherHide.svelte': + '0fa30a68b44e9de68c3bb1edc9ed2c7fedefc2dc8a916c0a1df1f15440248927' + }; + for (const [name, pin] of Object.entries(producers)) { + const bytes = await readOwned(web, name); + publicText(bytes); + const identity = + name === 'src/routes/+layout.svelte' + ? publicHideRootIdentity(bytes) + : createHash('sha256').update(bytes).digest('hex'); + if (identity !== pin) + throw new Error( + name === 'src/routes/+layout.svelte' + ? 'Invalid owned root runtime activation' + : 'Invalid owned public hiding source' + ); + } + return true; +} +/** @param {string} web */ async function hasOwnedPublicRuntime(web) { + const hasHiding = await publicHidingAdmission(web); const layout = publicText(await readOwned(web, 'src/routes/+layout.svelte')); const component = parseSvelte(layout); if (!component.instance) return false; @@ -204,7 +366,8 @@ async function hasOwnedPublicRuntime(web) { 'createPublicRuntimeContext', 'mountPublicRuntime', 'closePublicRuntime', - 'PUBLIC_RUNTIME_CONTEXT' + 'PUBLIC_RUNTIME_CONTEXT', + ...(hasHiding ? ['bindPublicRuntimeHides'] : []) ] ], ['svelte', ['onMount', 'setContext']] @@ -227,6 +390,13 @@ async function hasOwnedPublicRuntime(web) { 'closeIdentityView', 'invalidateIdentityView' ]); + if (hasHiding) + required.set('../lib/persistence/local-public-hides.ts', [ + 'createLocalPublicHides', + 'mountLocalPublicHides', + 'closeLocalPublicHides', + 'LOCAL_PUBLIC_HIDES_CONTEXT' + ]); const allowedImports = new Set(); for (const [module, names] of required) { const declarations = imports.filter( @@ -267,7 +437,20 @@ async function hasOwnedPublicRuntime(web) { printer.printNode(ts.EmitHint.Unspecified, node, file); const expected = ts.createSourceFile( 'expected.ts', - ` + hasHiding + ? ` + const publicContext = createPublicRuntimeContext(); + setContext(PUBLIC_RUNTIME_CONTEXT, publicContext); + onMount(() => { + const runtime = mountPublicRuntime(publicContext); + if(runtime) bindPublicRuntimeHides(runtime,publicHides); + void mountLocalPublicHides(publicHides); + return () => { + closeLocalPublicHides(publicHides); + closePublicRuntime(publicContext); + }; + });` + : ` const publicContext = createPublicRuntimeContext(); setContext(PUBLIC_RUNTIME_CONTEXT, publicContext); onMount(() => { @@ -294,6 +477,7 @@ async function hasOwnedPublicRuntime(web) { 'identity-expected.ts', ` const identityContext = createIdentityViewContext(); + ${hasHiding ? 'const publicHides = createLocalPublicHides(identityContext); setContext(LOCAL_PUBLIC_HIDES_CONTEXT, publicHides);' : ''} setContext(IDENTITY_VIEW_CONTEXT, identityContext); let identityView = $state(identityViewSnapshot(identityContext)); $effect(() => { @@ -360,6 +544,7 @@ async function hasOwnedPublicRuntime(web) { ...(hasIdentity ? [ 'identityContext', + ...(hasHiding ? ['publicHides'] : []), 'identityView', 'connect', 'disconnect', @@ -497,6 +682,13 @@ async function productPresentationAdmission(web) { if ( createHash('sha256').update(bytes).digest('hex') !== pin && !( + [ + 'src/routes/products/[naddr=naddr]/+page.svelte', + 'src/lib/catalog/product-view.ts', + 'src/lib/runtime/public-runtime.ts' + ].includes(name) && (await publicHidingAdmission(web)) + ) && + !( name === 'src/lib/runtime/public-runtime.ts' && ((await listingEditorAdmission(web)) === 'owned-revision' || (await listingEditorAdmission(web)) === 'owned-withdrawal') @@ -531,7 +723,13 @@ async function searchPresentationAdmission(web) { for (const [name, pin] of Object.entries(producers)) { const bytes = await readOwned(web, name); publicText(bytes); - if (createHash('sha256').update(bytes).digest('hex') !== pin) + if ( + createHash('sha256').update(bytes).digest('hex') !== pin && + !( + ['src/lib/catalog/search-view.ts'].includes(name) && + (await publicHidingAdmission(web)) + ) + ) throw new Error('Invalid owned search presentation source'); } return true; @@ -679,7 +877,51 @@ async function sellingWorkspaceAdmission(web) { for (const [name, pin] of Object.entries(producers)) { const bytes = await readOwned(web, name); publicText(bytes); - if (createHash('sha256').update(bytes).digest('hex') !== pin) + if ( + createHash('sha256').update(bytes).digest('hex') !== pin && + !( + [ + 'src/routes/sell/+page.svelte', + 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte', + 'src/routes/products/[naddr=naddr]/edit/+page.svelte', + 'src/lib/components/ListingEditor.svelte', + 'src/lib/publishing/listing-editor.ts', + 'src/lib/components/ListingReview.svelte', + 'src/lib/publishing/editor-workflow.ts', + 'src/lib/components/ConflictNotice.svelte', + 'src/lib/publishing/edit-source.ts', + 'src/lib/publishing/prepare-listing.ts', + 'src/lib/publishing/new-listing-readiness.ts', + 'src/lib/runtime/public-runtime.ts', + 'src/lib/persistence/public-publications.ts', + 'src/lib/persistence/quota.ts', + 'src/lib/publishing/revise-listing.ts', + 'src/lib/publishing/mark-sold.ts', + 'src/lib/components/ConfirmPanel.svelte', + 'src/lib/nostr/listing-publisher.ts', + 'src/lib/publishing/withdraw-listing.ts', + 'src/lib/publishing/sign-listing.ts', + 'src/lib/persistence/artifact-records.ts', + 'src/lib/publishing/listing-operation-view.ts', + 'src/lib/components/OperationStatus.svelte', + 'src/lib/runtime/effect-ownership.ts', + 'src/lib/nostr/public-pool.ts', + 'src/lib/persistence/public-receipts.ts', + 'src/routes/selling/+page.svelte', + 'src/lib/components/SellingRow.svelte', + 'src/lib/publishing/selling-view.ts', + 'src/lib/runtime/identity-session.ts', + 'src/lib/persistence/local-public-hides.ts', + 'src/lib/catalog/product-view.ts', + 'src/lib/catalog/search-run.ts', + 'src/lib/catalog/search-view.ts', + 'src/routes/+layout.svelte', + 'src/routes/products/[naddr=naddr]/+page.svelte', + 'src/routes/privacy/+page.svelte', + 'src/lib/components/PublisherHide.svelte' + ].includes(name) && (await publicHidingAdmission(web)) + ) + ) throw new Error('Invalid owned selling workspace source'); } return true; @@ -933,7 +1175,10 @@ async function listingEditorAdmission(web) { const bytes = await readOwned(web, name); publicText(bytes); withdrawing = - withdrawing && createHash('sha256').update(bytes).digest('hex') === pin; + withdrawing && + (createHash('sha256').update(bytes).digest('hex') === pin || + (name === 'src/lib/runtime/public-runtime.ts' && + (await publicHidingAdmission(web)))); } if (withdrawing) return 'owned-withdrawal'; if (revising) return 'owned-revision'; @@ -1109,6 +1354,7 @@ export async function auditOutput(webDirectory) { ]) await readOwned(web, name); } + const hasPublicHiding = hasFullRoutes && (await publicHidingAdmission(web)); const hasPublicRuntime = await hasOwnedPublicRuntime(web); if (hasPublicRuntime && !hasFullRoutes) throw new Error('Incomplete owned root runtime routes'); @@ -1270,6 +1516,11 @@ export async function auditOutput(webDirectory) { names.delete('AccountGate'); names.add('OperationStatus'); } + if (hasPublicHiding) { + names.delete('rolldown-runtime'); + names.add('local-public-hides'); + names.add('public-key'); + } const admitted = new Map([['build-info.json', expectedMetadata]]); const seen = new Set(); for (const [key, record] of Object.entries(manifest)) { @@ -3280,6 +3531,317 @@ export async function auditOutput(webDirectory) { } }); } + if (hasPublicHiding) { + delete expected['rolldown-runtime']; + Object.assign(expected, { + InboxSetup: { + file: '_app/immutable/chunks/HASH.js', + name: 'InboxSetup', + imports: ['local-public-hides', 'public-runtime', 'client', 'Button'] + }, + InboxStatus: { + file: '_app/immutable/chunks/HASH.js', + name: 'InboxStatus', + imports: [ + 'local-public-hides', + 'public-runtime', + 'client', + 'Button', + 'navigation', + 'CapabilityGate', + 'InboxSetup', + 'inbox-view' + ] + }, + ListingEditor: { + file: '_app/immutable/chunks/HASH.js', + name: 'ListingEditor', + imports: [ + 'public-key', + 'local-public-hides', + 'public-runtime', + 'references', + 'client', + 'Button', + 'CapabilityGate', + 'InboxSetup', + 'OperationStatus' + ] + }, + MessageComposer: { + file: '_app/immutable/chunks/HASH.js', + name: 'MessageComposer', + imports: [ + 'public-key', + 'local-public-hides', + 'public-runtime', + 'references', + 'client', + 'Button', + 'navigation', + 'inbox-view', + 'publishers' + ] + }, + OperationStatus: { + file: '_app/immutable/chunks/HASH.js', + name: 'OperationStatus', + imports: [ + 'public-key', + 'local-public-hides', + 'public-runtime', + 'client' + ] + }, + 'entry/app': { + file: '_app/immutable/entry/app.HASH.js', + name: 'entry/app', + src: '.svelte-kit/generated/build/client-optimized/app.js', + isEntry: true, + imports: [ + 'public-key', + 'preload-helper', + 'shared-errors', + 'references' + ], + dynamicImports: [ + 'nodes/0', + 'nodes/1', + 'nodes/2', + 'nodes/3', + 'nodes/4', + 'nodes/5', + 'nodes/6', + 'nodes/7', + 'nodes/8', + 'nodes/9', + 'nodes/10', + 'nodes/11', + 'nodes/12', + 'error-template' + ] + }, + 'inbox-view': { + file: '_app/immutable/chunks/HASH.js', + name: 'inbox-view', + imports: [ + 'public-key', + 'local-public-hides', + 'public-runtime', + 'references', + 'Button' + ] + }, + 'local-public-hides': { + file: '_app/immutable/chunks/HASH.js', + name: 'local-public-hides', + imports: ['public-key', 'Button'] + }, + negentropy: { + file: '_app/immutable/chunks/HASH.js', + name: 'negentropy', + src: 'node_modules/.pnpm/applesauce-relay@6.2.1_typescript@6.0.3/node_modules/applesauce-relay/dist/negentropy.js', + isDynamicEntry: true, + imports: ['local-public-hides', 'public-runtime'] + }, + 'nodes/0': { + file: '_app/immutable/nodes/0.HASH.js', + name: 'nodes/0', + src: '.svelte-kit/generated/build/client-optimized/nodes/0.js', + isEntry: true, + imports: [ + 'public-key', + 'local-public-hides', + 'public-runtime', + 'client', + 'Button', + 'client.svelte', + 'state', + 'CapabilityGate', + 'Disclosure' + ], + css: ['_app/immutable/assets/0.HASH.css'] + }, + 'nodes/10': { + file: '_app/immutable/nodes/10.HASH.js', + name: 'nodes/10', + src: '.svelte-kit/generated/build/client-optimized/nodes/10.js', + isEntry: true, + imports: [ + 'public-key', + 'client', + 'Button', + 'client.svelte', + 'navigation', + 'state', + 'legacy', + 'routes', + 'ListingEditor' + ] + }, + 'nodes/11': { + file: '_app/immutable/nodes/11.HASH.js', + name: 'nodes/11', + src: '.svelte-kit/generated/build/client-optimized/nodes/11.js', + isEntry: true, + imports: [ + 'local-public-hides', + 'public-runtime', + 'references', + 'client', + 'Button', + 'CapabilityGate', + 'Disclosure', + 'InboxSetup', + 'OperationStatus' + ] + }, + 'nodes/12': { + file: '_app/immutable/nodes/12.HASH.js', + name: 'nodes/12', + src: '.svelte-kit/generated/build/client-optimized/nodes/12.js', + isEntry: true, + imports: [ + 'public-key', + 'client', + 'client.svelte', + 'navigation', + 'state', + 'ListingEditor' + ] + }, + 'nodes/4': { + file: '_app/immutable/nodes/4.HASH.js', + name: 'nodes/4', + src: '.svelte-kit/generated/build/client-optimized/nodes/4.js', + isEntry: true, + imports: [ + 'local-public-hides', + 'client', + 'CapabilityGate', + 'InboxSetup', + 'InboxStatus' + ] + }, + 'nodes/5': { + file: '_app/immutable/nodes/5.HASH.js', + name: 'nodes/5', + src: '.svelte-kit/generated/build/client-optimized/nodes/5.js', + isEntry: true, + imports: [ + 'public-key', + 'local-public-hides', + 'public-runtime', + 'references', + 'client', + 'Button', + 'client.svelte', + 'state', + 'legacy', + 'inbox-view', + 'InboxStatus', + 'MessageComposer' + ] + }, + 'nodes/6': { + file: '_app/immutable/nodes/6.HASH.js', + name: 'nodes/6', + src: '.svelte-kit/generated/build/client-optimized/nodes/6.js', + isEntry: true, + imports: ['local-public-hides', 'client', 'Button'] + }, + 'nodes/7': { + file: '_app/immutable/nodes/7.HASH.js', + name: 'nodes/7', + src: '.svelte-kit/generated/build/client-optimized/nodes/7.js', + isEntry: true, + imports: [ + 'public-key', + 'local-public-hides', + 'public-runtime', + 'references', + 'client', + 'Button', + 'client.svelte', + 'state', + 'CapabilityGate', + 'Disclosure', + 'InboxSetup', + 'MessageComposer' + ] + }, + 'nodes/8': { + file: '_app/immutable/nodes/8.HASH.js', + name: 'nodes/8', + src: '.svelte-kit/generated/build/client-optimized/nodes/8.js', + isEntry: true, + imports: [ + 'public-key', + 'client', + 'client.svelte', + 'navigation', + 'state', + 'ListingEditor' + ] + }, + 'nodes/9': { + file: '_app/immutable/nodes/9.HASH.js', + name: 'nodes/9', + src: '.svelte-kit/generated/build/client-optimized/nodes/9.js', + isEntry: true, + imports: [ + 'local-public-hides', + 'public-runtime', + 'references', + 'client', + 'Button', + 'client.svelte', + 'navigation', + 'state', + 'Disclosure', + 'SearchForm', + 'routes', + 'publishers' + ] + }, + 'public-key': { + file: '_app/immutable/chunks/HASH.js', + name: 'public-key' + }, + 'public-runtime': { + file: '_app/immutable/chunks/HASH.js', + name: 'public-runtime', + imports: [ + 'public-key', + 'preload-helper', + 'local-public-hides', + 'references', + 'Button' + ], + dynamicImports: ['negentropy'] + }, + publishers: { + file: '_app/immutable/chunks/HASH.js', + name: 'publishers', + imports: [ + 'public-key', + 'local-public-hides', + 'public-runtime', + 'Button' + ] + }, + references: { + file: '_app/immutable/chunks/HASH.js', + name: 'references', + imports: ['public-key'] + }, + routes: { + file: '_app/immutable/chunks/HASH.js', + name: 'routes', + imports: ['public-key', 'references', 'Button'] + } + }); + } for (const record of Object.values(manifest)) { const actual = { ...record }; actual.file = actual.file.includes('/chunks/')