@941design/marmot 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 (192) hide show
  1. package/CHANGELOG.md +709 -0
  2. package/LICENSE +21 -0
  3. package/README.md +33 -2
  4. package/dist/account/admin.d.ts +72 -0
  5. package/dist/account/admin.js +209 -0
  6. package/dist/account/device-deps.d.ts +379 -0
  7. package/dist/account/device-deps.js +36 -0
  8. package/dist/account/device-lineage.d.ts +199 -0
  9. package/dist/account/device-lineage.js +390 -0
  10. package/dist/account/device-registry.d.ts +93 -0
  11. package/dist/account/device-registry.js +1290 -0
  12. package/dist/account/device-rotation.d.ts +61 -0
  13. package/dist/account/device-rotation.js +827 -0
  14. package/dist/account/enrolment.d.ts +339 -0
  15. package/dist/account/enrolment.js +1247 -0
  16. package/dist/account/identity-proof.d.ts +79 -0
  17. package/dist/account/identity-proof.js +264 -0
  18. package/dist/account/index.d.ts +17 -0
  19. package/dist/account/index.js +16 -0
  20. package/dist/account/restore-rotation.d.ts +21 -0
  21. package/dist/account/restore-rotation.js +22 -0
  22. package/dist/account/same-account-authorization.d.ts +86 -0
  23. package/dist/account/same-account-authorization.js +180 -0
  24. package/dist/account/teardown.d.ts +127 -0
  25. package/dist/account/teardown.js +856 -0
  26. package/dist/client/before-create-group.d.ts +18 -0
  27. package/dist/client/before-create-group.js +65 -0
  28. package/dist/client/before-publish-hooks.d.ts +121 -0
  29. package/dist/client/before-publish-hooks.js +180 -0
  30. package/dist/client/client-config.d.ts +42 -0
  31. package/dist/client/client-config.js +13 -0
  32. package/dist/client/commit-redrive.d.ts +68 -0
  33. package/dist/client/commit-redrive.js +221 -0
  34. package/dist/client/component-update.d.ts +43 -0
  35. package/dist/client/component-update.js +53 -0
  36. package/dist/client/confirm-hooks.d.ts +50 -0
  37. package/dist/client/confirm-hooks.js +59 -0
  38. package/dist/client/create-client.d.ts +1022 -0
  39. package/dist/client/create-client.js +1125 -0
  40. package/dist/client/group-disband.d.ts +28 -0
  41. package/dist/client/group-disband.js +64 -0
  42. package/dist/client/group-history.d.ts +435 -0
  43. package/dist/client/group-history.js +1295 -0
  44. package/dist/client/group-profile.d.ts +31 -0
  45. package/dist/client/group-profile.js +62 -0
  46. package/dist/client/group-records.d.ts +485 -0
  47. package/dist/client/group-records.js +1034 -0
  48. package/dist/client/group-removal.d.ts +36 -0
  49. package/dist/client/group-removal.js +127 -0
  50. package/dist/client/group-remove-member.d.ts +49 -0
  51. package/dist/client/group-remove-member.js +163 -0
  52. package/dist/client/group-runtime.d.ts +388 -0
  53. package/dist/client/group-runtime.js +2701 -0
  54. package/dist/client/group-snapshot.d.ts +98 -0
  55. package/dist/client/group-snapshot.js +453 -0
  56. package/dist/client/history-pages.d.ts +107 -0
  57. package/dist/client/history-pages.js +194 -0
  58. package/dist/client/inbox-send.d.ts +19 -0
  59. package/dist/client/inbox-send.js +71 -0
  60. package/dist/client/index.d.ts +21 -0
  61. package/dist/client/index.js +13 -0
  62. package/dist/client/ingest.d.ts +82 -0
  63. package/dist/client/ingest.js +1550 -0
  64. package/dist/client/lifecycle-events.d.ts +63 -0
  65. package/dist/client/lifecycle-events.js +35 -0
  66. package/dist/client/opaque-candidates.d.ts +81 -0
  67. package/dist/client/opaque-candidates.js +169 -0
  68. package/dist/client/own-change-outbox.d.ts +66 -0
  69. package/dist/client/own-change-outbox.js +156 -0
  70. package/dist/client/pending-leaf.d.ts +116 -0
  71. package/dist/client/pending-leaf.js +378 -0
  72. package/dist/client/permissions.d.ts +9 -0
  73. package/dist/client/permissions.js +12 -0
  74. package/dist/client/pipeline.d.ts +554 -0
  75. package/dist/client/pipeline.js +3545 -0
  76. package/dist/client/reentrancy-guard.d.ts +96 -0
  77. package/dist/client/reentrancy-guard.js +153 -0
  78. package/dist/client/rekey.d.ts +58 -0
  79. package/dist/client/rekey.js +149 -0
  80. package/dist/client/transport-policy.d.ts +181 -0
  81. package/dist/client/transport-policy.js +214 -0
  82. package/dist/history/equivocation.d.ts +55 -0
  83. package/dist/history/equivocation.js +113 -0
  84. package/dist/history/fencing.d.ts +25 -0
  85. package/dist/history/fencing.js +61 -0
  86. package/dist/history/hex.d.ts +3 -0
  87. package/dist/history/hex.js +10 -0
  88. package/dist/history/index.d.ts +73 -0
  89. package/dist/history/index.js +31 -0
  90. package/dist/history/notifications.d.ts +270 -0
  91. package/dist/history/notifications.js +264 -0
  92. package/dist/history/ordering-key.d.ts +24 -0
  93. package/dist/history/ordering-key.js +101 -0
  94. package/dist/history/own-change-fork.d.ts +112 -0
  95. package/dist/history/own-change-fork.js +196 -0
  96. package/dist/history/own-change.d.ts +106 -0
  97. package/dist/history/own-change.js +146 -0
  98. package/dist/history/policy.d.ts +48 -0
  99. package/dist/history/policy.js +52 -0
  100. package/dist/history/retained-window.d.ts +215 -0
  101. package/dist/history/retained-window.js +565 -0
  102. package/dist/inbox/demux.d.ts +90 -0
  103. package/dist/inbox/demux.js +78 -0
  104. package/dist/inbox/handler-registry.d.ts +42 -0
  105. package/dist/inbox/handler-registry.js +37 -0
  106. package/dist/inbox/index.d.ts +11 -0
  107. package/dist/inbox/index.js +10 -0
  108. package/dist/inbox/seen-set.d.ts +82 -0
  109. package/dist/inbox/seen-set.js +202 -0
  110. package/dist/inbox/subscription.d.ts +236 -0
  111. package/dist/inbox/subscription.js +644 -0
  112. package/dist/index.d.ts +10 -0
  113. package/dist/index.js +9 -0
  114. package/dist/invitations/competing-welcome.d.ts +223 -0
  115. package/dist/invitations/competing-welcome.js +128 -0
  116. package/dist/invitations/decline.d.ts +61 -0
  117. package/dist/invitations/decline.js +143 -0
  118. package/dist/invitations/expect-welcome.d.ts +66 -0
  119. package/dist/invitations/expect-welcome.js +138 -0
  120. package/dist/invitations/index.d.ts +16 -0
  121. package/dist/invitations/index.js +16 -0
  122. package/dist/invitations/invite.d.ts +303 -0
  123. package/dist/invitations/invite.js +966 -0
  124. package/dist/invitations/offers.d.ts +79 -0
  125. package/dist/invitations/offers.js +115 -0
  126. package/dist/invitations/on-proposal.d.ts +47 -0
  127. package/dist/invitations/on-proposal.js +40 -0
  128. package/dist/invitations/pending-proposal-policy.d.ts +52 -0
  129. package/dist/invitations/pending-proposal-policy.js +139 -0
  130. package/dist/invitations/proposal-deadline.d.ts +133 -0
  131. package/dist/invitations/proposal-deadline.js +164 -0
  132. package/dist/invitations/relay-planes.d.ts +43 -0
  133. package/dist/invitations/relay-planes.js +70 -0
  134. package/dist/invitations/welcome-processor.d.ts +253 -0
  135. package/dist/invitations/welcome-processor.js +1180 -0
  136. package/dist/key-packages/device-key.d.ts +131 -0
  137. package/dist/key-packages/device-key.js +272 -0
  138. package/dist/key-packages/device-rotation-records.d.ts +83 -0
  139. package/dist/key-packages/device-rotation-records.js +173 -0
  140. package/dist/key-packages/group-refs.d.ts +40 -0
  141. package/dist/key-packages/group-refs.js +79 -0
  142. package/dist/key-packages/index.d.ts +18 -0
  143. package/dist/key-packages/index.js +18 -0
  144. package/dist/key-packages/key-package-ref.d.ts +16 -0
  145. package/dist/key-packages/key-package-ref.js +21 -0
  146. package/dist/key-packages/observation-stream.d.ts +4 -0
  147. package/dist/key-packages/observation-stream.js +120 -0
  148. package/dist/key-packages/offer-rumor.d.ts +26 -0
  149. package/dist/key-packages/offer-rumor.js +69 -0
  150. package/dist/key-packages/publisher.d.ts +174 -0
  151. package/dist/key-packages/publisher.js +1247 -0
  152. package/dist/key-packages/select-key-package.d.ts +24 -0
  153. package/dist/key-packages/select-key-package.js +90 -0
  154. package/dist/key-packages/slot-manager.d.ts +167 -0
  155. package/dist/key-packages/slot-manager.js +327 -0
  156. package/dist/key-packages/validate-key-package-event.d.ts +3 -0
  157. package/dist/key-packages/validate-key-package-event.js +49 -0
  158. package/dist/media/cache.d.ts +14 -0
  159. package/dist/media/cache.js +10 -0
  160. package/dist/media/index.d.ts +52 -0
  161. package/dist/media/index.js +71 -0
  162. package/dist/mls.d.ts +15 -0
  163. package/dist/mls.js +15 -0
  164. package/dist/shared/account-pubkey.d.ts +4 -0
  165. package/dist/shared/account-pubkey.js +10 -0
  166. package/dist/shared/errors.d.ts +21 -0
  167. package/dist/shared/errors.js +85 -0
  168. package/dist/shared/hex.d.ts +4 -0
  169. package/dist/shared/hex.js +13 -0
  170. package/dist/shared/index.d.ts +14 -0
  171. package/dist/shared/index.js +14 -0
  172. package/dist/shared/kinds.d.ts +8 -0
  173. package/dist/shared/kinds.js +28 -0
  174. package/dist/shared/publish-classification.d.ts +26 -0
  175. package/dist/shared/publish-classification.js +31 -0
  176. package/dist/storage/envelope.d.ts +39 -0
  177. package/dist/storage/envelope.js +201 -0
  178. package/dist/storage/index.d.ts +227 -0
  179. package/dist/storage/index.js +459 -0
  180. package/dist/storage/indexeddb/idb-types.d.ts +68 -0
  181. package/dist/storage/indexeddb/idb-types.js +1 -0
  182. package/dist/storage/indexeddb/index.d.ts +17 -0
  183. package/dist/storage/indexeddb/index.js +141 -0
  184. package/dist/storage/lease.d.ts +41 -0
  185. package/dist/storage/lease.js +117 -0
  186. package/dist/storage/memory/deterministic-signer.d.ts +27 -0
  187. package/dist/storage/memory/deterministic-signer.js +65 -0
  188. package/dist/storage/memory/index.d.ts +32 -0
  189. package/dist/storage/memory/index.js +87 -0
  190. package/dist/storage/memory/lock-manager.d.ts +8 -0
  191. package/dist/storage/memory/lock-manager.js +71 -0
  192. package/package.json +66 -3
