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

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 (196) hide show
  1. package/CHANGELOG.md +434 -0
  2. package/LICENSE +49 -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 +74 -0
  55. package/dist/core/components/ids.js +73 -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 +45 -0
  91. package/dist/core/group.js +78 -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 +28 -0
  95. package/dist/core/index.js +26 -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 +102 -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 +55 -0
  107. package/dist/core/key-package.js +115 -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.d.ts +51 -0
  123. package/dist/core/protocol.js +41 -0
  124. package/dist/core/relay-lists.d.ts +52 -0
  125. package/dist/core/relay-lists.js +86 -0
  126. package/dist/core/retained-history.d.ts +78 -0
  127. package/dist/core/retained-history.js +59 -0
  128. package/dist/core/transport.d.ts +43 -0
  129. package/dist/core/transport.js +21 -0
  130. package/dist/core/welcome-event.d.ts +61 -0
  131. package/dist/core/welcome-event.js +116 -0
  132. package/dist/core/welcome-join.d.ts +155 -0
  133. package/dist/core/welcome-join.js +243 -0
  134. package/dist/core/welcome.d.ts +3 -0
  135. package/dist/core/welcome.js +6 -0
  136. package/dist/engine/admin-policy.d.ts +58 -0
  137. package/dist/engine/admin-policy.js +137 -0
  138. package/dist/engine/auto-committer.d.ts +39 -0
  139. package/dist/engine/auto-committer.js +42 -0
  140. package/dist/engine/delivered-payloads.d.ts +61 -0
  141. package/dist/engine/delivered-payloads.js +84 -0
  142. package/dist/engine/disband-request.d.ts +41 -0
  143. package/dist/engine/disband-request.js +86 -0
  144. package/dist/engine/disband-tombstone.d.ts +14 -0
  145. package/dist/engine/disband-tombstone.js +66 -0
  146. package/dist/engine/fork-recovery.d.ts +672 -0
  147. package/dist/engine/fork-recovery.js +1615 -0
  148. package/dist/engine/group-engine.d.ts +571 -0
  149. package/dist/engine/group-engine.js +5112 -0
  150. package/dist/engine/history-tree.d.ts +232 -0
  151. package/dist/engine/history-tree.js +651 -0
  152. package/dist/engine/index.d.ts +16 -0
  153. package/dist/engine/index.js +15 -0
  154. package/dist/engine/ingest-disposition.d.ts +5 -0
  155. package/dist/engine/ingest-disposition.js +63 -0
  156. package/dist/engine/ingest.d.ts +390 -0
  157. package/dist/engine/ingest.js +1258 -0
  158. package/dist/engine/ingestion-pool.d.ts +74 -0
  159. package/dist/engine/ingestion-pool.js +95 -0
  160. package/dist/engine/message-dedup.d.ts +16 -0
  161. package/dist/engine/message-dedup.js +20 -0
  162. package/dist/engine/own-commit-stamp.d.ts +30 -0
  163. package/dist/engine/own-commit-stamp.js +71 -0
  164. package/dist/engine/retained-store.d.ts +79 -0
  165. package/dist/engine/retained-store.js +133 -0
  166. package/dist/engine/sender-ratchet.d.ts +50 -0
  167. package/dist/engine/sender-ratchet.js +196 -0
  168. package/dist/engine/state-notifications.d.ts +122 -0
  169. package/dist/engine/state-notifications.js +173 -0
  170. package/dist/engine/tree-convergence.d.ts +41 -0
  171. package/dist/engine/tree-convergence.js +90 -0
  172. package/dist/engine/types.d.ts +366 -0
  173. package/dist/engine/types.js +14 -0
  174. package/dist/engine/wire-format.d.ts +77 -0
  175. package/dist/engine/wire-format.js +120 -0
  176. package/dist/index.d.ts +12 -0
  177. package/dist/index.js +1 -0
  178. package/dist/mls.d.ts +11 -0
  179. package/dist/mls.js +11 -0
  180. package/dist/utils/debug.d.ts +3 -0
  181. package/dist/utils/debug.js +3 -0
  182. package/dist/utils/encoding.d.ts +38 -0
  183. package/dist/utils/encoding.js +91 -0
  184. package/dist/utils/key-value.d.ts +18 -0
  185. package/dist/utils/key-value.js +2 -0
  186. package/dist/utils/nostr.d.ts +35 -0
  187. package/dist/utils/nostr.js +26 -0
  188. package/dist/utils/relay-url.d.ts +10 -0
  189. package/dist/utils/relay-url.js +23 -0
  190. package/dist/utils/tag-cardinality.d.ts +50 -0
  191. package/dist/utils/tag-cardinality.js +91 -0
  192. package/dist/utils/timestamp.d.ts +50 -0
  193. package/dist/utils/timestamp.js +95 -0
  194. package/dist/version.d.ts +112 -0
  195. package/dist/version.js +112 -0
  196. package/package.json +68 -3
