@serfab/cadre-host 0.7.1
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 +101 -0
- package/dist/auth/duration.d.ts +1 -0
- package/dist/auth/duration.js +32 -0
- package/dist/auth/duration.js.map +1 -0
- package/dist/auth/index.d.ts +9 -0
- package/dist/auth/index.js +8 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/auth/trust-circle-store.d.ts +26 -0
- package/dist/auth/trust-circle-store.js +129 -0
- package/dist/auth/trust-circle-store.js.map +1 -0
- package/dist/auth/trust-circle.d.ts +91 -0
- package/dist/auth/trust-circle.js +230 -0
- package/dist/auth/trust-circle.js.map +1 -0
- package/dist/auth/types.d.ts +81 -0
- package/dist/auth/types.js +24 -0
- package/dist/auth/types.js.map +1 -0
- package/dist/bin/host.d.ts +13 -0
- package/dist/bin/host.js +826 -0
- package/dist/bin/host.js.map +1 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -0
- package/dist/installer/browser.d.ts +14 -0
- package/dist/installer/browser.js +35 -0
- package/dist/installer/browser.js.map +1 -0
- package/dist/installer/config.d.ts +43 -0
- package/dist/installer/config.js +113 -0
- package/dist/installer/config.js.map +1 -0
- package/dist/installer/identity.d.ts +23 -0
- package/dist/installer/identity.js +36 -0
- package/dist/installer/identity.js.map +1 -0
- package/dist/installer/index.d.ts +83 -0
- package/dist/installer/index.js +204 -0
- package/dist/installer/index.js.map +1 -0
- package/dist/installer/paths.d.ts +33 -0
- package/dist/installer/paths.js +84 -0
- package/dist/installer/paths.js.map +1 -0
- package/dist/installer/platform.d.ts +9 -0
- package/dist/installer/platform.js +21 -0
- package/dist/installer/platform.js.map +1 -0
- package/dist/installer/service-host/index.d.ts +11 -0
- package/dist/installer/service-host/index.js +16 -0
- package/dist/installer/service-host/index.js.map +1 -0
- package/dist/installer/service-host/launchd.d.ts +16 -0
- package/dist/installer/service-host/launchd.js +79 -0
- package/dist/installer/service-host/launchd.js.map +1 -0
- package/dist/installer/service-host/nssm.d.ts +20 -0
- package/dist/installer/service-host/nssm.js +88 -0
- package/dist/installer/service-host/nssm.js.map +1 -0
- package/dist/installer/service-host/systemd.d.ts +16 -0
- package/dist/installer/service-host/systemd.js +78 -0
- package/dist/installer/service-host/systemd.js.map +1 -0
- package/dist/installer/service-host/template.d.ts +6 -0
- package/dist/installer/service-host/template.js +20 -0
- package/dist/installer/service-host/template.js.map +1 -0
- package/dist/installer/service-host/types.d.ts +40 -0
- package/dist/installer/service-host/types.js +6 -0
- package/dist/installer/service-host/types.js.map +1 -0
- package/dist/installer/wizard.d.ts +31 -0
- package/dist/installer/wizard.js +67 -0
- package/dist/installer/wizard.js.map +1 -0
- package/dist/nat/address-resolver.d.ts +22 -0
- package/dist/nat/address-resolver.js +31 -0
- package/dist/nat/address-resolver.js.map +1 -0
- package/dist/nat/ddns/duckdns.d.ts +12 -0
- package/dist/nat/ddns/duckdns.js +57 -0
- package/dist/nat/ddns/duckdns.js.map +1 -0
- package/dist/nat/ddns/index.d.ts +30 -0
- package/dist/nat/ddns/index.js +21 -0
- package/dist/nat/ddns/index.js.map +1 -0
- package/dist/nat/ddns/updater.d.ts +68 -0
- package/dist/nat/ddns/updater.js +194 -0
- package/dist/nat/ddns/updater.js.map +1 -0
- package/dist/nat/external-ip.d.ts +62 -0
- package/dist/nat/external-ip.js +114 -0
- package/dist/nat/external-ip.js.map +1 -0
- package/dist/nat/index.d.ts +22 -0
- package/dist/nat/index.js +16 -0
- package/dist/nat/index.js.map +1 -0
- package/dist/nat/nat-service.d.ts +101 -0
- package/dist/nat/nat-service.js +284 -0
- package/dist/nat/nat-service.js.map +1 -0
- package/dist/nat/nat-store.d.ts +19 -0
- package/dist/nat/nat-store.js +136 -0
- package/dist/nat/nat-store.js.map +1 -0
- package/dist/nat/port-mapper.d.ts +98 -0
- package/dist/nat/port-mapper.js +226 -0
- package/dist/nat/port-mapper.js.map +1 -0
- package/dist/nat/reachability.d.ts +19 -0
- package/dist/nat/reachability.js +29 -0
- package/dist/nat/reachability.js.map +1 -0
- package/dist/nat/secrets/file-store.d.ts +23 -0
- package/dist/nat/secrets/file-store.js +102 -0
- package/dist/nat/secrets/file-store.js.map +1 -0
- package/dist/nat/secrets/index.d.ts +36 -0
- package/dist/nat/secrets/index.js +56 -0
- package/dist/nat/secrets/index.js.map +1 -0
- package/dist/nat/secrets/keytar-store.d.ts +18 -0
- package/dist/nat/secrets/keytar-store.js +52 -0
- package/dist/nat/secrets/keytar-store.js.map +1 -0
- package/dist/nat/types.d.ts +120 -0
- package/dist/nat/types.js +24 -0
- package/dist/nat/types.js.map +1 -0
- package/dist/orchestrator/host-process-orchestrator.d.ts +87 -0
- package/dist/orchestrator/host-process-orchestrator.js +557 -0
- package/dist/orchestrator/host-process-orchestrator.js.map +1 -0
- package/dist/orchestrator/index.d.ts +3 -0
- package/dist/orchestrator/index.js +2 -0
- package/dist/orchestrator/index.js.map +1 -0
- package/dist/orchestrator/log-rotator.d.ts +25 -0
- package/dist/orchestrator/log-rotator.js +56 -0
- package/dist/orchestrator/log-rotator.js.map +1 -0
- package/dist/orchestrator/pid-liveness.d.ts +11 -0
- package/dist/orchestrator/pid-liveness.js +26 -0
- package/dist/orchestrator/pid-liveness.js.map +1 -0
- package/dist/orchestrator/port-allocator.d.ts +16 -0
- package/dist/orchestrator/port-allocator.js +38 -0
- package/dist/orchestrator/port-allocator.js.map +1 -0
- package/dist/orchestrator/state-store.d.ts +32 -0
- package/dist/orchestrator/state-store.js +44 -0
- package/dist/orchestrator/state-store.js.map +1 -0
- package/dist/orchestrator/types.d.ts +85 -0
- package/dist/orchestrator/types.js +31 -0
- package/dist/orchestrator/types.js.map +1 -0
- package/dist/server/error-handler.d.ts +26 -0
- package/dist/server/error-handler.js +95 -0
- package/dist/server/error-handler.js.map +1 -0
- package/dist/server/events/bus.d.ts +17 -0
- package/dist/server/events/bus.js +36 -0
- package/dist/server/events/bus.js.map +1 -0
- package/dist/server/events/sse-route.d.ts +22 -0
- package/dist/server/events/sse-route.js +65 -0
- package/dist/server/events/sse-route.js.map +1 -0
- package/dist/server/events/types.d.ts +25 -0
- package/dist/server/events/types.js +8 -0
- package/dist/server/events/types.js.map +1 -0
- package/dist/server/index.d.ts +67 -0
- package/dist/server/index.js +149 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/origin-guard.d.ts +24 -0
- package/dist/server/origin-guard.js +72 -0
- package/dist/server/origin-guard.js.map +1 -0
- package/dist/server/routes/nat.d.ts +16 -0
- package/dist/server/routes/nat.js +42 -0
- package/dist/server/routes/nat.js.map +1 -0
- package/dist/server/routes/nodes.d.ts +23 -0
- package/dist/server/routes/nodes.js +128 -0
- package/dist/server/routes/nodes.js.map +1 -0
- package/dist/server/routes/settings.d.ts +26 -0
- package/dist/server/routes/settings.js +97 -0
- package/dist/server/routes/settings.js.map +1 -0
- package/dist/server/routes/status.d.ts +42 -0
- package/dist/server/routes/status.js +76 -0
- package/dist/server/routes/status.js.map +1 -0
- package/dist/server/routes/trust-circle.d.ts +17 -0
- package/dist/server/routes/trust-circle.js +35 -0
- package/dist/server/routes/trust-circle.js.map +1 -0
- package/dist/server/routes/update.d.ts +16 -0
- package/dist/server/routes/update.js +29 -0
- package/dist/server/routes/update.js.map +1 -0
- package/dist/server/server.d.ts +40 -0
- package/dist/server/server.js +90 -0
- package/dist/server/server.js.map +1 -0
- package/dist/server/settings-store.d.ts +24 -0
- package/dist/server/settings-store.js +27 -0
- package/dist/server/settings-store.js.map +1 -0
- package/dist/server/static.d.ts +25 -0
- package/dist/server/static.js +177 -0
- package/dist/server/static.js.map +1 -0
- package/dist/ui/assets/index-BwU5mJGF.css +1 -0
- package/dist/ui/assets/index-C9uChk2P.js +14 -0
- package/dist/ui/assets/index-C9uChk2P.js.map +1 -0
- package/dist/ui/index.html +14 -0
- package/dist/update/apply.d.ts +37 -0
- package/dist/update/apply.js +102 -0
- package/dist/update/apply.js.map +1 -0
- package/dist/update/index.d.ts +101 -0
- package/dist/update/index.js +228 -0
- package/dist/update/index.js.map +1 -0
- package/dist/update/manifest.d.ts +48 -0
- package/dist/update/manifest.js +152 -0
- package/dist/update/manifest.js.map +1 -0
- package/dist/update/release-key.d.ts +24 -0
- package/dist/update/release-key.js +52 -0
- package/dist/update/release-key.js.map +1 -0
- package/dist/update/store.d.ts +22 -0
- package/dist/update/store.js +81 -0
- package/dist/update/store.js.map +1 -0
- package/dist/update/types.d.ts +90 -0
- package/dist/update/types.js +22 -0
- package/dist/update/types.js.map +1 -0
- package/dist/update/version.d.ts +18 -0
- package/dist/update/version.js +76 -0
- package/dist/update/version.js.map +1 -0
- package/package.json +80 -0
- package/service/README.md +86 -0
- package/service/cadre-host.service.tmpl +16 -0
- package/service/com.serfab.cadre-host.plist.tmpl +35 -0
- package/service/install-service.ps1 +98 -0
- package/service/uninstall-service.ps1 +19 -0
- package/src/__tests__/cli-invite.smoke.test.ts +187 -0
- package/src/__tests__/cli-nat.smoke.test.ts +207 -0
- package/src/__tests__/cli.smoke.test.ts +41 -0
- package/src/__tests__/orchestrator.test.ts +570 -0
- package/src/auth/__tests__/duration.test.ts +28 -0
- package/src/auth/__tests__/trust-circle-integration.test.ts +128 -0
- package/src/auth/__tests__/trust-circle-store.test.ts +115 -0
- package/src/auth/__tests__/trust-circle.test.ts +334 -0
- package/src/auth/duration.ts +33 -0
- package/src/auth/index.ts +19 -0
- package/src/auth/trust-circle-store.ts +155 -0
- package/src/auth/trust-circle.ts +304 -0
- package/src/auth/types.ts +96 -0
- package/src/bin/host.ts +905 -0
- package/src/index.ts +167 -0
- package/src/installer/__tests__/config.test.ts +86 -0
- package/src/installer/__tests__/identity.test.ts +34 -0
- package/src/installer/__tests__/installer.smoke.test.ts +124 -0
- package/src/installer/__tests__/paths.test.ts +47 -0
- package/src/installer/__tests__/service-host.test.ts +62 -0
- package/src/installer/__tests__/wizard.test.ts +60 -0
- package/src/installer/browser.ts +42 -0
- package/src/installer/config.ts +153 -0
- package/src/installer/identity.ts +49 -0
- package/src/installer/index.ts +303 -0
- package/src/installer/paths.ts +109 -0
- package/src/installer/platform.ts +27 -0
- package/src/installer/service-host/index.ts +21 -0
- package/src/installer/service-host/launchd.ts +90 -0
- package/src/installer/service-host/nssm.ts +100 -0
- package/src/installer/service-host/systemd.ts +88 -0
- package/src/installer/service-host/template.ts +21 -0
- package/src/installer/service-host/types.ts +48 -0
- package/src/installer/wizard.ts +92 -0
- package/src/nat/__tests__/address-resolver.test.ts +82 -0
- package/src/nat/__tests__/ddns-duckdns.test.ts +83 -0
- package/src/nat/__tests__/ddns-updater.test.ts +253 -0
- package/src/nat/__tests__/external-ip.test.ts +124 -0
- package/src/nat/__tests__/nat-service.test.ts +305 -0
- package/src/nat/__tests__/nat-store.test.ts +93 -0
- package/src/nat/__tests__/port-mapper.test.ts +191 -0
- package/src/nat/__tests__/reachability.test.ts +24 -0
- package/src/nat/__tests__/secrets.test.ts +156 -0
- package/src/nat/address-resolver.ts +51 -0
- package/src/nat/ddns/duckdns.ts +76 -0
- package/src/nat/ddns/index.ts +55 -0
- package/src/nat/ddns/updater.ts +243 -0
- package/src/nat/external-ip.ts +154 -0
- package/src/nat/index.ts +71 -0
- package/src/nat/nat-service.ts +375 -0
- package/src/nat/nat-store.ts +154 -0
- package/src/nat/port-mapper.ts +329 -0
- package/src/nat/reachability.ts +34 -0
- package/src/nat/secrets/file-store.ts +130 -0
- package/src/nat/secrets/index.ts +82 -0
- package/src/nat/secrets/keytar-store.ts +67 -0
- package/src/nat/types.ts +157 -0
- package/src/orchestrator/host-process-orchestrator.ts +626 -0
- package/src/orchestrator/index.ts +3 -0
- package/src/orchestrator/log-rotator.ts +53 -0
- package/src/orchestrator/pid-liveness.ts +24 -0
- package/src/orchestrator/port-allocator.ts +43 -0
- package/src/orchestrator/state-store.ts +72 -0
- package/src/orchestrator/types.ts +95 -0
- package/src/server/__tests__/bus.test.ts +38 -0
- package/src/server/__tests__/error-handler.test.ts +96 -0
- package/src/server/__tests__/nodes-route.test.ts +179 -0
- package/src/server/__tests__/origin-guard.test.ts +72 -0
- package/src/server/__tests__/publishers.test.ts +216 -0
- package/src/server/__tests__/server.smoke.test.ts +178 -0
- package/src/server/__tests__/settings-route.test.ts +177 -0
- package/src/server/__tests__/sse-route.test.ts +119 -0
- package/src/server/__tests__/status-route.test.ts +113 -0
- package/src/server/error-handler.ts +108 -0
- package/src/server/events/bus.ts +42 -0
- package/src/server/events/sse-route.ts +81 -0
- package/src/server/events/types.ts +22 -0
- package/src/server/index.ts +209 -0
- package/src/server/origin-guard.ts +84 -0
- package/src/server/routes/nat.ts +63 -0
- package/src/server/routes/nodes.ts +147 -0
- package/src/server/routes/settings.ts +115 -0
- package/src/server/routes/status.ts +108 -0
- package/src/server/routes/trust-circle.ts +49 -0
- package/src/server/routes/update.ts +43 -0
- package/src/server/server.ts +122 -0
- package/src/server/settings-store.ts +37 -0
- package/src/server/static.ts +191 -0
- package/src/update/__tests__/apply.test.ts +101 -0
- package/src/update/__tests__/manifest.test.ts +93 -0
- package/src/update/__tests__/store.test.ts +81 -0
- package/src/update/__tests__/update-service.integration.test.ts +221 -0
- package/src/update/__tests__/version.test.ts +31 -0
- package/src/update/apply.ts +148 -0
- package/src/update/index.ts +303 -0
- package/src/update/manifest.ts +172 -0
- package/src/update/release-key.ts +55 -0
- package/src/update/store.ts +101 -0
- package/src/update/types.ts +109 -0
- package/src/update/version.ts +80 -0
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import Fastify from 'fastify';
|
|
2
|
+
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
|
3
|
+
|
|
4
|
+
import { registerErrorHandler } from '../error-handler.js';
|
|
5
|
+
import { registerStatusRoute } from '../routes/status.js';
|
|
6
|
+
import type { HostProcessOrchestrator } from '../../orchestrator/index.js';
|
|
7
|
+
import type { ManagedNodeInfo } from '../../orchestrator/types.js';
|
|
8
|
+
import type { TrustCircleService } from '../../auth/index.js';
|
|
9
|
+
import type { TrustCircleSnapshot } from '../../auth/types.js';
|
|
10
|
+
import type { NatService } from '../../nat/index.js';
|
|
11
|
+
import type { NatStatusSnapshot } from '../../nat/types.js';
|
|
12
|
+
import type { UpdateService } from '../../update/index.js';
|
|
13
|
+
import type { UpdateState } from '../../update/types.js';
|
|
14
|
+
|
|
15
|
+
function fakeOrchestrator(nodes: ManagedNodeInfo[]): HostProcessOrchestrator {
|
|
16
|
+
return { listNodes: () => nodes } as unknown as HostProcessOrchestrator;
|
|
17
|
+
}
|
|
18
|
+
function fakeTrustCircle(snap: TrustCircleSnapshot): TrustCircleService {
|
|
19
|
+
return { list: async () => snap } as unknown as TrustCircleService;
|
|
20
|
+
}
|
|
21
|
+
function fakeNat(snap: NatStatusSnapshot): NatService {
|
|
22
|
+
return { getStatus: () => snap } as unknown as NatService;
|
|
23
|
+
}
|
|
24
|
+
function fakeUpdate(state: UpdateState): UpdateService {
|
|
25
|
+
return { getState: async () => state } as unknown as UpdateService;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const SAMPLE_CONNECTIVITY: NatStatusSnapshot = {
|
|
29
|
+
portMode: 'auto-upnp',
|
|
30
|
+
externalPort: 4001,
|
|
31
|
+
internalPort: 4001,
|
|
32
|
+
routerExternalIp: '203.0.113.5',
|
|
33
|
+
mappingLeaseExpiresAt: null,
|
|
34
|
+
externalIp: '203.0.113.5',
|
|
35
|
+
externalIpDetectedAt: null,
|
|
36
|
+
cgnatDetected: false,
|
|
37
|
+
directReachability: 'reachable',
|
|
38
|
+
lastTestedAt: null,
|
|
39
|
+
ddns: {
|
|
40
|
+
providerId: null,
|
|
41
|
+
hostname: null,
|
|
42
|
+
externallyManaged: false,
|
|
43
|
+
lastUpdateAt: null,
|
|
44
|
+
lastUpdateOk: null,
|
|
45
|
+
lastError: null,
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
describe('GET /api/status', () => {
|
|
50
|
+
let app: ReturnType<typeof Fastify>;
|
|
51
|
+
|
|
52
|
+
afterEach(async () => { await app.close(); });
|
|
53
|
+
|
|
54
|
+
it('returns aggregated status without update service', async () => {
|
|
55
|
+
app = Fastify();
|
|
56
|
+
registerErrorHandler(app);
|
|
57
|
+
registerStatusRoute(app, {
|
|
58
|
+
orchestrator: fakeOrchestrator([
|
|
59
|
+
{
|
|
60
|
+
id: 'alice',
|
|
61
|
+
dockerId: '1234:abc',
|
|
62
|
+
partyId: 'party-alice',
|
|
63
|
+
profile: 'storage',
|
|
64
|
+
status: 'running',
|
|
65
|
+
spawnedAt: '2025-01-01T00:00:00Z',
|
|
66
|
+
workdir: '/tmp/alice',
|
|
67
|
+
ports: { health: 1, metrics: 2, p2p: 3 },
|
|
68
|
+
},
|
|
69
|
+
]),
|
|
70
|
+
trustCircle: fakeTrustCircle({
|
|
71
|
+
members: [{ peerId: 'p1', label: 'Self', addedAt: '2025-01-01T00:00:00Z', self: true }],
|
|
72
|
+
pending: [],
|
|
73
|
+
}),
|
|
74
|
+
nat: fakeNat(SAMPLE_CONNECTIVITY),
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
const res = await app.inject({ method: 'GET', url: '/api/status' });
|
|
78
|
+
expect(res.statusCode).toBe(200);
|
|
79
|
+
const body = res.json() as {
|
|
80
|
+
service: { name: string; version: string; uptimeSeconds: number };
|
|
81
|
+
nodes: Array<{ id: string; status: string }>;
|
|
82
|
+
trustCircle: { members: number; pending: number };
|
|
83
|
+
connectivity: { portMode: string };
|
|
84
|
+
update?: { available?: string };
|
|
85
|
+
};
|
|
86
|
+
expect(body.service.name).toBe('cadre-host');
|
|
87
|
+
expect(body.nodes).toHaveLength(1);
|
|
88
|
+
expect(body.nodes[0]).toMatchObject({ id: 'alice', status: 'running' });
|
|
89
|
+
expect(body.trustCircle).toEqual({ members: 1, pending: 0 });
|
|
90
|
+
expect(body.connectivity.portMode).toBe('auto-upnp');
|
|
91
|
+
expect(body.update).toBeUndefined();
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('includes update info when service is present', async () => {
|
|
95
|
+
app = Fastify();
|
|
96
|
+
registerErrorHandler(app);
|
|
97
|
+
registerStatusRoute(app, {
|
|
98
|
+
orchestrator: fakeOrchestrator([]),
|
|
99
|
+
trustCircle: fakeTrustCircle({ members: [], pending: [] }),
|
|
100
|
+
nat: fakeNat(SAMPLE_CONNECTIVITY),
|
|
101
|
+
update: fakeUpdate({
|
|
102
|
+
version: 1,
|
|
103
|
+
lastChecked: '2025-06-01T00:00:00Z',
|
|
104
|
+
available: { version: '0.7.0', publishedAt: '2025-06-01T00:00:00Z' },
|
|
105
|
+
}),
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
const res = await app.inject({ method: 'GET', url: '/api/status' });
|
|
109
|
+
expect(res.statusCode).toBe(200);
|
|
110
|
+
const body = res.json() as { update?: { available?: string; lastChecked?: string } };
|
|
111
|
+
expect(body.update).toEqual({ available: '0.7.0', lastChecked: '2025-06-01T00:00:00Z' });
|
|
112
|
+
});
|
|
113
|
+
});
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fastify error handler — translates known typed errors to stable HTTP status
|
|
3
|
+
* codes and uniform `{ ok: false, error: { code, message } }` payloads.
|
|
4
|
+
*
|
|
5
|
+
* Codes (cross-referenced with `auth/types.ts`, `nat/types.ts`, `update/types.ts`):
|
|
6
|
+
* - TrustCircleError
|
|
7
|
+
* invalid_label, invalid_token → 400
|
|
8
|
+
* not_found, already_redeemed → 404
|
|
9
|
+
* expired → 410
|
|
10
|
+
* storage_error → 500
|
|
11
|
+
* - NatError
|
|
12
|
+
* invalid_config, ddns_provider_unknown,
|
|
13
|
+
* ddns_credentials_missing → 400
|
|
14
|
+
* secrets_unavailable, storage_error,
|
|
15
|
+
* mapping_failed, router_unreachable,
|
|
16
|
+
* ip_detection_failed, ddns_update_failed → 500
|
|
17
|
+
* - UpdateErrorException
|
|
18
|
+
* manifest_invalid, no_update_available,
|
|
19
|
+
* min_previous_version → 400
|
|
20
|
+
* apply_in_progress → 409
|
|
21
|
+
* signature_invalid, unsupported_state_version,
|
|
22
|
+
* apply_failed, rollback_failed, storage_error → 500
|
|
23
|
+
* - everything else → 500 (code "internal")
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import type { FastifyError, FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
|
27
|
+
import debug from 'debug';
|
|
28
|
+
|
|
29
|
+
import { TrustCircleError, type TrustCircleErrorCode } from '../auth/types.js';
|
|
30
|
+
import { NatError, type NatErrorCode } from '../nat/types.js';
|
|
31
|
+
import { UpdateErrorException, type UpdateErrorCode } from '../update/types.js';
|
|
32
|
+
|
|
33
|
+
const log = debug('cadre:host:error-handler');
|
|
34
|
+
|
|
35
|
+
const TRUST_STATUS: Record<TrustCircleErrorCode, number> = {
|
|
36
|
+
invalid_label: 400,
|
|
37
|
+
invalid_token: 400,
|
|
38
|
+
not_found: 404,
|
|
39
|
+
already_redeemed: 404,
|
|
40
|
+
expired: 410,
|
|
41
|
+
storage_error: 500,
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const NAT_STATUS: Record<NatErrorCode, number> = {
|
|
45
|
+
invalid_config: 400,
|
|
46
|
+
ddns_provider_unknown: 400,
|
|
47
|
+
ddns_credentials_missing: 400,
|
|
48
|
+
secrets_unavailable: 500,
|
|
49
|
+
storage_error: 500,
|
|
50
|
+
mapping_failed: 500,
|
|
51
|
+
router_unreachable: 500,
|
|
52
|
+
ip_detection_failed: 500,
|
|
53
|
+
ddns_update_failed: 500,
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const UPDATE_STATUS: Record<UpdateErrorCode, number> = {
|
|
57
|
+
manifest_invalid: 400,
|
|
58
|
+
no_update_available: 400,
|
|
59
|
+
min_previous_version: 400,
|
|
60
|
+
apply_in_progress: 409,
|
|
61
|
+
signature_invalid: 500,
|
|
62
|
+
unsupported_state_version: 500,
|
|
63
|
+
apply_failed: 500,
|
|
64
|
+
rollback_failed: 500,
|
|
65
|
+
storage_error: 500,
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export function registerErrorHandler(app: FastifyInstance): void {
|
|
69
|
+
app.setErrorHandler((err: FastifyError, request: FastifyRequest, reply: FastifyReply) => {
|
|
70
|
+
const { status, code, message } = classify(err);
|
|
71
|
+
if (status >= 500) {
|
|
72
|
+
log('5xx %s %s: [%s] %s', request.method, request.url, code, message);
|
|
73
|
+
} else {
|
|
74
|
+
log('%d %s %s: [%s] %s', status, request.method, request.url, code, message);
|
|
75
|
+
}
|
|
76
|
+
return reply.code(status).send({
|
|
77
|
+
ok: false,
|
|
78
|
+
error: { code, message },
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
interface Classified {
|
|
84
|
+
status: number;
|
|
85
|
+
code: string;
|
|
86
|
+
message: string;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function classify(err: FastifyError): Classified {
|
|
90
|
+
if (err instanceof TrustCircleError) {
|
|
91
|
+
return { status: TRUST_STATUS[err.code] ?? 500, code: err.code, message: err.message };
|
|
92
|
+
}
|
|
93
|
+
if (err instanceof NatError) {
|
|
94
|
+
return { status: NAT_STATUS[err.code] ?? 500, code: err.code, message: err.message };
|
|
95
|
+
}
|
|
96
|
+
if (err instanceof UpdateErrorException) {
|
|
97
|
+
return { status: UPDATE_STATUS[err.code] ?? 500, code: err.code, message: err.message };
|
|
98
|
+
}
|
|
99
|
+
// Fastify body-parsing / validation errors have a statusCode we should honour.
|
|
100
|
+
if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) {
|
|
101
|
+
return {
|
|
102
|
+
status: err.statusCode,
|
|
103
|
+
code: err.code ?? (err.statusCode === 404 ? 'not_found' : 'bad_request'),
|
|
104
|
+
message: err.message ?? 'request failed',
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
return { status: 500, code: 'internal', message: err.message || 'internal error' };
|
|
108
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory event bus for the local UI.
|
|
3
|
+
*
|
|
4
|
+
* Tiny synchronous fan-out: publishers (route adapters, orchestrator hook,
|
|
5
|
+
* update observer) call `publish`; SSE connections subscribe and receive every
|
|
6
|
+
* event until they unsubscribe. Listener errors are caught so one broken
|
|
7
|
+
* client cannot break others.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import debug from 'debug';
|
|
11
|
+
|
|
12
|
+
import type { LocalUiEvent } from './types.js';
|
|
13
|
+
|
|
14
|
+
const log = debug('cadre:host:event-bus');
|
|
15
|
+
|
|
16
|
+
export type LocalUiEventListener = (event: LocalUiEvent) => void;
|
|
17
|
+
|
|
18
|
+
export class EventBus {
|
|
19
|
+
private readonly listeners = new Set<LocalUiEventListener>();
|
|
20
|
+
|
|
21
|
+
publish(event: LocalUiEvent): void {
|
|
22
|
+
for (const listener of this.listeners) {
|
|
23
|
+
try {
|
|
24
|
+
listener(event);
|
|
25
|
+
} catch (err) {
|
|
26
|
+
log('listener threw for event %s: %s', event.type, (err as Error).message);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
subscribe(listener: LocalUiEventListener): () => void {
|
|
32
|
+
this.listeners.add(listener);
|
|
33
|
+
return () => {
|
|
34
|
+
this.listeners.delete(listener);
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Test helper. */
|
|
39
|
+
listenerCount(): number {
|
|
40
|
+
return this.listeners.size;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-Sent Events route — `GET /api/events`.
|
|
3
|
+
*
|
|
4
|
+
* Hand-rolled (~40 lines vs. the 30 KB @fastify/sse-v2 dep). The wire format:
|
|
5
|
+
*
|
|
6
|
+
* retry: 5000\n\n ← reconnect hint
|
|
7
|
+
* : heartbeat\n\n ← comment line, every 15 s
|
|
8
|
+
* event: <type>\n ← event name
|
|
9
|
+
* data: <json>\n\n ← payload
|
|
10
|
+
*
|
|
11
|
+
* The handler subscribes to the bus on connect, unsubscribes on client
|
|
12
|
+
* disconnect, and ticks a heartbeat so corporate proxies don't close the
|
|
13
|
+
* connection at the idle timeout.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
|
17
|
+
import debug from 'debug';
|
|
18
|
+
|
|
19
|
+
import type { EventBus } from './bus.js';
|
|
20
|
+
import type { LocalUiEvent } from './types.js';
|
|
21
|
+
|
|
22
|
+
const log = debug('cadre:host:sse');
|
|
23
|
+
|
|
24
|
+
const HEARTBEAT_INTERVAL_MS = 15_000;
|
|
25
|
+
const RECONNECT_HINT_MS = 5_000;
|
|
26
|
+
|
|
27
|
+
export interface SseRouteOptions {
|
|
28
|
+
events: EventBus;
|
|
29
|
+
/** Test override: shorter heartbeat. */
|
|
30
|
+
heartbeatIntervalMs?: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function registerSseRoute(app: FastifyInstance, opts: SseRouteOptions): void {
|
|
34
|
+
const heartbeatMs = opts.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS;
|
|
35
|
+
|
|
36
|
+
app.get('/api/events', (request: FastifyRequest, reply: FastifyReply) => {
|
|
37
|
+
// Tell Fastify we're handling the reply ourselves — it won't try to
|
|
38
|
+
// serialise or send a payload.
|
|
39
|
+
reply.hijack();
|
|
40
|
+
reply.raw.writeHead(200, {
|
|
41
|
+
'Content-Type': 'text/event-stream',
|
|
42
|
+
'Cache-Control': 'no-cache, no-transform',
|
|
43
|
+
Connection: 'keep-alive',
|
|
44
|
+
'X-Accel-Buffering': 'no',
|
|
45
|
+
});
|
|
46
|
+
reply.raw.write(`retry: ${RECONNECT_HINT_MS}\n\n`);
|
|
47
|
+
reply.raw.write(`: connected\n\n`);
|
|
48
|
+
|
|
49
|
+
const onEvent = (event: LocalUiEvent): void => {
|
|
50
|
+
try {
|
|
51
|
+
reply.raw.write(`event: ${event.type}\n`);
|
|
52
|
+
reply.raw.write(`data: ${JSON.stringify(event)}\n\n`);
|
|
53
|
+
} catch (err) {
|
|
54
|
+
log('write failed (client likely gone): %s', (err as Error).message);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
const unsubscribe = opts.events.subscribe(onEvent);
|
|
58
|
+
|
|
59
|
+
const heartbeat = setInterval(() => {
|
|
60
|
+
try {
|
|
61
|
+
reply.raw.write(`: heartbeat\n\n`);
|
|
62
|
+
} catch (err) {
|
|
63
|
+
log('heartbeat write failed: %s', (err as Error).message);
|
|
64
|
+
}
|
|
65
|
+
}, heartbeatMs);
|
|
66
|
+
// Don't hold the event loop open for the heartbeat alone.
|
|
67
|
+
if (typeof heartbeat === 'object' && 'unref' in heartbeat) {
|
|
68
|
+
(heartbeat as { unref?: () => void }).unref?.();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const cleanup = (): void => {
|
|
72
|
+
clearInterval(heartbeat);
|
|
73
|
+
unsubscribe();
|
|
74
|
+
};
|
|
75
|
+
request.raw.on('close', cleanup);
|
|
76
|
+
request.raw.on('error', cleanup);
|
|
77
|
+
|
|
78
|
+
// The reply object is intentionally not returned — Fastify must not
|
|
79
|
+
// attempt to serialise an SSE response.
|
|
80
|
+
});
|
|
81
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Event types broadcast over the SPA's SSE channel.
|
|
3
|
+
*
|
|
4
|
+
* Publishers (orchestrator hook, route adapters, update observer) call
|
|
5
|
+
* EventBus.publish; the `/api/events` route fan-outs to connected clients.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { ContainerStatus } from '@serfab/cadre-provider';
|
|
9
|
+
|
|
10
|
+
import type { DirectReachability, PortForwardMode } from '../../nat/index.js';
|
|
11
|
+
|
|
12
|
+
export type LocalUiEvent =
|
|
13
|
+
| { type: 'node-state-changed'; nodeId: string; status: ContainerStatus }
|
|
14
|
+
| { type: 'trust-circle-changed'; kind: 'invited' | 'redeemed' | 'revoked' }
|
|
15
|
+
| {
|
|
16
|
+
type: 'connectivity-changed';
|
|
17
|
+
portMode: PortForwardMode;
|
|
18
|
+
directReachability: DirectReachability;
|
|
19
|
+
}
|
|
20
|
+
| { type: 'update-available'; version: string; releaseNotesUrl?: string };
|
|
21
|
+
|
|
22
|
+
export type LocalUiEventType = LocalUiEvent['type'];
|
|
@@ -0,0 +1,209 @@
|
|
|
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
|
+
|
|
26
|
+
import { EventBus } from './events/bus.js';
|
|
27
|
+
import { registerSseRoute } from './events/sse-route.js';
|
|
28
|
+
import { registerErrorHandler } from './error-handler.js';
|
|
29
|
+
import { registerOriginGuard } from './origin-guard.js';
|
|
30
|
+
import { registerStaticMount } from './static.js';
|
|
31
|
+
import { buildFastify, startListening, stopListening } from './server.js';
|
|
32
|
+
import { registerNatRoutes } from './routes/nat.js';
|
|
33
|
+
import { registerTrustCircleRoutes } from './routes/trust-circle.js';
|
|
34
|
+
import { registerUpdateRoutes } from './routes/update.js';
|
|
35
|
+
import { registerStatusRoute } from './routes/status.js';
|
|
36
|
+
import { registerNodesRoutes } from './routes/nodes.js';
|
|
37
|
+
import { registerSettingsRoutes } from './routes/settings.js';
|
|
38
|
+
import { HostSettingsStore } from './settings-store.js';
|
|
39
|
+
|
|
40
|
+
export interface LocalUiServerOptions {
|
|
41
|
+
/** Configured UI port from host.config.json. May be re-bound on collision. */
|
|
42
|
+
uiPort: number;
|
|
43
|
+
/** Resolved data dir (passed by cadre-host start). */
|
|
44
|
+
dataDir: string;
|
|
45
|
+
/** Wired dependencies — all owned by the caller. */
|
|
46
|
+
orchestrator: HostProcessOrchestrator;
|
|
47
|
+
trustCircle: TrustCircleService;
|
|
48
|
+
nat: NatService;
|
|
49
|
+
/** Optional — 6.4.2 lands this; nullable while still iterating. */
|
|
50
|
+
update?: UpdateService;
|
|
51
|
+
/** Settings I/O facade. Defaults to a new one rooted at `dataDir`. */
|
|
52
|
+
settingsStore?: HostSettingsStore;
|
|
53
|
+
/** Bus instance — pass the same one to subsystems that publish events. */
|
|
54
|
+
events?: EventBus;
|
|
55
|
+
/**
|
|
56
|
+
* Static asset root override. Defaults to `<package>/dist/ui`. When the
|
|
57
|
+
* directory is absent the root handler returns a placeholder HTML.
|
|
58
|
+
*/
|
|
59
|
+
staticRoot?: string;
|
|
60
|
+
/**
|
|
61
|
+
* Test-only: bind to port 0 (OS picks any free port). The returned URL
|
|
62
|
+
* reflects the actual bound port.
|
|
63
|
+
*/
|
|
64
|
+
forcePort?: 0;
|
|
65
|
+
/**
|
|
66
|
+
* SSE heartbeat interval (ms). Defaults to 15 000 ms. Tests reduce this
|
|
67
|
+
* so the heartbeat can be observed quickly.
|
|
68
|
+
*/
|
|
69
|
+
sseHeartbeatMs?: number;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface LocalUiServer {
|
|
73
|
+
app: FastifyInstance;
|
|
74
|
+
events: EventBus;
|
|
75
|
+
/** Resolves with the actually-bound port. */
|
|
76
|
+
start(): Promise<{ port: number; url: string }>;
|
|
77
|
+
stop(): Promise<void>;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** How often to poll UpdateService.getState() looking for new versions. */
|
|
81
|
+
const UPDATE_OBSERVER_INTERVAL_MS = 60_000;
|
|
82
|
+
|
|
83
|
+
export function createLocalUiServer(opts: LocalUiServerOptions): LocalUiServer {
|
|
84
|
+
const events = opts.events ?? new EventBus();
|
|
85
|
+
const settingsStore = opts.settingsStore ?? new HostSettingsStore({ dataDir: opts.dataDir });
|
|
86
|
+
|
|
87
|
+
const app = buildFastify();
|
|
88
|
+
|
|
89
|
+
// Bound port is unknown until start(); the guard is registered then.
|
|
90
|
+
|
|
91
|
+
registerErrorHandler(app);
|
|
92
|
+
|
|
93
|
+
// /api/events (SSE) — must be registered before the static fallback so
|
|
94
|
+
// the not-found handler doesn't try to serve it.
|
|
95
|
+
registerSseRoute(app, {
|
|
96
|
+
events,
|
|
97
|
+
...(opts.sseHeartbeatMs !== undefined ? { heartbeatIntervalMs: opts.sseHeartbeatMs } : {}),
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
registerStatusRoute(app, {
|
|
101
|
+
orchestrator: opts.orchestrator,
|
|
102
|
+
trustCircle: opts.trustCircle,
|
|
103
|
+
nat: opts.nat,
|
|
104
|
+
...(opts.update ? { update: opts.update } : {}),
|
|
105
|
+
});
|
|
106
|
+
registerNodesRoutes(app, { orchestrator: opts.orchestrator });
|
|
107
|
+
registerSettingsRoutes(app, { settingsStore, nat: opts.nat, ...(opts.update ? { update: opts.update } : {}) });
|
|
108
|
+
|
|
109
|
+
registerTrustCircleRoutes(app, { handlers: createTrustCircleHandlers(opts.trustCircle), events });
|
|
110
|
+
registerNatRoutes(app, { handlers: createNatHandlers(opts.nat), events });
|
|
111
|
+
if (opts.update) {
|
|
112
|
+
registerUpdateRoutes(app, { handlers: createUpdateHandlers(opts.update), events });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Static mount registers as the not-found handler — declared last so the
|
|
116
|
+
// API paths above win.
|
|
117
|
+
registerStaticMount(app, { ...(opts.staticRoot !== undefined ? { rootDir: opts.staticRoot } : {}) });
|
|
118
|
+
|
|
119
|
+
let bound: { port: number; url: string } | null = null;
|
|
120
|
+
let stopped = false;
|
|
121
|
+
const teardown: Array<() => void> = [];
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
app,
|
|
125
|
+
events,
|
|
126
|
+
async start() {
|
|
127
|
+
if (bound) return bound;
|
|
128
|
+
// Origin guard reads the port at request time via the getter so the
|
|
129
|
+
// post-fallback bound port is honoured. Registered here (not at
|
|
130
|
+
// factory time) so it lives in the same lifecycle as listen.
|
|
131
|
+
registerOriginGuard(app, { port: () => bound?.port ?? opts.uiPort });
|
|
132
|
+
const started = await startListening(app, {
|
|
133
|
+
preferredPort: opts.uiPort,
|
|
134
|
+
...(opts.forcePort === 0 ? { forcePort: 0 as const } : {}),
|
|
135
|
+
});
|
|
136
|
+
bound = started;
|
|
137
|
+
|
|
138
|
+
// Orchestrator → bus adapter: forward node state changes.
|
|
139
|
+
teardown.push(
|
|
140
|
+
opts.orchestrator.onStateChange((info) => {
|
|
141
|
+
events.publish({
|
|
142
|
+
type: 'node-state-changed',
|
|
143
|
+
nodeId: info.id,
|
|
144
|
+
status: info.status === 'running' ? 'running' : 'stopped',
|
|
145
|
+
});
|
|
146
|
+
}),
|
|
147
|
+
);
|
|
148
|
+
|
|
149
|
+
// One-shot connectivity publish — the SPA will get a sane initial
|
|
150
|
+
// signal even if no settings have changed yet this session.
|
|
151
|
+
try {
|
|
152
|
+
const snap = opts.nat.getStatus();
|
|
153
|
+
events.publish({
|
|
154
|
+
type: 'connectivity-changed',
|
|
155
|
+
portMode: snap.portMode,
|
|
156
|
+
directReachability: snap.directReachability,
|
|
157
|
+
});
|
|
158
|
+
} catch {
|
|
159
|
+
// NatService.start may not have completed; harmless to skip.
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Update observer: poll UpdateService.getState() every 60 s and emit
|
|
163
|
+
// `update-available` when `available.version` changes. Cheap, avoids
|
|
164
|
+
// poking at the service's internals.
|
|
165
|
+
if (opts.update) {
|
|
166
|
+
const update = opts.update;
|
|
167
|
+
let lastVersion: string | undefined;
|
|
168
|
+
const tick = async (): Promise<void> => {
|
|
169
|
+
try {
|
|
170
|
+
const state = await update.getState();
|
|
171
|
+
const available = state.available;
|
|
172
|
+
if (available && available.version && available.version !== lastVersion) {
|
|
173
|
+
lastVersion = available.version;
|
|
174
|
+
events.publish({
|
|
175
|
+
type: 'update-available',
|
|
176
|
+
version: available.version,
|
|
177
|
+
...(available.releaseNotesUrl ? { releaseNotesUrl: available.releaseNotesUrl } : {}),
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
} catch {
|
|
181
|
+
// Update store I/O failure — silent, will retry next tick.
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
// Fire once on boot in case the timer set `available` before the server bound.
|
|
185
|
+
void tick();
|
|
186
|
+
const timer = setInterval(() => { void tick(); }, UPDATE_OBSERVER_INTERVAL_MS);
|
|
187
|
+
if (typeof timer === 'object' && 'unref' in timer) {
|
|
188
|
+
(timer as { unref?: () => void }).unref?.();
|
|
189
|
+
}
|
|
190
|
+
teardown.push(() => clearInterval(timer));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return started;
|
|
194
|
+
},
|
|
195
|
+
async stop() {
|
|
196
|
+
if (stopped) return;
|
|
197
|
+
stopped = true;
|
|
198
|
+
for (const fn of teardown.splice(0, teardown.length)) {
|
|
199
|
+
try { fn(); } catch { /* ignore teardown errors */ }
|
|
200
|
+
}
|
|
201
|
+
await stopListening(app);
|
|
202
|
+
},
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export { EventBus } from './events/bus.js';
|
|
207
|
+
export type { LocalUiEventListener } from './events/bus.js';
|
|
208
|
+
export type { LocalUiEvent, LocalUiEventType } from './events/types.js';
|
|
209
|
+
export { HostSettingsStore } from './settings-store.js';
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Origin guard — defeats DNS-rebind attacks against the loopback listener.
|
|
3
|
+
*
|
|
4
|
+
* The listener is bound to 127.0.0.1 only, but a malicious page on
|
|
5
|
+
* `evil.example.com` can still resolve its own hostname to 127.0.0.1 and
|
|
6
|
+
* speak HTTP to us. We mitigate by requiring that:
|
|
7
|
+
* - `Host` is `127.0.0.1[:port]` or `localhost[:port]` (case-insensitive),
|
|
8
|
+
* - `Origin` (when present) matches one of those origins.
|
|
9
|
+
*
|
|
10
|
+
* Forbidden requests return 403 with the standard error envelope.
|
|
11
|
+
*
|
|
12
|
+
* The expected port can be supplied as a constant or as a getter — the
|
|
13
|
+
* server's port-fallback loop discovers the bound port only after `listen`,
|
|
14
|
+
* but Fastify hooks must be registered before `ready`, so the guard reads
|
|
15
|
+
* the port at request time via the getter.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
|
19
|
+
|
|
20
|
+
export interface OriginGuardOptions {
|
|
21
|
+
/** Bound port (constant) or a getter for the current bound port. */
|
|
22
|
+
port: number | (() => number);
|
|
23
|
+
/** Allow these additional hosts (test harnesses, integrations). */
|
|
24
|
+
extraAllowedHosts?: ReadonlyArray<string>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const ALLOWED_HOSTNAMES = ['127.0.0.1', 'localhost', '[::1]', '::1'] as const;
|
|
28
|
+
|
|
29
|
+
export function registerOriginGuard(app: FastifyInstance, opts: OriginGuardOptions): void {
|
|
30
|
+
const getPort = typeof opts.port === 'function' ? opts.port : () => opts.port as number;
|
|
31
|
+
const extras = (opts.extraAllowedHosts ?? []).map((e) => e.toLowerCase());
|
|
32
|
+
|
|
33
|
+
app.addHook('onRequest', async (request: FastifyRequest, reply: FastifyReply) => {
|
|
34
|
+
const port = getPort();
|
|
35
|
+
const allowedHosts = buildAllowedHostHeaders(port, extras);
|
|
36
|
+
const allowedOrigins = buildAllowedOrigins(port, extras);
|
|
37
|
+
|
|
38
|
+
const hostHeader = (request.headers.host ?? '').toLowerCase();
|
|
39
|
+
if (!hostHeader || !allowedHosts.has(hostHeader)) {
|
|
40
|
+
return reply.code(403).send({
|
|
41
|
+
ok: false,
|
|
42
|
+
error: {
|
|
43
|
+
code: 'forbidden_origin',
|
|
44
|
+
message: `Host header "${request.headers.host ?? ''}" is not allowed`,
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
const origin = request.headers.origin;
|
|
49
|
+
if (typeof origin === 'string' && origin.length > 0) {
|
|
50
|
+
if (!allowedOrigins.has(origin.toLowerCase())) {
|
|
51
|
+
return reply.code(403).send({
|
|
52
|
+
ok: false,
|
|
53
|
+
error: {
|
|
54
|
+
code: 'forbidden_origin',
|
|
55
|
+
message: `Origin "${origin}" is not allowed`,
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return undefined;
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function buildAllowedHostHeaders(port: number, extras: ReadonlyArray<string>): Set<string> {
|
|
65
|
+
const set = new Set<string>();
|
|
66
|
+
for (const host of ALLOWED_HOSTNAMES) {
|
|
67
|
+
set.add(host);
|
|
68
|
+
set.add(`${host}:${port}`);
|
|
69
|
+
}
|
|
70
|
+
for (const e of extras) set.add(e);
|
|
71
|
+
return set;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function buildAllowedOrigins(port: number, extras: ReadonlyArray<string>): Set<string> {
|
|
75
|
+
const set = new Set<string>();
|
|
76
|
+
for (const host of ALLOWED_HOSTNAMES) {
|
|
77
|
+
set.add(`http://${host}`);
|
|
78
|
+
set.add(`http://${host}:${port}`);
|
|
79
|
+
set.add(`https://${host}`);
|
|
80
|
+
set.add(`https://${host}:${port}`);
|
|
81
|
+
}
|
|
82
|
+
for (const e of extras) set.add(e);
|
|
83
|
+
return set;
|
|
84
|
+
}
|