@941design/marmot 0.0.0-stage → 0.2.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/CHANGELOG.md +739 -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 +190 -0
  25. package/dist/account/teardown.js +878 -0
  26. package/dist/client/admission-cleanup.d.ts +197 -0
  27. package/dist/client/admission-cleanup.js +635 -0
  28. package/dist/client/adoption-proof.d.ts +39 -0
  29. package/dist/client/adoption-proof.js +102 -0
  30. package/dist/client/before-create-group.d.ts +18 -0
  31. package/dist/client/before-create-group.js +65 -0
  32. package/dist/client/before-publish-hooks.d.ts +121 -0
  33. package/dist/client/before-publish-hooks.js +182 -0
  34. package/dist/client/client-config.d.ts +42 -0
  35. package/dist/client/client-config.js +13 -0
  36. package/dist/client/commit-redrive.d.ts +92 -0
  37. package/dist/client/commit-redrive.js +274 -0
  38. package/dist/client/component-update.d.ts +43 -0
  39. package/dist/client/component-update.js +53 -0
  40. package/dist/client/confirm-hooks.d.ts +55 -0
  41. package/dist/client/confirm-hooks.js +74 -0
  42. package/dist/client/create-client.d.ts +1126 -0
  43. package/dist/client/create-client.js +1232 -0
  44. package/dist/client/group-availability.d.ts +182 -0
  45. package/dist/client/group-availability.js +301 -0
  46. package/dist/client/group-disband.d.ts +28 -0
  47. package/dist/client/group-disband.js +64 -0
  48. package/dist/client/group-history.d.ts +461 -0
  49. package/dist/client/group-history.js +1365 -0
  50. package/dist/client/group-profile.d.ts +31 -0
  51. package/dist/client/group-profile.js +62 -0
  52. package/dist/client/group-records.d.ts +522 -0
  53. package/dist/client/group-records.js +1117 -0
  54. package/dist/client/group-removal.d.ts +36 -0
  55. package/dist/client/group-removal.js +127 -0
  56. package/dist/client/group-remove-member.d.ts +49 -0
  57. package/dist/client/group-remove-member.js +163 -0
  58. package/dist/client/group-runtime.d.ts +415 -0
  59. package/dist/client/group-runtime.js +2811 -0
  60. package/dist/client/group-snapshot.d.ts +104 -0
  61. package/dist/client/group-snapshot.js +474 -0
  62. package/dist/client/history-pages.d.ts +107 -0
  63. package/dist/client/history-pages.js +194 -0
  64. package/dist/client/inbox-send.d.ts +19 -0
  65. package/dist/client/inbox-send.js +71 -0
  66. package/dist/client/index.d.ts +24 -0
  67. package/dist/client/index.js +13 -0
  68. package/dist/client/ingest.d.ts +82 -0
  69. package/dist/client/ingest.js +1584 -0
  70. package/dist/client/invitation-outcomes.d.ts +50 -0
  71. package/dist/client/invitation-outcomes.js +135 -0
  72. package/dist/client/lifecycle-events.d.ts +63 -0
  73. package/dist/client/lifecycle-events.js +35 -0
  74. package/dist/client/opaque-candidates.d.ts +82 -0
  75. package/dist/client/opaque-candidates.js +170 -0
  76. package/dist/client/own-change-outbox.d.ts +66 -0
  77. package/dist/client/own-change-outbox.js +158 -0
  78. package/dist/client/pending-leaf.d.ts +116 -0
  79. package/dist/client/pending-leaf.js +378 -0
  80. package/dist/client/permissions.d.ts +9 -0
  81. package/dist/client/permissions.js +12 -0
  82. package/dist/client/pipeline.d.ts +583 -0
  83. package/dist/client/pipeline.js +3666 -0
  84. package/dist/client/reentrancy-guard.d.ts +102 -0
  85. package/dist/client/reentrancy-guard.js +159 -0
  86. package/dist/client/rekey.d.ts +58 -0
  87. package/dist/client/rekey.js +149 -0
  88. package/dist/client/transport-policy.d.ts +181 -0
  89. package/dist/client/transport-policy.js +214 -0
  90. package/dist/history/admission-lineage.d.ts +186 -0
  91. package/dist/history/admission-lineage.js +589 -0
  92. package/dist/history/equivocation.d.ts +55 -0
  93. package/dist/history/equivocation.js +113 -0
  94. package/dist/history/fencing.d.ts +66 -0
  95. package/dist/history/fencing.js +121 -0
  96. package/dist/history/hex.d.ts +3 -0
  97. package/dist/history/hex.js +10 -0
  98. package/dist/history/index.d.ts +74 -0
  99. package/dist/history/index.js +32 -0
  100. package/dist/history/notifications.d.ts +270 -0
  101. package/dist/history/notifications.js +264 -0
  102. package/dist/history/ordering-key.d.ts +24 -0
  103. package/dist/history/ordering-key.js +101 -0
  104. package/dist/history/own-change-fork.d.ts +112 -0
  105. package/dist/history/own-change-fork.js +196 -0
  106. package/dist/history/own-change.d.ts +118 -0
  107. package/dist/history/own-change.js +146 -0
  108. package/dist/history/policy.d.ts +48 -0
  109. package/dist/history/policy.js +52 -0
  110. package/dist/history/retained-window.d.ts +215 -0
  111. package/dist/history/retained-window.js +565 -0
  112. package/dist/inbox/demux.d.ts +90 -0
  113. package/dist/inbox/demux.js +78 -0
  114. package/dist/inbox/handler-registry.d.ts +42 -0
  115. package/dist/inbox/handler-registry.js +37 -0
  116. package/dist/inbox/index.d.ts +11 -0
  117. package/dist/inbox/index.js +10 -0
  118. package/dist/inbox/seen-set.d.ts +82 -0
  119. package/dist/inbox/seen-set.js +202 -0
  120. package/dist/inbox/subscription.d.ts +236 -0
  121. package/dist/inbox/subscription.js +644 -0
  122. package/dist/index.d.ts +10 -0
  123. package/dist/index.js +9 -0
  124. package/dist/invitations/competing-welcome.d.ts +223 -0
  125. package/dist/invitations/competing-welcome.js +128 -0
  126. package/dist/invitations/decline.d.ts +67 -0
  127. package/dist/invitations/decline.js +149 -0
  128. package/dist/invitations/delivery-evidence.d.ts +288 -0
  129. package/dist/invitations/delivery-evidence.js +766 -0
  130. package/dist/invitations/expect-welcome.d.ts +66 -0
  131. package/dist/invitations/expect-welcome.js +138 -0
  132. package/dist/invitations/index.d.ts +18 -0
  133. package/dist/invitations/index.js +18 -0
  134. package/dist/invitations/invitation-outcome.d.ts +110 -0
  135. package/dist/invitations/invitation-outcome.js +210 -0
  136. package/dist/invitations/invite.d.ts +358 -0
  137. package/dist/invitations/invite.js +1102 -0
  138. package/dist/invitations/offers.d.ts +79 -0
  139. package/dist/invitations/offers.js +115 -0
  140. package/dist/invitations/on-proposal.d.ts +47 -0
  141. package/dist/invitations/on-proposal.js +40 -0
  142. package/dist/invitations/pending-proposal-policy.d.ts +52 -0
  143. package/dist/invitations/pending-proposal-policy.js +139 -0
  144. package/dist/invitations/proposal-deadline.d.ts +133 -0
  145. package/dist/invitations/proposal-deadline.js +164 -0
  146. package/dist/invitations/relay-planes.d.ts +43 -0
  147. package/dist/invitations/relay-planes.js +70 -0
  148. package/dist/invitations/welcome-processor.d.ts +272 -0
  149. package/dist/invitations/welcome-processor.js +1241 -0
  150. package/dist/key-packages/device-key.d.ts +131 -0
  151. package/dist/key-packages/device-key.js +272 -0
  152. package/dist/key-packages/device-rotation-records.d.ts +83 -0
  153. package/dist/key-packages/device-rotation-records.js +173 -0
  154. package/dist/key-packages/group-refs.d.ts +40 -0
  155. package/dist/key-packages/group-refs.js +79 -0
  156. package/dist/key-packages/index.d.ts +18 -0
  157. package/dist/key-packages/index.js +18 -0
  158. package/dist/key-packages/key-package-ref.d.ts +16 -0
  159. package/dist/key-packages/key-package-ref.js +21 -0
  160. package/dist/key-packages/observation-stream.d.ts +4 -0
  161. package/dist/key-packages/observation-stream.js +120 -0
  162. package/dist/key-packages/offer-rumor.d.ts +26 -0
  163. package/dist/key-packages/offer-rumor.js +69 -0
  164. package/dist/key-packages/publisher.d.ts +174 -0
  165. package/dist/key-packages/publisher.js +1247 -0
  166. package/dist/key-packages/select-key-package.d.ts +24 -0
  167. package/dist/key-packages/select-key-package.js +90 -0
  168. package/dist/key-packages/slot-manager.d.ts +167 -0
  169. package/dist/key-packages/slot-manager.js +327 -0
  170. package/dist/key-packages/validate-key-package-event.d.ts +3 -0
  171. package/dist/key-packages/validate-key-package-event.js +49 -0
  172. package/dist/media/cache.d.ts +14 -0
  173. package/dist/media/cache.js +10 -0
  174. package/dist/media/index.d.ts +52 -0
  175. package/dist/media/index.js +71 -0
  176. package/dist/mls.d.ts +15 -0
  177. package/dist/mls.js +15 -0
  178. package/dist/shared/account-pubkey.d.ts +4 -0
  179. package/dist/shared/account-pubkey.js +10 -0
  180. package/dist/shared/errors.d.ts +28 -0
  181. package/dist/shared/errors.js +96 -0
  182. package/dist/shared/hex.d.ts +4 -0
  183. package/dist/shared/hex.js +13 -0
  184. package/dist/shared/index.d.ts +14 -0
  185. package/dist/shared/index.js +14 -0
  186. package/dist/shared/kinds.d.ts +8 -0
  187. package/dist/shared/kinds.js +28 -0
  188. package/dist/shared/publish-classification.d.ts +26 -0
  189. package/dist/shared/publish-classification.js +31 -0
  190. package/dist/storage/envelope.d.ts +39 -0
  191. package/dist/storage/envelope.js +201 -0
  192. package/dist/storage/index.d.ts +237 -0
  193. package/dist/storage/index.js +491 -0
  194. package/dist/storage/indexeddb/idb-types.d.ts +68 -0
  195. package/dist/storage/indexeddb/idb-types.js +1 -0
  196. package/dist/storage/indexeddb/index.d.ts +17 -0
  197. package/dist/storage/indexeddb/index.js +141 -0
  198. package/dist/storage/lease.d.ts +54 -0
  199. package/dist/storage/lease.js +168 -0
  200. package/dist/storage/memory/deterministic-signer.d.ts +27 -0
  201. package/dist/storage/memory/deterministic-signer.js +65 -0
  202. package/dist/storage/memory/index.d.ts +32 -0
  203. package/dist/storage/memory/index.js +87 -0
  204. package/dist/storage/memory/lock-manager.d.ts +8 -0
  205. package/dist/storage/memory/lock-manager.js +71 -0
  206. package/package.json +66 -3
