@serfab/cadre-host 0.8.1 → 0.10.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 (198) hide show
  1. package/dist/auth/index.d.ts +2 -0
  2. package/dist/auth/index.js +1 -0
  3. package/dist/auth/index.js.map +1 -1
  4. package/dist/auth/self-label.d.ts +36 -0
  5. package/dist/auth/self-label.js +57 -0
  6. package/dist/auth/self-label.js.map +1 -0
  7. package/dist/auth/trust-circle.d.ts +36 -9
  8. package/dist/auth/trust-circle.js +40 -20
  9. package/dist/auth/trust-circle.js.map +1 -1
  10. package/dist/auth/types.d.ts +2 -2
  11. package/dist/bin/host.js +291 -54
  12. package/dist/bin/host.js.map +1 -1
  13. package/dist/donation/__tests__/fake-orchestrator.d.ts +103 -0
  14. package/dist/donation/__tests__/fake-orchestrator.js +180 -0
  15. package/dist/donation/__tests__/fake-orchestrator.js.map +1 -0
  16. package/dist/donation/donation-service.d.ts +361 -0
  17. package/dist/donation/donation-service.js +763 -0
  18. package/dist/donation/donation-service.js.map +1 -0
  19. package/dist/donation/donation-store.d.ts +49 -0
  20. package/dist/donation/donation-store.js +148 -0
  21. package/dist/donation/donation-store.js.map +1 -0
  22. package/dist/donation/donation-supervisor.d.ts +167 -0
  23. package/dist/donation/donation-supervisor.js +341 -0
  24. package/dist/donation/donation-supervisor.js.map +1 -0
  25. package/dist/donation/grant-service.d.ts +71 -0
  26. package/dist/donation/grant-service.js +163 -0
  27. package/dist/donation/grant-service.js.map +1 -0
  28. package/dist/donation/grant-store.d.ts +38 -0
  29. package/dist/donation/grant-store.js +135 -0
  30. package/dist/donation/grant-store.js.map +1 -0
  31. package/dist/donation/index.d.ts +20 -0
  32. package/dist/donation/index.js +17 -0
  33. package/dist/donation/index.js.map +1 -0
  34. package/dist/donation/types.d.ts +201 -0
  35. package/dist/donation/types.js +40 -0
  36. package/dist/donation/types.js.map +1 -0
  37. package/dist/index.d.ts +9 -5
  38. package/dist/index.js +7 -3
  39. package/dist/index.js.map +1 -1
  40. package/dist/installer/config.d.ts +26 -0
  41. package/dist/installer/config.js +13 -0
  42. package/dist/installer/config.js.map +1 -1
  43. package/dist/installer/index.d.ts +2 -0
  44. package/dist/installer/index.js +3 -0
  45. package/dist/installer/index.js.map +1 -1
  46. package/dist/installer/wizard.d.ts +4 -0
  47. package/dist/installer/wizard.js +5 -1
  48. package/dist/installer/wizard.js.map +1 -1
  49. package/dist/nat/nat-service.d.ts +5 -5
  50. package/dist/nat/nat-service.js +9 -9
  51. package/dist/nat/nat-service.js.map +1 -1
  52. package/dist/nat/types.d.ts +1 -1
  53. package/dist/orchestrator/host-process-orchestrator.d.ts +144 -32
  54. package/dist/orchestrator/host-process-orchestrator.js +397 -128
  55. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  56. package/dist/orchestrator/index.d.ts +3 -3
  57. package/dist/orchestrator/index.js +1 -1
  58. package/dist/orchestrator/index.js.map +1 -1
  59. package/dist/orchestrator/node-identity.d.ts +26 -0
  60. package/dist/orchestrator/node-identity.js +36 -0
  61. package/dist/orchestrator/node-identity.js.map +1 -0
  62. package/dist/orchestrator/port-allocator.d.ts +14 -0
  63. package/dist/orchestrator/port-allocator.js +45 -0
  64. package/dist/orchestrator/port-allocator.js.map +1 -1
  65. package/dist/orchestrator/state-store.d.ts +5 -5
  66. package/dist/orchestrator/state-store.js +2 -2
  67. package/dist/orchestrator/state-store.js.map +1 -1
  68. package/dist/orchestrator/types.d.ts +8 -8
  69. package/dist/owner/index.d.ts +11 -0
  70. package/dist/owner/index.js +11 -0
  71. package/dist/owner/index.js.map +1 -0
  72. package/dist/owner/owner-node-client.d.ts +110 -0
  73. package/dist/{authority/authority-node-client.js → owner/owner-node-client.js} +58 -17
  74. package/dist/owner/owner-node-client.js.map +1 -0
  75. package/dist/server/error-handler.d.ts +22 -1
  76. package/dist/server/error-handler.js +64 -1
  77. package/dist/server/error-handler.js.map +1 -1
  78. package/dist/server/events/types.d.ts +3 -0
  79. package/dist/server/index.d.ts +33 -2
  80. package/dist/server/index.js +43 -16
  81. package/dist/server/index.js.map +1 -1
  82. package/dist/server/routes/grants-admin.d.ts +17 -0
  83. package/dist/server/routes/grants-admin.js +32 -0
  84. package/dist/server/routes/grants-admin.js.map +1 -0
  85. package/dist/server/routes/grants.d.ts +28 -0
  86. package/dist/server/routes/grants.js +182 -0
  87. package/dist/server/routes/grants.js.map +1 -0
  88. package/dist/server/routes/nodes.d.ts +5 -4
  89. package/dist/server/routes/nodes.js +19 -18
  90. package/dist/server/routes/nodes.js.map +1 -1
  91. package/dist/server/routes/settings.d.ts +6 -1
  92. package/dist/server/routes/settings.js +5 -2
  93. package/dist/server/routes/settings.js.map +1 -1
  94. package/dist/server/routes/status.d.ts +8 -4
  95. package/dist/server/routes/status.js +9 -4
  96. package/dist/server/routes/status.js.map +1 -1
  97. package/dist/server/routes/strands.d.ts +20 -0
  98. package/dist/server/routes/strands.js +38 -0
  99. package/dist/server/routes/strands.js.map +1 -0
  100. package/dist/strands/index.d.ts +7 -0
  101. package/dist/strands/index.js +6 -0
  102. package/dist/strands/index.js.map +1 -0
  103. package/dist/strands/strand-service.d.ts +50 -0
  104. package/dist/strands/strand-service.js +103 -0
  105. package/dist/strands/strand-service.js.map +1 -0
  106. package/dist/strands/types.d.ts +93 -0
  107. package/dist/strands/types.js +23 -0
  108. package/dist/strands/types.js.map +1 -0
  109. package/dist/ui/assets/index-BVoqLjyX.css +1 -0
  110. package/dist/ui/assets/index-C-iks41M.js +17 -0
  111. package/dist/ui/assets/index-C-iks41M.js.map +1 -0
  112. package/dist/ui/index.html +2 -2
  113. package/dist/update/release-key.d.ts +1 -1
  114. package/dist/update/release-key.js +8 -6
  115. package/dist/update/release-key.js.map +1 -1
  116. package/package.json +5 -5
  117. package/src/__tests__/build-targets.test.ts +26 -0
  118. package/src/__tests__/global-setup.ts +51 -0
  119. package/src/__tests__/{host-authority.smoke.test.ts → host-owner.smoke.test.ts} +7 -7
  120. package/src/__tests__/orchestrator-env-scrub.test.ts +140 -0
  121. package/src/__tests__/orchestrator-node-identity.test.ts +204 -0
  122. package/src/__tests__/{orchestrator-authority.test.ts → orchestrator-owner.test.ts} +33 -33
  123. package/src/__tests__/orchestrator-pin-keys.test.ts +153 -0
  124. package/src/__tests__/orchestrator-push.test.ts +10 -10
  125. package/src/__tests__/orchestrator.test.ts +387 -6
  126. package/src/auth/__tests__/self-label.test.ts +85 -0
  127. package/src/auth/__tests__/trust-circle-integration.test.ts +152 -147
  128. package/src/auth/__tests__/trust-circle.test.ts +55 -11
  129. package/src/auth/index.ts +2 -0
  130. package/src/auth/self-label.ts +74 -0
  131. package/src/auth/trust-circle.ts +54 -22
  132. package/src/auth/types.ts +2 -2
  133. package/src/bin/host.ts +1299 -1038
  134. package/src/donation/__tests__/donation-service.test.ts +1068 -0
  135. package/src/donation/__tests__/donation-supervisor.test.ts +510 -0
  136. package/src/donation/__tests__/fake-orchestrator.test.ts +168 -0
  137. package/src/donation/__tests__/fake-orchestrator.ts +225 -0
  138. package/src/donation/__tests__/grant-service.test.ts +213 -0
  139. package/src/donation/__tests__/grant-store.test.ts +113 -0
  140. package/src/donation/donation-service.ts +962 -0
  141. package/src/donation/donation-store.ts +171 -0
  142. package/src/donation/donation-supervisor.ts +388 -0
  143. package/src/donation/grant-service.ts +200 -0
  144. package/src/donation/grant-store.ts +152 -0
  145. package/src/donation/index.ts +64 -0
  146. package/src/donation/types.ts +243 -0
  147. package/src/index.ts +51 -5
  148. package/src/installer/__tests__/config.test.ts +27 -1
  149. package/src/installer/__tests__/installer.smoke.test.ts +31 -1
  150. package/src/installer/__tests__/wizard.test.ts +5 -1
  151. package/src/installer/config.ts +34 -0
  152. package/src/installer/index.ts +5 -0
  153. package/src/installer/wizard.ts +12 -1
  154. package/src/nat/__tests__/nat-service.test.ts +5 -5
  155. package/src/nat/nat-service.ts +10 -10
  156. package/src/nat/types.ts +1 -1
  157. package/src/orchestrator/__tests__/node-identity.test.ts +62 -0
  158. package/src/orchestrator/host-process-orchestrator.ts +401 -134
  159. package/src/orchestrator/index.ts +3 -3
  160. package/src/orchestrator/node-identity.ts +40 -0
  161. package/src/orchestrator/port-allocator.ts +48 -0
  162. package/src/orchestrator/state-store.ts +7 -7
  163. package/src/orchestrator/types.ts +8 -8
  164. package/src/{authority/__tests__/authority-node-client.test.ts → owner/__tests__/owner-node-client.test.ts} +45 -17
  165. package/src/owner/index.ts +12 -0
  166. package/src/{authority/authority-node-client.ts → owner/owner-node-client.ts} +83 -23
  167. package/src/server/__tests__/error-handler.test.ts +22 -0
  168. package/src/server/__tests__/grants-admin-route.test.ts +73 -0
  169. package/src/server/__tests__/grants-route.test.ts +263 -0
  170. package/src/server/__tests__/nodes-route.test.ts +25 -25
  171. package/src/server/__tests__/server.smoke.test.ts +75 -0
  172. package/src/server/__tests__/settings-route.test.ts +17 -0
  173. package/src/server/__tests__/status-route.test.ts +21 -0
  174. package/src/server/__tests__/strands-route.test.ts +233 -0
  175. package/src/server/error-handler.ts +67 -1
  176. package/src/server/events/types.ts +1 -0
  177. package/src/server/index.ts +75 -17
  178. package/src/server/routes/grants-admin.ts +41 -0
  179. package/src/server/routes/grants.ts +210 -0
  180. package/src/server/routes/nodes.ts +19 -18
  181. package/src/server/routes/settings.ts +11 -3
  182. package/src/server/routes/status.ts +18 -8
  183. package/src/server/routes/strands.ts +54 -0
  184. package/src/strands/__tests__/strand-service.test.ts +165 -0
  185. package/src/strands/index.ts +14 -0
  186. package/src/strands/strand-service.ts +135 -0
  187. package/src/strands/types.ts +102 -0
  188. package/src/update/__tests__/release-key.test.ts +16 -3
  189. package/src/update/release-key.ts +8 -6
  190. package/dist/authority/authority-node-client.d.ts +0 -77
  191. package/dist/authority/authority-node-client.js.map +0 -1
  192. package/dist/authority/index.d.ts +0 -11
  193. package/dist/authority/index.js +0 -11
  194. package/dist/authority/index.js.map +0 -1
  195. package/dist/ui/assets/index-BlMXQPSw.js +0 -14
  196. package/dist/ui/assets/index-BlMXQPSw.js.map +0 -1
  197. package/dist/ui/assets/index-BwU5mJGF.css +0 -1
  198. package/src/authority/index.ts +0 -12
