@941design/marmot-engine 0.2.0-alpha.0 → 0.2.0-alpha.1

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.
@@ -0,0 +1,535 @@
1
+ /** @module @category Core - Protocol Profile */
2
+ import { schnorr } from "@noble/curves/secp256k1.js";
3
+ import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
4
+ import { appDataDictionaryExtensionType, appDataUpdateProposalType, defaultExtensionTypes, getAppDataDictionary, makeAppDataDictionaryExtension, selfRemoveProposalType, } from "ts-mls";
5
+ import { getEventHash, unixNow } from "../utils/nostr.js";
6
+ import { ACCOUNT_IDENTITY_PROOF_EVENT_KIND, ACCOUNT_IDENTITY_PROOF_EXTENSION_TYPE, accountIdentityProofSigningDigest, decodeAccountIdentityProof, mlsSignatureScheme, } from "./account-identity-proof.js";
7
+ import { ensureMarmotCapabilities, marmotRequiredCapabilitiesExtension, } from "./capabilities.js";
8
+ import { decodeComponentsList, encodeComponentsList, } from "./components/app-components-list.js";
9
+ import { ACCOUNT_DEVICES_COMPONENT_ID, ACCOUNT_IDENTITY_PROOF_COMPONENT_ID, APP_COMPONENTS_COMPONENT_ID, GROUP_ENCRYPTED_MEDIA_V2_COMPONENT_ID, PRIVATE_USE_APP_COMPONENT_ID_START, SAFE_AAD_COMPONENT_ID, SUPPORTED_APP_COMPONENT_IDS, } from "./components/ids.js";
10
+ import { getCredentialPubkey } from "./credential.js";
11
+ import { defaultCapabilities } from "./default-capabilities.js";
12
+ import { isGreaseValue } from "./grease.js";
13
+ /** Both profiles, in the order the library introduced them. */
14
+ export const PROTOCOL_PROFILES = [
15
+ "legacy",
16
+ "current",
17
+ ];
18
+ /** Whether `value` is one of the two protocol profiles (the narrowing companion of {@link profileOf}). */
19
+ export function isProtocolProfile(value) {
20
+ return value === "legacy" || value === "current";
21
+ }
22
+ function requiredCapabilitiesListsLegacyProof(extensions) {
23
+ return extensions.some((extension) => {
24
+ if (extension.extensionType !== defaultExtensionTypes.required_capabilities)
25
+ return false;
26
+ const data = extension.extensionData;
27
+ return (data?.extensionTypes ?? []).includes(ACCOUNT_IDENTITY_PROOF_EXTENSION_TYPE);
28
+ });
29
+ }
30
+ /** The decoded GroupContext dictionary, or `"undecodable"`. */
31
+ function groupDictionary(extensions) {
32
+ try {
33
+ return getAppDataDictionary(extensions);
34
+ }
35
+ catch {
36
+ return "undecodable";
37
+ }
38
+ }
39
+ /**
40
+ * The protocol profile of a group, read from its GroupContext (spec DD-0). Pure and total: never throws.
41
+ *
42
+ * Order of checks as in MDK `protocol_profile_of_group_extensions`: `0x8009` state in the GroupContext first, then the
43
+ * `0x0001` list must decode, then the two markers must name exactly one profile.
44
+ */
45
+ export function profileOf(groupContext) {
46
+ const extensions = groupContext.extensions;
47
+ const legacyRequired = requiredCapabilitiesListsLegacyProof(extensions);
48
+ const dictionary = groupDictionary(extensions);
49
+ if (dictionary === "undecodable")
50
+ return { invalid: "app-components-undecodable" };
51
+ if (dictionary?.some((entry) => entry.componentId === ACCOUNT_IDENTITY_PROOF_COMPONENT_ID))
52
+ return { invalid: "group-context-carries-proof-component" };
53
+ let currentRequired = false;
54
+ const list = dictionary?.find((entry) => entry.componentId === APP_COMPONENTS_COMPONENT_ID);
55
+ if (list !== undefined) {
56
+ let ids;
57
+ try {
58
+ ids = decodeComponentsList(list.data);
59
+ }
60
+ catch {
61
+ return { invalid: "app-components-undecodable" };
62
+ }
63
+ currentRequired = ids.includes(ACCOUNT_IDENTITY_PROOF_COMPONENT_ID);
64
+ }
65
+ if (legacyRequired && !currentRequired)
66
+ return "legacy";
67
+ if (!legacyRequired && currentRequired)
68
+ return "current";
69
+ return { invalid: legacyRequired ? "both-profiles" : "no-profile" };
70
+ }
71
+ /**
72
+ * Whether a group requires `0x800d` (`marmot.group.account-devices.v1`, spec DD-0): it is Current and its GroupContext
73
+ * `0x0001` list contains `0x800d`. A Legacy group, or a GroupContext of no single profile, never requires it.
74
+ */
75
+ export function requires0x800d(groupContext) {
76
+ if (profileOf(groupContext) !== "current")
77
+ return false;
78
+ const dictionary = groupDictionary(groupContext.extensions);
79
+ if (dictionary === "undecodable" || dictionary === undefined)
80
+ return false;
81
+ const list = dictionary.find((entry) => entry.componentId === APP_COMPONENTS_COMPONENT_ID);
82
+ if (list === undefined)
83
+ return false;
84
+ return decodeComponentsList(list.data).includes(ACCOUNT_DEVICES_COMPONENT_ID);
85
+ }
86
+ // ---------------------------------------------------------------------------
87
+ // Profile-keyed capabilities
88
+ // ---------------------------------------------------------------------------
89
+ /**
90
+ * The private-use app components a Current-form leaf advertises in its `app_components` (`0x0001`) list: every id the
91
+ * Legacy form advertises ({@link SUPPORTED_APP_COMPONENT_IDS}) plus `0x8009` (the proof, MDK requires it to be
92
+ * advertised), `0x800d` (`account-devices-v1`, spec DD-3: listed on every Current-form KeyPackage and leaf) and
93
+ * `0x800b` (`group.encrypted-media.v2`). MDK v0.19.0 groups require `0x8001`, `0x8003`, `0x8004`, `0x8009`, `0x800b`,
94
+ * `0x800c` and `0x800d` (reference-checks.md (e)); a KeyPackage missing any of them is never selected by MDK's
95
+ * inviter. `0x800b` is advertised for that reason only: this library carries an MDK group's `0x800b` state opaquely
96
+ * (it never writes it) and does not implement the v2 media codec.
97
+ */
98
+ export const CURRENT_PROFILE_LEAF_APP_COMPONENT_IDS = [
99
+ ...new Set([
100
+ ...SUPPORTED_APP_COMPONENT_IDS,
101
+ ACCOUNT_IDENTITY_PROOF_COMPONENT_ID,
102
+ GROUP_ENCRYPTED_MEDIA_V2_COMPONENT_ID,
103
+ ACCOUNT_DEVICES_COMPONENT_ID,
104
+ ]),
105
+ ].sort((a, b) => a - b);
106
+ /**
107
+ * The leaf `Capabilities` of a KeyPackage of `profile`. Legacy: {@link ensureMarmotCapabilities} over `base` (the
108
+ * {@link defaultCapabilities} when absent), exactly as before profiles existed. Current: the same, without the
109
+ * `0xf2f1` extension (MDK `leaf_capabilities` advertises it only for Legacy) and without GREASE proposal types — MDK's
110
+ * KeyPackage metadata keeps every advertised proposal type (it drops GREASE only from extensions), and the kind 30443
111
+ * `mls_proposals` tag must match that metadata exactly, so a Current-form leaf advertises no GREASE proposal.
112
+ */
113
+ export function marmotCapabilitiesForProfile(profile, base) {
114
+ const legacy = base ? ensureMarmotCapabilities(base) : defaultCapabilities();
115
+ if (profile === "legacy")
116
+ return legacy;
117
+ return {
118
+ ...legacy,
119
+ extensions: legacy.extensions.filter((type) => type !== ACCOUNT_IDENTITY_PROOF_EXTENSION_TYPE),
120
+ proposals: legacy.proposals.filter((type) => !isGreaseValue(type)),
121
+ };
122
+ }
123
+ /**
124
+ * The `required_capabilities` GroupContext extension of a group of `profile`. Legacy: the unchanged
125
+ * {@link marmotRequiredCapabilitiesExtension} (`0x0006`, `0xf2f1`; proposals `0x0008`, `0x000a`). Current: the same
126
+ * without `0xf2f1` — the Current proof requirement is `0x8009` in the GroupContext `0x0001` list instead (MDK
127
+ * `required_capabilities_extension`).
128
+ */
129
+ export function marmotRequiredCapabilitiesExtensionForProfile(profile) {
130
+ const legacy = marmotRequiredCapabilitiesExtension();
131
+ if (profile === "legacy")
132
+ return legacy;
133
+ return {
134
+ extensionType: legacy.extensionType,
135
+ extensionData: {
136
+ extensionTypes: [appDataDictionaryExtensionType],
137
+ proposalTypes: [appDataUpdateProposalType, selfRemoveProposalType].sort((a, b) => a - b),
138
+ credentialTypes: [],
139
+ },
140
+ };
141
+ }
142
+ // ---------------------------------------------------------------------------
143
+ // Current proof codec (component 0x8009, 104 bytes)
144
+ // ---------------------------------------------------------------------------
145
+ /** Byte length of the Current proof component: account identity (32) || created_at (u64 BE, 8) || signature (64). */
146
+ export const CURRENT_ACCOUNT_IDENTITY_PROOF_LENGTH = 104;
147
+ /** The largest NIP-01 timestamp a Current proof may carry (`2^53 - 1`); `0` is never valid. */
148
+ export const MAX_CURRENT_PROOF_TIMESTAMP = Number.MAX_SAFE_INTEGER;
149
+ const ACCOUNT_IDENTITY_PROOF_DOMAIN = "marmot.account-identity-proof.v2";
150
+ const CURRENT_PROOF_CONTENT = "Authorize this MLS leaf key for my Marmot account";
151
+ const ACCOUNT_IDENTITY_LEN = 32;
152
+ const SIGNATURE_LEN = 64;
153
+ /** A rejected account identity proof, with its typed {@link AccountIdentityProofFailure} reason. */
154
+ export class AccountIdentityProofError extends Error {
155
+ reason;
156
+ constructor(reason, message) {
157
+ super(message);
158
+ this.name = "AccountIdentityProofError";
159
+ this.reason = reason;
160
+ }
161
+ }
162
+ function hex4(value) {
163
+ return `0x${value.toString(16).padStart(4, "0")}`;
164
+ }
165
+ function validTimestamp(createdAt) {
166
+ return (Number.isSafeInteger(createdAt) &&
167
+ createdAt >= 1 &&
168
+ createdAt <= MAX_CURRENT_PROOF_TIMESTAMP);
169
+ }
170
+ /**
171
+ * The canonical, unpublished kind-450 event the account key signs for a Current proof (MDK `proof_event`, Current
172
+ * arm): `created_at` is the proof timestamp, `content` is the fixed authorization sentence, and the tags name the
173
+ * component, the ciphersuite and scheme as lowercase `0x%04x`, and the leaf key. Throws on an invalid timestamp.
174
+ */
175
+ export function buildCurrentAccountIdentityProofEvent(request) {
176
+ if (!validTimestamp(request.createdAt))
177
+ throw new AccountIdentityProofError("proof-invalid-timestamp", `current proof timestamp must be in 1..=${MAX_CURRENT_PROOF_TIMESTAMP}`);
178
+ return {
179
+ pubkey: bytesToHex(request.accountIdentity),
180
+ created_at: request.createdAt,
181
+ kind: ACCOUNT_IDENTITY_PROOF_EVENT_KIND,
182
+ content: CURRENT_PROOF_CONTENT,
183
+ tags: [
184
+ ["d", ACCOUNT_IDENTITY_PROOF_DOMAIN],
185
+ ["component", hex4(ACCOUNT_IDENTITY_PROOF_COMPONENT_ID)],
186
+ ["ciphersuite", hex4(request.ciphersuite)],
187
+ ["signature_scheme", hex4(request.signatureScheme)],
188
+ ["mls_signature_key", bytesToHex(request.mlsSignaturePublicKey)],
189
+ ],
190
+ };
191
+ }
192
+ /** The 32-byte digest a Current proof signs: the NIP-01 id of {@link buildCurrentAccountIdentityProofEvent}. */
193
+ export function currentAccountIdentityProofSigningDigest(request) {
194
+ return hexToBytes(getEventHash(buildCurrentAccountIdentityProofEvent(request)));
195
+ }
196
+ /** Encodes a Current proof to its 104-byte `0x8009` component data. Throws on a bad length or timestamp. */
197
+ export function encodeCurrentAccountIdentityProof(proof) {
198
+ if (proof.accountIdentity.length !== ACCOUNT_IDENTITY_LEN)
199
+ throw new AccountIdentityProofError("proof-wrong-length", "account identity must be exactly 32 bytes");
200
+ if (proof.signature.length !== SIGNATURE_LEN)
201
+ throw new AccountIdentityProofError("proof-wrong-length", "proof signature must be exactly 64 bytes");
202
+ if (!validTimestamp(proof.createdAt))
203
+ throw new AccountIdentityProofError("proof-invalid-timestamp", `current proof timestamp must be in 1..=${MAX_CURRENT_PROOF_TIMESTAMP}`);
204
+ const out = new Uint8Array(CURRENT_ACCOUNT_IDENTITY_PROOF_LENGTH);
205
+ out.set(proof.accountIdentity, 0);
206
+ new DataView(out.buffer).setBigUint64(ACCOUNT_IDENTITY_LEN, BigInt(proof.createdAt), false);
207
+ out.set(proof.signature, ACCOUNT_IDENTITY_LEN + 8);
208
+ return out;
209
+ }
210
+ /**
211
+ * Decodes 104-byte `0x8009` component data. Throws {@link AccountIdentityProofError} `proof-wrong-length` on any other
212
+ * length and `proof-invalid-timestamp` on a timestamp outside `1..2^53-1` (MDK `validate_current_proof_for_key` order).
213
+ */
214
+ export function decodeCurrentAccountIdentityProof(data) {
215
+ if (data.length !== CURRENT_ACCOUNT_IDENTITY_PROOF_LENGTH)
216
+ throw new AccountIdentityProofError("proof-wrong-length", `current proof component must be exactly ${CURRENT_ACCOUNT_IDENTITY_PROOF_LENGTH} bytes`);
217
+ const raw = new DataView(data.buffer, data.byteOffset, data.byteLength);
218
+ const createdAt = raw.getBigUint64(ACCOUNT_IDENTITY_LEN, false);
219
+ if (createdAt < 1n || createdAt > BigInt(MAX_CURRENT_PROOF_TIMESTAMP))
220
+ throw new AccountIdentityProofError("proof-invalid-timestamp", `current proof timestamp must be in 1..=${MAX_CURRENT_PROOF_TIMESTAMP}`);
221
+ return {
222
+ accountIdentity: data.slice(0, ACCOUNT_IDENTITY_LEN),
223
+ createdAt: Number(createdAt),
224
+ signature: data.slice(ACCOUNT_IDENTITY_LEN + 8),
225
+ };
226
+ }
227
+ /**
228
+ * Verifies a Current proof component for an account and leaf key (MDK `validate_current_proof_for_key`): exact length,
229
+ * timestamp range, the account it names equals `accountIdentity`, and the BIP-340 signature verifies over the event
230
+ * built for `mlsSignaturePublicKey` and `ciphersuite`. Age never invalidates a proof. Throws
231
+ * {@link AccountIdentityProofError}.
232
+ */
233
+ export function verifyCurrentAccountIdentityProofForKey(data, accountIdentity, mlsSignaturePublicKey, ciphersuite) {
234
+ const proof = decodeCurrentAccountIdentityProof(data);
235
+ if (!bytesEqual(proof.accountIdentity, accountIdentity))
236
+ throw new AccountIdentityProofError("proof-account-mismatch", "proof account identity does not match credential identity");
237
+ const digest = currentAccountIdentityProofSigningDigest({
238
+ accountIdentity: proof.accountIdentity,
239
+ mlsSignaturePublicKey,
240
+ ciphersuite,
241
+ signatureScheme: mlsSignatureScheme(ciphersuite),
242
+ createdAt: proof.createdAt,
243
+ });
244
+ let verified = false;
245
+ try {
246
+ verified = schnorr.verify(proof.signature, digest, accountIdentity);
247
+ }
248
+ catch {
249
+ verified = false;
250
+ }
251
+ if (!verified)
252
+ throw new AccountIdentityProofError("proof-signature-invalid", "proof signature does not verify for credential identity");
253
+ }
254
+ /** A {@link CurrentAccountIdentityProofSigner} over a raw 32-byte Nostr secret key. */
255
+ export function currentProofSignerFromSecretKey(secretKey) {
256
+ return (request) => schnorr.sign(currentAccountIdentityProofSigningDigest(request), secretKey);
257
+ }
258
+ function signatureFromSignedCurrentEvent(request, event) {
259
+ if (event.pubkey.toLowerCase() !== bytesToHex(request.accountIdentity))
260
+ throw new Error("proof event signer does not match account identity");
261
+ const expectedId = getEventHash(buildCurrentAccountIdentityProofEvent(request));
262
+ if (event.id.toLowerCase() !== expectedId)
263
+ throw new Error("signed proof event does not match proof request");
264
+ const signature = hexToBytes(event.sig);
265
+ if (!schnorr.verify(signature, hexToBytes(expectedId), request.accountIdentity))
266
+ throw new Error("invalid signed proof event: signature does not verify");
267
+ return signature;
268
+ }
269
+ /**
270
+ * Signs a Current proof for a leaf key and returns its 104-byte `0x8009` component data (MDK
271
+ * `account_identity_proof_component`). `createdAt` defaults to now (unix seconds).
272
+ */
273
+ export async function signCurrentAccountIdentityProof(params) {
274
+ const request = {
275
+ accountIdentity: params.accountIdentity,
276
+ mlsSignaturePublicKey: params.mlsSignaturePublicKey,
277
+ ciphersuite: params.ciphersuite,
278
+ signatureScheme: mlsSignatureScheme(params.ciphersuite),
279
+ createdAt: params.createdAt ?? unixNow(),
280
+ };
281
+ // Validates the timestamp before any signer is asked.
282
+ buildCurrentAccountIdentityProofEvent(request);
283
+ const signature = typeof params.signer === "function"
284
+ ? await params.signer(request)
285
+ : signatureFromSignedCurrentEvent(request, await params.signer.signEvent(buildCurrentAccountIdentityProofEvent(request)));
286
+ return encodeCurrentAccountIdentityProof({
287
+ accountIdentity: request.accountIdentity,
288
+ createdAt: request.createdAt,
289
+ signature,
290
+ });
291
+ }
292
+ function leafDictionary(leaf) {
293
+ return getAppDataDictionary(leaf.extensions);
294
+ }
295
+ function hasLegacyProofExtension(leaf) {
296
+ return leaf.extensions.some((e) => e.extensionType === ACCOUNT_IDENTITY_PROOF_EXTENSION_TYPE);
297
+ }
298
+ /**
299
+ * The proof form a leaf carries, read like MDK: `0xf2f1` LeafNode extension only is Legacy, an `app_data_dictionary`
300
+ * `0x8009` entry only is Current. A dictionary that does not decode counts as no Current entry here; the verifier
301
+ * reports it as `leaf-dictionary-undecodable`.
302
+ */
303
+ export function leafProofForm(leaf) {
304
+ const legacy = hasLegacyProofExtension(leaf);
305
+ let current = false;
306
+ try {
307
+ current =
308
+ leafDictionary(leaf)?.some((entry) => entry.componentId === ACCOUNT_IDENTITY_PROOF_COMPONENT_ID) ?? false;
309
+ }
310
+ catch {
311
+ current = false;
312
+ }
313
+ if (legacy && current)
314
+ return "both";
315
+ if (legacy)
316
+ return "legacy";
317
+ if (current)
318
+ return "current";
319
+ return "neither";
320
+ }
321
+ /**
322
+ * The `app_components` (`0x0001`) ids a leaf advertises in its own `app_data_dictionary`, or `undefined` when it
323
+ * advertises none. Throws {@link AccountIdentityProofError} `leaf-dictionary-undecodable` when the dictionary or the
324
+ * list does not decode.
325
+ */
326
+ export function leafAppComponents(leaf) {
327
+ let dictionary;
328
+ try {
329
+ dictionary = leafDictionary(leaf);
330
+ }
331
+ catch {
332
+ throw new AccountIdentityProofError("leaf-dictionary-undecodable", "leaf app_data_dictionary does not decode");
333
+ }
334
+ const list = dictionary?.find((entry) => entry.componentId === APP_COMPONENTS_COMPONENT_ID);
335
+ if (list === undefined)
336
+ return undefined;
337
+ try {
338
+ return decodeComponentsList(list.data);
339
+ }
340
+ catch {
341
+ throw new AccountIdentityProofError("leaf-dictionary-undecodable", "leaf app_components list does not decode");
342
+ }
343
+ }
344
+ function credentialIdentity(leaf) {
345
+ let pubkey;
346
+ try {
347
+ pubkey = getCredentialPubkey(leaf.credential);
348
+ }
349
+ catch (err) {
350
+ throw new AccountIdentityProofError("invalid-credential", `credential is not a Marmot account identity: ${err instanceof Error ? err.message : String(err)}`);
351
+ }
352
+ return hexToBytes(pubkey);
353
+ }
354
+ function verifyLegacyForm(leaf, accountIdentity, ciphersuite) {
355
+ const extension = leaf.extensions.find((e) => e.extensionType === ACCOUNT_IDENTITY_PROOF_EXTENSION_TYPE);
356
+ let proof;
357
+ try {
358
+ proof = decodeAccountIdentityProof(extension.extensionData);
359
+ }
360
+ catch (err) {
361
+ throw new AccountIdentityProofError("proof-malformed", `legacy proof extension does not decode: ${err instanceof Error ? err.message : String(err)}`);
362
+ }
363
+ if (!bytesEqual(proof.request.accountIdentity, accountIdentity))
364
+ throw new AccountIdentityProofError("proof-account-mismatch", "proof account identity does not match credential identity");
365
+ if (!bytesEqual(proof.request.mlsSignaturePublicKey, leaf.signaturePublicKey))
366
+ throw new AccountIdentityProofError("proof-signature-key-mismatch", "proof MLS signature key does not match leaf signature key");
367
+ if (proof.request.ciphersuite !== ciphersuite)
368
+ throw new AccountIdentityProofError("proof-ciphersuite-mismatch", "proof ciphersuite does not match expected ciphersuite");
369
+ if (proof.request.signatureScheme !== mlsSignatureScheme(ciphersuite))
370
+ throw new AccountIdentityProofError("proof-signature-scheme-mismatch", "proof signature scheme does not match ciphersuite");
371
+ let verified = false;
372
+ try {
373
+ verified = schnorr.verify(proof.signature, accountIdentityProofSigningDigest(proof.request), accountIdentity);
374
+ }
375
+ catch {
376
+ verified = false;
377
+ }
378
+ if (!verified)
379
+ throw new AccountIdentityProofError("proof-signature-invalid", "proof signature does not verify for credential identity");
380
+ }
381
+ function verifyCurrentForm(leaf, accountIdentity, ciphersuite) {
382
+ const advertised = leafAppComponents(leaf) ?? [];
383
+ if (!advertised.includes(ACCOUNT_IDENTITY_PROOF_COMPONENT_ID))
384
+ throw new AccountIdentityProofError("proof-not-advertised", "current proof component 0x8009 is not advertised in leaf app_components");
385
+ const data = leafDictionary(leaf).find((entry) => entry.componentId === ACCOUNT_IDENTITY_PROOF_COMPONENT_ID).data;
386
+ verifyCurrentAccountIdentityProofForKey(data, accountIdentity, leaf.signaturePublicKey, ciphersuite);
387
+ }
388
+ /**
389
+ * Verifies a leaf's account identity proof in whichever single form it carries and returns that form's profile (MDK
390
+ * `validate_leaf_account_identity_proof`). With `expected`, a valid proof in the other form is rejected `wrong-form`
391
+ * (MDK `ensure_profile`). Throws {@link AccountIdentityProofError}:
392
+ * `both-forms` / `no-proof` first, then the form's own checks. The Legacy form's checks and their order are exactly
393
+ * those of `verifyLeafAccountIdentityProof` (`account-identity-proof.ts`).
394
+ */
395
+ export function verifyLeafAccountIdentityProofForProfile(leaf, ciphersuite, expected) {
396
+ const accountIdentity = credentialIdentity(leaf);
397
+ const form = leafProofForm(leaf);
398
+ if (form === "both")
399
+ throw new AccountIdentityProofError("both-forms", "LeafNode mixes legacy proof extension 0xf2f1 with current proof component 0x8009");
400
+ if (form === "neither") {
401
+ // A dictionary that does not decode is its own reason, not a missing proof.
402
+ leafAppComponents(leaf);
403
+ throw new AccountIdentityProofError("no-proof", "missing account identity proof: LeafNode carries neither legacy proof extension 0xf2f1 nor current proof component 0x8009");
404
+ }
405
+ if (form === "legacy")
406
+ verifyLegacyForm(leaf, accountIdentity, ciphersuite);
407
+ else
408
+ verifyCurrentForm(leaf, accountIdentity, ciphersuite);
409
+ if (expected !== undefined && form !== expected)
410
+ throw new AccountIdentityProofError("wrong-form", `leaf uses the ${form} proof form in a ${expected} group`);
411
+ return form;
412
+ }
413
+ /** {@link verifyLeafAccountIdentityProofForProfile} as a result instead of a throw. */
414
+ export function checkLeafAccountIdentityProof(leaf, ciphersuite, expected) {
415
+ try {
416
+ return {
417
+ valid: true,
418
+ profile: verifyLeafAccountIdentityProofForProfile(leaf, ciphersuite, expected),
419
+ };
420
+ }
421
+ catch (err) {
422
+ if (err instanceof AccountIdentityProofError)
423
+ return { valid: false, reason: err.reason, message: err.message };
424
+ return {
425
+ valid: false,
426
+ reason: "proof-malformed",
427
+ message: err instanceof Error ? err.message : String(err),
428
+ };
429
+ }
430
+ }
431
+ // ---------------------------------------------------------------------------
432
+ // Leaf extension builders
433
+ // ---------------------------------------------------------------------------
434
+ function leafDictionaryEntries(proofComponent, supportedIds) {
435
+ const ids = [
436
+ ...new Set([...supportedIds, ACCOUNT_IDENTITY_PROOF_COMPONENT_ID]),
437
+ ].filter((id) => id >= PRIVATE_USE_APP_COMPONENT_ID_START);
438
+ return [
439
+ {
440
+ componentId: APP_COMPONENTS_COMPONENT_ID,
441
+ data: encodeComponentsList([APP_COMPONENTS_COMPONENT_ID, ...ids]),
442
+ },
443
+ { componentId: SAFE_AAD_COMPONENT_ID, data: encodeComponentsList([]) },
444
+ { componentId: ACCOUNT_IDENTITY_PROOF_COMPONENT_ID, data: proofComponent },
445
+ ];
446
+ }
447
+ /**
448
+ * The `app_data_dictionary` LeafNode extension of a Current-form leaf: the `app_components` (`0x0001`) list
449
+ * (`0x0001` itself plus `supportedIds`, which always gains `0x8009`), the SafeAAD advertisement (`0x0002`, empty
450
+ * list, as the Legacy leaf) and the 104-byte proof under `0x8009` — MDK's Current leaf shape.
451
+ */
452
+ export function makeCurrentLeafAppDataExtension(proofComponent, supportedIds = CURRENT_PROFILE_LEAF_APP_COMPONENT_IDS) {
453
+ return makeAppDataDictionaryExtension(leafDictionaryEntries(proofComponent, supportedIds));
454
+ }
455
+ /**
456
+ * `extensions` (a leaf's) with its proof replaced by `material`, every other extension unchanged and in place:
457
+ * - Legacy: the `0xf2f1` extension is replaced (appended when absent) — the rekey behaviour before profiles existed.
458
+ * - Current: the `0x8009` entry of the leaf `app_data_dictionary` is replaced (added when absent, with `0x8009` added
459
+ * to its `app_components`; a leaf with no dictionary gains the Current leaf dictionary), every other entry kept.
460
+ * Throws when the leaf dictionary does not decode.
461
+ */
462
+ export function leafExtensionsWithProof(extensions, material) {
463
+ if (material.profile === "legacy") {
464
+ const out = [];
465
+ let replaced = false;
466
+ for (const extension of extensions) {
467
+ if (extension.extensionType === ACCOUNT_IDENTITY_PROOF_EXTENSION_TYPE) {
468
+ if (!replaced)
469
+ out.push(material.extension);
470
+ replaced = true;
471
+ }
472
+ else
473
+ out.push(extension);
474
+ }
475
+ if (!replaced)
476
+ out.push(material.extension);
477
+ return out;
478
+ }
479
+ const dictionaryAt = extensions.findIndex((e) => e.extensionType === appDataDictionaryExtensionType);
480
+ if (dictionaryAt < 0)
481
+ return [...extensions, makeCurrentLeafAppDataExtension(material.component)];
482
+ const entries = getAppDataDictionary([
483
+ extensions[dictionaryAt],
484
+ ]);
485
+ const next = [];
486
+ for (const entry of entries) {
487
+ if (entry.componentId === ACCOUNT_IDENTITY_PROOF_COMPONENT_ID)
488
+ continue;
489
+ if (entry.componentId === APP_COMPONENTS_COMPONENT_ID) {
490
+ const ids = decodeComponentsList(entry.data);
491
+ next.push({
492
+ componentId: APP_COMPONENTS_COMPONENT_ID,
493
+ data: encodeComponentsList([...ids, ACCOUNT_IDENTITY_PROOF_COMPONENT_ID]),
494
+ });
495
+ continue;
496
+ }
497
+ next.push(entry);
498
+ }
499
+ if (!next.some((e) => e.componentId === APP_COMPONENTS_COMPONENT_ID))
500
+ next.push({
501
+ componentId: APP_COMPONENTS_COMPONENT_ID,
502
+ data: encodeComponentsList([
503
+ APP_COMPONENTS_COMPONENT_ID,
504
+ ACCOUNT_IDENTITY_PROOF_COMPONENT_ID,
505
+ ]),
506
+ });
507
+ next.push({
508
+ componentId: ACCOUNT_IDENTITY_PROOF_COMPONENT_ID,
509
+ data: material.component,
510
+ });
511
+ next.sort((a, b) => a.componentId - b.componentId);
512
+ const out = [...extensions];
513
+ out[dictionaryAt] = makeAppDataDictionaryExtension(next);
514
+ return out;
515
+ }
516
+ /**
517
+ * The 104-byte Current proof a leaf carries, or `undefined` when it carries none (no dictionary entry, or a dictionary
518
+ * that does not decode).
519
+ */
520
+ export function currentProofComponentOf(leaf) {
521
+ try {
522
+ return leafDictionary(leaf)?.find((entry) => entry.componentId === ACCOUNT_IDENTITY_PROOF_COMPONENT_ID)?.data;
523
+ }
524
+ catch {
525
+ return undefined;
526
+ }
527
+ }
528
+ function bytesEqual(a, b) {
529
+ if (a.length !== b.length)
530
+ return false;
531
+ for (let i = 0; i < a.length; i++)
532
+ if (a[i] !== b[i])
533
+ return false;
534
+ return true;
535
+ }
@@ -9,6 +9,23 @@ export declare function createAdminCommitPolicyCallback(args: {
9
9
  adminPubkeys: string[];
10
10
  ciphersuiteId: number;
11
11
  onUnverifiableCommit?: "reject" | "retry";
12
+ /**
13
+ * Seam (admin-policy group context): the GroupContext of the state the
14
+ * judged message is processed against — for a commit, its parent epoch.
15
+ * The engine always passes it; this vendored rule ignores it. It exists for
16
+ * `adminPolicyCallback` overrides whose decision depends on the group
17
+ * context of the commit's own epoch (a client gating same-account commits
18
+ * on a required app component), which `ratchetTree` alone cannot answer.
19
+ */
20
+ groupContext?: ClientState["groupContext"];
21
+ /**
22
+ * Seam (admin-policy group context): the proposals staged in that same
23
+ * state. ts-mls hands a commit's by-reference proposals to the callback as
24
+ * these staged entries and its by-value ones with the committer as sender,
25
+ * so an override can tell the two apart (MDK counts a same-account change
26
+ * only when it is carried by value). The vendored rule ignores it.
27
+ */
28
+ unappliedProposals?: ClientState["unappliedProposals"];
12
29
  }): IncomingMessageCallback;
