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