commit 687c5f9e3baee70c74044b46e8b86b43a23f9fdb
parent 96e6294d9440d9fe46cc06792b3a424f04dda30b
Author: triesap <tyson@radroots.org>
Date: Wed, 14 Oct 2026 11:01:03 +0000
harvestcircle_web: Preserve original inbox probe archive attempts
Bind probe publication to genuine original custody and one shared budget.
Persist only actual SDK archive evidence after exact native completion and readback.
Retain original cleanup through callback reentry and scope Stop retries.
RCLD-HCP-CR008-S4B1
Diffstat:
11 files changed, 2609 insertions(+), 234 deletions(-)
diff --git a/web/src/lib/nostr/inbox-access.ts b/web/src/lib/nostr/inbox-access.ts
@@ -46,6 +46,7 @@ export type InboxProbeReservationResult =
}>;
type Saved = {
session: PrivateSession;
+ policy: RelayPolicy;
record: PrivateAccessProbe;
handle: PrivateRecordHandle;
wire(): string | undefined;
@@ -243,6 +244,7 @@ export async function reserveInboxProbeIdentity(
offAccess = () => {};
const saved: Saved = {
session,
+ policy,
record,
handle: handle.value,
wire: () => wire,
@@ -355,3 +357,18 @@ export function inboxProbeReservationHandle(
export function stopInboxProbeIdentity(identity: InboxProbeIdentity): void {
identities.get(identity)?.stop();
}
+
+// Canonical policy bytes cannot substitute for the original opaque policy.
+export function inboxProbePolicyMatches(
+ identity: InboxProbeIdentity,
+ session: PrivateSession,
+ policy: RelayPolicy
+): boolean {
+ const saved = identities.get(identity);
+ return (
+ !!saved &&
+ saved.session === session &&
+ saved.policy === policy &&
+ saved.current()
+ );
+}
diff --git a/web/src/lib/nostr/private-pool.ts b/web/src/lib/nostr/private-pool.ts
@@ -5,7 +5,10 @@ import {
privatePublicationSnapshot,
takePrivatePublication,
type PrivatePublication,
- type PrivateDeliveryRole
+ type PrivateDeliveryRole,
+ inboxProbePublicationSnapshot,
+ takeInboxProbePublication,
+ type InboxProbePublication
} from './private-publisher.ts';
import {
takeInboxAuthAdmission,
@@ -45,6 +48,31 @@ export type PrivateGiftWrapAttemptResult = Readonly<{
actionId?: string;
attempt?: number;
}>;
+export type InboxProbeArchiveAttemptResult = Readonly<{
+ status: PrivateGiftWrapAttemptResult['status'];
+ role?: 'access_archive';
+ origin?: string;
+ eventId?: string;
+ actionId?: string;
+ attempt?: number;
+}>;
+type PublicationAttemptResult =
+ PrivateGiftWrapAttemptResult | InboxProbeArchiveAttemptResult;
+const probeAttemptEvidence = new WeakMap<
+ InboxProbeArchiveAttemptResult,
+ Readonly<{
+ repository: PrivateStorageRepository;
+ acknowledgement: import('../persistence/inbox-probes.ts').InboxProbeAcknowledgement;
+ predecessorWire: string;
+ receiptWire: string;
+ }>
+>();
+export function inboxProbeArchiveAttemptEvidence(
+ result: InboxProbeArchiveAttemptResult
+) {
+ const evidence = probeAttemptEvidence.get(result);
+ return evidence && { ...evidence };
+}
type AttemptEvidence = Readonly<{
repository: PrivateStorageRepository;
owner: string;
@@ -122,14 +150,15 @@ type Owner = {
cleaned(): boolean;
unavailable(): boolean;
publish(
- permission: PrivatePublication,
+ permission: PrivatePublication | InboxProbePublication,
signal: AbortSignal,
scopeCurrent?: () => boolean,
retainConnection?: (
origin: string,
cleanup: ScopedConnectionCleanup
- ) => boolean
- ): Promise<PrivateGiftWrapAttemptResult>;
+ ) => boolean,
+ retainPublicationCleanup?: (cleanup: () => void) => () => void
+ ): Promise<PublicationAttemptResult>;
auth(
origin: string,
admission: InboxAuthAdmission,
@@ -217,6 +246,7 @@ function scopedPool(
const life = new AbortController();
const stops = new Map<symbol, () => void>();
const authStops = new Map<string, () => void>();
+ const probePublicationStops = new Map<() => void, true>();
const connections = new Map<string, ScopedConnectionCleanup>();
let closed = false,
cleaned = false;
@@ -266,13 +296,23 @@ function scopedPool(
cleaned: () => (cleaned && !base.unavailable()) || base.cleaned(),
unavailable: () => base.unavailable() || (closed && !cleaned),
publish(permission, signal) {
- const view = privatePublicationSnapshot(permission);
+ const view =
+ privatePublicationSnapshot(permission as PrivatePublication) ??
+ inboxProbePublicationSnapshot(permission as InboxProbePublication);
return current() && view && origins.includes(view.origin)
? base.publish(
permission,
AbortSignal.any([signal, life.signal]),
current,
- retainConnection
+ retainConnection,
+ inboxProbePublicationSnapshot(permission as InboxProbePublication)
+ ? (cleanup) => {
+ probePublicationStops.set(cleanup, true);
+ return () => {
+ probePublicationStops.delete(cleanup);
+ };
+ }
+ : undefined
)
: Promise.resolve({ status: 'stopped' });
},
@@ -338,6 +378,14 @@ function scopedPool(
failed = true;
}
}
+ for (const cleanup of probePublicationStops.keys()) {
+ try {
+ cleanup();
+ probePublicationStops.delete(cleanup);
+ } catch {
+ failed = true;
+ }
+ }
for (const [origin, stop] of authStops) {
try {
stop();
@@ -435,6 +483,7 @@ export function getPrivatePool(
const authFailed = new Map<string, true>();
const authRetiring = new Map<string, true>();
const publicationStops = new Map<() => void, true>();
+ const publicationFailures = new Map<() => void, true>();
let publishing = false,
publicationCleanupRequired = false;
type Connection = Readonly<{
@@ -450,6 +499,25 @@ export function getPrivatePool(
}>;
}>;
const connections = new Map<string, Connection>();
+ function probeRelayAuthReady(
+ relay: ReturnType<typeof sdk.relay>,
+ origin: string
+ ) {
+ let required: boolean | undefined;
+ const observation = relay.authRequiredForPublish$.subscribe((value) => {
+ required = value;
+ });
+ observation.unsubscribe();
+ return (
+ required !== undefined &&
+ !(
+ (required || authCleanup.has(origin)) &&
+ (!relay.authenticated || relay.authenticatedAs !== capture.owner)
+ ) &&
+ (!relay.authenticated || relay.authenticatedAs === capture.owner)
+ );
+ }
+
function leaseConnection(origin: string) {
const previous = connections.get(origin);
if (previous) {
@@ -591,9 +659,14 @@ export function getPrivatePool(
permission,
signal,
scopeCurrent = () => true,
- retainConnection
+ retainConnection,
+ retainPublicationCleanup
) {
- const observed = privatePublicationSnapshot(permission);
+ const probe = inboxProbePublicationSnapshot(
+ permission as InboxProbePublication
+ );
+ const observed =
+ probe ?? privatePublicationSnapshot(permission as PrivatePublication);
if (!observed) return { status: 'stopped' };
const view = observed;
if (
@@ -619,6 +692,25 @@ export function getPrivatePool(
return { status: 'stopped' };
publishing = true;
try {
+ // A genuine C7 AUTH provider job may occupy the shared SDK scheduler.
+ // Observe that original connection before queueing another fresh-key
+ // job, so known waiting refuses without a probe prompt/meter/effect.
+ if (probe) {
+ const originalConnection = connections.get(view.origin);
+ if (originalConnection) {
+ if (originalConnection.retiring()) return { status: 'stopped' };
+ const observation = originalConnection.reserve();
+ try {
+ if (
+ !observation.current() ||
+ !probeRelayAuthReady(observation.relay, view.origin)
+ )
+ return { status: 'stopped' };
+ } finally {
+ observation.close();
+ }
+ }
+ }
// No owner lock is held across the serialized fresh extension job.
if (
!(await recheckPrivateSession(session)) ||
@@ -644,12 +736,19 @@ export function getPrivatePool(
authFailed.has(view.origin)
)
return { status: 'stopped' as const };
- const admitted = await takePrivatePublication(
- permission,
- session,
- policy,
- view.origin
- );
+ const admitted = probe
+ ? await takeInboxProbePublication(
+ permission as InboxProbePublication,
+ session,
+ policy,
+ view.origin
+ )
+ : await takePrivatePublication(
+ permission as PrivatePublication,
+ session,
+ policy,
+ view.origin
+ );
if (
!admitted ||
closed ||
@@ -662,6 +761,18 @@ export function getPrivatePool(
)
return { status: 'stopped' as const };
const connection = leaseConnection(view.origin);
+ // Stock SDK EVENT can wait behind known AUTH. Refuse probe work
+ // before starting its meter; only separate explicit C7 AUTH signs.
+ if (probe) {
+ if (
+ !probeRelayAuthReady(connection.relay, view.origin) ||
+ !connection.current() ||
+ !admitted.current()
+ ) {
+ connection.close();
+ return { status: 'stopped' as const };
+ }
+ }
const network = admitted.beginNetwork();
if (admitted.networkMetered && !network) {
connection.close();
@@ -679,163 +790,227 @@ export function getPrivatePool(
connection.close();
return { status: 'stopped' as const };
}
- return await new Promise<PrivateGiftWrapAttemptResult>(
- (resolve) => {
- let ended = false,
- attempted = false,
- release = () => {},
- fenceTimer: ReturnType<typeof setTimeout> | undefined,
- timer: ReturnType<typeof setTimeout> | undefined,
- retainedConnection = false;
- function finish(
- status: PrivateGiftWrapAttemptResult['status']
- ) {
- if (ended) return;
- ended = true;
- network?.finish();
- if (timer !== undefined) clearTimeout(timer);
- if (fenceTimer !== undefined) clearTimeout(fenceTimer);
- signal.removeEventListener('abort', stop);
- try {
- release();
- if (!retainedConnection) connection.close();
- publicationStops.delete(stop);
- } catch {
- publicationCleanupRequired = true;
- status = 'unknown';
- }
- if (!attempted) status = 'stopped';
- const result: PrivateGiftWrapAttemptResult = {
- status,
+ return await new Promise<PublicationAttemptResult>((resolve) => {
+ let ended = false,
+ attempted = false,
+ release = () => {},
+ forgetCleanup = () => {},
+ fenceTimer: ReturnType<typeof setTimeout> | undefined,
+ timer: ReturnType<typeof setTimeout> | undefined,
+ retainedConnection = false,
+ releasing = false;
+ function disposeOriginal() {
+ // The stock unsubscribe can run finalizers. Nested Stop must
+ // retain this exact port until the outer cleanup really settles.
+ if (releasing)
+ throw Error('private_publication_cleanup_pending');
+ releasing = true;
+ try {
+ release();
+ if (!retainedConnection) connection.close();
+ publicationStops.delete(stop);
+ publicationFailures.delete(stop);
+ publicationCleanupRequired = publicationFailures.size !== 0;
+ forgetCleanup();
+ } finally {
+ releasing = false;
+ }
+ }
+ function retainFailure() {
+ publicationStops.set(stop, true);
+ publicationFailures.set(stop, true);
+ publicationCleanupRequired = true;
+ forgetCleanup = retainPublicationCleanup?.(stop) ?? (() => {});
+ }
+ function finish(status: PrivateGiftWrapAttemptResult['status']) {
+ if (ended) return;
+ ended = true;
+ network?.finish();
+ if (timer !== undefined) clearTimeout(timer);
+ if (fenceTimer !== undefined) clearTimeout(fenceTimer);
+ signal.removeEventListener('abort', stop);
+ try {
+ disposeOriginal();
+ } catch {
+ retainFailure();
+ status = 'unknown';
+ }
+ if (!attempted) status = 'stopped';
+ const result: PublicationAttemptResult = {
+ status,
+ role: admitted!.role,
+ origin: admitted!.origin,
+ eventId: admitted!.eventId,
+ ...(attempted && network
+ ? { actionId: network.actionId, attempt: network.attempt }
+ : {})
+ };
+ if (attempted && network) {
+ const receiptWire = JSON.stringify({
+ actionId: network.actionId,
role: admitted!.role,
origin: admitted!.origin,
eventId: admitted!.eventId,
- ...(attempted && network
- ? { actionId: network.actionId, attempt: network.attempt }
- : {})
- };
- if (attempted && network) {
- attemptEvidence.set(result, {
- repository: admitted!.repository,
- owner: admitted!.owner,
- command: admitted!.command,
- pairWire: admitted!.pairWire,
- receiptWire: JSON.stringify({
- actionId: network.actionId,
- role: admitted!.role,
- origin: admitted!.origin,
- eventId: admitted!.eventId,
- attempt: network.attempt,
- status,
- observedAtMilliseconds: Date.now(),
- readbackWire: null
- })
- });
+ attempt: network.attempt,
+ status,
+ observedAtMilliseconds: Date.now(),
+ readbackWire: null
+ });
+ if ('acknowledgement' in admitted!) {
+ probeAttemptEvidence.set(
+ result as InboxProbeArchiveAttemptResult,
+ {
+ repository: admitted.repository,
+ acknowledgement: admitted.acknowledgement,
+ predecessorWire: admitted.predecessorWire,
+ receiptWire
+ }
+ );
+ } else {
+ attemptEvidence.set(
+ result as PrivateGiftWrapAttemptResult,
+ {
+ repository: admitted!.repository,
+ owner: admitted!.owner,
+ command: admitted!.command,
+ pairWire: admitted!.pairWire,
+ receiptWire
+ }
+ );
}
- resolve(result);
}
- function stop() {
- if (ended) {
- release();
- if (!retainedConnection) connection.close();
- publicationStops.delete(stop);
- return;
- }
- finish('stopped');
+ resolve(result);
+ }
+ function stop() {
+ if (ended) {
+ disposeOriginal();
+ return;
}
- function fence() {
- if (ended) return;
- if (network && network.remaining() <= 0) {
- finish('timed_out');
- return;
- }
- if (
- closed ||
+ finish('stopped');
+ }
+ function probeStopped() {
+ return (
+ !!probe &&
+ (closed ||
signal.aborted ||
!scopeCurrent() ||
!capture.current() ||
authRetiring.has(view.origin) ||
authFailed.has(view.origin) ||
- !admitted!.current()
- ) {
- finish('stopped');
- return;
- }
- fenceTimer = setTimeout(() => fence(), 50);
+ !admitted!.current())
+ );
+ }
+ function fence() {
+ if (ended) return;
+ if (probeStopped()) {
+ finish('stopped');
+ return;
}
- try {
- const relay = connection.relay;
- const allowance =
- network?.remaining() ??
- PRIVATE_PUBLICATION_BUDGETS.networkActionMilliseconds;
- const timeout =
- Number.isFinite(relay.eventTimeout) &&
- relay.eventTimeout > 0
- ? Math.min(allowance, relay.eventTimeout)
- : allowance;
- timer = setTimeout(() => finish('timed_out'), timeout);
- signal.addEventListener('abort', stop, { once: true });
- publicationStops.set(stop, true);
- if (
- closed ||
- signal.aborted ||
- !scopeCurrent() ||
- !capture.current() ||
- authRetiring.has(view.origin) ||
- authFailed.has(view.origin) ||
- !admitted.current()
- ) {
- finish('stopped');
- return;
- }
- // The only private EVENT port accepts the freshly read-back1059;
- // no caller event, key, relay template or SDK option crosses it.
- connection.start();
- retainedConnection =
- retainConnection?.(view.origin, {
- current: connection.current,
- close: connection.close
- }) ?? false;
- attempted = true;
- const subscription = relay
- .event(admitted.event, 'EVENT')
- .subscribe({
- next(response) {
- if (ended) return;
- if (network && network.remaining() <= 0) {
- finish('timed_out');
- return;
- }
- if (
- (response.from !== view.origin &&
- response.from !== view.origin + '/') ||
- typeof response.ok !== 'boolean'
- )
- finish('unknown');
- else if (response.ok) finish('accepted');
- else if (response.message === 'Timeout')
- finish('unknown');
- else finish('refused');
- },
- error: () => finish('unknown'),
- complete: () => {
- if (!ended) finish('unknown');
+ if (network && network.remaining() <= 0) {
+ finish('timed_out');
+ return;
+ }
+ if (
+ closed ||
+ signal.aborted ||
+ !scopeCurrent() ||
+ !capture.current() ||
+ authRetiring.has(view.origin) ||
+ authFailed.has(view.origin) ||
+ !admitted!.current()
+ ) {
+ finish('stopped');
+ return;
+ }
+ fenceTimer = setTimeout(() => fence(), 50);
+ }
+ try {
+ const relay = connection.relay;
+ const allowance =
+ network?.remaining() ??
+ PRIVATE_PUBLICATION_BUDGETS.networkActionMilliseconds;
+ const timeout =
+ Number.isFinite(relay.eventTimeout) && relay.eventTimeout > 0
+ ? Math.min(allowance, relay.eventTimeout)
+ : allowance;
+ timer = setTimeout(
+ () => finish(probeStopped() ? 'stopped' : 'timed_out'),
+ timeout
+ );
+ signal.addEventListener('abort', stop, { once: true });
+ publicationStops.set(stop, true);
+ forgetCleanup = retainPublicationCleanup?.(stop) ?? (() => {});
+ if (
+ closed ||
+ signal.aborted ||
+ !scopeCurrent() ||
+ !capture.current() ||
+ authRetiring.has(view.origin) ||
+ authFailed.has(view.origin) ||
+ !admitted.current()
+ ) {
+ finish('stopped');
+ return;
+ }
+ // The only private EVENT port accepts the freshly read-back1059;
+ // no caller event, key, relay template or SDK option crosses it.
+ connection.start();
+ retainedConnection =
+ retainConnection?.(view.origin, {
+ current: connection.current,
+ close: connection.close
+ }) ?? false;
+ if (
+ probe &&
+ (probeStopped() ||
+ !connection.current() ||
+ !probeRelayAuthReady(relay, view.origin))
+ ) {
+ finish('stopped');
+ return;
+ }
+ attempted = true;
+ const subscription = relay
+ .event(admitted.event, 'EVENT')
+ .subscribe({
+ next(response) {
+ if (ended) return;
+ if (probeStopped()) {
+ finish('stopped');
+ return;
}
- });
- release = () => subscription.unsubscribe();
- if (ended) {
- try {
- release();
- publicationStops.delete(stop);
- } catch {
- publicationCleanupRequired = true;
+ if (network && network.remaining() <= 0) {
+ finish('timed_out');
+ return;
+ }
+ if (
+ (response.from !== view.origin &&
+ response.from !== view.origin + '/') ||
+ typeof response.ok !== 'boolean'
+ )
+ finish('unknown');
+ else if (response.ok) finish('accepted');
+ else if (response.message === 'Timeout')
+ finish('unknown');
+ else finish('refused');
+ },
+ error: () => finish('unknown'),
+ complete: () => {
+ if (!ended) finish('unknown');
}
- } else fence();
- } catch {
- finish('unknown');
- }
+ });
+ release = () => subscription.unsubscribe();
+ if (ended) {
+ try {
+ disposeOriginal();
+ } catch {
+ retainFailure();
+ }
+ } else fence();
+ } catch {
+ finish('unknown');
}
- );
+ });
}
);
} catch {
@@ -1762,7 +1937,28 @@ export function publishPrivateGiftWrapAttempt(
signal: AbortSignal
): Promise<PrivateGiftWrapAttemptResult> {
try {
- return ownerOf(pool).publish(permission, signal);
+ if (!privatePublicationSnapshot(permission))
+ return Promise.resolve({ status: 'stopped' });
+ return ownerOf(pool).publish(
+ permission,
+ signal
+ ) as Promise<PrivateGiftWrapAttemptResult>;
+ } catch {
+ return Promise.resolve({ status: 'stopped' });
+ }
+}
+export function publishInboxProbeArchiveAttempt(
+ pool: PrivatePool,
+ permission: InboxProbePublication,
+ signal: AbortSignal
+): Promise<InboxProbeArchiveAttemptResult> {
+ try {
+ if (!inboxProbePublicationSnapshot(permission))
+ return Promise.resolve({ status: 'stopped' });
+ return ownerOf(pool).publish(
+ permission,
+ signal
+ ) as Promise<InboxProbeArchiveAttemptResult>;
} catch {
return Promise.resolve({ status: 'stopped' });
}
diff --git a/web/src/lib/nostr/private-publisher.ts b/web/src/lib/nostr/private-publisher.ts
@@ -1,4 +1,10 @@
import {
+ inboxProbePublicationBinding,
+ verifyInboxProbeAcknowledgement,
+ type InboxProbeAcknowledgement
+} from '../persistence/inbox-probes.ts';
+import type { InboxProbeIdentity } from './inbox-access.ts';
+import {
privateSessionOwnership,
type PrivateSession
} from '../runtime/private-session.ts';
@@ -64,38 +70,9 @@ function immutablePair(receipt: PairedDeliveryAcknowledgement) {
})
);
}
-// One explicit action has one network meter, including all artifacts/targets.
-// SDK identity approval and persisted readback happen before an attempt starts.
-export function capturePrivatePublicationAction(
- repository: PrivateStorageRepository,
- session: PrivateSession,
- receipt: PairedDeliveryAcknowledgement,
- context: PairedDeliveryContext,
- review: unknown
-): PrivatePublicationAction | undefined {
- if (review !== 'reviewed_private_retry') return undefined;
- const row = pairedDeliveryAcknowledgementSnapshot(receipt),
- original = immutablePair(receipt),
- ownership = privateSessionOwnership(session);
- if (!row || !original || !ownership?.current()) return undefined;
- for (const route of [
- row.deliveryPlan.routes.peer,
- row.deliveryPlan.routes.archive
- ])
- for (const origin of route.targets) {
- if (
- !capturePrivatePublication(
- repository,
- session,
- receipt,
- context,
- route.role,
- origin,
- 'reviewed_private_delivery'
- )
- )
- return undefined;
- }
+// Source-owned meter shared by ordinary actions and the original probe action.
+// Provider/native custody waits happen before begin; no caller clock or reset.
+function networkMeter(probe: boolean) {
const actionId = newLocalId();
if (!actionId) return undefined;
const counts = new Map<string, number>();
@@ -112,33 +89,24 @@ export function capturePrivatePublicationAction(
last = now;
return now;
}
- function current() {
- return (
- !broken &&
- ownership!.current() &&
- immutablePair(receipt) === original &&
- recheckInboxRoutePlan(
- context.plan,
- context.policy,
- context.own,
- context.other
- ) === 'unchanged'
- );
- }
- const token = Object.freeze({}) as PrivatePublicationAction;
- actions.set(token, {
- session,
- receipt,
- context,
- current,
- begin(role, origin, eventId) {
+ return {
+ current: () => !broken,
+ begin(
+ role: PrivateDeliveryRole | 'access_archive' | 'access_readback',
+ origin: string,
+ eventId: string,
+ current: () => boolean
+ ): NetworkAttempt | undefined {
if (
+ broken ||
!current() ||
running ||
used >= PRIVATE_PUBLICATION_BUDGETS.networkActionMilliseconds
)
return undefined;
- const key = JSON.stringify([role, origin, eventId]),
+ const key = JSON.stringify(
+ probe ? [origin, eventId] : [role, origin, eventId]
+ ),
count = counts.get(key) ?? 0;
if (count >= PRIVATE_PUBLICATION_BUDGETS.attemptsPerTargetAction)
return undefined;
@@ -177,6 +145,63 @@ export function capturePrivatePublicationAction(
}
};
}
+ };
+}
+// One explicit action has one network meter, including all artifacts/targets.
+// SDK identity approval and persisted readback happen before an attempt starts.
+export function capturePrivatePublicationAction(
+ repository: PrivateStorageRepository,
+ session: PrivateSession,
+ receipt: PairedDeliveryAcknowledgement,
+ context: PairedDeliveryContext,
+ review: unknown
+): PrivatePublicationAction | undefined {
+ if (review !== 'reviewed_private_retry') return undefined;
+ const row = pairedDeliveryAcknowledgementSnapshot(receipt),
+ original = immutablePair(receipt),
+ ownership = privateSessionOwnership(session);
+ if (!row || !original || !ownership?.current()) return undefined;
+ for (const route of [
+ row.deliveryPlan.routes.peer,
+ row.deliveryPlan.routes.archive
+ ])
+ for (const origin of route.targets) {
+ if (
+ !capturePrivatePublication(
+ repository,
+ session,
+ receipt,
+ context,
+ route.role,
+ origin,
+ 'reviewed_private_delivery'
+ )
+ )
+ return undefined;
+ }
+ const meter = networkMeter(false);
+ if (!meter) return undefined;
+ function current() {
+ return (
+ meter!.current() &&
+ ownership!.current() &&
+ immutablePair(receipt) === original &&
+ recheckInboxRoutePlan(
+ context.plan,
+ context.policy,
+ context.own,
+ context.other
+ ) === 'unchanged'
+ );
+ }
+ const token = Object.freeze({}) as PrivatePublicationAction;
+ actions.set(token, {
+ session,
+ receipt,
+ context,
+ current,
+ begin: (role, origin, eventId) =>
+ meter.begin(role, origin, eventId, current)
});
return token;
}
@@ -408,3 +433,259 @@ export async function takePrivatePublication(
return undefined;
}
}
+
+declare const probeActionBrand: unique symbol;
+export type InboxProbePublicationAction = Readonly<{
+ [probeActionBrand]: true;
+}>;
+declare const probePublicationBrand: unique symbol;
+export type InboxProbePublication = Readonly<{ [probePublicationBrand]: true }>;
+type ProbeAction = {
+ token: InboxProbePublicationAction;
+ repository: PrivateStorageRepository;
+ session: PrivateSession;
+ policy: RelayPolicy;
+ identity: InboxProbeIdentity;
+ original: string;
+ current(): boolean;
+ meter: NonNullable<ReturnType<typeof networkMeter>>;
+};
+const probeActions = new WeakMap<InboxProbePublicationAction, ProbeAction>();
+const identityActions = new WeakMap<InboxProbeIdentity, ProbeAction | null>();
+function probeImmutable(
+ row: NonNullable<ReturnType<typeof inboxProbePublicationBinding>>['record']
+) {
+ return JSON.stringify({
+ owner: row.owner,
+ id: row.id,
+ rumorHash: row.rumorHash,
+ createdAt: row.createdAt,
+ binding: row.binding,
+ self: row.self
+ });
+}
+export function captureInboxProbePublicationAction(
+ repository: PrivateStorageRepository,
+ session: PrivateSession,
+ policy: RelayPolicy,
+ acknowledgement: InboxProbeAcknowledgement,
+ review: unknown
+): InboxProbePublicationAction | undefined {
+ if (
+ typeof window === 'undefined' ||
+ review !== 'reviewed_inbox_probe_network'
+ )
+ return undefined;
+ try {
+ const binding = inboxProbePublicationBinding(
+ repository,
+ session,
+ acknowledgement,
+ policy
+ );
+ if (!binding || !binding.record.self) return undefined;
+ const original = probeImmutable(binding.record),
+ prior = identityActions.get(binding.identity);
+ if (identityActions.has(binding.identity))
+ return prior &&
+ prior.repository === repository &&
+ prior.session === session &&
+ prior.policy === policy &&
+ prior.original === original &&
+ prior.current()
+ ? prior.token
+ : undefined;
+ // Reserve this original identity before callback-capable UUID creation.
+ // Reentrant capture refuses; failed admission never grants a new meter.
+ identityActions.set(binding.identity, null);
+ const meter = networkMeter(true);
+ if (!meter || !binding.current()) return undefined;
+ const token = Object.freeze({}) as InboxProbePublicationAction;
+ const captured: ProbeAction = {
+ token,
+ repository,
+ session,
+ policy,
+ identity: binding.identity,
+ original,
+ current: () => meter.current() && binding.current(),
+ meter
+ };
+ identityActions.set(binding.identity, captured);
+ probeActions.set(token, captured);
+ return token;
+ } catch {
+ return undefined;
+ }
+}
+type ProbePermission = {
+ action: ProbeAction;
+ acknowledgement: InboxProbeAcknowledgement;
+ wire: string;
+ predecessorWire: string;
+ owner: string;
+ command: string;
+ origin: string;
+ eventId: string;
+ current(): boolean;
+ take(): boolean;
+};
+const probePermissions = new WeakMap<InboxProbePublication, ProbePermission>();
+export function captureInboxProbePublication(
+ repository: PrivateStorageRepository,
+ session: PrivateSession,
+ policy: RelayPolicy,
+ acknowledgement: InboxProbeAcknowledgement,
+ action: InboxProbePublicationAction,
+ origin: string,
+ review: unknown
+): InboxProbePublication | undefined {
+ if (
+ typeof window === 'undefined' ||
+ review !== 'reviewed_inbox_probe_publication'
+ )
+ return undefined;
+ try {
+ const captured = probeActions.get(action),
+ binding = inboxProbePublicationBinding(
+ repository,
+ session,
+ acknowledgement,
+ policy
+ );
+ if (
+ !captured ||
+ !binding ||
+ captured.repository !== repository ||
+ captured.session !== session ||
+ captured.policy !== policy ||
+ captured.identity !== binding.identity ||
+ !captured.current() ||
+ captured.original !== probeImmutable(binding.record) ||
+ !binding.record.self ||
+ !binding.record.binding.archiveTargets.includes(origin)
+ )
+ return undefined;
+ if (
+ !readRelayPolicy(policy).inbox.some(
+ ({ origin: allowed, write }) => allowed === origin && write
+ )
+ )
+ return undefined;
+ const artifact = binding.record.self,
+ verified = verifyEnvelope(artifact.wire),
+ event = verified.ok && verifiedEnvelopeSnapshot(verified.value);
+ if (
+ !event ||
+ event.kind !== 1059 ||
+ event.id !== artifact.eventId ||
+ JSON.stringify(event.tags) !==
+ JSON.stringify([['p', binding.record.owner]])
+ )
+ return undefined;
+ const predecessorWire = binding.wire;
+ let consumed = false;
+ function current() {
+ const fresh = inboxProbePublicationBinding(
+ repository,
+ session,
+ acknowledgement,
+ policy
+ );
+ return (
+ captured!.current() &&
+ !!fresh &&
+ fresh.identity === captured!.identity &&
+ fresh.wire === predecessorWire &&
+ probeImmutable(fresh.record) === captured!.original
+ );
+ }
+ const token = Object.freeze({}) as InboxProbePublication;
+ probePermissions.set(token, {
+ action: captured,
+ acknowledgement,
+ wire: artifact.wire,
+ predecessorWire,
+ owner: binding.record.owner,
+ command: binding.record.id,
+ origin,
+ eventId: event.id,
+ current,
+ take() {
+ if (consumed) return false;
+ consumed = true;
+ return true;
+ }
+ });
+ return token;
+ } catch {
+ return undefined;
+ }
+}
+export function inboxProbePublicationSnapshot(
+ permission: InboxProbePublication
+) {
+ const saved = probePermissions.get(permission);
+ return saved?.current()
+ ? {
+ owner: saved.owner,
+ command: saved.command,
+ role: 'access_archive' as const,
+ origin: saved.origin,
+ eventId: saved.eventId
+ }
+ : undefined;
+}
+export async function takeInboxProbePublication(
+ permission: InboxProbePublication,
+ session: PrivateSession,
+ policy: RelayPolicy,
+ origin: string
+) {
+ const saved = probePermissions.get(permission);
+ if (
+ !saved ||
+ saved.action.session !== session ||
+ saved.action.policy !== policy ||
+ saved.origin !== origin ||
+ !saved.current() ||
+ !saved.take()
+ )
+ return undefined;
+ if (
+ !(await verifyInboxProbeAcknowledgement(
+ saved.action.repository,
+ session,
+ saved.acknowledgement
+ )) ||
+ !saved.current()
+ )
+ return undefined;
+ const verified = verifyEnvelope(saved.wire),
+ event = verified.ok && verifiedEnvelopeSnapshot(verified.value);
+ if (
+ !event ||
+ event.kind !== 1059 ||
+ event.id !== saved.eventId ||
+ JSON.stringify(event.tags) !== JSON.stringify([['p', saved.owner]]) ||
+ !saved.current()
+ )
+ return undefined;
+ return {
+ event,
+ repository: saved.action.repository,
+ acknowledgement: saved.acknowledgement,
+ predecessorWire: saved.predecessorWire,
+ current: () => saved.current(),
+ owner: saved.owner,
+ command: saved.command,
+ role: 'access_archive' as const,
+ origin,
+ eventId: saved.eventId,
+ networkMetered: true,
+ beginNetwork: () =>
+ saved.action.meter.begin('access_archive', origin, saved.eventId, () =>
+ saved.current()
+ )
+ };
+}
diff --git a/web/src/lib/persistence/inbox-probes.ts b/web/src/lib/persistence/inbox-probes.ts
@@ -1,4 +1,10 @@
import {
+ inboxProbeArchiveAttemptEvidence,
+ type InboxProbeArchiveAttemptResult
+} from '../nostr/private-pool.ts';
+import { inboxProbePolicyMatches } from '../nostr/inbox-access.ts';
+import type { RelayPolicy } from '../config/relays.ts';
+import {
inboxProbeGiftwrapSnapshot,
inboxProbeGiftwrapSeal,
type InboxProbeGiftwrap
@@ -25,6 +31,7 @@ import {
import {
decodePrivateRecord,
privateRecordWire,
+ privateRecordSnapshot,
type PrivateAccessProbe
} from './private-records.ts';
import {
@@ -45,12 +52,52 @@ export type InboxProbeCommitResult =
status: PrivateStorageFailure | 'invalid' | 'busy' | 'stopped';
disposition: 'original_protected';
}>;
+type Lineage = {
+ repository: PrivateStorageRepository;
+ session: PrivateSession;
+ identity: InboxProbeIdentity;
+ record(): PrivateAccessProbe;
+ wire(): string;
+ begin(): boolean;
+ finish(): void;
+ admit(record: PrivateAccessProbe, wire: string): void;
+};
+function createLineage(
+ repository: PrivateStorageRepository,
+ session: PrivateSession,
+ identity: InboxProbeIdentity,
+ originalRecord: PrivateAccessProbe,
+ originalWire: string
+): Lineage {
+ let record = originalRecord,
+ wire = originalWire,
+ pending = false;
+ return {
+ repository,
+ session,
+ identity,
+ record: () => record,
+ wire: () => wire,
+ begin() {
+ if (pending) return false;
+ pending = true;
+ return true;
+ },
+ finish() {
+ pending = false;
+ },
+ admit(next, nextWire) {
+ record = next;
+ wire = nextWire;
+ }
+ };
+}
+const lineages = new WeakMap<InboxProbeIdentity, Lineage>();
type Saved = Readonly<{
repository: PrivateStorageRepository;
session: PrivateSession;
identity: InboxProbeIdentity;
- record: PrivateAccessProbe;
- wire: string;
+ lineage: Lineage;
current(): boolean;
revoke(): void;
}>;
@@ -197,11 +244,19 @@ export async function commitInboxProbe(
);
if (!original.current()) return refuse('stopped');
if (!loaded.ok) return refuse(loaded.reason);
+ const previous = lineages.get(original.identity);
+ if (
+ previous &&
+ (previous.repository !== repository ||
+ previous.session !== session)
+ )
+ return refuse('invalid_scope');
+ const expectedWire = previous?.wire() ?? original.wire;
let status: 'prepared' | 'existing' | 'reconciled';
- if (loaded.value.wire === original.wire) {
+ if (loaded.value.wire === expectedWire) {
status = 'existing';
} else {
- if (loaded.value.wire !== original.reservationWire)
+ if (previous || loaded.value.wire !== original.reservationWire)
return refuse('conflict');
const committed = await commitPrivateRecord(
repository,
@@ -224,16 +279,25 @@ export async function commitInboxProbe(
);
if (!original.current()) return refuse('stopped');
if (!readback.ok) return refuse(readback.reason);
- if (readback.value.wire !== original.wire)
- return refuse('conflict');
+ if (readback.value.wire !== expectedWire) return refuse('conflict');
// The handle and physical wire have both passed complete-owner
// validation. Their equality is checked independently of metadata
// normalization; equivalent raw JSON changes cannot be hidden.
if (
privateRecordWire(readback.value.handle, owner, id) !==
- original.wire
+ expectedWire
)
return refuse('conflict');
+ const lineage =
+ previous ??
+ createLineage(
+ repository,
+ session,
+ original.identity,
+ original.record,
+ original.wire
+ );
+ lineages.set(original.identity, lineage);
const acknowledgement = Object.freeze(
{}
) as InboxProbeAcknowledgement;
@@ -242,8 +306,7 @@ export async function commitInboxProbe(
repository,
session,
identity: original.identity,
- record: original.record,
- wire: original.wire,
+ lineage,
current: () => !revoked && original.current(),
revoke: () => {
revoked = true;
@@ -273,7 +336,9 @@ export function inboxProbeAcknowledgementSnapshot(
const saved = acknowledgements.get(acknowledgement);
return saved?.current()
? {
- record: JSON.parse(JSON.stringify(saved.record)) as PrivateAccessProbe,
+ record: JSON.parse(
+ JSON.stringify(saved.lineage.record())
+ ) as PrivateAccessProbe,
fact: 'acknowledged_local_probe_ciphertext_only' as const
}
: undefined;
@@ -295,17 +360,171 @@ export async function verifyInboxProbeAcknowledgement(
const readback = await observePrivateRecord(
repository,
'private_sends',
- saved.record.id
+ saved.lineage.record().id
);
const valid =
saved.current() &&
readback.ok &&
- readback.value.wire === saved.wire &&
+ readback.value.wire === saved.lineage.wire() &&
privateRecordWire(
readback.value.handle,
- saved.record.owner,
- saved.record.id
- ) === saved.wire;
+ saved.lineage.record().owner,
+ saved.lineage.record().id
+ ) === saved.lineage.wire();
if (!valid) saved.revoke();
return valid;
}
+
+// Genuine lexical associations only. Detached row fields cannot mint a binding.
+export function inboxProbePublicationBinding(
+ repository: PrivateStorageRepository,
+ session: PrivateSession,
+ acknowledgement: InboxProbeAcknowledgement,
+ policy: RelayPolicy
+) {
+ const saved = acknowledgements.get(acknowledgement);
+ if (
+ !saved ||
+ saved.repository !== repository ||
+ saved.session !== session ||
+ !saved.current() ||
+ !inboxProbePolicyMatches(saved.identity, session, policy)
+ )
+ return undefined;
+ return {
+ identity: saved.identity,
+ record: JSON.parse(
+ JSON.stringify(saved.lineage.record())
+ ) as PrivateAccessProbe,
+ wire: saved.lineage.wire(),
+ current: () =>
+ saved.current() &&
+ inboxProbePolicyMatches(saved.identity, session, policy)
+ };
+}
+export type InboxProbeArchiveCommitResult = Readonly<{
+ status:
+ | 'saved'
+ | 'existing'
+ | 'reconciled'
+ | PrivateStorageFailure
+ | 'invalid'
+ | 'busy';
+ disposition: 'original_protected';
+}>;
+const appliedArchiveEvidence = new WeakMap<
+ InboxProbeArchiveAttemptResult,
+ Lineage
+>();
+// Only actual SDK attempt observations can advance memory-only provenance.
+// This bookkeeping can settle after owner loss, but cannot authorize traffic.
+export async function commitInboxProbeArchiveAttempt(
+ repository: PrivateStorageRepository,
+ result: InboxProbeArchiveAttemptResult
+): Promise<InboxProbeArchiveCommitResult> {
+ const refuse = (
+ status: InboxProbeArchiveCommitResult['status']
+ ): InboxProbeArchiveCommitResult => ({
+ status,
+ disposition: 'original_protected'
+ });
+ const effect = inboxProbeArchiveAttemptEvidence(result);
+ if (!effect || effect.repository !== repository) return refuse('invalid');
+ const saved = acknowledgements.get(effect.acknowledgement),
+ lineage = saved?.lineage;
+ if (
+ !saved ||
+ !lineage ||
+ lineage.repository !== repository ||
+ privateStorageOwner(repository) !== lineage.record().owner ||
+ !lineage.record().self
+ )
+ return refuse('invalid');
+ if (!lineage.begin()) return refuse('busy');
+ try {
+ if (typeof window === 'undefined' || !navigator.locks?.request)
+ return refuse('unavailable');
+ return await navigator.locks.request(
+ 'harvestcircle:owner:' + lineage.record().owner,
+ { mode: 'exclusive', ifAvailable: true },
+ async (lock) => {
+ if (!lock) return refuse('busy');
+ const owner = lineage.record().owner,
+ id = lineage.record().id,
+ observed = await observePrivateRecord(
+ repository,
+ 'private_sends',
+ id
+ );
+ if (!observed.ok) return refuse(observed.reason);
+ if (
+ observed.value.wire !== lineage.wire() ||
+ privateRecordWire(observed.value.handle, owner, id) !== lineage.wire()
+ )
+ return refuse('conflict');
+ if (appliedArchiveEvidence.get(result) === lineage)
+ return refuse('existing');
+ if (
+ effect.predecessorWire !== lineage.wire() ||
+ lineage.record().revision === Number.MAX_SAFE_INTEGER
+ )
+ return refuse('conflict');
+ const fact: unknown = JSON.parse(effect.receiptWire);
+ const candidate = decodePrivateRecord(
+ JSON.stringify({
+ ...lineage.record(),
+ revision: lineage.record().revision + 1,
+ receipts: [...lineage.record().receipts, fact]
+ }),
+ owner,
+ id
+ );
+ if (!candidate.ok) return refuse('invalid_record');
+ const nextWire = privateRecordWire(candidate.value, owner, id),
+ next = privateRecordSnapshot(candidate.value, owner, id);
+ if (!nextWire || !next || next.family !== 'private_access_probe')
+ return refuse('invalid_record');
+ const last = next.receipts[next.receipts.length - 1];
+ if (
+ last.role !== 'access_archive' ||
+ last.eventId !== lineage.record().self!.eventId ||
+ !lineage.record().binding.archiveTargets.includes(last.origin)
+ )
+ return refuse('invalid_record');
+ const committed = await commitPrivateRecord(
+ repository,
+ candidate.value,
+ observed.value.handle
+ );
+ if (!committed.ok && committed.reason !== 'unknown_completion')
+ return refuse(committed.reason);
+ const readback = await observePrivateRecord(
+ repository,
+ 'private_sends',
+ id
+ );
+ if (!readback.ok) return refuse('unknown_completion');
+ if (
+ readback.value.wire !== nextWire ||
+ privateRecordWire(readback.value.handle, owner, id) !== nextWire
+ )
+ return refuse('conflict');
+ // Only this actual append/native completion/fresh physical observation can
+ // refresh live ACKs. A decoded receipt or metadata label never can.
+ lineage.admit(next, nextWire);
+ appliedArchiveEvidence.set(result, lineage);
+ return refuse(
+ !committed.ok
+ ? 'reconciled'
+ : committed.value.state === 'existing'
+ ? 'existing'
+ : 'saved'
+ );
+ }
+ );
+ } catch {
+ return refuse('unknown_completion');
+ } finally {
+ lineage.finish();
+ }
+}
diff --git a/web/tests/e2e/harness/inbox-probe-publication.ts b/web/tests/e2e/harness/inbox-probe-publication.ts
@@ -0,0 +1,178 @@
+import { finalize } from 'rxjs';
+export { makeFixture as makeOrdinaryPublicationFixture } from './private-publisher.ts';
+import { makeProbeFixture } from './inbox-probe.ts';
+import { RelayPool } from 'applesauce-relay/pool';
+import {
+ getPrivatePool,
+ publishInboxProbeArchiveAttempt,
+ closePrivatePool,
+ type PrivatePool,
+ type InboxProbeArchiveAttemptResult
+} from '../../../src/lib/nostr/private-pool.ts';
+import {
+ captureInboxProbePublicationAction,
+ captureInboxProbePublication,
+ type InboxProbePublicationAction
+} from '../../../src/lib/nostr/private-publisher.ts';
+import {
+ inboxProbeAcknowledgementSnapshot,
+ commitInboxProbeArchiveAttempt
+} from '../../../src/lib/persistence/inbox-probes.ts';
+export * from './inbox-probe.ts';
+export * from '../../../src/lib/nostr/private-publisher.ts';
+export * from '../../../src/lib/nostr/private-pool.ts';
+export async function makePublicationFixture() {
+ const f = await makeProbeFixture();
+ let pool: PrivatePool | undefined,
+ last: InboxProbeArchiveAttemptResult | undefined;
+ let action: InboxProbePublicationAction | undefined;
+ const consumer = Object.freeze({});
+ function capture() {
+ const acknowledgement = f.acknowledgement();
+ if (!acknowledgement) return undefined;
+ const next = captureInboxProbePublicationAction(
+ f.repository,
+ f.session,
+ f.policy,
+ acknowledgement,
+ 'reviewed_inbox_probe_network'
+ );
+ action ??= next;
+ return next;
+ }
+ function permission(
+ origin = 'wss://inbox.example.org',
+ review: unknown = 'reviewed_inbox_probe_publication'
+ ) {
+ const acknowledgement = f.acknowledgement(),
+ original = capture();
+ return acknowledgement && original
+ ? captureInboxProbePublication(
+ f.repository,
+ f.session,
+ f.policy,
+ acknowledgement,
+ original,
+ origin,
+ review
+ )
+ : undefined;
+ }
+ function acquire() {
+ pool ??= getPrivatePool(
+ f.session,
+ f.policy,
+ f.acknowledgement()
+ ? inboxProbeAcknowledgementSnapshot(f.acknowledgement()!)!.record
+ .binding.archiveTargets
+ : ['wss://inbox.example.org'],
+ consumer,
+ 'delivery'
+ );
+ if (!pool) throw Error('actual source delivery scope unavailable');
+ return pool;
+ }
+ return {
+ ...f,
+ action: capture,
+ permission,
+ pool: acquire,
+ snapshot: () =>
+ f.acknowledgement() &&
+ inboxProbeAcknowledgementSnapshot(f.acknowledgement()!),
+ async publish(token = permission(), signal = new AbortController().signal) {
+ if (!token) return { status: 'stopped' as const };
+ last = await publishInboxProbeArchiveAttempt(acquire(), token, signal);
+ return last;
+ },
+ last: () => last,
+ append: (result = last) =>
+ result
+ ? commitInboxProbeArchiveAttempt(f.repository, result)
+ : Promise.resolve({ status: 'invalid' as const }),
+ installNetworkClock() {
+ const original = performance.now.bind(performance);
+ let now = original(),
+ observations = 0;
+ // Only the actual shared publication meter samples this controlled clock.
+ // Public discovery/head/lease lifetimes and Date.now remain real.
+ performance.now = () => {
+ if (/at clock(?:\d+)? \(/.test(new Error().stack ?? '')) {
+ observations++;
+ return now;
+ }
+ return original();
+ };
+ return {
+ set: (value: number) => {
+ now = value;
+ },
+ advance: (value: number) => {
+ now += value;
+ },
+ observations: () => observations,
+ restore: () => {
+ performance.now = original;
+ }
+ };
+ },
+ installAttemptTeardownFailure(onTeardown?: () => void) {
+ const original = Object.getOwnPropertyDescriptor(
+ RelayPool.prototype,
+ 'relay'
+ )?.value as RelayPool['relay'];
+ const restorations: (() => void)[] = [];
+ let failing = true,
+ faults = 0;
+ RelayPool.prototype.relay = function (
+ ...args: Parameters<RelayPool['relay']>
+ ) {
+ const relay = original.apply(this, args),
+ event = relay.event.bind(relay);
+ relay.event = (...eventArgs: Parameters<typeof relay.event>) =>
+ event(...eventArgs).pipe(
+ finalize(() => {
+ if (failing) {
+ onTeardown?.();
+ faults++;
+ throw Error(
+ 'controlled original SDK observable teardown failure'
+ );
+ }
+ })
+ );
+ restorations.push(() => {
+ relay.event = event;
+ });
+ return relay;
+ };
+ return {
+ faults: () => faults,
+ restore: () => {
+ failing = false;
+ RelayPool.prototype.relay = original;
+ for (const restoration of restorations) restoration();
+ }
+ };
+ },
+ installAcquisitionFailure() {
+ const original = Object.getOwnPropertyDescriptor(
+ RelayPool.prototype,
+ 'relay'
+ )?.value as RelayPool['relay'];
+ RelayPool.prototype.relay = () => {
+ throw Error('controlled actual SDK metadata acquisition failure');
+ };
+ return () => {
+ RelayPool.prototype.relay = original;
+ };
+ },
+ stop: () => {
+ if (pool) closePrivatePool(pool);
+ },
+ close() {
+ if (pool) closePrivatePool(pool);
+ f.close();
+ }
+ };
+}
diff --git a/web/tests/e2e/inbox-probe-publication.spec.ts b/web/tests/e2e/inbox-probe-publication.spec.ts
@@ -0,0 +1,1386 @@
+import { test, expect } from '@playwright/test';
+import { build } from 'vite';
+import { once } from 'node:events';
+import { fileURLToPath } from 'node:url';
+import { WebSocketServer, type WebSocket } from 'ws';
+import { createStaticHarness } from '../integration/harness/static.ts';
+import type * as Fixture from './harness/inbox-probe-publication.ts';
+declare global {
+ interface Window {
+ pb: typeof Fixture;
+ pbFixture: Awaited<ReturnType<typeof Fixture.makePublicationFixture>>;
+ pbPending?: Promise<unknown>;
+ pbAbort?: AbortController;
+ pbOtherPool?: Fixture.PrivatePool;
+ pbRestore?: () => void;
+ pbClock?: number;
+ pbNetworkClock?: ReturnType<Window['pbFixture']['installNetworkClock']>;
+ pbDelayClose?: boolean;
+ pbFailClose?: boolean;
+ pbInvalidateOnSocket?: boolean;
+ pbNestedCleanup?: number;
+ pbNestedFailure?: number;
+ pbHeldClose?: (() => void)[];
+ }
+}
+let server: Awaited<ReturnType<typeof createStaticHarness>>,
+ sockets: WebSocketServer,
+ endpoint: string,
+ bundle: string;
+let head = '',
+ response: 'accepted' | 'refused' | 'unknown' | 'wrong' | 'auth_required' =
+ 'accepted',
+ auth = false;
+const frames: { origin: string; frame: unknown[] }[] = [],
+ physical = new Set<WebSocket>();
+let peak = 0,
+ privatePeak = 0;
+const privatePhysical = new Set<WebSocket>();
+const privateConnections = new Map<string, number>();
+test.beforeAll(async () => {
+ server = await createStaticHarness();
+ sockets = new WebSocketServer({
+ host: '127.0.0.1',
+ port: 0,
+ maxPayload: 65536
+ });
+ await once(sockets, 'listening');
+ const address = sockets.address();
+ if (!address || typeof address === 'string')
+ throw Error('actual loopback fixture');
+ endpoint = 'ws://127.0.0.1:' + address.port;
+ sockets.on('connection', (socket, request) => {
+ physical.add(socket);
+ peak = Math.max(peak, physical.size);
+ socket.on('close', () => physical.delete(socket));
+ const origin = new URL(request.url!, 'http://127.0.0.1').searchParams.get(
+ 'origin'
+ )!;
+ if (origin !== 'wss://discovery.example.org') {
+ privatePhysical.add(socket);
+ privateConnections.set(origin, (privateConnections.get(origin) ?? 0) + 1);
+ privatePeak = Math.max(privatePeak, privatePhysical.size);
+ socket.on('close', () => privatePhysical.delete(socket));
+ }
+ if (auth && origin === 'wss://inbox.example.org')
+ socket.send(JSON.stringify(['AUTH', 'probe-challenge']));
+ socket.on('message', (bytes) => {
+ const raw = Buffer.isBuffer(bytes)
+ ? bytes
+ : Array.isArray(bytes)
+ ? Buffer.concat(bytes)
+ : Buffer.from(bytes);
+ const frame = JSON.parse(raw.toString()) as unknown[];
+ frames.push({ origin, frame });
+ if (frame[0] === 'REQ') {
+ const filter = frame[2] as { kinds?: number[] };
+ if (filter.kinds?.includes(10050) && head)
+ socket.send(JSON.stringify(['EVENT', frame[1], JSON.parse(head)]));
+ socket.send(JSON.stringify(['EOSE', frame[1]]));
+ } else if (frame[0] === 'AUTH') {
+ socket.send(
+ JSON.stringify(['OK', (frame[1] as { id: string }).id, true, ''])
+ );
+ } else if (frame[0] === 'EVENT' && response !== 'unknown') {
+ socket.send(
+ JSON.stringify([
+ 'OK',
+ response === 'wrong'
+ ? 'f'.repeat(64)
+ : (frame[1] as { id: string }).id,
+ response !== 'refused' && response !== 'auth_required',
+ response === 'auth_required'
+ ? 'auth-required: source fixture'
+ : response === 'refused'
+ ? 'blocked: source fixture'
+ : ''
+ ])
+ );
+ }
+ });
+ });
+ const result = await build({
+ configFile: false,
+ logLevel: 'silent',
+ build: {
+ write: false,
+ minify: false,
+ lib: {
+ entry: fileURLToPath(
+ new URL('./harness/inbox-probe-publication.ts', import.meta.url)
+ ),
+ name: 'pb',
+ formats: ['iife']
+ }
+ }
+ });
+ const output = Array.isArray(result) ? result[0] : result;
+ if (!('output' in output)) throw Error('compiled fixture');
+ const chunks = output.output.filter((x) => x.type === 'chunk');
+ expect(chunks).toHaveLength(1);
+ bundle = chunks[0].code;
+});
+test.afterAll(async () => {
+ for (const socket of sockets.clients) socket.terminate();
+ await new Promise<void>((resolve) => sockets.close(() => resolve()));
+ await server.close();
+});
+test.beforeEach(async ({ page }, testInfo) => {
+ await expect.poll(() => physical.size).toBe(0);
+ head = '';
+ response = 'accepted';
+ auth = false;
+ peak = 0;
+ privatePeak = 0;
+ privateConnections.clear();
+ frames.length = 0;
+ await page.addInitScript(
+ ({ endpoint }) => {
+ const Native = window.WebSocket;
+ window.WebSocket = class extends Native {
+ constructor(url: string | URL, protocols?: string | string[]) {
+ const origin = new URL(String(url)).origin;
+ if (
+ ![
+ 'wss://discovery.example.org',
+ 'wss://inbox.example.org',
+ 'wss://peer.example.org',
+ 'wss://archive.example.org'
+ ].includes(origin)
+ )
+ throw Error('unapproved fixture origin');
+ super(endpoint + '/?origin=' + encodeURIComponent(origin), protocols);
+ if (
+ window.pbInvalidateOnSocket &&
+ origin === 'wss://inbox.example.org'
+ )
+ window.pb.closeInboxAccessController(
+ window.pbFixture.controller()!
+ );
+ }
+ override close(code?: number, reason?: string) {
+ if (window.pbFailClose)
+ throw Error('actual controlled disposal failure');
+ if (window.pbDelayClose)
+ (window.pbHeldClose ??= []).push(() => super.close(code, reason));
+ else super.close(code, reason);
+ }
+ };
+ },
+ { endpoint }
+ );
+ await page.goto(server.url + '/search');
+ await page.addScriptTag({ content: bundle });
+ head = await page.evaluate(async (multi) => {
+ window.pbFixture = await window.pb.makePublicationFixture();
+ return window.pbFixture.preferenceWire(
+ multi
+ ? [
+ 'wss://inbox.example.org',
+ 'wss://peer.example.org',
+ 'wss://archive.example.org'
+ ]
+ : ['wss://inbox.example.org']
+ );
+ }, testInfo.title.includes('three-origin'));
+ await page.evaluate(async () => {
+ const f = window.pbFixture;
+ await f.capture();
+ if (
+ (await f.reserve()).status !== 'reserved' ||
+ (await f.prepare()) !== 'wrapped' ||
+ (await f.commitOriginal()).status !== 'prepared'
+ )
+ throw Error('genuine cold native original setup');
+ });
+});
+test.afterEach(async ({ page }) => {
+ if (!page.isClosed())
+ await page.evaluate(() => {
+ window.pbRestore?.();
+ window.pbFailClose = false;
+ window.pbDelayClose = false;
+ for (const release of window.pbHeldClose ?? []) release();
+ window.pbFixture.close();
+ });
+});
+function privateEvents() {
+ return frames.filter(
+ (x) => x.origin !== 'wss://discovery.example.org' && x.frame[0] === 'EVENT'
+ );
+}
+function noPrivateReads() {
+ expect(
+ frames.filter(
+ (x) => x.origin !== 'wss://discovery.example.org' && x.frame[0] === 'REQ'
+ )
+ ).toHaveLength(0);
+}
+
+test('cold original artifact is published exactly; genuine receipts and new ACKs keep one action and three attempts', async ({
+ page
+}) => {
+ const before = await page.evaluate(() => window.pbFixture.stored());
+ expect(privateEvents()).toHaveLength(0);
+ noPrivateReads();
+ const observed = await page.evaluate(async () => {
+ const f = window.pbFixture,
+ api = window.pb,
+ action = f.action()!;
+ const first = await f.publish();
+ const clone = await f.append({ ...first });
+ const saved = await f.append(first),
+ duplicate = await f.append(first);
+ const afterFirst = f.snapshot()!.record;
+ const recommit = await f.commitOriginal(),
+ sameAction = f.action() === action;
+ const second = await f.publish();
+ await f.append(second);
+ const third = await f.publish();
+ await f.append(third);
+ const fourth = await f.publish();
+ return {
+ first,
+ clone,
+ saved,
+ duplicate,
+ afterFirst,
+ recommit: recommit.status,
+ sameAction,
+ second,
+ third,
+ fourth,
+ row: f.snapshot()!.record,
+ evidence: !!api.inboxProbeArchiveAttemptEvidence(first),
+ ordinaryEvidence: !!api.privateGiftWrapAttemptEvidence(
+ first as unknown as Parameters<
+ typeof api.privateGiftWrapAttemptEvidence
+ >[0]
+ ),
+ ready: api.inboxAccessControllerSnapshot(f.controller()!)?.readiness
+ };
+ });
+ expect(observed.first).toMatchObject({
+ status: 'accepted',
+ role: 'access_archive',
+ origin: 'wss://inbox.example.org',
+ attempt: 1
+ });
+ expect(observed.clone.status).toBe('invalid');
+ expect(observed.saved.status).toBe('saved');
+ expect(observed.duplicate.status).toBe('existing');
+ expect(observed.afterFirst.revision).toBe(2);
+ expect(observed.afterFirst.receipts).toHaveLength(1);
+ expect(observed.recommit).toBe('existing');
+ expect(observed.sameAction).toBe(true);
+ expect(observed.second).toMatchObject({
+ status: 'accepted',
+ actionId: observed.first.actionId,
+ attempt: 2
+ });
+ expect(observed.third).toMatchObject({
+ status: 'accepted',
+ actionId: observed.first.actionId,
+ attempt: 3
+ });
+ expect(observed.fourth).toEqual({ status: 'stopped' });
+ expect(observed.row.revision).toBe(4);
+ expect(observed.row.receipts).toHaveLength(3);
+ expect(observed.evidence).toBe(true);
+ expect(observed.ordinaryEvidence).toBe(false);
+ expect(observed.ready).toBe('unavailable');
+ expect(privateEvents()).toHaveLength(3);
+ expect(privateEvents().map((x) => JSON.stringify(x.frame[1]))).toEqual(
+ Array(3).fill(
+ (JSON.parse(before[0].wire) as { self: { wire: string } }).self.wire
+ )
+ );
+ noPrivateReads();
+});
+
+test('forged/cross-family permission and genuine foreign repository/session/policy/head cannot send', async ({
+ page
+}) => {
+ const observations = await page.evaluate(async () => {
+ const f = window.pbFixture,
+ api = window.pb,
+ ack = f.acknowledgement()!,
+ action = f.action()!,
+ permission = f.permission()!;
+ const copiedPolicy = f.copiedPolicy(),
+ otherSession = await f.foreignSession();
+ const invalidActions = [
+ api.captureInboxProbePublicationAction(
+ f.foreignRepository(),
+ f.session,
+ f.policy,
+ ack,
+ 'reviewed_inbox_probe_network'
+ ),
+ api.captureInboxProbePublicationAction(
+ f.repository,
+ otherSession,
+ f.policy,
+ ack,
+ 'reviewed_inbox_probe_network'
+ ),
+ api.captureInboxProbePublicationAction(
+ f.repository,
+ f.session,
+ copiedPolicy,
+ ack,
+ 'reviewed_inbox_probe_network'
+ ),
+ api.captureInboxProbePublicationAction(
+ f.repository,
+ f.session,
+ f.policy,
+ { ...f.snapshot() } as typeof ack,
+ 'reviewed_inbox_probe_network'
+ )
+ ].map(Boolean);
+ const invalidPermissions = [
+ api.captureInboxProbePublication(
+ f.repository,
+ f.session,
+ copiedPolicy,
+ ack,
+ action,
+ 'wss://inbox.example.org',
+ 'reviewed_inbox_probe_publication'
+ ),
+ f.permission('wss://peer.example.org'),
+ f.permission('wss://inbox.example.org', {})
+ ].map(Boolean);
+ const cross = await api.publishPrivateGiftWrapAttempt(
+ f.pool(),
+ permission as unknown as Parameters<
+ typeof api.publishPrivateGiftWrapAttempt
+ >[1],
+ new AbortController().signal
+ );
+ const fake = await api.publishInboxProbeArchiveAttempt(
+ f.pool(),
+ {} as typeof permission,
+ new AbortController().signal
+ );
+ f.churnHead();
+ return {
+ invalidActions,
+ invalidPermissions,
+ cross,
+ fake,
+ stale: await f.publish(permission)
+ };
+ });
+ expect(observations.invalidActions).toEqual([false, false, false, false]);
+ expect(observations.invalidPermissions).toEqual([false, false, false]);
+ expect(observations.cross).toEqual({ status: 'stopped' });
+ expect(observations.fake).toEqual({ status: 'stopped' });
+ expect(observations.stale).toEqual({ status: 'stopped' });
+ expect(privateEvents()).toHaveLength(0);
+ noPrivateReads();
+});
+for (const mutation of [
+ 'alias',
+ 'forged_fact',
+ 'corrupt_tail',
+ 'removed'
+] as const) {
+ test(`fresh native ${mutation} refuses before EVENT and cannot advance archive provenance`, async ({
+ page
+ }) => {
+ const result = await page.evaluate(async (mutation) => {
+ const f = window.pbFixture,
+ api = window.pb,
+ token = f.permission()!;
+ const rows = await f.stored();
+ if (mutation === 'removed') await f.removeOriginal();
+ else if (mutation === 'corrupt_tail')
+ await f.inject([
+ { owner: f.owner, id: crypto.randomUUID(), wire: 'bad' }
+ ]);
+ else {
+ if (mutation === 'alias') rows[0].wire += ' ';
+ else {
+ const row = JSON.parse(rows[0].wire) as {
+ revision: number;
+ self: { eventId: string };
+ receipts: unknown[];
+ };
+ row.revision++;
+ row.receipts.push({
+ actionId: crypto.randomUUID(),
+ role: 'access_archive',
+ origin: 'wss://inbox.example.org',
+ eventId: row.self.eventId,
+ attempt: 1,
+ status: 'accepted',
+ observedAtMilliseconds: 1,
+ readbackWire: null
+ });
+ rows[0].wire = JSON.stringify(row);
+ }
+ await f.inject(rows);
+ }
+ const before = await f.stored(),
+ result = await f.publish(token);
+ return {
+ before,
+ after: await f.stored(),
+ result,
+ evidence: !!api.inboxProbeArchiveAttemptEvidence(result),
+ recommit: await f.commitOriginal()
+ };
+ }, mutation);
+ expect(result.result).toEqual({ status: 'stopped' });
+ expect(result.evidence).toBe(false);
+ expect(result.after).toEqual(result.before);
+ expect(result.recommit.status).not.toBe('existing');
+ expect(privateEvents()).toHaveLength(0);
+ noPrivateReads();
+ });
+}
+
+test('handwritten valid receipt after actual EVENT cannot be adopted by append or refreshed ACK', async ({
+ page
+}) => {
+ const result = await page.evaluate(async () => {
+ const f = window.pbFixture,
+ actual = await f.publish(),
+ rows = await f.stored();
+ const row = JSON.parse(rows[0].wire) as {
+ revision: number;
+ self: { eventId: string };
+ receipts: unknown[];
+ };
+ row.revision++;
+ row.receipts.push({
+ actionId: crypto.randomUUID(),
+ origin: 'wss://inbox.example.org',
+ role: 'access_archive',
+ eventId: row.self.eventId,
+ attempt: 1,
+ status: 'accepted',
+ observedAtMilliseconds: 1,
+ readbackWire: null
+ });
+ rows[0].wire = JSON.stringify(row);
+ await f.inject(rows);
+ return {
+ append: await f.append(actual),
+ recommit: await f.commitOriginal(),
+ before: rows,
+ after: await f.stored(),
+ snapshot: f.snapshot()!.record
+ };
+ });
+ expect(result.append.status).toBe('conflict');
+ expect(result.recommit.status).toBe('conflict');
+ expect(result.after).toEqual(result.before);
+ expect(result.snapshot.receipts).toHaveLength(0);
+ expect(privateEvents()).toHaveLength(1);
+ noPrivateReads();
+});
+
+test('actual named relay refusal remains a genuine bounded archive observation', async ({
+ page
+}) => {
+ response = 'refused';
+ const result = await page.evaluate(async () => {
+ const f = window.pbFixture,
+ actual = await f.publish();
+ return {
+ actual,
+ append: await f.append(actual),
+ row: f.snapshot()!.record
+ };
+ });
+ expect(result.actual).toMatchObject({ status: 'refused', attempt: 1 });
+ expect(result.append.status).toBe('saved');
+ expect(result.row.receipts[0].status).toBe('refused');
+ expect(privateEvents()).toHaveLength(1);
+ noPrivateReads();
+});
+for (const disposition of ['stop', 'wrong_ack', 'clock_expired'] as const) {
+ test(`actual EVENT ${disposition} is truthful and cannot become acceptance`, async ({
+ page
+ }) => {
+ response = disposition === 'wrong_ack' ? 'wrong' : 'unknown';
+ await page.evaluate((disposition) => {
+ const f = window.pbFixture;
+ if (disposition === 'clock_expired') {
+ window.pbNetworkClock = f.installNetworkClock();
+ window.pbRestore = () => window.pbNetworkClock!.restore();
+ }
+ window.pbAbort = new AbortController();
+ window.pbPending = f.publish(f.permission(), window.pbAbort.signal);
+ }, disposition);
+ await expect.poll(() => privateEvents().length).toBe(1);
+ if (disposition === 'clock_expired')
+ await page.evaluate(() => {
+ window.pbNetworkClock!.advance(46000);
+ });
+ else await page.evaluate(() => window.pbAbort!.abort());
+ const result = await page.evaluate(async () => {
+ const actual = (await window.pbPending) as NonNullable<
+ ReturnType<typeof window.pbFixture.last>
+ >;
+ return {
+ actual,
+ append: await window.pbFixture.append(actual),
+ row: window.pbFixture.snapshot()!.record
+ };
+ });
+ expect(result.actual.status).toBe(
+ disposition === 'clock_expired' ? 'timed_out' : 'stopped'
+ );
+ expect(result.append.status).toBe('saved');
+ expect(result.row.receipts[0].status).toBe(result.actual.status);
+ noPrivateReads();
+ });
+}
+
+test('pending fresh owner approval and SDK acquisition failure consume no attempt; original starts at one', async ({
+ page
+}) => {
+ const stopped = await page.evaluate(async () => {
+ const f = window.pbFixture;
+ f.pool();
+ const restore = f.installAcquisitionFailure();
+ try {
+ return await f.publish();
+ } finally {
+ restore();
+ }
+ });
+ expect(stopped).toEqual({ status: 'stopped' });
+ expect(privateEvents()).toHaveLength(0);
+ await page.evaluate(() => {
+ const f = window.pbFixture;
+ window.pbNetworkClock = f.installNetworkClock();
+ window.pbRestore = () => window.pbNetworkClock!.restore();
+ f.mode('hold_key');
+ window.pbPending = f.publish();
+ });
+ await expect
+ .poll(() => page.evaluate(() => window.pbFixture.waiting()))
+ .toBe('key');
+ expect(privateEvents()).toHaveLength(0);
+ await page.evaluate(() => {
+ window.pbNetworkClock!.advance(90000);
+ window.pbFixture.mode('normal');
+ window.pbFixture.settle();
+ });
+ const first = await page.evaluate(async () => window.pbPending);
+ expect(first).toMatchObject({ status: 'accepted', attempt: 1 });
+ const next = await page.evaluate(async () => {
+ await window.pbFixture.append();
+ return window.pbFixture.publish();
+ });
+ expect(next).toMatchObject({ status: 'accepted', attempt: 2 });
+ expect(privateEvents()).toHaveLength(2);
+ noPrivateReads();
+});
+
+test('known AUTH with pending original signer consumes no probe attempt, then only original artifact sends', async ({
+ page
+}) => {
+ auth = true;
+ await page.evaluate(() => {
+ const f = window.pbFixture;
+ window.pbNetworkClock = f.installNetworkClock();
+ window.pbRestore = () => window.pbNetworkClock!.restore();
+ window.pbPending = window.pb.authenticateInboxAccess(
+ f.controller()!,
+ 'wss://inbox.example.org',
+ 'reviewed_inbox_connection_auth'
+ );
+ });
+ await page.evaluate(async () => window.pbPending);
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () =>
+ window.pb.inboxAccessControllerSnapshot(
+ window.pbFixture.controller()!
+ )?.auth[0]?.state
+ )
+ )
+ .toBe('challenge');
+ await page.evaluate(() => {
+ const f = window.pbFixture;
+ f.mode('hold_sign');
+ window.pbPending = window.pb.respondInboxAccessAuthentication(
+ f.controller()!,
+ 'wss://inbox.example.org',
+ 'reviewed_inbox_auth_response'
+ );
+ });
+ await expect
+ .poll(() => page.evaluate(() => window.pbFixture.waiting()))
+ .toBe('sign');
+ const stopped = await page.evaluate(() => window.pbFixture.publish());
+ expect(stopped).toEqual({ status: 'stopped' });
+ expect(privateEvents()).toHaveLength(0);
+ expect(
+ await page.evaluate(() => window.pbFixture.snapshot()!.record.receipts)
+ ).toHaveLength(0);
+ await page.evaluate(() => {
+ window.pbNetworkClock!.advance(90000);
+ window.pbFixture.mode('normal');
+ window.pbFixture.settle();
+ });
+ expect(await page.evaluate(async () => window.pbPending)).toBe('accepted');
+ const original = await page.evaluate(() => window.pbFixture.publish());
+ expect(original).toMatchObject({ status: 'accepted', attempt: 1 });
+ expect(privateEvents()).toHaveLength(1);
+ expect(frames.filter((x) => x.frame[0] === 'AUTH')).toHaveLength(1);
+ noPrivateReads();
+});
+
+for (const mode of ['aborted', 'uncertain'] as const) {
+ test(`actual native archive ${mode} commit retains original evidence for exact replay`, async ({
+ page
+ }) => {
+ const result = await page.evaluate(async (mode) => {
+ const f = window.pbFixture,
+ actual = await f.publish(),
+ before = await f.stored();
+ const uncertain =
+ mode === 'uncertain' ? f.installUncertainCommit() : undefined;
+ const restore =
+ mode === 'aborted'
+ ? f.installNativeAbort()
+ : () => uncertain!.restore();
+ let first: Awaited<ReturnType<typeof f.append>>;
+ try {
+ first = await f.append(actual);
+ } finally {
+ restore();
+ }
+ const afterFirst = await f.stored(),
+ second = await f.append(actual),
+ third = await f.append(actual);
+ return {
+ before,
+ afterFirst,
+ first,
+ second,
+ third,
+ row: f.snapshot()!.record,
+ native: uncertain?.counts()
+ };
+ }, mode);
+ expect(result.first.status).toBe(
+ mode === 'aborted' ? 'aborted' : 'reconciled'
+ );
+ if (mode === 'aborted') expect(result.afterFirst).toEqual(result.before);
+ expect(result.second.status).toBe(
+ mode === 'aborted' ? 'saved' : 'existing'
+ );
+ expect(result.third.status).toBe('existing');
+ expect(result.row.revision).toBe(2);
+ expect(result.row.receipts).toHaveLength(1);
+ expect(privateEvents()).toHaveLength(1);
+ noPrivateReads();
+ if (mode === 'uncertain')
+ expect(result.native).toMatchObject({
+ putSuccess: 1,
+ nativeComplete: 1,
+ nativeAbort: 0,
+ abortRefused: 1
+ });
+ });
+}
+
+test('original attempt metadata settles after owner loss, without restoring effect or readiness', async ({
+ page
+}) => {
+ const result = await page.evaluate(async () => {
+ const f = window.pbFixture,
+ actual = await f.publish();
+ f.closeSession();
+ const appended = await f.append(actual);
+ return {
+ actual,
+ appended,
+ rows: await f.stored(),
+ ack: f.snapshot(),
+ next: await f.publish()
+ };
+ });
+ expect(result.appended.status).toBe('saved');
+ expect(
+ (JSON.parse(result.rows[0].wire) as { receipts: unknown[] }).receipts
+ ).toHaveLength(1);
+ expect(result.ack).toBeUndefined();
+ expect(result.next).toEqual({ status: 'stopped' });
+ expect(privateEvents()).toHaveLength(1);
+ noPrivateReads();
+});
+
+test('held physical close retains original cleanup and prevents replacement traffic', async ({
+ page
+}) => {
+ response = 'unknown';
+ await page.evaluate(() => {
+ window.pbDelayClose = true;
+ window.pbAbort = new AbortController();
+ window.pbPending = window.pbFixture.publish(
+ window.pbFixture.permission(),
+ window.pbAbort.signal
+ );
+ });
+ await expect.poll(() => privateEvents().length).toBe(1);
+ await page.evaluate(() => {
+ window.pbAbort!.abort();
+ window.pbFixture.stop();
+ });
+ expect(await page.evaluate(() => window.pbFixture.publish())).toEqual({
+ status: 'stopped'
+ });
+ expect(privateEvents()).toHaveLength(1);
+ expect(peak).toBeLessThanOrEqual(3);
+ await page.evaluate(() => {
+ window.pbDelayClose = false;
+ for (const release of window.pbHeldClose ?? []) release();
+ window.pbFixture.stop();
+ });
+ await expect.poll(() => physical.size).toBe(0);
+ noPrivateReads();
+});
+
+test('reentrant genuine UUID capture reserves one original action before callbacks', async ({
+ page
+}) => {
+ const result = await page.evaluate(async () => {
+ const f = window.pbFixture,
+ original = crypto.randomUUID.bind(crypto);
+ let nested: ReturnType<typeof f.action>,
+ entered = false;
+ crypto.randomUUID = () => {
+ if (!entered) {
+ entered = true;
+ nested = f.action();
+ }
+ return original();
+ };
+ let first: ReturnType<typeof f.action>;
+ try {
+ first = f.action();
+ } finally {
+ crypto.randomUUID = original;
+ }
+ const outcomes = [];
+ for (let n = 0; n < 4; n++) {
+ const actual = await f.publish();
+ outcomes.push(actual);
+ if (n < 3) await f.append(actual);
+ }
+ return {
+ first: !!first,
+ nested: !!nested,
+ same: first === f.action(),
+ outcomes
+ };
+ });
+ expect(result.first).toBe(true);
+ expect(result.nested).toBe(false);
+ expect(result.same).toBe(true);
+ expect(result.outcomes.slice(0, 3).map((x) => x.attempt)).toEqual([1, 2, 3]);
+ expect(result.outcomes[3]).toEqual({ status: 'stopped' });
+ expect(privateEvents()).toHaveLength(3);
+ noPrivateReads();
+});
+
+for (const boundary of ['wrong_key', 'head_during_key', 'lock_busy'] as const) {
+ test(`actual ${boundary} refuses with no EVENT or attempted archive receipt`, async ({
+ page
+ }) => {
+ if (boundary === 'lock_busy') {
+ await page.evaluate(() => {
+ window.pbPending = navigator.locks.request(
+ 'harvestcircle:owner:' + window.pbFixture.owner,
+ async () => {
+ window.pbClock = 1;
+ await new Promise<void>((resolve) => {
+ window.pbRestore = resolve;
+ });
+ }
+ );
+ });
+ await expect.poll(() => page.evaluate(() => window.pbClock)).toBe(1);
+ } else {
+ await page.evaluate((boundary) => {
+ window.pbFixture.mode(
+ boundary === 'wrong_key' ? 'wrong_key' : 'hold_key'
+ );
+ }, boundary);
+ }
+ await page.evaluate(() => {
+ window.pbPending = window.pbFixture.publish();
+ });
+ if (boundary === 'head_during_key') {
+ await expect
+ .poll(() => page.evaluate(() => window.pbFixture.waiting()))
+ .toBe('key');
+ await page.evaluate(() => {
+ window.pbFixture.churnHead();
+ window.pbFixture.mode('normal');
+ window.pbFixture.settle();
+ });
+ }
+ const result = await page.evaluate(async () => {
+ const actual = (await window.pbPending) as NonNullable<
+ ReturnType<typeof window.pbFixture.last>
+ >;
+ return {
+ actual,
+ evidence: !!window.pb.inboxProbeArchiveAttemptEvidence(actual),
+ rows: await window.pbFixture.stored()
+ };
+ });
+ expect(result.actual.status).toBe('stopped');
+ expect(result.evidence).toBe(false);
+ expect(
+ (JSON.parse(result.rows[0].wire) as { receipts: unknown[] }).receipts
+ ).toHaveLength(0);
+ expect(privateEvents()).toHaveLength(0);
+ noPrivateReads();
+ if (boundary === 'lock_busy')
+ await page.evaluate(() => window.pbRestore?.());
+ });
+}
+for (const clock of ['backwards', 'nonfinite'] as const) {
+ test(`actual ${clock} network clock conservatively fences original action`, async ({
+ page
+ }) => {
+ response = 'unknown';
+ await page.evaluate(() => {
+ window.pbNetworkClock = window.pbFixture.installNetworkClock();
+ window.pbRestore = () => window.pbNetworkClock!.restore();
+ window.pbPending = window.pbFixture.publish();
+ });
+ await expect.poll(() => privateEvents().length).toBe(1);
+ await page.evaluate((clock) => {
+ window.pbNetworkClock!.set(clock === 'backwards' ? 0 : NaN);
+ }, clock);
+ const result = await page.evaluate(async () => {
+ const actual = (await window.pbPending) as NonNullable<
+ ReturnType<typeof window.pbFixture.last>
+ >;
+ const appended = await window.pbFixture.append(actual);
+ return {
+ actual,
+ appended,
+ action: !!window.pbFixture.action(),
+ next: await window.pbFixture.publish()
+ };
+ });
+ expect(result.actual.status).toBe('timed_out');
+ expect(result.appended.status).toBe('saved');
+ expect(result.action).toBe(false);
+ expect(result.next).toEqual({ status: 'stopped' });
+ expect(privateEvents()).toHaveLength(1);
+ noPrivateReads();
+ });
+}
+
+test('actual late acknowledgement after head loss cannot become accepted', async ({
+ page
+}) => {
+ response = 'unknown';
+ await page.evaluate(() => {
+ window.pbPending = window.pbFixture.publish();
+ });
+ await expect.poll(() => privateEvents().length).toBe(1);
+ await page.evaluate(() => window.pbFixture.churnHead());
+ const result = await page.evaluate(async () => window.pbPending);
+ expect(result).toMatchObject({ status: 'stopped', attempt: 1 });
+ for (const socket of sockets.clients)
+ if (socket.readyState === 1)
+ socket.send(
+ JSON.stringify([
+ 'OK',
+ (privateEvents()[0].frame[1] as { id: string }).id,
+ true,
+ 'late'
+ ])
+ );
+ const settlement = await page.evaluate(async () => {
+ const f = window.pbFixture;
+ return {
+ append: await f.append(),
+ row: (await f.stored())[0].wire,
+ next: await f.publish()
+ };
+ });
+ expect(settlement.append.status).toBe('saved');
+ expect(
+ (JSON.parse(settlement.row) as { receipts: { status: string }[] })
+ .receipts[0].status
+ ).toBe('stopped');
+ expect(settlement.next).toEqual({ status: 'stopped' });
+ noPrivateReads();
+});
+
+test('later physical disposal failure preserves prior stopped attempt and original Stop retries cleanup', async ({
+ page
+}) => {
+ response = 'unknown';
+ await page.evaluate(() => {
+ window.pbAbort = new AbortController();
+ window.pbPending = window.pbFixture.publish(
+ window.pbFixture.permission(),
+ window.pbAbort.signal
+ );
+ });
+ await expect.poll(() => privateEvents().length).toBe(1);
+ const result = await page.evaluate(async () => {
+ window.pbFailClose = true;
+ window.pbAbort!.abort();
+ let failed = false;
+ try {
+ window.pbFixture.stop();
+ } catch {
+ failed = true;
+ }
+ const actual = await window.pbPending;
+ const cleanup = window.pb.privatePoolCleanupRequired(
+ window.pbFixture.pool()
+ );
+ window.pbFailClose = false;
+ window.pbFixture.stop();
+ return { actual, failed, cleanup, next: await window.pbFixture.publish() };
+ });
+ expect(result.actual).toMatchObject({ status: 'stopped', attempt: 1 });
+ expect(result.failed).toBe(true);
+ expect(result.cleanup).toBe(true);
+ expect(result.next).toEqual({ status: 'stopped' });
+ await expect.poll(() => physical.size).toBe(0);
+ expect(privateEvents()).toHaveLength(1);
+ noPrivateReads();
+});
+
+test('archive append remains eligible in a full hundred-row namespace; concurrent replay adds one fact', async ({
+ page
+}) => {
+ const result = await page.evaluate(async () => {
+ const f = window.pbFixture,
+ actual = await f.publish(),
+ rows = await f.stored();
+ const template = JSON.parse(rows[0].wire) as { id: string };
+ const fillers = Array.from({ length: 99 }, () => {
+ const id = crypto.randomUUID();
+ return { owner: f.owner, id, wire: JSON.stringify({ ...template, id }) };
+ });
+ await f.inject(fillers);
+ const pair = await Promise.all([f.append(actual), f.append(actual)]);
+ const repeat = await f.append(actual);
+ return {
+ pair,
+ repeat,
+ row: f.snapshot()!.record,
+ count: (await f.stored()).length
+ };
+ });
+ expect(result.pair.map((x) => x.status).sort()).toEqual(['busy', 'saved']);
+ expect(result.repeat.status).toBe('existing');
+ expect(result.row.revision).toBe(2);
+ expect(result.row.receipts).toHaveLength(1);
+ expect(result.count).toBe(100);
+ expect(privateEvents()).toHaveLength(1);
+ noPrivateReads();
+});
+
+test('actual eight-MiB joint namespace refuses archive growth without losing original ciphertext or evidence', async ({
+ page
+}) => {
+ const result = await page.evaluate(async () => {
+ const f = window.pbFixture,
+ actual = await f.publish(),
+ original = await f.stored();
+ const template = JSON.parse(original[0].wire) as {
+ id: string;
+ self: { eventId: string };
+ receipts: unknown[];
+ };
+ const id = crypto.randomUUID(),
+ fact = {
+ actionId: crypto.randomUUID(),
+ origin: 'wss://inbox.example.org',
+ role: 'access_archive',
+ eventId: template.self.eventId,
+ attempt: 1,
+ status: 'accepted',
+ observedAtMilliseconds: 1,
+ readbackWire: null
+ };
+ const row = (count: number) => ({
+ owner: f.owner,
+ id,
+ wire: JSON.stringify({
+ ...template,
+ id,
+ receipts: Array.from({ length: count }, () => fact)
+ })
+ });
+ const bytes = (rows: typeof original) =>
+ rows.reduce(
+ (sum, x) => sum + new TextEncoder().encode(JSON.stringify(x)).length,
+ 0
+ );
+ const empty = bytes([...original, row(0)]),
+ step = bytes([row(1)]) - bytes([row(0)]),
+ limit = 8 * 1024 * 1024;
+ const count = Math.floor((limit - empty + 1) / (step + 1));
+ await f.inject([row(count)]);
+ const before = await f.stored(),
+ append = await f.append(actual),
+ after = await f.stored();
+ return {
+ append,
+ exact: JSON.stringify(before) === JSON.stringify(after),
+ headroom: limit - bytes(before),
+ count: after.length,
+ row: f.snapshot()!.record,
+ evidence: !!window.pb.inboxProbeArchiveAttemptEvidence(actual)
+ };
+ });
+ expect(result.headroom).toBeGreaterThanOrEqual(0);
+ expect(result.headroom).toBeLessThan(350);
+ expect(result.append.status).toBe('capacity');
+ expect(result.exact).toBe(true);
+ expect(result.count).toBe(2);
+ expect(result.row.revision).toBe(1);
+ expect(result.row.receipts).toHaveLength(0);
+ expect(result.evidence).toBe(true);
+ expect(privateEvents()).toHaveLength(1);
+ noPrivateReads();
+});
+
+test('actual auth-required refusal without C7 setup prevents any subsequent probe key prompt or charge', async ({
+ page
+}) => {
+ response = 'auth_required';
+ auth = true;
+ const first = await page.evaluate(() => window.pbFixture.publish());
+ expect(first).toMatchObject({ status: 'refused', attempt: 1 });
+ expect(privateEvents()).toHaveLength(1);
+ const refused = await page.evaluate(async () => {
+ const f = window.pbFixture;
+ await f.append();
+ const before = f.counts();
+ f.mode('hold_key');
+ const second = await f.publish();
+ return { second, before, after: f.counts(), waiting: f.waiting() };
+ });
+ expect(refused.second).toEqual({ status: 'stopped' });
+ expect(refused.after).toEqual(refused.before);
+ expect(refused.waiting).toBe('');
+ expect(privateEvents()).toHaveLength(1);
+ response = 'accepted';
+ await page.evaluate(() => {
+ window.pbFixture.mode('normal');
+ return window.pb.authenticateInboxAccess(
+ window.pbFixture.controller()!,
+ 'wss://inbox.example.org',
+ 'reviewed_inbox_connection_auth'
+ );
+ });
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () =>
+ window.pb.inboxAccessControllerSnapshot(
+ window.pbFixture.controller()!
+ )?.auth[0]?.state
+ )
+ )
+ .toBe('challenge');
+ expect(
+ await page.evaluate(() =>
+ window.pb.respondInboxAccessAuthentication(
+ window.pbFixture.controller()!,
+ 'wss://inbox.example.org',
+ 'reviewed_inbox_auth_response'
+ )
+ )
+ ).toBe('accepted');
+ const next = await page.evaluate(() => window.pbFixture.publish());
+ expect(next).toMatchObject({
+ status: 'accepted',
+ attempt: 2,
+ actionId: first.actionId
+ });
+ expect(privateEvents()).toHaveLength(2);
+ expect(frames.filter((x) => x.frame[0] === 'AUTH')).toHaveLength(1);
+ noPrivateReads();
+});
+
+test('three-origin original action has three admissions per target, nine genuine facts and bounded held physical sockets', async ({
+ page
+}) => {
+ const result = await page.evaluate(async () => {
+ const f = window.pbFixture,
+ originalAction = f.action(),
+ outcomes = [];
+ for (const origin of [
+ 'wss://inbox.example.org',
+ 'wss://peer.example.org',
+ 'wss://archive.example.org'
+ ]) {
+ for (let n = 0; n < 3; n++) {
+ const actual = await f.publish(f.permission(origin));
+ outcomes.push(actual);
+ await f.append(actual);
+ await f.commitOriginal();
+ }
+ outcomes.push(await f.publish(f.permission(origin)));
+ }
+ return {
+ outcomes,
+ same: f.action() === originalAction,
+ row: f.snapshot()!.record
+ };
+ });
+ expect(result.same).toBe(true);
+ expect(result.row.receipts).toHaveLength(9);
+ expect(result.row.revision).toBe(10);
+ const attempted = result.outcomes.filter((x) => x.actionId);
+ expect(new Set(attempted.map((x) => x.actionId)).size).toBe(1);
+ expect(attempted.map((x) => x.attempt)).toEqual([1, 2, 3, 1, 2, 3, 1, 2, 3]);
+ expect(result.outcomes.filter((x) => !x.actionId)).toEqual(
+ Array(3).fill({ status: 'stopped' })
+ );
+ expect(privateEvents()).toHaveLength(9);
+ expect(privatePeak).toBe(3);
+ expect(privatePhysical.size).toBe(3);
+ noPrivateReads();
+ await page.evaluate(() => {
+ window.pbDelayClose = true;
+ window.pbFixture.stop();
+ });
+ expect(privatePhysical.size).toBe(3);
+ expect(
+ await page.evaluate(() =>
+ window.pb.privatePoolCleanupRequired(window.pbFixture.pool())
+ )
+ ).toBe(true);
+ expect(
+ await page.evaluate(() =>
+ window.pbFixture.publish(
+ window.pbFixture.permission('wss://peer.example.org')
+ )
+ )
+ ).toEqual({ status: 'stopped' });
+ expect(privateEvents()).toHaveLength(9);
+ await page.evaluate(() => {
+ window.pbDelayClose = false;
+ for (const release of window.pbHeldClose ?? []) release();
+ window.pbFixture.stop();
+ });
+ await expect.poll(() => privatePhysical.size).toBe(0);
+ expect(privatePeak).toBe(3);
+});
+
+test('three-origin original action shares total forty-five seconds across targets and refreshed ACKs', async ({
+ page
+}) => {
+ response = 'unknown';
+ await page.evaluate(() => {
+ const f = window.pbFixture;
+ window.pbNetworkClock = f.installNetworkClock();
+ window.pbRestore = () => window.pbNetworkClock!.restore();
+ window.pbPending = f.publish();
+ });
+ await expect.poll(() => privateEvents().length).toBe(1);
+ await page.evaluate(() => window.pbNetworkClock!.advance(46000));
+ const result = await page.evaluate(async () => {
+ const f = window.pbFixture,
+ actual = (await window.pbPending) as NonNullable<
+ ReturnType<typeof f.last>
+ >;
+ await f.append(actual);
+ const recommit = await f.commitOriginal();
+ return {
+ actual,
+ recommit: recommit.status,
+ others: await Promise.all(
+ ['wss://peer.example.org', 'wss://archive.example.org'].map((origin) =>
+ f.publish(f.permission(origin))
+ )
+ ),
+ observations: window.pbNetworkClock!.observations(),
+ row: f.snapshot()!.record
+ };
+ });
+ expect(result.actual).toMatchObject({ status: 'timed_out', attempt: 1 });
+ expect(result.recommit).toBe('existing');
+ expect(result.others).toEqual([{ status: 'stopped' }, { status: 'stopped' }]);
+ expect(result.observations).toBeGreaterThan(2);
+ expect(result.row.receipts).toHaveLength(1);
+ expect(privateEvents()).toHaveLength(1);
+ expect(privatePeak).toBeLessThanOrEqual(3);
+ noPrivateReads();
+});
+
+for (const nested of [false, true])
+ test(`three-origin actual SDK teardown ${nested ? 'reentrant Stop' : 'failure'} retries original scope while another origin remains live`, async ({
+ page
+ }) => {
+ await page.evaluate(async () => {
+ const f = window.pbFixture,
+ other = f.scope(['wss://archive.example.org'], 'delivery');
+ window.pbOtherPool = other;
+ const result = await window.pb.publishInboxProbeArchiveAttempt(
+ other,
+ f.permission('wss://archive.example.org')!,
+ new AbortController().signal
+ );
+ if (result.status !== 'accepted')
+ throw Error('actual other scope publication');
+ await f.append(result);
+ });
+ expect(privatePhysical.size).toBe(1);
+ response = 'unknown';
+ await page.evaluate((nested) => {
+ const f = window.pbFixture;
+ f.pool();
+ const fault = f.installAttemptTeardownFailure(
+ nested
+ ? () => {
+ window.pbNestedCleanup = (window.pbNestedCleanup ?? 0) + 1;
+ try {
+ f.stop();
+ } catch {
+ window.pbNestedFailure = (window.pbNestedFailure ?? 0) + 1;
+ }
+ }
+ : undefined
+ );
+ window.pbRestore = () => fault.restore();
+ window.pbAbort = new AbortController();
+ window.pbPending = f.publish(f.permission(), window.pbAbort.signal);
+ }, nested);
+ await expect.poll(() => privateEvents().length).toBe(2);
+ const first = await page.evaluate(async () => {
+ const f = window.pbFixture;
+ window.pbAbort!.abort();
+ const actual = (await window.pbPending) as NonNullable<
+ ReturnType<typeof f.last>
+ >,
+ evidence = window.pb.inboxProbeArchiveAttemptEvidence(actual);
+ const cleanup = window.pb.privatePoolCleanupRequired(f.pool());
+ window.pbRestore?.();
+ const append = await f.append(actual);
+ f.stop();
+ f.stop();
+ return {
+ actual,
+ evidence: !!evidence,
+ cleanup,
+ append,
+ cleanAfter: window.pb.privatePoolCleanupRequired(f.pool()),
+ row: f.snapshot()!.record,
+ next: await f.publish()
+ };
+ });
+ expect(first.actual).toMatchObject({ status: 'unknown', attempt: 1 });
+ expect(first.evidence).toBe(true);
+ expect(first.cleanup).toBe(true);
+ expect(first.append.status).toBe('saved');
+ expect(first.row.receipts[1].status).toBe('unknown');
+ expect(first.next).toEqual({ status: 'stopped' });
+ await expect.poll(() => privatePhysical.size).toBe(1);
+ await expect
+ .poll(() =>
+ page.evaluate(() =>
+ window.pb.privatePoolCleanupRequired(window.pbFixture.pool())
+ )
+ )
+ .toBe(false);
+ expect(privateConnections.get('wss://archive.example.org')).toBe(1);
+ response = 'accepted';
+ const other = await page.evaluate(async () => {
+ const f = window.pbFixture,
+ pool = window.pbOtherPool!;
+ return window.pb.publishInboxProbeArchiveAttempt(
+ pool,
+ f.permission('wss://archive.example.org')!,
+ new AbortController().signal
+ );
+ });
+ expect(other).toMatchObject({ status: 'accepted', attempt: 2 });
+ expect(privateConnections.get('wss://archive.example.org')).toBe(1);
+ expect(privateEvents()).toHaveLength(3);
+ expect(privatePeak).toBeLessThanOrEqual(3);
+ if (nested)
+ expect(
+ await page.evaluate(() => ({
+ nested: window.pbNestedCleanup,
+ failed: window.pbNestedFailure
+ }))
+ ).toEqual({ nested: 1, failed: 1 });
+ noPrivateReads();
+ });
+
+test('genuine ordinary paired publication cannot enter the separate probe facade or evidence family', async ({
+ page
+}) => {
+ const result = await page.evaluate(async () => {
+ window.pbFixture.close();
+ const ordinary = await window.pb.makeOrdinaryPublicationFixture();
+ try {
+ await ordinary.prepare();
+ const permission = ordinary.permission('peer');
+ if (!permission)
+ throw Error('genuine original ordinary permission missing');
+ const result = await window.pb.publishInboxProbeArchiveAttempt(
+ {} as Parameters<typeof window.pb.publishInboxProbeArchiveAttempt>[0],
+ permission as unknown as Parameters<
+ typeof window.pb.publishInboxProbeArchiveAttempt
+ >[1],
+ new AbortController().signal
+ );
+ return {
+ result,
+ evidence: !!window.pb.inboxProbeArchiveAttemptEvidence(result)
+ };
+ } finally {
+ ordinary.close();
+ }
+ });
+ expect(result.result).toEqual({ status: 'stopped' });
+ expect(result.evidence).toBe(false);
+ expect(privateEvents()).toHaveLength(0);
+ noPrivateReads();
+});
+
+test('actual original SDK socket construction closing the genuine controller is fenced before EVENT and attempted evidence', async ({
+ page
+}) => {
+ const result = await page.evaluate(async () => {
+ const f = window.pbFixture;
+ window.pbInvalidateOnSocket = true;
+ const actual = await f.publish();
+ window.pbInvalidateOnSocket = false;
+ return {
+ actual,
+ evidence: !!window.pb.inboxProbeArchiveAttemptEvidence(actual),
+ rows: await f.stored(),
+ ready: window.pb.inboxAccessControllerSnapshot(f.controller()!)?.readiness
+ };
+ });
+ expect(result.actual.status).toBe('stopped');
+ expect(result.actual.actionId).toBeUndefined();
+ expect(result.actual.attempt).toBeUndefined();
+ expect(result.evidence).toBe(false);
+ expect(
+ (JSON.parse(result.rows[0].wire) as { receipts: unknown[] }).receipts
+ ).toHaveLength(0);
+ expect(result.ready).toBe('unavailable');
+ expect(privateEvents()).toHaveLength(0);
+ noPrivateReads();
+});
diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs
@@ -1968,6 +1968,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
);
}
for (const producer of [
+ 'src/lib/nostr/private-publisher.ts',
'src/lib/persistence/inbox-probes.ts',
'src/lib/nostr/inbox-access.ts',
'src/lib/nostr/seal-builder.ts',
diff --git a/web/tests/provenance/source-boundaries.test.mjs b/web/tests/provenance/source-boundaries.test.mjs
@@ -18,7 +18,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { test } from 'node:test';
-test('CR007 exact private SDK removal cannot become an arbitrary remove capability', async () => {
+test('CR007 and CR008-S4B1 exact private SDK removal cannot become an arbitrary remove capability', async () => {
await fixture(async ({ directory, put, execute }) => {
await isolateScriptDependencies(directory);
await cp(path.join(root, 'src'), path.join(directory, 'src'), {
diff --git a/web/tests/unit/inbox-probe-publication.test.ts b/web/tests/unit/inbox-probe-publication.test.ts
@@ -0,0 +1,93 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import type { InboxProbeAcknowledgement } from '../../src/lib/persistence/inbox-probes.ts';
+import type { PrivateSession } from '../../src/lib/runtime/private-session.ts';
+import type { PrivateStorageRepository } from '../../src/lib/persistence/private-storage.ts';
+import type { RelayPolicy } from '../../src/lib/config/relays.ts';
+import type {
+ InboxProbePublication,
+ InboxProbePublicationAction
+} from '../../src/lib/nostr/private-publisher.ts';
+import type {
+ PrivatePool,
+ InboxProbeArchiveAttemptResult
+} from '../../src/lib/nostr/private-pool.ts';
+afterEach(() => vi.unstubAllGlobals());
+for (const browser of [false, true]) {
+ it(`cold ${browser ? 'browser-shaped' : 'SSR'} publication/receipt imports and forged capabilities cause no effects`, async () => {
+ vi.resetModules();
+ let effects = 0;
+ const trap = () => {
+ effects++;
+ throw Error('forged work');
+ };
+ if (browser) {
+ vi.stubGlobal('window', {
+ get nostr() {
+ return trap();
+ }
+ });
+ vi.stubGlobal('navigator', {
+ get locks() {
+ return trap();
+ }
+ });
+ vi.stubGlobal('WebSocket', trap);
+ }
+ const publisher = await import('../../src/lib/nostr/private-publisher.ts'),
+ pool = await import('../../src/lib/nostr/private-pool.ts'),
+ persistence = await import('../../src/lib/persistence/inbox-probes.ts');
+ const repository = {} as PrivateStorageRepository,
+ session = {} as PrivateSession,
+ policy = {} as RelayPolicy;
+ for (const fake of [
+ null,
+ undefined,
+ false,
+ 0,
+ 'token',
+ Symbol(),
+ {},
+ { status: 'accepted', current: () => true }
+ ]) {
+ expect(
+ publisher.captureInboxProbePublicationAction(
+ repository,
+ session,
+ policy,
+ fake as InboxProbeAcknowledgement,
+ 'reviewed_inbox_probe_network'
+ )
+ ).toBeUndefined();
+ expect(
+ publisher.captureInboxProbePublication(
+ repository,
+ session,
+ policy,
+ fake as InboxProbeAcknowledgement,
+ fake as InboxProbePublicationAction,
+ 'wss://inbox.example.org',
+ 'reviewed_inbox_probe_publication'
+ )
+ ).toBeUndefined();
+ expect(
+ await pool.publishInboxProbeArchiveAttempt(
+ {} as PrivatePool,
+ fake as InboxProbePublication,
+ new AbortController().signal
+ )
+ ).toEqual({ status: 'stopped' });
+ expect(
+ pool.inboxProbeArchiveAttemptEvidence(
+ fake as InboxProbeArchiveAttemptResult
+ )
+ ).toBeUndefined();
+ expect(
+ await persistence.commitInboxProbeArchiveAttempt(
+ repository,
+ fake as InboxProbeArchiveAttemptResult
+ )
+ ).toEqual({ status: 'invalid', disposition: 'original_protected' });
+ }
+ expect(effects).toBe(0);
+ });
+}
diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs
@@ -318,14 +318,16 @@ async function operationalFlagsAdmission(web) {
'245c6ce88b146dc731e7ace4f16dc9b5002a87a997f5568e4811b0c4a2daf035',
'src/lib/nostr/self-recovery-reader.ts':
'b15be31d13499b6e397f8b8dc691076e2b41b4157bf62013e5105cdd03875fa6',
+ 'src/lib/nostr/private-publisher.ts':
+ 'f7032c8a138adf70331b690cbf88eaac695facc9fd58bb0f12f9461e46edd51b',
'src/lib/nostr/private-pool.ts':
- 'b4c718364625b3caacbc5cc5f98bd79a575a5d66dddb2d7f59f03351a1308a6d',
+ '4d5f5c671aefc5439ed2d4f1e7619e1a348598f98a81862ee8aed41ed03df286',
'src/lib/nostr/inbox-ingress.ts':
'f860a094a8ba767585124c795d44b7620064f73a5b3a0170041c581c0fc64ecb',
'src/lib/persistence/inbox-probes.ts':
- '7441272a31386a4a70791269c31d55adaa11978ffcb094a98a5a83162aae2f99',
+ '857c2cf7e5cbf9253ad4b60b0f0e9a84cd99a1648d3b05d8e3013c695ac227fa',
'src/lib/nostr/inbox-access.ts':
- 'fcd0a3aa216bd092b84e8ea1f4824f047367eaec6ed4e16715612554244eab0b',
+ 'd39f218b66fb51833e962b20152a2df81adf3097ba434a4cf2172ee4a7c8e3bc',
'src/lib/nostr/seal-builder.ts':
'3ccc967cc348e63857243ff6f0302c1a68da2afe85ca2c37e00d5a894785fc53',
'src/lib/nostr/giftwrap-builder.ts':
@@ -594,14 +596,16 @@ async function privacyDataAdmission(web) {
'9cc82877bfa8dbb2a7fa41bceb842793349416271f19569f49fdd5cfc1de07e5',
'src/lib/nostr/self-recovery-reader.ts':
'b15be31d13499b6e397f8b8dc691076e2b41b4157bf62013e5105cdd03875fa6',
+ 'src/lib/nostr/private-publisher.ts':
+ 'f7032c8a138adf70331b690cbf88eaac695facc9fd58bb0f12f9461e46edd51b',
'src/lib/nostr/private-pool.ts':
- 'b4c718364625b3caacbc5cc5f98bd79a575a5d66dddb2d7f59f03351a1308a6d',
+ '4d5f5c671aefc5439ed2d4f1e7619e1a348598f98a81862ee8aed41ed03df286',
'src/lib/nostr/inbox-ingress.ts':
'f860a094a8ba767585124c795d44b7620064f73a5b3a0170041c581c0fc64ecb',
'src/lib/persistence/inbox-probes.ts':
- '7441272a31386a4a70791269c31d55adaa11978ffcb094a98a5a83162aae2f99',
+ '857c2cf7e5cbf9253ad4b60b0f0e9a84cd99a1648d3b05d8e3013c695ac227fa',
'src/lib/nostr/inbox-access.ts':
- 'fcd0a3aa216bd092b84e8ea1f4824f047367eaec6ed4e16715612554244eab0b',
+ 'd39f218b66fb51833e962b20152a2df81adf3097ba434a4cf2172ee4a7c8e3bc',
'src/lib/nostr/seal-builder.ts':
'3ccc967cc348e63857243ff6f0302c1a68da2afe85ca2c37e00d5a894785fc53',
'src/lib/nostr/giftwrap-builder.ts':
@@ -2165,7 +2169,7 @@ async function inboxProbeStorageAdmission(web) {
'src/lib/persistence/private-storage.ts':
'ba4a61dd1fa08fc89d00adac3c258c1f6ae7e5c1b15165facffe76ddd71d5e91',
'src/lib/persistence/inbox-probes.ts':
- '7441272a31386a4a70791269c31d55adaa11978ffcb094a98a5a83162aae2f99'
+ '857c2cf7e5cbf9253ad4b60b0f0e9a84cd99a1648d3b05d8e3013c695ac227fa'
};
for (const [name, pin] of Object.entries(producers)) {
const bytes = await readOwned(web, name);
diff --git a/web/tools/source-boundaries.mjs b/web/tools/source-boundaries.mjs
@@ -1664,7 +1664,7 @@ export async function auditSource(root) {
const relayRemovalTrusted =
files.has(relayRemovalFile) &&
createHash('sha256').update(files.get(relayRemovalFile)).digest('hex') ===
- 'b4c718364625b3caacbc5cc5f98bd79a575a5d66dddb2d7f59f03351a1308a6d';
+ '4d5f5c671aefc5439ed2d4f1e7619e1a348598f98a81862ee8aed41ed03df286';
if (files.has(relayRemovalFile) && !relayRemovalTrusted)
complain(
relayRemovalFile,