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 (21408B)


      1 import { makeRetryFixture } from './inbox-probe-retry.ts';
      2 import { makeFixture as makeCheckCryptoFixture } from './approved-signing.ts';
      3 import {
      4   withIdlePrivateLocalStorage,
      5   createPrivateSession,
      6   closePrivateSession,
      7   type PrivateSession
      8 } from '../../../src/lib/runtime/private-session.ts';
      9 import {
     10   createIdentitySession,
     11   connectIdentity,
     12   probeIdentityMessaging,
     13   disconnectIdentity
     14 } from '../../../src/lib/runtime/identity-session.ts';
     15 import {
     16   installHostedProvider,
     17   openRecoveryContext,
     18   validateRelayPolicy,
     19   validateInboxOperatorQualification
     20 } from './inbox-probe-recovery.ts';
     21 import { inboxOperatorQualificationSnapshot } from '../../../src/lib/config/inbox-operators.ts';
     22 import {
     23   createPublicView,
     24   beginPublicViewRun,
     25   disposePublicView
     26 } from '../../../src/lib/runtime/public-runtime.ts';
     27 import {
     28   resolveInboxPreference,
     29   settleInboxResolver
     30 } from '../../../src/lib/messaging/resolve-inbox.ts';
     31 import { captureUnlockedSession } from '../../../src/lib/messaging/unlocked-session.ts';
     32 import {
     33   captureInboxSync,
     34   startInboxSync,
     35   stopInboxSync,
     36   inboxSyncSnapshot,
     37   type InboxSync
     38 } from '../../../src/lib/messaging/inbox-sync.ts';
     39 import { observeQualifiedInboxAccess } from '../../../src/lib/messaging/inbox-access-qualification.ts';
     40 import {
     41   openBrowserDatabase,
     42   closeBrowserDatabase,
     43   browserDatabaseTransaction
     44 } from '../../../src/lib/persistence/database.ts';
     45 import {
     46   captureDecryptionQueue,
     47   runDecryptionBatch,
     48   decryptionQueueSnapshot,
     49   decryptionQueueConversations,
     50   stopDecryptionQueue
     51 } from '../../../src/lib/messaging/decryption-queue.ts';
     52 import {
     53   createInboxAccessCheck,
     54   inboxAccessCheckSnapshot,
     55   inboxAccessCheckQualification,
     56   inboxAccessCheckReviewSnapshot,
     57   reviewInboxAccessCheck,
     58   runInboxAccessCheck,
     59   cleanupInboxAccessCheck,
     60   reviewInboxAccessCheckCleanup,
     61   reviewInboxAccessCheckReconciliation,
     62   reconcileInboxAccessCheck,
     63   stopInboxAccessCheck,
     64   retryInboxAccessCheckCleanup,
     65   type InboxAccessCheck,
     66   type InboxAccessCheckReview
     67 } from '../../../src/lib/messaging/inbox-access-check.ts';
     68 import {
     69   createInboxAccessController,
     70   closeInboxAccessController
     71 } from '../../../src/lib/messaging/inbox-access-controller.ts';
     72 export * from '../../../src/lib/messaging/inbox-access-check.ts';
     73 export * from '../../../src/lib/messaging/inbox-access-controller.ts';
     74 export * from '../../../src/lib/messaging/inbox-access-qualification.ts';
     75 export * from './inbox-probe-retry.ts';
     76 export { decodePrivateRecord } from '../../../src/lib/persistence/private-records.ts';
     77 export function otherCheckOwner() {
     78   const fixture = makeCheckCryptoFixture();
     79   try {
     80     return fixture.owner;
     81   } finally {
     82     fixture.close();
     83   }
     84 }
     85 export async function makeCheckFixture(authRequired = false) {
     86   // Only inert host/context setup and open() are reused. The new coordinator
     87   // must perform every preparation, network, nonce and qualification step.
     88   const base = await makeRetryFixture();
     89   if (authRequired) {
     90     const wire = inboxOperatorQualificationSnapshot(base.host.qualification)!;
     91     const operator = validateInboxOperatorQualification(
     92       JSON.stringify({
     93         ...wire,
     94         relays: wire.relays.map((relay) =>
     95           relay.origin === 'wss://inbox.example.org'
     96             ? { ...relay, auth: 'explicit_required' }
     97             : relay
     98         )
     99       })
    100     );
    101     if (!operator) throw Error('actual explicit AUTH operator declaration');
    102     base.host.qualification = operator;
    103   }
    104   let check: InboxAccessCheck | undefined;
    105   let selected: InboxAccessCheckReview | undefined;
    106   let sync: InboxSync | undefined;
    107   const views: ReturnType<typeof createPublicView>[] = [];
    108   const alternates = new Set<() => boolean>();
    109   return {
    110     ...base,
    111     check: () => check,
    112     review: () => selected,
    113     async open() {
    114       await base.open();
    115       const a = base.actors();
    116       check = createInboxAccessCheck(
    117         base.repository,
    118         a.identity,
    119         a.session,
    120         base.host.policy,
    121         a.access,
    122         base.host.qualification
    123       );
    124       if (!check) throw Error('actual source check capture');
    125     },
    126     snapshot: () => check && inboxAccessCheckSnapshot(check),
    127     qualification: () => check && inboxAccessCheckQualification(check),
    128     async alternateActors() {
    129       const identity = createIdentitySession();
    130       await connectIdentity(identity);
    131       await probeIdentityMessaging(identity, 'reviewed_self_copy');
    132       const session = await createPrivateSession(
    133         identity,
    134         'reviewed_private_session'
    135       );
    136       if (!session) throw Error('actual alternate private session missing');
    137       const view = createPublicView(base.sharedPublicRuntime());
    138       const resolver = resolveInboxPreference(
    139         view,
    140         beginPublicViewRun(view),
    141         base.host.owner
    142       );
    143       await settleInboxResolver(resolver);
    144       const access = createInboxAccessController(
    145         session,
    146         base.host.policy,
    147         resolver
    148       );
    149       if (!access) throw Error('actual alternate C7 missing');
    150       function close() {
    151         const c7 = closeInboxAccessController(access!);
    152         const actor = closePrivateSession(session!);
    153         disconnectIdentity(identity);
    154         disposePublicView(view);
    155         if (c7 && actor) alternates.delete(close);
    156         return c7 && actor;
    157       }
    158       alternates.add(close);
    159       return { identity, session, access, close };
    160     },
    161     async startOwnInbox() {
    162       const qualified = check && inboxAccessCheckQualification(check);
    163       if (!qualified) throw Error('actual coordinator qualification missing');
    164       const a = base.actors(),
    165         view = createPublicView(base.sharedPublicRuntime());
    166       views.push(view);
    167       const resolver = resolveInboxPreference(
    168         view,
    169         beginPublicViewRun(view),
    170         base.host.owner
    171       );
    172       await settleInboxResolver(resolver);
    173       const unlocked = captureUnlockedSession(
    174         a.session,
    175         'reviewed_messages_unlock'
    176       );
    177       if (!unlocked) throw Error('actual unlocked scope missing');
    178       sync = captureInboxSync(
    179         base.repository,
    180         a.session,
    181         base.host.policy,
    182         resolver,
    183         unlocked,
    184         observeQualifiedInboxAccess(qualified),
    185         'reviewed_foreground_inbox'
    186       );
    187       return !!sync && startInboxSync(sync, 'reviewed_foreground_inbox');
    188     },
    189     syncSnapshot: () => sync && inboxSyncSnapshot(sync),
    190     stopOwnInbox: () => {
    191       if (sync) stopInboxSync(sync);
    192     },
    193     async decryptReceived() {
    194       const a = base.actors(),
    195         unlocked = captureUnlockedSession(
    196           a.session,
    197           'reviewed_messages_unlock'
    198         );
    199       if (!unlocked) throw Error('actual explicit unlock missing');
    200       const queue = captureDecryptionQueue(
    201         base.repository,
    202         a.session,
    203         a.identity,
    204         unlocked,
    205         'reviewed_inbox_unlock'
    206       );
    207       if (!queue) throw Error('actual decryption queue missing');
    208       try {
    209         const result = await runDecryptionBatch(
    210           queue,
    211           'reviewed_decrypt_batch',
    212           []
    213         );
    214         return {
    215           result,
    216           snapshot: decryptionQueueSnapshot(queue),
    217           rooms: decryptionQueueConversations(queue).length
    218         };
    219       } finally {
    220         stopDecryptionQueue(queue);
    221       }
    222     },
    223     async replaceCheck(freshSession = false) {
    224       if (freshSession) await base.freshSession();
    225       else await base.replaceController();
    226       const a = base.actors();
    227       check = createInboxAccessCheck(
    228         base.repository,
    229         a.identity,
    230         a.session,
    231         base.host.policy,
    232         a.access,
    233         base.host.qualification
    234       );
    235       if (!check) throw Error('actual replacement check capture');
    236       selected = undefined;
    237     },
    238     select(
    239       mode: unknown = 'original',
    240       origin: unknown = 'wss://inbox.example.org',
    241       id?: unknown
    242     ) {
    243       if (!check) throw Error('actual coordinator missing');
    244       selected = reviewInboxAccessCheck(check, mode, origin, id);
    245       return selected && inboxAccessCheckReviewSnapshot(selected);
    246     },
    247     run(review: unknown = 'reviewed_inbox_access_check') {
    248       if (!selected) throw Error('actual source review missing');
    249       return runInboxAccessCheck(selected, review);
    250     },
    251     cleanup(review: unknown = 'reviewed_delete_local_inbox_probe') {
    252       if (!selected) throw Error('actual cleanup review missing');
    253       return cleanupInboxAccessCheck(selected, review);
    254     },
    255     selectCleanup() {
    256       if (!check) throw Error('actual coordinator missing');
    257       selected = reviewInboxAccessCheckCleanup(check);
    258       return selected && inboxAccessCheckReviewSnapshot(selected);
    259     },
    260     selectReconciliation() {
    261       if (!check) throw Error('actual coordinator missing');
    262       selected = reviewInboxAccessCheckReconciliation(check);
    263       return selected && inboxAccessCheckReviewSnapshot(selected);
    264     },
    265     reconcile(review: unknown = 'reviewed_inbox_access_check_reconciliation') {
    266       if (!selected) throw Error('actual reconciliation review missing');
    267       return reconcileInboxAccessCheck(selected, review);
    268     },
    269     stop: () => !!check && stopInboxAccessCheck(check),
    270     retryCleanup: () =>
    271       !!check &&
    272       retryInboxAccessCheckCleanup(
    273         check,
    274         'reviewed_inbox_access_check_cleanup_retry'
    275       ),
    276     close() {
    277       let failedAlternate = false;
    278       for (const close of alternates) if (!close()) failedAlternate = true;
    279       if (failedAlternate) throw Error('private_auth_cleanup_required');
    280       if (sync) stopInboxSync(sync);
    281       for (const view of views) disposePublicView(view);
    282       if (check && !stopInboxAccessCheck(check))
    283         throw Error('inbox_access_check_cleanup_required');
    284       base.close();
    285     }
    286   };
    287 }
    288 
    289 export function checkNativeLoss(
    290   phase: 'append' | 'nonce' | 'qualification',
    291   lose: () => void
    292 ) {
    293   const cursor = Object.getOwnPropertyDescriptor(
    294     IDBIndex.prototype,
    295     'openCursor'
    296   )!.value as IDBIndex['openCursor'];
    297   const put = Object.getOwnPropertyDescriptor(IDBObjectStore.prototype, 'put')!
    298     .value as IDBObjectStore['put'];
    299   let hits = 0;
    300   const nonce =
    301     phase === 'nonce'
    302       ? atCheckNonce(async () => {
    303           armed = true;
    304           await Promise.resolve();
    305         })
    306       : undefined;
    307   let armed = false;
    308   const lockRequest = Object.getOwnPropertyDescriptor(
    309     LockManager.prototype,
    310     'request'
    311   )!.value as LockManager['request'];
    312   if (phase === 'qualification') {
    313     navigator.locks.request = function (
    314       this: LockManager,
    315       ...args: Parameters<LockManager['request']>
    316     ) {
    317       // Observe the REAL qualification owner's lock admission; native event
    318       // callbacks intentionally do not retain their original async call stack.
    319       if (/qualifyInboxAccess/.test(new Error().stack ?? '')) armed = true;
    320       return lockRequest.apply(this, args);
    321     } as LockManager['request'];
    322   }
    323   IDBIndex.prototype.openCursor = function (
    324     ...args: Parameters<IDBIndex['openCursor']>
    325   ) {
    326     const request = cursor.apply(this, args);
    327     if (
    328       this.objectStore.name === 'private_sends' &&
    329       this.objectStore.transaction.mode === 'readonly' &&
    330       ((phase === 'nonce' && armed) || (phase === 'qualification' && armed))
    331     ) {
    332       request.addEventListener('success', () => {
    333         if (!hits && !request.result) {
    334           hits++;
    335           lose();
    336         }
    337       });
    338     }
    339     return request;
    340   };
    341   IDBObjectStore.prototype.put = function (
    342     ...args: Parameters<IDBObjectStore['put']>
    343   ) {
    344     const request = put.apply(this, args);
    345     const value = args[0] as { wire?: unknown };
    346     if (
    347       !hits &&
    348       phase === 'append' &&
    349       this.name === 'private_sends' &&
    350       typeof value?.wire === 'string'
    351     ) {
    352       const record = JSON.parse(value.wire) as {
    353         family?: string;
    354         receipts?: { role: string }[];
    355       };
    356       if (
    357         record.family === 'private_access_probe' &&
    358         record.receipts?.at(-1)?.role === 'access_archive'
    359       ) {
    360         request.addEventListener('success', () => {
    361           if (!hits) {
    362             hits++;
    363             lose();
    364           }
    365         });
    366       }
    367     }
    368     return request;
    369   };
    370   return {
    371     hits: () => hits,
    372     restore() {
    373       nonce?.restore();
    374       if (phase === 'qualification') navigator.locks.request = lockRequest;
    375       IDBIndex.prototype.openCursor = cursor;
    376       IDBObjectStore.prototype.put = put;
    377     }
    378   };
    379 }
    380 
    381 export function failCheckPreparationNative(
    382   phase: 'R0' | 'R1',
    383   mode: 'abort' | 'readback' | 'uncertain_readback'
    384 ) {
    385   const put = Object.getOwnPropertyDescriptor(IDBObjectStore.prototype, 'put')!
    386     .value as IDBObjectStore['put'];
    387   const abort = Object.getOwnPropertyDescriptor(
    388     IDBTransaction.prototype,
    389     'abort'
    390   )!.value as IDBTransaction['abort'];
    391   const cursor = Object.getOwnPropertyDescriptor(
    392     IDBIndex.prototype,
    393     'openCursor'
    394   )!.value as IDBIndex['openCursor'];
    395   let selected: IDBTransaction | undefined,
    396     candidate: { owner: string; id: string; wire: string } | undefined;
    397   let puts = 0,
    398     completes = 0,
    399     aborts = 0,
    400     abortRefusals = 0,
    401     readbackAborts = 0;
    402   IDBObjectStore.prototype.put = function (
    403     ...args: Parameters<IDBObjectStore['put']>
    404   ) {
    405     const request = put.apply(this, args),
    406       value = args[0] as { owner?: unknown; id?: unknown; wire?: unknown };
    407     if (
    408       !selected &&
    409       this.name === 'private_sends' &&
    410       typeof value?.wire === 'string'
    411     ) {
    412       const record = JSON.parse(value.wire) as {
    413         family?: string;
    414         self?: unknown;
    415         receipts?: unknown[];
    416       };
    417       if (
    418         record.family === 'private_access_probe' &&
    419         record.receipts?.length === 0 &&
    420         (phase === 'R0' ? record.self === null : record.self !== null)
    421       ) {
    422         if (typeof value.owner !== 'string' || typeof value.id !== 'string')
    423           throw Error('actual native preparation identity missing');
    424         candidate = { owner: value.owner, id: value.id, wire: value.wire };
    425         selected = this.transaction;
    426         selected.addEventListener('complete', () => {
    427           completes++;
    428         });
    429         selected.addEventListener('abort', () => {
    430           aborts++;
    431         });
    432         request.addEventListener('success', () => {
    433           puts++;
    434           if (mode === 'abort') selected!.abort();
    435         });
    436         if (mode === 'uncertain_readback')
    437           throw Error('actual admitted native write uncertainty');
    438       }
    439     }
    440     return request;
    441   };
    442   IDBTransaction.prototype.abort = function (
    443     ...args: Parameters<IDBTransaction['abort']>
    444   ) {
    445     if (this === selected && mode === 'uncertain_readback') {
    446       abortRefusals++;
    447       throw Error('actual admitted native abort refusal');
    448     }
    449     return abort.apply(this, args);
    450   };
    451   IDBIndex.prototype.openCursor = function (
    452     ...args: Parameters<IDBIndex['openCursor']>
    453   ) {
    454     const request = cursor.apply(this, args);
    455     if (
    456       mode !== 'abort' &&
    457       puts &&
    458       !readbackAborts &&
    459       this.objectStore.name === 'private_sends' &&
    460       this.objectStore.transaction.mode === 'readonly'
    461     ) {
    462       readbackAborts++;
    463       this.objectStore.transaction.abort();
    464     }
    465     return request;
    466   };
    467   return {
    468     counts: () => ({ puts, completes, aborts, abortRefusals, readbackAborts }),
    469     candidate: () => candidate,
    470     restore() {
    471       IDBObjectStore.prototype.put = put;
    472       IDBTransaction.prototype.abort = abort;
    473       IDBIndex.prototype.openCursor = cursor;
    474     }
    475   };
    476 }
    477 
    478 export function atCheckNonce(work: () => Promise<void>) {
    479   const original = Object.getOwnPropertyDescriptor(
    480     LockManager.prototype,
    481     'request'
    482   )!.value as LockManager['request'];
    483   let hits = 0;
    484   navigator.locks.request = async function (
    485     this: LockManager,
    486     ...args: Parameters<LockManager['request']>
    487   ) {
    488     if (
    489       !hits &&
    490       /read(?:Recovered)?InboxProbeNonce/.test(new Error().stack ?? '')
    491     ) {
    492       hits++;
    493       await work();
    494     }
    495     return original.apply(this, args);
    496   } as LockManager['request'];
    497   return {
    498     hits: () => hits,
    499     restore: () => {
    500       navigator.locks.request = original;
    501     }
    502   };
    503 }
    504 
    505 export async function changeCheckNativeRow(
    506   row: { owner: string; id: string; wire: string },
    507   mode: 'missing' | 'corrupt' | 'alias' | 'foreign'
    508 ) {
    509   const opened = await openBrowserDatabase();
    510   if (opened.state !== 'ready')
    511     throw Error('actual mutation database unavailable');
    512   try {
    513     const tx = browserDatabaseTransaction(
    514         opened.owner,
    515         ['private_sends'],
    516         'readwrite'
    517       ),
    518       store = tx.objectStore('private_sends');
    519     if (mode === 'missing') store.delete([row.owner, row.id]);
    520     else if (mode === 'corrupt') store.put({ ...row, wire: row.wire + 'x' });
    521     else if (mode === 'alias') store.put({ ...row, id: crypto.randomUUID() });
    522     else
    523       store.put({
    524         ...row,
    525         owner: row.owner === 'f'.repeat(64) ? 'e'.repeat(64) : 'f'.repeat(64)
    526       });
    527     await new Promise<void>((resolve, reject) => {
    528       tx.addEventListener('complete', () => resolve());
    529       tx.addEventListener('abort', () =>
    530         reject(Error('actual fixture mutation aborted'))
    531       );
    532     });
    533   } finally {
    534     closeBrowserDatabase(opened.owner);
    535   }
    536 }
    537 
    538 export function abortCheckCleanup() {
    539   const remove = Object.getOwnPropertyDescriptor(
    540     IDBObjectStore.prototype,
    541     'delete'
    542   )!.value as IDBObjectStore['delete'];
    543   let aborts = 0,
    544     selected = false;
    545   IDBObjectStore.prototype.delete = function (
    546     ...args: Parameters<IDBObjectStore['delete']>
    547   ) {
    548     const request = remove.apply(this, args);
    549     if (!selected && this.name === 'private_sends') {
    550       selected = true;
    551       const tx = this.transaction;
    552       tx.addEventListener('abort', () => {
    553         aborts++;
    554       });
    555       request.addEventListener('success', () => tx.abort());
    556     }
    557     return request;
    558   };
    559   return {
    560     aborts: () => aborts,
    561     restore: () => {
    562       IDBObjectStore.prototype.delete = remove;
    563     }
    564   };
    565 }
    566 
    567 // Hold an ACTUAL competing owner WebLock only when the real nonce reader first
    568 // requests admission. No callback receives a fabricated lock or idle result.
    569 export function holdCheckNonceOwnerLock(holds: 1 | 2 = 1) {
    570   return holdCheckNonceAdmission(undefined, holds);
    571 }
    572 export async function holdCheckOwnerLock(owner: string) {
    573   let release = () => {},
    574     enter = () => {};
    575   const entered = new Promise<void>((resolve) => {
    576     enter = resolve;
    577   });
    578   const held = navigator.locks.request(
    579     'harvestcircle:owner:' + owner,
    580     async (lock) => {
    581       if (!lock) throw Error('actual fixture owner lock missing');
    582       enter();
    583       await new Promise<void>((resolve) => {
    584         release = resolve;
    585       });
    586     }
    587   );
    588   await entered;
    589   return async () => {
    590     release();
    591     await held;
    592   };
    593 }
    594 export function holdCheckNonceSdk(session: PrivateSession, holds: 1 | 2 = 1) {
    595   return holdCheckNonceAdmission(session, holds);
    596 }
    597 function holdCheckNonceAdmission(
    598   session: PrivateSession | undefined,
    599   holds: 1 | 2
    600 ) {
    601   const original = Object.getOwnPropertyDescriptor(
    602     LockManager.prototype,
    603     'request'
    604   )!.value as LockManager['request'];
    605   let release: (() => void) | undefined,
    606     holder: Promise<unknown> | undefined,
    607     hits = 0;
    608   navigator.locks.request = async function (
    609     this: LockManager,
    610     ...args: Parameters<LockManager['request']>
    611   ) {
    612     if (
    613       hits < holds &&
    614       /read(?:Recovered)?InboxProbeNonce/.test(new Error().stack ?? '')
    615     ) {
    616       hits++;
    617       await new Promise<void>((ready) => {
    618         if (session) {
    619           holder = withIdlePrivateLocalStorage(session, async () => {
    620             ready();
    621             await new Promise<void>((resolve) => {
    622               release = resolve;
    623             });
    624           });
    625           return;
    626         }
    627         holder = original.call(
    628           this,
    629           args[0],
    630           { mode: 'exclusive' },
    631           async (lock) => {
    632             if (!lock) throw Error('actual nonce-stage competing lock missing');
    633             ready();
    634             await new Promise<void>((resolve) => {
    635               release = resolve;
    636             });
    637           }
    638         );
    639       });
    640     }
    641     return original.apply(this, args);
    642   } as LockManager['request'];
    643   return {
    644     hits: () => hits,
    645     async release() {
    646       release?.();
    647       await holder;
    648     },
    649     restore() {
    650       navigator.locks.request = original;
    651     }
    652   };
    653 }
    654 
    655 // A new child realm uses only the parent extension's ephemeral closure and
    656 // genuine native storage. No predecessor preparation or proof is imported.
    657 export async function openHostedCheck(setup: {
    658   owner: string;
    659   policyWire: string;
    660   operatorWire: string;
    661   command: string;
    662 }) {
    663   installHostedProvider();
    664   const policy = validateRelayPolicy(setup.policyWire),
    665     operator = validateInboxOperatorQualification(setup.operatorWire);
    666   if (!policy || !operator) throw Error('actual hosted policy and operator');
    667   const context = await openRecoveryContext(
    668     setup.owner,
    669     policy,
    670     operator,
    671     setup.command
    672   );
    673   const check = createInboxAccessCheck(
    674     context.repository,
    675     context.identity,
    676     context.session,
    677     policy,
    678     context.access,
    679     operator
    680   );
    681   if (!check) throw Error('actual hosted coordinator capture');
    682   return { context, check };
    683 }