@serfab/cadre-host 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (300) hide show
  1. package/README.md +101 -0
  2. package/dist/auth/duration.d.ts +1 -0
  3. package/dist/auth/duration.js +32 -0
  4. package/dist/auth/duration.js.map +1 -0
  5. package/dist/auth/index.d.ts +9 -0
  6. package/dist/auth/index.js +8 -0
  7. package/dist/auth/index.js.map +1 -0
  8. package/dist/auth/trust-circle-store.d.ts +26 -0
  9. package/dist/auth/trust-circle-store.js +129 -0
  10. package/dist/auth/trust-circle-store.js.map +1 -0
  11. package/dist/auth/trust-circle.d.ts +91 -0
  12. package/dist/auth/trust-circle.js +230 -0
  13. package/dist/auth/trust-circle.js.map +1 -0
  14. package/dist/auth/types.d.ts +81 -0
  15. package/dist/auth/types.js +24 -0
  16. package/dist/auth/types.js.map +1 -0
  17. package/dist/bin/host.d.ts +13 -0
  18. package/dist/bin/host.js +826 -0
  19. package/dist/bin/host.js.map +1 -0
  20. package/dist/index.d.ts +32 -0
  21. package/dist/index.js +27 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/installer/browser.d.ts +14 -0
  24. package/dist/installer/browser.js +35 -0
  25. package/dist/installer/browser.js.map +1 -0
  26. package/dist/installer/config.d.ts +43 -0
  27. package/dist/installer/config.js +113 -0
  28. package/dist/installer/config.js.map +1 -0
  29. package/dist/installer/identity.d.ts +23 -0
  30. package/dist/installer/identity.js +36 -0
  31. package/dist/installer/identity.js.map +1 -0
  32. package/dist/installer/index.d.ts +83 -0
  33. package/dist/installer/index.js +204 -0
  34. package/dist/installer/index.js.map +1 -0
  35. package/dist/installer/paths.d.ts +33 -0
  36. package/dist/installer/paths.js +84 -0
  37. package/dist/installer/paths.js.map +1 -0
  38. package/dist/installer/platform.d.ts +9 -0
  39. package/dist/installer/platform.js +21 -0
  40. package/dist/installer/platform.js.map +1 -0
  41. package/dist/installer/service-host/index.d.ts +11 -0
  42. package/dist/installer/service-host/index.js +16 -0
  43. package/dist/installer/service-host/index.js.map +1 -0
  44. package/dist/installer/service-host/launchd.d.ts +16 -0
  45. package/dist/installer/service-host/launchd.js +79 -0
  46. package/dist/installer/service-host/launchd.js.map +1 -0
  47. package/dist/installer/service-host/nssm.d.ts +20 -0
  48. package/dist/installer/service-host/nssm.js +88 -0
  49. package/dist/installer/service-host/nssm.js.map +1 -0
  50. package/dist/installer/service-host/systemd.d.ts +16 -0
  51. package/dist/installer/service-host/systemd.js +78 -0
  52. package/dist/installer/service-host/systemd.js.map +1 -0
  53. package/dist/installer/service-host/template.d.ts +6 -0
  54. package/dist/installer/service-host/template.js +20 -0
  55. package/dist/installer/service-host/template.js.map +1 -0
  56. package/dist/installer/service-host/types.d.ts +40 -0
  57. package/dist/installer/service-host/types.js +6 -0
  58. package/dist/installer/service-host/types.js.map +1 -0
  59. package/dist/installer/wizard.d.ts +31 -0
  60. package/dist/installer/wizard.js +67 -0
  61. package/dist/installer/wizard.js.map +1 -0
  62. package/dist/nat/address-resolver.d.ts +22 -0
  63. package/dist/nat/address-resolver.js +31 -0
  64. package/dist/nat/address-resolver.js.map +1 -0
  65. package/dist/nat/ddns/duckdns.d.ts +12 -0
  66. package/dist/nat/ddns/duckdns.js +57 -0
  67. package/dist/nat/ddns/duckdns.js.map +1 -0
  68. package/dist/nat/ddns/index.d.ts +30 -0
  69. package/dist/nat/ddns/index.js +21 -0
  70. package/dist/nat/ddns/index.js.map +1 -0
  71. package/dist/nat/ddns/updater.d.ts +68 -0
  72. package/dist/nat/ddns/updater.js +194 -0
  73. package/dist/nat/ddns/updater.js.map +1 -0
  74. package/dist/nat/external-ip.d.ts +62 -0
  75. package/dist/nat/external-ip.js +114 -0
  76. package/dist/nat/external-ip.js.map +1 -0
  77. package/dist/nat/index.d.ts +22 -0
  78. package/dist/nat/index.js +16 -0
  79. package/dist/nat/index.js.map +1 -0
  80. package/dist/nat/nat-service.d.ts +101 -0
  81. package/dist/nat/nat-service.js +284 -0
  82. package/dist/nat/nat-service.js.map +1 -0
  83. package/dist/nat/nat-store.d.ts +19 -0
  84. package/dist/nat/nat-store.js +136 -0
  85. package/dist/nat/nat-store.js.map +1 -0
  86. package/dist/nat/port-mapper.d.ts +98 -0
  87. package/dist/nat/port-mapper.js +226 -0
  88. package/dist/nat/port-mapper.js.map +1 -0
  89. package/dist/nat/reachability.d.ts +19 -0
  90. package/dist/nat/reachability.js +29 -0
  91. package/dist/nat/reachability.js.map +1 -0
  92. package/dist/nat/secrets/file-store.d.ts +23 -0
  93. package/dist/nat/secrets/file-store.js +102 -0
  94. package/dist/nat/secrets/file-store.js.map +1 -0
  95. package/dist/nat/secrets/index.d.ts +36 -0
  96. package/dist/nat/secrets/index.js +56 -0
  97. package/dist/nat/secrets/index.js.map +1 -0
  98. package/dist/nat/secrets/keytar-store.d.ts +18 -0
  99. package/dist/nat/secrets/keytar-store.js +52 -0
  100. package/dist/nat/secrets/keytar-store.js.map +1 -0
  101. package/dist/nat/types.d.ts +120 -0
  102. package/dist/nat/types.js +24 -0
  103. package/dist/nat/types.js.map +1 -0
  104. package/dist/orchestrator/host-process-orchestrator.d.ts +87 -0
  105. package/dist/orchestrator/host-process-orchestrator.js +557 -0
  106. package/dist/orchestrator/host-process-orchestrator.js.map +1 -0
  107. package/dist/orchestrator/index.d.ts +3 -0
  108. package/dist/orchestrator/index.js +2 -0
  109. package/dist/orchestrator/index.js.map +1 -0
  110. package/dist/orchestrator/log-rotator.d.ts +25 -0
  111. package/dist/orchestrator/log-rotator.js +56 -0
  112. package/dist/orchestrator/log-rotator.js.map +1 -0
  113. package/dist/orchestrator/pid-liveness.d.ts +11 -0
  114. package/dist/orchestrator/pid-liveness.js +26 -0
  115. package/dist/orchestrator/pid-liveness.js.map +1 -0
  116. package/dist/orchestrator/port-allocator.d.ts +16 -0
  117. package/dist/orchestrator/port-allocator.js +38 -0
  118. package/dist/orchestrator/port-allocator.js.map +1 -0
  119. package/dist/orchestrator/state-store.d.ts +32 -0
  120. package/dist/orchestrator/state-store.js +44 -0
  121. package/dist/orchestrator/state-store.js.map +1 -0
  122. package/dist/orchestrator/types.d.ts +85 -0
  123. package/dist/orchestrator/types.js +31 -0
  124. package/dist/orchestrator/types.js.map +1 -0
  125. package/dist/server/error-handler.d.ts +26 -0
  126. package/dist/server/error-handler.js +95 -0
  127. package/dist/server/error-handler.js.map +1 -0
  128. package/dist/server/events/bus.d.ts +17 -0
  129. package/dist/server/events/bus.js +36 -0
  130. package/dist/server/events/bus.js.map +1 -0
  131. package/dist/server/events/sse-route.d.ts +22 -0
  132. package/dist/server/events/sse-route.js +65 -0
  133. package/dist/server/events/sse-route.js.map +1 -0
  134. package/dist/server/events/types.d.ts +25 -0
  135. package/dist/server/events/types.js +8 -0
  136. package/dist/server/events/types.js.map +1 -0
  137. package/dist/server/index.d.ts +67 -0
  138. package/dist/server/index.js +149 -0
  139. package/dist/server/index.js.map +1 -0
  140. package/dist/server/origin-guard.d.ts +24 -0
  141. package/dist/server/origin-guard.js +72 -0
  142. package/dist/server/origin-guard.js.map +1 -0
  143. package/dist/server/routes/nat.d.ts +16 -0
  144. package/dist/server/routes/nat.js +42 -0
  145. package/dist/server/routes/nat.js.map +1 -0
  146. package/dist/server/routes/nodes.d.ts +23 -0
  147. package/dist/server/routes/nodes.js +128 -0
  148. package/dist/server/routes/nodes.js.map +1 -0
  149. package/dist/server/routes/settings.d.ts +26 -0
  150. package/dist/server/routes/settings.js +97 -0
  151. package/dist/server/routes/settings.js.map +1 -0
  152. package/dist/server/routes/status.d.ts +42 -0
  153. package/dist/server/routes/status.js +76 -0
  154. package/dist/server/routes/status.js.map +1 -0
  155. package/dist/server/routes/trust-circle.d.ts +17 -0
  156. package/dist/server/routes/trust-circle.js +35 -0
  157. package/dist/server/routes/trust-circle.js.map +1 -0
  158. package/dist/server/routes/update.d.ts +16 -0
  159. package/dist/server/routes/update.js +29 -0
  160. package/dist/server/routes/update.js.map +1 -0
  161. package/dist/server/server.d.ts +40 -0
  162. package/dist/server/server.js +90 -0
  163. package/dist/server/server.js.map +1 -0
  164. package/dist/server/settings-store.d.ts +24 -0
  165. package/dist/server/settings-store.js +27 -0
  166. package/dist/server/settings-store.js.map +1 -0
  167. package/dist/server/static.d.ts +25 -0
  168. package/dist/server/static.js +177 -0
  169. package/dist/server/static.js.map +1 -0
  170. package/dist/ui/assets/index-BwU5mJGF.css +1 -0
  171. package/dist/ui/assets/index-C9uChk2P.js +14 -0
  172. package/dist/ui/assets/index-C9uChk2P.js.map +1 -0
  173. package/dist/ui/index.html +14 -0
  174. package/dist/update/apply.d.ts +37 -0
  175. package/dist/update/apply.js +102 -0
  176. package/dist/update/apply.js.map +1 -0
  177. package/dist/update/index.d.ts +101 -0
  178. package/dist/update/index.js +228 -0
  179. package/dist/update/index.js.map +1 -0
  180. package/dist/update/manifest.d.ts +48 -0
  181. package/dist/update/manifest.js +152 -0
  182. package/dist/update/manifest.js.map +1 -0
  183. package/dist/update/release-key.d.ts +24 -0
  184. package/dist/update/release-key.js +52 -0
  185. package/dist/update/release-key.js.map +1 -0
  186. package/dist/update/store.d.ts +22 -0
  187. package/dist/update/store.js +81 -0
  188. package/dist/update/store.js.map +1 -0
  189. package/dist/update/types.d.ts +90 -0
  190. package/dist/update/types.js +22 -0
  191. package/dist/update/types.js.map +1 -0
  192. package/dist/update/version.d.ts +18 -0
  193. package/dist/update/version.js +76 -0
  194. package/dist/update/version.js.map +1 -0
  195. package/package.json +80 -0
  196. package/service/README.md +86 -0
  197. package/service/cadre-host.service.tmpl +16 -0
  198. package/service/com.serfab.cadre-host.plist.tmpl +35 -0
  199. package/service/install-service.ps1 +98 -0
  200. package/service/uninstall-service.ps1 +19 -0
  201. package/src/__tests__/cli-invite.smoke.test.ts +187 -0
  202. package/src/__tests__/cli-nat.smoke.test.ts +207 -0
  203. package/src/__tests__/cli.smoke.test.ts +41 -0
  204. package/src/__tests__/orchestrator.test.ts +570 -0
  205. package/src/auth/__tests__/duration.test.ts +28 -0
  206. package/src/auth/__tests__/trust-circle-integration.test.ts +128 -0
  207. package/src/auth/__tests__/trust-circle-store.test.ts +115 -0
  208. package/src/auth/__tests__/trust-circle.test.ts +334 -0
  209. package/src/auth/duration.ts +33 -0
  210. package/src/auth/index.ts +19 -0
  211. package/src/auth/trust-circle-store.ts +155 -0
  212. package/src/auth/trust-circle.ts +304 -0
  213. package/src/auth/types.ts +96 -0
  214. package/src/bin/host.ts +905 -0
  215. package/src/index.ts +167 -0
  216. package/src/installer/__tests__/config.test.ts +86 -0
  217. package/src/installer/__tests__/identity.test.ts +34 -0
  218. package/src/installer/__tests__/installer.smoke.test.ts +124 -0
  219. package/src/installer/__tests__/paths.test.ts +47 -0
  220. package/src/installer/__tests__/service-host.test.ts +62 -0
  221. package/src/installer/__tests__/wizard.test.ts +60 -0
  222. package/src/installer/browser.ts +42 -0
  223. package/src/installer/config.ts +153 -0
  224. package/src/installer/identity.ts +49 -0
  225. package/src/installer/index.ts +303 -0
  226. package/src/installer/paths.ts +109 -0
  227. package/src/installer/platform.ts +27 -0
  228. package/src/installer/service-host/index.ts +21 -0
  229. package/src/installer/service-host/launchd.ts +90 -0
  230. package/src/installer/service-host/nssm.ts +100 -0
  231. package/src/installer/service-host/systemd.ts +88 -0
  232. package/src/installer/service-host/template.ts +21 -0
  233. package/src/installer/service-host/types.ts +48 -0
  234. package/src/installer/wizard.ts +92 -0
  235. package/src/nat/__tests__/address-resolver.test.ts +82 -0
  236. package/src/nat/__tests__/ddns-duckdns.test.ts +83 -0
  237. package/src/nat/__tests__/ddns-updater.test.ts +253 -0
  238. package/src/nat/__tests__/external-ip.test.ts +124 -0
  239. package/src/nat/__tests__/nat-service.test.ts +305 -0
  240. package/src/nat/__tests__/nat-store.test.ts +93 -0
  241. package/src/nat/__tests__/port-mapper.test.ts +191 -0
  242. package/src/nat/__tests__/reachability.test.ts +24 -0
  243. package/src/nat/__tests__/secrets.test.ts +156 -0
  244. package/src/nat/address-resolver.ts +51 -0
  245. package/src/nat/ddns/duckdns.ts +76 -0
  246. package/src/nat/ddns/index.ts +55 -0
  247. package/src/nat/ddns/updater.ts +243 -0
  248. package/src/nat/external-ip.ts +154 -0
  249. package/src/nat/index.ts +71 -0
  250. package/src/nat/nat-service.ts +375 -0
  251. package/src/nat/nat-store.ts +154 -0
  252. package/src/nat/port-mapper.ts +329 -0
  253. package/src/nat/reachability.ts +34 -0
  254. package/src/nat/secrets/file-store.ts +130 -0
  255. package/src/nat/secrets/index.ts +82 -0
  256. package/src/nat/secrets/keytar-store.ts +67 -0
  257. package/src/nat/types.ts +157 -0
  258. package/src/orchestrator/host-process-orchestrator.ts +626 -0
  259. package/src/orchestrator/index.ts +3 -0
  260. package/src/orchestrator/log-rotator.ts +53 -0
  261. package/src/orchestrator/pid-liveness.ts +24 -0
  262. package/src/orchestrator/port-allocator.ts +43 -0
  263. package/src/orchestrator/state-store.ts +72 -0
  264. package/src/orchestrator/types.ts +95 -0
  265. package/src/server/__tests__/bus.test.ts +38 -0
  266. package/src/server/__tests__/error-handler.test.ts +96 -0
  267. package/src/server/__tests__/nodes-route.test.ts +179 -0
  268. package/src/server/__tests__/origin-guard.test.ts +72 -0
  269. package/src/server/__tests__/publishers.test.ts +216 -0
  270. package/src/server/__tests__/server.smoke.test.ts +178 -0
  271. package/src/server/__tests__/settings-route.test.ts +177 -0
  272. package/src/server/__tests__/sse-route.test.ts +119 -0
  273. package/src/server/__tests__/status-route.test.ts +113 -0
  274. package/src/server/error-handler.ts +108 -0
  275. package/src/server/events/bus.ts +42 -0
  276. package/src/server/events/sse-route.ts +81 -0
  277. package/src/server/events/types.ts +22 -0
  278. package/src/server/index.ts +209 -0
  279. package/src/server/origin-guard.ts +84 -0
  280. package/src/server/routes/nat.ts +63 -0
  281. package/src/server/routes/nodes.ts +147 -0
  282. package/src/server/routes/settings.ts +115 -0
  283. package/src/server/routes/status.ts +108 -0
  284. package/src/server/routes/trust-circle.ts +49 -0
  285. package/src/server/routes/update.ts +43 -0
  286. package/src/server/server.ts +122 -0
  287. package/src/server/settings-store.ts +37 -0
  288. package/src/server/static.ts +191 -0
  289. package/src/update/__tests__/apply.test.ts +101 -0
  290. package/src/update/__tests__/manifest.test.ts +93 -0
  291. package/src/update/__tests__/store.test.ts +81 -0
  292. package/src/update/__tests__/update-service.integration.test.ts +221 -0
  293. package/src/update/__tests__/version.test.ts +31 -0
  294. package/src/update/apply.ts +148 -0
  295. package/src/update/index.ts +303 -0
  296. package/src/update/manifest.ts +172 -0
  297. package/src/update/release-key.ts +55 -0
  298. package/src/update/store.ts +101 -0
  299. package/src/update/types.ts +109 -0
  300. package/src/update/version.ts +80 -0
