@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,180 @@
1
+ /**
2
+ * Same-account authorisation (S8; ADR-003, ADR-002 engine seams) — what lets
3
+ * a second device of an account join a group without an admin, and what
4
+ * bounds it.
5
+ *
6
+ * 1. `clientConfig` ({@link sameAccountClientConfig}): ts-mls's default
7
+ * `compareKeyPackageToLeafNode` treats a KeyPackage whose CREDENTIAL
8
+ * equals an existing leaf's as "already a member", so a sibling
9
+ * device's Add (same Nostr account, same basic credential) is refused
10
+ * on both the send and the receive path. Marmot compares signature keys
11
+ * only (ADR-003 Decision 2); every engine this client builds, and every
12
+ * Welcome join, runs with it (a mismatch between members is a silent
13
+ * fork hazard, AC-VENDOR-6).
14
+ * 2. The same-account rules, applied on BOTH paths:
15
+ * - a leaf may commit Adds of KeyPackages whose credential names its
16
+ * own account, and Removes of other leaves of its own account, even
17
+ * when it is not an admin ({@link createSameAccountAuthorizeCommit}
18
+ * on the send path, {@link createSameAccountAdminPolicy} on the
19
+ * receive path); every other part of the commit is judged by the
20
+ * vendored admin rule unchanged;
21
+ * - no commit may carry more than {@link MAX_ADDS_PER_ACCOUNT_PER_COMMIT}
22
+ * Adds for one account, nor leave one account with more than
23
+ * {@link MAX_LEAVES_PER_ACCOUNT} leaves — whoever commits it (an admin
24
+ * adding a sixth leaf is refused just the same).
25
+ * 3. The compensating control ADR-003 names — proof-v2 validation of every
26
+ * leaf on the receive path — is S3's `identity-proof.ts` gate, consumed
27
+ * here (it wraps these callbacks, it is not re-implemented).
28
+ */
29
+ import { decideCommitAuthorization, defaultMarmotClientConfig, getCredentialPubkey } from '@941design/marmot-engine/core';
30
+ import { createAdminCommitPolicyCallback } from '@941design/marmot-engine/engine';
31
+ import { defaultProposalTypes, nodeTypes, } from '@941design/marmot-engine/mls';
32
+ import { projectCommitLeaves } from './identity-proof.js';
33
+ /** ADR-003: at most four same-account Adds in one commit. */
34
+ export const MAX_ADDS_PER_ACCOUNT_PER_COMMIT = 4;
35
+ /** ADR-003: at most five leaves per account in a group. */
36
+ export const MAX_LEAVES_PER_ACCOUNT = 5;
37
+ function bytesEqual(a, b) {
38
+ if (a.length !== b.length)
39
+ return false;
40
+ let diff = 0;
41
+ for (let i = 0; i < a.length; i++)
42
+ diff |= a[i] ^ b[i];
43
+ return diff === 0;
44
+ }
45
+ /**
46
+ * The ts-mls `ClientConfig` every `marmot` engine and Welcome join uses: the
47
+ * Marmot default with `compareKeyPackageToLeafNode` comparing signature keys
48
+ * only (a device — one signature key — still never holds two leaves of one
49
+ * group; a sibling device of the same account is a new member).
50
+ */
51
+ export const sameAccountClientConfig = Object.freeze({
52
+ ...defaultMarmotClientConfig,
53
+ keyPackageEqualityConfig: Object.freeze({
54
+ compareKeyPackages: (a, b) => bytesEqual(a.leafNode.signaturePublicKey, b.leafNode.signaturePublicKey),
55
+ compareKeyPackageToLeafNode: (a, b) => bytesEqual(a.leafNode.signaturePublicKey, b.signaturePublicKey),
56
+ }),
57
+ });
58
+ function leafAt(ratchetTree, leafIndex) {
59
+ const node = ratchetTree[2 * leafIndex];
60
+ return node?.nodeType === nodeTypes.leaf ? node.leaf : undefined;
61
+ }
62
+ function accountOf(leaf) {
63
+ if (leaf === undefined)
64
+ return undefined;
65
+ try {
66
+ return getCredentialPubkey(leaf.credential);
67
+ }
68
+ catch {
69
+ return undefined;
70
+ }
71
+ }
72
+ /**
73
+ * The per-commit and per-group limits over the commit's exact proposal union
74
+ * against `ratchetTree` (the parent epoch's tree): `undefined` when both
75
+ * hold. Adds are counted by the credential they name; leaves over the
76
+ * projected (post-commit) leaf set, for the accounts the commit adds to.
77
+ */
78
+ export function checkSameAccountLimits(ratchetTree, proposals) {
79
+ const adds = new Map();
80
+ for (const { proposal } of proposals) {
81
+ if (proposal.proposalType !== defaultProposalTypes.add || !('add' in proposal))
82
+ continue;
83
+ const account = accountOf(proposal.add.keyPackage.leafNode);
84
+ if (account === undefined)
85
+ continue; // not a Marmot identity: the proof gate rejects it
86
+ const count = (adds.get(account) ?? 0) + 1;
87
+ if (count > MAX_ADDS_PER_ACCOUNT_PER_COMMIT)
88
+ return { reason: 'too-many-adds', account, adds: count };
89
+ adds.set(account, count);
90
+ }
91
+ if (adds.size === 0)
92
+ return undefined;
93
+ const leaves = new Map();
94
+ for (const { leaf } of projectCommitLeaves(ratchetTree, proposals)) {
95
+ const account = accountOf(leaf);
96
+ // Only the accounts this commit adds to: it cannot be blamed for a count it does not change.
97
+ if (account === undefined || !adds.has(account))
98
+ continue;
99
+ const count = (leaves.get(account) ?? 0) + 1;
100
+ if (count > MAX_LEAVES_PER_ACCOUNT)
101
+ return { reason: 'too-many-leaves', account, leaves: count };
102
+ leaves.set(account, count);
103
+ }
104
+ return undefined;
105
+ }
106
+ /**
107
+ * Whether one proposal is a same-account change of `actorAccount`: an Add of
108
+ * a KeyPackage naming that account, or a Remove of ANOTHER leaf of it (a
109
+ * leaf never removes itself — that is SelfRemove, judged by the admin rule).
110
+ */
111
+ export function isSameAccountChange(ratchetTree, actorAccount, actorLeafIndex, entry) {
112
+ const { proposal } = entry;
113
+ if (proposal.proposalType === defaultProposalTypes.add && 'add' in proposal) {
114
+ return accountOf(proposal.add.keyPackage.leafNode) === actorAccount;
115
+ }
116
+ if (proposal.proposalType === defaultProposalTypes.remove && 'remove' in proposal) {
117
+ const removed = Number(proposal.remove.removed);
118
+ return removed !== actorLeafIndex && accountOf(leafAt(ratchetTree, removed)) === actorAccount;
119
+ }
120
+ return false;
121
+ }
122
+ /**
123
+ * The engine's `authorizeCommit` seam (send path) over the tree `ratchetTree()`
124
+ * returns (the engine's current state — the commit's parent): the limits
125
+ * first, then the vendored rule; a non-admin's union is authorised when what
126
+ * remains after taking out its same-account changes is something the
127
+ * vendored rule lets a non-admin commit (nothing, its own Update, or
128
+ * SelfRemoves). The typed decision carries only the vendored reason; the
129
+ * client checks the limits itself before it builds a commit, so a refusal
130
+ * here is a backstop.
131
+ */
132
+ export function createSameAccountAuthorizeCommit(ratchetTree) {
133
+ return (args) => {
134
+ const tree = ratchetTree();
135
+ if (checkSameAccountLimits(tree, args.proposals) !== undefined)
136
+ return { authorized: false, reason: 'non-admin-proposal-union' };
137
+ const vendored = decideCommitAuthorization(args);
138
+ if (vendored.authorized)
139
+ return vendored;
140
+ const rest = args.proposals.filter((p) => !isSameAccountChange(tree, args.actorPubkey, args.actorLeafIndex, p));
141
+ if (rest.length === args.proposals.length)
142
+ return vendored;
143
+ // Nothing else, or only what a non-admin may commit alone.
144
+ if (rest.length === 0)
145
+ return { authorized: true };
146
+ return decideCommitAuthorization({ ...args, proposals: rest });
147
+ };
148
+ }
149
+ /**
150
+ * The receive-path counterpart, as an `adminPolicyCallback` factory wrapping
151
+ * `inner` (default: the vendored `createAdminCommitPolicyCallback`): a commit
152
+ * breaking a limit is rejected, whoever sent it; a non-admin committer's
153
+ * same-account changes are taken out of the proposal list `inner` judges, so
154
+ * `inner` decides only the rest (an empty rest is accepted by it). Proposals
155
+ * (not commits) go to `inner` unchanged. Wrapped in turn by S3's
156
+ * `createProofEnforcingAdminPolicy`, which checks every projected leaf's
157
+ * proof first (AC-DEV-3).
158
+ */
159
+ export function createSameAccountAdminPolicy(inner = createAdminCommitPolicyCallback) {
160
+ return (args) => {
161
+ const innerCallback = inner(args);
162
+ return (incoming) => {
163
+ if (incoming.kind !== 'commit')
164
+ return innerCallback(incoming);
165
+ if (checkSameAccountLimits(args.ratchetTree, incoming.proposals) !== undefined)
166
+ return 'reject';
167
+ const sender = incoming.senderLeafIndex;
168
+ if (sender === undefined)
169
+ return innerCallback(incoming);
170
+ const senderIndex = Number(sender);
171
+ const actor = accountOf(leafAt(args.ratchetTree, senderIndex));
172
+ if (actor === undefined || args.adminPubkeys.includes(actor))
173
+ return innerCallback(incoming);
174
+ const rest = incoming.proposals.filter((p) => !isSameAccountChange(args.ratchetTree, actor, senderIndex, p));
175
+ if (rest.length === incoming.proposals.length)
176
+ return innerCallback(incoming);
177
+ return innerCallback({ ...incoming, proposals: rest });
178
+ };
179
+ };
180
+ }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Group teardown (S9; AC-ADMIN-3, -5, -6, -7, -10): `leave()`, `abandon()`,
3
+ * `destroy()` and `departAsAdmin()` as ONE durable intent per group, and the
4
+ * per-group `leave()` that `devices.forget(ownLeafKey)` runs on every held
5
+ * group.
6
+ *
7
+ * The intent is an account record (extension `marmot.teardown`, keyed by a
8
+ * random request id) written before any effect — the group store is exactly
9
+ * what the teardown deletes, so the record cannot live there. Its phases:
10
+ *
11
+ * 1. `leaving` (leave only): the local leaf's SelfRemove proposal goes out
12
+ * through the pipeline's durable intents (re-proposed whenever an epoch
13
+ * change drops it); a leaf that is its admin account's last first
14
+ * commits the account's demotion (`departAsAdmin`). The phase ends when
15
+ * the group's own state shows the leaf removed — a peer's confirmed
16
+ * commit, the engine's SelfRemove auto-commit on some other member —
17
+ * or at the absolute `deadline` (`leaveTimeoutMs` after the request, on
18
+ * the client clock; re-armed after a reload), or at once when the leaf
19
+ * is the group's only member (nothing is sent). A leaf that is (or
20
+ * becomes, while this runs) the last leaf of the group's last active
21
+ * admin cannot leave: the intent ends `last-admin` straight to `done`,
22
+ * WITHOUT the purge — the group keeps its admin and stays held.
23
+ * 2. `purging` (every kind — this IS `abandon()`): the group runtime is
24
+ * retired and every artifact of the group's `GroupStore` deleted
25
+ * (nothing is published), then ONE account transaction drops what the
26
+ * account keeps per group — `invites` (Welcome deliveries),
27
+ * `enrolmentManifests`, still-`pending` invitations, received KeyPackage
28
+ * offers, `keyPackageGroupRefs`, and the group's index entry — and, for
29
+ * `destroy()`, the retained (grace-window) init keys of the KeyPackages
30
+ * the group's Welcomes consumed.
31
+ * 3. `deleting` (destroy only): S4's `forget()` — a durable kind-5 on the
32
+ * KeyPackage's slot — for every KeyPackage the account minted for the
33
+ * group (captured when the destroy was requested, before the purge
34
+ * deleted the refs): `keyPackages.offer({ groupId })` KeyPackages and
35
+ * the per-group KeyPackages of an enrolment request.
36
+ *
37
+ * `abandon()` / `destroy()` requested while a `leave()` runs take the
38
+ * record over (outcome `abandoned`); a second `leave()` joins the running
39
+ * one. A request joins only a record still in `leaving` or `purging` — the
40
+ * group's FRONT intent, at most one per group. A record past its purge
41
+ * (`deleting`) no longer stands for the group: the state it deleted is gone,
42
+ * and a group held again was re-joined through a newer Welcome (S11's join
43
+ * barrier lets none through earlier), so a request records a FRESH intent
44
+ * beside it (`succeeds` names it) instead of resolving on the old one's
45
+ * progress (S16). The front intent runs on one driver per group; each
46
+ * past-purge record's kind-5 pass on its own driver — the two settle
47
+ * independently: the fresh intent never waits on the old destroy's signer or
48
+ * relays, and the old one's deletions are neither dropped nor issued twice
49
+ * (the fresh destroy's KeyPackage capture skips refs an older record of the
50
+ * group still deletes). A driver re-reads its record inside every
51
+ * transaction and never holds one across a group operation, signer or relay
52
+ * call. Failures a pass counts (not explicitly transient,
53
+ * `maintenanceFailureReason`) — each charged to the record its driver was
54
+ * driving — give that intent up after {@link MAX_MAINTENANCE_FAILURES}
55
+ * (`maintenanceFailed`, kind `teardown`); any work left is retried by a
56
+ * background pass, each driver at its own capped backoff, and the
57
+ * next inbox pass or `groups.list()/get()` resumes intents a reload
58
+ * interrupted.
59
+ */
60
+ import { type AdoptionProofs } from '../invitations/index.js';
61
+ import type { AccountStoreTx } from '../storage/index.js';
62
+ /** Account extension namespace of teardown intents. */
63
+ export declare const TEARDOWN_EXTENSION = "marmot.teardown";
64
+ /** Default `leaveTimeoutMs`: how long `leave()` waits for a peer's commit before purging anyway. */
65
+ export declare const DEFAULT_LEAVE_TIMEOUT_MS = 60000;
66
+ export type TeardownKind = 'leave' | 'abandon' | 'destroy';
67
+ /**
68
+ * How a teardown ended its `leaving` phase: `removed` (the leaf left the tree),
69
+ * `sole-member` (nothing to send), `timed-out` (the deadline passed first),
70
+ * `last-admin` (the leaf could not leave: its account is the last active
71
+ * admin), `abandoned` (an `abandon()`/`destroy()` took it over); absent for
72
+ * a plain `abandon()`/`destroy()`.
73
+ */
74
+ export type TeardownOutcome = 'removed' | 'sole-member' | 'timed-out' | 'last-admin' | 'abandoned';
75
+ /** What the `leaving` phase reads from the group, on its queue. */
76
+ export interface LeaveView {
77
+ /** False once the local leaf was removed. */
78
+ readonly member: boolean;
79
+ /** The local leaf is the group's only occupied leaf. */
80
+ readonly soleMember: boolean;
81
+ /** The local account is a listed admin. */
82
+ readonly admin: boolean;
83
+ /** The local account holds another leaf of the group. */
84
+ readonly accountHasOtherLeaf: boolean;
85
+ /** AC-ADMIN-2 for the local account. */
86
+ readonly lastActiveAdmin: boolean;
87
+ /** The local leaf's own SelfRemove proposal is staged at the current epoch. */
88
+ readonly selfRemoveStaged: boolean;
89
+ /** An own commit-kind intent (proposal, commit, self-update) is still recorded: its fate decides first. */
90
+ readonly ownIntentPending: boolean;
91
+ /**
92
+ * S20: present while `member` is false and the removal is still revisable — the client-clock time it settles.
93
+ * Until then a same-epoch sibling may still rewind the leaf back into the group (BACKLOG
94
+ * same-epoch-fork-removal-divergence), so the leave waits for it before concluding `removed`.
95
+ */
96
+ readonly removalSettlesAt?: number;
97
+ }
98
+ /** The group operations teardown needs; `client` implements them (account never imports client). */
99
+ export interface TeardownGroupPort {
100
+ /** The group's current state as the leave sees it, loading the group; `undefined` when it is not held. */
101
+ view(groupId: string): Promise<LeaveView | undefined>;
102
+ /** The local leaf's SelfRemove proposal through the pipeline (rejects like `send`). */
103
+ proposeSelfRemove(groupId: string): Promise<void>;
104
+ /** One commit dropping the local account from the admin list (rejects like `send`). */
105
+ demote(groupId: string): Promise<void>;
106
+ /**
107
+ * Retires the group runtime and deletes everything of the group's `GroupStore`; idempotent, publishes nothing.
108
+ * Inside the ONE serialized group operation that clears the store — after every operation queued before it —
109
+ * it first reads the epoch of the stored state and the group's adoption proofs, and awaits
110
+ * `beforeClear(epoch, proofs)` (the watermark, and the stamping of every invitation the proofs make `joined`:
111
+ * epic marmot-invitation-outcomes S2, A1), then clears (F2). `beforeClear` is not called when no state is stored
112
+ * any more. `proofs` is optional only for ports that hold no adoption proofs (test doubles); the client's port always
113
+ * passes them — without them A1 stamps nothing and the proofs' outcomes rest on A2 alone.
114
+ */
115
+ purge(groupId: string, beforeClear: (epoch: bigint, proofs?: AdoptionProofs) => Promise<void>): Promise<void>;
116
+ /** Calls `listener` whenever the group's exposed state changes; returns the unsubscribe. */
117
+ watch(groupId: string, listener: () => void): () => void;
118
+ }
119
+ export interface TeardownDeps {
120
+ readonly clock: {
121
+ now(): number;
122
+ };
123
+ readonly timers: {
124
+ set(callback: () => void, ms: number): unknown;
125
+ clear(handle: unknown): void;
126
+ };
127
+ readonly leaveTimeoutMs: number;
128
+ /** AC-KP-3's grace window: how long a consumed KeyPackage's key serves other invitations' Welcomes. */
129
+ readonly graceWindowMs: number;
130
+ /** `AccountStore.transaction`, routed through the re-entrancy guard. */
131
+ transaction<T>(fn: (tx: AccountStoreTx) => Promise<T> | T): Promise<T>;
132
+ readonly groups: TeardownGroupPort;
133
+ /** The account extension holding the group index (`client`'s `marmot.groups`). */
134
+ readonly groupIndexExtension: string;
135
+ /** S4 `keyPackages.forget(ref)` (a durable kind-5 on the slot) and where a ref stands. */
136
+ forgetKeyPackage(ref: string): Promise<void>;
137
+ keyPackageStatus(ref: string): Promise<'absent' | 'deleting' | 'present'>;
138
+ /** S4's resume of pending KeyPackage intents (re-publishes a pending kind-5). */
139
+ resumeKeyPackageIntents(): Promise<void>;
140
+ /** A group's teardown settled (its `leaving` phase ended): the device service's own-leaf forget may continue. */
141
+ onSettled(groupId: string): void;
142
+ onMaintenanceFailed(failure: {
143
+ readonly invitationId: string;
144
+ readonly kind: 'teardown' | 'keypackage-deletion';
145
+ readonly reason: string;
146
+ }): void;
147
+ /** Runs `fn` outside every re-entrancy frame (a background driver must not inherit its starter's). */
148
+ detached<T>(fn: () => T): T;
149
+ isDisposed(): boolean;
150
+ }
151
+ export interface TeardownService {
152
+ /** AC-ADMIN-6; refused `last-admin` (nothing written) when the local leaf is the last leaf of the last active admin. */
153
+ leave(groupId: string): Promise<void>;
154
+ /** AC-ADMIN-3: `last-admin`, then `use-forget`, checked before anything is written; `invalid-options` for a non-admin. */
155
+ depart(groupId: string): Promise<void>;
156
+ /** AC-ADMIN-5. */
157
+ abandon(groupId: string): Promise<void>;
158
+ /** AC-ADMIN-7. */
159
+ destroy(groupId: string): Promise<void>;
160
+ /** AC-ADMIN-10's per-group `leave()` (no precondition refuses it); resolves with the request id once it is recorded. */
161
+ startLeave(groupId: string): Promise<string>;
162
+ /**
163
+ * Whether a Welcome bringing `groupId` back at `epoch` must be refused: this client purged the group and the
164
+ * Welcome's state is not newer than the one it deleted (an interrupted or redelivered join of the old group).
165
+ * A later re-invitation (a higher epoch) is not refused.
166
+ */
167
+ refusesJoin(groupId: string, epoch: bigint): Promise<boolean>;
168
+ /** Completes the group's interrupted purge, if one is recorded, before a Welcome may bring the group back. */
169
+ finishPurge(groupId: string): Promise<void>;
170
+ /**
171
+ * Whether this device is itself tearing the group down: an intent (`leave()`, an own-leaf `devices.forget`,
172
+ * `abandon()`, `destroy()`) is recorded for it in its leaving or purging phase, given up or not. Such a removal of the local leaf is not announced as `groupRemoved`.
173
+ */
174
+ tearingDown(groupId: string): Promise<boolean>;
175
+ /** A started leave's outcome as `devices.forget` reports it. */
176
+ leaveOutcome(requestId: string): Promise<'pending' | 'removed' | 'timed-out'>;
177
+ /** Drives every unfinished intent in the background (never awaited by the caller). */
178
+ resumeInBackground(): void;
179
+ dispose(): void;
180
+ }
181
+ /**
182
+ * Account extension of per-group purge watermarks: `groupId` → `{ epoch, at }`, the highest epoch this client
183
+ * purged of the group. Kept apart from the teardown records (pruned after 7 days) so a delayed Welcome of the old
184
+ * group is refused for as long as one could still be joined: a Welcome needs its KeyPackage's private key, and a
185
+ * KeyPackage lives at most `MAX_KEY_PACKAGE_LIFETIME` (engine: 7 261 200 s ≈ 84 days) — so a watermark is pruned
186
+ * after {@link WATERMARK_RETENTION_MS} (90 days, with margin); a later purge of the group replaces it.
187
+ */
188
+ export declare const PURGE_WATERMARK_EXTENSION = "marmot.purged";
189
+ export declare const WATERMARK_RETENTION_MS: number;
190
+ export declare function createTeardownService(deps: TeardownDeps): TeardownService;