commit a0c61c7cfece7316eeed06780c89a74d6134ffc2
parent f4cfa256a458741742252a31fc86a1b850d751b4
Author: triesap <tyson@radroots.org>
Date: Sat, 10 Oct 2026 04:20:11 +0000
publishing: publish listings through narrow per-target delivery (HCP-112)
Diffstat:
10 files changed, 1891 insertions(+), 113 deletions(-)
diff --git a/web/src/lib/nostr/listing-publisher.ts b/web/src/lib/nostr/listing-publisher.ts
@@ -0,0 +1,238 @@
+import type { NostrEvent } from 'applesauce-core/helpers';
+import {
+ publicRelayTargets,
+ readRelayPolicy,
+ type RelayPolicy
+} from '../config/relays.ts';
+import {
+ listingPublicationOwnership,
+ type ListingPublication
+} from '../publishing/sign-listing.ts';
+import {
+ identityMessagingOwnership,
+ identityPublicOperationOwnership,
+ recheckIdentityOwner
+} from '../runtime/identity-session.ts';
+import { preferencePolicyFingerprint } from './inbox-preference-publication.ts';
+import { readPublicListingIntent } from '../persistence/public-publications.ts';
+import {
+ decodePublicRecord,
+ publicRecordSnapshot,
+ type PublicRecordHandle
+} from '../persistence/records.ts';
+declare const leaseBrand: unique symbol;
+declare const permissionBrand: unique symbol;
+export type ListingDeliveryLease = Readonly<{ [leaseBrand]: true }>;
+export type ListingAttemptPermission = Readonly<{ [permissionBrand]: true }>;
+type Original = NonNullable<ReturnType<typeof listingPublicationOwnership>>;
+type Owner = Readonly<{
+ original: Original;
+ policy: RelayPolicy;
+ current(): boolean;
+}>;
+type Permission = Readonly<{
+ owner: Owner;
+ origin: string;
+ mode: 'publish' | 'readback';
+ wire: string;
+}>;
+const leases = new WeakMap<ListingDeliveryLease, Owner>();
+const permissions = new WeakMap<ListingAttemptPermission, Permission>();
+// Receipt revisions may grow, but the complete original operation payload and
+// verified artifact stay exact. No new command, author or destination is adopted.
+export async function readRetainedListingDelivery(
+ lease: ListingDeliveryLease
+): Promise<PublicRecordHandle | undefined> {
+ const owner = leases.get(lease);
+ if (!owner) return;
+ const original = owner.original;
+ const expected = decodePublicRecord(
+ original.recordWire,
+ original.owner,
+ original.command
+ );
+ if (!expected.ok) return;
+ const baseline = publicRecordSnapshot(
+ expected.value,
+ original.owner,
+ original.command
+ );
+ if (
+ baseline?.family !== 'public_operation' ||
+ baseline.capture.kind !== 30402 ||
+ !baseline.artifact ||
+ baseline.revision !== 2
+ )
+ return;
+ const read = await readPublicListingIntent(
+ original.repository,
+ original.command
+ );
+ if (read.status !== 'found') return;
+ const row = publicRecordSnapshot(
+ read.record,
+ original.owner,
+ original.command
+ );
+ if (
+ row?.family !== 'public_operation' ||
+ row.revision < baseline.revision ||
+ JSON.stringify({
+ ...row,
+ revision: baseline.revision,
+ receipts: baseline.receipts
+ }) !== JSON.stringify(baseline)
+ )
+ return;
+ return read.record;
+}
+// Current authority is mandatory for every new network permission. Retained
+// exact storage observation above remains usable for bookkeeping after Stop.
+export async function readOwnedListingDelivery(
+ lease: ListingDeliveryLease
+): Promise<PublicRecordHandle | undefined> {
+ const owner = leases.get(lease);
+ if (!owner?.current()) return;
+ const record = await readRetainedListingDelivery(lease);
+ return owner.current() ? record : undefined;
+}
+export function listingDeliveryOwnership(lease: ListingDeliveryLease) {
+ const owner = leases.get(lease);
+ return owner?.current()
+ ? {
+ repository: owner.original.repository,
+ owner: owner.original.owner,
+ command: owner.original.command,
+ current: owner.current
+ }
+ : undefined;
+}
+export type ListingOwnershipResult<T> =
+ | Readonly<{ status: 'completed'; value: T }>
+ | Readonly<{ status: 'invalid' | 'unavailable' | 'busy' | 'stopped' }>;
+// One original author lock spans this finite explicitly requested network
+// action. It never spans a native IDB transaction and cannot mint a signer.
+export async function withListingDeliveryOwnership<T>(
+ publication: ListingPublication,
+ policy: RelayPolicy,
+ consent: unknown,
+ work: (lease: ListingDeliveryLease) => Promise<T>
+): Promise<ListingOwnershipResult<T>> {
+ const original = listingPublicationOwnership(publication);
+ if (
+ !original ||
+ consent !== 'publish_stored_listing' ||
+ original.policy !== policy
+ )
+ return { status: 'invalid' };
+ if (typeof window === 'undefined' || !navigator.locks?.request)
+ return { status: 'unavailable' };
+ try {
+ return await navigator.locks.request(
+ 'harvestcircle:owner:' + original.owner,
+ { mode: 'exclusive', ifAvailable: true },
+ async (lock): Promise<ListingOwnershipResult<T>> => {
+ if (!lock) return { status: 'busy' };
+ await recheckIdentityOwner(original.identity);
+ const identity = identityMessagingOwnership(original.identity),
+ operation = identityPublicOperationOwnership(
+ original.identity,
+ original.operation
+ );
+ if (
+ !identity ||
+ !operation ||
+ identity.owner !== original.owner ||
+ operation.owner !== original.owner ||
+ operation.session !== identity.session ||
+ !original.current()
+ )
+ return { status: 'stopped' };
+ let active = true;
+ const owner: Owner = {
+ original,
+ policy,
+ current: () =>
+ active &&
+ original.current() &&
+ identity.current() &&
+ operation.current()
+ };
+ const lease = Object.freeze({}) as ListingDeliveryLease;
+ leases.set(lease, owner);
+ try {
+ if (!(await readOwnedListingDelivery(lease)))
+ return { status: 'unavailable' };
+ return { status: 'completed', value: await work(lease) };
+ } finally {
+ active = false;
+ }
+ }
+ );
+ } catch {
+ return { status: 'unavailable' };
+ }
+}
+// Each permission comes from actual stored signed bytes, fresh identity and
+// unchanged original policy. Preference/private capabilities cannot enter it.
+export async function authorizeListingAttempt(
+ lease: ListingDeliveryLease,
+ origin: string,
+ mode: 'publish' | 'readback'
+): Promise<ListingAttemptPermission | undefined> {
+ const owner = leases.get(lease);
+ if (!owner || !owner.current() || (mode !== 'publish' && mode !== 'readback'))
+ return;
+ try {
+ const record = await readOwnedListingDelivery(lease),
+ original = owner.original;
+ const row =
+ record && publicRecordSnapshot(record, original.owner, original.command);
+ const manifest = readRelayPolicy(owner.policy),
+ targets = publicRelayTargets(owner.policy, 'write'),
+ fingerprint = await preferencePolicyFingerprint(owner.policy);
+ if (
+ row?.family !== 'public_operation' ||
+ !row.artifact ||
+ !manifest.postingEnabled ||
+ !manifest.messagingEnabled ||
+ fingerprint !== row.capture.policyFingerprint ||
+ JSON.stringify(targets) !== JSON.stringify(row.capture.targets) ||
+ !row.capture.targets.includes(origin)
+ )
+ return;
+ await recheckIdentityOwner(original.identity);
+ if (!owner.current()) return;
+ const token = Object.freeze({}) as ListingAttemptPermission;
+ permissions.set(token, { owner, origin, mode, wire: row.artifact.wire });
+ return token;
+ } catch {
+ return;
+ }
+}
+// Original once-only token: detached metadata, wrong role, policy or origin
+// cannot supply a raw event. SDK effects remain owned by the public pool.
+export function takeListingPublication(
+ token: ListingAttemptPermission,
+ policy: RelayPolicy,
+ origin: string,
+ mode: 'publish' | 'readback'
+):
+ | Readonly<{ event: NostrEvent; wire: string; current(): boolean }>
+ | undefined {
+ const saved = permissions.get(token);
+ if (!saved) return;
+ permissions.delete(token);
+ if (
+ saved.owner.policy !== policy ||
+ saved.origin !== origin ||
+ saved.mode !== mode ||
+ !saved.owner.current()
+ )
+ return;
+ return {
+ event: JSON.parse(saved.wire) as NostrEvent,
+ wire: saved.wire,
+ current: saved.owner.current
+ };
+}
diff --git a/web/src/lib/nostr/public-pool.ts b/web/src/lib/nostr/public-pool.ts
@@ -11,6 +11,17 @@ import {
takePreferencePublication,
type PreferencePublication
} from './inbox-preference-publication.ts';
+import {
+ takeListingPublication,
+ type ListingAttemptPermission
+} from './listing-publisher.ts';
+import {
+ verifyEnvelope,
+ verifiedEnvelopeSnapshot
+} from './verified-envelope.ts';
+export type ListingReadbackResult =
+ | Readonly<{ status: 'found'; wire: string }>
+ | Readonly<{ status: 'missing' | 'unknown' | 'stopped' }>;
export type PreferenceAttemptResult = Readonly<{
status: 'accepted' | 'refused' | 'timed_out' | 'unknown' | 'stopped';
}>;
@@ -34,6 +45,18 @@ interface Owner {
signal: AbortSignal,
remaining: number
) => Promise<PreferenceAttemptResult>;
+ readonly listing: (
+ permission: ListingAttemptPermission,
+ origin: string,
+ signal: AbortSignal,
+ remaining: number
+ ) => Promise<PreferenceAttemptResult>;
+ readonly readListing: (
+ permission: ListingAttemptPermission,
+ origin: string,
+ signal: AbortSignal,
+ remaining: number
+ ) => Promise<ListingReadbackResult>;
}
const owners = new WeakMap<PublicPool, Owner>();
let lifetime: Owner | undefined;
@@ -172,6 +195,238 @@ export function getPublicPool(
}
});
},
+ async listing(permission, origin, signal, remaining) {
+ const admitted = takeListingPublication(
+ permission,
+ policy,
+ origin,
+ 'publish'
+ );
+ if (
+ closed ||
+ publicationCleanupRequired ||
+ !admitted ||
+ signal.aborted ||
+ !Number.isFinite(remaining) ||
+ remaining <= 0 ||
+ remaining > 45000
+ )
+ return { status: 'stopped' };
+ return await new Promise<PreferenceAttemptResult>((resolve) => {
+ let ended = false;
+ let release = () => {};
+ let fenceTimer: ReturnType<typeof setTimeout> | undefined;
+ function finish(status: PreferenceAttemptResult['status']) {
+ if (ended) return;
+ ended = true;
+ clearTimeout(timer);
+ if (fenceTimer !== undefined) clearTimeout(fenceTimer);
+ signal.removeEventListener('abort', stopped);
+ try {
+ release();
+ } catch {
+ publicationCleanupRequired = true;
+ status = 'unknown';
+ }
+ resolve({ status });
+ }
+ function stopped() {
+ if (ended) {
+ release();
+ return;
+ }
+ finish('stopped');
+ }
+ function fence() {
+ if (ended) return;
+ if (closed || signal.aborted || !admitted!.current()) {
+ finish('stopped');
+ return;
+ }
+ fenceTimer = setTimeout(() => fence(), 50);
+ }
+ signal.addEventListener('abort', stopped, { once: true });
+ // Arm our finite deadline before subscribing. The SDK uses the same
+ // response shape for its timer and a relay refusal saying "Timeout";
+ // only this owned deadline supplies retryable timeout evidence.
+ const relay = sdk.relay(origin);
+ const timeout =
+ Number.isFinite(relay.eventTimeout) && relay.eventTimeout > 0
+ ? Math.min(remaining, relay.eventTimeout)
+ : remaining;
+ const timer = setTimeout(() => finish('timed_out'), timeout);
+ try {
+ if (!admitted.current() || signal.aborted) {
+ finish('stopped');
+ return;
+ }
+ // This SDK invocation is an attempted effect. Stop cannot reverse an
+ // already emitted/buffered EVENT, but teardown schedules no new one.
+ const subscription = relay.event(admitted.event, 'EVENT').subscribe({
+ next(response) {
+ if (ended) return;
+ if (
+ (response.from !== origin && response.from !== origin + '/') ||
+ typeof response.ok !== 'boolean'
+ ) {
+ finish('unknown');
+ return;
+ }
+ if (response.ok) finish('accepted');
+ else if (response.message === 'Timeout') finish('unknown');
+ else if (
+ typeof response.message === 'string' &&
+ response.message.startsWith('auth-required:')
+ )
+ finish('unknown');
+ else finish('refused');
+ },
+ error: () => finish('unknown'),
+ complete: () => {
+ if (!ended) finish('unknown');
+ }
+ });
+ const stop = () => {
+ subscription.unsubscribe();
+ active.delete(stop);
+ };
+ release = () => {
+ stop();
+ active.delete(stopped);
+ };
+ active.set(stopped, true);
+ if (ended) {
+ try {
+ release();
+ } catch {
+ publicationCleanupRequired = true;
+ }
+ } else {
+ fence();
+ }
+ } catch {
+ finish('unknown');
+ }
+ });
+ },
+ async readListing(permission, origin, signal, remaining) {
+ const admitted = takeListingPublication(
+ permission,
+ policy,
+ origin,
+ 'readback'
+ );
+ if (
+ closed ||
+ publicationCleanupRequired ||
+ !admitted ||
+ signal.aborted ||
+ !Number.isFinite(remaining) ||
+ remaining <= 0 ||
+ remaining > 45000
+ )
+ return { status: 'stopped' };
+ return await new Promise<ListingReadbackResult>((resolve) => {
+ let ended = false,
+ release = () => {};
+ let fenceTimer: ReturnType<typeof setTimeout> | undefined;
+ function finish(result: ListingReadbackResult) {
+ if (ended) return;
+ ended = true;
+ clearTimeout(timer);
+ if (fenceTimer !== undefined) clearTimeout(fenceTimer);
+ signal.removeEventListener('abort', stopped);
+ try {
+ release();
+ } catch {
+ publicationCleanupRequired = true;
+ result = { status: 'unknown' };
+ }
+ resolve(result);
+ }
+ function stopped() {
+ finish({ status: 'stopped' });
+ }
+ function fence() {
+ if (ended) return;
+ if (closed || signal.aborted || !admitted!.current()) {
+ stopped();
+ return;
+ }
+ fenceTimer = setTimeout(fence, 50);
+ }
+ const timer = setTimeout(
+ () => finish({ status: 'unknown' }),
+ remaining
+ );
+ signal.addEventListener('abort', stopped, { once: true });
+ try {
+ if (!admitted.current() || signal.aborted) {
+ stopped();
+ return;
+ }
+ const expected = admitted.event;
+ // Exact frozen target and ID only. No generic filter/relay/request API.
+ const subscription = sdk
+ .req(
+ [origin],
+ [
+ {
+ ids: [expected.id],
+ authors: [expected.pubkey],
+ kinds: [30402],
+ limit: 1
+ }
+ ],
+ { waitForAuth: false, reconnect: false, resubscribe: false }
+ )
+ .subscribe({
+ next(message) {
+ if (
+ ended ||
+ (message.from !== origin && message.from !== origin + '/')
+ )
+ return;
+ if (message.type === 'EOSE') {
+ finish({ status: 'missing' });
+ return;
+ }
+ if (message.type !== 'EVENT' || !admitted.current()) return;
+ const checked = verifyEnvelope(JSON.stringify(message.event));
+ const observed =
+ checked.ok && verifiedEnvelopeSnapshot(checked.value);
+ const fields = (event: typeof expected) =>
+ JSON.stringify([
+ event.id,
+ event.pubkey,
+ event.created_at,
+ event.kind,
+ event.tags,
+ event.content,
+ event.sig
+ ]);
+ if (observed && fields(observed) === fields(expected))
+ // SDK object ingress is independently verified signed fields,
+ // not a claim to preserve the relay's original JSON encoding.
+ finish({ status: 'found', wire: admitted.wire });
+ },
+ error: () => finish({ status: 'unknown' }),
+ complete: () => {
+ if (!ended) finish({ status: 'missing' });
+ }
+ });
+ release = () => {
+ subscription.unsubscribe();
+ active.delete(stopped);
+ };
+ active.set(stopped, true);
+ if (ended) release();
+ else fence();
+ } catch {
+ finish({ status: 'unknown' });
+ }
+ });
+ },
subscribe(filters, onMessage, sampleSource) {
if (closed) throw new Error('public_pool_closed');
let release = () => {};
@@ -292,3 +547,36 @@ export function publishPublicPreferenceAttempt(
return Promise.resolve({ status: 'unknown' });
}
}
+// Listing and preference permissions stay separate despite the shared SDK owner.
+export function publishPublicListingAttempt(
+ token: PublicPool,
+ permission: ListingAttemptPermission,
+ policy: RelayPolicy,
+ origin: string,
+ signal: AbortSignal,
+ remaining: number
+): Promise<PreferenceAttemptResult> {
+ try {
+ const owner = ownerOf(token);
+ if (owner.policy !== policy) return Promise.resolve({ status: 'stopped' });
+ return owner.listing(permission, origin, signal, remaining);
+ } catch {
+ return Promise.resolve({ status: 'unknown' });
+ }
+}
+export function readPublicListingExactAttempt(
+ token: PublicPool,
+ permission: ListingAttemptPermission,
+ policy: RelayPolicy,
+ origin: string,
+ signal: AbortSignal,
+ remaining: number
+): Promise<ListingReadbackResult> {
+ try {
+ const owner = ownerOf(token);
+ if (owner.policy !== policy) return Promise.resolve({ status: 'stopped' });
+ return owner.readListing(permission, origin, signal, remaining);
+ } catch {
+ return Promise.resolve({ status: 'unknown' });
+ }
+}
diff --git a/web/src/lib/persistence/public-receipts.ts b/web/src/lib/persistence/public-receipts.ts
@@ -0,0 +1,80 @@
+import {
+ publicRecordSnapshot,
+ publicRecordWire,
+ type PublicRecordHandle
+} from './records.ts';
+import {
+ preparePublicReceiptTransition,
+ publicTransitionSnapshot
+} from './artifact-records.ts';
+import {
+ publicPublicationOwner,
+ publicPublicationQuotaRepository,
+ readPublicListingIntent,
+ type PublicPublicationRepository
+} from './public-publications.ts';
+import {
+ commitPublicOperationTransition,
+ observePublicOperationTransition
+} from './quota.ts';
+export type PublicListingReceiptResult =
+ | Readonly<{ status: 'saved'; record: PublicRecordHandle }>
+ | Readonly<{ status: 'invalid' | 'conflict' | 'unknown' | 'unavailable' }>;
+// Exact full-wire CAS append. A request success or detached cached observation
+// cannot acknowledge a receipt. Unknown native commits retain original payload.
+export async function commitPublicListingReceipt(
+ repository: PublicPublicationRepository,
+ record: PublicRecordHandle,
+ command: string,
+ receiptWire: string
+): Promise<PublicListingReceiptResult> {
+ try {
+ const owner = publicPublicationOwner(repository),
+ quota = publicPublicationQuotaRepository(repository);
+ const row = owner
+ ? publicRecordSnapshot(record, owner, command)
+ : undefined;
+ if (
+ !owner ||
+ !quota ||
+ row?.family !== 'public_operation' ||
+ row.capture.kind !== 30402 ||
+ !row.artifact
+ )
+ return { status: 'invalid' };
+ const transition = preparePublicReceiptTransition(
+ record,
+ owner,
+ command,
+ receiptWire
+ );
+ if (!transition.ok) return { status: 'invalid' };
+ const expected = publicTransitionSnapshot(transition.value, owner, command);
+ if (!expected) return { status: 'invalid' };
+ const saved = await commitPublicOperationTransition(
+ quota,
+ transition.value
+ );
+ 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')
+ return {
+ status: observed.state === 'conflict' ? 'conflict' : 'unknown'
+ };
+ }
+ const read = await readPublicListingIntent(repository, command);
+ if (read.status !== 'found') return { status: 'unknown' };
+ if (publicRecordWire(read.record, owner, command) !== expected.nextWire)
+ return { status: 'conflict' };
+ return { status: 'saved', record: read.record };
+ } catch {
+ return { status: 'unknown' };
+ }
+}
diff --git a/web/src/lib/publishing/deliver-listing.ts b/web/src/lib/publishing/deliver-listing.ts
@@ -0,0 +1,170 @@
+import { PUBLIC_PUBLICATION_BUDGETS } from '../config/budgets.ts';
+import type { RelayPolicy } from '../config/relays.ts';
+import type { ListingPublication } from './sign-listing.ts';
+import {
+ authorizeListingAttempt,
+ listingDeliveryOwnership,
+ readOwnedListingDelivery,
+ readRetainedListingDelivery,
+ withListingDeliveryOwnership,
+ type ListingDeliveryLease
+} from '../nostr/listing-publisher.ts';
+import {
+ publishPublicListingAttempt,
+ readPublicListingExactAttempt,
+ type PublicPool
+} from '../nostr/public-pool.ts';
+import { publicRecordSnapshot } from '../persistence/records.ts';
+import { commitPublicListingReceipt } from '../persistence/public-receipts.ts';
+export type ListingDeliveryResult = Readonly<{
+ status:
+ | 'completed'
+ | 'needs_action'
+ | 'storage_failed'
+ | 'invalid'
+ | 'unavailable'
+ | 'busy'
+ | 'stopped';
+}>;
+const pending = new WeakMap<
+ ListingPublication,
+ Promise<ListingDeliveryResult>
+>();
+async function deliver(
+ lease: ListingDeliveryLease,
+ pool: PublicPool,
+ policy: RelayPolicy
+): Promise<ListingDeliveryResult> {
+ const custody = listingDeliveryOwnership(lease),
+ initial = await readOwnedListingDelivery(lease);
+ if (!custody || !initial) return { status: 'storage_failed' };
+ const row = publicRecordSnapshot(initial, custody.owner, custody.command);
+ if (row?.family !== 'public_operation' || !row.artifact)
+ return { status: 'invalid' };
+ const eventId = row.artifact.eventId;
+ const actionId = crypto.randomUUID(),
+ controller = new AbortController(),
+ started = performance.now();
+ const remaining = () =>
+ PUBLIC_PUBLICATION_BUDGETS.networkActionMilliseconds -
+ (performance.now() - started);
+ async function retain(
+ origin: string,
+ attempt: number,
+ status: string,
+ readbackWire: string | null
+ ) {
+ const current = await readRetainedListingDelivery(lease);
+ if (!current || !custody) return false;
+ const result = await commitPublicListingReceipt(
+ custody.repository,
+ current,
+ custody.command,
+ JSON.stringify({
+ actionId,
+ origin,
+ role: 'publication',
+ attempt,
+ eventId,
+ status,
+ observedAtMilliseconds: Date.now(),
+ readbackWire
+ })
+ );
+ return result.status === 'saved';
+ }
+ try {
+ for (const origin of row.capture.targets) {
+ const accepted = row.receipts.some(
+ (fact) =>
+ fact.origin === origin &&
+ fact.eventId === row.artifact!.eventId &&
+ fact.status === 'accepted'
+ );
+ let done = accepted;
+ for (
+ let attempt = 1;
+ attempt <= PUBLIC_PUBLICATION_BUDGETS.attemptsPerTargetAction;
+ attempt++
+ ) {
+ if (!custody.current() || remaining() <= 0)
+ return { status: 'stopped' };
+ let status: 'accepted' | 'timed_out' = 'accepted';
+ if (!accepted) {
+ const permission = await authorizeListingAttempt(
+ lease,
+ origin,
+ 'publish'
+ );
+ if (!permission || remaining() <= 0) return { status: 'stopped' };
+ const result = await publishPublicListingAttempt(
+ pool,
+ permission,
+ policy,
+ origin,
+ controller.signal,
+ remaining()
+ );
+ if (!(await retain(origin, attempt, result.status, null)))
+ return { status: 'storage_failed' };
+ if (result.status !== 'accepted' && result.status !== 'timed_out')
+ return {
+ status: result.status === 'stopped' ? 'stopped' : 'needs_action'
+ };
+ status = result.status;
+ done = result.status === 'accepted';
+ }
+ const permission = await authorizeListingAttempt(
+ lease,
+ origin,
+ 'readback'
+ );
+ if (!permission || remaining() <= 0) return { status: 'stopped' };
+ const readback = await readPublicListingExactAttempt(
+ pool,
+ permission,
+ policy,
+ origin,
+ controller.signal,
+ remaining()
+ );
+ if (readback.status === 'found') {
+ if (!(await retain(origin, attempt, status, readback.wire)))
+ return { status: 'storage_failed' };
+ done = true;
+ }
+ if (done) break;
+ if (readback.status === 'stopped') return { status: 'stopped' };
+ }
+ if (!done) return { status: 'needs_action' };
+ }
+ return { status: 'completed' };
+ } finally {
+ controller.abort();
+ }
+}
+export function deliverListing(
+ publication: ListingPublication,
+ pool: PublicPool,
+ policy: RelayPolicy,
+ consent: unknown
+): Promise<ListingDeliveryResult> {
+ if (consent !== 'publish_stored_listing')
+ return Promise.resolve({ status: 'invalid' });
+ const active = pending.get(publication);
+ if (active) return active;
+ const job = withListingDeliveryOwnership(
+ publication,
+ policy,
+ consent,
+ (lease) => deliver(lease, pool, policy)
+ )
+ .then((result) =>
+ result.status === 'completed' ? result.value : { status: result.status }
+ )
+ .finally(() => {
+ if (pending.get(publication) === job) pending.delete(publication);
+ });
+ pending.set(publication, job);
+ return job;
+}
diff --git a/web/src/lib/publishing/sign-listing.ts b/web/src/lib/publishing/sign-listing.ts
@@ -187,6 +187,24 @@ export function listingPublicationSnapshot(token: ListingPublication) {
policyFingerprint: value.policyFingerprint
};
}
+// Original custody only. This port grants no raw event or network effect; the
+// typed publisher must obtain its own current lock and reread durable storage.
+export function listingPublicationOwnership(token: ListingPublication) {
+ const value = publications.get(token);
+ if (!value || !current(value.model)) return;
+ const operation = value.model.getOperation();
+ if (!operation) return;
+ return {
+ repository: value.model.original.repository,
+ identity: value.model.original.readiness.identity,
+ policy: value.model.original.readiness.policy,
+ operation,
+ owner: value.owner,
+ command: value.command,
+ recordWire: value.recordWire,
+ current: () => current(value.model)
+ };
+}
async function exactStored(
model: Model,
expected: PublicRecordHandle
diff --git a/web/tests/e2e/deliver-listing.spec.ts b/web/tests/e2e/deliver-listing.spec.ts
@@ -0,0 +1,295 @@
+import { expect, test } from '@playwright/test';
+import { build } from 'vite';
+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/deliver-listing.ts';
+declare global {
+ interface Window {
+ hcp112: typeof Fixture;
+ hcp112Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>;
+ }
+}
+let server: Awaited<ReturnType<typeof createStaticHarness>>,
+ sockets: WebSocketServer,
+ bundle: string,
+ endpoint: string;
+let frames: unknown[][] = [],
+ stored: Record<string, unknown> | undefined,
+ response: 'accepted' | 'refused' | 'timeout-refusal' | 'silent' = 'accepted',
+ readback: 'exact' | 'different' | 'invalid' | 'missing' = 'exact';
+test.beforeAll(async () => {
+ server = await createStaticHarness();
+ sockets = new WebSocketServer({
+ host: '127.0.0.1',
+ port: 0,
+ maxPayload: 262144
+ });
+ await once(sockets, 'listening');
+ const address = sockets.address();
+ if (!address || typeof address === 'string')
+ throw Error('loopback unavailable');
+ endpoint = 'ws://127.0.0.1:' + address.port;
+ sockets.on('connection', (socket) => {
+ socket.on('message', (bytes) => {
+ const raw = Buffer.isBuffer(bytes)
+ ? bytes.toString()
+ : Array.isArray(bytes)
+ ? Buffer.concat(bytes).toString()
+ : Buffer.from(bytes).toString();
+ const frame = JSON.parse(raw) as unknown[];
+ frames.push(frame);
+ if (frame[0] === 'EVENT') {
+ stored = frame[1] as Record<string, unknown>;
+ if (response === 'silent') return;
+ socket.send(
+ JSON.stringify([
+ 'OK',
+ stored.id,
+ response === 'accepted',
+ response === 'accepted'
+ ? ''
+ : response === 'timeout-refusal'
+ ? 'Timeout'
+ : 'blocked: controlled refusal'
+ ])
+ );
+ } else if (frame[0] === 'REQ') {
+ if (stored && readback !== 'missing') {
+ const event =
+ readback === 'exact'
+ ? stored
+ : {
+ ...stored,
+ ...(readback === 'different'
+ ? { id: '0'.repeat(64) }
+ : { sig: '0'.repeat(128) })
+ };
+ socket.send(JSON.stringify(['EVENT', frame[1], event]));
+ }
+ socket.send(JSON.stringify(['EOSE', frame[1]]));
+ }
+ });
+ });
+ const built = await build({
+ configFile: false,
+ logLevel: 'silent',
+ build: {
+ write: false,
+ minify: false,
+ lib: {
+ entry: fileURLToPath(
+ new URL('./harness/deliver-listing.ts', import.meta.url)
+ ),
+ name: 'hcp112',
+ formats: ['iife']
+ }
+ }
+ });
+ const output = Array.isArray(built) ? built[0] : built;
+ if (!('output' in output)) throw Error('fixture bundle unavailable');
+ const chunks = output.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();
+ await new Promise<void>((resolve) => sockets.close(() => resolve()));
+ await server.close();
+});
+test.beforeEach(async ({ page }) => {
+ frames = [];
+ stored = undefined;
+ response = 'accepted';
+ readback = 'exact';
+ await page.addInitScript(
+ ({ endpoint }) => {
+ const Native = window.WebSocket;
+ class LoopbackSocket extends Native {
+ constructor(url: string | URL, protocols?: string | string[]) {
+ if (String(url) !== 'wss://discovery.example.org/')
+ throw Error('unfrozen destination');
+ super(endpoint, protocols);
+ }
+ }
+ window.WebSocket = LoopbackSocket;
+ },
+ { endpoint }
+ );
+ await page.goto(server.url + '/search');
+ await page.addScriptTag({ content: bundle });
+ await page.evaluate(async () => {
+ window.hcp112Fixture = await window.hcp112.createFixture();
+ });
+});
+test.afterEach(async ({ page }) => {
+ if (!page.isClosed())
+ await page.evaluate(() => window.hcp112Fixture?.close());
+});
+test('HCP112 actual durable signed listing precedes SDK EVENT and acceptance stays separate from exact loopback readback', async ({
+ page
+}) => {
+ const r = await page.evaluate(() => window.hcp112Fixture.run());
+ expect(r.result.status).toBe('completed');
+ expect(r.same).toBe(true);
+ expect(r.signs).toBe(1);
+ expect(r.trace.indexOf('ack:2')).toBeGreaterThan(-1);
+ expect(r.trace.indexOf('EVENT')).toBeGreaterThan(r.trace.indexOf('ack:2'));
+ expect(r.originalCapture).toBe(true);
+ expect(r.row.receipts).toHaveLength(2);
+ expect(r.row.receipts[0].status).toBe('accepted');
+ expect(r.row.receipts[0].readbackWire).toBeNull();
+ expect(r.row.receipts[1].readbackWire).toBe(r.row.artifact?.wire);
+ const events = frames.filter((frame) => frame[0] === 'EVENT');
+ expect(events).toHaveLength(1);
+ expect(events[0][1]).toEqual(JSON.parse(r.row.artifact!.wire));
+ const requests = frames.filter((frame) => frame[0] === 'REQ');
+ expect(requests).toHaveLength(1);
+ expect(requests[0][2]).toEqual({
+ ids: [r.row.artifact!.eventId],
+ authors: [r.owner],
+ kinds: [30402],
+ limit: 1
+ });
+});
+for (const mode of ['different', 'invalid', 'missing'] as const)
+ test(`HCP112 ${mode} loopback event cannot replace exact-ID signed readback`, async ({
+ page
+ }) => {
+ readback = mode;
+ const r = await page.evaluate(() => window.hcp112Fixture.run());
+ expect(r.row.receipts).toHaveLength(1);
+ expect(r.row.receipts[0].status).toBe('accepted');
+ expect(r.row.receipts[0].readbackWire).toBeNull();
+ expect(frames.filter((frame) => frame[0] === 'EVENT')).toHaveLength(1);
+ expect(frames.filter((frame) => frame[0] === 'REQ')).toHaveLength(1);
+ });
+for (const mode of ['refused', 'timeout-refusal'] as const)
+ test(`HCP112 actual ${mode} is retained without spinning or fabricating a retryable deadline`, async ({
+ page
+ }) => {
+ response = mode;
+ const r = await page.evaluate(() => window.hcp112Fixture.run());
+ expect(r.result.status).toBe('needs_action');
+ expect(r.row.receipts).toHaveLength(1);
+ expect(r.row.receipts[0].status).toBe(
+ mode === 'refused' ? 'refused' : 'unknown'
+ );
+ expect(r.row.receipts[0].readbackWire).toBeNull();
+ expect(frames.filter((frame) => frame[0] === 'EVENT')).toHaveLength(1);
+ expect(frames.filter((frame) => frame[0] === 'REQ')).toHaveLength(0);
+ });
+for (const mode of ['logout', 'stop', 'changeKey'] as const)
+ test(`HCP112 original ${mode} revokes the final effect without changing the artifact`, async ({
+ page
+ }) => {
+ const r = await page.evaluate(async (mode) => {
+ const f = window.hcp112Fixture;
+ f[mode]();
+ return await f.run();
+ }, mode);
+ expect(r.result.status).not.toBe('completed');
+ expect(r.row.receipts).toHaveLength(0);
+ expect(r.signs).toBe(1);
+ expect(frames.filter((frame) => frame[0] === 'EVENT')).toHaveLength(0);
+ });
+test('HCP112 detached publication snapshot cannot borrow final delivery ownership', async ({
+ page
+}) => {
+ const r = await page.evaluate(() => window.hcp112Fixture.copied());
+ expect(r.status).toBe('invalid');
+ expect(frames).toHaveLength(0);
+});
+test('HCP112 actual original lease refuses a foreign target and changed policy without a relay effect', async ({
+ page
+}) => {
+ const r = await page.evaluate(async () => {
+ const f = window.hcp112Fixture;
+ return { foreign: await f.foreignTarget(), changed: await f.retargeted() };
+ });
+ expect(r.foreign).toEqual({ status: 'completed', value: false });
+ expect(r.changed).toEqual({ status: 'invalid' });
+ expect(frames).toHaveLength(0);
+});
+test('HCP112 actual cached signed event is not an exact relay readback receipt', async ({
+ page
+}) => {
+ readback = 'missing';
+ const r = await page.evaluate(async () => {
+ const f = window.hcp112Fixture,
+ cachedId = await f.cacheArtifact();
+ return { cachedId, ...(await f.run()) };
+ });
+ expect(r.cachedId.id).toBe(r.row.artifact?.eventId);
+ expect(r.cachedId.seen).toEqual([
+ 'wss://discovery.example.org',
+ 'wss://other.example.org'
+ ]);
+ expect(r.row.receipts).toHaveLength(1);
+ expect(r.row.receipts[0].status).toBe('accepted');
+ expect(r.row.receipts[0].readbackWire).toBeNull();
+ expect(frames.filter((frame) => frame[0] === 'REQ')).toHaveLength(1);
+});
+test('HCP112 actual silent relay deadlines retain three bounded timed-out attempts without a new signature', async ({
+ page
+}) => {
+ response = 'silent';
+ readback = 'missing';
+ const r = await page.evaluate(() => window.hcp112Fixture.run());
+ expect(r.result.status).toBe('needs_action');
+ expect(r.signs).toBe(1);
+ expect(r.row.receipts.map((fact) => fact.status)).toEqual([
+ 'timed_out',
+ 'timed_out',
+ 'timed_out'
+ ]);
+ expect(r.row.receipts.map((fact) => fact.attempt)).toEqual([1, 2, 3]);
+ expect(new Set(r.row.receipts.map((fact) => fact.actionId)).size).toBe(1);
+ expect(frames.filter((frame) => frame[0] === 'EVENT')).toHaveLength(3);
+ expect(
+ new Set(
+ frames
+ .filter((frame) => frame[0] === 'EVENT')
+ .map((frame) => JSON.stringify(frame[1]))
+ ).size
+ ).toBe(1);
+});
+test('HCP112 logout after the actual EVENT retains a stopped observation and schedules no dependent readback', async ({
+ page
+}) => {
+ response = 'silent';
+ const run = page.evaluate(() => window.hcp112Fixture.run());
+ await expect
+ .poll(() => frames.filter((frame) => frame[0] === 'EVENT').length)
+ .toBe(1);
+ await page.evaluate(() => window.hcp112Fixture.logout());
+ const r = await run;
+ expect(r.result.status).toBe('stopped');
+ expect(r.row.receipts).toHaveLength(1);
+ expect(r.row.receipts[0].status).toBe('stopped');
+ expect(r.row.receipts[0].readbackWire).toBeNull();
+ expect(frames.filter((frame) => frame[0] === 'REQ')).toHaveLength(0);
+});
+for (const unknown of [false, true])
+ test(`HCP112 actual receipt write unknown=${unknown} is reconciled before dependent readback`, async ({
+ page
+ }) => {
+ const r = await page.evaluate(
+ (unknown) => window.hcp112Fixture.receiptFault(unknown),
+ unknown
+ );
+ expect(r.signs).toBe(1);
+ expect(r.faultPuts).toBe(1);
+ expect(frames.filter((frame) => frame[0] === 'EVENT')).toHaveLength(1);
+ if (unknown) {
+ expect(r.result.status).toBe('completed');
+ expect(r.row.receipts).toHaveLength(2);
+ expect(r.row.receipts[1].readbackWire).toBe(r.row.artifact?.wire);
+ expect(frames.filter((frame) => frame[0] === 'REQ')).toHaveLength(1);
+ } else {
+ expect(r.result.status).toBe('storage_failed');
+ expect(r.row.receipts).toHaveLength(0);
+ expect(frames.filter((frame) => frame[0] === 'REQ')).toHaveLength(0);
+ }
+ });
diff --git a/web/tests/e2e/harness/deliver-listing.ts b/web/tests/e2e/harness/deliver-listing.ts
@@ -0,0 +1,449 @@
+import { deliverListing } from '../../../src/lib/publishing/deliver-listing.ts';
+import {
+ getPublicPool,
+ closePublicPool
+} from '../../../src/lib/nostr/public-pool.ts';
+import {
+ authorizeListingAttempt,
+ withListingDeliveryOwnership,
+ takeListingPublication
+} from '../../../src/lib/nostr/listing-publisher.ts';
+import {
+ readRelayPolicy,
+ validateRelayPolicy
+} from '../../../src/lib/config/relays.ts';
+import { verifyEnvelope } from '../../../src/lib/nostr/verified-envelope.ts';
+import {
+ getPublicStore,
+ insertPublicEnvelope,
+ publicStoreEnvelope
+} from '../../../src/lib/nostr/public-store.ts';
+export { deliverListing, authorizeListingAttempt, takeListingPublication };
+import { makeFixture } from './approved-signing.ts';
+import { EventStore } from 'applesauce-core';
+import { getSeenRelays, type NostrEvent } from 'applesauce-core/helpers';
+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
+} 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 } from '../../../src/lib/persistence/records.ts';
+import {
+ beginListingSigning,
+ runListingSigning,
+ listingPublicationSnapshot
+} from '../../../src/lib/publishing/sign-listing.ts';
+
+export async function createFixture() {
+ const trace: string[] = [];
+ const tracePut = Object.getOwnPropertyDescriptor(
+ IDBObjectStore.prototype,
+ 'put'
+ ),
+ traceSend = Object.getOwnPropertyDescriptor(WebSocket.prototype, 'send');
+ if (!tracePut) throw Error('native trace descriptors missing');
+ const nativeTracePut = tracePut.value as IDBObjectStore['put'],
+ nativeTraceSend = Reflect.get<WebSocket, 'send'>(
+ WebSocket.prototype,
+ 'send'
+ );
+ Object.defineProperty(IDBObjectStore.prototype, 'put', {
+ ...tracePut,
+ value: function (
+ this: IDBObjectStore,
+ ...args: Parameters<IDBObjectStore['put']>
+ ) {
+ const value: unknown = args[0];
+ if (
+ this.name === 'public_operations' &&
+ typeof value === 'object' &&
+ value &&
+ 'wire' in value &&
+ typeof value.wire === 'string'
+ ) {
+ const revision = (JSON.parse(value.wire) as { revision: number })
+ .revision;
+ this.transaction.addEventListener(
+ 'complete',
+ () => trace.push('ack:' + revision),
+ { once: true }
+ );
+ }
+ return nativeTracePut.apply(this, args);
+ }
+ });
+ Object.defineProperty(WebSocket.prototype, 'send', {
+ configurable: true,
+ writable: true,
+ ...traceSend,
+ value: function (this: WebSocket, ...args: Parameters<WebSocket['send']>) {
+ if (
+ typeof args[0] === 'string' &&
+ (JSON.parse(args[0]) as unknown[])[0] === 'EVENT'
+ )
+ trace.push('EVENT');
+ return nativeTraceSend.apply(this, args);
+ }
+ });
+ 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,
+ observedOwner = signer.owner;
+ Object.defineProperty(window, 'nostr', {
+ configurable: true,
+ value: {
+ getPublicKey: () => {
+ keys++;
+ return Promise.resolve(observedOwner);
+ },
+ signEvent: (input: Parameters<typeof signer.sign>[0]) => {
+ signs++;
+ return Promise.resolve(signer.sign(input));
+ },
+ 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');
+ }
+ const signed = await invoke();
+ if (signed.status !== 'prepared') throw Error(signed.status);
+ const publication = signed.publication,
+ pool = getPublicPool(policy);
+ if (!pool) throw Error('original public pool missing');
+ return {
+ owner: signer.owner,
+ command,
+ publication,
+ pool,
+ policy,
+ async run(consent: unknown = 'publish_stored_listing') {
+ const a = deliverListing(publication, pool, policy, consent),
+ b = deliverListing(publication, pool, policy, consent);
+ const result = await a,
+ row = await stored();
+ return {
+ result,
+ trace: trace.slice(),
+ same: a === b,
+ row,
+ signs,
+ keys,
+ owner: signer.owner,
+ expectedWire: listingPublicationSnapshot(publication)?.wire,
+ originalCapture: row.capture.wire === preview.templateWire
+ };
+ },
+ async read() {
+ return await stored();
+ },
+ copied() {
+ return deliverListing(
+ { ...listingPublicationSnapshot(publication) } as typeof publication,
+ pool,
+ policy,
+ 'publish_stored_listing'
+ );
+ },
+ async foreignTarget() {
+ return await withListingDeliveryOwnership(
+ publication,
+ policy,
+ 'publish_stored_listing',
+ async (lease) =>
+ !!(await authorizeListingAttempt(
+ lease,
+ 'wss://other.example.org',
+ 'publish'
+ ))
+ );
+ },
+ retargeted() {
+ const manifest = readRelayPolicy(policy),
+ changed = validateRelayPolicy(
+ JSON.stringify({
+ ...manifest,
+ public: [
+ {
+ origin: 'wss://other.example.org',
+ read: true,
+ write: true,
+ nip50: false
+ }
+ ]
+ })
+ );
+ if (!changed) throw Error('changed fixture policy invalid');
+ return deliverListing(
+ publication,
+ pool,
+ changed,
+ 'publish_stored_listing'
+ );
+ },
+ async cacheArtifact() {
+ const row = await stored();
+ const sdkStore = new EventStore();
+ let seen: string[];
+ try {
+ sdkStore.add(JSON.parse(row.artifact!.wire) as NostrEvent, discovery);
+ sdkStore.add(
+ JSON.parse(row.artifact!.wire) as NostrEvent,
+ 'wss://other.example.org'
+ );
+ const merged = sdkStore.getEvent(row.artifact!.eventId);
+ if (!merged) throw Error('actual SDK merge failed');
+ seen = [...(getSeenRelays(merged) ?? [])].sort();
+ if (seen.length !== 2)
+ throw Error('actual SDK seen metadata not merged');
+ } finally {
+ sdkStore.dispose();
+ }
+ const verified = verifyEnvelope(row.artifact!.wire),
+ store = getPublicStore();
+ if (
+ !verified.ok ||
+ !store ||
+ insertPublicEnvelope(store, verified.value) !== 'accepted' ||
+ !publicStoreEnvelope(store, row.artifact!.eventId)
+ )
+ throw Error('actual shared public cache admission failed');
+ return { id: row.artifact!.eventId, seen };
+ },
+ async receiptFault(unknown: boolean) {
+ const put = Object.getOwnPropertyDescriptor(
+ IDBObjectStore.prototype,
+ 'put'
+ ),
+ abort = Object.getOwnPropertyDescriptor(
+ IDBTransaction.prototype,
+ 'abort'
+ );
+ if (!put || !abort) throw Error('native descriptors missing');
+ const nativePut = put.value as IDBObjectStore['put'];
+ let faultPuts = 0;
+ Object.defineProperty(IDBObjectStore.prototype, 'put', {
+ ...put,
+ value: function (
+ this: IDBObjectStore,
+ ...args: Parameters<IDBObjectStore['put']>
+ ) {
+ const v: unknown = args[0];
+ if (
+ this.name === 'public_operations' &&
+ typeof v === 'object' &&
+ v &&
+ 'wire' in v &&
+ typeof v.wire === 'string' &&
+ (JSON.parse(v.wire) as { revision: number }).revision === 3
+ ) {
+ faultPuts++;
+ if (unknown) {
+ nativePut.apply(this, args);
+ throw Error(
+ 'HC_TEST_ONLY real receipt put lost JS acknowledgement'
+ );
+ }
+ this.transaction.abort();
+ throw Error('HC_TEST_ONLY definite receipt abort');
+ }
+ return nativePut.apply(this, args);
+ }
+ });
+ if (unknown)
+ Object.defineProperty(IDBTransaction.prototype, 'abort', {
+ ...abort,
+ value() {
+ throw Error('HC_TEST_ONLY unavailable abort channel');
+ }
+ });
+ try {
+ const result = await deliverListing(
+ publication,
+ pool,
+ policy,
+ 'publish_stored_listing'
+ ),
+ row = await stored();
+ return { result, row, signs, faultPuts };
+ } finally {
+ Object.defineProperty(IDBObjectStore.prototype, 'put', put);
+ Object.defineProperty(IDBTransaction.prototype, 'abort', abort);
+ }
+ },
+ logout() {
+ disconnectIdentity(identity);
+ },
+ stop() {
+ closeInboxSetupView(setup);
+ },
+ changeKey() {
+ const other = makeFixture(10050);
+ observedOwner = other.owner;
+ other.close();
+ },
+ close() {
+ closePublicPool(pool);
+ closePublicDraftController(controller);
+ closeBrowserDatabase(database);
+ closeInboxSetupView(setup);
+ disconnectIdentity(identity);
+ closePublicScheduler(scheduler);
+ signer.close();
+ if (prior) Object.defineProperty(window, 'nostr', prior);
+ else Reflect.deleteProperty(window, 'nostr');
+ Object.defineProperty(IDBObjectStore.prototype, 'put', tracePut);
+ if (traceSend)
+ Object.defineProperty(WebSocket.prototype, 'send', traceSend);
+ else Reflect.deleteProperty(WebSocket.prototype, 'send');
+ }
+ };
+}
diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs
@@ -246,13 +246,51 @@ import { auditOutput } from '../../tools/check-output.mjs';
);
assert.ok(
!Object.values(manifest).some(
- (record) => record.name === 'view-context'
+ (record) =>
+ record.name === 'view-context' || record.name === 'CapabilityGate'
)
);
assert.ok(
Object.values(manifest).some((record) => record.name === 'budgets')
);
assert.equal((await f.audit()).length, 47);
+ const manifestFile = path.join(
+ f.web,
+ '.svelte-kit/output/client/.vite/manifest.json'
+ );
+ const originalManifest = await readFile(manifestFile);
+ for (const mutation of ['shared-edge', 'button-import']) {
+ await t.test(
+ `public-only listing compatibility rejects extra ${mutation}`,
+ { timeout: 1800000 },
+ async () => {
+ const changed = JSON.parse(originalManifest.toString());
+ const records = Object.entries(changed);
+ const additional = records.find(
+ ([, record]) => record.name === 'entry/payload'
+ );
+ const target = records.find(
+ ([, record]) =>
+ record.name ===
+ (mutation === 'shared-edge' ? 'Disclosure' : 'Button')
+ );
+ assert.ok(additional);
+ assert.ok(target);
+ target[1].imports.push(additional[0]);
+ try {
+ await writeFile(manifestFile, JSON.stringify(changed));
+ await assert.rejects(
+ f.audit(),
+ mutation === 'shared-edge'
+ ? /Invalid owned shared compiler dependencies/
+ : /Invalid owned public-only Button compiler dependencies/
+ );
+ } finally {
+ await writeFile(manifestFile, originalManifest);
+ }
+ }
+ );
+ }
}
);
await test(
@@ -506,7 +544,9 @@ import { auditOutput } from '../../tools/check-output.mjs';
if (mutation === 'enquiry-root-missing-gate')
row.imports = row.imports.filter(
(/** @type {string} */ value) =>
- manifest[value].name !== 'view-context'
+ !['view-context', 'CapabilityGate'].includes(
+ manifest[value].name
+ )
);
if (mutation === 'context-resolver-dynamic')
row.dynamicImports = [];
@@ -898,7 +938,13 @@ import { auditOutput } from '../../tools/check-output.mjs';
)
? 'public-runtime'
: 'heads';
- const [identityKey, identity] = find('view-context'),
+ const [identityKey, identity] = find(
+ Object.values(manifest).some(
+ (record) => record.name === 'view-context'
+ )
+ ? 'view-context'
+ : 'CapabilityGate'
+ ),
[headsKey, heads] = find(identityCompilerRole);
if (mutation === 'missing-view') delete manifest[identityKey];
if (mutation === 'missing-heads') delete manifest[headsKey];
diff --git a/web/tests/unit/deliver-listing.test.ts b/web/tests/unit/deliver-listing.test.ts
@@ -0,0 +1,59 @@
+import { expect, it } from 'vitest';
+import { deliverListing } from '../../src/lib/publishing/deliver-listing.ts';
+import {
+ authorizeListingAttempt,
+ takeListingPublication,
+ withListingDeliveryOwnership,
+ type ListingDeliveryLease,
+ type ListingAttemptPermission
+} from '../../src/lib/nostr/listing-publisher.ts';
+import type { ListingPublication } from '../../src/lib/publishing/sign-listing.ts';
+import type { PublicPool } from '../../src/lib/nostr/public-pool.ts';
+import { deploymentRelayPolicy } from '../../src/lib/config/deployment-relays.ts';
+
+it('HCP112 copied durable disclosure cannot authorize a network action during SSR', async () => {
+ expect(
+ await deliverListing(
+ {} as ListingPublication,
+ {} as PublicPool,
+ deploymentRelayPolicy,
+ 'publish_stored_listing'
+ )
+ ).toEqual({ status: 'invalid' });
+});
+it('HCP112 copied lease cannot grant an event or readback permission', async () => {
+ for (const mode of ['publish', 'readback'] as const)
+ expect(
+ await authorizeListingAttempt(
+ {} as ListingDeliveryLease,
+ 'wss://discovery.example.org',
+ mode
+ )
+ ).toBeUndefined();
+});
+it('HCP112 copied per-target permission exposes no raw SDK event form', () => {
+ for (const mode of ['publish', 'readback'] as const)
+ expect(
+ takeListingPublication(
+ {} as ListingAttemptPermission,
+ deploymentRelayPolicy,
+ 'wss://discovery.example.org',
+ mode
+ )
+ ).toBeUndefined();
+});
+it('HCP112 copied source cannot execute an arbitrary ownership callback', async () => {
+ let called = false;
+ expect(
+ await withListingDeliveryOwnership(
+ {} as ListingPublication,
+ deploymentRelayPolicy,
+ 'publish_stored_listing',
+ () => {
+ called = true;
+ return Promise.resolve('unexpected');
+ }
+ )
+ ).toEqual({ status: 'invalid' });
+ expect(called).toBe(false);
+});
diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs
@@ -538,7 +538,7 @@ async function preferencePublicationAdmission(web) {
return false;
const producers = {
'src/lib/nostr/public-pool.ts':
- 'd5054acecd074a36e68d39e1f69c86cdde6480339c7f4bf901ece151a2b6a5b7',
+ 'd08c2c16936125e75a8195cfdc600f8c592cb942e1802d934823ee221c1c132b',
'src/lib/nostr/inbox-preference-publication.ts':
'fbad642340732bf7cf92905010af314829b80cc7b134121396f14e9bb8e765cc'
};
@@ -550,6 +550,26 @@ async function preferencePublicationAdmission(web) {
}
return true;
}
+// HCP112 exact original-token listing ports change the shared identity chunk.
+// Admit only their reviewed source pins and the complete observed closed graph.
+/** @param {string} web */
+async function listingPublicationAdmission(web) {
+ const pool = await readOwned(web, 'src/lib/nostr/public-pool.ts');
+ if (!pool.toString().includes("'./listing-publisher.ts'")) return false;
+ const producers = {
+ 'src/lib/nostr/listing-publisher.ts':
+ 'f2b4436665a2dc594e9c7b103cfa9257c7f58eeb46870bb06ee9fb63c18cb641',
+ 'src/lib/publishing/sign-listing.ts':
+ 'c33e1399c19e1134a8a9f511800056c65c9f48155358c903dfed7c2c10c32486'
+ };
+ for (const [name, pin] of Object.entries(producers)) {
+ const bytes = await readOwned(web, name);
+ publicText(bytes);
+ if (createHash('sha256').update(bytes).digest('hex') !== pin)
+ throw new Error('Invalid owned listing publication source');
+ }
+ return true;
+}
/** @param {string} web */
async function inboxSetupAdmission(web) {
const gate = await readOwned(web, 'src/lib/components/AccountGate.svelte');
@@ -729,6 +749,11 @@ export async function auditOutput(webDirectory) {
hasProductRequest || hasProductPresentation === 'enquiry';
const hasPreferencePublication =
hasPublicRuntime && (await preferencePublicationAdmission(web));
+ const hasListingPublication =
+ hasPreferencePublication && (await listingPublicationAdmission(web));
+ const identityViewCompilerModule = hasListingPublication
+ ? 'CapabilityGate'
+ : 'view-context';
const hasInboxSetup =
hasFullRoutes &&
hasPublicRuntime === 'public_identity' &&
@@ -777,7 +802,7 @@ export async function auditOutput(webDirectory) {
...(hasSearchPresentation ? ['Disclosure', 'navigation'] : ['dist']),
'negentropy',
...(hasPublicRuntime === 'public_identity'
- ? ['view-context', identityCompilerModule]
+ ? [identityViewCompilerModule, identityCompilerModule]
: ['budgets'])
])
names.add(name);
@@ -985,11 +1010,35 @@ export async function auditOutput(webDirectory) {
'preload-helper',
'public-key',
'client',
- 'budgets'
+ 'budgets',
+ ...(hasListingPublication && hasProductPresentation
+ ? ['Button']
+ : [])
]
).map((name) => requiredRecord(name)[0]),
'Invalid owned shared compiler dependencies'
);
+ // Historical public-only producers still compile current shared source.
+ // The exact HCP112 ports add only this existing, closed Button edge.
+ if (
+ hasPublicRuntime !== 'public_identity' &&
+ hasListingPublication &&
+ hasProductPresentation
+ ) {
+ const [buttonKey, button] = requiredRecord('Button');
+ if (
+ !/^_[A-Za-z0-9_-]+\.js$/.test(buttonKey) ||
+ Object.keys(button).some(
+ (field) => !['file', 'name', 'imports'].includes(field)
+ )
+ )
+ throw new Error('Invalid owned public-only Button compiler identity');
+ equal(
+ button.imports,
+ [requiredRecord('client')[0]],
+ 'Invalid owned public-only Button compiler dependencies'
+ );
+ }
for (const [key, record] of [dist, navigation]) {
if (
!/^_[A-Za-z0-9_-]+\.js$/.test(key) ||
@@ -1005,17 +1054,19 @@ export async function auditOutput(webDirectory) {
/** @type {[string, string[]][]} */
const identityDependencies = [
[
- 'view-context',
- hasProductRequest
- ? ['public-runtime', 'client', 'Button']
- : hasProductEnquiry
- ? [identityCompilerModule]
- : [
- ...(hasPreferencePublication ? [] : ['public-key']),
- identityCompilerModule,
- 'client',
- 'Button'
- ]
+ identityViewCompilerModule,
+ hasListingPublication
+ ? ['client', 'Button']
+ : hasProductRequest
+ ? ['public-runtime', 'client', 'Button']
+ : hasProductEnquiry
+ ? [identityCompilerModule]
+ : [
+ ...(hasPreferencePublication ? [] : ['public-key']),
+ identityCompilerModule,
+ 'client',
+ 'Button'
+ ]
],
[
identityCompilerModule,
@@ -1067,27 +1118,39 @@ export async function auditOutput(webDirectory) {
const [, gate] = requiredRecord('AccountGate');
equal(
gate.imports,
- (hasProductRequest
- ? ['client', 'view-context', 'InboxSetup']
- : hasProductEnquiry
- ? ['client', 'CapabilityGate', 'view-context', 'InboxSetup']
- : hasInboxPresentation
- ? ['client', 'view-context', 'InboxSetup']
- : [
- 'public-key',
- 'private-handles',
- 'public-runtime',
+ (hasListingPublication
+ ? [
+ 'public-runtime',
+ 'client',
+ identityViewCompilerModule,
+ 'InboxSetup'
+ ]
+ : hasProductRequest
+ ? ['client', identityViewCompilerModule, 'InboxSetup']
+ : hasProductEnquiry
+ ? [
'client',
- 'Button',
- 'view-context'
+ 'CapabilityGate',
+ identityViewCompilerModule,
+ 'InboxSetup'
]
+ : hasInboxPresentation
+ ? ['client', identityViewCompilerModule, 'InboxSetup']
+ : [
+ 'public-key',
+ 'private-handles',
+ 'public-runtime',
+ 'client',
+ 'Button',
+ identityViewCompilerModule
+ ]
).map((name) => requiredRecord(name)[0]),
'Invalid owned inbox compiler dependencies'
);
if (gate.dynamicImports !== undefined)
throw new Error('Invalid owned inbox compiler dynamic imports');
}
- const [identityKey] = requiredRecord('view-context');
+ const [identityKey] = requiredRecord(identityViewCompilerModule);
if (
!root.imports?.includes(identityKey) ||
!requiredRecord('AccountGate')[1].imports?.includes(identityKey)
@@ -1116,7 +1179,7 @@ export async function auditOutput(webDirectory) {
return row;
};
/** @type {[string,string[]][]} */
- const dependencies = hasProductRequest
+ const dependencies = hasListingPublication
? [
[
'InboxStatus',
@@ -1125,22 +1188,12 @@ export async function auditOutput(webDirectory) {
'client',
'Button',
'navigation',
- 'view-context',
+ 'CapabilityGate',
'InboxSetup',
'inbox-view'
]
],
- [
- 'InboxSetup',
- [
- 'public-key',
- 'private-handles',
- 'public-runtime',
- 'client',
- 'Button',
- 'view-context'
- ]
- ],
+ ['InboxSetup', ['public-runtime', 'client', 'Button']],
['read', ['public-runtime']],
['nodes/4', ['client', 'AccountGate', 'InboxStatus']],
[
@@ -1153,9 +1206,7 @@ export async function auditOutput(webDirectory) {
'Button',
'client.svelte',
'state',
- 'view-context',
'legacy',
- 'InboxSetup',
'inbox-view',
'InboxStatus',
'publishers',
@@ -1170,7 +1221,6 @@ export async function auditOutput(webDirectory) {
'public-runtime',
'references',
'Button',
- 'InboxSetup',
'read'
]
],
@@ -1183,7 +1233,6 @@ export async function auditOutput(webDirectory) {
'client',
'Button',
'navigation',
- 'InboxSetup',
'inbox-view',
'publishers'
]
@@ -1197,12 +1246,12 @@ export async function auditOutput(webDirectory) {
'Button',
'client.svelte',
'state',
- 'view-context',
+ 'CapabilityGate',
'Disclosure'
]
]
]
- : hasProductEnquiry
+ : hasProductRequest
? [
[
'InboxStatus',
@@ -1211,9 +1260,7 @@ export async function auditOutput(webDirectory) {
'client',
'Button',
'navigation',
- 'CapabilityGate',
- 'view-context',
- 'inbox-setup-view',
+ identityViewCompilerModule,
'InboxSetup',
'inbox-view'
]
@@ -1221,11 +1268,12 @@ export async function auditOutput(webDirectory) {
[
'InboxSetup',
[
+ 'public-key',
+ 'private-handles',
'public-runtime',
'client',
'Button',
- 'view-context',
- 'inbox-setup-view'
+ identityViewCompilerModule
]
],
['read', ['public-runtime']],
@@ -1234,23 +1282,21 @@ export async function auditOutput(webDirectory) {
'nodes/5',
[
'public-key',
- 'private-handles',
'public-runtime',
'references',
'client',
'Button',
'client.svelte',
- 'navigation',
'state',
- 'view-context',
+ identityViewCompilerModule,
'legacy',
- 'inbox-setup-view',
+ 'InboxSetup',
'inbox-view',
'InboxStatus',
- 'resolve-head'
+ 'publishers',
+ 'MessageComposer'
]
],
- ['resolve-head', ['public-runtime', 'Button', 'read']],
[
'inbox-view',
[
@@ -1259,21 +1305,24 @@ export async function auditOutput(webDirectory) {
'public-runtime',
'references',
'Button',
- 'inbox-setup-view',
+ 'InboxSetup',
'read'
]
],
[
- 'inbox-setup-view',
+ 'MessageComposer',
[
- 'public-key',
'private-handles',
'public-runtime',
+ 'references',
+ 'client',
'Button',
- 'view-context'
+ 'navigation',
+ 'InboxSetup',
+ 'inbox-view',
+ 'publishers'
]
],
- ['CapabilityGate', ['client', 'Button']],
[
'nodes/0',
[
@@ -1283,62 +1332,148 @@ export async function auditOutput(webDirectory) {
'Button',
'client.svelte',
'state',
- 'CapabilityGate',
- 'Disclosure',
- 'view-context'
+ identityViewCompilerModule,
+ 'Disclosure'
]
]
]
- : [
- [
- 'InboxStatus',
+ : hasProductEnquiry
+ ? [
+ [
+ 'InboxStatus',
+ [
+ 'public-runtime',
+ 'client',
+ 'Button',
+ 'navigation',
+ 'CapabilityGate',
+ identityViewCompilerModule,
+ 'inbox-setup-view',
+ 'InboxSetup',
+ 'inbox-view'
+ ]
+ ],
[
- 'public-key',
- 'private-handles',
- 'public-runtime',
- 'references',
- 'client',
- 'Button',
- 'navigation',
- 'view-context',
'InboxSetup',
- 'read'
- ]
- ],
- [
- 'InboxSetup',
+ [
+ 'public-runtime',
+ 'client',
+ 'Button',
+ identityViewCompilerModule,
+ 'inbox-setup-view'
+ ]
+ ],
+ ['read', ['public-runtime']],
+ ['nodes/4', ['client', 'AccountGate', 'InboxStatus']],
[
- 'public-key',
- 'private-handles',
- 'public-runtime',
- 'client',
- 'Button',
- 'view-context'
+ 'nodes/5',
+ [
+ 'public-key',
+ 'private-handles',
+ 'public-runtime',
+ 'references',
+ 'client',
+ 'Button',
+ 'client.svelte',
+ 'navigation',
+ 'state',
+ identityViewCompilerModule,
+ 'legacy',
+ 'inbox-setup-view',
+ 'inbox-view',
+ 'InboxStatus',
+ 'resolve-head'
+ ]
+ ],
+ ['resolve-head', ['public-runtime', 'Button', 'read']],
+ [
+ 'inbox-view',
+ [
+ 'public-key',
+ 'private-handles',
+ 'public-runtime',
+ 'references',
+ 'Button',
+ 'inbox-setup-view',
+ 'read'
+ ]
+ ],
+ [
+ 'inbox-setup-view',
+ [
+ 'public-key',
+ 'private-handles',
+ 'public-runtime',
+ 'Button',
+ identityViewCompilerModule
+ ]
+ ],
+ ['CapabilityGate', ['client', 'Button']],
+ [
+ 'nodes/0',
+ [
+ 'public-key',
+ 'public-runtime',
+ 'client',
+ 'Button',
+ 'client.svelte',
+ 'state',
+ 'CapabilityGate',
+ 'Disclosure',
+ identityViewCompilerModule
+ ]
]
- ],
- ['read', ['public-runtime']],
- ['nodes/4', ['client', 'AccountGate', 'InboxStatus']],
- [
- 'nodes/5',
+ ]
+ : [
[
- 'public-key',
- 'private-handles',
- 'public-runtime',
- 'references',
- 'client',
- 'Button',
- 'client.svelte',
- 'navigation',
- 'state',
- 'view-context',
- 'legacy',
- 'InboxSetup',
'InboxStatus',
- 'resolve-head'
- ]
- ],
- ['resolve-head', ['public-runtime', 'Button', 'read']]
- ];
+ [
+ 'public-key',
+ 'private-handles',
+ 'public-runtime',
+ 'references',
+ 'client',
+ 'Button',
+ 'navigation',
+ identityViewCompilerModule,
+ 'InboxSetup',
+ 'read'
+ ]
+ ],
+ [
+ 'InboxSetup',
+ [
+ 'public-key',
+ 'private-handles',
+ 'public-runtime',
+ 'client',
+ 'Button',
+ identityViewCompilerModule
+ ]
+ ],
+ ['read', ['public-runtime']],
+ ['nodes/4', ['client', 'AccountGate', 'InboxStatus']],
+ [
+ 'nodes/5',
+ [
+ 'public-key',
+ 'private-handles',
+ 'public-runtime',
+ 'references',
+ 'client',
+ 'Button',
+ 'client.svelte',
+ 'navigation',
+ 'state',
+ identityViewCompilerModule,
+ 'legacy',
+ 'InboxSetup',
+ 'InboxStatus',
+ 'resolve-head'
+ ]
+ ],
+ ['resolve-head', ['public-runtime', 'Button', 'read']]
+ ];
for (const [name, imports] of dependencies) {
const [key, row] = entry(name);
equal(
@@ -1426,7 +1561,7 @@ export async function auditOutput(webDirectory) {
'Button',
'client.svelte',
'state',
- 'view-context',
+ identityViewCompilerModule,
'Disclosure',
'InboxSetup',
'MessageComposer'