@@ -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,66 @@
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
+ /**
14
+ * The coarse cause of a fence (epic marmot-invitation-outcomes, SC-10): `lost-path-secrets` for the AC-HIST-4 replay
15
+ * failure, `invalid-stored-evidence` for stored evidence that cannot be trusted (a malformed present marker, a corrupt
16
+ * held-candidate record), `unknown` for a legacy marker written before the cause was recorded.
17
+ */
18
+ export type FenceCause = 'lost-path-secrets' | 'invalid-stored-evidence' | 'unknown';
19
+ export interface FenceRecord {
20
+ readonly at: number;
21
+ readonly epoch: string;
22
+ readonly message: string;
23
+ /** Additive (v:1): absent on a marker written before causes were recorded — it reads `unknown`. */
24
+ readonly cause?: FenceCause;
25
+ }
26
+ /**
27
+ * Stored fence evidence that cannot be trusted: a present but malformed fence marker, or a held-candidate record the
28
+ * engine refuses (client/opaque-candidates.ts `OpaqueRecordCorrupt` extends it). The group fails closed: it is
29
+ * fenced with cause `invalid-stored-evidence`.
30
+ */
31
+ export declare class InvalidStoredEvidenceError extends Error {
32
+ readonly name: string;
33
+ }
34
+ export declare function writeFence(view: KeyValueView, record: FenceRecord): Promise<void>;
35
+ /** What {@link loadFenceMarker} found under the marker key. */
36
+ export type FenceMarker = {
37
+ readonly kind: 'absent';
38
+ } | {
39
+ readonly kind: 'valid';
40
+ readonly record: FenceRecord;
41
+ } | {
42
+ readonly kind: 'malformed';
43
+ };
44
+ /**
45
+ * The fence marker as a load must judge it (fail closed): `absent` when no marker is stored, `valid` for a
46
+ * well-formed one (its `cause` kept when it is a known cause), `malformed` for anything else that is present —
47
+ * including a stored payload that does not decode. A malformed marker is never read as no fence. Any other read failure (an incompatible store, a failing backend) is thrown.
48
+ */
49
+ export declare function loadFenceMarker(view: KeyValueView): Promise<FenceMarker>;
50
+ /**
51
+ * Compatibility/test reader: the legacy fields (`at`, `epoch`, `message` — no `cause`) of a {@link loadFenceMarker |
52
+ * valid} marker, else `undefined`. `undefined` does not mean "no marker": a malformed one also reads `undefined` here,
53
+ * while a load fails closed on it. Code that decides whether a group is fenced uses {@link loadFenceMarker}.
54
+ */
55
+ export declare function readFence(view: KeyValueView): Promise<FenceRecord | undefined>;
56
+ /**
57
+ * The cause a reloaded fence carries: the ts-mls `InternalError` object does
58
+ * not survive a reload, so this is a plain `Error` named `InternalError`
59
+ * with the recorded message (not an `instanceof InternalError`).
60
+ */
61
+ export declare function recordedFencingError(record: FenceRecord): Error;
62
+ /**
63
+ * The coarse cause of the fence `error` stands for: a reloaded marker's recorded cause, `invalid-stored-evidence` for
64
+ * {@link InvalidStoredEvidenceError}, `lost-path-secrets` for the ts-mls replay failure, else `unknown`.
65
+ */
66
+ export declare function fenceCauseOf(error: unknown): FenceCause;
@@ -0,0 +1,121 @@
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 { isMarmotError, 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
+ const FENCE_CAUSES = ['lost-path-secrets', 'invalid-stored-evidence', 'unknown'];
41
+ /**
42
+ * Stored fence evidence that cannot be trusted: a present but malformed fence marker, or a held-candidate record the
43
+ * engine refuses (client/opaque-candidates.ts `OpaqueRecordCorrupt` extends it). The group fails closed: it is
44
+ * fenced with cause `invalid-stored-evidence`.
45
+ */
46
+ export class InvalidStoredEvidenceError extends Error {
47
+ name = 'InvalidStoredEvidenceError';
48
+ }
49
+ export async function writeFence(view, record) {
50
+ await view.put(FENCE_KEY, { at: record.at, epoch: record.epoch, message: record.message, ...(record.cause === undefined ? {} : { cause: record.cause }) });
51
+ }
52
+ /**
53
+ * The fence marker as a load must judge it (fail closed): `absent` when no marker is stored, `valid` for a
54
+ * well-formed one (its `cause` kept when it is a known cause), `malformed` for anything else that is present —
55
+ * including a stored payload that does not decode. A malformed marker is never read as no fence. Any other read failure (an incompatible store, a failing backend) is thrown.
56
+ */
57
+ export async function loadFenceMarker(view) {
58
+ let raw;
59
+ try {
60
+ raw = await view.get(FENCE_KEY);
61
+ }
62
+ catch (error) {
63
+ if (isMarmotError(error, 'envelope-mismatch') && error.details?.reason === 'malformed')
64
+ return { kind: 'malformed' };
65
+ throw error;
66
+ }
67
+ if (raw === undefined)
68
+ return { kind: 'absent' };
69
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw) || raw instanceof Uint8Array)
70
+ return { kind: 'malformed' };
71
+ const r = raw;
72
+ if (typeof r.at !== 'number' || typeof r.epoch !== 'string' || typeof r.message !== 'string')
73
+ return { kind: 'malformed' };
74
+ if (r.cause !== undefined && !FENCE_CAUSES.includes(r.cause))
75
+ return { kind: 'malformed' };
76
+ const cause = r.cause;
77
+ return { kind: 'valid', record: { at: r.at, epoch: r.epoch, message: r.message, ...(cause === undefined ? {} : { cause }) } };
78
+ }
79
+ /**
80
+ * Compatibility/test reader: the legacy fields (`at`, `epoch`, `message` — no `cause`) of a {@link loadFenceMarker |
81
+ * valid} marker, else `undefined`. `undefined` does not mean "no marker": a malformed one also reads `undefined` here,
82
+ * while a load fails closed on it. Code that decides whether a group is fenced uses {@link loadFenceMarker}.
83
+ */
84
+ export async function readFence(view) {
85
+ const marker = await loadFenceMarker(view);
86
+ if (marker.kind !== 'valid')
87
+ return undefined;
88
+ const { at, epoch, message } = marker.record;
89
+ return { at, epoch, message };
90
+ }
91
+ /**
92
+ * The cause a reloaded fence carries: the ts-mls `InternalError` object does
93
+ * not survive a reload, so this is a plain `Error` named `InternalError`
94
+ * with the recorded message (not an `instanceof InternalError`).
95
+ */
96
+ export function recordedFencingError(record) {
97
+ const error = new RecordedFencingError(record.message, record.cause ?? 'unknown');
98
+ error.name = 'InternalError';
99
+ return error;
100
+ }
101
+ /** A reloaded fence's cause object: carries the marker's recorded {@link FenceCause} (`unknown` for a legacy marker). */
102
+ class RecordedFencingError extends Error {
103
+ fenceCause;
104
+ constructor(message, fenceCause) {
105
+ super(message);
106
+ this.fenceCause = fenceCause;
107
+ }
108
+ }
109
+ /**
110
+ * The coarse cause of the fence `error` stands for: a reloaded marker's recorded cause, `invalid-stored-evidence` for
111
+ * {@link InvalidStoredEvidenceError}, `lost-path-secrets` for the ts-mls replay failure, else `unknown`.
112
+ */
113
+ export function fenceCauseOf(error) {
114
+ if (error instanceof RecordedFencingError)
115
+ return error.fenceCause;
116
+ if (error instanceof InvalidStoredEvidenceError)
117
+ return 'invalid-stored-evidence';
118
+ if (isFencingError(error))
119
+ return 'lost-path-secrets';
120
+ return 'unknown';
121
+ }
@@ -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,74 @@
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 { ADMISSION_LINEAGE_EXTENSION, admissionStep, advanceLineage, advanceLineageRecords, decodeLineageRecord, deriveAdmission, encodeLineageRecord, leafKeyAt, lineageKey, mergeSeed, mergeWindows, readLineageRecord, readLineageRecords, replaceLineageRecords, seedLineage, seedLineageRecords, stateResolver, validateRestoredLineage, windowRootOf, writeLineageRecord, type AdmissionDerivation, type AdmissionLineageRecord, type LineageAnchor, type LineageCheckpoint, type LineageEndedBy, type LineageGapReason, type LineageLink, type LineageOccupancy, type LineageProvenance, type StateResolver, } from './admission-lineage.js';
73
+ export { FENCE_EXTENSION, fenceCauseOf, fencedError, fencingErrorIn, InvalidStoredEvidenceError, isFencingError, loadFenceMarker, readFence, recordedFencingError, writeFence, type FenceCause, type FenceMarker, type FenceRecord } from './fencing.js';
74
+ 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,32 @@
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 { ADMISSION_LINEAGE_EXTENSION, admissionStep, advanceLineage, advanceLineageRecords, decodeLineageRecord, deriveAdmission, encodeLineageRecord, leafKeyAt, lineageKey, mergeSeed, mergeWindows, readLineageRecord, readLineageRecords, replaceLineageRecords, seedLineage, seedLineageRecords, stateResolver, validateRestoredLineage, windowRootOf, writeLineageRecord, } from './admission-lineage.js';
31
+ export { FENCE_EXTENSION, fenceCauseOf, fencedError, fencingErrorIn, InvalidStoredEvidenceError, isFencingError, loadFenceMarker, readFence, recordedFencingError, writeFence } from './fencing.js';
32
+ 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';