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