cautpartener / client / e2e / audience.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
// M5b audience-restriction e2e — the requirement proof: profile sections and
// posts restricted to a contact group are SEALED (AES-GCM under group epoch
// keys), embedded in public docs (existence visible, content opaque):
//   A groups B into "Prieteni", publishes a profile with a restricted section
//   and a restricted post; B (member, grant over the pairwise room) unseals
//   both; C (verified contact, NON-member) sees only lock chips and the
//   ciphertext never reaches the DOM. A removes B → rekey (epoch 2) + profile
//   re-seal → B still unseals the OLD post (removal ≠ retraction — asserted
//   explicitly) but not the new one. C joins at epoch 2 (grant + keychain ⇒
//   FULL history), then is removed (epoch 3). B re-added at epoch 3 unseals
//   EVERYTHING — epoch 2 posts minted while excluded open via the keychain
//   cascade. Second devices: A's via home-log gkey sync, B's via rgrant sync.
// Run: node e2e/audience.e2e.mjs        (HEADED=1 to watch)
// NEVER put a seed (or any part of one) into a fail message — it is logged.
import {
  acceptInvite,
  closeSheet,
  createHarness,
  createIdentity as createIdentityFlow,
  createInvite,
  fail,
  ok,
  pairMailboxRoomOf,
  roomIdOf,
  sleep,
  waitAllRoomsDrained,
  waitChatReady,
  waitContactsReady,
} from "./helpers.mjs";

const PORT = 5191;
const STUB_PORT = 8798;
const SHARD = "jocuri|bucuresti";

const harness = createHarness({ port: PORT, stubPort: STUB_PORT });
const BASE = harness.base;
const createIdentity = (page) => createIdentityFlow(page, BASE);

const T1 = "Întâlnire secretă la cabană sâmbătă";
const T2 = "Postare nouă după excluderea lui Bogdan";
const T3 = "A treia postare, epoca trei";
const SECRET_ABOUT = "Detalii private doar pentru prieteni";
const SECRET_CONTACT = "0722-000-111";

const myPubOf = (page) => page.evaluate(() => window.__cp.identity.identity.publicKeyB64);
const mySeedOf = (page) => page.evaluate(() => localStorage.getItem("cautpartener:id"));
const cardWithText = (text) => `[data-testid="feed-post"]:has-text("${text}")`;

/** Enter the shard feed (first open lands in general|…; pick jocuri|bucuresti via the picker). */
async function enterFeed(page) {
  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")) !== "jocuri|bucuresti") {
    await page.selectOption('[data-testid="feed-county"]', "bucuresti");
    await page.waitForSelector('[data-testid="feed-frame"][data-shard$="|bucuresti"]', { timeout: 20000 });
    await page.click('[data-testid="feed-cat"][data-cat="jocuri"]');
    await page.waitForSelector('[data-testid="feed-frame"][data-shard="jocuri|bucuresti"]', { timeout: 20000 });
  }
  await page.waitForFunction(() => !document.querySelector('[data-testid="feed-loading"]'), undefined, {
    timeout: 30000,
  });
}

/** Compose one restricted post to `gid` through the real composer UI. */
async function composeRestricted(page, gid, text) {
  await page.click('[data-testid="feed-fab"]');
  await page.waitForSelector('[data-testid="compose-sheet"]');
  await page.fill('[data-testid="compose-text"]', text);
  await page.selectOption('[data-testid="compose-aud"]', gid);
  // text-only honesty: picking a group hides the image picker + shows the note
  await page.waitForSelector('[data-testid="compose-aud-note"]', { timeout: 5000 });
  if (await page.$eval('[data-testid="compose-add-img"]', (el) => el.offsetParent !== null))
    fail("image picker still visible for a restricted post");
  await page.click('[data-testid="compose-publish"]');
  await page.waitForSelector(cardWithText(text), { timeout: 30000 });
}

