@serfab/cadre-host 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) 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 +32 -5
  8. package/dist/auth/trust-circle.js +31 -11
  9. package/dist/auth/trust-circle.js.map +1 -1
  10. package/dist/bin/host.js +41 -5
  11. package/dist/bin/host.js.map +1 -1
  12. package/dist/donation/__tests__/fake-orchestrator.d.ts +103 -0
  13. package/dist/donation/__tests__/fake-orchestrator.js +180 -0
  14. package/dist/donation/__tests__/fake-orchestrator.js.map +1 -0
  15. package/dist/donation/donation-service.d.ts +237 -12
  16. package/dist/donation/donation-service.js +491 -34
  17. package/dist/donation/donation-service.js.map +1 -1
  18. package/dist/donation/donation-store.d.ts +7 -0
  19. package/dist/donation/donation-store.js +7 -0
  20. package/dist/donation/donation-store.js.map +1 -1
  21. package/dist/donation/donation-supervisor.d.ts +167 -0
  22. package/dist/donation/donation-supervisor.js +341 -0
  23. package/dist/donation/donation-supervisor.js.map +1 -0
  24. package/dist/donation/index.d.ts +4 -2
  25. package/dist/donation/index.js +2 -1
  26. package/dist/donation/index.js.map +1 -1
  27. package/dist/donation/types.d.ts +26 -0
  28. package/dist/donation/types.js.map +1 -1
  29. package/dist/index.d.ts +3 -1
  30. package/dist/index.js +3 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/orchestrator/host-process-orchestrator.d.ts +109 -5
  33. package/dist/orchestrator/host-process-orchestrator.js +341 -98
  34. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  35. package/dist/orchestrator/node-identity.d.ts +26 -0
  36. package/dist/orchestrator/node-identity.js +36 -0
  37. package/dist/orchestrator/node-identity.js.map +1 -0
  38. package/dist/orchestrator/port-allocator.d.ts +14 -0
  39. package/dist/orchestrator/port-allocator.js +45 -0
  40. package/dist/orchestrator/port-allocator.js.map +1 -1
  41. package/dist/owner/owner-node-client.d.ts +20 -5
  42. package/dist/owner/owner-node-client.js +21 -4
  43. package/dist/owner/owner-node-client.js.map +1 -1
  44. package/dist/server/error-handler.d.ts +7 -1
  45. package/dist/server/error-handler.js +23 -1
  46. package/dist/server/error-handler.js.map +1 -1
  47. package/dist/server/events/types.d.ts +3 -0
  48. package/dist/server/index.d.ts +7 -0
  49. package/dist/server/index.js +9 -3
  50. package/dist/server/index.js.map +1 -1
  51. package/dist/server/routes/grants.js +22 -3
  52. package/dist/server/routes/grants.js.map +1 -1
  53. package/dist/server/routes/strands.d.ts +20 -0
  54. package/dist/server/routes/strands.js +38 -0
  55. package/dist/server/routes/strands.js.map +1 -0
  56. package/dist/server/static.js +38 -38
  57. package/dist/strands/index.d.ts +7 -0
  58. package/dist/strands/index.js +6 -0
  59. package/dist/strands/index.js.map +1 -0
  60. package/dist/strands/strand-service.d.ts +50 -0
  61. package/dist/strands/strand-service.js +103 -0
  62. package/dist/strands/strand-service.js.map +1 -0
  63. package/dist/strands/types.d.ts +93 -0
  64. package/dist/strands/types.js +23 -0
  65. package/dist/strands/types.js.map +1 -0
  66. package/dist/ui/assets/index-BVoqLjyX.css +1 -0
  67. package/dist/ui/assets/index-C-iks41M.js +17 -0
  68. package/dist/ui/assets/index-C-iks41M.js.map +1 -0
  69. package/dist/ui/index.html +14 -14
  70. package/dist/update/release-key.d.ts +1 -1
  71. package/dist/update/release-key.js +1 -1
  72. package/package.json +5 -5
  73. package/service/cadre-host.service.tmpl +16 -16
  74. package/service/com.serfab.cadre-host.plist.tmpl +35 -35
  75. package/service/install-service.ps1 +98 -98
  76. package/service/uninstall-service.ps1 +19 -19
  77. package/src/__tests__/build-targets.test.ts +26 -0
  78. package/src/__tests__/cli-invite.smoke.test.ts +192 -192
  79. package/src/__tests__/cli-nat.smoke.test.ts +212 -212
  80. package/src/__tests__/cli.smoke.test.ts +46 -46
  81. package/src/__tests__/global-setup.ts +51 -0
  82. package/src/__tests__/host-owner.smoke.test.ts +123 -123
  83. package/src/__tests__/orchestrator-env-scrub.test.ts +140 -0
  84. package/src/__tests__/orchestrator-node-identity.test.ts +204 -0
  85. package/src/__tests__/orchestrator-owner.test.ts +198 -198
  86. package/src/__tests__/orchestrator-pin-keys.test.ts +153 -153
  87. package/src/__tests__/orchestrator-push.test.ts +145 -145
  88. package/src/__tests__/orchestrator.test.ts +951 -570
  89. package/src/auth/__tests__/duration.test.ts +28 -28
  90. package/src/auth/__tests__/self-label.test.ts +85 -0
  91. package/src/auth/__tests__/trust-circle-integration.test.ts +152 -147
  92. package/src/auth/__tests__/trust-circle-store.test.ts +115 -115
  93. package/src/auth/__tests__/trust-circle.test.ts +445 -401
  94. package/src/auth/duration.ts +33 -33
  95. package/src/auth/index.ts +21 -19
  96. package/src/auth/self-label.ts +74 -0
  97. package/src/auth/trust-circle-store.ts +155 -155
  98. package/src/auth/trust-circle.ts +45 -13
  99. package/src/auth/types.ts +99 -99
  100. package/src/bin/host.ts +1299 -1258
  101. package/src/donation/__tests__/donation-service.test.ts +1068 -290
  102. package/src/donation/__tests__/donation-supervisor.test.ts +510 -0
  103. package/src/donation/__tests__/fake-orchestrator.test.ts +168 -0
  104. package/src/donation/__tests__/fake-orchestrator.ts +225 -0
  105. package/src/donation/__tests__/grant-service.test.ts +213 -213
  106. package/src/donation/__tests__/grant-store.test.ts +113 -113
  107. package/src/donation/donation-service.ts +962 -392
  108. package/src/donation/donation-store.ts +171 -164
  109. package/src/donation/donation-supervisor.ts +388 -0
  110. package/src/donation/grant-service.ts +200 -200
  111. package/src/donation/grant-store.ts +152 -152
  112. package/src/donation/index.ts +64 -49
  113. package/src/donation/types.ts +243 -220
  114. package/src/index.ts +14 -0
  115. package/src/installer/__tests__/identity.test.ts +34 -34
  116. package/src/installer/__tests__/paths.test.ts +47 -47
  117. package/src/installer/__tests__/service-host.test.ts +62 -62
  118. package/src/installer/__tests__/wizard.test.ts +64 -64
  119. package/src/installer/identity.ts +49 -49
  120. package/src/installer/paths.ts +109 -109
  121. package/src/installer/platform.ts +27 -27
  122. package/src/installer/service-host/index.ts +21 -21
  123. package/src/installer/service-host/template.ts +21 -21
  124. package/src/installer/wizard.ts +103 -103
  125. package/src/nat/__tests__/address-resolver.test.ts +82 -82
  126. package/src/nat/__tests__/ddns-duckdns.test.ts +83 -83
  127. package/src/nat/__tests__/ddns-updater.test.ts +253 -253
  128. package/src/nat/__tests__/external-ip.test.ts +124 -124
  129. package/src/nat/__tests__/nat-service.test.ts +497 -497
  130. package/src/nat/__tests__/nat-store.test.ts +93 -93
  131. package/src/nat/__tests__/port-mapper.test.ts +191 -191
  132. package/src/nat/__tests__/reachability.test.ts +24 -24
  133. package/src/nat/__tests__/secrets.test.ts +178 -178
  134. package/src/nat/address-resolver.ts +51 -51
  135. package/src/nat/ddns/duckdns.ts +76 -76
  136. package/src/nat/ddns/index.ts +55 -55
  137. package/src/nat/ddns/updater.ts +243 -243
  138. package/src/nat/external-ip.ts +154 -154
  139. package/src/nat/index.ts +71 -71
  140. package/src/nat/nat-service.ts +501 -501
  141. package/src/nat/nat-store.ts +154 -154
  142. package/src/nat/port-mapper.ts +329 -329
  143. package/src/nat/reachability.ts +34 -34
  144. package/src/nat/secrets/file-store.ts +130 -130
  145. package/src/nat/secrets/index.ts +112 -112
  146. package/src/nat/secrets/keytar-store.ts +67 -67
  147. package/src/nat/types.ts +159 -159
  148. package/src/orchestrator/__tests__/node-identity.test.ts +62 -0
  149. package/src/orchestrator/host-process-orchestrator.ts +1133 -894
  150. package/src/orchestrator/index.ts +10 -10
  151. package/src/orchestrator/log-rotator.ts +53 -53
  152. package/src/orchestrator/node-identity.ts +40 -0
  153. package/src/orchestrator/pid-liveness.ts +24 -24
  154. package/src/orchestrator/port-allocator.ts +91 -43
  155. package/src/orchestrator/state-store.ts +90 -90
  156. package/src/orchestrator/types.ts +141 -141
  157. package/src/owner/__tests__/owner-node-client.test.ts +194 -194
  158. package/src/owner/index.ts +12 -12
  159. package/src/owner/owner-node-client.ts +259 -233
  160. package/src/push/__tests__/push.test.ts +90 -90
  161. package/src/push/index.ts +146 -146
  162. package/src/server/__tests__/bus.test.ts +38 -38
  163. package/src/server/__tests__/error-handler.test.ts +118 -118
  164. package/src/server/__tests__/grants-admin-route.test.ts +73 -73
  165. package/src/server/__tests__/grants-route.test.ts +263 -189
  166. package/src/server/__tests__/nodes-route.test.ts +259 -259
  167. package/src/server/__tests__/origin-guard.test.ts +72 -72
  168. package/src/server/__tests__/publishers.test.ts +216 -216
  169. package/src/server/__tests__/server.smoke.test.ts +253 -253
  170. package/src/server/__tests__/settings-route.test.ts +194 -194
  171. package/src/server/__tests__/sse-route.test.ts +119 -119
  172. package/src/server/__tests__/static.test.ts +145 -145
  173. package/src/server/__tests__/status-route.test.ts +134 -134
  174. package/src/server/__tests__/strands-route.test.ts +233 -0
  175. package/src/server/error-handler.ts +178 -155
  176. package/src/server/events/bus.ts +42 -42
  177. package/src/server/events/sse-route.ts +81 -81
  178. package/src/server/events/types.ts +23 -22
  179. package/src/server/index.ts +267 -254
  180. package/src/server/origin-guard.ts +84 -84
  181. package/src/server/routes/grants-admin.ts +41 -41
  182. package/src/server/routes/grants.ts +210 -186
  183. package/src/server/routes/nat.ts +63 -63
  184. package/src/server/routes/nodes.ts +170 -170
  185. package/src/server/routes/settings.ts +123 -123
  186. package/src/server/routes/status.ts +118 -118
  187. package/src/server/routes/strands.ts +54 -0
  188. package/src/server/routes/trust-circle.ts +49 -49
  189. package/src/server/routes/update.ts +43 -43
  190. package/src/server/server.ts +122 -122
  191. package/src/server/settings-store.ts +37 -37
  192. package/src/server/static.ts +207 -207
  193. package/src/strands/__tests__/strand-service.test.ts +165 -0
  194. package/src/strands/index.ts +14 -0
  195. package/src/strands/strand-service.ts +135 -0
  196. package/src/strands/types.ts +102 -0
  197. package/src/update/__tests__/apply.test.ts +158 -158
  198. package/src/update/__tests__/manifest.test.ts +128 -128
  199. package/src/update/__tests__/release-key.test.ts +42 -42
  200. package/src/update/__tests__/sign.test.ts +78 -78
  201. package/src/update/__tests__/store.test.ts +81 -81
  202. package/src/update/__tests__/update-service.integration.test.ts +256 -256
  203. package/src/update/__tests__/version.test.ts +31 -31
  204. package/src/update/apply.ts +190 -190
  205. package/src/update/index.ts +341 -341
  206. package/src/update/release-key.ts +71 -71
  207. package/src/update/sign.ts +74 -74
  208. package/src/update/store.ts +101 -101
  209. package/src/update/types.ts +109 -109
  210. package/src/update/version.ts +80 -80
  211. package/dist/ui/assets/index-BlMXQPSw.js +0 -14
  212. package/dist/ui/assets/index-BlMXQPSw.js.map +0 -1
  213. package/dist/ui/assets/index-BwU5mJGF.css +0 -1
