@serfab/cadre-host 0.11.0 → 0.13.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 (46) hide show
  1. package/README.md +406 -296
  2. package/dist/bin/host.d.ts +11 -7
  3. package/dist/bin/host.js +40 -12
  4. package/dist/bin/host.js.map +1 -1
  5. package/dist/installer/config.d.ts +4 -4
  6. package/dist/installer/config.js +5 -39
  7. package/dist/installer/config.js.map +1 -1
  8. package/dist/installer/identity.d.ts +8 -1
  9. package/dist/installer/identity.js +8 -1
  10. package/dist/installer/identity.js.map +1 -1
  11. package/dist/orchestrator/host-process-orchestrator.d.ts +2 -2
  12. package/dist/orchestrator/host-process-orchestrator.js +14 -4
  13. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  14. package/dist/server/routes/bootstrap-node-validation.d.ts +96 -0
  15. package/dist/server/routes/bootstrap-node-validation.js +178 -0
  16. package/dist/server/routes/bootstrap-node-validation.js.map +1 -0
  17. package/dist/server/routes/grants.js +8 -25
  18. package/dist/server/routes/grants.js.map +1 -1
  19. package/dist/server/routes/provision-request-validation.d.ts +45 -0
  20. package/dist/server/routes/provision-request-validation.js +97 -0
  21. package/dist/server/routes/provision-request-validation.js.map +1 -0
  22. package/dist/server/settings-store.d.ts +1 -1
  23. package/dist/server/settings-store.js +5 -1
  24. package/dist/server/settings-store.js.map +1 -1
  25. package/package.json +5 -4
  26. package/src/__tests__/cli.smoke.test.ts +8 -3
  27. package/src/__tests__/global-setup.ts +9 -4
  28. package/src/__tests__/orchestrator-node-identity.test.ts +204 -204
  29. package/src/__tests__/orchestrator.test.ts +951 -951
  30. package/src/bin/__tests__/cli-reference.test.ts +167 -0
  31. package/src/bin/host.ts +1326 -1299
  32. package/src/donation/__tests__/donation-service.test.ts +1068 -1068
  33. package/src/donation/__tests__/donation-supervisor.test.ts +510 -510
  34. package/src/donation/__tests__/fake-orchestrator.test.ts +168 -168
  35. package/src/installer/__tests__/config.test.ts +134 -112
  36. package/src/installer/config.ts +5 -43
  37. package/src/installer/identity.ts +8 -1
  38. package/src/nat/__tests__/nat-service.test.ts +515 -497
  39. package/src/orchestrator/host-process-orchestrator.ts +1143 -1133
  40. package/src/server/__tests__/bootstrap-node-validation.test.ts +134 -0
  41. package/src/server/__tests__/grants-route.test.ts +326 -263
  42. package/src/server/__tests__/settings-route.test.ts +8 -7
  43. package/src/server/routes/bootstrap-node-validation.ts +187 -0
  44. package/src/server/routes/grants.ts +9 -26
  45. package/src/server/routes/provision-request-validation.ts +105 -0
  46. package/src/server/settings-store.ts +41 -37
