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


      1 import { ExtensionSigner } from 'applesauce-signers';
      2 import { getEventHash, type UnsignedEvent } from 'applesauce-core/helpers';
      3 import { verifyEnvelope } from './verified-envelope.ts';
      4 import {
      5   beginPrivateAuthConnection,
      6   privateAuthChallenge,
      7   privateAuthStopped,
      8   reservePrivateAuthResponse,
      9   sendPrivateAuthResponse,
     10   closePrivateAuthConnection,
     11   invalidatePrivateAuthGeneration,
     12   type PrivatePool,
     13   type PrivateAuthChallenge
     14 } from './private-pool.ts';
     15 import {
     16   browserExtensionScheduler,
     17   runExtensionAction,
     18   callExtension
     19 } from './extension-scheduler.ts';
     20 declare const authBrand: unique symbol;
     21 export type InboxAuthAction = Readonly<{ [authBrand]: true }>;
     22 type State = {
     23   snapshot(): { state: string; responses: number };
     24   run(): Promise<Readonly<{ status: string }>>;
     25   close(): void;
     26 };
     27 const actions = new WeakMap<InboxAuthAction, State>();
     28 declare const admissionBrand: unique symbol;
     29 declare const responseBrand: unique symbol;
     30 export type InboxAuthAdmission = Readonly<{ [admissionBrand]: true }>;
     31 export type GuardedInboxAuthResponse = Readonly<{ [responseBrand]: true }>;
     32 const admissions = new WeakMap<
     33   InboxAuthAdmission,
     34   Readonly<{ pool: PrivatePool; origin: string }>
     35 >();
     36 const signedResponses = new WeakMap<
     37   GuardedInboxAuthResponse,
     38   Readonly<{ proof: PrivateAuthChallenge; wire: string; current(): boolean }>
     39 >();
     40 // Read/consume ports cannot manufacture approval. Only the lexical reviewed
     41 // action and actual scheduler continuation create these genuine capabilities.
     42 export function takeInboxAuthAdmission(
     43   token: InboxAuthAdmission,
     44   pool: PrivatePool,
     45   origin: string
     46 ): boolean {
     47   const saved = admissions.get(token);
     48   if (!saved || saved.pool !== pool || saved.origin !== origin) return false;
     49   admissions.delete(token);
     50   return true;
     51 }
     52 export function takeGuardedInboxAuthResponse(
     53   token: GuardedInboxAuthResponse,
     54   proof: PrivateAuthChallenge
     55 ): string | undefined {
     56   const saved = signedResponses.get(token);
     57   if (!saved || saved.proof !== proof || !saved.current() || !proof.current())
     58     return undefined;
     59   signedResponses.delete(token);
     60   return saved.wire;
     61 }
     62 export async function beginInboxAuthentication(
     63   pool: PrivatePool,
     64   origin: string,
     65   review: unknown
     66 ): Promise<InboxAuthAction | undefined> {
     67   if (typeof window === 'undefined' || review !== 'reviewed_connection_auth')
     68     return undefined;
     69   const admission = Object.freeze({}) as InboxAuthAdmission;
     70   admissions.set(admission, { pool, origin });
     71   const acquired = await beginPrivateAuthConnection(pool, origin, admission);
     72   if (!acquired) return undefined;
     73   const connection = acquired;
     74   const token = Object.freeze({}) as InboxAuthAction;
     75   let busy = false,
     76     responses = 0;
     77   let phase: 'waiting' | 'accepted' | 'refused' | 'unknown' | 'stopped' =
     78     'waiting';
     79   function close() {
     80     phase = 'stopped';
     81     closePrivateAuthConnection(connection);
     82   }
     83   function own(value: object, name: string): unknown {
     84     const field = Object.getOwnPropertyDescriptor(value, name);
     85     return field && 'value' in field ? field.value : undefined;
     86   }
     87   function messagingCapabilitiesCurrent(): boolean {
     88     try {
     89       const cipher = new ExtensionSigner().nip44;
     90       return (
     91         typeof cipher?.encrypt === 'function' &&
     92         typeof cipher?.decrypt === 'function'
     93       );
     94     } catch {
     95       return false;
     96     }
     97   }
     98   // Fixed seven-field response reconstruction never invokes provider getters,
     99   // iterators/toJSON or mutable cached SDK signature markers.
    100   function bindResponse(
    101     template: UnsignedEvent,
    102     response: unknown
    103   ): string | undefined {
    104     try {
    105       if (!response || typeof response !== 'object' || Array.isArray(response))
    106         return undefined;
    107       for (const name of ['pubkey', 'kind', 'created_at', 'content'] as const)
    108         if (own(response, name) !== template[name]) return undefined;
    109       const tags = own(response, 'tags');
    110       if (!Array.isArray(tags) || own(tags, 'length') !== 2) return undefined;
    111       for (let i = 0; i < 2; i++) {
    112         const tag = own(tags, String(i));
    113         if (
    114           !Array.isArray(tag) ||
    115           own(tag, 'length') !== 2 ||
    116           own(tag, '0') !== template.tags[i][0] ||
    117           own(tag, '1') !== template.tags[i][1]
    118         )
    119           return undefined;
    120       }
    121       const id = own(response, 'id'),
    122         sig = own(response, 'sig');
    123       if (
    124         typeof id !== 'string' ||
    125         typeof sig !== 'string' ||
    126         id !== getEventHash(template)
    127       )
    128         return undefined;
    129       const wire = JSON.stringify({ ...template, id, sig });
    130       return verifyEnvelope(wire).ok ? wire : undefined;
    131     } catch {
    132       return undefined;
    133     }
    134   }
    135   async function run(): Promise<Readonly<{ status: string }>> {
    136     if (busy) return { status: 'busy' };
    137     const proof = privateAuthChallenge(connection),
    138       scheduler = browserExtensionScheduler();
    139     if (
    140       !proof ||
    141       !scheduler ||
    142       ['refused', 'unknown', 'stopped'].includes(phase)
    143     )
    144       return { status: 'stopped' };
    145     busy = true;
    146     try {
    147       const result = await runExtensionAction(
    148         scheduler,
    149         { owner: proof.owner, session: proof.session, operation: Symbol() },
    150         () => proof.current() && phase !== 'stopped',
    151         async (job) => {
    152           if (!reservePrivateAuthResponse(connection, proof))
    153             return { status: 'stopped' };
    154           responses++;
    155           const signer = new ExtensionSigner();
    156           const key = await callExtension(job, 'key', () =>
    157             new ExtensionSigner().getPublicKey()
    158           );
    159           if (
    160             proof.current() &&
    161             (key.status === 'denied' ||
    162               (key.status === 'settled' &&
    163                 key.current &&
    164                 (key.value !== proof.owner || !messagingCapabilitiesCurrent())))
    165           )
    166             invalidatePrivateAuthGeneration(connection, proof);
    167           if (
    168             key.status !== 'settled' ||
    169             !key.current ||
    170             key.value !== proof.owner ||
    171             !proof.current()
    172           ) {
    173             close();
    174             return { status: 'stopped' };
    175           }
    176           const time = Math.floor(Date.now() / 1000);
    177           if (!Number.isSafeInteger(time) || time < 0 || !proof.current()) {
    178             close();
    179             return { status: 'stopped' };
    180           }
    181           const template: UnsignedEvent = {
    182             pubkey: proof.owner,
    183             kind: 22242,
    184             created_at: time,
    185             tags: [
    186               ['relay', proof.relay],
    187               ['challenge', proof.challenge]
    188             ],
    189             content: ''
    190           };
    191           const response = await callExtension(job, 'auth', () =>
    192             signer.signEvent(
    193               JSON.parse(JSON.stringify(template)) as UnsignedEvent
    194             )
    195           );
    196           if (
    197             response.status !== 'settled' ||
    198             !response.current ||
    199             !proof.current()
    200           ) {
    201             close();
    202             return {
    203               status: response.status === 'denied' ? 'denied' : 'stopped'
    204             };
    205           }
    206           const wire = bindResponse(template, response.value);
    207           if (!wire || !proof.current()) {
    208             close();
    209             return { status: 'invalid_response' };
    210           }
    211           // The provider can change its selected identity during signing. Fresh
    212           // actual SDK key evidence is required again before the AUTH effect.
    213           const effectKey = await callExtension(job, 'key', () =>
    214             new ExtensionSigner().getPublicKey()
    215           );
    216           if (
    217             proof.current() &&
    218             (effectKey.status === 'denied' ||
    219               (effectKey.status === 'settled' &&
    220                 effectKey.current &&
    221                 (effectKey.value !== proof.owner ||
    222                   !messagingCapabilitiesCurrent())))
    223           )
    224             invalidatePrivateAuthGeneration(connection, proof);
    225           if (
    226             effectKey.status !== 'settled' ||
    227             !effectKey.current ||
    228             effectKey.value !== proof.owner ||
    229             !proof.current()
    230           ) {
    231             close();
    232             return { status: 'stopped' };
    233           }
    234           const approved = Object.freeze({}) as GuardedInboxAuthResponse;
    235           signedResponses.set(approved, {
    236             proof,
    237             wire,
    238             current: () => proof.current() && phase !== 'stopped'
    239           });
    240           const status = await sendPrivateAuthResponse(
    241             connection,
    242             proof,
    243             approved
    244           );
    245           phase =
    246             status === 'accepted'
    247               ? 'accepted'
    248               : status === 'refused'
    249                 ? 'refused'
    250                 : status === 'unknown'
    251                   ? 'unknown'
    252                   : 'stopped';
    253           return { status };
    254         }
    255       );
    256       return 'value' in result &&
    257         result.value &&
    258         (result.status === 'completed' ||
    259           result.value.status === 'refused' ||
    260           result.value.status === 'unknown')
    261         ? result.value
    262         : { status: result.status };
    263     } finally {
    264       busy = false;
    265     }
    266   }
    267   actions.set(token, {
    268     run,
    269     close,
    270     snapshot: () => ({
    271       state:
    272         privateAuthStopped(connection) &&
    273         phase !== 'refused' &&
    274         phase !== 'unknown'
    275           ? 'stopped'
    276           : busy
    277             ? 'signing'
    278             : privateAuthChallenge(connection)
    279               ? 'challenge'
    280               : phase,
    281       responses
    282     })
    283   });
    284   return token;
    285 }
    286 export function inboxAuthSnapshot(action: InboxAuthAction) {
    287   return actions.get(action)?.snapshot();
    288 }
    289 export function closeInboxAuthentication(action: InboxAuthAction): void {
    290   actions.get(action)?.close();
    291 }
    292 export function respondInboxAuthentication(
    293   action: InboxAuthAction
    294 ): Promise<Readonly<{ status: string }>> {
    295   return actions.get(action)?.run() ?? Promise.resolve({ status: 'invalid' });
    296 }