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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841 | /**
* Golden-vector computation against the current implementation — originally
* the v1.2.0 TypeScript sources (which the committed fixtures were extracted
* from); since the CLJS port it recomputes from the committed dist/, which
* must keep every fixture green.
*
* This module derives every DETERMINISTIC value the wire-compat fixtures
* assert on. It is shared by:
* - generate.mjs — writes/refreshes test/vectors/*.json (adds the sealed,
* randomized-IV blobs on top of the deterministic sections);
* - vectors.test.mjs — recomputes everything and deep-compares against the
* committed fixtures, then opens the committed sealed blobs.
*
* All seeds/timestamps below are FIXED, documented test constants. They are
* test-only material; nothing here is a real identity.
*
* NOTE for the CLJS port: the canon-case inputs that JSON cannot represent
* faithfully (-0, NaN, undefined, Date, typed arrays, lone surrogates) are
* constructed in code here; each fixture row carries an `input_desc` (and
* `input_json` where faithful) so the port can rebuild the same inputs.
*/
import {
canon,
sha256B64url,
hkdfId,
openEnvelope,
pairChannel,
selfChannel,
inboxRoomId,
envCtx,
roomHash,
receiptHash,
signReceipt,
verifyReceipt,
isoWeek,
lbRoomId,
lbTopic,
MIN_SIGNERS,
SOCIAL_SALT,
ENV_DEFAULT_TTL_MS,
INVITE_TTL_MS,
SEEN_ENV_CAP,
BLOCKED_CAP,
RECEIPTS_CAP,
AP2P_DESCRIPTOR_URL,
MAILBOX_URL_FALLBACK,
MAILBOX_CREDS_URL_FALLBACK,
SUITE_APPS,
buildFriendLink,
parseFriendLink,
sanitizeFriend,
sanitizeProfileSync,
foldProfileSync,
sanitizeAppsSync,
foldAppsSync,
enText,
mkT,
} from "../../dist/index.js";
import { Identity, toB64url, utf8 } from "ardegazu-id-kit";
import { SUITE_SALT, deriveSuiteXKeyPair, signXCert } from "ardegazu-id-kit/xkey";
// ---- fixed test constants ---------------------------------------------------
const seedBytes = (fill) => {
const b = new Uint8Array(32);
if (typeof fill === "number") b.fill(fill);
else for (let i = 0; i < 32; i++) b[i] = fill(i);
return b;
};
export const SEED_A = toB64url(seedBytes((i) => i)); // bytes 00..1f
export const SEED_B = toB64url(seedBytes((i) => 32 + i)); // bytes 20..3f
export const SEED_P1 = toB64url(seedBytes(0x11));
export const SEED_P2 = toB64url(seedBytes(0x22));
export const SEED_P3 = toB64url(seedBytes(0x33));
/** 2025-01-01T00:00:00Z — the fixed "match/envelope time" of every fixture. */
export const TS_FIXED = 1735689600000;
/** 2100-01-01T00:00:00Z — far-future exp so sealed fixtures never expire. */
export const EXP_FAR = 4102444800000;
/** Fixed envelope id: b64url of bytes 01..10 (16 bytes). */
export const ENV_ID_FIXED = toB64url(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]));
const hex = (bytes) => [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
const utf8Hex = (s) => hex(utf8(s));
// ---- identities -------------------------------------------------------------
export async function actors() {
const [idA, idB, idP1, idP2, idP3] = await Promise.all(
[SEED_A, SEED_B, SEED_P1, SEED_P2, SEED_P3].map((s) => Identity.fromSeed(s)),
);
const [xA, xB] = await Promise.all([deriveSuiteXKeyPair(SEED_A), deriveSuiteXKeyPair(SEED_B)]);
const [xCertA, xCertB] = await Promise.all([signXCert(idA, SUITE_SALT, xA.pubB64), signXCert(idB, SUITE_SALT, xB.pubB64)]);
return { idA, idB, idP1, idP2, idP3, xA, xB, xCertA, xCertB };
}
// ---- canon cases ------------------------------------------------------------
/**
* Every branch of canon.ts's stringify, plus the quirks the CLJS port must
* reproduce EXACTLY (they are hashed into envelope sigs and receipt hashes):
* - NaN/Infinity serialize as "null" (JSON.stringify semantics);
* - -0 serializes as "0";
* - undefined-valued keys are FILTERED from objects, but an undefined array
* element THROWS (unlike JSON.stringify's "null");
* - key order is Array.prototype.sort() default = UTF-16 code-unit order
* (surrogate-pair keys sort BEFORE U+E000..U+FFFF keys);
* - lone surrogates escape as \udXXX (well-formed JSON.stringify);
* - U+2028/U+2029 are emitted raw (JSON.stringify does not escape them);
* - a Date is a plain object with no enumerable keys => "{}";
* - a Uint8Array is an object with numeric enumerable keys => {"0":..,..}.
*/
export function canonCases() {
return [
{ name: "null", desc: "null", make: () => null },
{ name: "true", desc: "true", make: () => true },
{ name: "false", desc: "false", make: () => false },
{ name: "int-zero", desc: "0", make: () => 0 },
{ name: "int", desc: "42", make: () => 42 },
{ name: "int-negative", desc: "-7", make: () => -7 },
{ name: "neg-zero", desc: "-0 (negative zero)", make: () => -0 },
{ name: "float", desc: "3.14", make: () => 3.14 },
{ name: "float-tenth", desc: "0.1", make: () => 0.1 },
{ name: "max-safe-int", desc: "9007199254740991", make: () => 9007199254740991 },
{ name: "beyond-safe-int", desc: "2^53+1 (loses precision to ...992)", make: () => 9007199254740993 },
{ name: "exp-large", desc: "1e21 (exponent form)", make: () => 1e21 },
{ name: "exp-small", desc: "1e-7 (exponent form)", make: () => 1e-7 },
{ name: "nan", desc: "NaN (JSON.stringify -> null)", make: () => NaN },
{ name: "infinity", desc: "Infinity (JSON.stringify -> null)", make: () => Infinity },
{ name: "string-plain", desc: '"hello"', make: () => "hello" },
{ name: "string-empty", desc: "empty string", make: () => "" },
{
name: "string-escapes",
desc: 'quote, backslash, newline, tab, CR, control U+0001, DEL U+007F',
make: () => 'q"b\\n\nt\tr\rcd',
},
{ name: "string-2byte", desc: "2-byte UTF-8: é ñ ő (hu)", make: () => "éñő" },
{ name: "string-3byte", desc: "3-byte UTF-8: € こんにちは", make: () => "€こんにちは" },
{ name: "string-4byte", desc: "4-byte UTF-8 surrogate pairs: 🎟 𝄞 👩🚀 (ZWJ)", make: () => "🎟𝄞👩🚀" },
{ name: "string-lone-surrogate", desc: "lone high surrogate U+D800 -> \\ud800 escape", make: () => "\ud800" },
{ name: "string-line-seps", desc: "U+2028/U+2029 emitted raw", make: () => "a
b
c" },
{ name: "empty-object", desc: "{}", make: () => ({}) },
{ name: "empty-array", desc: "[]", make: () => [] },
{
name: "array-mixed",
desc: "[1,\"a\",null,true,[],{}] — order preserved",
make: () => [1, "a", null, true, [], {}],
},
{ name: "array-specials", desc: "[-0, NaN, Infinity] -> [0,null,null]", make: () => [-0, NaN, Infinity] },
{
name: "object-unsorted-keys",
desc: "keys inserted b,a,c,B,A — sorted by UTF-16 code units",
make: () => ({ b: 1, a: 2, c: 3, B: 4, A: 5 }),
},
{
name: "object-key-codeunit-order",
desc: 'keys é,z,Z,a,_,0 inserted unsorted -> "0","Z","_","a","z","é"',
make: () => ({ "é": 1, z: 2, Z: 3, a: 4, _: 5, 0: 6 }),
},
{
name: "object-surrogate-key-order",
desc: "surrogate-pair key 🎟 (D83C..) sorts BEFORE U+FFFD key (code-unit sort)",
make: () => ({ "�": 2, "🎟": 1 }),
},
{
name: "object-undefined-filtered",
desc: "{a:1,b:undefined,c:2} — undefined-valued keys dropped",
make: () => ({ a: 1, b: undefined, c: 2 }),
},
{ name: "object-null-kept", desc: "{a:null} is NOT {} (null vs absent)", make: () => ({ a: null }) },
{ name: "object-empty-string-key", desc: '{"":1}', make: () => ({ "": 1 }) },
{
name: "nested-unsorted",
desc: "nested objects unsorted at each level, arrays preserve order",
make: () => ({ z: { b: [3, { y: 1, x: 2 }], a: null }, a: [{ c: 1, b: 2 }] }),
},
{
name: "date-object",
desc: "a Date has no enumerable own keys -> {} (quirk)",
make: () => new Date(TS_FIXED),
},
{
name: "typed-array",
desc: "Uint8Array [1,2] -> {\"0\":1,\"1\":2} (numeric enumerable keys; quirk)",
make: () => new Uint8Array([1, 2]),
},
{
name: "envelope-shaped",
desc: "realistic unsigned-envelope shape, keys inserted wire-order (t,id,from,ts,exp,body)",
make: () => ({
t: "freq",
id: ENV_ID_FIXED,
from: { pub: "PUB", x: "X", xs: "XS", name: "Ala " },
ts: TS_FIXED,
exp: EXP_FAR,
body: { msg: "hei ✨", k: 1 },
}),
},
{
name: "receipt-shaped",
desc: "realistic receipt base, sc array order preserved, entry keys p,nm,s",
make: () => ({
v: 1,
g: "game.test",
m: "match",
r: "rrrrrrrrrrrrrrrrrrrrrr",
ts: TS_FIXED,
n: 3,
sc: [
{ p: "P1", nm: "unu", s: 300 },
{ p: "P2", nm: "doi", s: 200 },
],
}),
},
];
}
/** Inputs canon() must THROW on (the port must reject them too). */
export function canonThrowCases() {
return [
{ name: "undefined-top-level", desc: "canon(undefined) throws", make: () => undefined },
{ name: "undefined-in-array", desc: "[1,undefined] throws (JSON.stringify would emit null)", make: () => [1, undefined] },
{ name: "function-value", desc: "{a:fn} throws (only undefined is filtered)", make: () => ({ a: () => 1 }) },
{ name: "function-in-array", desc: "[fn] throws", make: () => [() => 1] },
{ name: "bigint", desc: "10n throws (unsupported type)", make: () => 10n },
{ name: "symbol-value", desc: "{a:Symbol()} throws", make: () => ({ a: Symbol("x") }) },
];
}
async function computeCanon() {
const cases = [];
for (const c of canonCases()) {
const value = c.make();
let input_json = null;
try {
const j = JSON.stringify(value);
// only claim JSON-faithful when a round trip reproduces the same canon
if (j !== undefined && canon(JSON.parse(j)) === canon(value)) input_json = j;
} catch {
/* not JSON-representable */
}
const s = canon(value);
cases.push({ name: c.name, input_desc: c.desc, input_json, canon: s, utf8_hex: utf8Hex(s), sha256_b64url: await sha256B64url(s) });
}
const throws = canonThrowCases().map((c) => ({ name: c.name, input_desc: c.desc }));
const ikm = seedBytes(0x0a);
const hkdf = [
{
name: "hkdfId-basic",
ikm_hex: hex(ikm),
salt: SOCIAL_SALT,
info: "test|info|v1",
out_b64url: await hkdfId(ikm, SOCIAL_SALT, "test|info|v1"),
},
{
name: "hkdfId-unicode-info",
ikm_hex: hex(ikm),
salt: SOCIAL_SALT,
info: "test|✨|v1",
out_b64url: await hkdfId(ikm, SOCIAL_SALT, "test|✨|v1"),
},
];
const sha = [];
for (const s of ["", "hello", "hei ✨🎟"]) {
sha.push({ input: s, utf8_hex: utf8Hex(s), sha256_b64url: await sha256B64url(s) });
}
return { cases, throws, hkdf, sha256_b64url: sha };
}
// ---- envelope ---------------------------------------------------------------
/** Replicates envelope.ts's internal sigBytes format; PROVEN against the impl
* by openEnvelope accepting the sealed fixture built from this signature. */
export const envelopeSigPreimage = (ctx, unsigned) => `social-env|v1|${ctx}|${canon(unsigned)}`;
/** The fixed inner envelope A -> B. Name has a trailing space ON PURPOSE:
* the signature covers the RAW name; openEnvelope clamps only after verify. */
export async function buildFixedEnvelope(ac) {
const ctx = envCtx(ac.idB.publicKeyB64);
const unsigned = {
t: "freq",
id: ENV_ID_FIXED,
from: { pub: ac.idA.publicKeyB64, x: ac.xA.pubB64, xs: ac.xCertA, name: "Ala " },
ts: TS_FIXED,
exp: EXP_FAR,
body: { msg: "hei ✨", k: 1 },
};
const preimage = envelopeSigPreimage(ctx, unsigned);
const sig = toB64url(await ac.idA.signRaw(utf8(preimage)));
const inner = { ...unsigned, sig };
return { ctx, unsigned, preimage, sig, inner, inner_json: JSON.stringify(inner) };
}
async function computeEnvelope(ac) {
const e = await buildFixedEnvelope(ac);
return {
seeds: { sender_A: SEED_A, recipient_B: SEED_B },
sender: { pub: ac.idA.publicKeyB64, suite_x_pub: ac.xA.pubB64, suite_x_priv_hex: hex(ac.xA.priv), x_cert: ac.xCertA },
recipient: { pub: ac.idB.publicKeyB64, suite_x_pub: ac.xB.pubB64, suite_x_priv_hex: hex(ac.xB.priv), x_cert: ac.xCertB },
suite_salt: SUITE_SALT,
ctx: e.ctx,
env_id_fixed: ENV_ID_FIXED,
sig_preimage: e.preimage,
sig_preimage_sha256_b64url: await sha256B64url(e.preimage),
sig_b64url: e.sig,
inner: e.inner,
inner_json: e.inner_json,
inner_json_utf8_hex_sha256: await sha256B64url(e.inner_json),
opened_name_clamped: "Ala",
consts: { ENV_DEFAULT_TTL_MS, INVITE_TTL_MS, SEEN_ENV_CAP },
notes: [
"dedup key = inner.id verbatim (16 random bytes b64url at build time; fixed here) — no derivation",
"sig = Ed25519 over utf8('social-env|v1|' + ctx + '|' + canon(inner minus sig))",
"wrapped plaintext is JSON.stringify(inner) in INSERTION order (t,id,from{pub,x,xs,name},ts,exp,body,sig) — NOT canon()",
"openEnvelope verifies the X-cert then the sig over the RAW from.name, and only then clamps the returned name (clampProfile)",
"ctx binds recipient identity: envCtx(toIdPub) = 'to|v1|' + toIdPub — same ctx across inbox/pair/live transports",
],
};
}
// ---- pair -------------------------------------------------------------------
export async function channels(ac) {
const pairAB = await pairChannel(ac.xA, ac.idA.publicKeyB64, ac.idB.publicKeyB64, ac.xB.pubB64);
const pairBA = await pairChannel(ac.xB, ac.idB.publicKeyB64, ac.idA.publicKeyB64, ac.xA.pubB64);
const self = await selfChannel(SEED_A);
return { pairAB, pairBA, self };
}
async function computePair(ac, ch) {
const { pairAB, pairBA, self } = ch;
const tagA = await pairAB.tagOf(ac.idA.publicKeyB64);
const tagB = await pairAB.tagOf(ac.idB.publicKeyB64);
if (pairAB.id !== pairBA.id || pairAB.topic !== pairBA.topic || pairAB.mailboxRoomId !== pairBA.mailboxRoomId)
throw new Error("pair channel is not symmetric — impl drift");
if ((await pairBA.tagOf(ac.idA.publicKeyB64)) !== tagA) throw new Error("pair tag asymmetric");
return {
social_salt: SOCIAL_SALT,
seeds: { A: SEED_A, B: SEED_B },
pair_AB: {
id: pairAB.id,
topic: pairAB.topic,
mailboxRoomId: pairAB.mailboxRoomId,
ctx: pairAB.ctx,
tag_of_A: tagA,
tag_of_B: tagB,
},
self_A: {
id: self.id,
topic: self.topic,
mailboxRoomId: self.mailboxRoomId,
ctx: self.ctx,
tag_of_A: await self.tagOf(ac.idA.publicKeyB64),
},
notes: [
"pair ikm = HKDF(X25519(myXpriv, friendXpub), SOCIAL_SALT, 'friend-pair|v1|<minPub>|<maxPub>') — pubs sorted, so both sides derive identically",
"self ikm = HKDF(seed, SOCIAL_SALT, 'self-room|v1')",
"one extra indirection first: ikm' = HKDF(ikm, SOCIAL_SALT, '<kind>|ikm'); then id/topic/mailbox/tag/msg keys derive from ikm'",
"topic = 'soc/1/' + hkdfId(ikm', SOCIAL_SALT, '<kind>|topic'); ctx = '<kind>|v1|' + id",
"tagOf(pub) = hkdfId(ikm', SOCIAL_SALT, '<kind>|tag|<pub>').slice(0,16)",
"seal: AES-GCM(hkdfAesKey(ikm', SOCIAL_SALT, '<kind>|msg|<pub>'), iv random 12B, AAD utf8('soc|v1|<id>|<senderPub>')); wire JSON {v:1,s:tag,iv:b64,ct:b64} (STANDARD b64, not b64url)",
],
};
}
// ---- receipts ---------------------------------------------------------------
export const RECEIPT_ROOM_ID = "vector-room-1";
export async function buildReceipts(ac) {
const r = await roomHash(RECEIPT_ROOM_ID);
const base = {
v: 1,
g: "game1-test-salt",
m: "match",
r,
ts: TS_FIXED,
n: 3,
sc: [
{ p: ac.idP1.publicKeyB64, nm: "unu", s: 300 },
{ p: ac.idP2.publicKeyB64, nm: "doi ✨", s: 200 },
{ p: ac.idP3.publicKeyB64, nm: "trei", s: 100 },
],
};
const [s1, s2, s3] = await Promise.all([signReceipt(ac.idP1, base), signReceipt(ac.idP2, base), signReceipt(ac.idP3, base)]);
return { base, s1, s2, s3 };
}
async function computeReceipts(ac) {
const { base, s1, s2, s3 } = await buildReceipts(ac);
const preimage = `lb-receipt|v1|${canon(base)}`;
const full = { ...base, sig: [s1, s2, s3] };
const hash = await receiptHash(base);
const tamperedScore = JSON.parse(JSON.stringify(full));
tamperedScore.sc[0].s = 999999;
const dupPlayer = JSON.parse(JSON.stringify(full));
dupPlayer.sc[1] = { ...dupPlayer.sc[0] };
const outsiderBase = { ...base, sc: base.sc.slice(0, 2) }; // P3 not on the score list
const outsiderSigned = {
...outsiderBase,
sig: [await signReceipt(ac.idP1, outsiderBase), await signReceipt(ac.idP3, outsiderBase)],
};
const futureBase = { ...base, ts: EXP_FAR };
const futureSigned = { ...futureBase, sig: [await signReceipt(ac.idP1, futureBase), await signReceipt(ac.idP2, futureBase)] };
const oversize = { ...full, m: "x".repeat(5000) };
const table = [
{ name: "three-signers-accept", receipt: full, opts: {} },
{ name: "two-signers-accept", receipt: { ...base, sig: [s1, s2] }, opts: {} },
{ name: "one-signer-reject", receipt: { ...base, sig: [s1] }, opts: {} },
{ name: "zero-signers-reject", receipt: { ...base, sig: [] }, opts: {} },
{
name: "one-valid-one-garbage-sig-reject",
receipt: { ...base, sig: [s1, { p: s2.p, s: s1.s }] },
opts: {},
},
{ name: "duplicate-signer-entries-reject", receipt: { ...base, sig: [s1, s1] }, opts: {} },
{ name: "tampered-score-reject", receipt: tamperedScore, opts: {} },
{ name: "duplicate-player-reject", receipt: dupPlayer, opts: {} },
{ name: "signer-not-in-scorelist-reject", receipt: outsiderSigned, opts: {} },
{ name: "future-ts-reject", receipt: futureSigned, opts: {} },
{ name: "oversize-reject", receipt: oversize, opts: {} },
{ name: "wrong-version-reject", receipt: { ...full, v: 2 }, opts: {} },
{ name: "max-score-cap-reject", receipt: full, opts: { maxScore: 250 } },
{ name: "max-score-cap-accept", receipt: full, opts: { maxScore: 1000 } },
];
const verify_table = [];
for (const t of table) {
const v = await verifyReceipt(t.receipt, t.opts);
verify_table.push({ name: t.name, receipt: t.receipt, opts: t.opts, accept: v !== null, ...(v ? { hash: v.hash } : {}) });
}
return {
seeds: { P1: SEED_P1, P2: SEED_P2, P3: SEED_P3 },
pubs: { P1: ac.idP1.publicKeyB64, P2: ac.idP2.publicKeyB64, P3: ac.idP3.publicKeyB64 },
room_id: RECEIPT_ROOM_ID,
room_hash: base.r,
base,
sig_preimage: preimage,
sig_preimage_utf8_hex: utf8Hex(preimage),
signatures: { P1: s1, P2: s2, P3: s3 },
receipt_hash: hash,
min_signers: MIN_SIGNERS,
consts: { RECEIPTS_CAP },
verify_table,
notes: [
"sig = Ed25519 over utf8('lb-receipt|v1|' + canon(base)); base key order irrelevant (canon sorts), sc ARRAY order signed as-is",
"receiptHash = sha256B64url(canon({v,g,m,r,ts,n,sc})) — sig field excluded by destructuring",
"roomHash = sha256B64url('lbroom|'+roomId).slice(0,22)",
"verify order: v===1, size<=4096 (JSON.stringify), field shapes, sc 1..32, ts<=now+300000, per-entry finite scores + duplicate-player check + optional maxScore, then signatures (distinct signers, must appear in sc), >=2 valid",
"receipts.ts has its own local b64url(btoa-based) for signatures — output identical to id-kit toB64url",
],
};
}
// ---- isoweek ----------------------------------------------------------------
const ISO_DATES = [
"1970-01-01T00:00:00.000Z",
"2000-01-01T00:00:00.000Z",
"2015-12-28T00:00:00.000Z",
"2016-01-01T00:00:00.000Z",
"2017-01-01T00:00:00.000Z",
"2017-01-02T00:00:00.000Z",
"2019-12-30T00:00:00.000Z",
"2020-12-31T23:59:59.999Z",
"2021-01-01T00:00:00.000Z",
"2021-01-04T00:00:00.000Z",
"2024-12-30T00:00:00.000Z",
"2025-01-05T23:59:59.999Z",
"2026-01-01T00:00:00.000Z",
"2026-08-27T12:00:00.000Z",
"2026-12-28T00:00:00.000Z",
"2026-12-31T23:59:59.999Z",
"2027-01-01T00:00:00.000Z",
"2028-01-01T00:00:00.000Z",
];
async function computeIsoweek() {
const weeks = ISO_DATES.map((d) => ({ date: d, ts: Date.parse(d), week: isoWeek(Date.parse(d)) }));
const g = "game1-test-salt";
const g2 = "game2-test-salt";
return {
weeks,
lb_room_ids: [
{ g, week: "2026-W35", room_id: await lbRoomId(g, "2026-W35") },
{ g, week: "2026-W53", room_id: await lbRoomId(g, "2026-W53") },
{ g: g2, week: "2020-W53", room_id: await lbRoomId(g2, "2020-W53") },
],
lb_topics: [
{ g, topic: await lbTopic(g) },
{ g: g2, topic: await lbTopic(g2) },
],
notes: [
"isoWeek works in UTC; Thursday of the containing week decides the week-year",
"lbRoomId = sha256B64url('lb|v1|<g>|<week>') (full 43 chars)",
"lbTopic = 'lb/1/' + sha256B64url('lb-topic|v1|<g>').slice(0,22)",
"fetchWeekly verifies with maxAgeMs = 8*86400000 by default (caller opts may override)",
],
};
}
// ---- mailbox ----------------------------------------------------------------
async function computeMailbox(ac) {
return {
inbox_room_ids: [
{ id_pub: ac.idA.publicKeyB64, room_id: await inboxRoomId(ac.idA.publicKeyB64) },
{ id_pub: ac.idB.publicKeyB64, room_id: await inboxRoomId(ac.idB.publicKeyB64) },
],
endpoints: {
descriptor_url: AP2P_DESCRIPTOR_URL,
mailbox_url_fallback: MAILBOX_URL_FALLBACK,
mailbox_creds_url_fallback: MAILBOX_CREDS_URL_FALLBACK,
max_message_kb_fallback: 64,
},
notes: [
"inboxRoomId(idPub) = hkdfId(fromB64url(idPub), SOCIAL_SALT, 'inbox|mailbox|v1') — ikm is the RAW decoded pub bytes",
"inbox envelope wrap ctx is envCtx(toIdPub) = 'to|v1|<idPub>' (recipient-bound, transport-agnostic)",
"HTTP shape (doc only, not vectored): POST/GET <base>/rooms/<encodeURIComponent(roomId)>/messages, bearer from <creds>?room=<id>&ttl=86400",
],
};
}
// ---- invites ----------------------------------------------------------------
function computeInvites() {
return {
suite_apps: SUITE_APPS.map((a) => ({ ...a })),
mint_room_url_pattern: "^https://<host>/#[A-Za-z0-9_-]{43}$",
notes: ["mintRoomUrl = 'https://' + host + '/#' + toB64url(randomBytes(32)) — 43-char b64url fragment secret"],
};
}
// ---- friends + selfsync -----------------------------------------------------
async function computeFriends(ac) {
const meA = { pub: ac.idA.publicKeyB64, x: ac.xA.pubB64, xs: ac.xCertA, name: "Ala Bala" };
const linkPlain = buildFriendLink("https://ardegazu.ro/", meA);
const linkUnicode = buildFriendLink("https://ardegazu.ro/", { ...meA, name: "Ắla ✨&=?" });
const linkNoName = buildFriendLink("https://ardegazu.ro/", { ...meA, name: "" });
const parse = async (link) => parseFriendLink(link.slice(link.indexOf("#")));
const parsedPlain = await parse(linkPlain);
const parsedUnicode = await parse(linkUnicode);
const parsedNoName = await parse(linkNoName);
const forged = `add=${meA.pub}.${meA.x}.${ac.xCertB}`; // B's cert on A's keys
const badShape = `add=${meA.pub}.${meA.x}`;
const negatives = [
{ name: "forged-cert", fragment: forged, parsed: await parseFriendLink(forged) },
{ name: "bad-shape", fragment: badShape, parsed: await parseFriendLink(badShape) },
{ name: "junk", fragment: "add=abc.def.ghi", parsed: await parseFriendLink("add=abc.def.ghi") },
].map((n) => ({ ...n, parsed: n.parsed === null ? null : n.parsed }));
const validFriend = {
pub: ac.idB.publicKeyB64,
x: ac.xB.pubB64,
xs: ac.xCertB,
pet: " vecinul ",
name: "a".repeat(40),
state: "friend",
addedTs: TS_FIXED,
petTs: TS_FIXED,
lastSeenTs: TS_FIXED,
lastApp: "x".repeat(80),
note: "n".repeat(250),
extra_garbage: "dropped",
};
const sanitize_cases = [
{ name: "valid-clamped", input: validFriend, output: sanitizeFriend(validFriend) },
{ name: "bad-pub", input: { ...validFriend, pub: "short" }, output: sanitizeFriend({ ...validFriend, pub: "short" }) },
{ name: "bad-state", input: { ...validFriend, state: "enemy" }, output: sanitizeFriend({ ...validFriend, state: "enemy" }) },
{ name: "not-object", input: null, output: sanitizeFriend(null) },
];
const p = (name, hue, glyph, lang, ts) => ({ name, hue, glyph, lang, ts });
const older = p("Ala", 120, "🐢", "ro", TS_FIXED);
const newer = p("Bala", null, null, "hu", TS_FIXED + 1000);
const blankNewer = p("", null, null, null, TS_FIXED + 5000);
const sameTsA = p("Ana", null, "🦊", null, TS_FIXED);
const sameTsB = p("", 200, null, "en", TS_FIXED);
const fold_cases = [
{ name: "newer-remote-wins-wholesale", local: older, remote: newer, folded: foldProfileSync(older, newer) },
{ name: "blank-newer-never-wins", local: older, remote: blankNewer, folded: foldProfileSync(older, blankNewer) },
{ name: "older-remote-backfills-blanks", local: newer, remote: older, folded: foldProfileSync(newer, older) },
{ name: "equal-ts-converges-ab", local: sameTsA, remote: sameTsB, folded: foldProfileSync(sameTsA, sameTsB) },
{ name: "equal-ts-converges-ba", local: sameTsB, remote: sameTsA, folded: foldProfileSync(sameTsB, sameTsA) },
{ name: "idempotent", local: older, remote: older, folded: foldProfileSync(older, older) },
];
const sanitize_profile_cases = [
{
name: "clamps",
input: { name: " Ala ", hue: 359.9, glyph: "🐢🦊", lang: "ro", ts: TS_FIXED, junk: 1 },
output: sanitizeProfileSync({ name: " Ala ", hue: 359.9, glyph: "🐢🦊", lang: "ro", ts: TS_FIXED, junk: 1 }),
},
{ name: "bad-lang", input: { name: "x", hue: null, glyph: null, lang: "not a lang!", ts: TS_FIXED }, output: sanitizeProfileSync({ name: "x", hue: null, glyph: null, lang: "not a lang!", ts: TS_FIXED }) },
{ name: "no-ts-null", input: { name: "x" }, output: sanitizeProfileSync({ name: "x" }) },
];
return {
links: {
base: "https://ardegazu.ro/",
me: meA,
plain: { link: linkPlain, parsed: parsedPlain },
unicode_name: { name: "Ắla ✨&=?", link: linkUnicode, parsed: parsedUnicode },
no_name: { link: linkNoName, parsed: parsedNoName },
negatives,
},
sanitize_cases,
profile_sync: { sanitize_cases: sanitize_profile_cases, fold_cases },
consts: { BLOCKED_CAP },
notes: [
"friend link fragment: add=<pub>.<x>.<xs>[&n=<encodeURIComponent(name)>]; pub/x are 43-char b64url, xs 20..120",
"parseFriendLink verifies the X-cert (board-x25519|v1 domain tag under SUITE_SALT) before returning",
"names clamp via clampProfile: trim + first 32 CODE POINTS ([...str].slice(0,32)); note 200 chars; lastApp 64 chars",
"foldProfileSync equal-ts tiebreak compares canon(remote) vs canon(local) as JS strings (UTF-16 code-unit >)",
],
};
}
// ---- apps sync (the identity record's per-app map) --------------------------
/**
* selfsync's `apps` section: `{<appKey>: {state, ts}}`, one key per app, folded
* PER KEY so two apps edited on two devices both survive.
*
* Every `ts` here is in the past, so the clamp to now is a no-op and the rows
* stay reproducible; the clamp itself is asserted dynamically by the selftest
* and by test/selfsync.test.mjs. The size and JSON-safety rows carry
* `input_desc` + a `kept` verdict rather than the input, because a 16 KB state
* (or a cycle, or a function) does not belong in — or cannot be expressed by —
* a JSON fixture.
*
* Every `output_keys` / `folded_keys` array is there because assert.deepEqual
* is key-order-BLIND: without them the fixture proves the key SET and nothing
* about the order, and key order is the wire.
*/
function computeAppsSync() {
const e = (state, ts) => ({ state, ts });
const one = (state, ts) => sanitizeAppsSync({ a: { state, ts } }) !== null;
const keysOf = (o) => (o === null ? null : Object.keys(o));
const san = (name, input) => ({ name, input, output: sanitizeAppsSync(input), output_keys: keysOf(sanitizeAppsSync(input)) });
const sanitize_cases = [
san("kept-in-deterministic-order", {
zed: e(1, TS_FIXED),
chat: e({ unread: 3 }, TS_FIXED + 1000),
board: e("z", TS_FIXED + 2000),
}),
// NOT lexicographic: the key charset permits all-digit labels and JS
// canonical property order hoists array-index-like keys numerically ahead
// of the rest, so "2" precedes "10" precedes "board". Deterministic, which
// is the actual contract.
san("digit-keys-are-not-lexicographic", {
board: e(1, TS_FIXED), 10: e(1, TS_FIXED), 2: e(1, TS_FIXED), a: e(1, TS_FIXED),
}),
san("bad-keys-dropped", { "BAD KEY": e(1, TS_FIXED), "under_score": e(1, TS_FIXED), "": e(1, TS_FIXED), ok: e(1, TS_FIXED) }),
// "__proto__" carries an underscore and fails the charset; "constructor"
// passes it and is ordinary data. Neither may reach a prototype.
san("proto-keys", JSON.parse('{"__proto__":{"state":"p","ts":1735689600000},"constructor":{"state":"c","ts":1735689600000}}')),
san("bad-entries-dropped-neighbours-kept", { a: e(1, 0), b: e(1, -1), c: { state: 1 }, d: e(1, "5"), ee: e(1, TS_FIXED), f: null }),
san("not-object", null),
san("array", []),
san("empty", {}),
san("nothing-survives-is-null", { "BAD KEY": e(1, TS_FIXED) }),
];
// A size is the UTF-16 code-unit length of JSON.stringify(state) — id-kit's
// unit, exactly. `"x".repeat(n)` and `"ș".repeat(n)` both serialize to n + 2
// units (the two quotes; JSON.stringify escapes neither character), which is
// the whole point: the same cap for ASCII and for the ro/hu text the suite
// actually carries. Measured in UTF-8 bytes the second pair would be 32768
// and 32770 and would have been refused at half the advertised cap.
const size_cases = [
{ name: "ascii-at-the-cap", input_desc: 'state = "x".repeat(16382) — JSON is 16382 + 2 = 16384 code units', kept: one("x".repeat(16382), TS_FIXED) },
{ name: "ascii-one-over", input_desc: 'state = "x".repeat(16383) — JSON is 16385 code units', kept: one("x".repeat(16383), TS_FIXED) },
{ name: "two-byte-at-the-cap", input_desc: 'state = "ș".repeat(16382) — JSON is 16384 code units (32768 UTF-8 bytes)', kept: one("ș".repeat(16382), TS_FIXED) },
{ name: "two-byte-one-over", input_desc: 'state = "ș".repeat(16383) — JSON is 16385 code units', kept: one("ș".repeat(16383), TS_FIXED) },
];
// The whole-map cap, arithmetic spelled out so a reader can check it:
// one entry costs len('"k"') + len(":") + len(JSON.stringify(entry)) + 1
// for the comma (or the closing brace), and the map costs 1 (the opening
// brace) + the sum. With a 1-character key and a 13-digit ts, the entry is
// '{"state":"<S>","ts":1735689600000}' = 31 + |S|, so an entry costs
// 3 + 1 + 31 + |S| + 1 = 36 + |S|.
// five entries at the per-entry cap: 5 * (36 + 16382) = 82090
// the map so far: 1 + 82090 = 82091
// left of MAX-APPS 98304: 98304 - 82091 = 16213
// so a sixth entry fits iff |S| <= 16213 - 36 = 16177.
const bigS = "x".repeat(16382);
const five = { a: e(bigS, TS_FIXED), b: e(bigS, TS_FIXED), c: e(bigS, TS_FIXED), d: e(bigS, TS_FIXED), f: e(bigS, TS_FIXED) };
const atCap = { ...five, g: e("x".repeat(16177), TS_FIXED) };
// `h` is one unit too big to fit and is SKIPPED, not fatal — `i` after it
// still fits and is kept, which is what makes the pass idempotent.
const overCap = { ...five, h: e("x".repeat(16178), TS_FIXED), i: e("x".repeat(100), TS_FIXED) };
const mapLen = (o) => JSON.stringify(sanitizeAppsSync(o)).length;
const map_cases = [
{
name: "map-exactly-at-the-cap",
input_desc: "5 entries at the per-entry cap + a sixth of 16177 units — 98304 exactly",
kept_keys: Object.keys(sanitizeAppsSync(atCap)),
serialized_units: mapLen(atCap),
},
{
name: "over-cap-entry-skipped-smaller-neighbour-kept",
input_desc: "the same 5 + one 16178-unit entry (1 over what is left) + one 100-unit entry",
kept_keys: Object.keys(sanitizeAppsSync(overCap)),
serialized_units: mapLen(overCap),
},
];
const cyclic = { self: null };
cyclic.self = cyclic;
const safety_cases = [
{ name: "null-state", input_desc: "state = null — JSON-safe, kept", kept: one(null, TS_FIXED) },
{ name: "absent-state", input_desc: "no state key at all — JSON.stringify(undefined) is undefined", kept: sanitizeAppsSync({ a: { ts: TS_FIXED } }) !== null },
{ name: "function-state", input_desc: "state = () => {} — JSON.stringify gives undefined", kept: one(() => {}, TS_FIXED) },
{ name: "function-valued-key", input_desc: "state = { f: () => {} } — JSON.stringify gives '{}' but canon() THROWS", kept: one({ f: () => {} }, TS_FIXED) },
{ name: "bigint-state", input_desc: "state = 1n — both serializers throw", kept: one(1n, TS_FIXED) },
{ name: "cyclic-state", input_desc: "state = an object holding itself", kept: one(cyclic, TS_FIXED) },
];
const local = { board: e({ n: 2 }, TS_FIXED + 3000), chat: e({ n: 1 }, TS_FIXED + 1000) };
const remote = { chat: e({ n: 9 }, TS_FIXED + 2000), game1: e({ n: 3 }, TS_FIXED) };
const stale = { board: e({ n: 7 }, TS_FIXED + 9000), chat: e({ n: 0 }, TS_FIXED) };
const tieA = { chat: e({ n: 1 }, TS_FIXED) };
const tieB = { chat: e({ n: 2 }, TS_FIXED) };
const fold = (name, l, r) => ({ name, local: l, remote: r, folded: foldAppsSync(l, r), folded_keys: Object.keys(foldAppsSync(l, r)) });
const fold_cases = [
fold("newer-entry-wins-its-key", local, remote),
fold("commutes", remote, local),
fold("per-key-independence", local, stale),
fold("equal-ts-converges-ab", tieA, tieB),
fold("equal-ts-converges-ba", tieB, tieA),
fold("idempotent", local, foldAppsSync(local, remote)),
fold("both-empty", {}, {}),
// "__proto__" is exactly what JSON.parse of wire text produces, and the
// fold's output must not grow a prototype from it; "constructor" is a
// legal app key and stays ordinary data.
fold("proto-keys-dropped-constructor-kept",
JSON.parse('{"__proto__":{"state":"p","ts":1735689600000},"constructor":{"state":"c","ts":1735689600000}}'), {}),
fold("digit-keys-are-not-lexicographic",
{ board: e(1, TS_FIXED), 10: e(1, TS_FIXED) }, { 2: e(1, TS_FIXED), a: e(1, TS_FIXED) }),
];
return {
sanitize_cases,
size_cases,
map_cases,
safety_cases,
fold_cases,
consts: {
app_key_re: "^[a-z0-9-]{1,32}$",
size_unit: "utf16-code-units-of-JSON.stringify",
state_max_units: 16384,
apps_max_units: 98304,
skew_ms: 120000,
},
notes: [
"the `apps` section rides the fsync body next to soc/profile/app — additive, old kits read past it",
"sanitizeAppsSync: plain object only (an array is refused), keys /^[a-z0-9-]{1,32}$/, entries {state,ts} with a finite ts > 0",
"key order is DETERMINISTIC, not lexicographic: entries are inserted sorted, but JS canonical property order hoists all-digit keys numerically ahead of the rest — \"2\" before \"10\" before \"board\"",
"sizes are UTF-16 CODE UNITS of JSON.stringify — never UTF-8 bytes — and the two caps are id-kit's own: 16384 per entry's `state`, 98304 for the whole serialized map. There is NO entry-count cap and no eviction",
"an entry that would push the map past 98304 is skipped and smaller ones after it are still kept, so a second pass over the result changes nothing",
"ts is clamped to NOW, never to now + skew: a section may never be emitted with a timestamp from the future (skew_ms is the PROFILE section's tolerance, kept for it alone)",
"state must satisfy BOTH JSON.stringify (not undefined, no throw) and canon() (which throws where JSON.stringify silently drops) — canon is what the agent's sync fingerprint runs over",
"foldAppsSync folds PER KEY over the union: strictly newer ts wins that key wholesale, equal ts breaks on the greater canon() of the ENTRY (role-independent), a key only one side has is adopted unchanged",
"the fold applies the key charset too, so a `__proto__` own key from JSON.parse can never reach the output's prototype setter; it returns {} rather than null when both sides are empty",
],
};
}
// ---- text -------------------------------------------------------------------
async function computeText() {
// SocialTextKey is a type (the generated union in types/text.d.ts); recover
// the runtime key set from the EN table's source, then read values via
// enText().
const { readFile } = await import("node:fs/promises");
const src = await readFile(new URL("../../src/ardegazu/social/text.cljs", import.meta.url), "utf8");
const KEYS = [...src.matchAll(/"(social\.[^"]+)"/g)].map((m) => m[1]).sort();
if (KEYS.length === 0) throw new Error("no social.* keys found in text.cljs");
const en = {};
for (const k of KEYS) {
const v = enText(k);
if (typeof v !== "string") throw new Error(`enText(${k}) is not a string`);
en[k] = v;
}
const fill_cases = [
{ key: "social.toast.invites-you", vars: { name: "Ala" }, out: enText("social.toast.invites-you", { name: "Ala" }) },
{ key: "social.sheet.here-now", vars: { app: "sueta" }, out: enText("social.sheet.here-now", { app: "sueta" }) },
{ key: "social.invite.join", vars: {}, out: enText("social.invite.join", {}) },
{ key: "social.invite.join", vars: { app: 42 }, out: enText("social.invite.join", { app: 42 }) },
];
const t1 = mkT((k) => (k === "social.toast.join" ? "hai" : undefined));
const t2 = mkT((k) => k); // returning the key itself = untranslated
const t3 = mkT(() => ""); // empty = untranslated
const mkT_cases = [
{ desc: "translator hit", key: "social.toast.join", out: t1("social.toast.join") },
{ desc: "translator miss -> EN", key: "social.toast.share", out: t1("social.toast.share") },
{ desc: "returns key -> EN", key: "social.toast.join", out: t2("social.toast.join") },
{ desc: "returns empty -> EN", key: "social.toast.join", out: t3("social.toast.join") },
];
return {
keys_sorted: KEYS,
en,
fill_cases,
mkT_cases,
notes: [
"SocialTextKey = the keys_sorted list — the i18n contract app catalogs mirror as Record<SocialTextKey,...>",
"EN values are wire-relevant: senders put enText on the wire as the legacy invite label (must stay English-stable)",
"fill: /\\{(\\w+)\\}/g; unknown vars stay as the literal {name} token; values via String()",
],
};
}
// ---- top level --------------------------------------------------------------
export async function computeAll() {
const ac = await actors();
const ch = await channels(ac);
return {
ac,
ch,
sections: {
canon: await computeCanon(),
envelope: await computeEnvelope(ac),
pair: await computePair(ac, ch),
receipts: await computeReceipts(ac),
isoweek: await computeIsoweek(),
mailbox: await computeMailbox(ac),
invites: computeInvites(),
friends: await computeFriends(ac),
"apps-sync": computeAppsSync(),
"text-keys": await computeText(),
},
};
}
|