app

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

private-hostile.test.ts (9229B)


      1 import assert from 'node:assert/strict';
      2 import { test } from 'node:test';
      3 import {
      4   generateSecretKey,
      5   getPublicKey,
      6   getEventHash,
      7   finalizeEvent,
      8   verifyEvent,
      9   verifiedSymbol,
     10   type UnsignedEvent
     11 } from 'applesauce-core/helpers';
     12 import { nip44 } from 'applesauce-core/helpers/encryption';
     13 import { verifyReceivedLayerData } from '../../src/lib/nostr/unwrap-admission.ts';
     14 import { verifyEnvelope } from '../../src/lib/nostr/verified-envelope.ts';
     15 import {
     16   getPublicStore,
     17   insertPublicEnvelope,
     18   publicStoreEnvelope,
     19   publicStoreRetention,
     20   closePublicStore
     21 } from '../../src/lib/nostr/public-store.ts';
     22 function fixture() {
     23   const keys = [generateSecretKey(), generateSecretKey(), generateSecretKey()];
     24   const sender = getPublicKey(keys[0]),
     25     owner = getPublicKey(keys[1]),
     26     other = getPublicKey(keys[2]);
     27   const template: UnsignedEvent = {
     28     pubkey: sender,
     29     kind: 14,
     30     created_at: 1700000000,
     31     tags: [['p', owner]],
     32     content: 'Private hostile-input qualification canary'
     33   };
     34   const rumor = { id: getEventHash(template), ...template };
     35   function encrypt(key: Uint8Array, target: string, plain: string) {
     36     const conversation = nip44.v2.utils.getConversationKey(key, target);
     37     try {
     38       return nip44.v2.encrypt(plain, conversation);
     39     } finally {
     40       conversation.fill(0);
     41     }
     42   }
     43   const seal = finalizeEvent(
     44     {
     45       kind: 13,
     46       created_at: 1699999900,
     47       tags: [],
     48       content: encrypt(keys[0], owner, JSON.stringify(rumor))
     49     },
     50     keys[0]
     51   );
     52   const outer = finalizeEvent(
     53     {
     54       kind: 1059,
     55       created_at: 1699999800,
     56       tags: [['p', owner]],
     57       content: encrypt(keys[2], owner, JSON.stringify(seal))
     58     },
     59     keys[2]
     60   );
     61   const wire = [outer, seal, rumor].map((value) => JSON.stringify(value));
     62   const check = (values: readonly unknown[], expected: unknown = owner) =>
     63     verifyReceivedLayerData(values[0], values[1], values[2], expected);
     64   return {
     65     keys,
     66     sender,
     67     owner,
     68     other,
     69     rumor,
     70     seal,
     71     outer,
     72     wire,
     73     check,
     74     close: () => keys.forEach((key) => key.fill(0))
     75   };
     76 }
     77 await test('finite adversarial nested matrix refuses altered IDs, signatures, author, target, schema and numeric spelling while preserving the next valid candidate', () => {
     78   const f = fixture();
     79   try {
     80     assert.equal(f.check(f.wire), true);
     81     const candidates: { label: string; layer: number; value: string }[] = [];
     82     for (const [index, original] of [f.outer, f.seal, f.rumor].entries()) {
     83       const raw = JSON.stringify(original);
     84       for (const [field, value] of [
     85         ['id', '0'.repeat(64)],
     86         ['pubkey', f.owner],
     87         ['kind', 15],
     88         ['content', 'altered plaintext or ciphertext'],
     89         ['created_at', 1700000001],
     90         ['verified', true]
     91       ] as const)
     92         candidates.push({
     93           label: `${index}:${field}`,
     94           layer: index,
     95           value: JSON.stringify({ ...original, [field]: value })
     96         });
     97       candidates.push({
     98         label: `${index}:duplicate`,
     99         layer: index,
    100         value: raw.replace('"kind":', '"kind":1,"kind":')
    101       });
    102       const escapedDuplicate = raw.replace('"kind":', '"k\\u0069nd":1,"kind":');
    103       assert.notEqual(escapedDuplicate, raw);
    104       assert.deepEqual(JSON.parse(escapedDuplicate), JSON.parse(raw));
    105       candidates.push({
    106         label: `${index}:escaped-duplicate`,
    107         layer: index,
    108         value: escapedDuplicate
    109       });
    110       candidates.push({
    111         label: `${index}:numeric-spelling`,
    112         layer: index,
    113         value: raw.replace(/"created_at":([0-9]+)/u, '"created_at":$1.0')
    114       });
    115       candidates.push({
    116         label: `${index}:invalid-json`,
    117         layer: index,
    118         value: raw.slice(0, -1)
    119       });
    120     }
    121     for (const [index, original] of [f.outer, f.seal].entries())
    122       candidates.push({
    123         label: `${index}:signature`,
    124         layer: index,
    125         value: JSON.stringify({ ...original, sig: '0'.repeat(128) })
    126       });
    127     candidates.push({
    128       label: 'outer:valid-wrong-destination',
    129       layer: 0,
    130       value: JSON.stringify(
    131         finalizeEvent({ ...f.outer, tags: [['p', f.sender]] }, f.keys[2])
    132       )
    133     });
    134     candidates.push({
    135       label: 'seal:valid-other-signer',
    136       layer: 1,
    137       value: JSON.stringify(finalizeEvent({ ...f.seal }, f.keys[1]))
    138     });
    139     candidates.push({
    140       label: 'seal:valid-metadata',
    141       layer: 1,
    142       value: JSON.stringify(
    143         finalizeEvent({ ...f.seal, tags: [['subject', 'private']] }, f.keys[0])
    144       )
    145     });
    146     for (const [label, tags, kind] of [
    147       [
    148         'group',
    149         [
    150           ['p', f.owner],
    151           ['p', f.other]
    152         ],
    153         14
    154       ],
    155       [
    156         'duplicate-peer',
    157         [
    158           ['p', f.owner],
    159           ['p', f.owner]
    160         ],
    161         14
    162       ],
    163       ['self-request', [['p', f.sender]], 14],
    164       [
    165         'file',
    166         [
    167           ['p', f.owner],
    168           ['file', 'https://example.org/a']
    169         ],
    170         15
    171       ],
    172       [
    173         'unsupported-expiration',
    174         [
    175           ['p', f.owner],
    176           ['expiration', '1700000001']
    177         ],
    178         14
    179       ]
    180     ] as const) {
    181       const changed: UnsignedEvent = {
    182         ...f.rumor,
    183         kind,
    184         tags: tags.map((row) => [...row])
    185       };
    186       candidates.push({
    187         label,
    188         layer: 2,
    189         value: JSON.stringify({ ...changed, id: getEventHash(changed) })
    190       });
    191     }
    192     assert.equal(candidates.length, 40);
    193     // D09 accepts this former negative as inert incoming metadata. Detached
    194     // parsing proves no ciphertext correspondence, order flow or effect authority.
    195     const inert: UnsignedEvent = {
    196       ...f.rumor,
    197       tags: [
    198         ['p', f.owner],
    199         ['order', 'unsupported']
    200       ]
    201     };
    202     assert.equal(
    203       f.check([
    204         f.wire[0],
    205         f.wire[1],
    206         JSON.stringify({ ...inert, id: getEventHash(inert) })
    207       ]),
    208       true
    209     );
    210     for (const row of candidates) {
    211       const values = [...f.wire];
    212       values[row.layer] = row.value;
    213       assert.equal(f.check(values), false, row.label);
    214       assert.equal(f.check(f.wire), true, `valid after ${row.label}`);
    215     }
    216     assert.equal(f.check(f.wire, f.other), false);
    217     assert.equal(f.check(f.wire, { toString: () => f.owner }), false);
    218   } finally {
    219     f.close();
    220   }
    221 });
    222 await test('actual SDK cached verified symbols and caller objects cannot replace fresh private layer parsing', () => {
    223   const f = fixture();
    224   try {
    225     for (const [index, original] of [f.outer, f.seal].entries()) {
    226       const cached = {
    227         ...original,
    228         tags: original.tags.map((tag) => [...tag])
    229       };
    230       assert.equal(verifyEvent(cached), true);
    231       assert.equal(
    232         (cached as unknown as Record<symbol, unknown>)[verifiedSymbol],
    233         true
    234       );
    235       cached.content += 'A';
    236       assert.equal(verifyEvent(cached), true);
    237       const values: unknown[] = [...f.wire];
    238       values[index] = JSON.stringify(cached);
    239       assert.equal(f.check(values), false);
    240       values[index] = cached;
    241       assert.equal(f.check(values), false);
    242     }
    243     let calls = 0;
    244     const value = {
    245       toJSON() {
    246         calls++;
    247         return f.rumor;
    248       },
    249       toString() {
    250         calls++;
    251         return f.wire[2];
    252       }
    253     };
    254     assert.equal(f.check([f.wire[0], f.wire[1], value]), false);
    255     assert.equal(calls, 0);
    256     assert.equal(f.check(f.wire), true);
    257   } finally {
    258     f.close();
    259   }
    260 });
    261 await test('actual owned public SDK store refuses signed private kinds before retention and remains usable for public inventory', () => {
    262   const f = fixture(),
    263     oldWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
    264   Object.defineProperty(globalThis, 'window', {
    265     configurable: true,
    266     value: {}
    267   });
    268   let store: ReturnType<typeof getPublicStore> = undefined;
    269   try {
    270     store = getPublicStore();
    271     assert.ok(store);
    272     const before = publicStoreRetention(store);
    273     const events = [f.outer, f.seal, finalizeEvent({ ...f.rumor }, f.keys[0])];
    274     for (const event of events) {
    275       const proof = verifyEnvelope(JSON.stringify(event));
    276       assert.equal(proof.ok, true);
    277       if (!proof.ok) throw new Error('invalid real signed control');
    278       assert.equal(insertPublicEnvelope(store, proof.value), 'not_public');
    279       assert.equal(publicStoreEnvelope(store, event.id), undefined);
    280       assert.deepEqual(publicStoreRetention(store), before);
    281     }
    282     const publicEvent = finalizeEvent(
    283       {
    284         kind: 10050,
    285         created_at: 1700000000,
    286         tags: [['relay', 'wss://inbox.example.org']],
    287         content: ''
    288       },
    289       f.keys[0]
    290     );
    291     const publicProof = verifyEnvelope(JSON.stringify(publicEvent));
    292     assert.equal(publicProof.ok, true);
    293     if (!publicProof.ok) throw new Error('invalid public control');
    294     assert.equal(insertPublicEnvelope(store, publicProof.value), 'accepted');
    295     assert.ok(publicStoreEnvelope(store, publicEvent.id));
    296     assert.equal(f.check(f.wire), true);
    297   } finally {
    298     if (store) closePublicStore(store);
    299     if (oldWindow) Object.defineProperty(globalThis, 'window', oldWindow);
    300     else Reflect.deleteProperty(globalThis, 'window');
    301     f.close();
    302   }
    303 });