cautpartener / client / e2e / chat.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
// M3a chat e2e — the requirement proof: two verified contacts who are NEVER
// online together exchange E2E text messages through their pairwise room's
// mailbox (offline delivery + unread detection), group chats propagate via
// pairwise ginvite + home-log chatreg (including to the receiver's OTHER
// device), and the room-budget LRU keeps >6 conversations from crashing.
// Devices are isolated persistent profiles; the mailbox stub is the ONLY
// transport. Run: node e2e/chat.e2e.mjs        (HEADED=1 to watch)
// NEVER put a seed (or any part of one) into a fail message — it is logged.
import {
  acceptInvite,
  confirmJoinedInvite,
  createHarness,
  createIdentity as createIdentityFlow,
  createInvite,
  fail,
  ok,
  pairMailboxRoomOf,
  roomIdOf,
  sleep,
  waitAllRoomsDrained,
  waitChatReady,
  waitContactsReady,
} from "./helpers.mjs";

const PORT = 5185;
const STUB_PORT = 8792;

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

const openChats = async (page) => {
  await page.click('[data-testid="tab-chats"]');
  await page.waitForSelector('[data-testid="chats-panel"]', { timeout: 60000 });
};

const openConversation = async (page, convId) => {
  await page.evaluate((h) => {
    location.hash = h;
  }, `#/c/${convId}`);
  await page.waitForSelector('[data-testid="chat-input"]', { timeout: 60000 });
};

const sendMessage = async (page, text) => {
  await page.fill('[data-testid="chat-input"]', text);
  await page.click('[data-testid="chat-send"]');
  await page.waitForFunction(
    (t) => [...document.querySelectorAll('[data-testid="chat-msg"]')].some((el) => el.textContent.includes(t)),
    text,
    { timeout: 30000 },
  );
};

