app

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

ingress.ts (7666B)


      1 import { PUBLIC_INGRESS_BUDGETS } from '../config/budgets.ts';
      2 import { boundedEnvelopeNumbers } from './envelope-bounds.ts';
      3 import { decodedInboxWire } from './decoded-inbox-wire.ts';
      4 import {
      5   boundedEnvelopeTags,
      6   verifyEnvelope,
      7   verifiedEnvelopeSnapshot,
      8   type VerifiedEnvelope
      9 } from './verified-envelope.ts';
     10 
     11 declare const ingressOwner: unique symbol;
     12 export type PublicIngress = Readonly<{ readonly [ingressOwner]: true }>;
     13 export type IngressResult =
     14   | Readonly<{ status: 'accepted' | 'duplicate'; value: VerifiedEnvelope }>
     15   | Readonly<{ status: 'rejected' | 'limit' }>;
     16 export type IngressStats = Readonly<{
     17   deliveries: number;
     18   chargedBytes: number;
     19   stopped: boolean;
     20 }>;
     21 interface Owner {
     22   readonly admit: (input: unknown, inbox?: boolean) => IngressResult;
     23   readonly stats: () => IngressStats;
     24 }
     25 const owners = new WeakMap<PublicIngress, Owner>();
     26 const encoder = new TextEncoder();
     27 
     28 // Read only own data properties. SDK cache symbols, getters, inherited fields,
     29 // toJSON and iterator overrides cannot cross into a verified snapshot.
     30 function ownData(
     31   input: object,
     32   name: string,
     33   assertActive: () => void
     34 ): unknown {
     35   assertActive();
     36   const descriptor = Object.getOwnPropertyDescriptor(input, name);
     37   assertActive();
     38   if (!descriptor || !('value' in descriptor))
     39     throw new Error('candidate_invalid');
     40   return descriptor.value;
     41 }
     42 function freshTags(
     43   input: unknown,
     44   assertActive: () => void
     45 ): string[][] | undefined {
     46   if (!Array.isArray(input)) return undefined;
     47   const length = ownData(input, 'length', assertActive);
     48   if (
     49     typeof length !== 'number' ||
     50     !Number.isSafeInteger(length) ||
     51     length < 0 ||
     52     length > 1024
     53   )
     54     return undefined;
     55   let elements = 0;
     56   const tags = Array.from({ length }, (_, index) => {
     57     const row = ownData(input, String(index), assertActive);
     58     if (!Array.isArray(row)) throw new Error('candidate_invalid');
     59     const width = ownData(row, 'length', assertActive);
     60     if (typeof width !== 'number' || !Number.isSafeInteger(width) || width < 1)
     61       throw new Error('candidate_invalid');
     62     elements += width;
     63     if (elements > 4096) throw new Error('candidate_invalid');
     64     return Array.from({ length: width }, (_, column) => {
     65       const element = ownData(row, String(column), assertActive);
     66       if (typeof element !== 'string' || element.length > 4096)
     67         throw new Error('candidate_invalid');
     68       return element;
     69     });
     70   });
     71   return boundedEnvelopeTags(tags) ? tags : undefined;
     72 }
     73 function reconstructedWire(
     74   input: unknown,
     75   assertActive: () => void
     76 ): string | undefined {
     77   try {
     78     assertActive();
     79     if (!input || typeof input !== 'object' || Array.isArray(input))
     80       return undefined;
     81     const id = ownData(input, 'id', assertActive);
     82     const pubkey = ownData(input, 'pubkey', assertActive);
     83     const sig = ownData(input, 'sig', assertActive);
     84     const kind = ownData(input, 'kind', assertActive);
     85     const createdAt = ownData(input, 'created_at', assertActive);
     86     const content = ownData(input, 'content', assertActive);
     87     if (
     88       typeof id !== 'string' ||
     89       !/^[0-9a-f]{64}$/u.test(id) ||
     90       typeof pubkey !== 'string' ||
     91       !/^[0-9a-f]{64}$/u.test(pubkey) ||
     92       typeof sig !== 'string' ||
     93       !/^[0-9a-f]{128}$/u.test(sig) ||
     94       !boundedEnvelopeNumbers(kind, createdAt) ||
     95       typeof content !== 'string' ||
     96       content.length > 131072
     97     )
     98       return undefined;
     99     const tags = freshTags(ownData(input, 'tags', assertActive), assertActive);
    100     if (!tags) return undefined;
    101     return JSON.stringify({
    102       id,
    103       pubkey,
    104       sig,
    105       kind,
    106       created_at: createdAt,
    107       tags,
    108       content
    109     });
    110   } catch {
    111     return undefined;
    112   }
    113 }
    114 
    115 // One owner is shared by a public run's primary and auxiliary candidates.
    116 // These are post-parse logical application bounds. The selected SDK exposes
    117 // parsed events, not a qualified raw-frame hook or preallocation guarantee.
    118 export function createPublicIngress(): PublicIngress {
    119   const token = Object.freeze({}) as PublicIngress;
    120   const seen = new Map<string, true>();
    121   let deliveries = 0;
    122   let chargedBytes = 0;
    123   let stopped = false;
    124   let busy = false;
    125   const assertActive = () => {
    126     if (stopped) throw new Error('candidate_invalid');
    127   };
    128   const charge = (bytes: number): boolean => {
    129     if (bytes > PUBLIC_INGRESS_BUDGETS.processedBytes - chargedBytes) {
    130       chargedBytes = PUBLIC_INGRESS_BUDGETS.processedBytes;
    131       stopped = true;
    132       return false;
    133     }
    134     chargedBytes += bytes;
    135     if (chargedBytes === PUBLIC_INGRESS_BUDGETS.processedBytes) stopped = true;
    136     return true;
    137   };
    138   owners.set(token, {
    139     stats: () =>
    140       Object.freeze({
    141         deliveries: deliveries,
    142         chargedBytes: chargedBytes,
    143         stopped: stopped
    144       }),
    145     admit(input, inbox = false) {
    146       if (stopped || deliveries >= PUBLIC_INGRESS_BUDGETS.deliveries) {
    147         stopped = true;
    148         return { status: 'limit' };
    149       }
    150       deliveries++;
    151       // Reserve entry before descriptor traps can reenter this owner. Refuse
    152       // nested admission without reflecting again; retain bounded charges.
    153       if (busy) {
    154         charge(PUBLIC_INGRESS_BUDGETS.eventBytes + 1);
    155         stopped = true;
    156         return { status: 'limit' };
    157       }
    158       busy = true;
    159       try {
    160         const rawAvailable = typeof input === 'string';
    161         const wire = rawAvailable
    162           ? input
    163           : inbox
    164             ? decodedInboxWire(input, assertActive)
    165             : reconstructedWire(input, assertActive);
    166         if (stopped) {
    167           charge(PUBLIC_INGRESS_BUDGETS.eventBytes + 1);
    168           return { status: 'limit' };
    169         }
    170         // Oversized raw input and unmeasurable rejected objects reserve the
    171         // event ceiling plus one. Decoded fields charge actual reconstructed
    172         // UTF8 JSON including expansion; original SDK frame bytes are unknown.
    173         const bytes =
    174           wire === undefined ||
    175           (rawAvailable && wire.length > PUBLIC_INGRESS_BUDGETS.eventBytes)
    176             ? PUBLIC_INGRESS_BUDGETS.eventBytes + 1
    177             : encoder.encode(wire).length;
    178         if (!charge(bytes)) return { status: 'limit' };
    179         if (deliveries === PUBLIC_INGRESS_BUDGETS.deliveries) stopped = true;
    180         // The inclusive last reserved candidate may finish. Subsequent entry
    181         // is already blocked by either cap; reentrant interruption aborts above.
    182         if (wire === undefined || bytes > PUBLIC_INGRESS_BUDGETS.eventBytes)
    183           return { status: 'rejected' };
    184         const result = verifyEnvelope(wire);
    185         if (!result.ok) return { status: 'rejected' };
    186         const event = verifiedEnvelopeSnapshot(result.value);
    187         if (!event) return { status: 'rejected' };
    188         // Dedup does not erase freshly verified per-source observation proof.
    189         if (seen.has(event.id))
    190           return { status: 'duplicate', value: result.value };
    191         seen.set(event.id, true);
    192         return { status: 'accepted', value: result.value };
    193       } finally {
    194         busy = false;
    195       }
    196     }
    197   });
    198   return token;
    199 }
    200 function ownerOf(token: PublicIngress): Owner {
    201   const owner = owners.get(token);
    202   if (!owner) throw new Error('public_ingress_invalid');
    203   return owner;
    204 }
    205 export function admitPublicEvent(
    206   token: PublicIngress,
    207   input: unknown
    208 ): IngressResult {
    209   return ownerOf(token).admit(input);
    210 }
    211 export function publicIngressStats(token: PublicIngress): IngressStats {
    212   return ownerOf(token).stats();
    213 }
    214 
    215 export function admitInboxEvent(
    216   token: PublicIngress,
    217   input: unknown
    218 ): IngressResult {
    219   return ownerOf(token).admit(input, true);
    220 }