@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,363 @@
1
+ /** @module @category Core - Binary Encoding */
2
+ /**
3
+ * The Marmot binary profile.
4
+ *
5
+ * Marmot-owned binary structures (app component state, app component updates, Marmot
6
+ * extensions, and other byte strings owned by the Marmot spec) use TLS Presentation
7
+ * Language syntax with QUIC variable-length vector prefixes. This module implements that
8
+ * profile: fixed-width network-byte-order integers, fixed `opaque[N]` fields, QUIC
9
+ * variable-length integer length prefixes, and length-prefixed variable vectors.
10
+ *
11
+ * It does not cover bytes owned by another protocol. MLS messages, KeyPackages,
12
+ * credentials, and MLS-defined extensions use the encoding defined by MLS; Nostr event ids
13
+ * and signatures use the Nostr canonical event serialization; transport envelopes use the
14
+ * encoding defined by their transport document.
15
+ *
16
+ * @see Marmot v2 spec: `foundation/canonical-encoding.md`
17
+ */
18
+ /** Largest value representable by a QUIC variable-length integer (`2^62 - 1`). */
19
+ export const MAX_VARINT = 4611686018427387903n;
20
+ /** Smallest value that requires each QUIC varint prefix size, indexed by prefix bits. */
21
+ const VARINT_MINS = [0n, 64n, 16384n, 1073741824n];
22
+ /** Error thrown when bytes do not conform to the Marmot binary profile. */
23
+ export class BinaryDecodeError extends Error {
24
+ constructor(message) {
25
+ super(message);
26
+ this.name = "BinaryDecodeError";
27
+ }
28
+ }
29
+ function toBigInt(value, field) {
30
+ if (typeof value === "bigint")
31
+ return value;
32
+ if (!Number.isInteger(value)) {
33
+ throw new RangeError(`${field} must be an integer, got ${value}`);
34
+ }
35
+ return BigInt(value);
36
+ }
37
+ /**
38
+ * Encodes a QUIC variable-length integer using the shortest prefix size that can hold the
39
+ * value, as required for canonical Marmot encoding.
40
+ *
41
+ * @param value - A non-negative integer in `[0, MAX_VARINT]`.
42
+ */
43
+ export function encodeVarint(value) {
44
+ const v = toBigInt(value, "varint");
45
+ if (v < 0n)
46
+ throw new RangeError(`varint must be non-negative, got ${v}`);
47
+ if (v > MAX_VARINT)
48
+ throw new RangeError(`varint too large: ${v}`);
49
+ let len;
50
+ let prefixBits;
51
+ if (v < 64n) {
52
+ len = 1;
53
+ prefixBits = 0;
54
+ }
55
+ else if (v < 16384n) {
56
+ len = 2;
57
+ prefixBits = 1;
58
+ }
59
+ else if (v < 1073741824n) {
60
+ len = 4;
61
+ prefixBits = 2;
62
+ }
63
+ else {
64
+ len = 8;
65
+ prefixBits = 3;
66
+ }
67
+ const out = new Uint8Array(len);
68
+ let tmp = v;
69
+ for (let i = len - 1; i >= 0; i--) {
70
+ out[i] = Number(tmp & 0xffn);
71
+ tmp >>= 8n;
72
+ }
73
+ out[0] |= prefixBits << 6;
74
+ return out;
75
+ }
76
+ /**
77
+ * Decodes a QUIC variable-length integer at `offset`.
78
+ *
79
+ * Rejects non-minimal encodings: a value MUST use the shortest prefix size that can hold
80
+ * it, so a longer prefix for the same value is invalid.
81
+ *
82
+ * @returns The decoded value and the number of bytes consumed.
83
+ */
84
+ export function decodeVarint(data, offset = 0) {
85
+ if (offset < 0 || offset >= data.length) {
86
+ throw new BinaryDecodeError("varint: read past end of buffer");
87
+ }
88
+ const first = data[offset];
89
+ const prefixBits = first >> 6;
90
+ const len = 1 << prefixBits;
91
+ if (offset + len > data.length) {
92
+ throw new BinaryDecodeError("varint: truncated length prefix");
93
+ }
94
+ let value = BigInt(first & 0x3f);
95
+ for (let i = 1; i < len; i++) {
96
+ value = (value << 8n) | BigInt(data[offset + i]);
97
+ }
98
+ if (value < VARINT_MINS[prefixBits]) {
99
+ throw new BinaryDecodeError(`varint: non-minimal encoding (value ${value} in ${len}-byte prefix)`);
100
+ }
101
+ return { value, length: len };
102
+ }
103
+ /** Number of bytes a value would occupy when encoded as a QUIC varint. */
104
+ export function varintSize(value) {
105
+ const v = toBigInt(value, "varint");
106
+ if (v < 0n || v > MAX_VARINT)
107
+ throw new RangeError(`varint out of range: ${v}`);
108
+ if (v < 64n)
109
+ return 1;
110
+ if (v < 16384n)
111
+ return 2;
112
+ if (v < 1073741824n)
113
+ return 4;
114
+ return 8;
115
+ }
116
+ /**
117
+ * Builds a byte string in the Marmot binary profile. Methods append in field order and
118
+ * return `this` for chaining; call {@link BinaryWriter.build} to materialize the bytes.
119
+ */
120
+ export class BinaryWriter {
121
+ chunks = [];
122
+ length = 0;
123
+ push(bytes) {
124
+ this.chunks.push(bytes);
125
+ this.length += bytes.length;
126
+ return this;
127
+ }
128
+ /** Appends a `uint8`. */
129
+ uint8(value) {
130
+ if (!Number.isInteger(value) || value < 0 || value > 0xff) {
131
+ throw new RangeError(`uint8 out of range: ${value}`);
132
+ }
133
+ return this.push(Uint8Array.of(value));
134
+ }
135
+ /** Appends a big-endian `uint16`. */
136
+ uint16(value) {
137
+ if (!Number.isInteger(value) || value < 0 || value > 0xffff) {
138
+ throw new RangeError(`uint16 out of range: ${value}`);
139
+ }
140
+ return this.push(Uint8Array.of((value >> 8) & 0xff, value & 0xff));
141
+ }
142
+ /** Appends a big-endian `uint32`. */
143
+ uint32(value) {
144
+ if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) {
145
+ throw new RangeError(`uint32 out of range: ${value}`);
146
+ }
147
+ const out = new Uint8Array(4);
148
+ new DataView(out.buffer).setUint32(0, value, false);
149
+ return this.push(out);
150
+ }
151
+ /** Appends a big-endian `uint64`. */
152
+ uint64(value) {
153
+ const v = toBigInt(value, "uint64");
154
+ if (v < 0n || v > 0xffffffffffffffffn) {
155
+ throw new RangeError(`uint64 out of range: ${v}`);
156
+ }
157
+ const out = new Uint8Array(8);
158
+ new DataView(out.buffer).setBigUint64(0, v, false);
159
+ return this.push(out);
160
+ }
161
+ /** Appends a QUIC variable-length integer. */
162
+ varint(value) {
163
+ return this.push(encodeVarint(value));
164
+ }
165
+ /** Appends raw fixed bytes with no length prefix (`opaque name[N]`). */
166
+ bytes(value) {
167
+ return this.push(value);
168
+ }
169
+ /**
170
+ * Appends a variable-length byte string as a QUIC varint length prefix followed by the
171
+ * bytes (`opaque name<min..max>`).
172
+ */
173
+ opaque(value, bounds) {
174
+ checkBounds(value.length, bounds, "opaque");
175
+ return this.push(encodeVarint(value.length)).push(value);
176
+ }
177
+ /**
178
+ * Appends a list as a QUIC varint byte-length prefix followed by the concatenated item
179
+ * encodings (`Type items<V>`).
180
+ */
181
+ vector(items, bounds) {
182
+ let total = 0;
183
+ for (const item of items)
184
+ total += item.length;
185
+ checkBounds(total, bounds, "vector");
186
+ this.varint(total);
187
+ for (const item of items)
188
+ this.push(item);
189
+ return this;
190
+ }
191
+ /** Materializes the accumulated bytes. */
192
+ build() {
193
+ const out = new Uint8Array(this.length);
194
+ let offset = 0;
195
+ for (const chunk of this.chunks) {
196
+ out.set(chunk, offset);
197
+ offset += chunk.length;
198
+ }
199
+ return out;
200
+ }
201
+ }
202
+ function checkBounds(len, bounds, field) {
203
+ if (!bounds)
204
+ return;
205
+ if (bounds.min !== undefined && len < bounds.min) {
206
+ throw new RangeError(`${field} length ${len} below minimum ${bounds.min}`);
207
+ }
208
+ if (bounds.max !== undefined && len > bounds.max) {
209
+ throw new RangeError(`${field} length ${len} above maximum ${bounds.max}`);
210
+ }
211
+ }
212
+ /**
213
+ * Reads a byte string in the Marmot binary profile with a moving cursor. Read methods
214
+ * advance the cursor and throw {@link BinaryDecodeError} on truncated or non-canonical
215
+ * input.
216
+ */
217
+ export class BinaryReader {
218
+ data;
219
+ offset = 0;
220
+ view;
221
+ constructor(data) {
222
+ this.data = data;
223
+ this.view = new DataView(data.buffer, data.byteOffset, data.byteLength);
224
+ }
225
+ /** Bytes not yet consumed. */
226
+ get remaining() {
227
+ return this.data.length - this.offset;
228
+ }
229
+ /** Current cursor position. */
230
+ get position() {
231
+ return this.offset;
232
+ }
233
+ /** Whether any bytes remain to be read. */
234
+ hasMore() {
235
+ return this.offset < this.data.length;
236
+ }
237
+ require(n, field) {
238
+ if (this.offset + n > this.data.length) {
239
+ throw new BinaryDecodeError(`${field}: read past end of buffer`);
240
+ }
241
+ }
242
+ /** Reads a `uint8`. */
243
+ uint8() {
244
+ this.require(1, "uint8");
245
+ return this.data[this.offset++];
246
+ }
247
+ /** Reads a big-endian `uint16`. */
248
+ uint16() {
249
+ this.require(2, "uint16");
250
+ const value = this.view.getUint16(this.offset, false);
251
+ this.offset += 2;
252
+ return value;
253
+ }
254
+ /** Reads a big-endian `uint32`. */
255
+ uint32() {
256
+ this.require(4, "uint32");
257
+ const value = this.view.getUint32(this.offset, false);
258
+ this.offset += 4;
259
+ return value;
260
+ }
261
+ /** Reads a big-endian `uint64`. */
262
+ uint64() {
263
+ this.require(8, "uint64");
264
+ const value = this.view.getBigUint64(this.offset, false);
265
+ this.offset += 8;
266
+ return value;
267
+ }
268
+ /** Reads a QUIC variable-length integer as a `bigint`. */
269
+ varintBig() {
270
+ const { value, length } = decodeVarint(this.data, this.offset);
271
+ this.offset += length;
272
+ return value;
273
+ }
274
+ /**
275
+ * Reads a QUIC variable-length integer as a `number`. Throws if the value exceeds
276
+ * {@link Number.MAX_SAFE_INTEGER}; use {@link BinaryReader.varintBig} for larger values.
277
+ */
278
+ varint() {
279
+ const value = this.varintBig();
280
+ if (value > BigInt(Number.MAX_SAFE_INTEGER)) {
281
+ throw new BinaryDecodeError(`varint: value ${value} exceeds safe integer range`);
282
+ }
283
+ return Number(value);
284
+ }
285
+ /** Reads exactly `n` raw bytes (`opaque name[N]`). */
286
+ bytes(n) {
287
+ if (!Number.isInteger(n) || n < 0) {
288
+ throw new RangeError(`bytes length must be a non-negative integer, got ${n}`);
289
+ }
290
+ this.require(n, "bytes");
291
+ const out = this.data.slice(this.offset, this.offset + n);
292
+ this.offset += n;
293
+ return out;
294
+ }
295
+ /**
296
+ * Reads a variable-length byte string written as a QUIC varint length prefix followed by
297
+ * the bytes (`opaque name<min..max>`). Enforces the field bounds when given.
298
+ */
299
+ opaque(bounds) {
300
+ const len = this.varint();
301
+ if (bounds) {
302
+ if (bounds.min !== undefined && len < bounds.min) {
303
+ throw new BinaryDecodeError(`opaque length ${len} below minimum ${bounds.min}`);
304
+ }
305
+ if (bounds.max !== undefined && len > bounds.max) {
306
+ throw new BinaryDecodeError(`opaque length ${len} above maximum ${bounds.max}`);
307
+ }
308
+ }
309
+ return this.bytes(len);
310
+ }
311
+ /**
312
+ * Reads a list written as a QUIC varint byte-length prefix followed by concatenated item
313
+ * encodings (`Type items<V>`). The body MUST decode to a whole number of items with no
314
+ * trailing bytes.
315
+ */
316
+ vector(readItem, bounds) {
317
+ const byteLength = this.varint();
318
+ if (bounds) {
319
+ if (bounds.min !== undefined && byteLength < bounds.min) {
320
+ throw new BinaryDecodeError(`vector length ${byteLength} below minimum ${bounds.min}`);
321
+ }
322
+ if (bounds.max !== undefined && byteLength > bounds.max) {
323
+ throw new BinaryDecodeError(`vector length ${byteLength} above maximum ${bounds.max}`);
324
+ }
325
+ }
326
+ this.require(byteLength, "vector");
327
+ // Copy (not subarray) so the inner reader owns an independent buffer — the
328
+ // same non-aliasing discipline as `bytes()`, avoiding a view that shares
329
+ // (and keeps alive) the outer backing store.
330
+ const body = this.data.slice(this.offset, this.offset + byteLength);
331
+ this.offset += byteLength;
332
+ const inner = new BinaryReader(body);
333
+ const items = [];
334
+ while (inner.hasMore()) {
335
+ items.push(readItem(inner));
336
+ }
337
+ if (inner.remaining !== 0) {
338
+ throw new BinaryDecodeError("vector: trailing bytes after final item");
339
+ }
340
+ return items;
341
+ }
342
+ /**
343
+ * Asserts that the cursor has consumed the entire buffer. Use this when a document says a
344
+ * value is "decoded exactly".
345
+ */
346
+ end() {
347
+ if (this.remaining !== 0) {
348
+ throw new BinaryDecodeError(`expected end of buffer, ${this.remaining} byte(s) remaining`);
349
+ }
350
+ }
351
+ }
352
+ /** UTF-8 encodes text. Marmot text fields are UTF-8 byte strings. */
353
+ export function encodeUtf8(text) {
354
+ return new TextEncoder().encode(text);
355
+ }
356
+ /**
357
+ * UTF-8 decodes bytes without Unicode normalization. A leading U+FEFF is
358
+ * content, not a byte-order mark (`ignoreBOM`): stripping it made
359
+ * `decode(encode(s)) !== s` and could turn a non-empty field empty.
360
+ */
361
+ export function decodeUtf8(bytes) {
362
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
363
+ }
@@ -0,0 +1,51 @@
1
+ /** @module @category Core - Capabilities */
2
+ import { Capabilities, type ExtensionRequiredCapabilities } from "ts-mls";
3
+ /**
4
+ * Ensures a {@link Capabilities} object advertises the MLS code points a Marmot
5
+ * v2 group relies on, so a LeafNode bearing these capabilities passes MLS
6
+ * leaf-capability validation when added to a group that carries them.
7
+ *
8
+ * Marmot v2 stores group state as versioned app components in the
9
+ * `app_data_dictionary` GroupContext extension (`0x0006`) and mutates them with
10
+ * `app_data_update` proposals (`0x0008`), both from draft-ietf-mls-extensions-09.
11
+ * Every member MUST advertise support for the extension and the proposal type.
12
+ * Key-package reusability (formerly a standalone MLS `last_resort`
13
+ * extension) is now signaled via the KeyPackage-level `app_data_dictionary`
14
+ * `0x0004` component (`key-package.ts`'s `isLastResortKeyPackage`), which
15
+ * needs no capability advertisement of its own. The `self_remove` proposal
16
+ * (`0x000a` proposal type) is still advertised for member departure
17
+ * (`protocol-core/member-departure.md`).
18
+ *
19
+ * The agent-text-stream-QUIC `receive` role capability (`0xf2d1`) is advertised
20
+ * so a member can be invited into a group whose
21
+ * `marmot.group.agent-text-stream.quic.v1` (`0x8006`) policy requires it —
22
+ * darkmatter's default group sets `required_member_roles = receive`, and its
23
+ * `do_send_invite` rejects any KeyPackage missing a required role capability
24
+ * (`agent-text-stream-quic-v1.md`).
25
+ *
26
+ * Only `receive` is advertised. The role extensions are capability *markers*
27
+ * (`registries.md`: "v1 defines no extension data for them"), and a client that
28
+ * does not implement raw QUIC is explicitly conformant — it "ignores the live
29
+ * preview and waits for the final MLS message" (`transports/quic.md`). marmot-ts
30
+ * honestly satisfies `receive` that way: it has no QUIC data plane (and raw QUIC
31
+ * is not portably available in browsers/Node/Bun), so it never advertises
32
+ * `send` (`0xf2d2`) or `fanout` (`0xf2d4`), which would claim the ability to
33
+ * originate or relay live QUIC streams it cannot fulfill.
34
+ */
35
+ export declare function ensureMarmotCapabilities(capabilities: Capabilities): Capabilities;
36
+ /**
37
+ * The Marmot v2 baseline `required_capabilities` (`0x0003`) GroupContext
38
+ * extension, set at group creation so every current and future member MUST
39
+ * advertise the protocol-mandatory code points. MLS then refuses to add a
40
+ * member whose LeafNode does not cover them (capability-negotiation.md §5.2
41
+ * "enforce on add").
42
+ *
43
+ * The baseline is fixed, not member-derived: the `app_data_dictionary`
44
+ * extension (`0x0006`) and account-identity-proof extension (`0xF2F1`) plus the
45
+ * `app_data_update` (`0x0008`) and `self_remove` (`0x000a`) proposals. The
46
+ * `self_remove` requirement matches a darkmatter MIP-03 client (which registers
47
+ * the self-remove feature as Required, advertising proposal type 10 in both leaf
48
+ * and required capabilities). Lists are sorted ascending to mirror the Rust
49
+ * `BTreeSet` ordering; `credentialTypes` is empty.
50
+ */
51
+ export declare function marmotRequiredCapabilitiesExtension(): ExtensionRequiredCapabilities;
@@ -0,0 +1,102 @@
1
+ /** @module @category Core - Capabilities */
2
+ import { appDataDictionaryExtensionType, appDataUpdateProposalType, defaultExtensionTypes, selfRemoveProposalType, } from "ts-mls";
3
+ import { ACCOUNT_IDENTITY_PROOF_EXTENSION_TYPE } from "./account-identity-proof.js";
4
+ import { AGENT_TEXT_STREAM_QUIC_RECEIVE_EXTENSION_TYPE } from "./components/agent-text-stream.js";
5
+ /**
6
+ * Ensures a {@link Capabilities} object advertises the MLS code points a Marmot
7
+ * v2 group relies on, so a LeafNode bearing these capabilities passes MLS
8
+ * leaf-capability validation when added to a group that carries them.
9
+ *
10
+ * Marmot v2 stores group state as versioned app components in the
11
+ * `app_data_dictionary` GroupContext extension (`0x0006`) and mutates them with
12
+ * `app_data_update` proposals (`0x0008`), both from draft-ietf-mls-extensions-09.
13
+ * Every member MUST advertise support for the extension and the proposal type.
14
+ * Key-package reusability (formerly a standalone MLS `last_resort`
15
+ * extension) is now signaled via the KeyPackage-level `app_data_dictionary`
16
+ * `0x0004` component (`key-package.ts`'s `isLastResortKeyPackage`), which
17
+ * needs no capability advertisement of its own. The `self_remove` proposal
18
+ * (`0x000a` proposal type) is still advertised for member departure
19
+ * (`protocol-core/member-departure.md`).
20
+ *
21
+ * The agent-text-stream-QUIC `receive` role capability (`0xf2d1`) is advertised
22
+ * so a member can be invited into a group whose
23
+ * `marmot.group.agent-text-stream.quic.v1` (`0x8006`) policy requires it —
24
+ * darkmatter's default group sets `required_member_roles = receive`, and its
25
+ * `do_send_invite` rejects any KeyPackage missing a required role capability
26
+ * (`agent-text-stream-quic-v1.md`).
27
+ *
28
+ * Only `receive` is advertised. The role extensions are capability *markers*
29
+ * (`registries.md`: "v1 defines no extension data for them"), and a client that
30
+ * does not implement raw QUIC is explicitly conformant — it "ignores the live
31
+ * preview and waits for the final MLS message" (`transports/quic.md`). marmot-ts
32
+ * honestly satisfies `receive` that way: it has no QUIC data plane (and raw QUIC
33
+ * is not portably available in browsers/Node/Bun), so it never advertises
34
+ * `send` (`0xf2d2`) or `fanout` (`0xf2d4`), which would claim the ability to
35
+ * originate or relay live QUIC streams it cannot fulfill.
36
+ */
37
+ export function ensureMarmotCapabilities(capabilities) {
38
+ const extensions = Array.from(capabilities.extensions);
39
+ const proposals = Array.from(capabilities.proposals);
40
+ // app_data_dictionary extension carrying the group's app components.
41
+ if (!extensions.includes(appDataDictionaryExtensionType))
42
+ extensions.push(appDataDictionaryExtensionType);
43
+ // NOTE: the legacy standalone `last_resort` MLS extension is no longer
44
+ // advertised here — key-package reusability is now signaled via the
45
+ // KeyPackage-level `app_data_dictionary` `0x0004` component (AC-VENDOR-8
46
+ // conformance patch, `isLastResortKeyPackage` in `key-package.ts`), which
47
+ // does not require a capability advertisement of its own (the dictionary
48
+ // extension type, `0x0006`, is already advertised above).
49
+ // account identity proof carried on the LeafNode binding the Nostr account.
50
+ if (!extensions.includes(ACCOUNT_IDENTITY_PROOF_EXTENSION_TYPE))
51
+ extensions.push(ACCOUNT_IDENTITY_PROOF_EXTENSION_TYPE);
52
+ // agent-text-stream-QUIC `receive` role capability so a group that requires it
53
+ // (e.g. darkmatter's default group) can invite this member. `receive` is an
54
+ // honest marker for a non-QUIC client (it reads the final MLS message); `send`
55
+ // and `fanout` are deliberately not advertised — see the doc comment above.
56
+ if (!extensions.includes(AGENT_TEXT_STREAM_QUIC_RECEIVE_EXTENSION_TYPE))
57
+ extensions.push(AGENT_TEXT_STREAM_QUIC_RECEIVE_EXTENSION_TYPE);
58
+ // app_data_update proposal that mutates the dictionary inside a commit.
59
+ if (!proposals.includes(appDataUpdateProposalType))
60
+ proposals.push(appDataUpdateProposalType);
61
+ // self_remove proposal for member departure (MIP-03).
62
+ if (!proposals.includes(selfRemoveProposalType))
63
+ proposals.push(selfRemoveProposalType);
64
+ return {
65
+ ...capabilities,
66
+ extensions,
67
+ proposals,
68
+ };
69
+ }
70
+ /**
71
+ * The Marmot v2 baseline `required_capabilities` (`0x0003`) GroupContext
72
+ * extension, set at group creation so every current and future member MUST
73
+ * advertise the protocol-mandatory code points. MLS then refuses to add a
74
+ * member whose LeafNode does not cover them (capability-negotiation.md §5.2
75
+ * "enforce on add").
76
+ *
77
+ * The baseline is fixed, not member-derived: the `app_data_dictionary`
78
+ * extension (`0x0006`) and account-identity-proof extension (`0xF2F1`) plus the
79
+ * `app_data_update` (`0x0008`) and `self_remove` (`0x000a`) proposals. The
80
+ * `self_remove` requirement matches a darkmatter MIP-03 client (which registers
81
+ * the self-remove feature as Required, advertising proposal type 10 in both leaf
82
+ * and required capabilities). Lists are sorted ascending to mirror the Rust
83
+ * `BTreeSet` ordering; `credentialTypes` is empty.
84
+ */
85
+ export function marmotRequiredCapabilitiesExtension() {
86
+ const extensionTypes = [
87
+ appDataDictionaryExtensionType,
88
+ ACCOUNT_IDENTITY_PROOF_EXTENSION_TYPE,
89
+ ].sort((a, b) => a - b);
90
+ const proposalTypes = [
91
+ appDataUpdateProposalType,
92
+ selfRemoveProposalType,
93
+ ].sort((a, b) => a - b);
94
+ return {
95
+ extensionType: defaultExtensionTypes.required_capabilities,
96
+ extensionData: {
97
+ extensionTypes,
98
+ proposalTypes,
99
+ credentialTypes: [],
100
+ },
101
+ };
102
+ }
@@ -0,0 +1,119 @@
1
+ import { ClientConfig, ClientState, GroupInfo } from "ts-mls";
2
+ import { type EncryptedMediaPolicyV1 } from "./components/index.js";
3
+ import type { GroupProtocolLifecycleValue } from "./components/index.js";
4
+ /** Default ClientConfig for Marmot. */
5
+ export declare const defaultMarmotClientConfig: ClientConfig;
6
+ /**
7
+ * A read projection of a Marmot group's app-component state, assembled from the
8
+ * group-scoped components in the MLS `app_data_dictionary` extension. This is
9
+ * the v2 replacement for the legacy `MarmotGroupData` monolith.
10
+ */
11
+ export interface MarmotGroupView {
12
+ /** Authenticated group protocol lifecycle, if the component is enabled. */
13
+ protocolLifecycle?: GroupProtocolLifecycleValue;
14
+ /** Public 32-byte nostr group id (from nostr routing), if routing is set. */
15
+ nostrGroupId?: Uint8Array;
16
+ /** Group display name (from the profile component). */
17
+ name: string;
18
+ /** Group description (from the profile component). */
19
+ description: string;
20
+ /** Admin nostr pubkeys (hex), from the admin-policy component. */
21
+ adminPubkeys: string[];
22
+ /** Nostr relay URLs (from nostr routing). */
23
+ relays: string[];
24
+ /** Group avatar URL (`group.avatar-url.v1`, `0x8007`), if set. */
25
+ avatarUrl?: string;
26
+ /**
27
+ * Group encrypted-media policy (`group.encrypted-media.v1`, `0x8008`): the
28
+ * group-scoped blob-store endpoints and format, if set.
29
+ */
30
+ encryptedMedia?: EncryptedMediaPolicyV1;
31
+ /**
32
+ * Message-retention window in seconds (`message-retention.v1`, `0x8005`), if
33
+ * set; `0n` means retain indefinitely.
34
+ */
35
+ messageRetention?: bigint;
36
+ }
37
+ export type MarmotGroupDecodedComponent = number[] | string[] | string | bigint | object;
38
+ /** Raw and decoded details for one app component in the MLS app_data_dictionary. */
39
+ export interface MarmotGroupComponentInfo {
40
+ /** Numeric MLS ComponentID. */
41
+ id: number;
42
+ /** Hex ComponentID, padded to uint16 width for display. */
43
+ idHex: string;
44
+ /** Known Marmot component name, or `unknown` for unrecognized ids. */
45
+ name: string;
46
+ /** Raw component data byte length. */
47
+ dataLength: number;
48
+ /** Raw component data as hex for protocol debugging. */
49
+ dataHex: string;
50
+ /** Decoded known component payload. Omitted when the component is unknown or invalid. */
51
+ decoded?: MarmotGroupDecodedComponent;
52
+ /** Decode failure for a known component. */
53
+ decodeError?: string;
54
+ }
55
+ /** Debug-oriented projection suitable for a chat/group info panel. */
56
+ export interface MarmotGroupInfo {
57
+ /** MLS protocol identifiers and epoch state. */
58
+ mls: {
59
+ groupId: Uint8Array;
60
+ groupIdHex: string;
61
+ epoch: bigint;
62
+ epochNumber: number;
63
+ epochString: string;
64
+ cipherSuite: number;
65
+ cipherSuiteName?: string;
66
+ treeHashHex: string;
67
+ confirmedTranscriptHashHex: string;
68
+ confirmationTagHex?: string;
69
+ historicalEpochs: string[];
70
+ memberCount: number;
71
+ proposalCount: number;
72
+ };
73
+ /** Marmot app-component state carried by the MLS group context. */
74
+ app: {
75
+ view: MarmotGroupView | null;
76
+ components: MarmotGroupComponentInfo[];
77
+ componentCount: number;
78
+ requiredComponentIds: number[];
79
+ decodeError?: string;
80
+ };
81
+ /** Public Nostr transport routing identity and relay set. */
82
+ nostr: {
83
+ groupId?: Uint8Array;
84
+ groupIdHex?: string;
85
+ relays: string[];
86
+ relayCount: number;
87
+ hasRouting: boolean;
88
+ };
89
+ /** Member identity summary decoded from the ratchet tree. */
90
+ members: {
91
+ pubkeys: string[];
92
+ count: number;
93
+ };
94
+ }
95
+ /**
96
+ * Reads the Marmot group view from a ClientState or GroupInfo. Returns null when
97
+ * the group carries no recognizable app components.
98
+ */
99
+ export declare function getMarmotGroupView(clientState: ClientState | GroupInfo): MarmotGroupView | null;
100
+ /**
101
+ * Builds a complete group information/debug projection from MLS state.
102
+ *
103
+ * This includes the private MLS group id and epoch details, decoded Marmot app
104
+ * components, public Nostr routing details, and member identity summary.
105
+ */
106
+ export declare function getMarmotGroupInfo(clientState: ClientState | GroupInfo): MarmotGroupInfo;
107
+ /** Reads the hex id of the group from a ClientState or GroupInfo object */
108
+ export declare function getGroupIdHex(clientState: ClientState | GroupInfo): string;
109
+ export declare function getNostrGroupIdHex(clientState: ClientState): string;
110
+ /** Reads the epoch number from a ClientState or GroupInfo object */
111
+ export declare function getEpoch(clientState: ClientState | GroupInfo): number;
112
+ /** Reads the number of members in the group from a ClientState ratchet tree */
113
+ export declare function getMemberCount(clientState: ClientState): number;
114
+ /** The serialized form of ClientState for storage (ts-mls TLS encoding). */
115
+ export type SerializedClientState = Uint8Array;
116
+ /** Serializes a ClientState object to a bytes array */
117
+ export declare function serializeClientState(state: ClientState): SerializedClientState;
118
+ /** Deserializes stored ClientState bytes (ts-mls TLS decoding). */
119
+ export declare function deserializeClientState(stored: SerializedClientState): ClientState;