@941design/marmot-engine 0.0.0-stage → 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.
Files changed (198) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/LICENSE +53 -0
  3. package/README.md +33 -2
  4. package/dist/audit/emitter.d.ts +17 -0
  5. package/dist/audit/emitter.js +30 -0
  6. package/dist/audit/helpers.d.ts +16 -0
  7. package/dist/audit/helpers.js +103 -0
  8. package/dist/audit/index.d.ts +6 -0
  9. package/dist/audit/index.js +6 -0
  10. package/dist/audit/recorder.d.ts +13 -0
  11. package/dist/audit/recorder.js +24 -0
  12. package/dist/audit/sink.d.ts +16 -0
  13. package/dist/audit/sink.js +27 -0
  14. package/dist/audit/types-internal.d.ts +7 -0
  15. package/dist/audit/types-internal.js +1 -0
  16. package/dist/audit/types.d.ts +289 -0
  17. package/dist/audit/types.js +2 -0
  18. package/dist/core/account-identity-proof.d.ts +165 -0
  19. package/dist/core/account-identity-proof.js +277 -0
  20. package/dist/core/application-rumor.d.ts +45 -0
  21. package/dist/core/application-rumor.js +120 -0
  22. package/dist/core/auth-service.d.ts +2 -0
  23. package/dist/core/auth-service.js +52 -0
  24. package/dist/core/binary.d.ts +142 -0
  25. package/dist/core/binary.js +363 -0
  26. package/dist/core/capabilities.d.ts +51 -0
  27. package/dist/core/capabilities.js +102 -0
  28. package/dist/core/client-state.d.ts +119 -0
  29. package/dist/core/client-state.js +226 -0
  30. package/dist/core/commit-authorization.d.ts +26 -0
  31. package/dist/core/commit-authorization.js +26 -0
  32. package/dist/core/components/admin-policy.d.ts +4 -0
  33. package/dist/core/components/admin-policy.js +69 -0
  34. package/dist/core/components/agent-text-stream.d.ts +51 -0
  35. package/dist/core/components/agent-text-stream.js +112 -0
  36. package/dist/core/components/app-components-list.d.ts +17 -0
  37. package/dist/core/components/app-components-list.js +35 -0
  38. package/dist/core/components/avatar-url.d.ts +12 -0
  39. package/dist/core/components/avatar-url.js +85 -0
  40. package/dist/core/components/bytes.d.ts +5 -0
  41. package/dist/core/components/bytes.js +18 -0
  42. package/dist/core/components/dictionary.d.ts +80 -0
  43. package/dist/core/components/dictionary.js +175 -0
  44. package/dist/core/components/disband-validation.d.ts +21 -0
  45. package/dist/core/components/disband-validation.js +173 -0
  46. package/dist/core/components/encrypted-media.d.ts +44 -0
  47. package/dist/core/components/encrypted-media.js +210 -0
  48. package/dist/core/components/group-lifecycle.d.ts +10 -0
  49. package/dist/core/components/group-lifecycle.js +32 -0
  50. package/dist/core/components/group-profile.d.ts +24 -0
  51. package/dist/core/components/group-profile.js +35 -0
  52. package/dist/core/components/host-safety.d.ts +9 -0
  53. package/dist/core/components/host-safety.js +148 -0
  54. package/dist/core/components/ids.d.ts +93 -0
  55. package/dist/core/components/ids.js +92 -0
  56. package/dist/core/components/index.d.ts +14 -0
  57. package/dist/core/components/index.js +14 -0
  58. package/dist/core/components/integrity.d.ts +141 -0
  59. package/dist/core/components/integrity.js +293 -0
  60. package/dist/core/components/message-retention.d.ts +17 -0
  61. package/dist/core/components/message-retention.js +26 -0
  62. package/dist/core/components/nostr-routing.d.ts +8 -0
  63. package/dist/core/components/nostr-routing.js +92 -0
  64. package/dist/core/components/url.d.ts +26 -0
  65. package/dist/core/components/url.js +44 -0
  66. package/dist/core/convergence-status.d.ts +84 -0
  67. package/dist/core/convergence-status.js +82 -0
  68. package/dist/core/convergence.d.ts +567 -0
  69. package/dist/core/convergence.js +1150 -0
  70. package/dist/core/credential.d.ts +16 -0
  71. package/dist/core/credential.js +64 -0
  72. package/dist/core/default-capabilities.d.ts +9 -0
  73. package/dist/core/default-capabilities.js +34 -0
  74. package/dist/core/extensions.d.ts +9 -0
  75. package/dist/core/extensions.js +5 -0
  76. package/dist/core/grease.d.ts +2 -0
  77. package/dist/core/grease.js +6 -0
  78. package/dist/core/group-event.d.ts +18 -0
  79. package/dist/core/group-event.js +30 -0
  80. package/dist/core/group-lifecycle.d.ts +42 -0
  81. package/dist/core/group-lifecycle.js +66 -0
  82. package/dist/core/group-members.d.ts +37 -0
  83. package/dist/core/group-members.js +99 -0
  84. package/dist/core/group-message-classify.d.ts +42 -0
  85. package/dist/core/group-message-classify.js +57 -0
  86. package/dist/core/group-message-crypto.d.ts +53 -0
  87. package/dist/core/group-message-crypto.js +140 -0
  88. package/dist/core/group-message.d.ts +5 -0
  89. package/dist/core/group-message.js +11 -0
  90. package/dist/core/group.d.ts +56 -0
  91. package/dist/core/group.js +95 -0
  92. package/dist/core/inbound.d.ts +102 -0
  93. package/dist/core/inbound.js +79 -0
  94. package/dist/core/index.d.ts +29 -0
  95. package/dist/core/index.js +27 -0
  96. package/dist/core/key-package-eligibility.d.ts +31 -0
  97. package/dist/core/key-package-eligibility.js +116 -0
  98. package/dist/core/key-package-event-decode.d.ts +43 -0
  99. package/dist/core/key-package-event-decode.js +118 -0
  100. package/dist/core/key-package-event-delete.d.ts +16 -0
  101. package/dist/core/key-package-event-delete.js +46 -0
  102. package/dist/core/key-package-event-encode.d.ts +28 -0
  103. package/dist/core/key-package-event-encode.js +117 -0
  104. package/dist/core/key-package-event.d.ts +4 -0
  105. package/dist/core/key-package-event.js +8 -0
  106. package/dist/core/key-package.d.ts +66 -0
  107. package/dist/core/key-package.js +147 -0
  108. package/dist/core/leaf-succession.d.ts +83 -0
  109. package/dist/core/leaf-succession.js +97 -0
  110. package/dist/core/media/canonical.d.ts +34 -0
  111. package/dist/core/media/canonical.js +57 -0
  112. package/dist/core/media/crypto.d.ts +79 -0
  113. package/dist/core/media/crypto.js +215 -0
  114. package/dist/core/media/imeta.d.ts +33 -0
  115. package/dist/core/media/imeta.js +188 -0
  116. package/dist/core/media/locator.d.ts +44 -0
  117. package/dist/core/media/locator.js +69 -0
  118. package/dist/core/media/types.d.ts +83 -0
  119. package/dist/core/media/types.js +12 -0
  120. package/dist/core/media.d.ts +6 -0
  121. package/dist/core/media.js +12 -0
  122. package/dist/core/protocol-profile.d.ts +262 -0
  123. package/dist/core/protocol-profile.js +535 -0
  124. package/dist/core/protocol.d.ts +51 -0
  125. package/dist/core/protocol.js +41 -0
  126. package/dist/core/relay-lists.d.ts +52 -0
  127. package/dist/core/relay-lists.js +86 -0
  128. package/dist/core/retained-history.d.ts +78 -0
  129. package/dist/core/retained-history.js +59 -0
  130. package/dist/core/transport.d.ts +43 -0
  131. package/dist/core/transport.js +21 -0
  132. package/dist/core/welcome-event.d.ts +61 -0
  133. package/dist/core/welcome-event.js +116 -0
  134. package/dist/core/welcome-join.d.ts +155 -0
  135. package/dist/core/welcome-join.js +243 -0
  136. package/dist/core/welcome.d.ts +3 -0
  137. package/dist/core/welcome.js +6 -0
  138. package/dist/engine/admin-policy.d.ts +75 -0
  139. package/dist/engine/admin-policy.js +137 -0
  140. package/dist/engine/auto-committer.d.ts +39 -0
  141. package/dist/engine/auto-committer.js +42 -0
  142. package/dist/engine/delivered-payloads.d.ts +61 -0
  143. package/dist/engine/delivered-payloads.js +84 -0
  144. package/dist/engine/disband-request.d.ts +41 -0
  145. package/dist/engine/disband-request.js +86 -0
  146. package/dist/engine/disband-tombstone.d.ts +14 -0
  147. package/dist/engine/disband-tombstone.js +66 -0
  148. package/dist/engine/fork-recovery.d.ts +672 -0
  149. package/dist/engine/fork-recovery.js +1615 -0
  150. package/dist/engine/group-engine.d.ts +571 -0
  151. package/dist/engine/group-engine.js +5134 -0
  152. package/dist/engine/history-tree.d.ts +232 -0
  153. package/dist/engine/history-tree.js +651 -0
  154. package/dist/engine/index.d.ts +16 -0
  155. package/dist/engine/index.js +15 -0
  156. package/dist/engine/ingest-disposition.d.ts +5 -0
  157. package/dist/engine/ingest-disposition.js +63 -0
  158. package/dist/engine/ingest.d.ts +390 -0
  159. package/dist/engine/ingest.js +1258 -0
  160. package/dist/engine/ingestion-pool.d.ts +74 -0
  161. package/dist/engine/ingestion-pool.js +95 -0
  162. package/dist/engine/message-dedup.d.ts +16 -0
  163. package/dist/engine/message-dedup.js +20 -0
  164. package/dist/engine/own-commit-stamp.d.ts +30 -0
  165. package/dist/engine/own-commit-stamp.js +71 -0
  166. package/dist/engine/retained-store.d.ts +79 -0
  167. package/dist/engine/retained-store.js +133 -0
  168. package/dist/engine/sender-ratchet.d.ts +50 -0
  169. package/dist/engine/sender-ratchet.js +196 -0
  170. package/dist/engine/state-notifications.d.ts +122 -0
  171. package/dist/engine/state-notifications.js +173 -0
  172. package/dist/engine/tree-convergence.d.ts +41 -0
  173. package/dist/engine/tree-convergence.js +90 -0
  174. package/dist/engine/types.d.ts +366 -0
  175. package/dist/engine/types.js +14 -0
  176. package/dist/engine/wire-format.d.ts +77 -0
  177. package/dist/engine/wire-format.js +120 -0
  178. package/dist/index.d.ts +12 -0
  179. package/dist/index.js +1 -0
  180. package/dist/mls.d.ts +11 -0
  181. package/dist/mls.js +11 -0
  182. package/dist/utils/debug.d.ts +3 -0
  183. package/dist/utils/debug.js +3 -0
  184. package/dist/utils/encoding.d.ts +38 -0
  185. package/dist/utils/encoding.js +91 -0
  186. package/dist/utils/key-value.d.ts +18 -0
  187. package/dist/utils/key-value.js +2 -0
  188. package/dist/utils/nostr.d.ts +35 -0
  189. package/dist/utils/nostr.js +26 -0
  190. package/dist/utils/relay-url.d.ts +10 -0
  191. package/dist/utils/relay-url.js +23 -0
  192. package/dist/utils/tag-cardinality.d.ts +50 -0
  193. package/dist/utils/tag-cardinality.js +91 -0
  194. package/dist/utils/timestamp.d.ts +50 -0
  195. package/dist/utils/timestamp.js +95 -0
  196. package/dist/version.d.ts +112 -0
  197. package/dist/version.js +112 -0
  198. package/package.json +68 -3
