app

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

private-receipts.test.ts (9691B)


      1 import { describe, it, expect } from 'vitest';
      2 import {
      3   generateSecretKey,
      4   getPublicKey,
      5   finalizeEvent
      6 } from 'applesauce-core/helpers';
      7 import { nip44 } from 'applesauce-core/helpers/encryption';
      8 import {
      9   decodePrivateRecord,
     10   privateRecordSnapshot,
     11   privateRecordWire,
     12   type PrivateRecordHandle
     13 } from '../../src/lib/persistence/private-records.ts';
     14 import {
     15   preparePrivateReceiptTransition,
     16   privateReceiptTransitionSnapshot
     17 } from '../../src/lib/persistence/private-receipts.ts';
     18 import { privateSendStatus } from '../../src/lib/messaging/send-status.ts';
     19 const command = '12345678-1234-4234-8234-123456789abc',
     20   action = '12345678-1234-4234-8234-123456789abd';
     21 function fixture() {
     22   const key = generateSecretKey(),
     23     other = generateSecretKey();
     24   let conversation: Uint8Array | undefined;
     25   try {
     26     const owner = getPublicKey(key),
     27       peer = getPublicKey(other);
     28     function artifact(destination: string) {
     29       conversation = nip44.v2.utils.getConversationKey(key, destination);
     30       try {
     31         const event = finalizeEvent(
     32           {
     33             kind: 1059,
     34             created_at: 1700000000,
     35             tags: [['p', destination]],
     36             content: nip44.v2.encrypt(
     37               'Structural codec fixture only',
     38               conversation
     39             )
     40           },
     41           key
     42         );
     43         return { eventId: event.id, wire: JSON.stringify(event) };
     44       } finally {
     45         conversation.fill(0);
     46       }
     47     }
     48     function route(
     49       author: string,
     50       role: 'peer' | 'self_archive',
     51       origin: string
     52     ) {
     53       return {
     54         author,
     55         role,
     56         targets: [origin],
     57         knownBase: { author, id: 'b'.repeat(64), createdAt: 1 },
     58         sources: [{ source: 'wss://discovery.example.org', state: 'eose' }]
     59       };
     60     }
     61     const row = {
     62       schema: 1,
     63       family: 'private_send_operation',
     64       owner,
     65       id: command,
     66       revision: 2,
     67       peer,
     68       rumorHash: 'a'.repeat(64),
     69       createdAt: 1700000000,
     70       self: artifact(owner),
     71       peerArtifact: artifact(peer),
     72       deliveryPlan: {
     73         state: 'prepared',
     74         routes: {
     75           peer: route(peer, 'peer', 'wss://peer.example.org'),
     76           archive: route(owner, 'self_archive', 'wss://archive.example.org')
     77         }
     78       }
     79     };
     80     function handle(value: unknown = row) {
     81       const result = decodePrivateRecord(JSON.stringify(value), owner, command);
     82       if (!result.ok) throw Error('invalid structural fixture');
     83       return result.value;
     84     }
     85     function fact(role: 'peer' | 'self_archive' = 'peer', status = 'accepted') {
     86       return {
     87         actionId: action,
     88         role,
     89         origin:
     90           role === 'peer'
     91             ? 'wss://peer.example.org'
     92             : 'wss://archive.example.org',
     93         attempt: 1,
     94         eventId: role === 'peer' ? row.peerArtifact.eventId : row.self.eventId,
     95         status,
     96         observedAtMilliseconds: 100,
     97         readbackWire: null
     98       };
     99     }
    100     function transition(base: PrivateRecordHandle, f: unknown) {
    101       return preparePrivateReceiptTransition(
    102         base,
    103         owner,
    104         command,
    105         JSON.stringify(f)
    106       );
    107     }
    108     function next(base: PrivateRecordHandle, f: unknown) {
    109       const result = transition(base, f);
    110       if (!result.ok) throw Error('transition refused');
    111       const saved = privateReceiptTransitionSnapshot(
    112         result.value,
    113         owner,
    114         command
    115       );
    116       if (!saved) throw Error('missing transition');
    117       return saved.next;
    118     }
    119     return { row, owner, handle, fact, transition, next };
    120   } finally {
    121     conversation?.fill(0);
    122     key.fill(0);
    123     other.fill(0);
    124   }
    125 }
    126 describe('private named relay observations are separate local evidence', () => {
    127   it('legacy paired ciphertext without receipt metadata stays readable and uncertain', () => {
    128     const f = fixture(),
    129       h = f.handle();
    130     expect(privateRecordSnapshot(h, f.owner, command)).toEqual(f.row);
    131     const s = privateSendStatus(h, f.owner, command)!;
    132     expect(s.recipient.state).toBe('unknown');
    133     expect(s.archive.state).toBe('pending');
    134   });
    135   it('forged record and transition handles cannot supply status or receipt custody', () => {
    136     expect(
    137       privateSendStatus({} as PrivateRecordHandle, 'a'.repeat(64), command)
    138     ).toBeUndefined();
    139     expect(
    140       preparePrivateReceiptTransition(
    141         {} as PrivateRecordHandle,
    142         'a'.repeat(64),
    143         command,
    144         '{}'
    145       ).ok
    146     ).toBe(false);
    147   });
    148   it('archive acceptance alone never means recipient acceptance', () => {
    149     const f = fixture(),
    150       h = f.next(f.handle(), f.fact('self_archive'));
    151     const s = privateSendStatus(h, f.owner, command)!;
    152     expect(s.recipient.state).toBe('unknown');
    153     expect(s.archive.state).toBe('accepted_by_inbox_relay');
    154     expect(s.labels).toContain('Recipient delivery unknown');
    155     expect(s.partial).toBe(true);
    156   });
    157   it('recipient acceptance preserves the separate sender archive pending fact', () => {
    158     const f = fixture(),
    159       h = f.next(f.handle(), f.fact());
    160     const s = privateSendStatus(h, f.owner, command)!;
    161     expect(s.recipient.state).toBe('accepted_by_inbox_relay');
    162     expect(s.archive.state).toBe('pending');
    163     expect(s.labels).toContain('Sender archive pending');
    164   });
    165   it('late duplicate ACK is idempotent even when sampled later', () => {
    166     const f = fixture(),
    167       a = f.fact(),
    168       base = f.next(f.handle(), a),
    169       again = f.next(base, { ...a, observedAtMilliseconds: 200 });
    170     expect(privateRecordWire(again, f.owner, command)).toBe(
    171       privateRecordWire(base, f.owner, command)
    172     );
    173   });
    174   it('distinct refusal and later acceptance observations are both retained', () => {
    175     const f = fixture(),
    176       a = f.next(f.handle(), f.fact('peer', 'refused')),
    177       b = f.next(a, f.fact());
    178     const row = privateRecordSnapshot(b, f.owner, command);
    179     expect(
    180       row?.family === 'private_send_operation' &&
    181         row.receipts?.map((r) => r.status)
    182     ).toEqual(['refused', 'accepted']);
    183     expect(privateSendStatus(b, f.owner, command)?.recipient.state).toBe(
    184       'accepted_by_inbox_relay'
    185     );
    186   });
    187   it('exact peer ciphertext readback is separate from a relay ACK', () => {
    188     const f = fixture(),
    189       fact = {
    190         ...f.fact('peer', 'readback'),
    191         readbackWire: f.row.peerArtifact.wire
    192       },
    193       h = f.next(f.handle(), fact),
    194       s = privateSendStatus(h, f.owner, command)!;
    195     expect(s.recipient.readbackTargets).toEqual(['wss://peer.example.org']);
    196     expect(s.recipient.acceptedTargets).toEqual([]);
    197     expect(s.recipient.state).toBe('unknown');
    198   });
    199   it('archive ciphertext cannot serve as peer readback', () => {
    200     const f = fixture();
    201     expect(
    202       f.transition(f.handle(), {
    203         ...f.fact('peer', 'readback'),
    204         readbackWire: f.row.self.wire
    205       }).ok
    206     ).toBe(false);
    207   });
    208   it('wrong role destination event and unsupported plaintext fields refuse', () => {
    209     const f = fixture(),
    210       base = f.fact();
    211     for (const bad of [
    212       { ...base, role: 'publication' },
    213       { ...base, origin: 'wss://other.example.org' },
    214       { ...base, eventId: f.row.self.eventId },
    215       { ...base, body: 'PRIVATE_TEXT' },
    216       { ...base, readbackWire: f.row.peerArtifact.wire }
    217     ])
    218       expect(f.transition(f.handle(), bad).ok).toBe(false);
    219   });
    220   it('unsafe times attempts and arbitrary outcome strings refuse', () => {
    221     const f = fixture(),
    222       base = f.fact();
    223     for (const bad of [
    224       { ...base, attempt: 0 },
    225       { ...base, attempt: 4 },
    226       { ...base, observedAtMilliseconds: -1 },
    227       { ...base, observedAtMilliseconds: Number.MAX_SAFE_INTEGER + 1 },
    228       { ...base, status: 'delivered' }
    229     ])
    230       expect(f.transition(f.handle(), bad).ok).toBe(false);
    231   });
    232   it('unknown stopped timeout and refusal never imply recipient success', () => {
    233     const f = fixture();
    234     for (const status of ['unknown', 'stopped', 'timed_out', 'refused'])
    235       expect(
    236         privateSendStatus(
    237           f.next(f.handle(), f.fact('peer', status)),
    238           f.owner,
    239           command
    240         )?.recipient.state
    241       ).toBe('unknown');
    242   });
    243   it('receipt transitions preserve exact original ciphertext and frozen routes', () => {
    244     const f = fixture(),
    245       base = f.handle(),
    246       next = f.next(base, f.fact()),
    247       row = privateRecordSnapshot(next, f.owner, command);
    248     expect(row?.family === 'private_send_operation' && row.self).toEqual(
    249       f.row.self
    250     );
    251     expect(
    252       row?.family === 'private_send_operation' && row.peerArtifact
    253     ).toEqual(f.row.peerArtifact);
    254     expect(
    255       row?.family === 'private_send_operation' && row.deliveryPlan
    256     ).toEqual(f.row.deliveryPlan);
    257     expect(privateRecordWire(base, f.owner, command)).toBe(
    258       JSON.stringify(f.row)
    259     );
    260   });
    261   it('revision exhaustion refuses a new fact', () => {
    262     const f = fixture();
    263     expect(
    264       f.transition(
    265         f.handle({ ...f.row, revision: Number.MAX_SAFE_INTEGER }),
    266         f.fact()
    267       ).ok
    268     ).toBe(false);
    269   });
    270   it('receipt acquisition never coerces caller objects or noncanonical duplicate JSON', () => {
    271     const f = fixture();
    272     let calls = 0;
    273     const input = {
    274       toString() {
    275         calls++;
    276         return JSON.stringify(f.fact());
    277       }
    278     };
    279     expect(
    280       preparePrivateReceiptTransition(f.handle(), f.owner, command, input).ok
    281     ).toBe(false);
    282     expect(calls).toBe(0);
    283     const raw = JSON.stringify(f.fact());
    284     expect(
    285       preparePrivateReceiptTransition(
    286         f.handle(),
    287         f.owner,
    288         command,
    289         '{"status":"accepted",' + raw.slice(1)
    290       ).ok
    291     ).toBe(false);
    292   });
    293 });