commit e2ed160a423dfb35d398a8524a2bb27403dc911a
parent d2657a801556df07e16b046142a0dc7a42f8d6aa
Author: triesap <tyson@radroots.org>
Date: Sat, 10 Oct 2026 14:06:05 +0000
publishing: resolve owned source and conflicting revisions (HCP-118)
Diffstat:
9 files changed, 1332 insertions(+), 151 deletions(-)
diff --git a/web/src/lib/components/ConflictNotice.svelte b/web/src/lib/components/ConflictNotice.svelte
@@ -0,0 +1,112 @@
+<script lang="ts">
+ /* global setInterval, clearInterval */
+ import { onMount } from 'svelte';
+ import Notice from './Notice.svelte';
+ import {
+ ownedEditSourceSnapshot,
+ type OwnedEditSource
+ } from '../publishing/edit-source.ts';
+ import type { PublicDraftForm } from '../contracts/local-records.ts';
+ let {
+ source,
+ proposed
+ }: { source: OwnedEditSource; proposed?: PublicDraftForm } = $props();
+ let observed = $derived(ownedEditSourceSnapshot(source));
+ onMount(() => {
+ // Observe existing bounded request state; this does not open new lookups.
+ const timer = setInterval(() => {
+ observed = ownedEditSourceSnapshot(source);
+ }, 250);
+ return () => clearInterval(timer);
+ });
+ const conflict = $derived(
+ observed?.status === 'conflict' || observed?.status === 'withdrawn'
+ );
+</script>
+
+{#if observed && conflict}
+ <section class="stack" aria-label="Current and proposed listing">
+ <Notice
+ tone="warning"
+ text="This listing changed elsewhere. Review the latest version before publishing."
+ />
+ <p>
+ Your proposed changes remain local. These versions have not been merged.
+ </p>
+ <h2>Current listing</h2>
+ {#if observed.current}
+ <dl class="stack">
+ <div>
+ <dt>Product name</dt>
+ <dd>{observed.current.title}</dd>
+ </div>
+ <div>
+ <dt>Full public description</dt>
+ <dd class="description">{observed.current.content}</dd>
+ </div>
+ <div>
+ <dt>Public area</dt>
+ <dd>{observed.current.location}</dd>
+ </div>
+ <div>
+ <dt>Price</dt>
+ <dd>
+ {observed.current.price.amount}
+ {observed.current.price.currency} per {observed.current.price.unit}
+ </dd>
+ </div>
+ <div>
+ <dt>Advertised quantity</dt>
+ <dd>{observed.current.quantity?.amount ?? 'Not specified'}</dd>
+ </div>
+ <div>
+ <dt>Availability</dt>
+ <dd>{observed.current.status}</dd>
+ </div>
+ </dl>
+ {:else}<p>
+ The current listing is withdrawn or unsupported. It cannot be
+ overwritten here.
+ </p>{/if}
+ {#if proposed}
+ <h2>Your proposed listing</h2>
+ <dl class="stack">
+ <div>
+ <dt>Product name</dt>
+ <dd>{proposed.title}</dd>
+ </div>
+ <div>
+ <dt>Description</dt>
+ <dd class="description">{proposed.description}</dd>
+ </div>
+ <div>
+ <dt>Public area</dt>
+ <dd>{proposed.location}</dd>
+ </div>
+ <div>
+ <dt>Price</dt>
+ <dd>{proposed.amount} {proposed.currency} per {proposed.unit}</dd>
+ </div>
+ <div>
+ <dt>Advertised quantity</dt>
+ <dd>{proposed.quantity || 'Not specified'}</dd>
+ </div>
+ <div>
+ <dt>Public contact</dt>
+ <dd>
+ {proposed.contactType
+ ? proposed.contactType + ': ' + proposed.contactValue
+ : 'Not included'}
+ </dd>
+ </div>
+ </dl>
+ {/if}
+ </section>
+{:else if observed && observed.status !== 'ready'}
+ <Notice
+ tone="info"
+ text={observed.status === 'checking'
+ ? 'Checking the current listing and removal requests. Your local values remain here.'
+ : 'The current listing check is incomplete. Keep your local values; this does not prove that another revision is absent.'}
+ />
+{/if}
diff --git a/web/src/lib/components/ListingEditor.svelte b/web/src/lib/components/ListingEditor.svelte
@@ -1,7 +1,8 @@
<script lang="ts">
- /* global document */
+ /* global document, setInterval, clearInterval */
import { getContext, onMount, tick } from 'svelte';
import ListingReview from './ListingReview.svelte';
+ import ConflictNotice from './ConflictNotice.svelte';
import InboxSetup from './InboxSetup.svelte';
import {
PUBLIC_RUNTIME_CONTEXT,
@@ -43,6 +44,8 @@
saveAndCloseListingEditor,
closeListingEditor,
subscribeListingEditor,
+ listingEditorEditSource,
+ observeListingEditor,
type ListingEditor as Editor,
type ListingEditorRoute,
type ListingEditorSnapshot
@@ -156,7 +159,8 @@
});
$effect(() => {
const resource = route,
- author = admittedAuthor;
+ author = admittedAuthor,
+ editRuntime = route.mode === 'edit' ? runtime : undefined;
if (!active || !author) {
editor = undefined;
snapshot = undefined;
@@ -168,6 +172,12 @@
let alive = true,
owned: Editor | undefined,
off = () => {};
+ const observer =
+ resource.mode === 'edit'
+ ? setInterval(() => {
+ if (owned) observeListingEditor(owned);
+ }, 250)
+ : undefined;
editor = undefined;
snapshot = undefined;
review = undefined;
@@ -175,58 +185,62 @@
reviewMessage = '';
form = blankForm();
unavailable = false;
- void openListingEditor(context, resource, cancellation.signal).then(
- (result) => {
- if (!alive) {
- if (result.status === 'ready') closeListingEditor(result.editor);
- return;
- }
- if (result.status !== 'ready') {
- unavailable = true;
- return;
+ void openListingEditor(
+ context,
+ resource,
+ cancellation.signal,
+ editRuntime
+ ).then((result) => {
+ if (!alive) {
+ if (result.status === 'ready') closeListingEditor(result.editor);
+ return;
+ }
+ if (result.status !== 'ready') {
+ unavailable = true;
+ return;
+ }
+ owned = result.editor;
+ editor = owned;
+ const next = listingEditorSnapshot(owned);
+ if (!next) {
+ unavailable = true;
+ return;
+ }
+ snapshot = next;
+ form = { ...next.form };
+ off = subscribeListingEditor(owned, () => {
+ snapshot = owned && listingEditorSnapshot(owned);
+ if (
+ snapshot?.state === 'saved' &&
+ snapshot.draftId &&
+ resource.mode === 'new' &&
+ owned &&
+ firstOwner !== owned &&
+ !closeBusy &&
+ onfirstsave
+ ) {
+ firstOwner = owned;
+ firstNavigation = onfirstsave(
+ snapshot.draftId,
+ () =>
+ alive &&
+ mounted &&
+ editor === owned &&
+ !!owned &&
+ !!listingEditorSnapshot(owned)
+ ).catch(() => {
+ if (alive) navigationFailed = true;
+ });
}
- owned = result.editor;
- editor = owned;
- const next = listingEditorSnapshot(owned);
- if (!next) {
+ if (!snapshot) {
unavailable = true;
- return;
+ form = blankForm();
}
- snapshot = next;
- form = { ...next.form };
- off = subscribeListingEditor(owned, () => {
- snapshot = owned && listingEditorSnapshot(owned);
- if (
- snapshot?.state === 'saved' &&
- snapshot.draftId &&
- resource.mode === 'new' &&
- owned &&
- firstOwner !== owned &&
- !closeBusy &&
- onfirstsave
- ) {
- firstOwner = owned;
- firstNavigation = onfirstsave(
- snapshot.draftId,
- () =>
- alive &&
- mounted &&
- editor === owned &&
- !!owned &&
- !!listingEditorSnapshot(owned)
- ).catch(() => {
- if (alive) navigationFailed = true;
- });
- }
- if (!snapshot) {
- unavailable = true;
- form = blankForm();
- }
- });
- }
- );
+ });
+ });
return () => {
alive = false;
+ if (observer !== undefined) clearInterval(observer);
cancellation.abort();
off();
if (owned) closeListingEditor(owned);
@@ -380,6 +394,16 @@
Loading local values.
</p>{/if}
{:else}
+ {#if route.mode === 'edit' && editor && listingEditorEditSource(editor)}
+ <ConflictNotice
+ source={listingEditorEditSource(editor)!}
+ proposed={form}
+ />
+ {#if visible.editable}<Notice
+ tone="info"
+ text="These changes can be saved locally. Publishing changes is not available."
+ />{/if}
+ {/if}
{#if !visible.editable}<Notice
tone="info"
text={route.mode === 'draft'
@@ -628,14 +652,17 @@
</div>
</details>
</form>
- {#if visible.editable}<button
+ {#if visible.editable && route.mode !== 'edit'}<button
type="button"
onclick={showReview}
disabled={reviewBusy || closeBusy}
>{reviewBusy ? 'Preparing review' : 'Review listing'}</button
>{/if}
{/if}
- {#if visible.editable && setup}<InboxSetup controller={setup} inline />{/if}
+ {#if visible.editable && route.mode !== 'edit' && setup}<InboxSetup
+ controller={setup}
+ inline
+ />{/if}
{#each visible.operations as operation (operation)}<OperationStatus
publicOperation={operation}
/>{/each}
diff --git a/web/src/lib/publishing/edit-source.ts b/web/src/lib/publishing/edit-source.ts
@@ -0,0 +1,361 @@
+import { buildFoodTemplate } from '../contracts/food-availability-v1/write.ts';
+import {
+ projectFoodParts,
+ type FoodProjection
+} from '../contracts/food-availability-v1/read.ts';
+import type { PublicDraftForm } from '../contracts/local-records.ts';
+import { decodeProductReference } from '../nostr/references.ts';
+import { inspectLocalTemplate } from '../nostr/local-template.ts';
+import {
+ verifyEnvelope,
+ verifiedEnvelopeSnapshot
+} from '../nostr/verified-envelope.ts';
+import {
+ publicPublicationOwner,
+ publicPublicationDraftRepository,
+ publicPublicationQuotaRepository,
+ readPublicListingIntent,
+ type PublicPublicationRepository
+} from '../persistence/public-publications.ts';
+import {
+ inspectPublicStorage,
+ publicInventorySnapshot
+} from '../persistence/quota.ts';
+import { publicRecordSnapshot } from '../persistence/records.ts';
+import { readPublicDraft } from '../persistence/drafts.ts';
+import {
+ identityViewSession,
+ identityViewMatchesOwner,
+ type IdentityViewContext
+} from '../runtime/view-context.ts';
+import { subscribeIdentityInvalidation } from '../runtime/identity-session.ts';
+import {
+ createPublicView,
+ beginPublicViewRun,
+ disposePublicView,
+ publicViewOwnsRun,
+ publicViewRunCurrent,
+ publicViewProjectionAvailable,
+ type PublicRuntime,
+ type PublicView
+} from '../runtime/public-runtime.ts';
+import {
+ createPublicViewHeadResolver,
+ resolveHeads,
+ headResolutionSnapshot,
+ closeHeadResolver,
+ type HeadResolver
+} from '../catalog/resolve-head.ts';
+import { createPublicHeadCandidate, publicHeadKey } from '../catalog/heads.ts';
+
+declare const sourceBrand: unique symbol;
+export type OwnedEditSource = Readonly<{ [sourceBrand]: true }>;
+export type OwnedEditSourceSnapshot = Readonly<{
+ owner: string;
+ coordinate: string;
+ sourceEventId: string;
+ sourceCommand: string;
+ publishedAtSeconds: number;
+ form: PublicDraftForm;
+ status:
+ 'read-only' | 'checking' | 'ready' | 'partial' | 'conflict' | 'withdrawn';
+ current?: FoodProjection;
+ currentEventId?: string;
+ definitiveAbsence: false;
+}>;
+type Source = {
+ snapshot(): OwnedEditSourceSnapshot | undefined;
+ authorize():
+ | Readonly<{
+ repository: PublicPublicationRepository;
+ owner: string;
+ coordinate: string;
+ baseWire: string;
+ sourceCommand: string;
+ publishedAtSeconds: number;
+ current(): boolean;
+ }>
+ | undefined;
+ close(): void;
+};
+const sources = new WeakMap<OwnedEditSource, Source>();
+// Retained prototype custody precedes network work. A public/Tera event, a
+// snapshot, or an arbitrary same-author signature is not adopted as local source.
+export async function openOwnedEditSource(
+ repository: PublicPublicationRepository,
+ context: IdentityViewContext,
+ value: unknown,
+ runtime?: PublicRuntime,
+ signal?: AbortSignal
+): Promise<OwnedEditSource | undefined> {
+ let view: PublicView | undefined, resolver: HeadResolver | undefined;
+ let closed = false,
+ off = () => {};
+ function close() {
+ if (closed) return;
+ closed = true;
+ off();
+ signal?.removeEventListener('abort', close);
+ try {
+ if (resolver) closeHeadResolver(resolver);
+ } finally {
+ if (view) disposePublicView(view);
+ }
+ }
+ try {
+ const owner = publicPublicationOwner(repository),
+ session = identityViewSession(context),
+ reference = decodeProductReference(value),
+ drafts = publicPublicationDraftRepository(repository),
+ quota = publicPublicationQuotaRepository(repository);
+ if (
+ !owner ||
+ !session ||
+ !reference ||
+ reference.pubkey !== owner ||
+ !drafts ||
+ !quota ||
+ signal?.aborted ||
+ !identityViewMatchesOwner(context, owner)
+ )
+ return;
+ const current = () =>
+ !closed &&
+ !signal?.aborted &&
+ identityViewSession(context) === session &&
+ identityViewMatchesOwner(context, owner) &&
+ publicPublicationOwner(repository) === owner;
+ off = subscribeIdentityInvalidation(session, close);
+ signal?.addEventListener('abort', close, { once: true });
+ const inspected = await inspectPublicStorage(quota);
+ if (!current() || !inspected.ok) {
+ close();
+ return;
+ }
+ const inventory = publicInventorySnapshot(quota, inspected.value);
+ if (!inventory) {
+ close();
+ return;
+ }
+ let retained:
+ | Readonly<{
+ form: PublicDraftForm;
+ wire: string;
+ command: string;
+ publishedAt: number;
+ eventId: string;
+ }>
+ | undefined;
+ for (const item of inventory.rows) {
+ if (item.family !== 'public_operation') continue;
+ const read = await readPublicListingIntent(repository, item.id);
+ if (!current()) {
+ close();
+ return;
+ }
+ const row =
+ read.status === 'found' &&
+ publicRecordSnapshot(read.record, owner, item.id);
+ // Incomplete critical storage is not an absence that permits adoption.
+ if (!row || row.family !== 'public_operation') {
+ close();
+ return;
+ }
+ if (
+ row.capture.kind !== 30402 ||
+ !row.artifact ||
+ row.source.type !== 'draft'
+ )
+ continue;
+ const template = inspectLocalTemplate(row.capture.wire, owner, 30402),
+ projected = template && projectFoodParts(template);
+ if (
+ !template ||
+ !projected ||
+ projected.outcome !== 'focused' ||
+ projected.projection.identifier !== reference.identifier
+ )
+ continue;
+ const source = await readPublicDraft(drafts, row.source.id);
+ if (!current()) {
+ close();
+ return;
+ }
+ if (!source.ok || source.value.revision !== row.source.revision) continue;
+ const form = source.value.form,
+ food = projected.projection;
+ if (form.contactType === '' && form.contactValue !== '') continue;
+ const built = buildFoodTemplate({
+ identifier: food.identifier,
+ title: form.title,
+ description: form.description,
+ location: form.location,
+ amount: form.amount,
+ currency: form.currency,
+ unit: form.unit,
+ ...(form.quantity === '' ? {} : { quantity: form.quantity }),
+ published_at: food.published_at,
+ created_at: template.created_at,
+ status: food.status,
+ ...(form.contactType === ''
+ ? {}
+ : {
+ contact: {
+ type: form.contactType,
+ value: form.contactValue,
+ public: true as const
+ }
+ })
+ });
+ if (
+ !built.ok ||
+ JSON.stringify({
+ pubkey: owner,
+ kind: 30402,
+ created_at: template.created_at,
+ tags: built.wire_parts.tags,
+ content: built.wire_parts.content
+ }) !== row.capture.wire
+ )
+ continue;
+ const verified = verifyEnvelope(row.artifact.wire),
+ signed = verified.ok && verifiedEnvelopeSnapshot(verified.value);
+ if (
+ !signed ||
+ signed.id !== row.artifact.eventId ||
+ signed.id !== row.capture.hash ||
+ JSON.stringify({
+ pubkey: signed.pubkey,
+ kind: signed.kind,
+ created_at: signed.created_at,
+ tags: signed.tags,
+ content: signed.content
+ }) !== row.capture.wire
+ )
+ continue;
+ if (retained) {
+ close();
+ return;
+ }
+ retained = {
+ form,
+ wire: row.artifact.wire,
+ command: row.id,
+ publishedAt: food.published_at,
+ eventId: signed.id
+ };
+ }
+ if (!retained || !current()) {
+ close();
+ return;
+ }
+ const base = retained,
+ proof = verifyEnvelope(base.wire);
+ const head = proof.ok && createPublicHeadCandidate(proof.value);
+ if (!head) {
+ close();
+ return;
+ }
+ const key = publicHeadKey(head);
+ let run: ReturnType<typeof beginPublicViewRun> | undefined;
+ if (runtime) {
+ // A separate view/run and exact coordinate+deletion requests are independent
+ // of keyword search. Genuine retained proof seeds the ordinary selector.
+ view = createPublicView(runtime);
+ run = beginPublicViewRun(view);
+ resolver = createPublicViewHeadResolver(view, run, {
+ nowSeconds: () => Math.floor(Date.now() / 1000)
+ });
+ resolveHeads(resolver, [head]);
+ }
+ const networkOwned = () =>
+ !!(
+ view &&
+ run &&
+ publicViewOwnsRun(view, run) &&
+ publicViewProjectionAvailable(view)
+ );
+ function snapshot(): OwnedEditSourceSnapshot | undefined {
+ if (!current()) {
+ close();
+ return;
+ }
+ const row =
+ resolver && networkOwned()
+ ? headResolutionSnapshot(resolver).find((row) => row.key === key)
+ : undefined;
+ const scopes = row && [row.headSources, row.deletionSources];
+ const complete = !!(
+ row &&
+ view &&
+ run &&
+ publicViewRunCurrent(view, run) &&
+ row.coverage === 'bounded-eose' &&
+ !row.lastKnown &&
+ scopes?.every(
+ (scope) =>
+ scope?.state === 'eose' && scope.result.coverage === 'bounded-eose'
+ )
+ );
+ const competing = row && row.state.head.id !== base.eventId;
+ const status: OwnedEditSourceSnapshot['status'] = !runtime
+ ? 'read-only'
+ : row?.deletion.outcome === 'suppressed'
+ ? 'withdrawn'
+ : competing
+ ? 'conflict'
+ : complete &&
+ row?.state.food &&
+ row.state.display === 'focused_known'
+ ? 'ready'
+ : scopes?.some((scope) => scope?.state === 'active')
+ ? 'checking'
+ : 'partial';
+ return {
+ owner: owner!,
+ coordinate: reference!.naddr,
+ sourceEventId: base.eventId,
+ sourceCommand: base.command,
+ publishedAtSeconds: base.publishedAt,
+ form: { ...base.form },
+ status,
+ ...(row?.state.food ? { current: row.state.food } : {}),
+ ...(row ? { currentEventId: row.state.head.id } : {}),
+ definitiveAbsence: false
+ };
+ }
+ const token = Object.freeze({}) as OwnedEditSource;
+ sources.set(token, {
+ snapshot,
+ close,
+ authorize() {
+ if (snapshot()?.status !== 'ready') return;
+ return {
+ repository,
+ owner,
+ coordinate: reference.naddr,
+ baseWire: base.wire,
+ sourceCommand: base.command,
+ publishedAtSeconds: base.publishedAt,
+ current: () => snapshot()?.status === 'ready'
+ };
+ }
+ });
+ return token;
+ } catch {
+ close();
+ return;
+ }
+}
+export function ownedEditSourceSnapshot(
+ source: OwnedEditSource
+): OwnedEditSourceSnapshot | undefined {
+ return sources.get(source)?.snapshot();
+}
+// Internal original edit custody only, never a signing/delivery lease.
+export function authorizeOwnedEditSource(source: OwnedEditSource) {
+ return sources.get(source)?.authorize();
+}
+export function closeOwnedEditSource(source: OwnedEditSource): void {
+ sources.get(source)?.close();
+}
diff --git a/web/src/lib/publishing/listing-editor.ts b/web/src/lib/publishing/listing-editor.ts
@@ -17,9 +17,14 @@ import {
type ListingReviewResult
} from './prepare-listing.ts';
import { decodeProductReference } from '../nostr/references.ts';
-import { inspectLocalTemplate } from '../nostr/local-template.ts';
-import { projectFoodParts } from '../contracts/food-availability-v1/read.ts';
-import { buildFoodTemplate } from '../contracts/food-availability-v1/write.ts';
+import {
+ openOwnedEditSource,
+ ownedEditSourceSnapshot,
+ authorizeOwnedEditSource,
+ closeOwnedEditSource,
+ type OwnedEditSource
+} from './edit-source.ts';
+import type { PublicRuntime } from '../runtime/public-runtime.ts';
import {
openBrowserDatabase,
closeBrowserDatabase,
@@ -37,7 +42,6 @@ import {
} from '../persistence/quota.ts';
import { publicRecordSnapshot } from '../persistence/records.ts';
import {
- readPublicDraft,
publicDraftRepositoryOwner,
type PublicDraftRepository
} from '../persistence/drafts.ts';
@@ -82,6 +86,7 @@ export type ListingEditorSnapshot = Readonly<{
failure: string | null;
coordinate: string | null;
sourceEventId: string | null;
+ sourcePublishedAtSeconds?: number;
operations: readonly ListingOperationView[];
}>;
type Editor = Readonly<{
@@ -96,6 +101,8 @@ type Editor = Readonly<{
form: PublicDraftForm
): Promise<ListingReviewResult>;
reviewCurrent(review: ListingReview): boolean;
+ source(): OwnedEditSource | undefined;
+ observe(): void;
subscribe(listener: () => void): () => void;
}>;
const editors = new WeakMap<ListingEditor, Editor>();
@@ -138,7 +145,8 @@ function routeSnapshot(value: unknown): ListingEditorRoute | undefined {
export async function openListingEditor(
context: IdentityViewContext,
input: unknown,
- signal?: AbortSignal
+ signal?: AbortSignal,
+ runtime?: PublicRuntime
): Promise<
| Readonly<{ status: 'ready'; editor: ListingEditor }>
| Readonly<{
@@ -173,6 +181,9 @@ export async function openListingEditor(
repository: PublicDraftRepository | undefined,
controller: PublicDraftController | undefined;
const operations = new Map<string, ListingOperationView>();
+ let editSource: OwnedEditSource | undefined;
+ let acquiringEditDraft:
+ Promise<PublicDraftController | undefined> | undefined;
let reviewed:
| {
setup: InboxSetupView | undefined;
@@ -220,6 +231,7 @@ export async function openListingEditor(
signal?.removeEventListener('abort', retire);
cancellation.abort();
clearReview();
+ if (editSource) closeOwnedEditSource(editSource);
if (controller) closePublicDraftController(controller);
for (const operation of operations.values())
closeListingOperationView(operation);
@@ -253,85 +265,19 @@ export async function openListingEditor(
coordinate: string | null = null,
sourceEventId: string | null = null;
if (route.mode === 'edit') {
- const reference = decodeProductReference(route.naddr),
- quota = publicPublicationQuotaRepository(publications);
- if (!reference || !quota) return unavailable('source');
- const inspected = await inspectPublicStorage(quota);
- if (!current() || !inspected.ok) return unavailable('source');
- const inventory = publicInventorySnapshot(quota, inspected.value);
- if (!inventory) return unavailable('source');
- let matching:
- Readonly<{ form: PublicDraftForm; eventId: string }> | undefined;
- for (const item of inventory.rows) {
- if (item.family !== 'public_operation') continue;
- const read = await readPublicListingIntent(publications, item.id);
- if (!current()) return unavailable('source');
- const row =
- read.status === 'found' &&
- publicRecordSnapshot(read.record, owner, item.id);
- if (
- !row ||
- row.family !== 'public_operation' ||
- row.capture.kind !== 30402 ||
- !row.artifact ||
- row.source.type !== 'draft'
- )
- continue;
- const template = inspectLocalTemplate(row.capture.wire, owner, 30402);
- if (!template) continue;
- const projected = projectFoodParts(template);
- if (
- projected.outcome !== 'focused' ||
- projected.projection.identifier !== reference.identifier
- )
- continue;
- const source = await readPublicDraft(drafts, row.source.id);
- if (!current()) return unavailable('source');
- if (!source.ok || source.value.revision !== row.source.revision)
- continue;
- const value = source.value.form,
- p = projected.projection;
- if (value.contactType === '' && value.contactValue !== '') continue;
- const built = buildFoodTemplate({
- identifier: p.identifier,
- title: value.title,
- description: value.description,
- location: value.location,
- amount: value.amount,
- currency: value.currency,
- unit: value.unit,
- ...(value.quantity === '' ? {} : { quantity: value.quantity }),
- published_at: p.published_at,
- created_at: template.created_at,
- status: p.status,
- ...(value.contactType === ''
- ? {}
- : {
- contact: {
- type: value.contactType,
- value: value.contactValue,
- public: true as const
- }
- })
- });
- if (
- !built.ok ||
- JSON.stringify({
- pubkey: owner,
- kind: 30402,
- created_at: template.created_at,
- tags: built.wire_parts.tags,
- content: built.wire_parts.content
- }) !== row.capture.wire
- )
- continue;
- if (matching) return unavailable('source');
- matching = { form: value, eventId: row.artifact.eventId };
- }
- if (!matching) return unavailable('source');
- sourceForm = matching.form;
+ editSource = await openOwnedEditSource(
+ publications,
+ context,
+ route.naddr,
+ runtime,
+ cancellation.signal
+ );
+ if (!current()) return unavailable('source');
+ const retained = editSource && ownedEditSourceSnapshot(editSource);
+ if (!retained) return unavailable('source');
+ sourceForm = retained.form;
coordinate = route.naddr;
- sourceEventId = matching.eventId;
+ sourceEventId = retained.sourceEventId;
} else {
const acquired = await createPublicDraftController(
drafts,
@@ -402,6 +348,10 @@ export async function openListingEditor(
const value: Editor = {
current,
retire,
+ source: () => (current() ? editSource : undefined),
+ observe: () => {
+ if (current()) notify();
+ },
snapshot() {
if (!current()) {
retire();
@@ -412,7 +362,10 @@ export async function openListingEditor(
mode: route.mode,
owner,
form: local ? local.form : { ...(sourceForm ?? emptyForm) },
- editable: route.mode !== 'edit' && operations.size === 0,
+ editable:
+ operations.size === 0 &&
+ (route.mode !== 'edit' ||
+ !!(editSource && authorizeOwnedEditSource(editSource))),
draftId: local?.draft?.id ?? null,
state:
local && operations.size === 0
@@ -423,6 +376,12 @@ export async function openListingEditor(
failure: local?.failure ?? null,
coordinate,
sourceEventId,
+ ...(editSource
+ ? {
+ sourcePublishedAtSeconds:
+ ownedEditSourceSnapshot(editSource)?.publishedAtSeconds
+ }
+ : {}),
operations: Array.from(operations.values())
};
},
@@ -431,8 +390,27 @@ export async function openListingEditor(
retire();
return false;
}
- if (!controller || route.mode === 'edit' || operations.size)
- return false;
+ if (route.mode === 'edit') {
+ if (
+ !editSource ||
+ !authorizeOwnedEditSource(editSource) ||
+ !sourceForm
+ )
+ return false;
+ if (!controller) {
+ acquiringEditDraft ??= createPublicDraftController(
+ drafts,
+ sourceForm
+ );
+ const acquired = await acquiringEditDraft;
+ if (!current() || !authorizeOwnedEditSource(editSource)) {
+ if (acquired) closePublicDraftController(acquired);
+ return false;
+ }
+ controller = acquired;
+ }
+ }
+ if (!controller || operations.size) return false;
if (!editPublicDraft(controller, input)) return false;
clearReview();
notify();
@@ -456,8 +434,7 @@ export async function openListingEditor(
retire();
return false;
}
- if (!controller || route.mode === 'edit' || operations.size)
- return false;
+ if (!controller || operations.size) return false;
const pending = flushPublicDraft(controller);
await Promise.resolve();
if (!current()) {
@@ -474,13 +451,7 @@ export async function openListingEditor(
return saved;
},
async saveClose() {
- if (
- !current() ||
- !controller ||
- route.mode === 'edit' ||
- operations.size ||
- closing
- )
+ if (!current() || !controller || operations.size || closing)
return false;
closing = true;
try {
@@ -621,6 +592,14 @@ export function flushListingEditor(editor: ListingEditor): Promise<boolean> {
export function closeListingEditor(editor: ListingEditor): void {
editors.get(editor)?.retire();
}
+export function listingEditorEditSource(
+ editor: ListingEditor
+): OwnedEditSource | undefined {
+ return editors.get(editor)?.source();
+}
+export function observeListingEditor(editor: ListingEditor): void {
+ editors.get(editor)?.observe();
+}
export function saveAndCloseListingEditor(
editor: ListingEditor
): Promise<boolean> {
diff --git a/web/tests/e2e/edit-source.spec.ts b/web/tests/e2e/edit-source.spec.ts
@@ -0,0 +1,311 @@
+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 { WebSocketServer } from 'ws';
+import { createStaticHarness } from '../integration/harness/static.ts';
+import type * as Fixture from './harness/edit-source.ts';
+import type { NostrEvent } from 'applesauce-core/helpers';
+declare global {
+ interface Window {
+ hcp118: typeof Fixture;
+ hcp118Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>;
+ }
+}
+let server: Awaited<ReturnType<typeof createStaticHarness>>,
+ sockets: WebSocketServer,
+ endpoint: string,
+ bundle: string;
+let event: NostrEvent | undefined,
+ partial = false,
+ requests: unknown[][] = [],
+ effects: unknown[][] = [];
+test.beforeAll(async () => {
+ server = await createStaticHarness();
+ sockets = new WebSocketServer({
+ host: '127.0.0.1',
+ port: 0,
+ maxPayload: 65536
+ });
+ await once(sockets, 'listening');
+ const address = sockets.address();
+ if (!address || typeof address === 'string') throw Error('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') {
+ effects.push(frame);
+ return;
+ }
+ if (frame[0] !== 'REQ') return;
+ requests.push(frame);
+ const filters = frame.slice(2) as { kinds?: number[] }[];
+ if (event && filters.some((f) => f.kinds?.includes(30402)))
+ socket.send(JSON.stringify(['EVENT', frame[1], event]));
+ if (!(partial && filters.some((f) => f.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/edit-source.ts', import.meta.url)
+ ),
+ name: 'hcp118',
+ 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 }) => {
+ event = undefined;
+ partial = false;
+ requests = [];
+ effects = [];
+ await page.addInitScript((endpoint) => {
+ const Native = window.WebSocket;
+ window.WebSocket = class extends Native {
+ constructor(url: string | URL, protocols?: string | string[]) {
+ const origin = new URL(url.toString()).origin;
+ if (
+ ![
+ 'wss://discovery.example.org',
+ 'wss://inbox.example.org',
+ 'wss://second.example.org'
+ ].includes(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.hcp118Fixture = await window.hcp118.createFixture();
+ return window.hcp118Fixture.event;
+ });
+});
+test.afterEach(async ({ page }) => {
+ await page.evaluate(async () => {
+ await window.hcp118Fixture?.close();
+ });
+});
+test('HCP118 exact retained source performs independent head/deletion lookup and genuine current-head authorization', async ({
+ page
+}) => {
+ const before = await page.evaluate(() => window.hcp118Fixture.counts());
+ await page.evaluate(() => window.hcp118Fixture.open());
+ await expect
+ .poll(() => page.evaluate(() => window.hcp118Fixture.snapshot()?.status))
+ .toBe('ready');
+ const result = await page.evaluate(() => ({
+ snapshot: window.hcp118Fixture.snapshot(),
+ authorized: window.hcp118Fixture.authorized(),
+ copied: window.hcp118Fixture.authorized(true),
+ counts: window.hcp118Fixture.counts()
+ }));
+ expect(result.authorized).toBe(true);
+ expect(result.copied).toBe(false);
+ expect(result.snapshot?.sourceEventId).toBe(event!.id);
+ expect(result.snapshot?.publishedAtSeconds).toBe(
+ Number(event!.tags.find((t) => t[0] === 'published_at')![1])
+ );
+ expect(result.counts).toEqual(before);
+ expect(requests.some((r) => JSON.stringify(r).includes('"#d"'))).toBe(true);
+ expect(requests.some((r) => JSON.stringify(r).includes('"kinds":[5]'))).toBe(
+ true
+ );
+ expect(requests.some((r) => JSON.stringify(r).includes('"search"'))).toBe(
+ false
+ );
+ expect(effects).toHaveLength(0);
+});
+test('HCP118 retained values without critical lookup remain read-only and cannot infer absence', async ({
+ page
+}) => {
+ const value = await page.evaluate(() => window.hcp118Fixture.open(false));
+ expect(value?.status).toBe('read-only');
+ expect(await page.evaluate(() => window.hcp118Fixture.authorized())).toBe(
+ false
+ );
+ expect(requests).toHaveLength(0);
+});
+test('HCP118 partial deletion coverage cannot authorize an unchanged known source', async ({
+ page
+}) => {
+ partial = true;
+ await page.evaluate(() => window.hcp118Fixture.open());
+ await expect.poll(() => requests.length).toBeGreaterThan(0);
+ expect(await page.evaluate(() => window.hcp118Fixture.authorized())).toBe(
+ false
+ );
+ expect(
+ await page.evaluate(
+ () => window.hcp118Fixture.snapshot()?.definitiveAbsence
+ )
+ ).toBe(false);
+});
+test('HCP118 Tera/external retained-head source is not adopted', async ({
+ page
+}) => {
+ await page.evaluate(() => window.hcp118Fixture.external());
+ expect(
+ await page.evaluate(() => window.hcp118Fixture.open())
+ ).toBeUndefined();
+ expect(requests).toHaveLength(0);
+});
+test('HCP118 foreign author is refused before any current-head query', async ({
+ page
+}) => {
+ expect(
+ await page.evaluate(() =>
+ window.hcp118Fixture.open(true, window.hcp118Fixture.foreign())
+ )
+ ).toBeUndefined();
+ expect(requests).toHaveLength(0);
+});
+test('HCP118 newer independently signed head stops the original retained base', async ({
+ page
+}) => {
+ event = await page.evaluate(() => window.hcp118Fixture.competing());
+ await page.evaluate(() => window.hcp118Fixture.open());
+ await expect
+ .poll(() => page.evaluate(() => window.hcp118Fixture.snapshot()?.status))
+ .toBe('conflict');
+ expect(await page.evaluate(() => window.hcp118Fixture.authorized())).toBe(
+ false
+ );
+ expect(effects).toHaveLength(0);
+});
+test('HCP118 original source closes on cancellation; copied close cannot revoke original custody', async ({
+ page
+}) => {
+ await page.evaluate(() => window.hcp118Fixture.open());
+ await expect
+ .poll(() => page.evaluate(() => window.hcp118Fixture.authorized()))
+ .toBe(true);
+ await page.evaluate(() => window.hcp118Fixture.copiedClose());
+ expect(await page.evaluate(() => window.hcp118Fixture.authorized())).toBe(
+ true
+ );
+ await page.evaluate(() => window.hcp118Fixture.cancel());
+ expect(
+ await page.evaluate(() => window.hcp118Fixture.snapshot())
+ ).toBeUndefined();
+ expect(await page.evaluate(() => window.hcp118Fixture.authorized())).toBe(
+ false
+ );
+});
+for (const width of [320, 1024])
+ test(`HCP118 ${width}px conflict displays actual current and exact proposed values without merge or publish`, async ({
+ page
+ }) => {
+ await page.setViewportSize({ width, height: 900 });
+ await page.evaluate(() => window.hcp118Fixture.open());
+ await expect
+ .poll(() => page.evaluate(() => window.hcp118Fixture.snapshot()?.status))
+ .toBe('ready');
+ await page.evaluate(() => window.hcp118Fixture.renderEditor());
+ const title = page.locator('#listing-title');
+ await expect(title).not.toHaveAttribute('readonly', '');
+ await title.fill('Exact proposed carrots');
+ await page
+ .locator('#listing-description')
+ .fill('Raw proposed description\n' + 'long '.repeat(100));
+ await page.locator('#listing-location').fill('Proposed town');
+ await page.locator('#listing-amount').fill('9');
+ await page.locator('#listing-quantity').fill('4');
+ await expect
+ .poll(() =>
+ page.evaluate(
+ async () =>
+ (await window.hcp118Fixture.drafts()).find(
+ (row) => row.form.title === 'Exact proposed carrots'
+ )?.form
+ )
+ )
+ .toEqual({
+ title: 'Exact proposed carrots',
+ description: 'Raw proposed description\n' + 'long '.repeat(100),
+ location: 'Proposed town',
+ amount: '9',
+ currency: 'USD',
+ unit: 'kg',
+ quantity: '4',
+ contactType: '',
+ contactValue: ''
+ });
+ const beforeExternalFixture = await page.evaluate(
+ () => window.hcp118Fixture.counts().signs
+ );
+ event = await page.evaluate(() => window.hcp118Fixture.competing());
+ const before = await page.evaluate(
+ () => window.hcp118Fixture.counts().signs
+ );
+ expect(before).toBe(beforeExternalFixture + 1);
+ await page.evaluate(() => window.hcp118Fixture.lookupAgain());
+ await expect
+ .poll(() => page.evaluate(() => window.hcp118Fixture.snapshot()?.status))
+ .toBe('conflict');
+ await expect(page.locator('#hcp118-conflict')).toContainText(
+ 'This listing changed elsewhere. Review the latest version before publishing.'
+ );
+ await expect(page.locator('#hcp118-conflict')).toContainText(
+ 'Actual current carrots'
+ );
+ await expect(page.locator('#hcp118-conflict')).toContainText(
+ 'Exact proposed carrots'
+ );
+ await expect(page.locator('#hcp118-conflict')).toContainText(
+ 'Proposed town'
+ );
+ await expect(title).toHaveValue('Exact proposed carrots');
+ await expect(title).toHaveAttribute('readonly', '');
+ const retained = await page.evaluate(() => window.hcp118Fixture.drafts());
+ expect(retained).toHaveLength(2);
+ expect(retained.find((row) => row.form.title === 'Carrots')).toBeDefined();
+ expect(
+ retained.find((row) => row.form.title === 'Exact proposed carrots')?.form
+ .location
+ ).toBe('Proposed town');
+ expect(await page.evaluate(() => window.hcp118Fixture.counts().signs)).toBe(
+ before
+ );
+ expect(
+ await page.evaluate(
+ () => document.documentElement.scrollWidth <= window.innerWidth
+ )
+ ).toBe(true);
+ await expect(
+ page.getByRole('button', { name: /publish|merge/i })
+ ).toHaveCount(0);
+ expect(effects).toHaveLength(0);
+ });
diff --git a/web/tests/e2e/harness/edit-source.ts b/web/tests/e2e/harness/edit-source.ts
@@ -0,0 +1,228 @@
+// HC_TEST_ONLY_RELAY/QUALIFICATION_PORT: actual original repositories, signed
+// events, anonymous SDK resolver and native IndexedDB; no live/operator Q.
+import { mount, unmount } from 'svelte';
+import ConflictNotice from '../../../src/lib/components/ConflictNotice.svelte';
+import ListingEditor from '../../../src/lib/components/ListingEditor.svelte';
+import { decodeProductReference } from '../../../src/lib/nostr/references.ts';
+import {
+ openOwnedEditSource,
+ ownedEditSourceSnapshot,
+ authorizeOwnedEditSource,
+ closeOwnedEditSource,
+ type OwnedEditSource
+} from '../../../src/lib/publishing/edit-source.ts';
+import { createFixture as originalFixture } from './listing-operation-view.ts';
+import { makeFixture } from './approved-signing.ts';
+import { fixturePolicy } from './inbox-setup.ts';
+import {
+ createIdentityViewContext,
+ mountIdentityView,
+ connectIdentityView,
+ closeIdentityView,
+ disconnectIdentityView,
+ IDENTITY_VIEW_CONTEXT
+} from '../../../src/lib/runtime/view-context.ts';
+import {
+ createPublicRuntimeContext,
+ mountPublicRuntime,
+ closePublicRuntime,
+ PUBLIC_RUNTIME_CONTEXT,
+ createPublicView,
+ beginPublicViewRun,
+ subscribePublicView,
+ disposePublicView,
+ type PublicView
+} from '../../../src/lib/runtime/public-runtime.ts';
+import {
+ openBrowserDatabase,
+ closeBrowserDatabase,
+ browserDatabaseTransaction
+} from '../../../src/lib/persistence/database.ts';
+import { createPublicPublicationRepository } from '../../../src/lib/persistence/public-publications.ts';
+import { encodeProductReference } from '../../../src/lib/nostr/references.ts';
+import { projectFoodParts } from '../../../src/lib/contracts/food-availability-v1/read.ts';
+import type { PublicDraftForm } from '../../../src/lib/contracts/local-records.ts';
+export async function createFixture() {
+ const original = await originalFixture();
+ if ((await original.signed()) !== 'prepared')
+ throw Error('actual original signature missing');
+ const row = await original.row();
+ if (!row.artifact) throw Error('actual artifact missing');
+ const event = JSON.parse(row.artifact.wire) as ReturnType<
+ ReturnType<typeof makeFixture>['sign']
+ >;
+ const projected = projectFoodParts(event);
+ if (projected.outcome !== 'focused')
+ throw Error('actual supported source missing');
+ const naddr = encodeProductReference({
+ kind: 30402,
+ pubkey: row.owner,
+ identifier: projected.projection.identifier
+ });
+ if (!naddr) throw Error('actual coordinate missing');
+ const context = createIdentityViewContext();
+ mountIdentityView(context);
+ await connectIdentityView(context);
+ const opened = await openBrowserDatabase();
+ if (opened.state !== 'ready') throw Error(opened.reason);
+ const database = opened.owner,
+ repository = createPublicPublicationRepository(database, row.owner);
+ if (!repository) throw Error('actual repository missing');
+ const publicContext = createPublicRuntimeContext();
+ const runtime = mountPublicRuntime(publicContext, fixturePolicy());
+ if (!runtime) throw Error('actual runtime missing');
+ let source: OwnedEditSource | undefined,
+ panel: ReturnType<typeof mount> | undefined,
+ target: HTMLElement | undefined;
+ const cancellation = new AbortController();
+ const lookups: PublicView[] = [];
+ return {
+ event,
+ naddr,
+ owner: row.owner,
+ counts: () => original.counts(),
+ async open(network = true, address = naddr) {
+ source = await openOwnedEditSource(
+ repository,
+ context,
+ address,
+ network ? runtime : undefined,
+ cancellation.signal
+ );
+ return source && ownedEditSourceSnapshot(source);
+ },
+ snapshot: (copy = false) =>
+ source && ownedEditSourceSnapshot(copy ? { ...source } : source),
+ authorized: (copy = false) =>
+ !!(source && authorizeOwnedEditSource(copy ? { ...source } : source)),
+ copiedClose() {
+ if (source) closeOwnedEditSource({ ...source });
+ },
+ async external() {
+ await original.externalSource();
+ },
+ async competing(
+ title = 'Actual current carrots',
+ status: 'active' | 'sold' = 'active'
+ ) {
+ const provider = window.nostr as
+ | {
+ signEvent: (
+ input: Parameters<ReturnType<typeof makeFixture>['sign']>[0]
+ ) => Promise<ReturnType<ReturnType<typeof makeFixture>['sign']>>;
+ }
+ | undefined;
+ if (!provider) throw Error('original controlled provider missing');
+ return await provider.signEvent({
+ kind: event.kind,
+ content: event.content,
+ created_at: event.created_at + 1,
+ tags: event.tags.map((tag) =>
+ tag[0] === 'title'
+ ? ['title', title]
+ : tag[0] === 'status'
+ ? ['status', status]
+ : tag
+ )
+ });
+ },
+ foreign() {
+ return encodeProductReference({
+ kind: 30402,
+ pubkey: makeFixture().owner,
+ identifier: projected.projection.identifier
+ })!;
+ },
+ async render(proposed: PublicDraftForm) {
+ if (!source) throw Error('actual source missing');
+ if (panel) await unmount(panel);
+ target?.remove();
+ target = document.createElement('div');
+ target.id = 'hcp118-conflict';
+ document.body.append(target);
+ panel = mount(ConflictNotice, { target, props: { source, proposed } });
+ },
+ async renderEditor() {
+ if (panel) await unmount(panel);
+ target?.remove();
+ target = document.createElement('div');
+ target.id = 'hcp118-conflict';
+ document.body.append(target);
+ panel = mount(ListingEditor, {
+ target,
+ props: { route: { mode: 'edit', naddr } },
+ context: new Map<string, unknown>([
+ [IDENTITY_VIEW_CONTEXT, context],
+ [PUBLIC_RUNTIME_CONTEXT, publicContext]
+ ])
+ });
+ },
+ lookupAgain() {
+ const reference = decodeProductReference(naddr);
+ if (!reference) throw Error('actual reference missing');
+ const view = createPublicView(runtime);
+ lookups.push(view);
+ const run = beginPublicViewRun(view);
+ subscribePublicView(
+ view,
+ run,
+ 'head',
+ [
+ {
+ kinds: [30402],
+ authors: [reference.pubkey],
+ '#d': [reference.identifier],
+ limit: 20
+ }
+ ],
+ () => {}
+ );
+ },
+ async drafts() {
+ const transaction = browserDatabaseTransaction(
+ database,
+ ['public_drafts'],
+ 'readonly'
+ );
+ const request = transaction.objectStore('public_drafts').getAll();
+ return await new Promise<
+ { owner: string; id: string; form: PublicDraftForm }[]
+ >((resolve, reject) => {
+ transaction.addEventListener('complete', () =>
+ resolve(
+ (request.result as { owner: string; wire: string }[])
+ .filter((row) => row.owner === original.owner)
+ .map(
+ (row) =>
+ JSON.parse(row.wire) as {
+ owner: string;
+ id: string;
+ form: PublicDraftForm;
+ }
+ )
+ )
+ );
+ transaction.addEventListener('abort', () =>
+ reject(Error('actual native draft read failed'))
+ );
+ });
+ },
+ cancel() {
+ cancellation.abort();
+ },
+ disconnect() {
+ disconnectIdentityView(context);
+ },
+ async close() {
+ cancellation.abort();
+ if (source) closeOwnedEditSource(source);
+ if (panel) await unmount(panel);
+ target?.remove();
+ for (const view of lookups) disposePublicView(view);
+ closePublicRuntime(publicContext);
+ closeIdentityView(context);
+ closeBrowserDatabase(database);
+ original.close();
+ }
+ };
+}
diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs
@@ -454,7 +454,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
const f = await fixture(t);
const files = await f.audit();
// Exact eleven-route module/page/static admission; CSS stays once-imported.
- assert.equal(files.length, 54);
+ assert.equal(files.length, 55);
// The actual SDK payload crosses the reader scratch boundary; a reused
// scratch buffer must still preserve every compiler/static byte exactly.
const sizes = await Promise.all(
@@ -738,7 +738,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
assert.ok(Buffer.byteLength(expanded) > 64 * 1024);
await writeFile(file, expanded);
await refresh(f);
- assert.equal((await f.audit()).length, 54);
+ assert.equal((await f.audit()).length, 55);
}
);
@@ -1300,7 +1300,9 @@ import { auditOutput } from '../../tools/check-output.mjs';
'src/lib/components/ListingEditor.svelte',
'src/lib/publishing/listing-editor.ts',
'src/lib/components/ListingReview.svelte',
- 'src/lib/publishing/editor-workflow.ts'
+ 'src/lib/publishing/editor-workflow.ts',
+ 'src/lib/components/ConflictNotice.svelte',
+ 'src/lib/publishing/edit-source.ts'
]) {
await check(
'listing editor rejects changed owned producer ' + producer,
diff --git a/web/tests/unit/edit-source.test.ts b/web/tests/unit/edit-source.test.ts
@@ -0,0 +1,37 @@
+import { expect, it } from 'vitest';
+import { render } from 'svelte/server';
+import ConflictNotice from '../../src/lib/components/ConflictNotice.svelte';
+import {
+ openOwnedEditSource,
+ ownedEditSourceSnapshot,
+ authorizeOwnedEditSource,
+ closeOwnedEditSource,
+ type OwnedEditSource
+} from '../../src/lib/publishing/edit-source.ts';
+import type { PublicPublicationRepository } from '../../src/lib/persistence/public-publications.ts';
+import type { IdentityViewContext } from '../../src/lib/runtime/view-context.ts';
+it('HCP118 copied repositories and unmounted identities cannot adopt a remote source', async () => {
+ expect(
+ await openOwnedEditSource(
+ {} as PublicPublicationRepository,
+ {} as IdentityViewContext,
+ 'untrusted'
+ )
+ ).toBeUndefined();
+});
+it('HCP118 copied ready snapshots cannot authorize editing or supply current/proposed authority', () => {
+ const copied = {
+ status: 'ready',
+ owner: '0'.repeat(64)
+ } as unknown as OwnedEditSource;
+ expect(ownedEditSourceSnapshot(copied)).toBeUndefined();
+ expect(authorizeOwnedEditSource(copied)).toBeUndefined();
+ expect(
+ render(ConflictNotice, { props: { source: copied } }).body
+ ).not.toContain('This listing changed elsewhere');
+});
+it('HCP118 closing copied or absent custody never manufactures readiness', () => {
+ const copied = {} as OwnedEditSource;
+ closeOwnedEditSource(copied);
+ expect(authorizeOwnedEditSource(copied)).toBeUndefined();
+});
diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs
@@ -639,9 +639,31 @@ async function listingEditorAdmission(web) {
'src/lib/publishing/editor-workflow.ts':
'5bc8827c5ff167e0974f03a87e4e9db350e42f30c511f199b785c30ad365d838'
};
+ /** @type {Record<string,string>} */
+ const editProducers = {
+ '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':
+ '3b1d6248c256ce02a668a2c92654816dd0c2659b7b430d5e1d3aeba6f9326bfa',
+ 'src/lib/publishing/listing-editor.ts':
+ 'fa2c698892b820f10adc0c816641da6a2c40b5cfc3df8db2880f61659d81b4ec',
+ 'src/lib/components/ListingReview.svelte':
+ 'bf4e6bf0fc76fa12672fabc441e1058d73c1f281a0a560aeafbdaa2aa36f6f90',
+ 'src/lib/publishing/editor-workflow.ts':
+ '5bc8827c5ff167e0974f03a87e4e9db350e42f30c511f199b785c30ad365d838',
+ 'src/lib/components/ConflictNotice.svelte':
+ 'f0a71cab9e8f1f12a3421402e3bc3b2f96c2ddb35ad8949c6e9599b850c3a17c',
+ 'src/lib/publishing/edit-source.ts':
+ '985634e4c4eb2cd12839409552b1c56cd518021d4f031166a3c1ab8c4a0e7eff'
+ };
let historical = true,
current = true,
- reviewed = true;
+ reviewed = true,
+ editing = true;
for (const [name, pin] of Object.entries(producers)) {
const bytes = await readOwned(web, name);
publicText(bytes);
@@ -649,6 +671,7 @@ async function listingEditorAdmission(web) {
historical = historical && actual === pin;
current = current && actual === continuity[name];
reviewed = reviewed && actual === reviewProducers[name];
+ editing = editing && actual === editProducers[name];
}
if (reviewed) {
for (const name of [
@@ -663,6 +686,22 @@ async function listingEditorAdmission(web) {
reviewProducers[name];
}
}
+ if (editing) {
+ for (const name of [
+ 'src/lib/components/ListingReview.svelte',
+ 'src/lib/publishing/editor-workflow.ts',
+ 'src/lib/components/ConflictNotice.svelte',
+ 'src/lib/publishing/edit-source.ts'
+ ]) {
+ const bytes = await readOwned(web, name);
+ publicText(bytes);
+ editing =
+ editing &&
+ createHash('sha256').update(bytes).digest('hex') ===
+ editProducers[name];
+ }
+ }
+ if (editing) return 'edit-source';
if (!historical && !current && !reviewed)
throw new Error('Invalid owned listing editor source');
if (reviewed) return 'review';
@@ -862,7 +901,8 @@ 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 hasListingReview = hasListingEditor === 'review';
+ const hasListingEdit = hasListingEditor === 'edit-source';
+ const hasListingReview = hasListingEditor === 'review' || hasListingEdit;
const hasListingContinuity =
hasListingEditor === 'continuity' || hasListingReview;
const identityCompilerModule = hasListingEditor
@@ -976,6 +1016,7 @@ export async function auditOutput(webDirectory) {
])
names.add(name);
}
+ if (hasListingEdit) names.add('resolve-head');
const admitted = new Map([['build-info.json', expectedMetadata]]);
const seen = new Set();
for (const [key, record] of Object.entries(manifest)) {
@@ -2646,6 +2687,89 @@ export async function auditOutput(webDirectory) {
'read'
]
};
+ if (hasListingEdit)
+ Object.assign(expected, {
+ 'nodes/5': {
+ file: '_app/immutable/nodes/5.HASH.js',
+ name: 'nodes/5',
+ src: '.svelte-kit/generated/build/client-optimized/nodes/5.js',
+ isEntry: true,
+ imports: [
+ 'public-key',
+ 'public-runtime',
+ 'references',
+ 'client',
+ 'Button',
+ 'client.svelte',
+ 'state',
+ 'legacy',
+ 'inbox-view',
+ 'InboxStatus',
+ 'resolve-head',
+ 'MessageComposer'
+ ]
+ },
+ 'nodes/9': {
+ file: '_app/immutable/nodes/9.HASH.js',
+ name: 'nodes/9',
+ src: '.svelte-kit/generated/build/client-optimized/nodes/9.js',
+ isEntry: true,
+ imports: [
+ 'public-runtime',
+ 'references',
+ 'client',
+ 'Button',
+ 'client.svelte',
+ 'navigation',
+ 'state',
+ 'Disclosure',
+ 'SearchForm',
+ 'routes',
+ 'resolve-head',
+ 'publishers'
+ ]
+ },
+ 'resolve-head': {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'resolve-head',
+ imports: ['public-runtime', 'Button', 'read']
+ },
+ ListingEditor: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'ListingEditor',
+ imports: [
+ 'public-key',
+ 'public-runtime',
+ 'references',
+ 'client',
+ 'Button',
+ 'CapabilityGate',
+ 'InboxSetup',
+ 'read',
+ 'resolve-head'
+ ]
+ },
+ MessageComposer: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'MessageComposer',
+ imports: [
+ 'public-key',
+ 'public-runtime',
+ 'references',
+ 'client',
+ 'Button',
+ 'navigation',
+ 'inbox-view',
+ 'resolve-head',
+ 'publishers'
+ ]
+ },
+ publishers: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'publishers',
+ imports: ['public-key', 'public-runtime', 'Button', 'resolve-head']
+ }
+ });
for (const record of Object.values(manifest)) {
const actual = { ...record };
actual.file = actual.file.includes('/chunks/')