app

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

decryption-queue.ts (12767B)


      1 import { planDecryptBatch } from './inbox-state.ts';
      2 import { canonicalPublicKey } from '../contracts/public-key.ts';
      3 import {
      4   privateBlocksForIdentity,
      5   mountLocalPrivateBlocks,
      6   localPrivateBlocksSnapshot,
      7   localPrivatePeerAllowed
      8 } from '../persistence/local-private-blocks.ts';
      9 import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts';
     10 import {
     11   privateSessionOwnership,
     12   subscribePrivateSessionClose,
     13   type PrivateSession
     14 } from '../runtime/private-session.ts';
     15 import {
     16   identityMessagingOwnership,
     17   type IdentitySession
     18 } from '../runtime/identity-session.ts';
     19 import {
     20   getPrivateVisibilityScope,
     21   privateVisibilitySnapshot
     22 } from '../runtime/dispose.ts';
     23 import {
     24   listPrivateReceivedRecords,
     25   type PrivateStorageRepository
     26 } from '../persistence/private-storage.ts';
     27 import { privateRecordIdentity } from '../persistence/private-records.ts';
     28 import {
     29   captureReceivedUnwrap,
     30   unwrapReceivedEnvelope,
     31   stopReceivedUnwrap,
     32   expireReceivedUnwrapWait,
     33   type ReceivedUnwrap
     34 } from '../nostr/unwrap-admission.ts';
     35 import {
     36   admitReceivedConversation,
     37   conversationSnapshot,
     38   type AdmittedConversation
     39 } from './admit-conversation.ts';
     40 import {
     41   unlockedSessionOwnership,
     42   subscribeUnlockedSessionClose,
     43   acceptUnlockedConversation,
     44   type UnlockedSession
     45 } from './unlocked-session.ts';
     46 declare const queueBrand: unique symbol;
     47 export type DecryptionQueue = Readonly<{ [queueBrand]: true }>;
     48 type View = Readonly<{
     49   state: string;
     50   reason: string | null;
     51   queued: number;
     52   attempted: number;
     53   blocked: number;
     54   admitted: number;
     55   invalid: number;
     56   busy: boolean;
     57 }>;
     58 type Controller = {
     59   refresh(): Promise<boolean>;
     60   run(review: unknown, blocked: readonly string[]): Promise<boolean>;
     61   snapshot(): View;
     62   rooms(): readonly AdmittedConversation[];
     63   stop(): void;
     64   expire(): void;
     65 };
     66 const controllers = new WeakMap<DecryptionQueue, Controller>(),
     67   sessions = new WeakMap<PrivateSession, DecryptionQueue>();
     68 // Only original current owner-generation and actual explicit Messages unlock
     69 // admit a controller. Construction/refresh never invoke an extension operation.
     70 export function captureDecryptionQueue(
     71   repository: PrivateStorageRepository,
     72   session: PrivateSession,
     73   identity: IdentitySession,
     74   unlocked: UnlockedSession,
     75   review: unknown
     76 ): DecryptionQueue | undefined {
     77   if (typeof window === 'undefined' || review !== 'reviewed_inbox_unlock')
     78     return undefined;
     79   const observed = privateSessionOwnership(session),
     80     owner = identityMessagingOwnership(identity),
     81     cache = unlockedSessionOwnership(unlocked);
     82   if (
     83     !observed?.current() ||
     84     !owner?.current() ||
     85     !cache?.current() ||
     86     observed.owner !== owner.owner ||
     87     observed.owner !== cache.owner ||
     88     observed.session !== owner.session ||
     89     observed.session !== cache.session
     90   )
     91     return undefined;
     92   const capture = observed,
     93     identityOwner = owner,
     94     unlockedOwner = cache;
     95   const preferences = privateBlocksForIdentity(identity);
     96   if (!preferences) return;
     97   let visibility;
     98   try {
     99     visibility = getPrivateVisibilityScope(session);
    100   } catch {
    101     return undefined;
    102   }
    103   if (!visibility || !privateVisibilitySnapshot(visibility).active)
    104     return undefined;
    105   const visible = visibility;
    106   const prior = sessions.get(session);
    107   if (prior) return prior;
    108   const token = Object.freeze({}) as DecryptionQueue;
    109   let stopped = false,
    110     busy = false,
    111     paused = false,
    112     state = 'ready',
    113     reason: string | null = null,
    114     attempted = 0,
    115     blocked = 0,
    116     admitted = 0,
    117     invalid = 0;
    118   let pending = Array.from<string>([]),
    119     processed = Array.from<string>([]),
    120     accepted = Array.from<AdmittedConversation>([]),
    121     readers = Array.from<ReceivedUnwrap>([]);
    122   let active: ReceivedUnwrap | undefined,
    123     off = () => {},
    124     unlockOff = () => {};
    125   const excluded = new Map<string, string>();
    126   function current() {
    127     return (
    128       !stopped &&
    129       capture.current() &&
    130       identityOwner.current() &&
    131       unlockedOwner.current() &&
    132       privateVisibilitySnapshot(visible).active
    133     );
    134   }
    135   function stop() {
    136     if (stopped) return;
    137     stopped = true;
    138     state = 'stopped';
    139     reason = 'stopped';
    140     if (active) stopReceivedUnwrap(active);
    141     for (const reader of readers) stopReceivedUnwrap(reader);
    142     readers = [];
    143     accepted = [];
    144     pending = [];
    145     processed = [];
    146     excluded.clear();
    147     off();
    148     unlockOff();
    149     if (sessions.get(session) === token) sessions.delete(session);
    150     // Actual pending SDK promise retains the shared slot until its settlement.
    151   }
    152   function expire() {
    153     if (stopped || !busy) return;
    154     paused = true;
    155     state = 'paused';
    156     reason = 'wait_expired';
    157     if (active) expireReceivedUnwrapWait(active);
    158   }
    159   function pause(why: string) {
    160     paused = true;
    161     state = 'paused';
    162     reason = why;
    163   }
    164   async function load() {
    165     if (!current()) {
    166       stop();
    167       return false;
    168     }
    169     const result = await listPrivateReceivedRecords(repository);
    170     if (!current()) {
    171       stop();
    172       return false;
    173     }
    174     if (!result.ok) {
    175       pause(result.reason);
    176       return false;
    177     }
    178     let ids = Array.from<string>([]);
    179     for (const handle of result.value) {
    180       const record = privateRecordIdentity(handle);
    181       if (record?.owner !== capture.owner) {
    182         pause('invalid_scope');
    183         return false;
    184       }
    185       if (!processed.includes(record.id)) ids = ids.concat(record.id);
    186     }
    187     pending = ids;
    188     return true;
    189   }
    190   const controller: Controller = {
    191     snapshot: () => ({
    192       state,
    193       reason,
    194       queued: pending.length,
    195       attempted,
    196       blocked,
    197       admitted,
    198       invalid,
    199       busy
    200     }),
    201     rooms: () =>
    202       current()
    203         ? accepted.filter((room) => {
    204             const message = conversationSnapshot(room);
    205             return (
    206               !!message && localPrivatePeerAllowed(preferences, message.peer)
    207             );
    208           })
    209         : [],
    210     stop,
    211     expire,
    212     async refresh() {
    213       if (busy || !current()) return false;
    214       try {
    215         return await load();
    216       } catch {
    217         pause('unavailable');
    218         return false;
    219       }
    220     },
    221     async run(reviewed, blockedPeers) {
    222       if (reviewed !== 'reviewed_decrypt_batch' || busy || !current())
    223         return false;
    224       // Detached block values can only suppress an already authenticated inner
    225       // peer's local projection; they never bypass envelope cost or confer SDK access.
    226       if (
    227         !Array.isArray(blockedPeers) ||
    228         blockedPeers.length > LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes
    229       )
    230         return false;
    231       const exclusions = blockedPeers.slice();
    232       for (const peer of exclusions)
    233         if (canonicalPublicKey(peer) !== peer) return false;
    234       busy = true;
    235       paused = false;
    236       state = 'running';
    237       reason = null;
    238       attempted = 0;
    239       blocked = 0;
    240       admitted = 0;
    241       invalid = 0;
    242       try {
    243         await mountLocalPrivateBlocks(preferences);
    244         const initial = localPrivateBlocksSnapshot(preferences);
    245         if (!current() || initial.state !== 'ready') {
    246           pause('local_preferences_unavailable');
    247           return false;
    248         }
    249         // Undo alone does nothing. Only this newly reviewed batch may revisit
    250         // previously identified ciphertext, without resetting unrelated IDs.
    251         for (const [id, peer] of excluded) {
    252           if (
    253             localPrivatePeerAllowed(preferences, peer) &&
    254             !exclusions.includes(peer)
    255           ) {
    256             processed = processed.filter((value) => value !== id);
    257             excluded.delete(id);
    258           }
    259         }
    260         if (!(await load()) || paused || !current()) return false;
    261         const plan = planDecryptBatch(pending);
    262         for (const id of plan.selected) {
    263           if (!current()) {
    264             stop();
    265             return false;
    266           }
    267           if (paused) return false;
    268           const before = localPrivateBlocksSnapshot(preferences);
    269           if (
    270             before.state !== 'ready' ||
    271             before.revision !== initial.revision
    272           ) {
    273             pause(
    274               before.state === 'ready'
    275                 ? 'local_block_changed'
    276                 : 'local_preferences_unavailable'
    277             );
    278             return false;
    279           }
    280           // Cost reservation occurs before unwrap/admission/dedup/blocked sender.
    281           attempted++;
    282           active = captureReceivedUnwrap(
    283             repository,
    284             identity,
    285             id,
    286             'reviewed_inbox_unlock'
    287           );
    288           if (!active) {
    289             pause('unavailable');
    290             return false;
    291           }
    292           const reader = active,
    293             result = await unwrapReceivedEnvelope(reader);
    294           if (!current()) {
    295             stopReceivedUnwrap(reader);
    296             stop();
    297             return false;
    298           }
    299           if (paused) {
    300             stopReceivedUnwrap(reader);
    301             return false;
    302           }
    303           if (result.status === 'authenticated') {
    304             const room =
    305               admitReceivedConversation(result.envelope, 'inbound') ??
    306               admitReceivedConversation(result.envelope, 'self_archive');
    307             const message = room && conversationSnapshot(room);
    308             if (!room || !message) {
    309               invalid++;
    310               stopReceivedUnwrap(reader);
    311             } else if (
    312               exclusions.includes(message.peer) ||
    313               !localPrivatePeerAllowed(preferences, message.peer)
    314             ) {
    315               blocked++;
    316               excluded.set(id, message.peer);
    317               stopReceivedUnwrap(reader);
    318             } else {
    319               const projection = acceptUnlockedConversation(unlocked, room);
    320               if (projection === 'added') {
    321                 accepted = accepted.concat(room);
    322                 readers = readers.concat(reader);
    323                 admitted++;
    324               } else if (projection === 'duplicate') {
    325                 admitted++;
    326                 stopReceivedUnwrap(reader);
    327               } else {
    328                 stopReceivedUnwrap(reader);
    329                 pause(projection);
    330                 return false;
    331               }
    332             }
    333           } else if (
    334             result.status === 'mismatch' ||
    335             result.status === 'invalid'
    336           ) {
    337             invalid++;
    338             stopReceivedUnwrap(reader);
    339           } else {
    340             stopReceivedUnwrap(reader);
    341             pause(result.status);
    342             return false;
    343           }
    344           active = undefined;
    345           if (!current() || paused) return false;
    346           processed = processed.concat(id);
    347           pending = pending.filter((next) => next !== id);
    348           const actual = localPrivateBlocksSnapshot(preferences);
    349           if (
    350             actual.state !== 'ready' ||
    351             actual.revision !== initial.revision
    352           ) {
    353             pause(
    354               actual.state === 'ready'
    355                 ? 'local_block_changed'
    356                 : 'local_preferences_unavailable'
    357             );
    358             return false;
    359           }
    360         }
    361         if (!(await load()) || paused || !current()) return false;
    362         state = pending.length ? 'needs_action' : 'idle';
    363         return true;
    364       } catch {
    365         if (current() && !paused) pause('unavailable');
    366         return false;
    367       } finally {
    368         active = undefined;
    369         busy = false;
    370       }
    371     }
    372   };
    373   controllers.set(token, controller);
    374   sessions.set(session, token);
    375   off = subscribePrivateSessionClose(session, stop);
    376   unlockOff = subscribeUnlockedSessionClose(unlocked, stop);
    377   if (!current()) {
    378     stop();
    379     return undefined;
    380   }
    381   return token;
    382 }
    383 export function refreshDecryptionQueue(
    384   token: DecryptionQueue
    385 ): Promise<boolean> {
    386   return controllers.get(token)?.refresh() ?? Promise.resolve(false);
    387 }
    388 export function runDecryptionBatch(
    389   token: DecryptionQueue,
    390   review: unknown,
    391   blockedPeers: readonly string[] = []
    392 ): Promise<boolean> {
    393   return (
    394     controllers.get(token)?.run(review, blockedPeers) ?? Promise.resolve(false)
    395   );
    396 }
    397 export function decryptionQueueSnapshot(token: DecryptionQueue): View {
    398   return (
    399     controllers.get(token)?.snapshot() ?? {
    400       state: 'stopped',
    401       reason: 'invalid',
    402       queued: 0,
    403       attempted: 0,
    404       blocked: 0,
    405       admitted: 0,
    406       invalid: 0,
    407       busy: false
    408     }
    409   );
    410 }
    411 export function decryptionQueueConversations(
    412   token: DecryptionQueue
    413 ): readonly AdmittedConversation[] {
    414   return controllers.get(token)?.rooms() ?? [];
    415 }
    416 export function stopDecryptionQueue(token: DecryptionQueue): void {
    417   controllers.get(token)?.stop();
    418 }
    419 export function expireDecryptionQueueWait(token: DecryptionQueue): void {
    420   controllers.get(token)?.expire();
    421 }