cautpartener / client / e2e / feed.e2e.mjs
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
// M5 public-feed e2e — posts, Instagram UX, likes, comments, caps, forgery,
// re-seeding and window honesty, all over PLAIN mailbox replay (no mesh):
//   A publishes a profile + 2 posts (one with 2 images) into jocuri|bucuresti,
//   plus a backdated (>24 h old) post deposited through the real signing code
//   path (receivers clamp ts only against the FUTURE, so an old ts is the
//   honest way to fake age without a clock stub).
//   B (stranger, fresh device) opens the shard feed → newest-first cards,
//   thumb carousel, bounded display image, double-tap → like, comments;
//   posts an own post; deposits FORGED post docs (wrong shard binding +
//   wrong stripe room) → dropped; floods >20 posts/day → render cap + note.
//   A reopens → sees B's post, B's like on A's post, B's comment.
//   Truncate + deposit → gap honesty on refresh; reseedShard() re-deposits
//   A's aged foreign post from B's raw-envelope cache; window-edge note.
// Run: node e2e/feed.e2e.mjs        (HEADED=1 to watch)
// NEVER put a seed (or any part of one) into a fail message — it is logged.
import { deflateSync } from "node:zlib";
import {
  createHarness,
  createIdentity as createIdentityFlow,
  fail,
  ok,
  sleep,
  waitContactsReady,
  waitQueueDrained,
} from "./helpers.mjs";

const PORT = 5190;
const STUB_PORT = 8797;
const SHARD = "jocuri|bucuresti";

const harness = createHarness({ port: PORT, stubPort: STUB_PORT });
const BASE = harness.base;
const openDevice = (label, dir) => harness.openDevice(label, dir);
const createIdentity = (page) => createIdentityFlow(page, BASE);
const roomCount = (roomId) => harness.roomCount(roomId);
const shutdown = () => harness.shutdown();

// ---- fixtures ----------------------------------------------------------------

/** Minimal valid 64×64 solid-color PNG (post image fixture). */
function solidPNG(rgb) {
  const S = 64;
  const crcT = [...Array(256)].map((_, n) => {
    let c = n;
    for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
    return c >>> 0;
  });
  const crc = (b) => {
    let c = 0xffffffff;
    for (const x of b) c = crcT[(c ^ x) & 0xff] ^ (c >>> 8);
    return (c ^ 0xffffffff) >>> 0;
  };
  const chunk = (t, d) => {
    const len = Buffer.alloc(4);
    len.writeUInt32BE(d.length);
    const td = Buffer.concat([Buffer.from(t), d]);
    const cc = Buffer.alloc(4);
    cc.writeUInt32BE(crc(td));
    return Buffer.concat([len, td, cc]);
  };
  const ihdr = Buffer.alloc(13);
  ihdr.writeUInt32BE(S, 0);
  ihdr.writeUInt32BE(S, 4);
  ihdr[8] = 8;
  ihdr[9] = 2; // RGB
  const raw = Buffer.alloc(S * (S * 3 + 1));
  for (let y = 0; y < S; y++) {
    raw[y * (S * 3 + 1)] = 0;
    for (let x = 0; x < S; x++) raw.writeUIntBE(rgb, y * (S * 3 + 1) + 1 + x * 3, 3);
  }
  return Buffer.concat([
    Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
    chunk("IHDR", ihdr),
    chunk("IDAT", deflateSync(raw)),
    chunk("IEND", Buffer.alloc(0)),
  ]);
}

/** feedRoom id for (shard, stripe) via the exact client code path. */
const feedRoomIdOf = (page, shard, stripe) =>
  page.evaluate(
    async ([sh, s]) => (await import("/src/public/public-rooms.ts")).feedRoom(sh, s),
    [shard, stripe],
  );

const stripeOf = (page, pub) =>
  page.evaluate(async (p) => (await import("/src/public/public-rooms.ts")).stripe(p), pub);

const myPubOf = (page) => page.evaluate(() => window.__cp.identity.identity.publicKeyB64);

