@serfab/cadre-core 0.11.0 → 0.13.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 (121) hide show
  1. package/README.md +3 -2
  2. package/dist/announce-addrs.d.ts +49 -0
  3. package/dist/announce-addrs.js +78 -0
  4. package/dist/announce-addrs.js.map +1 -0
  5. package/dist/cadre-node.d.ts +607 -53
  6. package/dist/cadre-node.js +1268 -157
  7. package/dist/cadre-node.js.map +1 -1
  8. package/dist/control-database.d.ts +174 -23
  9. package/dist/control-database.js +317 -107
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-read-retry.d.ts +103 -0
  12. package/dist/control-read-retry.js +145 -0
  13. package/dist/control-read-retry.js.map +1 -0
  14. package/dist/control-retry.d.ts +101 -0
  15. package/dist/control-retry.js +108 -0
  16. package/dist/control-retry.js.map +1 -0
  17. package/dist/control-schema.d.ts +1 -1
  18. package/dist/control-schema.js +50 -6
  19. package/dist/control-schema.js.map +1 -1
  20. package/dist/control-write-retry.d.ts +59 -35
  21. package/dist/control-write-retry.js +21 -92
  22. package/dist/control-write-retry.js.map +1 -1
  23. package/dist/delegate-admission.d.ts +17 -15
  24. package/dist/delegate-admission.js +17 -15
  25. package/dist/delegate-admission.js.map +1 -1
  26. package/dist/enrolled-machine-store-file.d.ts +13 -0
  27. package/dist/enrolled-machine-store-file.js +41 -0
  28. package/dist/enrolled-machine-store-file.js.map +1 -0
  29. package/dist/enrolled-machine-store.d.ts +81 -0
  30. package/dist/enrolled-machine-store.js +225 -0
  31. package/dist/enrolled-machine-store.js.map +1 -0
  32. package/dist/file-durable-slot.js +5 -3
  33. package/dist/file-durable-slot.js.map +1 -1
  34. package/dist/index.d.ts +10 -6
  35. package/dist/index.js +39 -12
  36. package/dist/index.js.map +1 -1
  37. package/dist/membership-connection-gater.d.ts +226 -26
  38. package/dist/membership-connection-gater.js +316 -30
  39. package/dist/membership-connection-gater.js.map +1 -1
  40. package/dist/node-local-snapshot.d.ts +6 -0
  41. package/dist/node-local-snapshot.js +7 -1
  42. package/dist/node-local-snapshot.js.map +1 -1
  43. package/dist/{strand-backfill.d.ts → peer-join-backfill.d.ts} +49 -20
  44. package/dist/{strand-backfill.js → peer-join-backfill.js} +146 -56
  45. package/dist/peer-join-backfill.js.map +1 -0
  46. package/dist/peer-record.d.ts +26 -0
  47. package/dist/peer-record.js +32 -0
  48. package/dist/peer-record.js.map +1 -1
  49. package/dist/relay-addrs.d.ts +145 -22
  50. package/dist/relay-addrs.js +314 -31
  51. package/dist/relay-addrs.js.map +1 -1
  52. package/dist/relay-reservation.d.ts +20 -15
  53. package/dist/relay-reservation.js +18 -14
  54. package/dist/relay-reservation.js.map +1 -1
  55. package/dist/strand-addr-protocol.js +16 -0
  56. package/dist/strand-addr-protocol.js.map +1 -1
  57. package/dist/strand-database.d.ts +12 -0
  58. package/dist/strand-database.js +16 -0
  59. package/dist/strand-database.js.map +1 -1
  60. package/dist/strand-formation-manager.d.ts +22 -9
  61. package/dist/strand-formation-manager.js +20 -12
  62. package/dist/strand-formation-manager.js.map +1 -1
  63. package/dist/strand-formation-protocol.d.ts +83 -9
  64. package/dist/strand-formation-protocol.js +86 -10
  65. package/dist/strand-formation-protocol.js.map +1 -1
  66. package/dist/strand-instance-manager.d.ts +151 -17
  67. package/dist/strand-instance-manager.js +237 -32
  68. package/dist/strand-instance-manager.js.map +1 -1
  69. package/dist/strand-membership-writer.d.ts +118 -14
  70. package/dist/strand-membership-writer.js +203 -15
  71. package/dist/strand-membership-writer.js.map +1 -1
  72. package/dist/strand-network-config.d.ts +84 -0
  73. package/dist/strand-network-config.js +136 -0
  74. package/dist/strand-network-config.js.map +1 -0
  75. package/dist/strand-revocation-enforcer.d.ts +392 -0
  76. package/dist/strand-revocation-enforcer.js +533 -0
  77. package/dist/strand-revocation-enforcer.js.map +1 -0
  78. package/dist/strand-solicitation.d.ts +10 -3
  79. package/dist/strand-solicitation.js +12 -7
  80. package/dist/strand-solicitation.js.map +1 -1
  81. package/dist/strand-wake-protocol.d.ts +47 -2
  82. package/dist/strand-wake-protocol.js +76 -6
  83. package/dist/strand-wake-protocol.js.map +1 -1
  84. package/dist/strand-watcher.js +6 -1
  85. package/dist/strand-watcher.js.map +1 -1
  86. package/dist/types.d.ts +282 -43
  87. package/dist/types.js +7 -1
  88. package/dist/types.js.map +1 -1
  89. package/package.json +16 -8
  90. package/src/announce-addrs.ts +93 -0
  91. package/src/cadre-node.ts +1366 -171
  92. package/src/control-database.ts +2628 -2406
  93. package/src/control-read-retry.ts +167 -0
  94. package/src/control-retry.ts +190 -0
  95. package/src/control-schema.ts +50 -6
  96. package/src/control-write-retry.ts +30 -130
  97. package/src/delegate-admission.ts +17 -15
  98. package/src/enrolled-machine-store-file.ts +43 -0
  99. package/src/enrolled-machine-store.ts +280 -0
  100. package/src/file-durable-slot.ts +5 -3
  101. package/src/index.ts +477 -407
  102. package/src/membership-connection-gater.ts +539 -204
  103. package/src/node-local-snapshot.ts +13 -1
  104. package/src/peer-addr-book.ts +251 -250
  105. package/src/{strand-backfill.ts → peer-join-backfill.ts} +187 -75
  106. package/src/peer-record.ts +33 -0
  107. package/src/relay-addrs.ts +436 -111
  108. package/src/relay-reservation.ts +828 -823
  109. package/src/strand-addr-protocol.ts +17 -0
  110. package/src/strand-database.ts +17 -0
  111. package/src/strand-formation-manager.ts +511 -491
  112. package/src/strand-formation-protocol.ts +808 -692
  113. package/src/strand-instance-manager.ts +899 -611
  114. package/src/strand-membership-writer.ts +232 -15
  115. package/src/strand-network-config.ts +172 -0
  116. package/src/strand-revocation-enforcer.ts +653 -0
  117. package/src/strand-solicitation.ts +484 -472
  118. package/src/strand-wake-protocol.ts +94 -8
  119. package/src/strand-watcher.ts +319 -314
  120. package/src/types.ts +1554 -1309
  121. package/dist/strand-backfill.js.map +0 -1
