app

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

local-records.test.ts (14450B)


      1 import { describe, expect, it } from 'vitest';
      2 import { finalizeEvent, getEventHash } from 'applesauce-core/helpers';
      3 import { verifyEnvelope } from '../../src/lib/nostr/verified-envelope.ts';
      4 import { LOCAL_PERSISTENCE_BUDGETS } from '../../src/lib/config/budgets.ts';
      5 import type {
      6   PublicDraftRecord,
      7   PublicRecord
      8 } from '../../src/lib/contracts/local-records.ts';
      9 import {
     10   decodePublicRecord,
     11   publicRecordSnapshot,
     12   publicRecordWire,
     13   decodeConversationMapping,
     14   conversationMappingSnapshot,
     15   type PublicRecordHandle
     16 } from '../../src/lib/persistence/records.ts';
     17 const owner =
     18   '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798';
     19 const peer = 'c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5';
     20 const id = '3d030bf5-901d-45e1-8251-41cbdf805e96';
     21 const anotherId = 'b1d6d23d-79f3-4779-9b03-e289712cc73f';
     22 const form = {
     23   title: '',
     24   description: '',
     25   location: '',
     26   amount: '.',
     27   currency: '',
     28   unit: '',
     29   quantity: '',
     30   contactType: '' as const,
     31   contactValue: ''
     32 };
     33 const draft: PublicDraftRecord = {
     34   schema: 1,
     35   family: 'public_draft',
     36   owner,
     37   id,
     38   revision: 0,
     39   savedAtMilliseconds: 1000,
     40   form
     41 };
     42 function read(value: unknown, expectedOwner = owner, expectedId = id) {
     43   return decodePublicRecord(JSON.stringify(value), expectedOwner, expectedId);
     44 }
     45 function operation(
     46   kind: 30402 | 5 | 10050,
     47   tagsOverride?: (eventId: string, pubkey: string) => string[][],
     48   createdAt = 101
     49 ) {
     50   const key = crypto.getRandomValues(new Uint8Array(32));
     51   try {
     52     const base = finalizeEvent(
     53       {
     54         kind: kind === 10050 ? 10050 : 30402,
     55         created_at: 100,
     56         tags:
     57           kind === 10050
     58             ? []
     59             : [
     60                 ['d', 'public'],
     61                 ['published_at', '100']
     62               ],
     63         content: 'public source fixture'
     64       },
     65       key
     66     );
     67     const template = {
     68       pubkey: base.pubkey,
     69       kind,
     70       created_at: createdAt,
     71       tags: tagsOverride
     72         ? tagsOverride(base.id, base.pubkey)
     73         : kind === 5
     74           ? [
     75               ['e', base.id],
     76               ['a', `30402:${base.pubkey}:public`]
     77             ]
     78           : kind === 10050
     79             ? []
     80             : [
     81                 ['d', 'public'],
     82                 ['published_at', '100']
     83               ],
     84       content: 'public outgoing fixture'
     85     };
     86     const templateWire = JSON.stringify(template);
     87     const templateHash = getEventHash(template);
     88     const artifact = finalizeEvent(
     89       { ...template, tags: template.tags.map((tag) => [...tag]) },
     90       key
     91     );
     92     return {
     93       schema: 1,
     94       family: kind === 10050 ? 'preference_operation' : 'public_operation',
     95       owner: base.pubkey,
     96       id,
     97       revision: 1,
     98       ...(kind === 10050 ? { consent: 'explicit_review' } : {}),
     99       source: {
    100         type: kind === 10050 ? 'inbox_head' : 'public_head',
    101         wire: JSON.stringify(base)
    102       },
    103       capture: {
    104         kind,
    105         wire: templateWire,
    106         hash: templateHash,
    107         targets: ['wss://one.example.org'],
    108         policyFingerprint: 'a'.repeat(64)
    109       },
    110       artifact: { eventId: artifact.id, wire: JSON.stringify(artifact) },
    111       receipts: [
    112         {
    113           actionId: anotherId,
    114           origin: 'wss://one.example.org',
    115           role: kind === 10050 ? 'preference' : 'publication',
    116           attempt: 1,
    117           eventId: artifact.id,
    118           status: 'accepted',
    119           observedAtMilliseconds: 1234,
    120           readbackWire: JSON.stringify(artifact)
    121         }
    122       ]
    123     };
    124   } finally {
    125     key.fill(0);
    126   }
    127 }
    128 describe('owner-scoped canonical public record codecs', () => {
    129   it('preserves incomplete strings exactly without publication validation', () => {
    130     const result = read(draft);
    131     expect(result.ok).toBe(true);
    132     if (!result.ok) throw new Error(result.reason);
    133     expect(publicRecordSnapshot(result.value, owner, id)).toEqual(draft);
    134     expect(publicRecordWire(result.value, owner, id)).toBe(
    135       JSON.stringify(draft)
    136     );
    137   });
    138   it('rejects cross-owner/cross-ID decoding and handle reads', () => {
    139     expect(read(draft, peer)).toEqual({ ok: false, reason: 'owner_mismatch' });
    140     expect(read(draft, owner, anotherId)).toEqual({
    141       ok: false,
    142       reason: 'id_mismatch'
    143     });
    144     const result = read(draft);
    145     if (!result.ok) throw new Error(result.reason);
    146     expect(publicRecordSnapshot(result.value, peer, id)).toBeUndefined();
    147     expect(publicRecordWire(result.value, owner, anotherId)).toBeUndefined();
    148   });
    149   it('rejects noncanonical owner/UUID scope rather than normalizing it', () => {
    150     for (const bad of ['', owner.toUpperCase(), '0'.repeat(64)])
    151       expect(read(draft, bad).ok).toBe(false);
    152     for (const bad of ['', id.toUpperCase(), 'a'.repeat(64)])
    153       expect(read(draft, owner, bad).ok).toBe(false);
    154   });
    155   for (const schema of [0, 2, '1', null])
    156     it(`rejects unknown schema ${String(schema)}`, () => {
    157       expect(read({ ...draft, schema })).toEqual({
    158         ok: false,
    159         reason: 'unsupported_schema'
    160       });
    161     });
    162   it('rejects malformed/noncanonical/duplicate-key input without coercion', () => {
    163     for (const raw of [
    164       '{',
    165       'null',
    166       '[]',
    167       JSON.stringify(draft, null, 2),
    168       JSON.stringify(draft).replace('"schema":1', '"schema":2,"schema":1'),
    169       JSON.stringify(draft).replace('"revision":0', '"revision":-0')
    170     ])
    171       expect(decodePublicRecord(raw, owner, id).ok).toBe(false);
    172   });
    173   it('does not inspect getters on non-string database input', () => {
    174     let touched = false;
    175     const raw = {
    176       get schema() {
    177         touched = true;
    178         throw new Error('test-only');
    179       }
    180     };
    181     expect(decodePublicRecord(raw, owner, id)).toEqual({
    182       ok: false,
    183       reason: 'malformed'
    184     });
    185     expect(touched).toBe(false);
    186   });
    187   it('bounds malformed raw bytes before parsing', () => {
    188     expect(
    189       decodePublicRecord(
    190         'x'.repeat(LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes + 1),
    191         owner,
    192         id
    193       )
    194     ).toEqual({ ok: false, reason: 'oversized' });
    195     expect(
    196       decodePublicRecord(
    197         'é'.repeat(LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes / 2 + 1),
    198         owner,
    199         id
    200       )
    201     ).toEqual({ ok: false, reason: 'oversized' });
    202   });
    203   it('counts composed UTF8 at the inclusive draft limit', () => {
    204     const blank = { ...form, amount: '' };
    205     expect(
    206       read({ ...draft, form: { ...blank, description: 'é'.repeat(8192) } }).ok
    207     ).toBe(true);
    208     expect(
    209       read({
    210         ...draft,
    211         form: { ...blank, description: 'é'.repeat(8192), title: 'x' }
    212       }).ok
    213     ).toBe(false);
    214     expect(
    215       read({ ...draft, form: { ...blank, description: '\ud800' } }).ok
    216     ).toBe(false);
    217   });
    218   it('rejects unknown/private fields, raw private families and unsafe revisions', () => {
    219     for (const record of [
    220       { ...draft, body: 'test-only private body' },
    221       { ...draft, family: 'private_message' },
    222       { ...draft, form: { ...form, subject: 'test-only' } },
    223       { ...draft, revision: -1 },
    224       { ...draft, revision: Number.MAX_SAFE_INTEGER + 1 },
    225       { ...draft, savedAtMilliseconds: -1 },
    226       { ...draft, form: { ...form, contactType: 'legacy' } }
    227     ])
    228       expect(read(record).ok).toBe(false);
    229     // Executable TypeScript check: a private-body field has no public member.
    230     const wrong: PublicRecord = {
    231       ...draft,
    232       // @ts-expect-error private body is outside the public record contract
    233       body: 'test-only private body'
    234     };
    235     expect(read(wrong).ok).toBe(false);
    236   });
    237   it('detaches snapshots and rejects fabricated capabilities', () => {
    238     const result = read(draft);
    239     if (!result.ok) throw new Error(result.reason);
    240     const first = publicRecordSnapshot(
    241       result.value,
    242       owner,
    243       id
    244     ) as PublicDraftRecord;
    245     Object.assign(first.form, { description: 'changed' });
    246     expect(publicRecordSnapshot(result.value, owner, id)).toEqual(draft);
    247     expect(
    248       publicRecordSnapshot(Object.freeze({}) as PublicRecordHandle, owner, id)
    249     ).toBeUndefined();
    250   });
    251   for (const kind of [30402, 5, 10050] as const)
    252     it(`binds actual signed ${kind} artifacts and separate named ACK/readback metadata`, () => {
    253       const value = operation(kind),
    254         result = read(value, value.owner);
    255       expect(result.ok).toBe(true);
    256       if (!result.ok) throw new Error(result.reason);
    257       expect(publicRecordSnapshot(result.value, value.owner, id)).toEqual(
    258         value
    259       );
    260     });
    261   it('rejects changed template/hash, artifact identity and destination bindings', () => {
    262     const value = operation(30402);
    263     for (const row of [
    264       { ...value, capture: { ...value.capture, hash: 'b'.repeat(64) } },
    265       {
    266         ...value,
    267         capture: {
    268           ...value.capture,
    269           wire: value.capture.wire.replace('outgoing', 'changed')
    270         }
    271       },
    272       {
    273         ...value,
    274         capture: {
    275           ...value.capture,
    276           targets: ['wss://one.example.org', 'wss://one.example.org']
    277         }
    278       },
    279       { ...value, capture: { ...value.capture, targets: ['wss://127.0.0.1'] } },
    280       { ...value, artifact: { ...value.artifact, eventId: 'b'.repeat(64) } },
    281       {
    282         ...value,
    283         receipts: [{ ...value.receipts[0], origin: 'wss://other.example.org' }]
    284       },
    285       { ...value, receipts: [{ ...value.receipts[0], attempt: 4 }] },
    286       { ...value, receipts: [{ ...value.receipts[0], role: 'archive' }] },
    287       {
    288         ...value,
    289         receipts: [{ ...value.receipts[0], eventId: 'b'.repeat(64) }]
    290       },
    291       { ...value, artifact: null }
    292     ])
    293       expect(read(row, value.owner).ok).toBe(false);
    294   });
    295   it('binds genuine replacement coordinates, original publication time and advancing revision time', () => {
    296     for (const value of [
    297       operation(30402, () => [
    298         ['d', 'other'],
    299         ['published_at', '100']
    300       ]),
    301       operation(30402, () => [
    302         ['d', 'public'],
    303         ['published_at', '101']
    304       ]),
    305       operation(30402, undefined, 100)
    306     ])
    307       expect(read(value, value.owner).ok).toBe(false);
    308   });
    309   it('binds genuine withdrawal to the captured version/coordinate and rejects additional unrelated targets', () => {
    310     for (const value of [
    311       operation(5, () => [['e', 'b'.repeat(64)]]),
    312       operation(5, (_, pubkey) => [['a', `30402:${pubkey}:other`]]),
    313       operation(5, (eventId) => [
    314         ['e', eventId],
    315         ['e', 'b'.repeat(64)]
    316       ]),
    317       operation(5, () => []),
    318       operation(5, undefined, 99)
    319     ])
    320       expect(read(value, value.owner).ok).toBe(false);
    321   });
    322   it('preserves original verified signed-wire layout while outer/template serialization stays canonical', () => {
    323     const value = operation(30402);
    324     function formatted(wire: string) {
    325       const parsed: unknown = JSON.parse(wire);
    326       return JSON.stringify(parsed, null, 2);
    327     }
    328     const aliases = {
    329       ...value,
    330       source: { ...value.source, wire: formatted(value.source.wire) },
    331       artifact: { ...value.artifact, wire: formatted(value.artifact.wire) },
    332       receipts: [
    333         {
    334           ...value.receipts[0],
    335           readbackWire: formatted(value.receipts[0].readbackWire)
    336         }
    337       ]
    338     };
    339     const ready = read(aliases, aliases.owner);
    340     expect(ready.ok).toBe(true);
    341     if (!ready.ok) throw new Error(ready.reason);
    342     expect(publicRecordSnapshot(ready.value, aliases.owner, id)).toEqual(
    343       aliases
    344     );
    345   });
    346   it('admits prepared-only records with no remote receipt claims', () => {
    347     const value = operation(30402);
    348     expect(
    349       read(
    350         {
    351           ...value,
    352           artifact: null,
    353           receipts: [],
    354           source: { type: 'draft', id, revision: 0 }
    355         },
    356         value.owner
    357       ).ok
    358     ).toBe(true);
    359   });
    360   it('rejects private signed kinds and forged signature/readback', () => {
    361     const value = operation(30402);
    362     for (const kind of [14, 13, 1059]) {
    363       // Genuine generic NIP01 signatures for forbidden kinds, not qualified
    364       // private message construction/encryption. Runtime input ignores TS casts.
    365       const privateKind = operation(kind as 30402);
    366       expect(verifyEnvelope(privateKind.artifact.wire).ok).toBe(true);
    367       expect(read(privateKind, privateKind.owner).ok).toBe(false);
    368     }
    369     const artifact = JSON.parse(value.artifact.wire) as {
    370       sig: string;
    371       kind: number;
    372     };
    373     artifact.sig = '0'.repeat(128);
    374     expect(
    375       read(
    376         {
    377           ...value,
    378           artifact: { ...value.artifact, wire: JSON.stringify(artifact) }
    379         },
    380         value.owner
    381       ).ok
    382     ).toBe(false);
    383     expect(
    384       read(
    385         {
    386           ...value,
    387           receipts: [{ ...value.receipts[0], readbackWire: value.source.wire }]
    388         },
    389         value.owner
    390       ).ok
    391     ).toBe(false);
    392   });
    393   it('keeps preference consent/source/role distinct from public operations', () => {
    394     const value = operation(10050);
    395     for (const row of [
    396       { ...value, consent: 'inferred' },
    397       { ...value, source: { type: 'draft', id, revision: 0 } },
    398       { ...value, family: 'public_operation' },
    399       { ...value, receipts: [{ ...value.receipts[0], role: 'publication' }] }
    400     ])
    401       expect(read(row, value.owner).ok).toBe(false);
    402   });
    403 });
    404 describe('separate opaque conversation mapping contracts', () => {
    405   const mapping = { schema: 1, family: 'conversation_handle', owner, id, peer };
    406   it('binds two distinct validated keys to an opaque local UUID', () => {
    407     const result = decodeConversationMapping(
    408       JSON.stringify(mapping),
    409       owner,
    410       id
    411     );
    412     expect(result.ok).toBe(true);
    413     if (!result.ok) throw new Error(result.reason);
    414     expect(conversationMappingSnapshot(result.value, owner, id)).toEqual(
    415       mapping
    416     );
    417     expect(conversationMappingSnapshot(result.value, peer, id)).toBeUndefined();
    418     expect(read(mapping).ok).toBe(false);
    419   });
    420   it('rejects self peer, private plaintext/listing fields and unknown scope', () => {
    421     for (const row of [
    422       { ...mapping, peer: owner },
    423       { ...mapping, peer: '0'.repeat(64) },
    424       { ...mapping, body: 'test-only' },
    425       { ...mapping, listing: 'test-only' },
    426       { ...mapping, schema: 2 }
    427     ])
    428       expect(decodeConversationMapping(JSON.stringify(row), owner, id).ok).toBe(
    429         false
    430       );
    431     expect(
    432       decodeConversationMapping(JSON.stringify(mapping), peer, id).ok
    433     ).toBe(false);
    434   });
    435 });