app

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

commit 34463eb756c626cf2f8e0ae78566c920e3f03239
parent 9dd0a55c3d1fe63bb9fb4b35414f9967fe0c5f50
Author: triesap <tyson@radroots.org>
Date:   Sat, 10 Oct 2026 17:48:58 +0000

publishing: implement reviewed listing withdrawal (HCP-120)

Diffstat:
Mweb/src/lib/components/ListingEditor.svelte | 43+++++++++++++++++++++++++++++++++++++++++--
Mweb/src/lib/components/ListingReview.svelte | 127+++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------
Mweb/src/lib/components/OperationStatus.svelte | 12+++++++++---
Mweb/src/lib/nostr/listing-publisher.ts | 5++++-
Mweb/src/lib/nostr/public-pool.ts | 2+-
Mweb/src/lib/persistence/artifact-records.ts | 6++++--
Mweb/src/lib/persistence/public-publications.ts | 7++++++-
Mweb/src/lib/persistence/public-receipts.ts | 5++++-
Mweb/src/lib/persistence/quota.ts | 54++++++++++++++++++++++++++++++++++++++++++------------
Mweb/src/lib/publishing/edit-source.ts | 37+++++++++++++++++++++++++++++++++++++
Mweb/src/lib/publishing/editor-workflow.ts | 17+++++++++++++----
Mweb/src/lib/publishing/listing-editor.ts | 34+++++++++++++++++++++-------------
Mweb/src/lib/publishing/listing-operation-view.ts | 28++++++++++++++++++++++++----
Mweb/src/lib/publishing/new-listing-readiness.ts | 12++++++++++--
Mweb/src/lib/publishing/prepare-listing.ts | 65+++++++++++++++++++++++++++++++++++++++++++++++------------------
Mweb/src/lib/publishing/sign-listing.ts | 10+++++++++-
Aweb/src/lib/publishing/withdraw-listing.ts | 14++++++++++++++
Mweb/src/lib/runtime/effect-ownership.ts | 19+++++++++++++++++--
Aweb/tests/e2e/harness/withdraw-listing.ts | 7+++++++
Aweb/tests/e2e/withdraw-listing.spec.ts | 539+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/provenance/output.test.mjs | 55+++++++++++++++++++++++++++++++++++++++++++++++++++----
Aweb/tests/unit/withdraw-listing.test.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tools/check-output.mjs | 92++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
23 files changed, 1132 insertions(+), 121 deletions(-)