const messageTexts = (page) =>
  page.$$eval('[data-testid="chat-msg"] .bubble-body', (els) => els.map((el) => el.textContent));

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

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

  const dirA = harness.newProfileDir("cp-chat-a-");
  const dirB = harness.newProfileDir("cp-chat-b-");
  const dirB2 = harness.newProfileDir("cp-chat-b2-");

  // --- A + B become contacts (M2 rendezvous flow, never co-online) ------------
  let A = await harness.openDevice("A", dirA);
  await createIdentity(A.page);
  await waitContactsReady(A.page);
  const pubA = await A.page.evaluate(() => window.__cp.identity.identity.publicKeyB64);
  const { token } = await createInvite(A.page, "Ana");
  const inviteRoom = await roomIdOf(A.page, token.split(".")[0]);
  {
    let count = 0;
    for (let i = 0; i < 40 && count !== 1; i++) {
      count = await harness.roomCount(inviteRoom);
      if (count !== 1) await sleep(500);
    }
    if (count !== 1) fail(`A's card is not in the rendezvous room (count=${count})`);
  }
  await waitAllRoomsDrained(A.page);
  await A.close();
  ok("A: invite created + card deposited; device closed");

  let B = await harness.openDevice("B", dirB);
  await createIdentity(B.page);
  await waitContactsReady(B.page);
  const pubB = await B.page.evaluate(() => window.__cp.identity.identity.publicKeyB64);
  await acceptInvite(B.page, BASE, token, "Bogdan");
  await waitAllRoomsDrained(B.page);
  const seedB = await B.page.evaluate(() => localStorage.getItem("cautpartener:id"));
  if (!seedB) fail("could not read B's seed for the second-device scenario");
  await B.close();
  ok("B: accepted A's invite; device closed");

  // --- A confirms B, then sends 2 messages while B is OFFLINE -----------------
  A = await harness.openDevice("A2", dirA);
  await A.page.goto(BASE);
  await confirmJoinedInvite(A.page);
  await A.page.waitForFunction((pub) => window.__cp?.contacts?.state.contacts.get(pub)?.status === "active", pubB, {
    timeout: 60000,
  });
  ok("A: B confirmed as a verified contact");

  await waitChatReady(A.page);
  await openChats(A.page);
  // every active contact is an available conversation
  await A.page.waitForSelector(`[data-testid="conv-row"][data-conv="${pubB}"]`, { timeout: 30000 });
  await A.page.click(`[data-testid="conv-row"][data-conv="${pubB}"]`);
  await A.page.waitForSelector('[data-testid="chat-input"]', { timeout: 60000 });
  await sendMessage(A.page, "Salut 1");
  await sleep(150); // distinct ts — the order assertion must not hinge on a hash tiebreak
  await sendMessage(A.page, "Salut 2");
  const pairRoomA = await pairMailboxRoomOf(A.page, pubB);
  await waitAllRoomsDrained(A.page);
  {
    // identity record + 2 sealed entries must sit in the pair room's mailbox
    const count = await harness.roomCount(pairRoomA);
    if (count < 3) fail(`pair room holds ${count} blobs — expected ident + 2 entries`);
  }
  await A.close();
  ok("A: 2 messages deposited to the pair room; device closed (B still offline)");

  // --- B boots: unread dot on the list, then both messages in order -----------
  B = await harness.openDevice("B2", dirB);
  await B.page.goto(BASE);
  await waitChatReady(B.page);
  // the pair secret must be SYMMETRIC: B derives the same mailbox room
  await waitContactsReady(B.page);
  const pairRoomB = await pairMailboxRoomOf(B.page, pubA);
  if (pairRoomB !== pairRoomA) fail("pairSecret asymmetry: A and B derived different mailbox rooms");
  ok("B: pairSecret symmetric — same pair mailbox room as A");

  await openChats(B.page);
  await B.page.waitForSelector(`[data-testid="conv-row"][data-conv="${pubA}"] [data-testid="conv-unread"]`, {
    timeout: 90000,
  });
  ok("B: conversation with A shows the unread dot (offline messages detected)");

  await B.page.click(`[data-testid="conv-row"][data-conv="${pubA}"]`);
  await B.page.waitForSelector('[data-testid="chat-input"]', { timeout: 60000 });
  await B.page.waitForFunction(() => document.querySelectorAll('[data-testid="chat-msg"]').length >= 2, undefined, {
    timeout: 90000,
  });
  {
    const texts = await messageTexts(B.page);
    if (texts.length !== 2) fail(`B sees ${texts.length} messages, expected 2`);
    if (texts[0] !== "Salut 1" || texts[1] !== "Salut 2") fail(`wrong order/content: ${JSON.stringify(texts)}`);
    const authors = await B.page.$$eval('[data-testid="chat-msg"]', (els) => els.map((el) => el.dataset.from));
    if (!authors.every((a) => a === pubA)) fail("a replayed message is not attributed to A's verified identity");
    const sides = await B.page.$$eval('[data-testid="chat-msg"]', (els) =>
      els.map((el) => el.closest(".msg-row")?.className ?? ""),
    );
    if (!sides.every((c) => c.includes("theirs"))) fail("A's messages did not render on the 'theirs' side");
    const days = await B.page.$$('[data-testid="chat-day"]');
    if (days.length < 1) fail("no day separator rendered");
  }
  ok("B: both offline messages delivered — correct order, author and styling");

  // --- B replies; A receives after reopening ----------------------------------
  await sendMessage(B.page, "Bine!");
  await waitAllRoomsDrained(B.page);
  await B.close();
  ok("B: replied; device closed");

  A = await harness.openDevice("A3", dirA);
  await A.page.goto(BASE);
  await waitChatReady(A.page);
  await openConversation(A.page, pubB);
  await A.page.waitForFunction(
    () => [...document.querySelectorAll('[data-testid="chat-msg"]')].some((el) => el.textContent.includes("Bine!")),
    undefined,
    { timeout: 90000 },
  );
  ok("A: received B's reply (both directions, never co-online)");

  // --- group: A creates it in the UI, sends a message -------------------------
  await A.page.evaluate(() => {
    location.hash = "#/";
  });
  await openChats(A.page);
  await A.page.click('[data-testid="newgroup-open"]');
  await A.page.fill('[data-testid="newgroup-name"]', "Trupa");
  await A.page.check(`[data-testid="newgroup-member"][data-pub="${pubB}"] input`);
  await A.page.waitForSelector('[data-testid="newgroup-create"]:not([disabled])');
  await A.page.click('[data-testid="newgroup-create"]');
  await A.page.waitForSelector('[data-testid="chat-input"]', { timeout: 60000 });
  const gid = await A.page.evaluate(() => location.hash.split("/c/")[1]);
  if (!gid || gid.includes(".")) fail(`unexpected group conversation id: ${gid}`);
  const members = await A.page.waitForFunction((id) => window.__cp.selfroom.state.chats.get(id)?.members, gid, {
    timeout: 30000,
  });
  const memberList = await members.jsonValue();
  if (memberList.length !== 2 || !memberList.includes(pubA) || !memberList.includes(pubB))
    fail(`chatreg member set wrong: ${memberList.length} members`);
  await sendMessage(A.page, "Hei grup");
  await waitAllRoomsDrained(A.page);
  await A.close();
  ok("A: group 'Trupa' created (chatreg + ginvite) and a message sent; device closed");

  // --- B boots: ginvite via pair room → group appears with the message --------
  B = await harness.openDevice("B3", dirB);
  await B.page.goto(BASE);
  await waitChatReady(B.page);
  await openChats(B.page);
  await B.page.waitForSelector(`[data-testid="conv-row"][data-conv="${gid}"]`, { timeout: 90000 });
  const groupRowText = (await B.page.textContent(`[data-testid="conv-row"][data-conv="${gid}"]`)).trim();
  if (!groupRowText.includes("Trupa")) fail(`group row reads "${groupRowText}"`);
  ok("B: ginvite folded from the pair room → group conversation registered");

  await B.page.click(`[data-testid="conv-row"][data-conv="${gid}"]`);
  await B.page.waitForSelector('[data-testid="chat-input"]', { timeout: 60000 });
  await B.page.waitForFunction(
    () => [...document.querySelectorAll('[data-testid="chat-msg"]')].some((el) => el.textContent.includes("Hei grup")),
    undefined,
    { timeout: 90000 },
  );
  {
    const author = await B.page.$eval('[data-testid="chat-msg"]', (el) => el.dataset.from);
    if (author !== pubA) fail("group message not attributed to A");
    const label = await B.page.$eval(".msg-author", (el) => el.textContent.trim()).catch(() => "");
    if (label !== "Ana") fail(`group author label is "${label}", expected "Ana"`);
    const memberCount = (await B.page.textContent('[data-testid="chat-members"]')).trim();
    if (!memberCount.includes("2")) fail(`group header member count reads "${memberCount}"`);
  }

  // --- §5 ginvite sender authorization: a forged invite from a contact who -----
  //     is NOT in its own member roster must NOT register a group (else that
  //     contact hands out a secret they hold while hiding from the roster —
  //     a hidden reader). A legitimate invite (sender ∈ members) still works.
  {
    const r = await B.page.evaluate(
      async ([senderPub, myPub]) => {
        const { registerGinvite } = await import("/src/core/groupchat.ts");
        const { randomBytes, toB64url } = await import("/src/lib/crypto.ts");
        const selfroom = window.__cp.selfroom;
        const stranger = toB64url(randomBytes(32)); // 43-char pub, not the sender
        // forged: names ME, but OMITS the verified sender from the roster
        const forgedId = toB64url(randomBytes(16));
        const forged = {
          t: "ginvite", ts: Date.now(), id: forgedId, secret: toB64url(randomBytes(32)),
          name: "Skulk", members: [myPub, stranger],
        };
        const rejected = await registerGinvite(selfroom, myPub, senderPub, forged);
        const forgedRegistered = selfroom.state.chats.has(forgedId);
        // legitimate: same shape, but the sender IS a member
        const legitId = toB64url(randomBytes(16));
        const legit = {
          t: "ginvite", ts: Date.now(), id: legitId, secret: toB64url(randomBytes(32)),
          name: "Legit", members: [myPub, senderPub],
        };
        const accepted = await registerGinvite(selfroom, myPub, senderPub, legit);
        const legitRegistered = selfroom.state.chats.has(legitId);
        return { rejected, forgedRegistered, accepted, legitRegistered };
      },
      [pubA, pubB],
    );
    if (r.rejected !== false) fail("forged ginvite (sender not in members) was accepted");
    if (r.forgedRegistered) fail("forged ginvite registered a group despite the sender not being a member");
    if (r.accepted !== true) fail("legitimate ginvite (sender in members) was rejected");
    if (!r.legitRegistered) fail("legitimate ginvite did not register the group");
  }
  ok("§5: ginvite from a non-member sender refused; legitimate invite still registers");

  await waitAllRoomsDrained(B.page); // B's chatreg registration reaches the mailbox
  await B.close();
  ok("B: group message delivered with author label; chatreg synced out");

  // --- B's OTHER device: same seed import → group via home-log chatreg --------
  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 waitChatReady(B2.page);
  await openChats(B2.page);
  await B2.page.waitForSelector(`[data-testid="conv-row"][data-conv="${gid}"]`, { timeout: 90000 });
  ok("B's second device: group visible via home-log chatreg sync (no ginvite needed)");
  await B2.page.click(`[data-testid="conv-row"][data-conv="${gid}"]`);
  await B2.page.waitForSelector('[data-testid="chat-input"]', { timeout: 60000 });
  await B2.page.waitForFunction(
    () => [...document.querySelectorAll('[data-testid="chat-msg"]')].some((el) => el.textContent.includes("Hei grup")),
    undefined,
    { timeout: 90000 },
  );
  ok("B's second device: group history replayed from the mailbox");
  await B2.close();

  // --- budget: >6 conversations must not crash (LRU-close, self pinned) -------
  A = await harness.openDevice("A4", dirA);
  const errorsBudget = [];
  A.page.on("pageerror", (e) => errorsBudget.push(e.message));
  await A.page.goto(BASE);
  await waitChatReady(A.page);
  const gids = await A.page.evaluate(async (peer) => {
    const ids = [];
    for (let i = 1; i <= 7; i++) ids.push(await window.__cp.chat.createGroup(`Grup ${i}`, [peer]));
    return ids;
  }, pubB);
  if (gids.length !== 7) fail("could not create 7 extra groups");
  for (const id of [...gids, pubB, gid]) {
    await openConversation(A.page, id);
    const open = await A.page.evaluate(() => window.__cp.hub.debug.open);
    if (open > 6) fail(`room budget exceeded: ${open} rooms open`);
  }
  // the app is still alive and can send in the most recent room
  await sendMessage(A.page, "încă merge");
  {
    const dbg = await A.page.evaluate(() => window.__cp.hub.debug);
    if (dbg.open > 6) fail(`room budget exceeded after churn: ${dbg.open}`);
    if (!dbg.rooms.some((r) => r.kind === "self" && r.pinned)) fail("self room lost its pin during LRU churn");
  }
  if (errorsBudget.length > 0) fail(`page errors during budget churn: ${errorsBudget.join(" | ")}`);
  ok("budget: 9 conversations cycled through ≤6 open rooms, self pinned, no errors");
  await waitAllRoomsDrained(A.page);
  await A.close();
}

let exitCode = 0;
try {
  await main();
  console.log("\n🎉 chat (pair + group + offline delivery + budget) scenarios 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