package/src/bin/host.ts CHANGED
@@ -1,1038 +1,1299 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * CLI entrypoint for cadre-host — the self-hosted cadre node manager.
5
- *
6
- * Most subcommands are still stubs at this stage (real implementations land
7
- * in the sibling tickets cadre-host-nat, cadre-host-installer,
8
- * cadre-host-local-ui).
9
- *
10
- * The `invite` and `trust` commands talk to the running cadre-host
11
- * management API over loopback. They are thin HTTP clients — they don't
12
- * spin up an inline service, so cadre-host must be running.
13
- */
14
-
15
- import { existsSync, readFileSync } from 'node:fs';
16
- import { createRequire } from 'node:module';
17
- import { fileURLToPath } from 'node:url';
18
- import { dirname, join, resolve } from 'node:path';
19
-
20
- import { Command } from 'commander';
21
-
22
- import { parseDuration } from '../auth/duration.js';
23
- import { Installer } from '../installer/index.js';
24
- import { readHostConfig, updateHostConfig } from '../installer/config.js';
25
- import {
26
- configPath as resolveConfigPath,
27
- defaultDataDir,
28
- defaultHostJs,
29
- defaultServiceDir,
30
- identityPath as resolveIdentityPath,
31
- } from '../installer/paths.js';
32
- import { detectPlatform } from '../installer/platform.js';
33
- import { createServiceHost } from '../installer/service-host/index.js';
34
- import { UpdateService } from '../update/index.js';
35
- import { HostProcessOrchestrator } from '../orchestrator/index.js';
36
- import { TrustCircleService, TrustCircleStore } from '../auth/index.js';
37
- import { NatService } from '../nat/index.js';
38
- import { createSecretsStore } from '../nat/secrets/index.js';
39
- import {
40
- resolvePushCredentials,
41
- setFcmSecret,
42
- setApnsSecret,
43
- clearPushSecret,
44
- pushStatus,
45
- } from '../push/index.js';
46
- import { AuthorityNodeClient } from '../authority/index.js';
47
- import { createLocalUiServer, HostSettingsStore } from '../server/index.js';
48
- import { openBrowser } from '../installer/browser.js';
49
-
50
- const DEFAULT_PORT = Number(process.env.CADRE_HOST_PORT ?? '8765');
51
-
52
- /** libp2p peer-ID prefixes by key type: Ed25519, secp256k1, legacy RSA. */
53
- const PEER_ID_PREFIXES = ['12D3Koo', '16Uiu2HAm', 'Qm'] as const;
54
-
55
- function looksLikePeerId(id: string): boolean {
56
- return PEER_ID_PREFIXES.some((p) => id.startsWith(p));
57
- }
58
-
59
- function resolvePort(raw: string): number {
60
- const n = Number(raw);
61
- if (!Number.isFinite(n) || n <= 0 || n > 65535) {
62
- console.error(`Invalid --port: ${raw}`);
63
- process.exit(1);
64
- }
65
- return n;
66
- }
67
-
68
- const program = new Command();
69
-
70
- program
71
- .name('cadre-host')
72
- .description('Sereus cadre node manager for self-hosted basement-PC deployments')
73
- .version('0.6.0');
74
-
75
- // ============================================================================
76
- // install — run the first-run wizard + register the system service
77
- // ============================================================================
78
-
79
- program
80
- .command('install')
81
- .description('Install cadre-host as a system service and run first-run setup')
82
- .option('--non-interactive', 'Use defaults / CLI flags only; never prompt')
83
- .option('--data-dir <path>', 'Override the data directory')
84
- .option('--ui-port <port>', 'Override the management UI port', parseIntArg)
85
- .option('--libp2p-port <port>', 'Override the cadre libp2p port', parseIntArg)
86
- .option('--no-upnp', 'Disable UPnP/NAT-PMP probing on first run')
87
- .option('--no-browser', 'Do not open a browser after install')
88
- .option('--no-invite', 'Skip generating the first enrollment invite')
89
- .option('--system', 'System-wide install (not yet supported in v1)')
90
- .option('--node-path <path>', 'Override the node binary embedded in the service unit')
91
- .action(async (opts: {
92
- nonInteractive?: boolean;
93
- dataDir?: string;
94
- uiPort?: number;
95
- libp2pPort?: number;
96
- upnp?: boolean;
97
- browser?: boolean;
98
- invite?: boolean;
99
- system?: boolean;
100
- nodePath?: string;
101
- }) => {
102
- const installer = new Installer();
103
- try {
104
- const result = await installer.install({
105
- nonInteractive: Boolean(opts.nonInteractive),
106
- ...(opts.dataDir ? { dataDir: opts.dataDir } : {}),
107
- ...(typeof opts.uiPort === 'number' ? { uiPort: opts.uiPort } : {}),
108
- ...(typeof opts.libp2pPort === 'number' ? { libp2pPort: opts.libp2pPort } : {}),
109
- noUpnp: opts.upnp === false,
110
- openBrowser: opts.browser !== false,
111
- noInvite: opts.invite === false,
112
- system: Boolean(opts.system),
113
- ...(opts.nodePath ? { nodePath: opts.nodePath } : {}),
114
- });
115
- console.log(`cadre-host installed.`);
116
- console.log(` Data dir: ${result.dataDir}`);
117
- console.log(` UI: ${result.uiUrl}`);
118
- console.log(` Service: ${result.serviceName}`);
119
- if (result.enrollmentInvite) {
120
- printEnrollmentInvite(result.enrollmentInvite);
121
- }
122
- process.exit(0);
123
- } catch (err) {
124
- console.error(`install failed: ${(err as Error).message}`);
125
- process.exit(1);
126
- }
127
- });
128
-
129
- // ============================================================================
130
- // uninstall — stop + deregister the system service
131
- // ============================================================================
132
-
133
- program
134
- .command('uninstall')
135
- .description('Stop and uninstall the cadre-host service')
136
- .option('--yes', 'Skip the confirmation prompt (for scripts)')
137
- .option('--remove-data', 'Also remove the data directory (default: preserve)')
138
- .option('--data-dir <path>', 'Override the data directory to clean up')
139
- .action(async (opts: { yes?: boolean; removeData?: boolean; dataDir?: string }) => {
140
- const installer = new Installer();
141
- try {
142
- // --remove-data is destructive and irreversible (identity + trust circle
143
- // are wiped). Require explicit --yes when stdin isn't a TTY, and prompt
144
- // confirmation when it is.
145
- if (opts.removeData && !opts.yes) {
146
- if (!process.stdin.isTTY) {
147
- console.error('uninstall: --remove-data requires --yes when stdin is not a TTY.');
148
- process.exit(1);
149
- return;
150
- }
151
- const dataDir = opts.dataDir ?? '(default data directory)';
152
- const confirmed = await confirmDestructive(
153
- `This will permanently delete ${dataDir} (identity, trust circle, NAT state). Continue? [y/N] `,
154
- );
155
- if (!confirmed) {
156
- console.error('uninstall aborted.');
157
- process.exit(1);
158
- return;
159
- }
160
- }
161
- await installer.uninstall({
162
- yes: Boolean(opts.yes),
163
- removeData: Boolean(opts.removeData),
164
- ...(opts.dataDir ? { dataDir: opts.dataDir } : {}),
165
- });
166
- console.log('cadre-host uninstalled.');
167
- process.exit(0);
168
- } catch (err) {
169
- console.error(`uninstall failed: ${(err as Error).message}`);
170
- process.exit(1);
171
- }
172
- });
173
-
174
- // ============================================================================
175
- // status — show service-host registration / running state
176
- // ============================================================================
177
-
178
- program
179
- .command('status')
180
- .description('Show running status of cadre-host and the cadre nodes it manages')
181
- .action(async () => {
182
- const installer = new Installer();
183
- try {
184
- const status = await installer.status();
185
- console.log(`Service installed: ${status.installed ? 'yes' : 'no'}`);
186
- console.log(`Service running: ${status.running ? 'yes' : 'no'}`);
187
- process.exit(0);
188
- } catch (err) {
189
- console.error(`status failed: ${(err as Error).message}`);
190
- process.exit(1);
191
- }
192
- });
193
-
194
- // ============================================================================
195
- // start — load config + identity, bind management API listener, wait
196
- // ============================================================================
197
-
198
- program
199
- .command('start')
200
- .description('Start cadre-host in the foreground')
201
- .option('--data-dir <path>', 'Override the data directory (env: CADRE_HOST_DATA_DIR)')
202
- .option('--no-tui', 'Reserved — currently a no-op (no TUI implemented yet)')
203
- .action(async (opts: { dataDir?: string; tui?: boolean }) => {
204
- try {
205
- void opts.tui;
206
- const platform = detectPlatform();
207
- const dataDir = opts.dataDir ?? process.env.CADRE_HOST_DATA_DIR ?? defaultDataDir(platform);
208
- const cfgPath = resolveConfigPath(dataDir);
209
- if (!existsSync(cfgPath)) {
210
- console.error(
211
- `cadre-host start: ${cfgPath} not found. ` +
212
- `Run \`cadre-host install\` first (or pass --data-dir to an existing install).`,
213
- );
214
- process.exit(1);
215
- return;
216
- }
217
- const cfg = readHostConfig(cfgPath);
218
- const idPath = resolveIdentityPath(cfg.dataDir);
219
- if (!existsSync(idPath)) {
220
- console.error(`cadre-host start: identity file not found at ${idPath}. Re-run \`cadre-host install\`.`);
221
- process.exit(1);
222
- return;
223
- }
224
- console.log(`cadre-host starting (dataDir=${cfg.dataDir}, uiPort=${cfg.uiPort})`);
225
-
226
- // Update flow: notify-by-default; auto-apply opt-in via host.config.json.
227
- // The local-UI ticket (6.5) wires the handlers into HTTP routes; here we
228
- // just construct the service so the in-process timer + state file are
229
- // populated.
230
- const serviceHost = createServiceHost(platform);
231
- const updateService = new UpdateService({
232
- dataDir: cfg.dataDir,
233
- currentVersion: readPackageVersionForStart(),
234
- settings: cfg.updates,
235
- ...(cfg.updates.manifestUrl ? { manifestUrl: cfg.updates.manifestUrl } : {}),
236
- restart: async () => {
237
- try {
238
- await serviceHost.restart({
239
- nodePath: process.execPath,
240
- hostJs: defaultHostJs(),
241
- dataDir: cfg.dataDir,
242
- serviceDir: defaultServiceDir(),
243
- });
244
- return undefined;
245
- } catch (err) {
246
- return (err as Error).message;
247
- }
248
- },
249
- });
250
- // Persist settings changes back to host.config.json on PUT /update/settings.
251
- updateService.onSettingsChanged((next) => {
252
- try {
253
- updateHostConfig(cfgPath, { updates: next });
254
- } catch (err) {
255
- console.error(`failed to persist updated settings to ${cfgPath}: ${(err as Error).message}`);
256
- }
257
- });
258
- // Don't block startup on the network round-trip — call and forget.
259
- void updateService.check();
260
- updateService.start();
261
-
262
- // Wire the long-lived HTTP management server. The manager holds no
263
- // in-process cadre node: it spawns the admin's **authority node** as a
264
- // managed child and delegates authority/membership/identity operations
265
- // to it over the node's loopback admin channel (the 6.6 contract). The
266
- // manager never joins the control network (see docs/cadre-host.md
267
- // § Control-plane separation).
268
- // Push (FCM/APNs) credentials are resolved fresh on every node spawn so a
269
- // restart re-reads the secret store (rotated keys) and nothing raw is
270
- // persisted in state.json. The non-secret bits (bundle id / sandbox toggle,
271
- // cooldown/debounce) are re-read from host.config.json each call too.
272
- const pushSecrets = await createSecretsStore(cfg.dataDir);
273
- const orchestrator = new HostProcessOrchestrator({
274
- rootDir: join(cfg.dataDir, 'orchestrator'),
275
- pushResolver: () => resolvePushCredentials(pushSecrets, readHostConfig(cfgPath).push),
276
- });
277
- await orchestrator.init();
278
-
279
- // Spawn the authority node. Best-effort: a spawn failure leaves the
280
- // management API up (trust-circle listing degrades to local labels,
281
- // authority ops return 503) rather than taking down the whole process.
282
- try {
283
- await orchestrator.ensureAuthorityNode({
284
- identityPath: idPath,
285
- partyId: cfg.installId,
286
- libp2pPort: cfg.libp2pPort,
287
- });
288
- console.log('cadre-host: authority node spawned');
289
- } catch (err) {
290
- console.error(`authority node spawn failed: ${(err as Error).message}`);
291
- }
292
-
293
- // The client reads the admin endpoint lazily so a node restart's fresh
294
- // bearer token is picked up automatically.
295
- const authority = new AuthorityNodeClient(() => orchestrator.getAuthorityAdminEndpoint());
296
-
297
- const trustCircle = new TrustCircleService({
298
- cadreNode: authority,
299
- store: new TrustCircleStore(cfg.dataDir),
300
- });
301
- const natService = new NatService({
302
- rootDir: cfg.dataDir,
303
- cadreNode: authority,
304
- });
305
-
306
- // Push NAT-resolved invite addresses to the node on every NAT change.
307
- // NatService.start() also fires this once as an initial push, retried
308
- // until the freshly spawned authority node accepts it (bounded; the
309
- // management API that mints invites comes up only after start() resolves).
310
- natService.onAddressesChanged(async (addresses) => {
311
- if (addresses.length === 0) return;
312
- try {
313
- await authority.pushInviteAddresses(addresses);
314
- } catch (err) {
315
- console.error(`invite-address push failed: ${(err as Error).message}`);
316
- }
317
- });
318
-
319
- // Best-effort NAT start. Failures here aren't fatal — the local UI
320
- // can still serve the trust circle, settings, etc.
321
- try {
322
- await natService.start();
323
- } catch (err) {
324
- console.error(`NAT start failed: ${(err as Error).message}`);
325
- }
326
-
327
- const settingsStore = new HostSettingsStore({ dataDir: cfg.dataDir });
328
- const server = createLocalUiServer({
329
- uiPort: cfg.uiPort,
330
- dataDir: cfg.dataDir,
331
- orchestrator,
332
- trustCircle,
333
- nat: natService,
334
- update: updateService,
335
- settingsStore,
336
- });
337
- const { url, port } = await server.start();
338
- if (port !== cfg.uiPort) {
339
- console.log(`(configured port ${cfg.uiPort} was in use — bound on ${port} instead)`);
340
- }
341
- console.log(`cadre-host local UI: ${url}`);
342
-
343
- await waitForTermination();
344
- try { await server.stop(); } catch { /* ignore */ }
345
- try { await natService.stop(); } catch { /* ignore */ }
346
- try { await orchestrator.stopAuthorityNode(); } catch { /* ignore */ }
347
- updateService.stop();
348
- console.log('cadre-host stopped.');
349
- process.exit(0);
350
- } catch (err) {
351
- console.error(`start failed: ${(err as Error).message}`);
352
- process.exit(1);
353
- }
354
- });
355
-
356
- // ============================================================================
357
- // ui — print the local-UI URL and open it in a browser
358
- // ============================================================================
359
-
360
- program
361
- .command('ui')
362
- .description('Print the local-UI URL and open it in the default browser')
363
- .option('--data-dir <path>', 'Override the data directory (env: CADRE_HOST_DATA_DIR)')
364
- .option('--no-browser', 'Print the URL but do not open a browser')
365
- .action((opts: { dataDir?: string; browser?: boolean }) => {
366
- try {
367
- const platform = detectPlatform();
368
- const dataDir = opts.dataDir ?? process.env.CADRE_HOST_DATA_DIR ?? defaultDataDir(platform);
369
- const cfgPath = resolveConfigPath(dataDir);
370
- if (!existsSync(cfgPath)) {
371
- console.error(`cadre-host ui: ${cfgPath} not found. Run \`cadre-host install\` first.`);
372
- process.exit(1);
373
- return;
374
- }
375
- const cfg = readHostConfig(cfgPath);
376
- const url = `http://127.0.0.1:${cfg.uiPort}`;
377
- console.log(url);
378
- if (opts.browser !== false) {
379
- const res = openBrowser(url);
380
- if (res.spawned) {
381
- console.log('(Opening in your default browser...)');
382
- } else if (res.error) {
383
- console.error(`(unable to launch browser: ${res.error})`);
384
- }
385
- }
386
- process.exit(0);
387
- } catch (err) {
388
- console.error(`ui failed: ${(err as Error).message}`);
389
- process.exit(1);
390
- }
391
- });
392
-
393
- function parseIntArg(raw: string): number {
394
- const n = Number(raw);
395
- if (!Number.isFinite(n) || !Number.isInteger(n)) {
396
- throw new Error(`Invalid integer: ${raw}`);
397
- }
398
- return n;
399
- }
400
-
401
- function readPackageVersionForStart(): string {
402
- try {
403
- // dist/bin/host.js -> ../../package.json
404
- const here = dirname(fileURLToPath(import.meta.url));
405
- const pkgPath = resolve(here, '..', '..', 'package.json');
406
- const raw = readFileSync(pkgPath, 'utf8');
407
- const parsed = JSON.parse(raw) as { version?: string };
408
- return parsed.version ?? '0.0.0-unknown';
409
- } catch {
410
- return '0.0.0-unknown';
411
- }
412
- }
413
-
414
- function waitForTermination(): Promise<void> {
415
- return new Promise<void>((resolveTerm) => {
416
- const done = () => resolveTerm();
417
- process.once('SIGINT', done);
418
- process.once('SIGTERM', done);
419
- });
420
- }
421
-
422
- async function confirmDestructive(message: string): Promise<boolean> {
423
- const { createInterface } = await import('node:readline');
424
- const rl = createInterface({ input: process.stdin, output: process.stdout });
425
- try {
426
- const answer = await new Promise<string>((res) => rl.question(message, res));
427
- return /^(y|yes)$/i.test(answer.trim());
428
- } finally {
429
- rl.close();
430
- }
431
- }
432
-
433
- const requireForQr = createRequire(import.meta.url);
434
-
435
- function printEnrollmentInvite(invite: { encodedInvite: string; expiresAt?: string }): void {
436
- // Best-effort QR render — fall back to the bare token if the lib chokes.
437
- console.log('\nEnroll your first device with this invite:');
438
- try {
439
- const qr = requireForQr('qrcode-terminal') as { generate: (text: string, opts?: { small?: boolean }, cb?: (s: string) => void) => void };
440
- qr.generate(invite.encodedInvite, { small: true }, (rendered) => {
441
- console.log(rendered);
442
- });
443
- } catch (err) {
444
- console.error(`(qrcode-terminal unavailable: ${(err as Error).message})`);
445
- }
446
- console.log(` ${invite.encodedInvite}`);
447
- if (invite.expiresAt) {
448
- console.log(` (expires ${invite.expiresAt})`);
449
- }
450
- }
451
-
452
- program
453
- .command('invite')
454
- .description('Generate an invite to add a member to the trust circle')
455
- .argument('<label>', 'Display label for the new member (e.g. "Mom\'s phone")')
456
- .option('--ttl <duration>', 'Invite lifetime (e.g. 24h, 7d, 30m)', '24h')
457
- .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
458
- .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
459
- .action(async (label: string, opts: { ttl: string; port: string; host: string }) => {
460
- let ttlMs: number;
461
- try {
462
- ttlMs = parseDuration(opts.ttl);
463
- } catch (err) {
464
- console.error(`Invalid --ttl: ${(err as Error).message}`);
465
- process.exit(1);
466
- return;
467
- }
468
-
469
- const port = resolvePort(opts.port);
470
-
471
- const url = `http://${opts.host}:${port}/auth/invites`;
472
- let response: Response;
473
- try {
474
- response = await fetch(url, {
475
- method: 'POST',
476
- headers: { 'content-type': 'application/json' },
477
- body: JSON.stringify({ label, ttlMs }),
478
- });
479
- } catch (err) {
480
- console.error(
481
- `Failed to reach cadre-host at ${url}: ${(err as Error).message}\n` +
482
- `Hint: is cadre-host running? Try \`cadre-host start\`.`,
483
- );
484
- process.exit(2);
485
- return;
486
- }
487
-
488
- if (!response.ok) {
489
- const text = await response.text().catch(() => '');
490
- console.error(`cadre-host returned ${response.status}: ${text || response.statusText}`);
491
- process.exit(1);
492
- return;
493
- }
494
-
495
- const body = await response.json() as { encodedInvite?: string; expiresAt?: string; token?: string };
496
- if (!body.encodedInvite) {
497
- console.error('cadre-host returned malformed response (missing encodedInvite)');
498
- process.exit(1);
499
- return;
500
- }
501
-
502
- console.log(body.encodedInvite);
503
- if (body.expiresAt) {
504
- console.error(`(expires at ${body.expiresAt})`);
505
- }
506
- process.exit(0);
507
- });
508
-
509
- const trust = program
510
- .command('trust')
511
- .description('Manage the trust circle (list members, revoke invites/members)');
512
-
513
- trust
514
- .command('list')
515
- .description('List trust-circle members and pending invites')
516
- .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
517
- .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
518
- .action(async (opts: { port: string; host: string }) => {
519
- const url = `http://${opts.host}:${resolvePort(opts.port)}/auth/trust-circle`;
520
- let response: Response;
521
- try {
522
- response = await fetch(url);
523
- } catch (err) {
524
- console.error(`Failed to reach cadre-host at ${url}: ${(err as Error).message}`);
525
- process.exit(2);
526
- return;
527
- }
528
- if (!response.ok) {
529
- console.error(`cadre-host returned ${response.status}: ${response.statusText}`);
530
- process.exit(1);
531
- return;
532
- }
533
- const body = await response.json() as {
534
- members: Array<{ peerId: string; label: string; addedAt: string; self?: boolean }>;
535
- pending: Array<{ token: string; label: string; createdAt: string; expiresAt?: string }>;
536
- };
537
- console.log('Members:');
538
- if (body.members.length === 0) {
539
- console.log(' (none)');
540
- } else {
541
- for (const m of body.members) {
542
- const self = m.self ? ' [self]' : '';
543
- console.log(` ${m.peerId} ${m.label}${self}`);
544
- }
545
- }
546
- console.log('\nPending invites:');
547
- if (body.pending.length === 0) {
548
- console.log(' (none)');
549
- } else {
550
- for (const p of body.pending) {
551
- const expires = p.expiresAt ? ` (expires ${p.expiresAt})` : '';
552
- console.log(` ${p.token} ${p.label}${expires}`);
553
- }
554
- }
555
- process.exit(0);
556
- });
557
-
558
- trust
559
- .command('revoke')
560
- .description('Revoke a pending invite (by token) or remove a member (by peerId)')
561
- .argument('<id>', 'Token (pending invite) or peerId (existing member) to remove')
562
- .option('--kind <kind>', 'Force interpretation: "invite" | "member" (default: auto)', 'auto')
563
- .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
564
- .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
565
- .action(async (id: string, opts: { kind: string; port: string; host: string }) => {
566
- const base = `http://${opts.host}:${resolvePort(opts.port)}`;
567
- const kind = opts.kind === 'auto'
568
- ? (looksLikePeerId(id) ? 'member' : 'invite')
569
- : opts.kind;
570
- const path = kind === 'member'
571
- ? `/auth/members/${encodeURIComponent(id)}`
572
- : `/auth/invites/${encodeURIComponent(id)}`;
573
-
574
- let response: Response;
575
- try {
576
- response = await fetch(`${base}${path}`, { method: 'DELETE' });
577
- } catch (err) {
578
- console.error(`Failed to reach cadre-host at ${base}: ${(err as Error).message}`);
579
- process.exit(2);
580
- return;
581
- }
582
- if (!response.ok) {
583
- const text = await response.text().catch(() => '');
584
- console.error(`cadre-host returned ${response.status}: ${text || response.statusText}`);
585
- process.exit(1);
586
- return;
587
- }
588
- console.log(`revoked ${kind}: ${id}`);
589
- process.exit(0);
590
- });
591
-
592
- // ============================================================================
593
- // nat subcommands
594
- // ============================================================================
595
-
596
- const nat = program
597
- .command('nat')
598
- .description('Manage NAT traversal, port forwarding, and dynamic DNS');
599
-
600
- nat
601
- .command('status')
602
- .description('Show NAT, external-IP, and DDNS status')
603
- .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
604
- .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
605
- .option('--json', 'Output raw JSON instead of a human-readable summary')
606
- .action(async (opts: { port: string; host: string; json?: boolean }) => {
607
- const url = `http://${opts.host}:${resolvePort(opts.port)}/nat/status`;
608
- const body = await getJson(url);
609
- if (opts.json) {
610
- console.log(JSON.stringify(body, null, 2));
611
- } else {
612
- printNatStatus(body);
613
- }
614
- process.exit(0);
615
- });
616
-
617
- nat
618
- .command('test')
619
- .description('Re-run reachability probes and print the result')
620
- .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
621
- .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
622
- .option('--json', 'Output raw JSON instead of a human-readable summary')
623
- .action(async (opts: { port: string; host: string; json?: boolean }) => {
624
- const url = `http://${opts.host}:${resolvePort(opts.port)}/nat/test`;
625
- const body = await postJson(url, {});
626
- if (opts.json) {
627
- console.log(JSON.stringify(body, null, 2));
628
- } else {
629
- printNatStatus(body);
630
- }
631
- process.exit(0);
632
- });
633
-
634
- nat
635
- .command('settings')
636
- .description('Update NAT settings (external port, UPnP toggle)')
637
- .option('--external-port <port>', 'External port to map')
638
- .option('--internal-port <port>', 'Internal libp2p port (defaults to external)')
639
- .option('--no-upnp', 'Disable UPnP/NAT-PMP port mapping')
640
- .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
641
- .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
642
- .action(async (opts: {
643
- externalPort?: string;
644
- internalPort?: string;
645
- upnp?: boolean;
646
- port: string;
647
- host: string;
648
- }) => {
649
- const url = `http://${opts.host}:${resolvePort(opts.port)}/nat/settings`;
650
- const patch: Record<string, unknown> = {};
651
- if (opts.externalPort) patch.externalPort = resolvePort(opts.externalPort);
652
- if (opts.internalPort) patch.internalPort = resolvePort(opts.internalPort);
653
- // Commander assigns `upnp: false` when `--no-upnp` is passed.
654
- if (opts.upnp === false) patch.upnpEnabled = false;
655
- if (opts.upnp === true) patch.upnpEnabled = true;
656
-
657
- const body = await putJson(url, patch);
658
- printNatStatus(body);
659
- process.exit(0);
660
- });
661
-
662
- const ddns = nat
663
- .command('ddns')
664
- .description('Configure dynamic DNS');
665
-
666
- ddns
667
- .command('set')
668
- .description('Configure a DDNS provider (and store credentials in the keychain)')
669
- .argument('<provider>', 'Provider ID (e.g. "duckdns")')
670
- .option('--hostname <hostname>', 'Hostname to publish (e.g. foo.duckdns.org)')
671
- .option('--token <token>', 'Provider token (a secret value; prompts if omitted)')
672
- .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
673
- .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
674
- .action(async (provider: string, opts: {
675
- hostname?: string;
676
- token?: string;
677
- port: string;
678
- host: string;
679
- }) => {
680
- if (!opts.hostname) {
681
- console.error('--hostname is required');
682
- process.exit(1);
683
- return;
684
- }
685
- const config: Record<string, string> = {};
686
- if (opts.token) config.token = opts.token;
687
-
688
- if (!config.token) {
689
- if (!process.stdin.isTTY) {
690
- console.error(
691
- 'Missing --token for provider "' + provider + '" and stdin is not a TTY. ' +
692
- 'Re-run with --token <secret>.',
693
- );
694
- process.exit(1);
695
- return;
696
- }
697
- try {
698
- config.token = await readSecretLine('DDNS token: ');
699
- } catch (err) {
700
- console.error('Failed to read token: ' + (err as Error).message);
701
- process.exit(1);
702
- return;
703
- }
704
- }
705
-
706
- const url = `http://${opts.host}:${resolvePort(opts.port)}/nat/ddns`;
707
- const body = await putJson(url, {
708
- providerId: provider,
709
- hostname: opts.hostname,
710
- config,
711
- externallyManaged: false,
712
- });
713
- printNatStatus(body);
714
- process.exit(0);
715
- });
716
-
717
- ddns
718
- .command('external')
719
- .description('Declare an externally-managed DDNS hostname (cadre-host does not update it)')
720
- .requiredOption('--hostname <hostname>', 'Hostname (no provider; cadre-host will not push updates)')
721
- .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
722
- .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
723
- .action(async (opts: { hostname: string; port: string; host: string }) => {
724
- const url = `http://${opts.host}:${resolvePort(opts.port)}/nat/settings`;
725
- const body = await putJson(url, {
726
- ddns: {
727
- providerId: 'external',
728
- hostname: opts.hostname,
729
- externallyManaged: true,
730
- },
731
- });
732
- printNatStatus(body);
733
- process.exit(0);
734
- });
735
-
736
- // ============================================================================
737
- // push subcommands — provision FCM/APNs credentials for strand-wake delivery
738
- // ============================================================================
739
- //
740
- // These operate directly on the data dir's secret store + host.config.json (they
741
- // do NOT go through the running management API). Private keys land in the OS
742
- // keychain (keytar) or the 0600 file-store fallback; the non-secret bits (APNs
743
- // bundle id / sandbox toggle, cooldown/debounce) land in host.config.json. New
744
- // credentials take effect on the next authority-node (re)spawn — run
745
- // `cadre-host` restart (or restart the service) to apply them immediately.
746
-
747
- const push = program
748
- .command('push')
749
- .description('Configure FCM/APNs push credentials for mobile strand-wake delivery');
750
-
751
- push
752
- .command('fcm')
753
- .description('Store Firebase Cloud Messaging (Android) service-account credentials')
754
- .requiredOption('--project-id <id>', 'GCP / Firebase project id')
755
- .requiredOption('--client-email <email>', 'Service-account email')
756
- .option('--private-key-file <path>', 'Path to the service-account private key (PEM)')
757
- .option('--private-key <pem>', 'Inline PEM private key (prefer --private-key-file)')
758
- .option('--data-dir <path>', 'Override the data directory (env: CADRE_HOST_DATA_DIR)')
759
- .action(async (opts: {
760
- projectId: string;
761
- clientEmail: string;
762
- privateKeyFile?: string;
763
- privateKey?: string;
764
- dataDir?: string;
765
- }) => {
766
- const { dataDir } = resolveHostPaths(opts.dataDir);
767
- const privateKey = readPrivateKeyArg(opts.privateKeyFile, opts.privateKey, 'FCM');
768
- const secrets = await createSecretsStore(dataDir);
769
- await setFcmSecret(secrets, {
770
- projectId: opts.projectId,
771
- clientEmail: opts.clientEmail,
772
- privateKey,
773
- });
774
- console.log('✓ FCM credentials stored. Restart cadre-host to apply on the authority node.');
775
- process.exit(0);
776
- });
777
-
778
- push
779
- .command('apns')
780
- .description('Store Apple Push Notification service (iOS) auth-key credentials')
781
- .requiredOption('--key-id <id>', 'APNs key id (the .p8 key identifier)')
782
- .requiredOption('--team-id <id>', 'Apple developer team id')
783
- .requiredOption('--bundle-id <id>', 'App bundle id (becomes the apns-topic)')
784
- .option('--private-key-file <path>', 'Path to the .p8 auth key (PEM)')
785
- .option('--private-key <pem>', 'Inline .p8 PEM key (prefer --private-key-file)')
786
- .option('--production', 'Target the production APNs host (default: sandbox)')
787
- .option('--data-dir <path>', 'Override the data directory (env: CADRE_HOST_DATA_DIR)')
788
- .action(async (opts: {
789
- keyId: string;
790
- teamId: string;
791
- bundleId: string;
792
- privateKeyFile?: string;
793
- privateKey?: string;
794
- production?: boolean;
795
- dataDir?: string;
796
- }) => {
797
- const { dataDir, cfgPath } = resolveHostPaths(opts.dataDir);
798
- const privateKey = readPrivateKeyArg(opts.privateKeyFile, opts.privateKey, 'APNs');
799
- const secrets = await createSecretsStore(dataDir);
800
- // Secret bits → secret store; non-secret app-config → host.config.json.
801
- await setApnsSecret(secrets, { keyId: opts.keyId, teamId: opts.teamId, privateKey });
802
- const current = readHostConfig(cfgPath);
803
- updateHostConfig(cfgPath, {
804
- push: {
805
- ...current.push,
806
- apns: { bundleId: opts.bundleId, production: opts.production === true },
807
- },
808
- });
809
- console.log(
810
- `✓ APNs credentials stored (${opts.production ? 'production' : 'sandbox'}). ` +
811
- `Restart cadre-host to apply on the authority node.`,
812
- );
813
- process.exit(0);
814
- });
815
-
816
- push
817
- .command('options')
818
- .description('Set non-secret push tuning (anti-spam cooldown / burst-coalesce window)')
819
- .option('--cooldown-ms <ms>', 'Per-(peer,strand) minimum gap between wakes', parseIntArg)
820
- .option('--debounce-ms <ms>', 'Per-strand burst-coalescing window', parseIntArg)
821
- .option('--data-dir <path>', 'Override the data directory (env: CADRE_HOST_DATA_DIR)')
822
- .action((opts: { cooldownMs?: number; debounceMs?: number; dataDir?: string }) => {
823
- const { cfgPath } = resolveHostPaths(opts.dataDir);
824
- const current = readHostConfig(cfgPath);
825
- const nextPush = { ...current.push };
826
- if (typeof opts.cooldownMs === 'number') nextPush.cooldownMs = opts.cooldownMs;
827
- if (typeof opts.debounceMs === 'number') nextPush.debounceMs = opts.debounceMs;
828
- updateHostConfig(cfgPath, { push: nextPush });
829
- console.log('✓ Push options updated.');
830
- process.exit(0);
831
- });
832
-
833
- push
834
- .command('clear')
835
- .description('Remove stored push credentials')
836
- .argument('<target>', 'Which to clear: "fcm", "apns", or "all"')
837
- .option('--data-dir <path>', 'Override the data directory (env: CADRE_HOST_DATA_DIR)')
838
- .action(async (target: string, opts: { dataDir?: string }) => {
839
- if (!['fcm', 'apns', 'all'].includes(target)) {
840
- console.error(`push clear: target must be one of fcm | apns | all (got "${target}")`);
841
- process.exit(1);
842
- return;
843
- }
844
- const { dataDir, cfgPath } = resolveHostPaths(opts.dataDir);
845
- const secrets = await createSecretsStore(dataDir);
846
- if (target === 'fcm' || target === 'all') await clearPushSecret(secrets, 'fcm');
847
- if (target === 'apns' || target === 'all') {
848
- await clearPushSecret(secrets, 'apns');
849
- const current = readHostConfig(cfgPath);
850
- if (current.push?.apns) {
851
- const { apns: _drop, ...rest } = current.push;
852
- updateHostConfig(cfgPath, { push: rest });
853
- }
854
- }
855
- console.log(`✓ Cleared push credentials: ${target}. Restart cadre-host to apply.`);
856
- process.exit(0);
857
- });
858
-
859
- push
860
- .command('status')
861
- .description('Show which push platforms are configured (no secret material)')
862
- .option('--data-dir <path>', 'Override the data directory (env: CADRE_HOST_DATA_DIR)')
863
- .action(async (opts: { dataDir?: string }) => {
864
- const { dataDir, cfgPath } = resolveHostPaths(opts.dataDir);
865
- const secrets = await createSecretsStore(dataDir);
866
- const status = await pushStatus(secrets);
867
- const cfg = readHostConfig(cfgPath);
868
- console.log('Push credentials:');
869
- console.log(` FCM: ${status.fcm ? 'configured' : 'not configured'}`);
870
- const prod = cfg.push?.apns?.production ? 'production' : 'sandbox';
871
- const bundle = cfg.push?.apns?.bundleId ? ` bundle=${cfg.push.apns.bundleId} (${prod})` : '';
872
- console.log(` APNs: ${status.apns ? `configured${bundle}` : 'not configured'}`);
873
- if (cfg.push?.cooldownMs !== undefined) console.log(` cooldownMs: ${cfg.push.cooldownMs}`);
874
- if (cfg.push?.debounceMs !== undefined) console.log(` debounceMs: ${cfg.push.debounceMs}`);
875
- process.exit(0);
876
- });
877
-
878
- /** Resolve the data dir + config path for a direct-on-disk push subcommand. */
879
- function resolveHostPaths(dataDirOpt?: string): { dataDir: string; cfgPath: string } {
880
- const platform = detectPlatform();
881
- const dataDir = dataDirOpt ?? process.env.CADRE_HOST_DATA_DIR ?? defaultDataDir(platform);
882
- const cfgPath = resolveConfigPath(dataDir);
883
- if (!existsSync(cfgPath)) {
884
- console.error(`${cfgPath} not found. Run \`cadre-host install\` first (or pass --data-dir).`);
885
- process.exit(1);
886
- }
887
- // Resolve the real data dir from the persisted config (handles default-dir installs).
888
- const cfg = readHostConfig(cfgPath);
889
- return { dataDir: cfg.dataDir, cfgPath };
890
- }
891
-
892
- /** Read a private key from a file or inline flag; exit with a clear error if neither. */
893
- function readPrivateKeyArg(file: string | undefined, inline: string | undefined, label: string): string {
894
- if (file) {
895
- try {
896
- return readFileSync(file, 'utf8');
897
- } catch (err) {
898
- console.error(`Failed to read ${label} private key file ${file}: ${(err as Error).message}`);
899
- process.exit(1);
900
- }
901
- }
902
- if (inline) return inline;
903
- console.error(`${label}: supply --private-key-file <path> (or --private-key <pem>).`);
904
- process.exit(1);
905
- throw new Error('unreachable');
906
- }
907
-
908
- async function getJson(url: string): Promise<NatStatusLike> {
909
- return await callJson(url, 'GET');
910
- }
911
-
912
- async function postJson(url: string, body: unknown): Promise<NatStatusLike> {
913
- return await callJson(url, 'POST', body);
914
- }
915
-
916
- async function putJson(url: string, body: unknown): Promise<NatStatusLike> {
917
- return await callJson(url, 'PUT', body);
918
- }
919
-
920
- interface NatStatusLike {
921
- portMode?: string;
922
- externalPort?: number;
923
- internalPort?: number;
924
- externalIp?: string | null;
925
- routerExternalIp?: string | null;
926
- cgnatDetected?: boolean;
927
- directReachability?: string;
928
- lastTestedAt?: string | null;
929
- mappingLeaseExpiresAt?: string | null;
930
- ddns?: {
931
- providerId?: string | null;
932
- hostname?: string | null;
933
- externallyManaged?: boolean;
934
- lastUpdateAt?: string | null;
935
- lastUpdateOk?: boolean | null;
936
- lastError?: string | null;
937
- };
938
- }
939
-
940
- async function callJson(url: string, method: string, body?: unknown): Promise<NatStatusLike> {
941
- let response: Response;
942
- try {
943
- const init: RequestInit = { method };
944
- if (body !== undefined) {
945
- init.headers = { 'content-type': 'application/json' };
946
- init.body = JSON.stringify(body);
947
- }
948
- response = await fetch(url, init);
949
- } catch (err) {
950
- console.error(
951
- `Failed to reach cadre-host at ${url}: ${(err as Error).message}\n` +
952
- `Hint: is cadre-host running? Try \`cadre-host start\`.`,
953
- );
954
- process.exit(2);
955
- throw err;
956
- }
957
- if (!response.ok) {
958
- const text = await response.text().catch(() => '');
959
- console.error(`cadre-host returned ${response.status}: ${text || response.statusText}`);
960
- process.exit(1);
961
- throw new Error('non-ok');
962
- }
963
- if (response.status === 204) return {} as NatStatusLike;
964
- return await response.json() as NatStatusLike;
965
- }
966
-
967
- function printNatStatus(s: NatStatusLike): void {
968
- console.log(`Port mapping: ${s.portMode ?? '?'} (external ${s.externalPort ?? '?'} → internal ${s.internalPort ?? '?'})`);
969
- if (s.routerExternalIp) {
970
- console.log(`Router IP: ${s.routerExternalIp}`);
971
- }
972
- console.log(`External IP: ${s.externalIp ?? '(unknown)'}${s.cgnatDetected ? ' [CGNAT detected]' : ''}`);
973
- console.log(`Reachability: ${s.directReachability ?? 'unknown'}${s.lastTestedAt ? ` (tested ${s.lastTestedAt})` : ''}`);
974
- if (s.mappingLeaseExpiresAt) {
975
- console.log(`Lease expires: ${s.mappingLeaseExpiresAt}`);
976
- }
977
- const ddns = s.ddns ?? {};
978
- if (ddns.providerId || ddns.hostname) {
979
- console.log(`\nDDNS:`);
980
- console.log(` Provider: ${ddns.providerId ?? '(none)'}${ddns.externallyManaged ? ' [externally managed]' : ''}`);
981
- console.log(` Hostname: ${ddns.hostname ?? '(unset)'}`);
982
- if (ddns.lastUpdateAt) {
983
- const ok = ddns.lastUpdateOk ? 'OK' : 'FAIL';
984
- console.log(` Last update: ${ok} at ${ddns.lastUpdateAt}${ddns.lastError ? ` — ${ddns.lastError}` : ''}`);
985
- }
986
- } else {
987
- console.log('\nDDNS: not configured');
988
- }
989
- }
990
-
991
- /** Read a single line from stdin with echo suppressed (TTY only). */
992
- function readSecretLine(prompt: string): Promise<string> {
993
- return new Promise<string>((resolveLine, rejectLine) => {
994
- const stdin = process.stdin;
995
- const stdout = process.stdout;
996
- const wasRaw = stdin.isRaw;
997
- try {
998
- stdout.write(prompt);
999
- stdin.setRawMode(true);
1000
- } catch (err) {
1001
- rejectLine(err);
1002
- return;
1003
- }
1004
- stdin.resume();
1005
- stdin.setEncoding('utf8');
1006
-
1007
- let buf = '';
1008
- const onData = (chunk: string) => {
1009
- for (const ch of chunk) {
1010
- if (ch === '\n' || ch === '\r' || ch === '') {
1011
- stdin.removeListener('data', onData);
1012
- try { stdin.setRawMode(wasRaw); } catch { /* ignore */ }
1013
- stdin.pause();
1014
- stdout.write('\n');
1015
- resolveLine(buf);
1016
- return;
1017
- }
1018
- if (ch === '') {
1019
- // Ctrl-C
1020
- stdin.removeListener('data', onData);
1021
- try { stdin.setRawMode(wasRaw); } catch { /* ignore */ }
1022
- stdin.pause();
1023
- stdout.write('\n');
1024
- rejectLine(new Error('cancelled'));
1025
- return;
1026
- }
1027
- if (ch === '' || ch === '\b') {
1028
- buf = buf.slice(0, -1);
1029
- continue;
1030
- }
1031
- buf += ch;
1032
- }
1033
- };
1034
- stdin.on('data', onData);
1035
- });
1036
- }
1037
-
1038
- void program.parseAsync();
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * CLI entrypoint for cadre-host — the self-hosted cadre node manager.
5
+ *
6
+ * Most subcommands are still stubs at this stage (real implementations land
7
+ * in the sibling tickets cadre-host-nat, cadre-host-installer,
8
+ * cadre-host-local-ui).
9
+ *
10
+ * The `invite` and `trust` commands talk to the running cadre-host
11
+ * management API over loopback. They are thin HTTP clients — they don't
12
+ * spin up an inline service, so cadre-host must be running.
13
+ */
14
+
15
+ import { existsSync, readFileSync } from 'node:fs';
16
+ import { createRequire } from 'node:module';
17
+ import { fileURLToPath } from 'node:url';
18
+ import { dirname, join, resolve } from 'node:path';
19
+
20
+ import { Command } from 'commander';
21
+
22
+ import { parseDuration } from '../auth/duration.js';
23
+ import { Installer } from '../installer/index.js';
24
+ import { readHostConfig, updateHostConfig, hostOwnsCadre } from '../installer/config.js';
25
+ import {
26
+ configPath as resolveConfigPath,
27
+ defaultDataDir,
28
+ defaultHostJs,
29
+ defaultServiceDir,
30
+ identityPath as resolveIdentityPath,
31
+ } from '../installer/paths.js';
32
+ import { detectPlatform } from '../installer/platform.js';
33
+ import { createServiceHost } from '../installer/service-host/index.js';
34
+ import { UpdateService } from '../update/index.js';
35
+ import { HostProcessOrchestrator } from '../orchestrator/index.js';
36
+ import { TrustCircleService, TrustCircleStore, ensureSelfLabel } from '../auth/index.js';
37
+ import {
38
+ GrantService,
39
+ GrantStore,
40
+ DonationService,
41
+ DonationStore,
42
+ DonationSupervisor,
43
+ DONATION_AWAITING_SEED_TTL_MS,
44
+ DONATION_PROVISIONING_TTL_MS,
45
+ DONATION_REAP_SWEEP_MS,
46
+ } from '../donation/index.js';
47
+ import { NatService } from '../nat/index.js';
48
+ import { createSecretsStore } from '../nat/secrets/index.js';
49
+ import {
50
+ resolvePushCredentials,
51
+ setFcmSecret,
52
+ setApnsSecret,
53
+ clearPushSecret,
54
+ pushStatus,
55
+ } from '../push/index.js';
56
+ import { StrandService } from '../strands/index.js';
57
+ import { OwnerNodeClient } from '../owner/index.js';
58
+ import { createLocalUiServer, HostSettingsStore } from '../server/index.js';
59
+ import { openBrowser } from '../installer/browser.js';
60
+
61
+ const DEFAULT_PORT = Number(process.env.CADRE_HOST_PORT ?? '8765');
62
+
63
+ /** libp2p peer-ID prefixes by key type: Ed25519, secp256k1, legacy RSA. */
64
+ const PEER_ID_PREFIXES = ['12D3Koo', '16Uiu2HAm', 'Qm'] as const;
65
+
66
+ function looksLikePeerId(id: string): boolean {
67
+ return PEER_ID_PREFIXES.some((p) => id.startsWith(p));
68
+ }
69
+
70
+ function resolvePort(raw: string): number {
71
+ const n = Number(raw);
72
+ if (!Number.isFinite(n) || n <= 0 || n > 65535) {
73
+ console.error(`Invalid --port: ${raw}`);
74
+ process.exit(1);
75
+ }
76
+ return n;
77
+ }
78
+
79
+ const program = new Command();
80
+
81
+ program
82
+ .name('cadre-host')
83
+ .description('Sereus cadre node manager for self-hosted basement-PC deployments')
84
+ .version('0.6.0');
85
+
86
+ // ============================================================================
87
+ // install — run the first-run wizard + register the system service
88
+ // ============================================================================
89
+
90
+ program
91
+ .command('install')
92
+ .description('Install cadre-host as a system service and run first-run setup')
93
+ .option('--non-interactive', 'Use defaults / CLI flags only; never prompt')
94
+ .option('--data-dir <path>', 'Override the data directory')
95
+ .option('--ui-port <port>', 'Override the management UI port', parseIntArg)
96
+ .option('--libp2p-port <port>', 'Override the cadre libp2p port', parseIntArg)
97
+ .option('--no-upnp', 'Disable UPnP/NAT-PMP probing on first run')
98
+ .option('--no-browser', 'Do not open a browser after install')
99
+ .option('--no-invite', 'Skip generating the first enrollment invite')
100
+ .option('--own-cadre', 'Also run the host\'s own personal cadre here (founder persona; default: donor-only)')
101
+ .option('--system', 'System-wide install (not yet supported in v1)')
102
+ .option('--node-path <path>', 'Override the node binary embedded in the service unit')
103
+ .action(async (opts: {
104
+ nonInteractive?: boolean;
105
+ dataDir?: string;
106
+ uiPort?: number;
107
+ libp2pPort?: number;
108
+ upnp?: boolean;
109
+ browser?: boolean;
110
+ invite?: boolean;
111
+ ownCadre?: boolean;
112
+ system?: boolean;
113
+ nodePath?: string;
114
+ }) => {
115
+ const installer = new Installer();
116
+ try {
117
+ const result = await installer.install({
118
+ nonInteractive: Boolean(opts.nonInteractive),
119
+ ...(opts.dataDir ? { dataDir: opts.dataDir } : {}),
120
+ ...(typeof opts.uiPort === 'number' ? { uiPort: opts.uiPort } : {}),
121
+ ...(typeof opts.libp2pPort === 'number' ? { libp2pPort: opts.libp2pPort } : {}),
122
+ noUpnp: opts.upnp === false,
123
+ openBrowser: opts.browser !== false,
124
+ noInvite: opts.invite === false,
125
+ ownCadre: opts.ownCadre === true,
126
+ system: Boolean(opts.system),
127
+ ...(opts.nodePath ? { nodePath: opts.nodePath } : {}),
128
+ });
129
+ console.log(`cadre-host installed.`);
130
+ console.log(` Data dir: ${result.dataDir}`);
131
+ console.log(` UI: ${result.uiUrl}`);
132
+ console.log(` Service: ${result.serviceName}`);
133
+ if (result.enrollmentInvite) {
134
+ printEnrollmentInvite(result.enrollmentInvite);
135
+ }
136
+ process.exit(0);
137
+ } catch (err) {
138
+ console.error(`install failed: ${(err as Error).message}`);
139
+ process.exit(1);
140
+ }
141
+ });
142
+
143
+ // ============================================================================
144
+ // uninstall — stop + deregister the system service
145
+ // ============================================================================
146
+
147
+ program
148
+ .command('uninstall')
149
+ .description('Stop and uninstall the cadre-host service')
150
+ .option('--yes', 'Skip the confirmation prompt (for scripts)')
151
+ .option('--remove-data', 'Also remove the data directory (default: preserve)')
152
+ .option('--data-dir <path>', 'Override the data directory to clean up')
153
+ .action(async (opts: { yes?: boolean; removeData?: boolean; dataDir?: string }) => {
154
+ const installer = new Installer();
155
+ try {
156
+ // --remove-data is destructive and irreversible (identity + trust circle
157
+ // are wiped). Require explicit --yes when stdin isn't a TTY, and prompt
158
+ // confirmation when it is.
159
+ if (opts.removeData && !opts.yes) {
160
+ if (!process.stdin.isTTY) {
161
+ console.error('uninstall: --remove-data requires --yes when stdin is not a TTY.');
162
+ process.exit(1);
163
+ return;
164
+ }
165
+ const dataDir = opts.dataDir ?? '(default data directory)';
166
+ const confirmed = await confirmDestructive(
167
+ `This will permanently delete ${dataDir} (identity, trust circle, NAT state). Continue? [y/N] `,
168
+ );
169
+ if (!confirmed) {
170
+ console.error('uninstall aborted.');
171
+ process.exit(1);
172
+ return;
173
+ }
174
+ }
175
+ await installer.uninstall({
176
+ yes: Boolean(opts.yes),
177
+ removeData: Boolean(opts.removeData),
178
+ ...(opts.dataDir ? { dataDir: opts.dataDir } : {}),
179
+ });
180
+ console.log('cadre-host uninstalled.');
181
+ process.exit(0);
182
+ } catch (err) {
183
+ console.error(`uninstall failed: ${(err as Error).message}`);
184
+ process.exit(1);
185
+ }
186
+ });
187
+
188
+ // ============================================================================
189
+ // status — show service-host registration / running state
190
+ // ============================================================================
191
+
192
+ program
193
+ .command('status')
194
+ .description('Show running status of cadre-host and the cadre nodes it manages')
195
+ .action(async () => {
196
+ const installer = new Installer();
197
+ try {
198
+ const status = await installer.status();
199
+ console.log(`Service installed: ${status.installed ? 'yes' : 'no'}`);
200
+ console.log(`Service running: ${status.running ? 'yes' : 'no'}`);
201
+ process.exit(0);
202
+ } catch (err) {
203
+ console.error(`status failed: ${(err as Error).message}`);
204
+ process.exit(1);
205
+ }
206
+ });
207
+
208
+ // ============================================================================
209
+ // start — load config + identity, bind management API listener, wait
210
+ // ============================================================================
211
+
212
+ program
213
+ .command('start')
214
+ .description('Start cadre-host in the foreground')
215
+ .option('--data-dir <path>', 'Override the data directory (env: CADRE_HOST_DATA_DIR)')
216
+ .option('--no-tui', 'Reserved — currently a no-op (no TUI implemented yet)')
217
+ .action(async (opts: { dataDir?: string; tui?: boolean }) => {
218
+ try {
219
+ void opts.tui;
220
+ const platform = detectPlatform();
221
+ const dataDir = opts.dataDir ?? process.env.CADRE_HOST_DATA_DIR ?? defaultDataDir(platform);
222
+ const cfgPath = resolveConfigPath(dataDir);
223
+ if (!existsSync(cfgPath)) {
224
+ console.error(
225
+ `cadre-host start: ${cfgPath} not found. ` +
226
+ `Run \`cadre-host install\` first (or pass --data-dir to an existing install).`,
227
+ );
228
+ process.exit(1);
229
+ return;
230
+ }
231
+ const cfg = readHostConfig(cfgPath);
232
+ const idPath = resolveIdentityPath(cfg.dataDir);
233
+ if (!existsSync(idPath)) {
234
+ console.error(`cadre-host start: identity file not found at ${idPath}. Re-run \`cadre-host install\`.`);
235
+ process.exit(1);
236
+ return;
237
+ }
238
+ console.log(`cadre-host starting (dataDir=${cfg.dataDir}, uiPort=${cfg.uiPort})`);
239
+
240
+ // Update flow: notify-by-default; auto-apply opt-in via host.config.json.
241
+ // The local-UI ticket (6.5) wires the handlers into HTTP routes; here we
242
+ // just construct the service so the in-process timer + state file are
243
+ // populated.
244
+ const serviceHost = createServiceHost(platform);
245
+ const updateService = new UpdateService({
246
+ dataDir: cfg.dataDir,
247
+ currentVersion: readPackageVersionForStart(),
248
+ settings: cfg.updates,
249
+ ...(cfg.updates.manifestUrl ? { manifestUrl: cfg.updates.manifestUrl } : {}),
250
+ restart: async () => {
251
+ try {
252
+ await serviceHost.restart({
253
+ nodePath: process.execPath,
254
+ hostJs: defaultHostJs(),
255
+ dataDir: cfg.dataDir,
256
+ serviceDir: defaultServiceDir(),
257
+ });
258
+ return undefined;
259
+ } catch (err) {
260
+ return (err as Error).message;
261
+ }
262
+ },
263
+ });
264
+ // Persist settings changes back to host.config.json on PUT /update/settings.
265
+ updateService.onSettingsChanged((next) => {
266
+ try {
267
+ updateHostConfig(cfgPath, { updates: next });
268
+ } catch (err) {
269
+ console.error(`failed to persist updated settings to ${cfgPath}: ${(err as Error).message}`);
270
+ }
271
+ });
272
+ // Don't block startup on the network round-trip — call and forget.
273
+ void updateService.check();
274
+ updateService.start();
275
+
276
+ // Wire the long-lived HTTP management server. cadre-host's primary role
277
+ // is **node donor**: it spawns generic cadre nodes for *other people's*
278
+ // cadres on request (the donation grant layer below) and never needs an
279
+ // owner node of its own for that. Running the host's **own** personal
280
+ // cadre here — the "founder" persona — is opt-in via `ownCadre.enabled`
281
+ // (see docs/cadre-host.md § Two roles: donor and founder). Only when it
282
+ // is enabled do we spawn the owner node and bring up trust-circle + NAT.
283
+ // The manager never joins the control network (docs/cadre-host.md
284
+ // § Control-plane separation).
285
+ // Push (FCM/APNs) credentials are resolved fresh on every node spawn so a
286
+ // restart re-reads the secret store (rotated keys) and nothing raw is
287
+ // persisted in state.json. The non-secret bits (bundle id / sandbox toggle,
288
+ // cooldown/debounce) are re-read from host.config.json each call too.
289
+ const pushSecrets = await createSecretsStore(cfg.dataDir);
290
+ const orchestrator = new HostProcessOrchestrator({
291
+ rootDir: join(cfg.dataDir, 'orchestrator'),
292
+ pushResolver: () => resolvePushCredentials(pushSecrets, readHostConfig(cfgPath).push),
293
+ });
294
+ await orchestrator.init();
295
+
296
+ // Donation grant layer — the always-on donor surface. Local-only:
297
+ // issue/validate/revoke are pure store ops (no node round-trip), so it
298
+ // needs no owner-node handle. The loopback `/grants-admin` surface is
299
+ // mounted by createLocalUiServer regardless of the founder persona.
300
+ const grantService = new GrantService({ store: new GrantStore(cfg.dataDir) });
301
+
302
+ // Donation lifecycle service — consumes a validated grant to actually
303
+ // spawn a donated node into the requester's cadre. Drives the
304
+ // grantee-facing `/grants` surface (mounted by createLocalUiServer below).
305
+ const donationStore = new DonationStore(cfg.dataDir);
306
+ const donationService = new DonationService({
307
+ orchestrator,
308
+ grants: grantService,
309
+ store: donationStore,
310
+ });
311
+
312
+ // Respawn supervision — nothing else brings a donated node back. A crash,
313
+ // an OOM kill, or a reboot otherwise leaves the record reading `seeded`
314
+ // with no process behind it, costing the borrower a node and their grant a
315
+ // quota slot. Sweeps at startup, on every child exit, and on its own timer.
316
+ const donationSupervisor = new DonationSupervisor({
317
+ service: donationService,
318
+ store: donationStore,
319
+ orchestrator,
320
+ });
321
+ donationSupervisor.start();
322
+
323
+ // Reap orphaned donations: a requester that provisioned a node but never
324
+ // presented a seed leaves an `awaiting_seed` child holding host ports,
325
+ // and a host that died between writing a `provisioning` row and finishing
326
+ // the spawn leaves that row stuck forever (nothing else ever revisits it).
327
+ // Sweep once at startup (for records recovered from disk by
328
+ // orchestrator.init()), then periodically.
329
+ const reapStale = (): void => {
330
+ void donationService
331
+ .reapStaleAwaitingSeed(DONATION_AWAITING_SEED_TTL_MS)
332
+ .catch((err) => console.error(`donation reap failed: ${(err as Error).message}`));
333
+ void donationService
334
+ .reapStaleProvisioning(DONATION_PROVISIONING_TTL_MS)
335
+ .catch((err) => console.error(`donation provisioning reap failed: ${(err as Error).message}`));
336
+ };
337
+ reapStale();
338
+ const reapTimer = setInterval(reapStale, DONATION_REAP_SWEEP_MS);
339
+ reapTimer.unref();
340
+
341
+ // Founder stack (opt-in). Absent `ownCadre.enabled`, cadre-host is a pure
342
+ // donor: no owner node, and the /auth + /nat surfaces stay unmounted
343
+ // (they 404). Per-donated-node WAN reachability is deferred to
344
+ // backlog/feat-cadre-host-wan-grant-reachability, so v1 donor mode is
345
+ // loopback-only — nothing for NatService to map without an owner node.
346
+ let trustCircle: TrustCircleService | undefined;
347
+ let natService: NatService | undefined;
348
+ let strandService: StrandService | undefined;
349
+ if (hostOwnsCadre(cfg)) {
350
+ // Spawn the owner node. Best-effort: a spawn failure leaves the
351
+ // management API up (trust-circle listing degrades to local labels,
352
+ // owner ops return 503) rather than taking down the whole process.
353
+ try {
354
+ await orchestrator.ensureOwnerNode({
355
+ identityPath: idPath,
356
+ partyId: cfg.installId,
357
+ libp2pPort: cfg.libp2pPort,
358
+ });
359
+ console.log('cadre-host: owner node spawned (host-own-cadre enabled)');
360
+ } catch (err) {
361
+ console.error(`owner node spawn failed: ${(err as Error).message}`);
362
+ }
363
+
364
+ // The client reads the admin endpoint lazily so a node restart's fresh
365
+ // bearer token is picked up automatically.
366
+ const owner = new OwnerNodeClient(() => orchestrator.getOwnerAdminEndpoint());
367
+
368
+ const trustCircleStore = new TrustCircleStore(cfg.dataDir);
369
+ trustCircle = new TrustCircleService({
370
+ cadreNode: owner,
371
+ store: trustCircleStore,
372
+ });
373
+
374
+ natService = new NatService({
375
+ rootDir: cfg.dataDir,
376
+ cadreNode: owner,
377
+ });
378
+
379
+ // Strand management is founder-only for the same reason as the trust
380
+ // circle: it asks the owner node, and donor-only mode has none.
381
+ strandService = new StrandService({ cadreNode: owner });
382
+
383
+ // Push NAT-resolved invite addresses to the node on every NAT change.
384
+ // NatService.start() also fires this once as an initial push, retried
385
+ // until the freshly spawned owner node accepts it (bounded; the
386
+ // management API that mints invites comes up only after start() resolves).
387
+ natService.onAddressesChanged(async (addresses) => {
388
+ if (addresses.length === 0) return;
389
+ try {
390
+ await owner.pushInviteAddresses(addresses);
391
+ } catch (err) {
392
+ console.error(`invite-address push failed: ${(err as Error).message}`);
393
+ }
394
+ });
395
+
396
+ // Best-effort NAT start. Failures here aren't fatal — the local UI
397
+ // can still serve the trust circle, settings, etc.
398
+ try {
399
+ await natService.start();
400
+ } catch (err) {
401
+ console.error(`NAT start failed: ${(err as Error).message}`);
402
+ }
403
+
404
+ // Label the owner's own device so it shows up in the trust-circle
405
+ // listing (see auth/self-label.ts for why the listing can't get it for
406
+ // free). Runs after natService.start(), which already waits out a
407
+ // freshly spawned node's warm-up, so the peer ID is normally there on
408
+ // the first try. Best-effort: a failure logs and the next start heals
409
+ // it — the listing gap is cosmetic, not a security boundary.
410
+ try {
411
+ await ensureSelfLabel({ store: trustCircleStore, getPeerId: () => owner.getPeerId() });
412
+ } catch (err) {
413
+ console.error(`self trust-circle label failed: ${(err as Error).message}`);
414
+ }
415
+ } else {
416
+ // Donor-only. If ownCadre was toggled off after a prior founder run,
417
+ // orchestrator.init() re-attaches the still-running owner child (it would
418
+ // otherwise linger in listNodes with no trustCircle/nat wired, serving
419
+ // the host's own cadre despite being disabled). Reap it now so a disabled
420
+ // own-cadre is actually stopped — its workdir + control-DB persist on
421
+ // disk, so toggling ownCadre back on re-spawns it from saved config.
422
+ try {
423
+ await orchestrator.stopOwnerNode();
424
+ } catch (err) {
425
+ console.error(`owner node reap failed: ${(err as Error).message}`);
426
+ }
427
+ console.log('cadre-host: node-donor mode (host-own-cadre disabled — no owner node; /auth + /nat inactive)');
428
+ }
429
+
430
+ const settingsStore = new HostSettingsStore({ dataDir: cfg.dataDir });
431
+ const server = createLocalUiServer({
432
+ uiPort: cfg.uiPort,
433
+ dataDir: cfg.dataDir,
434
+ orchestrator,
435
+ ...(trustCircle ? { trustCircle } : {}),
436
+ ...(natService ? { nat: natService } : {}),
437
+ ...(strandService ? { strands: strandService } : {}),
438
+ update: updateService,
439
+ grants: grantService,
440
+ donations: donationService,
441
+ settingsStore,
442
+ });
443
+ const { url, port } = await server.start();
444
+ if (port !== cfg.uiPort) {
445
+ console.log(`(configured port ${cfg.uiPort} was in use — bound on ${port} instead)`);
446
+ }
447
+ console.log(`cadre-host local UI: ${url}`);
448
+
449
+ await waitForTermination();
450
+ clearInterval(reapTimer);
451
+ donationSupervisor.stop();
452
+ try { await server.stop(); } catch { /* ignore */ }
453
+ try { await natService?.stop(); } catch { /* ignore */ }
454
+ try { await orchestrator.stopOwnerNode(); } catch { /* ignore */ }
455
+ updateService.stop();
456
+ console.log('cadre-host stopped.');
457
+ process.exit(0);
458
+ } catch (err) {
459
+ console.error(`start failed: ${(err as Error).message}`);
460
+ process.exit(1);
461
+ }
462
+ });
463
+
464
+ // ============================================================================
465
+ // ui — print the local-UI URL and open it in a browser
466
+ // ============================================================================
467
+
468
+ program
469
+ .command('ui')
470
+ .description('Print the local-UI URL and open it in the default browser')
471
+ .option('--data-dir <path>', 'Override the data directory (env: CADRE_HOST_DATA_DIR)')
472
+ .option('--no-browser', 'Print the URL but do not open a browser')
473
+ .action((opts: { dataDir?: string; browser?: boolean }) => {
474
+ try {
475
+ const platform = detectPlatform();
476
+ const dataDir = opts.dataDir ?? process.env.CADRE_HOST_DATA_DIR ?? defaultDataDir(platform);
477
+ const cfgPath = resolveConfigPath(dataDir);
478
+ if (!existsSync(cfgPath)) {
479
+ console.error(`cadre-host ui: ${cfgPath} not found. Run \`cadre-host install\` first.`);
480
+ process.exit(1);
481
+ return;
482
+ }
483
+ const cfg = readHostConfig(cfgPath);
484
+ const url = `http://127.0.0.1:${cfg.uiPort}`;
485
+ console.log(url);
486
+ if (opts.browser !== false) {
487
+ const res = openBrowser(url);
488
+ if (res.spawned) {
489
+ console.log('(Opening in your default browser...)');
490
+ } else if (res.error) {
491
+ console.error(`(unable to launch browser: ${res.error})`);
492
+ }
493
+ }
494
+ process.exit(0);
495
+ } catch (err) {
496
+ console.error(`ui failed: ${(err as Error).message}`);
497
+ process.exit(1);
498
+ }
499
+ });
500
+
501
+ function parseIntArg(raw: string): number {
502
+ const n = Number(raw);
503
+ if (!Number.isFinite(n) || !Number.isInteger(n)) {
504
+ throw new Error(`Invalid integer: ${raw}`);
505
+ }
506
+ return n;
507
+ }
508
+
509
+ function readPackageVersionForStart(): string {
510
+ try {
511
+ // dist/bin/host.js -> ../../package.json
512
+ const here = dirname(fileURLToPath(import.meta.url));
513
+ const pkgPath = resolve(here, '..', '..', 'package.json');
514
+ const raw = readFileSync(pkgPath, 'utf8');
515
+ const parsed = JSON.parse(raw) as { version?: string };
516
+ return parsed.version ?? '0.0.0-unknown';
517
+ } catch {
518
+ return '0.0.0-unknown';
519
+ }
520
+ }
521
+
522
+ function waitForTermination(): Promise<void> {
523
+ return new Promise<void>((resolveTerm) => {
524
+ const done = () => resolveTerm();
525
+ process.once('SIGINT', done);
526
+ process.once('SIGTERM', done);
527
+ });
528
+ }
529
+
530
+ async function confirmDestructive(message: string): Promise<boolean> {
531
+ const { createInterface } = await import('node:readline');
532
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
533
+ try {
534
+ const answer = await new Promise<string>((res) => rl.question(message, res));
535
+ return /^(y|yes)$/i.test(answer.trim());
536
+ } finally {
537
+ rl.close();
538
+ }
539
+ }
540
+
541
+ const requireForQr = createRequire(import.meta.url);
542
+
543
+ function printEnrollmentInvite(invite: { encodedInvite: string; expiresAt?: string }): void {
544
+ // Best-effort QR render — fall back to the bare token if the lib chokes.
545
+ console.log('\nEnroll your first device with this invite:');
546
+ try {
547
+ const qr = requireForQr('qrcode-terminal') as { generate: (text: string, opts?: { small?: boolean }, cb?: (s: string) => void) => void };
548
+ qr.generate(invite.encodedInvite, { small: true }, (rendered) => {
549
+ console.log(rendered);
550
+ });
551
+ } catch (err) {
552
+ console.error(`(qrcode-terminal unavailable: ${(err as Error).message})`);
553
+ }
554
+ console.log(` ${invite.encodedInvite}`);
555
+ if (invite.expiresAt) {
556
+ console.log(` (expires ${invite.expiresAt})`);
557
+ }
558
+ }
559
+
560
+ function printGrantToken(token: string, withQr: boolean): void {
561
+ if (withQr) {
562
+ // Best-effort QR render — fall back to the bare token if the lib chokes.
563
+ try {
564
+ const qr = requireForQr('qrcode-terminal') as { generate: (text: string, opts?: { small?: boolean }, cb?: (s: string) => void) => void };
565
+ qr.generate(token, { small: true }, (rendered) => {
566
+ console.error(rendered);
567
+ });
568
+ } catch (err) {
569
+ console.error(`(qrcode-terminal unavailable: ${(err as Error).message})`);
570
+ }
571
+ }
572
+ // The token goes to stdout alone so it can be piped/copied; metadata to stderr.
573
+ console.log(token);
574
+ }
575
+
576
+ program
577
+ .command('invite')
578
+ .description('Generate an invite to add a member to the trust circle')
579
+ .argument('<label>', 'Display label for the new member (e.g. "Mom\'s phone")')
580
+ .option('--ttl <duration>', 'Invite lifetime (e.g. 24h, 7d, 30m)', '24h')
581
+ .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
582
+ .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
583
+ .action(async (label: string, opts: { ttl: string; port: string; host: string }) => {
584
+ let ttlMs: number;
585
+ try {
586
+ ttlMs = parseDuration(opts.ttl);
587
+ } catch (err) {
588
+ console.error(`Invalid --ttl: ${(err as Error).message}`);
589
+ process.exit(1);
590
+ return;
591
+ }
592
+
593
+ const port = resolvePort(opts.port);
594
+
595
+ const url = `http://${opts.host}:${port}/auth/invites`;
596
+ let response: Response;
597
+ try {
598
+ response = await fetch(url, {
599
+ method: 'POST',
600
+ headers: { 'content-type': 'application/json' },
601
+ body: JSON.stringify({ label, ttlMs }),
602
+ });
603
+ } catch (err) {
604
+ console.error(
605
+ `Failed to reach cadre-host at ${url}: ${(err as Error).message}\n` +
606
+ `Hint: is cadre-host running? Try \`cadre-host start\`.`,
607
+ );
608
+ process.exit(2);
609
+ return;
610
+ }
611
+
612
+ if (!response.ok) {
613
+ const text = await response.text().catch(() => '');
614
+ console.error(`cadre-host returned ${response.status}: ${text || response.statusText}`);
615
+ process.exit(1);
616
+ return;
617
+ }
618
+
619
+ const body = await response.json() as { encodedInvite?: string; expiresAt?: string; token?: string };
620
+ if (!body.encodedInvite) {
621
+ console.error('cadre-host returned malformed response (missing encodedInvite)');
622
+ process.exit(1);
623
+ return;
624
+ }
625
+
626
+ console.log(body.encodedInvite);
627
+ if (body.expiresAt) {
628
+ console.error(`(expires at ${body.expiresAt})`);
629
+ }
630
+ process.exit(0);
631
+ });
632
+
633
+ const trust = program
634
+ .command('trust')
635
+ .description('Manage the trust circle (list members, revoke invites/members)');
636
+
637
+ trust
638
+ .command('list')
639
+ .description('List trust-circle members and pending invites')
640
+ .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
641
+ .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
642
+ .action(async (opts: { port: string; host: string }) => {
643
+ const url = `http://${opts.host}:${resolvePort(opts.port)}/auth/trust-circle`;
644
+ let response: Response;
645
+ try {
646
+ response = await fetch(url);
647
+ } catch (err) {
648
+ console.error(`Failed to reach cadre-host at ${url}: ${(err as Error).message}`);
649
+ process.exit(2);
650
+ return;
651
+ }
652
+ if (!response.ok) {
653
+ console.error(`cadre-host returned ${response.status}: ${response.statusText}`);
654
+ process.exit(1);
655
+ return;
656
+ }
657
+ const body = await response.json() as {
658
+ members: Array<{ peerId: string; label: string; addedAt: string; self?: boolean }>;
659
+ pending: Array<{ token: string; label: string; createdAt: string; expiresAt?: string }>;
660
+ };
661
+ console.log('Members:');
662
+ if (body.members.length === 0) {
663
+ console.log(' (none)');
664
+ } else {
665
+ for (const m of body.members) {
666
+ const self = m.self ? ' [self]' : '';
667
+ console.log(` ${m.peerId} ${m.label}${self}`);
668
+ }
669
+ }
670
+ console.log('\nPending invites:');
671
+ if (body.pending.length === 0) {
672
+ console.log(' (none)');
673
+ } else {
674
+ for (const p of body.pending) {
675
+ const expires = p.expiresAt ? ` (expires ${p.expiresAt})` : '';
676
+ console.log(` ${p.token} ${p.label}${expires}`);
677
+ }
678
+ }
679
+ process.exit(0);
680
+ });
681
+
682
+ trust
683
+ .command('revoke')
684
+ .description('Revoke a pending invite (by token) or remove a member (by peerId)')
685
+ .argument('<id>', 'Token (pending invite) or peerId (existing member) to remove')
686
+ .option('--kind <kind>', 'Force interpretation: "invite" | "member" (default: auto)', 'auto')
687
+ .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
688
+ .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
689
+ .action(async (id: string, opts: { kind: string; port: string; host: string }) => {
690
+ const base = `http://${opts.host}:${resolvePort(opts.port)}`;
691
+ const kind = opts.kind === 'auto'
692
+ ? (looksLikePeerId(id) ? 'member' : 'invite')
693
+ : opts.kind;
694
+ const path = kind === 'member'
695
+ ? `/auth/members/${encodeURIComponent(id)}`
696
+ : `/auth/invites/${encodeURIComponent(id)}`;
697
+
698
+ let response: Response;
699
+ try {
700
+ response = await fetch(`${base}${path}`, { method: 'DELETE' });
701
+ } catch (err) {
702
+ console.error(`Failed to reach cadre-host at ${base}: ${(err as Error).message}`);
703
+ process.exit(2);
704
+ return;
705
+ }
706
+ if (!response.ok) {
707
+ const text = await response.text().catch(() => '');
708
+ console.error(`cadre-host returned ${response.status}: ${text || response.statusText}`);
709
+ process.exit(1);
710
+ return;
711
+ }
712
+ console.log(`revoked ${kind}: ${id}`);
713
+ process.exit(0);
714
+ });
715
+
716
+ // ============================================================================
717
+ // grant subcommands — donation grant tokens (who may ask this host for a node)
718
+ // ============================================================================
719
+ //
720
+ // A grant token lets one grantee (friend/family) present a Bearer credential to
721
+ // ask this host to donate cadre nodes, up to a per-grantee cap. These commands
722
+ // are thin HTTP clients of the loopback `/grants-admin` admin surface — no
723
+ // bearer (same-machine admin), same posture as `invite` / `trust`. The
724
+ // grantee-facing provisioning surface lands in the donation-service ticket.
725
+
726
+ const grant = program
727
+ .command('grant')
728
+ .description('Manage donation grant tokens (who may ask this host to donate a node)');
729
+
730
+ grant
731
+ .command('issue')
732
+ .description('Issue a grant token for one grantee (prints the token + QR)')
733
+ .argument('<label>', 'Display label for the grantee (e.g. "Alice\'s cadre")')
734
+ .option('--max-nodes <n>', 'Max concurrently-live donated nodes this grant may hold', parseIntArg)
735
+ .option('--ttl <duration>', 'Grant lifetime (e.g. 30d, 12h); omit for no expiry')
736
+ .option('--no-qr', 'Print only the token, no QR code')
737
+ .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
738
+ .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
739
+ .action(async (label: string, opts: {
740
+ maxNodes?: number;
741
+ ttl?: string;
742
+ qr?: boolean;
743
+ port: string;
744
+ host: string;
745
+ }) => {
746
+ const payload: { label: string; maxNodes?: number; ttlMs?: number } = { label };
747
+ if (typeof opts.maxNodes === 'number') payload.maxNodes = opts.maxNodes;
748
+ if (opts.ttl) {
749
+ try {
750
+ payload.ttlMs = parseDuration(opts.ttl);
751
+ } catch (err) {
752
+ console.error(`Invalid --ttl: ${(err as Error).message}`);
753
+ process.exit(1);
754
+ return;
755
+ }
756
+ }
757
+
758
+ const url = `http://${opts.host}:${resolvePort(opts.port)}/grants-admin`;
759
+ let response: Response;
760
+ try {
761
+ response = await fetch(url, {
762
+ method: 'POST',
763
+ headers: { 'content-type': 'application/json' },
764
+ body: JSON.stringify(payload),
765
+ });
766
+ } catch (err) {
767
+ console.error(
768
+ `Failed to reach cadre-host at ${url}: ${(err as Error).message}\n` +
769
+ `Hint: is cadre-host running? Try \`cadre-host start\`.`,
770
+ );
771
+ process.exit(2);
772
+ return;
773
+ }
774
+ if (!response.ok) {
775
+ const text = await response.text().catch(() => '');
776
+ console.error(`cadre-host returned ${response.status}: ${text || response.statusText}`);
777
+ process.exit(1);
778
+ return;
779
+ }
780
+ const body = await response.json() as { grant?: { token?: string; maxNodes?: number; expiresAt?: string } };
781
+ const issued = body.grant;
782
+ if (!issued?.token) {
783
+ console.error('cadre-host returned malformed response (missing grant token)');
784
+ process.exit(1);
785
+ return;
786
+ }
787
+ printGrantToken(issued.token, opts.qr !== false);
788
+ console.error(`(maxNodes ${issued.maxNodes ?? '?'}${issued.expiresAt ? `, expires ${issued.expiresAt}` : ', no expiry'})`);
789
+ process.exit(0);
790
+ });
791
+
792
+ grant
793
+ .command('list')
794
+ .description('List issued grant tokens')
795
+ .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
796
+ .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
797
+ .action(async (opts: { port: string; host: string }) => {
798
+ const url = `http://${opts.host}:${resolvePort(opts.port)}/grants-admin`;
799
+ let response: Response;
800
+ try {
801
+ response = await fetch(url);
802
+ } catch (err) {
803
+ console.error(`Failed to reach cadre-host at ${url}: ${(err as Error).message}`);
804
+ process.exit(2);
805
+ return;
806
+ }
807
+ if (!response.ok) {
808
+ console.error(`cadre-host returned ${response.status}: ${response.statusText}`);
809
+ process.exit(1);
810
+ return;
811
+ }
812
+ const body = await response.json() as {
813
+ grants: Array<{ token: string; label: string; maxNodes: number; expiresAt?: string; revokedAt?: string }>;
814
+ };
815
+ console.log('Grants:');
816
+ if (body.grants.length === 0) {
817
+ console.log(' (none)');
818
+ } else {
819
+ for (const g of body.grants) {
820
+ const state = g.revokedAt ? ' [revoked]' : (g.expiresAt ? ` (expires ${g.expiresAt})` : '');
821
+ console.log(` ${g.token} ${g.label} max=${g.maxNodes}${state}`);
822
+ }
823
+ }
824
+ process.exit(0);
825
+ });
826
+
827
+ grant
828
+ .command('revoke')
829
+ .description('Revoke a grant token (blocks future requests; live nodes are not torn down)')
830
+ .argument('<token>', 'Grant token to revoke')
831
+ .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
832
+ .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
833
+ .action(async (token: string, opts: { port: string; host: string }) => {
834
+ const base = `http://${opts.host}:${resolvePort(opts.port)}`;
835
+ let response: Response;
836
+ try {
837
+ response = await fetch(`${base}/grants-admin/${encodeURIComponent(token)}`, { method: 'DELETE' });
838
+ } catch (err) {
839
+ console.error(`Failed to reach cadre-host at ${base}: ${(err as Error).message}`);
840
+ process.exit(2);
841
+ return;
842
+ }
843
+ if (!response.ok) {
844
+ const text = await response.text().catch(() => '');
845
+ console.error(`cadre-host returned ${response.status}: ${text || response.statusText}`);
846
+ process.exit(1);
847
+ return;
848
+ }
849
+ console.log(`revoked grant: ${token}`);
850
+ process.exit(0);
851
+ });
852
+
853
+ // ============================================================================
854
+ // nat subcommands
855
+ // ============================================================================
856
+
857
+ const nat = program
858
+ .command('nat')
859
+ .description('Manage NAT traversal, port forwarding, and dynamic DNS');
860
+
861
+ nat
862
+ .command('status')
863
+ .description('Show NAT, external-IP, and DDNS status')
864
+ .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
865
+ .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
866
+ .option('--json', 'Output raw JSON instead of a human-readable summary')
867
+ .action(async (opts: { port: string; host: string; json?: boolean }) => {
868
+ const url = `http://${opts.host}:${resolvePort(opts.port)}/nat/status`;
869
+ const body = await getJson(url);
870
+ if (opts.json) {
871
+ console.log(JSON.stringify(body, null, 2));
872
+ } else {
873
+ printNatStatus(body);
874
+ }
875
+ process.exit(0);
876
+ });
877
+
878
+ nat
879
+ .command('test')
880
+ .description('Re-run reachability probes and print the result')
881
+ .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
882
+ .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
883
+ .option('--json', 'Output raw JSON instead of a human-readable summary')
884
+ .action(async (opts: { port: string; host: string; json?: boolean }) => {
885
+ const url = `http://${opts.host}:${resolvePort(opts.port)}/nat/test`;
886
+ const body = await postJson(url, {});
887
+ if (opts.json) {
888
+ console.log(JSON.stringify(body, null, 2));
889
+ } else {
890
+ printNatStatus(body);
891
+ }
892
+ process.exit(0);
893
+ });
894
+
895
+ nat
896
+ .command('settings')
897
+ .description('Update NAT settings (external port, UPnP toggle)')
898
+ .option('--external-port <port>', 'External port to map')
899
+ .option('--internal-port <port>', 'Internal libp2p port (defaults to external)')
900
+ .option('--no-upnp', 'Disable UPnP/NAT-PMP port mapping')
901
+ .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
902
+ .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
903
+ .action(async (opts: {
904
+ externalPort?: string;
905
+ internalPort?: string;
906
+ upnp?: boolean;
907
+ port: string;
908
+ host: string;
909
+ }) => {
910
+ const url = `http://${opts.host}:${resolvePort(opts.port)}/nat/settings`;
911
+ const patch: Record<string, unknown> = {};
912
+ if (opts.externalPort) patch.externalPort = resolvePort(opts.externalPort);
913
+ if (opts.internalPort) patch.internalPort = resolvePort(opts.internalPort);
914
+ // Commander assigns `upnp: false` when `--no-upnp` is passed.
915
+ if (opts.upnp === false) patch.upnpEnabled = false;
916
+ if (opts.upnp === true) patch.upnpEnabled = true;
917
+
918
+ const body = await putJson(url, patch);
919
+ printNatStatus(body);
920
+ process.exit(0);
921
+ });
922
+
923
+ const ddns = nat
924
+ .command('ddns')
925
+ .description('Configure dynamic DNS');
926
+
927
+ ddns
928
+ .command('set')
929
+ .description('Configure a DDNS provider (and store credentials in the keychain)')
930
+ .argument('<provider>', 'Provider ID (e.g. "duckdns")')
931
+ .option('--hostname <hostname>', 'Hostname to publish (e.g. foo.duckdns.org)')
932
+ .option('--token <token>', 'Provider token (a secret value; prompts if omitted)')
933
+ .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
934
+ .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
935
+ .action(async (provider: string, opts: {
936
+ hostname?: string;
937
+ token?: string;
938
+ port: string;
939
+ host: string;
940
+ }) => {
941
+ if (!opts.hostname) {
942
+ console.error('--hostname is required');
943
+ process.exit(1);
944
+ return;
945
+ }
946
+ const config: Record<string, string> = {};
947
+ if (opts.token) config.token = opts.token;
948
+
949
+ if (!config.token) {
950
+ if (!process.stdin.isTTY) {
951
+ console.error(
952
+ 'Missing --token for provider "' + provider + '" and stdin is not a TTY. ' +
953
+ 'Re-run with --token <secret>.',
954
+ );
955
+ process.exit(1);
956
+ return;
957
+ }
958
+ try {
959
+ config.token = await readSecretLine('DDNS token: ');
960
+ } catch (err) {
961
+ console.error('Failed to read token: ' + (err as Error).message);
962
+ process.exit(1);
963
+ return;
964
+ }
965
+ }
966
+
967
+ const url = `http://${opts.host}:${resolvePort(opts.port)}/nat/ddns`;
968
+ const body = await putJson(url, {
969
+ providerId: provider,
970
+ hostname: opts.hostname,
971
+ config,
972
+ externallyManaged: false,
973
+ });
974
+ printNatStatus(body);
975
+ process.exit(0);
976
+ });
977
+
978
+ ddns
979
+ .command('external')
980
+ .description('Declare an externally-managed DDNS hostname (cadre-host does not update it)')
981
+ .requiredOption('--hostname <hostname>', 'Hostname (no provider; cadre-host will not push updates)')
982
+ .option('--port <port>', 'cadre-host management API port', String(DEFAULT_PORT))
983
+ .option('--host <host>', 'cadre-host management API host', '127.0.0.1')
984
+ .action(async (opts: { hostname: string; port: string; host: string }) => {
985
+ const url = `http://${opts.host}:${resolvePort(opts.port)}/nat/settings`;
986
+ const body = await putJson(url, {
987
+ ddns: {
988
+ providerId: 'external',
989
+ hostname: opts.hostname,
990
+ externallyManaged: true,
991
+ },
992
+ });
993
+ printNatStatus(body);
994
+ process.exit(0);
995
+ });
996
+
997
+ // ============================================================================
998
+ // push subcommands — provision FCM/APNs credentials for strand-wake delivery
999
+ // ============================================================================
1000
+ //
1001
+ // These operate directly on the data dir's secret store + host.config.json (they
1002
+ // do NOT go through the running management API). Private keys land in the OS
1003
+ // keychain (keytar) or the 0600 file-store fallback; the non-secret bits (APNs
1004
+ // bundle id / sandbox toggle, cooldown/debounce) land in host.config.json. New
1005
+ // credentials take effect on the next owner-node (re)spawn — run
1006
+ // `cadre-host` restart (or restart the service) to apply them immediately.
1007
+
1008
+ const push = program
1009
+ .command('push')
1010
+ .description('Configure FCM/APNs push credentials for mobile strand-wake delivery');
1011
+
1012
+ push
1013
+ .command('fcm')
1014
+ .description('Store Firebase Cloud Messaging (Android) service-account credentials')
1015
+ .requiredOption('--project-id <id>', 'GCP / Firebase project id')
1016
+ .requiredOption('--client-email <email>', 'Service-account email')
1017
+ .option('--private-key-file <path>', 'Path to the service-account private key (PEM)')
1018
+ .option('--private-key <pem>', 'Inline PEM private key (prefer --private-key-file)')
1019
+ .option('--data-dir <path>', 'Override the data directory (env: CADRE_HOST_DATA_DIR)')
1020
+ .action(async (opts: {
1021
+ projectId: string;
1022
+ clientEmail: string;
1023
+ privateKeyFile?: string;
1024
+ privateKey?: string;
1025
+ dataDir?: string;
1026
+ }) => {
1027
+ const { dataDir } = resolveHostPaths(opts.dataDir);
1028
+ const privateKey = readPrivateKeyArg(opts.privateKeyFile, opts.privateKey, 'FCM');
1029
+ const secrets = await createSecretsStore(dataDir);
1030
+ await setFcmSecret(secrets, {
1031
+ projectId: opts.projectId,
1032
+ clientEmail: opts.clientEmail,
1033
+ privateKey,
1034
+ });
1035
+ console.log('✓ FCM credentials stored. Restart cadre-host to apply on the owner node.');
1036
+ process.exit(0);
1037
+ });
1038
+
1039
+ push
1040
+ .command('apns')
1041
+ .description('Store Apple Push Notification service (iOS) auth-key credentials')
1042
+ .requiredOption('--key-id <id>', 'APNs key id (the .p8 key identifier)')
1043
+ .requiredOption('--team-id <id>', 'Apple developer team id')
1044
+ .requiredOption('--bundle-id <id>', 'App bundle id (becomes the apns-topic)')
1045
+ .option('--private-key-file <path>', 'Path to the .p8 auth key (PEM)')
1046
+ .option('--private-key <pem>', 'Inline .p8 PEM key (prefer --private-key-file)')
1047
+ .option('--production', 'Target the production APNs host (default: sandbox)')
1048
+ .option('--data-dir <path>', 'Override the data directory (env: CADRE_HOST_DATA_DIR)')
1049
+ .action(async (opts: {
1050
+ keyId: string;
1051
+ teamId: string;
1052
+ bundleId: string;
1053
+ privateKeyFile?: string;
1054
+ privateKey?: string;
1055
+ production?: boolean;
1056
+ dataDir?: string;
1057
+ }) => {
1058
+ const { dataDir, cfgPath } = resolveHostPaths(opts.dataDir);
1059
+ const privateKey = readPrivateKeyArg(opts.privateKeyFile, opts.privateKey, 'APNs');
1060
+ const secrets = await createSecretsStore(dataDir);
1061
+ // Secret bits → secret store; non-secret app-config → host.config.json.
1062
+ await setApnsSecret(secrets, { keyId: opts.keyId, teamId: opts.teamId, privateKey });
1063
+ const current = readHostConfig(cfgPath);
1064
+ updateHostConfig(cfgPath, {
1065
+ push: {
1066
+ ...current.push,
1067
+ apns: { bundleId: opts.bundleId, production: opts.production === true },
1068
+ },
1069
+ });
1070
+ console.log(
1071
+ `✓ APNs credentials stored (${opts.production ? 'production' : 'sandbox'}). ` +
1072
+ `Restart cadre-host to apply on the owner node.`,
1073
+ );
1074
+ process.exit(0);
1075
+ });
1076
+
1077
+ push
1078
+ .command('options')
1079
+ .description('Set non-secret push tuning (anti-spam cooldown / burst-coalesce window)')
1080
+ .option('--cooldown-ms <ms>', 'Per-(peer,strand) minimum gap between wakes', parseIntArg)
1081
+ .option('--debounce-ms <ms>', 'Per-strand burst-coalescing window', parseIntArg)
1082
+ .option('--data-dir <path>', 'Override the data directory (env: CADRE_HOST_DATA_DIR)')
1083
+ .action((opts: { cooldownMs?: number; debounceMs?: number; dataDir?: string }) => {
1084
+ const { cfgPath } = resolveHostPaths(opts.dataDir);
1085
+ const current = readHostConfig(cfgPath);
1086
+ const nextPush = { ...current.push };
1087
+ if (typeof opts.cooldownMs === 'number') nextPush.cooldownMs = opts.cooldownMs;
1088
+ if (typeof opts.debounceMs === 'number') nextPush.debounceMs = opts.debounceMs;
1089
+ updateHostConfig(cfgPath, { push: nextPush });
1090
+ console.log('✓ Push options updated.');
1091
+ process.exit(0);
1092
+ });
1093
+
1094
+ push
1095
+ .command('clear')
1096
+ .description('Remove stored push credentials')
1097
+ .argument('<target>', 'Which to clear: "fcm", "apns", or "all"')
1098
+ .option('--data-dir <path>', 'Override the data directory (env: CADRE_HOST_DATA_DIR)')
1099
+ .action(async (target: string, opts: { dataDir?: string }) => {
1100
+ if (!['fcm', 'apns', 'all'].includes(target)) {
1101
+ console.error(`push clear: target must be one of fcm | apns | all (got "${target}")`);
1102
+ process.exit(1);
1103
+ return;
1104
+ }
1105
+ const { dataDir, cfgPath } = resolveHostPaths(opts.dataDir);
1106
+ const secrets = await createSecretsStore(dataDir);
1107
+ if (target === 'fcm' || target === 'all') await clearPushSecret(secrets, 'fcm');
1108
+ if (target === 'apns' || target === 'all') {
1109
+ await clearPushSecret(secrets, 'apns');
1110
+ const current = readHostConfig(cfgPath);
1111
+ if (current.push?.apns) {
1112
+ const { apns: _drop, ...rest } = current.push;
1113
+ updateHostConfig(cfgPath, { push: rest });
1114
+ }
1115
+ }
1116
+ console.log(`✓ Cleared push credentials: ${target}. Restart cadre-host to apply.`);
1117
+ process.exit(0);
1118
+ });
1119
+
1120
+ push
1121
+ .command('status')
1122
+ .description('Show which push platforms are configured (no secret material)')
1123
+ .option('--data-dir <path>', 'Override the data directory (env: CADRE_HOST_DATA_DIR)')
1124
+ .action(async (opts: { dataDir?: string }) => {
1125
+ const { dataDir, cfgPath } = resolveHostPaths(opts.dataDir);
1126
+ const secrets = await createSecretsStore(dataDir);
1127
+ const status = await pushStatus(secrets);
1128
+ const cfg = readHostConfig(cfgPath);
1129
+ console.log('Push credentials:');
1130
+ console.log(` FCM: ${status.fcm ? 'configured' : 'not configured'}`);
1131
+ const prod = cfg.push?.apns?.production ? 'production' : 'sandbox';
1132
+ const bundle = cfg.push?.apns?.bundleId ? ` bundle=${cfg.push.apns.bundleId} (${prod})` : '';
1133
+ console.log(` APNs: ${status.apns ? `configured${bundle}` : 'not configured'}`);
1134
+ if (cfg.push?.cooldownMs !== undefined) console.log(` cooldownMs: ${cfg.push.cooldownMs}`);
1135
+ if (cfg.push?.debounceMs !== undefined) console.log(` debounceMs: ${cfg.push.debounceMs}`);
1136
+ process.exit(0);
1137
+ });
1138
+
1139
+ /** Resolve the data dir + config path for a direct-on-disk push subcommand. */
1140
+ function resolveHostPaths(dataDirOpt?: string): { dataDir: string; cfgPath: string } {
1141
+ const platform = detectPlatform();
1142
+ const dataDir = dataDirOpt ?? process.env.CADRE_HOST_DATA_DIR ?? defaultDataDir(platform);
1143
+ const cfgPath = resolveConfigPath(dataDir);
1144
+ if (!existsSync(cfgPath)) {
1145
+ console.error(`${cfgPath} not found. Run \`cadre-host install\` first (or pass --data-dir).`);
1146
+ process.exit(1);
1147
+ }
1148
+ // Resolve the real data dir from the persisted config (handles default-dir installs).
1149
+ const cfg = readHostConfig(cfgPath);
1150
+ return { dataDir: cfg.dataDir, cfgPath };
1151
+ }
1152
+
1153
+ /** Read a private key from a file or inline flag; exit with a clear error if neither. */
1154
+ function readPrivateKeyArg(file: string | undefined, inline: string | undefined, label: string): string {
1155
+ if (file) {
1156
+ try {
1157
+ return readFileSync(file, 'utf8');
1158
+ } catch (err) {
1159
+ console.error(`Failed to read ${label} private key file ${file}: ${(err as Error).message}`);
1160
+ process.exit(1);
1161
+ }
1162
+ }
1163
+ if (inline) return inline;
1164
+ console.error(`${label}: supply --private-key-file <path> (or --private-key <pem>).`);
1165
+ process.exit(1);
1166
+ throw new Error('unreachable');
1167
+ }
1168
+
1169
+ async function getJson(url: string): Promise<NatStatusLike> {
1170
+ return await callJson(url, 'GET');
1171
+ }
1172
+
1173
+ async function postJson(url: string, body: unknown): Promise<NatStatusLike> {
1174
+ return await callJson(url, 'POST', body);
1175
+ }
1176
+
1177
+ async function putJson(url: string, body: unknown): Promise<NatStatusLike> {
1178
+ return await callJson(url, 'PUT', body);
1179
+ }
1180
+
1181
+ interface NatStatusLike {
1182
+ portMode?: string;
1183
+ externalPort?: number;
1184
+ internalPort?: number;
1185
+ externalIp?: string | null;
1186
+ routerExternalIp?: string | null;
1187
+ cgnatDetected?: boolean;
1188
+ directReachability?: string;
1189
+ lastTestedAt?: string | null;
1190
+ mappingLeaseExpiresAt?: string | null;
1191
+ ddns?: {
1192
+ providerId?: string | null;
1193
+ hostname?: string | null;
1194
+ externallyManaged?: boolean;
1195
+ lastUpdateAt?: string | null;
1196
+ lastUpdateOk?: boolean | null;
1197
+ lastError?: string | null;
1198
+ };
1199
+ }
1200
+
1201
+ async function callJson(url: string, method: string, body?: unknown): Promise<NatStatusLike> {
1202
+ let response: Response;
1203
+ try {
1204
+ const init: RequestInit = { method };
1205
+ if (body !== undefined) {
1206
+ init.headers = { 'content-type': 'application/json' };
1207
+ init.body = JSON.stringify(body);
1208
+ }
1209
+ response = await fetch(url, init);
1210
+ } catch (err) {
1211
+ console.error(
1212
+ `Failed to reach cadre-host at ${url}: ${(err as Error).message}\n` +
1213
+ `Hint: is cadre-host running? Try \`cadre-host start\`.`,
1214
+ );
1215
+ process.exit(2);
1216
+ throw err;
1217
+ }
1218
+ if (!response.ok) {
1219
+ const text = await response.text().catch(() => '');
1220
+ console.error(`cadre-host returned ${response.status}: ${text || response.statusText}`);
1221
+ process.exit(1);
1222
+ throw new Error('non-ok');
1223
+ }
1224
+ if (response.status === 204) return {} as NatStatusLike;
1225
+ return await response.json() as NatStatusLike;
1226
+ }
1227
+
1228
+ function printNatStatus(s: NatStatusLike): void {
1229
+ console.log(`Port mapping: ${s.portMode ?? '?'} (external ${s.externalPort ?? '?'} → internal ${s.internalPort ?? '?'})`);
1230
+ if (s.routerExternalIp) {
1231
+ console.log(`Router IP: ${s.routerExternalIp}`);
1232
+ }
1233
+ console.log(`External IP: ${s.externalIp ?? '(unknown)'}${s.cgnatDetected ? ' [CGNAT detected]' : ''}`);
1234
+ console.log(`Reachability: ${s.directReachability ?? 'unknown'}${s.lastTestedAt ? ` (tested ${s.lastTestedAt})` : ''}`);
1235
+ if (s.mappingLeaseExpiresAt) {
1236
+ console.log(`Lease expires: ${s.mappingLeaseExpiresAt}`);
1237
+ }
1238
+ const ddns = s.ddns ?? {};
1239
+ if (ddns.providerId || ddns.hostname) {
1240
+ console.log(`\nDDNS:`);
1241
+ console.log(` Provider: ${ddns.providerId ?? '(none)'}${ddns.externallyManaged ? ' [externally managed]' : ''}`);
1242
+ console.log(` Hostname: ${ddns.hostname ?? '(unset)'}`);
1243
+ if (ddns.lastUpdateAt) {
1244
+ const ok = ddns.lastUpdateOk ? 'OK' : 'FAIL';
1245
+ console.log(` Last update: ${ok} at ${ddns.lastUpdateAt}${ddns.lastError ? ` — ${ddns.lastError}` : ''}`);
1246
+ }
1247
+ } else {
1248
+ console.log('\nDDNS: not configured');
1249
+ }
1250
+ }
1251
+
1252
+ /** Read a single line from stdin with echo suppressed (TTY only). */
1253
+ function readSecretLine(prompt: string): Promise<string> {
1254
+ return new Promise<string>((resolveLine, rejectLine) => {
1255
+ const stdin = process.stdin;
1256
+ const stdout = process.stdout;
1257
+ const wasRaw = stdin.isRaw;
1258
+ try {
1259
+ stdout.write(prompt);
1260
+ stdin.setRawMode(true);
1261
+ } catch (err) {
1262
+ rejectLine(err);
1263
+ return;
1264
+ }
1265
+ stdin.resume();
1266
+ stdin.setEncoding('utf8');
1267
+
1268
+ let buf = '';
1269
+ const onData = (chunk: string) => {
1270
+ for (const ch of chunk) {
1271
+ if (ch === '\n' || ch === '\r' || ch === '') {
1272
+ stdin.removeListener('data', onData);
1273
+ try { stdin.setRawMode(wasRaw); } catch { /* ignore */ }
1274
+ stdin.pause();
1275
+ stdout.write('\n');
1276
+ resolveLine(buf);
1277
+ return;
1278
+ }
1279
+ if (ch === '') {
1280
+ // Ctrl-C
1281
+ stdin.removeListener('data', onData);
1282
+ try { stdin.setRawMode(wasRaw); } catch { /* ignore */ }
1283
+ stdin.pause();
1284
+ stdout.write('\n');
1285
+ rejectLine(new Error('cancelled'));
1286
+ return;
1287
+ }
1288
+ if (ch === '' || ch === '\b') {
1289
+ buf = buf.slice(0, -1);
1290
+ continue;
1291
+ }
1292
+ buf += ch;
1293
+ }
1294
+ };
1295
+ stdin.on('data', onData);
1296
+ });
1297
+ }
1298
+
1299
+ void program.parseAsync();