commit 981f655471aab9592ffc4ce0faccbd3f3668deff
parent 10a1687be5a3291df996f5a0ad008cd53c932120
Author: triesap <tyson@radroots.org>
Date: Sun, 11 Oct 2026 07:09:56 +0000
harvestcircle: Add practical help and deliberate selected reports
- Admit bounded support policies while requiring actual launch operator inputs
- Bind optional private and listing previews to original current source owners
- Preserve explicit disclosure, clipboard limits and exact compiler provenance
- Verify all source lanes and retain failures under independent acceptance
Diffstat:
22 files changed, 2988 insertions(+), 148 deletions(-)
diff --git a/web/package.json b/web/package.json
@@ -19,7 +19,8 @@
"test:integration": "corepack pnpm build && node --test --test-timeout=1800000 tests/integration/*.test.ts",
"test:e2e": "corepack pnpm build && playwright test",
"test:conformance:oracle": "node tools/check-food-interop.mjs",
- "check:launch-relays": "node tools/check-source.mjs && node tools/check-launch-relays.mjs"
+ "check:launch-relays": "node tools/check-source.mjs && node tools/check-launch-relays.mjs",
+ "check:launch-support": "node tools/check-source.mjs && node tools/check-launch-support.mjs"
},
"dependencies": {
"@noble/curves": "1.2.0",
diff --git a/web/src/lib/components/ConversationOptions.svelte b/web/src/lib/components/ConversationOptions.svelte
@@ -1,5 +1,5 @@
<script lang="ts">
- import { onMount } from 'svelte';
+ import { onMount, untrack } from 'svelte';
import {
subscribeInboxView,
blockInboxConversation,
@@ -9,6 +9,12 @@
conversationOptionsSnapshot,
requestConversationOption
} from '../messaging/cited-product.ts';
+ import ReportPreview from './ReportPreview.svelte';
+ import {
+ createConversationReport,
+ closeReportContext,
+ type ReportContext
+ } from '../support/report.ts';
let {
controller,
conversationId,
@@ -21,6 +27,19 @@
onreport?: (peer: string) => void;
} = $props();
let revision = $state(0);
+ let report = $state.raw<ReportContext | undefined>();
+ let reportOwner = $state.raw<{ view: InboxView; id: string } | undefined>();
+ $effect(() => {
+ const view = controller,
+ id = conversationId;
+ untrack(() => {
+ if (reportOwner && (reportOwner.view !== view || reportOwner.id !== id)) {
+ if (report) closeReportContext(report);
+ report = undefined;
+ reportOwner = undefined;
+ }
+ });
+ });
let reviewing = $state(false),
busy = $state(false),
notice = $state<string | undefined>();
@@ -43,11 +62,15 @@
void revision;
return conversationOptionsSnapshot(controller, conversationId);
});
- onMount(() =>
- subscribeInboxView(controller, () => {
+ onMount(() => {
+ const off = subscribeInboxView(controller, () => {
revision++;
- })
- );
+ });
+ return () => {
+ off();
+ if (report) closeReportContext(report);
+ };
+ });
</script>
{#if actual}
@@ -88,18 +111,26 @@
>
{/if}
{#if notice}<p role="status">{notice}</p>{/if}
- {#if onreport}<button
- type="button"
- onclick={() => {
- if (onreport)
- requestConversationOption(
- controller,
- conversationId,
- 'report',
- onreport,
- 'reviewed_conversation_option'
- );
- }}>Report conversation</button
- >{/if}
+ <button
+ type="button"
+ onclick={() => {
+ if (onreport)
+ requestConversationOption(
+ controller,
+ conversationId,
+ 'report',
+ onreport,
+ 'reviewed_conversation_option'
+ );
+ else {
+ if (report) closeReportContext(report);
+ report = createConversationReport(controller, conversationId);
+ reportOwner = report
+ ? { view: controller, id: conversationId }
+ : undefined;
+ }
+ }}>Report conversation</button
+ >
+ {#if report}{#key report}<ReportPreview context={report} />{/key}{/if}
</details>
{/if}
diff --git a/web/src/lib/components/ReportPreview.svelte b/web/src/lib/components/ReportPreview.svelte
@@ -0,0 +1,223 @@
+<script lang="ts">
+ import { onMount } from 'svelte';
+ import { deploymentSupportPolicy } from '../config/deployment-support.ts';
+ import type { SupportPolicy } from '../config/support.ts';
+ import { internalHref } from '../navigation-url.ts';
+ import SupportLink from './SupportLink.svelte';
+ import {
+ reportContextSnapshot,
+ subscribeReportContext,
+ closeReportContext,
+ reviewReportPreview,
+ reportPreviewSnapshot,
+ closeReportPreview,
+ copyReportPreview,
+ type ReportContext,
+ type ReportPreview
+ } from '../support/report.ts';
+ let {
+ context,
+ policy = deploymentSupportPolicy
+ }: { context: ReportContext; policy?: SupportPolicy } = $props();
+ let revision = $state(0),
+ notes = $state(''),
+ listingVersion = $state(false),
+ coordinate = $state(false),
+ peer = $state(false),
+ messages = $state<string[]>([]),
+ privateDisclosure = $state(false),
+ preview = $state.raw<ReportPreview | undefined>(),
+ busy = $state(false),
+ notice = $state<string | undefined>();
+ const actual = $derived.by(() => {
+ void revision;
+ return reportContextSnapshot(context);
+ });
+ const text = $derived.by(() => {
+ void revision;
+ return preview && reportPreviewSnapshot(preview);
+ });
+ function discard() {
+ if (preview) closeReportPreview(preview);
+ preview = undefined;
+ notice = undefined;
+ }
+ function choose(id: string, checked: boolean) {
+ discard();
+ messages = checked
+ ? [...messages, id]
+ : messages.filter((value) => value !== id);
+ }
+ function review() {
+ discard();
+ preview = reviewReportPreview(
+ context,
+ JSON.stringify({
+ listingVersion,
+ coordinate,
+ peer,
+ messages,
+ notes,
+ privateDisclosure
+ }),
+ 'reviewed_report_preview'
+ );
+ if (!preview)
+ notice =
+ actual?.kind === 'conversation' && !privateDisclosure
+ ? 'Review the private sharing disclosure before preparing selected private information.'
+ : 'A report preview was not prepared. Select only the information you intend to share and keep the description short.';
+ }
+ async function copy() {
+ const selected = preview;
+ if (!selected || busy) return;
+ busy = true;
+ const outcome = await copyReportPreview(selected, 'reviewed_copy_report');
+ busy = false;
+ if (preview !== selected) return;
+ notice =
+ outcome === 'copied'
+ ? 'Report copied. Nothing was sent to support.'
+ : outcome === 'stopped'
+ ? 'This report is no longer current. A copy already requested may still remain outside HarvestCircle.'
+ : 'Copy was unavailable. Select the reviewed text below if you still want to share it.';
+ }
+ onMount(() => {
+ const original = context;
+ const off = subscribeReportContext(original, () => {
+ revision++;
+ if (!reportContextSnapshot(original)) {
+ discard();
+ notes = '';
+ messages = [];
+ peer = false;
+ listingVersion = false;
+ coordinate = false;
+ privateDisclosure = false;
+ }
+ });
+ return () => {
+ off();
+ discard();
+ closeReportContext(original);
+ };
+ });
+</script>
+
+<section class="stack" aria-label="Prepare a selected report">
+ <h3>Choose what to share</h3>
+ <p>
+ Only selected information appears in the preview. Preparing or copying a
+ report does not send it.
+ </p>
+ {#if actual}
+ {#if actual.kind === 'listing'}
+ <fieldset class="stack">
+ <legend>Public listing information</legend>
+ <label
+ ><input
+ type="checkbox"
+ checked={listingVersion}
+ onchange={(event) => {
+ discard();
+ listingVersion = event.currentTarget.checked;
+ }}
+ /> Share listing version</label
+ >
+ <label
+ ><input
+ type="checkbox"
+ checked={coordinate}
+ onchange={(event) => {
+ discard();
+ coordinate = event.currentTarget.checked;
+ }}
+ /> Share coordinate</label
+ >
+ </fieldset>
+ {:else if actual.kind === 'conversation'}
+ <p class="notice">
+ Support cannot automatically read encrypted messages. Selected private
+ text and identifiers become readable outside HarvestCircle if you share
+ them.
+ </p>
+ <fieldset class="stack">
+ <legend>Private information to include</legend>
+ <label
+ ><input
+ type="checkbox"
+ checked={peer}
+ onchange={(event) => {
+ discard();
+ peer = event.currentTarget.checked;
+ }}
+ /> Share authenticated peer key</label
+ >
+ {#each actual.messages as message, index (message.id)}
+ <div class="stack">
+ <label
+ ><input
+ type="checkbox"
+ aria-label={'Share message text and ID ' + (index + 1)}
+ checked={messages.includes(message.id)}
+ onchange={(event) =>
+ choose(message.id, event.currentTarget.checked)}
+ />
+ Share message text and ID {index + 1}</label
+ >
+ <p class="description">{message.content}</p>
+ </div>
+ {/each}
+ </fieldset>
+ {/if}
+ <label for="report-problem-description">Problem description</label>
+ <textarea
+ id="report-problem-description"
+ rows="4"
+ maxlength="4096"
+ value={notes}
+ oninput={(event) => {
+ discard();
+ notes = event.currentTarget.value;
+ }}></textarea>
+ <p>
+ Type only information you intend to share. No other messages, drafts,
+ receipts or account data are attached.
+ </p>
+ {#if actual.kind === 'conversation'}
+ <label
+ ><input
+ type="checkbox"
+ checked={privateDisclosure}
+ onchange={(event) => {
+ discard();
+ privateDisclosure = event.currentTarget.checked;
+ }}
+ /> I understand selected private information will leave HarvestCircle if I
+ share it.</label
+ >
+ {/if}
+ <button type="button" disabled={busy} onclick={review}>Review report</button
+ >
+ {#if text !== undefined}
+ <pre
+ class="description"
+ role="region"
+ aria-label="Selected report preview">{text}</pre>
+ <button type="button" disabled={busy} onclick={() => void copy()}
+ >Copy reviewed report</button
+ >
+ {/if}
+ {:else}<p class="notice">
+ This report context is no longer available. Reopen it from the current
+ listing or conversation if appropriate.
+ </p>{/if}
+ {#if notice}<p role="status">{notice}</p>{/if}
+ <p>
+ Copied text can remain in your clipboard or other applications.
+ Disconnecting or clearing local data cannot erase those copies. A copy
+ already requested may complete after disconnecting.
+ </p>
+ <SupportLink {policy} />
+ <a href={internalHref('/about#report')}>Help and report instructions</a>
+</section>
diff --git a/web/src/lib/components/SupportLink.svelte b/web/src/lib/components/SupportLink.svelte
@@ -0,0 +1,31 @@
+<script lang="ts">
+ import { deploymentSupportPolicy } from '../config/deployment-support.ts';
+ import { readSupportPolicy, type SupportPolicy } from '../config/support.ts';
+ import { navigationHref } from '../navigation-url.ts';
+ let { policy = deploymentSupportPolicy }: { policy?: SupportPolicy } =
+ $props();
+ const actual = $derived.by(() => {
+ try {
+ return readSupportPolicy(policy);
+ } catch {
+ return undefined;
+ }
+ });
+</script>
+
+{#if actual?.owner && actual.destination}
+ <p>Support is operated by {actual.owner}.</p>
+ <p>
+ This opens an external support destination. No report is attached
+ automatically.
+ </p>
+ <a
+ href={navigationHref(actual.destination)}
+ rel="noopener noreferrer"
+ referrerpolicy="no-referrer">Contact support</a
+ >
+{:else}
+ <p class="notice">
+ Support has not been configured. Reporting to an operator is unavailable.
+ </p>
+{/if}
diff --git a/web/src/lib/config/deployment-support.ts b/web/src/lib/config/deployment-support.ts
@@ -0,0 +1,14 @@
+import { validateSupportPolicy } from './support.ts';
+
+// Actual support owner/destination have not been supplied. These empty public
+// inputs allow source development; the named launch preparation gate refuses
+// them. Controlled fixture destinations never become production defaults.
+const policy = validateSupportPolicy(
+ JSON.stringify({
+ schemaVersion: 1,
+ owner: '',
+ destination: ''
+ })
+);
+if (!policy) throw Error('support_policy_invalid');
+export const deploymentSupportPolicy = policy;
diff --git a/web/src/lib/config/support.ts b/web/src/lib/config/support.ts
@@ -0,0 +1,106 @@
+import { navigationHref } from '../navigation-url.ts';
+import { canonicalRelayOrigin } from './relays.ts';
+
+export interface SupportManifest {
+ readonly schemaVersion: 1;
+ readonly owner: string;
+ readonly destination: string;
+}
+declare const supportBrand: unique symbol;
+export type SupportPolicy = Readonly<{ [supportBrand]: true }>;
+const policies = new WeakMap<SupportPolicy, string>();
+
+function destination(value: string): string | undefined {
+ if (!value) return '';
+ if (!navigationHref(value)) return undefined;
+ try {
+ const url = new URL(value);
+ if (url.search || url.hash || url.username || url.password)
+ return undefined;
+ if (url.protocol === 'https:') {
+ if (url.href !== value || !canonicalRelayOrigin('wss://' + url.host))
+ return undefined;
+ return value;
+ }
+ if (url.protocol !== 'mailto:' || !value.startsWith('mailto:'))
+ return undefined;
+ // One conservative, literal address. No recipient list, encoded header,
+ // subject/body carrier or automatically attached report content.
+ const address = value.slice(7);
+ const parts = address.split('@');
+ if (parts.length !== 2) return undefined;
+ const [local, host] = parts;
+ if (
+ !local ||
+ local.length > 64 ||
+ !/^[A-Za-z0-9._+-]+$/.test(local) ||
+ local.startsWith('.') ||
+ local.endsWith('.') ||
+ local.includes('..') ||
+ !canonicalRelayOrigin('wss://' + host) ||
+ new URL('https://' + host).hostname !== host
+ )
+ return undefined;
+ return value;
+ } catch {
+ return undefined;
+ }
+}
+
+// Public configuration only, bounded before JSON parsing. Caller objects and
+// getters never enter this owner. Admission is not operator qualification.
+export function validateSupportPolicy(raw: unknown): SupportPolicy | undefined {
+ if (
+ typeof raw !== 'string' ||
+ raw.length > 16384 ||
+ !raw.isWellFormed() ||
+ new TextEncoder().encode(raw).length > 16384
+ )
+ return undefined;
+ try {
+ const value: unknown = JSON.parse(raw);
+ if (!value || typeof value !== 'object' || Array.isArray(value))
+ return undefined;
+ const row = value as Record<string, unknown>;
+ let count = 0;
+ for (const key in row) {
+ if (!['schemaVersion', 'owner', 'destination'].includes(key))
+ return undefined;
+ count++;
+ }
+ if (
+ count !== 3 ||
+ row.schemaVersion !== 1 ||
+ typeof row.owner !== 'string' ||
+ typeof row.destination !== 'string' ||
+ !row.owner.isWellFormed() ||
+ row.owner !== row.owner.trim() ||
+ new TextEncoder().encode(row.owner).length > 256 ||
+ /[\p{Cc}\p{Cf}]/u.test(row.owner)
+ )
+ return undefined;
+ const href = destination(row.destination);
+ if (href === undefined) return undefined;
+ const token = Object.freeze({}) as SupportPolicy;
+ policies.set(
+ token,
+ JSON.stringify({ schemaVersion: 1, owner: row.owner, destination: href })
+ );
+ return token;
+ } catch {
+ return undefined;
+ }
+}
+export function readSupportPolicy(policy: SupportPolicy): SupportManifest {
+ const raw = policies.get(policy);
+ if (!raw) throw Error('support_policy_invalid');
+ return JSON.parse(raw) as SupportManifest;
+}
+export function requireLaunchSupportPolicy(
+ policy: SupportPolicy
+): SupportPolicy {
+ const actual = readSupportPolicy(policy);
+ if (!actual.owner || !actual.destination)
+ throw Error('support_launch_inputs_missing');
+ return policy;
+}
diff --git a/web/src/lib/support/report.ts b/web/src/lib/support/report.ts
@@ -0,0 +1,398 @@
+import {
+ productViewSnapshot,
+ productViewPublisherProof,
+ type ProductView
+} from '../catalog/product-view.ts';
+import { verifiedEnvelopeSnapshot } from '../nostr/verified-envelope.ts';
+import {
+ inboxThreadSnapshot,
+ inboxReplyOwnership,
+ subscribeInboxView,
+ type InboxView
+} from '../messaging/inbox-view.ts';
+
+declare const contextBrand: unique symbol, previewBrand: unique symbol;
+export type ReportContext = Readonly<{ [contextBrand]: true }>;
+export type ReportPreview = Readonly<{ [previewBrand]: true }>;
+export type ReportContextSnapshot = Readonly<
+ | { kind: 'general' }
+ | { kind: 'listing'; eventId: string; coordinate: string }
+ | {
+ kind: 'conversation';
+ peer: string;
+ messages: readonly Readonly<{
+ id: string;
+ content: string;
+ createdAt: number;
+ }>[];
+ }
+>;
+type Selection = Readonly<{
+ listingVersion: boolean;
+ coordinate: boolean;
+ peer: boolean;
+ messages: readonly string[];
+ notes: string;
+ privateDisclosure: boolean;
+}>;
+type PreviewOwner = {
+ text(): string | undefined;
+ current(): boolean;
+ retire(): void;
+};
+type ContextOwner = {
+ read(): ReportContextSnapshot | undefined;
+ close(deferNotification?: boolean): void;
+ subscribe(listener: () => void): () => void;
+ own(preview: PreviewOwner): () => void;
+ retirePreviews(): void;
+ listen(unsubscribe: () => void): void;
+ notify(): void;
+};
+const contexts = new WeakMap<ReportContext, ContextOwner>();
+const previews = new WeakMap<ReportPreview, PreviewOwner>();
+
+function capture(read: () => ReportContextSnapshot | undefined): ReportContext {
+ const token = Object.freeze({}) as ReportContext;
+ let closed = false;
+ let source = read;
+ let unsubscribe = () => {};
+ const listeners = new Map<symbol, () => void>();
+ const retained = new Map<symbol, PreviewOwner>();
+ const retirePreviews = () => {
+ for (const previous of retained.values()) previous.retire();
+ };
+ const notify = () => {
+ for (const listener of listeners.values()) listener();
+ };
+ const close = (deferNotification = false) => {
+ if (closed) return;
+ closed = true;
+ source = () => undefined;
+ unsubscribe();
+ unsubscribe = () => {};
+ retirePreviews();
+ const pending = Array.from(listeners.values());
+ listeners.clear();
+ // Plaintext and authority retire synchronously. Only UI notification may
+ // be deferred when a Svelte derivation discovers original-owner loss.
+ const notifyClosed = () => {
+ for (const listener of pending) listener();
+ };
+ if (deferNotification && pending.length) queueMicrotask(notifyClosed);
+ else notifyClosed();
+ };
+ contexts.set(token, {
+ read() {
+ if (closed) return undefined;
+ let snapshot: ReportContextSnapshot | undefined;
+ try {
+ snapshot = source();
+ } catch {
+ /* Original source unavailable. */
+ }
+ if (!snapshot) close(true);
+ return snapshot;
+ },
+ close,
+ subscribe(listener) {
+ if (closed) return () => {};
+ const id = Symbol();
+ listeners.set(id, listener);
+ return () => {
+ listeners.delete(id);
+ };
+ },
+ own(preview) {
+ const id = Symbol();
+ if (closed) preview.retire();
+ else retained.set(id, preview);
+ return () => {
+ retained.delete(id);
+ };
+ },
+ retirePreviews,
+ listen(next) {
+ if (closed) next();
+ else unsubscribe = next;
+ },
+ notify
+ });
+ return token;
+}
+export function createGeneralReport(): ReportContext {
+ return capture(() => ({ kind: 'general' }));
+}
+export function createListingReport(
+ view: ProductView
+): ReportContext | undefined {
+ if (typeof window === 'undefined') return undefined;
+ const proof = productViewPublisherProof(view);
+ const event = proof && verifiedEnvelopeSnapshot(proof);
+ if (!event || event.kind !== 30402) return undefined;
+ try {
+ const initial = productViewSnapshot(view);
+ if (
+ initial.eventId !== event.id ||
+ initial.reference.pubkey !== event.pubkey
+ )
+ return undefined;
+ const coordinate = `30402:${initial.reference.pubkey}:${initial.reference.identifier}`;
+ return capture(() => {
+ try {
+ const current = productViewSnapshot(view);
+ const currentProof = productViewPublisherProof(view);
+ const signed = currentProof && verifiedEnvelopeSnapshot(currentProof);
+ return current.eventId === event.id &&
+ signed?.id === event.id &&
+ `30402:${current.reference.pubkey}:${current.reference.identifier}` ===
+ coordinate
+ ? { kind: 'listing', eventId: event.id, coordinate }
+ : undefined;
+ } catch {
+ return undefined;
+ }
+ });
+ } catch {
+ return undefined;
+ }
+}
+export function createConversationReport(
+ view: InboxView,
+ id: string
+): ReportContext | undefined {
+ if (typeof window === 'undefined') return undefined;
+ const initial = inboxThreadSnapshot(view, id);
+ const first = initial.messages[0];
+ const original = first && inboxReplyOwnership(view, id, first.data.rumorId);
+ if (initial.status !== 'ready' || !original?.current()) return undefined;
+ const peer = original.peer;
+ const token = capture(() => {
+ if (!original.current()) return undefined;
+ const thread = inboxThreadSnapshot(view, id);
+ if (thread.status !== 'ready') return undefined;
+ if (
+ thread.messages.some((row) => {
+ const owned = inboxReplyOwnership(view, id, row.data.rumorId);
+ return !owned?.current() || owned.peer !== peer;
+ })
+ )
+ return undefined;
+ const rows = thread.messages.map((row) => ({
+ id: row.data.rumorId,
+ content: row.data.content,
+ createdAt: row.data.createdAt
+ }));
+ /* verified original rows only */
+ return { kind: 'conversation', peer, messages: rows };
+ });
+ const owned = contexts.get(token)!;
+ owned.listen(
+ subscribeInboxView(view, () => {
+ if (reportContextSnapshot(token)) owned.notify();
+ })
+ );
+ return token;
+}
+export function reportContextSnapshot(
+ token: ReportContext
+): ReportContextSnapshot | undefined {
+ return contexts.get(token)?.read();
+}
+export function subscribeReportContext(
+ token: ReportContext,
+ listener: () => void
+): () => void {
+ return contexts.get(token)?.subscribe(listener) ?? (() => {});
+}
+export function closeReportContext(token: ReportContext): void {
+ contexts.get(token)?.close();
+}
+function selection(raw: unknown): Selection | undefined {
+ if (
+ typeof raw !== 'string' ||
+ raw.length > 65536 ||
+ !raw.isWellFormed() ||
+ new TextEncoder().encode(raw).length > 65536
+ )
+ return undefined;
+ try {
+ const value: unknown = JSON.parse(raw);
+ if (!value || typeof value !== 'object' || Array.isArray(value))
+ return undefined;
+ const row = value as Record<string, unknown>;
+ let count = 0;
+ for (const key in row) {
+ if (
+ ![
+ 'listingVersion',
+ 'coordinate',
+ 'peer',
+ 'messages',
+ 'notes',
+ 'privateDisclosure'
+ ].includes(key)
+ )
+ return undefined;
+ count++;
+ }
+ if (
+ count !== 6 ||
+ typeof row.listingVersion !== 'boolean' ||
+ typeof row.coordinate !== 'boolean' ||
+ typeof row.peer !== 'boolean' ||
+ typeof row.privateDisclosure !== 'boolean' ||
+ typeof row.notes !== 'string' ||
+ !row.notes.isWellFormed() ||
+ new TextEncoder().encode(row.notes).length > 4096 ||
+ !Array.isArray(row.messages) ||
+ row.messages.some(
+ (value) => typeof value !== 'string' || !/^[0-9a-f]{64}$/.test(value)
+ ) ||
+ new Set(row.messages).size !== row.messages.length
+ )
+ return undefined;
+ return {
+ listingVersion: row.listingVersion,
+ coordinate: row.coordinate,
+ peer: row.peer,
+ messages: row.messages as string[],
+ notes: row.notes,
+ privateDisclosure: row.privateDisclosure
+ };
+ } catch {
+ return undefined;
+ }
+}
+function selectedText(
+ snapshot: ReportContextSnapshot,
+ selected: Selection
+): string | undefined {
+ if (
+ snapshot.kind !== 'listing' &&
+ (selected.listingVersion || selected.coordinate)
+ )
+ return undefined;
+ if (
+ snapshot.kind !== 'conversation' &&
+ (selected.peer || selected.messages.length)
+ )
+ return undefined;
+ if (snapshot.kind === 'conversation') {
+ if (
+ (selected.peer || selected.messages.length || selected.notes) &&
+ !selected.privateDisclosure
+ )
+ return undefined;
+ if (
+ selected.messages.some(
+ (id) => !snapshot.messages.some((message) => message.id === id)
+ )
+ )
+ return undefined;
+ }
+ const lines = [
+ 'HarvestCircle report',
+ ...(snapshot.kind === 'listing' && selected.listingVersion
+ ? ['Listing version: ' + snapshot.eventId]
+ : []),
+ ...(snapshot.kind === 'listing' && selected.coordinate
+ ? ['Coordinate: ' + snapshot.coordinate]
+ : []),
+ ...(snapshot.kind === 'conversation' && selected.peer
+ ? ['Authenticated peer: ' + snapshot.peer]
+ : []),
+ ...(snapshot.kind === 'conversation'
+ ? snapshot.messages
+ .filter((message) => selected.messages.includes(message.id))
+ .map(
+ (message) =>
+ `Message: ${message.id}\nTime: ${message.createdAt}\n${message.content}`
+ )
+ : []),
+ ...(selected.notes ? ['Notes:\n' + selected.notes] : [])
+ ];
+ if (lines.length === 1) return undefined;
+ const text = lines.join('\n\n');
+ // Conservative local-copy ceiling, not a message/transport quota. Refuse the
+ // complete selection rather than silently truncating private report content.
+ return new TextEncoder().encode(text).length <= 65536 ? text : undefined;
+}
+export function reviewReportPreview(
+ token: ReportContext,
+ raw: unknown,
+ review: unknown
+): ReportPreview | undefined {
+ if (review !== 'reviewed_report_preview') return undefined;
+ const owned = contexts.get(token),
+ selected = selection(raw),
+ snapshot = reportContextSnapshot(token);
+ if (!owned || !selected || !snapshot) return undefined;
+ const text = selectedText(snapshot, selected);
+ if (!text) return undefined;
+ // One current reviewed preview per context; obsolete selections do not form
+ // a retained plaintext history and cannot remain copyable by stale handles.
+ owned.retirePreviews();
+ const preview = Object.freeze({}) as ReportPreview;
+ let currentText: string | undefined = text;
+ let chosen: Selection | undefined = selected;
+ let forget = () => {};
+ const record: PreviewOwner = {
+ text: () => currentText,
+ current() {
+ const actual = reportContextSnapshot(token);
+ return (
+ !!actual &&
+ chosen !== undefined &&
+ currentText !== undefined &&
+ selectedText(actual, chosen) === currentText
+ );
+ },
+ retire() {
+ currentText = undefined;
+ chosen = undefined;
+ forget();
+ forget = () => {};
+ }
+ };
+ forget = owned.own(record);
+ previews.set(preview, record);
+ return preview;
+}
+export function reportPreviewSnapshot(
+ token: ReportPreview
+): string | undefined {
+ const record = previews.get(token);
+ if (!record || !record.current()) {
+ if (record) record.retire();
+ return undefined;
+ }
+ return record.text();
+}
+export function closeReportPreview(token: ReportPreview): void {
+ const record = previews.get(token);
+ if (record) record.retire();
+}
+export async function copyReportPreview(
+ token: ReportPreview,
+ review: unknown
+): Promise<'copied' | 'unavailable' | 'stopped'> {
+ if (review !== 'reviewed_copy_report' || !previews.has(token))
+ return 'unavailable';
+ const text = reportPreviewSnapshot(token);
+ if (text === undefined) return 'stopped';
+ if (typeof window === 'undefined' || typeof navigator === 'undefined')
+ return 'unavailable';
+ try {
+ const clipboard = navigator.clipboard,
+ write =
+ clipboard &&
+ Reflect.get<Clipboard, 'writeText'>(clipboard, 'writeText');
+ if (typeof write !== 'function') return 'unavailable';
+ if (reportPreviewSnapshot(token) !== text) return 'stopped';
+ await write.call(clipboard, text);
+ return reportPreviewSnapshot(token) === text ? 'copied' : 'stopped';
+ } catch {
+ return reportPreviewSnapshot(token) === text ? 'unavailable' : 'stopped';
+ }
+}
diff --git a/web/src/routes/about/+page.svelte b/web/src/routes/about/+page.svelte
@@ -1,11 +1,119 @@
+<script lang="ts">
+ import SupportLink from '../../lib/components/SupportLink.svelte';
+ import ReportPreview from '../../lib/components/ReportPreview.svelte';
+ import {
+ createGeneralReport,
+ type ReportContext
+ } from '../../lib/support/report.ts';
+ import { deploymentRelayPolicy } from '../../lib/config/deployment-relays.ts';
+ import { readRelayPolicy } from '../../lib/config/relays.ts';
+ const sources = readRelayPolicy(deploymentRelayPolicy);
+ let report = $state.raw<ReportContext | undefined>();
+</script>
+
<svelte:head><title>About — HarvestCircle</title></svelte:head>
<div class="page page--reading stack">
- <h1>About</h1>
- <p class="notice">
- Information about HarvestCircle is unavailable during development.
- </p>
- <section id="help">
- <h2>Help / report</h2>
- <p>Help and reporting are unavailable during development.</p>
+ <h1>About HarvestCircle</h1>
+ <p>Find food listings and speak directly with the people who posted them.</p>
+ <section class="stack">
+ <h2>How it works</h2>
+ <p>
+ Search without connecting. Connect a compatible Nostr extension to list
+ food or send a private message.
+ </p>
+ <p>
+ Messages do not reserve food or confirm an order. Payments are not handled
+ here.
+ </p>
+ </section>
+ <section class="stack">
+ <h2>Before you make arrangements</h2>
+ <p>
+ Confirm the quantity, price and collection details with the seller. A
+ profile name is not farm verification.
+ </p>
+ </section>
+ <section id="help" class="stack">
+ <h2>Help</h2>
+ <details>
+ <summary>Connecting an extension</summary>
+ <p>
+ Use Connect extension, review the identity shown, and approve only the
+ action you chose. Connecting does not post a listing or send a message.
+ </p>
+ <p>
+ Listing food requires a reachable reply inbox. Messages need the
+ extension's private encryption and decryption capabilities and an
+ explicit unlock.
+ </p>
+ <p>
+ Without an available compatible extension, public browsing remains
+ available. The website does not generate or import an identity secret.
+ </p>
+ </details>
+ <details>
+ <summary>Supported browsers and extensions</summary>
+ <p>
+ Real browser and extension combinations are still being qualified. No
+ supported tuple is claimed for this development build.
+ </p>
+ <p>
+ If the required capabilities are unavailable, posting and messages are
+ unavailable. Mobile extension support is not implied.
+ </p>
+ </details>
+ <details>
+ <summary>Search sources and inboxes</summary>
+ {#if sources.public.length}
+ <p>Configured public sources:</p>
+ <ul>
+ {#each sources.public as source (source.origin)}<li
+ class="message-text"
+ >
+ {source.origin}
+ </li>{/each}
+ </ul>
+ {:else}<p>No production search sources have been approved.</p>{/if}
+ {#if sources.inbox.length}
+ <p>Configured private inbox sources:</p>
+ <ul>
+ {#each sources.inbox as source (source.origin)}<li
+ class="message-text"
+ >
+ {source.origin}
+ </li>{/each}
+ </ul>
+ {:else}<p>No production private inbox sources have been approved.</p>{/if}
+ <p>
+ Checks are bounded and can be incomplete. Selected sources can observe
+ query and account interests; inbox retention needs operator
+ confirmation.
+ </p>
+ </details>
+ </section>
+ <section class="stack">
+ <h2>Listing rules</h2>
+ <p>
+ Use lawful food listings and truthful descriptions. Share public contact
+ information only with the contact person's consent. This prototype does
+ not certify food, farms or legal compliance.
+ </p>
+ </section>
+ <section id="report" class="stack">
+ <h2>Report a problem</h2>
+ <p>
+ Share only information needed to explain the issue. Listing and
+ conversation controls let you review selected context. Private messages
+ are never attached automatically, and support cannot automatically decrypt
+ them.
+ </p>
+ <SupportLink />
+ {#if report}<ReportPreview context={report} />
+ {:else}<button
+ type="button"
+ onclick={() => {
+ report = createGeneralReport();
+ }}>Prepare a report description</button
+ >{/if}
</section>
</div>
diff --git a/web/src/routes/products/[naddr=naddr]/+page.svelte b/web/src/routes/products/[naddr=naddr]/+page.svelte
@@ -1,5 +1,5 @@
<script lang="ts">
- import { getContext, onMount } from 'svelte';
+ import { getContext, onMount, untrack } from 'svelte';
import { page } from '$app/state';
import {
PUBLIC_RUNTIME_CONTEXT,
@@ -26,12 +26,19 @@
import Button from '../../../lib/components/primitives/Button.svelte';
import ProductEnquiry from '../../../lib/components/ProductEnquiry.svelte';
import PublisherHide from '../../../lib/components/PublisherHide.svelte';
+ import ReportPreview from '../../../lib/components/ReportPreview.svelte';
+ import {
+ createListingReport,
+ closeReportContext,
+ type ReportContext
+ } from '../../../lib/support/report.ts';
const context = getContext<PublicRuntimeContext>(PUBLIC_RUNTIME_CONTEXT);
let runtime = $state.raw<PublicRuntime | undefined>(),
result = $state.raw<ProductViewSnapshot | undefined>(),
error = $state<string | undefined>(),
copyNotice = $state<string | undefined>();
let productOwner = $state.raw<ProductView | undefined>();
+ let report = $state.raw<ReportContext | undefined>();
const reference = $derived(decodeProductReference(page.params.naddr));
const contact = $derived(readPublicContact(result?.food?.content));
let disposed = false;
@@ -61,6 +68,10 @@
result = undefined;
productOwner = undefined;
copyNotice = undefined;
+ untrack(() => {
+ if (report) closeReportContext(report);
+ report = undefined;
+ });
if (!selected || !shared) return;
let active = true,
acquired: PublicView | undefined,
@@ -154,6 +165,17 @@
<Disclosure summary="Publisher controls"
><PublisherHide view={productOwner} /></Disclosure
>
+ <button
+ type="button"
+ onclick={() => {
+ if (report) closeReportContext(report);
+ report = productOwner && createListingReport(productOwner);
+ }}>Report listing</button
+ >
+ {#if report}{#key result.eventId}{#key report}<ReportPreview
+ context={report}
+ />{/key}{/key}{/if}
+ <a href={internalHref('/about#report')}>Report instructions</a>
{/if}
<Disclosure summary="Listing and source details">
{#if result.eventId}<p>
diff --git a/web/tests/e2e/harness/reply-composer.ts b/web/tests/e2e/harness/reply-composer.ts
@@ -36,8 +36,12 @@ import {
probeIdentityMessaging,
disconnectIdentity
} from '../../../src/lib/runtime/identity-session.ts';
-import { inboxSetupViewOwnership } from '../../../src/lib/messaging/inbox-setup-view.ts';
+import {
+ inboxSetupViewOwnership,
+ inboxSetupViewSnapshot
+} from '../../../src/lib/messaging/inbox-setup-view.ts';
import { createInboxResolver } from '../../../src/lib/messaging/resolve-inbox.ts';
+import { browserDatabaseTransaction } from '../../../src/lib/persistence/database.ts';
import {
createPublicScheduler,
createPublicRun,
@@ -63,16 +67,110 @@ export function goto(destination: string | URL) {
export async function renderReplyFixture(qualified = true, production = false) {
navigation.length = 0;
destinations = [];
+ const manager = navigator.locks;
+ const originalDescriptor = Object.getOwnPropertyDescriptor(
+ manager,
+ 'request'
+ );
+ const originalRequest = Reflect.get(manager, 'request');
+ let fixedWallTime: number | undefined;
+ let crossOwnerSecond: string | undefined;
+ let nativeTransactions: {
+ stores: string[];
+ outcome: 'abort' | 'complete';
+ }[] = [];
+ let restoreTransaction = () => {};
+ let commandIds: string[] = [];
+ let lockAttempts: { name: string; ifAvailable: boolean; granted: boolean }[] =
+ [];
+ const observedRequest = ((...args: unknown[]) => {
+ const callbackIndex = args.length - 1;
+ const callback = args[callbackIndex] as (lock: Lock | null) => unknown;
+ const options = args.length === 3 ? (args[1] as LockOptions) : undefined;
+ const forwarded = args.slice();
+ forwarded[callbackIndex] = (lock: Lock | null) => {
+ lockAttempts = lockAttempts.concat({
+ name: String(args[0]),
+ ifAvailable: options?.ifAvailable === true,
+ granted: lock !== null
+ });
+ if (lock && options?.ifAvailable && args[0] === crossOwnerSecond) {
+ crossOwnerSecond = undefined;
+ const capturedSecond = Math.floor(clockSamples.at(-1)!.value / 1000);
+ return (async () => {
+ await new Promise<void>((resolve) => {
+ function forwardAfterBoundary() {
+ if (Math.floor(originalNow() / 1000) === capturedSecond) {
+ window.setTimeout(forwardAfterBoundary, 1);
+ return;
+ }
+ resolve();
+ }
+ window.setTimeout(
+ forwardAfterBoundary,
+ Math.max(1, (capturedSecond + 1) * 1000 - originalNow() + 1)
+ );
+ });
+ return callback(lock);
+ })();
+ }
+ return callback(lock);
+ };
+ return Reflect.apply(
+ originalRequest,
+ manager,
+ forwarded
+ ) as Promise<unknown>;
+ }) as typeof manager.request;
+ manager.request = observedRequest;
+ const originalNowDescriptor = Object.getOwnPropertyDescriptor(Date, 'now');
+ const originalNow = Reflect.get(Date, 'now');
+ let clockSamples: { value: number; stack: string | undefined }[] = [];
+ const observedNow = () => {
+ const value = fixedWallTime ?? originalNow();
+ clockSamples = clockSamples.concat({
+ value,
+ stack: new Error().stack?.split('\n').slice(1, 5).join('\n')
+ });
+ return value;
+ };
+ Date.now = observedNow;
+ function restoreSendClock() {
+ fixedWallTime = undefined;
+ crossOwnerSecond = undefined;
+ restoreTransaction();
+ restoreTransaction = () => {};
+ if (Date.now === observedNow && originalNowDescriptor)
+ Object.defineProperty(Date, 'now', originalNowDescriptor);
+ }
+
let clockOffset = 0,
alive = true;
+ let nextTimer = 0;
+ const timers = new Map<number, { at: number; callback: () => void }>();
const ownSchedulers: ReturnType<typeof createPublicScheduler>[] = [];
const clock: RequestClock = {
- now: () => performance.now() + clockOffset,
+ now: () => clockOffset,
schedule(callback, delay) {
- const timer = setTimeout(callback, delay);
- return () => clearTimeout(timer);
+ const id = ++nextTimer;
+ timers.set(id, { at: clockOffset + delay, callback });
+ return () => timers.delete(id);
}
};
+ function advanceClock() {
+ const target = clockOffset + 15_001;
+ for (;;) {
+ const next = [...timers]
+ .filter(([, timer]) => timer.at <= target)
+ .sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
+ if (!next) break;
+ const [id, timer] = next;
+ timers.delete(id);
+ clockOffset = timer.at;
+ timer.callback();
+ }
+ clockOffset = target;
+ }
const freshOwn: NonNullable<Parameters<typeof renderThread>[3]> = (
owner,
policy
@@ -166,6 +264,14 @@ export async function renderReplyFixture(qualified = true, production = false) {
const controller = candidate;
const target = document.createElement('div');
document.body.append(target);
+ let clicks = 0;
+ target.addEventListener(
+ 'click',
+ () => {
+ clicks++;
+ },
+ { capture: true }
+ );
const mounted = mount(Panel, { target, props: { controller } });
let unmounted = false,
held = false,
@@ -196,14 +302,83 @@ export async function renderReplyFixture(qualified = true, production = false) {
parent: thread.firstRumor,
conversationId: thread.conversationId,
snapshot: () => replySnapshot(controller),
+ diagnostic: async () => ({
+ setup: inboxSetupViewSnapshot(scope?.setup),
+ locks: await navigator.locks.query(),
+ lockAttempts: lockAttempts.slice(),
+ clicks,
+ clockSamples: clockSamples.slice(),
+ nativeTransactions: nativeTransactions.slice(),
+ commandIds: commandIds.slice()
+ }),
+ resetDiagnostics: () => {
+ lockAttempts = [];
+ clicks = 0;
+ clockSamples = [];
+ nativeTransactions = [];
+ commandIds = [];
+ },
+ configureSendClock(crossSecond: boolean) {
+ if (!scope) throw Error('no original reply scope');
+ fixedWallTime = crossSecond ? undefined : originalNow();
+ crossOwnerSecond = crossSecond
+ ? 'harvestcircle:owner:' + scope.owner
+ : undefined;
+ Date.now = observedNow;
+ const db = browserDatabaseTransaction(
+ scope.database,
+ ['private_sends'],
+ 'readonly'
+ ).db;
+ const descriptor = Object.getOwnPropertyDescriptor(db, 'transaction');
+ const original = Reflect.get(db, 'transaction');
+ const uuidDescriptor = Object.getOwnPropertyDescriptor(
+ crypto,
+ 'randomUUID'
+ );
+ const originalUuid = Reflect.get(crypto, 'randomUUID');
+ const observedUuid = () => {
+ const id = Reflect.apply(originalUuid, crypto, []);
+ commandIds = commandIds.concat(id);
+ return id;
+ };
+ crypto.randomUUID = observedUuid;
+ const observed = ((...args: Parameters<IDBDatabase['transaction']>) => {
+ const tx = Reflect.apply(original, db, args);
+ if (
+ tx.mode === 'readwrite' &&
+ tx.objectStoreNames.contains('private_sends')
+ ) {
+ for (const outcome of ['abort', 'complete'] as const)
+ tx.addEventListener(outcome, () => {
+ nativeTransactions = nativeTransactions.concat({
+ stores: Array.from(tx.objectStoreNames),
+ outcome
+ });
+ });
+ }
+ return tx;
+ }) as typeof db.transaction;
+ db.transaction = observed;
+ restoreTransaction = () => {
+ if (db.transaction === observed) {
+ if (descriptor) Object.defineProperty(db, 'transaction', descriptor);
+ else Reflect.deleteProperty(db, 'transaction');
+ }
+ if (crypto.randomUUID === observedUuid) {
+ if (uuidDescriptor)
+ Object.defineProperty(crypto, 'randomUUID', uuidDescriptor);
+ else Reflect.deleteProperty(crypto, 'randomUUID');
+ }
+ };
+ },
+ restoreSendClock,
text: () => replyText(controller),
native: thread.native,
delta: thread.delta,
list: () => inboxListSnapshot(thread.controller),
lookups: () => lookups,
- advance: () => {
- clockOffset += 15_001;
- },
+ advance: advanceClock,
refreshSetup: thread.checkSetup,
gate: (value: boolean) => {
gate = value;
@@ -292,13 +467,22 @@ export async function renderReplyFixture(qualified = true, production = false) {
closeComposer,
logout: thread.logout,
async close() {
+ restoreSendClock();
release?.();
provider.signEvent = nativeSign;
await closeComposer();
if (publicContext) closePublicRuntime(publicContext);
await thread.close();
+ if (manager.request === observedRequest) {
+ if (originalDescriptor)
+ Object.defineProperty(manager, 'request', originalDescriptor);
+ else Reflect.deleteProperty(manager, 'request');
+ }
+ if (Date.now === observedNow && originalNowDescriptor)
+ Object.defineProperty(Date, 'now', originalNowDescriptor);
alive = false;
for (const scheduler of ownSchedulers) closePublicScheduler(scheduler);
+ timers.clear();
}
};
}
diff --git a/web/tests/e2e/harness/support-report.ts b/web/tests/e2e/harness/support-report.ts
@@ -0,0 +1,138 @@
+// HC_TEST_ONLY_RELAY: original production views over real native IDB and
+// controlled loopback. These parser/navigation values are not live support.
+import { mount, unmount } from 'svelte';
+import ReportPanel from '../../../src/lib/components/ReportPreview.svelte';
+import SupportLink from '../../../src/lib/components/SupportLink.svelte';
+import { createFixture as privateFixture } from './private-blocks.ts';
+import { createFixture as publicFixture } from './public-hides.ts';
+import {
+ validateSupportPolicy,
+ type SupportPolicy
+} from '../../../src/lib/config/support.ts';
+import {
+ createGeneralReport,
+ createConversationReport,
+ createListingReport,
+ reportContextSnapshot,
+ reviewReportPreview,
+ reportPreviewSnapshot,
+ copyReportPreview,
+ closeReportContext,
+ type ReportContext,
+ type ReportPreview
+} from '../../../src/lib/support/report.ts';
+
+function fixturePolicy(): SupportPolicy {
+ const policy = validateSupportPolicy(
+ JSON.stringify({
+ schemaVersion: 1,
+ owner: 'Controlled fixture operator',
+ destination: 'https://support.operator.org/report'
+ })
+ );
+ if (!policy) throw Error('controlled fixture support policy unavailable');
+ return policy;
+}
+function panel(context: ReportContext) {
+ const target = document.createElement('div');
+ target.id = 'hcp124-report-fixture';
+ document.body.append(target);
+ const component = mount(ReportPanel, {
+ target,
+ props: { context, policy: fixturePolicy() }
+ });
+ return async () => {
+ await unmount(component);
+ closeReportContext(context);
+ target.remove();
+ };
+}
+export function createGeneralFixture() {
+ const context = createGeneralReport();
+ const close = panel(context);
+ return { close, context, snapshot: () => reportContextSnapshot(context) };
+}
+export function createSupportFixture() {
+ const target = document.createElement('div');
+ target.id = 'hcp124-support-fixture';
+ document.body.append(target);
+ const component = mount(SupportLink, {
+ target,
+ props: { policy: fixturePolicy() }
+ });
+ return {
+ async close() {
+ await unmount(component);
+ target.remove();
+ }
+ };
+}
+export async function createPrivateFixture() {
+ const original = await privateFixture('contexts');
+ let context: ReportContext | undefined,
+ closePanel: (() => Promise<void>) | undefined,
+ captured: ReportPreview | undefined;
+ return {
+ ...original,
+ report() {
+ context = createConversationReport(
+ original.controller,
+ original.conversationId
+ );
+ if (!context) throw Error('original unlocked report context unavailable');
+ closePanel = panel(context);
+ return reportContextSnapshot(context);
+ },
+ reportSnapshot: () => context && reportContextSnapshot(context),
+ captureSelected() {
+ if (!context) throw Error('original report not opened');
+ captured = reviewReportPreview(
+ context,
+ JSON.stringify({
+ listingVersion: false,
+ coordinate: false,
+ peer: false,
+ messages: [original.firstRumor],
+ notes: '',
+ privateDisclosure: true
+ }),
+ 'reviewed_report_preview'
+ );
+ if (!captured) throw Error('original selected preview unavailable');
+ return reportPreviewSnapshot(captured);
+ },
+ captured: () => captured && reportPreviewSnapshot(captured),
+ copyCaptured: () =>
+ captured
+ ? copyReportPreview(captured, 'reviewed_copy_report')
+ : Promise.resolve('unavailable' as const),
+ async close() {
+ await closePanel?.();
+ original.mode('normal');
+ original.settle();
+ original.releaseInventory();
+ await original.close();
+ }
+ };
+}
+export async function createPublicFixture() {
+ const original = await publicFixture();
+ let context: ReportContext | undefined,
+ closePanel: (() => Promise<void>) | undefined;
+ return {
+ ...original,
+ report() {
+ const view = original.view();
+ if (!view) throw Error('original product view unavailable');
+ context = createListingReport(view);
+ if (!context) throw Error('original signed listing context unavailable');
+ closePanel = panel(context);
+ return reportContextSnapshot(context);
+ },
+ reportSnapshot: () => context && reportContextSnapshot(context),
+ async close() {
+ await closePanel?.();
+ await original.close();
+ }
+ };
+}
diff --git a/web/tests/e2e/reply-composer.spec.ts b/web/tests/e2e/reply-composer.spec.ts
@@ -3,10 +3,11 @@ 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 { WebSocketServer, type WebSocket } from 'ws';
import { createStaticHarness } from '../integration/harness/static.ts';
import type * as Fixture from './harness/reply-composer.ts';
import { finalizeEvent } from 'applesauce-core/helpers';
+import { buildCanonicalPairRumor } from '../../src/lib/nostr/rumor-template.ts';
declare global {
interface Window {
hcp104: typeof Fixture;
@@ -21,6 +22,19 @@ let server: Awaited<ReturnType<typeof createStaticHarness>>,
let events: unknown[][] = [],
requests: unknown[][] = [];
let servePeerPreference = false;
+let holdPeerEose = false;
+let heldPeerRequest:
+ | {
+ socket: WebSocket;
+ id: string;
+ filter: unknown;
+ eventSent: boolean;
+ eoseSent: boolean;
+ closed: boolean;
+ closedBeforeEose: boolean;
+ disconnectedBeforeCompletion: boolean;
+ }
+ | undefined;
const peerPreference = finalizeEvent(
{
kind: 10050,
@@ -41,7 +55,11 @@ test.beforeAll(async () => {
const address = sockets.address();
if (!address || typeof address === 'string') throw Error('no loopback');
endpoint = 'ws://127.0.0.1:' + address.port;
- sockets.on('connection', (socket) =>
+ sockets.on('connection', (socket) => {
+ socket.on('close', () => {
+ if (heldPeerRequest?.socket === socket && !heldPeerRequest.closed)
+ heldPeerRequest.disconnectedBeforeCompletion = true;
+ });
socket.on('message', (bytes) => {
const raw = Buffer.isBuffer(bytes)
? bytes
@@ -49,6 +67,14 @@ test.beforeAll(async () => {
? Buffer.concat(bytes)
: Buffer.from(bytes),
frame = JSON.parse(raw.toString()) as unknown[];
+ if (
+ frame[0] === 'CLOSE' &&
+ heldPeerRequest?.socket === socket &&
+ heldPeerRequest.id === frame[1]
+ ) {
+ if (heldPeerRequest.eoseSent) heldPeerRequest.closed = true;
+ else heldPeerRequest.closedBeforeEose = true;
+ }
if (frame[0] === 'EVENT') {
events.push(frame);
const event = frame[1] as { id: string };
@@ -61,12 +87,27 @@ test.beforeAll(async () => {
servePeerPreference &&
filter.kinds?.includes(10050) &&
filter.authors?.includes(peerPreference.pubkey)
- )
+ ) {
+ if (holdPeerEose) {
+ if (heldPeerRequest) throw Error('duplicate held peer request');
+ heldPeerRequest = {
+ socket,
+ id: String(frame[1]),
+ filter: frame[2],
+ eventSent: true,
+ eoseSent: false,
+ closed: false,
+ closedBeforeEose: false,
+ disconnectedBeforeCompletion: false
+ };
+ }
socket.send(JSON.stringify(['EVENT', frame[1], peerPreference]));
+ if (holdPeerEose) return;
+ }
socket.send(JSON.stringify(['EOSE', frame[1]]));
}
- })
- );
+ });
+ });
const result = await build({
configFile: false,
logLevel: 'silent',
@@ -129,6 +170,8 @@ test.beforeEach(async ({ page }) => {
events = [];
requests = [];
servePeerPreference = false;
+ holdPeerEose = false;
+ heldPeerRequest = undefined;
await load(page);
});
test.afterEach(async ({ page }) => {
@@ -174,65 +217,207 @@ const composer = (page: import('@playwright/test').Page) =>
page.locator('[data-reply-fixture]');
const sentinel = 'HCP104_UNSENT_MEMORY_ONLY & <private>\nThursday pickup?';
-test('production explicit Send renews an expired peer lookup without losing the draft or automatically sending', async ({
- page
-}) => {
- await ready(page, true, true);
- await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
- const before = await page.evaluate(async () => ({
- native: await window.hcp104Fixture.native(),
- delta: window.hcp104Fixture.delta()
- }));
- expect(requests).toEqual([]);
- expect(await page.evaluate(() => window.hcp104Fixture.send())).toEqual({
- status: 'needs_action'
- });
- await expect.poll(() => requests.length).toBe(1);
- expect(requests[0][2]).toMatchObject({
- kinds: [10050],
- authors: [peerPreference.pubkey],
- limit: 200
- });
- // An active missing-peer run is reused. Neither its EOSE nor another Send
- // silently resets the bounded lookup or invents private readiness.
- expect(await page.evaluate(() => window.hcp104Fixture.send())).toEqual({
- status: 'needs_action'
- });
- expect(requests).toHaveLength(1);
- expect(events).toEqual([]);
- await page.evaluate(async () => {
- window.hcp104Fixture.advance();
- await window.hcp104Fixture.refreshSetup();
- });
- expect(requests).toHaveLength(1);
- expect(await page.evaluate(() => window.hcp104Fixture.text())).toBe(sentinel);
- expect(
- await page.evaluate(async () => ({
- native: await window.hcp104Fixture.native(),
- delta: window.hcp104Fixture.delta()
- }))
- ).toEqual(before);
- servePeerPreference = true;
- expect(await page.evaluate(() => window.hcp104Fixture.send())).toEqual({
- status: 'needs_action'
- });
- // The unchanged producer never issues this second original runtime query.
- await expect.poll(() => requests.length).toBe(2);
- expect(requests[1][2]).toEqual(requests[0][2]);
- expect(events).toEqual([]);
- expect(await page.evaluate(() => window.hcp104Fixture.text())).toBe(sentinel);
- await composer(page)
- .getByRole('button', { name: 'Send reply', exact: true })
- .click();
- await expect
- .poll(() => page.evaluate(() => window.hcp104Fixture.snapshot()?.state))
- .toBe('completed');
- expect(requests).toHaveLength(2);
- expect(events).toHaveLength(2);
- expect(await page.evaluate(() => window.hcp104Fixture.delta())).toMatchObject(
- { encrypts: before.delta.encrypts + 2, signs: before.delta.signs + 2 }
+for (const crossSecond of [false, true]) {
+ test(
+ crossSecond
+ ? 'production reply reservation rejects a real second-boundary crossing without persisting or sending the draft'
+ : 'production explicit Send renews an expired peer lookup without losing the draft or automatically sending',
+ async ({ page }) => {
+ await ready(page, true, true);
+ await composer(page).getByLabel('Reply', { exact: true }).fill(sentinel);
+ const before = await page.evaluate(async () => ({
+ native: await window.hcp104Fixture.native(),
+ delta: window.hcp104Fixture.delta()
+ }));
+ expect(requests).toEqual([]);
+ expect(await page.evaluate(() => window.hcp104Fixture.send())).toEqual({
+ status: 'needs_action'
+ });
+ await expect.poll(() => requests.length).toBe(1);
+ expect(requests[0][2]).toMatchObject({
+ kinds: [10050],
+ authors: [peerPreference.pubkey],
+ limit: 200
+ });
+ // An active missing-peer run is reused. Neither its EOSE nor another Send
+ // silently resets the bounded lookup or invents private readiness.
+ expect(await page.evaluate(() => window.hcp104Fixture.send())).toEqual({
+ status: 'needs_action'
+ });
+ expect(requests).toHaveLength(1);
+ expect(events).toEqual([]);
+ await page.evaluate(async () => {
+ window.hcp104Fixture.advance();
+ await window.hcp104Fixture.refreshSetup();
+ });
+ expect(requests).toHaveLength(1);
+ expect(await page.evaluate(() => window.hcp104Fixture.text())).toBe(
+ sentinel
+ );
+ expect(
+ await page.evaluate(async () => ({
+ native: await window.hcp104Fixture.native(),
+ delta: window.hcp104Fixture.delta()
+ }))
+ ).toEqual(before);
+ servePeerPreference = true;
+ holdPeerEose = true;
+ expect(await page.evaluate(() => window.hcp104Fixture.send())).toEqual({
+ status: 'needs_action'
+ });
+ // The unchanged producer never issues this second original runtime query.
+ await expect.poll(() => requests.length).toBe(2);
+ expect(requests[1][2]).toEqual(requests[0][2]);
+ expect(events).toEqual([]);
+ expect(await page.evaluate(() => window.hcp104Fixture.text())).toBe(
+ sentinel
+ );
+ expect(heldPeerRequest?.id).toBe(requests[1][1]);
+ expect(heldPeerRequest?.filter).toEqual(requests[1][2]);
+ expect(heldPeerRequest).toMatchObject({
+ eventSent: true,
+ eoseSent: false,
+ closed: false,
+ closedBeforeEose: false,
+ disconnectedBeforeCompletion: false
+ });
+ expect(
+ await page.evaluate(() => window.hcp104Fixture.snapshot()?.state)
+ ).toBe('needs_action');
+ expect(
+ await page.evaluate(async () => ({
+ native: await window.hcp104Fixture.native(),
+ delta: window.hcp104Fixture.delta()
+ }))
+ ).toEqual(before);
+ // Server REQ arrival is not consumer readiness. With the original run's
+ // virtual clock held, this exact subscription can finish only after its
+ // actual signed EVENT and released EOSE are consumed and cleaned up.
+ const originalPeerRequest = heldPeerRequest;
+ if (!originalPeerRequest) throw Error('missing original peer request');
+ originalPeerRequest.eoseSent = true;
+ originalPeerRequest.socket.send(
+ JSON.stringify(['EOSE', originalPeerRequest.id])
+ );
+ await expect.poll(() => originalPeerRequest.closed).toBe(true);
+ expect(originalPeerRequest.closedBeforeEose).toBe(false);
+ expect(originalPeerRequest.disconnectedBeforeCompletion).toBe(false);
+ expect(requests).toHaveLength(2);
+ expect(events).toEqual([]);
+ await page.evaluate(
+ (crossSecond) => window.hcp104Fixture.configureSendClock(crossSecond),
+ crossSecond
+ );
+ await page.evaluate(() => window.hcp104Fixture.resetDiagnostics());
+ const beforeSend = await page.evaluate(() =>
+ window.hcp104Fixture.diagnostic()
+ );
+ await composer(page)
+ .getByRole('button', { name: 'Send reply', exact: true })
+ .click();
+ // Once busy clears, needs_action is terminal until another explicit Send.
+ // Observe completion of the attempt before asserting its complete outcome.
+ await expect
+ .poll(() => page.evaluate(() => window.hcp104Fixture.snapshot()?.busy))
+ .toBe(false);
+ await page.evaluate(() => window.hcp104Fixture.restoreSendClock());
+ const terminal = await page.evaluate(async () => ({
+ snapshot: window.hcp104Fixture.snapshot(),
+ diagnostic: await window.hcp104Fixture.diagnostic(),
+ native: await window.hcp104Fixture.native(),
+ delta: window.hcp104Fixture.delta()
+ }));
+ if (crossSecond) {
+ expect(terminal.snapshot).toMatchObject({
+ state: 'needs_action',
+ busy: false,
+ dirty: true
+ });
+ expect(terminal.native).toEqual(before.native);
+ expect(terminal.delta).toEqual(before.delta);
+ expect(events).toEqual([]);
+ expect(await page.evaluate(() => window.hcp104Fixture.text())).toBe(
+ sentinel
+ );
+ expect(terminal.diagnostic.clicks).toBe(1);
+ expect(terminal.diagnostic.lockAttempts).toEqual([
+ {
+ name: 'harvestcircle:owner:' + terminal.diagnostic.setup.owner,
+ ifAvailable: true,
+ granted: true
+ }
+ ]);
+ expect(terminal.diagnostic.nativeTransactions).toEqual([
+ { stores: ['private_sends'], outcome: 'abort' }
+ ]);
+ expect(terminal.diagnostic.clockSamples).toHaveLength(2);
+ const [rumorTime, reservationTime] = terminal.diagnostic.clockSamples;
+ expect(rumorTime.stack).toContain('at Object.send');
+ expect(reservationTime.stack).toContain('<anonymous>');
+ expect(Math.floor(reservationTime.value / 1000)).toBeGreaterThan(
+ Math.floor(rumorTime.value / 1000)
+ );
+ expect(terminal.diagnostic.commandIds).toHaveLength(1);
+ const actualCommand = terminal.diagnostic.commandIds[0];
+ const pair = await page.evaluate(() => ({
+ owner: window.hcp104Fixture.owner,
+ peer: window.hcp104Fixture.peer,
+ parent: window.hcp104Fixture.parent
+ }));
+ const expectedRumor = buildCanonicalPairRumor(
+ JSON.stringify({
+ recipients: [{ public_key: pair.peer, relay_url: null }],
+ content: sentinel,
+ reply_to: { id: pair.parent, relays: null },
+ subject: null
+ }),
+ pair.owner,
+ Math.floor(rumorTime.value / 1000)
+ );
+ if (!expectedRumor) throw Error('missing canonical fixture rumor');
+ for (const row of before.native.sends) {
+ const wire = JSON.parse((row as { wire: string }).wire) as {
+ id: string;
+ rumorHash: string;
+ };
+ expect(wire.id).not.toBe(actualCommand);
+ expect(wire.rumorHash).not.toBe(expectedRumor.id);
+ }
+ const settledTrace = terminal.diagnostic;
+ expect(await page.evaluate(() => window.hcp104Fixture.send())).toEqual({
+ status: 'needs_action'
+ });
+ const afterRetry = await page.evaluate(async () => ({
+ native: await window.hcp104Fixture.native(),
+ delta: window.hcp104Fixture.delta(),
+ diagnostic: await window.hcp104Fixture.diagnostic(),
+ text: window.hcp104Fixture.text()
+ }));
+ expect(afterRetry.native).toEqual(before.native);
+ expect(afterRetry.delta).toEqual(before.delta);
+ expect(afterRetry.diagnostic).toEqual(settledTrace);
+ expect(afterRetry.text).toBe(sentinel);
+ expect(requests).toHaveLength(2);
+ expect(events).toEqual([]);
+ return;
+ }
+ expect(
+ terminal,
+ JSON.stringify({ beforeSend, terminal, published: events.length })
+ ).toMatchObject({
+ snapshot: { state: 'completed', busy: false }
+ });
+ expect(requests).toHaveLength(2);
+ expect(events).toHaveLength(2);
+ expect(
+ await page.evaluate(() => window.hcp104Fixture.delta())
+ ).toMatchObject({
+ encrypts: before.delta.encrypts + 2,
+ signs: before.delta.signs + 2
+ });
+ }
);
-});
+}
test('typing is memory only with no autosave SDK discovery publication or order transition', async ({
page
diff --git a/web/tests/e2e/support-report.spec.ts b/web/tests/e2e/support-report.spec.ts
@@ -0,0 +1,515 @@
+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 { createStaticHarness } from '../integration/harness/static.ts';
+import type * as Fixture from './harness/support-report.ts';
+declare global {
+ interface Window {
+ hcp124: typeof Fixture;
+ hcp124Private?: Awaited<ReturnType<typeof Fixture.createPrivateFixture>>;
+ hcp124Public?: Awaited<ReturnType<typeof Fixture.createPublicFixture>>;
+ hcp124General?: ReturnType<typeof Fixture.createGeneralFixture>;
+ hcp124Support?: ReturnType<typeof Fixture.createSupportFixture>;
+ hcp124Clipboard: string[];
+ hcp124PendingCopy?: Promise<'copied' | 'unavailable' | 'stopped'>;
+ hcp124FinishCopy?: () => void;
+ hcp124CopyStarted?: boolean;
+ }
+}
+
+// This case deliberately needs no future fixture/producer compilation. The
+// first preproducer run uses exact accepted HCP123 clean static output.
+test('HCP124 SSR practical About and honest missing support without private inventory', async ({
+ page
+}) => {
+ const server = await createStaticHarness();
+ try {
+ await page.addInitScript(() => {
+ Object.defineProperty(window, 'nostr', {
+ configurable: true,
+ get() {
+ throw Error('About must not acquire an extension');
+ }
+ });
+ });
+ await page.goto(server.url + '/about');
+ expect(await page.locator('h1').innerText()).toBe('About HarvestCircle');
+ await expect(
+ page.getByText('Search without connecting.', { exact: false })
+ ).toBeVisible();
+ await expect(
+ page.getByText('Messages do not reserve food or confirm an order.', {
+ exact: false
+ })
+ ).toBeVisible();
+ await expect(
+ page.getByText('Payments are not handled here.', { exact: false })
+ ).toBeVisible();
+ await expect(page.locator('#report')).toBeVisible();
+ await expect(
+ page.getByText('Support has not been configured.', { exact: false })
+ ).toBeVisible();
+ await expect(
+ page.getByRole('link', { name: 'Contact support', exact: true })
+ ).toHaveCount(0);
+ await expect(page.locator('input[type=checkbox]')).toHaveCount(0);
+ await expect(page).toHaveTitle('About — HarvestCircle');
+ } finally {
+ await server.close();
+ }
+});
+
+test.describe('HCP124 actual production selected-report controls', () => {
+ let server: Awaited<ReturnType<typeof createStaticHarness>>,
+ sockets: WebSocketServer,
+ endpoint: string,
+ bundle: string | undefined;
+ let publicEvents: unknown[] = [],
+ events: unknown[][] = [],
+ queries: unknown[][] = [];
+ 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('controlled loopback unavailable');
+ 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') events.push(frame);
+ if (frame[0] === 'REQ') {
+ queries.push(frame);
+ const filters = frame.slice(2) as {
+ kinds?: number[];
+ ids?: string[];
+ }[];
+ if (filters.some((filter) => filter.kinds?.includes(30402)))
+ for (const event of publicEvents)
+ 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) => sockets.close(() => resolve()));
+ await server?.close();
+ });
+ test.beforeEach(async ({ page }) => {
+ publicEvents = [];
+ events = [];
+ queries = [];
+ await page.addInitScript((endpoint) => {
+ const Native = window.WebSocket;
+ window.WebSocket = class extends Native {
+ constructor(url: string | URL, protocols?: string | string[]) {
+ if (
+ ![
+ 'wss://peer.example.org',
+ 'wss://archive.example.org',
+ 'wss://discovery.example.org'
+ ].includes(new URL(String(url)).origin)
+ )
+ throw Error('no live relay authorization');
+ super(endpoint, protocols);
+ }
+ };
+ window.hcp124Clipboard = [];
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: {
+ writeText: (text: string) => {
+ window.hcp124Clipboard.push(text);
+ return Promise.resolve();
+ }
+ }
+ });
+ }, endpoint);
+ });
+ test.afterEach(async ({ page }) => {
+ if (!page.isClosed())
+ await page.evaluate(async () => {
+ await window.hcp124Private?.close();
+ await window.hcp124Public?.close();
+ await window.hcp124General?.close();
+ await window.hcp124Support?.close();
+ });
+ });
+ async function load(page: Page) {
+ await page.goto(server.url + '/about');
+ if (!bundle) {
+ const output = await build({
+ configFile: false,
+ root: process.cwd(),
+ logLevel: 'silent',
+ plugins: [
+ svelte({ configFile: false, compilerOptions: { dev: false } })
+ ],
+ resolve: {
+ conditions: ['browser'],
+ alias: {
+ '$app/navigation': fileURLToPath(
+ new URL('./harness/conversation-thread.ts', import.meta.url)
+ )
+ }
+ },
+ build: {
+ write: false,
+ emptyOutDir: false,
+ minify: false,
+ lib: {
+ entry: fileURLToPath(
+ new URL('./harness/support-report.ts', import.meta.url)
+ ),
+ name: 'hcp124',
+ formats: ['iife']
+ }
+ }
+ });
+ const result = Array.isArray(output) ? output[0] : output;
+ if (!result || !('output' in result))
+ throw Error('fixture output unavailable');
+ const chunks = result.output.filter((row) => row.type === 'chunk');
+ expect(chunks).toHaveLength(1);
+ const chunk = chunks[0];
+ bundle = chunk.code;
+ }
+ await page.addScriptTag({ content: bundle });
+ }
+ async function privateReport(page: Page) {
+ await load(page);
+ await page.evaluate(async () => {
+ window.hcp124Private = await window.hcp124.createPrivateFixture();
+ });
+ await page.evaluate(() => window.hcp124Private!.checkSetup());
+ expect(await page.evaluate(() => window.hcp124Private!.unlock())).toBe(
+ true
+ );
+ await expect
+ .poll(() =>
+ page.evaluate(() => window.hcp124Private!.thread().messages.length)
+ )
+ .toBe(3);
+ await expect
+ .poll(() =>
+ page.evaluate(
+ async () =>
+ (await window.hcp124Private!.native()).received.filter((row) => {
+ const parsed = JSON.parse((row as { wire: string }).wire) as {
+ read: unknown;
+ };
+ return parsed.read !== null;
+ }).length
+ )
+ )
+ .toBe(3);
+ await page.evaluate(async () => {
+ await window.hcp124Private!.waitOwner();
+ window.hcp124Private!.report();
+ });
+ await expect(page.locator('#hcp124-report-fixture')).toBeVisible();
+ }
+ const panel = (page: Page) => page.locator('#hcp124-report-fixture');
+
+ test('actual support link has the reviewed destination without transcript carrier or automatic navigation', async ({
+ page
+ }) => {
+ await load(page);
+ await page.evaluate(() => {
+ window.hcp124Support = window.hcp124.createSupportFixture();
+ });
+ const link = page
+ .locator('#hcp124-support-fixture')
+ .getByRole('link', { name: 'Contact support', exact: true });
+ await expect(link).toHaveAttribute(
+ 'href',
+ 'https://support.operator.org/report'
+ );
+ await expect(link).toHaveAttribute('rel', /noopener/);
+ await expect(link).toHaveAttribute('rel', /noreferrer/);
+ await expect(link).toHaveAttribute('referrerpolicy', 'no-referrer');
+ expect(page.url()).toBe(server.url + '/about');
+ expect(events).toEqual([]);
+ expect(queries).toEqual([]);
+ });
+ test('voluntary plain notes require explicit review and optional copy without support transport', async ({
+ page
+ }) => {
+ await load(page);
+ await page.evaluate(() => {
+ window.hcp124General = window.hcp124.createGeneralFixture();
+ });
+ await panel(page)
+ .getByLabel('Problem description')
+ .fill('<img src=x> Deliberately selected description');
+ expect(await page.evaluate(() => window.hcp124Clipboard)).toEqual([]);
+ await panel(page)
+ .getByRole('button', { name: 'Review report', exact: true })
+ .click();
+ await expect(
+ panel(page).getByRole('region', { name: 'Selected report preview' })
+ ).toContainText('<img src=x> Deliberately selected description');
+ await expect(panel(page).locator('img')).toHaveCount(0);
+ await panel(page)
+ .getByRole('button', { name: 'Copy reviewed report', exact: true })
+ .click();
+ expect(await page.evaluate(() => window.hcp124Clipboard.length)).toBe(1);
+ expect(events).toEqual([]);
+ expect(queries).toEqual([]);
+ expect(page.url()).toBe(server.url + '/about');
+ });
+ test('private message and peer choices start unselected and no transcript is copied automatically', async ({
+ page
+ }) => {
+ await privateReport(page);
+ expect(
+ await panel(page).locator('input[type=checkbox]:checked').count()
+ ).toBe(0);
+ await expect(
+ panel(page).getByRole('region', { name: 'Selected report preview' })
+ ).toHaveCount(0);
+ expect(await page.evaluate(() => window.hcp124Clipboard)).toEqual([]);
+ await expect(
+ panel(page).getByText(
+ 'Support cannot automatically read encrypted messages.',
+ { exact: false }
+ )
+ ).toBeVisible();
+ await expect(
+ panel(page).getByText(
+ 'Copied text can remain in your clipboard or other applications.',
+ { exact: false }
+ )
+ ).toBeVisible();
+ });
+ test('selected private text needs extra acknowledgment and excludes every unselected message and owner', async ({
+ page
+ }) => {
+ await privateReport(page);
+ const before = await page.evaluate(async () => ({
+ native: await window.hcp124Private!.native(),
+ delta: window.hcp124Private!.delta(),
+ owner: window.hcp124Private!.owner,
+ peer: window.hcp124Private!.peer
+ }));
+ await panel(page)
+ .getByLabel('Share message text and ID 1', { exact: true })
+ .check();
+ await panel(page)
+ .getByRole('button', { name: 'Review report', exact: true })
+ .click();
+ await expect(
+ panel(page).getByRole('region', { name: 'Selected report preview' })
+ ).toHaveCount(0);
+ await panel(page)
+ .getByLabel(
+ 'I understand selected private information will leave HarvestCircle if I share it.',
+ { exact: true }
+ )
+ .check();
+ await panel(page)
+ .getByRole('button', { name: 'Review report', exact: true })
+ .click();
+ const text = await panel(page)
+ .getByRole('region', { name: 'Selected report preview' })
+ .innerText();
+ expect(text).toContain('Actual encrypted thread fixture');
+ expect(text).not.toContain('About carrots');
+ expect(text).not.toContain('About apples');
+ expect(text).not.toContain(before.owner);
+ expect(text).not.toContain(before.peer);
+ await panel(page)
+ .getByRole('button', { name: 'Copy reviewed report', exact: true })
+ .click();
+ expect(await page.evaluate(() => window.hcp124Clipboard)).toEqual([text]);
+ expect(await page.evaluate(() => window.hcp124Private!.delta())).toEqual(
+ before.delta
+ );
+ expect(await page.evaluate(() => window.hcp124Private!.native())).toEqual(
+ before.native
+ );
+ expect(events).toEqual([]);
+ const support = panel(page).getByRole('link', {
+ name: 'Contact support',
+ exact: true
+ });
+ await expect(support).toHaveAttribute(
+ 'href',
+ 'https://support.operator.org/report'
+ );
+ });
+ test('genuine logout retires an already captured selected private preview before copy', async ({
+ page
+ }) => {
+ await privateReport(page);
+ expect(
+ await page.evaluate(() => window.hcp124Private!.captureSelected())
+ ).toContain('Actual encrypted thread fixture');
+ await page.evaluate(() => window.hcp124Private!.logout());
+ expect(
+ await page.evaluate(() => window.hcp124Private!.captured())
+ ).toBeUndefined();
+ expect(
+ await page.evaluate(() => window.hcp124Private!.copyCaptured())
+ ).toBe('stopped');
+ expect(await page.evaluate(() => window.hcp124Clipboard)).toEqual([]);
+ await expect(
+ panel(page).getByRole('region', { name: 'Selected report preview' })
+ ).toHaveCount(0);
+ });
+ test('an already requested clipboard copy can finish after logout without claiming current success', async ({
+ page
+ }) => {
+ await privateReport(page);
+ const selected = await page.evaluate(() =>
+ window.hcp124Private!.captureSelected()
+ );
+ await page.evaluate(() => {
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: {
+ writeText: (text: string) =>
+ new Promise<void>((resolve) => {
+ window.hcp124CopyStarted = true;
+ window.hcp124FinishCopy = () => {
+ window.hcp124Clipboard.push(text);
+ resolve();
+ };
+ })
+ }
+ });
+ window.hcp124PendingCopy = window.hcp124Private!.copyCaptured();
+ });
+ await expect
+ .poll(() => page.evaluate(() => window.hcp124CopyStarted))
+ .toBe(true);
+ expect(await page.evaluate(() => window.hcp124Clipboard)).toEqual([]);
+ await page.evaluate(() => window.hcp124Private!.logout());
+ expect(
+ await page.evaluate(() => window.hcp124Private!.captured())
+ ).toBeUndefined();
+ const outcome = await page.evaluate(async () => {
+ window.hcp124FinishCopy!();
+ return await window.hcp124PendingCopy;
+ });
+ expect(outcome).toBe('stopped');
+ expect(await page.evaluate(() => window.hcp124Clipboard)).toEqual([
+ selected
+ ]);
+ await expect(
+ panel(page).getByRole('region', { name: 'Selected report preview' })
+ ).toHaveCount(0);
+ expect(events).toEqual([]);
+ });
+ test('acknowledged real native block retires captured private report with encrypted evidence retained', async ({
+ page
+ }) => {
+ await privateReport(page);
+ await page.evaluate(() => window.hcp124Private!.captureSelected());
+ const before = await page.evaluate(() => window.hcp124Private!.native());
+ expect(await page.evaluate(() => window.hcp124Private!.block())).toEqual({
+ status: 'saved'
+ });
+ expect(
+ await page.evaluate(() => window.hcp124Private!.captured())
+ ).toBeUndefined();
+ expect(
+ await page.evaluate(() => window.hcp124Private!.copyCaptured())
+ ).toBe('stopped');
+ expect(await page.evaluate(() => window.hcp124Clipboard)).toEqual([]);
+ expect(await page.evaluate(() => window.hcp124Private!.native())).toEqual(
+ before
+ );
+ });
+ test('actual signed public listing copies only separately selected version and coordinate', async ({
+ page
+ }) => {
+ await load(page);
+ publicEvents = await page.evaluate(async () => {
+ window.hcp124Public = await window.hcp124.createPublicFixture();
+ return window.hcp124Public.events;
+ });
+ await page.evaluate(() => window.hcp124Public!.read());
+ await expect
+ .poll(() =>
+ page.evaluate(() => window.hcp124Public!.publicSnapshot()?.outcome)
+ )
+ .toBe('active');
+ const selected = await page.evaluate(() => window.hcp124Public!.report());
+ expect(selected?.kind).toBe('listing');
+ expect(
+ await panel(page).locator('input[type=checkbox]:checked').count()
+ ).toBe(0);
+ await panel(page)
+ .getByLabel('Share listing version', { exact: true })
+ .check();
+ await panel(page)
+ .getByRole('button', { name: 'Review report', exact: true })
+ .click();
+ const text = await panel(page)
+ .getByRole('region', { name: 'Selected report preview' })
+ .innerText();
+ expect(text).toContain((publicEvents[0] as { id: string }).id);
+ expect(text).not.toContain('Coordinate:');
+ await panel(page).getByLabel('Share coordinate', { exact: true }).check();
+ await panel(page)
+ .getByRole('button', { name: 'Review report', exact: true })
+ .click();
+ await expect(
+ panel(page).getByRole('region', { name: 'Selected report preview' })
+ ).toContainText('30402:');
+ expect(events).toEqual([]);
+ });
+ for (const width of [320, 1024])
+ test(
+ 'HCP124 ' +
+ width +
+ ' private report selection and disclosure reflow without hidden confirmation',
+ async ({ page }) => {
+ await page.setViewportSize({ width, height: 900 });
+ await privateReport(page);
+ await panel(page)
+ .getByLabel('Share message text and ID 1', { exact: true })
+ .check();
+ await panel(page)
+ .getByLabel(
+ 'I understand selected private information will leave HarvestCircle if I share it.',
+ { exact: true }
+ )
+ .check();
+ await panel(page)
+ .getByRole('button', { name: 'Review report', exact: true })
+ .click();
+ await expect(
+ panel(page).getByRole('region', { name: 'Selected report preview' })
+ ).toBeVisible();
+ expect(
+ await page.evaluate(
+ () => document.documentElement.scrollWidth <= window.innerWidth
+ )
+ ).toBe(true);
+ await expect(
+ panel(page).getByRole('button', {
+ name: 'Copy reviewed report',
+ exact: true
+ })
+ ).toBeVisible();
+ }
+ );
+});
diff --git a/web/tests/integration/loopback.test.ts b/web/tests/integration/loopback.test.ts
@@ -94,6 +94,16 @@ await test('navigation fallback serves actual separate output and preserves miss
assert.doesNotMatch(html, /<form|<input|<textarea/);
}
assert.notEqual(search, fallback);
+ const about = prerendered.get('/about');
+ assert.ok(about);
+ assert.match(about, /About HarvestCircle/);
+ assert.match(about, /Search without connecting\./);
+ assert.match(about, /Support has not been configured\./);
+ assert.match(about, /id="report"/);
+ assert.doesNotMatch(
+ about,
+ /Contact support|Selected report preview|Share message text|mailto:|[0-9a-f]{64}/
+ );
assert.match(search, /<title>Search food — HarvestCircle<\/title>/);
assert.match(search, /Search sources are unavailable\./);
const privacy = prerendered.get('/privacy');
diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs
@@ -131,6 +131,26 @@ import { auditOutput } from '../../tools/check-output.mjs';
async function restoreHistoricalPublicProducers(web) {
for (const [name, value] of Object.entries({
...{
+ 'src/routes/about/+page.svelte': {
+ source:
+ '<svelte:head><title>About \u2014 HarvestCircle</title></svelte:head>\n<div class="page page--reading stack">\n <h1>About</h1>\n <p class="notice">\n Information about HarvestCircle is unavailable during development.\n </p>\n <section id="help">\n <h2>Help / report</h2>\n <p>Help and reporting are unavailable during development.</p>\n </section>\n</div>\n',
+ sha256:
+ 'eb405489e948426aee5716354304e8d6fb4dffcfefc9f6836470e3f5e02623a7'
+ },
+ '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 import PublisherHide from '../../../lib/components/PublisherHide.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 {#if productOwner && result.eventId}\n <Disclosure summary=\"Publisher controls\"\n ><PublisherHide view={productOwner} /></Disclosure\n >\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 <a href={internalHref('/privacy')}>Privacy and local publisher controls</a>\n</div>\n",
+ sha256:
+ 'd3afe029ad6ed6384a300ad6719f32c324a1841271eddf9baee5b8f31f54e680'
+ },
+ 'src/lib/components/ConversationOptions.svelte': {
+ source:
+ "<script lang=\"ts\">\n import { onMount } from 'svelte';\n import {\n subscribeInboxView,\n blockInboxConversation,\n type InboxView\n } from '../messaging/inbox-view.ts';\n import {\n conversationOptionsSnapshot,\n requestConversationOption\n } from '../messaging/cited-product.ts';\n let {\n controller,\n conversationId,\n onblock,\n onreport\n }: {\n controller: InboxView;\n conversationId: string;\n onblock?: (peer: string) => void;\n onreport?: (peer: string) => void;\n } = $props();\n let revision = $state(0);\n let reviewing = $state(false),\n busy = $state(false),\n notice = $state<string | undefined>();\n async function confirmBlock() {\n if (!reviewing || busy) return;\n busy = true;\n const result = await blockInboxConversation(\n controller,\n conversationId,\n 'reviewed_local_private_block'\n );\n busy = false;\n reviewing = false;\n notice =\n result.status === 'saved' || result.status === 'existing'\n ? 'Person blocked in this browser.'\n : 'Block was not confirmed. Existing local data has not been reset.';\n }\n const actual = $derived.by(() => {\n void revision;\n return conversationOptionsSnapshot(controller, conversationId);\n });\n onMount(() =>\n subscribeInboxView(controller, () => {\n revision++;\n })\n );\n</script>\n\n{#if actual}\n <details>\n <summary>Identity and conversation options</summary>\n <p>Authenticated conversation peer: {actual.peer}</p>\n <button\n type=\"button\"\n onclick={() => {\n if (onblock)\n requestConversationOption(\n controller,\n conversationId,\n 'block',\n onblock,\n 'reviewed_conversation_option'\n );\n else reviewing = true;\n }}>Block person</button\n >\n {#if reviewing}\n <p>\n Blocking hides messages and previews for this account in this browser\n and may discard unsaved private text. Encrypted evidence, delivery\n receipts and remote copies remain. It sends no report or sender\n notification and does not accept or reject an order. Undo is available\n in Privacy.\n </p>\n <button type=\"button\" disabled={busy} onclick={() => void confirmBlock()}\n >Confirm local block</button\n >\n <button\n type=\"button\"\n disabled={busy}\n onclick={() => {\n reviewing = false;\n }}>Cancel</button\n >\n {/if}\n {#if notice}<p role=\"status\">{notice}</p>{/if}\n {#if onreport}<button\n type=\"button\"\n onclick={() => {\n if (onreport)\n requestConversationOption(\n controller,\n conversationId,\n 'report',\n onreport,\n 'reviewed_conversation_option'\n );\n }}>Report conversation</button\n >{/if}\n </details>\n{/if}\n",
+ sha256:
+ 'b40915c0b11456fbc852d67591fd4c629a33d5b271e79b79dd042fcf2c0f74cb'
+ }
+ },
+ ...{
'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",
@@ -683,7 +703,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, 55);
+ assert.equal(files.length, 57);
// 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(
@@ -754,7 +774,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
await refresh(f);
await assert.rejects(
f.audit,
- /inbox presentation source|Invalid owned private blocking source/
+ /inbox presentation source|Invalid owned private blocking source|Invalid owned support reporting source/
);
}
);
@@ -930,7 +950,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
await refresh(f);
await assert.rejects(
f.audit,
- /inbox compiler source|Invalid owned private blocking source/
+ /inbox compiler source|Invalid owned private blocking source|Invalid owned support reporting source/
);
}
);
@@ -973,7 +993,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
assert.ok(Buffer.byteLength(expanded) > 64 * 1024);
await writeFile(file, expanded);
await refresh(f);
- assert.equal((await f.audit()).length, 55);
+ assert.equal((await f.audit()).length, 57);
}
);
@@ -1461,7 +1481,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
}
);
await check(
- 'actual shared budgets chunk has owned consumers and counterpart',
+ 'actual shared budgets/navigation validator chunk has owned consumers and counterpart',
async (t) => {
const f = await fixture(t);
const manifest = JSON.parse(
@@ -1474,34 +1494,27 @@ import { auditOutput } from '../../tools/check-output.mjs';
)
);
const entries = Object.entries(manifest).filter(
- ([, record]) => record.name === 'Button'
+ ([, record]) => record.name === 'navigation-url'
);
assert.equal(entries.length, 1);
const [key, budget] = entries[0];
- assert.deepEqual(Object.keys(budget).sort(), [
- 'file',
- 'imports',
- 'name'
- ]);
- const client = Object.entries(manifest).find(
- ([, record]) => record.name === 'client'
- );
- assert.ok(client);
- assert.deepEqual(budget.imports, [client[0]]);
+ assert.deepEqual(Object.keys(budget).sort(), ['file', 'name']);
for (const name of [
- Object.values(manifest).some(
- (row) => row.name === 'public-runtime'
- )
- ? 'public-runtime'
- : 'Disclosure',
+ 'public-runtime',
'nodes/9',
- 'routes'
- ])
+ 'routes',
+ 'Button',
+ 'ReportPreview'
+ ]) {
+ const consumer = Object.values(manifest).find(
+ (record) => record.name === name
+ );
+ assert.ok(consumer, 'Missing actual budget consumer ' + name);
assert.ok(
- Object.values(manifest)
- .find((record) => record.name === name)
- .imports.includes(key)
+ consumer.imports.includes(key),
+ 'Missing actual shared budget edge from ' + name
);
+ }
assert.deepEqual(
await readFile(path.join(f.web, 'build', budget.file)),
await readFile(
@@ -1610,7 +1623,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
await refresh(f);
await assert.rejects(
f.audit,
- /Invalid owned listing editor source|Invalid owned public hiding source|Invalid owned private blocking source/
+ /Invalid owned listing editor source|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source/
);
}
);
@@ -1632,7 +1645,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
await refresh(f);
await assert.rejects(
f.audit,
- /Invalid owned selling workspace source|Invalid owned public hiding source|Invalid owned private blocking source/
+ /Invalid owned selling workspace source|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source/
);
}
);
@@ -1662,7 +1675,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
await refresh(f);
await assert.rejects(
f.audit,
- /Invalid owned (public hiding source|private blocking source|root runtime activation)/
+ /Invalid owned (public hiding source|private blocking source|support reporting source|root runtime activation)/
);
}
);
@@ -1700,7 +1713,48 @@ import { auditOutput } from '../../tools/check-output.mjs';
await refresh(f);
await assert.rejects(
f.audit,
- /Invalid owned (private blocking source|root runtime activation)/
+ /Invalid owned (private blocking source|support reporting source|root runtime activation)/
+ );
+ }
+ );
+ }
+ for (const producer of [
+ 'src/lib/config/support.ts',
+ 'src/lib/config/deployment-support.ts',
+ 'src/lib/support/report.ts',
+ 'src/lib/components/ReportPreview.svelte',
+ 'src/lib/components/SupportLink.svelte',
+ 'src/routes/about/+page.svelte',
+ 'src/routes/products/[naddr=naddr]/+page.svelte',
+ 'src/lib/components/ConversationOptions.svelte',
+ 'src/lib/navigation-url.ts'
+ ]) {
+ await check(
+ 'support reporting rejects changed owned producer ' + producer,
+ async (t) => {
+ const f = await fixture(t);
+ const file = path.join(f.web, producer);
+ await writeFile(
+ file,
+ (await readFile(file, 'utf8')) +
+ '\n// changed support reporting producer\n'
+ );
+ await refresh(f);
+ await assert.rejects(
+ f.audit,
+ /Invalid owned support reporting source/
+ );
+ }
+ );
+ await check(
+ 'support reporting rejects missing owned producer ' + producer,
+ async (t) => {
+ const f = await fixture(t);
+ await rm(path.join(f.web, producer));
+ await refresh(f);
+ await assert.rejects(
+ f.audit,
+ /ENOENT|support reporting|incomplete route source/
);
}
);
@@ -1723,7 +1777,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
await refresh(f);
await assert.rejects(
f.audit,
- /Invalid owned listing editor activation|Invalid owned public hiding source|Invalid owned private blocking source/
+ /Invalid owned listing editor activation|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source/
);
}
);
@@ -1759,8 +1813,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 public hiding source|Invalid owned private blocking source/
- : /Invalid owned product presentation source|Invalid owned public hiding source|Invalid owned private blocking source/
+ ? /Invalid owned (product presentation|listing editor) source|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source/
+ : /Invalid owned product presentation source|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source/
);
}
);
@@ -1866,6 +1920,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
'.svelte-kit/output/client/.vite/manifest.json'
);
const manifest = JSON.parse(await readFile(file, 'utf8'));
+ const original = JSON.stringify(manifest);
const records = Object.entries(manifest);
const find = (/** @type {string} */ name) => {
const row = records.find(([, v]) => v.name === name);
@@ -1888,7 +1943,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
key !==
find(
mutation === 'publisher-budget'
- ? 'Button'
+ ? 'navigation-url'
: Object.values(manifest).some(
(row) => row.name === 'public-runtime'
)
@@ -1901,7 +1956,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
mutation === 'search-publisher'
? 'nodes/9'
: mutation === 'product-publisher'
- ? 'MessageComposer'
+ ? 'ReportPreview'
: 'nodes/7';
const dependency =
mutation === 'product-shared'
@@ -1913,6 +1968,11 @@ import { auditOutput } from '../../tools/check-output.mjs';
(/** @type {string} */ key) => key !== find(dependency)[0]
);
}
+ assert.notEqual(
+ JSON.stringify(manifest),
+ original,
+ 'Every product graph mutation must change the actual input'
+ );
await writeFile(file, JSON.stringify(manifest));
await assert.rejects(f.audit, /compiler|budgets/);
}
@@ -1938,7 +1998,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
await refresh(f);
await assert.rejects(
f.audit,
- /Invalid owned search presentation source|Invalid owned public hiding source|Invalid owned private blocking source/
+ /Invalid owned search presentation source|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source/
);
}
);
@@ -1963,6 +2023,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
'.svelte-kit/output/client/.vite/manifest.json'
);
const manifest = JSON.parse(await readFile(file, 'utf8'));
+ const original = JSON.stringify(manifest);
const records = Object.entries(manifest);
const find = (/** @type {string} */ name) => {
const entry = records.find(([, v]) => v.name === name);
@@ -1976,7 +2037,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
? 'public-runtime'
: 'Disclosure'
);
- const [budgetKey] = find('Button');
+ const [budgetKey] = find('navigation-url');
if (mutation === 'missing-shared') delete manifest[sharedKey];
else if (mutation === 'missing-navigation')
delete manifest[find('navigation')[0]];
@@ -2007,6 +2068,11 @@ import { auditOutput } from '../../tools/check-output.mjs';
(/** @type {string} */ k) => k !== find('references')[0]
);
else shared.dynamicImports = [];
+ assert.notEqual(
+ JSON.stringify(manifest),
+ original,
+ 'Every search graph mutation must change the actual input'
+ );
await writeFile(file, JSON.stringify(manifest));
await assert.rejects(f.audit, /compiler|SDK|budgets/);
});
@@ -2028,8 +2094,9 @@ import { auditOutput } from '../../tools/check-output.mjs';
'.svelte-kit/output/client/.vite/manifest.json'
);
const manifest = JSON.parse(await readFile(file, 'utf8'));
+ const original = JSON.stringify(manifest);
const entry = Object.entries(manifest).find(
- ([, record]) => record.name === 'Button'
+ ([, record]) => record.name === 'navigation-url'
);
assert.ok(entry);
const [key, budget] = entry;
@@ -2059,6 +2126,14 @@ import { auditOutput } from '../../tools/check-output.mjs';
path.join(f.web, 'build', budget.file),
'changed counterpart'
);
+ if (
+ !['missing-counterpart', 'changed-counterpart'].includes(mutation)
+ )
+ assert.notEqual(
+ JSON.stringify(manifest),
+ original,
+ 'Every budgets graph mutation must change the actual input'
+ );
await writeFile(file, JSON.stringify(manifest));
await assert.rejects(
f.audit,
@@ -2167,7 +2242,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
(dependency) => manifest[dependency].name === 'client'
)
);
- for (const consumer of ['nodes/0', 'nodes/2']) {
+ for (const consumer of ['nodes/0', 'nodes/9']) {
assert.ok(
Object.values(manifest).some(
(record) =>
diff --git a/web/tests/provenance/source-boundaries.test.mjs b/web/tests/provenance/source-boundaries.test.mjs
@@ -105,6 +105,50 @@ test('HCP044 clipboard access is confined to the exact public copy producer', as
const root = fileURLToPath(new URL('../../', import.meta.url));
/** @typedef {{directory: string, put: (name: string, content: string | Uint8Array) => Promise<void>, execute: (args?: string[]) => import('node:child_process').SpawnSyncReturns<string>, pkg: Record<string, unknown>}} Fixture */
+test('HCP124 selected report clipboard is confined to the exact original producer', async () => {
+ await fixture(async ({ put, execute }) => {
+ const report = await readFile(
+ path.join(root, 'src/lib/support/report.ts'),
+ 'utf8'
+ );
+ // Source grammar only. These inert exports cannot qualify runtime ownership.
+ await put(
+ 'src/lib/catalog/product-view.ts',
+ 'export function productViewSnapshot(){return undefined;} export function productViewPublisherProof(){return undefined;} export type ProductView = {};'
+ );
+ await put(
+ 'src/lib/nostr/verified-envelope.ts',
+ 'export function verifiedEnvelopeSnapshot(){return undefined;}'
+ );
+ await put(
+ 'src/lib/messaging/inbox-view.ts',
+ 'export function inboxThreadSnapshot(){return undefined;} export function inboxReplyOwnership(){return undefined;} export function subscribeInboxView(){return ()=>{};} export type InboxView = {};'
+ );
+ await put('src/lib/support/report.ts', report);
+ const positive = execute();
+ assert.equal(positive.status, 0, positive.stdout + positive.stderr);
+ for (const code of [
+ 'navigator.clipboard.writeText("private");',
+ 'const clipboard=navigator.clipboard;clipboard.writeText("private");',
+ 'navigator.clipboard.readText();',
+ 'Reflect.get(navigator.clipboard,"writeText")("private");',
+ 'window.navigator.clipboard.writeText("private");'
+ ]) {
+ await put('src/routes/+page.ts', code);
+ reject(execute(), /clipboard|navigator|reflection/);
+ }
+ await put('src/routes/+page.ts', 'export const value=1;');
+ await put(
+ 'src/lib/support/report.ts',
+ report + '\nnavigator.clipboard.readText();'
+ );
+ reject(execute(), /report.*identity|clipboard/);
+ await put('src/lib/support/report.ts', report);
+ await put('src/lib/support/copied-report.ts', report);
+ reject(execute(), /clipboard|navigator|reflection/);
+ });
+});
+
/** @param {(context: Fixture) => Promise<void>} run */
async function fixture(run) {
const directory = await realpath(
diff --git a/web/tests/unit/report-preview.test.ts b/web/tests/unit/report-preview.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ createGeneralReport,
+ createListingReport,
+ createConversationReport,
+ reviewReportPreview,
+ reportPreviewSnapshot,
+ copyReportPreview,
+ closeReportContext,
+ type ReportContext,
+ type ReportPreview
+} from '../../src/lib/support/report.ts';
+import type { ProductView } from '../../src/lib/catalog/product-view.ts';
+import type { InboxView } from '../../src/lib/messaging/inbox-view.ts';
+
+const selection = (notes: string, extra: Record<string, unknown> = {}) =>
+ JSON.stringify({
+ listingVersion: false,
+ coordinate: false,
+ peer: false,
+ messages: [],
+ notes,
+ privateDisclosure: false,
+ ...extra
+ });
+
+describe('HCP124 deliberately selected local report preview', () => {
+ it('general notes are explicitly selected plain memory text, without hidden context', () => {
+ const context = createGeneralReport();
+ const preview = reviewReportPreview(
+ context,
+ selection('A deliberately typed problem description.'),
+ 'reviewed_report_preview'
+ );
+ expect(preview).toBeDefined();
+ if (!preview) throw Error('explicit general preview');
+ const text = reportPreviewSnapshot(preview);
+ expect(text).toContain('A deliberately typed problem description.');
+ expect(text).not.toMatch(/Peer:|Message:|Listing version:|Coordinate:/);
+ closeReportContext(context);
+ expect(reportPreviewSnapshot(preview)).toBeUndefined();
+ });
+ it('an empty unreviewed report cannot become a copyable preview', () => {
+ const context = createGeneralReport();
+ expect(
+ reviewReportPreview(context, selection(''), 'reviewed_report_preview')
+ ).toBeUndefined();
+ expect(
+ reviewReportPreview(context, selection('notes'), 'not reviewed')
+ ).toBeUndefined();
+ closeReportContext(context);
+ });
+ it('copied context, preview and private fields never reveal a transcript', () => {
+ const fake = {
+ kind: 'conversation',
+ peer: 'a'.repeat(64),
+ messages: [{ id: 'b'.repeat(64), content: 'PRIVATE_UNSELECTED_SENTINEL' }]
+ };
+ expect(
+ reviewReportPreview(
+ fake as unknown as ReportContext,
+ selection('notes', {
+ peer: true,
+ messages: ['b'.repeat(64)],
+ privateDisclosure: true
+ }),
+ 'reviewed_report_preview'
+ )
+ ).toBeUndefined();
+ expect(
+ reportPreviewSnapshot({
+ text: 'PRIVATE_UNSELECTED_SENTINEL'
+ } as unknown as ReportPreview)
+ ).toBeUndefined();
+ expect(createListingReport(fake as unknown as ProductView)).toBeUndefined();
+ expect(
+ createConversationReport(
+ fake as unknown as InboxView,
+ '00000000-0000-4000-8000-000000000000'
+ )
+ ).toBeUndefined();
+ });
+ it('unknown, ill-formed and irrelevant selection fields do not silently attach data', () => {
+ const context = createGeneralReport();
+ for (const raw of [
+ '{',
+ selection('notes', { transcript: 'PRIVATE_SENTINEL' }),
+ selection('notes', { messages: ['b'.repeat(64)] }),
+ selection('notes', { peer: true }),
+ selection('notes', { listingVersion: true }),
+ selection('\ud800'),
+ selection('notes', { privateDisclosure: 'yes' })
+ ])
+ expect(
+ reviewReportPreview(context, raw, 'reviewed_report_preview')
+ ).toBeUndefined();
+ closeReportContext(context);
+ });
+ it('SSR preview preparation never acquires clipboard or private browser authority', async () => {
+ vi.stubGlobal('window', undefined);
+ let reads = 0;
+ vi.stubGlobal('navigator', {
+ get clipboard() {
+ reads++;
+ throw Error('SSR must not acquire clipboard');
+ }
+ });
+ try {
+ const context = createGeneralReport();
+ const preview = reviewReportPreview(
+ context,
+ selection('Explicit SSR notes'),
+ 'reviewed_report_preview'
+ );
+ expect(preview).toBeDefined();
+ if (!preview) throw Error('pure SSR preview');
+ expect(await copyReportPreview(preview, 'reviewed_copy_report')).toBe(
+ 'unavailable'
+ );
+ expect(reads).toBe(0);
+ closeReportContext(context);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+});
diff --git a/web/tests/unit/route-inventory.test.ts b/web/tests/unit/route-inventory.test.ts
@@ -154,7 +154,16 @@ describe('thin protected route SSR', () => {
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(About).body).toContain('About HarvestCircle');
+ expect(render(About).body).toContain('Search without connecting.');
+ expect(render(About).body).toContain(
+ 'Messages do not reserve food or confirm an order.'
+ );
+ expect(render(About).body).toContain('Support has not been configured.');
+ expect(render(About).body).toContain('id="report"');
+ expect(render(About).body).not.toMatch(
+ /Contact support|Selected report preview|Share message text|[0-9a-f]{64}/
+ );
expect(render(Privacy).body).toContain('Hiding a publisher is local');
expect(render(Privacy).body).toContain('Blocking a person is local');
expect(render(Privacy).body.replace(/\s+/g, ' ')).toContain(
diff --git a/web/tests/unit/support-config.test.ts b/web/tests/unit/support-config.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it } from 'vitest';
+import {
+ validateSupportPolicy,
+ readSupportPolicy,
+ requireLaunchSupportPolicy,
+ type SupportPolicy
+} from '../../src/lib/config/support.ts';
+
+// Parser-only, explicitly controlled values. No destination is contacted or
+// presented as the actual deployment's approved support owner/destination.
+const fixture = {
+ schemaVersion: 1,
+ owner: 'Controlled fixture operator',
+ destination: 'mailto:reports@operator.org'
+};
+const raw = (fields: Record<string, unknown> = {}) =>
+ JSON.stringify({ ...fixture, ...fields });
+
+describe('HCP124 original bounded deployment support configuration', () => {
+ it('admits the exact inert fixture and returns a detached snapshot', () => {
+ const policy = validateSupportPolicy(raw());
+ expect(policy).toBeDefined();
+ if (!policy) throw Error('fixture admission');
+ expect(readSupportPolicy(policy)).toEqual(fixture);
+ const detached = readSupportPolicy(policy) as { owner: string };
+ detached.owner = 'changed copy';
+ expect(readSupportPolicy(policy).owner).toBe(fixture.owner);
+ expect(requireLaunchSupportPolicy(policy)).toBe(policy);
+ });
+ it('empty development inputs are explicit and refuse launch preparation', () => {
+ const policy = validateSupportPolicy(raw({ owner: '', destination: '' }));
+ expect(policy).toBeDefined();
+ if (!policy) throw Error('development policy');
+ expect(() => requireLaunchSupportPolicy(policy)).toThrow(
+ 'support_launch_inputs_missing'
+ );
+ });
+ it('accepts a reviewed HTTPS destination without acquiring transport', () => {
+ const policy = validateSupportPolicy(
+ raw({ destination: 'https://support.operator.org/report' })
+ );
+ expect(policy).toBeDefined();
+ if (!policy) throw Error('fixture HTTPS admission');
+ expect(readSupportPolicy(policy).destination).toBe(
+ 'https://support.operator.org/report'
+ );
+ });
+ it.each([
+ ['malformed JSON', '{'],
+ ['unknown field', raw({ transcript: 'not allowed' })],
+ ['wrong version', raw({ schemaVersion: 2 })],
+ ['wrong owner type', raw({ owner: 42 })],
+ ['wrong destination type', raw({ destination: [] })],
+ ['owner control', raw({ owner: 'fixture\nforged owner' })],
+ ['oversized owner', raw({ owner: 'x'.repeat(257) })],
+ ['plaintext HTTP', raw({ destination: 'http://support.operator.org/' })],
+ ['script scheme', raw({ destination: 'javascript:alert(1)' })],
+ ['data carrier', raw({ destination: 'data:text/plain,report' })],
+ ['relative route', raw({ destination: '/about#report' })],
+ [
+ 'credentials',
+ raw({ destination: 'https://secret@support.operator.org/' })
+ ],
+ [
+ 'mailto headers',
+ raw({ destination: 'mailto:reports@operator.org?body=PRIVATE' })
+ ],
+ [
+ 'encoded header control',
+ raw({ destination: 'mailto:reports%0d%0a@operator.org' })
+ ],
+ [
+ 'multiple mail recipients',
+ raw({ destination: 'mailto:first@operator.org,second@operator.org' })
+ ],
+ [
+ 'HTTPS context query',
+ raw({ destination: 'https://support.operator.org/report?body=PRIVATE' })
+ ],
+ [
+ 'HTTPS context fragment',
+ raw({ destination: 'https://support.operator.org/report#PRIVATE' })
+ ],
+ ['oversized configuration', ' '.repeat(16385)],
+ ['ill formed text', raw({ owner: '\ud800' })]
+ ])(
+ 'rejects %s without making malformed configuration authoritative',
+ (_label, value) => {
+ expect(validateSupportPolicy(value)).toBeUndefined();
+ }
+ );
+ it('does not evaluate caller getters or admit copied policy objects', () => {
+ let reads = 0;
+ const caller = {
+ get owner() {
+ reads++;
+ return fixture.owner;
+ },
+ destination: fixture.destination,
+ schemaVersion: 1
+ };
+ expect(validateSupportPolicy(caller)).toBeUndefined();
+ expect(reads).toBe(0);
+ expect(() => readSupportPolicy(caller as unknown as SupportPolicy)).toThrow(
+ 'support_policy_invalid'
+ );
+ });
+});
diff --git a/web/tools/check-launch-support.mjs b/web/tools/check-launch-support.mjs
@@ -0,0 +1,12 @@
+import { deploymentSupportPolicy } from '../src/lib/config/deployment-support.ts';
+import { requireLaunchSupportPolicy } from '../src/lib/config/support.ts';
+
+try {
+ requireLaunchSupportPolicy(deploymentSupportPolicy);
+ console.log(
+ 'Support launch inputs admitted; actual operator qualification remains required'
+ );
+} catch {
+ console.error('support_launch_inputs_missing');
+ process.exitCode = 1;
+}
diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs
@@ -231,7 +231,204 @@ export function publicHideRootIdentity(bytes) {
// 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 supportReportingAdmission(web) {
+ let about;
+ try {
+ about = publicText(await readOwned(web, 'src/routes/about/+page.svelte'));
+ } catch (error) {
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT')
+ return false;
+ throw error;
+ }
+ if (!about.includes('../../lib/components/SupportLink.svelte')) return false;
+ /** @type {Record<string,string>} */
+ const producers = {
+ 'src/lib/catalog/observations.ts':
+ '7386470e698156f2480de1d6c9fcffacab507f97d2f4006df926db467327120c',
+ 'src/lib/catalog/product-view.ts':
+ '3558230c9f7cd17666e27c032de4ba6f30d2fb6b4d54149a69e5b8f5dc5d5363',
+ 'src/lib/catalog/search-run.ts':
+ '213a58cf897456a0dc0e99e46594cba013952ff08212802fb471f0d323c38573',
+ 'src/lib/catalog/search-view.ts':
+ 'bc4d0160574084a547d54d5ca582b15382f44d4649c255743ebdb4c8b398f795',
+ 'src/lib/components/ConfirmPanel.svelte':
+ '9e25745303bdf408a14df5153a28e9579bfa019ab083225acb7d874e93a17d59',
+ 'src/lib/components/ConflictNotice.svelte':
+ 'f0a71cab9e8f1f12a3421402e3bc3b2f96c2ddb35ad8949c6e9599b850c3a17c',
+ 'src/lib/components/ConversationOptions.svelte':
+ '032a5f49d19a43a8ee88495b92d5337f1bb2de5dc58bb600b579e1423c9dfab1',
+ 'src/lib/components/ConversationRow.svelte':
+ 'c5d0926ac9cdda18a6befe365227dfe62405f71598f59964ff36af9a0e85d743',
+ 'src/lib/components/ConversationThread.svelte':
+ '07d7421ca00f5f0c6e68b38b790f863ca5c0d01de6567ac3875ef719b83462f4',
+ 'src/lib/components/InboxStatus.svelte':
+ 'a1015aac1d6c9ebb7a54bd5746e4cbcb4b93e376a30a2cbd7f7df212713fc930',
+ 'src/lib/components/ListingEditor.svelte':
+ '060f4863f6f4f2a4fb1471bb0d5eeedf31ab13b5c83d894f47757cf5a68099e6',
+ 'src/lib/components/ListingReview.svelte':
+ 'deee41ca6c60b346afc7ed5e62e3101ee03b04fdd2a9aa8fa3f3dec585e3863b',
+ 'src/lib/components/MessageComposer.svelte':
+ 'bc8ac0e2123b60957f1c289acbb2b8740e171097029f640f657cd79f5aa8423b',
+ 'src/lib/components/MessageItem.svelte':
+ '5c9af10ece18deeddd85e11453239c2a0b8e741cb84529e15c4ad87864704517',
+ 'src/lib/components/OperationStatus.svelte':
+ 'ca3a007899996f6331fadd2ead4c55dc7116c273626ecd2f36bcd4701065ae5f',
+ 'src/lib/components/PublisherHide.svelte':
+ '0fa30a68b44e9de68c3bb1edc9ed2c7fedefc2dc8a916c0a1df1f15440248927',
+ 'src/lib/components/ReportPreview.svelte':
+ 'fe133c95d640d3fa306667c613940a81783ce821471f70394671bb474c96d767',
+ 'src/lib/components/SellingRow.svelte':
+ 'ce00de1bd033860b9c0a85a49c90c8a4d5b8a8223cfd5c0872572e548e79331d',
+ 'src/lib/components/SupportLink.svelte':
+ 'c8608221416a47055c6b0aabe7a9d8370d3bc26e3fcd3c65214275d99ea1927e',
+ 'src/lib/config/budgets.ts':
+ 'e61806f1c2b580340e862b8dc7dd8063e90f74e03c64c721a7d112b0872f935d',
+ 'src/lib/config/deployment-relays.ts':
+ '14443151ff819a11a4f9c71e4ff756d1fbdd7cf6c36242ac712c378e68583aa2',
+ 'src/lib/config/deployment-support.ts':
+ 'c698313143943749bb457674825b648f6af29477f07cae960f3435c035cd6bd8',
+ 'src/lib/config/relays.ts':
+ 'f54a4e91c6561cf02e5aebfb7b62a7913faa4416a5664f2d14d2e3f3f9886f55',
+ 'src/lib/config/support.ts':
+ 'a5b4c179db6f13ebf85081960e2f7c330c3e894666fbf8f0472edb1c5c818872',
+ 'src/lib/contracts/local-records.ts':
+ '04ddd51339a439665a94d4a4de7b23c2257d4a673873a672d4427e9764d21f3f',
+ 'src/lib/contracts/public-key.ts':
+ 'd36d4001c2f4835e24d50f00460a35c9cf9fa6b86cc3b4a6937d8b4e10afdeb9',
+ 'src/lib/messaging/admit-conversation.ts':
+ '3e1b0044c2269eb62fa0485db61d3159e4e779e36c309278863d56cba9f677c3',
+ 'src/lib/messaging/cited-product.ts':
+ 'bed076c0902f6453971f88f107766c331b5737e488cb8c3c5f6c941e3428778d',
+ 'src/lib/messaging/conversation-thread.ts':
+ '7367f0e6d96a9f249514f66c2459274e856eb83462523e37264d4cd97d2e36d1',
+ 'src/lib/messaging/decryption-queue.ts':
+ 'be704e6cbe777722c3eb80ec9843f00afd7bac8c52af0c2af7294f2437414553',
+ 'src/lib/messaging/inbox-list.ts':
+ '9cc82877bfa8dbb2a7fa41bceb842793349416271f19569f49fdd5cfc1de07e5',
+ 'src/lib/messaging/inbox-setup-view.ts':
+ '4ec9025232bb1355fef1ba039b46ce0a2be10e02e348e1b4eaadc3d1f3c2fd84',
+ 'src/lib/messaging/inbox-sync.ts':
+ '84f9b3bb165a81878bb281c51d245aff7eb06a0fa55b857a49b13d0cb1cff8ae',
+ 'src/lib/messaging/inbox-view.ts':
+ '6871707ae7395d3679856a01e87c7d8f273848e0b9ef0dc7b94f450d8417528c',
+ 'src/lib/messaging/reply-controller.ts':
+ 'c13f1395b5317febcd23396babbcc116065ff96e8cbeb29c8eadfdfc14e45c2d',
+ 'src/lib/messaging/rumor-plan.ts':
+ '8ecfa4b8238027f9011a657015da10cc2cc3691d03afa32b9a5064a6ccc56cd9',
+ 'src/lib/messaging/unlocked-session.ts':
+ 'b7ecc1acea5ed210b39cfe9ec82b3d02c75f6092c5c31dd3e0f79946b319ef4e',
+ 'src/lib/navigation-url.ts':
+ '4ce96334d7cf57ccba518132078278b71d3bf70f519202e491a5f6a8840f7b19',
+ 'src/lib/nostr/enquiry-references.ts':
+ 'a17175337ee53279f898a7c6fa1af7e77ad26c0d2c0da46f26a9766fa701d365',
+ 'src/lib/nostr/envelope-bounds.ts':
+ 'b1e1d4a0d0673f358321c978726747ddaba3ebf94dd65e67adac408bb6574dae',
+ 'src/lib/nostr/exports.ts':
+ '683fc933fadc515bd9999ddd337d85b408e0ad4fe891832f2825c35ffbe26f89',
+ 'src/lib/nostr/ingress.ts':
+ 'c433d459ad650c1fa9aa81aca24ddfaad8c251de9e43f92502e83fd5b673e772',
+ 'src/lib/nostr/listing-publisher.ts':
+ '10032c32482a766158d8a69027056e6a822a16b5f68ab9754b0f1cf42d0608f9',
+ 'src/lib/nostr/public-pool.ts':
+ '220b0b9ca0cea20c1a2e1a08a82fc4b68a1ba4dd6ffff1f45154b54735233806',
+ 'src/lib/nostr/public-store.ts':
+ '330f7599f601956ed44795df1e016945e3564bbb7da6491c48f628d407de3d14',
+ 'src/lib/nostr/request-result.ts':
+ '9bed0e13f94d38c3db471c0e750ef18d685776cb8832fedf7ddb7f92f663c2ac',
+ 'src/lib/nostr/request-scope.ts':
+ 'c6aa1005264e8ded37870c95f937d891afe67b8e07ef62dd137097c4ebb2388b',
+ 'src/lib/nostr/verified-envelope.ts':
+ '01eb6224ece812fcafed5203c2cd117058a3d45cb8a2175b370e8cd74cdc0f77',
+ 'src/lib/persistence/artifact-records.ts':
+ 'e3b235c5aaf19558b557feb6e17a35b2b1de39c1aa49cb2ef14084d670138d16',
+ 'src/lib/persistence/database.ts':
+ 'd37d53378f531de376fb6d1b307b9b99e54736299a04eff56a66b4036261e170',
+ 'src/lib/persistence/local-private-blocks.ts':
+ 'd7e76c1122ff5479f261293db458a3240438ce0471c788c2f07ffaf854449cbc',
+ 'src/lib/persistence/local-public-hides.ts':
+ '4f0e64ed0fabbe9f86014a0512e7dbd3c81711f28ca2c626e2dafa5cda349f83',
+ 'src/lib/persistence/private-storage.ts':
+ 'e45a95c9b12e8534a6ab0a4ec8ee1c86e730bba2f252dc1947954439720f2bfc',
+ 'src/lib/persistence/public-publications.ts':
+ 'be99c4114fb32880e0a9b48ab3593645532853fb4166fb506f398416db41a194',
+ 'src/lib/persistence/public-receipts.ts':
+ '10743a9d855c4f573eb42ca90a13c550dee9620e4ad3aac322858c696152e564',
+ 'src/lib/persistence/quota.ts':
+ 'e261a7c9c81d0685021663639b1bb543192e65580edb64fa58ccbb9a4a04cc95',
+ 'src/lib/publishing/edit-source.ts':
+ '1432a8ada3d822cc9f634d40a7847a4d6d02c202ecfe59a9634543d57202f56b',
+ 'src/lib/publishing/editor-workflow.ts':
+ 'c87e4f46793fd9beeedb5027cdbb06d533cf7e5df7378c030355c4608738e0f6',
+ 'src/lib/publishing/listing-editor.ts':
+ 'fe067bc1609f783aeee8ad5a0f3178cff50cae81085377b2bbec7874b5f4349d',
+ 'src/lib/publishing/listing-operation-view.ts':
+ '07f94625c0231a62f25c1db98c9459f8939c32505453633b58d2f72a894858ce',
+ 'src/lib/publishing/mark-sold.ts':
+ '80beaf8ad38b396154d5556e50e2cf5cd9f327bcdbc05f0db1ce190bf29f7234',
+ 'src/lib/publishing/new-listing-readiness.ts':
+ 'ba76be4d7309b1a6beb0c8e0f19b89f2595049e94709486b79eff38953e68893',
+ 'src/lib/publishing/prepare-listing.ts':
+ '00b922e8b0bfc73cf5ac59857472e8dd627c8df62d28f1c646c5d7c76ce5ede9',
+ 'src/lib/publishing/revise-listing.ts':
+ '1f03d43f460feb12a02489226131ec2f7b95df5f534fcbb0b49ccc686a1b0c06',
+ 'src/lib/publishing/selling-view.ts':
+ '7d1f07c5b128512d3ed19a73409f1c64ada9988d77ac9bf60799352261797f5b',
+ 'src/lib/publishing/sign-listing.ts':
+ 'a1c123c40a190699b57378c5569fcbbfbc5e23ab4d4c0df499ca40ff82fe1a10',
+ 'src/lib/publishing/withdraw-listing.ts':
+ '168064a7ce271f8342c7b7cbbf996bd96f8968e405eee0bb3e3dba1bdaf346fb',
+ 'src/lib/runtime/effect-ownership.ts':
+ 'a181d1fa8b18d45b3e143de19af4dfdaab91779ac44df972d22e7fada645778b',
+ 'src/lib/runtime/identity-session.ts':
+ '7d665f6872bdc780f1f2b56245730adcc90f32cf1fed6997f7e2e44ea2447b49',
+ 'src/lib/runtime/private-session.ts':
+ '4ba4250e2a96c077b19144517b1f091934a124916108afe73871ccb00d9b47ab',
+ 'src/lib/runtime/public-runtime.ts':
+ '679aa4cd51a1dfdc81459bdfccb29441ac60edfa8b1ddd579425787c85b5cff4',
+ 'src/lib/runtime/view-context.ts':
+ 'e2329113e29db35e983270217c47d38a44d4e0491fd710395e008786b5ae7033',
+ 'src/lib/support/report.ts':
+ 'd02ebbfa82cf415c1af192f691b5464fbbc51f898207263bf1422f049a5d9dec',
+ 'src/routes/+layout.svelte':
+ 'b013d2d2bba40ee894c122fbb352dc78110e35ad17ec7ebb830a4556d3204ff7',
+ 'src/routes/about/+page.svelte':
+ 'b89a886622bfaee20dc0bf3b8cb3f84bbdc94df249d746d690da4cf81619fcba',
+ 'src/routes/messages/+page.svelte':
+ '8279a92770f38858e197e790839bc98b4d7889214ebecdf47e542d632afbc84f',
+ 'src/routes/messages/[conversationId=local_id]/+page.svelte':
+ 'b06c6189adee80b68bc6657fa0e8504551fe9a8b1655a6d81807ebee9930a5e7',
+ 'src/routes/privacy/+page.svelte':
+ 'b16f21dddcff172b837ab9980a5d8e93b59d5ddb5fa15ce463e07affdee79547',
+ 'src/routes/products/[naddr=naddr]/+page.svelte':
+ '5f325300384e2156724f3f7ac3fa8512ac6b6090d11aef9e8e53f6aea9c51665',
+ 'src/routes/products/[naddr=naddr]/edit/+page.svelte':
+ '09c3a6bde766045319cd36a00a82ca565f9f3b5cd5322982be9482836f312998',
+ 'src/routes/sell/+page.svelte':
+ '97f22f9a0309621e9acb5f1b328d3376bc9c5affbe5a7ea1b85ece76097b9c08',
+ 'src/routes/selling/+page.svelte':
+ '65d982bdf3f625a38b6c886a31a2a699c92e9231636debc16d501e78d7c8faa0',
+ 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte':
+ '1df59a753fbef2bc2ebf77890a79cbd3d7a5bb0dcef34c219df1b5e8043cf787'
+ };
+ 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 support reporting source'
+ );
+ }
+ return true;
+}
+/** @param {string} web */
async function privateBlockingAdmission(web) {
+ if (await supportReportingAdmission(web)) return true;
const root = publicText(await readOwned(web, 'src/routes/+layout.svelte'));
if (!root.includes('../lib/persistence/local-private-blocks.ts'))
return false;
@@ -1535,6 +1732,8 @@ export async function auditOutput(webDirectory) {
])
await readOwned(web, name);
}
+ const hasSupportReporting =
+ hasFullRoutes && (await supportReportingAdmission(web));
const hasPrivateBlocking =
hasFullRoutes && (await privateBlockingAdmission(web));
const hasPublicHiding = hasFullRoutes && (await publicHidingAdmission(web));
@@ -1709,6 +1908,10 @@ export async function auditOutput(webDirectory) {
names.add('local-private-blocks');
names.add('private-session');
}
+ if (hasSupportReporting) {
+ names.add('ReportPreview');
+ names.add('navigation-url');
+ }
const admitted = new Map([['build-info.json', expectedMetadata]]);
const seen = new Set();
for (const [key, record] of Object.entries(manifest)) {
@@ -4257,6 +4460,273 @@ export async function auditOutput(webDirectory) {
}
});
}
+ if (hasSupportReporting)
+ Object.assign(expected, {
+ Button: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'Button',
+ imports: ['client', 'navigation-url']
+ },
+ CapabilityGate: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'CapabilityGate',
+ imports: ['client', 'navigation-url', 'Button']
+ },
+ InboxSetup: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'InboxSetup',
+ imports: ['private-session', 'client', 'public-runtime', 'Button']
+ },
+ InboxStatus: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'InboxStatus',
+ imports: [
+ 'private-session',
+ 'client',
+ 'navigation-url',
+ 'public-runtime',
+ 'navigation',
+ 'Button',
+ 'CapabilityGate',
+ 'inbox-view',
+ 'InboxSetup'
+ ]
+ },
+ ListingEditor: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'ListingEditor',
+ imports: [
+ 'public-key',
+ 'private-session',
+ 'references',
+ 'client',
+ 'navigation-url',
+ 'public-runtime',
+ 'CapabilityGate',
+ 'InboxSetup',
+ 'OperationStatus'
+ ]
+ },
+ MessageComposer: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'MessageComposer',
+ imports: [
+ 'public-key',
+ 'private-session',
+ 'client',
+ 'navigation-url',
+ 'public-runtime',
+ 'navigation',
+ 'local-private-blocks',
+ 'ReportPreview',
+ 'inbox-view'
+ ]
+ },
+ ReportPreview: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'ReportPreview',
+ imports: [
+ 'private-session',
+ 'references',
+ 'client',
+ 'navigation-url',
+ 'public-runtime',
+ 'publishers',
+ 'inbox-view'
+ ]
+ },
+ 'inbox-view': {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'inbox-view',
+ imports: [
+ 'public-key',
+ 'private-session',
+ 'references',
+ 'navigation-url',
+ 'public-runtime',
+ 'local-private-blocks'
+ ]
+ },
+ 'local-private-blocks': {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'local-private-blocks',
+ imports: ['public-key', 'private-session', 'navigation-url']
+ },
+ 'navigation-url': {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'navigation-url'
+ },
+ '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',
+ 'private-session',
+ 'client',
+ 'navigation-url',
+ 'public-runtime',
+ 'client.svelte',
+ 'state',
+ 'Button',
+ 'CapabilityGate',
+ 'Disclosure',
+ 'local-private-blocks'
+ ],
+ 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',
+ 'navigation-url',
+ '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: [
+ 'private-session',
+ 'references',
+ 'client',
+ 'navigation-url',
+ 'public-runtime',
+ 'CapabilityGate',
+ 'Disclosure',
+ 'InboxSetup',
+ 'OperationStatus'
+ ]
+ },
+ 'nodes/2': {
+ file: '_app/immutable/nodes/2.HASH.js',
+ name: 'nodes/2',
+ src: '.svelte-kit/generated/build/client-optimized/nodes/2.js',
+ isEntry: true,
+ imports: ['client', 'navigation-url', 'SearchForm', 'routes']
+ },
+ 'nodes/3': {
+ file: '_app/immutable/nodes/3.HASH.js',
+ name: 'nodes/3',
+ src: '.svelte-kit/generated/build/client-optimized/nodes/3.js',
+ isEntry: true,
+ imports: [
+ 'private-session',
+ 'client',
+ 'public-runtime',
+ 'ReportPreview'
+ ]
+ },
+ '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',
+ 'private-session',
+ 'references',
+ 'client',
+ 'navigation-url',
+ 'public-runtime',
+ 'client.svelte',
+ 'state',
+ 'Button',
+ 'legacy',
+ 'ReportPreview',
+ 'inbox-view',
+ 'InboxStatus',
+ 'MessageComposer'
+ ]
+ },
+ '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',
+ 'private-session',
+ 'references',
+ 'client',
+ 'navigation-url',
+ 'public-runtime',
+ 'client.svelte',
+ 'state',
+ 'Button',
+ 'CapabilityGate',
+ 'Disclosure',
+ 'ReportPreview',
+ 'InboxSetup',
+ 'MessageComposer'
+ ]
+ },
+ '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: [
+ 'private-session',
+ 'references',
+ 'client',
+ 'navigation-url',
+ 'public-runtime',
+ 'client.svelte',
+ 'navigation',
+ 'state',
+ 'Button',
+ 'Disclosure',
+ 'SearchForm',
+ 'routes',
+ 'publishers'
+ ]
+ },
+ 'private-session': {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'private-session',
+ imports: ['public-key', 'navigation-url']
+ },
+ 'public-runtime': {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'public-runtime',
+ imports: [
+ 'public-key',
+ 'preload-helper',
+ 'private-session',
+ 'references',
+ 'navigation-url'
+ ],
+ dynamicImports: ['negentropy']
+ },
+ publishers: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'publishers',
+ imports: [
+ 'public-key',
+ 'private-session',
+ 'navigation-url',
+ 'public-runtime'
+ ]
+ },
+ routes: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'routes',
+ imports: ['public-key', 'references', 'navigation-url']
+ }
+ });
for (const record of Object.values(manifest)) {
const actual = { ...record };
actual.file = actual.file.includes('/chunks/')
diff --git a/web/tools/source-boundaries.mjs b/web/tools/source-boundaries.mjs
@@ -119,7 +119,8 @@ function mutationAdmission(
identity = () => null,
reviewedScroll = false,
reviewedCopy = false,
- reviewedVisibility = false
+ reviewedVisibility = false,
+ reviewedReport = false
) {
// Bind this admitted AST only, without libs, module resolution, file reads,
// config loading or evaluation. Symbols distinguish aliases and shadowing.
@@ -886,14 +887,15 @@ function mutationAdmission(
const action = node.parent;
const call = action.parent;
if (
- !reviewedCopy ||
- !global(node.expression, ['navigator']) ||
- !ts.isPropertyAccessExpression(action) ||
- action.expression !== node ||
- action.name.text !== 'writeText' ||
- !ts.isCallExpression(call) ||
- call.expression !== action ||
- call.arguments.length !== 1
+ !reviewedReport &&
+ (!reviewedCopy ||
+ !global(node.expression, ['navigator']) ||
+ !ts.isPropertyAccessExpression(action) ||
+ action.expression !== node ||
+ action.name.text !== 'writeText' ||
+ !ts.isCallExpression(call) ||
+ call.expression !== action ||
+ call.arguments.length !== 1)
)
report(
'clipboard capability requires the exact reviewed public copy action'
@@ -1054,7 +1056,11 @@ function mutationAdmission(
)
report('escaped goto capability is forbidden');
if (!propertyName && !typeName && !symbol) {
- if (node.text === 'navigator' && !navigatorLeaf(node))
+ if (
+ node.text === 'navigator' &&
+ !navigatorLeaf(node) &&
+ !(reviewedReport && ts.isTypeOfExpression(parent))
+ )
report('opaque navigator capabilities cannot expose worker loaders');
if (
node.text === 'document' &&
@@ -1107,6 +1113,16 @@ function mutationAdmission(
!ts.isCallExpression(parent.parent) ||
parent.parent.expression !== parent ||
(!descriptorRead(parent) &&
+ !(
+ reviewedReport &&
+ node.text === 'Reflect' &&
+ parent.name.text === 'get' &&
+ parent.parent.arguments.length === 2 &&
+ ts.isIdentifier(parent.parent.arguments[0]) &&
+ parent.parent.arguments[0].text === 'clipboard' &&
+ ts.isStringLiteralLike(parent.parent.arguments[1]) &&
+ parent.parent.arguments[1].text === 'writeText'
+ ) &&
!parent.parent.arguments.every((argument) => pure(argument)))
)
report(
@@ -1581,6 +1597,19 @@ export async function auditSource(root) {
copyFile,
'copy helper source identity does not match reviewed pin'
);
+ // This report owner grants only the explicit reviewed selected-copy action.
+ // Its complete bytes pin original-context fences and memory retirement too;
+ // altered or copied producers receive no clipboard/reflection exception.
+ const reportFile = path.join(root, 'src/lib/support/report.ts');
+ const reportTrusted =
+ files.has(reportFile) &&
+ createHash('sha256').update(files.get(reportFile)).digest('hex') ===
+ 'd02ebbfa82cf415c1af192f691b5464fbbc51f898207263bf1422f049a5d9dec';
+ if (files.has(reportFile) && !reportTrusted)
+ complain(
+ reportFile,
+ 'report copy source identity does not match reviewed pin'
+ );
const scrollFile = path.join(root, 'src/lib/navigation-scroll.ts');
const scrollTrusted =
files.has(scrollFile) &&
@@ -2086,7 +2115,8 @@ export async function auditSource(root) {
},
file === scrollFile && scrollTrusted,
file === copyFile && copyTrusted,
- file === visibilityFile && visibilityTrusted
+ file === visibilityFile && visibilityTrusted,
+ file === reportFile && reportTrusted
);
if (ast.referencedFiles.length || ast.typeReferenceDirectives.length)
complain(file, 'source reference directives are forbidden');