app

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

verified-envelope.ts (5775B)


      1 import {
      2   getEventHash,
      3   verifyEvent,
      4   type NostrEvent
      5 } from 'applesauce-core/helpers';
      6 import { PUBLIC_INGRESS_BUDGETS } from '../config/budgets.ts';
      7 import { boundedEnvelopeNumbers } from './envelope-bounds.ts';
      8 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
      9 
     10 declare const verified: unique symbol;
     11 export type VerifiedEnvelope = Readonly<{ readonly [verified]: true }>;
     12 export type EnvelopeFailure = Readonly<{
     13   code: 'envelope_invalid' | 'event_id_mismatch' | 'signature_invalid';
     14   message: string;
     15 }>;
     16 // Weak ownership bounds lifetime to callers. Retained bytes cannot be mutated
     17 // through detached snapshots, nor forged by a type assertion or SDK cache flag.
     18 const snapshots = new WeakMap<VerifiedEnvelope, string>();
     19 const invalid: EnvelopeFailure = Object.freeze({
     20   code: 'envelope_invalid',
     21   message: 'invalid or unsupported bounded NIP-01 envelope'
     22 });
     23 export function boundedEnvelopeTags(tags: unknown): tags is string[][] {
     24   if (!Array.isArray(tags) || tags.length > 1024) return false;
     25   let elements = 0;
     26   let bytes = 0;
     27   const encoder = new TextEncoder();
     28   for (const tag of tags) {
     29     if (
     30       !Array.isArray(tag) ||
     31       tag.length === 0 ||
     32       typeof tag[0] !== 'string' ||
     33       tag[0].length === 0 ||
     34       /\p{Cc}/u.test(tag[0])
     35     )
     36       return false;
     37     elements += tag.length;
     38     if (elements > 4096) return false;
     39     for (const element of tag) {
     40       if (typeof element !== 'string' || !boundedUtf8(element, 4096))
     41         return false;
     42       bytes += encoder.encode(element).length;
     43       if (bytes > 131072) return false;
     44     }
     45   }
     46   return true;
     47 }
     48 export function verifyEnvelope(
     49   raw: unknown
     50 ):
     51   | Readonly<{ ok: true; value: VerifiedEnvelope }>
     52   | Readonly<{ ok: false; error: EnvelopeFailure }> {
     53   if (
     54     typeof raw !== 'string' ||
     55     !boundedUtf8(raw, PUBLIC_INGRESS_BUDGETS.eventBytes)
     56   )
     57     return { ok: false, error: invalid };
     58   try {
     59     // Parse a fresh bounded JSON object: caller getters and cached SDK symbols
     60     // never cross verification. Generic SDK helpers own hashing and crypto.
     61     const unsupportedNumbers = new WeakMap<object, boolean>();
     62     const event: unknown = JSON.parse(
     63       raw,
     64       function (
     65         this: object,
     66         key: string,
     67         value: unknown,
     68         context?: { source?: string }
     69       ) {
     70         if (
     71           (key === 'kind' || key === 'created_at') &&
     72           typeof value === 'number' &&
     73           (context?.source === undefined || !/^[0-9]+$/u.test(context.source))
     74         )
     75           unsupportedNumbers.set(this, true);
     76         if (
     77           !key.isWellFormed() ||
     78           (typeof value === 'string' && !value.isWellFormed())
     79         )
     80           throw new Error('Invalid Unicode in bounded envelope');
     81         if (typeof value === 'number' && !Number.isFinite(value))
     82           throw new Error('Nonfinite number in bounded envelope');
     83         return value;
     84       }
     85     );
     86     if (
     87       typeof event !== 'object' ||
     88       event === null ||
     89       Array.isArray(event) ||
     90       !('id' in event) ||
     91       !('pubkey' in event) ||
     92       !('sig' in event) ||
     93       !('kind' in event) ||
     94       !('created_at' in event) ||
     95       !('tags' in event) ||
     96       !('content' in event)
     97     )
     98       return { ok: false, error: invalid };
     99     if (
    100       typeof event.id !== 'string' ||
    101       !/^[0-9a-f]{64}$/u.test(event.id) ||
    102       typeof event.pubkey !== 'string' ||
    103       !/^[0-9a-f]{64}$/u.test(event.pubkey) ||
    104       typeof event.sig !== 'string' ||
    105       !/^[0-9a-f]{128}$/u.test(event.sig) ||
    106       !boundedEnvelopeNumbers(event.kind, event.created_at) ||
    107       !boundedEnvelopeTags(event.tags) ||
    108       typeof event.content !== 'string' ||
    109       !boundedUtf8(event.content, 131072)
    110     )
    111       return { ok: false, error: invalid };
    112     if (unsupportedNumbers.has(event)) return { ok: false, error: invalid };
    113     const fields = event as Record<string, unknown>;
    114     let extraFields = 0;
    115     let extraBytes = 0;
    116     const encoder = new TextEncoder();
    117     for (const name in fields) {
    118       if (
    119         [
    120           'id',
    121           'pubkey',
    122           'sig',
    123           'kind',
    124           'created_at',
    125           'tags',
    126           'content'
    127         ].includes(name)
    128       )
    129         continue;
    130       extraFields++;
    131       const encoded = JSON.stringify(fields[name]);
    132       if (!name.isWellFormed() || encoded === undefined)
    133         return { ok: false, error: invalid };
    134       extraBytes +=
    135         encoder.encode(JSON.stringify(name)).length +
    136         1 +
    137         encoder.encode(encoded).length;
    138       if (extraFields > 64 || extraBytes > 65536)
    139         return { ok: false, error: invalid };
    140     }
    141     const candidate = event as NostrEvent;
    142     if (getEventHash(candidate) !== candidate.id)
    143       return {
    144         ok: false,
    145         error: {
    146           code: 'event_id_mismatch',
    147           message: 'NIP-01 event id does not match canonical content'
    148         }
    149       };
    150     if (!verifyEvent(candidate))
    151       return {
    152         ok: false,
    153         error: {
    154           code: 'signature_invalid',
    155           message: 'invalid NIP-01 event signature'
    156         }
    157       };
    158     const token = Object.freeze({}) as VerifiedEnvelope;
    159     snapshots.set(token, raw);
    160     return { ok: true, value: token };
    161   } catch {
    162     return { ok: false, error: invalid };
    163   }
    164 }
    165 export function verifiedEnvelopeSnapshot(
    166   token: VerifiedEnvelope
    167 ): NostrEvent | undefined {
    168   const raw = snapshots.get(token);
    169   return raw === undefined ? undefined : (JSON.parse(raw) as NostrEvent);
    170 }
    171 
    172 // Genuine proof-owned input only. SDK object ingress records reconstructed
    173 // decoded JSON; callers must not mislabel that as original transport bytes.
    174 export function verifiedEnvelopeWire(
    175   token: VerifiedEnvelope
    176 ): string | undefined {
    177   return snapshots.get(token);
    178 }