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 | /**
* Golden-vector extractor — run against the TypeScript implementation while it
* was still canon (v1.0.0, HEAD 72065c2), per dev/docs/CLJS.md: "splice the
* real modules into a harness rather than transcribing their logic into a
* generator". Here the real modules ARE `dist/` (tsc output of src/), so this
* script imports them directly and dumps their observable behaviour verbatim;
* the state machines whose members are ES2022 hard-private come in through
* helpers/expose.mjs, which aliases them onto a public bag without touching a
* line of logic.
*
* These fixtures are the contract the ClojureScript port must satisfy. The
* crown jewels are the durable log and the encryption: LogOp payload bytes, the
* HKDF key ladder, and the AES-GCM seal/unseal envelopes — a silent divergence
* there does not fail loudly, it makes a bot's messages undecryptable to every
* deployed browser in the room.
*
* node test/vectors/generate.mjs # writes test/vectors/*.json
*
* Deliberately NOT re-runnable against the CLJS build: it reaches into
* `dist/lib/…` and patches hard-private members that only exist in the tsc
* output. `test/*.test.mjs` is what re-checks the vectors afterwards.
* Kept in the tree as the provenance record for every fixture below.
*/
import { writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { installDetRandom, resetRandom, restoreRandom, hex } from "../helpers/det-random.mjs";
import { loadExposed } from "../helpers/expose.mjs";
import { netScript, relayScript, logScript, chatScript, boardScript } from "../helpers/fakes.mjs";
const OUT = dirname(fileURLToPath(import.meta.url));
const DIST = join(OUT, "..", "..", "dist");
// inside node_modules so the patched copies still resolve bare npm specifiers
// (and so nothing lands in the tracked tree)
const SCRATCH = join(DIST, "..", "node_modules", ".rooms-kit-exposed");
const write = (name, data) => {
writeFileSync(join(OUT, `${name}.json`), `${JSON.stringify(data, null, 2)}\n`);
console.log(`wrote ${name}.json`);
};
const te = new TextEncoder();
const priv = (o, n) => o.__t[n];
/* ------------------------------------------------------------------ crypto -- */
const cryptoMod = await import(join(DIST, "lib/crypto.js"));
const { RoomCrypto, Sealer, AtRestCipher, randomBytes, toB64, fromB64, toB64url, fromB64url, newPeerId, newRoomSecret } =
cryptoMod;
{
const v = {};
// base64 / base64url primitives: the encodings every id and envelope rides on
const byteCases = [
[],
[0],
[255],
[0, 0, 0],
[1, 2, 3],
[0xfb, 0xff, 0xbf],
[...Array(32).keys()],
[251, 255, 191, 254, 255, 255],
];
v.b64 = byteCases.map((bytes) => {
const u8 = new Uint8Array(bytes);
const b64 = toB64(u8);
const b64url = toB64url(u8);
return { bytes, b64, b64url, roundTrip: [...fromB64(b64)], roundTripUrl: [...fromB64url(b64url)] };
});
// the room derivations (PROTOCOL.md §2) — pure HKDF, byte-exact
const secrets = [
"A".repeat(43),
toB64url(new Uint8Array([...Array(32).keys()])),
toB64url(new Uint8Array(32).fill(0xff)),
toB64url(new Uint8Array(16).fill(7)), // the 16-byte minimum
];
const salts = ["chat.ardegazu.ro/v2", "board.ardegazu.ro/v1", ""];
v.derivations = [];
for (const secret of secrets) {
for (const appSalt of salts) {
const rc = await RoomCrypto.create(secret, appSalt, "12D3KooWFixedPeerId");
v.derivations.push({
secret,
appSalt,
peerId: rc.peerId,
roomId: rc.roomId,
roomTopic: rc.roomTopic,
dbName: await rc.dbName(),
mailboxRoomId: await rc.mailboxRoomId(),
});
}
}
// a shorter secret is refused outright
v.tooShort = await RoomCrypto.create(toB64url(new Uint8Array(15).fill(1)), "x", "p").then(
() => "RESOLVED",
(e) => String(e.message),
);
// the session peerId defaults to a fresh 32-hex id when omitted
const anon = await RoomCrypto.create(secrets[0], salts[0]);
v.defaultPeerId = { length: anon.peerId.length, hex: /^[0-9a-f]{32}$/.test(anon.peerId) };
v.newPeerIdShape = /^[0-9a-f]{32}$/.test(newPeerId());
v.newRoomSecretShape = { length: newRoomSecret().length, chars: /^[A-Za-z0-9_-]{43}$/.test(newRoomSecret()) };
// Sealer IV discipline: 4-byte epoch fixed per Sealer, 8-byte BE counter
// incrementing from 0 — and no API takes a caller IV (PROTOCOL.md §3).
installDetRandom();
resetRandom(11);
{
const rc = await RoomCrypto.create(secrets[0], salts[0], "12D3KooWFixedPeerId");
const ivs = [];
for (let i = 0; i < 4; i++) ivs.push(fromB64((await rc.sealSignal("to-peer", { i })).iv));
v.sealerIvs = ivs.map((iv) => hex(iv));
v.sealerEpochStable = ivs.every((iv) => hex(iv.subarray(0, 4)) === hex(ivs[0].subarray(0, 4)));
}
// byte-exact envelopes under the deterministic IV stream
resetRandom(11);
{
const rc = await RoomCrypto.create(secrets[0], salts[0], "12D3KooWSender");
v.envelopes = {
signal: await rc.sealSignal("12D3KooWRecipient", { kind: "offer", sdp: "v=0", name: "a" }),
msg1: await rc.sealMsg({ kind: "presence", op: "beacon", name: "a", ts: 1700000000000 }),
msg2: await rc.sealMsg({ kind: "hello", name: "a" }),
binary: hex(new Uint8Array(await rc.sealMsgBinary(new Uint8Array([1, 2, 3, 4, 5])))),
};
}
// at-rest ciphers: version byte 0x02, random 12-byte IV, room+domain AAD
resetRandom(23);
{
const rc = await RoomCrypto.create(secrets[0], salts[0], "12D3KooWSender");
const entry = await rc.logEntryCipher();
const payload = await rc.logPayloadCipher();
const img = await rc.imgCipher();
const mbx = await rc.mbxCipher();
const data = te.encode('{"t":"chat","ts":1,"name":"a","text":"hi"}');
v.atRest = {
entry: hex(await entry.seal(data)),
payload: hex(await payload.seal(data)),
img: hex(await img.seal(new Uint8Array([9, 8, 7]))),
mbx: hex(await mbx.seal(new Uint8Array([1]))),
};
// open() rejects: wrong version byte, truncated, tampered tag, foreign key
const good = await entry.seal(data);
const flip = (u8, i) => {
const c = new Uint8Array(u8);
c[i] ^= 0xff;
return c;
};
v.atRestRejects = {
ok: [...(await entry.open(good))].length,
wrongVersion: await entry.open(flip(good, 0)),
truncated: await entry.open(good.subarray(0, 28)),
tamperedIv: await entry.open(flip(good, 3)),
tamperedCt: await entry.open(flip(good, 20)),
// domain separation: an entry-sealed block never opens as a payload
crossDomain: await payload.open(good),
};
}
// AAD binding across rooms / senders / directions (PROTOCOL.md §3)
resetRandom(31);
{
const rcA = await RoomCrypto.create(secrets[0], salts[0], "PEER-A");
const rcAasB = await RoomCrypto.create(secrets[0], salts[0], "PEER-B");
const rcOtherRoom = await RoomCrypto.create(secrets[1], salts[0], "PEER-A");
const rcOtherSalt = await RoomCrypto.create(secrets[0], salts[1], "PEER-A");
const env = await rcA.sealMsg({ hello: 1 });
v.aadBinding = {
correctSender: await rcAasB.openMsg("PEER-A", env),
wrongSenderClaim: await rcAasB.openMsg("PEER-B", env),
otherRoom: await rcOtherRoom.openMsg("PEER-A", env),
otherSalt: await rcOtherSalt.openMsg("PEER-A", env),
};
const sig = await rcA.sealSignal("PEER-B", { kind: "ice", candidate: null, name: "a" });
v.sigBinding = {
correctRecipient: await rcAasB.openSignal("PEER-A", sig),
wrongRecipient: await (await RoomCrypto.create(secrets[0], salts[0], "PEER-C")).openSignal("PEER-A", sig),
malformedEnvelope: await rcAasB.openSignal("PEER-A", { v: 1, iv: "!!", ct: "!!" }),
};
const bin = await rcA.sealMsgBinary(new Uint8Array([7, 7]));
v.binaryBinding = {
correct: [...(await rcAasB.openMsgBinary("PEER-A", bin))],
wrongSender: await rcAasB.openMsgBinary("PEER-B", bin),
badPrefix: await rcAasB.openMsgBinary("PEER-A", new Uint8Array([0x02, ...new Uint8Array(28)]).buffer),
tooShort: await rcAasB.openMsgBinary("PEER-A", new Uint8Array([0x01, 1, 2]).buffer),
};
}
// the per-sender key cache is FIFO-bounded at 512 (attacker-mintable ids)
resetRandom(41);
{
const rc = await RoomCrypto.create(secrets[0], salts[0], "PEER-A");
const before = await rc.openMsg("spam-0", { v: 1, iv: toB64(new Uint8Array(12)), ct: toB64(new Uint8Array(16)) });
for (let i = 0; i < 600; i++) {
await rc.openMsg(`spam-${i}`, { v: 1, iv: toB64(new Uint8Array(12)), ct: toB64(new Uint8Array(16)) });
}
const rc2 = await RoomCrypto.create(secrets[0], salts[0], "PEER-A");
const env = await rc2.sealMsg({ still: "works" });
v.keyCacheBounded = { rejectsGarbage: before, worksAfterEviction: await rc.openMsg("PEER-A", env) };
}
// Sealer / AtRestCipher used directly (they are exported by dist/lib/crypto.js)
resetRandom(53);
{
const key = await crypto.subtle.importKey("raw", new Uint8Array(32).fill(3), { name: "AES-GCM" }, false, [
"encrypt",
"decrypt",
]);
const s = new Sealer(key);
const aad = te.encode("aad|1");
v.rawSealer = {
first: await s.seal({ a: 1 }, aad),
second: await s.seal({ a: 2 }, aad),
binary: hex(new Uint8Array(await s.sealBinary(new Uint8Array([1, 2]), aad))),
};
const c = new AtRestCipher(key, aad);
const sealed = await c.seal(new Uint8Array([4, 5, 6]));
v.rawAtRest = { sealed: hex(sealed), opened: [...(await c.open(sealed))] };
}
restoreRandom();
// real-randomness cross-implementation fixtures: the port must unseal these
{
const rc = await RoomCrypto.create(secrets[0], salts[0], "12D3KooWTsSender");
const entryCipher = await rc.logEntryCipher();
v.crossImpl = {
secret: secrets[0],
appSalt: salts[0],
senderPeerId: "12D3KooWTsSender",
msg: { plaintext: { kind: "hello", name: "ts" }, envelope: await rc.sealMsg({ kind: "hello", name: "ts" }) },
signal: {
to: "12D3KooWRecipient",
plaintext: { kind: "answer", sdp: "v=0\r\n", name: "ts" },
envelope: await rc.sealSignal("12D3KooWRecipient", { kind: "answer", sdp: "v=0\r\n", name: "ts" }),
},
binary: {
plaintext: [1, 2, 3, 250, 255],
sealed: hex(new Uint8Array(await rc.sealMsgBinary(new Uint8Array([1, 2, 3, 250, 255])))),
},
atRestEntry: { plaintext: [10, 20, 30], sealed: hex(await entryCipher.seal(new Uint8Array([10, 20, 30]))) },
};
}
write("crypto", v);
}
/* -------------------------------------------------------------- encryption -- */
const encMod = await import(join(DIST, "lib/encryption.js"));
const { makeLogEncryption } = encMod;
{
const v = {};
const rc = await RoomCrypto.create("E".repeat(43), "chat.ardegazu.ro/v2", "12D3KooWEnc");
installDetRandom();
resetRandom(101);
const enc = await makeLogEncryption(rc);
const bytes = te.encode('{"op":"ADD","key":null,"value":{"t":"chat","ts":7,"name":"a","text":"hi"}}');
v.replication = hex(await enc.replication.encrypt(bytes));
v.data = hex(await enc.data.encrypt(bytes));
v.roundTrip = new TextDecoder().decode(await enc.replication.decrypt(fromHex(v.replication)));
// decrypt THROWS on failure — that is how OrbitDB rejects a non-member entry
v.decryptThrows = await enc.replication.decrypt(new Uint8Array([2, ...new Uint8Array(40)])).then(
() => "RESOLVED",
(e) => String(e.message),
);
v.dataDecryptThrows = await enc.data.decrypt(new Uint8Array([0])).then(
() => "RESOLVED",
(e) => String(e.message),
);
// dag-cbor hands views into larger buffers; asBytes must copy them out
resetRandom(101);
const enc2 = await makeLogEncryption(rc);
const backing = new Uint8Array(4 + bytes.length + 4);
backing.set(bytes, 4);
const view = backing.subarray(4, 4 + bytes.length);
v.viewInput = hex(await enc2.replication.encrypt(view));
v.viewMatchesPlain = v.viewInput === v.replication;
// the same, from a SharedArrayBuffer-free non-zero-offset Uint8Array of a
// buffer larger than the view (the exact dag-cbor shape)
v.viewByteOffset = view.byteOffset;
// domain separation between the two hooks
v.replicationNotData = v.replication !== v.data;
restoreRandom();
// cross-implementation: real IVs, the port must decrypt these
const encReal = await makeLogEncryption(rc);
v.crossImpl = {
secret: "E".repeat(43),
appSalt: "chat.ardegazu.ro/v2",
plaintext: [...bytes],
replication: hex(await encReal.replication.encrypt(bytes)),
data: hex(await encReal.data.encrypt(bytes)),
};
write("encryption", v);
}
function fromHex(s) {
const out = new Uint8Array(s.length / 2);
for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
return out;
}
/* ---------------------------------------------------------- orbit identity -- */
{
const v = {};
const idMod = await import(join(DIST, "vendor/id/index.js"));
const oiMod = await import(join(DIST, "lib/orbit-identity.js"));
const { SuetaIdentityProvider } = oiMod;
// Ed25519 is deterministic, so a fixed seed pins every signature byte-exactly
const seeds = [toB64url(new Uint8Array(32).fill(1)), toB64url(new Uint8Array([...Array(32).keys()]))];
v.providers = [];
for (const seed of seeds) {
const identity = await idMod.Identity.fromSeed(seed);
const provider = await SuetaIdentityProvider({ identity })();
const data = "some-device-public-key" + "identity-signature";
v.providers.push({
seed,
pub: identity.publicKeyB64,
fingerprint: identity.fingerprint,
type: provider.type,
id: await provider.getId(),
signIdentity: await provider.signIdentity(data),
signedData: data,
assertion: await identity.assert("chat.ardegazu.ro/v2", "ROOMID", "12D3KooWPeer"),
});
}
v.staticType = SuetaIdentityProvider.type;
// verifyIdentity signs `publicKey + signatures.id`
{
const identity = await idMod.Identity.fromSeed(seeds[0]);
const publicKey = "devicePubKey";
const sigId = "signature-over-the-device-key";
const good = {
id: identity.publicKeyB64,
publicKey,
signatures: { id: sigId, publicKey: await provSign(identity, publicKey + sigId) },
type: "sueta",
};
v.verifyIdentity = {
good: await SuetaIdentityProvider.verifyIdentity(good),
tamperedPublicKey: await SuetaIdentityProvider.verifyIdentity({ ...good, publicKey: "other" }),
tamperedSigId: await SuetaIdentityProvider.verifyIdentity({
...good,
signatures: { ...good.signatures, id: "other" },
}),
wrongId: await SuetaIdentityProvider.verifyIdentity({ ...good, id: toB64url(new Uint8Array(32).fill(9)) }),
garbageSig: await SuetaIdentityProvider.verifyIdentity({
...good,
signatures: { ...good.signatures, publicKey: "!!!" },
}),
record: good,
};
}
write("orbit-identity", v);
}
async function provSign(identity, data) {
return toB64url(await identity.signRaw(te.encode(data)));
}
/* -------------------------------------------------------------- access ------ */
{
const v = {};
const acMod = await import(join(DIST, "lib/access.js"));
const { HardenedIPFSAccessController, signerMatchesIdentity } = acMod;
const { IPFSAccessController } = await import("@orbitdb/core");
const identities = {
getIdentity: async (hash) =>
({
idA: { publicKey: "keyA" },
idNoKey: {},
})[hash],
};
const throwing = {
getIdentity: async () => {
throw new Error("bitswap timeout");
},
};
v.signerMatchesIdentity = [
{ entry: { key: "keyA", identity: "idA" }, ok: await signerMatchesIdentity(identities, { key: "keyA", identity: "idA" }) },
{ entry: { key: "keyB", identity: "idA" }, ok: await signerMatchesIdentity(identities, { key: "keyB", identity: "idA" }) },
{ entry: { key: "keyA", identity: "missing" }, ok: await signerMatchesIdentity(identities, { key: "keyA", identity: "missing" }) },
{ entry: { key: "keyA", identity: "idNoKey" }, ok: await signerMatchesIdentity(identities, { key: "keyA", identity: "idNoKey" }) },
{ entry: { identity: "idA" }, ok: await signerMatchesIdentity(identities, { identity: "idA" }) },
{ entry: { key: "keyA" }, ok: await signerMatchesIdentity(identities, { key: "keyA" }) },
{ entry: {}, ok: await signerMatchesIdentity(identities, {}) },
{ entry: { key: "keyA", identity: "idA" }, throws: true, ok: await signerMatchesIdentity(throwing, { key: "keyA", identity: "idA" }) },
];
// the wrapper must not change the manifest address (or the DB forks).
// IPFSAccessController writes the ACL block through orbitdb.ipfs, so the stub
// needs a blockstore + pins; the address it returns is the CID of
// {type:"ipfs", write} and nothing else — that is the interop guarantee.
const acStore = new Map();
const ipfs = {
blockstore: {
put: async (cid, data) => acStore.set(cid.toString(), data),
get: async (cid) => acStore.get(cid.toString()),
has: async (cid) => acStore.has(cid.toString()),
},
pins: { isPinned: async () => true, add: () => ({ [Symbol.asyncIterator]: () => ({ next: async () => ({ done: true }) }) }) },
};
const acIdentities = { ...identities, verifyIdentity: async () => true };
const mkStub = () => ({ orbitdb: { ipfs, identity: { id: "creator" } }, identities: acIdentities, name: "dbname" });
const vanilla = await IPFSAccessController({ write: ["*"] })(mkStub());
const hardened = await HardenedIPFSAccessController({ write: ["*"] })(mkStub());
v.controller = {
type: hardened.type,
write: hardened.write,
sameAddressAsVanilla: hardened.address === vanilla.address,
address: hardened.address,
vanillaAddress: vanilla.address,
};
// canAppend is the AND of the vanilla check and the signer↔identity binding
v.canAppend = {
vanillaAcceptsForged: await vanilla.canAppend({ key: "keyB", identity: "idA" }),
hardenedRejectsForged: await hardened.canAppend({ key: "keyB", identity: "idA" }),
hardenedAcceptsHonest: await hardened.canAppend({ key: "keyA", identity: "idA" }),
};
write("access", v);
}
/* ----------------------------------------------------------- descriptor ----- */
{
const v = { cases: [] };
const { resolveRelayConfig } = await import(join(DIST, "lib/descriptor.js"));
const DEFAULTS = {
relayMultiaddr: "/dns4/signal.example/tcp/443/tls/ws/p2p/12D3KooRELAY",
turnCredsUrl: "https://signal.example/turn-credentials",
discoveryTopic: "_peer-discovery._p2p._pubsub",
};
const realFetch = globalThis.fetch;
const run = async (label, defaults, impl) => {
globalThis.fetch = impl;
const urls = [];
globalThis.fetch = async (url, init) => {
urls.push(String(url));
return impl(url, init);
};
try {
v.cases.push({ label, urls, result: await resolveRelayConfig(defaults) });
} finally {
globalThis.fetch = realFetch;
}
};
const json = (body, ok = true, status = 200) => async () => ({ ok, status, json: async () => body });
await run("no-dns4-multiaddr", { ...DEFAULTS, relayMultiaddr: "/ip4/127.0.0.1/tcp/9090/ws/p2p/12D3KooDEV" }, json({}));
await run("fetch-throws", DEFAULTS, async () => {
throw new Error("offline");
});
await run("not-ok", DEFAULTS, json({}, false, 502));
await run("empty-descriptor", DEFAULTS, json({}));
await run("full-descriptor", DEFAULTS, json({
relay: { multiaddrs: ["/dns4/new.example/tcp/443/tls/ws/p2p/12D3KooNEW", "/ip4/1.2.3.4"], pubsub_discovery_topic: "_other" },
endpoints: { turn_credentials: "https://new.example/turn" },
mailbox: { endpoint: "https://new.example/mbx", mint_endpoint: "https://new.example/mint", max_message_kb: 128 },
}));
await run("mailbox-without-mint", DEFAULTS, json({ mailbox: { endpoint: "https://x/mbx" } }));
await run("mailbox-default-kb", DEFAULTS, json({ mailbox: { endpoint: "https://x/mbx", mint_endpoint: "https://x/mint" } }));
await run(
"descriptor-keeps-default-mailbox",
{ ...DEFAULTS, mailbox: { baseUrl: "https://d/mbx", credsUrl: "https://d/mint", maxMessageKb: 64 } },
json({}),
);
await run("malformed-json", DEFAULTS, async () => ({ ok: true, status: 200, json: async () => { throw new Error("bad json"); } }));
write("descriptor", v);
}
/* ---------------------------------------------------------------- turn ------ */
{
const v = { cases: [] };
const { IceConfig } = await import(join(DIST, "lib/turn.js"));
const realFetch = globalThis.fetch;
const realNow = Date.now;
const realWarn = console.warn;
const creds = { username: "u", credential: "c", ttl: 3600, urls: ["stun:s", "turn:t?transport=udp"] };
let now = 1_700_000_000_000;
Date.now = () => now;
console.warn = () => {};
try {
// happy path + caching until 5 min before expiry
let fetches = 0;
globalThis.fetch = async () => {
fetches++;
return { ok: true, status: 200, json: async () => creds };
};
const ice = new IceConfig("https://signal.example/turn-credentials");
v.cases.push({ label: "first", config: await ice.get(), fetches });
v.cases.push({ label: "cached", config: await ice.get(), fetches });
now += 3600_000 - 300_000 - 1;
v.cases.push({ label: "still-cached", config: await ice.get(), fetches });
now += 2;
v.cases.push({ label: "refetched", config: await ice.get(), fetches });
// inflight dedup: two concurrent gets share one fetch
fetches = 0;
const ice2 = new IceConfig("https://signal.example/turn-credentials");
const [a, b] = await Promise.all([ice2.get(), ice2.get()]);
v.cases.push({ label: "inflight-dedup", same: a === b, fetches });
// forceRelay
const ice3 = new IceConfig("https://signal.example/turn-credentials", true);
v.cases.push({ label: "force-relay", config: await ice3.get() });
// failure: no ICE servers, and a short retry window (30 s), never a throw
globalThis.fetch = async () => {
throw new Error("offline");
};
const ice4 = new IceConfig("https://signal.example/turn-credentials");
v.cases.push({ label: "fetch-fails", config: await ice4.get() });
const ice5 = new IceConfig("https://signal.example/turn-credentials", true);
v.cases.push({ label: "fetch-fails-force-relay", config: await ice5.get() });
globalThis.fetch = async () => ({ ok: false, status: 500, json: async () => ({}) });
const ice6 = new IceConfig("https://signal.example/turn-credentials");
v.cases.push({ label: "not-ok", config: await ice6.get() });
now += 29_000;
let f2 = 0;
globalThis.fetch = async () => {
f2++;
return { ok: true, status: 200, json: async () => creds };
};
v.cases.push({ label: "retry-window-not-expired", config: await ice6.get(), fetches: f2 });
now += 2_000;
v.cases.push({ label: "retry-window-expired", config: await ice6.get(), fetches: f2 });
} finally {
globalThis.fetch = realFetch;
Date.now = realNow;
console.warn = realWarn;
}
write("turn", v);
}
/* ------------------------------------------------------- protocol / wire ---- */
/**
* Every object this kit serializes with JSON.stringify before it is sealed, and
* every LogOp it appends. The bytes are the wire: a deployed browser opens the
* ciphertext and JSON.parses whatever is inside, so a reordered or renamed key
* is a protocol change. (dev/docs/CLJS.md: js-obj scrambles literals wider than
* eight pairs — these are the objects that rule exists for.)
*/
{
const v = {};
const chatMod = await loadExposed(join(DIST, "chat/index.js"), SCRATCH, {
ChatClient: ["applyEntry", "onLive", "onPeerState", "idFields", "sendHello"],
});
const boardMod = await loadExposed(join(DIST, "board/index.js"), SCRATCH, { BoardClient: ["applyEntry"] });
v.salts = { CHAT_SALT: chatMod.CHAT_SALT, BOARD_SALT: boardMod.BOARD_SALT };
// Wire bytes must be reproducible, so both sources of entropy are pinned for
// this whole block: the IV stream (det getRandomValues) and the clock (every
// op carries ts: Date.now(), every element id is randomBytes(16)).
installDetRandom();
resetRandom(7);
const realNowP = Date.now;
Date.now = () => 1_700_000_000_000;
// the envelope shape as it hits the wire (net.ts JSON.stringifies it)
const rc = await RoomCrypto.create("W".repeat(43), chatMod.CHAT_SALT, "12D3KooWWire");
v.envelopeJson = JSON.stringify(await rc.sealMsg({ kind: "presence", op: "beacon", name: "n", ts: 1 }));
// the payload literals, captured through the code that builds them: a
// ChatClient with a stub Net records exactly what it broadcasts / sends.
const sent = [];
const stubNet = {
myId: "12D3KooWSelf",
broadcast: async (payload) => sent.push(["broadcast", JSON.stringify(payload)]),
sendTo: async (peer, payload) => {
sent.push(["sendTo", peer, JSON.stringify(payload)]);
return true;
},
};
const appended = [];
const stubLog = {
append: async (op) => {
appended.push(JSON.stringify(op));
return `h${appended.length}`;
},
myAuthorId: "AUTHOR",
close: async () => {},
};
const idMod = await import(join(DIST, "vendor/id/index.js"));
const identity = await idMod.Identity.fromSeed(toB64url(new Uint8Array(32).fill(5)));
const chat = new chatMod.ChatClient(stubNet, stubLog, "ROOMID", "bot", identity, chatMod.CHAT_SALT);
await chat.send("hello");
await chat.send("threaded", "h1");
await chat.react("h1", "🔥");
await chat.react("h1", "🔥", "remove");
await chat.setName("renamed");
await priv(chat, "sendHello")("12D3KooWPeer");
v.chat = { appended: appended.splice(0), sent: sent.splice(0) };
// identity-less: idPub/idSig are absent, not null
const chatAnon = new chatMod.ChatClient(stubNet, stubLog, "ROOMID", "bot", null, chatMod.CHAT_SALT);
await chatAnon.setName("anon");
await priv(chatAnon, "sendHello")("12D3KooWPeer");
v.chatAnon = { sent: sent.splice(0) };
const board = new boardMod.BoardClient(stubNet, stubLog, "ROOMID", "bot");
const id = await board.addText(1.5, -2.25, "signed", { size: 14, color: 5 });
v.board = { appended: appended.splice(0), textId: /^[A-Za-z0-9_-]{22}$/.test(id) };
// drawStroke: live preview segments then the committed add op. `pts` is
// delta-encoded fixed point (world × 100) — the exact pen-tool encoding.
const points = [
{ x: 0, y: 0 },
{ x: 1.005, y: -1.004 },
{ x: 2.5, y: 3.5 },
{ x: 2.5, y: 3.5 },
];
await board.drawStroke(points, { width: 3, color: 9 });
v.stroke = { sent: sent.splice(0), appended: appended.splice(0) };
// long stroke: segments cap at 512 numbers each
const long = Array.from({ length: 400 }, (_, i) => ({ x: i, y: -i }));
await board.drawStroke(long, {});
const segs = sent.splice(0);
v.strokeSegments = {
count: segs.length,
lengths: segs.map((s) => JSON.parse(s[1]).seg.length),
doneFlags: segs.map((s) => JSON.parse(s[1]).done ?? null),
};
appended.splice(0);
v.strokeTooShort = await board.drawStroke([{ x: 1, y: 1 }], {}).then(
() => "RESOLVED",
(e) => String(e.message),
);
await board.erase(["a", "b"]);
v.erase = { appended: appended.splice(0) };
// colour clamp
await board.addText(0, 0, "clamp-low", { color: -5 });
await board.addText(0, 0, "clamp-high", { color: 99 });
v.clamp = appended.splice(0).map((s) => JSON.parse(s).el.c);
Date.now = realNowP;
restoreRandom();
write("protocol", v);
}
/* --------------------------------------------------------- state machines --- */
{
const netMod = await loadExposed(join(DIST, "lib/net.js"), SCRATCH, {
Net: [
"dialPeer", "recFor", "onConnChange", "refreshState", "maybeReady", "sweep", "endChannels",
"dropPeer", "hangUpStr", "beacon", "verified", "onTopicMessage", "onPresence", "beaconTo",
"onMsgFrame", "frame", "relayPeerId", "ensureRelay", "scheduleRedial", "setRelayUp", "pubsub",
],
});
write("net", await netScript({ Net: netMod.Net, RoomCrypto, priv }));
write("relay", await relayScript({ Net: netMod.Net, RoomCrypto, priv }));
const logMod = await loadExposed(join(DIST, "lib/log.js"), SCRATCH, {
RoomLog: ["emit", "onUpdate", "sweepUnseen", "authorOf", "canJoinLocally", "identityLocal"],
});
write("log", await logScript({ RoomLog: logMod.RoomLog, RoomCrypto, makeLogEncryption, priv }));
const chatMod = await loadExposed(join(DIST, "chat/index.js"), SCRATCH, {
ChatClient: ["applyEntry", "onLive", "onPeerState", "applyReaction", "foldReactionsInto", "idFields", "sendHello"],
});
write("chat", await chatScript({ ChatClient: chatMod.ChatClient, priv }));
const boardMod = await loadExposed(join(DIST, "board/index.js"), SCRATCH, { BoardClient: ["applyEntry"] });
write("board", await boardScript({ BoardClient: boardMod.BoardClient, priv }));
}
/* --------------------------------------------------------------- node env -- */
{
const v = {};
const envMod = await import(join(DIST, "node/env.js"));
v.selfPeerIdsIsGlobal = (() => {
const a = envMod.selfPeerIds();
a.add("x");
return envMod.selfPeerIds().has("x") && globalThis.__ardegazuSelfPeers === a;
})();
// installBrowserGlobals: the shallow DOM a headless peer needs
envMod.installBrowserGlobals();
v.browserGlobals = {
visibilityState: globalThis.document.visibilityState,
hasWindowSetTimeout: typeof globalThis.window.setTimeout === "function",
addEventListenerNoop: globalThis.window.addEventListener("x", () => {}) === undefined,
localStorage: (() => {
const ls = globalThis.localStorage;
const before = ls.getItem("k");
ls.setItem("k", 42);
const after = ls.getItem("k");
ls.removeItem("k");
return { before, after, afterRemove: ls.getItem("k") };
})(),
};
// installOriginFetch adds Origin only for the suite's hosts
const seen = [];
const realFetch = globalThis.fetch;
globalThis.fetch = async (input, init) => {
const h = new Headers(init?.headers ?? undefined);
seen.push([String(typeof input === "string" ? input : input.url), h.get("origin")]);
return { ok: true };
};
envMod.installOriginFetch("https://chat.ardegazu.ro");
await globalThis.fetch("https://signal.ardegazu.ro/turn-credentials");
await globalThis.fetch("https://mbx.ap2p.ro/x");
await globalThis.fetch("https://example.com/x");
await globalThis.fetch("https://signal.ardegazu.ro/y", { headers: { origin: "https://other" } });
v.originFetch = seen;
globalThis.fetch = realFetch;
// installOrigin is idempotent per origin and refuses a second, different one
envMod.installOrigin("https://chat.ardegazu.ro");
envMod.installOrigin("https://chat.ardegazu.ro");
v.installOriginConflict = (() => {
try {
envMod.installOrigin("https://board.ardegazu.ro");
return "NO THROW";
} catch (e) {
return String(e.message);
}
})();
v.webSocketReplaced = globalThis.WebSocket?.name ?? null;
write("env", v);
}
console.log("done");
|