@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,122 +1,157 @@
1
- /**
2
- * Fastify lifecycle for the cadre-host local UI.
3
- *
4
- * Bound to `127.0.0.1:<uiPort>` only — never `0.0.0.0`. On `EADDRINUSE`
5
- * tries the configured port and then nine consecutive ports. On total
6
- * failure the start() promise rejects with a clear message naming every
7
- * port that was attempted.
8
- *
9
- * Shutdown drains with a 5 s timeout, mirroring cadre-provider's pattern.
10
- */
11
-
12
- import Fastify, { type FastifyInstance } from 'fastify';
13
- import debug from 'debug';
14
-
15
- const log = debug('cadre:host:server');
16
-
17
- /** Hard cap on Fastify's drain phase during shutdown. */
18
- const SHUTDOWN_DRAIN_TIMEOUT_MS = 5000;
19
- /** Inclusive count of ports to try (config port + 9 alternates). */
20
- const PORT_FALLBACK_TRIES = 10;
21
- /** Loopback interface; never serve from 0.0.0.0. */
22
- const LOOPBACK_HOST = '127.0.0.1';
23
-
24
- export interface StartServerOptions {
25
- /** Preferred port. The server tries this then the next 9 on EADDRINUSE. */
26
- preferredPort: number;
27
- /**
28
- * Test override: when 0, lets the OS pick any free port (skips the
29
- * fallback loop). The returned `port` reflects the actual bound port.
30
- */
31
- forcePort?: 0;
32
- }
33
-
34
- export interface StartedServer {
35
- port: number;
36
- url: string;
37
- }
38
-
39
- export interface ShutdownOptions {
40
- /** Override the 5 s drain timeout (tests). */
41
- drainTimeoutMs?: number;
42
- }
43
-
44
- /**
45
- * Bind `app` to the loopback interface with port-fallback. Returns the
46
- * actually-bound port — the configured port may be in use.
47
- */
48
- export async function startListening(
49
- app: FastifyInstance,
50
- opts: StartServerOptions,
51
- ): Promise<StartedServer> {
52
- if (opts.forcePort === 0) {
53
- const address = await app.listen({ host: LOOPBACK_HOST, port: 0 });
54
- const port = parsePort(address);
55
- return { port, url: `http://${LOOPBACK_HOST}:${port}` };
56
- }
57
-
58
- const tried: number[] = [];
59
- let lastErr: Error | null = null;
60
- for (let i = 0; i < PORT_FALLBACK_TRIES; i++) {
61
- const port = opts.preferredPort + i;
62
- tried.push(port);
63
- try {
64
- const address = await app.listen({ host: LOOPBACK_HOST, port });
65
- const bound = parsePort(address);
66
- if (i > 0) {
67
- log('port %d in use; bound on fallback port %d', opts.preferredPort, bound);
68
- }
69
- return { port: bound, url: `http://${LOOPBACK_HOST}:${bound}` };
70
- } catch (err) {
71
- const code = (err as NodeJS.ErrnoException).code;
72
- if (code !== 'EADDRINUSE') {
73
- throw err;
74
- }
75
- lastErr = err as Error;
76
- log('port %d in use, trying next', port);
77
- }
78
- }
79
- throw new Error(
80
- `cadre-host: all ${PORT_FALLBACK_TRIES} candidate ports were in use ` +
81
- `(${tried.join(', ')}). Reconfigure uiPort in host.config.json. ` +
82
- `Last error: ${lastErr?.message ?? 'unknown'}`,
83
- );
84
- }
85
-
86
- /**
87
- * Close the server with a hard 5 s drain timeout. Idempotent — safe to call
88
- * from a SIGINT/SIGTERM handler that may fire twice.
89
- */
90
- export async function stopListening(
91
- app: FastifyInstance,
92
- opts: ShutdownOptions = {},
93
- ): Promise<void> {
94
- const drainMs = opts.drainTimeoutMs ?? SHUTDOWN_DRAIN_TIMEOUT_MS;
95
- let timer: ReturnType<typeof setTimeout> | undefined;
96
- const drain = app.close();
97
- const timeout = new Promise<'timeout'>((resolve) => {
98
- timer = setTimeout(() => resolve('timeout'), drainMs);
99
- });
100
- const outcome = await Promise.race([drain.then(() => 'drained' as const), timeout]);
101
- if (timer) clearTimeout(timer);
102
- if (outcome === 'timeout') {
103
- log('shutdown drain timeout after %dms', drainMs);
104
- }
105
- }
106
-
107
- /** Create a bare Fastify instance with the project's logging convention. */
108
- export function buildFastify(): FastifyInstance {
109
- return Fastify({
110
- // Stay quiet by default — request-level logs are noisy on a local UI.
111
- // Operators can opt in via the `debug` env var (cadre:host:*).
112
- logger: false,
113
- disableRequestLogging: true,
114
- });
115
- }
116
-
117
- function parsePort(address: string): number {
118
- // address is e.g. http://127.0.0.1:8765
119
- const m = address.match(/:(\d+)\/?$/);
120
- if (!m) throw new Error(`cadre-host: unable to parse port from listen address: ${address}`);
121
- return Number(m[1]);
122
- }
1
+ /**
2
+ * Fastify lifecycle for the cadre-host local UI.
3
+ *
4
+ * Bound to `127.0.0.1:<uiPort>` only — never `0.0.0.0`. On `EADDRINUSE`
5
+ * tries the configured port and then nine consecutive ports. On total
6
+ * failure the start() promise rejects with a clear message naming every
7
+ * port that was attempted.
8
+ *
9
+ * Shutdown drains with a 5 s timeout, mirroring cadre-provider's pattern.
10
+ */
11
+
12
+ import Fastify, { type FastifyInstance } from 'fastify';
13
+ import debug from 'debug';
14
+
15
+ const log = debug('cadre:host:server');
16
+
17
+ /** Hard cap on Fastify's drain phase during shutdown. */
18
+ const SHUTDOWN_DRAIN_TIMEOUT_MS = 5000;
19
+ /** Inclusive count of ports to try (config port + 9 alternates). */
20
+ const PORT_FALLBACK_TRIES = 10;
21
+ /** Loopback interface; never serve from 0.0.0.0. */
22
+ const LOOPBACK_HOST = '127.0.0.1';
23
+
24
+ export interface StartServerOptions {
25
+ /** Preferred port. The server tries this then the next 9 on EADDRINUSE. */
26
+ preferredPort: number;
27
+ /**
28
+ * Test override: when 0, lets the OS pick any free port (skips the
29
+ * fallback loop). The returned `port` reflects the actual bound port.
30
+ */
31
+ forcePort?: 0;
32
+ }
33
+
34
+ export interface StartedServer {
35
+ port: number;
36
+ url: string;
37
+ }
38
+
39
+ export interface ShutdownOptions {
40
+ /** Override the 5 s drain timeout (tests). */
41
+ drainTimeoutMs?: number;
42
+ }
43
+
44
+ /**
45
+ * Bind `app` to the loopback interface with port-fallback. Returns the
46
+ * actually-bound port — the configured port may be in use.
47
+ */
48
+ export async function startListening(
49
+ app: FastifyInstance,
50
+ opts: StartServerOptions,
51
+ ): Promise<StartedServer> {
52
+ if (opts.forcePort === 0) {
53
+ const address = await app.listen({ host: LOOPBACK_HOST, port: 0 });
54
+ const port = parsePort(address);
55
+ return { port, url: `http://${LOOPBACK_HOST}:${port}` };
56
+ }
57
+
58
+ const tried: number[] = [];
59
+ let lastErr: Error | null = null;
60
+ for (let i = 0; i < PORT_FALLBACK_TRIES; i++) {
61
+ const port = opts.preferredPort + i;
62
+ tried.push(port);
63
+ try {
64
+ const address = await app.listen({ host: LOOPBACK_HOST, port });
65
+ const bound = parsePort(address);
66
+ if (i > 0) {
67
+ log('port %d in use; bound on fallback port %d', opts.preferredPort, bound);
68
+ }
69
+ return { port: bound, url: `http://${LOOPBACK_HOST}:${bound}` };
70
+ } catch (err) {
71
+ const code = (err as NodeJS.ErrnoException).code;
72
+ if (code !== 'EADDRINUSE') {
73
+ throw err;
74
+ }
75
+ lastErr = err as Error;
76
+ log('port %d in use, trying next', port);
77
+ }
78
+ }
79
+ throw new Error(
80
+ `cadre-host: all ${PORT_FALLBACK_TRIES} candidate ports were in use ` +
81
+ `(${tried.join(', ')}). Reconfigure uiPort in host.config.json. ` +
82
+ `Last error: ${lastErr?.message ?? 'unknown'}`,
83
+ );
84
+ }
85
+
86
+ /**
87
+ * Close the server with a hard 5 s drain timeout. Idempotent — safe to call
88
+ * from a SIGINT/SIGTERM handler that may fire twice.
89
+ */
90
+ export async function stopListening(
91
+ app: FastifyInstance,
92
+ opts: ShutdownOptions = {},
93
+ ): Promise<void> {
94
+ const drainMs = opts.drainTimeoutMs ?? SHUTDOWN_DRAIN_TIMEOUT_MS;
95
+ let timer: ReturnType<typeof setTimeout> | undefined;
96
+ const drain = app.close();
97
+ const timeout = new Promise<'timeout'>((resolve) => {
98
+ timer = setTimeout(() => resolve('timeout'), drainMs);
99
+ });
100
+ const outcome = await Promise.race([drain.then(() => 'drained' as const), timeout]);
101
+ if (timer) clearTimeout(timer);
102
+ if (outcome === 'timeout') {
103
+ log('shutdown drain timeout after %dms', drainMs);
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Create a Fastify instance with the project's logging convention and the
109
+ * empty-body-tolerant JSON parser (see {@link acceptEmptyJsonBodies}).
110
+ */
111
+ export function buildFastify(): FastifyInstance {
112
+ const app = Fastify({
113
+ // Stay quiet by default — request-level logs are noisy on a local UI.
114
+ // Operators can opt in via the `debug` env var (cadre:host:*).
115
+ logger: false,
116
+ disableRequestLogging: true,
117
+ });
118
+ acceptEmptyJsonBodies(app);
119
+ return app;
120
+ }
121
+
122
+ /**
123
+ * Treat a request that declares `application/json` but carries no body as a
124
+ * request with no body (`request.body === undefined`), instead of Fastify's
125
+ * default `400 FST_ERR_CTP_EMPTY_JSON_BODY`.
126
+ *
127
+ * `/grants` is served to other people's clients, and sending the JSON content
128
+ * type on every request, body or not, is a common client habit — the phone app
129
+ * did it, and the refused body-less `DELETE /grants/:id` left the loan and its
130
+ * node running. Every route that reads a body already reads `request.body ?? {}`,
131
+ * so a route that needs a field still answers its own `invalid_request` naming it.
132
+ * A non-empty body goes to Fastify's own parser, so malformed JSON is still a 400
133
+ * and the prototype-poisoning checks are unchanged (`'error'` is Fastify's default
134
+ * for both).
135
+ */
136
+ function acceptEmptyJsonBodies(app: FastifyInstance): void {
137
+ // NOTE: 'error', 'error' mirrors Fastify's defaults for proto/constructor poisoning; if
138
+ // buildFastify ever sets `onProtoPoisoning` / `onConstructorPoisoning`, pass them here too.
139
+ const parseJson = app.getDefaultJsonParser('error', 'error');
140
+ app.removeContentTypeParser('application/json');
141
+ app.addContentTypeParser<string>('application/json', { parseAs: 'string' }, (request, body, done) => {
142
+ if (body.length === 0) {
143
+ done(null, undefined);
144
+ return;
145
+ }
146
+ // Typed as possibly promise-returning; Fastify's default parser is the
147
+ // callback form and answers through `done`.
148
+ void parseJson(request, body, done);
149
+ });
150
+ }
151
+
152
+ function parsePort(address: string): number {
153
+ // address is e.g. http://127.0.0.1:8765
154
+ const m = address.match(/:(\d+)\/?$/);
155
+ if (!m) throw new Error(`cadre-host: unable to parse port from listen address: ${address}`);
156
+ return Number(m[1]);
157
+ }