File size: 26,375 Bytes
b855ced
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cce9364
 
 
b855ced
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// End-to-end encryption test: two real crypto machines (vodozemac via
// @matrix-org/matrix-sdk-crypto-wasm) talk through the Taper server, which
// only ever relays ciphertext. Run with `npm test`.

import { spawn } from 'node:child_process';
import { createServer } from 'node:net';
import assert from 'node:assert/strict';
import { randomBytes } from 'node:crypto';
import * as sdk from '../client/node_modules/@matrix-org/matrix-sdk-crypto-wasm/node.mjs';
import { TaperCrypto, padme, verifyRoomState } from '../client/crypto.js';
import { encryptFile, decryptFile, upload, download } from '../client/media.js';
import { Client } from './test-client.js';

const PORT = await new Promise((r) => {
  const s = createServer();
  s.listen(0, '127.0.0.1', () => { const { port } = s.address(); s.close(() => r(port)); });
});
const URL_ = `ws://127.0.0.1:${PORT}/_taper/gateway/v1`;
const txn = () => randomBytes(8).toString('hex');

// Connect, register (or log in as another device), identify, and wire gateway
// dispatches into a crypto machine. Cross-signs the device unless told not to.
async function user(name, { login = false, crossSign = true } = {}) {
  const c = await Client.connectTo(URL_);
  const auth = await (login ? c.login(name, `${name}-password-1`) : c.register(name, `${name}-password-1`));
  c.send({ op: 'identify', body: { access_token: auth.access_token } });
  await c.next((f) => f.op === 'ready');
  const lc = await TaperCrypto.create(sdk, { userId: auth.user_id, deviceId: auth.device_id, request: (m, b) => c.call(m, b) });
  if (crossSign) assert.equal(await lc.ensureCrossSigning({ exportKey: auth.exportKey }), 'created');
  const pending = [];
  const bg = (p) => pending.push(p.catch((e) => { if (!/connection closed/.test(e?.message ?? '')) throw e; }));
  c.handlers.push((f) => {
    if (f.op !== 'dispatch') return false;
    if (f.type === 't.to_device') bg(lc.receive({ toDevice: f.body.events }));
    else if (f.type === 't.device_lists') bg(lc.receive({ changed: f.body.changed }));
    else if (f.type === 't.keys.counts') bg(lc.receive({ oneTimeKeyCounts: f.body.one_time_key_counts }));
    else return false;
    return true;
  });
  return { c, lc, id: auth.user_id, exportKey: auth.exportKey, settle: () => Promise.all(pending.splice(0)) };
}

// Poll until `pred` (sync or async) is truthy, letting dispatches settle.
async function waitFor(pred, ms = 10_000) {
  const end = Date.now() + ms;
  for (;;) {
    if (await pred()) return;
    if (Date.now() > end) throw new Error(`timed out waiting for ${pred}`);
    await new Promise((r) => setTimeout(r, 50));
  }
}

