app

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

inbox-envelope-repository.ts (6088B)


      1 import { canonicalPublicKey } from '../contracts/public-key.ts';
      2 import { canonicalRelayOrigin } from '../config/relays.ts';
      3 import { PRIVATE_TRANSPORT_BUDGETS } from '../config/budgets.ts';
      4 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
      5 import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts';
      6 import {
      7   verifyEnvelope,
      8   verifiedEnvelopeSnapshot
      9 } from '../nostr/verified-envelope.ts';
     10 import {
     11   privateSessionOwnership,
     12   type PrivateSession
     13 } from '../runtime/private-session.ts';
     14 import {
     15   decodePrivateRecord,
     16   privateRecordSnapshot,
     17   privateRecordWire,
     18   privateReceivedOuterMetadata,
     19   type PrivateRecordHandle
     20 } from './private-records.ts';
     21 import {
     22   loadPrivateRecord,
     23   privateStorageOwner,
     24   retainPrivateReceivedRecord,
     25   type PrivateStorageRepository,
     26   type PrivateStorageFailure
     27 } from './private-storage.ts';
     28 import {
     29   observeInboxProbeDelivery,
     30   consumeInboxProbeDelivery
     31 } from './inbox-probes.ts';
     32 declare const envelopeBrand: unique symbol;
     33 export type InboxEnvelope = Readonly<{ [envelopeBrand]: true }>;
     34 type Admitted = Readonly<{
     35   owner: string;
     36   id: string;
     37   source: string;
     38   record: PrivateRecordHandle;
     39 }>;
     40 const envelopes = new WeakMap<InboxEnvelope, Admitted>();
     41 // Outer authentication only. Ciphertext is untrusted until later nested seal,
     42 // rumor and sender/participant admission; this proof never grants decryption.
     43 export function admitInboxEnvelope(
     44   raw: unknown,
     45   expectedOwner: unknown,
     46   observedSource: unknown,
     47   observedAt: unknown
     48 ): InboxEnvelope | undefined {
     49   const owner = canonicalPublicKey(expectedOwner),
     50     source = canonicalRelayOrigin(observedSource),
     51     at = safeUnsignedInteger(observedAt);
     52   if (
     53     !owner ||
     54     !source ||
     55     at === undefined ||
     56     typeof raw !== 'string' ||
     57     !boundedUtf8(raw, PRIVATE_TRANSPORT_BUDGETS.envelopeBytes)
     58   )
     59     return undefined;
     60   const verified = verifyEnvelope(raw),
     61     event = verified.ok && verifiedEnvelopeSnapshot(verified.value);
     62   if (!event || event.kind !== 1059) return undefined;
     63   const record = decodePrivateRecord(
     64     JSON.stringify({
     65       schema: 1,
     66       family: 'received_envelope',
     67       owner,
     68       id: event.id,
     69       revision: 0,
     70       outer: raw,
     71       observedAtMilliseconds: at,
     72       sources: [source],
     73       read: null
     74     }),
     75     owner,
     76     event.id
     77   );
     78   if (!record.ok) return undefined;
     79   const token = Object.freeze({}) as InboxEnvelope;
     80   envelopes.set(token, { owner, id: event.id, source, record: record.value });
     81   return token;
     82 }
     83 export function inboxEnvelopeSnapshot(token: InboxEnvelope) {
     84   const row = envelopes.get(token);
     85   return row && privateRecordSnapshot(row.record, row.owner, row.id);
     86 }
     87 export function inboxEnvelopeOuterMetadata(token: InboxEnvelope) {
     88   const row = envelopes.get(token);
     89   return row && privateReceivedOuterMetadata(row.record, row.owner, row.id);
     90 }
     91 export type InboxRetentionResult = Readonly<{
     92   status:
     93     | 'retained'
     94     | 'duplicate'
     95     | 'probe_excluded'
     96     | 'invalid'
     97     | 'stopped'
     98     | 'busy'
     99     | PrivateStorageFailure;
    100 }>;
    101 // Ciphertext-only bookkeeping in the original owner namespace. No SDK work in
    102 // IDB; request success is insufficient without actual whole-wire readback.
    103 export async function retainInboxEnvelope(
    104   repository: PrivateStorageRepository,
    105   session: PrivateSession,
    106   envelope: InboxEnvelope,
    107   cancellation?: AbortSignal
    108 ): Promise<InboxRetentionResult> {
    109   const admitted = envelopes.get(envelope);
    110   if (!admitted || privateStorageOwner(repository) !== admitted.owner)
    111     return { status: 'invalid' };
    112   const ownership = privateSessionOwnership(session);
    113   if (
    114     !ownership?.current() ||
    115     ownership.owner !== admitted.owner ||
    116     typeof window === 'undefined' ||
    117     !navigator.locks?.request
    118   )
    119     return { status: 'invalid' };
    120   if (cancellation?.aborted) return { status: 'stopped' };
    121   try {
    122     return await navigator.locks.request(
    123       'harvestcircle:owner:' + admitted.owner,
    124       { mode: 'exclusive', ifAvailable: true },
    125       async (lock) => {
    126         if (!lock) return { status: 'busy' };
    127         if (!ownership.current() || cancellation?.aborted)
    128           return { status: 'stopped' };
    129         const record = privateRecordSnapshot(
    130           admitted.record,
    131           admitted.owner,
    132           admitted.id
    133         );
    134         if (!record || record.family !== 'received_envelope')
    135           return { status: 'invalid' };
    136         const probe = await observeInboxProbeDelivery(
    137           repository,
    138           session,
    139           admitted.id,
    140           record.outer,
    141           cancellation
    142         );
    143         if (
    144           !ownership.current() ||
    145           cancellation?.aborted ||
    146           probe === 'stopped'
    147         )
    148           return { status: 'stopped' };
    149         if (
    150           typeof probe !== 'string' &&
    151           consumeInboxProbeDelivery(
    152             probe,
    153             repository,
    154             session,
    155             admitted.id,
    156             record.outer
    157           )
    158         )
    159           return { status: 'probe_excluded' };
    160         const committed = await retainPrivateReceivedRecord(
    161           repository,
    162           session,
    163           admitted.record,
    164           cancellation
    165         );
    166         if (!ownership.current() || cancellation?.aborted)
    167           return { status: 'stopped' };
    168         if (!committed.ok) return { status: committed.reason };
    169         if (!committed.value.changed) return { status: committed.value.status };
    170         const readback = await loadPrivateRecord(
    171           repository,
    172           'received_envelopes',
    173           admitted.id
    174         );
    175         if (!ownership.current() || cancellation?.aborted)
    176           return { status: 'stopped' };
    177         if (!readback.ok) return { status: 'unknown_completion' };
    178         if (
    179           privateRecordWire(readback.value, admitted.owner, admitted.id) !==
    180           privateRecordWire(committed.value.record, admitted.owner, admitted.id)
    181         )
    182           return { status: 'conflict' };
    183         return { status: committed.value.status };
    184       }
    185     );
    186   } catch {
    187     return { status: 'unknown_completion' };
    188   }
    189 }