app

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

inbox-list.ts (7324B)


      1 import { mount, unmount } from 'svelte';
      2 import Panel from './inbox-list-panel.svelte';
      3 import { makeFixture as makeMetadataFixture } from './message-metadata.ts';
      4 import {
      5   createInboxSetupView,
      6   checkInboxSetupView,
      7   closeInboxSetupView
      8 } from '../../../src/lib/messaging/inbox-setup-view.ts';
      9 import {
     10   createInboxView,
     11   inboxViewSnapshot,
     12   inboxListSnapshot,
     13   unlockInboxView,
     14   readNewInboxView,
     15   checkInboxView,
     16   loadOlderInboxView,
     17   openInboxConversation,
     18   stopInboxView,
     19   closeInboxView
     20 } from '../../../src/lib/messaging/inbox-view.ts';
     21 import { identityMessagingOwnership } from '../../../src/lib/runtime/identity-session.ts';
     22 import {
     23   readRelayPolicy,
     24   validateRelayPolicy
     25 } from '../../../src/lib/config/relays.ts';
     26 import {
     27   openBrowserDatabase,
     28   closeBrowserDatabase,
     29   browserDatabaseTransaction
     30 } from '../../../src/lib/persistence/database.ts';
     31 import {
     32   admitInboxEnvelope,
     33   retainInboxEnvelope
     34 } from '../../../src/lib/persistence/inbox-envelope-repository.ts';
     35 import { finalizeEvent } from 'applesauce-core/helpers';
     36 import { nip44 } from 'applesauce-core/helpers/encryption';
     37 let navigations = Array.from<string>([]);
     38 // Harness-only alias for Kit navigation. Production retains actual Kit goto.
     39 export function goto(href: string) {
     40   navigations.push(href);
     41   return Promise.resolve();
     42 }
     43 export async function renderFixture(
     44   kind: 'inbound' | 'self_archive' | 'hostile_text' = 'inbound',
     45   qualified = false,
     46   variant: 'single' | 'duplicate' | 'mixed' = 'single'
     47 ) {
     48   const f = await makeMetadataFixture(kind);
     49   const original = identityMessagingOwnership(f.identity);
     50   if (!original) throw Error('no original identity');
     51   if (variant === 'duplicate') await f.anotherWrap(false);
     52   if (variant === 'mixed') {
     53     const record = (await f.row())!.record;
     54     const envelope = admitInboxEnvelope(
     55       record.self.wire,
     56       f.owner,
     57       'wss://archive.example.org',
     58       102
     59     );
     60     const session = f.navigationInputs().privateSession;
     61     if (
     62       !envelope ||
     63       (await retainInboxEnvelope(f.repository, session, envelope)).status !==
     64         'retained'
     65     )
     66       throw Error('no actual self archive');
     67   }
     68   async function native() {
     69     const opened = await openBrowserDatabase();
     70     if (opened.state !== 'ready') throw Error('no actual DB');
     71     try {
     72       const tx = browserDatabaseTransaction(
     73           opened.owner,
     74           ['received_envelopes', 'conversations'],
     75           'readonly'
     76         ),
     77         received = tx.objectStore('received_envelopes').getAll(),
     78         pairs = tx.objectStore('conversations').getAll();
     79       return await new Promise<{ received: unknown[]; pairs: unknown[] }>(
     80         (resolve, reject) => {
     81           tx.addEventListener('complete', () =>
     82             resolve({ received: received.result, pairs: pairs.result })
     83           );
     84           tx.addEventListener('abort', () => reject(Error('scan aborted')));
     85         }
     86       );
     87     } finally {
     88       closeBrowserDatabase(opened.owner);
     89     }
     90   }
     91   const initial = await native(),
     92     raw = initial.received[0] as { wire: string },
     93     record = JSON.parse(raw.wire) as { outer: string };
     94   // Produce a relay-only valid old outer with the same authenticated signed seal.
     95   // Both timestamps are set before signing. Nothing signed is edited afterward.
     96   const outer = JSON.parse(record.outer) as {
     97     pubkey: string;
     98     content: string;
     99     created_at: number;
    100   };
    101   const ownerSecret = new Uint8Array(32).fill(83),
    102     outerSecret = new Uint8Array(32).fill(86);
    103   let olderWire: string;
    104   try {
    105     const decryptKey = nip44.v2.utils.getConversationKey(
    106       ownerSecret,
    107       outer.pubkey
    108     );
    109     let seal: string;
    110     try {
    111       seal = nip44.v2.decrypt(outer.content, decryptKey);
    112     } finally {
    113       decryptKey.fill(0);
    114     }
    115     const encryptKey = nip44.v2.utils.getConversationKey(outerSecret, f.owner);
    116     let content: string;
    117     try {
    118       content = nip44.v2.encrypt(seal, encryptKey);
    119     } finally {
    120       encryptKey.fill(0);
    121     }
    122     olderWire = JSON.stringify(
    123       finalizeEvent(
    124         {
    125           kind: 1059,
    126           created_at: outer.created_at - 120,
    127           tags: [['p', f.owner]],
    128           content
    129         },
    130         outerSecret
    131       )
    132     );
    133   } finally {
    134     ownerSecret.fill(0);
    135     outerSecret.fill(0);
    136   }
    137   const policy = validateRelayPolicy(
    138     JSON.stringify({
    139       ...readRelayPolicy(f.context.policy),
    140       messagingEnabled: true
    141     })
    142   );
    143   if (!policy) throw Error('no policy');
    144   let access = true;
    145   const setup = createInboxSetupView({
    146     identity: f.identity,
    147     policy,
    148     lookup: () => Promise.resolve(f.context.own),
    149     observeAccess: qualified
    150       ? (context) => ({
    151           ...context,
    152           receive: 'qualified_exercised',
    153           archive: 'qualified_exercised',
    154           current: () => access && original.current()
    155         })
    156       : undefined
    157   });
    158   if (!setup) throw Error('no setup');
    159   const controller = createInboxView({ identity: f.identity, setup });
    160   if (!controller) throw Error('no original page');
    161   const target = document.createElement('div');
    162   document.body.append(target);
    163   const mounted = mount(Panel, { target, props: { controller } });
    164   navigations = [];
    165   const baseline = f.counts();
    166   return {
    167     controller,
    168     owner: f.owner,
    169     peer: f.peer,
    170     rumorId: f.rumorId,
    171     olderWire,
    172     native,
    173     snapshot: () => inboxViewSnapshot(controller),
    174     list: () => inboxListSnapshot(controller),
    175     navigations: () => navigations.slice(),
    176     checkSetup: () => checkInboxSetupView(setup),
    177     unlock: () => unlockInboxView(controller, 'reviewed_messages_unlock'),
    178     next: () => readNewInboxView(controller, 'reviewed_decrypt_batch'),
    179     check: () => checkInboxView(controller, 'reviewed_foreground_inbox'),
    180     older: (review: unknown = 'reviewed_load_older') =>
    181       loadOlderInboxView(controller, review),
    182     open: (
    183       peer: unknown = f.peer,
    184       review: unknown = 'reviewed_admitted_conversation_navigation'
    185     ) => openInboxConversation(controller, peer, review),
    186     delta: () => ({
    187       decrypts: f.counts().decrypts - baseline.decrypts,
    188       signs: f.counts().signs - baseline.signs,
    189       encrypts: f.counts().encrypts - baseline.encrypts
    190     }),
    191     copied: async () => ({
    192       list: inboxListSnapshot({ ...controller }),
    193       open: await openInboxConversation(
    194         { ...controller },
    195         f.peer,
    196         'reviewed_admitted_conversation_navigation'
    197       ),
    198       older: await loadOlderInboxView({ ...controller }, 'reviewed_load_older')
    199     }),
    200     async markRead() {
    201       if (
    202         (await f.unlock()) !== 'authenticated' ||
    203         !f.admit(kind === 'self_archive' ? 'self_archive' : 'inbound') ||
    204         !f.captureCache()
    205       )
    206         throw Error('no genuine explicit read proof');
    207       f.cache();
    208       if (!(await f.captureMetadata())) throw Error('no original metadata');
    209       return await f.display();
    210     },
    211     stop: () => stopInboxView(controller),
    212     logout: () => f.disconnect(),
    213     mode: f.mode,
    214     settle: () => f.settle(),
    215     pending: () => f.pending(),
    216     revokeAccess: () => {
    217       access = false;
    218     },
    219     async close() {
    220       f.settle();
    221       closeInboxView(controller);
    222       closeInboxSetupView(setup);
    223       await unmount(mounted);
    224       f.close();
    225       target.remove();
    226     }
    227   };
    228 }