@serfab/cadre-host 0.10.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 (138) hide show
  1. package/dist/server/static.js +38 -38
  2. package/dist/ui/assets/index-C-iks41M.js.map +1 -1
  3. package/dist/ui/index.html +12 -12
  4. package/package.json +4 -4
  5. package/service/cadre-host.service.tmpl +16 -16
  6. package/service/com.serfab.cadre-host.plist.tmpl +35 -35
  7. package/service/install-service.ps1 +98 -98
  8. package/service/uninstall-service.ps1 +19 -19
  9. package/src/__tests__/build-targets.test.ts +26 -26
  10. package/src/__tests__/cli-invite.smoke.test.ts +192 -192
  11. package/src/__tests__/cli-nat.smoke.test.ts +212 -212
  12. package/src/__tests__/cli.smoke.test.ts +46 -46
  13. package/src/__tests__/global-setup.ts +51 -51
  14. package/src/__tests__/host-owner.smoke.test.ts +123 -123
  15. package/src/__tests__/orchestrator-env-scrub.test.ts +140 -140
  16. package/src/__tests__/orchestrator-node-identity.test.ts +204 -204
  17. package/src/__tests__/orchestrator-owner.test.ts +198 -198
  18. package/src/__tests__/orchestrator-pin-keys.test.ts +153 -153
  19. package/src/__tests__/orchestrator-push.test.ts +145 -145
  20. package/src/__tests__/orchestrator.test.ts +951 -951
  21. package/src/auth/__tests__/duration.test.ts +28 -28
  22. package/src/auth/__tests__/self-label.test.ts +85 -85
  23. package/src/auth/__tests__/trust-circle-store.test.ts +115 -115
  24. package/src/auth/__tests__/trust-circle.test.ts +445 -445
  25. package/src/auth/duration.ts +33 -33
  26. package/src/auth/index.ts +21 -21
  27. package/src/auth/self-label.ts +74 -74
  28. package/src/auth/trust-circle-store.ts +155 -155
  29. package/src/auth/types.ts +99 -99
  30. package/src/donation/__tests__/donation-service.test.ts +1068 -1068
  31. package/src/donation/__tests__/donation-supervisor.test.ts +510 -510
  32. package/src/donation/__tests__/fake-orchestrator.test.ts +168 -168
  33. package/src/donation/__tests__/fake-orchestrator.ts +225 -225
  34. package/src/donation/__tests__/grant-service.test.ts +213 -213
  35. package/src/donation/__tests__/grant-store.test.ts +113 -113
  36. package/src/donation/donation-service.ts +962 -962
  37. package/src/donation/donation-store.ts +171 -171
  38. package/src/donation/donation-supervisor.ts +388 -388
  39. package/src/donation/grant-service.ts +200 -200
  40. package/src/donation/grant-store.ts +152 -152
  41. package/src/donation/index.ts +64 -64
  42. package/src/donation/types.ts +243 -243
  43. package/src/installer/__tests__/identity.test.ts +34 -34
  44. package/src/installer/__tests__/paths.test.ts +47 -47
  45. package/src/installer/__tests__/service-host.test.ts +62 -62
  46. package/src/installer/__tests__/wizard.test.ts +64 -64
  47. package/src/installer/identity.ts +49 -49
  48. package/src/installer/paths.ts +109 -109
  49. package/src/installer/platform.ts +27 -27
  50. package/src/installer/service-host/index.ts +21 -21
  51. package/src/installer/service-host/template.ts +21 -21
  52. package/src/installer/wizard.ts +103 -103
  53. package/src/nat/__tests__/address-resolver.test.ts +82 -82
  54. package/src/nat/__tests__/ddns-duckdns.test.ts +83 -83
  55. package/src/nat/__tests__/ddns-updater.test.ts +253 -253
  56. package/src/nat/__tests__/external-ip.test.ts +124 -124
  57. package/src/nat/__tests__/nat-service.test.ts +497 -497
  58. package/src/nat/__tests__/nat-store.test.ts +93 -93
  59. package/src/nat/__tests__/port-mapper.test.ts +191 -191
  60. package/src/nat/__tests__/reachability.test.ts +24 -24
  61. package/src/nat/__tests__/secrets.test.ts +178 -178
  62. package/src/nat/address-resolver.ts +51 -51
  63. package/src/nat/ddns/duckdns.ts +76 -76
  64. package/src/nat/ddns/index.ts +55 -55
  65. package/src/nat/ddns/updater.ts +243 -243
  66. package/src/nat/external-ip.ts +154 -154
  67. package/src/nat/index.ts +71 -71
  68. package/src/nat/nat-service.ts +501 -501
  69. package/src/nat/nat-store.ts +154 -154
  70. package/src/nat/port-mapper.ts +329 -329
  71. package/src/nat/reachability.ts +34 -34
  72. package/src/nat/secrets/file-store.ts +130 -130
  73. package/src/nat/secrets/index.ts +112 -112
  74. package/src/nat/secrets/keytar-store.ts +67 -67
  75. package/src/nat/types.ts +159 -159
  76. package/src/orchestrator/__tests__/node-identity.test.ts +62 -62
  77. package/src/orchestrator/host-process-orchestrator.ts +1133 -1133
  78. package/src/orchestrator/index.ts +10 -10
  79. package/src/orchestrator/log-rotator.ts +53 -53
  80. package/src/orchestrator/node-identity.ts +40 -40
  81. package/src/orchestrator/pid-liveness.ts +24 -24
  82. package/src/orchestrator/port-allocator.ts +91 -91
  83. package/src/orchestrator/state-store.ts +90 -90
  84. package/src/orchestrator/types.ts +141 -141
  85. package/src/owner/__tests__/owner-node-client.test.ts +194 -194
  86. package/src/owner/index.ts +12 -12
  87. package/src/owner/owner-node-client.ts +259 -259
  88. package/src/push/__tests__/push.test.ts +90 -90
  89. package/src/push/index.ts +146 -146
  90. package/src/server/__tests__/bus.test.ts +38 -38
  91. package/src/server/__tests__/error-handler.test.ts +118 -118
  92. package/src/server/__tests__/grants-admin-route.test.ts +73 -73
  93. package/src/server/__tests__/grants-route.test.ts +263 -263
  94. package/src/server/__tests__/nodes-route.test.ts +259 -259
  95. package/src/server/__tests__/origin-guard.test.ts +72 -72
  96. package/src/server/__tests__/publishers.test.ts +216 -216
  97. package/src/server/__tests__/server.smoke.test.ts +253 -253
  98. package/src/server/__tests__/settings-route.test.ts +194 -194
  99. package/src/server/__tests__/sse-route.test.ts +119 -119
  100. package/src/server/__tests__/static.test.ts +145 -145
  101. package/src/server/__tests__/status-route.test.ts +134 -134
  102. package/src/server/__tests__/strands-route.test.ts +233 -233
  103. package/src/server/error-handler.ts +178 -178
  104. package/src/server/events/bus.ts +42 -42
  105. package/src/server/events/sse-route.ts +81 -81
  106. package/src/server/events/types.ts +23 -23
  107. package/src/server/index.ts +267 -267
  108. package/src/server/origin-guard.ts +84 -84
  109. package/src/server/routes/grants-admin.ts +41 -41
  110. package/src/server/routes/grants.ts +210 -210
  111. package/src/server/routes/nat.ts +63 -63
  112. package/src/server/routes/nodes.ts +170 -170
  113. package/src/server/routes/settings.ts +123 -123
  114. package/src/server/routes/status.ts +118 -118
  115. package/src/server/routes/strands.ts +54 -54
  116. package/src/server/routes/trust-circle.ts +49 -49
  117. package/src/server/routes/update.ts +43 -43
  118. package/src/server/server.ts +122 -122
  119. package/src/server/settings-store.ts +37 -37
  120. package/src/server/static.ts +207 -207
  121. package/src/strands/__tests__/strand-service.test.ts +165 -165
  122. package/src/strands/index.ts +14 -14
  123. package/src/strands/strand-service.ts +135 -135
  124. package/src/strands/types.ts +102 -102
  125. package/src/update/__tests__/apply.test.ts +158 -158
  126. package/src/update/__tests__/manifest.test.ts +128 -128
  127. package/src/update/__tests__/release-key.test.ts +42 -42
  128. package/src/update/__tests__/sign.test.ts +78 -78
  129. package/src/update/__tests__/store.test.ts +81 -81
  130. package/src/update/__tests__/update-service.integration.test.ts +256 -256
  131. package/src/update/__tests__/version.test.ts +31 -31
  132. package/src/update/apply.ts +190 -190
  133. package/src/update/index.ts +341 -341
  134. package/src/update/release-key.ts +71 -71
  135. package/src/update/sign.ts +74 -74
  136. package/src/update/store.ts +101 -101
  137. package/src/update/types.ts +109 -109
  138. package/src/update/version.ts +80 -80
