@serfab/cadre-host 1.13.0 → 1.15.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 (352) hide show
  1. package/README.md +347 -423
  2. package/dist/bin/host.d.ts +6 -3
  3. package/dist/bin/host.js +332 -524
  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 +54 -0
  9. package/dist/bin/nat-output.js +138 -0
  10. package/dist/bin/nat-output.js.map +1 -0
  11. package/dist/bin/ui-access.d.ts +22 -0
  12. package/dist/bin/ui-access.js +44 -0
  13. package/dist/bin/ui-access.js.map +1 -0
  14. package/dist/hosted/claim-details.d.ts +66 -0
  15. package/dist/hosted/claim-details.js +60 -0
  16. package/dist/hosted/claim-details.js.map +1 -0
  17. package/dist/hosted/hosted-node-service.d.ts +325 -0
  18. package/dist/hosted/hosted-node-service.js +678 -0
  19. package/dist/hosted/hosted-node-service.js.map +1 -0
  20. package/dist/hosted/hosted-node-store.d.ts +40 -0
  21. package/dist/hosted/hosted-node-store.js +126 -0
  22. package/dist/hosted/hosted-node-store.js.map +1 -0
  23. package/dist/{donation/donation-supervisor.d.ts → hosted/hosted-node-supervisor.d.ts} +70 -53
  24. package/dist/hosted/hosted-node-supervisor.js +396 -0
  25. package/dist/hosted/hosted-node-supervisor.js.map +1 -0
  26. package/dist/hosted/hosted-node-watcher.d.ts +95 -0
  27. package/dist/hosted/hosted-node-watcher.js +260 -0
  28. package/dist/hosted/hosted-node-watcher.js.map +1 -0
  29. package/dist/hosted/index.d.ts +16 -0
  30. package/dist/hosted/index.js +13 -0
  31. package/dist/hosted/index.js.map +1 -0
  32. package/dist/hosted/node-status.d.ts +51 -0
  33. package/dist/hosted/node-status.js +77 -0
  34. package/dist/hosted/node-status.js.map +1 -0
  35. package/dist/hosted/types.d.ts +141 -0
  36. package/dist/hosted/types.js +22 -0
  37. package/dist/hosted/types.js.map +1 -0
  38. package/dist/index.d.ts +12 -24
  39. package/dist/index.js +9 -19
  40. package/dist/index.js.map +1 -1
  41. package/dist/installer/config.d.ts +27 -34
  42. package/dist/installer/config.js +46 -15
  43. package/dist/installer/config.js.map +1 -1
  44. package/dist/installer/index.d.ts +9 -19
  45. package/dist/installer/index.js +21 -85
  46. package/dist/installer/index.js.map +1 -1
  47. package/dist/installer/paths.d.ts +0 -2
  48. package/dist/installer/paths.js +0 -4
  49. package/dist/installer/paths.js.map +1 -1
  50. package/dist/installer/wizard.d.ts +12 -9
  51. package/dist/installer/wizard.js +15 -14
  52. package/dist/installer/wizard.js.map +1 -1
  53. package/dist/nat/address-resolver.d.ts +18 -17
  54. package/dist/nat/address-resolver.js +79 -25
  55. package/dist/nat/address-resolver.js.map +1 -1
  56. package/dist/nat/address-watch.d.ts +37 -0
  57. package/dist/nat/address-watch.js +84 -0
  58. package/dist/nat/address-watch.js.map +1 -0
  59. package/dist/nat/ddns/duckdns.d.ts +2 -1
  60. package/dist/nat/ddns/duckdns.js +5 -1
  61. package/dist/nat/ddns/duckdns.js.map +1 -1
  62. package/dist/nat/ddns/index.d.ts +6 -0
  63. package/dist/nat/ddns/index.js.map +1 -1
  64. package/dist/nat/index.d.ts +13 -9
  65. package/dist/nat/index.js +7 -5
  66. package/dist/nat/index.js.map +1 -1
  67. package/dist/nat/nat-service.d.ts +220 -77
  68. package/dist/nat/nat-service.js +653 -239
  69. package/dist/nat/nat-service.js.map +1 -1
  70. package/dist/nat/nat-store.d.ts +12 -5
  71. package/dist/nat/nat-store.js +124 -29
  72. package/dist/nat/nat-store.js.map +1 -1
  73. package/dist/nat/network-mode.d.ts +19 -0
  74. package/dist/nat/network-mode.js +32 -0
  75. package/dist/nat/network-mode.js.map +1 -0
  76. package/dist/nat/port-mapper.d.ts +83 -79
  77. package/dist/nat/port-mapper.js +148 -189
  78. package/dist/nat/port-mapper.js.map +1 -1
  79. package/dist/nat/reachability.d.ts +32 -15
  80. package/dist/nat/reachability.js +110 -22
  81. package/dist/nat/reachability.js.map +1 -1
  82. package/dist/nat/types.d.ts +98 -27
  83. package/dist/nat/types.js +8 -5
  84. package/dist/nat/types.js.map +1 -1
  85. package/dist/orchestrator/host-process-orchestrator.d.ts +32 -74
  86. package/dist/orchestrator/host-process-orchestrator.js +84 -233
  87. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  88. package/dist/{installer/identity.d.ts → orchestrator/identity-file.d.ts} +5 -5
  89. package/dist/{installer/identity.js → orchestrator/identity-file.js} +6 -6
  90. package/dist/orchestrator/identity-file.js.map +1 -0
  91. package/dist/orchestrator/index.d.ts +2 -3
  92. package/dist/orchestrator/index.js +1 -1
  93. package/dist/orchestrator/index.js.map +1 -1
  94. package/dist/orchestrator/node-identity.d.ts +6 -6
  95. package/dist/orchestrator/node-identity.js +7 -7
  96. package/dist/orchestrator/node-identity.js.map +1 -1
  97. package/dist/orchestrator/port-allocator.d.ts +5 -6
  98. package/dist/orchestrator/port-allocator.js +9 -11
  99. package/dist/orchestrator/port-allocator.js.map +1 -1
  100. package/dist/orchestrator/state-store.d.ts +3 -5
  101. package/dist/orchestrator/state-store.js +2 -10
  102. package/dist/orchestrator/state-store.js.map +1 -1
  103. package/dist/orchestrator/types.d.ts +33 -22
  104. package/dist/orchestrator/types.js.map +1 -1
  105. package/dist/package-version.d.ts +1 -0
  106. package/dist/package-version.js +4 -0
  107. package/dist/package-version.js.map +1 -0
  108. package/dist/server/error-handler.d.ts +5 -25
  109. package/dist/server/error-handler.js +11 -74
  110. package/dist/server/error-handler.js.map +1 -1
  111. package/dist/server/events/types.d.ts +7 -11
  112. package/dist/server/events/types.js +2 -1
  113. package/dist/server/events/types.js.map +1 -1
  114. package/dist/server/index.d.ts +11 -37
  115. package/dist/server/index.js +30 -48
  116. package/dist/server/index.js.map +1 -1
  117. package/dist/server/routes/hosted-nodes.d.ts +28 -0
  118. package/dist/server/routes/hosted-nodes.js +68 -0
  119. package/dist/server/routes/hosted-nodes.js.map +1 -0
  120. package/dist/server/routes/nat.d.ts +4 -1
  121. package/dist/server/routes/nat.js +13 -2
  122. package/dist/server/routes/nat.js.map +1 -1
  123. package/dist/server/routes/nodes.d.ts +6 -20
  124. package/dist/server/routes/nodes.js +7 -86
  125. package/dist/server/routes/nodes.js.map +1 -1
  126. package/dist/server/routes/settings.d.ts +3 -7
  127. package/dist/server/routes/settings.js +18 -8
  128. package/dist/server/routes/settings.js.map +1 -1
  129. package/dist/server/routes/status.d.ts +2 -25
  130. package/dist/server/routes/status.js +3 -43
  131. package/dist/server/routes/status.js.map +1 -1
  132. package/dist/server/server.js +8 -8
  133. package/dist/server/settings-store.d.ts +2 -2
  134. package/dist/server/settings-store.js +2 -2
  135. package/dist/server/static.js +1 -2
  136. package/dist/server/static.js.map +1 -1
  137. package/dist/ui/assets/index-BHd8CWZA.css +1 -0
  138. package/dist/ui/assets/index-Ccr2GjPT.js +23 -0
  139. package/dist/ui/assets/index-Ccr2GjPT.js.map +1 -0
  140. package/dist/ui/index.html +2 -2
  141. package/dist/update/index.d.ts +2 -2
  142. package/dist/update/index.js +2 -2
  143. package/dist/update/store.d.ts +1 -1
  144. package/dist/update/store.js +1 -1
  145. package/dist/update/types.d.ts +1 -1
  146. package/dist/update/types.js +1 -1
  147. package/package.json +5 -7
  148. package/src/__tests__/cli-nat.smoke.test.ts +219 -212
  149. package/src/__tests__/cli.smoke.test.ts +2 -2
  150. package/src/__tests__/global-setup.ts +2 -3
  151. package/src/__tests__/orchestrator-claim-secret.test.ts +111 -0
  152. package/src/__tests__/orchestrator-env-scrub.test.ts +160 -163
  153. package/src/__tests__/orchestrator-handle-contract.ts +134 -134
  154. package/src/__tests__/orchestrator-node-identity.test.ts +177 -203
  155. package/src/__tests__/orchestrator-ports.test.ts +124 -143
  156. package/src/__tests__/orchestrator-push.test.ts +138 -146
  157. package/src/__tests__/orchestrator.test.ts +1017 -1063
  158. package/src/__tests__/ui-access.test.ts +30 -0
  159. package/src/bin/host.ts +397 -572
  160. package/src/bin/join-output.ts +120 -0
  161. package/src/bin/nat-output.ts +188 -0
  162. package/src/bin/ui-access.ts +50 -0
  163. package/src/{donation → hosted}/__tests__/fake-orchestrator.test.ts +172 -173
  164. package/src/{donation → hosted}/__tests__/fake-orchestrator.ts +43 -23
  165. package/src/hosted/__tests__/hosted-node-service.test.ts +708 -0
  166. package/src/hosted/__tests__/hosted-node-supervisor.test.ts +475 -0
  167. package/src/hosted/__tests__/test-invitation.ts +33 -0
  168. package/src/hosted/claim-details.ts +103 -0
  169. package/src/hosted/hosted-node-service.ts +814 -0
  170. package/src/hosted/hosted-node-store.ts +144 -0
  171. package/src/hosted/hosted-node-supervisor.ts +439 -0
  172. package/src/hosted/hosted-node-watcher.ts +288 -0
  173. package/src/hosted/index.ts +53 -0
  174. package/src/hosted/node-status.ts +97 -0
  175. package/src/hosted/types.ts +160 -0
  176. package/src/index.ts +72 -91
  177. package/src/installer/__tests__/config.test.ts +15 -40
  178. package/src/installer/__tests__/installer.smoke.test.ts +184 -263
  179. package/src/installer/__tests__/wizard.test.ts +25 -13
  180. package/src/installer/config.ts +201 -175
  181. package/src/installer/index.ts +252 -327
  182. package/src/installer/paths.ts +104 -109
  183. package/src/installer/wizard.ts +24 -26
  184. package/src/nat/__tests__/address-resolver.test.ts +107 -82
  185. package/src/nat/__tests__/nat-service.test.ts +608 -515
  186. package/src/nat/__tests__/nat-store.test.ts +49 -12
  187. package/src/nat/__tests__/network-mode.test.ts +38 -0
  188. package/src/nat/__tests__/port-mapper.test.ts +30 -191
  189. package/src/nat/__tests__/reachability.test.ts +96 -13
  190. package/src/nat/address-resolver.ts +94 -52
  191. package/src/nat/address-watch.ts +92 -0
  192. package/src/nat/ddns/duckdns.ts +5 -1
  193. package/src/nat/ddns/index.ts +6 -0
  194. package/src/nat/index.ts +33 -13
  195. package/src/nat/nat-service.ts +942 -501
  196. package/src/nat/nat-store.ts +126 -31
  197. package/src/nat/network-mode.ts +36 -0
  198. package/src/nat/port-mapper.ts +241 -329
  199. package/src/nat/reachability.ts +155 -34
  200. package/src/nat/types.ts +110 -37
  201. package/src/{installer/__tests__/identity.test.ts → orchestrator/__tests__/identity-file.test.ts} +34 -34
  202. package/src/orchestrator/__tests__/node-identity.test.ts +62 -62
  203. package/src/orchestrator/host-process-orchestrator.ts +1089 -1260
  204. package/src/{installer/identity.ts → orchestrator/identity-file.ts} +56 -56
  205. package/src/orchestrator/index.ts +9 -10
  206. package/src/orchestrator/node-identity.ts +41 -41
  207. package/src/orchestrator/port-allocator.ts +71 -73
  208. package/src/orchestrator/state-store.ts +76 -90
  209. package/src/orchestrator/types.ts +34 -23
  210. package/src/package-version.ts +4 -0
  211. package/src/server/__tests__/bus.test.ts +38 -38
  212. package/src/server/__tests__/error-handler.test.ts +81 -118
  213. package/src/server/__tests__/fakes.ts +15 -18
  214. package/src/server/__tests__/hosted-nodes-route.test.ts +161 -0
  215. package/src/server/__tests__/nodes-route.test.ts +114 -283
  216. package/src/server/__tests__/publishers.test.ts +193 -180
  217. package/src/server/__tests__/server.smoke.test.ts +134 -223
  218. package/src/server/__tests__/settings-route.test.ts +210 -195
  219. package/src/server/__tests__/sse-route.test.ts +119 -119
  220. package/src/server/__tests__/status-route.test.ts +82 -121
  221. package/src/server/error-handler.ts +112 -178
  222. package/src/server/events/types.ts +20 -24
  223. package/src/server/index.ts +223 -267
  224. package/src/server/routes/hosted-nodes.ts +83 -0
  225. package/src/server/routes/nat.ts +75 -63
  226. package/src/server/routes/nodes.ts +96 -188
  227. package/src/server/routes/settings.ts +20 -15
  228. package/src/server/routes/status.ts +5 -67
  229. package/src/server/server.ts +8 -8
  230. package/src/server/settings-store.ts +2 -2
  231. package/src/server/static.ts +1 -2
  232. package/src/update/index.ts +2 -2
  233. package/src/update/store.ts +1 -1
  234. package/src/update/types.ts +1 -1
  235. package/dist/auth/duration.d.ts +0 -1
  236. package/dist/auth/duration.js +0 -32
  237. package/dist/auth/duration.js.map +0 -1
  238. package/dist/auth/index.d.ts +0 -11
  239. package/dist/auth/index.js +0 -9
  240. package/dist/auth/index.js.map +0 -1
  241. package/dist/auth/self-label.d.ts +0 -36
  242. package/dist/auth/self-label.js +0 -57
  243. package/dist/auth/self-label.js.map +0 -1
  244. package/dist/auth/trust-circle-store.d.ts +0 -26
  245. package/dist/auth/trust-circle-store.js +0 -129
  246. package/dist/auth/trust-circle-store.js.map +0 -1
  247. package/dist/auth/trust-circle.d.ts +0 -156
  248. package/dist/auth/trust-circle.js +0 -307
  249. package/dist/auth/trust-circle.js.map +0 -1
  250. package/dist/auth/types.d.ts +0 -84
  251. package/dist/auth/types.js +0 -24
  252. package/dist/auth/types.js.map +0 -1
  253. package/dist/donation/donation-service.d.ts +0 -389
  254. package/dist/donation/donation-service.js +0 -828
  255. package/dist/donation/donation-service.js.map +0 -1
  256. package/dist/donation/donation-store.d.ts +0 -51
  257. package/dist/donation/donation-store.js +0 -152
  258. package/dist/donation/donation-store.js.map +0 -1
  259. package/dist/donation/donation-supervisor.js +0 -364
  260. package/dist/donation/donation-supervisor.js.map +0 -1
  261. package/dist/donation/grant-service.d.ts +0 -80
  262. package/dist/donation/grant-service.js +0 -210
  263. package/dist/donation/grant-service.js.map +0 -1
  264. package/dist/donation/grant-store.d.ts +0 -38
  265. package/dist/donation/grant-store.js +0 -135
  266. package/dist/donation/grant-store.js.map +0 -1
  267. package/dist/donation/index.d.ts +0 -20
  268. package/dist/donation/index.js +0 -17
  269. package/dist/donation/index.js.map +0 -1
  270. package/dist/donation/types.d.ts +0 -224
  271. package/dist/donation/types.js +0 -40
  272. package/dist/donation/types.js.map +0 -1
  273. package/dist/installer/identity.js.map +0 -1
  274. package/dist/owner/index.d.ts +0 -11
  275. package/dist/owner/index.js +0 -11
  276. package/dist/owner/index.js.map +0 -1
  277. package/dist/owner/owner-node-client.d.ts +0 -110
  278. package/dist/owner/owner-node-client.js +0 -184
  279. package/dist/owner/owner-node-client.js.map +0 -1
  280. package/dist/server/routes/bootstrap-node-validation.d.ts +0 -115
  281. package/dist/server/routes/bootstrap-node-validation.js +0 -197
  282. package/dist/server/routes/bootstrap-node-validation.js.map +0 -1
  283. package/dist/server/routes/grants-admin.d.ts +0 -29
  284. package/dist/server/routes/grants-admin.js +0 -58
  285. package/dist/server/routes/grants-admin.js.map +0 -1
  286. package/dist/server/routes/grants.d.ts +0 -28
  287. package/dist/server/routes/grants.js +0 -165
  288. package/dist/server/routes/grants.js.map +0 -1
  289. package/dist/server/routes/provision-request-validation.d.ts +0 -45
  290. package/dist/server/routes/provision-request-validation.js +0 -97
  291. package/dist/server/routes/provision-request-validation.js.map +0 -1
  292. package/dist/server/routes/strands.d.ts +0 -20
  293. package/dist/server/routes/strands.js +0 -38
  294. package/dist/server/routes/strands.js.map +0 -1
  295. package/dist/server/routes/trust-circle.d.ts +0 -17
  296. package/dist/server/routes/trust-circle.js +0 -35
  297. package/dist/server/routes/trust-circle.js.map +0 -1
  298. package/dist/strands/index.d.ts +0 -7
  299. package/dist/strands/index.js +0 -6
  300. package/dist/strands/index.js.map +0 -1
  301. package/dist/strands/strand-service.d.ts +0 -50
  302. package/dist/strands/strand-service.js +0 -103
  303. package/dist/strands/strand-service.js.map +0 -1
  304. package/dist/strands/types.d.ts +0 -93
  305. package/dist/strands/types.js +0 -23
  306. package/dist/strands/types.js.map +0 -1
  307. package/dist/ui/assets/index-C6nELNfC.js +0 -23
  308. package/dist/ui/assets/index-C6nELNfC.js.map +0 -1
  309. package/dist/ui/assets/index-TtIYSeZO.css +0 -1
  310. package/src/__tests__/cli-invite.smoke.test.ts +0 -192
  311. package/src/__tests__/host-owner.smoke.test.ts +0 -123
  312. package/src/__tests__/orchestrator-owner.test.ts +0 -234
  313. package/src/__tests__/orchestrator-pin-keys.test.ts +0 -152
  314. package/src/auth/__tests__/duration.test.ts +0 -28
  315. package/src/auth/__tests__/self-label.test.ts +0 -85
  316. package/src/auth/__tests__/trust-circle-integration.test.ts +0 -152
  317. package/src/auth/__tests__/trust-circle-store.test.ts +0 -115
  318. package/src/auth/__tests__/trust-circle.test.ts +0 -445
  319. package/src/auth/duration.ts +0 -33
  320. package/src/auth/index.ts +0 -21
  321. package/src/auth/self-label.ts +0 -74
  322. package/src/auth/trust-circle-store.ts +0 -155
  323. package/src/auth/trust-circle.ts +0 -395
  324. package/src/auth/types.ts +0 -99
  325. package/src/donation/__tests__/donation-service.test.ts +0 -1193
  326. package/src/donation/__tests__/donation-supervisor.test.ts +0 -548
  327. package/src/donation/__tests__/grant-service.test.ts +0 -213
  328. package/src/donation/__tests__/grant-store.test.ts +0 -113
  329. package/src/donation/donation-service.ts +0 -1033
  330. package/src/donation/donation-store.ts +0 -176
  331. package/src/donation/donation-supervisor.ts +0 -411
  332. package/src/donation/grant-service.ts +0 -252
  333. package/src/donation/grant-store.ts +0 -152
  334. package/src/donation/index.ts +0 -65
  335. package/src/donation/types.ts +0 -260
  336. package/src/owner/__tests__/owner-node-client.test.ts +0 -194
  337. package/src/owner/index.ts +0 -12
  338. package/src/owner/owner-node-client.ts +0 -259
  339. package/src/server/__tests__/bootstrap-node-validation.test.ts +0 -138
  340. package/src/server/__tests__/grants-admin-route.test.ts +0 -171
  341. package/src/server/__tests__/grants-route.test.ts +0 -394
  342. package/src/server/__tests__/strands-route.test.ts +0 -234
  343. package/src/server/routes/bootstrap-node-validation.ts +0 -206
  344. package/src/server/routes/grants-admin.ts +0 -74
  345. package/src/server/routes/grants.ts +0 -193
  346. package/src/server/routes/provision-request-validation.ts +0 -105
  347. package/src/server/routes/strands.ts +0 -54
  348. package/src/server/routes/trust-circle.ts +0 -49
  349. package/src/strands/__tests__/strand-service.test.ts +0 -165
  350. package/src/strands/index.ts +0 -14
  351. package/src/strands/strand-service.ts +0 -135
  352. package/src/strands/types.ts +0 -102
