@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,1232 @@
1
+ import { unwrap } from '@941design/nostr-events/gift-wrap';
2
+ import { probeSigner } from '@941design/nostr-events/signer';
3
+ import { withSignerBudget } from '@941design/nostr-events/signer/budget';
4
+ import { HISTORY_BACKEND_TIMEOUT_MS } from './group-history.js';
5
+ import { DEFAULT_REMOVAL_SETTLE_MS } from './group-removal.js';
6
+ import { createDeviceService, createTeardownService, DEFAULT_LEAVE_TIMEOUT_MS, DEFAULT_MAX_GIFT_WRAP_BYTES, DEFAULT_PROMPT_RATE_LIMIT, enforceStateProofs, supersedeOwnForget, } from '../account/index.js';
7
+ import { createInboxHandlerRegistry, createInboxSubscription, createRumorDemux, DEFAULT_SEEN_SET_CAP, } from '../inbox/index.js';
8
+ import { createInvitationsService, createWelcomeService, declineCandidatePage, declineScanOptions, DEFAULT_INVITE_RETENTION_MS, DEFAULT_PROPOSAL_DEFERRAL_TIMEOUT_MS, handleKeyPackageOffer, listKeyPackageOffers, resolveInboxRelays, sendKeyPackageOffer, validateOfferOptions, } from '../invitations/index.js';
9
+ import { createKeyPackage, countKeyPackages, fetchKeyPackageEvents, resolveWriteRelays, forgetKeyPackage, keyPackageStatus, recordKeyPackageGroupRef, listKeyPackages, observeKeyPackages, purgeAllExpiredSuperseded, resumePendingIntents, probeParkedUnconfirmed, createParkedProbeState, rotateKeyPackage, retireKeyPackagesSignedWith, DEFAULT_CIPHERSUITE_NAME, } from '../key-packages/index.js';
10
+ import { defaultCryptoProvider, getCiphersuiteImpl } from '@941design/marmot-engine/mls';
11
+ import { isMarmotError, MarmotError, RUMOR_KINDS } from '../shared/index.js';
12
+ import { createBeforeCreateGroupGates } from './before-create-group.js';
13
+ import { createBeforePublishRegistry } from './before-publish-hooks.js';
14
+ import { createGroupRegistry } from './group-runtime.js';
15
+ import { sendInboxRumor } from './inbox-send.js';
16
+ import { GROUP_INDEX_EXTENSION } from './group-records.js';
17
+ import { fetchHistoryPages } from './history-pages.js';
18
+ import { createLifecycleEvents } from './lifecycle-events.js';
19
+ import { sameAccountClientConfig } from './client-config.js';
20
+ import { permissions } from './permissions.js';
21
+ import { ACCOUNT_SCOPE, createReentrancyGuard, DEVICE_SCOPE, GROUP_CONSUMER_SURFACES } from './reentrancy-guard.js';
22
+ import { readInvitationOutcome, RECOVERY_READ_INBOX_SURFACES } from './invitation-outcomes.js';
23
+ import { readCleanupDisposition } from './admission-cleanup.js';
24
+ // `satisfies Record<...>` (rather than a `Set` literal typed only as
25
+ // `Set<MarmotClientEventName>`) makes a member added to or removed from
26
+ // `MarmotClientEvents` without a matching update here a compile error,
27
+ // instead of a silent drift between the event type and `on()`'s runtime
28
+ // name check.
29
+ const EVENT_NAME_KEYS = {
30
+ enrolmentApproved: true,
31
+ deviceForgotten: true,
32
+ groupCreated: true,
33
+ groupRemoved: true,
34
+ deviceKeyRotated: true,
35
+ deviceKeyRotationSettled: true,
36
+ enrolmentRequested: true,
37
+ keyPackageOffered: true,
38
+ authFailed: true,
39
+ transportConnected: true,
40
+ confirmBlocked: true,
41
+ beforePublishSkipped: true,
42
+ relaySilent: true,
43
+ historyGap: true,
44
+ storeIncompatible: true,
45
+ intentFailed: true,
46
+ groupStateFailed: true,
47
+ welcomeFailed: true,
48
+ welcomeRestored: true,
49
+ welcomeReconcileFailed: true,
50
+ welcomeDeclined: true,
51
+ declineCandidate: true,
52
+ cleanupDisposition: true,
53
+ inboxDisposition: true,
54
+ handlerSlow: true,
55
+ groupJoined: true,
56
+ groupBranchSwitched: true,
57
+ proposalExpired: true,
58
+ maintenanceFailed: true,
59
+ };
60
+ const EVENT_NAMES = new Set(Object.keys(EVENT_NAME_KEYS));
61
+ // Maps a client handle to its context without putting internals on the
62
+ // public object. Holds no shared mutable state (INV-NO-SINGLETONS).
63
+ const contexts = new WeakMap();
64
+ /** A client's group registry — for tests of registry-internal answers (`hasGroup`); not re-exported. */
65
+ const registries = new WeakMap();
66
+ /** Internal accessor for tests; not re-exported. */
67
+ export function getGroupRegistry(client) {
68
+ const registry = registries.get(client);
69
+ if (registry === undefined)
70
+ throw new MarmotError('invalid-options', 'not a client created by createMarmotClient');
71
+ return registry;
72
+ }
73
+ /** Internal accessor for other client-module files and tests; not re-exported. */
74
+ export function getClientContext(client) {
75
+ const ctx = contexts.get(client);
76
+ if (ctx === undefined)
77
+ throw new MarmotError('invalid-options', 'not a client created by createMarmotClient');
78
+ return ctx;
79
+ }
80
+ const DEFAULT_HISTORY_SILENCE_THRESHOLD = 3;
81
+ const DEFAULT_GRACE_WINDOW_MS = 24 * 60 * 60 * 1000;
82
+ const DEFAULT_HISTORY_TIMEOUT_MS = 10_000;
83
+ const DEFAULT_MAX_PUBLISH_ATTEMPTS = 20;
84
+ /** AC-BAR-2: default `beforePublishTimeoutMs`. */
85
+ const DEFAULT_BEFORE_PUBLISH_TIMEOUT_MS = 10_000;
86
+ /** inbox-handler-time-budget: default `inboxHandlerBudgetMs`. */
87
+ const DEFAULT_INBOX_HANDLER_BUDGET_MS = 30_000;
88
+ /** S5 (AC-RACE-2): default `selfRemoveElectionWaitMs` — well under `DEFAULT_LEAVE_TIMEOUT_MS` (60 s). */
89
+ const DEFAULT_SELF_REMOVE_ELECTION_WAIT_MS = 5000;
90
+ /**
91
+ * S8 (AC-RATCH-1): `ratchetSkipMargin` default and bounds. The ceiling is half of ts-mls's receiver window
92
+ * (`KeyRetentionConfig.maximumForwardRatchetSteps`, 200 at the pinned ts-mls; the engine refuses any single skip
93
+ * beyond it), so one skip plus fewer than a margin of messages a member did not receive stays inside its window.
94
+ */
95
+ const DEFAULT_RATCHET_SKIP_MARGIN = 64;
96
+ const MIN_RATCHET_SKIP_MARGIN = 32;
97
+ const MAX_RATCHET_SKIP_MARGIN = 100;
98
+ // The ceiling `requestWithDeadline` itself enforces (32-bit setTimeout delay); also `leaveTimeoutMs`'s (a timer).
99
+ const MAX_HISTORY_TIMEOUT_MS = 2_147_483_647;
100
+ const DEFAULT_TIMERS = Object.freeze({
101
+ set: (callback, ms) => setTimeout(callback, ms),
102
+ clear: (handle) => clearTimeout(handle),
103
+ });
104
+ /** How many `timers.clear` failures a client keeps for dispose() to report; later ones are dropped. */
105
+ const MAX_RECORDED_CLEAR_ERRORS = 64;
106
+ /**
107
+ * The consumer's timers as every service sees them (`ctx.timers`): `set` passes through; a `clear` that throws is
108
+ * recorded in `clearErrors` and returns, so no service's teardown loop is cut short by it. `dispose()` reports the
109
+ * recorded errors in its AggregateError (BACKLOG dispose-inner-timer-clear-isolation). A clear that throws after
110
+ * `dispose()` returned (a released sleeper's continuation) is recorded too, but nothing reports it any more.
111
+ */
112
+ function recordingTimers(timers, clearErrors) {
113
+ // Bounded: a long-lived client whose clear keeps throwing must not grow the record without limit.
114
+ return Object.freeze({
115
+ set: (callback, ms) => timers.set(callback, ms),
116
+ clear: (handle) => {
117
+ try {
118
+ timers.clear(handle);
119
+ }
120
+ catch (error) {
121
+ if (clearErrors.length < MAX_RECORDED_CLEAR_ERRORS)
122
+ clearErrors.push(error);
123
+ }
124
+ },
125
+ });
126
+ }
127
+ function invalid(message, cause) {
128
+ return new MarmotError('invalid-options', `createMarmotClient: ${message}`, cause === undefined ? undefined : { cause });
129
+ }
130
+ /**
131
+ * Error helper for the lazy `stores.groupFactory` path (`validateGroupStore`,
132
+ * and `forwardIncompatible`'s per-group subscribe): both run on every call,
133
+ * long after `createMarmotClient()` has already returned, so — unlike
134
+ * `invalid()` — their errors must not claim to come from `createMarmotClient:`.
135
+ * The message's own `stores.groupFactory(...)` context is prefix enough.
136
+ */
137
+ function storesLazyError(message, cause) {
138
+ return new MarmotError('invalid-options', message, cause === undefined ? undefined : { cause });
139
+ }
140
+ // The numeric fields of `nostr-events`' BudgetPolicy. `normalizePolicy`
141
+ // there validates them with relational operators (`timeoutMs > 0`, `leaseMs
142
+ // > timeoutMs`, ...), which coerce a string operand: a same-type pair
143
+ // compares lexicographically, so e.g. `leaseMs: '20', timeoutMs: '100'`
144
+ // passes its `leaseMs > timeoutMs` check ('20' > '100' lexicographically,
145
+ // though 20 < 100) and the lease expires before its own timeout —
146
+ // concurrency: 1 then lets two calls through the slot at once. Rejecting
147
+ // any non-number here, before the policy ever reaches `withSignerBudget`,
148
+ // closes that gap on this side of the boundary (the nostr-events-side
149
+ // coercion is out of scope for this package).
150
+ // Exported for the create-client test's own field-driven checks (it.each /
151
+ // fc.constantFrom over the same list), not part of the package's public API.
152
+ export const BUDGET_NUMERIC_FIELDS = ['concurrency', 'minSpacingMs', 'timeoutMs', 'leaseMs'];
153
+ const budgetNumericFieldsComplete = true;
154
+ void budgetNumericFieldsComplete;
155
+ function validateBudgetNumericFields(budget) {
156
+ for (const field of BUDGET_NUMERIC_FIELDS) {
157
+ const value = budget[field];
158
+ if (value === undefined)
159
+ continue;
160
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
161
+ throw new MarmotError('invalid-options', `createMarmotClient: budget.${field} must be a finite number (got ${typeof value}: ${JSON.stringify(value)})`);
162
+ }
163
+ }
164
+ }
165
+ function isObject(value) {
166
+ return typeof value === 'object' && value !== null;
167
+ }
168
+ function isFunction(value) {
169
+ return typeof value === 'function';
170
+ }
171
+ /** An object whose `members` are all functions (a consumer seam's shape check). */
172
+ function hasMethods(value, members) {
173
+ return isObject(value) && members.every((m) => isFunction(value[m]));
174
+ }
175
+ function validateSigner(signer) {
176
+ // `getPublicKey`/`signEvent` have no shared structural probe in
177
+ // nostr-events, so those two stay a direct member check here; `nip44` is
178
+ // exactly what `probeSigner` (nostr-events/signer) exists to check — a
179
+ // synchronous shape probe with no signer/socket call — so this defers to
180
+ // it instead of re-implementing the same nip44.encrypt/decrypt check.
181
+ if (!isObject(signer) || !isFunction(signer.getPublicKey) || !isFunction(signer.signEvent) || !probeSigner(signer).nip44) {
182
+ throw invalid('signer must implement getPublicKey, signEvent and nip44.encrypt/decrypt');
183
+ }
184
+ }
185
+ function narrowTransport(transport) {
186
+ // Not `toTransportContract` (nostr-events/transport/contract): it assumes an already-valid `NostrNetworkInterface` and does no runtime validation of untrusted `unknown` input.
187
+ if (!isObject(transport) ||
188
+ !isFunction(transport.publish) ||
189
+ !isFunction(transport.requestWithDeadline) ||
190
+ !isFunction(transport.subscription)) {
191
+ throw invalid('transport must implement TransportContract (publish, requestWithDeadline, subscription)');
192
+ }
193
+ const t = transport;
194
+ // Only the three contract members are reachable from inside the client,
195
+ // whatever else the consumer's object carries (AC-API-4).
196
+ return Object.freeze({
197
+ publish: (relays, event, opts) => t.publish(relays, event, opts),
198
+ requestWithDeadline: (relays, filters, opts) => t.requestWithDeadline(relays, filters, opts),
199
+ subscription: (relays, filters) => t.subscription(relays, filters),
200
+ });
201
+ }
202
+ const STORE_SCOPE_METHODS = ['artifact', 'extension', 'transaction', 'onIncompatible'];
203
+ const ACCOUNT_STORE_METHODS = [...STORE_SCOPE_METHODS, 'wipe', 'wipeMarker'];
204
+ const GROUP_STORE_METHODS = [...STORE_SCOPE_METHODS, 'clear'];
205
+ function missingMembers(value, idKey, methods) {
206
+ const missing = methods.filter((m) => !isFunction(value[m]));
207
+ if (typeof value[idKey] !== 'string')
208
+ missing.unshift(idKey);
209
+ return missing;
210
+ }
211
+ function validateStores(stores) {
212
+ if (!isObject(stores) || !isObject(stores.account) || !isFunction(stores.groupFactory)) {
213
+ throw invalid('stores must be { account: AccountStore, groupFactory(groupId): GroupStore }');
214
+ }
215
+ const missing = missingMembers(stores.account, 'account', ACCOUNT_STORE_METHODS);
216
+ if (missing.length > 0)
217
+ throw invalid(`stores.account is not an AccountStore (missing ${missing.join(', ')})`);
218
+ return stores;
219
+ }
220
+ /** A `groupFactory` result is checked when it is yielded (the client calls the factory lazily). */
221
+ function validateGroupStore(store, groupId) {
222
+ const missing = isObject(store) ? missingMembers(store, 'groupId', GROUP_STORE_METHODS) : ['groupId', ...GROUP_STORE_METHODS];
223
+ if (missing.length > 0) {
224
+ throw storesLazyError(`stores.groupFactory(${JSON.stringify(groupId)}) did not return a GroupStore (missing ${missing.join(', ')})`);
225
+ }
226
+ return store;
227
+ }
228
+ function validateRelays(relays) {
229
+ if (!isObject(relays) || !Array.isArray(relays.defaults) || !relays.defaults.every((r) => typeof r === 'string')) {
230
+ throw invalid('relays.defaults must be an array of relay URLs');
231
+ }
232
+ if (relays.mode !== 'discover' && relays.mode !== 'fixed') {
233
+ throw invalid("relays.mode must be 'discover' or 'fixed'");
234
+ }
235
+ if (relays.mode === 'fixed' && relays.defaults.length === 0) {
236
+ throw invalid("relays.mode 'fixed' needs at least one relay in relays.defaults");
237
+ }
238
+ return Object.freeze({ defaults: Object.freeze([...relays.defaults]), mode: relays.mode });
239
+ }
240
+ function resolveClientOptions(raw) {
241
+ if (raw === undefined) {
242
+ return {
243
+ clock: { now: () => Date.now() },
244
+ historySilenceThreshold: DEFAULT_HISTORY_SILENCE_THRESHOLD,
245
+ graceWindowMs: DEFAULT_GRACE_WINDOW_MS,
246
+ timers: DEFAULT_TIMERS,
247
+ historyTimeoutMs: DEFAULT_HISTORY_TIMEOUT_MS,
248
+ maxPublishAttempts: DEFAULT_MAX_PUBLISH_ATTEMPTS,
249
+ beforePublishTimeoutMs: DEFAULT_BEFORE_PUBLISH_TIMEOUT_MS,
250
+ seenSetCap: DEFAULT_SEEN_SET_CAP,
251
+ enrolmentPromptRateLimit: DEFAULT_PROMPT_RATE_LIMIT,
252
+ maxGiftWrapBytes: DEFAULT_MAX_GIFT_WRAP_BYTES,
253
+ leaveTimeoutMs: DEFAULT_LEAVE_TIMEOUT_MS,
254
+ proposalDeferralTimeoutMs: DEFAULT_PROPOSAL_DEFERRAL_TIMEOUT_MS,
255
+ removalSettleMs: DEFAULT_REMOVAL_SETTLE_MS,
256
+ selfRemoveElectionWaitMs: DEFAULT_SELF_REMOVE_ELECTION_WAIT_MS,
257
+ inviteRetentionMs: DEFAULT_INVITE_RETENTION_MS,
258
+ inboxHandlerBudgetMs: DEFAULT_INBOX_HANDLER_BUDGET_MS,
259
+ ratchetSkipMargin: DEFAULT_RATCHET_SKIP_MARGIN,
260
+ };
261
+ }
262
+ if (!isObject(raw))
263
+ throw invalid('options must be an object');
264
+ const clock = raw.clock;
265
+ if (clock !== undefined && (!isObject(clock) || !isFunction(clock.now))) {
266
+ throw invalid('options.clock must implement now()');
267
+ }
268
+ const threshold = raw.historySilenceThreshold ?? DEFAULT_HISTORY_SILENCE_THRESHOLD;
269
+ if (typeof threshold !== 'number' || !Number.isInteger(threshold) || threshold < 1) {
270
+ throw invalid('options.historySilenceThreshold must be a positive integer');
271
+ }
272
+ const grace = raw.graceWindowMs ?? DEFAULT_GRACE_WINDOW_MS;
273
+ if (typeof grace !== 'number' || !Number.isFinite(grace) || grace < 0) {
274
+ throw invalid('options.graceWindowMs must be a finite, non-negative number');
275
+ }
276
+ const timers = raw.timers;
277
+ if (timers !== undefined && (!isObject(timers) || !isFunction(timers.set) || !isFunction(timers.clear))) {
278
+ throw invalid('options.timers must implement set(callback, ms) and clear(handle)');
279
+ }
280
+ const historyTimeoutMs = raw.historyTimeoutMs ?? DEFAULT_HISTORY_TIMEOUT_MS;
281
+ if (typeof historyTimeoutMs !== 'number' || !(historyTimeoutMs > 0) || !(historyTimeoutMs <= MAX_HISTORY_TIMEOUT_MS)) {
282
+ throw invalid(`options.historyTimeoutMs must be a number in (0, ${MAX_HISTORY_TIMEOUT_MS}]`);
283
+ }
284
+ const maxPublishAttempts = raw.maxPublishAttempts ?? DEFAULT_MAX_PUBLISH_ATTEMPTS;
285
+ if (typeof maxPublishAttempts !== 'number' || !Number.isInteger(maxPublishAttempts) || maxPublishAttempts < 1) {
286
+ throw invalid('options.maxPublishAttempts must be a positive integer');
287
+ }
288
+ const beforePublishTimeoutMs = raw.beforePublishTimeoutMs ?? DEFAULT_BEFORE_PUBLISH_TIMEOUT_MS;
289
+ if (typeof beforePublishTimeoutMs !== 'number' || !Number.isInteger(beforePublishTimeoutMs) || beforePublishTimeoutMs < 1) {
290
+ throw invalid('options.beforePublishTimeoutMs must be an integer >= 1');
291
+ }
292
+ const seenSetCap = raw.seenSetCap ?? DEFAULT_SEEN_SET_CAP;
293
+ if (typeof seenSetCap !== 'number' || !Number.isInteger(seenSetCap) || seenSetCap < 1) {
294
+ throw invalid('options.seenSetCap must be a positive integer');
295
+ }
296
+ const enrolmentPromptRateLimit = raw.enrolmentPromptRateLimit ?? DEFAULT_PROMPT_RATE_LIMIT;
297
+ if (typeof enrolmentPromptRateLimit !== 'number' || !Number.isInteger(enrolmentPromptRateLimit) || enrolmentPromptRateLimit < 1) {
298
+ throw invalid('options.enrolmentPromptRateLimit must be a positive integer');
299
+ }
300
+ const maxGiftWrapBytes = raw.maxGiftWrapBytes ?? DEFAULT_MAX_GIFT_WRAP_BYTES;
301
+ if (typeof maxGiftWrapBytes !== 'number' || !Number.isSafeInteger(maxGiftWrapBytes) || maxGiftWrapBytes < 1) {
302
+ throw invalid('options.maxGiftWrapBytes must be a positive safe integer');
303
+ }
304
+ const leaveTimeoutMs = raw.leaveTimeoutMs ?? DEFAULT_LEAVE_TIMEOUT_MS;
305
+ if (typeof leaveTimeoutMs !== 'number' || !(leaveTimeoutMs > 0) || !(leaveTimeoutMs <= MAX_HISTORY_TIMEOUT_MS)) {
306
+ throw invalid(`options.leaveTimeoutMs must be a number in (0, ${MAX_HISTORY_TIMEOUT_MS}]`);
307
+ }
308
+ const proposalDeferralTimeoutMs = raw.proposalDeferralTimeoutMs ?? DEFAULT_PROPOSAL_DEFERRAL_TIMEOUT_MS;
309
+ if (typeof proposalDeferralTimeoutMs !== 'number' || Number.isNaN(proposalDeferralTimeoutMs) || proposalDeferralTimeoutMs < 0) {
310
+ throw invalid('options.proposalDeferralTimeoutMs must be a non-negative number (0 or Infinity = never)');
311
+ }
312
+ const removalSettleMs = raw.removalSettleMs ?? DEFAULT_REMOVAL_SETTLE_MS;
313
+ if (typeof removalSettleMs !== 'number' || !Number.isInteger(removalSettleMs) || removalSettleMs < 0) {
314
+ throw invalid('options.removalSettleMs must be a finite integer >= 0 (0 = settle at the removal)');
315
+ }
316
+ const selfRemoveElectionWaitMs = raw.selfRemoveElectionWaitMs ?? DEFAULT_SELF_REMOVE_ELECTION_WAIT_MS;
317
+ if (typeof selfRemoveElectionWaitMs !== 'number' || !Number.isSafeInteger(selfRemoveElectionWaitMs) || selfRemoveElectionWaitMs < 0) {
318
+ throw invalid('options.selfRemoveElectionWaitMs must be a safe integer >= 0 (0 = commit at once)');
319
+ }
320
+ const inviteRetentionMs = raw.inviteRetentionMs ?? DEFAULT_INVITE_RETENTION_MS;
321
+ if (typeof inviteRetentionMs !== 'number' || !Number.isSafeInteger(inviteRetentionMs) || inviteRetentionMs < 0) {
322
+ throw invalid('options.inviteRetentionMs must be a safe integer >= 0');
323
+ }
324
+ const inboxHandlerBudgetMs = raw.inboxHandlerBudgetMs ?? DEFAULT_INBOX_HANDLER_BUDGET_MS;
325
+ if (typeof inboxHandlerBudgetMs !== 'number' || !Number.isSafeInteger(inboxHandlerBudgetMs) || inboxHandlerBudgetMs < 0) {
326
+ throw invalid('options.inboxHandlerBudgetMs must be a safe integer >= 0 (0 = never report)');
327
+ }
328
+ const ratchetSkipMargin = raw.ratchetSkipMargin ?? DEFAULT_RATCHET_SKIP_MARGIN;
329
+ if (typeof ratchetSkipMargin !== 'number' ||
330
+ !Number.isSafeInteger(ratchetSkipMargin) ||
331
+ ratchetSkipMargin < MIN_RATCHET_SKIP_MARGIN ||
332
+ ratchetSkipMargin > MAX_RATCHET_SKIP_MARGIN) {
333
+ throw invalid(`options.ratchetSkipMargin must be an integer in [${String(MIN_RATCHET_SKIP_MARGIN)}, ${String(MAX_RATCHET_SKIP_MARGIN)}]`);
334
+ }
335
+ return {
336
+ clock: clock === undefined ? { now: () => Date.now() } : clock,
337
+ historySilenceThreshold: threshold,
338
+ graceWindowMs: grace,
339
+ timers: timers === undefined ? DEFAULT_TIMERS : timers,
340
+ historyTimeoutMs,
341
+ maxPublishAttempts,
342
+ beforePublishTimeoutMs,
343
+ seenSetCap,
344
+ enrolmentPromptRateLimit,
345
+ maxGiftWrapBytes,
346
+ leaveTimeoutMs,
347
+ proposalDeferralTimeoutMs,
348
+ removalSettleMs,
349
+ selfRemoveElectionWaitMs,
350
+ inviteRetentionMs,
351
+ inboxHandlerBudgetMs,
352
+ ratchetSkipMargin,
353
+ };
354
+ }
355
+ // ---------------------------------------------------------------------------
356
+ // createMarmotClient
357
+ // ---------------------------------------------------------------------------
358
+ export function createMarmotClient(options) {
359
+ return createMarmotClientWith(options, {});
360
+ }
361
+ /** Internal (tests only): `createMarmotClient` with {@link InternalClientOptions}. */
362
+ export function createMarmotClientWith(options, internal) {
363
+ if (!isObject(options))
364
+ throw invalid('options must be an object');
365
+ // First, before anything could reach the signer: a budget is mandatory and
366
+ // only an object can be one. `{ policy: 'none' }` is the explicit opt-out;
367
+ // any absent or non-object value is refused rather than defaulted.
368
+ const budget = options.budget;
369
+ if (!isObject(budget) || Array.isArray(budget)) {
370
+ throw new MarmotError('missing-budget', "createMarmotClient: a `budget` option is required — pass a nostr-events BudgetPolicy, or { policy: 'none' } to opt out explicitly");
371
+ }
372
+ // Snapshot once: the object validated is the object handed to withSignerBudget,
373
+ // so an accessor cannot return a number here and a string there.
374
+ const budgetSnapshot = { ...budget };
375
+ validateBudgetNumericFields(budgetSnapshot);
376
+ validateSigner(options.signer);
377
+ const transport = narrowTransport(options.transport);
378
+ const consumerStores = validateStores(options.stores);
379
+ const relays = validateRelays(options.relays);
380
+ const verifier = options.verifier;
381
+ if (verifier !== undefined && !isFunction(verifier))
382
+ throw invalid('verifier must be a function');
383
+ const onProposal = options.onProposal;
384
+ if (onProposal !== undefined && !isFunction(onProposal))
385
+ throw invalid('onProposal must be a function');
386
+ const onApplicationRumor = options.onApplicationRumor;
387
+ if (onApplicationRumor !== undefined && !isFunction(onApplicationRumor))
388
+ throw invalid('onApplicationRumor must be a function');
389
+ const history = options.history;
390
+ if (history !== undefined && !hasMethods(history, ['append', 'withdraw', 'list', 'purge']))
391
+ throw invalid('history must implement append, withdraw, list and purge');
392
+ const mediaCache = options.mediaCache;
393
+ if (mediaCache !== undefined && !hasMethods(mediaCache, ['get', 'put']))
394
+ throw invalid('mediaCache must implement get and put');
395
+ const resolved = resolveClientOptions(options.options);
396
+ let accountSigner;
397
+ try {
398
+ accountSigner = withSignerBudget(options.signer, budgetSnapshot);
399
+ }
400
+ catch (err) {
401
+ throw invalid('budget rejected by withSignerBudget', err);
402
+ }
403
+ let disposed = false;
404
+ const listeners = new Map();
405
+ /** What the consumer's `timers.clear` threw (see {@link recordingTimers}); reported by dispose(). */
406
+ const timerClearErrors = [];
407
+ // AC-STORE-2: a store's envelope-mismatch report surfaces as the client's
408
+ // `storeIncompatible` event. The account store is subscribed now; each
409
+ // group store the first time `groupFactory` yields it. A consumer store
410
+ // whose `onIncompatible` throws fails with `invalid-options` (cause: the
411
+ // thrown error) — at construction for the account store, at first yield
412
+ // for a group store.
413
+ const storeUnsubscribers = [];
414
+ const subscribedStores = new WeakSet();
415
+ function forwardIncompatible(store, what, buildError = invalid) {
416
+ if (subscribedStores.has(store))
417
+ return;
418
+ const listener = ({ key, error }) => ctx.emit('storeIncompatible', { key, error });
419
+ let unsubscribe;
420
+ try {
421
+ unsubscribe = store.onIncompatible(listener);
422
+ }
423
+ catch (err) {
424
+ throw buildError(`${what}.onIncompatible threw while the client subscribed to it`, err);
425
+ }
426
+ subscribedStores.add(store);
427
+ if (typeof unsubscribe !== 'function')
428
+ return;
429
+ // A listener may have disposed the client synchronously during the subscribe; dispose() has
430
+ // already drained storeUnsubscribers, so unsubscribe here rather than leak the subscription.
431
+ if (disposed)
432
+ unsubscribe();
433
+ else
434
+ storeUnsubscribers.push(unsubscribe);
435
+ }
436
+ const stores = Object.freeze({
437
+ account: consumerStores.account,
438
+ groupFactory: (groupId) => {
439
+ const store = validateGroupStore(consumerStores.groupFactory(groupId), groupId);
440
+ // Skip the subscribe once disposed: dispose() already drained
441
+ // storeUnsubscribers, so a subscribe from a call racing past it would
442
+ // never be unsubscribed. The store itself is still returned — only
443
+ // the leak-prone subscribe is skipped.
444
+ if (!disposed)
445
+ forwardIncompatible(store, `stores.groupFactory(${JSON.stringify(groupId)})`, storesLazyError);
446
+ return store;
447
+ },
448
+ });
449
+ // `ctx` must exist before any store is subscribed: `forwardIncompatible`'s
450
+ // listener reads `ctx.emit` and a store's `onIncompatible` may invoke that
451
+ // listener *synchronously*, inline with the subscribe call (e.g. to replay
452
+ // an already-known mismatch). Building `ctx` first means that replay always
453
+ // finds a live `ctx` — never `ctx`'s temporal dead zone. `client.on(...)`
454
+ // cannot have run yet at this point (the `client` object below does not
455
+ // exist yet), so `listeners` is still empty: a synchronous replay during
456
+ // construction is therefore swallowed by `emit`'s own `listeners.get(event)
457
+ // ?? []` fallback — no crash, no throw, and nothing for a caller to
458
+ // observe, since no `storeIncompatible` listener could have been
459
+ // registered yet. This is intentional (not a bug to fix): the account
460
+ // store's *next* mismatch report, after construction returns and a
461
+ // listener is registered, is delivered normally.
462
+ // S3: per-instance re-entrancy guard (ADR-013); S7's beforeCreateGroup gates run through it.
463
+ const guard = createReentrancyGuard();
464
+ const ctx = {
465
+ signer: accountSigner,
466
+ transport,
467
+ stores,
468
+ relays,
469
+ verifier,
470
+ onProposal,
471
+ ...resolved,
472
+ beforePublish: createBeforePublishRegistry(resolved.beforePublishTimeoutMs),
473
+ timers: recordingTimers(resolved.timers, timerClearErrors),
474
+ history,
475
+ mediaCache,
476
+ engineSeamsOverride: internal.engineSeams,
477
+ engineOptionsForTest: internal.engineOptions,
478
+ finishPurgeBeforeJoin: internal.finishPurgeBeforeJoin !== false,
479
+ historyBackendTimeoutMs: internal.historyBackendTimeoutMs ?? HISTORY_BACKEND_TIMEOUT_MS,
480
+ disableSelfUpdateReenqueueForTest: internal.disableSelfUpdateReenqueueForTest === true,
481
+ disableRestoreRotationForTest: internal.disableRestoreRotationForTest === true,
482
+ disableRatchetSkipForTest: internal.disableRatchetSkipForTest === true,
483
+ redriveFaultsForTest: internal.redriveFaultsForTest,
484
+ // Stryker disable next-line all: test seam
485
+ exposeRuntimesForTest: internal.exposeRuntimesForTest,
486
+ emit(event, payload) {
487
+ if (disposed)
488
+ return;
489
+ // AC-RE-1: dispatched outside every re-entrancy frame — a client event can fire from
490
+ // inside a live surface frame (e.g. confirmBlocked/intentFailed from inside a devices.* operation's own
491
+ // confirmation, still nested in its DEVICE_SCOPE frame), but nothing awaits a listener, so one that
492
+ // starts another operation (a devices.* call from a `confirmBlocked` handler) must simply queue, never
493
+ // be rejected `reentrant` for a frame it does not actually run inside.
494
+ guard.detached(() => {
495
+ for (const listener of [...(listeners.get(event) ?? [])]) {
496
+ try {
497
+ const returned = listener(payload);
498
+ // An async listener's rejection is the listener's own: never an unhandled rejection of the client.
499
+ if (typeof returned?.then === 'function')
500
+ returned.then(undefined, () => undefined);
501
+ }
502
+ catch {
503
+ // A throwing consumer listener must not break the operation that emitted.
504
+ }
505
+ }
506
+ });
507
+ },
508
+ // AC-INBOX-6: emits through ctx.emit (read lazily — ctx is this very object).
509
+ // Dispatched outside every re-entrancy frame (round 5, Z1): a lifecycle event fires from inside the operation
510
+ // that committed it — for devices.* inside its DEVICE_SCOPE frame — but nothing awaits its listeners, so one
511
+ // that starts another operation (forget the next device after deviceForgotten) must simply queue, not be
512
+ // refused `reentrant`. Guarded surfaces the operation DOES await (onConfirm hooks, stores …) keep their frames.
513
+ lifecycle: createLifecycleEvents((event, payload) => guard.detached(() => ctx.emit(event, payload))),
514
+ beforeCreateGroup: createBeforeCreateGroupGates({
515
+ call: (gate) => guard.call(ACCOUNT_SCOPE, 'beforeCreateGroup', gate),
516
+ isDisposed: () => disposed,
517
+ }),
518
+ deviceLineage: { read: undefined },
519
+ isDisposed: () => disposed,
520
+ };
521
+ // Only now — with `ctx` live — do we subscribe the account store. See the
522
+ // comment on `ctx` above for why this ordering is load-bearing.
523
+ forwardIncompatible(consumerStores.account, 'stores.account');
524
+ function assertLive(member) {
525
+ if (disposed)
526
+ throw new MarmotError('disposed', `${member}: client has been disposed`);
527
+ }
528
+ /**
529
+ * The signer's account key (epic marmot-invitation-outcomes S4, SC-3 I9c): the account cleanup references are minted
530
+ * for and checked against. Asked once per client (through the guard); a failed call is asked again next time.
531
+ */
532
+ let signerAccountKey;
533
+ function signerAccount() {
534
+ if (signerAccountKey === undefined) {
535
+ const pending = guard.call(ACCOUNT_SCOPE, 'signer', () => ctx.signer.getPublicKey());
536
+ signerAccountKey = pending;
537
+ pending.catch(() => {
538
+ if (signerAccountKey === pending)
539
+ signerAccountKey = undefined;
540
+ });
541
+ }
542
+ return signerAccountKey;
543
+ }
544
+ /** SC-9 for `invitations.declineCandidates`: `reentrant` inside an account-scope frame other than an inbox surface. */
545
+ function assertDeclineScanAllowed() {
546
+ try {
547
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'invitations.declineCandidates');
548
+ }
549
+ catch (error) {
550
+ const surface = isMarmotError(error, 'reentrant') ? error.details?.['surface'] : undefined;
551
+ if (typeof surface === 'string' && RECOVERY_READ_INBOX_SURFACES.includes(surface))
552
+ return;
553
+ throw error;
554
+ }
555
+ }
556
+ // S3: the group registry (groups.create/get/list, extensions.onConfirm).
557
+ // Built here — after `ctx` is live, before `client` — so it closes over
558
+ // this exact `ctx` (INV-NO-SINGLETONS: no module-level state).
559
+ // S5: Welcome delivery. Same wiring rule as keyPackagesDeps below: every
560
+ // consumer surface (signer, transport — including the relay-list lookups
561
+ // `lookupInboxRelays` makes through it —, account store, verifier) is
562
+ // pre-wrapped through the guard on the account scope, so invitations/
563
+ // never touches ClientContext or the guard itself.
564
+ const invitationsDeps = {
565
+ clock: ctx.clock,
566
+ timers: ctx.timers,
567
+ relays: ctx.relays,
568
+ lookupTimeoutMs: ctx.historyTimeoutMs,
569
+ maxPublishAttempts: ctx.maxPublishAttempts,
570
+ verifier: ctx.verifier === undefined ? undefined : (event) => guard.call(ACCOUNT_SCOPE, 'verifier', () => ctx.verifier(event)),
571
+ signer: {
572
+ getPublicKey: () => guard.call(ACCOUNT_SCOPE, 'signer', () => ctx.signer.getPublicKey()),
573
+ signEvent: (template, opts) => guard.call(ACCOUNT_SCOPE, 'signer', () => ctx.signer.signEvent(template, opts)),
574
+ nip44: {
575
+ encrypt: (pubkey, plaintext, opts) => guard.call(ACCOUNT_SCOPE, 'signer', () => ctx.signer.nip44.encrypt(pubkey, plaintext, opts)),
576
+ decrypt: (pubkey, ciphertext, opts) => guard.call(ACCOUNT_SCOPE, 'signer', () => ctx.signer.nip44.decrypt(pubkey, ciphertext, opts)),
577
+ },
578
+ },
579
+ transport: {
580
+ publish: (relays, event, opts) => guard.callSync(ACCOUNT_SCOPE, 'transport', () => ctx.transport.publish([...relays], event, opts)),
581
+ requestWithDeadline: (relays, filters, opts) => guard.callSync(ACCOUNT_SCOPE, 'transport', () => ctx.transport.requestWithDeadline([...relays], filters, opts)),
582
+ subscription: (relays, filters) => guard.callSync(ACCOUNT_SCOPE, 'transport', () => ctx.transport.subscription([...relays], filters)),
583
+ },
584
+ transaction: (fn) => guard.call(ACCOUNT_SCOPE, 'store', () => ctx.stores.account.transaction(fn)),
585
+ isDisposed: () => disposed,
586
+ onFailed: (failure) => ctx.emit('welcomeFailed', failure),
587
+ onRestored: (restored) => ctx.emit('welcomeRestored', restored),
588
+ inviteRetentionMs: ctx.inviteRetentionMs,
589
+ onDeclined: (declined, { candidateId }) => ctx.emit('welcomeDeclined', { ...declined, candidateId }),
590
+ onCandidate: (candidate) => ctx.emit('declineCandidate', candidate),
591
+ // Epic marmot-invitation-outcomes S4 (SC-3 I9c): no `account` — the cleanup references' account is the signer's,
592
+ // the account `cleanupDisposition` checks them against (a custom store's `account` string is never authority).
593
+ };
594
+ const invitations = createInvitationsService(invitationsDeps);
595
+ // S9: the teardown service is built below (it needs the registry's port); the registry reaches it lazily.
596
+ const groupRegistry = createGroupRegistry(ctx, guard, invitations, () => teardown);
597
+ // Epic marmot-invitation-outcomes S1 (SC-10 A-4/A-5, ADR-019 D11): the account store's lease end closes every group's
598
+ // availability subscriptions `no-lease`, synchronously and without group work. Optional port member: a store without
599
+ // it gets that close only lazily (a background retry meeting `no-lease`, dispose — AR-2).
600
+ // The member is read inside the guarded block: a getter or proxy that throws on lookup gets the same cleanup and
601
+ // `invalid-options` as a throwing subscribe.
602
+ let leaseEndedOff;
603
+ try {
604
+ const accountLeaseEnded = consumerStores.account.onLeaseEnded;
605
+ if (typeof accountLeaseEnded === 'function') {
606
+ leaseEndedOff = accountLeaseEnded.call(consumerStores.account, () => groupRegistry.endAvailabilityForLease());
607
+ }
608
+ }
609
+ catch (err) {
610
+ for (const off of storeUnsubscribers.splice(0)) {
611
+ try {
612
+ off();
613
+ }
614
+ catch {
615
+ // construction fails with the subscribe's own error below
616
+ }
617
+ }
618
+ throw invalid('stores.account.onLeaseEnded threw while the client subscribed to it', err);
619
+ }
620
+ if (typeof leaseEndedOff === 'function')
621
+ storeUnsubscribers.push(leaseEndedOff);
622
+ // S4: key-packages deps — every signer/transport/STORE member already
623
+ // routed through the guard on the account scope, mirroring pipeline.ts's
624
+ // callSignerForGroup / settlePublishedRecord's guard.callSync('transport',
625
+ // ...) and group-runtime.ts:461's guard.call(groupId, 'store', ...)
626
+ // (gate-remediation F6: `transaction` — not a raw `AccountStore` — is the
627
+ // one store-access member key-packages/ ever sees, so it cannot reach the
628
+ // consumer's store other than through the guard). key-packages/ never
629
+ // imports ClientContext or ReentrancyGuard itself (architecture.md
630
+ // boundary rule); this is the one place the two meet.
631
+ const keyPackagesDeps = {
632
+ clock: ctx.clock,
633
+ graceWindowMs: ctx.graceWindowMs,
634
+ relays: ctx.relays,
635
+ historyTimeoutMs: ctx.historyTimeoutMs,
636
+ // R4: pre-wrapped through the guard here (mirrors ingest.ts:441's own
637
+ // `rt.guard.call(rt.groupId, 'verifier', () => rt.ctx.verifier!(event))`)
638
+ // so key-packages/ never touches the guard itself.
639
+ verifier: ctx.verifier === undefined ? undefined : (event) => guard.call(ACCOUNT_SCOPE, 'verifier', () => ctx.verifier(event)),
640
+ getPublicKey: () => guard.call(ACCOUNT_SCOPE, 'signer', () => ctx.signer.getPublicKey()),
641
+ signEvent: (template) => guard.call(ACCOUNT_SCOPE, 'signer', () => ctx.signer.signEvent(template)),
642
+ publish: (relays, event) => guard.callSync(ACCOUNT_SCOPE, 'transport', () => ctx.transport.publish([...relays], event)),
643
+ requestWithDeadline: (relays, filters, opts) => guard.callSync(ACCOUNT_SCOPE, 'transport', () => ctx.transport.requestWithDeadline([...relays], filters, opts)),
644
+ subscription: (relays, filters) => guard.callSync(ACCOUNT_SCOPE, 'transport', () => ctx.transport.subscription([...relays], filters)),
645
+ transaction: (fn) => guard.call(ACCOUNT_SCOPE, 'store', () => ctx.stores.account.transaction(fn)),
646
+ parkedProbe: createParkedProbeState(),
647
+ };
648
+ // S6: the inbox (one kind-1059 subscription, seen-set, verifier gate) and
649
+ // the invitee-side Welcome service behind its dispatch point. Same wiring
650
+ // rule as above: every consumer surface is pre-wrapped through the guard
651
+ // on the account scope. The two reference each other lazily (the service
652
+ // runs on the inbox's queue; the inbox dispatches Welcomes to it).
653
+ let welcomes;
654
+ // S7: the demux behind the inbox's dispatch point — Welcomes to the service below, the kinds S8 owns to
655
+ // their native handlers, claimed kinds to registerInboxHandler handlers, the rest to onApplicationRumor.
656
+ // Consumer callbacks run on the account scope: they hold the inbox queue that account operations use.
657
+ const inboxHandlers = createInboxHandlerRegistry();
658
+ const demux = createRumorDemux({
659
+ welcome: (rumor, wrap, dispatchCtx) => welcomes.processWelcome(rumor, wrap, dispatchCtx),
660
+ handlers: inboxHandlers,
661
+ application: onApplicationRumor,
662
+ // S7 (AC-HYG-3): native DECLINE bookkeeping, additive — the rumor still goes on to onApplicationRumor.
663
+ decline: (rumor) => invitations.recordDecline(rumor),
664
+ callConsumer: (surface, fn) => guard.call(ACCOUNT_SCOPE, surface, fn),
665
+ // inbox-handler-time-budget: a diagnostic only — the call is still awaited on the inbox queue.
666
+ handlerBudget: { ms: ctx.inboxHandlerBudgetMs, timers: ctx.timers, onSlow: (slow) => ctx.emit('handlerSlow', slow) },
667
+ isDisposed: () => disposed,
668
+ });
669
+ /** The account's inbox relays as last resolved conclusively (listened on, with the defaults, while a lookup times out). */
670
+ let lastInboxRelays = [];
671
+ const inbox = createInboxSubscription({
672
+ clock: ctx.clock,
673
+ timers: ctx.timers,
674
+ seenSetCap: ctx.seenSetCap,
675
+ account: async () => invitationsDeps.signer.getPublicKey(),
676
+ // The account's own inbox plane, resolved like an invitee's (fixed: defaults, no lookup). Discovery that
677
+ // finds nothing listens on the defaults — where a sender falls back to as well. A timed-out lookup is
678
+ // `transient`: meanwhile the pass listens on the defaults plus the last inbox relays it resolved, does
679
+ // not advance the backfill floor, and a retry pass re-resolves.
680
+ async relays() {
681
+ if (ctx.relays.mode === 'fixed')
682
+ return { relays: ctx.relays.defaults, transient: false };
683
+ const self = await invitationsDeps.signer.getPublicKey();
684
+ const resolution = await resolveInboxRelays(invitationsDeps, self);
685
+ if (resolution.kind === 'relays') {
686
+ lastInboxRelays = resolution.relays;
687
+ return { relays: resolution.relays, transient: false };
688
+ }
689
+ if (resolution.kind === 'none')
690
+ return { relays: ctx.relays.defaults, transient: false };
691
+ return { relays: [...new Set([...ctx.relays.defaults, ...lastInboxRelays])], transient: true };
692
+ },
693
+ backfill: (relays, filter) => fetchHistoryPages((pageRelays, pageFilter) => guard.callSync(ACCOUNT_SCOPE, 'transport', () => ctx.transport.requestWithDeadline(pageRelays, pageFilter, { timeoutMs: ctx.historyTimeoutMs })), relays, filter, { active: () => !disposed, nowSeconds: Math.floor(ctx.clock.now() / 1000) }),
694
+ subscription(relays, filter) {
695
+ const subscribable = invitationsDeps.transport.subscription([...relays], filter);
696
+ // A synchronous frame only (like ingest.ts): observer callbacks the transport fires later must not inherit it.
697
+ return { subscribe: (observer) => guard.callSync(ACCOUNT_SCOPE, 'transport', () => subscribable.subscribe(observer)) };
698
+ },
699
+ transaction: invitationsDeps.transaction,
700
+ verifier: invitationsDeps.verifier,
701
+ async unwrap(wrap) {
702
+ return (await unwrap({ wrap, recipientSigner: invitationsDeps.signer })).rumor;
703
+ },
704
+ // The rumor dispatch point: S7's demux.
705
+ dispatch: (rumor, wrap, dispatchCtx) => demux.dispatch(rumor, wrap, dispatchCtx),
706
+ beforePass: () => {
707
+ // S8: unfinished device intents (approvals, forgets, unsent requests) resume on their own queue —
708
+ // started, never awaited here: they run group operations, which must not wait on the inbox.
709
+ devices.resumeInBackground();
710
+ // S9: teardowns a reload interrupted, likewise.
711
+ teardown.resumeInBackground();
712
+ // S15 (AC-INVITE-4): deferred proposals past their deadline, in every loaded group — on each group's own queue.
713
+ groupRegistry.checkProposalDeadlines();
714
+ // AC-MX-2: unfinished restores an earlier client over these stores left (a scan the creation-time one missed).
715
+ groupRegistry.resumeUnfinishedRestores();
716
+ return inbox.serialize(() => welcomes.resume());
717
+ },
718
+ afterBackfill: () => inbox.serialize(() => welcomes.completeStuckJoins()),
719
+ isDisposed: () => disposed,
720
+ onDisposition: (disposition) => ctx.emit('inboxDisposition', disposition),
721
+ });
722
+ // AC-MX-2: a Welcome join deferred while its group was being restored completes on the next pass — run at once.
723
+ groupRegistry.onRestoreReleased(() => inbox.passNow());
724
+ // AC-FWJ-31: a condition the competing-Welcome gate waits on may have cleared (the group's first sync ended, an own
725
+ // commit settled, the engine's quiescence ended, a restore was released): while a `competing` record waits for the
726
+ // group, the pass that re-decides it runs now. One check per group at a time.
727
+ const gateChecks = new Map();
728
+ const checkGate = (groupId) => {
729
+ if (disposed)
730
+ return;
731
+ const running = gateChecks.get(groupId);
732
+ // An event that arrives during a check asks for one more (the record may have been written after the check read).
733
+ if (running !== undefined) {
734
+ gateChecks.set(groupId, true);
735
+ return;
736
+ }
737
+ gateChecks.set(groupId, false);
738
+ welcomes
739
+ .hasCompeting(groupId)
740
+ .then((waiting) => {
741
+ if (waiting && !disposed)
742
+ inbox.passNow();
743
+ })
744
+ .catch(() => undefined)
745
+ .finally(() => {
746
+ const again = gateChecks.get(groupId) === true;
747
+ gateChecks.delete(groupId);
748
+ if (again)
749
+ checkGate(groupId);
750
+ });
751
+ };
752
+ groupRegistry.onGateMayHaveCleared(checkGate);
753
+ welcomes = createWelcomeService({
754
+ ...invitationsDeps,
755
+ clock: ctx.clock,
756
+ serialize: (task) => inbox.serialize(task),
757
+ clientConfig: sameAccountClientConfig,
758
+ graceWindowMs: ctx.graceWindowMs,
759
+ checkJoinedState: (state) => enforceStateProofs(state),
760
+ adoptJoinedGroup: (groupId, state, joinedAtMs, joinEvidence, invitationId, welcomeCreatedAtMs) => groupRegistry.adoptJoinedGroup(groupId, state, joinedAtMs, joinEvidence, invitationId, welcomeCreatedAtMs),
761
+ adoptionProofOf: (groupId, invitationId) => groupRegistry.adoptionProofOf(groupId, invitationId),
762
+ competing: groupRegistry.competing,
763
+ hasGroup: (groupId) => groupRegistry.hasGroup(groupId),
764
+ rotateKeyPackage: (ref) => rotateKeyPackage(keyPackagesDeps, ref),
765
+ purgeKeyPackages: () => purgeAllExpiredSuperseded(keyPackagesDeps),
766
+ // A Welcome adopted under this device's own enrolment request ends its settled own forget (AC-ROT-5, until enrolled again).
767
+ onManifestFulfilled: async (tx, manifest) => {
768
+ if (manifest.recordedAt !== undefined)
769
+ await supersedeOwnForget(tx, manifest.recordedAt);
770
+ },
771
+ onJoined: (joined) => ctx.emit('groupJoined', joined),
772
+ onOutstanding: () => inbox.requestPass(),
773
+ passNow: () => inbox.passNow(),
774
+ onMaintenanceFailed: (failure) => ctx.emit('maintenanceFailed', failure),
775
+ // The inbox pass also settles an accepted KeyPackage left parked by a crash (AC-KPL-1).
776
+ resumeKeyPackageIntents: async () => {
777
+ await resumePendingIntents(keyPackagesDeps);
778
+ await probeParkedUnconfirmed(keyPackagesDeps);
779
+ },
780
+ });
781
+ const welcomeService = welcomes;
782
+ // S9: group teardown (account/teardown.ts) over the registry's port. Its records live in the account store; every
783
+ // consumer surface is the guard-wrapped one invitationsDeps carries.
784
+ const teardown = createTeardownService({
785
+ clock: ctx.clock,
786
+ timers: ctx.timers,
787
+ leaveTimeoutMs: ctx.leaveTimeoutMs,
788
+ graceWindowMs: ctx.graceWindowMs,
789
+ transaction: invitationsDeps.transaction,
790
+ groups: groupRegistry.teardownPort,
791
+ groupIndexExtension: GROUP_INDEX_EXTENSION,
792
+ forgetKeyPackage: (ref) => forgetKeyPackage(keyPackagesDeps, ref),
793
+ keyPackageStatus: (ref) => keyPackageStatus(keyPackagesDeps, ref),
794
+ resumeKeyPackageIntents: () => resumePendingIntents(keyPackagesDeps),
795
+ // A group's leave settled: an own-leaf devices.forget waiting on it continues (its own queue, not awaited).
796
+ onSettled: () => devices.resumeInBackground(),
797
+ onMaintenanceFailed: (failure) => ctx.emit('maintenanceFailed', failure),
798
+ detached: (fn) => guard.detached(fn),
799
+ isDisposed: () => disposed,
800
+ });
801
+ // S8: the device registry and same-account enrolment (account/), over ports into the group registry
802
+ // and the services above — every consumer surface is the guard-wrapped one invitationsDeps carries.
803
+ const devices = createDeviceService({
804
+ clock: ctx.clock,
805
+ timers: ctx.timers,
806
+ relays: ctx.relays,
807
+ lookupTimeoutMs: ctx.historyTimeoutMs,
808
+ promptRateLimit: ctx.enrolmentPromptRateLimit,
809
+ maxGiftWrapBytes: ctx.maxGiftWrapBytes,
810
+ signer: invitationsDeps.signer,
811
+ transport: invitationsDeps.transport,
812
+ verifier: invitationsDeps.verifier,
813
+ transaction: invitationsDeps.transaction,
814
+ groups: groupRegistry.devicePort,
815
+ createKeyPackage: () => createKeyPackage(keyPackagesDeps),
816
+ fetchKeyPackageEvents: (pubkey) => fetchKeyPackageEvents(keyPackagesDeps, pubkey),
817
+ keyPackageRelays: async () => resolveWriteRelays(keyPackagesDeps, await keyPackagesDeps.getPublicKey()),
818
+ lifecycle: ctx.lifecycle,
819
+ // S7 (epic marmot-device-key-rotation): what `devices.rotateKey()` builds on, over the same guard-wrapped KeyPackage deps.
820
+ rotation: {
821
+ ciphersuiteImpl: () => getCiphersuiteImpl(DEFAULT_CIPHERSUITE_NAME, defaultCryptoProvider),
822
+ retireKeyPackages: (keys) => retireKeyPackagesSignedWith(keyPackagesDeps, keys),
823
+ },
824
+ // S8 round 3 (E1): device operations run in a DEVICE_SCOPE frame; a devices.* call from any consumer surface
825
+ // inside one (whatever its scope — an onConfirm hook carries a group frame) is rejected `reentrant`.
826
+ inDeviceFrame: (fn) => guard.call(DEVICE_SCOPE, 'deviceOperation', fn),
827
+ assertNotInDeviceOperation: (operation) => guard.assertNotReentrant(DEVICE_SCOPE, operation),
828
+ // S3 (AC-RE-2): a devices.* op must not enqueue while ANY group's own onConfirm/verifier/onProposal
829
+ // surface is live — that surface's group queue may itself be waiting on this device op, and a second
830
+ // device op joining the device queue behind it would deadlock the two queues against each other.
831
+ // AC-RE-2: a live frame of `surface` on ACCOUNT_SCOPE / DEVICE_SCOPE (e.g. the account-scope
832
+ // `verifier` frame Welcome/KeyPackage verification runs in) is not a GROUP's own consumer surface and
833
+ // must not trip this check; only a frame whose scope is an actual group id does. Matching the frame (not
834
+ // a boolean) also lets the thrown error carry `scope`, matching the guard's own documented
835
+ // `{ scope, operation, surface }` convention. The exclusion must be applied INSIDE
836
+ // the frame walk (`guard.withinGroupScope`), not by filtering the innermost match after the fact — an
837
+ // excluded ACCOUNT_SCOPE/DEVICE_SCOPE frame nested inside a live group frame of the same surface would
838
+ // otherwise hide that outer group frame entirely (within(undefined, surface) only ever returns the
839
+ // innermost match, so a post-hoc filter on it could wrongly conclude no group surface is live).
840
+ assertNotInGroupConsumerSurface: (operation) => {
841
+ for (const surface of GROUP_CONSUMER_SURFACES) {
842
+ const frame = guard.withinGroupScope(surface);
843
+ if (frame !== undefined) {
844
+ throw new MarmotError('reentrant', `${operation}: re-entrant call from inside group ${JSON.stringify(frame.scope)}'s ${surface} surface`, {
845
+ details: { scope: frame.scope, operation, surface },
846
+ });
847
+ }
848
+ }
849
+ },
850
+ onPrompt: (prompt) => ctx.emit('enrolmentRequested', prompt),
851
+ onMaintenanceFailed: (failure) => ctx.emit('maintenanceFailed', failure),
852
+ isDisposed: () => disposed,
853
+ }, { ownLeaf: teardown });
854
+ // Epic marmot-device-key-rotation (S6): the lineage snapshot a group operation takes before its transaction.
855
+ ctx.deviceLineage.read = () => devices.lineage();
856
+ // S8: KeyPackage offers (invitations/offers.ts), same guard-wrapped surfaces.
857
+ const offerDeps = {
858
+ clock: ctx.clock,
859
+ relays: ctx.relays,
860
+ lookupTimeoutMs: ctx.historyTimeoutMs,
861
+ transport: invitationsDeps.transport,
862
+ verifier: invitationsDeps.verifier,
863
+ signer: invitationsDeps.signer,
864
+ transaction: invitationsDeps.transaction,
865
+ hasGroup: (groupId) => groupRegistry.hasGroup(groupId),
866
+ };
867
+ // S8 (carried from S7): the native handlers of the two reserved kinds S8 owns. Until now such rumors were
868
+ // `unhandled` (and marked seen); from here on they are recorded by marmot itself, never handed to consumer code.
869
+ demux.setNativeHandler(RUMOR_KINDS.ENROLMENT_REQUEST, (rumor, _wrap, dispatchCtx) => devices.handleEnrolmentRumor(rumor, dispatchCtx));
870
+ demux.setNativeHandler(RUMOR_KINDS.KEYPACKAGE_OFFER, (rumor, _wrap, dispatchCtx) => handleKeyPackageOffer(offerDeps, rumor, dispatchCtx, (offer) => ctx.emit('keyPackageOffered', offer)));
871
+ // AC-MX-3: the generic inbox send — the same guard-wrapped signer, transport and verifier as Welcome delivery.
872
+ const inboxSendDeps = {
873
+ relays: ctx.relays,
874
+ lookupTimeoutMs: ctx.historyTimeoutMs,
875
+ transport: invitationsDeps.transport,
876
+ verifier: invitationsDeps.verifier,
877
+ signer: invitationsDeps.signer,
878
+ };
879
+ // F10: observe() subscriptions must not outlive dispose() — tracked the
880
+ // same way `storeUnsubscribers` is, so a leaked observe() over a
881
+ // disposed client's transport does not keep delivering.
882
+ const keyPackageObserveUnsubscribers = new Set();
883
+ const client = {
884
+ get signer() {
885
+ assertLive('MarmotClient.signer');
886
+ return accountSigner;
887
+ },
888
+ permissions,
889
+ groups: {
890
+ create(name, options) {
891
+ assertLive('MarmotClient.groups.create');
892
+ return groupRegistry.groups.create(name, options);
893
+ },
894
+ get(groupId) {
895
+ assertLive('MarmotClient.groups.get');
896
+ // S9: a teardown a reload interrupted continues (in the background).
897
+ teardown.resumeInBackground();
898
+ return groupRegistry.groups.get(groupId);
899
+ },
900
+ list() {
901
+ assertLive('MarmotClient.groups.list');
902
+ teardown.resumeInBackground();
903
+ return groupRegistry.groups.list();
904
+ },
905
+ restore(groupId, snapshot) {
906
+ assertLive('MarmotClient.groups.restore');
907
+ // AC-HOOK-8: refused from inside any group's `onBeforePublish` hook or barrier, like `onConfirm` (the registry's own check).
908
+ const publishing = guard.withinGroupScope('onBeforePublish');
909
+ if (publishing !== undefined) {
910
+ return Promise.reject(new MarmotError('reentrant', `groups.restore: re-entrant call from inside group ${JSON.stringify(publishing.scope)}'s onBeforePublish surface`, {
911
+ details: { scope: publishing.scope, operation: 'groups.restore', surface: 'onBeforePublish' },
912
+ }));
913
+ }
914
+ teardown.resumeInBackground();
915
+ return groupRegistry.groups.restore(groupId, snapshot);
916
+ },
917
+ },
918
+ keyPackages: {
919
+ create(options) {
920
+ assertLive('MarmotClient.keyPackages.create');
921
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'keyPackages.create');
922
+ return createKeyPackage(keyPackagesDeps, options);
923
+ },
924
+ list() {
925
+ assertLive('MarmotClient.keyPackages.list');
926
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'keyPackages.list');
927
+ return listKeyPackages(keyPackagesDeps);
928
+ },
929
+ count() {
930
+ assertLive('MarmotClient.keyPackages.count');
931
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'keyPackages.count');
932
+ return countKeyPackages(keyPackagesDeps);
933
+ },
934
+ rotate(ref) {
935
+ assertLive('MarmotClient.keyPackages.rotate');
936
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'keyPackages.rotate');
937
+ return rotateKeyPackage(keyPackagesDeps, ref);
938
+ },
939
+ forget(ref) {
940
+ assertLive('MarmotClient.keyPackages.forget');
941
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'keyPackages.forget');
942
+ return forgetKeyPackage(keyPackagesDeps, ref);
943
+ },
944
+ observe(account, listener) {
945
+ assertLive('MarmotClient.keyPackages.observe');
946
+ const unsubscribe = observeKeyPackages(keyPackagesDeps, account, listener);
947
+ const tracked = () => {
948
+ keyPackageObserveUnsubscribers.delete(tracked);
949
+ unsubscribe();
950
+ };
951
+ keyPackageObserveUnsubscribers.add(tracked);
952
+ return tracked;
953
+ },
954
+ async offer(options) {
955
+ assertLive('MarmotClient.keyPackages.offer');
956
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'keyPackages.offer');
957
+ const { groupId, to } = validateOfferOptions(options);
958
+ const keyPackageEvent = await createKeyPackage(keyPackagesDeps);
959
+ // S9 (AC-ADMIN-7): minted for this group — `destroy()` publishes kind-5 for it.
960
+ await keyPackagesDeps.transaction((tx) => recordKeyPackageGroupRef(tx, { ref: keyPackageEvent.id, groupId, at: ctx.clock.now() }));
961
+ return sendKeyPackageOffer(offerDeps, { groupId, to, keyPackageEvent });
962
+ },
963
+ },
964
+ invitations: {
965
+ expectWelcome(manifest) {
966
+ assertLive('MarmotClient.invitations.expectWelcome');
967
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'invitations.expectWelcome');
968
+ return welcomeService.expectWelcome(manifest);
969
+ },
970
+ pending() {
971
+ assertLive('MarmotClient.invitations.pending');
972
+ return welcomeService.pending();
973
+ },
974
+ async accept(id) {
975
+ assertLive('MarmotClient.invitations.accept');
976
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'invitations.accept');
977
+ const groupId = await welcomeService.accept(id);
978
+ const group = await groupRegistry.groups.get(groupId);
979
+ if (group === undefined)
980
+ throw new MarmotError('store-failed', `invitations.accept: joined group ${groupId} is not stored`, { details: { groupId } });
981
+ return group;
982
+ },
983
+ decline(id, options) {
984
+ assertLive('MarmotClient.invitations.decline');
985
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'invitations.decline');
986
+ return welcomeService.decline(id, options);
987
+ },
988
+ outcome(id) {
989
+ // SC-9: decided synchronously, before anything is queued (a refused call never waits on a queue it holds).
990
+ try {
991
+ assertLive('MarmotClient.invitations.outcome');
992
+ }
993
+ catch (error) {
994
+ return Promise.reject(error);
995
+ }
996
+ return readInvitationOutcome({ guard, serialize: (task) => inbox.serialize(task), account: ctx.stores.account, groupStore: (groupId) => ctx.stores.groupFactory(groupId) }, id);
997
+ },
998
+ declineCandidates(options) {
999
+ // SC-9: decided synchronously, before any store access. Only account-scope consumer frames are refused (the
1000
+ // scan's account transaction would queue behind the very store call that runs the caller); the inbox
1001
+ // surfaces run on that scope too but hold no store transaction, so the scan proceeds from them.
1002
+ let paging;
1003
+ try {
1004
+ assertLive('MarmotClient.invitations.declineCandidates');
1005
+ assertDeclineScanAllowed();
1006
+ paging = declineScanOptions(options);
1007
+ }
1008
+ catch (error) {
1009
+ return Promise.reject(error);
1010
+ }
1011
+ // The cleanup references' account is the signer's (SC-3 I9c), as on the live path.
1012
+ return signerAccount().then((account) => guard.call(ACCOUNT_SCOPE, 'store', () => ctx.stores.account.transaction((tx) => declineCandidatePage(tx, { account, ...paging }))));
1013
+ },
1014
+ cleanupDisposition(ref) {
1015
+ // SC-9: decided synchronously, before any store access (inside readCleanupDisposition).
1016
+ try {
1017
+ assertLive('MarmotClient.invitations.cleanupDisposition');
1018
+ }
1019
+ catch (error) {
1020
+ return Promise.reject(error);
1021
+ }
1022
+ return readCleanupDisposition({
1023
+ guard,
1024
+ account: ctx.stores.account,
1025
+ groupStore: (groupId) => ctx.stores.groupFactory(groupId),
1026
+ accountKey: () => signerAccount(),
1027
+ sessionFenced: (groupId) => groupRegistry.sessionFenced(groupId),
1028
+ }, ref);
1029
+ },
1030
+ offers(groupId) {
1031
+ assertLive('MarmotClient.invitations.offers');
1032
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'invitations.offers');
1033
+ if (groupId !== undefined && typeof groupId !== 'string')
1034
+ throw new MarmotError('invalid-options', 'invitations.offers: groupId must be a string');
1035
+ return listKeyPackageOffers(offerDeps, groupId);
1036
+ },
1037
+ },
1038
+ inbox: {
1039
+ start() {
1040
+ assertLive('MarmotClient.inbox.start');
1041
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'inbox.start');
1042
+ return inbox.start();
1043
+ },
1044
+ stop() {
1045
+ assertLive('MarmotClient.inbox.stop');
1046
+ return inbox.stop();
1047
+ },
1048
+ },
1049
+ devices: {
1050
+ list() {
1051
+ assertLive('MarmotClient.devices.list');
1052
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'devices.list');
1053
+ return devices.list();
1054
+ },
1055
+ requestEnrolment(options) {
1056
+ assertLive('MarmotClient.devices.requestEnrolment');
1057
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'devices.requestEnrolment');
1058
+ return devices.requestEnrolment(options);
1059
+ },
1060
+ pendingEnrolments() {
1061
+ assertLive('MarmotClient.devices.pendingEnrolments');
1062
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'devices.pendingEnrolments');
1063
+ return devices.pendingEnrolments();
1064
+ },
1065
+ approveEnrolment(requestId) {
1066
+ assertLive('MarmotClient.devices.approveEnrolment');
1067
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'devices.approveEnrolment');
1068
+ return devices.approveEnrolment(requestId);
1069
+ },
1070
+ label(leafKey, label) {
1071
+ assertLive('MarmotClient.devices.label');
1072
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'devices.label');
1073
+ return devices.label(leafKey, label);
1074
+ },
1075
+ forget(leafKey) {
1076
+ assertLive('MarmotClient.devices.forget');
1077
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'devices.forget');
1078
+ return devices.forget(leafKey);
1079
+ },
1080
+ rotateKey() {
1081
+ assertLive('MarmotClient.devices.rotateKey');
1082
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'devices.rotateKey');
1083
+ return devices.rotateKey();
1084
+ },
1085
+ rotation() {
1086
+ assertLive('MarmotClient.devices.rotation');
1087
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'devices.rotation');
1088
+ return devices.rotation();
1089
+ },
1090
+ },
1091
+ extensions: {
1092
+ registerInboxHandler(kind, handler) {
1093
+ assertLive('MarmotClient.extensions.registerInboxHandler');
1094
+ return inboxHandlers.register(kind, handler);
1095
+ },
1096
+ onConfirm(hook) {
1097
+ assertLive('MarmotClient.extensions.onConfirm');
1098
+ return groupRegistry.onConfirm(hook);
1099
+ },
1100
+ onBeforePublish(hook) {
1101
+ assertLive('MarmotClient.extensions.onBeforePublish');
1102
+ return ctx.beforePublish.register(hook);
1103
+ },
1104
+ beforeCreateGroup(gate) {
1105
+ assertLive('MarmotClient.extensions.beforeCreateGroup');
1106
+ return ctx.beforeCreateGroup.register(gate);
1107
+ },
1108
+ async sendInboxRumor(input) {
1109
+ assertLive('MarmotClient.extensions.sendInboxRumor');
1110
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'extensions.sendInboxRumor');
1111
+ // AC-RE-2: never from inside a group's onConfirm hook — its confirmation transaction would wait on the
1112
+ // account signer and the relays for as long as this send takes.
1113
+ const confirming = guard.withinGroupScope('onConfirm');
1114
+ if (confirming !== undefined) {
1115
+ throw new MarmotError('reentrant', `extensions.sendInboxRumor: re-entrant call from inside group ${JSON.stringify(confirming.scope)}'s onConfirm surface`, {
1116
+ details: { scope: confirming.scope, operation: 'extensions.sendInboxRumor', surface: 'onConfirm' },
1117
+ });
1118
+ }
1119
+ // AC-HOOK-8: nor from an `onBeforePublish` hook or barrier — the commit's publish waits on them, and they on the signer.
1120
+ const publishing = guard.withinGroupScope('onBeforePublish');
1121
+ if (publishing !== undefined) {
1122
+ throw new MarmotError('reentrant', `extensions.sendInboxRumor: re-entrant call from inside group ${JSON.stringify(publishing.scope)}'s onBeforePublish surface`, {
1123
+ details: { scope: publishing.scope, operation: 'extensions.sendInboxRumor', surface: 'onBeforePublish' },
1124
+ });
1125
+ }
1126
+ return sendInboxRumor(inboxSendDeps, input);
1127
+ },
1128
+ },
1129
+ transportEvents: Object.freeze({
1130
+ // AC-PIPE-10. Called from inside a transport adapter's callback, so it
1131
+ // must never throw into the adapter: after dispose it is a no-op (emit
1132
+ // already is), and the relay string is forwarded exactly as the adapter
1133
+ // reported it (ADR-014 — a fact, never normalised here).
1134
+ authFailed(relayUrl, error) {
1135
+ if (disposed || typeof relayUrl !== 'string')
1136
+ return;
1137
+ ctx.emit('authFailed', { relayUrl, error });
1138
+ },
1139
+ // marmot-transport-connected-signal: same contract as authFailed (never throws into the adapter).
1140
+ connected(relayUrl) {
1141
+ if (disposed || typeof relayUrl !== 'string')
1142
+ return;
1143
+ ctx.emit('transportConnected', { relayUrl });
1144
+ },
1145
+ }),
1146
+ on(event, listener) {
1147
+ assertLive('MarmotClient.on');
1148
+ if (typeof event !== 'string' || !EVENT_NAMES.has(event)) {
1149
+ throw new MarmotError('invalid-options', `MarmotClient.on: unknown event ${JSON.stringify(event)}`);
1150
+ }
1151
+ if (!isFunction(listener))
1152
+ throw new MarmotError('invalid-options', 'MarmotClient.on: listener must be a function');
1153
+ let set = listeners.get(event);
1154
+ if (set === undefined) {
1155
+ set = new Set();
1156
+ listeners.set(event, set);
1157
+ }
1158
+ const entry = listener;
1159
+ set.add(entry);
1160
+ return () => {
1161
+ listeners.get(event)?.delete(entry);
1162
+ };
1163
+ },
1164
+ dispose() {
1165
+ if (disposed)
1166
+ return;
1167
+ disposed = true;
1168
+ // Every group's availability ends `disposed` (recorded, not yet delivered) before any consumer teardown code runs:
1169
+ // a store unsubscriber that subscribes to a group's availability gets that `ended`, never a writable snapshot.
1170
+ groupRegistry.beginDispose();
1171
+ listeners.clear();
1172
+ // Each teardown step is isolated: a consumer store's throwing
1173
+ // unsubscribe must not leave the other subscriptions, the group sync
1174
+ // loops or their timers alive (a disposed client cannot be disposed
1175
+ // again). What failed is thrown only once everything else is released.
1176
+ const errors = [];
1177
+ for (const unsubscribe of storeUnsubscribers.splice(0)) {
1178
+ try {
1179
+ unsubscribe();
1180
+ }
1181
+ catch (error) {
1182
+ errors.push(error);
1183
+ }
1184
+ }
1185
+ // F10: tear down every live keyPackages.observe() subscription.
1186
+ for (const unsubscribe of [...keyPackageObserveUnsubscribers]) {
1187
+ try {
1188
+ unsubscribe();
1189
+ }
1190
+ catch (error) {
1191
+ errors.push(error);
1192
+ }
1193
+ }
1194
+ try {
1195
+ invitations.dispose();
1196
+ }
1197
+ catch (error) {
1198
+ errors.push(error);
1199
+ }
1200
+ try {
1201
+ devices.dispose();
1202
+ }
1203
+ catch (error) {
1204
+ errors.push(error);
1205
+ }
1206
+ try {
1207
+ teardown.dispose();
1208
+ }
1209
+ catch (error) {
1210
+ errors.push(error);
1211
+ }
1212
+ // A transport whose unsubscribe throws must not keep the groups (and their timers) alive.
1213
+ try {
1214
+ inbox.dispose();
1215
+ }
1216
+ catch (error) {
1217
+ errors.push(error);
1218
+ }
1219
+ errors.push(...groupRegistry.dispose());
1220
+ ctx.beforePublish.clear();
1221
+ errors.push(...timerClearErrors.splice(0));
1222
+ if (errors.length > 0)
1223
+ throw new AggregateError(errors, `MarmotClient.dispose: ${errors.length} teardown step(s) failed; the client is disposed regardless`);
1224
+ },
1225
+ };
1226
+ contexts.set(client, ctx);
1227
+ registries.set(client, groupRegistry);
1228
+ // AC-MX-2: a restore an earlier client over these stores left unfinished (crash, dispose) completes on its own —
1229
+ // the app never re-supplies the snapshot (scanned in the background; `groups.get`/`list` also resume on access).
1230
+ groupRegistry.resumeUnfinishedRestores();
1231
+ return client;
1232
+ }