chat / client / test / vectors.test.mjs
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
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
/**
 * Golden-vector checks for the rooms core: ardegazu-rooms-kit's
 * ardegazu.rooms.lib.* on the classpath, plus what is still app-local under
 * client/src/sueta/lib/ (mailbox, media, selftest).
 *
 * Provenance: `vectors/rk-*.json` are rooms-kit's fixtures, copied verbatim.
 * chat's lib/{access,crypto,descriptor,encryption,protocol,turn}.ts were
 * BYTE-IDENTICAL to rooms-kit's pre-CLJS ancestors, and lib/{log,net,
 * orbit-identity}.ts differed only by the three sanctioned browser deltas
 * (IDB stores, no selfPeerIds, no wsOrigin) — so those fixtures describe chat's
 * TypeScript exactly, and this file was run green against it (`SUETA_TS=1`)
 * before the port landed, which is what makes the copy trustworthy.
 *
 * Two of those three deltas are HISTORY as of the kit-adoption pass: lib/net
 * now carries the kit's selfPeerIds registry and wsOrigin option verbatim (both
 * no-ops in a tab), and lib/log's open-helia takes already-open stores, with the
 * IndexedDB pair built in the app-local <app>.stores namespace. lib/log and
 * lib/net are byte-identical to rooms-kit's modulo the namespace rename, so
 * these fixtures now describe BOTH implementations.
 *
 * 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 { installDom } from "./harness/dom.mjs";
import { mods, readVector, hex, fromHex, json } from "./helpers/load.mjs";
import { installDetRandom, resetRandom, restoreRandom } from "./helpers/det-random.mjs";

installDom();
const M = await mods();
const te = new TextEncoder();
const td = new TextDecoder();

test("base64 / base64url primitives", () => {
  const v = readVector("rk-crypto");
  for (const c of v.b64) {
    const u8 = new Uint8Array(c.bytes);
    assert.equal(M.toB64(u8), c.b64, `toB64 ${c.bytes}`);
    assert.equal(M.toB64url(u8), c.b64url, `toB64url ${c.bytes}`);
    assert.deepEqual([...M.fromB64(c.b64)], c.roundTrip);
    assert.deepEqual([...M.fromB64url(c.b64url)], c.roundTripUrl);
  }
});

test("room derivations are byte-exact (PROTOCOL.md §2)", async () => {
  const v = readVector("rk-crypto");
  for (const d of v.derivations) {
    const rc = await M.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 = readVector("rk-crypto");
  const short = M.toB64url(new Uint8Array(15).fill(1));
  await assert.rejects(() => M.RoomCrypto.create(short, "x", "p"), (e) => e.message === v.tooShort);
  const anon = await M.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(M.newPeerId()), v.newPeerIdShape);
  assert.equal(M.newRoomSecret().length, v.newRoomSecretShape.length);
  assert.equal(/^[A-Za-z0-9_-]{43}$/.test(M.newRoomSecret()), v.newRoomSecretShape.chars);
});

test("Sealer IVs: fixed epoch, big-endian counter from zero", async () => {
  const v = readVector("rk-crypto");
  installDetRandom();
  try {
    resetRandom(11);
    const rc = await M.RoomCrypto.create("A".repeat(43), "chat.ardegazu.ro/v2", "12D3KooWFixedPeerId");
    const ivs = [];
    for (let i = 0; i < 4; i++) ivs.push(M.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);
    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 = readVector("rk-crypto");
  installDetRandom();
  try {
    resetRandom(11);
    const rc = await M.RoomCrypto.create("A".repeat(43), "chat.ardegazu.ro/v2", "12D3KooWSender");
    assert.deepEqual(
      json(await rc.sealSignal("12D3KooWRecipient", { kind: "offer", sdp: "v=0", name: "a" })),
      v.envelopes.signal,
    );
    assert.deepEqual(
      json(await rc.sealMsg({ kind: "presence", op: "beacon", name: "a", ts: 1700000000000 })),
      v.envelopes.msg1,
    );
    assert.deepEqual(json(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 = readVector("rk-crypto");
  installDetRandom();
  try {
    resetRandom(23);
    const rc = await M.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 = readVector("rk-crypto");
  const secretA = "A".repeat(43);
  const secretB = M.toB64url(new Uint8Array([...Array(32).keys()]));
  const rcA = await M.RoomCrypto.create(secretA, "chat.ardegazu.ro/v2", "PEER-A");
  const rcAasB = await M.RoomCrypto.create(secretA, "chat.ardegazu.ro/v2", "PEER-B");
  const rcOtherRoom = await M.RoomCrypto.create(secretB, "chat.ardegazu.ro/v2", "PEER-A");
  const rcOtherSalt = await M.RoomCrypto.create(secretA, "board.ardegazu.ro/v1", "PEER-A");
  const env = await rcA.sealMsg({ hello: 1 });
  assert.deepEqual(json(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(json(await rcAasB.openSignal("PEER-A", sig)), v.sigBinding.correctRecipient);
  const rcC = await M.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);
  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 = readVector("rk-crypto");
  const rc = await M.RoomCrypto.create("A".repeat(43), "chat.ardegazu.ro/v2", "PEER-A");
  const junk = { v: 1, iv: M.toB64(new Uint8Array(12)), ct: M.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 M.RoomCrypto.create("A".repeat(43), "chat.ardegazu.ro/v2", "PEER-A");
  assert.deepEqual(json(await rc.openMsg("PEER-A", await rc2.sealMsg({ still: "works" }))), v.keyCacheBounded.worksAfterEviction);
});

test("Sealer and AtRestCipher used directly", async () => {
  const v = readVector("rk-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 M.Sealer(key);
    const aad = te.encode("aad|1");
    assert.deepEqual(json(await s.seal({ a: 1 }, aad)), v.rawSealer.first);
    assert.deepEqual(json(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 M.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: this build opens what the TypeScript sealed", async () => {
  const v = readVector("rk-crypto").crossImpl;
  const rc = await M.RoomCrypto.create(v.secret, v.appSalt, "12D3KooWReader");
  assert.deepEqual(json(await rc.openMsg(v.senderPeerId, v.msg.envelope)), v.msg.plaintext);

  const rcTo = await M.RoomCrypto.create(v.secret, v.appSalt, v.signal.to);
  assert.deepEqual(json(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: a real-random seal opens under a second RoomCrypto", async () => {
  const rcA = await M.RoomCrypto.create("R".repeat(43), "chat.ardegazu.ro/v2", "PEER-SEND");
  const rcB = await M.RoomCrypto.create("R".repeat(43), "chat.ardegazu.ro/v2", "PEER-RECV");
  const payload = { kind: "presence", op: "beacon", name: "cljs", ts: 1700000000000 };
  assert.deepEqual(json(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 = readVector("rk-encryption");
  const rc = await M.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 M.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 M.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 = readVector("rk-encryption").crossImpl;
  const rc = await M.RoomCrypto.create(v.secret, v.appSalt, "12D3KooWAnyone");
  const enc = await M.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 = readVector("rk-orbit-identity");
  const id = await import("ardegazu-id-kit");
  for (const p of v.providers) {
    const identity = await id.Identity.fromSeed(p.seed);
    assert.equal(identity.publicKeyB64, p.pub);
    assert.deepEqual(json(identity.fingerprint), p.fingerprint);
    const provider = await M.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(M.SuetaIdentityProvider.type, v.staticType);

  const rec = v.verifyIdentity.record;
  assert.equal(await M.SuetaIdentityProvider.verifyIdentity(rec), v.verifyIdentity.good);
  assert.equal(await M.SuetaIdentityProvider.verifyIdentity({ ...rec, publicKey: "other" }), v.verifyIdentity.tamperedPublicKey);
  assert.equal(
    await M.SuetaIdentityProvider.verifyIdentity({ ...rec, signatures: { ...rec.signatures, id: "other" } }),
    v.verifyIdentity.tamperedSigId,
  );
  assert.equal(
    await M.SuetaIdentityProvider.verifyIdentity({ ...rec, id: M.toB64url(new Uint8Array(32).fill(9)) }),
    v.verifyIdentity.wrongId,
  );
  assert.equal(
    await M.SuetaIdentityProvider.verifyIdentity({ ...rec, signatures: { ...rec.signatures, publicKey: "!!!" } }),
    v.verifyIdentity.garbageSig,
  );
  // registration with OrbitDB's registry is idempotent
  M.registerSuetaProvider();
  M.registerSuetaProvider();
});

test("the hardened access controller closes the authorship-forgery gap", async () => {
  const v = readVector("rk-access");
  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 M.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 M.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 = readVector("rk-descriptor");
  const DEFAULTS = {
    relayMultiaddr: "/dns4/signal.example/tcp/443/tls/ws/p2p/12D3KooRELAY",
    turnCredsUrl: "https://signal.example/turn-credentials",
    discoveryTopic: "_peer-discovery._p2p._pubsub",
  };
  const jsonRes = (body, ok = true, status = 200) => async () => ({ ok, status, json: async () => body });
  const CASES = {
    "no-dns4-multiaddr": [{ ...DEFAULTS, relayMultiaddr: "/ip4/127.0.0.1/tcp/9090/ws/p2p/12D3KooDEV" }, jsonRes({})],
    "fetch-throws": [DEFAULTS, async () => { throw new Error("offline"); }],
    "not-ok": [DEFAULTS, jsonRes({}, false, 502)],
    "empty-descriptor": [DEFAULTS, jsonRes({})],
    "full-descriptor": [DEFAULTS, jsonRes({
      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, jsonRes({ mailbox: { endpoint: "https://x/mbx" } })],
    "mailbox-default-kb": [DEFAULTS, jsonRes({ 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 } },
      jsonRes({}),
    ],
    "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 M.resolveRelayConfig(defaults);
      assert.deepEqual(urls, c.urls, `${c.label}: fetch urls`);
      assert.deepEqual(json(got), c.result, `${c.label}: config`);
    }
  } finally {
    globalThis.fetch = realFetch;
  }
});

test("TURN credential caching and failure fallbacks", async () => {
  const v = readVector("rk-turn");
  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 M.IceConfig("https://signal.example/turn-credentials");
    const eq = (label, config, f) => {
      assert.deepEqual(json(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 M.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 M.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 M.IceConfig("https://signal.example/turn-credentials").get());
    eq("fetch-fails-force-relay", await new M.IceConfig("https://signal.example/turn-credentials", true).get());

    globalThis.fetch = async () => ({ ok: false, status: 500, json: async () => ({}) });
    const ice6 = new M.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;
  }
});

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/chat.git