/** Sign + deposit one post through the real code path, with an ARBITRARY ts. */
const depositPostAs = (page, { shard, roomShard, roomStripe, text, ts }) =>
  page.evaluate(
    async ([sh, rSh, rSt, txt, when]) => {
      const pd = await import("/src/public/public-doc.ts");
      const rooms = await import("/src/public/public-rooms.ts");
      const io = await import("/src/public/mailbox-io.ts");
      const me = window.__cp.identity;
      const doc = { ts: when, shard: sh, text: txt, imgs: [] };
      const signed = await pd.signDoc(me.identity, "post", doc);
      const room = io.publicRoom(await rooms.feedRoom(rSh, rSt));
      const r = await room.depositDoc(signed);
      return { ok: r.ok, cid: signed.cid.toString() };
    },
    [shard, roomShard, roomStripe, text, ts],
  );

/** Enter the feed (first open lands in general|…), then pick cat|county via the picker. */
async function enterFeed(page, county, cat) {
  await page.click('[data-testid="tab-feed"]');
  await page.waitForSelector('[data-testid="feed-frame"]', { timeout: 20000 });
  if ((await page.getAttribute('[data-testid="feed-frame"]', "data-shard")) !== `${cat}|${county}`) {
    await page.selectOption('[data-testid="feed-county"]', county);
    await page.waitForSelector(`[data-testid="feed-frame"][data-shard$="|${county}"]`, { timeout: 20000 });
    await page.click(`[data-testid="feed-cat"][data-cat="${cat}"]`);
    await page.waitForSelector(`[data-testid="feed-frame"][data-shard="${cat}|${county}"]`, { timeout: 20000 });
  }
  // the initial 4-stripe replay finished when the loading note is gone
  await page.waitForFunction(() => !document.querySelector('[data-testid="feed-loading"]'), undefined, {
    timeout: 30000,
  });
}

const cardWithText = (text) => `[data-testid="feed-post"]:has-text("${text}")`;

// ---- scenario ----------------------------------------------------------------