@@ -5,24 +5,26 @@
5
5
  * A strand node runs as its own libp2p instance with its own transport peerId,
6
6
  * derived from the cadre identity key + strandId (`strand-transport-key.ts`).
7
7
  * That derivation uses the member's PRIVATE seed by design, so no third party —
8
- * including a co-cadre relay — can recompute it. When a NAT'd member's strand
9
- * node tries to reserve a circuit-relay slot on a sibling's control node, the
10
- * relay's membership connection gater sees an unknown peerId and denies the
11
- * connection, which kills the reservation and fails the strand's
12
- * `libp2p.start()` outright.
8
+ * including a co-cadre relay — can recompute it: a sibling's relay sees an
9
+ * unknown peerId it has no way to place as a member.
13
10
  *
14
- * The resolution (docs/strands.md → "Relays and admission"): a party control
11
+ * The resolution (docs/strands.md → "Relay willingness"): a party control
15
12
  * node running a relay is party-private infrastructure — it relays for its own
16
13
  * party's nodes, including the extra transport identities its members' strand
17
- * nodes run as, and for nobody else. The mechanism is a **member-announced
18
- * delegate grant**: before a member's control node starts a strand node, it
19
- * tells its siblings (over the already-authenticated `/sereus/strand-addr/1.0.0`
20
- * RPC) the derived peerId that strand node will use, and the receiver holds a
21
- * short-lived, in-memory admission grant for exactly that peerId. The grant is
22
- * consulted ONLY by the connection-level gate
23
- * (`CadreNode.admitInboundControlConnection`); the fail-closed per-stream gate
24
- * (`authorizeInboundControlStream`) never honors it, so a delegate gets the
25
- * connection (all a circuit-relay `hop` reservation needs) and nothing more.
14
+ * nodes run as. The mechanism is a **member-announced delegate grant**: before
15
+ * a member's control node starts a strand node, it tells its siblings (over the
16
+ * already-authenticated `/sereus/strand-addr/1.0.0` RPC) the derived peerId
17
+ * that strand node will use, and the receiver holds a short-lived, in-memory
18
+ * admission grant for exactly that peerId. The grant is consulted by the
19
+ * connection-level gate (`CadreNode.admitInboundControlConnection`) and by the
20
+ * relay-reservation admission (`CadreNode.admitControlRelayReservation`) — a
21
+ * granted delegate is admitted outright, never drawing on the small
22
+ * unauthorized-reservation budget that unplaced peers share
23
+ * (`membership-connection-gater.ts` → "The relay-reservation seam") and never
24
+ * racing its not-reserving connection deadline. The fail-closed per-stream gate
25
+ * (`authorizeInboundControlStream`) never honors a grant, so a delegate gets
26
+ * the connection and its reservation (all a circuit-relay `hop` needs) and
27
+ * nothing more.
26
28
  *
