@serfab/cadre-host 0.12.0 → 1.0.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 (70) hide show
  1. package/README.md +6 -4
  2. package/dist/bin/host.js +9 -1
  3. package/dist/bin/host.js.map +1 -1
  4. package/dist/donation/__tests__/fake-orchestrator.js +1 -1
  5. package/dist/donation/__tests__/fake-orchestrator.js.map +1 -1
  6. package/dist/donation/donation-service.d.ts +7 -2
  7. package/dist/donation/donation-service.js +16 -2
  8. package/dist/donation/donation-service.js.map +1 -1
  9. package/dist/donation/donation-supervisor.d.ts +12 -2
  10. package/dist/donation/donation-supervisor.js +25 -2
  11. package/dist/donation/donation-supervisor.js.map +1 -1
  12. package/dist/donation/types.d.ts +2 -1
  13. package/dist/donation/types.js.map +1 -1
  14. package/dist/installer/index.d.ts +9 -1
  15. package/dist/installer/index.js +5 -1
  16. package/dist/installer/index.js.map +1 -1
  17. package/dist/orchestrator/host-process-orchestrator.d.ts +71 -11
  18. package/dist/orchestrator/host-process-orchestrator.js +173 -75
  19. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  20. package/dist/orchestrator/port-allocator.d.ts +44 -2
  21. package/dist/orchestrator/port-allocator.js +63 -5
  22. package/dist/orchestrator/port-allocator.js.map +1 -1
  23. package/dist/orchestrator/port-probe.d.ts +15 -0
  24. package/dist/orchestrator/port-probe.js +22 -0
  25. package/dist/orchestrator/port-probe.js.map +1 -0
  26. package/dist/orchestrator/types.d.ts +13 -1
  27. package/dist/orchestrator/types.js.map +1 -1
  28. package/dist/server/routes/bootstrap-node-validation.d.ts +115 -0
  29. package/dist/server/routes/bootstrap-node-validation.js +197 -0
  30. package/dist/server/routes/bootstrap-node-validation.js.map +1 -0
  31. package/dist/server/routes/grants.js +8 -25
  32. package/dist/server/routes/grants.js.map +1 -1
  33. package/dist/server/routes/provision-request-validation.d.ts +45 -0
  34. package/dist/server/routes/provision-request-validation.js +97 -0
  35. package/dist/server/routes/provision-request-validation.js.map +1 -0
  36. package/dist/server/server.d.ts +4 -1
  37. package/dist/server/server.js +36 -2
  38. package/dist/server/server.js.map +1 -1
  39. package/dist/ui/assets/{index-C-iks41M.js → index-CEoNRwM_.js} +3 -3
  40. package/dist/ui/assets/{index-C-iks41M.js.map → index-CEoNRwM_.js.map} +1 -1
  41. package/dist/ui/index.html +1 -1
  42. package/package.json +5 -4
  43. package/src/__tests__/orchestrator-env-scrub.test.ts +22 -0
  44. package/src/__tests__/orchestrator-node-identity.test.ts +4 -4
  45. package/src/__tests__/orchestrator-owner.test.ts +45 -2
  46. package/src/__tests__/orchestrator-ports.test.ts +172 -0
  47. package/src/__tests__/orchestrator.test.ts +1062 -951
  48. package/src/bin/host.ts +9 -1
  49. package/src/donation/__tests__/donation-service.test.ts +94 -7
  50. package/src/donation/__tests__/donation-supervisor.test.ts +50 -12
  51. package/src/donation/__tests__/fake-orchestrator.test.ts +168 -168
  52. package/src/donation/__tests__/fake-orchestrator.ts +1 -1
  53. package/src/donation/donation-service.ts +22 -3
  54. package/src/donation/donation-supervisor.ts +25 -2
  55. package/src/donation/types.ts +2 -1
  56. package/src/installer/__tests__/installer.smoke.test.ts +263 -218
  57. package/src/installer/index.ts +327 -314
  58. package/src/orchestrator/host-process-orchestrator.ts +1250 -1138
  59. package/src/orchestrator/port-allocator.ts +148 -91
  60. package/src/orchestrator/port-probe.ts +31 -0
  61. package/src/orchestrator/types.ts +13 -1
  62. package/src/server/__tests__/bootstrap-node-validation.test.ts +138 -0
  63. package/src/server/__tests__/grants-route.test.ts +394 -263
  64. package/src/server/__tests__/nodes-route.test.ts +2 -2
  65. package/src/server/__tests__/publishers.test.ts +1 -1
  66. package/src/server/__tests__/status-route.test.ts +1 -1
  67. package/src/server/routes/bootstrap-node-validation.ts +206 -0
  68. package/src/server/routes/grants.ts +9 -26
  69. package/src/server/routes/provision-request-validation.ts +105 -0
  70. package/src/server/server.ts +157 -122
