app

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

artifact-records.test.ts (12950B)


      1 import { expect, it } from 'vitest';
      2 import { finalizeEvent, getEventHash } from 'applesauce-core/helpers';
      3 import {
      4   decodePublicRecord,
      5   publicRecordSnapshot
      6 } from '../../src/lib/persistence/records.ts';
      7 import type {
      8   PublicOperationRecord,
      9   PreferenceOperationRecord,
     10   PublicTargetReceipt
     11 } from '../../src/lib/contracts/local-records.ts';
     12 import {
     13   bindCapturedArtifact,
     14   capturedArtifactSnapshot,
     15   preparePublicArtifactTransition,
     16   preparePublicReceiptTransition,
     17   publicTransitionSnapshot,
     18   type CapturedArtifact,
     19   type PublicOperationTransition
     20 } from '../../src/lib/persistence/artifact-records.ts';
     21 import { decideFrozenTransition } from '../../src/lib/persistence/operation-transactions.ts';
     22 const id = '3d030bf5-901d-45e1-8251-41cbdf805e96';
     23 const actionId = 'b1d6d23d-79f3-4779-9b03-e289712cc73f';
     24 function fixture(kind: 30402 | 10050 | 1059 = 30402) {
     25   const key = crypto.getRandomValues(new Uint8Array(32));
     26   try {
     27     const event = finalizeEvent(
     28       {
     29         kind,
     30         created_at: 100,
     31         tags:
     32           kind === 30402
     33             ? [
     34                 ['d', 'transition'],
     35                 ['published_at', '100']
     36               ]
     37             : [],
     38         content:
     39           kind === 1059 ? 'controlled ciphertext fixture' : 'public fixture'
     40       },
     41       key
     42     );
     43     const template = {
     44       pubkey: event.pubkey,
     45       kind: kind === 1059 ? 30402 : kind,
     46       created_at: event.created_at,
     47       tags: event.tags,
     48       content: event.content
     49     };
     50     const capture = {
     51       kind: kind === 10050 ? (10050 as const) : (30402 as const),
     52       wire: JSON.stringify(template),
     53       hash: getEventHash(template),
     54       targets: ['wss://one.example.org'],
     55       policyFingerprint: 'a'.repeat(64)
     56     };
     57     const row: PublicOperationRecord | PreferenceOperationRecord =
     58       kind === 10050
     59         ? {
     60             schema: 1,
     61             family: 'preference_operation',
     62             owner: event.pubkey,
     63             id,
     64             revision: 0,
     65             source: { type: 'inbox_head', wire: null },
     66             consent: 'explicit_review',
     67             capture: { ...capture, kind: 10050 },
     68             artifact: null,
     69             receipts: []
     70           }
     71         : {
     72             schema: 1,
     73             family: 'public_operation',
     74             owner: event.pubkey,
     75             id,
     76             revision: 0,
     77             source: { type: 'draft', id, revision: 0 },
     78             capture: { ...capture, kind: 30402 },
     79             artifact: null,
     80             receipts: []
     81           };
     82     return { row, event, wire: JSON.stringify(event) };
     83   } finally {
     84     key.fill(0);
     85   }
     86 }
     87 function handle(row: PublicOperationRecord | PreferenceOperationRecord) {
     88   const decoded = decodePublicRecord(JSON.stringify(row), row.owner, row.id);
     89   if (!decoded.ok) throw new Error(decoded.reason);
     90   return decoded.value;
     91 }
     92 function artifact(f: ReturnType<typeof fixture>) {
     93   const result = bindCapturedArtifact(
     94     f.wire,
     95     f.row.owner,
     96     f.event.kind,
     97     f.event.id
     98   );
     99   if (!result.ok) throw new Error(result.reason);
    100   return result.value;
    101 }
    102 function signedRow(f: ReturnType<typeof fixture>) {
    103   return {
    104     ...f.row,
    105     revision: 1,
    106     artifact: { eventId: f.event.id, wire: f.wire }
    107   };
    108 }
    109 function receipt(f: ReturnType<typeof fixture>): PublicTargetReceipt {
    110   return {
    111     actionId,
    112     origin: 'wss://one.example.org',
    113     role:
    114       f.row.family === 'preference_operation' ? 'preference' : 'publication',
    115     attempt: 1,
    116     eventId: f.event.id,
    117     status: 'accepted',
    118     observedAtMilliseconds: 1000,
    119     readbackWire: null
    120   };
    121 }
    122 it('SDK signature binding rejects changed author, kind, hash and forged wire', () => {
    123   const f = fixture();
    124   expect(bindCapturedArtifact(f.wire, f.row.owner, 30402, f.event.id).ok).toBe(
    125     true
    126   );
    127   for (const args of [
    128     [
    129       f.wire,
    130       'c6047f9441ed7d6d3045406e95c07cd85c778e4bcef3ca7abac09b95c709ee5',
    131       30402,
    132       f.event.id
    133     ],
    134     [f.wire, f.row.owner, 10050, f.event.id],
    135     [f.wire, f.row.owner, 30402, 'b'.repeat(64)],
    136     [
    137       JSON.stringify({ ...f.event, sig: '0'.repeat(128) }),
    138       f.row.owner,
    139       30402,
    140       f.event.id
    141     ]
    142   ] as const)
    143     expect(bindCapturedArtifact(args[0], args[1], args[2], args[3]).ok).toBe(
    144       false
    145     );
    146 });
    147 it('outer1059 binding is only a mechanical capability and cannot enter public record transitions', () => {
    148   const f = fixture(1059);
    149   expect(bindCapturedArtifact(f.wire, f.row.owner, 1059, f.event.id).ok).toBe(
    150     true
    151   );
    152   expect(
    153     preparePublicArtifactTransition(handle(f.row), f.row.owner, id, artifact(f))
    154       .ok
    155   ).toBe(false);
    156   expect(bindCapturedArtifact(f.wire, f.row.owner, 14, f.event.id).ok).toBe(
    157     false
    158   );
    159 });
    160 it('artifact transition binds original full wire and advances one revision with immutable capture', () => {
    161   const f = fixture();
    162   const base = handle(f.row);
    163   const result = preparePublicArtifactTransition(
    164     base,
    165     f.row.owner,
    166     id,
    167     artifact(f)
    168   );
    169   expect(result.ok).toBe(true);
    170   if (!result.ok) return;
    171   const state = publicTransitionSnapshot(result.value, f.row.owner, id);
    172   expect(state?.baseWire).toBe(JSON.stringify(f.row));
    173   expect(state?.revision).toBe(1);
    174   const decoded = decodePublicRecord(state?.nextWire, f.row.owner, id);
    175   expect(decoded.ok).toBe(true);
    176   if (!decoded.ok) return;
    177   const next = publicRecordSnapshot(decoded.value, f.row.owner, id);
    178   expect(next).toMatchObject({
    179     ...f.row,
    180     revision: 1,
    181     artifact: { eventId: f.event.id, wire: f.wire }
    182   });
    183 });
    184 it('same exact already-bound artifact is idempotent but different signed wire conflicts', () => {
    185   const f = fixture();
    186   const row = signedRow(f);
    187   const same = preparePublicArtifactTransition(
    188     handle(row),
    189     row.owner,
    190     id,
    191     artifact(f)
    192   );
    193   expect(same.ok).toBe(true);
    194   if (!same.ok) return;
    195   expect(publicTransitionSnapshot(same.value, row.owner, id)?.nextWire).toBe(
    196     JSON.stringify(row)
    197   );
    198   const formatted = bindCapturedArtifact(
    199     JSON.stringify(f.event, null, 2),
    200     row.owner,
    201     30402,
    202     f.event.id
    203   );
    204   expect(formatted.ok).toBe(true);
    205   if (!formatted.ok) return;
    206   expect(
    207     preparePublicArtifactTransition(handle(row), row.owner, id, formatted.value)
    208   ).toEqual({ ok: false, reason: 'conflict' });
    209 });
    210 it('forged capabilities, wrong scope and maximum revision fail before transitions', () => {
    211   const f = fixture();
    212   expect(
    213     preparePublicArtifactTransition(
    214       handle(f.row),
    215       f.row.owner,
    216       id,
    217       {} as CapturedArtifact
    218     ).ok
    219   ).toBe(false);
    220   expect(
    221     publicTransitionSnapshot({} as PublicOperationTransition, f.row.owner, id)
    222   ).toBeUndefined();
    223   expect(
    224     preparePublicArtifactTransition(
    225       handle({ ...f.row, revision: Number.MAX_SAFE_INTEGER }),
    226       f.row.owner,
    227       id,
    228       artifact(f)
    229     ).ok
    230   ).toBe(false);
    231   expect(
    232     preparePublicArtifactTransition(
    233       handle(f.row),
    234       'b'.repeat(64),
    235       id,
    236       artifact(f)
    237     ).ok
    238   ).toBe(false);
    239 });
    240 it('preference artifact remains typed, consent and source unchanged', () => {
    241   const f = fixture(10050);
    242   const result = preparePublicArtifactTransition(
    243     handle(f.row),
    244     f.row.owner,
    245     id,
    246     artifact(f)
    247   );
    248   expect(result.ok).toBe(true);
    249   if (!result.ok) return;
    250   const state = publicTransitionSnapshot(result.value, f.row.owner, id);
    251   expect(JSON.parse(state?.nextWire ?? 'null')).toMatchObject({
    252     family: 'preference_operation',
    253     consent: 'explicit_review',
    254     source: { type: 'inbox_head', wire: null },
    255     capture: f.row.capture
    256   });
    257 });
    258 it('receipt append preserves separate observations and exact duplicate has no revision growth', () => {
    259   const f = fixture();
    260   const row = signedRow(f);
    261   const fact = receipt(f);
    262   const first = preparePublicReceiptTransition(
    263     handle(row),
    264     row.owner,
    265     id,
    266     JSON.stringify(fact)
    267   );
    268   expect(first.ok).toBe(true);
    269   if (!first.ok) return;
    270   const state = publicTransitionSnapshot(first.value, row.owner, id);
    271   const next = JSON.parse(state?.nextWire ?? 'null') as PublicOperationRecord;
    272   expect(next.receipts).toEqual([fact]);
    273   expect(next.revision).toBe(2);
    274   const duplicate = preparePublicReceiptTransition(
    275     handle(next),
    276     row.owner,
    277     id,
    278     JSON.stringify(fact)
    279   );
    280   expect(duplicate.ok).toBe(true);
    281   if (!duplicate.ok) return;
    282   expect(
    283     publicTransitionSnapshot(duplicate.value, row.owner, id)?.nextWire
    284   ).toBe(JSON.stringify(next));
    285   const timed = preparePublicReceiptTransition(
    286     handle(next),
    287     row.owner,
    288     id,
    289     JSON.stringify({
    290       ...fact,
    291       status: 'timed_out',
    292       observedAtMilliseconds: 999
    293     })
    294   );
    295   expect(timed.ok).toBe(true);
    296   if (!timed.ok) return;
    297   expect(
    298     (
    299       JSON.parse(
    300         publicTransitionSnapshot(timed.value, row.owner, id)?.nextWire ?? 'null'
    301       ) as PublicOperationRecord
    302     ).receipts
    303   ).toHaveLength(2);
    304 });
    305 it('same fact identity with changed readback conflicts; wrong role/target/event or unsigned record rejects', () => {
    306   const f = fixture();
    307   const fact = receipt(f);
    308   const row = { ...signedRow(f), receipts: [fact] };
    309   expect(
    310     preparePublicReceiptTransition(
    311       handle(row),
    312       row.owner,
    313       id,
    314       JSON.stringify({ ...fact, readbackWire: f.wire })
    315     )
    316   ).toEqual({ ok: false, reason: 'conflict' });
    317   for (const changed of [
    318     { ...fact, role: 'preference' },
    319     { ...fact, origin: 'wss://other.example.org' },
    320     { ...fact, eventId: 'b'.repeat(64) },
    321     { ...fact, body: 'forbidden' }
    322   ])
    323     expect(
    324       preparePublicReceiptTransition(
    325         handle(signedRow(f)),
    326         row.owner,
    327         id,
    328         JSON.stringify(changed)
    329       ).ok
    330     ).toBe(false);
    331   expect(
    332     preparePublicReceiptTransition(
    333       handle(f.row),
    334       row.owner,
    335       id,
    336       JSON.stringify(fact)
    337     ).ok
    338   ).toBe(false);
    339 });
    340 it('returned snapshots are detached and cannot retarget an existing transition', () => {
    341   const f = fixture();
    342   const token = artifact(f);
    343   const snapshot = capturedArtifactSnapshot(token);
    344   expect(snapshot?.wire).toBe(f.wire);
    345   if (snapshot) (snapshot as { wire: string }).wire = 'changed';
    346   expect(capturedArtifactSnapshot(token)?.wire).toBe(f.wire);
    347   const result = preparePublicArtifactTransition(
    348     handle(f.row),
    349     f.row.owner,
    350     id,
    351     token
    352   );
    353   if (!result.ok) throw new Error(result.reason);
    354   const view = publicTransitionSnapshot(result.value, f.row.owner, id);
    355   if (view) (view as { nextWire: string }).nextWire = 'changed';
    356   expect(
    357     publicTransitionSnapshot(result.value, f.row.owner, id)?.nextWire
    358   ).not.toBe('changed');
    359 });
    360 it('full original and expected payload comparison distinguishes committed, base and conflict', () => {
    361   expect(decideFrozenTransition('next', 'base', 'next')).toBe('committed');
    362   expect(decideFrozenTransition('base', 'base', 'next')).toBe('base_observed');
    363   expect(decideFrozenTransition('different', 'base', 'next')).toBe('conflict');
    364   expect(decideFrozenTransition(undefined, 'base', 'next')).toBe('conflict');
    365 });
    366 
    367 it('actual signed kind5 binds its immutable own-author source and rejects cross-kind binding', () => {
    368   const key = crypto.getRandomValues(new Uint8Array(32));
    369   try {
    370     const base = finalizeEvent(
    371       {
    372         kind: 30402,
    373         created_at: 99,
    374         tags: [
    375           ['d', 'withdraw'],
    376           ['published_at', '99']
    377         ],
    378         content: 'public source'
    379       },
    380       key
    381     );
    382     const event = finalizeEvent(
    383       { kind: 5, created_at: 100, tags: [['e', base.id]], content: 'withdraw' },
    384       key
    385     );
    386     const template = {
    387       pubkey: event.pubkey,
    388       kind: 5,
    389       created_at: 100,
    390       tags: event.tags,
    391       content: event.content
    392     };
    393     const row: PublicOperationRecord = {
    394       schema: 1,
    395       family: 'public_operation',
    396       owner: event.pubkey,
    397       id,
    398       revision: 0,
    399       source: { type: 'public_head', wire: JSON.stringify(base) },
    400       capture: {
    401         kind: 5,
    402         wire: JSON.stringify(template),
    403         hash: getEventHash(template),
    404         targets: ['wss://one.example.org'],
    405         policyFingerprint: 'a'.repeat(64)
    406       },
    407       artifact: null,
    408       receipts: []
    409     };
    410     const bound = bindCapturedArtifact(
    411       JSON.stringify(event),
    412       row.owner,
    413       5,
    414       event.id
    415     );
    416     expect(bound.ok).toBe(true);
    417     if (!bound.ok) return;
    418     const result = preparePublicArtifactTransition(
    419       handle(row),
    420       row.owner,
    421       id,
    422       bound.value
    423     );
    424     expect(result.ok).toBe(true);
    425     if (!result.ok) return;
    426     expect(
    427       JSON.parse(
    428         publicTransitionSnapshot(result.value, row.owner, id)?.nextWire ??
    429           'null'
    430       )
    431     ).toMatchObject({
    432       capture: row.capture,
    433       source: row.source,
    434       artifact: { eventId: event.id, wire: JSON.stringify(event) }
    435     });
    436     expect(
    437       bindCapturedArtifact(JSON.stringify(event), row.owner, 30402, event.id).ok
    438     ).toBe(false);
    439   } finally {
    440     key.fill(0);
    441   }
    442 });