@serfab/cadre-host 0.9.0 → 0.10.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 (113) hide show
  1. package/dist/auth/index.d.ts +2 -0
  2. package/dist/auth/index.js +1 -0
  3. package/dist/auth/index.js.map +1 -1
  4. package/dist/auth/self-label.d.ts +36 -0
  5. package/dist/auth/self-label.js +57 -0
  6. package/dist/auth/self-label.js.map +1 -0
  7. package/dist/auth/trust-circle.d.ts +32 -5
  8. package/dist/auth/trust-circle.js +31 -11
  9. package/dist/auth/trust-circle.js.map +1 -1
  10. package/dist/bin/host.js +41 -5
  11. package/dist/bin/host.js.map +1 -1
  12. package/dist/donation/__tests__/fake-orchestrator.d.ts +103 -0
  13. package/dist/donation/__tests__/fake-orchestrator.js +180 -0
  14. package/dist/donation/__tests__/fake-orchestrator.js.map +1 -0
  15. package/dist/donation/donation-service.d.ts +237 -12
  16. package/dist/donation/donation-service.js +491 -34
  17. package/dist/donation/donation-service.js.map +1 -1
  18. package/dist/donation/donation-store.d.ts +7 -0
  19. package/dist/donation/donation-store.js +7 -0
  20. package/dist/donation/donation-store.js.map +1 -1
  21. package/dist/donation/donation-supervisor.d.ts +167 -0
  22. package/dist/donation/donation-supervisor.js +341 -0
  23. package/dist/donation/donation-supervisor.js.map +1 -0
  24. package/dist/donation/index.d.ts +4 -2
  25. package/dist/donation/index.js +2 -1
  26. package/dist/donation/index.js.map +1 -1
  27. package/dist/donation/types.d.ts +26 -0
  28. package/dist/donation/types.js.map +1 -1
  29. package/dist/index.d.ts +3 -1
  30. package/dist/index.js +3 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/orchestrator/host-process-orchestrator.d.ts +109 -5
  33. package/dist/orchestrator/host-process-orchestrator.js +341 -98
  34. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  35. package/dist/orchestrator/node-identity.d.ts +26 -0
  36. package/dist/orchestrator/node-identity.js +36 -0
  37. package/dist/orchestrator/node-identity.js.map +1 -0
  38. package/dist/orchestrator/port-allocator.d.ts +14 -0
  39. package/dist/orchestrator/port-allocator.js +45 -0
  40. package/dist/orchestrator/port-allocator.js.map +1 -1
  41. package/dist/owner/owner-node-client.d.ts +20 -5
  42. package/dist/owner/owner-node-client.js +21 -4
  43. package/dist/owner/owner-node-client.js.map +1 -1
  44. package/dist/server/error-handler.d.ts +7 -1
  45. package/dist/server/error-handler.js +23 -1
  46. package/dist/server/error-handler.js.map +1 -1
  47. package/dist/server/events/types.d.ts +3 -0
  48. package/dist/server/index.d.ts +7 -0
  49. package/dist/server/index.js +9 -3
  50. package/dist/server/index.js.map +1 -1
  51. package/dist/server/routes/grants.js +22 -3
  52. package/dist/server/routes/grants.js.map +1 -1
  53. package/dist/server/routes/strands.d.ts +20 -0
  54. package/dist/server/routes/strands.js +38 -0
  55. package/dist/server/routes/strands.js.map +1 -0
  56. package/dist/strands/index.d.ts +7 -0
  57. package/dist/strands/index.js +6 -0
  58. package/dist/strands/index.js.map +1 -0
  59. package/dist/strands/strand-service.d.ts +50 -0
  60. package/dist/strands/strand-service.js +103 -0
  61. package/dist/strands/strand-service.js.map +1 -0
  62. package/dist/strands/types.d.ts +93 -0
  63. package/dist/strands/types.js +23 -0
  64. package/dist/strands/types.js.map +1 -0
  65. package/dist/ui/assets/index-BVoqLjyX.css +1 -0
  66. package/dist/ui/assets/index-C-iks41M.js +17 -0
  67. package/dist/ui/assets/index-C-iks41M.js.map +1 -0
  68. package/dist/ui/index.html +2 -2
  69. package/dist/update/release-key.d.ts +1 -1
  70. package/dist/update/release-key.js +1 -1
  71. package/package.json +5 -5
  72. package/src/__tests__/build-targets.test.ts +26 -0
  73. package/src/__tests__/global-setup.ts +51 -0
  74. package/src/__tests__/orchestrator-env-scrub.test.ts +140 -0
  75. package/src/__tests__/orchestrator-node-identity.test.ts +204 -0
  76. package/src/__tests__/orchestrator.test.ts +387 -6
  77. package/src/auth/__tests__/self-label.test.ts +85 -0
  78. package/src/auth/__tests__/trust-circle-integration.test.ts +152 -147
  79. package/src/auth/__tests__/trust-circle.test.ts +45 -1
  80. package/src/auth/index.ts +2 -0
  81. package/src/auth/self-label.ts +74 -0
  82. package/src/auth/trust-circle.ts +45 -13
  83. package/src/bin/host.ts +1299 -1258
  84. package/src/donation/__tests__/donation-service.test.ts +836 -58
  85. package/src/donation/__tests__/donation-supervisor.test.ts +510 -0
  86. package/src/donation/__tests__/fake-orchestrator.test.ts +168 -0
  87. package/src/donation/__tests__/fake-orchestrator.ts +225 -0
  88. package/src/donation/donation-service.ts +611 -41
  89. package/src/donation/donation-store.ts +7 -0
  90. package/src/donation/donation-supervisor.ts +388 -0
  91. package/src/donation/index.ts +15 -0
  92. package/src/donation/types.ts +23 -0
  93. package/src/index.ts +14 -0
  94. package/src/orchestrator/__tests__/node-identity.test.ts +62 -0
  95. package/src/orchestrator/host-process-orchestrator.ts +336 -97
  96. package/src/orchestrator/node-identity.ts +40 -0
  97. package/src/orchestrator/port-allocator.ts +48 -0
  98. package/src/owner/owner-node-client.ts +31 -5
  99. package/src/server/__tests__/grants-route.test.ts +80 -6
  100. package/src/server/__tests__/strands-route.test.ts +233 -0
  101. package/src/server/error-handler.ts +24 -1
  102. package/src/server/events/types.ts +1 -0
  103. package/src/server/index.ts +16 -3
  104. package/src/server/routes/grants.ts +27 -3
  105. package/src/server/routes/strands.ts +54 -0
  106. package/src/strands/__tests__/strand-service.test.ts +165 -0
  107. package/src/strands/index.ts +14 -0
  108. package/src/strands/strand-service.ts +135 -0
  109. package/src/strands/types.ts +102 -0
  110. package/src/update/release-key.ts +1 -1
  111. package/dist/ui/assets/index-BlMXQPSw.js +0 -14
  112. package/dist/ui/assets/index-BlMXQPSw.js.map +0 -1
  113. package/dist/ui/assets/index-BwU5mJGF.css +0 -1
