sigelo-contact 0.1.21 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/GROUPS-REFERENCE.md +165 -0
  2. package/GROUPS.md +53 -0
  3. package/LICENSE +235 -21
  4. package/README.md +4 -5
  5. package/call.mjs +89 -28
  6. package/carrier.mjs +230 -51
  7. package/control.mjs +2 -2
  8. package/create.mjs +2 -2
  9. package/device.mjs +2 -2
  10. package/enrol.mjs +2 -2
  11. package/envelope.mjs +6 -6
  12. package/file.mjs +2 -2
  13. package/fixtures/carrier-v0.json +1 -1
  14. package/fixtures/envelope-v0.json +1 -1
  15. package/fixtures/group-v2.json +2999 -0
  16. package/gen-carrier.mjs +2 -2
  17. package/gen-device.mjs +1 -1
  18. package/gen-envelope.mjs +2 -2
  19. package/gen-group2.mjs +291 -0
  20. package/gen-invite.mjs +2 -2
  21. package/gen-short.mjs +1 -1
  22. package/group.mjs +116 -17
  23. package/group2.mjs +1534 -0
  24. package/home-wire.mjs +812 -0
  25. package/invite.mjs +3 -3
  26. package/kdf.mjs +2 -2
  27. package/kin.mjs +62 -0
  28. package/link.mjs +6 -6
  29. package/package.json +25 -8
  30. package/page.mjs +542 -63
  31. package/photo.mjs +2 -2
  32. package/platform-node.mjs +6 -6
  33. package/prekeys.mjs +3 -3
  34. package/public.mjs +2 -2
  35. package/qr-decode.mjs +1 -1
  36. package/qr.mjs +2 -2
  37. package/relays.mjs +2 -2
  38. package/restore.mjs +2 -2
  39. package/rtc-web.mjs +3 -3
  40. package/short.mjs +2 -2
  41. package/store.mjs +22 -9
  42. package/test-carrier.mjs +32 -11
  43. package/test-device.mjs +3 -3
  44. package/test-enrol.mjs +9 -4
  45. package/test-envelope.mjs +2 -2
  46. package/test-file.mjs +2 -2
  47. package/test-group-move.mjs +225 -0
  48. package/test-group.mjs +1 -1
  49. package/test-group2.mjs +202 -0
  50. package/test-home.mjs +225 -0
  51. package/test-invite.mjs +1 -1
  52. package/test-link.mjs +3 -3
  53. package/test-platform.mjs +2 -2
  54. package/test-presence.mjs +2 -2
  55. package/test-push.mjs +5 -5
  56. package/test-relay-lane.mjs +3 -3
  57. package/test-short.mjs +1 -1
  58. package/test-tier.mjs +8 -2
  59. package/test-transfer-web.mjs +15 -7
  60. package/test-transfer.mjs +24 -6
  61. package/test-voice.mjs +2 -2
  62. package/test-ws.mjs +1 -1
  63. package/transfer-engine.mjs +46 -16
  64. package/transfer-node.mjs +9 -7
  65. package/transfer-web.mjs +4 -4
  66. package/transfer.mjs +8 -8
  67. package/voice-web.mjs +2 -2
  68. package/voice.mjs +7 -3
  69. package/words-lock.mjs +2 -2
