@serfab/cadre-core 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/README.md +255 -253
  2. package/dist/bootstrap-peer-store-file.d.ts +13 -0
  3. package/dist/bootstrap-peer-store-file.js +42 -0
  4. package/dist/bootstrap-peer-store-file.js.map +1 -0
  5. package/dist/bootstrap-peer-store.d.ts +73 -0
  6. package/dist/bootstrap-peer-store.js +128 -0
  7. package/dist/bootstrap-peer-store.js.map +1 -0
  8. package/dist/cadre-node.d.ts +1121 -81
  9. package/dist/cadre-node.js +2276 -262
  10. package/dist/cadre-node.js.map +1 -1
  11. package/dist/control-authorization.d.ts +93 -0
  12. package/dist/control-authorization.js +57 -0
  13. package/dist/control-authorization.js.map +1 -0
  14. package/dist/control-cohort.d.ts +26 -0
  15. package/dist/control-cohort.js +26 -0
  16. package/dist/control-cohort.js.map +1 -1
  17. package/dist/control-database.d.ts +959 -54
  18. package/dist/control-database.js +1421 -148
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +90 -10
  21. package/dist/control-formation-recorder.js +130 -14
  22. package/dist/control-formation-recorder.js.map +1 -1
  23. package/dist/control-schema.d.ts +1 -1
  24. package/dist/control-schema.js +651 -72
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-stream.d.ts +38 -4
  27. package/dist/control-stream.js +70 -4
  28. package/dist/control-stream.js.map +1 -1
  29. package/dist/control-write-retry.d.ts +161 -0
  30. package/dist/control-write-retry.js +412 -0
  31. package/dist/control-write-retry.js.map +1 -0
  32. package/dist/delegate-admission.d.ts +134 -0
  33. package/dist/delegate-admission.js +244 -0
  34. package/dist/delegate-admission.js.map +1 -0
  35. package/dist/device-token.d.ts +11 -11
  36. package/dist/device-token.js +14 -13
  37. package/dist/device-token.js.map +1 -1
  38. package/dist/ed25519-key.d.ts +26 -0
  39. package/dist/ed25519-key.js +56 -1
  40. package/dist/ed25519-key.js.map +1 -1
  41. package/dist/file-durable-slot.d.ts +20 -0
  42. package/dist/file-durable-slot.js +53 -0
  43. package/dist/file-durable-slot.js.map +1 -0
  44. package/dist/formation-approval.d.ts +157 -0
  45. package/dist/formation-approval.js +375 -0
  46. package/dist/formation-approval.js.map +1 -0
  47. package/dist/fs-atomic.d.ts +38 -0
  48. package/dist/fs-atomic.js +97 -0
  49. package/dist/fs-atomic.js.map +1 -0
  50. package/dist/identity-key.d.ts +49 -0
  51. package/dist/identity-key.js +81 -0
  52. package/dist/identity-key.js.map +1 -0
  53. package/dist/index.d.ts +17 -7
  54. package/dist/index.js +40 -6
  55. package/dist/index.js.map +1 -1
  56. package/dist/key-store-file.d.ts +2 -24
  57. package/dist/key-store-file.js +10 -77
  58. package/dist/key-store-file.js.map +1 -1
  59. package/dist/membership-connection-gater.d.ts +146 -0
  60. package/dist/membership-connection-gater.js +180 -0
  61. package/dist/membership-connection-gater.js.map +1 -0
  62. package/dist/node-local-snapshot.d.ts +109 -0
  63. package/dist/node-local-snapshot.js +182 -0
  64. package/dist/node-local-snapshot.js.map +1 -0
  65. package/dist/peer-addr-book.d.ts +92 -0
  66. package/dist/peer-addr-book.js +220 -0
  67. package/dist/peer-addr-book.js.map +1 -0
  68. package/dist/peer-authorization.d.ts +135 -18
  69. package/dist/peer-authorization.js +152 -21
  70. package/dist/peer-authorization.js.map +1 -1
  71. package/dist/peer-record.d.ts +21 -8
  72. package/dist/peer-record.js +26 -10
  73. package/dist/peer-record.js.map +1 -1
  74. package/dist/relay-addrs.d.ts +45 -0
  75. package/dist/relay-addrs.js +103 -0
  76. package/dist/relay-addrs.js.map +1 -0
  77. package/dist/relay-reservation.d.ts +266 -0
  78. package/dist/relay-reservation.js +613 -0
  79. package/dist/relay-reservation.js.map +1 -0
  80. package/dist/seed-bootstrap.d.ts +228 -56
  81. package/dist/seed-bootstrap.js +340 -198
  82. package/dist/seed-bootstrap.js.map +1 -1
  83. package/dist/seed-trust-policy.d.ts +47 -21
  84. package/dist/seed-trust-policy.js +24 -15
  85. package/dist/seed-trust-policy.js.map +1 -1
  86. package/dist/strand-addr-protocol.d.ts +42 -13
  87. package/dist/strand-addr-protocol.js +58 -52
  88. package/dist/strand-addr-protocol.js.map +1 -1
  89. package/dist/strand-backfill.d.ts +109 -0
  90. package/dist/strand-backfill.js +279 -0
  91. package/dist/strand-backfill.js.map +1 -0
  92. package/dist/strand-cohort.d.ts +4 -37
  93. package/dist/strand-cohort.js +4 -15
  94. package/dist/strand-cohort.js.map +1 -1
  95. package/dist/strand-database.d.ts +11 -16
  96. package/dist/strand-database.js +19 -7
  97. package/dist/strand-database.js.map +1 -1
  98. package/dist/strand-formation-manager.d.ts +36 -7
  99. package/dist/strand-formation-manager.js +115 -15
  100. package/dist/strand-formation-manager.js.map +1 -1
  101. package/dist/strand-formation-protocol.d.ts +103 -4
  102. package/dist/strand-formation-protocol.js +232 -4
  103. package/dist/strand-formation-protocol.js.map +1 -1
  104. package/dist/strand-instance-manager.d.ts +88 -19
  105. package/dist/strand-instance-manager.js +178 -34
  106. package/dist/strand-instance-manager.js.map +1 -1
  107. package/dist/strand-member-registry.d.ts +5 -5
  108. package/dist/strand-member-registry.js +18 -10
  109. package/dist/strand-member-registry.js.map +1 -1
  110. package/dist/strand-membership-writer.d.ts +484 -88
  111. package/dist/strand-membership-writer.js +751 -128
  112. package/dist/strand-membership-writer.js.map +1 -1
  113. package/dist/strand-solicitation.d.ts +99 -33
  114. package/dist/strand-solicitation.js +100 -52
  115. package/dist/strand-solicitation.js.map +1 -1
  116. package/dist/strand-transport-key.d.ts +40 -0
  117. package/dist/strand-transport-key.js +56 -0
  118. package/dist/strand-transport-key.js.map +1 -0
  119. package/dist/strand-wake-protocol.d.ts +9 -7
  120. package/dist/strand-wake-protocol.js +22 -46
  121. package/dist/strand-wake-protocol.js.map +1 -1
  122. package/dist/strand-watcher.d.ts +17 -2
  123. package/dist/strand-watcher.js +47 -3
  124. package/dist/strand-watcher.js.map +1 -1
  125. package/dist/trusted-owner-store-file.d.ts +12 -0
  126. package/dist/trusted-owner-store-file.js +39 -0
  127. package/dist/trusted-owner-store-file.js.map +1 -0
  128. package/dist/trusted-owner-store.d.ts +64 -0
  129. package/dist/trusted-owner-store.js +126 -0
  130. package/dist/trusted-owner-store.js.map +1 -0
  131. package/dist/types.d.ts +307 -44
  132. package/dist/types.js +13 -0
  133. package/dist/types.js.map +1 -1
  134. package/package.json +20 -8
  135. package/src/arachnode-stub.ts +159 -159
  136. package/src/bootstrap-peer-store-file.ts +44 -0
  137. package/src/bootstrap-peer-store.ts +172 -0
  138. package/src/cadre-node.ts +5158 -2981
  139. package/src/canonical-json.ts +30 -30
  140. package/src/control-authorization.ts +114 -0
  141. package/src/control-cohort.ts +130 -103
  142. package/src/control-database.ts +2406 -948
  143. package/src/control-formation-recorder.ts +305 -151
  144. package/src/control-schema.ts +651 -72
  145. package/src/control-stream.ts +205 -128
  146. package/src/control-write-retry.ts +483 -0
  147. package/src/delegate-admission.ts +302 -0
  148. package/src/device-token.ts +94 -89
  149. package/src/diagnostics/connection-path.ts +277 -277
  150. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  151. package/src/ed25519-key.ts +66 -1
  152. package/src/enrollment.ts +199 -199
  153. package/src/file-durable-slot.ts +61 -0
  154. package/src/formation-approval.ts +604 -0
  155. package/src/fs-atomic.ts +107 -0
  156. package/src/hibernation-manager.ts +437 -437
  157. package/src/identity-key.ts +109 -0
  158. package/src/index.ts +137 -5
  159. package/src/key-store-file.ts +132 -203
  160. package/src/key-store.ts +99 -99
  161. package/src/membership-connection-gater.ts +204 -0
  162. package/src/node-local-snapshot.ts +260 -0
  163. package/src/peer-addr-book.ts +250 -0
  164. package/src/peer-authorization.ts +259 -81
  165. package/src/peer-record.ts +164 -146
  166. package/src/push-credentials.ts +84 -84
  167. package/src/push-node.ts +64 -64
  168. package/src/push-notifier-apns.ts +247 -247
  169. package/src/push-notifier-fcm.ts +220 -220
  170. package/src/push-notifier-shared.ts +28 -28
  171. package/src/push-notifier.ts +52 -52
  172. package/src/relay-addrs.ts +111 -0
  173. package/src/relay-reservation.ts +823 -0
  174. package/src/seed-bootstrap.ts +409 -209
  175. package/src/seed-trust-policy.ts +140 -107
  176. package/src/strand-addr-protocol.ts +441 -410
  177. package/src/strand-backfill.ts +366 -0
  178. package/src/strand-cohort.ts +38 -77
  179. package/src/strand-database.ts +202 -204
  180. package/src/strand-formation-manager.ts +491 -368
  181. package/src/strand-formation-protocol.ts +692 -391
  182. package/src/strand-instance-manager.ts +201 -46
  183. package/src/strand-member-key.ts +39 -39
  184. package/src/strand-member-registry.ts +182 -177
  185. package/src/strand-membership-writer.ts +938 -146
  186. package/src/strand-solicitation.ts +472 -407
  187. package/src/strand-transport-key.ts +58 -0
  188. package/src/strand-wake-payload.ts +32 -32
  189. package/src/strand-wake-protocol.ts +314 -331
  190. package/src/strand-watcher.ts +314 -251
  191. package/src/trusted-owner-store-file.ts +41 -0
  192. package/src/trusted-owner-store.ts +171 -0
  193. package/src/types.ts +1309 -1032
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Control-network inbound connection gate (defense-in-depth).
3
+ *
4
+ * Layer 2 of the membership enforcement chain: the PRIMARY gates are per-stream
5
+ * — every sensitive sereus control protocol rejects a peer that fails the
6
+ * voucher-anchored membership check (wake and strand-addr via
7
+ * `CadreNode.isAuthorizedMember`; the Optimystic control-DB protocols via the
8
+ * materialized-snapshot gate `CadreNode.authorizeInboundControlStream`), and
9
+ * the replicated rows an outsider *can* still write are disbelieved at read
10
+ * time. This module adds the opportunistic connection-level layer on top: a
11
+ * peer this node can positively determine is NOT authorized is refused at the
12
+ * encrypted-connection checkpoint, before any protocol negotiation, so a
13
+ * known-nothing outsider is never even in the conversation.
14
+ *
15
+ * ## The stranger allowlist (the ONE place it is defined)
16
+ *
17
+ * A libp2p connection gater decides per CONNECTION, before protocols are
18
+ * negotiated, so "allow seed, deny repo" cannot be expressed here — instead the
19
+ * policy admits a connection whenever a legitimate stranger interaction could be
20
+ * riding it, and the per-stream gates take over. The complete set of protocols a
21
+ * NOT-yet-authorized peer may legitimately speak on a control node is:
22
+ *
23
+ * - `/sereus/seed/1.0.0` ({@link SEED_PROTOCOL}) — enrollment seed delivery.
24
+ * An owner dials a brand-new node to seed it (the new node has no members
25
+ * yet, so its gate is inert), and an invited phone dials the owner before it
26
+ * is authorized (admitted via the enrollment window `CadreNode.createInvite`
27
+ * opens). The handler's own trust decision is the anchored seed-trust policy.
28
+ * - `/sereus/formation/1.0.0` ({@link FORMATION_PROTOCOL}) — cross-party
29
+ * strand formation via open invitations. Stranger-facing BY DESIGN: the
30
+ * initiator is another party, and its token is only checkable inside the
31
+ * protocol. The exemption is therefore keyed on EXPECTATION of a stranger,
32
+ * not capability to serve one: stranger denial is suspended only while this
33
+ * node has at least one UNEXPIRED, NOT-FULLY-CONSUMED open invitation
34
+ * outstanding (`StrandSolicitationService.hasOutstandingInvitation` — the
35
+ * tokens this process minted or published, plus any still-redeemable
36
+ * `FormationInvite` row the usage recorder can see). Merely registering the
37
+ * responder (`CadreNode.initializeStrandSolicitation`) does NOT suspend it,
38
+ * so an app that registers eagerly at node bring-up keeps a live gate. The
39
+ * handler's own trust decision remains the per-token check, which is
40
+ * strictly finer than this one: a peer admitted here can still be rejected
41
+ * in-protocol for a bogus or spent token.
42
+ *
43
+ * There is one further connection-level carve-out, which is NOT a protocol
44
+ * exemption and needs no stranger window:
45
+ *
46
+ * - **Announced delegate peers** (`delegate-admission.ts`). A member's strand
47
+ * node runs as a separate libp2p identity whose peerId no sibling can
48
+ * recompute, so a relay-running control node would deny its circuit-relay
49
+ * reservation. Before starting a strand node, a member's control node
50
+ * announces that peerId over the already-authenticated strand-addr RPC, and
51
+ * the receiver holds a short-lived grant for it
52
+ * (`CadreNode.grantDelegateAdmission`). The grant admits the CONNECTION and
53
+ * nothing else — a reservation needs no stream — and is deliberately
54
+ * invisible to the per-stream gate below, so a delegate still gets refused
55
+ * on every members-only protocol.
56
+ *
57
+ * Everything else a control node handles — the Optimystic control-DB protocols
58
+ * (`/optimystic/control-<party>/{repo,cluster,sync,block-transfer}/…`), wake
59
+ * (`/sereus/strand-wake/1.0.0`), and strand-addr (`/sereus/strand-addr/1.0.0`)
60
+ * — is members-only, and every one of them enforces that per-stream. Wake and
61
+ * strand-addr check `isAuthorizedMember` inside their handlers; the four
62
+ * control-DB protocols are gated by the fail-closed
63
+ * `CadreNode.authorizeInboundControlStream` (wired as libp2p's
64
+ * `authorizeInboundStream` upstream hook), which judges each inbound stream
65
+ * against the MATERIALIZED authorized-peer snapshot — synchronous and
66
+ * in-memory, because a live DB read from inside the gate would deadlock into
67
+ * mutual denial. The two layers complement, not duplicate: this connection
68
+ * gate is fail-open over a live DB read (deny only on positive proof of an
69
+ * outsider), the stream gate is fail-closed over the snapshot and has NO
70
+ * stranger carve-outs — an enrollment window admits a stranger's connection
71
+ * for seed delivery, yet its repo streams are still refused.
72
+ *
73
+ * ## Fail-open, deliberately
74
+ *
75
+ * This layer only ever denies on a POSITIVE determination of "unauthorized
76
+ * outsider while no stranger path is open". Any error, missing dependency, or
77
+ * ambiguous state admits the connection and defers to the fail-closed stream
78
+ * gates — a DB hiccup must not partition a legitimate cadre.
79
+ */
80
+
81
+ import debug from 'debug';
82
+ import type { ConnectionGater, PeerId, MultiaddrConnection } from '@libp2p/interface';
83
+ import { SEED_PROTOCOL } from './seed-bootstrap.js';
84
+ import { FORMATION_PROTOCOL } from './strand-formation-protocol.js';
85
+
86
+ const log = debug('sereus:cadre:connection-gater');
87
+
88
+ /**
89
+ * The protocols a not-yet-authorized peer may legitimately speak on a control
90
+ * node (see the module doc above for why each is open and where its own trust
91
+ * decision lives). Exported as the single reference point so the allowlist
92
+ * cannot silently drift across modules.
93
+ */
94
+ export const STRANGER_OPEN_PROTOCOLS: readonly string[] = [SEED_PROTOCOL, FORMATION_PROTOCOL];
95
+
96
+ /**
97
+ * How long `CadreNode.createInvite` holds the inbound gate open for strangers
98
+ * when the invite carries no explicit expiry: the invitee must dial in before
99
+ * it is authorized, and an expiry-less invite gives the gate no bound of its
100
+ * own. Redeeming after this window still works once the owner re-mints (or the
101
+ * caller re-opens the window via `CadreNode.openEnrollmentWindow`).
102
+ */
103
+ export const DEFAULT_ENROLLMENT_WINDOW_MS = 30 * 60 * 1000;
104
+
105
+ /**
106
+ * Deadline for one admission decision, after which the connection is ADMITTED.
107
+ *
108
+ * libp2p awaits `denyInboundEncryptedConnection` inside the inbound upgrade
109
+ * WITHOUT racing its inbound-upgrade timeout signal (unlike the pre-encryption
110
+ * `denyInboundConnection` hook), so a decision that never settles wedges that
111
+ * upgrade forever — the connection-manager's inbound-upgrade slot is taken by
112
+ * `acceptIncomingConnection` and released in the `finally` that never runs. The
113
+ * real policy reads the control DB (`listAuthorizedMembers`), which can pull
114
+ * over the network, so "never settles" is reachable. Bounding it here keeps the
115
+ * fail-open contract honest: a slow decision admits rather than silently
116
+ * failing closed (or not at all).
117
+ */
118
+ export const ADMISSION_DECISION_TIMEOUT_MS = 2_000;
119
+
120
+ /**
121
+ * The admission decision the gate defers to — implemented by
122
+ * `CadreNode.admitInboundControlConnection` (enrollment windows, anchor state,
123
+ * bootstrap infra, the authorized-member set). Kept injectable so the gater's
124
+ * composition/fail-open behavior is unit-testable without a full node.
125
+ */
126
+ export interface InboundAdmissionPolicy {
127
+ /** Should an inbound encrypted connection from this peer be admitted? */
128
+ admitInbound(remotePeerId: string): Promise<boolean> | boolean;
129
+ }
130
+
131
+ /**
132
+ * Build the control node's connection gater: the caller-supplied gater (if any)
133
+ * with membership admission composed onto `denyInboundEncryptedConnection` —
134
+ * the earliest checkpoint where the remote's authenticated PeerId is known.
135
+ *
136
+ * Composition semantics: every hook of `base` is preserved as-is; on the
137
+ * inbound-encrypted hook a deny from EITHER the base gater or the admission
138
+ * policy denies. A policy error — or a decision slower than
139
+ * `decisionTimeoutMs` — admits (fail-open, see module doc); the base gater's
140
+ * verdict is still honored first.
141
+ *
142
+ * NOTE: `base` is spread, so a gater passed as a CLASS INSTANCE would lose its
143
+ * prototype methods; every caller in this repo (and libp2p's own default)
144
+ * supplies a plain object. If a class-based gater ever shows up, delegate
145
+ * per-hook instead of spreading.
146
+ *
147
+ * Deny timing, as observed by the denied dialer: noise negotiates the muxer in
148
+ * the security handshake's early data, so the DIALER's upgrade may complete
149
+ * (its `dial()` resolves) before this receiver-side hook runs. The deny then
150
+ * aborts the receiver's upgrade — the receiver never registers the connection
151
+ * and never creates its muxer, so no protocol can ever be negotiated — and the
152
+ * dialer sees its "open" connection close moments later.
153
+ *
154
+ * Control node only: strand cohort nodes legitimately connect cross-party
155
+ * peers, so `CadreNode` threads the raw configured gater to them unchanged.
156
+ */
157
+ export function createMembershipConnectionGater(
158
+ policy: InboundAdmissionPolicy,
159
+ base?: ConnectionGater,
160
+ decisionTimeoutMs: number = ADMISSION_DECISION_TIMEOUT_MS
161
+ ): ConnectionGater {
162
+ return {
163
+ ...base,
164
+ denyInboundEncryptedConnection: async (peerId: PeerId, maConn: MultiaddrConnection): Promise<boolean> => {
165
+ if (await base?.denyInboundEncryptedConnection?.(peerId, maConn)) {
166
+ return true;
167
+ }
168
+ const remotePeerId = peerId.toString();
169
+ try {
170
+ return !(await admitWithinDeadline(policy, remotePeerId, decisionTimeoutMs));
171
+ } catch (error) {
172
+ log('admitInbound threw for %s — admitting (fail-open; stream gates decide): %o', remotePeerId, error);
173
+ return false;
174
+ }
175
+ }
176
+ };
177
+ }
178
+
179
+ /**
180
+ * Run the admission decision under {@link ADMISSION_DECISION_TIMEOUT_MS},
181
+ * resolving to "admit" if it has not settled in time (see that constant for why
182
+ * an unbounded await is not safe here). The timer is always cleared so a decided
183
+ * connection never holds the event loop open.
184
+ */
185
+ async function admitWithinDeadline(
186
+ policy: InboundAdmissionPolicy,
187
+ remotePeerId: string,
188
+ timeoutMs: number
189
+ ): Promise<boolean> {
190
+ let timer: ReturnType<typeof setTimeout> | undefined;
191
+ try {
192
+ return await Promise.race([
193
+ Promise.resolve(policy.admitInbound(remotePeerId)),
194
+ new Promise<boolean>((resolve) => {
195
+ timer = setTimeout(() => {
196
+ log('admitInbound exceeded %dms for %s — admitting (fail-open; stream gates decide)', timeoutMs, remotePeerId);
197
+ resolve(true);
198
+ }, timeoutMs);
199
+ })
200
+ ]);
201
+ } finally {
202
+ clearTimeout(timer);
203
+ }
204
+ }
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Shared machinery for the node's **node-local** records — the small,
3
+ * NEVER-replicated, per-party sets a node keeps for itself and never sources
4
+ * from shared group state:
5
+ *
6
+ * - the trusted-owner anchor (`trusted-owner-store.ts`),
7
+ * - the cold-start bootstrap-peer store (`bootstrap-peer-store.ts`).
8
+ *
9
+ * Both are the same mechanism with a different payload: a
10
+ * `{ version, partyId, <entries> }` envelope, snapshot-written whole on every
11
+ * change, loaded under one fail-safe-but-not-fail-silent policy. The only part
12
+ * that differs per platform is WHERE the bytes are kept — Node writes a file,
13
+ * a browser writes IndexedDB, React Native writes SecureStore or its LevelDB
14
+ * KV, NativeScript writes SQLite. That difference is the whole of
15
+ * {@link DurableSlot}, which the embedding app supplies; everything else lives
16
+ * here.
17
+ *
18
+ * This module is cross-platform (no `node:` imports), so it is safe in the
19
+ * package's default entry — the Node-only `FileDurableSlot`
20
+ * (`file-durable-slot.ts`) is what stays behind the `*-store-file` subpaths.
21
+ */
22
+ import debug from 'debug';
23
+
24
+ const log = debug('sereus:cadre:node-local-snapshot');
25
+
26
+ /**
27
+ * A single durable text slot, supplied by the embedding app. The only
28
+ * platform-specific part of a persistent node-local store.
29
+ */
30
+ export interface DurableSlot {
31
+ /**
32
+ * The slot's persisted text, or `undefined` when it was never written.
33
+ *
34
+ * MUST throw (not return `undefined`) when the slot exists but cannot be
35
+ * read. That distinction is load-bearing: `undefined` means "cold start,
36
+ * nothing was ever here", and callers snapshot-write the whole record, so a
37
+ * failed read reported as `undefined` silently converts a recoverable error
38
+ * (permissions, a blocked database upgrade, an I/O fault) into destruction
39
+ * of a still-intact record on the next save.
40
+ */
41
+ load(): Promise<string | undefined>;
42
+ /**
43
+ * Durably replace the slot's text. Callers snapshot-write the whole record,
44
+ * so an implementation never needs to merge.
45
+ */
46
+ save(text: string): Promise<void>;
47
+ }
48
+
49
+ /** Envelope version. Guards future migrations; an unknown version loads empty. */
50
+ const ENVELOPE_VERSION = 1;
51
+
52
+ /**
53
+ * What one unusable entry means for its siblings — the single intentional
54
+ * difference between the two records:
55
+ *
56
+ * - `'discard-all'` (the trusted-owner anchor): a record that cannot be read
57
+ * in full is not an anchor. Trusting a *subset* of the keys a file claims is
58
+ * a silent, security-relevant downgrade, so the whole record is discarded
59
+ * and the node trusts no one until re-seeded out of band.
60
+ * - `'drop-entry'` (the bootstrap-peer store): the record is a best-effort
61
+ * retry list and nothing in it is trust-bearing, so one junk entry must not
62
+ * discard a stranded node's only remaining way back into its party.
63
+ */
64
+ export type UnusableEntryPolicy = 'discard-all' | 'drop-entry';
65
+
66
+ /** What a particular node-local record persists, and how it validates it. */
67
+ export interface NodeLocalSnapshotSpec<E> {
68
+ /** Human name of the record, used in load errors and logs. */
69
+ readonly label: string;
70
+ /** Envelope property holding the `key -> entry` record (`owners`, `peers`). */
71
+ readonly payloadKey: string;
72
+ /** See {@link UnusableEntryPolicy}. */
73
+ readonly unusableEntry: UnusableEntryPolicy;
74
+ /**
75
+ * Validate one persisted entry, returning the value to hold in memory
76
+ * (copied, so later mutation of the parsed JSON cannot reach it) or
77
+ * `undefined` when the entry is unusable.
78
+ */
79
+ readonly acceptEntry: (key: string, entry: unknown) => E | undefined;
80
+ }
81
+
82
+ /**
83
+ * A loaded node-local record over a {@link DurableSlot}: an in-memory
84
+ * `key -> entry` map plus a serialised full-snapshot write chain.
85
+ *
86
+ * NOTE: writes are serialised in-process only. Two processes (or two browser
87
+ * tabs) sharing ONE slot for ONE party would each snapshot-write their own
88
+ * view, so the loser's entries are dropped. Fine for every backend today —
89
+ * each node gets its own directory / origin database — but a single slot
90
+ * backing two concurrent nodes of one party needs a lock or a merge-on-write,
91
+ * not a snapshot replace.
92
+ */
93
+ export class NodeLocalSnapshot<E> {
94
+ /**
95
+ * Serialises persists: every {@link put} snapshot-writes the full entry set,
96
+ * so chaining writes keeps them ordered and the last landed snapshot
97
+ * complete.
98
+ */
99
+ private writeChain: Promise<void> = Promise.resolve();
100
+
101
+ private constructor(
102
+ private readonly slot: DurableSlot,
103
+ readonly partyId: string,
104
+ private readonly spec: NodeLocalSnapshotSpec<E>,
105
+ private readonly entries: Map<string, E>
106
+ ) {}
107
+
108
+ /**
109
+ * Load (or cold-start) the party's record from `slot`. Failure policy, per
110
+ * the trust model of the anchor this was first written for: only a real,
111
+ * well-formed, matching-party record yields entries.
112
+ *
113
+ * A *decidable* non-record — slot never written, unparsable JSON, unknown
114
+ * envelope shape, `partyId` mismatch (a slot reused for a different party
115
+ * must not leak into this one) — yields an EMPTY record, the safe direction:
116
+ * the node holds nothing until it is re-seeded, rather than acting on stale
117
+ * or foreign state.
118
+ *
119
+ * A slot that is *present but unreadable* ({@link DurableSlot.load} threw)
120
+ * is NOT decidable and **throws** instead — mirroring `FileKeyStore.get`.
121
+ * Loading empty there would both hide a real misconfiguration and let the
122
+ * next {@link put} snapshot-write silently destroy a still-intact record.
123
+ */
124
+ static async open<E>(
125
+ slot: DurableSlot,
126
+ partyId: string,
127
+ spec: NodeLocalSnapshotSpec<E>
128
+ ): Promise<NodeLocalSnapshot<E>> {
129
+ return new NodeLocalSnapshot(slot, partyId, spec, await loadEntries(slot, partyId, spec));
130
+ }
131
+
132
+ has(key: string): boolean {
133
+ return this.entries.has(key);
134
+ }
135
+
136
+ /** Fresh copy of the keys — a snapshot decoupled from later {@link put} calls. */
137
+ keySnapshot(): Set<string> {
138
+ return new Set(this.entries.keys());
139
+ }
140
+
141
+ /**
142
+ * Fresh copy of the `key -> entry` map — a snapshot decoupled from later
143
+ * {@link put} calls. The entries themselves need no copy: {@link put}
144
+ * REPLACES an entry rather than mutating it in place.
145
+ */
146
+ entrySnapshot(): Map<string, E> {
147
+ return new Map(this.entries);
148
+ }
149
+
150
+ /**
151
+ * Add or replace an entry: the in-memory map updates SYNCHRONOUSLY (so a
152
+ * synchronous caller may consult the store the moment this returns), then
153
+ * the full snapshot is persisted. A persist failure rejects the returned
154
+ * promise but leaves the entry in memory — this session's decision stands,
155
+ * and any later successful {@link put} re-lands the complete set.
156
+ */
157
+ put(key: string, entry: E): Promise<void> {
158
+ this.entries.set(key, entry);
159
+ const persist = this.writeChain.then(() => this.persistSnapshot());
160
+ // The chain itself must survive a failed persist (the next put retries the
161
+ // full snapshot); the caller still observes the rejection via `persist`.
162
+ this.writeChain = persist.catch((error) => {
163
+ log('%s: persist failed for party %s: %o', this.spec.label, this.partyId, error);
164
+ });
165
+ return persist;
166
+ }
167
+
168
+ private async persistSnapshot(): Promise<void> {
169
+ const envelope: Record<string, unknown> = {
170
+ version: ENVELOPE_VERSION,
171
+ partyId: this.partyId,
172
+ [this.spec.payloadKey]: Object.fromEntries(this.entries),
173
+ };
174
+ await this.slot.save(JSON.stringify(envelope, null, '\t'));
175
+ }
176
+ }
177
+
178
+ /** Read + validate the slot's text into the initial entry map (see {@link NodeLocalSnapshot.open}). */
179
+ async function loadEntries<E>(
180
+ slot: DurableSlot,
181
+ partyId: string,
182
+ spec: NodeLocalSnapshotSpec<E>
183
+ ): Promise<Map<string, E>> {
184
+ const entries = new Map<string, E>();
185
+ let text: string | undefined;
186
+ try {
187
+ text = await slot.load();
188
+ } catch (error) {
189
+ // Present but unreadable: the one non-decidable case, and the one that must
190
+ // not cold-start empty (see NodeLocalSnapshot.open). The slot's own text is
191
+ // folded into the message, not left only on `cause`: the operator-facing
192
+ // print sites (e.g. `cadre-cli start`) log `error.message` alone, and the
193
+ // slot is what knows the platform detail worth acting on (which file, which
194
+ // database).
195
+ throw new Error(
196
+ `failed to read the ${spec.label} for party ${partyId}: ${error instanceof Error ? error.message : String(error)}`,
197
+ { cause: error }
198
+ );
199
+ }
200
+ if (text === undefined) return entries;
201
+
202
+ let parsed: unknown;
203
+ try {
204
+ parsed = JSON.parse(text);
205
+ } catch (error) {
206
+ log('%s: corrupt slot for party %s (cold start): %o', spec.label, partyId, error);
207
+ return entries;
208
+ }
209
+
210
+ const payload = envelopePayload(parsed, partyId, spec.payloadKey);
211
+ if (!payload) {
212
+ log('%s: slot for party %s has an unknown shape or a foreign partyId (cold start)', spec.label, partyId);
213
+ return entries;
214
+ }
215
+
216
+ for (const [key, raw] of Object.entries(payload)) {
217
+ const entry = spec.acceptEntry(key, raw);
218
+ if (entry === undefined) {
219
+ if (spec.unusableEntry === 'discard-all') {
220
+ log('%s: unusable entry for %s discards the whole record (party %s, cold start)', spec.label, key, partyId);
221
+ return new Map();
222
+ }
223
+ log('%s: dropping unusable entry for %s (party %s)', spec.label, key, partyId);
224
+ continue;
225
+ }
226
+ entries.set(key, entry);
227
+ }
228
+ log('%s: loaded %d entr(ies) for party %s', spec.label, entries.size, partyId);
229
+ return entries;
230
+ }
231
+
232
+ /**
233
+ * The envelope's `key -> entry` record, or undefined on any envelope mismatch —
234
+ * wrong version, wrong (or absent) `partyId`, missing or non-record payload.
235
+ * Individual entries are judged separately by
236
+ * {@link NodeLocalSnapshotSpec.acceptEntry}, because one bad entry does not
237
+ * always mean a bad record.
238
+ */
239
+ function envelopePayload(
240
+ value: unknown,
241
+ partyId: string,
242
+ payloadKey: string
243
+ ): Record<string, unknown> | undefined {
244
+ if (!isRecord(value)) return undefined;
245
+ // A non-string partyId cannot equal the requested one, so this covers both
246
+ // "malformed partyId" and "another party's record".
247
+ if (value.version !== ENVELOPE_VERSION || value.partyId !== partyId) return undefined;
248
+ const payload = value[payloadKey];
249
+ return isRecord(payload) ? payload : undefined;
250
+ }
251
+
252
+ /**
253
+ * A plain JSON object usable as a `key -> value` record. Arrays are excluded
254
+ * explicitly: they are `typeof 'object'`, so an array payload would otherwise
255
+ * reach `acceptEntry` once per numeric index — the entries all get rejected in
256
+ * the end, but by accident rather than by decision, and noisily.
257
+ */
258
+ function isRecord(value: unknown): value is Record<string, unknown> {
259
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
260
+ }