/** Confirm queued rendezvous joins until every pub is an active contact. */
async function confirmAll(page, pubs) {
  const deadline = Date.now() + 120000;
  for (;;) {
    const allActive = await page.evaluate(
      (ps) => ps.every((p) => window.__cp?.contacts?.state.contacts.get(p)?.status === "active"),
      pubs,
    );
    if (allActive) return;
    if (Date.now() > deadline) fail("contacts were not all confirmed in time");
    const btn = await page.$('[data-testid="invite-confirm-yes"]');
    if (btn) await btn.click().catch(() => {});
    await sleep(400);
  }
}

/** Toggle B/C's membership in the group via the contact-detail sheet. */
async function setMembershipUI(page, pub, gid, on) {
  await page.click('[data-testid="tab-contacts"]');
  await page.waitForSelector(`[data-testid="contact-row"][data-pub="${pub}"]`, { timeout: 20000 });
  await page.click(`[data-testid="contact-row"][data-pub="${pub}"]`);
  const box = `[data-testid="detail-group"][data-gid="${gid}"] input`;
  await page.waitForSelector(box, { timeout: 10000 });
  if (on) await page.check(box);
  else await page.uncheck(box);
  await sleep(300); // the change handler appends the gmember op
  await closeSheet(page);
}

/** Every aud-post ciphertext (box.ct) currently in the shard rooms. */
const audCiphertexts = (page) =>
  page.evaluate(async (shard) => {
    const rooms = await import("/src/public/public-rooms.ts");
    const io = await import("/src/public/mailbox-io.ts");
    const pd = await import("/src/public/public-doc.ts");
    const out = [];
    for (let s = 0; s < 4; s++) {
      const room = io.publicRoom(await rooms.feedRoom(shard, s));
      if (!room) continue;
      await room.walkBackward(async (m) => {
        const env = io.parseEnvelope(m.payload);
        if (!env || env.type !== io.ENV_DOC) return;
        const v = await pd.verifyDoc(env.body, { kinds: ["post"], shard, stripe: s, cid: env.cid });
        if (v && v.doc.aud) out.push(v.doc.box.ct);
      });
    }
    return out;
  }, SHARD);

const gkeyEpochs = (page) =>
  page.evaluate(() => [...window.__cp.selfroom.state.gkeys.values()].map((k) => k.epoch).sort((a, b) => a - b));

