@serfab/cadre-host 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) 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/server/static.js +38 -38
  57. package/dist/strands/index.d.ts +7 -0
  58. package/dist/strands/index.js +6 -0
  59. package/dist/strands/index.js.map +1 -0
  60. package/dist/strands/strand-service.d.ts +50 -0
  61. package/dist/strands/strand-service.js +103 -0
  62. package/dist/strands/strand-service.js.map +1 -0
  63. package/dist/strands/types.d.ts +93 -0
  64. package/dist/strands/types.js +23 -0
  65. package/dist/strands/types.js.map +1 -0
  66. package/dist/ui/assets/index-BVoqLjyX.css +1 -0
  67. package/dist/ui/assets/index-C-iks41M.js +17 -0
  68. package/dist/ui/assets/index-C-iks41M.js.map +1 -0
  69. package/dist/ui/index.html +14 -14
  70. package/dist/update/release-key.d.ts +1 -1
  71. package/dist/update/release-key.js +1 -1
  72. package/package.json +5 -5
  73. package/service/cadre-host.service.tmpl +16 -16
  74. package/service/com.serfab.cadre-host.plist.tmpl +35 -35
  75. package/service/install-service.ps1 +98 -98
  76. package/service/uninstall-service.ps1 +19 -19
  77. package/src/__tests__/build-targets.test.ts +26 -0
  78. package/src/__tests__/cli-invite.smoke.test.ts +192 -192
  79. package/src/__tests__/cli-nat.smoke.test.ts +212 -212
  80. package/src/__tests__/cli.smoke.test.ts +46 -46
  81. package/src/__tests__/global-setup.ts +51 -0
  82. package/src/__tests__/host-owner.smoke.test.ts +123 -123
  83. package/src/__tests__/orchestrator-env-scrub.test.ts +140 -0
  84. package/src/__tests__/orchestrator-node-identity.test.ts +204 -0
  85. package/src/__tests__/orchestrator-owner.test.ts +198 -198
  86. package/src/__tests__/orchestrator-pin-keys.test.ts +153 -153
  87. package/src/__tests__/orchestrator-push.test.ts +145 -145
  88. package/src/__tests__/orchestrator.test.ts +951 -570
  89. package/src/auth/__tests__/duration.test.ts +28 -28
  90. package/src/auth/__tests__/self-label.test.ts +85 -0
  91. package/src/auth/__tests__/trust-circle-integration.test.ts +152 -147
  92. package/src/auth/__tests__/trust-circle-store.test.ts +115 -115
  93. package/src/auth/__tests__/trust-circle.test.ts +445 -401
  94. package/src/auth/duration.ts +33 -33
  95. package/src/auth/index.ts +21 -19
  96. package/src/auth/self-label.ts +74 -0
  97. package/src/auth/trust-circle-store.ts +155 -155
  98. package/src/auth/trust-circle.ts +45 -13
  99. package/src/auth/types.ts +99 -99
  100. package/src/bin/host.ts +1299 -1258
  101. package/src/donation/__tests__/donation-service.test.ts +1068 -290
  102. package/src/donation/__tests__/donation-supervisor.test.ts +510 -0
  103. package/src/donation/__tests__/fake-orchestrator.test.ts +168 -0
  104. package/src/donation/__tests__/fake-orchestrator.ts +225 -0
  105. package/src/donation/__tests__/grant-service.test.ts +213 -213
  106. package/src/donation/__tests__/grant-store.test.ts +113 -113
  107. package/src/donation/donation-service.ts +962 -392
  108. package/src/donation/donation-store.ts +171 -164
  109. package/src/donation/donation-supervisor.ts +388 -0
  110. package/src/donation/grant-service.ts +200 -200
  111. package/src/donation/grant-store.ts +152 -152
  112. package/src/donation/index.ts +64 -49
  113. package/src/donation/types.ts +243 -220
  114. package/src/index.ts +14 -0
  115. package/src/installer/__tests__/identity.test.ts +34 -34
  116. package/src/installer/__tests__/paths.test.ts +47 -47
  117. package/src/installer/__tests__/service-host.test.ts +62 -62
  118. package/src/installer/__tests__/wizard.test.ts +64 -64
  119. package/src/installer/identity.ts +49 -49
  120. package/src/installer/paths.ts +109 -109
  121. package/src/installer/platform.ts +27 -27
  122. package/src/installer/service-host/index.ts +21 -21
  123. package/src/installer/service-host/template.ts +21 -21
  124. package/src/installer/wizard.ts +103 -103
  125. package/src/nat/__tests__/address-resolver.test.ts +82 -82
  126. package/src/nat/__tests__/ddns-duckdns.test.ts +83 -83
  127. package/src/nat/__tests__/ddns-updater.test.ts +253 -253
  128. package/src/nat/__tests__/external-ip.test.ts +124 -124
  129. package/src/nat/__tests__/nat-service.test.ts +497 -497
  130. package/src/nat/__tests__/nat-store.test.ts +93 -93
  131. package/src/nat/__tests__/port-mapper.test.ts +191 -191
  132. package/src/nat/__tests__/reachability.test.ts +24 -24
  133. package/src/nat/__tests__/secrets.test.ts +178 -178
  134. package/src/nat/address-resolver.ts +51 -51
  135. package/src/nat/ddns/duckdns.ts +76 -76
  136. package/src/nat/ddns/index.ts +55 -55
  137. package/src/nat/ddns/updater.ts +243 -243
  138. package/src/nat/external-ip.ts +154 -154
  139. package/src/nat/index.ts +71 -71
  140. package/src/nat/nat-service.ts +501 -501
  141. package/src/nat/nat-store.ts +154 -154
  142. package/src/nat/port-mapper.ts +329 -329
  143. package/src/nat/reachability.ts +34 -34
  144. package/src/nat/secrets/file-store.ts +130 -130
  145. package/src/nat/secrets/index.ts +112 -112
  146. package/src/nat/secrets/keytar-store.ts +67 -67
  147. package/src/nat/types.ts +159 -159
  148. package/src/orchestrator/__tests__/node-identity.test.ts +62 -0
  149. package/src/orchestrator/host-process-orchestrator.ts +1133 -894
  150. package/src/orchestrator/index.ts +10 -10
  151. package/src/orchestrator/log-rotator.ts +53 -53
  152. package/src/orchestrator/node-identity.ts +40 -0
  153. package/src/orchestrator/pid-liveness.ts +24 -24
  154. package/src/orchestrator/port-allocator.ts +91 -43
  155. package/src/orchestrator/state-store.ts +90 -90
  156. package/src/orchestrator/types.ts +141 -141
  157. package/src/owner/__tests__/owner-node-client.test.ts +194 -194
  158. package/src/owner/index.ts +12 -12
  159. package/src/owner/owner-node-client.ts +259 -233
  160. package/src/push/__tests__/push.test.ts +90 -90
  161. package/src/push/index.ts +146 -146
  162. package/src/server/__tests__/bus.test.ts +38 -38
  163. package/src/server/__tests__/error-handler.test.ts +118 -118
  164. package/src/server/__tests__/grants-admin-route.test.ts +73 -73
  165. package/src/server/__tests__/grants-route.test.ts +263 -189
  166. package/src/server/__tests__/nodes-route.test.ts +259 -259
  167. package/src/server/__tests__/origin-guard.test.ts +72 -72
  168. package/src/server/__tests__/publishers.test.ts +216 -216
  169. package/src/server/__tests__/server.smoke.test.ts +253 -253
  170. package/src/server/__tests__/settings-route.test.ts +194 -194
  171. package/src/server/__tests__/sse-route.test.ts +119 -119
  172. package/src/server/__tests__/static.test.ts +145 -145
  173. package/src/server/__tests__/status-route.test.ts +134 -134
  174. package/src/server/__tests__/strands-route.test.ts +233 -0
  175. package/src/server/error-handler.ts +178 -155
  176. package/src/server/events/bus.ts +42 -42
  177. package/src/server/events/sse-route.ts +81 -81
  178. package/src/server/events/types.ts +23 -22
  179. package/src/server/index.ts +267 -254
  180. package/src/server/origin-guard.ts +84 -84
  181. package/src/server/routes/grants-admin.ts +41 -41
  182. package/src/server/routes/grants.ts +210 -186
  183. package/src/server/routes/nat.ts +63 -63
  184. package/src/server/routes/nodes.ts +170 -170
  185. package/src/server/routes/settings.ts +123 -123
  186. package/src/server/routes/status.ts +118 -118
  187. package/src/server/routes/strands.ts +54 -0
  188. package/src/server/routes/trust-circle.ts +49 -49
  189. package/src/server/routes/update.ts +43 -43
  190. package/src/server/server.ts +122 -122
  191. package/src/server/settings-store.ts +37 -37
  192. package/src/server/static.ts +207 -207
  193. package/src/strands/__tests__/strand-service.test.ts +165 -0
  194. package/src/strands/index.ts +14 -0
  195. package/src/strands/strand-service.ts +135 -0
  196. package/src/strands/types.ts +102 -0
  197. package/src/update/__tests__/apply.test.ts +158 -158
  198. package/src/update/__tests__/manifest.test.ts +128 -128
  199. package/src/update/__tests__/release-key.test.ts +42 -42
  200. package/src/update/__tests__/sign.test.ts +78 -78
  201. package/src/update/__tests__/store.test.ts +81 -81
  202. package/src/update/__tests__/update-service.integration.test.ts +256 -256
  203. package/src/update/__tests__/version.test.ts +31 -31
  204. package/src/update/apply.ts +190 -190
  205. package/src/update/index.ts +341 -341
  206. package/src/update/release-key.ts +71 -71
  207. package/src/update/sign.ts +74 -74
  208. package/src/update/store.ts +101 -101
  209. package/src/update/types.ts +109 -109
  210. package/src/update/version.ts +80 -80
  211. package/dist/ui/assets/index-BlMXQPSw.js +0 -14
  212. package/dist/ui/assets/index-BlMXQPSw.js.map +0 -1
  213. package/dist/ui/assets/index-BwU5mJGF.css +0 -1
