app

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

private-pool.ts (84220B)


      1 import { RelayClosedError } from 'applesauce-relay/relay';
      2 import { inboxProbeReadbackMatches } from '../persistence/private-records.ts';
      3 import { privateInboxQueries } from './inbox-queries.ts';
      4 import { createScopedRelayPool } from './pool-factory.ts';
      5 import { NEVER } from 'rxjs';
      6 import {
      7   privatePublicationSnapshot,
      8   takePrivatePublication,
      9   type PrivatePublication,
     10   type PrivateDeliveryRole,
     11   inboxProbePublicationSnapshot,
     12   takeInboxProbePublication,
     13   type InboxProbePublication,
     14   inboxProbeReadbackSnapshot,
     15   takeInboxProbeReadback,
     16   type InboxProbeReadback
     17 } from './private-publisher.ts';
     18 import {
     19   takeInboxAuthAdmission,
     20   takeGuardedInboxAuthResponse,
     21   type InboxAuthAdmission,
     22   type GuardedInboxAuthResponse
     23 } from './inbox-auth.ts';
     24 import {
     25   verifyEnvelope,
     26   verifiedEnvelopeSnapshot,
     27   boundedEnvelopeTags
     28 } from './verified-envelope.ts';
     29 import { readRelayPolicy, type RelayPolicy } from '../config/relays.ts';
     30 import {
     31   PRIVATE_TRANSPORT_BUDGETS,
     32   PRIVATE_LIVE_BUDGETS,
     33   PRIVATE_AUTH_BUDGETS,
     34   PRIVATE_PUBLICATION_BUDGETS,
     35   RELAY_BUDGETS
     36 } from '../config/budgets.ts';
     37 import {
     38   privateSessionOwnership,
     39   privateSessionSnapshot,
     40   subscribePrivateSessionClose,
     41   recheckPrivateSession,
     42   invalidatePrivateSessionGeneration,
     43   type PrivateSession
     44 } from '../runtime/private-session.ts';
     45 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
     46 import type { PrivateStorageRepository } from '../persistence/private-storage.ts';
     47 declare const poolBrand: unique symbol;
     48 export type PrivatePool = Readonly<{ [poolBrand]: true }>;
     49 export type PrivateGiftWrapAttemptResult = Readonly<{
     50   status: 'accepted' | 'refused' | 'unknown' | 'timed_out' | 'stopped';
     51   role?: PrivateDeliveryRole;
     52   origin?: string;
     53   eventId?: string;
     54   actionId?: string;
     55   attempt?: number;
     56 }>;
     57 export type InboxProbeArchiveAttemptResult = Readonly<{
     58   status: PrivateGiftWrapAttemptResult['status'];
     59   role?: 'access_archive';
     60   origin?: string;
     61   eventId?: string;
     62   actionId?: string;
     63   attempt?: number;
     64 }>;
     65 export type InboxProbeReadbackAttemptResult = Readonly<{
     66   status:
     67     | 'readback'
     68     | 'empty'
     69     | 'refused'
     70     | 'error'
     71     | 'budget'
     72     | 'unknown'
     73     | 'timed_out'
     74     | 'stopped';
     75   role?: 'access_readback';
     76   origin?: string;
     77   eventId?: string;
     78   actionId?: string;
     79   attempt?: number;
     80   deliveries?: number;
     81 }>;
     82 const probeReadEvidence = new WeakMap<
     83   InboxProbeReadbackAttemptResult,
     84   Readonly<{
     85     repository: PrivateStorageRepository;
     86     acknowledgement: import('../persistence/inbox-probes.ts').InboxProbeAcknowledgement;
     87     predecessorWire: string;
     88     receiptWire: string;
     89   }>
     90 >();
     91 export function inboxProbeReadbackAttemptEvidence(
     92   result: InboxProbeReadbackAttemptResult
     93 ) {
     94   const evidence = probeReadEvidence.get(result);
     95   return evidence && { ...evidence };
     96 }
     97 type PublicationAttemptResult =
     98   PrivateGiftWrapAttemptResult | InboxProbeArchiveAttemptResult;
     99 const probeAttemptEvidence = new WeakMap<
    100   InboxProbeArchiveAttemptResult,
    101   Readonly<{
    102     repository: PrivateStorageRepository;
    103     acknowledgement: import('../persistence/inbox-probes.ts').InboxProbeAcknowledgement;
    104     predecessorWire: string;
    105     receiptWire: string;
    106   }>
    107 >();
    108 export function inboxProbeArchiveAttemptEvidence(
    109   result: InboxProbeArchiveAttemptResult
    110 ) {
    111   const evidence = probeAttemptEvidence.get(result);
    112   return evidence && { ...evidence };
    113 }
    114 type AttemptEvidence = Readonly<{
    115   repository: PrivateStorageRepository;
    116   owner: string;
    117   command: string;
    118   pairWire: string;
    119   receiptWire: string;
    120 }>;
    121 const attemptEvidence = new WeakMap<
    122   PrivateGiftWrapAttemptResult,
    123   AttemptEvidence
    124 >();
    125 // Only this module's actual admitted SDK EVENT port mints these observations.
    126 // Detached/cloned status objects cannot impersonate an attempted operation.
    127 export function privateGiftWrapAttemptEvidence(
    128   result: PrivateGiftWrapAttemptResult
    129 ) {
    130   const evidence = attemptEvidence.get(result);
    131   return evidence && { ...evidence };
    132 }
    133 export type PrivatePageMessage =
    134   | Readonly<{ type: 'candidate'; from: string; wire: string }>
    135   | Readonly<{
    136       type: 'end';
    137       deliveries?: number;
    138       reason:
    139         | 'complete'
    140         | 'closed'
    141         | 'stale'
    142         | 'error'
    143         | 'budget'
    144         | 'elapsed'
    145         | 'stopped';
    146     }>;
    147 export type PrivateLiveMessage =
    148   PrivatePageMessage | Readonly<{ type: 'open' }>;
    149 type FiniteBudget = {
    150   elapsed(): number;
    151   count(): number;
    152   remainingBytes(): number;
    153   charge(bytes: number): boolean;
    154   finish(milliseconds: number): void;
    155 };
    156 function finiteBudget(): FiniteBudget {
    157   let deliveries = 0,
    158     bytes = 0,
    159     elapsed = 0;
    160   return {
    161     elapsed: () => elapsed,
    162     count: () => deliveries,
    163     remainingBytes: () => PRIVATE_TRANSPORT_BUDGETS.processedBytes - bytes,
    164     charge(size) {
    165       deliveries++;
    166       bytes += size;
    167       return (
    168         deliveries <= PRIVATE_TRANSPORT_BUDGETS.deliveries &&
    169         bytes <= PRIVATE_TRANSPORT_BUDGETS.processedBytes
    170       );
    171     },
    172     finish(milliseconds) {
    173       elapsed += milliseconds;
    174     }
    175   };
    176 }
    177 type ScopedConnectionCleanup = Readonly<{
    178   current(): boolean;
    179   close(): void;
    180 }>;
    181 type Owner = {
    182   session: PrivateSession;
    183   policy: RelayPolicy;
    184   origins: readonly string[];
    185   readOrigins: readonly string[];
    186   token: PrivatePool;
    187   closed(): boolean;
    188   cleaned(): boolean;
    189   unavailable(): boolean;
    190   publish(
    191     permission: PrivatePublication | InboxProbePublication,
    192     signal: AbortSignal,
    193     scopeCurrent?: () => boolean,
    194     retainConnection?: (
    195       origin: string,
    196       cleanup: ScopedConnectionCleanup
    197     ) => boolean,
    198     retainPublicationCleanup?: (cleanup: () => void) => () => void
    199   ): Promise<PublicationAttemptResult>;
    200   readProbe(
    201     permission: InboxProbeReadback,
    202     signal: AbortSignal,
    203     scopeCurrent?: () => boolean,
    204     retainConnection?: (
    205       origin: string,
    206       cleanup: ScopedConnectionCleanup
    207     ) => boolean,
    208     retainCleanup?: (cleanup: () => void) => () => void
    209   ): Promise<InboxProbeReadbackAttemptResult>;
    210   auth(
    211     origin: string,
    212     admission: InboxAuthAdmission,
    213     admittedPool?: PrivatePool,
    214     scopeCurrent?: () => boolean,
    215     retainCleanup?: (cleanup: () => void) => void
    216   ): Promise<PrivateAuthConnection | undefined>;
    217   subscribe(
    218     limit: number,
    219     listener: (message: PrivatePageMessage) => void,
    220     since?: number,
    221     budget?: FiniteBudget,
    222     until?: number,
    223     source?: string,
    224     reads?: readonly string[],
    225     scopeCurrent?: () => boolean,
    226     retainConnection?: (
    227       origin: string,
    228       cleanup: ScopedConnectionCleanup
    229     ) => boolean
    230   ): () => void;
    231   subscribeLive(
    232     listener: (message: PrivateLiveMessage) => void,
    233     reads?: readonly string[],
    234     scopeCurrent?: () => boolean,
    235     retainConnection?: (
    236       origin: string,
    237       cleanup: ScopedConnectionCleanup
    238     ) => boolean
    239   ): () => void;
    240   close(): void;
    241 };
    242 declare const connectionBrand: unique symbol;
    243 export type PrivateAuthConnection = Readonly<{ [connectionBrand]: true }>;
    244 export type PrivateAuthChallenge = Readonly<{
    245   owner: string;
    246   session: symbol;
    247   connection: symbol;
    248   relay: string;
    249   challenge: string;
    250   current(): boolean;
    251 }>;
    252 type AuthControl = {
    253   invalidate(proof: PrivateAuthChallenge): boolean;
    254   challenge(): PrivateAuthChallenge | undefined;
    255   stopped(): boolean;
    256   reserve(proof: PrivateAuthChallenge): boolean;
    257   send(
    258     proof: PrivateAuthChallenge,
    259     response: GuardedInboxAuthResponse
    260   ): Promise<'accepted' | 'refused' | 'unknown' | 'stopped'>;
    261   close(): void;
    262 };
    263 const authConnections = new WeakMap<PrivateAuthConnection, AuthControl>();
    264 const pools = new WeakMap<PrivatePool, Owner>();
    265 const probeRetryIdle = new WeakMap<Owner, () => boolean>();
    266 let lifetime: Owner | undefined;
    267 type ScopeRole = 'receive' | 'delivery' | 'access';
    268 const scopes = new WeakMap<Owner, WeakMap<object, Map<string, PrivatePool>>>();
    269 // Consumer identity is lexical workflow ownership, never a relay/access proof.
    270 // Weak ownership retains at most45 bounded selections per live consumer. All
    271 // selections share the one session SDK; ciphertext/plaintext is absent here.
    272 function scopedPool(
    273   base: Owner,
    274   consumer: object,
    275   selected: readonly string[],
    276   role: ScopeRole,
    277   authorized: () => boolean
    278 ): PrivatePool {
    279   const consumers =
    280     scopes.get(base) ?? new WeakMap<object, Map<string, PrivatePool>>();
    281   scopes.set(base, consumers);
    282   const owned = consumers.get(consumer) ?? new Map<string, PrivatePool>();
    283   consumers.set(consumer, owned);
    284   const key = JSON.stringify([role, selected]);
    285   const previous = owned.get(key);
    286   const prior = previous && pools.get(previous);
    287   if (previous && prior && !prior.closed()) return previous;
    288   if (prior && !prior.cleaned()) throw Error('private_pool_close_failed');
    289   const token = Object.freeze({}) as PrivatePool;
    290   const origins = [...selected];
    291   const readOrigins =
    292     role === 'delivery'
    293       ? []
    294       : origins.filter((origin) => base.readOrigins.includes(origin));
    295   const life = new AbortController();
    296   const stops = new Map<symbol, () => void>();
    297   const authStops = new Map<string, () => void>();
    298   const probePublicationStops = new Map<() => void, true>();
    299   const connections = new Map<string, ScopedConnectionCleanup>();
    300   let closed = false,
    301     cleaned = false;
    302   const current = () =>
    303     !closed &&
    304     !base.closed() &&
    305     authorized() &&
    306     !!privateSessionOwnership(base.session)?.current() &&
    307     !closed &&
    308     !base.closed();
    309   function track(start: (ended: () => void) => () => void): () => void {
    310     if (!current()) throw Error('private_pool_closed');
    311     const id = Symbol();
    312     let release = () => {},
    313       ended = false;
    314     const stop = () => {
    315       release();
    316       stops.delete(id);
    317     };
    318     stops.set(id, stop);
    319     try {
    320       release = start(() => {
    321         ended = true;
    322         if (!base.unavailable()) stops.delete(id);
    323       });
    324       if (ended && !base.unavailable()) stops.delete(id);
    325       return stop;
    326     } catch (error) {
    327       stops.delete(id);
    328       throw error;
    329     }
    330   }
    331   function retainConnection(origin: string, cleanup: ScopedConnectionCleanup) {
    332     const previous = connections.get(origin);
    333     if (previous?.current()) return false;
    334     previous?.close();
    335     connections.set(origin, cleanup);
    336     return true;
    337   }
    338   const scope: Owner = {
    339     session: base.session,
    340     policy: base.policy,
    341     origins,
    342     readOrigins,
    343     token,
    344     closed: () => closed || base.closed(),
    345     cleaned: () => (cleaned && !base.unavailable()) || base.cleaned(),
    346     unavailable: () => base.unavailable() || (closed && !cleaned),
    347     publish(permission, signal) {
    348       const view =
    349         privatePublicationSnapshot(permission as PrivatePublication) ??
    350         inboxProbePublicationSnapshot(permission as InboxProbePublication);
    351       return current() && view && origins.includes(view.origin)
    352         ? base.publish(
    353             permission,
    354             AbortSignal.any([signal, life.signal]),
    355             current,
    356             retainConnection,
    357             inboxProbePublicationSnapshot(permission as InboxProbePublication)
    358               ? (cleanup) => {
    359                   probePublicationStops.set(cleanup, true);
    360                   return () => {
    361                     probePublicationStops.delete(cleanup);
    362                   };
    363                 }
    364               : undefined
    365           )
    366         : Promise.resolve({ status: 'stopped' });
    367     },
    368     readProbe(permission, signal) {
    369       const view = inboxProbeReadbackSnapshot(permission);
    370       return current() && view && readOrigins.includes(view.origin)
    371         ? base.readProbe(
    372             permission,
    373             AbortSignal.any([signal, life.signal]),
    374             current,
    375             retainConnection,
    376             (cleanup) => {
    377               probePublicationStops.set(cleanup, true);
    378               return () => {
    379                 probePublicationStops.delete(cleanup);
    380               };
    381             }
    382           )
    383         : Promise.resolve({ status: 'stopped' });
    384     },
    385     async auth(origin, admission) {
    386       if (!current() || !origins.includes(origin)) return undefined;
    387       const connection = await base.auth(
    388         origin,
    389         admission,
    390         token,
    391         current,
    392         (cleanup) => {
    393           authStops.set(origin, cleanup);
    394         }
    395       );
    396       if (!connection) return undefined;
    397       if (!current()) {
    398         closePrivateAuthConnection(connection);
    399         return undefined;
    400       }
    401       authStops.set(origin, () => closePrivateAuthConnection(connection));
    402       return connection;
    403     },
    404     subscribe(limit, listener, since, budget, until, source) {
    405       return track((ended) =>
    406         base.subscribe(
    407           limit,
    408           (message) => {
    409             if (message.type === 'end') ended();
    410             listener(message);
    411           },
    412           since,
    413           budget,
    414           until,
    415           source,
    416           readOrigins,
    417           current,
    418           retainConnection
    419         )
    420       );
    421     },
    422     subscribeLive(listener) {
    423       return track((ended) =>
    424         base.subscribeLive(
    425           (message) => {
    426             if (message.type === 'end') ended();
    427             listener(message);
    428           },
    429           readOrigins,
    430           current,
    431           retainConnection
    432         )
    433       );
    434     },
    435     close() {
    436       closed = true;
    437       life.abort();
    438       let failed = false;
    439       for (const [id, stop] of stops) {
    440         try {
    441           stop();
    442           stops.delete(id);
    443         } catch {
    444           failed = true;
    445         }
    446       }
    447       for (const cleanup of probePublicationStops.keys()) {
    448         try {
    449           cleanup();
    450           probePublicationStops.delete(cleanup);
    451         } catch {
    452           failed = true;
    453         }
    454       }
    455       for (const [origin, stop] of authStops) {
    456         try {
    457           stop();
    458           authStops.delete(origin);
    459         } catch {
    460           failed = true;
    461         }
    462       }
    463       for (const [origin, connection] of connections) {
    464         try {
    465           connection.close();
    466           connections.delete(origin);
    467         } catch {
    468           failed = true;
    469         }
    470       }
    471       cleaned = !failed;
    472       if (failed) throw Error('private_pool_close_failed');
    473     }
    474   };
    475   pools.set(token, scope);
    476   owned.set(key, token);
    477   return token;
    478 }
    479 // Fixed scope selection is not authenticated owner10050 membership/readiness.
    480 // No production receive workflow calls this until its later inbox owner exists.
    481 export function getPrivatePool(
    482   session: PrivateSession,
    483   policy: RelayPolicy,
    484   selected: readonly string[],
    485   consumer: object = session,
    486   role: ScopeRole = 'receive',
    487   authorized: () => boolean = () => true
    488 ): PrivatePool | undefined {
    489   if (typeof window === 'undefined') return undefined;
    490   const captured = privateSessionOwnership(session);
    491   if (!captured) throw new Error('private_session_invalid');
    492   const capture = captured;
    493   if (
    494     !consumer ||
    495     typeof consumer !== 'object' ||
    496     !['receive', 'delivery', 'access'].includes(role) ||
    497     typeof authorized !== 'function'
    498   )
    499     throw Error('private_pool_scope_invalid');
    500   const manifest = readRelayPolicy(policy);
    501   if (!manifest.messagingEnabled) throw new Error('private_pool_disabled');
    502   const length = Array.isArray(selected) ? selected.length : 0;
    503   if (length < 1 || length > RELAY_BUDGETS.inbox)
    504     throw new Error('private_pool_origins_invalid');
    505   const selectedOrigins = new Map<string, true>();
    506   for (let i = 0; i < length; i++) {
    507     const origin = selected[i];
    508     if (
    509       typeof origin !== 'string' ||
    510       selectedOrigins.has(origin) ||
    511       !manifest.inbox.some(
    512         ({ origin: allowed, read, write }) =>
    513           allowed === origin && (read || write)
    514       )
    515     )
    516       throw new Error('private_pool_origins_invalid');
    517     selectedOrigins.set(origin, true);
    518   }
    519   const selectedTargets = [...selectedOrigins.keys()];
    520   // SDK identity is fixed by the entire bounded manifest, while each consumer
    521   // retains only its reviewed role/targets. No connection opens on acquisition.
    522   const origins = manifest.inbox.map((row) => row.origin);
    523   const readOrigins = origins.filter((origin) =>
    524     manifest.inbox.some((row) => row.origin === origin && row.read)
    525   );
    526   // Untrusted selection access can run code. Recheck before factory admission.
    527   if (!capture.current()) throw new Error('private_session_invalid');
    528   if (lifetime) {
    529     if (!lifetime.cleaned()) {
    530       if (lifetime.closed() || lifetime.unavailable())
    531         throw new Error('private_pool_closed');
    532       if (lifetime.session !== session || lifetime.policy !== policy)
    533         throw new Error('private_pool_in_use');
    534       return scopedPool(lifetime, consumer, selectedTargets, role, authorized);
    535     }
    536   }
    537   const token = Object.freeze({}) as PrivatePool;
    538   const sdk = createScopedRelayPool();
    539   let closed = false,
    540     cleaned = false,
    541     busy = false,
    542     cleanupRequired = false;
    543   let active = () => {};
    544   let liveActive = () => {},
    545     liveBusy = false,
    546     liveCleanupRequired = false;
    547   let off = () => {};
    548   const authCleanup = new Map<string, () => void>();
    549   const authFailed = new Map<string, true>();
    550   const authRetiring = new Map<string, true>();
    551   const publicationStops = new Map<() => void, true>();
    552   const publicationFailures = new Map<() => void, true>();
    553   let publishing = false,
    554     publicationCleanupRequired = false;
    555   type Connection = Readonly<{
    556     retiring(): boolean;
    557     retire(): void;
    558     reserve(): Readonly<{
    559       relay: ReturnType<typeof sdk.relay>;
    560       start(): void;
    561       close(): void;
    562       retire(): void;
    563       pending(): boolean;
    564       current(): boolean;
    565     }>;
    566   }>;
    567   const connections = new Map<string, Connection>();
    568   function probeRelayAuthReady(
    569     relay: ReturnType<typeof sdk.relay>,
    570     origin: string,
    571     role: 'publish' | 'read' = 'publish'
    572   ) {
    573     let required: boolean | undefined;
    574     const observation = (
    575       role === 'read'
    576         ? relay.authRequiredForRead$
    577         : relay.authRequiredForPublish$
    578     ).subscribe((value) => {
    579       required = value;
    580     });
    581     observation.unsubscribe();
    582     return (
    583       required !== undefined &&
    584       !(
    585         (required || authCleanup.has(origin)) &&
    586         (!relay.authenticated || relay.authenticatedAs !== capture.owner)
    587       ) &&
    588       (!relay.authenticated || relay.authenticatedAs === capture.owner)
    589     );
    590   }
    591 
    592   function leaseConnection(origin: string) {
    593     const previous = connections.get(origin);
    594     if (previous) {
    595       if (previous.retiring()) throw Error('private_connection_close_pending');
    596       return previous.reserve();
    597     }
    598     const relay = sdk.relay(origin);
    599     let references = 0,
    600       started = false,
    601       physicallyClosed = false,
    602       retiring = false,
    603       disposed = false,
    604       releaseBridge = () => {},
    605       unwatch = () => {};
    606     function retire() {
    607       if (disposed) return;
    608       retiring = true;
    609       releaseBridge();
    610       sdk.remove(relay);
    611       if (started && !physicallyClosed) return;
    612       unwatch();
    613       disposed = true;
    614       if (connections.get(origin) === original) connections.delete(origin);
    615     }
    616     const original: Connection = {
    617       retiring: () => retiring,
    618       retire,
    619       reserve() {
    620         references++;
    621         let released = false;
    622         return {
    623           relay,
    624           start() {
    625             if (
    626               released ||
    627               closed ||
    628               retiring ||
    629               disposed ||
    630               !capture.current()
    631             )
    632               throw Error('private_connection_closed');
    633             if (started) return;
    634             started = true;
    635             let starting = true,
    636               opened = false,
    637               noSocket = false;
    638             const open = relay.open$.subscribe(() => {
    639               opened = true;
    640             });
    641             function startupFailure() {
    642               if (!starting || opened || noSocket) return;
    643               noSocket = true;
    644               started = false;
    645               retiring = true;
    646               queueMicrotask(() => {
    647                 try {
    648                   retire();
    649                 } catch {
    650                   /* Retry retained. */
    651                 }
    652               });
    653             }
    654             const error = relay.error$.subscribe((failure) => {
    655               // Original NEVER/no filters cannot receive a remote callback
    656               // before this synchronous subscribe returns. Only a native
    657               // constructor failure proves no physical socket in that stack.
    658               if (failure) startupFailure();
    659             });
    660             const bridge = relay
    661               .req(NEVER, {
    662                 waitForAuth: false,
    663                 reconnect: false,
    664                 resubscribe: false
    665               })
    666               .subscribe({
    667                 error() {
    668                   startupFailure();
    669                   if (!noSocket) {
    670                     retiring = true;
    671                     queueMicrotask(() => {
    672                       try {
    673                         retire();
    674                       } catch {
    675                         /* Actual closure still required. */
    676                       }
    677                     });
    678                   }
    679                 }
    680               });
    681             starting = false;
    682             open.unsubscribe();
    683             error.unsubscribe();
    684             releaseBridge = () => bridge.unsubscribe();
    685             if (noSocket) throw Error('private_connection_start_failed');
    686           },
    687           close() {
    688             if (!released) {
    689               released = true;
    690               references--;
    691             }
    692             // Cancel keepAlive's zero timer before a closing socket can reopen.
    693             if (references === 0) retire();
    694           },
    695           retire,
    696           pending: () => started && !physicallyClosed && !disposed,
    697           current: () => !retiring && !disposed
    698         };
    699       }
    700     };
    701     connections.set(origin, original);
    702     const lost = relay.close$.subscribe(() => {
    703       physicallyClosed = true;
    704       try {
    705         retire();
    706         if (closed) owner.close();
    707       } catch {
    708         /* Original physical retirement remains retryable. */
    709       }
    710     });
    711     unwatch = () => lost.unsubscribe();
    712     return original.reserve();
    713   }
    714   const owner: Owner = {
    715     session,
    716     policy,
    717     origins,
    718     readOrigins,
    719     token,
    720     closed: () => closed,
    721     cleaned: () => cleaned,
    722     unavailable: () =>
    723       cleanupRequired ||
    724       liveCleanupRequired ||
    725       publicationCleanupRequired ||
    726       authFailed.size !== 0 ||
    727       authRetiring.size !== 0 ||
    728       [...connections.values()].some((connection) => connection.retiring()),
    729     async publish(
    730       permission,
    731       signal,
    732       scopeCurrent = () => true,
    733       retainConnection,
    734       retainPublicationCleanup
    735     ) {
    736       const probe = inboxProbePublicationSnapshot(
    737         permission as InboxProbePublication
    738       );
    739       const observed =
    740         probe ?? privatePublicationSnapshot(permission as PrivatePublication);
    741       if (!observed) return { status: 'stopped' };
    742       const view = observed;
    743       if (
    744         publishing ||
    745         closed ||
    746         cleanupRequired ||
    747         publicationCleanupRequired ||
    748         signal.aborted ||
    749         !scopeCurrent() ||
    750         !capture.current() ||
    751         authRetiring.has(view.origin) ||
    752         authFailed.has(view.origin) ||
    753         view.owner !== capture.owner ||
    754         !origins.includes(view.origin) ||
    755         authRetiring.has(view.origin) ||
    756         authFailed.has(view.origin) ||
    757         !manifest.inbox.some(
    758           ({ origin: allowed, write }) => allowed === view.origin && write
    759         ) ||
    760         typeof window === 'undefined' ||
    761         !navigator.locks?.request
    762       )
    763         return { status: 'stopped' };
    764       publishing = true;
    765       try {
    766         // A genuine C7 AUTH provider job may occupy the shared SDK scheduler.
    767         // Observe that original connection before queueing another fresh-key
    768         // job, so known waiting refuses without a probe prompt/meter/effect.
    769         if (probe) {
    770           const originalConnection = connections.get(view.origin);
    771           if (originalConnection) {
    772             if (originalConnection.retiring()) return { status: 'stopped' };
    773             const observation = originalConnection.reserve();
    774             try {
    775               if (
    776                 !observation.current() ||
    777                 !probeRelayAuthReady(observation.relay, view.origin)
    778               )
    779                 return { status: 'stopped' };
    780             } finally {
    781               observation.close();
    782             }
    783           }
    784         }
    785         // No owner lock is held across the serialized fresh extension job.
    786         if (
    787           !(await recheckPrivateSession(session)) ||
    788           closed ||
    789           signal.aborted ||
    790           !scopeCurrent() ||
    791           !capture.current() ||
    792           authRetiring.has(view.origin) ||
    793           authFailed.has(view.origin)
    794         )
    795           return { status: 'stopped' };
    796         return await navigator.locks.request(
    797           'harvestcircle:owner:' + capture.owner,
    798           { mode: 'exclusive', ifAvailable: true },
    799           async (lock) => {
    800             if (
    801               !lock ||
    802               closed ||
    803               signal.aborted ||
    804               !scopeCurrent() ||
    805               !capture.current() ||
    806               authRetiring.has(view.origin) ||
    807               authFailed.has(view.origin)
    808             )
    809               return { status: 'stopped' as const };
    810             const admitted = probe
    811               ? await takeInboxProbePublication(
    812                   permission as InboxProbePublication,
    813                   session,
    814                   policy,
    815                   view.origin
    816                 )
    817               : await takePrivatePublication(
    818                   permission as PrivatePublication,
    819                   session,
    820                   policy,
    821                   view.origin
    822                 );
    823             if (
    824               !admitted ||
    825               closed ||
    826               signal.aborted ||
    827               !scopeCurrent() ||
    828               !capture.current() ||
    829               authRetiring.has(view.origin) ||
    830               authFailed.has(view.origin) ||
    831               !admitted.current()
    832             )
    833               return { status: 'stopped' as const };
    834             const connection = leaseConnection(view.origin);
    835             // Stock SDK EVENT can wait behind known AUTH. Refuse probe work
    836             // before starting its meter; only separate explicit C7 AUTH signs.
    837             if (probe) {
    838               if (
    839                 !probeRelayAuthReady(connection.relay, view.origin) ||
    840                 !connection.current() ||
    841                 !admitted.current()
    842               ) {
    843                 connection.close();
    844                 return { status: 'stopped' as const };
    845               }
    846             }
    847             const network = admitted.beginNetwork();
    848             if (admitted.networkMetered && !network) {
    849               connection.close();
    850               return { status: 'stopped' as const };
    851             }
    852             if (
    853               !scopeCurrent() ||
    854               !capture.current() ||
    855               closed ||
    856               signal.aborted ||
    857               authRetiring.has(view.origin) ||
    858               authFailed.has(view.origin)
    859             ) {
    860               network?.finish();
    861               connection.close();
    862               return { status: 'stopped' as const };
    863             }
    864             return await new Promise<PublicationAttemptResult>((resolve) => {
    865               let ended = false,
    866                 attempted = false,
    867                 release = () => {},
    868                 forgetCleanup = () => {},
    869                 fenceTimer: ReturnType<typeof setTimeout> | undefined,
    870                 timer: ReturnType<typeof setTimeout> | undefined,
    871                 retainedConnection = false,
    872                 releasing = false;
    873               function disposeOriginal() {
    874                 // The stock unsubscribe can run finalizers. Nested Stop must
    875                 // retain this exact port until the outer cleanup really settles.
    876                 if (releasing)
    877                   throw Error('private_publication_cleanup_pending');
    878                 releasing = true;
    879                 try {
    880                   release();
    881                   if (!retainedConnection) connection.close();
    882                   publicationStops.delete(stop);
    883                   publicationFailures.delete(stop);
    884                   publicationCleanupRequired = publicationFailures.size !== 0;
    885                   forgetCleanup();
    886                 } finally {
    887                   releasing = false;
    888                 }
    889               }
    890               function retainFailure() {
    891                 publicationStops.set(stop, true);
    892                 publicationFailures.set(stop, true);
    893                 publicationCleanupRequired = true;
    894                 forgetCleanup = retainPublicationCleanup?.(stop) ?? (() => {});
    895               }
    896               function finish(status: PrivateGiftWrapAttemptResult['status']) {
    897                 if (ended) return;
    898                 ended = true;
    899                 network?.finish();
    900                 if (timer !== undefined) clearTimeout(timer);
    901                 if (fenceTimer !== undefined) clearTimeout(fenceTimer);
    902                 signal.removeEventListener('abort', stop);
    903                 try {
    904                   disposeOriginal();
    905                 } catch {
    906                   retainFailure();
    907                   status = 'unknown';
    908                 }
    909                 if (!attempted) status = 'stopped';
    910                 const result: PublicationAttemptResult = {
    911                   status,
    912                   role: admitted!.role,
    913                   origin: admitted!.origin,
    914                   eventId: admitted!.eventId,
    915                   ...(attempted && network
    916                     ? { actionId: network.actionId, attempt: network.attempt }
    917                     : {})
    918                 };
    919                 if (attempted && network) {
    920                   const receiptWire = JSON.stringify({
    921                     actionId: network.actionId,
    922                     role: admitted!.role,
    923                     origin: admitted!.origin,
    924                     eventId: admitted!.eventId,
    925                     attempt: network.attempt,
    926                     status,
    927                     observedAtMilliseconds: Date.now(),
    928                     readbackWire: null
    929                   });
    930                   if ('acknowledgement' in admitted!) {
    931                     probeAttemptEvidence.set(
    932                       result as InboxProbeArchiveAttemptResult,
    933                       {
    934                         repository: admitted.repository,
    935                         acknowledgement: admitted.acknowledgement,
    936                         predecessorWire: admitted.predecessorWire,
    937                         receiptWire
    938                       }
    939                     );
    940                   } else {
    941                     attemptEvidence.set(
    942                       result as PrivateGiftWrapAttemptResult,
    943                       {
    944                         repository: admitted!.repository,
    945                         owner: admitted!.owner,
    946                         command: admitted!.command,
    947                         pairWire: admitted!.pairWire,
    948                         receiptWire
    949                       }
    950                     );
    951                   }
    952                 }
    953                 resolve(result);
    954               }
    955               function stop() {
    956                 if (ended) {
    957                   disposeOriginal();
    958                   return;
    959                 }
    960                 finish('stopped');
    961               }
    962               function probeStopped() {
    963                 return (
    964                   !!probe &&
    965                   (closed ||
    966                     signal.aborted ||
    967                     !scopeCurrent() ||
    968                     !capture.current() ||
    969                     authRetiring.has(view.origin) ||
    970                     authFailed.has(view.origin) ||
    971                     !admitted!.current())
    972                 );
    973               }
    974               function fence() {
    975                 if (ended) return;
    976                 if (probeStopped()) {
    977                   finish('stopped');
    978                   return;
    979                 }
    980                 if (network && network.remaining() <= 0) {
    981                   finish('timed_out');
    982                   return;
    983                 }
    984                 if (
    985                   closed ||
    986                   signal.aborted ||
    987                   !scopeCurrent() ||
    988                   !capture.current() ||
    989                   authRetiring.has(view.origin) ||
    990                   authFailed.has(view.origin) ||
    991                   !admitted!.current()
    992                 ) {
    993                   finish('stopped');
    994                   return;
    995                 }
    996                 fenceTimer = setTimeout(() => fence(), 50);
    997               }
    998               try {
    999                 const relay = connection.relay;
   1000                 const allowance =
   1001                   network?.remaining() ??
   1002                   PRIVATE_PUBLICATION_BUDGETS.networkActionMilliseconds;
   1003                 const timeout =
   1004                   Number.isFinite(relay.eventTimeout) && relay.eventTimeout > 0
   1005                     ? Math.min(allowance, relay.eventTimeout)
   1006                     : allowance;
   1007                 timer = setTimeout(
   1008                   () => finish(probeStopped() ? 'stopped' : 'timed_out'),
   1009                   timeout
   1010                 );
   1011                 signal.addEventListener('abort', stop, { once: true });
   1012                 publicationStops.set(stop, true);
   1013                 forgetCleanup = retainPublicationCleanup?.(stop) ?? (() => {});
   1014                 if (
   1015                   closed ||
   1016                   signal.aborted ||
   1017                   !scopeCurrent() ||
   1018                   !capture.current() ||
   1019                   authRetiring.has(view.origin) ||
   1020                   authFailed.has(view.origin) ||
   1021                   !admitted.current()
   1022                 ) {
   1023                   finish('stopped');
   1024                   return;
   1025                 }
   1026                 // The only private EVENT port accepts the freshly read-back1059;
   1027                 // no caller event, key, relay template or SDK option crosses it.
   1028                 connection.start();
   1029                 retainedConnection =
   1030                   retainConnection?.(view.origin, {
   1031                     current: connection.current,
   1032                     close: connection.close
   1033                   }) ?? false;
   1034                 if (
   1035                   probe &&
   1036                   (probeStopped() ||
   1037                     !connection.current() ||
   1038                     !probeRelayAuthReady(relay, view.origin))
   1039                 ) {
   1040                   finish('stopped');
   1041                   return;
   1042                 }
   1043                 attempted = true;
   1044                 const subscription = relay
   1045                   .event(admitted.event, 'EVENT')
   1046                   .subscribe({
   1047                     next(response) {
   1048                       if (ended) return;
   1049                       if (probeStopped()) {
   1050                         finish('stopped');
   1051                         return;
   1052                       }
   1053                       if (network && network.remaining() <= 0) {
   1054                         finish('timed_out');
   1055                         return;
   1056                       }
   1057                       if (
   1058                         (response.from !== view.origin &&
   1059                           response.from !== view.origin + '/') ||
   1060                         typeof response.ok !== 'boolean'
   1061                       )
   1062                         finish('unknown');
   1063                       else if (response.ok) finish('accepted');
   1064                       else if (response.message === 'Timeout')
   1065                         finish('unknown');
   1066                       else finish('refused');
   1067                     },
   1068                     error: () => finish('unknown'),
   1069                     complete: () => {
   1070                       if (!ended) finish('unknown');
   1071                     }
   1072                   });
   1073                 release = () => subscription.unsubscribe();
   1074                 if (ended) {
   1075                   try {
   1076                     disposeOriginal();
   1077                   } catch {
   1078                     retainFailure();
   1079                   }
   1080                 } else fence();
   1081               } catch {
   1082                 finish('unknown');
   1083               }
   1084             });
   1085           }
   1086         );
   1087       } catch {
   1088         return { status: 'stopped' };
   1089       } finally {
   1090         publishing = false;
   1091       }
   1092     },
   1093     async readProbe(
   1094       permission,
   1095       signal,
   1096       scopeCurrent = () => true,
   1097       retainConnection,
   1098       retainCleanup
   1099     ) {
   1100       const view = inboxProbeReadbackSnapshot(permission);
   1101       if (!view) return { status: 'stopped' };
   1102       function stopped() {
   1103         return (
   1104           closed ||
   1105           cleanupRequired ||
   1106           publicationCleanupRequired ||
   1107           signal.aborted ||
   1108           !scopeCurrent() ||
   1109           !capture.current() ||
   1110           authRetiring.has(view!.origin) ||
   1111           authFailed.has(view!.origin)
   1112         );
   1113       }
   1114       if (
   1115         publishing ||
   1116         stopped() ||
   1117         view.owner !== capture.owner ||
   1118         !readOrigins.includes(view.origin) ||
   1119         typeof window === 'undefined' ||
   1120         !navigator.locks?.request
   1121       )
   1122         return { status: 'stopped' };
   1123       publishing = true;
   1124       try {
   1125         const previous = connections.get(view.origin);
   1126         if (previous) {
   1127           if (previous.retiring()) return { status: 'stopped' };
   1128           const observation = previous.reserve();
   1129           try {
   1130             if (
   1131               !observation.current() ||
   1132               !probeRelayAuthReady(observation.relay, view.origin, 'read')
   1133             )
   1134               return { status: 'stopped' };
   1135           } finally {
   1136             observation.close();
   1137           }
   1138         }
   1139         if (!(await recheckPrivateSession(session)) || stopped())
   1140           return { status: 'stopped' };
   1141         return await navigator.locks.request(
   1142           'harvestcircle:owner:' + capture.owner,
   1143           { mode: 'exclusive', ifAvailable: true },
   1144           async (lock) => {
   1145             if (!lock || stopped()) return { status: 'stopped' as const };
   1146             const admitted = await takeInboxProbeReadback(
   1147               permission,
   1148               session,
   1149               policy,
   1150               view.origin
   1151             );
   1152             if (!admitted || stopped() || !admitted.current())
   1153               return { status: 'stopped' as const };
   1154             const connection = leaseConnection(view.origin);
   1155             if (
   1156               !connection.current() ||
   1157               !probeRelayAuthReady(connection.relay, view.origin, 'read') ||
   1158               stopped() ||
   1159               !admitted.current()
   1160             ) {
   1161               connection.close();
   1162               return { status: 'stopped' as const };
   1163             }
   1164             const network = admitted.beginNetwork();
   1165             if (!network) {
   1166               connection.close();
   1167               return { status: 'stopped' as const };
   1168             }
   1169             return await new Promise<InboxProbeReadbackAttemptResult>(
   1170               (resolve) => {
   1171                 const budget = finiteBudget();
   1172                 let ended = false,
   1173                   attempted = false,
   1174                   installing = false,
   1175                   releasing = false,
   1176                   retainedConnection = false,
   1177                   release = () => {},
   1178                   forgetCleanup = () => {},
   1179                   pending:
   1180                     InboxProbeReadbackAttemptResult['status'] | undefined,
   1181                   observedWire: string | undefined,
   1182                   timer: ReturnType<typeof setTimeout> | undefined,
   1183                   fenceTimer: ReturnType<typeof setTimeout> | undefined;
   1184                 const pageStarted = performance.now();
   1185                 let lastClock = pageStarted;
   1186                 function stale() {
   1187                   return (
   1188                     stopped() || !admitted!.current() || !connection.current()
   1189                   );
   1190                 }
   1191                 function remainingPage() {
   1192                   const now = performance.now();
   1193                   if (
   1194                     !Number.isFinite(now) ||
   1195                     now < lastClock ||
   1196                     !Number.isFinite(pageStarted)
   1197                   )
   1198                     return 0;
   1199                   lastClock = now;
   1200                   return Math.max(
   1201                     0,
   1202                     PRIVATE_TRANSPORT_BUDGETS.pageMilliseconds -
   1203                       (now - pageStarted)
   1204                   );
   1205                 }
   1206                 function expired() {
   1207                   return remainingPage() <= 0 || network!.remaining() <= 0;
   1208                 }
   1209                 function disposeOriginal() {
   1210                   if (installing || releasing)
   1211                     throw Error('private_probe_read_cleanup_pending');
   1212                   releasing = true;
   1213                   try {
   1214                     release();
   1215                     if (!retainedConnection) connection.close();
   1216                     publicationStops.delete(stop);
   1217                     publicationFailures.delete(stop);
   1218                     publicationCleanupRequired = publicationFailures.size !== 0;
   1219                     forgetCleanup();
   1220                   } finally {
   1221                     releasing = false;
   1222                   }
   1223                 }
   1224                 function retainFailure() {
   1225                   publicationStops.set(stop, true);
   1226                   publicationFailures.set(stop, true);
   1227                   publicationCleanupRequired = true;
   1228                   forgetCleanup = retainCleanup?.(stop) ?? (() => {});
   1229                 }
   1230                 function finish(
   1231                   status: InboxProbeReadbackAttemptResult['status']
   1232                 ) {
   1233                   if (ended) return;
   1234                   if (installing) {
   1235                     pending ??= status;
   1236                     return;
   1237                   }
   1238                   ended = true;
   1239                   network!.finish();
   1240                   if (timer !== undefined) clearTimeout(timer);
   1241                   if (fenceTimer !== undefined) clearTimeout(fenceTimer);
   1242                   signal.removeEventListener('abort', onAbort);
   1243                   try {
   1244                     disposeOriginal();
   1245                   } catch {
   1246                     retainFailure();
   1247                     status = 'unknown';
   1248                   }
   1249                   if (!attempted) status = 'stopped';
   1250                   const result: InboxProbeReadbackAttemptResult = {
   1251                     status,
   1252                     role: 'access_readback',
   1253                     origin: admitted!.origin,
   1254                     eventId: admitted!.eventId,
   1255                     deliveries: budget.count(),
   1256                     ...(attempted
   1257                       ? {
   1258                           actionId: network!.actionId,
   1259                           attempt: network!.attempt
   1260                         }
   1261                       : {})
   1262                   };
   1263                   if (
   1264                     attempted &&
   1265                     status === 'readback' &&
   1266                     observedWire !== undefined
   1267                   ) {
   1268                     probeReadEvidence.set(result, {
   1269                       repository: admitted!.repository,
   1270                       acknowledgement: admitted!.acknowledgement,
   1271                       predecessorWire: admitted!.predecessorWire,
   1272                       receiptWire: JSON.stringify({
   1273                         actionId: network!.actionId,
   1274                         role: 'access_readback',
   1275                         origin: admitted!.origin,
   1276                         eventId: admitted!.eventId,
   1277                         attempt: network!.attempt,
   1278                         status: 'readback',
   1279                         observedAtMilliseconds: Date.now(),
   1280                         readbackWire: observedWire
   1281                       })
   1282                     });
   1283                   }
   1284                   resolve(result);
   1285                 }
   1286                 // Abort dispatch cannot propagate a synchronous cleanup exception.
   1287                 // Explicit retained Stop still reports pending original installation.
   1288                 function onAbort() {
   1289                   finish('stopped');
   1290                 }
   1291                 function stop() {
   1292                   if (ended) {
   1293                     disposeOriginal();
   1294                     return;
   1295                   }
   1296                   finish('stopped');
   1297                   if (installing)
   1298                     throw Error('private_probe_read_cleanup_pending');
   1299                 }
   1300                 function fence() {
   1301                   if (ended) return;
   1302                   if (stale()) {
   1303                     finish('stopped');
   1304                     return;
   1305                   }
   1306                   if (expired()) {
   1307                     finish('timed_out');
   1308                     return;
   1309                   }
   1310                   fenceTimer = setTimeout(fence, 50);
   1311                 }
   1312                 try {
   1313                   publicationStops.set(stop, true);
   1314                   forgetCleanup = retainCleanup?.(stop) ?? (() => {});
   1315                   signal.addEventListener('abort', onAbort, { once: true });
   1316                   if (stale() || expired()) {
   1317                     finish(stale() ? 'stopped' : 'timed_out');
   1318                     return;
   1319                   }
   1320                   connection.start();
   1321                   retainedConnection =
   1322                     retainConnection?.(view.origin, {
   1323                       current: connection.current,
   1324                       close: connection.close
   1325                     }) ?? false;
   1326                   if (
   1327                     stale() ||
   1328                     !probeRelayAuthReady(connection.relay, view.origin, 'read')
   1329                   ) {
   1330                     finish('stopped');
   1331                     return;
   1332                   }
   1333                   if (expired()) {
   1334                     finish('timed_out');
   1335                     return;
   1336                   }
   1337                   installing = true;
   1338                   attempted = true;
   1339                   // Exact original self artifact/recipient only. SDK owns transport;
   1340                   // no caller filter, socket, key or auto AUTH/retry port is exposed.
   1341                   const subscription = sdk
   1342                     .req(
   1343                       [view.origin],
   1344                       [
   1345                         {
   1346                           kinds: [1059],
   1347                           ids: [admitted.eventId],
   1348                           '#p': [admitted.owner],
   1349                           limit: 1
   1350                         }
   1351                       ],
   1352                       {
   1353                         waitForAuth: false,
   1354                         reconnect: false,
   1355                         resubscribe: false
   1356                       }
   1357                     )
   1358                     .subscribe({
   1359                       next(message) {
   1360                         if (ended || pending !== undefined) return;
   1361                         if (stale()) {
   1362                           finish('stopped');
   1363                           return;
   1364                         }
   1365                         if (expired()) {
   1366                           finish('timed_out');
   1367                           return;
   1368                         }
   1369                         if (
   1370                           message.type !== 'EVENT' &&
   1371                           message.from !== view.origin &&
   1372                           message.from !== view.origin + '/'
   1373                         ) {
   1374                           finish('error');
   1375                           return;
   1376                         }
   1377                         if (message.type === 'EVENT') {
   1378                           const wire = JSON.stringify(message.event);
   1379                           if (
   1380                             typeof wire !== 'string' ||
   1381                             !boundedUtf8(wire, budget.remainingBytes())
   1382                           ) {
   1383                             budget.charge(budget.remainingBytes() + 1);
   1384                             finish('budget');
   1385                             return;
   1386                           }
   1387                           if (
   1388                             !budget.charge(
   1389                               new TextEncoder().encode(wire).length
   1390                             )
   1391                           ) {
   1392                             finish('budget');
   1393                             return;
   1394                           }
   1395                           // Charge delivered work before source or signature rejection.
   1396                           if (
   1397                             message.from !== view.origin &&
   1398                             message.from !== view.origin + '/'
   1399                           ) {
   1400                             finish('error');
   1401                             return;
   1402                           }
   1403                           if (
   1404                             !boundedUtf8(
   1405                               wire,
   1406                               PRIVATE_TRANSPORT_BUDGETS.envelopeBytes
   1407                             )
   1408                           )
   1409                             return;
   1410                           if (
   1411                             inboxProbeReadbackMatches(
   1412                               {
   1413                                 eventId: admitted.eventId,
   1414                                 wire: JSON.stringify(admitted.event)
   1415                               },
   1416                               admitted.owner,
   1417                               wire
   1418                             )
   1419                           ) {
   1420                             observedWire = wire;
   1421                             finish('readback');
   1422                           }
   1423                         } else if (message.type === 'EOSE') finish('empty');
   1424                         else if (message.type === 'CLOSED') finish('refused');
   1425                         else if (message.type === 'ERROR')
   1426                           finish(
   1427                             message.error instanceof RelayClosedError
   1428                               ? 'refused'
   1429                               : 'error'
   1430                           );
   1431                       },
   1432                       error: (error: unknown) =>
   1433                         finish(
   1434                           stale()
   1435                             ? 'stopped'
   1436                             : error instanceof RelayClosedError
   1437                               ? 'refused'
   1438                               : 'error'
   1439                         ),
   1440                       complete: () => finish(stale() ? 'stopped' : 'empty')
   1441                     });
   1442                   release = () => subscription.unsubscribe();
   1443                   installing = false;
   1444                   if (pending !== undefined) {
   1445                     finish(pending);
   1446                     return;
   1447                   }
   1448                   if (stale()) {
   1449                     finish('stopped');
   1450                     return;
   1451                   }
   1452                   if (expired()) {
   1453                     finish('timed_out');
   1454                     return;
   1455                   }
   1456                   timer = setTimeout(
   1457                     () => finish(stale() ? 'stopped' : 'timed_out'),
   1458                     Math.min(remainingPage(), network.remaining())
   1459                   );
   1460                   fence();
   1461                 } catch {
   1462                   installing = false;
   1463                   finish(stale() ? 'stopped' : 'unknown');
   1464                 }
   1465               }
   1466             );
   1467           }
   1468         );
   1469       } catch {
   1470         return { status: 'stopped' };
   1471       } finally {
   1472         publishing = false;
   1473       }
   1474     },
   1475     async auth(
   1476       origin,
   1477       admission,
   1478       admittedPool = token,
   1479       scopeCurrent = () => true,
   1480       retainCleanup = () => {}
   1481     ) {
   1482       if (
   1483         closed ||
   1484         cleanupRequired ||
   1485         !origins.includes(origin) ||
   1486         !scopeCurrent() ||
   1487         authFailed.size !== 0 ||
   1488         authCleanup.has(origin) ||
   1489         authRetiring.has(origin) ||
   1490         !capture.current()
   1491       )
   1492         return undefined;
   1493       if (!takeInboxAuthAdmission(admission, admittedPool, origin))
   1494         return undefined;
   1495       // Reserve before any provider job. No duplicate reviewed action may reset
   1496       // a live connection's response admission counter.
   1497       let stopped = false,
   1498         responded = false,
   1499         responses = 0,
   1500         challenge: string | undefined;
   1501       let generation: symbol | undefined;
   1502       const proofs = new WeakMap<PrivateAuthChallenge, true>();
   1503       let reservation: PrivateAuthChallenge | undefined;
   1504       let sent = false;
   1505       const releases = new Map<symbol, () => void>();
   1506       let retireRelay = () => {};
   1507       let disposed = false;
   1508       let pendingClose = () => false;
   1509       let closeWatch = () => {};
   1510       function cleanup() {
   1511         if (disposed) return;
   1512         stopped = true;
   1513         challenge = undefined;
   1514         generation = undefined;
   1515         let failed = false;
   1516         for (const [id, release] of releases) {
   1517           try {
   1518             release();
   1519             releases.delete(id);
   1520           } catch {
   1521             failed = true;
   1522           }
   1523         }
   1524         try {
   1525           retireRelay();
   1526         } catch {
   1527           failed = true;
   1528         }
   1529         if (failed) {
   1530           authFailed.set(origin, true);
   1531           throw new Error('private_auth_cleanup_required');
   1532         }
   1533         if (pendingClose()) {
   1534           authRetiring.set(origin, true);
   1535           return;
   1536         }
   1537         closeWatch();
   1538         disposed = true;
   1539         authCleanup.delete(origin);
   1540         authFailed.delete(origin);
   1541         authRetiring.delete(origin);
   1542       }
   1543       authCleanup.set(origin, cleanup);
   1544       retainCleanup(cleanup);
   1545       const halt = () => {
   1546         if (stopped) return;
   1547         stopped = true;
   1548         try {
   1549           cleanup();
   1550         } catch {
   1551           /* Actual control retained for retry. */
   1552         }
   1553       };
   1554       if (
   1555         !(await recheckPrivateSession(session)) ||
   1556         closed ||
   1557         stopped ||
   1558         !scopeCurrent() ||
   1559         !capture.current()
   1560       ) {
   1561         halt();
   1562         return undefined;
   1563       }
   1564       try {
   1565         const connection = leaseConnection(origin);
   1566         retireRelay = () => {
   1567           connection.close();
   1568           connection.retire();
   1569         };
   1570         const actualRelay = connection.relay;
   1571         pendingClose = connection.pending;
   1572         const token = Object.freeze({}) as PrivateAuthConnection;
   1573         // A private page may already own this actual SDK connection. Its open$
   1574         // Subject does not replay; initialize from its genuine connected state.
   1575         if (actualRelay.connected$.value) generation = Symbol();
   1576         function current() {
   1577           return (
   1578             !stopped &&
   1579             !closed &&
   1580             scopeCurrent() &&
   1581             capture.current() &&
   1582             generation !== undefined
   1583           );
   1584         }
   1585         const control: AuthControl = {
   1586           invalidate(proof) {
   1587             if (
   1588               !proofs.has(proof) ||
   1589               !proof.current() ||
   1590               !current() ||
   1591               proof.connection !== generation ||
   1592               proof.challenge !== challenge
   1593             )
   1594               return false;
   1595             return invalidatePrivateSessionGeneration(session);
   1596           },
   1597           stopped: () => !current(),
   1598           challenge() {
   1599             if (!current() || challenge === undefined || responded)
   1600               return undefined;
   1601             const exact = challenge,
   1602               stamp = generation!;
   1603             const proof: PrivateAuthChallenge = {
   1604               owner: capture.owner,
   1605               session: capture.session,
   1606               connection: stamp,
   1607               relay: actualRelay.url,
   1608               challenge: exact,
   1609               current: () =>
   1610                 current() && generation === stamp && challenge === exact
   1611             };
   1612             proofs.set(proof, true);
   1613             return proof;
   1614           },
   1615           reserve(proof) {
   1616             if (
   1617               !proofs.has(proof) ||
   1618               reservation !== undefined ||
   1619               !proof.current() ||
   1620               !current() ||
   1621               responded ||
   1622               proof.connection !== generation ||
   1623               proof.challenge !== challenge ||
   1624               responses >= PRIVATE_AUTH_BUDGETS.responsesPerConnectionAction
   1625             )
   1626               return false;
   1627             responses++;
   1628             reservation = proof;
   1629             sent = false;
   1630             return true;
   1631           },
   1632           async send(proof, approved) {
   1633             const wire = takeGuardedInboxAuthResponse(approved, proof);
   1634             const verified = verifyEnvelope(wire);
   1635             const event = verified.ok
   1636               ? verifiedEnvelopeSnapshot(verified.value)
   1637               : undefined;
   1638             if (
   1639               !proofs.has(proof) ||
   1640               reservation !== proof ||
   1641               sent ||
   1642               !event ||
   1643               event.kind !== 22242 ||
   1644               event.pubkey !== capture.owner ||
   1645               event.content !== '' ||
   1646               JSON.stringify(event.tags) !==
   1647                 JSON.stringify([
   1648                   ['relay', actualRelay.url],
   1649                   ['challenge', proof.challenge]
   1650                 ]) ||
   1651               !proof.current() ||
   1652               !current() ||
   1653               proof.connection !== generation ||
   1654               proof.challenge !== challenge
   1655             )
   1656               return 'stopped';
   1657             try {
   1658               sent = true;
   1659               const response = await actualRelay.auth(event);
   1660               if (!proof.current() || !current()) return 'stopped';
   1661               if (response.ok) {
   1662                 responded = true;
   1663                 return 'accepted';
   1664               }
   1665               const outcome =
   1666                 response.message === 'Timeout' ? 'unknown' : 'refused';
   1667               halt();
   1668               return outcome;
   1669             } catch {
   1670               halt();
   1671               return 'unknown';
   1672             }
   1673           },
   1674           close: cleanup
   1675         };
   1676         authConnections.set(token, control);
   1677         const opened = actualRelay.open$.subscribe(() => {
   1678           if (!stopped && !closed && capture.current()) generation = Symbol();
   1679         });
   1680         releases.set(Symbol(), () => opened.unsubscribe());
   1681         const lost = actualRelay.close$.subscribe(() => {
   1682           halt();
   1683           try {
   1684             cleanup();
   1685             if (closed) owner.close();
   1686           } catch {
   1687             /* Keep owned disposal retryable. */
   1688           }
   1689         });
   1690         closeWatch = () => lost.unsubscribe();
   1691         const closing = actualRelay.closing$.subscribe(halt);
   1692         releases.set(Symbol(), () => closing.unsubscribe());
   1693         const challenges = actualRelay.challenge$.subscribe((next: unknown) => {
   1694           if (stopped || closed || !capture.current()) {
   1695             halt();
   1696             return;
   1697           }
   1698           if (next === null) return;
   1699           if (
   1700             typeof next !== 'string' ||
   1701             !next ||
   1702             !boundedEnvelopeTags([
   1703               ['relay', actualRelay.url],
   1704               ['challenge', next]
   1705             ]) ||
   1706             !generation
   1707           ) {
   1708             halt();
   1709             return;
   1710           }
   1711           if (next === challenge) return;
   1712           if (
   1713             responses >= PRIVATE_AUTH_BUDGETS.responsesPerConnectionAction ||
   1714             (challenge !== undefined && !responded)
   1715           ) {
   1716             halt();
   1717             return;
   1718           }
   1719           challenge = next;
   1720           responded = false;
   1721           reservation = undefined;
   1722         });
   1723         releases.set(Symbol(), () => challenges.unsubscribe());
   1724         if (closed || stopped || !capture.current()) {
   1725           cleanup();
   1726           return undefined;
   1727         }
   1728         // Official Observable filter input holds the watchTower without emitting
   1729         // a filter/REQ. Its own CLOSE at teardown is ordinary SDK control cleanup.
   1730         connection.start();
   1731         const hold = actualRelay
   1732           .req(NEVER, {
   1733             waitForAuth: false,
   1734             reconnect: false,
   1735             resubscribe: false
   1736           })
   1737           .subscribe({ error: halt, complete: halt });
   1738         releases.set(Symbol(), () => hold.unsubscribe());
   1739         if (closed || stopped || !capture.current()) {
   1740           cleanup();
   1741           return undefined;
   1742         }
   1743         return token;
   1744       } catch {
   1745         try {
   1746           cleanup();
   1747         } catch {
   1748           /* Original failed cleanup retained. */
   1749         }
   1750         return undefined;
   1751       }
   1752     },
   1753     subscribeLive(
   1754       listener,
   1755       reads = readOrigins,
   1756       scopeCurrent = () => true,
   1757       retainConnection
   1758     ) {
   1759       if (!reads.length) throw Error('private_read_origins_unavailable');
   1760       if (
   1761         reads.some(
   1762           (origin) => authRetiring.has(origin) || authFailed.has(origin)
   1763         )
   1764       )
   1765         throw Error('private_auth_cleanup_required');
   1766       if (
   1767         closed ||
   1768         !scopeCurrent() ||
   1769         !capture.current() ||
   1770         reads.some(
   1771           (origin) => authRetiring.has(origin) || authFailed.has(origin)
   1772         )
   1773       )
   1774         throw Error('private_pool_closed');
   1775       if (liveBusy || liveCleanupRequired) throw Error('private_live_busy');
   1776       liveBusy = true;
   1777       let ended = false,
   1778         release = () => {},
   1779         serial = 0;
   1780       const opened = new Map<string, true>(),
   1781         meters = new Map<string, Map<number, { at: number; bytes: number }>>();
   1782       const leased = new Map<string, ReturnType<typeof leaseConnection>>();
   1783       function releaseAll() {
   1784         release();
   1785         for (const [origin, connection] of leased) {
   1786           connection.close();
   1787           leased.delete(origin);
   1788         }
   1789       }
   1790       function emit(message: PrivateLiveMessage) {
   1791         try {
   1792           listener(message);
   1793         } catch {
   1794           /* Keep cleanup owned even when a consumer throws. */
   1795         }
   1796       }
   1797       function finish(
   1798         reason: Extract<PrivatePageMessage, { type: 'end' }>['reason'],
   1799         propagate = false
   1800       ) {
   1801         if (ended) {
   1802           if (liveCleanupRequired && propagate) {
   1803             releaseAll();
   1804             liveCleanupRequired = false;
   1805             liveBusy = false;
   1806           }
   1807           return;
   1808         }
   1809         ended = true;
   1810         let failure: unknown;
   1811         try {
   1812           releaseAll();
   1813           liveCleanupRequired = false;
   1814           liveBusy = false;
   1815         } catch (error) {
   1816           failure = error;
   1817           liveCleanupRequired = true;
   1818         }
   1819         meters.clear();
   1820         opened.clear();
   1821         emit({ type: 'end', reason: liveCleanupRequired ? 'error' : reason });
   1822         if (liveCleanupRequired && propagate) throw failure;
   1823       }
   1824       liveActive = () => {
   1825         finish('closed', true);
   1826         releaseAll();
   1827       };
   1828       void recheckPrivateSession(session)
   1829         .then((fresh) => {
   1830           if (ended) return;
   1831           if (
   1832             !fresh ||
   1833             closed ||
   1834             !scopeCurrent() ||
   1835             !capture.current() ||
   1836             reads.some(
   1837               (origin) => authRetiring.has(origin) || authFailed.has(origin)
   1838             )
   1839           ) {
   1840             finish('stale');
   1841             return;
   1842           }
   1843           for (const origin of reads) {
   1844             const connection = leaseConnection(origin);
   1845             leased.set(origin, connection);
   1846             connection.start();
   1847             if (
   1848               retainConnection?.(origin, {
   1849                 current: connection.current,
   1850                 close: connection.close
   1851               })
   1852             )
   1853               leased.delete(origin);
   1854           }
   1855           const subscription = sdk
   1856             .req([...reads], [...privateInboxQueries(capture.owner, 'live')], {
   1857               waitForAuth: false,
   1858               reconnect: false,
   1859               resubscribe: false
   1860             })
   1861             .subscribe({
   1862               next(message) {
   1863                 if (ended) return;
   1864                 if (
   1865                   closed ||
   1866                   !scopeCurrent() ||
   1867                   !capture.current() ||
   1868                   reads.some(
   1869                     (origin) =>
   1870                       authRetiring.has(origin) || authFailed.has(origin)
   1871                   )
   1872                 ) {
   1873                   finish('stale');
   1874                   return;
   1875                 }
   1876                 const origin = message.from.endsWith('/')
   1877                   ? message.from.slice(0, -1)
   1878                   : message.from;
   1879                 if (!reads.includes(origin)) {
   1880                   finish('error');
   1881                   return;
   1882                 }
   1883                 if (message.type === 'OPEN') {
   1884                   opened.set(origin, true);
   1885                   if (opened.size === reads.length) emit({ type: 'open' });
   1886                 } else if (message.type === 'EVENT') {
   1887                   const now = performance.now();
   1888                   let meter = meters.get(origin);
   1889                   if (!meter) {
   1890                     meter = new Map();
   1891                     meters.set(origin, meter);
   1892                   }
   1893                   let bytes = 0;
   1894                   for (const [key, item] of meter) {
   1895                     if (
   1896                       now - item.at >=
   1897                       PRIVATE_LIVE_BUDGETS.windowMilliseconds
   1898                     )
   1899                       meter.delete(key);
   1900                     else bytes += item.bytes;
   1901                   }
   1902                   // Count every actual delivery, including invalid envelopes/duplicates.
   1903                   if (meter.size >= PRIVATE_LIVE_BUDGETS.deliveries) {
   1904                     finish('budget');
   1905                     return;
   1906                   }
   1907                   const wire = JSON.stringify(message.event);
   1908                   if (
   1909                     typeof wire !== 'string' ||
   1910                     !boundedUtf8(
   1911                       wire,
   1912                       PRIVATE_LIVE_BUDGETS.processedBytes - bytes
   1913                     )
   1914                   ) {
   1915                     finish('budget');
   1916                     return;
   1917                   }
   1918                   meter.set(++serial, {
   1919                     at: now,
   1920                     bytes: new TextEncoder().encode(wire).length
   1921                   });
   1922                   if (
   1923                     boundedUtf8(wire, PRIVATE_TRANSPORT_BUDGETS.envelopeBytes)
   1924                   )
   1925                     emit({ type: 'candidate', from: origin, wire });
   1926                 } else if (message.type === 'CLOSED') finish('closed');
   1927                 else if (message.type === 'ERROR') finish('error');
   1928                 // EOSE ends retained history only; the unthrottled live owner remains.
   1929               },
   1930               error: () => finish('error'),
   1931               complete: () => finish('closed')
   1932             });
   1933           release = () => subscription.unsubscribe();
   1934           if (
   1935             ended ||
   1936             closed ||
   1937             !scopeCurrent() ||
   1938             !capture.current() ||
   1939             reads.some(
   1940               (origin) => authRetiring.has(origin) || authFailed.has(origin)
   1941             )
   1942           ) {
   1943             releaseAll();
   1944             if (!ended) finish('stale');
   1945           }
   1946         })
   1947         .catch(() => {
   1948           if (!ended) finish('error');
   1949         });
   1950       return () => finish('stopped', true);
   1951     },
   1952     subscribe(
   1953       limit,
   1954       listener,
   1955       since,
   1956       sharedBudget,
   1957       until,
   1958       source,
   1959       reads = readOrigins,
   1960       scopeCurrent = () => true,
   1961       retainConnection
   1962     ) {
   1963       const targets =
   1964         source === undefined
   1965           ? reads
   1966           : reads.filter((origin) => origin === source);
   1967       if (targets.length === 0)
   1968         throw new Error('private_read_origins_unavailable');
   1969       if (
   1970         targets.some(
   1971           (origin) => authRetiring.has(origin) || authFailed.has(origin)
   1972         )
   1973       )
   1974         throw Error('private_auth_cleanup_required');
   1975       if (
   1976         closed ||
   1977         !scopeCurrent() ||
   1978         !capture.current() ||
   1979         targets.some(
   1980           (origin) => authRetiring.has(origin) || authFailed.has(origin)
   1981         )
   1982       ) {
   1983         if (closed || !capture.current()) owner.close();
   1984         throw new Error('private_pool_closed');
   1985       }
   1986       if (cleanupRequired) throw new Error('private_page_cleanup_required');
   1987       if (busy) throw new Error('private_page_busy');
   1988       busy = true;
   1989       let ended = false;
   1990       const budget = sharedBudget ?? finiteBudget();
   1991       const baselineDeliveries = budget.count();
   1992       let release = () => {};
   1993       let timer: ReturnType<typeof setTimeout> | undefined;
   1994       const completed = new Map<string, true>();
   1995       let started = 0;
   1996       const leased = new Map<string, ReturnType<typeof leaseConnection>>();
   1997       function releaseAll() {
   1998         release();
   1999         for (const [origin, connection] of leased) {
   2000           connection.close();
   2001           leased.delete(origin);
   2002         }
   2003       }
   2004       function emit(message: PrivatePageMessage) {
   2005         try {
   2006           listener(message);
   2007         } catch {
   2008           /* Consumer cannot interrupt cleanup. */
   2009         }
   2010       }
   2011       function finish(
   2012         reason: Extract<PrivatePageMessage, { type: 'end' }>['reason'],
   2013         propagate = false
   2014       ) {
   2015         if (ended) {
   2016           if (cleanupRequired && propagate) {
   2017             releaseAll();
   2018             cleanupRequired = false;
   2019             busy = false;
   2020           }
   2021           return;
   2022         }
   2023         ended = true;
   2024         if (started > 0) budget.finish(performance.now() - started);
   2025         if (timer !== undefined) clearTimeout(timer);
   2026         let failure: unknown;
   2027         try {
   2028           releaseAll();
   2029         } catch (error) {
   2030           cleanupRequired = true;
   2031           failure = error;
   2032         } finally {
   2033           busy = cleanupRequired;
   2034           emit({
   2035             type: 'end',
   2036             reason: cleanupRequired ? 'error' : reason,
   2037             ...(source === undefined
   2038               ? {}
   2039               : { deliveries: budget.count() - baselineDeliveries })
   2040           });
   2041         }
   2042         // SDK and timer callbacks report finite error state without leaking an
   2043         // exception. Explicit stop/close can report failure and retry release.
   2044         if (cleanupRequired && propagate) throw failure;
   2045       }
   2046       active = () => {
   2047         finish('closed', true);
   2048         releaseAll();
   2049       };
   2050       // Reserve the page before awaiting fresh extension ownership. Stop/logout
   2051       // fence the continuation and no socket may open from a stale key result.
   2052       void recheckPrivateSession(session)
   2053         .then((fresh) => {
   2054           if (ended) return;
   2055           if (
   2056             !fresh ||
   2057             closed ||
   2058             !scopeCurrent() ||
   2059             !capture.current() ||
   2060             targets.some(
   2061               (origin) => authRetiring.has(origin) || authFailed.has(origin)
   2062             )
   2063           ) {
   2064             finish('stale');
   2065             return;
   2066           }
   2067           if (budget.elapsed() >= PRIVATE_TRANSPORT_BUDGETS.pageMilliseconds) {
   2068             finish('elapsed');
   2069             return;
   2070           }
   2071           started = performance.now();
   2072           if (
   2073             ended ||
   2074             closed ||
   2075             !scopeCurrent() ||
   2076             !capture.current() ||
   2077             targets.some(
   2078               (origin) => authRetiring.has(origin) || authFailed.has(origin)
   2079             )
   2080           ) {
   2081             if (!ended) finish('stale');
   2082             return;
   2083           }
   2084           for (const origin of targets) {
   2085             const connection = leaseConnection(origin);
   2086             leased.set(origin, connection);
   2087             connection.start();
   2088             if (
   2089               retainConnection?.(origin, {
   2090                 current: connection.current,
   2091                 close: connection.close
   2092               })
   2093             )
   2094               leased.delete(origin);
   2095           }
   2096           const subscription = sdk
   2097             .req(
   2098               [...targets],
   2099               privateInboxQueries(capture.owner, 'backfill', since, until).map(
   2100                 (filter) => ({
   2101                   ...filter,
   2102                   limit
   2103                 })
   2104               ),
   2105               {
   2106                 waitForAuth: false,
   2107                 reconnect: false,
   2108                 resubscribe: false
   2109               }
   2110             )
   2111             .subscribe({
   2112               next(message) {
   2113                 if (ended) return;
   2114                 if (
   2115                   closed ||
   2116                   !scopeCurrent() ||
   2117                   !capture.current() ||
   2118                   targets.some(
   2119                     (origin) =>
   2120                       authRetiring.has(origin) || authFailed.has(origin)
   2121                   )
   2122                 ) {
   2123                   finish('stale');
   2124                   if (closed || !capture.current()) {
   2125                     try {
   2126                       owner.close();
   2127                     } catch {
   2128                       /* Original session cleanup retains pending/failure. */
   2129                     }
   2130                   }
   2131                   return;
   2132                 }
   2133                 const elapsed = budget.elapsed() + performance.now() - started;
   2134                 if (
   2135                   ended ||
   2136                   closed ||
   2137                   !scopeCurrent() ||
   2138                   !capture.current() ||
   2139                   targets.some(
   2140                     (origin) =>
   2141                       authRetiring.has(origin) || authFailed.has(origin)
   2142                   )
   2143                 ) {
   2144                   if (!ended) finish('stale');
   2145                   if (closed || !capture.current()) {
   2146                     try {
   2147                       owner.close();
   2148                     } catch {
   2149                       /* Original session cleanup retains pending/failure. */
   2150                     }
   2151                   }
   2152                   return;
   2153                 }
   2154                 if (elapsed >= PRIVATE_TRANSPORT_BUDGETS.pageMilliseconds) {
   2155                   finish('elapsed');
   2156                   return;
   2157                 }
   2158                 if (message.type === 'EOSE') {
   2159                   completed.set(message.from, true);
   2160                   if (completed.size === targets.length) finish('complete');
   2161                 } else if (message.type === 'EVENT') {
   2162                   const wire = JSON.stringify(message.event);
   2163                   // Charge actual encoded bytes, including rejected envelopes. An
   2164                   // input beyond the remaining budget stops before encoding it.
   2165                   if (
   2166                     typeof wire !== 'string' ||
   2167                     !boundedUtf8(wire, budget.remainingBytes())
   2168                   ) {
   2169                     finish('budget');
   2170                     return;
   2171                   }
   2172                   if (!budget.charge(new TextEncoder().encode(wire).length)) {
   2173                     finish('budget');
   2174                     return;
   2175                   }
   2176                   const accepted = boundedUtf8(
   2177                     wire,
   2178                     PRIVATE_TRANSPORT_BUDGETS.envelopeBytes
   2179                   );
   2180                   if (accepted)
   2181                     emit({ type: 'candidate', from: message.from, wire });
   2182                 } else if (message.type === 'CLOSED') finish('closed');
   2183                 else if (message.type === 'ERROR') finish('error');
   2184               },
   2185               complete: () => finish('complete'),
   2186               error: () => finish('error')
   2187             });
   2188           release = () => {
   2189             subscription.unsubscribe();
   2190           };
   2191           if (
   2192             ended ||
   2193             closed ||
   2194             !scopeCurrent() ||
   2195             !capture.current() ||
   2196             targets.some(
   2197               (origin) => authRetiring.has(origin) || authFailed.has(origin)
   2198             )
   2199           ) {
   2200             releaseAll();
   2201             if (!ended) finish('stale');
   2202           } else {
   2203             timer = setTimeout(
   2204               () => finish('elapsed'),
   2205               Math.max(
   2206                 0,
   2207                 PRIVATE_TRANSPORT_BUDGETS.pageMilliseconds - budget.elapsed()
   2208               )
   2209             );
   2210           }
   2211         })
   2212         .catch(() => {
   2213           if (!ended) finish('error');
   2214         });
   2215       return () => finish('stopped', true);
   2216     },
   2217     close() {
   2218       if (cleaned) return;
   2219       closed = true;
   2220       let failed = false;
   2221       try {
   2222         liveActive();
   2223       } catch {
   2224         failed = true;
   2225       }
   2226       try {
   2227         active();
   2228       } catch {
   2229         failed = true;
   2230       }
   2231       for (const cleanup of authCleanup.values()) {
   2232         try {
   2233           cleanup();
   2234         } catch {
   2235           failed = true;
   2236         }
   2237       }
   2238       for (const stop of publicationStops.keys()) {
   2239         try {
   2240           stop();
   2241         } catch {
   2242           failed = true;
   2243         }
   2244       }
   2245       for (const connection of connections.values()) {
   2246         try {
   2247           connection.retire();
   2248         } catch {
   2249           failed = true;
   2250         }
   2251       }
   2252       try {
   2253         sdk.close();
   2254       } catch {
   2255         failed = true;
   2256       }
   2257       if (!failed && (authRetiring.size !== 0 || connections.size !== 0))
   2258         throw Error('private_pool_close_pending');
   2259       if (!failed) {
   2260         cleanupRequired = false;
   2261         cleaned = true;
   2262         off();
   2263       }
   2264       if (failed) throw new Error('private_pool_close_failed');
   2265     }
   2266   };
   2267   // Install ownership before observer registration; reentry cannot allocate a
   2268   // second private SDK. A failed close retains this unavailable page lifetime.
   2269   pools.set(token, owner);
   2270   probeRetryIdle.set(
   2271     owner,
   2272     () => !closed && !publishing && !busy && !liveBusy && !owner.unavailable()
   2273   );
   2274   lifetime = owner;
   2275   off = subscribePrivateSessionClose(session, () => owner.close());
   2276   if (!capture.current()) {
   2277     owner.close();
   2278     throw new Error('private_session_invalid');
   2279   }
   2280   return scopedPool(owner, consumer, selectedTargets, role, authorized);
   2281 }
   2282 function ownerOf(token: PrivatePool): Owner {
   2283   const owner = pools.get(token);
   2284   if (!owner) throw new Error('private_pool_invalid');
   2285   return owner;
   2286 }
   2287 
   2288 // Read only the actual lifetime. This does not acquire a scope, invoke a
   2289 // provider, reserve/start a connection or retry another owner's cleanup.
   2290 export function privatePoolProbeRetryIdle(
   2291   session: PrivateSession,
   2292   policy: RelayPolicy
   2293 ): boolean {
   2294   try {
   2295     if (!privateSessionSnapshot(session)?.current) return false;
   2296     readRelayPolicy(policy);
   2297     const original = lifetime;
   2298     if (!original || original.cleaned()) return true;
   2299     return (
   2300       original.session === session &&
   2301       original.policy === policy &&
   2302       !original.closed() &&
   2303       !original.unavailable() &&
   2304       probeRetryIdle.get(original)?.() === true
   2305     );
   2306   } catch {
   2307     return false;
   2308   }
   2309 }
   2310 export function privatePoolOrigins(token: PrivatePool): readonly string[] {
   2311   return [...ownerOf(token).origins];
   2312 }
   2313 export function privatePoolCleanupRequired(token: PrivatePool): boolean {
   2314   return ownerOf(token).unavailable();
   2315 }
   2316 export function subscribePrivatePage(
   2317   token: PrivatePool,
   2318   requested: number,
   2319   listener: (message: PrivatePageMessage) => void
   2320 ): () => void {
   2321   if (
   2322     !Number.isInteger(requested) ||
   2323     requested < 1 ||
   2324     requested > PRIVATE_TRANSPORT_BUDGETS.requestedPerRelay
   2325   )
   2326     throw new Error('private_page_limit_invalid');
   2327   return ownerOf(token).subscribe(requested, listener);
   2328 }
   2329 // Two bounded windows, one actual original pool and shared pre-dedup work meter.
   2330 // Each fresh provider ownership wait is outside cumulative active network time.
   2331 export function subscribePrivateHistory(
   2332   token: PrivatePool,
   2333   since: number,
   2334   listener: (message: PrivatePageMessage) => void
   2335 ): () => void {
   2336   if (!Number.isSafeInteger(since) || since < 0)
   2337     throw Error('private_history_since_invalid');
   2338   const owner = ownerOf(token),
   2339     budget: FiniteBudget = finiteBudget();
   2340   let stopped = false,
   2341     release = () => {};
   2342   function window(overlap: boolean) {
   2343     if (stopped) return;
   2344     try {
   2345       release = owner.subscribe(
   2346         PRIVATE_TRANSPORT_BUDGETS.requestedPerRelay,
   2347         (message) => {
   2348           if (stopped) return;
   2349           if (
   2350             !overlap &&
   2351             message.type === 'end' &&
   2352             message.reason === 'complete'
   2353           ) {
   2354             // finish has released its busy page before notifying this callback.
   2355             queueMicrotask(() => window(true));
   2356           } else listener(message);
   2357         },
   2358         overlap ? since : undefined,
   2359         budget
   2360       );
   2361     } catch {
   2362       listener({ type: 'end', reason: 'error' });
   2363     }
   2364   }
   2365   window(false);
   2366   return () => {
   2367     stopped = true;
   2368     release();
   2369   };
   2370 }
   2371 
   2372 declare const historyRunBrand: unique symbol;
   2373 export type PrivateHistoryRun = Readonly<{ [historyRunBrand]: true }>;
   2374 const historyRuns = new WeakMap<
   2375   PrivateHistoryRun,
   2376   { pool: PrivatePool; budget: FiniteBudget }
   2377 >();
   2378 // Meter only; original pool's current owner/access admission remains mandatory.
   2379 export function createPrivateHistoryRun(pool: PrivatePool): PrivateHistoryRun {
   2380   const owner = ownerOf(pool);
   2381   if (owner.closed()) throw Error('private_pool_closed');
   2382   const token = Object.freeze({}) as PrivateHistoryRun;
   2383   historyRuns.set(token, { pool, budget: finiteBudget() });
   2384   return token;
   2385 }
   2386 export function subscribePrivateSourcePage(
   2387   pool: PrivatePool,
   2388   run: PrivateHistoryRun,
   2389   source: string,
   2390   until: number | undefined,
   2391   listener: (message: PrivatePageMessage) => void
   2392 ): () => void {
   2393   const stored = historyRuns.get(run),
   2394     owner = ownerOf(pool);
   2395   if (
   2396     !stored ||
   2397     stored.pool !== pool ||
   2398     !owner.readOrigins.includes(source) ||
   2399     (until !== undefined && (!Number.isSafeInteger(until) || until < 0))
   2400   )
   2401     throw Error('private_history_scope_invalid');
   2402   return owner.subscribe(
   2403     PRIVATE_TRANSPORT_BUDGETS.requestedPerRelay,
   2404     listener,
   2405     undefined,
   2406     stored.budget,
   2407     until,
   2408     source
   2409   );
   2410 }
   2411 export function closePrivatePool(token: PrivatePool): void {
   2412   ownerOf(token).close();
   2413 }
   2414 export function publishPrivateGiftWrapAttempt(
   2415   pool: PrivatePool,
   2416   permission: PrivatePublication,
   2417   signal: AbortSignal
   2418 ): Promise<PrivateGiftWrapAttemptResult> {
   2419   try {
   2420     if (!privatePublicationSnapshot(permission))
   2421       return Promise.resolve({ status: 'stopped' });
   2422     return ownerOf(pool).publish(
   2423       permission,
   2424       signal
   2425     ) as Promise<PrivateGiftWrapAttemptResult>;
   2426   } catch {
   2427     return Promise.resolve({ status: 'stopped' });
   2428   }
   2429 }
   2430 export function publishInboxProbeArchiveAttempt(
   2431   pool: PrivatePool,
   2432   permission: InboxProbePublication,
   2433   signal: AbortSignal
   2434 ): Promise<InboxProbeArchiveAttemptResult> {
   2435   try {
   2436     if (!inboxProbePublicationSnapshot(permission))
   2437       return Promise.resolve({ status: 'stopped' });
   2438     return ownerOf(pool).publish(
   2439       permission,
   2440       signal
   2441     ) as Promise<InboxProbeArchiveAttemptResult>;
   2442   } catch {
   2443     return Promise.resolve({ status: 'stopped' });
   2444   }
   2445 }
   2446 export function readInboxProbeAttempt(
   2447   pool: PrivatePool,
   2448   permission: InboxProbeReadback,
   2449   signal: AbortSignal
   2450 ): Promise<InboxProbeReadbackAttemptResult> {
   2451   try {
   2452     if (!inboxProbeReadbackSnapshot(permission))
   2453       return Promise.resolve({ status: 'stopped' });
   2454     return ownerOf(pool).readProbe(permission, signal);
   2455   } catch {
   2456     return Promise.resolve({ status: 'stopped' });
   2457   }
   2458 }
   2459 export function beginPrivateAuthConnection(
   2460   pool: PrivatePool,
   2461   origin: string,
   2462   admission: InboxAuthAdmission
   2463 ): Promise<PrivateAuthConnection | undefined> {
   2464   return ownerOf(pool).auth(origin, admission);
   2465 }
   2466 export function privateAuthChallenge(
   2467   connection: PrivateAuthConnection
   2468 ): PrivateAuthChallenge | undefined {
   2469   return authConnections.get(connection)?.challenge();
   2470 }
   2471 export function privateAuthStopped(connection: PrivateAuthConnection): boolean {
   2472   return authConnections.get(connection)?.stopped() ?? true;
   2473 }
   2474 export function reservePrivateAuthResponse(
   2475   connection: PrivateAuthConnection,
   2476   proof: PrivateAuthChallenge
   2477 ): boolean {
   2478   return authConnections.get(connection)?.reserve(proof) ?? false;
   2479 }
   2480 export function sendPrivateAuthResponse(
   2481   connection: PrivateAuthConnection,
   2482   proof: PrivateAuthChallenge,
   2483   response: GuardedInboxAuthResponse
   2484 ) {
   2485   return (
   2486     authConnections.get(connection)?.send(proof, response) ??
   2487     Promise.resolve('stopped' as const)
   2488   );
   2489 }
   2490 export function closePrivateAuthConnection(
   2491   connection: PrivateAuthConnection
   2492 ): void {
   2493   authConnections.get(connection)?.close();
   2494 }
   2495 export function invalidatePrivateAuthGeneration(
   2496   connection: PrivateAuthConnection,
   2497   proof: PrivateAuthChallenge
   2498 ): boolean {
   2499   return authConnections.get(connection)?.invalidate(proof) ?? false;
   2500 }
   2501 
   2502 // One foreground live lane per selected private relay on the original pool.
   2503 export function subscribePrivateLive(
   2504   pool: PrivatePool,
   2505   listener: (message: PrivateLiveMessage) => void
   2506 ): () => void {
   2507   return ownerOf(pool).subscribeLive(listener);
   2508 }