app

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

giftwrap-builder.ts (7691B)


      1 import {
      2   generateSecretKey,
      3   getPublicKey,
      4   finalizeEvent,
      5   getEventHash,
      6   type UnsignedEvent
      7 } from 'applesauce-core/helpers';
      8 import { nip44 } from 'applesauce-core/helpers/encryption';
      9 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
     10 import { safeUnsignedInteger } from './envelope-bounds.ts';
     11 import { verifyEnvelope } from './verified-envelope.ts';
     12 import {
     13   privateSealSnapshot,
     14   inboxProbeSealSnapshot,
     15   type InboxProbeRecipientSeal,
     16   type PrivateRecipientSeal
     17 } from './seal-builder.ts';
     18 
     19 declare const probeWrapBrand: unique symbol;
     20 export type InboxProbeGiftwrap = Readonly<{ [probeWrapBrand]: true }>;
     21 declare const giftwrapBrand: unique symbol;
     22 export type PrivateGiftwrap = Readonly<{ [giftwrapBrand]: true }>;
     23 type Saved = Readonly<{
     24   owner: string;
     25   peer: string;
     26   destination: string;
     27   role: 'peer' | 'self';
     28   command: string;
     29   rumorHash: string;
     30   kind: 1059;
     31   wire: string;
     32   seal: PrivateRecipientSeal;
     33 }>;
     34 const wraps = new WeakMap<PrivateGiftwrap, Saved>();
     35 function own(value: object, name: string): unknown {
     36   const descriptor = Object.getOwnPropertyDescriptor(value, name);
     37   return descriptor && 'value' in descriptor ? descriptor.value : undefined;
     38 }
     39 type SavedProbeWrap = Readonly<{
     40   owner: string;
     41   destination: string;
     42   command: string;
     43   rumorHash: string;
     44   createdAt: number;
     45   kind: 1059;
     46   wire: string;
     47   seal: InboxProbeRecipientSeal;
     48 }>;
     49 const probeWraps = new WeakMap<InboxProbeGiftwrap, SavedProbeWrap>();
     50 const originalProbeWraps = new WeakMap<
     51   InboxProbeRecipientSeal,
     52   InboxProbeGiftwrap | null
     53 >();
     54 // Module-private stock SDK wrapper construction; only genuine ordinary/probe
     55 // seal factories below can supply the binding. No exported callback/key port.
     56 function constructGiftwrap(
     57   record: Readonly<{ destination: string; wire: string }>,
     58   current: () => boolean
     59 ): string | undefined {
     60   let secret: Uint8Array | undefined, conversation: Uint8Array | undefined;
     61   try {
     62     const milliseconds = safeUnsignedInteger(Date.now());
     63     if (milliseconds === undefined || !current()) return undefined;
     64     const random = crypto.getRandomValues(new Uint32Array(1))[0],
     65       time = Math.max(0, Math.floor(milliseconds / 1000) - (random % 3600));
     66     if (!current()) return undefined;
     67     secret = generateSecretKey();
     68     if (!current()) return undefined;
     69     const author = getPublicKey(secret);
     70     conversation = nip44.v2.utils.getConversationKey(
     71       secret,
     72       record.destination
     73     );
     74     if (!current()) return undefined;
     75     const content = nip44.v2.encrypt(record.wire, conversation);
     76     if (!current()) return undefined;
     77     if (nip44.v2.decrypt(content, conversation) !== record.wire || !current())
     78       return undefined;
     79     const captured = JSON.stringify({
     80       pubkey: author,
     81       kind: 1059,
     82       created_at: time,
     83       tags: [['p', record.destination]],
     84       content
     85     });
     86     const response = finalizeEvent(
     87         JSON.parse(captured) as UnsignedEvent,
     88         secret
     89       ),
     90       id = own(response, 'id'),
     91       sig = own(response, 'sig'),
     92       tags = own(response, 'tags');
     93     if (
     94       own(response, 'pubkey') !== author ||
     95       own(response, 'kind') !== 1059 ||
     96       own(response, 'created_at') !== time ||
     97       own(response, 'content') !== content ||
     98       !Array.isArray(tags) ||
     99       own(tags, 'length') !== 1
    100     )
    101       return undefined;
    102     const target = own(tags, '0');
    103     if (
    104       !Array.isArray(target) ||
    105       own(target, 'length') !== 2 ||
    106       own(target, '0') !== 'p' ||
    107       own(target, '1') !== record.destination ||
    108       typeof id !== 'string' ||
    109       typeof sig !== 'string' ||
    110       id !== getEventHash(JSON.parse(captured) as UnsignedEvent)
    111     )
    112       return undefined;
    113     // Explicit fields discard SDK verification/cache symbols and extra data.
    114     // Parse and verify a fresh wire, independently of the SDK result object.
    115     const wire = JSON.stringify({
    116       pubkey: author,
    117       kind: 1059,
    118       created_at: time,
    119       tags: [['p', record.destination]],
    120       content,
    121       id,
    122       sig
    123     });
    124     if (!boundedUtf8(wire, 32768) || !verifyEnvelope(wire).ok || !current())
    125       return undefined;
    126     return wire;
    127   } catch {
    128     return undefined;
    129   } finally {
    130     // Directly owned byte buffers only. The SDK/engine may allocate other
    131     // buffers; this does not promise complete browser-memory zeroization.
    132     conversation?.fill(0);
    133     secret?.fill(0);
    134   }
    135 }
    136 // Genuine ordinary sender seals only; probe casts grant no ordinary token.
    137 export function buildPrivateGiftwrap(
    138   seal: PrivateRecipientSeal,
    139   review: unknown
    140 ): PrivateGiftwrap | undefined {
    141   if (typeof window === 'undefined' || review !== 'reviewed_private_wrap')
    142     return undefined;
    143   const record = privateSealSnapshot(seal);
    144   if (
    145     !record ||
    146     !boundedUtf8(record.wire, 16384) ||
    147     record.destination !== (record.role === 'self' ? record.owner : record.peer)
    148   )
    149     return undefined;
    150   const wire = constructGiftwrap(record, () => !!privateSealSnapshot(seal));
    151   if (!wire || !privateSealSnapshot(seal)) return undefined;
    152   const token = Object.freeze({}) as PrivateGiftwrap;
    153   wraps.set(token, { ...record, kind: 1059, wire, seal });
    154   return token;
    155 }
    156 // One self-only immutable crypto artifact per genuine diagnostic seal. Failed
    157 // construction cannot silently generate a replacement artifact in this action.
    158 export function buildInboxProbeGiftwrap(
    159   seal: InboxProbeRecipientSeal,
    160   review: unknown
    161 ): InboxProbeGiftwrap | undefined {
    162   if (typeof window === 'undefined' || review !== 'reviewed_inbox_probe_wrap')
    163     return undefined;
    164   const record = inboxProbeSealSnapshot(seal);
    165   if (
    166     !record ||
    167     record.destination !== record.owner ||
    168     !boundedUtf8(record.wire, 16384)
    169   )
    170     return undefined;
    171   if (originalProbeWraps.has(seal))
    172     return originalProbeWraps.get(seal) ?? undefined;
    173   originalProbeWraps.set(seal, null);
    174   const wire = constructGiftwrap(record, () => !!inboxProbeSealSnapshot(seal));
    175   if (!wire || !inboxProbeSealSnapshot(seal)) return undefined;
    176   const token = Object.freeze({}) as InboxProbeGiftwrap;
    177   probeWraps.set(token, { ...record, kind: 1059, wire, seal });
    178   originalProbeWraps.set(seal, token);
    179   return token;
    180 }
    181 export function inboxProbeGiftwrapSeal(
    182   token: InboxProbeGiftwrap
    183 ): InboxProbeRecipientSeal | undefined {
    184   const saved = probeWraps.get(token);
    185   return saved && inboxProbeSealSnapshot(saved.seal) ? saved.seal : undefined;
    186 }
    187 export function inboxProbeGiftwrapSnapshot(
    188   token: InboxProbeGiftwrap
    189 ): Readonly<Omit<SavedProbeWrap, 'seal'>> | undefined {
    190   const saved = probeWraps.get(token);
    191   return saved && inboxProbeSealSnapshot(saved.seal)
    192     ? {
    193         owner: saved.owner,
    194         destination: saved.destination,
    195         command: saved.command,
    196         rumorHash: saved.rumorHash,
    197         createdAt: saved.createdAt,
    198         kind: 1059,
    199         wire: saved.wire
    200       }
    201     : undefined;
    202 }
    203 // Returns only the genuine original capability, never disposable key material.
    204 export function privateGiftwrapSeal(
    205   token: PrivateGiftwrap
    206 ): PrivateRecipientSeal | undefined {
    207   const saved = wraps.get(token);
    208   return saved && privateSealSnapshot(saved.seal) ? saved.seal : undefined;
    209 }
    210 export function privateGiftwrapSnapshot(
    211   token: PrivateGiftwrap
    212 ): Readonly<Omit<Saved, 'seal'>> | undefined {
    213   const saved = wraps.get(token);
    214   return saved && privateSealSnapshot(saved.seal)
    215     ? {
    216         owner: saved.owner,
    217         peer: saved.peer,
    218         destination: saved.destination,
    219         role: saved.role,
    220         command: saved.command,
    221         rumorHash: saved.rumorHash,
    222         kind: 1059,
    223         wire: saved.wire
    224       }
    225     : undefined;
    226 }