@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,226 @@
1
+ /** @module @category Core - Client State */
2
+ import { bytesToHex } from "@noble/hashes/utils.js";
3
+ import { clientStateDecoder, clientStateEncoder, ciphersuites, decode, defaultAppDataUpdateCallback, defaultKeyPackageEqualityConfig, defaultKeyRetentionConfig, defaultLifetimeConfig, defaultPaddingConfig, getAppDataDictionary, nodeTypes, encode, } from "ts-mls";
4
+ import { AGENT_TEXT_STREAM_QUIC_COMPONENT, AGENT_TEXT_STREAM_QUIC_COMPONENT_ID, APP_COMPONENTS_COMPONENT_ID, GROUP_ADMIN_POLICY_COMPONENT, GROUP_ADMIN_POLICY_COMPONENT_ID, GROUP_AVATAR_URL_COMPONENT, GROUP_AVATAR_URL_COMPONENT_ID, GROUP_BLOSSOM_IMAGE_COMPONENT, GROUP_BLOSSOM_IMAGE_COMPONENT_ID, GROUP_ENCRYPTED_MEDIA_COMPONENT, GROUP_ENCRYPTED_MEDIA_COMPONENT_ID, GROUP_MESSAGE_RETENTION_COMPONENT, GROUP_MESSAGE_RETENTION_COMPONENT_ID, GROUP_LIFECYCLE_COMPONENT, GROUP_LIFECYCLE_COMPONENT_ID, GROUP_PROFILE_COMPONENT, GROUP_PROFILE_COMPONENT_ID, NOSTR_ROUTING_COMPONENT, NOSTR_ROUTING_COMPONENT_ID, decodeAdminPolicyV1, decodeAgentTextStreamQuicPolicyV1, decodeComponentsList, decodeEncryptedMediaPolicyV1, decodeGroupAvatarUrlV1, decodeGroupProfileV1, decodeMessageRetentionV1, decodeGroupLifecycleV1, decodeNostrRoutingV1, getAdminPolicy, getEncryptedMediaPolicy, getGroupAvatarUrl, getGroupProfile, getMessageRetention, getGroupLifecycle, getNostrRouting, } from "./components/index.js";
5
+ import { getGroupMemberPubkeys } from "./group-members.js";
6
+ /** Default ClientConfig for Marmot. */
7
+ export const defaultMarmotClientConfig = {
8
+ keyRetentionConfig: defaultKeyRetentionConfig,
9
+ lifetimeConfig: defaultLifetimeConfig,
10
+ keyPackageEqualityConfig: defaultKeyPackageEqualityConfig,
11
+ paddingConfig: defaultPaddingConfig,
12
+ // Marmot v2 app components use full-replacement update payloads, so the
13
+ // default last-update-wins callback is the correct merge policy.
14
+ appDataUpdateCallback: defaultAppDataUpdateCallback,
15
+ };
16
+ const COMPONENT_NAMES = new Map([
17
+ [APP_COMPONENTS_COMPONENT_ID, "app_components"],
18
+ [GROUP_PROFILE_COMPONENT_ID, GROUP_PROFILE_COMPONENT],
19
+ [GROUP_BLOSSOM_IMAGE_COMPONENT_ID, GROUP_BLOSSOM_IMAGE_COMPONENT],
20
+ [GROUP_ADMIN_POLICY_COMPONENT_ID, GROUP_ADMIN_POLICY_COMPONENT],
21
+ [NOSTR_ROUTING_COMPONENT_ID, NOSTR_ROUTING_COMPONENT],
22
+ [GROUP_MESSAGE_RETENTION_COMPONENT_ID, GROUP_MESSAGE_RETENTION_COMPONENT],
23
+ [AGENT_TEXT_STREAM_QUIC_COMPONENT_ID, AGENT_TEXT_STREAM_QUIC_COMPONENT],
24
+ [GROUP_AVATAR_URL_COMPONENT_ID, GROUP_AVATAR_URL_COMPONENT],
25
+ [GROUP_ENCRYPTED_MEDIA_COMPONENT_ID, GROUP_ENCRYPTED_MEDIA_COMPONENT],
26
+ [GROUP_LIFECYCLE_COMPONENT_ID, GROUP_LIFECYCLE_COMPONENT],
27
+ ]);
28
+ const CIPHERSUITE_NAMES = new Map(Object.entries(ciphersuites).map(([name, id]) => [id, name]));
29
+ function componentIdHex(id) {
30
+ return `0x${id.toString(16).padStart(4, "0")}`;
31
+ }
32
+ function errorMessage(error) {
33
+ return error instanceof Error ? error.message : String(error);
34
+ }
35
+ function decodeGroupComponent(componentId, data) {
36
+ switch (componentId) {
37
+ case APP_COMPONENTS_COMPONENT_ID:
38
+ return decodeComponentsList(data);
39
+ case GROUP_PROFILE_COMPONENT_ID:
40
+ return decodeGroupProfileV1(data);
41
+ case GROUP_ADMIN_POLICY_COMPONENT_ID:
42
+ return decodeAdminPolicyV1(data);
43
+ case NOSTR_ROUTING_COMPONENT_ID: {
44
+ const routing = decodeNostrRoutingV1(data);
45
+ return {
46
+ nostrGroupId: routing.nostrGroupId,
47
+ nostrGroupIdHex: bytesToHex(routing.nostrGroupId),
48
+ relays: routing.relays,
49
+ };
50
+ }
51
+ case GROUP_MESSAGE_RETENTION_COMPONENT_ID:
52
+ return decodeMessageRetentionV1(data);
53
+ case AGENT_TEXT_STREAM_QUIC_COMPONENT_ID:
54
+ return decodeAgentTextStreamQuicPolicyV1(data);
55
+ case GROUP_AVATAR_URL_COMPONENT_ID:
56
+ return decodeGroupAvatarUrlV1(data);
57
+ case GROUP_ENCRYPTED_MEDIA_COMPONENT_ID:
58
+ return decodeEncryptedMediaPolicyV1(data);
59
+ case GROUP_LIFECYCLE_COMPONENT_ID:
60
+ return decodeGroupLifecycleV1(data);
61
+ default:
62
+ return undefined;
63
+ }
64
+ }
65
+ function getGroupComponentInfos(clientState) {
66
+ let dictionary;
67
+ try {
68
+ dictionary = getAppDataDictionary(clientState.groupContext.extensions);
69
+ }
70
+ catch (error) {
71
+ return { components: [], decodeError: errorMessage(error) };
72
+ }
73
+ const components = (dictionary ?? []).map((entry) => {
74
+ const info = {
75
+ id: entry.componentId,
76
+ idHex: componentIdHex(entry.componentId),
77
+ name: COMPONENT_NAMES.get(entry.componentId) ?? "unknown",
78
+ dataLength: entry.data.length,
79
+ dataHex: bytesToHex(entry.data),
80
+ };
81
+ try {
82
+ const decoded = decodeGroupComponent(entry.componentId, entry.data);
83
+ if (decoded !== undefined)
84
+ info.decoded = decoded;
85
+ }
86
+ catch (error) {
87
+ info.decodeError = errorMessage(error);
88
+ }
89
+ return info;
90
+ });
91
+ return { components };
92
+ }
93
+ /**
94
+ * Reads the Marmot group view from a ClientState or GroupInfo. Returns null when
95
+ * the group carries no recognizable app components.
96
+ */
97
+ export function getMarmotGroupView(clientState) {
98
+ const extensions = clientState.groupContext.extensions;
99
+ try {
100
+ const profile = getGroupProfile(extensions);
101
+ const adminPubkeys = getAdminPolicy(extensions);
102
+ const routing = getNostrRouting(extensions);
103
+ const avatar = getGroupAvatarUrl(extensions);
104
+ const encryptedMedia = getEncryptedMediaPolicy(extensions);
105
+ const messageRetention = getMessageRetention(extensions);
106
+ const protocolLifecycle = getGroupLifecycle(extensions);
107
+ if (!profile && !adminPubkeys && !routing)
108
+ return null;
109
+ return {
110
+ nostrGroupId: routing?.nostrGroupId,
111
+ name: profile?.name ?? "",
112
+ description: profile?.description ?? "",
113
+ adminPubkeys: adminPubkeys ?? [],
114
+ relays: routing?.relays ?? [],
115
+ avatarUrl: avatar?.url,
116
+ encryptedMedia,
117
+ messageRetention,
118
+ protocolLifecycle,
119
+ };
120
+ }
121
+ catch {
122
+ return null;
123
+ }
124
+ }
125
+ function hasLocalClientState(state) {
126
+ return "ratchetTree" in state;
127
+ }
128
+ /**
129
+ * Builds a complete group information/debug projection from MLS state.
130
+ *
131
+ * This includes the private MLS group id and epoch details, decoded Marmot app
132
+ * components, public Nostr routing details, and member identity summary.
133
+ */
134
+ export function getMarmotGroupInfo(clientState) {
135
+ const groupContext = clientState.groupContext;
136
+ const view = getMarmotGroupView(clientState);
137
+ const { components, decodeError } = getGroupComponentInfos(clientState);
138
+ const appComponents = components.find((component) => component.id === APP_COMPONENTS_COMPONENT_ID);
139
+ const requiredComponentIds = Array.isArray(appComponents?.decoded)
140
+ ? appComponents.decoded.filter((id) => typeof id === "number")
141
+ : [];
142
+ const members = hasLocalClientState(clientState)
143
+ ? getGroupMemberPubkeys(clientState)
144
+ : [];
145
+ return {
146
+ mls: {
147
+ groupId: groupContext.groupId,
148
+ groupIdHex: bytesToHex(groupContext.groupId),
149
+ epoch: groupContext.epoch,
150
+ epochNumber: Number(groupContext.epoch),
151
+ epochString: groupContext.epoch.toString(),
152
+ cipherSuite: groupContext.cipherSuite,
153
+ cipherSuiteName: CIPHERSUITE_NAMES.get(groupContext.cipherSuite),
154
+ treeHashHex: bytesToHex(groupContext.treeHash),
155
+ confirmedTranscriptHashHex: bytesToHex(groupContext.confirmedTranscriptHash),
156
+ confirmationTagHex: hasLocalClientState(clientState)
157
+ ? bytesToHex(clientState.confirmationTag)
158
+ : undefined,
159
+ historicalEpochs: hasLocalClientState(clientState)
160
+ ? Array.from(clientState.historicalReceiverData.keys()).map((epoch) => epoch.toString())
161
+ : [],
162
+ memberCount: hasLocalClientState(clientState)
163
+ ? getMemberCount(clientState)
164
+ : 0,
165
+ proposalCount: hasLocalClientState(clientState)
166
+ ? Object.keys(clientState.unappliedProposals).length
167
+ : 0,
168
+ },
169
+ app: {
170
+ view,
171
+ components,
172
+ componentCount: components.length,
173
+ requiredComponentIds,
174
+ decodeError,
175
+ },
176
+ nostr: {
177
+ groupId: view?.nostrGroupId,
178
+ groupIdHex: view?.nostrGroupId
179
+ ? bytesToHex(view.nostrGroupId)
180
+ : undefined,
181
+ relays: view?.relays ?? [],
182
+ relayCount: view?.relays.length ?? 0,
183
+ hasRouting: !!view?.nostrGroupId,
184
+ },
185
+ members: {
186
+ pubkeys: members,
187
+ count: members.length,
188
+ },
189
+ };
190
+ }
191
+ /** Reads the hex id of the group from a ClientState or GroupInfo object */
192
+ export function getGroupIdHex(clientState) {
193
+ return bytesToHex(clientState.groupContext.groupId);
194
+ }
195
+ export function getNostrGroupIdHex(clientState) {
196
+ const routing = getNostrRouting(clientState.groupContext.extensions);
197
+ if (!routing)
198
+ throw new Error("nostr routing component not found in ClientState");
199
+ return bytesToHex(routing.nostrGroupId);
200
+ }
201
+ /** Reads the epoch number from a ClientState or GroupInfo object */
202
+ export function getEpoch(clientState) {
203
+ return Number(clientState.groupContext.epoch);
204
+ }
205
+ /** Reads the number of members in the group from a ClientState ratchet tree */
206
+ export function getMemberCount(clientState) {
207
+ return clientState.ratchetTree.filter((node) => node && node.nodeType === nodeTypes.leaf).length;
208
+ }
209
+ /** Serializes a ClientState object to a bytes array */
210
+ export function serializeClientState(state) {
211
+ return encode(clientStateEncoder, state);
212
+ }
213
+ /** Deserializes stored ClientState bytes (ts-mls TLS decoding). */
214
+ export function deserializeClientState(stored) {
215
+ try {
216
+ const decoded = decode(clientStateDecoder, stored);
217
+ if (!decoded)
218
+ throw new Error("Failed to deserialize ClientState: clientStateDecoder returned null");
219
+ return decoded;
220
+ }
221
+ catch (error) {
222
+ if (error instanceof Error)
223
+ throw new Error(`Failed to deserialize ClientState: ${error.message}`);
224
+ throw new Error("Failed to deserialize ClientState: Unknown error");
225
+ }
226
+ }
@@ -0,0 +1,26 @@
1
+ /** @module @category Core - Commit Authorization */
2
+ import { type ProposalWithSender } from "ts-mls";
3
+ export type CommitAuthorizationDecision = {
4
+ authorized: true;
5
+ } | {
6
+ authorized: false;
7
+ reason: "non-admin-proposal-union";
8
+ };
9
+ /**
10
+ * Decide whether an actor may author the exact proposal union carried by a
11
+ * commit. Admins may author any otherwise-valid union. A non-admin may author
12
+ * only an empty/self-update commit, Updates sent exclusively by its own leaf,
13
+ * or a SelfRemove-only union.
14
+ *
15
+ * This is deliberately independent of MLS state: callers must derive the
16
+ * actor identity and leaf index from the local state and pass the exact
17
+ * by-reference plus by-value union that `createCommit` will encode.
18
+ *
19
+ * @see refs/marmot/protocol-core/group-messaging.md "Commit authorization"
20
+ */
21
+ export declare function decideCommitAuthorization(args: {
22
+ actorPubkey: string;
23
+ actorLeafIndex: number;
24
+ adminPubkeys: readonly string[];
25
+ proposals: readonly ProposalWithSender[];
26
+ }): CommitAuthorizationDecision;
@@ -0,0 +1,26 @@
1
+ /** @module @category Core - Commit Authorization */
2
+ import { defaultProposalTypes, selfRemoveProposalType, } from "ts-mls";
3
+ /**
4
+ * Decide whether an actor may author the exact proposal union carried by a
5
+ * commit. Admins may author any otherwise-valid union. A non-admin may author
6
+ * only an empty/self-update commit, Updates sent exclusively by its own leaf,
7
+ * or a SelfRemove-only union.
8
+ *
9
+ * This is deliberately independent of MLS state: callers must derive the
10
+ * actor identity and leaf index from the local state and pass the exact
11
+ * by-reference plus by-value union that `createCommit` will encode.
12
+ *
13
+ * @see refs/marmot/protocol-core/group-messaging.md "Commit authorization"
14
+ */
15
+ export function decideCommitAuthorization(args) {
16
+ if (args.adminPubkeys.includes(args.actorPubkey))
17
+ return { authorized: true };
18
+ const selfUpdateOnly = args.proposals.every(({ proposal, senderLeafIndex }) => proposal.proposalType === defaultProposalTypes.update &&
19
+ senderLeafIndex !== undefined &&
20
+ Number(senderLeafIndex) === Number(args.actorLeafIndex));
21
+ const selfRemoveOnly = args.proposals.length > 0 &&
22
+ args.proposals.every(({ proposal }) => proposal.proposalType === selfRemoveProposalType);
23
+ return selfUpdateOnly || selfRemoveOnly
24
+ ? { authorized: true }
25
+ : { authorized: false, reason: "non-admin-proposal-union" };
26
+ }
@@ -0,0 +1,4 @@
1
+ /** Encodes a list of admin x-only pubkeys (64-char hex) to component `data`. */
2
+ export declare function encodeAdminPolicyV1(adminPubkeys: string[]): Uint8Array;
3
+ /** Decodes `marmot.group.admin-policy.v1` component `data` bytes to hex keys. */
4
+ export declare function decodeAdminPolicyV1(data: Uint8Array): string[];
@@ -0,0 +1,69 @@
1
+ /** @module @category Core - App Components */
2
+ import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
3
+ import { BinaryReader, BinaryWriter } from "../binary.js";
4
+ import { compareBytes } from "./bytes.js";
5
+ /**
6
+ * Codec for `marmot.group.admin-policy.v1` (`0x8003`) — the set of group admin
7
+ * x-only public keys. Replaces the `admin_pubkeys` field of the legacy
8
+ * `marmot_group_data` monolith.
9
+ *
10
+ * Wire (Marmot binary profile):
11
+ * MarmotAdminKeyV1 admins<V>; // QUIC-varint byte length over the concatenation
12
+ * // each MarmotAdminKeyV1 = opaque xonly_pubkey[32] (fixed, no per-key prefix)
13
+ *
14
+ * Keys are sorted ascending by raw byte value, MUST be unique, and the list
15
+ * MUST be non-empty. The decoder re-checks sort + uniqueness.
16
+ *
17
+ * @see darkmatter `crates/cgka-engine/src/app_components.rs` `encode_admin_policy`
18
+ * @see Marmot v2 spec: `app-components/admin-policy-v1.md`
19
+ */
20
+ const ADMIN_KEY_BYTES = 32;
21
+ function isHexKey(str) {
22
+ return /^[0-9a-fA-F]{64}$/.test(str);
23
+ }
24
+ /** Encodes a list of admin x-only pubkeys (64-char hex) to component `data`. */
25
+ export function encodeAdminPolicyV1(adminPubkeys) {
26
+ for (const pk of adminPubkeys) {
27
+ if (!isHexKey(pk))
28
+ throw new Error("Invalid admin public key format");
29
+ }
30
+ const sorted = adminPubkeys.map((pk) => hexToBytes(pk)).sort(compareBytes);
31
+ // Sort + dedup to match the canonical Rust ordering (consecutive == all dups
32
+ // after sorting).
33
+ const keys = [];
34
+ for (let i = 0; i < sorted.length; i++) {
35
+ if (i > 0 && compareBytes(sorted[i - 1], sorted[i]) === 0)
36
+ continue;
37
+ keys.push(sorted[i]);
38
+ }
39
+ if (keys.length === 0) {
40
+ throw new Error("admin-policy must contain at least one admin");
41
+ }
42
+ const concat = new Uint8Array(keys.length * ADMIN_KEY_BYTES);
43
+ keys.forEach((k, i) => concat.set(k, i * ADMIN_KEY_BYTES));
44
+ return new BinaryWriter().opaque(concat).build();
45
+ }
46
+ /** Decodes `marmot.group.admin-policy.v1` component `data` bytes to hex keys. */
47
+ export function decodeAdminPolicyV1(data) {
48
+ const reader = new BinaryReader(data);
49
+ const concat = reader.opaque();
50
+ reader.end();
51
+ if (concat.length === 0) {
52
+ throw new Error("admin-policy must contain at least one admin");
53
+ }
54
+ if (concat.length % ADMIN_KEY_BYTES !== 0) {
55
+ throw new Error("admin_pubkeys length must be a multiple of 32");
56
+ }
57
+ const keys = [];
58
+ for (let i = 0; i < concat.length; i += ADMIN_KEY_BYTES) {
59
+ keys.push(concat.slice(i, i + ADMIN_KEY_BYTES));
60
+ }
61
+ for (let i = 1; i < keys.length; i++) {
62
+ const cmp = compareBytes(keys[i - 1], keys[i]);
63
+ if (cmp === 0)
64
+ throw new Error("admin_pubkeys must be unique");
65
+ if (cmp > 0)
66
+ throw new Error("admin_pubkeys must be sorted");
67
+ }
68
+ return keys.map((k) => bytesToHex(k));
69
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Codec for `marmot.group.agent-text-stream.quic.v1` (`0x8006`) — the policy
3
+ * gating the QUIC agent-text-stream transport binding.
4
+ *
5
+ * Wire (Marmot binary profile): a fixed 12-byte record, no length prefixes.
6
+ * uint8 required_member_roles;
7
+ * uint8 allowed_member_roles;
8
+ * uint32 max_plaintext_frame_len; // big-endian
9
+ * uint32 replay_ttl_secs; // big-endian
10
+ * uint16 padding_bucket_bytes; // big-endian
11
+ *
12
+ * @see darkmatter `crates/traits/src/agent_text_stream.rs` `encode_component_state`
13
+ */
14
+ export declare const AGENT_TEXT_STREAM_ROLE_RECEIVE = 1;
15
+ export declare const AGENT_TEXT_STREAM_ROLE_SEND = 2;
16
+ export declare const AGENT_TEXT_STREAM_ROLE_FANOUT = 4;
17
+ /**
18
+ * MLS LeafNode extension types that advertise each agent-text-stream-QUIC member
19
+ * role. A member advertises a role by listing the role's extension type in its
20
+ * LeafNode capabilities (agent-text-stream-quic-v1.md "role capability"); a
21
+ * group's `required_member_roles` mask is enforced against these on invite/join.
22
+ * A client that does not advertise a required role capability cannot be invited
23
+ * into the group.
24
+ *
25
+ * @see darkmatter `crates/traits/src/agent_text_stream.rs`
26
+ * (`AGENT_TEXT_STREAM_QUIC_{RECEIVE,SEND,FANOUT}_CAPABILITY`)
27
+ */
28
+ export declare const AGENT_TEXT_STREAM_QUIC_RECEIVE_EXTENSION_TYPE = 62161;
29
+ export declare const AGENT_TEXT_STREAM_QUIC_SEND_EXTENSION_TYPE = 62162;
30
+ export declare const AGENT_TEXT_STREAM_QUIC_FANOUT_EXTENSION_TYPE = 62164;
31
+ /**
32
+ * All agent-text-stream-QUIC role capability extension types, ascending — the
33
+ * full registered set (`registries.md`).
34
+ *
35
+ * Note: marmot-ts only *advertises* `receive` in its KeyPackage capabilities
36
+ * (see {@link ensureMarmotCapabilities}), because it has no QUIC data plane and
37
+ * `receive` is satisfiable by reading the final MLS message. This list is the
38
+ * registry reference for all three roles, not the set marmot-ts claims.
39
+ */
40
+ export declare const AGENT_TEXT_STREAM_QUIC_ROLE_EXTENSION_TYPES: readonly [62161, 62162, 62164];
41
+ export interface AgentTextStreamQuicPolicyV1 {
42
+ requiredMemberRoles: number;
43
+ allowedMemberRoles: number;
44
+ maxPlaintextFrameLen: number;
45
+ replayTtlSecs: number;
46
+ paddingBucketBytes: number;
47
+ }
48
+ /** Encodes an {@link AgentTextStreamQuicPolicyV1} to its 12-byte component `data`. */
49
+ export declare function encodeAgentTextStreamQuicPolicyV1(policy: AgentTextStreamQuicPolicyV1): Uint8Array;
50
+ /** Decodes `marmot.group.agent-text-stream.quic.v1` component `data` bytes. */
51
+ export declare function decodeAgentTextStreamQuicPolicyV1(data: Uint8Array): AgentTextStreamQuicPolicyV1;
@@ -0,0 +1,112 @@
1
+ /** @module @category Core - App Components */
2
+ import { BinaryReader, BinaryWriter } from "../binary.js";
3
+ /**
4
+ * Codec for `marmot.group.agent-text-stream.quic.v1` (`0x8006`) — the policy
5
+ * gating the QUIC agent-text-stream transport binding.
6
+ *
7
+ * Wire (Marmot binary profile): a fixed 12-byte record, no length prefixes.
8
+ * uint8 required_member_roles;
9
+ * uint8 allowed_member_roles;
10
+ * uint32 max_plaintext_frame_len; // big-endian
11
+ * uint32 replay_ttl_secs; // big-endian
12
+ * uint16 padding_bucket_bytes; // big-endian
13
+ *
14
+ * @see darkmatter `crates/traits/src/agent_text_stream.rs` `encode_component_state`
15
+ */
16
+ export const AGENT_TEXT_STREAM_ROLE_RECEIVE = 0x01;
17
+ export const AGENT_TEXT_STREAM_ROLE_SEND = 0x02;
18
+ export const AGENT_TEXT_STREAM_ROLE_FANOUT = 0x04;
19
+ const ROLE_MASK = AGENT_TEXT_STREAM_ROLE_RECEIVE |
20
+ AGENT_TEXT_STREAM_ROLE_SEND |
21
+ AGENT_TEXT_STREAM_ROLE_FANOUT;
22
+ /**
23
+ * MLS LeafNode extension types that advertise each agent-text-stream-QUIC member
24
+ * role. A member advertises a role by listing the role's extension type in its
25
+ * LeafNode capabilities (agent-text-stream-quic-v1.md "role capability"); a
26
+ * group's `required_member_roles` mask is enforced against these on invite/join.
27
+ * A client that does not advertise a required role capability cannot be invited
28
+ * into the group.
29
+ *
30
+ * @see darkmatter `crates/traits/src/agent_text_stream.rs`
31
+ * (`AGENT_TEXT_STREAM_QUIC_{RECEIVE,SEND,FANOUT}_CAPABILITY`)
32
+ */
33
+ export const AGENT_TEXT_STREAM_QUIC_RECEIVE_EXTENSION_TYPE = 0xf2d1;
34
+ export const AGENT_TEXT_STREAM_QUIC_SEND_EXTENSION_TYPE = 0xf2d2;
35
+ export const AGENT_TEXT_STREAM_QUIC_FANOUT_EXTENSION_TYPE = 0xf2d4;
36
+ /**
37
+ * All agent-text-stream-QUIC role capability extension types, ascending — the
38
+ * full registered set (`registries.md`).
39
+ *
40
+ * Note: marmot-ts only *advertises* `receive` in its KeyPackage capabilities
41
+ * (see {@link ensureMarmotCapabilities}), because it has no QUIC data plane and
42
+ * `receive` is satisfiable by reading the final MLS message. This list is the
43
+ * registry reference for all three roles, not the set marmot-ts claims.
44
+ */
45
+ export const AGENT_TEXT_STREAM_QUIC_ROLE_EXTENSION_TYPES = [
46
+ AGENT_TEXT_STREAM_QUIC_RECEIVE_EXTENSION_TYPE,
47
+ AGENT_TEXT_STREAM_QUIC_SEND_EXTENSION_TYPE,
48
+ AGENT_TEXT_STREAM_QUIC_FANOUT_EXTENSION_TYPE,
49
+ ];
50
+ const COMPONENT_STATE_LEN = 12;
51
+ // 65519 (not 64*1024) keeps a maximum-length frame's ciphertext within one
52
+ // QUIC datagram, matching darkmatter AGENT_TEXT_STREAM_MAX_PLAINTEXT_FRAME_LEN
53
+ // (agent_text_stream.rs). A larger cap would accept policy bytes a conformant
54
+ // peer rejects.
55
+ const MAX_PLAINTEXT_FRAME_LEN = 65519;
56
+ const MAX_REPLAY_TTL_SECS = 5 * 60;
57
+ const MAX_PADDING_BUCKET_BYTES = 4096;
58
+ function validate(policy) {
59
+ const { requiredMemberRoles, allowedMemberRoles, maxPlaintextFrameLen, replayTtlSecs, paddingBucketBytes, } = policy;
60
+ if (requiredMemberRoles === 0) {
61
+ throw new Error("required agent text stream roles cannot be empty");
62
+ }
63
+ if (requiredMemberRoles & ~ROLE_MASK) {
64
+ throw new Error("required agent text stream role mask contains unknown bits");
65
+ }
66
+ if (allowedMemberRoles & ~ROLE_MASK) {
67
+ throw new Error("allowed agent text stream role mask contains unknown bits");
68
+ }
69
+ if (requiredMemberRoles & ~allowedMemberRoles) {
70
+ throw new Error("required agent text stream roles must be a subset of allowed roles");
71
+ }
72
+ if (maxPlaintextFrameLen === 0) {
73
+ throw new Error("agent text stream plaintext frame limit cannot be zero");
74
+ }
75
+ if (maxPlaintextFrameLen > MAX_PLAINTEXT_FRAME_LEN) {
76
+ throw new Error("agent text stream plaintext frame limit exceeds app profile max");
77
+ }
78
+ if (replayTtlSecs > MAX_REPLAY_TTL_SECS) {
79
+ throw new Error("agent text stream replay ttl exceeds app profile max");
80
+ }
81
+ if (paddingBucketBytes > MAX_PADDING_BUCKET_BYTES) {
82
+ throw new Error("agent text stream padding bucket exceeds app profile max");
83
+ }
84
+ }
85
+ /** Encodes an {@link AgentTextStreamQuicPolicyV1} to its 12-byte component `data`. */
86
+ export function encodeAgentTextStreamQuicPolicyV1(policy) {
87
+ validate(policy);
88
+ return new BinaryWriter()
89
+ .uint8(policy.requiredMemberRoles)
90
+ .uint8(policy.allowedMemberRoles)
91
+ .uint32(policy.maxPlaintextFrameLen)
92
+ .uint32(policy.replayTtlSecs)
93
+ .uint16(policy.paddingBucketBytes)
94
+ .build();
95
+ }
96
+ /** Decodes `marmot.group.agent-text-stream.quic.v1` component `data` bytes. */
97
+ export function decodeAgentTextStreamQuicPolicyV1(data) {
98
+ if (data.length !== COMPONENT_STATE_LEN) {
99
+ throw new Error(`agent text stream component state must be ${COMPONENT_STATE_LEN} bytes, got ${data.length}`);
100
+ }
101
+ const reader = new BinaryReader(data);
102
+ const policy = {
103
+ requiredMemberRoles: reader.uint8(),
104
+ allowedMemberRoles: reader.uint8(),
105
+ maxPlaintextFrameLen: reader.uint32(),
106
+ replayTtlSecs: reader.uint32(),
107
+ paddingBucketBytes: reader.uint16(),
108
+ };
109
+ reader.end();
110
+ validate(policy);
111
+ return policy;
112
+ }
@@ -0,0 +1,17 @@
1
+ import type { AppComponentId } from "./ids.js";
2
+ /**
3
+ * Codec for the upstream `app_components` component (`0x0001`) `data` payload:
4
+ * the sorted, unique list of component ids a member supports (in a LeafNode) or
5
+ * a group requires (in the GroupContext).
6
+ *
7
+ * Wire (Marmot binary profile):
8
+ * ComponentID component_ids<V>; // QUIC-varint byte length, then be-uint16 ids
9
+ *
10
+ * Ids are encoded ascending and MUST be unique.
11
+ *
12
+ * @see darkmatter `crates/traits/src/app_components.rs` `encode_components_list`
13
+ */
14
+ /** Encodes a set of component ids to the `app_components` data payload. */
15
+ export declare function encodeComponentsList(ids: Iterable<AppComponentId>): Uint8Array;
16
+ /** Decodes an `app_components` data payload into a sorted, unique id list. */
17
+ export declare function decodeComponentsList(data: Uint8Array): AppComponentId[];
@@ -0,0 +1,35 @@
1
+ /** @module @category Core - App Components */
2
+ import { BinaryReader, BinaryWriter } from "../binary.js";
3
+ /**
4
+ * Codec for the upstream `app_components` component (`0x0001`) `data` payload:
5
+ * the sorted, unique list of component ids a member supports (in a LeafNode) or
6
+ * a group requires (in the GroupContext).
7
+ *
8
+ * Wire (Marmot binary profile):
9
+ * ComponentID component_ids<V>; // QUIC-varint byte length, then be-uint16 ids
10
+ *
11
+ * Ids are encoded ascending and MUST be unique.
12
+ *
13
+ * @see darkmatter `crates/traits/src/app_components.rs` `encode_components_list`
14
+ */
15
+ /** Encodes a set of component ids to the `app_components` data payload. */
16
+ export function encodeComponentsList(ids) {
17
+ const sorted = [...new Set(ids)].sort((a, b) => a - b);
18
+ const items = sorted.map((id) => new BinaryWriter().uint16(id).build());
19
+ return new BinaryWriter().vector(items).build();
20
+ }
21
+ /** Decodes an `app_components` data payload into a sorted, unique id list. */
22
+ export function decodeComponentsList(data) {
23
+ const reader = new BinaryReader(data);
24
+ const seen = new Set();
25
+ const ids = reader.vector((item) => {
26
+ const id = item.uint16();
27
+ if (seen.has(id)) {
28
+ throw new Error(`duplicate component id ${id} in app_components list`);
29
+ }
30
+ seen.add(id);
31
+ return id;
32
+ });
33
+ reader.end();
34
+ return ids;
35
+ }
@@ -0,0 +1,12 @@
1
+ export interface GroupAvatarUrlV1 {
2
+ /** Normalized `https` avatar URL, or `""` for an absent/cleared avatar. */
3
+ url: string;
4
+ /** Optional render dimension hint (e.g. `"128x128"`). */
5
+ dim?: string;
6
+ /** Optional thumbhash render hint. */
7
+ thumbhash?: string;
8
+ }
9
+ /** Encodes a {@link GroupAvatarUrlV1} to its component `data` bytes. */
10
+ export declare function encodeGroupAvatarUrlV1(avatar: GroupAvatarUrlV1): Uint8Array;
11
+ /** Decodes `marmot.group.avatar-url.v1` component `data` bytes. */
12
+ export declare function decodeGroupAvatarUrlV1(data: Uint8Array): GroupAvatarUrlV1;
@@ -0,0 +1,85 @@
1
+ /** @module @category Core - App Components */
2
+ import { BinaryReader, BinaryWriter, decodeUtf8, encodeUtf8, } from "../binary.js";
3
+ import { validateAndNormalizeHttpsUrl } from "./url.js";
4
+ /**
5
+ * Codec for `marmot.group.avatar-url.v1` (`0x8007`) — a small group avatar
6
+ * pointer: an `https` URL plus optional `dim`/`thumbhash` render hints. An
7
+ * empty `url` encodes the absent/cleared avatar (all fields empty).
8
+ *
9
+ * Wire (Marmot binary profile):
10
+ * opaque url<V>; // QUIC-varint length + UTF-8; "" means absent
11
+ * opaque dim<V>; // optional render hint, "" when absent
12
+ * opaque thumbhash<V>; // optional render hint, "" when absent
13
+ *
14
+ * The URL is validated + normalized (`https` only, no credentials/fragment, not
15
+ * localhost or a non-routable address); the decoder re-checks that a present
16
+ * URL is already normalized.
17
+ *
18
+ * @see darkmatter `crates/traits/src/app_components.rs` `encode_group_avatar_url_v1`
19
+ */
20
+ const GROUP_AVATAR_URL_MAX_LEN = 2048;
21
+ const GROUP_AVATAR_HINT_MAX_LEN = 256;
22
+ function normalizeUrl(url) {
23
+ return validateAndNormalizeHttpsUrl(url, {
24
+ maxLen: GROUP_AVATAR_URL_MAX_LEN,
25
+ label: "group avatar URL",
26
+ });
27
+ }
28
+ /** Encodes a {@link GroupAvatarUrlV1} to its component `data` bytes. */
29
+ export function encodeGroupAvatarUrlV1(avatar) {
30
+ const dim = avatar.dim ?? "";
31
+ const thumbhash = avatar.thumbhash ?? "";
32
+ if (avatar.url === "" && (avatar.dim != null || avatar.thumbhash != null)) {
33
+ throw new Error("group avatar absent state must not include hints");
34
+ }
35
+ const url = avatar.url === "" ? "" : normalizeUrl(avatar.url);
36
+ if (encodeUtf8(dim).length > GROUP_AVATAR_HINT_MAX_LEN) {
37
+ throw new Error(`group avatar dim exceeds ${GROUP_AVATAR_HINT_MAX_LEN} bytes`);
38
+ }
39
+ if (encodeUtf8(thumbhash).length > GROUP_AVATAR_HINT_MAX_LEN) {
40
+ throw new Error(`group avatar thumbhash exceeds ${GROUP_AVATAR_HINT_MAX_LEN} bytes`);
41
+ }
42
+ return new BinaryWriter()
43
+ .opaque(encodeUtf8(url), { max: GROUP_AVATAR_URL_MAX_LEN })
44
+ .opaque(encodeUtf8(dim), { max: GROUP_AVATAR_HINT_MAX_LEN })
45
+ .opaque(encodeUtf8(thumbhash), { max: GROUP_AVATAR_HINT_MAX_LEN })
46
+ .build();
47
+ }
48
+ /**
49
+ * Decodes a length-bounded opaque hint field. Presence is decided by the caller
50
+ * on the raw bytes; here a non-UTF-8 hint is interpreted as ABSENT (`undefined`)
51
+ * rather than rejected — matching darkmatter `String::from_utf8(..).ok()` in
52
+ * `avatar_url.rs`. Rejecting it would fork commit acceptance.
53
+ */
54
+ function decodeHintOrUndefined(bytes) {
55
+ if (bytes.length === 0)
56
+ return undefined;
57
+ try {
58
+ // A leading U+FEFF is content, as `String::from_utf8` keeps it.
59
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
64
+ }
65
+ /** Decodes `marmot.group.avatar-url.v1` component `data` bytes. */
66
+ export function decodeGroupAvatarUrlV1(data) {
67
+ const reader = new BinaryReader(data);
68
+ const url = decodeUtf8(reader.opaque({ max: GROUP_AVATAR_URL_MAX_LEN }));
69
+ const dimBytes = reader.opaque({ max: GROUP_AVATAR_HINT_MAX_LEN });
70
+ const thumbhashBytes = reader.opaque({ max: GROUP_AVATAR_HINT_MAX_LEN });
71
+ reader.end();
72
+ // Presence is decided on the raw bytes: an absent state (empty url) must carry
73
+ // no hint bytes at all — even non-UTF-8 ones (darkmatter avatar_url.rs).
74
+ if (url === "" && (dimBytes.length > 0 || thumbhashBytes.length > 0)) {
75
+ throw new Error("group avatar absent state must not include hints");
76
+ }
77
+ if (url !== "" && normalizeUrl(url) !== url) {
78
+ throw new Error("group avatar URL is not normalized");
79
+ }
80
+ return {
81
+ url,
82
+ dim: decodeHintOrUndefined(dimBytes),
83
+ thumbhash: decodeHintOrUndefined(thumbhashBytes),
84
+ };
85
+ }