const waitRgrantEpoch = (page, epoch) =>
  page.waitForFunction(
    (e) => {
      const s = window.__cp?.selfroom?.state;
      return !!s && [...s.rgrants.values()].some((g) => g.epoch >= e);
    },
    epoch,
    { timeout: 120000 },
  );

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

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

  const dirA = harness.newProfileDir("cp-aud-a-");
  const dirB = harness.newProfileDir("cp-aud-b-");
  const dirC = harness.newProfileDir("cp-aud-c-");
  const dirA2 = harness.newProfileDir("cp-aud-a2-");
  const dirB2 = harness.newProfileDir("cp-aud-b2-");

  // --- contacts: A ↔ B and A ↔ C via the rendezvous flow ----------------------
  let A = await harness.openDevice("A", dirA);
  await createIdentity(A.page);
  await waitContactsReady(A.page);
  const pubA = await myPubOf(A.page);
  const seedA = await mySeedOf(A.page);
  if (!seedA) fail("could not read A's seed for the second-device scenario");
  const { token: tokB } = await createInvite(A.page, "Ana");
  const { token: tokC } = await createInvite(A.page, "Ana");
  for (const tok of [tokB, tokC]) {
    const room = await roomIdOf(A.page, tok.split(".")[0]);
    let count = 0;
    for (let i = 0; i < 40 && count < 1; i++) {
      count = await harness.roomCount(room);
      if (count < 1) await sleep(500);
    }
    if (count < 1) fail("an invite card did not reach its rendezvous room");
  }
  await waitAllRoomsDrained(A.page);
  await A.close();
  ok("A: identity + 2 invites deposited; device closed");

  let B = await harness.openDevice("B", dirB);
  await createIdentity(B.page);
  await waitContactsReady(B.page);
  const pubB = await myPubOf(B.page);
  const seedB = await mySeedOf(B.page);
  if (!seedB) fail("could not read B's seed for the second-device scenario");
  await acceptInvite(B.page, BASE, tokB, "Bogdan");
  await waitAllRoomsDrained(B.page);
  await B.close();

  let C = await harness.openDevice("C", dirC);
  await createIdentity(C.page);
  await waitContactsReady(C.page);
  const pubC = await myPubOf(C.page);
  await acceptInvite(C.page, BASE, tokC, "Cristi");
  await waitAllRoomsDrained(C.page);
  await C.close();
  ok("B + C: accepted A's invites; devices closed");

  // --- A: confirm contacts, group "Prieteni" with B, restricted profile + post -
  A = await harness.openDevice("A2", dirA);
  await A.page.goto(BASE);
  await waitContactsReady(A.page);
  await confirmAll(A.page, [pubB, pubC]);
  await waitChatReady(A.page);
  ok("A: B and C confirmed as verified contacts");

  await A.page.click('[data-testid="tab-contacts"]');
  await A.page.waitForSelector('[data-testid="group-create"]');
  await A.page.click('[data-testid="group-create"]');
  await A.page.fill('[data-testid="group-create-input"]', "Prieteni");
  await A.page.click('[data-testid="group-create-ok"]');
  const gid = await A.page.waitForFunction(
    () => [...window.__cp.selfroom.state.groups.values()].find((g) => g.name === "Prieteni")?.gid,
    undefined,
    { timeout: 20000 },
  );
  const gidStr = await gid.jsonValue();
  await setMembershipUI(A.page, pubB, gidStr, true);
  ok("A: group 'Prieteni' created, B is a member (no key minted yet)");

  // profile with a restricted section for Prieteni → mints G_1 + grants B
  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-sec-add"]');
  await A.page.waitForSelector('[data-testid="pf-sec"]');
  await A.page.fill('[data-testid="pf-sec-about"]', SECRET_ABOUT);
  await A.page.fill('[data-testid="pf-sec-contact"]', SECRET_CONTACT);
  await A.page.click('[data-testid="pf-publish"]');
  await A.page.waitForFunction(
    () => document.querySelector('[data-testid="pf-status"]')?.textContent.includes("publicat:"),
    undefined,
    { timeout: 30000 },
  );
  {
    const epochs = await gkeyEpochs(A.page);
    if (epochs.join(",") !== "1") fail(`expected exactly epoch 1 after first restriction, got [${epochs}]`);
  }
  ok("A: profile published with a sealed section — G_1 + gidHint minted, grant queued for B");

  // --- item 2: owner first-restriction convergence (§3b) ----------------------
  // Simulate a CONCURRENT ensureGroupKey on another of A's devices: inject a
  // competing epoch-1 gkey for the SAME gid that WINS LWW (higher ts, a fresh
  // secret + gidHint). A's live device must notice its own mint lost, re-grant
  // the winning epoch to members over the pair room, and re-seal the profile
  // (onRekeyed) — everyone converges on the ONE winning gidHint.
  await waitAllRoomsDrained(A.page);
  const conv0 = await A.page.evaluate(() => {
    const g = [...window.__cp.selfroom.state.gkeys.values()].find((k) => k.epoch === 1);
    return { gid: g.gid, hint: g.hint, ts: g.ts, seq: window.__cp.selfroom.state.profileSrc?.seq ?? 0 };
  });
  const pairRoomB = await pairMailboxRoomOf(A.page, pubB);
  const grantsBefore = await harness.roomCount(pairRoomB);
  const winner = await A.page.evaluate(
    async ([gid, minTs]) => {
      const crypto = await import("/src/lib/crypto.ts");
      const hint = crypto.toB64url(crypto.randomBytes(16));
      const secret = crypto.toB64url(crypto.randomBytes(32));
      await window.__cp.selfroom.appendHomeOp({ t: "gkey", ts: minTs + 5000, gid, epoch: 1, secret, hint });
      return { hint, secret };
    },
    [conv0.gid, Math.max(conv0.ts, Date.now())],
  );
  // the fold winner's hint is now current, AND it is the group's only hint
  await A.page.waitForFunction(
    ([gid, h]) => {
      const keys = [...window.__cp.selfroom.state.gkeys.values()].filter((k) => k.gid === gid);
      return keys.length > 0 && keys.every((k) => k.hint === h);
    },
    [conv0.gid, winner.hint],
    { timeout: 30000 },
  );
  // onRekeyed fired: the profile re-sealed (seq bumped) under the winning hint
  await A.page.waitForFunction((s) => (window.__cp.selfroom.state.profileSrc?.seq ?? 0) > s, conv0.seq, {
    timeout: 30000,
  });
  await A.page.waitForFunction(
    (h) => (window.__cp.selfroom.state.profileSrc?.doc?.sealed ?? []).some((s) => s.gidHint === h),
    winner.hint,
    { timeout: 30000 },
  );
  if (winner.hint === conv0.hint) fail("convergence test did not actually change the winning hint");
  // the re-grant of the winning epoch reached B's pair room
  {
    const deadline = Date.now() + 30000;
    let after = grantsBefore;
    while (after <= grantsBefore && Date.now() < deadline) {
      after = await harness.roomCount(pairRoomB);
      if (after <= grantsBefore) await sleep(300);
    }
    if (after <= grantsBefore) fail("convergence did not re-grant the winning epoch to B over the pair room");
  }
  await waitAllRoomsDrained(A.page);
  ok("convergence: a concurrent device's winning gkey → own mint re-grants members + re-seals under the ONE winning gidHint");

  // restricted post T1 (epoch 1); A unseals own content → owner badge
  await enterFeed(A.page);
  await composeRestricted(A.page, gidStr, T1);
  const badge = (await A.page.textContent(`${cardWithText(T1)} [data-testid="feed-aud-badge"]`)).trim();
  if (!badge.includes("Prieteni")) fail(`owner badge reads "${badge}", expected the group name`);
  await sleep(2000); // grant append is hook-async — let it reach the queue
  await waitAllRoomsDrained(A.page);
  await A.close();
  ok("A: restricted post T1 published; own card renders with the 'Prieteni' badge");

  // --- B (member): unseals section + post -------------------------------------
  B = await harness.openDevice("B2", dirB);
  await B.page.goto(BASE);
  await waitChatReady(B.page);
  await waitRgrantEpoch(B.page, 1);
  ok("B: audience grant folded from the pairwise room into the home log (rgrant)");

  await B.page.goto(`${BASE}/#/u/${pubA}`);
  await B.page.waitForSelector('[data-testid="up-sealed-open"]', { timeout: 30000 });
  const aboutB = (await B.page.textContent('[data-testid="up-sealed-about"]')).trim();
  const contactB = (await B.page.textContent('[data-testid="up-sealed-contact"]')).trim();
  if (aboutB !== SECRET_ABOUT) fail(`B's unsealed about reads "${aboutB}"`);
  if (contactB !== SECRET_CONTACT) fail(`B's unsealed contact reads "${contactB}"`);
  ok("B: sealed profile section unsealed (about + contact) with the open-lock badge");

  await B.page.goto(`${BASE}/#/`);
  await enterFeed(B.page);
  await B.page.waitForSelector(cardWithText(T1), { timeout: 30000 });
  await B.page.waitForSelector(`${cardWithText(T1)} [data-testid="feed-aud-badge"]`, { timeout: 10000 });
  if (await B.page.$(`${cardWithText(T1)} [data-testid="feed-locked"]`)) fail("B sees T1 locked despite the grant");
  await waitAllRoomsDrained(B.page);
  await B.close();
  ok("B: restricted post T1 unsealed in the feed with the audience badge");

  // --- C (verified contact, NON-member): lock chips only, no ciphertext -------
  C = await harness.openDevice("C2", dirC);
  await C.page.goto(BASE);
  await waitContactsReady(C.page);
  await C.page.goto(`${BASE}/#/u/${pubA}`);
  await C.page.waitForSelector('[data-testid="up-sealed-locked"]', { timeout: 30000 });
  await sleep(2500); // give a (wrong) unseal every chance to happen — it must not
  if (await C.page.$('[data-testid="up-sealed-open"]')) fail("C unsealed a section without a key");
  {
    const body = await C.page.evaluate(() => document.body.innerText);
    if (body.includes(SECRET_ABOUT) || body.includes(SECRET_CONTACT)) fail("restricted plaintext leaked to C's profile view");
  }
  ok("C: profile shows the lock chip only — no plaintext");

  const cts = await audCiphertexts(C.page);
  if (cts.length < 1) fail("no aud-post ciphertext found in the shard rooms");
  await C.page.goto(`${BASE}/#/`);
  await enterFeed(C.page);
  await C.page.waitForSelector('[data-testid="feed-locked"]', { timeout: 30000 });
  {
    const lockedCount = await C.page.$$eval('[data-testid="feed-locked"]', (els) => els.length);
    if (lockedCount !== 1) fail(`C sees ${lockedCount} locked cards, expected 1 (T1)`);
    // locked card = author + time only: no caption, no action row inside it
    const extras = await C.page.$$eval('[data-testid="feed-post"]', (els) =>
      els
        .filter((el) => el.querySelector('[data-testid="feed-locked"]'))
        .map((el) => ({
          caption: !!el.querySelector('[data-testid="feed-caption"]'),
          like: !!el.querySelector('[data-testid="feed-like"]'),
          author: !!el.querySelector('[data-testid="feed-author"]'),
          time: !!el.querySelector(".feed-time"),
        })),
    );
    if (extras.some((e) => e.caption || e.like || !e.author || !e.time))
      fail(`locked card shape wrong: ${JSON.stringify(extras)}`);
    const html = await C.page.content();
    if (html.includes(T1)) fail("restricted post plaintext leaked to C's feed");
    for (const ct of cts) if (html.includes(ct)) fail("sealed-box ciphertext reached C's DOM");
  }
  await C.close();
  ok("C: locked feed card (author + time only); plaintext AND ciphertext absent from the DOM");

  // --- A removes B → rekey epoch 2 + profile re-seal → post T2 ----------------
  A = await harness.openDevice("A3", dirA);
  await A.page.goto(BASE);
  await waitContactsReady(A.page);
  await waitChatReady(A.page);
  await setMembershipUI(A.page, pubB, gidStr, false);
  await A.page.waitForFunction(() => window.__cp.selfroom.state.gkeys.size >= 2, undefined, { timeout: 30000 });
  // the rekey hook re-publishes the profile: the section re-seals under G_2
  await A.page.waitForFunction(() => window.__cp.selfroom.state.profileSrc?.seq >= 2, undefined, { timeout: 30000 });
  ok("A: B removed → G_2 minted, profile re-sealed under the new epoch (seq bumped)");
  await enterFeed(A.page);
  await composeRestricted(A.page, gidStr, T2);
  await sleep(2000);
  await waitAllRoomsDrained(A.page);
  await A.close();
  ok("A: restricted post T2 published under epoch 2; device closed");

  // --- B while EXCLUDED: keeps T1 (removal ≠ retraction), T2 stays locked -----
  B = await harness.openDevice("B3", dirB);
  await B.page.goto(BASE);
  await waitChatReady(B.page);
  await enterFeed(B.page);
  await B.page.waitForSelector(cardWithText(T1), { timeout: 30000 });
  await B.page.waitForSelector('[data-testid="feed-locked"]', { timeout: 30000 });
  {
    const lockedCount = await B.page.$$eval('[data-testid="feed-locked"]', (els) => els.length);
    if (lockedCount !== 1) fail(`excluded B sees ${lockedCount} locked cards, expected 1 (T2)`);
    const html = await B.page.content();
    if (html.includes(T2)) fail("excluded B can read T2");
  }
  ok("HONESTY: removed B still unseals the OLD post T1 (removal ≠ retraction) but NOT the new T2");
  // the re-sealed profile section (epoch 2) went dark for B too
  await B.page.goto(`${BASE}/#/u/${pubA}`);
  await B.page.waitForSelector('[data-testid="up-sealed-locked"]', { timeout: 30000 });
  await sleep(2000);
  if (await B.page.$('[data-testid="up-sealed-open"]')) fail("excluded B still unseals the re-sealed profile section");
  await B.close();
  ok("B: re-sealed profile section is locked for the removed member (rekey cascade works)");

  // --- A: C joins (epoch 2 + chain), C removed (epoch 3), T3, B re-added ------
  A = await harness.openDevice("A4", dirA);
  await A.page.goto(BASE);
  await waitContactsReady(A.page);
  await waitChatReady(A.page);
  await setMembershipUI(A.page, pubC, gidStr, true); // grant: epoch 2 + chain{2}
  await sleep(2000);
  await setMembershipUI(A.page, pubC, gidStr, false); // rekey → epoch 3
  await A.page.waitForFunction(() => window.__cp.selfroom.state.gkeys.size >= 3, undefined, { timeout: 30000 });
  await A.page.waitForFunction(() => window.__cp.selfroom.state.profileSrc?.seq >= 3, undefined, { timeout: 30000 });
  await enterFeed(A.page);
  await composeRestricted(A.page, gidStr, T3);
  await setMembershipUI(A.page, pubB, gidStr, true); // grant: epoch 3 + chain{2,3}
  await sleep(2000);
  await waitAllRoomsDrained(A.page);
  {
    const epochs = await gkeyEpochs(A.page);
    if (epochs.join(",") !== "1,2,3") fail(`A's gkey epochs are [${epochs}], expected [1,2,3]`);
  }
  await A.close();
  ok("A: C joined@2 then removed (→ epoch 3), T3 published, B re-added with the full keychain");

  // --- C after removal: holds epoch 2 → T1+T2 open (chain cascade), T3 locked -
  C = await harness.openDevice("C3", dirC);
  await C.page.goto(BASE);
  await waitChatReady(C.page);
  await waitRgrantEpoch(C.page, 2);
  await enterFeed(C.page);
  await C.page.waitForSelector(cardWithText(T2), { timeout: 30000 });
  await C.page.waitForSelector(cardWithText(T1), { timeout: 30000 }); // epoch 1 via chain{2} — mid-life add = full history
  await C.page.waitForSelector('[data-testid="feed-locked"]', { timeout: 30000 });
  {
    const lockedCount = await C.page.$$eval('[data-testid="feed-locked"]', (els) => els.length);
    if (lockedCount !== 1) fail(`removed C sees ${lockedCount} locked cards, expected 1 (T3)`);
    const html = await C.page.content();
    if (html.includes(T3)) fail("removed C can read T3");
  }
  await C.close();
  ok("C: joined mid-life got FULL history (T1 via keychain); removal keeps epoch 2 (T2) but locks epoch 3 (T3)");

  // --- B re-added: epoch 3 + cascade → EVERYTHING opens, incl. epoch-2 T2 -----
  B = await harness.openDevice("B4", dirB);
  await B.page.goto(BASE);
  await waitChatReady(B.page);
  await waitRgrantEpoch(B.page, 3);
  await enterFeed(B.page);
  for (const text of [T1, T2, T3]) await B.page.waitForSelector(cardWithText(text), { timeout: 30000 });
  if (await B.page.$('[data-testid="feed-locked"]')) fail("re-added B still sees a locked card");
  // T2 was minted WHILE B was excluded — only the keychain cascade (3→2) opens it
  await B.page.waitForSelector(`${cardWithText(T2)} [data-testid="feed-aud-badge"]`, { timeout: 10000 });
  await B.page.goto(`${BASE}/#/u/${pubA}`);
  await B.page.waitForSelector('[data-testid="up-sealed-open"]', { timeout: 30000 });
  await waitAllRoomsDrained(B.page); // rgrants must sync out for B's 2nd device
  await B.close();
  ok("B re-added: unseals T1+T2+T3 (epoch-2 content via keychain cascade) + the profile section");

  // --- A's second device: seed import → gkey sync unseals everything ----------
  const A2 = await harness.openDevice("A-dev2", dirA2);
  await A2.page.goto(BASE);
  await A2.page.waitForSelector('[data-testid="import-id"]', { timeout: 20000 });
  await A2.page.click('[data-testid="import-id"]');
  await A2.page.fill('[data-testid="import-seed"]', seedA);
  await A2.page.waitForSelector('[data-testid="import-fp"]');
  await A2.page.click('[data-testid="import-confirm"]');
  await A2.page.waitForSelector('[data-testid="tab-profile"]', { timeout: 20000 });
  await waitContactsReady(A2.page);
  await A2.page.waitForFunction(() => window.__cp.selfroom.state.gkeys.size >= 3, undefined, { timeout: 120000 });
  await A2.page.goto(`${BASE}/#/u/${pubA}`);
  await A2.page.waitForSelector('[data-testid="up-sealed-open"]', { timeout: 30000 });
  const aboutA2 = (await A2.page.textContent('[data-testid="up-sealed-about"]')).trim();
  if (aboutA2 !== SECRET_ABOUT) fail("A's second device could not unseal the own profile section");
  // restricted posts render as honest lock tiles in the public grid
  await A2.page.waitForSelector('[data-testid="up-tile-lock"]', { timeout: 30000 });
  await A2.page.goto(`${BASE}/#/`);
  await enterFeed(A2.page);
  for (const text of [T1, T2, T3]) await A2.page.waitForSelector(cardWithText(text), { timeout: 30000 });
  if (await A2.page.$('[data-testid="feed-locked"]')) fail("A's second device sees a locked own post");
  const badgeA2 = (await A2.page.textContent(`${cardWithText(T3)} [data-testid="feed-aud-badge"]`)).trim();
  if (!badgeA2.includes("Prieteni")) fail(`A2 owner badge reads "${badgeA2}"`);
  await A2.close();
  ok("A's second device: home-log gkey sync unseals all posts + the profile section (owner labels)");

  // --- B's second device: rgrant sync unseals everything ----------------------
  const B2 = await harness.openDevice("B-dev2", dirB2);
  await B2.page.goto(BASE);
  await B2.page.waitForSelector('[data-testid="import-id"]', { timeout: 20000 });
  await B2.page.click('[data-testid="import-id"]');
  await B2.page.fill('[data-testid="import-seed"]', seedB);
  await B2.page.waitForSelector('[data-testid="import-fp"]');
  await B2.page.click('[data-testid="import-confirm"]');
  await B2.page.waitForSelector('[data-testid="tab-profile"]', { timeout: 20000 });
  await waitContactsReady(B2.page);
  await waitRgrantEpoch(B2.page, 3);
  await enterFeed(B2.page);
  for (const text of [T1, T2, T3]) await B2.page.waitForSelector(cardWithText(text), { timeout: 30000 });
  if (await B2.page.$('[data-testid="feed-locked"]')) fail("B's second device sees a locked card");
  await B2.page.goto(`${BASE}/#/u/${pubA}`);
  await B2.page.waitForSelector('[data-testid="up-sealed-open"]', { timeout: 30000 });
  await B2.close();
  ok("B's second device: rgrant home-log sync unseals all posts + the profile section");
}

let exitCode = 0;
try {
  await main();
  console.log("\n🎉 audience restriction: sealing + grants + rekey + keychain cascade + honesty + multi-device passed");
} catch (err) {
  console.error("❌ " + (err?.message ?? err));
  exitCode = 1;
} finally {
  await harness.shutdown();
}
process.exit(exitCode);

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