@@ -0,0 +1,243 @@
1
+ /** @module @category Core - Welcome */
2
+ import { isRumor } from "../utils/nostr.js";
3
+ import { decode, encode, joinGroup, mlsMessageDecoder, mlsMessageEncoder, nodeTypes, protocolVersions, wireformats, } from "ts-mls";
4
+ import { marmotAuthService } from "./auth-service.js";
5
+ import { getMarmotGroupView } from "./client-state.js";
6
+ import { getWelcome } from "./welcome-event.js";
7
+ /**
8
+ * Decrypts the {@link GroupInfo} from a Welcome message using the provided key package.
9
+ *
10
+ * This executes a full ts-mls `joinGroup` — the same protocol run
11
+ * {@link joinGroupFromWelcome} performs — and then discards everything but
12
+ * the `GroupInfo`. It is not a lighter-weight path: the Welcome is
13
+ * validated exactly as it would be by a real join, giving access to
14
+ * `groupContext` (group ID, epoch, extensions) and `GroupInfo`-level
15
+ * extensions (ratchet tree, external pub) without keeping the resulting
16
+ * `ClientState` around.
17
+ *
18
+ * `clientConfig` MUST match the config the group's creator (and every prior
19
+ * committer) used, for the same reason it matters to
20
+ * {@link joinGroupFromWelcome} — see the note there. Because this function
21
+ * performs a real join internally, omitting `clientConfig` here while
22
+ * passing one to `joinGroupFromWelcome` for the same Welcome is itself a
23
+ * silent-fork hazard: one call validates under ts-mls defaults, the other
24
+ * under the caller's config (AC-VENDOR-6).
25
+ *
26
+ * @returns The decrypted GroupInfo
27
+ * @throws Error if the key package does not match any secret in the welcome
28
+ */
29
+ export async function readWelcomeGroupInfo({ welcome, keyPackage, ciphersuiteImpl, clientConfig, }) {
30
+ // Unwrap welcome rumor if provided
31
+ if (isRumor(welcome))
32
+ welcome = getWelcome(welcome);
33
+ try {
34
+ const clientState = await joinGroup({
35
+ context: {
36
+ cipherSuite: ciphersuiteImpl,
37
+ authService: marmotAuthService,
38
+ externalPsks: {},
39
+ clientConfig,
40
+ },
41
+ welcome,
42
+ keyPackage: keyPackage.publicPackage,
43
+ privateKeys: keyPackage.privatePackage,
44
+ });
45
+ return {
46
+ groupContext: clientState.groupContext,
47
+ extensions: [],
48
+ confirmationTag: clientState.confirmationTag,
49
+ signer: clientState.privatePath.leafIndex,
50
+ signature: new Uint8Array(),
51
+ };
52
+ }
53
+ catch (err) {
54
+ throw new Error(`Failed to decrypt group secrets: key package does not match this welcome (${err instanceof Error ? err.message : String(err)})`);
55
+ }
56
+ }
57
+ /**
58
+ * Joins a group from a Welcome message (or a kind 444 Rumor), performing a
59
+ * full ts-mls join and returning the resulting {@link ClientState}.
60
+ *
61
+ * {@link readWelcomeGroupInfo} performs this SAME full join internally and
62
+ * then discards everything but the `GroupInfo`; this function keeps the
63
+ * live, ready-to-use group state instead of discarding it.
64
+ *
65
+ * `clientConfig` MUST match the config the group's creator (and every prior
66
+ * committer) used — a mismatched `keyPackageEqualityConfig` in particular is
67
+ * a silent-fork hazard: this member can accept a commit the group's other
68
+ * members would reject, or vice versa (AC-VENDOR-6). Defaults to ts-mls's
69
+ * own default when omitted.
70
+ *
71
+ * @returns The joined {@link ClientState}
72
+ * @throws Error if the key package does not match any secret in the welcome
73
+ */
74
+ export async function joinGroupFromWelcome({ welcome, keyPackage, ciphersuiteImpl, clientConfig, }) {
75
+ // Unwrap welcome rumor if provided
76
+ if (isRumor(welcome))
77
+ welcome = getWelcome(welcome);
78
+ try {
79
+ return await joinGroup({
80
+ context: {
81
+ cipherSuite: ciphersuiteImpl,
82
+ authService: marmotAuthService,
83
+ externalPsks: {},
84
+ clientConfig,
85
+ },
86
+ welcome,
87
+ keyPackage: keyPackage.publicPackage,
88
+ privateKeys: keyPackage.privatePackage,
89
+ });
90
+ }
91
+ catch (err) {
92
+ throw new Error(`Failed to decrypt group secrets: key package does not match this welcome (${err instanceof Error ? err.message : String(err)})`);
93
+ }
94
+ }
95
+ const GROUP_INFO_TBS_LABEL = new TextEncoder().encode("MLS 1.0 GroupInfoTBS");
96
+ function bytesEqual(a, b) {
97
+ if (a.length !== b.length)
98
+ return false;
99
+ for (let i = 0; i < a.length; i++)
100
+ if (a[i] !== b[i])
101
+ return false;
102
+ return true;
103
+ }
104
+ /** An RFC 9420 §2.1.2 variable-length integer at `offset`, minimally encoded only: `[value, size]`. */
105
+ function readMinimalVarint(bytes, offset) {
106
+ if (offset >= bytes.length)
107
+ return undefined;
108
+ const size = [1, 2, 4, 0][bytes[offset] >> 6];
109
+ if (size === 0 || offset + size > bytes.length)
110
+ return undefined;
111
+ let value = bytes[offset] & 0x3f;
112
+ for (let i = 1; i < size; i++)
113
+ value = value * 256 + bytes[offset + i];
114
+ const minimal = size === 1 || value >= (size === 2 ? 64 : 16384);
115
+ return minimal ? [value, size] : undefined;
116
+ }
117
+ /**
118
+ * The `GroupInfo.signer` leaf index when `message` is exactly the input of a
119
+ * GroupInfo signature — `SignContent { label = "MLS 1.0 GroupInfoTBS",
120
+ * content = GroupInfoTBS }` (RFC 9420 §5.1.2, §12.4.3) as ts-mls's
121
+ * `verifyWithLabel` encodes it — and `undefined` for any other input.
122
+ *
123
+ * Matched on the whole layout, never on a length or a prefix: the label
124
+ * bytes, a minimal length prefix whose content runs exactly to the end, and
125
+ * content that decodes as a GroupInfoTBS whose canonical re-encoding
126
+ * reproduces it byte for byte. `groupInfoTBSEncoder` writes `signer` last as
127
+ * a big-endian uint32, so the decoded `signer` is also the content's final
128
+ * four bytes.
129
+ */
130
+ export function groupInfoSignerOfSignatureInput(message) {
131
+ const label = readMinimalVarint(message, 0);
132
+ if (label === undefined || label[0] !== GROUP_INFO_TBS_LABEL.length)
133
+ return undefined;
134
+ let offset = label[1];
135
+ const labelBytes = message.subarray(offset, offset + label[0]);
136
+ if (!bytesEqual(labelBytes, GROUP_INFO_TBS_LABEL))
137
+ return undefined;
138
+ offset += label[0];
139
+ const content = readMinimalVarint(message, offset);
140
+ if (content === undefined)
141
+ return undefined;
142
+ offset += content[1];
143
+ if (offset + content[0] !== message.length || content[0] < 4)
144
+ return undefined;
145
+ const tbs = message.subarray(offset);
146
+ // A GroupInfoTBS is a GroupInfo without its trailing `signature<V>`: frame
147
+ // it as an MLSMessage(group_info) with an empty signature, so the public
148
+ // MLSMessage codec parses it.
149
+ const framed = new Uint8Array(4 + tbs.length + 1);
150
+ framed[1] = protocolVersions.mls10;
151
+ framed[3] = wireformats.mls_group_info;
152
+ framed.set(tbs, 4);
153
+ let signer;
154
+ try {
155
+ const decoded = decode(mlsMessageDecoder, framed);
156
+ if (decoded?.wireformat !== wireformats.mls_group_info)
157
+ return undefined;
158
+ if (!bytesEqual(encode(mlsMessageEncoder, decoded), framed))
159
+ return undefined;
160
+ signer = decoded.groupInfo.signer;
161
+ }
162
+ catch {
163
+ return undefined;
164
+ }
165
+ const trailing = new DataView(tbs.buffer, tbs.byteOffset + tbs.length - 4, 4).getUint32(0);
166
+ return trailing === signer ? signer : undefined;
167
+ }
168
+ /**
169
+ * {@link joinGroupFromWelcome}, also returning the leaf that signed the
170
+ * Welcome's GroupInfo.
171
+ *
172
+ * ts-mls's `joinGroup` verifies the GroupInfo signature against the signer
173
+ * leaf of the joined tree but returns neither the GroupInfo nor the signer.
174
+ * The join here runs over `ciphersuiteImpl` with `signature.verify` wrapped:
175
+ * every call is passed through unchanged (same arguments, same result) and
176
+ * the one SUCCESSFUL call whose input is a GroupInfo signature
177
+ * ({@link groupInfoSignerOfSignatureInput}) records the signer leaf index
178
+ * and the key it verified under. Every other call — leaf-node, KeyPackage,
179
+ * framed-content signatures — is only passed through.
180
+ *
181
+ * Fails closed: throws when the join did not verify exactly one GroupInfo
182
+ * signature, or when the recorded leaf of the joined tree is not a leaf
183
+ * holding the key the signature verified under. Same join and the same
184
+ * errors as {@link joinGroupFromWelcome} otherwise.
185
+ */
186
+ export async function joinGroupFromWelcomeWithSigner(params) {
187
+ const signature = params.ciphersuiteImpl.signature;
188
+ const verified = [];
189
+ const observed = {
190
+ ...params.ciphersuiteImpl,
191
+ signature: {
192
+ sign: (signKey, message) => signature.sign(signKey, message),
193
+ keygen: () => signature.keygen(),
194
+ verify: async (publicKey, message, sig) => {
195
+ const ok = await signature.verify(publicKey, message, sig);
196
+ if (ok) {
197
+ const leafIndex = groupInfoSignerOfSignatureInput(message);
198
+ if (leafIndex !== undefined)
199
+ verified.push({ leafIndex, publicKey: publicKey.slice() });
200
+ }
201
+ return ok;
202
+ },
203
+ },
204
+ };
205
+ const state = await joinGroupFromWelcome({
206
+ ...params,
207
+ ciphersuiteImpl: observed,
208
+ });
209
+ if (verified.length !== 1)
210
+ throw new Error(`GroupInfo signer not recovered: the join verified ${verified.length} GroupInfo signatures, expected exactly 1`);
211
+ const [{ leafIndex, publicKey }] = verified;
212
+ const node = state.ratchetTree[leafIndex * 2];
213
+ if (node?.nodeType !== nodeTypes.leaf ||
214
+ !bytesEqual(node.leaf.signaturePublicKey, publicKey))
215
+ throw new Error(`GroupInfo signer not recovered: leaf ${leafIndex} of the joined tree does not hold the key the GroupInfo signature verified under`);
216
+ return {
217
+ state,
218
+ signer: {
219
+ leafIndex,
220
+ credential: node.leaf.credential,
221
+ signaturePublicKey: node.leaf.signaturePublicKey,
222
+ },
223
+ };
224
+ }
225
+ /**
226
+ * Reads the {@link MarmotGroupView} from a Welcome message using the provided
227
+ * key package.
228
+ *
229
+ * Convenience wrapper around {@link readWelcomeGroupInfo} — which performs a
230
+ * full ts-mls join and discards everything but the `GroupInfo` — that
231
+ * projects the app-component state from `groupInfo.groupContext.extensions`.
232
+ *
233
+ * @returns The group view, or null if no app components are present
234
+ */
235
+ export async function readWelcomeMarmotGroupView({ welcome, keyPackage, ciphersuiteImpl, clientConfig, }) {
236
+ const groupInfo = await readWelcomeGroupInfo({
237
+ welcome,
238
+ keyPackage,
239
+ ciphersuiteImpl,
240
+ clientConfig,
241
+ });
242
+ return getMarmotGroupView(groupInfo);
243
+ }
@@ -0,0 +1,3 @@
1
+ /** @module @category Core - Welcome */
2
+ export * from "./welcome-event.js";
3
+ export * from "./welcome-join.js";
@@ -0,0 +1,6 @@
1
+ /** @module @category Core - Welcome */
2
+ // Transport codec: build/parse the kind-444 welcome rumor and read its MLS
3
+ // Welcome payload + recipient KeyPackageRefs.
4
+ export * from "./welcome-event.js";
5
+ // MLS join: decrypt the group secrets/GroupInfo from a Welcome (uses joinGroup).
6
+ export * from "./welcome-join.js";
@@ -0,0 +1,58 @@
1
+ /** @module @category Engine */
2
+ import { type ClientState, type IncomingMessageCallback, type ProposalWithSender } from "ts-mls";
3
+ /**
4
+ * Build an incoming-message callback that enforces
5
+ * `refs/marmot/protocol-core/group-messaging.md` "admin-only commits".
6
+ */
7
+ export declare function createAdminCommitPolicyCallback(args: {
8
+ ratchetTree: ClientState["ratchetTree"];
9
+ adminPubkeys: string[];
10
+ ciphersuiteId: number;
11
+ onUnverifiableCommit?: "reject" | "retry";
12
+ }): IncomingMessageCallback;
13
+ /**
14
+ * A pure side-channel decorator around an `IncomingMessageCallback`, used to
15
+ * capture a commit's own proposals for the WIRE-03/CONV-01 commit-legality
16
+ * validators (`src/core/components/integrity.ts`).
17
+ *
18
+ * WHY this exists: ts-mls has no OpenMLS `StagedCommit` equivalent —
19
+ * `processMessage` returns the fully-applied `newState` in one step, and
20
+ * `IncomingMessageCallback` is the only pre-apply hook, but it never sees the
21
+ * resulting `GroupContext`. `validateCommitLegality` needs both the
22
+ * pre-apply (`parentState`) and post-apply (`resultingState`) `ClientState`,
23
+ * plus the commit's own proposals, so it can only run AFTER `processMessage`
24
+ * resolves. This wrapper's sole job is to make the commit's proposals
25
+ * available at that later point — it is a side channel, not a policy
26
+ * decision. It feeds the same algorithm ported from MDK's
27
+ * `refs/mdk/crates/cgka-engine/src/app_components.rs`
28
+ * `validate_app_component_integrity_for_staged_commit`.
29
+ *
30
+ * `callback` delegates every decision to `inner` unchanged — this is a
31
+ * decorator, NOT a policy change. The
32
+ * `refs/marmot/protocol-core/group-messaging.md` admin gate, the
33
+ * account-identity-proof check, and the admin-self-remove guard in
34
+ * `createAdminCommitPolicyCallback` all keep their exact current behavior.
35
+ * Its only extra effect: when `incoming.kind === "commit"`, it appends
36
+ * `incoming.proposals.map((p) => p.proposal)` to a private buffer BEFORE
37
+ * returning `inner(incoming)`, so proposals are captured even for a commit
38
+ * the admin gate itself rejects.
39
+ *
40
+ * No validation logic may be added inside this wrapper or inside `inner`
41
+ * (Pitfall 1 — validating inside the callback runs before the resulting
42
+ * `GroupContext` exists and would produce wrong verdicts or throw mid-apply).
43
+ *
44
+ * Contract: `take()` returns the buffered proposals and clears the buffer.
45
+ * Callers MUST call `take()` immediately before each `processMessage` call
46
+ * (discarding the result, to clear any stale proposals left over from a
47
+ * prior message) and again immediately after `processMessage` returns (to
48
+ * read exactly the proposals of the commit just processed). This makes it
49
+ * safe to reuse one `callback`/`take()` pair across a loop of several
50
+ * commits processed with the same wrapped callback.
51
+ */
52
+ export declare function withCapturedProposals(inner: IncomingMessageCallback): {
53
+ callback: IncomingMessageCallback;
54
+ take(): {
55
+ proposals: ProposalWithSender[];
56
+ committerLeafIndex: number | undefined;
57
+ };
58
+ };
@@ -0,0 +1,137 @@
1
+ /** @module @category Engine */
2
+ import { defaultProposalTypes, getCredentialFromLeafIndex, selfRemoveProposalType, } from "ts-mls";
3
+ import { ACCOUNT_IDENTITY_PROOF_EXTENSION_TYPE, verifyLeafAccountIdentityProof, } from "../core/account-identity-proof.js";
4
+ import { getCredentialPubkey } from "../core/credential.js";
5
+ function toLeafIndex(index) {
6
+ return index;
7
+ }
8
+ /**
9
+ * Build an incoming-message callback that enforces
10
+ * `refs/marmot/protocol-core/group-messaging.md` "admin-only commits".
11
+ */
12
+ export function createAdminCommitPolicyCallback(args) {
13
+ const { ratchetTree, adminPubkeys, ciphersuiteId, onUnverifiableCommit = "retry", } = args;
14
+ return (incoming) => {
15
+ if (incoming.kind === "proposal")
16
+ return "accept";
17
+ for (const { proposal } of incoming.proposals) {
18
+ if (proposal.proposalType !== defaultProposalTypes.add)
19
+ continue;
20
+ if (!("add" in proposal))
21
+ continue;
22
+ const leaf = proposal.add.keyPackage.leafNode;
23
+ const hasProof = leaf.extensions.some((e) => e.extensionType === ACCOUNT_IDENTITY_PROOF_EXTENSION_TYPE);
24
+ if (!hasProof)
25
+ continue;
26
+ try {
27
+ verifyLeafAccountIdentityProof(leaf, ciphersuiteId);
28
+ }
29
+ catch {
30
+ return "reject";
31
+ }
32
+ }
33
+ // An admin MUST drop admin before self-removing (member-departure.md), so a
34
+ // self_remove whose sender (the leaver) is still an active admin is invalid.
35
+ // Checked before the admin short-circuit below, so even an admin committer
36
+ // cannot splice in an admin's self_remove.
37
+ for (const { proposal, senderLeafIndex } of incoming.proposals) {
38
+ if (proposal.proposalType !== selfRemoveProposalType)
39
+ continue;
40
+ if (senderLeafIndex === undefined)
41
+ return "reject";
42
+ try {
43
+ const leaverPubkey = getCredentialPubkey(getCredentialFromLeafIndex(ratchetTree, toLeafIndex(Number(senderLeafIndex))));
44
+ if (adminPubkeys.includes(leaverPubkey))
45
+ return "reject";
46
+ }
47
+ catch {
48
+ return "reject";
49
+ }
50
+ }
51
+ const senderLeafIndexUnknown = incoming.senderLeafIndex;
52
+ if (senderLeafIndexUnknown === undefined)
53
+ return "reject";
54
+ const senderLeafIndex = typeof senderLeafIndexUnknown === "number"
55
+ ? toLeafIndex(senderLeafIndexUnknown)
56
+ : senderLeafIndexUnknown;
57
+ try {
58
+ const senderCredential = getCredentialFromLeafIndex(ratchetTree, senderLeafIndex);
59
+ const senderPubkey = getCredentialPubkey(senderCredential);
60
+ if (adminPubkeys.includes(senderPubkey))
61
+ return "accept";
62
+ if (incoming.proposals.length === 0)
63
+ return "accept";
64
+ // A non-admin may commit only a self-update-only commit (its own Update)
65
+ // or a self_remove-only commit (committing peers' departures), per
66
+ // protocol-core/group-messaging.md.
67
+ const isSelfUpdateOnly = incoming.proposals.every((p) => p.proposal.proposalType === defaultProposalTypes.update &&
68
+ p.senderLeafIndex !== undefined &&
69
+ Number(p.senderLeafIndex) === Number(senderLeafIndex));
70
+ const isSelfRemoveOnly = incoming.proposals.every((p) => p.proposal.proposalType === selfRemoveProposalType);
71
+ return isSelfUpdateOnly || isSelfRemoveOnly ? "accept" : "reject";
72
+ }
73
+ catch {
74
+ if (onUnverifiableCommit === "retry") {
75
+ throw new Error("unverifiable commit sender");
76
+ }
77
+ return "reject";
78
+ }
79
+ };
80
+ }
81
+ /**
82
+ * A pure side-channel decorator around an `IncomingMessageCallback`, used to
83
+ * capture a commit's own proposals for the WIRE-03/CONV-01 commit-legality
84
+ * validators (`src/core/components/integrity.ts`).
85
+ *
86
+ * WHY this exists: ts-mls has no OpenMLS `StagedCommit` equivalent —
87
+ * `processMessage` returns the fully-applied `newState` in one step, and
88
+ * `IncomingMessageCallback` is the only pre-apply hook, but it never sees the
89
+ * resulting `GroupContext`. `validateCommitLegality` needs both the
90
+ * pre-apply (`parentState`) and post-apply (`resultingState`) `ClientState`,
91
+ * plus the commit's own proposals, so it can only run AFTER `processMessage`
92
+ * resolves. This wrapper's sole job is to make the commit's proposals
93
+ * available at that later point — it is a side channel, not a policy
94
+ * decision. It feeds the same algorithm ported from MDK's
95
+ * `refs/mdk/crates/cgka-engine/src/app_components.rs`
96
+ * `validate_app_component_integrity_for_staged_commit`.
97
+ *
98
+ * `callback` delegates every decision to `inner` unchanged — this is a
99
+ * decorator, NOT a policy change. The
100
+ * `refs/marmot/protocol-core/group-messaging.md` admin gate, the
101
+ * account-identity-proof check, and the admin-self-remove guard in
102
+ * `createAdminCommitPolicyCallback` all keep their exact current behavior.
103
+ * Its only extra effect: when `incoming.kind === "commit"`, it appends
104
+ * `incoming.proposals.map((p) => p.proposal)` to a private buffer BEFORE
105
+ * returning `inner(incoming)`, so proposals are captured even for a commit
106
+ * the admin gate itself rejects.
107
+ *
108
+ * No validation logic may be added inside this wrapper or inside `inner`
109
+ * (Pitfall 1 — validating inside the callback runs before the resulting
110
+ * `GroupContext` exists and would produce wrong verdicts or throw mid-apply).
111
+ *
112
+ * Contract: `take()` returns the buffered proposals and clears the buffer.
113
+ * Callers MUST call `take()` immediately before each `processMessage` call
114
+ * (discarding the result, to clear any stale proposals left over from a
115
+ * prior message) and again immediately after `processMessage` returns (to
116
+ * read exactly the proposals of the commit just processed). This makes it
117
+ * safe to reuse one `callback`/`take()` pair across a loop of several
118
+ * commits processed with the same wrapped callback.
119
+ */
120
+ export function withCapturedProposals(inner) {
121
+ let buffered = [];
122
+ let committerLeafIndex;
123
+ const callback = (incoming) => {
124
+ if (incoming.kind === "commit") {
125
+ buffered = buffered.concat(incoming.proposals);
126
+ committerLeafIndex = incoming.senderLeafIndex;
127
+ }
128
+ return inner(incoming);
129
+ };
130
+ const take = () => {
131
+ const result = { proposals: buffered, committerLeafIndex };
132
+ buffered = [];
133
+ committerLeafIndex = undefined;
134
+ return result;
135
+ };
136
+ return { callback, take };
137
+ }
@@ -0,0 +1,39 @@
1
+ /** @module @category Engine */
2
+ /**
3
+ * Whether this client should commit a peer's `self_remove` proposal, or just
4
+ * observe and let another member do it.
5
+ */
6
+ export type AutoCommitDecision = "commit" | "observe";
7
+ /**
8
+ * Decides whether *this* client auto-commits the round's `self_remove`
9
+ * proposals (Marmot v2 `protocol-core/member-departure.md`, darkmatter
10
+ * `auto_committer.rs`).
11
+ *
12
+ * A `self_remove`-only commit may carry several departures at once, so the
13
+ * decision is over the whole leaver set rather than one proposal. Every
14
+ * remaining member runs this independently on the same inputs, so the choice is
15
+ * deterministic and exactly one member commits — which is what stops concurrent
16
+ * committers from forking the group. The rule:
17
+ *
18
+ * 1. A leaver never commits the batch (RFC 9420 §12.2 — a committer cannot
19
+ * remove their own leaf).
20
+ * 2. If any leaver is still an active admin the batch is refused: an admin MUST
21
+ * drop admin before leaving, so it would produce an invalid commit.
22
+ * `anyLeaverIsActiveAdmin` is fail-closed — pass `true` when the admin set or
23
+ * a leaver's identity cannot be read, so an unreadable state never commits.
24
+ * 3. Otherwise the eligible committers are all current members except the
25
+ * leavers, and only the one with the lowest MLS leaf index commits.
26
+ *
27
+ * There is no fallback timer: if the lowest-index eligible member is offline,
28
+ * the commit simply waits until they (or a re-evaluated set) act.
29
+ */
30
+ export declare function decideAutoCommit(params: {
31
+ /** Leaf indices of the leaving members (`self_remove` proposal senders). */
32
+ leaverLeafIndices: number[];
33
+ /** This client's own leaf index. */
34
+ ownLeafIndex: number;
35
+ /** Leaf indices of all current members (occupied leaves). */
36
+ memberLeafIndices: number[];
37
+ /** Whether any leaver is still an active admin (fail-closed: `true` if unknown). */
38
+ anyLeaverIsActiveAdmin: boolean;
39
+ }): AutoCommitDecision;
@@ -0,0 +1,42 @@
1
+ /** @module @category Engine */
2
+ /**
3
+ * Decides whether *this* client auto-commits the round's `self_remove`
4
+ * proposals (Marmot v2 `protocol-core/member-departure.md`, darkmatter
5
+ * `auto_committer.rs`).
6
+ *
7
+ * A `self_remove`-only commit may carry several departures at once, so the
8
+ * decision is over the whole leaver set rather than one proposal. Every
9
+ * remaining member runs this independently on the same inputs, so the choice is
10
+ * deterministic and exactly one member commits — which is what stops concurrent
11
+ * committers from forking the group. The rule:
12
+ *
13
+ * 1. A leaver never commits the batch (RFC 9420 §12.2 — a committer cannot
14
+ * remove their own leaf).
15
+ * 2. If any leaver is still an active admin the batch is refused: an admin MUST
16
+ * drop admin before leaving, so it would produce an invalid commit.
17
+ * `anyLeaverIsActiveAdmin` is fail-closed — pass `true` when the admin set or
18
+ * a leaver's identity cannot be read, so an unreadable state never commits.
19
+ * 3. Otherwise the eligible committers are all current members except the
20
+ * leavers, and only the one with the lowest MLS leaf index commits.
21
+ *
22
+ * There is no fallback timer: if the lowest-index eligible member is offline,
23
+ * the commit simply waits until they (or a re-evaluated set) act.
24
+ */
25
+ export function decideAutoCommit(params) {
26
+ const { leaverLeafIndices, ownLeafIndex, memberLeafIndices, anyLeaverIsActiveAdmin, } = params;
27
+ const leavers = new Set(leaverLeafIndices);
28
+ if (leavers.size === 0)
29
+ return "observe";
30
+ // (1) A leaver never commits the batch.
31
+ if (leavers.has(ownLeafIndex))
32
+ return "observe";
33
+ // (2) An admin must leave the admin set before self-removing; never
34
+ // auto-commit a batch containing an admin's self_remove (fail-closed).
35
+ if (anyLeaverIsActiveAdmin)
36
+ return "observe";
37
+ // (3) Lowest-leaf-index eligible member (all members except the leavers) commits.
38
+ const eligible = memberLeafIndices.filter((i) => !leavers.has(i));
39
+ if (eligible.length === 0)
40
+ return "observe";
41
+ return ownLeafIndex === Math.min(...eligible) ? "commit" : "observe";
42
+ }
@@ -0,0 +1,61 @@
1
+ /** @module @category Engine */
2
+ import type { MlsMessage } from "ts-mls";
3
+ /**
4
+ * One application payload delivered (yielded `processed` / `accepted`) on a
5
+ * specific branch state. Remembered so that if a later convergence rewind
6
+ * abandons the branch it decrypted on, the payload can be reported
7
+ * `invalidated` (`protocol-core/inbound-processing.md`, `convergence.md`).
8
+ */
9
+ export interface DeliveredAppPayload<TEnvelope> {
10
+ /** Epoch of the state the payload decrypted against. */
11
+ epoch: number;
12
+ /** Hex confirmation tag of that state — its branch+epoch identity. */
13
+ stateTag: string;
14
+ envelope: TEnvelope;
15
+ /** The MLS application message (encrypted wrapper). */
16
+ message: MlsMessage;
17
+ /** The decrypted Marmot app payload bytes, so a retraction can name it. */
18
+ payload: Uint8Array;
19
+ }
20
+ /**
21
+ * A bounded ledger of application payloads already delivered as `accepted`,
22
+ * keyed by the branch state they decrypted on.
23
+ *
24
+ * Marmot v2 delivers app payloads eagerly — there is no settle-then-release
25
+ * gate yet (that is B5) — so when a convergence fork rewind abandons a branch,
26
+ * the payloads delivered on it MUST be retracted with an `invalidated`
27
+ * notification. This ledger lets the engine find exactly those payloads on a
28
+ * rewind.
29
+ *
30
+ * It holds no protocol state of its own; entries are pruned only below the
31
+ * oldest state still named by retained history or the fork tree. A finite,
32
+ * pruned tree can bound this ledger. With an unpruned full-history tree — and
33
+ * especially `maxRewindCommits: Infinity` — correctness requires unbounded
34
+ * retention until tree pruning exists. Mirrors the bookkeeping darkmatter does in
35
+ * `distributed_convergence.rs` (`AppMessageInvalidated`).
36
+ */
37
+ export declare class DeliveredPayloadLedger<TEnvelope> {
38
+ #private;
39
+ /** Number of remembered payloads. */
40
+ get size(): number;
41
+ /** Whether this exact MLS message is recorded against `stateTag`. */
42
+ has(stateTag: string, message: MlsMessage): boolean;
43
+ /** Retained transport envelopes used as witnesses by later fork passes. */
44
+ envelopes(): TEnvelope[];
45
+ /** Remembers a delivered application payload. */
46
+ record(entry: DeliveredAppPayload<TEnvelope>): void;
47
+ /**
48
+ * Removes and returns the payloads abandoned by a rewind to a canonical
49
+ * branch: those delivered strictly after `forkEpoch` whose delivery state is
50
+ * not on the canonical chain (`canonicalTags`). Payloads that decrypted on
51
+ * the canonical branch, and any at or below the fork epoch (shared history),
52
+ * are retained.
53
+ */
54
+ invalidatedByRewind(forkEpoch: number, canonicalTags: ReadonlySet<string>): DeliveredAppPayload<TEnvelope>[];
55
+ /**
56
+ * Drops entries below the caller's tree-aware correctness horizon. The
57
+ * engine supplies `min(retained anchor, oldest tree-node epoch)` so no
58
+ * payload still nameable by a fork candidate loses its retraction record.
59
+ */
60
+ pruneBelow(epoch: number): void;
61
+ }