app

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

food-writer.test.ts (10064B)


      1 import { describe, expect, it } from 'vitest';
      2 import {
      3   buildFoodTemplate,
      4   type FoodDraft
      5 } from '../../src/lib/contracts/food-availability-v1/write.ts';
      6 import { publicContact } from '../../src/lib/contracts/food-availability-v1/contact.ts';
      7 import { foodUnits } from '../../src/lib/contracts/food-availability-v1/values.ts';
      8 const draft: FoodDraft = {
      9   identifier: 'fixed-draft-id',
     10   title: 'Carrots',
     11   description: 'Fresh carrots.\nCollected locally.',
     12   location: 'Victoria',
     13   created_at: 1700000060,
     14   published_at: 1700000000,
     15   amount: '3.5',
     16   currency: 'CAD',
     17   unit: 'lb',
     18   quantity: '10',
     19   status: 'active'
     20 };
     21 function valid(value: FoodDraft) {
     22   const result = buildFoodTemplate(value);
     23   expect(result.ok).toBe(true);
     24   if (!result.ok) throw new Error(result.error.code);
     25   return result;
     26 }
     27 describe('known fields are read once before validation', () => {
     28   it('title getter cannot replace the validated title', () => {
     29     let reads = 0;
     30     const r = valid({
     31       ...draft,
     32       get title() {
     33         return ++reads === 1 ? 'Carrots' : 'x'.repeat(161);
     34       }
     35     });
     36     expect(reads).toBe(1);
     37     expect(r.wire_parts.tags[1]).toEqual(['title', 'Carrots']);
     38   });
     39   it('description getter cannot replace the bounded description', () => {
     40     let reads = 0;
     41     const r = valid({
     42       ...draft,
     43       get description() {
     44         return ++reads === 1 ? 'Carrots' : 'x'.repeat(20000);
     45       }
     46     });
     47     expect(reads).toBe(1);
     48     expect(r.wire_parts.content).toBe('Carrots');
     49   });
     50   it('contact getter and its fields cannot replace validated contact', () => {
     51     let contacts = 0;
     52     let values = 0;
     53     const r = valid({
     54       ...draft,
     55       get contact() {
     56         contacts++;
     57         return {
     58           type: 'email' as const,
     59           public: true as const,
     60           get value() {
     61             return ++values === 1
     62               ? 'seller@example.com'
     63               : 'attacker?body=private@example.com';
     64           }
     65         };
     66       }
     67     });
     68     expect(contacts).toBe(1);
     69     expect(values).toBe(1);
     70     expect(r.wire_parts.content).toBe(
     71       draft.description + '\n\nPublic contact: mailto:seller@example.com'
     72     );
     73   });
     74   it('public contact snapshots disclosure and type once', () => {
     75     let types = 0;
     76     let disclosures = 0;
     77     expect(
     78       publicContact({
     79         get public() {
     80           disclosures++;
     81           return true;
     82         },
     83         get type() {
     84           return ++types === 1 ? 'email' : 'phone';
     85         },
     86         value: 'seller@example.com'
     87       })
     88     ).toEqual({ type: 'email', href: 'mailto:seller@example.com' });
     89     expect(types).toBe(1);
     90     expect(disclosures).toBe(1);
     91   });
     92 });
     93 describe('strict text-only authored Food templates', () => {
     94   for (const unit of foodUnits)
     95     it(unit, () => {
     96       const r = valid({ ...draft, unit });
     97       expect(r.wire_parts.kind).toBe(30402);
     98       expect(r.wire_parts.tags).toEqual([
     99         ['d', 'fixed-draft-id'],
    100         ['title', 'Carrots'],
    101         ['summary', 'Fresh carrots. Collected locally.'],
    102         ['published_at', '1700000000'],
    103         ['location', 'Victoria'],
    104         ['price', '3.5', 'CAD'],
    105         ['radroots:price_unit', unit],
    106         ['radroots:quantity', '10', unit],
    107         ['status', 'active']
    108       ]);
    109     });
    110   it('stable identity/publication time is not inferred from changed title', () => {
    111     const a = valid(draft);
    112     const b = valid({
    113       ...draft,
    114       title: 'New title',
    115       created_at: 1700000070,
    116       status: 'sold'
    117     });
    118     expect(a.wire_parts.tags[0]).toEqual(b.wire_parts.tags[0]);
    119     expect(a.wire_parts.tags[3]).toEqual(b.wire_parts.tags[3]);
    120   });
    121   it('summary is derived and visible with whole Unicode code points', () => {
    122     const r = valid({ ...draft, description: '😀'.repeat(241) });
    123     expect(r.summary).toBe('😀'.repeat(240));
    124     expect(r.summary.isWellFormed()).toBe(true);
    125     expect(r.wire_parts.tags[2]).toEqual(['summary', r.summary]);
    126   });
    127   it('fresh draft line endings normalize without changing already signed data', () => {
    128     const r = valid({ ...draft, description: '  Fresh\r\ncarrots.\rHere.  ' });
    129     expect(r.wire_parts.content).toBe('Fresh\ncarrots.\nHere.');
    130     expect(r.summary).toBe('Fresh carrots. Here.');
    131   });
    132   it('zero price and absent quantity differ from quantity zero', () => {
    133     const r = valid({ ...draft, amount: '0', quantity: undefined });
    134     expect(r.wire_parts.tags.find((t) => t[0] === 'price')).toEqual([
    135       'price',
    136       '0',
    137       'CAD'
    138     ]);
    139     expect(r.wire_parts.tags.some((t) => t[0] === 'radroots:quantity')).toBe(
    140       false
    141     );
    142     expect(buildFoodTemplate({ ...draft, quantity: '0' }).ok).toBe(false);
    143   });
    144   it('canonical28digit amount remains exact', () =>
    145     expect(
    146       valid({
    147         ...draft,
    148         amount: '9999999999999999999999999999'
    149       }).wire_parts.tags.find((t) => t[0] === 'price')?.[1]
    150     ).toBe('9999999999999999999999999999'));
    151   for (const amount of ['003.500', '1.0', '+1', '1e3', '1,000', '1'.repeat(29)])
    152     it('rejects authored amount ' + amount, () =>
    153       expect(buildFoodTemplate({ ...draft, amount }).ok).toBe(false)
    154     );
    155   for (const value of [
    156     { currency: 'cad' },
    157     { unit: 'lbs' },
    158     { quantity: '-1' },
    159     { identifier: '' },
    160     { identifier: 'x y' },
    161     { identifier: 'x'.repeat(513) },
    162     { status: 'withdrawn' },
    163     { created_at: Number('18446744073709551615') },
    164     { published_at: 1700000061 },
    165     { published_at: 0 },
    166     { title: ' x' },
    167     { title: 'x\u200b' },
    168     { title: '😀'.repeat(161) },
    169     { location: 'x'.repeat(161) },
    170     { description: '' },
    171     { description: 'x'.repeat(16385) }
    172   ])
    173     it('rejects invalid draft ' + JSON.stringify(value), () =>
    174       expect(buildFoodTemplate({ ...draft, ...value } as FoodDraft).ok).toBe(
    175         false
    176       )
    177     );
    178   it('actual160codepoint titles and locations plus16KiB content are admitted', () => {
    179     const r = valid({
    180       ...draft,
    181       title: '😀'.repeat(160),
    182       location: 'é'.repeat(160),
    183       description: 'x'.repeat(16384)
    184     });
    185     expect(new TextEncoder().encode(r.wire_parts.content)).toHaveLength(16384);
    186   });
    187   it('contact block participates in composed16KiB budget', () =>
    188     expect(
    189       buildFoodTemplate({
    190         ...draft,
    191         description: 'x'.repeat(16380),
    192         contact: { type: 'email', value: 'seller@example.com', public: true }
    193       }).ok
    194     ).toBe(false));
    195   it('only explicitly public contact composes into content', () => {
    196     const r = valid({
    197       ...draft,
    198       contact: { type: 'email', value: 'seller@example.com', public: true }
    199     });
    200     expect(r.wire_parts.content).toBe(
    201       draft.description + '\n\nPublic contact: mailto:seller@example.com'
    202     );
    203     expect(
    204       r.wire_parts.tags.some((t) =>
    205         ['contact', 'image', 'contract'].includes(t[0])
    206       )
    207     ).toBe(false);
    208     expect(
    209       buildFoodTemplate({
    210         ...draft,
    211         contact: {
    212           type: 'email',
    213           value: 'seller@example.com',
    214           public: false
    215         } as never
    216       }).ok
    217     ).toBe(false);
    218   });
    219   it('private enquiry/subject/recipient extras never enter the public event', () => {
    220     const r = valid({
    221       ...draft,
    222       privateEnquiry: 'PRIVATE ENQUIRY',
    223       subject: 'PRIVATE SUBJECT',
    224       recipient: 'PRIVATE RECIPIENT',
    225       summary: 'PRIVATE SUMMARY',
    226       images: ['https://secret.example/image']
    227     } as FoodDraft);
    228     expect(JSON.stringify(r.wire_parts)).not.toContain('PRIVATE');
    229     expect(JSON.stringify(r.wire_parts)).not.toContain('secret.example');
    230     expect(r.summary).toBe('Fresh carrots. Collected locally.');
    231   });
    232 });
    233 describe('dedicated optional public-contact fields', () => {
    234   for (const input of [
    235     { type: 'email', value: 'seller+food@example.com', public: true },
    236     { type: 'phone', value: '+12505550123', public: true },
    237     { type: 'https', value: 'https://farm.example/contact', public: true }
    238   ])
    239     it('allowed ' + input.type, () =>
    240       expect(publicContact(input as never)).toBeDefined()
    241     );
    242   for (const input of [
    243     { type: 'email', value: 'seller@example.com?body=private', public: true },
    244     { type: 'email', value: 'a\nb@example.com', public: true },
    245     { type: 'email', value: 'missing-domain', public: true },
    246     { type: 'phone', value: '555 HELP', public: true },
    247     { type: 'phone', value: '+0', public: true },
    248     { type: 'https', value: 'http://farm.example/contact', public: true },
    249     {
    250       type: 'https',
    251       value: 'https://user:pass@farm.example/contact',
    252       public: true
    253     },
    254     { type: 'https', value: 'javascript:alert(1)', public: true },
    255     { type: 'https', value: 'https://farm.example/%0a', public: true },
    256     { type: 'https', value: 'https://farm.example/contact', public: false },
    257     { type: 'other', value: 'private prose', public: true }
    258   ])
    259     it('rejects ' + JSON.stringify(input), () =>
    260       expect(publicContact(input as never)).toBeUndefined()
    261     );
    262   it('absence stays absent', () =>
    263     expect(publicContact(undefined)).toBeUndefined());
    264 });
    265 
    266 describe('contact recipient and visible URI preservation', () => {
    267   for (const value of [
    268     'foo?subject=x@example.com',
    269     'foo#bar@example.com',
    270     'foo%3Fbar@example.com',
    271     'foo%0abar@example.com'
    272   ])
    273     it('reject mailbox URI syntax ' + value, () =>
    274       expect(
    275         publicContact({ type: 'email', value, public: true })
    276       ).toBeUndefined()
    277     );
    278   for (const value of [
    279     'https://farm\u200b.example/contact',
    280     'https://farm.example/%E2%80%8Bcontact'
    281   ])
    282     it('reject URL format character ' + value, () =>
    283       expect(
    284         publicContact({ type: 'https', value, public: true })
    285       ).toBeUndefined()
    286     );
    287   it('normal mailbox preserves its exact recipient with no header/fragment', () => {
    288     const contact = publicContact({
    289       type: 'email',
    290       value: 'seller+food@example.com',
    291       public: true
    292     })!;
    293     const parsed = new URL(contact.href);
    294     expect(parsed.pathname).toBe('seller+food@example.com');
    295     expect(parsed.search).toBe('');
    296     expect(parsed.hash).toBe('');
    297   });
    298 });