@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,52 @@
1
+ /** @module @category Core - Relay Lists */
2
+ import { NostrEvent, UnsignedEvent } from "../utils/nostr.js";
3
+ /** Optional NIP-65 read/write marker on an `r` tag. */
4
+ export type Nip65RelayUsage = "read" | "write";
5
+ /**
6
+ * Reads relay URLs from a NIP-65 (kind 10002) relay-list event.
7
+ *
8
+ * Each entry is an `r` tag: `["r", url]` (both read and write) or
9
+ * `["r", url, "read" | "write"]`. Pass `usage` to keep only relays usable for
10
+ * that direction; omit it to return every advertised relay (markerless `r`
11
+ * tags count as both directions).
12
+ *
13
+ * @param event - The kind 10002 event
14
+ * @param usage - Optional direction filter
15
+ * @returns Normalized, validated relay URLs
16
+ */
17
+ export declare function getNip65Relays(event: NostrEvent, usage?: Nip65RelayUsage): string[];
18
+ /** True for a kind 10002 event that advertises at least one valid relay. */
19
+ export declare function isValidNip65RelayListEvent(event: NostrEvent): boolean;
20
+ /** Options for {@link createNip65RelayListEvent}. */
21
+ export type CreateNip65RelayListEventOptions = {
22
+ /** The pubkey of the event author */
23
+ pubkey: string;
24
+ /** The relays the account publishes and fetches KeyPackages from */
25
+ relays: string[];
26
+ /** Optional NIP-65 marker applied to every relay (omit for read+write) */
27
+ usage?: Nip65RelayUsage;
28
+ };
29
+ /**
30
+ * Creates an unsigned NIP-65 (kind 10002) relay-list event. Marmot reads this
31
+ * list to discover an account's KeyPackage relays.
32
+ */
33
+ export declare function createNip65RelayListEvent(options: CreateNip65RelayListEventOptions): UnsignedEvent;
34
+ /**
35
+ * Reads relay URLs from an inbox (kind 10050) relay-list event. Each entry is a
36
+ * `relay` tag: `["relay", url]`.
37
+ */
38
+ export declare function getInboxRelays(event: NostrEvent): string[];
39
+ /** True for a kind 10050 event that advertises at least one valid relay. */
40
+ export declare function isValidInboxRelayListEvent(event: NostrEvent): boolean;
41
+ /** Options for {@link createInboxRelayListEvent}. */
42
+ export type CreateInboxRelayListEventOptions = {
43
+ /** The pubkey of the event author */
44
+ pubkey: string;
45
+ /** The relays where the account receives gift-wrapped welcomes */
46
+ relays: string[];
47
+ };
48
+ /**
49
+ * Creates an unsigned inbox (kind 10050) relay-list event. Marmot reads this
50
+ * list to learn where to deliver a recipient's welcomes.
51
+ */
52
+ export declare function createInboxRelayListEvent(options: CreateInboxRelayListEventOptions): UnsignedEvent;
@@ -0,0 +1,86 @@
1
+ import { isValidRelayUrl, normalizeRelayUrl } from "../utils/relay-url.js";
2
+ import { INBOX_RELAY_LIST_KIND, INBOX_RELAY_TAG, NIP65_RELAY_LIST_KIND, NIP65_RELAY_TAG, } from "./protocol.js";
3
+ import { unixNow } from "../utils/nostr.js";
4
+ /**
5
+ * Reads relay URLs from a NIP-65 (kind 10002) relay-list event.
6
+ *
7
+ * Each entry is an `r` tag: `["r", url]` (both read and write) or
8
+ * `["r", url, "read" | "write"]`. Pass `usage` to keep only relays usable for
9
+ * that direction; omit it to return every advertised relay (markerless `r`
10
+ * tags count as both directions).
11
+ *
12
+ * @param event - The kind 10002 event
13
+ * @param usage - Optional direction filter
14
+ * @returns Normalized, validated relay URLs
15
+ */
16
+ export function getNip65Relays(event, usage) {
17
+ return event.tags
18
+ .filter((tag) => tag[0] === NIP65_RELAY_TAG && tag[1])
19
+ .filter((tag) => {
20
+ if (!usage)
21
+ return true;
22
+ const marker = tag[2];
23
+ // A markerless `r` tag means the relay is used for both read and write.
24
+ return !marker || marker === usage;
25
+ })
26
+ .map((tag) => tag[1])
27
+ .filter(isValidRelayUrl)
28
+ .map(normalizeRelayUrl);
29
+ }
30
+ /** True for a kind 10002 event that advertises at least one valid relay. */
31
+ export function isValidNip65RelayListEvent(event) {
32
+ return (event.kind === NIP65_RELAY_LIST_KIND && getNip65Relays(event).length > 0);
33
+ }
34
+ /**
35
+ * Creates an unsigned NIP-65 (kind 10002) relay-list event. Marmot reads this
36
+ * list to discover an account's KeyPackage relays.
37
+ */
38
+ export function createNip65RelayListEvent(options) {
39
+ const { pubkey, relays, usage } = options;
40
+ const validRelays = relays.filter(isValidRelayUrl).map(normalizeRelayUrl);
41
+ const tags = validRelays.map((relay) => usage ? [NIP65_RELAY_TAG, relay, usage] : [NIP65_RELAY_TAG, relay]);
42
+ return {
43
+ kind: NIP65_RELAY_LIST_KIND,
44
+ created_at: unixNow(),
45
+ tags,
46
+ content: "",
47
+ pubkey,
48
+ };
49
+ }
50
+ // ---------------------------------------------------------------------------
51
+ // Inbox relay list (kind 10050) — Welcome delivery
52
+ //
53
+ // Welcomes are gift-wrapped to the recipient's inbox relay set
54
+ // (transports/nostr.md "Publish targets and acknowledgements").
55
+ // ---------------------------------------------------------------------------
56
+ /**
57
+ * Reads relay URLs from an inbox (kind 10050) relay-list event. Each entry is a
58
+ * `relay` tag: `["relay", url]`.
59
+ */
60
+ export function getInboxRelays(event) {
61
+ return event.tags
62
+ .filter((tag) => tag[0] === INBOX_RELAY_TAG && tag[1])
63
+ .map((tag) => tag[1])
64
+ .filter(isValidRelayUrl)
65
+ .map(normalizeRelayUrl);
66
+ }
67
+ /** True for a kind 10050 event that advertises at least one valid relay. */
68
+ export function isValidInboxRelayListEvent(event) {
69
+ return (event.kind === INBOX_RELAY_LIST_KIND && getInboxRelays(event).length > 0);
70
+ }
71
+ /**
72
+ * Creates an unsigned inbox (kind 10050) relay-list event. Marmot reads this
73
+ * list to learn where to deliver a recipient's welcomes.
74
+ */
75
+ export function createInboxRelayListEvent(options) {
76
+ const { pubkey, relays } = options;
77
+ const validRelays = relays.filter(isValidRelayUrl).map(normalizeRelayUrl);
78
+ const tags = validRelays.map((relay) => [INBOX_RELAY_TAG, relay]);
79
+ return {
80
+ kind: INBOX_RELAY_LIST_KIND,
81
+ created_at: unixNow(),
82
+ tags,
83
+ content: "",
84
+ pubkey,
85
+ };
86
+ }
@@ -0,0 +1,78 @@
1
+ /** @module @category Core - Retained History */
2
+ /**
3
+ * Retained-history decision logic (Marmot v2 `protocol-core/retained-history.md`).
4
+ *
5
+ * Clients retain group state so they can rebuild candidate branches and recover
6
+ * from forks and late delivery. The **retained anchor** is the oldest state from
7
+ * which a client can rebuild a candidate branch; the **rollback horizon**
8
+ * (`max_rewind_commits`) bounds how far back a branch may fork. These pure
9
+ * functions classify late commits, expire old app payloads, and decide what
10
+ * must be retained vs. may be pruned — without consulting transport order.
11
+ */
12
+ /** The outcome of judging a late commit by its source epoch. */
13
+ export type LateCommitOutcome =
14
+ /** Source epoch is at/after the anchor with retained state present: replayable. */
15
+ {
16
+ kind: "replay";
17
+ }
18
+ /** Source epoch is older than the retained anchor: drop as BeyondAnchor. */
19
+ | {
20
+ kind: "beyond_anchor";
21
+ }
22
+ /** Inside the rollback horizon but required retained state was lost: → Unrecoverable. */
23
+ | {
24
+ kind: "missing_retained_anchor";
25
+ }
26
+ /** Parent commit has not arrived yet: wait for it (a transport gap, not loss). */
27
+ | {
28
+ kind: "deferred";
29
+ }
30
+ /** At/after the anchor but forks from outside the rollback horizon: not selectable. */
31
+ | {
32
+ kind: "ineligible";
33
+ };
34
+ /** Inputs for {@link classifyLateCommit}. */
35
+ export interface LateCommitContext {
36
+ /** The late commit's MLS source epoch (the epoch it advances from). */
37
+ sourceEpoch: number;
38
+ /** The oldest retained state epoch (the retained anchor). */
39
+ anchorEpoch: number;
40
+ /** The current canonical tip epoch. */
41
+ currentTipEpoch: number;
42
+ /** The group's rollback horizon (`max_rewind_commits`). */
43
+ maxRewindCommits: number;
44
+ /** Whether the commit's parent commit has arrived (so its parent epoch is known). */
45
+ parentArrived: boolean;
46
+ /** Whether the retained parent state needed to replay is still in storage. */
47
+ retainedParentStateAvailable: boolean;
48
+ }
49
+ /**
50
+ * Classifies a late commit per `retained-history.md` "Late commits".
51
+ *
52
+ * Precedence: a commit below the anchor is always `beyond_anchor`; otherwise a
53
+ * commit whose parent has not arrived is `deferred` (a transport gap, not
54
+ * storage loss); within the rollback horizon it `replay`s when its retained
55
+ * parent state is present and is `missing_retained_anchor` (→ `Unrecoverable`)
56
+ * when that state was lost from storage; at/after the anchor but outside the
57
+ * horizon it is `ineligible` for selection.
58
+ */
59
+ export declare function classifyLateCommit(ctx: LateCommitContext): LateCommitOutcome;
60
+ /**
61
+ * Whether an MLS application message has fallen outside the retained app-payload
62
+ * window and MUST expire: it is more than `appPayloadPastEpochLimit` past epochs
63
+ * behind the current tip.
64
+ */
65
+ export declare function isAppPayloadExpired(messageEpoch: number, currentTipEpoch: number, appPayloadPastEpochLimit: number): boolean;
66
+ /**
67
+ * The minimum set of epochs a client must retain to replay candidate branches
68
+ * inside the rollback horizon: every epoch from `tip - maxRewindCommits` (floored
69
+ * at 0) through the current tip. Staged-commit and deferred-parent states are
70
+ * additional and tracked separately by the caller.
71
+ */
72
+ export declare function requiredRetainedEpochs(currentTipEpoch: number, maxRewindCommits: number): number[];
73
+ /**
74
+ * The retained epochs a client SHOULD prune after convergence settles: those
75
+ * older than the rollback horizon, excluding any `pinnedEpochs` still needed to
76
+ * resolve an active PendingPublish / Merging / Recovering / Unrecoverable state.
77
+ */
78
+ export declare function prunableRetainedEpochs(retainedEpochs: Iterable<number>, currentTipEpoch: number, maxRewindCommits: number, pinnedEpochs?: Iterable<number>): number[];
@@ -0,0 +1,59 @@
1
+ /** @module @category Core - Retained History */
2
+ /**
3
+ * Classifies a late commit per `retained-history.md` "Late commits".
4
+ *
5
+ * Precedence: a commit below the anchor is always `beyond_anchor`; otherwise a
6
+ * commit whose parent has not arrived is `deferred` (a transport gap, not
7
+ * storage loss); within the rollback horizon it `replay`s when its retained
8
+ * parent state is present and is `missing_retained_anchor` (→ `Unrecoverable`)
9
+ * when that state was lost from storage; at/after the anchor but outside the
10
+ * horizon it is `ineligible` for selection.
11
+ */
12
+ export function classifyLateCommit(ctx) {
13
+ if (ctx.sourceEpoch < ctx.anchorEpoch)
14
+ return { kind: "beyond_anchor" };
15
+ if (!ctx.parentArrived)
16
+ return { kind: "deferred" };
17
+ const withinHorizon = ctx.currentTipEpoch - ctx.sourceEpoch <= ctx.maxRewindCommits;
18
+ if (!withinHorizon)
19
+ return { kind: "ineligible" };
20
+ return ctx.retainedParentStateAvailable
21
+ ? { kind: "replay" }
22
+ : { kind: "missing_retained_anchor" };
23
+ }
24
+ /**
25
+ * Whether an MLS application message has fallen outside the retained app-payload
26
+ * window and MUST expire: it is more than `appPayloadPastEpochLimit` past epochs
27
+ * behind the current tip.
28
+ */
29
+ export function isAppPayloadExpired(messageEpoch, currentTipEpoch, appPayloadPastEpochLimit) {
30
+ return currentTipEpoch - messageEpoch > appPayloadPastEpochLimit;
31
+ }
32
+ /**
33
+ * The minimum set of epochs a client must retain to replay candidate branches
34
+ * inside the rollback horizon: every epoch from `tip - maxRewindCommits` (floored
35
+ * at 0) through the current tip. Staged-commit and deferred-parent states are
36
+ * additional and tracked separately by the caller.
37
+ */
38
+ export function requiredRetainedEpochs(currentTipEpoch, maxRewindCommits) {
39
+ const floor = Math.max(0, currentTipEpoch - maxRewindCommits);
40
+ const epochs = [];
41
+ for (let e = floor; e <= currentTipEpoch; e++)
42
+ epochs.push(e);
43
+ return epochs;
44
+ }
45
+ /**
46
+ * The retained epochs a client SHOULD prune after convergence settles: those
47
+ * older than the rollback horizon, excluding any `pinnedEpochs` still needed to
48
+ * resolve an active PendingPublish / Merging / Recovering / Unrecoverable state.
49
+ */
50
+ export function prunableRetainedEpochs(retainedEpochs, currentTipEpoch, maxRewindCommits, pinnedEpochs = []) {
51
+ const floor = Math.max(0, currentTipEpoch - maxRewindCommits);
52
+ const pinned = new Set(pinnedEpochs);
53
+ const prunable = [];
54
+ for (const epoch of retainedEpochs) {
55
+ if (epoch < floor && !pinned.has(epoch))
56
+ prunable.push(epoch);
57
+ }
58
+ return prunable.sort((a, b) => a - b);
59
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Marmot defines its group semantics independently of any one transport; a
3
+ * transport binding maps those semantics onto a concrete delivery network's
4
+ * wire identity (`transports/nostr.md`, target-architecture §4). Nostr is the
5
+ * binding shipped here, but the protocol is written so another binding (a relay
6
+ * mesh, a queue, etc.) could implement the same shape and carry the identical
7
+ * MLS bytes.
8
+ *
9
+ * The binding owns only *transport addressing* — event kinds and routing tags.
10
+ * The encrypted MLS payloads and the canonical signed group state (including
11
+ * `transport.nostr.routing.v1`) are transport-independent.
12
+ */
13
+ export interface TransportBinding {
14
+ /** Stable binding name (matches the `transport.<name>.*` component family). */
15
+ readonly name: string;
16
+ /** Event kind carrying an encrypted group message (commit/proposal/app). */
17
+ readonly groupMessageKind: number;
18
+ /** Event kind carrying a Welcome. */
19
+ readonly welcomeKind: number;
20
+ /** Event kind for an addressable KeyPackage. */
21
+ readonly addressableKeyPackageKind: number;
22
+ /**
23
+ * Event kind for the NIP-65 relay list used to discover an account's
24
+ * KeyPackage relays (there is no dedicated KeyPackage relay list).
25
+ */
26
+ readonly nip65RelayListKind: number;
27
+ /** Event kind for the inbox relay list welcomes are delivered to. */
28
+ readonly inboxRelayListKind: number;
29
+ /** Event kind for the privacy-preserving outer wrap of a Welcome. */
30
+ readonly giftWrapKind: number;
31
+ /** Single-letter event tag naming the (public) group a message routes to. */
32
+ readonly groupIdTag: string;
33
+ }
34
+ /** The Nostr group routing tag (`h`) naming the public nostr group id. */
35
+ export declare const NOSTR_GROUP_ID_TAG = "h";
36
+ /** NIP-59 gift-wrap event kind used to wrap a Welcome for its recipient. */
37
+ export declare const GIFT_WRAP_KIND = 1059;
38
+ /**
39
+ * The Nostr transport binding: the default (and currently only) Marmot delivery
40
+ * binding. All kinds and the routing tag are gathered here so the transport
41
+ * seam is explicit and a future binding can mirror the shape.
42
+ */
43
+ export declare const nostrTransportBinding: TransportBinding;
@@ -0,0 +1,21 @@
1
+ /** @module @category Core - Transport */
2
+ import { ADDRESSABLE_KEY_PACKAGE_KIND, GROUP_EVENT_KIND, INBOX_RELAY_LIST_KIND, NIP65_RELAY_LIST_KIND, WELCOME_EVENT_KIND, } from "./protocol.js";
3
+ /** The Nostr group routing tag (`h`) naming the public nostr group id. */
4
+ export const NOSTR_GROUP_ID_TAG = "h";
5
+ /** NIP-59 gift-wrap event kind used to wrap a Welcome for its recipient. */
6
+ export const GIFT_WRAP_KIND = 1059;
7
+ /**
8
+ * The Nostr transport binding: the default (and currently only) Marmot delivery
9
+ * binding. All kinds and the routing tag are gathered here so the transport
10
+ * seam is explicit and a future binding can mirror the shape.
11
+ */
12
+ export const nostrTransportBinding = {
13
+ name: "nostr",
14
+ groupMessageKind: GROUP_EVENT_KIND,
15
+ welcomeKind: WELCOME_EVENT_KIND,
16
+ addressableKeyPackageKind: ADDRESSABLE_KEY_PACKAGE_KIND,
17
+ nip65RelayListKind: NIP65_RELAY_LIST_KIND,
18
+ inboxRelayListKind: INBOX_RELAY_LIST_KIND,
19
+ giftWrapKind: GIFT_WRAP_KIND,
20
+ groupIdTag: NOSTR_GROUP_ID_TAG,
21
+ };
@@ -0,0 +1,61 @@
1
+ /** @module @category Core - Welcome */
2
+ import { Rumor } from "../utils/nostr.js";
3
+ import { type Welcome } from "ts-mls";
4
+ /**
5
+ * Creates a welcome rumor (kind 444) for a welcome message.
6
+ *
7
+ * @returns Welcome rumor with precomputed ID
8
+ */
9
+ export declare function createWelcomeRumor({ welcome, author, groupRelays, keyPackageEventId, }: {
10
+ /** The MLS welcome message */
11
+ welcome: Welcome;
12
+ /** The author's public key (hex string) */
13
+ author: string;
14
+ /**
15
+ * The ID of the KeyPackage event consumed for this add. Required: the spec
16
+ * mandates a 32-byte-hex `e` tag on every welcome rumor
17
+ * (transports/nostr.md "Welcome delivery").
18
+ */
19
+ keyPackageEventId: string;
20
+ /**
21
+ * Array of relay URLs for the group (becomes the `relays` tag). Must be
22
+ * non-empty and every URL must be distinct — matching the #236
23
+ * list-cardinality rule this rumor's own consumer (`getWelcome` /
24
+ * `getWelcomeGroupRelays`, via `getListTag`) enforces (WIRE-02).
25
+ */
26
+ groupRelays: string[];
27
+ }): Rumor;
28
+ /**
29
+ * Returns the key package event ID from a welcome rumor. Strict (#236): a
30
+ * repeated, missing, or empty-valued `e` tag yields `undefined` rather than
31
+ * silently resolving to the first match (WIRE-02).
32
+ */
33
+ export declare function getWelcomeKeyPackageEventId(event: Rumor): string | undefined;
34
+ /**
35
+ * Returns the group relays from a welcome rumor. Strict (#236): a repeated
36
+ * `relays` tag, an empty/absent one, or one carrying duplicate URLs yields
37
+ * `[]` rather than silently resolving to the first match (WIRE-02).
38
+ *
39
+ * NOTE: The "relays" tag is a normal Nostr tag vector: ["relays", ...urls]
40
+ * (see transports/nostr.md "Welcome delivery" and createWelcomeRumor()).
41
+ */
42
+ export declare function getWelcomeGroupRelays(event: Rumor): string[];
43
+ /**
44
+ * Returns the KeyPackageRefs of the intended recipients from a Welcome message.
45
+ *
46
+ * Each entry in `welcome.secrets` contains a plaintext `newMember` field which
47
+ * is the RFC 9420 KeyPackageRef (a hash of the recipient's KeyPackage). No
48
+ * decryption is required to read these.
49
+ *
50
+ * @param welcome - The MLS Welcome message
51
+ * @returns Array of KeyPackageRefs (one per recipient)
52
+ */
53
+ export declare function getWelcomeKeyPackageRefs(welcome: Welcome | Rumor): Uint8Array[];
54
+ /**
55
+ * Gets the Welcome message from a kind 444 event.
56
+ *
57
+ * @param event - The Nostr event containing the welcome message
58
+ * @returns The decoded Welcome message
59
+ * @throws Error if the content cannot be decoded
60
+ */
61
+ export declare function getWelcome(event: Rumor): Welcome;
@@ -0,0 +1,116 @@
1
+ /** @module @category Core - Welcome */
2
+ import { getEventHash, isRumor } from "../utils/nostr.js";
3
+ import { decode, encode, mlsMessageDecoder, mlsMessageEncoder, protocolVersions, wireformats, } from "ts-mls";
4
+ import { decodeContent, encodeContent } from "../utils/encoding.js";
5
+ import { unixNow } from "../utils/nostr.js";
6
+ import { getListTag, getSingletonTagValue } from "../utils/tag-cardinality.js";
7
+ import { WELCOME_EVENT_KIND } from "./protocol.js";
8
+ /** True when `value` is a 32-byte (64-char) lowercase-or-uppercase hex string. */
9
+ function isEventId(value) {
10
+ return typeof value === "string" && /^[0-9a-fA-F]{64}$/.test(value);
11
+ }
12
+ /**
13
+ * Creates a welcome rumor (kind 444) for a welcome message.
14
+ *
15
+ * @returns Welcome rumor with precomputed ID
16
+ */
17
+ export function createWelcomeRumor({ welcome, author, groupRelays, keyPackageEventId, }) {
18
+ if (!isEventId(keyPackageEventId))
19
+ throw new Error("Welcome rumor requires a 32-byte hex KeyPackage event id (e tag)");
20
+ if (groupRelays.length === 0 || groupRelays.some((r) => r.length === 0))
21
+ throw new Error("Welcome rumor requires a non-empty relays tag with no empty relay URLs");
22
+ if (new Set(groupRelays).size !== groupRelays.length)
23
+ throw new Error("Welcome rumor requires distinct relay URLs — a duplicate relay tag value would be rejected by this library's own getWelcome consumer");
24
+ // Serialize the welcome message as a full MLSMessage (RFC 9420)
25
+ const mlsMessage = {
26
+ version: protocolVersions.mls10,
27
+ wireformat: wireformats.mls_welcome,
28
+ welcome,
29
+ };
30
+ const serializedWelcome = encode(mlsMessageEncoder, mlsMessage);
31
+ const content = encodeContent(serializedWelcome, "base64");
32
+ // No `encoding` tag: the spec forbids it and content is always standard
33
+ // base64 (transports/nostr.md "Transport byte encoding"). The `e` tag is
34
+ // mandatory and validated above.
35
+ const draft = {
36
+ kind: WELCOME_EVENT_KIND,
37
+ pubkey: author,
38
+ created_at: unixNow(),
39
+ content,
40
+ tags: [
41
+ ["relays", ...groupRelays],
42
+ ["e", keyPackageEventId],
43
+ ],
44
+ };
45
+ // Calculate the event ID for the rumor
46
+ const id = getEventHash(draft);
47
+ return {
48
+ ...draft,
49
+ id,
50
+ };
51
+ }
52
+ /**
53
+ * Returns the key package event ID from a welcome rumor. Strict (#236): a
54
+ * repeated, missing, or empty-valued `e` tag yields `undefined` rather than
55
+ * silently resolving to the first match (WIRE-02).
56
+ */
57
+ export function getWelcomeKeyPackageEventId(event) {
58
+ return getSingletonTagValue(event, "e");
59
+ }
60
+ /**
61
+ * Returns the group relays from a welcome rumor. Strict (#236): a repeated
62
+ * `relays` tag, an empty/absent one, or one carrying duplicate URLs yields
63
+ * `[]` rather than silently resolving to the first match (WIRE-02).
64
+ *
65
+ * NOTE: The "relays" tag is a normal Nostr tag vector: ["relays", ...urls]
66
+ * (see transports/nostr.md "Welcome delivery" and createWelcomeRumor()).
67
+ */
68
+ export function getWelcomeGroupRelays(event) {
69
+ return getListTag(event, "relays") ?? [];
70
+ }
71
+ /**
72
+ * Returns the KeyPackageRefs of the intended recipients from a Welcome message.
73
+ *
74
+ * Each entry in `welcome.secrets` contains a plaintext `newMember` field which
75
+ * is the RFC 9420 KeyPackageRef (a hash of the recipient's KeyPackage). No
76
+ * decryption is required to read these.
77
+ *
78
+ * @param welcome - The MLS Welcome message
79
+ * @returns Array of KeyPackageRefs (one per recipient)
80
+ */
81
+ export function getWelcomeKeyPackageRefs(welcome) {
82
+ // Unwrap welcome rumor if provided
83
+ if (isRumor(welcome))
84
+ welcome = getWelcome(welcome);
85
+ return welcome.secrets.map((s) => s.newMember);
86
+ }
87
+ /**
88
+ * Gets the Welcome message from a kind 444 event.
89
+ *
90
+ * @param event - The Nostr event containing the welcome message
91
+ * @returns The decoded Welcome message
92
+ * @throws Error if the content cannot be decoded
93
+ */
94
+ export function getWelcome(event) {
95
+ if (event.kind !== WELCOME_EVENT_KIND)
96
+ throw new Error(`Expected welcome event kind ${WELCOME_EVENT_KIND}, got ${event.kind}`);
97
+ // Validate the transport-level rumor shape the spec mandates before decoding
98
+ // (transports/nostr.md "Welcome delivery"): a singleton 32-byte-hex `e` tag
99
+ // and a singleton non-empty, non-duplicate `relays` tag (#236 strict
100
+ // cardinality — WIRE-02). getSingletonTagValue/getListTag reject repeated,
101
+ // empty, or duplicate-valued tags instead of first-match-resolving them.
102
+ const keyPackageEventId = getSingletonTagValue(event, "e");
103
+ if (!isEventId(keyPackageEventId))
104
+ throw new Error("Invalid welcome event: missing or malformed e tag (expected 32-byte hex KeyPackage event id)");
105
+ const relays = getWelcomeGroupRelays(event);
106
+ if (relays.length === 0 || relays.some((r) => r.length === 0))
107
+ throw new Error("Invalid welcome event: relays tag must contain at least one non-empty relay URL");
108
+ // Content is always standard base64; the spec forbids an `encoding` tag.
109
+ const content = decodeContent(event.content, "base64");
110
+ const mlsMessage = decode(mlsMessageDecoder, content);
111
+ if (!mlsMessage)
112
+ throw new Error("Failed to decode welcome message");
113
+ if (mlsMessage.wireformat !== wireformats.mls_welcome)
114
+ throw new Error(`Expected MLSMessage with mls_welcome wireformat, got wireformat ${mlsMessage.wireformat}`);
115
+ return mlsMessage.welcome;
116
+ }