id-kit / test / bridge.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
// Bridge host + client integration on a hand-rolled DOM stub: the compiled
// host actually answers the compiled client over the same postMessage shapes,
// origin gates and CAS semantics the real iframe pair uses. The stub keeps
// TWO storages (apex origin vs app origin) switched synchronously around each
// dispatch, mirroring the browser's origin separation.
import test from "node:test";
import assert from "node:assert/strict";

const APP_ORIGIN = "https://chat.ardegazu.ro";
const BRIDGE_URL = "https://ardegazu.ro/id/";
const BRIDGE_ORIGIN = "https://ardegazu.ro";
const STORE_KEY = "ardegazu-id:v1";
const NS = "chat-ardegazu-ro-v2";

class FakeStorage {
  #m = new Map();
  getItem(k) { return this.#m.has(k) ? this.#m.get(k) : null; }
  setItem(k, v) { this.#m.set(k, String(v)); }
  removeItem(k) { this.#m.delete(k); }
  dump() { return Object.fromEntries(this.#m); }
}

function makeListenerHub() {
  const listeners = new Map(); // type -> Set<fn>
  return {
    addEventListener(type, fn) {
      if (!listeners.has(type)) listeners.set(type, new Set());
      listeners.get(type).add(fn);
    },
    removeEventListener(type, fn) { listeners.get(type)?.delete(fn); },
    dispatch(type, ev) { for (const fn of [...(listeners.get(type) ?? [])]) fn(ev); },
  };
}

// current world, swapped per test; the global getters below read through it
let world = null;

function makeWorld({ hostAnswers = true } = {}) {
  const w = {
    context: "client", // which origin the running code belongs to
    clientLS: new FakeStorage(),
    hostLS: new FakeStorage(),
    hostBroken: false, // simulate apex storage unavailable (private mode)
  };

  const clientHub = makeListenerHub();
  const hostHub = makeListenerHub();

  const inHost = (fn) => {
    const prev = w.context;
    w.context = "host";
    try { return fn(); } finally { w.context = prev; }
  };

  // the iframe's window, as the client sees it (contentWindow) and as the
  // host's global `window`
  const hostWin = {
    ...hostHub,
    parent: null, // set below
    postMessage(msg, _origin) {
      // client -> host request path
      queueMicrotask(() =>
        inHost(() => hostHub.dispatch("message", { origin: APP_ORIGIN, source: clientPort, data: msg })));
    },
    dispatchStorage(ev) { queueMicrotask(() => inHost(() => hostHub.dispatch("storage", ev))); },
  };

  // how the host addresses the client back (ev.source of requests)
  const clientPort = {
    postMessage(msg, origin) {
      // the payload-free id-ready announcement is the ONLY "*" post allowed
      if (msg?.t === "id-ready") assert.equal(origin, "*");
      else assert.equal(origin, APP_ORIGIN, "host must reply to the proven app origin");
      queueMicrotask(() => clientHub.dispatch("message", { origin: BRIDGE_ORIGIN, source: hostWin, data: msg }));
    },
  };
  hostWin.parent = clientPort;

  // the app page's window (the client's global `window`)
  const clientWin = { ...clientHub, parent: null };

  const doc = {
    body: {
      appendChild(_f) {
        if (!hostAnswers) return; // apex unreachable: nothing ever loads
        queueMicrotask(async () => {
          const { initBridgeHost } = await import("../dist/index.js");
          inHost(() => initBridgeHost());
        });
      },
    },
    documentElement: { appendChild() {} },
    createElement(tag) {
      assert.equal(tag, "iframe");
      return {
        hidden: false,
        src: "",
        contentWindow: hostWin,
        setAttribute() {},
        addEventListener() {},
        remove() {},
      };
    },
  };

  w.clientWin = clientWin;
  w.hostWin = hostWin;
  w.document = doc;
  return w;
}

for (const [name, get] of [
  ["window", () => (world?.context === "host" ? world?.hostWin : world?.clientWin)],
  ["document", () => world?.document],
  // the running code's own origin โ€” what appKey() derives its section from
  ["location", () => ({ origin: world?.context === "host" ? BRIDGE_ORIGIN : APP_ORIGIN })],
  ["localStorage", () => {
    if (!world) return undefined;
    if (world.context === "host") {
      if (world.hostBroken) throw new Error("storage unavailable");
      return world.hostLS;
    }
    return world.clientLS;
  }],
]) {
  Object.defineProperty(globalThis, name, { get, configurable: true });
}

const { IdBridge, SEED_RE, sanitizeRecord } = await import("../dist/index.js");

const newBridge = (opts = {}) => new IdBridge({ ns: NS, bridgeUrl: BRIDGE_URL, timeoutMs: 250, ...opts });
const hostRecord = () => {
  const raw = world.hostLS.getItem(STORE_KEY);
  return raw ? JSON.parse(raw) : null;
};

test("fresh world: boot mints a seed, publishes it, mirrors it", async () => {
  world = makeWorld();
  const b = newBridge();
  const r = await b.boot();
  assert.equal(r.source, "fresh");
  assert.equal(r.bridged, true);
  assert.equal(r.conflict, null);
  assert.match(r.seed, SEED_RE);
  assert.ok(r.identity, "identity derived");
  assert.equal(r.identity.publicKeyB64.length, 43);
  assert.deepEqual(r.profile, { name: "", hue: null, glyph: null, lang: null });
  // mirror written
  assert.equal(world.clientLS.getItem(`${NS}:id`), r.seed);
  // suite record published on the apex origin, exact stored key order
  const rec = hostRecord();
  assert.equal(rec.seed, r.seed);
  assert.deepEqual(Object.keys(rec),
    ["v", "seed", "name", "hue", "glyph", "lang", "soc", "apps", "createdAt", "updatedAt"]);
  assert.equal(rec.apps, null, "no app has claimed a section yet");
  // quirk preserved from the TS original: boot's own put reply does NOT
  // update lastRecord (only get/putProfile/putSoc state replies do)
  assert.equal(b.lastRecord(), null);
  await b.putProfile({});
  assert.equal(b.lastRecord().seed, r.seed);
  b.destroy();
});

test("bridge has a record, mirror empty: adopt", async () => {
  world = makeWorld();
  const seed = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";
  world.hostLS.setItem(STORE_KEY, JSON.stringify({
    v: 1, seed, name: "Ana", hue: 200, glyph: "๐ŸฆŠ", lang: "ro", soc: null,
    createdAt: 1756150000000, updatedAt: 1756160000000,
  }));
  const b = newBridge();
  const r = await b.boot();
  assert.equal(r.source, "bridge");
  assert.equal(r.seed, seed);
  assert.deepEqual(r.profile, { name: "Ana", hue: 200, glyph: "๐ŸฆŠ", lang: "ro" });
  assert.equal(world.clientLS.getItem(`${NS}:id`), seed);
  assert.equal(world.clientLS.getItem(`${NS}:name`), "Ana");
  assert.deepEqual(JSON.parse(world.clientLS.getItem(`${NS}:profile`)),
    { hue: 200, glyph: "๐ŸฆŠ", lang: "ro", ts: 1756160000000 });
  b.destroy();
});

test("mirror has a seed, bridge empty: publish claims the suite", async () => {
  world = makeWorld();
  const seed = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";
  world.clientLS.setItem(`${NS}:id`, seed);
  world.clientLS.setItem(`${NS}:name`, "Zed");
  world.clientLS.setItem(`${NS}:profile`, JSON.stringify({ hue: 33, glyph: null, lang: null, ts: 5 }));
  const b = newBridge();
  const r = await b.boot();
  assert.equal(r.source, "mirror");
  assert.equal(r.seed, seed);
  assert.equal(r.profile.name, "Zed");
  const rec = hostRecord();
  assert.equal(rec.seed, seed);
  assert.equal(rec.name, "Zed");
  assert.equal(rec.hue, 33);
  b.destroy();
});

test("different seeds: conflict surfaced, mirror kept; adopt/keep choosers", async () => {
  world = makeWorld();
  const mirrorSeed = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";
  const bridgeSeed = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
  world.clientLS.setItem(`${NS}:id`, mirrorSeed);
  world.hostLS.setItem(STORE_KEY, JSON.stringify({
    v: 1, seed: bridgeSeed, name: "Suite", hue: null, glyph: null, lang: null,
    soc: null, createdAt: 1, updatedAt: 2,
  }));
  let b = newBridge();
  let r = await b.boot();
  assert.equal(r.source, "mirror");
  assert.equal(r.seed, mirrorSeed, "never silently switch");
  assert.ok(r.conflict);
  assert.equal(r.conflict.seed, bridgeSeed);

  // keepLocalSeed: same bridge seed stops asking
  b.keepLocalSeed(r.conflict);
  b.destroy();
  b = newBridge();
  r = await b.boot();
  assert.equal(r.conflict, null, "dismissed seed no longer surfaces");
  assert.equal(r.seed, mirrorSeed);

  // adoptBridgeSeed: suite identity becomes local, old seed backed up
  const rec = sanitizeRecord(JSON.parse(world.hostLS.getItem(STORE_KEY)));
  b.adoptBridgeSeed(rec);
  assert.equal(world.clientLS.getItem(`${NS}:id`), bridgeSeed);
  assert.equal(world.clientLS.getItem(`${NS}:id-prev`), mirrorSeed);
  assert.equal(world.clientLS.getItem(`${NS}:id-conflict-dismissed`), null);
  b.destroy();
});

test("same seed: fresher bridge profile wins; fresher mirror pushes", async () => {
  world = makeWorld();
  const seed = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";
  // bridge fresher
  world.clientLS.setItem(`${NS}:id`, seed);
  world.clientLS.setItem(`${NS}:profile`, JSON.stringify({ hue: 1, glyph: null, lang: null, ts: 10 }));
  world.hostLS.setItem(STORE_KEY, JSON.stringify({
    v: 1, seed, name: "Fresh", hue: 99, glyph: null, lang: "hu", soc: null,
    createdAt: 1, updatedAt: 99999,
  }));
  let b = newBridge();
  let r = await b.boot();
  assert.equal(r.source, "mirror");
  assert.equal(r.profile.hue, 99, "bridge profile adopted");
  assert.equal(r.profile.lang, "hu");
  b.destroy();

  // mirror fresher: pushes to the bridge (fire and forget)
  const now = Date.now() + 60_000;
  world.clientLS.setItem(`${NS}:name`, "Newer");
  world.clientLS.setItem(`${NS}:profile`, JSON.stringify({ hue: 7, glyph: null, lang: "ro", ts: now }));
  b = newBridge();
  r = await b.boot();
  assert.equal(r.profile.hue, 7, "mirror kept");
  await new Promise((res) => setTimeout(res, 20)); // let the background push land
  const rec = hostRecord();
  assert.equal(rec.hue, 7, "bridge caught up");
  assert.equal(rec.name, "Newer");
  b.destroy();
});

test("putProfile / putSoc round-trip through the host CAS", async () => {
  world = makeWorld();
  const b = newBridge();
  const r = await b.boot();
  await b.putProfile({ name: "Kilroy", hue: 123.9 });
  let rec = hostRecord();
  assert.equal(rec.name, "Kilroy");
  assert.equal(rec.hue, 123, "clamped by the host too");
  assert.equal(rec.seed, r.seed, "CAS on the same seed");
  assert.equal(world.clientLS.getItem(`${NS}:name`), "Kilroy");

  assert.equal(await b.putSoc({ friends: ["fp1"] }), true);
  rec = hostRecord();
  assert.deepEqual(rec.soc, { friends: ["fp1"] });
  assert.equal(rec.name, "Kilroy", "soc write leaves profile alone");

  // an oversize soc blob is refused (conflict), nothing written
  assert.equal(await b.putSoc("x".repeat(129 * 1024)), false);
  assert.deepEqual(hostRecord().soc, { friends: ["fp1"] });
  b.destroy();
});

test("putAppState: this origin's section round-trips; other writes preserve it", async () => {
  world = makeWorld();
  const b = newBridge();
  const r = await b.boot();
  assert.equal(b.appKey(), "chat", "the key comes from the app's own origin");
  assert.equal(await b.putAppState({ banks: ["ing"] }), true);
  let rec = hostRecord();
  assert.deepEqual(Object.keys(rec.apps), ["chat"]);
  assert.deepEqual(rec.apps.chat.state, { banks: ["ing"] });
  assert.ok(rec.apps.chat.ts > 0, "ts stamped by the host");
  assert.deepEqual(Object.keys(rec.apps.chat), ["state", "ts"]);
  // readers: our own and (absent) other apps' sections, off the last record
  assert.deepEqual(b.appStateOf("chat"), { banks: ["ing"] });
  assert.equal(b.appStateOf("banca"), null, "no section yet");
  assert.deepEqual(b.lastRecord().apps.chat.state, { banks: ["ing"] });

  // every other write path must carry the section through untouched
  await b.putProfile({ name: "Kilroy" });
  assert.deepEqual(hostRecord().apps.chat.state, { banks: ["ing"] }, "profile write");
  assert.equal(await b.putSoc({ friends: ["fp1"] }), true);
  assert.deepEqual(hostRecord().apps.chat.state, { banks: ["ing"] }, "soc write");
  assert.equal(await b.publishSeed(r.seed, { force: true }), true);
  assert.deepEqual(hostRecord().apps.chat.state, { banks: ["ing"] },
    "a same-seed put (which sends apps:null) does not wipe sections");
  assert.equal(hostRecord().name, "Kilroy", "the put carried the mirror profile");
  assert.equal(hostRecord().soc, null,
    "soc, unlike apps, still follows the put payload โ€” deliberate asymmetry");

  // null deletes; the last section gone collapses the field to null
  assert.equal(await b.putAppState(null), true);
  assert.equal(hostRecord().apps, null);
  assert.equal(b.appStateOf("chat"), null);
  b.destroy();
});

test("putAppState offline / seedless: false, nothing mirrored", async () => {
  world = makeWorld({ hostAnswers: false });
  const b = newBridge({ timeoutMs: 40 });
  await b.boot();
  assert.equal(await b.putAppState({ x: 1 }), false, "online-only, no local fallback");
  assert.deepEqual(world.clientLS.dump()[`${NS}:apps`], undefined, "no mirror key invented");
  b.destroy();
});

test("bridge unreachable: mirror-only boot, then fresh mint offline", async () => {
  world = makeWorld({ hostAnswers: false });
  const seed = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";
  world.clientLS.setItem(`${NS}:id`, seed);
  let b = newBridge({ timeoutMs: 40 });
  let r = await b.boot();
  assert.equal(r.source, "mirror");
  assert.equal(r.bridged, false);
  assert.equal(r.seed, seed);
  b.destroy();

  world = makeWorld({ hostAnswers: false });
  b = newBridge({ timeoutMs: 40 });
  r = await b.boot();
  assert.equal(r.source, "fresh");
  assert.equal(r.bridged, false);
  assert.match(r.seed, SEED_RE);
  assert.equal(world.clientLS.getItem(`${NS}:id`), r.seed, "offline mint mirrored");
  await new Promise((res) => setTimeout(res, 60)); // background publish retry fails quietly
  b.destroy();
});

test("host CAS: stale expect conflicts, nothing written", async () => {
  world = makeWorld();
  const b = newBridge();
  const r = await b.boot();
  const before = hostRecord();
  // publishSeed without force expects an empty bridge -> conflict -> false
  const other = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
  assert.equal(await b.publishSeed(other), false);
  assert.equal(hostRecord().seed, before.seed, "record untouched");
  // refresh lastRecord (boot's own put reply never updates it โ€” TS quirk),
  // then force: expect = last seen seed -> overwrite succeeds
  await b.putProfile({});
  assert.equal(await b.publishSeed(other, { force: true }), true);
  assert.equal(hostRecord().seed, other);
  assert.equal(r.seed !== other, true);
  b.destroy();
});

test("storage event: proven client gets an unsolicited push; onChange fires; mirror absorbs", async () => {
  world = makeWorld();
  const b = newBridge();
  const r = await b.boot();
  const pushed = [];
  const off = b.onChange((rec) => pushed.push(rec));
  // the hub (apex page) writes the suite record directly; the host observes
  // the storage event and pushes to its proven client
  const newer = {
    v: 1, seed: r.seed, name: "FromHub", hue: 250, glyph: null, lang: null,
    soc: null, createdAt: Date.now(), updatedAt: Date.now() + 99999,
  };
  world.hostLS.setItem(STORE_KEY, JSON.stringify(newer));
  world.hostWin.dispatchStorage({ key: STORE_KEY });
  await new Promise((res) => setTimeout(res, 20));
  assert.equal(pushed.length, 1);
  assert.equal(pushed[0].name, "FromHub");
  assert.equal(b.lastRecord().name, "FromHub");
  assert.equal(world.clientLS.getItem(`${NS}:name`), "FromHub", "mirror absorbed fresher push");
  off();
  world.hostWin.dispatchStorage({ key: STORE_KEY });
  await new Promise((res) => setTimeout(res, 20));
  assert.equal(pushed.length, 1, "unsubscribed");
  b.destroy();
});

test("host origin gate: a disallowed origin is ignored outright", async () => {
  world = makeWorld();
  const b = newBridge();
  await b.boot();
  // forge a message from an evil origin straight into the host
  let answered = false;
  const evil = { postMessage() { answered = true; } };
  world.hostWin.postMessage = undefined; // not used here
  const forge = { origin: "https://ardegazu.ro.evil.com", source: evil, data: { t: "get", v: 1, reqId: 99 } };
  world.context = "host";
  world.hostWin.dispatch("message", forge);
  world.context = "client";
  await new Promise((res) => setTimeout(res, 20));
  assert.equal(answered, false, "no reply crosses the origin gate");
  b.destroy();
});

test("private mode: host storage broken -> ephemeral in-memory record", async () => {
  world = makeWorld();
  world.hostBroken = true;
  const b = newBridge();
  const r = await b.boot();
  assert.equal(r.bridged, true);
  assert.equal(r.source, "fresh");
  assert.equal(world.hostLS.getItem(STORE_KEY), null, "nothing persisted");
  // the record still lives for the session, in the host's memory
  await b.putProfile({});
  assert.equal(b.lastRecord().seed, r.seed);
  b.destroy();
});

static mirror of HEAD ยท about ยท clone: git clone https://git.ardegazu.ro/id-kit.git