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 | /**
* Golden-vector checks against the committed dist/.
*
* Every fixture here was extracted from the TypeScript implementation while it
* was canon (test/vectors/generate.mjs). Deterministic outputs are compared
* byte-for-byte; the randomized-IV sealers are proven both ways — the port
* reproduces TS ciphertext under a pinned IV stream, AND opens envelopes the TS
* build sealed with real randomness.
*/
import { test } from "node:test";
import assert from "node:assert/strict";
import { load, readVector, hex, fromHex } from "./helpers/load.mjs";
import { installDetRandom, resetRandom, restoreRandom } from "./helpers/det-random.mjs";
const te = new TextEncoder();
const td = new TextDecoder();
const cryptoMod = await load("lib/crypto.js");
const encMod = await load("lib/encryption.js");
test("base64 / base64url primitives", async () => {
const v = await readVector("crypto");
const { toB64, fromB64, toB64url, fromB64url } = cryptoMod;
for (const c of v.b64) {
const u8 = new Uint8Array(c.bytes);
assert.equal(toB64(u8), c.b64, `toB64 ${c.bytes}`);
assert.equal(toB64url(u8), c.b64url, `toB64url ${c.bytes}`);
assert.deepEqual([...fromB64(c.b64)], c.roundTrip);
assert.deepEqual([...fromB64url(c.b64url)], c.roundTripUrl);
}
});
test("room derivations are byte-exact (PROTOCOL.md §2)", async () => {
const v = await readVector("crypto");
for (const d of v.derivations) {
const rc = await cryptoMod.RoomCrypto.create(d.secret, d.appSalt, d.peerId);
assert.equal(rc.peerId, d.peerId);
assert.equal(rc.roomId, d.roomId, `roomId for ${d.appSalt}`);
assert.equal(rc.roomTopic, d.roomTopic);
assert.equal(await rc.dbName(), d.dbName);
assert.equal(await rc.mailboxRoomId(), d.mailboxRoomId);
assert.match(rc.roomTopic, /^sueta\/2\//);
}
});
test("a short room secret is refused; ids have the documented shapes", async () => {
const v = await readVector("crypto");
const short = cryptoMod.toB64url(new Uint8Array(15).fill(1));
await assert.rejects(() => cryptoMod.RoomCrypto.create(short, "x", "p"), (e) => e.message === v.tooShort);
const anon = await cryptoMod.RoomCrypto.create("A".repeat(43), "chat.ardegazu.ro/v2");
assert.equal(anon.peerId.length, v.defaultPeerId.length);
assert.equal(/^[0-9a-f]{32}$/.test(anon.peerId), v.defaultPeerId.hex);
assert.equal(/^[0-9a-f]{32}$/.test(cryptoMod.newPeerId()), v.newPeerIdShape);
assert.equal(cryptoMod.newRoomSecret().length, v.newRoomSecretShape.length);
assert.equal(/^[A-Za-z0-9_-]{43}$/.test(cryptoMod.newRoomSecret()), v.newRoomSecretShape.chars);
});
test("Sealer IVs: fixed epoch, big-endian counter from zero", async () => {
const v = await readVector("crypto");
installDetRandom();
try {
resetRandom(11);
const rc = await cryptoMod.RoomCrypto.create("A".repeat(43), "chat.ardegazu.ro/v2", "12D3KooWFixedPeerId");
const ivs = [];
for (let i = 0; i < 4; i++) ivs.push(cryptoMod.fromB64((await rc.sealSignal("to-peer", { i })).iv));
assert.deepEqual(ivs.map(hex), v.sealerIvs);
assert.equal(ivs.every((iv) => hex(iv.subarray(0, 4)) === hex(ivs[0].subarray(0, 4))), true);
// the counter is the low 8 bytes, big-endian, starting at 0
assert.deepEqual([...ivs[0].subarray(4)], [0, 0, 0, 0, 0, 0, 0, 0]);
assert.deepEqual([...ivs[3].subarray(4)], [0, 0, 0, 0, 0, 0, 0, 3]);
} finally {
restoreRandom();
}
});
test("sealed envelopes are byte-identical to the TS build under a pinned IV stream", async () => {
const v = await readVector("crypto");
installDetRandom();
try {
resetRandom(11);
const rc = await cryptoMod.RoomCrypto.create("A".repeat(43), "chat.ardegazu.ro/v2", "12D3KooWSender");
assert.deepEqual(
JSON.parse(JSON.stringify(await rc.sealSignal("12D3KooWRecipient", { kind: "offer", sdp: "v=0", name: "a" }))),
v.envelopes.signal,
);
assert.deepEqual(
JSON.parse(JSON.stringify(await rc.sealMsg({ kind: "presence", op: "beacon", name: "a", ts: 1700000000000 }))),
v.envelopes.msg1,
);
assert.deepEqual(JSON.parse(JSON.stringify(await rc.sealMsg({ kind: "hello", name: "a" }))), v.envelopes.msg2);
assert.equal(hex(new Uint8Array(await rc.sealMsgBinary(new Uint8Array([1, 2, 3, 4, 5])))), v.envelopes.binary);
} finally {
restoreRandom();
}
});
test("at-rest ciphers: 0x02 envelope, byte-exact, and the reject table", async () => {
const v = await readVector("crypto");
installDetRandom();
try {
resetRandom(23);
const rc = await cryptoMod.RoomCrypto.create("A".repeat(43), "chat.ardegazu.ro/v2", "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"}');
assert.equal(hex(await entry.seal(data)), v.atRest.entry);
assert.equal(hex(await payload.seal(data)), v.atRest.payload);
assert.equal(hex(await img.seal(new Uint8Array([9, 8, 7]))), v.atRest.img);
assert.equal(hex(await mbx.seal(new Uint8Array([1]))), v.atRest.mbx);
const good = await entry.seal(data);
assert.equal(good[0], 0x02);
const flip = (u8, i) => {
const c = new Uint8Array(u8);
c[i] ^= 0xff;
return c;
};
assert.equal((await entry.open(good)).length, v.atRestRejects.ok);
assert.equal(await entry.open(flip(good, 0)), v.atRestRejects.wrongVersion);
assert.equal(await entry.open(good.subarray(0, 28)), v.atRestRejects.truncated);
assert.equal(await entry.open(flip(good, 3)), v.atRestRejects.tamperedIv);
assert.equal(await entry.open(flip(good, 20)), v.atRestRejects.tamperedCt);
assert.equal(await payload.open(good), v.atRestRejects.crossDomain);
} finally {
restoreRandom();
}
});
test("AAD binds room, salt, sender and direction", async () => {
const v = await readVector("crypto");
const secretA = "A".repeat(43);
const secretB = cryptoMod.toB64url(new Uint8Array([...Array(32).keys()]));
const rcA = await cryptoMod.RoomCrypto.create(secretA, "chat.ardegazu.ro/v2", "PEER-A");
const rcAasB = await cryptoMod.RoomCrypto.create(secretA, "chat.ardegazu.ro/v2", "PEER-B");
const rcOtherRoom = await cryptoMod.RoomCrypto.create(secretB, "chat.ardegazu.ro/v2", "PEER-A");
const rcOtherSalt = await cryptoMod.RoomCrypto.create(secretA, "board.ardegazu.ro/v1", "PEER-A");
const env = await rcA.sealMsg({ hello: 1 });
assert.deepEqual(await rcAasB.openMsg("PEER-A", env), v.aadBinding.correctSender);
assert.equal(await rcAasB.openMsg("PEER-B", env), null);
assert.equal(await rcOtherRoom.openMsg("PEER-A", env), null);
assert.equal(await rcOtherSalt.openMsg("PEER-A", env), null);
const sig = await rcA.sealSignal("PEER-B", { kind: "ice", candidate: null, name: "a" });
assert.deepEqual(await rcAasB.openSignal("PEER-A", sig), v.sigBinding.correctRecipient);
const rcC = await cryptoMod.RoomCrypto.create(secretA, "chat.ardegazu.ro/v2", "PEER-C");
assert.equal(await rcC.openSignal("PEER-A", sig), null);
assert.equal(await rcAasB.openSignal("PEER-A", { v: 1, iv: "!!", ct: "!!" }), null);
const bin = await rcA.sealMsgBinary(new Uint8Array([7, 7]));
assert.deepEqual([...(await rcAasB.openMsgBinary("PEER-A", bin))], v.binaryBinding.correct);
assert.equal(await rcAasB.openMsgBinary("PEER-B", bin), null);
// wrong version prefix (0x02 is the at-rest envelope, not the live one)
assert.equal(await rcAasB.openMsgBinary("PEER-A", new Uint8Array([0x02, ...new Uint8Array(28)]).buffer), null);
assert.equal(await rcAasB.openMsgBinary("PEER-A", new Uint8Array([0x01, 1, 2]).buffer), null);
});
test("the per-sender key cache stays bounded under minted sender ids", async () => {
const v = await readVector("crypto");
const rc = await cryptoMod.RoomCrypto.create("A".repeat(43), "chat.ardegazu.ro/v2", "PEER-A");
const junk = { v: 1, iv: cryptoMod.toB64(new Uint8Array(12)), ct: cryptoMod.toB64(new Uint8Array(16)) };
assert.equal(await rc.openMsg("spam-0", junk), v.keyCacheBounded.rejectsGarbage);
for (let i = 0; i < 600; i++) await rc.openMsg(`spam-${i}`, junk);
const rc2 = await cryptoMod.RoomCrypto.create("A".repeat(43), "chat.ardegazu.ro/v2", "PEER-A");
assert.deepEqual(await rc.openMsg("PEER-A", await rc2.sealMsg({ still: "works" })), v.keyCacheBounded.worksAfterEviction);
});
test("Sealer and AtRestCipher used directly", async () => {
const v = await readVector("crypto");
installDetRandom();
try {
resetRandom(53);
const key = await crypto.subtle.importKey("raw", new Uint8Array(32).fill(3), { name: "AES-GCM" }, false, [
"encrypt",
"decrypt",
]);
const s = new cryptoMod.Sealer(key);
const aad = te.encode("aad|1");
assert.deepEqual(JSON.parse(JSON.stringify(await s.seal({ a: 1 }, aad))), v.rawSealer.first);
assert.deepEqual(JSON.parse(JSON.stringify(await s.seal({ a: 2 }, aad))), v.rawSealer.second);
assert.equal(hex(new Uint8Array(await s.sealBinary(new Uint8Array([1, 2]), aad))), v.rawSealer.binary);
const c = new cryptoMod.AtRestCipher(key, aad);
const sealed = await c.seal(new Uint8Array([4, 5, 6]));
assert.equal(hex(sealed), v.rawAtRest.sealed);
assert.deepEqual([...(await c.open(sealed))], v.rawAtRest.opened);
} finally {
restoreRandom();
}
});
test("cross-implementation: the port opens what the TS build sealed", async () => {
const v = (await readVector("crypto")).crossImpl;
const rc = await cryptoMod.RoomCrypto.create(v.secret, v.appSalt, "12D3KooWReader");
assert.deepEqual(await rc.openMsg(v.senderPeerId, v.msg.envelope), v.msg.plaintext);
// the signal envelope is addressed to a specific recipient
const rcTo = await cryptoMod.RoomCrypto.create(v.secret, v.appSalt, v.signal.to);
assert.deepEqual(await rcTo.openSignal(v.senderPeerId, v.signal.envelope), v.signal.plaintext);
const sealed = fromHex(v.binary.sealed);
const ab = new ArrayBuffer(sealed.length);
new Uint8Array(ab).set(sealed);
assert.deepEqual([...(await rc.openMsgBinary(v.senderPeerId, ab))], v.binary.plaintext);
const entry = await rc.logEntryCipher();
assert.deepEqual([...(await entry.open(fromHex(v.atRestEntry.sealed)))], v.atRestEntry.plaintext);
});
test("cross-implementation: the TS build opens what the port seals", async () => {
// Proven by construction from the other direction: the port's ciphertext under
// a pinned IV stream is byte-identical to the TS build's (the envelope tests
// above), and AES-GCM decryption depends on nothing but key, IV, AAD and
// ciphertext. This case pins the remaining piece — that a REAL-random seal by
// this implementation opens under a second, independently derived RoomCrypto.
const rcA = await cryptoMod.RoomCrypto.create("R".repeat(43), "chat.ardegazu.ro/v2", "PEER-SEND");
const rcB = await cryptoMod.RoomCrypto.create("R".repeat(43), "chat.ardegazu.ro/v2", "PEER-RECV");
const payload = { kind: "presence", op: "beacon", name: "cljs", ts: 1700000000000 };
assert.deepEqual(await rcB.openMsg("PEER-SEND", await rcA.sealMsg(payload)), payload);
const entryA = await rcA.logEntryCipher();
const entryB = await rcB.logEntryCipher();
assert.deepEqual([...(await entryB.open(await entryA.seal(new Uint8Array([1, 2, 3]))))], [1, 2, 3]);
});
test("log encryption hooks: byte-exact, decrypt-or-throw, view-safe", async () => {
const v = await readVector("encryption");
const rc = await cryptoMod.RoomCrypto.create("E".repeat(43), "chat.ardegazu.ro/v2", "12D3KooWEnc");
const bytes = te.encode('{"op":"ADD","key":null,"value":{"t":"chat","ts":7,"name":"a","text":"hi"}}');
installDetRandom();
try {
resetRandom(101);
const enc = await encMod.makeLogEncryption(rc);
assert.equal(hex(await enc.replication.encrypt(bytes)), v.replication);
assert.equal(hex(await enc.data.encrypt(bytes)), v.data);
assert.equal(td.decode(await enc.replication.decrypt(fromHex(v.replication))), v.roundTrip);
assert.notEqual(v.replication, v.data);
await assert.rejects(
() => enc.replication.decrypt(new Uint8Array([2, ...new Uint8Array(40)])),
(e) => e.message === v.decryptThrows,
);
await assert.rejects(() => enc.data.decrypt(new Uint8Array([0])), (e) => e.message === v.dataDecryptThrows);
// dag-cbor hands the hooks views into a larger buffer
resetRandom(101);
const enc2 = await encMod.makeLogEncryption(rc);
const backing = new Uint8Array(4 + bytes.length + 4);
backing.set(bytes, 4);
const view = backing.subarray(4, 4 + bytes.length);
assert.equal(view.byteOffset, v.viewByteOffset);
assert.equal(hex(await enc2.replication.encrypt(view)), v.viewInput);
assert.equal(v.viewInput, v.replication, "a view must seal exactly like a plain array");
} finally {
restoreRandom();
}
});
test("cross-implementation: TS-sealed log blocks decrypt here", async () => {
const v = (await readVector("encryption")).crossImpl;
const rc = await cryptoMod.RoomCrypto.create(v.secret, v.appSalt, "12D3KooWAnyone");
const enc = await encMod.makeLogEncryption(rc);
assert.deepEqual([...(await enc.replication.decrypt(fromHex(v.replication)))], v.plaintext);
assert.deepEqual([...(await enc.data.decrypt(fromHex(v.data)))], v.plaintext);
});
test("the sueta OrbitDB identity provider (byte-exact Ed25519)", async () => {
const v = await readVector("orbit-identity");
const oi = await load("lib/orbit-identity.js");
const root = await load("index.js");
for (const p of v.providers) {
const identity = await root.Identity.fromSeed(p.seed);
assert.equal(identity.publicKeyB64, p.pub);
assert.deepEqual(JSON.parse(JSON.stringify(identity.fingerprint)), p.fingerprint);
const provider = await oi.SuetaIdentityProvider({ identity })();
assert.equal(provider.type, p.type);
assert.equal(await provider.getId(), p.id);
assert.equal(await provider.signIdentity(p.signedData), p.signIdentity);
assert.equal(await identity.assert("chat.ardegazu.ro/v2", "ROOMID", "12D3KooWPeer"), p.assertion);
}
assert.equal(oi.SuetaIdentityProvider.type, v.staticType);
const rec = v.verifyIdentity.record;
assert.equal(await oi.SuetaIdentityProvider.verifyIdentity(rec), v.verifyIdentity.good);
assert.equal(
await oi.SuetaIdentityProvider.verifyIdentity({ ...rec, publicKey: "other" }),
v.verifyIdentity.tamperedPublicKey,
);
assert.equal(
await oi.SuetaIdentityProvider.verifyIdentity({ ...rec, signatures: { ...rec.signatures, id: "other" } }),
v.verifyIdentity.tamperedSigId,
);
assert.equal(
await oi.SuetaIdentityProvider.verifyIdentity({ ...rec, id: cryptoMod.toB64url(new Uint8Array(32).fill(9)) }),
v.verifyIdentity.wrongId,
);
assert.equal(
await oi.SuetaIdentityProvider.verifyIdentity({ ...rec, signatures: { ...rec.signatures, publicKey: "!!!" } }),
v.verifyIdentity.garbageSig,
);
// registration with OrbitDB's registry is idempotent
const reg = await load("lib/orbit-identity.js");
reg.registerSuetaProvider();
reg.registerSuetaProvider();
});
test("the hardened access controller closes the authorship-forgery gap", async () => {
const v = await readVector("access");
const ac = await load("lib/access.js");
const { IPFSAccessController } = await import("@orbitdb/core");
const identities = {
getIdentity: async (h) => ({ idA: { publicKey: "keyA" }, idNoKey: {} })[h],
verifyIdentity: async () => true,
};
const throwing = {
getIdentity: async () => {
throw new Error("bitswap timeout");
},
verifyIdentity: async () => true,
};
for (const c of v.signerMatchesIdentity) {
const ids = c.throws ? throwing : identities;
assert.equal(await ac.signerMatchesIdentity(ids, c.entry), c.ok, JSON.stringify(c.entry));
}
const store = new Map();
const ipfs = {
blockstore: {
put: async (cid, d) => store.set(cid.toString(), d),
get: async (cid) => store.get(cid.toString()),
has: async (cid) => store.has(cid.toString()),
},
pins: { isPinned: async () => true, add: () => ({ [Symbol.asyncIterator]: () => ({ next: async () => ({ done: true }) }) }) },
};
const params = () => ({ orbitdb: { ipfs, identity: { id: "creator" } }, identities, name: "dbname" });
const vanilla = await IPFSAccessController({ write: ["*"] })(params());
const hardened = await ac.HardenedIPFSAccessController({ write: ["*"] })(params());
assert.equal(hardened.type, v.controller.type);
assert.deepEqual([...hardened.write], v.controller.write);
// THE interop guarantee: the manifest address must not move, or wrapped and
// vanilla clients open different databases (PROTOCOL.md §5).
assert.equal(hardened.address, vanilla.address);
assert.equal(hardened.address, v.controller.address);
assert.equal(await vanilla.canAppend({ key: "keyB", identity: "idA" }), v.canAppend.vanillaAcceptsForged);
assert.equal(await hardened.canAppend({ key: "keyB", identity: "idA" }), v.canAppend.hardenedRejectsForged);
assert.equal(await hardened.canAppend({ key: "keyA", identity: "idA" }), v.canAppend.hardenedAcceptsHonest);
});
test("relay descriptor resolution", async () => {
const v = await readVector("descriptor");
const { resolveRelayConfig } = await load("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 json = (body, ok = true, status = 200) => async () => ({ ok, status, json: async () => body });
// label -> [defaults, fetch impl] — the same table the generator drove
const CASES = {
"no-dns4-multiaddr": [{ ...DEFAULTS, relayMultiaddr: "/ip4/127.0.0.1/tcp/9090/ws/p2p/12D3KooDEV" }, json({})],
"fetch-throws": [DEFAULTS, async () => { throw new Error("offline"); }],
"not-ok": [DEFAULTS, json({}, false, 502)],
"empty-descriptor": [DEFAULTS, json({})],
"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 },
})],
"mailbox-without-mint": [DEFAULTS, json({ mailbox: { endpoint: "https://x/mbx" } })],
"mailbox-default-kb": [DEFAULTS, json({ mailbox: { endpoint: "https://x/mbx", mint_endpoint: "https://x/mint" } })],
"descriptor-keeps-default-mailbox": [
{ ...DEFAULTS, mailbox: { baseUrl: "https://d/mbx", credsUrl: "https://d/mint", maxMessageKb: 64 } },
json({}),
],
"malformed-json": [DEFAULTS, async () => ({ ok: true, status: 200, json: async () => { throw new Error("bad json"); } })],
};
const realFetch = globalThis.fetch;
try {
for (const c of v.cases) {
const [defaults, impl] = CASES[c.label];
const urls = [];
globalThis.fetch = async (url, init) => {
urls.push(String(url));
return impl(url, init);
};
const got = await resolveRelayConfig(defaults);
assert.deepEqual(urls, c.urls, `${c.label}: fetch urls`);
assert.deepEqual(JSON.parse(JSON.stringify(got)), c.result, `${c.label}: config`);
}
} finally {
globalThis.fetch = realFetch;
}
});
test("TURN credential caching and failure fallbacks", async () => {
const v = await readVector("turn");
const { IceConfig } = await load("lib/turn.js");
const creds = { username: "u", credential: "c", ttl: 3600, urls: ["stun:s", "turn:t?transport=udp"] };
const realFetch = globalThis.fetch;
const realNow = Date.now;
const realWarn = console.warn;
let now = 1_700_000_000_000;
Date.now = () => now;
console.warn = () => {};
const byLabel = Object.fromEntries(v.cases.map((c) => [c.label, c]));
try {
let fetches = 0;
globalThis.fetch = async () => {
fetches++;
return { ok: true, status: 200, json: async () => creds };
};
const ice = new IceConfig("https://signal.example/turn-credentials");
const eq = (label, config, f) => {
assert.deepEqual(JSON.parse(JSON.stringify(config)), byLabel[label].config, label);
if (byLabel[label].fetches !== undefined) assert.equal(f, byLabel[label].fetches, `${label}: fetch count`);
};
eq("first", await ice.get(), fetches);
eq("cached", await ice.get(), fetches);
now += 3600_000 - 300_000 - 1;
eq("still-cached", await ice.get(), fetches);
now += 2;
eq("refetched", await ice.get(), fetches);
fetches = 0;
const ice2 = new IceConfig("https://signal.example/turn-credentials");
const [a, b] = await Promise.all([ice2.get(), ice2.get()]);
assert.equal(a === b, byLabel["inflight-dedup"].same);
assert.equal(fetches, byLabel["inflight-dedup"].fetches);
const ice3 = new IceConfig("https://signal.example/turn-credentials", true);
eq("force-relay", await ice3.get());
globalThis.fetch = async () => {
throw new Error("offline");
};
eq("fetch-fails", await new IceConfig("https://signal.example/turn-credentials").get());
eq("fetch-fails-force-relay", await new IceConfig("https://signal.example/turn-credentials", true).get());
globalThis.fetch = async () => ({ ok: false, status: 500, json: async () => ({}) });
const ice6 = new IceConfig("https://signal.example/turn-credentials");
eq("not-ok", await ice6.get());
now += 29_000;
let f2 = 0;
globalThis.fetch = async () => {
f2++;
return { ok: true, status: 200, json: async () => creds };
};
eq("retry-window-not-expired", await ice6.get(), f2);
now += 2_000;
eq("retry-window-expired", await ice6.get(), f2);
} finally {
globalThis.fetch = realFetch;
Date.now = realNow;
console.warn = realWarn;
}
});
test("node env shims", async () => {
const v = await readVector("env");
const env = await load("node/env.js");
const set = env.selfPeerIds();
set.add("x");
assert.equal(env.selfPeerIds().has("x"), true);
assert.equal(globalThis.__ardegazuSelfPeers === set, true);
env.installBrowserGlobals();
assert.equal(globalThis.document.visibilityState, v.browserGlobals.visibilityState);
assert.equal(typeof globalThis.window.setTimeout, "function");
assert.equal(globalThis.window.addEventListener("x", () => {}), undefined);
const ls = globalThis.localStorage;
assert.equal(ls.getItem("k"), v.browserGlobals.localStorage.before);
ls.setItem("k", 42);
assert.equal(ls.getItem("k"), v.browserGlobals.localStorage.after);
ls.removeItem("k");
assert.equal(ls.getItem("k"), v.browserGlobals.localStorage.afterRemove);
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 };
};
env.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" } });
assert.deepEqual(seen, v.originFetch);
globalThis.fetch = realFetch;
env.installOrigin("https://chat.ardegazu.ro");
env.installOrigin("https://chat.ardegazu.ro");
assert.throws(() => env.installOrigin("https://board.ardegazu.ro"), (e) => e.message === v.installOriginConflict);
});
|