@@ -1,165 +1,165 @@
1
- /**
2
- * StrandService unit tests — a fake node, no HTTP.
3
- *
4
- * The two things this layer actually owns: id validation (which must never reach
5
- * the node) and the translation of the admin channel's single
6
- * `OwnerNodeUnavailableError` into a vocabulary the HTTP layer can map. The
7
- * confirmation *policy* is the node's and is not re-tested here — only that the
8
- * flag is forwarded verbatim.
9
- */
10
-
11
- import { describe, it, expect, beforeEach } from 'vitest';
12
-
13
- import { OwnerNodeUnavailableError } from '../../owner/owner-node-client.js';
14
- import { StrandService } from '../strand-service.js';
15
- import { StrandError } from '../types.js';
16
- import type { CadreNodeLike } from '../strand-service.js';
17
- import type { StrandListSnapshot, StrandRemovalResult } from '../types.js';
18
-
19
- interface FakeNode extends CadreNodeLike {
20
- calls: Array<{ strandId: string; confirm: boolean }>;
21
- listCalls: number;
22
- /** Thrown by both methods when set. */
23
- failWith?: unknown;
24
- }
25
-
26
- const SNAPSHOT: StrandListSnapshot = {
27
- strands: [
28
- { id: 'open-one', type: 'o', running: true, status: 'active' },
29
- { id: 'closed-one', type: 'c', running: false, status: null },
30
- ],
31
- controlConnections: 2,
32
- };
33
-
34
- function fakeNode(): FakeNode {
35
- const node: FakeNode = {
36
- calls: [],
37
- listCalls: 0,
38
- async listStrands() {
39
- node.listCalls++;
40
- if (node.failWith) throw node.failWith;
41
- return SNAPSHOT;
42
- },
43
- async removeStrand(strandId, opts) {
44
- node.calls.push({ strandId, confirm: opts.confirm });
45
- if (node.failWith) throw node.failWith;
46
- const result: StrandRemovalResult = {
47
- strandId,
48
- published: true,
49
- type: 'o',
50
- removed: true,
51
- alone: false,
52
- };
53
- return result;
54
- },
55
- };
56
- return node;
57
- }
58
-
59
- /** Await a call expected to reject, assert it is a StrandError, and hand it back. */
60
- async function catchStrandError(p: Promise<unknown>): Promise<StrandError> {
61
- const err = await p.then(() => undefined, (e: unknown) => e);
62
- expect(err).toBeInstanceOf(StrandError);
63
- return err as StrandError;
64
- }
65
-
66
- let node: FakeNode;
67
- let service: StrandService;
68
-
69
- beforeEach(() => {
70
- node = fakeNode();
71
- service = new StrandService({ cadreNode: node });
72
- });
73
-
74
- describe('StrandService.list', () => {
75
- it('passes the node snapshot through unchanged', async () => {
76
- await expect(service.list()).resolves.toEqual(SNAPSHOT);
77
- expect(node.listCalls).toBe(1);
78
- });
79
- });
80
-
81
- describe('StrandService.remove — id validation', () => {
82
- it.each([
83
- ['blank', ''],
84
- ['whitespace-only', ' '],
85
- ['tab/newline only', '\t\n'],
86
- ])('rejects a %s id with invalid_id and never calls the node', async (_label, id) => {
87
- await expect(service.remove(id, { confirm: false })).rejects.toMatchObject({
88
- name: 'StrandError',
89
- code: 'invalid_id',
90
- });
91
- expect(node.calls).toEqual([]);
92
- });
93
-
94
- it('forwards an id containing "/" rather than refusing it', async () => {
95
- // The whole chain carries it: Fastify decodes `%2F` into `params.id`,
96
- // `OwnerNodeClient` re-encodes it, and the admin channel splits on the still
97
- // -encoded segment and decodes it back. Refusing here would break the only
98
- // form that works. `strands-route.test.ts` pins the Fastify half.
99
- await service.remove('ns/strand', { confirm: true });
100
- expect(node.calls).toEqual([{ strandId: 'ns/strand', confirm: true }]);
101
- });
102
-
103
- it('trims a padded id before forwarding it', async () => {
104
- await service.remove(' spaced ', { confirm: false });
105
- expect(node.calls).toEqual([{ strandId: 'spaced', confirm: false }]);
106
- });
107
- });
108
-
109
- describe('StrandService.remove — confirmation forwarding', () => {
110
- it('forwards confirm: false as false', async () => {
111
- await service.remove('open-one', { confirm: false });
112
- expect(node.calls).toEqual([{ strandId: 'open-one', confirm: false }]);
113
- });
114
-
115
- it('forwards confirm: true as true', async () => {
116
- await service.remove('closed-one', { confirm: true });
117
- expect(node.calls).toEqual([{ strandId: 'closed-one', confirm: true }]);
118
- });
119
-
120
- it('does not retry a refused removal with confirmation added', async () => {
121
- node.failWith = new OwnerNodeUnavailableError('needs confirmation', 'confirmation_required');
122
- await expect(service.remove('closed-one', { confirm: false })).rejects.toBeInstanceOf(StrandError);
123
- // Exactly one attempt, and it carried the caller's flag.
124
- expect(node.calls).toEqual([{ strandId: 'closed-one', confirm: false }]);
125
- });
126
- });
127
-
128
- describe('StrandService — error translation', () => {
129
- const cases: Array<{ nodeCode: string | undefined; code: string; keepsMessage: boolean }> = [
130
- { nodeCode: 'confirmation_required', code: 'confirmation_required', keepsMessage: true },
131
- { nodeCode: 'bad_request', code: 'invalid_id', keepsMessage: true },
132
- { nodeCode: 'not_ready', code: 'node_unavailable', keepsMessage: false },
133
- { nodeCode: 'not_authorized', code: 'node_unavailable', keepsMessage: false },
134
- { nodeCode: undefined, code: 'node_unavailable', keepsMessage: false },
135
- { nodeCode: 'internal', code: 'internal', keepsMessage: true },
136
- { nodeCode: 'something_new', code: 'internal', keepsMessage: true },
137
- ];
138
-
139
- for (const { nodeCode, code, keepsMessage } of cases) {
140
- it(`maps nodeCode ${nodeCode ?? '(absent)'} → ${code}`, async () => {
141
- const message = `node said ${nodeCode ?? 'nothing'}`;
142
- node.failWith = new OwnerNodeUnavailableError(message, nodeCode);
143
- const err = await catchStrandError(service.remove('x', { confirm: false }));
144
- expect(err.code).toBe(code);
145
- if (keepsMessage) {
146
- expect(err.message).toBe(message);
147
- } else {
148
- // Wrapped, but the node's words survive inside.
149
- expect(err.message).toContain(message);
150
- }
151
- });
152
- }
153
-
154
- it('translates a transport failure (no nodeCode) on list() too', async () => {
155
- node.failWith = new OwnerNodeUnavailableError('Owner node unreachable: ECONNREFUSED');
156
- const err = await catchStrandError(service.list());
157
- expect(err.code).toBe('node_unavailable');
158
- });
159
-
160
- it('rethrows a non-owner-node error unchanged rather than dressing it as a strand error', async () => {
161
- const boom = new TypeError('something else broke');
162
- node.failWith = boom;
163
- await expect(service.list()).rejects.toBe(boom);
164
- });
165
- });
1
+ /**
2
+ * StrandService unit tests — a fake node, no HTTP.
3
+ *
4
+ * The two things this layer actually owns: id validation (which must never reach
5
+ * the node) and the translation of the admin channel's single
6
+ * `OwnerNodeUnavailableError` into a vocabulary the HTTP layer can map. The
7
+ * confirmation *policy* is the node's and is not re-tested here — only that the
8
+ * flag is forwarded verbatim.
9
+ */
10
+
11
+ import { describe, it, expect, beforeEach } from 'vitest';
12
+
13
+ import { OwnerNodeUnavailableError } from '../../owner/owner-node-client.js';
14
+ import { StrandService } from '../strand-service.js';
15
+ import { StrandError } from '../types.js';
16
+ import type { CadreNodeLike } from '../strand-service.js';
17
+ import type { StrandListSnapshot, StrandRemovalResult } from '../types.js';
18
+
19
+ interface FakeNode extends CadreNodeLike {
20
+ calls: Array<{ strandId: string; confirm: boolean }>;
21
+ listCalls: number;
22
+ /** Thrown by both methods when set. */
23
+ failWith?: unknown;
24
+ }
25
+
26
+ const SNAPSHOT: StrandListSnapshot = {
27
+ strands: [
28
+ { id: 'open-one', type: 'o', running: true, status: 'active' },
29
+ { id: 'closed-one', type: 'c', running: false, status: null },
30
+ ],
31
+ controlConnections: 2,
32
+ };
33
+
34
+ function fakeNode(): FakeNode {
35
+ const node: FakeNode = {
36
+ calls: [],
37
+ listCalls: 0,
38
+ async listStrands() {
39
+ node.listCalls++;
40
+ if (node.failWith) throw node.failWith;
41
+ return SNAPSHOT;
42
+ },
43
+ async removeStrand(strandId, opts) {
44
+ node.calls.push({ strandId, confirm: opts.confirm });
45
+ if (node.failWith) throw node.failWith;
46
+ const result: StrandRemovalResult = {
47
+ strandId,
48
+ published: true,
49
+ type: 'o',
50
+ removed: true,
51
+ alone: false,
52
+ };
53
+ return result;
54
+ },
55
+ };
56
+ return node;
57
+ }
58
+
59
+ /** Await a call expected to reject, assert it is a StrandError, and hand it back. */
60
+ async function catchStrandError(p: Promise<unknown>): Promise<StrandError> {
61
+ const err = await p.then(() => undefined, (e: unknown) => e);
62
+ expect(err).toBeInstanceOf(StrandError);
63
+ return err as StrandError;
64
+ }
65
+
66
+ let node: FakeNode;
67
+ let service: StrandService;
68
+
69
+ beforeEach(() => {
70
+ node = fakeNode();
71
+ service = new StrandService({ cadreNode: node });
72
+ });
73
+
74
+ describe('StrandService.list', () => {
75
+ it('passes the node snapshot through unchanged', async () => {
76
+ await expect(service.list()).resolves.toEqual(SNAPSHOT);
77
+ expect(node.listCalls).toBe(1);
78
+ });
79
+ });
80
+
81
+ describe('StrandService.remove — id validation', () => {
82
+ it.each([
83
+ ['blank', ''],
84
+ ['whitespace-only', ' '],
85
+ ['tab/newline only', '\t\n'],
86
+ ])('rejects a %s id with invalid_id and never calls the node', async (_label, id) => {
87
+ await expect(service.remove(id, { confirm: false })).rejects.toMatchObject({
88
+ name: 'StrandError',
89
+ code: 'invalid_id',
90
+ });
91
+ expect(node.calls).toEqual([]);
92
+ });
93
+
94
+ it('forwards an id containing "/" rather than refusing it', async () => {
95
+ // The whole chain carries it: Fastify decodes `%2F` into `params.id`,
96
+ // `OwnerNodeClient` re-encodes it, and the admin channel splits on the still
97
+ // -encoded segment and decodes it back. Refusing here would break the only
98
+ // form that works. `strands-route.test.ts` pins the Fastify half.
99
+ await service.remove('ns/strand', { confirm: true });
100
+ expect(node.calls).toEqual([{ strandId: 'ns/strand', confirm: true }]);
101
+ });
102
+
103
+ it('trims a padded id before forwarding it', async () => {
104
+ await service.remove(' spaced ', { confirm: false });
105
+ expect(node.calls).toEqual([{ strandId: 'spaced', confirm: false }]);
106
+ });
107
+ });
108
+
109
+ describe('StrandService.remove — confirmation forwarding', () => {
110
+ it('forwards confirm: false as false', async () => {
111
+ await service.remove('open-one', { confirm: false });
112
+ expect(node.calls).toEqual([{ strandId: 'open-one', confirm: false }]);
113
+ });
114
+
115
+ it('forwards confirm: true as true', async () => {
116
+ await service.remove('closed-one', { confirm: true });
117
+ expect(node.calls).toEqual([{ strandId: 'closed-one', confirm: true }]);
118
+ });
119
+
120
+ it('does not retry a refused removal with confirmation added', async () => {
121
+ node.failWith = new OwnerNodeUnavailableError('needs confirmation', 'confirmation_required');
122
+ await expect(service.remove('closed-one', { confirm: false })).rejects.toBeInstanceOf(StrandError);
123
+ // Exactly one attempt, and it carried the caller's flag.
124
+ expect(node.calls).toEqual([{ strandId: 'closed-one', confirm: false }]);
125
+ });
126
+ });
127
+
128
+ describe('StrandService — error translation', () => {
129
+ const cases: Array<{ nodeCode: string | undefined; code: string; keepsMessage: boolean }> = [
130
+ { nodeCode: 'confirmation_required', code: 'confirmation_required', keepsMessage: true },
131
+ { nodeCode: 'bad_request', code: 'invalid_id', keepsMessage: true },
132
+ { nodeCode: 'not_ready', code: 'node_unavailable', keepsMessage: false },
133
+ { nodeCode: 'not_authorized', code: 'node_unavailable', keepsMessage: false },
134
+ { nodeCode: undefined, code: 'node_unavailable', keepsMessage: false },
135
+ { nodeCode: 'internal', code: 'internal', keepsMessage: true },
136
+ { nodeCode: 'something_new', code: 'internal', keepsMessage: true },
137
+ ];
138
+
139
+ for (const { nodeCode, code, keepsMessage } of cases) {
140
+ it(`maps nodeCode ${nodeCode ?? '(absent)'} → ${code}`, async () => {
141
+ const message = `node said ${nodeCode ?? 'nothing'}`;
142
+ node.failWith = new OwnerNodeUnavailableError(message, nodeCode);
143
+ const err = await catchStrandError(service.remove('x', { confirm: false }));
144
+ expect(err.code).toBe(code);
145
+ if (keepsMessage) {
146
+ expect(err.message).toBe(message);
147
+ } else {
148
+ // Wrapped, but the node's words survive inside.
149
+ expect(err.message).toContain(message);
150
+ }
151
+ });
152
+ }
153
+
154
+ it('translates a transport failure (no nodeCode) on list() too', async () => {
155
+ node.failWith = new OwnerNodeUnavailableError('Owner node unreachable: ECONNREFUSED');
156
+ const err = await catchStrandError(service.list());
157
+ expect(err.code).toBe('node_unavailable');
158
+ });
159
+
160
+ it('rethrows a non-owner-node error unchanged rather than dressing it as a strand error', async () => {
161
+ const boom = new TypeError('something else broke');
162
+ node.failWith = boom;
163
+ await expect(service.list()).rejects.toBe(boom);
164
+ });
165
+ });
@@ -1,14 +1,14 @@
1
- /**
2
- * Strand management for cadre-host. See ./strand-service.ts and ./types.ts.
3
- */
4
-
5
- export { StrandService, createStrandHandlers } from './strand-service.js';
6
- export type { StrandServiceOptions, CadreNodeLike } from './strand-service.js';
7
- export { StrandError } from './types.js';
8
- export type {
9
- StrandSummary,
10
- StrandListSnapshot,
11
- StrandRemovalResult,
12
- StrandHandlers,
13
- StrandErrorCode,
14
- } from './types.js';
1
+ /**
2
+ * Strand management for cadre-host. See ./strand-service.ts and ./types.ts.
3
+ */
4
+
5
+ export { StrandService, createStrandHandlers } from './strand-service.js';
6
+ export type { StrandServiceOptions, CadreNodeLike } from './strand-service.js';
7
+ export { StrandError } from './types.js';
8
+ export type {
9
+ StrandSummary,
10
+ StrandListSnapshot,
11
+ StrandRemovalResult,
12
+ StrandHandlers,
13
+ StrandErrorCode,
14
+ } from './types.js';
@@ -1,135 +1,135 @@
1
- import debug from 'debug';
2
-
3
- import { OwnerNodeUnavailableError } from '../owner/owner-node-client.js';
4
-
5
- import type {
6
- StrandHandlers,
7
- StrandListSnapshot,
8
- StrandRemovalResult,
9
- } from './types.js';
10
- import { StrandError } from './types.js';
11
-
12
- const log = debug('cadre:host:strands');
13
-
14
- /**
15
- * Minimal slice of the owner node that StrandService uses. Declared here (rather
16
- * than reaching into `OwnerNodeClient`) so unit tests can inject a fake without
17
- * standing up an admin channel — the third such trimmed interface the client
18
- * satisfies, alongside the trust-circle and NAT ones.
19
- */
20
- export interface CadreNodeLike {
21
- listStrands(): Promise<StrandListSnapshot>;
22
- removeStrand(strandId: string, opts: { confirm: boolean }): Promise<StrandRemovalResult>;
23
- }
24
-
25
- /** Constructor options. */
26
- export interface StrandServiceOptions {
27
- /** The owner node — provides listStrands / removeStrand over the admin channel. */
28
- cadreNode: CadreNodeLike;
29
- }
30
-
31
- /**
32
- * StrandService — validation and error translation over the owner node's strand
33
- * admin routes.
34
- *
35
- * It owns no state and makes no policy. In particular it does NOT decide whether a
36
- * closed strand needs confirmation: it never reads the row, so it could only guess.
37
- * The node enforces that rule and answers `confirmation_required`; this layer
38
- * forwards the caller's flag verbatim and surfaces the refusal as a distinct code
39
- * so the UI can raise the right dialog.
40
- */
41
- export class StrandService {
42
- private readonly cadreNode: CadreNodeLike;
43
-
44
- constructor(opts: StrandServiceOptions) {
45
- this.cadreNode = opts.cadreNode;
46
- }
47
-
48
- /** This party's strands, plus the node's current control-connection count. */
49
- async list(): Promise<StrandListSnapshot> {
50
- return await this.cadreNode.listStrands().catch((err: unknown) => toDomainError(err));
51
- }
52
-
53
- /**
54
- * Remove this party's participation in one strand.
55
- *
56
- * `confirm` is forwarded exactly as given — never defaulted to true, never
57
- * re-sent as true after a refusal. A closed strand's row carries this party's
58
- * membership key for that network and is stored nowhere else, so an automatic
59
- * retry would destroy it on the caller's behalf.
60
- */
61
- async remove(rawId: string, opts: { confirm: boolean }): Promise<StrandRemovalResult> {
62
- const strandId = validateStrandId(rawId);
63
- log('remove %s (confirm=%s)', strandId, opts.confirm);
64
- return await this.cadreNode
65
- .removeStrand(strandId, { confirm: opts.confirm })
66
- .catch((err: unknown) => toDomainError(err));
67
- }
68
- }
69
-
70
- /**
71
- * Trim and reject an id this surface cannot act on. Blank is the only such id.
72
- *
73
- * A `/` is deliberately NOT refused. `/api/strands/:id` is one path segment, but a
74
- * caller that percent-encodes the id reaches this layer with the `/` restored
75
- * (Fastify decodes `params`), `OwnerNodeClient` re-encodes it, and the admin channel
76
- * splits on the still-encoded `%2F` and decodes it back — so the whole chain carries
77
- * it. Refusing here would break the only form that works, while doing nothing about
78
- * an UNencoded `/`, which never reaches this handler at all (the router 404s it).
79
- */
80
- function validateStrandId(rawId: string): string {
81
- const strandId = typeof rawId === 'string' ? rawId.trim() : '';
82
- if (!strandId) {
83
- throw new StrandError('invalid_id', 'A strand id is required');
84
- }
85
- return strandId;
86
- }
87
-
88
- /**
89
- * Translate an owner-node failure into the strand error vocabulary.
90
- *
91
- * `OwnerNodeUnavailableError` is thrown for *every* non-ok admin response, not only
92
- * for a node that is down — so read `nodeCode` first and fall back to
93
- * `node_unavailable` only when nothing better fits. Reporting a 428 as "your node is
94
- * down" would be actively misleading.
95
- *
96
- * Declared to return `never` so callers can `.catch((err) => toDomainError(err))`.
97
- *
98
- * NOTE: the trust-circle and NAT services translate the SAME error blanket-style —
99
- * every `OwnerNodeUnavailableError` becomes `node_unavailable` — because neither has
100
- * a code worth distinguishing yet. If a second surface ever needs a code-aware
101
- * mapping, hoist this switch into a shared owner-error translator instead of growing
102
- * a third copy.
103
- */
104
- function toDomainError(err: unknown): never {
105
- if (!(err instanceof OwnerNodeUnavailableError)) {
106
- throw err instanceof Error ? err : new Error(String(err));
107
- }
108
- switch (err.nodeCode) {
109
- case 'confirmation_required':
110
- throw new StrandError('confirmation_required', err.message);
111
- case 'bad_request':
112
- throw new StrandError('invalid_id', err.message);
113
- case undefined:
114
- case 'not_ready':
115
- case 'not_authorized':
116
- throw new StrandError('node_unavailable', `Owner node unavailable: ${err.message}`);
117
- default:
118
- throw new StrandError('internal', err.message);
119
- }
120
- }
121
-
122
- /**
123
- * Wrap a StrandService into the typed handler shape the local UI server mounts.
124
- * Errors propagate as StrandError; `server/error-handler.ts` maps `.code` → status.
125
- */
126
- export function createStrandHandlers(service: StrandService): StrandHandlers {
127
- return {
128
- async listStrands() {
129
- return await service.list();
130
- },
131
- async removeStrand(strandId, opts) {
132
- return await service.remove(strandId, { confirm: opts.confirm === true });
133
- },
134
- };
135
- }
1
+ import debug from 'debug';
2
+
3
+ import { OwnerNodeUnavailableError } from '../owner/owner-node-client.js';
4
+
5
+ import type {
6
+ StrandHandlers,
7
+ StrandListSnapshot,
8
+ StrandRemovalResult,
9
+ } from './types.js';
10
+ import { StrandError } from './types.js';
11
+
12
+ const log = debug('cadre:host:strands');
13
+
14
+ /**
15
+ * Minimal slice of the owner node that StrandService uses. Declared here (rather
16
+ * than reaching into `OwnerNodeClient`) so unit tests can inject a fake without
17
+ * standing up an admin channel — the third such trimmed interface the client
18
+ * satisfies, alongside the trust-circle and NAT ones.
19
+ */
20
+ export interface CadreNodeLike {
21
+ listStrands(): Promise<StrandListSnapshot>;
22
+ removeStrand(strandId: string, opts: { confirm: boolean }): Promise<StrandRemovalResult>;
23
+ }
24
+
25
+ /** Constructor options. */
26
+ export interface StrandServiceOptions {
27
+ /** The owner node — provides listStrands / removeStrand over the admin channel. */
28
+ cadreNode: CadreNodeLike;
29
+ }
30
+
31
+ /**
32
+ * StrandService — validation and error translation over the owner node's strand
33
+ * admin routes.
34
+ *
35
+ * It owns no state and makes no policy. In particular it does NOT decide whether a
36
+ * closed strand needs confirmation: it never reads the row, so it could only guess.
37
+ * The node enforces that rule and answers `confirmation_required`; this layer
38
+ * forwards the caller's flag verbatim and surfaces the refusal as a distinct code
39
+ * so the UI can raise the right dialog.
40
+ */
41
+ export class StrandService {
42
+ private readonly cadreNode: CadreNodeLike;
43
+
44
+ constructor(opts: StrandServiceOptions) {
45
+ this.cadreNode = opts.cadreNode;
46
+ }
47
+
48
+ /** This party's strands, plus the node's current control-connection count. */
49
+ async list(): Promise<StrandListSnapshot> {
50
+ return await this.cadreNode.listStrands().catch((err: unknown) => toDomainError(err));
51
+ }
52
+
53
+ /**
54
+ * Remove this party's participation in one strand.
55
+ *
56
+ * `confirm` is forwarded exactly as given — never defaulted to true, never
57
+ * re-sent as true after a refusal. A closed strand's row carries this party's
58
+ * membership key for that network and is stored nowhere else, so an automatic
59
+ * retry would destroy it on the caller's behalf.
60
+ */
61
+ async remove(rawId: string, opts: { confirm: boolean }): Promise<StrandRemovalResult> {
62
+ const strandId = validateStrandId(rawId);
63
+ log('remove %s (confirm=%s)', strandId, opts.confirm);
64
+ return await this.cadreNode
65
+ .removeStrand(strandId, { confirm: opts.confirm })
66
+ .catch((err: unknown) => toDomainError(err));
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Trim and reject an id this surface cannot act on. Blank is the only such id.
72
+ *
73
+ * A `/` is deliberately NOT refused. `/api/strands/:id` is one path segment, but a
74
+ * caller that percent-encodes the id reaches this layer with the `/` restored
75
+ * (Fastify decodes `params`), `OwnerNodeClient` re-encodes it, and the admin channel
76
+ * splits on the still-encoded `%2F` and decodes it back — so the whole chain carries
77
+ * it. Refusing here would break the only form that works, while doing nothing about
78
+ * an UNencoded `/`, which never reaches this handler at all (the router 404s it).
79
+ */
80
+ function validateStrandId(rawId: string): string {
81
+ const strandId = typeof rawId === 'string' ? rawId.trim() : '';
82
+ if (!strandId) {
83
+ throw new StrandError('invalid_id', 'A strand id is required');
84
+ }
85
+ return strandId;
86
+ }
87
+
88
+ /**
89
+ * Translate an owner-node failure into the strand error vocabulary.
90
+ *
91
+ * `OwnerNodeUnavailableError` is thrown for *every* non-ok admin response, not only
92
+ * for a node that is down — so read `nodeCode` first and fall back to
93
+ * `node_unavailable` only when nothing better fits. Reporting a 428 as "your node is
94
+ * down" would be actively misleading.
95
+ *
96
+ * Declared to return `never` so callers can `.catch((err) => toDomainError(err))`.
97
+ *
98
+ * NOTE: the trust-circle and NAT services translate the SAME error blanket-style —
99
+ * every `OwnerNodeUnavailableError` becomes `node_unavailable` — because neither has
100
+ * a code worth distinguishing yet. If a second surface ever needs a code-aware
101
+ * mapping, hoist this switch into a shared owner-error translator instead of growing
102
+ * a third copy.
103
+ */
104
+ function toDomainError(err: unknown): never {
105
+ if (!(err instanceof OwnerNodeUnavailableError)) {
106
+ throw err instanceof Error ? err : new Error(String(err));
107
+ }
108
+ switch (err.nodeCode) {
109
+ case 'confirmation_required':
110
+ throw new StrandError('confirmation_required', err.message);
111
+ case 'bad_request':
112
+ throw new StrandError('invalid_id', err.message);
113
+ case undefined:
114
+ case 'not_ready':
115
+ case 'not_authorized':
116
+ throw new StrandError('node_unavailable', `Owner node unavailable: ${err.message}`);
117
+ default:
118
+ throw new StrandError('internal', err.message);
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Wrap a StrandService into the typed handler shape the local UI server mounts.
124
+ * Errors propagate as StrandError; `server/error-handler.ts` maps `.code` → status.
125
+ */
126
+ export function createStrandHandlers(service: StrandService): StrandHandlers {
127
+ return {
128
+ async listStrands() {
129
+ return await service.list();
130
+ },
131
+ async removeStrand(strandId, opts) {
132
+ return await service.remove(strandId, { confirm: opts.confirm === true });
133
+ },
134
+ };
135
+ }