@@ -1,33 +1,33 @@
1
- /**
2
- * Tiny duration parser for invite TTLs.
3
- *
4
- * Accepts a single value+unit token: `30s`, `5m`, `24h`, `7d`, `2w`.
5
- * Whitespace is allowed around it. Bare numbers are treated as milliseconds.
6
- *
7
- * Returns the duration in milliseconds. Throws on unparseable input.
8
- */
9
- const UNIT_MULTIPLIERS: Record<string, number> = {
10
- ms: 1,
11
- s: 1000,
12
- m: 60 * 1000,
13
- h: 60 * 60 * 1000,
14
- d: 24 * 60 * 60 * 1000,
15
- w: 7 * 24 * 60 * 60 * 1000,
16
- };
17
-
18
- const DURATION_RE = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w)?$/;
19
-
20
- export function parseDuration(input: string): number {
21
- const trimmed = input.trim();
22
- const match = DURATION_RE.exec(trimmed);
23
- if (!match) {
24
- throw new Error(`Invalid duration: ${JSON.stringify(input)} (expected e.g. "24h", "7d", "30m")`);
25
- }
26
- const value = parseFloat(match[1]!);
27
- const unit = match[2] ?? 'ms';
28
- const multiplier = UNIT_MULTIPLIERS[unit];
29
- if (multiplier === undefined) {
30
- throw new Error(`Unknown duration unit: ${unit}`);
31
- }
32
- return Math.round(value * multiplier);
33
- }
1
+ /**
2
+ * Tiny duration parser for invite TTLs.
3
+ *
4
+ * Accepts a single value+unit token: `30s`, `5m`, `24h`, `7d`, `2w`.
5
+ * Whitespace is allowed around it. Bare numbers are treated as milliseconds.
6
+ *
7
+ * Returns the duration in milliseconds. Throws on unparseable input.
8
+ */
9
+ const UNIT_MULTIPLIERS: Record<string, number> = {
10
+ ms: 1,
11
+ s: 1000,
12
+ m: 60 * 1000,
13
+ h: 60 * 60 * 1000,
14
+ d: 24 * 60 * 60 * 1000,
15
+ w: 7 * 24 * 60 * 60 * 1000,
16
+ };
17
+
18
+ const DURATION_RE = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w)?$/;
19
+
20
+ export function parseDuration(input: string): number {
21
+ const trimmed = input.trim();
22
+ const match = DURATION_RE.exec(trimmed);
23
+ if (!match) {
24
+ throw new Error(`Invalid duration: ${JSON.stringify(input)} (expected e.g. "24h", "7d", "30m")`);
25
+ }
26
+ const value = parseFloat(match[1]!);
27
+ const unit = match[2] ?? 'ms';
28
+ const multiplier = UNIT_MULTIPLIERS[unit];
29
+ if (multiplier === undefined) {
30
+ throw new Error(`Unknown duration unit: ${unit}`);
31
+ }
32
+ return Math.round(value * multiplier);
33
+ }
package/src/auth/index.ts CHANGED
@@ -1,19 +1,21 @@
1
- /**
2
- * Trust-circle auth for cadre-host. See ./trust-circle.ts and ./types.ts.
3
- */
4
-
5
- export { TrustCircleService, createTrustCircleHandlers, DEFAULT_INVITE_TTL_MS } from './trust-circle.js';
6
- export type { TrustCircleServiceOptions, CadreNodeLike } from './trust-circle.js';
7
- export { TrustCircleStore } from './trust-circle-store.js';
8
- export { parseDuration } from './duration.js';
9
- export {
10
- TrustCircleError,
11
- } from './types.js';
12
- export type {
13
- TrustCircleMember,
14
- PendingInvite,
15
- TrustCircleFile,
16
- TrustCircleSnapshot,
17
- TrustCircleHandlers,
18
- TrustCircleErrorCode,
19
- } from './types.js';
1
+ /**
2
+ * Trust-circle auth for cadre-host. See ./trust-circle.ts and ./types.ts.
3
+ */
4
+
5
+ export { TrustCircleService, createTrustCircleHandlers, DEFAULT_INVITE_TTL_MS } from './trust-circle.js';
6
+ export type { TrustCircleServiceOptions, CadreNodeLike } from './trust-circle.js';
7
+ export { TrustCircleStore } from './trust-circle-store.js';
8
+ export { ensureSelfLabel, SELF_LABEL } from './self-label.js';
9
+ export type { EnsureSelfLabelOptions } from './self-label.js';
10
+ export { parseDuration } from './duration.js';
11
+ export {
12
+ TrustCircleError,
13
+ } from './types.js';
14
+ export type {
15
+ TrustCircleMember,
16
+ PendingInvite,
17
+ TrustCircleFile,
18
+ TrustCircleSnapshot,
19
+ TrustCircleHandlers,
20
+ TrustCircleErrorCode,
21
+ } from './types.js';
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Self-labelling for the trust-circle listing.
3
+ *
4
+ * `TrustCircleService.list()` shows the cadre's *authorized* membership, which
5
+ * deliberately excludes the node's own self-published row — a node's own
6
+ * address record isn't something an owner key vouched for. To keep the owner's
7
+ * own device visible in the listing, cadre-host records a local
8
+ * `self: true` label for it and `list()` splices that row back in.
9
+ *
10
+ * Writing that label is this module's job. Kept out of `bin/host.ts` so it is
11
+ * unit-testable without standing up the CLI.
12
+ */
13
+
14
+ import debug from 'debug';
15
+
16
+ import type { TrustCircleStore } from './trust-circle-store.js';
17
+
18
+ const log = debug('cadre:host:trust-circle-self');
19
+
20
+ /** Label written for the owner's own device when none exists yet. */
21
+ export const SELF_LABEL = 'This device';
22
+
23
+ export interface EnsureSelfLabelOptions {
24
+ /** Local labels store to write into. */
25
+ store: TrustCircleStore;
26
+ /** Resolves the owner node's peer ID; '' when the node isn't ready yet. */
27
+ getPeerId: () => Promise<string>;
28
+ /** Clock override for tests. */
29
+ now?: () => Date;
30
+ }
31
+
32
+ /**
33
+ * Record the owner node's own peer ID as a `self: true` local label.
34
+ *
35
+ * Idempotent: an existing row for that peer ID is left alone, so an admin's
36
+ * rename survives restarts. Stale `self` rows (a different peer ID — the node
37
+ * identity was replaced) are dropped, since `list()` splices every `self` row
38
+ * in unconditionally and would otherwise show a device that no longer exists.
39
+ *
40
+ * Returns the peer ID that is now labelled, or `undefined` when the node
41
+ * wasn't ready. Throws whatever `getPeerId` throws — callers treat a failure
42
+ * as best-effort (the next start heals it).
43
+ */
44
+ export async function ensureSelfLabel(opts: EnsureSelfLabelOptions): Promise<string | undefined> {
45
+ const { store, getPeerId } = opts;
46
+ const now = opts.now ?? (() => new Date());
47
+
48
+ const peerId = await getPeerId();
49
+ if (!peerId) {
50
+ log('owner node not ready — no self label written');
51
+ return undefined;
52
+ }
53
+
54
+ for (const member of store.listMembers()) {
55
+ if (member.self && member.peerId !== peerId) {
56
+ log('dropping stale self label for %s (current identity is %s)', member.peerId, peerId);
57
+ store.removeMember(member.peerId);
58
+ }
59
+ }
60
+
61
+ const existing = store.getMember(peerId);
62
+ if (!existing) {
63
+ store.addMember({ peerId, label: SELF_LABEL, addedAt: now().toISOString(), self: true });
64
+ log('labelled own device %s as "%s"', peerId, SELF_LABEL);
65
+ } else if (!existing.self) {
66
+ // Row predates self-labelling (or was written by a redemption). Stamp the
67
+ // flag, keeping the label: without it `list()` prunes the row, since the
68
+ // authorized set never contains self.
69
+ store.addMember({ ...existing, self: true });
70
+ log('stamped existing label for own device %s as self', peerId);
71
+ }
72
+
73
+ return peerId;
74
+ }
@@ -1,155 +1,155 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
- import { dirname, join } from 'node:path';
3
- import debug from 'debug';
4
-
5
- import type {
6
- PendingInvite,
7
- TrustCircleFile,
8
- TrustCircleMember,
9
- } from './types.js';
10
- import { TrustCircleError } from './types.js';
11
-
12
- const log = debug('cadre:host:trust-circle-store');
13
-
14
- const FILE_VERSION = 1;
15
-
16
- /**
17
- * Atomic JSON store for trust-circle.json. Mirrors the pattern in
18
- * `orchestrator/state-store.ts`: write to `<path>.tmp`, then rename.
19
- *
20
- * Concurrency assumption: only one cadre-host process owns a given rootDir
21
- * (the orchestrator already enforces this). No file-locking primitives.
22
- */
23
- export class TrustCircleStore {
24
- private readonly path: string;
25
- private cache: TrustCircleFile | null = null;
26
-
27
- constructor(rootDir: string) {
28
- mkdirSync(rootDir, { recursive: true });
29
- this.path = join(rootDir, 'trust-circle.json');
30
- }
31
-
32
- filePath(): string {
33
- return this.path;
34
- }
35
-
36
- /** Load (with caching). A missing file returns an empty store. */
37
- load(): TrustCircleFile {
38
- if (this.cache) return this.cache;
39
- if (!existsSync(this.path)) {
40
- this.cache = emptyFile();
41
- return this.cache;
42
- }
43
- let raw: string;
44
- try {
45
- raw = readFileSync(this.path, 'utf8');
46
- } catch (err) {
47
- throw new TrustCircleError(
48
- 'storage_error',
49
- `failed to read trust-circle file at ${this.path}: ${(err as Error).message}`,
50
- );
51
- }
52
- let parsed: unknown;
53
- try {
54
- parsed = JSON.parse(raw);
55
- } catch (err) {
56
- throw new TrustCircleError(
57
- 'storage_error',
58
- `trust-circle file at ${this.path} is not valid JSON: ${(err as Error).message}`,
59
- );
60
- }
61
- if (!isTrustCircleFile(parsed)) {
62
- throw new TrustCircleError(
63
- 'storage_error',
64
- `trust-circle file at ${this.path} has unexpected shape`,
65
- );
66
- }
67
- this.cache = parsed;
68
- return this.cache;
69
- }
70
-
71
- /** Persist the current state atomically (write then rename). */
72
- save(state: TrustCircleFile): void {
73
- mkdirSync(dirname(this.path), { recursive: true });
74
- const payload = JSON.stringify({ ...state, version: FILE_VERSION }, null, 2);
75
- const tmp = `${this.path}.tmp`;
76
- writeFileSync(tmp, payload, { encoding: 'utf8' });
77
- renameSync(tmp, this.path);
78
- this.cache = { ...state, version: FILE_VERSION };
79
- log('saved trust-circle (%d members, %d pending) to %s',
80
- Object.keys(state.members).length,
81
- Object.keys(state.pendingInvites).length,
82
- this.path);
83
- }
84
-
85
- // --- Member ops ---
86
-
87
- addMember(member: TrustCircleMember): void {
88
- const state = this.load();
89
- const { peerId, ...rest } = member;
90
- state.members[peerId] = rest;
91
- this.save(state);
92
- }
93
-
94
- removeMember(peerId: string): boolean {
95
- const state = this.load();
96
- if (!(peerId in state.members)) return false;
97
- delete state.members[peerId];
98
- this.save(state);
99
- return true;
100
- }
101
-
102
- getMember(peerId: string): TrustCircleMember | undefined {
103
- const state = this.load();
104
- const row = state.members[peerId];
105
- if (!row) return undefined;
106
- return { peerId, ...row };
107
- }
108
-
109
- listMembers(): TrustCircleMember[] {
110
- const state = this.load();
111
- return Object.entries(state.members).map(([peerId, row]) => ({ peerId, ...row }));
112
- }
113
-
114
- // --- Pending invite ops ---
115
-
116
- addPending(invite: PendingInvite): void {
117
- const state = this.load();
118
- const { token, ...rest } = invite;
119
- state.pendingInvites[token] = rest;
120
- this.save(state);
121
- }
122
-
123
- removePending(token: string): boolean {
124
- const state = this.load();
125
- if (!(token in state.pendingInvites)) return false;
126
- delete state.pendingInvites[token];
127
- this.save(state);
128
- return true;
129
- }
130
-
131
- getPending(token: string): PendingInvite | undefined {
132
- const state = this.load();
133
- const row = state.pendingInvites[token];
134
- if (!row) return undefined;
135
- return { token, ...row };
136
- }
137
-
138
- listPending(): PendingInvite[] {
139
- const state = this.load();
140
- return Object.entries(state.pendingInvites).map(([token, row]) => ({ token, ...row }));
141
- }
142
- }
143
-
144
- function emptyFile(): TrustCircleFile {
145
- return { version: FILE_VERSION, members: {}, pendingInvites: {} };
146
- }
147
-
148
- function isTrustCircleFile(v: unknown): v is TrustCircleFile {
149
- if (!v || typeof v !== 'object') return false;
150
- const obj = v as Record<string, unknown>;
151
- if (obj.version !== FILE_VERSION) return false;
152
- if (!obj.members || typeof obj.members !== 'object') return false;
153
- if (!obj.pendingInvites || typeof obj.pendingInvites !== 'object') return false;
154
- return true;
155
- }
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import debug from 'debug';
4
+
5
+ import type {
6
+ PendingInvite,
7
+ TrustCircleFile,
8
+ TrustCircleMember,
9
+ } from './types.js';
10
+ import { TrustCircleError } from './types.js';
11
+
12
+ const log = debug('cadre:host:trust-circle-store');
13
+
14
+ const FILE_VERSION = 1;
15
+
16
+ /**
17
+ * Atomic JSON store for trust-circle.json. Mirrors the pattern in
18
+ * `orchestrator/state-store.ts`: write to `<path>.tmp`, then rename.
19
+ *
20
+ * Concurrency assumption: only one cadre-host process owns a given rootDir
21
+ * (the orchestrator already enforces this). No file-locking primitives.
22
+ */
23
+ export class TrustCircleStore {
24
+ private readonly path: string;
25
+ private cache: TrustCircleFile | null = null;
26
+
27
+ constructor(rootDir: string) {
28
+ mkdirSync(rootDir, { recursive: true });
29
+ this.path = join(rootDir, 'trust-circle.json');
30
+ }
31
+
32
+ filePath(): string {
33
+ return this.path;
34
+ }
35
+
36
+ /** Load (with caching). A missing file returns an empty store. */
37
+ load(): TrustCircleFile {
38
+ if (this.cache) return this.cache;
39
+ if (!existsSync(this.path)) {
40
+ this.cache = emptyFile();
41
+ return this.cache;
42
+ }
43
+ let raw: string;
44
+ try {
45
+ raw = readFileSync(this.path, 'utf8');
46
+ } catch (err) {
47
+ throw new TrustCircleError(
48
+ 'storage_error',
49
+ `failed to read trust-circle file at ${this.path}: ${(err as Error).message}`,
50
+ );
51
+ }
52
+ let parsed: unknown;
53
+ try {
54
+ parsed = JSON.parse(raw);
55
+ } catch (err) {
56
+ throw new TrustCircleError(
57
+ 'storage_error',
58
+ `trust-circle file at ${this.path} is not valid JSON: ${(err as Error).message}`,
59
+ );
60
+ }
61
+ if (!isTrustCircleFile(parsed)) {
62
+ throw new TrustCircleError(
63
+ 'storage_error',
64
+ `trust-circle file at ${this.path} has unexpected shape`,
65
+ );
66
+ }
67
+ this.cache = parsed;
68
+ return this.cache;
69
+ }
70
+
71
+ /** Persist the current state atomically (write then rename). */
72
+ save(state: TrustCircleFile): void {
73
+ mkdirSync(dirname(this.path), { recursive: true });
74
+ const payload = JSON.stringify({ ...state, version: FILE_VERSION }, null, 2);
75
+ const tmp = `${this.path}.tmp`;
76
+ writeFileSync(tmp, payload, { encoding: 'utf8' });
77
+ renameSync(tmp, this.path);
78
+ this.cache = { ...state, version: FILE_VERSION };
79
+ log('saved trust-circle (%d members, %d pending) to %s',
80
+ Object.keys(state.members).length,
81
+ Object.keys(state.pendingInvites).length,
82
+ this.path);
83
+ }
84
+
85
+ // --- Member ops ---
86
+
87
+ addMember(member: TrustCircleMember): void {
88
+ const state = this.load();
89
+ const { peerId, ...rest } = member;
90
+ state.members[peerId] = rest;
91
+ this.save(state);
92
+ }
93
+
94
+ removeMember(peerId: string): boolean {
95
+ const state = this.load();
96
+ if (!(peerId in state.members)) return false;
97
+ delete state.members[peerId];
98
+ this.save(state);
99
+ return true;
100
+ }
101
+
102
+ getMember(peerId: string): TrustCircleMember | undefined {
103
+ const state = this.load();
104
+ const row = state.members[peerId];
105
+ if (!row) return undefined;
106
+ return { peerId, ...row };
107
+ }
108
+
109
+ listMembers(): TrustCircleMember[] {
110
+ const state = this.load();
111
+ return Object.entries(state.members).map(([peerId, row]) => ({ peerId, ...row }));
112
+ }
113
+
114
+ // --- Pending invite ops ---
115
+
116
+ addPending(invite: PendingInvite): void {
117
+ const state = this.load();
118
+ const { token, ...rest } = invite;
119
+ state.pendingInvites[token] = rest;
120
+ this.save(state);
121
+ }
122
+
123
+ removePending(token: string): boolean {
124
+ const state = this.load();
125
+ if (!(token in state.pendingInvites)) return false;
126
+ delete state.pendingInvites[token];
127
+ this.save(state);
128
+ return true;
129
+ }
130
+
131
+ getPending(token: string): PendingInvite | undefined {
132
+ const state = this.load();
133
+ const row = state.pendingInvites[token];
134
+ if (!row) return undefined;
135
+ return { token, ...row };
136
+ }
137
+
138
+ listPending(): PendingInvite[] {
139
+ const state = this.load();
140
+ return Object.entries(state.pendingInvites).map(([token, row]) => ({ token, ...row }));
141
+ }
142
+ }
143
+
144
+ function emptyFile(): TrustCircleFile {
145
+ return { version: FILE_VERSION, members: {}, pendingInvites: {} };
146
+ }
147
+
148
+ function isTrustCircleFile(v: unknown): v is TrustCircleFile {
149
+ if (!v || typeof v !== 'object') return false;
150
+ const obj = v as Record<string, unknown>;
151
+ if (obj.version !== FILE_VERSION) return false;
152
+ if (!obj.members || typeof obj.members !== 'object') return false;
153
+ if (!obj.pendingInvites || typeof obj.pendingInvites !== 'object') return false;
154
+ return true;
155
+ }
@@ -42,10 +42,22 @@ export interface CadreNodeLike {
42
42
  acceptPhone(options: { phonePeerId: string; token?: string }, issuedInvite?: CadreInvite): Promise<void>;
43
43
  removePeer(peerId: string): Promise<void>;
44
44
  encodeInvite(invite: CadreInvite): string;
45
- /** Enumerate the cadre's `CadrePeer` membership (over the admin channel). */
45
+ /**
46
+ * Enumerate the cadre's *addressable* peers (over the admin channel) —
47
+ * anyone with an address record, including devices no owner vouched for.
48
+ * Used only for {@link removeMember}, where "the row exists" is the point.
49
+ */
46
50
  listMembers(): Promise<Array<{ peerId: string; multiaddr: string | null }>>;
47
- /** Probe whether a peer is a `CadrePeer` member (over the admin channel). */
51
+ /** Probe whether a peer is *addressable* (over the admin channel). See {@link listMembers}. */
48
52
  isMember(peerId: string): Promise<boolean>;
53
+ /**
54
+ * Enumerate the cadre's *authorized* membership (over the admin channel) —
55
+ * devices an owner key vouched for. Excludes the node's own self-published
56
+ * row. This is the real membership test the trust-circle listing shows.
57
+ */
58
+ listAuthorizedMembers(): Promise<Array<{ peerId: string; multiaddr: string | null }>>;
59
+ /** Probe whether a peer is *authorized*. See {@link listAuthorizedMembers}. */
60
+ isAuthorizedMember(peerId: string): Promise<boolean>;
49
61
  }