27
29
  * A grant is a delegation of trust to an already-trusted member: the receiver
28
30
  * cannot verify that the announced peerId really is the member's strand node,
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Node-only file-backed {@link EnrolledMachineStore}: one JSON file per party under
3
+ * a configured directory (the node's state directory — `cadre-cli` passes
4
+ * `ResolvedConfig.nodeStateDir`), holding the node-local, non-replicated count of
5
+ * machines this party had enrolled the last time this node looked.
6
+ *
7
+ * Nothing but the file itself lives here: the envelope, the cold-start-on-anything
8
+ * load policy (deliberately NOT the throw-on-unreadable policy its two sibling
9
+ * records use — see the `enrolled-machine-store.ts` module comment) and the
10
+ * serialised writes are cross-platform in `PersistentEnrolledMachineStore`, and the
11
+ * file is a `FileDurableSlot`. This module exists only so the `node:fs` edge stays
12
+ * out of the package's cross-platform default entry (`./index.js`) — import it from
13
+ * the dedicated subpath instead:
14
+ *
15
+ * ```ts
16
+ * import { FileEnrolledMachineStore } from '@serfab/cadre-core/enrolled-machine-store-file';
17
+ * ```
18
+ *
19
+ * A React Native / browser entry graph never resolves this path, so the `node:fs`
20
+ * edge never reaches a bundler that cannot satisfy it (same isolation pattern as
21
+ * `bootstrap-peer-store-file.ts` / `trusted-owner-store-file.ts` / `key-store-file.ts`).
22
+ */
23
+ import { FileDurableSlot } from './file-durable-slot.js';
24
+ import { PersistentEnrolledMachineStore } from './enrolled-machine-store.js';
25
+ import type { EnrolledMachineStore } from './enrolled-machine-store.js';
26
+
27
+ /** Base name of the store file: `<dir>/enrolled-machines.<encoded partyId>.json`. */
28
+ const SLOT_NAME = 'enrolled-machines';
29
+
30
+ /**
31
+ * File-backed {@link EnrolledMachineStore}. Open via {@link open}, which loads the
32
+ * existing file and returns the cross-platform store over it. An absent, corrupt,
33
+ * wrong-party, junk-valued **or unreadable** file is a cold start (`count()` is
34
+ * `undefined`, the node declares no repair yardstick and runs at the base control
35
+ * policy) — `open` never rejects, unlike the sibling stores' file backends. That
36
+ * divergence and its reasoning live on `enrolled-machine-store.ts`.
37
+ */
38
+ export const FileEnrolledMachineStore = {
39
+ /** Load (or cold-start) the party's last recorded machine count from a file in `dir`. */
40
+ async open(dir: string, partyId: string): Promise<EnrolledMachineStore> {
41
+ return PersistentEnrolledMachineStore.open(new FileDurableSlot(dir, SLOT_NAME, partyId), partyId);
42
+ }
43
+ };
@@ -0,0 +1,280 @@
1
+ /**
2
+ * Node-local, NON-replicated record of how many machines this party had enrolled
3
+ * the last time this node looked — the block-repair corroboration yardstick the
4
+ * CONTROL network declares when its libp2p node is built.
5
+ *
6
+ * ## Why the number has to be remembered rather than read
7
+ *
8
+ * `resolveRepairYardstick` (in `@serfab/quereus-plugin-sereus`'s `cluster-size.ts`
9
+ * — read it first; the arithmetic and both clamps are explained there and are not
10
+ * repeated here) derives the yardstick from the machines that SERVE the network being
11
+ * configured. For the CONTROL network that is the machines enrolled in the party, and
12
+ * exactly so: every enrolled machine runs the control node by construction. (It is NOT
13
+ * the right number for a strand, which runs on a subset — see
14
+ * `StartStrandConfig.servingMachines`. This store is control-network-only, and that
15
+ * scope is a safety property, not an accident.) Optimystic freezes a network's
16
+ * `clusterPolicy` when its libp2p node is built and offers no runtime setter, so the
17
+ * number has to be known at construction time.
18
+ *
19
+ * The control node cannot read it when it needs it. `CadreNode.buildControlNodeOptions`
20
+ * runs inside `start()` BEFORE `createControlNode()`, which is before the
21
+ * `ControlDatabase` holding the `CadrePeer` rows exists — so at the one moment the
22
+ * number is needed, nothing can answer. That deadlock is why the control network
23
+ * declared no yardstick at all and ran at `CONTROL_CLUSTER_POLICY`'s
24
+ * `assumedClusterSize` of 2.
25
+ *
26
+ * This store breaks it the only way a chicken-and-egg is broken: by remembering
27
+ * across the restart. `CadreNode.refreshAuthorizedControlPeers` records the count
28
+ * every time membership is recomputed; `CadreNode.start()` reads it back before the
29
+ * control node is built. A node therefore declares what it last knew, and a party
30
+ * that grows applies the larger number on each node's NEXT launch. Raising the
31
+ * yardstick is the safe direction and a node still holding the old value is running
32
+ * at exactly today's behaviour, so the next natural restart is soon enough — there
33
+ * is deliberately no forced rebuild.
34
+ *
35
+ * ## Why this is NOT a `NodeLocalSnapshot` like its two siblings
36
+ *
37
+ * The trusted-owner anchor (`trusted-owner-store.ts`) and the cold-start
38
+ * bootstrap-peer store (`bootstrap-peer-store.ts`) are the same `{ version,
39
+ * partyId, ... }` envelope over a {@link DurableSlot} this record is, and this
40
+ * module is deliberately symmetrical with them — same injected-backend shape, same
41
+ * `Memory*` / `Persistent*` / `File*` split, same party scoping. It does NOT share
42
+ * their `NodeLocalSnapshot` machinery, for two reasons:
43
+ *
44
+ * - **Shape.** `NodeLocalSnapshot` is a `key -> entry` map with no delete. This
45
+ * record is one integer that must be able to go DOWN after a machine is removed.
46
+ * - **Load policy — the important one.** `NodeLocalSnapshot.open` THROWS when the
47
+ * slot is present but unreadable. That is right for the anchor (a record that
48
+ * cannot be read in full is not a trust anchor) and right for the peer store (a
49
+ * failed read reported as absent would let the next snapshot write destroy a
50
+ * stranded node's only way home). It is WRONG here. Nothing in this record is
51
+ * trust-bearing, it holds nothing that is not recomputed the moment the control
52
+ * database is up, and refusing to start a node over an unreadable *repair hint*
53
+ * is strictly worse than declaring today's 2. So every unreadable, unparsable,
54
+ * foreign-party or junk slot LOGS and COLD-STARTS, yielding `undefined`, which
55
+ * declares nothing, which is byte-for-byte today's behaviour.
56
+ *
57
+ * Do not "unify" the three modules by routing this one through `NodeLocalSnapshot`:
58
+ * that would quietly import the throw, and turn an unreadable hint into a node that
59
+ * will not start.
60
+ *
61
+ * NOTE: writes are serialised in-process only, the same caveat `NodeLocalSnapshot`
62
+ * carries. Two processes (or two browser tabs) sharing ONE slot for ONE party each
63
+ * write their own view and the loser's count is lost. Two same-origin tabs of
64
+ * `reference-app-web` do exactly that — its slot is one key of a shared IndexedDB
65
+ * database, the same last-writer-wins caveat its `node-local-slots.ts` already
66
+ * records for the other two records. Harmless here, unlike there: this value is one
67
+ * integer both tabs re-derive from the same membership rows on their next refresh,
68
+ * so the views reconverge rather than losing an entry nobody rewrites.
69
+ */
70
+ import debug from 'debug';
71
+ import type { DurableSlot } from './node-local-snapshot.js';
72
+
73
+ const log = debug('sereus:cadre:enrolled-machine-store');
74
+
75
+ /** Envelope version. Guards future migrations; an unknown version cold-starts. */
76
+ const ENVELOPE_VERSION = 1;
77
+
78
+ /** Envelope property holding the count. */
79
+ const PAYLOAD_KEY = 'enrolledMachines';
80
+
81
+ export interface EnrolledMachineStore {
82
+ /** Party this store is scoped to. */
83
+ readonly partyId: string;
84
+
85
+ /**
86
+ * Machines last recorded for this party, or `undefined` when nothing usable was
87
+ * ever recorded — a brand-new node, or a slot that could not be read. Callers
88
+ * pass this straight to `controlClusterPolicy`, whose `undefined` branch returns
89
+ * the frozen base policy unchanged, so "this node does not know" and "this node
90
+ * has never run" are the same declaration: none.
91
+ */
92
+ count(): number | undefined;
93
+
94
+ /**
95
+ * Record the current count. Reflected by {@link count} SYNCHRONOUSLY; the
96
+ * returned promise resolves once the persist attempt has settled.
97
+ *
98
+ * **Never rejects.** Its sole caller is
99
+ * `CadreNode.refreshAuthorizedControlPeers`, whose contract is never-rejects and
100
+ * which leaves the promise un-awaited (`void`) — so a rejection here would
101
+ * surface as an unhandled rejection in the embedder's process, over a hint that
102
+ * re-lands on the next refresh anyway. A failed persist is LOGGED, and the
103
+ * in-memory count stays correct for this session.
104
+ *
105
+ * A count that is not a positive integer is a caller bug: it is logged and
106
+ * IGNORED rather than persisted, so a degenerate value can never reach the slot
107
+ * and be read back as a declaration nobody chose.
108
+ */
109
+ record(count: number): Promise<void>;
110
+ }
111
+
112
+ /**
113
+ * Ephemeral in-memory store — the default when no store is injected via
114
+ * `CadreNodeConfig.enrolledMachines`. A node using this cold-starts on every
115
+ * launch: `count()` is `undefined` at `start()`, so its control node declares
116
+ * nothing and runs at today's behaviour, exactly as before this record existed.
117
+ */
118
+ export class MemoryEnrolledMachineStore implements EnrolledMachineStore {
119
+ private current: number | undefined;
120
+
121
+ constructor(readonly partyId: string) {}
122
+
123
+ count(): number | undefined {
124
+ return this.current;
125
+ }
126
+
127
+ async record(count: number): Promise<void> {
128
+ const accepted = asMachineCount(count);
129
+ if (accepted === undefined) {
130
+ log('refusing to record a non-positive-integer count %o for party %s', count, this.partyId);
131
+ return;
132
+ }
133
+ this.current = accepted;
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Durable {@link EnrolledMachineStore} over an app-supplied {@link DurableSlot} —
139
+ * the cross-platform half of every persistent backend (the Node
140
+ * `FileEnrolledMachineStore` is this class over a file slot).
141
+ *
142
+ * Construct via {@link open}. Load policy is the module comment's: every failure
143
+ * mode cold-starts, and `open` never rejects.
144
+ */
145
+ export class PersistentEnrolledMachineStore implements EnrolledMachineStore {
146
+ /** Serialises persists so the last count recorded is the last one written. */
147
+ private writeChain: Promise<void> = Promise.resolve();
148
+ /** Last count accepted, whether or not it has reached the slot yet. */
149
+ private current: number | undefined;
150
+ /** Last count believed to BE in the slot; drives the unchanged-write skip. */
151
+ private persisted: number | undefined;
152
+
153
+ private constructor(
154
+ private readonly slot: DurableSlot,
155
+ readonly partyId: string,
156
+ loaded: number | undefined
157
+ ) {
158
+ this.current = loaded;
159
+ this.persisted = loaded;
160
+ }
161
+
162
+ /** Load (or cold-start) the party's last recorded machine count from `slot`. */
163
+ static async open(slot: DurableSlot, partyId: string): Promise<PersistentEnrolledMachineStore> {
164
+ return new PersistentEnrolledMachineStore(slot, partyId, await loadCount(slot, partyId));
165
+ }
166
+
167
+ count(): number | undefined {
168
+ return this.current;
169
+ }
170
+
171
+ /**
172
+ * Record the count: visible via {@link count} synchronously, then persisted.
173
+ *
174
+ * Writes are SKIPPED when the slot already holds this number, because the sole
175
+ * caller runs on every committed membership write *and* every timed reconcile
176
+ * pass — a party whose membership is stable would otherwise rewrite the same
177
+ * integer forever. The skip is keyed off {@link persisted} rather than
178
+ * {@link current}, so a write that FAILED is retried by the next refresh instead
179
+ * of being suppressed as "unchanged".
180
+ */
181
+ record(count: number): Promise<void> {
182
+ const accepted = asMachineCount(count);
183
+ if (accepted === undefined) {
184
+ log('refusing to record a non-positive-integer count %o for party %s', count, this.partyId);
185
+ return Promise.resolve();
186
+ }
187
+ this.current = accepted;
188
+ if (this.persisted === accepted) {
189
+ return Promise.resolve();
190
+ }
191
+ this.writeChain = this.writeChain.then(() => this.persistCurrent());
192
+ return this.writeChain;
193
+ }
194
+
195
+ /**
196
+ * Write whatever {@link current} holds when this link of the chain runs — so a
197
+ * burst of records collapses into one write of the latest value — and never
198
+ * throw (see {@link EnrolledMachineStore.record}).
199
+ */
200
+ private async persistCurrent(): Promise<void> {
201
+ const pending = this.current;
202
+ if (pending === undefined || pending === this.persisted) {
203
+ return;
204
+ }
205
+ const envelope = {
206
+ version: ENVELOPE_VERSION,
207
+ partyId: this.partyId,
208
+ [PAYLOAD_KEY]: pending
209
+ };
210
+ try {
211
+ await this.slot.save(JSON.stringify(envelope, null, '\t'));
212
+ this.persisted = pending;
213
+ log('recorded %d enrolled machine(s) for party %s', pending, this.partyId);
214
+ } catch (error) {
215
+ log(
216
+ 'persisting %d enrolled machine(s) for party %s failed (in-memory count stands, retried on the next refresh): %o',
217
+ pending, this.partyId, error
218
+ );
219
+ }
220
+ }
221
+ }
222
+
223
+ /**
224
+ * A usable machine count, or `undefined`. Anything that is not a positive integer
225
+ * is unknown rather than coerced — `'3'`, `0`, `-1`, `2.5`, `null` and a missing key
226
+ * all cold-start. Coercing here would be the beginning of a parser, and Optimystic
227
+ * itself treats a degenerate declaration as absent, so a rounded value would be a
228
+ * number nobody chose.
229
+ */
230
+ function asMachineCount(value: unknown): number | undefined {
231
+ return typeof value === 'number' && Number.isInteger(value) && value >= 1 ? value : undefined;
232
+ }
233
+
234
+ /**
235
+ * Read the slot into the initial count. EVERY failure — unreadable slot, unparsable
236
+ * JSON, wrong envelope version, foreign `partyId`, junk payload — logs and returns
237
+ * `undefined` (see the module comment for why this record, unlike its two siblings,
238
+ * must not throw on an unreadable slot).
239
+ */
240
+ async function loadCount(slot: DurableSlot, partyId: string): Promise<number | undefined> {
241
+ let text: string | undefined;
242
+ try {
243
+ text = await slot.load();
244
+ } catch (error) {
245
+ // The deliberate divergence from `NodeLocalSnapshot.open`, which throws here.
246
+ log('slot for party %s is present but unreadable (cold start — this node declares no yardstick): %o', partyId, error);
247
+ return undefined;
248
+ }
249
+ if (text === undefined) {
250
+ return undefined;
251
+ }
252
+
253
+ let parsed: unknown;
254
+ try {
255
+ parsed = JSON.parse(text);
256
+ } catch (error) {
257
+ log('corrupt slot for party %s (cold start): %o', partyId, error);
258
+ return undefined;
259
+ }
260
+
261
+ if (!isRecord(parsed) || parsed.version !== ENVELOPE_VERSION || parsed.partyId !== partyId) {
262
+ // A non-string partyId cannot equal the requested one, so this covers both a
263
+ // malformed envelope and a slot reused for another party.
264
+ log('slot for party %s has an unknown shape or a foreign partyId (cold start)', partyId);
265
+ return undefined;
266
+ }
267
+
268
+ const count = asMachineCount(parsed[PAYLOAD_KEY]);
269
+ if (count === undefined) {
270
+ log('slot for party %s holds an unusable %s value %o (cold start)', partyId, PAYLOAD_KEY, parsed[PAYLOAD_KEY]);
271
+ return undefined;
272
+ }
273
+ log('loaded %d enrolled machine(s) for party %s', count, partyId);
274
+ return count;
275
+ }
276
+
277
+ /** A plain JSON object. Arrays excluded: an array envelope is not an envelope. */
278
+ function isRecord(value: unknown): value is Record<string, unknown> {
279
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
280
+ }
@@ -5,9 +5,11 @@
5
5
  * parties without cross-party leakage.
6
6
  *
7
7
  * This is the whole platform-specific part of the file-backed node-local
8
- * stores (`trusted-owner-store-file.ts`, `bootstrap-peer-store-file.ts`); the
9
- * load policy, envelope and write chain are cross-platform in
10
- * `node-local-snapshot.ts`. Like its two importers, this module imports
8
+ * stores (`trusted-owner-store-file.ts`, `bootstrap-peer-store-file.ts`,
9
+ * `enrolled-machine-store-file.ts`); the load policy, envelope and write chain
10
+ * are cross-platform — in `node-local-snapshot.ts` for the first two, and in
11
+ * `enrolled-machine-store.ts` for the third, which deliberately does not share
12
+ * that machinery. Like its three importers, this module imports
11
13
  * `node:fs/promises`, so it is kept OUT of the package's cross-platform
12
14
  * default entry and is not itself an exported subpath.
13
15
  */