app

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

extension.ts (20645B)


      1 import {
      2   ExtensionSigner,
      3   ExtensionMissingError
      4 } from 'applesauce-signers/signers/extension-signer';
      5 import { canonicalPublicKey } from '../contracts/public-key.ts';
      6 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
      7 import { PUBLIC_INGRESS_BUDGETS } from '../config/budgets.ts';
      8 import {
      9   approvedSigningIdentity,
     10   disposableApprovedTemplate,
     11   bindApprovedResponse,
     12   type ApprovedPublicSigning
     13 } from './approved-signing.ts';
     14 import type { CapturedArtifact } from '../persistence/artifact-records.ts';
     15 import {
     16   bindLatePublicResponse,
     17   type LatePublicArtifact
     18 } from '../runtime/late-results.ts';
     19 import {
     20   callOwnedExtension,
     21   publicEffectLeaseCurrent,
     22   publicEffectSnapshot,
     23   markOwnedSignaturePending,
     24   type PublicEffectLease,
     25   type PublicEffectCapture
     26 } from '../runtime/effect-ownership.ts';
     27 
     28 export type ApprovedSignResult =
     29   | Readonly<{ status: 'signed'; artifact: CapturedArtifact }>
     30   | Readonly<{ status: 'unknown'; late?: LatePublicArtifact }>
     31   | Readonly<{
     32       status:
     33         | 'invalid_approval'
     34         | 'invalid_ownership'
     35         | 'unavailable'
     36         | 'busy'
     37         | 'stale'
     38         | 'refused'
     39         | 'mismatch';
     40     }>;
     41 
     42 import {
     43   browserExtensionScheduler,
     44   runExtensionAction,
     45   callExtension,
     46   markExtensionWaitExpired,
     47   type ExtensionAction,
     48   type ExtensionCallKind
     49 } from './extension-scheduler.ts';
     50 
     51 declare const adapterBrand: unique symbol;
     52 export type ExtensionAdapter = Readonly<{ [adapterBrand]: true }>;
     53 export type ExtensionGuestReason =
     54   | 'disconnected'
     55   | 'missing'
     56   | 'refused'
     57   | 'invalid_key'
     58   | 'changed_key'
     59   | 'unavailable';
     60 export type ExtensionSnapshot = (
     61   | Readonly<{ state: 'guest'; reason: ExtensionGuestReason }>
     62   | Readonly<{ state: 'pending'; action: 'connect' | 'recheck' | 'probe' }>
     63   | Readonly<{
     64       state: 'connected';
     65       publicKey: string;
     66       signingCandidate: boolean;
     67       messaging: 'not_probed' | 'unsupported' | 'refused' | 'capable';
     68     }>
     69 ) &
     70   Readonly<{ admission?: 'busy' }>;
     71 
     72 declare global {
     73   interface Window {
     74     nostr?: unknown;
     75   }
     76 }
     77 type Controller = {
     78   snapshot(): ExtensionSnapshot;
     79   disconnect(): void;
     80   connect(): Promise<ExtensionSnapshot>;
     81   recheck(): Promise<ExtensionSnapshot>;
     82   probe(review: unknown): Promise<ExtensionSnapshot>;
     83   capture(): PublicEffectCapture | undefined;
     84   captureMessaging(): PublicEffectCapture | undefined;
     85   subscribeInvalidation(listener: () => void): () => void;
     86   expire(approval: ApprovedPublicSigning, lease: PublicEffectLease): void;
     87   sign(
     88     approval: ApprovedPublicSigning,
     89     lease: PublicEffectLease
     90   ): Promise<ApprovedSignResult>;
     91 };
     92 const adapters = new WeakMap<ExtensionAdapter, Controller>();
     93 function present(): Readonly<{ signingCandidate: boolean }> | undefined {
     94   if (typeof window === 'undefined') return undefined;
     95   const provider: unknown = window.nostr;
     96   if (
     97     (typeof provider !== 'object' && typeof provider !== 'function') ||
     98     provider === null
     99   )
    100     return undefined;
    101   const value = provider as { getPublicKey?: unknown; signEvent?: unknown };
    102   return typeof value.getPublicKey === 'function'
    103     ? { signingCandidate: typeof value.signEvent === 'function' }
    104     : undefined;
    105 }
    106 async function invokeExtension<T>(
    107   action: ExtensionAction | undefined,
    108   kind: ExtensionCallKind,
    109   work: () => Promise<T>
    110 ): Promise<T> {
    111   if (!action) throw new Error('extension_unavailable');
    112   let missing = false;
    113   const result = await callExtension(action, kind, async () => {
    114     try {
    115       return await work();
    116     } catch (error) {
    117       missing = error instanceof ExtensionMissingError;
    118       throw error;
    119     }
    120   });
    121   if (result.status === 'settled' && result.current) return result.value;
    122   if (missing) throw new ExtensionMissingError('extension_missing');
    123   throw new Error('extension_' + result.status);
    124 }
    125 async function freshKey(
    126   current: () => boolean,
    127   action: ExtensionAction | undefined
    128 ): Promise<string | undefined> {
    129   if (!current()) return undefined;
    130   const signer = new ExtensionSigner();
    131   // This SDK invocation admits one NIP-07 call. Its internal getters and
    132   // permission wait cannot universally be interrupted; callers fence the result.
    133   if (!current()) return undefined;
    134   return canonicalPublicKey(
    135     await invokeExtension(action, 'key', () => signer.getPublicKey())
    136   );
    137 }
    138 // Lexically owned per-adapter state; no mutable opaque receiver, browser handle
    139 // or imported signer escapes through the WeakMap/controller boundary.
    140 export function createExtensionAdapter(): ExtensionAdapter {
    141   const invalidations = new Map<symbol, () => void>();
    142   function notifyInvalidation() {
    143     for (const listener of invalidations.values()) {
    144       try {
    145         listener();
    146       } catch {
    147         /* Cleanup failure stays owned by its scope. */
    148       }
    149     }
    150   }
    151   let key: string | null = null,
    152     signingCandidate = false;
    153   let messaging: 'not_probed' | 'unsupported' | 'refused' | 'capable' =
    154     'not_probed';
    155   let reason: ExtensionGuestReason = 'disconnected';
    156   let pending: 'connect' | 'recheck' | 'probe' | null = null;
    157   let signing = false;
    158   let activeSigning: Readonly<{
    159     approval: ApprovedPublicSigning;
    160     lease: PublicEffectLease;
    161     action: ExtensionAction;
    162   }> | null = null;
    163   let generation = Symbol(),
    164     cancelled = false;
    165   function snapshot(): ExtensionSnapshot {
    166     if (pending && !cancelled) return { state: 'pending', action: pending };
    167     return key
    168       ? { state: 'connected', publicKey: key, signingCandidate, messaging }
    169       : { state: 'guest', reason };
    170   }
    171   function guest(nextReason: ExtensionGuestReason) {
    172     // An observed account loss cannot later revive an old capture, including
    173     // a reconnect to the same key. Rotate before clearing the observed owner.
    174     if (key !== null) generation = Symbol();
    175     key = null;
    176     signingCandidate = false;
    177     messaging = 'not_probed';
    178     reason = nextReason;
    179     notifyInvalidation();
    180   }
    181   function disconnect() {
    182     generation = Symbol();
    183     cancelled = true;
    184     guest(
    185       'disconnected'
    186     ); /* Retain pending slot until actual promise settlement. */
    187   }
    188   async function run(
    189     action: 'connect' | 'recheck' | 'probe',
    190     work: (
    191       current: () => boolean,
    192       action: ExtensionAction | undefined
    193     ) => Promise<void>
    194   ): Promise<ExtensionSnapshot> {
    195     if (pending || signing) return { ...snapshot(), admission: 'busy' };
    196     let busy = false;
    197     const original = generation;
    198     pending = action;
    199     cancelled = false;
    200     const current = () => generation === original && !cancelled;
    201     try {
    202       const scheduler = browserExtensionScheduler();
    203       if (scheduler) {
    204         // One shared page slot for all sessions and effect kinds. Busy performs
    205         // no provider work and never schedules an automatic retry.
    206         const admitted = await runExtensionAction(
    207           scheduler,
    208           { owner: key, session: original, operation: Symbol() },
    209           current,
    210           async (lease) => {
    211             try {
    212               await work(current, lease);
    213             } catch (error) {
    214               if (current())
    215                 guest(
    216                   error instanceof ExtensionMissingError ? 'missing' : 'refused'
    217                 );
    218               throw error;
    219             }
    220           }
    221         );
    222         busy = admitted.status === 'busy';
    223       } else await work(current, undefined);
    224     } catch (error) {
    225       if (current())
    226         guest(error instanceof ExtensionMissingError ? 'missing' : 'refused');
    227     } finally {
    228       pending = null;
    229       notifyInvalidation();
    230     }
    231     return busy ? { ...snapshot(), admission: 'busy' } : snapshot();
    232   }
    233   function connect(): Promise<ExtensionSnapshot> {
    234     return run('connect', async (current, action) => {
    235       if (typeof window === 'undefined') {
    236         guest('unavailable');
    237         return;
    238       }
    239       const candidate = present();
    240       if (!current()) return;
    241       if (!candidate) {
    242         guest('missing');
    243         return;
    244       }
    245       const owner = await freshKey(current, action);
    246       if (!current()) return;
    247       if (!owner) {
    248         guest('invalid_key');
    249         return;
    250       }
    251       if (key && owner !== key) {
    252         guest('changed_key');
    253         return;
    254       }
    255       const resolvedCandidate = present();
    256       if (!current()) return;
    257       if (!resolvedCandidate) {
    258         guest('missing');
    259         return;
    260       }
    261       key = owner;
    262       signingCandidate = resolvedCandidate.signingCandidate;
    263       messaging = 'not_probed';
    264     });
    265   }
    266   function recheck(): Promise<ExtensionSnapshot> {
    267     if (!key) return Promise.resolve(snapshot());
    268     return run('recheck', async (current, action) => {
    269       const owner = await freshKey(current, action);
    270       if (!current()) return;
    271       if (!owner) {
    272         guest('invalid_key');
    273         return;
    274       }
    275       if (owner !== key) {
    276         guest('changed_key');
    277         return;
    278       }
    279       const candidate = present();
    280       if (!current()) return;
    281       if (!candidate) {
    282         guest('missing');
    283         return;
    284       }
    285       signingCandidate = candidate.signingCandidate;
    286       if (messaging === 'capable') {
    287         const cipher = new ExtensionSigner().nip44;
    288         if (!current()) return;
    289         if (!cipher) {
    290           messaging = 'unsupported';
    291           return;
    292         }
    293         const encrypt = cipher.encrypt;
    294         if (!current()) return;
    295         const decrypt = cipher.decrypt;
    296         if (!current()) return;
    297         if (typeof encrypt !== 'function' || typeof decrypt !== 'function')
    298           messaging = 'unsupported';
    299       }
    300     });
    301   }
    302   function probe(review: unknown): Promise<ExtensionSnapshot> {
    303     if (!key || review !== 'reviewed_self_copy')
    304       return Promise.resolve(snapshot());
    305     return run('probe', async (current, action) => {
    306       const owner = key;
    307       if (!owner) return;
    308       const checked = await freshKey(current, action);
    309       if (!current()) return;
    310       if (checked !== owner) {
    311         guest(checked ? 'changed_key' : 'invalid_key');
    312         return;
    313       }
    314       const signer = new ExtensionSigner(),
    315         cipher = signer.nip44;
    316       if (!current()) return;
    317       if (!cipher) {
    318         messaging = 'unsupported';
    319         return;
    320       }
    321       const encryptMethod = cipher.encrypt;
    322       if (!current()) return;
    323       const decryptMethod = cipher.decrypt;
    324       if (!current()) return;
    325       if (
    326         typeof encryptMethod !== 'function' ||
    327         typeof decryptMethod !== 'function'
    328       ) {
    329         messaging = 'unsupported';
    330         return;
    331       }
    332       const encrypt = encryptMethod.bind(cipher);
    333       if (!current()) return;
    334       const decrypt = decryptMethod.bind(cipher);
    335       if (!current()) return;
    336       const text = 'HarvestCircle self-copy check:' + crypto.randomUUID();
    337       let encrypted: unknown, decrypted: unknown;
    338       try {
    339         if (!current()) return;
    340         encrypted = await invokeExtension(action, 'encrypt', () =>
    341           encrypt(owner, text)
    342         );
    343         if (!current()) return;
    344         if (
    345           typeof encrypted !== 'string' ||
    346           !boundedUtf8(encrypted, PUBLIC_INGRESS_BUDGETS.eventBytes)
    347         ) {
    348           messaging = 'refused';
    349           return;
    350         }
    351         if (!current()) return;
    352         decrypted = await invokeExtension(action, 'decrypt', () =>
    353           decrypt(owner, encrypted as string)
    354         );
    355       } catch {
    356         if (current()) messaging = 'refused';
    357         return;
    358       }
    359       if (!current()) return;
    360       if (decrypted !== text) {
    361         messaging = 'refused';
    362         return;
    363       }
    364       const after = await freshKey(current, action);
    365       if (!current()) return;
    366       if (after !== owner) {
    367         guest(after ? 'changed_key' : 'invalid_key');
    368         return;
    369       }
    370       const candidate = present();
    371       if (!current()) return;
    372       if (!candidate) {
    373         guest('missing');
    374         return;
    375       }
    376       signingCandidate = candidate.signingCandidate;
    377       const finalCipher = new ExtensionSigner().nip44;
    378       if (!current()) return;
    379       if (!finalCipher) {
    380         messaging = 'unsupported';
    381         return;
    382       }
    383       const finalEncrypt = finalCipher.encrypt;
    384       if (!current()) return;
    385       const finalDecrypt = finalCipher.decrypt;
    386       if (!current()) return;
    387       if (
    388         typeof finalEncrypt !== 'function' ||
    389         typeof finalDecrypt !== 'function'
    390       ) {
    391         messaging = 'unsupported';
    392         return;
    393       }
    394       messaging = 'capable';
    395     });
    396   }
    397   async function sign(
    398     approval: ApprovedPublicSigning,
    399     lease: PublicEffectLease
    400   ): Promise<ApprovedSignResult> {
    401     const captured = approvedSigningIdentity(approval);
    402     if (!captured) return { status: 'invalid_approval' };
    403     if (pending || signing) return { status: 'busy' };
    404     if (
    405       !key ||
    406       key !== captured.owner ||
    407       !signingCandidate ||
    408       typeof window === 'undefined'
    409     )
    410       return { status: 'unavailable' };
    411     const original = generation,
    412       owner = key;
    413     const authority = {
    414       owner,
    415       id: captured.id,
    416       recordWire: captured.recordWire,
    417       session: original
    418     };
    419     if (!publicEffectLeaseCurrent(lease, authority))
    420       return { status: 'invalid_ownership' };
    421     const current = () =>
    422       generation === original &&
    423       !cancelled &&
    424       key === owner &&
    425       publicEffectLeaseCurrent(lease, authority);
    426     signing = true;
    427     let late: LatePublicArtifact | undefined;
    428     function lost(): ApprovedSignResult {
    429       return publicEffectSnapshot(lease)?.state === 'unknown'
    430         ? { status: 'unknown', ...(late ? { late } : {}) }
    431         : { status: 'stale' };
    432     }
    433     try {
    434       const owned = await callOwnedExtension(
    435         lease,
    436         authority,
    437         async (): Promise<ApprovedSignResult> => {
    438           const scheduler = browserExtensionScheduler();
    439           if (!scheduler) return { status: 'unavailable' };
    440           const admitted = await runExtensionAction(
    441             scheduler,
    442             { owner, session: original, operation: Symbol() },
    443             current,
    444             async (action): Promise<ApprovedSignResult> => {
    445               activeSigning = { approval, lease, action };
    446               const before = await freshKey(current, action);
    447               if (!current()) return { status: 'stale' };
    448               if (before !== owner) {
    449                 guest(before ? 'changed_key' : 'invalid_key');
    450                 return { status: 'stale' };
    451               }
    452               const disposable = disposableApprovedTemplate(approval);
    453               if (!disposable) return { status: 'invalid_approval' };
    454               const signer = new ExtensionSigner();
    455               if (!current() || !markOwnedSignaturePending(lease))
    456                 return { status: 'stale' };
    457               const response: unknown = await invokeExtension(
    458                 action,
    459                 'sign',
    460                 async () => {
    461                   const raw: unknown = await signer.signEvent(disposable);
    462                   // Retain only bounded independently verified original public
    463                   // fields inside the actual admitted SDK callback, even after
    464                   // its owner/view/wait generation was invalidated. No new call.
    465                   late = bindLatePublicResponse(approval, raw, original);
    466                   return raw;
    467                 }
    468               );
    469               if (!current()) return { status: 'stale' };
    470               const artifact = bindApprovedResponse(approval, response);
    471               if (!artifact) return { status: 'mismatch' };
    472               const after = await freshKey(current, action);
    473               if (!current()) return { status: 'stale' };
    474               if (after !== owner) {
    475                 guest(after ? 'changed_key' : 'invalid_key');
    476                 return { status: 'stale' };
    477               }
    478               return { status: 'signed', artifact };
    479             }
    480           );
    481           if (admitted.status === 'busy') return { status: 'busy' };
    482           if (!current()) return { status: 'stale' };
    483           return 'value' in admitted && admitted.value
    484             ? admitted.value
    485             : { status: admitted.status === 'denied' ? 'refused' : 'stale' };
    486         }
    487       );
    488       if (owned.status === 'settled')
    489         return owned.current ? owned.value : lost();
    490       if (owned.status === 'unknown')
    491         return { status: 'unknown', ...(late ? { late } : {}) };
    492       return {
    493         status:
    494           owned.status === 'invalid'
    495             ? 'invalid_ownership'
    496             : owned.status === 'stopped'
    497               ? 'stale'
    498               : owned.status
    499       };
    500     } catch {
    501       return current() ? { status: 'refused' } : lost();
    502     } finally {
    503       activeSigning = null;
    504       signing = false;
    505     }
    506   }
    507   const adapter = Object.freeze({}) as ExtensionAdapter;
    508   adapters.set(adapter, {
    509     snapshot,
    510     disconnect,
    511     connect,
    512     recheck,
    513     probe,
    514     capture() {
    515       if (!key || cancelled) return undefined;
    516       const owner = key,
    517         original = generation;
    518       return {
    519         owner,
    520         session: original,
    521         current: () => generation === original && !cancelled && key === owner
    522       };
    523     },
    524     captureMessaging() {
    525       if (
    526         !key ||
    527         cancelled ||
    528         !signingCandidate ||
    529         messaging !== 'capable' ||
    530         pending ||
    531         signing
    532       )
    533         return undefined;
    534       const owner = key,
    535         original = generation;
    536       return {
    537         owner,
    538         session: original,
    539         current: () =>
    540           generation === original &&
    541           !cancelled &&
    542           key === owner &&
    543           signingCandidate &&
    544           messaging === 'capable'
    545       };
    546     },
    547     subscribeInvalidation(listener) {
    548       const id = Symbol();
    549       invalidations.set(id, listener);
    550       return () => {
    551         invalidations.delete(id);
    552       };
    553     },
    554     sign,
    555     expire(approval, lease) {
    556       if (activeSigning?.approval === approval && activeSigning.lease === lease)
    557         markExtensionWaitExpired(activeSigning.action);
    558     }
    559   });
    560   return adapter;
    561 }
    562 export function extensionSnapshot(
    563   adapter: ExtensionAdapter
    564 ): ExtensionSnapshot {
    565   return (
    566     adapters.get(adapter)?.snapshot() ?? {
    567       state: 'guest',
    568       reason: 'unavailable'
    569     }
    570   );
    571 }
    572 export function disconnectExtensionAdapter(adapter: ExtensionAdapter): void {
    573   adapters.get(adapter)?.disconnect();
    574 }
    575 // Explicit action methods only; constructor/import never request an extension.
    576 export function connectExtensionAdapter(
    577   adapter: ExtensionAdapter
    578 ): Promise<ExtensionSnapshot> {
    579   return (
    580     adapters.get(adapter)?.connect() ??
    581     Promise.resolve({ state: 'guest', reason: 'unavailable' })
    582   );
    583 }
    584 export function recheckExtensionAdapter(
    585   adapter: ExtensionAdapter
    586 ): Promise<ExtensionSnapshot> {
    587   return (
    588     adapters.get(adapter)?.recheck() ??
    589     Promise.resolve({ state: 'guest', reason: 'unavailable' })
    590   );
    591 }
    592 // Only reviewed disposable self-copy text. No caller body, NIP04 fallback, signer
    593 // object, setup, EVENT or AUTH is exposed. Signing shapes are candidates only.
    594 export function probeExtensionAdapter(
    595   adapter: ExtensionAdapter,
    596   review: unknown
    597 ): Promise<ExtensionSnapshot> {
    598   return (
    599     adapters.get(adapter)?.probe(review) ??
    600     Promise.resolve({ state: 'guest', reason: 'unavailable' })
    601   );
    602 }
    603 // Internal operation capability only. UI identity sessions do not expose this
    604 // adapter or an unrestricted raw-event signing/publishing function.
    605 export function signApprovedExtensionAdapter(
    606   adapter: ExtensionAdapter,
    607   approval: ApprovedPublicSigning,
    608   lease: PublicEffectLease
    609 ): Promise<ApprovedSignResult> {
    610   return (
    611     adapters.get(adapter)?.sign(approval, lease) ??
    612     Promise.resolve({ status: 'unavailable' })
    613   );
    614 }
    615 export function extensionOwnershipCapture(
    616   adapter: ExtensionAdapter
    617 ): PublicEffectCapture | undefined {
    618   return adapters.get(adapter)?.capture();
    619 }
    620 export function extensionMessagingOwnershipCapture(
    621   adapter: ExtensionAdapter
    622 ): PublicEffectCapture | undefined {
    623   return adapters.get(adapter)?.captureMessaging();
    624 }
    625 export function subscribeExtensionInvalidation(
    626   adapter: ExtensionAdapter,
    627   listener: () => void
    628 ): () => void {
    629   return adapters.get(adapter)?.subscribeInvalidation(listener) ?? (() => {});
    630 }
    631 // Internal exact original operation port. Expiry pauses the real scheduler;
    632 // neither this method nor a UI timeout pretends to cancel the SDK promise.
    633 export function markApprovedSigningWaitExpired(
    634   adapter: ExtensionAdapter,
    635   approval: ApprovedPublicSigning,
    636   lease: PublicEffectLease
    637 ): void {
    638   adapters.get(adapter)?.expire(approval, lease);
    639 }