@serfab/cadre-host 0.13.0 → 1.0.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 (62) hide show
  1. package/README.md +6 -4
  2. package/dist/bin/host.js +9 -1
  3. package/dist/bin/host.js.map +1 -1
  4. package/dist/donation/__tests__/fake-orchestrator.js +1 -1
  5. package/dist/donation/__tests__/fake-orchestrator.js.map +1 -1
  6. package/dist/donation/donation-service.d.ts +7 -2
  7. package/dist/donation/donation-service.js +16 -2
  8. package/dist/donation/donation-service.js.map +1 -1
  9. package/dist/donation/donation-supervisor.d.ts +12 -2
  10. package/dist/donation/donation-supervisor.js +25 -2
  11. package/dist/donation/donation-supervisor.js.map +1 -1
  12. package/dist/donation/types.d.ts +2 -1
  13. package/dist/donation/types.js.map +1 -1
  14. package/dist/installer/index.d.ts +9 -1
  15. package/dist/installer/index.js +5 -1
  16. package/dist/installer/index.js.map +1 -1
  17. package/dist/orchestrator/host-process-orchestrator.d.ts +71 -11
  18. package/dist/orchestrator/host-process-orchestrator.js +173 -80
  19. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  20. package/dist/orchestrator/port-allocator.d.ts +44 -2
  21. package/dist/orchestrator/port-allocator.js +63 -5
  22. package/dist/orchestrator/port-allocator.js.map +1 -1
  23. package/dist/orchestrator/port-probe.d.ts +15 -0
  24. package/dist/orchestrator/port-probe.js +22 -0
  25. package/dist/orchestrator/port-probe.js.map +1 -0
  26. package/dist/orchestrator/types.d.ts +13 -1
  27. package/dist/orchestrator/types.js.map +1 -1
  28. package/dist/server/routes/bootstrap-node-validation.d.ts +30 -11
  29. package/dist/server/routes/bootstrap-node-validation.js +32 -13
  30. package/dist/server/routes/bootstrap-node-validation.js.map +1 -1
  31. package/dist/server/server.d.ts +4 -1
  32. package/dist/server/server.js +36 -2
  33. package/dist/server/server.js.map +1 -1
  34. package/dist/ui/assets/{index-C-iks41M.js → index-CEoNRwM_.js} +3 -3
  35. package/dist/ui/assets/{index-C-iks41M.js.map → index-CEoNRwM_.js.map} +1 -1
  36. package/dist/ui/index.html +1 -1
  37. package/package.json +4 -4
  38. package/src/__tests__/orchestrator-env-scrub.test.ts +22 -0
  39. package/src/__tests__/orchestrator-node-identity.test.ts +4 -4
  40. package/src/__tests__/orchestrator-owner.test.ts +45 -2
  41. package/src/__tests__/orchestrator-ports.test.ts +172 -0
  42. package/src/__tests__/orchestrator.test.ts +190 -79
  43. package/src/bin/host.ts +9 -1
  44. package/src/donation/__tests__/donation-service.test.ts +1155 -1068
  45. package/src/donation/__tests__/donation-supervisor.test.ts +548 -510
  46. package/src/donation/__tests__/fake-orchestrator.ts +1 -1
  47. package/src/donation/donation-service.ts +22 -3
  48. package/src/donation/donation-supervisor.ts +25 -2
  49. package/src/donation/types.ts +2 -1
  50. package/src/installer/__tests__/installer.smoke.test.ts +263 -218
  51. package/src/installer/index.ts +327 -314
  52. package/src/orchestrator/host-process-orchestrator.ts +1250 -1143
  53. package/src/orchestrator/port-allocator.ts +148 -91
  54. package/src/orchestrator/port-probe.ts +31 -0
  55. package/src/orchestrator/types.ts +13 -1
  56. package/src/server/__tests__/bootstrap-node-validation.test.ts +12 -8
  57. package/src/server/__tests__/grants-route.test.ts +72 -4
  58. package/src/server/__tests__/nodes-route.test.ts +2 -2
  59. package/src/server/__tests__/publishers.test.ts +1 -1
  60. package/src/server/__tests__/status-route.test.ts +1 -1
  61. package/src/server/routes/bootstrap-node-validation.ts +32 -13
  62. package/src/server/server.ts +157 -122
