app

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

conversation-thread.test.ts (9226B)


      1 import { describe, expect, it } from 'vitest';
      2 import { getPublicKey, finalizeEvent } from 'applesauce-core/helpers';
      3 import { nip44 } from 'applesauce-core/helpers/encryption';
      4 import { projectConversationThread } from '../../src/lib/messaging/conversation-thread.ts';
      5 import type { ConversationData } from '../../src/lib/messaging/admit-conversation.ts';
      6 import { encodeProductReference } from '../../src/lib/nostr/references.ts';
      7 import { decodePrivateRecord } from '../../src/lib/persistence/private-records.ts';
      8 import {
      9   resolveInboxConversation,
     10   inboxThreadSnapshot,
     11   inboxMessageSnapshot,
     12   markInboxConversationDisplayed,
     13   type InboxView
     14 } from '../../src/lib/messaging/inbox-view.ts';
     15 
     16 const owner = getPublicKey(new Uint8Array(32).fill(83)),
     17   peer = getPublicKey(new Uint8Array(32).fill(84)),
     18   other = getPublicKey(new Uint8Array(32).fill(85)),
     19   command = '12345678-1234-4234-8234-123456789abc';
     20 function message(overrides: Partial<ConversationData> = {}): ConversationData {
     21   return {
     22     owner,
     23     peer,
     24     sender: peer,
     25     recipient: owner,
     26     role: 'inbound',
     27     rumorId: 'a'.repeat(64),
     28     createdAt: 1700000000,
     29     content: 'Actual message text',
     30     subject: null,
     31     replyTo: null,
     32     ...overrides
     33   };
     34 }
     35 function archive(overrides: Partial<ConversationData> = {}): ConversationData {
     36   return message({
     37     role: 'self_archive',
     38     sender: owner,
     39     recipient: peer,
     40     ...overrides
     41   });
     42 }
     43 // Structural local receipt projection fixture; no factory, native commit or
     44 // real target delivery authority is claimed by this pure unit fixture.
     45 function receipt(role: 'peer' | 'self_archive', rumorHash = 'a'.repeat(64)) {
     46   const key = new Uint8Array(32).fill(83);
     47   try {
     48     function artifact(destination: string) {
     49       const conversation = nip44.v2.utils.getConversationKey(key, destination);
     50       try {
     51         const event = finalizeEvent(
     52           {
     53             kind: 1059,
     54             created_at: 1700000000,
     55             tags: [['p', destination]],
     56             content: nip44.v2.encrypt(
     57               'Structural codec fixture only',
     58               conversation
     59             )
     60           },
     61           key
     62         );
     63         return { eventId: event.id, wire: JSON.stringify(event) };
     64       } finally {
     65         conversation.fill(0);
     66       }
     67     }
     68     function route(
     69       author: string,
     70       kind: 'peer' | 'self_archive',
     71       origin: string
     72     ) {
     73       return {
     74         author,
     75         role: kind,
     76         targets: [origin],
     77         knownBase: { author, id: 'b'.repeat(64), createdAt: 1 },
     78         sources: [{ source: 'wss://discovery.example.org', state: 'eose' }]
     79       };
     80     }
     81     const self = artifact(owner),
     82       peerArtifact = artifact(peer),
     83       row = {
     84         schema: 1,
     85         family: 'private_send_operation',
     86         owner,
     87         id: command,
     88         revision: 3,
     89         peer,
     90         rumorHash,
     91         createdAt: 1700000000,
     92         self,
     93         peerArtifact,
     94         deliveryPlan: {
     95           state: 'prepared',
     96           routes: {
     97             peer: route(peer, 'peer', 'wss://peer.example.org'),
     98             archive: route(owner, 'self_archive', 'wss://archive.example.org')
     99           }
    100         },
    101         receipts: [
    102           {
    103             actionId: '12345678-1234-4234-8234-123456789abd',
    104             role,
    105             origin:
    106               role === 'peer'
    107                 ? 'wss://peer.example.org'
    108                 : 'wss://archive.example.org',
    109             attempt: 1,
    110             eventId: role === 'peer' ? peerArtifact.eventId : self.eventId,
    111             status: 'accepted',
    112             observedAtMilliseconds: 100,
    113             readbackWire: null
    114           }
    115         ]
    116       },
    117       decoded = decodePrivateRecord(JSON.stringify(row), owner, command);
    118     if (!decoded.ok) throw Error('invalid structural codec fixture');
    119     return decoded.value;
    120   } finally {
    121     key.fill(0);
    122   }
    123 }
    124 describe('detached plain chronological pair presentation grants no custody', () => {
    125   it('orders by actual inner time then stable rumor identity without room-level product state', () => {
    126     const first = message({
    127         rumorId: 'b'.repeat(64),
    128         createdAt: 2,
    129         content: 'About apples'
    130       }),
    131       second = archive({ createdAt: 1, content: 'About carrots' }),
    132       view = projectConversationThread(owner, peer, [first, second], []);
    133     expect(view.status).toBe('ready');
    134     expect(view.messages.map((row) => row.data.content)).toEqual([
    135       'About carrots',
    136       'About apples'
    137     ]);
    138     expect(view.messages.map((row) => row.data.role)).toEqual([
    139       'self_archive',
    140       'inbound'
    141     ]);
    142   });
    143   it('deduplicates the same verified rumor and returns detached independent rows', () => {
    144     const original = message(),
    145       view = projectConversationThread(
    146         owner,
    147         peer,
    148         [original, { ...original }],
    149         []
    150       );
    151     expect(view.messages).toHaveLength(1);
    152     expect(view.messages[0].data).not.toBe(original);
    153     expect(original.content).toBe('Actual message text');
    154   });
    155   it('rejects conflicting same-rumor data instead of substituting later bytes', () => {
    156     expect(
    157       projectConversationThread(
    158         owner,
    159         peer,
    160         [message(), message({ content: 'Changed' })],
    161         []
    162       ).status
    163     ).toBe('unavailable');
    164   });
    165   it('rejects foreign owner, different pair and false sender roles', () => {
    166     for (const row of [
    167       message({ owner: other }),
    168       message({ peer: other }),
    169       message({ sender: owner })
    170     ])
    171       expect(projectConversationThread(owner, peer, [row], []).status).toBe(
    172         'unavailable'
    173       );
    174   });
    175   it('keeps canonical public citations on their own message without promoting a listing claim', () => {
    176     const carrots = encodeProductReference({
    177         kind: 30402,
    178         pubkey: peer,
    179         identifier: 'carrots'
    180       })!,
    181       apples = encodeProductReference({
    182         kind: 30402,
    183         pubkey: peer,
    184         identifier: 'apples'
    185       })!,
    186       view = projectConversationThread(
    187         owner,
    188         peer,
    189         [
    190           message({ content: 'Product: nostr:' + carrots }),
    191           message({
    192             rumorId: 'b'.repeat(64),
    193             content: 'Product: nostr:' + apples
    194           })
    195         ],
    196         []
    197       );
    198     expect(view.messages[0].citations.map((row) => row.naddr)).toEqual([
    199       carrots
    200     ]);
    201     expect(view.messages[1].citations.map((row) => row.naddr)).toEqual([
    202       apples
    203     ]);
    204   });
    205   it('preserves quoted price and hostile text as text without HTML or external URL projection', () => {
    206     const content =
    207         '<img src=x> Quoted price 4 GBP https://untrusted.example.org nostr:naddr1invalid',
    208       view = projectConversationThread(owner, peer, [message({ content })], []);
    209     expect(view.messages[0].data.content).toBe(content);
    210     expect(view.messages[0].citations).toEqual([]);
    211   });
    212   it('recognizes only a present parent in the same admitted pair without an external private-ID lookup', () => {
    213     const parent = message(),
    214       reply = archive({ rumorId: 'b'.repeat(64), replyTo: parent.rumorId }),
    215       missing = message({ rumorId: 'c'.repeat(64), replyTo: 'd'.repeat(64) }),
    216       view = projectConversationThread(
    217         owner,
    218         peer,
    219         [parent, reply, missing],
    220         []
    221       );
    222     expect(
    223       view.messages.find((row) => row.data.rumorId === reply.rumorId)?.parent
    224     ).toBe('present');
    225     expect(
    226       view.messages.find((row) => row.data.rumorId === missing.rumorId)?.parent
    227     ).toBe('missing');
    228   });
    229   it('never upgrades sender archive acceptance to recipient acceptance or reports incoming remote reads', () => {
    230     const view = projectConversationThread(
    231       owner,
    232       peer,
    233       [archive()],
    234       [receipt('self_archive')]
    235     );
    236     expect(view.messages[0].delivery).toContain('Recipient delivery unknown');
    237     expect(view.messages[0].delivery).not.toContain(
    238       'Accepted by recipient inbox relay'
    239     );
    240     expect(
    241       projectConversationThread(owner, peer, [message()], [receipt('peer')])
    242         .messages[0].delivery
    243     ).toBeNull();
    244   });
    245   it('uses only an exact local owner peer rumor receipt projection, never a different message fact', () => {
    246     expect(
    247       projectConversationThread(owner, peer, [archive()], [receipt('peer')])
    248         .messages[0].delivery
    249     ).toContain('Accepted by recipient inbox relay');
    250     expect(
    251       projectConversationThread(
    252         owner,
    253         peer,
    254         [archive()],
    255         [receipt('peer', 'b'.repeat(64))]
    256       ).messages[0].delivery
    257     ).toContain('Recipient delivery unknown');
    258   });
    259   it('unavailable copied and SSR controllers cannot import thread bodies or native display custody', async () => {
    260     const fake = {} as InboxView;
    261     expect(inboxThreadSnapshot(fake, command).status).toBe('unavailable');
    262     expect(inboxMessageSnapshot(fake, command, 'a'.repeat(64))).toBeUndefined();
    263     expect(
    264       await resolveInboxConversation(
    265         fake,
    266         command,
    267         'reviewed_conversation_navigation'
    268       )
    269     ).toBe(false);
    270     expect(
    271       await markInboxConversationDisplayed(
    272         fake,
    273         command,
    274         ['a'.repeat(64)],
    275         'reviewed_displayed_conversation'
    276       )
    277     ).toBe(false);
    278   });
    279 });