app

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

inbox-access-check.ts (30752B)


      1 import type { RelayPolicy } from '../config/relays.ts';
      2 import {
      3   inboxOperatorQualificationSnapshot,
      4   inboxOperatorQualificationWire,
      5   type InboxOperatorQualification
      6 } from '../config/inbox-operators.ts';
      7 import {
      8   identityMessagingOwnership,
      9   type IdentitySession
     10 } from '../runtime/identity-session.ts';
     11 import {
     12   privateSessionOwnership,
     13   subscribePrivateSessionClose,
     14   type PrivateSession
     15 } from '../runtime/private-session.ts';
     16 import {
     17   privateStorageOwner,
     18   type PrivateStorageRepository
     19 } from '../persistence/private-storage.ts';
     20 import { canonicalLocalId } from '../private-handles.ts';
     21 import {
     22   inboxAccessConstructionBinding,
     23   inboxAccessControllerSourceSnapshot,
     24   subscribeInboxAccessControllerClose,
     25   closeInboxAccessController,
     26   type InboxAccessController
     27 } from './inbox-access-controller.ts';
     28 import {
     29   reserveInboxProbeIdentity,
     30   inboxProbeSnapshot,
     31   stopInboxProbeIdentity,
     32   type InboxProbeIdentity
     33 } from '../nostr/inbox-access.ts';
     34 import {
     35   captureInboxProbeSealOperation,
     36   buildInboxProbeSeal,
     37   stopInboxProbeSeal,
     38   type InboxProbeSealOperation
     39 } from '../nostr/seal-builder.ts';
     40 import {
     41   buildInboxProbeGiftwrap,
     42   type InboxProbeGiftwrap
     43 } from '../nostr/giftwrap-builder.ts';
     44 import {
     45   commitInboxProbe,
     46   adoptRecoveredInboxProbe,
     47   commitInboxProbeArchiveAttempt,
     48   commitInboxProbeReadbackAttempt,
     49   commitInboxProbeNonceVerification,
     50   type InboxProbeAcknowledgement,
     51   type InboxProbeNonceAcknowledgement
     52 } from '../persistence/inbox-probes.ts';
     53 import {
     54   captureInboxProbePublicationAction,
     55   captureRecoveredInboxProbeRetryAction,
     56   captureInboxProbePublication,
     57   captureInboxProbeReadback,
     58   type InboxProbePublicationAction
     59 } from '../nostr/private-publisher.ts';
     60 import {
     61   getPrivatePool,
     62   closePrivatePool,
     63   privatePoolCleanupRequired,
     64   publishInboxProbeArchiveAttempt,
     65   readInboxProbeAttempt,
     66   inboxProbeArchiveAttemptEvidence,
     67   inboxProbeReadbackAttemptEvidence,
     68   type PrivatePool,
     69   type InboxProbeArchiveAttemptResult,
     70   type InboxProbeReadbackAttemptResult
     71 } from '../nostr/private-pool.ts';
     72 import {
     73   captureInboxProbeRecoveryReader,
     74   recoverInboxProbe,
     75   stopInboxProbeRecoveryReader,
     76   captureInboxProbeNonceReader,
     77   readInboxProbeNonce,
     78   stopInboxProbeNonceReader,
     79   captureRecoveredInboxProbeNonceReader,
     80   readRecoveredInboxProbeNonce,
     81   stopRecoveredInboxProbeNonceReader,
     82   type InboxProbeRecoveryReader,
     83   type RecoveredInboxProbe,
     84   type InboxProbeNonceReader,
     85   type RecoveredInboxProbeNonceReader,
     86   type InboxProbeNonceProof,
     87   type RecoveredInboxProbeNonceProof
     88 } from '../nostr/self-recovery-reader.ts';
     89 import {
     90   qualifyInboxAccess,
     91   qualifyRemovedInboxAccess,
     92   inboxAccessQualificationSnapshot,
     93   stopInboxAccessQualification,
     94   type InboxAccessQualification
     95 } from './inbox-access-qualification.ts';
     96 import {
     97   captureInboxProbeCleanup,
     98   deleteReviewedInboxProbe,
     99   stopInboxProbeCleanup,
    100   type InboxProbeCleanup,
    101   type InboxProbeRemovalAcknowledgement
    102 } from '../persistence/inbox-probe-cleanup.ts';
    103 
    104 declare const checkBrand: unique symbol;
    105 export type InboxAccessCheck = Readonly<{ [checkBrand]: true }>;
    106 declare const reviewBrand: unique symbol;
    107 export type InboxAccessCheckReview = Readonly<{ [reviewBrand]: true }>;
    108 export type InboxAccessCheckResult = Readonly<{ status: string }>;
    109 type Mode = 'original' | 'recover';
    110 const disclosures = Object.freeze([
    111   'This private inbox diagnostic may appear as a note to self or an extra event in other compatible clients.',
    112   'Relay operators may retain the diagnostic remotely after local removal. Local journal cleanup does not delete remote copies.',
    113   'After journal loss, removal or reload, the diagnostic uses ordinary bounded receive and retention costs and two-layer decryption before authenticated self-message rejection.',
    114   'This check is not an enquiry, reply, delivery receipt or proof that another person or client received a message.'
    115 ]);
    116 type CheckSelection = Readonly<{
    117   kind: 'check';
    118   mode: Mode;
    119   origin: string;
    120   command?: string;
    121 }>;
    122 type Selection = CheckSelection | Readonly<{ kind: 'cleanup' | 'reconcile' }>;
    123 type Snapshot = Readonly<{
    124   state: string;
    125   busy: boolean;
    126   cleanupRequired: boolean;
    127   pendingSettlement: boolean;
    128   sourceOnly: true;
    129   mode?: Mode;
    130   command?: string;
    131   reason: string | null;
    132 }>;
    133 type Control = Readonly<{
    134   repository: PrivateStorageRepository;
    135   identity: IdentitySession;
    136   session: PrivateSession;
    137   policy: RelayPolicy;
    138   operator: InboxOperatorQualification;
    139   current(): boolean;
    140   snapshot(): Snapshot;
    141   select(
    142     mode: unknown,
    143     origin: unknown,
    144     command: unknown
    145   ): InboxAccessCheckReview | undefined;
    146   selectAction(
    147     kind: 'cleanup' | 'reconcile'
    148   ): InboxAccessCheckReview | undefined;
    149   reviewCurrent(selection: Selection): boolean;
    150   run(selection: CheckSelection): Promise<InboxAccessCheckResult>;
    151   cleanup(review: unknown): Promise<InboxAccessCheckResult>;
    152   reconcile(review: unknown): Promise<InboxAccessCheckResult>;
    153   qualification(): InboxAccessQualification | undefined;
    154   stop(): boolean;
    155 }>;
    156 const controls = new WeakMap<InboxAccessCheck, Control>();
    157 const currentChecks = new WeakMap<InboxAccessController, InboxAccessCheck>();
    158 const reviews = new WeakMap<
    159   InboxAccessCheckReview,
    160   Readonly<{
    161     control: Control;
    162     selection: Selection;
    163   }>
    164 >();
    165 function applied(status: string) {
    166   return status === 'saved' || status === 'existing' || status === 'reconciled';
    167 }
    168 
    169 // Capture is source metadata only. Actual C7 association precedes passive
    170 // session observation; this coordinator owns the exact opaque operator binding.
    171 export function createInboxAccessCheck(
    172   repository: PrivateStorageRepository,
    173   identity: IdentitySession,
    174   session: PrivateSession,
    175   policy: RelayPolicy,
    176   access: InboxAccessController,
    177   operator: InboxOperatorQualification
    178 ): InboxAccessCheck | undefined {
    179   if (typeof window === 'undefined') return undefined;
    180   try {
    181     const source = inboxAccessConstructionBinding(access, session, policy);
    182     if (!source || privateStorageOwner(repository) !== source.owner)
    183       return undefined;
    184     const publicOwner = identityMessagingOwnership(identity),
    185       owner = privateSessionOwnership(session),
    186       declaration = inboxOperatorQualificationSnapshot(operator),
    187       operatorWire = inboxOperatorQualificationWire(operator, policy);
    188     if (
    189       !publicOwner?.current() ||
    190       !owner?.current() ||
    191       publicOwner.owner !== source.owner ||
    192       owner.owner !== source.owner ||
    193       publicOwner.session !== source.session ||
    194       owner.session !== source.session ||
    195       !declaration ||
    196       declaration.authority === 'unconfigured' ||
    197       !operatorWire ||
    198       ![...source.readTargets, ...source.archiveTargets].every((origin) => {
    199         const row = declaration.relays.find((row) => row.origin === origin);
    200         return (
    201           row &&
    202           row.auth !== 'unsupported' &&
    203           row.recipientRead === 'supported' &&
    204           row.namedArchiveAck === 'supported' &&
    205           row.exactReadback === 'supported' &&
    206           row.retention === 'operator_defined'
    207         );
    208       })
    209     )
    210       return undefined;
    211     const prior = currentChecks.get(access),
    212       previous = prior && controls.get(prior);
    213     if (previous)
    214       return previous.repository === repository &&
    215         previous.identity === identity &&
    216         previous.session === session &&
    217         previous.policy === policy &&
    218         previous.operator === operator &&
    219         previous.current()
    220         ? prior
    221         : undefined;
    222     const token = Object.freeze({}) as InboxAccessCheck;
    223     const cancellation = new AbortController();
    224     const archive = new Map<string, InboxProbeArchiveAttemptResult>();
    225     const listeners = new Map<symbol, () => void>();
    226     let stopped = false,
    227       busy = false,
    228       cleanupRequired = false,
    229       state = 'not_checked',
    230       reason: string | null = null,
    231       mode: Mode | undefined,
    232       readOrigin: string | undefined,
    233       command: string | undefined,
    234       selectedReview: InboxAccessCheckReview | undefined,
    235       original: InboxProbeIdentity | undefined,
    236       seal: InboxProbeSealOperation | undefined,
    237       wrap: InboxProbeGiftwrap | undefined,
    238       recovery: InboxProbeRecoveryReader | undefined,
    239       recovered: RecoveredInboxProbe | undefined,
    240       acknowledgement: InboxProbeAcknowledgement | undefined,
    241       action: InboxProbePublicationAction | undefined,
    242       pool: PrivatePool | undefined,
    243       pendingArchive:
    244         | Readonly<{ origin: string; result: InboxProbeArchiveAttemptResult }>
    245         | undefined,
    246       pendingRead: InboxProbeReadbackAttemptResult | undefined,
    247       read: InboxProbeReadbackAttemptResult | undefined,
    248       nonceReader: InboxProbeNonceReader | undefined,
    249       recoveredNonceReader: RecoveredInboxProbeNonceReader | undefined,
    250       nonceProof:
    251         InboxProbeNonceProof | RecoveredInboxProbeNonceProof | undefined,
    252       nonce: InboxProbeNonceAcknowledgement | undefined,
    253       qualified: InboxAccessQualification | undefined,
    254       cleanup: InboxProbeCleanup | undefined,
    255       removal: InboxProbeRemovalAcknowledgement | undefined;
    256     function current() {
    257       if (stopped) return false;
    258       const fresh =
    259         source!.current() &&
    260         publicOwner!.current() &&
    261         owner!.current() &&
    262         inboxOperatorQualificationWire(operator, policy) === operatorWire;
    263       if (!fresh && !stopped) {
    264         revoke();
    265         closeOwn();
    266       }
    267       return fresh && !stopped;
    268     }
    269     function qualification() {
    270       return current() &&
    271         !busy &&
    272         !cleanupRequired &&
    273         qualified &&
    274         inboxAccessQualificationSnapshot(qualified)
    275         ? qualified
    276         : undefined;
    277     }
    278     function result(status: string): InboxAccessCheckResult {
    279       reason = status === 'qualified' ? null : status;
    280       state =
    281         stopped || !current()
    282           ? 'stopped'
    283           : status === 'qualified'
    284             ? 'qualified'
    285             : 'needs_action';
    286       return { status };
    287     }
    288     function observeCleanup() {
    289       cleanupRequired =
    290         !!pendingArchive ||
    291         !!pendingRead ||
    292         (!!pool && privatePoolCleanupRequired(pool)) ||
    293         !!inboxAccessControllerSourceSnapshot(access)?.cleanupRequired;
    294       return !cleanupRequired;
    295     }
    296     function revoke() {
    297       stopped = true;
    298       state = 'stopped';
    299       cancellation.abort();
    300       if (selectedReview) reviews.delete(selectedReview);
    301       selectedReview = undefined;
    302       if (qualified) stopInboxAccessQualification(qualified);
    303       qualified = undefined;
    304       if (nonceReader) stopInboxProbeNonceReader(nonceReader);
    305       if (recoveredNonceReader)
    306         stopRecoveredInboxProbeNonceReader(recoveredNonceReader);
    307       if (recovery) stopInboxProbeRecoveryReader(recovery);
    308       if (seal) stopInboxProbeSeal(seal);
    309       if (original) stopInboxProbeIdentity(original);
    310       if (cleanup) stopInboxProbeCleanup(cleanup);
    311     }
    312     function closeOwn() {
    313       let failed = busy;
    314       if (pool) {
    315         try {
    316           closePrivatePool(pool);
    317         } catch {
    318           failed = true;
    319         }
    320         if (privatePoolCleanupRequired(pool)) failed = true;
    321       }
    322       cleanupRequired = failed || !!pendingArchive || !!pendingRead;
    323       if (!cleanupRequired)
    324         for (const [id, off] of listeners) {
    325           off();
    326           listeners.delete(id);
    327         }
    328       return !cleanupRequired;
    329     }
    330     function stop() {
    331       revoke();
    332       const own = closeOwn();
    333       const accessClosed = closeInboxAccessController(access);
    334       cleanupRequired = !own || !accessClosed;
    335       return !cleanupRequired;
    336     }
    337     function sourceClosed() {
    338       revoke();
    339       // The source is already inside its close owner. Calling close() again
    340       // would report its legitimate reentry as a permanent cleanup failure.
    341       if (!closeOwn()) throw Error('inbox_access_check_cleanup_required');
    342     }
    343     async function settle() {
    344       if (pendingArchive) {
    345         const pending = pendingArchive;
    346         // Authentic admitted outcomes must reach the historical append owner
    347         // even after Stop/head/session loss. No new traffic is authorized here.
    348         const saved = await commitInboxProbeArchiveAttempt(
    349           repository,
    350           pending.result
    351         );
    352         if (!applied(saved.status)) return saved.status;
    353         if (pending.result.status === 'accepted')
    354           archive.set(pending.origin, pending.result);
    355         pendingArchive = undefined;
    356       }
    357       if (pendingRead) {
    358         const pending = pendingRead;
    359         const saved = await commitInboxProbeReadbackAttempt(
    360           repository,
    361           pending
    362         );
    363         if (!applied(saved.status)) return saved.status;
    364         read = pending;
    365         pendingRead = undefined;
    366       }
    367       return 'saved';
    368     }
    369     function selectReview(selection: Selection) {
    370       if (selectedReview) reviews.delete(selectedReview);
    371       const review = Object.freeze({}) as InboxAccessCheckReview;
    372       reviews.set(review, { control, selection });
    373       selectedReview = review;
    374       return review;
    375     }
    376     function retryNonceRead(status: string) {
    377       if (status !== 'busy') return;
    378       // A used reader permanently owns its actual read observation. An explicit
    379       // Retry must spend a later real READ under the SAME publication action,
    380       // rather than recapture from that observation or reset any attempt meter.
    381       if (nonceReader) stopInboxProbeNonceReader(nonceReader);
    382       if (recoveredNonceReader)
    383         stopRecoveredInboxProbeNonceReader(recoveredNonceReader);
    384       nonceReader = undefined;
    385       recoveredNonceReader = undefined;
    386       read = undefined;
    387     }
    388     const control: Control = {
    389       repository,
    390       identity,
    391       session,
    392       policy,
    393       operator,
    394       current,
    395       qualification,
    396       stop,
    397       snapshot() {
    398         const fresh = current();
    399         return {
    400           state: !fresh
    401             ? 'stopped'
    402             : qualification()
    403               ? 'qualified'
    404               : state === 'qualified'
    405                 ? 'needs_action'
    406                 : state,
    407           busy,
    408           cleanupRequired,
    409           pendingSettlement: !!pendingArchive || !!pendingRead,
    410           sourceOnly: true,
    411           mode,
    412           command,
    413           reason
    414         };
    415       },
    416       select(selectedMode, origin, selectedCommand) {
    417         if (
    418           !current() ||
    419           busy ||
    420           cleanupRequired ||
    421           (selectedMode !== 'original' && selectedMode !== 'recover') ||
    422           typeof origin !== 'string' ||
    423           !source.readTargets.includes(origin) ||
    424           (readOrigin !== undefined && readOrigin !== origin) ||
    425           (mode && mode !== selectedMode)
    426         )
    427           return undefined;
    428         const id =
    429           selectedMode === 'recover'
    430             ? canonicalLocalId(selectedCommand)
    431             : undefined;
    432         if (
    433           (selectedMode === 'recover' && !id) ||
    434           (selectedMode === 'original' && selectedCommand !== undefined) ||
    435           (command && selectedMode === 'recover' && id !== command)
    436         )
    437           return undefined;
    438         return selectReview({
    439           kind: 'check',
    440           mode: selectedMode,
    441           origin,
    442           command: id
    443         });
    444       },
    445       reviewCurrent(selection) {
    446         if (busy) return false;
    447         // Historical append is allowed only for an authentic already-admitted
    448         // pending result. It neither restores live authority nor issues proof.
    449         if (selection.kind === 'reconcile')
    450           return !!pendingArchive || !!pendingRead;
    451         return current() && !cleanupRequired;
    452       },
    453       selectAction(kind) {
    454         const selection = { kind };
    455         return control.reviewCurrent(selection)
    456           ? selectReview(selection)
    457           : undefined;
    458       },
    459       async reconcile(consent) {
    460         if (consent !== 'reviewed_inbox_access_check_reconciliation')
    461           return { status: 'invalid' };
    462         if (busy) return { status: 'busy' };
    463         busy = true;
    464         try {
    465           const status = await settle();
    466           observeCleanup();
    467           return { status };
    468         } catch {
    469           return { status: 'unknown_completion' };
    470         } finally {
    471           busy = false;
    472         }
    473       },
    474       async run(selection) {
    475         if (!current()) return { status: 'stopped' };
    476         if (busy || cleanupRequired) return { status: 'busy' };
    477         if (qualification()) return { status: 'qualified' };
    478         if (mode && mode !== selection.mode) return { status: 'invalid' };
    479         if (readOrigin !== undefined && readOrigin !== selection.origin)
    480           return { status: 'invalid' };
    481         mode ??= selection.mode;
    482         readOrigin ??= selection.origin;
    483         busy = true;
    484         state = 'working';
    485         try {
    486           const settled = await settle();
    487           if (!current()) return result('stopped');
    488           if (!applied(settled)) return result(settled);
    489           if (!acknowledgement) {
    490             if (mode === 'original') {
    491               if (!original) {
    492                 const reserved = await reserveInboxProbeIdentity(
    493                   repository,
    494                   session,
    495                   policy,
    496                   access,
    497                   operator,
    498                   'reviewed_inbox_probe_reservation'
    499                 );
    500                 if ('identity' in reserved) {
    501                   original = reserved.identity;
    502                   command = inboxProbeSnapshot(original)?.id;
    503                 }
    504                 if (!current()) return result('stopped');
    505                 if (!original) return result(reserved.status);
    506               }
    507               if (!current() || !original) return result('stopped');
    508               if (!wrap) {
    509                 seal ??= captureInboxProbeSealOperation(
    510                   session,
    511                   original,
    512                   'reviewed_inbox_probe_seal'
    513                 );
    514                 if (!seal) return result('unavailable');
    515                 const sealed = await buildInboxProbeSeal(seal);
    516                 if (!current()) return result('stopped');
    517                 if (!('seal' in sealed)) return result(sealed.status);
    518                 wrap = buildInboxProbeGiftwrap(
    519                   sealed.seal,
    520                   'reviewed_inbox_probe_wrap'
    521                 );
    522                 if (!wrap || !current()) return result('stopped');
    523               }
    524               const committed = await commitInboxProbe(
    525                 repository,
    526                 session,
    527                 wrap,
    528                 'reviewed_inbox_probe_commit'
    529               );
    530               if ('acknowledgement' in committed)
    531                 acknowledgement = committed.acknowledgement;
    532               if (!current()) return result('stopped');
    533               if (!acknowledgement) return result(committed.status);
    534             } else {
    535               command ??= selection.command;
    536               if (!recovery)
    537                 recovery = captureInboxProbeRecoveryReader(
    538                   repository,
    539                   identity,
    540                   session,
    541                   policy,
    542                   access,
    543                   operator,
    544                   command,
    545                   'reviewed_inbox_probe_recovery'
    546                 );
    547               if (!recovery) return result('unavailable');
    548               if (!recovered) {
    549                 const found = await recoverInboxProbe(recovery);
    550                 if ('proof' in found) recovered = found.proof;
    551                 if (!current()) return result('stopped');
    552                 if (!recovered) return result(found.status);
    553               }
    554               const adopted = await adoptRecoveredInboxProbe(
    555                 repository,
    556                 session,
    557                 access,
    558                 policy,
    559                 operator,
    560                 recovered,
    561                 'reviewed_original_inbox_probe_retry'
    562               );
    563               if ('acknowledgement' in adopted)
    564                 acknowledgement = adopted.acknowledgement;
    565               if (!current()) return result('stopped');
    566               if (!acknowledgement) return result(adopted.status);
    567             }
    568           }
    569           if (!current()) return result('stopped');
    570           if (!action)
    571             action =
    572               mode === 'original'
    573                 ? captureInboxProbePublicationAction(
    574                     repository,
    575                     session,
    576                     policy,
    577                     acknowledgement,
    578                     'reviewed_inbox_probe_network'
    579                   )
    580                 : await captureRecoveredInboxProbeRetryAction(
    581                     repository,
    582                     session,
    583                     policy,
    584                     acknowledgement,
    585                     'reviewed_original_inbox_probe_retry'
    586                   );
    587           if (!current()) return result('stopped');
    588           if (!action) return result('unavailable');
    589           const targets = new Map<string, true>();
    590           for (const origin of [
    591             ...source.readTargets,
    592             ...source.archiveTargets
    593           ])
    594             targets.set(origin, true);
    595           pool ??= getPrivatePool(
    596             session,
    597             policy,
    598             Array.from(targets.keys()),
    599             token,
    600             'access',
    601             current
    602           );
    603           if (!pool || !current()) return result('stopped');
    604           for (const origin of source.archiveTargets) {
    605             if (!current()) return result('stopped');
    606             if (archive.has(origin)) continue;
    607             const permission = captureInboxProbePublication(
    608               repository,
    609               session,
    610               policy,
    611               acknowledgement,
    612               action,
    613               origin,
    614               'reviewed_inbox_probe_publication'
    615             );
    616             if (!permission) return result('unavailable');
    617             const attempt = await publishInboxProbeArchiveAttempt(
    618               pool,
    619               permission,
    620               cancellation.signal
    621             );
    622             if (inboxProbeArchiveAttemptEvidence(attempt))
    623               pendingArchive = { origin, result: attempt };
    624             const saved = await settle();
    625             if (!current()) return result('stopped');
    626             if (!applied(saved)) return result(saved);
    627             if (attempt.status !== 'accepted' || !archive.has(origin))
    628               return result(attempt.status);
    629           }
    630           if (!read) {
    631             if (!current()) return result('stopped');
    632             const permission = captureInboxProbeReadback(
    633               repository,
    634               session,
    635               policy,
    636               acknowledgement,
    637               action,
    638               selection.origin,
    639               'reviewed_inbox_probe_readback'
    640             );
    641             if (!permission) return result('unavailable');
    642             const attempt = await readInboxProbeAttempt(
    643               pool,
    644               permission,
    645               cancellation.signal
    646             );
    647             if (inboxProbeReadbackAttemptEvidence(attempt))
    648               pendingRead = attempt;
    649             const saved = await settle();
    650             if (!current()) return result('stopped');
    651             if (!applied(saved)) return result(saved);
    652             if (attempt.status !== 'readback' || !read)
    653               return result(attempt.status);
    654           }
    655           if (!nonceProof) {
    656             if (!current()) return result('stopped');
    657             if (mode === 'original') {
    658               nonceReader ??= captureInboxProbeNonceReader(
    659                 repository,
    660                 identity,
    661                 session,
    662                 policy,
    663                 read,
    664                 'reviewed_inbox_probe_nonce_decryption'
    665               );
    666               if (!nonceReader) return result('unavailable');
    667               const decrypted = await readInboxProbeNonce(nonceReader);
    668               if ('proof' in decrypted) nonceProof = decrypted.proof;
    669               if (!current()) return result('stopped');
    670               if (!nonceProof) {
    671                 retryNonceRead(decrypted.status);
    672                 return result(decrypted.status);
    673               }
    674             } else {
    675               recoveredNonceReader ??= captureRecoveredInboxProbeNonceReader(
    676                 repository,
    677                 identity,
    678                 session,
    679                 policy,
    680                 read,
    681                 'reviewed_inbox_probe_nonce_decryption'
    682               );
    683               if (!recoveredNonceReader) return result('unavailable');
    684               const decrypted =
    685                 await readRecoveredInboxProbeNonce(recoveredNonceReader);
    686               if ('proof' in decrypted) nonceProof = decrypted.proof;
    687               if (!current()) return result('stopped');
    688               if (!nonceProof) {
    689                 retryNonceRead(decrypted.status);
    690                 return result(decrypted.status);
    691               }
    692             }
    693           }
    694           if (!nonce) {
    695             if (!current()) return result('stopped');
    696             const saved = await commitInboxProbeNonceVerification(
    697               repository,
    698               session,
    699               policy,
    700               nonceProof
    701             );
    702             if (saved.acknowledgement) nonce = saved.acknowledgement;
    703             if (!current()) return result('stopped');
    704             if (!nonce) return result(saved.status);
    705           }
    706           const issued = await qualifyInboxAccess(
    707             repository,
    708             session,
    709             policy,
    710             access,
    711             operator,
    712             nonce,
    713             [...archive.values(), read],
    714             'reviewed_qualify_inbox_access'
    715           );
    716           if (!current()) {
    717             if (issued.qualification)
    718               stopInboxAccessQualification(issued.qualification);
    719             return result('stopped');
    720           }
    721           if (issued.qualification) qualified = issued.qualification;
    722           return result(issued.status);
    723         } catch {
    724           return result(current() ? 'unknown_completion' : 'stopped');
    725         } finally {
    726           busy = false;
    727           if (stopped) observeCleanup();
    728         }
    729       },
    730       async cleanup(consent) {
    731         if (consent !== 'reviewed_delete_local_inbox_probe')
    732           return { status: 'invalid' };
    733         if (!current()) return { status: 'stopped' };
    734         if (busy || cleanupRequired) return { status: 'busy' };
    735         if (removal) return { status: 'removed' };
    736         if (!nonce || !read) return { status: 'unavailable' };
    737         busy = true;
    738         try {
    739           cleanup = await captureInboxProbeCleanup(
    740             repository,
    741             session,
    742             policy,
    743             nonce,
    744             [...archive.values(), read],
    745             'reviewed_inbox_probe_cleanup_selection'
    746           );
    747           if (!cleanup || !current()) return result('unavailable');
    748           const deleted = await deleteReviewedInboxProbe(cleanup, consent);
    749           // A real claim invalidates the prior journal proof even on abort.
    750           if (qualified && !inboxAccessQualificationSnapshot(qualified))
    751             qualified = undefined;
    752           if (deleted.acknowledgement) removal = deleted.acknowledgement;
    753           if (!current()) return result('stopped');
    754           if (!removal) return result(deleted.status);
    755           const issued = qualifyRemovedInboxAccess(
    756             repository,
    757             session,
    758             policy,
    759             access,
    760             operator,
    761             removal,
    762             'reviewed_qualify_inbox_access'
    763           );
    764           if (issued.qualification) qualified = issued.qualification;
    765           return result(
    766             issued.status === 'qualified' ? 'removed' : issued.status
    767           );
    768         } catch {
    769           return result('unknown_completion');
    770         } finally {
    771           busy = false;
    772         }
    773       }
    774     };
    775     controls.set(token, control);
    776     currentChecks.set(access, token);
    777     listeners.set(
    778       Symbol(),
    779       subscribeInboxAccessControllerClose(access, sourceClosed)
    780     );
    781     listeners.set(
    782       Symbol(),
    783       subscribePrivateSessionClose(session, sourceClosed)
    784     );
    785     if (!current()) {
    786       stop();
    787       return undefined;
    788     }
    789     return token;
    790   } catch {
    791     return undefined;
    792   }
    793 }
    794 
    795 export function inboxAccessCheckSnapshot(token: InboxAccessCheck) {
    796   return controls.get(token)?.snapshot();
    797 }
    798 export function inboxAccessCheckQualification(token: InboxAccessCheck) {
    799   return controls.get(token)?.qualification();
    800 }
    801 export function reviewInboxAccessCheck(
    802   token: InboxAccessCheck,
    803   mode: unknown,
    804   origin: unknown,
    805   command?: unknown
    806 ) {
    807   return controls.get(token)?.select(mode, origin, command);
    808 }
    809 export function inboxAccessCheckReviewSnapshot(token: InboxAccessCheckReview) {
    810   const saved = reviews.get(token);
    811   return saved?.control.reviewCurrent(saved.selection)
    812     ? { ...saved.selection, disclosures: disclosures.slice(), sourceOnly: true }
    813     : undefined;
    814 }
    815 export function runInboxAccessCheck(
    816   token: InboxAccessCheckReview,
    817   review: unknown
    818 ): Promise<InboxAccessCheckResult> {
    819   const saved = reviews.get(token);
    820   if (
    821     !saved ||
    822     saved.selection.kind !== 'check' ||
    823     review !== 'reviewed_inbox_access_check'
    824   )
    825     return Promise.resolve({ status: 'invalid' });
    826   reviews.delete(token);
    827   return saved.control.run(saved.selection);
    828 }
    829 export function cleanupInboxAccessCheck(
    830   token: InboxAccessCheckReview,
    831   review: unknown
    832 ): Promise<InboxAccessCheckResult> {
    833   const saved = reviews.get(token);
    834   if (
    835     !saved ||
    836     saved.selection.kind !== 'cleanup' ||
    837     review !== 'reviewed_delete_local_inbox_probe'
    838   )
    839     return Promise.resolve({ status: 'invalid' });
    840   reviews.delete(token);
    841   return saved.control.cleanup(review);
    842 }
    843 export function reviewInboxAccessCheckCleanup(token: InboxAccessCheck) {
    844   return controls.get(token)?.selectAction('cleanup');
    845 }
    846 export function reviewInboxAccessCheckReconciliation(token: InboxAccessCheck) {
    847   return controls.get(token)?.selectAction('reconcile');
    848 }
    849 export function reconcileInboxAccessCheck(
    850   token: InboxAccessCheckReview,
    851   review: unknown
    852 ): Promise<InboxAccessCheckResult> {
    853   const saved = reviews.get(token);
    854   if (
    855     !saved ||
    856     saved.selection.kind !== 'reconcile' ||
    857     review !== 'reviewed_inbox_access_check_reconciliation'
    858   )
    859     return Promise.resolve({ status: 'invalid' });
    860   reviews.delete(token);
    861   return saved.control.reconcile(review);
    862 }
    863 export function stopInboxAccessCheck(token: InboxAccessCheck): boolean {
    864   return controls.get(token)?.stop() ?? false;
    865 }
    866 export function retryInboxAccessCheckCleanup(
    867   token: InboxAccessCheck,
    868   review: unknown
    869 ): boolean {
    870   return (
    871     review === 'reviewed_inbox_access_check_cleanup_retry' &&
    872     (controls.get(token)?.stop() ?? false)
    873   );
    874 }