@@ -1,259 +1,259 @@
1
- import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from 'node:fs';
2
- import { tmpdir } from 'node:os';
3
- import { join } from 'node:path';
4
-
5
- import Fastify from 'fastify';
6
- import { describe, it, expect, beforeEach, afterEach } from 'vitest';
7
-
8
- import { EventBus } from '../events/bus.js';
9
- import { registerErrorHandler } from '../error-handler.js';
10
- import { registerNodesRoutes, tailLogFile } from '../routes/nodes.js';
11
- import type { HostProcessOrchestrator } from '../../orchestrator/index.js';
12
- import type { ManagedNodeInfo, NodeStateListener } from '../../orchestrator/types.js';
13
-
14
- interface FakeOrchestrator extends HostProcessOrchestrator {
15
- __nodes: Map<string, ManagedNodeInfo>;
16
- __listeners: Set<NodeStateListener>;
17
- __stoppedDockerIds: string[];
18
- __ensured: number;
19
- __restarted: number;
20
- }
21
-
22
- function fakeOrchestrator(
23
- initial: ManagedNodeInfo[] = [],
24
- opts: { ownerId?: string; hasOwnerConfig?: boolean } = {},
25
- ): FakeOrchestrator {
26
- const nodes = new Map(initial.map((n) => [n.dockerId, n]));
27
- const listeners = new Set<NodeStateListener>();
28
- const stopped: string[] = [];
29
- const counters = { ensured: 0, restarted: 0 };
30
- const findById = (id: string): ManagedNodeInfo | undefined => {
31
- const direct = nodes.get(id);
32
- if (direct) return direct;
33
- for (const n of nodes.values()) if (n.id === id) return n;
34
- return undefined;
35
- };
36
- const inst = {
37
- listNodes: () => [...nodes.values()],
38
- getNode: (id: string) => findById(id),
39
- resolveDockerId: (id: string) => {
40
- if (nodes.has(id)) return id;
41
- for (const n of nodes.values()) if (n.id === id) return n.dockerId;
42
- return undefined;
43
- },
44
- isOwnerNode: (id: string) => {
45
- if (!opts.ownerId) return false;
46
- const node = findById(id);
47
- return id === opts.ownerId || node?.id === opts.ownerId;
48
- },
49
- hasOwnerConfig: () => opts.hasOwnerConfig ?? false,
50
- ensureOwnerNode: async () => {
51
- counters.ensured++;
52
- const node = opts.ownerId ? findById(opts.ownerId) : undefined;
53
- return node ?? { id: opts.ownerId, status: 'running' } as unknown as ManagedNodeInfo;
54
- },
55
- restartOwnerNode: async () => {
56
- counters.restarted++;
57
- const node = opts.ownerId ? findById(opts.ownerId) : undefined;
58
- return node ?? { id: opts.ownerId, status: 'running' } as unknown as ManagedNodeInfo;
59
- },
60
- onStateChange: (l: NodeStateListener) => { listeners.add(l); return () => { listeners.delete(l); }; },
61
- stopContainer: async (dockerId: string) => {
62
- stopped.push(dockerId);
63
- const node = nodes.get(dockerId);
64
- if (node) {
65
- const next: ManagedNodeInfo = { ...node, status: 'stopped' };
66
- nodes.set(dockerId, next);
67
- for (const l of listeners) l(next);
68
- }
69
- },
70
- getStats: async () => ({ cpuPercent: 1, memoryBytes: 2, networkRxBytes: 3, networkTxBytes: 4 }),
71
- __nodes: nodes,
72
- __listeners: listeners,
73
- __stoppedDockerIds: stopped,
74
- get __ensured() { return counters.ensured; },
75
- get __restarted() { return counters.restarted; },
76
- } as unknown as FakeOrchestrator;
77
- return inst;
78
- }
79
-
80
- const SAMPLE_NODE: ManagedNodeInfo = {
81
- id: 'alice',
82
- dockerId: '12345:abcdef',
83
- partyId: 'party-alice',
84
- profile: 'storage',
85
- status: 'running',
86
- spawnedAt: '2025-01-01T00:00:00Z',
87
- workdir: '',
88
- ports: { health: 11, metrics: 12, p2p: 13, admin: 14 },
89
- };
90
-
91
- describe('/api/nodes routes', () => {
92
- let app: ReturnType<typeof Fastify>;
93
- let bus: EventBus;
94
- let orchestrator: FakeOrchestrator;
95
- let workdir: string;
96
-
97
- beforeEach(async () => {
98
- workdir = mkdtempSync(join(tmpdir(), 'cadre-host-nodes-'));
99
- bus = new EventBus();
100
- app = Fastify();
101
- registerErrorHandler(app);
102
- orchestrator = fakeOrchestrator([{ ...SAMPLE_NODE, workdir }]);
103
- registerNodesRoutes(app, { orchestrator });
104
- // Mirror what createLocalUiServer.start() does — forward orchestrator
105
- // state changes onto the bus. The route itself doesn't publish; the
106
- // listener is the single publication point.
107
- orchestrator.onStateChange((info) => {
108
- bus.publish({
109
- type: 'node-state-changed',
110
- nodeId: info.id,
111
- status: info.status === 'running' ? 'running' : 'stopped',
112
- });
113
- });
114
- });
115
-
116
- afterEach(async () => {
117
- await app.close();
118
- rmSync(workdir, { recursive: true, force: true });
119
- });
120
-
121
- it('GET /api/nodes lists known nodes', async () => {
122
- const res = await app.inject({ method: 'GET', url: '/api/nodes' });
123
- expect(res.statusCode).toBe(200);
124
- const body = res.json() as { ok: boolean; data: { nodes: Array<{ id: string }> } };
125
- expect(body.ok).toBe(true);
126
- expect(body.data.nodes).toHaveLength(1);
127
- expect(body.data.nodes[0]?.id).toBe('alice');
128
- });
129
-
130
- it('GET /api/nodes/:id returns details with stats', async () => {
131
- const res = await app.inject({ method: 'GET', url: '/api/nodes/alice' });
132
- expect(res.statusCode).toBe(200);
133
- const body = res.json() as { data: { node: { id: string }; stats: { cpuPercent: number } } };
134
- expect(body.data.node.id).toBe('alice');
135
- expect(body.data.stats.cpuPercent).toBe(1);
136
- });
137
-
138
- it('GET /api/nodes/:id 404 for unknown', async () => {
139
- const res = await app.inject({ method: 'GET', url: '/api/nodes/nobody' });
140
- expect(res.statusCode).toBe(404);
141
- const body = res.json() as { ok: boolean; error: { code: string } };
142
- expect(body.error.code).toBe('not_found');
143
- });
144
-
145
- it('GET /api/nodes/:id/logs returns tail of node.log', async () => {
146
- // Mirror the orchestrator's defaultLogPath layout: <workdir>/node.log
147
- writeFileSync(join(workdir, 'node.log'), 'one\ntwo\nthree\nfour\nfive\n', 'utf8');
148
- const res = await app.inject({ method: 'GET', url: '/api/nodes/alice/logs?lines=2' });
149
- expect(res.statusCode).toBe(200);
150
- const body = res.json() as { data: { lines: string[] } };
151
- expect(body.data.lines).toEqual(['four', 'five']);
152
- });
153
-
154
- it('GET /api/nodes/:id/logs returns [] when log file missing', async () => {
155
- const res = await app.inject({ method: 'GET', url: '/api/nodes/alice/logs' });
156
- expect(res.statusCode).toBe(200);
157
- const body = res.json() as { data: { lines: string[] } };
158
- expect(body.data.lines).toEqual([]);
159
- });
160
-
161
- it('POST /api/nodes/:id/stop calls orchestrator and publishes exactly one event via the listener', async () => {
162
- const events: unknown[] = [];
163
- bus.subscribe((e) => events.push(e));
164
- const res = await app.inject({ method: 'POST', url: '/api/nodes/alice/stop' });
165
- expect(res.statusCode).toBe(200);
166
- expect(orchestrator.__stoppedDockerIds).toContain(SAMPLE_NODE.dockerId);
167
- // Exactly one event — the orchestrator listener publishes; the route
168
- // does not re-publish (regression guard).
169
- expect(events).toEqual([
170
- { type: 'node-state-changed', nodeId: 'alice', status: 'stopped' },
171
- ]);
172
- });
173
-
174
- it('POST /api/nodes/:id/start on a non-owner node returns 501 not_implemented', async () => {
175
- const res = await app.inject({ method: 'POST', url: '/api/nodes/alice/start' });
176
- expect(res.statusCode).toBe(501);
177
- const body = res.json() as { error: { code: string } };
178
- expect(body.error.code).toBe('not_implemented');
179
- });
180
-
181
- it('POST /api/nodes/:id/restart on a non-owner node returns 501 not_implemented', async () => {
182
- const res = await app.inject({ method: 'POST', url: '/api/nodes/alice/restart' });
183
- expect(res.statusCode).toBe(501);
184
- });
185
-
186
- it('POST /api/nodes/:id/start on an unknown node returns 404', async () => {
187
- const res = await app.inject({ method: 'POST', url: '/api/nodes/nobody/start' });
188
- expect(res.statusCode).toBe(404);
189
- const body = res.json() as { error: { code: string } };
190
- expect(body.error.code).toBe('not_found');
191
- });
192
- });
193
-
194
- describe('/api/nodes — owner node start/restart', () => {
195
- const OWNER_NODE: ManagedNodeInfo = {
196
- id: 'owner',
197
- dockerId: '999:tok',
198
- partyId: 'install-id',
199
- profile: 'storage',
200
- status: 'running',
201
- spawnedAt: '2025-01-01T00:00:00Z',
202
- workdir: '',
203
- ports: { health: 1, metrics: 2, p2p: 4555, admin: 3 },
204
- owner: true,
205
- };
206
-
207
- let app: ReturnType<typeof Fastify>;
208
- let orchestrator: FakeOrchestrator;
209
-
210
- beforeEach(() => {
211
- app = Fastify();
212
- registerErrorHandler(app);
213
- orchestrator = fakeOrchestrator([OWNER_NODE], { ownerId: 'owner', hasOwnerConfig: true });
214
- registerNodesRoutes(app, { orchestrator });
215
- });
216
-
217
- afterEach(async () => { await app.close(); });
218
-
219
- it('start ensures the owner node', async () => {
220
- const res = await app.inject({ method: 'POST', url: '/api/nodes/owner/start' });
221
- expect(res.statusCode).toBe(200);
222
- expect(orchestrator.__ensured).toBe(1);
223
- });
224
-
225
- it('restart re-spawns the owner node', async () => {
226
- const res = await app.inject({ method: 'POST', url: '/api/nodes/owner/restart' });
227
- expect(res.statusCode).toBe(200);
228
- expect(orchestrator.__restarted).toBe(1);
229
- });
230
-
231
- it('start returns 501 when there is no saved owner config', async () => {
232
- const app2 = Fastify();
233
- registerErrorHandler(app2);
234
- const orch2 = fakeOrchestrator([OWNER_NODE], { ownerId: 'owner', hasOwnerConfig: false });
235
- registerNodesRoutes(app2, { orchestrator: orch2 });
236
- const res = await app2.inject({ method: 'POST', url: '/api/nodes/owner/start' });
237
- expect(res.statusCode).toBe(501);
238
- await app2.close();
239
- });
240
- });
241
-
242
- describe('tailLogFile', () => {
243
- it('returns [] for missing file', () => {
244
- expect(tailLogFile(join(tmpdir(), 'definitely-not-here-' + Date.now()), 10)).toEqual([]);
245
- });
246
-
247
- it('returns the last N lines from a multi-line file', () => {
248
- const dir = mkdtempSync(join(tmpdir(), 'cadre-host-tail-'));
249
- mkdirSync(dir, { recursive: true });
250
- const path = join(dir, 'sample.log');
251
- writeFileSync(path, Array.from({ length: 50 }, (_, i) => `line-${i + 1}`).join('\n') + '\n', 'utf8');
252
- try {
253
- const last3 = tailLogFile(path, 3);
254
- expect(last3).toEqual(['line-48', 'line-49', 'line-50']);
255
- } finally {
256
- rmSync(dir, { recursive: true, force: true });
257
- }
258
- });
259
- });
1
+ import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+
5
+ import Fastify from 'fastify';
6
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
7
+
8
+ import { EventBus } from '../events/bus.js';
9
+ import { registerErrorHandler } from '../error-handler.js';
10
+ import { registerNodesRoutes, tailLogFile } from '../routes/nodes.js';
11
+ import type { HostProcessOrchestrator } from '../../orchestrator/index.js';
12
+ import type { ManagedNodeInfo, NodeStateListener } from '../../orchestrator/types.js';
13
+
14
+ interface FakeOrchestrator extends HostProcessOrchestrator {
15
+ __nodes: Map<string, ManagedNodeInfo>;
16
+ __listeners: Set<NodeStateListener>;
17
+ __stoppedDockerIds: string[];
18
+ __ensured: number;
19
+ __restarted: number;
20
+ }
21
+
22
+ function fakeOrchestrator(
23
+ initial: ManagedNodeInfo[] = [],
24
+ opts: { ownerId?: string; hasOwnerConfig?: boolean } = {},
25
+ ): FakeOrchestrator {
26
+ const nodes = new Map(initial.map((n) => [n.dockerId, n]));
27
+ const listeners = new Set<NodeStateListener>();
28
+ const stopped: string[] = [];
29
+ const counters = { ensured: 0, restarted: 0 };
30
+ const findById = (id: string): ManagedNodeInfo | undefined => {
31
+ const direct = nodes.get(id);
32
+ if (direct) return direct;
33
+ for (const n of nodes.values()) if (n.id === id) return n;
34
+ return undefined;
35
+ };
36
+ const inst = {
37
+ listNodes: () => [...nodes.values()],
38
+ getNode: (id: string) => findById(id),
39
+ resolveDockerId: (id: string) => {
40
+ if (nodes.has(id)) return id;
41
+ for (const n of nodes.values()) if (n.id === id) return n.dockerId;
42
+ return undefined;
43
+ },
44
+ isOwnerNode: (id: string) => {
45
+ if (!opts.ownerId) return false;
46
+ const node = findById(id);
47
+ return id === opts.ownerId || node?.id === opts.ownerId;
48
+ },
49
+ hasOwnerConfig: () => opts.hasOwnerConfig ?? false,
50
+ ensureOwnerNode: async () => {
51
+ counters.ensured++;
52
+ const node = opts.ownerId ? findById(opts.ownerId) : undefined;
53
+ return node ?? { id: opts.ownerId, status: 'running' } as unknown as ManagedNodeInfo;
54
+ },
55
+ restartOwnerNode: async () => {
56
+ counters.restarted++;
57
+ const node = opts.ownerId ? findById(opts.ownerId) : undefined;
58
+ return node ?? { id: opts.ownerId, status: 'running' } as unknown as ManagedNodeInfo;
59
+ },
60
+ onStateChange: (l: NodeStateListener) => { listeners.add(l); return () => { listeners.delete(l); }; },
61
+ stopContainer: async (dockerId: string) => {
62
+ stopped.push(dockerId);
63
+ const node = nodes.get(dockerId);
64
+ if (node) {
65
+ const next: ManagedNodeInfo = { ...node, status: 'stopped' };
66
+ nodes.set(dockerId, next);
67
+ for (const l of listeners) l(next);
68
+ }
69
+ },
70
+ getStats: async () => ({ cpuPercent: 1, memoryBytes: 2, networkRxBytes: 3, networkTxBytes: 4 }),
71
+ __nodes: nodes,
72
+ __listeners: listeners,
73
+ __stoppedDockerIds: stopped,
74
+ get __ensured() { return counters.ensured; },
75
+ get __restarted() { return counters.restarted; },
76
+ } as unknown as FakeOrchestrator;
77
+ return inst;
78
+ }
79
+
80
+ const SAMPLE_NODE: ManagedNodeInfo = {
81
+ id: 'alice',
82
+ dockerId: '12345:abcdef',
83
+ partyId: 'party-alice',
84
+ profile: 'storage',
85
+ status: 'running',
86
+ spawnedAt: '2025-01-01T00:00:00Z',
87
+ workdir: '',
88
+ ports: { health: 11, metrics: 12, p2p: 13, admin: 14 },
89
+ };
90
+
91
+ describe('/api/nodes routes', () => {
92
+ let app: ReturnType<typeof Fastify>;
93
+ let bus: EventBus;
94
+ let orchestrator: FakeOrchestrator;
95
+ let workdir: string;
96
+
97
+ beforeEach(async () => {
98
+ workdir = mkdtempSync(join(tmpdir(), 'cadre-host-nodes-'));
99
+ bus = new EventBus();
100
+ app = Fastify();
101
+ registerErrorHandler(app);
102
+ orchestrator = fakeOrchestrator([{ ...SAMPLE_NODE, workdir }]);
103
+ registerNodesRoutes(app, { orchestrator });
104
+ // Mirror what createLocalUiServer.start() does — forward orchestrator
105
+ // state changes onto the bus. The route itself doesn't publish; the
106
+ // listener is the single publication point.
107
+ orchestrator.onStateChange((info) => {
108
+ bus.publish({
109
+ type: 'node-state-changed',
110
+ nodeId: info.id,
111
+ status: info.status === 'running' ? 'running' : 'stopped',
112
+ });
113
+ });
114
+ });
115
+
116
+ afterEach(async () => {
117
+ await app.close();
118
+ rmSync(workdir, { recursive: true, force: true });
119
+ });
120
+
121
+ it('GET /api/nodes lists known nodes', async () => {
122
+ const res = await app.inject({ method: 'GET', url: '/api/nodes' });
123
+ expect(res.statusCode).toBe(200);
124
+ const body = res.json() as { ok: boolean; data: { nodes: Array<{ id: string }> } };
125
+ expect(body.ok).toBe(true);
126
+ expect(body.data.nodes).toHaveLength(1);
127
+ expect(body.data.nodes[0]?.id).toBe('alice');
128
+ });
129
+
130
+ it('GET /api/nodes/:id returns details with stats', async () => {
131
+ const res = await app.inject({ method: 'GET', url: '/api/nodes/alice' });
132
+ expect(res.statusCode).toBe(200);
133
+ const body = res.json() as { data: { node: { id: string }; stats: { cpuPercent: number } } };
134
+ expect(body.data.node.id).toBe('alice');
135
+ expect(body.data.stats.cpuPercent).toBe(1);
136
+ });
137
+
138
+ it('GET /api/nodes/:id 404 for unknown', async () => {
139
+ const res = await app.inject({ method: 'GET', url: '/api/nodes/nobody' });
140
+ expect(res.statusCode).toBe(404);
141
+ const body = res.json() as { ok: boolean; error: { code: string } };
142
+ expect(body.error.code).toBe('not_found');
143
+ });
144
+
145
+ it('GET /api/nodes/:id/logs returns tail of node.log', async () => {
146
+ // Mirror the orchestrator's defaultLogPath layout: <workdir>/node.log
147
+ writeFileSync(join(workdir, 'node.log'), 'one\ntwo\nthree\nfour\nfive\n', 'utf8');
148
+ const res = await app.inject({ method: 'GET', url: '/api/nodes/alice/logs?lines=2' });
149
+ expect(res.statusCode).toBe(200);
150
+ const body = res.json() as { data: { lines: string[] } };
151
+ expect(body.data.lines).toEqual(['four', 'five']);
152
+ });
153
+
154
+ it('GET /api/nodes/:id/logs returns [] when log file missing', async () => {
155
+ const res = await app.inject({ method: 'GET', url: '/api/nodes/alice/logs' });
156
+ expect(res.statusCode).toBe(200);
157
+ const body = res.json() as { data: { lines: string[] } };
158
+ expect(body.data.lines).toEqual([]);
159
+ });
160
+
161
+ it('POST /api/nodes/:id/stop calls orchestrator and publishes exactly one event via the listener', async () => {
162
+ const events: unknown[] = [];
163
+ bus.subscribe((e) => events.push(e));
164
+ const res = await app.inject({ method: 'POST', url: '/api/nodes/alice/stop' });
165
+ expect(res.statusCode).toBe(200);
166
+ expect(orchestrator.__stoppedDockerIds).toContain(SAMPLE_NODE.dockerId);
167
+ // Exactly one event — the orchestrator listener publishes; the route
168
+ // does not re-publish (regression guard).
169
+ expect(events).toEqual([
170
+ { type: 'node-state-changed', nodeId: 'alice', status: 'stopped' },
171
+ ]);
172
+ });
173
+
174
+ it('POST /api/nodes/:id/start on a non-owner node returns 501 not_implemented', async () => {
175
+ const res = await app.inject({ method: 'POST', url: '/api/nodes/alice/start' });
176
+ expect(res.statusCode).toBe(501);
177
+ const body = res.json() as { error: { code: string } };
178
+ expect(body.error.code).toBe('not_implemented');
179
+ });
180
+
181
+ it('POST /api/nodes/:id/restart on a non-owner node returns 501 not_implemented', async () => {
182
+ const res = await app.inject({ method: 'POST', url: '/api/nodes/alice/restart' });
183
+ expect(res.statusCode).toBe(501);
184
+ });
185
+
186
+ it('POST /api/nodes/:id/start on an unknown node returns 404', async () => {
187
+ const res = await app.inject({ method: 'POST', url: '/api/nodes/nobody/start' });
188
+ expect(res.statusCode).toBe(404);
189
+ const body = res.json() as { error: { code: string } };
190
+ expect(body.error.code).toBe('not_found');
191
+ });
192
+ });
193
+
194
+ describe('/api/nodes — owner node start/restart', () => {
195
+ const OWNER_NODE: ManagedNodeInfo = {
196
+ id: 'owner',
197
+ dockerId: '999:tok',
198
+ partyId: 'install-id',
199
+ profile: 'storage',
200
+ status: 'running',
201
+ spawnedAt: '2025-01-01T00:00:00Z',
202
+ workdir: '',
203
+ ports: { health: 1, metrics: 2, p2p: 4555, admin: 3 },
204
+ owner: true,
205
+ };
206
+
207
+ let app: ReturnType<typeof Fastify>;
208
+ let orchestrator: FakeOrchestrator;
209
+
210
+ beforeEach(() => {
211
+ app = Fastify();
212
+ registerErrorHandler(app);
213
+ orchestrator = fakeOrchestrator([OWNER_NODE], { ownerId: 'owner', hasOwnerConfig: true });
214
+ registerNodesRoutes(app, { orchestrator });
215
+ });
216
+
217
+ afterEach(async () => { await app.close(); });
218
+
219
+ it('start ensures the owner node', async () => {
220
+ const res = await app.inject({ method: 'POST', url: '/api/nodes/owner/start' });
221
+ expect(res.statusCode).toBe(200);
222
+ expect(orchestrator.__ensured).toBe(1);
223
+ });
224
+
225
+ it('restart re-spawns the owner node', async () => {
226
+ const res = await app.inject({ method: 'POST', url: '/api/nodes/owner/restart' });
227
+ expect(res.statusCode).toBe(200);
228
+ expect(orchestrator.__restarted).toBe(1);
229
+ });
230
+
231
+ it('start returns 501 when there is no saved owner config', async () => {
232
+ const app2 = Fastify();
233
+ registerErrorHandler(app2);
234
+ const orch2 = fakeOrchestrator([OWNER_NODE], { ownerId: 'owner', hasOwnerConfig: false });
235
+ registerNodesRoutes(app2, { orchestrator: orch2 });
236
+ const res = await app2.inject({ method: 'POST', url: '/api/nodes/owner/start' });
237
+ expect(res.statusCode).toBe(501);
238
+ await app2.close();
239
+ });
240
+ });
241
+
242
+ describe('tailLogFile', () => {
243
+ it('returns [] for missing file', () => {
244
+ expect(tailLogFile(join(tmpdir(), 'definitely-not-here-' + Date.now()), 10)).toEqual([]);
245
+ });
246
+
247
+ it('returns the last N lines from a multi-line file', () => {
248
+ const dir = mkdtempSync(join(tmpdir(), 'cadre-host-tail-'));
249
+ mkdirSync(dir, { recursive: true });
250
+ const path = join(dir, 'sample.log');
251
+ writeFileSync(path, Array.from({ length: 50 }, (_, i) => `line-${i + 1}`).join('\n') + '\n', 'utf8');
252
+ try {
253
+ const last3 = tailLogFile(path, 3);
254
+ expect(last3).toEqual(['line-48', 'line-49', 'line-50']);
255
+ } finally {
256
+ rmSync(dir, { recursive: true, force: true });
257
+ }
258
+ });
259
+ });
@@ -1,72 +1,72 @@
1
- import Fastify from 'fastify';
2
- import { describe, it, expect, beforeEach, afterEach } from 'vitest';
3
-
4
- import { registerOriginGuard } from '../origin-guard.js';
5
-
6
- describe('origin guard', () => {
7
- let app: ReturnType<typeof Fastify>;
8
-
9
- beforeEach(async () => {
10
- app = Fastify();
11
- registerOriginGuard(app, { port: 8765 });
12
- app.get('/ping', async () => ({ ok: true, data: { pong: true } }));
13
- });
14
-
15
- afterEach(async () => {
16
- await app.close();
17
- });
18
-
19
- it('accepts 127.0.0.1:<port>', async () => {
20
- const res = await app.inject({ method: 'GET', url: '/ping', headers: { host: '127.0.0.1:8765' } });
21
- expect(res.statusCode).toBe(200);
22
- });
23
-
24
- it('accepts localhost:<port>', async () => {
25
- const res = await app.inject({ method: 'GET', url: '/ping', headers: { host: 'localhost:8765' } });
26
- expect(res.statusCode).toBe(200);
27
- });
28
-
29
- it('accepts case-insensitive localhost', async () => {
30
- const res = await app.inject({ method: 'GET', url: '/ping', headers: { host: 'LOCALHOST:8765' } });
31
- expect(res.statusCode).toBe(200);
32
- });
33
-
34
- it('rejects mismatched host', async () => {
35
- const res = await app.inject({
36
- method: 'GET',
37
- url: '/ping',
38
- headers: { host: 'evil.example.com' },
39
- });
40
- expect(res.statusCode).toBe(403);
41
- const body = res.json() as { ok: boolean; error: { code: string } };
42
- expect(body.ok).toBe(false);
43
- expect(body.error.code).toBe('forbidden_origin');
44
- });
45
-
46
- it('rejects host with wrong port', async () => {
47
- const res = await app.inject({
48
- method: 'GET',
49
- url: '/ping',
50
- headers: { host: '127.0.0.1:9999' },
51
- });
52
- expect(res.statusCode).toBe(403);
53
- });
54
-
55
- it('accepts request with matching Origin', async () => {
56
- const res = await app.inject({
57
- method: 'GET',
58
- url: '/ping',
59
- headers: { host: '127.0.0.1:8765', origin: 'http://127.0.0.1:8765' },
60
- });
61
- expect(res.statusCode).toBe(200);
62
- });
63
-
64
- it('rejects request with mismatched Origin', async () => {
65
- const res = await app.inject({
66
- method: 'GET',
67
- url: '/ping',
68
- headers: { host: '127.0.0.1:8765', origin: 'http://evil.example.com' },
69
- });
70
- expect(res.statusCode).toBe(403);
71
- });
72
- });
1
+ import Fastify from 'fastify';
2
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
3
+
4
+ import { registerOriginGuard } from '../origin-guard.js';
5
+
6
+ describe('origin guard', () => {
7
+ let app: ReturnType<typeof Fastify>;
8
+
9
+ beforeEach(async () => {
10
+ app = Fastify();
11
+ registerOriginGuard(app, { port: 8765 });
12
+ app.get('/ping', async () => ({ ok: true, data: { pong: true } }));
13
+ });
14
+
15
+ afterEach(async () => {
16
+ await app.close();
17
+ });
18
+
19
+ it('accepts 127.0.0.1:<port>', async () => {
20
+ const res = await app.inject({ method: 'GET', url: '/ping', headers: { host: '127.0.0.1:8765' } });
21
+ expect(res.statusCode).toBe(200);
22
+ });
23
+
24
+ it('accepts localhost:<port>', async () => {
25
+ const res = await app.inject({ method: 'GET', url: '/ping', headers: { host: 'localhost:8765' } });
26
+ expect(res.statusCode).toBe(200);
27
+ });
28
+
29
+ it('accepts case-insensitive localhost', async () => {
30
+ const res = await app.inject({ method: 'GET', url: '/ping', headers: { host: 'LOCALHOST:8765' } });
31
+ expect(res.statusCode).toBe(200);
32
+ });
33
+
34
+ it('rejects mismatched host', async () => {
35
+ const res = await app.inject({
36
+ method: 'GET',
37
+ url: '/ping',
38
+ headers: { host: 'evil.example.com' },
39
+ });
40
+ expect(res.statusCode).toBe(403);
41
+ const body = res.json() as { ok: boolean; error: { code: string } };
42
+ expect(body.ok).toBe(false);
43
+ expect(body.error.code).toBe('forbidden_origin');
44
+ });
45
+
46
+ it('rejects host with wrong port', async () => {
47
+ const res = await app.inject({
48
+ method: 'GET',
49
+ url: '/ping',
50
+ headers: { host: '127.0.0.1:9999' },
51
+ });
52
+ expect(res.statusCode).toBe(403);
53
+ });
54
+
55
+ it('accepts request with matching Origin', async () => {
56
+ const res = await app.inject({
57
+ method: 'GET',
58
+ url: '/ping',
59
+ headers: { host: '127.0.0.1:8765', origin: 'http://127.0.0.1:8765' },
60
+ });
61
+ expect(res.statusCode).toBe(200);
62
+ });
63
+
64
+ it('rejects request with mismatched Origin', async () => {
65
+ const res = await app.inject({
66
+ method: 'GET',
67
+ url: '/ping',
68
+ headers: { host: '127.0.0.1:8765', origin: 'http://evil.example.com' },
69
+ });
70
+ expect(res.statusCode).toBe(403);
71
+ });
72
+ });