13
30
  /**
14
31
  * A pure side-channel decorator around an `IncomingMessageCallback`, used to
@@ -2041,8 +2041,15 @@ export class MarmotGroupEngine {
2041
2041
  if (this.#convergencePass) {
2042
2042
  const cutoffMs = Math.min(this.#convergencePass.deadlineMs, this.#convergencePass.lastRelevantInputMs +
2043
2043
  this.#settlementQuiescenceMs);
2044
- if (this.#now() < cutoffMs)
2044
+ if (this.#now() < cutoffMs) {
2045
+ // Seam (settle re-arm): a drive before the cutoff decides nothing, so
2046
+ // it must leave a settle check armed for the remaining delay — the
2047
+ // timer that woke it may have fired early, or been replaced by a
2048
+ // retained-input continuation. A live timer is kept as it is.
2049
+ if (this.#settleTimer === undefined)
2050
+ this.#scheduleSettleCheck();
2045
2051
  return leftovers;
2052
+ }
2046
2053
  this.#closeConvergencePass();
2047
2054
  }
2048
2055
  // Seam (`equivocationCredit`): the settlement's equivocation report leads
@@ -2509,6 +2516,13 @@ export class MarmotGroupEngine {
2509
2516
  * since the last convergence-relevant input elapses (B5). Cancels any pending
2510
2517
  * check first, so a fresh input always restarts the window. A no-op when no
2511
2518
  * settle callback is wired (the engine has nothing to notify).
2519
+ *
2520
+ * Seam (settle re-arm): a timer that fires before `cutoffAt` on the engine
2521
+ * clock (an injected or coarse clock, a scheduler that rounds) re-arms once
2522
+ * for the remaining `cutoffAt - now` and does not wake the owner — a wake
2523
+ * before the cutoff would find the pass still open and decide nothing, and
2524
+ * no timer would be left to retry it. The single handle in `#settleTimer`
2525
+ * keeps at most one live timer per engine.
2512
2526
  */
