@serfab/cadre-host 1.13.0 → 1.14.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 (337) hide show
  1. package/README.md +332 -423
  2. package/dist/bin/host.d.ts +6 -3
  3. package/dist/bin/host.js +301 -505
  4. package/dist/bin/host.js.map +1 -1
  5. package/dist/bin/join-output.d.ts +56 -0
  6. package/dist/bin/join-output.js +92 -0
  7. package/dist/bin/join-output.js.map +1 -0
  8. package/dist/bin/nat-output.d.ts +49 -0
  9. package/dist/bin/nat-output.js +127 -0
  10. package/dist/bin/nat-output.js.map +1 -0
  11. package/dist/hosted/claim-details.d.ts +44 -0
  12. package/dist/hosted/claim-details.js +66 -0
  13. package/dist/hosted/claim-details.js.map +1 -0
  14. package/dist/hosted/hosted-node-service.d.ts +318 -0
  15. package/dist/hosted/hosted-node-service.js +666 -0
  16. package/dist/hosted/hosted-node-service.js.map +1 -0
  17. package/dist/hosted/hosted-node-store.d.ts +40 -0
  18. package/dist/hosted/hosted-node-store.js +126 -0
  19. package/dist/hosted/hosted-node-store.js.map +1 -0
  20. package/dist/{donation/donation-supervisor.d.ts → hosted/hosted-node-supervisor.d.ts} +70 -53
  21. package/dist/hosted/hosted-node-supervisor.js +396 -0
  22. package/dist/hosted/hosted-node-supervisor.js.map +1 -0
  23. package/dist/hosted/hosted-node-watcher.d.ts +83 -0
  24. package/dist/hosted/hosted-node-watcher.js +224 -0
  25. package/dist/hosted/hosted-node-watcher.js.map +1 -0
  26. package/dist/hosted/index.d.ts +16 -0
  27. package/dist/hosted/index.js +13 -0
  28. package/dist/hosted/index.js.map +1 -0
  29. package/dist/hosted/node-status.d.ts +35 -0
  30. package/dist/hosted/node-status.js +61 -0
  31. package/dist/hosted/node-status.js.map +1 -0
  32. package/dist/hosted/types.d.ts +134 -0
  33. package/dist/hosted/types.js +22 -0
  34. package/dist/hosted/types.js.map +1 -0
  35. package/dist/index.d.ts +12 -24
  36. package/dist/index.js +9 -19
  37. package/dist/index.js.map +1 -1
  38. package/dist/installer/config.d.ts +4 -34
  39. package/dist/installer/config.js +3 -18
  40. package/dist/installer/config.js.map +1 -1
  41. package/dist/installer/index.d.ts +7 -19
  42. package/dist/installer/index.js +14 -69
  43. package/dist/installer/index.js.map +1 -1
  44. package/dist/installer/paths.d.ts +0 -2
  45. package/dist/installer/paths.js +0 -4
  46. package/dist/installer/paths.js.map +1 -1
  47. package/dist/installer/wizard.d.ts +0 -7
  48. package/dist/installer/wizard.js +1 -8
  49. package/dist/installer/wizard.js.map +1 -1
  50. package/dist/nat/address-resolver.d.ts +18 -17
  51. package/dist/nat/address-resolver.js +79 -25
  52. package/dist/nat/address-resolver.js.map +1 -1
  53. package/dist/nat/address-watch.d.ts +37 -0
  54. package/dist/nat/address-watch.js +84 -0
  55. package/dist/nat/address-watch.js.map +1 -0
  56. package/dist/nat/ddns/duckdns.d.ts +2 -1
  57. package/dist/nat/ddns/duckdns.js +5 -1
  58. package/dist/nat/ddns/duckdns.js.map +1 -1
  59. package/dist/nat/ddns/index.d.ts +6 -0
  60. package/dist/nat/ddns/index.js.map +1 -1
  61. package/dist/nat/index.d.ts +12 -9
  62. package/dist/nat/index.js +6 -5
  63. package/dist/nat/index.js.map +1 -1
  64. package/dist/nat/nat-service.d.ts +203 -77
  65. package/dist/nat/nat-service.js +602 -237
  66. package/dist/nat/nat-service.js.map +1 -1
  67. package/dist/nat/nat-store.d.ts +12 -5
  68. package/dist/nat/nat-store.js +114 -30
  69. package/dist/nat/nat-store.js.map +1 -1
  70. package/dist/nat/port-mapper.d.ts +83 -79
  71. package/dist/nat/port-mapper.js +148 -189
  72. package/dist/nat/port-mapper.js.map +1 -1
  73. package/dist/nat/reachability.d.ts +31 -15
  74. package/dist/nat/reachability.js +97 -22
  75. package/dist/nat/reachability.js.map +1 -1
  76. package/dist/nat/types.d.ts +78 -27
  77. package/dist/nat/types.js +8 -5
  78. package/dist/nat/types.js.map +1 -1
  79. package/dist/orchestrator/host-process-orchestrator.d.ts +29 -71
  80. package/dist/orchestrator/host-process-orchestrator.js +78 -218
  81. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  82. package/dist/{installer/identity.d.ts → orchestrator/identity-file.d.ts} +5 -5
  83. package/dist/{installer/identity.js → orchestrator/identity-file.js} +6 -6
  84. package/dist/orchestrator/identity-file.js.map +1 -0
  85. package/dist/orchestrator/index.d.ts +2 -3
  86. package/dist/orchestrator/index.js +1 -1
  87. package/dist/orchestrator/index.js.map +1 -1
  88. package/dist/orchestrator/node-identity.d.ts +6 -6
  89. package/dist/orchestrator/node-identity.js +7 -7
  90. package/dist/orchestrator/node-identity.js.map +1 -1
  91. package/dist/orchestrator/port-allocator.d.ts +5 -6
  92. package/dist/orchestrator/port-allocator.js +9 -11
  93. package/dist/orchestrator/port-allocator.js.map +1 -1
  94. package/dist/orchestrator/state-store.d.ts +3 -5
  95. package/dist/orchestrator/state-store.js +2 -10
  96. package/dist/orchestrator/state-store.js.map +1 -1
  97. package/dist/orchestrator/types.d.ts +33 -22
  98. package/dist/orchestrator/types.js.map +1 -1
  99. package/dist/server/error-handler.d.ts +5 -25
  100. package/dist/server/error-handler.js +11 -74
  101. package/dist/server/error-handler.js.map +1 -1
  102. package/dist/server/events/types.d.ts +7 -11
  103. package/dist/server/events/types.js +2 -1
  104. package/dist/server/events/types.js.map +1 -1
  105. package/dist/server/index.d.ts +11 -37
  106. package/dist/server/index.js +30 -48
  107. package/dist/server/index.js.map +1 -1
  108. package/dist/server/routes/hosted-nodes.d.ts +28 -0
  109. package/dist/server/routes/hosted-nodes.js +68 -0
  110. package/dist/server/routes/hosted-nodes.js.map +1 -0
  111. package/dist/server/routes/nat.d.ts +4 -1
  112. package/dist/server/routes/nat.js +13 -2
  113. package/dist/server/routes/nat.js.map +1 -1
  114. package/dist/server/routes/nodes.d.ts +6 -20
  115. package/dist/server/routes/nodes.js +7 -86
  116. package/dist/server/routes/nodes.js.map +1 -1
  117. package/dist/server/routes/settings.d.ts +2 -7
  118. package/dist/server/routes/settings.js +3 -7
  119. package/dist/server/routes/settings.js.map +1 -1
  120. package/dist/server/routes/status.d.ts +2 -25
  121. package/dist/server/routes/status.js +1 -11
  122. package/dist/server/routes/status.js.map +1 -1
  123. package/dist/server/server.js +8 -8
  124. package/dist/server/settings-store.d.ts +2 -2
  125. package/dist/server/settings-store.js +2 -2
  126. package/dist/server/static.js +1 -2
  127. package/dist/server/static.js.map +1 -1
  128. package/dist/ui/assets/index-4FWuU8ye.js +19 -0
  129. package/dist/ui/assets/index-4FWuU8ye.js.map +1 -0
  130. package/dist/ui/assets/index-Di9Q4d01.css +1 -0
  131. package/dist/ui/index.html +2 -2
  132. package/dist/update/index.d.ts +2 -2
  133. package/dist/update/index.js +2 -2
  134. package/dist/update/store.d.ts +1 -1
  135. package/dist/update/store.js +1 -1
  136. package/dist/update/types.d.ts +1 -1
  137. package/dist/update/types.js +1 -1
  138. package/package.json +5 -6
  139. package/src/__tests__/cli-nat.smoke.test.ts +219 -212
  140. package/src/__tests__/cli.smoke.test.ts +1 -1
  141. package/src/__tests__/global-setup.ts +2 -3
  142. package/src/__tests__/orchestrator-claim-secret.test.ts +112 -0
  143. package/src/__tests__/orchestrator-handle-contract.ts +134 -134
  144. package/src/__tests__/orchestrator-node-identity.test.ts +182 -203
  145. package/src/__tests__/orchestrator-ports.test.ts +124 -143
  146. package/src/__tests__/orchestrator-push.test.ts +138 -146
  147. package/src/__tests__/orchestrator.test.ts +1019 -1063
  148. package/src/bin/host.ts +368 -553
  149. package/src/bin/join-output.ts +120 -0
  150. package/src/bin/nat-output.ts +177 -0
  151. package/src/{donation → hosted}/__tests__/fake-orchestrator.test.ts +173 -173
  152. package/src/{donation → hosted}/__tests__/fake-orchestrator.ts +265 -243
  153. package/src/hosted/__tests__/hosted-node-service.test.ts +609 -0
  154. package/src/hosted/__tests__/hosted-node-supervisor.test.ts +474 -0
  155. package/src/hosted/__tests__/test-invitation.ts +33 -0
  156. package/src/hosted/claim-details.ts +96 -0
  157. package/src/hosted/hosted-node-service.ts +795 -0
  158. package/src/hosted/hosted-node-store.ts +144 -0
  159. package/src/hosted/hosted-node-supervisor.ts +439 -0
  160. package/src/hosted/hosted-node-watcher.ts +250 -0
  161. package/src/hosted/index.ts +53 -0
  162. package/src/hosted/node-status.ts +71 -0
  163. package/src/hosted/types.ts +153 -0
  164. package/src/index.ts +72 -91
  165. package/src/installer/__tests__/config.test.ts +15 -40
  166. package/src/installer/__tests__/installer.smoke.test.ts +5 -86
  167. package/src/installer/__tests__/wizard.test.ts +56 -64
  168. package/src/installer/config.ts +135 -175
  169. package/src/installer/index.ts +15 -83
  170. package/src/installer/paths.ts +104 -109
  171. package/src/installer/wizard.ts +87 -103
  172. package/src/nat/__tests__/address-resolver.test.ts +107 -82
  173. package/src/nat/__tests__/nat-service.test.ts +433 -408
  174. package/src/nat/__tests__/nat-store.test.ts +127 -93
  175. package/src/nat/__tests__/port-mapper.test.ts +30 -191
  176. package/src/nat/__tests__/reachability.test.ts +96 -13
  177. package/src/nat/address-resolver.ts +94 -52
  178. package/src/nat/address-watch.ts +92 -0
  179. package/src/nat/ddns/duckdns.ts +5 -1
  180. package/src/nat/ddns/index.ts +6 -0
  181. package/src/nat/index.ts +87 -71
  182. package/src/nat/nat-service.ts +889 -501
  183. package/src/nat/nat-store.ts +237 -154
  184. package/src/nat/port-mapper.ts +241 -329
  185. package/src/nat/reachability.ts +134 -25
  186. package/src/nat/types.ts +209 -159
  187. package/src/{installer/__tests__/identity.test.ts → orchestrator/__tests__/identity-file.test.ts} +34 -34
  188. package/src/orchestrator/__tests__/node-identity.test.ts +62 -62
  189. package/src/orchestrator/host-process-orchestrator.ts +81 -243
  190. package/src/{installer/identity.ts → orchestrator/identity-file.ts} +56 -56
  191. package/src/orchestrator/index.ts +9 -10
  192. package/src/orchestrator/node-identity.ts +41 -41
  193. package/src/orchestrator/port-allocator.ts +71 -73
  194. package/src/orchestrator/state-store.ts +76 -90
  195. package/src/orchestrator/types.ts +34 -23
  196. package/src/server/__tests__/bus.test.ts +38 -38
  197. package/src/server/__tests__/error-handler.test.ts +81 -118
  198. package/src/server/__tests__/fakes.ts +40 -44
  199. package/src/server/__tests__/hosted-nodes-route.test.ts +160 -0
  200. package/src/server/__tests__/nodes-route.test.ts +114 -283
  201. package/src/server/__tests__/publishers.test.ts +193 -180
  202. package/src/server/__tests__/server.smoke.test.ts +134 -223
  203. package/src/server/__tests__/settings-route.test.ts +179 -195
  204. package/src/server/__tests__/sse-route.test.ts +119 -119
  205. package/src/server/__tests__/status-route.test.ts +82 -121
  206. package/src/server/error-handler.ts +112 -178
  207. package/src/server/events/types.ts +20 -24
  208. package/src/server/index.ts +223 -267
  209. package/src/server/routes/hosted-nodes.ts +83 -0
  210. package/src/server/routes/nat.ts +75 -63
  211. package/src/server/routes/nodes.ts +96 -188
  212. package/src/server/routes/settings.ts +115 -123
  213. package/src/server/routes/status.ts +102 -134
  214. package/src/server/server.ts +8 -8
  215. package/src/server/settings-store.ts +2 -2
  216. package/src/server/static.ts +1 -2
  217. package/src/update/index.ts +2 -2
  218. package/src/update/store.ts +1 -1
  219. package/src/update/types.ts +1 -1
  220. package/dist/auth/duration.d.ts +0 -1
  221. package/dist/auth/duration.js +0 -32
  222. package/dist/auth/duration.js.map +0 -1
  223. package/dist/auth/index.d.ts +0 -11
  224. package/dist/auth/index.js +0 -9
  225. package/dist/auth/index.js.map +0 -1
  226. package/dist/auth/self-label.d.ts +0 -36
  227. package/dist/auth/self-label.js +0 -57
  228. package/dist/auth/self-label.js.map +0 -1
  229. package/dist/auth/trust-circle-store.d.ts +0 -26
  230. package/dist/auth/trust-circle-store.js +0 -129
  231. package/dist/auth/trust-circle-store.js.map +0 -1
  232. package/dist/auth/trust-circle.d.ts +0 -156
  233. package/dist/auth/trust-circle.js +0 -307
  234. package/dist/auth/trust-circle.js.map +0 -1
  235. package/dist/auth/types.d.ts +0 -84
  236. package/dist/auth/types.js +0 -24
  237. package/dist/auth/types.js.map +0 -1
  238. package/dist/donation/donation-service.d.ts +0 -389
  239. package/dist/donation/donation-service.js +0 -828
  240. package/dist/donation/donation-service.js.map +0 -1
  241. package/dist/donation/donation-store.d.ts +0 -51
  242. package/dist/donation/donation-store.js +0 -152
  243. package/dist/donation/donation-store.js.map +0 -1
  244. package/dist/donation/donation-supervisor.js +0 -364
  245. package/dist/donation/donation-supervisor.js.map +0 -1
  246. package/dist/donation/grant-service.d.ts +0 -80
  247. package/dist/donation/grant-service.js +0 -210
  248. package/dist/donation/grant-service.js.map +0 -1
  249. package/dist/donation/grant-store.d.ts +0 -38
  250. package/dist/donation/grant-store.js +0 -135
  251. package/dist/donation/grant-store.js.map +0 -1
  252. package/dist/donation/index.d.ts +0 -20
  253. package/dist/donation/index.js +0 -17
  254. package/dist/donation/index.js.map +0 -1
  255. package/dist/donation/types.d.ts +0 -224
  256. package/dist/donation/types.js +0 -40
  257. package/dist/donation/types.js.map +0 -1
  258. package/dist/installer/identity.js.map +0 -1
  259. package/dist/owner/index.d.ts +0 -11
  260. package/dist/owner/index.js +0 -11
  261. package/dist/owner/index.js.map +0 -1
  262. package/dist/owner/owner-node-client.d.ts +0 -110
  263. package/dist/owner/owner-node-client.js +0 -184
  264. package/dist/owner/owner-node-client.js.map +0 -1
  265. package/dist/server/routes/bootstrap-node-validation.d.ts +0 -115
  266. package/dist/server/routes/bootstrap-node-validation.js +0 -197
  267. package/dist/server/routes/bootstrap-node-validation.js.map +0 -1
  268. package/dist/server/routes/grants-admin.d.ts +0 -29
  269. package/dist/server/routes/grants-admin.js +0 -58
  270. package/dist/server/routes/grants-admin.js.map +0 -1
  271. package/dist/server/routes/grants.d.ts +0 -28
  272. package/dist/server/routes/grants.js +0 -165
  273. package/dist/server/routes/grants.js.map +0 -1
  274. package/dist/server/routes/provision-request-validation.d.ts +0 -45
  275. package/dist/server/routes/provision-request-validation.js +0 -97
  276. package/dist/server/routes/provision-request-validation.js.map +0 -1
  277. package/dist/server/routes/strands.d.ts +0 -20
  278. package/dist/server/routes/strands.js +0 -38
  279. package/dist/server/routes/strands.js.map +0 -1
  280. package/dist/server/routes/trust-circle.d.ts +0 -17
  281. package/dist/server/routes/trust-circle.js +0 -35
  282. package/dist/server/routes/trust-circle.js.map +0 -1
  283. package/dist/strands/index.d.ts +0 -7
  284. package/dist/strands/index.js +0 -6
  285. package/dist/strands/index.js.map +0 -1
  286. package/dist/strands/strand-service.d.ts +0 -50
  287. package/dist/strands/strand-service.js +0 -103
  288. package/dist/strands/strand-service.js.map +0 -1
  289. package/dist/strands/types.d.ts +0 -93
  290. package/dist/strands/types.js +0 -23
  291. package/dist/strands/types.js.map +0 -1
  292. package/dist/ui/assets/index-C6nELNfC.js +0 -23
  293. package/dist/ui/assets/index-C6nELNfC.js.map +0 -1
  294. package/dist/ui/assets/index-TtIYSeZO.css +0 -1
  295. package/src/__tests__/cli-invite.smoke.test.ts +0 -192
  296. package/src/__tests__/host-owner.smoke.test.ts +0 -123
  297. package/src/__tests__/orchestrator-owner.test.ts +0 -234
  298. package/src/__tests__/orchestrator-pin-keys.test.ts +0 -152
  299. package/src/auth/__tests__/duration.test.ts +0 -28
  300. package/src/auth/__tests__/self-label.test.ts +0 -85
  301. package/src/auth/__tests__/trust-circle-integration.test.ts +0 -152
  302. package/src/auth/__tests__/trust-circle-store.test.ts +0 -115
  303. package/src/auth/__tests__/trust-circle.test.ts +0 -445
  304. package/src/auth/duration.ts +0 -33
  305. package/src/auth/index.ts +0 -21
  306. package/src/auth/self-label.ts +0 -74
  307. package/src/auth/trust-circle-store.ts +0 -155
  308. package/src/auth/trust-circle.ts +0 -395
  309. package/src/auth/types.ts +0 -99
  310. package/src/donation/__tests__/donation-service.test.ts +0 -1193
  311. package/src/donation/__tests__/donation-supervisor.test.ts +0 -548
  312. package/src/donation/__tests__/grant-service.test.ts +0 -213
  313. package/src/donation/__tests__/grant-store.test.ts +0 -113
  314. package/src/donation/donation-service.ts +0 -1033
  315. package/src/donation/donation-store.ts +0 -176
  316. package/src/donation/donation-supervisor.ts +0 -411
  317. package/src/donation/grant-service.ts +0 -252
  318. package/src/donation/grant-store.ts +0 -152
  319. package/src/donation/index.ts +0 -65
  320. package/src/donation/types.ts +0 -260
  321. package/src/owner/__tests__/owner-node-client.test.ts +0 -194
  322. package/src/owner/index.ts +0 -12
  323. package/src/owner/owner-node-client.ts +0 -259
  324. package/src/server/__tests__/bootstrap-node-validation.test.ts +0 -138
  325. package/src/server/__tests__/grants-admin-route.test.ts +0 -171
  326. package/src/server/__tests__/grants-route.test.ts +0 -394
  327. package/src/server/__tests__/strands-route.test.ts +0 -234
  328. package/src/server/routes/bootstrap-node-validation.ts +0 -206
  329. package/src/server/routes/grants-admin.ts +0 -74
  330. package/src/server/routes/grants.ts +0 -193
  331. package/src/server/routes/provision-request-validation.ts +0 -105
  332. package/src/server/routes/strands.ts +0 -54
  333. package/src/server/routes/trust-circle.ts +0 -49
  334. package/src/strands/__tests__/strand-service.test.ts +0 -165
  335. package/src/strands/index.ts +0 -14
  336. package/src/strands/strand-service.ts +0 -135
  337. package/src/strands/types.ts +0 -102
