app

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

commit ec13e3d9a3e730227141c880cb42e4c6913d1019
parent a5cbf6b0c98fbc60a8d9805c7d210608d23536ce
Author: triesap <tyson@radroots.org>
Date:   Sun, 11 Oct 2026 10:37:01 +0000

web: enforce separate posting and messaging operational flags (HCP-126)

- Separate original policy admission and view capability.
- Preserve drafts and uncertain operations for explicit review.
- Verify genuine messaging-only and disabled effect consumers.
- Pin measured compiler output and retain historical guards.

Diffstat:
Mweb/src/lib/components/AppShell.svelte | 22++++++++++++++++++++++
Mweb/src/lib/components/ListingEditor.svelte | 30+++++++++++++++++++++++++++---
Mweb/src/lib/components/MessageComposer.svelte | 2+-
Aweb/src/lib/config/operation-flags.ts | 20++++++++++++++++++++
Mweb/src/lib/messaging/inbox-setup-operation.ts | 17+++++------------
Mweb/src/lib/messaging/inbox-setup-view.ts | 4++--
Mweb/src/lib/messaging/inbox-setup.ts | 4++--
Mweb/src/lib/messaging/product-request-controller.ts | 22+++++++++++++++++-----
Mweb/src/lib/messaging/reply-controller.ts | 34+++++++++++++++++++++++++++++-----
Mweb/src/lib/nostr/inbox-preference-publication.ts | 5++---
Mweb/src/lib/nostr/listing-publisher.ts | 13++++---------
Mweb/src/lib/publishing/prepare-listing.ts | 7++++++-
Mweb/src/lib/publishing/resume-listing.ts | 13++++---------
Aweb/src/lib/runtime/capabilities.ts | 15+++++++++++++++
Mweb/tests/e2e/harness/edit-source.ts | 6++++--
Mweb/tests/e2e/harness/inbox-preference-publisher.ts | 6++++--
Mweb/tests/e2e/harness/inbox-setup.ts | 8+++++---
Aweb/tests/e2e/harness/operation-flags.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/operation-flags.spec.ts | 494+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/e2e/product-request.spec.ts | 298++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mweb/tests/e2e/shell.spec.ts | 22++++++++++++++++------
Aweb/tests/integration/operation-flags.test.ts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/provenance/output.test.mjs | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Aweb/tests/unit/operation-flags.test.ts | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tools/check-output.mjs | 305++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
25 files changed, 1559 insertions(+), 135 deletions(-)