@@ -2,11 +2,12 @@ import { spawn } from 'node:child_process';
2
2
  import { createRequire } from 'node:module';
3
3
  import { randomBytes } from 'node:crypto';
4
4
  import { existsSync, readFileSync, rmSync, writeFileSync, mkdirSync, statSync, openSync, readSync, closeSync, } from 'node:fs';
5
- import { join, resolve as resolvePath } from 'node:path';
5
+ import { join, resolve as resolvePath, sep } from 'node:path';
6
6
  import debug from 'debug';
7
7
  import pidusage from 'pidusage';
8
8
  import { defaultLogPath, rotateOnDisk } from './log-rotator.js';
9
- import { PortAllocator } from './port-allocator.js';
9
+ import { ensureNodeIdentity } from './node-identity.js';
10
+ import { allocateNodePorts, PortAllocator } from './port-allocator.js';
10
11
  import { StateStore } from './state-store.js';
11
12
  import { isPidAlive } from './pid-liveness.js';
12
13
  import { decodeDockerId, encodeDockerId, } from './types.js';
@@ -21,6 +22,26 @@ const DEFAULTS = {
21
22
  const STARTUP_TOKEN_FILE = '.startup-token';
22
23
  const CONFIG_FILE = 'cadre.json';
23
24
  const LIVENESS_POLL_MS = 100;
25
+ const CADRE_ENV_PREFIX = 'CADRE_';
26
+ /**
27
+ * Manager's own `process.env` with every `CADRE_*` key removed. A child node
28
+ * takes its whole configuration from the config file this orchestrator writes
29
+ * plus the vars set explicitly below, and `@serfab/cadre-cli` treats inherited
30
+ * `CADRE_*` vars as overrides that BEAT that config file — so inheriting them
31
+ * would let a var set on the manager (e.g. CADRE_PARTY_ID) silently
32
+ * reconfigure every spawned child. Scrubbing the whole prefix rather than a
33
+ * list of known keys means a new cli env var can't reintroduce the leak by
34
+ * being forgotten here. Non-CADRE vars (PATH, DEBUG, proxy/TLS settings, etc.)
35
+ * still pass through untouched.
36
+ */
37
+ function scrubbedParentEnv() {
38
+ const env = { ...process.env };
39
+ for (const key of Object.keys(env)) {
40
+ if (key.startsWith(CADRE_ENV_PREFIX))
41
+ delete env[key];
42
+ }
43
+ return env;
44
+ }
24
45
  /** Fixed friendly id for the admin's owner node. */
25
46
  export const OWNER_CONTAINER_ID = 'owner';
26
47
  /**
@@ -96,13 +117,7 @@ export class HostProcessOrchestrator {
96
117
  };
97
118
  this.handles.set(handle.dockerId, handle);
98
119
  // Always reserve ports — even for dead handles, until the caller cleans them up
99
- this.portAllocator.markUsed(persisted.ports.health);
100
- this.portAllocator.markUsed(persisted.ports.metrics);
101
- this.portAllocator.markUsed(persisted.ports.p2p);
102
- // `admin` is absent on handles persisted before this build.
103
- if (typeof persisted.ports.admin === 'number') {
104
- this.portAllocator.markUsed(persisted.ports.admin);
105
- }
120
+ this.reservePorts(persisted.ports);
106
121
  }
107
122
  log('init: re-attached %d handles', state.handles.length);
108
123
  }
@@ -148,49 +163,156 @@ export class HostProcessOrchestrator {
148
163
  this.stateListeners.add(listener);
149
164
  return () => { this.stateListeners.delete(listener); };
150
165
  }
151
- /** Handles that init() found dead (PID gone or token mismatch). */
152
- listDeadHandles() {
153
- const dead = [];
154
- for (const h of this.handles.values()) {
155
- if (!h.alive) {
156
- dead.push(this.toPersisted(h));
157
- }
166
+ /**
167
+ * Spawn a generic managed node — the donated-node path (the requester's cadre,
168
+ * pinned to the *requester's* owner key). The node is given its own protobuf
169
+ * identity key inside its workdir (`ensureNodeIdentity`, reused across
170
+ * re-spawns of the same containerId), which is what makes its peer id stable
171
+ * across restarts AND what makes its node-local stores durable: `cadre-cli
172
+ * start` opens the file-backed bootstrap-peer and trusted-owner stores only
173
+ * when a protobuf identity key file is configured, and puts them beside it.
174
+ * Terminating the loan (`removeContainer`) deletes the workdir, so the key and
175
+ * both stores go with it.
176
+ */
177
+ async createContainer(request) {
178
+ const workdir = this.workdirFor(request.containerId);
179
+ // Sampled BEFORE `ensureNodeIdentity`, which brings the directory into
180
+ // existence as a side effect of writing the key. Only a spawn that found
181
+ // nothing here may delete anything on its way out — a re-spawn is REUSING
182
+ // the identity key and node-local stores this directory holds, and they are
183
+ // the whole reason the node comes back as the same peer. `false` is
184
+ // therefore the safe default: a directory that exists for any reason
185
+ // (respawn, an earlier failed provision, an operator's file) is never
186
+ // touched by the unwind below.
187
+ const isNewWorkdir = !existsSync(workdir);
188
+ let dropped = [];
189
+ let ports;
190
+ try {
191
+ // Identity BEFORE any port is reserved: it is the one step here that can
192
+ // fail on its own (an unreadable or undecodable identity.key throws rather
193
+ // than silently re-keying), and everything past the allocation is either
194
+ // infallible or releases the ports itself. Allocating first would leak four
195
+ // ports from a bounded range on every failed provision attempt.
196
+ const identity = await ensureNodeIdentity(workdir);
197
+ log('container %s identity peerId=%s', request.containerId, identity.peerId);
198
+ // A node started with pinned owner keys belongs to a FOREIGN cadre (the
199
+ // node-donation flow: it trusts the requester's owner key, not the host's).
200
+ // The host's FCM/APNs credentials are minted for the host owner's own app
201
+ // and are meaningless to a foreign cadre — so donated nodes get NO push
202
+ // block. (Per-grantee push creds would be a future ticket; none in v1.)
203
+ const foreignParty = (request.pinnedOwnerKeys?.length ?? 0) > 0;
204
+ // Only storage-profile nodes participate in strands and thus fan out push
205
+ // wakes — a transaction-only node need not carry credentials. Resolved
206
+ // BEFORE the drop below: it is the last `await` on this path, which is what
207
+ // keeps the drop → launch window synchronous (see restoreDroppedHandles).
208
+ const push = request.profile === 'storage' && !foreignParty ? await this.resolvePush() : undefined;
209
+ // Pinned owner key(s) reach the child via CADRE_OWNER_KEYS (comma-separated);
210
+ // `cadre-cli start` unions it into its cold-start pinnedKeyTrustPolicy so the
211
+ // node will accept the foreign-authority-signed seed presented via POST /seed.
212
+ const extraEnv = request.pinnedOwnerKeys?.length
213
+ ? { CADRE_OWNER_KEYS: request.pinnedOwnerKeys.join(',') }
214
+ : undefined;
215
+ // Nothing from here to the launch is `await`ed — which is what keeps
216
+ // `restoreDroppedHandles`'s documented precondition true even though the
217
+ // `try` now opens further up. Do not add an `await` past this line.
218
+ dropped = this.dropStaleHandle(request.containerId);
219
+ // NOTE: the p2p port is re-allocated per spawn, so a re-spawned donated
220
+ // node keeps its peer id but may announce a different port. Recoverable —
221
+ // it dials out to its retained bootstrap peers and republishes its own
222
+ // CadrePeer row once connected. If that reconnect ever proves too slow,
223
+ // pin the p2p port per containerId (see donated-node-respawn-core).
224
+ ports = allocateNodePorts(this.portAllocator);
225
+ return this.launchChild({
226
+ containerId: request.containerId,
227
+ partyId: request.partyId,
228
+ profile: request.profile,
229
+ ports,
230
+ owner: false,
231
+ buildConfig: () => this.buildChildConfig(request, workdir, push),
232
+ extraArgs: ['--identity-protobuf', identity.path],
233
+ ...(extraEnv ? { extraEnv } : {}),
234
+ ...(request.resources?.memoryLimit ? { memoryLimit: request.resources.memoryLimit } : {}),
235
+ });
236
+ }
237
+ catch (err) {
238
+ // Release BEFORE restoring: a re-spawn allocates the very ports the drop
239
+ // just freed, so restoring first and releasing second would hand the
240
+ // restored handle's own ports straight back to the allocator.
241
+ if (ports)
242
+ this.releasePorts(ports);
243
+ // A no-op for the failures that happen before the drop (`dropped` is
244
+ // still empty).
245
+ this.restoreDroppedHandles(dropped);
246
+ // Safe because a throw out of `launchChild` means NO child is running:
247
+ // its throw surface ends where the child is spawned and its handle stored
248
+ // (everything past that line is best-effort), and the `if (!child.pid)`
249
+ // throw is on the no-process side too. So nothing is ever holding the
250
+ // directory this deletes.
251
+ if (isNewWorkdir)
252
+ this.discardWorkdir(workdir);
253
+ throw err;
158
254
  }
159
- return dead;
160
255
  }
161
- async createContainer(request) {
162
- const ports = {
163
- health: this.portAllocator.allocate(),
164
- metrics: this.portAllocator.allocate(),
165
- p2p: this.portAllocator.allocate(),
166
- admin: this.portAllocator.allocate(),
167
- };
168
- // A node started with pinned owner keys belongs to a FOREIGN cadre (the
169
- // node-donation flow: it trusts the requester's owner key, not the host's).
170
- // The host's FCM/APNs credentials are minted for the host owner's own app
171
- // and are meaningless to a foreign cadre — so donated nodes get NO push
172
- // block. (Per-grantee push creds would be a future ticket; none in v1.)
173
- const foreignParty = (request.pinnedOwnerKeys?.length ?? 0) > 0;
174
- // Only storage-profile nodes participate in strands and thus fan out push
175
- // wakes — a transaction-only node need not carry credentials.
176
- const push = request.profile === 'storage' && !foreignParty ? await this.resolvePush() : undefined;
177
- // Pinned owner key(s) reach the child via CADRE_OWNER_KEYS (comma-separated);
178
- // `cadre-cli start` unions it into its cold-start pinnedKeyTrustPolicy so the
179
- // node will accept the foreign-authority-signed seed presented via POST /seed.
180
- const extraEnv = request.pinnedOwnerKeys?.length
181
- ? { CADRE_OWNER_KEYS: request.pinnedOwnerKeys.join(',') }
182
- : undefined;
183
- return this.launchChild({
184
- containerId: request.containerId,
185
- partyId: request.partyId,
186
- profile: request.profile,
187
- ports,
188
- owner: false,
189
- buildConfig: (workdir) => this.buildChildConfig(request, workdir, push),
190
- extraArgs: [],
191
- ...(extraEnv ? { extraEnv } : {}),
192
- ...(request.resources?.memoryLimit ? { memoryLimit: request.resources.memoryLimit } : {}),
193
- });
256
+ /**
257
+ * Remove the working directory a spawn created for `containerId` when no
258
+ * handle owns it — the cleanup of last resort for a donation record that
259
+ * never got a `dockerId` (the host died between `ensureNodeIdentity` and the
260
+ * handle write, so `createContainer`'s own unwind never ran). Returns whether
261
+ * anything was removed.
262
+ *
263
+ * Synchronous, mirroring {@link resolveDockerId}: nothing on this path needs
264
+ * to await.
265
+ */
266
+ reclaimWorkdir(containerId) {
267
+ // The admin's own node is never reclaimed by this route: its workdir is a
268
+ // single fixed path reused by every restart and it holds the host's own
269
+ // control-DB storage.
270
+ if (containerId === OWNER_CONTAINER_ID)
271
+ return false;
272
+ // A live handle owns that directory, and `removeContainer` — which stops
273
+ // the child first — is the only thing allowed to delete it.
274
+ if (this.resolveDockerId(containerId))
275
+ return false;
276
+ const workdir = this.workdirFor(containerId);
277
+ // Defence, not a live case: donation ids are `grn_<base64url>` and so can
278
+ // hold neither a path separator nor a dot. A caller that ever passes
279
+ // something else must not be able to walk out of `rootDir`.
280
+ if (!workdir.startsWith(this.rootDir + sep)) {
281
+ log('refusing to reclaim workdir outside rootDir: %s', workdir);
282
+ return false;
283
+ }
284
+ // Must be a DIRECTORY, not merely something that exists: `rootDir` also
285
+ // holds `state.json` (this orchestrator's own persisted handles), and
286
+ // `discardWorkdir`'s `rmSync` deletes files as happily as trees. Same
287
+ // defence class as the escape check above — no real containerId names a
288
+ // file — but the blast radius if one ever did is the whole handle map.
289
+ if (!statSync(workdir, { throwIfNoEntry: false })?.isDirectory())
290
+ return false;
291
+ this.discardWorkdir(workdir);
292
+ return true;
293
+ }
294
+ /**
295
+ * Best-effort removal of a workdir no handle owns. Logs, never throws: every
296
+ * caller is either unwinding a failure it must report instead of this one, or
297
+ * tearing a container down along a path where a surviving directory is a
298
+ * nuisance rather than a fault.
299
+ *
300
+ * `retries` sizes the wait for the OS to release a cwd handle — Windows drops
301
+ * it asynchronously after a child exits. `createContainer`'s unwind needs none
302
+ * of that (its throw surface ends before any child is spawned), but
303
+ * `reclaimWorkdir` can still meet an orphan process the previous host left
304
+ * running with this directory as its cwd, so it is not a *guaranteed*
305
+ * no-process path either — it simply logs and leaves the directory when the
306
+ * removal fails.
307
+ */
308
+ discardWorkdir(workdir, retries = { maxRetries: 5, retryDelay: 100 }) {
309
+ try {
310
+ rmSync(workdir, { recursive: true, force: true, ...retries });
311
+ log('discarded workdir %s', workdir);
312
+ }
313
+ catch (err) {
314
+ log('failed to discard workdir %s: %o', workdir, err);
315
+ }
194
316
  }
195
317
  /**
196
318
  * Resolve the push credentials to inject into the node about to spawn. Called
@@ -237,38 +359,46 @@ export class HostProcessOrchestrator {
237
359
  this.persist();
238
360
  return toNodeInfo(existing);
239
361
  }
240
- if (existing) {
241
- // Drop the stale handle and release its ports — but DO NOT delete the
242
- // workdir: the owner node's control-DB storage lives there and must
243
- // survive a restart. launchChild reuses the same workdir.
244
- this.releasePorts(existing.ports);
245
- this.handles.delete(existing.dockerId);
246
- }
247
362
  const profile = config.profile ?? 'storage';
248
363
  // Re-resolve push credentials from the secret store on every (re-)spawn so a
249
364
  // restart picks up rotated keys and nothing raw is replayed from state.json.
365
+ // Resolved BEFORE the drop below so the drop → launch window stays
366
+ // synchronous (see restoreDroppedHandles).
250
367
  const push = await this.resolvePush();
251
- const ports = {
252
- health: this.portAllocator.allocate(),
253
- metrics: this.portAllocator.allocate(),
254
- admin: this.portAllocator.allocate(),
255
- // The owner node must listen on the configured libp2p port so the
256
- // NAT mapping (external → internal) lands on it. That port is outside
257
- // the managed range, so markUsed is a harmless no-op.
258
- p2p: config.libp2pPort,
259
- };
260
- this.portAllocator.markUsed(config.libp2pPort);
261
- const result = this.launchChild({
262
- containerId: OWNER_CONTAINER_ID,
263
- partyId: config.partyId,
264
- profile,
265
- ports,
266
- owner: true,
267
- buildConfig: (workdir) => this.buildOwnerChildConfig(config, profile, workdir, push),
268
- extraArgs: ['--owner', '--admin-port', String(ports.admin), '--identity-protobuf', config.identityPath],
269
- });
270
- const handle = this.handles.get(result.dockerId);
271
- return toNodeInfo(handle);
368
+ // NOTE: the short-circuit above matches via `findOwnerHandle` (owner flag OR
369
+ // containerId), this drop only by containerId. Equivalent today — every
370
+ // owner handle is launched with OWNER_CONTAINER_ID. If an owner spawn ever
371
+ // takes a different containerId, the two would disagree and the handle the
372
+ // short-circuit found would survive here, leaking it and its ports.
373
+ const dropped = this.dropStaleHandle(OWNER_CONTAINER_ID);
374
+ let ports;
375
+ try {
376
+ // The owner node must listen on the configured libp2p port so the NAT
377
+ // mapping (external → internal) lands on it — hence the p2p override.
378
+ ports = allocateNodePorts(this.portAllocator, { p2p: config.libp2pPort });
379
+ const result = this.launchChild({
380
+ containerId: OWNER_CONTAINER_ID,
381
+ partyId: config.partyId,
382
+ profile,
383
+ ports,
384
+ owner: true,
385
+ buildConfig: (workdir) => this.buildOwnerChildConfig(config, profile, workdir, push),
386
+ extraArgs: ['--owner', '--admin-port', String(ports.admin), '--identity-protobuf', config.identityPath],
387
+ });
388
+ const handle = this.handles.get(result.dockerId);
389
+ return toNodeInfo(handle);
390
+ }
391
+ catch (err) {
392
+ // Release before restoring — see the same note in createContainer.
393
+ if (ports)
394
+ this.releasePorts(ports);
395
+ this.restoreDroppedHandles(dropped);
396
+ // Deliberately NOT `discardWorkdir` — the asymmetry with createContainer
397
+ // is the point. `<rootDir>/owner` is a single fixed path reused by every
398
+ // restart and holds the host's own control-DB storage, so it neither
399
+ // grows without bound nor is safe to delete on a failed spawn.
400
+ throw err;
401
+ }
272
402
  }
273
403
  /** Endpoint + bearer for the owner node's admin channel, if spawned. */
274
404
  getOwnerAdminEndpoint() {
@@ -314,12 +444,22 @@ export class HostProcessOrchestrator {
314
444
  }
315
445
  /**
316
446
  * Core spawn mechanics shared by `createContainer` and `ensureOwnerNode`.
317
- * The caller has already allocated `ports`. Releases the ports on a
318
- * synchronous spawn failure.
447
+ *
448
+ * The caller has already allocated `ports` and **owns their lifetime**: this
449
+ * method never releases them, so every caller must release on any throw out
450
+ * of here (it has to unwind its handle drop on the same path anyway — see
451
+ * `restoreDroppedHandles`).
452
+ *
453
+ * That contract holds because this method throws only *before* the child is
454
+ * spawned and its handle stored — everything after that point is
455
+ * best-effort. Anything new added at the tail must keep it that way.
456
+ *
457
+ * Entirely synchronous, which is what makes that unwind sound. Do not add an
458
+ * `await` here.
319
459
  */
320
460
  launchChild(opts) {
321
461
  const { containerId, ports } = opts;
322
- const workdir = join(this.rootDir, containerId);
462
+ const workdir = this.workdirFor(containerId);
323
463
  mkdirSync(workdir, { recursive: true });
324
464
  mkdirSync(join(workdir, 'storage'), { recursive: true });
325
465
  const token = randomBytes(16).toString('hex');
@@ -343,15 +483,23 @@ export class HostProcessOrchestrator {
343
483
  const heapBytes = parseMemoryLimit(memoryLimit);
344
484
  const heapMB = heapBytes !== undefined ? Math.max(64, Math.floor(heapBytes / (1024 * 1024))) : undefined;
345
485
  const env = {
346
- ...process.env,
347
- // Caller-supplied extras first — the fixed per-child vars below always win
348
- // so extraEnv can never clobber the seed/startup tokens or port wiring.
486
+ // Scrubbed, not raw process.env: every CADRE_* config-override key is
487
+ // stripped so a var set on the manager can't silently reconfigure every
488
+ // child (see scrubbedParentEnv). Caller-supplied extras come next — the
489
+ // fixed per-child vars below always win so extraEnv can never clobber
490
+ // the seed/startup tokens or port wiring.
491
+ ...scrubbedParentEnv(),
349
492
  ...opts.extraEnv,
350
493
  CADRE_STARTUP_TOKEN: token,
351
494
  CADRE_HEALTH_PORT: String(ports.health),
352
495
  CADRE_METRICS_PORT: String(ports.metrics),
353
496
  CADRE_LISTEN_ADDRS: `/ip4/0.0.0.0/tcp/${ports.p2p}`,
354
497
  CADRE_SEED_TOKEN: seedToken,
498
+ // Pin each child's node-local state (trusted-owner anchor, retained
499
+ // cold-start dial targets) to its OWN workdir. This is the same value the
500
+ // cli would derive by default (the config file lives here too), but stated
501
+ // explicitly rather than relying on the scrub above (belt and suspenders).
502
+ CADRE_NODE_STATE_DIR: workdir,
355
503
  };
356
504
  if (heapMB !== undefined) {
357
505
  env.NODE_OPTIONS = `${process.env.NODE_OPTIONS ?? ''} --max-old-space-size=${heapMB}`.trim();
@@ -384,17 +532,16 @@ export class HostProcessOrchestrator {
384
532
  });
385
533
  }
386
534
  catch (err) {
387
- // Synchronous spawn failure — release the fd and the reserved ports
388
- // before propagating, so a bad-args bug doesn't leak resources.
535
+ // Synchronous spawn failure — close the fd before propagating. This is
536
+ // the ONLY fd-leak guard on this path: nothing between the `openSync`
537
+ // above and the `spawn` can throw, so no other catch is needed. Keep it
538
+ // that way, or add one. (The ports are the caller's to release.)
389
539
  closeSync(logFd);
390
- this.releasePorts(ports);
391
540
  throw err;
392
541
  }
393
542
  // Always release the parent's copy of the fd — the child has its own.
394
543
  closeSync(logFd);
395
544
  if (!child.pid) {
396
- // Spawn returned without a pid — release reservations and report.
397
- this.releasePorts(ports);
398
545
  throw new Error(`Failed to spawn child for container ${containerId}`);
399
546
  }
400
547
  child.unref();
@@ -421,7 +568,20 @@ export class HostProcessOrchestrator {
421
568
  }
422
569
  });
423
570
  this.handles.set(dockerId, handle);
424
- this.persist();
571
+ // Past this line the launch has SUCCEEDED: the child is running and this
572
+ // handle owns its ports. So the state mirror is best-effort — a throw here
573
+ // would reach the caller's unwind, which would release ports the live child
574
+ // is bound to and restore the handle this spawn just replaced, leaving two
575
+ // handles for one container and one of them holding unreserved ports. A
576
+ // lost write self-heals: the next persist() (any stop/remove/spawn)
577
+ // rewrites the whole map. Until then a manager restart would fail to
578
+ // re-attach this child, hence the log.
579
+ try {
580
+ this.persist();
581
+ }
582
+ catch (err) {
583
+ log('failed to persist state after launching container %s: %o', containerId, err);
584
+ }
425
585
  this.emitStateChange(handle);
426
586
  log('created container %s -> pid %d ports=%j', containerId, child.pid, handle.ports);
427
587
  return {
@@ -434,6 +594,79 @@ export class HostProcessOrchestrator {
434
594
  p2pPort: ports.p2p,
435
595
  };
436
596
  }
597
+ /**
598
+ * Drop any handle left over from a previous spawn of the same `containerId`
599
+ * and release its ports. Handles are keyed by the per-spawn `dockerId`, so
600
+ * without this a re-spawn (donated-node respawn) would strand the prior
601
+ * handle in the map forever, leaking four ports from a bounded range each
602
+ * time. Mirrors the same cleanup in `ensureOwnerNode`.
603
+ *
604
+ * DO NOT delete the workdir: the identity key and node-local stores
605
+ * (trusted-owner anchor, retained cold-start dial targets) live there and are
606
+ * the whole reason a respawn comes back as the same node. `launchChild`
607
+ * reuses the same workdir.
608
+ *
609
+ * NOTE: releasing the ports hands them straight back to the allocator, so a
610
+ * re-spawn while the *previous* child is still listening can bind-clash. Every
611
+ * caller today re-spawns only a container it has established is not running
612
+ * (`DonationService.respawn`, `ensureOwnerNode`). If a caller ever needs to
613
+ * replace a live child, stop it first — or hold the ports until its exit.
614
+ *
615
+ * **The drop is reversible.** It happens before the launch can fail, so the
616
+ * dropped handles are returned and every caller restores them via
617
+ * {@link restoreDroppedHandles} when the launch throws — otherwise the caller
618
+ * would be left holding a dockerId this orchestrator no longer knows, and the
619
+ * node's workdir could never be reclaimed. On a *successful* spawn the drop
620
+ * stands: `DonationService.abandonRespawn` depends on the old handle being
621
+ * gone by then.
622
+ */
623
+ dropStaleHandle(containerId) {
624
+ const dropped = [];
625
+ for (const h of this.handles.values()) {
626
+ if (h.containerId !== containerId)
627
+ continue;
628
+ log('dropping stale handle %s for container %s', h.dockerId, containerId);
629
+ this.releasePorts(h.ports);
630
+ this.handles.delete(h.dockerId);
631
+ dropped.push(h);
632
+ }
633
+ return dropped;
634
+ }
635
+ /**
636
+ * Inverse of {@link dropStaleHandle}, for a spawn that then failed: put each
637
+ * handle back in the map and re-reserve its four ports, leaving host state
638
+ * exactly as the failed attempt found it.
639
+ *
640
+ * **Precondition: the drop → launch window is synchronous.** Restoring is
641
+ * sound only because nothing can have taken those ports or run cleanup
642
+ * against the handle in between — `launchChild` contains no `await` and both
643
+ * callers resolve push credentials *before* their drop. `launchChild`'s half
644
+ * is enforced: its declared return type is not a Promise, so adding an
645
+ * `await` there is a compile error. The callers' half is not — an `await`
646
+ * slipped between a drop and its launch silently breaks this.
647
+ *
648
+ * No `persist()` here: `state.json` is rewritten only by `launchChild` and
649
+ * only *after* the new handle is stored, so throughout the failure window the
650
+ * on-disk state still lists the dropped handle — this restore realigns memory
651
+ * to disk rather than diverging from it.
652
+ *
653
+ * NOTE: a restored handle keeps `alive: true` even if its child exited while
654
+ * it was out of the map (`launchChild`'s exit listener looks the handle up by
655
+ * dockerId and finds nothing). Only reachable by re-spawning a container
656
+ * whose child is still live, which `dropStaleHandle`'s note above already
657
+ * forbids.
658
+ */
659
+ restoreDroppedHandles(dropped) {
660
+ for (const h of dropped) {
661
+ log('restoring dropped handle %s for container %s after failed launch', h.dockerId, h.containerId);
662
+ this.handles.set(h.dockerId, h);
663
+ this.reservePorts(h.ports);
664
+ }
665
+ }
666
+ /** A managed node's own directory under `rootDir` — config, log, storage, identity. */
667
+ workdirFor(containerId) {
668
+ return join(this.rootDir, containerId);
669
+ }
437
670
  /** Locate the owner node's handle, if one has been spawned. */
438
671
  findOwnerHandle() {
439
672
  for (const h of this.handles.values()) {
@@ -442,6 +675,20 @@ export class HostProcessOrchestrator {
442
675
  }
443
676
  return undefined;
444
677
  }
678
+ /**
679
+ * Inverse of {@link releasePorts} — hold a handle's whole port set against
680
+ * the allocator. Used both to rehydrate on `init` and to undo a drop whose
681
+ * launch then failed.
682
+ */
683
+ reservePorts(ports) {
684
+ this.portAllocator.markUsed(ports.health);
685
+ this.portAllocator.markUsed(ports.metrics);
686
+ this.portAllocator.markUsed(ports.p2p);
687
+ // `admin` is absent on handles persisted before this build; markUsed would
688
+ // otherwise put `undefined` in the used-set.
689
+ if (typeof ports.admin === 'number')
690
+ this.portAllocator.markUsed(ports.admin);
691
+ }
445
692
  releasePorts(ports) {
446
693
  this.portAllocator.release(ports.health);
447
694
  this.portAllocator.release(ports.metrics);
@@ -506,14 +753,10 @@ export class HostProcessOrchestrator {
506
753
  await this.stopContainer(dockerId);
507
754
  }
508
755
  this.releasePorts(handle.ports);
509
- // On Windows the OS releases the child's cwd handle asynchronously, so
510
- // retry rmSync to give the kernel a chance to drop it.
511
- try {
512
- rmSync(handle.workdir, { recursive: true, force: true, maxRetries: 20, retryDelay: 200 });
513
- }
514
- catch (err) {
515
- log('failed to remove workdir %s: %o', handle.workdir, err);
516
- }
756
+ // Longer retries than the other callers': this is the one path that has
757
+ // just killed a child which held this directory as its cwd, and on Windows
758
+ // the OS releases that handle asynchronously.
759
+ this.discardWorkdir(handle.workdir, { maxRetries: 20, retryDelay: 200 });
517
760
  this.handles.delete(dockerId);
518
761
  this.persist();
519
762
  }