app

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

inbox-probe-recovery.ts (23859B)


      1 import { makeFixture as makeCryptoFixture } from './approved-signing.ts';
      2 import {
      3   createIdentitySession,
      4   connectIdentity,
      5   probeIdentityMessaging,
      6   disconnectIdentity
      7 } from '../../../src/lib/runtime/identity-session.ts';
      8 import {
      9   createPrivateSession,
     10   closePrivateSession
     11 } from '../../../src/lib/runtime/private-session.ts';
     12 import {
     13   createPublicRuntimeContext,
     14   mountPublicRuntime,
     15   closePublicRuntime,
     16   createPublicView,
     17   beginPublicViewRun,
     18   disposePublicView
     19 } from '../../../src/lib/runtime/public-runtime.ts';
     20 import {
     21   resolveInboxPreference,
     22   settleInboxResolver
     23 } from '../../../src/lib/messaging/resolve-inbox.ts';
     24 import {
     25   createInboxAccessController,
     26   closeInboxAccessController
     27 } from '../../../src/lib/messaging/inbox-access-controller.ts';
     28 import {
     29   openBrowserDatabase,
     30   closeBrowserDatabase,
     31   browserDatabaseTransaction
     32 } from '../../../src/lib/persistence/database.ts';
     33 import { createPrivateStorageRepository } from '../../../src/lib/persistence/private-storage.ts';
     34 import {
     35   captureInboxProbeRecoveryReader,
     36   recoverInboxProbe,
     37   recoveredInboxProbeBinding,
     38   stopInboxProbeRecoveryReader,
     39   type InboxProbeRecoveryReader,
     40   type RecoveredInboxProbe
     41 } from '../../../src/lib/nostr/self-recovery-reader.ts';
     42 import {
     43   reserveInboxProbeIdentity,
     44   inboxProbeSnapshot
     45 } from '../../../src/lib/nostr/inbox-access.ts';
     46 import {
     47   captureInboxProbeSealOperation,
     48   buildInboxProbeSeal
     49 } from '../../../src/lib/nostr/seal-builder.ts';
     50 import { buildInboxProbeGiftwrap } from '../../../src/lib/nostr/giftwrap-builder.ts';
     51 import {
     52   commitInboxProbe,
     53   inboxProbeAcknowledgementSnapshot,
     54   commitInboxProbeArchiveAttempt,
     55   commitInboxProbeReadbackAttempt,
     56   type InboxProbeAcknowledgement
     57 } from '../../../src/lib/persistence/inbox-probes.ts';
     58 import {
     59   getPrivatePool,
     60   closePrivatePool,
     61   publishInboxProbeArchiveAttempt,
     62   readInboxProbeAttempt,
     63   type PrivatePool,
     64   type InboxProbeArchiveAttemptResult,
     65   type InboxProbeReadbackAttemptResult
     66 } from '../../../src/lib/nostr/private-pool.ts';
     67 import {
     68   captureInboxProbePublicationAction,
     69   captureInboxProbePublication,
     70   captureInboxProbeReadback,
     71   type InboxProbePublicationAction
     72 } from '../../../src/lib/nostr/private-publisher.ts';
     73 import {
     74   captureInboxProbeNonceReader,
     75   readInboxProbeNonce,
     76   stopInboxProbeNonceReader,
     77   type InboxProbeNonceReader
     78 } from '../../../src/lib/nostr/self-recovery-reader.ts';
     79 import type { InboxProbeIdentity } from '../../../src/lib/nostr/inbox-access.ts';
     80 import type { InboxProbeGiftwrap } from '../../../src/lib/nostr/giftwrap-builder.ts';
     81 import {
     82   readRelayPolicy,
     83   validateRelayPolicy,
     84   type RelayPolicy
     85 } from '../../../src/lib/config/relays.ts';
     86 import {
     87   inboxOperatorQualificationWire,
     88   validateInboxOperatorQualification,
     89   type InboxOperatorQualification
     90 } from '../../../src/lib/config/inbox-operators.ts';
     91 import type { UnsignedEvent } from 'applesauce-core/helpers';
     92 export * from './inbox-probe-nonce.ts';
     93 export {
     94   readRelayPolicy,
     95   validateRelayPolicy,
     96   inboxOperatorQualificationWire,
     97   validateInboxOperatorQualification
     98 };
     99 
    100 // All actors are actual source factories. The emulated extension may outlive a
    101 // product realm, as a real extension does; no secret leaves its test closure.
    102 function createRecoveryPublicScope(policy: RelayPolicy) {
    103   const context = createPublicRuntimeContext(),
    104     runtime = mountPublicRuntime(context, policy);
    105   if (!runtime) throw Error('actual public discovery scope');
    106   return { context, runtime };
    107 }
    108 export async function openRecoveryContext(
    109   owner: string,
    110   policy: RelayPolicy,
    111   operator: InboxOperatorQualification,
    112   localId: string,
    113   shared?: ReturnType<typeof createRecoveryPublicScope>
    114 ) {
    115   const identity = createIdentitySession();
    116   await connectIdentity(identity);
    117   await probeIdentityMessaging(identity, 'reviewed_self_copy');
    118   const session = await createPrivateSession(
    119     identity,
    120     'reviewed_private_session'
    121   );
    122   const opened = await openBrowserDatabase();
    123   if (!session || opened.state !== 'ready')
    124     throw Error('fresh actual recovery actors');
    125   const repository = createPrivateStorageRepository(opened.owner, owner);
    126   if (!repository) throw Error('actual original native namespace');
    127   const { context, runtime } = shared ?? createRecoveryPublicScope(policy);
    128   const view = createPublicView(runtime),
    129     run = beginPublicViewRun(view),
    130     resolver = resolveInboxPreference(view, run, owner);
    131   await settleInboxResolver(resolver);
    132   const access = createInboxAccessController(session, policy, resolver);
    133   if (!access) throw Error('fresh actual recovery controller');
    134   let selected: InboxProbeRecoveryReader | undefined,
    135     proof: RecoveredInboxProbe | undefined;
    136   function capture(
    137     review: unknown = 'reviewed_inbox_probe_recovery',
    138     id: unknown = localId
    139   ) {
    140     return captureInboxProbeRecoveryReader(
    141       repository!,
    142       identity,
    143       session!,
    144       policy,
    145       access!,
    146       operator,
    147       id,
    148       review
    149     );
    150   }
    151   return {
    152     owner,
    153     identity,
    154     session,
    155     repository,
    156     policy,
    157     operator,
    158     access,
    159     localId,
    160     capture,
    161     reader: () => selected,
    162     proof: () => proof,
    163     binding: () =>
    164       proof &&
    165       recoveredInboxProbeBinding(
    166         proof,
    167         repository,
    168         session,
    169         access,
    170         policy,
    171         operator
    172       ),
    173     async recover(reader = (selected ??= capture())) {
    174       if (!reader) return { status: 'invalid' as const };
    175       selected ??= reader;
    176       const result = await recoverInboxProbe(reader);
    177       if ('proof' in result) proof = result.proof;
    178       return result;
    179     },
    180     churnHead: () => beginPublicViewRun(view),
    181     close() {
    182       if (selected) stopInboxProbeRecoveryReader(selected);
    183       closeInboxAccessController(access);
    184       closePrivateSession(session);
    185       disconnectIdentity(identity);
    186       disposePublicView(view);
    187       if (!shared) closePublicRuntime(context);
    188       closeBrowserDatabase(opened.owner);
    189     }
    190   };
    191 }
    192 export async function makeRecoveryFixture() {
    193   const host = createHostedProvider();
    194   const opened = await openBrowserDatabase();
    195   if (opened.state !== 'ready') throw Error('actual original native database');
    196   const database = opened.owner,
    197     repository = createPrivateStorageRepository(database, host.owner);
    198   if (!repository) throw Error('actual original native namespace');
    199   const policy = validateRelayPolicy(
    200     JSON.stringify({
    201       schemaVersion: 1,
    202       public: [
    203         {
    204           origin: 'wss://discovery.example.org',
    205           read: true,
    206           write: true,
    207           nip50: false
    208         }
    209       ],
    210       inbox: [
    211         'wss://inbox.example.org',
    212         'wss://peer.example.org',
    213         'wss://archive.example.org'
    214       ].map((origin) => ({ origin, read: true, write: true })),
    215       postingEnabled: true,
    216       messagingEnabled: true,
    217       operatorDenylist: []
    218     })
    219   );
    220   if (!policy) throw Error('actual fixture policy');
    221   function operator(unsupported = false, unconfigured = false) {
    222     const result = validateInboxOperatorQualification(
    223       JSON.stringify({
    224         schemaVersion: 1,
    225         revision: 1,
    226         authority: unconfigured ? 'unconfigured' : 'source_fixture',
    227         policyWire: JSON.stringify(readRelayPolicy(policy!)),
    228         evidenceSha256: unconfigured ? null : 'a'.repeat(64),
    229         relays: unconfigured
    230           ? []
    231           : readRelayPolicy(policy!).inbox.map(({ origin }) => ({
    232               origin,
    233               auth: 'not_required',
    234               recipientRead: 'supported',
    235               namedArchiveAck: 'supported',
    236               exactReadback: unsupported ? 'unsupported' : 'supported',
    237               retention: 'operator_defined'
    238             }))
    239       })
    240     );
    241     if (!result) throw Error('source-labelled supported operator fixture');
    242     return result;
    243   }
    244   const qualification = operator();
    245   let publicOwner: ReturnType<typeof createRecoveryPublicScope> | undefined,
    246     original: Awaited<ReturnType<typeof openRecoveryContext>> | undefined,
    247     recovery: Awaited<ReturnType<typeof openRecoveryContext>> | undefined;
    248   let originalId: string | undefined;
    249   let probe: InboxProbeIdentity | undefined,
    250     wrap: InboxProbeGiftwrap | undefined,
    251     acknowledgement: InboxProbeAcknowledgement | undefined,
    252     action: InboxProbePublicationAction | undefined,
    253     pool: PrivatePool | undefined,
    254     lastRead: InboxProbeReadbackAttemptResult | undefined,
    255     nonceReader: InboxProbeNonceReader | undefined;
    256   function context() {
    257     if (!original) throw Error('actual original context missing');
    258     return original;
    259   }
    260   function acquire() {
    261     const r = context();
    262     pool ??= getPrivatePool(
    263       r.session,
    264       policy!,
    265       ['wss://inbox.example.org'],
    266       Object.freeze({}),
    267       'access'
    268     );
    269     if (!pool) throw Error('actual original probe pool');
    270     return pool;
    271   }
    272   return {
    273     ...host,
    274     repository,
    275     policy,
    276     qualification,
    277     operator,
    278     get identity() {
    279       return context().identity;
    280     },
    281     get session() {
    282       return context().session;
    283     },
    284     controller: () => original?.access,
    285     probeIdentity: () => probe,
    286     async capture() {
    287       publicOwner ??= createRecoveryPublicScope(policy);
    288       original ??= await openRecoveryContext(
    289         host.owner,
    290         policy,
    291         qualification,
    292         crypto.randomUUID(),
    293         publicOwner
    294       );
    295       return original.access;
    296     },
    297     async reserve() {
    298       const r = context(),
    299         result = await reserveInboxProbeIdentity(
    300           repository,
    301           r.session,
    302           policy,
    303           r.access,
    304           qualification,
    305           'reviewed_inbox_probe_reservation'
    306         );
    307       if ('identity' in result) {
    308         probe = result.identity;
    309         originalId = inboxProbeSnapshot(probe)?.id;
    310         if (!originalId)
    311           throw Error('genuine reserved command metadata missing');
    312       }
    313       return result;
    314     },
    315     async prepare() {
    316       const r = context();
    317       if (!probe) throw Error('actual R0 missing');
    318       const operation = captureInboxProbeSealOperation(
    319         r.session,
    320         probe,
    321         'reviewed_inbox_probe_seal'
    322       );
    323       if (!operation) throw Error('actual seal admission');
    324       const result = await buildInboxProbeSeal(operation);
    325       if (!('seal' in result)) return result.status;
    326       wrap = buildInboxProbeGiftwrap(result.seal, 'reviewed_inbox_probe_wrap');
    327       return wrap ? 'wrapped' : 'invalid';
    328     },
    329     async commitOriginal() {
    330       if (!wrap) throw Error('actual original wrap missing');
    331       const result = await commitInboxProbe(
    332         repository,
    333         context().session,
    334         wrap,
    335         'reviewed_inbox_probe_commit'
    336       );
    337       if ('acknowledgement' in result) acknowledgement = result.acknowledgement;
    338       return result;
    339     },
    340     snapshot: () =>
    341       acknowledgement && inboxProbeAcknowledgementSnapshot(acknowledgement),
    342     async publish() {
    343       const r = context();
    344       if (!acknowledgement) throw Error('actual original ACK missing');
    345       action ??= captureInboxProbePublicationAction(
    346         repository,
    347         r.session,
    348         policy,
    349         acknowledgement,
    350         'reviewed_inbox_probe_network'
    351       );
    352       const permission =
    353         action &&
    354         captureInboxProbePublication(
    355           repository,
    356           r.session,
    357           policy,
    358           acknowledgement,
    359           action,
    360           'wss://inbox.example.org',
    361           'reviewed_inbox_probe_publication'
    362         );
    363       if (!permission) throw Error('actual original PUB admission');
    364       return publishInboxProbeArchiveAttempt(
    365         acquire(),
    366         permission,
    367         new AbortController().signal
    368       );
    369     },
    370     append: (result: InboxProbeArchiveAttemptResult) =>
    371       commitInboxProbeArchiveAttempt(repository, result),
    372     async read() {
    373       const r = context();
    374       if (!acknowledgement || !action)
    375         throw Error('actual original PUB action missing');
    376       const permission = captureInboxProbeReadback(
    377         repository,
    378         r.session,
    379         policy,
    380         acknowledgement,
    381         action,
    382         'wss://inbox.example.org',
    383         'reviewed_inbox_probe_readback'
    384       );
    385       if (!permission) throw Error('actual original read admission');
    386       return (lastRead = await readInboxProbeAttempt(
    387         acquire(),
    388         permission,
    389         new AbortController().signal
    390       ));
    391     },
    392     appendRead: (result: InboxProbeReadbackAttemptResult) =>
    393       commitInboxProbeReadbackAttempt(repository, result),
    394     nonceCapture() {
    395       const r = context();
    396       return (
    397         lastRead &&
    398         captureInboxProbeNonceReader(
    399           repository,
    400           r.identity,
    401           r.session,
    402           policy,
    403           lastRead,
    404           'reviewed_inbox_probe_nonce_decryption'
    405         )
    406       );
    407     },
    408     async nonce() {
    409       const r = context();
    410       nonceReader ??=
    411         lastRead &&
    412         captureInboxProbeNonceReader(
    413           repository,
    414           r.identity,
    415           r.session,
    416           policy,
    417           lastRead,
    418           'reviewed_inbox_probe_nonce_decryption'
    419         );
    420       return nonceReader
    421         ? readInboxProbeNonce(nonceReader)
    422         : { status: 'invalid' as const };
    423     },
    424     nonceReader: () => nonceReader,
    425     foreignRepository() {
    426       const fixture = makeCryptoFixture();
    427       const other = createPrivateStorageRepository(database, fixture.owner);
    428       fixture.close();
    429       if (!other) throw Error('actual other namespace');
    430       return other;
    431     },
    432     copiedPolicy() {
    433       const other = validateRelayPolicy(
    434         JSON.stringify(readRelayPolicy(policy))
    435       );
    436       if (!other) throw Error('actual copied policy');
    437       return other;
    438     },
    439     async stored() {
    440       const tx = browserDatabaseTransaction(
    441           database,
    442           ['private_sends'],
    443           'readonly'
    444         ),
    445         request = tx.objectStore('private_sends').getAll();
    446       return new Promise<{ owner: string; id: string; wire: string }[]>(
    447         (resolve, reject) => {
    448           tx.addEventListener('complete', () =>
    449             resolve(
    450               request.result as { owner: string; id: string; wire: string }[]
    451             )
    452           );
    453           tx.addEventListener('abort', () =>
    454             reject(Error('actual fixture read abort'))
    455           );
    456         }
    457       );
    458     },
    459     async inject(rows: { owner: string; id: string; wire: string }[]) {
    460       const tx = browserDatabaseTransaction(
    461         database,
    462         ['private_sends'],
    463         'readwrite'
    464       );
    465       for (const row of rows) tx.objectStore('private_sends').put(row);
    466       await new Promise<void>((resolve, reject) => {
    467         tx.addEventListener('complete', () => resolve());
    468         tx.addEventListener('abort', () =>
    469           reject(Error('actual fixture write abort'))
    470         );
    471       });
    472     },
    473     async removeOriginal() {
    474       if (!originalId) throw Error('original command metadata missing');
    475       const tx = browserDatabaseTransaction(
    476         database,
    477         ['private_sends'],
    478         'readwrite'
    479       );
    480       tx.objectStore('private_sends').delete([host.owner, originalId]);
    481       await new Promise<void>((resolve, reject) => {
    482         tx.addEventListener('complete', () => resolve());
    483         tx.addEventListener('abort', () =>
    484           reject(Error('actual native deletion abort'))
    485         );
    486       });
    487     },
    488     async fresh() {
    489       // Recovery explicitly permits expired original memory authority. Only the
    490       // original genuine reserved ID survives as inert selection metadata.
    491       if (!originalId) throw Error('original command metadata missing');
    492       const tx = browserDatabaseTransaction(
    493         database,
    494         ['private_sends'],
    495         'readonly'
    496       );
    497       const request = tx
    498         .objectStore('private_sends')
    499         .get([host.owner, originalId]);
    500       const row = await new Promise<unknown>((resolve, reject) => {
    501         tx.addEventListener('complete', () => resolve(request.result));
    502         tx.addEventListener('abort', () =>
    503           reject(Error('actual original selection abort'))
    504         );
    505       });
    506       if (!row) throw Error('stored original selection missing');
    507       if (pool) closePrivatePool(pool);
    508       original!.close();
    509       if (inboxProbeSnapshot(probe!)) throw Error('old nonce still visible');
    510       recovery = await openRecoveryContext(
    511         host.owner,
    512         policy,
    513         qualification,
    514         originalId,
    515         publicOwner
    516       );
    517       return recovery;
    518     },
    519     close() {
    520       if (nonceReader) stopInboxProbeNonceReader(nonceReader);
    521       if (pool) closePrivatePool(pool);
    522       recovery?.close();
    523       original?.close();
    524       if (publicOwner) closePublicRuntime(publicOwner.context);
    525       closeBrowserDatabase(database);
    526       host.close();
    527     }
    528   };
    529 }
    530 
    531 // A parent-realm test extension host supports actual child-frame destruction and
    532 // reload without persisting/exposing its random key. It is controlled evidence,
    533 // not installed-extension or operator qualification.
    534 export function createHostedProvider() {
    535   const cryptoFixture = makeCryptoFixture(10050);
    536   let keys = 0,
    537     signs = 0,
    538     encrypts = 0,
    539     decrypts = 0,
    540     mode:
    541       | 'normal'
    542       | 'hold_key'
    543       | 'hold_decrypt'
    544       | 'wrong_key'
    545       | 'refuse_decrypt'
    546       | 'wrong_decrypt' = 'normal',
    547     waiting = '',
    548     release: (() => void) | undefined;
    549   const restorations = new Map<symbol, () => void>();
    550   function retain(off: () => void) {
    551     const id = Symbol();
    552     restorations.set(id, off);
    553     return () => {
    554       off();
    555       restorations.delete(id);
    556     };
    557   }
    558   async function pause(stage: string) {
    559     if (mode !== 'hold_' + stage) return;
    560     waiting = stage;
    561     await new Promise<void>((resolve) => {
    562       release = resolve;
    563     });
    564     waiting = '';
    565     release = undefined;
    566   }
    567   const cipher = {
    568     encrypt: (target: string, wire: string) => {
    569       encrypts++;
    570       return Promise.resolve(cryptoFixture.encrypt(target, wire));
    571     },
    572     decrypt: async (target: string, wire: string) => {
    573       decrypts++;
    574       await pause('decrypt');
    575       if (mode === 'refuse_decrypt')
    576         throw Error('controlled actual provider refusal');
    577       return mode === 'wrong_decrypt'
    578         ? 'substituted plaintext'
    579         : cryptoFixture.decrypt(target, wire);
    580     }
    581   };
    582   const provider = {
    583     getPublicKey: async () => {
    584       keys++;
    585       await pause('key');
    586       return mode === 'wrong_key' ? 'f'.repeat(64) : cryptoFixture.owner;
    587     },
    588     signEvent: (input: UnsignedEvent) => {
    589       signs++;
    590       return Promise.resolve(cryptoFixture.sign(input));
    591     },
    592     nip44: cipher
    593   };
    594   Object.defineProperty(window, 'nostr', {
    595     configurable: true,
    596     value: provider
    597   });
    598   return {
    599     owner: cryptoFixture.owner,
    600     preferenceWire: (origins: string[]) =>
    601       JSON.stringify(
    602         cryptoFixture.sign({
    603           kind: 10050,
    604           created_at: Math.floor(Date.now() / 1000),
    605           tags: origins.map((origin) => ['relay', origin]),
    606           content: ''
    607         })
    608       ),
    609     head: () =>
    610       JSON.stringify(
    611         cryptoFixture.sign({
    612           kind: 10050,
    613           created_at: Math.floor(Date.now() / 1000),
    614           tags: [['relay', 'wss://inbox.example.org']],
    615           content: ''
    616         })
    617       ),
    618     counts: () => ({ keys, signs, encrypts, decrypts }),
    619     mode: (next: typeof mode) => {
    620       mode = next;
    621     },
    622     waiting: () => waiting,
    623     settle: () => release?.(),
    624     keyCallback(hit: number, callback: () => void | Promise<void>) {
    625       const original = provider.getPublicKey.bind(provider);
    626       let n = 0;
    627       provider.getPublicKey = async () => {
    628         if (++n === hit) await callback();
    629         return original();
    630       };
    631       return retain(() => {
    632         provider.getPublicKey = original;
    633       });
    634     },
    635     cipherGetter(callback: () => void) {
    636       const descriptor = Object.getOwnPropertyDescriptor(provider, 'nip44')!;
    637       Object.defineProperty(provider, 'nip44', {
    638         configurable: true,
    639         get() {
    640           callback();
    641           return cipher;
    642         }
    643       });
    644       return retain(() => {
    645         Object.defineProperty(provider, 'nip44', descriptor);
    646       });
    647     },
    648     decryptCallback(
    649       hit: number,
    650       transform: (wire: string) => string | Promise<string>
    651     ) {
    652       const original = cipher.decrypt.bind(cipher),
    653         descriptor = Object.getOwnPropertyDescriptor(cipher, 'decrypt')!;
    654       let n = 0,
    655         receivers = 0;
    656       Object.defineProperty(cipher, 'decrypt', {
    657         configurable: true,
    658         value: async function (
    659           this: typeof cipher,
    660           target: string,
    661           wire: string
    662         ) {
    663           if (this !== cipher) throw Error('wrong actual SDK cipher receiver');
    664           receivers++;
    665           const opened = await original(target, wire);
    666           return ++n === hit ? transform(opened) : opened;
    667         }
    668       });
    669       return {
    670         receivers: () => receivers,
    671         restore: retain(() => {
    672           Object.defineProperty(cipher, 'decrypt', descriptor);
    673         })
    674       };
    675     },
    676     signSeal(wire: string, change: Record<string, unknown>) {
    677       const seal = JSON.parse(wire) as UnsignedEvent;
    678       return JSON.stringify(
    679         cryptoFixture.sign({
    680           kind: seal.kind,
    681           created_at: seal.created_at,
    682           tags: seal.tags,
    683           content: seal.content,
    684           ...change
    685         })
    686       );
    687     },
    688     close() {
    689       for (const [id, off] of restorations) {
    690         off();
    691         restorations.delete(id);
    692       }
    693       cryptoFixture.close();
    694     }
    695   };
    696 }
    697 
    698 // Extension messages return data in the requesting document's realm. Direct
    699 // parent objects fail the stock SDK's instanceof-Object event admission. Clone
    700 // only the signed public event response; account key custody stays in the host.
    701 export function installHostedProvider() {
    702   type Port = {
    703     getPublicKey(): Promise<string>;
    704     signEvent(input: UnsignedEvent): Promise<Record<string, unknown>>;
    705     nip44: {
    706       encrypt(target: string, wire: string): Promise<string>;
    707       decrypt(target: string, wire: string): Promise<string>;
    708     };
    709   };
    710   const host = Reflect.get(window.parent, 'nostr') as Port;
    711   const cipher = host.nip44;
    712   Object.defineProperty(window, 'nostr', {
    713     configurable: true,
    714     value: {
    715       getPublicKey: host.getPublicKey.bind(host),
    716       signEvent: async (input: UnsignedEvent) => {
    717         const signed = await host.signEvent(input);
    718         return JSON.parse(JSON.stringify(signed)) as Record<string, unknown>;
    719       },
    720       nip44: {
    721         encrypt: cipher.encrypt.bind(cipher),
    722         decrypt: cipher.decrypt.bind(cipher)
    723       }
    724     }
    725   });
    726 }
    727 
    728 export async function prepareHostedOriginal(
    729   context: Awaited<ReturnType<typeof openRecoveryContext>>
    730 ) {
    731   const { repository, session, policy, access, operator } = context;
    732   const reserved = await reserveInboxProbeIdentity(
    733     repository,
    734     session,
    735     policy,
    736     access,
    737     operator,
    738     'reviewed_inbox_probe_reservation'
    739   );
    740   if (!('identity' in reserved)) throw Error('actual hosted R0');
    741   const operation = captureInboxProbeSealOperation(
    742     session,
    743     reserved.identity,
    744     'reviewed_inbox_probe_seal'
    745   );
    746   if (!operation) throw Error('actual hosted seal operation');
    747   const sealed = await buildInboxProbeSeal(operation);
    748   if (!('seal' in sealed)) throw Error('actual hosted seal');
    749   const wrapped = buildInboxProbeGiftwrap(
    750     sealed.seal,
    751     'reviewed_inbox_probe_wrap'
    752   );
    753   if (!wrapped) throw Error('actual hosted wrap');
    754   const committed = await commitInboxProbe(
    755     repository,
    756     session,
    757     wrapped,
    758     'reviewed_inbox_probe_commit'
    759   );
    760   if (!('acknowledgement' in committed)) throw Error('actual hosted native R1');
    761   return inboxProbeAcknowledgementSnapshot(committed.acknowledgement)!.record;
    762 }