File size: 45,566 Bytes
b855ced
 
 
 
 
 
 
 
 
 
cce9364
 
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
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
// End-to-end smoke test: starts the server and drives it over real WebSockets.
// Run with `npm test`.

import { spawn, spawnSync } from 'node:child_process';
import { mkdtempSync, rmSync, readdirSync, cpSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import WS from 'ws';
import { readFileSync as readFile } from 'node:fs';
import { withUrl } from './test-client.js';
import { randomBytes, generateKeyPairSync } from 'node:crypto';
import { signWith } from './events.js';
import assert from 'node:assert/strict';

const PORT = 18000 + Math.floor(Math.random() * 1000);
const URL_ = `ws://127.0.0.1:${PORT}/_taper/gateway/v1`;

const Client = withUrl(URL_);

const encrypted = (text) => ({
  algorithm: 't.megolm.v1.aes-sha2',
  ciphertext: Buffer.from(text).toString('base64'), // stand-in for a real Megolm message
  session_id: 'test-session',
  binding: randomBytes(16).toString('base64url'),
});

const txn = () => randomBytes(8).toString('hex');

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));

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

  let alice, bob, aliceAuth, bobAuth, room_id, bobSession, lastSeq;

  await test('hello frame on connect', async () => {
    alice = await Client.connect();
    assert.equal(alice.hello.body.room_version, '13');
    assert.equal(alice.hello.body.heartbeat_interval_ms > 0, true);
  });

  await test('each connection gets its own heartbeat interval', async () => {
    const others = await Promise.all([Client.connect(), Client.connect(), Client.connect()]);
    const intervals = [alice, ...others].map((c) => c.hello.body.heartbeat_interval_ms);
    for (const ms of intervals) assert.ok(ms >= 24_000 && ms <= 36_000, `interval ${ms} is outside 30 s ± 20%`);
    assert.ok(new Set(intervals).size > 1, 'every connection got the same interval');
    await Promise.all(others.map((c) => c.close()));
  });

  await test('register over the socket before identify', async () => {
    aliceAuth = await alice.register('alice', 'correct horse');
    assert.equal(aliceAuth.user_id, '@alice:localhost');
    await assert.rejects(alice.register('alice', 'whatever123'), /T_USER_IN_USE/);
  });

  await test('the password never crosses the socket (OPAQUE)', async () => {
    assert.ok(alice.sent.length > 0);
    for (const text of alice.sent) assert.ok(!text.includes('correct horse') && !text.includes('whatever123'), 'a frame carried the password');
    assert.equal((await alice.request('t.register', { username: 'x', password: 'plaintext!' })).error?.errcode, 'T_UNRECOGNIZED');
    assert.equal((await alice.request('t.login', { username: 'alice', password: 'correct horse' })).error?.errcode, 'T_UNRECOGNIZED');
  });

  await test('authenticated methods refused before identify', async () => {
    const r = await alice.request('t.room.create', {});
    assert.equal(r.error.errcode, 'T_MISSING_TOKEN');
  });

  await test('identify returns ready', async () => {
    const ready = await alice.identify(aliceAuth.access_token);
    assert.equal(ready.user_id, '@alice:localhost');
    assert.deepEqual(ready.rooms, { joined: [], invited: [] });
  });

  await test('heartbeat is acked and noop cover traffic is accepted', async () => {
    alice.send({ op: 'heartbeat' });
    await alice.next((f) => f.op === 'heartbeat_ack');
    alice.send({ op: 'noop' });
    // Still connected and responsive after noop cover traffic.
    assert.equal((await alice.call('t.whoami', {})).user_id, '@alice:localhost');
  });

  await test('login with wrong password fails, right one works', async () => {
    bob = await Client.connect();
    await bob.register('bob', 'hunter2hunter2');
    await assert.rejects(bob.login('bob', 'nope-nope'), /Invalid username or password/);
    bobAuth = await bob.login('bob', 'hunter2hunter2');
    bobSession = (await bob.identify(bobAuth.access_token)).session_id;
  });

  await test('OPAQUE: unknown users look like real ones, and forged or malformed messages fail', async () => {
    const c = await Client.connect();
    const { client: oc } = await import('../client/node_modules/@serenity-kit/opaque/esm/index.js');
    const ke1 = oc.startLogin({ password: 'anything' }).startLoginRequest;
    const real = await c.call('t.opaque.login.start', { username: 'bob', ke1 });
    const fake = await c.call('t.opaque.login.start', { username: 'nobody-here', ke1 });
    assert.equal(Buffer.from(fake.ke2, 'base64url').length, Buffer.from(real.ke2, 'base64url').length);
    await assert.rejects(c.login('nobody-here', 'whatever-pass'), /Invalid username or password/);
    // A forged KE3 never gets a token, for a real or a fake record.
    for (const { login_id } of [real, fake]) {
      const r = await c.request('t.opaque.login.finish', { login_id, ke3: Buffer.alloc(64, 7).toString('base64url') });
      assert.equal(r.error?.errcode, 'T_FORBIDDEN');
    }
    // Flows are single use.
    assert.equal((await c.request('t.opaque.login.finish', { login_id: real.login_id, ke3: Buffer.alloc(64).toString('base64url') })).error?.errcode, 'T_FORBIDDEN');
    // Messages of the wrong size never reach the library.
    for (const bad of [Buffer.alloc(95), Buffer.alloc(97), 'not base64!']) {
      const r = await c.request('t.opaque.login.start', { username: 'bob', ke1: typeof bad === 'string' ? bad : bad.toString('base64url') });
      assert.equal(r.error?.errcode, 'T_INVALID_PARAM');
    }
    await c.close();
  });

  await test('OPAQUE: logins that never finish count as failures', async () => {
    const c = await Client.connect();
    const { client: oc } = await import('../client/node_modules/@serenity-kit/opaque/esm/index.js');
    const ke1 = () => oc.startLogin({ password: 'guess' }).startLoginRequest;
    // The earlier tests already started one unfinished login for this name.
    let r;
    for (let i = 0; i < 6 && !r?.error; i++) r = await c.request('t.opaque.login.start', { username: 'nobody-here', ke1: ke1() });
    assert.equal(r.error?.errcode, 'T_CHALLENGE_REQUIRED');
    // Other accounts are unaffected.
    assert.ok((await c.request('t.opaque.login.start', { username: 'alice', ke1: ke1() })).ok);
    await c.close();
  });

  await test('create room (v13, encrypted, joined-only history)', async () => {
    ({ room_id } = await alice.call('t.room.create', {}));
    assert.match(room_id, /^!/);
    const { state } = await alice.call('t.room.state', { room_id });
    const get = (t) => state.find((e) => e.type === t)?.content;
    assert.equal(get('t.room.create').room_version, '13');
    assert.equal(get('t.room.encryption').algorithm, 't.megolm.v1.aes-sha2');
    assert.equal(get('t.room.history_visibility').history_visibility, 'joined');
  });

  await test('history before joining is not visible', async () => {
    await alice.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content: encrypted('before bob') });
  });

  await test('invite is dispatched to invitee; invitee can join', async () => {
    await alice.call('t.room.invite', { room_id, user_id: '@bob:localhost' });
    const inv = await bob.next((f) => f.type === 't.room.invite');
    assert.equal(inv.body.room_id, room_id);
    await bob.call('t.room.join', { room_id });
    const { chunk } = await bob.call('t.room.messages', { room_id });
    assert.equal(chunk.some((e) => e.type === 't.room.encrypted'), false, 'bob saw pre-join history');
  });

  await test('encrypted message is dispatched live with expires_ts', async () => {
    const content = encrypted('hi bob');
    const { event_id } = await alice.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content });
    const d = await bob.next((f) => f.type === 't.room.event' && f.body.event.event_id === event_id);
    assert.equal(d.body.event.content.ciphertext, content.ciphertext);
    assert.equal(d.body.event.unsigned.expires_ts - d.body.event.origin_server_ts, 1_814_400_000);
    lastSeq = d.seq;
  });

  await test('plaintext message events are rejected', async () => {
    const r = await alice.request('t.room.send', { room_id, type: 't.room.message', txn_id: txn(), content: { msgtype: 't.text', body: 'plaintext' } });
    assert.equal(r.error.errcode, 'T_FORBIDDEN');
  });

  await test('encrypted events without a 128-bit binding are rejected', async () => {
    const r = await alice.request('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content: { ...encrypted('x'), binding: 'short' } });
    assert.equal(r.error.errcode, 'T_INVALID_PARAM');
  });

  await test('redaction strips content but keeps binding', async () => {
    const content = encrypted('to be redacted');
    const { event_id } = await alice.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content });
    await alice.call('t.room.send', { room_id, type: 't.room.redaction', txn_id: txn(), content: { redacts: event_id, reason: 'dropped' } });
    const ev = await alice.call('t.room.event', { room_id, event_id });
    assert.deepEqual(ev.content, { binding: content.binding });
    assert.equal(ev.event_id, event_id);
  });

  await test('redaction reasons are stripped', async () => {
    const { chunk } = await alice.call('t.room.messages', { room_id });
    const red = chunk.filter((e) => e.type === 't.room.redaction').at(-1);
    assert.deepEqual(Object.keys(red.content), ['redacts']);
  });

  await test('redacting an original also redacts its edits, even late ones', async () => {
    const original = await alice.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content: encrypted('v1') });
    const edit = (text) => ({ ...encrypted(text), 't.relates_to': { rel_type: 't.replace', event_id: original.event_id } });
    const early = await alice.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content: edit('v2') });
    await alice.call('t.room.send', { room_id, type: 't.room.redaction', txn_id: txn(), content: { redacts: original.event_id } });
    const late = await alice.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content: edit('v3') });
    for (const { event_id } of [original, early, late]) {
      const ev = await alice.call('t.room.event', { room_id, event_id });
      assert.deepEqual(Object.keys(ev.content), ['binding'], `${event_id} still has content`);
      assert.ok(ev.unsigned.redacted_because);
    }
  });

  await test('txn_id makes sends idempotent', async () => {
    const t = txn();
    const a = await alice.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: t, content: encrypted('once') });
    const b = await alice.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: t, content: encrypted('once') });
    assert.equal(a.event_id, b.event_id);
  });

  await test('resume replays missed dispatches', async () => {
    // Drain bob's queue so lastSeq is current, then drop his connection.
    while (bob.frames.length) { const f = bob.frames.shift(); if (f.seq) lastSeq = f.seq; }
    await bob.close();
    const { event_id } = await alice.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content: encrypted('while you were out') });
    bob = await Client.connect();
    bob.send({ op: 'resume', body: { access_token: bobAuth.access_token, session_id: bobSession, seq: lastSeq } });
    const d = await bob.next((f) => f.type === 't.room.event' && f.body.event.event_id === event_id);
    assert.equal(d.seq > lastSeq, true);
    await bob.next((f) => f.op === 'resumed');
  });

  await test('resume with unknown session closes with 4007', async () => {
    const c = await Client.connect();
    c.send({ op: 'resume', body: { access_token: bobAuth.access_token, session_id: 'nope', seq: 0 } });
    assert.equal((await c.closed).code, 4007);
  });

  await test('rate limit returns retry_after_ms', async () => {
    const rs = await Promise.all(Array.from({ length: 40 }, () => alice.request('t.whoami')));
    const limited = rs.find((r) => !r.ok);
    assert.equal(limited?.error.errcode, 'T_LIMIT_EXCEEDED');
    assert.equal(limited.error.retry_after_ms > 0, true);
  });

  await test('garbage frame closes with 4002', async () => {
    const c = await Client.connect();
    c.ws.send('not json');
    assert.equal((await c.closed).code, 4002);
  });

  await test('the web client is served under the gateway path, and nothing else from its directory', async () => {
    const base = `http://127.0.0.1:${PORT}/_taper/gateway/v1`;
    const page = await fetch(`${base}/`);
    assert.equal(page.status, 200);
    assert.equal(page.headers.get('referrer-policy'), 'no-referrer');
    assert.match(page.headers.get('content-security-policy'), /frame-ancestors 'none'/);
    assert.match(await page.text(), /<meta name="taper-gateway" content="same-origin">/);
    assert.equal((await fetch(`${base}/node_modules/@matrix-org/matrix-sdk-crypto-wasm/pkg/matrix_sdk_crypto_wasm_bg.wasm`)).headers.get('content-type'), 'application/wasm');
    for (const path of ['package.json', 'test-browser.mjs', 'README.md', 'node_modules/@serenity-kit/opaque/package.json', '..%2fserver%2findex.js', '../server/index.js']) {
      assert.equal((await fetch(`${base}/${path}`)).status, 404, path);
    }
    // Without the path, there is no client: the root is the cover site.
    assert.doesNotMatch(await (await fetch(`http://127.0.0.1:${PORT}/`)).text(), /taper/i);
  });

  await test('everything except the gateway looks like an ordinary website', async () => {
    const home = await fetch(`http://127.0.0.1:${PORT}/`);
    assert.equal(home.status, 200);
    assert.equal(home.headers.get('server'), null);
    const missing = await fetch(`http://127.0.0.1:${PORT}/_taper/client/v3/sync`);
    assert.equal(missing.status, 404);
    // Without federation peers there are no server keys to fetch.
    assert.equal((await fetch(`http://127.0.0.1:${PORT}/_taper/key/v2/server`)).status, 404);
    for (const body of [await home.text(), await missing.text()]) assert.doesNotMatch(body, /taper|websocket|gateway/i);
    // A WebSocket handshake on any other path gets the same 404 page.
    const ws = new WS(`ws://127.0.0.1:${PORT}/not-the-gateway`);
    const status = await new Promise((resolve) => ws.once('unexpected-response', (_req, res) => resolve(res.statusCode)));
    assert.equal(status, 404);
  });

  server.kill('SIGTERM');
  await new Promise((r) => server.once('exit', r));

  await test('expired message events are purged (1.5s retention server)', async () => {
    const port = PORT + 1;
    const short = spawn(process.execPath, ['index.js'], { env: { ...process.env, PORT: String(port), TAPER_RETENTION_MS: '1500', TAPER_REGISTER_POW_BITS: '8' }, stdio: ['ignore', 'pipe', 'inherit'] });
    await new Promise((resolve) => short.stdout.once('data', resolve));
    try {
      const c = await Client.connectTo(`ws://127.0.0.1:${port}/_taper/gateway/v1`);
      const auth = await c.register('carol', 'carolcarol');
      await c.identify(auth.access_token);
      const { room_id: rid } = await c.call('t.room.create', {});
      const { event_id } = await c.call('t.room.send', { room_id: rid, type: 't.room.encrypted', txn_id: txn(), content: encrypted('ephemeral') });
      await new Promise((r) => setTimeout(r, 3500));
      const r = await c.request('t.room.event', { room_id: rid, event_id });
      assert.equal(r.error?.errcode, 'T_EXPIRED');
      const { chunk } = await c.call('t.room.messages', { room_id: rid });
      assert.equal(chunk.some((e) => e.type === 't.room.encrypted'), false);
      const { state } = await c.call('t.room.state', { room_id: rid });
      assert.equal(state.some((e) => e.type === 't.room.create'), true, 'current state should survive');
      await c.close();
    } finally {
      short.kill('SIGTERM');
    }
  });

  // Spawn a server with extra env; resolves once it prints its banner.
  const startServer = async (env) => {
    const proc = spawn(process.execPath, ['index.js'], { env: { ...process.env, TAPER_REGISTER_POW_BITS: '8', ...env }, stdio: ['ignore', 'pipe', 'pipe'] });
    await new Promise((resolve, reject) => {
      proc.stdout.on('data', (d) => { if (String(d).includes('Taper gateway on')) resolve(); });
      proc.once('exit', (code) => reject(new Error(`server exited with ${code}`)));
    });
    return proc;
  };

  await test('refuses plaintext on a non-loopback address', async () => {
    const r = spawnSync(process.execPath, ['index.js'], { env: { ...process.env, PORT: String(PORT + 2), HOST: '0.0.0.0' }, encoding: 'utf8', timeout: 5000 });
    assert.equal(r.status, 1);
    assert.match(r.stderr, /without TLS/);
  });

  await test('TLS 1.3 negotiates hybrid post-quantum X25519MLKEM768', async () => {
    const dir = mkdtempSync(join(tmpdir(), 'taper-tls-'));
    const cert = join(dir, 'cert.pem');
    const key = join(dir, 'key.pem');
    const gen = spawnSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:P-256', '-nodes', '-days', '1',
      '-subj', '/CN=localhost', '-addext', 'subjectAltName=IP:127.0.0.1', '-keyout', key, '-out', cert], { encoding: 'utf8' });
    assert.equal(gen.status, 0, gen.stderr);
    const port = PORT + 3;
    const tlsEnv = { ...process.env, PORT: String(port), TAPER_TLS_CERT: cert, TAPER_TLS_KEY: key };
    const refused = spawnSync(process.execPath, ['index.js'], { env: tlsEnv, encoding: 'utf8', timeout: 5000 });
    assert.equal(refused.status, 1, 'with TLS, a default gateway path must be refused');
    assert.match(refused.stderr, /TAPER_GATEWAY_PATH/);
    const secret = `/${randomBytes(18).toString('base64url')}`;
    const srv = await startServer({ PORT: String(port), TAPER_TLS_CERT: cert, TAPER_TLS_KEY: key, TAPER_GATEWAY_PATH: secret });
    try {
      // Independent check with OpenSSL: the negotiated group must be the hybrid one.
      const probe = spawnSync('openssl', ['s_client', '-connect', `127.0.0.1:${port}`, '-tls1_3', '-groups', 'X25519MLKEM768:X25519', '-CAfile', cert],
        { input: '', encoding: 'utf8', timeout: 10_000 });
      assert.match(probe.stdout + probe.stderr, /group: X25519MLKEM768/);
      // TLS 1.2 must be refused.
      const old = spawnSync('openssl', ['s_client', '-connect', `127.0.0.1:${port}`, '-tls1_2', '-CAfile', cert], { input: '', encoding: 'utf8', timeout: 10_000 });
      assert.match(old.stdout, /Cipher is \(NONE\)/, 'TLS 1.2 handshake should not complete');
      assert.notEqual(old.status, 0);
      // And the gateway works over wss://.
      // Discovery is off by default with TLS, and the old fixed path is gone.
      const https = await import('node:https');
      const get = (path) => new Promise((resolve, reject) => https.get({ host: '127.0.0.1', port, path, ca: readFile(cert) }, (res) => { res.resume(); resolve(res.statusCode); }).on('error', reject));
      assert.equal(await get('/.well-known/taper/client'), 404);
      assert.equal(await get('/'), 200);
      const fixedPath = new WS(`wss://127.0.0.1:${port}/_taper/gateway/v1`, { ca: readFile(cert) });
      assert.equal(await new Promise((resolve) => fixedPath.once('unexpected-response', (_q, res) => resolve(res.statusCode))), 404);
      const ws = new WS(`wss://127.0.0.1:${port}${secret}`, { ca: readFile(cert) });
      const hello = await new Promise((resolve, reject) => { ws.once('message', (d) => resolve(JSON.parse(d))); ws.once('error', reject); });
      assert.equal(hello.op, 'hello');
      ws.close();
      // A renewed certificate is picked up on SIGHUP, without a restart.
      const fingerprint = () => new Promise((resolve, reject) => {
        const s = https.request({ host: '127.0.0.1', port, path: '/', rejectUnauthorized: false, agent: false }, (res) => { resolve(res.socket.getPeerCertificate().fingerprint256); res.resume(); });
        s.on('error', reject); s.end();
      });
      const before = await fingerprint();
      const renew = spawnSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:P-256', '-nodes', '-days', '1',
        '-subj', '/CN=localhost', '-addext', 'subjectAltName=IP:127.0.0.1', '-keyout', key, '-out', cert], { encoding: 'utf8' });
      assert.equal(renew.status, 0, renew.stderr);
      const reloaded = new Promise((resolve) => srv.stdout.on('data', (d) => { if (String(d).includes('Reloaded TLS certificate')) resolve(); }));
      srv.kill('SIGHUP');
      await reloaded;
      assert.notEqual(await fingerprint(), before, 'the certificate did not change');
      assert.equal(srv.exitCode, null, 'the server must keep running');
    } finally {
      srv.kill('SIGTERM');
      rmSync(dir, { recursive: true, force: true });
    }
  });

  await test('registration requires a proof-of-work challenge', async () => {
    const port = PORT + 7;
    const srv = await startServer({ PORT: String(port) });
    const c = await Client.connectTo(`ws://127.0.0.1:${port}/_taper/gateway/v1`);
    const { client: oc } = await import('../client/node_modules/@serenity-kit/opaque/esm/index.js');
    const startBody = { username: 'powtest', registration_request: oc.startRegistration({ password: 'powtest-password' }).registrationRequest };
    const first = await c.request('t.opaque.register.start', startBody);
    assert.equal(first.error?.errcode, 'T_CHALLENGE_REQUIRED');
    assert.equal(first.error.challenge.type, 't.pow.sha256');
    const wrong = await c.request('t.opaque.register.start', startBody,
      { challenge_response: { nonce: first.error.challenge.nonce, solution: 'nope' } });
    assert.equal(wrong.error?.errcode, 'T_CHALLENGE_REQUIRED', 'a wrong solution must not pass');
    const ok = await c.register('powtest', 'powtest-password');
    assert.match(ok.user_id, /^@powtest:/);
    await c.close();
    srv.kill('SIGTERM');
  });

  await test('every text frame the server sends is padded to its Padme bucket', async () => {
    const { padme } = await import('./padding.js');
    const sizes = [...alice.sizes.text, ...bob.sizes.text];
    assert.ok(sizes.length > 20);
    for (const n of sizes) assert.equal(n, padme(n), `frame of ${n} bytes is not padded`);
    assert.ok(Math.min(...sizes) >= 256);
    // Different lengths land in the same bucket.
    assert.equal(padme(260), padme(257));
    assert.equal(padme(5000), 5120);
  });

  await test('a scraper paging through history runs out of budget', async () => {
    const port = PORT + 5;
    const srv = await startServer({ PORT: String(port), TAPER_BUDGET_SCALE: '0.01' });
    try {
      const c = await Client.connectTo(`ws://127.0.0.1:${port}/_taper/gateway/v1`);
      const auth = await c.register('scraper', 'scraper-password');
      c.send({ op: 'identify', body: { access_token: auth.access_token } });
      await c.next((f) => f.op === 'ready');
      const { room_id: rid } = await c.call('t.room.create', {});
      // A new account's history budget here is 20000 * 0.01 * 0.1 = 20 events.
      assert.ok((await c.request('t.room.messages', { room_id: rid, limit: 10 })).ok);
      const r2 = await c.request('t.room.messages', { room_id: rid, limit: 10 });
      assert.ok(r2.ok || r2.error.errcode === 'T_CHALLENGE_REQUIRED');
      const r3 = await c.request('t.room.messages', { room_id: rid, limit: 10 });
      assert.ok(['T_LIMIT_EXCEEDED', 'T_CHALLENGE_REQUIRED'].includes(r3.error?.errcode), JSON.stringify(r3));
      let last;
      for (let i = 0; i < 3; i++) last = await c.request('t.room.messages', { room_id: rid, limit: 10 });
      assert.equal(last.error?.errcode, 'T_LIMIT_EXCEEDED');
      assert.ok(last.error.retry_after_ms > 3_600_000, 'retry_after_ms should point at the end of the day');
      await c.close();
    } finally {
      srv.kill('SIGTERM');
    }
  });

  await test('touching canaries raises the tier until every read needs a challenge', async () => {
    const port = PORT + 6;
    const srv = await startServer({ PORT: String(port), TAPER_CANARIES: '!canary:localhost' });
    try {
      const c = await Client.connectTo(`ws://127.0.0.1:${port}/_taper/gateway/v1`);
      const auth = await c.register('prober', 'prober-password');
      c.send({ op: 'identify', body: { access_token: auth.access_token } });
      await c.next((f) => f.op === 'ready');
      const { room_id: rid } = await c.call('t.room.create', {});
      const first = await c.request('t.room.join', { room_id: '!canary:localhost' });
      assert.equal(first.error?.errcode, 'T_NOT_FOUND', 'the canary itself must look like nothing');
      const second = await c.request('t.room.join', { room_id: '!canary:localhost' });
      assert.equal(second.error?.errcode, 'T_CHALLENGE_REQUIRED');
      const read = await c.request('t.room.state', { room_id: rid });
      assert.equal(read.error?.errcode, 'T_CHALLENGE_REQUIRED', 'high tier: every budgeted action needs a challenge');
      assert.equal(read.error.challenge.difficulty, 20);
      await c.close();
    } finally {
      srv.kill('SIGTERM');
    }
  });

  await test('data survives a restart and is encrypted at rest', async () => {
    const base = mkdtempSync(join(tmpdir(), 'taper-store-'));
    const env = { TAPER_DATA_DIR: join(base, 'data'), TAPER_KEY_DIR: join(base, 'keys') };
    const marker = `persist-${randomBytes(8).toString('hex')}`;
    const port = PORT + 8;
    let srv = await startServer({ PORT: String(port), ...env });
    try {
      let c = await Client.connectTo(`ws://127.0.0.1:${port}/_taper/gateway/v1`);
      const auth = await c.register('keeper', 'keeper-password');
      c.send({ op: 'identify', body: { access_token: auth.access_token } });
      await c.next((f) => f.op === 'ready');
      const { room_id: rid } = await c.call('t.room.create', {});
      const content = { ...encrypted('x'), ciphertext: Buffer.from(marker).toString('base64') };
      const { event_id } = await c.call('t.room.send', { room_id: rid, type: 't.room.encrypted', txn_id: txn(), content });
      await c.close();
      srv.kill('SIGTERM');
      await new Promise((r) => srv.once('exit', r));

      // Nothing in the data directory contains the event's content.
      const needle = Buffer.from(content.ciphertext);
      for (const f of readdirSync(env.TAPER_DATA_DIR)) {
        assert.equal(readFile(join(env.TAPER_DATA_DIR, f)).includes(needle), false, `${f} holds plaintext event content`);
      }

      srv = await startServer({ PORT: String(port), ...env });
      c = await Client.connectTo(`ws://127.0.0.1:${port}/_taper/gateway/v1`);
      const again = await c.login('keeper', 'keeper-password');
      c.send({ op: 'identify', body: { access_token: again.access_token } });
      const ready = await c.next((f) => f.op === 'ready');
      assert.equal(ready.body.rooms.joined.length, 1, 'room not restored');
      const ev = await c.call('t.room.event', { room_id: rid, event_id });
      assert.equal(ev.content.ciphertext, content.ciphertext);
      await c.close();
    } finally {
      srv.kill('SIGTERM');
      rmSync(base, { recursive: true, force: true });
    }
  });

  await test('crypto-shredding makes expired data unreadable, even in a backup', async () => {
    const base = mkdtempSync(join(tmpdir(), 'taper-shred-'));
    const env = { TAPER_DATA_DIR: join(base, 'data'), TAPER_KEY_DIR: join(base, 'keys'), TAPER_RETENTION_MS: '1500', TAPER_KEY_PERIOD_MS: '500' };
    const port = PORT + 9;
    const srv = await startServer({ PORT: String(port), ...env });
    try {
      const c = await Client.connectTo(`ws://127.0.0.1:${port}/_taper/gateway/v1`);
      const auth = await c.register('shredder', 'shredder-password');
      c.send({ op: 'identify', body: { access_token: auth.access_token } });
      await c.next((f) => f.op === 'ready');
      const { room_id: rid } = await c.call('t.room.create', {});
      const { event_id } = await c.call('t.room.send', { room_id: rid, type: 't.room.encrypted', txn_id: txn(), content: encrypted('ephemeral') });
      // Take a "backup" while the event is still live.
      const backup = join(base, 'backup');
      cpSync(env.TAPER_DATA_DIR, backup, { recursive: true });
      const keysBefore = readdirSync(env.TAPER_KEY_DIR);
      await new Promise((r) => setTimeout(r, 5000));
      const keysAfter = readdirSync(env.TAPER_KEY_DIR);
      assert.ok(keysBefore.some((k) => !keysAfter.includes(k)), 'no period key was destroyed');

      // Open the backup with the remaining keys: the message can't be read.
      const { Store } = await import('./store.js');
      const restored = new Store({ dataDir: backup, keyDir: env.TAPER_KEY_DIR, retentionMs: 1500, periodMs: 500 });
      const readable = restored.unsealAll('events').map(([id]) => id);
      restored.close();
      assert.equal(readable.includes(event_id), false, 'the backup still decrypts an expired message');
      await c.close();
    } finally {
      srv.kill('SIGTERM');
      rmSync(base, { recursive: true, force: true });
    }
  });

  await test('the server refuses to keep encryption keys inside its data directory', async () => {
    const base = mkdtempSync(join(tmpdir(), 'taper-keys-'));
    const r = spawnSync(process.execPath, ['index.js'], {
      env: { ...process.env, PORT: String(PORT + 10), TAPER_DATA_DIR: base, TAPER_KEY_DIR: join(base, 'keys') }, encoding: 'utf8', timeout: 5000,
    });
    rmSync(base, { recursive: true, force: true });
    assert.notEqual(r.status, 0);
    assert.match(r.stderr, /must not be the data directory or inside it/);
  });

  await test('tokens that expired while the server was stopped are removed at the next start', async () => {
    const base = mkdtempSync(join(tmpdir(), 'taper-tokens-'));
    const env = { PORT: String(PORT + 12), TAPER_TOKEN_TTL_MS: '800', TAPER_DATA_DIR: join(base, 'data'), TAPER_KEY_DIR: join(base, 'keys') };
    const tokenRows = async () => {
      const { DatabaseSync } = await import('node:sqlite');
      const db = new DatabaseSync(join(env.TAPER_DATA_DIR, 'taper.db'));
      const n = db.prepare("SELECT count(*) AS n FROM records WHERE ns = 'tokens'").get().n;
      db.close();
      return n;
    };
    try {
      const first = await startServer(env);
      const c = await Client.connectTo(`ws://127.0.0.1:${env.PORT}/_taper/gateway/v1`);
      await c.register('erin', 'erin-erin-erin');
      first.kill('SIGTERM');
      await new Promise((r) => first.once('exit', r));
      assert.equal(await tokenRows(), 1);
      await new Promise((r) => setTimeout(r, 1000));
      const second = await startServer(env);
      second.kill('SIGTERM');
      await new Promise((r) => second.once('exit', r));
      assert.equal(await tokenRows(), 0);
    } finally {
      rmSync(base, { recursive: true, force: true });
    }
  });

  await test('a token that is in use does not lapse, up to its absolute limit', async () => {
    const port = PORT + 13;
    const srv = await startServer({ PORT: String(port), TAPER_TOKEN_TTL_MS: '2000', TAPER_TOKEN_MAX_MS: '5000' });
    try {
      const url = `ws://127.0.0.1:${port}/_taper/gateway/v1`;
      const c = await Client.connectTo(url);
      const auth = await c.register('fay', 'fayfayfayfay');
      for (let i = 0; i < 3; i++) {
        await new Promise((r) => setTimeout(r, 1000));
        const cc = await Client.connectTo(url);
        assert.equal((await cc.identify(auth.access_token)).user_id, '@fay:localhost', `lapsed at ${i + 1}s`);
        await cc.close();
      }
      // 3 s of use kept it alive past its first 2 s; the 5 s limit from issue ends it however much it's used.
      await new Promise((r) => setTimeout(r, 2200));
      const last = await Client.connectTo(url);
      last.send({ op: 'identify', body: { access_token: auth.access_token } });
      assert.equal((await last.closed).code, 4004);
    } finally {
      srv.kill('SIGTERM');
    }
  });

  await test('a database written by a newer format is refused, not guessed at', async () => {
    const base = mkdtempSync(join(tmpdir(), 'taper-schema-'));
    const env = { ...process.env, PORT: String(PORT + 11), TAPER_DATA_DIR: join(base, 'data'), TAPER_KEY_DIR: join(base, 'keys') };
    try {
      // A first run creates the database at the current format.
      const first = await startServer({ PORT: env.PORT, TAPER_DATA_DIR: env.TAPER_DATA_DIR, TAPER_KEY_DIR: env.TAPER_KEY_DIR });
      first.kill('SIGTERM');
      await new Promise((r) => first.once('exit', r));
      const { DatabaseSync } = await import('node:sqlite');
      const db = new DatabaseSync(join(env.TAPER_DATA_DIR, 'taper.db'));
      assert.equal(db.prepare('PRAGMA user_version').get().user_version, 1);
      db.exec('PRAGMA user_version = 99');
      db.close();
      const r = spawnSync(process.execPath, ['index.js'], { env, encoding: 'utf8', timeout: 5000 });
      assert.notEqual(r.status, 0);
      assert.match(r.stderr, /newer Taper \(format 99\)/);
    } finally {
      rmSync(base, { recursive: true, force: true });
    }
  });

  await test('expired leave membership state and empty rooms are purged after retention', async () => {
    const port = PORT + 14;
    const srv = await startServer({ PORT: String(port), TAPER_RETENTION_MS: '1200' });
    try {
      const url = `ws://127.0.0.1:${port}/_taper/gateway/v1`;
      const a = await Client.connectTo(url);
      const aAuth = await a.register('alma', 'almaalmaalma');
      await a.identify(aAuth.access_token);
      const b = await Client.connectTo(url);
      const bAuth = await b.register('bert', 'bertbertbert');
      await b.identify(bAuth.access_token);
      const { room_id: r } = await a.call('t.room.create', {});
      await a.call('t.room.invite', { room_id: r, user_id: bAuth.user_id });
      await b.call('t.room.join', { room_id: r });
      await b.call('t.room.leave', { room_id: r });
      // Wait for retention + purge cycle (runs every RETENTION_MS = 1.2s).
      await new Promise((res) => setTimeout(res, 2800));
      const { state } = await a.call('t.room.state', { room_id: r });
      assert.equal(state.some((e) => e.type === 't.room.member' && e.state_key === bAuth.user_id), false, 'expired leave event stayed in room state');
      // Now Alma leaves too -> empty room is deleted after retention.
      await a.call('t.room.leave', { room_id: r });
      await new Promise((res) => setTimeout(res, 2800));
      const gone = await a.request('t.room.state', { room_id: r });
      assert.equal(gone.error?.errcode, 'T_NOT_FOUND', 'empty room was not purged');
      await a.close();
      await b.close();
    } finally {
      srv.kill('SIGTERM');
    }
  });

  await test('access tokens expire', async () => {
    const port = PORT + 4;
    const srv = await startServer({ PORT: String(port), TAPER_TOKEN_TTL_MS: '1000' });
    try {
      const c = await Client.connectTo(`ws://127.0.0.1:${port}/_taper/gateway/v1`);
      const auth = await c.register('dave', 'davedavedave');
      assert.equal(auth.expires_in_ms, 1000);
      await new Promise((r) => setTimeout(r, 1500));
      c.send({ op: 'identify', body: { access_token: auth.access_token } });
      assert.equal((await c.closed).code, 4004);
    } finally {
      srv.kill('SIGTERM');
    }
  });

  // ---- Round 2 regressions -------------------------------------------------
  const R2_PORT = PORT + 20;
  const r2Server = await startServer({ PORT: String(R2_PORT) });
  const C2 = withUrl(`ws://127.0.0.1:${R2_PORT}/_taper/gateway/v1`);
  const pair = async (a, b) => {
    const ca = await C2.connect();
    const aa = await ca.register(a, `${a}-password-1`);
    await ca.identify(aa.access_token);
    const cb = await C2.connect();
    const ab = await cb.register(b, `${b}-password-1`);
    await cb.identify(ab.access_token);
    const { room_id: rid } = await ca.call('t.room.create', {});
    return { ca, aa, cb, ab, rid };
  };
  // Signed device keys for a device, as a client would upload them.
  const deviceKeysFor = (user_id, device_id, curve = randomBytes(32).toString('base64').replace(/=+$/, '')) => {
    const { publicKey, privateKey } = generateKeyPairSync('ed25519');
    const ed = Buffer.from(publicKey.export({ format: 'jwk' }).x, 'base64url').toString('base64').replace(/=+$/, '');
    const dk = { user_id, device_id, algorithms: ['t.olm.v1.curve25519-aes-sha2'], keys: { [`ed25519:${device_id}`]: ed, [`curve25519:${device_id}`]: curve } };
    dk.signatures = { [user_id]: { [`ed25519:${device_id}`]: signWith(privateKey, dk) } };
    return { dk, privateKey, sign: (obj) => ({ ...obj, signatures: { [user_id]: { [`ed25519:${device_id}`]: signWith(privateKey, obj) } } }) };
  };

  await test('C-1: a "__proto__" user in t.keys.signatures.upload pollutes nothing', async () => {
    const { ca, rid } = await pair('proto1', 'proto2');
    const polluting = JSON.parse('{"__proto__": {"t.relates_to": 5, "sender_key": 5}}');
    const r = await ca.request('t.keys.signatures.upload', polluting);
    assert.ok(r.ok, JSON.stringify(r));
    // Had Object.prototype gained 't.relates_to', every message would now carry one.
    const { event_id } = await ca.call('t.room.send', { room_id: rid, type: 't.room.encrypted', txn_id: txn(), content: encrypted('clean') });
    const ev = await ca.call('t.room.event', { room_id: rid, event_id });
    assert.equal(Object.hasOwn(ev.content, 't.relates_to'), false);
    assert.equal(Object.hasOwn(ev.content, 'sender_key'), false);
    await ca.close();
  });

  await test('C-4: sockets reset during an HTTP upgrade cannot crash the server', async () => {
    const { connect } = await import('node:net');
    for (let i = 0; i < 20; i++) {
      await new Promise((resolve) => {
        const sock = connect(R2_PORT, '127.0.0.1', () => {
          sock.write(`GET /cover-${i} HTTP/1.1\r\nhost: x\r\nupgrade: websocket\r\nconnection: Upgrade\r\nsec-websocket-key: ${randomBytes(16).toString('base64')}\r\nsec-websocket-version: 13\r\n\r\n`);
          setImmediate(() => { sock.resetAndDestroy(); resolve(); });
        });
        sock.on('error', resolve);
      });
    }
    await new Promise((r) => setTimeout(r, 200));
    const c = await C2.connect();
    assert.equal(c.hello.body.room_version, '13');
    await c.close();
  });

  await test('M-1: t.relates_to carries only rel_type and event_id', async () => {
    const { ca, rid } = await pair('rel1', 'rel2');
    const extra = { ...encrypted('x'), 't.relates_to': { rel_type: 't.replace', event_id: '$e', body: 'plaintext leak' } };
    assert.equal((await ca.request('t.room.send', { room_id: rid, type: 't.room.encrypted', txn_id: txn(), content: extra })).error?.errcode, 'T_INVALID_PARAM');
    // Plaintext state: unknown fields are refused, not stored.
    const leaky = await ca.request('t.room.state.set', { room_id: rid, type: 't.room.join_rules', content: { join_rule: 'invite', topic: 'plaintext' } });
    assert.equal(leaky.error?.errcode, 'T_INVALID_PARAM');
    await ca.close();
  });

  await test('M-4: refused invites all read the same, whatever the reason', async () => {
    const { ca, cb, ab, rid } = await pair('inv1', 'inv2');
    const ghost = await ca.request('t.room.invite', { room_id: rid, user_id: '@nobody-here:localhost' });
    assert.equal(ghost.error?.error, 'Cannot invite user');
    await ca.call('t.room.state.set', { room_id: rid, type: 't.room.join_rules', content: { join_rule: 'public' } });
    await cb.call('t.room.join', { room_id: rid });
    await ca.call('t.room.state.set', { room_id: rid, type: 't.room.power_levels', content: { invite: 50 } });
    // Bob lacks the power to invite: an existing and a missing account look alike.
    const real = await cb.request('t.room.invite', { room_id: rid, user_id: '@alice:localhost' });
    const fake = await cb.request('t.room.invite', { room_id: rid, user_id: '@nobody-here:localhost' });
    assert.deepEqual([real.error?.errcode, real.error?.error], ['T_FORBIDDEN', 'Cannot invite user']);
    assert.deepEqual(fake.error, real.error);
    assert.ok(ab.user_id);
    await ca.close();
    await cb.close();
  });

  await test('L: paging from an event before the join is as unknown as an expired one', async () => {
    const { ca, cb, ab, rid } = await pair('page1', 'page2');
    const { event_id } = await ca.call('t.room.send', { room_id: rid, type: 't.room.encrypted', txn_id: txn(), content: encrypted('before bob') });
    await ca.call('t.room.invite', { room_id: rid, user_id: ab.user_id });
    await cb.call('t.room.join', { room_id: rid });
    assert.equal((await cb.request('t.room.messages', { room_id: rid, before: event_id })).error?.errcode, 'T_EXPIRED');
    await ca.close();
    await cb.close();
  });

  await test('H-6: a signed-in session cannot start logins for another account', async () => {
    const { ca } = await pair('step1', 'step2');
    const opaqueLib = await import('@serenity-kit/opaque');
    await opaqueLib.ready;
    const { startLoginRequest } = opaqueLib.client.startLogin({ password: 'whatever-it-is' });
    const r = await ca.request('t.opaque.login.start', { username: 'step2', ke1: startLoginRequest });
    assert.equal(r.error?.errcode, 'T_FORBIDDEN');
    assert.ok((await ca.request('t.opaque.login.start', { username: 'step1', ke1: startLoginRequest })).ok, 'a step-up for oneself still works');
    await ca.close();
  });

  await test('H-6/L: to-device and one-time-key claims only reach devices that exist', async () => {
    const { ca, cb, ab, rid } = await pair('dev1', 'dev2');
    await ca.call('t.room.invite', { room_id: rid, user_id: ab.user_id });
    await cb.call('t.room.join', { room_id: rid });
    // Claims for made-up devices draw on no quota: never throttled, never answered.
    for (let i = 0; i < 25; i++) {
      const r = await ca.call('t.keys.claim', { one_time_keys: { [ab.user_id]: { NOSUCHDEVICE: 'signed_curve25519' } } });
      assert.deepEqual(r.one_time_keys, {});
    }
    // A made-up device gets no queued message (it would never be read).
    await ca.call('t.to_device.send', { event_type: 't.dummy', txn_id: txn(), messages: { [ab.user_id]: { FAKEDEVICE: { x: 1 } } } });
    const other = await C2.connect();
    other.timeoutMs = 300;
    await ca.close();
    await cb.close();
    await other.close();
  });

  await test('L: a device cannot swap its curve25519 key, and its keys take no extra fields', async () => {
    const c = await C2.connect();
    const auth = await c.register('curve1', 'curve1-password-1');
    await c.identify(auth.access_token);
    const { dk, sign } = deviceKeysFor(auth.user_id, auth.device_id);
    await c.call('t.keys.upload', { device_keys: dk });
    const { signatures: _s, ...unsigned } = dk;
    const swapped = sign({ ...unsigned, keys: { ...dk.keys, [`curve25519:${auth.device_id}`]: randomBytes(32).toString('base64').replace(/=+$/, '') } });
    assert.equal((await c.request('t.keys.upload', { device_keys: swapped })).error?.errcode, 'T_INVALID_PARAM');
    const extra = sign({ ...unsigned, display_name: 'plaintext' });
    assert.equal((await c.request('t.keys.upload', { device_keys: extra })).error?.errcode, 'T_INVALID_PARAM');
    assert.ok((await c.request('t.keys.upload', { device_keys: dk })).ok, 'the same keys again are fine');
    await c.close();
  });

  r2Server.kill('SIGTERM');

  await test('M-2: a token found expired closes every socket bound to it', async () => {
    const port = PORT + 21;
    const srv = await startServer({ PORT: String(port), TAPER_TOKEN_TTL_MS: '1500' });
    try {
      const url = `ws://127.0.0.1:${port}/_taper/gateway/v1`;
      const a = await Client.connectTo(url);
      const auth = await a.register('gus', 'gusgusgusgus');
      await a.identify(auth.access_token);
      const b = await Client.connectTo(url);
      await b.identify(auth.access_token);
      await new Promise((r) => setTimeout(r, 1800));
      a.send({ op: 'request', id: 1, method: 't.whoami', body: {} });
      assert.equal((await a.closed).code, 4004);
      assert.equal((await Promise.race([b.closed, new Promise((r) => setTimeout(() => r({ code: 'still open' }), 2000))])).code, 4004);
    } finally {
      srv.kill('SIGTERM');
    }
  });

  await test('L: placeholder secret paths and bad retention floors are refused at start', async () => {
    const env = { ...process.env, PORT: String(PORT + 22) };
    const placeholder = spawnSync(process.execPath, ['index.js'], { env: { ...env, TAPER_DMS_PATH: '/REPLACE-WITH-A-RANDOM-PATH-0123456789abcdef' }, encoding: 'utf8', timeout: 5000 });
    assert.equal(placeholder.status, 1);
    assert.match(placeholder.stderr, /TAPER_DMS_PATH/);
    const floor = spawnSync(process.execPath, ['index.js'], { env: { ...env, TAPER_MIN_RETENTION_MS: 'soon' }, encoding: 'utf8', timeout: 5000 });
    assert.equal(floor.status, 1);
    assert.match(floor.stderr, /TAPER_MIN_RETENTION_MS/);
  });

  for (const [status, name, msg] of results) console.log(`${status}  ${name}${msg ? `\n      ${msg}` : ''}`);
  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); });