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