package/home-wire.mjs ADDED
@@ -0,0 +1,812 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Home-relay groups, the wire: contract sigelo-group/2 (GROUPS.md).
3
+ // Pure: no network, no file, no clock (every `now` is a parameter). What is here:
4
+ //
5
+ // the entry the bytes one PUBLISH to a group's g/ topic carries: a relay-read head
6
+ // (version, kind 0x03, flags, keep slot, epoch, credential signature), a sealed
7
+ // header (sender hint, counter) and the sealed {body, sig, chain?}
8
+ // the door a joiner's request to a link's d/ topic (kind 0x04) and the admin's answer on the
9
+ // joiner's i/ topic (kind 0x05): X-Wing to a public key, then XChaCha20-Poly1305
10
+ // the keys epoch secret E → member write key W, header key HK, sender chain starts; admin
11
+ // vault V → admin write key AW, the vault key; letter keys L (one per member)
12
+ // the letters E' sealed to each member at a renewal: symmetric under L, or X-Wing to its gkey
13
+ // the boxes vault, welcome, history: X-Wing to one member's gkey
14
+ // the bodies every sigelo-group/2 body as a closed table (an object has exactly its keys)
15
+ // the rules who may sign which body (authorize), the agent-allowed flag on a role grant
16
+ // the invite the signed invite, its long form and its GRP- short code
17
+ //
18
+ // Additional data: the header's is bytes 0-7 ‖ topic, the body's bytes 0-7 ‖ 72-147 ‖ topic. Not the
19
+ // credential signature (bytes 8-71): it covers the sealed bytes, so they cannot cover it; the signature
20
+ // and the seals both bind bytes 0-7 and the topic.
21
+ //
22
+ // Order: sign, then encrypt. A body is signed by its sender's identity key over "sigelo\n" ‖ JCS(body)
23
+ // (SPEC §3, detached), the {body, sig, chain?} is JCS-encoded, padded and sealed. A reader opens,
24
+ // strict-parses (duplicate keys refused), checks that the bytes are the JCS of what they parse to,
25
+ // checks the table, then the signature under the sender's chain: offline, with the sigelo library.
26
+ // The relay reads bytes 0-71 of an entry and nothing else.
27
+ //
28
+ // Refusals, by check: group_entry (a layout, a flag, a size), group_key (a seal that does not open:
29
+ // wrong key or altered bytes), group_message (a body or object not as its table says), group_text (a
30
+ // name or text out of its bounds), group_sig (a signature, a chain, a DID that does not match),
31
+ // group_role (a signer without the role for this body), group_member (a signer or target not in the
32
+ // group), group_epoch (a body under another epoch than its entry), group_stale (iat out of its
33
+ // window; an invite past exp), group_code (not a GRP- code).
34
+ import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
35
+ import { ed25519 } from '@noble/curves/ed25519.js';
36
+ import { hkdf } from '@noble/hashes/hkdf.js';
37
+ import { hmac } from '@noble/hashes/hmac.js';
38
+ import { sha256 } from '@noble/hashes/sha2.js';
39
+ import { bytesToHex, concatBytes, hexToBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
40
+ import { ml_kem768_x25519 as xwing } from '@noble/post-quantum/hybrid.js';
41
+ import { canonicalize, did as didOf, parseBytes, verify, verifySig } from 'sigelo';
42
+ import { pad, unpad } from './envelope.mjs';
43
+ import { fail, signAs, step } from './kdf.mjs';
44
+ import { checkPhoto } from './photo.mjs';
45
+ import { normaliseShort, formatShort } from './short.mjs';
46
+ import { checkVoice } from './voice.mjs';
47
+
48
+ export const GROUP2_V = 'sigelo-group/2', HOME_V = 'sigelo-home/0';
49
+ // ---------------------------------------------------------------- the entry
50
+ export const VERSION = 0x02, KIND_ENTRY = 0x03, KIND_DOOR = 0x04, KIND_ANSWER = 0x05;
51
+ export const FLAG = Object.freeze({ admin: 1, keep: 2, letters: 4 });
52
+ export const HEAD = 72, HEADER_NONCE = 72, SEALED_HEADER = 96, BODY_NONCE = 124, BODY = 148, NONCE = 24, TAG = 16;
53
+ export const KEEP_STATE = [1, 8], KEEP_AVATAR = 9, KEEP_MAX = 32;
54
+ export const MAX_ENTRY = 1 << 20, MAX_DOOR = 16 * 1024, MAX_ANSWER = 16 * 1024;
55
+ export const XWING_PUB = 1216, XWING_CT = 1120;
56
+ export const EPOCH_MAX = 0xffffffff;
57
+ // Times (G1's window: 5 minutes ahead, 91 days back); invites and links live 1 hour to 366 days.
58
+ export const SKEW = 300, DAY = 86400, OLDEST = 91 * DAY, LINK_MIN = 3600, LINK_MAX = 366 * DAY, LINK_TTL = 7 * DAY;
59
+ export const LINK_CAP = 50, LINK_CAP_MAX = 500, CHAIN_MAX = 64, WINDOW = 64;
60
+ // Sizes of the content bodies.
61
+ export const NAME_MAX = 40, MEMBER_NAME_MAX = 64, TEXT_MAX = 8000, ABOUT_MAX = 500, REASON_MAX = 200;
62
+ export const QUESTION_MAX = 300, OPTION_MAX = 100, OPTIONS = [2, 10], EMOJI_BYTES = 32, BRAKE = 20, BRAKE_MAX = 10000;
63
+ // The most a capped member (a moderator, an admin that is an agent) kicks (bans too) and deletes a UTC day: settings.mod's bounds.
64
+ export const MOD_KICKS = 20, MOD_DELETES = 200;
65
+ export const BLOB_PART = 256 * 1024, BLOB_PARTS = 32, FILE_IN_LOG = 8 * 1024 * 1024, FILE_MAX = 16 * 2 ** 30, CHUNK = 1 << 20;
66
+ export const LIST_MAX = 2000, BARRED_MAX = 10000, PINS_MAX = 50, LINKS_MAX = 16, GRANTS_MAX = 64, STATE_PARTS = 8, LETTER_PARTS = 64;
67
+
68
+ // ---------------------------------------------------------------- roles
69
+ export const ROLES = ['owner', 'admin', 'moderator', 'member'];
70
+ const RANK = { owner: 3, admin: 2, moderator: 1, member: 0 };
71
+ // The agent-allowed flag. A `role` body carries `agent`: true when the member it names is an agent.
72
+ // Which roles an agent may hold, and who may grant them, is this table, read by every member, not
73
+ // the wire: any agent may be moderator (granted by an admin); only the owner's own agents may be
74
+ // admin, so an agent-flagged admin grant is valid only when the owner signs it (the owner vouches
75
+ // that the agent is its own). Other operators' agents: moderator at most. null would refuse a role.
76
+ export const AGENT_ROLES = Object.freeze({ moderator: 'admin', admin: 'owner', member: 'admin' });
77
+
78
+ // ---------------------------------------------------------------- bytes
79
+ export const hex = (b) => bytesToHex(b);
80
+ const u32 = (n) => { const b = new Uint8Array(4); new DataView(b.buffer).setUint32(0, n); return b; };
81
+ const u = (s) => utf8ToBytes(s);
82
+ const isObject = (x) => typeof x === 'object' && x !== null && !Array.isArray(x);
83
+ export const b64u = (b) => {
84
+ let s = '';
85
+ for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode.apply(null, b.subarray(i, i + 0x8000));
86
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
87
+ };
88
+ /** Unpadded base64url → bytes, or null. Strict: re-encoding must give the same text. */
89
+ export function unb64u(s) {
90
+ if (typeof s !== 'string' || !/^[A-Za-z0-9_-]*$/.test(s)) return null;
91
+ let b;
92
+ try { const t = atob(s.replace(/-/g, '+').replace(/_/g, '/')); b = new Uint8Array(t.length); for (let i = 0; i < t.length; i++) b[i] = t.charCodeAt(i); } catch { return null; }
93
+ return b64u(b) === s ? b : null;
94
+ }
95
+ const bytesOf = (s, len, check, what) => { const b = unb64u(s); if (b === null || (len !== undefined && b.length !== len)) fail(check, `${what}: expected ${len} bytes as unpadded base64url`); return b; };
96
+ const need32 = (b, what) => { if (!(b instanceof Uint8Array) || b.length !== 32) fail('group_key', `${what} must be 32 bytes`); return b; };
97
+ const gidBytes = (gid) => { if (typeof gid !== 'string' || !GID.test(gid)) fail('group_message', 'gid: 16 bytes, hex'); return hexToBytes(gid); };
98
+ const kdf = (ikm, gid, info, len = 32) => hkdf(sha256, ikm, gidBytes(gid), typeof info === 'string' ? u(info) : info, len);
99
+
100
+ // ---------------------------------------------------------------- identifiers
101
+ const GID = /^[0-9a-f]{32}$/, MID = /^[0-9a-f]{16}$/, HEX64 = /^[0-9a-f]{64}$/, DID = /^did:sigelo:z[1-9A-HJ-NP-Za-km-z]{20,60}$/;
102
+ const HOST = /^[a-z0-9.-]{1,253}(:[0-9]{1,5})?$/, DOOR = /^d\/[0-9a-f]{32}$/, REPLY = /^i\/[0-9a-f]{32}$/, TOPIC = /^g\/[0-9a-f]{32}$/;
103
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/;
104
+ const TEXT_CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/;
105
+ const MIME = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,62}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,62}$/;
106
+ // One emoji, by its structure (u flag only, so every engine the app runs on reads it alike): a flag
107
+ // pair, a keycap, or a pictograph with its variation selector, skin tone, tag sequence and ZWJ joins.
108
+ const EMOJI = /^(?:\p{Regional_Indicator}{2}|[#*0-9]\uFE0F?\u20E3|\p{Extended_Pictographic}\uFE0F?\p{Emoji_Modifier}?(?:[\u{E0020}-\u{E007E}]+\u{E007F})?(?:\u200D\p{Extended_Pictographic}\uFE0F?\p{Emoji_Modifier}?)*)$/u;
109
+
110
+ /** gid: the first 16 bytes of SHA-256("sigelo-group/2 gid\n" ‖ creator's original DID ‖ "\n" ‖ nonce), hex. */
111
+ export function gidOf(creator, nonce) {
112
+ if (typeof creator !== 'string' || !DID.test(creator)) fail('group_message', 'creator: a did:sigelo');
113
+ if (typeof nonce !== 'string' || !GID.test(nonce)) fail('group_message', 'nonce: 16 bytes, hex');
114
+ return hex(sha256(u(`sigelo-group/2 gid\n${creator}\n${nonce}`)).slice(0, 16));
115
+ }
116
+ /** The group's log at its home relay: "g/" + the first 16 bytes of SHA-256("sigelo-home/0 topic\n" ‖ gid bytes), hex. */
117
+ export const topicOf = (gid) => 'g/' + hex(sha256(concatBytes(u('sigelo-home/0 topic\n'), gidBytes(gid))).slice(0, 16));
118
+ export const newNonce = (rng = randomBytes) => hex(rng(16));
119
+ export const newMid = (rng = randomBytes) => hex(rng(8));
120
+ export const newLinkId = (rng = randomBytes) => hex(rng(8));
121
+ export const newDoor = (rng = randomBytes) => 'd/' + hex(rng(16));
122
+ export const newReply = (rng = randomBytes) => 'i/' + hex(rng(16));
123
+
124
+ // ---------------------------------------------------------------- the key schedule
125
+ // HKDF-SHA256, salt = the gid's 16 bytes, 32 bytes out. An epoch number in a label is its 4 bytes,
126
+ // big-endian; a DID is its UTF-8 text; a link id its 8 bytes.
127
+ const writeKey = (seed) => ({ seed, pub: ed25519.getPublicKey(seed) });
128
+ /** The epoch's keys from its secret E: the member write key W (Ed25519) and the header key HK. */
129
+ export function epochKeys(E, gid) {
130
+ need32(E, 'E');
131
+ return { W: writeKey(kdf(E, gid, 'sigelo-group/2 write')), HK: kdf(E, gid, 'sigelo-group/2 header') };
132
+ }
133
+ /** The admin write key AW of an epoch, from the admin vault V. */
134
+ export const adminKey = (V, gid, epoch) => writeKey(kdf(need32(V, 'V'), gid, concatBytes(u('sigelo-group/2 admin write\n'), u32(epochNumber(epoch)))));
135
+ /** The key that seals the door seeds and each member's letter key for admins (the add body's vault, the link's box). */
136
+ export const vaultKey = (V, gid) => kdf(need32(V, 'V'), gid, 'sigelo-group/2 vault');
137
+ /** A sender's chain start in an epoch: CK0 = HKDF(E, "sigelo-group/2 chain\n" ‖ its original DID). */
138
+ export const chainStart = (E, gid, did) => kdf(need32(E, 'E'), gid, `sigelo-group/2 chain\n${checkDid(did)}`);
139
+ /** The key a mid-epoch joiner's chain start is sealed under in its add body: HKDF(HK, "sigelo-group/2 add"). */
140
+ export const addKey = (HK, gid) => kdf(need32(HK, 'HK'), gid, 'sigelo-group/2 add');
141
+ /** The hook for group calls (later): HKDF(E, "sigelo-group/2 call\n" ‖ call id, 32 hex). */
142
+ export function callKey(E, gid, id) {
143
+ if (typeof id !== 'string' || !GID.test(id)) fail('group_message', 'call id: 16 bytes, hex');
144
+ return kdf(need32(E, 'E'), gid, `sigelo-group/2 call\n${id}`);
145
+ }
146
+ /** The sender hint in a sealed header: the first 8 bytes of HMAC-SHA256(HK, the sender's original DID). */
147
+ export const senderHint = (HK, did) => hmac(sha256, need32(HK, 'HK'), u(checkDid(did))).slice(0, 8);
148
+ /** The message key at counter n from a chain start (kdf.mjs step: HMAC(CK, 1), next HMAC(CK, 2)). ck0 is kept. */
149
+ export function messageKey(ck0, n) {
150
+ if (!Number.isSafeInteger(n) || n < 0 || n > EPOCH_MAX) fail('group_entry', 'n: 0 to 2^32-1');
151
+ let ck = need32(ck0, 'a chain key').slice();
152
+ for (let i = 0; ; i++) { const { mk, next } = step(ck); if (i === n) { next.fill(0); return mk; } mk.fill(0); ck = next; }
153
+ }
154
+ /** A chain moved on by k steps: {ck} for counter n + k. ck is kept. */
155
+ export function chainAt(ck0, k) {
156
+ let ck = need32(ck0, 'a chain key').slice();
157
+ for (let i = 0; i < k; i++) { const { mk, next } = step(ck); mk.fill(0); ck = next; }
158
+ return ck;
159
+ }
160
+ // Letter keys: hint and box key for epoch e+1, then the step once the relay switched.
161
+ export const letterHint = (L, next) => hex(hmac(sha256, need32(L, 'L'), concatBytes(u('sigelo-group/2 hint\n'), u32(epochNumber(next)))).slice(0, 8));
162
+ const letterBoxKey = (L, gid, next) => kdf(need32(L, 'L'), gid, concatBytes(u('sigelo-group/2 letter\n'), u32(epochNumber(next))));
163
+ /** L ← HKDF(L, "sigelo-group/2 next"); the caller deletes the old one. */
164
+ export const nextLetterKey = (L, gid) => kdf(need32(L, 'L'), gid, 'sigelo-group/2 next');
165
+ function epochNumber(e) { if (!Number.isSafeInteger(e) || e < 1 || e > EPOCH_MAX) fail('group_epoch', 'an epoch is 1 to 2^32-1'); return e; }
166
+ function checkDid(d) { if (typeof d !== 'string' || !DID.test(d)) fail('group_message', 'not a did:sigelo'); return d; }
167
+
168
+ // ---------------------------------------------------------------- seals
169
+ // box = nonce (24) ‖ XChaCha20-Poly1305(key, plaintext, aad) + tag (16).
170
+ export function seal(key, pt, aad = new Uint8Array(0), rng = randomBytes) {
171
+ const nonce = rng(NONCE);
172
+ return concatBytes(nonce, xchacha20poly1305(key, nonce, aad).encrypt(pt));
173
+ }
174
+ export function unseal(key, box, aad = new Uint8Array(0), what = 'a box') {
175
+ if (!(box instanceof Uint8Array) || box.length < NONCE + TAG) fail('group_key', `${what} is shorter than a nonce and a tag`);
176
+ try { return xchacha20poly1305(key, box.subarray(0, NONCE), aad).decrypt(box.subarray(NONCE)); } catch { fail('group_key', `${what} does not open: another key, or altered`); }
177
+ }
178
+ // X-Wing seals to one member's gkey: {kem (1,120 bytes), box}, box key = HKDF(shared, gid, label).
179
+ // label names the purpose and the epoch, so a box cannot be taken for another one.
180
+ const kemLabel = (purpose, epoch) => concatBytes(u(`sigelo-group/2 ${purpose}\n`), u32(epochNumber(epoch)));
181
+ export function kemSeal(pub, gid, purpose, epoch, pt, rng = randomBytes) {
182
+ if (!(pub instanceof Uint8Array) || pub.length !== XWING_PUB) fail('group_key', 'a gkey is an X-Wing public key, 1,216 bytes');
183
+ const { cipherText, sharedSecret } = xwing.encapsulate(pub, rng(64));
184
+ return { kem: cipherText, box: seal(kdf(sharedSecret, gid, kemLabel(purpose, epoch)), pt, new Uint8Array(0), rng) };
185
+ }
186
+ export function kemOpen(secretKey, gid, purpose, epoch, kem, box) {
187
+ if (!(kem instanceof Uint8Array) || kem.length !== XWING_CT) fail('group_key', 'an X-Wing ciphertext is 1,120 bytes');
188
+ let ss;
189
+ try { ss = xwing.decapsulate(kem, secretKey); } catch { fail('group_key', `the ${purpose} box: the X-Wing ciphertext does not decapsulate`); }
190
+ return unseal(kdf(ss, gid, kemLabel(purpose, epoch)), box, new Uint8Array(0), `the ${purpose} box`);
191
+ }
192
+ /** A member box key pair (gkey) or a door key pair from a 32-byte seed. */
193
+ export const boxKey = (seed) => xwing.keygen(need32(seed, 'a seed'));
194
+
195
+ // ---------------------------------------------------------------- letters
196
+ /** A symmetric letter to a member holding L: {hint, box}; box opens to E' (32) [‖ V (32) for an admin]. */
197
+ export function letter(L, gid, next, secret, rng = randomBytes) {
198
+ if (!(secret instanceof Uint8Array) || (secret.length !== 32 && secret.length !== 64)) fail('group_key', 'a letter carries E\' (32 bytes), or E\' and V (64)');
199
+ return { hint: letterHint(L, next), box: b64u(seal(letterBoxKey(L, gid, next), secret, new Uint8Array(0), rng)) };
200
+ }
201
+ /** A KEM letter to a member's gkey: {hint, kem, box}; box opens to a fresh L (32) ‖ E' (32) [‖ V (32)]. hint under its current L. */
202
+ export function kemLetter(L, gkey, gid, next, secret, rng = randomBytes) {
203
+ if (!(secret instanceof Uint8Array) || (secret.length !== 64 && secret.length !== 96)) fail('group_key', 'a KEM letter carries a fresh L and E\' (64 bytes), or L, E\' and V (96)');
204
+ const { kem, box } = kemSeal(gkey, gid, 'kem letter', next, secret, rng);
205
+ return { hint: letterHint(L, next), kem: b64u(kem), box: b64u(box) };
206
+ }
207
+ /** This member's letter among an epoch body's: → {E, V?, L?} (L when a KEM letter gave a fresh one), or null. */
208
+ export function openLetter(letters, L, gid, next, gkeySecret = null) {
209
+ const hint = letterHint(L, next), mine = letters.filter((x) => x.hint === hint);
210
+ if (mine.length === 0) return null;
211
+ if (mine.length > 1) fail('group_message', 'two letters with one hint');
212
+ const x = mine[0];
213
+ if (x.kem === undefined) {
214
+ const s = unseal(letterBoxKey(L, gid, next), bytesOf(x.box, undefined, 'group_message', 'box'), new Uint8Array(0), 'a letter');
215
+ return { E: s.slice(0, 32), V: s.length === 64 ? s.slice(32) : null };
216
+ }
217
+ if (gkeySecret === null) fail('group_key', 'a KEM letter needs this member\'s gkey');
218
+ const s = kemOpen(gkeySecret, gid, 'kem letter', next, bytesOf(x.kem, XWING_CT, 'group_message', 'kem'), bytesOf(x.box, undefined, 'group_message', 'box'));
219
+ if (s.length !== 64 && s.length !== 96) fail('group_key', 'a KEM letter that does not hold L and E\'');
220
+ return { L: s.slice(0, 32), E: s.slice(32, 64), V: s.length === 96 ? s.slice(64) : null };
221
+ }
222
+
223
+ // ---------------------------------------------------------------- canonical JSON in a seal
224
+ const enc = (x) => u(canonicalize(x));
225
+ /** Bytes that must be the JCS of one JSON value: strict parse (duplicate keys refused), then re-encoded and compared. */
226
+ export function decodeJcs(bytes, what) {
227
+ let x;
228
+ try { x = parseBytes(bytes); } catch (e) { fail('group_message', `${what} does not parse as JSON: ${e.message}`); }
229
+ if (canonicalize(x) !== new TextDecoder().decode(bytes)) fail('group_message', `${what} is not in canonical form (JCS)`);
230
+ return x;
231
+ }
232
+
233
+ // ---------------------------------------------------------------- the entry bytes
234
+ /** The bytes the credential signature covers: "sigelo-home/0 entry\n" ‖ topic ‖ bytes 0-7 ‖ SHA-256(bytes 72 to the end). */
235
+ export const credentialInput = (bytes, topic) => concatBytes(u('sigelo-home/0 entry\n'), u(checkTopic(topic)), bytes.subarray(0, 8), sha256(bytes.subarray(HEAD)));
236
+ function checkTopic(t) { if (typeof t !== 'string' || !TOPIC.test(t)) fail('group_entry', 'topic: g/ and 32 hex'); return t; }
237
+
238
+ /**
239
+ * Seal one entry. content = {body, sig, chain?} (signed already: sign, then encrypt). write = the
240
+ * epoch's W, or AW with flags.admin; hint and n from the sender's chain; mk = messageKey(ck0, n).
241
+ */
242
+ export function sealEntry({ topic, epoch, flags = 0, slot = 0, write, HK, hint, n, mk, content }, rng = randomBytes) {
243
+ checkTopic(topic); epochNumber(epoch); checkFlags(flags, slot);
244
+ checkContent(content);
245
+ checkEntryBody(flags, slot, content.body);
246
+ if (content.body.epoch !== epoch) fail('group_epoch', `a body of epoch ${content.body.epoch} in an entry of epoch ${epoch}`);
247
+ const head = new Uint8Array(HEAD);
248
+ head[0] = VERSION; head[1] = KIND_ENTRY; head[2] = flags; head[3] = slot; head.set(u32(epoch), 4);
249
+ const t = u(topic), hn = rng(NONCE);
250
+ const h8 = head.subarray(0, 8), header = xchacha20poly1305(need32(HK, 'HK'), hn, concatBytes(h8, t)).encrypt(concatBytes(hint, u32(n)));
251
+ const bn = rng(NONCE), pt = pad(enc(content));
252
+ const out = concatBytes(head, hn, header, bn, xchacha20poly1305(need32(mk, 'mk'), bn, concatBytes(h8, hn, header, bn, t)).encrypt(pt));
253
+ if (out.length > MAX_ENTRY) fail('group_entry', `a ${out.length}-byte entry, at most ${MAX_ENTRY}`);
254
+ out.set(ed25519.sign(credentialInput(out, topic), write.seed), 8);
255
+ return out;
256
+ }
257
+ function checkFlags(flags, slot) {
258
+ if (!Number.isInteger(flags) || flags < 0 || flags > 7) fail('group_entry', 'flags: bits 0 to 2 only (admin credential, keep, letters part)');
259
+ if ((flags & FLAG.keep) ? !(slot >= 1 && slot <= KEEP_MAX) : slot !== 0) fail('group_entry', `keep slot: 1 to ${KEEP_MAX} with the keep flag, else 0`);
260
+ if ((flags & FLAG.letters) && !(flags & FLAG.admin)) fail('group_entry', 'a letters part goes under the admin credential');
261
+ if ((flags & FLAG.keep) && !(flags & FLAG.admin)) fail('group_entry', 'a kept entry goes under the admin credential');
262
+ if ((flags & FLAG.keep) && (flags & FLAG.letters)) fail('group_entry', 'a letters part is never kept');
263
+ }
264
+ /** Structure only, as the relay reads it: → {flags, slot, epoch, sig}. Nothing is authenticated here. */
265
+ export function parseEntry(bytes) {
266
+ if (!(bytes instanceof Uint8Array) || bytes.length < BODY + 256 + TAG) fail('group_entry', 'shorter than a head, a header and one padded block');
267
+ if (bytes.length > MAX_ENTRY) fail('group_entry', `${bytes.length} bytes, at most ${MAX_ENTRY}`);
268
+ if (bytes[0] !== VERSION) fail('group_entry', `version byte ${bytes[0]}, this reader knows ${VERSION}`);
269
+ if (bytes[1] !== KIND_ENTRY) fail('group_entry', `kind ${bytes[1]}, a log entry is ${KIND_ENTRY}`);
270
+ if ((bytes.length - BODY - TAG) % 256 !== 0) fail('group_entry', `${bytes.length} bytes is not a head, a header and a padded body`);
271
+ checkFlags(bytes[2], bytes[3]);
272
+ const epoch = new DataView(bytes.buffer, bytes.byteOffset + 4, 4).getUint32(0);
273
+ if (epoch < 1) fail('group_entry', 'epoch 0: an entry is under epoch 1 or later');
274
+ return { flags: bytes[2], slot: bytes[3], epoch, sig: bytes.subarray(8, HEAD) };
275
+ }
276
+ /** The relay's check (and anyone's): the credential signature under the epoch's write key, or its admin key with flag bit 0. */
277
+ export function credentialOk(bytes, topic, { write, admin }) {
278
+ const { flags, sig } = parseEntry(bytes);
279
+ const pub = flags & FLAG.admin ? admin : write;
280
+ try { return ed25519.verify(sig, credentialInput(bytes, topic), pub); } catch { return false; }
281
+ }
282
+ /** A member's first step: the sealed header under HK → {hint (8 bytes), n}. */
283
+ export function openHeader(bytes, topic, HK) {
284
+ parseEntry(bytes);
285
+ const t = u(checkTopic(topic));
286
+ let p;
287
+ try { p = xchacha20poly1305(need32(HK, 'HK'), bytes.subarray(HEADER_NONCE, SEALED_HEADER), concatBytes(bytes.subarray(0, 8), t)).decrypt(bytes.subarray(SEALED_HEADER, BODY_NONCE)); } catch { fail('group_key', 'the header does not open under this epoch\'s header key'); }
288
+ return { hint: p.slice(0, 8), n: new DataView(p.buffer, p.byteOffset + 8, 4).getUint32(0) };
289
+ }
290
+ /** The second: the body under the sender's message key at n → {body, sig, chain?}, checked (table, epoch, flags). Not the signature: verifyContent. */
291
+ export function openEntry(bytes, topic, mk) {
292
+ const { flags, slot, epoch } = parseEntry(bytes);
293
+ const t = u(checkTopic(topic));
294
+ let pt;
295
+ try { pt = xchacha20poly1305(need32(mk, 'mk'), bytes.subarray(BODY_NONCE, BODY), concatBytes(bytes.subarray(0, 8), bytes.subarray(HEAD, BODY), t)).decrypt(bytes.subarray(BODY)); } catch { fail('group_key', 'the body does not open under this message key'); }
296
+ let text;
297
+ try { text = unpad(pt); } catch { fail('group_entry', 'the body is not padded 0x80 then zeros to a multiple of 256'); }
298
+ const content = checkContent(decodeJcs(text, 'the body'));
299
+ checkEntryBody(flags, slot, content.body);
300
+ if (content.body.epoch !== epoch) fail('group_epoch', `a body of epoch ${content.body.epoch} in an entry of epoch ${epoch}`);
301
+ return content;
302
+ }
303
+ // What the flags say about the body inside: letters part ⇔ an epoch body; keep slots 1-8 a state,
304
+ // 9 the avatar's one blob part, 10-32 nothing yet (refused).
305
+ function checkEntryBody(flags, slot, body) {
306
+ if (body.typ === 'join' || body.typ === 'answer') fail('group_entry', `a ${body.typ} goes through a door or a reply topic, never the log`);
307
+ if (Boolean(flags & FLAG.letters) !== (body.typ === 'epoch')) fail('group_entry', 'the letters-part flag is set for an epoch body and only for one');
308
+ if (flags & FLAG.keep) {
309
+ if (slot >= KEEP_STATE[0] && slot <= KEEP_STATE[1]) { if (body.typ !== 'state' || body.part !== slot) fail('group_entry', `keep slot ${slot} holds state part ${slot}`); }
310
+ else if (slot === KEEP_AVATAR) { if (body.typ !== 'blob' || body.parts !== 1) fail('group_entry', 'keep slot 9 holds the avatar: one blob part'); }
311
+ else fail('group_entry', `keep slot ${slot} is not in use (state 1-8, avatar 9)`);
312
+ } else if (body.typ === 'state') fail('group_entry', 'a state part is kept (keep flag, slot = its part)');
313
+ }
314
+
315
+ // ---------------------------------------------------------------- the door and the answer
316
+ const doorLabel = (link) => concatBytes(u('sigelo-group/2 door\n'), hexToBytes(link));
317
+ const answerLabel = (link) => concatBytes(u('sigelo-group/2 answer\n'), hexToBytes(link));
318
+ // 0x02 ‖ kind ‖ link id (8) ‖ X-Wing ciphertext (1,120) ‖ nonce (24) ‖ sealed padded JCS + tag.
319
+ // The additional data is the bytes before the nonce ‖ the topic it is published to.
320
+ function sealTo(kind, label, max, { pub, gid, link, topic, content }, rng) {
321
+ if (typeof link !== 'string' || !MID.test(link)) fail('group_message', 'link: 8 bytes, hex');
322
+ if (!(pub instanceof Uint8Array) || pub.length !== XWING_PUB) fail('group_key', 'an X-Wing public key is 1,216 bytes');
323
+ const { cipherText, sharedSecret } = xwing.encapsulate(pub, rng(64));
324
+ const head = concatBytes(Uint8Array.of(VERSION, kind), hexToBytes(link), cipherText), nonce = rng(NONCE);
325
+ const out = concatBytes(head, nonce, xchacha20poly1305(kdf(sharedSecret, gid, label(link)), nonce, concatBytes(head, u(topic))).encrypt(pad(enc(content))));
326
+ if (out.length > max) fail('group_entry', `a ${out.length}-byte request, at most ${max}`);
327
+ return out;
328
+ }
329
+ function openFrom(kind, label, max, what, bytes, { secretKey, gid, topic }) {
330
+ const H = 2 + 8 + XWING_CT;
331
+ if (!(bytes instanceof Uint8Array) || bytes.length < H + NONCE + 256 + TAG || bytes.length > max) fail('group_entry', `${what}: ${bytes?.length} bytes, ${H + NONCE + 256 + TAG} to ${max}`);
332
+ if (bytes[0] !== VERSION || bytes[1] !== kind) fail('group_entry', `${what}: version ${bytes[0]} kind ${bytes[1]}, expected ${VERSION} and ${kind}`);
333
+ if ((bytes.length - H - NONCE - TAG) % 256 !== 0) fail('group_entry', `${what}: not a padded body`);
334
+ const link = hex(bytes.subarray(2, 10));
335
+ let ss;
336
+ try { ss = xwing.decapsulate(bytes.subarray(10, H), secretKey); } catch { fail('group_key', `${what}: the X-Wing ciphertext does not decapsulate`); }
337
+ let pt;
338
+ try { pt = xchacha20poly1305(kdf(ss, gid, label(link)), bytes.subarray(H, H + NONCE), concatBytes(bytes.subarray(0, H), u(topic))).decrypt(bytes.subarray(H + NONCE)); } catch { fail('group_key', `${what} does not open under this key`); }
339
+ let text;
340
+ try { text = unpad(pt); } catch { fail('group_entry', `${what}: not padded 0x80 then zeros`); }
341
+ return { link, content: decodeJcs(text, what) };
342
+ }
343
+ /** A joiner's door request: its signed join, sealed to the link's door key, published to the link's d/ topic. */
344
+ export function sealDoor({ doorKey, gid, door, content }, rng = randomBytes) {
345
+ if (typeof door !== 'string' || !DOOR.test(door)) fail('group_message', 'door: d/ and 32 hex');
346
+ checkJoin(content, gid);
347
+ return sealTo(KIND_DOOR, doorLabel, MAX_DOOR, { pub: doorKey, gid, link: content.body.link, topic: door, content }, rng);
348
+ }
349
+ /** An admin opens a door request (the door key's secret half) → {link, content: {body: join, sig}}; the link id outside must be the one signed inside. */
350
+ export function openDoor(bytes, { doorSecret, gid, door }) {
351
+ const r = openFrom(KIND_DOOR, doorLabel, MAX_DOOR, 'a door request', bytes, { secretKey: doorSecret, gid, topic: door });
352
+ checkJoin(r.content, gid);
353
+ if (r.content.body.link !== r.link) fail('group_message', 'a door request whose join names another link');
354
+ return r;
355
+ }
356
+ function checkJoin(content, gid) {
357
+ if (!isObject(content) || !exactKeys(content, ['body', 'sig'])) fail('group_message', 'a door request holds {body, sig}');
358
+ checkContent(content);
359
+ if (content.body.typ !== 'join') fail('group_message', 'a door request holds a join');
360
+ if (content.body.gid !== gid) fail('group_message', 'a join for another group');
361
+ }
362
+ /** The admin's answer on the joiner's reply topic: its signed answer and chain, sealed to the joiner's gkey. */
363
+ export function sealAnswer({ gkey, gid, link, reply, content }, rng = randomBytes) {
364
+ if (typeof reply !== 'string' || !REPLY.test(reply)) fail('group_message', 'reply: i/ and 32 hex');
365
+ checkContent(content);
366
+ if (content.body.typ !== 'answer' || content.chain === undefined) fail('group_message', 'an answer holds {body: answer, sig, chain}');
367
+ return sealTo(KIND_ANSWER, answerLabel, MAX_ANSWER, { pub: gkey, gid, link, topic: reply, content }, rng);
368
+ }
369
+ export function openAnswer(bytes, { gkeySecret, gid, reply }) {
370
+ const r = openFrom(KIND_ANSWER, answerLabel, MAX_ANSWER, 'an answer', bytes, { secretKey: gkeySecret, gid, topic: reply });
371
+ checkContent(r.content);
372
+ if (r.content.body.typ !== 'answer' || r.content.chain === undefined || r.content.body.gid !== gid) fail('group_message', 'an answer holds {body: answer for this group, sig, chain}');
373
+ return r;
374
+ }
375
+
376
+ // ---------------------------------------------------------------- the bodies
377
+ // A field is [test, what it must be, check]: the check a failure names (group_message, or
378
+ // group_text for a name or a text). The refusal: `not a sigelo-group/2 <typ>: <field> must be <what>`.
379
+ const exactKeys = (x, keys) => Object.keys(x).length === keys.length && keys.every((k) => Object.hasOwn(x, k));
380
+ const len = (s) => [...s].length;
381
+ const an = (w) => (/^[aeiou]/.test(w) ? 'an ' : 'a ') + w;
382
+ const F = {};
383
+ const def = (name, test, what, check = 'group_message') => { F[name] = [test, what, check]; };
384
+ def('did', (x) => typeof x === 'string' && DID.test(x), 'a did:sigelo');
385
+ def('gid', (x) => typeof x === 'string' && GID.test(x), '16 bytes, hex');
386
+ def('hex8', (x) => typeof x === 'string' && MID.test(x), '8 bytes, hex');
387
+ def('hex16', (x) => typeof x === 'string' && GID.test(x), '16 bytes, hex');
388
+ def('sha256', (x) => typeof x === 'string' && HEX64.test(x), 'a SHA-256, 64 hex');
389
+ def('time', (x) => Number.isSafeInteger(x) && x >= 0, 'unix seconds');
390
+ def('epoch', (x) => Number.isSafeInteger(x) && x >= 1 && x <= EPOCH_MAX, 'an epoch, 1 to 2^32-1');
391
+ def('zero', (x) => x === 0, '0 (a join is under no epoch)');
392
+ def('seq', (x) => Number.isSafeInteger(x) && x >= 0, 'a seq, a whole number from 0');
393
+ def('seq1', (x) => Number.isSafeInteger(x) && x >= 1, 'a seq, a whole number from 1');
394
+ def('n', (x) => Number.isSafeInteger(x) && x >= 0 && x <= EPOCH_MAX, 'a counter, 0 to 2^32-1');
395
+ def('host', (x) => typeof x === 'string' && HOST.test(x), 'a host name, lower case, with an optional :port');
396
+ def('door', (x) => typeof x === 'string' && DOOR.test(x), 'd/ and 32 hex');
397
+ def('reply', (x) => typeof x === 'string' && REPLY.test(x), 'i/ and 32 hex');
398
+ def('topic', (x) => typeof x === 'string' && TOPIC.test(x), 'g/ and 32 hex');
399
+ def('bool', (x) => typeof x === 'boolean', 'true or false');
400
+ def('kind', (x) => x === 'human' || x === 'agent', 'human or agent');
401
+ def('role', (x) => ROLES.includes(x), 'owner, admin, moderator or member');
402
+ def('modCaps', (x) => isObject(x) && exactKeys(x, ['kicks', 'deletes']) && Number.isSafeInteger(x.kicks) && x.kicks >= 0 && x.kicks <= MOD_KICKS
403
+ && Number.isSafeInteger(x.deletes) && x.deletes >= 0 && x.deletes <= MOD_DELETES, `{kicks: 0 to ${MOD_KICKS}, deletes: 0 to ${MOD_DELETES}}, a UTC day`);
404
+ def('grant', (x) => x === 'admin' || x === 'moderator' || x === 'member', 'admin, moderator or member');
405
+ def('approve', (x) => x === 'auto' || x === 'admin', 'auto or admin');
406
+ def('gkey', (x) => unb64u(x)?.length === XWING_PUB, 'an X-Wing public key, 1,216 bytes, unpadded base64url');
407
+ def('kem', (x) => unb64u(x)?.length === XWING_CT, 'an X-Wing ciphertext, 1,120 bytes, unpadded base64url');
408
+ def('key32', (x) => unb64u(x)?.length === 32, '32 bytes, unpadded base64url');
409
+ def('sealed32', (x) => unb64u(x)?.length === NONCE + 32 + TAG, '32 bytes sealed (72), unpadded base64url');
410
+ def('box', (x) => { const b = unb64u(x); return b !== null && b.length >= NONCE + TAG && b.length <= MAX_ENTRY; }, 'a nonce and a sealed box, unpadded base64url');
411
+ def('data', (x) => { const b = unb64u(x); return b !== null && b.length >= 1 && b.length <= BLOB_PART; }, `1 to ${BLOB_PART} bytes, unpadded base64url`);
412
+ def('mime', (x) => typeof x === 'string' && MIME.test(x), 'a media type, lower case');
413
+ def('name', (x) => typeof x === 'string' && x.trim() === x && x !== '' && len(x) <= NAME_MAX && !CONTROL.test(x), `1 to ${NAME_MAX} characters, trimmed, no control or bidi characters`, 'group_text');
414
+ def('memberName', (x) => typeof x === 'string' && x.trim() === x && x !== '' && len(x) <= MEMBER_NAME_MAX && !CONTROL.test(x), `1 to ${MEMBER_NAME_MAX} characters, trimmed, no control or bidi characters`, 'group_text');
415
+ def('fileName', (x) => typeof x === 'string' && x !== '' && len(x) <= 255 && !CONTROL.test(x) && !/[/\\]/.test(x), '1 to 255 characters, no control characters, no / or \\', 'group_text');
416
+ def('text', (x) => typeof x === 'string' && x.trim() !== '' && len(x) <= TEXT_MAX && !TEXT_CONTROL.test(x), `1 to ${TEXT_MAX} characters, no control characters but tab and new line`, 'group_text');
417
+ def('about', (x) => typeof x === 'string' && len(x) <= ABOUT_MAX && !TEXT_CONTROL.test(x), `0 to ${ABOUT_MAX} characters, no control characters but tab and new line`, 'group_text');
418
+ def('reason', (x) => typeof x === 'string' && x.trim() !== '' && len(x) <= REASON_MAX && !TEXT_CONTROL.test(x), `1 to ${REASON_MAX} characters`, 'group_text');
419
+ def('question', (x) => typeof x === 'string' && x.trim() !== '' && len(x) <= QUESTION_MAX && !CONTROL.test(x), `1 to ${QUESTION_MAX} characters, no control or bidi characters`, 'group_text');
420
+ def('options', (x) => Array.isArray(x) && x.length >= OPTIONS[0] && x.length <= OPTIONS[1] && x.every((o) => typeof o === 'string' && o.trim() !== '' && len(o) <= OPTION_MAX && !CONTROL.test(o)) && new Set(x).size === x.length, `${OPTIONS[0]} to ${OPTIONS[1]} distinct options of 1 to ${OPTION_MAX} characters`, 'group_text');
421
+ def('emoji', (x) => typeof x === 'string' && u(x).length <= EMOJI_BYTES && EMOJI.test(x), `one emoji, at most ${EMOJI_BYTES} bytes`);
422
+ def('choices', (x) => Array.isArray(x) && x.length <= OPTIONS[1] && x.every((c, i) => Number.isSafeInteger(c) && c >= 0 && c < OPTIONS[1] && (i === 0 || c > x[i - 1])), 'option indexes 0 to 9, ascending, each once (empty withdraws)');
423
+ def('mids', (x) => Array.isArray(x) && x.length >= 1 && x.length <= BLOB_PARTS && x.every((m) => typeof m === 'string' && MID.test(m)) && new Set(x).size === x.length, `1 to ${BLOB_PARTS} distinct mids`);
424
+ def('mentions', (x) => Array.isArray(x) && x.length >= 1 && x.length <= LIST_MAX && x.every((d) => typeof d === 'string' && DID.test(d)) && new Set(x).size === x.length, `1 to ${LIST_MAX} distinct DIDs`);
425
+ def('chain', (x) => isObject(x) && exactKeys(x, ['genesis', 'rotations']) && isObject(x.genesis) && Array.isArray(x.rotations) && x.rotations.length <= CHAIN_MAX && x.rotations.every(isObject), `{genesis, rotations} (at most ${CHAIN_MAX})`);
426
+ def('signed', (x) => isObject(x) && exactKeys(x, ['body', 'sig']) && isObject(x.body) && typeof x.sig === 'string' && x.sig.length <= 200, '{body, sig}');
427
+ def('photo', (x) => { try { checkPhoto(x); return true; } catch { return false; } }, 'a photo preview (photo.mjs)');
428
+ def('voice', (x) => { try { checkVoice(x); return true; } catch { return false; } }, 'a voice message\'s fields (voice.mjs)');
429
+ def('avatar', (x) => x === null || (isObject(x) && exactKeys(x, ['sha256', 'type', 'w', 'h']) && HEX64.test(x.sha256) && ['image/jpeg', 'image/png', 'image/webp'].includes(x.type) && [x.w, x.h].every((d) => Number.isSafeInteger(d) && d >= 1 && d <= 1024)), 'null or {sha256, type (image/jpeg, image/png, image/webp), w, h (1 to 1024)}');
430
+ def('brake', (x) => x === 'off' || (Number.isSafeInteger(x) && x >= 1 && x <= BRAKE_MAX), `"off" or 1 to ${BRAKE_MAX}`);
431
+ def('join', (x) => x === 'request' || x === 'open', 'request or open');
432
+ def('history', (x) => x === 'always' || x === 'request' || x === 'never', 'always, request or never');
433
+ def('cap', (x) => Number.isSafeInteger(x) && x >= 1 && x <= LINK_CAP_MAX, `1 to ${LINK_CAP_MAX} requests a day`);
434
+ def('members', (x) => Number.isSafeInteger(x) && x >= 1, 'a whole number from 1');
435
+ def('part', (x) => Number.isSafeInteger(x) && x >= 1 && x <= LETTER_PARTS, `1 to ${LETTER_PARTS}`);
436
+ def('statePart', (x) => Number.isSafeInteger(x) && x >= 1 && x <= STATE_PARTS, `1 to ${STATE_PARTS}`);
437
+ def('blobPart', (x) => Number.isSafeInteger(x) && x >= 1 && x <= BLOB_PARTS, `1 to ${BLOB_PARTS}`);
438
+ def('next', (x) => Number.isSafeInteger(x) && x >= 2 && x <= EPOCH_MAX, 'an epoch, 2 to 2^32-1');
439
+
440
+ // The settings: every key in create and state, one or more in a settings body.
441
+ export const SETTINGS = ['name', 'about', 'avatar', 'channel', 'join', 'history', 'agents', 'brake'];
442
+ // Optional settings: never required in create or state; absent = the default. mod: the daily caps of a member that is
443
+ // capped (a moderator, an admin that is an agent), each member's own software counting its own acts (group2.mjs).
444
+ export const OPTIONAL_SETTINGS = ['mod'];
445
+ const SETTING_FIELD = { name: 'name', about: 'about', avatar: 'avatar', channel: 'bool', join: 'join', history: 'history', agents: 'bool', brake: 'brake', mod: 'modCaps' };
446
+ export const DEFAULTS = Object.freeze({ about: '', avatar: null, channel: false, join: 'request', history: 'request', agents: true, brake: BRAKE });
447
+ /** Owner-only settings: history for new members, the agent-allowed flag, the moderators' daily caps. */
448
+ export const OWNER_SETTINGS = ['history', 'agents', 'mod'];
449
+
450
+ // Every log body begins with these.
451
+ export const BASE = ['v', 'typ', 'gid', 'mid', 'iat', 'from', 'epoch', 'at'];
452
+ const BASE_FIELD = { gid: 'gid', mid: 'hex8', iat: 'time', from: 'did', epoch: 'epoch', at: 'seq' };
453
+ // typ → [required fields, optional fields]; each field → its F entry. Closed: nothing else.
454
+ const R = (o) => o, O = (o) => o;
455
+ export const BODIES = Object.freeze({
456
+ // shape and membership
457
+ create: [R({ name: 'name', nonce: 'hex16', home: 'host', settings: 'settings' }), O({})],
458
+ join: [R({ name: 'memberName', kind: 'kind', gkey: 'gkey', chain: 'chain', link: 'hex8', reply: 'reply' }), O({})],
459
+ add: [R({ member: 'newMember', request: 'signed', vault: 'sealed32', ck: 'sealed32' }), O({})],
460
+ leave: [R({}), O({})],
461
+ kick: [R({ member: 'did', bar: 'bool' }), O({ reason: 'reason' })],
462
+ unbar: [R({ member: 'did' }), O({})],
463
+ role: [R({ member: 'did', role: 'grant', agent: 'bool' }), O({})],
464
+ kind: [R({ member: 'did', kind: 'kind' }), O({})],
465
+ profile: [R({}), O({ name: 'memberName', gkey: 'gkey', chain: 'chain' })],
466
+ handover: [R({ to: 'did' }), O({})],
467
+ settings: [R({ settings: 'someSettings' }), O({})],
468
+ link: [R({ id: 'hex8', door: 'door', door_key: 'gkey', exp: 'time', cap: 'cap', approve: 'approve', box: 'sealed32' }), O({})],
469
+ unlink: [R({ id: 'hex8' }), O({})],
470
+ state: [R({ part: 'statePart', parts: 'statePart', upto: 'seq1', members: 'records', settings: 'settings', pins: 'pins', barred: 'barred', links: 'links', grants: 'grants', cap: 'members' }), O({})],
471
+ moved: [R({ home: 'host', topic: 'topic' }), O({})],
472
+ end: [R({}), O({})],
473
+ // keys
474
+ epoch: [R({ next: 'next', part: 'part', parts: 'part', letters: 'letters' }), O({})],
475
+ vault: [R({ to: 'did', kem: 'kem', box: 'box' }), O({})],
476
+ welcome: [R({ to: 'did', kem: 'kem', box: 'box' }), O({})],
477
+ history: [R({ to: 'did', kem: 'kem', box: 'box' }), O({})],
478
+ history_ask: [R({}), O({})],
479
+ answer: [R({ to: 'did', link: 'hex8', write: 'key32', hk: 'key32', start: 'seq1', welcome: 'seq1', mk: 'key32' }), O({})],
480
+ // content
481
+ msg: [R({}), O({ text: 'text', re: 'hex8', mentions: 'mentions', photo: 'photo', voice: 'voice', file: 'file' })],
482
+ edit: [R({ re: 'hex8', text: 'text' }), O({})],
483
+ delete: [R({ re: 'hex8' }), O({})],
484
+ react: [R({ re: 'hex8', emoji: 'emoji', on: 'bool' }), O({})],
485
+ pin: [R({ re: 'hex8', on: 'bool' }), O({})],
486
+ poll: [R({ question: 'question', options: 'options', multi: 'bool' }), O({ closes: 'time' })],
487
+ vote: [R({ re: 'hex8', choices: 'choices' }), O({})],
488
+ poll_end: [R({ re: 'hex8' }), O({})],
489
+ blob: [R({ sha256: 'sha256', type: 'mime', part: 'blobPart', parts: 'blobPart', data: 'data' }), O({})],
490
+ });
491
+ export const TYPS = Object.freeze(Object.keys(BODIES));
492
+ // Reserved, refused until group calls are built: call.
493
+ export const RESERVED = ['call'];
494
+
495
+ // Nested closed objects, each a field of F.
496
+ const nested = (name, keys, opt, what) => def(name, (x) => { try { checkObject(x, keys, opt, name); return true; } catch { return false; } }, what);
497
+ function checkObject(x, need, may, where) {
498
+ if (!isObject(x)) throw new Error(where);
499
+ const all = { ...need, ...may };
500
+ if (!Object.keys(need).every((k) => Object.hasOwn(x, k)) || !Object.keys(x).every((k) => Object.hasOwn(all, k))) throw new Error(where);
501
+ for (const [k, f] of Object.entries(all)) if (Object.hasOwn(x, k) && !F[f][0](x[k])) throw new Error(where);
502
+ }
503
+ const objFields = (keys) => Object.fromEntries(keys.map((k) => [k, SETTING_FIELD[k]]));
504
+ nested('settings', objFields(SETTINGS), {}, 'settings');
505
+ def('someSettings', (x) => isObject(x) && Object.keys(x).length >= 1 && Object.keys(x).every((k) => SETTINGS.includes(k)) && Object.entries(x).every(([k, v]) => F[SETTING_FIELD[k]][0](v)), `one or more of ${SETTINGS.join(', ')}, each as GROUPS.md says`);
506
+ F.settings[1] = `{${SETTINGS.join(', ')}}, each as GROUPS.md says`;
507
+ nested('newMember', { did: 'did', current: 'did', name: 'memberName', kind: 'kind' }, {}, '{did, current, name, kind}');
508
+ nested('record', { did: 'did', current: 'did', name: 'memberName', kind: 'kind', role: 'role', gkey: 'gkey', chain: 'chain', since: 'seq1' }, {}, 'a member record');
509
+ def('records', (x) => Array.isArray(x) && x.length >= 1 && x.length <= LIST_MAX && x.every(F.record[0]) && new Set(x.map((m) => m.did)).size === x.length, `1 to ${LIST_MAX} member records {did, current, name, kind, role, gkey, chain, since}, each DID once`);
510
+ def('pins', (x) => Array.isArray(x) && x.length <= PINS_MAX && x.every((m) => typeof m === 'string' && MID.test(m)) && new Set(x).size === x.length, `0 to ${PINS_MAX} distinct mids`);
511
+ def('barred', (x) => Array.isArray(x) && x.length <= BARRED_MAX && x.every(F.did[0]) && new Set(x).size === x.length, `0 to ${BARRED_MAX} distinct DIDs`);
512
+ nested('linkRecord', { id: 'hex8', exp: 'time', approve: 'approve' }, {}, '{id, exp, approve}');
513
+ def('links', (x) => Array.isArray(x) && x.length <= LINKS_MAX && x.every(F.linkRecord[0]), `0 to ${LINKS_MAX} {id, exp, approve}`);
514
+ def('grants', (x) => Array.isArray(x) && x.length >= 1 && x.length <= GRANTS_MAX && x.every(F.signed[0]), `1 to ${GRANTS_MAX} signed bodies (create, handovers, role grants)`);
515
+ nested('symLetter', { hint: 'hex8', box: 'box' }, {}, '{hint, box}');
516
+ nested('kemLetter', { hint: 'hex8', kem: 'kem', box: 'box' }, {}, '{hint, kem, box}');
517
+ def('letters', (x) => Array.isArray(x) && x.length >= 1 && x.length <= LIST_MAX && x.every((l) => F.symLetter[0](l) || F.kemLetter[0](l)) && new Set(x.map((l) => l.hint)).size === x.length, `1 to ${LIST_MAX} letters {hint, box} or {hint, kem, box}, each hint once`);
518
+ // A file: up to 8 MiB its parts are blob entries in the log; past it the bytes go direct on
519
+ // request (a transfer manifest's fields, with group calls' code later).
520
+ nested('logFile', { name: 'fileName', size: 'members', sha256: 'sha256', type: 'mime', parts: 'mids' }, {}, 'a file in the log');
521
+ nested('directFile', { name: 'fileName', size: 'members', sha256: 'sha256', type: 'mime', id: 'hex16', chunk: 'members', chunks: 'members', list: 'sha256' }, {}, 'a file sent direct');
522
+ def('file', (x) => (F.logFile[0](x) && x.size <= FILE_IN_LOG && x.parts.length === Math.ceil(x.size / BLOB_PART))
523
+ || (F.directFile[0](x) && x.size > FILE_IN_LOG && x.size <= FILE_MAX && x.chunk === CHUNK && x.chunks === Math.ceil(x.size / CHUNK)),
524
+ `{name, size (1 to ${FILE_IN_LOG}), sha256, type, parts (one mid per ${BLOB_PART} bytes)} or {name, size (past ${FILE_IN_LOG}), sha256, type, id, chunk (${CHUNK}), chunks, list}`);
525
+
526
+ /** A body as its table says, plus the rules between its fields. → the body. Not the signature, not the role. */
527
+ export function checkBody(b) {
528
+ const no = (why, check = 'group_message') => fail(check, `not a ${GROUP2_V} body: ${why}`);
529
+ if (!isObject(b) || b.v !== GROUP2_V) no(`v must be "${GROUP2_V}"`);
530
+ if (RESERVED.includes(b.typ)) no(`typ ${b.typ} is reserved`);
531
+ if (!Object.hasOwn(BODIES, b.typ)) no(`typ must be one of ${TYPS.join(', ')}`);
532
+ const [need, may] = BODIES[b.typ], fields = { ...BASE_FIELD, ...(b.typ === 'join' ? { epoch: 'zero', at: 'zero' } : {}), ...need, ...may };
533
+ const missing = [...BASE, ...Object.keys(need)].filter((k) => !Object.hasOwn(b, k)), extra = Object.keys(b).filter((k) => k !== 'v' && k !== 'typ' && !Object.hasOwn(fields, k));
534
+ if (missing.length || extra.length) no(`a ${b.typ} is {${[...BASE, ...Object.keys(need)].join(', ')}${Object.keys(may).map((k) => `, ${k}?`).join('')}}${missing.length ? `; missing ${missing.join(', ')}` : ''}${extra.length ? `; not allowed ${extra.join(', ')}` : ''}`);
535
+ for (const [k, f] of Object.entries(fields)) {
536
+ if (!Object.hasOwn(b, k)) continue;
537
+ if (f === 'settings' || f === 'someSettings') { checkSettings(b[k], f === 'settings', b.typ); continue; }
538
+ const [test, what, check] = F[f];
539
+ if (!test(b[k])) fail(check, `not a ${GROUP2_V} ${b.typ}: ${k} must be ${what}`);
540
+ }
541
+ const rule = (cond, why, check = 'group_message') => { if (!cond) fail(check, `not a ${GROUP2_V} ${b.typ}: ${why}`); };
542
+ switch (b.typ) {
543
+ case 'create':
544
+ rule(b.epoch === 1 && b.at === 0, 'a create is epoch 1, at 0');
545
+ rule(b.settings.name === b.name, 'settings.name is the name');
546
+ break;
547
+ case 'msg': rule(['text', 'photo', 'voice', 'file'].some((k) => Object.hasOwn(b, k)), 'at least one of text, photo, voice, file'); break;
548
+ case 'profile': rule(['name', 'gkey', 'chain'].some((k) => Object.hasOwn(b, k)), 'at least one of name, gkey, chain'); break;
549
+ case 'link': rule(b.exp - b.iat >= LINK_MIN && b.exp - b.iat <= LINK_MAX, 'exp is 1 hour to 366 days after iat'); break;
550
+ case 'state': rule(b.part <= b.parts, 'part is at most parts'); break;
551
+ case 'epoch':
552
+ rule(b.next === b.epoch + 1, 'next is epoch + 1');
553
+ rule(b.part <= b.parts, 'part is at most parts');
554
+ break;
555
+ case 'blob':
556
+ rule(b.part <= b.parts, 'part is at most parts');
557
+ rule(b.part === b.parts || unb64u(b.data).length === BLOB_PART, `every part but the last is ${BLOB_PART} bytes`);
558
+ break;
559
+ case 'poll': rule(!Object.hasOwn(b, 'closes') || b.closes > b.iat, 'closes is after iat'); break;
560
+ case 'moved': rule(b.topic === topicOf(b.gid), 'topic is the gid\'s (the group keeps its gid at its new home)'); break;
561
+ case 'add': {
562
+ let j;
563
+ try { j = checkContent(b.request).body; } catch (e) { rule(false, `request: ${e.message}`); }
564
+ rule(j.typ === 'join' && j.gid === b.gid, 'request is a join for this group');
565
+ rule(j.from === b.member.current && j.name === b.member.name && j.kind === b.member.kind, 'member is the request\'s current DID, name and kind');
566
+ break;
567
+ }
568
+ }
569
+ return b;
570
+ }
571
+ // Settings, key by key: all eight in create and state, one or more in a settings body.
572
+ function checkSettings(x, full, typ) {
573
+ const no = (why, check = 'group_message') => fail(check, `not a ${GROUP2_V} ${typ}: settings${why}`);
574
+ if (!isObject(x)) no(' must be an object');
575
+ const keys = Object.keys(x), extra = keys.filter((k) => !SETTINGS.includes(k) && !OPTIONAL_SETTINGS.includes(k)), missing = full ? SETTINGS.filter((k) => !Object.hasOwn(x, k)) : [];
576
+ if (extra.length) no(` may hold only ${[...SETTINGS, ...OPTIONAL_SETTINGS].join(', ')}; not allowed ${extra.join(', ')}`);
577
+ if (missing.length) no(` must hold every setting; missing ${missing.join(', ')}`);
578
+ if (keys.length === 0) no(' must hold one or more settings');
579
+ for (const k of [...SETTINGS, ...OPTIONAL_SETTINGS]) if (Object.hasOwn(x, k) && !F[SETTING_FIELD[k]][0](x[k])) no(`.${k} must be ${F[SETTING_FIELD[k]][1]}`, F[SETTING_FIELD[k]][2]);
580
+ }
581
+ /** {body, sig, chain?}: one body, its sender's detached signature, its chain after a rotation. */
582
+ export function checkContent(x) {
583
+ if (!isObject(x) || !Object.hasOwn(x, 'body') || !Object.hasOwn(x, 'sig') || !Object.keys(x).every((k) => k === 'body' || k === 'sig' || k === 'chain')) fail('group_message', `not a ${GROUP2_V} content: {body, sig, chain?}`);
584
+ if (typeof x.sig !== 'string' || x.sig.length < 1 || x.sig.length > 200) fail('group_message', `not a ${GROUP2_V} content: sig must be a multibase signature`);
585
+ if (x.chain !== undefined && !F.chain[0](x.chain)) fail('group_message', `not a ${GROUP2_V} content: chain must be ${F.chain[1]}`);
586
+ checkBody(x.body);
587
+ return x;
588
+ }
589
+
590
+ /** iat within its window: at most SKEW ahead of now, at most OLDEST behind. */
591
+ export function checkFresh(body, now) {
592
+ if (!Number.isSafeInteger(now) || now < 0) fail('time', 'now must be Unix seconds');
593
+ if (body.iat > now + SKEW) fail('group_stale', `iat is ${body.iat - now} s ahead of now, at most ${SKEW}`);
594
+ if (body.iat + OLDEST < now) fail('group_stale', `iat is more than ${OLDEST / DAY} days old`);
595
+ return body;
596
+ }
597
+
598
+ // ---------------------------------------------------------------- signatures (offline, SPEC §3, §9)
599
+ /** sign then wrap: {body, sig[, chain]}; the body checked first. me as kdf.signAs takes it. */
600
+ export function signBody(me, body, chain) {
601
+ checkBody(body);
602
+ const out = { body, sig: signAs(me, body) };
603
+ if (chain !== undefined) out.chain = chain;
604
+ return out;
605
+ }
606
+ /** A chain {genesis, rotations} → {original, current, key}: SPEC §9 over it, no network. */
607
+ export function chainKey(chain, now) {
608
+ if (!F.chain[0](chain)) fail('group_sig', `a chain is ${F.chain[1]}`);
609
+ let r;
610
+ try { r = verify({ v: 'sigelo/0', typ: 'bundle', genesis: chain.genesis, rotations: chain.rotations, bindings: [], attestations: [], issuers: [] }, now); } catch (e) { fail('group_sig', `the chain does not verify: ${e.message}`); }
611
+ const g = [chain.genesis, ...chain.rotations.map((x) => x.next_genesis)].find((x) => didOf(x) === r.did);
612
+ return { original: r.chain[0], current: r.did, key: g.key };
613
+ }
614
+ /**
615
+ * The signature of a {body, sig} under its sender's chain: `from` is the chain's current DID and the
616
+ * current key signed the body. → {original, current}. The member check (is that original DID in the
617
+ * roster, with which role) is group2.mjs's; this is all the bytes alone can show.
618
+ */
619
+ export function verifyContent(content, chain, now) {
620
+ checkContent(content);
621
+ const c = chainKey(chain, now);
622
+ if (content.body.from !== c.current) fail('group_sig', `from ${content.body.from} is not the chain's current DID ${c.current}`);
623
+ if (!verifySig(c.key, content.body, content.sig)) fail('group_sig', `the ${content.body.typ} is not signed by ${c.current}`);
624
+ return { original: c.original, current: c.current };
625
+ }
626
+ /** A create checked whole: signature, and gid = gidOf(the creator's ORIGINAL DID, nonce). */
627
+ export function verifyCreate(content, chain, now) {
628
+ const who = verifyContent(content, chain, now);
629
+ if (content.body.typ !== 'create') fail('group_message', 'not a create');
630
+ if (gidOf(who.original, content.body.nonce) !== content.body.gid) fail('group_sig', 'the gid is not the creator\'s: SHA-256("sigelo-group/2 gid\\n" ‖ original DID ‖ "\\n" ‖ nonce)');
631
+ return who;
632
+ }
633
+ /** A join checked whole: its signature under the chain it carries. → {original, current}. */
634
+ export const verifyJoin = (content, now) => verifyContent(content, content.body.chain, now);
635
+ /** An add checked whole: the admin's signature (the caller gives its chain), the joiner's under its own, member.did its original. */
636
+ export function verifyAdd(content, adminChain, now) {
637
+ const admin = verifyContent(content, adminChain, now), joiner = verifyJoin(content.body.request, now);
638
+ if (content.body.member.did !== joiner.original) fail('group_sig', 'member.did is not the joiner\'s original DID');
639
+ return { admin, joiner };
640
+ }
641
+
642
+ // ---------------------------------------------------------------- who may sign what
643
+ /**
644
+ * The role check for a body at its seq, every member running the same rules. ctx:
645
+ * role the signer's role then (owner, admin, moderator, member), null when not a member
646
+ * self the signer's original DID
647
+ * target for member/to bodies: {did, role, kind} of the member named (null if not in the group)
648
+ * author for edit, delete, poll_end: the original DID that sent `re`; authorRole its role now
649
+ * channel, agents the group's settings then
650
+ * slot the entry's keep slot (blob: 9 is the avatar, an admin's)
651
+ * Throws group_member (not in the group) or group_role. Not for join (the door) or answer (reply topic).
652
+ */
653
+ export function authorize(b, ctx) {
654
+ const { role, self, target = null, author = null, channel = false, agents = true, slot = 0 } = ctx;
655
+ const no = (why, check = 'group_role') => fail(check, `${an(b.typ)} body ${why}`);
656
+ if (b.typ === 'create') return;
657
+ if (b.typ === 'join' || b.typ === 'answer') no('is not a log body');
658
+ if (!ROLES.includes(role)) no('from someone not in the group', 'group_member');
659
+ const at = (r) => RANK[role] >= RANK[r];
660
+ const needTarget = () => { if (!target || !ROLES.includes(target.role)) no('names someone not in the group', 'group_member'); return target; };
661
+ switch (b.typ) {
662
+ case 'leave': if (role === 'owner') no('by the owner: hand over or end the group first'); return;
663
+ case 'profile': case 'history_ask': case 'react': case 'vote': return;
664
+ case 'msg': case 'poll': if (channel && !at('admin')) no('in channel mode: only admins post'); return;
665
+ case 'edit': if (author !== self) no('of someone else\'s message'); return;
666
+ case 'delete': if (author !== self && !at('moderator')) no('of someone else\'s message needs a moderator or admin'); return;
667
+ case 'pin': if (!at('moderator')) no('needs a moderator or admin'); return;
668
+ case 'poll_end': if (author !== self && !at('admin')) no('of someone else\'s poll needs an admin'); return;
669
+ case 'blob': if (slot === KEEP_AVATAR && !at('admin')) no('in the avatar slot needs an admin'); return;
670
+ case 'kick': {
671
+ const t = needTarget();
672
+ if (t.did === self) no('of oneself: leave instead');
673
+ if (t.role === 'owner') no('names the owner, whom nobody kicks');
674
+ if (t.role === 'admin' && role !== 'owner') no('of an admin needs the owner');
675
+ if (t.role === 'moderator' && !at('admin')) no('of a moderator needs an admin');
676
+ if (!at('moderator')) no('needs a moderator or admin');
677
+ return;
678
+ }
679
+ case 'role': {
680
+ const t = needTarget();
681
+ if (t.role === 'owner') no('cannot change the owner (handover)');
682
+ if ((b.role === 'admin' || t.role === 'admin') && role !== 'owner') no('making or unmaking an admin needs the owner');
683
+ if (!at('admin')) no('needs an admin');
684
+ if (b.agent !== (t.kind === 'agent')) no(`says agent ${b.agent} of ${an(t.kind)}`);
685
+ if (b.agent) {
686
+ const by = AGENT_ROLES[b.role];
687
+ if (by === null) no(`makes an agent ${b.role}: agents may not hold it`);
688
+ if (by === 'owner' && role !== 'owner') no(`makes an agent ${b.role}: only the owner, for its own agents`);
689
+ if (!at(by)) no(`makes an agent ${b.role}: needs ${an(by)}`);
690
+ }
691
+ return;
692
+ }
693
+ case 'add': if (!at('admin')) no('needs an admin'); if (!agents && b.member.kind === 'agent') no('of an agent: agents are not allowed here'); return;
694
+ case 'kind': needTarget(); if (!at('admin')) no('needs an admin'); if (!agents && b.kind === 'agent') no('making a member an agent: agents are not allowed here'); return;
695
+ case 'handover': { const t = needTarget(); if (role !== 'owner') no('needs the owner'); if (t.role !== 'admin') no('goes to an admin'); return; }
696
+ case 'settings':
697
+ if (!at('admin')) no('needs an admin');
698
+ if (Object.keys(b.settings).some((k) => OWNER_SETTINGS.includes(k)) && role !== 'owner') no(`of ${OWNER_SETTINGS.join(' or ')} needs the owner`);
699
+ return;
700
+ case 'moved': case 'end': if (role !== 'owner') no('needs the owner'); return;
701
+ case 'unbar': case 'link': case 'unlink': case 'state': case 'epoch': case 'vault': case 'welcome': case 'history':
702
+ if (!at('admin')) no('needs an admin');
703
+ if (b.typ === 'vault') { const t = needTarget(); if (!['owner', 'admin'].includes(t.role)) no('goes to an admin'); }
704
+ return;
705
+ }
706
+ no('has no rule');
707
+ }
708
+ /** A vote against its poll: a choice past the options, or two choices in a one-answer poll, are refused. */
709
+ export function checkVote(vote, poll) {
710
+ if (vote.choices.some((c) => c >= poll.options.length)) fail('group_message', `a vote for option ${Math.max(...vote.choices)} of a poll with ${poll.options.length}`);
711
+ if (!poll.multi && vote.choices.length > 1) fail('group_message', 'two choices in a one-answer poll');
712
+ return vote;
713
+ }
714
+
715
+ // ---------------------------------------------------------------- boxes in bodies
716
+ // The plaintexts (JCS, closed tables): vault {V, L: {DID: key}, D?: [{id, seed}]}; welcome {L, chains: [{hint, n, ck}],
717
+ // keys: [{seq, key}], secrets: [{epoch, E}]}; history {secrets: [{epoch, E}]}. All keys base64url.
718
+ nested('chainRecord', { hint: 'hex8', n: 'n', ck: 'key32' }, {}, '{hint, n, ck}');
719
+ nested('rowKey', { seq: 'seq1', key: 'key32' }, {}, '{seq, key}');
720
+ nested('secret', { epoch: 'epoch', E: 'key32' }, {}, '{epoch, E}');
721
+ const listOf = (f, max) => (x) => Array.isArray(x) && x.length <= max && x.every(F[f][0]);
722
+ def('chains', listOf('chainRecord', LIST_MAX * 2), 'chain records {hint, n, ck}');
723
+ def('rowKeys', listOf('rowKey', 100000), 'row keys {seq, key}');
724
+ def('secrets', listOf('secret', 10000), 'epoch secrets {epoch, E}');
725
+ def('letterKeys', (x) => isObject(x) && Object.keys(x).length <= 100000 && Object.entries(x).every(([d, k]) => DID.test(d) && F.key32[0](k)), 'a map of original DIDs to letter keys');
726
+ // vault's optional D: the door seeds of the links open at its sealing, so an admin made after a link reads its requests
727
+ // (§4.15); the link body's own box is sealed under the V of its moment, which a later admin may never hold.
728
+ nested('doorSeed', { id: 'hex8', seed: 'key32' }, {}, '{id, seed}');
729
+ def('doorSeeds', (x) => Array.isArray(x) && x.length >= 1 && x.length <= LINKS_MAX && x.every(F.doorSeed[0]) && new Set(x.map((d) => d.id)).size === x.length, `1 to ${LINKS_MAX} door seeds {id, seed}, each id once`);
730
+ const BOX = { vault: [{ V: 'key32', L: 'letterKeys' }, { D: 'doorSeeds' }], welcome: [{ L: 'key32', chains: 'chains', keys: 'rowKeys', secrets: 'secrets' }], history: [{ secrets: 'secrets' }] };
731
+ /** Seal a vault, welcome or history box to a member's gkey under the body's epoch: → {kem, box}, base64url. */
732
+ export function sealBox(purpose, gkey, gid, epoch, pt, rng = randomBytes) {
733
+ checkBoxPlain(purpose, pt);
734
+ const r = kemSeal(gkey, gid, purpose, epoch, enc(pt), rng);
735
+ return { kem: b64u(r.kem), box: b64u(r.box) };
736
+ }
737
+ export function openBox(body, gkeySecret) {
738
+ const p = decodeJcs(kemOpen(gkeySecret, body.gid, body.typ, body.epoch, bytesOf(body.kem, XWING_CT, 'group_message', 'kem'), bytesOf(body.box, undefined, 'group_message', 'box')), `the ${body.typ} box`);
739
+ return checkBoxPlain(body.typ, p);
740
+ }
741
+ function checkBoxPlain(purpose, p) {
742
+ if (!Object.hasOwn(BOX, purpose)) fail('group_message', `no box for ${purpose}`);
743
+ const [need, may = {}] = BOX[purpose];
744
+ try { checkObject(p, need, may, purpose); } catch { fail('group_message', `a ${purpose} box holds {${[...Object.keys(need), ...Object.keys(may).map((k) => `${k}?`)].join(', ')}}`); }
745
+ return p;
746
+ }
747
+ /** The letter key a member's add body seals for admins (vault key, the member's original DID as additional data). */
748
+ export const sealForAdmins = (V, gid, did, secret, rng = randomBytes) => b64u(seal(vaultKey(V, gid), need32(secret, 'a key'), u(checkDid(did)), rng));
749
+ export const openForAdmins = (V, gid, did, box) => unseal(vaultKey(V, gid), bytesOf(box, NONCE + 32 + TAG, 'group_message', 'box'), u(checkDid(did)), 'a key sealed for admins');
750
+ /** A mid-epoch joiner's chain start in its add body (addKey, its original DID as additional data). */
751
+ export const sealChainStart = (HK, gid, did, ck0, rng = randomBytes) => b64u(seal(addKey(HK, gid), need32(ck0, 'CK0'), u(checkDid(did)), rng));
752
+ export const openChainStart = (HK, gid, did, box) => unseal(addKey(HK, gid), bytesOf(box, NONCE + 32 + TAG, 'group_message', 'ck'), u(checkDid(did)), 'a chain start');
753
+ /** A link's door seed for admins (vault key, the link id as additional data). */
754
+ export const sealDoorSeed = (V, gid, link, seed, rng = randomBytes) => b64u(seal(vaultKey(V, gid), need32(seed, 'a door seed'), hexToBytes(link), rng));
755
+ export const openDoorSeed = (V, gid, link, box) => unseal(vaultKey(V, gid), bytesOf(box, NONCE + 32 + TAG, 'group_message', 'box'), hexToBytes(link), 'a door seed');
756
+
757
+ // ---------------------------------------------------------------- the invite
758
+ export const INVITE = ['v', 'typ', 'gid', 'name', 'owner', 'home', 'door', 'door_key', 'link', 'by', 'iat', 'exp', 'approve'];
759
+ const INVITE_FIELD = { gid: 'gid', name: 'name', owner: 'did', home: 'host', door: 'door', door_key: 'gkey', link: 'hex8', by: 'did', iat: 'time', exp: 'time', approve: 'approve', moved_from: 'gid' };
760
+ export const GRP_PREFIX = 'GRP', GRP_V = 'sigelo-group/2 code', LINK_BASE = 'https://sigelo.io/join#';
761
+ /** {body, sig, genesis}: the body as INVITE says (moved_from? names a sigelo-group/1 group it replaces), signed by `by`, genesis = by's current genesis. */
762
+ export function checkInvite(inv, now) {
763
+ const no = (why, check = 'group_message') => fail(check, `not a ${GROUP2_V} invite: ${why}`);
764
+ if (!isObject(inv) || !exactKeys(inv, ['body', 'sig', 'genesis'])) no('{body, sig, genesis}');
765
+ const b = inv.body;
766
+ if (!isObject(b) || b.v !== GROUP2_V || b.typ !== 'invite') no(`v "${GROUP2_V}", typ "invite"`);
767
+ const extra = Object.keys(b).filter((k) => !INVITE.includes(k) && k !== 'moved_from'), missing = INVITE.filter((k) => !Object.hasOwn(b, k));
768
+ if (extra.length || missing.length) no(`a body is {${INVITE.join(', ')}, moved_from?}`);
769
+ for (const [k, f] of Object.entries(INVITE_FIELD)) if (Object.hasOwn(b, k) && !F[f][0](b[k])) no(`${k} must be ${F[f][1]}`, F[f][2]);
770
+ if (!(b.exp - b.iat >= LINK_MIN && b.exp - b.iat <= LINK_MAX)) no('exp is 1 hour to 366 days after iat');
771
+ if (typeof inv.sig !== 'string' || !isObject(inv.genesis)) no('sig, genesis');
772
+ let d;
773
+ try { d = didOf(inv.genesis); } catch { no('genesis is not a sigelo genesis', 'group_sig'); }
774
+ if (d !== b.by) no('genesis is not by\'s', 'group_sig');
775
+ if (!verifySig(inv.genesis.key, b, inv.sig)) no(`not signed by ${b.by}`, 'group_sig');
776
+ if (now !== undefined) {
777
+ if (b.iat > now + SKEW) no('iat is in the future', 'group_stale');
778
+ if (now >= b.exp) no('expired', 'group_stale');
779
+ }
780
+ return inv;
781
+ }
782
+ /** The long form: base64url of the invite's JCS. */
783
+ export const inviteLong = (inv) => b64u(enc(inv));
784
+ export function parseInviteLong(text, now) {
785
+ const b = unb64u(typeof text === 'string' ? text.trim() : text);
786
+ if (b === null || b.length > 8192) fail('group_message', 'not a long invite: base64url of at most 8 KiB');
787
+ return checkInvite(decodeJcs(b, 'the invite'), now);
788
+ }
789
+ const GRP_RE = /^\s*GRP[\s\-\u2010-\u2015\u2212]*/i;
790
+ /** A GRP- code: the prefix, then a short code (8, or 12 with the home's relay tag) → the 8 or 12 characters. */
791
+ export function normaliseGroupCode(text) {
792
+ if (typeof text !== 'string' || text.length > 80 || !GRP_RE.test(text)) fail('group_code', 'not a group code (like GRP-7Q4K-M2XD: GRP, then 8 characters of 0-9 and A-Z without I, L, O, U)');
793
+ try { return normaliseShort(text.replace(GRP_RE, '')); } catch (e) { fail('group_code', `not a group code: ${e.message.replace(/^short_code: /, '')}`); }
794
+ }
795
+ export const isGroupCode = (text) => { try { normaliseGroupCode(text); return true; } catch { return false; } };
796
+ export const formatGroupCode = (norm) => `${GRP_PREFIX}-${formatShort(norm)}`;
797
+ /** The key a home relay parks the long invite under: hex SHA-256("sigelo-group/2 code" ‖ the normalised code); never a one-time code's. */
798
+ export const groupCodeHash = (text) => hex(sha256(concatBytes(u(GRP_V), u(normaliseGroupCode(text)))));
799
+ export const groupLink = (norm) => LINK_BASE + formatGroupCode(norm);
800
+
801
+ // ---------------------------------------------------------------- the name card (supergroups)
802
+ export const CARD = ['v', 'typ', 'name', 'home', 'gid', 'owner', 'public', 'about', 'avatar', 'invite', 'iat'];
803
+ const CARD_FIELD = { name: 'cardName', home: 'host', gid: 'gid', owner: 'did', public: 'bool', about: 'about', avatar: 'avatar', invite: 'inviteOrNull', iat: 'time' };
804
+ def('cardName', (x) => typeof x === 'string' && /^[a-z0-9-]{3,32}$/.test(x), 'a name of 3 to 32 characters a-z, 0-9, -');
805
+ def('inviteOrNull', (x) => x === null || (unb64u(x) !== null && x.length > 0), 'null or a long invite');
806
+ export function checkCard(b) {
807
+ const no = (why, check = 'group_message') => fail(check, `not a ${GROUP2_V} card: ${why}`);
808
+ if (!isObject(b) || b.v !== GROUP2_V || b.typ !== 'card' || !exactKeys(b, CARD)) no(`{${CARD.join(', ')}}`);
809
+ for (const [k, f] of Object.entries(CARD_FIELD)) if (!F[f][0](b[k])) no(`${k} must be ${F[f][1]}`, F[f][2]);
810
+ if (b.public !== (b.invite !== null)) no('a public card has an invite, a private one null');
811
+ return b;
812
+ }