app

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

private-cache-scope.ts (5304B)


      1 import {
      2   privateSessionOwnership,
      3   subscribePrivateSessionClose,
      4   type PrivateSession
      5 } from '../runtime/private-session.ts';
      6 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
      7 import {
      8   PRIVATE_TRANSPORT_BUDGETS,
      9   LOCAL_PERSISTENCE_BUDGETS
     10 } from '../config/budgets.ts';
     11 
     12 declare const cacheBrand: unique symbol;
     13 export type PrivateCacheScope = Readonly<{ [cacheBrand]: true }>;
     14 export type PrivateCachePurpose = 'raw_ciphertext' | 'projection_ownership';
     15 export type PrivateCacheResult =
     16   'accepted' | 'duplicate' | 'conflict' | 'rejected' | 'limit' | 'closed';
     17 type Snapshot = Readonly<{ closed: boolean; count: number; bytes: number }>;
     18 type Controller = {
     19   current(): boolean;
     20   retain(id: string, wire: unknown): PrivateCacheResult;
     21   wire(id: string): string | undefined;
     22   snapshot(): Snapshot;
     23   clear(): void;
     24   close(): void;
     25 };
     26 const scopes = new WeakMap<PrivateCacheScope, Controller>();
     27 const sessions = new WeakMap<
     28   PrivateSession,
     29   Map<PrivateCachePurpose, PrivateCacheScope>
     30 >();
     31 // Internal serialized-memory ownership only. This does not validate a message,
     32 // seal, participant or plaintext projection. Current product use is ciphertext;
     33 // later validated proofs must precede projection admission by its typed owner.
     34 // Primitive JSON strings cannot import SDK verification/decrypt/helper Symbols
     35 // or enter Applesauce module-global memoized references.
     36 export function getPrivateCacheScope(
     37   session: PrivateSession,
     38   purpose: PrivateCachePurpose
     39 ): PrivateCacheScope | undefined {
     40   if (typeof window === 'undefined') return undefined;
     41   const observed = privateSessionOwnership(session);
     42   if (!observed) throw new Error('private_session_invalid');
     43   const capture = observed;
     44   if (purpose !== 'raw_ciphertext' && purpose !== 'projection_ownership')
     45     throw new Error('private_cache_purpose_invalid');
     46   let owned = sessions.get(session);
     47   const prior = owned?.get(purpose);
     48   if (prior) {
     49     if (!controller(prior).current()) throw new Error('private_cache_closed');
     50     return prior;
     51   }
     52   if (!owned) {
     53     owned = new Map();
     54     sessions.set(session, owned);
     55   }
     56   const token = Object.freeze({}) as PrivateCacheScope;
     57   const entries = new Map<string, string>();
     58   let closed = false,
     59     bytes = 0;
     60   let off = () => {};
     61   function close() {
     62     if (closed) return;
     63     closed = true;
     64     entries.clear();
     65     bytes = 0;
     66     off();
     67     // Retained opaque handles no longer keep the old cache, session or closure.
     68     // Returned copies in caller memory cannot be securely erased by JavaScript.
     69     scopes.set(token, {
     70       current: () => false,
     71       retain: () => 'closed',
     72       wire: () => undefined,
     73       snapshot: () => ({ closed: true, count: 0, bytes: 0 }),
     74       clear: () => {},
     75       close: () => {}
     76     });
     77   }
     78   function current() {
     79     if (closed || !capture.current()) {
     80       close();
     81       return false;
     82     }
     83     return true;
     84   }
     85   const state: Controller = {
     86     current,
     87     retain(id, raw) {
     88       if (!current()) return 'closed';
     89       if (
     90         typeof id !== 'string' ||
     91         !/^[0-9a-f]{64}$/.test(id) ||
     92         typeof raw !== 'string' ||
     93         !boundedUtf8(raw, PRIVATE_TRANSPORT_BUDGETS.envelopeBytes)
     94       )
     95         return 'rejected';
     96       let wire: string;
     97       try {
     98         wire = JSON.stringify(JSON.parse(raw));
     99       } catch {
    100         return 'rejected';
    101       }
    102       if (!boundedUtf8(wire, PRIVATE_TRANSPORT_BUDGETS.envelopeBytes))
    103         return 'rejected';
    104       const existing = entries.get(id);
    105       if (existing !== undefined)
    106         return existing === wire ? 'duplicate' : 'conflict';
    107       const size = new TextEncoder().encode(wire).length;
    108       if (
    109         entries.size >= LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes ||
    110         size > LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes - bytes
    111       )
    112         return 'limit';
    113       if (!current()) return 'closed';
    114       entries.set(id, wire);
    115       bytes += size;
    116       return 'accepted';
    117     },
    118     wire: (id) => (current() ? entries.get(id) : undefined),
    119     snapshot: () =>
    120       current()
    121         ? { closed: false, count: entries.size, bytes }
    122         : { closed: true, count: 0, bytes: 0 },
    123     clear() {
    124       if (current()) {
    125         entries.clear();
    126         bytes = 0;
    127       }
    128     },
    129     close
    130   };
    131   scopes.set(token, state);
    132   owned.set(purpose, token);
    133   off = subscribePrivateSessionClose(session, close);
    134   if (!current()) {
    135     close();
    136     throw new Error('private_session_invalid');
    137   }
    138   return token;
    139 }
    140 function controller(scope: PrivateCacheScope): Controller {
    141   const state = scopes.get(scope);
    142   if (!state) throw new Error('private_cache_invalid');
    143   return state;
    144 }
    145 export function retainPrivateCacheWire(
    146   scope: PrivateCacheScope,
    147   id: string,
    148   wire: unknown
    149 ): PrivateCacheResult {
    150   return controller(scope).retain(id, wire);
    151 }
    152 export function privateCacheWire(
    153   scope: PrivateCacheScope,
    154   id: string
    155 ): string | undefined {
    156   return controller(scope).wire(id);
    157 }
    158 export function privateCacheSnapshot(scope: PrivateCacheScope): Snapshot {
    159   return controller(scope).snapshot();
    160 }
    161 export function clearPrivateCacheScope(scope: PrivateCacheScope): void {
    162   controller(scope).clear();
    163 }
    164 export function closePrivateCacheScope(scope: PrivateCacheScope): void {
    165   controller(scope).close();
    166 }