@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,141 @@
1
+ /** @module @category Core - App Components */
2
+ import { ClientState, GroupContextExtension, Proposal, ProposalWithSender } from "ts-mls";
3
+ import { AppComponentId } from "./ids.js";
4
+ /**
5
+ * Ported commit-legality validators for the Marmot app-component layer.
6
+ *
7
+ * Both validators here are pure, seam-agnostic, and non-throwing by design
8
+ * (D-01/D-02 split): they read plain `GroupContextExtension[]` values and
9
+ * return a typed {@link CommitIntegrityViolation} instead of throwing, so
10
+ * every calling seam (send, inbound, convergence/replay) decides its own
11
+ * disposition — throw, `rejected`, or drop-edge — for the same violation.
12
+ *
13
+ * @see refs/mdk/crates/cgka-engine/src/app_components.rs
14
+ * @see Marmot v2 spec: app-components/README.md, app-components/admin-policy-v1.md
15
+ */
16
+ /** The reason a commit was found to violate a ported MDK commit-legality rule. */
17
+ export type CommitIntegrityViolationReason = "component-integrity" | "admin-leaf-coupling" | "disband-legality";
18
+ /**
19
+ * A typed, non-throwing violation returned by {@link validateAppComponentIntegrity},
20
+ * {@link validateAdminLeafCoupling}, or {@link validateCommitLegality}.
21
+ *
22
+ * `detail` is a diagnostic string naming component ids and counts only — never
23
+ * raw pubkeys or other protocol-sensitive material (diagnostics-privacy rule,
24
+ * see foundation/errors.md). The protocol-visible signal is `reason`.
25
+ */
26
+ export interface CommitIntegrityViolation {
27
+ reason: CommitIntegrityViolationReason;
28
+ detail: string;
29
+ }
30
+ /**
31
+ * A single `AppDataUpdate` operation extracted from a commit's proposals, in
32
+ * the shape {@link validateAppComponentIntegrity} consumes. `data === undefined`
33
+ * means the operation is a Remove (mirrors MDK's `Option<&[u8]>` with `None` =
34
+ * Remove).
35
+ */
36
+ export interface AppDataUpdateOp {
37
+ componentId: AppComponentId;
38
+ data: Uint8Array | undefined;
39
+ }
40
+ /**
41
+ * Turns a commit's `Proposal[]` into the `AppDataUpdateOp[]` shape every seam
42
+ * feeds to {@link validateAppComponentIntegrity} (and, later, the shared seam
43
+ * adapter). This is the single adapter every seam uses so the proposal → op
44
+ * mapping is never re-implemented seam-locally.
45
+ *
46
+ * Preserves commit order and does not deduplicate — a component id may legally
47
+ * carry more than one `AppDataUpdate` op in a single commit.
48
+ */
49
+ export declare function collectAppDataUpdateOps(proposals: readonly Proposal[]): AppDataUpdateOp[];
50
+ /**
51
+ * Ported from `validate_app_component_integrity_for_staged_commit`: rejects a
52
+ * commit whose resulting GroupContext strips or rewrites Marmot component
53
+ * state outside the validated `AppDataUpdate` channel.
54
+ *
55
+ * Enforced rules, in order (mirrors the MDK rustdoc numbering):
56
+ * 1. the `app_data_dictionary` extension itself may never be dropped if it was
57
+ * present before;
58
+ * 2. the `app_components` id (`0x0001`) and every id in the CURRENT epoch's
59
+ * required-component-id list may never be dropped;
60
+ * 3. every dictionary entry that changes relative to the current epoch —
61
+ * added, rewritten, or removed — must match one of this commit's own
62
+ * `AppDataUpdate` operations.
63
+ *
64
+ * @param args.requiredIds MUST be derived by the caller from the CURRENT
65
+ * (pre-commit) extensions — see Pitfall 2 in 03-RESEARCH.md. Deriving this
66
+ * from `resultingExtensions` would let a commit add an id to `app_components`
67
+ * and thereby protect that same id in the same commit, which is the exact bug
68
+ * class this validator exists to close.
69
+ * @see refs/mdk/crates/cgka-engine/src/app_components.rs `validate_app_component_integrity_for_staged_commit`
70
+ * @see Marmot v2 spec: app-components/README.md "Update Processing", "Unknown Data"
71
+ */
72
+ export declare function validateAppComponentIntegrity(args: {
73
+ currentExtensions: GroupContextExtension[];
74
+ resultingExtensions: GroupContextExtension[];
75
+ appDataUpdateOps: readonly AppDataUpdateOp[];
76
+ requiredIds: readonly AppComponentId[];
77
+ }): CommitIntegrityViolation | undefined;
78
+ /**
79
+ * Ported from `validate_admin_leaf_coupling_for_staged_commit`: enforces the
80
+ * admin-policy resulting-epoch invariant (admin-policy-v1.md "Validation") —
81
+ * every admin key in the resulting epoch's admin set MUST correspond to an
82
+ * account with at least one member leaf in the resulting epoch.
83
+ *
84
+ * `resultingMemberAccounts` is the set of hex account pubkeys that have at
85
+ * least one member leaf in the RESULTING epoch (D-08: account-level, not
86
+ * leaf-level — an account with two leaves survives if only one is removed).
87
+ * Callers derive it from the post-apply state; this validator stays pure and
88
+ * MLS-free.
89
+ *
90
+ * When the resulting extensions carry no admin-policy bytes, this evaluates
91
+ * the carried-forward (current-epoch) admin set instead of skipping the check
92
+ * (Pitfall 3): a membership-only commit that de-leafs an admin without
93
+ * touching admin-policy bytes must still be rejected.
94
+ *
95
+ * An empty resolved admin set returns `undefined` (vacuously satisfied):
96
+ * component bytes cannot encode an empty admin list, so an empty resolved set
97
+ * means the epoch carries no admin-policy state at all — not a bypass, per
98
+ * MDK's own documented rationale for the same early return.
99
+ *
100
+ * Does NOT special-case SelfRemove (Pitfall 4): a non-admin's SelfRemove never
101
+ * changes the admin set and passes trivially here; an admin's SelfRemove is
102
+ * already refused earlier by `createAdminCommitPolicyCallback`
103
+ * (`src/engine/admin-policy.ts`), so this validator never needs its own
104
+ * carve-out for it.
105
+ *
106
+ * Seam: `resultingAdminPolicyOp`, when given, REPLACES `resultingExtensions` as the
107
+ * source of the resulting admin set — the caller's last admin-policy op, whose
108
+ * bytes are decoded here. A `remove` op (`data === undefined`) and bytes that
109
+ * do not decode are the "did not decode" violation. Only
110
+ * {@link validateCommitLegality} passes it, for a receiver the commit removes.
111
+ *
112
+ * @see refs/mdk/crates/cgka-engine/src/app_components.rs `validate_admin_leaf_coupling_for_staged_commit`, `reject_admins_without_member_accounts`
113
+ * @see Marmot v2 spec: app-components/admin-policy-v1.md "Validation"
114
+ */
115
+ export declare function validateAdminLeafCoupling(args: {
116
+ currentExtensions: GroupContextExtension[];
117
+ resultingExtensions: GroupContextExtension[];
118
+ resultingMemberAccounts: readonly string[];
119
+ resultingAdminPolicyOp?: AppDataUpdateOp;
120
+ }): CommitIntegrityViolation | undefined;
121
+ /**
122
+ * The single shared seam adapter for commit legality: derives every argument
123
+ * {@link validateAppComponentIntegrity} and {@link validateAdminLeafCoupling}
124
+ * need from `parentState`/`resultingState`/`proposals`, so no seam re-derives
125
+ * them independently (the mdk#707 bug class — "a guard that exists on one
126
+ * seam only is a documented bug").
127
+ *
128
+ * Stays pure: reads two `ClientState` values, performs no I/O, and calls
129
+ * nothing from `src/engine` or `src/client`.
130
+ *
131
+ * Each calling seam supplies its own disposition for a returned violation:
132
+ * throw on send (D-02), `rejected` with the violation's `reason` on inbound
133
+ * (D-03), or drop the candidate edge on convergence/replay (D-04/D-09). This
134
+ * adapter itself is seam-agnostic.
135
+ */
136
+ export declare function validateCommitLegality(args: {
137
+ parentState: ClientState;
138
+ resultingState: ClientState;
139
+ proposals: readonly (Proposal | ProposalWithSender)[];
140
+ committerLeafIndex?: number;
141
+ }): CommitIntegrityViolation | undefined;
@@ -0,0 +1,293 @@
1
+ /** @module @category Core - App Components */
2
+ import { appDataUpdateProposalType, getAppDataDictionary, } from "ts-mls";
3
+ import { decodeAdminPolicyV1 } from "./admin-policy.js";
4
+ import { getAdminPolicy, getAppComponents } from "./dictionary.js";
5
+ import { getGroupMemberPubkeys } from "../group-members.js";
6
+ import { APP_COMPONENTS_COMPONENT_ID, GROUP_ADMIN_POLICY_COMPONENT_ID, } from "./ids.js";
7
+ import { bytesEqual } from "./bytes.js";
8
+ import { classifyDisbandCommit, } from "./disband-validation.js";
9
+ /**
10
+ * Turns a commit's `Proposal[]` into the `AppDataUpdateOp[]` shape every seam
11
+ * feeds to {@link validateAppComponentIntegrity} (and, later, the shared seam
12
+ * adapter). This is the single adapter every seam uses so the proposal → op
13
+ * mapping is never re-implemented seam-locally.
14
+ *
15
+ * Preserves commit order and does not deduplicate — a component id may legally
16
+ * carry more than one `AppDataUpdate` op in a single commit.
17
+ */
18
+ export function collectAppDataUpdateOps(proposals) {
19
+ const ops = [];
20
+ for (const proposal of proposals) {
21
+ if (proposal.proposalType !== appDataUpdateProposalType ||
22
+ !("appDataUpdate" in proposal))
23
+ continue;
24
+ const { appDataUpdate } = proposal;
25
+ if (appDataUpdate.operation === "update") {
26
+ ops.push({
27
+ componentId: appDataUpdate.componentId,
28
+ data: appDataUpdate.update,
29
+ });
30
+ }
31
+ else {
32
+ ops.push({ componentId: appDataUpdate.componentId, data: undefined });
33
+ }
34
+ }
35
+ return ops;
36
+ }
37
+ /**
38
+ * Ported from `validate_app_component_integrity_for_staged_commit`: rejects a
39
+ * commit whose resulting GroupContext strips or rewrites Marmot component
40
+ * state outside the validated `AppDataUpdate` channel.
41
+ *
42
+ * Enforced rules, in order (mirrors the MDK rustdoc numbering):
43
+ * 1. the `app_data_dictionary` extension itself may never be dropped if it was
44
+ * present before;
45
+ * 2. the `app_components` id (`0x0001`) and every id in the CURRENT epoch's
46
+ * required-component-id list may never be dropped;
47
+ * 3. every dictionary entry that changes relative to the current epoch —
48
+ * added, rewritten, or removed — must match one of this commit's own
49
+ * `AppDataUpdate` operations.
50
+ *
51
+ * @param args.requiredIds MUST be derived by the caller from the CURRENT
52
+ * (pre-commit) extensions — see Pitfall 2 in 03-RESEARCH.md. Deriving this
53
+ * from `resultingExtensions` would let a commit add an id to `app_components`
54
+ * and thereby protect that same id in the same commit, which is the exact bug
55
+ * class this validator exists to close.
56
+ * @see refs/mdk/crates/cgka-engine/src/app_components.rs `validate_app_component_integrity_for_staged_commit`
57
+ * @see Marmot v2 spec: app-components/README.md "Update Processing", "Unknown Data"
58
+ */
59
+ export function validateAppComponentIntegrity(args) {
60
+ // Read the raw dictionary generically (not the typed accessors in
61
+ // dictionary.ts) so unknown component ids participate in the diff.
62
+ const current = getAppDataDictionary(args.currentExtensions);
63
+ const resulting = getAppDataDictionary(args.resultingExtensions);
64
+ // Rule 1: the app_data_dictionary extension itself may never be dropped.
65
+ if (current !== undefined && resulting === undefined) {
66
+ return {
67
+ reason: "component-integrity",
68
+ detail: "resulting GroupContext drops the app_data_dictionary",
69
+ };
70
+ }
71
+ // Rule 2: the protected set (current required ids + 0x0001) may never be
72
+ // dropped.
73
+ const protectedIds = new Set(args.requiredIds);
74
+ protectedIds.add(APP_COMPONENTS_COMPONENT_ID);
75
+ for (const id of protectedIds) {
76
+ const currentlyPresent = current?.some((c) => c.componentId === id) ?? false;
77
+ const stillPresent = resulting?.some((c) => c.componentId === id) ?? false;
78
+ if (currentlyPresent && !stillPresent) {
79
+ return {
80
+ reason: "component-integrity",
81
+ detail: `drops required app component 0x${id.toString(16)}`,
82
+ };
83
+ }
84
+ }
85
+ // Rule 3: every changed entry must be attributable to one of this commit's
86
+ // own AppDataUpdate ops.
87
+ const opsByComponent = new Map();
88
+ for (const op of args.appDataUpdateOps) {
89
+ const list = opsByComponent.get(op.componentId) ?? [];
90
+ list.push(op.data);
91
+ opsByComponent.set(op.componentId, list);
92
+ }
93
+ const allIds = new Set();
94
+ for (const entry of current ?? [])
95
+ allIds.add(entry.componentId);
96
+ for (const entry of resulting ?? [])
97
+ allIds.add(entry.componentId);
98
+ for (const id of allIds) {
99
+ const before = current?.find((c) => c.componentId === id)?.data;
100
+ const after = resulting?.find((c) => c.componentId === id)?.data;
101
+ if (bytesEqual(before, after))
102
+ continue;
103
+ const allowed = opsByComponent.get(id);
104
+ const backed = allowed?.some((candidate) => bytesEqual(candidate, after));
105
+ if (!backed) {
106
+ return {
107
+ reason: "component-integrity",
108
+ detail: `changes app component 0x${id.toString(16)} outside an AppDataUpdate proposal`,
109
+ };
110
+ }
111
+ }
112
+ return undefined;
113
+ }
114
+ /**
115
+ * Ported from `validate_admin_leaf_coupling_for_staged_commit`: enforces the
116
+ * admin-policy resulting-epoch invariant (admin-policy-v1.md "Validation") —
117
+ * every admin key in the resulting epoch's admin set MUST correspond to an
118
+ * account with at least one member leaf in the resulting epoch.
119
+ *
120
+ * `resultingMemberAccounts` is the set of hex account pubkeys that have at
121
+ * least one member leaf in the RESULTING epoch (D-08: account-level, not
122
+ * leaf-level — an account with two leaves survives if only one is removed).
123
+ * Callers derive it from the post-apply state; this validator stays pure and
124
+ * MLS-free.
125
+ *
126
+ * When the resulting extensions carry no admin-policy bytes, this evaluates
127
+ * the carried-forward (current-epoch) admin set instead of skipping the check
128
+ * (Pitfall 3): a membership-only commit that de-leafs an admin without
129
+ * touching admin-policy bytes must still be rejected.
130
+ *
131
+ * An empty resolved admin set returns `undefined` (vacuously satisfied):
132
+ * component bytes cannot encode an empty admin list, so an empty resolved set
133
+ * means the epoch carries no admin-policy state at all — not a bypass, per
134
+ * MDK's own documented rationale for the same early return.
135
+ *
136
+ * Does NOT special-case SelfRemove (Pitfall 4): a non-admin's SelfRemove never
137
+ * changes the admin set and passes trivially here; an admin's SelfRemove is
138
+ * already refused earlier by `createAdminCommitPolicyCallback`
139
+ * (`src/engine/admin-policy.ts`), so this validator never needs its own
140
+ * carve-out for it.
141
+ *
142
+ * Seam: `resultingAdminPolicyOp`, when given, REPLACES `resultingExtensions` as the
143
+ * source of the resulting admin set — the caller's last admin-policy op, whose
144
+ * bytes are decoded here. A `remove` op (`data === undefined`) and bytes that
145
+ * do not decode are the "did not decode" violation. Only
146
+ * {@link validateCommitLegality} passes it, for a receiver the commit removes.
147
+ *
148
+ * @see refs/mdk/crates/cgka-engine/src/app_components.rs `validate_admin_leaf_coupling_for_staged_commit`, `reject_admins_without_member_accounts`
149
+ * @see Marmot v2 spec: app-components/admin-policy-v1.md "Validation"
150
+ */
151
+ export function validateAdminLeafCoupling(args) {
152
+ let resultingSet;
153
+ try {
154
+ if (args.resultingAdminPolicyOp === undefined)
155
+ resultingSet = getAdminPolicy(args.resultingExtensions);
156
+ else if (args.resultingAdminPolicyOp.data === undefined)
157
+ throw new Error("the commit's last admin-policy operation is a remove");
158
+ else
159
+ resultingSet = decodeAdminPolicyV1(args.resultingAdminPolicyOp.data);
160
+ }
161
+ catch {
162
+ return {
163
+ reason: "admin-leaf-coupling",
164
+ detail: "resulting admin-policy component did not decode",
165
+ };
166
+ }
167
+ let resultingAdmins;
168
+ if (resultingSet !== undefined) {
169
+ resultingAdmins = resultingSet;
170
+ }
171
+ else {
172
+ try {
173
+ resultingAdmins = getAdminPolicy(args.currentExtensions) ?? [];
174
+ }
175
+ catch {
176
+ return {
177
+ reason: "admin-leaf-coupling",
178
+ detail: "carried-forward admin-policy component did not decode",
179
+ };
180
+ }
181
+ }
182
+ // An empty resolved admin set means the epoch has no admin-policy state at
183
+ // all (component bytes cannot encode an empty list) — vacuously satisfied,
184
+ // not a bypass.
185
+ if (resultingAdmins.length === 0)
186
+ return undefined;
187
+ const memberAccounts = new Set(args.resultingMemberAccounts);
188
+ const orphaned = resultingAdmins.filter((admin) => !memberAccounts.has(admin));
189
+ if (orphaned.length > 0) {
190
+ return {
191
+ reason: "admin-leaf-coupling",
192
+ detail: `${orphaned.length} admin key(s) have no member leaf in the resulting epoch`,
193
+ };
194
+ }
195
+ return undefined;
196
+ }
197
+ /**
198
+ * The single shared seam adapter for commit legality: derives every argument
199
+ * {@link validateAppComponentIntegrity} and {@link validateAdminLeafCoupling}
200
+ * need from `parentState`/`resultingState`/`proposals`, so no seam re-derives
201
+ * them independently (the mdk#707 bug class — "a guard that exists on one
202
+ * seam only is a documented bug").
203
+ *
204
+ * Stays pure: reads two `ClientState` values, performs no I/O, and calls
205
+ * nothing from `src/engine` or `src/client`.
206
+ *
207
+ * Each calling seam supplies its own disposition for a returned violation:
208
+ * throw on send (D-02), `rejected` with the violation's `reason` on inbound
209
+ * (D-03), or drop the candidate edge on convergence/replay (D-04/D-09). This
210
+ * adapter itself is seam-agnostic.
211
+ */
212
+ export function validateCommitLegality(args) {
213
+ const proposalsWithSenders = args.proposals.map((item) => "proposal" in item
214
+ ? item
215
+ : { proposal: item, senderLeafIndex: undefined });
216
+ const proposals = proposalsWithSenders.map(({ proposal }) => proposal);
217
+ const appDataUpdateOps = collectAppDataUpdateOps(proposals);
218
+ // The `app_components` (0x0001) bytes are attacker-influenceable: an admin
219
+ // can land an AppDataUpdate writing arbitrary bytes to that id (Rule 3
220
+ // accepts it because the change IS backed by that commit's own op, and
221
+ // Rule 2 only checks presence, never decodability). From the next commit
222
+ // onward every seam decodes those bytes here, and `decodeComponentsList`
223
+ // throws on malformed input or a duplicate id. Honour this adapter's
224
+ // documented non-throwing contract (D-01/D-02) by converting that into a
225
+ // typed violation — otherwise the throw escapes the convergence/replay
226
+ // seams (`fork-recovery.ts`, `group-engine.ts` tree re-convergence), which
227
+ // do not wrap this call, and aborts the ingest generator before the caller
228
+ // can persist state.
229
+ let requiredIds;
230
+ try {
231
+ requiredIds =
232
+ getAppComponents(args.parentState.groupContext.extensions) ?? [];
233
+ }
234
+ catch {
235
+ return {
236
+ reason: "component-integrity",
237
+ detail: "current app_components component did not decode",
238
+ };
239
+ }
240
+ const integrityViolation = validateAppComponentIntegrity({
241
+ currentExtensions: args.parentState.groupContext.extensions,
242
+ resultingExtensions: args.resultingState.groupContext.extensions,
243
+ appDataUpdateOps,
244
+ requiredIds,
245
+ });
246
+ if (integrityViolation)
247
+ return integrityViolation;
248
+ const disband = classifyDisbandCommit({
249
+ parentState: args.parentState,
250
+ resultingState: args.resultingState,
251
+ proposals: proposalsWithSenders,
252
+ committerLeafIndex: args.committerLeafIndex,
253
+ });
254
+ if (disband.kind === "violation")
255
+ return { reason: "disband-legality", detail: disband.detail };
256
+ // Seam: a valid disband's resulting admin set is its exact inline `[actor]`
257
+ // replacement, and the actor's leaf is the one it keeps, so admin-leaf
258
+ // coupling holds by construction. Checking it against `resultingState`
259
+ // instead is wrong on every removed receiver: ts-mls's tombstone carries the
260
+ // PARENT GroupContext (its admin set) beside the post-commit roster, so any
261
+ // other parent admin reads as orphaned and a multi-admin group's disband is
262
+ // rejected by everyone it removes.
263
+ if (disband.kind === "validDisband")
264
+ return undefined;
265
+ const resultingMemberAccounts = getGroupMemberPubkeys(args.resultingState);
266
+ // Seam: the same tombstone shape breaks the coupling check for a removed
267
+ // ADMIN. Its `resultingState` carries the PARENT's admin set beside the
268
+ // post-commit roster, so the admin the commit removes (whose same commit
269
+ // carries the engine's D-05 splice dropping it from the admin list) reads as
270
+ // an orphan, and the removed admin rejected the very commit that removes it.
271
+ // The resulting admin set is the commit's own LAST admin-policy op in commit
272
+ // order (a component resolves to its last update). A trailing `remove` op or
273
+ // undecodable bytes are the "did not decode" violation. A blanket skip is
274
+ // wrong: unlike a disband (its admin set is pinned by `classifyDisbandCommit`),
275
+ // a plain removal's is not, and a skip would let a removed device accept a
276
+ // commit every remaining member rejects. A tombstone whose commit carries no
277
+ // admin-policy op keeps checking the carried-forward set.
278
+ // Not covered (predates this seam): an admin set written through a
279
+ // group_context_extensions proposal instead of an AppDataUpdate op is
280
+ // invisible here, so a removed receiver still checks the parent's set for it.
281
+ let resultingAdminPolicyOp;
282
+ if (args.resultingState.groupActiveState?.kind === "removedFromGroup") {
283
+ for (const op of appDataUpdateOps)
284
+ if (op.componentId === GROUP_ADMIN_POLICY_COMPONENT_ID)
285
+ resultingAdminPolicyOp = op;
286
+ }
287
+ return validateAdminLeafCoupling({
288
+ currentExtensions: args.parentState.groupContext.extensions,
289
+ resultingExtensions: args.resultingState.groupContext.extensions,
290
+ resultingMemberAccounts,
291
+ ...(resultingAdminPolicyOp === undefined ? {} : { resultingAdminPolicyOp }),
292
+ });
293
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Codec for `marmot.group.message-retention.v1` (`0x8005`) — the disappearing
3
+ * message timer. Replaces the `disappearing_message_secs` field of the legacy
4
+ * `marmot_group_data` monolith.
5
+ *
6
+ * Wire (Marmot binary profile):
7
+ * uint64 disappearing_message_secs; // fixed 8-byte big-endian, NO length prefix
8
+ *
9
+ * A value of `0` disables disappearing messages.
10
+ *
11
+ * @see darkmatter `crates/marmot-app/src/groups.rs` `AppGroupMessageRetentionComponent`
12
+ * @see Marmot v2 spec: `app-components/message-retention-v1.md`
13
+ */
14
+ /** Encodes a disappearing-message timer (seconds) to component `data` bytes. */
15
+ export declare function encodeMessageRetentionV1(disappearingMessageSecs: number | bigint): Uint8Array;
16
+ /** Decodes `marmot.group.message-retention.v1` component `data` bytes. */
17
+ export declare function decodeMessageRetentionV1(data: Uint8Array): bigint;
@@ -0,0 +1,26 @@
1
+ /** @module @category Core - App Components */
2
+ import { BinaryReader, BinaryWriter } from "../binary.js";
3
+ /**
4
+ * Codec for `marmot.group.message-retention.v1` (`0x8005`) — the disappearing
5
+ * message timer. Replaces the `disappearing_message_secs` field of the legacy
6
+ * `marmot_group_data` monolith.
7
+ *
8
+ * Wire (Marmot binary profile):
9
+ * uint64 disappearing_message_secs; // fixed 8-byte big-endian, NO length prefix
10
+ *
11
+ * A value of `0` disables disappearing messages.
12
+ *
13
+ * @see darkmatter `crates/marmot-app/src/groups.rs` `AppGroupMessageRetentionComponent`
14
+ * @see Marmot v2 spec: `app-components/message-retention-v1.md`
15
+ */
16
+ /** Encodes a disappearing-message timer (seconds) to component `data` bytes. */
17
+ export function encodeMessageRetentionV1(disappearingMessageSecs) {
18
+ return new BinaryWriter().uint64(disappearingMessageSecs).build();
19
+ }
20
+ /** Decodes `marmot.group.message-retention.v1` component `data` bytes. */
21
+ export function decodeMessageRetentionV1(data) {
22
+ const reader = new BinaryReader(data);
23
+ const secs = reader.uint64();
24
+ reader.end();
25
+ return secs;
26
+ }
@@ -0,0 +1,8 @@
1
+ export interface NostrRoutingV1 {
2
+ nostrGroupId: Uint8Array;
3
+ relays: string[];
4
+ }
5
+ /** Encodes a {@link NostrRoutingV1} to its component `data` bytes. */
6
+ export declare function encodeNostrRoutingV1(routing: NostrRoutingV1): Uint8Array;
7
+ /** Decodes `marmot.transport.nostr.routing.v1` component `data` bytes. */
8
+ export declare function decodeNostrRoutingV1(data: Uint8Array): NostrRoutingV1;
@@ -0,0 +1,92 @@
1
+ /** @module @category Core - App Components */
2
+ import { BinaryReader, BinaryWriter, decodeUtf8, encodeUtf8, } from "../binary.js";
3
+ import { isValidRelayUrl } from "../../utils/relay-url.js";
4
+ import { compareBytes } from "./bytes.js";
5
+ /**
6
+ * Codec for `marmot.transport.nostr.routing.v1` (`0x8004`) — the public Nostr
7
+ * group id and the relay set used to route the group's transport. Replaces the
8
+ * `nostr_group_id`/`relays` fields of the legacy `marmot_group_data` monolith.
9
+ *
10
+ * Wire (Marmot binary profile):
11
+ * opaque nostr_group_id[32]; // fixed 32 bytes, no length prefix
12
+ * MarmotNostrRelayV1 relays<V>; // QUIC-varint byte length over the entries
13
+ * // each MarmotNostrRelayV1 = opaque url<1..512> (QUIC-varint length + UTF-8)
14
+ *
15
+ * Relays are sorted ascending by raw UTF-8 byte value, MUST be unique, and the
16
+ * list MUST be non-empty. The decoder re-checks sort + uniqueness.
17
+ *
18
+ * @see darkmatter `crates/traits/src/app_components.rs` `encode_nostr_routing_v1`
19
+ * @see Marmot v2 spec: `app-components/nostr-routing-v1.md`
20
+ */
21
+ const NOSTR_GROUP_ID_BYTES = 32;
22
+ const RELAY_URL_MAX_BYTES = 512;
23
+ function validateRelay(url) {
24
+ if (encodeUtf8(url).length > RELAY_URL_MAX_BYTES) {
25
+ throw new Error("Nostr relay URL exceeds 512 bytes");
26
+ }
27
+ if (!isValidRelayUrl(url))
28
+ throw new Error("Invalid relay URL");
29
+ // darkmatter `validate_nostr_relay_url` (routing.rs) also rejects credentials,
30
+ // fragments, and a missing host. This validation runs on both encode and
31
+ // decode, so omitting it accepts routing bytes that a conformant peer rejects
32
+ // → cross-implementation commit-acceptance fork. isValidRelayUrl already
33
+ // guaranteed the URL parses and is ws/wss, so `new URL` will not throw here.
34
+ const parsed = new URL(url);
35
+ if (parsed.username !== "" || parsed.password !== "")
36
+ throw new Error("Nostr relay URL must not include credentials");
37
+ if (parsed.hash !== "")
38
+ throw new Error("Nostr relay URL must not include a fragment");
39
+ if (parsed.hostname === "")
40
+ throw new Error("Nostr relay URL must include a host");
41
+ }
42
+ /** Encodes a {@link NostrRoutingV1} to its component `data` bytes. */
43
+ export function encodeNostrRoutingV1(routing) {
44
+ if (routing.nostrGroupId.length !== NOSTR_GROUP_ID_BYTES) {
45
+ throw new Error("nostr_group_id must be exactly 32 bytes");
46
+ }
47
+ // Sort by UTF-8 bytes + dedup to match the canonical Rust ordering.
48
+ const encoded = routing.relays.map((r) => [r, encodeUtf8(r)]);
49
+ encoded.sort((a, b) => compareBytes(a[1], b[1]));
50
+ const relays = [];
51
+ for (let i = 0; i < encoded.length; i++) {
52
+ if (i > 0 && compareBytes(encoded[i - 1][1], encoded[i][1]) === 0)
53
+ continue;
54
+ relays.push(encoded[i][0]);
55
+ }
56
+ if (relays.length === 0) {
57
+ throw new Error("Nostr routing must contain at least one relay");
58
+ }
59
+ for (const relay of relays)
60
+ validateRelay(relay);
61
+ const items = relays.map((r) => new BinaryWriter()
62
+ .opaque(encodeUtf8(r), { max: RELAY_URL_MAX_BYTES })
63
+ .build());
64
+ return new BinaryWriter().bytes(routing.nostrGroupId).vector(items).build();
65
+ }
66
+ /** Decodes `marmot.transport.nostr.routing.v1` component `data` bytes. */
67
+ export function decodeNostrRoutingV1(data) {
68
+ const reader = new BinaryReader(data);
69
+ const nostrGroupId = reader.bytes(NOSTR_GROUP_ID_BYTES);
70
+ const relayBytes = [];
71
+ const relays = reader.vector((item) => {
72
+ const bytes = item.opaque({ max: RELAY_URL_MAX_BYTES });
73
+ if (bytes.length === 0)
74
+ throw new Error("Nostr relay URL must not be empty");
75
+ relayBytes.push(bytes);
76
+ return decodeUtf8(bytes);
77
+ });
78
+ reader.end();
79
+ if (relays.length === 0) {
80
+ throw new Error("Nostr routing must contain at least one relay");
81
+ }
82
+ for (let i = 1; i < relayBytes.length; i++) {
83
+ const cmp = compareBytes(relayBytes[i - 1], relayBytes[i]);
84
+ if (cmp === 0)
85
+ throw new Error("Nostr relay URLs must be unique");
86
+ if (cmp > 0)
87
+ throw new Error("Nostr relay URLs must be sorted");
88
+ }
89
+ for (const relay of relays)
90
+ validateRelay(relay);
91
+ return { nostrGroupId, relays };
92
+ }
@@ -0,0 +1,26 @@
1
+ export interface HttpsUrlOptions {
2
+ /** Maximum byte length of both the input and normalized URL. */
3
+ maxLen: number;
4
+ /** Allow `http` URLs that point at a loopback host (encrypted-media only). */
5
+ allowLoopbackHttp?: boolean;
6
+ /**
7
+ * Trim surrounding whitespace from the input before parsing. The darkmatter
8
+ * encrypted-media endpoint validator does this (`raw.trim()`); the avatar
9
+ * validator does not.
10
+ */
11
+ trimInput?: boolean;
12
+ /** Prefix used in thrown error messages. */
13
+ label: string;
14
+ }
15
+ /**
16
+ * Validates and normalizes an `https` (optionally loopback-`http`) URL the way
17
+ * the darkmatter `validate_and_normalize_*` helpers do: no credentials, no
18
+ * fragment, a routable host, and length bounds. Returns the WHATWG-normalized
19
+ * URL. Both this and the Rust `url` crate implement the WHATWG URL Standard, so
20
+ * normalized output matches across implementations for ordinary URLs.
21
+ *
22
+ * Note (darkmatter parity): query strings are accepted and preserved (#374 —
23
+ * rejecting them forked commit acceptance), and the WHATWG trailing `/` is
24
+ * kept, never stripped (the serializer's output is the stored form).
25
+ */
26
+ export declare function validateAndNormalizeHttpsUrl(raw: string, opts: HttpsUrlOptions): string;
@@ -0,0 +1,44 @@
1
+ /** @module @category Core - App Components */
2
+ import { isLoopbackHost, rejectNonRoutableHost } from "./host-safety.js";
3
+ /**
4
+ * Validates and normalizes an `https` (optionally loopback-`http`) URL the way
5
+ * the darkmatter `validate_and_normalize_*` helpers do: no credentials, no
6
+ * fragment, a routable host, and length bounds. Returns the WHATWG-normalized
7
+ * URL. Both this and the Rust `url` crate implement the WHATWG URL Standard, so
8
+ * normalized output matches across implementations for ordinary URLs.
9
+ *
10
+ * Note (darkmatter parity): query strings are accepted and preserved (#374 —
11
+ * rejecting them forked commit acceptance), and the WHATWG trailing `/` is
12
+ * kept, never stripped (the serializer's output is the stored form).
13
+ */
14
+ export function validateAndNormalizeHttpsUrl(raw, opts) {
15
+ const { label, maxLen } = opts;
16
+ const trimmed = opts.trimInput ? raw.trim() : raw;
17
+ if (trimmed.length === 0)
18
+ throw new Error(`${label} must not be empty`);
19
+ if (utf8Len(trimmed) > maxLen)
20
+ throw new Error(`${label} exceeds ${maxLen} bytes`);
21
+ if (!URL.canParse(trimmed))
22
+ throw new Error(`${label} is invalid`);
23
+ const url = new URL(trimmed);
24
+ if (url.username !== "" || url.password !== "")
25
+ throw new Error(`${label} must not include credentials`);
26
+ if (url.hash !== "")
27
+ throw new Error(`${label} must not include a fragment`);
28
+ const scheme = url.protocol.replace(/:$/, "");
29
+ const isLoopbackHttp = scheme === "http" && opts.allowLoopbackHttp && isLoopbackHost(url.hostname);
30
+ if (scheme === "https") {
31
+ rejectNonRoutableHost(url.hostname, label);
32
+ }
33
+ else if (!isLoopbackHttp) {
34
+ throw new Error(`${label} scheme must be https`);
35
+ }
36
+ // WHATWG parse-and-serialize is the stored form; keep the trailing `/`.
37
+ const normalized = url.toString();
38
+ if (utf8Len(normalized) > maxLen)
39
+ throw new Error(`${label} exceeds ${maxLen} bytes`);
40
+ return normalized;
41
+ }
42
+ function utf8Len(s) {
43
+ return new TextEncoder().encode(s).length;
44
+ }