app

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

artifact-records.ts (10319B)


      1 import { canonicalPublicKey } from '../contracts/public-key.ts';
      2 import { canonicalLocalId } from '../private-handles.ts';
      3 import {
      4   exactLocalFields,
      5   type PublicOperationRecord,
      6   type PreferenceOperationRecord,
      7   type PublicTargetReceipt
      8 } from '../contracts/local-records.ts';
      9 import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts';
     10 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
     11 import {
     12   verifyEnvelope,
     13   verifiedEnvelopeSnapshot
     14 } from '../nostr/verified-envelope.ts';
     15 import {
     16   decodePublicRecord,
     17   publicRecordSnapshot,
     18   publicRecordWire,
     19   type PublicRecordHandle
     20 } from './records.ts';
     21 
     22 declare const artifactBrand: unique symbol;
     23 declare const transitionBrand: unique symbol;
     24 export type CapturedArtifact = Readonly<{ [artifactBrand]: true }>;
     25 export type PublicOperationTransition = Readonly<{ [transitionBrand]: true }>;
     26 export type ArtifactFailure =
     27   'invalid_artifact' | 'invalid_record' | 'conflict' | 'revision_exhausted';
     28 type Result<T> =
     29   | Readonly<{ ok: true; value: T }>
     30   | Readonly<{ ok: false; reason: ArtifactFailure }>;
     31 type Artifact = Readonly<{
     32   author: string;
     33   kind: 30402 | 5 | 10050 | 1059;
     34   hash: string;
     35   wire: string;
     36 }>;
     37 type Operation = PublicOperationRecord | PreferenceOperationRecord;
     38 type Transition = Readonly<{
     39   owner: string;
     40   id: string;
     41   family: Operation['family'];
     42   kind: 30402 | 5 | 10050;
     43   expectedRevision: number;
     44   revision: number;
     45   baseWire: string;
     46   nextWire: string;
     47 }>;
     48 const artifacts = new WeakMap<CapturedArtifact, Artifact>();
     49 const transitions = new WeakMap<PublicOperationTransition, Transition>();
     50 function failed(reason: ArtifactFailure): Result<never> {
     51   return { ok: false, reason };
     52 }
     53 // SDK-verified exact envelope binding only. A1059 token proves an outer
     54 // signature/hash, not nested Message authenticity, routing or durable storage.
     55 // Private typed repositories own those later checks. No plaintext14/13 token.
     56 export function bindCapturedArtifact(
     57   rawWire: unknown,
     58   expectedAuthor: unknown,
     59   expectedKind: unknown,
     60   expectedHash: unknown
     61 ): Result<CapturedArtifact> {
     62   const author = canonicalPublicKey(expectedAuthor);
     63   if (
     64     !author ||
     65     (expectedKind !== 30402 &&
     66       expectedKind !== 5 &&
     67       expectedKind !== 10050 &&
     68       expectedKind !== 1059) ||
     69     typeof expectedHash !== 'string' ||
     70     !/^[0-9a-f]{64}$/.test(expectedHash) ||
     71     typeof rawWire !== 'string'
     72   )
     73     return failed('invalid_artifact');
     74   const proof = verifyEnvelope(rawWire);
     75   if (!proof.ok) return failed('invalid_artifact');
     76   const event = verifiedEnvelopeSnapshot(proof.value);
     77   if (
     78     !event ||
     79     !exactLocalFields(event, [
     80       'id',
     81       'pubkey',
     82       'kind',
     83       'created_at',
     84       'tags',
     85       'content',
     86       'sig'
     87     ]) ||
     88     event.pubkey !== author ||
     89     event.kind !== expectedKind ||
     90     event.id !== expectedHash
     91   )
     92     return failed('invalid_artifact');
     93   const token = Object.freeze({}) as CapturedArtifact;
     94   artifacts.set(token, {
     95     author,
     96     kind: expectedKind,
     97     hash: expectedHash,
     98     wire: rawWire
     99   });
    100   return { ok: true, value: token };
    101 }
    102 export function capturedArtifactSnapshot(
    103   handle: CapturedArtifact
    104 ): Artifact | undefined {
    105   const saved = artifacts.get(handle);
    106   return saved ? { ...saved } : undefined;
    107 }
    108 function baseOf(
    109   handle: PublicRecordHandle,
    110   owner: unknown,
    111   id: unknown
    112 ): Readonly<{ row: Operation; wire: string }> | undefined {
    113   const row = publicRecordSnapshot(handle, owner, id),
    114     wire = publicRecordWire(handle, owner, id);
    115   return row && row.family !== 'public_draft' && wire
    116     ? { row, wire }
    117     : undefined;
    118 }
    119 function retain(
    120   base: Readonly<{ row: Operation; wire: string }>,
    121   next: Operation
    122 ): Result<PublicOperationTransition> {
    123   const nextWire = JSON.stringify(next);
    124   const decoded = decodePublicRecord(nextWire, base.row.owner, base.row.id);
    125   if (!decoded.ok) return failed('invalid_record');
    126   const token = Object.freeze({}) as PublicOperationTransition;
    127   transitions.set(token, {
    128     owner: base.row.owner,
    129     id: base.row.id,
    130     family: base.row.family,
    131     kind: base.row.capture.kind,
    132     expectedRevision: base.row.revision,
    133     revision: next.revision,
    134     baseWire: base.wire,
    135     nextWire
    136   });
    137   return { ok: true, value: token };
    138 }
    139 // A durable one-attempt marker, not a known refusal or a retry permission.
    140 // Lost unsigned revision1 remains uncertain; it can never be reset by this API.
    141 export function preparePreferenceSigningTransition(
    142   record: PublicRecordHandle,
    143   owner: unknown,
    144   id: unknown
    145 ): Result<PublicOperationTransition> {
    146   const base = baseOf(record, owner, id);
    147   if (
    148     !base ||
    149     base.row.family !== 'preference_operation' ||
    150     base.row.capture.kind !== 10050 ||
    151     base.row.revision !== 0 ||
    152     base.row.artifact !== null ||
    153     base.row.receipts.length !== 0
    154   )
    155     return failed('invalid_record');
    156   return retain(base, { ...base.row, revision: 1 });
    157 }
    158 // The acknowledged unsigned revision1 records an original listing attempt.
    159 // It cannot be reset into permission to prompt again after page/ack loss.
    160 export function preparePublicListingSigningTransition(
    161   record: PublicRecordHandle,
    162   owner: unknown,
    163   id: unknown
    164 ): Result<PublicOperationTransition> {
    165   const base = baseOf(record, owner, id);
    166   if (
    167     !base ||
    168     base.row.family !== 'public_operation' ||
    169     !(
    170       (base.row.source.type === 'draft' && base.row.capture.kind === 30402) ||
    171       (base.row.source.type === 'public_head' && base.row.capture.kind === 5)
    172     ) ||
    173     base.row.revision !== 0 ||
    174     base.row.artifact !== null ||
    175     base.row.receipts.length !== 0
    176   )
    177     return failed('invalid_record');
    178   return retain(base, { ...base.row, revision: 1 });
    179 }
    180 export function preparePublicArtifactTransition(
    181   record: PublicRecordHandle,
    182   owner: unknown,
    183   id: unknown,
    184   artifact: CapturedArtifact
    185 ): Result<PublicOperationTransition> {
    186   const base = baseOf(record, owner, id),
    187     signed = artifacts.get(artifact);
    188   if (!base) return failed('invalid_record');
    189   if (
    190     !signed ||
    191     signed.author !== base.row.owner ||
    192     signed.kind !== base.row.capture.kind ||
    193     signed.hash !== base.row.capture.hash
    194   )
    195     return failed('invalid_artifact');
    196   if (base.row.artifact !== null)
    197     return base.row.artifact.wire === signed.wire
    198       ? retain(base, base.row)
    199       : failed('conflict');
    200   if (base.row.revision === Number.MAX_SAFE_INTEGER)
    201     return failed('revision_exhausted');
    202   return retain(base, {
    203     ...base.row,
    204     revision: base.row.revision + 1,
    205     artifact: { eventId: signed.hash, wire: signed.wire }
    206   });
    207 }
    208 function sameFact(a: PublicTargetReceipt, b: PublicTargetReceipt): boolean {
    209   return (
    210     a.actionId === b.actionId &&
    211     a.origin === b.origin &&
    212     a.readbackOrigin === b.readbackOrigin &&
    213     a.role === b.role &&
    214     a.attempt === b.attempt &&
    215     a.eventId === b.eventId &&
    216     a.status === b.status &&
    217     a.observedAtMilliseconds === b.observedAtMilliseconds
    218   );
    219 }
    220 // Only canonical primitive wire is acquired; defensive record decoding validates
    221 // every receipt field, target, role, event and exact readback signature. Distinct
    222 // status/time observations remain distinct. No EventStore seen metadata is used.
    223 export function preparePublicReceiptTransition(
    224   record: PublicRecordHandle,
    225   owner: unknown,
    226   id: unknown,
    227   receiptWire: unknown
    228 ): Result<PublicOperationTransition> {
    229   const base = baseOf(record, owner, id);
    230   if (
    231     !base ||
    232     !base.row.artifact ||
    233     typeof receiptWire !== 'string' ||
    234     !boundedUtf8(receiptWire, LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes)
    235   )
    236     return failed('invalid_record');
    237   try {
    238     const fact: unknown = JSON.parse(receiptWire);
    239     if (
    240       JSON.stringify(fact) !== receiptWire ||
    241       !(
    242         exactLocalFields(fact, [
    243           'actionId',
    244           'origin',
    245           'role',
    246           'attempt',
    247           'eventId',
    248           'status',
    249           'observedAtMilliseconds',
    250           'readbackWire'
    251         ]) ||
    252         (base.row.family === 'preference_operation' &&
    253           exactLocalFields(fact, [
    254             'actionId',
    255             'origin',
    256             'role',
    257             'attempt',
    258             'eventId',
    259             'status',
    260             'observedAtMilliseconds',
    261             'readbackWire',
    262             'readbackOrigin'
    263           ]))
    264       )
    265     )
    266       return failed('invalid_record');
    267     // Validate the proposed fact through the existing complete typed codec before
    268     // comparing keys; the parsed object contains only detached JSON data.
    269     const checked = decodePublicRecord(
    270       JSON.stringify({ ...base.row, receipts: [fact] }),
    271       base.row.owner,
    272       base.row.id
    273     );
    274     if (!checked.ok) return failed('invalid_record');
    275     const admitted = publicRecordSnapshot(
    276       checked.value,
    277       base.row.owner,
    278       base.row.id
    279     );
    280     if (!admitted || admitted.family === 'public_draft')
    281       return failed('invalid_record');
    282     const nextFact = admitted.receipts[0];
    283     const existing = base.row.receipts.find((row) => sameFact(row, nextFact));
    284     if (existing)
    285       return JSON.stringify(existing) === JSON.stringify(nextFact)
    286         ? retain(base, base.row)
    287         : failed('conflict');
    288     if (base.row.revision === Number.MAX_SAFE_INTEGER)
    289       return failed('revision_exhausted');
    290     return retain(base, {
    291       ...base.row,
    292       revision: base.row.revision + 1,
    293       receipts: [...base.row.receipts, nextFact]
    294     });
    295   } catch {
    296     return failed('invalid_record');
    297   }
    298 }
    299 // Internal repository input: a detached snapshot of a genuine frozen command,
    300 // never a signing/network capability. Scope and full-wire CAS remain in IDB.
    301 export function publicTransitionSnapshot(
    302   handle: PublicOperationTransition,
    303   owner: unknown,
    304   id: unknown
    305 ): Transition | undefined {
    306   const saved = transitions.get(handle);
    307   return saved &&
    308     saved.owner === canonicalPublicKey(owner) &&
    309     saved.id === canonicalLocalId(id)
    310     ? { ...saved }
    311     : undefined;
    312 }
    313 // Metadata-only scope admission avoids accepting caller-owned record objects.
    314 export function publicTransitionIdentity(
    315   handle: PublicOperationTransition
    316 ): Readonly<{ owner: string; id: string }> | undefined {
    317   const saved = transitions.get(handle);
    318   return saved ? { owner: saved.owner, id: saved.id } : undefined;
    319 }