@@ -0,0 +1,475 @@
1
+ /**
2
+ * HostedNodeSupervisor unit tests — the component that notices a hosted node is
3
+ * no longer running and calls `HostedNodeService.respawn`, backs off between
4
+ * attempts, and eventually gives up.
5
+ *
6
+ * Exercised against the shared `FakeOrchestrator` (no real child processes), a
7
+ * real on-disk `HostedNodeStore`, and an injected clock — so backoff and the
8
+ * healthy-reset window are asserted without any wall-clock waiting.
9
+ *
10
+ * What is NOT covered here: that a really-respawned child rejoins its cadre.
11
+ * That is the cross-package `cadre-host-join-by-qr` integration scenario.
12
+ */
13
+
14
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
15
+ import { mkdtempSync, rmSync } from 'node:fs';
16
+ import { tmpdir } from 'node:os';
17
+ import { join } from 'node:path';
18
+
19
+ import { HostedNodeService } from '../hosted-node-service.js';
20
+ import { HostedNodeStore } from '../hosted-node-store.js';
21
+ import {
22
+ HostedNodeSupervisor,
23
+ HOSTED_NODE_RESPAWN_HEALTHY_MS,
24
+ HOSTED_NODE_RESPAWN_MAX_ATTEMPTS,
25
+ } from '../hosted-node-supervisor.js';
26
+ import type { HostedNode, HostedNodeChange, HostedNodeView } from '../types.js';
27
+ import { HostedNodeError } from '../types.js';
28
+ import { FakeOrchestrator } from './fake-orchestrator.js';
29
+ import { encodedTestInvitation } from './test-invitation.js';
30
+
31
+ let tmpRoot: string;
32
+
33
+ beforeEach(() => {
34
+ tmpRoot = mkdtempSync(join(tmpdir(), 'cadre-host-hosted-sup-'));
35
+ });
36
+
37
+ afterEach(() => {
38
+ try { rmSync(tmpRoot, { recursive: true, force: true }); } catch { /* ignore */ }
39
+ });
40
+
41
+ /** Everything one test needs, sharing a single mutable clock. */
42
+ interface Harness {
43
+ orch: FakeOrchestrator;
44
+ store: HostedNodeStore;
45
+ service: HostedNodeService;
46
+ supervisor: HostedNodeSupervisor;
47
+ changes: HostedNodeChange[];
48
+ /** Move the shared clock forward. */
49
+ advance: (ms: number) => void;
50
+ nowMs: () => number;
51
+ /** Start one node waiting to be claimed. */
52
+ join: () => Promise<HostedNodeView>;
53
+ }
54
+
55
+ const START_MS = Date.parse('2026-01-01T00:00:00.000Z');
56
+
57
+ function makeHarness(store?: HostedNodeStore): Harness {
58
+ let nowMs = START_MS;
59
+ const now = (): Date => new Date(nowMs);
60
+
61
+ const orch = new FakeOrchestrator();
62
+ const theStore = store ?? new HostedNodeStore(join(tmpRoot, 'hosted'));
63
+ const service = new HostedNodeService({
64
+ orchestrator: orch,
65
+ store: theStore,
66
+ addresses: { publicAddressesFor: () => [], getStatus: () => ({ nodes: [], gateway: { lanAddress: null }, network: { mode: 'lan' } }) },
67
+ primaryLan: async () => undefined,
68
+ now,
69
+ });
70
+ const changes: HostedNodeChange[] = [];
71
+ service.onChange((c) => changes.push(c));
72
+ const supervisor = new HostedNodeSupervisor({ service, store: theStore, orchestrator: orch, now });
73
+
74
+ return {
75
+ orch,
76
+ store: theStore,
77
+ service,
78
+ supervisor,
79
+ changes,
80
+ advance: (ms) => { nowMs += ms; },
81
+ nowMs: () => nowMs,
82
+ join: () => service.join(),
83
+ };
84
+ }
85
+
86
+ /** Mark a record claimed without going through the (fetch-driven) status watcher. */
87
+ function markJoined(store: HostedNodeStore, id: string): void {
88
+ store.put({ ...requireNode(store, id), status: 'joined', partyId: 'party-P', ownerKey: 'owner' });
89
+ }
90
+
91
+ function requireNode(store: HostedNodeStore, id: string): HostedNode {
92
+ const node = store.get(id);
93
+ if (!node) throw new Error(`no hosted node ${id}`);
94
+ return node;
95
+ }
96
+
97
+ function dockerIdOf(node: { dockerId?: string }): string {
98
+ if (!node.dockerId) throw new Error('hosted node has no dockerId');
99
+ return node.dockerId;
100
+ }
101
+
102
+ /** Let queued fire-and-forget passes run. */
103
+ function flush(): Promise<void> {
104
+ return new Promise((res) => setTimeout(res, 5));
105
+ }
106
+
107
+ /** A store whose every read fails — a malformed `hosted-nodes.json` on disk. */
108
+ class UnreadableStore extends HostedNodeStore {
109
+ override list(): HostedNode[] {
110
+ throw new HostedNodeError('storage_error', 'hosted-nodes file is not valid JSON');
111
+ }
112
+ }
113
+
114
+ describe('HostedNodeSupervisor.reconcile', () => {
115
+ it('respawns a joined-but-stopped node, keeping its status and swapping its handle', async () => {
116
+ const h = makeHarness();
117
+ const view = await h.join();
118
+ markJoined(h.store, view.id);
119
+ h.orch.crash(dockerIdOf(view));
120
+
121
+ const respawned = await h.supervisor.reconcile();
122
+
123
+ expect(respawned).toEqual([view.id]);
124
+ const stored = requireNode(h.store, view.id);
125
+ expect(stored.dockerId).toBe('dock_2');
126
+ expect(stored.status).toBe('joined');
127
+ expect(h.orch.createCalls).toHaveLength(2);
128
+ });
129
+
130
+ it('respawns an unclaimed node whose handle is dead with the record\'s secret, on the previous handle\'s ports', async () => {
131
+ const h = makeHarness();
132
+ const view = await h.join();
133
+ const { join: joinedBy } = requireNode(h.store, view.id);
134
+ const secret = joinedBy.kind === 'claim' ? joinedBy.secret : undefined;
135
+ const portsBefore = h.orch.getNode(view.id)!.ports;
136
+ // A host restart that found the child dead: the handle is there, the process is not.
137
+ h.orch.crash(dockerIdOf(view));
138
+
139
+ await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
140
+
141
+ // The QR code already shown names this secret and these ports, so both must hold.
142
+ expect(h.orch.createCalls[1]).toMatchObject({ containerId: view.id, partyId: 'unclaimed', claimSecret: secret });
143
+ expect(h.orch.getNode(view.id)!.ports).toEqual(portsBefore);
144
+ expect(requireNode(h.store, view.id)).toMatchObject({ status: 'unclaimed', dockerId: 'dock_2' });
145
+ });
146
+
147
+ it('respawns a joining invitation node with its invitation, and a joined one without it', async () => {
148
+ const h = makeHarness();
149
+ const invitation = encodedTestInvitation('party-P');
150
+ const view = await h.service.join({ invitation });
151
+ h.orch.crash(dockerIdOf(view));
152
+
153
+ await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
154
+ // Still joining: the child redeems again, and a member answers a node that already got in as accepted.
155
+ expect(h.orch.createCalls[1]).toMatchObject({ containerId: view.id, partyId: 'party-P', invitation });
156
+
157
+ // Joined: a member whose rows are in its own database, and whose invitation may since have expired.
158
+ h.store.put({ ...requireNode(h.store, view.id), status: 'joined' });
159
+ h.orch.crash(dockerIdOf(requireNode(h.store, view.id)));
160
+ h.advance(HOSTED_NODE_RESPAWN_HEALTHY_MS);
161
+
162
+ await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
163
+ expect(h.orch.createCalls[2]).toEqual({ containerId: view.id, partyId: 'party-P', profile: 'storage' });
164
+ });
165
+
166
+ it('leaves a running node alone', async () => {
167
+ const h = makeHarness();
168
+ const view = await h.join();
169
+ markJoined(h.store, view.id);
170
+
171
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
172
+ expect(h.orch.createCalls).toHaveLength(1);
173
+ });
174
+
175
+ it('never respawns a node the host gave up on', async () => {
176
+ const h = makeHarness();
177
+ const view = await h.join();
178
+ h.store.put({ ...requireNode(h.store, view.id), status: 'error', error: 'gave up' });
179
+ h.orch.crash(dockerIdOf(view));
180
+
181
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
182
+ expect(h.orch.createCalls).toHaveLength(1);
183
+ });
184
+
185
+ it('honours the backoff window, then attempts again once the clock passes it', async () => {
186
+ const h = makeHarness();
187
+ const view = await h.join();
188
+ markJoined(h.store, view.id);
189
+ h.orch.crash(dockerIdOf(view));
190
+ h.orch.failCreate = true;
191
+
192
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
193
+ expect(h.orch.createCalls).toHaveLength(2);
194
+ expect(requireNode(h.store, view.id).respawn?.attempts).toBe(1);
195
+
196
+ // attempts = 1 → base * 2^1 = 10s. One second later is still too soon.
197
+ h.advance(1_000);
198
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
199
+ expect(h.orch.createCalls).toHaveLength(2);
200
+ expect(requireNode(h.store, view.id).respawn?.attempts).toBe(1);
201
+
202
+ h.advance(10_000);
203
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
204
+ expect(h.orch.createCalls).toHaveLength(3);
205
+ expect(requireNode(h.store, view.id).respawn?.attempts).toBe(2);
206
+ });
207
+
208
+ it('gives up after the attempt cap: record → error, child stopped but not reclaimed, change published', async () => {
209
+ const h = makeHarness();
210
+ const view = await h.join();
211
+ markJoined(h.store, view.id);
212
+ h.orch.crash(dockerIdOf(view));
213
+ h.orch.failCreate = true;
214
+ h.changes.length = 0;
215
+
216
+ for (let i = 0; i < HOSTED_NODE_RESPAWN_MAX_ATTEMPTS; i++) {
217
+ await h.supervisor.reconcile();
218
+ // Well past the longest backoff, so every pass gets to attempt.
219
+ h.advance(10 * 60_000);
220
+ }
221
+
222
+ const stored = requireNode(h.store, view.id);
223
+ expect(stored.status).toBe('error');
224
+ expect(stored.respawn?.attempts).toBe(HOSTED_NODE_RESPAWN_MAX_ATTEMPTS);
225
+ expect(stored.error).toContain(`${HOSTED_NODE_RESPAWN_MAX_ATTEMPTS} attempts`);
226
+ expect(stored.error).toContain('spawn boom');
227
+ // The workdir holds the identity key the node's cadre approved — the
228
+ // give-up path stops the child but must never reclaim it.
229
+ //
230
+ // Doubles as the standing guard on `FakeOrchestrator`'s drop being
231
+ // success-only (mirroring `restoreDroppedHandles`): every create here fails,
232
+ // so a fake that dropped the prior handle regardless would leave `giveUp`
233
+ // with nothing to stop, and this line fails with
234
+ // `expected [] to include 'dock_1'`.
235
+ expect(h.orch.stopped).toContain(view.dockerId);
236
+ expect(h.orch.removed).toEqual([]);
237
+ expect(h.changes).toEqual([{ kind: 'changed', id: view.id }]);
238
+
239
+ // `error` is terminal: no further attempts.
240
+ const createsAtGiveUp = h.orch.createCalls.length;
241
+ h.advance(10 * 60_000);
242
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
243
+ expect(h.orch.createCalls).toHaveLength(createsAtGiveUp);
244
+ });
245
+
246
+ // A spawn that succeeds and then dies at once (a crash on boot, a port clash)
247
+ // never throws out of `respawn`, so a give-up checked only on a throw would
248
+ // respawn such a node forever.
249
+ it('gives up on a node whose every respawn spawns but does not stay up', async () => {
250
+ const h = makeHarness();
251
+ const view = await h.join();
252
+ markJoined(h.store, view.id);
253
+ h.orch.crash(dockerIdOf(view));
254
+ h.orch.onSpawned = (dockerId) => { h.orch.crash(dockerId); };
255
+
256
+ for (let i = 0; i < HOSTED_NODE_RESPAWN_MAX_ATTEMPTS; i++) {
257
+ await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
258
+ // Well past the longest backoff, so every pass gets to act.
259
+ h.advance(10 * 60_000);
260
+ }
261
+ expect(h.orch.createCalls).toHaveLength(1 + HOSTED_NODE_RESPAWN_MAX_ATTEMPTS);
262
+ expect(requireNode(h.store, view.id).status).toBe('joined');
263
+
264
+ // The budget is spent and the last respawn died too: this pass gives up
265
+ // instead of spawning again.
266
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
267
+ const stored = requireNode(h.store, view.id);
268
+ expect(h.orch.createCalls).toHaveLength(1 + HOSTED_NODE_RESPAWN_MAX_ATTEMPTS);
269
+ expect(stored.status).toBe('error');
270
+ expect(stored.respawn?.attempts).toBe(HOSTED_NODE_RESPAWN_MAX_ATTEMPTS);
271
+ expect(stored.error).toContain('did not stay running');
272
+ // The child the record names is stopped, never reclaimed.
273
+ expect(h.orch.stopped).toEqual([stored.dockerId]);
274
+ expect(h.orch.removed).toEqual([]);
275
+
276
+ h.advance(10 * 60_000);
277
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
278
+ expect(h.orch.createCalls).toHaveLength(1 + HOSTED_NODE_RESPAWN_MAX_ATTEMPTS);
279
+ });
280
+
281
+ it('refills the attempt budget once a respawned node has stayed up', async () => {
282
+ const h = makeHarness();
283
+ const view = await h.join();
284
+ h.store.put({
285
+ ...requireNode(h.store, view.id),
286
+ status: 'joined',
287
+ respawn: { attempts: 3, lastAttemptAt: new Date(h.nowMs()).toISOString() },
288
+ });
289
+
290
+ // Still inside the healthy window — the crash loop's count stands.
291
+ h.advance(HOSTED_NODE_RESPAWN_HEALTHY_MS - 1_000);
292
+ await h.supervisor.reconcile();
293
+ expect(requireNode(h.store, view.id).respawn?.attempts).toBe(3);
294
+
295
+ h.advance(2_000);
296
+ await h.supervisor.reconcile();
297
+ expect(requireNode(h.store, view.id).respawn?.attempts).toBe(0);
298
+ });
299
+
300
+ it('leaves a still-spawning record alone — join owns that child', async () => {
301
+ const h = makeHarness();
302
+ // A handle written by a join that has not yet flipped to unclaimed.
303
+ // Respawning it here would race that join and strand the record.
304
+ h.store.put({
305
+ id: 'hn_inflight', join: { kind: 'claim', secret: 's' }, partyId: 'unclaimed', profile: 'storage',
306
+ status: 'spawning', dockerId: 'dock_inflight',
307
+ createdAt: new Date(START_MS).toISOString(), updatedAt: new Date(START_MS).toISOString(),
308
+ });
309
+
310
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
311
+ expect(h.orch.createCalls).toEqual([]);
312
+ expect(requireNode(h.store, 'hn_inflight').status).toBe('spawning');
313
+ });
314
+
315
+ it('skips a record that has no orchestrator handle yet', async () => {
316
+ const h = makeHarness();
317
+ h.store.put({
318
+ id: 'hn_nohandle', join: { kind: 'claim', secret: 's' }, partyId: 'unclaimed', profile: 'storage',
319
+ status: 'unclaimed',
320
+ createdAt: new Date(START_MS).toISOString(), updatedAt: new Date(START_MS).toISOString(),
321
+ });
322
+
323
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
324
+ expect(h.orch.createCalls).toEqual([]);
325
+ });
326
+
327
+ it('does not undo a claim that lands while the pass is mid-flight', async () => {
328
+ const h = makeHarness();
329
+ const view = await h.join();
330
+ h.store.put({
331
+ ...requireNode(h.store, view.id),
332
+ respawn: { attempts: 3, lastAttemptAt: new Date(h.nowMs()).toISOString() },
333
+ });
334
+ h.advance(HOSTED_NODE_RESPAWN_HEALTHY_MS + 1_000);
335
+
336
+ // The watcher's claim write lands between the pass's store snapshot and the
337
+ // budget-refill write — the refill must merge, not replay a stale row.
338
+ h.orch.onIsRunning = () => {
339
+ h.orch.onIsRunning = undefined;
340
+ markJoined(h.store, view.id);
341
+ };
342
+
343
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
344
+ const stored = requireNode(h.store, view.id);
345
+ expect(stored.status).toBe('joined');
346
+ expect(stored.partyId).toBe('party-P');
347
+ expect(stored.respawn?.attempts).toBe(0);
348
+ });
349
+
350
+ it('leaves a record removed mid-attempt alone instead of recreating it as error', async () => {
351
+ const h = makeHarness();
352
+ const view = await h.join();
353
+ h.store.put({
354
+ ...requireNode(h.store, view.id),
355
+ status: 'joined',
356
+ // One attempt short of the cap (at the cap, the pass would give up before
357
+ // attempting), and long past the longest backoff — so the next failure
358
+ // lands straight in the give-up path.
359
+ respawn: {
360
+ attempts: HOSTED_NODE_RESPAWN_MAX_ATTEMPTS - 1,
361
+ lastAttemptAt: new Date(h.nowMs() - 10 * 60_000).toISOString(),
362
+ },
363
+ });
364
+ h.orch.crash(dockerIdOf(view));
365
+ h.orch.failCreate = true;
366
+ // The admin removes the node while the respawn's spawn is in flight.
367
+ h.orch.onCreate = () => { h.store.remove(view.id); };
368
+
369
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
370
+
371
+ expect(h.store.get(view.id)).toBeUndefined();
372
+ expect(h.orch.stopped).toEqual([]);
373
+ });
374
+
375
+ it('does not count a respawn abandoned mid-spawn as a failed attempt', async () => {
376
+ const h = makeHarness();
377
+ const view = await h.join();
378
+ markJoined(h.store, view.id);
379
+ h.orch.crash(dockerIdOf(view));
380
+ // The admin removes the node while the respawn's spawn is in flight.
381
+ h.orch.createDelayMs = 20;
382
+ let removed: Promise<void> | undefined;
383
+ h.orch.onCreate = () => { removed ??= h.service.remove(view.id); };
384
+
385
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
386
+ await removed;
387
+
388
+ // Nothing threw, so no attempt was persisted and give-up never ran; the
389
+ // abandoned child is stopped and reclaimed, not left holding ports.
390
+ expect(h.store.get(view.id)).toBeUndefined();
391
+ expect(h.orch.stopped).toContain('dock_2');
392
+ expect(h.orch.removed).toContain('dock_2');
393
+ });
394
+
395
+ it('survives a pass over a store it cannot read', async () => {
396
+ const h = makeHarness(new UnreadableStore(join(tmpRoot, 'hosted')));
397
+
398
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
399
+ expect(h.orch.createCalls).toEqual([]);
400
+ });
401
+
402
+ it('serializes overlapping passes so one id is never double-spawned', async () => {
403
+ const h = makeHarness();
404
+ const view = await h.join();
405
+ markJoined(h.store, view.id);
406
+ h.orch.crash(dockerIdOf(view));
407
+ h.orch.createDelayMs = 20;
408
+
409
+ const [first, second] = await Promise.all([
410
+ h.supervisor.reconcile(),
411
+ h.supervisor.reconcile(),
412
+ ]);
413
+
414
+ // Whichever pass wins the tail respawns; the other then finds it running.
415
+ expect([...first, ...second]).toEqual([view.id]);
416
+ // The original join plus exactly one respawn.
417
+ expect(h.orch.createCalls).toHaveLength(2);
418
+ });
419
+ });
420
+
421
+ describe('HostedNodeSupervisor.restart', () => {
422
+ it('stops and respawns a running node without spending its respawn budget', async () => {
423
+ const h = makeHarness();
424
+ const view = await h.join();
425
+ const respawn = { attempts: 2, lastAttemptAt: new Date(h.nowMs()).toISOString() };
426
+ const before: HostedNode = { ...requireNode(h.store, view.id), status: 'joined', partyId: 'party-P', respawn };
427
+ h.store.put(before);
428
+ h.advance(60_000);
429
+
430
+ await h.supervisor.restart(view.id);
431
+
432
+ expect(h.orch.stopped).toEqual([view.dockerId]);
433
+ const after = requireNode(h.store, view.id);
434
+ expect(after).toMatchObject({ status: 'joined', dockerId: 'dock_2', respawn, updatedAt: before.updatedAt });
435
+ });
436
+ });
437
+
438
+ describe('HostedNodeSupervisor start/stop', () => {
439
+ it('sweeps at startup and again on a child exit', async () => {
440
+ const h = makeHarness();
441
+ const view = await h.join();
442
+ markJoined(h.store, view.id);
443
+ h.orch.crash(dockerIdOf(view));
444
+
445
+ h.supervisor.start();
446
+ try {
447
+ // Queued behind the startup pass, so awaiting it proves that pass ran.
448
+ await h.supervisor.reconcile();
449
+ expect(requireNode(h.store, view.id).dockerId).toBe('dock_2');
450
+
451
+ // Now the exit-event trigger, with no manual reconcile in between.
452
+ h.advance(60_000);
453
+ h.orch.crash('dock_2');
454
+ await flush();
455
+ expect(requireNode(h.store, view.id).dockerId).toBe('dock_3');
456
+ } finally {
457
+ h.supervisor.stop();
458
+ }
459
+ });
460
+
461
+ it('stops reacting to exits after stop()', async () => {
462
+ const h = makeHarness();
463
+ const view = await h.join();
464
+ markJoined(h.store, view.id);
465
+
466
+ h.supervisor.start();
467
+ await h.supervisor.reconcile();
468
+ h.supervisor.stop();
469
+
470
+ h.orch.crash(dockerIdOf(view));
471
+ await flush();
472
+ // The exit listener is gone, so the crash goes unnoticed until the next start.
473
+ expect(requireNode(h.store, view.id).dockerId).toBe(view.dockerId);
474
+ });
475
+ });
@@ -0,0 +1,33 @@
1
+ /**
2
+ * A cadre invitation for the hosted-node unit tests: well-formed enough for
3
+ * `decodeCadreInvitation`, which checks shape only. Nothing on the host verifies its
4
+ * signatures; a member does, and the integration scenario covers that.
5
+ */
6
+
7
+ import { encodeCadreInvitation } from '@serfab/cadre-core';
8
+
9
+ /** The invitation's issuer: the owner key a joined invitation node is shown under. */
10
+ export const ISSUER_KEY = Buffer.alloc(32, 9).toString('base64url');
11
+
12
+ /** The member a test reports as having admitted the node. */
13
+ export const MEMBER_PEER_ID = '12D3KooWQYhTNQdmr3ArTeUHRYzFg94BKyTkoWBDWez9kSCVe2Xo';
14
+
15
+ export function encodedTestInvitation(partyId: string): string {
16
+ return encodeCadreInvitation({
17
+ v: 1,
18
+ partyId,
19
+ invitePrivateKey: Buffer.alloc(32, 3).toString('base64url'),
20
+ invite: {
21
+ key: Buffer.alloc(32, 4).toString('base64url'),
22
+ peerId: null,
23
+ grantsOwner: false,
24
+ expiresAt: null,
25
+ totalUses: 1,
26
+ stampId: 'stamp-1',
27
+ issuerKey: ISSUER_KEY,
28
+ issuerSig: 'signature',
29
+ },
30
+ ownerKeys: [ISSUER_KEY],
31
+ members: [`/ip4/127.0.0.1/tcp/4001/ws/p2p/${MEMBER_PEER_ID}`],
32
+ });
33
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * What the QR code of a node waiting to be claimed carries, and the address list behind it.
3
+ * `HostedNodeService.claimDetails` reads the child's `/status` and hands it here.
4
+ */
5
+
6
+ import { encodeNodeClaimPayload, selectNodeClaimAddresses, withClaimDestination } from '@serfab/cadre-core';
7
+
8
+ import type { ClaimAddressSettings } from '../installer/config.js';
9
+ import type { NetworkMode, NodeReachability } from '../nat/types.js';
10
+ import type { NodeStatus } from './node-status.js';
11
+ import { HostedNodeError } from './types.js';
12
+
13
+ /** What `claimDetails` answers: the QR payload and its parts. */
14
+ export interface ClaimDetails {
15
+ /** `encodeNodeClaimPayload` of the three fields below — the text the QR code carries. */
16
+ payload: string;
17
+ peerId: string;
18
+ /** Public names (or public IPs when there is no name), then the one LAN address; see {@link dialAddressesFor}. */
19
+ multiaddrs: string[];
20
+ /** The NAT layer's verdict for the node, or null when it has no entry yet. A phone at home reaches the LAN address either way. */
21
+ reachability: NodeReachability | null;
22
+ }
23
+
24
+ /** The NAT layer's answers the claim details need. `NatService` satisfies this. */
25
+ export interface HostedNodeAddressSource {
26
+ /** The node's public multiaddrs (no `/p2p/` suffix), TCP then WebSocket. */
27
+ publicAddressesFor(nodeId: string, ports: { p2p: number; ws?: number }): string[];
28
+ /**
29
+ * `gateway.lanAddress` is this machine's address on the router's subnet, when a UPnP gateway
30
+ * answered; `network.mode` is whether it sits behind a router (`lan`) or holds a public IPv4.
31
+ */
32
+ getStatus(): { nodes: NodeReachability[]; gateway: { lanAddress: string | null }; network: { mode: NetworkMode } };
33
+ }
34
+
35
+ /** One node's claim details, from its record's secret, its `/status`, and its ports. */
36
+ export interface ClaimDetailsInput {
37
+ id: string;
38
+ secret: string;
39
+ status: NodeStatus;
40
+ /** The orchestrator handle's ports; absent, the code carries LAN addresses only. */
41
+ ports: { p2p: number; ws?: number } | undefined;
42
+ addresses: HostedNodeAddressSource;
43
+ /** `host.config.json`'s `claimAddresses.addrs`: exact addresses replacing the automatic choice. */
44
+ exactAddrs?: readonly string[];
45
+ /** The LAN address to keep, as {@link claimLanAddress} resolved it. */
46
+ lan: string | null | undefined;
47
+ }
48
+
49
+ /**
50
+ * The claim details for a node whose `/status` answered. `503 node_unavailable` while the
51
+ * node reports no address a phone could dial (callers poll).
52
+ */
53
+ export function buildClaimDetails(input: ClaimDetailsInput): ClaimDetails {
54
+ const { id, status, addresses } = input;
55
+ const multiaddrs = dialAddressesFor(input);
56
+ if (multiaddrs.length === 0) {
57
+ throw new HostedNodeError('node_unavailable', `Hosted node ${id} reports no address a phone could dial yet`);
58
+ }
59
+ return {
60
+ payload: encodeNodeClaimPayload({ peerId: status.peerId, multiaddrs, secret: input.secret }),
61
+ peerId: status.peerId,
62
+ multiaddrs,
63
+ reachability: addresses.getStatus().nodes.find((n) => n.nodeId === id) ?? null,
64
+ };
65
+ }
66
+
67
+ /**
68
+ * The LAN address a node code keeps (`selectNodeClaimAddresses`' `lan`), from `claimAddresses.lan`:
69
+ * `'none'` is null; an IP is itself; `'auto'` (default) is null in public-IP mode (no phone shares
70
+ * a LAN with a VPS), else the gateway's `lanAddress`, else the machine's primary address
71
+ * (`primaryLan`, probed only then), else undefined (keep every private address).
72
+ */
73
+ export async function claimLanAddress(
74
+ settings: ClaimAddressSettings | undefined,
75
+ addresses: HostedNodeAddressSource,
76
+ primaryLan: () => Promise<string | undefined>,
77
+ ): Promise<string | null | undefined> {
78
+ const lan = settings?.lan ?? 'auto';
79
+ if (lan === 'none') return null;
80
+ if (lan !== 'auto') return lan;
81
+ const { network, gateway } = addresses.getStatus();
82
+ if (network.mode === 'public') return null;
83
+ return gateway.lanAddress ?? await primaryLan();
84
+ }
85
+
86
+ /**
87
+ * The addresses the QR code names, in dial order. A phone dials each in turn on its own
88
+ * timeout, so every address it cannot reach delays a failing claim and enlarges the code.
89
+ *
90
+ * - With `exactAddrs`, exactly those, each given the node's peer id.
91
+ * - Otherwise cadre-core's `selectNodeClaimAddresses` over the NAT layer's public addresses
92
+ * and the node's own (`/status`): WebSocket and relay only (a phone has no TCP), public
93
+ * names before raw public IPs, and of the private addresses only `lan`. Docker bridges,
94
+ * VPNs and other interfaces a phone cannot reach are left out.
95
+ */
96
+ function dialAddressesFor({ id, status, ports, addresses, exactAddrs, lan }: ClaimDetailsInput): string[] {
97
+ // NOTE: `claimAddresses.addrs` is host-wide, so every hosted node's code carries the same
98
+ // addresses with its own peer id; that reaches each node only if they route per node (one
99
+ // node, or a port per node). If several nodes behind one proxy is reported, make it per node.
100
+ if (exactAddrs && exactAddrs.length > 0) return [...new Set(exactAddrs.map((a) => withClaimDestination(a, status.peerId)))];
101
+ const publicAddrs = ports ? addresses.publicAddressesFor(id, ports) : [];
102
+ return selectNodeClaimAddresses([...publicAddrs, ...status.multiaddrs], status.peerId, { lan });
103
+ }