@@ -0,0 +1,375 @@
1
+ import debug from 'debug';
2
+
3
+ import {
4
+ NatError,
5
+ type DdnsProviderInfo,
6
+ type NatDdnsStatus,
7
+ type NatHandlers,
8
+ type NatSettingsFile,
9
+ type NatStatusSnapshot,
10
+ } from './types.js';
11
+ import { NatStore } from './nat-store.js';
12
+ import { ExternalIpDetector, type ExternalIpResult } from './external-ip.js';
13
+ import {
14
+ PortMapperService,
15
+ createDefaultPortMapper,
16
+ type PortMapper,
17
+ type PortMapperState,
18
+ } from './port-mapper.js';
19
+ import { evaluateReachability } from './reachability.js';
20
+ import { DdnsUpdater } from './ddns/updater.js';
21
+ import { getProvider, listProviders } from './ddns/index.js';
22
+ import {
23
+ buildInviteAddresses,
24
+ type BuildInviteAddressesInput,
25
+ } from './address-resolver.js';
26
+ import { createSecretsStore, ddnsAccount, type SecretsStore } from './secrets/index.js';
27
+
28
+ const log = debug('cadre:host:nat-service');
29
+
30
+ /**
31
+ * Minimal slice of CadreNode that NatService needs — defined as an interface
32
+ * so tests can inject a mock without a real libp2p stack. Mirrors
33
+ * `CadreNodeLike` in `auth/trust-circle.ts`.
34
+ */
35
+ export interface CadreNodeLike {
36
+ /** Returns this node's peer ID (libp2p) as a string. */
37
+ getPeerId(): string;
38
+ /** Returns the current observed multiaddrs from libp2p. */
39
+ getMultiaddrs(): string[];
40
+ }
41
+
42
+ export interface NatServiceOptions {
43
+ /** Cadre-host root directory (same one orchestrator + trust-circle use). */
44
+ rootDir: string;
45
+ /** libp2p node — used for peer ID and the libp2p multiaddrs fallback. */
46
+ cadreNode: CadreNodeLike;
47
+ /** Clock override for tests. */
48
+ now?: () => Date;
49
+ /** Fetch override for tests. */
50
+ fetch?: typeof fetch;
51
+ /** Test-only: stub the keytar/file-store. Default: createSecretsStore. */
52
+ secretsStore?: SecretsStore;
53
+ /** Test-only: stub the port mapper. Default: createDefaultPortMapper(). */
54
+ portMapper?: PortMapper;
55
+ /** Test-only: stub the external-IP detector. */
56
+ externalIpDetector?: ExternalIpDetector;
57
+ /** Optional: re-use an existing NatStore (mostly for tests). */
58
+ store?: NatStore;
59
+ }
60
+
61
+ /**
62
+ * NatService — orchestrates port mapping, external-IP detection, DDNS updates,
63
+ * and address resolution for invites.
64
+ *
65
+ * Lifecycle:
66
+ * - `start()`: load settings, install port mapping (if upnpEnabled), detect
67
+ * external IP, kick off DDNS loop.
68
+ * - `stop()`: release port mapping, stop DDNS timer.
69
+ * - `getStatus()`: build a fresh status snapshot from internal state (cheap).
70
+ * - `testReachability()`: re-run the IP + verify cycle and the heuristic.
71
+ * - `getInviteAddresses()`: build the multiaddrs to embed in invites.
72
+ *
73
+ * NatService is library + lifecycle only. The long-running process that owns
74
+ * it is `cadre-host-local-ui` (see docs/cadre-host.md and the ticket header).
75
+ */
76
+ export class NatService {
77
+ private readonly cadreNode: CadreNodeLike;
78
+ private readonly store: NatStore;
79
+ private readonly nowFn: () => Date;
80
+ private readonly fetchImpl: typeof fetch;
81
+
82
+ // Injected or lazily-created.
83
+ private secretsStore: SecretsStore | null;
84
+ private portMapper: PortMapper | null;
85
+ /** Caller-supplied detector — used as-is when present (skips the auto router-probe stitch). */
86
+ private readonly injectedDetector: ExternalIpDetector | null;
87
+
88
+ // Built once start() completes.
89
+ private portService: PortMapperService | null = null;
90
+ private ddnsUpdater: DdnsUpdater | null = null;
91
+
92
+ // Runtime state.
93
+ private currentSettings: NatSettingsFile;
94
+ private latestIp: ExternalIpResult | null = null;
95
+ private lastTestedAt: Date | null = null;
96
+ private started = false;
97
+
98
+ // For createSecretsStore async init.
99
+ private readonly secretsRootDir: string;
100
+
101
+ constructor(opts: NatServiceOptions) {
102
+ this.cadreNode = opts.cadreNode;
103
+ this.store = opts.store ?? new NatStore(opts.rootDir);
104
+ this.nowFn = opts.now ?? (() => new Date());
105
+ this.fetchImpl = opts.fetch ?? fetch;
106
+ this.secretsStore = opts.secretsStore ?? null;
107
+ this.portMapper = opts.portMapper ?? null;
108
+ this.injectedDetector = opts.externalIpDetector ?? null;
109
+ this.secretsRootDir = opts.rootDir;
110
+ this.currentSettings = this.store.load();
111
+ }
112
+
113
+ /** Initial start: port mapping → IP detect → DDNS. Idempotent. */
114
+ async start(): Promise<void> {
115
+ if (this.started) return;
116
+ this.started = true;
117
+
118
+ // 1. Secrets store (lazy if not injected).
119
+ if (!this.secretsStore) {
120
+ this.secretsStore = await createSecretsStore(this.secretsRootDir);
121
+ }
122
+
123
+ // 2. Port mapping.
124
+ await this.startPortService();
125
+
126
+ // 3. External IP detection.
127
+ await this.detectIp();
128
+
129
+ // 4. DDNS updater.
130
+ this.ddnsUpdater = new DdnsUpdater({
131
+ settings: this.currentSettings.ddns,
132
+ secrets: this.secretsStore,
133
+ getExternalIp: () => this.latestIp?.publicIp ?? this.latestIp?.routerIp ?? null,
134
+ fetch: this.fetchImpl,
135
+ now: this.nowFn,
136
+ });
137
+ await this.ddnsUpdater.start();
138
+ }
139
+
140
+ /** Release the port mapping and clear timers. Idempotent. */
141
+ async stop(): Promise<void> {
142
+ if (!this.started) return;
143
+ this.started = false;
144
+ try {
145
+ this.ddnsUpdater?.stop();
146
+ } catch (err) {
147
+ log('ddns stop failed: %s', (err as Error).message);
148
+ }
149
+ this.ddnsUpdater = null;
150
+
151
+ try {
152
+ await this.portService?.stop();
153
+ } catch (err) {
154
+ log('port-service stop failed: %s', (err as Error).message);
155
+ }
156
+ this.portService = null;
157
+ }
158
+
159
+ /** Cheap read of the current snapshot. */
160
+ getStatus(): NatStatusSnapshot {
161
+ const portState = this.portService?.getState() ?? this.disabledPortState();
162
+ const externalIp = this.latestIp?.publicIp ?? this.latestIp?.routerIp ?? null;
163
+ const ddns: NatDdnsStatus = this.ddnsUpdater?.getStatus() ?? {
164
+ providerId: this.currentSettings.ddns.providerId,
165
+ hostname: this.currentSettings.ddns.hostname,
166
+ externallyManaged: this.currentSettings.ddns.externallyManaged,
167
+ lastUpdateAt: null,
168
+ lastUpdateOk: null,
169
+ lastError: null,
170
+ };
171
+
172
+ return {
173
+ portMode: this.currentSettings.upnpEnabled ? portState.mode : 'disabled',
174
+ externalPort: portState.externalPort,
175
+ internalPort: portState.internalPort,
176
+ routerExternalIp: portState.routerExternalIp,
177
+ mappingLeaseExpiresAt: portState.leaseExpiresAt?.toISOString() ?? null,
178
+ externalIp,
179
+ externalIpDetectedAt: this.latestIp?.detectedAt.toISOString() ?? null,
180
+ cgnatDetected: this.latestIp?.cgnat ?? false,
181
+ directReachability: evaluateReachability({
182
+ portMode: portState.mode,
183
+ cgnatDetected: this.latestIp?.cgnat ?? false,
184
+ }),
185
+ lastTestedAt: this.lastTestedAt?.toISOString() ?? null,
186
+ ddns,
187
+ };
188
+ }
189
+
190
+ /** Re-run the IP probe + port-mapper verify, then return a fresh snapshot. */
191
+ async testReachability(): Promise<NatStatusSnapshot> {
192
+ if (this.portService) {
193
+ await this.portService.refresh().catch((err) => log('refresh err: %s', (err as Error).message));
194
+ }
195
+ await this.detectIp();
196
+ this.lastTestedAt = this.nowFn();
197
+ // Best-effort DDNS push when the IP just changed.
198
+ if (this.ddnsUpdater) {
199
+ await this.ddnsUpdater.forceUpdate().catch((err) => log('ddns forceUpdate err: %s', (err as Error).message));
200
+ }
201
+ return this.getStatus();
202
+ }
203
+
204
+ /** Build the multiaddrs to embed in invites. */
205
+ async getInviteAddresses(): Promise<string[]> {
206
+ const peerId = this.cadreNode.getPeerId();
207
+ const status = this.getStatus();
208
+ const input: BuildInviteAddressesInput = {
209
+ peerId,
210
+ externalPort: status.externalPort,
211
+ ddnsHostname: status.ddns.hostname,
212
+ externalIp: status.externalIp,
213
+ reachable: status.directReachability === 'reachable',
214
+ libp2pAddrs: this.cadreNode.getMultiaddrs(),
215
+ };
216
+ return buildInviteAddresses(input);
217
+ }
218
+
219
+ /** Current settings (cheap read; for handlers to surface to UI). */
220
+ getSettings(): NatSettingsFile {
221
+ return this.currentSettings;
222
+ }
223
+
224
+ /** Replace settings; persists to disk and reconfigures the runtime. */
225
+ async putSettings(patch: Partial<Omit<NatSettingsFile, 'version'>>): Promise<NatStatusSnapshot> {
226
+ const next = this.store.update(patch);
227
+ const upnpChanged = next.upnpEnabled !== this.currentSettings.upnpEnabled;
228
+ const portChanged =
229
+ next.externalPort !== this.currentSettings.externalPort ||
230
+ next.internalPort !== this.currentSettings.internalPort;
231
+ const ddnsChanged =
232
+ next.ddns.providerId !== this.currentSettings.ddns.providerId ||
233
+ next.ddns.hostname !== this.currentSettings.ddns.hostname ||
234
+ next.ddns.externallyManaged !== this.currentSettings.ddns.externallyManaged ||
235
+ next.ddns.intervalMs !== this.currentSettings.ddns.intervalMs;
236
+ this.currentSettings = next;
237
+
238
+ if (this.started) {
239
+ if (upnpChanged || portChanged) {
240
+ try { await this.portService?.stop(); } catch { /* ignore */ }
241
+ this.portService = null;
242
+ await this.startPortService();
243
+ }
244
+ if (ddnsChanged && this.ddnsUpdater) {
245
+ await this.ddnsUpdater.updateSettings(next.ddns);
246
+ }
247
+ }
248
+ return this.getStatus();
249
+ }
250
+
251
+ /**
252
+ * Set DDNS configuration and persist secret values into the SecretsStore.
253
+ * Throws if the provider is unknown or required secrets are missing.
254
+ */
255
+ async putDdns(body: {
256
+ providerId: string;
257
+ hostname: string;
258
+ config: Record<string, string>;
259
+ externallyManaged?: boolean;
260
+ }): Promise<NatStatusSnapshot> {
261
+ if (!body || typeof body.providerId !== 'string' || typeof body.hostname !== 'string') {
262
+ throw new NatError('invalid_config', 'providerId and hostname are required');
263
+ }
264
+ const provider = getProvider(body.providerId);
265
+ if (!this.secretsStore) {
266
+ throw new NatError('secrets_unavailable', 'secrets store not initialised; call start() first');
267
+ }
268
+
269
+ // Persist secrets.
270
+ for (const field of provider.configFields) {
271
+ if (!field.secret) continue;
272
+ const value = body.config[field.key];
273
+ if (typeof value !== 'string' || value.length === 0) {
274
+ throw new NatError(
275
+ 'ddns_credentials_missing',
276
+ `Missing value for required secret field "${field.key}" of provider "${provider.id}"`,
277
+ );
278
+ }
279
+ await this.secretsStore.set(ddnsAccount(provider.id, field.key), value);
280
+ }
281
+
282
+ // Update nat.json.
283
+ const externallyManaged = body.externallyManaged ?? false;
284
+ return await this.putSettings({
285
+ ddns: {
286
+ providerId: provider.id,
287
+ hostname: body.hostname,
288
+ externallyManaged,
289
+ intervalMs: this.currentSettings.ddns.intervalMs,
290
+ },
291
+ });
292
+ }
293
+
294
+ /** List available DDNS providers (UI listing for configuration). */
295
+ listDdnsProviders(): DdnsProviderInfo[] {
296
+ return listProviders().map((p) => ({
297
+ id: p.id,
298
+ displayName: p.displayName,
299
+ configFields: p.configFields,
300
+ }));
301
+ }
302
+
303
+ // --- private ---
304
+
305
+ private async startPortService(): Promise<void> {
306
+ if (!this.currentSettings.upnpEnabled) {
307
+ log('UPnP disabled by settings; skipping port mapping');
308
+ return;
309
+ }
310
+ let mapper = this.portMapper;
311
+ if (!mapper) {
312
+ try {
313
+ mapper = await createDefaultPortMapper();
314
+ this.portMapper = mapper;
315
+ } catch (err) {
316
+ log('default port mapper unavailable: %s', (err as Error).message);
317
+ return;
318
+ }
319
+ }
320
+ this.portService = new PortMapperService({
321
+ mapper,
322
+ externalPort: this.currentSettings.externalPort,
323
+ internalPort: this.currentSettings.internalPort,
324
+ now: this.nowFn,
325
+ });
326
+ await this.portService.start();
327
+ }
328
+
329
+ private async detectIp(): Promise<void> {
330
+ // If the caller injected a detector (typically a test stub), use it as-is —
331
+ // don't second-guess them by stitching in the port mapper's router probe.
332
+ const detector = this.injectedDetector ?? (
333
+ this.portMapper
334
+ ? new ExternalIpDetector({
335
+ fetch: this.fetchImpl,
336
+ now: this.nowFn,
337
+ routerProbe: async () => this.portMapper!.externalIp(),
338
+ })
339
+ : new ExternalIpDetector({
340
+ fetch: this.fetchImpl,
341
+ now: this.nowFn,
342
+ })
343
+ );
344
+ try {
345
+ this.latestIp = await detector.detect();
346
+ } catch (err) {
347
+ log('detectIp failed: %s', (err as Error).message);
348
+ }
349
+ }
350
+
351
+ private disabledPortState(): PortMapperState {
352
+ return {
353
+ mode: this.currentSettings.upnpEnabled ? 'failed' : 'disabled',
354
+ externalPort: this.currentSettings.externalPort,
355
+ internalPort: this.currentSettings.internalPort,
356
+ routerExternalIp: null,
357
+ leaseExpiresAt: null,
358
+ lastError: null,
359
+ };
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Wrap a NatService into the typed handler shape consumed by
365
+ * `cadre-host-local-ui`. Mirrors `createTrustCircleHandlers`.
366
+ */
367
+ export function createNatHandlers(service: NatService): NatHandlers {
368
+ return {
369
+ async getStatus() { return service.getStatus(); },
370
+ async testReachability() { return await service.testReachability(); },
371
+ async listDdnsProviders() { return service.listDdnsProviders(); },
372
+ async putDdns(body) { return await service.putDdns(body); },
373
+ async putSettings(body) { return await service.putSettings(body); },
374
+ };
375
+ }
@@ -0,0 +1,154 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import debug from 'debug';
4
+
5
+ import { NatError, type NatDdnsSettings, type NatSettingsFile } from './types.js';
6
+
7
+ const log = debug('cadre:host:nat-store');
8
+
9
+ const FILE_VERSION = 1;
10
+
11
+ /** Default port (libp2p TCP default). */
12
+ const DEFAULT_PORT = 4001;
13
+
14
+ /** Default DDNS update interval (5 minutes). */
15
+ const DEFAULT_DDNS_INTERVAL_MS = 5 * 60 * 1000;
16
+
17
+ /**
18
+ * Atomic JSON store for `nat.json`. Mirrors `TrustCircleStore` — write to
19
+ * `<path>.tmp`, then rename.
20
+ *
21
+ * Concurrency assumption: only one cadre-host process owns a given rootDir.
22
+ */
23
+ export class NatStore {
24
+ private readonly path: string;
25
+ private cache: NatSettingsFile | null = null;
26
+
27
+ constructor(rootDir: string) {
28
+ mkdirSync(rootDir, { recursive: true });
29
+ this.path = join(rootDir, 'nat.json');
30
+ }
31
+
32
+ filePath(): string {
33
+ return this.path;
34
+ }
35
+
36
+ /** Load (with caching). A missing file returns defaults. */
37
+ load(): NatSettingsFile {
38
+ if (this.cache) return this.cache;
39
+ if (!existsSync(this.path)) {
40
+ this.cache = defaultSettings();
41
+ return this.cache;
42
+ }
43
+ let raw: string;
44
+ try {
45
+ raw = readFileSync(this.path, 'utf8');
46
+ } catch (err) {
47
+ throw new NatError(
48
+ 'storage_error',
49
+ `failed to read nat file at ${this.path}: ${(err as Error).message}`,
50
+ );
51
+ }
52
+ let parsed: unknown;
53
+ try {
54
+ parsed = JSON.parse(raw);
55
+ } catch (err) {
56
+ throw new NatError(
57
+ 'storage_error',
58
+ `nat file at ${this.path} is not valid JSON: ${(err as Error).message}`,
59
+ );
60
+ }
61
+ if (!isNatSettingsFile(parsed)) {
62
+ throw new NatError(
63
+ 'storage_error',
64
+ `nat file at ${this.path} has unexpected shape`,
65
+ );
66
+ }
67
+ this.cache = parsed;
68
+ return this.cache;
69
+ }
70
+
71
+ /** Persist current settings atomically. */
72
+ save(state: NatSettingsFile): void {
73
+ mkdirSync(dirname(this.path), { recursive: true });
74
+ const next: NatSettingsFile = { ...state, version: FILE_VERSION };
75
+ const payload = JSON.stringify(next, null, 2);
76
+ const tmp = `${this.path}.tmp`;
77
+ writeFileSync(tmp, payload, { encoding: 'utf8' });
78
+ renameSync(tmp, this.path);
79
+ this.cache = next;
80
+ log('saved nat.json (port=%d, ddns=%s) to %s',
81
+ next.externalPort,
82
+ next.ddns.providerId ?? '(none)',
83
+ this.path);
84
+ }
85
+
86
+ /** Patch and persist (validation lives here). */
87
+ update(patch: Partial<Omit<NatSettingsFile, 'version'>>): NatSettingsFile {
88
+ const current = this.load();
89
+ const merged: NatSettingsFile = {
90
+ ...current,
91
+ ...patch,
92
+ ddns: { ...current.ddns, ...(patch.ddns ?? {}) },
93
+ version: FILE_VERSION,
94
+ };
95
+ validate(merged);
96
+ this.save(merged);
97
+ return merged;
98
+ }
99
+ }
100
+
101
+ function defaultSettings(): NatSettingsFile {
102
+ return {
103
+ version: FILE_VERSION,
104
+ externalPort: DEFAULT_PORT,
105
+ internalPort: DEFAULT_PORT,
106
+ upnpEnabled: true,
107
+ ddns: defaultDdns(),
108
+ };
109
+ }
110
+
111
+ function defaultDdns(): NatDdnsSettings {
112
+ return {
113
+ providerId: null,
114
+ hostname: null,
115
+ externallyManaged: false,
116
+ intervalMs: DEFAULT_DDNS_INTERVAL_MS,
117
+ };
118
+ }
119
+
120
+ function isNatSettingsFile(v: unknown): v is NatSettingsFile {
121
+ if (!v || typeof v !== 'object') return false;
122
+ const obj = v as Record<string, unknown>;
123
+ if (obj.version !== FILE_VERSION) return false;
124
+ if (typeof obj.externalPort !== 'number' || typeof obj.internalPort !== 'number') return false;
125
+ if (typeof obj.upnpEnabled !== 'boolean') return false;
126
+ const ddns = obj.ddns as Record<string, unknown> | undefined;
127
+ if (!ddns || typeof ddns !== 'object') return false;
128
+ if (ddns.providerId !== null && typeof ddns.providerId !== 'string') return false;
129
+ if (ddns.hostname !== null && typeof ddns.hostname !== 'string') return false;
130
+ if (typeof ddns.externallyManaged !== 'boolean') return false;
131
+ if (typeof ddns.intervalMs !== 'number') return false;
132
+ return true;
133
+ }
134
+
135
+ function validate(s: NatSettingsFile): void {
136
+ if (!Number.isInteger(s.externalPort) || s.externalPort < 1 || s.externalPort > 65535) {
137
+ throw new NatError('invalid_config', `externalPort must be 1-65535, got ${s.externalPort}`);
138
+ }
139
+ if (!Number.isInteger(s.internalPort) || s.internalPort < 1 || s.internalPort > 65535) {
140
+ throw new NatError('invalid_config', `internalPort must be 1-65535, got ${s.internalPort}`);
141
+ }
142
+ if (!Number.isFinite(s.ddns.intervalMs) || s.ddns.intervalMs < 1000) {
143
+ throw new NatError(
144
+ 'invalid_config',
145
+ `ddns.intervalMs must be >= 1000ms, got ${s.ddns.intervalMs}`,
146
+ );
147
+ }
148
+ if (s.ddns.providerId !== null && s.ddns.providerId.length === 0) {
149
+ throw new NatError('invalid_config', 'ddns.providerId must be a non-empty string or null');
150
+ }
151
+ if (s.ddns.hostname !== null && s.ddns.hostname.length === 0) {
152
+ throw new NatError('invalid_config', 'ddns.hostname must be a non-empty string or null');
153
+ }
154
+ }