@@ -1,168 +1,168 @@
1
- /**
2
- * Contract tests for `FakeOrchestrator` itself — the handle lifecycle it borrows
3
- * from `HostProcessOrchestrator`. The donation suites lean on these semantics to
4
- * express races that only exist because the real class drops and rejects
5
- * handles, so this file exists to stop a later relaxation of the fake from
6
- * quietly turning one of those tests green. Each case names the real behaviour
7
- * it mirrors.
8
- */
9
-
10
- import { describe, expect, it } from 'vitest';
11
-
12
- import type { OrchestratorCreateRequest } from '@serfab/cadre-provider';
13
-
14
- import { FakeOrchestrator } from './fake-orchestrator.js';
15
-
16
- const request = (containerId: string): OrchestratorCreateRequest => ({
17
- containerId,
18
- partyId: 'party-P',
19
- bootstrapNodes: ['/ip4/127.0.0.1/tcp/4001/p2p/12D3KooReq'],
20
- profile: 'storage',
21
- });
22
-
23
- describe('FakeOrchestrator handle lifecycle', () => {
24
- it('drops the prior handle when a re-spawn succeeds (mirrors dropStaleHandle)', async () => {
25
- const orch = new FakeOrchestrator();
26
- const first = await orch.createContainer(request('grn_1'));
27
- const second = await orch.createContainer(request('grn_1'));
28
-
29
- await expect(orch.stopContainer(first.dockerId)).rejects.toThrow(
30
- `Container not found: ${first.dockerId}`,
31
- );
32
- // The rejected call left no trace: `stopped` records handles acted on, not
33
- // calls attempted.
34
- expect(orch.stopped).toEqual([]);
35
- // …and the container now resolves only to the new spawn.
36
- expect(orch.resolveDockerId('grn_1')).toBe(second.dockerId);
37
-
38
- await orch.stopContainer(second.dockerId);
39
- expect(orch.stopped).toEqual([second.dockerId]);
40
- });
41
-
42
- it('drops only the re-spawned container, leaving another container untouched', async () => {
43
- const orch = new FakeOrchestrator();
44
- const other = await orch.createContainer(request('grn_2'));
45
- await orch.createContainer(request('grn_1'));
46
- await orch.createContainer(request('grn_1'));
47
-
48
- // The real drop filters on containerId; a fake that cleared the whole map
49
- // would still pass every same-container case above.
50
- await expect(orch.stopContainer(other.dockerId)).resolves.toBeUndefined();
51
- expect(orch.resolveDockerId('grn_2')).toBe(other.dockerId);
52
- });
53
-
54
- it('keeps the prior handle live across the whole pre-drop await window', async () => {
55
- const orch = new FakeOrchestrator();
56
- const first = await orch.createContainer(request('grn_1'));
57
-
58
- // The invariant the donation race tests rest on: a concurrent stop started
59
- // from `onCreate` still finds the old handle. Deferring it onto a microtask
60
- // puts it strictly after `onCreate` returns and strictly before the
61
- // `createDelayMs` timer, so this one case pins the drop behind BOTH — with
62
- // no dependence on wall-clock timing. The outcome is captured rather than
63
- // rethrown so a regression fails this assertion instead of surfacing as an
64
- // unhandled rejection.
65
- orch.createDelayMs = 1;
66
- let outcome: Promise<string> | undefined;
67
- orch.onCreate = () => {
68
- outcome ??= Promise.resolve()
69
- .then(() => orch.stopContainer(first.dockerId))
70
- .then(() => 'stopped', (err: Error) => `rejected: ${err.message}`);
71
- };
72
-
73
- const second = await orch.createContainer(request('grn_1'));
74
-
75
- expect(await outcome).toBe('stopped');
76
- expect(orch.stopped).toEqual([first.dockerId]);
77
- expect(orch.resolveDockerId('grn_1')).toBe(second.dockerId);
78
- });
79
-
80
- it('leaves the prior handle in place when the re-spawn fails (mirrors restoreDroppedHandles)', async () => {
81
- const orch = new FakeOrchestrator();
82
- const first = await orch.createContainer(request('grn_1'));
83
-
84
- orch.failCreate = true;
85
- await expect(orch.createContainer(request('grn_1'))).rejects.toThrow('spawn boom');
86
-
87
- // Host state is exactly as the failed attempt found it — which is what lets
88
- // `DonationSupervisor.giveUp` still stop the child it knows about.
89
- await expect(orch.stopContainer(first.dockerId)).resolves.toBeUndefined();
90
- expect(orch.stopped).toEqual([first.dockerId]);
91
- expect(orch.resolveDockerId('grn_1')).toBe(first.dockerId);
92
- });
93
-
94
- it('rejects a never-issued dockerId (mirrors requireHandle)', async () => {
95
- const orch = new FakeOrchestrator();
96
-
97
- await expect(orch.removeContainer('dock_nope')).rejects.toThrow(
98
- 'Container not found: dock_nope',
99
- );
100
- expect(orch.removed).toEqual([]);
101
- });
102
-
103
- it('rejects a second call once a handle has been removed (mirrors removeContainer deleting it)', async () => {
104
- const orch = new FakeOrchestrator();
105
- const { dockerId } = await orch.createContainer(request('grn_1'));
106
-
107
- await orch.removeContainer(dockerId);
108
- expect(orch.removed).toEqual([dockerId]);
109
-
110
- await expect(orch.stopContainer(dockerId)).rejects.toThrow(
111
- `Container not found: ${dockerId}`,
112
- );
113
- expect(orch.stopped).toEqual([]);
114
- });
115
-
116
- it('fires onStop for a rejected stop, so a test can still observe the attempt', async () => {
117
- const orch = new FakeOrchestrator();
118
- const attempted: string[] = [];
119
- orch.onStop = (id) => { attempted.push(id); };
120
-
121
- await expect(orch.stopContainer('dock_nope')).rejects.toThrow('Container not found');
122
- expect(attempted).toEqual(['dock_nope']);
123
- expect(orch.stopped).toEqual([]);
124
- });
125
-
126
- it('refuses to reclaim the workdir of a container that still resolves (mirrors the live-handle guard)', async () => {
127
- const orch = new FakeOrchestrator();
128
- await orch.createContainer(request('grn_1'));
129
-
130
- // A live handle owns that directory; only `removeContainer` — which stops
131
- // the child first — may delete it.
132
- expect(orch.reclaimWorkdir('grn_1')).toBe(false);
133
- expect(orch.reclaimedWorkdirs).toEqual([]);
134
- });
135
-
136
- it('reclaims the workdir of a container no handle owns', async () => {
137
- const orch = new FakeOrchestrator();
138
-
139
- // Never spawned — the stuck-`provisioning` record whose host died before a
140
- // handle ever existed.
141
- expect(orch.reclaimWorkdir('grn_orphan')).toBe(true);
142
- expect(orch.reclaimedWorkdirs).toEqual(['grn_orphan']);
143
-
144
- // …and once the container's own handle is removed, its id becomes
145
- // reclaimable too.
146
- const { dockerId } = await orch.createContainer(request('grn_1'));
147
- expect(orch.reclaimWorkdir('grn_1')).toBe(false);
148
- await orch.removeContainer(dockerId);
149
- expect(orch.reclaimWorkdir('grn_1')).toBe(true);
150
- expect(orch.reclaimedWorkdirs).toEqual(['grn_orphan', 'grn_1']);
151
- });
152
-
153
- it('fires onSpawned after the drop, with the new handle live and the old one gone', async () => {
154
- const orch = new FakeOrchestrator();
155
- const first = await orch.createContainer(request('grn_1'));
156
-
157
- let observed: { spawned: string; resolves: string | undefined } | undefined;
158
- orch.onSpawned = (dockerId) => {
159
- observed = { spawned: dockerId, resolves: orch.resolveDockerId('grn_1') };
160
- };
161
- const second = await orch.createContainer(request('grn_1'));
162
-
163
- // The post-drop world: the container already resolves to the new handle, so
164
- // work driven from here sees what `abandonRespawn`'s caller would see.
165
- expect(observed).toEqual({ spawned: second.dockerId, resolves: second.dockerId });
166
- expect(second.dockerId).not.toBe(first.dockerId);
167
- });
168
- });
1
+ /**
2
+ * Contract tests for `FakeOrchestrator` itself — the handle lifecycle it borrows
3
+ * from `HostProcessOrchestrator`. The donation suites lean on these semantics to
4
+ * express races that only exist because the real class drops and rejects
5
+ * handles, so this file exists to stop a later relaxation of the fake from
6
+ * quietly turning one of those tests green. Each case names the real behaviour
7
+ * it mirrors.
8
+ */
9
+
10
+ import { describe, expect, it } from 'vitest';
11
+
12
+ import type { OrchestratorCreateRequest } from '@serfab/cadre-provider';
13
+
14
+ import { FakeOrchestrator } from './fake-orchestrator.js';
15
+
16
+ const request = (containerId: string): OrchestratorCreateRequest => ({
17
+ containerId,
18
+ partyId: 'party-P',
19
+ bootstrapNodes: ['/ip4/127.0.0.1/tcp/4001/p2p/12D3KooWA9hbnKrRnPRSPTRkzXqTHzGE8YpJ3JHZmQ5tGwLRTMmp'],
20
+ profile: 'storage',
21
+ });
22
+
23
+ describe('FakeOrchestrator handle lifecycle', () => {
24
+ it('drops the prior handle when a re-spawn succeeds (mirrors dropStaleHandle)', async () => {
25
+ const orch = new FakeOrchestrator();
26
+ const first = await orch.createContainer(request('grn_1'));
27
+ const second = await orch.createContainer(request('grn_1'));
28
+
29
+ await expect(orch.stopContainer(first.dockerId)).rejects.toThrow(
30
+ `Container not found: ${first.dockerId}`,
31
+ );
32
+ // The rejected call left no trace: `stopped` records handles acted on, not
33
+ // calls attempted.
34
+ expect(orch.stopped).toEqual([]);
35
+ // …and the container now resolves only to the new spawn.
36
+ expect(orch.resolveDockerId('grn_1')).toBe(second.dockerId);
37
+
38
+ await orch.stopContainer(second.dockerId);
39
+ expect(orch.stopped).toEqual([second.dockerId]);
40
+ });
41
+
42
+ it('drops only the re-spawned container, leaving another container untouched', async () => {
43
+ const orch = new FakeOrchestrator();
44
+ const other = await orch.createContainer(request('grn_2'));
45
+ await orch.createContainer(request('grn_1'));
46
+ await orch.createContainer(request('grn_1'));
47
+
48
+ // The real drop filters on containerId; a fake that cleared the whole map
49
+ // would still pass every same-container case above.
50
+ await expect(orch.stopContainer(other.dockerId)).resolves.toBeUndefined();
51
+ expect(orch.resolveDockerId('grn_2')).toBe(other.dockerId);
52
+ });
53
+
54
+ it('keeps the prior handle live across the whole pre-drop await window', async () => {
55
+ const orch = new FakeOrchestrator();
56
+ const first = await orch.createContainer(request('grn_1'));
57
+
58
+ // The invariant the donation race tests rest on: a concurrent stop started
59
+ // from `onCreate` still finds the old handle. Deferring it onto a microtask
60
+ // puts it strictly after `onCreate` returns and strictly before the
61
+ // `createDelayMs` timer, so this one case pins the drop behind BOTH — with
62
+ // no dependence on wall-clock timing. The outcome is captured rather than
63
+ // rethrown so a regression fails this assertion instead of surfacing as an
64
+ // unhandled rejection.
65
+ orch.createDelayMs = 1;
66
+ let outcome: Promise<string> | undefined;
67
+ orch.onCreate = () => {
68
+ outcome ??= Promise.resolve()
69
+ .then(() => orch.stopContainer(first.dockerId))
70
+ .then(() => 'stopped', (err: Error) => `rejected: ${err.message}`);
71
+ };
72
+
73
+ const second = await orch.createContainer(request('grn_1'));
74
+
75
+ expect(await outcome).toBe('stopped');
76
+ expect(orch.stopped).toEqual([first.dockerId]);
77
+ expect(orch.resolveDockerId('grn_1')).toBe(second.dockerId);
78
+ });
79
+
80
+ it('leaves the prior handle in place when the re-spawn fails (mirrors restoreDroppedHandles)', async () => {
81
+ const orch = new FakeOrchestrator();
82
+ const first = await orch.createContainer(request('grn_1'));
83
+
84
+ orch.failCreate = true;
85
+ await expect(orch.createContainer(request('grn_1'))).rejects.toThrow('spawn boom');
86
+
87
+ // Host state is exactly as the failed attempt found it — which is what lets
88
+ // `DonationSupervisor.giveUp` still stop the child it knows about.
89
+ await expect(orch.stopContainer(first.dockerId)).resolves.toBeUndefined();
90
+ expect(orch.stopped).toEqual([first.dockerId]);
91
+ expect(orch.resolveDockerId('grn_1')).toBe(first.dockerId);
92
+ });
93
+
94
+ it('rejects a never-issued dockerId (mirrors requireHandle)', async () => {
95
+ const orch = new FakeOrchestrator();
96
+
97
+ await expect(orch.removeContainer('dock_nope')).rejects.toThrow(
98
+ 'Container not found: dock_nope',
99
+ );
100
+ expect(orch.removed).toEqual([]);
101
+ });
102
+
103
+ it('rejects a second call once a handle has been removed (mirrors removeContainer deleting it)', async () => {
104
+ const orch = new FakeOrchestrator();
105
+ const { dockerId } = await orch.createContainer(request('grn_1'));
106
+
107
+ await orch.removeContainer(dockerId);
108
+ expect(orch.removed).toEqual([dockerId]);
109
+
110
+ await expect(orch.stopContainer(dockerId)).rejects.toThrow(
111
+ `Container not found: ${dockerId}`,
112
+ );
113
+ expect(orch.stopped).toEqual([]);
114
+ });
115
+
116
+ it('fires onStop for a rejected stop, so a test can still observe the attempt', async () => {
117
+ const orch = new FakeOrchestrator();
118
+ const attempted: string[] = [];
119
+ orch.onStop = (id) => { attempted.push(id); };
120
+
121
+ await expect(orch.stopContainer('dock_nope')).rejects.toThrow('Container not found');
122
+ expect(attempted).toEqual(['dock_nope']);
123
+ expect(orch.stopped).toEqual([]);
124
+ });
125
+
126
+ it('refuses to reclaim the workdir of a container that still resolves (mirrors the live-handle guard)', async () => {
127
+ const orch = new FakeOrchestrator();
128
+ await orch.createContainer(request('grn_1'));
129
+
130
+ // A live handle owns that directory; only `removeContainer` — which stops
131
+ // the child first — may delete it.
132
+ expect(orch.reclaimWorkdir('grn_1')).toBe(false);
133
+ expect(orch.reclaimedWorkdirs).toEqual([]);
134
+ });
135
+
136
+ it('reclaims the workdir of a container no handle owns', async () => {
137
+ const orch = new FakeOrchestrator();
138
+
139
+ // Never spawned — the stuck-`provisioning` record whose host died before a
140
+ // handle ever existed.
141
+ expect(orch.reclaimWorkdir('grn_orphan')).toBe(true);
142
+ expect(orch.reclaimedWorkdirs).toEqual(['grn_orphan']);
143
+
144
+ // …and once the container's own handle is removed, its id becomes
145
+ // reclaimable too.
146
+ const { dockerId } = await orch.createContainer(request('grn_1'));
147
+ expect(orch.reclaimWorkdir('grn_1')).toBe(false);
148
+ await orch.removeContainer(dockerId);
149
+ expect(orch.reclaimWorkdir('grn_1')).toBe(true);
150
+ expect(orch.reclaimedWorkdirs).toEqual(['grn_orphan', 'grn_1']);
151
+ });
152
+
153
+ it('fires onSpawned after the drop, with the new handle live and the old one gone', async () => {
154
+ const orch = new FakeOrchestrator();
155
+ const first = await orch.createContainer(request('grn_1'));
156
+
157
+ let observed: { spawned: string; resolves: string | undefined } | undefined;
158
+ orch.onSpawned = (dockerId) => {
159
+ observed = { spawned: dockerId, resolves: orch.resolveDockerId('grn_1') };
160
+ };
161
+ const second = await orch.createContainer(request('grn_1'));
162
+
163
+ // The post-drop world: the container already resolves to the new handle, so
164
+ // work driven from here sees what `abandonRespawn`'s caller would see.
165
+ expect(observed).toEqual({ spawned: second.dockerId, resolves: second.dockerId });
166
+ expect(second.dockerId).not.toBe(first.dockerId);
167
+ });
168
+ });
@@ -1,112 +1,134 @@
1
- import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2
- import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3
- import { tmpdir } from 'node:os';
4
- import { join } from 'node:path';
5
-
6
- import { readHostConfig, writeHostConfig, hostOwnsCadre, type HostConfigFile } from '../config.js';
7
-
8
- describe('host.config.json round-trip', () => {
9
- let tmp: string;
10
-
11
- beforeEach(() => {
12
- tmp = mkdtempSync(join(tmpdir(), 'cadre-host-cfg-'));
13
- });
14
-
15
- afterEach(() => {
16
- rmSync(tmp, { recursive: true, force: true });
17
- });
18
-
19
- function makeCfg(overrides: Partial<HostConfigFile> = {}): HostConfigFile {
20
- return {
21
- version: 2,
22
- installId: 'abc123',
23
- uiPort: 8765,
24
- libp2pPort: 4001,
25
- dataDir: tmp,
26
- identityPath: join(tmp, 'identity.key'),
27
- upnpEnabled: true,
28
- installedAt: '2026-01-01T00:00:00.000Z',
29
- installerVersion: '0.6.0',
30
- updates: { autoApply: false },
31
- ...overrides,
32
- };
33
- }
34
-
35
- it('writes and reads the same shape', () => {
36
- const cfg = makeCfg();
37
- const path = join(tmp, 'host.config.json');
38
- writeHostConfig(path, cfg);
39
- expect(readHostConfig(path)).toEqual(cfg);
40
- });
41
-
42
- it('upgrades v1 files in place on read', () => {
43
- const path = join(tmp, 'host.config.json');
44
- const v1 = {
45
- version: 1,
46
- installId: 'abc123',
47
- uiPort: 8765,
48
- libp2pPort: 4001,
49
- dataDir: tmp,
50
- identityPath: join(tmp, 'identity.key'),
51
- upnpEnabled: true,
52
- installedAt: '2026-01-01T00:00:00.000Z',
53
- installerVersion: '0.6.0',
54
- };
55
- writeFileSync(path, JSON.stringify(v1));
56
- const upgraded = readHostConfig(path);
57
- expect(upgraded.version).toBe(2);
58
- expect(upgraded.updates).toEqual({ autoApply: false });
59
- // Reading again should be idempotent and stay v2.
60
- const reRead = readHostConfig(path);
61
- expect(reRead.version).toBe(2);
62
- });
63
-
64
- it('rejects unknown versions', () => {
65
- const path = join(tmp, 'host.config.json');
66
- writeFileSync(path, JSON.stringify({ ...makeCfg(), version: 99 }));
67
- expect(() => readHostConfig(path)).toThrow(/unsupported version=99/);
68
- });
69
-
70
- it('rejects malformed JSON', () => {
71
- const path = join(tmp, 'host.config.json');
72
- writeFileSync(path, 'not json');
73
- expect(() => readHostConfig(path)).toThrow(/Failed to parse/);
74
- });
75
-
76
- it('rejects missing required fields', () => {
77
- const path = join(tmp, 'host.config.json');
78
- writeFileSync(path, JSON.stringify({ version: 2, uiPort: 1234 }));
79
- expect(() => readHostConfig(path)).toThrow(/missing required fields/);
80
- });
81
-
82
- it('refuses to write the wrong version', () => {
83
- const path = join(tmp, 'host.config.json');
84
- expect(() => writeHostConfig(path, { ...makeCfg(), version: 3 as never })).toThrow(/version=3/);
85
- });
86
-
87
- it('round-trips ownCadre and hostOwnsCadre reflects it', () => {
88
- const path = join(tmp, 'host.config.json');
89
- const cfg = makeCfg({ ownCadre: { enabled: true } });
90
- writeHostConfig(path, cfg);
91
- const read = readHostConfig(path);
92
- expect(read.ownCadre).toEqual({ enabled: true });
93
- expect(hostOwnsCadre(read)).toBe(true);
94
- });
95
-
96
- it('treats an absent ownCadre as donor-only (hostOwnsCadre false)', () => {
97
- // A pre-ownCadre v2 config (field absent) must read back cleanly and be
98
- // donor-only — no migration, field stays absent.
99
- const path = join(tmp, 'host.config.json');
100
- const cfg = makeCfg();
101
- writeHostConfig(path, cfg);
102
- const read = readHostConfig(path);
103
- expect(read.ownCadre).toBeUndefined();
104
- expect(hostOwnsCadre(read)).toBe(false);
105
- });
106
-
107
- it('rejects a malformed ownCadre shape', () => {
108
- const path = join(tmp, 'host.config.json');
109
- writeFileSync(path, JSON.stringify({ ...makeCfg(), ownCadre: { enabled: 'yes' } }));
110
- expect(() => readHostConfig(path)).toThrow(/missing required fields/);
111
- });
112
- });
1
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+
6
+ import { readHostConfig, updateHostConfig, writeHostConfig, hostOwnsCadre, type HostConfigFile } from '../config.js';
7
+
8
+ describe('host.config.json round-trip', () => {
9
+ let tmp: string;
10
+
11
+ beforeEach(() => {
12
+ tmp = mkdtempSync(join(tmpdir(), 'cadre-host-cfg-'));
13
+ });
14
+
15
+ afterEach(() => {
16
+ rmSync(tmp, { recursive: true, force: true });
17
+ });
18
+
19
+ function makeCfg(overrides: Partial<HostConfigFile> = {}): HostConfigFile {
20
+ return {
21
+ version: 2,
22
+ installId: 'abc123',
23
+ uiPort: 8765,
24
+ libp2pPort: 4001,
25
+ dataDir: tmp,
26
+ identityPath: join(tmp, 'identity.key'),
27
+ upnpEnabled: true,
28
+ installedAt: '2026-01-01T00:00:00.000Z',
29
+ installerVersion: '0.6.0',
30
+ updates: { autoApply: false },
31
+ ...overrides,
32
+ };
33
+ }
34
+
35
+ it('writes and reads the same shape', () => {
36
+ const cfg = makeCfg();
37
+ const path = join(tmp, 'host.config.json');
38
+ writeHostConfig(path, cfg);
39
+ expect(readHostConfig(path)).toEqual(cfg);
40
+ });
41
+
42
+ it('rejects v1 files without rewriting them', () => {
43
+ const path = join(tmp, 'host.config.json');
44
+ const v1 = {
45
+ version: 1,
46
+ installId: 'abc123',
47
+ uiPort: 8765,
48
+ libp2pPort: 4001,
49
+ dataDir: tmp,
50
+ identityPath: join(tmp, 'identity.key'),
51
+ upnpEnabled: true,
52
+ installedAt: '2026-01-01T00:00:00.000Z',
53
+ installerVersion: '0.6.0',
54
+ };
55
+ const raw = JSON.stringify(v1);
56
+ writeFileSync(path, raw);
57
+ expect(() => readHostConfig(path)).toThrow(/unsupported version=1/);
58
+ expect(readFileSync(path, 'utf8')).toBe(raw);
59
+ });
60
+
61
+ it('rejects unknown versions', () => {
62
+ const path = join(tmp, 'host.config.json');
63
+ writeFileSync(path, JSON.stringify({ ...makeCfg(), version: 99 }));
64
+ expect(() => readHostConfig(path)).toThrow(/unsupported version=99/);
65
+ });
66
+
67
+ it('rejects a file with no version field', () => {
68
+ const { version: _version, ...noVersion } = makeCfg();
69
+ const path = join(tmp, 'host.config.json');
70
+ writeFileSync(path, JSON.stringify(noVersion));
71
+ expect(() => readHostConfig(path)).toThrow(/unsupported version=undefined/);
72
+ });
73
+
74
+ it('rejects malformed JSON', () => {
75
+ const path = join(tmp, 'host.config.json');
76
+ writeFileSync(path, 'not json');
77
+ expect(() => readHostConfig(path)).toThrow(/Failed to parse/);
78
+ });
79
+
80
+ it('rejects missing required fields', () => {
81
+ const path = join(tmp, 'host.config.json');
82
+ writeFileSync(path, JSON.stringify({ version: 2, uiPort: 1234 }));
83
+ expect(() => readHostConfig(path)).toThrow(/missing required fields/);
84
+ });
85
+
86
+ it('refuses to write the wrong version', () => {
87
+ const path = join(tmp, 'host.config.json');
88
+ expect(() => writeHostConfig(path, { ...makeCfg(), version: 3 as never })).toThrow(/version=3/);
89
+ });
90
+
91
+ it('update patches fields and re-stamps the current version', () => {
92
+ const path = join(tmp, 'host.config.json');
93
+ writeHostConfig(path, makeCfg());
94
+ const next = updateHostConfig(path, { updates: { autoApply: true } });
95
+ expect(next.version).toBe(2);
96
+ expect(next.updates).toEqual({ autoApply: true });
97
+ expect(next.installId).toBe('abc123');
98
+ expect(readHostConfig(path)).toEqual(next);
99
+ });
100
+
101
+ it('update never lets a patch downgrade the version', () => {
102
+ const path = join(tmp, 'host.config.json');
103
+ writeHostConfig(path, makeCfg());
104
+ const patch = { version: 1 } as unknown as Partial<Omit<HostConfigFile, 'version'>>;
105
+ expect(updateHostConfig(path, patch).version).toBe(2);
106
+ expect(readHostConfig(path).version).toBe(2);
107
+ });
108
+
109
+ it('round-trips ownCadre and hostOwnsCadre reflects it', () => {
110
+ const path = join(tmp, 'host.config.json');
111
+ const cfg = makeCfg({ ownCadre: { enabled: true } });
112
+ writeHostConfig(path, cfg);
113
+ const read = readHostConfig(path);
114
+ expect(read.ownCadre).toEqual({ enabled: true });
115
+ expect(hostOwnsCadre(read)).toBe(true);
116
+ });
117
+
118
+ it('treats an absent ownCadre as donor-only (hostOwnsCadre false)', () => {
119
+ // A pre-ownCadre v2 config (field absent) must read back cleanly and be
120
+ // donor-only — no migration, field stays absent.
121
+ const path = join(tmp, 'host.config.json');
122
+ const cfg = makeCfg();
123
+ writeHostConfig(path, cfg);
124
+ const read = readHostConfig(path);
125
+ expect(read.ownCadre).toBeUndefined();
126
+ expect(hostOwnsCadre(read)).toBe(false);
127
+ });
128
+
129
+ it('rejects a malformed ownCadre shape', () => {
130
+ const path = join(tmp, 'host.config.json');
131
+ writeFileSync(path, JSON.stringify({ ...makeCfg(), ownCadre: { enabled: 'yes' } }));
132
+ expect(() => readHostConfig(path)).toThrow(/missing required fields/);
133
+ });
134
+ });