@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,243 @@
1
+ import debug from 'debug';
2
+
3
+ import type { SecretsStore } from '../secrets/index.js';
4
+ import { ddnsAccount } from '../secrets/index.js';
5
+ import { NatError, type NatDdnsStatus, type NatDdnsSettings } from '../types.js';
6
+ import type { DdnsProvider } from './index.js';
7
+ import { getProvider } from './index.js';
8
+
9
+ const log = debug('cadre:host:nat-ddns:updater');
10
+
11
+ /** Outcome of a single DDNS update attempt. */
12
+ export interface DdnsUpdateOutcome {
13
+ attempted: boolean;
14
+ ok: boolean;
15
+ ip: string | null;
16
+ error: string | null;
17
+ at: Date;
18
+ }
19
+
20
+ export interface DdnsUpdaterOptions {
21
+ /** Current DDNS settings (provider, hostname, externally-managed flag). */
22
+ settings: NatDdnsSettings;
23
+ /** Backing credential store. */
24
+ secrets: SecretsStore;
25
+ /** Returns the most recently observed external IP (null when unknown). */
26
+ getExternalIp: () => string | null;
27
+ /** Fetch override for tests. */
28
+ fetch?: typeof fetch;
29
+ /** Provider resolver override (tests can inject fakes). */
30
+ resolveProvider?: (providerId: string) => DdnsProvider;
31
+ /** Clock override for tests. */
32
+ now?: () => Date;
33
+ /** Timer overrides for tests. */
34
+ setInterval?: (fn: () => void, ms: number) => NodeJS.Timeout;
35
+ clearInterval?: (h: NodeJS.Timeout) => void;
36
+ }
37
+
38
+ /**
39
+ * DDNS update loop.
40
+ *
41
+ * Lifecycle:
42
+ * - `start()`: if a provider is configured AND not externally managed, runs
43
+ * an immediate update, then schedules `setInterval(intervalMs)`.
44
+ * - On each tick: re-evaluates the IP. If unchanged from the last successful
45
+ * update, no provider call. If changed, calls `provider.update`. Errors
46
+ * are recorded but the timer keeps ticking.
47
+ * - `stop()`: clears the timer. Idempotent.
48
+ * - `updateSettings(...)`: swap in new settings, re-starting if needed.
49
+ * - `forceUpdate()`: bypass the unchanged-IP check (used by `testReachability`).
50
+ */
51
+ export class DdnsUpdater {
52
+ private settings: NatDdnsSettings;
53
+ private readonly secrets: SecretsStore;
54
+ private readonly getExternalIp: () => string | null;
55
+ private readonly fetchImpl: typeof fetch;
56
+ private readonly resolveProvider: (providerId: string) => DdnsProvider;
57
+ private readonly nowFn: () => Date;
58
+ private readonly setIntervalFn: (fn: () => void, ms: number) => NodeJS.Timeout;
59
+ private readonly clearIntervalFn: (h: NodeJS.Timeout) => void;
60
+
61
+ private timer: NodeJS.Timeout | null = null;
62
+ private lastPushedIp: string | null = null;
63
+ private lastOutcome: DdnsUpdateOutcome | null = null;
64
+ private started = false;
65
+
66
+ constructor(opts: DdnsUpdaterOptions) {
67
+ this.settings = opts.settings;
68
+ this.secrets = opts.secrets;
69
+ this.getExternalIp = opts.getExternalIp;
70
+ this.fetchImpl = opts.fetch ?? fetch;
71
+ this.resolveProvider = opts.resolveProvider ?? getProvider;
72
+ this.nowFn = opts.now ?? (() => new Date());
73
+ this.setIntervalFn = opts.setInterval ?? ((fn, ms) => setInterval(fn, ms));
74
+ this.clearIntervalFn = opts.clearInterval ?? ((h) => clearInterval(h));
75
+ }
76
+
77
+ /** Current status (for the NatService snapshot). */
78
+ getStatus(): NatDdnsStatus {
79
+ return {
80
+ providerId: this.settings.providerId,
81
+ hostname: this.settings.hostname,
82
+ externallyManaged: this.settings.externallyManaged,
83
+ lastUpdateAt: this.lastOutcome?.at.toISOString() ?? null,
84
+ lastUpdateOk: this.lastOutcome?.ok ?? null,
85
+ lastError: this.lastOutcome?.error ?? null,
86
+ };
87
+ }
88
+
89
+ async start(): Promise<DdnsUpdateOutcome> {
90
+ if (this.started) {
91
+ return this.lastOutcome ?? notAttempted(this.nowFn());
92
+ }
93
+ this.started = true;
94
+
95
+ if (!this.shouldUpdate()) {
96
+ const outcome = notAttempted(this.nowFn());
97
+ // For an externally-managed entry we still report state, but never push.
98
+ return outcome;
99
+ }
100
+
101
+ const outcome = await this.runOnce();
102
+ this.scheduleNext();
103
+ return outcome;
104
+ }
105
+
106
+ stop(): void {
107
+ if (!this.started) return;
108
+ this.started = false;
109
+ if (this.timer) {
110
+ this.clearIntervalFn(this.timer);
111
+ this.timer = null;
112
+ }
113
+ }
114
+
115
+ /** Replace settings; restart the loop with the new configuration. */
116
+ async updateSettings(next: NatDdnsSettings): Promise<DdnsUpdateOutcome> {
117
+ const wasRunning = this.started;
118
+ this.stop();
119
+ this.settings = next;
120
+ this.lastPushedIp = null;
121
+ if (!wasRunning) return this.lastOutcome ?? notAttempted(this.nowFn());
122
+ return await this.start();
123
+ }
124
+
125
+ /** Force an immediate update, bypassing the unchanged-IP skip. */
126
+ async forceUpdate(): Promise<DdnsUpdateOutcome> {
127
+ if (!this.shouldUpdate()) return notAttempted(this.nowFn());
128
+ this.lastPushedIp = null;
129
+ return await this.runOnce();
130
+ }
131
+
132
+ private shouldUpdate(): boolean {
133
+ if (!this.settings.providerId) return false;
134
+ if (!this.settings.hostname) return false;
135
+ if (this.settings.externallyManaged) return false;
136
+ return true;
137
+ }
138
+
139
+ private scheduleNext(): void {
140
+ if (this.timer) this.clearIntervalFn(this.timer);
141
+ this.timer = this.setIntervalFn(() => {
142
+ void this.runOnce().catch((err) => log('updater tick error: %s', (err as Error).message));
143
+ }, this.settings.intervalMs);
144
+ }
145
+
146
+ private async runOnce(): Promise<DdnsUpdateOutcome> {
147
+ const ip = this.getExternalIp();
148
+ if (!ip) {
149
+ const outcome: DdnsUpdateOutcome = {
150
+ attempted: false,
151
+ ok: false,
152
+ ip: null,
153
+ error: 'external IP unknown',
154
+ at: this.nowFn(),
155
+ };
156
+ this.lastOutcome = outcome;
157
+ return outcome;
158
+ }
159
+
160
+ if (ip === this.lastPushedIp) {
161
+ // Unchanged: no provider call (per DuckDNS guidance: don't re-push).
162
+ log('DDNS skip: IP unchanged (%s)', ip);
163
+ return this.lastOutcome ?? notAttempted(this.nowFn());
164
+ }
165
+
166
+ let provider: DdnsProvider;
167
+ try {
168
+ provider = this.resolveProvider(this.settings.providerId!);
169
+ } catch (err) {
170
+ const outcome: DdnsUpdateOutcome = {
171
+ attempted: true,
172
+ ok: false,
173
+ ip,
174
+ error: (err as Error).message,
175
+ at: this.nowFn(),
176
+ };
177
+ this.lastOutcome = outcome;
178
+ return outcome;
179
+ }
180
+
181
+ let config: Record<string, string>;
182
+ try {
183
+ config = await this.loadConfig(provider);
184
+ } catch (err) {
185
+ const outcome: DdnsUpdateOutcome = {
186
+ attempted: true,
187
+ ok: false,
188
+ ip,
189
+ error: (err as Error).message,
190
+ at: this.nowFn(),
191
+ };
192
+ this.lastOutcome = outcome;
193
+ return outcome;
194
+ }
195
+
196
+ try {
197
+ await provider.update(config, this.settings.hostname!, ip, { fetch: this.fetchImpl });
198
+ this.lastPushedIp = ip;
199
+ const outcome: DdnsUpdateOutcome = {
200
+ attempted: true,
201
+ ok: true,
202
+ ip,
203
+ error: null,
204
+ at: this.nowFn(),
205
+ };
206
+ this.lastOutcome = outcome;
207
+ log('DDNS update OK: %s → %s', this.settings.hostname, ip);
208
+ return outcome;
209
+ } catch (err) {
210
+ const outcome: DdnsUpdateOutcome = {
211
+ attempted: true,
212
+ ok: false,
213
+ ip,
214
+ error: (err as Error).message,
215
+ at: this.nowFn(),
216
+ };
217
+ this.lastOutcome = outcome;
218
+ log('DDNS update FAIL: %s', outcome.error);
219
+ return outcome;
220
+ }
221
+ }
222
+
223
+ private async loadConfig(provider: DdnsProvider): Promise<Record<string, string>> {
224
+ const result: Record<string, string> = {};
225
+ for (const field of provider.configFields) {
226
+ if (!field.secret) continue;
227
+ const value = await this.secrets.get(ddnsAccount(provider.id, field.key));
228
+ if (value === null) {
229
+ throw new NatError(
230
+ 'ddns_credentials_missing',
231
+ `Missing DDNS credential for provider "${provider.id}", field "${field.key}". ` +
232
+ `Configure with \`cadre-host nat ddns set ${provider.id}\`.`,
233
+ );
234
+ }
235
+ result[field.key] = value;
236
+ }
237
+ return result;
238
+ }
239
+ }
240
+
241
+ function notAttempted(at: Date): DdnsUpdateOutcome {
242
+ return { attempted: false, ok: false, ip: null, error: null, at };
243
+ }
@@ -0,0 +1,154 @@
1
+ import debug from 'debug';
2
+
3
+ const log = debug('cadre:host:nat-external-ip');
4
+
5
+ /** Result of an external-IP detection cycle. */
6
+ export interface ExternalIpResult {
7
+ /** IP reported by the upstream router (UPnP/NAT-PMP gateway), if reachable. */
8
+ routerIp: string | null;
9
+ /** IP reported by a public IP echo service. */
10
+ publicIp: string | null;
11
+ /**
12
+ * True when both probes succeeded AND returned different addresses, which
13
+ * is the textbook CGNAT signature: the router thinks its WAN address is
14
+ * private to the carrier.
15
+ */
16
+ cgnat: boolean;
17
+ /** When this snapshot was taken. */
18
+ detectedAt: Date;
19
+ }
20
+
21
+ /** Abstract router-side probe (gateway WAN address). */
22
+ export type RouterIpProbe = () => Promise<string | null>;
23
+
24
+ /** Public IP echo endpoints. Tried in order; first success wins. */
25
+ const DEFAULT_PUBLIC_IP_URLS: ReadonlyArray<string> = [
26
+ 'https://api.ipify.org',
27
+ 'https://ifconfig.me/ip',
28
+ 'https://icanhazip.com',
29
+ ];
30
+
31
+ export interface ExternalIpDetectorOptions {
32
+ /** Probe the local router's external IP (typically via the port mapper). */
33
+ routerProbe?: RouterIpProbe;
34
+ /** Public IP service endpoints. */
35
+ publicIpUrls?: ReadonlyArray<string>;
36
+ /** Fetch override (tests stub this). Defaults to global fetch. */
37
+ fetch?: typeof fetch;
38
+ /** Clock override for tests. */
39
+ now?: () => Date;
40
+ /** Per-request timeout in ms (default 5000). */
41
+ requestTimeoutMs?: number;
42
+ }
43
+
44
+ /**
45
+ * External-IP detector.
46
+ *
47
+ * Two independent sources:
48
+ * - The router (queried via the port mapper's gateway interface). May be
49
+ * unavailable if UPnP is off or the upstream device doesn't expose
50
+ * WANIPConnection.
51
+ * - A public HTTPS echo service (api.ipify.org and friends). May be
52
+ * unreachable on a firewalled / offline machine.
53
+ *
54
+ * When both succeed AND disagree, we flag CGNAT. The check is heuristic — a
55
+ * fast-changing IP, a sliced VPN, or an IPv6-only public probe could all
56
+ * trigger a false positive. The verdict is informational, not enforced.
57
+ */
58
+ export class ExternalIpDetector {
59
+ private readonly routerProbe: RouterIpProbe | undefined;
60
+ private readonly publicIpUrls: ReadonlyArray<string>;
61
+ private readonly fetchImpl: typeof fetch;
62
+ private readonly nowFn: () => Date;
63
+ private readonly requestTimeoutMs: number;
64
+
65
+ constructor(opts: ExternalIpDetectorOptions = {}) {
66
+ this.routerProbe = opts.routerProbe;
67
+ this.publicIpUrls = opts.publicIpUrls ?? DEFAULT_PUBLIC_IP_URLS;
68
+ this.fetchImpl = opts.fetch ?? fetch;
69
+ this.nowFn = opts.now ?? (() => new Date());
70
+ this.requestTimeoutMs = opts.requestTimeoutMs ?? 5_000;
71
+ }
72
+
73
+ /** Run both probes in parallel and return the snapshot. */
74
+ async detect(): Promise<ExternalIpResult> {
75
+ const [routerIp, publicIp] = await Promise.all([
76
+ this.runRouterProbe(),
77
+ this.runPublicProbe(),
78
+ ]);
79
+
80
+ const cgnat = routerIp !== null && publicIp !== null && routerIp !== publicIp;
81
+ if (cgnat) {
82
+ log('CGNAT detected: routerIp=%s, publicIp=%s', routerIp, publicIp);
83
+ }
84
+
85
+ return {
86
+ routerIp,
87
+ publicIp,
88
+ cgnat,
89
+ detectedAt: this.nowFn(),
90
+ };
91
+ }
92
+
93
+ private async runRouterProbe(): Promise<string | null> {
94
+ if (!this.routerProbe) return null;
95
+ try {
96
+ const ip = await this.routerProbe();
97
+ return ip && isPlausibleIp(ip) ? ip : null;
98
+ } catch (err) {
99
+ log('routerProbe failed: %s', (err as Error).message);
100
+ return null;
101
+ }
102
+ }
103
+
104
+ private async runPublicProbe(): Promise<string | null> {
105
+ for (const url of this.publicIpUrls) {
106
+ const ip = await this.tryPublicUrl(url);
107
+ if (ip) return ip;
108
+ }
109
+ return null;
110
+ }
111
+
112
+ private async tryPublicUrl(url: string): Promise<string | null> {
113
+ const controller = new AbortController();
114
+ const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs);
115
+ try {
116
+ const res = await this.fetchImpl(url, { signal: controller.signal });
117
+ if (!res.ok) {
118
+ log('public IP probe %s returned %d', url, res.status);
119
+ return null;
120
+ }
121
+ const text = (await res.text()).trim();
122
+ if (!isPlausibleIp(text)) {
123
+ log('public IP probe %s returned non-IP: %s', url, text.slice(0, 64));
124
+ return null;
125
+ }
126
+ return text;
127
+ } catch (err) {
128
+ log('public IP probe %s failed: %s', url, (err as Error).message);
129
+ return null;
130
+ } finally {
131
+ clearTimeout(timer);
132
+ }
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Liberal IP validation — accepts both IPv4 and IPv6 in dotted/colon form.
138
+ * Tighter validation lives at the consumer (`nat-service` checks for IPv4
139
+ * before building an `/ip4/` multiaddr).
140
+ */
141
+ export function isPlausibleIp(s: string): boolean {
142
+ if (!s || s.length > 45) return false;
143
+ // IPv4: 4 dotted octets, 0-255 each.
144
+ const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(s);
145
+ if (v4) {
146
+ return v4.slice(1).every((octet) => {
147
+ const n = Number(octet);
148
+ return n >= 0 && n <= 255;
149
+ });
150
+ }
151
+ // IPv6: very liberal — at least two colons, only hex/colon characters.
152
+ if (/^[0-9a-fA-F:]+$/.test(s) && s.split(':').length >= 3) return true;
153
+ return false;
154
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * NAT / DDNS substrate for cadre-host.
3
+ *
4
+ * See ./nat-service.ts for the top-level orchestrator and `docs/cadre-host.md`
5
+ * for integration notes (the long-running process owner is `cadre-host-local-ui`).
6
+ */
7
+
8
+ export { NatService, createNatHandlers } from './nat-service.js';
9
+ export type { NatServiceOptions, CadreNodeLike } from './nat-service.js';
10
+ export { NatStore } from './nat-store.js';
11
+ export {
12
+ NatError,
13
+ } from './types.js';
14
+ export type {
15
+ NatStatusSnapshot,
16
+ NatDdnsStatus,
17
+ NatSettingsFile,
18
+ NatDdnsSettings,
19
+ NatHandlers,
20
+ NatErrorCode,
21
+ PortForwardMode,
22
+ DirectReachability,
23
+ DdnsProviderInfo,
24
+ DdnsConfigField,
25
+ } from './types.js';
26
+ export {
27
+ ExternalIpDetector,
28
+ isPlausibleIp,
29
+ } from './external-ip.js';
30
+ export type {
31
+ ExternalIpResult,
32
+ RouterIpProbe,
33
+ ExternalIpDetectorOptions,
34
+ } from './external-ip.js';
35
+ export {
36
+ PortMapperService,
37
+ createDefaultPortMapper,
38
+ DEFAULT_LEASE_TTL_MS,
39
+ DEFAULT_REFRESH_MS,
40
+ } from './port-mapper.js';
41
+ export type {
42
+ PortMapper,
43
+ PortMappingResult,
44
+ PortMapOptions,
45
+ PortMapperState,
46
+ PortMapperServiceOptions,
47
+ } from './port-mapper.js';
48
+ export { evaluateReachability } from './reachability.js';
49
+ export { buildInviteAddresses } from './address-resolver.js';
50
+ export type { BuildInviteAddressesInput } from './address-resolver.js';
51
+ export {
52
+ BUILTIN_PROVIDERS,
53
+ getProvider,
54
+ listProviders,
55
+ duckDnsProvider,
56
+ DdnsUpdater,
57
+ } from './ddns/index.js';
58
+ export type {
59
+ DdnsProvider,
60
+ DdnsProviderDeps,
61
+ DdnsUpdaterOptions,
62
+ DdnsUpdateOutcome,
63
+ } from './ddns/index.js';
64
+ export {
65
+ KeytarSecretsStore,
66
+ FileSecretsStore,
67
+ createSecretsStore,
68
+ ddnsAccount,
69
+ KEYTAR_SERVICE,
70
+ } from './secrets/index.js';
71
+ export type { SecretsStore, KeytarLike } from './secrets/index.js';