app

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

approved-signing.ts (6529B)


      1 import type { UnsignedEvent } from 'applesauce-core/helpers';
      2 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
      3 import {
      4   publicRecordSnapshot,
      5   publicRecordWire,
      6   type PublicRecordHandle
      7 } from '../persistence/records.ts';
      8 import {
      9   bindCapturedArtifact,
     10   type CapturedArtifact
     11 } from '../persistence/artifact-records.ts';
     12 import { inspectLocalTemplate } from './local-template.ts';
     13 import { boundedEnvelopeNumbers } from './envelope-bounds.ts';
     14 
     15 declare const approvalBrand: unique symbol;
     16 export type ApprovedPublicSigning = Readonly<{ [approvalBrand]: true }>;
     17 type Capture = Readonly<{
     18   owner: string;
     19   id: string;
     20   revision: number;
     21   wire: string;
     22   hash: string;
     23   recordWire: string;
     24 }>;
     25 const approvals = new WeakMap<ApprovedPublicSigning, Capture>();
     26 // Internal captured-operation capability. This is neither a raw UI template
     27 // signer nor current IDB/CAS, inbox-readiness, transport or publication proof.
     28 // Later operation controllers own those obligations. Private seal13/AUTH22242
     29 // approvals require their separate typed owners; plaintext14 is never admitted.
     30 export function approveCapturedPublicSigning(
     31   record: PublicRecordHandle,
     32   owner: unknown,
     33   id: unknown,
     34   review: unknown
     35 ): ApprovedPublicSigning | undefined {
     36   if (review !== 'reviewed_captured_operation') return undefined;
     37   const row = publicRecordSnapshot(record, owner, id);
     38   const recordWire = publicRecordWire(record, owner, id);
     39   if (
     40     !row ||
     41     !recordWire ||
     42     row.family === 'public_draft' ||
     43     row.artifact !== null
     44   )
     45     return undefined;
     46   const template = inspectLocalTemplate(
     47     row.capture.wire,
     48     row.owner,
     49     row.capture.kind
     50   );
     51   if (!template || template.hash !== row.capture.hash) return undefined;
     52   // Retain primitive canonical wire/hash independently, never caller arrays.
     53   const token = Object.freeze({}) as ApprovedPublicSigning;
     54   approvals.set(token, {
     55     owner: row.owner,
     56     id: row.id,
     57     revision: row.revision,
     58     wire: row.capture.wire,
     59     hash: row.capture.hash,
     60     recordWire
     61   });
     62   return token;
     63 }
     64 export function approvedSigningIdentity(approval: ApprovedPublicSigning):
     65   | Readonly<{
     66       owner: string;
     67       id: string;
     68       revision: number;
     69       recordWire: string;
     70     }>
     71   | undefined {
     72   const saved = approvals.get(approval);
     73   return saved
     74     ? {
     75         owner: saved.owner,
     76         id: saved.id,
     77         revision: saved.revision,
     78         recordWire: saved.recordWire
     79       }
     80     : undefined;
     81 }
     82 // Each acquisition is a disposable fresh JSON copy. No retained template or
     83 // mutable SDK verification symbol ever crosses the provider boundary.
     84 export function disposableApprovedTemplate(
     85   approval: ApprovedPublicSigning
     86 ): UnsignedEvent | undefined {
     87   const saved = approvals.get(approval);
     88   return saved ? (JSON.parse(saved.wire) as UnsignedEvent) : undefined;
     89 }
     90 function own(value: object, name: string): unknown {
     91   const descriptor = Object.getOwnPropertyDescriptor(value, name);
     92   return descriptor && 'value' in descriptor ? descriptor.value : undefined;
     93 }
     94 // Bounded reconstruction, using only own data fields and indexed array entries.
     95 // Do not spread/serialize the response, enumerate extras, invoke toJSON, acquire
     96 // accessor values, or follow provider-controlled iterators and cache symbols.
     97 function signedWire(raw: unknown): string | undefined {
     98   try {
     99     if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
    100       return undefined;
    101     const id = own(raw, 'id'),
    102       pubkey = own(raw, 'pubkey'),
    103       sig = own(raw, 'sig'),
    104       numbers = boundedEnvelopeNumbers(
    105         own(raw, 'kind'),
    106         own(raw, 'created_at')
    107       ),
    108       content = own(raw, 'content'),
    109       sourceTags = own(raw, 'tags');
    110     if (
    111       typeof id !== 'string' ||
    112       !/^[0-9a-f]{64}$/.test(id) ||
    113       typeof pubkey !== 'string' ||
    114       !/^[0-9a-f]{64}$/.test(pubkey) ||
    115       typeof sig !== 'string' ||
    116       !/^[0-9a-f]{128}$/.test(sig) ||
    117       !numbers ||
    118       typeof content !== 'string' ||
    119       !boundedUtf8(content, 131072) ||
    120       !Array.isArray(sourceTags)
    121     )
    122       return undefined;
    123     const count = own(sourceTags, 'length');
    124     if (
    125       typeof count !== 'number' ||
    126       !Number.isSafeInteger(count) ||
    127       count < 0 ||
    128       count > 1024
    129     )
    130       return undefined;
    131     const tags: string[][] = [];
    132     let elements = 0,
    133       bytes = 0;
    134     const encoder = new TextEncoder();
    135     for (let i = 0; i < count; i++) {
    136       const source = own(sourceTags, String(i));
    137       if (!Array.isArray(source)) return undefined;
    138       const length = own(source, 'length');
    139       if (
    140         typeof length !== 'number' ||
    141         !Number.isSafeInteger(length) ||
    142         length <= 0 ||
    143         length > 4096 - elements
    144       )
    145         return undefined;
    146       elements += length;
    147       const tag: string[] = [];
    148       function append(value: string) {
    149         tag.push(value);
    150       }
    151       for (let j = 0; j < length; j++) {
    152         const value = own(source, String(j));
    153         if (
    154           typeof value !== 'string' ||
    155           !boundedUtf8(value, 4096) ||
    156           (j === 0 && (value.length === 0 || /\p{Cc}/u.test(value)))
    157         )
    158           return undefined;
    159         bytes += encoder.encode(value).length;
    160         if (bytes > 131072) return undefined;
    161         append(value);
    162       }
    163       tags.push(tag);
    164     }
    165     return JSON.stringify({
    166       id,
    167       pubkey,
    168       kind: numbers.kind,
    169       created_at: numbers.created_at,
    170       tags,
    171       content,
    172       sig
    173     });
    174   } catch {
    175     return undefined;
    176   }
    177 }
    178 export function bindApprovedResponse(
    179   approval: ApprovedPublicSigning,
    180   response: unknown
    181 ): CapturedArtifact | undefined {
    182   const saved = approvals.get(approval);
    183   if (!saved) return undefined;
    184   const wire = signedWire(response);
    185   if (!wire) return undefined;
    186   const returned = JSON.parse(wire) as UnsignedEvent;
    187   const original = JSON.parse(saved.wire) as UnsignedEvent;
    188   if (
    189     returned.pubkey !== original.pubkey ||
    190     returned.kind !== original.kind ||
    191     returned.created_at !== original.created_at ||
    192     returned.content !== original.content ||
    193     JSON.stringify(returned.tags) !== JSON.stringify(original.tags)
    194   )
    195     return undefined;
    196   // Reparse into a fresh SDK-verification object: no provider cache survives.
    197   // Hash and signature must both verify, independently of field comparison.
    198   const bound = bindCapturedArtifact(
    199     wire,
    200     saved.owner,
    201     original.kind,
    202     saved.hash
    203   );
    204   return bound.ok ? bound.value : undefined;
    205 }