diff --git a/web/src/lib/components/ListingEditor.svelte b/web/src/lib/components/ListingEditor.svelte @@ -23,6 +23,7 @@ editorReviewSnapshot, closeEditorReview, publishEditorRevision, + stopEditorAction, editorPublicationOperation, type EditorReview, type EditorFormError @@ -76,6 +77,7 @@ let review = $state.raw<EditorReview | undefined>(), reviewBusy = $state(false); let soldConfirm = $state(false), + withdrawalConfirm = $state(false), publishBusy = $state(false); let publicationOperation = $state.raw<ListingOperationView | undefined>(); let errors = $state<readonly EditorFormError[]>([]), @@ -199,6 +201,7 @@ review = undefined; publicationOperation = undefined; soldConfirm = false; + withdrawalConfirm = false; errors = []; reviewMessage = ''; form = blankForm(); @@ -273,9 +276,12 @@ review = undefined; errors = []; soldConfirm = false; + withdrawalConfirm = false; void editListingEditor(original, { ...form }); } - async function showReview(status: 'active' | 'sold' = 'active') { + async function showReview( + status: 'active' | 'sold' | 'withdrawal' = 'active' + ) { const original = editor, resource = route, author = admittedAuthor; @@ -348,7 +354,9 @@ try { const result = await publishEditorRevision( original, - 'publish_reviewed_revision' + editorReviewSnapshot(original)?.withdrawal + ? 'publish_reviewed_withdrawal' + : 'publish_reviewed_revision' ); if ( !mounted || @@ -490,6 +498,18 @@ soldConfirm = false; }} />{/if} + {#if withdrawalConfirm && editable}<ConfirmPanel + title="Confirm removal request" + text="This public request asks clients to stop displaying the listing. It cannot erase all other copies. Review the exact target before publishing." + confirmLabel="Review removal request" + onconfirm={() => { + withdrawalConfirm = false; + void showReview('withdrawal'); + }} + oncancel={() => { + withdrawalConfirm = false; + }} + />{/if} {#if visibleReview}<ListingReview review={visibleReview} onedit={editDetails} @@ -758,7 +778,26 @@ }} disabled={reviewBusy || closeBusy}>Mark as sold</button > + <button + type="button" + onclick={() => { + withdrawalConfirm = true; + }} + disabled={reviewBusy || closeBusy}>Request removal</button + > </details>{/if} + {#if publishBusy && review && editorReviewSnapshot(review)?.withdrawal} + <p> + Stop stops further attempts; it cannot retract requests already sent or + whose outcome is unknown. + </p> + <button + type="button" + onclick={() => { + if (review) stopEditorAction(review); + }}>Stop current action</button + > + {/if} {#if publicationOperation}<OperationStatus publicOperation={publicationOperation} />{/if} diff --git a/web/src/lib/components/ListingReview.svelte b/web/src/lib/components/ListingReview.svelte @@ -31,56 +31,93 @@ {#if preview} <section class="stack" aria-label="Public listing review"> <h2 id="listing-review-heading" tabindex="-1">Public review</h2> - <p>Check the complete public listing before any signing or publication.</p> - <h3>{tag('title')}</h3> - <p class="description" id="listing-review-content">{preview.content}</p> - <dl> - <dt>Derived summary</dt> - <dd>{preview.summary}</dd> - <dt>Public area</dt> - <dd>{tag('location')}</dd> - <dt>Price</dt> - <dd>{tag('price')} per {tag('radroots:price_unit')}</dd> - {#if tag('radroots:quantity')}<dt>Advertised quantity</dt> - <dd>{tag('radroots:quantity')}</dd>{/if} - <dt>Publisher</dt> - <dd class="key">{preview.owner}</dd> - {#if preview.revision} - <dt>Unchanged listing coordinate</dt> - <dd class="key">{preview.revision.coordinate}</dd> - <dt>Original publication time</dt> - <dd>{preview.revision.publishedAtSeconds}</dd> - <dt>Proposed availability</dt> - <dd>{preview.revision.status === 'sold' ? 'Sold' : 'Available'}</dd> - {/if} - <dt>Public destinations</dt> - <dd> - <ul> - {#each preview.targets as target (target)}<li class="key"> - {target} - </li>{/each} - </ul> - </dd> - </dl> - {#if !preview.revision}<p>Messages: ready to receive replies</p>{/if} - {#if !captured && !publishing}<p> - This review has not requested a signature or published the listing. - </p>{/if} - {#if preview.revision?.status === 'sold'}<p> - This is a public availability update, not a payment or stock reservation - receipt. - </p>{/if} - {#if preview.revision && onpublish && !captured} + {#if preview.withdrawal} + <h3>Removal request</h3> + <p>This public request cannot erase all other copies.</p> + <dl> + <dt>Listing coordinate</dt> + <dd class="key">{preview.withdrawal.coordinate}</dd> + <dt>Exact retained event</dt> + <dd class="key">{preview.withdrawal.eventId}</dd> + <dt>Public author</dt> + <dd class="key">{preview.owner}</dd> + <dt>Request time</dt> + <dd>{preview.createdAtSeconds}</dd> + <dt>Request kind</dt> + <dd>5</dd> + <dt>Exact request ID</dt> + <dd class="key">{preview.expectedHash}</dd> + <dt>Public reason</dt> + <dd>No public reason text.</dd> + <dt>Public references</dt> + <dd class="key">{tag('e')} {tag('a')} {tag('k')}</dd> + <dt>Public destinations</dt> + <dd> + <ul> + {#each preview.targets as target (target)}<li class="key"> + {target} + </li>{/each} + </ul> + </dd> + </dl> + {:else} + <p> + Check the complete public listing before any signing or publication. + </p> + <h3>{tag('title')}</h3> + <p class="description" id="listing-review-content">{preview.content}</p> + <dl> + <dt>Derived summary</dt> + <dd>{preview.summary}</dd> + <dt>Public area</dt> + <dd>{tag('location')}</dd> + <dt>Price</dt> + <dd>{tag('price')} per {tag('radroots:price_unit')}</dd> + {#if tag('radroots:quantity')}<dt>Advertised quantity</dt> + <dd>{tag('radroots:quantity')}</dd>{/if} + <dt>Publisher</dt> + <dd class="key">{preview.owner}</dd> + {#if preview.revision} + <dt>Unchanged listing coordinate</dt> + <dd class="key">{preview.revision.coordinate}</dd> + <dt>Original publication time</dt> + <dd>{preview.revision.publishedAtSeconds}</dd> + <dt>Proposed availability</dt> + <dd>{preview.revision.status === 'sold' ? 'Sold' : 'Available'}</dd> + {/if} + <dt>Public destinations</dt> + <dd> + <ul> + {#each preview.targets as target (target)}<li class="key"> + {target} + </li>{/each} + </ul> + </dd> + </dl> + {#if !preview.revision}<p>Messages: ready to receive replies</p>{/if} + {#if !captured && !publishing}<p> + This review has not requested a signature or published the listing. + </p>{/if} + {#if preview.revision?.status === 'sold'}<p> + This is a public availability update, not a payment or stock + reservation receipt. + </p>{/if} + {/if} + {#if (preview.revision || preview.withdrawal) && onpublish && !captured} <button type="button" class="button button--primary" onclick={onpublish} disabled={publishing} - >{publishing - ? 'Publishing update' - : preview.revision.status === 'sold' - ? 'Publish sold update' - : 'Publish changes'}</button + >{preview.withdrawal + ? publishing + ? 'Publishing removal request' + : 'Publish removal request' + : publishing + ? 'Publishing update' + : preview.revision?.status === 'sold' + ? 'Publish sold update' + : 'Publish changes'}</button > {/if} <button type="button" onclick={onedit} disabled={publishing || captured} diff --git a/web/src/lib/components/OperationStatus.svelte b/web/src/lib/components/OperationStatus.svelte @@ -43,6 +43,10 @@ <div class="stack stack--tight"> <Notice tone={summary.tone} text={summary.text} /> {#if publicSnapshot} + {#if publicSnapshot.purpose === 'withdrawal'}<p> + Removal request evidence remains here even when the listing is + suppressed. It cannot erase all other copies. + </p>{/if} <p> Relay acceptance recorded for {publicSnapshot.acceptanceCount} of {publicSnapshot .targets.length} targets. @@ -52,9 +56,11 @@ .targets.length} targets. </p> <p> - {publicSnapshot.localSource === 'retained-prototype' - ? 'Retained prototype source is available in this browser. Editing requires a separate current-head check.' - : 'No supported retained prototype source is available for editing. Keep this listing read-only.'} + {publicSnapshot.purpose === 'withdrawal' + ? 'This request has its own retained local operation. Listing visibility does not determine its delivery outcome.' + : publicSnapshot.localSource === 'retained-prototype' + ? 'Retained prototype source is available in this browser. Editing requires a separate current-head check.' + : 'No supported retained prototype source is available for editing. Keep this listing read-only.'} </p> {#if publicSnapshot.needsAction} <Notice diff --git a/web/src/lib/nostr/listing-publisher.ts b/web/src/lib/nostr/listing-publisher.ts @@ -98,7 +98,10 @@ export async function readRetainedListingDelivery( ); if ( baseline?.family !== 'public_operation' || - baseline.capture.kind !== 30402 || + !( + baseline.capture.kind === 30402 || + (baseline.capture.kind === 5 && baseline.source.type === 'public_head') + ) || !baseline.artifact || baseline.revision !== 2 ) diff --git a/web/src/lib/nostr/public-pool.ts b/web/src/lib/nostr/public-pool.ts @@ -374,7 +374,7 @@ export function getPublicPool( { ids: [expected.id], authors: [expected.pubkey], - kinds: [30402], + kinds: [expected.kind], limit: 1 } ], diff --git a/web/src/lib/persistence/artifact-records.ts b/web/src/lib/persistence/artifact-records.ts @@ -166,8 +166,10 @@ export function preparePublicListingSigningTransition( if ( !base || base.row.family !== 'public_operation' || - base.row.source.type !== 'draft' || - base.row.capture.kind !== 30402 || + !( + (base.row.source.type === 'draft' && base.row.capture.kind === 30402) || + (base.row.source.type === 'public_head' && base.row.capture.kind === 5) + ) || base.row.revision !== 0 || base.row.artifact !== null || base.row.receipts.length !== 0 diff --git a/web/src/lib/persistence/public-publications.ts b/web/src/lib/persistence/public-publications.ts @@ -173,7 +173,12 @@ export async function savePublicListingIntent( custody.repository !== scope.drafts || !row || row.family !== 'public_operation' || - row.source.type !== 'draft' + (row.source.type !== 'draft' && + !( + row.capture.kind === 5 && + row.source.type === 'public_head' && + revisionBase + )) ) return { status: 'invalid_scope' }; if ( diff --git a/web/src/lib/persistence/public-receipts.ts b/web/src/lib/persistence/public-receipts.ts @@ -38,7 +38,10 @@ export async function commitPublicListingReceipt( !owner || !quota || row?.family !== 'public_operation' || - row.capture.kind !== 30402 || + !( + row.capture.kind === 30402 || + (row.capture.kind === 5 && row.source.type === 'public_head') + ) || !row.artifact ) return { status: 'invalid' }; diff --git a/web/src/lib/persistence/quota.ts b/web/src/lib/persistence/quota.ts @@ -389,7 +389,11 @@ function claimOperation( inspectLocalTemplate(witness.capture.wire, scope.owner, 30402); const nextTemplate = record.family === 'public_operation' && - inspectLocalTemplate(record.capture.wire, scope.owner, 30402); + inspectLocalTemplate( + record.capture.wire, + scope.owner, + record.capture.kind + ); const tag = ( template: NonNullable<ReturnType<typeof inspectLocalTemplate>>, key: string @@ -405,26 +409,45 @@ function claimOperation( JSON.stringify(base.source) !== JSON.stringify(witness.source) || JSON.stringify(base.capture) !== JSON.stringify(witness.capture) || JSON.stringify(base.artifact) !== JSON.stringify(witness.artifact) || - tag(oldTemplate, 'd') !== tag(nextTemplate, 'd') || - tag(oldTemplate, 'published_at') !== - tag(nextTemplate, 'published_at') || + (nextTemplate.kind === 5 + ? record.family !== 'public_operation' || + record.source.type !== 'public_head' || + record.source.wire !== witness.artifact.wire || + JSON.stringify(nextTemplate.tags) !== + JSON.stringify([ + ['e', witness.artifact.eventId], + ['a', `30402:${scope.owner}:${tag(oldTemplate, 'd')}`], + ['k', '30402'] + ]) || + nextTemplate.content !== '' + : tag(oldTemplate, 'd') !== tag(nextTemplate, 'd') || + tag(oldTemplate, 'published_at') !== + tag(nextTemplate, 'published_at')) || nextTemplate.created_at <= oldTemplate.created_at || rows.some((row) => { if ( row.record.family !== 'public_operation' || - row.record.id === base.id || - row.record.capture.kind !== 30402 + row.record.id === base.id ) return false; const other = inspectLocalTemplate( row.record.capture.wire, scope.owner, - 30402 + row.record.capture.kind ); return ( !!other && - tag(other, 'd') === tag(oldTemplate, 'd') && - other.created_at >= oldTemplate.created_at + (other.kind === 5 + ? other.tags.some( + (value) => + (value[0] === 'e' && + value[1] === witness.artifact!.eventId) || + (value[0] === 'a' && + value[1] === + `30402:${scope.owner}:${tag(oldTemplate, 'd')}`) + ) && other.created_at >= oldTemplate.created_at + : tag(other, 'd') === tag(oldTemplate, 'd') && + other.created_at >= oldTemplate.created_at) ); }) ) { @@ -441,10 +464,17 @@ function claimOperation( ); if ( !source || - source.type !== 'draft' || + (source.type !== 'draft' && + !( + source.type === 'public_head' && + record.family === 'public_operation' && + record.capture.kind === 5 && + draft.revisionBase + )) || draft.expected.owner !== scope.owner || - source.id !== draft.expected.id || - source.revision !== draft.expected.revision || + (source.type === 'draft' && + (source.id !== draft.expected.id || + source.revision !== draft.expected.revision)) || !previousDraft || JSON.stringify(previousDraft.record) !== JSON.stringify(draft.expected) || diff --git a/web/src/lib/publishing/edit-source.ts b/web/src/lib/publishing/edit-source.ts @@ -88,6 +88,7 @@ type Source = { identity: IdentitySession; policy: RelayPolicy; currentRevision(eventId: string): boolean; + currentWithdrawal(eventId: string): boolean; current(): boolean; }> | undefined; @@ -389,6 +390,42 @@ export async function openOwnedEditSource( publishedAtSeconds: base.publishedAt, identity: session, policy, + currentWithdrawal(eventId: string) { + const state = snapshot(); + if ( + !current() || + !runtime || + publicRuntimePolicy(runtime) !== policy + ) + return false; + if (state?.status === 'ready') return true; + const row = + resolver && networkOwned() + ? headResolutionSnapshot(resolver).find( + (value) => value.key === key + ) + : undefined; + // Only the original request's verified suppression preserves its + // delivery continuity. A different request/head remains fenced. + return !!( + state?.status === 'withdrawn' && + state.currentEventId === base.eventId && + row && + row.state.display === 'focused_known' && + row.deletion.eventReference?.requestId === eventId && + row.deletion.addressReference?.requestId === eventId && + row.coverage === 'bounded-eose' && + !row.lastKnown && + view && + run && + publicViewRunCurrent(view, run) && + [row.headSources, row.deletionSources].every( + (scope) => + scope?.state === 'eose' && + scope.result.coverage === 'bounded-eose' + ) + ); + }, currentRevision(eventId: string) { const state = snapshot(); if ( diff --git a/web/src/lib/publishing/editor-workflow.ts b/web/src/lib/publishing/editor-workflow.ts @@ -185,7 +185,7 @@ export async function openEditorReview( editor: ListingEditor, setup: InboxSetupView | undefined, form: PublicDraftForm, - status: 'active' | 'sold' = 'active' + status: 'active' | 'sold' | 'withdrawal' = 'active' ): Promise< | Readonly<{ status: 'review'; review: EditorReview }> | Readonly<{ @@ -194,7 +194,7 @@ export async function openEditorReview( message: string; }> > { - const errors = validateEditorForm(form); + const errors = status === 'withdrawal' ? [] : validateEditorForm(form); if (errors.length) return { status: 'blocked', @@ -253,6 +253,12 @@ export function editorPublicationOperation( const owned = reviews.get(review); return owned?.active() ? owned.operation() : undefined; } +// Revokes future effects of this original action; stored/sent evidence remains. +export function stopEditorAction(review: EditorReview): void { + const owned = reviews.get(review); + const signing = owned?.active() ? owned.signing() : undefined; + if (signing) stopListingSigning(signing); +} // Existing publication pipeline only. One original review deduplicates clicks; // explicit consent does not bypass original editor/source/draft/current-head. export function publishEditorRevision( @@ -263,8 +269,11 @@ export function publishEditorRevision( const preview = owned && listingReviewSnapshot(owned.original); if ( !owned?.active() || - !preview?.revision || - consent !== 'publish_reviewed_revision' + (!preview?.revision && !preview?.withdrawal) || + consent !== + (preview?.withdrawal + ? 'publish_reviewed_withdrawal' + : 'publish_reviewed_revision') ) return Promise.resolve({ status: 'invalid' }); const pending = publishing.get(review); diff --git a/web/src/lib/publishing/listing-editor.ts b/web/src/lib/publishing/listing-editor.ts @@ -19,6 +19,7 @@ import { } from './prepare-listing.ts'; import { reviewOwnedRevision } from './revise-listing.ts'; import { reviewMarkSold } from './mark-sold.ts'; +import { reviewOwnedWithdrawal } from './withdraw-listing.ts'; import { decodeProductReference } from '../nostr/references.ts'; import { openOwnedEditSource, @@ -102,7 +103,7 @@ type Editor = Readonly<{ review( setup: InboxSetupView | undefined, form: PublicDraftForm, - status: 'active' | 'sold' + status: 'active' | 'sold' | 'withdrawal' ): Promise<ListingReviewResult>; reviewCurrent(review: ListingReview): boolean; source(): OwnedEditSource | undefined; @@ -192,14 +193,14 @@ export async function openListingEditor( | { setup: InboxSetupView | undefined; proof?: NewListingReadiness; - status: 'active' | 'sold'; + status: 'active' | 'sold' | 'withdrawal'; review: ListingReview; } | undefined; let reviewing: Promise<ListingReviewResult> | undefined; let reviewingForm: string | undefined; let reviewingSetup: InboxSetupView | undefined; - let reviewingStatus: 'active' | 'sold' | undefined; + let reviewingStatus: 'active' | 'sold' | 'withdrawal' | undefined; function clearReview() { if (reviewed?.proof) closeNewListingReadiness(reviewed.proof); if (reviewed) closeListingReview(reviewed.review); @@ -540,19 +541,26 @@ export async function openListingEditor( reviewingStatus = status; const prepared = route.mode === 'edit' && editSource - ? status === 'sold' - ? reviewMarkSold( + ? status === 'withdrawal' + ? reviewOwnedWithdrawal( editSource, original, command, - 'reviewed_sold_availability' - ) - : reviewOwnedRevision( - editSource, - original, - command, - 'reviewed_owned_revision' + 'reviewed_owned_withdrawal' ) + : status === 'sold' + ? reviewMarkSold( + editSource, + original, + command, + 'reviewed_sold_availability' + ) + : reviewOwnedRevision( + editSource, + original, + command, + 'reviewed_owned_revision' + ) : proof ? reviewNewListing( publications, @@ -657,7 +665,7 @@ export function reviewListingEditor( editor: ListingEditor, setup: InboxSetupView | undefined, form: PublicDraftForm, - status: 'active' | 'sold' = 'active' + status: 'active' | 'sold' | 'withdrawal' = 'active' ): Promise<ListingReviewResult> { return ( editors.get(editor)?.review(setup, form, status) ?? diff --git a/web/src/lib/publishing/listing-operation-view.ts b/web/src/lib/publishing/listing-operation-view.ts @@ -27,6 +27,7 @@ export type ListingOperationSnapshot = Readonly<{ command: string; revision: number; eventId: string; + purpose: 'listing' | 'withdrawal'; artifact: 'unsigned' | 'signed'; state: | 'prepared' @@ -137,7 +138,10 @@ export async function readListingOperationView( !current() || !row || row.family !== 'public_operation' || - row.capture.kind !== 30402 || + !( + row.capture.kind === 30402 || + (row.capture.kind === 5 && row.source.type === 'public_head') + ) || row.capture.targets.length === 0 || (!row.artifact && (row.revision > 1 || row.receipts.length !== 0)) || (row.artifact && row.revision < 2) @@ -145,8 +149,16 @@ export async function readListingOperationView( retire(); return { status: 'unavailable' }; } - const template = inspectLocalTemplate(row.capture.wire, owner, 30402); - if (!template || projectFoodParts(template).outcome !== 'focused') { + const template = inspectLocalTemplate( + row.capture.wire, + owner, + row.capture.kind + ); + if ( + !template || + (template.kind === 30402 && + projectFoodParts(template).outcome !== 'focused') + ) { retire(); return { status: 'unavailable' }; } @@ -207,7 +219,7 @@ export async function readListingOperationView( observesSigning = state === 'signing'; if (observesSigning && signing) unsubscribeSigning = subscribeListingSigning(signing, retire); - const text = + const listingText = state === 'signing' ? 'Waiting for your extension to sign the retained listing.' : state === 'unknown' @@ -223,11 +235,19 @@ export async function readListingOperationView( : row.artifact ? 'Signed listing saved in this browser. No relay acceptance is recorded.' : 'Saved in this browser. The retained listing has not been signed.'; + const text = + row.capture.kind === 5 + ? listingText + .replaceAll('listing event', 'removal request') + .replaceAll('listing', 'removal request') + + ' This request cannot erase all other copies.' + : listingText; const snapshot: ListingOperationSnapshot = { owner, command: id, revision: row.revision, eventId: row.capture.hash, + purpose: row.capture.kind === 5 ? 'withdrawal' : 'listing', artifact: row.artifact ? 'signed' : 'unsigned', state, acceptanceCount, diff --git a/web/src/lib/publishing/new-listing-readiness.ts b/web/src/lib/publishing/new-listing-readiness.ts @@ -224,11 +224,19 @@ export function captureOwnedListingReadiness( eventId: string, review: unknown ): NewListingReadiness | undefined { - if (review !== 'reviewed_owned_listing') return; + if ( + review !== 'reviewed_owned_listing' && + review !== 'reviewed_owned_withdrawal' + ) + return; const original = authorizeOwnedEditSource(source); if (!original) return; let active = true; - const current = () => active && original.currentRevision(eventId); + const current = () => + active && + (review === 'reviewed_owned_withdrawal' + ? original.currentWithdrawal(eventId) + : original.currentRevision(eventId)); const token = Object.freeze({}) as NewListingReadiness; reviews.set(token, { ownership: { diff --git a/web/src/lib/publishing/prepare-listing.ts b/web/src/lib/publishing/prepare-listing.ts @@ -57,6 +57,7 @@ export type ListingPreview = Readonly<{ expectedHash: string; targets: readonly string[]; policyFingerprint: string; + withdrawal?: Readonly<{ coordinate: string; eventId: string }>; revision?: Readonly<{ coordinate: string; publishedAtSeconds: number; @@ -71,7 +72,7 @@ type Review = Readonly<{ command: string; readiness: NewListingReadiness; source?: OwnedEditSource; - status?: 'active' | 'sold'; + status?: 'active' | 'sold' | 'withdrawal'; record: PublicRecordHandle; revisionBase?: Readonly<{ command: string; record: PublicRecordHandle }>; previewWire: string; @@ -131,7 +132,7 @@ export async function reviewOwnedListing( source: OwnedEditSource, controller: PublicDraftController, command: unknown, - status: 'active' | 'sold', + status: 'active' | 'sold' | 'withdrawal', consent: unknown ): Promise<ListingReviewResult> { const original = authorizeOwnedEditSource(source); @@ -151,7 +152,10 @@ async function reviewListing( readiness: NewListingReadiness | undefined, command: unknown, consent: unknown, - revision?: Readonly<{ source: OwnedEditSource; status: 'active' | 'sold' }> + revision?: Readonly<{ + source: OwnedEditSource; + status: 'active' | 'sold' | 'withdrawal'; + }> ): Promise<ListingReviewResult> { try { const custody = publicDraftControllerOwnership(controller), @@ -172,9 +176,11 @@ async function reviewListing( !ready.current() || consent !== (revision - ? revision.status === 'sold' - ? 'reviewed_sold_availability' - : 'reviewed_owned_revision' + ? revision.status === 'withdrawal' + ? 'reviewed_owned_withdrawal' + : revision.status === 'sold' + ? 'reviewed_sold_availability' + : 'reviewed_owned_revision' : 'reviewed_new_listing') ) return { status: 'blocked', reason: 'unavailable' }; @@ -224,7 +230,8 @@ async function reviewListing( reason: revision ? 'conflict' : 'unavailable' }; const form = expected.form; - if (form.contactType === '' && form.contactValue !== '') + const withdrawal = revision?.status === 'withdrawal'; + if (!withdrawal && form.contactType === '' && form.contactValue !== '') return { status: 'blocked', reason: 'invalid_form' }; const contact = form.contactType === '' @@ -245,20 +252,34 @@ async function reviewListing( ...(form.quantity === '' ? {} : { quantity: form.quantity }), created_at: createdAtSeconds, published_at: retained ? retained.publishedAtSeconds : createdAtSeconds, - status: revision?.status ?? 'active', + status: revision?.status === 'sold' ? 'sold' : 'active', ...(contact ? { contact } : {}) }); - if (!built.ok) return { status: 'blocked', reason: 'invalid_form' }; + if (!withdrawal && !built.ok) + return { status: 'blocked', reason: 'invalid_form' }; const manifest = readRelayPolicy(ready.policy), targets = publicRelayTargets(ready.policy, 'write'); const templateWire = JSON.stringify({ pubkey: owner, - kind: 30402, + kind: withdrawal ? 5 : 30402, created_at: createdAtSeconds, - tags: built.wire_parts.tags, - content: built.wire_parts.content + tags: + withdrawal && base + ? [ + ['e', base.id], + ['a', `30402:${owner}:${identifier}`], + ['k', '30402'] + ] + : built.ok + ? built.wire_parts.tags + : [], + content: withdrawal ? '' : built.ok ? built.wire_parts.content : '' }); - const template = inspectLocalTemplate(templateWire, owner, 30402); + const template = inspectLocalTemplate( + templateWire, + owner, + withdrawal ? 5 : 30402 + ); if (!template || !manifest.postingEnabled || targets.length === 0) return { status: 'blocked', reason: 'unavailable' }; const digest = await crypto.subtle.digest( @@ -301,9 +322,12 @@ async function reviewListing( owner, id, revision: 0, - source: { type: 'draft', id: expected.id, revision: expected.revision }, + source: + withdrawal && retained + ? { type: 'public_head', wire: retained.baseWire } + : { type: 'draft', id: expected.id, revision: expected.revision }, capture: { - kind: 30402, + kind: withdrawal ? 5 : 30402, wire: templateWire, hash: template.hash, targets, @@ -320,7 +344,7 @@ async function reviewListing( ? captureOwnedListingReadiness( revision.source, template.hash, - 'reviewed_owned_listing' + withdrawal ? 'reviewed_owned_withdrawal' : 'reviewed_owned_listing' ) : readiness; const finalReady = newListingReadinessOwnership(proof); @@ -352,12 +376,17 @@ async function reviewListing( identifier, createdAtSeconds, form, - summary: built.summary, + summary: withdrawal ? 'Removal request' : built.ok ? built.summary : '', templateWire, expectedHash: template.hash, targets, policyFingerprint, - ...(retained && revision + ...(withdrawal && retained && base + ? { + withdrawal: { coordinate: retained.coordinate, eventId: base.id } + } + : {}), + ...(retained && revision && !withdrawal ? { revision: { coordinate: retained.coordinate, diff --git a/web/src/lib/publishing/sign-listing.ts b/web/src/lib/publishing/sign-listing.ts @@ -380,12 +380,20 @@ async function execute(model: Model): Promise<ListingSigningResult> { model.setOperation(operation); const ownership = identityPublicOperationOwnership(identity, operation); if (!ownership || !current(model)) return { status: 'unavailable' }; + const captured = publicRecordSnapshot( + original.record, + owner, + original.command + ); + if (captured?.family !== 'public_operation') return { status: 'invalid' }; const result = await runCapturedPublicEffect( quota, original.record, original.command, { ...ownership, current: () => current(model) && ownership.current() }, - 'reviewed_prepared_listing_operation', + captured.capture.kind === 5 && captured.source.type === 'public_head' + ? 'reviewed_prepared_withdrawal_operation' + : 'reviewed_prepared_listing_operation', async (lease): Promise<ListingSigningResult> => { const marker = preparePublicListingSigningTransition( original.record, diff --git a/web/src/lib/publishing/withdraw-listing.ts b/web/src/lib/publishing/withdraw-listing.ts @@ -0,0 +1,14 @@ +import type { OwnedEditSource } from './edit-source.ts'; +import type { PublicDraftController } from './draft-controller.ts'; +import { reviewOwnedListing } from './prepare-listing.ts'; + +// Original retained-source custody is mandatory. A copied public event or a +// display snapshot cannot authorize a removal request. +export function reviewOwnedWithdrawal( + source: OwnedEditSource, + controller: PublicDraftController, + command: unknown, + consent: unknown +) { + return reviewOwnedListing(source, controller, command, 'withdrawal', consent); +} diff --git a/web/src/lib/runtime/effect-ownership.ts b/web/src/lib/runtime/effect-ownership.ts @@ -75,6 +75,7 @@ export async function runCapturedPublicEffect<T>( if ( (review !== 'reviewed_captured_operation' && review !== 'reviewed_prepared_listing_operation' && + review !== 'reviewed_prepared_withdrawal_operation' && review !== 'reviewed_prepared_preference_operation' && review !== 'reviewed_stored_preference_retry') || !owner || @@ -90,8 +91,11 @@ export async function runCapturedPublicEffect<T>( ) return { status: 'invalid' }; const listingMode = review === 'reviewed_prepared_listing_operation'; + const withdrawalMode = review === 'reviewed_prepared_withdrawal_operation'; const preferenceMode = - review !== 'reviewed_captured_operation' && !listingMode; + review !== 'reviewed_captured_operation' && + !listingMode && + !withdrawalMode; const storedRetry = review === 'reviewed_stored_preference_retry'; if ( listingMode && @@ -101,6 +105,13 @@ export async function runCapturedPublicEffect<T>( ) return { status: 'invalid' }; if ( + withdrawalMode && + (row.family !== 'public_operation' || + row.capture.kind !== 5 || + row.source.type !== 'public_head') + ) + return { status: 'invalid' }; + if ( preferenceMode && (row.family !== 'preference_operation' || row.capture.kind !== 10050) ) @@ -150,7 +161,11 @@ export async function runCapturedPublicEffect<T>( (listingMode && stored?.family === 'public_operation' && stored.capture.kind === 30402 && - stored.source.type === 'draft')) && + stored.source.type === 'draft') || + (withdrawalMode && + stored?.family === 'public_operation' && + stored.capture.kind === 5 && + stored.source.type === 'public_head')) && stored.revision === 0 && stored.artifact === null; const retry = diff --git a/web/tests/e2e/harness/withdraw-listing.ts b/web/tests/e2e/harness/withdraw-listing.ts @@ -0,0 +1,7 @@ +// HC_TEST_ONLY_RELAY/QUALIFICATION_PORT: original installed provider, +// retained signed prototype source and native IndexedDB. No live/operator Q. +export { + createFixture, + openSecondEditor, + type ControlledSignInput +} from './revise-listing.ts'; diff --git a/web/tests/e2e/withdraw-listing.spec.ts b/web/tests/e2e/withdraw-listing.spec.ts @@ -0,0 +1,539 @@ +import { expect, test } from '@playwright/test'; +import { build } from 'vite'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; +import { fileURLToPath } from 'node:url'; +import { once } from 'node:events'; +import { writeFile } from 'node:fs/promises'; +import { WebSocketServer } from 'ws'; +import { createStaticHarness } from '../integration/harness/static.ts'; +import type * as Fixture from './harness/withdraw-listing.ts'; +import type { NostrEvent } from 'applesauce-core/helpers'; +declare global { + interface Window { + hcp120: typeof Fixture; + hcp120Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>; + hcp120Second: Awaited<ReturnType<typeof Fixture.openSecondEditor>>; + hcp120OriginalSign(input: Fixture.ControlledSignInput): Promise<NostrEvent>; + } +} +let server: Awaited<ReturnType<typeof createStaticHarness>>, + sockets: WebSocketServer, + endpoint: string, + bundle: string; +let event: NostrEvent | undefined, + partial = false, + effects: NostrEvent[] = [], + retained: NostrEvent[] = [], + holdAck = false; +let tabs: import('@playwright/test').Page[] = []; +test.beforeAll(async () => { + server = await createStaticHarness(); + sockets = new WebSocketServer({ + host: '127.0.0.1', + port: 0, + maxPayload: 262144 + }); + await once(sockets, 'listening'); + const address = sockets.address(); + if (!address || typeof address === 'string') throw Error('loopback missing'); + endpoint = 'ws://127.0.0.1:' + address.port; + sockets.on('connection', (socket) => + socket.on('message', (bytes) => { + const raw = Buffer.isBuffer(bytes) + ? bytes + : Array.isArray(bytes) + ? Buffer.concat(bytes) + : Buffer.from(bytes); + const frame = JSON.parse(raw.toString()) as unknown[]; + if (frame[0] === 'EVENT') { + event = frame[1] as NostrEvent; + effects.push(event); + retained.push(event); + if (!holdAck) socket.send(JSON.stringify(['OK', event.id, true, ''])); + return; + } + if (frame[0] !== 'REQ') return; + const filters = frame.slice(2) as { + kinds?: number[]; + ids?: string[]; + authors?: string[]; + '#d'?: string[]; + '#e'?: string[]; + '#a'?: string[]; + }[]; + for (const actual of retained) + if ( + filters.some( + (filter) => + (!filter.kinds || filter.kinds.includes(actual.kind)) && + (!filter.ids || filter.ids.includes(actual.id)) && + (!filter.authors || filter.authors.includes(actual.pubkey)) && + (['#d', '#e', '#a'] as const).every( + (key) => + !filter[key] || + actual.tags.some( + (tag) => + tag[0] === key.slice(1) && filter[key]!.includes(tag[1]) + ) + ) + ) + ) + socket.send(JSON.stringify(['EVENT', frame[1], actual])); + if (!(partial && filters.some((filter) => filter.kinds?.includes(5)))) + socket.send(JSON.stringify(['EOSE', frame[1]])); + }) + ); + const built = await build({ + configFile: false, + plugins: [svelte({ configFile: false })], + resolve: { conditions: ['browser'] }, + logLevel: 'silent', + build: { + write: false, + minify: false, + lib: { + entry: fileURLToPath( + new URL('./harness/withdraw-listing.ts', import.meta.url) + ), + name: 'hcp120', + formats: ['iife'] + } + } + }); + const result = Array.isArray(built) ? built[0] : built; + if (!('output' in result)) throw Error('actual fixture bundle missing'); + const chunks = result.output.filter((row) => row.type === 'chunk'); + expect(chunks).toHaveLength(1); + bundle = chunks[0].code; +}); +test.afterAll(async () => { + for (const socket of sockets?.clients ?? []) socket.terminate(); + if (sockets) + await new Promise<void>((resolve, reject) => + sockets.close((error) => (error ? reject(error) : resolve())) + ); + await server?.close(); +}); +test.beforeEach(async ({ page }) => { + tabs = []; + event = undefined; + partial = false; + effects = []; + retained = []; + holdAck = false; + await page.addInitScript((endpoint) => { + const Native = window.WebSocket; + window.WebSocket = class extends Native { + constructor(url: string | URL, protocols?: string | string[]) { + if ( + ![ + 'wss://discovery.example.org', + 'wss://inbox.example.org', + 'wss://second.example.org' + ].includes(new URL(url.toString()).origin) + ) + throw Error('no live relay permission'); + super(endpoint, protocols); + } + }; + }, endpoint); + await page.goto(server.url + '/search'); + await page.addScriptTag({ content: bundle }); + event = await page.evaluate(async () => { + window.hcp120Fixture = await window.hcp120.createFixture(); + return window.hcp120Fixture.event; + }); + retained.push(event); +}); +test.afterEach(async ({ page }) => { + await page.evaluate(async () => { + await window.hcp120Second?.close(); + }); + for (const tab of tabs) { + if (!tab.isClosed()) { + await tab.evaluate(async () => { + await window.hcp120Second?.close(); + }); + await tab.close(); + } + } + await page.evaluate(async () => { + await window.hcp120Fixture?.close(); + }); +}); +async function editor(page: import('@playwright/test').Page) { + await page.evaluate(() => window.hcp120Fixture.renderEditor()); + await expect(page.locator('#listing-title')).not.toHaveAttribute( + 'readonly', + '' + ); +} +async function secondEditorPage( + page: import('@playwright/test').Page, + naddr: string +) { + const tab = await page.context().newPage(); + tabs.push(tab); + const owner = await page.evaluate(() => window.hcp120Fixture.owner); + await tab.exposeFunction( + 'hcp120OriginalSign', + async (input: Fixture.ControlledSignInput) => + await page.evaluate( + (input) => window.hcp120Fixture.signOriginal(input), + input + ) + ); + await tab.addInitScript( + ({ endpoint, owner }) => { + const Native = window.WebSocket; + window.WebSocket = class extends Native { + constructor(url: string | URL, protocols?: string | string[]) { + if ( + ![ + 'wss://discovery.example.org', + 'wss://inbox.example.org', + 'wss://second.example.org' + ].includes(new URL(url.toString()).origin) + ) + throw Error('no live relay permission'); + super(endpoint, protocols); + } + }; + Object.defineProperty(window, 'nostr', { + configurable: true, + value: { + getPublicKey: () => Promise.resolve(owner), + signEvent: (input: Fixture.ControlledSignInput) => + window.hcp120OriginalSign(input) + } + }); + }, + { endpoint, owner } + ); + await tab.goto(server.url + '/search'); + await tab.addScriptTag({ content: bundle }); + await tab.evaluate( + async ({ owner, naddr }) => { + window.hcp120Second = await window.hcp120.openSecondEditor(owner, naddr); + }, + { owner, naddr } + ); + return tab; +} + +async function removalReview(page: import('@playwright/test').Page) { + await editor(page); + await page.getByText('Other listing actions', { exact: true }).click(); + const removal = page.getByRole('button', { + name: 'Request removal', + exact: true + }); + // Count is an immediate DOM observation: a missing future action fails this + // body without making isEnabled wait for an element that does not exist. + expect(await removal.count()).toBe(1); + expect(await removal.isEnabled()).toBe(true); + await removal.click(); + await expect( + page.getByRole('region', { name: 'Confirm removal request' }) + ).toContainText('cannot erase all other copies'); + await page + .getByRole('button', { name: 'Review removal request', exact: true }) + .click(); + await expect( + page.getByRole('region', { name: 'Public listing review' }) + ).toContainText('Removal request'); +} +test('HCP120 separate consequence confirmation and full removal review perform no sign capture or send', async ({ + page +}) => { + const before = await page.evaluate(() => window.hcp120Fixture.counts()); + await removalReview(page); + const region = page.getByRole('region', { name: 'Public listing review' }); + await expect(region).toContainText( + await page.evaluate(() => window.hcp120Fixture.naddr) + ); + await expect(region).toContainText('cannot erase all other copies'); + expect(await page.evaluate(() => window.hcp120Fixture.counts())).toEqual( + before + ); + expect( + await page.evaluate(() => window.hcp120Fixture.operations()) + ).toHaveLength(1); + expect(effects).toHaveLength(0); +}); +test('HCP120 explicit removal persists distinct same-author kind5 and delivery independently of suppressed listing', async ({ + page +}) => { + const base = await page.evaluate(() => window.hcp120Fixture.event); + const signs = await page.evaluate(() => window.hcp120Fixture.counts().signs); + await removalReview(page); + await page + .getByRole('button', { name: 'Publish removal request', exact: true }) + .click(); + await expect.poll(() => effects.length).toBeGreaterThan(0); + await expect + .poll( + async () => + (await page.evaluate(() => window.hcp120Fixture.operations())) + .find((row) => row.capture.kind === 5) + ?.receipts.filter((fact) => fact.readbackWire !== null).length ?? 0 + ) + .toBe(1); + const rows = await page.evaluate(() => window.hcp120Fixture.operations()); + expect(rows).toHaveLength(2); + const removal = rows.find((row) => row.capture.kind === 5)!; + expect(removal.source).toEqual({ + type: 'public_head', + wire: JSON.stringify(base) + }); + expect(removal.capture.targets).toEqual(['wss://discovery.example.org']); + const signed = JSON.parse(removal.artifact!.wire) as NostrEvent; + expect(signed.kind).toBe(5); + expect(signed.pubkey).toBe(base.pubkey); + expect(signed.tags).toEqual([ + ['e', base.id], + [ + 'a', + `30402:${base.pubkey}:${base.tags.find((tag) => tag[0] === 'd')![1]}` + ], + ['k', '30402'] + ]); + expect(signed.created_at).toBeGreaterThanOrEqual(base.created_at); + expect(signed.created_at - Math.floor(Date.now() / 1000)).toBeLessThanOrEqual( + 300 + ); + expect( + effects.every((actual) => actual.id === signed.id && actual.kind === 5) + ).toBe(true); + expect(await page.evaluate(() => window.hcp120Fixture.counts().signs)).toBe( + signs + 1 + ); + expect( + rows.find((row) => row.artifact?.eventId === base.id)?.artifact?.wire + ).toBe(JSON.stringify(base)); + await expect( + page.getByText('Exact read-back recorded for 1 of 1 targets.', { + exact: true + }) + ).toBeVisible(); + await page.evaluate(() => window.hcp120Fixture.open()); + await expect + .poll(() => page.evaluate(() => window.hcp120Fixture.snapshot()?.status)) + .toBe('withdrawn'); + const after = await page.evaluate(() => window.hcp120Fixture.operations()); + expect(after.find((row) => row.capture.kind === 5)).toEqual(removal); + await writeFile( + test.info().outputPath('actual-retained-removal-operation.json'), + JSON.stringify(removal) + ); +}); +test('HCP120 cancel removal confirmation preserves exact proposal with no effect', async ({ + page +}) => { + await editor(page); + await page.locator('#listing-title').fill('Keep my local proposed carrots'); + const before = await page.evaluate(() => window.hcp120Fixture.counts()); + await page.getByText('Other listing actions', { exact: true }).click(); + expect( + await page + .getByRole('button', { name: 'Request removal', exact: true }) + .isEnabled() + ).toBe(true); + await page + .getByRole('button', { name: 'Request removal', exact: true }) + .click(); + await page.getByRole('button', { name: 'Keep editing', exact: true }).click(); + await expect(page.locator('#listing-title')).toHaveValue( + 'Keep my local proposed carrots' + ); + expect(await page.evaluate(() => window.hcp120Fixture.counts())).toEqual( + before + ); + expect(effects).toHaveLength(0); +}); +test('HCP120 wrong author source cannot expose a removal signing path', async ({ + page +}) => { + const before = await page.evaluate(() => window.hcp120Fixture.counts().signs); + expect( + await page.evaluate(() => + window.hcp120Fixture.open(false, window.hcp120Fixture.foreign()) + ) + ).toBeUndefined(); + const tab = await secondEditorPage( + page, + await page.evaluate(() => window.hcp120Fixture.foreign()) + ); + await expect(tab.locator('#hcp119-second')).toContainText( + 'Supported local listing values are not available for editing' + ); + await expect( + tab + .locator('#hcp119-second') + .getByRole('button', { name: 'Request removal', exact: true }) + ).toHaveCount(0); + expect(await page.evaluate(() => window.hcp120Fixture.counts().signs)).toBe( + before + ); + expect(effects).toHaveLength(0); +}); +test('HCP120 incomplete deletion coverage cannot authorize withdrawal', async ({ + page +}) => { + partial = true; + await page.evaluate(() => window.hcp120Fixture.renderEditor()); + await expect(page.locator('#listing-title')).toHaveAttribute('readonly', ''); + await expect( + page.getByRole('button', { name: 'Request removal', exact: true }) + ).toHaveCount(0); + expect(effects).toHaveLength(0); +}); +test('HCP120 independently competing head fences an already reviewed deletion without replacing proposal', async ({ + page +}) => { + await removalReview(page); + event = await page.evaluate(() => window.hcp120Fixture.competing()); + retained.push(event); + const before = await page.evaluate(() => window.hcp120Fixture.counts().signs); + await page.evaluate(() => window.hcp120Fixture.lookupAgain()); + await expect( + page.getByRole('button', { name: 'Publish removal request', exact: true }) + ).toHaveCount(0); + expect(await page.evaluate(() => window.hcp120Fixture.counts().signs)).toBe( + before + ); + expect(effects).toHaveLength(0); +}); +test('HCP120 Stop prevents more attempts and never retracts an already sent kind5', async ({ + page +}) => { + holdAck = true; + await removalReview(page); + await page + .getByRole('button', { name: 'Publish removal request', exact: true }) + .click(); + await expect.poll(() => effects.length).toBe(1); + const sent = effects[0]; + expect(sent.kind).toBe(5); + await page + .getByRole('button', { name: 'Stop current action', exact: true }) + .click(); + await expect( + page.getByRole('button', { + name: 'Publishing removal request', + exact: true + }) + ).toHaveCount(0); + expect(effects).toEqual([sent]); + const rows = await page.evaluate(() => window.hcp120Fixture.operations()); + expect(rows.find((row) => row.capture.kind === 5)?.artifact?.wire).toBe( + JSON.stringify(sent) + ); + expect( + rows + .find((row) => row.capture.kind === 5) + ?.receipts.some((fact) => fact.status === 'accepted') + ).toBe(false); +}); +for (const width of [320, 1024]) + test(`HCP120 ${width}px reviewed removal is readable without raw message deletion`, async ({ + page + }) => { + await page.setViewportSize({ width, height: 900 }); + await removalReview(page); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth + ) + ).toBe(true); + await expect( + page.getByRole('button', { name: /Delete message|Delete conversation/ }) + ).toHaveCount(0); + expect(effects).toHaveLength(0); + }); + +for (const first of ['revision', 'withdrawal'] as const) + test(`HCP120 native unresolved ${first} capture fences the other original review`, async ({ + page + }) => { + await editor(page); + const tab = await secondEditorPage( + page, + await page.evaluate(() => window.hcp120Fixture.naddr) + ); + const second = tab.locator('#hcp119-second'); + await expect(second.locator('#listing-title')).not.toHaveAttribute( + 'readonly', + '' + ); + const primary = page.locator('#hcp118-conflict'); + const removal = first === 'withdrawal' ? primary : second; + const revision = first === 'revision' ? primary : second; + await removal.getByText('Other listing actions', { exact: true }).click(); + await removal + .getByRole('button', { name: 'Request removal', exact: true }) + .click(); + await removal + .getByRole('button', { name: 'Review removal request', exact: true }) + .click(); + await expect( + removal.getByRole('region', { name: 'Public listing review' }) + ).toContainText('Removal request'); + await revision + .locator('#listing-title') + .fill('Concurrent proposed carrots'); + await revision + .getByRole('button', { name: 'Review changes', exact: true }) + .click(); + await expect( + revision.getByRole('region', { name: 'Public listing review' }) + ).toContainText('Concurrent proposed carrots'); + await page.evaluate(() => window.hcp120Fixture.refuseNextSignature()); + const firstScope = first === 'withdrawal' ? removal : revision; + const firstLabel = + first === 'withdrawal' ? 'Publish removal request' : 'Publish changes'; + await firstScope + .getByRole('button', { name: firstLabel, exact: true }) + .click(); + await expect + .poll(() => page.evaluate(() => window.hcp120Fixture.signRequests())) + .toBe(1); + await expect( + firstScope.getByRole('button', { name: /^Publishing/ }) + ).toHaveCount(0); + const before = await page.evaluate(() => window.hcp120Fixture.operations()); + expect(before).toHaveLength(2); + expect(before.find((row) => row.artifact === null)?.capture.kind).toBe( + first === 'withdrawal' ? 5 : 30402 + ); + const otherScope = first === 'withdrawal' ? revision : removal; + await otherScope + .getByRole('button', { + name: + first === 'withdrawal' + ? 'Publish changes' + : 'Publish removal request', + exact: true + }) + .click(); + await expect( + otherScope.getByText( + 'The update did not complete. Your proposed draft remains here. Check any retained operation before another attempt.', + { exact: true } + ) + ).toBeVisible(); + await expect( + otherScope.getByRole('button', { name: /^Publishing/ }) + ).toHaveCount(0); + expect( + await page.evaluate(() => window.hcp120Fixture.operations()) + ).toEqual(before); + expect(await page.evaluate(() => window.hcp120Fixture.signRequests())).toBe( + 1 + ); + expect(effects).toHaveLength(0); + await writeFile( + test.info().outputPath('actual-native-competing-capture.json'), + JSON.stringify(before) + ); + }); diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs @@ -89,11 +89,50 @@ import { auditOutput } from '../../tools/check-output.mjs'; sha256: '1c8c3445513329d57fcddc75da63991f0c1c27c28caf87db381d32bba739c872' } }; + /** @type {Record<string, {source:string, sha256:string}>} */ + const historicalWithdrawalProducerClosure = { + 'src/lib/publishing/sign-listing.ts': { + source: + "import {\n listingReviewOwnership,\n type ListingReview\n} from './prepare-listing.ts';\nimport {\n publicPublicationQuotaRepository,\n readPublicListingIntent\n} from '../persistence/public-publications.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot,\n publicRecordWire,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport {\n preparePublicListingSigningTransition,\n preparePublicArtifactTransition,\n publicTransitionSnapshot,\n type CapturedArtifact\n} from '../persistence/artifact-records.ts';\nimport {\n commitPublicOperationTransition,\n observePublicOperationTransition\n} from '../persistence/quota.ts';\nimport {\n captureIdentityPublicOperation,\n identityPublicOperationOwnership,\n identityPublicOperationSnapshot,\n recheckIdentityOwner,\n signIdentityPublicOperation,\n stopIdentityPublicOperation,\n type IdentityPublicOperation\n} from '../runtime/identity-session.ts';\nimport { runCapturedPublicEffect } from '../runtime/effect-ownership.ts';\n\ndeclare const signingBrand: unique symbol;\ndeclare const publicationBrand: unique symbol;\nexport type ListingSigning = Readonly<{ [signingBrand]: true }>;\nexport type ListingPublication = Readonly<{ [publicationBrand]: true }>;\ntype Ownership = NonNullable<ReturnType<typeof listingReviewOwnership>>;\ntype Model = Readonly<{\n original: Ownership;\n getOperation(): IdentityPublicOperation | undefined;\n setOperation(value: IdentityPublicOperation): void;\n getAttempted(): boolean;\n setAttempted(): void;\n getStopped(): boolean;\n stop(): void;\n getSigning(): boolean;\n startSigning(): void;\n finishSigning(): void;\n subscribe(listener: () => void): () => void;\n getMarked(): PublicRecordHandle | undefined;\n setMarked(value: PublicRecordHandle): void;\n getArtifact(): CapturedArtifact | undefined;\n setArtifact(value: CapturedArtifact): void;\n getPublication(): ListingPublication | undefined;\n setPublication(value: ListingPublication): void;\n}>;\nfunction createModel(original: Ownership): Model {\n let operation: IdentityPublicOperation | undefined;\n let signing = false;\n let attempted = false,\n stopped = false;\n let marked: PublicRecordHandle | undefined;\n let artifact: CapturedArtifact | undefined;\n let publication: ListingPublication | undefined;\n const listeners = new Map<symbol, () => void>();\n let notifying = false;\n function notify() {\n if (notifying) return;\n notifying = true;\n try {\n const callbacks = Array.from(listeners.entries());\n for (const [key, listener] of callbacks) {\n if (listeners.get(key) !== listener) continue;\n try {\n listener();\n } catch {\n /* Disclosure observers never control signing. */\n }\n }\n } finally {\n notifying = false;\n }\n }\n return {\n original,\n subscribe(listener) {\n const key = Symbol();\n listeners.set(key, listener);\n return () => {\n listeners.delete(key);\n };\n },\n getOperation: () => operation,\n setOperation: (value) => {\n operation = value;\n },\n getAttempted: () => attempted,\n setAttempted: () => {\n attempted = true;\n },\n getStopped: () => stopped,\n stop: () => {\n if (stopped) return;\n stopped = true;\n notify();\n },\n getSigning: () => signing,\n startSigning: () => {\n if (signing) return;\n signing = true;\n notify();\n },\n finishSigning: () => {\n if (!signing) return;\n signing = false;\n notify();\n },\n getMarked: () => marked,\n setMarked: (value) => {\n marked = value;\n },\n getArtifact: () => artifact,\n setArtifact: (value) => {\n artifact = value;\n },\n getPublication: () => publication,\n setPublication: (value) => {\n publication = value;\n }\n };\n}\ntype Publication = Readonly<{\n model: Model;\n recordWire: string;\n wire: string;\n owner: string;\n command: string;\n hash: string;\n targets: readonly string[];\n policyFingerprint: string;\n}>;\nconst signings = new WeakMap<ListingSigning, Model>();\nconst commands = new WeakMap<ListingReview, ListingSigning>();\nconst pending = new WeakMap<ListingSigning, Promise<ListingSigningResult>>();\nconst publications = new WeakMap<ListingPublication, Publication>();\nexport type ListingSigningResult =\n | Readonly<{ status: 'prepared'; publication: ListingPublication }>\n | Readonly<{\n status:\n 'invalid' | 'unavailable' | 'conflict' | 'unknown' | 'busy' | 'stopped';\n }>;\n\nfunction current(model: Model): boolean {\n const operation = model.getOperation();\n return (\n !model.getStopped() &&\n (model.getSigning()\n ? model.original.readiness.signingCurrent() &&\n !!publicPublicationQuotaRepository(model.original.repository)\n : model.original.current()) &&\n (!operation ||\n !!identityPublicOperationOwnership(\n model.original.readiness.identity,\n operation\n ))\n );\n}\nexport function beginListingSigning(\n review: ListingReview,\n consent: unknown\n): ListingSigning | undefined {\n if (consent !== 'sign_reviewed_listing') return;\n const original = listingReviewOwnership(review);\n if (!original || !publicPublicationQuotaRepository(original.repository))\n return;\n const existing = commands.get(review);\n if (existing) return existing;\n const token = Object.freeze({}) as ListingSigning;\n signings.set(token, createModel(original));\n commands.set(review, token);\n return token;\n}\nexport function listingSigningSnapshot(token: ListingSigning) {\n const model = signings.get(token);\n if (!model) return;\n const original = model.original;\n const row = publicRecordSnapshot(\n original.record,\n original.readiness.owner,\n original.command\n );\n if (!row || row.family !== 'public_operation') return;\n const heldOperation = model.getOperation();\n const operation =\n heldOperation &&\n identityPublicOperationSnapshot(original.readiness.identity, heldOperation);\n return {\n owner: row.owner,\n command: row.id,\n hash: row.capture.hash,\n stopped: model.getStopped(),\n attempted: model.getAttempted(),\n signing: model.getSigning() && current(model),\n lateAvailable: operation?.lateAvailable ?? false\n };\n}\n// Original-token lifecycle observation only; no sign, retry or send authority.\nexport function subscribeListingSigning(\n token: ListingSigning,\n listener: () => void\n): () => void {\n return signings.get(token)?.subscribe(listener) ?? (() => {});\n}\n// Detached disclosure is never a send capability. HCP112 must independently\n// admit the original plan, reread storage and obtain final network ownership.\nexport function listingPublicationSnapshot(token: ListingPublication) {\n const value = publications.get(token);\n if (!value || !current(value.model)) return;\n return {\n owner: value.owner,\n command: value.command,\n hash: value.hash,\n wire: value.wire,\n targets: value.targets.slice(),\n policyFingerprint: value.policyFingerprint\n };\n}\n// Original custody only. This port grants no raw event or network effect; the\n// typed publisher must obtain its own current lock and reread durable storage.\nexport function listingPublicationOwnership(token: ListingPublication) {\n const value = publications.get(token);\n if (!value || !current(value.model)) return;\n const operation = value.model.getOperation();\n if (!operation) return;\n return {\n repository: value.model.original.repository,\n identity: value.model.original.readiness.identity,\n policy: value.model.original.readiness.policy,\n operation,\n owner: value.owner,\n command: value.command,\n recordWire: value.recordWire,\n current: () => current(value.model)\n };\n}\nasync function exactStored(\n model: Model,\n expected: PublicRecordHandle\n): Promise<boolean> {\n const original = model.original,\n owner = original.readiness.owner;\n const read = await readPublicListingIntent(\n original.repository,\n original.command\n );\n return (\n current(model) &&\n read.status === 'found' &&\n publicRecordWire(read.record, owner, original.command) ===\n publicRecordWire(expected, owner, original.command)\n );\n}\nasync function persist(model: Model): Promise<ListingSigningResult> {\n const original = model.original,\n owner = original.readiness.owner;\n const quota = publicPublicationQuotaRepository(original.repository);\n const marked = model.getMarked(),\n artifact = model.getArtifact();\n if (!quota || !marked || !artifact || !current(model))\n return { status: 'unavailable' };\n const transition = preparePublicArtifactTransition(\n marked,\n owner,\n original.command,\n artifact\n );\n if (!transition.ok) return { status: 'conflict' };\n const proposed = publicTransitionSnapshot(\n transition.value,\n owner,\n original.command\n );\n if (!proposed) return { status: 'invalid' };\n const decoded = decodePublicRecord(\n proposed.nextWire,\n owner,\n original.command\n );\n if (!decoded.ok) return { status: 'invalid' };\n if (!current(model)) return { status: 'stopped' };\n const saved = await commitPublicOperationTransition(quota, transition.value);\n if (!current(model)) return { status: 'unknown' };\n if (!saved.ok) {\n if (saved.reason !== 'unknown_completion')\n return {\n status: saved.reason === 'conflict' ? 'conflict' : 'unavailable'\n };\n const observed = await observePublicOperationTransition(\n quota,\n transition.value\n );\n if (observed.state !== 'committed' || !current(model))\n return { status: observed.state === 'conflict' ? 'conflict' : 'unknown' };\n }\n if (!(await exactStored(model, decoded.value))) return { status: 'unknown' };\n const row = publicRecordSnapshot(decoded.value, owner, original.command);\n if (!row || row.family !== 'public_operation' || !row.artifact)\n return { status: 'invalid' };\n const token = Object.freeze({}) as ListingPublication;\n publications.set(token, {\n model,\n recordWire: proposed.nextWire,\n wire: row.artifact.wire,\n owner,\n command: row.id,\n hash: row.artifact.eventId,\n targets: row.capture.targets.slice(),\n policyFingerprint: row.capture.policyFingerprint\n });\n model.setPublication(token);\n return { status: 'prepared', publication: token };\n}\nasync function execute(model: Model): Promise<ListingSigningResult> {\n try {\n const original = model.original,\n identity = original.readiness.identity,\n owner = original.readiness.owner;\n const quota = publicPublicationQuotaRepository(original.repository);\n if (\n !quota ||\n !current(model) ||\n typeof window === 'undefined' ||\n !navigator.locks?.request\n )\n return { status: 'unavailable' };\n const publication = model.getPublication();\n if (publication) {\n const value = publications.get(publication);\n if (!value) return { status: 'invalid' };\n const rechecked = await recheckIdentityOwner(identity);\n if (!current(model) || rechecked.state === 'guest')\n return { status: 'unavailable' };\n const read = await readPublicListingIntent(\n original.repository,\n original.command\n );\n if (\n !current(model) ||\n read.status !== 'found' ||\n publicRecordWire(read.record, owner, original.command) !==\n value.recordWire\n )\n return { status: 'conflict' };\n return { status: 'prepared', publication };\n }\n if (model.getArtifact()) {\n await recheckIdentityOwner(identity);\n if (!current(model)) return { status: 'unavailable' };\n // Retained exact verified artifact retry is storage-only; never a prompt.\n return await navigator.locks.request(\n 'harvestcircle:owner:' + owner,\n { mode: 'exclusive', ifAvailable: true },\n (lock) =>\n lock ? persist(model) : Promise.resolve({ status: 'busy' as const })\n );\n }\n if (model.getAttempted()) return { status: 'unknown' };\n if (!(await exactStored(model, original.record)))\n return { status: 'conflict' };\n const operation = captureIdentityPublicOperation(\n identity,\n original.record,\n original.command,\n 'reviewed_captured_operation'\n );\n if (!operation) return { status: 'unavailable' };\n model.setOperation(operation);\n const ownership = identityPublicOperationOwnership(identity, operation);\n if (!ownership || !current(model)) return { status: 'unavailable' };\n const result = await runCapturedPublicEffect(\n quota,\n original.record,\n original.command,\n { ...ownership, current: () => current(model) && ownership.current() },\n 'reviewed_prepared_listing_operation',\n async (lease): Promise<ListingSigningResult> => {\n const marker = preparePublicListingSigningTransition(\n original.record,\n owner,\n original.command\n );\n if (!marker.ok || !current(model)) return { status: 'invalid' };\n const next = publicTransitionSnapshot(\n marker.value,\n owner,\n original.command\n );\n if (!next) return { status: 'invalid' };\n model.setAttempted();\n const saved = await commitPublicOperationTransition(\n quota,\n marker.value\n );\n if (!saved.ok || !current(model))\n return {\n status:\n saved.ok || saved.reason === 'unknown_completion'\n ? 'unknown'\n : 'unavailable'\n };\n const decoded = decodePublicRecord(\n next.nextWire,\n owner,\n original.command\n );\n if (!decoded.ok || !(await exactStored(model, decoded.value)))\n return { status: 'unknown' };\n model.setMarked(decoded.value);\n model.startSigning();\n let signed;\n try {\n signed = await signIdentityPublicOperation(\n identity,\n operation,\n lease\n );\n } finally {\n model.finishSigning();\n }\n if (signed.status !== 'signed' || !current(model))\n return {\n status:\n signed.status === 'unknown' || !current(model)\n ? 'unknown'\n : 'invalid'\n };\n model.setArtifact(signed.artifact);\n return await persist(model);\n }\n );\n return result.status === 'completed'\n ? result.value\n : {\n status:\n result.status === 'busy'\n ? 'busy'\n : result.status === 'unknown' || result.status === 'retained'\n ? 'unknown'\n : 'unavailable'\n };\n } catch {\n return { status: 'unknown' };\n }\n}\nexport function runListingSigning(\n token: ListingSigning,\n consent: unknown\n): Promise<ListingSigningResult> {\n const model = signings.get(token);\n if (!model || consent !== 'sign_reviewed_listing')\n return Promise.resolve({ status: 'invalid' });\n const active = pending.get(token);\n if (active) return active;\n const work = execute(model).finally(() => {\n if (pending.get(token) === work) pending.delete(token);\n });\n pending.set(token, work);\n return work;\n}\nexport function stopListingSigning(token: ListingSigning): void {\n const model = signings.get(token);\n if (!model) return;\n model.stop();\n const operation = model.getOperation();\n if (operation)\n stopIdentityPublicOperation(model.original.readiness.identity, operation);\n}\n", + sha256: '5051a2e0eb3353b9f099cb92dcbd3162003a9a32cebac6035b979ae3a9400bfe' + }, + 'src/lib/persistence/artifact-records.ts': { + source: + "import { canonicalPublicKey } from '../contracts/public-key.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport {\n exactLocalFields,\n type PublicOperationRecord,\n type PreferenceOperationRecord,\n type PublicTargetReceipt\n} from '../contracts/local-records.ts';\nimport { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts';\nimport { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';\nimport {\n verifyEnvelope,\n verifiedEnvelopeSnapshot\n} from '../nostr/verified-envelope.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot,\n publicRecordWire,\n type PublicRecordHandle\n} from './records.ts';\n\ndeclare const artifactBrand: unique symbol;\ndeclare const transitionBrand: unique symbol;\nexport type CapturedArtifact = Readonly<{ [artifactBrand]: true }>;\nexport type PublicOperationTransition = Readonly<{ [transitionBrand]: true }>;\nexport type ArtifactFailure =\n 'invalid_artifact' | 'invalid_record' | 'conflict' | 'revision_exhausted';\ntype Result<T> =\n | Readonly<{ ok: true; value: T }>\n | Readonly<{ ok: false; reason: ArtifactFailure }>;\ntype Artifact = Readonly<{\n author: string;\n kind: 30402 | 5 | 10050 | 1059;\n hash: string;\n wire: string;\n}>;\ntype Operation = PublicOperationRecord | PreferenceOperationRecord;\ntype Transition = Readonly<{\n owner: string;\n id: string;\n family: Operation['family'];\n kind: 30402 | 5 | 10050;\n expectedRevision: number;\n revision: number;\n baseWire: string;\n nextWire: string;\n}>;\nconst artifacts = new WeakMap<CapturedArtifact, Artifact>();\nconst transitions = new WeakMap<PublicOperationTransition, Transition>();\nfunction failed(reason: ArtifactFailure): Result<never> {\n return { ok: false, reason };\n}\n// SDK-verified exact envelope binding only. A1059 token proves an outer\n// signature/hash, not nested Message authenticity, routing or durable storage.\n// Private typed repositories own those later checks. No plaintext14/13 token.\nexport function bindCapturedArtifact(\n rawWire: unknown,\n expectedAuthor: unknown,\n expectedKind: unknown,\n expectedHash: unknown\n): Result<CapturedArtifact> {\n const author = canonicalPublicKey(expectedAuthor);\n if (\n !author ||\n (expectedKind !== 30402 &&\n expectedKind !== 5 &&\n expectedKind !== 10050 &&\n expectedKind !== 1059) ||\n typeof expectedHash !== 'string' ||\n !/^[0-9a-f]{64}$/.test(expectedHash) ||\n typeof rawWire !== 'string'\n )\n return failed('invalid_artifact');\n const proof = verifyEnvelope(rawWire);\n if (!proof.ok) return failed('invalid_artifact');\n const event = verifiedEnvelopeSnapshot(proof.value);\n if (\n !event ||\n !exactLocalFields(event, [\n 'id',\n 'pubkey',\n 'kind',\n 'created_at',\n 'tags',\n 'content',\n 'sig'\n ]) ||\n event.pubkey !== author ||\n event.kind !== expectedKind ||\n event.id !== expectedHash\n )\n return failed('invalid_artifact');\n const token = Object.freeze({}) as CapturedArtifact;\n artifacts.set(token, {\n author,\n kind: expectedKind,\n hash: expectedHash,\n wire: rawWire\n });\n return { ok: true, value: token };\n}\nexport function capturedArtifactSnapshot(\n handle: CapturedArtifact\n): Artifact | undefined {\n const saved = artifacts.get(handle);\n return saved ? { ...saved } : undefined;\n}\nfunction baseOf(\n handle: PublicRecordHandle,\n owner: unknown,\n id: unknown\n): Readonly<{ row: Operation; wire: string }> | undefined {\n const row = publicRecordSnapshot(handle, owner, id),\n wire = publicRecordWire(handle, owner, id);\n return row && row.family !== 'public_draft' && wire\n ? { row, wire }\n : undefined;\n}\nfunction retain(\n base: Readonly<{ row: Operation; wire: string }>,\n next: Operation\n): Result<PublicOperationTransition> {\n const nextWire = JSON.stringify(next);\n const decoded = decodePublicRecord(nextWire, base.row.owner, base.row.id);\n if (!decoded.ok) return failed('invalid_record');\n const token = Object.freeze({}) as PublicOperationTransition;\n transitions.set(token, {\n owner: base.row.owner,\n id: base.row.id,\n family: base.row.family,\n kind: base.row.capture.kind,\n expectedRevision: base.row.revision,\n revision: next.revision,\n baseWire: base.wire,\n nextWire\n });\n return { ok: true, value: token };\n}\n// A durable one-attempt marker, not a known refusal or a retry permission.\n// Lost unsigned revision1 remains uncertain; it can never be reset by this API.\nexport function preparePreferenceSigningTransition(\n record: PublicRecordHandle,\n owner: unknown,\n id: unknown\n): Result<PublicOperationTransition> {\n const base = baseOf(record, owner, id);\n if (\n !base ||\n base.row.family !== 'preference_operation' ||\n base.row.capture.kind !== 10050 ||\n base.row.revision !== 0 ||\n base.row.artifact !== null ||\n base.row.receipts.length !== 0\n )\n return failed('invalid_record');\n return retain(base, { ...base.row, revision: 1 });\n}\n// The acknowledged unsigned revision1 records an original listing attempt.\n// It cannot be reset into permission to prompt again after page/ack loss.\nexport function preparePublicListingSigningTransition(\n record: PublicRecordHandle,\n owner: unknown,\n id: unknown\n): Result<PublicOperationTransition> {\n const base = baseOf(record, owner, id);\n if (\n !base ||\n base.row.family !== 'public_operation' ||\n base.row.source.type !== 'draft' ||\n base.row.capture.kind !== 30402 ||\n base.row.revision !== 0 ||\n base.row.artifact !== null ||\n base.row.receipts.length !== 0\n )\n return failed('invalid_record');\n return retain(base, { ...base.row, revision: 1 });\n}\nexport function preparePublicArtifactTransition(\n record: PublicRecordHandle,\n owner: unknown,\n id: unknown,\n artifact: CapturedArtifact\n): Result<PublicOperationTransition> {\n const base = baseOf(record, owner, id),\n signed = artifacts.get(artifact);\n if (!base) return failed('invalid_record');\n if (\n !signed ||\n signed.author !== base.row.owner ||\n signed.kind !== base.row.capture.kind ||\n signed.hash !== base.row.capture.hash\n )\n return failed('invalid_artifact');\n if (base.row.artifact !== null)\n return base.row.artifact.wire === signed.wire\n ? retain(base, base.row)\n : failed('conflict');\n if (base.row.revision === Number.MAX_SAFE_INTEGER)\n return failed('revision_exhausted');\n return retain(base, {\n ...base.row,\n revision: base.row.revision + 1,\n artifact: { eventId: signed.hash, wire: signed.wire }\n });\n}\nfunction sameFact(a: PublicTargetReceipt, b: PublicTargetReceipt): boolean {\n return (\n a.actionId === b.actionId &&\n a.origin === b.origin &&\n a.readbackOrigin === b.readbackOrigin &&\n a.role === b.role &&\n a.attempt === b.attempt &&\n a.eventId === b.eventId &&\n a.status === b.status &&\n a.observedAtMilliseconds === b.observedAtMilliseconds\n );\n}\n// Only canonical primitive wire is acquired; defensive record decoding validates\n// every receipt field, target, role, event and exact readback signature. Distinct\n// status/time observations remain distinct. No EventStore seen metadata is used.\nexport function preparePublicReceiptTransition(\n record: PublicRecordHandle,\n owner: unknown,\n id: unknown,\n receiptWire: unknown\n): Result<PublicOperationTransition> {\n const base = baseOf(record, owner, id);\n if (\n !base ||\n !base.row.artifact ||\n typeof receiptWire !== 'string' ||\n !boundedUtf8(receiptWire, LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes)\n )\n return failed('invalid_record');\n try {\n const fact: unknown = JSON.parse(receiptWire);\n if (\n JSON.stringify(fact) !== receiptWire ||\n !(\n exactLocalFields(fact, [\n 'actionId',\n 'origin',\n 'role',\n 'attempt',\n 'eventId',\n 'status',\n 'observedAtMilliseconds',\n 'readbackWire'\n ]) ||\n (base.row.family === 'preference_operation' &&\n exactLocalFields(fact, [\n 'actionId',\n 'origin',\n 'role',\n 'attempt',\n 'eventId',\n 'status',\n 'observedAtMilliseconds',\n 'readbackWire',\n 'readbackOrigin'\n ]))\n )\n )\n return failed('invalid_record');\n // Validate the proposed fact through the existing complete typed codec before\n // comparing keys; the parsed object contains only detached JSON data.\n const checked = decodePublicRecord(\n JSON.stringify({ ...base.row, receipts: [fact] }),\n base.row.owner,\n base.row.id\n );\n if (!checked.ok) return failed('invalid_record');\n const admitted = publicRecordSnapshot(\n checked.value,\n base.row.owner,\n base.row.id\n );\n if (!admitted || admitted.family === 'public_draft')\n return failed('invalid_record');\n const nextFact = admitted.receipts[0];\n const existing = base.row.receipts.find((row) => sameFact(row, nextFact));\n if (existing)\n return JSON.stringify(existing) === JSON.stringify(nextFact)\n ? retain(base, base.row)\n : failed('conflict');\n if (base.row.revision === Number.MAX_SAFE_INTEGER)\n return failed('revision_exhausted');\n return retain(base, {\n ...base.row,\n revision: base.row.revision + 1,\n receipts: [...base.row.receipts, nextFact]\n });\n } catch {\n return failed('invalid_record');\n }\n}\n// Internal repository input: a detached snapshot of a genuine frozen command,\n// never a signing/network capability. Scope and full-wire CAS remain in IDB.\nexport function publicTransitionSnapshot(\n handle: PublicOperationTransition,\n owner: unknown,\n id: unknown\n): Transition | undefined {\n const saved = transitions.get(handle);\n return saved &&\n saved.owner === canonicalPublicKey(owner) &&\n saved.id === canonicalLocalId(id)\n ? { ...saved }\n : undefined;\n}\n// Metadata-only scope admission avoids accepting caller-owned record objects.\nexport function publicTransitionIdentity(\n handle: PublicOperationTransition\n): Readonly<{ owner: string; id: string }> | undefined {\n const saved = transitions.get(handle);\n return saved ? { owner: saved.owner, id: saved.id } : undefined;\n}\n", + sha256: '2ea4ccd624ec25890f009f29960a4d266d4dcae7d15e078759e7b4c70c65e9f3' + }, + 'src/lib/publishing/listing-operation-view.ts': { + source: + "import { canonicalLocalId } from '../private-handles.ts';\nimport {\n publicPublicationOwner,\n readPublicListingIntent,\n type PublicPublicationRepository\n} from '../persistence/public-publications.ts';\nimport { publicRecordSnapshot } from '../persistence/records.ts';\nimport {\n identitySessionSnapshot,\n subscribeIdentityInvalidation,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport {\n listingSigningSnapshot,\n subscribeListingSigning,\n type ListingSigning\n} from './sign-listing.ts';\nimport { inspectLocalTemplate } from '../nostr/local-template.ts';\nimport { projectFoodParts } from '../contracts/food-availability-v1/read.ts';\nimport type { PublicTargetReceipt } from '../contracts/local-records.ts';\nimport type { StatusCopy } from '../presentation/status-copy.ts';\n\ndeclare const viewBrand: unique symbol;\nexport type ListingOperationView = Readonly<{ [viewBrand]: true }>;\nexport type ListingOperationSnapshot = Readonly<{\n owner: string;\n command: string;\n revision: number;\n eventId: string;\n artifact: 'unsigned' | 'signed';\n state:\n | 'prepared'\n | 'signing'\n | 'partial'\n | 'accepted'\n | 'readback'\n | 'unknown'\n | 'needs-action';\n acceptanceCount: number;\n readbackCount: number;\n needsAction: boolean;\n localSource: 'retained-prototype' | 'read-only';\n summary: StatusCopy;\n targets: readonly Readonly<{\n origin: string;\n eventId: string;\n accepted: boolean;\n readback: 'confirmed' | 'not-observed';\n latestOutcome: PublicTargetReceipt['status'] | 'unattempted';\n receipts: readonly PublicTargetReceipt[];\n }>[];\n}>;\ntype View = Readonly<{\n wire: string;\n current(): boolean;\n retire(): void;\n subscribe(listener: () => void): () => void;\n}>;\nconst views = new WeakMap<ListingOperationView, View>();\nconst active = new WeakMap<\n PublicPublicationRepository,\n Map<string, Readonly<{ stamp: symbol; retire(): void }>>\n>();\n\n// This is account-local presentation only. Reading a retained operation grants\n// no sign, send, edit, current-head or relay qualification capability.\nexport async function readListingOperationView(\n repository: PublicPublicationRepository,\n identity: IdentitySession,\n command: unknown,\n signing?: ListingSigning\n): Promise<\n | Readonly<{ status: 'found'; view: ListingOperationView }>\n | Readonly<{ status: 'unavailable' }>\n> {\n const owner = publicPublicationOwner(repository),\n id = canonicalLocalId(command);\n const identityOwner = () => {\n const snapshot = identitySessionSnapshot(identity);\n return 'publicKey' in snapshot ? snapshot.publicKey : undefined;\n };\n if (!owner || !id || identityOwner() !== owner)\n return { status: 'unavailable' };\n const cache =\n active.get(repository) ??\n new Map<string, Readonly<{ stamp: symbol; retire(): void }>>();\n active.set(repository, cache);\n cache.get(id)?.retire();\n const stamp = Symbol(),\n listeners = new Map<symbol, () => void>();\n let alive = true,\n unsubscribe = () => {},\n unsubscribeSigning = () => {},\n observesSigning = false;\n function retire() {\n if (!alive) return;\n alive = false;\n unsubscribe();\n unsubscribeSigning();\n if (cache.get(id!)?.stamp === stamp) cache.delete(id!);\n for (const listener of listeners.values()) {\n try {\n listener();\n } catch {\n /* Presentation callbacks cannot retain original custody. */\n }\n }\n listeners.clear();\n }\n function current() {\n const live =\n observesSigning && signing ? listingSigningSnapshot(signing) : undefined;\n const originalSigningCurrent =\n !observesSigning ||\n !!(\n live &&\n live.signing &&\n !live.stopped &&\n live.owner === owner &&\n live.command === id\n );\n return (\n originalSigningCurrent &&\n alive &&\n cache.get(id!)?.stamp === stamp &&\n publicPublicationOwner(repository) === owner &&\n identityOwner() === owner\n );\n }\n cache.set(id, { stamp, retire });\n unsubscribe = subscribeIdentityInvalidation(identity, retire);\n try {\n const read = await readPublicListingIntent(repository, id);\n const row =\n read.status === 'found' && publicRecordSnapshot(read.record, owner, id);\n if (\n !current() ||\n !row ||\n row.family !== 'public_operation' ||\n row.capture.kind !== 30402 ||\n row.capture.targets.length === 0 ||\n (!row.artifact && (row.revision > 1 || row.receipts.length !== 0)) ||\n (row.artifact && row.revision < 2)\n ) {\n retire();\n return { status: 'unavailable' };\n }\n const template = inspectLocalTemplate(row.capture.wire, owner, 30402);\n if (!template || projectFoodParts(template).outcome !== 'focused') {\n retire();\n return { status: 'unavailable' };\n }\n const targets = row.capture.targets.map((origin) => {\n const receipts = row.receipts.filter(\n (receipt) =>\n receipt.origin === origin && receipt.eventId === row.capture.hash\n );\n return {\n origin,\n eventId: row.capture.hash,\n accepted: receipts.some((receipt) => receipt.status === 'accepted'),\n readback: receipts.some((receipt) => receipt.readbackWire !== null)\n ? ('confirmed' as const)\n : ('not-observed' as const),\n latestOutcome: receipts.at(-1)?.status ?? ('unattempted' as const),\n receipts\n };\n });\n const acceptanceCount = targets.filter((target) => target.accepted).length,\n readbackCount = targets.filter(\n (target) => target.readback === 'confirmed'\n ).length;\n const needsAction = targets.some((target) =>\n ['refused', 'timed_out', 'unknown', 'stopped'].includes(\n target.latestOutcome\n )\n );\n const live = signing && listingSigningSnapshot(signing);\n const genuinelySigning =\n live &&\n live.owner === owner &&\n live.command === id &&\n live.hash === row.capture.hash &&\n live.signing &&\n !live.stopped;\n const state: ListingOperationSnapshot['state'] = !row.artifact\n ? row.revision === 0\n ? 'prepared'\n : genuinelySigning\n ? 'signing'\n : 'unknown'\n : readbackCount === targets.length\n ? 'readback'\n : acceptanceCount === targets.length\n ? 'accepted'\n : acceptanceCount > 0 || readbackCount > 0\n ? 'partial'\n : targets.some(\n (target) =>\n target.latestOutcome === 'refused' ||\n target.latestOutcome === 'stopped'\n )\n ? 'needs-action'\n : row.receipts.length > 0\n ? 'unknown'\n : 'prepared';\n observesSigning = state === 'signing';\n if (observesSigning && signing)\n unsubscribeSigning = subscribeListingSigning(signing, retire);\n const text =\n state === 'signing'\n ? 'Waiting for your extension to sign the retained listing.'\n : state === 'unknown'\n ? 'The outcome is unknown. Keep the original listing operation for reconciliation.'\n : state === 'needs-action'\n ? 'Needs action. Keep the original listing operation and its recorded target outcomes.'\n : state === 'partial'\n ? 'Publication evidence is partial. Check the individual target outcomes.'\n : state === 'readback'\n ? 'Exact listing read-back is recorded for each frozen target.'\n : state === 'accepted'\n ? 'Each frozen target accepted this listing event. Exact read-back is recorded separately.'\n : row.artifact\n ? 'Signed listing saved in this browser. No relay acceptance is recorded.'\n : 'Saved in this browser. The retained listing has not been signed.';\n const snapshot: ListingOperationSnapshot = {\n owner,\n command: id,\n revision: row.revision,\n eventId: row.capture.hash,\n artifact: row.artifact ? 'signed' : 'unsigned',\n state,\n acceptanceCount,\n readbackCount,\n needsAction,\n localSource:\n row.artifact && row.source.type === 'draft'\n ? 'retained-prototype'\n : 'read-only',\n summary: {\n tone:\n needsAction || state === 'unknown' || state === 'partial'\n ? 'warning'\n : 'info',\n text\n },\n targets\n };\n if (!current()) {\n retire();\n return { status: 'unavailable' };\n }\n const view = Object.freeze({}) as ListingOperationView;\n views.set(view, {\n wire: JSON.stringify(snapshot),\n current,\n retire,\n subscribe(listener) {\n if (!current()) return () => {};\n const key = Symbol();\n listeners.set(key, listener);\n return () => {\n listeners.delete(key);\n };\n }\n });\n return { status: 'found', view };\n } catch {\n retire();\n return { status: 'unavailable' };\n }\n}\nexport function listingOperationSnapshot(\n token: ListingOperationView\n): ListingOperationSnapshot | undefined {\n const value = views.get(token);\n if (!value) return;\n if (!value.current()) {\n value.retire();\n return;\n }\n return JSON.parse(value.wire) as ListingOperationSnapshot;\n}\nexport function closeListingOperationView(token: ListingOperationView): void {\n views.get(token)?.retire();\n}\nexport function subscribeListingOperationView(\n token: ListingOperationView,\n listener: () => void\n): () => void {\n const value = views.get(token);\n if (!value?.current()) return () => {};\n return value.subscribe(listener);\n}\n", + sha256: '5f48bfb7056b56bd29357e605e20ef1375c559973fcc31f38d564a3b9eb07094' + }, + 'src/lib/components/OperationStatus.svelte': { + source: + "<script lang=\"ts\">\n import Notice from './Notice.svelte';\n import {\n listingOperationSnapshot,\n subscribeListingOperationView,\n type ListingOperationView\n } from '../publishing/listing-operation-view.ts';\n import {\n statusCopy,\n receiptCopy,\n type OperationFact,\n type TargetReceipt\n } from '../presentation/status-copy';\n let {\n fact = 'unknown',\n receipts = [],\n publicOperation\n }: {\n fact?: OperationFact;\n receipts?: readonly TargetReceipt[];\n publicOperation?: ListingOperationView;\n } = $props();\n let retired = $state(false);\n const publicSnapshot = $derived(\n publicOperation && !retired\n ? listingOperationSnapshot(publicOperation)\n : undefined\n );\n const summary = $derived(\n publicOperation\n ? (publicSnapshot?.summary ?? statusCopy('unknown'))\n : statusCopy(fact)\n );\n $effect(() => {\n retired = false;\n if (!publicOperation) return;\n return subscribeListingOperationView(publicOperation, () => {\n retired = true;\n });\n });\n</script>\n\n<div class=\"stack stack--tight\">\n <Notice tone={summary.tone} text={summary.text} />\n {#if publicSnapshot}\n <p>\n Relay acceptance recorded for {publicSnapshot.acceptanceCount} of {publicSnapshot\n .targets.length} targets.\n </p>\n <p>\n Exact read-back recorded for {publicSnapshot.readbackCount} of {publicSnapshot\n .targets.length} targets.\n </p>\n <p>\n {publicSnapshot.localSource === 'retained-prototype'\n ? 'Retained prototype source is available in this browser. Editing requires a separate current-head check.'\n : 'No supported retained prototype source is available for editing. Keep this listing read-only.'}\n </p>\n {#if publicSnapshot.needsAction}\n <Notice\n tone=\"warning\"\n text=\"Needs action. Earlier acceptance and exact read-back facts are preserved.\"\n />\n {/if}\n {#each publicSnapshot.targets as target (target.origin)}\n <div class=\"stack stack--tight\">\n <p class=\"key\">Event: {target.eventId} \u00b7 Target: {target.origin}</p>\n <p>\n {target.accepted\n ? 'Acceptance recorded for this event and target.'\n : 'No acceptance recorded for this event and target.'}\n </p>\n <p>\n {target.readback === 'confirmed'\n ? 'Exact read-back is confirmed for this event and target.'\n : 'Exact read-back was not observed for this event and target.'}\n </p>\n {#each target.receipts as receipt, index (index)}\n <p>\n Attempt {receipt.attempt} \u00b7 Recorded outcome: {receipt.status ===\n 'timed_out'\n ? 'timed out'\n : receipt.status}.\n </p>\n {/each}\n </div>\n {/each}\n {:else if !publicOperation}\n {#each receipts as receipt, index (index)}\n {@const copy = receiptCopy(receipt)}\n <div class=\"stack stack--tight\">\n <p class=\"key\">\n Event: {receipt.eventId} \u00b7 Target: {receipt.destination}\n </p>\n <Notice tone={copy.tone} text={copy.text} />\n <p>{copy.readback}</p>\n </div>\n {/each}\n {/if}\n</div>\n", + sha256: 'c6a1d741d16b577783e80b8f447cb959d5bf8b2d711cd5abcdc396be430a7472' + }, + 'src/lib/runtime/effect-ownership.ts': { + source: + "import { canonicalPublicKey } from '../contracts/public-key.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport {\n publicRecordSnapshot,\n publicRecordWire,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport {\n claimPublicOperation,\n loadPreferenceOperation,\n publicQuotaOwner,\n type PublicQuotaRepository,\n type PublicQuotaFailure\n} from '../persistence/quota.ts';\n\ndeclare const leaseBrand: unique symbol;\nexport type PublicEffectLease = Readonly<{ [leaseBrand]: true }>;\nexport type PublicEffectCapture = Readonly<{\n owner: string;\n session: symbol;\n current(): boolean;\n}>;\nexport type PublicEffectResult<T> =\n | Readonly<{ status: 'completed'; value: T }>\n | Readonly<{ status: 'unknown' | 'retained'; record: PublicRecordHandle }>\n | Readonly<{\n status:\n 'invalid' | 'unavailable' | 'busy' | 'stopped' | PublicQuotaFailure;\n }>;\ntype Authority = Readonly<{\n owner: string;\n id: string;\n recordWire: string;\n session: symbol;\n}>;\ntype State = 'active' | 'unknown' | 'stopped' | 'closed';\ntype JobResult<T> =\n | Readonly<{ status: 'settled'; value: T; current: boolean }>\n | Readonly<{ status: 'invalid' | 'busy' | 'stopped' | 'unknown' }>;\ntype Controller = {\n current(authority: Authority): boolean;\n call<T>(authority: Authority, work: () => Promise<T>): Promise<JobResult<T>>;\n mark(): boolean;\n stop(): void;\n snapshot(): Readonly<{\n state: State;\n pending: boolean;\n owner: string;\n id: string;\n hash: string;\n revision: number;\n }>;\n};\nconst leases = new WeakMap<PublicEffectLease, Controller>();\n\n// Lazy browser-only origin/author ownership. It coordinates this client, never\n// independent Nostr clients. Only transaction completion acknowledges a plan.\nexport async function runCapturedPublicEffect<T>(\n repository: PublicQuotaRepository,\n handle: PublicRecordHandle,\n expectedId: unknown,\n input: PublicEffectCapture,\n review: unknown,\n work: (lease: PublicEffectLease, stored: PublicRecordHandle) => Promise<T>\n): Promise<PublicEffectResult<T>> {\n try {\n const owner = canonicalPublicKey(input?.owner),\n id = canonicalLocalId(expectedId);\n const session = input?.session,\n fresh = input?.current;\n const row =\n owner && id ? publicRecordSnapshot(handle, owner, id) : undefined;\n const recordWire =\n owner && id ? publicRecordWire(handle, owner, id) : undefined;\n if (\n (review !== 'reviewed_captured_operation' &&\n review !== 'reviewed_prepared_listing_operation' &&\n review !== 'reviewed_prepared_preference_operation' &&\n review !== 'reviewed_stored_preference_retry') ||\n !owner ||\n !id ||\n !row ||\n !recordWire ||\n row.family === 'public_draft' ||\n row.revision !== 0 ||\n row.artifact !== null ||\n typeof session !== 'symbol' ||\n typeof fresh !== 'function' ||\n typeof work !== 'function'\n )\n return { status: 'invalid' };\n const listingMode = review === 'reviewed_prepared_listing_operation';\n const preferenceMode =\n review !== 'reviewed_captured_operation' && !listingMode;\n const storedRetry = review === 'reviewed_stored_preference_retry';\n if (\n listingMode &&\n (row.family !== 'public_operation' ||\n row.capture.kind !== 30402 ||\n row.source.type !== 'draft')\n )\n return { status: 'invalid' };\n if (\n preferenceMode &&\n (row.family !== 'preference_operation' || row.capture.kind !== 10050)\n )\n return { status: 'invalid' };\n if (typeof window === 'undefined' || !navigator.locks?.request)\n return { status: 'unavailable' };\n if (publicQuotaOwner(repository) !== owner)\n return { status: 'invalid_scope' };\n return await navigator.locks.request(\n 'harvestcircle:owner:' + owner,\n { mode: 'exclusive', ifAvailable: true },\n async (lock): Promise<PublicEffectResult<T>> => {\n if (!lock) return { status: 'busy' };\n if (!fresh()) return { status: 'stopped' };\n async function claimOriginal() {\n if (!storedRetry)\n return await claimPublicOperation(repository, id, handle);\n const loaded = await loadPreferenceOperation(repository, id);\n if (!loaded.ok) return loaded;\n const stored = publicRecordSnapshot(loaded.value, owner, id);\n if (\n stored?.family !== 'preference_operation' ||\n row?.family !== 'preference_operation' ||\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 { ok: false as const, reason: 'conflict' as const };\n return {\n ok: true as const,\n value: { state: 'existing' as const, record: loaded.value }\n };\n }\n const claimed = await claimOriginal();\n if (!claimed.ok)\n return claimed.reason === 'unknown_completion'\n ? { status: 'unknown', record: handle }\n : { status: claimed.reason };\n const original = claimed.value.record;\n if (storedRetry && claimed.value.state !== 'existing')\n return { status: 'unknown', record: original };\n if (claimed.value.state === 'existing') {\n const stored = publicRecordSnapshot(original, owner, id);\n const prepared =\n !storedRetry &&\n ((preferenceMode && stored?.family === 'preference_operation') ||\n (listingMode &&\n stored?.family === 'public_operation' &&\n stored.capture.kind === 30402 &&\n stored.source.type === 'draft')) &&\n stored.revision === 0 &&\n stored.artifact === null;\n const retry =\n storedRetry &&\n stored?.family === 'preference_operation' &&\n stored.revision >= 2 &&\n stored.artifact !== null;\n if (!prepared && !retry)\n return {\n status:\n stored &&\n stored.family !== 'public_draft' &&\n stored.artifact !== null\n ? 'retained'\n : 'unknown',\n record: original\n };\n }\n let phase: State = 'active',\n closed = false,\n accepting = true,\n started = false;\n let settlement: Promise<void> | null = null;\n function outstanding(): Promise<void> | null {\n return settlement;\n }\n function stop() {\n if (!closed) phase = started ? 'unknown' : 'stopped';\n }\n function current() {\n if (closed || phase !== 'active') return false;\n let valid = false;\n try {\n valid = publicQuotaOwner(repository) === owner && fresh() === true;\n } catch {\n /* finite stale result */\n }\n if (!valid) stop();\n return valid && !closed && phase === 'active';\n }\n function matches(authority: Authority) {\n return (\n authority.owner === owner &&\n authority.id === id &&\n authority.recordWire === recordWire &&\n authority.session === session\n );\n }\n const lease = Object.freeze({}) as PublicEffectLease;\n async function call<V>(\n authority: Authority,\n invoke: () => Promise<V>\n ): Promise<JobResult<V>> {\n if (\n storedRetry ||\n !matches(authority) ||\n typeof invoke !== 'function'\n )\n return { status: 'invalid' };\n if (!accepting || !current())\n return { status: phase === 'unknown' ? 'unknown' : 'stopped' };\n if (outstanding()) return { status: 'busy' };\n if (started) return { status: 'stopped' };\n // Reserve the whole SDK job before invoking even its synchronous prefix.\n // Callback return cannot release a forgotten/unsettled permission wait.\n let release = () => {};\n const held = new Promise<void>((resolve) => {\n release = resolve;\n });\n settlement = held;\n try {\n const value = await invoke();\n return { status: 'settled', value, current: current() };\n } catch {\n stop();\n return { status: phase === 'unknown' ? 'unknown' : 'stopped' };\n } finally {\n settlement = null;\n release();\n }\n }\n leases.set(lease, {\n current: (authority) => matches(authority) && current(),\n call,\n stop,\n mark() {\n if (storedRetry || started || !outstanding() || !current())\n return false;\n started = true;\n return true;\n },\n snapshot: () => ({\n state: phase,\n pending: outstanding() !== null,\n owner,\n id,\n hash: row.capture.hash,\n revision: row.revision\n })\n });\n try {\n if (!current()) return { status: 'stopped' };\n let value: T;\n try {\n value = await work(lease, original);\n } catch {\n stop();\n return {\n status: 'unknown',\n record: original\n };\n }\n accepting = false;\n const waiting = outstanding();\n if (waiting) {\n // An orphaned job may settle, but cannot acquire more SDK effects\n // or expose an artifact after the operation callback has returned.\n phase = 'unknown';\n await waiting;\n }\n if (!current())\n return phase === 'unknown'\n ? { status: 'unknown', record: original }\n : { status: 'stopped' };\n return { status: 'completed', value };\n } finally {\n accepting = false;\n const waiting = outstanding();\n if (waiting) await waiting;\n closed = true;\n if (phase === 'active') phase = 'closed';\n }\n }\n );\n } catch {\n return { status: 'unavailable' };\n }\n}\n// These internal mechanical ports expose neither a signer nor a raw template.\n// The adapter supplies its actual private session and genuine approval wire.\nexport function publicEffectLeaseCurrent(\n lease: PublicEffectLease,\n authority: Authority\n): boolean {\n return leases.get(lease)?.current(authority) ?? false;\n}\nexport function callOwnedExtension<T>(\n lease: PublicEffectLease,\n authority: Authority,\n work: () => Promise<T>\n): Promise<JobResult<T>> {\n return (\n leases.get(lease)?.call(authority, work) ??\n Promise.resolve({ status: 'invalid' })\n );\n}\nexport function markOwnedSignaturePending(lease: PublicEffectLease): boolean {\n return leases.get(lease)?.mark() ?? false;\n}\nexport function stopPublicEffect(lease: PublicEffectLease): void {\n leases.get(lease)?.stop();\n}\nexport function publicEffectSnapshot(lease: PublicEffectLease) {\n return leases.get(lease)?.snapshot();\n}\n", + sha256: '28e09d9f8143c1bc1e66e1f2531acd64bd786a6f35ead1d10ac646b0356f7a1f' + }, + 'src/lib/nostr/public-pool.ts': { + source: + "import { createScopedRelayPool } from './pool-factory.ts';\nimport { deploymentRelayPolicy } from '../config/deployment-relays.ts';\nimport {\n publicRelayTargets,\n readRelayPolicy,\n type RelayPolicy\n} from '../config/relays.ts';\nimport type { PublicFilter, PublicPoolMessage } from './exports.ts';\nimport { requireNip50Source } from './search-sources.ts';\nimport {\n takePreferencePublication,\n type PreferencePublication\n} from './inbox-preference-publication.ts';\nimport {\n takeListingPublication,\n type ListingAttemptPermission\n} from './listing-publisher.ts';\nimport {\n verifyEnvelope,\n verifiedEnvelopeSnapshot\n} from './verified-envelope.ts';\nexport type ListingReadbackResult =\n | Readonly<{ status: 'found'; wire: string }>\n | Readonly<{ status: 'missing' | 'unknown' | 'stopped' }>;\nexport type PreferenceAttemptResult = Readonly<{\n status: 'accepted' | 'refused' | 'timed_out' | 'unknown' | 'stopped';\n}>;\n\ndeclare const ownedPool: unique symbol;\nexport type PublicPool = Readonly<{ readonly [ownedPool]: true }>;\ninterface Owner {\n readonly policy: RelayPolicy;\n readonly token: PublicPool;\n readonly origins: readonly string[];\n readonly closed: () => boolean;\n readonly subscribe: (\n filters: readonly PublicFilter[],\n onMessage: (message: PublicPoolMessage) => void,\n sampleSource?: string\n ) => () => void;\n readonly close: () => void;\n readonly preference: (\n permission: PreferencePublication,\n origin: string,\n signal: AbortSignal,\n remaining: number\n ) => Promise<PreferenceAttemptResult>;\n readonly listing: (\n permission: ListingAttemptPermission,\n origin: string,\n signal: AbortSignal,\n remaining: number\n ) => Promise<PreferenceAttemptResult>;\n readonly readListing: (\n permission: ListingAttemptPermission,\n origin: string,\n signal: AbortSignal,\n remaining: number\n ) => Promise<ListingReadbackResult>;\n}\nconst owners = new WeakMap<PublicPool, Owner>();\nlet lifetime: Owner | undefined;\n\n// Anonymous state exists only after browser acquisition. No socket, information\n// fetch, identity or extension operation occurs during import or SSR.\nexport function getPublicPool(\n policy: RelayPolicy = deploymentRelayPolicy\n): PublicPool | undefined {\n if (typeof window === 'undefined') return undefined;\n readRelayPolicy(policy);\n if (lifetime) {\n if (lifetime.closed()) throw new Error('public_pool_closed');\n if (lifetime.policy !== policy)\n throw new Error('public_pool_policy_changed');\n return lifetime.token;\n }\n const token = Object.freeze({}) as PublicPool;\n const origins = publicRelayTargets(policy, 'read');\n const sdk = createScopedRelayPool();\n const active = new Map<() => void, true>();\n let closed = false;\n let cleanupComplete = false;\n let publicationCleanupRequired = false;\n const owner: Owner = {\n policy,\n token,\n origins,\n closed: () => closed,\n async preference(permission, origin, signal, remaining) {\n const admitted = takePreferencePublication(permission, policy, origin);\n if (\n closed ||\n publicationCleanupRequired ||\n !admitted ||\n signal.aborted ||\n !Number.isFinite(remaining) ||\n remaining <= 0 ||\n remaining > 45000\n )\n return { status: 'stopped' };\n return await new Promise<PreferenceAttemptResult>((resolve) => {\n let ended = false;\n let release = () => {};\n let fenceTimer: ReturnType<typeof setTimeout> | undefined;\n function finish(status: PreferenceAttemptResult['status']) {\n if (ended) return;\n ended = true;\n clearTimeout(timer);\n if (fenceTimer !== undefined) clearTimeout(fenceTimer);\n signal.removeEventListener('abort', stopped);\n try {\n release();\n } catch {\n publicationCleanupRequired = true;\n status = 'unknown';\n }\n resolve({ status });\n }\n function stopped() {\n if (ended) {\n release();\n return;\n }\n finish('stopped');\n }\n function fence() {\n if (ended) return;\n if (closed || signal.aborted || !admitted!.current()) {\n finish('stopped');\n return;\n }\n fenceTimer = setTimeout(() => fence(), 50);\n }\n signal.addEventListener('abort', stopped, { once: true });\n // Arm our finite deadline before subscribing. The SDK uses the same\n // response shape for its timer and a relay refusal saying \"Timeout\";\n // only this owned deadline supplies retryable timeout evidence.\n const relay = sdk.relay(origin);\n const timeout =\n Number.isFinite(relay.eventTimeout) && relay.eventTimeout > 0\n ? Math.min(remaining, relay.eventTimeout)\n : remaining;\n const timer = setTimeout(() => finish('timed_out'), timeout);\n try {\n if (!admitted.current() || signal.aborted) {\n finish('stopped');\n return;\n }\n // This SDK invocation is an attempted effect. Stop cannot reverse an\n // already emitted/buffered EVENT, but teardown schedules no new one.\n const subscription = relay.event(admitted.event, 'EVENT').subscribe({\n next(response) {\n if (ended) return;\n if (\n (response.from !== origin && response.from !== origin + '/') ||\n typeof response.ok !== 'boolean'\n ) {\n finish('unknown');\n return;\n }\n if (response.ok) finish('accepted');\n else if (response.message === 'Timeout') finish('unknown');\n else if (\n typeof response.message === 'string' &&\n response.message.startsWith('auth-required:')\n )\n finish('unknown');\n else finish('refused');\n },\n error: () => finish('unknown'),\n complete: () => {\n if (!ended) finish('unknown');\n }\n });\n const stop = () => {\n subscription.unsubscribe();\n active.delete(stop);\n };\n release = () => {\n stop();\n active.delete(stopped);\n };\n active.set(stopped, true);\n if (ended) {\n try {\n release();\n } catch {\n publicationCleanupRequired = true;\n }\n } else {\n fence();\n }\n } catch {\n finish('unknown');\n }\n });\n },\n async listing(permission, origin, signal, remaining) {\n const admitted = takeListingPublication(\n permission,\n policy,\n origin,\n 'publish'\n );\n if (\n closed ||\n publicationCleanupRequired ||\n !admitted ||\n signal.aborted ||\n !Number.isFinite(remaining) ||\n remaining <= 0 ||\n remaining > 45000\n )\n return { status: 'stopped' };\n return await new Promise<PreferenceAttemptResult>((resolve) => {\n let ended = false;\n let release = () => {};\n let fenceTimer: ReturnType<typeof setTimeout> | undefined;\n function finish(status: PreferenceAttemptResult['status']) {\n if (ended) return;\n ended = true;\n clearTimeout(timer);\n if (fenceTimer !== undefined) clearTimeout(fenceTimer);\n signal.removeEventListener('abort', stopped);\n try {\n release();\n } catch {\n publicationCleanupRequired = true;\n status = 'unknown';\n }\n resolve({ status });\n }\n function stopped() {\n if (ended) {\n release();\n return;\n }\n finish('stopped');\n }\n function fence() {\n if (ended) return;\n if (closed || signal.aborted || !admitted!.current()) {\n finish('stopped');\n return;\n }\n fenceTimer = setTimeout(() => fence(), 50);\n }\n signal.addEventListener('abort', stopped, { once: true });\n // Arm our finite deadline before subscribing. The SDK uses the same\n // response shape for its timer and a relay refusal saying \"Timeout\";\n // only this owned deadline supplies retryable timeout evidence.\n const relay = sdk.relay(origin);\n const timeout =\n Number.isFinite(relay.eventTimeout) && relay.eventTimeout > 0\n ? Math.min(remaining, relay.eventTimeout)\n : remaining;\n const timer = setTimeout(() => finish('timed_out'), timeout);\n try {\n if (!admitted.current() || signal.aborted) {\n finish('stopped');\n return;\n }\n // This SDK invocation is an attempted effect. Stop cannot reverse an\n // already emitted/buffered EVENT, but teardown schedules no new one.\n const subscription = relay.event(admitted.event, 'EVENT').subscribe({\n next(response) {\n if (ended) return;\n if (\n (response.from !== origin && response.from !== origin + '/') ||\n typeof response.ok !== 'boolean'\n ) {\n finish('unknown');\n return;\n }\n if (response.ok) finish('accepted');\n else if (response.message === 'Timeout') finish('unknown');\n else if (\n typeof response.message === 'string' &&\n response.message.startsWith('auth-required:')\n )\n finish('unknown');\n else finish('refused');\n },\n error: () => finish('unknown'),\n complete: () => {\n if (!ended) finish('unknown');\n }\n });\n const stop = () => {\n subscription.unsubscribe();\n active.delete(stop);\n };\n release = () => {\n stop();\n active.delete(stopped);\n };\n active.set(stopped, true);\n if (ended) {\n try {\n release();\n } catch {\n publicationCleanupRequired = true;\n }\n } else {\n fence();\n }\n } catch {\n finish('unknown');\n }\n });\n },\n async readListing(permission, origin, signal, remaining) {\n const admitted = takeListingPublication(\n permission,\n policy,\n origin,\n 'readback'\n );\n if (\n closed ||\n publicationCleanupRequired ||\n !admitted ||\n signal.aborted ||\n !Number.isFinite(remaining) ||\n remaining <= 0 ||\n remaining > 45000\n )\n return { status: 'stopped' };\n return await new Promise<ListingReadbackResult>((resolve) => {\n let ended = false,\n release = () => {};\n let fenceTimer: ReturnType<typeof setTimeout> | undefined;\n function finish(result: ListingReadbackResult) {\n if (ended) return;\n ended = true;\n clearTimeout(timer);\n if (fenceTimer !== undefined) clearTimeout(fenceTimer);\n signal.removeEventListener('abort', stopped);\n try {\n release();\n } catch {\n publicationCleanupRequired = true;\n result = { status: 'unknown' };\n }\n resolve(result);\n }\n function stopped() {\n finish({ status: 'stopped' });\n }\n function fence() {\n if (ended) return;\n if (closed || signal.aborted || !admitted!.current()) {\n stopped();\n return;\n }\n fenceTimer = setTimeout(fence, 50);\n }\n const timer = setTimeout(\n () => finish({ status: 'unknown' }),\n remaining\n );\n signal.addEventListener('abort', stopped, { once: true });\n try {\n if (!admitted.current() || signal.aborted) {\n stopped();\n return;\n }\n const expected = admitted.event;\n // Exact frozen target and ID only. No generic filter/relay/request API.\n const subscription = sdk\n .req(\n [origin],\n [\n {\n ids: [expected.id],\n authors: [expected.pubkey],\n kinds: [30402],\n limit: 1\n }\n ],\n { waitForAuth: false, reconnect: false, resubscribe: false }\n )\n .subscribe({\n next(message) {\n if (\n ended ||\n (message.from !== origin && message.from !== origin + '/')\n )\n return;\n if (message.type === 'EOSE') {\n finish({ status: 'missing' });\n return;\n }\n if (message.type !== 'EVENT' || !admitted.current()) return;\n const checked = verifyEnvelope(JSON.stringify(message.event));\n const observed =\n checked.ok && verifiedEnvelopeSnapshot(checked.value);\n const fields = (event: typeof expected) =>\n JSON.stringify([\n event.id,\n event.pubkey,\n event.created_at,\n event.kind,\n event.tags,\n event.content,\n event.sig\n ]);\n if (observed && fields(observed) === fields(expected))\n // SDK object ingress is independently verified signed fields,\n // not a claim to preserve the relay's original JSON encoding.\n finish({ status: 'found', wire: admitted.wire });\n },\n error: () => finish({ status: 'unknown' }),\n complete: () => {\n if (!ended) finish({ status: 'missing' });\n }\n });\n release = () => {\n subscription.unsubscribe();\n active.delete(stopped);\n };\n active.set(stopped, true);\n if (ended) release();\n else fence();\n } catch {\n finish({ status: 'unknown' });\n }\n });\n },\n subscribe(filters, onMessage, sampleSource) {\n if (closed) throw new Error('public_pool_closed');\n let release = () => {};\n const subscription = sdk\n .req(\n sampleSource === undefined\n ? [...origins]\n : [requireNip50Source(policy, sampleSource)],\n [...filters],\n {\n waitForAuth: false,\n reconnect: false,\n resubscribe: false\n }\n )\n .subscribe({\n next: (message) => {\n if (!closed) onMessage(message);\n },\n complete: () => release(),\n error: () => release()\n });\n const stop = () => {\n try {\n subscription.unsubscribe();\n } finally {\n active.delete(stop);\n }\n };\n release = stop;\n if (closed) stop();\n else if (!subscription.closed) active.set(stop, true);\n return stop;\n },\n close() {\n if (cleanupComplete) return;\n closed = true;\n let failed = false;\n for (const stop of active.keys()) {\n try {\n stop();\n } catch {\n failed = true;\n }\n }\n try {\n sdk.close();\n } catch {\n failed = true;\n }\n cleanupComplete = !failed && active.size === 0;\n if (!cleanupComplete) throw new Error('public_pool_close_failed');\n }\n };\n owners.set(token, owner);\n lifetime = owner;\n return token;\n}\n\nfunction ownerOf(token: PublicPool): Owner {\n const owner = owners.get(token);\n if (!owner) throw new Error('public_pool_invalid');\n return owner;\n}\nexport function publicPoolOrigins(token: PublicPool): readonly string[] {\n return [...ownerOf(token).origins];\n}\n\n// Filter construction and event verification/work budgets have separate owners.\n// Accept no SDK filter callback (which would expose a raw relay), arbitrary\n// destination, AUTH method, information fetch or retry option through this API.\nexport function subscribePublicPool(\n token: PublicPool,\n filters: readonly PublicFilter[],\n onMessage: (message: PublicPoolMessage) => void,\n sampleSource?: string\n): () => void {\n const owner = ownerOf(token);\n if (owner.closed()) throw new Error('public_pool_closed');\n if (\n !Array.isArray(filters) ||\n filters.length === 0 ||\n filters.some(\n (filter) => !filter || typeof filter !== 'object' || Array.isArray(filter)\n )\n )\n throw new Error('public_pool_filters_invalid');\n if (sampleSource !== undefined)\n requireNip50Source(owner.policy, sampleSource);\n if (\n sampleSource === undefined &&\n filters.some((filter) => 'search' in filter)\n )\n throw new Error('public_pool_search_requires_source');\n return owner.subscribe(filters, onMessage, sampleSource);\n}\n\n// Terminal browser-lifetime shutdown: cancel request controls before closing the\n// SDK sockets and its keepalive/reconnect watchers. Routes cannot recreate it.\nexport function closePublicPool(token: PublicPool): void {\n ownerOf(token).close();\n}\n// Narrow once-only preference capability; no raw event, arbitrary SDK options,\n// AUTH or general UI publisher. Pool remains the anonymous lifetime owner.\nexport function publishPublicPreferenceAttempt(\n token: PublicPool,\n permission: PreferencePublication,\n policy: RelayPolicy,\n origin: string,\n signal: AbortSignal,\n remaining: number\n): Promise<PreferenceAttemptResult> {\n try {\n const owner = ownerOf(token);\n if (owner.policy !== policy) return Promise.resolve({ status: 'stopped' });\n return owner.preference(permission, origin, signal, remaining);\n } catch {\n return Promise.resolve({ status: 'unknown' });\n }\n}\n// Listing and preference permissions stay separate despite the shared SDK owner.\nexport function publishPublicListingAttempt(\n token: PublicPool,\n permission: ListingAttemptPermission,\n policy: RelayPolicy,\n origin: string,\n signal: AbortSignal,\n remaining: number\n): Promise<PreferenceAttemptResult> {\n try {\n const owner = ownerOf(token);\n if (owner.policy !== policy) return Promise.resolve({ status: 'stopped' });\n return owner.listing(permission, origin, signal, remaining);\n } catch {\n return Promise.resolve({ status: 'unknown' });\n }\n}\nexport function readPublicListingExactAttempt(\n token: PublicPool,\n permission: ListingAttemptPermission,\n policy: RelayPolicy,\n origin: string,\n signal: AbortSignal,\n remaining: number\n): Promise<ListingReadbackResult> {\n try {\n const owner = ownerOf(token);\n if (owner.policy !== policy) return Promise.resolve({ status: 'stopped' });\n return owner.readListing(permission, origin, signal, remaining);\n } catch {\n return Promise.resolve({ status: 'unknown' });\n }\n}\n", + sha256: 'd08c2c16936125e75a8195cfdc600f8c592cb942e1802d934823ee221c1c132b' + }, + 'src/lib/persistence/public-receipts.ts': { + source: + "import {\n publicRecordSnapshot,\n publicRecordWire,\n type PublicRecordHandle\n} from './records.ts';\nimport {\n preparePublicReceiptTransition,\n publicTransitionSnapshot\n} from './artifact-records.ts';\nimport {\n publicPublicationOwner,\n publicPublicationQuotaRepository,\n readPublicListingIntent,\n type PublicPublicationRepository\n} from './public-publications.ts';\nimport {\n commitPublicOperationTransition,\n observePublicOperationTransition\n} from './quota.ts';\nexport type PublicListingReceiptResult =\n | Readonly<{ status: 'saved'; record: PublicRecordHandle }>\n | Readonly<{ status: 'invalid' | 'conflict' | 'unknown' | 'unavailable' }>;\n// Exact full-wire CAS append. A request success or detached cached observation\n// cannot acknowledge a receipt. Unknown native commits retain original payload.\nexport async function commitPublicListingReceipt(\n repository: PublicPublicationRepository,\n record: PublicRecordHandle,\n command: string,\n receiptWire: string\n): Promise<PublicListingReceiptResult> {\n try {\n const owner = publicPublicationOwner(repository),\n quota = publicPublicationQuotaRepository(repository);\n const row = owner\n ? publicRecordSnapshot(record, owner, command)\n : undefined;\n if (\n !owner ||\n !quota ||\n row?.family !== 'public_operation' ||\n row.capture.kind !== 30402 ||\n !row.artifact\n )\n return { status: 'invalid' };\n const transition = preparePublicReceiptTransition(\n record,\n owner,\n command,\n receiptWire\n );\n if (!transition.ok) return { status: 'invalid' };\n const expected = publicTransitionSnapshot(transition.value, owner, command);\n if (!expected) return { status: 'invalid' };\n const saved = await commitPublicOperationTransition(\n quota,\n transition.value\n );\n if (!saved.ok) {\n if (saved.reason !== 'unknown_completion')\n return {\n status: saved.reason === 'conflict' ? 'conflict' : 'unavailable'\n };\n const observed = await observePublicOperationTransition(\n quota,\n transition.value\n );\n if (observed.state !== 'committed')\n return {\n status: observed.state === 'conflict' ? 'conflict' : 'unknown'\n };\n }\n const read = await readPublicListingIntent(repository, command);\n if (read.status !== 'found') return { status: 'unknown' };\n if (publicRecordWire(read.record, owner, command) !== expected.nextWire)\n return { status: 'conflict' };\n return { status: 'saved', record: read.record };\n } catch {\n return { status: 'unknown' };\n }\n}\n", + sha256: '0b88e68b963e2052f29df9013378af56e8a0013415e52619dfbf36f7daa593c7' + } + }; /** @param {string} web */ async function restoreHistoricalPublicProducers(web) { - for (const [name, value] of Object.entries( - historicalPublicProducerClosure - )) { + for (const [name, value] of Object.entries({ + ...historicalPublicProducerClosure, + ...historicalWithdrawalProducerClosure + })) { assert.equal( createHash('sha256').update(value.source).digest('hex'), value.sha256 @@ -1387,7 +1426,15 @@ import { auditOutput } from '../../tools/check-output.mjs'; 'src/lib/publishing/revise-listing.ts', 'src/lib/publishing/mark-sold.ts', 'src/lib/components/ConfirmPanel.svelte', - 'src/lib/nostr/listing-publisher.ts' + 'src/lib/nostr/listing-publisher.ts', + 'src/lib/publishing/withdraw-listing.ts', + 'src/lib/publishing/sign-listing.ts', + 'src/lib/persistence/artifact-records.ts', + 'src/lib/publishing/listing-operation-view.ts', + 'src/lib/components/OperationStatus.svelte', + 'src/lib/runtime/effect-ownership.ts', + 'src/lib/nostr/public-pool.ts', + 'src/lib/persistence/public-receipts.ts' ]) { await check( 'listing editor rejects changed owned producer ' + producer, diff --git a/web/tests/unit/withdraw-listing.test.ts b/web/tests/unit/withdraw-listing.test.ts @@ -0,0 +1,63 @@ +import { expect, test } from 'vitest'; +import { reviewOwnedWithdrawal } from '../../src/lib/publishing/withdraw-listing.ts'; +import type { OwnedEditSource } from '../../src/lib/publishing/edit-source.ts'; +import type { PublicDraftController } from '../../src/lib/publishing/draft-controller.ts'; +import { makeFixture } from '../e2e/harness/approved-signing.ts'; +import { runCapturedPublicEffect } from '../../src/lib/runtime/effect-ownership.ts'; +import type { PublicQuotaRepository } from '../../src/lib/persistence/quota.ts'; + +for (const source of [undefined, null, {}, { owner: 'copied' }]) + test(`withdrawal cannot acquire source custody from ${JSON.stringify(source)}`, async () => { + const result = await reviewOwnedWithdrawal( + source as OwnedEditSource, + {} as PublicDraftController, + '00000000-0000-4000-8000-000000000120', + 'reviewed_owned_withdrawal' + ); + expect(result).toEqual({ status: 'blocked', reason: 'invalid_scope' }); + }); + +for (const kind of [30402, 5, 10050] as const) + test(`withdrawal signing mode admits only linked kind5 and never invokes SSR effects (${kind})`, async () => { + const fixture = makeFixture(kind); + let calls = 0; + try { + const result = await runCapturedPublicEffect( + {} as PublicQuotaRepository, + fixture.record, + fixture.id, + { owner: fixture.owner, session: Symbol(), current: () => true }, + 'reviewed_prepared_withdrawal_operation', + () => { + calls++; + return Promise.resolve(); + } + ); + expect(result.status).toBe(kind === 5 ? 'unavailable' : 'invalid'); + expect(calls).toBe(0); + } finally { + fixture.close(); + } + }); + +test('linked removal cannot enter the prepared ordinary-listing signing mode', async () => { + const fixture = makeFixture(5); + let calls = 0; + try { + const result = await runCapturedPublicEffect( + {} as PublicQuotaRepository, + fixture.record, + fixture.id, + { owner: fixture.owner, session: Symbol(), current: () => true }, + 'reviewed_prepared_listing_operation', + () => { + calls++; + return Promise.resolve(); + } + ); + expect(result.status).toBe('invalid'); + expect(calls).toBe(0); + } finally { + fixture.close(); + } +}); diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs @@ -498,7 +498,8 @@ async function productPresentationAdmission(web) { createHash('sha256').update(bytes).digest('hex') !== pin && !( name === 'src/lib/runtime/public-runtime.ts' && - (await listingEditorAdmission(web)) === 'owned-revision' + ((await listingEditorAdmission(web)) === 'owned-revision' || + (await listingEditorAdmission(web)) === 'owned-withdrawal') ) ) throw new Error('Invalid owned product presentation source'); @@ -551,7 +552,13 @@ async function preferencePublicationAdmission(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/nostr/public-pool.ts' && + (await listingEditorAdmission(web)) === 'owned-withdrawal' + ) + ) throw new Error('Invalid owned preference publication source'); } return true; @@ -584,8 +591,15 @@ async function listingPublicationAdmission(web) { if ( createHash('sha256').update(bytes).digest('hex') !== pin && !( - name === 'src/lib/nostr/listing-publisher.ts' && - (await listingEditorAdmission(web)) === 'owned-revision' + (name === 'src/lib/nostr/listing-publisher.ts' && + (await listingEditorAdmission(web)) === 'owned-revision') || + ([ + 'src/lib/nostr/listing-publisher.ts', + 'src/lib/publishing/sign-listing.ts', + 'src/lib/publishing/listing-operation-view.ts', + 'src/lib/components/OperationStatus.svelte' + ].includes(name) && + (await listingEditorAdmission(web)) === 'owned-withdrawal') ) ) throw new Error('Invalid owned listing publication source'); @@ -711,6 +725,61 @@ async function listingEditorAdmission(web) { 'src/lib/nostr/listing-publisher.ts': '1d7e1f99fe393626a3dda6796867be0d52ce4bcd064c185c9f4b3a24290183e2' }; + /** @type {Record<string,string>} */ + const withdrawalProducers = { + 'src/routes/sell/+page.svelte': + '97f22f9a0309621e9acb5f1b328d3376bc9c5affbe5a7ea1b85ece76097b9c08', + 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte': + '1df59a753fbef2bc2ebf77890a79cbd3d7a5bb0dcef34c219df1b5e8043cf787', + 'src/routes/products/[naddr=naddr]/edit/+page.svelte': + '09c3a6bde766045319cd36a00a82ca565f9f3b5cd5322982be9482836f312998', + 'src/lib/components/ListingEditor.svelte': + '060f4863f6f4f2a4fb1471bb0d5eeedf31ab13b5c83d894f47757cf5a68099e6', + 'src/lib/publishing/listing-editor.ts': + 'fe067bc1609f783aeee8ad5a0f3178cff50cae81085377b2bbec7874b5f4349d', + 'src/lib/components/ListingReview.svelte': + 'deee41ca6c60b346afc7ed5e62e3101ee03b04fdd2a9aa8fa3f3dec585e3863b', + 'src/lib/publishing/editor-workflow.ts': + 'c87e4f46793fd9beeedb5027cdbb06d533cf7e5df7378c030355c4608738e0f6', + 'src/lib/components/ConflictNotice.svelte': + 'f0a71cab9e8f1f12a3421402e3bc3b2f96c2ddb35ad8949c6e9599b850c3a17c', + 'src/lib/publishing/edit-source.ts': + '1432a8ada3d822cc9f634d40a7847a4d6d02c202ecfe59a9634543d57202f56b', + 'src/lib/publishing/prepare-listing.ts': + '00b922e8b0bfc73cf5ac59857472e8dd627c8df62d28f1c646c5d7c76ce5ede9', + 'src/lib/publishing/new-listing-readiness.ts': + 'ba76be4d7309b1a6beb0c8e0f19b89f2595049e94709486b79eff38953e68893', + 'src/lib/runtime/public-runtime.ts': + '8d2b840e94448b55642b1481d12785ed76d326735a4461e9795f57a98e8d2530', + 'src/lib/persistence/public-publications.ts': + 'be99c4114fb32880e0a9b48ab3593645532853fb4166fb506f398416db41a194', + 'src/lib/persistence/quota.ts': + 'e261a7c9c81d0685021663639b1bb543192e65580edb64fa58ccbb9a4a04cc95', + 'src/lib/publishing/revise-listing.ts': + '1f03d43f460feb12a02489226131ec2f7b95df5f534fcbb0b49ccc686a1b0c06', + 'src/lib/publishing/mark-sold.ts': + '80beaf8ad38b396154d5556e50e2cf5cd9f327bcdbc05f0db1ce190bf29f7234', + 'src/lib/components/ConfirmPanel.svelte': + '9e25745303bdf408a14df5153a28e9579bfa019ab083225acb7d874e93a17d59', + 'src/lib/nostr/listing-publisher.ts': + '10032c32482a766158d8a69027056e6a822a16b5f68ab9754b0f1cf42d0608f9', + 'src/lib/publishing/withdraw-listing.ts': + '168064a7ce271f8342c7b7cbbf996bd96f8968e405eee0bb3e3dba1bdaf346fb', + 'src/lib/publishing/sign-listing.ts': + 'a1c123c40a190699b57378c5569fcbbfbc5e23ab4d4c0df499ca40ff82fe1a10', + 'src/lib/persistence/artifact-records.ts': + 'e3b235c5aaf19558b557feb6e17a35b2b1de39c1aa49cb2ef14084d670138d16', + 'src/lib/publishing/listing-operation-view.ts': + '07f94625c0231a62f25c1db98c9459f8939c32505453633b58d2f72a894858ce', + 'src/lib/components/OperationStatus.svelte': + 'ca3a007899996f6331fadd2ead4c55dc7116c273626ecd2f36bcd4701065ae5f', + 'src/lib/runtime/effect-ownership.ts': + 'a181d1fa8b18d45b3e143de19af4dfdaab91779ac44df972d22e7fada645778b', + 'src/lib/nostr/public-pool.ts': + '220b0b9ca0cea20c1a2e1a08a82fc4b68a1ba4dd6ffff1f45154b54735233806', + 'src/lib/persistence/public-receipts.ts': + '10743a9d855c4f573eb42ca90a13c550dee9620e4ad3aac322858c696152e564' + }; let historical = true, current = true, reviewed = true, @@ -778,6 +847,17 @@ async function listingEditorAdmission(web) { revisionProducers[name]; } } + let withdrawing = publicText( + await readOwned(web, 'src/lib/components/ListingEditor.svelte') + ).includes('Request removal'); + if (withdrawing) + for (const [name, pin] of Object.entries(withdrawalProducers)) { + const bytes = await readOwned(web, name); + publicText(bytes); + withdrawing = + withdrawing && createHash('sha256').update(bytes).digest('hex') === pin; + } + if (withdrawing) return 'owned-withdrawal'; if (revising) return 'owned-revision'; if (editing) return 'edit-source'; if (!historical && !current && !reviewed) @@ -979,7 +1059,9 @@ export async function auditOutput(webDirectory) { const hasListingEditor = hasFullRoutes && (await listingEditorAdmission(web)); if (hasListingEditor && !(hasListingPublication && hasInboxSetup)) throw new Error('Invalid owned listing editor runtime authority'); - const hasListingRevision = hasListingEditor === 'owned-revision'; + const hasListingRevision = + hasListingEditor === 'owned-revision' || + hasListingEditor === 'owned-withdrawal'; const hasListingEdit = hasListingEditor === 'edit-source' || hasListingRevision; const hasListingReview = hasListingEditor === 'review' || hasListingEdit;