@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
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  import type { ChildProcess } from 'node:child_process';
6
+ import type { PushCredentials } from '@serfab/cadre-core';
6
7
 
7
8
  /** User-facing configuration for `HostProcessOrchestrator`. */
8
9
  export interface HostProcessConfig {
@@ -23,6 +24,31 @@ export interface HostProcessConfig {
23
24
  * spawns `node <entrypoint> ...` instead of resolving `@serfab/cadre-cli`.
24
25
  */
25
26
  spawn?: { entrypoint?: string };
27
+ /**
28
+ * Resolver for the platform push credentials (FCM/APNs) to inject into a
29
+ * spawned strand-participating node's `cadre.json` (`config.push`). Called
30
+ * fresh on EVERY spawn/re-spawn so the secret store stays the source of truth
31
+ * and no raw private key is ever persisted in `state.json`. Returns `undefined`
32
+ * when no push credentials are configured (the default — push is opt-in). The
33
+ * resolver itself is responsible for rejecting a partial credential set.
34
+ */
35
+ pushResolver?: PushCredentialsResolver;
36
+ }
37
+
38
+ /**
39
+ * Resolves the push credentials to inject into a node being spawned. Re-invoked
40
+ * per spawn so a restart re-reads the secret store rather than replaying stale
41
+ * (or persisted) material. See {@link HostProcessConfig.pushResolver}.
42
+ */
43
+ export type PushCredentialsResolver = () => Promise<PushCredentials | undefined>;
44
+
45
+ /** Per-child allocated ports. `admin` carries the loopback admin channel (6.6). */
46
+ export interface NodePorts {
47
+ health: number;
48
+ metrics: number;
49
+ p2p: number;
50
+ /** Loopback admin-channel port. Bound only by the owner node. */
51
+ admin: number;
26
52
  }
27
53
 
28
54
  /** In-memory record per managed child. */
@@ -32,10 +58,12 @@ export interface Handle {
32
58
  pid: number;
33
59
  startupToken: string;
34
60
  workdir: string;
35
- ports: { health: number; metrics: number; p2p: number };
61
+ ports: NodePorts;
36
62
  spawnedAt: string;
37
63
  partyId: string;
38
64
  profile: 'storage' | 'transaction';
65
+ /** True for the admin's owner node (binds the admin channel). */
66
+ owner?: boolean;
39
67
  /** Live ChildProcess reference; absent after re-attach via init(). */
40
68
  child?: ChildProcess;
41
69
  /** Marked false when init() finds the PID dead or token mismatched. */
@@ -54,7 +82,25 @@ export interface ManagedNodeInfo {
54
82
  status: 'running' | 'stopped';
55
83
  spawnedAt: string;
56
84
  workdir: string;
57
- ports: { health: number; metrics: number; p2p: number };
85
+ ports: NodePorts;
86
+ /** True for the admin's owner node. */
87
+ owner?: boolean;
88
+ }
89
+
90
+ /**
91
+ * Persisted spawn parameters for the admin's owner node. Stored alongside
92
+ * the handles so an orchestrator restart can re-spawn the owner node from
93
+ * `/api/nodes/:id/{start,restart}` without the caller re-supplying them.
94
+ */
95
+ export interface OwnerSpawnConfig {
96
+ /** Absolute path to the host's libp2p protobuf identity (`identity.key`). */
97
+ identityPath: string;
98
+ /** Control-network partyId (the host's installId). */
99
+ partyId: string;
100
+ /** External libp2p port — mapped to the child's listen address. */
101
+ libp2pPort: number;
102
+ /** Node profile. Defaults to `storage` (the household node holds strands). */
103
+ profile?: 'storage' | 'transaction';
58
104
  }
59
105
 
60
106
  /**
@@ -0,0 +1,194 @@
1
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2
+ import http from 'node:http';
3
+
4
+ import { OwnerNodeClient, OwnerNodeUnavailableError } from '../owner-node-client.js';
5
+ import type { OwnerAdminEndpoint } from '../../orchestrator/index.js';
6
+
7
+ /**
8
+ * Stub HTTP server matching the 6.6 admin contract. Records the last request
9
+ * so tests can assert method/path/headers/body, and lets each test choose the
10
+ * response.
11
+ */
12
+ interface Recorded {
13
+ method: string;
14
+ path: string;
15
+ auth: string | undefined;
16
+ body: string;
17
+ }
18
+
19
+ const TOKEN = 'secret-bearer-token';
20
+
21
+ let server: http.Server;
22
+ let baseUrl: string;
23
+ let last: Recorded | null;
24
+ let responder: (req: Recorded) => { status: number; payload: unknown };
25
+
26
+ beforeEach(async () => {
27
+ last = null;
28
+ responder = () => ({ status: 200, payload: { ok: true, data: { ok: true } } });
29
+ server = http.createServer((req, res) => {
30
+ const chunks: Buffer[] = [];
31
+ req.on('data', (c) => chunks.push(c as Buffer));
32
+ req.on('end', () => {
33
+ const rec: Recorded = {
34
+ method: req.method ?? 'GET',
35
+ path: req.url ?? '/',
36
+ auth: req.headers['authorization'] as string | undefined,
37
+ body: Buffer.concat(chunks).toString('utf8'),
38
+ };
39
+ last = rec;
40
+ const { status, payload } = responder(rec);
41
+ res.writeHead(status, { 'content-type': 'application/json' });
42
+ res.end(JSON.stringify(payload));
43
+ });
44
+ });
45
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()));
46
+ const addr = server.address();
47
+ const port = typeof addr === 'object' && addr ? addr.port : 0;
48
+ baseUrl = `http://127.0.0.1:${port}`;
49
+ });
50
+
51
+ afterEach(async () => {
52
+ await new Promise<void>((resolve) => server.close(() => resolve()));
53
+ });
54
+
55
+ function makeClient(): OwnerNodeClient {
56
+ const endpoint: OwnerAdminEndpoint = { baseUrl, token: TOKEN };
57
+ return new OwnerNodeClient(endpoint);
58
+ }
59
+
60
+ describe('OwnerNodeClient', () => {
61
+ it('createInvite POSTs /admin/invites with bearer + body and unwraps data', async () => {
62
+ responder = () => ({
63
+ status: 200,
64
+ payload: { ok: true, data: { invite: { partyId: 'p', ownerAddrs: [], token: 't', createdAt: 1 }, encodedInvite: 'enc' } },
65
+ });
66
+ const client = makeClient();
67
+ const result = await client.createInvite('t', 60_000);
68
+
69
+ expect(result.encodedInvite).toBe('enc');
70
+ expect(last?.method).toBe('POST');
71
+ expect(last?.path).toBe('/admin/invites');
72
+ expect(last?.auth).toBe(`Bearer ${TOKEN}`);
73
+ expect(JSON.parse(last!.body)).toEqual({ token: 't', expiresInMs: 60_000 });
74
+ });
75
+
76
+ it('acceptPhone POSTs /admin/accept-phone', async () => {
77
+ const client = makeClient();
78
+ await client.acceptPhone({ phonePeerId: '12D3KooWX', token: 't' }, { partyId: 'p', ownerAddrs: [], token: 't', createdAt: 1 });
79
+ expect(last?.method).toBe('POST');
80
+ expect(last?.path).toBe('/admin/accept-phone');
81
+ const body = JSON.parse(last!.body);
82
+ expect(body.phonePeerId).toBe('12D3KooWX');
83
+ expect(body.issuedInvite.token).toBe('t');
84
+ });
85
+
86
+ it('removePeer DELETEs /admin/members/:peerId (url-encoded)', async () => {
87
+ const client = makeClient();
88
+ await client.removePeer('12D3KooWMember');
89
+ expect(last?.method).toBe('DELETE');
90
+ expect(last?.path).toBe('/admin/members/12D3KooWMember');
91
+ });
92
+
93
+ it('listMembers GETs /admin/members and returns the array', async () => {
94
+ responder = () => ({ status: 200, payload: { ok: true, data: { members: [{ peerId: 'a', multiaddr: '/ip4/1.2.3.4/tcp/1' }] } } });
95
+ const client = makeClient();
96
+ const members = await client.listMembers();
97
+ expect(last?.method).toBe('GET');
98
+ expect(last?.path).toBe('/admin/members');
99
+ expect(members).toEqual([{ peerId: 'a', multiaddr: '/ip4/1.2.3.4/tcp/1' }]);
100
+ });
101
+
102
+ it('isMember GETs /admin/members/:peerId and returns the boolean', async () => {
103
+ responder = () => ({ status: 200, payload: { ok: true, data: { member: true } } });
104
+ const client = makeClient();
105
+ expect(await client.isMember('peer-1')).toBe(true);
106
+ expect(last?.path).toBe('/admin/members/peer-1');
107
+ });
108
+
109
+ it('listAuthorizedMembers GETs /admin/authorized-members and returns the array', async () => {
110
+ responder = () => ({ status: 200, payload: { ok: true, data: { members: [{ peerId: 'b', multiaddr: null }] } } });
111
+ const client = makeClient();
112
+ const members = await client.listAuthorizedMembers();
113
+ expect(last?.method).toBe('GET');
114
+ expect(last?.path).toBe('/admin/authorized-members');
115
+ expect(members).toEqual([{ peerId: 'b', multiaddr: null }]);
116
+ });
117
+
118
+ it('isAuthorizedMember GETs /admin/authorized-members/:peerId and returns the boolean', async () => {
119
+ responder = () => ({ status: 200, payload: { ok: true, data: { member: false } } });
120
+ const client = makeClient();
121
+ expect(await client.isAuthorizedMember('peer-2')).toBe(false);
122
+ expect(last?.path).toBe('/admin/authorized-members/peer-2');
123
+ });
124
+
125
+ it('getPeerId GETs /admin/identity', async () => {
126
+ responder = () => ({ status: 200, payload: { ok: true, data: { peerId: '12D3KooWHost', partyId: 'party' } } });
127
+ const client = makeClient();
128
+ expect(await client.getPeerId()).toBe('12D3KooWHost');
129
+ expect(last?.path).toBe('/admin/identity');
130
+ });
131
+
132
+ it('getMultiaddrs GETs /admin/multiaddrs', async () => {
133
+ responder = () => ({ status: 200, payload: { ok: true, data: { multiaddrs: ['/ip4/0.0.0.0/tcp/4001'] } } });
134
+ const client = makeClient();
135
+ expect(await client.getMultiaddrs()).toEqual(['/ip4/0.0.0.0/tcp/4001']);
136
+ expect(last?.path).toBe('/admin/multiaddrs');
137
+ });
138
+
139
+ it('pushInviteAddresses PUTs /admin/invite-addresses', async () => {
140
+ const client = makeClient();
141
+ await client.pushInviteAddresses(['/dns4/h/tcp/1/p2p/x']);
142
+ expect(last?.method).toBe('PUT');
143
+ expect(last?.path).toBe('/admin/invite-addresses');
144
+ expect(JSON.parse(last!.body)).toEqual({ addresses: ['/dns4/h/tcp/1/p2p/x'] });
145
+ });
146
+
147
+ it('addDrone POSTs /admin/add-drone with body and unwraps the seed result', async () => {
148
+ responder = () => ({ status: 200, payload: { ok: true, data: { seed: { partyId: 'p', peers: [] }, encodedSeed: 'enc-seed' } } });
149
+ const client = makeClient();
150
+ const result = await client.addDrone({ dronePeerId: '12D3KooWDrone', droneMultiaddrs: ['/ip4/10.0.0.9/tcp/4001'] });
151
+
152
+ expect(result.encodedSeed).toBe('enc-seed');
153
+ expect(last?.method).toBe('POST');
154
+ expect(last?.path).toBe('/admin/add-drone');
155
+ expect(last?.auth).toBe(`Bearer ${TOKEN}`);
156
+ expect(JSON.parse(last!.body)).toEqual({ dronePeerId: '12D3KooWDrone', droneMultiaddrs: ['/ip4/10.0.0.9/tcp/4001'] });
157
+ });
158
+
159
+ it('encodeInvite mirrors cadre-core base64url(JSON)', () => {
160
+ const client = makeClient();
161
+ const invite = { partyId: 'p', ownerAddrs: [], token: 't', createdAt: 1 };
162
+ const encoded = client.encodeInvite(invite);
163
+ const decoded = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8'));
164
+ expect(decoded).toEqual(invite);
165
+ });
166
+
167
+ it('maps a non-2xx response to OwnerNodeUnavailableError carrying the code', async () => {
168
+ responder = () => ({ status: 503, payload: { ok: false, error: { code: 'not_ready', message: 'node booting' } } });
169
+ const client = makeClient();
170
+ await expect(client.getPeerId()).rejects.toBeInstanceOf(OwnerNodeUnavailableError);
171
+ await expect(client.getPeerId()).rejects.toMatchObject({ nodeCode: 'not_ready' });
172
+ });
173
+
174
+ it('maps a refused connection to OwnerNodeUnavailableError', async () => {
175
+ // Bind a throwaway server to claim a port, then close it so the address
176
+ // is guaranteed refused.
177
+ const tmp = http.createServer();
178
+ const closedPort = await new Promise<number>((resolve) => {
179
+ tmp.listen(0, '127.0.0.1', () => {
180
+ const a = tmp.address();
181
+ resolve(typeof a === 'object' && a ? a.port : 0);
182
+ });
183
+ });
184
+ await new Promise<void>((resolve) => tmp.close(() => resolve()));
185
+
186
+ const client = new OwnerNodeClient({ baseUrl: `http://127.0.0.1:${closedPort}`, token: TOKEN });
187
+ await expect(client.getPeerId()).rejects.toBeInstanceOf(OwnerNodeUnavailableError);
188
+ });
189
+
190
+ it('throws OwnerNodeUnavailableError when the endpoint is undefined', async () => {
191
+ const client = new OwnerNodeClient(() => undefined);
192
+ await expect(client.getPeerId()).rejects.toBeInstanceOf(OwnerNodeUnavailableError);
193
+ });
194
+ });
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Owner-node delegation surface for cadre-host.
3
+ *
4
+ * The manager process spawns the admin's owner cadre node (via
5
+ * `HostProcessOrchestrator`) and delegates owner/membership/identity
6
+ * operations to it over the loopback admin channel using
7
+ * {@link OwnerNodeClient}. See `docs/cadre-host.md` § Control-plane
8
+ * separation.
9
+ */
10
+
11
+ export { OwnerNodeClient, OwnerNodeUnavailableError } from './owner-node-client.js';
12
+ export type { OwnerNodeClientOptions } from './owner-node-client.js';
@@ -0,0 +1,233 @@
1
+ /**
2
+ * HTTP client for the owner node's loopback admin channel (the 6.6
3
+ * `cadre-node-admin-channel` contract).
4
+ *
5
+ * cadre-host's manager process holds no in-process `CadreNode`; it spawns the
6
+ * admin's owner node as a managed child (see `HostProcessOrchestrator`)
7
+ * and delegates all owner/membership/identity operations to it over this
8
+ * client. The client implements **both** trimmed `CadreNodeLike` interfaces —
9
+ * the trust-circle one (`auth/trust-circle.ts`) and the NAT one
10
+ * (`nat/nat-service.ts`) — plus `pushInviteAddresses` and `addDrone` (the
11
+ * node-donation requester side).
12
+ *
13
+ * Transport: `Authorization: Bearer <token>` against
14
+ * `http://127.0.0.1:<adminPort>`. Every response uses the cadre-provider
15
+ * envelope `{ ok: true, data }` / `{ ok: false, error: { code, message } }`.
16
+ * A refused connection, a transport error, or any non-2xx response surfaces
17
+ * as {@link OwnerNodeUnavailableError}; the trust-circle / NAT services
18
+ * translate that into a `node_unavailable` domain error so the management API
19
+ * returns a clear 503 rather than a raw 500.
20
+ */
21
+
22
+ import debug from 'debug';
23
+ import type { CadreInvite, DroneInitResult } from '@serfab/cadre-core';
24
+
25
+ import type { OwnerAdminEndpoint } from '../orchestrator/index.js';
26
+ import type { CadreNodeLike as TrustCircleCadreNodeLike } from '../auth/trust-circle.js';
27
+ import type { CadreNodeLike as NatCadreNodeLike } from '../nat/nat-service.js';
28
+
29
+ const log = debug('cadre:host:owner-client');
30
+
31
+ /**
32
+ * Raised when the owner node's admin channel can't be reached or returns
33
+ * a non-success response. Carries the node's stable error `code` when one was
34
+ * present in the envelope (e.g. `not_ready`, `not_authorized`).
35
+ */
36
+ export class OwnerNodeUnavailableError extends Error {
37
+ /** The admin-channel error code, when the node answered with an envelope. */
38
+ readonly nodeCode?: string;
39
+
40
+ constructor(message: string, nodeCode?: string) {
41
+ super(message);
42
+ this.name = 'OwnerNodeUnavailableError';
43
+ if (nodeCode !== undefined) this.nodeCode = nodeCode;
44
+ }
45
+ }
46
+
47
+ /** Endpoint provided directly or via a getter (so it tracks re-spawns). */
48
+ type EndpointSource =
49
+ | OwnerAdminEndpoint
50
+ | (() => OwnerAdminEndpoint | undefined)
51
+ | undefined;
52
+
53
+ export interface OwnerNodeClientOptions {
54
+ /** Fetch override for tests. Defaults to the global `fetch`. */
55
+ fetch?: typeof fetch;
56
+ }
57
+
58
+ export class OwnerNodeClient implements TrustCircleCadreNodeLike, NatCadreNodeLike {
59
+ private readonly endpointSource: EndpointSource;
60
+ private readonly fetchImpl: typeof fetch;
61
+
62
+ /**
63
+ * @param endpoint Either a fixed `{ baseUrl, token }` or a getter returning
64
+ * the current endpoint (pass `orchestrator.getOwnerAdminEndpoint`
65
+ * bound, so a restart's new bearer token is picked up automatically).
66
+ */
67
+ constructor(endpoint: EndpointSource, opts: OwnerNodeClientOptions = {}) {
68
+ this.endpointSource = endpoint;
69
+ this.fetchImpl = opts.fetch ?? fetch;
70
+ }
71
+
72
+ // --- trust-circle CadreNodeLike ---
73
+
74
+ async createInvite(
75
+ token?: string,
76
+ expiresInMs?: number,
77
+ ): Promise<{ invite: CadreInvite; encodedInvite: string }> {
78
+ const body: Record<string, unknown> = {};
79
+ if (token !== undefined) body.token = token;
80
+ if (expiresInMs !== undefined) body.expiresInMs = expiresInMs;
81
+ return await this.request<{ invite: CadreInvite; encodedInvite: string }>(
82
+ 'POST',
83
+ '/admin/invites',
84
+ body,
85
+ );
86
+ }
87
+
88
+ async acceptPhone(
89
+ options: { phonePeerId: string; token?: string },
90
+ issuedInvite?: CadreInvite,
91
+ ): Promise<void> {
92
+ const body: Record<string, unknown> = { phonePeerId: options.phonePeerId };
93
+ if (options.token !== undefined) body.token = options.token;
94
+ if (issuedInvite !== undefined) body.issuedInvite = issuedInvite;
95
+ await this.request('POST', '/admin/accept-phone', body);
96
+ }
97
+
98
+ async removePeer(peerId: string): Promise<void> {
99
+ await this.request('DELETE', `/admin/members/${encodeURIComponent(peerId)}`);
100
+ }
101
+
102
+ /**
103
+ * Encode an invite for out-of-band delivery. The admin contract has no
104
+ * encode route (the mint route already returns `encodedInvite`), so this
105
+ * mirrors cadre-core's encoding (`base64url(JSON.stringify(invite))`).
106
+ */
107
+ encodeInvite(invite: CadreInvite): string {
108
+ return Buffer.from(JSON.stringify(invite), 'utf8').toString('base64url');
109
+ }
110
+
111
+ async listMembers(): Promise<Array<{ peerId: string; multiaddr: string | null }>> {
112
+ const data = await this.request<{ members: Array<{ peerId: string; multiaddr: string | null }> }>(
113
+ 'GET',
114
+ '/admin/members',
115
+ );
116
+ return data.members;
117
+ }
118
+
119
+ async isMember(peerId: string): Promise<boolean> {
120
+ const data = await this.request<{ member: boolean }>(
121
+ 'GET',
122
+ `/admin/members/${encodeURIComponent(peerId)}`,
123
+ );
124
+ return data.member;
125
+ }
126
+
127
+ /** Authorized-membership surface (excludes self) — see {@link listMembers} for the addressable one. */
128
+ async listAuthorizedMembers(): Promise<Array<{ peerId: string; multiaddr: string | null }>> {
129
+ const data = await this.request<{ members: Array<{ peerId: string; multiaddr: string | null }> }>(
130
+ 'GET',
131
+ '/admin/authorized-members',
132
+ );
133
+ return data.members;
134
+ }
135
+
136
+ async isAuthorizedMember(peerId: string): Promise<boolean> {
137
+ const data = await this.request<{ member: boolean }>(
138
+ 'GET',
139
+ `/admin/authorized-members/${encodeURIComponent(peerId)}`,
140
+ );
141
+ return data.member;
142
+ }
143
+
144
+ // --- NAT CadreNodeLike ---
145
+
146
+ async getPeerId(): Promise<string> {
147
+ const data = await this.request<{ peerId: string | null; partyId: string }>('GET', '/admin/identity');
148
+ return data.peerId ?? '';
149
+ }
150
+
151
+ async getMultiaddrs(): Promise<string[]> {
152
+ const data = await this.request<{ multiaddrs: string[] }>('GET', '/admin/multiaddrs');
153
+ return data.multiaddrs;
154
+ }
155
+
156
+ // --- drone seeding (node-donation requester side) ---
157
+
158
+ /**
159
+ * Mint a seed authorizing a drone — a provider-hosted / donated node — to join
160
+ * this node's cadre. The node signs the seed with its own authority key; only
161
+ * the signed, public `encodedSeed` is returned (the private key never leaves
162
+ * the node). This is the requester ("phone") side of the node-donation flow:
163
+ * the donor host presents the returned seed to the donated node's `POST /seed`.
164
+ */
165
+ async addDrone(options: { dronePeerId: string; droneMultiaddrs: string[] }): Promise<DroneInitResult> {
166
+ return await this.request<DroneInitResult>('POST', '/admin/add-drone', {
167
+ dronePeerId: options.dronePeerId,
168
+ droneMultiaddrs: options.droneMultiaddrs,
169
+ });
170
+ }
171
+
172
+ // --- push-model invite addresses ---
173
+
174
+ /** Push the NAT-resolved addresses the node should embed in future invites. */
175
+ async pushInviteAddresses(addresses: string[]): Promise<void> {
176
+ await this.request('PUT', '/admin/invite-addresses', { addresses });
177
+ }
178
+
179
+ // --- internals ---
180
+
181
+ private resolveEndpoint(): OwnerAdminEndpoint {
182
+ const ep = typeof this.endpointSource === 'function' ? this.endpointSource() : this.endpointSource;
183
+ if (!ep) {
184
+ throw new OwnerNodeUnavailableError('Owner node admin endpoint is not available');
185
+ }
186
+ return ep;
187
+ }
188
+
189
+ private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
190
+ const ep = this.resolveEndpoint();
191
+ const headers: Record<string, string> = { authorization: `Bearer ${ep.token}` };
192
+ const init: RequestInit = { method, headers };
193
+ if (body !== undefined) {
194
+ headers['content-type'] = 'application/json';
195
+ init.body = JSON.stringify(body);
196
+ }
197
+
198
+ let res: Response;
199
+ try {
200
+ res = await this.fetchImpl(`${ep.baseUrl}${path}`, init);
201
+ } catch (err) {
202
+ const message = err instanceof Error ? err.message : String(err);
203
+ log('admin %s %s transport error: %s', method, path, message);
204
+ throw new OwnerNodeUnavailableError(`Owner node unreachable: ${message}`);
205
+ }
206
+
207
+ const envelope = await this.parseEnvelope(res);
208
+ if (!res.ok || !envelope.ok) {
209
+ const code = envelope.error?.code;
210
+ const message = envelope.error?.message ?? `admin ${method} ${path} → HTTP ${res.status}`;
211
+ log('admin %s %s failed: [%s] %s', method, path, code ?? res.status, message);
212
+ throw new OwnerNodeUnavailableError(message, code);
213
+ }
214
+ return envelope.data as T;
215
+ }
216
+
217
+ private async parseEnvelope(res: Response): Promise<{
218
+ ok?: boolean;
219
+ data?: unknown;
220
+ error?: { code?: string; message?: string };
221
+ }> {
222
+ try {
223
+ const parsed = await res.json();
224
+ if (parsed && typeof parsed === 'object') {
225
+ return parsed as { ok?: boolean; data?: unknown; error?: { code?: string; message?: string } };
226
+ }
227
+ } catch {
228
+ // Non-JSON body — fall through to an empty envelope; status drives the
229
+ // ok/non-ok decision in the caller.
230
+ }
231
+ return {};
232
+ }
233
+ }
@@ -0,0 +1,90 @@
1
+ import { describe, it, expect } from 'vitest';
2
+
3
+ import type { SecretsStore } from '../../nat/secrets/index.js';
4
+ import type { PushSettings } from '../../installer/config.js';
5
+ import {
6
+ resolvePushCredentials,
7
+ setFcmSecret,
8
+ setApnsSecret,
9
+ clearPushSecret,
10
+ pushAccount,
11
+ pushStatus,
12
+ } from '../index.js';
13
+
14
+ /** In-memory SecretsStore for tests. */
15
+ function fakeStore(): SecretsStore {
16
+ const map = new Map<string, string>();
17
+ return {
18
+ async set(account, value) { map.set(account, value); },
19
+ async get(account) { return map.get(account) ?? null; },
20
+ async delete(account) { return map.delete(account); },
21
+ async list() { return [...map.keys()]; },
22
+ };
23
+ }
24
+
25
+ const FCM = { projectId: 'proj', clientEmail: 'svc@proj.iam', privateKey: 'FCM-PEM' };
26
+ const APNS = { keyId: 'KID', teamId: 'TEAM', privateKey: 'P8-PEM' };
27
+
28
+ describe('resolvePushCredentials', () => {
29
+ it('returns undefined when no platform is configured (opt-in default)', async () => {
30
+ const store = fakeStore();
31
+ expect(await resolvePushCredentials(store, undefined)).toBeUndefined();
32
+ });
33
+
34
+ it('resolves an FCM-only bundle from the secret store', async () => {
35
+ const store = fakeStore();
36
+ await setFcmSecret(store, FCM);
37
+ const push = await resolvePushCredentials(store, undefined);
38
+ expect(push).toEqual({ fcm: FCM });
39
+ });
40
+
41
+ it('merges the APNs secret with non-secret bundleId/production from settings', async () => {
42
+ const store = fakeStore();
43
+ await setApnsSecret(store, APNS);
44
+ const settings: PushSettings = { apns: { bundleId: 'com.example.app', production: true }, cooldownMs: 1000, debounceMs: 50 };
45
+ const push = await resolvePushCredentials(store, settings);
46
+ expect(push).toEqual({
47
+ apns: { keyId: 'KID', teamId: 'TEAM', bundleId: 'com.example.app', privateKey: 'P8-PEM', production: true },
48
+ cooldownMs: 1000,
49
+ debounceMs: 50,
50
+ });
51
+ });
52
+
53
+ it('combines both platforms when both secrets are present', async () => {
54
+ const store = fakeStore();
55
+ await setFcmSecret(store, FCM);
56
+ await setApnsSecret(store, APNS);
57
+ const push = await resolvePushCredentials(store, { apns: { bundleId: 'com.example.app' } });
58
+ expect(push?.fcm).toEqual(FCM);
59
+ expect(push?.apns?.bundleId).toBe('com.example.app');
60
+ });
61
+
62
+ it('throws on a partial APNs config (secret present but bundleId unset)', async () => {
63
+ const store = fakeStore();
64
+ await setApnsSecret(store, APNS);
65
+ // No settings.apns.bundleId → bundleId resolves to '' → validation rejects.
66
+ await expect(resolvePushCredentials(store, undefined)).rejects.toThrow(/push\.apns\.bundleId/);
67
+ });
68
+
69
+ it('keeps the FCM private key out of the secret-store account name', async () => {
70
+ const store = fakeStore();
71
+ await setFcmSecret(store, FCM);
72
+ const accounts = await store.list();
73
+ expect(accounts).toContain(pushAccount('fcm'));
74
+ expect(accounts.join()).not.toContain('FCM-PEM');
75
+ });
76
+ });
77
+
78
+ describe('clearPushSecret / pushStatus', () => {
79
+ it('reports configured platforms and clears them', async () => {
80
+ const store = fakeStore();
81
+ await setFcmSecret(store, FCM);
82
+ await setApnsSecret(store, APNS);
83
+ expect(await pushStatus(store)).toEqual({ fcm: true, apns: true });
84
+
85
+ expect(await clearPushSecret(store, 'fcm')).toBe(true);
86
+ expect(await pushStatus(store)).toEqual({ fcm: false, apns: true });
87
+
88
+ expect(await clearPushSecret(store, 'fcm')).toBe(false);
89
+ });
90
+ });