@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
@@ -1,828 +0,0 @@
1
- import { randomBytes } from 'node:crypto';
2
- import debug from 'debug';
3
- import { requireEd25519PublicKeyB64 } from '@serfab/cadre-core';
4
- import { DonationError } from './types.js';
5
- const log = debug('cadre:host:donation-service');
6
- /**
7
- * The only statuses a loan may come back from. An allowlist, not a terminal
8
- * denylist: `terminated` is a loan the borrower ended and `error` one the host
9
- * gave up on (neither may come back), while `provisioning` is a provision still
10
- * in flight — replaying its spawn would race that provision and strand the
11
- * record in `provisioning`, which no reap sweep collects.
12
- *
13
- * Checked twice in {@link DonationService.respawn} — once on entry, once after
14
- * the spawn — so the "may this loan come back" rule is stated exactly once.
15
- */
16
- const RESPAWNABLE_STATUSES = new Set([
17
- 'awaiting_seed',
18
- 'seeded',
19
- ]);
20
- /**
21
- * The only statuses a record may be marked `seeded` from. A different question
22
- * from {@link RESPAWNABLE_STATUSES} — "may this record accept a seed result"
23
- * rather than "may this loan come back" — so it is stated separately even though
24
- * the two sets happen to coincide today. Re-seeding an already-`seeded` record is
25
- * allowed (the borrower may present a fresh seed); `terminated` / `error` /
26
- * `provisioning` may not be written over.
27
- *
28
- * Checked twice in {@link DonationService.applySeed} — once on entry, once after
29
- * the node's round-trip — so the rule is stated exactly once.
30
- */
31
- const SEEDABLE_STATUSES = new Set([
32
- 'awaiting_seed',
33
- 'seeded',
34
- ]);
35
- /**
36
- * Default age after which a donation still stuck in `awaiting_seed` is
37
- * auto-terminated: the requester provisioned a node but never presented a seed
38
- * (it vanished, or abandoned the flow), leaving an orphaned child holding host
39
- * ports. 30 minutes.
40
- *
41
- * NOTE: not operator-configurable yet — a single module constant. If hosts need
42
- * to tune the grace period, promote this to `host.config.json`.
43
- */
44
- export const DONATION_AWAITING_SEED_TTL_MS = 30 * 60 * 1000;
45
- /**
46
- * Default age after which a donation still stuck in `provisioning` is
47
- * auto-terminated: the host wrote the row before starting the child, and a
48
- * crash/kill in that window (or during the spawn itself) leaves nothing to
49
- * advance it across a restart. A real spawn (identity key read/gen, port
50
- * allocation, process spawn) completes in well under a second normally, so 5
51
- * minutes is generously past "any plausible spawn" without risking a false
52
- * reap of one still genuinely in flight under heavy load.
53
- */
54
- export const DONATION_PROVISIONING_TTL_MS = 5 * 60 * 1000;
55
- /** How often the reap sweep runs while cadre-host is up. 5 minutes. */
56
- export const DONATION_REAP_SWEEP_MS = 5 * 60 * 1000;
57
- /**
58
- * DonationService — drives the donate-a-node lifecycle on behalf of an external
59
- * requester (a friend's phone). It is cadre-host's analogue of cadre-provider's
60
- * `ContainerService`, minus Docker/billing, plus the grant-token gate.
61
- *
62
- * The host contributes capacity only: it spawns a generic node into the
63
- * *requester's* cadre (`partyId`), pins the requester's owner key(s) so the node
64
- * will accept a requester-signed seed, and presents that seed to the node's
65
- * `POST /seed` — it never holds the requester's authority private key.
66
- *
67
- * Scope note: this class covers the service surface the node-donation
68
- * integration test drives directly (`provision` / `getPeer` / `applySeed` /
69
- * `terminate` / `get` / `list`). The grantee-facing HTTP routes, the `bin/host.ts`
70
- * wiring, and the stale-`awaiting_seed` reap sweep are owned by the
71
- * `2-donation-service` ticket and land alongside this file.
72
- */
73
- export class DonationService {
74
- constructor(opts) {
75
- /**
76
- * Per-grant-token serialization tail. `provision` chains onto the prior
77
- * operation for the same token so the quota check and record-create are
78
- * atomic — two concurrent requests at `count = maxNodes - 1` can't both pass.
79
- * `terminateGrant` chains onto it too, so a revoke's teardown cannot miss a
80
- * record that a provision already queued for the grant is about to write.
81
- *
82
- * NOTE: one entry per distinct token, never evicted. Fine at household scale
83
- * (a handful of grants); if grant counts ever grow large, evict the tail once
84
- * it resolves.
85
- */
86
- this.grantTail = new Map();
87
- this.orchestrator = opts.orchestrator;
88
- this.grants = opts.grants;
89
- this.store = opts.store;
90
- this.now = opts.now ?? (() => new Date());
91
- log('DonationService initialized');
92
- }
93
- /**
94
- * Provision a donated node for a validated grant. Serialized per grant token
95
- * so the quota check and record-create are atomic. On any orchestrator failure
96
- * the reserved resources are reclaimed and the record is marked `error`.
97
- *
98
- * The owner-key pins are shape-checked FIRST — ahead of the per-grant lock, the
99
- * quota check and the record write — so a malformed request costs nothing: no
100
- * waiting behind another provision, no grant quota slot burned, no workdir or
101
- * port taken, and no `error` record to explain later. Without it the request is
102
- * answered as provisioned and the child dies at boot, which is the one place the
103
- * caller cannot act on the typo.
104
- */
105
- async provision(request) {
106
- const validated = { ...request, ownerKeys: validateOwnerKeys(request.ownerKeys) };
107
- return this.serializeByGrant(validated.grantToken, () => this.provisionLocked(validated));
108
- }
109
- async provisionLocked(request) {
110
- const validation = this.grants.validateForProvision(request.grantToken, (token) => this.store.liveNodeCount(token));
111
- if (!validation.ok) {
112
- throw denialToError(validation.reason);
113
- }
114
- const id = generateDonationId();
115
- const nowIso = this.now().toISOString();
116
- const profile = request.profile ?? 'storage';
117
- const record = {
118
- id,
119
- grantToken: request.grantToken,
120
- partyId: request.partyId,
121
- // Persisted so `respawn` can replay the spawn from the record alone.
122
- // Neither is secret (dialable addrs + public keys), so both ride along in
123
- // the redacted `DonationView` too.
124
- bootstrapNodes: request.bootstrapNodes,
125
- ownerKeys: request.ownerKeys,
126
- profile,
127
- status: 'provisioning',
128
- createdAt: nowIso,
129
- updatedAt: nowIso,
130
- };
131
- this.store.put(record);
132
- // The spawn is the only step that can fail before anything is allocated, so
133
- // it gets a `try` of its own — a wider one would swallow the abandon
134
- // decision below and mark a borrower's own ending as a host-side `error`.
135
- let result;
136
- try {
137
- result = await this.orchestrator.createContainer({
138
- containerId: id,
139
- partyId: request.partyId,
140
- bootstrapNodes: request.bootstrapNodes,
141
- profile,
142
- pinnedOwnerKeys: request.ownerKeys,
143
- });
144
- }
145
- catch (err) {
146
- const message = errorMessage(err);
147
- log('provision of donation %s failed: %s', id, message);
148
- this.markProvisionFailed(id, message);
149
- throw new DonationError('orchestrator_error', `Failed to provision donated node: ${message}`);
150
- }
151
- // Re-read: `record` predates the orchestrator round-trip (seconds of wall
152
- // clock) and `store.put` replaces the whole row, so writing that copy back
153
- // would undo a `terminate` — or a delete — that landed while the spawn was
154
- // in flight, resurrecting a loan the borrower just ended. The store is
155
- // synchronous, so this read-decide-write is atomic against the event loop
156
- // only as long as no `await` sneaks in between.
157
- const current = this.store.get(id);
158
- if (!current || current.status !== 'provisioning') {
159
- // The ending cleaned up nothing: the record named no `dockerId` yet, so
160
- // `terminate`'s cleanup branch never ran and this child is the only thing
161
- // holding the spawn's ports and workdir. Reclaim (not merely stop) — the
162
- // workdir was created by this very spawn, so there is nothing to preserve.
163
- log('donation %s went %s during provision — abandoning new child %s', id, current?.status ?? 'missing', result.dockerId);
164
- await this.safeReclaim(result.dockerId);
165
- throw current
166
- ? new DonationError('invalid_state', `Donation ${id} was ${current.status} before it finished provisioning`)
167
- : new DonationError('not_found', `No such donation: ${id}`);
168
- }
169
- const provisioned = {
170
- ...current,
171
- dockerId: result.dockerId,
172
- seedEndpoint: result.seedEndpoint,
173
- // Persisted so a host restart in the request→seed gap can still present
174
- // the seed. NEVER returned to the grantee (stripped by `DonationView`).
175
- seedToken: result.seedToken,
176
- status: 'awaiting_seed',
177
- updatedAt: this.now().toISOString(),
178
- };
179
- try {
180
- this.store.put(provisioned);
181
- }
182
- catch (err) {
183
- const message = errorMessage(err);
184
- log('provision of donation %s failed: %s', id, message);
185
- await this.safeReclaim(result.dockerId);
186
- this.markProvisionFailed(id, message);
187
- throw new DonationError('orchestrator_error', `Failed to provision donated node: ${message}`);
188
- }
189
- log('provisioned donation %s (party=%s) → awaiting_seed', id, request.partyId);
190
- return redact(provisioned);
191
- }
192
- /**
193
- * Mark a still-`provisioning` record as failed — and ONLY such a record. A row
194
- * that went `terminated` while the spawn was in flight is the borrower's own
195
- * ending and must not be rewritten as a host fault; a row that vanished must
196
- * not be recreated.
197
- *
198
- * Best-effort (mirroring {@link storeRespawnAttempt}): we are already unwinding a
199
- * provision failure, and a store error here must not mask the error being
200
- * reported to the caller.
201
- */
202
- markProvisionFailed(id, message) {
203
- try {
204
- const current = this.store.get(id);
205
- if (current?.status !== 'provisioning')
206
- return;
207
- this.store.put({
208
- ...current,
209
- status: 'error',
210
- error: message,
211
- updatedAt: this.now().toISOString(),
212
- });
213
- }
214
- catch (err) {
215
- log('failed to mark donation %s as errored: %s', id, errorMessage(err));
216
- }
217
- }
218
- /**
219
- * Live peer identity of a donated node, read fresh from its `/status` every
220
- * call (no cache) so a re-keyed identity / remapped multiaddr is never served
221
- * stale. Throws `peer_unavailable` while the node has no peer identity yet.
222
- */
223
- async getPeer(id) {
224
- const donation = this.requireDonation(id);
225
- if (!donation.seedEndpoint) {
226
- throw new DonationError('peer_unavailable', `Donation ${id} has no node endpoint`);
227
- }
228
- const statusUrl = toStatusUrl(donation.seedEndpoint);
229
- let res;
230
- try {
231
- res = await fetch(statusUrl);
232
- }
233
- catch (err) {
234
- throw new DonationError('peer_unavailable', `Donated node unreachable: ${errorMessage(err)}`);
235
- }
236
- if (!res.ok) {
237
- throw new DonationError('peer_unavailable', `Donated node /status returned ${res.status}`);
238
- }
239
- const status = (await res.json());
240
- if (!status.peerId || !status.multiaddrs?.length) {
241
- throw new DonationError('peer_unavailable', `Donated node ${id} has no peer identity yet`);
242
- }
243
- return { peerId: status.peerId, multiaddrs: status.multiaddrs };
244
- }
245
- /**
246
- * Present the requester's phone-signed seed to the donated node's `POST /seed`,
247
- * authenticated with the host↔node `seedToken`. On success the donation moves
248
- * to `seeded`. The node still enforces its own seed-trust policy, so a seed
249
- * signed by a key the node did not pin comes back `rejected`.
250
- *
251
- * **An ending that lands mid-seed wins.** The record is re-read after the node
252
- * answers; if the loan ended (or the row vanished) while the request was in
253
- * flight, that write stands and we report `abandoned` rather than marking a
254
- * dead loan `seeded`. Unlike an abandoned respawn there is nothing to clean up
255
- * — the record named its `dockerId` the whole time, so the ending's own
256
- * `terminate` already stopped and reclaimed the child.
257
- */
258
- async applySeed(id, encodedSeed) {
259
- const donation = this.requireDonation(id);
260
- if (!SEEDABLE_STATUSES.has(donation.status)) {
261
- throw new DonationError('invalid_state', `Donation ${id} cannot be seeded in status ${donation.status}`);
262
- }
263
- if (!donation.seedEndpoint) {
264
- throw new DonationError('peer_unavailable', `Donation ${id} has no seed endpoint`);
265
- }
266
- // A record with an endpoint but no token can never authenticate — fail here
267
- // rather than let the node reject with an opaque 401.
268
- if (!donation.seedToken) {
269
- throw new DonationError('seed_failed', `Donation ${id} has no seed token`);
270
- }
271
- let res;
272
- try {
273
- res = await fetch(donation.seedEndpoint, {
274
- method: 'POST',
275
- headers: {
276
- 'content-type': 'application/json',
277
- authorization: `Bearer ${donation.seedToken}`,
278
- },
279
- body: JSON.stringify({ seed: encodedSeed }),
280
- });
281
- }
282
- catch (err) {
283
- throw new DonationError('seed_failed', `Donated node unreachable: ${errorMessage(err)}`);
284
- }
285
- if (res.status === 401) {
286
- // The node refused the host's bearer, not the requester's seed — the node
287
- // never looked at the seed. So the fault is the host's own token
288
- // bookkeeping (the record names a token the running child was not started
289
- // with), and the message must not read as a trust-policy rejection.
290
- //
291
- // Still `seed_failed`, deliberately: the phone retries that code, and a
292
- // bookkeeping gap that is mid-repair (a respawn about to write its new
293
- // token) can clear inside that retry window.
294
- log('donated node for donation %s refused the host seed credential (401)', id);
295
- throw new DonationError('seed_failed', 'Donated node rejected the host\'s seed credential (401)');
296
- }
297
- if (!res.ok) {
298
- const body = await res.text();
299
- throw new DonationError('seed_failed', `Donated node /seed returned ${res.status}: ${body}`);
300
- }
301
- const result = (await res.json());
302
- if (!result.success) {
303
- log('donation %s rejected the seed: %s', id, result.error ?? 'no reason given');
304
- return result.error === undefined
305
- ? { outcome: 'rejected' }
306
- : { outcome: 'rejected', error: result.error };
307
- }
308
- // Re-read: `donation` predates the node round-trip and `store.put` replaces
309
- // the whole row, so writing that copy back would undo a `terminate` — or a
310
- // reap — that landed while the seed was in flight, resurrecting an ended
311
- // loan. The store is synchronous, so this read-decide-write is atomic
312
- // against the event loop only as long as no `await` sneaks in between.
313
- //
314
- // NOTE: a concurrent `respawn` also passes this check — it leaves the status
315
- // alone but swaps `seedEndpoint`/`seedToken`, so we would mark `seeded` a
316
- // record whose live child is the new one while the seed went to the old
317
- // endpoint. Harmless today (respawn only fires when the supervisor believes
318
- // the child is down, in which case our `fetch` would have failed; and both
319
- // spawns share one workdir, so the seed the old child persisted is on disk
320
- // for the new one). If a second `respawn` caller appears, or respawn ever
321
- // stops sharing the workdir, compare `current.seedEndpoint`/`seedToken`
322
- // against the ones we actually seeded and report `abandoned` on a mismatch.
323
- const current = this.store.get(id);
324
- if (!current || !SEEDABLE_STATUSES.has(current.status)) {
325
- log('donation %s went %s during seed — the ending wins', id, current?.status ?? 'missing');
326
- return current ? { outcome: 'abandoned', status: current.status } : { outcome: 'abandoned' };
327
- }
328
- // Merge only the status transition onto the on-disk row.
329
- this.store.put({ ...current, status: 'seeded', updatedAt: this.now().toISOString() });
330
- log('donation %s seeded (peersAdded=%d)', id, result.peersAdded ?? 0);
331
- return { outcome: 'seeded', peersAdded: result.peersAdded ?? 0 };
332
- }
333
- /**
334
- * Re-spawn a donated node that is no longer running, replaying the spawn
335
- * inputs persisted on the record. The node keeps its workdir — and with it its
336
- * identity key, trusted-owner anchor, and retained bootstrap peers — so it
337
- * comes back as the *same* peer and rejoins from its own durable node-local
338
- * stores. Only the host-side handles change: `dockerId`, `seedEndpoint`,
339
- * `seedToken` are written back fresh.
340
- *
341
- * **Status is deliberately unchanged.** A `seeded` node stays `seeded` (it
342
- * needs no re-seeding); an `awaiting_seed` node stays `awaiting_seed` and the
343
- * borrower's later seed goes to the new endpoint/token.
344
- *
345
- * **An ending that lands mid-spawn wins.** The record is re-read after the
346
- * orchestrator returns; if it went `terminated` (or `error`, or vanished)
347
- * while the child was starting, that write stands and the new child is
348
- * abandoned — see {@link abandonRespawn}. Both non-`respawned` outcomes are
349
- * skips, not failures, so a sweep over the store keeps going. Orchestrator
350
- * failures DO throw; the caller owns backoff/give-up.
351
- *
352
- * NOTE: not serialized. Two overlapping calls for the same id both spawn a
353
- * child, and the second spawn drops the first's orchestrator handle — leaving
354
- * an unmanaged process. A supervisor with more than one trigger (timer +
355
- * exit event) must not let its passes overlap on one id.
356
- */
357
- async respawn(id) {
358
- const donation = this.requireDonation(id);
359
- // Callers filter for this already; the guard is here so no future one can
360
- // resurrect or double-spawn a loan by omission.
361
- if (!RESPAWNABLE_STATUSES.has(donation.status)) {
362
- throw new DonationError('invalid_state', `Donation ${id} cannot be respawned in status ${donation.status}`);
363
- }
364
- // An empty `bootstrapNodes` is a real spawn input (a requester that dials the node
365
- // itself); only a missing field marks a record written before inputs were persisted.
366
- if (donation.bootstrapNodes === undefined || !donation.ownerKeys?.length) {
367
- log('donation %s is not respawnable (record predates persisted spawn inputs)', id);
368
- return { outcome: 'not_respawnable' };
369
- }
370
- // Just the counters, never a whole row copy: both exits below merge these
371
- // onto whatever the store holds *after* the spawn, and an entry-time
372
- // `Donation` in scope is a standing invitation to write the stale row back.
373
- const attempt = {
374
- attempts: (donation.respawn?.attempts ?? 0) + 1,
375
- lastAttemptAt: this.now().toISOString(),
376
- };
377
- let spawned;
378
- try {
379
- const result = await this.orchestrator.createContainer({
380
- containerId: id,
381
- partyId: donation.partyId,
382
- bootstrapNodes: donation.bootstrapNodes,
383
- profile: donation.profile,
384
- pinnedOwnerKeys: donation.ownerKeys,
385
- });
386
- spawned = {
387
- dockerId: result.dockerId,
388
- seedEndpoint: result.seedEndpoint,
389
- seedToken: result.seedToken,
390
- };
391
- // Re-read: `donation` predates the orchestrator round-trip (seconds of
392
- // wall clock) and `store.put` replaces the whole row, so writing that copy
393
- // back would undo a `terminate` — or a reap, or a give-up — that landed
394
- // while the spawn was in flight, resurrecting an ended loan. The store is
395
- // synchronous, so this read-decide-write is atomic against the event loop
396
- // only as long as no `await` sneaks in between.
397
- const current = this.store.get(id);
398
- if (!current || !RESPAWNABLE_STATUSES.has(current.status)) {
399
- return this.abandonRespawn(id, result.dockerId, current);
400
- }
401
- const respawned = {
402
- ...current,
403
- // Merge only the attempt counters forward off the entry-time copy.
404
- respawn: attempt,
405
- dockerId: result.dockerId,
406
- seedEndpoint: result.seedEndpoint,
407
- seedToken: result.seedToken,
408
- // NOTE: on an `awaiting_seed` record this is the very field the
409
- // stale-seed reap measures age from, so each respawn defers that reap.
410
- // Bounded today (5 attempts, ≤80s backoff ≈ 2.5min against a 30min TTL,
411
- // then give-up moves the record to `error`) — but anyone raising
412
- // DONATION_RESPAWN_MAX_ATTEMPTS should re-check that arithmetic.
413
- updatedAt: this.now().toISOString(),
414
- };
415
- this.store.put(respawned);
416
- log('respawned donation %s → %s (status %s)', id, result.dockerId, respawned.status);
417
- return { outcome: 'respawned', donation: redact(respawned) };
418
- }
419
- catch (err) {
420
- const message = errorMessage(err);
421
- log('respawn of donation %s failed: %s', id, message);
422
- // Stop — never reclaim — a child we spawned but failed to record:
423
- // `removeContainer` deletes the workdir, which holds the identity key and
424
- // node-local stores that are the whole reason a respawn is the same node.
425
- // The new handles go onto the record below, so it names the child that
426
- // actually exists and a later `terminate()` reclaims that one.
427
- if (spawned)
428
- await this.safeStop(spawned.dockerId);
429
- this.storeRespawnAttempt(id, attempt, spawned);
430
- throw new DonationError('orchestrator_error', `Failed to respawn donated node: ${message}`);
431
- }
432
- }
433
- /**
434
- * Give up on a respawn whose loan ended while the child was starting: stop the
435
- * new child and, unless the record went `error`, reclaim it.
436
- *
437
- * Reclaim, not merely stop. The ending's own cleanup already ran and found
438
- * nothing: `HostProcessOrchestrator.createContainer` calls `dropStaleHandle`
439
- * *while* spawning, so by the time the concurrent `terminate` reached its
440
- * stop/reclaim the old handle was gone and both calls were swallowed as
441
- * best-effort no-ops. The new handle is now the only thing holding that
442
- * spawn's ports and workdir, so stopping alone would leak both. On a
443
- * `terminated` record the loan is over and the workdir (identity key +
444
- * node-local stores) goes with it — which is what `terminate` intended.
445
- *
446
- * `error` is the deliberate exception: `removeContainer` deletes the workdir,
447
- * and `DonationSupervisor.giveUp` keeps it on purpose so the identity key the
448
- * borrower's cadre approved survives. Since both spawns share one workdir
449
- * (`<rootDir>/<containerId>`), reclaiming here would delete exactly what
450
- * `giveUp` meant to keep.
451
- *
452
- * NOTE: that skipped reclaim leaks the new spawn's ports — the record
453
- * still names the *previous* `dockerId`, so a later `terminate` cleans up the
454
- * old handle, not this one. Unreachable today (`giveUp` is only called from
455
- * the supervisor's serialized pass, so it cannot overlap a respawn); if a
456
- * second `respawn` caller ever appears, write the new `dockerId` onto the
457
- * `error` record here so that later `terminate` reclaims the right child.
458
- */
459
- async abandonRespawn(id, dockerId, current) {
460
- const status = current?.status;
461
- log('donation %s went %s during respawn — abandoning new child %s', id, status ?? 'missing', dockerId);
462
- await this.safeStop(dockerId);
463
- if (status !== 'error')
464
- await this.safeReclaim(dockerId);
465
- return status ? { outcome: 'abandoned', status } : { outcome: 'abandoned' };
466
- }
467
- /**
468
- * Terminate a donation: mark the record `terminated` FIRST, then stop + remove
469
- * the child process (kept in the store for audit, excluded from the live-node
470
- * tally).
471
- *
472
- * Order matters: stopping the child fires the orchestrator's `onStateChange`,
473
- * and a respawn supervisor listening there must already see a terminal record
474
- * — otherwise it observes "node gone, record still `seeded`" and resurrects a
475
- * loan the borrower just ended. The tradeoff: a crash between the write and
476
- * the stop leaves a `terminated` record with a live child (reaped on the next
477
- * host start), which is strictly better than resurrecting an ended loan.
478
- */
479
- async terminate(id) {
480
- const donation = this.requireDonation(id);
481
- this.store.put({ ...donation, status: 'terminated', updatedAt: this.now().toISOString() });
482
- if (donation.dockerId) {
483
- await this.safeStop(donation.dockerId);
484
- await this.safeReclaim(donation.dockerId);
485
- }
486
- else {
487
- // No `dockerId` — the spawn never got far enough to produce one, so the
488
- // stop-and-reclaim above has nothing to aim at and the node's working
489
- // directory would be stranded on disk with nothing able to name it.
490
- // Without this branch the stuck-`provisioning` reap is bypassed entirely:
491
- // terminating such a record moves it to `terminated`, which that reap no
492
- // longer matches.
493
- //
494
- // NOTE: this can race an in-flight `provision` for the same record — the
495
- // delete may land between that spawn's `mkdirSync` and its `spawn`. The
496
- // end state is still correct (`provisionLocked`'s post-spawn re-read sees
497
- // a non-`provisioning` record and reclaims the new child, which deletes
498
- // the workdir anyway); the interim delete can only make that child fail
499
- // to start noisily, which is strictly better than a permanent strand.
500
- this.safeReclaimWorkdir(id);
501
- }
502
- log('donation %s terminated', id);
503
- }
504
- /**
505
- * Terminate every donation under one grant that is not already `terminated` —
506
- * the teardown behind an admin revoke. Returns the ids it terminated.
507
- *
508
- * Includes `error` records on purpose: the supervisor's give-up keeps such a
509
- * record's workdir (its identity key) for a later `terminate`, and once the
510
- * grant is revoked the grantee can no longer make that call, so this is the
511
- * last thing that can reclaim it.
512
- *
513
- * Serialized with `provision` on the same per-grant queue. The caller revokes
514
- * the grant first, and `provisionLocked` re-validates the grant inside that
515
- * queue, so a provision queued ahead of this call finishes and is then
516
- * terminated here, while one queued behind it is refused as revoked.
517
- *
518
- * Idempotent, and best-effort per record like the reap sweeps: a failed
519
- * terminate is logged and the loop continues, and running it again terminates
520
- * whatever is still left.
521
- */
522
- async terminateGrant(token) {
523
- return this.serializeByGrant(token, () => this.terminateGrantLocked(token));
524
- }
525
- async terminateGrantLocked(token) {
526
- const candidates = this.store.listByGrant(token).filter(isUnterminated);
527
- const terminated = [];
528
- for (const donation of candidates) {
529
- try {
530
- // Re-read: every `terminate` awaits, so from the second record on the
531
- // candidate list is a stale snapshot (see `reapStaleAwaitingSeed`).
532
- if (!isUnterminated(this.store.get(donation.id)))
533
- continue;
534
- await this.terminate(donation.id);
535
- terminated.push(donation.id);
536
- }
537
- catch (err) {
538
- log('failed to terminate donation %s of grant %s: %s', donation.id, token, errorMessage(err));
539
- }
540
- }
541
- log('terminated %d donation(s) under grant %s', terminated.length, token);
542
- return terminated;
543
- }
544
- /**
545
- * Auto-terminate donations still `awaiting_seed` past `ttlMs` — a requester
546
- * that provisioned a node but never presented a seed leaves an orphaned child
547
- * holding host ports. Run on a periodic sweep and once at startup for records
548
- * recovered from disk. Age is measured from the record's `updatedAt` (set when
549
- * it entered `awaiting_seed`). Best-effort per record: a failed terminate is
550
- * logged and the sweep continues. Returns the reaped donation ids.
551
- */
552
- async reapStaleAwaitingSeed(ttlMs = DONATION_AWAITING_SEED_TTL_MS) {
553
- const cutoff = this.now().getTime() - ttlMs;
554
- const stale = this.store.list().filter((d) => isReapable(d, cutoff));
555
- const reaped = [];
556
- for (const donation of stale) {
557
- try {
558
- // Re-read: every `terminate` awaits, so from the second record on the
559
- // candidate list is a stale snapshot. A seed landing in that gap makes
560
- // the record `seeded`, and a respawn refreshes `updatedAt` precisely to
561
- // defer this reap — terminating the snapshot copy would kill a loan that
562
- // just came good. `terminate` writes synchronously from here, so nothing
563
- // can slip between this decision and the terminal write.
564
- if (!isReapable(this.store.get(donation.id), cutoff))
565
- continue;
566
- await this.terminate(donation.id);
567
- reaped.push(donation.id);
568
- log('reaped stale awaiting_seed donation %s (age > %dms)', donation.id, ttlMs);
569
- }
570
- catch (err) {
571
- log('failed to reap donation %s: %s', donation.id, errorMessage(err));
572
- }
573
- }
574
- return reaped;
575
- }
576
- /**
577
- * Auto-terminate donations stuck in `provisioning` past `ttlMs` — the record
578
- * is written before the child spawn starts, so a host crash/kill anywhere in
579
- * that window (including mid-spawn) leaves nothing to advance it across a
580
- * restart: there is no in-flight `provisionLocked` call left to reach its
581
- * post-spawn re-read. Run on the same periodic sweep and startup pass as
582
- * {@link reapStaleAwaitingSeed}. Age is measured from `updatedAt`, which for a
583
- * genuinely-stuck row equals `createdAt` — `provisionLocked` never touches a
584
- * `provisioning` record again except to advance it out of this predicate.
585
- * Best-effort per record: a failed reap is logged and the sweep continues.
586
- * Returns the reaped donation ids.
587
- */
588
- async reapStaleProvisioning(ttlMs = DONATION_PROVISIONING_TTL_MS) {
589
- const cutoff = this.now().getTime() - ttlMs;
590
- const stale = this.store.list().filter((d) => isStaleProvisioning(d, cutoff));
591
- const reaped = [];
592
- for (const donation of stale) {
593
- try {
594
- // Re-read: an in-flight (same-process) provisionLocked call can still
595
- // advance this exact record between the snapshot above and now.
596
- const current = this.store.get(donation.id);
597
- if (!current || !isStaleProvisioning(current, cutoff))
598
- continue;
599
- await this.reclaimStuckProvisioning(current);
600
- reaped.push(donation.id);
601
- log('reaped stuck provisioning donation %s (age > %dms)', donation.id, ttlMs);
602
- }
603
- catch (err) {
604
- log('failed to reap stuck provisioning donation %s: %s', donation.id, errorMessage(err));
605
- }
606
- }
607
- return reaped;
608
- }
609
- /**
610
- * Terminalize a stuck-`provisioning` record as `error` and reclaim any child
611
- * the orchestrator can still find for it. Status is written FIRST (same
612
- * ordering rule as {@link terminate}): reclaiming fires `onStateChange`, and
613
- * anything listening must already see a terminal record.
614
- *
615
- * NOTE: the stop only reaches a child the orchestrator has a handle for.
616
- * `HostProcessOrchestrator.launchChild` spawns the process and persists the
617
- * handle in the same synchronous step, so the only child this misses is one
618
- * whose host died between the OS spawn and that write — an orphan *process*
619
- * this reap terminalizes the record for but cannot kill (its ports stay held
620
- * until a reboot). Its working directory is no longer out of reach, though:
621
- * with no handle to resolve we fall back to reclaiming by container name,
622
- * which also covers the far commoner case of a host that died before any
623
- * child existed at all. If the spawn→persist window ever widens (an async
624
- * step added between the two), the orchestrator still needs its own orphan
625
- * *process* sweep — a record that names no handle cannot get one after the
626
- * fact.
627
- */
628
- async reclaimStuckProvisioning(donation) {
629
- this.store.put({
630
- ...donation,
631
- status: 'error',
632
- error: 'stuck in provisioning past TTL — host likely restarted mid-spawn',
633
- updatedAt: this.now().toISOString(),
634
- });
635
- const dockerId = this.orchestrator.resolveDockerId?.(donation.id);
636
- if (dockerId) {
637
- await this.safeStop(dockerId);
638
- await this.safeReclaim(dockerId);
639
- }
640
- else {
641
- this.safeReclaimWorkdir(donation.id);
642
- }
643
- }
644
- /** One donation (redacted), or undefined when unknown. */
645
- get(id) {
646
- const donation = this.store.get(id);
647
- return donation ? redact(donation) : undefined;
648
- }
649
- /** All donations (redacted), optionally scoped to one grant token. */
650
- list(grantToken) {
651
- const rows = grantToken ? this.store.listByGrant(grantToken) : this.store.list();
652
- return rows.map(redact);
653
- }
654
- requireDonation(id) {
655
- const donation = this.store.get(id);
656
- if (!donation) {
657
- throw new DonationError('not_found', `No such donation: ${id}`);
658
- }
659
- return donation;
660
- }
661
- /** Best-effort stop; logs but never throws (cleanup path). */
662
- async safeStop(dockerId) {
663
- try {
664
- await this.orchestrator.stopContainer(dockerId);
665
- }
666
- catch (err) {
667
- log('failed to stop container %s: %s', dockerId, errorMessage(err));
668
- }
669
- }
670
- /**
671
- * Persist a failed respawn's attempt counters — plus, when the spawn itself
672
- * succeeded and it was the record write that failed, the new child's handles.
673
- * Merged onto whatever is on disk now, never written wholesale: the caller's
674
- * copy predates the orchestrator round-trip and `store.put` replaces the whole
675
- * row, so writing it back would undo a `terminate` that landed while the spawn
676
- * was in flight and resurrect a loan the borrower just ended.
677
- *
678
- * `status` and `updatedAt` are deliberately untouched — the attempt did not
679
- * succeed, and `updatedAt` is what defers the stale-`awaiting_seed` reap.
680
- *
681
- * Recording `spawned` is what keeps the record pointing at the child that
682
- * actually exists: `createContainer` already dropped the handle the record
683
- * previously named, so leaving the old `dockerId` there would send every later
684
- * stop/reclaim at an id the orchestrator cannot resolve — stranding the node's
685
- * workdir on disk forever.
686
- *
687
- * Best-effort: we are already unwinding a respawn failure, and a store error
688
- * here must not mask it. Losing the write costs the caller one extra attempt
689
- * before backoff; the supervisor's next pass re-reads the record, finds the
690
- * named child not running, and respawns again — which drops whatever handle is
691
- * current, so the ports self-heal either way.
692
- */
693
- storeRespawnAttempt(id, respawn, spawned) {
694
- try {
695
- // A row that vanished (terminate + delete) must not be recreated.
696
- const current = this.store.get(id);
697
- if (!current)
698
- return;
699
- this.store.put({ ...current, respawn, ...spawned });
700
- }
701
- catch (err) {
702
- log('failed to record respawn attempt for %s: %s', id, errorMessage(err));
703
- }
704
- }
705
- /** Best-effort remove; logs but never throws (cleanup path). */
706
- async safeReclaim(dockerId) {
707
- try {
708
- await this.orchestrator.removeContainer(dockerId);
709
- }
710
- catch (err) {
711
- log('failed to reclaim container %s: %s', dockerId, errorMessage(err));
712
- }
713
- }
714
- /**
715
- * Best-effort removal of the working directory of a donation whose spawn
716
- * never produced a `dockerId`; logs but never throws (cleanup path). A no-op
717
- * on an orchestrator without the capability, and on one that refuses because
718
- * a live handle still owns the directory.
719
- */
720
- safeReclaimWorkdir(id) {
721
- try {
722
- if (this.orchestrator.reclaimWorkdir?.(id)) {
723
- log('reclaimed orphaned workdir for donation %s', id);
724
- }
725
- }
726
- catch (err) {
727
- log('failed to reclaim workdir for donation %s: %s', id, errorMessage(err));
728
- }
729
- }
730
- /**
731
- * Run `fn` after any in-flight provision or grant teardown for the same grant
732
- * token, so the quota check + record-create pair is atomic per grant and a
733
- * teardown sees every record a queued provision writes.
734
- */
735
- async serializeByGrant(token, fn) {
736
- const prior = this.grantTail.get(token) ?? Promise.resolve();
737
- const run = prior.then(fn, fn);
738
- // The stored tail swallows outcomes — a rejected provision must not reject
739
- // the next caller's wait, only defer it.
740
- this.grantTail.set(token, run.then(() => undefined, () => undefined));
741
- return run;
742
- }
743
- }
744
- /** `grn_<high-entropy base64url>` — also the donated node's orchestrator containerId. */
745
- function generateDonationId() {
746
- return `grn_${randomBytes(12).toString('base64url')}`;
747
- }
748
- /** Strip the host-only secrets (`seedToken`) and internal URL (`seedEndpoint`). */
749
- function redact(donation) {
750
- const { seedToken: _seedToken, seedEndpoint: _seedEndpoint, ...view } = donation;
751
- return view;
752
- }
753
- /**
754
- * Shape-check the requester-supplied owner-key pins at the boundary they arrive
755
- * on, returning them trimmed so the persisted record and the child's
756
- * `CADRE_OWNER_KEYS` carry exactly what was validated — the same discipline
757
- * `cadre-cli start` applies to its own `--pin-owner-key` / `CADRE_OWNER_KEYS`.
758
- *
759
- * `requireEd25519PublicKeyB64` throws a plain `Error`; it is re-thrown as
760
- * `invalid_request` so `server/error-handler.ts` renders it as a 400 naming the
761
- * bad key rather than a 500.
762
- *
763
- * Deliberately NOT applied in {@link DonationService.respawn}, which replays
764
- * `donation.ownerKeys` off a record written before this check existed: validating
765
- * there would make such a record permanently un-respawnable, and by then the pins
766
- * are already inside the trust boundary. Validating the boundary is the point.
767
- */
768
- function validateOwnerKeys(keys) {
769
- // NOTE: every throw out of this `try` is reported to the caller as their fault.
770
- // True while `requireEd25519PublicKeyB64` rejects only bad input (and while the
771
- // route ahead of it has already established the entries are strings); if it ever
772
- // grows a failure of its own — a key-server lookup, a curve check needing crypto
773
- // — narrow this catch, or a host-side fault answers 400.
774
- try {
775
- return (keys ?? []).map((key) => requireEd25519PublicKeyB64(key, 'donation owner key (ownerKeys)'));
776
- }
777
- catch (err) {
778
- throw new DonationError('invalid_request', errorMessage(err));
779
- }
780
- }
781
- /** Map a grant denial to the donation error the routes surface as HTTP status. */
782
- function denialToError(reason) {
783
- switch (reason) {
784
- case 'quota_exceeded':
785
- return new DonationError('quota_exceeded', 'Grant is already at its node cap');
786
- case 'expired':
787
- case 'revoked':
788
- return new DonationError('forbidden', `Grant is ${reason}`);
789
- case 'unknown_token':
790
- default:
791
- return new DonationError('unauthorized', 'Unknown or missing grant token');
792
- }
793
- }
794
- /**
795
- * Whether a record still needs a grant teardown. Stated once and applied twice
796
- * in {@link DonationService.terminateGrant} — on the candidate list, and again
797
- * per record before terminating it.
798
- */
799
- function isUnterminated(donation) {
800
- return donation !== undefined && donation.status !== 'terminated';
801
- }
802
- /**
803
- * Whether a record is still a stale-`awaiting_seed` reap candidate: the requester
804
- * provisioned a node and has not presented a seed since `cutoff`. Stated once and
805
- * applied twice in {@link DonationService.reapStaleAwaitingSeed} — on the sweep's
806
- * candidate list, and again per record before the terminal write.
807
- */
808
- function isReapable(donation, cutoff) {
809
- return donation?.status === 'awaiting_seed' && Date.parse(donation.updatedAt) < cutoff;
810
- }
811
- /**
812
- * Whether a record is still a stuck-`provisioning` reap candidate. Stated
813
- * once and applied twice in {@link DonationService.reapStaleProvisioning} — on
814
- * the sweep's candidate list, and again per record before the terminal write.
815
- */
816
- function isStaleProvisioning(donation, cutoff) {
817
- return donation?.status === 'provisioning' && Date.parse(donation.updatedAt) < cutoff;
818
- }
819
- /** Derive the node's `/status` URL from its `/seed` URL (same origin/port). */
820
- function toStatusUrl(seedEndpoint) {
821
- const url = new URL(seedEndpoint);
822
- url.pathname = '/status';
823
- return url.toString();
824
- }
825
- function errorMessage(err) {
826
- return err instanceof Error ? err.message : String(err);
827
- }
828
- //# sourceMappingURL=donation-service.js.map