@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,116 @@
1
+ import { getMarmotGroupInfo } from "./client-state.js";
2
+ import { getCredentialPubkey } from "./credential.js";
3
+ import { AGENT_TEXT_STREAM_QUIC_FANOUT_EXTENSION_TYPE, AGENT_TEXT_STREAM_QUIC_RECEIVE_EXTENSION_TYPE, AGENT_TEXT_STREAM_QUIC_SEND_EXTENSION_TYPE, AGENT_TEXT_STREAM_ROLE_FANOUT, AGENT_TEXT_STREAM_ROLE_RECEIVE, AGENT_TEXT_STREAM_ROLE_SEND, } from "./components/agent-text-stream.js";
4
+ import { AGENT_TEXT_STREAM_QUIC_COMPONENT_ID } from "./components/ids.js";
5
+ import { getKeyPackage } from "./key-package-event.js";
6
+ import { isLifetimeCurrentWithGrace, isLifetimeWithinCap, } from "../utils/timestamp.js";
7
+ /**
8
+ * MLS `required_capabilities` GroupContext extension type (code point `0x0003`).
9
+ * A LeafNode added to the group MUST advertise every extension/proposal/credential
10
+ * listed here (capability-negotiation.md "enforce on add").
11
+ */
12
+ const REQUIRED_CAPABILITIES_EXTENSION_TYPE = 0x0003;
13
+ /**
14
+ * Maps each agent-text-stream-QUIC `required_member_roles` bit to the LeafNode
15
+ * capability (extension type) a KeyPackage must advertise to satisfy it. A group
16
+ * whose policy requires a role rejects any KeyPackage missing the marker
17
+ * (agent-text-stream-quic-v1.md `do_send_invite`).
18
+ */
19
+ const ROLE_CAPABILITIES = [
20
+ {
21
+ bit: AGENT_TEXT_STREAM_ROLE_RECEIVE,
22
+ extension: AGENT_TEXT_STREAM_QUIC_RECEIVE_EXTENSION_TYPE,
23
+ name: "receive",
24
+ },
25
+ {
26
+ bit: AGENT_TEXT_STREAM_ROLE_SEND,
27
+ extension: AGENT_TEXT_STREAM_QUIC_SEND_EXTENSION_TYPE,
28
+ name: "send",
29
+ },
30
+ {
31
+ bit: AGENT_TEXT_STREAM_ROLE_FANOUT,
32
+ extension: AGENT_TEXT_STREAM_QUIC_FANOUT_EXTENSION_TYPE,
33
+ name: "fanout",
34
+ },
35
+ ];
36
+ function codePointHex(value) {
37
+ return `0x${value.toString(16).padStart(4, "0")}`;
38
+ }
39
+ /**
40
+ * Evaluates whether a candidate's KeyPackage event (kind 30443) can be added to a
41
+ * group, against every Marmot add requirement: cipher-suite match, the group's
42
+ * `required_capabilities` (extension/proposal/credential types), the
43
+ * agent-text-stream-QUIC `required_member_roles` policy, and whether the
44
+ * KeyPackage's account is already a member.
45
+ *
46
+ * This is the eligibility logic an app needs before sending an invite — the
47
+ * library's {@link createInviteIntent} only checks the credential identity. A
48
+ * `reasons` array of length 0 means the KeyPackage is safe to add; a non-empty
49
+ * array explains every failing requirement. Never throws: an undecodable
50
+ * KeyPackage yields `eligible: false` with an `undecodable: …` reason.
51
+ *
52
+ * @param state - The local group state to evaluate against (`group.state`).
53
+ * @param keyPackageEvent - The invitee's kind-30443 KeyPackage event.
54
+ */
55
+ export function evaluateKeyPackageForGroup(state, keyPackageEvent) {
56
+ const info = getMarmotGroupInfo(state);
57
+ const members = new Set(info.members.pubkeys);
58
+ const groupCipherSuite = state.groupContext.cipherSuite;
59
+ const requiredExtension = state.groupContext.extensions.find((extension) => extension.extensionType === REQUIRED_CAPABILITIES_EXTENSION_TYPE);
60
+ const required = requiredExtension?.extensionData;
61
+ const policy = info.app.components.find((component) => component.id === AGENT_TEXT_STREAM_QUIC_COMPONENT_ID)?.decoded;
62
+ const requiredRoles = policy?.requiredMemberRoles ?? 0;
63
+ const reasons = [];
64
+ let alreadyMember = false;
65
+ let cipherSuite = -1;
66
+ try {
67
+ const keyPackage = getKeyPackage(keyPackageEvent);
68
+ cipherSuite = keyPackage.cipherSuite;
69
+ const memberPubkey = getCredentialPubkey(keyPackage.leafNode.credential);
70
+ if (members.has(memberPubkey)) {
71
+ alreadyMember = true;
72
+ reasons.push("already a member");
73
+ }
74
+ if (keyPackage.cipherSuite !== groupCipherSuite) {
75
+ reasons.push(`cipher suite ${codePointHex(keyPackage.cipherSuite)} ≠ group ${codePointHex(groupCipherSuite)}`);
76
+ }
77
+ const capabilities = keyPackage.leafNode.capabilities;
78
+ if (required) {
79
+ for (const type of required.extensionTypes ?? [])
80
+ if (!capabilities.extensions.includes(type))
81
+ reasons.push(`missing extension ${codePointHex(type)}`);
82
+ for (const type of required.proposalTypes ?? [])
83
+ if (!capabilities.proposals.includes(type))
84
+ reasons.push(`missing proposal ${codePointHex(type)}`);
85
+ for (const type of required.credentialTypes ?? [])
86
+ if (!capabilities.credentials.includes(type))
87
+ reasons.push(`missing credential ${codePointHex(type)}`);
88
+ }
89
+ for (const role of ROLE_CAPABILITIES) {
90
+ if (requiredRoles & role.bit &&
91
+ !capabilities.extensions.includes(role.extension)) {
92
+ reasons.push(`missing ${role.name} role ${codePointHex(role.extension)}`);
93
+ }
94
+ }
95
+ // WIRE-01 (defense-in-depth): reject an over-long or expired Lifetime,
96
+ // mirroring the hard-reject boundary at KeyPackageManager.track()/
97
+ // createInviteIntent() so a caller invoking this evaluator directly
98
+ // cannot bypass the cap/current check (RESEARCH A2).
99
+ const lifetime = keyPackage.leafNode.lifetime;
100
+ if (!isLifetimeWithinCap(lifetime)) {
101
+ reasons.push("KeyPackage lifetime range exceeds the 7,261,200s cap");
102
+ }
103
+ else if (!isLifetimeCurrentWithGrace(lifetime)) {
104
+ reasons.push("KeyPackage lifetime is not current (outside ~1h grace)");
105
+ }
106
+ }
107
+ catch (err) {
108
+ reasons.push(`undecodable: ${err instanceof Error ? err.message : String(err)}`);
109
+ }
110
+ return {
111
+ eligible: reasons.length === 0,
112
+ alreadyMember,
113
+ cipherSuite,
114
+ reasons,
115
+ };
116
+ }
@@ -0,0 +1,43 @@
1
+ /** @module @category Core - Key Package Event */
2
+ import { NostrEvent } from "../utils/nostr.js";
3
+ import { CiphersuiteId, KeyPackage, Lifetime } from "ts-mls";
4
+ import { KeyPackageClient, MLS_VERSIONS } from "./protocol.js";
5
+ /** Get the KeyPackage from a kind 30443 event */
6
+ export declare function getKeyPackage(event: NostrEvent): KeyPackage;
7
+ /**
8
+ * Reads the inbound MLS `Lifetime` ({@link Lifetime}) from a kind 30443
9
+ * event's decoded KeyPackage leaf node (WIRE-01 inbound read). Returns
10
+ * `undefined` when the event cannot be decoded as a KeyPackage — never
11
+ * throws, matching the project's typed-reject convention for boundary
12
+ * readers (D-08).
13
+ */
14
+ export declare function getKeyPackageLifetime(event: NostrEvent): Lifetime | undefined;
15
+ /** Gets the MLS protocol version from a kind 30443 event */
16
+ export declare function getKeyPackageMLSVersion(event: NostrEvent): MLS_VERSIONS | undefined;
17
+ /** Gets the MLS cipher suite from a kind 30443 event */
18
+ export declare function getKeyPackageCipherSuiteId(event: NostrEvent): CiphersuiteId | undefined;
19
+ /** Gets the MLS extensions for a kind 30443 event */
20
+ export declare function getKeyPackageExtensions(event: NostrEvent): number[] | undefined;
21
+ /** Gets the relays for a kind 30443 event */
22
+ export declare function getKeyPackageRelays(event: NostrEvent): string[] | undefined;
23
+ /** Gets the client for a kind 30443 event */
24
+ export declare function getKeyPackageClient(event: NostrEvent): KeyPackageClient | undefined;
25
+ /**
26
+ * Gets the addressable slot identifier (`d` tag) from a kind 30443 event.
27
+ */
28
+ export declare function getKeyPackageIdentifier(event: NostrEvent): string | undefined;
29
+ /**
30
+ * Gets the nostr public key from a key package event.
31
+ *
32
+ * @param event - The key package event (kind 30443)
33
+ * @returns The nostr public key (hex string)
34
+ * @throws Error if the credential is not a basic credential
35
+ */
36
+ export declare function getKeyPackageNostrPubkey(event: NostrEvent): string;
37
+ /**
38
+ * Returns the KeyPackageRef (MIP-00 `i` tag value) from a kind 30443
39
+ * KeyPackage event.
40
+ *
41
+ * Per MIP-00, KeyPackage events MUST include this tag.
42
+ */
43
+ export declare function getKeyPackageReference(event: NostrEvent): string | undefined;
@@ -0,0 +1,118 @@
1
+ import { ciphersuites, decode, defaultCredentialTypes, mlsMessageDecoder, wireformats, } from "ts-mls";
2
+ import { decodeContent } from "../utils/encoding.js";
3
+ import { getTagValue } from "../utils/nostr.js";
4
+ import { isValidRelayUrl, normalizeRelayUrl } from "../utils/relay-url.js";
5
+ import { getCredentialPubkey } from "./credential.js";
6
+ import { ADDRESSABLE_KEY_PACKAGE_KIND, KEY_PACKAGE_CIPHER_SUITE_TAG, KEY_PACKAGE_CLIENT_TAG, KEY_PACKAGE_EXTENSIONS_TAG, KEY_PACKAGE_MLS_VERSION_TAG, KEY_PACKAGE_RELAYS_TAG, } from "./protocol.js";
7
+ /** Get the KeyPackage from a kind 30443 event */
8
+ export function getKeyPackage(event) {
9
+ // Transport byte encoding is always standard base64; the spec forbids an
10
+ // `encoding` tag and forbids switching decoders based on one
11
+ // (transports/nostr.md "Transport byte encoding").
12
+ const content = decodeContent(event.content, "base64");
13
+ // The spec frames kind-30443 content as an MLSMessage with wire_format
14
+ // mls_key_package (transports/nostr.md), a 4-byte header (ProtocolVersion
15
+ // 00 01 + WireFormat 00 05) ahead of the inner KeyPackage. This mirrors the
16
+ // kind-444 welcome framing and is what the darkmatter reference engine emits.
17
+ // We only accept this framed form — bare KeyPackage content is not spec
18
+ // conformant and is rejected.
19
+ const message = decode(mlsMessageDecoder, content);
20
+ if (!message)
21
+ throw new Error("Failed to decode key package event content");
22
+ if (message.wireformat !== wireformats.mls_key_package)
23
+ throw new Error(`Expected MLSMessage with mls_key_package wireformat, got wireformat ${message.wireformat}`);
24
+ return message.keyPackage;
25
+ }
26
+ /**
27
+ * Reads the inbound MLS `Lifetime` ({@link Lifetime}) from a kind 30443
28
+ * event's decoded KeyPackage leaf node (WIRE-01 inbound read). Returns
29
+ * `undefined` when the event cannot be decoded as a KeyPackage — never
30
+ * throws, matching the project's typed-reject convention for boundary
31
+ * readers (D-08).
32
+ */
33
+ export function getKeyPackageLifetime(event) {
34
+ try {
35
+ return getKeyPackage(event).leafNode.lifetime;
36
+ }
37
+ catch {
38
+ return undefined;
39
+ }
40
+ }
41
+ /** Gets the MLS protocol version from a kind 30443 event */
42
+ export function getKeyPackageMLSVersion(event) {
43
+ const version = getTagValue(event, KEY_PACKAGE_MLS_VERSION_TAG);
44
+ return version;
45
+ }
46
+ /** Gets the MLS cipher suite from a kind 30443 event */
47
+ export function getKeyPackageCipherSuiteId(event) {
48
+ const cipherSuite = getTagValue(event, KEY_PACKAGE_CIPHER_SUITE_TAG);
49
+ if (!cipherSuite)
50
+ return undefined;
51
+ const id = parseInt(cipherSuite);
52
+ // Verify that cipher suite is a valid ID
53
+ if (!Object.values(ciphersuites).includes(id)) {
54
+ throw new Error(`Invalid MLS cipher suite ID ${id}`);
55
+ }
56
+ return id;
57
+ }
58
+ /** Gets the MLS extensions for a kind 30443 event */
59
+ export function getKeyPackageExtensions(event) {
60
+ const tag = event.tags.find((t) => t[0] === KEY_PACKAGE_EXTENSIONS_TAG);
61
+ if (!tag)
62
+ return undefined;
63
+ const ids = tag
64
+ .slice(1)
65
+ // NOTE: we are intentially not passing a radix to parseInt here so that it can handle base 10 and 16 (with leading 0x)
66
+ .map((t) => parseInt(t))
67
+ .filter((id) => Number.isFinite(id));
68
+ return ids;
69
+ }
70
+ /** Gets the relays for a kind 30443 event */
71
+ export function getKeyPackageRelays(event) {
72
+ const tag = event.tags.find((t) => t[0] === KEY_PACKAGE_RELAYS_TAG);
73
+ if (!tag)
74
+ return;
75
+ return tag.slice(1).filter(isValidRelayUrl).map(normalizeRelayUrl);
76
+ }
77
+ /** Gets the client for a kind 30443 event */
78
+ export function getKeyPackageClient(event) {
79
+ const tag = event.tags.find((t) => t[0] === KEY_PACKAGE_CLIENT_TAG);
80
+ if (!tag)
81
+ return undefined;
82
+ // TODO: parse the rest of the client tag
83
+ return {
84
+ name: tag[1],
85
+ };
86
+ }
87
+ /**
88
+ * Gets the addressable slot identifier (`d` tag) from a kind 30443 event.
89
+ */
90
+ export function getKeyPackageIdentifier(event) {
91
+ if (event.kind !== ADDRESSABLE_KEY_PACKAGE_KIND)
92
+ return undefined;
93
+ return getTagValue(event, "d");
94
+ }
95
+ /**
96
+ * Gets the nostr public key from a key package event.
97
+ *
98
+ * @param event - The key package event (kind 30443)
99
+ * @returns The nostr public key (hex string)
100
+ * @throws Error if the credential is not a basic credential
101
+ */
102
+ export function getKeyPackageNostrPubkey(event) {
103
+ const keyPackage = getKeyPackage(event);
104
+ if (keyPackage.leafNode.credential.credentialType !==
105
+ defaultCredentialTypes.basic) {
106
+ throw new Error("Key package does not use a basic credential, cannot get nostr public key");
107
+ }
108
+ return getCredentialPubkey(keyPackage.leafNode.credential);
109
+ }
110
+ /**
111
+ * Returns the KeyPackageRef (MIP-00 `i` tag value) from a kind 30443
112
+ * KeyPackage event.
113
+ *
114
+ * Per MIP-00, KeyPackage events MUST include this tag.
115
+ */
116
+ export function getKeyPackageReference(event) {
117
+ return getTagValue(event, "i");
118
+ }
@@ -0,0 +1,16 @@
1
+ /** @module @category Core - Key Package Event */
2
+ import { EventTemplate, NostrEvent } from "../utils/nostr.js";
3
+ export type DeleteKeyPackageEventInput = string | NostrEvent;
4
+ export type CreateDeleteKeyPackageEventOptions = {
5
+ /** List of event ids (or full events) to delete */
6
+ events: DeleteKeyPackageEventInput[];
7
+ };
8
+ /**
9
+ * Creates a NIP-09 delete event (kind 5) to delete one or more KeyPackage
10
+ * events (kind 30443).
11
+ *
12
+ * Both an `e` tag (event id) and an `a` tag (addressable coordinate) are
13
+ * included so relays can match either way. String-only inputs produce only an
14
+ * `e` tag since no pubkey/d is available.
15
+ */
16
+ export declare function createDeleteKeyPackageEvent(options: CreateDeleteKeyPackageEventOptions): EventTemplate;
@@ -0,0 +1,46 @@
1
+ import { unixNow } from "../utils/nostr.js";
2
+ import { ADDRESSABLE_KEY_PACKAGE_KIND } from "./protocol.js";
3
+ import { getKeyPackageIdentifier } from "./key-package-event-decode.js";
4
+ /**
5
+ * Creates a NIP-09 delete event (kind 5) to delete one or more KeyPackage
6
+ * events (kind 30443).
7
+ *
8
+ * Both an `e` tag (event id) and an `a` tag (addressable coordinate) are
9
+ * included so relays can match either way. String-only inputs produce only an
10
+ * `e` tag since no pubkey/d is available.
11
+ */
12
+ export function createDeleteKeyPackageEvent(options) {
13
+ const { events } = options;
14
+ if (!events || events.length === 0) {
15
+ throw new Error("At least one event must be provided for deletion");
16
+ }
17
+ const eTags = [];
18
+ const aTags = [];
19
+ for (const e of events) {
20
+ if (typeof e === "string") {
21
+ // String id only — no kind info available, emit e tag without k inference
22
+ eTags.push(["e", e]);
23
+ }
24
+ else {
25
+ if (e.kind !== ADDRESSABLE_KEY_PACKAGE_KIND) {
26
+ throw new Error(`Event ${e.id} is not a key package event (kind ${e.kind} instead of ${ADDRESSABLE_KEY_PACKAGE_KIND})`);
27
+ }
28
+ eTags.push(["e", e.id]);
29
+ const identifier = getKeyPackageIdentifier(e);
30
+ if (identifier !== undefined) {
31
+ aTags.push([
32
+ "a",
33
+ `${ADDRESSABLE_KEY_PACKAGE_KIND}:${e.pubkey}:${identifier}`,
34
+ ]);
35
+ }
36
+ }
37
+ }
38
+ // All KeyPackage events are kind 30443.
39
+ const kTags = [["k", String(ADDRESSABLE_KEY_PACKAGE_KIND)]];
40
+ return {
41
+ kind: 5,
42
+ created_at: unixNow(),
43
+ content: "",
44
+ tags: [...kTags, ...eTags, ...aTags],
45
+ };
46
+ }
@@ -0,0 +1,28 @@
1
+ import { EventTemplate } from "../utils/nostr.js";
2
+ import { KeyPackage } from "ts-mls";
3
+ export type CreateKeyPackageEventOptions = {
4
+ keyPackage: KeyPackage;
5
+ /**
6
+ * The addressable slot identifier (`d` tag value). Required — callers must
7
+ * supply this; {@link KeyPackageManager} handles defaulting to `clientId` or
8
+ * throwing {@link MissingSlotIdentifierError} when none is available.
9
+ */
10
+ identifier: string;
11
+ /** Relay URLs to advertise in the event */
12
+ relays?: string[];
13
+ client?: string;
14
+ /**
15
+ * Whether to include the NIP-70 protected tag (["-"]).
16
+ *
17
+ * Per MIP-00 this SHOULD be omitted by default because many relays reject
18
+ * protected events.
19
+ */
20
+ protected?: boolean;
21
+ };
22
+ /**
23
+ * Creates an addressable key package event (kind 30443) from a key package.
24
+ *
25
+ * @param options - The options for creating the key package event
26
+ * @returns The unsigned key package event template
27
+ */
28
+ export declare function createKeyPackageEvent(options: CreateKeyPackageEventOptions): Promise<EventTemplate>;
@@ -0,0 +1,117 @@
1
+ /** @module @category Core - Key Package Event */
2
+ import { bytesToHex } from "@noble/hashes/utils.js";
3
+ import { encode, mlsMessageEncoder, protocolVersions, wireformats, } from "ts-mls";
4
+ import { encodeContent } from "../utils/encoding.js";
5
+ import { unixNow } from "../utils/nostr.js";
6
+ import { isValidRelayUrl, normalizeRelayUrl } from "../utils/relay-url.js";
7
+ import { isGreaseValue } from "./grease.js";
8
+ import { calculateKeyPackageRef } from "./key-package.js";
9
+ import { ADDRESSABLE_KEY_PACKAGE_KIND, KEY_PACKAGE_APP_COMPONENTS_TAG, KEY_PACKAGE_CIPHER_SUITE_TAG, KEY_PACKAGE_CLIENT_TAG, KEY_PACKAGE_EXTENSIONS_TAG, KEY_PACKAGE_MLS_VERSION_TAG, KEY_PACKAGE_PROPOSALS_TAG, KEY_PACKAGE_RELAYS_TAG, } from "./protocol.js";
10
+ import { PRIVATE_USE_APP_COMPONENT_ID_START, SUPPORTED_APP_COMPONENT_IDS } from "./components/ids.js";
11
+ import { leafAppComponents, leafProofForm } from "./protocol-profile.js";
12
+ /**
13
+ * Creates an addressable key package event (kind 30443) from a key package.
14
+ *
15
+ * @param options - The options for creating the key package event
16
+ * @returns The unsigned key package event template
17
+ */
18
+ export function createKeyPackageEvent(options) {
19
+ return createKeyPackageEventInternal(options);
20
+ }
21
+ async function createKeyPackageEventInternal(options) {
22
+ const { keyPackage, relays, client } = options;
23
+ // Publish the KeyPackage wrapped in an MLSMessage with wire_format
24
+ // mls_key_package (RFC 9420 §6). The kind-30443 content is specified as the
25
+ // serialized MLSMessage bytes (transports/nostr.md), mirroring the kind-444
26
+ // welcome framing, and this is what the darkmatter reference engine and
27
+ // deployed clients (e.g. White Noise) publish and expect. getKeyPackage
28
+ // still tolerates a bare KeyPackage on read for backwards compatibility.
29
+ const mlsMessage = {
30
+ version: protocolVersions.mls10,
31
+ wireformat: wireformats.mls_key_package,
32
+ keyPackage,
33
+ };
34
+ const encodedBytes = encode(mlsMessageEncoder, mlsMessage);
35
+ const content = encodeContent(encodedBytes, "base64");
36
+ // Get the cipher suite from the key package
37
+ // ts-mls v2: keyPackage.cipherSuite is a numeric id already
38
+ const ciphersuiteHex = `0x${keyPackage.cipherSuite
39
+ .toString(16)
40
+ .padStart(4, "0")}`;
41
+ // Extract extension types from the key package extensions
42
+ const extensionTypes = keyPackage.extensions.map((ext) => {
43
+ // Extension type is now always a number in v2
44
+ return `0x${ext.extensionType.toString(16).padStart(4, "0")}`;
45
+ });
46
+ // Also include extensions from leaf node capabilities to signal support
47
+ // This ensures Marmot Group Data Extension (0xf2ee) is included in the event
48
+ if (keyPackage.leafNode.capabilities?.extensions) {
49
+ for (const extType of keyPackage.leafNode.capabilities.extensions) {
50
+ // Only add if not already present (avoid duplicates)
51
+ const hexValue = `0x${extType.toString(16).padStart(4, "0")}`;
52
+ if (!extensionTypes.includes(hexValue)) {
53
+ extensionTypes.push(hexValue);
54
+ }
55
+ }
56
+ }
57
+ // Filter out GREASE values from the extension types
58
+ // We only want to include actual extensions (last_resort and Marmot Group Data Extension)
59
+ const filteredExtensionTypes = extensionTypes.filter((hexValue) => {
60
+ // Parse the hex value back to number to check if it's a GREASE value
61
+ const extType = parseInt(hexValue);
62
+ return !isGreaseValue(extType);
63
+ });
64
+ // Get the protocol version - keyPackage.version is a numeric ProtocolVersionValue
65
+ // NIP tag expects a display string like "1.0".
66
+ const versionName = Object.keys(protocolVersions).find((k) => protocolVersions[k] === keyPackage.version);
67
+ const version = versionName === "mls10" ? "1.0" : String(keyPackage.version);
68
+ const keyPackageRef = await calculateKeyPackageRef(keyPackage);
69
+ // Build tags in the canonical MDK publisher order.
70
+ const tags = [];
71
+ // NIP-70: protected event — relay must not serve this event to non-authors.
72
+ // NOTE: Optional/opt-in because many popular relays reject protected events.
73
+ if (options.protected)
74
+ tags.push(["-"]);
75
+ // Addressable identifier (required for kind 30443)
76
+ tags.push(["d", options.identifier]);
77
+ // Supported MLS proposal ids advertised by this leaf (e.g. app_data_update
78
+ // 0x0008), formatted as lowercase 0x-prefixed hex; GREASE values dropped.
79
+ const proposalTypes = (keyPackage.leafNode.capabilities?.proposals ?? [])
80
+ .filter((p) => !isGreaseValue(p))
81
+ .map((p) => `0x${p.toString(16).padStart(4, "0")}`);
82
+ // A Current-form leaf (epic marmot-mdk-interop S7, spec DD-7): the private-use
83
+ // app-component ids the leaf itself advertises in its `app_components`
84
+ // (`0x0001`) list — what MDK's KeyPackage metadata reads and its kind-30443
85
+ // tag check compares against exactly. Any other leaf keeps the previous
86
+ // advertisement (SUPPORTED_APP_COMPONENT_IDS), byte for byte.
87
+ let leafListed;
88
+ try {
89
+ leafListed = leafProofForm(keyPackage.leafNode) === "current" ? leafAppComponents(keyPackage.leafNode) : undefined;
90
+ }
91
+ catch {
92
+ leafListed = undefined;
93
+ }
94
+ const appComponentIds = (leafListed?.filter((id) => id >= PRIVATE_USE_APP_COMPONENT_ID_START) ??
95
+ SUPPORTED_APP_COMPONENT_IDS).map((id) => `0x${id.toString(16).padStart(4, "0")}`);
96
+ // The spec forbids an `encoding` tag (transports/nostr.md "Transport byte
97
+ // encoding"); content is always standard base64.
98
+ tags.push([KEY_PACKAGE_MLS_VERSION_TAG, version], ["i", bytesToHex(keyPackageRef)], [KEY_PACKAGE_CIPHER_SUITE_TAG, ciphersuiteHex],
99
+ // A Current-form leaf's lists go out ascending, as MDK publishes its own (BTreeSet order; equal-width lowercase hex).
100
+ [KEY_PACKAGE_EXTENSIONS_TAG, ...(leafListed === undefined ? filteredExtensionTypes : [...filteredExtensionTypes].sort())], [KEY_PACKAGE_PROPOSALS_TAG, ...(leafListed === undefined ? proposalTypes : [...proposalTypes].sort())], [KEY_PACKAGE_APP_COMPONENTS_TAG, ...appComponentIds]);
101
+ // Add client tag if provided
102
+ if (client)
103
+ tags.push([KEY_PACKAGE_CLIENT_TAG, client]);
104
+ // Add relay tags if provided
105
+ if (relays && relays.length > 0) {
106
+ const validRelays = relays.filter(isValidRelayUrl).map(normalizeRelayUrl);
107
+ if (validRelays.length > 0) {
108
+ tags.push([KEY_PACKAGE_RELAYS_TAG, ...validRelays]);
109
+ }
110
+ }
111
+ return {
112
+ kind: ADDRESSABLE_KEY_PACKAGE_KIND,
113
+ created_at: unixNow(),
114
+ content,
115
+ tags,
116
+ };
117
+ }
@@ -0,0 +1,4 @@
1
+ /** @module @category Core - Key Package Event */
2
+ export * from "./key-package-event-decode.js";
3
+ export * from "./key-package-event-encode.js";
4
+ export * from "./key-package-event-delete.js";
@@ -0,0 +1,8 @@
1
+ /** @module @category Core - Key Package Event */
2
+ // Engine-side reads: tag accessors + the MLSMessage-frame compat decode.
3
+ export * from "./key-package-event-decode.js";
4
+ // Adapter-side build: the kind-30443 event encoder (GREASE/extension/version
5
+ // munging + MLSMessage framing).
6
+ export * from "./key-package-event-encode.js";
7
+ // NIP-09 kind-5 delete builder for KeyPackage events.
8
+ export * from "./key-package-event-delete.js";
@@ -0,0 +1,66 @@
1
+ /** @module @category Core - Key Package */
2
+ import { Capabilities, Credential, CryptoProvider, CiphersuiteImpl, CustomExtension, KeyPackage, Lifetime, PrivateKeyPackage } from "ts-mls";
3
+ import { type AccountIdentityProofSigner } from "./account-identity-proof.js";
4
+ import { type CurrentProofProvider, type ProtocolProfile } from "./protocol-profile.js";
5
+ /**
6
+ * A complete key package containing both public and private components.
7
+ *
8
+ * The public package can be shared with others to add this participant to groups,
9
+ * while the private package must be kept secret and is used for decryption and signing.
10
+ */
11
+ export type CompleteKeyPackage = {
12
+ /** The public key package that can be shared with others */
13
+ publicPackage: KeyPackage;
14
+ /** The private key package that must be kept secret */
15
+ privatePackage: PrivateKeyPackage;
16
+ };
17
+ /** Create default extensions for a key package */
18
+ export declare function keyPackageDefaultExtensions(): CustomExtension[];
19
+ /**
20
+ * Reads whether a KeyPackage is marked reusable ("last resort"): the
21
+ * empty-data `0x0004` component inside its KeyPackage-level (not
22
+ * LeafNode-level) `app_data_dictionary` extension (AC-VENDOR-8).
23
+ *
24
+ * Deliberately reads `keyPackage.extensions` (the `KeyPackageTBS`-level
25
+ * field) rather than `keyPackage.leafNode.extensions` — the same component
26
+ * present only in the LeafNode-level dictionary does not count.
27
+ */
28
+ export declare function isLastResortKeyPackage(keyPackage: KeyPackage): boolean;
29
+ /** Calculates a key package reference with the hash implementation based on the key package's cipher suite */
30
+ export declare function calculateKeyPackageRef(keyPackage: KeyPackage, cryptoProvider?: CryptoProvider): Promise<Uint8Array>;
31
+ /** Options for generating a marmot key package */
32
+ export type GenerateKeyPackageOptions = {
33
+ credential: Credential;
34
+ capabilities?: Capabilities;
35
+ lifetime?: Lifetime;
36
+ extensions?: CustomExtension[];
37
+ /**
38
+ * Whether to mark this KeyPackage as reusable using the MLS `last_resort` extension.
39
+ *
40
+ * - `true`: include the `last_resort` KeyPackage extension (reusable; helps with race windows)
41
+ * - `false`: omit the extension (single-use; private init_key is expected to be consumed)
42
+ *
43
+ * Default: `true` for backwards compatibility with existing marmot-ts behavior.
44
+ */
45
+ isLastResort?: boolean;
46
+ /**
47
+ * Optional Nostr-account signer. When provided, the generated key package
48
+ * carries a `marmot.account-identity-proof.v1` LeafNode extension binding the
49
+ * credential's Nostr account to the leaf signature key — required for wire
50
+ * interop with darkmatter, which validates this proof on every leaf.
51
+ */
52
+ accountProofSigner?: AccountIdentityProofSigner;
53
+ /**
54
+ * The proof form (spec DD-7, `protocol-profile.ts`). `"legacy"` (the default): the `0xf2f1` LeafNode extension and
55
+ * {@link ensureMarmotCapabilities}, exactly as before profiles existed. `"current"`: the 104-byte proof as component
56
+ * `0x8009` in the leaf's `app_data_dictionary` (advertised in its `app_components`, with
57
+ * `CURRENT_PROFILE_LEAF_APP_COMPONENT_IDS`), no `0xf2f1` capability, no GREASE proposal type. A Current KeyPackage
58
+ * always carries a proof: {@link currentProof}, or else an `accountProofSigner` of the `{ signEvent }` shape.
59
+ */
60
+ profile?: ProtocolProfile;
61
+ /** The Current proof for the generated leaf key (`profile: "current"` only); see {@link CurrentProofProvider}. */
62
+ currentProof?: CurrentProofProvider;
63
+ ciphersuiteImpl: CiphersuiteImpl;
64
+ };
65
+ /** Generate a marmot key package that is compliant with MIP-00 */
66
+ export declare function generateKeyPackage({ credential, capabilities, lifetime, extensions, isLastResort, accountProofSigner, profile, currentProof, ciphersuiteImpl, }: GenerateKeyPackageOptions): Promise<CompleteKeyPackage>;