@@ -1,501 +1,889 @@
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
- import { OwnerNodeUnavailableError } from '../owner/owner-node-client.js';
28
-
29
- const log = debug('cadre:host:nat-service');
30
-
31
- /** Sleep helper for the initial-push retry loop; unref'd so it never holds the process open. */
32
- function sleep(ms: number): Promise<void> {
33
- return new Promise((res) => {
34
- const t = setTimeout(res, ms);
35
- if (typeof t.unref === 'function') t.unref();
36
- });
37
- }
38
-
39
- /**
40
- * Minimal slice of CadreNode that NatService needs — defined as an interface
41
- * so tests can inject a mock without a real libp2p stack. Mirrors
42
- * `CadreNodeLike` in `auth/trust-circle.ts`.
43
- *
44
- * Both methods are async: in production they round-trip over the owner
45
- * node's loopback admin channel (`GET /admin/identity`, `GET /admin/multiaddrs`).
46
- * Synchronous test mocks can return a value directly (it's awaited).
47
- */
48
- export interface CadreNodeLike {
49
- /** Returns this node's peer ID (libp2p) as a string. */
50
- getPeerId(): Promise<string> | string;
51
- /** Returns the current observed multiaddrs from libp2p. */
52
- getMultiaddrs(): Promise<string[]> | string[];
53
- }
54
-
55
- /** Listener notified when the invite addresses may have changed. */
56
- export type AddressesChangedListener = (addresses: string[]) => void | Promise<void>;
57
-
58
- export interface NatServiceOptions {
59
- /** Cadre-host root directory (same one orchestrator + trust-circle use). */
60
- rootDir: string;
61
- /** libp2p node — used for peer ID and the libp2p multiaddrs fallback. */
62
- cadreNode: CadreNodeLike;
63
- /** Clock override for tests. */
64
- now?: () => Date;
65
- /** Fetch override for tests. */
66
- fetch?: typeof fetch;
67
- /** Test-only: stub the keytar/file-store. Default: createSecretsStore. */
68
- secretsStore?: SecretsStore;
69
- /** Test-only: stub the port mapper. Default: createDefaultPortMapper(). */
70
- portMapper?: PortMapper;
71
- /** Test-only: stub the external-IP detector. */
72
- externalIpDetector?: ExternalIpDetector;
73
- /** Optional: re-use an existing NatStore (mostly for tests). */
74
- store?: NatStore;
75
- /** Initial-push retry: poll interval while the node is not-yet-ready. Default 250ms. */
76
- initialPushRetryMs?: number;
77
- /** Initial-push retry: total budget before giving up (best-effort). Default 15000ms. */
78
- initialPushTimeoutMs?: number;
79
- }
80
-
81
- /**
82
- * NatService — orchestrates port mapping, external-IP detection, DDNS updates,
83
- * and address resolution for invites.
84
- *
85
- * Lifecycle:
86
- * - `start()`: load settings, install port mapping (if upnpEnabled), detect
87
- * external IP, kick off DDNS loop.
88
- * - `stop()`: release port mapping, stop DDNS timer.
89
- * - `getStatus()`: build a fresh status snapshot from internal state (cheap).
90
- * - `testReachability()`: re-run the IP + verify cycle and the heuristic.
91
- * - `getInviteAddresses()`: build the multiaddrs to embed in invites.
92
- *
93
- * NatService is library + lifecycle only. The long-running process that owns
94
- * it is `cadre-host-local-ui` (see docs/cadre-host.md and the ticket header).
95
- */
96
- export class NatService {
97
- private readonly cadreNode: CadreNodeLike;
98
- private readonly store: NatStore;
99
- private readonly nowFn: () => Date;
100
- private readonly fetchImpl: typeof fetch;
101
-
102
- // Injected or lazily-created.
103
- private secretsStore: SecretsStore | null;
104
- private portMapper: PortMapper | null;
105
- /** Caller-supplied detector — used as-is when present (skips the auto router-probe stitch). */
106
- private readonly injectedDetector: ExternalIpDetector | null;
107
-
108
- // Built once start() completes.
109
- private portService: PortMapperService | null = null;
110
- private ddnsUpdater: DdnsUpdater | null = null;
111
-
112
- // Runtime state.
113
- private currentSettings: NatSettingsFile;
114
- private latestIp: ExternalIpResult | null = null;
115
- private lastTestedAt: Date | null = null;
116
- private started = false;
117
- /** Listeners notified when the invite addresses may have changed. */
118
- private readonly addressListeners = new Set<AddressesChangedListener>();
119
-
120
- // For createSecretsStore async init.
121
- private readonly secretsRootDir: string;
122
-
123
- // Initial invite-address push retry tunables (injectable so tests run fast).
124
- private readonly initialPushRetryMs: number;
125
- private readonly initialPushTimeoutMs: number;
126
-
127
- constructor(opts: NatServiceOptions) {
128
- this.cadreNode = opts.cadreNode;
129
- this.store = opts.store ?? new NatStore(opts.rootDir);
130
- this.nowFn = opts.now ?? (() => new Date());
131
- this.fetchImpl = opts.fetch ?? fetch;
132
- this.secretsStore = opts.secretsStore ?? null;
133
- this.portMapper = opts.portMapper ?? null;
134
- this.injectedDetector = opts.externalIpDetector ?? null;
135
- this.secretsRootDir = opts.rootDir;
136
- this.initialPushRetryMs = opts.initialPushRetryMs ?? 250;
137
- this.initialPushTimeoutMs = opts.initialPushTimeoutMs ?? 15_000;
138
- this.currentSettings = this.store.load();
139
- }
140
-
141
- /** Initial start: port mapping → IP detect → DDNS. Idempotent. */
142
- async start(): Promise<void> {
143
- if (this.started) return;
144
- this.started = true;
145
-
146
- // 1. Secrets store (lazy if not injected).
147
- if (!this.secretsStore) {
148
- this.secretsStore = await createSecretsStore(this.secretsRootDir);
149
- }
150
-
151
- // 2. Port mapping.
152
- await this.startPortService();
153
-
154
- // 3. External IP detection.
155
- await this.detectIp();
156
-
157
- // 4. DDNS updater.
158
- this.ddnsUpdater = new DdnsUpdater({
159
- settings: this.currentSettings.ddns,
160
- secrets: this.secretsStore,
161
- getExternalIp: () => this.latestIp?.publicIp ?? this.latestIp?.routerIp ?? null,
162
- fetch: this.fetchImpl,
163
- now: this.nowFn,
164
- });
165
- await this.ddnsUpdater.start();
166
-
167
- // Initial invite-address push. Retries on `node_unavailable` until the
168
- // freshly spawned owner node accepts it (bounded; best-effort after).
169
- await this.pushInitialAddresses();
170
- }
171
-
172
- /** Release the port mapping and clear timers. Idempotent. */
173
- async stop(): Promise<void> {
174
- if (!this.started) return;
175
- this.started = false;
176
- try {
177
- this.ddnsUpdater?.stop();
178
- } catch (err) {
179
- log('ddns stop failed: %s', (err as Error).message);
180
- }
181
- this.ddnsUpdater = null;
182
-
183
- try {
184
- await this.portService?.stop();
185
- } catch (err) {
186
- log('port-service stop failed: %s', (err as Error).message);
187
- }
188
- this.portService = null;
189
- }
190
-
191
- /** Cheap read of the current snapshot. */
192
- getStatus(): NatStatusSnapshot {
193
- const portState = this.portService?.getState() ?? this.disabledPortState();
194
- const externalIp = this.latestIp?.publicIp ?? this.latestIp?.routerIp ?? null;
195
- const ddns: NatDdnsStatus = this.ddnsUpdater?.getStatus() ?? {
196
- providerId: this.currentSettings.ddns.providerId,
197
- hostname: this.currentSettings.ddns.hostname,
198
- externallyManaged: this.currentSettings.ddns.externallyManaged,
199
- lastUpdateAt: null,
200
- lastUpdateOk: null,
201
- lastError: null,
202
- };
203
-
204
- return {
205
- portMode: this.currentSettings.upnpEnabled ? portState.mode : 'disabled',
206
- externalPort: portState.externalPort,
207
- internalPort: portState.internalPort,
208
- routerExternalIp: portState.routerExternalIp,
209
- mappingLeaseExpiresAt: portState.leaseExpiresAt?.toISOString() ?? null,
210
- externalIp,
211
- externalIpDetectedAt: this.latestIp?.detectedAt.toISOString() ?? null,
212
- cgnatDetected: this.latestIp?.cgnat ?? false,
213
- directReachability: evaluateReachability({
214
- portMode: portState.mode,
215
- cgnatDetected: this.latestIp?.cgnat ?? false,
216
- }),
217
- lastTestedAt: this.lastTestedAt?.toISOString() ?? null,
218
- ddns,
219
- };
220
- }
221
-
222
- /** Re-run the IP probe + port-mapper verify, then return a fresh snapshot. */
223
- async testReachability(): Promise<NatStatusSnapshot> {
224
- if (this.portService) {
225
- await this.portService.refresh().catch((err) => log('refresh err: %s', (err as Error).message));
226
- }
227
- await this.detectIp();
228
- this.lastTestedAt = this.nowFn();
229
- // Best-effort DDNS push when the IP just changed.
230
- if (this.ddnsUpdater) {
231
- await this.ddnsUpdater.forceUpdate().catch((err) => log('ddns forceUpdate err: %s', (err as Error).message));
232
- }
233
- // Reachability/IP may have changed → invite addresses may have changed.
234
- await this.fireAddressesChanged();
235
- return this.getStatus();
236
- }
237
-
238
- /**
239
- * Build the multiaddrs to embed in invites. The peer ID and libp2p
240
- * fallback addresses are fetched over the owner node's admin channel; a
241
- * node-unavailable failure surfaces as `NatError('node_unavailable')`.
242
- */
243
- async getInviteAddresses(): Promise<string[]> {
244
- let peerId: string;
245
- let libp2pAddrs: string[];
246
- try {
247
- peerId = await this.cadreNode.getPeerId();
248
- libp2pAddrs = await this.cadreNode.getMultiaddrs();
249
- } catch (err) {
250
- if (err instanceof OwnerNodeUnavailableError) {
251
- throw new NatError('node_unavailable', `Owner node unavailable: ${err.message}`);
252
- }
253
- throw err;
254
- }
255
- // A reachable node that hasn't yet established its libp2p peer ID reports
256
- // an empty peerId. Building addresses now would mint malformed `…/p2p/`
257
- // suffixes (and push them to the node), so treat it as not-ready.
258
- if (!peerId) {
259
- throw new NatError('node_unavailable', 'Owner node has no peer ID yet (not ready)');
260
- }
261
- const status = this.getStatus();
262
- const input: BuildInviteAddressesInput = {
263
- peerId,
264
- externalPort: status.externalPort,
265
- ddnsHostname: status.ddns.hostname,
266
- externalIp: status.externalIp,
267
- reachable: status.directReachability === 'reachable',
268
- libp2pAddrs,
269
- };
270
- return buildInviteAddresses(input);
271
- }
272
-
273
- /**
274
- * Register a listener fired when the invite addresses may have changed
275
- * (after `start`, `putSettings`, and `testReachability`). `cadre-host start`
276
- * wires this to `OwnerNodeClient.pushInviteAddresses`. Returns an
277
- * unsubscribe fn.
278
- */
279
- onAddressesChanged(listener: AddressesChangedListener): () => void {
280
- this.addressListeners.add(listener);
281
- return () => { this.addressListeners.delete(listener); };
282
- }
283
-
284
- /**
285
- * Recompute invite addresses and notify listeners. Best-effort: when the
286
- * owner node is unreachable (or the build fails), the notification is
287
- * skipped — the push is retried on the next NAT event.
288
- */
289
- private async fireAddressesChanged(): Promise<void> {
290
- if (this.addressListeners.size === 0) return;
291
- let addresses: string[];
292
- try {
293
- addresses = await this.getInviteAddresses();
294
- } catch (err) {
295
- log('onAddressesChanged skipped: %s', (err as Error).message);
296
- return;
297
- }
298
- await this.notifyAddressListeners(addresses);
299
- }
300
-
301
- /** Deliver an address set to every registered listener (errors are logged, not thrown). */
302
- private async notifyAddressListeners(addresses: string[]): Promise<void> {
303
- for (const listener of this.addressListeners) {
304
- try {
305
- await listener(addresses);
306
- } catch (err) {
307
- log('address listener threw: %s', (err as Error).message);
308
- }
309
- }
310
- }
311
-
312
- /**
313
- * Initial invite-address push. The owner node's admin channel is a freshly
314
- * spawned detached child that may not be bound yet (and may not have a libp2p
315
- * peer ID yet), so a single attempt races readiness and silently drops the first
316
- * NAT-resolved address set. Retry on `node_unavailable` until the node accepts it
317
- * or the bounded budget elapses (best-effort thereafter). Awaited by start() so
318
- * the management API — the invite-minting path — does not come up first.
319
- */
320
- private async pushInitialAddresses(): Promise<void> {
321
- if (this.addressListeners.size === 0) return;
322
- const deadline = this.nowFn().getTime() + this.initialPushTimeoutMs;
323
- for (;;) {
324
- if (!this.started) return; // stop() ran during a retry
325
- try {
326
- const addresses = await this.getInviteAddresses();
327
- await this.notifyAddressListeners(addresses);
328
- return;
329
- } catch (err) {
330
- const code = err instanceof NatError ? err.code : undefined;
331
- // Only retry transient not-ready; surface anything unexpected via log + give up.
332
- if (code !== 'node_unavailable' || this.nowFn().getTime() >= deadline) {
333
- log('initial invite-address push not delivered: %s', (err as Error).message);
334
- return;
335
- }
336
- await sleep(this.initialPushRetryMs);
337
- }
338
- }
339
- }
340
-
341
- /** Current settings (cheap read; for handlers to surface to UI). */
342
- getSettings(): NatSettingsFile {
343
- return this.currentSettings;
344
- }
345
-
346
- /** Replace settings; persists to disk and reconfigures the runtime. */
347
- async putSettings(patch: Partial<Omit<NatSettingsFile, 'version'>>): Promise<NatStatusSnapshot> {
348
- const next = this.store.update(patch);
349
- const upnpChanged = next.upnpEnabled !== this.currentSettings.upnpEnabled;
350
- const portChanged =
351
- next.externalPort !== this.currentSettings.externalPort ||
352
- next.internalPort !== this.currentSettings.internalPort;
353
- const ddnsChanged =
354
- next.ddns.providerId !== this.currentSettings.ddns.providerId ||
355
- next.ddns.hostname !== this.currentSettings.ddns.hostname ||
356
- next.ddns.externallyManaged !== this.currentSettings.ddns.externallyManaged ||
357
- next.ddns.intervalMs !== this.currentSettings.ddns.intervalMs;
358
- this.currentSettings = next;
359
-
360
- if (this.started) {
361
- if (upnpChanged || portChanged) {
362
- try { await this.portService?.stop(); } catch { /* ignore */ }
363
- this.portService = null;
364
- await this.startPortService();
365
- }
366
- if (ddnsChanged && this.ddnsUpdater) {
367
- await this.ddnsUpdater.updateSettings(next.ddns);
368
- }
369
- if (upnpChanged || portChanged || ddnsChanged) {
370
- // Port / DDNS changes alter the advertised invite addresses.
371
- await this.fireAddressesChanged();
372
- }
373
- }
374
- return this.getStatus();
375
- }
376
-
377
- /**
378
- * Set DDNS configuration and persist secret values into the SecretsStore.
379
- * Throws if the provider is unknown or required secrets are missing.
380
- */
381
- async putDdns(body: {
382
- providerId: string;
383
- hostname: string;
384
- config: Record<string, string>;
385
- externallyManaged?: boolean;
386
- }): Promise<NatStatusSnapshot> {
387
- if (!body || typeof body.providerId !== 'string' || typeof body.hostname !== 'string') {
388
- throw new NatError('invalid_config', 'providerId and hostname are required');
389
- }
390
- const provider = getProvider(body.providerId);
391
- if (!this.secretsStore) {
392
- throw new NatError('secrets_unavailable', 'secrets store not initialised; call start() first');
393
- }
394
-
395
- // Persist secrets.
396
- for (const field of provider.configFields) {
397
- if (!field.secret) continue;
398
- const value = body.config[field.key];
399
- if (typeof value !== 'string' || value.length === 0) {
400
- throw new NatError(
401
- 'ddns_credentials_missing',
402
- `Missing value for required secret field "${field.key}" of provider "${provider.id}"`,
403
- );
404
- }
405
- await this.secretsStore.set(ddnsAccount(provider.id, field.key), value);
406
- }
407
-
408
- // Update nat.json.
409
- const externallyManaged = body.externallyManaged ?? false;
410
- return await this.putSettings({
411
- ddns: {
412
- providerId: provider.id,
413
- hostname: body.hostname,
414
- externallyManaged,
415
- intervalMs: this.currentSettings.ddns.intervalMs,
416
- },
417
- });
418
- }
419
-
420
- /** List available DDNS providers (UI listing for configuration). */
421
- listDdnsProviders(): DdnsProviderInfo[] {
422
- return listProviders().map((p) => ({
423
- id: p.id,
424
- displayName: p.displayName,
425
- configFields: p.configFields,
426
- }));
427
- }
428
-
429
- // --- private ---
430
-
431
- private async startPortService(): Promise<void> {
432
- if (!this.currentSettings.upnpEnabled) {
433
- log('UPnP disabled by settings; skipping port mapping');
434
- return;
435
- }
436
- let mapper = this.portMapper;
437
- if (!mapper) {
438
- try {
439
- mapper = await createDefaultPortMapper();
440
- this.portMapper = mapper;
441
- } catch (err) {
442
- log('default port mapper unavailable: %s', (err as Error).message);
443
- return;
444
- }
445
- }
446
- this.portService = new PortMapperService({
447
- mapper,
448
- externalPort: this.currentSettings.externalPort,
449
- internalPort: this.currentSettings.internalPort,
450
- now: this.nowFn,
451
- });
452
- await this.portService.start();
453
- }
454
-
455
- private async detectIp(): Promise<void> {
456
- // If the caller injected a detector (typically a test stub), use it as-is —
457
- // don't second-guess them by stitching in the port mapper's router probe.
458
- const detector = this.injectedDetector ?? (
459
- this.portMapper
460
- ? new ExternalIpDetector({
461
- fetch: this.fetchImpl,
462
- now: this.nowFn,
463
- routerProbe: async () => this.portMapper!.externalIp(),
464
- })
465
- : new ExternalIpDetector({
466
- fetch: this.fetchImpl,
467
- now: this.nowFn,
468
- })
469
- );
470
- try {
471
- this.latestIp = await detector.detect();
472
- } catch (err) {
473
- log('detectIp failed: %s', (err as Error).message);
474
- }
475
- }
476
-
477
- private disabledPortState(): PortMapperState {
478
- return {
479
- mode: this.currentSettings.upnpEnabled ? 'failed' : 'disabled',
480
- externalPort: this.currentSettings.externalPort,
481
- internalPort: this.currentSettings.internalPort,
482
- routerExternalIp: null,
483
- leaseExpiresAt: null,
484
- lastError: null,
485
- };
486
- }
487
- }
488
-
489
- /**
490
- * Wrap a NatService into the typed handler shape consumed by
491
- * `cadre-host-local-ui`. Mirrors `createTrustCircleHandlers`.
492
- */
493
- export function createNatHandlers(service: NatService): NatHandlers {
494
- return {
495
- async getStatus() { return service.getStatus(); },
496
- async testReachability() { return await service.testReachability(); },
497
- async listDdnsProviders() { return service.listDdnsProviders(); },
498
- async putDdns(body) { return await service.putDdns(body); },
499
- async putSettings(body) { return await service.putSettings(body); },
500
- };
501
- }
1
+ import debug from 'debug';
2
+
3
+ import {
4
+ NatError,
5
+ type DdnsProviderInfo,
6
+ type ManualForwardPatch,
7
+ type NatDdnsStatus,
8
+ type NatGatewayStatus,
9
+ type NatHandlers,
10
+ type NatSettingsFile,
11
+ type NatStatusSnapshot,
12
+ type NodeReachability,
13
+ type PortKind,
14
+ type PortRoute,
15
+ } from './types.js';
16
+ import { NatStore } from './nat-store.js';
17
+ import { ExternalIpDetector, type ExternalIpResult } from './external-ip.js';
18
+ import {
19
+ DEFAULT_LEASE_TTL_MS,
20
+ DEFAULT_REFRESH_MS,
21
+ GATEWAY_DISCOVERY_TIMEOUT_MS,
22
+ UpnpPortMapper,
23
+ type PortMapper,
24
+ } from './port-mapper.js';
25
+ import { evaluateHostReachability, evaluateNodeReachability } from './reachability.js';
26
+ import { DdnsUpdater } from './ddns/updater.js';
27
+ import { getProvider, listProviders } from './ddns/index.js';
28
+ import { buildPublicAddresses, isPublicIpv4 } from './address-resolver.js';
29
+ import { createSecretsStore, ddnsAccount, type SecretsStore } from './secrets/index.js';
30
+ import { AddressWatch, type NodeAddressesStaleListener } from './address-watch.js';
31
+ import type { ManagedNodeInfo, NodeStateListener } from '../orchestrator/types.js';
32
+
33
+ const log = debug('cadre:host:nat-service');
34
+
35
+ /**
36
+ * How long a node may sit `stopped` before its mappings are released. Longer
37
+ * than the hosted-node supervisor's whole respawn backoff (150 s), so a crash
38
+ * followed by a respawn keeps its mapping.
39
+ */
40
+ export const NAT_UNMAP_GRACE_MS = 3 * 60_000;
41
+
42
+ /** The backstop reconcile cadence; state-change events trigger passes between ticks. */
43
+ export const NAT_RECONCILE_INTERVAL_MS = 60_000;
44
+
45
+ /**
46
+ * How often the external IP is re-detected, and how often gateway discovery is
47
+ * retried while UPnP is on and no router has answered.
48
+ */
49
+ export const NAT_IP_REDETECT_INTERVAL_MS = 5 * 60_000;
50
+
51
+ /**
52
+ * The orchestrator surface the service needs: the node list and cadre-host's
53
+ * own state-change subscription. `HostProcessOrchestrator` satisfies this; the
54
+ * hosted-node supervisor declares the same slice.
55
+ */
56
+ export interface NatNodeSource {
57
+ listNodes(): ManagedNodeInfo[];
58
+ onStateChange(listener: NodeStateListener): () => void;
59
+ }
60
+
61
+ /** Listener notified when the status snapshot changed in a way the UI should follow. */
62
+ export type NatChangeListener = (snapshot: NatStatusSnapshot) => void;
63
+
64
+ export interface NatServiceOptions {
65
+ /** Cadre-host root directory (same one the orchestrator and the hosted-node store use). */
66
+ rootDir: string;
67
+ /** Where the hosted nodes and their ports come from. */
68
+ nodeSource: NatNodeSource;
69
+ /** Clock override for tests. */
70
+ now?: () => Date;
71
+ /** Fetch override for tests. */
72
+ fetch?: typeof fetch;
73
+ /** Test-only: stub the keytar/file-store. Default: createSecretsStore. */
74
+ secretsStore?: SecretsStore;
75
+ /** Test-only: stub the router. Default: `UpnpPortMapper`. */
76
+ portMapper?: PortMapper;
77
+ /** Test-only: stub the external-IP detector. */
78
+ externalIpDetector?: ExternalIpDetector;
79
+ /** Optional: re-use an existing NatStore (mostly for tests). */
80
+ store?: NatStore;
81
+ /** Lease TTL asked of the router. Default 1 h. */
82
+ leaseTtlMs?: number;
83
+ }
84
+
85
+ /** A node's two mapped ports — `tcp` is `NodePorts.p2p`, `ws` is `NodePorts.ws`. */
86
+ interface NodePortPair {
87
+ tcp: number;
88
+ /** Null for a handle persisted by an older build without a WebSocket port. */
89
+ ws: number | null;
90
+ }
91
+
92
+ /** One row of the mapping table. */
93
+ interface NodeEntry {
94
+ nodeId: string;
95
+ running: boolean;
96
+ /** When the node was first seen stopped (ms since epoch); null while running. */
97
+ stoppedSince: number | null;
98
+ ports: NodePortPair;
99
+ routes: { tcp: PortRoute; ws: PortRoute | null };
100
+ }
101
+
102
+ const PORT_KINDS: ReadonlyArray<PortKind> = ['tcp', 'ws'];
103
+
104
+ function noRoute(internalPort: number): PortRoute {
105
+ return { internalPort, externalPort: null, source: null, leaseExpiresAt: null, error: null };
106
+ }
107
+
108
+ function manualRoute(internalPort: number, externalPort: number): PortRoute {
109
+ return { internalPort, externalPort, source: 'manual', leaseExpiresAt: null, error: null };
110
+ }
111
+
112
+ function portsOf(ports: { p2p: number; ws?: number }): NodePortPair {
113
+ // A handle read back from an older `state.json` lacks `ws` whatever the type says.
114
+ const ws = typeof ports.ws === 'number' ? ports.ws : null;
115
+ return { tcp: ports.p2p, ws };
116
+ }
117
+
118
+ function samePorts(a: NodePortPair, b: NodePortPair): boolean {
119
+ return a.tcp === b.tcp && a.ws === b.ws;
120
+ }
121
+
122
+ function errorMessage(err: unknown): string {
123
+ return err instanceof Error ? err.message : String(err);
124
+ }
125
+
126
+ /**
127
+ * NatService — one mapping table for every node the host runs, keyed by node
128
+ * id, with a route per port (TCP and WebSocket); external-IP detection; DDNS;
129
+ * and the public addresses a node announces.
130
+ *
131
+ * Lifecycle:
132
+ * - `start()`: load settings, discover the router (bounded), detect the
133
+ * external IP, start DDNS, then map the running nodes in the background.
134
+ * - `stop()`: clear timers only — mappings outlive the host process.
135
+ * - `getStatus()`: snapshot from cached state (cheap).
136
+ * - `publicAddressesFor(nodeId, ports)`: a node's public multiaddrs, also
137
+ * from cached state, predicting the identity mapping for a port that has
138
+ * no route yet.
139
+ * - `onNodeAddressesStale(listener)`: asked to restart a running node whose
140
+ * announced addresses no longer match `publicAddressesFor`, checked after
141
+ * every pass and every settings write (see `AddressWatch`).
142
+ *
143
+ * One reconcile pass against the node source behind three triggers (start,
144
+ * node state change, a 1-minute timer), plus one renewal pass for every lease
145
+ * every `DEFAULT_REFRESH_MS`. Passes are serialized on one promise tail, so a
146
+ * state change during a timer pass can neither map a port twice nor unmap a
147
+ * port the other pass is mapping.
148
+ *
149
+ * NOTE: this file holds the settings/DDNS glue, the mapping table and the status
150
+ * assembly together (about 890 lines; the stale-address check lives in
151
+ * `address-watch.ts` for that reason); when the next capability lands here, move
152
+ * the mapping table (`NodeEntry` through `releaseUpnpRoutes`) into its own module.
153
+ */
154
+ export class NatService {
155
+ private readonly nodeSource: NatNodeSource;
156
+ private readonly store: NatStore;
157
+ private readonly nowFn: () => Date;
158
+ private readonly fetchImpl: typeof fetch;
159
+ private readonly portMapper: PortMapper;
160
+ private readonly leaseTtlMs: number;
161
+ private readonly secretsRootDir: string;
162
+
163
+ private secretsStore: SecretsStore | null;
164
+ /** Caller-supplied detector — used as-is when present (skips the router-probe stitch). */
165
+ private readonly injectedDetector: ExternalIpDetector | null;
166
+ private detector: ExternalIpDetector | null = null;
167
+ private ddnsUpdater: DdnsUpdater | null = null;
168
+
169
+ private currentSettings: NatSettingsFile;
170
+ private gateway: NatGatewayStatus = { found: false, lanAddress: null, routerExternalIp: null, lastError: null };
171
+ private latestIp: ExternalIpResult | null = null;
172
+ private lastTestedAt: Date | null = null;
173
+ private readonly table = new Map<string, NodeEntry>();
174
+
175
+ private started = false;
176
+ private tail: Promise<void> = Promise.resolve();
177
+ /** True while an event-triggered pass is queued and not yet started (crash storms coalesce into it). */
178
+ private eventPassQueued = false;
179
+ private timers: NodeJS.Timeout[] = [];
180
+ private unsubscribe: (() => void) | null = null;
181
+
182
+ private readonly changeListeners = new Set<NatChangeListener>();
183
+ private lastSignature: string | null = null;
184
+ private readonly addressWatch: AddressWatch;
185
+
186
+ constructor(opts: NatServiceOptions) {
187
+ this.nodeSource = opts.nodeSource;
188
+ this.store = opts.store ?? new NatStore(opts.rootDir);
189
+ this.nowFn = opts.now ?? (() => new Date());
190
+ this.fetchImpl = opts.fetch ?? fetch;
191
+ this.portMapper = opts.portMapper ?? new UpnpPortMapper();
192
+ this.leaseTtlMs = opts.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS;
193
+ this.secretsStore = opts.secretsStore ?? null;
194
+ this.injectedDetector = opts.externalIpDetector ?? null;
195
+ this.secretsRootDir = opts.rootDir;
196
+ this.currentSettings = this.store.load();
197
+ this.addressWatch = new AddressWatch(() => this.nowFn().getTime());
198
+ }
199
+
200
+ // --- lifecycle ---
201
+
202
+ /**
203
+ * Discover the router and detect the external IP (both awaited, both
204
+ * bounded), start DDNS, then map re-attached running nodes in the background
205
+ * so the management API comes up promptly. Idempotent.
206
+ */
207
+ async start(): Promise<void> {
208
+ if (this.started) return;
209
+ this.started = true;
210
+
211
+ if (!this.secretsStore) {
212
+ this.secretsStore = await createSecretsStore(this.secretsRootDir);
213
+ }
214
+ if (this.currentSettings.upnpEnabled) await this.discoverGateway();
215
+ await this.detectIp();
216
+
217
+ this.ddnsUpdater = new DdnsUpdater({
218
+ settings: this.currentSettings.ddns,
219
+ secrets: this.secretsStore,
220
+ getExternalIp: () => this.detectedIp(),
221
+ fetch: this.fetchImpl,
222
+ now: this.nowFn,
223
+ });
224
+ await this.ddnsUpdater.start();
225
+
226
+ // Subscribe before the first pass so a spawn during it is not missed.
227
+ this.unsubscribe = this.nodeSource.onStateChange(() => { this.queueEventPass(); });
228
+ this.timers = [
229
+ setInterval(() => { this.sweep('reconcile', () => this.reconcile()); }, NAT_RECONCILE_INTERVAL_MS),
230
+ setInterval(() => { this.sweep('renewal', () => this.renewMappings()); }, DEFAULT_REFRESH_MS),
231
+ setInterval(() => { this.sweep('probe', () => this.redetect()); }, NAT_IP_REDETECT_INTERVAL_MS),
232
+ ];
233
+ for (const t of this.timers) t.unref();
234
+
235
+ this.sweep('startup', () => this.reconcile());
236
+ }
237
+
238
+ /**
239
+ * Clear timers and release client resources. Idempotent.
240
+ *
241
+ * NOTE: deliberately unmaps nothing. Hosted children are detached and keep
242
+ * running across a host restart (an update restart included), so their
243
+ * mappings must outlive this process; they expire on their own within the
244
+ * lease TTL if the host stays down, and the next `start()` re-maps the
245
+ * re-attached nodes (re-mapping the same internal port is idempotent on the
246
+ * router).
247
+ */
248
+ async stop(): Promise<void> {
249
+ if (!this.started) return;
250
+ this.started = false;
251
+ for (const t of this.timers) clearInterval(t);
252
+ this.timers = [];
253
+ this.unsubscribe?.();
254
+ this.unsubscribe = null;
255
+ try {
256
+ this.ddnsUpdater?.stop();
257
+ } catch (err) {
258
+ log('ddns stop failed: %s', errorMessage(err));
259
+ }
260
+ this.ddnsUpdater = null;
261
+ try {
262
+ await this.portMapper.stop();
263
+ } catch (err) {
264
+ log('port mapper stop failed: %s', errorMessage(err));
265
+ }
266
+ }
267
+
268
+ // --- reads ---
269
+
270
+ /** Cheap read of the current snapshot. */
271
+ getStatus(): NatStatusSnapshot {
272
+ const cgnatDetected = this.latestIp?.cgnat ?? false;
273
+ const nodes = [...this.table.values()]
274
+ .sort((a, b) => a.nodeId.localeCompare(b.nodeId))
275
+ .map((entry) => this.describeNode(entry, cgnatDetected));
276
+ return {
277
+ upnpEnabled: this.currentSettings.upnpEnabled,
278
+ gateway: { ...this.gateway, routerExternalIp: this.latestIp?.routerIp ?? null },
279
+ externalIp: this.detectedIp(),
280
+ externalIpDetectedAt: this.latestIp?.detectedAt.toISOString() ?? null,
281
+ cgnatDetected,
282
+ directReachability: evaluateHostReachability(nodes, cgnatDetected),
283
+ lastTestedAt: this.lastTestedAt?.toISOString() ?? null,
284
+ ddns: this.ddnsStatus(),
285
+ nodes,
286
+ };
287
+ }
288
+
289
+ /** Current settings (cheap read; for handlers to surface to UI). */
290
+ getSettings(): NatSettingsFile {
291
+ return this.currentSettings;
292
+ }
293
+
294
+ /**
295
+ * The public multiaddrs for a node, from cached state. A port with no route
296
+ * yet is predicted to land on the identity mapping when UPnP is enabled and
297
+ * a gateway was discovered — callers ask at spawn time, before the mapping
298
+ * for a brand-new node exists. A port whose mapping attempt failed is not
299
+ * predicted.
300
+ */
301
+ publicAddressesFor(nodeId: string, ports: { p2p: number; ws?: number }): string[] {
302
+ const pair = portsOf(ports);
303
+ const entry = this.table.get(nodeId);
304
+ const tcp = this.routeOrPrediction(nodeId, 'tcp', pair.tcp, entry);
305
+ const ws = pair.ws === null ? null : this.routeOrPrediction(nodeId, 'ws', pair.ws, entry);
306
+ return this.addressesFor(tcp, ws);
307
+ }
308
+
309
+ /**
310
+ * Register a listener fired whenever a node's routes, the gateway, the
311
+ * external IP, the CGNAT flag, the UPnP toggle or the DDNS settings change.
312
+ * Returns an unsubscribe fn.
313
+ */
314
+ onChange(listener: NatChangeListener): () => void {
315
+ this.changeListeners.add(listener);
316
+ return () => { this.changeListeners.delete(listener); };
317
+ }
318
+
319
+ /**
320
+ * Register a listener asked to restart a running node whose announced addresses
321
+ * (`ManagedNodeInfo.announcedAddrs`) differ from `publicAddressesFor` — at most
322
+ * once per node per `NAT_ADDRESS_RESTART_MIN_INTERVAL_MS`. Returns an unsubscribe fn.
323
+ */
324
+ onNodeAddressesStale(listener: NodeAddressesStaleListener): () => void {
325
+ return this.addressWatch.subscribe(listener);
326
+ }
327
+
328
+ /** List available DDNS providers (UI listing for configuration). */
329
+ listDdnsProviders(): DdnsProviderInfo[] {
330
+ return listProviders().map((p) => ({
331
+ id: p.id,
332
+ displayName: p.displayName,
333
+ configFields: p.configFields,
334
+ }));
335
+ }
336
+
337
+ // --- passes (public so tests and `testReachability` can drive them) ---
338
+
339
+ /**
340
+ * One reconcile pass against the node source: map running nodes, release
341
+ * nodes stopped past the grace, forget terminated ones. Serialized against
342
+ * every other pass, so a caller may get a queued pass rather than an
343
+ * immediate one.
344
+ */
345
+ reconcile(): Promise<void> {
346
+ return this.enqueue(() => this.reconcileOnce({ mapMissing: true }));
347
+ }
348
+
349
+ /**
350
+ * One renewal pass: re-request every UPnP-eligible mapping of every running
351
+ * node, failed ones included. Each renewal is isolated; one failure does not
352
+ * stop the pass. A router that answers with another external port updates
353
+ * the route.
354
+ */
355
+ renewMappings(): Promise<void> {
356
+ return this.enqueue(() => this.renewOnce());
357
+ }
358
+
359
+ /**
360
+ * The 5-minute probe pass: while UPnP is on and no router has answered,
361
+ * search again and map the running nodes as soon as one does — a host that
362
+ * boots before its network, or a router that comes up later, is found here
363
+ * rather than at the next restart; then re-detect the external IP.
364
+ */
365
+ async redetect(): Promise<void> {
366
+ if (this.currentSettings.upnpEnabled && !this.gateway.found) {
367
+ await this.enqueue(async () => {
368
+ await this.discoverGateway();
369
+ if (this.gateway.found) await this.reconcileOnce({ mapMissing: true });
370
+ });
371
+ }
372
+ await this.detectIp();
373
+ this.publish();
374
+ }
375
+
376
+ // --- writes ---
377
+
378
+ /** Re-discover the router if needed, re-map everything, re-detect the IP, then return a fresh snapshot. */
379
+ async testReachability(): Promise<NatStatusSnapshot> {
380
+ await this.enqueue(async () => {
381
+ if (this.currentSettings.upnpEnabled && !this.gateway.found) await this.discoverGateway();
382
+ await this.reconcileOnce({ mapMissing: false });
383
+ await this.renewOnce();
384
+ });
385
+ await this.detectIp();
386
+ this.lastTestedAt = this.nowFn();
387
+ if (this.ddnsUpdater) {
388
+ await this.ddnsUpdater.forceUpdate().catch((err) => log('ddns forceUpdate err: %s', errorMessage(err)));
389
+ }
390
+ this.publish();
391
+ return this.getStatus();
392
+ }
393
+
394
+ /** Replace settings; persists to disk and reconfigures the runtime. */
395
+ async putSettings(patch: Partial<Omit<NatSettingsFile, 'version' | 'forwards'>>): Promise<NatStatusSnapshot> {
396
+ const next = this.store.update(patch);
397
+ const upnpChanged = next.upnpEnabled !== this.currentSettings.upnpEnabled;
398
+ const ddnsChanged =
399
+ next.ddns.providerId !== this.currentSettings.ddns.providerId ||
400
+ next.ddns.hostname !== this.currentSettings.ddns.hostname ||
401
+ next.ddns.externallyManaged !== this.currentSettings.ddns.externallyManaged ||
402
+ next.ddns.intervalMs !== this.currentSettings.ddns.intervalMs;
403
+ this.currentSettings = next;
404
+
405
+ if (this.started) {
406
+ if (ddnsChanged && this.ddnsUpdater) {
407
+ await this.ddnsUpdater.updateSettings(next.ddns);
408
+ }
409
+ if (upnpChanged) {
410
+ // Turning UPnP on with no gateway known yet: look for one before the
411
+ // pass, so the pass can map. Turning it off: the pass releases every
412
+ // `upnp` route and keeps the manual ones.
413
+ await this.enqueue(async () => {
414
+ if (next.upnpEnabled && !this.gateway.found) await this.discoverGateway();
415
+ await this.reconcileOnce({ mapMissing: true });
416
+ });
417
+ }
418
+ }
419
+ this.publish();
420
+ return this.getStatus();
421
+ }
422
+
423
+ /**
424
+ * Set DDNS configuration and persist secret values into the SecretsStore.
425
+ * Throws if the provider is unknown or required secrets are missing.
426
+ */
427
+ async putDdns(body: {
428
+ providerId: string;
429
+ hostname: string;
430
+ config: Record<string, string>;
431
+ externallyManaged?: boolean;
432
+ }): Promise<NatStatusSnapshot> {
433
+ if (!body || typeof body.providerId !== 'string' || typeof body.hostname !== 'string') {
434
+ throw new NatError('invalid_config', 'providerId and hostname are required');
435
+ }
436
+ const provider = getProvider(body.providerId);
437
+ if (!this.secretsStore) {
438
+ throw new NatError('secrets_unavailable', 'secrets store not initialised; call start() first');
439
+ }
440
+
441
+ for (const field of provider.configFields) {
442
+ if (!field.secret) continue;
443
+ const value = body.config[field.key];
444
+ if (typeof value !== 'string' || value.length === 0) {
445
+ throw new NatError(
446
+ 'ddns_credentials_missing',
447
+ `Missing value for required secret field "${field.key}" of provider "${provider.id}"`,
448
+ );
449
+ }
450
+ await this.secretsStore.set(ddnsAccount(provider.id, field.key), value);
451
+ }
452
+
453
+ const externallyManaged = body.externallyManaged ?? false;
454
+ return await this.putSettings({
455
+ ddns: {
456
+ providerId: provider.id,
457
+ hostname: provider.qualifyHostname(body.hostname),
458
+ externallyManaged,
459
+ intervalMs: this.currentSettings.ddns.intervalMs,
460
+ },
461
+ });
462
+ }
463
+
464
+ /**
465
+ * Record the external ports the user forwarded by hand for one node (`null`
466
+ * clears a port). A port that became manual releases its UPnP mapping; a
467
+ * port whose entry was cleared is re-requested over UPnP.
468
+ */
469
+ async putForward(nodeId: string, patch: ManualForwardPatch): Promise<NatStatusSnapshot> {
470
+ validateForwardPatch(patch);
471
+ if (!this.nodeSource.listNodes().some((n) => n.id === nodeId)) {
472
+ throw new NatError('unknown_node', `no hosted node with id "${nodeId}"`);
473
+ }
474
+ this.currentSettings = this.store.setForward(nodeId, patch);
475
+ if (this.started) await this.reconcile();
476
+ this.publish();
477
+ return this.getStatus();
478
+ }
479
+
480
+ // --- reconcile internals ---
481
+
482
+ private enqueue<T>(fn: () => Promise<T>): Promise<T> {
483
+ const next = this.tail.then(fn, fn);
484
+ // The stored tail swallows outcomes — a failed pass must not reject the
485
+ // next caller's wait, only sequence after it.
486
+ this.tail = next.then(() => undefined, () => undefined);
487
+ return next;
488
+ }
489
+
490
+ /** Fire-and-forget pass for the timer / event / startup triggers. */
491
+ private sweep(trigger: string, run: () => Promise<void>): void {
492
+ void run().catch((err) => { log('%s pass failed: %s', trigger, errorMessage(err)); });
493
+ }
494
+
495
+ /**
496
+ * One pass per burst of events: an event while a pass is queued joins it,
497
+ * and an event during a running pass queues exactly one more, so a node that
498
+ * spawned after the running pass listed the nodes is mapped by the next pass
499
+ * rather than by the timer.
500
+ */
501
+ private queueEventPass(): void {
502
+ if (this.eventPassQueued) return;
503
+ this.eventPassQueued = true;
504
+ void this.enqueue(() => {
505
+ this.eventPassQueued = false;
506
+ return this.reconcileOnce({ mapMissing: true });
507
+ }).catch((err) => { log('event pass failed: %s', errorMessage(err)); });
508
+ }
509
+
510
+ private async reconcileOnce(opts: { mapMissing: boolean }): Promise<void> {
511
+ if (!this.started) return;
512
+ const listed = new Map(this.nodeSource.listNodes().map((n) => [n.id, n]));
513
+ await this.forgetMissingNodes(listed);
514
+ for (const node of listed.values()) {
515
+ if (!this.started) break;
516
+ try {
517
+ await this.reconcileNode(node, opts.mapMissing);
518
+ } catch (err) {
519
+ // One bad node must never end the pass — the others still need their routes.
520
+ log('reconcile of node %s failed: %s', node.id, errorMessage(err));
521
+ }
522
+ }
523
+ this.publish();
524
+ }
525
+
526
+ /**
527
+ * A node no longer listed was terminated (`removeContainer`): release its
528
+ * mappings at once and drop its manual forward. A forward left behind for a
529
+ * node that vanished while the host was down goes the same way.
530
+ */
531
+ private async forgetMissingNodes(listed: Map<string, ManagedNodeInfo>): Promise<void> {
532
+ for (const [nodeId, entry] of this.table) {
533
+ if (listed.has(nodeId)) continue;
534
+ await this.releaseUpnpRoutes(entry);
535
+ this.table.delete(nodeId);
536
+ }
537
+ for (const nodeId of Object.keys(this.currentSettings.forwards)) {
538
+ if (listed.has(nodeId)) continue;
539
+ this.currentSettings = this.store.deleteForward(nodeId);
540
+ }
541
+ }
542
+
543
+ private async reconcileNode(node: ManagedNodeInfo, mapMissing: boolean): Promise<void> {
544
+ const ports = portsOf(node.ports);
545
+ let entry = this.table.get(node.id);
546
+ if (entry && !samePorts(entry.ports, ports)) {
547
+ // Ports changed across a respawn: the old mappings point at ports nothing binds.
548
+ await this.releaseUpnpRoutes(entry);
549
+ entry = undefined;
550
+ }
551
+ if (!entry) {
552
+ entry = {
553
+ nodeId: node.id,
554
+ running: false,
555
+ stoppedSince: null,
556
+ ports,
557
+ routes: { tcp: noRoute(ports.tcp), ws: ports.ws === null ? null : noRoute(ports.ws) },
558
+ };
559
+ this.table.set(node.id, entry);
560
+ }
561
+ if (node.status === 'running') {
562
+ entry.running = true;
563
+ entry.stoppedSince = null;
564
+ await this.reconcileRoutes(entry, mapMissing);
565
+ return;
566
+ }
567
+ entry.running = false;
568
+ entry.stoppedSince ??= this.nowFn().getTime();
569
+ if (this.nowFn().getTime() - entry.stoppedSince >= NAT_UNMAP_GRACE_MS) {
570
+ await this.releaseUpnpRoutes(entry);
571
+ }
572
+ // Manual forwards still follow the settings while the node is down; no router call is needed.
573
+ await this.reconcileRoutes(entry, false);
574
+ }
575
+
576
+ /**
577
+ * Bring one node's routes in line with the settings: manual wins over UPnP;
578
+ * UPnP off releases every `upnp` route; with `mapMissing`, a port with no
579
+ * route and no recorded failure (or an expired lease) is requested.
580
+ */
581
+ private async reconcileRoutes(entry: NodeEntry, mapMissing: boolean): Promise<void> {
582
+ for (const kind of this.kindsOf(entry)) {
583
+ const route = entry.routes[kind]!;
584
+ const forward = this.currentSettings.forwards[entry.nodeId]?.[kind];
585
+ if (forward !== undefined) {
586
+ if (route.source === 'upnp') await this.unmapRoute(entry, kind);
587
+ entry.routes[kind] = manualRoute(route.internalPort, forward);
588
+ continue;
589
+ }
590
+ if (route.source === 'manual') {
591
+ entry.routes[kind] = noRoute(route.internalPort);
592
+ }
593
+ if (!this.currentSettings.upnpEnabled) {
594
+ if (entry.routes[kind]!.source === 'upnp') await this.unmapRoute(entry, kind);
595
+ entry.routes[kind] = noRoute(route.internalPort);
596
+ continue;
597
+ }
598
+ if (!mapMissing || !this.gateway.found) continue;
599
+ const current = entry.routes[kind]!;
600
+ const untried = current.source === null && current.error === null;
601
+ if (untried || this.leaseExpired(current)) {
602
+ await this.mapRoute(entry, kind);
603
+ }
604
+ }
605
+ }
606
+
607
+ private async renewOnce(): Promise<void> {
608
+ if (!this.started) return;
609
+ if (!this.currentSettings.upnpEnabled || !this.gateway.found) return;
610
+ for (const entry of this.table.values()) {
611
+ if (!this.started) break;
612
+ if (!entry.running) continue;
613
+ for (const kind of this.kindsOf(entry)) {
614
+ if (entry.routes[kind]!.source === 'manual') continue;
615
+ await this.mapRoute(entry, kind);
616
+ }
617
+ }
618
+ this.publish();
619
+ }
620
+
621
+ /**
622
+ * Ask the router for one port. A refusal records `error` on that port only.
623
+ *
624
+ * NOTE: a router that stops answering costs each attempt its 10 s timeout, so a
625
+ * pass over N mapped ports can take 10 s × N; passes are serialized, so they queue
626
+ * rather than overlap. If that ever shows, skip ports whose last failure was a
627
+ * timeout until the next renewal pass.
628
+ */
629
+ private async mapRoute(entry: NodeEntry, kind: PortKind): Promise<void> {
630
+ const previous = entry.routes[kind]!;
631
+ const internalPort = previous.internalPort;
632
+ try {
633
+ const result = await this.portMapper.map({ internalPort, protocol: 'tcp', ttlMs: this.leaseTtlMs });
634
+ entry.routes[kind] = {
635
+ internalPort,
636
+ externalPort: result.externalPort,
637
+ source: 'upnp',
638
+ leaseExpiresAt: result.leaseExpiresAt.toISOString(),
639
+ error: null,
640
+ };
641
+ log('mapped %s %s port %d → external %d', entry.nodeId, kind, internalPort, result.externalPort);
642
+ } catch (err) {
643
+ const message = errorMessage(err);
644
+ // A failed renewal of a live mapping keeps the route: the router still
645
+ // holds it until the lease expires, and `leaseExpired` drops it then.
646
+ const live = previous.source === 'upnp' && !this.leaseExpired(previous);
647
+ entry.routes[kind] = live ? { ...previous, error: message } : { ...noRoute(internalPort), error: message };
648
+ log('mapping %s %s port %d failed: %s', entry.nodeId, kind, internalPort, message);
649
+ }
650
+ }
651
+
652
+ private async unmapRoute(entry: NodeEntry, kind: PortKind): Promise<void> {
653
+ const route = entry.routes[kind]!;
654
+ await this.portMapper.unmap(route.internalPort, 'tcp');
655
+ entry.routes[kind] = noRoute(route.internalPort);
656
+ log('unmapped %s %s port %d', entry.nodeId, kind, route.internalPort);
657
+ }
658
+
659
+ private async releaseUpnpRoutes(entry: NodeEntry): Promise<void> {
660
+ for (const kind of this.kindsOf(entry)) {
661
+ if (entry.routes[kind]!.source === 'upnp') await this.unmapRoute(entry, kind);
662
+ }
663
+ }
664
+
665
+ private kindsOf(entry: NodeEntry): PortKind[] {
666
+ return PORT_KINDS.filter((kind) => entry.routes[kind] !== null);
667
+ }
668
+
669
+ private leaseExpired(route: PortRoute): boolean {
670
+ if (route.source !== 'upnp' || !route.leaseExpiresAt) return false;
671
+ return Date.parse(route.leaseExpiresAt) <= this.nowFn().getTime();
672
+ }
673
+
674
+ /** A UPnP route whose lease ran out reads as no route, keeping any recorded failure. */
675
+ private effectiveRoute(route: PortRoute): PortRoute {
676
+ if (!this.leaseExpired(route)) return route;
677
+ return { ...noRoute(route.internalPort), error: route.error };
678
+ }
679
+
680
+ // --- gateway / external IP ---
681
+
682
+ private async discoverGateway(): Promise<void> {
683
+ try {
684
+ const info = await this.portMapper.discover();
685
+ this.gateway = info
686
+ ? { found: true, lanAddress: info.lanAddress, routerExternalIp: null, lastError: null }
687
+ : {
688
+ found: false,
689
+ lanAddress: null,
690
+ routerExternalIp: null,
691
+ lastError: `no UPnP gateway answered within ${GATEWAY_DISCOVERY_TIMEOUT_MS / 1000} s`,
692
+ };
693
+ } catch (err) {
694
+ this.gateway = { found: false, lanAddress: null, routerExternalIp: null, lastError: errorMessage(err) };
695
+ }
696
+ if (!this.gateway.found) log('gateway discovery: %s', this.gateway.lastError);
697
+ }
698
+
699
+ /**
700
+ * Detect the external IP. A detection that finds nothing (or throws), or that
701
+ * lost the public echo the previous one had, keeps the previous result: one
702
+ * failed probe must not drop every node's public address, and a router-only
703
+ * answer must not flip the CGNAT flag the two probes had agreed on.
704
+ */
705
+ private async detectIp(): Promise<void> {
706
+ try {
707
+ const result = await this.ipDetector().detect();
708
+ if (this.knowsLessThanPrevious(result)) {
709
+ log('external IP detection found less than before; keeping the previous result');
710
+ return;
711
+ }
712
+ this.latestIp = result;
713
+ } catch (err) {
714
+ log('detectIp failed: %s', errorMessage(err));
715
+ }
716
+ }
717
+
718
+ private knowsLessThanPrevious(result: ExternalIpResult): boolean {
719
+ if (result.publicIp === null && result.routerIp === null) return true;
720
+ return result.publicIp === null && this.latestIp?.publicIp != null;
721
+ }
722
+
723
+ private ipDetector(): ExternalIpDetector {
724
+ if (this.injectedDetector) return this.injectedDetector;
725
+ this.detector ??= new ExternalIpDetector({
726
+ fetch: this.fetchImpl,
727
+ now: this.nowFn,
728
+ routerProbe: async () => (this.gateway.found ? await this.portMapper.externalIp() : null),
729
+ });
730
+ return this.detector;
731
+ }
732
+
733
+ /** The detected external IP for display and DDNS: the public probe's, else the router's. */
734
+ private detectedIp(): string | null {
735
+ return this.latestIp?.publicIp ?? this.latestIp?.routerIp ?? null;
736
+ }
737
+
738
+ /** The IP used in `/ip4/` addresses: only a public IPv4 counts. */
739
+ private publicIpv4(): string | null {
740
+ const ip = this.detectedIp();
741
+ return ip && isPublicIpv4(ip) ? ip : null;
742
+ }
743
+
744
+ // --- status assembly ---
745
+
746
+ private describeNode(entry: NodeEntry, cgnatDetected: boolean): NodeReachability {
747
+ const tcp = this.effectiveRoute(entry.routes.tcp);
748
+ const ws = entry.routes.ws ? this.effectiveRoute(entry.routes.ws) : null;
749
+ const { verdict, reason } = evaluateNodeReachability({
750
+ tcp,
751
+ ws,
752
+ hostKnown: this.hostKnown(),
753
+ cgnatDetected,
754
+ upnpEnabled: this.currentSettings.upnpEnabled,
755
+ gatewayFound: this.gateway.found,
756
+ lanAddress: this.gateway.lanAddress,
757
+ });
758
+ return {
759
+ nodeId: entry.nodeId,
760
+ running: entry.running,
761
+ verdict,
762
+ reason,
763
+ tcp,
764
+ ws,
765
+ publicAddrs: this.addressesFor(tcp, ws),
766
+ };
767
+ }
768
+
769
+ private hostKnown(): boolean {
770
+ return this.currentSettings.ddns.hostname !== null || this.publicIpv4() !== null;
771
+ }
772
+
773
+ private addressesFor(tcp: PortRoute, ws: PortRoute | null): string[] {
774
+ return buildPublicAddresses({
775
+ ddnsHostname: this.currentSettings.ddns.hostname,
776
+ externalIp: this.publicIpv4(),
777
+ cgnatDetected: this.latestIp?.cgnat ?? false,
778
+ tcp,
779
+ ws,
780
+ });
781
+ }
782
+
783
+ private routeOrPrediction(nodeId: string, kind: PortKind, internalPort: number, entry: NodeEntry | undefined): PortRoute {
784
+ const forward = this.currentSettings.forwards[nodeId]?.[kind];
785
+ if (forward !== undefined) return manualRoute(internalPort, forward);
786
+ const existing = entry?.routes[kind];
787
+ if (existing && existing.internalPort === internalPort) {
788
+ const route = this.effectiveRoute(existing);
789
+ if (route.source !== null || route.error !== null) return route;
790
+ }
791
+ if (this.currentSettings.upnpEnabled && this.gateway.found) {
792
+ return { internalPort, externalPort: internalPort, source: 'upnp', leaseExpiresAt: null, error: null };
793
+ }
794
+ return noRoute(internalPort);
795
+ }
796
+
797
+ private ddnsStatus(): NatDdnsStatus {
798
+ return this.ddnsUpdater?.getStatus() ?? {
799
+ providerId: this.currentSettings.ddns.providerId,
800
+ hostname: this.currentSettings.ddns.hostname,
801
+ externallyManaged: this.currentSettings.ddns.externallyManaged,
802
+ lastUpdateAt: null,
803
+ lastUpdateOk: null,
804
+ lastError: null,
805
+ };
806
+ }
807
+
808
+ // --- change notification ---
809
+
810
+ /**
811
+ * The end of every pass and every settings write: tell the change listeners
812
+ * when the snapshot moved, then ask for a restart of every running node whose
813
+ * announced addresses went stale. Running the check here rather than only on a
814
+ * change is what lets a difference deferred by the restart rate limit fire on the
815
+ * first timer pass after the limit ends.
816
+ */
817
+ private publish(): void {
818
+ this.notifyIfChanged();
819
+ if (!this.started) return;
820
+ this.addressWatch.check(this.nodeSource.listNodes(), (node) => this.publicAddressesFor(node.id, node.ports));
821
+ }
822
+
823
+ /** Fire the change listeners when the snapshot differs (timestamps aside) from the last one they saw. */
824
+ private notifyIfChanged(): void {
825
+ const snapshot = this.getStatus();
826
+ const signature = signatureOf(snapshot);
827
+ if (signature === this.lastSignature) return;
828
+ this.lastSignature = signature;
829
+ for (const listener of this.changeListeners) {
830
+ try {
831
+ listener(snapshot);
832
+ } catch (err) {
833
+ log('change listener threw: %s', errorMessage(err));
834
+ }
835
+ }
836
+ }
837
+ }
838
+
839
+ /** The snapshot minus the fields that move on their own (timestamps, lease expiry). */
840
+ function signatureOf(s: NatStatusSnapshot): string {
841
+ return JSON.stringify({
842
+ upnpEnabled: s.upnpEnabled,
843
+ gateway: s.gateway,
844
+ externalIp: s.externalIp,
845
+ cgnatDetected: s.cgnatDetected,
846
+ directReachability: s.directReachability,
847
+ ddns: { providerId: s.ddns.providerId, hostname: s.ddns.hostname, externallyManaged: s.ddns.externallyManaged },
848
+ nodes: s.nodes.map((n) => ({
849
+ nodeId: n.nodeId,
850
+ running: n.running,
851
+ verdict: n.verdict,
852
+ tcp: routeSignature(n.tcp),
853
+ ws: n.ws ? routeSignature(n.ws) : null,
854
+ publicAddrs: n.publicAddrs,
855
+ })),
856
+ });
857
+ }
858
+
859
+ function routeSignature(r: PortRoute): Omit<PortRoute, 'leaseExpiresAt'> {
860
+ return { internalPort: r.internalPort, externalPort: r.externalPort, source: r.source, error: r.error };
861
+ }
862
+
863
+ function validateForwardPatch(patch: ManualForwardPatch): void {
864
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
865
+ throw new NatError('invalid_config', 'a forward patch must be an object with tcp and/or ws');
866
+ }
867
+ for (const kind of PORT_KINDS) {
868
+ const value = patch[kind];
869
+ if (value === undefined || value === null) continue;
870
+ if (!Number.isInteger(value) || value < 1 || value > 65535) {
871
+ throw new NatError('invalid_config', `${kind} must be an integer 1-65535 or null, got ${String(value)}`);
872
+ }
873
+ }
874
+ }
875
+
876
+ /**
877
+ * Wrap a NatService into the typed handler shape consumed by the local UI
878
+ * server. Same shape as `createUpdateHandlers`.
879
+ */
880
+ export function createNatHandlers(service: NatService): NatHandlers {
881
+ return {
882
+ async getStatus() { return service.getStatus(); },
883
+ async testReachability() { return await service.testReachability(); },
884
+ async listDdnsProviders() { return service.listDdnsProviders(); },
885
+ async putDdns(body) { return await service.putDdns(body); },
886
+ async putSettings(body) { return await service.putSettings(body); },
887
+ async putForward(nodeId, patch) { return await service.putForward(nodeId, patch); },
888
+ };
889
+ }