@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,16 @@
1
+ import { Credential, CredentialBasic } from "ts-mls";
2
+ export declare function isHexKey(str: string): boolean;
3
+ /**
4
+ * Whether `identity` is a valid Marmot account identity: exactly 32 bytes and a
5
+ * valid x-only secp256k1 public key (it lifts to a point on the curve via
6
+ * BIP-340 `lift_x`). `foundation/identity.md`: "clients reject credentials whose
7
+ * identity is not a valid x-only secp256k1 public key." Mirrors darkmatter
8
+ * `validate_credential_identity` (`k256::schnorr::VerifyingKey::from_bytes`).
9
+ */
10
+ export declare function isValidAccountIdentity(identity: Uint8Array): boolean;
11
+ /** Creates a MLS basic credential from a nostr public key. */
12
+ export declare function createCredential(pubkey: string): CredentialBasic;
13
+ /** Gets the nostr public key from a credential. */
14
+ export declare function getCredentialPubkey(credential: Credential): string;
15
+ /** Checks if two credentials are the same. */
16
+ export declare function isSameCredential(a: Credential, b: Credential): boolean;
@@ -0,0 +1,64 @@
1
+ /** @module @category Core - Credentials */
2
+ import { secp256k1 } from "@noble/curves/secp256k1.js";
3
+ import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
4
+ import { defaultCredentialTypes } from "ts-mls";
5
+ export function isHexKey(str) {
6
+ return /^[0-9a-fA-F]{64}$/.test(str);
7
+ }
8
+ /**
9
+ * Whether `identity` is a valid Marmot account identity: exactly 32 bytes and a
10
+ * valid x-only secp256k1 public key (it lifts to a point on the curve via
11
+ * BIP-340 `lift_x`). `foundation/identity.md`: "clients reject credentials whose
12
+ * identity is not a valid x-only secp256k1 public key." Mirrors darkmatter
13
+ * `validate_credential_identity` (`k256::schnorr::VerifyingKey::from_bytes`).
14
+ */
15
+ export function isValidAccountIdentity(identity) {
16
+ if (identity.length !== 32)
17
+ return false;
18
+ try {
19
+ // lift_x: an x-only key is valid iff its x-coordinate is < the field prime
20
+ // and lies on the curve. Parsing it as a compressed point (even-y prefix)
21
+ // performs exactly that check; an invalid x throws.
22
+ secp256k1.Point.fromHex(`02${bytesToHex(identity)}`);
23
+ return true;
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ }
29
+ /** Creates a MLS basic credential from a nostr public key. */
30
+ export function createCredential(pubkey) {
31
+ if (isHexKey(pubkey) === false)
32
+ throw new Error("Invalid nostr public key, must be 64 hex characters");
33
+ const identity = hexToBytes(pubkey);
34
+ if (!isValidAccountIdentity(identity))
35
+ throw new Error("Invalid nostr public key: not a valid x-only secp256k1 public key");
36
+ return {
37
+ credentialType: defaultCredentialTypes.basic,
38
+ identity,
39
+ };
40
+ }
41
+ /** Gets the nostr public key from a credential. */
42
+ export function getCredentialPubkey(credential) {
43
+ if (credential.credentialType !== defaultCredentialTypes.basic)
44
+ throw new Error("Credential is not a basic credential, cannot get nostr public key");
45
+ // Type assertion needed because TypeScript doesn't narrow credential type
46
+ const basicCredential = credential;
47
+ const str = bytesToHex(basicCredential.identity);
48
+ // Marmot requires identity to be the raw 32-byte Nostr pubkey.
49
+ // If this is not 32 bytes, bytesToHex() will not yield 64 hex chars.
50
+ if (isHexKey(str) === false)
51
+ throw new Error("Invalid credential nostr public key");
52
+ return str;
53
+ }
54
+ /** Checks if two credentials are the same. */
55
+ export function isSameCredential(a, b) {
56
+ // If they are basic credentials, we can just compare the identities
57
+ if (a.credentialType === defaultCredentialTypes.basic &&
58
+ b.credentialType === defaultCredentialTypes.basic) {
59
+ const aBasic = a;
60
+ const bBasic = b;
61
+ return bytesToHex(aBasic.identity) === bytesToHex(bBasic.identity);
62
+ }
63
+ return false;
64
+ }
@@ -0,0 +1,9 @@
1
+ /** @module @category Core - Capabilities */
2
+ import { Capabilities } from "ts-mls";
3
+ /**
4
+ * Default capabilities for Marmot key packages.
5
+ *
6
+ * According to MIP-01, key packages MUST signal support for the Marmot Group Data Extension
7
+ * and ratchet_tree in their capabilities to pass validation when being added to groups.
8
+ */
9
+ export declare function defaultCapabilities(): Capabilities;
@@ -0,0 +1,34 @@
1
+ /** @module @category Core - Capabilities */
2
+ import { ciphersuites, defaultCapabilities as mlsDefaultCapabilities, defaultCredentialTypes, } from "ts-mls";
3
+ import { ensureMarmotCapabilities } from "./capabilities.js";
4
+ import { isGreaseValue } from "./grease.js";
5
+ /**
6
+ * Default capabilities for Marmot key packages.
7
+ *
8
+ * According to MIP-01, key packages MUST signal support for the Marmot Group Data Extension
9
+ * and ratchet_tree in their capabilities to pass validation when being added to groups.
10
+ */
11
+ export function defaultCapabilities() {
12
+ let capabilities = mlsDefaultCapabilities();
13
+ // Ensure capabilities include the Marmot Group Data Extension
14
+ capabilities = ensureMarmotCapabilities(capabilities);
15
+ // Filter ciphersuites: keep the default one (MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519)
16
+ // and keep GREASE values (numeric IDs), but remove other MLS ciphersuites
17
+ // In v2, ciphersuites is an object mapping names to numeric IDs
18
+ const defaultCiphersuiteName = "MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519";
19
+ capabilities.ciphersuites = Object.entries(ciphersuites)
20
+ .filter(([name, id]) => {
21
+ // Keep the default ciphersuite by name
22
+ if (name === defaultCiphersuiteName)
23
+ return true;
24
+ // Keep canonical GREASE values published by ts-mls.
25
+ if (isGreaseValue(id))
26
+ return true;
27
+ return false;
28
+ })
29
+ .map(([, id]) => id);
30
+ // Only include "basic" credential type (remove "x509" since we don't support it)
31
+ // In v2, credential types are numeric values (see defaultCredentialTypes)
32
+ capabilities.credentials = capabilities.credentials.filter((c) => c === defaultCredentialTypes.basic);
33
+ return capabilities;
34
+ }
@@ -0,0 +1,9 @@
1
+ /** @module @category Core - Extensions */
2
+ /** Replaces an extension in an array of extensions */
3
+ export declare function replaceExtension(extensions: Array<{
4
+ extensionType: number;
5
+ }>, extension: {
6
+ extensionType: number;
7
+ }): Array<{
8
+ extensionType: number;
9
+ }>;
@@ -0,0 +1,5 @@
1
+ /** @module @category Core - Extensions */
2
+ /** Replaces an extension in an array of extensions */
3
+ export function replaceExtension(extensions, extension) {
4
+ return extensions.map((ext) => ext.extensionType === extension.extensionType ? extension : ext);
5
+ }
@@ -0,0 +1,2 @@
1
+ export declare const GREASE_VALUE_SET: ReadonlySet<number>;
2
+ export declare function isGreaseValue(value: number): boolean;
@@ -0,0 +1,6 @@
1
+ /** @module @category Core - Grease */
2
+ import { greaseValues } from "ts-mls";
3
+ export const GREASE_VALUE_SET = new Set(greaseValues);
4
+ export function isGreaseValue(value) {
5
+ return GREASE_VALUE_SET.has(value);
6
+ }
@@ -0,0 +1,18 @@
1
+ /** @module @category Core - Group Messages */
2
+ import { NostrEvent } from "../utils/nostr.js";
3
+ import { ClientState, CiphersuiteImpl, type MlsMessage } from "ts-mls";
4
+ export type CreateGroupEventOptions = {
5
+ /** The serialized MLS message */
6
+ message: MlsMessage;
7
+ /** The ClientState for the group */
8
+ state: ClientState;
9
+ /** The ciphersuite implementation */
10
+ ciphersuite: CiphersuiteImpl;
11
+ };
12
+ /**
13
+ * Creates a Nostr event containing an encrypted MLS message.
14
+ *
15
+ * @param options - The options for creating the event
16
+ * @returns A signed Nostr event
17
+ */
18
+ export declare function createGroupEvent(options: CreateGroupEventOptions): Promise<NostrEvent>;
@@ -0,0 +1,30 @@
1
+ /** @module @category Core - Group Messages */
2
+ import { finalizeEvent, generateSecretKey } from "../utils/nostr.js";
3
+ import { unixNow } from "../utils/nostr.js";
4
+ import { getNostrGroupIdHex } from "./client-state.js";
5
+ import { nostrTransportBinding } from "./transport.js";
6
+ import { createEncryptedGroupEventContent } from "./group-message-crypto.js";
7
+ /**
8
+ * Creates a Nostr event containing an encrypted MLS message.
9
+ *
10
+ * @param options - The options for creating the event
11
+ * @returns A signed Nostr event
12
+ */
13
+ export async function createGroupEvent(options) {
14
+ const { message, state, ciphersuite } = options;
15
+ const content = await createEncryptedGroupEventContent({
16
+ state,
17
+ ciphersuite,
18
+ message,
19
+ });
20
+ const groupId = getNostrGroupIdHex(state);
21
+ const draft = {
22
+ kind: nostrTransportBinding.groupMessageKind,
23
+ created_at: unixNow(),
24
+ content,
25
+ tags: [[nostrTransportBinding.groupIdTag, groupId]],
26
+ };
27
+ // Ephemeral keypair for signing — distinct from the encryption keypair (MIP-03)
28
+ const ephemeralSecretKey = generateSecretKey();
29
+ return finalizeEvent(draft, ephemeralSecretKey);
30
+ }
@@ -0,0 +1,42 @@
1
+ /** @module @category Core - Group Lifecycle */
2
+ /**
3
+ * The Marmot v2 group lifecycle state machine (`protocol-core/group-state.md`).
4
+ *
5
+ * Each group has exactly one canonical MLS state at a time; a client may hold
6
+ * candidate or pending state transiently but exposes only one canonical state.
7
+ * The lifecycle gates when local commits may be prepared and whether retained
8
+ * inbound may change canonical state.
9
+ */
10
+ export declare const groupLifecycleStates: {
11
+ /** Has a canonical MLS epoch; normal inbound/outbound work may proceed. */
12
+ readonly stable: "Stable";
13
+ /** A local group-state commit is prepared but its publish is unconfirmed. */
14
+ readonly pendingPublish: "PendingPublish";
15
+ /** Publication confirmed; the staged commit is being applied locally. */
16
+ readonly merging: "Merging";
17
+ /** A fork-shaped conflict was detected; selecting a safe retained branch. */
18
+ readonly recovering: "Recovering";
19
+ /** A selected lifecycle-v1 disband Commit terminated this group forever. */
20
+ readonly disbanded: "Disbanded";
21
+ /** No safe branch can be selected from retained local material (client-local). */
22
+ readonly unrecoverable: "Unrecoverable";
23
+ };
24
+ /** A group lifecycle state value. */
25
+ export type GroupLifecycleState = (typeof groupLifecycleStates)[keyof typeof groupLifecycleStates];
26
+ /** Returns whether `from -> to` is a legal lifecycle transition. */
27
+ export declare function canTransitionLifecycle(from: GroupLifecycleState, to: GroupLifecycleState): boolean;
28
+ /** Throws if `from -> to` is not a legal lifecycle transition; returns `to`. */
29
+ export declare function transitionLifecycle(from: GroupLifecycleState, to: GroupLifecycleState): GroupLifecycleState;
30
+ /**
31
+ * A client MAY prepare a new local group-state commit only in `Stable`. (Fork
32
+ * detection also runs only from `Stable`.)
33
+ */
34
+ export declare function mayPrepareLocalCommit(state: GroupLifecycleState): boolean;
35
+ /**
36
+ * Whether retained inbound may change canonical group state in this lifecycle
37
+ * state. Only `Stable` (normal processing) and `Recovering` (a selected branch
38
+ * is applied) may; `PendingPublish`, `Merging`, and `Unrecoverable` MUST NOT.
39
+ */
40
+ export declare function mayApplyRetainedInbound(state: GroupLifecycleState): boolean;
41
+ /** Whether fork detection may run (only from settled `Stable` canonical state). */
42
+ export declare function mayRunForkDetection(state: GroupLifecycleState): boolean;
@@ -0,0 +1,66 @@
1
+ /** @module @category Core - Group Lifecycle */
2
+ /**
3
+ * The Marmot v2 group lifecycle state machine (`protocol-core/group-state.md`).
4
+ *
5
+ * Each group has exactly one canonical MLS state at a time; a client may hold
6
+ * candidate or pending state transiently but exposes only one canonical state.
7
+ * The lifecycle gates when local commits may be prepared and whether retained
8
+ * inbound may change canonical state.
9
+ */
10
+ export const groupLifecycleStates = {
11
+ /** Has a canonical MLS epoch; normal inbound/outbound work may proceed. */
12
+ stable: "Stable",
13
+ /** A local group-state commit is prepared but its publish is unconfirmed. */
14
+ pendingPublish: "PendingPublish",
15
+ /** Publication confirmed; the staged commit is being applied locally. */
16
+ merging: "Merging",
17
+ /** A fork-shaped conflict was detected; selecting a safe retained branch. */
18
+ recovering: "Recovering",
19
+ /** A selected lifecycle-v1 disband Commit terminated this group forever. */
20
+ disbanded: "Disbanded",
21
+ /** No safe branch can be selected from retained local material (client-local). */
22
+ unrecoverable: "Unrecoverable",
23
+ };
24
+ const S = groupLifecycleStates;
25
+ /**
26
+ * The legal lifecycle transitions from `group-state.md`. `Recovering` also
27
+ * re-enters itself implicitly (convergence input arriving mid-recovery folds
28
+ * into the same pass), so it is included as a self-edge.
29
+ */
30
+ const LEGAL_TRANSITIONS = {
31
+ [S.stable]: [S.pendingPublish, S.recovering],
32
+ [S.pendingPublish]: [S.merging, S.stable],
33
+ [S.merging]: [S.stable],
34
+ [S.recovering]: [S.stable, S.unrecoverable, S.disbanded, S.recovering],
35
+ [S.disbanded]: [],
36
+ [S.unrecoverable]: [S.stable],
37
+ };
38
+ /** Returns whether `from -> to` is a legal lifecycle transition. */
39
+ export function canTransitionLifecycle(from, to) {
40
+ return LEGAL_TRANSITIONS[from].includes(to);
41
+ }
42
+ /** Throws if `from -> to` is not a legal lifecycle transition; returns `to`. */
43
+ export function transitionLifecycle(from, to) {
44
+ if (!canTransitionLifecycle(from, to))
45
+ throw new Error(`Illegal group lifecycle transition: ${from} -> ${to}`);
46
+ return to;
47
+ }
48
+ /**
49
+ * A client MAY prepare a new local group-state commit only in `Stable`. (Fork
50
+ * detection also runs only from `Stable`.)
51
+ */
52
+ export function mayPrepareLocalCommit(state) {
53
+ return state === S.stable;
54
+ }
55
+ /**
56
+ * Whether retained inbound may change canonical group state in this lifecycle
57
+ * state. Only `Stable` (normal processing) and `Recovering` (a selected branch
58
+ * is applied) may; `PendingPublish`, `Merging`, and `Unrecoverable` MUST NOT.
59
+ */
60
+ export function mayApplyRetainedInbound(state) {
61
+ return state === S.stable || state === S.recovering;
62
+ }
63
+ /** Whether fork detection may run (only from settled `Stable` canonical state). */
64
+ export function mayRunForkDetection(state) {
65
+ return state === S.stable;
66
+ }
@@ -0,0 +1,37 @@
1
+ /** @module @category Core - Group Members */
2
+ import { ClientState, Credential, LeafNode } from "ts-mls";
3
+ /**
4
+ * Gets all the nostr pubkey keys in a group.
5
+ *
6
+ * WR-15: a leaf whose identity is not a valid 32-byte hex key is SKIPPED, not
7
+ * thrown on. Filtering on `credentialType` alone is not enough — a basic
8
+ * credential can still carry a malformed identity, and `getCredentialPubkey`
9
+ * throws for one. `marmotAuthService.validateCredential` gates identities on
10
+ * the inbound path, but a state hydrated from a Welcome or a `ratchet_tree`
11
+ * extension is not covered by that gate. Callers here (notably
12
+ * `deriveStateNotifications`, run per link of an applied rewind AFTER state
13
+ * has already advanced) treat this as an enumeration, so one unparseable leaf
14
+ * must not abort the whole enumeration — and such a leaf is not a valid
15
+ * Marmot member in the first place.
16
+ */
17
+ export declare function getGroupMemberPubkeys(state: ClientState): string[];
18
+ /** @deprecated Use {@link getGroupMemberPubkeys}. */
19
+ export declare const getGroupMembers: typeof getGroupMemberPubkeys;
20
+ /** Gets all leaf nodes for a given nostr pubkey in a group */
21
+ export declare function getPubkeyLeafNodes(state: ClientState, pubkey: string): LeafNode[];
22
+ /**
23
+ * Gets all leaf node indexes for a given nostr pubkey in a group.
24
+ *
25
+ * @param state - The ClientState to search
26
+ * @param pubkey - The nostr pubkey to find
27
+ * @returns Array of leaf node indexes (numbers) for the given pubkey
28
+ */
29
+ export declare function getPubkeyLeafNodeIndexes(state: ClientState, pubkey: string): number[];
30
+ /**
31
+ * Gets all leaf node indexes for a given credential in a group.
32
+ *
33
+ * @param state - The ClientState to search
34
+ * @param credential - The credential to find
35
+ * @returns Array of leaf node indexes (numbers) for the given credential
36
+ */
37
+ export declare function getCredentialLeafNodeIndexes(state: ClientState, credential: Credential): number[];
@@ -0,0 +1,99 @@
1
+ /** @module @category Core - Group Members */
2
+ import { defaultCredentialTypes, getGroupMembers as getMlsGroupMembers, nodeTypes, } from "ts-mls";
3
+ import { getCredentialPubkey, isSameCredential } from "./credential.js";
4
+ function nodeToLeafIndex(nodeIndex) {
5
+ // This matches ts-mls treemath: nodeToLeafIndex(nodeIndex) = nodeIndex / 2
6
+ // for leaf positions in the ratchet tree.
7
+ return Math.floor(nodeIndex / 2);
8
+ }
9
+ /**
10
+ * Gets all the nostr pubkey keys in a group.
11
+ *
12
+ * WR-15: a leaf whose identity is not a valid 32-byte hex key is SKIPPED, not
13
+ * thrown on. Filtering on `credentialType` alone is not enough — a basic
14
+ * credential can still carry a malformed identity, and `getCredentialPubkey`
15
+ * throws for one. `marmotAuthService.validateCredential` gates identities on
16
+ * the inbound path, but a state hydrated from a Welcome or a `ratchet_tree`
17
+ * extension is not covered by that gate. Callers here (notably
18
+ * `deriveStateNotifications`, run per link of an applied rewind AFTER state
19
+ * has already advanced) treat this as an enumeration, so one unparseable leaf
20
+ * must not abort the whole enumeration — and such a leaf is not a valid
21
+ * Marmot member in the first place.
22
+ */
23
+ export function getGroupMemberPubkeys(state) {
24
+ const pubkeys = new Set();
25
+ for (const leaf of getMlsGroupMembers(state)) {
26
+ if (leaf.credential.credentialType !== defaultCredentialTypes.basic)
27
+ continue;
28
+ try {
29
+ pubkeys.add(getCredentialPubkey(leaf.credential));
30
+ }
31
+ catch {
32
+ // Not a valid Marmot account identity — skip this leaf.
33
+ }
34
+ }
35
+ return Array.from(pubkeys);
36
+ }
37
+ /** @deprecated Use {@link getGroupMemberPubkeys}. */
38
+ export const getGroupMembers = getGroupMemberPubkeys;
39
+ /** Gets all leaf nodes for a given nostr pubkey in a group */
40
+ export function getPubkeyLeafNodes(state, pubkey) {
41
+ const leaves = [];
42
+ for (const node of state.ratchetTree) {
43
+ if (!node ||
44
+ node.nodeType !== nodeTypes.leaf ||
45
+ node.leaf.credential.credentialType !== defaultCredentialTypes.basic)
46
+ continue;
47
+ try {
48
+ if (getCredentialPubkey(node.leaf.credential) === pubkey)
49
+ leaves.push(node.leaf);
50
+ }
51
+ catch {
52
+ // Not a valid Marmot account identity — skip this leaf.
53
+ }
54
+ }
55
+ return leaves;
56
+ }
57
+ /**
58
+ * Gets all leaf node indexes for a given nostr pubkey in a group.
59
+ *
60
+ * @param state - The ClientState to search
61
+ * @param pubkey - The nostr pubkey to find
62
+ * @returns Array of leaf node indexes (numbers) for the given pubkey
63
+ */
64
+ export function getPubkeyLeafNodeIndexes(state, pubkey) {
65
+ const leafIndexes = [];
66
+ for (let nodeIndex = 0; nodeIndex < state.ratchetTree.length; nodeIndex++) {
67
+ const node = state.ratchetTree[nodeIndex];
68
+ if (node &&
69
+ node.nodeType === nodeTypes.leaf &&
70
+ node.leaf.credential.credentialType === defaultCredentialTypes.basic) {
71
+ try {
72
+ if (getCredentialPubkey(node.leaf.credential) === pubkey)
73
+ leafIndexes.push(Number(nodeToLeafIndex(nodeIndex)));
74
+ }
75
+ catch {
76
+ // Not a valid Marmot account identity — skip this leaf.
77
+ }
78
+ }
79
+ }
80
+ return leafIndexes;
81
+ }
82
+ /**
83
+ * Gets all leaf node indexes for a given credential in a group.
84
+ *
85
+ * @param state - The ClientState to search
86
+ * @param credential - The credential to find
87
+ * @returns Array of leaf node indexes (numbers) for the given credential
88
+ */
89
+ export function getCredentialLeafNodeIndexes(state, credential) {
90
+ const leafIndexes = [];
91
+ for (let nodeIndex = 0; nodeIndex < state.ratchetTree.length; nodeIndex++) {
92
+ const node = state.ratchetTree[nodeIndex];
93
+ if (node && node.nodeType === nodeTypes.leaf) {
94
+ if (isSameCredential(node.leaf.credential, credential))
95
+ leafIndexes.push(Number(nodeToLeafIndex(nodeIndex)));
96
+ }
97
+ }
98
+ return leafIndexes;
99
+ }
@@ -0,0 +1,42 @@
1
+ /** @module @category Core - Group Messages */
2
+ import { type MlsMessage, wireformats } from "ts-mls";
3
+ import type { GroupMessagePair } from "./group-message-crypto.js";
4
+ /**
5
+ * Orders group commits by the content-derived convergence key
6
+ * (`protocol-core/convergence.md`): by MLS source epoch ascending, then by the
7
+ * lower `commit_digest = SHA-256(MLS message bytes)`. For a same-epoch race the
8
+ * lowest commit digest wins.
9
+ *
10
+ * Transport arrival order, transport timestamps (`created_at`), and outer event
11
+ * ids MUST NOT participate in this ordering — every member computes the same
12
+ * order from the same MLS bytes, which is what makes convergence deterministic
13
+ * across implementations.
14
+ *
15
+ * @param commits - Array of commit message pairs to order
16
+ * @returns A new array ordered by the convergence key
17
+ */
18
+ export declare function sortGroupCommits(commits: GroupMessagePair[]): GroupMessagePair[];
19
+ /**
20
+ * Checks if a message is an application message (not a proposal or commit).
21
+ */
22
+ export declare function isApplicationMessage(pair: GroupMessagePair): pair is GroupMessagePair & {
23
+ message: MlsMessage & {
24
+ wireformat: typeof wireformats.mls_private_message;
25
+ };
26
+ };
27
+ /**
28
+ * Checks if a message is a commit message.
29
+ */
30
+ export declare function isCommitMessage(pair: GroupMessagePair): pair is GroupMessagePair & {
31
+ message: MlsMessage & {
32
+ wireformat: typeof wireformats.mls_private_message;
33
+ };
34
+ };
35
+ /**
36
+ * Checks if a message is a proposal message.
37
+ */
38
+ export declare function isProposalMessage(pair: GroupMessagePair): pair is GroupMessagePair & {
39
+ message: MlsMessage & {
40
+ wireformat: typeof wireformats.mls_private_message;
41
+ };
42
+ };
@@ -0,0 +1,57 @@
1
+ /** @module @category Core - Group Messages */
2
+ import { contentTypes, encode, mlsMessageEncoder, wireformats, } from "ts-mls";
3
+ import { commitDigest, compareCommitOrderingKeys, } from "./convergence.js";
4
+ /**
5
+ * Orders group commits by the content-derived convergence key
6
+ * (`protocol-core/convergence.md`): by MLS source epoch ascending, then by the
7
+ * lower `commit_digest = SHA-256(MLS message bytes)`. For a same-epoch race the
8
+ * lowest commit digest wins.
9
+ *
10
+ * Transport arrival order, transport timestamps (`created_at`), and outer event
11
+ * ids MUST NOT participate in this ordering — every member computes the same
12
+ * order from the same MLS bytes, which is what makes convergence deterministic
13
+ * across implementations.
14
+ *
15
+ * @param commits - Array of commit message pairs to order
16
+ * @returns A new array ordered by the convergence key
17
+ */
18
+ export function sortGroupCommits(commits) {
19
+ const keyed = commits.map((pair) => {
20
+ const sourceEpoch = pair.message.wireformat === wireformats.mls_private_message
21
+ ? Number(pair.message.privateMessage.epoch)
22
+ : 0;
23
+ const key = {
24
+ sourceEpoch,
25
+ // commit_digest is over the serialized MLS message bytes; ts-mls TLS
26
+ // encoding is canonical, so this matches the transmitted commit bytes.
27
+ commitDigest: commitDigest(encode(mlsMessageEncoder, pair.message)),
28
+ };
29
+ return { pair, key };
30
+ });
31
+ keyed.sort((a, b) => compareCommitOrderingKeys(a.key, b.key));
32
+ return keyed.map((entry) => entry.pair);
33
+ }
34
+ /**
35
+ * Checks if a message is an application message (not a proposal or commit).
36
+ */
37
+ export function isApplicationMessage(pair) {
38
+ if (pair.message.wireformat !== wireformats.mls_private_message)
39
+ return false;
40
+ return pair.message.privateMessage.contentType === contentTypes.application;
41
+ }
42
+ /**
43
+ * Checks if a message is a commit message.
44
+ */
45
+ export function isCommitMessage(pair) {
46
+ if (pair.message.wireformat !== wireformats.mls_private_message)
47
+ return false;
48
+ return pair.message.privateMessage.contentType === contentTypes.commit;
49
+ }
50
+ /**
51
+ * Checks if a message is a proposal message.
52
+ */
53
+ export function isProposalMessage(pair) {
54
+ if (pair.message.wireformat !== wireformats.mls_private_message)
55
+ return false;
56
+ return pair.message.privateMessage.contentType === contentTypes.proposal;
57
+ }
@@ -0,0 +1,53 @@
1
+ /** @module @category Core - Group Messages */
2
+ import { NostrEvent } from "../utils/nostr.js";
3
+ import { ClientState, CiphersuiteImpl, type MlsMessage } from "ts-mls";
4
+ /**
5
+ * Reads a {@link NostrEvent} and returns the {@link MlsMessage} it contains.
6
+ * Decrypts group-event encrypted content using the exporter_secret from the group state.
7
+ *
8
+ * @param message - The Nostr event containing the encrypted MLS message
9
+ * @param clientState - The ClientState for the group (to get exporter_secret)
10
+ * @param ciphersuite - The ciphersuite implementation
11
+ * @returns The decoded MlsMessage
12
+ */
13
+ export declare function decryptGroupMessageEvent(message: NostrEvent, clientState: ClientState, ciphersuite: CiphersuiteImpl): Promise<MlsMessage>;
14
+ /**
15
+ * Encrypts the content of a group event using MIP-03.
16
+ *
17
+ * @returns The encrypted content
18
+ */
19
+ export declare function createEncryptedGroupEventContent({ state, ciphersuite, message, }: {
20
+ /** The ClientState for the group (to get exporter_secret) */
21
+ state: ClientState;
22
+ /** The ciphersuite implementation */
23
+ ciphersuite: CiphersuiteImpl;
24
+ /** The MLS message to encrypt */
25
+ message: MlsMessage;
26
+ }): Promise<string>;
27
+ export type GroupMessagePair = {
28
+ event: NostrEvent;
29
+ message: MlsMessage;
30
+ };
31
+ /**
32
+ * Decrypts a kind 445 event and returns the {@link MlsMessage} it contains.
33
+ *
34
+ * @param event - The Nostr event containing the encrypted MLS message
35
+ * @param clientState - The ClientState for the group (to get exporter_secret)
36
+ * @param ciphersuite - The ciphersuite implementation
37
+ * @returns The event and the decoded MlsMessage
38
+ */
39
+ export declare function decryptGroupMessage(event: NostrEvent, clientState: ClientState, ciphersuite: CiphersuiteImpl): Promise<GroupMessagePair>;
40
+ /**
41
+ * Decrypts multiple kind 445 events and returns the {@link MlsMessage} they contain.
42
+ *
43
+ * `read` and `unreadable` preserve the input order of `events`.
44
+ *
45
+ * @param events - The Nostr events containing the encrypted MLS messages
46
+ * @param clientState - The ClientState for the group (to get exporter_secret)
47
+ * @param ciphersuite - The ciphersuite implementation
48
+ * @returns An array of event and decoded MlsMessage pairs
49
+ */
50
+ export declare function decryptGroupMessages(events: NostrEvent[], clientState: ClientState, ciphersuite: CiphersuiteImpl): Promise<{
51
+ read: GroupMessagePair[];
52
+ unreadable: NostrEvent[];
53
+ }>;