@serfab/cadre-host 1.9.0 → 1.11.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.
@@ -1,260 +1,260 @@
1
- /**
2
- * Donation grant-token types for cadre-host.
3
- *
4
- * A **grant token** is a high-entropy base64url secret the host admin issues,
5
- * out-of-band (QR / copy-paste), to one *grantee* — a friend or family member
6
- * whose cadre authority (their phone) may then ask this host to spawn donated
7
- * nodes. The grantee presents the token as `Authorization: Bearer <grant-token>`
8
- * on every donation request (the grantee-facing surface lands in the
9
- * `2-donation-service` ticket).
10
- *
11
- * This module owns the grant's identity, expiry, and per-grantee quota. The
12
- * *live-node tally* it checks the quota against is owned by the donation
13
- * service, not by the grant layer — see `GrantValidator.validateForProvision`.
14
- *
15
- * **Grant ≠ trust-circle membership.** A trust-circle invite (`auth/`)
16
- * authorises a device to join *the host's own* cadre. A donation grant
17
- * authorises an external cadre authority to ask the host to spawn a node that
18
- * joins *the grantee's* cadre. The two token flows are deliberately separate
19
- * modules; this one reuses the *shape* of the trust-circle store (atomic
20
- * write-then-rename JSON, token-keyed rows) but with grant — not invite —
21
- * semantics: a grant is long-lived and reusable up to a quota, never
22
- * one-time-redeemed.
23
- */
24
-
25
- /** A grant the host admin issued to one grantee (friend/family). */
26
- export interface Grant {
27
- /** base64url secret; also the bearer credential. The store key. */
28
- token: string;
29
- /** Human label chosen by the admin, e.g. "Alice's cadre". Display-only. */
30
- label: string;
31
- /** Max concurrently-live donated nodes this grant may hold. */
32
- maxNodes: number;
33
- /** ISO timestamp when the grant was issued. */
34
- createdAt: string;
35
- /** ISO expiry; absent = no expiry. */
36
- expiresAt?: string;
37
- /** Set when the admin revokes; a revoked grant validates as denied. */
38
- revokedAt?: string;
39
- }
40
-
41
- /** One grant as the admin list reports it: the grant plus what is running under it. */
42
- export interface GrantListing extends Grant {
43
- /** Donations counting against `maxNodes` (provisioning / awaiting_seed / seeded). */
44
- liveNodes: number;
45
- /** Every donation under this grant that is not `terminated` — what revoke would tear down. */
46
- donations: Array<{ id: string; status: DonationStatus }>;
47
- }
48
-
49
- /** Why a presented grant token was denied. */
50
- export type GrantDenyReason =
51
- | 'unknown_token' // no such grant
52
- | 'expired'
53
- | 'revoked'
54
- | 'quota_exceeded'; // live node count already at maxNodes
55
-
56
- /** Result of validating a presented bearer token. */
57
- export interface GrantValidation {
58
- ok: boolean;
59
- /** The matched grant, when the token names one (present even on some denials). */
60
- grant?: Grant;
61
- /** Set when `ok` is false. */
62
- reason?: GrantDenyReason;
63
- }
64
-
65
- /**
66
- * The slice `2-donation-service` depends on. Keeps that ticket decoupled from
67
- * the store implementation: it holds a `GrantValidator`, not a `GrantStore`.
68
- *
69
- * Both methods are pure functions of the store state (and, for provision, the
70
- * caller-supplied count) — they never throw for a bad token, they return a
71
- * denial. Issuance/revocation (which mutate) live on `GrantService`.
72
- */
73
- export interface GrantValidator {
74
- /**
75
- * Validate a presented bearer token for a *new* provision request.
76
- *
77
- * `liveNodeCount(token)` is supplied by the donation service — the grant
78
- * layer owns identity/expiry/revocation; the donation service owns the
79
- * authoritative live-node tally (it holds the grant→node records). The count
80
- * is only consulted once identity/expiry/revocation have passed, so an
81
- * unknown or dead token never invokes it.
82
- */
83
- validateForProvision(
84
- token: string,
85
- liveNodeCount: (token: string) => number,
86
- ): GrantValidation;
87
- /**
88
- * Validate for a non-provisioning op (peer/seed/terminate): identity + not
89
- * expired/revoked. No quota check.
90
- */
91
- validate(token: string): GrantValidation;
92
- }
93
-
94
- /** On-disk shape of `grants.json`. */
95
- export interface GrantFile {
96
- version: 1;
97
- /** keyed by token. */
98
- grants: Record<string, Omit<Grant, 'token'>>;
99
- }
100
-
101
- /**
102
- * Typed handlers exposed to the loopback management server for the **admin**
103
- * grant surface (`/grants-admin`). Distinct from the grantee-facing `/grants`
104
- * provisioning surface: the admin surface is loopback, no bearer — same-machine
105
- * admin, matching cadre-host's local-UI "no login" posture.
106
- *
107
- * Handlers throw a `GrantError` (or, for donation teardown, a `DonationError`)
108
- * whose `.code` the server maps to an HTTP status (see `server/error-handler.ts`).
109
- */
110
- export interface GrantAdminHandlers {
111
- postGrant(body: { label: string; maxNodes?: number; ttlMs?: number }): Promise<{ grant: Grant }>;
112
- listGrants(): Promise<{ grants: GrantListing[] }>;
113
- /**
114
- * Revoke a grant and, unless `keepNodes`, terminate every donated node under
115
- * it. Resolves with the ids of the donations terminated.
116
- */
117
- deleteGrant(token: string, opts: { keepNodes: boolean }): Promise<{ terminated: string[] }>;
118
- /**
119
- * Terminate one donated node by id, whatever state its grant is in. Absent
120
- * when no donation service is wired — there are then no donated nodes to end.
121
- */
122
- terminateDonation?(id: string): Promise<void>;
123
- }
124
-
125
- /* ──────────────── donation lifecycle (2-donation-service) ──────────────── */
126
-
127
- /**
128
- * Lifecycle of one donated node:
129
- * provisioning → the child process is being spawned.
130
- * awaiting_seed → spawned + reachable; waiting for the requester to present
131
- * its phone-signed seed (`PUT /grants/:id/seed`).
132
- * seeded → the seed was applied; the node has joined the requester's cadre.
133
- * error → provisioning failed (orchestrator resources reclaimed).
134
- * terminated → stopped + removed (kept in the store for audit).
135
- *
136
- * A donation is "live" (counts against a grant's `maxNodes` quota) while it is
137
- * `provisioning`, `awaiting_seed`, or `seeded` — see `DonationStore.liveNodeCount`.
138
- */
139
- export type DonationStatus =
140
- | 'provisioning'
141
- | 'awaiting_seed'
142
- | 'seeded'
143
- | 'error'
144
- | 'terminated';
145
-
146
- /**
147
- * One donated node, tracked host-side and persisted to `donations.json`.
148
- *
149
- * The host contributes capacity only: `partyId` is the REQUESTER's cadre (a
150
- * foreign party), and `seedToken` gates the node's own `POST /seed` — it is
151
- * minted host-side, persisted here (so a host restart in the request→seed gap
152
- * can still present the seed), and NEVER returned to the grantee.
153
- *
154
- * The record also carries every input the original spawn consumed
155
- * (`partyId` + `profile` + `bootstrapNodes` + `ownerKeys`), so a crashed node can
156
- * be re-spawned from the record alone — see `DonationService.respawn`. Records
157
- * written before those two fields existed have neither; such a record is NOT
158
- * respawnable and is skipped (never crashes a sweep).
159
- */
160
- export interface Donation {
161
- /** "grn_<nanoid>" — also the donated node's orchestrator containerId. */
162
- id: string;
163
- /** The grant token that authorized this donation (the quota key). */
164
- grantToken: string;
165
- /** The REQUESTER's cadre (a foreign party this host merely hosts a node for). */
166
- partyId: string;
167
- /**
168
- * Requester control-network bootstrap multiaddrs — replayed on respawn. Empty when
169
- * the requester dials the node itself (see `DonationProvisionRequest.bootstrapNodes`).
170
- * Absent on records written before respawn support; those are not respawnable.
171
- */
172
- bootstrapNodes?: string[];
173
- /**
174
- * Requester owner public key(s), base64url — replayed as the node's pinned
175
- * seed-trust anchors (`CADRE_OWNER_KEYS`) on respawn. Absent on records written
176
- * before respawn support; those are not respawnable.
177
- */
178
- ownerKeys?: string[];
179
- /**
180
- * Respawn bookkeeping, owned by the supervisor's backoff. Absent until the
181
- * first respawn attempt. Not secret — it rides along in `DonationView` so the
182
- * borrower's `GET /grants/:id` shows the counters for free.
183
- */
184
- respawn?: { attempts: number; lastAttemptAt: string };
185
- /** Node profile. Defaults to `storage` so the node participates and is dialable. */
186
- profile: 'storage' | 'transaction';
187
- status: DonationStatus;
188
- /** Orchestrator handle (opaque `pid:token`), set once the child is spawned. */
189
- dockerId?: string;
190
- /**
191
- * Reserved: a donation's live peer identity is read fresh from the node's
192
- * `/status` on each `getPeer` call and is NOT persisted here — this field is
193
- * currently never written. Kept for a future cache if `/status` fan-out ever
194
- * shows up as hot.
195
- */
196
- peerId?: string;
197
- /** The node's loopback `POST /seed` URL. Host-internal — stripped from the wire view. */
198
- seedEndpoint?: string;
199
- /** Host↔node bearer gating `POST /seed`. Persisted; NEVER leaves the host. */
200
- seedToken?: string;
201
- createdAt: string;
202
- updatedAt: string;
203
- /** Failure detail when `status === 'error'`. */
204
- error?: string;
205
- }
206
-
207
- /**
208
- * Redacted wire shape returned to the grantee: the host-only secrets
209
- * (`seedToken`) and host-internal loopback URL (`seedEndpoint`) are stripped.
210
- */
211
- export type DonationView = Omit<Donation, 'seedToken' | 'seedEndpoint'>;
212
-
213
- /** On-disk shape of `donations.json`. Keyed by donation id. */
214
- export interface DonationFile {
215
- version: 1;
216
- donations: Record<string, Omit<Donation, 'id'>>;
217
- }
218
-
219
- /** Error codes thrown by the donation service / grantee-facing routes. */
220
- export type DonationErrorCode =
221
- | 'unauthorized' // 401 — missing / unknown grant bearer
222
- | 'forbidden' // 403 — revoked or expired grant
223
- | 'quota_exceeded' // 429 — grant already at its maxNodes cap
224
- | 'invalid_request' // 400 — malformed body
225
- | 'not_found' // 404 — no such donation (or not owned by this grant)
226
- | 'invalid_state' // 409 — op invalid for the donation's current status
227
- | 'seed_failed' // 502 — the node rejected the presented seed
228
- | 'peer_unavailable' // 503 — the node has no peer identity yet
229
- | 'orchestrator_error' // 500 — spawn / stop failure
230
- | 'storage_error'; // 500 — donations.json read/write failure
231
-
232
- /** Typed donation error carrying a stable `code` for HTTP mapping. */
233
- export class DonationError extends Error {
234
- readonly code: DonationErrorCode;
235
-
236
- constructor(code: DonationErrorCode, message: string) {
237
- super(message);
238
- this.name = 'DonationError';
239
- this.code = code;
240
- }
241
- }
242
-
243
- /** Error codes thrown by GrantStore / GrantService. */
244
- export type GrantErrorCode =
245
- | 'not_found' // unknown token on revoke
246
- | 'invalid_label'
247
- | 'invalid_max_nodes'
248
- | 'invalid_ttl'
249
- | 'storage_error';
250
-
251
- /** Typed error carrying a stable `code` for HTTP mapping. */
252
- export class GrantError extends Error {
253
- readonly code: GrantErrorCode;
254
-
255
- constructor(code: GrantErrorCode, message: string) {
256
- super(message);
257
- this.name = 'GrantError';
258
- this.code = code;
259
- }
260
- }
1
+ /**
2
+ * Donation grant-token types for cadre-host.
3
+ *
4
+ * A **grant token** is a high-entropy base64url secret the host admin issues,
5
+ * out-of-band (QR / copy-paste), to one *grantee* — a friend or family member
6
+ * whose cadre authority (their phone) may then ask this host to spawn donated
7
+ * nodes. The grantee presents the token as `Authorization: Bearer <grant-token>`
8
+ * on every donation request (the grantee-facing surface lands in the
9
+ * `2-donation-service` ticket).
10
+ *
11
+ * This module owns the grant's identity, expiry, and per-grantee quota. The
12
+ * *live-node tally* it checks the quota against is owned by the donation
13
+ * service, not by the grant layer — see `GrantValidator.validateForProvision`.
14
+ *
15
+ * **Grant ≠ trust-circle membership.** A trust-circle invite (`auth/`)
16
+ * authorises a device to join *the host's own* cadre. A donation grant
17
+ * authorises an external cadre authority to ask the host to spawn a node that
18
+ * joins *the grantee's* cadre. The two token flows are deliberately separate
19
+ * modules; this one reuses the *shape* of the trust-circle store (atomic
20
+ * write-then-rename JSON, token-keyed rows) but with grant — not invite —
21
+ * semantics: a grant is long-lived and reusable up to a quota, never
22
+ * one-time-redeemed.
23
+ */
24
+
25
+ /** A grant the host admin issued to one grantee (friend/family). */
26
+ export interface Grant {
27
+ /** base64url secret; also the bearer credential. The store key. */
28
+ token: string;
29
+ /** Human label chosen by the admin, e.g. "Alice's cadre". Display-only. */
30
+ label: string;
31
+ /** Max concurrently-live donated nodes this grant may hold. */
32
+ maxNodes: number;
33
+ /** ISO timestamp when the grant was issued. */
34
+ createdAt: string;
35
+ /** ISO expiry; absent = no expiry. */
36
+ expiresAt?: string;
37
+ /** Set when the admin revokes; a revoked grant validates as denied. */
38
+ revokedAt?: string;
39
+ }
40
+
41
+ /** One grant as the admin list reports it: the grant plus what is running under it. */
42
+ export interface GrantListing extends Grant {
43
+ /** Donations counting against `maxNodes` (provisioning / awaiting_seed / seeded). */
44
+ liveNodes: number;
45
+ /** Every donation under this grant that is not `terminated` — what revoke would tear down. */
46
+ donations: Array<{ id: string; status: DonationStatus }>;
47
+ }
48
+
49
+ /** Why a presented grant token was denied. */
50
+ export type GrantDenyReason =
51
+ | 'unknown_token' // no such grant
52
+ | 'expired'
53
+ | 'revoked'
54
+ | 'quota_exceeded'; // live node count already at maxNodes
55
+
56
+ /** Result of validating a presented bearer token. */
57
+ export interface GrantValidation {
58
+ ok: boolean;
59
+ /** The matched grant, when the token names one (present even on some denials). */
60
+ grant?: Grant;
61
+ /** Set when `ok` is false. */
62
+ reason?: GrantDenyReason;
63
+ }
64
+
65
+ /**
66
+ * The slice `2-donation-service` depends on. Keeps that ticket decoupled from
67
+ * the store implementation: it holds a `GrantValidator`, not a `GrantStore`.
68
+ *
69
+ * Both methods are pure functions of the store state (and, for provision, the
70
+ * caller-supplied count) — they never throw for a bad token, they return a
71
+ * denial. Issuance/revocation (which mutate) live on `GrantService`.
72
+ */
73
+ export interface GrantValidator {
74
+ /**
75
+ * Validate a presented bearer token for a *new* provision request.
76
+ *
77
+ * `liveNodeCount(token)` is supplied by the donation service — the grant
78
+ * layer owns identity/expiry/revocation; the donation service owns the
79
+ * authoritative live-node tally (it holds the grant→node records). The count
80
+ * is only consulted once identity/expiry/revocation have passed, so an
81
+ * unknown or dead token never invokes it.
82
+ */
83
+ validateForProvision(
84
+ token: string,
85
+ liveNodeCount: (token: string) => number,
86
+ ): GrantValidation;
87
+ /**
88
+ * Validate for a non-provisioning op (peer/seed/terminate): identity + not
89
+ * expired/revoked. No quota check.
90
+ */
91
+ validate(token: string): GrantValidation;
92
+ }
93
+
94
+ /** On-disk shape of `grants.json`. */
95
+ export interface GrantFile {
96
+ version: 1;
97
+ /** keyed by token. */
98
+ grants: Record<string, Omit<Grant, 'token'>>;
99
+ }
100
+
101
+ /**
102
+ * Typed handlers exposed to the loopback management server for the **admin**
103
+ * grant surface (`/grants-admin`). Distinct from the grantee-facing `/grants`
104
+ * provisioning surface: the admin surface is loopback, no bearer — same-machine
105
+ * admin, matching cadre-host's local-UI "no login" posture.
106
+ *
107
+ * Handlers throw a `GrantError` (or, for donation teardown, a `DonationError`)
108
+ * whose `.code` the server maps to an HTTP status (see `server/error-handler.ts`).
109
+ */
110
+ export interface GrantAdminHandlers {
111
+ postGrant(body: { label: string; maxNodes?: number; ttlMs?: number }): Promise<{ grant: Grant }>;
112
+ listGrants(): Promise<{ grants: GrantListing[] }>;
113
+ /**
114
+ * Revoke a grant and, unless `keepNodes`, terminate every donated node under
115
+ * it. Resolves with the ids of the donations terminated.
116
+ */
117
+ deleteGrant(token: string, opts: { keepNodes: boolean }): Promise<{ terminated: string[] }>;
118
+ /**
119
+ * Terminate one donated node by id, whatever state its grant is in. Absent
120
+ * when no donation service is wired — there are then no donated nodes to end.
121
+ */
122
+ terminateDonation?(id: string): Promise<void>;
123
+ }
124
+
125
+ /* ──────────────── donation lifecycle (2-donation-service) ──────────────── */
126
+
127
+ /**
128
+ * Lifecycle of one donated node:
129
+ * provisioning → the child process is being spawned.
130
+ * awaiting_seed → spawned + reachable; waiting for the requester to present
131
+ * its phone-signed seed (`PUT /grants/:id/seed`).
132
+ * seeded → the seed was applied; the node has joined the requester's cadre.
133
+ * error → provisioning failed (orchestrator resources reclaimed).
134
+ * terminated → stopped + removed (kept in the store for audit).
135
+ *
136
+ * A donation is "live" (counts against a grant's `maxNodes` quota) while it is
137
+ * `provisioning`, `awaiting_seed`, or `seeded` — see `DonationStore.liveNodeCount`.
138
+ */
139
+ export type DonationStatus =
140
+ | 'provisioning'
141
+ | 'awaiting_seed'
142
+ | 'seeded'
143
+ | 'error'
144
+ | 'terminated';
145
+
146
+ /**
147
+ * One donated node, tracked host-side and persisted to `donations.json`.
148
+ *
149
+ * The host contributes capacity only: `partyId` is the REQUESTER's cadre (a
150
+ * foreign party), and `seedToken` gates the node's own `POST /seed` — it is
151
+ * minted host-side, persisted here (so a host restart in the request→seed gap
152
+ * can still present the seed), and NEVER returned to the grantee.
153
+ *
154
+ * The record also carries every input the original spawn consumed
155
+ * (`partyId` + `profile` + `bootstrapNodes` + `ownerKeys`), so a crashed node can
156
+ * be re-spawned from the record alone — see `DonationService.respawn`. Records
157
+ * written before those two fields existed have neither; such a record is NOT
158
+ * respawnable and is skipped (never crashes a sweep).
159
+ */
160
+ export interface Donation {
161
+ /** "grn_<nanoid>" — also the donated node's orchestrator containerId. */
162
+ id: string;
163
+ /** The grant token that authorized this donation (the quota key). */
164
+ grantToken: string;
165
+ /** The REQUESTER's cadre (a foreign party this host merely hosts a node for). */
166
+ partyId: string;
167
+ /**
168
+ * Requester control-network bootstrap multiaddrs — replayed on respawn. Empty when
169
+ * the requester dials the node itself (see `DonationProvisionRequest.bootstrapNodes`).
170
+ * Absent on records written before respawn support; those are not respawnable.
171
+ */
172
+ bootstrapNodes?: string[];
173
+ /**
174
+ * Requester owner public key(s), base64url — replayed as the node's pinned
175
+ * seed-trust anchors (`CADRE_OWNER_KEYS`) on respawn. Absent on records written
176
+ * before respawn support; those are not respawnable.
177
+ */
178
+ ownerKeys?: string[];
179
+ /**
180
+ * Respawn bookkeeping, owned by the supervisor's backoff. Absent until the
181
+ * first respawn attempt. Not secret — it rides along in `DonationView` so the
182
+ * borrower's `GET /grants/:id` shows the counters for free.
183
+ */
184
+ respawn?: { attempts: number; lastAttemptAt: string };
185
+ /** Node profile. Defaults to `storage` so the node participates and is dialable. */
186
+ profile: 'storage' | 'transaction';
187
+ status: DonationStatus;
188
+ /** Orchestrator handle (opaque `pid:token`), set once the child is spawned. */
189
+ dockerId?: string;
190
+ /**
191
+ * Reserved: a donation's live peer identity is read fresh from the node's
192
+ * `/status` on each `getPeer` call and is NOT persisted here — this field is
193
+ * currently never written. Kept for a future cache if `/status` fan-out ever
194
+ * shows up as hot.
195
+ */
196
+ peerId?: string;
197
+ /** The node's loopback `POST /seed` URL. Host-internal — stripped from the wire view. */
198
+ seedEndpoint?: string;
199
+ /** Host↔node bearer gating `POST /seed`. Persisted; NEVER leaves the host. */
200
+ seedToken?: string;
201
+ createdAt: string;
202
+ updatedAt: string;
203
+ /** Failure detail when `status === 'error'`. */
204
+ error?: string;
205
+ }
206
+
207
+ /**
208
+ * Redacted wire shape returned to the grantee: the host-only secrets
209
+ * (`seedToken`) and host-internal loopback URL (`seedEndpoint`) are stripped.
210
+ */
211
+ export type DonationView = Omit<Donation, 'seedToken' | 'seedEndpoint'>;
212
+
213
+ /** On-disk shape of `donations.json`. Keyed by donation id. */
214
+ export interface DonationFile {
215
+ version: 1;
216
+ donations: Record<string, Omit<Donation, 'id'>>;
217
+ }
218
+
219
+ /** Error codes thrown by the donation service / grantee-facing routes. */
220
+ export type DonationErrorCode =
221
+ | 'unauthorized' // 401 — missing / unknown grant bearer
222
+ | 'forbidden' // 403 — revoked or expired grant
223
+ | 'quota_exceeded' // 429 — grant already at its maxNodes cap
224
+ | 'invalid_request' // 400 — malformed body
225
+ | 'not_found' // 404 — no such donation (or not owned by this grant)
226
+ | 'invalid_state' // 409 — op invalid for the donation's current status
227
+ | 'seed_failed' // 502 — the node rejected the presented seed
228
+ | 'peer_unavailable' // 503 — the node has no peer identity yet
229
+ | 'orchestrator_error' // 500 — spawn / stop failure
230
+ | 'storage_error'; // 500 — donations.json read/write failure
231
+
232
+ /** Typed donation error carrying a stable `code` for HTTP mapping. */
233
+ export class DonationError extends Error {
234
+ readonly code: DonationErrorCode;
235
+
236
+ constructor(code: DonationErrorCode, message: string) {
237
+ super(message);
238
+ this.name = 'DonationError';
239
+ this.code = code;
240
+ }
241
+ }
242
+
243
+ /** Error codes thrown by GrantStore / GrantService. */
244
+ export type GrantErrorCode =
245
+ | 'not_found' // unknown token on revoke
246
+ | 'invalid_label'
247
+ | 'invalid_max_nodes'
248
+ | 'invalid_ttl'
249
+ | 'storage_error';
250
+
251
+ /** Typed error carrying a stable `code` for HTTP mapping. */
252
+ export class GrantError extends Error {
253
+ readonly code: GrantErrorCode;
254
+
255
+ constructor(code: GrantErrorCode, message: string) {
256
+ super(message);
257
+ this.name = 'GrantError';
258
+ this.code = code;
259
+ }
260
+ }