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 | // Golden vectors extracted from the TypeScript implementation while it was
// canon — the compat contract this dist must reproduce exactly: byte-exact
// Ed25519 signatures under the deployed "sueta-id|v2" tag, HKDF/X25519
// derivations, "board-x25519|v1" certs, profile clamping, and the bridge's
// record/message shapes. Random-IV sealing is proven by the committed
// TS-sealed fixtures (TS seals -> this dist unseals) plus a live roundtrip.
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import {
utf8, toB64, fromB64, toB64url, fromB64url,
Identity, verifyRaw, verifyAssertion, fingerprintOf, isEd25519Supported,
hueOfPub, effectiveHue, colorOfPub, defaultGlyph, clampProfile, EMPTY_PROFILE, MAX_NAME_LEN,
BRIDGE_PATH, DEFAULT_BRIDGE_URL, BRIDGE_STORE_KEY, MAX_RECORD_BYTES, MAX_APP_STATE_BYTES,
RESERVED_CORE_BYTES, MAX_APPS_BYTES,
SEED_RE, APP_ORIGIN_RE, APP_KEY_RE, RESERVED_APP_KEYS, DEV_ORIGINS,
isAllowedAppOrigin, appKeyOfOrigin,
isBridgeReply, isBridgeRequest,
sanitizeRecord,
} from "../dist/index.js";
import {
SUITE_SALT, deriveXKeyPair, deriveSuiteXKeyPair, signXCert, verifyXCert, wrapTo, unwrap,
} from "../dist/xkey.js";
const VEC = join(dirname(fileURLToPath(import.meta.url)), "vectors");
const load = (name) => JSON.parse(readFileSync(join(VEC, name), "utf8"));
test("crypto: b64/b64url primitives match and roundtrip", () => {
const { b64, utf8: utf8Cases } = load("crypto.json");
for (const c of b64) {
const bytes = Uint8Array.from(c.bytes);
assert.equal(toB64(bytes), c.b64);
assert.equal(toB64url(bytes), c.b64url);
assert.deepEqual([...fromB64(c.b64)], c.bytes);
assert.deepEqual([...fromB64url(c.b64url)], c.bytes);
}
for (const c of utf8Cases) assert.deepEqual([...utf8(c.s)], c.bytes);
});
test("identity: runtime supports Ed25519", async () => {
assert.equal(await isEd25519Supported(), true);
});
test("identity: seeds -> pubs, fingerprints, byte-exact assertion signatures", async () => {
const { cases } = load("identity.json");
for (const c of cases) {
const id = await Identity.fromSeed(c.seed);
assert.equal(id.publicKeyB64, c.publicKeyB64, c.name);
assert.deepEqual({ ...id.fingerprint }, c.fingerprint, c.name);
assert.deepEqual({ ...(await fingerprintOf(c.publicKeyB64)) }, c.fingerprint, c.name);
for (const a of c.assertions) {
// Ed25519 is deterministic: the signature must be byte-identical to
// what the deployed TS implementation produced
assert.equal(await id.assert(a.appSalt, a.roomId, a.peerId), a.sigB64, `${c.name} ${a.roomId}`);
}
assert.equal(toB64url(await id.signRaw(utf8(c.raw.dataUtf8))), c.raw.sigB64url, `${c.name} raw`);
assert.equal(await verifyRaw(c.publicKeyB64, c.raw.sigB64url, utf8(c.raw.dataUtf8)), true);
assert.equal(await verifyRaw(c.publicKeyB64, c.raw.sigB64url, utf8("tampered")), false);
}
});
test("identity: malformed seeds reject", async () => {
await assert.rejects(() => Identity.fromSeed("AAAA"));
assert.match(Identity.newSeed(), /^[A-Za-z0-9_-]{43}$/);
});
test("identity: verifyAssertion accept/reject table", async () => {
const { verifyAssertion: cases } = load("identity.json");
for (const c of cases) {
const got = await verifyAssertion(...c.args);
assert.equal(got !== null, c.ok, c.desc);
if (c.ok) assert.equal(got.hex.length, 64);
}
});
test("xkey: deterministic derivations + byte-exact certs", async () => {
const { cases } = load("xkey.json");
for (const c of cases) {
const id = await Identity.fromSeed(c.seed);
assert.equal(id.publicKeyB64, c.idPub);
for (const side of [c.suite, c.other]) {
const kp = await deriveXKeyPair(c.seed, side.salt);
assert.equal(toB64url(kp.priv), side.privB64url, `${c.name} ${side.salt} priv`);
assert.equal(kp.pubB64, side.pubB64, `${c.name} ${side.salt} pub`);
assert.equal(await signXCert(id, side.salt, kp.pubB64), side.certB64url, `${c.name} cert`);
assert.equal(await verifyXCert(side.salt, c.idPub, kp.pubB64, side.certB64url), true);
}
// suite helper = SUITE_SALT derivation; certs are salt-bound
assert.equal((await deriveSuiteXKeyPair(c.seed)).pubB64, c.suite.pubB64);
assert.equal(await verifyXCert(c.other.salt, c.idPub, c.suite.pubB64, c.suite.certB64url), false);
}
});
test("xkey: TS-sealed fixtures unseal here (cross-implementation)", async () => {
const { sealed } = load("xkey.json");
for (const s of sealed) {
const kp = await deriveXKeyPair(s.recipientSeed, s.salt);
const pt = await unwrap(s.salt, s.ctx, s.wrap, kp);
assert.notEqual(pt, null, s.name);
assert.equal(new TextDecoder().decode(pt), s.payloadUtf8, s.name);
// bound to ctx and recipient
assert.equal(await unwrap(s.salt, "other-ctx", s.wrap, kp), null, `${s.name} ctx`);
const stranger = await deriveXKeyPair("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", s.salt);
assert.equal(await unwrap(s.salt, s.ctx, s.wrap, stranger), null, `${s.name} recipient`);
}
});
test("xkey: live wrap roundtrip (fresh random IVs)", async () => {
const { cases } = load("xkey.json");
const c = cases.find((x) => x.name === "counting");
const kp = await deriveSuiteXKeyPair(c.seed);
const w = await wrapTo(SUITE_SALT, "ctx-live", c.idPub, kp.pubB64, utf8("salut 🦊"));
assert.equal(w.to, c.idPub);
assert.equal(w.toX, kp.pubB64);
assert.deepEqual(Object.keys(w), ["to", "toX", "ephPub", "iv", "ct"]);
const pt = await unwrap(SUITE_SALT, "ctx-live", w, kp);
assert.equal(new TextDecoder().decode(pt), "salut 🦊");
assert.equal(await unwrap(SUITE_SALT, "ctx-other", w, kp), null);
});
test("profile: hueOfPub / effectiveHue / colorOfPub match", () => {
const v = load("profile.json");
assert.equal(MAX_NAME_LEN, v.maxNameLen);
assert.deepEqual({ ...EMPTY_PROFILE }, v.emptyProfile);
for (const c of v.hueOfPub) assert.equal(hueOfPub(c.input), c.hue, JSON.stringify(c.input));
for (const c of v.effectiveHue) assert.equal(effectiveHue(c.pub, c.profile), c.hue, JSON.stringify(c.profile));
for (const c of v.colorOfPub) assert.equal(colorOfPub(c.pub, c.profile), c.color);
});
test("profile: clampProfile edge cases match", () => {
const { clampProfile: cases } = load("profile.json");
for (const c of cases) {
// NaN/Infinity don't survive JSON — rebuild those inputs
const input = c.desc === "hue NaN" ? { hue: NaN } : c.desc === "hue Infinity" ? { hue: Infinity } : c.input;
assert.deepEqual({ ...clampProfile(input) }, c.output, c.desc);
}
});
test("profile: defaultGlyph matches", async () => {
const { defaultGlyph: cases } = load("profile.json");
for (const c of cases) assert.equal(await defaultGlyph(c.pub), c.glyph, c.name);
});
test("bridge protocol: constants and regexes", () => {
const { constants } = load("bridge.json");
assert.equal(BRIDGE_PATH, constants.BRIDGE_PATH);
assert.equal(DEFAULT_BRIDGE_URL, constants.DEFAULT_BRIDGE_URL);
assert.equal(BRIDGE_STORE_KEY, constants.BRIDGE_STORE_KEY);
assert.equal(MAX_RECORD_BYTES, constants.MAX_RECORD_BYTES);
assert.equal(MAX_APP_STATE_BYTES, constants.MAX_APP_STATE_BYTES);
assert.equal(RESERVED_CORE_BYTES, constants.RESERVED_CORE_BYTES);
assert.equal(MAX_APPS_BYTES, constants.MAX_APPS_BYTES);
// the sections' budget stops short of the record's, and that gap is the
// reserve only `soc`/profile can spend — the invariant, not just the numbers
assert.equal(MAX_APPS_BYTES, MAX_RECORD_BYTES - RESERVED_CORE_BYTES);
assert.ok(MAX_APP_STATE_BYTES * 2 <= MAX_APPS_BYTES,
"two apps at the per-entry cap must not be able to spend the whole budget");
assert.deepEqual([...RESERVED_APP_KEYS], ["home", "dev"]);
assert.equal(SEED_RE.source, constants.seedRe);
assert.equal(APP_KEY_RE.source, constants.appKeyRe);
assert.deepEqual([...DEV_ORIGINS], [
"http://localhost:4173", "http://localhost:5173",
"http://127.0.0.1:4173", "http://127.0.0.1:5173",
]);
assert.ok(APP_ORIGIN_RE instanceof RegExp);
});
test("bridge protocol: origin allowlist and seed regex tables", () => {
const v = load("bridge.json");
for (const c of v.isAllowedAppOrigin) assert.equal(isAllowedAppOrigin(c.origin), c.allowed, c.origin);
for (const c of v.seedRe) assert.equal(SEED_RE.test(c.s), c.ok, JSON.stringify(c.s));
});
test("bridge protocol: appKeyOfOrigin truth table", () => {
const v = load("bridge.json");
for (const c of v.appKeyOfOrigin)
assert.equal(appKeyOfOrigin(c.origin), c.key, JSON.stringify(c.origin));
// ONE direction only: a key implies an allowed origin. The converse is
// false — an allowed origin whose label is over-long, or is a reserved
// label, passes the gate and still derives no key (so it has no section).
for (const c of v.isAllowedAppOrigin)
if (appKeyOfOrigin(c.origin) !== null)
assert.equal(c.allowed, true, `${c.origin} derives a key but is not allowed`);
const longLabel = `https://${"a".repeat(33)}.ardegazu.ro`;
assert.equal(isAllowedAppOrigin(longLabel), true, "a 33-char label passes the gate…");
assert.equal(appKeyOfOrigin(longLabel), null, "…but derives no key");
// reserved labels: neither host exists, and neither may ever claim the key
// the apex hub / the dev origins already own
for (const k of RESERVED_APP_KEYS) {
assert.equal(isAllowedAppOrigin(`https://${k}.ardegazu.ro`), true);
assert.equal(appKeyOfOrigin(`https://${k}.ardegazu.ro`), null, `${k} is reserved`);
}
assert.equal(appKeyOfOrigin("https://ardegazu.ro"), "home", "the apex still owns home");
assert.equal(appKeyOfOrigin("http://localhost:5173"), "dev", "dev origins still own dev");
// undefined and non-strings never derive a key
for (const x of [undefined, 42, {}, ["https://ardegazu.ro"]])
assert.equal(appKeyOfOrigin(x), null, JSON.stringify(x) ?? "undefined");
for (const c of v.appKeyOfOrigin)
if (c.key !== null) assert.equal(APP_KEY_RE.test(c.key), true, c.key);
});
test("bridge protocol: message guards", () => {
const v = load("bridge.json");
for (const c of v.isBridgeReply) assert.equal(isBridgeReply(c.m), c.ok, JSON.stringify(c.m));
for (const c of v.isBridgeRequest) assert.equal(isBridgeRequest(c.m), c.ok, JSON.stringify(c.m));
// `state` must be an OWN property: `in` walks the prototype chain, so a
// polluted Object.prototype would make every `app` message look well-formed
const seed = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";
const noState = { t: "app", v: 1, reqId: 1, expect: seed };
Object.defineProperty(Object.prototype, "state", {
value: 1, configurable: true, writable: true, enumerable: false,
});
try {
assert.equal(isBridgeRequest(noState), false, "an INHERITED `state` does not count");
} finally {
delete Object.prototype.state;
}
assert.equal(isBridgeRequest({ ...noState, state: null }), true, "an own `state` does");
});
test("bridge host: sanitizeRecord matches, including exact key order", () => {
const v = load("bridge.json");
for (const c of v.sanitizeRecord) {
const got = sanitizeRecord(c.input);
if (c.output === null) assert.equal(got, null, c.desc);
else {
assert.deepEqual({ ...got }, c.output, c.desc);
// the apex record is serialized with JSON.stringify — key order is part
// of the byte-level storage shape, nested `apps` entries included
assert.deepEqual(Object.keys(got), Object.keys(c.output), `${c.desc} key order`);
assert.equal(JSON.stringify(got), JSON.stringify(c.output), `${c.desc} serialized bytes`);
}
}
for (const c of v.sanitizeRecordNow) {
const got = sanitizeRecord(c.input);
assert.notEqual(got, null, c.desc);
for (const k of c.nonDeterministic) assert.ok(got[k] > 0, `${c.desc} ${k} -> now`);
}
});
test("bridge host: an oversize apps entry is dropped, its siblings survive", () => {
const seed = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";
const at = (n) => ({ state: "x".repeat(n), ts: 5 });
// JSON adds the two quotes, so the cap is hit one char before it
const got = sanitizeRecord({
seed, createdAt: 1, updatedAt: 1,
apps: { big: at(MAX_APP_STATE_BYTES), edge: at(MAX_APP_STATE_BYTES - 2), small: at(1) },
});
assert.deepEqual(Object.keys(got.apps), ["edge", "small"], "only the oversize entry dropped");
// a state that cannot be JSON'd at all is dropped too (cycle, undefined)
const cyclic = {}; cyclic.self = cyclic;
const got2 = sanitizeRecord({
seed, createdAt: 1, updatedAt: 1,
apps: { loop: { state: cyclic, ts: 5 }, gone: { state: undefined, ts: 5 }, ok: at(1) },
});
assert.deepEqual(Object.keys(got2.apps), ["ok"]);
});
test("bridge host: the stored ten-field shape is byte-exact", () => {
const { hostShape } = load("bridge.json");
assert.equal(BRIDGE_STORE_KEY, hostShape.key);
assert.equal(JSON.stringify(sanitizeRecord(hostShape.input)), hostShape.value);
});
|