@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,225 @@
1
+ /**
2
+ * Shared fake orchestrator for the donation unit tests — no real child
3
+ * processes. Records every create / stop / remove, hands out deterministic
4
+ * unique spawn results, and tracks per-`dockerId` liveness so a test can crash
5
+ * one node and let the supervisor observe exactly that one as down.
6
+ *
7
+ * This file holds no tests of its own; its contract is pinned by the sibling
8
+ * `fake-orchestrator.test.ts`, which exists so a future agent cannot make a
9
+ * failing donation test go green by relaxing the fake.
10
+ */
11
+
12
+ import type {
13
+ Orchestrator,
14
+ OrchestratorCreateRequest,
15
+ OrchestratorCreateResult,
16
+ OrchestratorStats,
17
+ } from '@serfab/cadre-provider';
18
+
19
+ import type { ManagedNodeInfo, NodeStateListener } from '../../orchestrator/types.js';
20
+
21
+ function sleep(ms: number): Promise<void> {
22
+ return new Promise((res) => setTimeout(res, ms));
23
+ }
24
+
25
+ /** What the fake remembers about one spawned child. */
26
+ interface FakeChild {
27
+ containerId: string;
28
+ partyId: string;
29
+ profile: 'storage' | 'transaction';
30
+ running: boolean;
31
+ }
32
+
33
+ /**
34
+ * Mirrors the parts of `HostProcessOrchestrator`'s handle lifecycle the donation
35
+ * code depends on:
36
+ *
37
+ * - a **successful** `createContainer` drops every prior handle for the same
38
+ * `containerId` (the real `dropStaleHandle`), so an old `dockerId` stops
39
+ * resolving the moment its container re-spawns;
40
+ * - a **failed** `createContainer` leaves those handles exactly as it found them
41
+ * (the real `restoreDroppedHandles`);
42
+ * - `stopContainer` / `removeContainer` throw `Container not found: <dockerId>`
43
+ * for a handle this orchestrator no longer knows (the real `requireHandle`);
44
+ * - `reclaimWorkdir` refuses a containerId that still resolves to a live
45
+ * handle (the real guard — that directory belongs to `removeContainer`).
46
+ *
47
+ * Consequently `stopped` / `removed` mean **"handles this orchestrator actually
48
+ * acted on"**, not "calls attempted" — a stop aimed at a dropped handle is
49
+ * rejected and never appears. `onStop` still fires for those rejected calls, so
50
+ * a test can observe the attempt separately from its outcome.
51
+ */
52
+ export class FakeOrchestrator implements Orchestrator {
53
+ createCalls: OrchestratorCreateRequest[] = [];
54
+ stopped: string[] = [];
55
+ removed: string[] = [];
56
+ /**
57
+ * Container ids whose workdir this orchestrator actually removed. Same
58
+ * "acted on, not attempted" rule as `stopped` / `removed`: a refused reclaim
59
+ * leaves no entry.
60
+ */
61
+ reclaimedWorkdirs: string[] = [];
62
+ failCreate = false;
63
+ createDelayMs = 0;
64
+ /**
65
+ * Observation hook — lets a test inspect the world as the stop happens. Fires
66
+ * even when the handle is unknown and the stop is then rejected.
67
+ */
68
+ onStop?: (dockerId: string) => void;
69
+ /**
70
+ * Observation hook — fires before the spawn resolves or fails, modelling the
71
+ * real class's *pre-drop* `await` window (`ensureNodeIdentity`, `resolvePush`).
72
+ * Work driven from here sees the previous handle still alive. Contrast
73
+ * {@link onSpawned}.
74
+ */
75
+ onCreate?: (request: OrchestratorCreateRequest) => void;
76
+ /**
77
+ * Observation hook — fires once the drop has landed and the new child is
78
+ * registered, immediately before `createContainer` resolves. Models the
79
+ * microtask gap between the real `createContainer` returning and its caller's
80
+ * `await` resuming: the real drop → launch → return runs synchronously, so
81
+ * this is the earliest point other code can observe the post-drop world.
82
+ * Contrast {@link onCreate}.
83
+ */
84
+ onSpawned?: (dockerId: string) => void;
85
+ /** Observation hook — fires before the liveness answer is computed. */
86
+ onIsRunning?: (dockerId: string) => void;
87
+
88
+ private readonly children = new Map<string, FakeChild>();
89
+ private readonly listeners = new Set<NodeStateListener>();
90
+ private counter = 0;
91
+
92
+ async createContainer(request: OrchestratorCreateRequest): Promise<OrchestratorCreateResult> {
93
+ this.createCalls.push(request);
94
+ this.onCreate?.(request);
95
+ if (this.createDelayMs) await sleep(this.createDelayMs);
96
+ if (this.failCreate) throw new Error('spawn boom');
97
+ // Drop the prior handles for this container, mirroring `dropStaleHandle`.
98
+ // Success-only, and placed here on purpose: the real drop happens after the
99
+ // spawn's every `await` and cannot fail afterwards, and a create that throws
100
+ // puts the handles back (`restoreDroppedHandles`) — so a failed create must
101
+ // leave them untouched. `DonationSupervisor`'s give-up test depends on that.
102
+ for (const [id, child] of this.children) {
103
+ if (child.containerId === request.containerId) this.children.delete(id);
104
+ }
105
+ const n = ++this.counter;
106
+ const dockerId = `dock_${n}`;
107
+ this.children.set(dockerId, {
108
+ containerId: request.containerId,
109
+ partyId: request.partyId,
110
+ profile: request.profile,
111
+ running: true,
112
+ });
113
+ this.onSpawned?.(dockerId);
114
+ return {
115
+ dockerId,
116
+ healthEndpoint: `http://127.0.0.1:${9000 + n}/health`,
117
+ metricsEndpoint: `http://127.0.0.1:${9000 + n}/metrics`,
118
+ seedEndpoint: `http://127.0.0.1:${9000 + n}/seed`,
119
+ seedToken: `seed-token-${n}`,
120
+ p2pPort: 4000 + n,
121
+ };
122
+ }
123
+
124
+ async stopContainer(dockerId: string): Promise<void> {
125
+ // Before the check: a test may want to observe that a stop was *attempted*
126
+ // even when this orchestrator rejects it.
127
+ this.onStop?.(dockerId);
128
+ const child = this.requireChild(dockerId);
129
+ this.stopped.push(dockerId);
130
+ child.running = false;
131
+ }
132
+
133
+ async removeContainer(dockerId: string): Promise<void> {
134
+ // NOTE: the real `removeContainer` stops a still-live child first; this one
135
+ // only deletes, so a remove aimed at a running child records no `stopped`
136
+ // entry and emits no state change. Every donation caller stops before it
137
+ // reclaims, so nothing sees the difference today — if one stops doing that,
138
+ // stop the child here too.
139
+ this.requireChild(dockerId);
140
+ this.removed.push(dockerId);
141
+ this.children.delete(dockerId);
142
+ }
143
+
144
+ /**
145
+ * NOTE: this and {@link getLogs} take an unknown `dockerId` where the real
146
+ * class throws (`requireHandle`). No donation path calls either, so the gap is
147
+ * unobservable — route them through `requireChild` if one starts to.
148
+ */
149
+ async getStats(): Promise<OrchestratorStats> {
150
+ return { cpuPercent: 0, memoryBytes: 0, networkRxBytes: 0, networkTxBytes: 0 };
151
+ }
152
+
153
+ /** Unknown handles read as not running, matching the real orchestrator. */
154
+ async isRunning(dockerId: string): Promise<boolean> {
155
+ this.onIsRunning?.(dockerId);
156
+ return this.children.get(dockerId)?.running ?? false;
157
+ }
158
+
159
+ /** Resolve a spawn's friendly containerId back to its dockerId. */
160
+ resolveDockerId(containerId: string): string | undefined {
161
+ for (const [dockerId, child] of this.children) {
162
+ if (child.containerId === containerId) return dockerId;
163
+ }
164
+ return undefined;
165
+ }
166
+
167
+ /**
168
+ * Remove the workdir of a container no handle owns, mirroring the real
169
+ * `reclaimWorkdir`. Refuses (returns `false`, records nothing) while a child
170
+ * for that containerId still resolves — that directory belongs to
171
+ * `removeContainer`, which stops the child first.
172
+ *
173
+ * There is no directory here to check for existence, so a first reclaim of an
174
+ * unresolvable id always reports `true`; the real class returns `false` when
175
+ * the path is already gone. Nothing in the donation layer branches on the
176
+ * return value, so the gap is unobservable — model it if one starts to.
177
+ */
178
+ reclaimWorkdir(containerId: string): boolean {
179
+ if (this.resolveDockerId(containerId)) return false;
180
+ this.reclaimedWorkdirs.push(containerId);
181
+ return true;
182
+ }
183
+
184
+ async getLogs(): Promise<string> {
185
+ return '';
186
+ }
187
+
188
+ onStateChange(listener: NodeStateListener): () => void {
189
+ this.listeners.add(listener);
190
+ return () => { this.listeners.delete(listener); };
191
+ }
192
+
193
+ /** Kill a child out from under the host — the crash the supervisor exists for. */
194
+ crash(dockerId: string): void {
195
+ const child = this.children.get(dockerId);
196
+ if (!child?.running) return;
197
+ child.running = false;
198
+ this.emit(toNodeInfo(dockerId, child));
199
+ }
200
+
201
+ /** Emit an arbitrary state change (e.g. the owner node stopping). */
202
+ emit(info: ManagedNodeInfo): void {
203
+ for (const listener of this.listeners) listener(info);
204
+ }
205
+
206
+ /** Mirrors `HostProcessOrchestrator.requireHandle` — unknown handles throw. */
207
+ private requireChild(dockerId: string): FakeChild {
208
+ const child = this.children.get(dockerId);
209
+ if (!child) throw new Error(`Container not found: ${dockerId}`);
210
+ return child;
211
+ }
212
+ }
213
+
214
+ function toNodeInfo(dockerId: string, child: FakeChild): ManagedNodeInfo {
215
+ return {
216
+ id: child.containerId,
217
+ dockerId,
218
+ partyId: child.partyId,
219
+ profile: child.profile,
220
+ status: child.running ? 'running' : 'stopped',
221
+ spawnedAt: new Date(0).toISOString(),
222
+ workdir: `/fake/${child.containerId}`,
223
+ ports: { health: 0, metrics: 0, p2p: 0, admin: 0 },
224
+ };
225
+ }
@@ -0,0 +1,213 @@
1
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2
+ import { mkdtempSync, rmSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+
6
+ import { GrantService, createGrantAdminHandlers, DEFAULT_MAX_NODES } from '../grant-service.js';
7
+ import { GrantStore } from '../grant-store.js';
8
+ import { GrantError } from '../types.js';
9
+
10
+ let tmpRoot: string;
11
+ let store: GrantStore;
12
+ let service: GrantService;
13
+
14
+ beforeEach(() => {
15
+ tmpRoot = mkdtempSync(join(tmpdir(), 'cadre-host-grant-svc-'));
16
+ store = new GrantStore(tmpRoot);
17
+ service = new GrantService({ store });
18
+ });
19
+
20
+ afterEach(() => {
21
+ try { rmSync(tmpRoot, { recursive: true, force: true }); } catch { /* ignore */ }
22
+ });
23
+
24
+ describe('GrantService.issue', () => {
25
+ it('persists a grant and returns a base64url token', () => {
26
+ const grant = service.issue({ label: "Alice's cadre", maxNodes: 2 });
27
+ expect(grant.token).toBeTruthy();
28
+ // base64url alphabet only.
29
+ expect(grant.token).toMatch(/^[A-Za-z0-9_-]+$/);
30
+ expect(grant.label).toBe("Alice's cadre");
31
+ expect(grant.maxNodes).toBe(2);
32
+ expect(grant.createdAt).toBeTruthy();
33
+ expect(grant.expiresAt).toBeUndefined();
34
+ expect(grant.revokedAt).toBeUndefined();
35
+
36
+ expect(store.get(grant.token)).toMatchObject({ label: "Alice's cadre", maxNodes: 2 });
37
+ });
38
+
39
+ it('defaults maxNodes when omitted', () => {
40
+ const grant = service.issue({ label: 'Bob' });
41
+ expect(grant.maxNodes).toBe(DEFAULT_MAX_NODES);
42
+ });
43
+
44
+ it('sets expiresAt from ttlMs', () => {
45
+ const clock = new Date('2025-01-01T00:00:00.000Z');
46
+ const svc = new GrantService({ store, now: () => clock });
47
+ const grant = svc.issue({ label: 'Carol', ttlMs: 24 * 60 * 60 * 1000 });
48
+ expect(grant.expiresAt).toBe('2025-01-02T00:00:00.000Z');
49
+ });
50
+
51
+ it('rejects empty / whitespace labels', () => {
52
+ expect(() => service.issue({ label: ' ' })).toThrow(GrantError);
53
+ expect(() => service.issue({ label: '' })).toThrow(GrantError);
54
+ });
55
+
56
+ it('rejects labels over 200 characters', () => {
57
+ expect(() => service.issue({ label: 'a'.repeat(201) }))
58
+ .toThrow(expect.objectContaining({ code: 'invalid_label' }));
59
+ });
60
+
61
+ it('rejects non-positive / non-integer maxNodes', () => {
62
+ expect(() => service.issue({ label: 'X', maxNodes: 0 }))
63
+ .toThrow(expect.objectContaining({ code: 'invalid_max_nodes' }));
64
+ expect(() => service.issue({ label: 'X', maxNodes: -1 }))
65
+ .toThrow(expect.objectContaining({ code: 'invalid_max_nodes' }));
66
+ expect(() => service.issue({ label: 'X', maxNodes: 1.5 }))
67
+ .toThrow(expect.objectContaining({ code: 'invalid_max_nodes' }));
68
+ });
69
+
70
+ it('rejects non-positive ttl', () => {
71
+ expect(() => service.issue({ label: 'X', ttlMs: 0 }))
72
+ .toThrow(expect.objectContaining({ code: 'invalid_ttl' }));
73
+ expect(() => service.issue({ label: 'X', ttlMs: -1 }))
74
+ .toThrow(expect.objectContaining({ code: 'invalid_ttl' }));
75
+ });
76
+ });
77
+
78
+ describe('GrantService.validate', () => {
79
+ it('accepts a live grant', () => {
80
+ const { token } = service.issue({ label: 'Alice' });
81
+ const v = service.validate(token);
82
+ expect(v.ok).toBe(true);
83
+ expect(v.grant?.token).toBe(token);
84
+ expect(v.reason).toBeUndefined();
85
+ });
86
+
87
+ it('denies an empty bearer with unknown_token (never throws)', () => {
88
+ expect(service.validate('')).toEqual({ ok: false, reason: 'unknown_token' });
89
+ });
90
+
91
+ it('denies an unknown token with unknown_token (never throws)', () => {
92
+ expect(service.validate('does-not-exist')).toEqual({ ok: false, reason: 'unknown_token' });
93
+ });
94
+
95
+ it('denies a revoked grant with reason "revoked"', () => {
96
+ const { token } = service.issue({ label: 'Rev' });
97
+ service.revoke(token);
98
+ const v = service.validate(token);
99
+ expect(v.ok).toBe(false);
100
+ expect(v.reason).toBe('revoked');
101
+ expect(v.grant?.token).toBe(token);
102
+ });
103
+
104
+ it('denies an expired grant with reason "expired" even when not revoked', () => {
105
+ let clock = new Date('2025-01-01T00:00:00.000Z');
106
+ const svc = new GrantService({ store, now: () => clock });
107
+ const { token } = svc.issue({ label: 'Exp', ttlMs: 60_000 });
108
+
109
+ clock = new Date('2025-01-02T00:00:00.000Z'); // past expiry
110
+ const v = svc.validate(token);
111
+ expect(v.ok).toBe(false);
112
+ expect(v.reason).toBe('expired');
113
+ });
114
+
115
+ it('reports revoked over expired when both apply', () => {
116
+ let clock = new Date('2025-01-01T00:00:00.000Z');
117
+ const svc = new GrantService({ store, now: () => clock });
118
+ const { token } = svc.issue({ label: 'Both', ttlMs: 60_000 });
119
+ svc.revoke(token);
120
+
121
+ clock = new Date('2025-01-02T00:00:00.000Z'); // also past expiry now
122
+ expect(svc.validate(token).reason).toBe('revoked');
123
+ });
124
+ });
125
+
126
+ describe('GrantService.validateForProvision', () => {
127
+ it('allows up to the quota, then denies with quota_exceeded', () => {
128
+ const { token } = service.issue({ label: 'Alice', maxNodes: 2 });
129
+
130
+ // First two provisions (live count 0, then 1) pass.
131
+ expect(service.validateForProvision(token, () => 0).ok).toBe(true);
132
+ expect(service.validateForProvision(token, () => 1).ok).toBe(true);
133
+
134
+ // Third (live count already at 2) is denied.
135
+ const v = service.validateForProvision(token, () => 2);
136
+ expect(v.ok).toBe(false);
137
+ expect(v.reason).toBe('quota_exceeded');
138
+ expect(v.grant?.token).toBe(token);
139
+ });
140
+
141
+ it('does not consult liveNodeCount for an unknown token', () => {
142
+ let called = false;
143
+ const v = service.validateForProvision('nope', () => { called = true; return 0; });
144
+ expect(v).toEqual({ ok: false, reason: 'unknown_token' });
145
+ expect(called).toBe(false);
146
+ });
147
+
148
+ it('does not consult liveNodeCount for a revoked or expired grant', () => {
149
+ const { token } = service.issue({ label: 'Rev', maxNodes: 5 });
150
+ service.revoke(token);
151
+ let called = false;
152
+ const v = service.validateForProvision(token, () => { called = true; return 0; });
153
+ expect(v.reason).toBe('revoked');
154
+ expect(called).toBe(false);
155
+ });
156
+ });
157
+
158
+ describe('GrantService.revoke', () => {
159
+ it('throws not_found for an unknown token', () => {
160
+ expect(() => service.revoke('nope'))
161
+ .toThrow(expect.objectContaining({ code: 'not_found' }));
162
+ });
163
+
164
+ it('is idempotent (second revoke keeps the original timestamp)', () => {
165
+ let clock = new Date('2025-01-01T00:00:00.000Z');
166
+ const svc = new GrantService({ store, now: () => clock });
167
+ const { token } = svc.issue({ label: 'X' });
168
+
169
+ svc.revoke(token);
170
+ const first = store.get(token)?.revokedAt;
171
+
172
+ clock = new Date('2025-02-01T00:00:00.000Z');
173
+ svc.revoke(token); // no throw; keeps first timestamp
174
+ expect(store.get(token)?.revokedAt).toBe(first);
175
+ });
176
+ });
177
+
178
+ describe('GrantService.list', () => {
179
+ it('enumerates issued grants', () => {
180
+ service.issue({ label: 'A' });
181
+ service.issue({ label: 'B' });
182
+ expect(service.list().map(g => g.label).sort()).toEqual(['A', 'B']);
183
+ });
184
+ });
185
+
186
+ describe('createGrantAdminHandlers', () => {
187
+ it('exposes the admin HTTP-handler surface', async () => {
188
+ const handlers = createGrantAdminHandlers(service);
189
+
190
+ const issued = await handlers.postGrant({ label: 'Pat', maxNodes: 3 });
191
+ expect(issued.grant.token).toBeTruthy();
192
+ expect(issued.grant.maxNodes).toBe(3);
193
+
194
+ let listed = await handlers.listGrants();
195
+ expect(listed.grants.map(g => g.token)).toContain(issued.grant.token);
196
+
197
+ await handlers.deleteGrant(issued.grant.token);
198
+ listed = await handlers.listGrants();
199
+ // Revocation marks, not removes — the grant is still listed but revoked.
200
+ expect(listed.grants.find(g => g.token === issued.grant.token)?.revokedAt).toBeTruthy();
201
+ });
202
+
203
+ it('postGrant rejects a missing label', async () => {
204
+ const handlers = createGrantAdminHandlers(service);
205
+ await expect(handlers.postGrant({ label: undefined as unknown as string }))
206
+ .rejects.toMatchObject({ code: 'invalid_label' });
207
+ });
208
+
209
+ it('deleteGrant surfaces not_found for an unknown token', async () => {
210
+ const handlers = createGrantAdminHandlers(service);
211
+ await expect(handlers.deleteGrant('nope')).rejects.toMatchObject({ code: 'not_found' });
212
+ });
213
+ });
@@ -0,0 +1,113 @@
1
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+
6
+ import { GrantStore } from '../grant-store.js';
7
+ import { GrantError } from '../types.js';
8
+ import type { Grant } from '../types.js';
9
+
10
+ let tmpRoot: string;
11
+
12
+ function grant(over: Partial<Grant> = {}): Grant {
13
+ return {
14
+ token: 'tok-A',
15
+ label: "Alice's cadre",
16
+ maxNodes: 2,
17
+ createdAt: '2025-01-01T00:00:00.000Z',
18
+ ...over,
19
+ };
20
+ }
21
+
22
+ beforeEach(() => {
23
+ tmpRoot = mkdtempSync(join(tmpdir(), 'cadre-host-grant-store-'));
24
+ });
25
+
26
+ afterEach(() => {
27
+ try { rmSync(tmpRoot, { recursive: true, force: true }); } catch { /* ignore */ }
28
+ });
29
+
30
+ describe('GrantStore', () => {
31
+ it('returns empty state when file is missing', () => {
32
+ const store = new GrantStore(tmpRoot);
33
+ expect(store.list()).toEqual([]);
34
+ expect(store.get('anything')).toBeUndefined();
35
+ });
36
+
37
+ it('round-trips grants through save/load', () => {
38
+ const store = new GrantStore(tmpRoot);
39
+ store.add(grant({ token: 'tok-A', label: 'Alice' }));
40
+ store.add(grant({ token: 'tok-B', label: 'Bob', maxNodes: 1, expiresAt: '2025-06-01T00:00:00.000Z' }));
41
+
42
+ const reread = new GrantStore(tmpRoot);
43
+ expect(reread.list()).toHaveLength(2);
44
+ expect(reread.get('tok-A')).toMatchObject({ token: 'tok-A', label: 'Alice', maxNodes: 2 });
45
+ expect(reread.get('tok-B')?.expiresAt).toBe('2025-06-01T00:00:00.000Z');
46
+ expect(reread.get('tok-A')?.expiresAt).toBeUndefined();
47
+ });
48
+
49
+ it('removes grants', () => {
50
+ const store = new GrantStore(tmpRoot);
51
+ store.add(grant({ token: 'tok-A' }));
52
+ expect(store.remove('tok-A')).toBe(true);
53
+ expect(store.remove('tok-A')).toBe(false);
54
+
55
+ const reread = new GrantStore(tmpRoot);
56
+ expect(reread.list()).toEqual([]);
57
+ });
58
+
59
+ it('marks a grant revoked, idempotently', () => {
60
+ const store = new GrantStore(tmpRoot);
61
+ store.add(grant({ token: 'tok-A' }));
62
+
63
+ expect(store.markRevoked('tok-A', '2025-02-01T00:00:00.000Z')).toBe(true);
64
+ expect(store.get('tok-A')?.revokedAt).toBe('2025-02-01T00:00:00.000Z');
65
+
66
+ // Second revoke keeps the original timestamp.
67
+ expect(store.markRevoked('tok-A', '2025-03-01T00:00:00.000Z')).toBe(true);
68
+ expect(store.get('tok-A')?.revokedAt).toBe('2025-02-01T00:00:00.000Z');
69
+
70
+ // Unknown token.
71
+ expect(store.markRevoked('nope', '2025-02-01T00:00:00.000Z')).toBe(false);
72
+ });
73
+
74
+ it('writes through a temp file (atomic rename, no residue)', () => {
75
+ const store = new GrantStore(tmpRoot);
76
+ store.add(grant());
77
+ expect(existsSync(join(tmpRoot, 'grants.json'))).toBe(true);
78
+ expect(existsSync(join(tmpRoot, 'grants.json.tmp'))).toBe(false);
79
+ });
80
+
81
+ it('persists the version field in saved JSON', () => {
82
+ const store = new GrantStore(tmpRoot);
83
+ store.add(grant({ token: 'tok-A', label: 'one' }));
84
+ const raw = JSON.parse(readFileSync(join(tmpRoot, 'grants.json'), 'utf8'));
85
+ expect(raw.version).toBe(1);
86
+ expect(raw.grants['tok-A'].label).toBe('one');
87
+ // token is the map key, not duplicated inside the row.
88
+ expect(raw.grants['tok-A'].token).toBeUndefined();
89
+ });
90
+
91
+ it('throws on malformed JSON rather than silently wiping (would revoke everyone)', () => {
92
+ writeFileSync(join(tmpRoot, 'grants.json'), 'not json', 'utf8');
93
+ const store = new GrantStore(tmpRoot);
94
+ expect(() => store.load()).toThrow(GrantError);
95
+ });
96
+
97
+ it('throws on a file with the wrong shape', () => {
98
+ writeFileSync(join(tmpRoot, 'grants.json'), JSON.stringify({ version: 99, foo: 'bar' }), 'utf8');
99
+ const store = new GrantStore(tmpRoot);
100
+ expect(() => store.load()).toThrow(GrantError);
101
+ });
102
+
103
+ it('wraps a write failure as storage_error (not a bare Error)', () => {
104
+ const store = new GrantStore(tmpRoot);
105
+ // load() sees no grants.json (empty), then save() writes grants.json.tmp.
106
+ // Make that temp path a directory so writeFileSync fails (EISDIR) — the
107
+ // failure must surface as GrantError storage_error, not a bare Error.
108
+ mkdirSync(join(tmpRoot, 'grants.json.tmp'));
109
+ expect(() => store.add(grant())).toThrow(
110
+ expect.objectContaining({ code: 'storage_error' }),
111
+ );
112
+ });
113
+ });