async function main() {
  await harness.start();

  const dirA = harness.newProfileDir("cp-e2e-fa-");
  const dirB = harness.newProfileDir("cp-e2e-fb-");

  const TEXT_IMG = "Cine vine la board games sâmbătă?";
  const TEXT_PLAIN = "Căutăm al patrulea la Catan.";
  const TEXT_OLD = "postare veche de ieri";
  const TEXT_B = "Eu aduc jocurile.";
  const TEXT_COMMENT = "Vin și eu, sigur!";

  // --- A: identity + profile + 2 posts (one with 2 images) --------------------
  let A = await openDevice("A", dirA);
  await createIdentity(A.page);
  await waitContactsReady(A.page);
  const pubA = await myPubOf(A.page);
  const stripeA = await stripeOf(A.page, pubA);
  const roomA = await feedRoomIdOf(A.page, SHARD, stripeA);

  await A.page.click('[data-testid="tab-profile"]');
  await A.page.waitForSelector('[data-testid="pf-name"]', { timeout: 30000 });
  await A.page.fill('[data-testid="pf-name"]', "Ana");
  await A.page.selectOption('[data-testid="pf-county"]', "bucuresti");
  await A.page.click('[data-testid="pf-cat"][data-cat="jocuri"]');
  await A.page.click('[data-testid="pf-publish"]');
  await A.page.waitForFunction(
    () => document.querySelector('[data-testid="pf-status"]')?.textContent.includes("publicat:"),
    undefined,
    { timeout: 30000 },
  );
  ok("A: profile published (jocuri / București)");

  await enterFeed(A.page, "bucuresti", "jocuri");
  // post 1: two images + caption
  await A.page.click('[data-testid="feed-fab"]');
  await A.page.waitForSelector('[data-testid="compose-sheet"]');
  await A.page.fill('[data-testid="compose-text"]', TEXT_IMG);
  await A.page.setInputFiles('[data-testid="compose-file"]', [
    { name: "one.png", mimeType: "image/png", buffer: solidPNG(0x2f9e6b) },
    { name: "two.png", mimeType: "image/png", buffer: solidPNG(0x9e2f6b) },
  ]);
  await A.page.waitForFunction(
    () => document.querySelectorAll('[data-testid="compose-previews"] img').length === 2,
    undefined,
    { timeout: 20000 },
  );
  await A.page.click('[data-testid="compose-publish"]');
  await A.page.waitForSelector(cardWithText(TEXT_IMG), { timeout: 30000 });
  await sleep(50); // distinct ts for deterministic newest-first ordering
  // post 2: text only
  await A.page.click('[data-testid="feed-fab"]');
  await A.page.waitForSelector('[data-testid="compose-sheet"]');
  await A.page.fill('[data-testid="compose-text"]', TEXT_PLAIN);
  await A.page.click('[data-testid="compose-publish"]');
  await A.page.waitForSelector(cardWithText(TEXT_PLAIN), { timeout: 30000 });
  ok("A: 2 posts published through the composer (doc + image blocks deposited)");

  // an aged post (ts 25 h back) deposited through the real signing path — the
  // §3 clamp only rejects FUTURE ts, so a backdated ts is the honest age fake
  const old = await depositPostAs(A.page, {
    shard: SHARD,
    roomShard: SHARD,
    roomStripe: stripeA,
    text: TEXT_OLD,
    ts: Date.now() - 25 * 3600_000,
  });
  if (!old.ok) fail("aged post deposit did not land");
  const countA = await roomCount(roomA);
  if (countA < 3) fail(`A's stripe room holds ${countA} messages, expected ≥3 (2 docs + blocks + aged doc)`);
  await waitQueueDrained(A.page);
  await A.close();
  ok("A: aged (25 h) post deposited; device closed");

  // --- B: stranger browses the shard ------------------------------------------
  let B = await openDevice("B", dirB);
  await createIdentity(B.page);
  await waitContactsReady(B.page);
  const pubB = await myPubOf(B.page);
  const stripeB = await stripeOf(B.page, pubB);
  const roomB = await feedRoomIdOf(B.page, SHARD, stripeB);

  await enterFeed(B.page, "bucuresti", "jocuri");
  await B.page.waitForSelector(cardWithText(TEXT_OLD), { timeout: 30000 });
  const order = await B.page.$$eval('[data-testid="feed-post"] [data-testid="feed-caption"]', (els) =>
    els.map((e) => e.textContent),
  );
  if (order.length !== 3) fail(`B sees ${order.length} posts, expected 3`);
  if (!(order[0].includes("Catan") && order[1].includes("board games") && order[2].includes("veche")))
    fail(`feed order wrong: ${JSON.stringify(order)}`);
  ok("B: cold-load renders A's 3 posts newest-first from replay alone");

  // carousel: 2 slides with data-URL thumbs + 2 dots. `:has-text` only works
  // in Playwright selectors, so pin the card by its data-cid for in-page CSS.
  const imgCardCid = await B.page.getAttribute(cardWithText(TEXT_IMG), "data-cid");
  const imgCard = `[data-testid="feed-post"][data-cid="${imgCardCid}"]`; // valid CSS + Playwright
  await B.page.waitForFunction(
    (sel) => {
      const card = document.querySelector(sel);
      const imgs = card?.querySelectorAll('[data-testid="feed-img"]') ?? [];
      return imgs.length === 2 && [...imgs].every((i) => i.src.startsWith("data:image/"));
    },
    imgCard,
    { timeout: 30000 },
  );
  const dots = await B.page.$$eval(`${imgCard} .feed-dot`, (els) => els.length);
  if (dots !== 2) fail(`carousel dots: ${dots}, expected 2`);
  ok("B: carousel renders both thumbs (data URLs) + dots");

  // display image via lightbox (bounded decode)
  await B.page.click(`${imgCard} [data-testid="feed-img"]`);
  await B.page.waitForSelector('[data-testid="feed-display-img"]', { timeout: 30000 });
  const dispSrc = await B.page.getAttribute('[data-testid="feed-display-img"]', "src");
  if (!dispSrc?.startsWith("data:image/")) fail("display image not assembled/decoded");
  await B.page.mouse.click(640, 30); // close lightbox
  await B.page.waitForFunction(() => !document.querySelector('[data-testid="feed-display-img"]'), undefined, {
    timeout: 10000,
  });
  ok("B: display image opens in the lightbox after bounded decode");

  // double-tap like → count 1, liked state, honest no-unlike note
  await B.page.dblclick(`${imgCard} [data-testid="feed-carousel"]`);
  await B.page.waitForFunction(
    (sel) => document.querySelector(sel)?.querySelector('[data-testid="feed-like"]')?.dataset.liked === "1",
    imgCard,
    { timeout: 30000 },
  );
  const likeCount = (await B.page.textContent(`${imgCard} [data-testid="feed-like-count"]`)).trim();
  if (likeCount !== "1") fail(`like count reads "${likeCount}", expected "1"`);
  await B.page.waitForSelector(`${imgCard} [data-testid="feed-liked-note"]`, { timeout: 10000 });
  ok("B: double-tap likes the post (count 1, immutable-like note shown)");

  // comment via the sheet
  await B.page.click(`${imgCard} [data-testid="feed-comment"]`);
  await B.page.waitForSelector('[data-testid="feed-comments-sheet"]');
  await B.page.fill('[data-testid="feed-comment-input"]', TEXT_COMMENT);
  await B.page.click('[data-testid="feed-comment-send"]');
  await B.page.waitForFunction(
    (txt) => [...document.querySelectorAll('[data-testid="feed-comment-item"]')].some((el) => el.textContent.includes(txt)),
    TEXT_COMMENT,
    { timeout: 30000 },
  );
  await B.page.mouse.click(640, 30); // close sheet
  await B.page.waitForFunction(
    (sel) => document.querySelector(`${sel} [data-testid="feed-comment-count"]`)?.textContent === "1",
    imgCard,
    { timeout: 15000 },
  );
  ok("B: comment posted and listed (count 1 on the card)");

  // B's own post
  await B.page.click('[data-testid="feed-fab"]');
  await B.page.waitForSelector('[data-testid="compose-sheet"]');
  await B.page.fill('[data-testid="compose-text"]', TEXT_B);
  await B.page.click('[data-testid="compose-publish"]');
  await B.page.waitForSelector(cardWithText(TEXT_B), { timeout: 30000 });
  ok("B: own post published into the shard");

  // share link shape
  const shareCid = await B.page.getAttribute(cardWithText(TEXT_B), "data-cid");
  // permalink view resolves the post from the shard rooms
  await B.page.goto(`${BASE}/#/p/${encodeURIComponent(SHARD)}/${shareCid}`);
  await B.page.waitForSelector(`[data-testid="pv-view"] ${cardWithText(TEXT_B)}`, { timeout: 30000 });
  ok("B: #/p/<shard>/<cid> permalink resolves and renders the card");
  await B.page.goto(`${BASE}/#/`);
  await enterFeed(B.page, "bucuresti", "jocuri");
  await B.page.waitForSelector(cardWithText(TEXT_B), { timeout: 30000 });

  // --- forged post docs are dropped --------------------------------------------
  const before = await B.page.$$eval('[data-testid="feed-post"]', (els) => els.length);
  // (a) wrong shard binding: doc says sport|cluj, deposited into THIS shard's room
  const f1 = await depositPostAs(B.page, {
    shard: "sport|cluj",
    roomShard: SHARD,
    roomStripe: stripeB,
    text: "forged wrong-shard",
    ts: Date.now(),
  });
  // (b) right shard, wrong STRIPE room (not the author's stripe)
  const f2 = await depositPostAs(B.page, {
    shard: SHARD,
    roomShard: SHARD,
    roomStripe: (stripeB + 1) % 4,
    text: "forged wrong-stripe",
    ts: Date.now(),
  });
  if (!f1.ok || !f2.ok) fail("forged deposits did not land in the stub");
  await B.page.click('[data-testid="feed-refresh"]');
  await sleep(1500);
  const after = await B.page.$$eval('[data-testid="feed-post"]', (els) => els.length);
  if (after !== before) fail(`forged docs rendered (cards ${before} → ${after})`);
  if (await B.page.$(cardWithText("forged"))) fail("a forged post text is visible");
  ok("forgery: wrong-shard-binding + wrong-stripe post docs deposited — both dropped");

  // --- per-author render cap (≤20 posts/author/shard/day) ----------------------
  // The flood author is a FRESH in-page identity C whose stripe differs from
  // both A's and B's: keeps the later re-seed room budgets deterministic
  // (26 own docs from B would otherwise eat B's ≤10/room/visit budget, and a
  // stripe collision with A would starve the foreign re-seed the suite
  // asserts). Documented §6 consequence, not a workaround.
  const nSpam = 25;
  const pubC = await B.page.evaluate(
    async ([sh, n, avoid]) => {
      const { Identity } = await import("/src/lib/identity.ts");
      const pd = await import("/src/public/public-doc.ts");
      const rooms = await import("/src/public/public-rooms.ts");
      const io = await import("/src/public/mailbox-io.ts");
      let idC = await Identity.fromSeed(Identity.newSeed());
      while (avoid.includes(rooms.stripe(idC.publicKeyB64))) idC = await Identity.fromSeed(Identity.newSeed());
      const room = io.publicRoom(await rooms.feedRoom(sh, rooms.stripe(idC.publicKeyB64)));
      for (let i = 0; i < n; i++) {
        const doc = { ts: Date.now() - (i + 1) * 1000, shard: sh, text: `spam-cap ${i}`, imgs: [] };
        const r = await room.depositDoc(await pd.signDoc(idC, "post", doc));
        if (!r.ok) throw new Error(`spam post ${i} did not land`);
      }
      return idC.publicKeyB64;
    },
    [SHARD, nSpam, [stripeA, stripeB]],
  );
  await B.page.click('[data-testid="feed-refresh"]');
  await B.page.waitForSelector('[data-testid="feed-capped"]', { timeout: 30000 });
  const cCards = await B.page.$$eval(
    `[data-testid="feed-post"][data-pub="${pubC}"]`,
    (els) => els.length,
  );
  if (cCards !== 20) fail(`author cap: ${cCards} of C's posts render, expected exactly 20`);
  ok(`author cap: ${nSpam} same-day posts by one author → exactly 20 render + honest "și altele" note`);
  await B.close();

  // --- A reopens: sees B's post + like + comment on own post -------------------
  A = await openDevice("A2", dirA);
  await A.page.goto(BASE);
  await A.page.waitForSelector('[data-testid="tab-feed"]', { timeout: 20000 });
  await waitContactsReady(A.page);
  await enterFeed(A.page, "bucuresti", "jocuri"); // persisted choice skips the landing
  await A.page.waitForSelector(cardWithText(TEXT_B), { timeout: 30000 });
  await A.page.waitForFunction(
    (sel) => document.querySelector(sel)?.querySelector('[data-testid="feed-like-count"]')?.textContent === "1",
    imgCard,
    { timeout: 30000 },
  );
  await A.page.click(`${imgCard} [data-testid="feed-comment"]`);
  await A.page.waitForFunction(
    (txt) => [...document.querySelectorAll('[data-testid="feed-comment-item"]')].some((el) => el.textContent.includes(txt)),
    TEXT_COMMENT,
    { timeout: 30000 },
  );
  await A.page.mouse.click(640, 30);
  ok("A: refresh shows B's post, B's like (count 1) and B's comment on A's own post");

  // profile grid: A's declared shard surfaces A's posts as tiles
  await A.page.goto(`${BASE}/#/u/${pubA}`);
  await A.page.waitForSelector('[data-testid="up-post-grid"]', { timeout: 30000 });
  const tiles = await A.page.$$eval('[data-testid="up-post-tile"]', (els) => els.length);
  if (tiles < 3) fail(`profile grid shows ${tiles} tiles, expected ≥3`);
  await A.page.waitForSelector('[data-testid="up-grid-note"]', { timeout: 10000 });
  ok(`profile grid: ${tiles} tiles from the declared shard + honest discoverability note`);
  await A.close();

  // --- B again: gap honesty, then re-seed from the raw-envelope cache ----------
  B = await openDevice("B2", dirB);
  await B.page.goto(BASE);
  await B.page.waitForSelector('[data-testid="tab-feed"]', { timeout: 20000 });
  await waitContactsReady(B.page);
  await enterFeed(B.page, "bucuresti", "jocuri");
  await B.page.waitForSelector(cardWithText(TEXT_OLD), { timeout: 30000 });

  // simulate TTL expiry: wipe every stripe room, then deposit one new post —
  // the refresh cursor now sits BELOW the room's oldest seq ⇒ gap notice
  for (let s = 0; s < 4; s++) {
    const rid = await feedRoomIdOf(B.page, SHARD, s);
    const res = await fetch(`http://localhost:${STUB_PORT}/__test/truncate?room=${encodeURIComponent(rid)}&keep=0`, {
      method: "POST",
    });
    if (!res.ok) fail(`truncate of stripe ${s} failed`);
  }
  const fresh = await depositPostAs(B.page, {
    shard: SHARD,
    roomShard: SHARD,
    roomStripe: stripeB,
    text: "postare după expirare",
    ts: Date.now(),
  });
  if (!fresh.ok) fail("post-truncation deposit did not land");
  await B.page.click('[data-testid="feed-refresh"]');
  await B.page.waitForSelector('[data-testid="feed-gap"]', { timeout: 30000 });
  ok("gap honesty: expired-unseen history surfaces the incomplete-history notice");

  // §6 re-seed: B's cache holds A's >24h-old post as a FOREIGN doc — the
  // re-seed pass must deposit it back into A's stripe room. The direct call
  // keeps the suite deterministic (in the app the SAME function runs after
  // every shard replay, jittered 0–60 s; an ambient jittered pass may also
  // fire here, which is why the assertions are ≥, not exact).
  await B.page.evaluate(async (sh) => (await import("/src/public/feed-service.ts")).reseedShard(sh), SHARD);
  const afterReseed = await roomCount(roomA);
  if (afterReseed < 1) fail(`re-seed deposited nothing into A's stripe room (count ${afterReseed})`);
  // own docs re-seed too: B's stripe room must hold B's re-deposited docs
  if ((await roomCount(roomB)) < 1) fail("re-seed did not re-deposit B's own docs");
  // the re-seeded aged post must actually render for a fresh walk
  await B.page.reload();
  await B.page.waitForSelector('[data-testid="tab-feed"]', { timeout: 20000 });
  await enterFeed(B.page, "bucuresti", "jocuri");
  await B.page.waitForSelector(cardWithText(TEXT_OLD), { timeout: 30000 });
  ok("re-seed: A's aged post re-deposited from B's raw-envelope cache and renders again");

  // window-edge honesty: every stripe fully walked ⇒ the edge note is shown
  await B.page.waitForSelector('[data-testid="feed-window-edge"]', { timeout: 15000 });
  await B.page.waitForSelector('[data-testid="feed-window-note"]', { timeout: 15000 });
  ok("window honesty: TTL-window note + window-edge note shown");

  // --- SECURITY (item 1): unverified 0x11 block ingestion --------------------
  // A junk 0x11 block deposited under a real image cid BEFORE the genuine block
  // must NOT occupy the cid slot and break assembly. The feed walk ingests a
  // page oldest-first with first-write-wins, so the OLDER (junk) deposit would
  // win the slot without verify-at-ingest; with it, junk fails the hash check
  // and the genuine (newer) block still assembles + decodes.
  const JUNK_SHARD = "sport|cluj";
  const junk = await B.page.evaluate(
    async ([sh, png]) => {
      const media = await import("/src/core/media.ts");
      const ps = await import("/src/public/profile-service.ts");
      const pd = await import("/src/public/public-doc.ts");
      const rooms = await import("/src/public/public-rooms.ts");
      const io = await import("/src/public/mailbox-io.ts");
      const fs = await import("/src/public/feed-service.ts");
      const me = window.__cp.identity;
      const st = rooms.stripe(me.identity.publicKeyB64);
      const room = io.publicRoom(await rooms.feedRoom(sh, st));
      // encode a real image, pack it into 0x11 blocks (thumb = one raw block)
      const file = new File([new Uint8Array(png)], "guard.png", { type: "image/png" });
      const enc = await media.encodeImage(file);
      const thumbPack = await ps.packBlocks(enc.thumb);
      const dispPack = await ps.packBlocks(enc.display);
      // 1) deposit JUNK under the REAL thumb cid FIRST (older seq → ingested
      //    first by the oldest-first-within-page walk)
      const junkBody = new Uint8Array((thumbPack.blocks[0].bytes.length || 32) + 1).fill(0x7a);
      const jr = await room.depositBlock(thumbPack.root, junkBody);
      const junkVerifies = await io.verifyBlock({
        type: io.ENV_BLOCK,
        cid: thumbPack.root,
        body: junkBody,
        raw: junkBody,
      });
      // 2) then the genuine post doc + genuine blocks (newer seqs)
      const doc = {
        ts: Date.now(),
        shard: sh,
        text: "junk-guard",
        imgs: [
          {
            thumbCid: thumbPack.root.toString(),
            cid: dispPack.root.toString(),
            mime: enc.mime === "image/jpeg" ? "image/jpeg" : "image/webp",
            w: enc.w,
            h: enc.h,
            bytes: enc.display.length,
          },
        ],
      };
      const signed = await pd.signDoc(me.identity, "post", doc);
      const dr = await room.depositDoc(signed);
      for (const b of [...thumbPack.blocks, ...dispPack.blocks]) await room.depositBlock(b.cid, b.bytes);
      // 3) a FRESH walk must assemble the genuine thumb despite the junk
      const handle = await fs.openFeed(sh, { live: false });
      const post = handle.view().posts.find((p) => p.text === "junk-guard");
      const url = post ? await handle.imageUrl(post.imgs[0], "thumb") : null;
      handle.close();
      return {
        deposited: jr.ok && dr.ok,
        junkVerifies,
        rendered: !!post,
        thumbOk: typeof url === "string" && url.startsWith("data:image/"),
      };
    },
    [JUNK_SHARD, [...solidPNG(0x336699)]],
  );
  if (!junk.deposited) fail("junk-guard: deposits did not land");
  if (junk.junkVerifies) fail("junk-guard: junk block unexpectedly hash-verifies to the real cid");
  if (!junk.rendered) fail("junk-guard: genuine post did not surface in the walk");
  if (!junk.thumbOk) fail("junk-guard: junk block occupied the cid slot — genuine image did NOT assemble");
  ok("security: junk 0x11 under a real image cid is rejected at ingest — genuine block still wins + assembles");

  // --- enum expansion (Cluj launch): picker order, general|romania, open slugs --
  // picker order: "General" is the first category chip, "Toată România" the
  // first location option (the natural default landing pair), 19 categories
  const firstChip = await B.page.$eval('[data-testid="feed-cat"]', (el) => ({
    cat: el.dataset.cat,
    label: el.textContent.trim(),
  }));
  if (firstChip.cat !== "general" || firstChip.label !== "General")
    fail(`first category chip is ${firstChip.cat}/${firstChip.label}, expected general/General`);
  const firstLoc = await B.page.$eval('[data-testid="feed-county"] option', (el) => ({
    value: el.value,
    label: el.textContent.trim(),
  }));
  if (firstLoc.value !== "romania" || firstLoc.label !== "Toată România")
    fail(`first location option is ${firstLoc.value}/${firstLoc.label}, expected romania/Toată România`);
  const chipCount = await B.page.$$eval('[data-testid="feed-cat"]', (els) => els.length);
  if (chipCount !== 19) fail(`category picker shows ${chipCount} chips, expected 19`);
  ok("picker: 19 category chips with General first; Toată România first among locations");

  // the country-wide default shard round-trips a post end to end (compose →
  // deposit → reload → fresh 4-stripe mailbox walk renders it again)
  const TEXT_RO = "Salut, toată România!";
  await enterFeed(B.page, "romania", "general");
  await B.page.click('[data-testid="feed-fab"]');
  await B.page.waitForSelector('[data-testid="compose-sheet"]');
  await B.page.fill('[data-testid="compose-text"]', TEXT_RO);
  await B.page.click('[data-testid="compose-publish"]');
  await B.page.waitForSelector(cardWithText(TEXT_RO), { timeout: 30000 });
  await waitQueueDrained(B.page);
  await B.page.reload();
  await B.page.waitForSelector('[data-testid="tab-feed"]', { timeout: 20000 });
  await waitContactsReady(B.page);
  await enterFeed(B.page, "romania", "general");
  await B.page.waitForSelector(cardWithText(TEXT_RO), { timeout: 30000 });
  ok("general|romania: post round-trips through mailbox replay in the country-wide shard");

  // open slug vocabulary at the wire: an unknown-but-shape-valid slug (a
  // future append) verifies; malformed slugs are rejected (shape clamp)
  const shapes = await B.page.evaluate(async () => {
    const pd = await import("/src/public/public-doc.ts");
    const me = window.__cp.identity;
    const verify = async (shard) => {
      const signed = await pd.signDoc(me.identity, "post", { ts: Date.now(), shard, text: "x", imgs: [] });
      return (await pd.verifyDoc(signed.bytes, { kinds: ["post"] })) !== null;
    };
    return {
      unknownOk: await verify("ceramica-2027|cluj"), // future slug: must verify
      upperBad: await verify("Ceramica|cluj"),
      spaceBad: await verify("cera mica|cluj"),
      longBad: await verify("a".repeat(25) + "|cluj"),
    };
  });
  if (!shapes.unknownOk) fail("open vocabulary: unknown shape-valid slug was rejected at the wire");
  if (shapes.upperBad || shapes.spaceBad || shapes.longBad) fail("slug shape: a malformed slug unexpectedly verified");
  ok("wire: unknown shape-valid slug verifies (append-only vocabulary); malformed slugs rejected");

  // a profile carrying an unknown category slug is NOT rejected wholesale and
  // its chip renders as the raw slug (newer-client forward compat)
  const prof = await B.page.evaluate(async (cat) => {
    const pd = await import("/src/public/public-doc.ts");
    const rooms = await import("/src/public/public-rooms.ts");
    const io = await import("/src/public/mailbox-io.ts");
    const contacts = await import("/src/core/contacts.ts");
    const ps = await import("/src/public/profile-service.ts");
    const me = window.__cp.identity;
    const { op } = ps.mySource();
    const x = await contacts.myXIdentity(me.identity, me.seed, "Barbu");
    const doc = {
      ts: Date.now(),
      seq: (op?.seq ?? 0) + 10,
      name: x.name,
      bio: "",
      county: "cluj",
      categories: [cat],
      xPub: x.xPub,
      xSig: x.xSig,
      commentPolicy: "open",
    };
    const signed = await pd.signDoc(me.identity, "profile", doc);
    const verifies =
      (await pd.verifyDoc(signed.bytes, { kinds: ["profile"], pub: me.identity.publicKeyB64 })) !== null;
    const room = io.publicRoom(await rooms.profileRoom(me.identity.publicKeyB64));
    const r = await room.depositDoc(signed);
    return { verifies, deposited: r.ok };
  }, "ceramica");
  if (!prof.verifies) fail("profile with an unknown category slug was rejected wholesale at the wire");
  if (!prof.deposited) fail("unknown-slug profile deposit did not land");
  await B.page.goto(`${BASE}/#/u/${pubB}`);
  await B.page.waitForSelector('[data-testid="up-cat"][data-cat="ceramica"]', { timeout: 30000 });
  const rawChip = await B.page.$eval('[data-testid="up-cat"][data-cat="ceramica"]', (el) => el.textContent.trim());
  if (rawChip !== "ceramica") fail(`unknown-slug chip renders "${rawChip}", expected the raw slug`);
  ok("profile: unknown category slug verifies and renders as a raw-slug chip");

  await B.close();
}

let exitCode = 0;
try {
  await main();
  console.log("\n🎉 public feed: posts + carousel + likes + comments + caps + forgery + re-seed + honesty passed");
} catch (err) {
  console.error("❌ " + (err?.message ?? err));
  exitCode = 1;
} finally {
  await shutdown();
}
process.exit(exitCode);

static mirror of HEAD · about · clone: git clone https://cod-sursa.cautpartener.ro/cautpartener.git