@@ -0,0 +1,147 @@
1
+ /** @module @category Core - Key Package */
2
+ import { defaultCredentialTypes, defaultCryptoProvider, getAppDataDictionary, generateKeyPackage as MLSGenerateKeyPackage, generateKeyPackageWithKey as MLSGenerateKeyPackageWithKey, makeKeyPackageRef, } from "ts-mls";
3
+ import { hexToBytes } from "@noble/hashes/utils.js";
4
+ import { createDefaultKeyPackageLifetime, isLifetimeWithinCap, } from "../utils/timestamp.js";
5
+ import { buildAccountIdentityProofExtension, } from "./account-identity-proof.js";
6
+ import { ensureMarmotCapabilities } from "./capabilities.js";
7
+ import { componentEntry, LAST_RESORT_COMPONENT_ID, makeAppComponentsExtension, makeLeafAppComponentsExtension, } from "./components/index.js";
8
+ import { getCredentialPubkey } from "./credential.js";
9
+ import { defaultCapabilities } from "./default-capabilities.js";
10
+ import { makeCurrentLeafAppDataExtension, marmotCapabilitiesForProfile, signCurrentAccountIdentityProof, verifyCurrentAccountIdentityProofForKey, } from "./protocol-profile.js";
11
+ /**
12
+ * Ensures a KeyPackage-level extensions array carries the last-resort marker:
13
+ * the empty-data `0x0004` component inside the KeyPackage-level
14
+ * `app_data_dictionary` extension (AC-VENDOR-8 conformance patch — replaces
15
+ * the legacy standalone `last_resort` MLS extension, which upstream
16
+ * marmot-ts used before this port).
17
+ */
18
+ function ensureLastResortComponent(extensions) {
19
+ const existingDictionary = getAppDataDictionary(extensions);
20
+ if (existingDictionary?.some((c) => c.componentId === LAST_RESORT_COMPONENT_ID))
21
+ return extensions;
22
+ const entries = [
23
+ ...(existingDictionary ?? []),
24
+ componentEntry(LAST_RESORT_COMPONENT_ID, new Uint8Array(0)),
25
+ ];
26
+ const dictionaryExtension = makeAppComponentsExtension(entries);
27
+ const withoutOldDictionary = extensions.filter((e) => getAppDataDictionary([e]) === undefined);
28
+ return [...withoutOldDictionary, dictionaryExtension];
29
+ }
30
+ /** Create default extensions for a key package */
31
+ export function keyPackageDefaultExtensions() {
32
+ return ensureLastResortComponent([]);
33
+ }
34
+ /**
35
+ * Reads whether a KeyPackage is marked reusable ("last resort"): the
36
+ * empty-data `0x0004` component inside its KeyPackage-level (not
37
+ * LeafNode-level) `app_data_dictionary` extension (AC-VENDOR-8).
38
+ *
39
+ * Deliberately reads `keyPackage.extensions` (the `KeyPackageTBS`-level
40
+ * field) rather than `keyPackage.leafNode.extensions` — the same component
41
+ * present only in the LeafNode-level dictionary does not count.
42
+ */
43
+ export function isLastResortKeyPackage(keyPackage) {
44
+ let dictionary;
45
+ try {
46
+ dictionary = getAppDataDictionary(keyPackage.extensions);
47
+ }
48
+ catch {
49
+ return false;
50
+ }
51
+ return (dictionary?.some((c) => c.componentId === LAST_RESORT_COMPONENT_ID) ??
52
+ false);
53
+ }
54
+ /** Calculates a key package reference with the hash implementation based on the key package's cipher suite */
55
+ export async function calculateKeyPackageRef(keyPackage, cryptoProvider) {
56
+ const provider = cryptoProvider ?? defaultCryptoProvider;
57
+ const ciphersuiteImpl = await provider.getCiphersuiteImpl(keyPackage.cipherSuite);
58
+ return await makeKeyPackageRef(keyPackage, ciphersuiteImpl.hash);
59
+ }
60
+ /** Generate a marmot key package that is compliant with MIP-00 */
61
+ export async function generateKeyPackage({ credential, capabilities, lifetime, extensions, isLastResort = true, accountProofSigner, profile = "legacy", currentProof, ciphersuiteImpl, }) {
62
+ if (credential.credentialType !== defaultCredentialTypes.basic)
63
+ throw new Error("Marmot key packages must use a basic credential");
64
+ // Ensure the credential has a valid pubkey
65
+ const accountPubkey = getCredentialPubkey(credential);
66
+ if (profile === "current") {
67
+ const provider = currentProof ??
68
+ (accountProofSigner !== undefined && typeof accountProofSigner !== "function"
69
+ ? (key) => signCurrentAccountIdentityProof({ ...key, signer: accountProofSigner })
70
+ : undefined);
71
+ if (provider === undefined)
72
+ throw new Error("generateKeyPackage: a Current-form KeyPackage needs `currentProof` or an `accountProofSigner` with `signEvent`");
73
+ const lifetimeCurrent = lifetime ?? createDefaultKeyPackageLifetime();
74
+ if (!isLifetimeWithinCap(lifetimeCurrent))
75
+ throw new Error(`generateKeyPackage: lifetime range ${lifetimeCurrent.notAfter - lifetimeCurrent.notBefore}s exceeds the 7,261,200s (84-day) cap`);
76
+ const signatureKeyPair = await ciphersuiteImpl.signature.keygen();
77
+ const accountIdentity = hexToBytes(accountPubkey);
78
+ const proof = await provider({
79
+ accountIdentity,
80
+ mlsSignaturePublicKey: signatureKeyPair.publicKey,
81
+ ciphersuite: ciphersuiteImpl.id,
82
+ });
83
+ // Never mint a leaf the group would reject: the provider's proof must bind this account and this key.
84
+ verifyCurrentAccountIdentityProofForKey(proof, accountIdentity, signatureKeyPair.publicKey, ciphersuiteImpl.id);
85
+ return await MLSGenerateKeyPackageWithKey({
86
+ credential,
87
+ capabilities: marmotCapabilitiesForProfile("current", capabilities),
88
+ lifetime: lifetimeCurrent,
89
+ extensions: isLastResort
90
+ ? ensureLastResortComponent(extensions ?? [])
91
+ : (extensions ?? []),
92
+ signatureKeyPair,
93
+ leafNodeExtensions: [makeCurrentLeafAppDataExtension(proof)],
94
+ cipherSuite: ciphersuiteImpl,
95
+ });
96
+ }
97
+ const resolvedCapabilities = capabilities
98
+ ? ensureMarmotCapabilities(capabilities)
99
+ : defaultCapabilities();
100
+ const resolvedLifetime = lifetime ?? createDefaultKeyPackageLifetime();
101
+ // WIRE-01 produce path: the cap must hold regardless of how lifetime is
102
+ // supplied. The default is always within cap, so this check only ever
103
+ // rejects an explicit caller-supplied `lifetime` override (D-09).
104
+ if (!isLifetimeWithinCap(resolvedLifetime))
105
+ throw new Error(`generateKeyPackage: lifetime range ${resolvedLifetime.notAfter - resolvedLifetime.notBefore}s exceeds the 7,261,200s (84-day) cap`);
106
+ // Marmot requires support for last_resort capability signaling (MIP-00),
107
+ // but individual KeyPackages may be single-use or last-resort reusable.
108
+ // `isLastResort` controls whether this KeyPackage is marked reusable.
109
+ const resolvedExtensions = isLastResort
110
+ ? ensureLastResortComponent(extensions ?? [])
111
+ : (extensions ?? []);
112
+ // Advertise the supported app components on the LeafNode so this member can
113
+ // be added to groups that require them (matches darkmatter's leaf state).
114
+ const leafNodeExtensions = [
115
+ makeLeafAppComponentsExtension(),
116
+ ];
117
+ // When an account signer is supplied, generate the leaf signature keypair
118
+ // first, bind it to the Nostr account with an identity proof, and carry the
119
+ // proof on the LeafNode (darkmatter validates this on every leaf).
120
+ if (accountProofSigner) {
121
+ const signatureKeyPair = await ciphersuiteImpl.signature.keygen();
122
+ leafNodeExtensions.push(await buildAccountIdentityProofExtension({
123
+ accountIdentity: hexToBytes(accountPubkey),
124
+ mlsSignaturePublicKey: signatureKeyPair.publicKey,
125
+ ciphersuite: ciphersuiteImpl.id,
126
+ signer: accountProofSigner,
127
+ }));
128
+ return await MLSGenerateKeyPackageWithKey({
129
+ credential,
130
+ capabilities: resolvedCapabilities,
131
+ lifetime: resolvedLifetime,
132
+ extensions: resolvedExtensions,
133
+ signatureKeyPair,
134
+ leafNodeExtensions,
135
+ cipherSuite: ciphersuiteImpl,
136
+ });
137
+ }
138
+ // In v2, generateKeyPackage takes a single params object
139
+ return await MLSGenerateKeyPackage({
140
+ credential,
141
+ capabilities: resolvedCapabilities,
142
+ lifetime: resolvedLifetime,
143
+ extensions: resolvedExtensions,
144
+ leafNodeExtensions,
145
+ cipherSuite: ciphersuiteImpl,
146
+ });
147
+ }
@@ -0,0 +1,83 @@
1
+ import type { ClientState } from "ts-mls";
2
+ /**
3
+ * Locally authored (not vendored from marmot-ts; listed in VENDOR.md's
4
+ * "Locally authored (not vendored)" section).
5
+ *
6
+ * Key succession: what a leaf's signature key did between two group states.
7
+ *
8
+ * A device can replace the signature key of its own leaf in a commit's UpdatePath
9
+ * (RFC 9420; `SendIntent.selfUpdate.leafNodePatch`) or, in principle, through a
10
+ * committed Update proposal. Every consumer that keys a member by its leaf signature
11
+ * key reads such a replacement as the leaf *disappearing*. {@link leafKeySuccessions}
12
+ * is the one place that tells a replacement of a key in place from a removal: a
13
+ * pure function of a parent and a child `ClientState`.
14
+ *
15
+ * A succession is reported for a leaf index when the leaf is occupied in both
16
+ * states by the same account (same basic credential identity) and carries a
17
+ * different signature key in the child, and the child's leaf was written by the
18
+ * leaf itself: its leaf node source is `commit` (the committer's UpdatePath leaf)
19
+ * or `update` (a committed Update proposal). A Remove plus an Add into the same
20
+ * index yields a `key_package` leaf and is never a succession, nor is a different
21
+ * account at the index, nor a blank index.
22
+ *
23
+ * Consumers:
24
+ * - the equivocation-credit lineage clause (ADR-016 D2 rule 4, `convergence.ts`):
25
+ * only the `commit` successions of the committing leaf itself along a candidate
26
+ * path extend which key of that leaf earns credit;
27
+ * - `epic-marmot-removal-finality` Design Decision 2: its key-difference evidence
28
+ * for "the leaf was removed" takes this predicate as the "a rotation is not a
29
+ * removal" exception when it ships (that epic is design only; this module is
30
+ * the exception it adopts);
31
+ * - `@941design/marmot` (`history/notifications.ts`): `removedLeaves` skips a
32
+ * same-account leaf at the same index iff this reports the index, and
33
+ * `rotatedLeaves` maps the entries to notifications.
34
+ *
35
+ * Precondition: `child` is exactly ONE commit after `parent` (the commit that
36
+ * produced `child` was applied to `parent`). The predicate compares two trees
37
+ * and cannot see what happened between them: over a gap of several commits a
38
+ * Remove plus re-Add of the same account at an index followed by a self-update
39
+ * leaves a `commit`-source leaf with a new key and reads as a rotation. Call it
40
+ * per edge of a window (consecutive states), never on a tip pair.
41
+ *
42
+ * Pure and total: the module imports nothing but `ts-mls` and `./credential.js`,
43
+ * reads no clock, random source or I/O, and never throws, whatever the trees hold
44
+ * (non-basic or malformed credentials, blank nodes, trees of unequal width).
45
+ */
46
+ /** One signature-key replacement of a leaf between a parent and a child state. */
47
+ export interface LeafKeySuccession {
48
+ /** The leaf index at which the key was replaced (the same in both states). */
49
+ readonly leafIndex: number;
50
+ /** Hex account pubkey: the (unchanged) basic-credential identity of the leaf. */
51
+ readonly account: string;
52
+ /** Hex signature public key the leaf held in the parent. */
53
+ readonly fromKey: string;
54
+ /** Hex signature public key the leaf holds in the child. */
55
+ readonly toKey: string;
56
+ /**
57
+ * How the child's leaf came about: `commit` (the committer's UpdatePath leaf, so
58
+ * the committer is the leaf itself) or `update` (a committed Update proposal; the
59
+ * committer may be any other leaf).
60
+ */
61
+ readonly source: "commit" | "update";
62
+ }
63
+ /**
64
+ * The signature-key successions between `parent` and `child`, ordered by leaf
65
+ * index: one entry for every leaf index occupied in both states by the same
66
+ * account whose signature key differs and whose child leaf has source `commit`
67
+ * or `update` (see the module header). Precondition: `child` is exactly one
68
+ * commit after `parent`; over a longer gap the result is NOT guaranteed (a Remove
69
+ * plus re-Add followed by a self-update reads as a rotation).
70
+ *
71
+ * Pure and total: never throws. Totality is per leaf, not per state: a leaf
72
+ * that cannot be read (missing or non-byte `signaturePublicKey`, non-basic or
73
+ * undecodable credential, unknown source) contributes no entry and leaves the
74
+ * other indices' verdicts untouched, so a malformed leaf never erases a
75
+ * genuine rotation elsewhere. This is deliberately NOT the whole-state `[]`
76
+ * reading: under ADR-017 R-1 an empty `succ(x)` would turn every other
77
+ * rotation on the edge into a positive removal fact, whereas R-1's fail-closed
78
+ * value is *absent*, which the removal-fact producer derives on its own when a
79
+ * leaf is unreadable. Only a state that is not a tree at all yields `[]`. Real
80
+ * ts-mls states cannot hold such leaves (`signaturePublicKey` is a required
81
+ * decoded `Uint8Array`); the guard exists for arbitrary input (AC-SUCC-4).
82
+ */
83
+ export declare function leafKeySuccessions(parent: ClientState, child: ClientState): readonly LeafKeySuccession[];
@@ -0,0 +1,97 @@
1
+ /** @module @category Core - Leaf key succession */
2
+ import { defaultCredentialTypes, leafNodeSources, nodeTypes } from "ts-mls";
3
+ import { getCredentialPubkey } from "./credential.js";
4
+ const HEX = "0123456789abcdef";
5
+ function toHex(bytes) {
6
+ let out = "";
7
+ for (let i = 0; i < bytes.length; i++) {
8
+ const byte = bytes[i];
9
+ out += HEX[byte >> 4] + HEX[byte & 15];
10
+ }
11
+ return out;
12
+ }
13
+ function sameBytes(a, b) {
14
+ if (a.length !== b.length)
15
+ return false;
16
+ for (let i = 0; i < a.length; i++)
17
+ if (a[i] !== b[i])
18
+ return false;
19
+ return true;
20
+ }
21
+ /** The leaf at node index `nodeIndex` of `tree`, or `undefined` when blank, a parent node, or out of range. */
22
+ function leafAt(tree, nodeIndex) {
23
+ const node = tree[nodeIndex];
24
+ if (node === undefined || node === null || node.nodeType !== nodeTypes.leaf)
25
+ return undefined;
26
+ const leaf = node.leaf;
27
+ return typeof leaf === "object" && leaf !== null ? leaf : undefined;
28
+ }
29
+ /** The hex account pubkey of `leaf`'s basic credential, or `undefined` when it has none (non-basic or malformed). */
30
+ function accountOf(leaf) {
31
+ try {
32
+ if (leaf.credential.credentialType !== defaultCredentialTypes.basic)
33
+ return undefined;
34
+ return getCredentialPubkey(leaf.credential);
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
40
+ /**
41
+ * The signature-key successions between `parent` and `child`, ordered by leaf
42
+ * index: one entry for every leaf index occupied in both states by the same
43
+ * account whose signature key differs and whose child leaf has source `commit`
44
+ * or `update` (see the module header). Precondition: `child` is exactly one
45
+ * commit after `parent`; over a longer gap the result is NOT guaranteed (a Remove
46
+ * plus re-Add followed by a self-update reads as a rotation).
47
+ *
48
+ * Pure and total: never throws. Totality is per leaf, not per state: a leaf
49
+ * that cannot be read (missing or non-byte `signaturePublicKey`, non-basic or
50
+ * undecodable credential, unknown source) contributes no entry and leaves the
51
+ * other indices' verdicts untouched, so a malformed leaf never erases a
52
+ * genuine rotation elsewhere. This is deliberately NOT the whole-state `[]`
53
+ * reading: under ADR-017 R-1 an empty `succ(x)` would turn every other
54
+ * rotation on the edge into a positive removal fact, whereas R-1's fail-closed
55
+ * value is *absent*, which the removal-fact producer derives on its own when a
56
+ * leaf is unreadable. Only a state that is not a tree at all yields `[]`. Real
57
+ * ts-mls states cannot hold such leaves (`signaturePublicKey` is a required
58
+ * decoded `Uint8Array`); the guard exists for arbitrary input (AC-SUCC-4).
59
+ */
60
+ export function leafKeySuccessions(parent, child) {
61
+ const out = [];
62
+ try {
63
+ const width = Math.min(parent.ratchetTree.length, child.ratchetTree.length);
64
+ for (let nodeIndex = 0; nodeIndex < width; nodeIndex += 2) {
65
+ const before = leafAt(parent.ratchetTree, nodeIndex);
66
+ const after = leafAt(child.ratchetTree, nodeIndex);
67
+ if (before === undefined || after === undefined)
68
+ continue;
69
+ const source = after.leafNodeSource === leafNodeSources.commit
70
+ ? "commit"
71
+ : after.leafNodeSource === leafNodeSources.update
72
+ ? "update"
73
+ : undefined;
74
+ if (source === undefined)
75
+ continue;
76
+ if (!(before.signaturePublicKey instanceof Uint8Array) || !(after.signaturePublicKey instanceof Uint8Array))
77
+ continue;
78
+ if (sameBytes(before.signaturePublicKey, after.signaturePublicKey))
79
+ continue;
80
+ const account = accountOf(before);
81
+ if (account === undefined || account !== accountOf(after))
82
+ continue;
83
+ out.push({
84
+ leafIndex: nodeIndex / 2,
85
+ account,
86
+ fromKey: toHex(before.signaturePublicKey),
87
+ toKey: toHex(after.signaturePublicKey),
88
+ source,
89
+ });
90
+ }
91
+ }
92
+ catch {
93
+ // A state that is not a well-formed tree has no successions (total: never throws).
94
+ return [];
95
+ }
96
+ return out;
97
+ }
@@ -0,0 +1,34 @@
1
+ /** @module @category Core - Encrypted Media */
2
+ /**
3
+ * Canonicalizes a MIME type for use in `encrypted-media-v1` cryptographic
4
+ * operations (key derivation and AEAD AAD).
5
+ *
6
+ * Sender and receiver MUST apply this identical algorithm
7
+ * (`features/encrypted-media.md` — Media Type Canonicalization):
8
+ *
9
+ * 1. take the substring before the first `;`, dropping any parameters
10
+ * 2. trim leading and trailing ASCII whitespace
11
+ * 3. lowercase using ASCII case folding only
12
+ * 4. reject if the result is empty or does not contain `/`
13
+ * 5. apply the canonical alias `image/jpg` → `image/jpeg`
14
+ *
15
+ * Adding an alias or normalization step is a breaking media-version change.
16
+ *
17
+ * @param mimeType - The raw MIME type string
18
+ * @returns The canonical MIME type
19
+ * @throws If the canonical result is empty or has no `/`
20
+ */
21
+ export declare function canonicalizeMimeType(mimeType: string): string;
22
+ /**
23
+ * Returns `true` iff {@link canonicalizeMimeType} accepts `value` (it is a
24
+ * non-empty `type/subtype` string).
25
+ *
26
+ * @internal
27
+ */
28
+ export declare function isValidMimeType(value: string): boolean;
29
+ /**
30
+ * Returns true iff `value` is valid hex with the expected encoded byte length.
31
+ *
32
+ * @internal
33
+ */
34
+ export declare function isValidHex(value: string, expectedBytes: number): boolean;
@@ -0,0 +1,57 @@
1
+ /** @module @category Core - Encrypted Media */
2
+ /**
3
+ * Canonicalizes a MIME type for use in `encrypted-media-v1` cryptographic
4
+ * operations (key derivation and AEAD AAD).
5
+ *
6
+ * Sender and receiver MUST apply this identical algorithm
7
+ * (`features/encrypted-media.md` — Media Type Canonicalization):
8
+ *
9
+ * 1. take the substring before the first `;`, dropping any parameters
10
+ * 2. trim leading and trailing ASCII whitespace
11
+ * 3. lowercase using ASCII case folding only
12
+ * 4. reject if the result is empty or does not contain `/`
13
+ * 5. apply the canonical alias `image/jpg` → `image/jpeg`
14
+ *
15
+ * Adding an alias or normalization step is a breaking media-version change.
16
+ *
17
+ * @param mimeType - The raw MIME type string
18
+ * @returns The canonical MIME type
19
+ * @throws If the canonical result is empty or has no `/`
20
+ */
21
+ export function canonicalizeMimeType(mimeType) {
22
+ // Steps 1–3: strip parameters, trim, ASCII-lowercase.
23
+ const base = mimeType
24
+ .split(";")[0]
25
+ .trim()
26
+ .replace(/[A-Z]/g, (c) => c.toLowerCase());
27
+ // Step 4: reject empty or `/`-less results.
28
+ const slash = base.indexOf("/");
29
+ if (slash <= 0 || slash >= base.length - 1) {
30
+ throw new Error(`invalid media type: ${JSON.stringify(mimeType)}`);
31
+ }
32
+ // Step 5: canonical alias.
33
+ return base === "image/jpg" ? "image/jpeg" : base;
34
+ }
35
+ /**
36
+ * Returns `true` iff {@link canonicalizeMimeType} accepts `value` (it is a
37
+ * non-empty `type/subtype` string).
38
+ *
39
+ * @internal
40
+ */
41
+ export function isValidMimeType(value) {
42
+ try {
43
+ canonicalizeMimeType(value);
44
+ return true;
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ }
50
+ /**
51
+ * Returns true iff `value` is valid hex with the expected encoded byte length.
52
+ *
53
+ * @internal
54
+ */
55
+ export function isValidHex(value, expectedBytes) {
56
+ return value.length === expectedBytes * 2 && /^[0-9a-f]+$/.test(value);
57
+ }
@@ -0,0 +1,79 @@
1
+ import { type CiphersuiteImpl, type ClientState } from "ts-mls";
2
+ import { type EncryptMediaFileResult, type MediaAttachment } from "./types.js";
3
+ /** The crypto-relevant subset of a {@link MediaAttachment}. */
4
+ export type MediaCryptoFields = Pick<MediaAttachment, "plaintextSha256" | "mediaType" | "filename">;
5
+ /**
6
+ * Derives the per-file encryption key for an `encrypted-media-v1` attachment.
7
+ *
8
+ * ```
9
+ * media_secret = MLS-Exporter("marmot", "encrypted-media", 32) at source_epoch
10
+ * file_key = HKDF-Expand(media_secret,
11
+ * "encrypted-media-v1" || 0x00 || plaintext_sha256_bytes ||
12
+ * 0x00 || media_type || 0x00 || filename || 0x00 || "key", 32)
13
+ * ```
14
+ *
15
+ * HKDF is HKDF-SHA256 with `media_secret` used directly as the PRK (Expand
16
+ * only, no Extract). The key is deterministic for a given source epoch + file.
17
+ *
18
+ * The source epoch is the MLS epoch of the application message that carried the
19
+ * attachment. The caller MUST pass the `ClientState` for that epoch: on send,
20
+ * the current state; on receive, the retained state for the message's source
21
+ * epoch (see `features/encrypted-media.md` — Key Derivation).
22
+ *
23
+ * @param clientState - The MLS `ClientState` for the attachment's source epoch
24
+ * @param ciphersuite - The ciphersuite implementation used by the group
25
+ * @param attachment - Provides `plaintextSha256`, `mediaType`, and `filename`
26
+ * @returns 32-byte ChaCha20-Poly1305 encryption key
27
+ */
28
+ export declare function deriveMediaEncryptionKey(clientState: ClientState, ciphersuite: CiphersuiteImpl, attachment: MediaCryptoFields): Promise<Uint8Array>;
29
+ /**
30
+ * Encrypts a media file for an `encrypted-media-v1` attachment.
31
+ *
32
+ * Uses ChaCha20-Poly1305 AEAD with a random 12-byte nonce. The AAD binds the
33
+ * scheme version, plaintext hash, canonical MIME type, and filename. Computes
34
+ * `ciphertextSha256 = SHA256(encrypted)` and returns a {@link MediaAttachment}
35
+ * with `locators` left empty for the caller to fill after upload.
36
+ *
37
+ * @param file - The plaintext file bytes to encrypt
38
+ * @param fileKey - 32-byte key from {@link deriveMediaEncryptionKey}
39
+ * @param fields - Provides `plaintextSha256`, `mediaType`, and `filename`;
40
+ * optional `dim`/`thumbhash` are carried through onto the result
41
+ * @returns Encrypted blob and a populated {@link MediaAttachment}
42
+ */
43
+ export declare function encryptMediaFile(file: Uint8Array, fileKey: Uint8Array, fields: MediaCryptoFields & Pick<Partial<MediaAttachment>, "dim" | "thumbhash">): EncryptMediaFileResult;
44
+ /**
45
+ * Decrypts a fetched `encrypted-media-v1` blob.
46
+ *
47
+ * Performs the receive-side integrity checks in order
48
+ * (`features/encrypted-media.md` — Validation):
49
+ *
50
+ * 1. the fetched bytes match `ciphertextSha256`
51
+ * 2. ChaCha20-Poly1305 authentication succeeds
52
+ * 3. the decrypted bytes match `plaintextSha256`
53
+ *
54
+ * @param encrypted - The encrypted blob downloaded from a blob store
55
+ * @param fileKey - 32-byte key from {@link deriveMediaEncryptionKey}
56
+ * @param attachment - The parsed attachment from the message's `imeta` tag
57
+ * @returns The decrypted file bytes
58
+ * @throws If any integrity check fails or required fields are missing
59
+ */
60
+ export declare function decryptMediaFile(encrypted: Uint8Array, fileKey: Uint8Array, attachment: MediaAttachment): Uint8Array;
61
+ /**
62
+ * Decrypts a fetched `encrypted-media-v1` blob, trying each candidate key in
63
+ * order until one authenticates the ciphertext.
64
+ *
65
+ * The media file key is derived from the source-epoch media exporter secret
66
+ * (`features/encrypted-media.md` — Key Derivation), but the source epoch is not
67
+ * carried in the `imeta` tag. Rather than thread the source epoch through every
68
+ * caller, the receiver supplies one key per still-retained epoch (current epoch
69
+ * first) and relies on the AEAD tag to identify the right one. The ciphertext
70
+ * hash is verified once; only the cheap AEAD open is retried per key.
71
+ *
72
+ * @param encrypted - The encrypted blob downloaded from a blob store
73
+ * @param fileKeys - Candidate keys from {@link deriveMediaEncryptionKey}, one
74
+ * per retained epoch; tried in order. MUST be non-empty.
75
+ * @param attachment - The parsed attachment from the message's `imeta` tag
76
+ * @returns The decrypted file bytes from the first key that authenticates
77
+ * @throws If no candidate key authenticates the ciphertext, or a check fails
78
+ */
79
+ export declare function decryptMediaFileWithKeys(encrypted: Uint8Array, fileKeys: Uint8Array[], attachment: MediaAttachment): Uint8Array;