@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,254 +1,267 @@
1
- /**
2
- * Public surface for the cadre-host local UI server.
3
- *
4
- * `createLocalUiServer(opts)` wires:
5
- * - the origin guard + error handler
6
- * - existing trust-circle / NAT / update typed handlers, mounted at
7
- * `/auth/*`, `/nat/*`, `/update/*` (the CLI contract)
8
- * - new UI-only routes under `/api/*` (status, nodes, settings, events)
9
- * - the static SPA mount at `/`
10
- *
11
- * Callers (cadre-host start) own the subsystems and pass them in. The
12
- * server doesn't construct them — start has to own their lifecycle anyway
13
- * (orchestrator init, trust-circle/NAT bring-up, update timer).
14
- */
15
-
16
- import type { FastifyInstance } from 'fastify';
17
-
18
- import type { HostProcessOrchestrator } from '../orchestrator/index.js';
19
- import type { TrustCircleService } from '../auth/index.js';
20
- import { createTrustCircleHandlers } from '../auth/index.js';
21
- import type { NatService } from '../nat/index.js';
22
- import { createNatHandlers } from '../nat/index.js';
23
- import type { UpdateService } from '../update/index.js';
24
- import { createUpdateHandlers } from '../update/index.js';
25
- import type { GrantService, DonationService } from '../donation/index.js';
26
- import { createGrantAdminHandlers } from '../donation/index.js';
27
-
28
- import { EventBus } from './events/bus.js';
29
- import { registerSseRoute } from './events/sse-route.js';
30
- import { registerErrorHandler } from './error-handler.js';
31
- import { registerOriginGuard } from './origin-guard.js';
32
- import { registerStaticMount } from './static.js';
33
- import { buildFastify, startListening, stopListening } from './server.js';
34
- import { registerNatRoutes } from './routes/nat.js';
35
- import { registerTrustCircleRoutes } from './routes/trust-circle.js';
36
- import { registerUpdateRoutes } from './routes/update.js';
37
- import { registerStatusRoute } from './routes/status.js';
38
- import { registerNodesRoutes } from './routes/nodes.js';
39
- import { registerSettingsRoutes } from './routes/settings.js';
40
- import { registerGrantsAdminRoutes } from './routes/grants-admin.js';
41
- import { registerGrantsRoutes } from './routes/grants.js';
42
- import { HostSettingsStore } from './settings-store.js';
43
-
44
- export interface LocalUiServerOptions {
45
- /** Configured UI port from host.config.json. May be re-bound on collision. */
46
- uiPort: number;
47
- /** Resolved data dir (passed by cadre-host start). */
48
- dataDir: string;
49
- /** Wired dependencies — all owned by the caller. */
50
- orchestrator: HostProcessOrchestrator;
51
- /**
52
- * Trust-circle service — present only when the host runs its own personal
53
- * cadre (`ownCadre.enabled`). Absent in donor-only mode, where `/auth/*`
54
- * stays unmounted and 404s.
55
- */
56
- trustCircle?: TrustCircleService;
57
- /**
58
- * NAT service — present only when the host runs its own personal cadre.
59
- * Absent in donor-only mode (loopback-only in v1), where `/nat/*` stays
60
- * unmounted and 404s.
61
- */
62
- nat?: NatService;
63
- /** Optional — 6.4.2 lands this; nullable while still iterating. */
64
- update?: UpdateService;
65
- /**
66
- * Donation grant layer. When present, mounts the loopback admin surface at
67
- * `/grants-admin` (issue/list/revoke). Optional so existing callers/tests
68
- * that don't exercise donations need not wire it.
69
- */
70
- grants?: GrantService;
71
- /**
72
- * Donation lifecycle service. When present (alongside `grants`), mounts the
73
- * bearer-gated grantee-facing provisioning surface at `/grants`
74
- * (provision / peer / seed / terminate). Optional so callers/tests that don't
75
- * exercise the donor path need not wire it.
76
- */
77
- donations?: DonationService;
78
- /** Settings I/O facade. Defaults to a new one rooted at `dataDir`. */
79
- settingsStore?: HostSettingsStore;
80
- /** Bus instance — pass the same one to subsystems that publish events. */
81
- events?: EventBus;
82
- /**
83
- * Static asset root override. Defaults to `<package>/dist/ui`. When the
84
- * directory is absent the root handler returns a placeholder HTML.
85
- */
86
- staticRoot?: string;
87
- /**
88
- * Test-only: bind to port 0 (OS picks any free port). The returned URL
89
- * reflects the actual bound port.
90
- */
91
- forcePort?: 0;
92
- /**
93
- * SSE heartbeat interval (ms). Defaults to 15 000 ms. Tests reduce this
94
- * so the heartbeat can be observed quickly.
95
- */
96
- sseHeartbeatMs?: number;
97
- }
98
-
99
- export interface LocalUiServer {
100
- app: FastifyInstance;
101
- events: EventBus;
102
- /** Resolves with the actually-bound port. */
103
- start(): Promise<{ port: number; url: string }>;
104
- stop(): Promise<void>;
105
- }
106
-
107
- /** How often to poll UpdateService.getState() looking for new versions. */
108
- const UPDATE_OBSERVER_INTERVAL_MS = 60_000;
109
-
110
- export function createLocalUiServer(opts: LocalUiServerOptions): LocalUiServer {
111
- const events = opts.events ?? new EventBus();
112
- const settingsStore = opts.settingsStore ?? new HostSettingsStore({ dataDir: opts.dataDir });
113
-
114
- const app = buildFastify();
115
-
116
- // Bound port is unknown until start(); the guard is registered then.
117
-
118
- registerErrorHandler(app);
119
-
120
- // /api/events (SSE) — must be registered before the static fallback so
121
- // the not-found handler doesn't try to serve it.
122
- registerSseRoute(app, {
123
- events,
124
- ...(opts.sseHeartbeatMs !== undefined ? { heartbeatIntervalMs: opts.sseHeartbeatMs } : {}),
125
- });
126
-
127
- registerStatusRoute(app, {
128
- orchestrator: opts.orchestrator,
129
- ...(opts.trustCircle ? { trustCircle: opts.trustCircle } : {}),
130
- ...(opts.nat ? { nat: opts.nat } : {}),
131
- ...(opts.update ? { update: opts.update } : {}),
132
- });
133
- registerNodesRoutes(app, { orchestrator: opts.orchestrator });
134
- registerSettingsRoutes(app, { settingsStore, ...(opts.nat ? { nat: opts.nat } : {}), ...(opts.update ? { update: opts.update } : {}) });
135
-
136
- // Trust-circle + NAT surfaces exist only when the host runs its own personal
137
- // cadre. In donor-only mode they're left unmounted, so `/auth/*` and `/nat/*`
138
- // fall through to the static not-found handler and 404 (see static.ts).
139
- if (opts.trustCircle) {
140
- registerTrustCircleRoutes(app, { handlers: createTrustCircleHandlers(opts.trustCircle), events });
141
- }
142
- if (opts.nat) {
143
- registerNatRoutes(app, { handlers: createNatHandlers(opts.nat), events });
144
- }
145
- if (opts.update) {
146
- registerUpdateRoutes(app, { handlers: createUpdateHandlers(opts.update), events });
147
- }
148
- if (opts.grants) {
149
- registerGrantsAdminRoutes(app, { handlers: createGrantAdminHandlers(opts.grants) });
150
- // Grantee-facing provisioning surface needs both the donation service and a
151
- // grant validator (the GrantService doubles as the validator).
152
- if (opts.donations) {
153
- registerGrantsRoutes(app, { donations: opts.donations, grants: opts.grants });
154
- }
155
- }
156
-
157
- // Static mount registers as the not-found handler — declared last so the
158
- // API paths above win.
159
- registerStaticMount(app, { ...(opts.staticRoot !== undefined ? { rootDir: opts.staticRoot } : {}) });
160
-
161
- let bound: { port: number; url: string } | null = null;
162
- let stopped = false;
163
- const teardown: Array<() => void> = [];
164
-
165
- return {
166
- app,
167
- events,
168
- async start() {
169
- if (bound) return bound;
170
- // Origin guard reads the port at request time via the getter so the
171
- // post-fallback bound port is honoured. Registered here (not at
172
- // factory time) so it lives in the same lifecycle as listen.
173
- registerOriginGuard(app, { port: () => bound?.port ?? opts.uiPort });
174
- const started = await startListening(app, {
175
- preferredPort: opts.uiPort,
176
- ...(opts.forcePort === 0 ? { forcePort: 0 as const } : {}),
177
- });
178
- bound = started;
179
-
180
- // Orchestrator → bus adapter: forward node state changes.
181
- teardown.push(
182
- opts.orchestrator.onStateChange((info) => {
183
- events.publish({
184
- type: 'node-state-changed',
185
- nodeId: info.id,
186
- status: info.status === 'running' ? 'running' : 'stopped',
187
- });
188
- }),
189
- );
190
-
191
- // One-shot connectivity publish — the SPA will get a sane initial
192
- // signal even if no settings have changed yet this session. Skipped in
193
- // donor-only mode, where there is no NatService.
194
- if (opts.nat) {
195
- try {
196
- const snap = opts.nat.getStatus();
197
- events.publish({
198
- type: 'connectivity-changed',
199
- portMode: snap.portMode,
200
- directReachability: snap.directReachability,
201
- });
202
- } catch {
203
- // NatService.start may not have completed; harmless to skip.
204
- }
205
- }
206
-
207
- // Update observer: poll UpdateService.getState() every 60 s and emit
208
- // `update-available` when `available.version` changes. Cheap, avoids
209
- // poking at the service's internals.
210
- if (opts.update) {
211
- const update = opts.update;
212
- let lastVersion: string | undefined;
213
- const tick = async (): Promise<void> => {
214
- try {
215
- const state = await update.getState();
216
- const available = state.available;
217
- if (available && available.version && available.version !== lastVersion) {
218
- lastVersion = available.version;
219
- events.publish({
220
- type: 'update-available',
221
- version: available.version,
222
- ...(available.releaseNotesUrl ? { releaseNotesUrl: available.releaseNotesUrl } : {}),
223
- });
224
- }
225
- } catch {
226
- // Update store I/O failure — silent, will retry next tick.
227
- }
228
- };
229
- // Fire once on boot in case the timer set `available` before the server bound.
230
- void tick();
231
- const timer = setInterval(() => { void tick(); }, UPDATE_OBSERVER_INTERVAL_MS);
232
- if (typeof timer === 'object' && 'unref' in timer) {
233
- (timer as { unref?: () => void }).unref?.();
234
- }
235
- teardown.push(() => clearInterval(timer));
236
- }
237
-
238
- return started;
239
- },
240
- async stop() {
241
- if (stopped) return;
242
- stopped = true;
243
- for (const fn of teardown.splice(0, teardown.length)) {
244
- try { fn(); } catch { /* ignore teardown errors */ }
245
- }
246
- await stopListening(app);
247
- },
248
- };
249
- }
250
-
251
- export { EventBus } from './events/bus.js';
252
- export type { LocalUiEventListener } from './events/bus.js';
253
- export type { LocalUiEvent, LocalUiEventType } from './events/types.js';
254
- export { HostSettingsStore } from './settings-store.js';
1
+ /**
2
+ * Public surface for the cadre-host local UI server.
3
+ *
4
+ * `createLocalUiServer(opts)` wires:
5
+ * - the origin guard + error handler
6
+ * - existing trust-circle / NAT / update typed handlers, mounted at
7
+ * `/auth/*`, `/nat/*`, `/update/*` (the CLI contract)
8
+ * - new UI-only routes under `/api/*` (status, nodes, settings, events)
9
+ * - the static SPA mount at `/`
10
+ *
11
+ * Callers (cadre-host start) own the subsystems and pass them in. The
12
+ * server doesn't construct them — start has to own their lifecycle anyway
13
+ * (orchestrator init, trust-circle/NAT bring-up, update timer).
14
+ */
15
+
16
+ import type { FastifyInstance } from 'fastify';
17
+
18
+ import type { HostProcessOrchestrator } from '../orchestrator/index.js';
19
+ import type { TrustCircleService } from '../auth/index.js';
20
+ import { createTrustCircleHandlers } from '../auth/index.js';
21
+ import type { NatService } from '../nat/index.js';
22
+ import { createNatHandlers } from '../nat/index.js';
23
+ import type { StrandService } from '../strands/index.js';
24
+ import { createStrandHandlers } from '../strands/index.js';
25
+ import type { UpdateService } from '../update/index.js';
26
+ import { createUpdateHandlers } from '../update/index.js';
27
+ import type { GrantService, DonationService } from '../donation/index.js';
28
+ import { createGrantAdminHandlers } from '../donation/index.js';
29
+
30
+ import { EventBus } from './events/bus.js';
31
+ import { registerSseRoute } from './events/sse-route.js';
32
+ import { registerErrorHandler } from './error-handler.js';
33
+ import { registerOriginGuard } from './origin-guard.js';
34
+ import { registerStaticMount } from './static.js';
35
+ import { buildFastify, startListening, stopListening } from './server.js';
36
+ import { registerNatRoutes } from './routes/nat.js';
37
+ import { registerTrustCircleRoutes } from './routes/trust-circle.js';
38
+ import { registerStrandRoutes } from './routes/strands.js';
39
+ import { registerUpdateRoutes } from './routes/update.js';
40
+ import { registerStatusRoute } from './routes/status.js';
41
+ import { registerNodesRoutes } from './routes/nodes.js';
42
+ import { registerSettingsRoutes } from './routes/settings.js';
43
+ import { registerGrantsAdminRoutes } from './routes/grants-admin.js';
44
+ import { registerGrantsRoutes } from './routes/grants.js';
45
+ import { HostSettingsStore } from './settings-store.js';
46
+
47
+ export interface LocalUiServerOptions {
48
+ /** Configured UI port from host.config.json. May be re-bound on collision. */
49
+ uiPort: number;
50
+ /** Resolved data dir (passed by cadre-host start). */
51
+ dataDir: string;
52
+ /** Wired dependencies — all owned by the caller. */
53
+ orchestrator: HostProcessOrchestrator;
54
+ /**
55
+ * Trust-circle service — present only when the host runs its own personal
56
+ * cadre (`ownCadre.enabled`). Absent in donor-only mode, where `/auth/*`
57
+ * stays unmounted and 404s.
58
+ */
59
+ trustCircle?: TrustCircleService;
60
+ /**
61
+ * NAT service — present only when the host runs its own personal cadre.
62
+ * Absent in donor-only mode (loopback-only in v1), where `/nat/*` stays
63
+ * unmounted and 404s.
64
+ */
65
+ nat?: NatService;
66
+ /**
67
+ * Strand service — present only when the host runs its own personal cadre.
68
+ * Absent in donor-only mode, where there is no owner node to ask, so
69
+ * `/api/strands` stays unmounted and 404s through the static handler.
70
+ */
71
+ strands?: StrandService;
72
+ /** Optional — 6.4.2 lands this; nullable while still iterating. */
73
+ update?: UpdateService;
74
+ /**
75
+ * Donation grant layer. When present, mounts the loopback admin surface at
76
+ * `/grants-admin` (issue/list/revoke). Optional so existing callers/tests
77
+ * that don't exercise donations need not wire it.
78
+ */
79
+ grants?: GrantService;
80
+ /**
81
+ * Donation lifecycle service. When present (alongside `grants`), mounts the
82
+ * bearer-gated grantee-facing provisioning surface at `/grants`
83
+ * (provision / peer / seed / terminate). Optional so callers/tests that don't
84
+ * exercise the donor path need not wire it.
85
+ */
86
+ donations?: DonationService;
87
+ /** Settings I/O facade. Defaults to a new one rooted at `dataDir`. */
88
+ settingsStore?: HostSettingsStore;
89
+ /** Bus instance — pass the same one to subsystems that publish events. */
90
+ events?: EventBus;
91
+ /**
92
+ * Static asset root override. Defaults to `<package>/dist/ui`. When the
93
+ * directory is absent the root handler returns a placeholder HTML.
94
+ */
95
+ staticRoot?: string;
96
+ /**
97
+ * Test-only: bind to port 0 (OS picks any free port). The returned URL
98
+ * reflects the actual bound port.
99
+ */
100
+ forcePort?: 0;
101
+ /**
102
+ * SSE heartbeat interval (ms). Defaults to 15 000 ms. Tests reduce this
103
+ * so the heartbeat can be observed quickly.
104
+ */
105
+ sseHeartbeatMs?: number;
106
+ }
107
+
108
+ export interface LocalUiServer {
109
+ app: FastifyInstance;
110
+ events: EventBus;
111
+ /** Resolves with the actually-bound port. */
112
+ start(): Promise<{ port: number; url: string }>;
113
+ stop(): Promise<void>;
114
+ }
115
+
116
+ /** How often to poll UpdateService.getState() looking for new versions. */
117
+ const UPDATE_OBSERVER_INTERVAL_MS = 60_000;
118
+
119
+ export function createLocalUiServer(opts: LocalUiServerOptions): LocalUiServer {
120
+ const events = opts.events ?? new EventBus();
121
+ const settingsStore = opts.settingsStore ?? new HostSettingsStore({ dataDir: opts.dataDir });
122
+
123
+ const app = buildFastify();
124
+
125
+ // Bound port is unknown until start(); the guard is registered then.
126
+
127
+ registerErrorHandler(app);
128
+
129
+ // /api/events (SSE) — must be registered before the static fallback so
130
+ // the not-found handler doesn't try to serve it.
131
+ registerSseRoute(app, {
132
+ events,
133
+ ...(opts.sseHeartbeatMs !== undefined ? { heartbeatIntervalMs: opts.sseHeartbeatMs } : {}),
134
+ });
135
+
136
+ registerStatusRoute(app, {
137
+ orchestrator: opts.orchestrator,
138
+ ...(opts.trustCircle ? { trustCircle: opts.trustCircle } : {}),
139
+ ...(opts.nat ? { nat: opts.nat } : {}),
140
+ ...(opts.update ? { update: opts.update } : {}),
141
+ });
142
+ registerNodesRoutes(app, { orchestrator: opts.orchestrator });
143
+ registerSettingsRoutes(app, { settingsStore, ...(opts.nat ? { nat: opts.nat } : {}), ...(opts.update ? { update: opts.update } : {}) });
144
+
145
+ // Trust-circle + NAT + strand surfaces exist only when the host runs its own
146
+ // personal cadre. In donor-only mode they're left unmounted, so `/auth/*`,
147
+ // `/nat/*` and `/api/strands` fall through to the static not-found handler and
148
+ // 404 (see static.ts).
149
+ if (opts.trustCircle) {
150
+ registerTrustCircleRoutes(app, { handlers: createTrustCircleHandlers(opts.trustCircle), events });
151
+ }
152
+ if (opts.nat) {
153
+ registerNatRoutes(app, { handlers: createNatHandlers(opts.nat), events });
154
+ }
155
+ if (opts.strands) {
156
+ registerStrandRoutes(app, { handlers: createStrandHandlers(opts.strands), events });
157
+ }
158
+ if (opts.update) {
159
+ registerUpdateRoutes(app, { handlers: createUpdateHandlers(opts.update), events });
160
+ }
161
+ if (opts.grants) {
162
+ registerGrantsAdminRoutes(app, { handlers: createGrantAdminHandlers(opts.grants) });
163
+ // Grantee-facing provisioning surface needs both the donation service and a
164
+ // grant validator (the GrantService doubles as the validator).
165
+ if (opts.donations) {
166
+ registerGrantsRoutes(app, { donations: opts.donations, grants: opts.grants });
167
+ }
168
+ }
169
+
170
+ // Static mount registers as the not-found handler — declared last so the
171
+ // API paths above win.
172
+ registerStaticMount(app, { ...(opts.staticRoot !== undefined ? { rootDir: opts.staticRoot } : {}) });
173
+
174
+ let bound: { port: number; url: string } | null = null;
175
+ let stopped = false;
176
+ const teardown: Array<() => void> = [];
177
+
178
+ return {
179
+ app,
180
+ events,
181
+ async start() {
182
+ if (bound) return bound;
183
+ // Origin guard reads the port at request time via the getter so the
184
+ // post-fallback bound port is honoured. Registered here (not at
185
+ // factory time) so it lives in the same lifecycle as listen.
186
+ registerOriginGuard(app, { port: () => bound?.port ?? opts.uiPort });
187
+ const started = await startListening(app, {
188
+ preferredPort: opts.uiPort,
189
+ ...(opts.forcePort === 0 ? { forcePort: 0 as const } : {}),
190
+ });
191
+ bound = started;
192
+
193
+ // Orchestrator → bus adapter: forward node state changes.
194
+ teardown.push(
195
+ opts.orchestrator.onStateChange((info) => {
196
+ events.publish({
197
+ type: 'node-state-changed',
198
+ nodeId: info.id,
199
+ status: info.status === 'running' ? 'running' : 'stopped',
200
+ });
201
+ }),
202
+ );
203
+
204
+ // One-shot connectivity publish — the SPA will get a sane initial
205
+ // signal even if no settings have changed yet this session. Skipped in
206
+ // donor-only mode, where there is no NatService.
207
+ if (opts.nat) {
208
+ try {
209
+ const snap = opts.nat.getStatus();
210
+ events.publish({
211
+ type: 'connectivity-changed',
212
+ portMode: snap.portMode,
213
+ directReachability: snap.directReachability,
214
+ });
215
+ } catch {
216
+ // NatService.start may not have completed; harmless to skip.
217
+ }
218
+ }
219
+
220
+ // Update observer: poll UpdateService.getState() every 60 s and emit
221
+ // `update-available` when `available.version` changes. Cheap, avoids
222
+ // poking at the service's internals.
223
+ if (opts.update) {
224
+ const update = opts.update;
225
+ let lastVersion: string | undefined;
226
+ const tick = async (): Promise<void> => {
227
+ try {
228
+ const state = await update.getState();
229
+ const available = state.available;
230
+ if (available && available.version && available.version !== lastVersion) {
231
+ lastVersion = available.version;
232
+ events.publish({
233
+ type: 'update-available',
234
+ version: available.version,
235
+ ...(available.releaseNotesUrl ? { releaseNotesUrl: available.releaseNotesUrl } : {}),
236
+ });
237
+ }
238
+ } catch {
239
+ // Update store I/O failure — silent, will retry next tick.
240
+ }
241
+ };
242
+ // Fire once on boot in case the timer set `available` before the server bound.
243
+ void tick();
244
+ const timer = setInterval(() => { void tick(); }, UPDATE_OBSERVER_INTERVAL_MS);
245
+ if (typeof timer === 'object' && 'unref' in timer) {
246
+ (timer as { unref?: () => void }).unref?.();
247
+ }
248
+ teardown.push(() => clearInterval(timer));
249
+ }
250
+
251
+ return started;
252
+ },
253
+ async stop() {
254
+ if (stopped) return;
255
+ stopped = true;
256
+ for (const fn of teardown.splice(0, teardown.length)) {
257
+ try { fn(); } catch { /* ignore teardown errors */ }
258
+ }
259
+ await stopListening(app);
260
+ },
261
+ };
262
+ }
263
+
264
+ export { EventBus } from './events/bus.js';
265
+ export type { LocalUiEventListener } from './events/bus.js';
266
+ export type { LocalUiEvent, LocalUiEventType } from './events/types.js';
267
+ export { HostSettingsStore } from './settings-store.js';