@@ -0,0 +1,214 @@
1
+ import { classifyPublish, MarmotError } from '../shared/index.js';
2
+ // Gate-remediation R2: `classifyPublish`/`PublishOutcome` now live in
3
+ // `shared/publish-classification.ts` (key-packages/ needs the same
4
+ // classification and cannot import client/) — re-exported here UNCHANGED so
5
+ // this module's own callers (pipeline.ts) and its tests need no changes.
6
+ export { classifyPublish };
7
+ /** Kind of Marmot group events (MIP-03). */
8
+ export const GROUP_EVENT_KIND = 445;
9
+ /**
10
+ * The group's relay plane for kind 445: the group state's relays (routing
11
+ * component), or `fallback` (the client's `relays.defaults`) when the group
12
+ * names none. Order preserved, raw strings, duplicates dropped by exact match.
13
+ */
14
+ export function groupRelayPlane(groupRelays, fallback) {
15
+ const source = groupRelays.length > 0 ? groupRelays : fallback;
16
+ const seen = new Set();
17
+ const plane = [];
18
+ for (const relay of source) {
19
+ if (seen.has(relay))
20
+ continue;
21
+ seen.add(relay);
22
+ plane.push(relay);
23
+ }
24
+ return plane;
25
+ }
26
+ /** The kind-445 filter for one group, `since` the cursor when given. */
27
+ export function groupEventFilter(nostrGroupId, since) {
28
+ const filter = { kinds: [GROUP_EVENT_KIND], '#h': [nostrGroupId] };
29
+ if (since !== undefined)
30
+ filter.since = since;
31
+ return filter;
32
+ }
33
+ export function createHistorySilenceTracker(threshold) {
34
+ if (!Number.isInteger(threshold) || threshold <= 0) {
35
+ throw new MarmotError('invalid-options', `createHistorySilenceTracker: threshold must be a positive integer, got ${JSON.stringify(threshold)}`);
36
+ }
37
+ // Consecutive-silence count per relay, and the excluded set (insertion order preserved for `excluded()`).
38
+ const counters = new Map();
39
+ const excludedOrder = [];
40
+ const excludedSet = new Set();
41
+ return {
42
+ record(requested, result) {
43
+ const newlySilent = [];
44
+ const silentSet = new Set(result.silentRelays);
45
+ for (const relay of requested) {
46
+ if (result.timedOut && silentSet.has(relay)) {
47
+ const count = (counters.get(relay) ?? 0) + 1;
48
+ counters.set(relay, count);
49
+ if (count >= threshold && !excludedSet.has(relay)) {
50
+ excludedSet.add(relay);
51
+ excludedOrder.push(relay);
52
+ newlySilent.push(relay);
53
+ }
54
+ }
55
+ else {
56
+ counters.set(relay, 0);
57
+ }
58
+ }
59
+ return { newlySilent };
60
+ },
61
+ historyRelays(plane) {
62
+ const filtered = plane.filter((relay) => !excludedSet.has(relay));
63
+ return filtered.length > 0 ? filtered : [...plane];
64
+ },
65
+ excluded() {
66
+ return [...excludedOrder];
67
+ },
68
+ exclude(relay) {
69
+ if (excludedSet.has(relay))
70
+ return false;
71
+ excludedSet.add(relay);
72
+ excludedOrder.push(relay);
73
+ return true;
74
+ },
75
+ };
76
+ }
77
+ export const CURSOR_KEY = 'kind445';
78
+ /** Tolerated future skew of an event's `created_at` against the client clock (seconds). */
79
+ export const CURSOR_FUTURE_SKEW_S = 300;
80
+ /** `since` sits this far below the cursor's floor so late-stamped events are redelivered; the ledger dedups them (seconds). */
81
+ export const CURSOR_REDELIVERY_MARGIN_S = 300;
82
+ /** Ledger entries whose event `created_at` lies this far below the cursor's `since` are pruned (seconds). */
83
+ export const LEDGER_RETENTION_S = 7 * 86_400;
84
+ /** An undecryptable hold older than this is given up, so junk cannot pin the cursor forever (seconds). Pins are exempt. */
85
+ export const HOLD_MAX_AGE_S = 7 * 86_400;
86
+ /** At most this many undecryptable holds are kept (eviction policy: see {@link IngestCursor}), bounding the cursor record. Pins are exempt. */
87
+ export const MAX_HOLDS = 1000;
88
+ /** At most this many `group-busy` holds are kept (eviction policy: see {@link IngestCursor}), bounding the record during a long blocked confirmation. */
89
+ export const MAX_BUSY_PINS = 1000;
90
+ const byId = (a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
91
+ /**
92
+ * The cursor after one sync batch (see {@link IngestCursor}); `current`
93
+ * itself when nothing moved it. `high` never decreases except through the
94
+ * future-skew clamp; `since` may move backwards when a new hold predates it.
95
+ * A cursor without `high` (nothing authenticated has advanced it yet) keeps
96
+ * its `since` until something does.
97
+ */
98
+ export function nextCursor(current, update, nowSeconds) {
99
+ const ceiling = nowSeconds + CURSOR_FUTURE_SKEW_S;
100
+ let high = current?.high === undefined ? undefined : Math.min(current.high, ceiling);
101
+ for (const createdAt of update.advanced) {
102
+ const clamped = Math.min(createdAt, ceiling);
103
+ high = high === undefined ? clamped : Math.max(high, clamped);
104
+ }
105
+ const holds = new Map(Object.entries(current?.holds ?? {}));
106
+ const pins = new Map(Object.entries(current?.pins ?? {}));
107
+ const busy = new Map(Object.entries(current?.busy ?? {}));
108
+ for (const id of update.released) {
109
+ holds.delete(id);
110
+ pins.delete(id);
111
+ busy.delete(id);
112
+ }
113
+ // The batch's classification of an event replaces any earlier tier it sat in.
114
+ for (const [id, createdAt] of update.held) {
115
+ if (update.released.has(id))
116
+ continue;
117
+ pins.delete(id);
118
+ busy.delete(id);
119
+ if (createdAt <= ceiling)
120
+ holds.set(id, createdAt);
121
+ }
122
+ for (const [id, createdAt] of update.pinned) {
123
+ if (update.released.has(id))
124
+ continue;
125
+ holds.delete(id);
126
+ busy.delete(id);
127
+ if (createdAt <= ceiling)
128
+ pins.set(id, createdAt);
129
+ }
130
+ // `group-busy` says nothing new about an event already classified: it keeps its tier.
131
+ for (const [id, createdAt] of update.busy ?? []) {
132
+ if (update.released.has(id) || pins.has(id) || holds.has(id))
133
+ continue;
134
+ if (createdAt <= ceiling)
135
+ busy.set(id, createdAt);
136
+ }
137
+ for (const [id, createdAt] of holds)
138
+ if (createdAt < nowSeconds - HOLD_MAX_AGE_S)
139
+ holds.delete(id);
140
+ // The capped tiers' eviction policy (see IngestCursor): the oldest are kept.
141
+ const oldestFirst = (a, b) => a[1] - b[1] || byId(a, b);
142
+ const keptHolds = [...holds].sort(oldestFirst).slice(0, MAX_HOLDS);
143
+ const keptBusy = [...busy].sort(oldestFirst).slice(0, MAX_BUSY_PINS);
144
+ const keptPins = [...pins];
145
+ const resume = update.resume === undefined ? current?.resume : (update.resume ?? undefined);
146
+ let floor = high;
147
+ for (const [, createdAt] of [...keptHolds, ...keptPins, ...keptBusy])
148
+ floor = floor === undefined ? createdAt : Math.min(floor, createdAt);
149
+ // An unwalked window keeps `since` at or below its `from`.
150
+ if (resume !== undefined)
151
+ floor = Math.min(floor ?? Infinity, resume.from + CURSOR_REDELIVERY_MARGIN_S);
152
+ if (floor === undefined) {
153
+ // Nothing authenticated yet and no hold left: keep `since` where it was.
154
+ return current === undefined || (current.holds === undefined && current.pins === undefined && current.busy === undefined && current.resume === undefined)
155
+ ? current
156
+ : { since: current.since };
157
+ }
158
+ const next = {
159
+ since: Math.max(0, floor - CURSOR_REDELIVERY_MARGIN_S),
160
+ ...(high === undefined ? {} : { high }),
161
+ ...(keptHolds.length === 0 ? {} : { holds: Object.fromEntries(keptHolds.sort(byId)) }),
162
+ ...(keptPins.length === 0 ? {} : { pins: Object.fromEntries(keptPins.sort(byId)) }),
163
+ ...(keptBusy.length === 0 ? {} : { busy: Object.fromEntries(keptBusy.sort(byId)) }),
164
+ ...(resume === undefined ? {} : { resume: copyResume(resume) }),
165
+ };
166
+ return current !== undefined && sameCursor(current, next) ? current : next;
167
+ }
168
+ /**
169
+ * Pins and busy entries of `cursor` that a history pass should have
170
+ * returned but did not — so no relay can still redeliver them, and the
171
+ * entry would otherwise hold the floor forever. An entry is released only
172
+ * when the pass was complete (not `timedOut`, pagination finished — a
173
+ * truncated response proves nothing about what it cut off), covered the
174
+ * entry's `created_at` (within `[since, until]`, each edge open when absent,
175
+ * and not on a gap second a relay may have truncated), and
176
+ * asked the whole relay plane (a relay excluded as silent may still hold
177
+ * it). Anything else releases nothing.
178
+ */
179
+ export function absentPins(cursor, coverage, returnedIds) {
180
+ const absent = new Set();
181
+ if (!coverage.complete || !coverage.wholePlane)
182
+ return absent;
183
+ const { since, until } = coverage;
184
+ const gaps = new Set(coverage.gaps);
185
+ for (const tier of [cursor?.pins, cursor?.busy]) {
186
+ for (const [id, createdAt] of Object.entries(tier ?? {})) {
187
+ if ((since === undefined || createdAt >= since) && (until === undefined || createdAt <= until) && !gaps.has(createdAt) && !returnedIds.has(id))
188
+ absent.add(id);
189
+ }
190
+ }
191
+ return absent;
192
+ }
193
+ function copyResume(resume) {
194
+ return {
195
+ from: resume.from,
196
+ ...(resume.until === undefined ? {} : { until: resume.until }),
197
+ ...(resume.above === undefined || resume.above.length === 0 ? {} : { above: [...resume.above] }),
198
+ };
199
+ }
200
+ function sameHoldMap(a, b) {
201
+ const ah = Object.entries(a ?? {});
202
+ const bh = b ?? {};
203
+ return ah.length === Object.keys(bh).length && ah.every(([id, at]) => bh[id] === at);
204
+ }
205
+ function sameCursor(a, b) {
206
+ return (a.since === b.since &&
207
+ a.high === b.high &&
208
+ a.resume?.from === b.resume?.from &&
209
+ a.resume?.until === b.resume?.until &&
210
+ (a.resume?.above ?? []).join() === (b.resume?.above ?? []).join() &&
211
+ sameHoldMap(a.holds, b.holds) &&
212
+ sameHoldMap(a.pins, b.pins) &&
213
+ sameHoldMap(a.busy, b.busy));
214
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Equivocation records (epic `marmot-rewind-takeover-stale-leaf-snapshot`, ADR-016 D5, architecture.md SC-6): the
3
+ * durable, once-only form of the engine's `LeafEquivocation` report — one leaf authored two or more distinct child
4
+ * commits of one node, which no honest Marmot client does (a restored stale leaf snapshot does).
5
+ *
6
+ * Each piece of evidence is identified by `${nodeTag}:${leafIndex}` (the same whichever selection site or member
7
+ * found it). Client ingest writes its record inside the batch's store transaction (or, for evidence found outside a batch, in
8
+ * a transaction of its own) only when the key is absent, and announces it (`leaf-equivocation`) only after that transaction committed and only for keys it newly wrote: a
9
+ * re-report — a later tree-fed pass, a redelivery, a rebuilt engine — finds the key and is not announced again.
10
+ * Further sibling commits by the same leaf at the same node are the same evidence. Records carry no timestamp and
11
+ * are never pruned (architecture.md OQ-4).
12
+ */
13
+ import type { LeafEquivocation } from '@941design/marmot-engine/core';
14
+ import type { KeyValueView } from '../storage/index.js';
15
+ import type { LeafEquivocationNotification } from './notifications.js';
16
+ /** Group extension namespace of the equivocation records. */
17
+ export declare const EQUIVOCATION_EXTENSION = "marmot.equivocation";
18
+ /** One stored piece of evidence. `epoch` is the node's MLS epoch in decimal (the stored form of a bigint). */
19
+ export interface EquivocationRecord {
20
+ readonly leafIndex: number;
21
+ readonly account: string;
22
+ readonly leafKey: string;
23
+ readonly epoch: string;
24
+ readonly nodeTag: string;
25
+ readonly commitDigests: readonly string[];
26
+ }
27
+ /** The record key of a piece of evidence: `${nodeTag}:${leafIndex}`. */
28
+ export declare function equivocationKey(evidence: {
29
+ readonly nodeTag: string;
30
+ readonly leafIndex: number;
31
+ }): string;
32
+ /** The record of an engine report (digests de-duplicated, ascending). */
33
+ export declare function equivocationRecordOf(evidence: LeafEquivocation): EquivocationRecord;
34
+ /** The application-visible notification of a record. */
35
+ export declare function equivocationNotification(record: EquivocationRecord): LeafEquivocationNotification;
36
+ /**
37
+ * Whether `value` is an engine report this module can record: an object whose `leafIndex` and `epoch` are
38
+ * non-negative safe integers, whose `account` / `leafKey` / `nodeTag` are lowercase hex, and whose `commitDigests`
39
+ * name two or more distinct lowercase-hex digests — exactly what {@link equivocationRecordOf} turns into a record the
40
+ * decoder reads back. Anything else (`undefined` from a result that carries no evidence, a partial object) would
41
+ * otherwise be merged and written as a record no reader ever returns, occupying its key for good.
42
+ */
43
+ export declare function isRecordableEquivocation(value: unknown): value is LeafEquivocation;
44
+ /** Every well-formed record of the group, by key order. A malformed entry is skipped (it still occupies its key). */
45
+ export declare function readEquivocations(view: KeyValueView): Promise<EquivocationRecord[]>;
46
+ /**
47
+ * The application-visible form of every well-formed record of the group — what `MarmotGroup.equivocations()`
48
+ * returns: one notification per record, ordered by `(epoch, nodeTag, leafIndex)` (numeric epoch), frozen.
49
+ */
50
+ export declare function readEquivocationNotifications(view: KeyValueView): Promise<readonly LeafEquivocationNotification[]>;
51
+ /**
52
+ * Writes `record` under its key unless that key is already present (whatever it holds): true iff this call wrote
53
+ * it. Called inside the batch's store transaction, so the check and the write are one atomic unit.
54
+ */
55
+ export declare function writeEquivocation(view: KeyValueView, record: EquivocationRecord): Promise<boolean>;
@@ -0,0 +1,113 @@
1
+ /** Group extension namespace of the equivocation records. */
2
+ export const EQUIVOCATION_EXTENSION = 'marmot.equivocation';
3
+ /** The record key of a piece of evidence: `${nodeTag}:${leafIndex}`. */
4
+ export function equivocationKey(evidence) {
5
+ return `${evidence.nodeTag}:${String(evidence.leafIndex)}`;
6
+ }
7
+ /** The record of an engine report (digests de-duplicated, ascending). */
8
+ export function equivocationRecordOf(evidence) {
9
+ return {
10
+ leafIndex: evidence.leafIndex,
11
+ account: evidence.account,
12
+ leafKey: evidence.leafKey,
13
+ epoch: String(evidence.epoch),
14
+ nodeTag: evidence.nodeTag,
15
+ commitDigests: [...new Set(evidence.commitDigests)].sort(),
16
+ };
17
+ }
18
+ /** The application-visible notification of a record. */
19
+ export function equivocationNotification(record) {
20
+ return {
21
+ type: 'leaf-equivocation',
22
+ leafIndex: record.leafIndex,
23
+ account: record.account,
24
+ leafKey: record.leafKey,
25
+ epoch: BigInt(record.epoch),
26
+ nodeTag: record.nodeTag,
27
+ commitDigests: Object.freeze([...record.commitDigests]),
28
+ };
29
+ }
30
+ /** Non-empty, even-length lowercase hex — the only form this module ever writes. */
31
+ const LOWER_HEX = /^(?:[0-9a-f]{2})+$/;
32
+ function isLowerHex(value) {
33
+ return typeof value === 'string' && LOWER_HEX.test(value);
34
+ }
35
+ /**
36
+ * The stored form of one record, or `undefined` for anything this module never writes: a `leafIndex` that is not a
37
+ * non-negative safe integer, an `account` / `leafKey` / `nodeTag` / digest that is not lowercase hex, an `epoch` that
38
+ * is not a decimal string, or fewer than two `commitDigests` (SC-6: an equivocation is two or more commits).
39
+ */
40
+ function decode(raw) {
41
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw) || raw instanceof Uint8Array)
42
+ return undefined;
43
+ const r = raw;
44
+ const leafIndex = r['leafIndex'];
45
+ if (typeof leafIndex !== 'number' || !Number.isSafeInteger(leafIndex) || leafIndex < 0)
46
+ return undefined;
47
+ const { account, leafKey, nodeTag, epoch } = r;
48
+ if (!isLowerHex(account) || !isLowerHex(leafKey) || !isLowerHex(nodeTag))
49
+ return undefined;
50
+ if (typeof epoch !== 'string' || !/^\d+$/.test(epoch))
51
+ return undefined;
52
+ const digests = r['commitDigests'];
53
+ if (!Array.isArray(digests) || digests.length < 2 || !digests.every(isLowerHex))
54
+ return undefined;
55
+ return { leafIndex, account, leafKey, epoch, nodeTag, commitDigests: [...digests] };
56
+ }
57
+ /**
58
+ * Whether `value` is an engine report this module can record: an object whose `leafIndex` and `epoch` are
59
+ * non-negative safe integers, whose `account` / `leafKey` / `nodeTag` are lowercase hex, and whose `commitDigests`
60
+ * name two or more distinct lowercase-hex digests — exactly what {@link equivocationRecordOf} turns into a record the
61
+ * decoder reads back. Anything else (`undefined` from a result that carries no evidence, a partial object) would
62
+ * otherwise be merged and written as a record no reader ever returns, occupying its key for good.
63
+ */
64
+ export function isRecordableEquivocation(value) {
65
+ if (typeof value !== 'object' || value === null)
66
+ return false;
67
+ const v = value;
68
+ const { leafIndex, epoch, commitDigests } = v;
69
+ if (typeof leafIndex !== 'number' || !Number.isSafeInteger(leafIndex) || leafIndex < 0)
70
+ return false;
71
+ if (typeof epoch !== 'number' || !Number.isSafeInteger(epoch) || epoch < 0)
72
+ return false;
73
+ if (!isLowerHex(v['account']) || !isLowerHex(v['leafKey']) || !isLowerHex(v['nodeTag']))
74
+ return false;
75
+ return Array.isArray(commitDigests) && commitDigests.every(isLowerHex) && new Set(commitDigests).size >= 2;
76
+ }
77
+ /** Every well-formed record of the group, by key order. A malformed entry is skipped (it still occupies its key). */
78
+ export async function readEquivocations(view) {
79
+ const out = [];
80
+ for (const key of await view.keys()) {
81
+ const record = decode(await view.get(key));
82
+ if (record !== undefined)
83
+ out.push(record);
84
+ }
85
+ return out;
86
+ }
87
+ /**
88
+ * The application-visible form of every well-formed record of the group — what `MarmotGroup.equivocations()`
89
+ * returns: one notification per record, ordered by `(epoch, nodeTag, leafIndex)` (numeric epoch), frozen.
90
+ */
91
+ export async function readEquivocationNotifications(view) {
92
+ const records = await readEquivocations(view);
93
+ const ordered = records.map(equivocationNotification).sort((x, y) => x.epoch !== y.epoch ? (x.epoch < y.epoch ? -1 : 1) : x.nodeTag !== y.nodeTag ? (x.nodeTag < y.nodeTag ? -1 : 1) : x.leafIndex - y.leafIndex);
94
+ return Object.freeze(ordered.map((n) => Object.freeze(n)));
95
+ }
96
+ /**
97
+ * Writes `record` under its key unless that key is already present (whatever it holds): true iff this call wrote
98
+ * it. Called inside the batch's store transaction, so the check and the write are one atomic unit.
99
+ */
100
+ export async function writeEquivocation(view, record) {
101
+ const key = equivocationKey(record);
102
+ if ((await view.get(key)) !== undefined)
103
+ return false;
104
+ await view.put(key, {
105
+ leafIndex: record.leafIndex,
106
+ account: record.account,
107
+ leafKey: record.leafKey,
108
+ epoch: record.epoch,
109
+ nodeTag: record.nodeTag,
110
+ commitDigests: [...record.commitDigests],
111
+ });
112
+ return true;
113
+ }
@@ -0,0 +1,25 @@
1
+ import { MarmotError } from '../shared/index.js';
2
+ import type { KeyValueView } from '../storage/index.js';
3
+ /** Group extension namespace of the fence marker. */
4
+ export declare const FENCE_EXTENSION = "marmot.fence";
5
+ /**
6
+ * Whether `error` is ts-mls's "this device lost its own path secrets" failure — the engine's predicate, so the
7
+ * client fences on exactly what every engine replay path (direct apply, fork recovery, tree sweep) surfaces.
8
+ */
9
+ export declare function isFencingError(error: unknown): error is Error;
10
+ /** The first fencing error among `errors`, if any. */
11
+ export declare function fencingErrorIn(errors: readonly unknown[] | undefined): Error | undefined;
12
+ export declare function fencedError(groupId: string, operation: string, cause: unknown): MarmotError;
13
+ export interface FenceRecord {
14
+ readonly at: number;
15
+ readonly epoch: string;
16
+ readonly message: string;
17
+ }
18
+ export declare function writeFence(view: KeyValueView, record: FenceRecord): Promise<void>;
19
+ export declare function readFence(view: KeyValueView): Promise<FenceRecord | undefined>;
20
+ /**
21
+ * The cause a reloaded fence carries: the ts-mls `InternalError` object does
22
+ * not survive a reload, so this is a plain `Error` named `InternalError`
23
+ * with the recorded message (not an `instanceof InternalError`).
24
+ */
25
+ export declare function recordedFencingError(record: FenceRecord): Error;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Fencing (AC-HIST-4): a device whose `GroupStore` was restored from a
3
+ * snapshot taken before one of its own confirmed commits no longer holds the
4
+ * path secrets the group moved on with. Replaying that own commit (or any
5
+ * later commit whose UpdatePath is encrypted to the keys the lost commit
6
+ * installed) makes ts-mls throw `InternalError('No overlap between provided
7
+ * private keys and update path')` — or, for a sole member's own commit (an
8
+ * empty UpdatePath), `ValidationError('Could not find common ancestor')`,
9
+ * which the engine attributes to the own leaf where it knows the committer
10
+ * (`isLostPathSecretsError`). Sending from such a state would reuse ratchet
11
+ * secrets the device already spent. The group is fenced: `fenced`
12
+ * carrying that error as `cause`, then `Unrecoverable` — no further sends.
13
+ *
14
+ * The fence is durable (the group extension {@link FENCE_EXTENSION}): a
15
+ * reload of a fenced group stays fenced. After a reload the original error
16
+ * object is gone; the recorded one carries its message.
17
+ */
18
+ import { isLostPathSecretsError } from '@941design/marmot-engine/engine';
19
+ import { MarmotError } from '../shared/index.js';
20
+ /** Group extension namespace of the fence marker. */
21
+ export const FENCE_EXTENSION = 'marmot.fence';
22
+ const FENCE_KEY = 'current';
23
+ /**
24
+ * Whether `error` is ts-mls's "this device lost its own path secrets" failure — the engine's predicate, so the
25
+ * client fences on exactly what every engine replay path (direct apply, fork recovery, tree sweep) surfaces.
26
+ */
27
+ export function isFencingError(error) {
28
+ return isLostPathSecretsError(error);
29
+ }
30
+ /** The first fencing error among `errors`, if any. */
31
+ export function fencingErrorIn(errors) {
32
+ return errors?.find(isFencingError);
33
+ }
34
+ export function fencedError(groupId, operation, cause) {
35
+ return new MarmotError('fenced', `${operation}: group ${groupId} is fenced — its stored state predates one of this device's own confirmed commits; the group is Unrecoverable here (abandon it and re-join)`, {
36
+ cause,
37
+ details: { groupId },
38
+ });
39
+ }
40
+ export async function writeFence(view, record) {
41
+ await view.put(FENCE_KEY, { at: record.at, epoch: record.epoch, message: record.message });
42
+ }
43
+ export async function readFence(view) {
44
+ const raw = await view.get(FENCE_KEY);
45
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw) || raw instanceof Uint8Array)
46
+ return undefined;
47
+ const r = raw;
48
+ if (typeof r.at !== 'number' || typeof r.epoch !== 'string' || typeof r.message !== 'string')
49
+ return undefined;
50
+ return { at: r.at, epoch: r.epoch, message: r.message };
51
+ }
52
+ /**
53
+ * The cause a reloaded fence carries: the ts-mls `InternalError` object does
54
+ * not survive a reload, so this is a plain `Error` named `InternalError`
55
+ * with the recorded message (not an `instanceof InternalError`).
56
+ */
57
+ export function recordedFencingError(record) {
58
+ const error = new Error(record.message);
59
+ error.name = 'InternalError';
60
+ return error;
61
+ }
@@ -0,0 +1,3 @@
1
+ /** Lower-case hex codec for the digests and identities the history module keys by. */
2
+ export declare function hexOf(bytes: Uint8Array): string;
3
+ export declare function hexToBytes(hex: string): Uint8Array;
@@ -0,0 +1,10 @@
1
+ /** Lower-case hex codec for the digests and identities the history module keys by. */
2
+ export function hexOf(bytes) {
3
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
4
+ }
5
+ export function hexToBytes(hex) {
6
+ const out = new Uint8Array(hex.length / 2);
7
+ for (let i = 0; i < out.length; i++)
8
+ out[i] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);
9
+ return out;
10
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * `history-media` (S10), history half: the optional rumor history backend
3
+ * seam (AC-HIST-3), the notification stream's types and derivation
4
+ * (AC-HIST-2), the ordering key (AC-HIST-1), fencing (AC-HIST-4), and the
5
+ * persisted rewind window every engine is rebuilt with (the fork-recovery
6
+ * material behind AC-HIST-2 and the same-epoch fork fix), and the durable
7
+ * equivocation records behind `leaf-equivocation` (ADR-016).
8
+ */
9
+ import type { Rumor } from '@941design/nostr-events/event';
10
+ import type { OrderingKey } from './notifications.js';
11
+ /** One retained application message. */
12
+ export interface HistoryEntry {
13
+ readonly groupId: string;
14
+ /** The id of the kind-445 event that carried the rumor — not `rumor.id`. */
15
+ readonly eventId: string;
16
+ readonly rumor: Rumor;
17
+ readonly orderingKey: OrderingKey;
18
+ }
19
+ /**
20
+ * The rumor history backend seam (optional — `MarmotClientOptions.history`):
21
+ * where accepted application messages are retained for `group.history()`.
22
+ * Live delivery (`group.onNotification`) never depends on it. It is consumer
23
+ * code: every call runs through the client's re-entrancy guard, after the
24
+ * group's own state was persisted — never inside a store transaction.
25
+ *
26
+ * Delivery is AT-LEAST-ONCE: each `append` / `withdraw` is recorded durably
27
+ * with the transition that produced it and handed over in order until the
28
+ * call succeeds — so after a crash (or a call that failed after the backend
29
+ * already applied it) the same call can come again. Both MUST be idempotent
30
+ * by `eventId`: appending a retained entry again is a no-op, withdrawing an
31
+ * absent one too. A call that fails — or does not settle within 10 s
32
+ * (`HISTORY_BACKEND_TIMEOUT_MS`) — counts as a failed attempt; after 5 in a
33
+ * row (`MAX_HISTORY_ATTEMPTS`) that update is given up (missing from
34
+ * `history()`) so one poisoned entry never blocks the ones after it. No
35
+ * event reports it.
36
+ *
37
+ * ORDERING (per client instance): at most one `append` / `withdraw` /
38
+ * `purge` of a group is outstanding at a time from one client. A call that
39
+ * timed out is still waited for — the next one is issued only once it
40
+ * actually settled — so a late call never lands after, and undoes, a
41
+ * withdrawal or the teardown purge meant to follow it. A backend shared by
42
+ * several client instances (tabs, devices of one store) gets no such
43
+ * guarantee across them and must serialize per `groupId` itself.
44
+ *
45
+ * Updates are fed by a per-group worker outside the group's operation queue:
46
+ * a slow or hanging backend never holds up `send` or `ingest`.
47
+ * `group.history()` first waits for that worker, so it reads its own
48
+ * committed updates — except one still outstanding, failed or timed out,
49
+ * which stays queued. Teardown stops the worker, waits (up to the timeout)
50
+ * for its last call to settle, then calls `purge` with the same bound; a
51
+ * call or purge that does not settle in time fails that teardown step, which
52
+ * is retried — before the group's store is cleared — so a stuck backend
53
+ * delays a teardown until it answers.
54
+ */
55
+ export interface HistoryBackend {
56
+ /** Retains one accepted application message (in delivery order; at least once — idempotent by `eventId`). */
57
+ append(entry: HistoryEntry): void | Promise<void>;
58
+ /** A rewind abandoned the branch these messages were delivered on: they leave the history (at least once — idempotent by `eventId`). */
59
+ withdraw(groupId: string, eventIds: readonly string[]): void | Promise<void>;
60
+ /** The retained messages of `groupId`, in delivery order. */
61
+ list(groupId: string): readonly HistoryEntry[] | Promise<readonly HistoryEntry[]>;
62
+ /** Deletes everything retained for `groupId` (teardown: `leave`, `abandon`, `destroy`). */
63
+ purge(groupId: string): void | Promise<void>;
64
+ }
65
+ /** A `HistoryBackend` over process memory (tests, ephemeral clients). */
66
+ export declare function createMemoryHistoryBackend(): HistoryBackend;
67
+ export { commitNotifications, windowTransition, leafTransition, removedLeaves, rotatedLeaves, retiredKeyReadds, successionsInWindow, abandonedSuccessionsInWindow, type AppliedNotification, type LeafKeyRotatedNotification, type LeafKeyRotationWithdrawnNotification, type LeafTransitionOptions, type RetiredKeyReaddedNotification, type RotatedLeaf, type WindowSuccession, type GroupDisbandedNotification, type GroupNotification, type LeafEquivocationNotification, type LeafRemovalWithdrawnNotification, type LeafRemovedNotification, type MessageNotification, type MessageWithdrawnNotification, type OrderingKey, type WindowTransition, type WithdrawnNotification, } from './notifications.js';
68
+ export { orderingKeyOf, senderGeneration, messageEpoch } from './ordering-key.js';
69
+ export { EQUIVOCATION_EXTENSION, equivocationKey, equivocationNotification, equivocationRecordOf, isRecordableEquivocation, readEquivocations, readEquivocationNotifications, writeEquivocation, type EquivocationRecord, } from './equivocation.js';
70
+ export { adminsOf, commitViewOf, holdsLeafKey, sameBytes, diffCommitViews, ownCommitChanges, OWN_CHANGE_LOST_REASONS, type CommitView, type OwnChange, type OwnChangeLostNotification, type OwnChangeLostReason, type OwnChangeReappliedNotification, type OwnChangeWithdrawnNotification, type OwnCommitChange, } from './own-change.js';
71
+ export { breakdownWithdrawnCommit, forkPointNode, intersectDeclared, winnerHeldLeaf, winnerRemovedAccount, type BreakdownUnreadable, type DeclaredChanges, type ForkedChange, type WithdrawalBreakdown, } from './own-change-fork.js';
72
+ export { FENCE_EXTENSION, fencedError, fencingErrorIn, isFencingError, readFence, recordedFencingError, writeFence, type FenceRecord } from './fencing.js';
73
+ export { canonicalPath, captureWindow, commitOf, extendWindow, heldBranchScore, withForkNode, linkRestorable, readWindow, restoreHistory, restrictWindow, rewoundToParent, REWIND_HORIZON, sameNode, sameWindow, senderOfNode, senderOfStored, tagOf, tipOnlyWindow, windowFor, wireOf, writeWindow, type HeldBranchScore, type JoinEvidence, type RestoredHistory, type RetainedWindow, type WindowNode, } from './retained-window.js';
@@ -0,0 +1,31 @@
1
+ /** A `HistoryBackend` over process memory (tests, ephemeral clients). */
2
+ export function createMemoryHistoryBackend() {
3
+ const byGroup = new Map();
4
+ return {
5
+ append(entry) {
6
+ const list = byGroup.get(entry.groupId) ?? [];
7
+ if (!list.some((e) => e.eventId === entry.eventId))
8
+ list.push(Object.freeze({ ...entry }));
9
+ byGroup.set(entry.groupId, list);
10
+ },
11
+ withdraw(groupId, eventIds) {
12
+ const drop = new Set(eventIds);
13
+ const list = byGroup.get(groupId);
14
+ if (list !== undefined)
15
+ byGroup.set(groupId, list.filter((e) => !drop.has(e.eventId)));
16
+ },
17
+ list(groupId) {
18
+ return Object.freeze([...(byGroup.get(groupId) ?? [])]);
19
+ },
20
+ purge(groupId) {
21
+ byGroup.delete(groupId);
22
+ },
23
+ };
24
+ }
25
+ export { commitNotifications, windowTransition, leafTransition, removedLeaves, rotatedLeaves, retiredKeyReadds, successionsInWindow, abandonedSuccessionsInWindow, } from './notifications.js';
26
+ export { orderingKeyOf, senderGeneration, messageEpoch } from './ordering-key.js';
27
+ export { EQUIVOCATION_EXTENSION, equivocationKey, equivocationNotification, equivocationRecordOf, isRecordableEquivocation, readEquivocations, readEquivocationNotifications, writeEquivocation, } from './equivocation.js';
28
+ export { adminsOf, commitViewOf, holdsLeafKey, sameBytes, diffCommitViews, ownCommitChanges, OWN_CHANGE_LOST_REASONS, } from './own-change.js';
29
+ export { breakdownWithdrawnCommit, forkPointNode, intersectDeclared, winnerHeldLeaf, winnerRemovedAccount, } from './own-change-fork.js';
30
+ export { FENCE_EXTENSION, fencedError, fencingErrorIn, isFencingError, readFence, recordedFencingError, writeFence } from './fencing.js';
31
+ export { canonicalPath, captureWindow, commitOf, extendWindow, heldBranchScore, withForkNode, linkRestorable, readWindow, restoreHistory, restrictWindow, rewoundToParent, REWIND_HORIZON, sameNode, sameWindow, senderOfNode, senderOfStored, tagOf, tipOnlyWindow, windowFor, wireOf, writeWindow, } from './retained-window.js';