@serfab/cadre-host 0.7.1 → 0.9.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 (193) hide show
  1. package/README.md +296 -101
  2. package/dist/auth/trust-circle.d.ts +45 -7
  3. package/dist/auth/trust-circle.js +116 -59
  4. package/dist/auth/trust-circle.js.map +1 -1
  5. package/dist/auth/types.d.ts +4 -1
  6. package/dist/auth/types.js.map +1 -1
  7. package/dist/bin/host.js +426 -112
  8. package/dist/bin/host.js.map +1 -1
  9. package/dist/donation/donation-service.d.ts +136 -0
  10. package/dist/donation/donation-service.js +306 -0
  11. package/dist/donation/donation-service.js.map +1 -0
  12. package/dist/donation/donation-store.d.ts +42 -0
  13. package/dist/donation/donation-store.js +141 -0
  14. package/dist/donation/donation-store.js.map +1 -0
  15. package/dist/donation/grant-service.d.ts +71 -0
  16. package/dist/donation/grant-service.js +163 -0
  17. package/dist/donation/grant-service.js.map +1 -0
  18. package/dist/donation/grant-store.d.ts +38 -0
  19. package/dist/donation/grant-store.js +135 -0
  20. package/dist/donation/grant-store.js.map +1 -0
  21. package/dist/donation/index.d.ts +18 -0
  22. package/dist/donation/index.js +16 -0
  23. package/dist/donation/index.js.map +1 -0
  24. package/dist/donation/types.d.ts +175 -0
  25. package/dist/donation/types.js +40 -0
  26. package/dist/donation/types.js.map +1 -0
  27. package/dist/index.d.ts +12 -6
  28. package/dist/index.js +8 -3
  29. package/dist/index.js.map +1 -1
  30. package/dist/installer/browser.js +16 -17
  31. package/dist/installer/browser.js.map +1 -1
  32. package/dist/installer/config.d.ts +51 -0
  33. package/dist/installer/config.js +14 -1
  34. package/dist/installer/config.js.map +1 -1
  35. package/dist/installer/index.d.ts +7 -2
  36. package/dist/installer/index.js +17 -10
  37. package/dist/installer/index.js.map +1 -1
  38. package/dist/installer/service-host/launchd.js +1 -1
  39. package/dist/installer/service-host/launchd.js.map +1 -1
  40. package/dist/installer/service-host/systemd.js +1 -1
  41. package/dist/installer/service-host/systemd.js.map +1 -1
  42. package/dist/installer/wizard.d.ts +4 -0
  43. package/dist/installer/wizard.js +5 -1
  44. package/dist/installer/wizard.js.map +1 -1
  45. package/dist/nat/index.d.ts +1 -1
  46. package/dist/nat/nat-service.d.ts +45 -3
  47. package/dist/nat/nat-service.js +116 -3
  48. package/dist/nat/nat-service.js.map +1 -1
  49. package/dist/nat/secrets/index.d.ts +7 -0
  50. package/dist/nat/secrets/index.js +28 -2
  51. package/dist/nat/secrets/index.js.map +1 -1
  52. package/dist/nat/types.d.ts +3 -1
  53. package/dist/nat/types.js.map +1 -1
  54. package/dist/orchestrator/host-process-orchestrator.d.ts +68 -1
  55. package/dist/orchestrator/host-process-orchestrator.js +272 -39
  56. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  57. package/dist/orchestrator/index.d.ts +3 -2
  58. package/dist/orchestrator/index.js +1 -1
  59. package/dist/orchestrator/index.js.map +1 -1
  60. package/dist/orchestrator/state-store.d.ts +6 -5
  61. package/dist/orchestrator/state-store.js +10 -2
  62. package/dist/orchestrator/state-store.js.map +1 -1
  63. package/dist/orchestrator/types.d.ts +45 -10
  64. package/dist/orchestrator/types.js.map +1 -1
  65. package/dist/owner/index.d.ts +11 -0
  66. package/dist/owner/index.js +11 -0
  67. package/dist/owner/index.js.map +1 -0
  68. package/dist/owner/owner-node-client.d.ts +95 -0
  69. package/dist/owner/owner-node-client.js +167 -0
  70. package/dist/owner/owner-node-client.js.map +1 -0
  71. package/dist/push/index.d.ts +67 -0
  72. package/dist/push/index.js +101 -0
  73. package/dist/push/index.js.map +1 -0
  74. package/dist/server/error-handler.d.ts +17 -0
  75. package/dist/server/error-handler.js +45 -0
  76. package/dist/server/error-handler.js.map +1 -1
  77. package/dist/server/index.d.ts +26 -2
  78. package/dist/server/index.js +37 -16
  79. package/dist/server/index.js.map +1 -1
  80. package/dist/server/routes/grants-admin.d.ts +17 -0
  81. package/dist/server/routes/grants-admin.js +32 -0
  82. package/dist/server/routes/grants-admin.js.map +1 -0
  83. package/dist/server/routes/grants.d.ts +28 -0
  84. package/dist/server/routes/grants.js +163 -0
  85. package/dist/server/routes/grants.js.map +1 -0
  86. package/dist/server/routes/nodes.d.ts +5 -3
  87. package/dist/server/routes/nodes.js +39 -24
  88. package/dist/server/routes/nodes.js.map +1 -1
  89. package/dist/server/routes/settings.d.ts +6 -1
  90. package/dist/server/routes/settings.js +5 -2
  91. package/dist/server/routes/settings.js.map +1 -1
  92. package/dist/server/routes/status.d.ts +8 -4
  93. package/dist/server/routes/status.js +9 -4
  94. package/dist/server/routes/status.js.map +1 -1
  95. package/dist/server/static.d.ts +12 -0
  96. package/dist/server/static.js +24 -7
  97. package/dist/server/static.js.map +1 -1
  98. package/dist/ui/assets/index-BlMXQPSw.js +14 -0
  99. package/dist/ui/assets/{index-C9uChk2P.js.map → index-BlMXQPSw.js.map} +1 -1
  100. package/dist/ui/index.html +1 -1
  101. package/dist/update/apply.d.ts +23 -1
  102. package/dist/update/apply.js +46 -4
  103. package/dist/update/apply.js.map +1 -1
  104. package/dist/update/index.d.ts +14 -3
  105. package/dist/update/index.js +35 -2
  106. package/dist/update/index.js.map +1 -1
  107. package/dist/update/manifest.d.ts +28 -9
  108. package/dist/update/manifest.js +56 -29
  109. package/dist/update/manifest.js.map +1 -1
  110. package/dist/update/release-key.d.ts +18 -7
  111. package/dist/update/release-key.js +29 -14
  112. package/dist/update/release-key.js.map +1 -1
  113. package/dist/update/sign.d.ts +46 -0
  114. package/dist/update/sign.js +53 -0
  115. package/dist/update/sign.js.map +1 -0
  116. package/package.json +9 -4
  117. package/service/README.md +95 -86
  118. package/src/__tests__/cli-invite.smoke.test.ts +6 -1
  119. package/src/__tests__/cli-nat.smoke.test.ts +6 -1
  120. package/src/__tests__/cli.smoke.test.ts +6 -1
  121. package/src/__tests__/host-owner.smoke.test.ts +123 -0
  122. package/src/__tests__/orchestrator-owner.test.ts +198 -0
  123. package/src/__tests__/orchestrator-pin-keys.test.ts +153 -0
  124. package/src/__tests__/orchestrator-push.test.ts +145 -0
  125. package/src/auth/__tests__/trust-circle-integration.test.ts +44 -25
  126. package/src/auth/__tests__/trust-circle.test.ts +91 -24
  127. package/src/auth/trust-circle.ts +363 -304
  128. package/src/auth/types.ts +4 -1
  129. package/src/bin/host.ts +1258 -905
  130. package/src/donation/__tests__/donation-service.test.ts +290 -0
  131. package/src/donation/__tests__/grant-service.test.ts +213 -0
  132. package/src/donation/__tests__/grant-store.test.ts +113 -0
  133. package/src/donation/donation-service.ts +392 -0
  134. package/src/donation/donation-store.ts +164 -0
  135. package/src/donation/grant-service.ts +200 -0
  136. package/src/donation/grant-store.ts +152 -0
  137. package/src/donation/index.ts +49 -0
  138. package/src/donation/types.ts +220 -0
  139. package/src/index.ts +66 -3
  140. package/src/installer/__tests__/config.test.ts +27 -1
  141. package/src/installer/__tests__/installer.smoke.test.ts +94 -0
  142. package/src/installer/__tests__/wizard.test.ts +5 -1
  143. package/src/installer/browser.ts +40 -42
  144. package/src/installer/config.ts +61 -1
  145. package/src/installer/index.ts +23 -12
  146. package/src/installer/service-host/launchd.ts +1 -1
  147. package/src/installer/service-host/systemd.ts +1 -1
  148. package/src/installer/wizard.ts +12 -1
  149. package/src/nat/__tests__/ddns-updater.test.ts +1 -1
  150. package/src/nat/__tests__/nat-service.test.ts +192 -0
  151. package/src/nat/__tests__/port-mapper.test.ts +1 -1
  152. package/src/nat/__tests__/secrets.test.ts +23 -1
  153. package/src/nat/index.ts +1 -1
  154. package/src/nat/nat-service.ts +131 -5
  155. package/src/nat/secrets/index.ts +32 -2
  156. package/src/nat/types.ts +3 -1
  157. package/src/orchestrator/host-process-orchestrator.ts +322 -54
  158. package/src/orchestrator/index.ts +9 -2
  159. package/src/orchestrator/state-store.ts +21 -3
  160. package/src/orchestrator/types.ts +48 -2
  161. package/src/owner/__tests__/owner-node-client.test.ts +194 -0
  162. package/src/owner/index.ts +12 -0
  163. package/src/owner/owner-node-client.ts +233 -0
  164. package/src/push/__tests__/push.test.ts +90 -0
  165. package/src/push/index.ts +146 -0
  166. package/src/server/__tests__/error-handler.test.ts +26 -4
  167. package/src/server/__tests__/grants-admin-route.test.ts +73 -0
  168. package/src/server/__tests__/grants-route.test.ts +189 -0
  169. package/src/server/__tests__/nodes-route.test.ts +90 -10
  170. package/src/server/__tests__/publishers.test.ts +1 -1
  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__/static.test.ts +145 -0
  174. package/src/server/__tests__/status-route.test.ts +23 -2
  175. package/src/server/error-handler.ts +47 -0
  176. package/src/server/index.ts +62 -17
  177. package/src/server/routes/grants-admin.ts +41 -0
  178. package/src/server/routes/grants.ts +186 -0
  179. package/src/server/routes/nodes.ts +49 -26
  180. package/src/server/routes/settings.ts +11 -3
  181. package/src/server/routes/status.ts +18 -8
  182. package/src/server/static.ts +24 -8
  183. package/src/update/__tests__/apply.test.ts +58 -1
  184. package/src/update/__tests__/manifest.test.ts +41 -6
  185. package/src/update/__tests__/release-key.test.ts +42 -0
  186. package/src/update/__tests__/sign.test.ts +78 -0
  187. package/src/update/__tests__/update-service.integration.test.ts +44 -9
  188. package/src/update/apply.ts +46 -4
  189. package/src/update/index.ts +41 -3
  190. package/src/update/manifest.ts +214 -172
  191. package/src/update/release-key.ts +31 -15
  192. package/src/update/sign.ts +74 -0
  193. package/dist/ui/assets/index-C9uChk2P.js +0 -14
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Push (FCM/APNs) credential storage + resolution for cadre-host.
3
+ *
4
+ * The platform-push secrets a self-hosted deployment provisions live in the host
5
+ * secret store (keytar with file-store fallback — the same store DDNS tokens use);
6
+ * the non-secret app-config bits (APNs bundle id / sandbox toggle, cooldown /
7
+ * debounce) live in `host.config.json` (`PushSettings`). At node-spawn time the
8
+ * orchestrator's `pushResolver` calls {@link resolvePushCredentials}, which reads
9
+ * BOTH and merges them into the `PushCredentials` block written into the spawned
10
+ * node's `cadre.json`.
11
+ *
12
+ * Secret hygiene: the FCM service-account fields and the APNs `.p8` key are stored
13
+ * ONLY in the secret store, never in `host.config.json` and never in `state.json`.
14
+ * They are re-read on every spawn so a restart picks up rotated keys, and the
15
+ * resolver redacts on any log line. A partial credential set (a present platform
16
+ * missing required fields) is rejected — fail fast, not at first push.
17
+ */
18
+
19
+ import debug from 'debug';
20
+
21
+ import type { PushCredentials, FcmCredentials, ApnsCredentials } from '@serfab/cadre-core';
22
+ import { validatePushCredentials } from '@serfab/cadre-core';
23
+
24
+ import type { SecretsStore } from '../nat/secrets/index.js';
25
+ import type { PushSettings } from '../installer/config.js';
26
+
27
+ const log = debug('cadre:host:push');
28
+
29
+ /** Push platform whose secret bundle lives in the secret store. */
30
+ export type PushSecretPlatform = 'fcm' | 'apns';
31
+
32
+ /** Build the secret-store account key for a platform's credential bundle. */
33
+ export function pushAccount(platform: PushSecretPlatform): string {
34
+ return `push:${platform}`;
35
+ }
36
+
37
+ /** FCM secret bundle persisted in the secret store (the whole set is sensitive). */
38
+ export interface FcmSecret {
39
+ projectId: string;
40
+ clientEmail: string;
41
+ /** Service-account RSA private key, PEM. */
42
+ privateKey: string;
43
+ }
44
+
45
+ /**
46
+ * APNs secret bundle persisted in the secret store. `bundleId` / `production` are
47
+ * NOT here — they are non-secret app-config in {@link PushSettings}.
48
+ */
49
+ export interface ApnsSecret {
50
+ keyId: string;
51
+ teamId: string;
52
+ /** `.p8` ES256 private key, PEM. */
53
+ privateKey: string;
54
+ }
55
+
56
+ /** Store (or replace) the FCM service-account secret bundle. */
57
+ export async function setFcmSecret(secrets: SecretsStore, secret: FcmSecret): Promise<void> {
58
+ await secrets.set(pushAccount('fcm'), JSON.stringify(secret));
59
+ }
60
+
61
+ /** Store (or replace) the APNs auth-key secret bundle. */
62
+ export async function setApnsSecret(secrets: SecretsStore, secret: ApnsSecret): Promise<void> {
63
+ await secrets.set(pushAccount('apns'), JSON.stringify(secret));
64
+ }
65
+
66
+ /** Remove a platform's secret bundle. Returns true if one was present. */
67
+ export async function clearPushSecret(secrets: SecretsStore, platform: PushSecretPlatform): Promise<boolean> {
68
+ return secrets.delete(pushAccount(platform));
69
+ }
70
+
71
+ /** Read a platform's stored secret bundle, or null when unset. */
72
+ async function readSecret<T>(secrets: SecretsStore, platform: PushSecretPlatform): Promise<T | null> {
73
+ const raw = await secrets.get(pushAccount(platform));
74
+ if (raw === null) return null;
75
+ try {
76
+ return JSON.parse(raw) as T;
77
+ } catch (err) {
78
+ throw new Error(`Stored ${platform} push secret is not valid JSON: ${(err as Error).message}`, { cause: err });
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Resolve the full {@link PushCredentials} block to inject into a spawned node,
84
+ * merging the secret-store bundles with the non-secret {@link PushSettings}.
85
+ *
86
+ * Returns `undefined` when NO platform is configured (push is opt-in — the node
87
+ * then constructs no fan-out). Throws when a configured platform is incomplete
88
+ * (e.g. APNs secret present but `bundleId` unset), so a misconfig surfaces at the
89
+ * spawn boundary rather than silently at first push.
90
+ */
91
+ export async function resolvePushCredentials(
92
+ secrets: SecretsStore,
93
+ settings: PushSettings | undefined,
94
+ ): Promise<PushCredentials | undefined> {
95
+ const fcmSecret = await readSecret<FcmSecret>(secrets, 'fcm');
96
+ const apnsSecret = await readSecret<ApnsSecret>(secrets, 'apns');
97
+
98
+ if (!fcmSecret && !apnsSecret) return undefined;
99
+
100
+ const push: PushCredentials = {};
101
+ if (fcmSecret) {
102
+ const fcm: FcmCredentials = {
103
+ projectId: fcmSecret.projectId,
104
+ clientEmail: fcmSecret.clientEmail,
105
+ privateKey: fcmSecret.privateKey,
106
+ };
107
+ push.fcm = fcm;
108
+ }
109
+ if (apnsSecret) {
110
+ const apns: ApnsCredentials = {
111
+ keyId: apnsSecret.keyId,
112
+ teamId: apnsSecret.teamId,
113
+ bundleId: settings?.apns?.bundleId ?? '',
114
+ privateKey: apnsSecret.privateKey,
115
+ ...(settings?.apns?.production !== undefined ? { production: settings.apns.production } : {}),
116
+ };
117
+ push.apns = apns;
118
+ }
119
+ if (settings?.cooldownMs !== undefined) push.cooldownMs = settings.cooldownMs;
120
+ if (settings?.debounceMs !== undefined) push.debounceMs = settings.debounceMs;
121
+
122
+ const errors = validatePushCredentials(push);
123
+ if (errors.length > 0) {
124
+ throw new Error(`Invalid push credentials: ${errors.join('; ')}`);
125
+ }
126
+ log('resolved push credentials (fcm=%s apns=%s)', !!push.fcm, !!push.apns);
127
+ return push;
128
+ }
129
+
130
+ /**
131
+ * A description of which push platforms are configured, for the `push status` CLI
132
+ * and any UI — derived without exposing any secret material.
133
+ */
134
+ export interface PushStatus {
135
+ fcm: boolean;
136
+ apns: boolean;
137
+ }
138
+
139
+ /** Report which platforms have a stored secret bundle (no secret material). */
140
+ export async function pushStatus(secrets: SecretsStore): Promise<PushStatus> {
141
+ const accounts = await secrets.list();
142
+ return {
143
+ fcm: accounts.includes(pushAccount('fcm')),
144
+ apns: accounts.includes(pushAccount('apns')),
145
+ };
146
+ }
@@ -1,9 +1,10 @@
1
- import Fastify from 'fastify';
1
+ import Fastify, { type FastifyRequest } from 'fastify';
2
2
  import { describe, it, expect, beforeEach, afterEach } from 'vitest';
3
3
 
4
4
  import { TrustCircleError } from '../../auth/types.js';
5
5
  import { NatError } from '../../nat/types.js';
6
6
  import { UpdateErrorException } from '../../update/types.js';
7
+ import { GrantError } from '../../donation/types.js';
7
8
  import { registerErrorHandler } from '../error-handler.js';
8
9
 
9
10
  describe('error handler', () => {
@@ -12,18 +13,22 @@ describe('error handler', () => {
12
13
  beforeEach(async () => {
13
14
  app = Fastify();
14
15
  registerErrorHandler(app);
15
- app.get('/trust/:code', async (req) => {
16
+ app.get('/trust/:code', async (req: FastifyRequest) => {
16
17
  const { code } = req.params as { code: string };
17
18
  throw new TrustCircleError(code as never, `trust err: ${code}`);
18
19
  });
19
- app.get('/nat/:code', async (req) => {
20
+ app.get('/nat/:code', async (req: FastifyRequest) => {
20
21
  const { code } = req.params as { code: string };
21
22
  throw new NatError(code as never, `nat err: ${code}`);
22
23
  });
23
- app.get('/update/:code', async (req) => {
24
+ app.get('/update/:code', async (req: FastifyRequest) => {
24
25
  const { code } = req.params as { code: string };
25
26
  throw new UpdateErrorException(code as never, `update err: ${code}`);
26
27
  });
28
+ app.get('/grant/:code', async (req: FastifyRequest) => {
29
+ const { code } = req.params as { code: string };
30
+ throw new GrantError(code as never, `grant err: ${code}`);
31
+ });
27
32
  app.get('/unknown', async () => {
28
33
  throw new Error('mystery');
29
34
  });
@@ -85,6 +90,23 @@ describe('error handler', () => {
85
90
  expect(res.statusCode).toBe(400);
86
91
  });
87
92
 
93
+ it('GrantError invalid_max_nodes → 400', async () => {
94
+ const res = await app.inject({ method: 'GET', url: '/grant/invalid_max_nodes' });
95
+ expect(res.statusCode).toBe(400);
96
+ const body = res.json() as { error: { code: string } };
97
+ expect(body.error.code).toBe('invalid_max_nodes');
98
+ });
99
+
100
+ it('GrantError not_found → 404', async () => {
101
+ const res = await app.inject({ method: 'GET', url: '/grant/not_found' });
102
+ expect(res.statusCode).toBe(404);
103
+ });
104
+
105
+ it('GrantError storage_error → 500', async () => {
106
+ const res = await app.inject({ method: 'GET', url: '/grant/storage_error' });
107
+ expect(res.statusCode).toBe(500);
108
+ });
109
+
88
110
  it('unknown Error → 500 internal', async () => {
89
111
  const res = await app.inject({ method: 'GET', url: '/unknown' });
90
112
  expect(res.statusCode).toBe(500);
@@ -0,0 +1,73 @@
1
+ import Fastify from 'fastify';
2
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
3
+ import { mkdtempSync, rmSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+
7
+ import { registerErrorHandler } from '../error-handler.js';
8
+ import { registerGrantsAdminRoutes } from '../routes/grants-admin.js';
9
+ import { GrantService, GrantStore, createGrantAdminHandlers } from '../../donation/index.js';
10
+ import type { Grant } from '../../donation/index.js';
11
+
12
+ let tmpRoot: string;
13
+ let app: ReturnType<typeof Fastify>;
14
+
15
+ beforeEach(() => {
16
+ tmpRoot = mkdtempSync(join(tmpdir(), 'cadre-host-grants-route-'));
17
+ const service = new GrantService({ store: new GrantStore(tmpRoot) });
18
+ app = Fastify();
19
+ registerErrorHandler(app);
20
+ registerGrantsAdminRoutes(app, { handlers: createGrantAdminHandlers(service) });
21
+ });
22
+
23
+ afterEach(async () => {
24
+ await app.close();
25
+ try { rmSync(tmpRoot, { recursive: true, force: true }); } catch { /* ignore */ }
26
+ });
27
+
28
+ describe('/grants-admin routes', () => {
29
+ it('POST issues a grant, GET lists it, DELETE revokes it', async () => {
30
+ const post = await app.inject({
31
+ method: 'POST',
32
+ url: '/grants-admin',
33
+ payload: { label: "Alice's cadre", maxNodes: 2 },
34
+ });
35
+ expect(post.statusCode).toBe(200);
36
+ const created = (post.json() as { grant: Grant }).grant;
37
+ expect(created.token).toBeTruthy();
38
+ expect(created.maxNodes).toBe(2);
39
+
40
+ const list = await app.inject({ method: 'GET', url: '/grants-admin' });
41
+ expect(list.statusCode).toBe(200);
42
+ expect((list.json() as { grants: Grant[] }).grants.map(g => g.token)).toContain(created.token);
43
+
44
+ const del = await app.inject({
45
+ method: 'DELETE',
46
+ url: `/grants-admin/${encodeURIComponent(created.token)}`,
47
+ });
48
+ expect(del.statusCode).toBe(200);
49
+
50
+ // Revoked → still listed, now carries revokedAt.
51
+ const after = await app.inject({ method: 'GET', url: '/grants-admin' });
52
+ const row = (after.json() as { grants: Grant[] }).grants.find(g => g.token === created.token);
53
+ expect(row?.revokedAt).toBeTruthy();
54
+ });
55
+
56
+ it('POST with an empty label → 400 invalid_label', async () => {
57
+ const res = await app.inject({ method: 'POST', url: '/grants-admin', payload: { label: ' ' } });
58
+ expect(res.statusCode).toBe(400);
59
+ expect((res.json() as { error: { code: string } }).error.code).toBe('invalid_label');
60
+ });
61
+
62
+ it('POST with a bad maxNodes → 400 invalid_max_nodes', async () => {
63
+ const res = await app.inject({ method: 'POST', url: '/grants-admin', payload: { label: 'X', maxNodes: 0 } });
64
+ expect(res.statusCode).toBe(400);
65
+ expect((res.json() as { error: { code: string } }).error.code).toBe('invalid_max_nodes');
66
+ });
67
+
68
+ it('DELETE of an unknown token → 404 not_found', async () => {
69
+ const res = await app.inject({ method: 'DELETE', url: '/grants-admin/nope' });
70
+ expect(res.statusCode).toBe(404);
71
+ expect((res.json() as { error: { code: string } }).error.code).toBe('not_found');
72
+ });
73
+ });
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Grantee-facing `/grants` route tests — the bearer-gated provisioning surface.
3
+ *
4
+ * Uses a fake orchestrator (no real children) so the focus is the HTTP contract:
5
+ * bearer auth, request validation, per-grant ownership isolation, the quota gate,
6
+ * and seedToken redaction. The live-node round-trips (peer/seed) are covered by
7
+ * the cross-package integration scenario.
8
+ */
9
+
10
+ import Fastify from 'fastify';
11
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
12
+ import { mkdtempSync, rmSync } from 'node:fs';
13
+ import { tmpdir } from 'node:os';
14
+ import { join } from 'node:path';
15
+
16
+ import type {
17
+ Orchestrator,
18
+ OrchestratorCreateRequest,
19
+ OrchestratorCreateResult,
20
+ OrchestratorStats,
21
+ } from '@serfab/cadre-provider';
22
+
23
+ import { registerErrorHandler } from '../error-handler.js';
24
+ import { registerGrantsRoutes } from '../routes/grants.js';
25
+ import { DonationService } from '../../donation/donation-service.js';
26
+ import { DonationStore } from '../../donation/donation-store.js';
27
+ import { GrantService } from '../../donation/grant-service.js';
28
+ import { GrantStore } from '../../donation/grant-store.js';
29
+
30
+ class FakeOrchestrator implements Orchestrator {
31
+ stopped: string[] = [];
32
+ removed: string[] = [];
33
+ private counter = 0;
34
+ async createContainer(_request: OrchestratorCreateRequest): Promise<OrchestratorCreateResult> {
35
+ const n = ++this.counter;
36
+ return {
37
+ dockerId: `dock_${n}`,
38
+ healthEndpoint: `http://127.0.0.1:${9000 + n}/health`,
39
+ metricsEndpoint: `http://127.0.0.1:${9000 + n}/metrics`,
40
+ seedEndpoint: `http://127.0.0.1:${9000 + n}/seed`,
41
+ seedToken: `seed-token-${n}`,
42
+ p2pPort: 4000 + n,
43
+ };
44
+ }
45
+ async stopContainer(id: string): Promise<void> { this.stopped.push(id); }
46
+ async removeContainer(id: string): Promise<void> { this.removed.push(id); }
47
+ async getStats(): Promise<OrchestratorStats> {
48
+ return { cpuPercent: 0, memoryBytes: 0, networkRxBytes: 0, networkTxBytes: 0 };
49
+ }
50
+ async isRunning(): Promise<boolean> { return true; }
51
+ async getLogs(): Promise<string> { return ''; }
52
+ }
53
+
54
+ let tmpRoot: string;
55
+ let app: ReturnType<typeof Fastify>;
56
+ let grants: GrantService;
57
+ let token: string;
58
+
59
+ const body = {
60
+ partyId: 'party-P',
61
+ bootstrapNodes: ['/ip4/127.0.0.1/tcp/4001/p2p/12D3KooReq'],
62
+ ownerKeys: ['owner-key-b64url'],
63
+ };
64
+
65
+ const bearer = (t: string) => ({ authorization: `Bearer ${t}` });
66
+
67
+ beforeEach(() => {
68
+ tmpRoot = mkdtempSync(join(tmpdir(), 'cadre-host-grants-svc-route-'));
69
+ grants = new GrantService({ store: new GrantStore(join(tmpRoot, 'grants')) });
70
+ token = grants.issue({ label: 'Alice', maxNodes: 2 }).token;
71
+ const donations = new DonationService({
72
+ orchestrator: new FakeOrchestrator(),
73
+ grants,
74
+ store: new DonationStore(join(tmpRoot, 'donations')),
75
+ });
76
+ app = Fastify();
77
+ registerErrorHandler(app);
78
+ registerGrantsRoutes(app, { donations, grants });
79
+ });
80
+
81
+ afterEach(async () => {
82
+ await app.close();
83
+ try { rmSync(tmpRoot, { recursive: true, force: true }); } catch { /* ignore */ }
84
+ });
85
+
86
+ describe('POST /grants', () => {
87
+ it('provisions a donated node → 201, awaiting_seed, seedToken redacted', async () => {
88
+ const res = await app.inject({ method: 'POST', url: '/grants', headers: bearer(token), payload: body });
89
+ expect(res.statusCode).toBe(201);
90
+ const donation = (res.json() as { data: { donation: Record<string, unknown> } }).data.donation;
91
+ expect(donation.status).toBe('awaiting_seed');
92
+ expect(donation.partyId).toBe('party-P');
93
+ expect(donation.seedToken).toBeUndefined();
94
+ expect(donation.seedEndpoint).toBeUndefined();
95
+ });
96
+
97
+ it('rejects a missing bearer → 401', async () => {
98
+ const res = await app.inject({ method: 'POST', url: '/grants', payload: body });
99
+ expect(res.statusCode).toBe(401);
100
+ expect((res.json() as { error: { code: string } }).error.code).toBe('unauthorized');
101
+ });
102
+
103
+ it('rejects an unknown bearer → 401', async () => {
104
+ const res = await app.inject({ method: 'POST', url: '/grants', headers: bearer('nope'), payload: body });
105
+ expect(res.statusCode).toBe(401);
106
+ });
107
+
108
+ it('rejects a missing partyId → 400 invalid_request', async () => {
109
+ const res = await app.inject({
110
+ method: 'POST', url: '/grants', headers: bearer(token),
111
+ payload: { bootstrapNodes: body.bootstrapNodes, ownerKeys: body.ownerKeys },
112
+ });
113
+ expect(res.statusCode).toBe(400);
114
+ expect((res.json() as { error: { code: string } }).error.code).toBe('invalid_request');
115
+ });
116
+
117
+ it('rejects empty ownerKeys → 400 invalid_request', async () => {
118
+ const res = await app.inject({
119
+ method: 'POST', url: '/grants', headers: bearer(token),
120
+ payload: { ...body, ownerKeys: [] },
121
+ });
122
+ expect(res.statusCode).toBe(400);
123
+ });
124
+
125
+ it('enforces the grant quota → 429 quota_exceeded once maxNodes is reached', async () => {
126
+ const g = grants.issue({ label: 'Bob', maxNodes: 1 }).token;
127
+ const first = await app.inject({ method: 'POST', url: '/grants', headers: bearer(g), payload: body });
128
+ expect(first.statusCode).toBe(201);
129
+ const second = await app.inject({ method: 'POST', url: '/grants', headers: bearer(g), payload: body });
130
+ expect(second.statusCode).toBe(429);
131
+ expect((second.json() as { error: { code: string } }).error.code).toBe('quota_exceeded');
132
+ });
133
+ });
134
+
135
+ describe('GET /grants auth', () => {
136
+ it('rejects an unknown bearer → 401 unauthorized (code matches the status)', async () => {
137
+ const res = await app.inject({ method: 'GET', url: '/grants', headers: bearer('nope') });
138
+ expect(res.statusCode).toBe(401);
139
+ expect((res.json() as { error: { code: string } }).error.code).toBe('unauthorized');
140
+ });
141
+ });
142
+
143
+ describe('GET /grants (ownership isolation)', () => {
144
+ it('lists only the donations the presented grant authorized', async () => {
145
+ const other = grants.issue({ label: 'Carol' }).token;
146
+ await app.inject({ method: 'POST', url: '/grants', headers: bearer(token), payload: body });
147
+ await app.inject({ method: 'POST', url: '/grants', headers: bearer(other), payload: body });
148
+
149
+ const mine = await app.inject({ method: 'GET', url: '/grants', headers: bearer(token) });
150
+ const donations = (mine.json() as { data: { donations: Array<{ grantToken: string }> } }).data.donations;
151
+ expect(donations).toHaveLength(1);
152
+ expect(donations[0].grantToken).toBe(token);
153
+ });
154
+
155
+ it('a foreign grant cannot read another grant’s donation → 404', async () => {
156
+ const other = grants.issue({ label: 'Carol' }).token;
157
+ const created = await app.inject({ method: 'POST', url: '/grants', headers: bearer(token), payload: body });
158
+ const id = (created.json() as { data: { donation: { id: string } } }).data.donation.id;
159
+
160
+ const mine = await app.inject({ method: 'GET', url: `/grants/${id}`, headers: bearer(token) });
161
+ expect(mine.statusCode).toBe(200);
162
+
163
+ const foreign = await app.inject({ method: 'GET', url: `/grants/${id}`, headers: bearer(other) });
164
+ expect(foreign.statusCode).toBe(404);
165
+ });
166
+ });
167
+
168
+ describe('PUT /grants/:id/seed validation', () => {
169
+ it('rejects a missing seed body → 400 invalid_request', async () => {
170
+ const created = await app.inject({ method: 'POST', url: '/grants', headers: bearer(token), payload: body });
171
+ const id = (created.json() as { data: { donation: { id: string } } }).data.donation.id;
172
+ const res = await app.inject({ method: 'PUT', url: `/grants/${id}/seed`, headers: bearer(token), payload: {} });
173
+ expect(res.statusCode).toBe(400);
174
+ expect((res.json() as { error: { code: string } }).error.code).toBe('invalid_request');
175
+ });
176
+ });
177
+
178
+ describe('DELETE /grants/:id', () => {
179
+ it('terminates a donation and drops it from the live tally', async () => {
180
+ const created = await app.inject({ method: 'POST', url: '/grants', headers: bearer(token), payload: body });
181
+ const id = (created.json() as { data: { donation: { id: string } } }).data.donation.id;
182
+
183
+ const del = await app.inject({ method: 'DELETE', url: `/grants/${id}`, headers: bearer(token) });
184
+ expect(del.statusCode).toBe(200);
185
+
186
+ const one = await app.inject({ method: 'GET', url: `/grants/${id}`, headers: bearer(token) });
187
+ expect((one.json() as { data: { donation: { status: string } } }).data.donation.status).toBe('terminated');
188
+ });
189
+ });
@@ -15,25 +15,48 @@ interface FakeOrchestrator extends HostProcessOrchestrator {
15
15
  __nodes: Map<string, ManagedNodeInfo>;
16
16
  __listeners: Set<NodeStateListener>;
17
17
  __stoppedDockerIds: string[];
18
+ __ensured: number;
19
+ __restarted: number;
18
20
  }
19
21
 
20
- function fakeOrchestrator(initial: ManagedNodeInfo[] = []): FakeOrchestrator {
22
+ function fakeOrchestrator(
23
+ initial: ManagedNodeInfo[] = [],
24
+ opts: { ownerId?: string; hasOwnerConfig?: boolean } = {},
25
+ ): FakeOrchestrator {
21
26
  const nodes = new Map(initial.map((n) => [n.dockerId, n]));
22
27
  const listeners = new Set<NodeStateListener>();
23
28
  const stopped: string[] = [];
29
+ const counters = { ensured: 0, restarted: 0 };
30
+ const findById = (id: string): ManagedNodeInfo | undefined => {
31
+ const direct = nodes.get(id);
32
+ if (direct) return direct;
33
+ for (const n of nodes.values()) if (n.id === id) return n;
34
+ return undefined;
35
+ };
24
36
  const inst = {
25
37
  listNodes: () => [...nodes.values()],
26
- getNode: (id: string) => {
27
- const direct = nodes.get(id);
28
- if (direct) return direct;
29
- for (const n of nodes.values()) if (n.id === id) return n;
30
- return undefined;
31
- },
38
+ getNode: (id: string) => findById(id),
32
39
  resolveDockerId: (id: string) => {
33
40
  if (nodes.has(id)) return id;
34
41
  for (const n of nodes.values()) if (n.id === id) return n.dockerId;
35
42
  return undefined;
36
43
  },
44
+ isOwnerNode: (id: string) => {
45
+ if (!opts.ownerId) return false;
46
+ const node = findById(id);
47
+ return id === opts.ownerId || node?.id === opts.ownerId;
48
+ },
49
+ hasOwnerConfig: () => opts.hasOwnerConfig ?? false,
50
+ ensureOwnerNode: async () => {
51
+ counters.ensured++;
52
+ const node = opts.ownerId ? findById(opts.ownerId) : undefined;
53
+ return node ?? { id: opts.ownerId, status: 'running' } as unknown as ManagedNodeInfo;
54
+ },
55
+ restartOwnerNode: async () => {
56
+ counters.restarted++;
57
+ const node = opts.ownerId ? findById(opts.ownerId) : undefined;
58
+ return node ?? { id: opts.ownerId, status: 'running' } as unknown as ManagedNodeInfo;
59
+ },
37
60
  onStateChange: (l: NodeStateListener) => { listeners.add(l); return () => { listeners.delete(l); }; },
38
61
  stopContainer: async (dockerId: string) => {
39
62
  stopped.push(dockerId);
@@ -48,6 +71,8 @@ function fakeOrchestrator(initial: ManagedNodeInfo[] = []): FakeOrchestrator {
48
71
  __nodes: nodes,
49
72
  __listeners: listeners,
50
73
  __stoppedDockerIds: stopped,
74
+ get __ensured() { return counters.ensured; },
75
+ get __restarted() { return counters.restarted; },
51
76
  } as unknown as FakeOrchestrator;
52
77
  return inst;
53
78
  }
@@ -60,7 +85,7 @@ const SAMPLE_NODE: ManagedNodeInfo = {
60
85
  status: 'running',
61
86
  spawnedAt: '2025-01-01T00:00:00Z',
62
87
  workdir: '',
63
- ports: { health: 11, metrics: 12, p2p: 13 },
88
+ ports: { health: 11, metrics: 12, p2p: 13, admin: 14 },
64
89
  };
65
90
 
66
91
  describe('/api/nodes routes', () => {
@@ -146,17 +171,72 @@ describe('/api/nodes routes', () => {
146
171
  ]);
147
172
  });
148
173
 
149
- it('POST /api/nodes/:id/start returns 501 not_implemented', async () => {
174
+ it('POST /api/nodes/:id/start on a non-owner node returns 501 not_implemented', async () => {
150
175
  const res = await app.inject({ method: 'POST', url: '/api/nodes/alice/start' });
151
176
  expect(res.statusCode).toBe(501);
152
177
  const body = res.json() as { error: { code: string } };
153
178
  expect(body.error.code).toBe('not_implemented');
154
179
  });
155
180
 
156
- it('POST /api/nodes/:id/restart returns 501 not_implemented', async () => {
181
+ it('POST /api/nodes/:id/restart on a non-owner node returns 501 not_implemented', async () => {
157
182
  const res = await app.inject({ method: 'POST', url: '/api/nodes/alice/restart' });
158
183
  expect(res.statusCode).toBe(501);
159
184
  });
185
+
186
+ it('POST /api/nodes/:id/start on an unknown node returns 404', async () => {
187
+ const res = await app.inject({ method: 'POST', url: '/api/nodes/nobody/start' });
188
+ expect(res.statusCode).toBe(404);
189
+ const body = res.json() as { error: { code: string } };
190
+ expect(body.error.code).toBe('not_found');
191
+ });
192
+ });
193
+
194
+ describe('/api/nodes — owner node start/restart', () => {
195
+ const OWNER_NODE: ManagedNodeInfo = {
196
+ id: 'owner',
197
+ dockerId: '999:tok',
198
+ partyId: 'install-id',
199
+ profile: 'storage',
200
+ status: 'running',
201
+ spawnedAt: '2025-01-01T00:00:00Z',
202
+ workdir: '',
203
+ ports: { health: 1, metrics: 2, p2p: 4555, admin: 3 },
204
+ owner: true,
205
+ };
206
+
207
+ let app: ReturnType<typeof Fastify>;
208
+ let orchestrator: FakeOrchestrator;
209
+
210
+ beforeEach(() => {
211
+ app = Fastify();
212
+ registerErrorHandler(app);
213
+ orchestrator = fakeOrchestrator([OWNER_NODE], { ownerId: 'owner', hasOwnerConfig: true });
214
+ registerNodesRoutes(app, { orchestrator });
215
+ });
216
+
217
+ afterEach(async () => { await app.close(); });
218
+
219
+ it('start ensures the owner node', async () => {
220
+ const res = await app.inject({ method: 'POST', url: '/api/nodes/owner/start' });
221
+ expect(res.statusCode).toBe(200);
222
+ expect(orchestrator.__ensured).toBe(1);
223
+ });
224
+
225
+ it('restart re-spawns the owner node', async () => {
226
+ const res = await app.inject({ method: 'POST', url: '/api/nodes/owner/restart' });
227
+ expect(res.statusCode).toBe(200);
228
+ expect(orchestrator.__restarted).toBe(1);
229
+ });
230
+
231
+ it('start returns 501 when there is no saved owner config', async () => {
232
+ const app2 = Fastify();
233
+ registerErrorHandler(app2);
234
+ const orch2 = fakeOrchestrator([OWNER_NODE], { ownerId: 'owner', hasOwnerConfig: false });
235
+ registerNodesRoutes(app2, { orchestrator: orch2 });
236
+ const res = await app2.inject({ method: 'POST', url: '/api/nodes/owner/start' });
237
+ expect(res.statusCode).toBe(501);
238
+ await app2.close();
239
+ });
160
240
  });
161
241
 
162
242
  describe('tailLogFile', () => {
@@ -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 },
134
+ ports: { health: 1, metrics: 2, p2p: 3, admin: 4 },
135
135
  });
136
136
  expect(received).toContainEqual({
137
137
  type: 'node-state-changed',