app

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

unlocked-session.ts (9818B)


      1 import {
      2   captureUnlockedSession,
      3   acceptUnlockedConversation,
      4   readUnlockedMessages,
      5   unlockedSessionSnapshot,
      6   closeUnlockedSession,
      7   type UnlockedSession
      8 } from '../../../src/lib/messaging/unlocked-session.ts';
      9 import {
     10   getPrivateCacheScope,
     11   retainPrivateCacheWire,
     12   clearPrivateCacheScope,
     13   privateCacheSnapshot,
     14   type PrivateCacheScope
     15 } from '../../../src/lib/nostr/private-cache-scope.ts';
     16 import {
     17   createIdentitySession,
     18   connectIdentity,
     19   probeIdentityMessaging,
     20   disconnectIdentity,
     21   recheckIdentityOwner
     22 } from '../../../src/lib/runtime/identity-session.ts';
     23 import {
     24   getPublicKey,
     25   getEventHash,
     26   finalizeEvent,
     27   type UnsignedEvent
     28 } from 'applesauce-core/helpers';
     29 import { nip44 } from 'applesauce-core/helpers/encryption';
     30 import { makeFixture as makeRecoveryFixture } from './resume-preparation.ts';
     31 import {
     32   createPrivateSession,
     33   closePrivateSession
     34 } from '../../../src/lib/runtime/private-session.ts';
     35 import {
     36   admitInboxEnvelope,
     37   retainInboxEnvelope
     38 } from '../../../src/lib/persistence/inbox-envelope-repository.ts';
     39 import {
     40   captureReceivedUnwrap,
     41   unwrapReceivedEnvelope,
     42   stopReceivedUnwrap,
     43   type ReceivedUnwrap,
     44   type ReceivedNestedEnvelope
     45 } from '../../../src/lib/nostr/unwrap-admission.ts';
     46 import {
     47   admitReceivedConversation,
     48   conversationSnapshot,
     49   type AdmittedConversation
     50 } from '../../../src/lib/messaging/admit-conversation.ts';
     51 type Scenario =
     52   | 'inbound'
     53   | 'self_archive'
     54   | 'third_party'
     55   | 'hostile_text'
     56   | 'missing_parent';
     57 export async function makeFixture(scenario: Scenario = 'inbound') {
     58   const f = await makeRecoveryFixture(),
     59     privateSession = await createPrivateSession(
     60       f.identity,
     61       'reviewed_private_session'
     62     );
     63   if (!privateSession) throw Error('missing genuine private session');
     64   const ownerSecret = new Uint8Array(32).fill(83),
     65     peerSecret = new Uint8Array(32).fill(84),
     66     outerSecret = new Uint8Array(32).fill(85),
     67     other = getPublicKey(outerSecret);
     68   const senderSecret = scenario === 'self_archive' ? ownerSecret : peerSecret,
     69     sender = getPublicKey(senderSecret),
     70     recipient =
     71       scenario === 'self_archive'
     72         ? f.peer
     73         : scenario === 'third_party'
     74           ? other
     75           : f.owner;
     76   const tags: string[][] = [['p', recipient]];
     77   if (scenario === 'hostile_text') tags.push(['subject', other]);
     78   if (scenario === 'missing_parent')
     79     tags.push(['e', 'a'.repeat(64), 'wss://untrusted.example.org']);
     80   const template: UnsignedEvent = {
     81       pubkey: sender,
     82       kind: 14,
     83       created_at: 1700000000,
     84       tags,
     85       content:
     86         scenario === 'hostile_text'
     87           ? `Contact ${other} https://untrusted.example.org`
     88           : 'Actual encrypted room fixture'
     89     },
     90     rumor = { id: getEventHash(template), ...template };
     91   function encrypt(key: Uint8Array, target: string, plain: string) {
     92     const conversation = nip44.v2.utils.getConversationKey(key, target);
     93     try {
     94       return nip44.v2.encrypt(plain, conversation);
     95     } finally {
     96       conversation.fill(0);
     97     }
     98   }
     99   const seal = finalizeEvent(
    100     {
    101       kind: 13,
    102       created_at: 1699999900,
    103       tags: [],
    104       content: encrypt(senderSecret, f.owner, JSON.stringify(rumor))
    105     },
    106     senderSecret
    107   );
    108   const outer = finalizeEvent(
    109     {
    110       kind: 1059,
    111       created_at: 1699999800,
    112       tags: [['p', f.owner]],
    113       content: encrypt(outerSecret, f.owner, JSON.stringify(seal))
    114     },
    115     outerSecret
    116   );
    117   ownerSecret.fill(0);
    118   peerSecret.fill(0);
    119   outerSecret.fill(0);
    120   const admitted = admitInboxEnvelope(
    121     JSON.stringify(outer),
    122     f.owner,
    123     'wss://archive.example.org',
    124     100
    125   );
    126   if (!admitted) throw Error('missing signed addressed outer');
    127   const saved = await retainInboxEnvelope(
    128     f.repository,
    129     privateSession,
    130     admitted
    131   );
    132   if (saved.status !== 'retained') throw Error('no actual retained cipher');
    133   let reader: ReceivedUnwrap | undefined,
    134     nested: ReceivedNestedEnvelope | undefined,
    135     room: AdmittedConversation | undefined;
    136   let unlocked: UnlockedSession | undefined;
    137   let rawCache: PrivateCacheScope | undefined;
    138   let otherPrivateSession: Awaited<ReturnType<typeof createPrivateSession>>;
    139   let otherIdentity: ReturnType<typeof createIdentitySession> | undefined;
    140   return {
    141     ...f,
    142     other,
    143     rumorId: rumor.id,
    144     async unlock() {
    145       reader = captureReceivedUnwrap(
    146         f.repository,
    147         f.identity,
    148         outer.id,
    149         'reviewed_inbox_unlock'
    150       );
    151       if (!reader) return 'invalid';
    152       const result = await unwrapReceivedEnvelope(reader);
    153       if (result.status === 'authenticated') nested = result.envelope;
    154       return result.status;
    155     },
    156     admit(role: unknown) {
    157       room = nested && admitReceivedConversation(nested, role);
    158       return room && conversationSnapshot(room);
    159     },
    160     snapshot() {
    161       return room && conversationSnapshot(room);
    162     },
    163     forged() {
    164       return admitReceivedConversation({} as ReceivedNestedEnvelope, 'inbound');
    165     },
    166     copied() {
    167       return room && conversationSnapshot({ ...room });
    168     },
    169     captureCache(review: unknown = 'reviewed_messages_unlock') {
    170       unlocked = captureUnlockedSession(privateSession, review);
    171       if (unlocked)
    172         rawCache = getPrivateCacheScope(privateSession, 'projection_ownership');
    173       return !!unlocked;
    174     },
    175     cache() {
    176       return unlocked && room
    177         ? acceptUnlockedConversation(unlocked, room)
    178         : 'rejected';
    179     },
    180     messages() {
    181       return unlocked && readUnlockedMessages(unlocked);
    182     },
    183     cacheSnapshot() {
    184       return unlocked && unlockedSessionSnapshot(unlocked);
    185     },
    186     rawCacheSnapshot() {
    187       return rawCache && privateCacheSnapshot(rawCache);
    188     },
    189     forgedCache() {
    190       return (
    191         unlocked &&
    192         acceptUnlockedConversation(unlocked, {} as AdmittedConversation)
    193       );
    194     },
    195     copiedCache() {
    196       return (
    197         unlocked && room && acceptUnlockedConversation(unlocked, { ...room })
    198       );
    199     },
    200     closeCache() {
    201       if (unlocked) closeUnlockedSession(unlocked);
    202     },
    203     closePrivate() {
    204       closePrivateSession(privateSession);
    205     },
    206     async changedOwner() {
    207       f.mode('changed_key');
    208       return await recheckIdentityOwner(f.identity);
    209     },
    210     async otherGeneration() {
    211       otherIdentity = createIdentitySession();
    212       await connectIdentity(otherIdentity);
    213       await probeIdentityMessaging(otherIdentity, 'reviewed_self_copy');
    214       otherPrivateSession = await createPrivateSession(
    215         otherIdentity,
    216         'reviewed_private_session'
    217       );
    218       if (!otherPrivateSession)
    219         throw Error('missing other genuine private session');
    220       const scope = captureUnlockedSession(
    221         otherPrivateSession,
    222         'reviewed_messages_unlock'
    223       );
    224       if (!scope || !room) throw Error('missing genuine scope/room');
    225       return {
    226         accepted: acceptUnlockedConversation(scope, room),
    227         snapshot: unlockedSessionSnapshot(scope)
    228       };
    229     },
    230     quota() {
    231       const scope = getPrivateCacheScope(
    232         privateSession,
    233         'projection_ownership'
    234       );
    235       if (!scope) throw Error('missing actual scoped cache');
    236       for (let i = 0; i < 2000; i++) {
    237         const result = retainPrivateCacheWire(
    238           scope,
    239           i.toString(16).padStart(64, '0'),
    240           '{}'
    241         );
    242         if (result !== 'accepted')
    243           throw Error('unexpected quota fixture result ' + result);
    244       }
    245       return 2000;
    246     },
    247     corruptCachedWire() {
    248       const scope = getPrivateCacheScope(
    249         privateSession,
    250         'projection_ownership'
    251       );
    252       if (!scope || !room) throw Error('missing actual cache');
    253       const snapshot = conversationSnapshot(room);
    254       if (!snapshot) throw Error('no current room');
    255       clearPrivateCacheScope(scope);
    256       return retainPrivateCacheWire(
    257         scope,
    258         snapshot.rumorId,
    259         JSON.stringify({
    260           ...snapshot,
    261           peer: other,
    262           content: 'HOSTILE_CACHE_POISON'
    263         })
    264       );
    265     },
    266     async anotherWrap() {
    267       const key = new Uint8Array(32).fill(86);
    268       let next;
    269       try {
    270         next = finalizeEvent(
    271           {
    272             kind: 1059,
    273             created_at: 1699999799,
    274             tags: [['p', f.owner]],
    275             content: encrypt(key, f.owner, JSON.stringify(seal))
    276           },
    277           key
    278         );
    279       } finally {
    280         key.fill(0);
    281       }
    282       const candidate = admitInboxEnvelope(
    283         JSON.stringify(next),
    284         f.owner,
    285         'wss://archive.example.org',
    286         101
    287       );
    288       if (!candidate) throw Error('no second outer');
    289       const result = await retainInboxEnvelope(
    290         f.repository,
    291         privateSession,
    292         candidate
    293       );
    294       if (result.status !== 'retained') throw Error('no second retained outer');
    295       reader = captureReceivedUnwrap(
    296         f.repository,
    297         f.identity,
    298         next.id,
    299         'reviewed_inbox_unlock'
    300       );
    301       if (!reader) throw Error('no genuine second reader');
    302       const opened = await unwrapReceivedEnvelope(reader);
    303       if (opened.status !== 'authenticated')
    304         throw Error('no actual second decrypt');
    305       nested = opened.envelope;
    306       room = admitReceivedConversation(
    307         nested,
    308         scenario === 'self_archive' ? 'self_archive' : 'inbound'
    309       );
    310       return { outerId: next.id, rumorId: rumor.id };
    311     },
    312     stop() {
    313       if (reader) stopReceivedUnwrap(reader);
    314     },
    315     close() {
    316       if (unlocked) closeUnlockedSession(unlocked);
    317       if (otherPrivateSession) closePrivateSession(otherPrivateSession);
    318       if (otherIdentity) disconnectIdentity(otherIdentity);
    319       if (reader) stopReceivedUnwrap(reader);
    320       closePrivateSession(privateSession);
    321       f.close();
    322     }
    323   };
    324 }