@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,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,102 @@
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 { SUPPORTED_APP_COMPONENT_IDS } from "./components/ids.js";
11
+ /**
12
+ * Creates an addressable key package event (kind 30443) from a key package.
13
+ *
14
+ * @param options - The options for creating the key package event
15
+ * @returns The unsigned key package event template
16
+ */
17
+ export function createKeyPackageEvent(options) {
18
+ return createKeyPackageEventInternal(options);
19
+ }
20
+ async function createKeyPackageEventInternal(options) {
21
+ const { keyPackage, relays, client } = options;
22
+ // Publish the KeyPackage wrapped in an MLSMessage with wire_format
23
+ // mls_key_package (RFC 9420 §6). The kind-30443 content is specified as the
24
+ // serialized MLSMessage bytes (transports/nostr.md), mirroring the kind-444
25
+ // welcome framing, and this is what the darkmatter reference engine and
26
+ // deployed clients (e.g. White Noise) publish and expect. getKeyPackage
27
+ // still tolerates a bare KeyPackage on read for backwards compatibility.
28
+ const mlsMessage = {
29
+ version: protocolVersions.mls10,
30
+ wireformat: wireformats.mls_key_package,
31
+ keyPackage,
32
+ };
33
+ const encodedBytes = encode(mlsMessageEncoder, mlsMessage);
34
+ const content = encodeContent(encodedBytes, "base64");
35
+ // Get the cipher suite from the key package
36
+ // ts-mls v2: keyPackage.cipherSuite is a numeric id already
37
+ const ciphersuiteHex = `0x${keyPackage.cipherSuite
38
+ .toString(16)
39
+ .padStart(4, "0")}`;
40
+ // Extract extension types from the key package extensions
41
+ const extensionTypes = keyPackage.extensions.map((ext) => {
42
+ // Extension type is now always a number in v2
43
+ return `0x${ext.extensionType.toString(16).padStart(4, "0")}`;
44
+ });
45
+ // Also include extensions from leaf node capabilities to signal support
46
+ // This ensures Marmot Group Data Extension (0xf2ee) is included in the event
47
+ if (keyPackage.leafNode.capabilities?.extensions) {
48
+ for (const extType of keyPackage.leafNode.capabilities.extensions) {
49
+ // Only add if not already present (avoid duplicates)
50
+ const hexValue = `0x${extType.toString(16).padStart(4, "0")}`;
51
+ if (!extensionTypes.includes(hexValue)) {
52
+ extensionTypes.push(hexValue);
53
+ }
54
+ }
55
+ }
56
+ // Filter out GREASE values from the extension types
57
+ // We only want to include actual extensions (last_resort and Marmot Group Data Extension)
58
+ const filteredExtensionTypes = extensionTypes.filter((hexValue) => {
59
+ // Parse the hex value back to number to check if it's a GREASE value
60
+ const extType = parseInt(hexValue);
61
+ return !isGreaseValue(extType);
62
+ });
63
+ // Get the protocol version - keyPackage.version is a numeric ProtocolVersionValue
64
+ // NIP tag expects a display string like "1.0".
65
+ const versionName = Object.keys(protocolVersions).find((k) => protocolVersions[k] === keyPackage.version);
66
+ const version = versionName === "mls10" ? "1.0" : String(keyPackage.version);
67
+ const keyPackageRef = await calculateKeyPackageRef(keyPackage);
68
+ // Build tags in the canonical MDK publisher order.
69
+ const tags = [];
70
+ // NIP-70: protected event — relay must not serve this event to non-authors.
71
+ // NOTE: Optional/opt-in because many popular relays reject protected events.
72
+ if (options.protected)
73
+ tags.push(["-"]);
74
+ // Addressable identifier (required for kind 30443)
75
+ tags.push(["d", options.identifier]);
76
+ // Supported MLS proposal ids advertised by this leaf (e.g. app_data_update
77
+ // 0x0008), formatted as lowercase 0x-prefixed hex; GREASE values dropped.
78
+ const proposalTypes = (keyPackage.leafNode.capabilities?.proposals ?? [])
79
+ .filter((p) => !isGreaseValue(p))
80
+ .map((p) => `0x${p.toString(16).padStart(4, "0")}`);
81
+ // Supported Marmot app-component ids this implementation can encode/decode.
82
+ const appComponentIds = SUPPORTED_APP_COMPONENT_IDS.map((id) => `0x${id.toString(16).padStart(4, "0")}`);
83
+ // The spec forbids an `encoding` tag (transports/nostr.md "Transport byte
84
+ // encoding"); content is always standard base64.
85
+ tags.push([KEY_PACKAGE_MLS_VERSION_TAG, version], ["i", bytesToHex(keyPackageRef)], [KEY_PACKAGE_CIPHER_SUITE_TAG, ciphersuiteHex], [KEY_PACKAGE_EXTENSIONS_TAG, ...filteredExtensionTypes], [KEY_PACKAGE_PROPOSALS_TAG, ...proposalTypes], [KEY_PACKAGE_APP_COMPONENTS_TAG, ...appComponentIds]);
86
+ // Add client tag if provided
87
+ if (client)
88
+ tags.push([KEY_PACKAGE_CLIENT_TAG, client]);
89
+ // Add relay tags if provided
90
+ if (relays && relays.length > 0) {
91
+ const validRelays = relays.filter(isValidRelayUrl).map(normalizeRelayUrl);
92
+ if (validRelays.length > 0) {
93
+ tags.push([KEY_PACKAGE_RELAYS_TAG, ...validRelays]);
94
+ }
95
+ }
96
+ return {
97
+ kind: ADDRESSABLE_KEY_PACKAGE_KIND,
98
+ created_at: unixNow(),
99
+ content,
100
+ tags,
101
+ };
102
+ }
@@ -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,55 @@
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
+ /**
5
+ * A complete key package containing both public and private components.
6
+ *
7
+ * The public package can be shared with others to add this participant to groups,
8
+ * while the private package must be kept secret and is used for decryption and signing.
9
+ */
10
+ export type CompleteKeyPackage = {
11
+ /** The public key package that can be shared with others */
12
+ publicPackage: KeyPackage;
13
+ /** The private key package that must be kept secret */
14
+ privatePackage: PrivateKeyPackage;
15
+ };
16
+ /** Create default extensions for a key package */
17
+ export declare function keyPackageDefaultExtensions(): CustomExtension[];
18
+ /**
19
+ * Reads whether a KeyPackage is marked reusable ("last resort"): the
20
+ * empty-data `0x0004` component inside its KeyPackage-level (not
21
+ * LeafNode-level) `app_data_dictionary` extension (AC-VENDOR-8).
22
+ *
23
+ * Deliberately reads `keyPackage.extensions` (the `KeyPackageTBS`-level
24
+ * field) rather than `keyPackage.leafNode.extensions` — the same component
25
+ * present only in the LeafNode-level dictionary does not count.
26
+ */
27
+ export declare function isLastResortKeyPackage(keyPackage: KeyPackage): boolean;
28
+ /** Calculates a key package reference with the hash implementation based on the key package's cipher suite */
29
+ export declare function calculateKeyPackageRef(keyPackage: KeyPackage, cryptoProvider?: CryptoProvider): Promise<Uint8Array>;
30
+ /** Options for generating a marmot key package */
31
+ export type GenerateKeyPackageOptions = {
32
+ credential: Credential;
33
+ capabilities?: Capabilities;
34
+ lifetime?: Lifetime;
35
+ extensions?: CustomExtension[];
36
+ /**
37
+ * Whether to mark this KeyPackage as reusable using the MLS `last_resort` extension.
38
+ *
39
+ * - `true`: include the `last_resort` KeyPackage extension (reusable; helps with race windows)
40
+ * - `false`: omit the extension (single-use; private init_key is expected to be consumed)
41
+ *
42
+ * Default: `true` for backwards compatibility with existing marmot-ts behavior.
43
+ */
44
+ isLastResort?: boolean;
45
+ /**
46
+ * Optional Nostr-account signer. When provided, the generated key package
47
+ * carries a `marmot.account-identity-proof.v1` LeafNode extension binding the
48
+ * credential's Nostr account to the leaf signature key — required for wire
49
+ * interop with darkmatter, which validates this proof on every leaf.
50
+ */
51
+ accountProofSigner?: AccountIdentityProofSigner;
52
+ ciphersuiteImpl: CiphersuiteImpl;
53
+ };
54
+ /** Generate a marmot key package that is compliant with MIP-00 */
55
+ export declare function generateKeyPackage({ credential, capabilities, lifetime, extensions, isLastResort, accountProofSigner, ciphersuiteImpl, }: GenerateKeyPackageOptions): Promise<CompleteKeyPackage>;
@@ -0,0 +1,115 @@
1
+ /** @module @category Core - Key Package */
2
+ import { defaultCredentialTypes, defaultCryptoProvider, getAppDataDictionary, generateKeyPackage as MLSGenerateKeyPackage, generateKeyPackageWithKey as MLSGenerateKeyPackageWithKey, makeKeyPackageRef, } from "ts-mls";
3
+ import { hexToBytes } from "@noble/hashes/utils.js";
4
+ import { createDefaultKeyPackageLifetime, isLifetimeWithinCap, } from "../utils/timestamp.js";
5
+ import { buildAccountIdentityProofExtension, } from "./account-identity-proof.js";
6
+ import { ensureMarmotCapabilities } from "./capabilities.js";
7
+ import { componentEntry, LAST_RESORT_COMPONENT_ID, makeAppComponentsExtension, makeLeafAppComponentsExtension, } from "./components/index.js";
8
+ import { getCredentialPubkey } from "./credential.js";
9
+ import { defaultCapabilities } from "./default-capabilities.js";
10
+ /**
11
+ * Ensures a KeyPackage-level extensions array carries the last-resort marker:
12
+ * the empty-data `0x0004` component inside the KeyPackage-level
13
+ * `app_data_dictionary` extension (AC-VENDOR-8 conformance patch — replaces
14
+ * the legacy standalone `last_resort` MLS extension, which upstream
15
+ * marmot-ts used before this port).
16
+ */
17
+ function ensureLastResortComponent(extensions) {
18
+ const existingDictionary = getAppDataDictionary(extensions);
19
+ if (existingDictionary?.some((c) => c.componentId === LAST_RESORT_COMPONENT_ID))
20
+ return extensions;
21
+ const entries = [
22
+ ...(existingDictionary ?? []),
23
+ componentEntry(LAST_RESORT_COMPONENT_ID, new Uint8Array(0)),
24
+ ];
25
+ const dictionaryExtension = makeAppComponentsExtension(entries);
26
+ const withoutOldDictionary = extensions.filter((e) => getAppDataDictionary([e]) === undefined);
27
+ return [...withoutOldDictionary, dictionaryExtension];
28
+ }
29
+ /** Create default extensions for a key package */
30
+ export function keyPackageDefaultExtensions() {
31
+ return ensureLastResortComponent([]);
32
+ }
33
+ /**
34
+ * Reads whether a KeyPackage is marked reusable ("last resort"): the
35
+ * empty-data `0x0004` component inside its KeyPackage-level (not
36
+ * LeafNode-level) `app_data_dictionary` extension (AC-VENDOR-8).
37
+ *
38
+ * Deliberately reads `keyPackage.extensions` (the `KeyPackageTBS`-level
39
+ * field) rather than `keyPackage.leafNode.extensions` — the same component
40
+ * present only in the LeafNode-level dictionary does not count.
41
+ */
42
+ export function isLastResortKeyPackage(keyPackage) {
43
+ let dictionary;
44
+ try {
45
+ dictionary = getAppDataDictionary(keyPackage.extensions);
46
+ }
47
+ catch {
48
+ return false;
49
+ }
50
+ return (dictionary?.some((c) => c.componentId === LAST_RESORT_COMPONENT_ID) ??
51
+ false);
52
+ }
53
+ /** Calculates a key package reference with the hash implementation based on the key package's cipher suite */
54
+ export async function calculateKeyPackageRef(keyPackage, cryptoProvider) {
55
+ const provider = cryptoProvider ?? defaultCryptoProvider;
56
+ const ciphersuiteImpl = await provider.getCiphersuiteImpl(keyPackage.cipherSuite);
57
+ return await makeKeyPackageRef(keyPackage, ciphersuiteImpl.hash);
58
+ }
59
+ /** Generate a marmot key package that is compliant with MIP-00 */
60
+ export async function generateKeyPackage({ credential, capabilities, lifetime, extensions, isLastResort = true, accountProofSigner, ciphersuiteImpl, }) {
61
+ if (credential.credentialType !== defaultCredentialTypes.basic)
62
+ throw new Error("Marmot key packages must use a basic credential");
63
+ // Ensure the credential has a valid pubkey
64
+ const accountPubkey = getCredentialPubkey(credential);
65
+ const resolvedCapabilities = capabilities
66
+ ? ensureMarmotCapabilities(capabilities)
67
+ : defaultCapabilities();
68
+ const resolvedLifetime = lifetime ?? createDefaultKeyPackageLifetime();
69
+ // WIRE-01 produce path: the cap must hold regardless of how lifetime is
70
+ // supplied. The default is always within cap, so this check only ever
71
+ // rejects an explicit caller-supplied `lifetime` override (D-09).
72
+ if (!isLifetimeWithinCap(resolvedLifetime))
73
+ throw new Error(`generateKeyPackage: lifetime range ${resolvedLifetime.notAfter - resolvedLifetime.notBefore}s exceeds the 7,261,200s (84-day) cap`);
74
+ // Marmot requires support for last_resort capability signaling (MIP-00),
75
+ // but individual KeyPackages may be single-use or last-resort reusable.
76
+ // `isLastResort` controls whether this KeyPackage is marked reusable.
77
+ const resolvedExtensions = isLastResort
78
+ ? ensureLastResortComponent(extensions ?? [])
79
+ : (extensions ?? []);
80
+ // Advertise the supported app components on the LeafNode so this member can
81
+ // be added to groups that require them (matches darkmatter's leaf state).
82
+ const leafNodeExtensions = [
83
+ makeLeafAppComponentsExtension(),
84
+ ];
85
+ // When an account signer is supplied, generate the leaf signature keypair
86
+ // first, bind it to the Nostr account with an identity proof, and carry the
87
+ // proof on the LeafNode (darkmatter validates this on every leaf).
88
+ if (accountProofSigner) {
89
+ const signatureKeyPair = await ciphersuiteImpl.signature.keygen();
90
+ leafNodeExtensions.push(await buildAccountIdentityProofExtension({
91
+ accountIdentity: hexToBytes(accountPubkey),
92
+ mlsSignaturePublicKey: signatureKeyPair.publicKey,
93
+ ciphersuite: ciphersuiteImpl.id,
94
+ signer: accountProofSigner,
95
+ }));
96
+ return await MLSGenerateKeyPackageWithKey({
97
+ credential,
98
+ capabilities: resolvedCapabilities,
99
+ lifetime: resolvedLifetime,
100
+ extensions: resolvedExtensions,
101
+ signatureKeyPair,
102
+ leafNodeExtensions,
103
+ cipherSuite: ciphersuiteImpl,
104
+ });
105
+ }
106
+ // In v2, generateKeyPackage takes a single params object
107
+ return await MLSGenerateKeyPackage({
108
+ credential,
109
+ capabilities: resolvedCapabilities,
110
+ lifetime: resolvedLifetime,
111
+ extensions: resolvedExtensions,
112
+ leafNodeExtensions,
113
+ cipherSuite: ciphersuiteImpl,
114
+ });
115
+ }
@@ -0,0 +1,83 @@
1
+ import type { ClientState } from "ts-mls";
2
+ /**
3
+ * Locally authored (not vendored from marmot-ts; listed in VENDOR.md's
4
+ * "Locally authored (not vendored)" section).
5
+ *
6
+ * Key succession: what a leaf's signature key did between two group states.
7
+ *
8
+ * A device can replace the signature key of its own leaf in a commit's UpdatePath
9
+ * (RFC 9420; `SendIntent.selfUpdate.leafNodePatch`) or, in principle, through a
10
+ * committed Update proposal. Every consumer that keys a member by its leaf signature
11
+ * key reads such a replacement as the leaf *disappearing*. {@link leafKeySuccessions}
12
+ * is the one place that tells a replacement of a key in place from a removal: a
13
+ * pure function of a parent and a child `ClientState`.
14
+ *
15
+ * A succession is reported for a leaf index when the leaf is occupied in both
16
+ * states by the same account (same basic credential identity) and carries a
17
+ * different signature key in the child, and the child's leaf was written by the
18
+ * leaf itself: its leaf node source is `commit` (the committer's UpdatePath leaf)
19
+ * or `update` (a committed Update proposal). A Remove plus an Add into the same
20
+ * index yields a `key_package` leaf and is never a succession, nor is a different
21
+ * account at the index, nor a blank index.
22
+ *
23
+ * Consumers:
24
+ * - the equivocation-credit lineage clause (ADR-016 D2 rule 4, `convergence.ts`):
25
+ * only the `commit` successions of the committing leaf itself along a candidate
26
+ * path extend which key of that leaf earns credit;
27
+ * - `epic-marmot-removal-finality` Design Decision 2: its key-difference evidence
28
+ * for "the leaf was removed" takes this predicate as the "a rotation is not a
29
+ * removal" exception when it ships (that epic is design only; this module is
30
+ * the exception it adopts);
31
+ * - `@941design/marmot` (`history/notifications.ts`): `removedLeaves` skips a
32
+ * same-account leaf at the same index iff this reports the index, and
33
+ * `rotatedLeaves` maps the entries to notifications.
34
+ *
35
+ * Precondition: `child` is exactly ONE commit after `parent` (the commit that
36
+ * produced `child` was applied to `parent`). The predicate compares two trees
37
+ * and cannot see what happened between them: over a gap of several commits a
38
+ * Remove plus re-Add of the same account at an index followed by a self-update
39
+ * leaves a `commit`-source leaf with a new key and reads as a rotation. Call it
40
+ * per edge of a window (consecutive states), never on a tip pair.
41
+ *
42
+ * Pure and total: the module imports nothing but `ts-mls` and `./credential.js`,
43
+ * reads no clock, random source or I/O, and never throws, whatever the trees hold
44
+ * (non-basic or malformed credentials, blank nodes, trees of unequal width).
45
+ */
46
+ /** One signature-key replacement of a leaf between a parent and a child state. */
47
+ export interface LeafKeySuccession {
48
+ /** The leaf index at which the key was replaced (the same in both states). */
49
+ readonly leafIndex: number;
50
+ /** Hex account pubkey: the (unchanged) basic-credential identity of the leaf. */
51
+ readonly account: string;
52
+ /** Hex signature public key the leaf held in the parent. */
53
+ readonly fromKey: string;
54
+ /** Hex signature public key the leaf holds in the child. */
55
+ readonly toKey: string;
56
+ /**
57
+ * How the child's leaf came about: `commit` (the committer's UpdatePath leaf, so
58
+ * the committer is the leaf itself) or `update` (a committed Update proposal; the
59
+ * committer may be any other leaf).
60
+ */
61
+ readonly source: "commit" | "update";
62
+ }
63
+ /**
64
+ * The signature-key successions between `parent` and `child`, ordered by leaf
65
+ * index: one entry for every leaf index occupied in both states by the same
66
+ * account whose signature key differs and whose child leaf has source `commit`
67
+ * or `update` (see the module header). Precondition: `child` is exactly one
68
+ * commit after `parent`; over a longer gap the result is NOT guaranteed (a Remove
69
+ * plus re-Add followed by a self-update reads as a rotation).
70
+ *
71
+ * Pure and total: never throws. Totality is per leaf, not per state: a leaf
72
+ * that cannot be read (missing or non-byte `signaturePublicKey`, non-basic or
73
+ * undecodable credential, unknown source) contributes no entry and leaves the
74
+ * other indices' verdicts untouched, so a malformed leaf never erases a
75
+ * genuine rotation elsewhere. This is deliberately NOT the whole-state `[]`
76
+ * reading: under ADR-017 R-1 an empty `succ(x)` would turn every other
77
+ * rotation on the edge into a positive removal fact, whereas R-1's fail-closed
78
+ * value is *absent*, which the removal-fact producer derives on its own when a
79
+ * leaf is unreadable. Only a state that is not a tree at all yields `[]`. Real
80
+ * ts-mls states cannot hold such leaves (`signaturePublicKey` is a required
81
+ * decoded `Uint8Array`); the guard exists for arbitrary input (AC-SUCC-4).
82
+ */
83
+ export declare function leafKeySuccessions(parent: ClientState, child: ClientState): readonly LeafKeySuccession[];