async function main() {
  const server = spawn(process.execPath, ['index.js'], { env: { ...process.env, PORT: String(PORT), TAPER_REGISTER_POW_BITS: '8' }, stdio: ['ignore', 'pipe', 'inherit'] });
  await new Promise((resolve) => server.stdout.once('data', resolve));
  await sdk.initAsync();

  const results = [];
  const test = async (name, fn) => {
    try { await fn(); results.push(['PASS', name]); } catch (e) { results.push(['FAIL', name, e.stack ?? e.message]); }
  };

  let alice, bob, room_id, aliceEvent;
  const members = () => [alice.id, bob.id];
  const nextEvent = (u, pred) => u.c.next((f) => f.type === 't.room.event' && pred(f.body.event), 5000).then((f) => f.body.event);

  await test('devices upload signed keys', async () => {
    alice = await user('alice');
    bob = await user('bob');
    ({ room_id } = await alice.c.call('t.room.create', {}));
    await alice.c.call('t.room.invite', { room_id, user_id: bob.id });
    await bob.c.call('t.room.join', { room_id });
    const q = await alice.c.call('t.keys.query', { device_keys: { [bob.id]: [] } });
    const devices = Object.values(q.device_keys[bob.id]);
    assert.equal(devices.length, 1);
    assert.ok(devices[0].signatures[bob.id]);
  });

  await test('every device is cross-signed by its owner', async () => {
    const q = await alice.c.call('t.keys.query', { device_keys: { [bob.id]: [] } });
    const master = q.master_keys[bob.id];
    const ssk = q.self_signing_keys[bob.id];
    assert.ok(master && ssk, 'no cross-signing keys');
    const sskId = Object.keys(ssk.keys)[0];
    const device = Object.values(q.device_keys[bob.id])[0];
    assert.ok(device.signatures[bob.id][sskId], 'device not signed by the self-signing key');
    assert.equal(q.user_signing_keys[bob.id], undefined, 'user-signing keys must only go to their owner');
  });

  await test('server rejects device keys with a bad signature', async () => {
    const q = await alice.c.call('t.keys.query', { device_keys: { [alice.id]: [] } });
    const mine = structuredClone(Object.values(q.device_keys[alice.id])[0]);
    mine.algorithms = [...mine.algorithms, 'tampered'];
    const r = await alice.c.request('t.keys.upload', { device_keys: mine });
    assert.equal(r.error?.errcode, 'T_INVALID_SIGNATURE');
  });

  await test('alice sends, bob decrypts; the server only sees ciphertext', async () => {
    const body = 'hello bob, this is end-to-end encrypted';
    const content = await alice.lc.encrypt(room_id, members(), 't.room.message', { msgtype: 't.text', body });
    assert.equal(content.algorithm, 't.megolm.v1.aes-sha2');
    assert.ok(!JSON.stringify(content).includes(body), 'plaintext leaked into the event content');
    const { event_id } = await alice.c.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content });
    aliceEvent = await nextEvent(bob, (e) => e.event_id === event_id);
    await bob.settle();
    const out = await bob.lc.decrypt(aliceEvent);
    assert.equal(out.content.body, body);
    // The server's copy is ciphertext too.
    const stored = await bob.c.call('t.room.event', { room_id, event_id });
    assert.ok(!JSON.stringify(stored).includes(body));
  });

  await test('bob replies, alice decrypts', async () => {
    const content = await bob.lc.encrypt(room_id, members(), 't.room.message', { msgtype: 't.text', body: 'hi alice' });
    const { event_id } = await bob.c.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content });
    const ev = await nextEvent(alice, (e) => e.event_id === event_id);
    await alice.settle();
    assert.equal((await alice.lc.decrypt(ev)).content.body, 'hi alice');
  });

  await test('the room name is encrypted state that only members can read', async () => {
    const plain = await alice.c.request('t.room.state.set', { room_id, type: 't.room.name', content: { name: 'leaky' } });
    assert.equal(plain.error?.errcode, 'T_FORBIDDEN', 'plaintext room names must be refused');
    const enc = await alice.lc.encryptState(room_id, members(), 't.room.name', '', { name: 'secret plans' });
    assert.equal(enc.state_key, 't.room.name:');
    const { event_id } = await alice.c.call('t.room.state.set', { room_id, ...enc });
    const ev = await nextEvent(bob, (e) => e.event_id === event_id);
    await bob.settle();
    assert.ok(!JSON.stringify(ev).includes('secret plans'), 'the server saw the room name');
    const out = await bob.lc.decrypt(ev);
    assert.equal(out.type, 't.room.name');
    assert.equal(out.content.name, 'secret plans');
    // A server can't relabel encrypted state: the packed key must match.
    const relabelled = structuredClone(ev);
    relabelled.state_key = 't.room.topic:';
    relabelled.event_id = '$' + randomBytes(32).toString('base64url');
    // Rejected by the library or, failing that, by our own check.
    await assert.rejects(bob.lc.decrypt(relabelled));
  });

  await test('encrypted media: only members who can see the message can download it', async () => {
    const marker = new TextEncoder().encode('TAPER-MEDIA-MARKER');
    const plain = new Uint8Array(150_000);
    for (let i = 0; i < 100_000; i += 65_536) crypto.getRandomValues(plain.subarray(i, Math.min(i + 65_536, 100_000)));
    plain.set(marker, 1000);
    const enc = await encryptFile(plain);
    assert.equal(enc.ciphertext.length, padme(plain.length), 'ciphertext should be padded to its Padme bucket');
    const io = (u) => ({ request: (m, b) => u.c.call(m, b), sendBinary: (x) => u.c.sendBinary(x), downloads: u.c.downloads });
    const uri = await upload(enc.ciphertext, io(alice));
    assert.match(uri, /^runit:\/\/localhost\//);

    // Before any message lists it, only the uploader can fetch it.
    assert.equal((await download(uri, io(alice))).length, enc.ciphertext.length);
    await assert.rejects(download(uri, io(bob)), /T_NOT_FOUND/);

    // Nobody can attach someone else's upload.
    const stolen = await bob.lc.encrypt(room_id, members(), 't.room.message', { msgtype: 't.text', body: 'mine now' }, { attachments: [uri] });
    await assert.rejects(bob.c.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content: stolen }), /T_FORBIDDEN/);

    const content = await alice.lc.encrypt(room_id, members(), 't.room.message',
      { msgtype: 't.image', body: 'picture.bin', file: { ...enc.file, url: uri }, info: { size: plain.length } }, { attachments: [uri] });
    const { event_id } = await alice.c.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content });
    const ev = await nextEvent(bob, (e) => e.event_id === event_id);
    await bob.settle();
    const msg = await bob.lc.decrypt(ev);
    const fetched = await download(msg.content.file.url, io(bob));
    const bytes = await decryptFile(msg.content.file, fetched, msg.content.info.size);
    assert.deepEqual(bytes, plain, 'decrypted media differs from the original');
    // Every media frame on the wire is a full chunk, so sizes don't leak.
    assert.ok(bob.c.sizes.binary.length > 0 && bob.c.sizes.binary.every((n) => n === 21 + 65_536), `binary frame sizes: ${[...new Set(bob.c.sizes.binary)]}`);

    // Someone outside the room gets "not found".
    const dave = await user('dave');
    await assert.rejects(download(uri, io(dave)), /T_NOT_FOUND/);
    dave.c.close();

    // A message that mentions media without listing it in attachments is rejected.
    const unlisted = await alice.lc.encrypt(room_id, members(), 't.room.message',
      { msgtype: 't.image', body: 'sneaky', file: { ...enc.file, url: uri }, info: { size: plain.length } });
    const sneaky = await alice.c.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content: unlisted });
    const sneakyEv = await nextEvent(bob, (e) => e.event_id === sneaky.event_id);
    await assert.rejects(bob.lc.decrypt(sneakyEv), /does not list in attachments/);

    // Redacting the message takes away access.
    await alice.c.call('t.room.send', { room_id, type: 't.room.redaction', txn_id: txn(), content: { redacts: event_id } });
    await assert.rejects(download(uri, io(bob)), /T_NOT_FOUND/);
  });

  await test('plaintext is padded to its Padme bucket', async () => {
    const short = await alice.lc.encrypt(room_id, members(), 't.room.message', { msgtype: 't.text', body: 'a' });
    const longer = await alice.lc.encrypt(room_id, members(), 't.room.message', { msgtype: 't.text', body: 'a'.repeat(40) });
    // Both fit the minimum 256-byte bucket, so their ciphertexts are the same size.
    assert.equal(short.ciphertext.length, longer.ciphertext.length);
    assert.equal(padme(300), 304);
  });

  await test('a ciphertext moved to another binding is rejected', async () => {
    const forged = structuredClone(aliceEvent);
    forged.content.binding = randomBytes(16).toString('base64').replace(/=+$/, '');
    await assert.rejects(bob.lc.decrypt(forged), /moved from another event/);
  });

  await test('a ciphertext claimed by the wrong sender is rejected', async () => {
    const forged = structuredClone(aliceEvent);
    forged.sender = bob.id;
    await assert.rejects(bob.lc.decrypt(forged), /someone else|known device/);
  });

  await test('a replayed message index is rejected', async () => {
    const replay = structuredClone(aliceEvent);
    replay.event_id = `$${randomBytes(32).toString('base64url')}`;
    await assert.rejects(bob.lc.decrypt(replay), /Replayed message/);
  });

  await test('a device the server invents gets no room keys', async () => {
    // A malicious server can mint a login for bob and add a device. It can't
    // sign that device with bob's self-signing key, so nobody shares with it.
    const fake = await user('bob', { login: true, crossSign: false });
    await alice.lc.receive({ changed: [bob.id] });
    const content = await alice.lc.encrypt(room_id, members(), 't.room.message', { msgtype: 't.text', body: 'not for the server' });
    const { event_id } = await alice.c.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content });
    const toFake = await nextEvent(fake, (e) => e.event_id === event_id);
    await fake.settle();
    await assert.rejects(fake.lc.decrypt(toFake), 'the unsigned device could decrypt');
    const toBob = await nextEvent(bob, (e) => e.event_id === event_id);
    await bob.settle();
    assert.equal((await bob.lc.decrypt(toBob)).content.body, 'not for the server');
    fake.c.close();
  });

  await test('replacing an identity needs the password', async () => {
    const other = await user('bob', { login: true, crossSign: false });
    assert.equal(await other.lc.ensureCrossSigning(), 'needs-password');
    await assert.rejects(other.lc.ensureCrossSigning({ reauth: () => other.c.reauth('bob', 'wrong-password') }), /Invalid username or password/);
    // The server checks the proof itself: a forged KE3, or a proof for
    // another account, is refused.
    const forged = async () => ({ ...(await other.c.reauth('bob', 'bob-password-1')), ke3: Buffer.alloc(64, 1).toString('base64url') });
    await assert.rejects(other.lc.ensureCrossSigning({ reauth: forged }), /T_FORBIDDEN/);
    await assert.rejects(other.lc.ensureCrossSigning({ reauth: () => other.c.reauth('alice', 'alice-password-1') }), /another account/);
    other.c.close();
  });

  await test('a new member cannot decrypt messages from before they joined', async () => {
    const carol = await user('carol');
    await alice.c.call('t.room.invite', { room_id, user_id: carol.id });
    await carol.c.call('t.room.join', { room_id });
    await carol.settle();
    await assert.rejects(carol.lc.decrypt(aliceEvent));
    // ...but can read new ones.
    const content = await alice.lc.encrypt(room_id, [alice.id, bob.id, carol.id], 't.room.message', { msgtype: 't.text', body: 'welcome carol' });
    const { event_id } = await alice.c.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content });
    const ev = await nextEvent(carol, (e) => e.event_id === event_id);
    await carol.settle();
    assert.equal((await carol.lc.decrypt(ev)).content.body, 'welcome carol');
  });

  await test('alice and bob verify each other by comparing emoji', async () => {
    let bobSide = null;
    bob.lc.onVerificationRequest = (v) => { bobSide = v; };
    const aliceSide = await alice.lc.startVerification(bob.id);
    await waitFor(() => bobSide);
    await bobSide.accept();
    await waitFor(() => aliceSide.state() === 'ready');
    await aliceSide.start();
    await waitFor(() => aliceSide.state() === 'emoji' && bobSide.state() === 'emoji');
    const emoji = aliceSide.emoji();
    assert.equal(emoji.length, 7);
    assert.deepEqual(emoji, bobSide.emoji(), 'both sides must show the same emoji');
    await aliceSide.confirm();
    await bobSide.confirm();
    await waitFor(() => aliceSide.state() === 'done' && bobSide.state() === 'done');
    await waitFor(async () => (await alice.lc.identityTrust(bob.id)) === 'verified');
    await waitFor(async () => (await bob.lc.identityTrust(alice.id)) === 'verified');
  });

  await test("bob's new device recovers his identity with his password; alice still trusts him", async () => {
    const phone = await user('bob', { login: true, crossSign: false });
    // The server holds only a sealed blob, and never sees the export key.
    const { secrets } = await phone.c.call('t.secrets.get', {});
    assert.equal(secrets.algorithm, 't.secrets.v1.aes-gcm');
    for (const text of phone.c.sent) assert.ok(!text.includes(phone.exportKey), 'the export key crossed the socket');
    assert.equal(await phone.lc.ensureCrossSigning({ exportKey: phone.exportKey }), 'recovered');
    await alice.lc.receive({ changed: [bob.id] });
    await alice.settle();
    assert.equal(await alice.lc.identityTrust(bob.id), 'verified', 'recovery must not look like an identity change');
    // Alice's messages reach the new device, which is trusted.
    const content = await alice.lc.encrypt(room_id, members(), 't.room.message', { msgtype: 't.text', body: 'to every bob device' });
    const { event_id } = await alice.c.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content });
    const ev = await nextEvent(phone, (e) => e.event_id === event_id);
    await phone.settle();
    assert.equal((await phone.lc.decrypt(ev)).content.body, 'to every bob device');
    // A stolen token can't replace the stored copy without the password.
    const r = await phone.c.request('t.secrets.put', { secrets });
    assert.equal(r.error?.errcode, 'T_FORBIDDEN');
    phone.c.close();
  });

  await test('a wrong password or a tampered copy recovers nothing', async () => {
    const { openSecrets, sealSecrets } = await import('../client/crypto.js');
    const sealed = await sealSecrets(bob.exportKey, bob.id, { master: 'x' });
    assert.deepEqual(await openSecrets(bob.exportKey, bob.id, sealed), { master: 'x' });
    await assert.rejects(openSecrets(alice.exportKey, bob.id, sealed));
    await assert.rejects(openSecrets(bob.exportKey, alice.id, sealed), undefined, 'a copy moved to another account must not open');
    const flipped = { ...sealed, ciphertext: sealed.ciphertext.replace(/^./, (ch) => (ch === 'A' ? 'B' : 'A')) };
    await assert.rejects(openSecrets(bob.exportKey, bob.id, flipped));
  });

  await test("alice is warned when verified bob's identity changes", async () => {
    const reset = await user('bob', { login: true, crossSign: false });
    assert.equal(await reset.lc.ensureCrossSigning({ reauth: () => reset.c.reauth('bob', 'bob-password-1') }), 'reset');
    await alice.lc.receive({ changed: [bob.id] });
    assert.equal(await alice.lc.identityTrust(bob.id), 'violation');
    // Alice's client refuses to send to bob until she verifies him again.
    await assert.rejects(
      alice.lc.encrypt(room_id, members(), 't.room.message', { msgtype: 't.text', body: 'blocked' }),
      /changed their identity/,
    );
    reset.c.close();
  });

  await test('in-band room key forwarding and requests are disabled (Albrecht et al.)', () => {
    assert.equal(alice.lc.machine.roomKeyForwardingEnabled, false);
    assert.equal(alice.lc.machine.roomKeyRequestsEnabled, false);
  });

  await test('messages from an unsigned device are rejected on receive (Albrecht et al.)', async () => {
    const { room_id: r2 } = await alice.c.call('t.room.create', {});
    const eve = await user('eve', { crossSign: false });
    await alice.c.call('t.room.invite', { room_id: r2, user_id: eve.id });
    await eve.c.call('t.room.join', { room_id: r2 });
    // Eve uploads device keys without cross-signing and tries to send a message.
    const { UserId, RoomId, EncryptionSettings, CollectStrategy } = sdk;
    await eve.lc.serial(async () => {
      await eve.lc.machine.updateTrackedUsers([new UserId(alice.id), new UserId(eve.id)]);
    });
    await eve.lc.flush();
    await eve.lc.serial(async () => {
      const claim = await eve.lc.machine.getMissingSessions([new UserId(alice.id)]);
      if (claim) await eve.lc.sendRequest(claim);
      const settings = new EncryptionSettings();
      settings.sharingStrategy = CollectStrategy.allDevices();
      const reqs = await eve.lc.machine.shareRoomKey(new RoomId(r2), [new UserId(alice.id)], settings);
      for (const req of reqs) await eve.lc.sendRequest(req);
    });
    const binding = randomBytes(16).toString('base64').replace(/=+$/, '');
    const encJson = await eve.lc.serial(() => eve.lc.machine.encryptRoomEvent(
      new RoomId(r2), 't.room.message', JSON.stringify({ msgtype: 't.text', body: 'spoofed', binding }),
    ));
    const outer = JSON.parse(encJson);
    const { event_id } = await eve.c.call('t.room.send', {
      room_id: r2, type: 't.room.encrypted', txn_id: txn(),
      content: { ...outer, algorithm: 't.megolm.v1.aes-sha2', binding },
    });
    const ev = await nextEvent(alice, (e) => e.event_id === event_id);
    await alice.settle();
    // Rejected either at Olm TrustRequirement.CrossSigned (no key) or explicit unsigned device check!
    await assert.rejects(alice.lc.decrypt(ev));
    eve.c.close();
  });

  await test('stripped binding, tampered relation, and backdated server timestamp are caught', async () => {
    const frank = await user('frank');
    const { room_id: r3 } = await alice.c.call('t.room.create', {});
    await alice.c.call('t.room.invite', { room_id: r3, user_id: frank.id });
    await frank.c.call('t.room.join', { room_id: r3 });
    const rel = { rel_type: 't.replace', event_id: '$orig123' };
    const content = await alice.lc.encrypt(r3, [alice.id, frank.id], 't.room.message', { msgtype: 't.text', body: 'edited text' }, { relatesTo: rel });
    const { event_id } = await alice.c.call('t.room.send', { room_id: r3, type: 't.room.encrypted', txn_id: txn(), content });
    const ev = await nextEvent(frank, (e) => e.event_id === event_id);
    await frank.settle();

    // Stripped outer binding must fail (no undefined === undefined bypass).
    const noBind = structuredClone(ev);
    delete noBind.content.binding;
    await assert.rejects(frank.lc.decrypt(noBind), /moved from another event/);

    // Tampered outer t.relates_to must fail.
    const badRel = structuredClone(ev);
    badRel.content['t.relates_to'] = { rel_type: 't.replace', event_id: '$different' };
    await assert.rejects(frank.lc.decrypt(badRel), /relation does not match/);

    // Backdated server origin_server_ts triggers a timestamp warning.
    const backdated = structuredClone(ev);
    backdated.origin_server_ts = Date.now() - 3_600_000;
    const dec = await frank.lc.decrypt(backdated);
    assert.equal(dec.trust, 'warning');
    assert.match(dec.trustMessage, /timestamp differs/);

    // Client-side room state verification passes for real state and flags forged room_id.
    const { state } = await frank.c.call('t.room.state', { room_id: r3 });
    assert.equal((await verifyRoomState(r3, state)).ok, true);
    assert.equal((await verifyRoomState('!forged-id', state)).ok, false);

    // Verified-only mode refuses to send to unverified Frank!
    await assert.rejects(
      alice.lc.encrypt(r3, [alice.id, frank.id], 't.room.message', { msgtype: 't.text', body: 'secret' }, { verifiedOnly: true }),
      /Verified-only room/,
    );
    frank.c.close();
  });

  await test('client-side Megolm session retention expires old keys and blocks export', async () => {
    const c = await Client.connectTo(URL_);
    const auth = await c.register('grace', 'grace-password-1');
    await c.identify(auth.access_token);
    const lc = await TaperCrypto.create(sdk, { userId: auth.user_id, deviceId: auth.device_id, request: (m, b) => c.call(m, b), maxKeyAgeMs: 120 });
    await lc.ensureCrossSigning({ exportKey: auth.exportKey });
    const { room_id: r4 } = await c.call('t.room.create', {});
    const content = await lc.encrypt(r4, [auth.user_id], 't.room.message', { msgtype: 't.text', body: 'ephemeral key' });
    const { event_id } = await c.call('t.room.send', { room_id: r4, type: 't.room.encrypted', txn_id: txn(), content });
    const ev = await c.call('t.room.event', { room_id: r4, event_id });
    assert.equal((await lc.decrypt(ev)).content.body, 'ephemeral key');
    await new Promise((r) => setTimeout(r, 160));
    // Running the periodic pruner MUST tombstone (not delete) the session so
    // decrypt() cannot re-stamp it as fresh and backup export still excludes it (H6).
    lc.pruneExpiredSessions();
    await assert.rejects(lc.decrypt(ev), /expired past retention/);
    const exported = await lc.exportNewRoomKeys(new Set());
    assert.equal(exported.ids.length, 0, 'expired session was still exported for backup');
    c.close();
  });

  await test('one-time key exhaustion is throttled per requester and target device', async () => {
    const attacker = await user('heidi');
    const victim = await user('ivan');
    const { room_id: r5 } = await victim.c.call('t.room.create', {});
    await victim.c.call('t.room.invite', { room_id: r5, user_id: attacker.id });
    await attacker.c.call('t.room.join', { room_id: r5 });
    const q = await attacker.c.call('t.keys.query', { device_keys: { [victim.id]: [] } });
    const devId = Object.keys(q.device_keys[victim.id])[0];
    let limited = false;
    for (let i = 0; i < 8; i++) {
      const r = await attacker.c.request('t.keys.claim', { one_time_keys: { [victim.id]: { [devId]: 'signed_curve25519' } } });
      if (!r.ok && r.error?.errcode === 'T_LIMIT_EXCEEDED') { limited = true; break; }
    }
    assert.equal(limited, true, 'attacker could drain one-time keys without hitting throttle');
    attacker.c.close();
    victim.c.close();
  });

  await test('forged device signatures on own master key are rejected by the server', async () => {
    const q = await alice.c.call('t.keys.query', { device_keys: { [alice.id]: [] } });
    const master = structuredClone(q.master_keys[alice.id]);
    const keyId = Object.keys(master.keys)[0].slice('ed25519:'.length);
    master.signatures = { [alice.id]: { 'ed25519:FAKEDEV': Buffer.alloc(64, 9).toString('base64').replace(/=+$/, '') } };
    const r = await alice.c.call('t.keys.signatures.upload', { [alice.id]: { [keyId]: master } });
    assert.ok(r.failures[alice.id]?.[keyId], 'forged device signature on master key was accepted');
  });

  server.kill('SIGTERM');
  for (const [status, name, msg] of results) console.log(`${status}  ${name}${msg ? `\n      ${msg.split('\n').slice(0, 4).join('\n      ')}` : ''}`);
  const failed = results.filter((r) => r[0] === 'FAIL').length;
  console.log(`\n${results.length - failed}/${results.length} passed`);
  process.exit(failed ? 1 : 0);
}

main().catch((e) => { console.error(e); process.exit(1); });