@@ -1,91 +1,148 @@
1
- import type { NodePorts } from './types.js';
2
-
3
- /**
4
- * Range-based port tracker. Allocations are in-memory; on orchestrator
5
- * restart the caller rehydrates the used-set from persisted state via
6
- * `markUsed(port)` before serving new allocations.
7
- */
8
- export class PortAllocator {
9
- private readonly usedPorts = new Set<number>();
10
-
11
- constructor(
12
- private readonly start: number,
13
- private readonly end: number,
14
- ) {
15
- if (!Number.isInteger(start) || !Number.isInteger(end) || start <= 0 || end < start) {
16
- throw new Error(`Invalid port range: ${start}..${end}`);
17
- }
18
- }
19
-
20
- allocate(): number {
21
- for (let port = this.start; port <= this.end; port++) {
22
- if (!this.usedPorts.has(port)) {
23
- this.usedPorts.add(port);
24
- return port;
25
- }
26
- }
27
- throw new Error(`No available ports in range ${this.start}..${this.end}`);
28
- }
29
-
30
- release(port: number): void {
31
- this.usedPorts.delete(port);
32
- }
33
-
34
- /** Used during restart rehydration to reserve ports already in use. */
35
- markUsed(port: number): void {
36
- if (port < this.start || port > this.end) {
37
- return;
38
- }
39
- this.usedPorts.add(port);
40
- }
41
-
42
- has(port: number): boolean {
43
- return this.usedPorts.has(port);
44
- }
45
- }
46
-
47
- /**
48
- * Allocation order for a node's port set. Fixed so that swapping a caller onto
49
- * {@link allocateNodePorts} does not shift the ports an existing deployment
50
- * already handed out.
51
- */
52
- const NODE_PORT_KEYS = ['health', 'metrics', 'p2p', 'admin'] as const;
53
-
54
- /**
55
- * Allocate a full NodePorts set atomically — a mid-way failure (an exhausted
56
- * range) releases everything already taken rather than stranding the ports it
57
- * got before the throw. `overrides` supply a port instead of allocating one
58
- * (the owner node's p2p port, which is fixed by NAT config).
59
- *
60
- * Overrides are reserved FIRST, before any allocation, so an override that
61
- * happens to sit inside the managed range cannot also be handed out to another
62
- * key. Reserving is `markUsed`, a documented no-op outside the range — which is
63
- * the production case for the owner node's libp2p port, and why reserving first
64
- * leaves every real port assignment unchanged.
65
- */
66
- export function allocateNodePorts(
67
- allocator: PortAllocator,
68
- overrides?: Partial<NodePorts>,
69
- ): NodePorts {
70
- const reserved: number[] = [];
71
- const ports: Partial<NodePorts> = {};
72
- try {
73
- for (const key of NODE_PORT_KEYS) {
74
- const override = overrides?.[key];
75
- if (override === undefined) continue;
76
- allocator.markUsed(override);
77
- reserved.push(override);
78
- ports[key] = override;
79
- }
80
- for (const key of NODE_PORT_KEYS) {
81
- if (ports[key] !== undefined) continue;
82
- const port = allocator.allocate();
83
- reserved.push(port);
84
- ports[key] = port;
85
- }
86
- } catch (err) {
87
- for (const port of reserved) allocator.release(port);
88
- throw err;
89
- }
90
- return ports as NodePorts;
91
- }
1
+ import type { NodePorts } from './types.js';
2
+
3
+ /**
4
+ * Range-based port tracker. Allocations are in-memory; on orchestrator
5
+ * restart the caller rehydrates the used-set from persisted state via
6
+ * `markUsed(port)` before serving new allocations.
7
+ */
8
+ export class PortAllocator {
9
+ private readonly usedPorts = new Set<number>();
10
+
11
+ constructor(
12
+ private readonly start: number,
13
+ private readonly end: number,
14
+ ) {
15
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start <= 0 || end < start) {
16
+ throw new Error(`Invalid port range: ${start}..${end}`);
17
+ }
18
+ }
19
+
20
+ allocate(): number {
21
+ for (let port = this.start; port <= this.end; port++) {
22
+ if (!this.usedPorts.has(port)) {
23
+ this.usedPorts.add(port);
24
+ return port;
25
+ }
26
+ }
27
+ throw new Error(`No available ports in range ${this.start}..${this.end}`);
28
+ }
29
+
30
+ release(port: number): void {
31
+ this.usedPorts.delete(port);
32
+ }
33
+
34
+ /**
35
+ * Used during restart rehydration to reserve ports already in use. A no-op for a
36
+ * port outside the range, and for a non-integer: a handle persisted by an older
37
+ * build lacks the ports added since, and `undefined` must not enter the used-set.
38
+ */
39
+ markUsed(port: number): void {
40
+ if (!Number.isInteger(port) || port < this.start || port > this.end) {
41
+ return;
42
+ }
43
+ this.usedPorts.add(port);
44
+ }
45
+
46
+ has(port: number): boolean {
47
+ return this.usedPorts.has(port);
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Allocation order for a node's port set. Fixed so that swapping a caller onto
53
+ * {@link allocateNodePorts} does not shift the ports an existing deployment
54
+ * already handed out — which is also why a key added later goes on the end
55
+ * (`ws` came after the first four).
56
+ */
57
+ const NODE_PORT_KEYS = ['health', 'metrics', 'p2p', 'admin', 'ws'] as const;
58
+
59
+ /**
60
+ * Allocate a full NodePorts set atomically — a mid-way failure (an exhausted
61
+ * range) releases everything already taken rather than stranding the ports it
62
+ * got before the throw. `overrides` supply a port instead of allocating one
63
+ * (the owner node's p2p port, which is fixed by NAT config; a re-spawn's
64
+ * previous ports, see {@link reusedNodePorts}).
65
+ *
66
+ * Overrides are reserved FIRST, before any allocation, so an override that
67
+ * happens to sit inside the managed range cannot also be handed out to another
68
+ * key. Reserving is `markUsed`, a documented no-op outside the range — which is
69
+ * the production case for the owner node's libp2p port, and why reserving first
70
+ * leaves every real port assignment unchanged.
71
+ *
72
+ * NOTE: an override is trusted, not checked — `markUsed` does not refuse a port
73
+ * another handle already holds, nor two keys naming the same port. Safe for
74
+ * today's callers: a re-spawn's overrides were released by its own handle drop
75
+ * with no `await` in between, and the owner's `libp2pPort` can only collide if an
76
+ * operator configures it inside the range onto a port a node already holds. If a
77
+ * caller ever passes ports it did not just release, refuse an override that
78
+ * `allocator.has()` or that repeats another key's port.
79
+ */
80
+ export function allocateNodePorts(
81
+ allocator: PortAllocator,
82
+ overrides?: Partial<NodePorts>,
83
+ ): NodePorts {
84
+ const reserved: number[] = [];
85
+ const ports: Partial<NodePorts> = {};
86
+ try {
87
+ for (const key of NODE_PORT_KEYS) {
88
+ const override = overrides?.[key];
89
+ if (override === undefined) continue;
90
+ allocator.markUsed(override);
91
+ reserved.push(override);
92
+ ports[key] = override;
93
+ }
94
+ for (const key of NODE_PORT_KEYS) {
95
+ if (ports[key] !== undefined) continue;
96
+ const port = allocator.allocate();
97
+ reserved.push(port);
98
+ ports[key] = port;
99
+ }
100
+ } catch (err) {
101
+ for (const port of reserved) allocator.release(port);
102
+ throw err;
103
+ }
104
+ return ports as NodePorts;
105
+ }
106
+
107
+ /**
108
+ * Hold a node's whole port set against `allocator` — the inverse of
109
+ * {@link releaseNodePorts}. A key the set lacks is skipped (see `markUsed`).
110
+ */
111
+ export function reserveNodePorts(allocator: PortAllocator, ports: NodePorts): void {
112
+ for (const key of NODE_PORT_KEYS) allocator.markUsed(ports[key]);
113
+ }
114
+
115
+ /**
116
+ * Give a node's whole port set back to `allocator`. A key the set lacks releases
117
+ * nothing: deleting a value the used-set never held is a no-op.
118
+ */
119
+ export function releaseNodePorts(allocator: PortAllocator, ports: NodePorts): void {
120
+ for (const key of NODE_PORT_KEYS) allocator.release(ports[key]);
121
+ }
122
+
123
+ /**
124
+ * The ports a re-spawn comes back on: the set the dropped handle held, as
125
+ * {@link allocateNodePorts} overrides. `{}` when nothing was dropped (a first
126
+ * spawn, or a handle lost along with `state.json`), so every port is allocated
127
+ * fresh.
128
+ *
129
+ * Why a re-spawn must not simply take the lowest free ports: a requester with no
130
+ * address of its own (a phone) reaches a lent node only by dialing the address it
131
+ * was given, so a node that comes back on a different port is one that requester
132
+ * can no longer find.
133
+ *
134
+ * A key the dropped handle lacks — `ws` on a handle persisted by an older build —
135
+ * is left out, and so allocated fresh. When more than one handle was dropped (only
136
+ * possible from a `state.json` that already held duplicates), the last one stored
137
+ * wins and the others' ports stay released.
138
+ */
139
+ export function reusedNodePorts(dropped: readonly { ports: NodePorts }[]): Partial<NodePorts> {
140
+ const reused: Partial<NodePorts> = {};
141
+ const previous = dropped[dropped.length - 1]?.ports;
142
+ if (!previous) return reused;
143
+ for (const key of NODE_PORT_KEYS) {
144
+ const port = previous[key];
145
+ if (Number.isInteger(port)) reused[key] = port;
146
+ }
147
+ return reused;
148
+ }
@@ -0,0 +1,31 @@
1
+ import { createServer } from 'node:net';
2
+
3
+ /** One TCP port a child binds, on the address it binds it to. */
4
+ export interface PortBinding {
5
+ port: number;
6
+ host: string;
7
+ }
8
+
9
+ /**
10
+ * Resolve when `binding` can be bound right now; reject, naming the port and the
11
+ * OS error code, when it cannot. Binds briefly and closes again at once.
12
+ *
13
+ * Any bind error counts as "unavailable", not just `EADDRINUSE`: on Windows a
14
+ * port held with `SO_EXCLUSIVEADDRUSE` (which libuv sets on every TCP bind) can
15
+ * answer `EACCES` instead, and a child launched onto a port that fails either way
16
+ * would die on it.
17
+ */
18
+ export function assertPortFree(binding: PortBinding): Promise<void> {
19
+ return new Promise((resolve, reject) => {
20
+ const server = createServer();
21
+ server.once('error', (err: NodeJS.ErrnoException) => {
22
+ reject(new Error(
23
+ `port ${binding.port} on ${binding.host} is unavailable (${err.code ?? err.message})`,
24
+ { cause: err },
25
+ ));
26
+ });
27
+ server.listen({ port: binding.port, host: binding.host }, () => {
28
+ server.close(() => resolve());
29
+ });
30
+ });
31
+ }
@@ -42,13 +42,25 @@ export interface HostProcessConfig {
42
42
  */
43
43
  export type PushCredentialsResolver = () => Promise<PushCredentials | undefined>;
44
44
 
45
- /** Per-child allocated ports. `admin` carries the loopback admin channel (6.6). */
45
+ /**
46
+ * Per-child allocated ports. `admin` carries the loopback admin channel (6.6).
47
+ *
48
+ * A handle read back from a `state.json` written by an older build lacks every key
49
+ * added since, whatever this type says — the node-set helpers in `port-allocator.ts`
50
+ * skip a missing key rather than reserving `undefined`.
51
+ */
46
52
  export interface NodePorts {
47
53
  health: number;
48
54
  metrics: number;
55
+ /** libp2p TCP listener. */
49
56
  p2p: number;
50
57
  /** Loopback admin-channel port. Bound only by the owner node. */
51
58
  admin: number;
59
+ /**
60
+ * libp2p WebSocket listener. The one a phone dials: a phone's node has no TCP
61
+ * transport, so the `p2p` port is unreachable to it.
62
+ */
63
+ ws: number;
52
64
  }
53
65
 
54
66
  /** In-memory record per managed child. */
@@ -2,12 +2,14 @@
2
2
  * The host's `bootstrapNodes` rule — the requester addresses a donated node is
3
3
  * started with — exercised directly.
4
4
  *
5
- * This is one half of a **manual tripwire**: cadre-provider carries a
6
- * byte-identical copy of this rule
7
- * (`packages/cadre-provider/src/server/bootstrap-node-validation.ts`) and the table
8
- * below is the same table
5
+ * This is one half of a **manual tripwire**: cadre-provider carries an identical
6
+ * copy of this rule's per-entry half
7
+ * (`packages/cadre-provider/src/server/bootstrap-node-validation.ts`) and the
8
+ * per-entry rows below are the same rows
9
9
  * `packages/cadre-provider/src/server/__tests__/bootstrap-node-validation.test.ts`
10
- * pins that copy to. Neither suite can observe the other package — nothing here
10
+ * pins that copy to. The empty-list row differs on purpose: this host accepts an
11
+ * empty list (a phone requester dials its lent node instead), the provider still
12
+ * requires one. Neither suite can observe the other package — nothing here
11
13
  * imports cadre-provider's server module — so this does not detect a change made
12
14
  * over there; what it does is fail if *this* copy is changed, which is how an
13
15
  * editor is landed on the comment pointing at the other one.
@@ -50,9 +52,11 @@ describe('validateBootstrapNodes (the host copy of the address rule)', () => {
50
52
  expect(validateBootstrapNodes([relayed])).toEqual({ nodes: [relayed] });
51
53
  });
52
54
 
53
- it('treats an absent field and an empty list alike: the field is required', () => {
54
- expect(errorOf(undefined)).toBe('bootstrapNodes is required');
55
- expect(errorOf([])).toBe('bootstrapNodes is required');
55
+ // The one row that differs from cadre-provider's table: a requester with no address
56
+ // of its own (a phone) sends none and dials the lent node itself.
57
+ it('treats an absent field and an empty list alike: no addresses, nothing rejected', () => {
58
+ expect(validateBootstrapNodes(undefined)).toEqual({ nodes: [] });
59
+ expect(validateBootstrapNodes([])).toEqual({ nodes: [] });
56
60
  });
57
61
 
58
62
  it('rejects a non-array, and an array with a non-string element', () => {
@@ -7,7 +7,7 @@
7
7
  * the cross-package integration scenario.
8
8
  */
9
9
 
10
- import Fastify from 'fastify';
10
+ import type { FastifyInstance } from 'fastify';
11
11
  import { afterEach, beforeEach, describe, expect, it } from 'vitest';
12
12
  import { mkdtempSync, rmSync } from 'node:fs';
13
13
  import { tmpdir } from 'node:os';
@@ -22,6 +22,7 @@ import type {
22
22
 
23
23
  import { registerErrorHandler } from '../error-handler.js';
24
24
  import { registerGrantsRoutes } from '../routes/grants.js';
25
+ import { buildFastify } from '../server.js';
25
26
  import { DonationService } from '../../donation/donation-service.js';
26
27
  import { DonationStore } from '../../donation/donation-store.js';
27
28
  import { GrantService } from '../../donation/grant-service.js';
@@ -52,7 +53,7 @@ class FakeOrchestrator implements Orchestrator {
52
53
  }
53
54
 
54
55
  let tmpRoot: string;
55
- let app: ReturnType<typeof Fastify>;
56
+ let app: FastifyInstance;
56
57
  let grants: GrantService;
57
58
  let store: DonationStore;
58
59
  let token: string;
@@ -78,7 +79,8 @@ beforeEach(() => {
78
79
  token = grants.issue({ label: 'Alice', maxNodes: 2 }).token;
79
80
  store = new DonationStore(join(tmpRoot, 'donations'));
80
81
  const donations = new DonationService({ orchestrator: new FakeOrchestrator(), grants, store });
81
- app = Fastify();
82
+ // The production constructor, so these tests run with the same body parsing.
83
+ app = buildFastify();
82
84
  registerErrorHandler(app);
83
85
  registerGrantsRoutes(app, { donations, grants });
84
86
  });
@@ -182,7 +184,6 @@ describe('POST /grants', () => {
182
184
  // finds no transport for it, and the node is alone just the same.
183
185
  ['/p2p/12D3KooWA9hbnKrRnPRSPTRkzXqTHzGE8YpJ3JHZmQ5tGwLRTMmp'],
184
186
  [''],
185
- [],
186
187
  ];
187
188
  for (const bootstrapNodes of bad) {
188
189
  const res = await app.inject({
@@ -196,6 +197,20 @@ describe('POST /grants', () => {
196
197
  expect((list.json() as { data: { donations: unknown[] } }).data.donations).toHaveLength(0);
197
198
  });
198
199
 
200
+ // A phone has no address to give, so it sends none and dials the lent node itself:
201
+ // leaving the field out, or sending an empty list, provisions a node with no
202
+ // bootstrap peers rather than being rejected.
203
+ it('provisions with bootstrapNodes absent or empty → 201, recording an empty list', async () => {
204
+ const { bootstrapNodes: _bootstrapNodes, ...withoutBootstrap } = body;
205
+ for (const payload of [withoutBootstrap, { ...body, bootstrapNodes: [] }]) {
206
+ const res = await app.inject({ method: 'POST', url: '/grants', headers: bearer(token), payload });
207
+ expect(res.statusCode, `expected 201 for ${JSON.stringify(payload)}`).toBe(201);
208
+ const donation = (res.json() as { data: { donation: { id: string; bootstrapNodes?: string[] } } }).data.donation;
209
+ expect(donation.bootstrapNodes).toEqual([]);
210
+ expect(store.get(donation.id)?.bootstrapNodes).toEqual([]);
211
+ }
212
+ });
213
+
199
214
  it('rejects a non-string partyId → 400, rather than stringifying it into the child config', async () => {
200
215
  for (const partyId of [42, { id: 'party-P' }, ' ']) {
201
216
  const res = await app.inject({
@@ -323,4 +338,57 @@ describe('DELETE /grants/:id', () => {
323
338
  const one = await app.inject({ method: 'GET', url: `/grants/${id}`, headers: bearer(token) });
324
339
  expect((one.json() as { data: { donation: { status: string } } }).data.donation.status).toBe('terminated');
325
340
  });
341
+
342
+ // The phone app sent `content-type: application/json` on its body-less DELETE, and
343
+ // Fastify's default parser answered 400 FST_ERR_CTP_EMPTY_JSON_BODY — so the loan,
344
+ // and the host's node, kept running.
345
+ it('ends the loan when the DELETE declares JSON but sends no body', async () => {
346
+ const created = await app.inject({ method: 'POST', url: '/grants', headers: bearer(token), payload: body });
347
+ const id = (created.json() as { data: { donation: { id: string } } }).data.donation.id;
348
+
349
+ const del = await app.inject({
350
+ method: 'DELETE', url: `/grants/${id}`,
351
+ headers: { ...bearer(token), 'content-type': 'application/json' },
352
+ });
353
+ expect(del.statusCode).toBe(200);
354
+ expect(store.get(id)?.status).toBe('terminated');
355
+ });
356
+ });
357
+
358
+ describe('JSON body parsing (buildFastify)', () => {
359
+ const json = (t: string) => ({ ...bearer(t), 'content-type': 'application/json' });
360
+
361
+ it('treats a declared-JSON empty body as no body, so the route answers its own 400', async () => {
362
+ const res = await app.inject({ method: 'POST', url: '/grants', headers: json(token) });
363
+ expect(res.statusCode).toBe(400);
364
+ const error = (res.json() as { error: { code: string; message: string } }).error;
365
+ expect(error.code).toBe('invalid_request');
366
+ expect(error.message).toBe('partyId is required');
367
+ });
368
+
369
+ it('still rejects a non-empty malformed body → 400 FST_ERR_CTP_INVALID_JSON_BODY', async () => {
370
+ const res = await app.inject({ method: 'POST', url: '/grants', headers: json(token), payload: '{"partyId":' });
371
+ expect(res.statusCode).toBe(400);
372
+ expect((res.json() as { error: { code: string } }).error.code).toBe('FST_ERR_CTP_INVALID_JSON_BODY');
373
+ });
374
+
375
+ it('still refuses a prototype-poisoning body, as Fastify\'s own parser does', async () => {
376
+ const res = await app.inject({
377
+ method: 'POST', url: '/grants', headers: json(token),
378
+ payload: '{"partyId":"party-P","__proto__":{"polluted":true}}',
379
+ });
380
+ expect(res.statusCode).toBe(400);
381
+ expect((res.json() as { error: { code: string } }).error.code).toBe('FST_ERR_CTP_INVALID_JSON_BODY');
382
+ const list = await app.inject({ method: 'GET', url: '/grants', headers: bearer(token) });
383
+ expect((list.json() as { data: { donations: unknown[] } }).data.donations).toHaveLength(0);
384
+ });
385
+
386
+ it('parses a well-formed body with a charset parameter on the content type', async () => {
387
+ const res = await app.inject({
388
+ method: 'POST', url: '/grants',
389
+ headers: { ...bearer(token), 'content-type': 'application/json; charset=utf-8' },
390
+ payload: JSON.stringify(body),
391
+ });
392
+ expect(res.statusCode).toBe(201);
393
+ });
326
394
  });
@@ -85,7 +85,7 @@ const SAMPLE_NODE: ManagedNodeInfo = {
85
85
  status: 'running',
86
86
  spawnedAt: '2025-01-01T00:00:00Z',
87
87
  workdir: '',
88
- ports: { health: 11, metrics: 12, p2p: 13, admin: 14 },
88
+ ports: { health: 11, metrics: 12, p2p: 13, admin: 14, ws: 15 },
89
89
  };
90
90
 
91
91
  describe('/api/nodes routes', () => {
@@ -200,7 +200,7 @@ describe('/api/nodes — owner node start/restart', () => {
200
200
  status: 'running',
201
201
  spawnedAt: '2025-01-01T00:00:00Z',
202
202
  workdir: '',
203
- ports: { health: 1, metrics: 2, p2p: 4555, admin: 3 },
203
+ ports: { health: 1, metrics: 2, p2p: 4555, admin: 3, ws: 4 },
204
204
  owner: true,
205
205
  };
206
206
 
@@ -131,7 +131,7 @@ describe('publisher wiring', () => {
131
131
  status: 'stopped',
132
132
  spawnedAt: 'x',
133
133
  workdir: '/tmp',
134
- ports: { health: 1, metrics: 2, p2p: 3, admin: 4 },
134
+ ports: { health: 1, metrics: 2, p2p: 3, admin: 4, ws: 5 },
135
135
  });
136
136
  expect(received).toContainEqual({
137
137
  type: 'node-state-changed',
@@ -64,7 +64,7 @@ describe('GET /api/status', () => {
64
64
  status: 'running',
65
65
  spawnedAt: '2025-01-01T00:00:00Z',
66
66
  workdir: '/tmp/alice',
67
- ports: { health: 1, metrics: 2, p2p: 3, admin: 4 },
67
+ ports: { health: 1, metrics: 2, p2p: 3, admin: 4, ws: 5 },
68
68
  },
69
69
  ]),
70
70
  trustCircle: fakeTrustCircle({
@@ -4,12 +4,28 @@
4
4
  * (written into the child's `cadre.json` as `controlNetwork.bootstrapNodes` by
5
5
  * `orchestrator/host-process-orchestrator.ts`) and hands to `@libp2p/bootstrap`.
6
6
  *
7
- * Its own module rather than part of `grants.ts`: the rule is a duplicate of
8
- * cadre-provider's copy (`packages/cadre-provider/src/server/bootstrap-node-validation.ts`)
7
+ * Its own module rather than part of `grants.ts`: the per-entry rule is a duplicate
8
+ * of cadre-provider's copy (`packages/cadre-provider/src/server/bootstrap-node-validation.ts`)
9
9
  * and must stay identical to it, so it is worth reading, testing and changing on
10
10
  * its own, without a routing file around it — the same arrangement cadre-provider
11
11
  * uses for its restatement of cadre-core's owner-key rule.
12
12
  *
13
+ * ## An empty list is accepted — where this copy differs, on purpose
14
+ *
15
+ * The field may be absent or `[]`; cadre-provider's copy still requires at least one
16
+ * address. A lent node's requester is typically a phone, and a phone has no address
17
+ * to give — its node listens on nothing and can only dial out. Such a requester sends
18
+ * no addresses and dials the node itself, at the WebSocket address
19
+ * `GET /grants/:id/peer` reports. The node starts with no bootstrap peers and waits,
20
+ * and admits that first inbound connection because it holds no authorized members
21
+ * yet (`admitInboundControlConnection` / `authorizeInboundControlStream` in
22
+ * `cadre-core/src/cadre-node.ts`). A provider container has no such requester yet, so
23
+ * there an empty list is still the node-comes-up-alone failure described below
24
+ * (`backlog/feat-provider-drone-reachable-by-phone`).
25
+ *
26
+ * The difference is at the list level only: every entry that IS given must pass the
27
+ * rule below, which is identical in both packages.
28
+ *
13
29
  * ## The rule, and why each clause is there
14
30
  *
15
31
  * An entry is usable exactly when it is a string, parses as a multiaddr, carries
@@ -58,21 +74,22 @@
58
74
  * this rule: cadre-provider joins its list with `,` into `CADRE_BOOTSTRAP_NODES`
59
75
  * and cadre-cli's env loader splits it back on `,`, so an entry containing a comma
60
76
  * would silently become two addresses there. This host writes JSON rather than an
61
- * env var and so is not exposed to that, but the two rules are kept identical —
62
- * see the note about manual upkeep below.
77
+ * env var and so is not exposed to that, but the two per-entry rules are kept
78
+ * identical — see the note about manual upkeep below.
63
79
  *
64
80
  * Reachability is deliberately NOT checked: a well-formed address for a peer that
65
81
  * happens to be down is indistinguishable here from one that is up, and no
66
82
  * boundary check can tell them apart. This validates the *shape* the child must be
67
83
  * able to parse, nothing more.
68
84
  *
69
- * Keeping the two copies in step is **manual** — neither package can see the
70
- * other's rule, so no test can compare them. What the tests give instead is a
85
+ * Keeping the two per-entry rules in step is **manual** — neither package can see
86
+ * the other's rule, so no test can compare them. What the tests give instead is a
71
87
  * tripwire on each side: `../__tests__/bootstrap-node-validation.test.ts` here and
72
88
  * `packages/cadre-provider/src/server/__tests__/bootstrap-node-validation.test.ts`
73
- * there each pin their own copy to the same accept/reject table, so changing
74
- * either rule fails that package's own suite — and the comment above the rule you
75
- * just changed is what points at the other copy.
89
+ * there each pin their own copy to the same per-entry accept/reject table (the
90
+ * empty-list row is the one that differs), so changing either rule fails that
91
+ * package's own suite — and the comment above the rule you just changed is what
92
+ * points at the other copy.
76
93
  */
77
94
 
78
95
  import debug from 'debug';
@@ -155,8 +172,10 @@ function validateBootstrapNode(value: string): { node: string } | { error: strin
155
172
  }
156
173
 
157
174
  /**
158
- * Validate the required `bootstrapNodes` field of a provision request: a non-empty
175
+ * Validate the optional `bootstrapNodes` field of a provision request: absent, or an
159
176
  * array of dialable control-network addresses (see {@link validateBootstrapNode}).
177
+ * Absent and `[]` alike mean the requester dials the node itself — see "An empty list
178
+ * is accepted" in the module comment.
160
179
  *
161
180
  * Provisioning is the last point at which the requester can still fix a typo, so
162
181
  * the shape is checked here: without it a bad address is answered 201 and then
@@ -167,11 +186,11 @@ function validateBootstrapNode(value: string): { node: string } | { error: strin
167
186
  * Every rejection names the offending entry: with several addresses in one
168
187
  * request the message is the only thing that says WHICH one.
169
188
  *
170
- * @returns the trimmed addresses, so the provision request carries exactly what was validated.
189
+ * @returns the trimmed addresses (`[]` when none were given), so the provision request carries exactly what was validated.
171
190
  */
172
191
  export function validateBootstrapNodes(value: unknown): { nodes: string[] } | { error: string } {
173
- if (value === undefined || (Array.isArray(value) && value.length === 0)) {
174
- return { error: 'bootstrapNodes is required' };
192
+ if (value === undefined) {
193
+ return { nodes: [] };
175
194
  }
176
195
  if (!Array.isArray(value) || !value.every((entry): entry is string => typeof entry === 'string')) {
177
196
  return { error: 'bootstrapNodes must be an array of strings' };