@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,39 @@
1
+ /**
2
+ * Group adoption proofs (epic marmot-invitation-outcomes S2; ADR-019 D6).
3
+ *
4
+ * Two group extensions record which invitation's Welcome put the group's state into this store:
5
+ *
6
+ * - `marmot.adoption` ({@link ADOPTION_PROOF_EXTENSION}): `invitationId` → `{ v: 1, via: 'join', tag, at }`, written
7
+ * in the SAME group transaction as the adopted state (`group-runtime.ts` `adoptJoinedGroupOp`). Adoption happens
8
+ * when that transaction commits and the adopting call does not retract it (its compensating clear);
9
+ * - `marmot.branchSwitch` ({@link SWITCH_PROOF_EXTENSION}): `invitationId` → `{ to }`, written in a competing
10
+ * Welcome's switch transaction (`rebaseOnQueue`).
11
+ *
12
+ * Only teardown (after stamping), the adoption's compensating clear and an account wipe remove them (the
13
+ * proof-retraction rule, enumerated by the S2 oracle's `RETRACTORS` test).
14
+ */
15
+ import { type AdoptionProof, type AdoptionProofs } from '../invitations/index.js';
16
+ import type { KeyValueView } from '../storage/index.js';
17
+ /** The group extension of join adoption proofs. */
18
+ export declare const ADOPTION_PROOF_EXTENSION = "marmot.adoption";
19
+ /** The group extension holding one row per invitation whose switch transaction committed: the durable proof it was written. */
20
+ export declare const SWITCH_PROOF_EXTENSION = "marmot.branchSwitch";
21
+ /** Anything with group extensions: a `GroupStore` or one of its transactions. */
22
+ export interface ExtensionScope {
23
+ extension(id: string): KeyValueView;
24
+ }
25
+ /** Writes invitation `invitationId`'s join adoption proof (inside the adoption's group transaction). */
26
+ export declare function writeAdoptionProof(scope: ExtensionScope, invitationId: string, proof: AdoptionProof): Promise<void>;
27
+ /**
28
+ * Invitation `invitationId`'s join adoption proof in the group, or `undefined`: none, or a malformed row — no evidence
29
+ * (the welcome processor's completion stamps only what a decodable proof names; the outcome reader rejects the row).
30
+ */
31
+ export declare function readAdoptionProofOf(scope: ExtensionScope, invitationId: string): Promise<AdoptionProof | undefined>;
32
+ /**
33
+ * Both proof maps of the group. A malformed row — its payload, or for either extension its envelope — rejects
34
+ * `store-failed` (`details.malformed`): the outcome reader never reads it as absent. `skipMalformed` (teardown's read before the clear): a malformed row is no evidence
35
+ * and is skipped, so it can never block the purge that deletes it.
36
+ */
37
+ export declare function readAdoptionProofs(scope: ExtensionScope, options?: {
38
+ readonly skipMalformed?: boolean;
39
+ }): Promise<AdoptionProofs>;
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Group adoption proofs (epic marmot-invitation-outcomes S2; ADR-019 D6).
3
+ *
4
+ * Two group extensions record which invitation's Welcome put the group's state into this store:
5
+ *
6
+ * - `marmot.adoption` ({@link ADOPTION_PROOF_EXTENSION}): `invitationId` → `{ v: 1, via: 'join', tag, at }`, written
7
+ * in the SAME group transaction as the adopted state (`group-runtime.ts` `adoptJoinedGroupOp`). Adoption happens
8
+ * when that transaction commits and the adopting call does not retract it (its compensating clear);
9
+ * - `marmot.branchSwitch` ({@link SWITCH_PROOF_EXTENSION}): `invitationId` → `{ to }`, written in a competing
10
+ * Welcome's switch transaction (`rebaseOnQueue`).
11
+ *
12
+ * Only teardown (after stamping), the adoption's compensating clear and an account wipe remove them (the
13
+ * proof-retraction rule, enumerated by the S2 oracle's `RETRACTORS` test).
14
+ */
15
+ import { isMalformedRowError } from '../invitations/index.js';
16
+ import { MarmotError } from '../shared/index.js';
17
+ /** The group extension of join adoption proofs. */
18
+ export const ADOPTION_PROOF_EXTENSION = 'marmot.adoption';
19
+ /** The group extension holding one row per invitation whose switch transaction committed: the durable proof it was written. */
20
+ export const SWITCH_PROOF_EXTENSION = 'marmot.branchSwitch';
21
+ function malformedProof(id, extension = ADOPTION_PROOF_EXTENSION, cause) {
22
+ return new MarmotError('store-failed', `${extension}/${id}: malformed adoption proof`, { details: { id, malformed: true }, ...(cause === undefined ? {} : { cause }) });
23
+ }
24
+ const MALFORMED = Symbol('malformed');
25
+ /**
26
+ * One proof row read raw: `undefined` when absent; `MALFORMED` when its envelope does not open (skipped when
27
+ * `skipMalformed`, else rejected `store-failed` `details.malformed` like a payload that does not decode). Every other
28
+ * error (the backend, the lease, a row of another build) propagates.
29
+ */
30
+ async function readProofRow(view, extension, key, skipMalformed) {
31
+ try {
32
+ return await view.get(key);
33
+ }
34
+ catch (error) {
35
+ if (!isMalformedRowError(error))
36
+ throw error;
37
+ if (skipMalformed)
38
+ return MALFORMED;
39
+ throw malformedProof(key, extension, error);
40
+ }
41
+ }
42
+ function decodeAdoptionProof(id, raw) {
43
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
44
+ throw malformedProof(id);
45
+ const r = raw;
46
+ if (r.v !== 1 || r.via !== 'join' || typeof r.tag !== 'string' || typeof r.at !== 'number')
47
+ throw malformedProof(id);
48
+ return { via: 'join', tag: r.tag, at: r.at };
49
+ }
50
+ /** Writes invitation `invitationId`'s join adoption proof (inside the adoption's group transaction). */
51
+ export async function writeAdoptionProof(scope, invitationId, proof) {
52
+ await scope.extension(ADOPTION_PROOF_EXTENSION).put(invitationId, { v: 1, via: proof.via, tag: proof.tag, at: proof.at });
53
+ }
54
+ /**
55
+ * Invitation `invitationId`'s join adoption proof in the group, or `undefined`: none, or a malformed row — no evidence
56
+ * (the welcome processor's completion stamps only what a decodable proof names; the outcome reader rejects the row).
57
+ */
58
+ export async function readAdoptionProofOf(scope, invitationId) {
59
+ // A row whose envelope (or payload) does not open is no evidence, as in the teardown scans: it must never strand a
60
+ // resumed join behind a throw.
61
+ const raw = await readProofRow(scope.extension(ADOPTION_PROOF_EXTENSION), ADOPTION_PROOF_EXTENSION, invitationId, true);
62
+ if (raw === undefined || raw === MALFORMED)
63
+ return undefined;
64
+ try {
65
+ return decodeAdoptionProof(invitationId, raw);
66
+ }
67
+ catch {
68
+ return undefined;
69
+ }
70
+ }
71
+ /**
72
+ * Both proof maps of the group. A malformed row — its payload, or for either extension its envelope — rejects
73
+ * `store-failed` (`details.malformed`): the outcome reader never reads it as absent. `skipMalformed` (teardown's read before the clear): a malformed row is no evidence
74
+ * and is skipped, so it can never block the purge that deletes it.
75
+ */
76
+ export async function readAdoptionProofs(scope, options = {}) {
77
+ const skipMalformed = options.skipMalformed === true;
78
+ const adoptionView = scope.extension(ADOPTION_PROOF_EXTENSION);
79
+ const adoption = new Map();
80
+ for (const key of await adoptionView.keys()) {
81
+ const raw = await readProofRow(adoptionView, ADOPTION_PROOF_EXTENSION, key, skipMalformed);
82
+ if (raw === undefined || raw === MALFORMED)
83
+ continue;
84
+ try {
85
+ adoption.set(key, decodeAdoptionProof(key, raw));
86
+ }
87
+ catch (error) {
88
+ if (!skipMalformed)
89
+ throw error;
90
+ }
91
+ }
92
+ const switchView = scope.extension(SWITCH_PROOF_EXTENSION);
93
+ const branchSwitch = new Set();
94
+ // A switch row's presence is the proof (its payload names the branch, `rebaseOnQueue`). A row whose envelope does
95
+ // not open is no evidence, as a malformed adoption row is.
96
+ for (const key of await switchView.keys()) {
97
+ const raw = await readProofRow(switchView, SWITCH_PROOF_EXTENSION, key, skipMalformed);
98
+ if (raw !== undefined && raw !== MALFORMED)
99
+ branchSwitch.add(key);
100
+ }
101
+ return { adoption, branchSwitch };
102
+ }
@@ -0,0 +1,18 @@
1
+ /** What a gate may resolve with: `{ once: true }` satisfies it for the rest of the client's life. */
2
+ export type CreateGroupGateResult = void | {
3
+ readonly once?: boolean;
4
+ };
5
+ /** A `beforeCreateGroup` gate: `groups.create()` waits until it resolves and aborts with its rejection. */
6
+ export type CreateGroupGate = () => Promise<CreateGroupGateResult> | CreateGroupGateResult;
7
+ export interface BeforeCreateGroupGates {
8
+ /** Registers `gate`; returns its unregister function (idempotent). */
9
+ register(gate: CreateGroupGate): () => void;
10
+ /** Resolves once every registered, not yet satisfied gate resolved (serialised); rejects with the first rejection. */
11
+ pass(): Promise<void>;
12
+ }
13
+ export interface BeforeCreateGroupDeps {
14
+ /** Invokes a gate through the client's re-entrancy guard. */
15
+ call(gate: CreateGroupGate): Promise<CreateGroupGateResult>;
16
+ isDisposed(): boolean;
17
+ }
18
+ export declare function createBeforeCreateGroupGates(deps: BeforeCreateGroupDeps): BeforeCreateGroupGates;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * `extensions.beforeCreateGroup(gate)` (S7, AC-INBOX-7): gates consulted by
3
+ * `groups.create()` before it does anything else — no signer call, no
4
+ * KeyPackage, no store write happens until every registered gate resolved.
5
+ *
6
+ * - A gate that rejects aborts that `create()` with the gate's own rejection
7
+ * (the same error value); nothing is created.
8
+ * - A gate that resolves with `{ once: true }` is satisfied for the rest of
9
+ * this client instance: it is never invoked again (a reload — a new
10
+ * client — asks it again). Any other resolution lets this one creation
11
+ * through and the next `create()` invokes it again.
12
+ * - Gate passes are serialised per client: concurrent `create()` calls wait
13
+ * for the gate invocation in flight instead of invoking it alongside it, so
14
+ * a `once: true` gate is invoked at most once even under concurrency, and a
15
+ * non-once gate once per creation. Several gates run in registration order.
16
+ * - Each invocation is a consumer surface (ADR-013, `beforeCreateGroup`):
17
+ * `groups.create()` from inside a gate is rejected `reentrant` — it would
18
+ * wait on the very gate pass that awaits it. Without an async-context
19
+ * carrier (browsers) only a synchronous re-entry is detectable; an
20
+ * awaited asynchronous one deadlocks this client's `groups.create()`
21
+ * (the residue ADR-013 Decision item 4 states).
22
+ *
23
+ * Per-instance state only (one registry per client, INV-NO-SINGLETONS).
24
+ */
25
+ import { MarmotError } from '../shared/index.js';
26
+ function reportsOnce(result) {
27
+ return typeof result === 'object' && result !== null && result.once === true;
28
+ }
29
+ export function createBeforeCreateGroupGates(deps) {
30
+ const entries = [];
31
+ let tail = Promise.resolve();
32
+ async function runGates() {
33
+ // The gates registered when this pass's turn comes (one registered meanwhile applies to it too).
34
+ for (const entry of [...entries]) {
35
+ if (entry.satisfied || !entries.includes(entry))
36
+ continue;
37
+ if (deps.isDisposed())
38
+ throw new MarmotError('disposed', 'groups.create: client has been disposed');
39
+ const result = await deps.call(entry.gate);
40
+ if (reportsOnce(result))
41
+ entry.satisfied = true;
42
+ }
43
+ }
44
+ return {
45
+ register(gate) {
46
+ if (typeof gate !== 'function')
47
+ throw new MarmotError('invalid-options', 'extensions.beforeCreateGroup: gate must be a function');
48
+ const entry = { gate, satisfied: false };
49
+ entries.push(entry);
50
+ return () => {
51
+ const i = entries.indexOf(entry);
52
+ if (i >= 0)
53
+ entries.splice(i, 1);
54
+ };
55
+ },
56
+ pass() {
57
+ // Every gate satisfied (or none registered): nothing to wait for.
58
+ if (entries.every((e) => e.satisfied))
59
+ return Promise.resolve();
60
+ const run = tail.then(runGates);
61
+ tail = run.catch(() => undefined);
62
+ return run;
63
+ },
64
+ };
65
+ }
@@ -0,0 +1,121 @@
1
+ import type { ClientState } from '@941design/marmot-engine/mls';
2
+ import { type RetainedWindow } from '../history/index.js';
3
+ import type { GroupStoreTx } from '../storage/index.js';
4
+ import { type GroupSnapshot } from './group-snapshot.js';
5
+ import type { ReentrancyGuard } from './reentrancy-guard.js';
6
+ /**
7
+ * Awaited by marmot after every `onBeforePublish` hook transaction committed and before the commit's first publish.
8
+ * Resolve when the backup is safe, reject when it could not be made; `signal` aborts when marmot stops waiting (the
9
+ * deadline passed, or the client ended) — a barrier must then stop work that could outlive its usefulness.
10
+ */
11
+ export type PublishBarrier = (signal: AbortSignal) => Promise<void>;
12
+ /** What an `onBeforePublish` hook receives. `tx` is the hook's OWN transaction on the group's store. */
13
+ export interface BeforePublishContext {
14
+ readonly groupId: string;
15
+ /** The intent's id (what `ConfirmContext.intentId` will be at its confirmation). */
16
+ readonly intentId: string;
17
+ readonly kind: 'commit' | 'self-update';
18
+ /** Epoch of the state the commit produces. */
19
+ readonly epoch: bigint;
20
+ readonly commit: {
21
+ /** The staged envelope's Nostr event id. Never a stable identity of the commit: a re-encrypted copy has another id. */
22
+ readonly eventId: string;
23
+ /** Hex SHA-256 of the commit's MLS wire bytes (`commitDigest`): the commit's identity, and what the pending marker binds. */
24
+ readonly digest: string;
25
+ /** Hex confirmation tag of the state the commit was built from. */
26
+ readonly parentTag: string;
27
+ /** Hex confirmation tag of the state the commit produces. */
28
+ readonly tag: string;
29
+ };
30
+ /**
31
+ * The hook's own transaction: its writes commit when the hook returns and roll back when it throws. Use it, never
32
+ * the store. The hook is unbounded in time and holds the group's queue: store writes only, no I/O (see the module
33
+ * comment); signer and relay calls belong in the returned {@link PublishBarrier}.
34
+ */
35
+ readonly tx: GroupStoreTx;
36
+ /**
37
+ * The pending-tagged snapshot of the state the commit produces (payload kind `marmot.groupSnapshot.pending`,
38
+ * carrying `{ digest, parentTag }`; its window's tip edge is the commit from the parent). Built lazily on the first
39
+ * read and memoized; readable only while the hook runs — a first read after it returned throws `transaction-closed`.
40
+ * NOT ENCRYPTED, like every snapshot: it holds live key material.
41
+ */
42
+ readonly snapshot: GroupSnapshot;
43
+ /** Set only for the commit `devices.forget` issues: the signature keys (hex) of the leaves it removes. Its backup stays on the confirm path. */
44
+ readonly forgetting?: {
45
+ readonly leafKeys: readonly string[];
46
+ };
47
+ /** `true` only when the hook runs for an envelope an earlier pass staged (the resume path or a publish retry timer), not the run that staged it. */
48
+ readonly resumed: boolean;
49
+ }
50
+ export type BeforePublishHook = (ctx: BeforePublishContext) => void | PublishBarrier | Promise<void | PublishBarrier>;
51
+ /** Why the commit went out without (all of) its pre-publish work. */
52
+ export type BeforePublishSkippedReason = 'hook-error' | 'barrier-failed' | 'barrier-timeout';
53
+ /** `beforePublishSkipped`: the commit was published although a hook threw, a barrier rejected or the deadline passed. */
54
+ export interface BeforePublishSkipped {
55
+ readonly groupId: string;
56
+ readonly intentId: string;
57
+ readonly reason: BeforePublishSkippedReason;
58
+ /** The hook's or the barrier's rejection; absent for `barrier-timeout`. */
59
+ readonly error?: unknown;
60
+ }
61
+ /** The client's `onBeforePublish` registry and its deadline. */
62
+ export interface BeforePublishRegistry {
63
+ /** `options.beforePublishTimeoutMs`. */
64
+ readonly timeoutMs: number;
65
+ /** The live hook list, in registration order. */
66
+ readonly hooks: readonly BeforePublishHook[];
67
+ /** Registers `hook`; returns its unregister function (idempotent). */
68
+ register(hook: BeforePublishHook): () => void;
69
+ /** Drops every hook (dispose). */
70
+ clear(): void;
71
+ }
72
+ export declare function createBeforePublishRegistry(timeoutMs: number): BeforePublishRegistry;
73
+ /** The scheduler the barrier deadline runs on (the client's injectable timers). */
74
+ export interface BeforePublishTimers {
75
+ set(callback: () => void, ms: number): unknown;
76
+ clear(handle: unknown): void;
77
+ }
78
+ export interface BeforePublishSite {
79
+ readonly groupId: string;
80
+ readonly guard: ReentrancyGuard;
81
+ /** The registry's live hook list (read once per run, in registration order). */
82
+ readonly hooks: readonly BeforePublishHook[];
83
+ readonly timeoutMs: number;
84
+ readonly timers: BeforePublishTimers;
85
+ /** One hook transaction on the group's store, framed on the group's `store` surface. */
86
+ transaction<T>(fn: (tx: GroupStoreTx) => Promise<T>): Promise<T>;
87
+ /** Emits `beforePublishSkipped`. */
88
+ skipped(event: BeforePublishSkipped): void;
89
+ /** Whether the group's runtime has ended (client disposed, group fenced or abandoned, stores lost their lease). */
90
+ ended(): boolean;
91
+ /**
92
+ * Registers `end` to be told once if the group's runtime ends while the barriers wait; returns its removal. The
93
+ * wait then stops at once, abandoning the barriers. Calls `end` at once when the runtime already ended.
94
+ */
95
+ onRuntimeEnd(end: () => void): () => void;
96
+ }
97
+ /** One own commit, staged and about to be published. */
98
+ export interface BeforePublishRun {
99
+ readonly intentId: string;
100
+ readonly kind: 'commit' | 'self-update';
101
+ readonly envelopeId: string;
102
+ /** The staged commit's MLS wire bytes. */
103
+ readonly commitMessage: Uint8Array;
104
+ /** The state the commit was built from, and the state it produces (deserialized from the staged record). */
105
+ readonly parentState: ClientState;
106
+ readonly newState: ClientState;
107
+ /** The window `confirmRecord` would persist for this commit — called at most once, on the first `snapshot` read. */
108
+ readonly window: () => RetainedWindow;
109
+ /** The group's account-index `createdAt` (client-clock ms), when known. */
110
+ readonly createdAt: number | undefined;
111
+ readonly forgetting?: {
112
+ readonly leafKeys: readonly string[];
113
+ };
114
+ readonly resumed: boolean;
115
+ }
116
+ /**
117
+ * Runs every registered hook for `run`, then awaits the barriers they returned under one deadline. Never rejects for
118
+ * a hook or barrier failure (the commit is published whatever happens; `site.skipped` reports it); a disposal of the
119
+ * client propagates, like everywhere else in the settlement.
120
+ */
121
+ export declare function runBeforePublish(site: BeforePublishSite, run: BeforePublishRun): Promise<'done' | 'ended'>;
@@ -0,0 +1,182 @@
1
+ /**
2
+ * `extensions.onBeforePublish` (epic marmot-leaf-backup-pre-publish, AC-HOOK-*, AC-BAR-*): a hook between an own
3
+ * commit's staging and its FIRST publish, handed the pending-tagged {@link GroupSnapshot} of the state the commit
4
+ * produces, plus an optional bounded, best-effort {@link PublishBarrier} the commit's publish waits for.
5
+ *
6
+ * Unlike `onConfirm` (which runs INSIDE the persisting transaction and whose throw aborts it) this surface is
7
+ * best-effort by decision: each hook runs in its OWN group-store transaction, after the staging transaction
8
+ * committed, so a throw rolls back only that hook's writes and never the durable `pendingIntents` record; the
9
+ * commit is published whatever the hooks and barriers do (a `beforePublishSkipped` event reports it). Marmot alone
10
+ * publishes the commit (ADR-007): a hook never takes the commit's transaction nor publishes it.
11
+ *
12
+ * Contract:
13
+ * - runs for `commit` and `self-update` intents only (never an application message, a proposal, a create, a join,
14
+ * a foreign commit's ingest or a restore's adoption), once per staged envelope per runtime;
15
+ * - hooks run in registration order, each in its own transaction and `onBeforePublish` re-entrancy frame;
16
+ * - the barriers they return run AFTER every hook transaction committed, outside any storage transaction,
17
+ * concurrently under ONE deadline (`beforePublishTimeoutMs`); a rejection or the deadline abandons a barrier (its
18
+ * `signal` aborts) and the commit is published anyway;
19
+ * - `ctx.snapshot` is lazy (a hook that never reads it pays no serialization) and readable only while the hook runs.
20
+ *
21
+ * The hook is the DURABLE-WRITE half: it holds the group's queue and an open store transaction for as long as it
22
+ * runs, and nothing bounds it (a transaction cannot be abandoned safely mid-flight). A hook therefore does store
23
+ * writes through `ctx.tx` and CPU work only (read the snapshot, seal it, write a record), never signer, relay or
24
+ * other I/O. All I/O belongs in the `PublishBarrier` it returns, which runs outside any transaction under the
25
+ * deadline. Register hooks before the first group access: a commit staged or resumed earlier does not see a hook
26
+ * registered later.
27
+ *
28
+ * Hooks must be idempotent per `commit.digest`: a crash between staging and the hook is repaired by the resume path
29
+ * running the hook again (`resumed: true`).
30
+ */
31
+ import { commitDigest } from '@941design/marmot-engine/core';
32
+ import { tagOf } from '../history/index.js';
33
+ import { hexOf } from '../history/hex.js';
34
+ import { MarmotError } from '../shared/index.js';
35
+ import { cursorFloor, snapshotLineage } from './confirm-hooks.js';
36
+ import { sealGroupSnapshot } from './group-snapshot.js';
37
+ export function createBeforePublishRegistry(timeoutMs) {
38
+ const hooks = [];
39
+ return {
40
+ timeoutMs,
41
+ hooks,
42
+ register(hook) {
43
+ if (typeof hook !== 'function')
44
+ throw new MarmotError('invalid-options', 'extensions.onBeforePublish: hook must be a function');
45
+ hooks.push(hook);
46
+ return () => {
47
+ const i = hooks.indexOf(hook);
48
+ if (i >= 0)
49
+ hooks.splice(i, 1);
50
+ };
51
+ },
52
+ clear() {
53
+ hooks.length = 0;
54
+ },
55
+ };
56
+ }
57
+ /**
58
+ * Runs every registered hook for `run`, then awaits the barriers they returned under one deadline. Never rejects for
59
+ * a hook or barrier failure (the commit is published whatever happens; `site.skipped` reports it); a disposal of the
60
+ * client propagates, like everywhere else in the settlement.
61
+ */
62
+ export async function runBeforePublish(site, run) {
63
+ const hooks = [...site.hooks];
64
+ if (hooks.length === 0)
65
+ return 'done';
66
+ const digest = hexOf(commitDigest(run.commitMessage));
67
+ const parentTag = tagOf(run.parentState);
68
+ const tag = tagOf(run.newState);
69
+ const epoch = run.newState.groupContext.epoch;
70
+ const barriers = [];
71
+ for (const hook of hooks) {
72
+ if (site.ended())
73
+ return 'ended';
74
+ let open = true;
75
+ let sealed;
76
+ let barrier;
77
+ try {
78
+ await site.transaction(async (tx) => {
79
+ const since = await cursorFloor(tx);
80
+ const lineage = await snapshotLineage(tx);
81
+ const snapshotOf = () => {
82
+ if (!open) {
83
+ throw new MarmotError('transaction-closed', 'BeforePublishContext.snapshot: read after the hook returned; read it inside the hook', {
84
+ details: { groupId: site.groupId, intentId: run.intentId },
85
+ });
86
+ }
87
+ if (sealed !== undefined)
88
+ return sealed;
89
+ sealed = sealGroupSnapshot({
90
+ groupId: site.groupId,
91
+ state: run.newState,
92
+ window: run.window(),
93
+ ...(run.createdAt === undefined ? {} : { createdAt: run.createdAt }),
94
+ ...(since === undefined ? {} : { since }),
95
+ ...(lineage.length === 0 ? {} : { lineage }),
96
+ pending: { digest, parentTag },
97
+ });
98
+ return sealed;
99
+ };
100
+ const ctx = {
101
+ groupId: site.groupId,
102
+ intentId: run.intentId,
103
+ kind: run.kind,
104
+ epoch,
105
+ commit: Object.freeze({ eventId: run.envelopeId, digest, parentTag, tag }),
106
+ tx,
107
+ get snapshot() {
108
+ return snapshotOf();
109
+ },
110
+ ...(run.forgetting === undefined ? {} : { forgetting: { leafKeys: [...run.forgetting.leafKeys] } }),
111
+ resumed: run.resumed,
112
+ };
113
+ try {
114
+ const result = await site.guard.call(site.groupId, 'onBeforePublish', () => hook(ctx));
115
+ if (typeof result === 'function')
116
+ barrier = result;
117
+ }
118
+ finally {
119
+ open = false;
120
+ }
121
+ });
122
+ }
123
+ catch (error) {
124
+ // The hook's own transaction rolled back; the staged record and every other hook's writes stay.
125
+ if (error instanceof MarmotError && error.code === 'disposed')
126
+ throw error;
127
+ site.skipped({ groupId: site.groupId, intentId: run.intentId, reason: 'hook-error', error });
128
+ continue;
129
+ }
130
+ if (barrier !== undefined)
131
+ barriers.push(barrier);
132
+ }
133
+ // A runtime that ended during a hook (dispose, fence, lost lease) starts no barrier and arms no timer.
134
+ if (site.ended())
135
+ return 'ended';
136
+ if (barriers.length > 0)
137
+ await awaitBarriers(site, run.intentId, barriers);
138
+ return site.ended() ? 'ended' : 'done';
139
+ }
140
+ /** Awaits every barrier concurrently under the site's one deadline; resolves when all settled, the deadline passed or the runtime ended. */
141
+ function awaitBarriers(site, intentId, barriers) {
142
+ const abort = new AbortController();
143
+ return new Promise((resolve) => {
144
+ let finished = false;
145
+ let pending = barriers.length;
146
+ let timer;
147
+ let release = () => undefined;
148
+ const finish = () => {
149
+ if (finished)
150
+ return;
151
+ finished = true;
152
+ site.timers.clear(timer);
153
+ release();
154
+ resolve();
155
+ };
156
+ timer = site.timers.set(() => {
157
+ if (finished)
158
+ return;
159
+ abort.abort(new Error('onBeforePublish barrier: the beforePublishTimeoutMs deadline passed'));
160
+ site.skipped({ groupId: site.groupId, intentId, reason: 'barrier-timeout' });
161
+ finish();
162
+ }, site.timeoutMs);
163
+ release = site.onRuntimeEnd(() => {
164
+ abort.abort(new Error('onBeforePublish barrier: the group ended'));
165
+ finish();
166
+ });
167
+ for (const barrier of barriers) {
168
+ site.guard
169
+ .call(site.groupId, 'onBeforePublish', () => barrier(abort.signal))
170
+ .then(() => {
171
+ if (--pending === 0)
172
+ finish();
173
+ }, (error) => {
174
+ // A barrier that fails after the wait ended (deadline, runtime end) is already abandoned: nothing to report.
175
+ if (!finished)
176
+ site.skipped({ groupId: site.groupId, intentId, reason: 'barrier-failed', error });
177
+ if (--pending === 0)
178
+ finish();
179
+ });
180
+ }
181
+ });
182
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The engine seams every `marmot` group engine is built with (S8, S9; ADR-002
3
+ * seams, ADR-003, ADR-006, ADR-012): one place, so the engine that builds a
4
+ * commit and every engine that receives one — and the Welcome join
5
+ * (`clientConfig`) — agree (AC-VENDOR-6: a mismatched equality rule is a
6
+ * silent fork hazard).
7
+ *
8
+ * - `clientConfig`: {@link sameAccountClientConfig} — signature-key-only
9
+ * KeyPackage/leaf equality (AC-DEV-12 pins that the ts-mls default would
10
+ * refuse a same-account Add);
11
+ * - `authorizeCommit`: the admin rule's send-path half (S9: no SelfRemove
12
+ * of an admin account's last leaf) around the same-account rules over the
13
+ * engine's CURRENT tree (the commit's parent), read lazily through
14
+ * `ratchetTree`;
15
+ * - `adminPolicyCallback`: S3's proof gate around the same-account receive
16
+ * rules around S9's admin deviation (AC-ADMIN-4) around the vendored
17
+ * admin rule;
18
+ * - `isActiveAdminLeaver`: S9's "last active leaf of an admin account" for
19
+ * the engine's SelfRemove auto-commit election (AC-ADMIN-9).
20
+ */
21
+ import type { decideCommitAuthorization } from '@941design/marmot-engine/core';
22
+ import type { ActiveAdminLeaverPredicate } from '@941design/marmot-engine/engine';
23
+ import type { ClientConfig, RatchetTree } from '@941design/marmot-engine/mls';
24
+ import { sameAccountClientConfig, type AdminPolicyFactory } from '../account/index.js';
25
+ /** An absent seam is the engine's own default (the vendored rule). */
26
+ export interface EngineSeams {
27
+ readonly clientConfig: ClientConfig;
28
+ readonly authorizeCommit: typeof decideCommitAuthorization | undefined;
29
+ readonly adminPolicyCallback: AdminPolicyFactory | undefined;
30
+ readonly isActiveAdminLeaver: ActiveAdminLeaverPredicate | undefined;
31
+ }
32
+ /**
33
+ * Internal (tests only, never part of `MarmotClientOptions`): rewrites the
34
+ * seams a client's engines get — how a test builds a client on the engine
35
+ * defaults to prove a seam is load-bearing (AC-ADMIN-8, AC-ADMIN-9).
36
+ */
37
+ export type EngineSeamsOverride = (seams: EngineSeams) => EngineSeams;
38
+ /** The seams for one engine; `ratchetTree` returns that engine's current tree. */
39
+ export declare function engineSeams(ratchetTree: () => RatchetTree): EngineSeams;
40
+ export { sameAccountClientConfig };
41
+ /** The convergence policy every `marmot` engine runs — defined beside the rewind window's horizon (one source). */
42
+ export { MARMOT_CONVERGENCE_POLICY } from '../history/policy.js';
@@ -0,0 +1,13 @@
1
+ import { createAdminAuthorizeCommit, createAdminDeviationPolicy, createProofEnforcingAdminPolicy, createSameAccountAdminPolicy, createSameAccountAuthorizeCommit, isLastActiveLeafOfAdmin, sameAccountClientConfig, } from '../account/index.js';
2
+ /** The seams for one engine; `ratchetTree` returns that engine's current tree. */
3
+ export function engineSeams(ratchetTree) {
4
+ return {
5
+ clientConfig: sameAccountClientConfig,
6
+ authorizeCommit: createAdminAuthorizeCommit(createSameAccountAuthorizeCommit(ratchetTree), ratchetTree),
7
+ adminPolicyCallback: createProofEnforcingAdminPolicy(createSameAccountAdminPolicy(createAdminDeviationPolicy())),
8
+ isActiveAdminLeaver: isLastActiveLeafOfAdmin,
9
+ };
10
+ }
11
+ export { sameAccountClientConfig };
12
+ /** The convergence policy every `marmot` engine runs — defined beside the rewind window's horizon (one source). */
13
+ export { MARMOT_CONVERGENCE_POLICY } from '../history/policy.js';