@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,814 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import debug from 'debug';
3
+
4
+ import { CLAIM_SECRET_BYTES, decodeCadreInvitation, type CadreInvitation } from '@serfab/cadre-core';
5
+ import { primaryLanAddress } from '@serfab/cadre-core/primary-lan-address';
6
+ import type { Orchestrator, OrchestratorCreateResult } from '@serfab/cadre-provider';
7
+
8
+ import type { HostedSpawnRequest, ManagedNodeInfo, NodeStateListener } from '../orchestrator/types.js';
9
+ import type { ClaimAddressSettings } from '../installer/config.js';
10
+ import { buildClaimDetails, claimLanAddress, type ClaimDetails, type HostedNodeAddressSource } from './claim-details.js';
11
+ import type { HostedNodeStore } from './hosted-node-store.js';
12
+ import { HostedNodeWatcher } from './hosted-node-watcher.js';
13
+ import { PLACEHOLDER_PARTY, errorMessage, readNodeStatus, statusUrlFor } from './node-status.js';
14
+ import type {
15
+ HostedNode,
16
+ HostedNodeChange,
17
+ HostedNodeChangeListener,
18
+ HostedNodeJoin,
19
+ HostedNodeStatus,
20
+ HostedNodeView,
21
+ } from './types.js';
22
+ import { HostedNodeError } from './types.js';
23
+
24
+ const log = debug('cadre:host:hosted-node-service');
25
+
26
+ /**
27
+ * The only statuses a node may come back from. An allowlist, not a terminal
28
+ * denylist: `error` is a node the host gave up on, and `spawning` is a join still
29
+ * in flight — replaying its spawn would race that join and strand the record in
30
+ * `spawning`, which only the stuck-`spawning` reap collects.
31
+ *
32
+ * Checked twice in {@link HostedNodeService.respawn} — once on entry, once after
33
+ * the spawn — so the "may this node come back" rule is stated exactly once.
34
+ */
35
+ const RESPAWNABLE_STATUSES: ReadonlySet<HostedNodeStatus> = new Set<HostedNodeStatus>([
36
+ 'unclaimed',
37
+ 'joining',
38
+ 'joined',
39
+ ]);
40
+
41
+ /**
42
+ * Age after which a record still stuck in `spawning` is marked `error` and its
43
+ * child, if any, reclaimed: the host wrote the row before starting the child, and
44
+ * a crash/kill in that window (or during the spawn itself) leaves nothing to
45
+ * advance it across a restart. A real spawn (identity key read/gen, port
46
+ * allocation, process spawn) completes in well under a second normally, so 5
47
+ * minutes is generously past "any plausible spawn" without risking a false reap
48
+ * of one still genuinely in flight under heavy load.
49
+ */
50
+ export const HOSTED_NODE_SPAWNING_TTL_MS = 5 * 60 * 1000;
51
+
52
+ /** How often the stuck-`spawning` reap runs while cadre-host is up. 5 minutes. */
53
+ export const HOSTED_NODE_REAP_SWEEP_MS = 5 * 60 * 1000;
54
+
55
+ /**
56
+ * Outcome of {@link HostedNodeService.respawn}:
57
+ *
58
+ * - `respawned` — a new child is up and the record now names its handles.
59
+ * - `abandoned` — the record was removed, or went `error`, while the spawn was in
60
+ * flight. The ending wins: the record is left exactly as the ending wrote it and
61
+ * the new child is cleaned up. `status` is the status that won, absent when the
62
+ * row is gone entirely.
63
+ */
64
+ export type RespawnResult =
65
+ | { outcome: 'respawned'; node: HostedNodeView }
66
+ | { outcome: 'abandoned'; status?: HostedNodeStatus };
67
+
68
+ /**
69
+ * The per-spawn fields a record carries for the child that currently exists.
70
+ * Whatever the record names here is what every later cleanup (`remove` → stop +
71
+ * reclaim) acts on, so a spawn that succeeded must land these on the record even
72
+ * when the surrounding operation then fails.
73
+ */
74
+ interface SpawnedHandles {
75
+ dockerId: string;
76
+ statusEndpoint: string;
77
+ }
78
+
79
+ /** A respawn's attempt counters — the record's `respawn` block, never absent. */
80
+ type RespawnAttempt = NonNullable<HostedNode['respawn']>;
81
+
82
+ /** Options for {@link HostedNodeService.respawn}. */
83
+ export interface RespawnOptions {
84
+ /**
85
+ * Whether this respawn spends one of the record's attempts. Default true: a crash
86
+ * respawn does, since the supervisor's backoff and give-up read the count. A
87
+ * deliberate restart of a running node (`HostedNodeSupervisor.restart`) passes false
88
+ * and leaves both the counters and `updatedAt` alone.
89
+ */
90
+ countAttempt?: boolean;
91
+ }
92
+
93
+ /**
94
+ * Orchestrator capabilities the service needs beyond the base `Orchestrator`.
95
+ * `createContainer` takes the claim secret. The rest are optional — only
96
+ * `HostProcessOrchestrator` implements them; absent on a test double or a future
97
+ * orchestrator, the cleanup degrades to terminalizing the record with nothing to
98
+ * reclaim, and the claim details carry LAN addresses only.
99
+ */
100
+ export interface HostedNodeOrchestrator extends Orchestrator {
101
+ createContainer(request: HostedSpawnRequest): Promise<OrchestratorCreateResult>;
102
+ /**
103
+ * Resolve a spawn's friendly containerId (== a hosted node's id) back to its
104
+ * current dockerId, so a stuck-`spawning` reap can find and reclaim a child that
105
+ * was actually spawned before the host died.
106
+ */
107
+ resolveDockerId?(containerId: string): string | undefined;
108
+ /**
109
+ * Remove the working directory a spawn created for `containerId` when no handle
110
+ * owns it — the cleanup of last resort for a record that never got a `dockerId`.
111
+ * Returns whether anything was removed. Refuses when a handle still resolves
112
+ * (that child's directory belongs to `removeContainer`).
113
+ */
114
+ reclaimWorkdir?(containerId: string): boolean;
115
+ /** The node's handle, for the ports its public addresses are built from. */
116
+ getNode?(idOrDockerId: string): ManagedNodeInfo | undefined;
117
+ /** The exit/start signal the status watcher follows. */
118
+ onStateChange?(listener: NodeStateListener): () => void;
119
+ }
120
+
121
+ /** What `join` takes: nothing for a node waiting to be claimed, or the invitation the node redeems. */
122
+ export interface JoinOptions {
123
+ /** An encoded cadre invitation (`encodeCadreInvitation`), as the owner's app copies it. */
124
+ invitation?: string;
125
+ }
126
+
127
+ /** Constructor options. */
128
+ export interface HostedNodeServiceOptions {
129
+ /** Orchestrator that spawns/stops the hosted child processes. */
130
+ orchestrator: HostedNodeOrchestrator;
131
+ /** Persistent record store (`hosted-nodes.json`). */
132
+ store: HostedNodeStore;
133
+ /** The NAT layer, for the node's public addresses and reachability verdict. */
134
+ addresses: HostedNodeAddressSource;
135
+ /** `host.config.json`'s `claimAddresses`, read on every claim-code request so an edit applies at once. */
136
+ claimAddressSettings?: () => ClaimAddressSettings | undefined;
137
+ /** The machine's primary address, the `lan: 'auto'` fallback when no UPnP gateway answered. */
138
+ primaryLan?: () => Promise<string | undefined>;
139
+ /** Clock override for tests. */
140
+ now?: () => Date;
141
+ }
142
+
143
+ /**
144
+ * HostedNodeService — the host's one action, "Join a cadre", and what follows from it.
145
+ *
146
+ * `join` starts a child waiting to be claimed, or one that redeems a cadre invitation;
147
+ * `claimDetails` reads a waiting node's addresses and builds the QR payload; the status
148
+ * watcher ({@link startWatching}) notices the claim or the redemption's outcome, and the
149
+ * node's liveness; `respawn` brings a dead child back as the same node with the same
150
+ * secret and ports; `retry` starts an invitation node again after no member could be
151
+ * reached; `remove` and `reset` end it. The host contributes capacity only: it never
152
+ * holds an owner key.
153
+ *
154
+ * **An ending that lands mid-operation wins.** Spawning a child takes seconds, and
155
+ * a `remove` can land inside that window. `hosted-nodes.json` is written a whole row
156
+ * at a time, so every long operation re-reads the record after its wait, decides
157
+ * against what is actually stored, and merges forward only the fields it itself
158
+ * produced — never the entry-time copy.
159
+ *
160
+ * **Respawns run one at a time** ({@link serializeRespawns}): the supervisor's passes and
161
+ * restarts and `retry` share one queue, since two overlapping respawns of one id both spawn
162
+ * a child and the second drops the first's orchestrator handle.
163
+ */
164
+ export class HostedNodeService {
165
+ private readonly orchestrator: HostedNodeOrchestrator;
166
+ private readonly store: HostedNodeStore;
167
+ private readonly addresses: HostedNodeAddressSource;
168
+ private readonly claimAddressSettings: () => ClaimAddressSettings | undefined;
169
+ private readonly primaryLan: () => Promise<string | undefined>;
170
+ private readonly now: () => Date;
171
+ private readonly listeners = new Set<HostedNodeChangeListener>();
172
+ private readonly watcher: HostedNodeWatcher;
173
+ /** Serialization tail for `join`, so two joins at once cannot interleave their store writes. */
174
+ private joinTail: Promise<void> = Promise.resolve();
175
+ /** Serialization tail for every respawn — see {@link serializeRespawns}. */
176
+ private respawnTail: Promise<void> = Promise.resolve();
177
+
178
+ constructor(opts: HostedNodeServiceOptions) {
179
+ this.orchestrator = opts.orchestrator;
180
+ this.store = opts.store;
181
+ this.addresses = opts.addresses;
182
+ this.claimAddressSettings = opts.claimAddressSettings ?? (() => undefined);
183
+ this.primaryLan = opts.primaryLan ?? primaryLanAddress;
184
+ this.now = opts.now ?? (() => new Date());
185
+ this.watcher = new HostedNodeWatcher({
186
+ store: this.store,
187
+ orchestrator: this.orchestrator,
188
+ now: this.now,
189
+ emit: (change) => this.emit(change),
190
+ });
191
+ log('HostedNodeService initialized');
192
+ }
193
+
194
+ /** Register a change listener (the server publishes each change as an SSE event). Returns an unsubscribe fn. */
195
+ onChange(listener: HostedNodeChangeListener): () => void {
196
+ this.listeners.add(listener);
197
+ return () => { this.listeners.delete(listener); };
198
+ }
199
+
200
+ /**
201
+ * Report a change to the listeners. Public for the supervisor's give-up, which
202
+ * writes the record itself; a listener that throws is logged, never propagated.
203
+ */
204
+ emit(change: HostedNodeChange): void {
205
+ for (const listener of this.listeners) {
206
+ try {
207
+ listener(change);
208
+ } catch (err) {
209
+ log('change listener threw for %s: %s', change.id, errorMessage(err));
210
+ }
211
+ }
212
+ }
213
+
214
+ /** Start following every node's `/status` (claims and liveness). Idempotent. */
215
+ startWatching(): void {
216
+ this.watcher.start();
217
+ }
218
+
219
+ stopWatching(): void {
220
+ this.watcher.stop();
221
+ }
222
+
223
+ /** One status pass now, awaited — for tests and callers that need the result before going on. */
224
+ pollStatuses(): Promise<void> {
225
+ return this.watcher.poll();
226
+ }
227
+
228
+ /**
229
+ * Start a node: write the record, spawn the child, and record its handles. Without an
230
+ * invitation the node waits to be claimed — a fresh claim secret, the placeholder
231
+ * party, `unclaimed`. With one it redeems the invitation — the invitation's party,
232
+ * `joining` — and an invitation that does not decode is `invalid_request` before
233
+ * anything is written. On any orchestrator failure the reserved resources are
234
+ * reclaimed and the record is marked `error`. Resolves once the child is spawned; its
235
+ * `/status` may take a few seconds more, which `claimDetails` reports as
236
+ * `node_unavailable`.
237
+ */
238
+ async join(opts: JoinOptions = {}): Promise<HostedNodeView> {
239
+ const invitation = opts.invitation === undefined ? undefined : decodeInvitation(opts.invitation);
240
+ return this.serializeJoin(() => this.joinLocked(invitation));
241
+ }
242
+
243
+ private async joinLocked(invitation: DecodedInvitation | undefined): Promise<HostedNodeView> {
244
+ const id = generateHostedNodeId();
245
+ const nowIso = this.now().toISOString();
246
+ const join: HostedNodeJoin = invitation
247
+ ? { kind: 'invitation', encoded: invitation.encoded }
248
+ : { kind: 'claim', secret: generateClaimSecret() };
249
+ const record: HostedNode = {
250
+ id,
251
+ join,
252
+ partyId: invitation ? invitation.decoded.partyId : PLACEHOLDER_PARTY,
253
+ profile: 'storage',
254
+ status: 'spawning',
255
+ createdAt: nowIso,
256
+ updatedAt: nowIso,
257
+ };
258
+ this.store.put(record);
259
+
260
+ // The spawn is the only step that can fail before anything is allocated, so
261
+ // it gets a `try` of its own — a wider one would swallow the abandon decision
262
+ // below and mark a removal as a host-side `error`.
263
+ let result: OrchestratorCreateResult;
264
+ try {
265
+ result = await this.orchestrator.createContainer(spawnRequestFor(record));
266
+ } catch (err) {
267
+ const message = errorMessage(err);
268
+ log('spawn of hosted node %s failed: %s', id, message);
269
+ this.markSpawnFailed(id, message);
270
+ throw new HostedNodeError('orchestrator_error', `Failed to start hosted node: ${message}`);
271
+ }
272
+
273
+ // Re-read: `record` predates the orchestrator round-trip (seconds of wall
274
+ // clock) and `store.put` replaces the whole row, so writing that copy back
275
+ // would resurrect a node removed while the spawn was in flight. The store is
276
+ // synchronous, so this read-decide-write is atomic against the event loop
277
+ // only as long as no `await` sneaks in between.
278
+ const current = this.store.get(id);
279
+ if (!current || current.status !== 'spawning') {
280
+ // The removal cleaned up nothing: the record named no `dockerId` yet, so
281
+ // `remove`'s stop-and-reclaim never ran and this child is the only thing
282
+ // holding the spawn's ports and workdir. Reclaim (not merely stop) — the
283
+ // workdir was created by this very spawn, so there is nothing to preserve.
284
+ log('hosted node %s went %s during its spawn — abandoning new child %s', id, current?.status ?? 'missing', result.dockerId);
285
+ await this.safeReclaim(result.dockerId);
286
+ throw current
287
+ ? new HostedNodeError('invalid_state', `Hosted node ${id} was ${current.status} before it finished starting`)
288
+ : new HostedNodeError('not_found', `No such hosted node: ${id}`);
289
+ }
290
+
291
+ const started: HostedNode = {
292
+ ...current,
293
+ ...handlesOf(result),
294
+ status: invitation ? 'joining' : 'unclaimed',
295
+ updatedAt: this.now().toISOString(),
296
+ };
297
+ try {
298
+ this.store.put(started);
299
+ } catch (err) {
300
+ const message = errorMessage(err);
301
+ log('recording hosted node %s failed: %s', id, message);
302
+ await this.safeReclaim(result.dockerId);
303
+ this.markSpawnFailed(id, message);
304
+ throw new HostedNodeError('orchestrator_error', `Failed to start hosted node: ${message}`);
305
+ }
306
+ log(invitation ? 'hosted node %s is up and redeeming its invitation' : 'hosted node %s is up and waiting to be claimed', id);
307
+ this.emit({ kind: 'added', id });
308
+ this.watcher.poke(id);
309
+ return redact(started);
310
+ }
311
+
312
+ /**
313
+ * Mark a still-`spawning` record as failed — and ONLY such a record. A row that
314
+ * was removed while the spawn was in flight must not be recreated.
315
+ *
316
+ * Best-effort (mirroring {@link storeRespawnAttempt}): we are already unwinding a
317
+ * spawn failure, and a store error here must not mask the error being reported
318
+ * to the caller.
319
+ */
320
+ private markSpawnFailed(id: string, message: string): void {
321
+ try {
322
+ const current = this.store.get(id);
323
+ if (current?.status !== 'spawning') return;
324
+ this.store.put({ ...current, status: 'error', error: message, updatedAt: this.now().toISOString() });
325
+ this.emit({ kind: 'changed', id });
326
+ } catch (err) {
327
+ log('failed to mark hosted node %s as errored: %s', id, errorMessage(err));
328
+ }
329
+ }
330
+
331
+ /**
332
+ * What the QR code carries for a node waiting to be claimed: its peer id, the
333
+ * addresses a phone may dial it at, and its claim secret — the only place the
334
+ * secret ever leaves the host. `409 invalid_state` unless the node is `unclaimed`;
335
+ * `503 node_unavailable` until the child's `/status` answers (callers poll).
336
+ */
337
+ async claimDetails(id: string): Promise<ClaimDetails> {
338
+ const node = this.requireNode(id);
339
+ if (node.status !== 'unclaimed' || node.join.kind !== 'claim') {
340
+ throw new HostedNodeError('invalid_state', `Hosted node ${id} is ${node.status}; only a node waiting to be claimed has claim details`);
341
+ }
342
+ if (!node.statusEndpoint) {
343
+ throw new HostedNodeError('node_unavailable', `Hosted node ${id} has no status endpoint yet`);
344
+ }
345
+ const { secret } = node.join;
346
+ const status = await readNodeStatus(node.statusEndpoint);
347
+ this.recordPeerId(id, status.peerId);
348
+ const settings = this.claimAddressSettings();
349
+ const exactAddrs = settings?.addrs ?? [];
350
+ return buildClaimDetails({
351
+ id,
352
+ secret,
353
+ status,
354
+ ports: this.orchestrator.getNode?.(id)?.ports,
355
+ addresses: this.addresses,
356
+ exactAddrs,
357
+ lan: exactAddrs.length > 0 ? undefined : await claimLanAddress(settings, this.addresses, this.primaryLan),
358
+ });
359
+ }
360
+
361
+ /** Cache the peer id on the record, once. Best-effort: the claim details do not depend on it. */
362
+ private recordPeerId(id: string, peerId: string): void {
363
+ try {
364
+ // Re-read: the entry-time copy predates the `/status` round-trip.
365
+ const current = this.store.get(id);
366
+ if (!current || current.peerId === peerId) return;
367
+ this.store.put({ ...current, peerId });
368
+ } catch (err) {
369
+ log('failed to record peer id of hosted node %s: %s', id, errorMessage(err));
370
+ }
371
+ }
372
+
373
+ /**
374
+ * Re-spawn a node that is no longer running, replaying the record's party and
375
+ * claim secret, or its invitation while it is still `joining`. The node keeps its
376
+ * workdir — and with it its identity key and node-local stores — and comes back on
377
+ * the same ports, so it is the *same* peer at the same addresses: a QR code already
378
+ * shown stays valid, and a joined node's cadre finds it where it was. Keeping the
379
+ * secret after the claim is deliberate: `cadre-cli` honours `claim.json` and, with the
380
+ * secret still set, answers a rival `already-claimed`. A joined invitation node comes
381
+ * back without its invitation ({@link spawnRequestFor} says why).
382
+ *
383
+ * **Status is deliberately unchanged.** A `joined` node stays `joined`; an
384
+ * `unclaimed` one keeps waiting, a `joining` one redeems again. `connected` is
385
+ * dropped until the watcher reads the new child.
386
+ *
387
+ * **An ending that lands mid-spawn wins.** The record is re-read after the
388
+ * orchestrator returns; if it was removed (or went `error`) while the child was
389
+ * starting, that write stands and the new child is abandoned — see
390
+ * {@link abandonRespawn}. An abandoned respawn is a skip, not a failure, so a
391
+ * sweep over the store keeps going. Orchestrator failures DO throw; the caller
392
+ * owns backoff/give-up.
393
+ *
394
+ * Not serialized itself: callers run it on {@link serializeRespawns}. Two overlapping
395
+ * calls for the same id both spawn a child, and the second spawn drops the first's
396
+ * orchestrator handle — leaving an unmanaged process.
397
+ */
398
+ async respawn(id: string, opts: RespawnOptions = {}): Promise<RespawnResult> {
399
+ const node = this.requireNode(id);
400
+ // Callers filter for this already; the guard is here so no future one can
401
+ // resurrect or double-spawn a node by omission.
402
+ if (!RESPAWNABLE_STATUSES.has(node.status)) {
403
+ throw new HostedNodeError('invalid_state', `Hosted node ${id} cannot be respawned in status ${node.status}`);
404
+ }
405
+
406
+ // Just the counters, never a whole row copy: both exits below merge these
407
+ // onto whatever the store holds *after* the spawn, and an entry-time record
408
+ // in scope is a standing invitation to write the stale row back.
409
+ const attempt: RespawnAttempt | undefined = opts.countAttempt === false
410
+ ? undefined
411
+ : { attempts: (node.respawn?.attempts ?? 0) + 1, lastAttemptAt: this.now().toISOString() };
412
+
413
+ let spawned: SpawnedHandles | undefined;
414
+ try {
415
+ const result = await this.orchestrator.createContainer(spawnRequestFor(node));
416
+ spawned = handlesOf(result);
417
+
418
+ // Re-read: see `joinLocked`. A removal or a give-up that landed while the
419
+ // spawn was in flight must stand.
420
+ const current = this.store.get(id);
421
+ if (!current || !RESPAWNABLE_STATUSES.has(current.status)) {
422
+ return this.abandonRespawn(id, spawned, current);
423
+ }
424
+
425
+ const { connected: _connected, ...rest } = current;
426
+ const respawned: HostedNode = {
427
+ ...rest,
428
+ ...(attempt ? { respawn: attempt, updatedAt: this.now().toISOString() } : {}),
429
+ ...spawned,
430
+ };
431
+ this.store.put(respawned);
432
+ log('respawned hosted node %s → %s (status %s)', id, result.dockerId, respawned.status);
433
+ this.emit({ kind: 'changed', id });
434
+ this.watcher.poke(id);
435
+ return { outcome: 'respawned', node: redact(respawned) };
436
+ } catch (err) {
437
+ const message = errorMessage(err);
438
+ log('respawn of hosted node %s failed: %s', id, message);
439
+ // Stop — never reclaim — a child we spawned but failed to record:
440
+ // `removeContainer` deletes the workdir, which holds the identity key and
441
+ // node-local stores that are the whole reason a respawn is the same node.
442
+ // The new handles go onto the record below, so it names the child that
443
+ // actually exists and a later `remove()` reclaims that one.
444
+ if (spawned) await this.safeStop(spawned.dockerId);
445
+ this.storeRespawnAttempt(id, attempt, spawned);
446
+ throw new HostedNodeError('orchestrator_error', `Failed to respawn hosted node: ${message}`);
447
+ }
448
+ }
449
+
450
+ /**
451
+ * Start an invitation node again after no member of its cadre could be reached: the
452
+ * `error` record goes back to `joining` and is respawned with its invitation, without
453
+ * spending a respawn attempt. On the respawn queue, so it never overlaps the
454
+ * supervisor's handling of the same node. `409 invalid_state` unless the node is `error`
455
+ * with `retryable` — a refused invitation stays refused, and the supervisor's give-up and
456
+ * the other failures are a reset's.
457
+ */
458
+ retry(id: string): Promise<HostedNodeView> {
459
+ return this.serializeRespawns(() => this.retryLocked(id));
460
+ }
461
+
462
+ private async retryLocked(id: string): Promise<HostedNodeView> {
463
+ const node = this.requireNode(id);
464
+ if (node.status !== 'error' || node.retryable !== true) {
465
+ throw new HostedNodeError('invalid_state', `Hosted node ${id} is ${node.status}${node.status === 'error' ? ' and not retryable' : ''}; only an invitation no member could be reached for can be retried`);
466
+ }
467
+ // The watcher stops a child whose redemption failed; one still running (that stop
468
+ // failed, or a host restart re-attached it) would make the spawn below refuse.
469
+ if (node.dockerId && await this.orchestrator.isRunning(node.dockerId)) await this.safeStop(node.dockerId);
470
+ // Re-read: the stop is an await, and a removal may have landed in it.
471
+ const current = this.store.get(id);
472
+ if (current?.status !== 'error') {
473
+ throw current
474
+ ? new HostedNodeError('invalid_state', `Hosted node ${id} went ${current.status} before its retry started`)
475
+ : new HostedNodeError('not_found', `No such hosted node: ${id}`);
476
+ }
477
+ const { error: _error, retryable: _retryable, ...rest } = current;
478
+ this.store.put({ ...rest, status: 'joining', updatedAt: this.now().toISOString() });
479
+ log('retrying the invitation of hosted node %s', id);
480
+ this.emit({ kind: 'changed', id });
481
+ // A respawn that throws leaves the record `joining` with no child, which the
482
+ // supervisor's next pass respawns, counting the attempt.
483
+ const result = await this.respawn(id, { countAttempt: false });
484
+ if (result.outcome === 'abandoned') {
485
+ throw result.status
486
+ ? new HostedNodeError('invalid_state', `Hosted node ${id} went ${result.status} while its retry was starting`)
487
+ : new HostedNodeError('not_found', `No such hosted node: ${id}`);
488
+ }
489
+ return result.node;
490
+ }
491
+
492
+ /**
493
+ * Give up on a respawn whose record ended while the child was starting: stop
494
+ * the new child and, unless the record went `error`, reclaim it.
495
+ *
496
+ * Reclaim, not merely stop. The removal's own cleanup already ran and found
497
+ * nothing: `HostProcessOrchestrator.createContainer` calls `dropStaleHandle`
498
+ * *while* spawning, so by the time the concurrent `remove` reached its
499
+ * stop/reclaim the old handle was gone and both calls were swallowed as
500
+ * best-effort no-ops. The new handle is now the only thing holding that
501
+ * spawn's ports and workdir, so stopping alone would leak both.
502
+ *
503
+ * `error` is the deliberate exception: `removeContainer` deletes the workdir,
504
+ * and `HostedNodeSupervisor.giveUp` keeps it on purpose so the identity key the
505
+ * node's cadre approved survives. Since both spawns share one workdir
506
+ * (`<rootDir>/<containerId>`), reclaiming here would delete exactly what
507
+ * `giveUp` meant to keep.
508
+ *
509
+ * The `error` record is then pointed at the new child, the one that exists, so a
510
+ * later `remove` reclaims its ports and workdir. `giveUp` runs on the respawn queue
511
+ * and cannot overlap a respawn; the watcher's write of a failed invitation can, when
512
+ * a poll of the old child answers while the new one is starting.
513
+ */
514
+ private async abandonRespawn(id: string, spawned: SpawnedHandles, current: HostedNode | undefined): Promise<RespawnResult> {
515
+ const status = current?.status;
516
+ log('hosted node %s went %s during respawn — abandoning new child %s', id, status ?? 'missing', spawned.dockerId);
517
+ await this.safeStop(spawned.dockerId);
518
+ if (status === 'error') this.storeRespawnAttempt(id, undefined, spawned);
519
+ else await this.safeReclaim(spawned.dockerId);
520
+ return status ? { outcome: 'abandoned', status } : { outcome: 'abandoned' };
521
+ }
522
+
523
+ /**
524
+ * Remove a hosted node: delete the row FIRST, then stop and reclaim the child
525
+ * (its workdir, identity key and data go with it). The node's cadre keeps the
526
+ * node's row until its owner removes it there.
527
+ *
528
+ * Order matters: stopping the child fires the orchestrator's `onStateChange`,
529
+ * and the supervisor's exit-triggered pass must find no record — otherwise it
530
+ * observes "node gone, record still `joined`" and brings back a node the admin
531
+ * just removed. The tradeoff: a crash between the delete and the stop leaves a
532
+ * running child no record names, which `remove` on its id still reclaims (below).
533
+ *
534
+ * A handle no record names — `hosted-nodes.json` lost, or a handle an older
535
+ * build persisted — is removed the same way, so `/api/nodes` cannot list a node
536
+ * for good that nothing can end.
537
+ */
538
+ async remove(id: string): Promise<void> {
539
+ const node = this.store.get(id);
540
+ if (!node) {
541
+ await this.removeOrphanHandle(id);
542
+ return;
543
+ }
544
+ this.store.remove(id);
545
+ if (node.dockerId) {
546
+ await this.safeStop(node.dockerId);
547
+ await this.safeReclaim(node.dockerId);
548
+ } else {
549
+ // No `dockerId` — the spawn never got far enough to produce one, so the
550
+ // stop-and-reclaim above has nothing to aim at and the node's working
551
+ // directory would be stranded on disk with nothing able to name it.
552
+ //
553
+ // NOTE: this can race an in-flight `join` for the same record — the delete
554
+ // may land between that spawn's `mkdirSync` and its `spawn`. The end state
555
+ // is still correct (`joinLocked`'s post-spawn re-read sees no record and
556
+ // reclaims the new child, which deletes the workdir anyway); the interim
557
+ // delete can only make that child fail to start noisily, which is strictly
558
+ // better than a permanent strand.
559
+ this.safeReclaimWorkdir(id);
560
+ }
561
+ log('hosted node %s removed', id);
562
+ this.emit({ kind: 'removed', id });
563
+ }
564
+
565
+ private async removeOrphanHandle(id: string): Promise<void> {
566
+ const dockerId = this.orchestrator.resolveDockerId?.(id);
567
+ if (!dockerId) throw new HostedNodeError('not_found', `No such hosted node: ${id}`);
568
+ log('hosted node %s has a handle but no record — removing the handle', id);
569
+ await this.safeStop(dockerId);
570
+ await this.safeReclaim(dockerId);
571
+ this.emit({ kind: 'removed', id });
572
+ }
573
+
574
+ /**
575
+ * Remove a node and start a fresh one waiting to be claimed, with a new secret and
576
+ * identity. For the case where someone else photographed the QR code and claimed the
577
+ * node first, and for an `error` node the admin wants to try again. An invitation node
578
+ * is replaced by one waiting to be claimed too: its invitation may be spent, and the
579
+ * admin can join with a fresh one instead.
580
+ */
581
+ async reset(id: string): Promise<HostedNodeView> {
582
+ await this.remove(id);
583
+ return this.join();
584
+ }
585
+
586
+ /**
587
+ * Mark records stuck in `spawning` past `ttlMs` as `error` and reclaim whatever
588
+ * the orchestrator can still find for them — the record is written before the
589
+ * child spawn starts, so a host crash/kill anywhere in that window (including
590
+ * mid-spawn) leaves nothing to advance it across a restart. Run once at
591
+ * startup and on a periodic sweep. Age is measured from `updatedAt`, which for
592
+ * a genuinely-stuck row equals `createdAt` — `joinLocked` never touches a
593
+ * `spawning` record again except to advance it out of this predicate.
594
+ * Best-effort per record: a failed reap is logged and the sweep continues.
595
+ * Returns the reaped ids.
596
+ */
597
+ async reapStuckSpawning(ttlMs: number = HOSTED_NODE_SPAWNING_TTL_MS): Promise<string[]> {
598
+ const cutoff = this.now().getTime() - ttlMs;
599
+ const stale = this.store.list().filter((n) => isStuckSpawning(n, cutoff));
600
+ const reaped: string[] = [];
601
+ for (const node of stale) {
602
+ try {
603
+ // Re-read: an in-flight (same-process) `joinLocked` call can still
604
+ // advance this exact record between the snapshot above and now.
605
+ const current = this.store.get(node.id);
606
+ if (!current || !isStuckSpawning(current, cutoff)) continue;
607
+ await this.reclaimStuckSpawning(current);
608
+ reaped.push(node.id);
609
+ log('reaped stuck spawning hosted node %s (age > %dms)', node.id, ttlMs);
610
+ } catch (err) {
611
+ log('failed to reap stuck spawning hosted node %s: %s', node.id, errorMessage(err));
612
+ }
613
+ }
614
+ return reaped;
615
+ }
616
+
617
+ /**
618
+ * Terminalize a stuck-`spawning` record as `error` and reclaim any child the
619
+ * orchestrator can still find for it. Status is written FIRST (same ordering
620
+ * rule as {@link remove}): reclaiming fires `onStateChange`, and anything
621
+ * listening must already see a terminal record.
622
+ *
623
+ * NOTE: the stop only reaches a child the orchestrator has a handle for.
624
+ * `HostProcessOrchestrator.launchChild` spawns the process and persists the
625
+ * handle in the same synchronous step, so the only child this misses is one
626
+ * whose host died between the OS spawn and that write — an orphan *process*
627
+ * this reap terminalizes the record for but cannot kill (its ports stay held
628
+ * until a reboot). Its working directory is reclaimed by container name when
629
+ * no handle resolves, which also covers the far commoner case of a host that
630
+ * died before any child existed at all.
631
+ */
632
+ private async reclaimStuckSpawning(node: HostedNode): Promise<void> {
633
+ this.store.put({
634
+ ...node,
635
+ status: 'error',
636
+ error: 'stuck starting past its deadline — the host likely restarted mid-spawn',
637
+ updatedAt: this.now().toISOString(),
638
+ });
639
+ this.emit({ kind: 'changed', id: node.id });
640
+ const dockerId = this.orchestrator.resolveDockerId?.(node.id);
641
+ if (dockerId) {
642
+ await this.safeStop(dockerId);
643
+ await this.safeReclaim(dockerId);
644
+ } else {
645
+ this.safeReclaimWorkdir(node.id);
646
+ }
647
+ }
648
+
649
+ /** One node (secret stripped), or undefined when unknown. */
650
+ get(id: string): HostedNodeView | undefined {
651
+ const node = this.store.get(id);
652
+ return node ? redact(node) : undefined;
653
+ }
654
+
655
+ /** Every node (secret stripped). */
656
+ list(): HostedNodeView[] {
657
+ return this.store.list().map(redact);
658
+ }
659
+
660
+ private requireNode(id: string): HostedNode {
661
+ const node = this.store.get(id);
662
+ if (!node) throw new HostedNodeError('not_found', `No such hosted node: ${id}`);
663
+ return node;
664
+ }
665
+
666
+ /** Best-effort stop; logs but never throws (cleanup path). */
667
+ private async safeStop(dockerId: string): Promise<void> {
668
+ try {
669
+ await this.orchestrator.stopContainer(dockerId);
670
+ } catch (err) {
671
+ log('failed to stop container %s: %s', dockerId, errorMessage(err));
672
+ }
673
+ }
674
+
675
+ /**
676
+ * Persist a failed respawn's attempt counters (none for an uncounted restart) —
677
+ * plus, when the spawn itself succeeded and it was the record write that failed,
678
+ * the new child's handles. Merged onto whatever is on disk now, never written
679
+ * wholesale: the caller's copy predates the orchestrator round-trip.
680
+ *
681
+ * `status` and `updatedAt` are deliberately untouched — the attempt did not succeed.
682
+ *
683
+ * Recording `spawned` is what keeps the record pointing at the child that
684
+ * actually exists: `createContainer` already dropped the handle the record
685
+ * previously named, so leaving the old `dockerId` there would send every later
686
+ * stop/reclaim at an id the orchestrator cannot resolve — stranding the node's
687
+ * workdir on disk forever.
688
+ *
689
+ * Best-effort: we are already unwinding a respawn failure, and a store error
690
+ * here must not mask it. Losing the write costs the caller one extra attempt
691
+ * before backoff; the supervisor's next pass re-reads the record, finds the
692
+ * named child not running, and respawns again — which drops whatever handle is
693
+ * current, so the ports self-heal either way.
694
+ */
695
+ private storeRespawnAttempt(id: string, respawn: RespawnAttempt | undefined, spawned?: SpawnedHandles): void {
696
+ if (!respawn && !spawned) return;
697
+ try {
698
+ // A row that vanished (a removal) must not be recreated.
699
+ const current = this.store.get(id);
700
+ if (!current) return;
701
+ this.store.put({ ...current, ...(respawn ? { respawn } : {}), ...spawned });
702
+ } catch (err) {
703
+ log('failed to record respawn attempt for %s: %s', id, errorMessage(err));
704
+ }
705
+ }
706
+
707
+ /** Best-effort remove; logs but never throws (cleanup path). */
708
+ private async safeReclaim(dockerId: string): Promise<void> {
709
+ try {
710
+ await this.orchestrator.removeContainer(dockerId);
711
+ } catch (err) {
712
+ log('failed to reclaim container %s: %s', dockerId, errorMessage(err));
713
+ }
714
+ }
715
+
716
+ /**
717
+ * Best-effort removal of the working directory of a node whose spawn never
718
+ * produced a `dockerId`; logs but never throws (cleanup path). A no-op on an
719
+ * orchestrator without the capability, and on one that refuses because a live
720
+ * handle still owns the directory.
721
+ */
722
+ private safeReclaimWorkdir(id: string): void {
723
+ try {
724
+ if (this.orchestrator.reclaimWorkdir?.(id)) {
725
+ log('reclaimed orphaned workdir for hosted node %s', id);
726
+ }
727
+ } catch (err) {
728
+ log('failed to reclaim workdir for hosted node %s: %s', id, errorMessage(err));
729
+ }
730
+ }
731
+
732
+ /** Run `fn` after any in-flight join. */
733
+ private serializeJoin<T>(fn: () => Promise<T>): Promise<T> {
734
+ const run = this.joinTail.then(fn, fn);
735
+ // The stored tail swallows outcomes — a rejected join must not reject the
736
+ // next caller's wait, only defer it.
737
+ this.joinTail = run.then(() => undefined, () => undefined);
738
+ return run;
739
+ }
740
+
741
+ /**
742
+ * Run `fn` after every respawn already queued. Every caller of {@link respawn} goes
743
+ * through here: the supervisor's reconcile passes and restarts, and {@link retry}.
744
+ */
745
+ serializeRespawns<T>(fn: () => Promise<T>): Promise<T> {
746
+ const run = this.respawnTail.then(fn, fn);
747
+ // As in `serializeJoin`: a failed pass only sequences the next one, never rejects it.
748
+ this.respawnTail = run.then(() => undefined, () => undefined);
749
+ return run;
750
+ }
751
+ }
752
+
753
+ /** `hn_<high-entropy base64url>` — also the node's orchestrator containerId and workdir name. */
754
+ function generateHostedNodeId(): string {
755
+ return `hn_${randomBytes(12).toString('base64url')}`;
756
+ }
757
+
758
+ function generateClaimSecret(): string {
759
+ return randomBytes(CLAIM_SECRET_BYTES).toString('base64url');
760
+ }
761
+
762
+ /** An invitation `join` was given, with what decoding it found. */
763
+ interface DecodedInvitation {
764
+ encoded: string;
765
+ decoded: CadreInvitation;
766
+ }
767
+
768
+ /** Decode a pasted invitation; one that does not decode is `invalid_request` with the decoder's reason. */
769
+ function decodeInvitation(encoded: string): DecodedInvitation {
770
+ const trimmed = encoded.trim();
771
+ try {
772
+ return { encoded: trimmed, decoded: decodeCadreInvitation(trimmed) };
773
+ } catch (err) {
774
+ throw new HostedNodeError('invalid_request', `The invitation does not decode: ${errorMessage(err)}`);
775
+ }
776
+ }
777
+
778
+ /**
779
+ * The spawn a record describes: its party, profile, and how it gets into its cadre. Used
780
+ * by `join` and `respawn` alike.
781
+ *
782
+ * An invitation is passed until the node has joined, and never after: a joined node is a
783
+ * member whose rows are in its own control database, and an invitation that expired
784
+ * meanwhile must not turn a healthy member's restart into a refusal.
785
+ */
786
+ function spawnRequestFor(node: HostedNode): HostedSpawnRequest {
787
+ const base: HostedSpawnRequest = {
788
+ containerId: node.id,
789
+ partyId: node.partyId,
790
+ profile: node.profile,
791
+ };
792
+ if (node.join.kind === 'claim') return { ...base, claimSecret: node.join.secret };
793
+ return node.status === 'joined' ? base : { ...base, invitation: node.join.encoded };
794
+ }
795
+
796
+ /** The record fields a spawn result lands. */
797
+ function handlesOf(result: OrchestratorCreateResult): SpawnedHandles {
798
+ return { dockerId: result.dockerId, statusEndpoint: statusUrlFor(result.healthEndpoint) };
799
+ }
800
+
801
+ /** Strip the claim secret or the invitation. */
802
+ function redact(node: HostedNode): HostedNodeView {
803
+ const { join, ...rest } = node;
804
+ return { ...rest, join: { kind: join.kind } };
805
+ }
806
+
807
+ /**
808
+ * Whether a record is still a stuck-`spawning` reap candidate. Stated once and
809
+ * applied twice in {@link HostedNodeService.reapStuckSpawning} — on the sweep's
810
+ * candidate list, and again per record before the terminal write.
811
+ */
812
+ function isStuckSpawning(node: HostedNode | undefined, cutoff: number): boolean {
813
+ return node?.status === 'spawning' && Date.parse(node.updatedAt) < cutoff;
814
+ }