app

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

inbox-auth.ts (8484B)


      1 import { makeFixture } from './approved-signing.ts';
      2 import { fixturePolicy, inbox } from './inbox-setup.ts';
      3 import {
      4   createIdentitySession,
      5   connectIdentity,
      6   probeIdentityMessaging,
      7   disconnectIdentity,
      8   identityMessagingOwnership
      9 } from '../../../src/lib/runtime/identity-session.ts';
     10 import {
     11   createPrivateSession,
     12   closePrivateSession,
     13   privateSessionSnapshot
     14 } from '../../../src/lib/runtime/private-session.ts';
     15 import * as ActualPrivateSession from '../../../src/lib/runtime/private-session.ts';
     16 import {
     17   getPrivateStore,
     18   insertPrivateEnvelope,
     19   privateStoreSnapshot
     20 } from '../../../src/lib/messaging/private-store.ts';
     21 import { verifyEnvelope } from '../../../src/lib/nostr/verified-envelope.ts';
     22 import {
     23   getPrivatePool,
     24   beginPrivateAuthConnection,
     25   privateAuthChallenge,
     26   reservePrivateAuthResponse,
     27   sendPrivateAuthResponse,
     28   subscribePrivatePage
     29 } from '../../../src/lib/nostr/private-pool.ts';
     30 import { RelayPool } from 'applesauce-relay';
     31 import type { RelayPolicy } from '../../../src/lib/config/relays.ts';
     32 export {
     33   beginInboxAuthentication,
     34   respondInboxAuthentication,
     35   inboxAuthSnapshot,
     36   closeInboxAuthentication
     37 } from '../../../src/lib/nostr/inbox-auth.ts';
     38 export {
     39   browserExtensionScheduler,
     40   extensionSchedulerSnapshot
     41 } from '../../../src/lib/nostr/extension-scheduler.ts';
     42 export {
     43   getPublicPool,
     44   subscribePublicPool,
     45   closePublicPool
     46 } from '../../../src/lib/nostr/public-pool.ts';
     47 export { inbox, fixturePolicy };
     48 export async function makeAuthFixture(
     49   selectedPolicy?: RelayPolicy,
     50   actualCrypto = false
     51 ) {
     52   const fixture = makeFixture(10050),
     53     identity = createIdentitySession();
     54   let mode: 'exact' | 'author' | 'relay' | 'challenge' | 'cached' | 'denied' =
     55       'exact',
     56     signs = 0,
     57     changed = false,
     58     invalidKey = false;
     59   let before = () => Promise.resolve();
     60   let beforeKey = () => Promise.resolve();
     61   Object.defineProperty(window, 'nostr', {
     62     configurable: true,
     63     value: {
     64       getPublicKey: async () => {
     65         await beforeKey();
     66         return invalidKey
     67           ? 'not-a-public-key'
     68           : changed
     69             ? 'f'.repeat(64)
     70             : fixture.owner;
     71       },
     72       signEvent: async (input: Parameters<typeof fixture.sign>[0]) => {
     73         signs++;
     74         await before();
     75         if (mode === 'relay') input.tags[0][1] = 'wss://wrong.example.org/';
     76         if (mode === 'challenge') input.tags[1][1] = 'wrong';
     77         return fixture.sign(
     78           input,
     79           mode === 'relay' || mode === 'challenge' ? 'exact' : mode
     80         );
     81       },
     82       nip44: {
     83         encrypt: (peer: string, value: string) =>
     84           Promise.resolve(
     85             actualCrypto ? fixture.encrypt(peer, value) : 'fixture:' + value
     86           ),
     87         decrypt: (peer: string, value: string) =>
     88           Promise.resolve(
     89             actualCrypto ? fixture.decrypt(peer, value) : value.slice(8)
     90           )
     91       }
     92     }
     93   });
     94   await connectIdentity(identity);
     95   await probeIdentityMessaging(identity, 'reviewed_self_copy');
     96   const session = await createPrivateSession(
     97     identity,
     98     'reviewed_private_session'
     99   );
    100   if (!session) throw new Error('missing genuine private session');
    101   const policy = selectedPolicy ?? fixturePolicy(),
    102     pool = getPrivatePool(session, policy, [inbox]);
    103   if (!pool) throw new Error('missing private pool');
    104   const store = getPrivateStore(session);
    105   if (!store) throw new Error('missing genuine raw store');
    106   const cached = verifyEnvelope(
    107     JSON.stringify(
    108       fixture.sign({
    109         kind: 1059,
    110         created_at: 101,
    111         tags: [['p', fixture.owner]],
    112         content: 'opaque raw ciphertext fixture'
    113       })
    114     )
    115   );
    116   if (!cached.ok || insertPrivateEnvelope(store, cached.value) !== 'accepted')
    117     throw new Error('missing actual verified raw cache fixture');
    118   return {
    119     pool,
    120     policy,
    121     identity,
    122     session,
    123     preferenceWire(
    124       relays: readonly string[],
    125       seconds = Math.floor(Date.now() / 1000)
    126     ) {
    127       return JSON.stringify(
    128         fixture.sign({
    129           kind: 10050,
    130           created_at: seconds,
    131           tags: relays.map((origin) => ['relay', origin]),
    132           content: ''
    133         })
    134       );
    135     },
    136     beforeKey(next: typeof beforeKey) {
    137       beforeKey = next;
    138     },
    139     owner: fixture.owner,
    140     signs: () => signs,
    141     mode: (next: typeof mode) => {
    142       mode = next;
    143     },
    144     beforeSign: (next: typeof before) => {
    145       before = next;
    146     },
    147     changeOwner: () => {
    148       changed = true;
    149     },
    150     loseCapability: () => {
    151       const provider: unknown = Reflect.get(window, 'nostr');
    152       if (!provider || typeof provider !== 'object')
    153         throw new Error('missing controlled provider');
    154       Object.defineProperty(provider, 'nip44', {
    155         configurable: true,
    156         value: undefined
    157       });
    158     },
    159     failKey: (mode: 'invalid' | 'missing') => {
    160       if (mode === 'invalid') invalidKey = true;
    161       else Reflect.deleteProperty(window, 'nostr');
    162     },
    163     logout: () => disconnectIdentity(identity),
    164     reopen: () => getPrivatePool(session, policy, [inbox]),
    165     startPage: () => subscribePrivatePage(pool, 1, () => {}),
    166     ownership: () => ({
    167       private: privateSessionSnapshot(session)?.current,
    168       identity: identityMessagingOwnership(identity)?.current() ?? false,
    169       cache: privateStoreSnapshot(store)
    170     }),
    171     async staleGenerationInvalidation() {
    172       disconnectIdentity(identity);
    173       while (ActualPrivateSession.privateSessionCleanupRequired(session)) {
    174         closePrivateSession(session);
    175         await new Promise<void>((resolve) => setTimeout(resolve, 0));
    176       }
    177       await connectIdentity(identity);
    178       await probeIdentityMessaging(identity, 'reviewed_self_copy');
    179       const successor = await createPrivateSession(
    180         identity,
    181         'reviewed_private_session'
    182       );
    183       if (!successor) throw new Error('missing genuine successor');
    184       const invalidate: unknown = Reflect.get(
    185         ActualPrivateSession,
    186         'invalidatePrivateSessionGeneration'
    187       );
    188       const result: unknown =
    189         typeof invalidate === 'function'
    190           ? Reflect.apply(invalidate, undefined, [session])
    191           : 'missing';
    192       const observed = {
    193         result,
    194         successor: privateSessionSnapshot(successor)?.current,
    195         identity: identityMessagingOwnership(identity)?.current() ?? false
    196       };
    197       closePrivateSession(successor);
    198       return observed;
    199     },
    200     async rawPortBypass() {
    201       const connection = (await Reflect.apply(
    202         beginPrivateAuthConnection,
    203         undefined,
    204         [pool, inbox]
    205       )) as Awaited<ReturnType<typeof beginPrivateAuthConnection>>;
    206       if (!connection) return 'blocked';
    207       for (let i = 0; i < 100; i++) {
    208         const proof = privateAuthChallenge(connection);
    209         if (proof) {
    210           if (!reservePrivateAuthResponse(connection, proof)) return 'blocked';
    211           const event = fixture.sign({
    212             kind: 22242,
    213             created_at: Math.floor(Date.now() / 1000),
    214             tags: [
    215               ['relay', proof.relay],
    216               ['challenge', proof.challenge]
    217             ],
    218             content: ''
    219           });
    220           return (await Reflect.apply(sendPrivateAuthResponse, undefined, [
    221             connection,
    222             proof,
    223             JSON.stringify(event)
    224           ])) as string;
    225         }
    226         await new Promise<void>((resolve) => setTimeout(resolve, 10));
    227       }
    228       throw new Error('missing real challenge for bypass test');
    229     },
    230     async closeAndWait() {
    231       closePrivateSession(session);
    232       disconnectIdentity(identity);
    233       fixture.close();
    234       while (ActualPrivateSession.privateSessionCleanupRequired(session)) {
    235         closePrivateSession(session);
    236         await new Promise<void>((resolve) => setTimeout(resolve, 0));
    237       }
    238     },
    239     close: () => {
    240       closePrivateSession(session);
    241       disconnectIdentity(identity);
    242       fixture.close();
    243     }
    244   };
    245 }
    246 export function installCloseFailure() {
    247   const original = Reflect.get<RelayPool, 'remove'>(
    248     RelayPool.prototype,
    249     'remove'
    250   );
    251   let failing = true;
    252   RelayPool.prototype.remove = function (
    253     ...args: Parameters<RelayPool['remove']>
    254   ) {
    255     if (failing) throw new Error('controlled physical cleanup fault');
    256     return original.apply(this, args);
    257   };
    258   return {
    259     allow: () => {
    260       failing = false;
    261     },
    262     restore: () => {
    263       RelayPool.prototype.remove = original;
    264     }
    265   };
    266 }