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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/CHANGELOG.md +709 -0
  2. package/LICENSE +21 -0
  3. package/README.md +33 -2
  4. package/dist/account/admin.d.ts +72 -0
  5. package/dist/account/admin.js +209 -0
  6. package/dist/account/device-deps.d.ts +379 -0
  7. package/dist/account/device-deps.js +36 -0
  8. package/dist/account/device-lineage.d.ts +199 -0
  9. package/dist/account/device-lineage.js +390 -0
  10. package/dist/account/device-registry.d.ts +93 -0
  11. package/dist/account/device-registry.js +1290 -0
  12. package/dist/account/device-rotation.d.ts +61 -0
  13. package/dist/account/device-rotation.js +827 -0
  14. package/dist/account/enrolment.d.ts +339 -0
  15. package/dist/account/enrolment.js +1247 -0
  16. package/dist/account/identity-proof.d.ts +79 -0
  17. package/dist/account/identity-proof.js +264 -0
  18. package/dist/account/index.d.ts +17 -0
  19. package/dist/account/index.js +16 -0
  20. package/dist/account/restore-rotation.d.ts +21 -0
  21. package/dist/account/restore-rotation.js +22 -0
  22. package/dist/account/same-account-authorization.d.ts +86 -0
  23. package/dist/account/same-account-authorization.js +180 -0
  24. package/dist/account/teardown.d.ts +127 -0
  25. package/dist/account/teardown.js +856 -0
  26. package/dist/client/before-create-group.d.ts +18 -0
  27. package/dist/client/before-create-group.js +65 -0
  28. package/dist/client/before-publish-hooks.d.ts +121 -0
  29. package/dist/client/before-publish-hooks.js +180 -0
  30. package/dist/client/client-config.d.ts +42 -0
  31. package/dist/client/client-config.js +13 -0
  32. package/dist/client/commit-redrive.d.ts +68 -0
  33. package/dist/client/commit-redrive.js +221 -0
  34. package/dist/client/component-update.d.ts +43 -0
  35. package/dist/client/component-update.js +53 -0
  36. package/dist/client/confirm-hooks.d.ts +50 -0
  37. package/dist/client/confirm-hooks.js +59 -0
  38. package/dist/client/create-client.d.ts +1022 -0
  39. package/dist/client/create-client.js +1125 -0
  40. package/dist/client/group-disband.d.ts +28 -0
  41. package/dist/client/group-disband.js +64 -0
  42. package/dist/client/group-history.d.ts +435 -0
  43. package/dist/client/group-history.js +1295 -0
  44. package/dist/client/group-profile.d.ts +31 -0
  45. package/dist/client/group-profile.js +62 -0
  46. package/dist/client/group-records.d.ts +485 -0
  47. package/dist/client/group-records.js +1034 -0
  48. package/dist/client/group-removal.d.ts +36 -0
  49. package/dist/client/group-removal.js +127 -0
  50. package/dist/client/group-remove-member.d.ts +49 -0
  51. package/dist/client/group-remove-member.js +163 -0
  52. package/dist/client/group-runtime.d.ts +388 -0
  53. package/dist/client/group-runtime.js +2701 -0
  54. package/dist/client/group-snapshot.d.ts +98 -0
  55. package/dist/client/group-snapshot.js +453 -0
  56. package/dist/client/history-pages.d.ts +107 -0
  57. package/dist/client/history-pages.js +194 -0
  58. package/dist/client/inbox-send.d.ts +19 -0
  59. package/dist/client/inbox-send.js +71 -0
  60. package/dist/client/index.d.ts +21 -0
  61. package/dist/client/index.js +13 -0
  62. package/dist/client/ingest.d.ts +82 -0
  63. package/dist/client/ingest.js +1550 -0
  64. package/dist/client/lifecycle-events.d.ts +63 -0
  65. package/dist/client/lifecycle-events.js +35 -0
  66. package/dist/client/opaque-candidates.d.ts +81 -0
  67. package/dist/client/opaque-candidates.js +169 -0
  68. package/dist/client/own-change-outbox.d.ts +66 -0
  69. package/dist/client/own-change-outbox.js +156 -0
  70. package/dist/client/pending-leaf.d.ts +116 -0
  71. package/dist/client/pending-leaf.js +378 -0
  72. package/dist/client/permissions.d.ts +9 -0
  73. package/dist/client/permissions.js +12 -0
  74. package/dist/client/pipeline.d.ts +554 -0
  75. package/dist/client/pipeline.js +3545 -0
  76. package/dist/client/reentrancy-guard.d.ts +96 -0
  77. package/dist/client/reentrancy-guard.js +153 -0
  78. package/dist/client/rekey.d.ts +58 -0
  79. package/dist/client/rekey.js +149 -0
  80. package/dist/client/transport-policy.d.ts +181 -0
  81. package/dist/client/transport-policy.js +214 -0
  82. package/dist/history/equivocation.d.ts +55 -0
  83. package/dist/history/equivocation.js +113 -0
  84. package/dist/history/fencing.d.ts +25 -0
  85. package/dist/history/fencing.js +61 -0
  86. package/dist/history/hex.d.ts +3 -0
  87. package/dist/history/hex.js +10 -0
  88. package/dist/history/index.d.ts +73 -0
  89. package/dist/history/index.js +31 -0
  90. package/dist/history/notifications.d.ts +270 -0
  91. package/dist/history/notifications.js +264 -0
  92. package/dist/history/ordering-key.d.ts +24 -0
  93. package/dist/history/ordering-key.js +101 -0
  94. package/dist/history/own-change-fork.d.ts +112 -0
  95. package/dist/history/own-change-fork.js +196 -0
  96. package/dist/history/own-change.d.ts +106 -0
  97. package/dist/history/own-change.js +146 -0
  98. package/dist/history/policy.d.ts +48 -0
  99. package/dist/history/policy.js +52 -0
  100. package/dist/history/retained-window.d.ts +215 -0
  101. package/dist/history/retained-window.js +565 -0
  102. package/dist/inbox/demux.d.ts +90 -0
  103. package/dist/inbox/demux.js +78 -0
  104. package/dist/inbox/handler-registry.d.ts +42 -0
  105. package/dist/inbox/handler-registry.js +37 -0
  106. package/dist/inbox/index.d.ts +11 -0
  107. package/dist/inbox/index.js +10 -0
  108. package/dist/inbox/seen-set.d.ts +82 -0
  109. package/dist/inbox/seen-set.js +202 -0
  110. package/dist/inbox/subscription.d.ts +236 -0
  111. package/dist/inbox/subscription.js +644 -0
  112. package/dist/index.d.ts +10 -0
  113. package/dist/index.js +9 -0
  114. package/dist/invitations/competing-welcome.d.ts +223 -0
  115. package/dist/invitations/competing-welcome.js +128 -0
  116. package/dist/invitations/decline.d.ts +61 -0
  117. package/dist/invitations/decline.js +143 -0
  118. package/dist/invitations/expect-welcome.d.ts +66 -0
  119. package/dist/invitations/expect-welcome.js +138 -0
  120. package/dist/invitations/index.d.ts +16 -0
  121. package/dist/invitations/index.js +16 -0
  122. package/dist/invitations/invite.d.ts +303 -0
  123. package/dist/invitations/invite.js +966 -0
  124. package/dist/invitations/offers.d.ts +79 -0
  125. package/dist/invitations/offers.js +115 -0
  126. package/dist/invitations/on-proposal.d.ts +47 -0
  127. package/dist/invitations/on-proposal.js +40 -0
  128. package/dist/invitations/pending-proposal-policy.d.ts +52 -0
  129. package/dist/invitations/pending-proposal-policy.js +139 -0
  130. package/dist/invitations/proposal-deadline.d.ts +133 -0
  131. package/dist/invitations/proposal-deadline.js +164 -0
  132. package/dist/invitations/relay-planes.d.ts +43 -0
  133. package/dist/invitations/relay-planes.js +70 -0
  134. package/dist/invitations/welcome-processor.d.ts +253 -0
  135. package/dist/invitations/welcome-processor.js +1180 -0
  136. package/dist/key-packages/device-key.d.ts +131 -0
  137. package/dist/key-packages/device-key.js +272 -0
  138. package/dist/key-packages/device-rotation-records.d.ts +83 -0
  139. package/dist/key-packages/device-rotation-records.js +173 -0
  140. package/dist/key-packages/group-refs.d.ts +40 -0
  141. package/dist/key-packages/group-refs.js +79 -0
  142. package/dist/key-packages/index.d.ts +18 -0
  143. package/dist/key-packages/index.js +18 -0
  144. package/dist/key-packages/key-package-ref.d.ts +16 -0
  145. package/dist/key-packages/key-package-ref.js +21 -0
  146. package/dist/key-packages/observation-stream.d.ts +4 -0
  147. package/dist/key-packages/observation-stream.js +120 -0
  148. package/dist/key-packages/offer-rumor.d.ts +26 -0
  149. package/dist/key-packages/offer-rumor.js +69 -0
  150. package/dist/key-packages/publisher.d.ts +174 -0
  151. package/dist/key-packages/publisher.js +1247 -0
  152. package/dist/key-packages/select-key-package.d.ts +24 -0
  153. package/dist/key-packages/select-key-package.js +90 -0
  154. package/dist/key-packages/slot-manager.d.ts +167 -0
  155. package/dist/key-packages/slot-manager.js +327 -0
  156. package/dist/key-packages/validate-key-package-event.d.ts +3 -0
  157. package/dist/key-packages/validate-key-package-event.js +49 -0
  158. package/dist/media/cache.d.ts +14 -0
  159. package/dist/media/cache.js +10 -0
  160. package/dist/media/index.d.ts +52 -0
  161. package/dist/media/index.js +71 -0
  162. package/dist/mls.d.ts +15 -0
  163. package/dist/mls.js +15 -0
  164. package/dist/shared/account-pubkey.d.ts +4 -0
  165. package/dist/shared/account-pubkey.js +10 -0
  166. package/dist/shared/errors.d.ts +21 -0
  167. package/dist/shared/errors.js +85 -0
  168. package/dist/shared/hex.d.ts +4 -0
  169. package/dist/shared/hex.js +13 -0
  170. package/dist/shared/index.d.ts +14 -0
  171. package/dist/shared/index.js +14 -0
  172. package/dist/shared/kinds.d.ts +8 -0
  173. package/dist/shared/kinds.js +28 -0
  174. package/dist/shared/publish-classification.d.ts +26 -0
  175. package/dist/shared/publish-classification.js +31 -0
  176. package/dist/storage/envelope.d.ts +39 -0
  177. package/dist/storage/envelope.js +201 -0
  178. package/dist/storage/index.d.ts +227 -0
  179. package/dist/storage/index.js +459 -0
  180. package/dist/storage/indexeddb/idb-types.d.ts +68 -0
  181. package/dist/storage/indexeddb/idb-types.js +1 -0
  182. package/dist/storage/indexeddb/index.d.ts +17 -0
  183. package/dist/storage/indexeddb/index.js +141 -0
  184. package/dist/storage/lease.d.ts +41 -0
  185. package/dist/storage/lease.js +117 -0
  186. package/dist/storage/memory/deterministic-signer.d.ts +27 -0
  187. package/dist/storage/memory/deterministic-signer.js +65 -0
  188. package/dist/storage/memory/index.d.ts +32 -0
  189. package/dist/storage/memory/index.js +87 -0
  190. package/dist/storage/memory/lock-manager.d.ts +8 -0
  191. package/dist/storage/memory/lock-manager.js +71 -0
  192. package/package.json +66 -3
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Account identity-proof enforcement (ADR-012; AC-PROOF-1..4) — the early,
3
+ * narrow slice of the `account` module that S3 builds ahead of S8/S9.
4
+ *
5
+ * `marmot-engine` checks a proof only when one is present
6
+ * (`engine/admin-policy.ts`), never calls `verifyAllLeafAccountIdentityProofs`
7
+ * and never compares an Update's successor credential with its predecessor
8
+ * (`core/auth-service.ts` `validateSuccessorCredential`). ADR-012 assigns
9
+ * all three checks to this layer:
10
+ *
11
+ * 1. presence — every leaf of every group state carries a valid
12
+ * `marmot.account-identity-proof.v2` LeafNode extension (the engine's
13
+ * `ACCOUNT_IDENTITY_PROOF_EXTENSION_TYPE`; the spec's "0x8009" is the
14
+ * capability code that advertises it);
15
+ * 2. projected-set gate — inside the `adminPolicyCallback` seam, a commit is
16
+ * rejected when any leaf of `ratchetTree ∪ Add ∪ Update − Removed` lacks
17
+ * a valid proof;
18
+ * 3. continuity — an Update (proposal or commit path) whose new credential
19
+ * names a different Nostr account than the leaf's previous credential is
20
+ * rejected.
21
+ *
22
+ * {@link ProofEnforcementResult} is the seam S8 (AC-DEV-3) and S9
23
+ * (commit-time re-check) consume; neither re-implements these checks.
24
+ */
25
+ import { type ClientState, type LeafNode, type ProposalWithSender, type RatchetTree } from '@941design/marmot-engine/mls';
26
+ import { createAdminCommitPolicyCallback } from '@941design/marmot-engine/engine';
27
+ /** Outcome of one leaf's proof or continuity check. `reason` is present iff `valid` is false. */
28
+ export interface ProofEnforcementResult {
29
+ readonly valid: boolean;
30
+ readonly leafIndex: number;
31
+ readonly reason?: string;
32
+ }
33
+ /** A leaf of a projected (post-commit) leaf set; `previous` is the leaf it replaces when it is an Update. */
34
+ export interface ProjectedLeaf {
35
+ readonly leafIndex: number;
36
+ readonly leaf: LeafNode;
37
+ readonly previous?: LeafNode;
38
+ }
39
+ /** The engine's `adminPolicyCallback` factory type. */
40
+ export type AdminPolicyFactory = typeof createAdminCommitPolicyCallback;
41
+ /**
42
+ * Presence and validity of the account identity proof on one leaf.
43
+ * `valid: false` when the extension is absent, malformed, or does not verify
44
+ * (engine `verifyLeafAccountIdentityProof`).
45
+ */
46
+ export declare function checkLeafProof(leaf: LeafNode, leafIndex: number, ciphersuite: number): ProofEnforcementResult;
47
+ /** AC-PROOF-3: `next`'s credential must name the same Nostr account as `previous`'s. */
48
+ export declare function checkIdentityContinuity(previous: LeafNode, next: LeafNode, leafIndex: number): ProofEnforcementResult;
49
+ /**
50
+ * The leaf set a commit would produce: every leaf of `ratchetTree`, with each
51
+ * Update's sender leaf replaced (carrying `previous`), each Remove / SelfRemove
52
+ * target dropped, and each Add leaf placed at the leaf index RFC 9420 §12.1.1
53
+ * assigns it (leftmost blank leaf after removals, else appended).
54
+ */
55
+ export declare function projectCommitLeaves(ratchetTree: RatchetTree, proposals: readonly ProposalWithSender[]): ProjectedLeaf[];
56
+ /**
57
+ * Wraps the engine's `adminPolicyCallback` factory. The returned callback
58
+ * rejects (returns `"reject"`) a commit whose projected leaf set contains a
59
+ * leaf without a valid proof or an identity-changing Update, and a standalone
60
+ * Update proposal that changes its sender's account identity or lacks a valid
61
+ * proof; every other decision is delegated to `inner` unchanged.
62
+ */
63
+ export declare function createProofEnforcingAdminPolicy(inner?: AdminPolicyFactory): AdminPolicyFactory;
64
+ /** Failures only: every member leaf of `state` must carry a valid proof. Empty array = pass. */
65
+ export declare function enforceStateProofs(state: ClientState): ProofEnforcementResult[];
66
+ /**
67
+ * Failures only: {@link enforceStateProofs} over `next`, plus continuity for
68
+ * every leaf index occupied in both `parent` and `next` (covers a commit's
69
+ * UpdatePath leaf, which the admin callback never sees). Empty array = pass.
70
+ */
71
+ export declare function enforceStateTransition(parent: ClientState, next: ClientState): ProofEnforcementResult[];
72
+ /**
73
+ * Failures only, for proposals `next` staged that `parent` did not hold.
74
+ * The engine consults `adminPolicyCallback` for commits but accepts every
75
+ * standalone proposal envelope unconditionally (`engine/ingest.ts`), so the
76
+ * receive path re-checks each newly staged Update (proof + continuity against
77
+ * its sender's current leaf) and Add (proof) here. Empty array = pass.
78
+ */
79
+ export declare function enforceStagedProposals(parent: ClientState, next: ClientState): ProofEnforcementResult[];
@@ -0,0 +1,264 @@
1
+ /**
2
+ * Account identity-proof enforcement (ADR-012; AC-PROOF-1..4) — the early,
3
+ * narrow slice of the `account` module that S3 builds ahead of S8/S9.
4
+ *
5
+ * `marmot-engine` checks a proof only when one is present
6
+ * (`engine/admin-policy.ts`), never calls `verifyAllLeafAccountIdentityProofs`
7
+ * and never compares an Update's successor credential with its predecessor
8
+ * (`core/auth-service.ts` `validateSuccessorCredential`). ADR-012 assigns
9
+ * all three checks to this layer:
10
+ *
11
+ * 1. presence — every leaf of every group state carries a valid
12
+ * `marmot.account-identity-proof.v2` LeafNode extension (the engine's
13
+ * `ACCOUNT_IDENTITY_PROOF_EXTENSION_TYPE`; the spec's "0x8009" is the
14
+ * capability code that advertises it);
15
+ * 2. projected-set gate — inside the `adminPolicyCallback` seam, a commit is
16
+ * rejected when any leaf of `ratchetTree ∪ Add ∪ Update − Removed` lacks
17
+ * a valid proof;
18
+ * 3. continuity — an Update (proposal or commit path) whose new credential
19
+ * names a different Nostr account than the leaf's previous credential is
20
+ * rejected.
21
+ *
22
+ * {@link ProofEnforcementResult} is the seam S8 (AC-DEV-3) and S9
23
+ * (commit-time re-check) consume; neither re-implements these checks.
24
+ */
25
+ import { defaultProposalTypes, leafNodeSources, nodeTypes, selfRemoveProposalType, } from '@941design/marmot-engine/mls';
26
+ import { createAdminCommitPolicyCallback } from '@941design/marmot-engine/engine';
27
+ import { getCredentialPubkey, verifyLeafAccountIdentityProof } from '@941design/marmot-engine/core';
28
+ /** The number of leaf slots (occupied or blank) a `RatchetTree` node array carries. */
29
+ function leafCountOf(ratchetTree) {
30
+ return Math.ceil(ratchetTree.length / 2);
31
+ }
32
+ /** The occupied leaf at `leafIndex`, or `undefined` if that slot is blank or out of range. */
33
+ function leafAt(ratchetTree, leafIndex) {
34
+ const node = ratchetTree[2 * leafIndex];
35
+ return node?.nodeType === nodeTypes.leaf ? node.leaf : undefined;
36
+ }
37
+ /**
38
+ * Presence and validity of the account identity proof on one leaf.
39
+ * `valid: false` when the extension is absent, malformed, or does not verify
40
+ * (engine `verifyLeafAccountIdentityProof`).
41
+ */
42
+ export function checkLeafProof(leaf, leafIndex, ciphersuite) {
43
+ try {
44
+ verifyLeafAccountIdentityProof(leaf, ciphersuite);
45
+ return { valid: true, leafIndex };
46
+ }
47
+ catch (err) {
48
+ // `verifyLeafAccountIdentityProof` itself names the "missing ... LeafNode
49
+ // extension" case in its thrown message, so no separate presence check
50
+ // is needed here to satisfy the "missing extension" reason requirement.
51
+ return { valid: false, leafIndex, reason: err instanceof Error ? err.message : String(err) };
52
+ }
53
+ }
54
+ /** AC-PROOF-3: `next`'s credential must name the same Nostr account as `previous`'s. */
55
+ export function checkIdentityContinuity(previous, next, leafIndex) {
56
+ let previousPubkey;
57
+ let nextPubkey;
58
+ try {
59
+ previousPubkey = getCredentialPubkey(previous.credential);
60
+ }
61
+ catch (err) {
62
+ return {
63
+ valid: false,
64
+ leafIndex,
65
+ reason: `previous credential is not a valid Marmot account identity: ${err instanceof Error ? err.message : String(err)}`,
66
+ };
67
+ }
68
+ try {
69
+ nextPubkey = getCredentialPubkey(next.credential);
70
+ }
71
+ catch (err) {
72
+ return {
73
+ valid: false,
74
+ leafIndex,
75
+ reason: `next credential is not a valid Marmot account identity: ${err instanceof Error ? err.message : String(err)}`,
76
+ };
77
+ }
78
+ if (previousPubkey !== nextPubkey) {
79
+ return {
80
+ valid: false,
81
+ leafIndex,
82
+ reason: `leaf ${leafIndex} changed account identity from ${previousPubkey} to ${nextPubkey}`,
83
+ };
84
+ }
85
+ return { valid: true, leafIndex };
86
+ }
87
+ /**
88
+ * The leaf set a commit would produce: every leaf of `ratchetTree`, with each
89
+ * Update's sender leaf replaced (carrying `previous`), each Remove / SelfRemove
90
+ * target dropped, and each Add leaf placed at the leaf index RFC 9420 §12.1.1
91
+ * assigns it (leftmost blank leaf after removals, else appended).
92
+ */
93
+ export function projectCommitLeaves(ratchetTree, proposals) {
94
+ const leafCount = leafCountOf(ratchetTree);
95
+ // The base occupied-leaf map — Updates need the ORIGINAL leaf (not one
96
+ // already touched by another proposal in this same batch) as `previous`,
97
+ // since RFC 9420 evaluates a commit's proposals against one common base
98
+ // state, not sequentially against each other.
99
+ const base = new Map();
100
+ for (let i = 0; i < leafCount; i++) {
101
+ const leaf = leafAt(ratchetTree, i);
102
+ if (leaf !== undefined)
103
+ base.set(i, leaf);
104
+ }
105
+ const projected = new Map();
106
+ for (const [leafIndex, leaf] of base)
107
+ projected.set(leafIndex, { leafIndex, leaf });
108
+ // Removes / SelfRemoves free their slot before Adds may reuse it.
109
+ for (const { proposal, senderLeafIndex } of proposals) {
110
+ if (proposal.proposalType === defaultProposalTypes.remove && 'remove' in proposal) {
111
+ projected.delete(proposal.remove.removed);
112
+ }
113
+ else if (proposal.proposalType === selfRemoveProposalType) {
114
+ if (senderLeafIndex !== undefined)
115
+ projected.delete(senderLeafIndex);
116
+ }
117
+ }
118
+ // Updates replace their sender's leaf, carrying the base leaf as `previous`.
119
+ for (const { proposal, senderLeafIndex } of proposals) {
120
+ if (proposal.proposalType !== defaultProposalTypes.update || !('update' in proposal))
121
+ continue;
122
+ if (senderLeafIndex === undefined)
123
+ continue;
124
+ const previous = base.get(senderLeafIndex);
125
+ projected.set(senderLeafIndex, previous === undefined
126
+ ? { leafIndex: senderLeafIndex, leaf: proposal.update.leafNode }
127
+ : { leafIndex: senderLeafIndex, leaf: proposal.update.leafNode, previous });
128
+ }
129
+ // Adds fill the leftmost blank slot (freed by a Remove, or already blank),
130
+ // else are appended beyond the current tree width — in proposal order.
131
+ let blankCursor = 0;
132
+ let appendCursor = leafCount;
133
+ for (const { proposal } of proposals) {
134
+ if (proposal.proposalType !== defaultProposalTypes.add || !('add' in proposal))
135
+ continue;
136
+ while (blankCursor < leafCount && projected.has(blankCursor))
137
+ blankCursor++;
138
+ const leafIndex = blankCursor < leafCount ? blankCursor++ : appendCursor++;
139
+ projected.set(leafIndex, { leafIndex, leaf: proposal.add.keyPackage.leafNode });
140
+ }
141
+ return [...projected.values()].sort((a, b) => a.leafIndex - b.leafIndex);
142
+ }
143
+ /**
144
+ * Wraps the engine's `adminPolicyCallback` factory. The returned callback
145
+ * rejects (returns `"reject"`) a commit whose projected leaf set contains a
146
+ * leaf without a valid proof or an identity-changing Update, and a standalone
147
+ * Update proposal that changes its sender's account identity or lacks a valid
148
+ * proof; every other decision is delegated to `inner` unchanged.
149
+ */
150
+ export function createProofEnforcingAdminPolicy(inner) {
151
+ const resolvedInner = inner ?? createAdminCommitPolicyCallback;
152
+ return (args) => {
153
+ const innerCallback = resolvedInner(args);
154
+ return (incoming) => {
155
+ if (incoming.kind === 'commit') {
156
+ const projected = projectCommitLeaves(args.ratchetTree, incoming.proposals);
157
+ for (const { leaf, leafIndex, previous } of projected) {
158
+ if (!checkLeafProof(leaf, leafIndex, args.ciphersuiteId).valid)
159
+ return 'reject';
160
+ if (previous !== undefined && !checkIdentityContinuity(previous, leaf, leafIndex).valid)
161
+ return 'reject';
162
+ }
163
+ return innerCallback(incoming);
164
+ }
165
+ // incoming.kind === 'proposal'
166
+ const { proposal, senderLeafIndex } = incoming.proposal;
167
+ if (proposal.proposalType === defaultProposalTypes.update && 'update' in proposal) {
168
+ if (senderLeafIndex === undefined)
169
+ return 'reject';
170
+ const previous = leafAt(args.ratchetTree, senderLeafIndex);
171
+ if (previous === undefined)
172
+ return 'reject';
173
+ if (!checkLeafProof(proposal.update.leafNode, senderLeafIndex, args.ciphersuiteId).valid)
174
+ return 'reject';
175
+ if (!checkIdentityContinuity(previous, proposal.update.leafNode, senderLeafIndex).valid)
176
+ return 'reject';
177
+ return innerCallback(incoming);
178
+ }
179
+ if (proposal.proposalType === defaultProposalTypes.add && 'add' in proposal) {
180
+ // The Add's leaf has no assigned leaf index yet (it lands wherever
181
+ // the eventual commit's projection places it) — the index carried
182
+ // here is unused beyond this presence/validity check.
183
+ if (!checkLeafProof(proposal.add.keyPackage.leafNode, -1, args.ciphersuiteId).valid)
184
+ return 'reject';
185
+ return innerCallback(incoming);
186
+ }
187
+ return innerCallback(incoming);
188
+ };
189
+ };
190
+ }
191
+ /** Failures only: every member leaf of `state` must carry a valid proof. Empty array = pass. */
192
+ export function enforceStateProofs(state) {
193
+ const ciphersuite = state.groupContext.cipherSuite;
194
+ const leafCount = leafCountOf(state.ratchetTree);
195
+ const failures = [];
196
+ for (let leafIndex = 0; leafIndex < leafCount; leafIndex++) {
197
+ const leaf = leafAt(state.ratchetTree, leafIndex);
198
+ if (leaf === undefined)
199
+ continue;
200
+ const result = checkLeafProof(leaf, leafIndex, ciphersuite);
201
+ if (!result.valid)
202
+ failures.push(result);
203
+ }
204
+ return failures;
205
+ }
206
+ /**
207
+ * Failures only: {@link enforceStateProofs} over `next`, plus continuity for
208
+ * every leaf index occupied in both `parent` and `next` (covers a commit's
209
+ * UpdatePath leaf, which the admin callback never sees). Empty array = pass.
210
+ */
211
+ export function enforceStateTransition(parent, next) {
212
+ const failures = enforceStateProofs(next);
213
+ const leafCount = Math.max(leafCountOf(parent.ratchetTree), leafCountOf(next.ratchetTree));
214
+ for (let leafIndex = 0; leafIndex < leafCount; leafIndex++) {
215
+ const previous = leafAt(parent.ratchetTree, leafIndex);
216
+ const current = leafAt(next.ratchetTree, leafIndex);
217
+ if (previous === undefined || current === undefined)
218
+ continue;
219
+ // A leaf freshly taken from a KeyPackage is an Add into a slot a Remove in
220
+ // the same commit freed — a different member, not an Update of the old one.
221
+ if (current !== previous && current.leafNodeSource === leafNodeSources.key_package)
222
+ continue;
223
+ const continuity = checkIdentityContinuity(previous, current, leafIndex);
224
+ if (!continuity.valid)
225
+ failures.push(continuity);
226
+ }
227
+ return failures;
228
+ }
229
+ /**
230
+ * Failures only, for proposals `next` staged that `parent` did not hold.
231
+ * The engine consults `adminPolicyCallback` for commits but accepts every
232
+ * standalone proposal envelope unconditionally (`engine/ingest.ts`), so the
233
+ * receive path re-checks each newly staged Update (proof + continuity against
234
+ * its sender's current leaf) and Add (proof) here. Empty array = pass.
235
+ */
236
+ export function enforceStagedProposals(parent, next) {
237
+ const ciphersuite = next.groupContext.cipherSuite;
238
+ const failures = [];
239
+ for (const [ref, staged] of Object.entries(next.unappliedProposals)) {
240
+ if (ref in parent.unappliedProposals)
241
+ continue;
242
+ const { proposal, senderLeafIndex } = staged;
243
+ if (proposal.proposalType === defaultProposalTypes.update && 'update' in proposal) {
244
+ const leafIndex = senderLeafIndex ?? -1;
245
+ const previous = senderLeafIndex === undefined ? undefined : leafAt(next.ratchetTree, senderLeafIndex);
246
+ if (previous === undefined) {
247
+ failures.push({ valid: false, leafIndex, reason: 'Update proposal from a sender with no current leaf' });
248
+ continue;
249
+ }
250
+ const proof = checkLeafProof(proposal.update.leafNode, leafIndex, ciphersuite);
251
+ if (!proof.valid)
252
+ failures.push(proof);
253
+ const continuity = checkIdentityContinuity(previous, proposal.update.leafNode, leafIndex);
254
+ if (!continuity.valid)
255
+ failures.push(continuity);
256
+ }
257
+ else if (proposal.proposalType === defaultProposalTypes.add && 'add' in proposal) {
258
+ const proof = checkLeafProof(proposal.add.keyPackage.leafNode, -1, ciphersuite);
259
+ if (!proof.valid)
260
+ failures.push(proof);
261
+ }
262
+ }
263
+ return failures;
264
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Barrel of the `account` module (architecture.md: cross-module access only
3
+ * through each module's `index.ts`). S3 landed the identity-proof slice; S8
4
+ * the same-account seams, enrolment and the device registry; S9 the admin
5
+ * model and teardown.
6
+ */
7
+ export { checkIdentityContinuity, checkLeafProof, createProofEnforcingAdminPolicy, enforceStagedProposals, enforceStateProofs, enforceStateTransition, projectCommitLeaves, type AdminPolicyFactory, type ProjectedLeaf, type ProofEnforcementResult, } from './identity-proof.js';
8
+ export { checkSameAccountLimits, createSameAccountAdminPolicy, createSameAccountAuthorizeCommit, isSameAccountChange, MAX_ADDS_PER_ACCOUNT_PER_COMMIT, MAX_LEAVES_PER_ACCOUNT, sameAccountClientConfig, type SameAccountLimitViolation, } from './same-account-authorization.js';
9
+ export { createDeviceService, supersedeOwnForget, type DeviceForgetGroupOutcome, type DeviceForgetOutcome, type DeviceInfo, type DeviceService, type DeviceTombstone, type OwnLeafLeave, } from './device-registry.js';
10
+ export { createRotationDriver, MAX_KEYPACKAGE_ATTEMPTS, MAX_RECHECK_FAILURES, ROTATION_CONCURRENCY, ROTATION_WAIT_DEADLINE_MS, rotationOutcomeOf, type DeviceKeyRotationOutcome, type DeviceKeyRotationOutcomeStatus, type RotationDriver, type RotationSeams, } from './device-rotation.js';
11
+ export { createDeviceLineage, directedAncestors, loadDeviceLineage, MAX_LINEAGE_DEPTH, recordSuccession, persistSuccessionEdges, viewSuccessionEdges, localAccountOf, readRegistryEdges, ROTATED_ALT_PREFIX, type DeviceLineage, type LineageEdge, type RecordSuccessionInput, type RecordSuccessionResult, } from './device-lineage.js';
12
+ export { decodeEnrolmentRumor, DEFAULT_MAX_GIFT_WRAP_BYTES, DEFAULT_PROMPT_RATE_LIMIT, encodeEnrolmentApprovalRumor, encodeEnrolmentRequestRumor, MAX_GROUP_ATTEMPTS, REOPENED_LEAF_STILL_CANONICAL, type EnrolmentApprovalOutcome, type EnrolmentGroupOutcome, type EnrolmentRequestHandle, type EnrolmentRequestOptions, } from './enrolment.js';
13
+ export { MAX_MAINTENANCE_FAILURES as MAX_DEVICE_MAINTENANCE_FAILURES } from './device-deps.js';
14
+ export { RESTORE_ROTATION_EXTENSION, writeRestoreRotationOwed } from './restore-rotation.js';
15
+ export { accountLeafIndexes, activeAdmins, adminPolicyProposal, createAdminAuthorizeCommit, createAdminDeviationPolicy, isActiveAdmin, isLastActiveAdmin, isLastActiveLeafOfAdmin, validateAdminList, } from './admin.js';
16
+ export { createTeardownService, DEFAULT_LEAVE_TIMEOUT_MS, TEARDOWN_EXTENSION, type LeaveView, type TeardownDeps, type TeardownGroupPort, type TeardownKind, type TeardownOutcome, type TeardownService, } from './teardown.js';
17
+ export type { DeviceGroupPort, DeviceGroupView, DeviceMaintenanceKind, DeviceRotationPorts, DeviceServiceDeps, EnrolmentPrompt, GroupSuccession } from './device-deps.js';
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Barrel of the `account` module (architecture.md: cross-module access only
3
+ * through each module's `index.ts`). S3 landed the identity-proof slice; S8
4
+ * the same-account seams, enrolment and the device registry; S9 the admin
5
+ * model and teardown.
6
+ */
7
+ export { checkIdentityContinuity, checkLeafProof, createProofEnforcingAdminPolicy, enforceStagedProposals, enforceStateProofs, enforceStateTransition, projectCommitLeaves, } from './identity-proof.js';
8
+ export { checkSameAccountLimits, createSameAccountAdminPolicy, createSameAccountAuthorizeCommit, isSameAccountChange, MAX_ADDS_PER_ACCOUNT_PER_COMMIT, MAX_LEAVES_PER_ACCOUNT, sameAccountClientConfig, } from './same-account-authorization.js';
9
+ export { createDeviceService, supersedeOwnForget, } from './device-registry.js';
10
+ export { createRotationDriver, MAX_KEYPACKAGE_ATTEMPTS, MAX_RECHECK_FAILURES, ROTATION_CONCURRENCY, ROTATION_WAIT_DEADLINE_MS, rotationOutcomeOf, } from './device-rotation.js';
11
+ export { createDeviceLineage, directedAncestors, loadDeviceLineage, MAX_LINEAGE_DEPTH, recordSuccession, persistSuccessionEdges, viewSuccessionEdges, localAccountOf, readRegistryEdges, ROTATED_ALT_PREFIX, } from './device-lineage.js';
12
+ export { decodeEnrolmentRumor, DEFAULT_MAX_GIFT_WRAP_BYTES, DEFAULT_PROMPT_RATE_LIMIT, encodeEnrolmentApprovalRumor, encodeEnrolmentRequestRumor, MAX_GROUP_ATTEMPTS, REOPENED_LEAF_STILL_CANONICAL, } from './enrolment.js';
13
+ export { MAX_MAINTENANCE_FAILURES as MAX_DEVICE_MAINTENANCE_FAILURES } from './device-deps.js';
14
+ export { RESTORE_ROTATION_EXTENSION, writeRestoreRotationOwed } from './restore-rotation.js';
15
+ export { accountLeafIndexes, activeAdmins, adminPolicyProposal, createAdminAuthorizeCommit, createAdminDeviationPolicy, isActiveAdmin, isLastActiveAdmin, isLastActiveLeafOfAdmin, validateAdminList, } from './admin.js';
16
+ export { createTeardownService, DEFAULT_LEAVE_TIMEOUT_MS, TEARDOWN_EXTENSION, } from './teardown.js';
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Owner decision 13 (2026-10-29, BACKLOG `restore-rekeys-device-automatically`): a successful `groups.restore` owes a
3
+ * device-key rotation. Most restores happen because the old device is gone (lost, stolen): until the key it held is
4
+ * rotated, a device still holding it keeps reading the group. The owed rotation is one durable marker per restored group
5
+ * (account extension {@link RESTORE_ROTATION_EXTENSION}), written by the restore when it succeeded and drained by the
6
+ * device service's rotation pass (device-rotation.ts `drainRestoreRotations`): a crash between the two only delays it.
7
+ */
8
+ import type { KeyValueView } from '../storage/index.js';
9
+ /** Account extension: `groupId` → {@link RestoreRotationOwed}. */
10
+ export declare const RESTORE_ROTATION_EXTENSION = "marmot.restore-rotation";
11
+ export interface RestoreRotationOwed {
12
+ /** Client-clock ms the restore succeeded. */
13
+ readonly at: number;
14
+ /** Rotation attempts that failed for a counted cause; the marker is given up at `MAX_MAINTENANCE_FAILURES`. */
15
+ readonly failures: number;
16
+ }
17
+ export declare function writeRestoreRotationOwed(view: KeyValueView, groupId: string, at: number): Promise<void>;
18
+ /** Every owed marker; a malformed one reads as fresh (it only costs a rotation check). */
19
+ export declare function readRestoreRotationsOwed(view: KeyValueView): Promise<Map<string, RestoreRotationOwed>>;
20
+ export declare function putRestoreRotationOwed(view: KeyValueView, groupId: string, owed: RestoreRotationOwed): Promise<void>;
21
+ export declare function clearRestoreRotationOwed(view: KeyValueView, groupId: string): Promise<void>;
@@ -0,0 +1,22 @@
1
+ /** Account extension: `groupId` → {@link RestoreRotationOwed}. */
2
+ export const RESTORE_ROTATION_EXTENSION = 'marmot.restore-rotation';
3
+ export async function writeRestoreRotationOwed(view, groupId, at) {
4
+ await view.put(groupId, { at, failures: 0 });
5
+ }
6
+ /** Every owed marker; a malformed one reads as fresh (it only costs a rotation check). */
7
+ export async function readRestoreRotationsOwed(view) {
8
+ const out = new Map();
9
+ for (const groupId of await view.keys()) {
10
+ const raw = (await view.get(groupId));
11
+ const at = typeof raw?.at === 'number' && Number.isFinite(raw.at) ? raw.at : 0;
12
+ const failures = typeof raw?.failures === 'number' && Number.isSafeInteger(raw.failures) && raw.failures >= 0 ? raw.failures : 0;
13
+ out.set(groupId, { at, failures });
14
+ }
15
+ return out;
16
+ }
17
+ export async function putRestoreRotationOwed(view, groupId, owed) {
18
+ await view.put(groupId, { at: owed.at, failures: owed.failures });
19
+ }
20
+ export async function clearRestoreRotationOwed(view, groupId) {
21
+ await view.delete(groupId);
22
+ }
@@ -0,0 +1,86 @@
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 } from '@941design/marmot-engine/core';
30
+ import { type ClientConfig, type ProposalWithSender, type RatchetTree } from '@941design/marmot-engine/mls';
31
+ import { type AdminPolicyFactory } from './identity-proof.js';
32
+ /** ADR-003: at most four same-account Adds in one commit. */
33
+ export declare const MAX_ADDS_PER_ACCOUNT_PER_COMMIT = 4;
34
+ /** ADR-003: at most five leaves per account in a group. */
35
+ export declare const MAX_LEAVES_PER_ACCOUNT = 5;
36
+ /**
37
+ * The ts-mls `ClientConfig` every `marmot` engine and Welcome join uses: the
38
+ * Marmot default with `compareKeyPackageToLeafNode` comparing signature keys
39
+ * only (a device — one signature key — still never holds two leaves of one
40
+ * group; a sibling device of the same account is a new member).
41
+ */
42
+ export declare const sameAccountClientConfig: ClientConfig;
43
+ export type SameAccountLimitViolation = {
44
+ readonly reason: 'too-many-adds';
45
+ readonly account: string;
46
+ readonly adds: number;
47
+ } | {
48
+ readonly reason: 'too-many-leaves';
49
+ readonly account: string;
50
+ readonly leaves: number;
51
+ };
52
+ /**
53
+ * The per-commit and per-group limits over the commit's exact proposal union
54
+ * against `ratchetTree` (the parent epoch's tree): `undefined` when both
55
+ * hold. Adds are counted by the credential they name; leaves over the
56
+ * projected (post-commit) leaf set, for the accounts the commit adds to.
57
+ */
58
+ export declare function checkSameAccountLimits(ratchetTree: RatchetTree, proposals: readonly ProposalWithSender[]): SameAccountLimitViolation | undefined;
59
+ /**
60
+ * Whether one proposal is a same-account change of `actorAccount`: an Add of
61
+ * a KeyPackage naming that account, or a Remove of ANOTHER leaf of it (a
62
+ * leaf never removes itself — that is SelfRemove, judged by the admin rule).
63
+ */
64
+ export declare function isSameAccountChange(ratchetTree: RatchetTree, actorAccount: string, actorLeafIndex: number, entry: ProposalWithSender): boolean;
65
+ /**
66
+ * The engine's `authorizeCommit` seam (send path) over the tree `ratchetTree()`
67
+ * returns (the engine's current state — the commit's parent): the limits
68
+ * first, then the vendored rule; a non-admin's union is authorised when what
69
+ * remains after taking out its same-account changes is something the
70
+ * vendored rule lets a non-admin commit (nothing, its own Update, or
71
+ * SelfRemoves). The typed decision carries only the vendored reason; the
72
+ * client checks the limits itself before it builds a commit, so a refusal
73
+ * here is a backstop.
74
+ */
75
+ export declare function createSameAccountAuthorizeCommit(ratchetTree: () => RatchetTree): typeof decideCommitAuthorization;
76
+ /**
77
+ * The receive-path counterpart, as an `adminPolicyCallback` factory wrapping
78
+ * `inner` (default: the vendored `createAdminCommitPolicyCallback`): a commit
79
+ * breaking a limit is rejected, whoever sent it; a non-admin committer's
80
+ * same-account changes are taken out of the proposal list `inner` judges, so
81
+ * `inner` decides only the rest (an empty rest is accepted by it). Proposals
82
+ * (not commits) go to `inner` unchanged. Wrapped in turn by S3's
83
+ * `createProofEnforcingAdminPolicy`, which checks every projected leaf's
84
+ * proof first (AC-DEV-3).
85
+ */
86
+ export declare function createSameAccountAdminPolicy(inner?: AdminPolicyFactory): AdminPolicyFactory;