@serfab/cadre-host 1.10.0 → 1.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.
- package/README.md +423 -423
- package/dist/ui/assets/index-C6nELNfC.js.map +1 -1
- package/package.json +4 -4
- package/src/__tests__/global-setup.ts +58 -58
- package/src/__tests__/orchestrator-handle-contract.ts +134 -134
- package/src/__tests__/orchestrator-node-identity.test.ts +203 -203
- package/src/__tests__/orchestrator-ports.test.ts +143 -143
- package/src/__tests__/orchestrator-teardown.ts +65 -65
- package/src/__tests__/orchestrator.test.ts +1063 -1063
- package/src/bin/host.ts +1357 -1357
- package/src/donation/__tests__/fake-orchestrator.test.ts +173 -173
- package/src/donation/donation-store.ts +176 -176
- package/src/donation/grant-service.ts +252 -252
- package/src/donation/index.ts +65 -65
- package/src/donation/types.ts +260 -260
- package/src/orchestrator/host-process-orchestrator.ts +1260 -1260
- package/src/orchestrator/port-allocator.ts +73 -73
- package/src/server/__tests__/grants-admin-route.test.ts +171 -171
- package/src/server/events/types.ts +24 -24
- package/src/server/index.ts +267 -267
- package/src/server/routes/grants-admin.ts +74 -74
package/src/server/index.ts
CHANGED
|
@@ -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, 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';
|
|
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';
|