@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,155 @@
1
+ /** @module @category Core - Welcome */
2
+ import { Rumor } from "../utils/nostr.js";
3
+ import { CiphersuiteImpl, type ClientConfig, type ClientState, type Credential, type GroupInfo, KeyPackage, PrivateKeyPackage, type Welcome } from "ts-mls";
4
+ import { type MarmotGroupView } from "./client-state.js";
5
+ /**
6
+ * Decrypts the {@link GroupInfo} from a Welcome message using the provided key package.
7
+ *
8
+ * This executes a full ts-mls `joinGroup` — the same protocol run
9
+ * {@link joinGroupFromWelcome} performs — and then discards everything but
10
+ * the `GroupInfo`. It is not a lighter-weight path: the Welcome is
11
+ * validated exactly as it would be by a real join, giving access to
12
+ * `groupContext` (group ID, epoch, extensions) and `GroupInfo`-level
13
+ * extensions (ratchet tree, external pub) without keeping the resulting
14
+ * `ClientState` around.
15
+ *
16
+ * `clientConfig` MUST match the config the group's creator (and every prior
17
+ * committer) used, for the same reason it matters to
18
+ * {@link joinGroupFromWelcome} — see the note there. Because this function
19
+ * performs a real join internally, omitting `clientConfig` here while
20
+ * passing one to `joinGroupFromWelcome` for the same Welcome is itself a
21
+ * silent-fork hazard: one call validates under ts-mls defaults, the other
22
+ * under the caller's config (AC-VENDOR-6).
23
+ *
24
+ * @returns The decrypted GroupInfo
25
+ * @throws Error if the key package does not match any secret in the welcome
26
+ */
27
+ export declare function readWelcomeGroupInfo({ welcome, keyPackage, ciphersuiteImpl, clientConfig, }: {
28
+ /** The MLS Welcome message (or a kind 444 Rumor) */
29
+ welcome: Welcome | Rumor;
30
+ /** The full key package (public + private) used to receive the invite */
31
+ keyPackage: {
32
+ publicPackage: KeyPackage;
33
+ privatePackage: PrivateKeyPackage;
34
+ };
35
+ /** The ciphersuite implementation */
36
+ ciphersuiteImpl: CiphersuiteImpl;
37
+ /** ts-mls `ClientConfig` — see the module-level note on config agreement. */
38
+ clientConfig?: ClientConfig;
39
+ }): Promise<GroupInfo>;
40
+ /**
41
+ * Joins a group from a Welcome message (or a kind 444 Rumor), performing a
42
+ * full ts-mls join and returning the resulting {@link ClientState}.
43
+ *
44
+ * {@link readWelcomeGroupInfo} performs this SAME full join internally and
45
+ * then discards everything but the `GroupInfo`; this function keeps the
46
+ * live, ready-to-use group state instead of discarding it.
47
+ *
48
+ * `clientConfig` MUST match the config the group's creator (and every prior
49
+ * committer) used — a mismatched `keyPackageEqualityConfig` in particular is
50
+ * a silent-fork hazard: this member can accept a commit the group's other
51
+ * members would reject, or vice versa (AC-VENDOR-6). Defaults to ts-mls's
52
+ * own default when omitted.
53
+ *
54
+ * @returns The joined {@link ClientState}
55
+ * @throws Error if the key package does not match any secret in the welcome
56
+ */
57
+ export declare function joinGroupFromWelcome({ welcome, keyPackage, ciphersuiteImpl, clientConfig, }: {
58
+ /** The MLS Welcome message (or a kind 444 Rumor) */
59
+ welcome: Welcome | Rumor;
60
+ /** The full key package (public + private) used to receive the invite */
61
+ keyPackage: {
62
+ publicPackage: KeyPackage;
63
+ privatePackage: PrivateKeyPackage;
64
+ };
65
+ /** The ciphersuite implementation */
66
+ ciphersuiteImpl: CiphersuiteImpl;
67
+ /** ts-mls `ClientConfig` — see the module-level note on config agreement. */
68
+ clientConfig?: ClientConfig;
69
+ }): Promise<ClientState>;
70
+ /**
71
+ * The member leaf that signed a Welcome's GroupInfo — the author of the
72
+ * commit the Welcome belongs to — as ts-mls verified it during the join.
73
+ */
74
+ export interface GroupInfoSigner {
75
+ /** `GroupInfo.signer`: the signer's leaf index in the joined ratchet tree. */
76
+ readonly leafIndex: number;
77
+ /**
78
+ * That leaf's credential: its Marmot account identity
79
+ * ({@link getCredentialPubkey}). Several leaves of one account share it.
80
+ */
81
+ readonly credential: Credential;
82
+ /** That leaf's signature key: the key the GroupInfo signature verified under. */
83
+ readonly signaturePublicKey: Uint8Array;
84
+ }
85
+ /**
86
+ * The `GroupInfo.signer` leaf index when `message` is exactly the input of a
87
+ * GroupInfo signature — `SignContent { label = "MLS 1.0 GroupInfoTBS",
88
+ * content = GroupInfoTBS }` (RFC 9420 §5.1.2, §12.4.3) as ts-mls's
89
+ * `verifyWithLabel` encodes it — and `undefined` for any other input.
90
+ *
91
+ * Matched on the whole layout, never on a length or a prefix: the label
92
+ * bytes, a minimal length prefix whose content runs exactly to the end, and
93
+ * content that decodes as a GroupInfoTBS whose canonical re-encoding
94
+ * reproduces it byte for byte. `groupInfoTBSEncoder` writes `signer` last as
95
+ * a big-endian uint32, so the decoded `signer` is also the content's final
96
+ * four bytes.
97
+ */
98
+ export declare function groupInfoSignerOfSignatureInput(message: Uint8Array): number | undefined;
99
+ /**
100
+ * {@link joinGroupFromWelcome}, also returning the leaf that signed the
101
+ * Welcome's GroupInfo.
102
+ *
103
+ * ts-mls's `joinGroup` verifies the GroupInfo signature against the signer
104
+ * leaf of the joined tree but returns neither the GroupInfo nor the signer.
105
+ * The join here runs over `ciphersuiteImpl` with `signature.verify` wrapped:
106
+ * every call is passed through unchanged (same arguments, same result) and
107
+ * the one SUCCESSFUL call whose input is a GroupInfo signature
108
+ * ({@link groupInfoSignerOfSignatureInput}) records the signer leaf index
109
+ * and the key it verified under. Every other call — leaf-node, KeyPackage,
110
+ * framed-content signatures — is only passed through.
111
+ *
112
+ * Fails closed: throws when the join did not verify exactly one GroupInfo
113
+ * signature, or when the recorded leaf of the joined tree is not a leaf
114
+ * holding the key the signature verified under. Same join and the same
115
+ * errors as {@link joinGroupFromWelcome} otherwise.
116
+ */
117
+ export declare function joinGroupFromWelcomeWithSigner(params: {
118
+ /** The MLS Welcome message (or a kind 444 Rumor) */
119
+ welcome: Welcome | Rumor;
120
+ /** The full key package (public + private) used to receive the invite */
121
+ keyPackage: {
122
+ publicPackage: KeyPackage;
123
+ privatePackage: PrivateKeyPackage;
124
+ };
125
+ /** The ciphersuite implementation */
126
+ ciphersuiteImpl: CiphersuiteImpl;
127
+ /** ts-mls `ClientConfig` — see the module-level note on config agreement. */
128
+ clientConfig?: ClientConfig;
129
+ }): Promise<{
130
+ state: ClientState;
131
+ signer: GroupInfoSigner;
132
+ }>;
133
+ /**
134
+ * Reads the {@link MarmotGroupView} from a Welcome message using the provided
135
+ * key package.
136
+ *
137
+ * Convenience wrapper around {@link readWelcomeGroupInfo} — which performs a
138
+ * full ts-mls join and discards everything but the `GroupInfo` — that
139
+ * projects the app-component state from `groupInfo.groupContext.extensions`.
140
+ *
141
+ * @returns The group view, or null if no app components are present
142
+ */
143
+ export declare function readWelcomeMarmotGroupView({ welcome, keyPackage, ciphersuiteImpl, clientConfig, }: {
144
+ /** The MLS Welcome message (or a kind 444 Rumor) */
145
+ welcome: Welcome | Rumor;
146
+ /** The full key package (public + private) used to receive the invite */
147
+ keyPackage: {
148
+ publicPackage: KeyPackage;
149
+ privatePackage: PrivateKeyPackage;
150
+ };
151
+ /** The ciphersuite implementation */
152
+ ciphersuiteImpl: CiphersuiteImpl;
153
+ /** ts-mls `ClientConfig` — see the module-level note on config agreement. */
154
+ clientConfig?: ClientConfig;
155
+ }): Promise<MarmotGroupView | null>;
@@ -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,75 @@
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
+ /**
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"];
29
+ }): IncomingMessageCallback;
30
+ /**
31
+ * A pure side-channel decorator around an `IncomingMessageCallback`, used to
32
+ * capture a commit's own proposals for the WIRE-03/CONV-01 commit-legality
33
+ * validators (`src/core/components/integrity.ts`).
34
+ *
35
+ * WHY this exists: ts-mls has no OpenMLS `StagedCommit` equivalent —
36
+ * `processMessage` returns the fully-applied `newState` in one step, and
37
+ * `IncomingMessageCallback` is the only pre-apply hook, but it never sees the
38
+ * resulting `GroupContext`. `validateCommitLegality` needs both the
39
+ * pre-apply (`parentState`) and post-apply (`resultingState`) `ClientState`,
40
+ * plus the commit's own proposals, so it can only run AFTER `processMessage`
41
+ * resolves. This wrapper's sole job is to make the commit's proposals
42
+ * available at that later point — it is a side channel, not a policy
43
+ * decision. It feeds the same algorithm ported from MDK's
44
+ * `refs/mdk/crates/cgka-engine/src/app_components.rs`
45
+ * `validate_app_component_integrity_for_staged_commit`.
46
+ *
47
+ * `callback` delegates every decision to `inner` unchanged — this is a
48
+ * decorator, NOT a policy change. The
49
+ * `refs/marmot/protocol-core/group-messaging.md` admin gate, the
50
+ * account-identity-proof check, and the admin-self-remove guard in
51
+ * `createAdminCommitPolicyCallback` all keep their exact current behavior.
52
+ * Its only extra effect: when `incoming.kind === "commit"`, it appends
53
+ * `incoming.proposals.map((p) => p.proposal)` to a private buffer BEFORE
54
+ * returning `inner(incoming)`, so proposals are captured even for a commit
55
+ * the admin gate itself rejects.
56
+ *
57
+ * No validation logic may be added inside this wrapper or inside `inner`
58
+ * (Pitfall 1 — validating inside the callback runs before the resulting
59
+ * `GroupContext` exists and would produce wrong verdicts or throw mid-apply).
60
+ *
61
+ * Contract: `take()` returns the buffered proposals and clears the buffer.
62
+ * Callers MUST call `take()` immediately before each `processMessage` call
63
+ * (discarding the result, to clear any stale proposals left over from a
64
+ * prior message) and again immediately after `processMessage` returns (to
65
+ * read exactly the proposals of the commit just processed). This makes it
66
+ * safe to reuse one `callback`/`take()` pair across a loop of several
67
+ * commits processed with the same wrapped callback.
68
+ */
69
+ export declare function withCapturedProposals(inner: IncomingMessageCallback): {
70
+ callback: IncomingMessageCallback;
71
+ take(): {
72
+ proposals: ProposalWithSender[];
73
+ committerLeafIndex: number | undefined;
74
+ };
75
+ };
@@ -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;