@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,74 @@
1
+ /** @module @category Engine */
2
+ /** One pooled envelope awaiting a retained state that can decrypt it. */
3
+ export interface PooledEntry<TEnvelope> {
4
+ /** Stable transport id (kind-445 event id) — the pool key. */
5
+ id: string;
6
+ /** The raw undecryptable envelope. */
7
+ envelope: TEnvelope;
8
+ /** MLS-authenticated source epoch, when the wrapper has been peeled. */
9
+ sourceEpoch?: number;
10
+ /**
11
+ * History-tree node tags this entry has already been peeled against without
12
+ * success, so the tree-targeted sweep tries each `(event, node)` pair once.
13
+ */
14
+ triedTags: Set<string>;
15
+ }
16
+ /** Tuning for {@link IngestionPool}. */
17
+ export interface IngestionPoolOptions {
18
+ /** Max entries; new entries are refused while the pool is full. */
19
+ maxSize?: number;
20
+ /** Rollback horizon used for authenticated source-epoch expiry. */
21
+ maxRewindCommits?: number;
22
+ }
23
+ export type PoolAddResult = {
24
+ kind: "accepted";
25
+ } | {
26
+ kind: "refused";
27
+ reason: "capacity";
28
+ };
29
+ /**
30
+ * A persistent pool of incoming events that could not yet be decrypted against
31
+ * any tried state (Marmot v2 `protocol-core/inbound-processing.md` "deferred").
32
+ *
33
+ * Transport delivers events roughly chronologically, so a message from a newer
34
+ * epoch routinely arrives before the commit that unlocks its epoch key — and a
35
+ * fork/old-epoch message may arrive long after. Rather than dropping these as
36
+ * terminally unreadable, the engine holds them here and retries as the history
37
+ * tree grows (a new commit reaches their epoch, or a retained fork state is
38
+ * tried). Bounded by size and epoch-age so genuinely-undecryptable garbage
39
+ * (foreign or spam kind-445 events) cannot grow it without limit.
40
+ */
41
+ export declare class IngestionPool<TEnvelope> {
42
+ #private;
43
+ constructor(options?: IngestionPoolOptions);
44
+ /** Number of pooled entries. */
45
+ get size(): number;
46
+ /** Whether an entry with this id is pooled. */
47
+ has(id: string): boolean;
48
+ /**
49
+ * Pools an envelope (keyed by id). A peeled Commit supplies its authenticated
50
+ * source epoch. Capacity refusal is retryable and never evicts accepted work.
51
+ */
52
+ add(id: string, envelope: TEnvelope, sourceEpoch?: number): PoolAddResult;
53
+ /** Removes an entry (it was read, or is being given up). */
54
+ remove(id: string): void;
55
+ /**
56
+ * Clears every entry's tried-tag memo so the next tree sweep re-peels all
57
+ * pooled events against all node states. Called after a convergence branch
58
+ * switch: the canonical path changed, so a fork message previously held on a
59
+ * losing branch may now decrypt on the canonical one and be delivered.
60
+ */
61
+ resetTried(): void;
62
+ /** The pooled envelopes, oldest-first. */
63
+ envelopes(): TEnvelope[];
64
+ /** All pooled entries, oldest-first. */
65
+ entries(): PooledEntry<TEnvelope>[];
66
+ /**
67
+ * Drops authenticated deferred commits only once their source epoch is
68
+ * strictly beyond the rollback horizon. Opaque wrappers have no trustworthy
69
+ * epoch and remain capacity-bounded until they authenticate or are removed.
70
+ */
71
+ evictStale(currentEpoch: number): PooledEntry<TEnvelope>[];
72
+ /** Authenticated source epochs whose parent states remain active dependencies. */
73
+ sourceEpochs(): number[];
74
+ }
@@ -0,0 +1,95 @@
1
+ /** @module @category Engine */
2
+ const DEFAULT_MAX_SIZE = 1000;
3
+ /**
4
+ * A persistent pool of incoming events that could not yet be decrypted against
5
+ * any tried state (Marmot v2 `protocol-core/inbound-processing.md` "deferred").
6
+ *
7
+ * Transport delivers events roughly chronologically, so a message from a newer
8
+ * epoch routinely arrives before the commit that unlocks its epoch key — and a
9
+ * fork/old-epoch message may arrive long after. Rather than dropping these as
10
+ * terminally unreadable, the engine holds them here and retries as the history
11
+ * tree grows (a new commit reaches their epoch, or a retained fork state is
12
+ * tried). Bounded by size and epoch-age so genuinely-undecryptable garbage
13
+ * (foreign or spam kind-445 events) cannot grow it without limit.
14
+ */
15
+ export class IngestionPool {
16
+ #entries = new Map();
17
+ #maxSize;
18
+ #maxRewindCommits;
19
+ constructor(options) {
20
+ this.#maxSize = options?.maxSize ?? DEFAULT_MAX_SIZE;
21
+ this.#maxRewindCommits =
22
+ options?.maxRewindCommits ?? Number.POSITIVE_INFINITY;
23
+ }
24
+ /** Number of pooled entries. */
25
+ get size() {
26
+ return this.#entries.size;
27
+ }
28
+ /** Whether an entry with this id is pooled. */
29
+ has(id) {
30
+ return this.#entries.has(id);
31
+ }
32
+ /**
33
+ * Pools an envelope (keyed by id). A peeled Commit supplies its authenticated
34
+ * source epoch. Capacity refusal is retryable and never evicts accepted work.
35
+ */
36
+ add(id, envelope, sourceEpoch) {
37
+ const existing = this.#entries.get(id);
38
+ if (existing) {
39
+ if (existing.sourceEpoch === undefined && sourceEpoch !== undefined)
40
+ existing.sourceEpoch = sourceEpoch;
41
+ return { kind: "accepted" };
42
+ }
43
+ if (this.#entries.size >= this.#maxSize)
44
+ return { kind: "refused", reason: "capacity" };
45
+ this.#entries.set(id, {
46
+ id,
47
+ envelope,
48
+ sourceEpoch,
49
+ triedTags: new Set(),
50
+ });
51
+ return { kind: "accepted" };
52
+ }
53
+ /** Removes an entry (it was read, or is being given up). */
54
+ remove(id) {
55
+ this.#entries.delete(id);
56
+ }
57
+ /**
58
+ * Clears every entry's tried-tag memo so the next tree sweep re-peels all
59
+ * pooled events against all node states. Called after a convergence branch
60
+ * switch: the canonical path changed, so a fork message previously held on a
61
+ * losing branch may now decrypt on the canonical one and be delivered.
62
+ */
63
+ resetTried() {
64
+ for (const entry of this.#entries.values())
65
+ entry.triedTags.clear();
66
+ }
67
+ /** The pooled envelopes, oldest-first. */
68
+ envelopes() {
69
+ return [...this.#entries.values()].map((e) => e.envelope);
70
+ }
71
+ /** All pooled entries, oldest-first. */
72
+ entries() {
73
+ return [...this.#entries.values()];
74
+ }
75
+ /**
76
+ * Drops authenticated deferred commits only once their source epoch is
77
+ * strictly beyond the rollback horizon. Opaque wrappers have no trustworthy
78
+ * epoch and remain capacity-bounded until they authenticate or are removed.
79
+ */
80
+ evictStale(currentEpoch) {
81
+ const evicted = [];
82
+ for (const entry of this.#entries.values()) {
83
+ if (entry.sourceEpoch !== undefined &&
84
+ currentEpoch - entry.sourceEpoch > this.#maxRewindCommits)
85
+ evicted.push(entry);
86
+ }
87
+ for (const entry of evicted)
88
+ this.#entries.delete(entry.id);
89
+ return evicted;
90
+ }
91
+ /** Authenticated source epochs whose parent states remain active dependencies. */
92
+ sourceEpochs() {
93
+ return this.entries().flatMap((entry) => entry.sourceEpoch === undefined ? [] : [entry.sourceEpoch]);
94
+ }
95
+ }
@@ -0,0 +1,16 @@
1
+ /** @module @category Engine */
2
+ import { type MlsMessage } from "ts-mls";
3
+ /**
4
+ * The content-derived dedup id of an MLS message (`inbound-processing.md`;
5
+ * mirrors the reference engine's `content_dedup_id`): the lowercase-hex SHA-256
6
+ * of the TLS-serialized MLS message wire bytes, with no domain-separation
7
+ * prefix.
8
+ *
9
+ * It is computed over the peeled MLS message (the inner wire bytes), not the
10
+ * outer transport ciphertext, so the same message re-wrapped in a fresh kind-445
11
+ * envelope — new ephemeral key + nonce, hence a new Nostr event id — yields the
12
+ * same id. Distinct MLS ciphertexts produce distinct ids, so genuinely different
13
+ * messages are never collapsed. This is the key for replay dedup
14
+ * (`seen_message_ids`) and content-keyed own-echo detection (`sent_message_ids`).
15
+ */
16
+ export declare function contentDedupId(message: MlsMessage): string;
@@ -0,0 +1,20 @@
1
+ /** @module @category Engine */
2
+ import { encode, mlsMessageEncoder } from "ts-mls";
3
+ import { sha256 } from "@noble/hashes/sha2.js";
4
+ import { bytesToHex } from "@noble/hashes/utils.js";
5
+ /**
6
+ * The content-derived dedup id of an MLS message (`inbound-processing.md`;
7
+ * mirrors the reference engine's `content_dedup_id`): the lowercase-hex SHA-256
8
+ * of the TLS-serialized MLS message wire bytes, with no domain-separation
9
+ * prefix.
10
+ *
11
+ * It is computed over the peeled MLS message (the inner wire bytes), not the
12
+ * outer transport ciphertext, so the same message re-wrapped in a fresh kind-445
13
+ * envelope — new ephemeral key + nonce, hence a new Nostr event id — yields the
14
+ * same id. Distinct MLS ciphertexts produce distinct ids, so genuinely different
15
+ * messages are never collapsed. This is the key for replay dedup
16
+ * (`seen_message_ids`) and content-keyed own-echo detection (`sent_message_ids`).
17
+ */
18
+ export function contentDedupId(message) {
19
+ return bytesToHex(sha256(encode(mlsMessageEncoder, message)));
20
+ }
@@ -0,0 +1,30 @@
1
+ export type CommitOrderingPriority = "privileged" | "ordinary";
2
+ /** Evidence captured while a locally-authored commit is still staged. */
3
+ export interface OwnCommitConvergenceStamp {
4
+ /** Authenticated Marmot account identity of the committer. */
5
+ committer: string;
6
+ /** Authorization-aware ordering class decided at preparation time. */
7
+ priority: CommitOrderingPriority;
8
+ /** Exact proposal references consumed by the commit, sorted on storage. */
9
+ consumedProposalRefs: Uint8Array[];
10
+ }
11
+ export type DecodedOwnCommitRecord = {
12
+ kind: "stamped";
13
+ wireBytes: Uint8Array;
14
+ stamp: OwnCommitConvergenceStamp;
15
+ } | {
16
+ kind: "legacy";
17
+ wireBytes: Uint8Array;
18
+ };
19
+ /** Encodes a stamped own commit as a versioned, strictly-decodable record. */
20
+ export declare function encodeOwnCommitRecord(input: {
21
+ wireBytes: Uint8Array;
22
+ stamp: OwnCommitConvergenceStamp;
23
+ }): Uint8Array;
24
+ /**
25
+ * Decodes a stamped record, or explicitly reports an old bare-wire record.
26
+ * Bytes carrying the stamp magic always fail closed on malformed content.
27
+ */
28
+ export declare function decodeOwnCommitRecord(bytes: Uint8Array): DecodedOwnCommitRecord;
29
+ /** Stable record identity: SHA-256 of the exact MLS wire commit, never the stamp. */
30
+ export declare function ownCommitRecordIdentity(record: DecodedOwnCommitRecord): Uint8Array;
@@ -0,0 +1,71 @@
1
+ /** @module @category Engine */
2
+ import { sha256 } from "@noble/hashes/sha2.js";
3
+ import { BinaryReader, BinaryWriter } from "../core/binary.js";
4
+ const OWN_COMMIT_RECORD_MAGIC = Uint8Array.of(0x4f, 0x43, 0x53, 0x54); // OCST
5
+ const OWN_COMMIT_RECORD_VERSION = 1;
6
+ function startsWithMagic(bytes) {
7
+ return (bytes.length >= OWN_COMMIT_RECORD_MAGIC.length &&
8
+ OWN_COMMIT_RECORD_MAGIC.every((byte, index) => bytes[index] === byte));
9
+ }
10
+ function compareBytes(a, b) {
11
+ const length = Math.min(a.length, b.length);
12
+ for (let i = 0; i < length; i++) {
13
+ const difference = a[i] - b[i];
14
+ if (difference !== 0)
15
+ return difference;
16
+ }
17
+ return a.length - b.length;
18
+ }
19
+ /** Encodes a stamped own commit as a versioned, strictly-decodable record. */
20
+ export function encodeOwnCommitRecord(input) {
21
+ const references = input.stamp.consumedProposalRefs
22
+ .map((reference) => reference.slice())
23
+ .sort(compareBytes)
24
+ .map((reference) => new BinaryWriter().opaque(reference).build());
25
+ const priority = input.stamp.priority === "privileged" ? 0 : 1;
26
+ return new BinaryWriter()
27
+ .bytes(OWN_COMMIT_RECORD_MAGIC)
28
+ .uint8(OWN_COMMIT_RECORD_VERSION)
29
+ .opaque(input.wireBytes)
30
+ .opaque(new TextEncoder().encode(input.stamp.committer))
31
+ .uint8(priority)
32
+ .vector(references)
33
+ .build();
34
+ }
35
+ /**
36
+ * Decodes a stamped record, or explicitly reports an old bare-wire record.
37
+ * Bytes carrying the stamp magic always fail closed on malformed content.
38
+ */
39
+ export function decodeOwnCommitRecord(bytes) {
40
+ if (!startsWithMagic(bytes))
41
+ return { kind: "legacy", wireBytes: bytes.slice() };
42
+ const reader = new BinaryReader(bytes);
43
+ reader.bytes(OWN_COMMIT_RECORD_MAGIC.length);
44
+ const version = reader.uint8();
45
+ if (version !== OWN_COMMIT_RECORD_VERSION)
46
+ throw new Error(`Unknown own commit record version ${version}`);
47
+ const wireBytes = reader.opaque();
48
+ const committer = new TextDecoder("utf-8", { fatal: true }).decode(reader.opaque({ min: 1 }));
49
+ const priorityValue = reader.uint8();
50
+ if (priorityValue !== 0 && priorityValue !== 1)
51
+ throw new Error(`Unknown commit ordering priority ${priorityValue}`);
52
+ const consumedProposalRefs = reader.vector((item) => item.opaque());
53
+ reader.end();
54
+ for (let i = 1; i < consumedProposalRefs.length; i++) {
55
+ if (compareBytes(consumedProposalRefs[i - 1], consumedProposalRefs[i]) > 0)
56
+ throw new Error("Own commit proposal references are not sorted");
57
+ }
58
+ return {
59
+ kind: "stamped",
60
+ wireBytes,
61
+ stamp: {
62
+ committer,
63
+ priority: priorityValue === 0 ? "privileged" : "ordinary",
64
+ consumedProposalRefs,
65
+ },
66
+ };
67
+ }
68
+ /** Stable record identity: SHA-256 of the exact MLS wire commit, never the stamp. */
69
+ export function ownCommitRecordIdentity(record) {
70
+ return sha256(record.wireBytes);
71
+ }
@@ -0,0 +1,79 @@
1
+ /** @module @category Engine */
2
+ import { type ClientState, type MlsMessage } from "ts-mls";
3
+ import { type ConvergencePolicy } from "../core/convergence.js";
4
+ import type { OwnCommitConvergenceStamp } from "./own-commit-stamp.js";
5
+ /** Parent-bound evidence for one already-applied canonical commit. */
6
+ export interface RetainedAppliedLink {
7
+ parentState: ClientState;
8
+ message: MlsMessage;
9
+ resultingState: ClientState;
10
+ /** Present only for locally-authored commits confirmed by stamp-aware code. */
11
+ ownCommitStamp?: OwnCommitConvergenceStamp;
12
+ }
13
+ /**
14
+ * The bounded convergence window — the recent canonical states + applied commits
15
+ * the convergence hot path needs to rebuild candidate branches and recover from
16
+ * forks and late delivery (Marmot v2 `protocol-core/retained-history.md`).
17
+ *
18
+ * Holds, keyed by epoch number:
19
+ * - the canonical {@link ClientState} *at* each retained epoch (the parent for
20
+ * the next commit), and
21
+ * - the commit message applied to advance *from* each source epoch on our
22
+ * current canonical branch.
23
+ *
24
+ * Both maps are bounded to the rollback horizon (`max_rewind_commits`): material
25
+ * older than `tip - maxRewindCommits` is pruned on every {@link record}. This is
26
+ * a purely **in-memory, derived** index: it is never persisted (the full-fork
27
+ * {@link GroupHistoryTree} is the single persisted source) and is rebuilt from
28
+ * the tree's canonical path on load.
29
+ */
30
+ export declare class RetainedHistoryStore {
31
+ #private;
32
+ constructor(init: ClientState, policy?: ConvergencePolicy);
33
+ /** The retained canonical state at `epoch`, if still held. */
34
+ stateAt(epoch: number): ClientState | undefined;
35
+ /** Whether a canonical state is retained at `epoch`. */
36
+ hasState(epoch: number): boolean;
37
+ /** All retained canonical states (for cross-epoch decrypt retries). */
38
+ states(): IterableIterator<ClientState>;
39
+ /** Number of retained canonical states. */
40
+ get size(): number;
41
+ /** The oldest retained epoch (the retained anchor), or undefined if empty. */
42
+ anchorEpoch(): number | undefined;
43
+ /**
44
+ * The commits applied on our current canonical branch from `forkEpoch`
45
+ * (inclusive) up to but not including `tipEpoch`, in epoch order.
46
+ */
47
+ appliedCommitsBetween(forkEpoch: number, tipEpoch: number): MlsMessage[];
48
+ /**
49
+ * Parent-bound applied links on the current canonical branch. Unlike a
50
+ * digest plus later epoch lookups, each entry keeps the exact parent state
51
+ * (including proposal-reference evidence) beside its resulting state.
52
+ */
53
+ appliedLinksBetween(forkEpoch: number, tipEpoch: number): RetainedAppliedLink[];
54
+ /**
55
+ * Records the retained parent state and the applied commit message after
56
+ * advancing an epoch, then prunes retained material beyond the rollback
57
+ * horizon (`retained-history.md`).
58
+ *
59
+ * `pinnedEpochs` are epochs the caller's active lifecycle still needs and that
60
+ * MUST NOT be pruned even when older than the horizon (`retained-history.md`
61
+ * "Pruning": state needed to resolve an active PendingPublish / Merging /
62
+ * Recovering / Unrecoverable). The engine supplies them; e.g. the source epoch
63
+ * of a staged local commit the canonical tip has since advanced past.
64
+ */
65
+ record(parentState: ClientState, appliedMessage: MlsMessage, newState: ClientState, pinnedEpochs?: Iterable<number>, ownCommitStamp?: OwnCommitConvergenceStamp): void;
66
+ /**
67
+ * Seam: drops the retained material of a branch abandoned by a rewind onto a
68
+ * shallower tip — every state above `epoch` and every applied link leaving
69
+ * `epoch` or a later epoch — so the window holds only the canonical branch
70
+ * (a state at `epoch` and below, links that end at or below it). Pruning in
71
+ * {@link record} removes only material below the horizon, and a rewind
72
+ * records only the winner's epochs, so without this the abandoned branch's
73
+ * deeper states stayed retained (ADR-016 equivocation credit is the first
74
+ * path that rewinds onto a shallower tip).
75
+ */
76
+ discardAbove(epoch: number): void;
77
+ /** The highest retained epoch (the canonical tip), or undefined if empty. */
78
+ tipEpoch(): number | undefined;
79
+ }
@@ -0,0 +1,133 @@
1
+ import { DEFAULT_CONVERGENCE_POLICY, } from "../core/convergence.js";
2
+ import { prunableRetainedEpochs } from "../core/retained-history.js";
3
+ /**
4
+ * The bounded convergence window — the recent canonical states + applied commits
5
+ * the convergence hot path needs to rebuild candidate branches and recover from
6
+ * forks and late delivery (Marmot v2 `protocol-core/retained-history.md`).
7
+ *
8
+ * Holds, keyed by epoch number:
9
+ * - the canonical {@link ClientState} *at* each retained epoch (the parent for
10
+ * the next commit), and
11
+ * - the commit message applied to advance *from* each source epoch on our
12
+ * current canonical branch.
13
+ *
14
+ * Both maps are bounded to the rollback horizon (`max_rewind_commits`): material
15
+ * older than `tip - maxRewindCommits` is pruned on every {@link record}. This is
16
+ * a purely **in-memory, derived** index: it is never persisted (the full-fork
17
+ * {@link GroupHistoryTree} is the single persisted source) and is rebuilt from
18
+ * the tree's canonical path on load.
19
+ */
20
+ export class RetainedHistoryStore {
21
+ /** Canonical state at each retained epoch. Holds the state *at* that epoch. */
22
+ #states = new Map();
23
+ /** Commit applied to advance *from* each source epoch on our branch. */
24
+ #appliedLinks = new Map();
25
+ #policy;
26
+ constructor(init, policy = DEFAULT_CONVERGENCE_POLICY) {
27
+ this.#policy = policy;
28
+ this.#states.set(Number(init.groupContext.epoch), init);
29
+ }
30
+ /** The retained canonical state at `epoch`, if still held. */
31
+ stateAt(epoch) {
32
+ return this.#states.get(epoch);
33
+ }
34
+ /** Whether a canonical state is retained at `epoch`. */
35
+ hasState(epoch) {
36
+ return this.#states.has(epoch);
37
+ }
38
+ /** All retained canonical states (for cross-epoch decrypt retries). */
39
+ states() {
40
+ return this.#states.values();
41
+ }
42
+ /** Number of retained canonical states. */
43
+ get size() {
44
+ return this.#states.size;
45
+ }
46
+ /** The oldest retained epoch (the retained anchor), or undefined if empty. */
47
+ anchorEpoch() {
48
+ let min;
49
+ for (const epoch of this.#states.keys())
50
+ if (min === undefined || epoch < min)
51
+ min = epoch;
52
+ return min;
53
+ }
54
+ /**
55
+ * The commits applied on our current canonical branch from `forkEpoch`
56
+ * (inclusive) up to but not including `tipEpoch`, in epoch order.
57
+ */
58
+ appliedCommitsBetween(forkEpoch, tipEpoch) {
59
+ return this.appliedLinksBetween(forkEpoch, tipEpoch).map((link) => link.message);
60
+ }
61
+ /**
62
+ * Parent-bound applied links on the current canonical branch. Unlike a
63
+ * digest plus later epoch lookups, each entry keeps the exact parent state
64
+ * (including proposal-reference evidence) beside its resulting state.
65
+ */
66
+ appliedLinksBetween(forkEpoch, tipEpoch) {
67
+ const out = [];
68
+ for (let e = forkEpoch; e < tipEpoch; e++) {
69
+ const link = this.#appliedLinks.get(e);
70
+ if (link)
71
+ out.push(link);
72
+ }
73
+ return out;
74
+ }
75
+ /**
76
+ * Records the retained parent state and the applied commit message after
77
+ * advancing an epoch, then prunes retained material beyond the rollback
78
+ * horizon (`retained-history.md`).
79
+ *
80
+ * `pinnedEpochs` are epochs the caller's active lifecycle still needs and that
81
+ * MUST NOT be pruned even when older than the horizon (`retained-history.md`
82
+ * "Pruning": state needed to resolve an active PendingPublish / Merging /
83
+ * Recovering / Unrecoverable). The engine supplies them; e.g. the source epoch
84
+ * of a staged local commit the canonical tip has since advanced past.
85
+ */
86
+ record(parentState, appliedMessage, newState, pinnedEpochs = [], ownCommitStamp) {
87
+ const parentEpoch = Number(parentState.groupContext.epoch);
88
+ const newEpoch = Number(newState.groupContext.epoch);
89
+ const preceding = this.#appliedLinks.get(parentEpoch - 1);
90
+ if (preceding)
91
+ preceding.resultingState = parentState;
92
+ this.#states.set(parentEpoch, parentState);
93
+ this.#states.set(newEpoch, newState);
94
+ this.#appliedLinks.set(parentEpoch, {
95
+ parentState,
96
+ message: appliedMessage,
97
+ resultingState: newState,
98
+ ownCommitStamp,
99
+ });
100
+ const max = this.#policy.maxRewindCommits;
101
+ const pins = new Set(pinnedEpochs);
102
+ for (const epoch of prunableRetainedEpochs(this.#states.keys(), newEpoch, max, pins))
103
+ this.#states.delete(epoch);
104
+ for (const epoch of prunableRetainedEpochs(this.#appliedLinks.keys(), newEpoch, max, pins))
105
+ this.#appliedLinks.delete(epoch);
106
+ }
107
+ /**
108
+ * Seam: drops the retained material of a branch abandoned by a rewind onto a
109
+ * shallower tip — every state above `epoch` and every applied link leaving
110
+ * `epoch` or a later epoch — so the window holds only the canonical branch
111
+ * (a state at `epoch` and below, links that end at or below it). Pruning in
112
+ * {@link record} removes only material below the horizon, and a rewind
113
+ * records only the winner's epochs, so without this the abandoned branch's
114
+ * deeper states stayed retained (ADR-016 equivocation credit is the first
115
+ * path that rewinds onto a shallower tip).
116
+ */
117
+ discardAbove(epoch) {
118
+ for (const e of [...this.#states.keys()])
119
+ if (e > epoch)
120
+ this.#states.delete(e);
121
+ for (const e of [...this.#appliedLinks.keys()])
122
+ if (e >= epoch)
123
+ this.#appliedLinks.delete(e);
124
+ }
125
+ /** The highest retained epoch (the canonical tip), or undefined if empty. */
126
+ tipEpoch() {
127
+ let max;
128
+ for (const epoch of this.#states.keys())
129
+ if (max === undefined || epoch > max)
130
+ max = epoch;
131
+ return max;
132
+ }
133
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @module @category Engine
3
+ *
4
+ * Sender-ratchet advance seam (ADR-002 `seam` class).
5
+ *
6
+ * A client that loads an older snapshot of its own `ClientState` may already
7
+ * have sent application messages at generations the restored secret tree
8
+ * still treats as unused. If no relay it can read replays them, its next
9
+ * application message re-mints one of those (epoch, generation) pairs: same
10
+ * key and nonce (only the 4-byte reuse guard differs), and every member that
11
+ * read the earlier message refuses the new one (its ratchet has moved past
12
+ * that generation). Jumping the own application ratchet forward before that
13
+ * first message avoids every generation the snapshot could have missed, as
14
+ * long as the jump stays inside the receivers' forward window
15
+ * (`KeyRetentionConfig.maximumForwardRatchetSteps`).
16
+ *
17
+ * `advanceOwnApplicationRatchet` leaves the secret tree exactly as `steps`
18
+ * calls of ts-mls's internal `consumeRatchet` for the own leaf would (without
19
+ * producing any message): the own leaf's ratchets are derived first if they
20
+ * never were in this epoch, intermediate nodes on the way are consumed the
21
+ * same way, and the application ratchet's `unusedGenerations` is untouched
22
+ * (a sender keeps no secrets for generations it skipped). ts-mls does not
23
+ * export its secret-tree derivation, so RFC 9420's `ExpandWithLabel` /
24
+ * `DeriveTreeSecret` (section 8) and the left-balanced tree arithmetic
25
+ * (appendix C) are re-derived here over the exported `Kdf`.
26
+ *
27
+ * Nothing here runs unless a caller asks for it: `MarmotGroupEngine.send`
28
+ * applies it only for an `applicationMessage` intent carrying a positive
29
+ * `ratchetSkip`; without one the send path is upstream's.
30
+ */
31
+ import { type CiphersuiteImpl, type ClientConfig, type ClientState } from "ts-mls";
32
+ /**
33
+ * The largest `ratchetSkip` a receiver configured with `clientConfig` (ts-mls
34
+ * defaults when omitted) accepts in one jump:
35
+ * `keyRetentionConfig.maximumForwardRatchetSteps`.
36
+ */
37
+ export declare function maxSenderRatchetSkip(clientConfig?: ClientConfig): number;
38
+ /**
39
+ * The generation the own leaf's next application message uses in `state`'s
40
+ * epoch: 0 when its ratchet was never derived in this epoch.
41
+ */
42
+ export declare function nextOwnApplicationGeneration(state: ClientState): number;
43
+ /**
44
+ * A new state whose own-leaf application ratchet is `steps` generations
45
+ * further on — the secret tree `steps` own application messages would have
46
+ * left, with no message produced. `steps` must be a safe integer in
47
+ * `[0, maxSenderRatchetSkip(clientConfig)]`; `0` returns `state` itself. The
48
+ * input state is never mutated.
49
+ */
50
+ export declare function advanceOwnApplicationRatchet(state: ClientState, steps: number, cs: CiphersuiteImpl, clientConfig?: ClientConfig): Promise<ClientState>;