@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,366 @@
1
+ /** @module @category Engine */
2
+ import type { CiphersuiteImpl, ClientState, LeafNodePatch, MlsMessage, MlsWelcomeMessage, ProcessMessageResult, Proposal, ProposalRemove } from "ts-mls";
3
+ import type { LeafEquivocation } from "../core/convergence.js";
4
+ /** Immutable timing identity for one bounded convergence collection pass. */
5
+ export interface ConvergencePassState {
6
+ readonly generation: number;
7
+ readonly openedAtMs: number;
8
+ readonly deadlineMs: number;
9
+ readonly lastRelevantInputMs: number;
10
+ /** Canonical epoch sampled once when this pass opened. */
11
+ readonly baseEpoch: number;
12
+ }
13
+ /** Opens a pass from one monotonic-clock sample. */
14
+ export declare function openConvergencePass(nowMs: number, maxDurationMs: number, generation: number, baseEpoch?: number): ConvergencePassState;
15
+ /** Restarts quiescence without changing a pass's identity or absolute deadline. */
16
+ export declare function refreshConvergencePass(pass: ConvergencePassState, nowMs: number): ConvergencePassState;
17
+ /** Authenticated terminal metadata carried beside, never inside, branch scores. */
18
+ export interface DisbandCandidateEvidence {
19
+ readonly commitDigest: Uint8Array;
20
+ readonly actorPubkey: string;
21
+ readonly sourceEpoch: number;
22
+ readonly parentTag: string;
23
+ readonly terminalOutcome: "disbanded";
24
+ }
25
+ import type { MarmotGroupView } from "../core/client-state.js";
26
+ import type { DeferredReason, Disposition } from "../core/inbound.js";
27
+ import type { StateNotification } from "./state-notifications.js";
28
+ import type { OwnCommitConvergenceStamp } from "./own-commit-stamp.js";
29
+ /** A decrypted transport envelope paired with its MLS message. */
30
+ export type PeeledMessagePair<TEnvelope> = {
31
+ envelope: TEnvelope;
32
+ message: MlsMessage;
33
+ };
34
+ /** Crypto boundary between the engine and transport-specific wrapping. */
35
+ export interface GroupPeeler<TEnvelope> {
36
+ peelGroupMessages(envelopes: TEnvelope[], state: ClientState): Promise<{
37
+ read: PeeledMessagePair<TEnvelope>[];
38
+ unreadable: TEnvelope[];
39
+ }>;
40
+ wrapGroupMessage(message: MlsMessage, state: ClientState): Promise<TEnvelope>;
41
+ /** A stable transport id for an envelope (used to key the ingestion pool). */
42
+ idOf(envelope: TEnvelope): string;
43
+ }
44
+ /** Staged state awaiting publish confirmation (publish-before-apply). */
45
+ export type PendingState = {
46
+ kind: "proposal" | "commit" | "selfUpdate";
47
+ newState: ClientState;
48
+ /**
49
+ * Parent state before apply. Required for BOTH commit-producing kinds —
50
+ * `"commit"` and `"selfUpdate"` (CR-09) — because `confirmPublished` records
51
+ * the applied commit into retained history and the fork tree from it.
52
+ * Absent only for `"proposal"`.
53
+ */
54
+ parentState?: ClientState;
55
+ /**
56
+ * Applied commit MLS message. Required for both `"commit"` and
57
+ * `"selfUpdate"`; absent only for `"proposal"`.
58
+ */
59
+ commitMessage?: MlsMessage;
60
+ /** Confirmation-time recovery evidence captured before proposals are cleared. */
61
+ ownCommitStamp?: OwnCommitConvergenceStamp;
62
+ /** Authenticated local terminal intent retained until bounded selection. */
63
+ terminalEvidence?: DisbandCandidateEvidence;
64
+ };
65
+ export type ProposalContext = {
66
+ state: ClientState;
67
+ ciphersuite: CiphersuiteImpl;
68
+ groupData: MarmotGroupView;
69
+ };
70
+ export type ProposalAction<T extends Proposal | Proposal[]> = (context: ProposalContext) => Promise<T>;
71
+ /** Application intent when calling {@link MarmotGroupEngine.send}. */
72
+ export type SendIntent = {
73
+ kind: "applicationMessage";
74
+ payload: Uint8Array;
75
+ /**
76
+ * Generations to advance the own application sender ratchet by before
77
+ * this message is encrypted (`advanceOwnApplicationRatchet`, an integer
78
+ * in `[0, maxSenderRatchetSkip(clientConfig)]`). The engine adopts the
79
+ * advanced ratchet only together with the sent message. Omitted or `0`:
80
+ * the message uses the ratchet's next generation, as upstream.
81
+ */
82
+ ratchetSkip?: number;
83
+ } | {
84
+ kind: "proposal";
85
+ proposal: Proposal;
86
+ } | {
87
+ kind: "commit";
88
+ actorPubkey: string;
89
+ extraProposals?: (Proposal | ProposalAction<Proposal> | (Proposal | ProposalAction<Proposal>)[])[];
90
+ proposalRefs?: string[];
91
+ } | {
92
+ kind: "selfUpdate";
93
+ /**
94
+ * Seam: replaces fields of the committer's own leaf in the commit's
95
+ * UpdatePath (ts-mls `createCommit`'s `leafNodePatch`). A
96
+ * `signatureKeyPair` rotates the leaf's signature key: the commit is
97
+ * signed with the key the leaf holds now (receivers verify it against
98
+ * the parent tree), the new leaf is self-signed with the patched key and
99
+ * `pending.newState.signaturePrivateKey` is the patched private key. A
100
+ * patched signature key must be unique in the tree the commit produces
101
+ * (a Remove committed with it frees the leaf that held it); a duplicate
102
+ * is refused before anything is staged. `extensions` replaces the whole
103
+ * leaf extension list. Omitted: the self-update is upstream's.
104
+ */
105
+ leafNodePatch?: LeafNodePatch;
106
+ /**
107
+ * Seam: by-value Remove proposals committed in the same commit as the
108
+ * patched path rotation (only with `leafNodePatch`; any other kind is
109
+ * refused before staging). They are judged exactly like a `commit`
110
+ * intent's by-value proposals: the engine's commit-authorization seam
111
+ * decides (the default refuses a non-admin's Remove; marmot's
112
+ * same-account seam allows a Remove of the committer's own account's
113
+ * leaf), and the patched key's uniqueness is checked on the tree they
114
+ * produce, so a Remove of the leaf holding the key repairs a
115
+ * duplicate-leaf state atomically. Omitted: nothing changes.
116
+ */
117
+ extraProposals?: readonly ProposalRemove[];
118
+ };
119
+ /** Engine response to {@link MarmotGroupEngine.send}. */
120
+ export type SendResult<TEnvelope> = {
121
+ kind: "applicationMessage";
122
+ envelope: TEnvelope;
123
+ newState: ClientState;
124
+ } | {
125
+ kind: "proposal";
126
+ envelope: TEnvelope;
127
+ pending: PendingState;
128
+ } | {
129
+ kind: "groupEvolution";
130
+ envelope: TEnvelope;
131
+ welcome: MlsWelcomeMessage | undefined;
132
+ pending: PendingState;
133
+ } | {
134
+ kind: "selfUpdate";
135
+ envelope: TEnvelope;
136
+ pending: PendingState;
137
+ };
138
+ /** An envelope whose MLS message was successfully processed. */
139
+ export type ProcessedIngestResult<TEnvelope> = {
140
+ kind: "processed";
141
+ result: ProcessMessageResult;
142
+ envelope: TEnvelope;
143
+ message: MlsMessage;
144
+ /**
145
+ * Commit-digest-attributed group-state notifications (D-10/D-11,
146
+ * `convergence.md` "Applying the selected branch"). Optional — populated by
147
+ * the seam that wires notification derivation.
148
+ *
149
+ * ATTRIBUTION (WR-18): these are NOT always this `message`'s own
150
+ * notifications. In the normal in-order case they are. But when this result
151
+ * reports an applied fork resolution, the array is the concatenation of the
152
+ * notifications derived from EVERY commit on the adopted winner chain, while
153
+ * `message` is merely the representative fork-pool envelope the rewind was
154
+ * reported against — it may be unrelated to most of the entries. Never pair
155
+ * `message` with `notifications` positionally; each entry carries its own
156
+ * `commitDigest`, which is the only correct way to attribute it.
157
+ */
158
+ notifications?: StateNotification[];
159
+ /** Authenticated terminal evidence, present only after canonical selection. */
160
+ selectedTerminal?: DisbandCandidateEvidence;
161
+ };
162
+ /** A commit rejected by the admin-verification callback. */
163
+ export type RejectedIngestResult<TEnvelope> = {
164
+ kind: "rejected";
165
+ result: ProcessMessageResult;
166
+ envelope: TEnvelope;
167
+ message: MlsMessage;
168
+ /**
169
+ * Additive, extensible rejection reason (D-03). The protocol-visible
170
+ * category stays `authorization_failed` regardless of which reason fires —
171
+ * `foundation/errors.md` requires pre-convergence rejections be described
172
+ * "by category alone".
173
+ */
174
+ reason?: "admin-policy" | "component-integrity" | "admin-leaf-coupling" | "disband-legality";
175
+ };
176
+ /**
177
+ * Why a commit failed the authorization / commit-legality gate: the reason of
178
+ * a {@link RejectedIngestResult}.
179
+ */
180
+ export type CommitRejectionReason = NonNullable<RejectedIngestResult<unknown>["reason"]>;
181
+ /**
182
+ * A commit a convergence seam (pool replay) dropped as a candidate because it
183
+ * failed the gate that would have `rejected` it on the direct apply path.
184
+ * `detail` is the diagnostic of the legality violation (component ids and
185
+ * counts only, never key material); it is logged, not part of a result.
186
+ */
187
+ export interface CommitRejection {
188
+ reason: CommitRejectionReason;
189
+ detail?: string;
190
+ }
191
+ /** An envelope skipped without processing. */
192
+ export type SkippedIngestResult<TEnvelope> = {
193
+ kind: "skipped";
194
+ envelope: TEnvelope;
195
+ /**
196
+ * Absent for inactive reasons because input for a client removed from, or a
197
+ * group canonically disbanded is classified by its group
198
+ * before any peel or decrypt (`member-departure.md`: such input "need not
199
+ * be decrypted or authenticated"). Every other skip reason still populates
200
+ * this (D-13).
201
+ */
202
+ message?: MlsMessage;
203
+ reason: "past-epoch" | "wrong-wireformat" | "self-echo" | "duplicate" | "beyond-anchor" | "missing-retained-anchor" | "invalid-app-payload" | "self-evicted" | "group-disbanded";
204
+ /**
205
+ * Seam (convergence rejection reason): present on a `past-epoch` skip of a
206
+ * commit that fork recovery dropped as a candidate because it failed the
207
+ * authorization / commit-legality gate (the reason the direct apply path
208
+ * reports as `rejected`), at every node it was replayed on. Absent for an
209
+ * ordinary `past-epoch` skip (a commit that lost, duplicated a canonical
210
+ * commit, or was never evaluated). Additive: `reason` is unchanged.
211
+ */
212
+ droppedReason?: CommitRejectionReason;
213
+ };
214
+ /** An envelope that could not be decrypted or processed after all retry attempts. */
215
+ export type UnreadableIngestResult<TEnvelope> = {
216
+ kind: "unreadable";
217
+ envelope: TEnvelope;
218
+ errors: unknown[];
219
+ /**
220
+ * The envelope failed to *decrypt* (its kind-445 wrapper did not open against
221
+ * any tried state), as opposed to decoding/processing after decryption. Such
222
+ * failures are retryable: the unlocking epoch/fork state may arrive later, so
223
+ * the engine pools them rather than treating them as terminal. A permanent
224
+ * MLS forward-secrecy failure (`gen-in-past`) is NOT flagged.
225
+ */
226
+ decryptFailure?: boolean;
227
+ };
228
+ /**
229
+ * An envelope that cannot be processed yet but may become processable once more
230
+ * protocol bytes arrive (`protocol-core/inbound-processing.md` "deferred"). Unlike
231
+ * {@link UnreadableIngestResult}, this is NOT terminal: callers MUST retry when
232
+ * the missing state becomes available rather than treating it as malformed.
233
+ */
234
+ export type DeferredIngestResult<TEnvelope> = {
235
+ kind: "deferred";
236
+ envelope: TEnvelope;
237
+ message: MlsMessage;
238
+ reason: DeferredReason;
239
+ /** MLS-authenticated source epoch used for horizon retention. */
240
+ sourceEpoch: number;
241
+ };
242
+ /** An envelope retained outside the bounded pool until admission capacity frees. */
243
+ export type CapacityRefusedIngestResult<TEnvelope> = {
244
+ kind: "refused";
245
+ envelope: TEnvelope;
246
+ reason: "capacity";
247
+ };
248
+ /**
249
+ * An MLS application message that decrypted only on a losing/abandoned branch
250
+ * (`protocol-core/inbound-processing.md`, `convergence.md`). Either it was
251
+ * tentatively delivered as `accepted` on a branch a later convergence rewind
252
+ * abandoned (Marmot v2 delivers eagerly), or it only ever decrypted on a
253
+ * non-canonical fork node during the tree sweep. The spec requires it be
254
+ * reported as `invalidated`, not delivered as accepted output — but the local
255
+ * API is free to expose where it decrypted so a consumer (e.g. a full-history
256
+ * debugger) can still attribute it to its fork.
257
+ *
258
+ * `message` is the MLS application message (the encrypted wrapper); `payload` is
259
+ * its decrypted Marmot app payload bytes, so a consumer can identify the rumor
260
+ * being retracted (e.g. to withdraw it from a UI, or to record it under its
261
+ * fork). `tag` and `epoch` identify the losing branch: `tag` is the hex MLS
262
+ * confirmation tag of the fork-tree node the payload decrypted against (an
263
+ * application message does not change the epoch or confirmation tag, so the node
264
+ * is the delivery branch), and `epoch` is that node's MLS epoch. All three are
265
+ * populated for invalidations the engine produces; they are optional only for
266
+ * backward compatibility with consumers that ignore them.
267
+ */
268
+ export type InvalidatedIngestResult<TEnvelope> = {
269
+ kind: "invalidated";
270
+ envelope: TEnvelope;
271
+ message: MlsMessage;
272
+ /** The decrypted Marmot app payload bytes of the invalidated message. */
273
+ payload?: Uint8Array;
274
+ /** Hex confirmation tag of the losing fork-tree node it decrypted against. */
275
+ tag?: string;
276
+ /** MLS epoch of that fork node. */
277
+ epoch?: number;
278
+ };
279
+ /**
280
+ * A `self_remove`-only commit this client built and staged during ingest because
281
+ * it is the deterministically-elected committer for a peer's departure (B6,
282
+ * `protocol-core/member-departure.md`). It is NOT applied yet — the layer that
283
+ * owns the transport MUST publish `envelope` and then confirm/roll back the
284
+ * `pending` state (publish-before-apply), exactly like a local commit send.
285
+ */
286
+ export type AutoCommitIngestResult<TEnvelope> = {
287
+ kind: "autoCommit";
288
+ envelope: TEnvelope;
289
+ pending: PendingState;
290
+ /** This client's own pubkey — the auto-committer (actor) of the commit. */
291
+ actorPubkey: string;
292
+ };
293
+ /**
294
+ * An inbound commit that removed *this* client from the group — an admin's
295
+ * involuntary `Remove`, or a peer committing this client's own `self_remove`
296
+ * (`protocol-core/member-departure.md`). The commit applied and advanced state
297
+ * to the `removedFromGroup` tombstone: no secrets advanced, so nothing further
298
+ * can be decrypted, and retained history is moot. The transport-owning layer
299
+ * surfaces this (a `removed` event); local-state teardown is left to the app —
300
+ * the engine keeps the tombstone.
301
+ */
302
+ export type RemovedIngestResult<TEnvelope> = {
303
+ kind: "removed";
304
+ result: ProcessMessageResult;
305
+ envelope: TEnvelope;
306
+ message: MlsMessage;
307
+ /**
308
+ * Commit-digest-attributed group-state notifications (D-10/D-11/D-12) — in
309
+ * particular the `selfRemoved` notification attributed to the very commit
310
+ * that removed us.
311
+ *
312
+ * ATTRIBUTION (WR-18): as with {@link ProcessedIngestResult.notifications},
313
+ * when this result reports an applied fork resolution the array spans the
314
+ * WHOLE adopted winner chain, not just this `message`. Attribute entries by
315
+ * their `commitDigest`, never by position against `message`.
316
+ */
317
+ notifications?: StateNotification[];
318
+ };
319
+ /**
320
+ * A rewind superseded a previously-accepted commit and withdrew the
321
+ * notifications derived from it (D-11, `convergence.md` "Applying the
322
+ * selected branch"). Unlike every other {@link IngestResult} variant, this
323
+ * carries NO `envelope` and NO `message`: a rewind supersedes a commit, and
324
+ * there is no triggering transport envelope to attribute the withdrawal to.
325
+ * It is generic-free — it is not parameterized on `TEnvelope`.
326
+ */
327
+ export type StateInvalidatedIngestResult = {
328
+ kind: "stateInvalidated";
329
+ /** Digest of the superseded commit. */
330
+ commitDigest: Uint8Array;
331
+ /** Epoch the rewind selected as canonical. */
332
+ forkEpoch: number;
333
+ /** Notifications withdrawn because the commit that produced them was superseded. */
334
+ withdrawn: StateNotification[];
335
+ };
336
+ /** Notifications made observable after a commit has been confirmed locally or adopted. */
337
+ export type AppliedNotificationsIngestResult = {
338
+ kind: "appliedNotifications";
339
+ commitDigest: Uint8Array;
340
+ notifications: StateNotification[];
341
+ };
342
+ /** A previously withdrawn branch commit has become canonical again. */
343
+ export type StateRevalidatedIngestResult = {
344
+ kind: "stateRevalidated";
345
+ commitDigest: Uint8Array;
346
+ effectId: Uint8Array;
347
+ notifications: StateNotification[];
348
+ };
349
+ /**
350
+ * Seam (`equivocationCredit`): branch selection found a leaf that authored two
351
+ * or more child commits of one node (ADR-016). Report only — the selection it
352
+ * came from is already applied. Like {@link StateInvalidatedIngestResult} it has
353
+ * no envelope: it is yielded whoever won, and again on every pass whose
354
+ * candidate tree still holds the node, so a consumer dedupes by
355
+ * `(evidence.nodeTag, evidence.leafIndex)`.
356
+ */
357
+ export type LeafEquivocationIngestResult = {
358
+ kind: "leafEquivocation";
359
+ evidence: LeafEquivocation;
360
+ };
361
+ /** Result from ingesting group transport envelopes. */
362
+ export type IngestResult<TEnvelope> = ProcessedIngestResult<TEnvelope> | RejectedIngestResult<TEnvelope> | SkippedIngestResult<TEnvelope> | DeferredIngestResult<TEnvelope> | CapacityRefusedIngestResult<TEnvelope> | InvalidatedIngestResult<TEnvelope> | AutoCommitIngestResult<TEnvelope> | RemovedIngestResult<TEnvelope> | UnreadableIngestResult<TEnvelope> | AppliedNotificationsIngestResult | StateRevalidatedIngestResult | StateInvalidatedIngestResult | LeafEquivocationIngestResult;
363
+ /** An {@link IngestResult} carrying its protocol-visible {@link Disposition}. */
364
+ export type DispositionedIngestResult<TEnvelope> = IngestResult<TEnvelope> & {
365
+ disposition: Disposition;
366
+ };
@@ -0,0 +1,14 @@
1
+ /** Opens a pass from one monotonic-clock sample. */
2
+ export function openConvergencePass(nowMs, maxDurationMs, generation, baseEpoch = 0) {
3
+ return {
4
+ generation,
5
+ openedAtMs: nowMs,
6
+ deadlineMs: nowMs + maxDurationMs,
7
+ lastRelevantInputMs: nowMs,
8
+ baseEpoch,
9
+ };
10
+ }
11
+ /** Restarts quiescence without changing a pass's identity or absolute deadline. */
12
+ export function refreshConvergencePass(pass, nowMs) {
13
+ return { ...pass, lastRelevantInputMs: nowMs };
14
+ }
@@ -0,0 +1,77 @@
1
+ /** @module @category Engine */
2
+ import { type ClientState, type ContentTypeValue, type LeafIndex, type MlsMessage, type Proposal, type ProposalWithSender } from "ts-mls";
3
+ /**
4
+ * Marmot v2 carries MLS handshake content — Commits and Proposals — as
5
+ * `PublicMessage`, while application messages stay `PrivateMessage`
6
+ * (`darkmatter/spec/foundation/mls-protocol.md`, "Handshake wire format"). The
7
+ * kind-445 transport wrap provides confidentiality, so relays never see
8
+ * plaintext handshake bytes. The inbound pipeline therefore cannot assume a
9
+ * single wire format when classifying or ordering framed messages; these
10
+ * accessors read the framed fields uniformly across both carriages.
11
+ */
12
+ /**
13
+ * The MLS framed content type (application / proposal / commit) carried by a
14
+ * private- or public-message {@link MlsMessage}, or `undefined` for non-framed
15
+ * messages (welcome / key package / group info).
16
+ */
17
+ export declare function framedContentType(message: MlsMessage): ContentTypeValue | undefined;
18
+ /**
19
+ * The MLS epoch carried by a private- or public-message {@link MlsMessage}, or
20
+ * `undefined` for non-framed messages. Normalizes to `bigint` regardless of how
21
+ * each wire format models the field.
22
+ */
23
+ export declare function framedEpoch(message: MlsMessage): bigint | undefined;
24
+ /**
25
+ * The {@link Proposal}s a commit actually carries, read straight off the wire
26
+ * with NO `processMessage` replay — the union of its inline proposals and the
27
+ * proposals its `ProposalRef` entries name in `parentState.unappliedProposals`.
28
+ *
29
+ * This exists for the one seam that cannot replay: `ForkRecovery`'s CONV-04
30
+ * short-circuit reuses an already-known resulting state precisely BECAUSE the
31
+ * commit cannot be reprocessed (an `UpdatePath` never encrypts a path secret to
32
+ * the committer's own leaf, RFC 9420), so `withCapturedProposals` can never
33
+ * observe that commit's proposals. Without this, that seam had no way to run
34
+ * `validateCommitLegality` and silently grandfathered violations every other
35
+ * seam refuses (CR-04).
36
+ *
37
+ * Returns `undefined` — never a partial list — when the proposal set cannot be
38
+ * fully reconstructed:
39
+ * - the message is not a public-message commit (a `PrivateMessage`'s content
40
+ * is encrypted; Marmot v2 wires handshake content as `PublicMessage`, so
41
+ * this is a defensive branch), or
42
+ * - a `ProposalRef` names a proposal absent from `parentState`.
43
+ *
44
+ * Callers MUST treat `undefined` as "cannot validate" and fail closed, mirroring
45
+ * `#treeResolution`'s policy for any link it cannot re-validate.
46
+ *
47
+ * @param parentState The state the commit was applied to — the only state whose
48
+ * `unappliedProposals` can resolve this commit's refs.
49
+ */
50
+ export declare function framedCommitProposals(message: MlsMessage, parentState: ClientState): Proposal[] | undefined;
51
+ /**
52
+ * The sender-attributed form of {@link framedCommitProposals}, plus the
53
+ * commit's own committer leaf index.
54
+ *
55
+ * This reproduces exactly what ts-mls's `applyProposals` assembles as
56
+ * `allProposals` and hands to an {@link IncomingMessageCallback}: an inline
57
+ * (by-value) proposal is attributed to the COMMITTER's leaf, while a
58
+ * `ProposalRef` carries the ORIGINAL proposer's leaf from
59
+ * `parentState.unappliedProposals` (`ts-mls/src/clientState.ts`
60
+ * `applyProposals`). Getting that attribution right is load-bearing — the
61
+ * `refs/marmot/protocol-core/group-messaging.md` admin gate's self_remove rule
62
+ * and its non-admin self-update carve-out
63
+ * both branch on per-proposal sender identity.
64
+ *
65
+ * Exists so `ForkRecovery`'s CONV-04 known-state short-circuit can run the same
66
+ * admin-policy callback that `#treeResolution` runs on the identical class of
67
+ * persisted edge (CR-11) — that seam cannot replay the commit, so it cannot
68
+ * obtain these from `processMessage`.
69
+ *
70
+ * Returns `undefined` under exactly the same conditions as
71
+ * {@link framedCommitProposals}: a non-public-message commit, or a
72
+ * `ProposalRef` absent from `parentState`.
73
+ */
74
+ export declare function framedCommitProposalsWithSender(message: MlsMessage, parentState: ClientState): {
75
+ proposals: ProposalWithSender[];
76
+ senderLeafIndex: LeafIndex | undefined;
77
+ } | undefined;
@@ -0,0 +1,120 @@
1
+ /** @module @category Engine */
2
+ import { bytesToBase64, contentTypes, proposalOrRefTypes, senderTypes, wireformats, } from "ts-mls";
3
+ /**
4
+ * Marmot v2 carries MLS handshake content — Commits and Proposals — as
5
+ * `PublicMessage`, while application messages stay `PrivateMessage`
6
+ * (`darkmatter/spec/foundation/mls-protocol.md`, "Handshake wire format"). The
7
+ * kind-445 transport wrap provides confidentiality, so relays never see
8
+ * plaintext handshake bytes. The inbound pipeline therefore cannot assume a
9
+ * single wire format when classifying or ordering framed messages; these
10
+ * accessors read the framed fields uniformly across both carriages.
11
+ */
12
+ /**
13
+ * The MLS framed content type (application / proposal / commit) carried by a
14
+ * private- or public-message {@link MlsMessage}, or `undefined` for non-framed
15
+ * messages (welcome / key package / group info).
16
+ */
17
+ export function framedContentType(message) {
18
+ switch (message.wireformat) {
19
+ case wireformats.mls_private_message:
20
+ return message.privateMessage.contentType;
21
+ case wireformats.mls_public_message:
22
+ return message.publicMessage.content.contentType;
23
+ default:
24
+ return undefined;
25
+ }
26
+ }
27
+ /**
28
+ * The MLS epoch carried by a private- or public-message {@link MlsMessage}, or
29
+ * `undefined` for non-framed messages. Normalizes to `bigint` regardless of how
30
+ * each wire format models the field.
31
+ */
32
+ export function framedEpoch(message) {
33
+ switch (message.wireformat) {
34
+ case wireformats.mls_private_message:
35
+ return BigInt(message.privateMessage.epoch);
36
+ case wireformats.mls_public_message:
37
+ return BigInt(message.publicMessage.content.epoch);
38
+ default:
39
+ return undefined;
40
+ }
41
+ }
42
+ /**
43
+ * The {@link Proposal}s a commit actually carries, read straight off the wire
44
+ * with NO `processMessage` replay — the union of its inline proposals and the
45
+ * proposals its `ProposalRef` entries name in `parentState.unappliedProposals`.
46
+ *
47
+ * This exists for the one seam that cannot replay: `ForkRecovery`'s CONV-04
48
+ * short-circuit reuses an already-known resulting state precisely BECAUSE the
49
+ * commit cannot be reprocessed (an `UpdatePath` never encrypts a path secret to
50
+ * the committer's own leaf, RFC 9420), so `withCapturedProposals` can never
51
+ * observe that commit's proposals. Without this, that seam had no way to run
52
+ * `validateCommitLegality` and silently grandfathered violations every other
53
+ * seam refuses (CR-04).
54
+ *
55
+ * Returns `undefined` — never a partial list — when the proposal set cannot be
56
+ * fully reconstructed:
57
+ * - the message is not a public-message commit (a `PrivateMessage`'s content
58
+ * is encrypted; Marmot v2 wires handshake content as `PublicMessage`, so
59
+ * this is a defensive branch), or
60
+ * - a `ProposalRef` names a proposal absent from `parentState`.
61
+ *
62
+ * Callers MUST treat `undefined` as "cannot validate" and fail closed, mirroring
63
+ * `#treeResolution`'s policy for any link it cannot re-validate.
64
+ *
65
+ * @param parentState The state the commit was applied to — the only state whose
66
+ * `unappliedProposals` can resolve this commit's refs.
67
+ */
68
+ export function framedCommitProposals(message, parentState) {
69
+ return framedCommitProposalsWithSender(message, parentState)?.proposals.map((entry) => entry.proposal);
70
+ }
71
+ /**
72
+ * The sender-attributed form of {@link framedCommitProposals}, plus the
73
+ * commit's own committer leaf index.
74
+ *
75
+ * This reproduces exactly what ts-mls's `applyProposals` assembles as
76
+ * `allProposals` and hands to an {@link IncomingMessageCallback}: an inline
77
+ * (by-value) proposal is attributed to the COMMITTER's leaf, while a
78
+ * `ProposalRef` carries the ORIGINAL proposer's leaf from
79
+ * `parentState.unappliedProposals` (`ts-mls/src/clientState.ts`
80
+ * `applyProposals`). Getting that attribution right is load-bearing — the
81
+ * `refs/marmot/protocol-core/group-messaging.md` admin gate's self_remove rule
82
+ * and its non-admin self-update carve-out
83
+ * both branch on per-proposal sender identity.
84
+ *
85
+ * Exists so `ForkRecovery`'s CONV-04 known-state short-circuit can run the same
86
+ * admin-policy callback that `#treeResolution` runs on the identical class of
87
+ * persisted edge (CR-11) — that seam cannot replay the commit, so it cannot
88
+ * obtain these from `processMessage`.
89
+ *
90
+ * Returns `undefined` under exactly the same conditions as
91
+ * {@link framedCommitProposals}: a non-public-message commit, or a
92
+ * `ProposalRef` absent from `parentState`.
93
+ */
94
+ export function framedCommitProposalsWithSender(message, parentState) {
95
+ if (message.wireformat !== wireformats.mls_public_message)
96
+ return undefined;
97
+ const content = message.publicMessage.content;
98
+ if (content.contentType !== contentTypes.commit)
99
+ return undefined;
100
+ const senderLeafIndex = content.sender.senderType === senderTypes.member
101
+ ? content.sender.leafIndex
102
+ : undefined;
103
+ const proposals = [];
104
+ for (const entry of content.commit.proposals) {
105
+ if (entry.proposalOrRefType === proposalOrRefTypes.proposal) {
106
+ // By-value proposals are attributed to the committer, exactly as
107
+ // ts-mls's `applyProposals` does.
108
+ proposals.push({ proposal: entry.proposal, senderLeafIndex });
109
+ continue;
110
+ }
111
+ // ts-mls keys `unappliedProposals` by the base64 of the proposal
112
+ // reference (see its own `applyProposals` lookup). The staged entry
113
+ // already carries the original proposer's leaf.
114
+ const staged = parentState.unappliedProposals[bytesToBase64(entry.reference)];
115
+ if (!staged)
116
+ return undefined;
117
+ proposals.push(staged);
118
+ }
119
+ return { proposals, senderLeafIndex };
120
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `marmot-engine` has no root barrel — subpaths only (`./core`, `./engine`,
3
+ * `./audit`, `./mls`; architecture.md boundary rule 5). This file is not
4
+ * part of the package's public API (nothing in `package.json#exports`
5
+ * points at it) and exists solely as the boundary-proof convention every
6
+ * workspace shell carries (AC-STRUCT-6): a real, resolved `import type`
7
+ * naming each of this package's permitted AC-STRUCT-3 neighbours — for
8
+ * marmot-engine, that is `ts-mls` alone, the one external dependency this
9
+ * package is the sole workspace owner of (ADR-002, ADR-005).
10
+ */
11
+ import type { ClientState } from "ts-mls";
12
+ export type { ClientState as _ACStruct6BoundaryProof };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/mls.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @module @category MLS re-export seam
3
+ *
4
+ * `marmot-engine` is the sole workspace package permitted to depend on
5
+ * `ts-mls` (ADR-005, ADR-002's single-instance rule — `ts-mls` brands types
6
+ * with `unique symbol`, which do not unify across two copies even at an
7
+ * identical version string). Every other package reaches ts-mls's types
8
+ * through this subpath (or `@941design/marmot/mls`, which re-exports this
9
+ * one), never through a direct dependency of their own.
10
+ */
11
+ export * from "ts-mls";
package/dist/mls.js ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @module @category MLS re-export seam
3
+ *
4
+ * `marmot-engine` is the sole workspace package permitted to depend on
5
+ * `ts-mls` (ADR-005, ADR-002's single-instance rule — `ts-mls` brands types
6
+ * with `unique symbol`, which do not unify across two copies even at an
7
+ * identical version string). Every other package reaches ts-mls's types
8
+ * through this subpath (or `@941design/marmot/mls`, which re-exports this
9
+ * one), never through a direct dependency of their own.
10
+ */
11
+ export * from "ts-mls";
@@ -0,0 +1,3 @@
1
+ import createDebug from "debug";
2
+ /** Root namespace logger for the marmot-ts package. Enable with DEBUG=marmot-ts:* */
3
+ export declare const logger: createDebug.Debugger;
@@ -0,0 +1,3 @@
1
+ import createDebug from "debug";
2
+ /** Root namespace logger for the marmot-ts package. Enable with DEBUG=marmot-ts:* */
3
+ export const logger = createDebug("marmot-ts");
@@ -0,0 +1,38 @@
1
+ import { NostrEvent, Rumor } from "./nostr.js";
2
+ /**
3
+ * Encoding format for binary content in Nostr events.
4
+ * - 'base64': Base64 encoding (~33% smaller, required for new implementations)
5
+ * - 'hex': Hexadecimal encoding (deprecated, supported for backward compatibility)
6
+ */
7
+ export type EncodingFormat = "base64" | "hex";
8
+ /**
9
+ * Encodes binary data to a string using the specified format.
10
+ *
11
+ * @param bytes - The binary data to encode
12
+ * @param format - The encoding format ('base64' or 'hex')
13
+ * @returns The encoded string
14
+ */
15
+ export declare function encodeContent(bytes: Uint8Array, format: EncodingFormat): string;
16
+ /**
17
+ * Decodes a string to binary data using the specified or auto-detected format.
18
+ *
19
+ * @param content - The encoded string
20
+ * @param format - Optional encoding format. If not specified, will auto-detect.
21
+ * @returns The decoded binary data
22
+ * @throws Error if the content cannot be decoded
23
+ */
24
+ export declare function decodeContent(content: string, format?: EncodingFormat): Uint8Array;
25
+ /**
26
+ * Detects the encoding format of a content string.
27
+ *
28
+ * @param content - The encoded string to analyze
29
+ * @returns The detected encoding format
30
+ */
31
+ export declare function detectEncoding(content: string): EncodingFormat;
32
+ /**
33
+ * Extracts the encoding tag from a Nostr event.
34
+ *
35
+ * @param event - The Nostr event to check
36
+ * @returns The encoding format specified in the event, or undefined if not present
37
+ */
38
+ export declare function getEncodingTag(event: NostrEvent | Rumor): EncodingFormat | undefined;