50
62
 
51
63
  /**
@@ -212,6 +224,13 @@ export class TrustCircleService {
212
224
  /**
213
225
  * Remove an authorised member. Deletes the CadrePeer row and the local
214
226
  * label. Throws not_found when the peer is in neither place.
227
+ *
228
+ * NOTE: no special case for the host's own peer ID — the local UI hides the
229
+ * Remove button on the `self` row, but `DELETE /auth/members/<ownPeerId>`
230
+ * (or `cadre-host trust revoke <ownPeerId>`) will delete the node's own
231
+ * `CadrePeer` row. cadre-core re-registers self on node start, so a restart
232
+ * heals it. If that stops being true, or the removal path grows a
233
+ * non-loopback caller, guard `self` rows here.
215
234
  */
216
235
  async removeMember(peerId: string): Promise<void> {
217
236
  const inLocal = this.store.getMember(peerId);
@@ -240,10 +259,15 @@ export class TrustCircleService {
240
259
  }
241
260
 
242
261
  /**
243
- * UI snapshot. Joins the canonical CadrePeer list (fetched over the admin
262
+ * UI snapshot. Joins the *authorized* membership (fetched over the admin
244
263
  * channel) with local labels; prunes any orphan labels (peer is no longer
245
- * authorised). When the owner node is unreachable, degrades to the
246
- * local labels file so listing keeps working while the node is down.
264
+ * authorised). Addressable-but-unauthorized peers — devices that merely
265
+ * published an address record without an owner voucher — are deliberately
266
+ * excluded; this is the listing an operator uses to decide who belongs.
267
+ * The node's own self-published row is spliced back in from the local
268
+ * label, since the authorized set excludes self by design. When the owner
269
+ * node is unreachable, degrades to the local labels file so listing keeps
270
+ * working while the node is down.
247
271
  */
248
272
  async list(): Promise<TrustCircleSnapshot> {
249
273
  const labels = new Map<string, Omit<TrustCircleMember, 'peerId'>>();
@@ -256,17 +280,17 @@ export class TrustCircleService {
256
280
  // Consult the control DB over the admin channel. A node-unavailable error
257
281
  // is non-fatal — fall back to the local labels rather than 503-ing a
258
282
  // read-only listing.
259
- let controlMembers: Array<{ peerId: string }> | null;
283
+ let authorizedMembers: Array<{ peerId: string }> | null;
260
284
  try {
261
- controlMembers = await this.cadreNode.listMembers();
285
+ authorizedMembers = await this.cadreNode.listAuthorizedMembers();
262
286
  } catch (err) {
263
287
  if (!(err instanceof OwnerNodeUnavailableError)) throw err;
264
- controlMembers = null;
288
+ authorizedMembers = null;
265
289
  }
266
290
 
267
- if (controlMembers) {
291
+ if (authorizedMembers) {
268
292
  const seenPeerIds = new Set<string>();
269
- for (const { peerId } of controlMembers) {
293
+ for (const { peerId } of authorizedMembers) {
270
294
  seenPeerIds.add(peerId);
271
295
  const label = labels.get(peerId);
272
296
  members.push({
@@ -276,9 +300,17 @@ export class TrustCircleService {
276
300
  ...(label?.self ? { self: true } : {}),
277
301
  });
278
302
  }
279
- // Prune labels for peers that no longer exist in CadrePeer. Only when we
280
- // successfully consulted the node — otherwise a transient outage would
281
- // wipe labels.
303
+ // The authorized set excludes the node's own self-published row —
304
+ // splice it back in from the local label rather than dropping it.
305
+ for (const [peerId, row] of labels) {
306
+ if (row.self && !seenPeerIds.has(peerId)) {
307
+ seenPeerIds.add(peerId);
308
+ members.push({ peerId, ...row });
309
+ }
310
+ }
311
+ // Prune labels for peers that are neither authorized nor self. Only
312
+ // when we successfully consulted the node — otherwise a transient
313
+ // outage would wipe labels.
282
314
  for (const peerId of labels.keys()) {
283
315
  if (!seenPeerIds.has(peerId)) {
284
316
  this.store.removeMember(peerId);