commit f4cfa256a458741742252a31fc86a1b850d751b4
parent 675fc297233682acc94c657ef33856cbdb8ad11e
Author: triesap <tyson@radroots.org>
Date: Sat, 10 Oct 2026 03:05:34 +0000
publishing: persist verified signed listings before relay effects (HCP-111)
Diffstat:
9 files changed, 1253 insertions(+), 5 deletions(-)
diff --git a/web/src/lib/persistence/artifact-records.ts b/web/src/lib/persistence/artifact-records.ts
@@ -155,6 +155,26 @@ export function preparePreferenceSigningTransition(
return failed('invalid_record');
return retain(base, { ...base.row, revision: 1 });
}
+// The acknowledged unsigned revision1 records an original listing attempt.
+// It cannot be reset into permission to prompt again after page/ack loss.
+export function preparePublicListingSigningTransition(
+ record: PublicRecordHandle,
+ owner: unknown,
+ id: unknown
+): Result<PublicOperationTransition> {
+ const base = baseOf(record, owner, id);
+ if (
+ !base ||
+ base.row.family !== 'public_operation' ||
+ base.row.source.type !== 'draft' ||
+ base.row.capture.kind !== 30402 ||
+ base.row.revision !== 0 ||
+ base.row.artifact !== null ||
+ base.row.receipts.length !== 0
+ )
+ return failed('invalid_record');
+ return retain(base, { ...base.row, revision: 1 });
+}
export function preparePublicArtifactTransition(
record: PublicRecordHandle,
owner: unknown,
diff --git a/web/src/lib/persistence/public-publications.ts b/web/src/lib/persistence/public-publications.ts
@@ -72,6 +72,13 @@ export function publicPublicationOwner(
): string | undefined {
return scopeOf(repository)?.owner;
}
+// Original same-database quota custody only; it does not mint an identity,
+// extension approval, lock lease or public network capability.
+export function publicPublicationQuotaRepository(
+ repository: PublicPublicationRepository
+): PublicQuotaRepository | undefined {
+ return scopeOf(repository)?.quota;
+}
export type PublicListingSave =
| Readonly<{ status: 'saved' | 'existing'; record: PublicRecordHandle }>
| Readonly<{ status: PublicQuotaFailure | 'busy' }>;
diff --git a/web/src/lib/publishing/new-listing-readiness.ts b/web/src/lib/publishing/new-listing-readiness.ts
@@ -23,6 +23,7 @@ type Ownership = Readonly<{
identity: IdentitySession;
policy: RelayPolicy;
current(this: void): boolean;
+ signingCurrent(this: void): boolean;
}>;
const reviews = new WeakMap<
NewListingReadiness,
@@ -96,7 +97,13 @@ function sample(identity: IdentitySession, setup: InboxSetupView | undefined) {
!inboxResolverCurrentAfterSample(own.resolver)
)
return;
- return { actor, own, privateOwner, preferenceId: final.knownBase.id };
+ return {
+ actor,
+ own,
+ privateOwner,
+ preferenceId: final.knownBase.id,
+ accessCurrent: () => access?.current() ?? false
+ };
} catch {
return;
}
@@ -126,7 +133,38 @@ export function captureNewListingReadiness(
if (review !== 'reviewed_new_listing_inbox') return;
const captured = sample(identity, setup);
if (!captured) return;
+ const capturedResolver = captured.own.resolver;
+ if (!capturedResolver) return;
let active = true;
+ // Continuity of an already admitted original signing action. Reacquiring
+ // messaging capability during that action would reject its own busy prompt.
+ // This checks retained original generations/access, never admits a new action.
+ const signingCurrent = () => {
+ const actual = inboxSetupViewOwnership(setup);
+ const state = inboxSetupViewSnapshot(setup);
+ const resolved = inboxResolutionSnapshot(capturedResolver);
+ return (
+ active &&
+ captured.actor.current() &&
+ captured.own.current() &&
+ captured.privateOwner.current() &&
+ captured.accessCurrent() &&
+ !!actual?.current() &&
+ actual.identity === captured.own.identity &&
+ actual.policy === captured.own.policy &&
+ actual.session === captured.own.session &&
+ actual.resolver === captured.own.resolver &&
+ !state.busy &&
+ state.setupComplete &&
+ resolved.status === 'ready' &&
+ resolved.author === captured.actor.owner &&
+ resolved.knownBase?.id === captured.preferenceId &&
+ inboxResolverCurrentAfterSample(capturedResolver) &&
+ active &&
+ captured.actor.current() &&
+ captured.privateOwner.current()
+ );
+ };
const current = () => {
if (
!active ||
@@ -157,7 +195,8 @@ export function captureNewListingReadiness(
owner: captured.actor.owner,
identity,
policy: captured.own.policy,
- current
+ current,
+ signingCurrent
},
close: () => {
active = false;
diff --git a/web/src/lib/publishing/prepare-listing.ts b/web/src/lib/publishing/prepare-listing.ts
@@ -264,6 +264,21 @@ export function listingReviewSnapshot(
const value = reviews.get(review);
return value ? (JSON.parse(value.previewWire) as ListingPreview) : undefined;
}
+// Internal original custody, not a signing or transport permission. The later
+// controller must reread the persisted intent and obtain its own effect lease.
+export function listingReviewOwnership(review: ListingReview) {
+ const original = reviews.get(review);
+ const ready = original && newListingReadinessOwnership(original.readiness);
+ return original && ready && original.current()
+ ? {
+ repository: original.repository,
+ record: original.record,
+ command: original.command,
+ readiness: ready,
+ current: original.current
+ }
+ : undefined;
+}
// One original review deduplicates simultaneous clicks. Failed/uncertain work
// remains the same capture for later explicit retry; no fresh ID/time/template.
export function reserveNewListing(
diff --git a/web/src/lib/publishing/sign-listing.ts b/web/src/lib/publishing/sign-listing.ts
@@ -0,0 +1,421 @@
+import {
+ listingReviewOwnership,
+ type ListingReview
+} from './prepare-listing.ts';
+import {
+ publicPublicationQuotaRepository,
+ readPublicListingIntent
+} from '../persistence/public-publications.ts';
+import {
+ decodePublicRecord,
+ publicRecordSnapshot,
+ publicRecordWire,
+ type PublicRecordHandle
+} from '../persistence/records.ts';
+import {
+ preparePublicListingSigningTransition,
+ preparePublicArtifactTransition,
+ publicTransitionSnapshot,
+ type CapturedArtifact
+} from '../persistence/artifact-records.ts';
+import {
+ commitPublicOperationTransition,
+ observePublicOperationTransition
+} from '../persistence/quota.ts';
+import {
+ captureIdentityPublicOperation,
+ identityPublicOperationOwnership,
+ identityPublicOperationSnapshot,
+ recheckIdentityOwner,
+ signIdentityPublicOperation,
+ stopIdentityPublicOperation,
+ type IdentityPublicOperation
+} from '../runtime/identity-session.ts';
+import { runCapturedPublicEffect } from '../runtime/effect-ownership.ts';
+
+declare const signingBrand: unique symbol;
+declare const publicationBrand: unique symbol;
+export type ListingSigning = Readonly<{ [signingBrand]: true }>;
+export type ListingPublication = Readonly<{ [publicationBrand]: true }>;
+type Ownership = NonNullable<ReturnType<typeof listingReviewOwnership>>;
+type Model = Readonly<{
+ original: Ownership;
+ getOperation(): IdentityPublicOperation | undefined;
+ setOperation(value: IdentityPublicOperation): void;
+ getAttempted(): boolean;
+ setAttempted(): void;
+ getStopped(): boolean;
+ stop(): void;
+ getSigning(): boolean;
+ startSigning(): void;
+ finishSigning(): void;
+ getMarked(): PublicRecordHandle | undefined;
+ setMarked(value: PublicRecordHandle): void;
+ getArtifact(): CapturedArtifact | undefined;
+ setArtifact(value: CapturedArtifact): void;
+ getPublication(): ListingPublication | undefined;
+ setPublication(value: ListingPublication): void;
+}>;
+function createModel(original: Ownership): Model {
+ let operation: IdentityPublicOperation | undefined;
+ let signing = false;
+ let attempted = false,
+ stopped = false;
+ let marked: PublicRecordHandle | undefined;
+ let artifact: CapturedArtifact | undefined;
+ let publication: ListingPublication | undefined;
+ return {
+ original,
+ getOperation: () => operation,
+ setOperation: (value) => {
+ operation = value;
+ },
+ getAttempted: () => attempted,
+ setAttempted: () => {
+ attempted = true;
+ },
+ getStopped: () => stopped,
+ stop: () => {
+ stopped = true;
+ },
+ getSigning: () => signing,
+ startSigning: () => {
+ signing = true;
+ },
+ finishSigning: () => {
+ signing = false;
+ },
+ getMarked: () => marked,
+ setMarked: (value) => {
+ marked = value;
+ },
+ getArtifact: () => artifact,
+ setArtifact: (value) => {
+ artifact = value;
+ },
+ getPublication: () => publication,
+ setPublication: (value) => {
+ publication = value;
+ }
+ };
+}
+type Publication = Readonly<{
+ model: Model;
+ recordWire: string;
+ wire: string;
+ owner: string;
+ command: string;
+ hash: string;
+ targets: readonly string[];
+ policyFingerprint: string;
+}>;
+const signings = new WeakMap<ListingSigning, Model>();
+const commands = new WeakMap<ListingReview, ListingSigning>();
+const pending = new WeakMap<ListingSigning, Promise<ListingSigningResult>>();
+const publications = new WeakMap<ListingPublication, Publication>();
+export type ListingSigningResult =
+ | Readonly<{ status: 'prepared'; publication: ListingPublication }>
+ | Readonly<{
+ status:
+ 'invalid' | 'unavailable' | 'conflict' | 'unknown' | 'busy' | 'stopped';
+ }>;
+
+function current(model: Model): boolean {
+ const operation = model.getOperation();
+ return (
+ !model.getStopped() &&
+ (model.getSigning()
+ ? model.original.readiness.signingCurrent() &&
+ !!publicPublicationQuotaRepository(model.original.repository)
+ : model.original.current()) &&
+ (!operation ||
+ !!identityPublicOperationOwnership(
+ model.original.readiness.identity,
+ operation
+ ))
+ );
+}
+export function beginListingSigning(
+ review: ListingReview,
+ consent: unknown
+): ListingSigning | undefined {
+ if (consent !== 'sign_reviewed_listing') return;
+ const original = listingReviewOwnership(review);
+ if (!original || !publicPublicationQuotaRepository(original.repository))
+ return;
+ const existing = commands.get(review);
+ if (existing) return existing;
+ const token = Object.freeze({}) as ListingSigning;
+ signings.set(token, createModel(original));
+ commands.set(review, token);
+ return token;
+}
+export function listingSigningSnapshot(token: ListingSigning) {
+ const model = signings.get(token);
+ if (!model) return;
+ const original = model.original;
+ const row = publicRecordSnapshot(
+ original.record,
+ original.readiness.owner,
+ original.command
+ );
+ if (!row || row.family !== 'public_operation') return;
+ const heldOperation = model.getOperation();
+ const operation =
+ heldOperation &&
+ identityPublicOperationSnapshot(original.readiness.identity, heldOperation);
+ return {
+ owner: row.owner,
+ command: row.id,
+ hash: row.capture.hash,
+ stopped: model.getStopped(),
+ attempted: model.getAttempted(),
+ lateAvailable: operation?.lateAvailable ?? false
+ };
+}
+// Detached disclosure is never a send capability. HCP112 must independently
+// admit the original plan, reread storage and obtain final network ownership.
+export function listingPublicationSnapshot(token: ListingPublication) {
+ const value = publications.get(token);
+ if (!value || !current(value.model)) return;
+ return {
+ owner: value.owner,
+ command: value.command,
+ hash: value.hash,
+ wire: value.wire,
+ targets: value.targets.slice(),
+ policyFingerprint: value.policyFingerprint
+ };
+}
+async function exactStored(
+ model: Model,
+ expected: PublicRecordHandle
+): Promise<boolean> {
+ const original = model.original,
+ owner = original.readiness.owner;
+ const read = await readPublicListingIntent(
+ original.repository,
+ original.command
+ );
+ return (
+ current(model) &&
+ read.status === 'found' &&
+ publicRecordWire(read.record, owner, original.command) ===
+ publicRecordWire(expected, owner, original.command)
+ );
+}
+async function persist(model: Model): Promise<ListingSigningResult> {
+ const original = model.original,
+ owner = original.readiness.owner;
+ const quota = publicPublicationQuotaRepository(original.repository);
+ const marked = model.getMarked(),
+ artifact = model.getArtifact();
+ if (!quota || !marked || !artifact || !current(model))
+ return { status: 'unavailable' };
+ const transition = preparePublicArtifactTransition(
+ marked,
+ owner,
+ original.command,
+ artifact
+ );
+ if (!transition.ok) return { status: 'conflict' };
+ const proposed = publicTransitionSnapshot(
+ transition.value,
+ owner,
+ original.command
+ );
+ if (!proposed) return { status: 'invalid' };
+ const decoded = decodePublicRecord(
+ proposed.nextWire,
+ owner,
+ original.command
+ );
+ if (!decoded.ok) return { status: 'invalid' };
+ if (!current(model)) return { status: 'stopped' };
+ const saved = await commitPublicOperationTransition(quota, transition.value);
+ if (!current(model)) return { status: 'unknown' };
+ if (!saved.ok) {
+ if (saved.reason !== 'unknown_completion')
+ return {
+ status: saved.reason === 'conflict' ? 'conflict' : 'unavailable'
+ };
+ const observed = await observePublicOperationTransition(
+ quota,
+ transition.value
+ );
+ if (observed.state !== 'committed' || !current(model))
+ return { status: observed.state === 'conflict' ? 'conflict' : 'unknown' };
+ }
+ if (!(await exactStored(model, decoded.value))) return { status: 'unknown' };
+ const row = publicRecordSnapshot(decoded.value, owner, original.command);
+ if (!row || row.family !== 'public_operation' || !row.artifact)
+ return { status: 'invalid' };
+ const token = Object.freeze({}) as ListingPublication;
+ publications.set(token, {
+ model,
+ recordWire: proposed.nextWire,
+ wire: row.artifact.wire,
+ owner,
+ command: row.id,
+ hash: row.artifact.eventId,
+ targets: row.capture.targets.slice(),
+ policyFingerprint: row.capture.policyFingerprint
+ });
+ model.setPublication(token);
+ return { status: 'prepared', publication: token };
+}
+async function execute(model: Model): Promise<ListingSigningResult> {
+ try {
+ const original = model.original,
+ identity = original.readiness.identity,
+ owner = original.readiness.owner;
+ const quota = publicPublicationQuotaRepository(original.repository);
+ if (
+ !quota ||
+ !current(model) ||
+ typeof window === 'undefined' ||
+ !navigator.locks?.request
+ )
+ return { status: 'unavailable' };
+ const publication = model.getPublication();
+ if (publication) {
+ const value = publications.get(publication);
+ if (!value) return { status: 'invalid' };
+ const rechecked = await recheckIdentityOwner(identity);
+ if (!current(model) || rechecked.state === 'guest')
+ return { status: 'unavailable' };
+ const read = await readPublicListingIntent(
+ original.repository,
+ original.command
+ );
+ if (
+ !current(model) ||
+ read.status !== 'found' ||
+ publicRecordWire(read.record, owner, original.command) !==
+ value.recordWire
+ )
+ return { status: 'conflict' };
+ return { status: 'prepared', publication };
+ }
+ if (model.getArtifact()) {
+ await recheckIdentityOwner(identity);
+ if (!current(model)) return { status: 'unavailable' };
+ // Retained exact verified artifact retry is storage-only; never a prompt.
+ return await navigator.locks.request(
+ 'harvestcircle:owner:' + owner,
+ { mode: 'exclusive', ifAvailable: true },
+ (lock) =>
+ lock ? persist(model) : Promise.resolve({ status: 'busy' as const })
+ );
+ }
+ if (model.getAttempted()) return { status: 'unknown' };
+ if (!(await exactStored(model, original.record)))
+ return { status: 'conflict' };
+ const operation = captureIdentityPublicOperation(
+ identity,
+ original.record,
+ original.command,
+ 'reviewed_captured_operation'
+ );
+ if (!operation) return { status: 'unavailable' };
+ model.setOperation(operation);
+ const ownership = identityPublicOperationOwnership(identity, operation);
+ if (!ownership || !current(model)) return { status: 'unavailable' };
+ const result = await runCapturedPublicEffect(
+ quota,
+ original.record,
+ original.command,
+ { ...ownership, current: () => current(model) && ownership.current() },
+ 'reviewed_prepared_listing_operation',
+ async (lease): Promise<ListingSigningResult> => {
+ const marker = preparePublicListingSigningTransition(
+ original.record,
+ owner,
+ original.command
+ );
+ if (!marker.ok || !current(model)) return { status: 'invalid' };
+ const next = publicTransitionSnapshot(
+ marker.value,
+ owner,
+ original.command
+ );
+ if (!next) return { status: 'invalid' };
+ model.setAttempted();
+ const saved = await commitPublicOperationTransition(
+ quota,
+ marker.value
+ );
+ if (!saved.ok || !current(model))
+ return {
+ status:
+ saved.ok || saved.reason === 'unknown_completion'
+ ? 'unknown'
+ : 'unavailable'
+ };
+ const decoded = decodePublicRecord(
+ next.nextWire,
+ owner,
+ original.command
+ );
+ if (!decoded.ok || !(await exactStored(model, decoded.value)))
+ return { status: 'unknown' };
+ model.setMarked(decoded.value);
+ model.startSigning();
+ let signed;
+ try {
+ signed = await signIdentityPublicOperation(
+ identity,
+ operation,
+ lease
+ );
+ } finally {
+ model.finishSigning();
+ }
+ if (signed.status !== 'signed' || !current(model))
+ return {
+ status:
+ signed.status === 'unknown' || !current(model)
+ ? 'unknown'
+ : 'invalid'
+ };
+ model.setArtifact(signed.artifact);
+ return await persist(model);
+ }
+ );
+ return result.status === 'completed'
+ ? result.value
+ : {
+ status:
+ result.status === 'busy'
+ ? 'busy'
+ : result.status === 'unknown' || result.status === 'retained'
+ ? 'unknown'
+ : 'unavailable'
+ };
+ } catch {
+ return { status: 'unknown' };
+ }
+}
+export function runListingSigning(
+ token: ListingSigning,
+ consent: unknown
+): Promise<ListingSigningResult> {
+ const model = signings.get(token);
+ if (!model || consent !== 'sign_reviewed_listing')
+ return Promise.resolve({ status: 'invalid' });
+ const active = pending.get(token);
+ if (active) return active;
+ const work = execute(model).finally(() => {
+ if (pending.get(token) === work) pending.delete(token);
+ });
+ pending.set(token, work);
+ return work;
+}
+export function stopListingSigning(token: ListingSigning): void {
+ const model = signings.get(token);
+ if (!model) return;
+ model.stop();
+ const operation = model.getOperation();
+ if (operation)
+ stopIdentityPublicOperation(model.original.readiness.identity, operation);
+}
diff --git a/web/src/lib/runtime/effect-ownership.ts b/web/src/lib/runtime/effect-ownership.ts
@@ -74,6 +74,7 @@ export async function runCapturedPublicEffect<T>(
owner && id ? publicRecordWire(handle, owner, id) : undefined;
if (
(review !== 'reviewed_captured_operation' &&
+ review !== 'reviewed_prepared_listing_operation' &&
review !== 'reviewed_prepared_preference_operation' &&
review !== 'reviewed_stored_preference_retry') ||
!owner ||
@@ -88,9 +89,18 @@ export async function runCapturedPublicEffect<T>(
typeof work !== 'function'
)
return { status: 'invalid' };
- const preferenceMode = review !== 'reviewed_captured_operation';
+ const listingMode = review === 'reviewed_prepared_listing_operation';
+ const preferenceMode =
+ review !== 'reviewed_captured_operation' && !listingMode;
const storedRetry = review === 'reviewed_stored_preference_retry';
if (
+ listingMode &&
+ (row.family !== 'public_operation' ||
+ row.capture.kind !== 30402 ||
+ row.source.type !== 'draft')
+ )
+ return { status: 'invalid' };
+ if (
preferenceMode &&
(row.family !== 'preference_operation' || row.capture.kind !== 10050)
)
@@ -135,9 +145,12 @@ export async function runCapturedPublicEffect<T>(
if (claimed.value.state === 'existing') {
const stored = publicRecordSnapshot(original, owner, id);
const prepared =
- preferenceMode &&
!storedRetry &&
- stored?.family === 'preference_operation' &&
+ ((preferenceMode && stored?.family === 'preference_operation') ||
+ (listingMode &&
+ stored?.family === 'public_operation' &&
+ stored.capture.kind === 30402 &&
+ stored.source.type === 'draft')) &&
stored.revision === 0 &&
stored.artifact === null;
const retry =
diff --git a/web/tests/e2e/harness/sign-listing.ts b/web/tests/e2e/harness/sign-listing.ts
@@ -0,0 +1,507 @@
+import { makeFixture, type Mode } from './approved-signing.ts';
+import { fixturePolicy, discovery, inbox } from './inbox-setup.ts';
+import {
+ createIdentitySession,
+ connectIdentity,
+ probeIdentityMessaging,
+ disconnectIdentity
+} from '../../../src/lib/runtime/identity-session.ts';
+import {
+ createPublicScheduler,
+ createPublicRun,
+ openInboxRequest,
+ closePublicScheduler
+} from '../../../src/lib/nostr/request-scope.ts';
+import { createInboxResolver } from '../../../src/lib/messaging/resolve-inbox.ts';
+import {
+ createInboxSetupView,
+ checkInboxSetupView,
+ unlockInboxSetupView,
+ closeInboxSetupView
+} from '../../../src/lib/messaging/inbox-setup-view.ts';
+import { captureNewListingReadiness } from '../../../src/lib/publishing/new-listing-readiness.ts';
+import {
+ openBrowserDatabase,
+ closeBrowserDatabase,
+ browserDatabaseTransaction
+} from '../../../src/lib/persistence/database.ts';
+import {
+ createPublicPublicationRepository,
+ publicPublicationDraftRepository,
+ readPublicListingIntent
+} from '../../../src/lib/persistence/public-publications.ts';
+import {
+ createPublicDraftController,
+ closePublicDraftController
+} from '../../../src/lib/publishing/draft-controller.ts';
+import {
+ reviewNewListing,
+ reserveNewListing,
+ listingReviewSnapshot
+} from '../../../src/lib/publishing/prepare-listing.ts';
+import {
+ publicRecordSnapshot,
+ decodePublicRecord
+} from '../../../src/lib/persistence/records.ts';
+import type { PublicOperationRecord } from '../../../src/lib/contracts/local-records.ts';
+import {
+ beginListingSigning,
+ runListingSigning,
+ stopListingSigning,
+ listingSigningSnapshot,
+ listingPublicationSnapshot
+} from '../../../src/lib/publishing/sign-listing.ts';
+
+export async function createFixture() {
+ const signer = makeFixture(10050),
+ identity = createIdentitySession(),
+ policy = fixturePolicy();
+ const preference = signer.sign({
+ ...signer.template,
+ kind: 10050,
+ created_at: 100,
+ tags: [['relay', inbox]],
+ content: ''
+ });
+ const prior = Object.getOwnPropertyDescriptor(window, 'nostr');
+ let signs = 0,
+ keys = 0,
+ mode: Mode = 'exact',
+ observedOwner = signer.owner;
+ let beforeSign: (() => Promise<void>) | undefined;
+ Object.defineProperty(window, 'nostr', {
+ configurable: true,
+ value: {
+ getPublicKey: () => {
+ keys++;
+ return Promise.resolve(observedOwner);
+ },
+ signEvent: async (input: Parameters<typeof signer.sign>[0]) => {
+ signs++;
+ await beforeSign?.();
+ return signer.sign(input, mode);
+ },
+ nip44: {
+ encrypt: (_peer: string, text: string) =>
+ Promise.resolve('fixture:' + text),
+ decrypt: (_peer: string, text: string) => Promise.resolve(text.slice(8))
+ }
+ }
+ });
+ await connectIdentity(identity);
+ await probeIdentityMessaging(identity, 'reviewed_self_copy');
+ const scheduler = createPublicScheduler({
+ now: () => 0,
+ schedule: () => () => {}
+ });
+ const run = createPublicRun(scheduler, policy);
+ const resolver = createInboxResolver(
+ run,
+ signer.owner,
+ (next) =>
+ openInboxRequest(
+ run,
+ signer.owner,
+ (sink) => {
+ sink({
+ type: 'EVENT',
+ from: discovery,
+ id: 'fixture',
+ event: preference
+ });
+ sink({ type: 'EOSE', from: discovery, id: 'fixture' });
+ return () => {};
+ },
+ next
+ ),
+ () => true
+ );
+ // HC_TEST_ONLY_QUALIFICATION_PORT: original SDK owners, controlled exercised
+ // access observation; no real extension/operator/relay qualification.
+ const setup = createInboxSetupView({
+ identity,
+ policy,
+ lookup: () => Promise.resolve(resolver),
+ observeAccess: (context) => ({
+ ...context,
+ readTargets: context.readTargets.slice(),
+ archiveTargets: context.archiveTargets.slice(),
+ receive: 'qualified_exercised',
+ archive: 'qualified_exercised',
+ current: () => true
+ })
+ });
+ if (!setup) throw Error('original setup missing');
+ await checkInboxSetupView(setup);
+ await unlockInboxSetupView(setup);
+ const ready = captureNewListingReadiness(
+ identity,
+ setup,
+ 'reviewed_new_listing_inbox'
+ );
+ if (!ready) throw Error('original readiness missing');
+ const opened = await openBrowserDatabase();
+ if (opened.state !== 'ready') throw Error(opened.reason);
+ const database = opened.owner,
+ repository = createPublicPublicationRepository(database, signer.owner);
+ const drafts = repository && publicPublicationDraftRepository(repository);
+ if (!repository || !drafts) throw Error('original repository missing');
+ const originalRepository = repository;
+ const controller = await createPublicDraftController(drafts, {
+ title: 'Carrots',
+ description: 'Exact signed description',
+ location: 'Local farm',
+ amount: '2',
+ currency: 'USD',
+ unit: 'kg',
+ quantity: '',
+ contactType: '',
+ contactValue: ''
+ });
+ if (!controller) throw Error('original controller missing');
+ const command = crypto.randomUUID();
+ const reviewed = await reviewNewListing(
+ repository,
+ controller,
+ ready,
+ command,
+ 'reviewed_new_listing'
+ );
+ if (reviewed.status !== 'review') throw Error(reviewed.reason);
+ const original = reviewed.review,
+ preview = listingReviewSnapshot(original);
+ if (!preview) throw Error('original preview missing');
+ const reserved = await reserveNewListing(
+ original,
+ 'publish_reviewed_listing'
+ );
+ if (reserved.status !== 'saved') throw Error(reserved.status);
+ const signing = beginListingSigning(original, 'sign_reviewed_listing');
+ if (!signing) throw Error('original signing missing');
+ const originalSigning = signing;
+ async function stored() {
+ const read = await readPublicListingIntent(originalRepository, command);
+ const row =
+ read.status === 'found' &&
+ publicRecordSnapshot(read.record, signer.owner, command);
+ if (!row || row.family !== 'public_operation')
+ throw Error('original stored command missing');
+ return row;
+ }
+ function invoke() {
+ return runListingSigning(originalSigning, 'sign_reviewed_listing');
+ }
+ return {
+ async exact() {
+ const a = invoke(),
+ b = invoke(),
+ same = a === b;
+ const result = await a,
+ row = await stored();
+ const plan =
+ result.status === 'prepared'
+ ? listingPublicationSnapshot(result.publication)
+ : undefined;
+ const retry = await invoke();
+ return {
+ status: result.status,
+ same,
+ signatures: signs,
+ keys,
+ revision: row.revision,
+ artifact: row.artifact,
+ plan,
+ expectedHash: preview.expectedHash,
+ originalCapture: row.capture.wire === preview.templateWire,
+ retry: retry.status,
+ sameArtifact:
+ retry.status === 'prepared' &&
+ listingPublicationSnapshot(retry.publication)?.wire === plan?.wire
+ };
+ },
+ async wrong(next: Mode) {
+ mode = next;
+ const result = await invoke(),
+ row = await stored();
+ const retry = await invoke();
+ return {
+ status: result.status,
+ signatures: signs,
+ revision: row.revision,
+ artifact: row.artifact,
+ retry: retry.status,
+ exposed: result.status === 'prepared'
+ };
+ },
+ async changedKey() {
+ const other = makeFixture(10050);
+ observedOwner = other.owner;
+ other.close();
+ const result = await invoke(),
+ row = await stored();
+ return {
+ status: result.status,
+ signatures: signs,
+ keys,
+ revision: row.revision,
+ artifact: row.artifact,
+ exposed: result.status === 'prepared'
+ };
+ },
+ async late(logout: boolean, retireSetup = false) {
+ let release = () => {},
+ entered = () => {};
+ const enteredPromise = new Promise<void>((resolve) => {
+ entered = resolve;
+ });
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ beforeSign = () => {
+ entered();
+ return held;
+ };
+ const pending = invoke();
+ await enteredPromise;
+ if (retireSetup) closeInboxSetupView(setup);
+ else stopListingSigning(originalSigning);
+ if (logout) disconnectIdentity(identity);
+ release();
+ const result = await pending,
+ row = await stored();
+ return {
+ status: result.status,
+ signatures: signs,
+ revision: row.revision,
+ artifact: row.artifact,
+ exposed: result.status === 'prepared',
+ snapshot: listingSigningSnapshot(originalSigning),
+ originalOwner: signer.owner,
+ expectedHash: preview.expectedHash,
+ command
+ };
+ },
+ async fault(
+ revision: 1 | 2,
+ unknown: boolean,
+ unavailableReadback = false,
+ tamper: 'none' | 'valid' | 'corrupt' = 'none'
+ ) {
+ const put = Object.getOwnPropertyDescriptor(
+ IDBObjectStore.prototype,
+ 'put'
+ ),
+ abort = Object.getOwnPropertyDescriptor(
+ IDBTransaction.prototype,
+ 'abort'
+ );
+ const get = Object.getOwnPropertyDescriptor(
+ IDBObjectStore.prototype,
+ 'get'
+ );
+ if (!put || !abort || !get) throw Error('native descriptors missing');
+ const nativePut = put.value as IDBObjectStore['put'];
+ const nativeGet = get.value as IDBObjectStore['get'];
+ let faultPuts = 0,
+ nativePuts = 0;
+ Object.defineProperty(IDBObjectStore.prototype, 'put', {
+ ...put,
+ value: function (
+ this: IDBObjectStore,
+ ...args: Parameters<IDBObjectStore['put']>
+ ) {
+ const value: unknown = args[0];
+ const wire =
+ typeof value === 'object' &&
+ value &&
+ 'wire' in value &&
+ typeof value.wire === 'string'
+ ? value.wire
+ : undefined;
+ const row = wire
+ ? (JSON.parse(wire) as { revision: number })
+ : undefined;
+ if (this.name === 'public_operations' && row?.revision === revision) {
+ faultPuts++;
+ if (unknown) {
+ const request = nativePut.apply(this, args);
+ nativePuts++;
+ if (tamper !== 'none')
+ request.addEventListener('success', () => {
+ let changedWire = '{"schema":999}';
+ if (tamper === 'valid') {
+ const originalRow = JSON.parse(
+ wire!
+ ) as PublicOperationRecord;
+ const different = JSON.parse(
+ preview.templateWire
+ ) as typeof signer.template;
+ different.tags = different.tags.map((tag) =>
+ tag[0] === 'd' ? ['d', crypto.randomUUID()] : tag
+ );
+ const signed = signer.sign(different);
+ const templateWire = JSON.stringify({
+ pubkey: signed.pubkey,
+ kind: signed.kind,
+ created_at: signed.created_at,
+ tags: signed.tags,
+ content: signed.content
+ });
+ changedWire = JSON.stringify({
+ ...originalRow,
+ capture: {
+ ...originalRow.capture,
+ wire: templateWire,
+ hash: signed.id
+ },
+ artifact: {
+ eventId: signed.id,
+ wire: JSON.stringify(signed)
+ }
+ });
+ if (
+ !decodePublicRecord(changedWire, signer.owner, command).ok
+ )
+ throw Error('actual changed signed capture is not valid');
+ }
+ nativePut.call(this, {
+ owner: signer.owner,
+ id: command,
+ wire: changedWire
+ });
+ nativePuts++;
+ faultPuts++;
+ });
+ throw Error('HC_TEST_ONLY actual put lost acknowledgement');
+ }
+ this.transaction.abort();
+ throw Error('HC_TEST_ONLY actual definite rollback');
+ }
+ const request = nativePut.apply(this, args);
+ if (this.name === 'public_operations') nativePuts++;
+ return request;
+ }
+ });
+ if (unknown)
+ Object.defineProperty(IDBTransaction.prototype, 'abort', {
+ ...abort,
+ value() {
+ throw Error('HC_TEST_ONLY unavailable abort channel');
+ }
+ });
+ if (unavailableReadback)
+ Object.defineProperty(IDBObjectStore.prototype, 'get', {
+ ...get,
+ value: function (
+ this: IDBObjectStore,
+ ...args: Parameters<IDBObjectStore['get']>
+ ) {
+ if (this.name === 'public_operations' && faultPuts > 0)
+ throw Error(
+ 'HC_TEST_ONLY actual readback unavailable after committed signed artifact'
+ );
+ return nativeGet.apply(this, args);
+ }
+ });
+ let result;
+ try {
+ result = await invoke();
+ } finally {
+ Object.defineProperty(IDBObjectStore.prototype, 'put', put);
+ Object.defineProperty(IDBTransaction.prototype, 'abort', abort);
+ Object.defineProperty(IDBObjectStore.prototype, 'get', get);
+ }
+ const observed = await readPublicListingIntent(
+ originalRepository,
+ command
+ );
+ const row = tamper === 'corrupt' ? undefined : await stored();
+ let corruptWire: string | undefined;
+ if (tamper === 'corrupt')
+ corruptWire = await new Promise<string>((resolve, reject) => {
+ const tx = browserDatabaseTransaction(
+ database,
+ ['public_operations'],
+ 'readonly'
+ );
+ const request = tx
+ .objectStore('public_operations')
+ .get([signer.owner, command]);
+ let wire: string | undefined;
+ request.addEventListener('success', () => {
+ const raw: unknown = request.result;
+ if (
+ typeof raw === 'object' &&
+ raw &&
+ 'wire' in raw &&
+ typeof raw.wire === 'string'
+ )
+ wire = raw.wire;
+ });
+ tx.addEventListener('complete', () =>
+ wire === undefined
+ ? reject(Error('actual corrupt row missing'))
+ : resolve(wire)
+ );
+ tx.addEventListener('abort', () =>
+ reject(Error('actual raw read aborted'))
+ );
+ });
+ const plan =
+ result.status === 'prepared'
+ ? listingPublicationSnapshot(result.publication)
+ : undefined;
+ let retryStatus: string | undefined,
+ retryPuts = 0,
+ retryExact = false;
+ if (unavailableReadback || tamper !== 'none') {
+ Object.defineProperty(IDBObjectStore.prototype, 'put', {
+ ...put,
+ value: function (
+ this: IDBObjectStore,
+ ...args: Parameters<IDBObjectStore['put']>
+ ) {
+ if (this.name === 'public_operations') retryPuts++;
+ return nativePut.apply(this, args);
+ }
+ });
+ try {
+ const retry = await invoke();
+ retryStatus = retry.status;
+ retryExact =
+ retry.status === 'prepared' &&
+ listingPublicationSnapshot(retry.publication)?.wire ===
+ row?.artifact?.wire;
+ } finally {
+ Object.defineProperty(IDBObjectStore.prototype, 'put', put);
+ }
+ }
+ return {
+ status: result.status,
+ exposed: !!plan,
+ signatures: signs,
+ revision: row?.revision,
+ artifact: row?.artifact,
+ faultPuts,
+ nativePuts,
+ readStatus: observed.status,
+ corruptWire,
+ retryStatus,
+ retryPuts,
+ retryExact,
+ sameArtifact: !!plan && plan.wire === row?.artifact?.wire,
+ originalCapture: row?.capture.wire === preview.templateWire
+ };
+ },
+ close() {
+ closePublicDraftController(controller);
+ closeBrowserDatabase(database);
+ closeInboxSetupView(setup);
+ disconnectIdentity(identity);
+ closePublicScheduler(scheduler);
+ signer.close();
+ if (prior) Object.defineProperty(window, 'nostr', prior);
+ else Reflect.deleteProperty(window, 'nostr');
+ }
+ };
+}
diff --git a/web/tests/e2e/sign-listing.spec.ts b/web/tests/e2e/sign-listing.spec.ts
@@ -0,0 +1,200 @@
+import { expect, test } from '@playwright/test';
+import { build } from 'vite';
+import { fileURLToPath } from 'node:url';
+import { createStaticHarness } from '../integration/harness/static.ts';
+import type * as Fixture from './harness/sign-listing.ts';
+declare global {
+ interface Window {
+ hcp111: typeof Fixture;
+ hcp111Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>;
+ }
+}
+let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string;
+test.beforeAll(async () => {
+ server = await createStaticHarness();
+ const result = await build({
+ configFile: false,
+ logLevel: 'silent',
+ build: {
+ write: false,
+ minify: false,
+ lib: {
+ entry: fileURLToPath(
+ new URL('./harness/sign-listing.ts', import.meta.url)
+ ),
+ name: 'hcp111',
+ formats: ['iife']
+ }
+ }
+ });
+ const output = Array.isArray(result) ? result[0] : result;
+ if (!('output' in output)) throw Error('fixture bundle missing');
+ const chunks = output.output.filter((row) => row.type === 'chunk');
+ expect(chunks).toHaveLength(1);
+ bundle = chunks[0].code;
+});
+test.afterAll(async () => server.close());
+test.beforeEach(async ({ page }) => {
+ await page.goto(server.url + '/search');
+ await page.addScriptTag({ content: bundle });
+ await page.evaluate(async () => {
+ window.hcp111Fixture = await window.hcp111.createFixture();
+ });
+});
+test.afterEach(async ({ page }) => {
+ if (!page.isClosed())
+ await page.evaluate(() => window.hcp111Fixture?.close());
+});
+test('HCP111 original verified signed artifact commits before a typed plan and repeated clicks never re-sign', async ({
+ page
+}) => {
+ const r = await page.evaluate(() => window.hcp111Fixture.exact());
+ console.log('HCP111_DIAGNOSTIC_ACTUAL_ORIGINAL_RESULT', JSON.stringify(r));
+ expect(r.status).toBe('prepared');
+ expect(r.same).toBe(true);
+ expect(r.signatures).toBe(1);
+ expect(r.keys).toBeGreaterThan(1);
+ expect(r.revision).toBe(2);
+ expect(r.artifact?.eventId).toBe(r.expectedHash);
+ expect(r.plan?.wire).toBe(r.artifact?.wire);
+ expect(r.originalCapture).toBe(true);
+ expect(r.retry).toBe('prepared');
+ expect(r.sameArtifact).toBe(true);
+});
+for (const mode of [
+ 'author',
+ 'kind',
+ 'time',
+ 'tags',
+ 'content',
+ 'cached',
+ 'mutate'
+] as const)
+ test(`HCP111 actual signed changed ${mode} response never commits or exposes a plan`, async ({
+ page
+ }) => {
+ const r = await page.evaluate(
+ (mode) => window.hcp111Fixture.wrong(mode),
+ mode
+ );
+ expect(r.exposed).toBe(false);
+ expect(r.signatures).toBe(1);
+ expect(r.revision).toBe(1);
+ expect(r.artifact).toBeNull();
+ expect(r.retry).not.toBe('prepared');
+ });
+test('HCP111 changed actual fresh extension key stops signature and plan', async ({
+ page
+}) => {
+ const r = await page.evaluate(() => window.hcp111Fixture.changedKey());
+ expect(r.exposed).toBe(false);
+ expect(r.signatures).toBe(0);
+ expect(r.artifact).toBeNull();
+});
+for (const logout of [false, true])
+ test(`HCP111 held actual signature after Stop logout=${logout} remains original without artifact or plan`, async ({
+ page
+ }) => {
+ const r = await page.evaluate(
+ (logout) => window.hcp111Fixture.late(logout),
+ logout
+ );
+ expect(r.exposed).toBe(false);
+ expect(r.signatures).toBe(1);
+ expect(r.revision).toBe(1);
+ expect(r.artifact).toBeNull();
+ expect(r.snapshot?.owner).toBe(r.originalOwner);
+ expect(r.snapshot?.command).toBe(r.command);
+ expect(r.snapshot?.hash).toBe(r.expectedHash);
+ expect(r.snapshot?.lateAvailable).toBe(true);
+ });
+for (const revision of [1, 2] as const)
+ test(`HCP111 actual revision${revision} transaction abort stops the dependent effect`, async ({
+ page
+ }) => {
+ const r = await page.evaluate(
+ (revision) => window.hcp111Fixture.fault(revision, false),
+ revision
+ );
+ expect(r.exposed).toBe(false);
+ expect(r.faultPuts).toBe(1);
+ expect(r.revision).toBe(revision - 1);
+ expect(r.artifact).toBeNull();
+ expect(r.signatures).toBe(revision - 1);
+ expect(r.originalCapture).toBe(true);
+ });
+test('HCP111 actual artifact commit lost acknowledgement reconciles exact original signed bytes before plan', async ({
+ page
+}) => {
+ const r = await page.evaluate(() => window.hcp111Fixture.fault(2, true));
+ expect(r.status).toBe('prepared');
+ expect(r.exposed).toBe(true);
+ expect(r.faultPuts).toBe(1);
+ expect(r.revision).toBe(2);
+ expect(r.signatures).toBe(1);
+ expect(r.sameArtifact).toBe(true);
+ expect(r.originalCapture).toBe(true);
+});
+test('HCP111 original inbox retirement during the actual prompt revokes continuity without another effect', async ({
+ page
+}) => {
+ const r = await page.evaluate(() => window.hcp111Fixture.late(false, true));
+ expect(r.exposed).toBe(false);
+ expect(r.signatures).toBe(1);
+ expect(r.revision).toBe(1);
+ expect(r.artifact).toBeNull();
+ expect(r.snapshot?.owner).toBe(r.originalOwner);
+ expect(r.snapshot?.hash).toBe(r.expectedHash);
+ expect(r.snapshot?.lateAvailable).toBe(true);
+});
+test('HCP111 unavailable artifact readback preserves uncertainty until exact original explicit retry without a new signature or put', async ({
+ page
+}) => {
+ const r = await page.evaluate(() =>
+ window.hcp111Fixture.fault(2, true, true)
+ );
+ expect(r.status).toBe('unknown');
+ expect(r.exposed).toBe(false);
+ expect(r.faultPuts).toBe(1);
+ expect(r.revision).toBe(2);
+ expect(r.signatures).toBe(1);
+ expect(r.originalCapture).toBe(true);
+ expect(r.retryStatus).toBe('prepared');
+ expect(r.retryExact).toBe(true);
+ expect(r.retryPuts).toBe(0);
+});
+test('HCP111 actual valid mismatched signed artifact readback conflicts without adoption or another effect', async ({
+ page
+}) => {
+ const r = await page.evaluate(() =>
+ window.hcp111Fixture.fault(2, true, false, 'valid')
+ );
+ expect(r.status).toBe('conflict');
+ expect(r.exposed).toBe(false);
+ expect(r.readStatus).toBe('found');
+ expect(r.faultPuts).toBe(2);
+ expect(r.nativePuts).toBe(3);
+ expect(r.revision).toBe(2);
+ expect(r.signatures).toBe(1);
+ expect(r.originalCapture).toBe(false);
+ expect(r.retryStatus).toBe('conflict');
+ expect(r.retryExact).toBe(false);
+ expect(r.retryPuts).toBe(0);
+});
+test('HCP111 actual corrupt artifact readback preserves stored evidence and refuses an explicit retry', async ({
+ page
+}) => {
+ const r = await page.evaluate(() =>
+ window.hcp111Fixture.fault(2, true, false, 'corrupt')
+ );
+ expect(r.status).toBe('unknown');
+ expect(r.exposed).toBe(false);
+ expect(r.readStatus).toBe('corrupt_record');
+ expect(r.corruptWire).toBe('{"schema":999}');
+ expect(r.faultPuts).toBe(2);
+ expect(r.nativePuts).toBe(3);
+ expect(r.signatures).toBe(1);
+ expect(r.retryStatus).toBe('unavailable');
+ expect(r.retryExact).toBe(false);
+ expect(r.retryPuts).toBe(0);
+});
diff --git a/web/tests/unit/sign-listing.test.ts b/web/tests/unit/sign-listing.test.ts
@@ -0,0 +1,26 @@
+import { expect, it } from 'vitest';
+import {
+ beginListingSigning,
+ runListingSigning,
+ listingSigningSnapshot,
+ listingPublicationSnapshot,
+ type ListingSigning,
+ type ListingPublication
+} from '../../src/lib/publishing/sign-listing.ts';
+import type { ListingReview } from '../../src/lib/publishing/prepare-listing.ts';
+
+it('HCP111 copied review cannot create signing ownership', () => {
+ expect(
+ beginListingSigning({} as ListingReview, 'sign_reviewed_listing')
+ ).toBeUndefined();
+});
+it('HCP111 SSR copied command cannot sign or disclose original state', async () => {
+ const copy = {} as ListingSigning;
+ expect(listingSigningSnapshot(copy)).toBeUndefined();
+ expect(await runListingSigning(copy, 'sign_reviewed_listing')).toEqual({
+ status: 'invalid'
+ });
+});
+it('HCP111 copied publication cannot disclose a durable signed plan', () => {
+ expect(listingPublicationSnapshot({} as ListingPublication)).toBeUndefined();
+});