@@ -85,7 +85,7 @@ const SAMPLE_NODE: ManagedNodeInfo = {
85
85
  status: 'running',
86
86
  spawnedAt: '2025-01-01T00:00:00Z',
87
87
  workdir: '',
88
- ports: { health: 11, metrics: 12, p2p: 13, admin: 14 },
88
+ ports: { health: 11, metrics: 12, p2p: 13, admin: 14, ws: 15 },
89
89
  };
90
90
 
91
91
  describe('/api/nodes routes', () => {
@@ -200,7 +200,7 @@ describe('/api/nodes — owner node start/restart', () => {
200
200
  status: 'running',
201
201
  spawnedAt: '2025-01-01T00:00:00Z',
202
202
  workdir: '',
203
- ports: { health: 1, metrics: 2, p2p: 4555, admin: 3 },
203
+ ports: { health: 1, metrics: 2, p2p: 4555, admin: 3, ws: 4 },
204
204
  owner: true,
205
205
  };
206
206
 
@@ -131,7 +131,7 @@ describe('publisher wiring', () => {
131
131
  status: 'stopped',
132
132
  spawnedAt: 'x',
133
133
  workdir: '/tmp',
134
- ports: { health: 1, metrics: 2, p2p: 3, admin: 4 },
134
+ ports: { health: 1, metrics: 2, p2p: 3, admin: 4, ws: 5 },
135
135
  });
136
136
  expect(received).toContainEqual({
137
137
  type: 'node-state-changed',
@@ -64,7 +64,7 @@ describe('GET /api/status', () => {
64
64
  status: 'running',
65
65
  spawnedAt: '2025-01-01T00:00:00Z',
66
66
  workdir: '/tmp/alice',
67
- ports: { health: 1, metrics: 2, p2p: 3, admin: 4 },
67
+ ports: { health: 1, metrics: 2, p2p: 3, admin: 4, ws: 5 },
68
68
  },
69
69
  ]),
70
70
  trustCircle: fakeTrustCircle({
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Shape validation for the requester-supplied `bootstrapNodes` of `POST /grants`
3
+ * — the requester's control-network addresses the donated node is started with
4
+ * (written into the child's `cadre.json` as `controlNetwork.bootstrapNodes` by
5
+ * `orchestrator/host-process-orchestrator.ts`) and hands to `@libp2p/bootstrap`.
6
+ *
7
+ * Its own module rather than part of `grants.ts`: the per-entry rule is a duplicate
8
+ * of cadre-provider's copy (`packages/cadre-provider/src/server/bootstrap-node-validation.ts`)
9
+ * and must stay identical to it, so it is worth reading, testing and changing on
10
+ * its own, without a routing file around it — the same arrangement cadre-provider
11
+ * uses for its restatement of cadre-core's owner-key rule.
12
+ *
13
+ * ## An empty list is accepted — where this copy differs, on purpose
14
+ *
15
+ * The field may be absent or `[]`; cadre-provider's copy still requires at least one
16
+ * address. A lent node's requester is typically a phone, and a phone has no address
17
+ * to give — its node listens on nothing and can only dial out. Such a requester sends
18
+ * no addresses and dials the node itself, at the WebSocket address
19
+ * `GET /grants/:id/peer` reports. The node starts with no bootstrap peers and waits,
20
+ * and admits that first inbound connection because it holds no authorized members
21
+ * yet (`admitInboundControlConnection` / `authorizeInboundControlStream` in
22
+ * `cadre-core/src/cadre-node.ts`). A provider container has no such requester yet, so
23
+ * there an empty list is still the node-comes-up-alone failure described below
24
+ * (`backlog/feat-provider-drone-reachable-by-phone`).
25
+ *
26
+ * The difference is at the list level only: every entry that IS given must pass the
27
+ * rule below, which is identical in both packages.
28
+ *
29
+ * ## The rule, and why each clause is there
30
+ *
31
+ * An entry is usable exactly when it is a string, parses as a multiaddr, carries
32
+ * a `/p2p/<peerId>` component whose peer id decodes, and says where that peer is.
33
+ * Each clause corresponds to a distinct downstream failure the caller would
34
+ * otherwise never be told about — the value is forwarded verbatim into the spawned
35
+ * child, so every one of these surfaces where the caller cannot see it:
36
+ *
37
+ * - **Not parsable as a multiaddr → the child dies at boot.** `@libp2p/bootstrap`'s
38
+ * constructor maps `multiaddr()` over the whole list *before* filtering anything,
39
+ * and `multiaddr()` throws on a string that does not start with `/` (and on a
40
+ * non-string outright). libp2p construction throws and the node never starts.
41
+ * - **No `/p2p/<peerId>` → the node starts and never joins.** The quiet one.
42
+ * `/ip4/127.0.0.1/tcp/4001` parses fine, then `@libp2p/bootstrap` filters it out
43
+ * ("invalid bootstrap multiaddr without peer id", logged inside the child) and
44
+ * the node comes up with *zero* bootstrap peers: healthy-looking, permanently
45
+ * alone, never reaching the party it was created for. cadre-core's
46
+ * `getBootstrapPeerIds` (`packages/cadre-core/src/cadre-node.ts`) skips such an
47
+ * entry silently for the same reason.
48
+ * - **Malformed peer id → the child dies at boot.** `multiaddr()` does *not*
49
+ * validate the `/p2p/` value — parsing `/ip4/1.2.3.4/tcp/1/p2p/12D3KooReq` yields
50
+ * a `p2p` component whose value is the junk string unchanged — but
51
+ * `@libp2p/bootstrap` then calls `peerIdFromString` on it, unguarded, and it
52
+ * throws `Incorrect length`. A truncated copy-paste of a 52-character peer id is
53
+ * the likeliest human typo in this field.
54
+ * - **No location at all → the node starts and never joins.** `/p2p/<peerId>` (and
55
+ * `/p2p/<relay>/p2p-circuit/p2p/<target>`) parses and names a decodable peer, and
56
+ * `@libp2p/bootstrap` keeps it — but it says nothing about *where* the peer is, so
57
+ * libp2p finds no transport for it and the dial fails with no valid addresses.
58
+ * The node comes up with a bootstrap peer it can never reach, which looks the same
59
+ * from outside as having none. Only the total absence of a location is rejected:
60
+ * which transports the child can actually dial is the embedder's choice
61
+ * (`NetworkConfig.transports`), invisible from here, so a partial address like
62
+ * `/ip4/1.2.3.4/p2p/<peerId>` is deliberately left to the child.
63
+ *
64
+ * The peer id is read the way `@libp2p/bootstrap` reads it — the `p2p` components
65
+ * of `getComponents()` — rather than through the deprecated `getPeerId()`, so the
66
+ * two cannot disagree about which part of the address is the peer. Bootstrap uses
67
+ * only the *last* `p2p` component; this checks **every** one, so the relay half of
68
+ * a `…/p2p/<relay>/p2p-circuit/p2p/<target>` address must decode too. An address
69
+ * naming an undecodable relay is not dialable either, and bootstrap's own
70
+ * `P2P.matches` filter accepts any address carrying a `p2p` component, so nothing
71
+ * this accepts is dropped there.
72
+ *
73
+ * Requiring a multiaddr also closes a downstream ambiguity on the *other* side of
74
+ * this rule: cadre-provider joins its list with `,` into `CADRE_BOOTSTRAP_NODES`
75
+ * and cadre-cli's env loader splits it back on `,`, so an entry containing a comma
76
+ * would silently become two addresses there. This host writes JSON rather than an
77
+ * env var and so is not exposed to that, but the two per-entry rules are kept
78
+ * identical — see the note about manual upkeep below.
79
+ *
80
+ * Reachability is deliberately NOT checked: a well-formed address for a peer that
81
+ * happens to be down is indistinguishable here from one that is up, and no
82
+ * boundary check can tell them apart. This validates the *shape* the child must be
83
+ * able to parse, nothing more.
84
+ *
85
+ * Keeping the two per-entry rules in step is **manual** — neither package can see
86
+ * the other's rule, so no test can compare them. What the tests give instead is a
87
+ * tripwire on each side: `../__tests__/bootstrap-node-validation.test.ts` here and
88
+ * `packages/cadre-provider/src/server/__tests__/bootstrap-node-validation.test.ts`
89
+ * there each pin their own copy to the same per-entry accept/reject table (the
90
+ * empty-list row is the one that differs), so changing either rule fails that
91
+ * package's own suite — and the comment above the rule you just changed is what
92
+ * points at the other copy.
93
+ */
94
+
95
+ import debug from 'debug';
96
+ import { CODE_P2P, CODE_P2P_CIRCUIT, multiaddr, type Multiaddr } from '@multiformats/multiaddr';
97
+ import { peerIdFromString } from '@libp2p/peer-id';
98
+
99
+ const log = debug('cadre:host:bootstrap-nodes');
100
+
101
+ /**
102
+ * Longest rejected address echoed back in an error message. Generous compared to
103
+ * the owner-key limit because a legitimate address is long: a plain
104
+ * `/ip4/…/tcp/…/p2p/<52 chars>` runs ~80 characters and a relayed
105
+ * `…/p2p-circuit/p2p/<52 chars>` about 150, so a smaller cap would truncate the
106
+ * very values an operator needs to read back.
107
+ */
108
+ const REJECTED_ADDRESS_ECHO_LIMIT = 192;
109
+
110
+ /**
111
+ * Render a rejected address for an error message, capped: `bootstrapNodes`
112
+ * arrives from a caller over the network, so an unbounded echo would let one junk
113
+ * string become a megabyte of log line.
114
+ */
115
+ function describeRejectedAddress(value: string): string {
116
+ return value.length <= REJECTED_ADDRESS_ECHO_LIMIT
117
+ ? value
118
+ : `${value.slice(0, REJECTED_ADDRESS_ECHO_LIMIT)}… (${value.length} chars)`;
119
+ }
120
+
121
+ /** The message of a thrown parse/decode failure, whatever the thrower used. */
122
+ function reasonOf(error: unknown): string {
123
+ return error instanceof Error ? error.message : String(error);
124
+ }
125
+
126
+ /**
127
+ * Apply the rule above to one entry. Returns the trimmed value, so the create
128
+ * provision request carries exactly what was validated.
129
+ */
130
+ function validateBootstrapNode(value: string): { node: string } | { error: string } {
131
+ const trimmed = value.trim();
132
+ if (trimmed.length === 0) {
133
+ return { error: 'bootstrapNodes entries must not be empty or whitespace-only' };
134
+ }
135
+
136
+ let address: Multiaddr;
137
+ try {
138
+ address = multiaddr(trimmed);
139
+ } catch (error) {
140
+ log('rejecting bootstrapNodes entry: %s', reasonOf(error));
141
+ return {
142
+ error: `bootstrapNodes entries must be multiaddrs (could not parse "${describeRejectedAddress(trimmed)}": ${reasonOf(error)})`,
143
+ };
144
+ }
145
+
146
+ const components = address.getComponents();
147
+ const peerIds = components.filter(component => component.code === CODE_P2P);
148
+ if (peerIds.length === 0) {
149
+ return {
150
+ error: `bootstrapNodes entries must include a /p2p/<peerId> component ("${describeRejectedAddress(trimmed)}" names no peer, so the node would drop it and start with no bootstrap peers)`,
151
+ };
152
+ }
153
+
154
+ if (!components.some(component => component.code !== CODE_P2P && component.code !== CODE_P2P_CIRCUIT)) {
155
+ return {
156
+ error: `bootstrapNodes entries must name where to reach the peer ("${describeRejectedAddress(trimmed)}" names only peer ids, so no transport can dial it and the node would start with no reachable bootstrap peers)`,
157
+ };
158
+ }
159
+
160
+ for (const { value } of peerIds) {
161
+ try {
162
+ peerIdFromString(value ?? '');
163
+ } catch (error) {
164
+ log('rejecting bootstrapNodes peer id: %s', reasonOf(error));
165
+ return {
166
+ error: `bootstrapNodes entries must carry a decodable peer id ("${describeRejectedAddress(trimmed)}" names peer "${describeRejectedAddress(value ?? '')}", which does not decode: ${reasonOf(error)})`,
167
+ };
168
+ }
169
+ }
170
+
171
+ return { node: trimmed };
172
+ }
173
+
174
+ /**
175
+ * Validate the optional `bootstrapNodes` field of a provision request: absent, or an
176
+ * array of dialable control-network addresses (see {@link validateBootstrapNode}).
177
+ * Absent and `[]` alike mean the requester dials the node itself — see "An empty list
178
+ * is accepted" in the module comment.
179
+ *
180
+ * Provisioning is the last point at which the requester can still fix a typo, so
181
+ * the shape is checked here: without it a bad address is answered 201 and then
182
+ * produces a donated node that either dies at boot or comes up permanently alone
183
+ * — the requester learning about it, if ever, from donation status rather than
184
+ * from a 400 naming the bad address.
185
+ *
186
+ * Every rejection names the offending entry: with several addresses in one
187
+ * request the message is the only thing that says WHICH one.
188
+ *
189
+ * @returns the trimmed addresses (`[]` when none were given), so the provision request carries exactly what was validated.
190
+ */
191
+ export function validateBootstrapNodes(value: unknown): { nodes: string[] } | { error: string } {
192
+ if (value === undefined) {
193
+ return { nodes: [] };
194
+ }
195
+ if (!Array.isArray(value) || !value.every((entry): entry is string => typeof entry === 'string')) {
196
+ return { error: 'bootstrapNodes must be an array of strings' };
197
+ }
198
+
199
+ const nodes: string[] = [];
200
+ for (const entry of value) {
201
+ const checked = validateBootstrapNode(entry);
202
+ if ('error' in checked) return checked;
203
+ nodes.push(checked.node);
204
+ }
205
+ return { nodes };
206
+ }
@@ -20,8 +20,9 @@
20
20
 
21
21
  import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
22
22
 
23
- import type { DonationService, DonationProvisionRequest } from '../../donation/donation-service.js';
23
+ import type { DonationService } from '../../donation/donation-service.js';
24
24
  import type { DonationView, GrantValidator } from '../../donation/types.js';
25
+ import { validateProvisionRequest } from './provision-request-validation.js';
25
26
 
26
27
  export interface GrantsRoutesOptions {
27
28
  donations: DonationService;
@@ -109,33 +110,15 @@ export function registerGrantsRoutes(app: FastifyInstance, opts: GrantsRoutesOpt
109
110
  return errorResponse(reply, 'unauthorized', 'Missing bearer grant token', 401);
110
111
  }
111
112
 
112
- const body = (request.body ?? {}) as Partial<DonationProvisionRequest>;
113
- if (typeof body.partyId !== 'string' || body.partyId.length === 0) {
114
- return errorResponse(reply, 'invalid_request', 'partyId is required', 400);
115
- }
116
- if (!Array.isArray(body.bootstrapNodes) || body.bootstrapNodes.length === 0) {
117
- return errorResponse(reply, 'invalid_request', 'bootstrapNodes is required', 400);
118
- }
119
- if (!Array.isArray(body.ownerKeys) || body.ownerKeys.length === 0) {
120
- return errorResponse(reply, 'invalid_request', 'ownerKeys is required', 400);
121
- }
122
- // Element types too, not just the array: `provision`'s shape check trims each
123
- // entry, so a non-string reaches the caller as an internal `.trim is not a
124
- // function` rather than as a message naming what is wrong with the request.
125
- if (!body.ownerKeys.every(key => typeof key === 'string')) {
126
- return errorResponse(reply, 'invalid_request', 'ownerKeys must be an array of strings', 400);
127
- }
128
- if (body.profile !== undefined && body.profile !== 'storage' && body.profile !== 'transaction') {
129
- return errorResponse(reply, 'invalid_request', 'profile must be "storage" or "transaction"', 400);
113
+ // One validator owns the whole body — see `provision-request-validation.ts`
114
+ // for why no per-field check lives here. Nothing is provisioned on a
115
+ // rejection: this runs before the service is touched.
116
+ const validated = validateProvisionRequest(request.body ?? {}, token);
117
+ if ('error' in validated) {
118
+ return errorResponse(reply, 'invalid_request', validated.error, 400);
130
119
  }
131
120
 
132
- const donation = await donations.provision({
133
- grantToken: token,
134
- partyId: body.partyId,
135
- bootstrapNodes: body.bootstrapNodes,
136
- ownerKeys: body.ownerKeys,
137
- ...(body.profile ? { profile: body.profile } : {}),
138
- });
121
+ const donation = await donations.provision(validated.request);
139
122
  return reply.status(201).send({ ok: true, data: { donation } });
140
123
  });
141
124
 
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The whole shape check for `POST /grants` — one call that either yields the
3
+ * typed {@link DonationProvisionRequest} the `DonationService` is handed, or the
4
+ * message the route answers 400 with.
5
+ *
6
+ * **Why a validator rather than a few more `if`s in the route.** Every field in
7
+ * this body is forwarded into a child process the requester cannot see:
8
+ * `partyId`, `bootstrapNodes` and `profile` are written into the child's
9
+ * `cadre.json` (`orchestrator/host-process-orchestrator.ts`) and `ownerKeys`
10
+ * become its cold-start seed-trust anchors. A field the route forgets to check is
11
+ * not a 400 — it is a donated node that dies at boot, or comes up subtly wrong,
12
+ * with a 201 already sent. Routing the body through one function that *constructs*
13
+ * the request object means a field can only reach the spawn path by having been
14
+ * through here; adding a field to `DonationProvisionRequest` without validating it
15
+ * stops compiling rather than silently shipping.
16
+ *
17
+ * **Division of labour with `DonationService.provision`.** The Ed25519 rule for
18
+ * `ownerKeys` stays in the service, where it is applied by cadre-core's own
19
+ * `requireEd25519PublicKeyB64` — the service is also reached by the respawn path,
20
+ * which replays a persisted record rather than an HTTP body, so the crypto rule
21
+ * has to live there to cover both. What this validator owns for `ownerKeys` is the
22
+ * *container* shape (present, non-empty, all strings), which the service's rule
23
+ * assumes: a number reaching it surfaces as an internal `.trim is not a function`
24
+ * rather than as a message naming what is wrong with the request.
25
+ *
26
+ * The multiaddr rule has no such home — it is duplicated in cadre-provider — so it
27
+ * lives in `bootstrap-node-validation.ts` next to the comment saying so.
28
+ */
29
+
30
+ import type { DonationProvisionRequest } from '../../donation/donation-service.js';
31
+ import { validateBootstrapNodes } from './bootstrap-node-validation.js';
32
+
33
+ /** `partyId` becomes `controlNetwork.partyId` in the child's config. */
34
+ function validatePartyId(value: unknown): { partyId: string } | { error: string } {
35
+ if (typeof value !== 'string' || value.trim().length === 0) {
36
+ return { error: 'partyId is required' };
37
+ }
38
+ return { partyId: value.trim() };
39
+ }
40
+
41
+ /**
42
+ * Container shape only — see the module comment: the per-key Ed25519 rule is
43
+ * `DonationService.provision`'s, so the respawn path gets it too.
44
+ */
45
+ function validateOwnerKeys(value: unknown): { ownerKeys: string[] } | { error: string } {
46
+ if (!Array.isArray(value) || value.length === 0) {
47
+ return { error: 'ownerKeys is required' };
48
+ }
49
+ if (!value.every((key): key is string => typeof key === 'string')) {
50
+ return { error: 'ownerKeys must be an array of strings' };
51
+ }
52
+ return { ownerKeys: value };
53
+ }
54
+
55
+ /** Absent means `storage` — see {@link DonationProvisionRequest.profile}. */
56
+ function validateProfile(value: unknown): { profile?: DonationProvisionRequest['profile'] } | { error: string } {
57
+ if (value === undefined) return {};
58
+ if (value !== 'storage' && value !== 'transaction') {
59
+ return { error: 'profile must be "storage" or "transaction"' };
60
+ }
61
+ return { profile: value };
62
+ }
63
+
64
+ /**
65
+ * Validate a `POST /grants` body and build the request `DonationService.provision`
66
+ * is handed.
67
+ *
68
+ * `grantToken` comes from the `Authorization` bearer rather than the body — a
69
+ * requester does not get to name which grant pays for this — so it is a
70
+ * parameter, not a validated field. Whether that grant is live and within quota is
71
+ * `provision`'s call, not this function's.
72
+ *
73
+ * @returns the typed provision request, or the message to answer `invalid_request` with.
74
+ */
75
+ export function validateProvisionRequest(
76
+ body: unknown,
77
+ grantToken: string,
78
+ ): { request: DonationProvisionRequest } | { error: string } {
79
+ if (typeof body !== 'object' || body === null || Array.isArray(body)) {
80
+ return { error: 'request body must be a JSON object' };
81
+ }
82
+ const fields = body as Record<string, unknown>;
83
+
84
+ const partyId = validatePartyId(fields.partyId);
85
+ if ('error' in partyId) return partyId;
86
+
87
+ const bootstrap = validateBootstrapNodes(fields.bootstrapNodes);
88
+ if ('error' in bootstrap) return bootstrap;
89
+
90
+ const ownerKeys = validateOwnerKeys(fields.ownerKeys);
91
+ if ('error' in ownerKeys) return ownerKeys;
92
+
93
+ const profile = validateProfile(fields.profile);
94
+ if ('error' in profile) return profile;
95
+
96
+ return {
97
+ request: {
98
+ grantToken,
99
+ partyId: partyId.partyId,
100
+ bootstrapNodes: bootstrap.nodes,
101
+ ownerKeys: ownerKeys.ownerKeys,
102
+ ...(profile.profile ? { profile: profile.profile } : {}),
103
+ },
104
+ };
105
+ }