diff --git a/web/src/lib/components/AppShell.svelte b/web/src/lib/components/AppShell.svelte @@ -6,6 +6,9 @@ import type { IdentityViewActionResult } from '../runtime/view-context.ts'; import type { IdentitySnapshot } from '../runtime/identity-session.ts'; import Disclosure from './primitives/Disclosure.svelte'; + import { deploymentRelayPolicy } from '../config/deployment-relays.ts'; + import { operationCapabilities } from '../runtime/capabilities.ts'; + const availability = operationCapabilities(deploymentRelayPolicy); type ShellRoute = '/search' | '/sell' | '/selling' | '/messages' | '/about' | '/privacy'; @@ -118,6 +121,25 @@ </nav> </header> <main id="main-content" tabindex="-1" class="page"> + {#if !availability.posting || !availability.messaging} + <div class="notice stack" role="note" aria-label="Build availability"> + {#if !availability.posting}<p>Posting is disabled in this build.</p>{/if} + {#if !availability.messaging}<p> + Messaging is disabled in this build. + </p>{/if} + <p> + Browsing, local editing and pending-work review remain available where + supported. Availability flags do not establish full qualification. + </p> + <details class="disclosure"> + <summary>Availability limits</summary> + <p> + Static build flags do not instantly stop already-open tabs. Urgent + stops require relay enforcement. + </p> + </details> + </div> + {/if} {@render children()} </main> <footer class="footer"> diff --git a/web/src/lib/components/ListingEditor.svelte b/web/src/lib/components/ListingEditor.svelte @@ -8,11 +8,13 @@ import { PUBLIC_RUNTIME_CONTEXT, publicRuntimeReady, + publicRuntimePolicy, type PublicRuntimeContext, type PublicRuntime } from '../runtime/public-runtime.ts'; import { createRuntimeInboxSetupView, + inboxSetupViewOwnership, inboxSetupViewSnapshot, subscribeInboxSetupView, closeInboxSetupView, @@ -56,6 +58,7 @@ type ListingEditorSnapshot } from '../publishing/listing-editor.ts'; import { internalHref } from '../navigation-url.ts'; + import { operationCapabilities } from '../runtime/capabilities.ts'; let { route, onfirstsave, @@ -124,6 +127,12 @@ const editable = $derived( !!(visible && visible.editable && !publicationOperation && !publishBusy) ); + const availability = $derived( + operationCapabilities( + (runtime && publicRuntimePolicy(runtime)) ?? + inboxSetupViewOwnership(setup)?.policy + ) + ); onMount(() => { mounted = true; const off = subscribeIdentityView(context, (next) => { @@ -290,6 +299,8 @@ closeBusy || publishBusy || publicationOperation || + !availability.posting || + (route.mode !== 'edit' && !availability.newListing) || !original || !listingEditorSnapshot(original)?.editable ) @@ -347,6 +358,7 @@ !original || publishBusy || publicationOperation || + !availability.posting || route.mode !== 'edit' ) return; @@ -467,6 +479,13 @@ Loading local values. </p>{/if} {:else} + {#if !availability.posting}<Notice + tone="info" + text="Posting is unavailable here. Keep editing your local draft; retained operations still need separate review." + />{:else if route.mode !== 'edit' && !availability.newListing}<Notice + tone="info" + text="New listings require messaging availability as well as inbox readiness. Your local draft remains available." + />{/if} {#if route.mode === 'edit' && editor && listingEditorEditSource(editor)} <ConflictNotice source={listingEditorEditSource(editor)!} @@ -761,7 +780,10 @@ onclick={() => { void showReview(); }} - disabled={reviewBusy || closeBusy} + disabled={reviewBusy || + closeBusy || + !availability.posting || + (route.mode !== 'edit' && !availability.newListing)} >{reviewBusy ? 'Preparing review' : route.mode === 'edit' @@ -776,14 +798,16 @@ onclick={() => { soldConfirm = true; }} - disabled={reviewBusy || closeBusy}>Mark as sold</button + disabled={reviewBusy || closeBusy || !availability.posting} + >Mark as sold</button > <button type="button" onclick={() => { withdrawalConfirm = true; }} - disabled={reviewBusy || closeBusy}>Request removal</button + disabled={reviewBusy || closeBusy || !availability.posting} + >Request removal</button > </details>{/if} {#if publishBusy && review && editorReviewSnapshot(review)?.withdrawal} diff --git a/web/src/lib/components/MessageComposer.svelte b/web/src/lib/components/MessageComposer.svelte @@ -157,7 +157,7 @@ disabled={model.busy || model.state === 'completed' || !text.trim() || - (!!request && !productRequestSnapshot(request)?.readyToSend)} + !model.readyToSend} onclick={() => { void send(); }}>{request ? 'Send request' : 'Send reply'}</button diff --git a/web/src/lib/config/operation-flags.ts b/web/src/lib/config/operation-flags.ts @@ -0,0 +1,20 @@ +import { readRelayPolicy, type RelayPolicy } from './relays.ts'; + +// Static availability is read only from original admitted policy. This boolean +// is not an owner, signer, route, lease or permission to replay retained work. +export function operationEnabled( + policy: RelayPolicy | undefined, + operation: unknown +): boolean { + if (!policy) return false; + try { + const manifest = readRelayPolicy(policy); + if (operation === 'posting') return manifest.postingEnabled; + if (operation === 'messaging') return manifest.messagingEnabled; + if (operation === 'new_listing') + return manifest.postingEnabled && manifest.messagingEnabled; + return false; + } catch { + return false; + } +} diff --git a/web/src/lib/messaging/inbox-setup-operation.ts b/web/src/lib/messaging/inbox-setup-operation.ts @@ -3,12 +3,9 @@ import { inboxSetupRecordCurrent, type InboxSetupReview } from './inbox-setup.ts'; +import { operationEnabled } from '../config/operation-flags.ts'; import type { InboxResolver } from './resolve-inbox.ts'; -import { - publicRelayTargets, - readRelayPolicy, - type RelayPolicy -} from '../config/relays.ts'; +import { publicRelayTargets, type RelayPolicy } from '../config/relays.ts'; import { canonicalLocalId } from '../private-handles.ts'; import { identityMessagingOwnership, @@ -165,12 +162,10 @@ export async function resumeInboxPreferenceOperation( const row = publicRecordSnapshot(read.value, owner.owner, id); if (row?.family !== 'preference_operation') return { status: 'invalid' }; if (row.revision < 2 || !row.artifact) return { status: 'unknown' }; - const manifest = readRelayPolicy(policy), - fingerprint = await preferencePolicyFingerprint(policy), + const fingerprint = await preferencePolicyFingerprint(policy), resolver = await lookup(); if ( - !manifest.messagingEnabled || - !manifest.postingEnabled || + !operationEnabled(policy, 'messaging') || row.capture.policyFingerprint !== fingerprint || JSON.stringify(row.capture.targets) !== JSON.stringify(publicRelayTargets(policy, 'write')) || @@ -270,10 +265,8 @@ export async function runInboxPreferenceOperation( const row = publicRecordSnapshot(claimed, capture.owner, saved.id); if (row?.family !== 'preference_operation') return { status: 'invalid' }; - const manifest = readRelayPolicy(saved.policy); if ( - !manifest.messagingEnabled || - !manifest.postingEnabled || + !operationEnabled(saved.policy, 'messaging') || row.capture.policyFingerprint !== (await preferencePolicyFingerprint(saved.policy)) || JSON.stringify(row.capture.targets) !== diff --git a/web/src/lib/messaging/inbox-setup-view.ts b/web/src/lib/messaging/inbox-setup-view.ts @@ -1,3 +1,4 @@ +import { operationEnabled } from '../config/operation-flags.ts'; import { readRelayPolicy, inboxRelayTargets, @@ -331,8 +332,7 @@ export function createInboxSetupView( if ( !review || state.preview === undefined || - !manifest.postingEnabled || - !manifest.messagingEnabled + !operationEnabled(input.policy, 'messaging') ) { update('unavailable'); return; diff --git a/web/src/lib/messaging/inbox-setup.ts b/web/src/lib/messaging/inbox-setup.ts @@ -23,6 +23,7 @@ import { type PublicRecordHandle } from '../persistence/records.ts'; import { canonicalLocalId } from '../private-handles.ts'; +import { operationEnabled } from '../config/operation-flags.ts'; import { inboxResolutionSnapshot, inboxResolverCurrentAfterSample, @@ -101,8 +102,7 @@ export async function reviewInboxSetup( if ( !capture || !capture.current() || - !manifest.messagingEnabled || - !manifest.postingEnabled + !operationEnabled(policy, 'messaging') ) return { status: 'blocked', reason: 'unavailable' }; const previous = base(resolver, policy, capture.owner); diff --git a/web/src/lib/messaging/product-request-controller.ts b/web/src/lib/messaging/product-request-controller.ts @@ -15,6 +15,7 @@ import { type InboxSetupView } from './inbox-setup-view.ts'; import { messagingReadinessSnapshot } from './readiness.ts'; +import { operationEnabled } from '../config/operation-flags.ts'; import { sellerInboxStatus, sellerInboxCopy, @@ -193,6 +194,7 @@ export function createProductRequestController( return ( !!scope && !!source && + operationEnabled(scope.own.policy, 'messaging') && messagingReadinessSnapshot( identity!, scope.own.session, @@ -227,11 +229,14 @@ export function createProductRequestController( ), copy: copy || - (state === 'preparing' - ? 'Preparing encryption. The extension may ask for several approvals.' - : state === 'publishing' - ? 'Publishing encrypted copies to the reviewed inbox relays.' - : ''), + (inboxSetupViewOwnership(setup)?.policy && + !operationEnabled(inboxSetupViewOwnership(setup)?.policy, 'messaging') + ? 'Messaging is disabled in this build. Keep your unsent draft and review existing encrypted work separately.' + : state === 'preparing' + ? 'Preparing encryption. The extension may ask for several approvals.' + : state === 'publishing' + ? 'Publishing encrypted copies to the reviewed inbox relays.' + : ''), saveCopy: draft ? draft.copy : attempted @@ -248,6 +253,13 @@ export function createProductRequestController( if (!current()) return { status: 'stopped' }; if (busy) return { status: 'busy' }; if (attempted) return { status: 'needs_action' }; + const requestedPolicy = inboxSetupViewOwnership(setup)?.policy; + if (requestedPolicy && !operationEnabled(requestedPolicy, 'messaging')) { + state = 'needs_action'; + copy = + 'Messaging is disabled in this build. Your unsent text remains in memory; existing encrypted work needs its own recovery review.'; + return { status: 'needs_action' }; + } const captured = ownership(); if ( !captured || diff --git a/web/src/lib/messaging/reply-controller.ts b/web/src/lib/messaging/reply-controller.ts @@ -1,6 +1,7 @@ import { inboxReplyOwnership, type InboxView } from './inbox-view.ts'; import { inboxSetupViewOwnership } from './inbox-setup-view.ts'; import { messagingReadinessSnapshot } from './readiness.ts'; +import { operationEnabled } from '../config/operation-flags.ts'; import { createInboxRoutePlan, inboxRoutePlanSnapshot @@ -78,6 +79,7 @@ type State = | 'completed'; type Snapshot = Readonly<{ state: State; + readyToSend: boolean; busy: boolean; dirty: boolean; copy: string; @@ -154,15 +156,26 @@ export function createReplyController( if (!draft) return; return { state, + readyToSend: + !attempted && + operationEnabled( + inboxSetupViewOwnership(scope!.setup)?.policy, + 'messaging' + ), busy, dirty: draft.dirty, copy: copy || - (state === 'preparing' - ? 'Preparing encryption. The extension may ask for several approvals.' - : state === 'publishing' - ? 'Publishing encrypted copies to the reviewed inbox relays.' - : ''), + (!operationEnabled( + inboxSetupViewOwnership(scope!.setup)?.policy, + 'messaging' + ) + ? 'Messaging is disabled in this build. Keep your unsent draft and review existing encrypted work separately.' + : state === 'preparing' + ? 'Preparing encryption. The extension may ask for several approvals.' + : state === 'publishing' + ? 'Publishing encrypted copies to the reviewed inbox relays.' + : ''), saveCopy: draft.copy, pairCopy: workflow?.pairCopy ?? draft.pairCopy, navigation: dirtyNavigationSnapshot(navigation!)?.state ?? 'idle' @@ -172,6 +185,17 @@ export function createReplyController( if (review !== 'reviewed_reply_send') return { status: 'invalid' }; if (!current()) return { status: 'stopped' }; if (busy) return { status: 'busy' }; + if ( + !operationEnabled( + inboxSetupViewOwnership(scope!.setup)?.policy, + 'messaging' + ) + ) { + state = 'needs_action'; + copy = + 'Messaging is disabled in this build. Your unsent text remains in memory; existing encrypted work needs its own recovery review.'; + return { status: 'needs_action' }; + } const text = privateComposerText(composer!); if (!text?.trim()) return { status: 'invalid' }; if (attempted) return { status: 'needs_action' }; diff --git a/web/src/lib/nostr/inbox-preference-publication.ts b/web/src/lib/nostr/inbox-preference-publication.ts @@ -1,4 +1,5 @@ import type { NostrEvent } from 'applesauce-core/helpers'; +import { operationEnabled } from '../config/operation-flags.ts'; import { publicRelayTargets, readRelayPolicy, @@ -86,11 +87,9 @@ export async function authorizeStoredInboxPreference( session: capture.session }; const fingerprint = await preferencePolicyFingerprint(policy), - manifest = readRelayPolicy(policy), targets = publicRelayTargets(policy, 'write'); if ( - !manifest.messagingEnabled || - !manifest.postingEnabled || + !operationEnabled(policy, 'messaging') || fingerprint !== row.capture.policyFingerprint || JSON.stringify(targets) !== JSON.stringify(row.capture.targets) ) diff --git a/web/src/lib/nostr/listing-publisher.ts b/web/src/lib/nostr/listing-publisher.ts @@ -1,9 +1,6 @@ import type { NostrEvent } from 'applesauce-core/helpers'; -import { - publicRelayTargets, - readRelayPolicy, - type RelayPolicy -} from '../config/relays.ts'; +import { operationEnabled } from '../config/operation-flags.ts'; +import { publicRelayTargets, type RelayPolicy } from '../config/relays.ts'; import { listingPublicationOwnership, type ListingPublication @@ -268,14 +265,12 @@ export async function authorizeListingAttempt( original = owner.original; const row = record && publicRecordSnapshot(record, original.owner, original.command); - const manifest = readRelayPolicy(owner.policy), - targets = publicRelayTargets(owner.policy, 'write'), + const targets = publicRelayTargets(owner.policy, 'write'), fingerprint = await preferencePolicyFingerprint(owner.policy); if ( row?.family !== 'public_operation' || !row.artifact || - !manifest.postingEnabled || - !manifest.messagingEnabled || + !operationEnabled(owner.policy, 'posting') || fingerprint !== row.capture.policyFingerprint || JSON.stringify(targets) !== JSON.stringify(row.capture.targets) || !row.capture.targets.includes(origin) diff --git a/web/src/lib/publishing/prepare-listing.ts b/web/src/lib/publishing/prepare-listing.ts @@ -6,6 +6,7 @@ import type { import { canonicalLocalId, newLocalId } from '../private-handles.ts'; import { readRelayPolicy, publicRelayTargets } from '../config/relays.ts'; import { inspectLocalTemplate } from '../nostr/local-template.ts'; +import { operationEnabled } from '../config/operation-flags.ts'; import { verifyEnvelope, verifiedEnvelopeSnapshot @@ -280,7 +281,11 @@ async function reviewListing( owner, withdrawal ? 5 : 30402 ); - if (!template || !manifest.postingEnabled || targets.length === 0) + if ( + !template || + !operationEnabled(ready.policy, retained ? 'posting' : 'new_listing') || + targets.length === 0 + ) return { status: 'blocked', reason: 'unavailable' }; const digest = await crypto.subtle.digest( 'SHA-256', diff --git a/web/src/lib/publishing/resume-listing.ts b/web/src/lib/publishing/resume-listing.ts @@ -1,3 +1,4 @@ +import { operationEnabled } from '../config/operation-flags.ts'; import { publicPublicationOwner, readPublicListingIntent, @@ -13,11 +14,7 @@ import { recheckIdentityOwner, type IdentitySession } from '../runtime/identity-session.ts'; -import { - publicRelayTargets, - readRelayPolicy, - type RelayPolicy -} from '../config/relays.ts'; +import { publicRelayTargets, type RelayPolicy } from '../config/relays.ts'; import { preferencePolicyFingerprint } from '../nostr/inbox-preference-publication.ts'; import type { PublicPool } from '../nostr/public-pool.ts'; import { beginListingRetry } from './retry-listing.ts'; @@ -89,8 +86,7 @@ export async function prepareListingResume( const read = await readPublicListingIntent(repository, id); const row = read.status === 'found' && publicRecordSnapshot(read.record, owner, id); - const manifest = readRelayPolicy(policy), - targets = publicRelayTargets(policy, 'write'), + const targets = publicRelayTargets(policy, 'write'), fingerprint = await preferencePolicyFingerprint(policy); if ( !current() || @@ -99,8 +95,7 @@ export async function prepareListingResume( row.capture.kind !== 30402 || !row.artifact || row.revision < 2 || - !manifest.postingEnabled || - !manifest.messagingEnabled || + !operationEnabled(policy, 'posting') || fingerprint !== row.capture.policyFingerprint || JSON.stringify(targets) !== JSON.stringify(row.capture.targets) ) diff --git a/web/src/lib/runtime/capabilities.ts b/web/src/lib/runtime/capabilities.ts @@ -0,0 +1,15 @@ +import { operationEnabled } from '../config/operation-flags.ts'; +import type { RelayPolicy } from '../config/relays.ts'; + +// Detached view information. Original effect owners still validate every +// owner/template/target/native receipt and explicit action independently. +export function operationCapabilities(policy?: RelayPolicy) { + return { + posting: operationEnabled(policy, 'posting'), + messaging: operationEnabled(policy, 'messaging'), + newListing: operationEnabled(policy, 'new_listing'), + draft: true as const, + pendingReview: true as const, + qualification: 'not_established_by_flags' as const + }; +} diff --git a/web/tests/e2e/harness/edit-source.ts b/web/tests/e2e/harness/edit-source.ts @@ -42,7 +42,9 @@ import { createPublicPublicationRepository } from '../../../src/lib/persistence/ import { encodeProductReference } from '../../../src/lib/nostr/references.ts'; import { projectFoodParts } from '../../../src/lib/contracts/food-availability-v1/read.ts'; import type { PublicDraftForm } from '../../../src/lib/contracts/local-records.ts'; -export async function createFixture() { +export async function createFixture( + flags = { postingEnabled: true, messagingEnabled: true } +) { const original = await originalFixture(); if ((await original.signed()) !== 'prepared') throw Error('actual original signature missing'); @@ -69,7 +71,7 @@ export async function createFixture() { repository = createPublicPublicationRepository(database, row.owner); if (!repository) throw Error('actual repository missing'); const publicContext = createPublicRuntimeContext(); - const runtime = mountPublicRuntime(publicContext, fixturePolicy()); + const runtime = mountPublicRuntime(publicContext, fixturePolicy(flags)); if (!runtime) throw Error('actual runtime missing'); let source: OwnedEditSource | undefined, panel: ReturnType<typeof mount> | undefined, diff --git a/web/tests/e2e/harness/inbox-preference-publisher.ts b/web/tests/e2e/harness/inbox-preference-publisher.ts @@ -46,7 +46,9 @@ export { loadPreferenceOperation } from '../../../src/lib/persistence/quota.ts'; export { publicRecordSnapshot }; -export async function makePublisherFixture() { +export async function makePublisherFixture( + flags = { postingEnabled: true, messagingEnabled: true } +) { const fixture = makeFixture(10050), original = publicRecordSnapshot(fixture.record, fixture.owner, fixture.id)!; if (original.family !== 'preference_operation' || !original.source.wire) @@ -77,7 +79,7 @@ export async function makePublisherFixture() { }); await connectIdentity(identity); await probeIdentityMessaging(identity, 'reviewed_self_copy'); - const policy = fixturePolicy(), + const policy = fixturePolicy(flags), schedulers: ReturnType<typeof createPublicScheduler>[] = []; function resolve(event = source, complete = true) { const scheduler = createPublicScheduler({ diff --git a/web/tests/e2e/harness/inbox-setup.ts b/web/tests/e2e/harness/inbox-setup.ts @@ -34,14 +34,16 @@ export { } from '../../../src/lib/persistence/records.ts'; export const discovery = 'wss://discovery.example.org', inbox = 'wss://inbox.example.org'; -export function fixturePolicy() { +export function fixturePolicy( + flags = { postingEnabled: true, messagingEnabled: true } +) { return validateRelayPolicy( JSON.stringify({ schemaVersion: 1, public: [{ origin: discovery, read: true, write: true, nip50: false }], inbox: [{ origin: inbox, read: true, write: true }], - postingEnabled: true, - messagingEnabled: true, + postingEnabled: flags.postingEnabled, + messagingEnabled: flags.messagingEnabled, operatorDenylist: [] }) )!; diff --git a/web/tests/e2e/harness/operation-flags.ts b/web/tests/e2e/harness/operation-flags.ts @@ -0,0 +1,64 @@ +// HC_TEST_ONLY_QUALIFICATION_PORT: original identity, native IDB, SDK transport; +// controlled provider and loopback prove source behavior, not live qualification. +export { + createPrivateSession, + closePrivateSession +} from '../../../src/lib/runtime/private-session.ts'; +export { + getPrivatePool, + closePrivatePool +} from '../../../src/lib/nostr/private-pool.ts'; +export * from './inbox-preference-publisher.ts'; +export { + readRelayPolicy, + validateRelayPolicy +} from '../../../src/lib/config/relays.ts'; + +export { createFixture as makeStoredPublicFixture } from './retry-listing.ts'; +export { createFixture as makeUnknownPublicFixture } from './listing-operation-view.ts'; +export { + makeFixture as makeDisabledPairFixture, + prepareSelfRecovery, + preparePairedDelivery +} from './paired-delivery.ts'; +export { makeSetupFixture, fixturePolicy } from './inbox-setup.ts'; +export { + createIdentitySession, + connectIdentity, + probeIdentityMessaging, + disconnectIdentity +} from '../../../src/lib/runtime/identity-session.ts'; +export { createPublicPublicationRepository } from '../../../src/lib/persistence/public-publications.ts'; +export { prepareListingResume } from '../../../src/lib/publishing/resume-listing.ts'; +export { + readListingOperationView, + listingOperationSnapshot, + closeListingOperationView +} from '../../../src/lib/publishing/listing-operation-view.ts'; +export { + createPublicRuntimeContext, + mountPublicRuntime, + closePublicRuntime, + createPublicView +} from '../../../src/lib/runtime/public-runtime.ts'; +export { + createProductView, + productViewSnapshot, + closeProductView, + acknowledgeProductViewUncertainty +} from '../../../src/lib/catalog/product-view.ts'; +export { captureProductEnquiry } from '../../../src/lib/messaging/product-enquiry.ts'; +export { + createProductRequestController, + configureProductRequest, + updateProductRequestText, + productRequestText, + productRequestSnapshot, + sendProductRequest, + closeProductRequestController +} from '../../../src/lib/messaging/product-request-controller.ts'; +export { + createInboxSetupView, + closeInboxSetupView +} from '../../../src/lib/messaging/inbox-setup-view.ts'; +export { encodeProductReference } from '../../../src/lib/nostr/references.ts'; diff --git a/web/tests/e2e/operation-flags.spec.ts b/web/tests/e2e/operation-flags.spec.ts @@ -0,0 +1,494 @@ +import { expect, test } from '@playwright/test'; +import { build } from 'vite'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; +import { finalizeEvent, getPublicKey } from 'applesauce-core/helpers'; +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/operation-flags.ts'; +declare global { + interface Window { + hcp126: typeof Fixture; + } +} +let server: Awaited<ReturnType<typeof createStaticHarness>>, + sockets: WebSocketServer, + endpoint: string, + bundle: string; +let frames: string[] = []; +const sellerSecret = new Uint8Array(32).fill(84); +const seller = getPublicKey(sellerSecret); +test.beforeAll(async () => { + server = await createStaticHarness(); + sockets = new WebSocketServer({ + host: '127.0.0.1', + port: 0, + maxPayload: 65536 + }); + await once(sockets, 'listening'); + const address = sockets.address(); + if (!address || typeof address === 'string') + throw Error('actual loopback missing'); + endpoint = 'ws://127.0.0.1:' + address.port; + sockets.on('connection', (socket) => + socket.on('message', (bytes) => { + const raw = Buffer.isBuffer(bytes) + ? bytes.toString() + : Array.isArray(bytes) + ? Buffer.concat(bytes).toString() + : Buffer.from(bytes).toString(); + const frame = JSON.parse(raw) as [string, { id: string }]; + if (frame[0] === 'REQ') { + const request = JSON.parse(raw) as [ + string, + string, + ...{ kinds?: number[]; authors?: string[] }[] + ]; + const [, requestId, ...filters] = request; + if ( + filters.some( + (f) => + f.kinds?.includes(30402) && + (!f.authors || f.authors.includes(seller)) + ) + ) { + const event = finalizeEvent( + { + kind: 30402, + created_at: 1700000060, + content: 'Signed carrots', + tags: [ + ['d', 'carrots'], + ['title', 'Verified carrots'], + ['summary', 'Actual signed listing'], + ['published_at', '1700000000'], + ['location', 'Victoria'], + ['price', '3.5', 'CAD'], + ['radroots:price_unit', 'lb'], + ['status', 'active'] + ] + }, + sellerSecret + ); + socket.send(JSON.stringify(['EVENT', requestId, event])); + } + socket.send(JSON.stringify(['EOSE', requestId])); + } + + if (frame[0] === 'EVENT') { + frames.push(raw); + socket.send(JSON.stringify(['OK', frame[1].id, true, ''])); + } + }) + ); + const result = await build({ + configFile: false, + plugins: [svelte({ configFile: false })], + resolve: { conditions: ['browser'] }, + logLevel: 'silent', + build: { + write: false, + minify: false, + lib: { + entry: fileURLToPath( + new URL('./harness/operation-flags.ts', import.meta.url) + ), + name: 'hcp126', + formats: ['iife'] + } + } + }); + const output = Array.isArray(result) ? result[0] : result; + if (!('output' in output)) throw Error('actual fixture bundle missing'); + const chunks = output.output.filter((x) => x.type === 'chunk'); + expect(chunks).toHaveLength(1); + bundle = chunks[0].code; +}); +test.afterAll(async () => { + for (const socket of sockets.clients) socket.terminate(); + await new Promise<void>((resolve) => sockets.close(() => resolve())); + await server.close(); +}); +test.beforeEach(async ({ page }) => { + frames = []; + await page.addInitScript( + ({ endpoint }) => { + const Native = window.WebSocket; + window.WebSocket = class extends Native { + constructor(url: string | URL, protocols?: string | string[]) { + if (String(url) !== 'wss://discovery.example.org/') + throw Error('unexpected original fixture destination'); + super(endpoint, protocols); + } + }; + }, + { endpoint } + ); + await page.goto(server.url + '/search'); + await page.addScriptTag({ content: bundle }); +}); +test('HCP126 first-level static availability is honest and cannot promise revocation of already-open tabs', async ({ + page +}) => { + const actual = await page.locator('body').innerText(); + expect(actual).toContain('Posting is disabled in this build.'); + await expect( + page.getByText('Posting is disabled in this build.', { exact: true }) + ).toBeVisible(); + await expect( + page.getByText('Messaging is disabled in this build.', { exact: true }) + ).toBeVisible(); + await page.getByText('Availability limits', { exact: true }).click(); + await expect( + page.getByText(/Static build flags do not instantly stop already-open tabs/) + ).toBeVisible(); + await expect( + page.getByText(/Availability flags do not establish full qualification/) + ).toBeVisible(); + expect(frames).toHaveLength(0); +}); +test('HCP126 messaging-only genuine preference action signs once after native acknowledgment and sends actual kind10050', async ({ + page +}) => { + const result = await page.evaluate(async () => { + const s = window.hcp126, + f = await s.makePublisherFixture({ + postingEnabled: false, + messagingEnabled: true + }); + let database: Parameters<typeof s.closeBrowserDatabase>[0] | undefined; + try { + const policy = f.policy; + if (!policy) throw Error('genuine messaging-only policy missing'); + const reviewed = await s.reviewInboxSetup( + f.identity, + f.resolve(), + policy, + s.setupInput(), + () => 101 + ); + if (reviewed.status !== 'review') + return { + stage: reviewed.status, + reason: reviewed.reason, + signs: f.signs() + }; + const opened = await s.openBrowserDatabase(); + if (opened.state !== 'ready') throw Error(opened.reason); + database = opened.owner; + const repo = s.createPublicQuotaRepository(database, f.owner); + if (!repo) throw Error('genuine original repo missing'); + const id = crypto.randomUUID(); + const saved = await s.saveInboxPreferenceOperation( + repo, + reviewed.review, + f.resolve(), + id, + 'reviewed_global_inbox_replacement' + ); + if (saved.status !== 'saved' && saved.status !== 'existing') + throw Error(saved.status); + const prepared = await s.beginInboxPreferenceOperation( + repo, + f.identity, + policy, + reviewed.review, + id, + () => Promise.resolve(f.resolve()), + 'reviewed_global_inbox_replacement' + ); + if (prepared.status !== 'prepared') + return { stage: prepared.status, signs: f.signs() }; + const trace = s.installEffectTrace(); + try { + const delivered = await s.runInboxPreferenceOperation(prepared.action); + const read = await s.loadPreferenceOperation(repo, id); + const row = read.ok && s.publicRecordSnapshot(read.value, f.owner, id); + return { + stage: delivered.status, + signs: f.signs(), + trace: trace.events(), + artifact: + row && row.family === 'preference_operation' + ? row.artifact?.eventId + : undefined + }; + } finally { + trace.restore(); + } + } finally { + f.close(); + if (database) s.closeBrowserDatabase(database); + } + }); + expect(result.stage).toBe('completed'); + expect(result.signs).toBe(1); + expect(result.trace).toEqual( + expect.arrayContaining(['ack:1', 'ack:2', 'EVENT']) + ); + expect(result.trace?.indexOf('ack:1')).toBeLessThan( + result.trace?.indexOf('ack:2') ?? -1 + ); + expect(result.trace?.indexOf('ack:2')).toBeLessThan( + result.trace?.indexOf('EVENT') ?? -1 + ); + expect(frames).toHaveLength(1); + const event = ( + JSON.parse(frames[0]) as [string, { id: string; kind: number }] + )[1]; + expect(event.kind).toBe(10050); + expect(event.id).toBe(result.artifact); +}); + +test('HCP126 posting-off stored public recovery remains needs-action with exact native record and no signature or EVENT', async ({ + page +}) => { + const result = await page.evaluate(async () => { + const s = window.hcp126, + f = await s.makeStoredPublicFixture(), + identity = s.createIdentitySession(); + let db: Parameters<typeof s.closeBrowserDatabase>[0] | undefined; + try { + await s.connectIdentity(identity); + await s.probeIdentityMessaging(identity, 'reviewed_self_copy'); + const opened = await s.openBrowserDatabase(); + if (opened.state !== 'ready') throw Error(opened.reason); + db = opened.owner; + const repo = s.createPublicPublicationRepository(db, f.owner); + if (!repo) throw Error('genuine stored repo absent'); + const off = s.validateRelayPolicy( + JSON.stringify({ + ...s.readRelayPolicy(f.policy), + postingEnabled: false, + messagingEnabled: true + }) + ); + if (!off) throw Error('genuine disabled policy absent'); + const before = await f.details(); + const action = await s.prepareListingResume( + repo, + identity, + off, + f.command, + 'reviewed_stored_listing_resume' + ); + const read = await s.readListingOperationView(repo, identity, f.command); + const snapshot = + read.status === 'found' + ? s.listingOperationSnapshot(read.view) + : undefined; + if (read.status === 'found') s.closeListingOperationView(read.view); + const after = await f.details(); + return { + status: action.status, + before: before.row, + after: after.row, + signsBefore: before.signs, + signsAfter: after.signs, + snapshot + }; + } finally { + if (db) s.closeBrowserDatabase(db); + s.disconnectIdentity(identity); + f.close(); + } + }); + expect(result.status).toBe('needs_action'); + expect(result.after).toEqual(result.before); + expect(result.signsAfter).toBe(result.signsBefore); + expect(result.snapshot).toBeDefined(); + expect(frames).toHaveLength(0); +}); +test('HCP126 actual uncertain public signing stays visible in this disabled build and is never retried automatically', async ({ + page +}) => { + const result = await page.evaluate(async () => { + const f = await window.hcp126.makeUnknownPublicFixture(); + try { + await f.holdSigning(); + await f.stopSigning(); + const before = await f.row(), + counts = f.counts(); + const snapshot = await f.renderView(); + const after = await f.row(); + return { before, after, counts, afterCounts: f.counts(), snapshot }; + } finally { + f.close(); + } + }); + expect(result.after).toEqual(result.before); + expect(result.afterCounts).toEqual(result.counts); + expect(result.snapshot).toMatchObject({ state: 'unknown' }); + await expect( + page.getByText('Posting is disabled in this build.', { exact: true }) + ).toBeVisible(); + expect(frames).toHaveLength(0); +}); +test('HCP126 messaging-off denies actual publication while preserving explicitly prepared stored recovery', async ({ + page +}) => { + const result = await page.evaluate(async () => { + const s = window.hcp126, + f = await s.makeDisabledPairFixture({ messaging: false }); + try { + const self = await s.prepareSelfRecovery( + f.preparation, + 'reviewed_self_recovery' + ); + if (self.status !== 'saved') throw Error(self.status); + const pair = await s.preparePairedDelivery( + f.preparation, + f.context, + 'reviewed_pair_preparation' + ); + if (pair.status !== 'prepared') throw Error(pair.status); + const session = await s.createPrivateSession( + f.identity, + 'reviewed_private_session' + ); + if (!session) throw Error('genuine retained private session missing'); + const before = await f.stored(), + counts = f.counts(); + let disabled = false; + try { + const pool = s.getPrivatePool(session, f.context.policy, [ + 'wss://peer.example.org', + 'wss://archive.example.org' + ]); + if (pool) s.closePrivatePool(pool); + } catch (error) { + if ( + !(error instanceof Error) || + error.message !== 'private_pool_disabled' + ) + throw error; + disabled = true; + } finally { + s.closePrivateSession(session); + } + return { + disabled, + before, + after: await f.stored(), + counts, + afterCounts: f.counts() + }; + } finally { + f.close(); + } + }); + expect(result.disabled).toBe(true); + expect(result.after).toEqual(result.before); + expect(result.afterCounts).toEqual(result.counts); + expect(frames).toHaveLength(0); +}); +test('HCP126 messaging-off original product request keeps unsaved text and denies actual Send before any effect', async ({ + page +}) => { + const result = await page.evaluate(async (seller) => { + const s = window.hcp126, + f = await s.makeSetupFixture(), + context = s.createPublicRuntimeContext(), + policy = s.fixturePolicy({ + postingEnabled: true, + messagingEnabled: false + }); + const runtime = s.mountPublicRuntime(context, policy); + if (!runtime) throw Error('genuine runtime absent'); + const address = s.encodeProductReference({ + kind: 30402, + pubkey: seller, + identifier: 'carrots' + }); + if (!address) throw Error('original coordinate absent'); + let settled = () => {}; + const observed = new Promise<void>((resolve) => { + settled = resolve; + }); + const view = s.createProductView( + s.createPublicView(runtime), + address, + { nowSeconds: () => 1700000200 }, + (snapshot) => { + if (snapshot.outcome === 'active') settled(); + } + ); + let setup: ReturnType<typeof s.createInboxSetupView>, + controller: ReturnType<typeof s.createProductRequestController>; + try { + // Await the original bounded resolver's actual completed SDK request, not a fabricated listing. + if (s.productViewSnapshot(view).outcome !== 'active') await observed; + const acknowledgement = s.acknowledgeProductViewUncertainty( + view, + 'reviewed_last_known_listing' + ); + const draft = s.captureProductEnquiry( + view, + 'reviewed_product_enquiry', + acknowledgement + ); + if (!draft) + throw Error( + 'genuine verified product enquiry absent: ' + + s.productViewSnapshot(view).outcome + ); + setup = s.createInboxSetupView({ + identity: f.identity, + policy, + lookup: () => Promise.resolve(f.own.resolver) + }); + if (!setup) throw Error('genuine original setup absent'); + controller = s.createProductRequestController(draft, runtime); + if ( + !controller || + !s.configureProductRequest( + controller, + f.identity, + setup, + 'reviewed_product_request_setup' + ) + ) + throw Error('genuine request owner absent'); + const text = 'HCP126 preserve my unsaved memory text'; + if ( + !s.updateProductRequestText(controller, text, 'reviewed_private_text') + ) + throw Error('original text update absent'); + let encrypts = 0; + const provider = window.nostr as { + nip44: { encrypt: (...args: unknown[]) => unknown }; + }; + const originalEncrypt = provider.nip44.encrypt; + provider.nip44.encrypt = (...args: unknown[]) => { + encrypts++; + return Reflect.apply(originalEncrypt, provider.nip44, args); + }; + const counts = f.counts(); + const delivered = await s.sendProductRequest( + controller, + 'reviewed_product_request_send' + ); + return { + status: delivered.status, + text: s.productRequestText(controller), + snapshot: s.productRequestSnapshot(controller), + counts, + afterCounts: f.counts(), + encrypts + }; + } finally { + if (controller) s.closeProductRequestController(controller); + if (setup) s.closeInboxSetupView(setup); + s.closeProductView(view); + s.closePublicRuntime(context); + f.close(); + } + }, seller); + expect(result.status).toBe('needs_action'); + expect(result.text).toBe('HCP126 preserve my unsaved memory text'); + expect(result.snapshot).toMatchObject({ readyToSend: false, dirty: true }); + expect(result.encrypts).toBe(0); + expect(result.afterCounts).toEqual(result.counts); + expect(frames).toHaveLength(0); +}); diff --git a/web/tests/e2e/product-request.spec.ts b/web/tests/e2e/product-request.spec.ts @@ -12,6 +12,12 @@ declare global { interface Window { hcp107: typeof Fixture; hcp107Fixture: Awaited<ReturnType<typeof Fixture.renderFixture>>; + hcp108SendClock: { + samples: { milliseconds: number; phase: string; stack?: string }[]; + locks: { captured: number; callback: number; granted: boolean }[]; + transactions: string[]; + restore(): void; + }; } } let server: Awaited<ReturnType<typeof createStaticHarness>>; @@ -335,62 +341,244 @@ for (const status of ['sold', 'withdrawn'] as const) await noPrivate(page); }); -test('HCP108 incomplete active terms need explicit original acknowledgement and retain signed citations', async ({ - page -}) => { - incompleteListing = true; - await page.evaluate(async () => { - window.hcp107Fixture = await window.hcp107.renderFixture(); - }); - await expect - .poll(() => - page.evaluate(() => window.hcp107Fixture.viewSnapshot().outcome) - ) - .toBe('active'); - await expect( - panel(page).getByRole('button', { name: 'Message seller', exact: true }) - ).toBeDisabled(); - expect( - await page.evaluate(() => window.hcp107Fixture.captureUncertain(undefined)) - ).toBe(false); - await panel(page) - .getByRole('button', { - name: 'I understand the listing status is uncertain', - exact: true - }) - .click(); - await panel(page) - .getByRole('button', { name: 'Message seller', exact: true }) - .click(); - await expect(editor(page)).toBeVisible(); - const observed = await page.evaluate(() => ({ - product: window.hcp107Fixture.product(), - view: window.hcp107Fixture.viewSnapshot(), - message: window.hcp107Fixture.message() - })); - expect(observed.product?.eventId).toBe(observed.view.eventId); - expect(observed.message?.tags).toEqual([['p', peer]]); - expect(observed.message?.content).toContain( - 'nostr:' + observed.product?.nevent +for (const crossSecond of [false, true]) + test( + crossSecond + ? 'HCP126 original product request refuses a real reservation second boundary without native rows or crypto' + : 'HCP108 incomplete active terms need explicit original acknowledgement and retain signed citations', + async ({ page }) => { + incompleteListing = true; + await page.evaluate(async () => { + window.hcp107Fixture = await window.hcp107.renderFixture(); + }); + await expect + .poll(() => + page.evaluate(() => window.hcp107Fixture.viewSnapshot().outcome) + ) + .toBe('active'); + await expect( + panel(page).getByRole('button', { name: 'Message seller', exact: true }) + ).toBeDisabled(); + expect( + await page.evaluate(() => + window.hcp107Fixture.captureUncertain(undefined) + ) + ).toBe(false); + await panel(page) + .getByRole('button', { + name: 'I understand the listing status is uncertain', + exact: true + }) + .click(); + await panel(page) + .getByRole('button', { name: 'Message seller', exact: true }) + .click(); + await expect(editor(page)).toBeVisible(); + const observed = await page.evaluate(() => ({ + product: window.hcp107Fixture.product(), + view: window.hcp107Fixture.viewSnapshot(), + message: window.hcp107Fixture.message() + })); + expect(observed.product?.eventId).toBe(observed.view.eventId); + expect(observed.message?.tags).toEqual([['p', peer]]); + expect(observed.message?.content).toContain( + 'nostr:' + observed.product?.nevent + ); + await noPrivate(page); + if (crossSecond) + await editor(page).fill('HC_TEST_ONLY_unsent_boundary_request'); + await unlock(page); + const before = await page.evaluate(async () => ({ + native: await window.hcp107Fixture.native(), + counts: window.hcp107Fixture.counts(), + text: window.hcp107Fixture.text() + })); + await page.evaluate((crossSecond) => { + const original = Date.now; + const fixed = original(); + let phase = 'send'; + let crossed = false; + const samples: { + milliseconds: number; + phase: string; + stack?: string; + }[] = []; + const locks: { + captured: number; + callback: number; + granted: boolean; + }[] = []; + const transactions: string[] = []; + const manager = navigator.locks; + const descriptor = Object.getOwnPropertyDescriptor(manager, 'request'); + const request = Reflect.get(manager, 'request'); + const owner = window.hcp107Fixture.owner; + manager.request = (...args: unknown[]) => { + const forwarded = args.slice(); + const at = args.length - 1; + const callback = args[at] as (lock: Lock | null) => unknown; + const options = + args.length === 3 ? (args[1] as LockOptions) : undefined; + forwarded[at] = async (lock: Lock | null) => { + if ( + lock && + options?.ifAvailable && + args[0] === 'harvestcircle:owner:' + owner && + !crossed + ) { + crossed = true; + const captured = samples.at(-1)!.milliseconds; + if (crossSecond) + await new Promise<void>((resolve) => { + function afterBoundary() { + if ( + Math.floor(original() / 1000) === + Math.floor(captured / 1000) + ) { + window.setTimeout(afterBoundary, 1); + return; + } + resolve(); + } + window.setTimeout( + afterBoundary, + Math.max( + 1, + (Math.floor(captured / 1000) + 1) * 1000 - original() + 1 + ) + ); + }); + locks.push({ captured, callback: original(), granted: true }); + phase = 'owner_reservation'; + try { + return await callback(lock); + } finally { + phase = 'send'; + } + } + return callback(lock); + }; + return Reflect.apply(request, manager, forwarded) as Promise<unknown>; + }; + const prototype = IDBDatabase.prototype; + const transactionDescriptor = Object.getOwnPropertyDescriptor( + prototype, + 'transaction' + )!; + const transaction = Reflect.get(prototype, 'transaction'); + prototype.transaction = function ( + this: IDBDatabase, + ...args: Parameters<IDBDatabase['transaction']> + ) { + const tx: IDBTransaction = Reflect.apply(transaction, this, args); + if ( + tx.mode === 'readwrite' && + tx.objectStoreNames.contains('private_sends') + ) + for (const outcome of ['abort', 'complete']) + tx.addEventListener(outcome, () => transactions.push(outcome)); + return tx; + } as typeof prototype.transaction; + Date.now = () => { + const milliseconds = crossSecond ? original() : fixed; + if (samples.length < 128) + samples.push({ + milliseconds, + phase, + stack: new Error().stack?.split('\n').slice(0, 5).join('\n') + }); + return milliseconds; + }; + window.hcp108SendClock = { + samples, + locks, + transactions, + restore: () => { + Date.now = original; + if (descriptor) + Object.defineProperty(manager, 'request', descriptor); + else Reflect.deleteProperty(manager, 'request'); + Object.defineProperty( + prototype, + 'transaction', + transactionDescriptor + ); + } + }; + }, crossSecond); + try { + await panel(page) + .getByRole('button', { name: 'Send request', exact: true }) + .click(); + await expect + .poll(() => + page.evaluate(() => window.hcp107Fixture.snapshot()?.busy) + ) + .toBe(false); + const terminal = await page.evaluate(() => { + window.hcp108SendClock.restore(); + return { + snapshot: window.hcp107Fixture.snapshot(), + counts: window.hcp107Fixture.counts(), + samples: window.hcp108SendClock.samples, + locks: window.hcp108SendClock.locks, + transactions: window.hcp108SendClock.transactions + }; + }); + console.log( + JSON.stringify({ + fixture: 'HCP126_ORIGINAL_REQUEST_SEND_DIAGNOSTIC', + terminal + }) + ); + if (crossSecond) { + expect(terminal.snapshot?.state).toBe('needs_action'); + expect(terminal.locks).toHaveLength(1); + expect(Math.floor(terminal.locks[0].callback / 1000)).toBeGreaterThan( + Math.floor(terminal.locks[0].captured / 1000) + ); + expect(terminal.transactions).toEqual(['abort']); + expect(events.filter((row) => row.event.kind === 1059)).toEqual([]); + expect( + await page.evaluate(() => window.hcp107Fixture.native()) + ).toEqual(before.native); + expect(await page.evaluate(() => window.hcp107Fixture.text())).toBe( + before.text + ); + for (const key of ['encrypts', 'decrypts', 'signs'] as const) + expect(terminal.counts[key]).toBe(before.counts[key]); + await expect( + panel(page).getByRole('button', { + name: 'Send request', + exact: true + }) + ).toBeDisabled(); + expect( + await page.evaluate(() => window.hcp107Fixture.counts()) + ).toEqual(terminal.counts); + expect(events.filter((row) => row.event.kind === 1059)).toEqual([]); + return; + } + expect(terminal.snapshot?.state).toBe('completed'); + await expect + .poll(() => events.filter((row) => row.event.kind === 1059).length) + .toBe(2); + expect( + events + .filter((row) => row.event.kind === 1059) + .map((row) => row.origin) + .sort() + ).toEqual(['wss://archive.example.org', 'wss://peer.example.org']); + await expect + .poll(() => + page.evaluate(() => window.hcp107Fixture.snapshot()?.state) + ) + .toBe('completed'); + } finally { + await page.evaluate(() => window.hcp108SendClock.restore()); + } + } ); - await noPrivate(page); - await unlock(page); - await panel(page) - .getByRole('button', { name: 'Send request', exact: true }) - .click(); - await expect - .poll(() => events.filter((row) => row.event.kind === 1059).length) - .toBe(2); - expect( - events - .filter((row) => row.event.kind === 1059) - .map((row) => row.origin) - .sort() - ).toEqual(['wss://archive.example.org', 'wss://peer.example.org']); - await expect - .poll(() => page.evaluate(() => window.hcp107Fixture.snapshot()?.state)) - .toBe('completed'); -}); test('HCP108 connecting as the verified publisher shows Manage and keeps unsent memory without self enquiry', async ({ page diff --git a/web/tests/e2e/shell.spec.ts b/web/tests/e2e/shell.spec.ts @@ -36,6 +36,8 @@ test.beforeAll(async () => { 'web/src/lib/components/AppShell.svelte', 'web/src/lib/components/CapabilityGate.svelte', 'web/src/lib/runtime/view-context.ts', + 'web/src/lib/runtime/capabilities.ts', + 'web/src/lib/config/operation-flags.ts', 'web/src/app.css', 'web/src/routes/+layout.svelte', 'web/tests/unit/components/shell.test.ts', @@ -314,14 +316,20 @@ for (const width of [320, 1024]) { expect( connectedClosed.navigation.map((item) => item.label?.split(' ')[0]) ).toEqual(['HarvestCircle', 'Search', 'Messages', 'Selling', 'Identity']); - const summary = page.locator('summary'); + const summary = page.locator('nav[aria-label="Primary"] summary'); await summary.focus(); await page.keyboard.press('Enter'); - await expect(page.locator('details')).toHaveAttribute('open', ''); + await expect( + page.locator('nav[aria-label="Primary"] details') + ).toHaveAttribute('open', ''); await page.keyboard.press('Space'); - await expect(page.locator('details')).not.toHaveAttribute('open', ''); + await expect( + page.locator('nav[aria-label="Primary"] details') + ).not.toHaveAttribute('open', ''); await page.keyboard.press('Enter'); - await expect(page.locator('details')).toHaveAttribute('open', ''); + await expect( + page.locator('nav[aria-label="Primary"] details') + ).toHaveAttribute('open', ''); await expect(page.locator('.key')).toHaveText( 'HC_TEST_ONLY_PUBLIC_KEY_' + 'a'.repeat(64) ); @@ -420,11 +428,13 @@ test('controlled shell callbacks become available only after actual hydration', await expect( page.getByRole('status').filter({ hasText: /^Commands:/ }) ).toHaveText('Commands: 1'); - const identity = page.locator('summary'); + const identity = page.locator('nav[aria-label="Primary"] summary'); await identity.focus(); await expect(identity).toBeFocused(); await page.keyboard.press('Enter'); - await expect(page.locator('details')).toHaveAttribute('open', ''); + await expect( + page.locator('nav[aria-label="Primary"] details') + ).toHaveAttribute('open', ''); await expect( page.getByRole('button', { name: 'Disconnect', exact: true }) ).toBeEnabled(); diff --git a/web/tests/integration/operation-flags.test.ts b/web/tests/integration/operation-flags.test.ts @@ -0,0 +1,70 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { + readRelayPolicy, + validateRelayPolicy +} from '../../src/lib/config/relays.ts'; +import { + makeSetupFixture, + fixturePolicy, + setupInput, + reviewInboxSetup, + inboxSetupPreview +} from '../e2e/harness/inbox-setup.ts'; + +void test('HCP126 posting off preserves genuine deliberate messaging-only preference review without signing', async () => { + const f = await makeSetupFixture(); + try { + const policy = validateRelayPolicy( + JSON.stringify({ + ...readRelayPolicy(fixturePolicy()), + postingEnabled: false, + messagingEnabled: true + }) + ); + if (!policy) throw Error('original messaging-only policy missing'); + const before = f.counts(); + const result = await reviewInboxSetup( + f.identity, + f.own.resolver, + policy, + setupInput(), + () => 101 + ); + assert.equal(result.status, 'review'); + assert.match( + inboxSetupPreview(result.review)?.globalEffect ?? '', + /does not publish/ + ); + assert.deepEqual(f.counts(), before); + } finally { + f.close(); + } +}); +void test('HCP126 messaging off denies genuine preference preparation even when public posting is on', async () => { + const f = await makeSetupFixture(); + try { + const policy = validateRelayPolicy( + JSON.stringify({ + ...readRelayPolicy(fixturePolicy()), + postingEnabled: true, + messagingEnabled: false + }) + ); + if (!policy) throw Error('original posting-only policy missing'); + const before = f.counts(); + assert.deepEqual( + await reviewInboxSetup( + f.identity, + f.own.resolver, + policy, + setupInput(), + () => 101 + ), + { status: 'blocked', reason: 'unavailable' } + ); + assert.deepEqual(f.counts(), before); + } finally { + f.close(); + } +}); diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs @@ -131,6 +131,80 @@ import { auditOutput } from '../../tools/check-output.mjs'; async function restoreHistoricalPublicProducers(web) { for (const [name, value] of Object.entries({ ...{ + 'src/lib/components/AppShell.svelte': { + source: + "<script lang=\"ts\">\n import type { Snippet } from 'svelte';\n import { internalHref } from '../navigation-url';\n import Button from './primitives/Button.svelte';\n import CapabilityGate from './CapabilityGate.svelte';\n import type { IdentityViewActionResult } from '../runtime/view-context.ts';\n import type { IdentitySnapshot } from '../runtime/identity-session.ts';\n import Disclosure from './primitives/Disclosure.svelte';\n\n type ShellRoute =\n '/search' | '/sell' | '/selling' | '/messages' | '/about' | '/privacy';\n type Identity =\n | {\n kind: 'guest';\n onconnect?: () => Promise<IdentityViewActionResult> | void;\n }\n | { kind: 'connected'; publicKey: string; ondisconnect?: () => void };\n let {\n children,\n currentPath = '/',\n availableRoutes = [],\n identity = { kind: 'guest' },\n capability,\n ondisconnect\n }: {\n children: Snippet;\n currentPath?: string;\n availableRoutes?: readonly ShellRoute[];\n identity?: Identity;\n capability?: IdentitySnapshot;\n ondisconnect?: () => void;\n } = $props();\n\n const observed = $derived(\n capability ??\n (identity.kind === 'guest'\n ? { state: 'guest' as const, reason: 'disconnected' as const }\n : {\n state: 'connected' as const,\n publicKey: identity.publicKey,\n messaging: 'not_probed' as const\n })\n );\n const unavailable = $derived(\n !availableRoutes.includes('/search') ||\n !availableRoutes.includes('/about') ||\n !availableRoutes.includes('/privacy') ||\n (identity.kind === 'guest'\n ? !availableRoutes.includes('/sell') || !identity.onconnect\n : !availableRoutes.includes('/selling') ||\n !availableRoutes.includes('/messages') ||\n !identity.ondisconnect)\n );\n\n function available(href: string) {\n return (\n href === '/' ||\n availableRoutes.some((route) => route === href.split('#')[0])\n );\n }\n</script>\n\n{#snippet navigation(label: string, href: string, brand = false)}\n {#if available(href) && internalHref(href)}\n <a\n href={internalHref(href)}\n class=\"shell-link\"\n class:brand\n aria-current={currentPath === href ? 'page' : undefined}>{label}</a\n >\n {:else}\n <span\n class=\"shell-link text-muted\"\n aria-disabled=\"true\"\n aria-describedby=\"shell-availability\"\n aria-current={currentPath === href ? 'page' : undefined}>{label}</span\n >\n {/if}\n{/snippet}\n\n<a href={internalHref('#main-content')} class=\"skip-link visually-hidden\"\n >Skip to main content</a\n>\n<header class=\"navbar\">\n <nav aria-label=\"Primary\" class=\"page navbar__inner\">\n <div class=\"cluster\">\n {@render navigation('HarvestCircle', '/', true)}\n {@render navigation('Search', '/search')}\n {#if identity.kind === 'guest'}\n {@render navigation('List food', '/sell')}\n {@render navigation('Messages', '/messages')}\n {:else}\n {@render navigation('Messages', '/messages')}\n {@render navigation('Selling', '/selling')}\n <Disclosure summary=\"Identity\">\n <p class=\"key\">{identity.publicKey}</p>\n <Button\n label=\"Disconnect\"\n disabled={!identity.ondisconnect}\n onclick={identity.ondisconnect}\n />\n </Disclosure>\n {/if}\n <CapabilityGate\n focusTarget=\"navbar\"\n {ondisconnect}\n identity={observed}\n compact\n focusScope={currentPath}\n onconnect={identity.kind === 'guest' ? identity.onconnect : undefined}\n />\n </div>\n {#if unavailable}\n <p id=\"shell-availability\" class=\"text-small text-muted\">\n Unavailable during development: disabled navigation and actions.\n </p>\n {/if}\n </nav>\n</header>\n<main id=\"main-content\" tabindex=\"-1\" class=\"page\">\n {@render children()}\n</main>\n<footer class=\"footer\">\n <nav aria-label=\"Footer\" class=\"page cluster\">\n {@render navigation('About', '/about')}\n {@render navigation('Privacy', '/privacy')}\n {@render navigation('Help / report', '/about#help')}\n </nav>\n</footer>\n", + sha256: + 'a13f0c08f61cfe8ef0635263503c7d87c0946ae8b0300eeccf66602fb44de83e' + }, + 'src/lib/components/ListingEditor.svelte': { + source: + "<script lang=\"ts\">\n /* global document, setInterval, clearInterval */\n import { getContext, onMount, tick } from 'svelte';\n import ListingReview from './ListingReview.svelte';\n import ConflictNotice from './ConflictNotice.svelte';\n import ConfirmPanel from './ConfirmPanel.svelte';\n import InboxSetup from './InboxSetup.svelte';\n import {\n PUBLIC_RUNTIME_CONTEXT,\n publicRuntimeReady,\n type PublicRuntimeContext,\n type PublicRuntime\n } from '../runtime/public-runtime.ts';\n import {\n createRuntimeInboxSetupView,\n inboxSetupViewSnapshot,\n subscribeInboxSetupView,\n closeInboxSetupView,\n type InboxSetupView\n } from '../messaging/inbox-setup-view.ts';\n import {\n openEditorReview,\n editorReviewSnapshot,\n closeEditorReview,\n publishEditorRevision,\n stopEditorAction,\n editorPublicationOperation,\n type EditorReview,\n type EditorFormError\n } from '../publishing/editor-workflow.ts';\n import type { ListingOperationView } from '../publishing/listing-operation-view.ts';\n import CapabilityGate from './CapabilityGate.svelte';\n import Notice from './Notice.svelte';\n import OperationStatus from './OperationStatus.svelte';\n import { foodUnits } from '../contracts/food-availability-v1/values.ts';\n import type { PublicDraftForm } from '../contracts/local-records.ts';\n import {\n IDENTITY_VIEW_CONTEXT,\n identityViewSnapshot,\n subscribeIdentityView,\n connectIdentityView,\n disconnectIdentityView,\n type IdentityViewContext\n } from '../runtime/view-context.ts';\n import {\n openListingEditor,\n listingEditorSnapshot,\n editListingEditor,\n saveAndCloseListingEditor,\n closeListingEditor,\n subscribeListingEditor,\n listingEditorEditSource,\n observeListingEditor,\n type ListingEditor as Editor,\n type ListingEditorRoute,\n type ListingEditorSnapshot\n } from '../publishing/listing-editor.ts';\n import { internalHref } from '../navigation-url.ts';\n let {\n route,\n onfirstsave,\n onsavedclose,\n inboxController\n }: {\n route: ListingEditorRoute;\n onfirstsave?: (draftId: string, current: () => boolean) => Promise<void>;\n onsavedclose?: () => Promise<void>;\n inboxController?: InboxSetupView;\n } = $props();\n const context = getContext<IdentityViewContext>(IDENTITY_VIEW_CONTEXT);\n const publicContext = getContext<PublicRuntimeContext>(\n PUBLIC_RUNTIME_CONTEXT\n );\n let runtime = $state.raw<PublicRuntime | undefined>(),\n setup = $state.raw<InboxSetupView | undefined>();\n let setupState = $state(inboxSetupViewSnapshot(undefined));\n let review = $state.raw<EditorReview | undefined>(),\n reviewBusy = $state(false);\n let soldConfirm = $state(false),\n withdrawalConfirm = $state(false),\n publishBusy = $state(false);\n let publicationOperation = $state.raw<ListingOperationView | undefined>();\n let errors = $state<readonly EditorFormError[]>([]),\n reviewMessage = $state('');\n let identity = $state(identityViewSnapshot(context)),\n mounted = $state(false),\n editor = $state.raw<Editor | undefined>(),\n snapshot = $state<ListingEditorSnapshot>(),\n unavailable = $state(false);\n let closeBusy = $state(false),\n navigationFailed = $state(false);\n let firstNavigation: Promise<void> | undefined;\n let firstOwner: Editor | undefined;\n type Form = {\n -readonly [Key in keyof PublicDraftForm]: PublicDraftForm[Key];\n };\n const blankForm = (): Form => ({\n title: '',\n description: '',\n location: '',\n amount: '',\n currency: '',\n unit: '',\n quantity: '',\n contactType: '',\n contactValue: ''\n });\n let form = $state<Form>(blankForm());\n const admittedAuthor = $derived(\n identity.identity.state !== 'guest' && identity.identity.state !== 'pending'\n ? identity.identity.publicKey\n : undefined\n );\n const active = $derived(mounted && identity.mounted);\n const visible = $derived(\n snapshot &&\n editor &&\n identity.mounted &&\n identity.identity.state !== 'guest' &&\n identity.identity.state !== 'pending' &&\n identity.identity.publicKey === snapshot.owner &&\n listingEditorSnapshot(editor)\n );\n const editable = $derived(\n !!(visible && visible.editable && !publicationOperation && !publishBusy)\n );\n onMount(() => {\n mounted = true;\n const off = subscribeIdentityView(context, (next) => {\n identity = next;\n });\n if (publicContext)\n void publicRuntimeReady(publicContext)\n .then((value) => {\n if (mounted) runtime = value;\n })\n .catch(() => {\n /* Draft saving does not depend on inbox setup. */\n });\n return () => {\n mounted = false;\n off();\n };\n });\n $effect(() => {\n const author = admittedAuthor,\n available = active,\n source = runtime,\n supplied = inboxController;\n if (!available || !author) {\n setup = undefined;\n setupState = inboxSetupViewSnapshot(undefined);\n return;\n }\n const owned =\n supplied ?? (source && createRuntimeInboxSetupView(context, source));\n setup = owned;\n const off = owned\n ? subscribeInboxSetupView(owned, (next) => {\n setupState = next;\n })\n : () => {};\n return () => {\n off();\n if (owned) closeInboxSetupView(owned);\n };\n });\n const visibleReview = $derived.by(() => {\n if (\n (!setupState.owner && route.mode !== 'edit') ||\n !snapshot ||\n !visible ||\n !review\n )\n return;\n return editorReviewSnapshot(review) ? review : undefined;\n });\n $effect(() => {\n const resource = route,\n author = admittedAuthor,\n editRuntime = route.mode === 'edit' ? runtime : undefined;\n if (!active || !author) {\n editor = undefined;\n snapshot = undefined;\n form = blankForm();\n unavailable = false;\n return;\n }\n const cancellation = new AbortController();\n let alive = true,\n owned: Editor | undefined,\n off = () => {};\n const observer =\n resource.mode === 'edit'\n ? setInterval(() => {\n if (owned) observeListingEditor(owned);\n }, 250)\n : undefined;\n editor = undefined;\n snapshot = undefined;\n review = undefined;\n publicationOperation = undefined;\n soldConfirm = false;\n withdrawalConfirm = false;\n errors = [];\n reviewMessage = '';\n form = blankForm();\n unavailable = false;\n void openListingEditor(\n context,\n resource,\n cancellation.signal,\n editRuntime\n ).then((result) => {\n if (!alive) {\n if (result.status === 'ready') closeListingEditor(result.editor);\n return;\n }\n if (result.status !== 'ready') {\n unavailable = true;\n return;\n }\n owned = result.editor;\n editor = owned;\n const next = listingEditorSnapshot(owned);\n if (!next) {\n unavailable = true;\n return;\n }\n snapshot = next;\n form = { ...next.form };\n off = subscribeListingEditor(owned, () => {\n snapshot = owned && listingEditorSnapshot(owned);\n if (\n snapshot?.state === 'saved' &&\n snapshot.draftId &&\n resource.mode === 'new' &&\n owned &&\n firstOwner !== owned &&\n !closeBusy &&\n onfirstsave\n ) {\n firstOwner = owned;\n firstNavigation = onfirstsave(\n snapshot.draftId,\n () =>\n alive &&\n mounted &&\n editor === owned &&\n !!owned &&\n !!listingEditorSnapshot(owned)\n ).catch(() => {\n if (alive) navigationFailed = true;\n });\n }\n if (!snapshot) {\n unavailable = true;\n form = blankForm();\n }\n });\n });\n return () => {\n alive = false;\n if (observer !== undefined) clearInterval(observer);\n cancellation.abort();\n off();\n if (owned) closeListingEditor(owned);\n if (editor === owned && review) closeEditorReview(review);\n form = blankForm();\n };\n });\n function changed() {\n const original = editor;\n if (!original || !listingEditorSnapshot(original)?.editable) return;\n if (review) closeEditorReview(review);\n review = undefined;\n errors = [];\n soldConfirm = false;\n withdrawalConfirm = false;\n void editListingEditor(original, { ...form });\n }\n async function showReview(\n status: 'active' | 'sold' | 'withdrawal' = 'active'\n ) {\n const original = editor,\n resource = route,\n author = admittedAuthor;\n if (\n reviewBusy ||\n closeBusy ||\n publishBusy ||\n publicationOperation ||\n !original ||\n !listingEditorSnapshot(original)?.editable\n )\n return;\n reviewBusy = true;\n try {\n const result = await openEditorReview(\n original,\n setup,\n { ...form },\n status\n );\n if (\n !mounted ||\n editor !== original ||\n route !== resource ||\n admittedAuthor !== author ||\n !listingEditorSnapshot(original)\n ) {\n if (result.status === 'review') closeEditorReview(result.review);\n return;\n }\n if (result.status === 'blocked') {\n errors = result.errors;\n reviewMessage = result.message;\n await tick();\n document.querySelector<HTMLElement>('#listing-review-errors')?.focus();\n return;\n }\n if (review) closeEditorReview(review);\n review = result.review;\n errors = [];\n reviewMessage = '';\n await tick();\n if (mounted && editor === original && editorReviewSnapshot(result.review))\n document.querySelector<HTMLElement>('#listing-review-heading')?.focus();\n } finally {\n reviewBusy = false;\n }\n }\n async function editDetails() {\n if (review) closeEditorReview(review);\n review = undefined;\n errors = [];\n reviewMessage = '';\n await tick();\n if (mounted && editor && listingEditorSnapshot(editor)?.editable)\n document.querySelector<HTMLInputElement>('#listing-title')?.focus();\n }\n async function publishChanges() {\n const original = review,\n resource = route,\n author = admittedAuthor;\n if (\n !original ||\n publishBusy ||\n publicationOperation ||\n route.mode !== 'edit'\n )\n return;\n publishBusy = true;\n try {\n const result = await publishEditorRevision(\n original,\n editorReviewSnapshot(original)?.withdrawal\n ? 'publish_reviewed_withdrawal'\n : 'publish_reviewed_revision'\n );\n if (\n !mounted ||\n review !== original ||\n route !== resource ||\n admittedAuthor !== author\n )\n return;\n publicationOperation = editorPublicationOperation(original);\n if (result.status !== 'completed')\n reviewMessage =\n 'The update did not complete. Your proposed draft remains here. Check any retained operation before another attempt.';\n } finally {\n publishBusy = false;\n }\n }\n function fieldError(field: keyof PublicDraftForm) {\n return errors.find((value) => value.field === field);\n }\n function fieldId(field: keyof PublicDraftForm) {\n return (\n 'listing-' +\n (field === 'contactType'\n ? 'contact-type'\n : field === 'contactValue'\n ? 'contact-value'\n : field)\n );\n }\n function connect() {\n return connectIdentityView(context);\n }\n async function saveClose() {\n const original = editor,\n resource = route,\n author = admittedAuthor;\n if (\n closeBusy ||\n publishBusy ||\n publicationOperation ||\n !original ||\n !listingEditorSnapshot(original)?.editable\n )\n return;\n closeBusy = true;\n try {\n const saved = await saveAndCloseListingEditor(original);\n await firstNavigation;\n if (\n !saved ||\n !mounted ||\n editor !== original ||\n route !== resource ||\n !author ||\n admittedAuthor !== author\n )\n return;\n await onsavedclose?.();\n } catch {\n if (mounted) navigationFailed = true;\n } finally {\n closeBusy = false;\n }\n }\n function disconnect() {\n disconnectIdentityView(context);\n }\n const title = $derived(\n route.mode === 'new'\n ? 'New listing'\n : route.mode === 'draft'\n ? 'Continue draft'\n : 'Edit listing'\n );\n</script>\n\n<svelte:head\n ><title>{title} \u00b7 HarvestCircle</title><meta\n name=\"robots\"\n content=\"noindex\"\n /></svelte:head\n>\n<div class=\"page page--reading stack\">\n <a\n href={internalHref(\n route.mode === 'edit' ? `/products/${route.naddr}` : '/selling'\n )}>{route.mode === 'edit' ? 'Back to listing' : 'Back to Selling'}</a\n >\n <h1>{title}</h1>\n {#if !visible}\n <CapabilityGate\n identity={identity.identity}\n required=\"connection\"\n focusTarget=\"protected\"\n onconnect={mounted ? connect : undefined}\n ondisconnect={disconnect}\n />\n {#if unavailable}<Notice\n tone=\"warning\"\n text={route.mode === 'draft'\n ? 'This draft is not available here.'\n : route.mode === 'edit'\n ? 'Supported local listing values are not available for editing. Keep this listing read-only.'\n : 'Browser storage is unavailable. Your existing local data has not been reset.'}\n />{:else if identity.identity.state !== 'guest' && identity.identity.state !== 'pending'}<p\n role=\"status\"\n >\n Loading local values.\n </p>{/if}\n {:else}\n {#if route.mode === 'edit' && editor && listingEditorEditSource(editor)}\n <ConflictNotice\n source={listingEditorEditSource(editor)!}\n proposed={form}\n />\n {#if editable}<Notice\n tone=\"info\"\n text=\"Changes stay local until you review and publish them.\"\n />{/if}\n {/if}\n {#if !editable}<Notice\n tone=\"info\"\n text={route.mode === 'draft'\n ? 'This draft has a retained listing operation. Keep its original outcome for reconciliation.'\n : 'These retained local values are read-only until the current listing is checked.'}\n />{:else}<p>\n Changes are saved in this browser. Browser storage is not a backup.\n </p>{/if}\n {#if reviewMessage}<Notice tone=\"warning\" text={reviewMessage} />{/if}\n {#if soldConfirm && editable}<ConfirmPanel\n title=\"Confirm sold update\"\n text=\"Marking this listing as sold is a public availability update, not a payment or stock reservation receipt. Review the exact update before publishing.\"\n confirmLabel=\"Review sold update\"\n onconfirm={() => {\n soldConfirm = false;\n void showReview('sold');\n }}\n oncancel={() => {\n soldConfirm = false;\n }}\n />{/if}\n {#if withdrawalConfirm && editable}<ConfirmPanel\n title=\"Confirm removal request\"\n text=\"This public request asks clients to stop displaying the listing. It cannot erase all other copies. Review the exact target before publishing.\"\n confirmLabel=\"Review removal request\"\n onconfirm={() => {\n withdrawalConfirm = false;\n void showReview('withdrawal');\n }}\n oncancel={() => {\n withdrawalConfirm = false;\n }}\n />{/if}\n {#if visibleReview}<ListingReview\n review={visibleReview}\n onedit={editDetails}\n onpublish={route.mode === 'edit'\n ? () => {\n void publishChanges();\n }\n : undefined}\n publishing={publishBusy}\n captured={!!publicationOperation}\n />{:else}\n {#if errors.length}<div\n id=\"listing-review-errors\"\n tabindex=\"-1\"\n role=\"alert\"\n >\n <p>Check these listing fields. Your input remains here.</p>\n <ul>\n {#each errors as error (error.field)}<li>\n <a href={internalHref('#' + fieldId(error.field))}\n >{error.message}</a\n >\n </li>{/each}\n </ul>\n </div>{/if}\n <form\n class=\"stack\"\n onsubmit={(event) => event.preventDefault()}\n novalidate\n >\n <div class=\"field\">\n <label class=\"label\" for=\"listing-title\">Product name</label><input\n id=\"listing-title\"\n aria-invalid={fieldError('title') ? 'true' : undefined}\n aria-errormessage={fieldError('title')\n ? 'listing-title-error'\n : undefined}\n type=\"text\"\n value={form.title}\n oninput={(event) => {\n form = { ...form, title: event.currentTarget.value };\n changed();\n }}\n readonly={!editable}\n />\n {#if fieldError('title')}<p id=\"listing-title-error\">\n {fieldError('title')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-description\">Description</label\n ><textarea\n id=\"listing-description\"\n aria-invalid={fieldError('description') ? 'true' : undefined}\n aria-errormessage={fieldError('description')\n ? 'listing-description-error'\n : undefined}\n rows=\"6\"\n value={form.description}\n oninput={(event) => {\n form = { ...form, description: event.currentTarget.value };\n changed();\n }}\n readonly={!editable}></textarea>\n {#if fieldError('description')}<p id=\"listing-description-error\">\n {fieldError('description')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-location\">Public area</label>\n <p id=\"listing-location-hint\" class=\"text-small\">\n A town or collection area is enough.\n </p>\n <input\n id=\"listing-location\"\n aria-invalid={fieldError('location') ? 'true' : undefined}\n aria-errormessage={fieldError('location')\n ? 'listing-location-error'\n : undefined}\n type=\"text\"\n aria-describedby=\"listing-location-hint\"\n value={form.location}\n oninput={(event) => {\n form = { ...form, location: event.currentTarget.value };\n changed();\n }}\n readonly={!editable}\n />\n {#if fieldError('location')}<p id=\"listing-location-error\">\n {fieldError('location')?.message}\n </p>{/if}\n </div>\n <div class=\"cluster\">\n <div class=\"field\">\n <label class=\"label\" for=\"listing-amount\">Price</label><input\n id=\"listing-amount\"\n aria-invalid={fieldError('amount') ? 'true' : undefined}\n aria-errormessage={fieldError('amount')\n ? 'listing-amount-error'\n : undefined}\n type=\"text\"\n inputmode=\"decimal\"\n value={form.amount}\n oninput={(event) => {\n form = { ...form, amount: event.currentTarget.value };\n changed();\n }}\n readonly={!editable}\n />\n {#if fieldError('amount')}<p id=\"listing-amount-error\">\n {fieldError('amount')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-currency\">Currency</label><input\n id=\"listing-currency\"\n aria-invalid={fieldError('currency') ? 'true' : undefined}\n aria-errormessage={fieldError('currency')\n ? 'listing-currency-error'\n : undefined}\n type=\"text\"\n maxlength=\"3\"\n value={form.currency}\n oninput={(event) => {\n form = { ...form, currency: event.currentTarget.value };\n changed();\n }}\n readonly={!editable}\n />\n {#if fieldError('currency')}<p id=\"listing-currency-error\">\n {fieldError('currency')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-unit\">Per</label><select\n id=\"listing-unit\"\n aria-invalid={fieldError('unit') ? 'true' : undefined}\n aria-errormessage={fieldError('unit')\n ? 'listing-unit-error'\n : undefined}\n value={form.unit}\n onchange={(event) => {\n form = { ...form, unit: event.currentTarget.value };\n changed();\n }}\n disabled={!editable}\n ><option value=\"\">Choose a unit</option\n >{#each foodUnits as unit (unit)}<option value={unit}\n >{unit}</option\n >{/each}</select\n >\n {#if fieldError('unit')}<p id=\"listing-unit-error\">\n {fieldError('unit')?.message}\n </p>{/if}\n </div>\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-quantity\"\n >Advertised quantity (optional)</label\n >\n <p id=\"listing-quantity-unit\">\n {form.unit || 'Uses the selected price unit'}\n </p>\n <input\n id=\"listing-quantity\"\n aria-invalid={fieldError('quantity') ? 'true' : undefined}\n aria-errormessage={fieldError('quantity')\n ? 'listing-quantity-error'\n : undefined}\n type=\"text\"\n inputmode=\"decimal\"\n aria-describedby=\"listing-quantity-unit\"\n value={form.quantity}\n oninput={(event) => {\n form = { ...form, quantity: event.currentTarget.value };\n changed();\n }}\n readonly={!editable}\n />\n {#if fieldError('quantity')}<p id=\"listing-quantity-error\">\n {fieldError('quantity')?.message}\n </p>{/if}\n </div>\n <details>\n <summary>Add public contact details (optional)</summary>\n <div class=\"stack\">\n <p>Only add contact details you want to include publicly.</p>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-contact-type\"\n >Public contact type</label\n ><select\n id=\"listing-contact-type\"\n aria-invalid={fieldError('contactType') ? 'true' : undefined}\n aria-errormessage={fieldError('contactType')\n ? 'listing-contact-type-error'\n : undefined}\n value={form.contactType}\n onchange={(event) => {\n const value = event.currentTarget.value;\n if (\n value === '' ||\n value === 'email' ||\n value === 'phone' ||\n value === 'https'\n ) {\n form = { ...form, contactType: value };\n changed();\n }\n }}\n disabled={!editable}\n ><option value=\"\">No public contact</option><option\n value=\"email\">Email</option\n ><option value=\"phone\">Phone</option><option value=\"https\"\n >Website</option\n ></select\n >\n {#if fieldError('contactType')}<p id=\"listing-contact-type-error\">\n {fieldError('contactType')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-contact-value\"\n >Public contact details</label\n ><input\n id=\"listing-contact-value\"\n aria-invalid={fieldError('contactValue') ? 'true' : undefined}\n aria-errormessage={fieldError('contactValue')\n ? 'listing-contact-value-error'\n : undefined}\n type=\"text\"\n value={form.contactValue}\n oninput={(event) => {\n form = { ...form, contactValue: event.currentTarget.value };\n changed();\n }}\n readonly={!editable}\n />\n {#if fieldError('contactValue')}<p\n id=\"listing-contact-value-error\"\n >\n {fieldError('contactValue')?.message}\n </p>{/if}\n </div>\n </div>\n </details>\n </form>\n {#if editable}<button\n type=\"button\"\n onclick={() => {\n void showReview();\n }}\n disabled={reviewBusy || closeBusy}\n >{reviewBusy\n ? 'Preparing review'\n : route.mode === 'edit'\n ? 'Review changes'\n : 'Review listing'}</button\n >{/if}\n {/if}\n {#if editable && route.mode === 'edit' && !visibleReview}<details>\n <summary>Other listing actions</summary>\n <button\n type=\"button\"\n onclick={() => {\n soldConfirm = true;\n }}\n disabled={reviewBusy || closeBusy}>Mark as sold</button\n >\n <button\n type=\"button\"\n onclick={() => {\n withdrawalConfirm = true;\n }}\n disabled={reviewBusy || closeBusy}>Request removal</button\n >\n </details>{/if}\n {#if publishBusy && review && editorReviewSnapshot(review)?.withdrawal}\n <p>\n Stop stops further attempts; it cannot retract requests already sent or\n whose outcome is unknown.\n </p>\n <button\n type=\"button\"\n onclick={() => {\n if (review) stopEditorAction(review);\n }}>Stop current action</button\n >\n {/if}\n {#if publicationOperation}<OperationStatus\n publicOperation={publicationOperation}\n />{/if}\n {#if editable && route.mode !== 'edit' && setup}<InboxSetup\n controller={setup}\n inline\n />{/if}\n {#each visible.operations as operation (operation)}<OperationStatus\n publicOperation={operation}\n />{/each}\n {#if editable}<button\n type=\"button\"\n onclick={saveClose}\n disabled={closeBusy || reviewBusy}>Save and close</button\n >{/if}\n {#if navigationFailed}<Notice\n tone=\"warning\"\n text=\"Navigation did not complete. Your saved local data remains in this browser.\"\n />{/if}\n {#if editable}<p role=\"status\">\n {visible.state === 'saved'\n ? 'Saved in this browser.'\n : visible.state === 'saving'\n ? 'Saving in this browser.'\n : visible.state === 'failed'\n ? 'Not saved. Keep your current input here.'\n : 'Not yet saved.'}\n </p>\n {#if visible.failure}<Notice\n tone=\"warning\"\n text=\"Saving did not complete. Keep your current input. Existing local data has not been reset.\"\n />{/if}{/if}\n {/if}\n</div>\n", + sha256: + '060f4863f6f4f2a4fb1471bb0d5eeedf31ab13b5c83d894f47757cf5a68099e6' + }, + 'src/lib/components/MessageComposer.svelte': { + source: + "<script lang=\"ts\">\n /* global document, setInterval, clearInterval */\n import { onMount, tick } from 'svelte';\n import { beforeNavigate, goto } from '$app/navigation';\n import { internalHref } from '../navigation-url.ts';\n import {\n productRequestSnapshot,\n productRequestText,\n updateProductRequestText,\n sendProductRequest,\n requestProductRequestNavigation,\n keepProductRequestEditing,\n discardProductRequestNavigation,\n productRequestBeforeUnload,\n closeProductRequestController,\n type ProductRequestController\n } from '../messaging/product-request-controller.ts';\n import {\n replySnapshot,\n replyText,\n updateReplyText,\n sendReply,\n requestReplyNavigation,\n keepReplyEditing,\n discardReplyNavigation,\n replyBeforeUnload,\n closeReplyController,\n type ReplyController\n } from '../messaging/reply-controller.ts';\n let {\n controller,\n request,\n oncancel,\n ondiscard,\n focusScope = 'enquiry'\n }: {\n controller?: ReplyController;\n request?: ProductRequestController;\n oncancel?: () => void;\n ondiscard?: () => void;\n focusScope?: 'conversation' | 'enquiry';\n } = $props();\n let model = $state<\n | ReturnType<typeof replySnapshot>\n | ReturnType<typeof productRequestSnapshot>\n >(),\n text = $state('');\n let destination: string | undefined,\n disposed = false;\n const fieldId = $derived(\n focusScope === 'conversation' ? 'conversation-reply' : 'enquiry-reply'\n );\n function focusEditor() {\n if (disposed) return;\n if (focusScope === 'conversation')\n document.getElementById('conversation-reply')?.focus();\n else document.getElementById('enquiry-reply')?.focus();\n }\n function focusKeep() {\n if (disposed) return;\n if (focusScope === 'conversation')\n document.getElementById('conversation-keep-reply')?.focus();\n else document.getElementById('enquiry-keep-reply')?.focus();\n }\n function refresh() {\n if (disposed) return;\n model = request\n ? productRequestSnapshot(request)\n : controller && replySnapshot(controller);\n text =\n (request\n ? productRequestText(request)\n : controller && replyText(controller)) ?? '';\n }\n function askNavigation() {\n return request\n ? requestProductRequestNavigation(request)\n : controller\n ? requestReplyNavigation(controller)\n : 'invalid';\n }\n beforeNavigate((event) => {\n if (disposed || askNavigation() !== 'confirmation_required') return;\n event.cancel();\n const url = event.to?.url;\n destination =\n url && !event.willUnload\n ? internalHref(url.pathname + url.search + url.hash)\n : undefined;\n refresh();\n void tick().then(focusKeep);\n });\n onMount(() => {\n refresh();\n const timer = setInterval(refresh, 200);\n return () => {\n disposed = true;\n clearInterval(timer);\n if (request) closeProductRequestController(request);\n else if (controller) closeReplyController(controller);\n text = '';\n model = undefined;\n destination = undefined;\n };\n });\n async function send() {\n const work = request\n ? sendProductRequest(request, 'reviewed_product_request_send')\n : controller && sendReply(controller, 'reviewed_reply_send');\n refresh();\n await work;\n refresh();\n }\n function warnUnload(event: BeforeUnloadEvent) {\n if (request) productRequestBeforeUnload(request, event);\n else if (controller) replyBeforeUnload(controller, event);\n }\n</script>\n\n<svelte:window onbeforeunload={warnUnload} />\n\n{#if model}\n <div class=\"stack\">\n <label for={fieldId}>{request ? 'Your message' : 'Reply'}</label>\n <textarea\n id={fieldId}\n value={text}\n disabled={model.busy || model.state === 'completed'}\n aria-describedby={fieldId + '-save'}\n oninput={(event) => {\n if (request)\n updateProductRequestText(\n request,\n event.currentTarget.value,\n 'reviewed_private_text'\n );\n else if (controller)\n updateReplyText(\n controller,\n event.currentTarget.value,\n 'reviewed_private_text'\n );\n refresh();\n }}></textarea>\n <p id={fieldId + '-save'}>\n {model.saveCopy} Unsent text is lost when this page closes.\n </p>\n <p>{model.pairCopy}</p>\n {#if !request}<p>\n Replying moves this conversation to your inbox in this view. It does not\n accept an order.\n </p>{/if}\n <p>Messages do not reserve products or record payment.</p>\n <button\n type=\"button\"\n class=\"button button--primary\"\n disabled={model.busy ||\n model.state === 'completed' ||\n !text.trim() ||\n (!!request && !productRequestSnapshot(request)?.readyToSend)}\n onclick={() => {\n void send();\n }}>{request ? 'Send request' : 'Send reply'}</button\n >\n <p role=\"status\" aria-live=\"polite\">{model.copy}</p>\n {#if request}<button\n type=\"button\"\n class=\"button button--secondary\"\n onclick={() => {\n oncancel?.();\n destination = undefined;\n if (askNavigation() === 'allowed') ondiscard?.();\n refresh();\n void tick().then(focusKeep);\n }}>Cancel</button\n >{/if}\n {#if model.navigation === 'confirmation_required'}\n <div class=\"notice stack\" role=\"group\" aria-label=\"Unsaved private reply\">\n <p>\n Discard unsaved private text? Keep editing to preserve it. An\n outstanding extension call remains pending until it settles.\n </p>\n <div class=\"cluster\">\n <button\n type=\"button\"\n class=\"button button--secondary\"\n id={focusScope === 'conversation'\n ? 'conversation-keep-reply'\n : 'enquiry-keep-reply'}\n onclick={() => {\n if (request) keepProductRequestEditing(request);\n else if (controller) keepReplyEditing(controller);\n destination = undefined;\n refresh();\n void tick().then(focusEditor);\n }}>Keep editing</button\n >\n <button\n type=\"button\"\n class=\"button button--secondary\"\n onclick={() => {\n const target = internalHref(destination);\n const result = request\n ? discardProductRequestNavigation(\n request,\n 'reviewed_discard_private_text'\n )\n : controller\n ? discardReplyNavigation(\n controller,\n 'reviewed_discard_private_text'\n )\n : 'invalid';\n destination = undefined;\n refresh();\n if (result === 'allowed') {\n ondiscard?.();\n if (target) void goto(target);\n } else void tick().then(focusEditor);\n }}>Discard draft</button\n >\n </div>\n </div>\n {/if}\n </div>\n{/if}\n", + sha256: + 'bc8ac0e2123b60957f1c289acbb2b8740e171097029f640f657cd79f5aa8423b' + }, + 'src/lib/publishing/prepare-listing.ts': { + source: + "import { buildFoodTemplate } from '../contracts/food-availability-v1/write.ts';\nimport type {\n PublicDraftRecord,\n PublicDraftForm\n} from '../contracts/local-records.ts';\nimport { canonicalLocalId, newLocalId } from '../private-handles.ts';\nimport { readRelayPolicy, publicRelayTargets } from '../config/relays.ts';\nimport { inspectLocalTemplate } from '../nostr/local-template.ts';\nimport {\n verifyEnvelope,\n verifiedEnvelopeSnapshot\n} from '../nostr/verified-envelope.ts';\nimport {\n decodePublicRecord,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport {\n publicPublicationOwner,\n publicPublicationDraftRepository,\n savePublicListingIntent,\n type PublicPublicationRepository,\n type PublicListingSave\n} from '../persistence/public-publications.ts';\nimport {\n publicDraftControllerOwnership,\n publicDraftControllerSnapshot,\n flushPublicDraft,\n type PublicDraftController\n} from './draft-controller.ts';\nimport {\n newListingReadinessOwnership,\n captureOwnedListingReadiness,\n closeNewListingReadiness,\n type NewListingReadiness\n} from './new-listing-readiness.ts';\nimport {\n authorizeOwnedEditSource,\n type OwnedEditSource\n} from './edit-source.ts';\nimport {\n assessFutureTimestamp,\n wallClockAvailable\n} from '../catalog/clock-policy.ts';\n\ndeclare const reviewBrand: unique symbol;\nexport type ListingReview = Readonly<{ [reviewBrand]: true }>;\nexport type ListingPreview = Readonly<{\n owner: string;\n command: string;\n draftId: string;\n draftRevision: number;\n identifier: string;\n createdAtSeconds: number;\n form: PublicDraftForm;\n summary: string;\n templateWire: string;\n expectedHash: string;\n targets: readonly string[];\n policyFingerprint: string;\n withdrawal?: Readonly<{ coordinate: string; eventId: string }>;\n revision?: Readonly<{\n coordinate: string;\n publishedAtSeconds: number;\n status: 'active' | 'sold';\n }>;\n}>;\ntype Review = Readonly<{\n repository: PublicPublicationRepository;\n controller: PublicDraftController;\n expected: PublicDraftRecord;\n editVersion: number;\n command: string;\n readiness: NewListingReadiness;\n source?: OwnedEditSource;\n status?: 'active' | 'sold' | 'withdrawal';\n record: PublicRecordHandle;\n revisionBase?: Readonly<{ command: string; record: PublicRecordHandle }>;\n previewWire: string;\n current(this: void): boolean;\n}>;\nconst reviews = new WeakMap<ListingReview, Review>();\nconst commands = new WeakMap<\n PublicPublicationRepository,\n Map<string, ListingReview>\n>();\nconst activeReservations = new WeakMap<\n ListingReview,\n Promise<ListingReservation>\n>();\nexport type ListingReviewResult =\n | Readonly<{ status: 'review'; review: ListingReview }>\n | Readonly<{\n status: 'blocked';\n reason:\n | 'invalid_scope'\n | 'invalid_command'\n | 'unavailable'\n | 'invalid_form'\n | 'conflict';\n }>;\nexport type ListingReservation =\n PublicListingSave | Readonly<{ status: 'invalid' }>;\n// Review flushes local draft state and prepares an exact immutable template;\n// it neither reserves a publication nor asks the extension to sign.\nexport async function reviewNewListing(\n repository: PublicPublicationRepository,\n controller: PublicDraftController,\n readiness: NewListingReadiness,\n command: unknown,\n consent: unknown\n): Promise<ListingReviewResult> {\n return reviewListing(repository, controller, readiness, command, consent);\n}\n// Pure declared clock policy; production supplies actual Date.now below.\nexport function ownedRevisionTimestamp(\n head: number,\n now: number\n): number | undefined {\n if (\n !Number.isSafeInteger(head) ||\n head < 0 ||\n head >= Number.MAX_SAFE_INTEGER ||\n !wallClockAvailable(now)\n )\n return;\n const next = Math.max(head + 1, Math.floor(now));\n return assessFutureTimestamp(next, now) === 'within_policy'\n ? next\n : undefined;\n}\nexport async function reviewOwnedListing(\n source: OwnedEditSource,\n controller: PublicDraftController,\n command: unknown,\n status: 'active' | 'sold' | 'withdrawal',\n consent: unknown\n): Promise<ListingReviewResult> {\n const original = authorizeOwnedEditSource(source);\n if (!original) return { status: 'blocked', reason: 'invalid_scope' };\n return reviewListing(\n original.repository,\n controller,\n undefined,\n command,\n consent,\n { source, status }\n );\n}\nasync function reviewListing(\n repository: PublicPublicationRepository,\n controller: PublicDraftController,\n readiness: NewListingReadiness | undefined,\n command: unknown,\n consent: unknown,\n revision?: Readonly<{\n source: OwnedEditSource;\n status: 'active' | 'sold' | 'withdrawal';\n }>\n): Promise<ListingReviewResult> {\n try {\n const custody = publicDraftControllerOwnership(controller),\n owner = publicPublicationOwner(repository);\n if (\n !custody ||\n !owner ||\n custody.repository !== publicPublicationDraftRepository(repository)\n )\n return { status: 'blocked', reason: 'invalid_scope' };\n const id = canonicalLocalId(command);\n if (!id) return { status: 'blocked', reason: 'invalid_command' };\n const retained = revision && authorizeOwnedEditSource(revision.source);\n const ready = revision ? retained : newListingReadinessOwnership(readiness);\n if (\n !ready ||\n ready.owner !== owner ||\n !ready.current() ||\n consent !==\n (revision\n ? revision.status === 'withdrawal'\n ? 'reviewed_owned_withdrawal'\n : revision.status === 'sold'\n ? 'reviewed_sold_availability'\n : 'reviewed_owned_revision'\n : 'reviewed_new_listing')\n )\n return { status: 'blocked', reason: 'unavailable' };\n if (!(await flushPublicDraft(controller)))\n return { status: 'blocked', reason: 'unavailable' };\n const snapshot = publicDraftControllerSnapshot(controller),\n expected = snapshot?.draft;\n if (\n !snapshot ||\n !expected ||\n expected.owner !== owner ||\n !custody.current(JSON.stringify(expected), snapshot.editVersion)\n )\n return { status: 'blocked', reason: 'conflict' };\n const cached = commands.get(repository)?.get(id);\n if (cached) {\n const original = reviews.get(cached);\n if (\n original &&\n original.controller === controller &&\n (revision\n ? original.source === revision.source &&\n original.status === revision.status\n : original.readiness === readiness) &&\n JSON.stringify(original.expected) === JSON.stringify(expected) &&\n original.current() &&\n custody.current(JSON.stringify(expected), snapshot.editVersion)\n ) {\n return { status: 'review', review: cached };\n }\n return { status: 'blocked', reason: 'conflict' };\n }\n const baseProof = retained && verifyEnvelope(retained.baseWire);\n const base = baseProof?.ok\n ? verifiedEnvelopeSnapshot(baseProof.value)\n : undefined;\n const identifier = revision\n ? base?.tags.find((tag) => tag[0] === 'd')?.[1]\n : newLocalId();\n const now = Math.floor(Date.now() / 1000);\n const createdAtSeconds = revision\n ? base && ownedRevisionTimestamp(base.created_at, now)\n : now;\n if (!identifier || createdAtSeconds === undefined)\n return {\n status: 'blocked',\n reason: revision ? 'conflict' : 'unavailable'\n };\n const form = expected.form;\n const withdrawal = revision?.status === 'withdrawal';\n if (!withdrawal && form.contactType === '' && form.contactValue !== '')\n return { status: 'blocked', reason: 'invalid_form' };\n const contact =\n form.contactType === ''\n ? undefined\n : {\n type: form.contactType,\n value: form.contactValue,\n public: true as const\n };\n const built = buildFoodTemplate({\n identifier,\n title: form.title,\n description: form.description,\n location: form.location,\n amount: form.amount,\n currency: form.currency,\n unit: form.unit,\n ...(form.quantity === '' ? {} : { quantity: form.quantity }),\n created_at: createdAtSeconds,\n published_at: retained ? retained.publishedAtSeconds : createdAtSeconds,\n status: revision?.status === 'sold' ? 'sold' : 'active',\n ...(contact ? { contact } : {})\n });\n if (!withdrawal && !built.ok)\n return { status: 'blocked', reason: 'invalid_form' };\n const manifest = readRelayPolicy(ready.policy),\n targets = publicRelayTargets(ready.policy, 'write');\n const templateWire = JSON.stringify({\n pubkey: owner,\n kind: withdrawal ? 5 : 30402,\n created_at: createdAtSeconds,\n tags:\n withdrawal && base\n ? [\n ['e', base.id],\n ['a', `30402:${owner}:${identifier}`],\n ['k', '30402']\n ]\n : built.ok\n ? built.wire_parts.tags\n : [],\n content: withdrawal ? '' : built.ok ? built.wire_parts.content : ''\n });\n const template = inspectLocalTemplate(\n templateWire,\n owner,\n withdrawal ? 5 : 30402\n );\n if (!template || !manifest.postingEnabled || targets.length === 0)\n return { status: 'blocked', reason: 'unavailable' };\n const digest = await crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(JSON.stringify(manifest))\n );\n const policyFingerprint = Array.from(new Uint8Array(digest), (value) =>\n value.toString(16).padStart(2, '0')\n ).join('');\n // Hashing is outside any IDB transaction; recheck original mutable owners.\n if (\n !ready.current() ||\n publicPublicationOwner(repository) !== owner ||\n !custody.current(JSON.stringify(expected), snapshot.editVersion)\n )\n return { status: 'blocked', reason: 'conflict' };\n // Another review may have completed while this one awaited hashing. The\n // first retained command owns its ID/time/template; never replace it.\n const racing = commands.get(repository)?.get(id);\n if (racing) {\n const original = reviews.get(racing);\n if (\n original &&\n original.controller === controller &&\n (revision\n ? original.source === revision.source &&\n original.status === revision.status\n : original.readiness === readiness) &&\n JSON.stringify(original.expected) === JSON.stringify(expected) &&\n original.current() &&\n custody.current(JSON.stringify(expected), snapshot.editVersion)\n )\n return { status: 'review', review: racing };\n return { status: 'blocked', reason: 'conflict' };\n }\n const admitted = decodePublicRecord(\n JSON.stringify({\n schema: 1,\n family: 'public_operation',\n owner,\n id,\n revision: 0,\n source:\n withdrawal && retained\n ? { type: 'public_head', wire: retained.baseWire }\n : { type: 'draft', id: expected.id, revision: expected.revision },\n capture: {\n kind: withdrawal ? 5 : 30402,\n wire: templateWire,\n hash: template.hash,\n targets,\n policyFingerprint\n },\n artifact: null,\n receipts: []\n }),\n owner,\n id\n );\n if (!admitted.ok) return { status: 'blocked', reason: 'invalid_form' };\n const proof = revision\n ? captureOwnedListingReadiness(\n revision.source,\n template.hash,\n withdrawal ? 'reviewed_owned_withdrawal' : 'reviewed_owned_listing'\n )\n : readiness;\n const finalReady = newListingReadinessOwnership(proof);\n if (!proof || !finalReady || !finalReady.current())\n return { status: 'blocked', reason: 'conflict' };\n const review = Object.freeze({}) as ListingReview;\n reviews.set(review, {\n repository,\n controller,\n expected,\n editVersion: snapshot.editVersion,\n command: id,\n readiness: proof,\n ...(revision ? { source: revision.source, status: revision.status } : {}),\n record: admitted.value,\n ...(retained\n ? {\n revisionBase: {\n command: retained.sourceCommand,\n record: retained.sourceRecord\n }\n }\n : {}),\n previewWire: JSON.stringify({\n owner,\n command: id,\n draftId: expected.id,\n draftRevision: expected.revision,\n identifier,\n createdAtSeconds,\n form,\n summary: withdrawal ? 'Removal request' : built.ok ? built.summary : '',\n templateWire,\n expectedHash: template.hash,\n targets,\n policyFingerprint,\n ...(withdrawal && retained && base\n ? {\n withdrawal: { coordinate: retained.coordinate, eventId: base.id }\n }\n : {}),\n ...(retained && revision && !withdrawal\n ? {\n revision: {\n coordinate: retained.coordinate,\n publishedAtSeconds: retained.publishedAtSeconds,\n status: revision.status\n }\n }\n : {})\n }),\n current: () =>\n finalReady.current() &&\n publicPublicationOwner(repository) === owner &&\n (!revision ||\n assessFutureTimestamp(\n createdAtSeconds,\n Math.floor(Date.now() / 1000)\n ) === 'within_policy')\n });\n const cache = commands.get(repository) ?? new Map<string, ListingReview>();\n cache.set(id, review);\n commands.set(repository, cache);\n return { status: 'review', review };\n } catch {\n return { status: 'blocked', reason: 'unavailable' };\n }\n}\nexport function listingReviewSnapshot(\n review: ListingReview\n): ListingPreview | undefined {\n const value = reviews.get(review);\n return value ? (JSON.parse(value.previewWire) as ListingPreview) : undefined;\n}\nexport function closeListingReview(review: ListingReview): void {\n const original = reviews.get(review);\n if (original) closeNewListingReadiness(original.readiness);\n}\n// Internal original custody, not a signing or transport permission. The later\n// controller must reread the persisted intent and obtain its own effect lease.\nexport function listingReviewOwnership(review: ListingReview) {\n const original = reviews.get(review);\n const ready = original && newListingReadinessOwnership(original.readiness);\n return original && ready && original.current()\n ? {\n repository: original.repository,\n record: original.record,\n command: original.command,\n readiness: ready,\n current: original.current\n }\n : undefined;\n}\n// One original review deduplicates simultaneous clicks. Failed/uncertain work\n// remains the same capture for later explicit retry; no fresh ID/time/template.\nexport function reserveNewListing(\n review: ListingReview,\n consent: unknown\n): Promise<ListingReservation> {\n const value = reviews.get(review);\n if (!value || consent !== 'publish_reviewed_listing')\n return Promise.resolve({ status: 'invalid' });\n const active = activeReservations.get(review);\n if (active) return active;\n const work = savePublicListingIntent(\n value.repository,\n value.controller,\n value.record,\n value.expected,\n value.editVersion,\n value.command,\n value.current,\n value.revisionBase\n ).finally(() => {\n if (activeReservations.get(review) === work)\n activeReservations.delete(review);\n });\n activeReservations.set(review, work);\n return work;\n}\n", + sha256: + '00b922e8b0bfc73cf5ac59857472e8dd627c8df62d28f1c646c5d7c76ce5ede9' + }, + 'src/lib/nostr/listing-publisher.ts': { + source: + "import type { NostrEvent } from 'applesauce-core/helpers';\nimport {\n publicRelayTargets,\n readRelayPolicy,\n type RelayPolicy\n} from '../config/relays.ts';\nimport {\n listingPublicationOwnership,\n type ListingPublication\n} from '../publishing/sign-listing.ts';\nimport {\n listingResumeOwnership,\n type ListingResumption\n} from '../publishing/resume-listing.ts';\nimport {\n listingRetryOwnership,\n type ListingRetry\n} from '../publishing/retry-listing.ts';\nimport {\n identityMessagingOwnership,\n identityPublicOperationOwnership,\n recheckIdentityOwner,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport { preferencePolicyFingerprint } from './inbox-preference-publication.ts';\nimport { readPublicListingIntent } from '../persistence/public-publications.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot,\n type PublicRecordHandle\n} from '../persistence/records.ts';\ndeclare const leaseBrand: unique symbol;\ndeclare const permissionBrand: unique symbol;\nexport type ListingDeliveryLease = Readonly<{ [leaseBrand]: true }>;\nexport type ListingAttemptPermission = Readonly<{ [permissionBrand]: true }>;\ntype Original = NonNullable<\n | ReturnType<typeof listingPublicationOwnership>\n | ReturnType<typeof listingResumeOwnership>\n>;\ntype Owner = Readonly<{\n original: Original;\n policy: RelayPolicy;\n signal?: AbortSignal;\n current(): boolean;\n}>;\ntype Permission = Readonly<{\n owner: Owner;\n origin: string;\n mode: 'publish' | 'readback';\n wire: string;\n}>;\nconst leases = new WeakMap<ListingDeliveryLease, Owner>();\nconst permissions = new WeakMap<ListingAttemptPermission, Permission>();\n// Stop releases this action's wait and author lock. The extension promise may\n// settle later; it cannot resurrect the revoked network lease or a signer.\nasync function recheckDeliveryOwner(\n identity: IdentitySession,\n signal?: AbortSignal\n): Promise<boolean> {\n if (signal?.aborted) return false;\n if (!signal) {\n await recheckIdentityOwner(identity);\n return true;\n }\n let stop = () => {};\n const stopped = new Promise<boolean>((resolve) => {\n stop = () => resolve(false);\n signal.addEventListener('abort', stop, { once: true });\n if (signal.aborted) stop();\n });\n try {\n return await Promise.race([\n recheckIdentityOwner(identity).then(() => true),\n stopped\n ]);\n } finally {\n signal.removeEventListener('abort', stop);\n }\n}\n// Receipt revisions may grow, but the complete original operation payload and\n// verified artifact stay exact. No new command, author or destination is adopted.\nexport async function readRetainedListingDelivery(\n lease: ListingDeliveryLease\n): Promise<PublicRecordHandle | undefined> {\n const owner = leases.get(lease);\n if (!owner) return;\n const original = owner.original;\n const expected = decodePublicRecord(\n original.recordWire,\n original.owner,\n original.command\n );\n if (!expected.ok) return;\n const baseline = publicRecordSnapshot(\n expected.value,\n original.owner,\n original.command\n );\n if (\n baseline?.family !== 'public_operation' ||\n !(\n baseline.capture.kind === 30402 ||\n (baseline.capture.kind === 5 && baseline.source.type === 'public_head')\n ) ||\n !baseline.artifact ||\n baseline.revision !== 2\n )\n return;\n const read = await readPublicListingIntent(\n original.repository,\n original.command\n );\n if (read.status !== 'found') return;\n const row = publicRecordSnapshot(\n read.record,\n original.owner,\n original.command\n );\n if (\n row?.family !== 'public_operation' ||\n row.revision < baseline.revision ||\n JSON.stringify({\n ...row,\n revision: baseline.revision,\n receipts: baseline.receipts\n }) !== JSON.stringify(baseline)\n )\n return;\n return read.record;\n}\n// Current authority is mandatory for every new network permission. Retained\n// exact storage observation above remains usable for bookkeeping after Stop.\nexport async function readOwnedListingDelivery(\n lease: ListingDeliveryLease\n): Promise<PublicRecordHandle | undefined> {\n const owner = leases.get(lease);\n if (!owner?.current()) return;\n const read = readRetainedListingDelivery(lease);\n let stop = () => {};\n const stopped =\n owner.signal &&\n new Promise<undefined>((resolve) => {\n stop = () => resolve(undefined);\n owner.signal!.addEventListener('abort', stop, { once: true });\n if (owner.signal!.aborted) stop();\n });\n let record: PublicRecordHandle | undefined;\n try {\n record = await (stopped ? Promise.race([read, stopped]) : read);\n } finally {\n owner.signal?.removeEventListener('abort', stop);\n }\n return owner.current() ? record : undefined;\n}\nexport function listingDeliveryOwnership(lease: ListingDeliveryLease) {\n const owner = leases.get(lease);\n return owner?.current()\n ? {\n repository: owner.original.repository,\n owner: owner.original.owner,\n command: owner.original.command,\n current: owner.current\n }\n : undefined;\n}\nexport type ListingOwnershipResult<T> =\n | Readonly<{ status: 'completed'; value: T }>\n | Readonly<{ status: 'invalid' | 'unavailable' | 'busy' | 'stopped' }>;\n// One original author lock spans this finite explicitly requested network\n// action. It never spans a native IDB transaction and cannot mint a signer.\nexport async function withListingDeliveryOwnership<T>(\n publication: ListingPublication | ListingResumption,\n policy: RelayPolicy,\n consent: unknown,\n work: (lease: ListingDeliveryLease) => Promise<T>,\n control?: ListingRetry\n): Promise<ListingOwnershipResult<T>> {\n const signed = listingPublicationOwnership(publication as ListingPublication),\n resumed = listingResumeOwnership(publication as ListingResumption),\n original = signed ?? resumed,\n retry = control && listingRetryOwnership(control);\n if (\n !original ||\n (control\n ? !retry ||\n retry.source !== publication ||\n retry.policy !== policy ||\n retry.consent !== consent\n : !signed || consent !== 'publish_stored_listing') ||\n original.policy !== policy\n )\n return { status: 'invalid' };\n if (retry && !retry.current()) return { status: 'stopped' };\n if (typeof window === 'undefined' || !navigator.locks?.request)\n return { status: 'unavailable' };\n try {\n return await navigator.locks.request(\n 'harvestcircle:owner:' + original.owner,\n { mode: 'exclusive', ifAvailable: true },\n async (lock): Promise<ListingOwnershipResult<T>> => {\n if (!lock) return { status: 'busy' };\n if (!(await recheckDeliveryOwner(original.identity, retry?.signal)))\n return { status: 'stopped' };\n const operation =\n signed &&\n identityPublicOperationOwnership(\n original.identity,\n signed.operation\n ),\n // A signed public update retains its original public operation.\n // New-listing inbox readiness stays in original.current(); edits\n // do not require a messaging probe. Resumptions keep their gate.\n identity = signed\n ? operation\n : identityMessagingOwnership(original.identity);\n if (\n !identity ||\n (signed && !operation) ||\n identity.owner !== original.owner ||\n (operation &&\n (operation.owner !== original.owner ||\n operation.session !== identity.session)) ||\n !original.current() ||\n (retry && !retry.current())\n )\n return { status: 'stopped' };\n let active = true;\n const owner: Owner = {\n original,\n policy,\n signal: retry?.signal,\n current: () =>\n active &&\n original.current() &&\n identity.current() &&\n (!operation || operation.current()) &&\n (!retry || retry.current())\n };\n const lease = Object.freeze({}) as ListingDeliveryLease;\n leases.set(lease, owner);\n try {\n if (!(await readOwnedListingDelivery(lease)))\n return {\n status: retry && !retry.current() ? 'stopped' : 'unavailable'\n };\n return { status: 'completed', value: await work(lease) };\n } finally {\n active = false;\n }\n }\n );\n } catch {\n return { status: 'unavailable' };\n }\n}\n// Each permission comes from actual stored signed bytes, fresh identity and\n// unchanged original policy. Preference/private capabilities cannot enter it.\nexport async function authorizeListingAttempt(\n lease: ListingDeliveryLease,\n origin: string,\n mode: 'publish' | 'readback'\n): Promise<ListingAttemptPermission | undefined> {\n const owner = leases.get(lease);\n if (!owner || !owner.current() || (mode !== 'publish' && mode !== 'readback'))\n return;\n try {\n const record = await readOwnedListingDelivery(lease),\n original = owner.original;\n const row =\n record && publicRecordSnapshot(record, original.owner, original.command);\n const manifest = readRelayPolicy(owner.policy),\n targets = publicRelayTargets(owner.policy, 'write'),\n fingerprint = await preferencePolicyFingerprint(owner.policy);\n if (\n row?.family !== 'public_operation' ||\n !row.artifact ||\n !manifest.postingEnabled ||\n !manifest.messagingEnabled ||\n fingerprint !== row.capture.policyFingerprint ||\n JSON.stringify(targets) !== JSON.stringify(row.capture.targets) ||\n !row.capture.targets.includes(origin)\n )\n return;\n if (!(await recheckDeliveryOwner(original.identity, owner.signal))) return;\n if (!owner.current()) return;\n const token = Object.freeze({}) as ListingAttemptPermission;\n permissions.set(token, { owner, origin, mode, wire: row.artifact.wire });\n return token;\n } catch {\n return;\n }\n}\n// Original once-only token: detached metadata, wrong role, policy or origin\n// cannot supply a raw event. SDK effects remain owned by the public pool.\nexport function takeListingPublication(\n token: ListingAttemptPermission,\n policy: RelayPolicy,\n origin: string,\n mode: 'publish' | 'readback'\n):\n | Readonly<{ event: NostrEvent; wire: string; current(): boolean }>\n | undefined {\n const saved = permissions.get(token);\n if (!saved) return;\n permissions.delete(token);\n if (\n saved.owner.policy !== policy ||\n saved.origin !== origin ||\n saved.mode !== mode ||\n !saved.owner.current()\n )\n return;\n return {\n event: JSON.parse(saved.wire) as NostrEvent,\n wire: saved.wire,\n current: saved.owner.current\n };\n}\n", + sha256: + '10032c32482a766158d8a69027056e6a822a16b5f68ab9754b0f1cf42d0608f9' + }, + 'src/lib/publishing/resume-listing.ts': { + source: + "import {\n publicPublicationOwner,\n readPublicListingIntent,\n type PublicPublicationRepository\n} from '../persistence/public-publications.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot\n} from '../persistence/records.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport {\n identityMessagingOwnership,\n recheckIdentityOwner,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport {\n publicRelayTargets,\n readRelayPolicy,\n type RelayPolicy\n} from '../config/relays.ts';\nimport { preferencePolicyFingerprint } from '../nostr/inbox-preference-publication.ts';\nimport type { PublicPool } from '../nostr/public-pool.ts';\nimport { beginListingRetry } from './retry-listing.ts';\n\ndeclare const resumeBrand: unique symbol;\nexport type ListingResumption = Readonly<{ [resumeBrand]: true }>;\ntype Ownership = Readonly<{\n repository: PublicPublicationRepository;\n identity: IdentitySession;\n policy: RelayPolicy;\n owner: string;\n command: string;\n recordWire: string;\n current(): boolean;\n}>;\nconst resumptions = new WeakMap<ListingResumption, Ownership>();\nexport function listingResumeOwnership(token: ListingResumption) {\n const original = resumptions.get(token);\n return original?.current() ? original : undefined;\n}\nexport function listingResumeSnapshot(token: ListingResumption) {\n const original = listingResumeOwnership(token);\n if (!original) return;\n const decoded = decodePublicRecord(\n original.recordWire,\n original.owner,\n original.command\n );\n const row =\n decoded.ok &&\n publicRecordSnapshot(decoded.value, original.owner, original.command);\n if (!row || row.family !== 'public_operation' || !row.artifact) return;\n return {\n owner: row.owner,\n command: row.id,\n hash: row.artifact.eventId,\n wire: row.artifact.wire,\n targets: row.capture.targets.slice(),\n policyFingerprint: row.capture.policyFingerprint\n };\n}\nexport async function prepareListingResume(\n repository: PublicPublicationRepository,\n identity: IdentitySession,\n policy: RelayPolicy,\n command: unknown,\n consent: unknown\n): Promise<\n | Readonly<{ status: 'ready'; resume: ListingResumption }>\n | Readonly<{ status: 'invalid' | 'unavailable' | 'needs_action' }>\n> {\n const owner = publicPublicationOwner(repository),\n id = canonicalLocalId(command);\n if (\n !owner ||\n !id ||\n !identityMessagingOwnership(identity) ||\n consent !== 'reviewed_stored_listing_resume'\n )\n return { status: 'invalid' };\n if (typeof window === 'undefined' || !navigator.locks?.request)\n return { status: 'unavailable' };\n try {\n await recheckIdentityOwner(identity);\n const capture = identityMessagingOwnership(identity);\n if (!capture || capture.owner !== owner) return { status: 'needs_action' };\n const current = () =>\n capture.current() && publicPublicationOwner(repository) === owner;\n const read = await readPublicListingIntent(repository, id);\n const row =\n read.status === 'found' && publicRecordSnapshot(read.record, owner, id);\n const manifest = readRelayPolicy(policy),\n targets = publicRelayTargets(policy, 'write'),\n fingerprint = await preferencePolicyFingerprint(policy);\n if (\n !current() ||\n !row ||\n row.family !== 'public_operation' ||\n row.capture.kind !== 30402 ||\n !row.artifact ||\n row.revision < 2 ||\n !manifest.postingEnabled ||\n !manifest.messagingEnabled ||\n fingerprint !== row.capture.policyFingerprint ||\n JSON.stringify(targets) !== JSON.stringify(row.capture.targets)\n )\n return { status: 'needs_action' };\n // Normalize receipt bookkeeping only. Every original capture field and the\n // independently verified stored signature remain exact; no signer is minted.\n const recordWire = JSON.stringify({ ...row, revision: 2, receipts: [] });\n if (!decodePublicRecord(recordWire, owner, id).ok || !current())\n return { status: 'needs_action' };\n const resume = Object.freeze({}) as ListingResumption;\n resumptions.set(resume, {\n repository,\n identity,\n policy,\n owner,\n command: id,\n recordWire,\n current\n });\n return { status: 'ready', resume };\n } catch {\n return { status: 'needs_action' };\n }\n}\nexport function resumeListing(\n token: ListingResumption,\n pool: PublicPool,\n consent: unknown\n) {\n const original = listingResumeOwnership(token);\n if (!original || consent !== 'resume_stored_listing') return;\n return beginListingRetry(token, pool, original.policy, consent);\n}\n", + sha256: + '42cd0404f1e543e03350e6c8c92fce5a1c4f8eb02f9540831fc6c7cf84bba9a9' + }, + 'src/lib/messaging/inbox-setup.ts': { + source: + "import { exactLocalFields } from '../contracts/local-records.ts';\nimport { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';\nimport { safeUnsignedInteger } from '../nostr/envelope-bounds.ts';\nimport { inspectLocalTemplate } from '../nostr/local-template.ts';\nimport {\n inboxPreferenceSnapshot,\n inboxPreferenceWire\n} from '../nostr/inbox-preferences.ts';\nimport {\n canonicalRelayOrigin,\n readRelayPolicy,\n publicRelayTargets,\n inboxRelayTargets,\n type RelayPolicy\n} from '../config/relays.ts';\nimport {\n identityMessagingOwnership,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport {\n inboxResolutionSnapshot,\n inboxResolverCurrentAfterSample,\n type InboxResolver\n} from './resolve-inbox.ts';\n\ndeclare const reviewBrand: unique symbol;\nexport type InboxSetupReview = Readonly<{ [reviewBrand]: true }>;\ntype Preview = {\n author: string;\n originalWire: string | null;\n baseId: string | null;\n wire: string;\n hash: string;\n policyFingerprint: string;\n selectedInboxes: string[];\n destinations: string[];\n removedTagIndices: number[];\n removedExtraFields: string[];\n globalEffect: string;\n};\ntype Saved = Readonly<{\n identity: IdentitySession;\n session: symbol;\n policy: RelayPolicy;\n previewWire: string;\n}>;\nconst reviews = new WeakMap<InboxSetupReview, Saved>();\nconst globalEffect =\n 'This replaces your public inbox preference for other clients. Relay acceptance and readback are still required; this review does not publish.';\nfunction base(resolver: InboxResolver, policy: RelayPolicy, owner: string) {\n const resolution = inboxResolutionSnapshot(resolver),\n discovery = publicRelayTargets(policy, 'read');\n if (\n resolution.author !== owner ||\n resolution.coverage !== 'bounded-eose' ||\n resolution.status === 'inconclusive' ||\n discovery.length === 0 ||\n discovery.length !== resolution.sources.length ||\n !discovery.every((origin) =>\n resolution.sources.some(\n (row) => row.source === origin && row.state === 'eose'\n )\n )\n )\n return undefined;\n if (resolution.status === 'missing')\n return !resolution.head && !resolution.knownBase\n ? { wire: null, id: null, createdAt: undefined }\n : undefined;\n const head = resolution.head && inboxPreferenceSnapshot(resolution.head),\n wire = resolution.head && inboxPreferenceWire(resolution.head);\n return head &&\n wire &&\n head.author === owner &&\n head.id === resolution.knownBase?.id\n ? { wire, id: head.id, createdAt: head.createdAt }\n : undefined;\n}\n// Explicit source review only. The clock is an internal observation port like\n// the resolver clock; production uses actual wall time, tests control it. No\n// caller event extras enter the canonical signing contract implicitly.\nexport async function reviewInboxSetup(\n identity: IdentitySession,\n resolver: InboxResolver,\n policy: RelayPolicy,\n raw: unknown,\n observeNow: () => number = () => Math.floor(Date.now() / 1000)\n): Promise<\n | Readonly<{ status: 'review'; review: InboxSetupReview }>\n | Readonly<{ status: 'blocked'; reason: string }>\n> {\n try {\n const capture = identityMessagingOwnership(identity),\n manifest = readRelayPolicy(policy);\n if (\n !capture ||\n !capture.current() ||\n !manifest.messagingEnabled ||\n !manifest.postingEnabled\n )\n return { status: 'blocked', reason: 'unavailable' };\n const previous = base(resolver, policy, capture.owner);\n if (!previous || typeof raw !== 'string' || !boundedUtf8(raw, 65536))\n return { status: 'blocked', reason: 'unavailable' };\n const input: unknown = JSON.parse(raw);\n if (\n !exactLocalFields(input, [\n 'selectedInboxes',\n 'removeTagIndices',\n 'removeExtraFields',\n 'createdAt'\n ]) ||\n !Array.isArray(input.selectedInboxes) ||\n input.selectedInboxes.length < 1 ||\n input.selectedInboxes.length > 3 ||\n !Array.isArray(input.removeTagIndices) ||\n !Array.isArray(input.removeExtraFields)\n )\n return { status: 'blocked', reason: 'invalid_selection' };\n const time = safeUnsignedInteger(input.createdAt),\n now = safeUnsignedInteger(observeNow());\n if (\n time === undefined ||\n now !== time ||\n (previous.createdAt !== undefined && time <= previous.createdAt)\n )\n return { status: 'blocked', reason: 'clock_conflict' };\n const selected: string[] = [];\n function appendSelected(value: string) {\n selected.push(value);\n }\n for (const value of input.selectedInboxes as unknown[]) {\n if (\n typeof value !== 'string' ||\n selected.includes(value) ||\n !inboxRelayTargets(policy, [value], 'read').includes(value) ||\n !inboxRelayTargets(policy, [value], 'write').includes(value)\n )\n return { status: 'blocked', reason: 'invalid_selection' };\n appendSelected(value);\n }\n const old =\n previous.wire === null\n ? undefined\n : (JSON.parse(previous.wire) as { tags: string[][]; content: string });\n const tags = old?.tags ?? [];\n const removeTags: number[] = [],\n removeFields: string[] = [];\n function appendTagIndex(value: number) {\n removeTags.push(value);\n }\n function appendField(value: string) {\n removeFields.push(value);\n }\n if (\n input.removeTagIndices.length > tags.length ||\n input.removeExtraFields.length > 64\n )\n return { status: 'blocked', reason: 'invalid_selection' };\n for (const index of input.removeTagIndices as unknown[]) {\n if (\n typeof index !== 'number' ||\n safeUnsignedInteger(index) === undefined ||\n index >= tags.length ||\n removeTags.includes(index)\n )\n return { status: 'blocked', reason: 'invalid_selection' };\n appendTagIndex(index);\n }\n const standard = [\n 'id',\n 'sig',\n 'pubkey',\n 'kind',\n 'created_at',\n 'tags',\n 'content'\n ];\n const extras: string[] = [];\n function appendExtra(value: string) {\n extras.push(value);\n }\n if (old)\n for (const key in old) if (!standard.includes(key)) appendExtra(key);\n for (const key of input.removeExtraFields as unknown[]) {\n if (\n typeof key !== 'string' ||\n !extras.includes(key) ||\n removeFields.includes(key)\n )\n return { status: 'blocked', reason: 'invalid_selection' };\n appendField(key);\n }\n // Unsigned extra fields cannot survive the existing exact five-field signer.\n // Block until the owner chooses every removal; retaining only the old source\n // would not constitute preservation in the outgoing replacement.\n if (extras.some((key) => !removeFields.includes(key)))\n return { status: 'blocked', reason: 'unsupported_extra_fields' };\n let nextTags = tags.filter((_tag, index) => !removeTags.includes(index));\n for (const origin of selected)\n if (\n !nextTags.some(\n (tag) => tag.length === 2 && tag[0] === 'relay' && tag[1] === origin\n )\n )\n nextTags = nextTags.concat([['relay', origin]]);\n // Reuse the public preference grammar without signing a synthetic event:\n // every retained relay tag must remain a canonical advertised origin. Other\n // tags/content/order/duplicates survive unchanged, including >3 advertisements.\n if (\n nextTags.some(\n (tag) =>\n tag[0] === 'relay' &&\n (tag.length !== 2 || !canonicalRelayOrigin(tag[1]))\n )\n )\n return { status: 'blocked', reason: 'unsupported_profile' };\n const wire = JSON.stringify({\n pubkey: capture.owner,\n kind: 10050,\n created_at: time,\n tags: nextTags,\n content: old?.content ?? ''\n });\n const template = inspectLocalTemplate(wire, capture.owner, 10050),\n destinations = publicRelayTargets(policy, 'write');\n if (!template || destinations.length === 0)\n return { status: 'blocked', reason: 'unsupported_profile' };\n const digest = await crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(JSON.stringify(manifest))\n );\n const policyFingerprint = Array.from(new Uint8Array(digest), (value) =>\n value.toString(16).padStart(2, '0')\n ).join('');\n if (!capture.current() || !inboxResolverCurrentAfterSample(resolver))\n return { status: 'blocked', reason: 'unavailable' };\n const preview: Preview = {\n author: capture.owner,\n originalWire: previous.wire,\n baseId: previous.id,\n wire,\n hash: template.hash,\n policyFingerprint,\n selectedInboxes: selected,\n destinations: destinations.slice(),\n removedTagIndices: removeTags,\n removedExtraFields: removeFields,\n globalEffect\n };\n const review = Object.freeze({}) as InboxSetupReview;\n reviews.set(review, {\n identity,\n session: capture.session,\n policy,\n previewWire: JSON.stringify(preview)\n });\n return { status: 'review', review };\n } catch {\n return { status: 'blocked', reason: 'unavailable' };\n }\n}\nexport function inboxSetupPreview(\n review: InboxSetupReview\n): Preview | undefined {\n const saved = reviews.get(review);\n return saved ? (JSON.parse(saved.previewWire) as Preview) : undefined;\n}\nexport type InboxSetupCapture =\n | Readonly<{ status: 'captured'; record: PublicRecordHandle; owner: string }>\n | Readonly<{ status: 'invalid' | 'conflict' | 'unavailable' }>;\n// No effect permission: this exact reviewed record must be durably admitted\n// before later signing/publication. Fresh lookup is bounded knowledge, never CAS.\nexport function captureInboxSetup(\n review: InboxSetupReview,\n resolver: InboxResolver,\n command: unknown,\n consent: unknown\n): InboxSetupCapture {\n try {\n const saved = reviews.get(review),\n id = canonicalLocalId(command);\n if (!saved || !id || consent !== 'reviewed_global_inbox_replacement')\n return { status: 'invalid' };\n const preview = JSON.parse(saved.previewWire) as Preview,\n capture = identityMessagingOwnership(saved.identity);\n if (\n !capture ||\n capture.owner !== preview.author ||\n capture.session !== saved.session\n )\n return { status: 'unavailable' };\n const current = base(resolver, saved.policy, preview.author);\n if (!current) return { status: 'unavailable' };\n if (current.id !== preview.baseId || current.wire !== preview.originalWire)\n return { status: 'conflict' };\n const record = decodePublicRecord(\n JSON.stringify({\n schema: 1,\n family: 'preference_operation',\n owner: preview.author,\n id,\n revision: 0,\n source: { type: 'inbox_head', wire: preview.originalWire },\n consent: 'explicit_review',\n capture: {\n kind: 10050,\n wire: preview.wire,\n hash: preview.hash,\n targets: preview.destinations,\n policyFingerprint: preview.policyFingerprint\n },\n artifact: null,\n receipts: []\n }),\n preview.author,\n id\n );\n if (\n !record.ok ||\n !capture.current() ||\n !inboxResolverCurrentAfterSample(resolver)\n )\n return { status: 'unavailable' };\n return { status: 'captured', record: record.value, owner: preview.author };\n } catch {\n return { status: 'unavailable' };\n }\n}\n// Informational known-base fence only, never a signing or network capability.\n// Exact already-published artifact is an allowed observation on explicit resume;\n// competing/partial observations still block. This is not a global CAS.\nexport function inboxSetupRecordCurrent(\n record: PublicRecordHandle,\n owner: string,\n id: string,\n resolver: InboxResolver,\n policy: RelayPolicy\n): boolean {\n try {\n const row = publicRecordSnapshot(record, owner, id),\n observed = base(resolver, policy, owner);\n if (!row || row.family !== 'preference_operation' || !observed)\n return false;\n const matches =\n observed.wire === row.source.wire ||\n (row.artifact !== null &&\n observed.id === row.artifact.eventId &&\n observed.wire === row.artifact.wire);\n return matches && inboxResolverCurrentAfterSample(resolver);\n } catch {\n return false;\n }\n}\n", + sha256: + 'e7c9861facd0897c2e19ab84370be9d8ac5c27295d4a450e6511c30dd7218323' + }, + 'src/lib/messaging/inbox-setup-operation.ts': { + source: + "import {\n captureInboxSetup,\n inboxSetupRecordCurrent,\n type InboxSetupReview\n} from './inbox-setup.ts';\nimport type { InboxResolver } from './resolve-inbox.ts';\nimport {\n publicRelayTargets,\n readRelayPolicy,\n type RelayPolicy\n} from '../config/relays.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport {\n identityMessagingOwnership,\n captureIdentityPublicOperation,\n identityPublicOperationOwnership,\n signIdentityPublicOperation,\n stopIdentityPublicOperation,\n recheckIdentityOwner,\n subscribeIdentityInvalidation,\n type IdentitySession,\n type IdentityPublicOperation\n} from '../runtime/identity-session.ts';\nimport {\n runCapturedPublicEffect,\n type PublicEffectLease\n} from '../runtime/effect-ownership.ts';\nimport {\n publicRecordSnapshot,\n decodePublicRecord,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport {\n loadPreferenceOperation,\n commitPublicOperationTransition,\n observePublicOperationTransition,\n publicQuotaOwner,\n type PublicQuotaRepository\n} from '../persistence/quota.ts';\nimport {\n preparePreferenceSigningTransition,\n preparePublicArtifactTransition,\n type PublicOperationTransition\n} from '../persistence/artifact-records.ts';\nimport { getPublicPool } from '../nostr/public-pool.ts';\nimport {\n authorizeStoredInboxPreference,\n preferencePolicyFingerprint\n} from '../nostr/inbox-preference-publication.ts';\nimport {\n publishInboxPreference,\n type PreferencePublicationResult\n} from '../nostr/inbox-preference-publisher.ts';\ndeclare const actionBrand: unique symbol;\nexport type InboxPreferenceAction = Readonly<{ [actionBrand]: true }>;\ntype Lookup = () => Promise<InboxResolver>;\ntype Saved = Readonly<{\n repository: PublicQuotaRepository;\n identity: IdentitySession;\n policy: RelayPolicy;\n original: PublicRecordHandle;\n operation: IdentityPublicOperation;\n id: string;\n actionId: string;\n lookup: Lookup;\n retry: boolean;\n control: AbortController;\n running(): boolean;\n markRunning(): void;\n}>;\nconst actions = new WeakMap<InboxPreferenceAction, Saved>();\ntype Prepared =\n | Readonly<{ status: 'prepared'; action: InboxPreferenceAction }>\n | Readonly<{ status: 'invalid' | 'unavailable' | 'conflict' | 'unknown' }>;\nfunction retain(\n repository: PublicQuotaRepository,\n identity: IdentitySession,\n policy: RelayPolicy,\n original: PublicRecordHandle,\n id: string,\n lookup: Lookup,\n retry: boolean\n): Prepared {\n const operation = captureIdentityPublicOperation(\n identity,\n original,\n id,\n 'reviewed_captured_operation'\n );\n if (!operation || typeof lookup !== 'function')\n return { status: 'unavailable' };\n let used = false;\n const action = Object.freeze({}) as InboxPreferenceAction;\n actions.set(action, {\n repository,\n identity,\n policy,\n original,\n operation,\n id,\n actionId: crypto.randomUUID(),\n lookup,\n retry,\n control: new AbortController(),\n running: () => used,\n markRunning: () => {\n used = true;\n }\n });\n return { status: 'prepared', action };\n}\n// Original opaque065 review only. This does not auto-run after connect/setup.\nexport async function beginInboxPreferenceOperation(\n repository: PublicQuotaRepository,\n identity: IdentitySession,\n policy: RelayPolicy,\n review: InboxSetupReview,\n command: unknown,\n lookup: Lookup,\n consent: unknown\n): Promise<Prepared> {\n try {\n const id = canonicalLocalId(command),\n owner = identityMessagingOwnership(identity);\n if (!id || !owner || publicQuotaOwner(repository) !== owner.owner)\n return { status: 'unavailable' };\n const resolver = await lookup(),\n captured = captureInboxSetup(review, resolver, id, consent);\n if (captured.status !== 'captured') return captured;\n if (captured.owner !== owner.owner || !owner.current())\n return { status: 'unavailable' };\n return retain(\n repository,\n identity,\n policy,\n captured.record,\n id,\n lookup,\n false\n );\n } catch {\n return { status: 'unavailable' };\n }\n}\n// Explicit reload review of the actual stored signed operation, with full\n// original capture retained. Unsigned uncertainty cannot become a fresh plan.\nexport async function resumeInboxPreferenceOperation(\n repository: PublicQuotaRepository,\n identity: IdentitySession,\n policy: RelayPolicy,\n command: unknown,\n lookup: Lookup,\n consent: unknown\n): Promise<Prepared> {\n try {\n if (consent !== 'reviewed_stored_inbox_preference')\n return { status: 'invalid' };\n const id = canonicalLocalId(command);\n await recheckIdentityOwner(identity);\n const owner = identityMessagingOwnership(identity);\n if (!id || !owner || publicQuotaOwner(repository) !== owner.owner)\n return { status: 'unavailable' };\n const read = await loadPreferenceOperation(repository, id);\n if (!read.ok) return { status: 'unavailable' };\n const row = publicRecordSnapshot(read.value, owner.owner, id);\n if (row?.family !== 'preference_operation') return { status: 'invalid' };\n if (row.revision < 2 || !row.artifact) return { status: 'unknown' };\n const manifest = readRelayPolicy(policy),\n fingerprint = await preferencePolicyFingerprint(policy),\n resolver = await lookup();\n if (\n !manifest.messagingEnabled ||\n !manifest.postingEnabled ||\n row.capture.policyFingerprint !== fingerprint ||\n JSON.stringify(row.capture.targets) !==\n JSON.stringify(publicRelayTargets(policy, 'write')) ||\n !inboxSetupRecordCurrent(read.value, owner.owner, id, resolver, policy) ||\n !owner.current()\n )\n return { status: 'conflict' };\n // Historical original signing wire for lease matching only; never written\n // back, never a reset. The effect runner uses the actual stored artifact.\n const original = decodePublicRecord(\n JSON.stringify({ ...row, revision: 0, artifact: null, receipts: [] }),\n owner.owner,\n id\n );\n return original.ok\n ? retain(repository, identity, policy, original.value, id, lookup, true)\n : { status: 'invalid' };\n } catch {\n return { status: 'unavailable' };\n }\n}\nasync function acknowledged(\n repository: PublicQuotaRepository,\n transition: PublicOperationTransition\n): Promise<boolean> {\n const result = await commitPublicOperationTransition(repository, transition);\n return (\n result.ok &&\n (await observePublicOperationTransition(repository, transition)).state ===\n 'committed'\n );\n}\nasync function knownBase(saved: Saved): Promise<(() => boolean) | undefined> {\n const owner = identityMessagingOwnership(saved.identity);\n const operation = identityPublicOperationOwnership(\n saved.identity,\n saved.operation\n );\n if (!owner || !operation || saved.control.signal.aborted) return undefined;\n const stored = await loadPreferenceOperation(saved.repository, saved.id);\n if (!stored.ok) return undefined;\n const resolver = await saved.lookup();\n const current = () =>\n !saved.control.signal.aborted &&\n operation.current() &&\n owner.current() &&\n inboxSetupRecordCurrent(\n stored.value,\n owner.owner,\n saved.id,\n resolver,\n saved.policy\n );\n return current() ? current : undefined;\n}\nexport async function runInboxPreferenceOperation(\n action: InboxPreferenceAction\n): Promise<PreferencePublicationResult> {\n const saved = actions.get(action);\n if (!saved) return { status: 'invalid' };\n if (saved.running() || saved.control.signal.aborted)\n return { status: 'stopped' };\n saved.markRunning();\n const capture = identityPublicOperationOwnership(\n saved.identity,\n saved.operation\n );\n if (!capture) return { status: 'stopped' };\n const messagingOwner = identityMessagingOwnership(saved.identity);\n if (\n !messagingOwner ||\n messagingOwner.owner !== capture.owner ||\n messagingOwner.session !== capture.session\n )\n return { status: 'stopped' };\n if (!capture.current() || saved.control.signal.aborted)\n return { status: 'stopped' };\n const invalidate = subscribeIdentityInvalidation(saved.identity, () => {\n // Notifications also describe pending/completed observations. Only actual\n // owner/capability/generation loss cancels this original explicit action.\n if (!capture.current() || !messagingOwner.current()) saved.control.abort();\n });\n try {\n const result = await runCapturedPublicEffect<PreferencePublicationResult>(\n saved.repository,\n saved.original,\n saved.id,\n {\n ...capture,\n current: () => capture.current() && !saved.control.signal.aborted\n },\n saved.retry\n ? 'reviewed_stored_preference_retry'\n : 'reviewed_prepared_preference_operation',\n async (lease: PublicEffectLease, claimed: PublicRecordHandle) => {\n if (!(await knownBase(saved))) return { status: 'stopped' };\n const row = publicRecordSnapshot(claimed, capture.owner, saved.id);\n if (row?.family !== 'preference_operation')\n return { status: 'invalid' };\n const manifest = readRelayPolicy(saved.policy);\n if (\n !manifest.messagingEnabled ||\n !manifest.postingEnabled ||\n row.capture.policyFingerprint !==\n (await preferencePolicyFingerprint(saved.policy)) ||\n JSON.stringify(row.capture.targets) !==\n JSON.stringify(publicRelayTargets(saved.policy, 'write'))\n )\n return { status: 'stopped' };\n if (!capture.current() || saved.control.signal.aborted)\n return { status: 'stopped' };\n if (!row.artifact) {\n const marker = preparePreferenceSigningTransition(\n claimed,\n capture.owner,\n saved.id\n );\n if (\n !marker.ok ||\n !(await acknowledged(saved.repository, marker.value))\n )\n return { status: 'storage_failed' };\n if (!(await knownBase(saved))) return { status: 'stopped' };\n const signed = await signIdentityPublicOperation(\n saved.identity,\n saved.operation,\n lease\n );\n if (signed.status !== 'signed') return { status: 'stopped' };\n const pending = await loadPreferenceOperation(\n saved.repository,\n saved.id\n );\n if (!pending.ok) return { status: 'storage_failed' };\n if (!capture.current() || saved.control.signal.aborted)\n return { status: 'stopped' };\n const transition = preparePublicArtifactTransition(\n pending.value,\n capture.owner,\n saved.id,\n signed.artifact\n );\n if (\n !transition.ok ||\n !(await acknowledged(saved.repository, transition.value))\n )\n return { status: 'storage_failed' };\n }\n if (saved.control.signal.aborted || !capture.current())\n return { status: 'stopped' };\n const pool = getPublicPool(saved.policy);\n if (!pool) return { status: 'stopped' };\n return await publishInboxPreference(\n saved.repository,\n capture.owner,\n saved.id,\n saved.actionId,\n pool,\n saved.policy,\n saved.control.signal,\n () =>\n authorizeStoredInboxPreference(\n saved.repository,\n saved.identity,\n saved.operation,\n lease,\n saved.original,\n saved.id,\n saved.policy,\n () => knownBase(saved)\n )\n );\n }\n );\n return result.status === 'completed' ? result.value : { status: 'stopped' };\n } catch {\n return { status: 'stopped' };\n } finally {\n invalidate();\n }\n}\nexport function stopInboxPreferenceOperation(\n action: InboxPreferenceAction\n): void {\n const saved = actions.get(action);\n if (!saved) return;\n saved.control.abort();\n stopIdentityPublicOperation(saved.identity, saved.operation);\n}\n", + sha256: + 'f9deefbd5c58234c720fd2196edf1d242ee16fcdf4e32082c0456662fbe15122' + }, + 'src/lib/messaging/inbox-setup-view.ts': { + source: + "import {\n readRelayPolicy,\n inboxRelayTargets,\n type RelayPolicy\n} from '../config/relays.ts';\nimport { deploymentRelayPolicy } from '../config/deployment-relays.ts';\nimport {\n identityMessagingOwnership,\n subscribeIdentityInvalidation,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport {\n createPrivateSession,\n closePrivateSession,\n type PrivateSession\n} from '../runtime/private-session.ts';\nimport {\n identityViewSession,\n type IdentityViewContext\n} from '../runtime/view-context.ts';\nimport {\n createPublicView,\n beginPublicViewRun,\n disposePublicView,\n type PublicRuntime\n} from '../runtime/public-runtime.ts';\nimport {\n resolveInboxPreference,\n settleInboxResolver,\n inboxResolutionSnapshot,\n closeInboxResolver,\n type InboxResolver\n} from './resolve-inbox.ts';\nimport {\n inboxPreferenceSnapshot,\n inboxPreferenceWire\n} from '../nostr/inbox-preferences.ts';\nimport {\n reviewInboxSetup,\n inboxSetupPreview,\n type InboxSetupReview\n} from './inbox-setup.ts';\nimport {\n beginInboxPreferenceOperation,\n runInboxPreferenceOperation,\n stopInboxPreferenceOperation,\n type InboxPreferenceAction\n} from './inbox-setup-operation.ts';\nimport {\n openBrowserDatabase,\n closeBrowserDatabase,\n type BrowserDatabase\n} from '../persistence/database.ts';\nimport {\n createPublicQuotaRepository,\n loadPreferenceOperation,\n type PublicQuotaRepository\n} from '../persistence/quota.ts';\nimport {\n publicRecordSnapshot,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport {\n resolveInboxReadback,\n inboxReadbackSnapshot,\n closeInboxReadback,\n type InboxReadback\n} from '../nostr/inbox-readback.ts';\nimport {\n existingInboxSetupSnapshot,\n verifyInboxSetupOperation\n} from './inbox-setup-verification.ts';\nimport type { ObserveInboxAccess } from './readiness.ts';\ndeclare const viewBrand: unique symbol;\nexport type InboxSetupView = Readonly<{ [viewBrand]: true }>;\nexport type InboxSetupViewSnapshot = Readonly<{\n status: string;\n busy: boolean;\n owner?: string;\n currentWire: string | null;\n existingInboxes: string[];\n availableInboxes: string[];\n preview?: NonNullable<ReturnType<typeof inboxSetupPreview>>;\n accepted: string[];\n readback: string[];\n setupComplete: boolean;\n}>;\n// Internal trusted orchestration ports require real opaque discovery/readback\n// owners. Neither displayed facts nor caller booleans admit a preference effect.\ntype Inputs = Readonly<{\n identity: IdentitySession;\n policy: RelayPolicy;\n lookup(current?: () => boolean): Promise<InboxResolver>;\n readback?(\n record: PublicRecordHandle,\n owner: string,\n id: string\n ): InboxReadback | undefined;\n observeAccess?: ObserveInboxAccess;\n now?(): number;\n close?(): void;\n}>;\ntype Controller = {\n ownership():\n | Readonly<{\n identity: IdentitySession;\n policy: RelayPolicy;\n session: PrivateSession | undefined;\n resolver: InboxResolver | undefined;\n observeAccess: ObserveInboxAccess | undefined;\n current(): boolean;\n }>\n | undefined;\n observe(): void;\n snapshot(): InboxSetupViewSnapshot;\n subscribe(listener: (state: InboxSetupViewSnapshot) => void): () => void;\n check(): Promise<void>;\n review(\n selected: string[],\n removeTags: number[],\n removeFields: string[]\n ): Promise<void>;\n enable(): Promise<void>;\n unlock(): Promise<void>;\n readback(): Promise<void>;\n stop(): void;\n close(): void;\n};\nconst views = new WeakMap<InboxSetupView, Controller>();\nconst unavailable = (): InboxSetupViewSnapshot => ({\n status: 'unavailable',\n busy: false,\n currentWire: null,\n existingInboxes: [],\n availableInboxes: [],\n accepted: [],\n readback: [],\n setupComplete: false\n});\nexport function createInboxSetupView(\n input: Inputs\n): InboxSetupView | undefined {\n if (typeof window === 'undefined') return undefined;\n const initial = identityMessagingOwnership(input.identity);\n if (!initial || !initial.current()) return undefined;\n const capture = initial;\n const manifest = readRelayPolicy(input.policy);\n const available = manifest.inbox\n .filter(\n ({ read, write, origin }) =>\n read && write && !manifest.operatorDenylist.includes(origin)\n )\n .map((row) => row.origin);\n const token = Object.freeze({}) as InboxSetupView;\n let state = {\n ...unavailable(),\n status: 'not_checked',\n owner: capture.owner,\n availableInboxes: available\n },\n epoch = 0,\n closed = false;\n let pendingClose: (() => void)[] | undefined;\n let resolver: InboxResolver | undefined,\n review: InboxSetupReview | undefined,\n action: InboxPreferenceAction | undefined,\n database: BrowserDatabase | undefined,\n repository: PublicQuotaRepository | undefined,\n session: PrivateSession | undefined,\n reader: InboxReadback | undefined,\n command: string | undefined;\n const listeners = new Map<symbol, (state: InboxSetupViewSnapshot) => void>();\n const current = (generation = epoch) =>\n !closed && generation === epoch && capture.current();\n const snapshot = () => {\n if (closed) return { ...unavailable(), status: 'closed' };\n if (!capture.current()) return unavailable();\n return JSON.parse(JSON.stringify(state)) as InboxSetupViewSnapshot;\n };\n function notify() {\n for (const listener of listeners.values()) {\n try {\n listener(snapshot());\n } catch {\n /* Isolate presentation observers. */\n }\n }\n }\n function update(status: string, busy = state.busy) {\n state = { ...state, status, busy };\n notify();\n }\n function inspect() {\n if (!resolver || !current()) return;\n const observed = inboxResolutionSnapshot(resolver);\n if (!current() || observed.author !== capture.owner) return;\n const head = observed.head && inboxPreferenceSnapshot(observed.head);\n state = {\n ...state,\n currentWire: observed.head\n ? (inboxPreferenceWire(observed.head) ?? null)\n : null,\n existingInboxes: head?.relays.slice() ?? [],\n setupComplete: false\n };\n if (\n observed.coverage !== 'bounded-eose' ||\n observed.status === 'inconclusive'\n ) {\n update('lookup_incomplete');\n return;\n }\n const compatible =\n head?.status === 'supported' &&\n inboxRelayTargets(input.policy, head.relays, 'read').length > 0 &&\n inboxRelayTargets(input.policy, head.relays, 'write').length > 0;\n update(\n compatible\n ? 'compatible'\n : observed.status === 'missing'\n ? 'not_observed'\n : 'needs_review'\n );\n }\n async function work(\n status: string,\n perform: (generation: number) => Promise<void>\n ) {\n if (!current() || state.busy) return;\n const generation = epoch;\n update(status, true);\n if (!current(generation)) return;\n try {\n await perform(generation);\n } catch {\n if (current(generation)) update('unavailable');\n } finally {\n if (current(generation)) {\n state = { ...state, busy: false };\n notify();\n }\n }\n }\n function stop() {\n epoch++;\n if (action) stopInboxPreferenceOperation(action);\n review = undefined;\n state = { ...state, preview: undefined, setupComplete: false };\n if (reader) closeInboxReadback(reader);\n reader = undefined;\n if (resolver) closeInboxResolver(resolver);\n resolver = undefined;\n update('paused', false);\n }\n const invalidate = subscribeIdentityInvalidation(input.identity, () => {\n if (!capture.current()) stop();\n });\n views.set(token, {\n ownership: () =>\n current()\n ? {\n identity: input.identity,\n policy: input.policy,\n session,\n resolver,\n observeAccess: input.observeAccess,\n current: () => current()\n }\n : undefined,\n observe() {\n if (current() && !state.busy && state.status === 'lookup_incomplete')\n inspect();\n },\n snapshot,\n subscribe(listener) {\n const id = Symbol();\n listeners.set(id, listener);\n try {\n listener(snapshot());\n } catch {\n /* Isolate presentation observers. */\n }\n return () => {\n listeners.delete(id);\n };\n },\n check: () =>\n work('checking', async (generation) => {\n if (resolver) closeInboxResolver(resolver);\n const found = await input.lookup(() => current(generation));\n if (!current(generation)) {\n closeInboxResolver(found);\n return;\n }\n resolver = found;\n review = undefined;\n state = { ...state, preview: undefined };\n inspect();\n }),\n review: (selected, removeTags, removeFields) =>\n work('reviewing', async (generation) => {\n if (!resolver) {\n update('lookup_incomplete');\n return;\n }\n inspect();\n if (!current(generation) || state.status === 'compatible') return;\n const result = await reviewInboxSetup(\n input.identity,\n resolver,\n input.policy,\n JSON.stringify({\n selectedInboxes: selected,\n removeTagIndices: removeTags,\n removeExtraFields: removeFields,\n createdAt: (input.now ?? (() => Math.floor(Date.now() / 1000)))()\n }),\n input.now\n );\n if (!current(generation)) return;\n if (result.status !== 'review') {\n update(result.reason);\n return;\n }\n review = result.review;\n state = { ...state, preview: inboxSetupPreview(review) };\n update('review');\n }),\n enable: () =>\n work('approval_wait', async (generation) => {\n if (\n !review ||\n state.preview === undefined ||\n !manifest.postingEnabled ||\n !manifest.messagingEnabled\n ) {\n update('unavailable');\n return;\n }\n const opened = await openBrowserDatabase();\n if (!current(generation)) {\n if (opened.state === 'ready') closeBrowserDatabase(opened.owner);\n return;\n }\n if (opened.state !== 'ready') {\n update('storage_unavailable');\n return;\n }\n if (database) closeBrowserDatabase(database);\n database = opened.owner;\n repository = createPublicQuotaRepository(database, capture.owner);\n if (!repository) {\n update('storage_unavailable');\n return;\n }\n command = crypto.randomUUID();\n const prepared = await beginInboxPreferenceOperation(\n repository,\n input.identity,\n input.policy,\n review,\n command,\n () => input.lookup(() => current(generation)),\n 'reviewed_global_inbox_replacement'\n );\n if (!current(generation)) {\n if (prepared.status === 'prepared')\n stopInboxPreferenceOperation(prepared.action);\n return;\n }\n if (prepared.status !== 'prepared') {\n update(prepared.status);\n return;\n }\n action = prepared.action;\n const result = await runInboxPreferenceOperation(action);\n if (!current(generation)) return;\n const stored = await loadPreferenceOperation(repository, command);\n if (!current(generation)) return;\n const row =\n stored.ok &&\n publicRecordSnapshot(stored.value, capture.owner, command);\n state = {\n ...state,\n accepted:\n row && row.family === 'preference_operation'\n ? row.receipts\n .filter(\n (fact) =>\n fact.status === 'accepted' &&\n fact.eventId === row.artifact?.eventId\n )\n .map((fact) => fact.origin)\n : [],\n setupComplete: false\n };\n review = undefined;\n state = { ...state, preview: undefined };\n update(\n result.status === 'completed' ? 'awaiting_readback' : result.status\n );\n }),\n unlock: () =>\n work('approval_wait', async (generation) => {\n const acquired = await createPrivateSession(\n input.identity,\n 'reviewed_private_session'\n );\n if (!current(generation)) {\n if (acquired) closePrivateSession(acquired);\n return;\n }\n session = acquired;\n if (!session || !resolver) {\n update('unavailable');\n return;\n }\n const result = existingInboxSetupSnapshot(\n input.identity,\n session,\n input.policy,\n resolver,\n input.observeAccess\n );\n if (!current(generation)) return;\n state = { ...state, setupComplete: result.setupComplete };\n update(result.status);\n }),\n readback: () =>\n work('checking_readback', async (generation) => {\n if (!repository || !command || !input.readback) {\n update('awaiting_readback');\n return;\n }\n if (!reader) {\n const stored = await loadPreferenceOperation(repository, command);\n if (!current(generation)) return;\n if (!stored.ok) {\n update('storage_unavailable');\n return;\n }\n reader = input.readback(stored.value, capture.owner, command);\n }\n const observation = reader && inboxReadbackSnapshot(reader);\n if (!observation || observation.status === 'pending') {\n update('awaiting_readback');\n return;\n }\n state = { ...state, readback: observation.sources.slice() };\n const result = await verifyInboxSetupOperation(\n repository,\n input.identity,\n session,\n input.policy,\n reader!,\n input.observeAccess\n );\n if (!current(generation)) return;\n state = { ...state, setupComplete: result.setupComplete };\n closeInboxReadback(reader!);\n reader = undefined;\n update(result.status);\n }),\n stop,\n close() {\n if (!pendingClose) {\n closed = true;\n const originalResolver = resolver,\n originalReader = reader,\n originalSession = session,\n originalDatabase = database;\n pendingClose = [\n stop,\n invalidate,\n () => {\n if (originalReader) closeInboxReadback(originalReader);\n },\n () => {\n if (originalResolver) closeInboxResolver(originalResolver);\n },\n () => {\n if (originalSession && !closePrivateSession(originalSession))\n throw Error('private_cleanup_required');\n },\n () => {\n if (originalDatabase) closeBrowserDatabase(originalDatabase);\n },\n () => input.close?.(),\n () => listeners.clear()\n ];\n }\n let unfinished = Array.from<() => void>([]);\n for (const cleanup of pendingClose) {\n try {\n cleanup();\n } catch {\n unfinished = unfinished.concat(cleanup);\n }\n }\n pendingClose = unfinished;\n // Closed admission and completed disposal are separate facts. A failed\n // original cleanup remains owned and retryable after invalidation.\n if (unfinished.length > 0) throw Error('inbox_setup_cleanup_required');\n }\n });\n return token;\n}\n// Production egress always comes from the root's governed runtime and fixed\n// deployment manifest. No fixture, arbitrary relay, signing template or sender.\nexport function createRuntimeInboxSetupView(\n context: IdentityViewContext,\n runtime: PublicRuntime\n): InboxSetupView | undefined {\n const identity = identityViewSession(context);\n if (!identity) return undefined;\n const view = createPublicView(runtime);\n try {\n const controller = createInboxSetupView({\n identity,\n policy: deploymentRelayPolicy,\n lookup: (current = () => true) => {\n const owner = identityMessagingOwnership(identity);\n if (!owner) throw new Error('inbox_owner_unavailable');\n return settleInboxResolver(\n resolveInboxPreference(view, beginPublicViewRun(view), owner.owner),\n () => owner.current() && current()\n );\n },\n readback: (record, owner, id) =>\n resolveInboxReadback(\n view,\n beginPublicViewRun(view),\n record,\n owner,\n id,\n deploymentRelayPolicy\n ),\n close: () => disposePublicView(view)\n });\n if (!controller) disposePublicView(view);\n return controller;\n } catch {\n disposePublicView(view);\n return undefined;\n }\n}\nexport function inboxSetupViewSnapshot(\n view: InboxSetupView | undefined\n): InboxSetupViewSnapshot {\n return (view && views.get(view)?.snapshot()) || unavailable();\n}\nexport function subscribeInboxSetupView(\n view: InboxSetupView | undefined,\n listener: (state: InboxSetupViewSnapshot) => void\n): () => void {\n return (view && views.get(view)?.subscribe(listener)) || (() => {});\n}\nexport async function checkInboxSetupView(\n view: InboxSetupView | undefined\n): Promise<void> {\n await (view && views.get(view)?.check());\n}\nexport async function reviewInboxSetupView(\n view: InboxSetupView | undefined,\n selected: string[],\n removeTags: number[],\n removeFields: string[]\n): Promise<void> {\n await (view && views.get(view)?.review(selected, removeTags, removeFields));\n}\nexport async function enableInboxSetupView(\n view: InboxSetupView | undefined\n): Promise<void> {\n await (view && views.get(view)?.enable());\n}\nexport async function unlockInboxSetupView(\n view: InboxSetupView | undefined\n): Promise<void> {\n await (view && views.get(view)?.unlock());\n}\nexport async function readbackInboxSetupView(\n view: InboxSetupView | undefined\n): Promise<void> {\n await (view && views.get(view)?.readback());\n}\nexport function stopInboxSetupView(view: InboxSetupView | undefined): void {\n if (view) views.get(view)?.stop();\n}\nexport function closeInboxSetupView(view: InboxSetupView | undefined): void {\n if (view) views.get(view)?.close();\n}\n\n// Detached original-token observation for trusted page orchestration. Neither\n// its scalar fields nor mutation of this fresh object changes stored custody.\nexport function inboxSetupViewOwnership(view: InboxSetupView | undefined) {\n return view && views.get(view)?.ownership();\n}\nexport function observeInboxSetupView(view: InboxSetupView | undefined): void {\n if (view) views.get(view)?.observe();\n}\n", + sha256: + '4ec9025232bb1355fef1ba039b46ce0a2be10e02e348e1b4eaadc3d1f3c2fd84' + }, + 'src/lib/messaging/reply-controller.ts': { + source: + "import { inboxReplyOwnership, type InboxView } from './inbox-view.ts';\nimport { inboxSetupViewOwnership } from './inbox-setup-view.ts';\nimport { messagingReadinessSnapshot } from './readiness.ts';\nimport {\n createInboxRoutePlan,\n inboxRoutePlanSnapshot\n} from './inbox-routing.ts';\nimport {\n resolveInboxPreference,\n closeInboxResolver,\n type InboxResolver\n} from './resolve-inbox.ts';\nimport {\n createPublicView,\n beginPublicViewRun,\n publicViewRunCurrent,\n disposePublicView,\n type PublicRuntime\n} from '../runtime/public-runtime.ts';\nimport {\n createPrivateComposer,\n privateComposerText,\n privateComposerSnapshot,\n updatePrivateComposerText,\n bindPrivateComposerPreparation,\n closePrivateComposer\n} from './composer-state.ts';\nimport {\n captureDirtyNavigation,\n requestPrivateNavigation,\n confirmDiscardNavigation,\n keepPrivateEditing,\n dirtyNavigationSnapshot,\n privateNavigationBeforeUnload\n} from '../runtime/dirty-navigation.ts';\nimport {\n captureAuthenticatedReplyRumor,\n stopRumorPlan,\n type RumorPlan\n} from './rumor-plan.ts';\nimport { createPrivateSendReservationRepository } from '../persistence/private-send-reservations.ts';\nimport { reserveSendIdentity } from './send-identity.ts';\nimport {\n captureSelfRecoveryPreparation,\n prepareSelfRecovery,\n preparedSelfRecovery,\n preparePairedDelivery,\n preparedPairedDelivery,\n selfRecoveryPreparationSnapshot,\n type SelfRecoveryPreparation\n} from './prepare-send.ts';\nimport { getPrivatePool } from '../nostr/private-pool.ts';\nimport {\n capturePrivateRetry,\n runPrivateRetry,\n stopPrivateRetry,\n type PrivateRetry\n} from './retry-send.ts';\nimport { newLocalId } from '../private-handles.ts';\nimport { subscribeIdentityInvalidation } from '../runtime/identity-session.ts';\nimport { subscribePrivateSessionClose } from '../runtime/private-session.ts';\n\ndeclare const replyBrand: unique symbol;\nexport type ReplyController = Readonly<{ [replyBrand]: true }>;\ntype Result = Readonly<{\n status: 'invalid' | 'busy' | 'stopped' | 'needs_action' | 'completed';\n}>;\ntype Options = Readonly<{\n lookupPeer?(peer: string): Promise<InboxResolver>;\n close?(): void;\n}>;\ntype State =\n | 'idle'\n | 'checking'\n | 'preparing'\n | 'publishing'\n | 'needs_action'\n | 'completed';\ntype Snapshot = Readonly<{\n state: State;\n busy: boolean;\n dirty: boolean;\n copy: string;\n saveCopy: string;\n pairCopy: string;\n navigation: 'idle' | 'confirmation_required';\n}>;\ntype Controller = {\n snapshot(): Snapshot | undefined;\n text(): string | undefined;\n update(text: unknown, review: unknown): boolean;\n select(parent: unknown, review: unknown): boolean;\n send(review: unknown): Promise<Result>;\n request(): ReturnType<typeof requestPrivateNavigation>;\n keep(): boolean;\n discard(review: unknown): ReturnType<typeof confirmDiscardNavigation>;\n unload(event: BeforeUnloadEvent): boolean;\n close(): void;\n};\nconst controllers = new WeakMap<ReplyController, Controller>();\n\n// Allocating or typing a draft performs no SDK, native write or discovery.\n// Caller hints are resolved through the original selected view's Room/cache.\nexport function createReplyController(\n view: InboxView,\n conversationId: unknown,\n parent: unknown,\n options: Options = {}\n): ReplyController | undefined {\n if (typeof window === 'undefined') return;\n let scope = inboxReplyOwnership(view, conversationId, parent);\n if (!scope?.current()) return;\n const original = scope,\n composer = createPrivateComposer(\n original.identity,\n 'reviewed_private_composer'\n );\n const navigation = composer && captureDirtyNavigation(composer);\n if (!composer || !navigation) {\n if (composer) closePrivateComposer(composer);\n return;\n }\n let active = true,\n busy = false,\n state: State = 'idle',\n copy = '',\n attempted = false;\n let plan: RumorPlan | undefined,\n preparation: SelfRecoveryPreparation | undefined,\n retry: PrivateRetry | undefined;\n let identityOff = () => {},\n privateOff = () => {};\n function close() {\n if (!active) return;\n active = false;\n if (retry) stopPrivateRetry(retry);\n closePrivateComposer(composer!);\n if (plan) stopRumorPlan(plan);\n identityOff();\n privateOff();\n options.close?.();\n }\n function current() {\n if (!active || !scope?.current() || !privateComposerSnapshot(composer!)) {\n close();\n return false;\n }\n return true;\n }\n function snapshot(): Snapshot | undefined {\n if (!current()) return;\n const draft = privateComposerSnapshot(composer!),\n workflow = preparation && selfRecoveryPreparationSnapshot(preparation);\n if (!draft) return;\n return {\n state,\n busy,\n dirty: draft.dirty,\n copy:\n copy ||\n (state === 'preparing'\n ? 'Preparing encryption. The extension may ask for several approvals.'\n : state === 'publishing'\n ? 'Publishing encrypted copies to the reviewed inbox relays.'\n : ''),\n saveCopy: draft.copy,\n pairCopy: workflow?.pairCopy ?? draft.pairCopy,\n navigation: dirtyNavigationSnapshot(navigation!)?.state ?? 'idle'\n };\n }\n async function send(review: unknown): Promise<Result> {\n if (review !== 'reviewed_reply_send') return { status: 'invalid' };\n if (!current()) return { status: 'stopped' };\n if (busy) return { status: 'busy' };\n const text = privateComposerText(composer!);\n if (!text?.trim()) return { status: 'invalid' };\n if (attempted) return { status: 'needs_action' };\n busy = true;\n state = 'checking';\n copy =\n 'Checking the authenticated peer inbox. Your text remains in memory.';\n const captured = scope!;\n const admitted = () => current() && scope === captured;\n function needsAction(): Result {\n state = 'needs_action';\n copy =\n 'Send needs review. Keep this draft; check inbox setup or connection, then explicitly send again. Existing encrypted work needs its own recovery review.';\n return { status: 'needs_action' };\n }\n try {\n const setup = inboxSetupViewOwnership(captured.setup);\n if (!setup?.current() || !setup.resolver || !options.lookupPeer)\n return needsAction();\n const other = await options.lookupPeer(captured.peer);\n if (!admitted()) return { status: 'stopped' };\n if (\n !messagingReadinessSnapshot(\n captured.identity,\n captured.session,\n setup.policy,\n setup.resolver,\n { author: captured.peer, resolver: other },\n setup.observeAccess\n ).sendReady ||\n !admitted()\n )\n return needsAction();\n const routes = createInboxRoutePlan(\n setup.policy,\n captured.owner,\n captured.peer,\n setup.resolver,\n other\n );\n const routeData = routes && inboxRoutePlanSnapshot(routes);\n const reservations = createPrivateSendReservationRepository(\n captured.database,\n captured.owner\n );\n if (!routes || !routeData || !reservations || !admitted())\n return needsAction();\n plan = captureAuthenticatedReplyRumor(\n captured.identity,\n captured.session,\n captured.unlocked,\n captured.room,\n text,\n Math.floor(Date.now() / 1000)\n );\n const command = newLocalId();\n if (!plan || !command || !admitted()) return needsAction();\n // After a native intent may exist, repeated Send never creates another\n // rumor or silently replays this command. Recovery has its own owner.\n attempted = true;\n const reserved = await reserveSendIdentity(\n reservations,\n captured.identity,\n command,\n plan,\n 'reviewed_private_intent'\n );\n if (!admitted()) return { status: 'stopped' };\n if (!('identity' in reserved)) return needsAction();\n preparation = captureSelfRecoveryPreparation(\n captured.repository,\n captured.identity,\n reserved.identity,\n 'reviewed_self_recovery'\n );\n if (\n !preparation ||\n !bindPrivateComposerPreparation(\n composer!,\n reserved.identity,\n preparation,\n undefined,\n 'reviewed_composer_preparation'\n )\n )\n return needsAction();\n state = 'preparing';\n copy = '';\n const self = await prepareSelfRecovery(\n preparation,\n 'reviewed_self_recovery'\n );\n if (!admitted()) return { status: 'stopped' };\n const saved = preparedSelfRecovery(preparation);\n if (\n !['saved', 'existing', 'reconciled'].includes(self.status) ||\n !saved ||\n !(await captured.acceptLocalReply(saved, 'reviewed_local_reply')) ||\n !admitted()\n )\n return needsAction();\n const context = {\n plan: routes,\n policy: setup.policy,\n own: setup.resolver,\n other\n };\n const paired = await preparePairedDelivery(\n preparation,\n context,\n 'reviewed_pair_preparation'\n );\n if (!admitted()) return { status: 'stopped' };\n const receipt = preparedPairedDelivery(preparation);\n if (\n !['prepared', 'existing', 'reconciled'].includes(paired.status) ||\n !receipt\n )\n return needsAction();\n const origins = Array.from(\n new Set([...routeData.peer.targets, ...routeData.archive.targets])\n );\n const pool = getPrivatePool(captured.session, setup.policy, origins);\n if (!pool || !admitted()) return needsAction();\n retry = capturePrivateRetry(\n captured.repository,\n captured.session,\n receipt,\n context,\n pool,\n 'reviewed_private_retry'\n );\n if (!retry || !admitted()) return needsAction();\n state = 'publishing';\n const delivered = await runPrivateRetry(retry, 'reviewed_private_retry');\n if (!admitted()) return { status: 'stopped' };\n if (delivered.status !== 'completed') return needsAction();\n state = 'completed';\n copy =\n 'Accepted by recipient inbox relay. This does not confirm that the person read the message.';\n return { status: 'completed' };\n } catch {\n return current() ? needsAction() : { status: 'stopped' };\n } finally {\n busy = false;\n }\n }\n const token = Object.freeze({}) as ReplyController;\n controllers.set(token, {\n snapshot,\n text: () => (current() ? privateComposerText(composer) : undefined),\n update: (text, review) =>\n current() &&\n !busy &&\n !attempted &&\n updatePrivateComposerText(composer, text, review),\n select(parent, review) {\n if (review !== 'reviewed_reply_parent' || !current() || busy || attempted)\n return false;\n const selected = inboxReplyOwnership(view, conversationId, parent);\n if (\n !selected?.current() ||\n selected.identity !== original.identity ||\n selected.session !== original.session ||\n selected.peer !== original.peer\n )\n return false;\n scope = selected;\n return true;\n },\n send,\n request: () =>\n current() ? requestPrivateNavigation(navigation) : 'invalid',\n keep: () => current() && keepPrivateEditing(navigation),\n discard: (review) =>\n current() ? confirmDiscardNavigation(navigation, review) : 'invalid',\n unload: (event) =>\n current() && privateNavigationBeforeUnload(navigation, event),\n close\n });\n identityOff = subscribeIdentityInvalidation(original.identity, () => {\n if (!original.current()) close();\n });\n privateOff = subscribePrivateSessionClose(original.session, close);\n return current() ? token : undefined;\n}\n\nexport function createRuntimeReplyController(\n view: InboxView,\n id: unknown,\n parent: unknown,\n runtime: PublicRuntime\n): ReplyController | undefined {\n const publicView = createPublicView(runtime);\n let resolver: InboxResolver | undefined,\n run: ReturnType<typeof beginPublicViewRun> | undefined;\n const token = createReplyController(view, id, parent, {\n lookupPeer: (peer) => {\n // Only this explicit Send lookup may renew an expired run. An active\n // lookup retains its original bounded work, including pending results.\n if (!resolver || !run || !publicViewRunCurrent(publicView, run)) {\n if (resolver) closeInboxResolver(resolver);\n resolver = undefined;\n run = beginPublicViewRun(publicView);\n resolver = resolveInboxPreference(publicView, run, peer);\n }\n return Promise.resolve(resolver);\n },\n close: () => {\n if (resolver) closeInboxResolver(resolver);\n disposePublicView(publicView);\n }\n });\n if (!token) disposePublicView(publicView);\n return token;\n}\nexport function replySnapshot(token: ReplyController) {\n return controllers.get(token)?.snapshot();\n}\nexport function replyText(token: ReplyController) {\n return controllers.get(token)?.text();\n}\nexport function updateReplyText(\n token: ReplyController,\n text: unknown,\n review: unknown\n) {\n return controllers.get(token)?.update(text, review) ?? false;\n}\nexport function selectReplyParent(\n token: ReplyController,\n parent: unknown,\n review: unknown\n) {\n return controllers.get(token)?.select(parent, review) ?? false;\n}\nexport function sendReply(\n token: ReplyController,\n review: unknown\n): Promise<Result> {\n return (\n controllers.get(token)?.send(review) ??\n Promise.resolve({ status: 'invalid' })\n );\n}\nexport function requestReplyNavigation(token: ReplyController) {\n return controllers.get(token)?.request() ?? 'invalid';\n}\nexport function keepReplyEditing(token: ReplyController) {\n return controllers.get(token)?.keep() ?? false;\n}\nexport function discardReplyNavigation(\n token: ReplyController,\n review: unknown\n) {\n return controllers.get(token)?.discard(review) ?? 'invalid';\n}\nexport function replyBeforeUnload(\n token: ReplyController,\n event: BeforeUnloadEvent\n) {\n return controllers.get(token)?.unload(event) ?? false;\n}\nexport function closeReplyController(token: ReplyController) {\n controllers.get(token)?.close();\n}\n", + sha256: + 'c13f1395b5317febcd23396babbcc116065ff96e8cbeb29c8eadfdfc14e45c2d' + }, + 'src/lib/messaging/product-request-controller.ts': { + source: + "import {\n productEnquirySnapshot,\n productEnquirySendOwnership,\n updateProductEnquiry,\n closeProductEnquiry,\n type ProductEnquiry\n} from './product-enquiry.ts';\nimport {\n identityMessagingOwnership,\n subscribeIdentityInvalidation,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport {\n inboxSetupViewOwnership,\n type InboxSetupView\n} from './inbox-setup-view.ts';\nimport { messagingReadinessSnapshot } from './readiness.ts';\nimport {\n sellerInboxStatus,\n sellerInboxCopy,\n type SellerInboxStatus\n} from './enquiry-readiness.ts';\nimport {\n createInboxRoutePlan,\n inboxRoutePlanSnapshot\n} from './inbox-routing.ts';\nimport {\n resolveInboxPreference,\n settleInboxResolver,\n closeInboxResolver,\n type InboxResolver\n} from './resolve-inbox.ts';\nimport {\n createPublicView,\n beginPublicViewRun,\n disposePublicView,\n type PublicRuntime\n} from '../runtime/public-runtime.ts';\nimport {\n openBrowserDatabase,\n closeBrowserDatabase,\n type BrowserDatabase\n} from '../persistence/database.ts';\nimport { createPrivateStorageRepository } from '../persistence/private-storage.ts';\nimport { createPrivateSendReservationRepository } from '../persistence/private-send-reservations.ts';\nimport {\n createPrivateComposer,\n updatePrivateComposerText,\n privateComposerSnapshot,\n bindPrivateComposerPreparation,\n closePrivateComposer,\n type PrivateComposer\n} from './composer-state.ts';\nimport {\n captureEnquiryRumor,\n stopRumorPlan,\n type RumorPlan\n} from './rumor-plan.ts';\nimport { reserveSendIdentity } from './send-identity.ts';\nimport {\n captureSelfRecoveryPreparation,\n prepareSelfRecovery,\n preparedSelfRecovery,\n preparePairedDelivery,\n preparedPairedDelivery,\n selfRecoveryPreparationSnapshot,\n type SelfRecoveryPreparation\n} from './prepare-send.ts';\nimport { getPrivatePool } from '../nostr/private-pool.ts';\nimport {\n capturePrivateRetry,\n runPrivateRetry,\n stopPrivateRetry,\n type PrivateRetry\n} from './retry-send.ts';\nimport { newLocalId } from '../private-handles.ts';\nimport { privateSessionOwnership } from '../runtime/private-session.ts';\n\ndeclare const requestBrand: unique symbol;\nexport type ProductRequestController = Readonly<{ [requestBrand]: true }>;\ntype Result = Readonly<{\n status: 'invalid' | 'busy' | 'stopped' | 'needs_action' | 'completed';\n}>;\ntype NavigationResult =\n 'invalid' | 'allowed' | 'confirmation_required' | 'review_required';\ntype State =\n | 'idle'\n | 'checking'\n | 'preparing'\n | 'publishing'\n | 'needs_action'\n | 'completed';\ntype Snapshot = Readonly<{\n state: State;\n busy: boolean;\n dirty: boolean;\n revision: number;\n readyToSend: boolean;\n sellerInbox: SellerInboxStatus;\n copy: string;\n saveCopy: string;\n pairCopy: string;\n navigation: 'idle' | 'confirmation_required';\n}>;\ntype Controller = {\n snapshot(): Snapshot | undefined;\n text(): string | undefined;\n update(text: unknown, review: unknown): boolean;\n configure(\n identity: IdentitySession,\n setup: InboxSetupView,\n review: unknown\n ): boolean;\n send(review: unknown): Promise<Result>;\n request(): NavigationResult;\n keep(): boolean;\n discard(review: unknown): NavigationResult;\n unload(event: BeforeUnloadEvent): boolean;\n close(): void;\n stop(review: unknown): boolean;\n};\nconst controllers = new WeakMap<ProductRequestController, Controller>();\n\n// Guest allocation and configuration preserve the original enquiry memory.\n// Only the reviewed Send command acquires storage, crypto or publication.\nexport function createProductRequestController(\n enquiry: ProductEnquiry,\n runtime?: PublicRuntime\n): ProductRequestController | undefined {\n if (typeof window === 'undefined' || !productEnquirySnapshot(enquiry)) return;\n let active = true,\n busy = false,\n attempted = false;\n let state: State = 'idle',\n copy = '',\n requestedRevision: number | undefined,\n sentRevision: number | undefined;\n let identity: IdentitySession | undefined, setup: InboxSetupView | undefined;\n let composer: PrivateComposer | undefined,\n database: BrowserDatabase | undefined;\n let plan: RumorPlan | undefined,\n preparation: SelfRecoveryPreparation | undefined,\n retry: PrivateRetry | undefined;\n let identityOff = () => {},\n generation = 0;\n const source = runtime && createPublicView(runtime);\n let resolver: InboxResolver | undefined;\n function stopWork(preserveComposer = false) {\n generation++;\n if (preserveComposer && composer) privateComposerSnapshot(composer);\n if (retry) stopPrivateRetry(retry);\n if (plan) stopRumorPlan(plan);\n if (!preserveComposer) {\n if (composer) closePrivateComposer(composer);\n composer = undefined;\n }\n }\n function close() {\n if (!active) return;\n active = false;\n stopWork();\n identityOff();\n closeProductEnquiry(enquiry);\n if (resolver) closeInboxResolver(resolver);\n if (source) disposePublicView(source);\n if (database) closeBrowserDatabase(database);\n }\n function current() {\n if (!active || !productEnquirySnapshot(enquiry)) {\n close();\n return false;\n }\n return true;\n }\n function ownership() {\n const actor = identity && identityMessagingOwnership(identity);\n const own = inboxSetupViewOwnership(setup);\n const product = productEnquirySendOwnership(enquiry);\n const data = productEnquirySnapshot(enquiry);\n return current() &&\n actor?.current() &&\n own?.current() &&\n own.identity === identity &&\n own.session &&\n product?.current() &&\n data &&\n data.peer !== actor.owner\n ? { actor, own, product, data }\n : undefined;\n }\n function ready() {\n const scope = ownership();\n return (\n !!scope &&\n !!source &&\n messagingReadinessSnapshot(\n identity!,\n scope.own.session,\n scope.own.policy,\n scope.own.resolver,\n undefined,\n scope.own.observeAccess\n ).newListingReady\n );\n }\n function snapshot(): Snapshot | undefined {\n if (!current()) return;\n const actual = productEnquirySnapshot(enquiry);\n const draft =\n actual?.revision === sentRevision &&\n composer &&\n privateComposerSnapshot(composer);\n const workflow =\n preparation && selfRecoveryPreparationSnapshot(preparation);\n return {\n state,\n busy,\n dirty: draft\n ? draft.dirty\n : !!productEnquirySnapshot(enquiry)?.text.trim(),\n revision: actual?.revision ?? 0,\n readyToSend: !attempted && state !== 'needs_action' && ready(),\n sellerInbox: sellerInboxStatus(\n resolver,\n actual!.peer,\n inboxSetupViewOwnership(setup)?.policy\n ),\n copy:\n copy ||\n (state === 'preparing'\n ? 'Preparing encryption. The extension may ask for several approvals.'\n : state === 'publishing'\n ? 'Publishing encrypted copies to the reviewed inbox relays.'\n : ''),\n saveCopy: draft\n ? draft.copy\n : attempted\n ? 'Encrypted work needs review in this browser.'\n : 'Not yet saved.',\n pairCopy: workflow?.pairCopy ?? '',\n navigation:\n requestedRevision === undefined ? 'idle' : 'confirmation_required'\n };\n }\n async function send(review: unknown): Promise<Result> {\n if (review !== 'reviewed_product_request_send')\n return { status: 'invalid' };\n if (!current()) return { status: 'stopped' };\n if (busy) return { status: 'busy' };\n if (attempted) return { status: 'needs_action' };\n const captured = ownership();\n if (\n !captured ||\n !ready() ||\n !identity ||\n !source ||\n !captured.data.text.trim()\n )\n return { status: 'invalid' };\n const actor = identity,\n originalSetup = setup,\n originalGeneration = generation;\n const privateOwner = privateSessionOwnership(captured.own.session!);\n if (\n !privateOwner?.current() ||\n privateOwner.owner !== captured.actor.owner ||\n privateOwner.session !== captured.actor.session\n )\n return { status: 'invalid' };\n const admitted = () =>\n current() &&\n generation === originalGeneration &&\n identity === actor &&\n setup === originalSetup &&\n captured.actor.current() &&\n captured.own.current() &&\n captured.product.current() &&\n privateOwner.current() &&\n productEnquirySnapshot(enquiry)?.revision === captured.data.revision &&\n inboxSetupViewOwnership(originalSetup)?.session === captured.own.session;\n function needsAction(): Result {\n state = 'needs_action';\n copy =\n 'Send needs review. Your unsent text stays in memory. Existing encrypted work requires its own recovery review.';\n return { status: 'needs_action' };\n }\n busy = true;\n state = 'checking';\n copy =\n 'Checking the intended publisher inbox. Your text remains in memory.';\n try {\n if (resolver) closeInboxResolver(resolver);\n resolver = resolveInboxPreference(\n source,\n beginPublicViewRun(source),\n captured.data.peer\n );\n const other = resolver;\n // Resolver observations are asynchronous; sample their original bounded\n // result through the existing readiness projection, without guessing.\n await settleInboxResolver(other, admitted);\n if (!admitted()) {\n const unavailable = sellerInboxCopy(\n sellerInboxStatus(other, captured.data.peer, captured.own.policy)\n );\n if (\n unavailable &&\n current() &&\n generation === originalGeneration &&\n identity === actor &&\n setup === originalSetup &&\n captured.actor.current() &&\n captured.own.current() &&\n privateOwner.current() &&\n productEnquirySnapshot(enquiry)?.revision === captured.data.revision\n ) {\n state = 'needs_action';\n copy =\n (captured.product.current()\n ? ''\n : 'Listing status changed or could not be confirmed. Review the current listing before sending. ') +\n unavailable +\n ' Your unsent text stays in memory.';\n }\n return { status: 'stopped' };\n }\n if (\n !messagingReadinessSnapshot(\n actor,\n captured.own.session,\n captured.own.policy,\n captured.own.resolver,\n { author: captured.data.peer, resolver: other },\n captured.own.observeAccess\n ).sendReady\n ) {\n const result = needsAction();\n const unavailable = sellerInboxCopy(\n sellerInboxStatus(other, captured.data.peer, captured.own.policy)\n );\n if (unavailable)\n copy =\n unavailable +\n ' Your unsent text stays in memory. Optional other contact details may be available on the listing.';\n return result;\n }\n const routes = createInboxRoutePlan(\n captured.own.policy,\n captured.actor.owner,\n captured.data.peer,\n captured.own.resolver!,\n other\n );\n const routeData = routes && inboxRoutePlanSnapshot(routes);\n if (!routes || !routeData || !admitted()) return needsAction();\n const opened = await openBrowserDatabase();\n if (opened.state !== 'ready') return needsAction();\n database = opened.owner;\n if (!admitted()) return { status: 'stopped' };\n const repository = createPrivateStorageRepository(\n database,\n captured.actor.owner\n );\n const reservations = createPrivateSendReservationRepository(\n database,\n captured.actor.owner\n );\n composer = createPrivateComposer(actor, 'reviewed_private_composer');\n sentRevision = captured.data.revision;\n if (\n !repository ||\n !reservations ||\n !composer ||\n !updatePrivateComposerText(\n composer,\n captured.data.text,\n 'reviewed_private_text'\n )\n )\n return needsAction();\n plan = captureEnquiryRumor(\n actor,\n captured.product.context,\n captured.data.text,\n Math.floor(Date.now() / 1000),\n admitted\n );\n const command = newLocalId();\n if (!plan || !command || !admitted()) return needsAction();\n attempted = true;\n const reserved = await reserveSendIdentity(\n reservations,\n actor,\n command,\n plan,\n 'reviewed_private_intent'\n );\n if (!admitted()) return { status: 'stopped' };\n if (!('identity' in reserved)) return needsAction();\n preparation = captureSelfRecoveryPreparation(\n repository,\n actor,\n reserved.identity,\n 'reviewed_self_recovery'\n );\n if (\n !preparation ||\n !bindPrivateComposerPreparation(\n composer,\n reserved.identity,\n preparation,\n captured.product.context,\n 'reviewed_composer_preparation'\n )\n )\n return needsAction();\n state = 'preparing';\n copy = '';\n const self = await prepareSelfRecovery(\n preparation,\n 'reviewed_self_recovery'\n );\n if (!admitted()) return { status: 'stopped' };\n if (\n !['saved', 'existing', 'reconciled'].includes(self.status) ||\n !preparedSelfRecovery(preparation)\n )\n return needsAction();\n const context = {\n plan: routes,\n policy: captured.own.policy,\n own: captured.own.resolver!,\n other\n };\n const paired = await preparePairedDelivery(\n preparation,\n context,\n 'reviewed_pair_preparation'\n );\n if (!admitted()) return { status: 'stopped' };\n const receipt = preparedPairedDelivery(preparation);\n if (\n !['prepared', 'existing', 'reconciled'].includes(paired.status) ||\n !receipt\n )\n return needsAction();\n const pool = getPrivatePool(\n captured.own.session!,\n captured.own.policy,\n Array.from(\n new Set([...routeData.peer.targets, ...routeData.archive.targets])\n )\n );\n if (!pool || !admitted()) return needsAction();\n retry = capturePrivateRetry(\n repository,\n captured.own.session!,\n receipt,\n context,\n pool,\n 'reviewed_private_retry'\n );\n if (!retry || !admitted()) return needsAction();\n state = 'publishing';\n const delivered = await runPrivateRetry(retry, 'reviewed_private_retry');\n if (!admitted()) return { status: 'stopped' };\n if (delivered.status !== 'completed') return needsAction();\n state = 'completed';\n copy =\n 'Accepted by recipient inbox relay. This does not confirm that the person read the message.';\n return { status: 'completed' };\n } catch {\n return admitted() ? needsAction() : { status: 'stopped' };\n } finally {\n busy = false;\n }\n }\n const token = Object.freeze({}) as ProductRequestController;\n controllers.set(token, {\n snapshot,\n text: () => (current() ? productEnquirySnapshot(enquiry)?.text : undefined),\n update(text, review) {\n if (\n review !== 'reviewed_private_text' ||\n !current() ||\n busy ||\n attempted ||\n !updateProductEnquiry(enquiry, text, 'reviewed_product_enquiry_edit')\n )\n return false;\n return true;\n },\n configure(nextIdentity, nextSetup, review) {\n if (\n review !== 'reviewed_product_request_setup' ||\n !current() ||\n attempted ||\n busy\n )\n return false;\n const actor = identityMessagingOwnership(nextIdentity),\n own = inboxSetupViewOwnership(nextSetup);\n if (!actor?.current() || !own?.current() || own.identity !== nextIdentity)\n return false;\n if (identity === nextIdentity && setup === nextSetup) return true;\n stopWork();\n identityOff();\n identity = nextIdentity;\n setup = nextSetup;\n identityOff = subscribeIdentityInvalidation(nextIdentity, () => {\n if (!actor.current()) {\n stopWork();\n copy = 'Connection changed. Your unsent text stays in memory.';\n }\n });\n return true;\n },\n send,\n stop(review) {\n if (review !== 'reviewed_product_request_cancel' || !current())\n return false;\n stopWork(true);\n if (state !== 'completed') {\n state = attempted ? 'needs_action' : 'idle';\n copy =\n 'Sending is paused. Your unsent text stays in this page; existing encrypted work requires its own recovery review.';\n }\n return true;\n },\n request() {\n if (!current()) return 'invalid';\n if (!snapshot()?.dirty) return 'allowed';\n requestedRevision = productEnquirySnapshot(enquiry)?.revision;\n return 'confirmation_required';\n },\n keep() {\n if (!current()) return false;\n requestedRevision = undefined;\n return true;\n },\n discard(review) {\n if (\n !current() ||\n review !== 'reviewed_discard_private_text' ||\n requestedRevision === undefined\n )\n return 'invalid';\n const expected = requestedRevision;\n requestedRevision = undefined;\n if (expected !== productEnquirySnapshot(enquiry)?.revision)\n return 'review_required';\n close();\n return 'allowed';\n },\n unload(event) {\n if (!current() || !snapshot()?.dirty) return false;\n event.preventDefault();\n return true;\n },\n close\n });\n return token;\n}\nexport function productRequestSnapshot(token: ProductRequestController) {\n return controllers.get(token)?.snapshot();\n}\nexport function productRequestText(token: ProductRequestController) {\n return controllers.get(token)?.text();\n}\nexport function updateProductRequestText(\n token: ProductRequestController,\n text: unknown,\n review: unknown\n) {\n return controllers.get(token)?.update(text, review) ?? false;\n}\nexport function configureProductRequest(\n token: ProductRequestController,\n identity: IdentitySession,\n setup: InboxSetupView,\n review: unknown\n) {\n return controllers.get(token)?.configure(identity, setup, review) ?? false;\n}\nexport function sendProductRequest(\n token: ProductRequestController,\n review: unknown\n): Promise<Result> {\n return (\n controllers.get(token)?.send(review) ??\n Promise.resolve({ status: 'invalid' })\n );\n}\nexport function requestProductRequestNavigation(\n token: ProductRequestController\n): NavigationResult {\n return controllers.get(token)?.request() ?? 'invalid';\n}\nexport function keepProductRequestEditing(token: ProductRequestController) {\n return controllers.get(token)?.keep() ?? false;\n}\nexport function discardProductRequestNavigation(\n token: ProductRequestController,\n review: unknown\n): NavigationResult {\n return controllers.get(token)?.discard(review) ?? 'invalid';\n}\nexport function productRequestBeforeUnload(\n token: ProductRequestController,\n event: BeforeUnloadEvent\n) {\n return controllers.get(token)?.unload(event) ?? false;\n}\nexport function closeProductRequestController(token: ProductRequestController) {\n controllers.get(token)?.close();\n}\nexport function stopProductRequestWork(\n token: ProductRequestController,\n review: unknown\n) {\n return controllers.get(token)?.stop(review) ?? false;\n}\n", + sha256: + '9fb8bb41657de661d4fe32d05f78fdc453e215467b08ee7d8036d39093cb0979' + }, + 'src/lib/nostr/inbox-preference-publication.ts': { + source: + "import type { NostrEvent } from 'applesauce-core/helpers';\nimport {\n publicRelayTargets,\n readRelayPolicy,\n type RelayPolicy\n} from '../config/relays.ts';\nimport {\n identityMessagingOwnership,\n identityPublicOperationOwnership,\n recheckIdentityOwner,\n type IdentitySession,\n type IdentityPublicOperation\n} from '../runtime/identity-session.ts';\nimport {\n publicEffectLeaseCurrent,\n type PublicEffectLease\n} from '../runtime/effect-ownership.ts';\nimport {\n loadPreferenceOperation,\n type PublicQuotaRepository\n} from '../persistence/quota.ts';\nimport {\n publicRecordSnapshot,\n publicRecordWire,\n type PublicRecordHandle\n} from '../persistence/records.ts';\ndeclare const publicationBrand: unique symbol;\nexport type PreferencePublication = Readonly<{ [publicationBrand]: true }>;\ntype Saved = Readonly<{\n policy: RelayPolicy;\n wire: string;\n eventId: string;\n origins: readonly string[];\n current(): boolean;\n}>;\nconst publications = new WeakMap<PreferencePublication, Saved>();\n// Internal exact policy observation, not a Nostr cryptographic replacement.\nexport async function preferencePolicyFingerprint(\n policy: RelayPolicy\n): Promise<string> {\n const hash = await crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(JSON.stringify(readRelayPolicy(policy)))\n );\n return Array.from(new Uint8Array(hash), (byte) =>\n byte.toString(16).padStart(2, '0')\n ).join('');\n}\n// Only a genuine current identity operation and original lease can acquire this\n// one-attempt capability from actual acknowledged storage. No caller event wire.\n// beforeEffect is an internal bounded lookup port; its final fence is retained.\nexport async function authorizeStoredInboxPreference(\n repository: PublicQuotaRepository,\n identity: IdentitySession,\n operation: IdentityPublicOperation,\n lease: PublicEffectLease,\n original: PublicRecordHandle,\n id: string,\n policy: RelayPolicy,\n beforeEffect: () => Promise<(() => boolean) | undefined>\n): Promise<PreferencePublication | undefined> {\n try {\n if (typeof window === 'undefined') return undefined;\n const capture = identityPublicOperationOwnership(identity, operation);\n const messageOwner = identityMessagingOwnership(identity);\n if (\n !capture ||\n !messageOwner ||\n capture.owner !== messageOwner.owner ||\n capture.session !== messageOwner.session\n )\n return undefined;\n const originalWire = publicRecordWire(original, capture.owner, id),\n row = publicRecordSnapshot(original, capture.owner, id);\n if (\n !originalWire ||\n row?.family !== 'preference_operation' ||\n row.revision !== 0 ||\n row.capture.kind !== 10050\n )\n return undefined;\n const authority = {\n owner: capture.owner,\n id,\n recordWire: originalWire,\n session: capture.session\n };\n const fingerprint = await preferencePolicyFingerprint(policy),\n manifest = readRelayPolicy(policy),\n targets = publicRelayTargets(policy, 'write');\n if (\n !manifest.messagingEnabled ||\n !manifest.postingEnabled ||\n fingerprint !== row.capture.policyFingerprint ||\n JSON.stringify(targets) !== JSON.stringify(row.capture.targets)\n )\n return undefined;\n const read = await loadPreferenceOperation(repository, id);\n if (!read.ok) return undefined;\n const stored = publicRecordSnapshot(read.value, capture.owner, id);\n if (\n stored?.family !== 'preference_operation' ||\n stored.revision < 2 ||\n !stored.artifact ||\n JSON.stringify(stored.capture) !== JSON.stringify(row.capture) ||\n JSON.stringify(stored.source) !== JSON.stringify(row.source) ||\n stored.consent !== row.consent\n )\n return undefined;\n const headCurrent = await beforeEffect();\n if (!headCurrent) return undefined;\n await recheckIdentityOwner(identity);\n const current = () =>\n capture.current() &&\n messageOwner.current() &&\n headCurrent() &&\n publicEffectLeaseCurrent(lease, authority);\n if (!current()) return undefined;\n const token = Object.freeze({}) as PreferencePublication;\n publications.set(token, {\n policy,\n wire: stored.artifact.wire,\n eventId: stored.artifact.eventId,\n origins: [...stored.capture.targets],\n current\n });\n return token;\n } catch {\n return undefined;\n }\n}\n// Detached metadata never grants permission. Pool consumes the original token.\nexport function preferencePublicationSnapshot(token: PreferencePublication) {\n const saved = publications.get(token);\n return saved\n ? { eventId: saved.eventId, origins: [...saved.origins] }\n : undefined;\n}\nexport function takePreferencePublication(\n token: PreferencePublication,\n policy: RelayPolicy,\n origin: string\n): Readonly<{ event: NostrEvent; current(): boolean }> | undefined {\n const saved = publications.get(token);\n if (!saved) return undefined;\n publications.delete(token);\n if (\n saved.policy !== policy ||\n !saved.origins.includes(origin) ||\n !saved.current()\n )\n return undefined;\n return {\n event: JSON.parse(saved.wire) as NostrEvent,\n current: saved.current\n };\n}\n", + sha256: + 'fbad642340732bf7cf92905010af314829b80cc7b134121396f14e9bb8e765cc' + } + }, + ...{ 'src/routes/privacy/+page.svelte': { source: "<script lang=\"ts\">\n import { getContext, onMount } from 'svelte';\n import Button from '../../lib/components/primitives/Button.svelte';\n import {\n LOCAL_PUBLIC_HIDES_CONTEXT,\n PUBLIC_HIDE_DISCLOSURE,\n localPublicHidesSnapshot,\n subscribeLocalPublicHides,\n undoLocalPublicPublisher,\n type LocalPublicHides\n } from '../../lib/persistence/local-public-hides.ts';\n const hides = getContext<LocalPublicHides | undefined>(\n LOCAL_PUBLIC_HIDES_CONTEXT\n );\n import {\n LOCAL_PRIVATE_BLOCKS_CONTEXT,\n PRIVATE_BLOCK_DISCLOSURE,\n localPrivateBlocksViewSnapshot,\n subscribeLocalPrivateBlocksView,\n undoLocalPrivateBlocksView,\n type LocalPrivateBlocksView\n } from '../../lib/persistence/local-private-blocks.ts';\n const blocks = getContext<LocalPrivateBlocksView | undefined>(\n LOCAL_PRIVATE_BLOCKS_CONTEXT\n );\n let privateSnapshot = $state.raw(\n blocks\n ? localPrivateBlocksViewSnapshot(blocks)\n : { state: 'guest' as const }\n );\n let privateNotice = $state<string | undefined>();\n let privateBusy = $state(false);\n onMount(() => {\n if (!blocks) return;\n privateSnapshot = localPrivateBlocksViewSnapshot(blocks);\n return subscribeLocalPrivateBlocksView(blocks, () => {\n privateSnapshot = localPrivateBlocksViewSnapshot(blocks);\n privateNotice = undefined;\n });\n });\n async function undoBlock(peer: string) {\n if (!blocks || privateBusy || privateSnapshot.state !== 'ready') return;\n const owner = privateSnapshot.owner;\n privateBusy = true;\n const result = await undoLocalPrivateBlocksView(\n blocks,\n peer,\n 'reviewed_local_private_undo'\n );\n if (!alive) return;\n privateBusy = false;\n const current = localPrivateBlocksViewSnapshot(blocks);\n if (current.state !== 'ready' || current.owner !== owner) return;\n privateNotice =\n result.status === 'saved' || result.status === 'existing'\n ? 'Block undone. Eligible local views can be shown again. Another explicit bounded decryption action may be needed; Undo starts no message work.'\n : 'Undo was not confirmed. Existing local data has not been reset.';\n }\n let snapshot = $state.raw(\n hides ? localPublicHidesSnapshot(hides) : { state: 'guest' as const }\n );\n let notice = $state<string | undefined>(),\n busy = $state(false);\n let alive = false;\n onMount(() => {\n alive = true;\n const off = hides\n ? subscribeLocalPublicHides(hides, () => {\n snapshot = localPublicHidesSnapshot(hides);\n notice = undefined;\n })\n : () => {};\n if (hides) snapshot = localPublicHidesSnapshot(hides);\n return () => {\n alive = false;\n off();\n };\n });\n async function undo(publisher: string) {\n if (!hides || busy || snapshot.state !== 'ready') return;\n const owner = snapshot.owner;\n busy = true;\n const result = await undoLocalPublicPublisher(\n hides,\n publisher,\n 'reviewed_local_public_undo'\n );\n if (!alive) return;\n busy = false;\n const current = localPublicHidesSnapshot(hides);\n if (current.state !== 'ready' || current.owner !== owner) return;\n notice =\n result.status === 'saved' || result.status === 'existing'\n ? 'Hide undone. Eligible public listings can be shown again; operator policy still applies.'\n : 'Undo was not confirmed. Existing local data has not been reset.';\n }\n</script>\n\n<svelte:head><title>Privacy \u2014 HarvestCircle</title></svelte:head>\n<div class=\"page page--reading stack\">\n <h1>Privacy</h1>\n <p>\n Listings are public. Relay queries can reveal your search or publisher\n interest; search URLs may remain in browser history and hosting logs. This\n prototype uses no tracking analytics.\n </p>\n <p>{PUBLIC_HIDE_DISCLOSURE}</p>\n <h2>Local publisher controls</h2>\n {#if snapshot.state === 'ready'}\n {#if snapshot.publishers.length}\n <ul class=\"stack\">\n {#each snapshot.publishers as publisher (publisher)}\n <li class=\"stack\">\n <p class=\"key\">{publisher}</p>\n <Button\n label=\"Undo hide\"\n onclick={() => undo(publisher)}\n disabled={busy}\n />\n </li>\n {/each}\n </ul>\n {:else}<p>No publishers hidden for this account in this browser.</p>{/if}\n {:else if snapshot.state === 'guest'}\n <p>\n Connect to review your account-local publisher preferences. Guest browsing\n does not expose an account inventory.\n </p>\n {:else if snapshot.state === 'loading'}\n <p>Checking local publisher preferences\u2026</p>\n {:else}\n <p class=\"notice\">\n Local preferences could not be checked. You can still browse public food.\n Existing local data has not been reset; previous hides are unconfirmed.\n </p>\n {/if}\n {#if notice}<p role=\"status\">{notice}</p>{/if}\n <p>{PRIVATE_BLOCK_DISCLOSURE}</p>\n <h2>Local private blocks</h2>\n {#if privateSnapshot.state === 'ready'}\n {#if privateSnapshot.peers.length}\n <ul class=\"stack\">\n {#each privateSnapshot.peers as peer (peer)}\n <li class=\"stack\">\n <p class=\"key\">{peer}</p>\n <Button\n label=\"Undo block\"\n onclick={() => undoBlock(peer)}\n disabled={privateBusy}\n />\n </li>\n {/each}\n </ul>\n {:else}<p>No people blocked for this account in this browser.</p>{/if}\n {:else if privateSnapshot.state === 'guest'}\n <p>\n Connect to review account-local blocks. Guest browsing does not expose a\n private inventory.\n </p>\n {:else if privateSnapshot.state === 'loading'}\n <p>Checking local private block preferences\u2026</p>\n {:else}\n <p class=\"notice\">\n Local private preferences could not be checked. Previous blocks are\n unconfirmed; private rendering and decryption continuation are\n unavailable. Existing local data has not been reset.\n </p>\n {/if}\n {#if privateNotice}<p role=\"status\">{privateNotice}</p>{/if}\n</div>\n", @@ -717,7 +791,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, 58); + assert.equal(files.length, 59); // 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( @@ -788,7 +862,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; await refresh(f); await assert.rejects( f.audit, - /inbox presentation source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source/ + /inbox presentation source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ ); } ); @@ -964,7 +1038,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; await refresh(f); await assert.rejects( f.audit, - /inbox compiler source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source/ + /inbox compiler source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ ); } ); @@ -1007,7 +1081,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, 58); + assert.equal((await f.audit()).length, 59); } ); @@ -1637,7 +1711,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 support reporting source|Invalid owned privacy data source/ + /Invalid owned listing editor source|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ ); } ); @@ -1659,7 +1733,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 support reporting source|Invalid owned privacy data source/ + /Invalid owned selling workspace source|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ ); } ); @@ -1689,7 +1763,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; await refresh(f); await assert.rejects( f.audit, - /Invalid owned (public hiding source|private blocking source|support reporting source|privacy data source|root runtime activation)/ + /Invalid owned (public hiding source|private blocking source|support reporting source|privacy data source|operational flags source|root runtime activation)/ ); } ); @@ -1727,7 +1801,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; await refresh(f); await assert.rejects( f.audit, - /Invalid owned (private blocking source|support reporting source|privacy data source|root runtime activation)/ + /Invalid owned (private blocking source|support reporting source|privacy data source|operational flags source|root runtime activation)/ ); } ); @@ -1756,7 +1830,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; await refresh(f); await assert.rejects( f.audit, - /Invalid owned support reporting source|Invalid owned privacy data source/ + /Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ ); } ); @@ -1795,7 +1869,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; await refresh(f); await assert.rejects( f.audit, - /Invalid owned privacy data source/ + /Invalid owned privacy data source|Invalid owned operational flags source/ ); } ); @@ -1814,6 +1888,49 @@ import { auditOutput } from '../../tools/check-output.mjs'; } ); } + for (const producer of [ + 'src/lib/config/operation-flags.ts', + 'src/lib/runtime/capabilities.ts', + 'src/lib/components/AppShell.svelte', + 'src/lib/components/ListingEditor.svelte', + 'src/lib/components/MessageComposer.svelte', + 'src/lib/publishing/prepare-listing.ts', + 'src/lib/nostr/listing-publisher.ts', + 'src/lib/publishing/resume-listing.ts', + 'src/lib/messaging/inbox-setup.ts', + 'src/lib/messaging/inbox-setup-operation.ts', + 'src/lib/messaging/inbox-setup-view.ts', + 'src/lib/messaging/reply-controller.ts', + 'src/lib/messaging/product-request-controller.ts', + 'src/lib/nostr/inbox-preference-publication.ts' + ]) { + await check( + 'operational flags 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 operational flags producer\n' + ); + await refresh(f); + await assert.rejects( + f.audit, + /Invalid owned operational flags source/ + ); + } + ); + await check( + 'operational flags 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|operational flags/); + } + ); + } for (const route of [ 'src/routes/sell/+page.svelte', 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte', @@ -1832,7 +1949,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 support reporting source|Invalid owned privacy data source/ + /Invalid owned listing editor activation|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ ); } ); @@ -1868,8 +1985,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 support reporting source|Invalid owned privacy data source/ - : /Invalid owned product presentation source|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data 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 privacy data source|Invalid owned operational flags source/ + : /Invalid owned product presentation source|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ ); } ); @@ -2053,7 +2170,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 support reporting source|Invalid owned privacy data source/ + /Invalid owned search presentation source|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ ); } ); diff --git a/web/tests/unit/operation-flags.test.ts b/web/tests/unit/operation-flags.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from 'vitest'; +import { validateRelayPolicy } from '../../src/lib/config/relays.ts'; +import { operationEnabled } from '../../src/lib/config/operation-flags.ts'; +import { operationCapabilities } from '../../src/lib/runtime/capabilities.ts'; + +function policy(postingEnabled: boolean, messagingEnabled: boolean) { + const value = validateRelayPolicy( + JSON.stringify({ + schemaVersion: 1, + public: [ + { + origin: 'wss://discovery.example.org', + read: true, + write: true, + nip50: false + } + ], + inbox: [{ origin: 'wss://inbox.example.org', read: true, write: true }], + postingEnabled, + messagingEnabled, + operatorDenylist: [] + }) + ); + if (!value) throw Error('genuine policy missing'); + return value; +} +describe('HCP126 separate static availability without effect authority', () => { + for (const posting of [false, true]) + for (const messaging of [false, true]) { + it(`admits posting=${posting}, messaging=${messaging} independently while new listings require both`, () => { + const original = policy(posting, messaging); + expect(operationEnabled(original, 'posting')).toBe(posting); + expect(operationEnabled(original, 'messaging')).toBe(messaging); + expect(operationEnabled(original, 'new_listing')).toBe( + posting && messaging + ); + expect(operationCapabilities(original)).toMatchObject({ + posting, + messaging, + newListing: posting && messaging, + draft: true, + pendingReview: true, + qualification: 'not_established_by_flags' + }); + }); + } + it('copied and absent policy observations fail closed without hiding retained local work', () => { + const original = policy(true, true); + for (const value of [{ ...original }, undefined]) { + expect(operationEnabled(value, 'posting')).toBe(false); + expect(operationEnabled(value, 'messaging')).toBe(false); + expect(operationEnabled(value, 'new_listing')).toBe(false); + expect(operationCapabilities(value)).toMatchObject({ + posting: false, + messaging: false, + newListing: false, + draft: true, + pendingReview: true + }); + } + expect(operationEnabled(original, 'receive_as_order')).toBe(false); + const view = operationCapabilities(original); + expect(view).not.toHaveProperty('sign'); + expect(view).not.toHaveProperty('send'); + expect(view).not.toHaveProperty('resume'); + expect(operationCapabilities(original)).not.toBe(view); + }); +}); diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs @@ -231,7 +231,225 @@ 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 operationalFlagsAdmission(web) { + const shell = publicText( + await readOwned(web, 'src/lib/components/AppShell.svelte') + ); + if (!shell.includes('../runtime/capabilities.ts')) 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/AppShell.svelte': + '90430e0503f2c1f2e22a4cf55ca6ec56985d1f2a15e17f13bcc6ccd5036f31e0', + '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': + '593c28fbce8b010d57ee6e79f11fdbeeba07787f20d868ad83024349a4d8a9f5', + 'src/lib/components/ListingReview.svelte': + 'deee41ca6c60b346afc7ed5e62e3101ee03b04fdd2a9aa8fa3f3dec585e3863b', + 'src/lib/components/LocalDataReview.svelte': + '662e77b3c7df48baeed317628c848bfc50f0b5643145e04cdaf017a1cc078ff5', + 'src/lib/components/MessageComposer.svelte': + 'c3ab09ae9a2dc5ac8268cc45218140c5480dcb9bcf8b8bce54d2ae35ffdb2d14', + '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/operation-flags.ts': + 'd5e0ce74a17de7a06100dcc75886616655fbd398c657027e7d6990d97aa8a0c1', + '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-operation.ts': + '245c6ce88b146dc731e7ace4f16dc9b5002a87a997f5568e4811b0c4a2daf035', + 'src/lib/messaging/inbox-setup-view.ts': + 'e85238d20f1bbcb23599b36e67910f3df784efa43f0fa0b0b7f3da7e7fd33c79', + 'src/lib/messaging/inbox-setup.ts': + '7a935d8542ff8f64287d2b441a8a458d299dea4ed88beecda39cb1637dd4a9ac', + 'src/lib/messaging/inbox-sync.ts': + '84f9b3bb165a81878bb281c51d245aff7eb06a0fa55b857a49b13d0cb1cff8ae', + 'src/lib/messaging/inbox-view.ts': + '6871707ae7395d3679856a01e87c7d8f273848e0b9ef0dc7b94f450d8417528c', + 'src/lib/messaging/product-request-controller.ts': + 'ad0a4ac96a18250fd6ed66bb68a22dacd7542e57a62b040b884d8b2dfd2fabef', + 'src/lib/messaging/reply-controller.ts': + 'aacd2f4ad0b738fc85d14dab403447edda2665df36120b200b3e468447002254', + '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/inbox-preference-publication.ts': + '032e40d12ecd3a55a973edb8a8b8c7c2a9c7a791425dc5e7d56aab4b0ea4c4bb', + 'src/lib/nostr/ingress.ts': + 'c433d459ad650c1fa9aa81aca24ddfaad8c251de9e43f92502e83fd5b673e772', + 'src/lib/nostr/listing-publisher.ts': + '43a61caa6e308e15608ace5337086ef5eb5cee2c1191fe73de99405be159cfb0', + '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/inbox-retention.ts': + '8bcc73be03321e60a6fbbe7ba58de14eb8fb34db5d5cdce0adee31b5467d7bb9', + 'src/lib/persistence/local-data-review.ts': + '80c786bcce36f84b79775eea1710611ea77a1ee666fedb0067be4341949eb5df', + 'src/lib/persistence/local-inventory.ts': + '2ff3ca31cee4eec65b56a8f87d8ecdd0238cb86ef4bbe18d74518f299570adc1', + 'src/lib/persistence/local-private-blocks.ts': + 'd7e76c1122ff5479f261293db458a3240438ce0471c788c2f07ffaf854449cbc', + 'src/lib/persistence/local-public-hides.ts': + '4f0e64ed0fabbe9f86014a0512e7dbd3c81711f28ca2c626e2dafa5cda349f83', + 'src/lib/persistence/private-records.ts': + '5892589a11e7009d4f4c27620a7da7ca34913552d9aa513431941050742ff386', + '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': + 'd82858b3de51ddb55466eedb980f37ebe3f70db6c36d0abe5f39feed30d441fc', + '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': + '70cbd7ba19222bed0a1584961eace7d21cefded1659e2597d813bfdf0ee25c76', + 'src/lib/publishing/resume-listing.ts': + 'cf33ef15c3c7bee3ac2095bf50db4d93f0d4a3c505e944be9dfa10c79bca89c9', + '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/capabilities.ts': + '55a3dffc6b4b58fd96a91820c9a26a6ac951864d12ed269d8708cf61d446799f', + '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': + 'c6fdaeea02196067c111e839ec2d8ea3ba4bf21b81dbe23a2cad5ae9503aad44', + '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 operational flags source' + ); + } + return true; +} +/** @param {string} web */ async function privacyDataAdmission(web) { + if (await operationalFlagsAdmission(web)) return true; let privacy; try { privacy = publicText( @@ -1267,6 +1485,10 @@ async function productPresentationAdmission(web) { if ( createHash('sha256').update(bytes).digest('hex') !== pin && !( + name === 'src/lib/messaging/product-request-controller.ts' && + (await operationalFlagsAdmission(web)) + ) && + !( [ 'src/routes/products/[naddr=naddr]/+page.svelte', 'src/lib/catalog/product-view.ts', @@ -1338,6 +1560,10 @@ async function preferencePublicationAdmission(web) { if ( createHash('sha256').update(bytes).digest('hex') !== pin && !( + name === 'src/lib/nostr/inbox-preference-publication.ts' && + (await operationalFlagsAdmission(web)) + ) && + !( name === 'src/lib/nostr/public-pool.ts' && (await listingEditorAdmission(web)) === 'owned-withdrawal' ) @@ -1374,6 +1600,12 @@ async function listingPublicationAdmission(web) { if ( createHash('sha256').update(bytes).digest('hex') !== pin && !( + [ + 'src/lib/nostr/listing-publisher.ts', + 'src/lib/publishing/resume-listing.ts' + ].includes(name) && (await operationalFlagsAdmission(web)) + ) && + !( (name === 'src/lib/nostr/listing-publisher.ts' && (await listingEditorAdmission(web)) === 'owned-revision') || ([ @@ -1762,6 +1994,23 @@ async function listingEditorAdmission(web) { withdrawing = withdrawing && (createHash('sha256').update(bytes).digest('hex') === pin || + ([ + 'src/lib/config/operation-flags.ts', + 'src/lib/runtime/capabilities.ts', + 'src/lib/components/AppShell.svelte', + 'src/lib/components/ListingEditor.svelte', + 'src/lib/components/MessageComposer.svelte', + 'src/lib/publishing/prepare-listing.ts', + 'src/lib/nostr/listing-publisher.ts', + 'src/lib/publishing/resume-listing.ts', + 'src/lib/messaging/inbox-setup.ts', + 'src/lib/messaging/inbox-setup-operation.ts', + 'src/lib/messaging/inbox-setup-view.ts', + 'src/lib/messaging/reply-controller.ts', + 'src/lib/messaging/product-request-controller.ts', + 'src/lib/nostr/inbox-preference-publication.ts' + ].includes(name) && + (await operationalFlagsAdmission(web))) || (name === 'src/lib/runtime/public-runtime.ts' && (await publicHidingAdmission(web))) || (name === 'src/lib/persistence/quota.ts' && @@ -1791,7 +2040,13 @@ async function inboxSetupAdmission(web) { for (const [name, pin] of Object.entries(producers)) { const bytes = await readOwned(web, name); publicText(bytes); - if (createHash('sha256').update(bytes).digest('hex') !== pin) + if ( + createHash('sha256').update(bytes).digest('hex') !== pin && + !( + name === 'src/lib/messaging/inbox-setup-view.ts' && + (await operationalFlagsAdmission(web)) + ) + ) throw new Error('Invalid owned inbox compiler source'); } return true; @@ -1944,6 +2199,8 @@ export async function auditOutput(webDirectory) { ]) await readOwned(web, name); } + const hasOperationalFlags = + hasFullRoutes && (await operationalFlagsAdmission(web)); const hasPrivacyData = hasFullRoutes && (await privacyDataAdmission(web)); const hasSupportReporting = hasFullRoutes && (await supportReportingAdmission(web)); @@ -2126,6 +2383,7 @@ export async function auditOutput(webDirectory) { names.add('navigation-url'); } if (hasPrivacyData) names.add('SupportLink'); + if (hasOperationalFlags) names.add('capabilities'); const admitted = new Map([['build-info.json', expectedMetadata]]); const seen = new Set(); for (const [key, record] of Object.entries(manifest)) { @@ -4990,6 +5248,51 @@ export async function auditOutput(webDirectory) { ] } }); + if (hasOperationalFlags) + Object.assign(expected, { + ListingEditor: { + file: '_app/immutable/chunks/HASH.js', + name: 'ListingEditor', + imports: [ + 'public-key', + 'private-session', + 'references', + 'client', + 'navigation-url', + 'public-runtime', + 'CapabilityGate', + 'capabilities', + 'InboxSetup', + 'OperationStatus' + ] + }, + capabilities: { + file: '_app/immutable/chunks/HASH.js', + name: 'capabilities', + imports: ['public-runtime'] + }, + 'nodes/0': { + file: '_app/immutable/nodes/0.HASH.js', + name: 'nodes/0', + src: '.svelte-kit/generated/build/client-optimized/nodes/0.js', + isEntry: true, + imports: [ + 'public-key', + 'private-session', + 'client', + 'navigation-url', + 'public-runtime', + 'client.svelte', + 'state', + 'Button', + 'CapabilityGate', + 'Disclosure', + 'capabilities', + 'local-private-blocks' + ], + css: ['_app/immutable/assets/0.HASH.css'] + } + }); for (const record of Object.values(manifest)) { const actual = { ...record }; actual.file = actual.file.includes('/chunks/')