2513
2527
  #scheduleSettleCheck() {
2514
2528
  if (!this.#onSettleCheck)
@@ -2527,7 +2541,11 @@ export class MarmotGroupEngine {
2527
2541
  const delay = Math.max(0, cutoffAt - nowMs);
2528
2542
  this.#settleTimer = this.#scheduler.setTimer(delay, () => {
2529
2543
  this.#settleTimer = undefined;
2530
- if (this.#convergencePass && this.#now() >= cutoffAt)
2544
+ if (this.#now() < cutoffAt) {
2545
+ this.#scheduleSettleCheck();
2546
+ return;
2547
+ }
2548
+ if (this.#convergencePass)
2531
2549
  this.#closeConvergencePass();
2532
2550
  // Fire-and-forget; the owner's drain handles and logs its own errors.
2533
2551
  void this.#onSettleCheck?.();
@@ -4982,6 +5000,10 @@ export class MarmotGroupEngine {
4982
5000
  adminPubkeys: groupData.adminPubkeys,
4983
5001
  ciphersuiteId: this.ciphersuite.id,
4984
5002
  onUnverifiableCommit: "retry",
5003
+ // Seam (admin-policy group context): the same state's GroupContext, so
5004
+ // an override decides against the epoch the message is processed in.
5005
+ groupContext: state.groupContext,
5006
+ unappliedProposals: state.unappliedProposals,
4985
5007
  });
4986
5008
  }
4987
5009
  }
package/dist/version.d.ts CHANGED
@@ -78,7 +78,7 @@
78
78
  * a stale stamp.
79
79
  */
80
80
  /** `@941design/marmot-engine` package version. */
81
- export declare const ENGINE_PACKAGE_VERSION = "0.1.0";
81
+ export declare const ENGINE_PACKAGE_VERSION = "0.2.0-alpha.1";
82
82
  /**
83
83
  * First 16 hex chars of SHA-256 over `marmot-ts@<pin SHA>\n` followed by,
84
84
  * for each non-test `patches/*.diff` (a patch excluded only when every one
@@ -91,13 +91,13 @@ export declare const ENGINE_PACKAGE_VERSION = "0.1.0";
91
91
  * listed as locally authored moves neither digest. `scripts/vendor/verify.sh`'s
92
92
  * full re-derivation is the authoritative guard for that.
93
93
  */
94
- export declare const PATCHSET_DIGEST = "bd07cca1c2873857";
94
+ export declare const PATCHSET_DIGEST = "e5ef81e07ff92b85";
95
95
  /**
96
96
  * First 16 hex chars of SHA-256 over `local-source\n` followed by, for each
97
97
  * non-test, non-`src/version.ts` path in VENDOR.md's "Locally authored (not
98
98
  * vendored)" list, in code-unit order, `<path>\n<byte length>\n<bytes>`.
99
99
  */
100
- export declare const LOCAL_SOURCE_DIGEST = "dda4692d9eb4c034";
100
+ export declare const LOCAL_SOURCE_DIGEST = "ed610401e629ac7c";
101
101
  /**
102
102
  * The engine's stored-state format. Bump it for any change that could make a
103
103
  * stored artifact read differently (see the module doc); record each digest
@@ -107,6 +107,6 @@ export declare const ENGINE_STATE_FORMAT = 1;
107
107
  /** The envelope's engine stamp (compared on every read): the state format. */
108
108
  export declare const ENGINE_VERSION = "state.1";
109
109
  /** The engine build's full code identity (diagnostics): package version plus the vendored patch set and the locally-authored source. */
110
- export declare const ENGINE_BUILD = "0.1.0+patches.bd07cca1c2873857.local.dda4692d9eb4c034";
110
+ export declare const ENGINE_BUILD = "0.2.0-alpha.1+patches.e5ef81e07ff92b85.local.ed610401e629ac7c";
111
111
  /** Commit SHA of the `941design/ts-mls` pin recorded in VENDOR.md (consumed via the `@941design/ts-mls` registry alias). */
112
112
  export declare const TS_MLS_PIN = "26afb1d69fd4c5a613b8319610a69e4f4239e5b5";
package/dist/version.js CHANGED
@@ -78,7 +78,7 @@
78
78
  * a stale stamp.
79
79
  */
80
80
  /** `@941design/marmot-engine` package version. */
81
- export const ENGINE_PACKAGE_VERSION = "0.1.0";
81
+ export const ENGINE_PACKAGE_VERSION = "0.2.0-alpha.1";
82
82
  /**
83
83
  * First 16 hex chars of SHA-256 over `marmot-ts@<pin SHA>\n` followed by,
84
84
  * for each non-test `patches/*.diff` (a patch excluded only when every one
@@ -91,13 +91,13 @@ export const ENGINE_PACKAGE_VERSION = "0.1.0";
91
91
  * listed as locally authored moves neither digest. `scripts/vendor/verify.sh`'s
92
92
  * full re-derivation is the authoritative guard for that.
93
93
  */
94
- export const PATCHSET_DIGEST = "bd07cca1c2873857";
94
+ export const PATCHSET_DIGEST = "e5ef81e07ff92b85";
95
95
  /**
96
96
  * First 16 hex chars of SHA-256 over `local-source\n` followed by, for each
97
97
  * non-test, non-`src/version.ts` path in VENDOR.md's "Locally authored (not
98
98
  * vendored)" list, in code-unit order, `<path>\n<byte length>\n<bytes>`.
99
99
  */
100
- export const LOCAL_SOURCE_DIGEST = "dda4692d9eb4c034";
100
+ export const LOCAL_SOURCE_DIGEST = "ed610401e629ac7c";
101
101
  /**
102
102
  * The engine's stored-state format. Bump it for any change that could make a
103
103
  * stored artifact read differently (see the module doc); record each digest