@serfab/cadre-host 0.10.0 → 0.12.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 (158) hide show
  1. package/README.md +406 -296
  2. package/dist/bin/host.d.ts +11 -7
  3. package/dist/bin/host.js +40 -12
  4. package/dist/bin/host.js.map +1 -1
  5. package/dist/installer/config.d.ts +4 -4
  6. package/dist/installer/config.js +5 -39
  7. package/dist/installer/config.js.map +1 -1
  8. package/dist/installer/identity.d.ts +8 -1
  9. package/dist/installer/identity.js +8 -1
  10. package/dist/installer/identity.js.map +1 -1
  11. package/dist/orchestrator/host-process-orchestrator.d.ts +2 -2
  12. package/dist/orchestrator/host-process-orchestrator.js +9 -4
  13. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  14. package/dist/server/settings-store.d.ts +1 -1
  15. package/dist/server/settings-store.js +5 -1
  16. package/dist/server/settings-store.js.map +1 -1
  17. package/dist/server/static.js +38 -38
  18. package/dist/ui/assets/index-C-iks41M.js.map +1 -1
  19. package/dist/ui/index.html +12 -12
  20. package/package.json +4 -4
  21. package/service/cadre-host.service.tmpl +16 -16
  22. package/service/com.serfab.cadre-host.plist.tmpl +35 -35
  23. package/service/install-service.ps1 +98 -98
  24. package/service/uninstall-service.ps1 +19 -19
  25. package/src/__tests__/build-targets.test.ts +26 -26
  26. package/src/__tests__/cli-invite.smoke.test.ts +192 -192
  27. package/src/__tests__/cli-nat.smoke.test.ts +212 -212
  28. package/src/__tests__/cli.smoke.test.ts +51 -46
  29. package/src/__tests__/global-setup.ts +56 -51
  30. package/src/__tests__/host-owner.smoke.test.ts +123 -123
  31. package/src/__tests__/orchestrator-env-scrub.test.ts +140 -140
  32. package/src/__tests__/orchestrator-node-identity.test.ts +5 -5
  33. package/src/__tests__/orchestrator-owner.test.ts +198 -198
  34. package/src/__tests__/orchestrator-pin-keys.test.ts +153 -153
  35. package/src/__tests__/orchestrator-push.test.ts +145 -145
  36. package/src/__tests__/orchestrator.test.ts +951 -951
  37. package/src/auth/__tests__/duration.test.ts +28 -28
  38. package/src/auth/__tests__/self-label.test.ts +85 -85
  39. package/src/auth/__tests__/trust-circle-store.test.ts +115 -115
  40. package/src/auth/__tests__/trust-circle.test.ts +445 -445
  41. package/src/auth/duration.ts +33 -33
  42. package/src/auth/index.ts +21 -21
  43. package/src/auth/self-label.ts +74 -74
  44. package/src/auth/trust-circle-store.ts +155 -155
  45. package/src/auth/types.ts +99 -99
  46. package/src/bin/__tests__/cli-reference.test.ts +167 -0
  47. package/src/bin/host.ts +1326 -1299
  48. package/src/donation/__tests__/donation-service.test.ts +1068 -1068
  49. package/src/donation/__tests__/donation-supervisor.test.ts +510 -510
  50. package/src/donation/__tests__/fake-orchestrator.test.ts +168 -168
  51. package/src/donation/__tests__/fake-orchestrator.ts +225 -225
  52. package/src/donation/__tests__/grant-service.test.ts +213 -213
  53. package/src/donation/__tests__/grant-store.test.ts +113 -113
  54. package/src/donation/donation-service.ts +962 -962
  55. package/src/donation/donation-store.ts +171 -171
  56. package/src/donation/donation-supervisor.ts +388 -388
  57. package/src/donation/grant-service.ts +200 -200
  58. package/src/donation/grant-store.ts +152 -152
  59. package/src/donation/index.ts +64 -64
  60. package/src/donation/types.ts +243 -243
  61. package/src/installer/__tests__/config.test.ts +134 -112
  62. package/src/installer/__tests__/identity.test.ts +34 -34
  63. package/src/installer/__tests__/paths.test.ts +47 -47
  64. package/src/installer/__tests__/service-host.test.ts +62 -62
  65. package/src/installer/__tests__/wizard.test.ts +64 -64
  66. package/src/installer/config.ts +5 -43
  67. package/src/installer/identity.ts +56 -49
  68. package/src/installer/paths.ts +109 -109
  69. package/src/installer/platform.ts +27 -27
  70. package/src/installer/service-host/index.ts +21 -21
  71. package/src/installer/service-host/template.ts +21 -21
  72. package/src/installer/wizard.ts +103 -103
  73. package/src/nat/__tests__/address-resolver.test.ts +82 -82
  74. package/src/nat/__tests__/ddns-duckdns.test.ts +83 -83
  75. package/src/nat/__tests__/ddns-updater.test.ts +253 -253
  76. package/src/nat/__tests__/external-ip.test.ts +124 -124
  77. package/src/nat/__tests__/nat-service.test.ts +18 -0
  78. package/src/nat/__tests__/nat-store.test.ts +93 -93
  79. package/src/nat/__tests__/port-mapper.test.ts +191 -191
  80. package/src/nat/__tests__/reachability.test.ts +24 -24
  81. package/src/nat/__tests__/secrets.test.ts +178 -178
  82. package/src/nat/address-resolver.ts +51 -51
  83. package/src/nat/ddns/duckdns.ts +76 -76
  84. package/src/nat/ddns/index.ts +55 -55
  85. package/src/nat/ddns/updater.ts +243 -243
  86. package/src/nat/external-ip.ts +154 -154
  87. package/src/nat/index.ts +71 -71
  88. package/src/nat/nat-service.ts +501 -501
  89. package/src/nat/nat-store.ts +154 -154
  90. package/src/nat/port-mapper.ts +329 -329
  91. package/src/nat/reachability.ts +34 -34
  92. package/src/nat/secrets/file-store.ts +130 -130
  93. package/src/nat/secrets/index.ts +112 -112
  94. package/src/nat/secrets/keytar-store.ts +67 -67
  95. package/src/nat/types.ts +159 -159
  96. package/src/orchestrator/__tests__/node-identity.test.ts +62 -62
  97. package/src/orchestrator/host-process-orchestrator.ts +9 -4
  98. package/src/orchestrator/index.ts +10 -10
  99. package/src/orchestrator/log-rotator.ts +53 -53
  100. package/src/orchestrator/node-identity.ts +40 -40
  101. package/src/orchestrator/pid-liveness.ts +24 -24
  102. package/src/orchestrator/port-allocator.ts +91 -91
  103. package/src/orchestrator/state-store.ts +90 -90
  104. package/src/orchestrator/types.ts +141 -141
  105. package/src/owner/__tests__/owner-node-client.test.ts +194 -194
  106. package/src/owner/index.ts +12 -12
  107. package/src/owner/owner-node-client.ts +259 -259
  108. package/src/push/__tests__/push.test.ts +90 -90
  109. package/src/push/index.ts +146 -146
  110. package/src/server/__tests__/bus.test.ts +38 -38
  111. package/src/server/__tests__/error-handler.test.ts +118 -118
  112. package/src/server/__tests__/grants-admin-route.test.ts +73 -73
  113. package/src/server/__tests__/grants-route.test.ts +263 -263
  114. package/src/server/__tests__/nodes-route.test.ts +259 -259
  115. package/src/server/__tests__/origin-guard.test.ts +72 -72
  116. package/src/server/__tests__/publishers.test.ts +216 -216
  117. package/src/server/__tests__/server.smoke.test.ts +253 -253
  118. package/src/server/__tests__/settings-route.test.ts +195 -194
  119. package/src/server/__tests__/sse-route.test.ts +119 -119
  120. package/src/server/__tests__/static.test.ts +145 -145
  121. package/src/server/__tests__/status-route.test.ts +134 -134
  122. package/src/server/__tests__/strands-route.test.ts +233 -233
  123. package/src/server/error-handler.ts +178 -178
  124. package/src/server/events/bus.ts +42 -42
  125. package/src/server/events/sse-route.ts +81 -81
  126. package/src/server/events/types.ts +23 -23
  127. package/src/server/index.ts +267 -267
  128. package/src/server/origin-guard.ts +84 -84
  129. package/src/server/routes/grants-admin.ts +41 -41
  130. package/src/server/routes/grants.ts +210 -210
  131. package/src/server/routes/nat.ts +63 -63
  132. package/src/server/routes/nodes.ts +170 -170
  133. package/src/server/routes/settings.ts +123 -123
  134. package/src/server/routes/status.ts +118 -118
  135. package/src/server/routes/strands.ts +54 -54
  136. package/src/server/routes/trust-circle.ts +49 -49
  137. package/src/server/routes/update.ts +43 -43
  138. package/src/server/server.ts +122 -122
  139. package/src/server/settings-store.ts +5 -1
  140. package/src/server/static.ts +207 -207
  141. package/src/strands/__tests__/strand-service.test.ts +165 -165
  142. package/src/strands/index.ts +14 -14
  143. package/src/strands/strand-service.ts +135 -135
  144. package/src/strands/types.ts +102 -102
  145. package/src/update/__tests__/apply.test.ts +158 -158
  146. package/src/update/__tests__/manifest.test.ts +128 -128
  147. package/src/update/__tests__/release-key.test.ts +42 -42
  148. package/src/update/__tests__/sign.test.ts +78 -78
  149. package/src/update/__tests__/store.test.ts +81 -81
  150. package/src/update/__tests__/update-service.integration.test.ts +256 -256
  151. package/src/update/__tests__/version.test.ts +31 -31
  152. package/src/update/apply.ts +190 -190
  153. package/src/update/index.ts +341 -341
  154. package/src/update/release-key.ts +71 -71
  155. package/src/update/sign.ts +74 -74
  156. package/src/update/store.ts +101 -101
  157. package/src/update/types.ts +109 -109
  158. package/src/update/version.ts +80 -80
@@ -1,178 +1,178 @@
1
- /**
2
- * Fastify error handler — translates known typed errors to stable HTTP status
3
- * codes and uniform `{ ok: false, error: { code, message } }` payloads.
4
- *
5
- * Codes (cross-referenced with `auth/types.ts`, `nat/types.ts`, `strands/types.ts`,
6
- * `update/types.ts`):
7
- * - TrustCircleError
8
- * invalid_label, invalid_token → 400
9
- * not_found, already_redeemed → 404
10
- * expired → 410
11
- * node_unavailable → 503
12
- * storage_error → 500
13
- * - NatError
14
- * invalid_config, ddns_provider_unknown,
15
- * ddns_credentials_missing → 400
16
- * secrets_unavailable, storage_error,
17
- * mapping_failed, router_unreachable,
18
- * ip_detection_failed, ddns_update_failed → 500
19
- * node_unavailable → 503
20
- * - StrandError
21
- * invalid_id → 400
22
- * confirmation_required → 428
23
- * node_unavailable → 503
24
- * internal → 500
25
- * - UpdateErrorException
26
- * manifest_invalid, no_update_available,
27
- * min_previous_version → 400
28
- * apply_in_progress → 409
29
- * signature_invalid, unsupported_state_version,
30
- * apply_failed, rollback_failed, storage_error → 500
31
- * - GrantError
32
- * invalid_label, invalid_max_nodes,
33
- * invalid_ttl → 400
34
- * not_found → 404
35
- * storage_error → 500
36
- * - DonationError
37
- * invalid_request → 400
38
- * unauthorized → 401
39
- * forbidden → 403
40
- * not_found → 404
41
- * invalid_state → 409
42
- * quota_exceeded → 429
43
- * orchestrator_error, storage_error → 500
44
- * seed_failed → 502
45
- * peer_unavailable → 503
46
- * - everything else → 500 (code "internal")
47
- */
48
-
49
- import type { FastifyError, FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
50
- import debug from 'debug';
51
-
52
- import { TrustCircleError, type TrustCircleErrorCode } from '../auth/types.js';
53
- import { NatError, type NatErrorCode } from '../nat/types.js';
54
- import { StrandError, type StrandErrorCode } from '../strands/types.js';
55
- import { UpdateErrorException, type UpdateErrorCode } from '../update/types.js';
56
- import { GrantError, type GrantErrorCode, DonationError, type DonationErrorCode } from '../donation/types.js';
57
-
58
- const log = debug('cadre:host:error-handler');
59
-
60
- const TRUST_STATUS: Record<TrustCircleErrorCode, number> = {
61
- invalid_label: 400,
62
- invalid_token: 400,
63
- not_found: 404,
64
- already_redeemed: 404,
65
- expired: 410,
66
- storage_error: 500,
67
- node_unavailable: 503,
68
- };
69
-
70
- const NAT_STATUS: Record<NatErrorCode, number> = {
71
- invalid_config: 400,
72
- ddns_provider_unknown: 400,
73
- ddns_credentials_missing: 400,
74
- secrets_unavailable: 500,
75
- storage_error: 500,
76
- mapping_failed: 500,
77
- router_unreachable: 500,
78
- ip_detection_failed: 500,
79
- ddns_update_failed: 500,
80
- node_unavailable: 503,
81
- };
82
-
83
- /**
84
- * 428 (Precondition Required) for `confirmation_required`: the node refused a
85
- * closed-strand removal because the caller had not confirmed. It is not a 400
86
- * (the request was well-formed) and not a 409 (nothing conflicts) — the caller
87
- * must re-send with the precondition satisfied.
88
- */
89
- const STRAND_STATUS: Record<StrandErrorCode, number> = {
90
- invalid_id: 400,
91
- confirmation_required: 428,
92
- node_unavailable: 503,
93
- internal: 500,
94
- };
95
-
96
- const GRANT_STATUS: Record<GrantErrorCode, number> = {
97
- invalid_label: 400,
98
- invalid_max_nodes: 400,
99
- invalid_ttl: 400,
100
- not_found: 404,
101
- storage_error: 500,
102
- };
103
-
104
- const DONATION_STATUS: Record<DonationErrorCode, number> = {
105
- unauthorized: 401,
106
- forbidden: 403,
107
- quota_exceeded: 429,
108
- invalid_request: 400,
109
- not_found: 404,
110
- invalid_state: 409,
111
- seed_failed: 502,
112
- peer_unavailable: 503,
113
- orchestrator_error: 500,
114
- storage_error: 500,
115
- };
116
-
117
- const UPDATE_STATUS: Record<UpdateErrorCode, number> = {
118
- manifest_invalid: 400,
119
- no_update_available: 400,
120
- min_previous_version: 400,
121
- apply_in_progress: 409,
122
- signature_invalid: 500,
123
- unsupported_state_version: 500,
124
- apply_failed: 500,
125
- rollback_failed: 500,
126
- storage_error: 500,
127
- };
128
-
129
- export function registerErrorHandler(app: FastifyInstance): void {
130
- app.setErrorHandler((err: FastifyError, request: FastifyRequest, reply: FastifyReply) => {
131
- const { status, code, message } = classify(err);
132
- if (status >= 500) {
133
- log('5xx %s %s: [%s] %s', request.method, request.url, code, message);
134
- } else {
135
- log('%d %s %s: [%s] %s', status, request.method, request.url, code, message);
136
- }
137
- return reply.code(status).send({
138
- ok: false,
139
- error: { code, message },
140
- });
141
- });
142
- }
143
-
144
- interface Classified {
145
- status: number;
146
- code: string;
147
- message: string;
148
- }
149
-
150
- function classify(err: FastifyError): Classified {
151
- if (err instanceof TrustCircleError) {
152
- return { status: TRUST_STATUS[err.code] ?? 500, code: err.code, message: err.message };
153
- }
154
- if (err instanceof NatError) {
155
- return { status: NAT_STATUS[err.code] ?? 500, code: err.code, message: err.message };
156
- }
157
- if (err instanceof StrandError) {
158
- return { status: STRAND_STATUS[err.code] ?? 500, code: err.code, message: err.message };
159
- }
160
- if (err instanceof UpdateErrorException) {
161
- return { status: UPDATE_STATUS[err.code] ?? 500, code: err.code, message: err.message };
162
- }
163
- if (err instanceof GrantError) {
164
- return { status: GRANT_STATUS[err.code] ?? 500, code: err.code, message: err.message };
165
- }
166
- if (err instanceof DonationError) {
167
- return { status: DONATION_STATUS[err.code] ?? 500, code: err.code, message: err.message };
168
- }
169
- // Fastify body-parsing / validation errors have a statusCode we should honour.
170
- if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) {
171
- return {
172
- status: err.statusCode,
173
- code: err.code ?? (err.statusCode === 404 ? 'not_found' : 'bad_request'),
174
- message: err.message ?? 'request failed',
175
- };
176
- }
177
- return { status: 500, code: 'internal', message: err.message || 'internal error' };
178
- }
1
+ /**
2
+ * Fastify error handler — translates known typed errors to stable HTTP status
3
+ * codes and uniform `{ ok: false, error: { code, message } }` payloads.
4
+ *
5
+ * Codes (cross-referenced with `auth/types.ts`, `nat/types.ts`, `strands/types.ts`,
6
+ * `update/types.ts`):
7
+ * - TrustCircleError
8
+ * invalid_label, invalid_token → 400
9
+ * not_found, already_redeemed → 404
10
+ * expired → 410
11
+ * node_unavailable → 503
12
+ * storage_error → 500
13
+ * - NatError
14
+ * invalid_config, ddns_provider_unknown,
15
+ * ddns_credentials_missing → 400
16
+ * secrets_unavailable, storage_error,
17
+ * mapping_failed, router_unreachable,
18
+ * ip_detection_failed, ddns_update_failed → 500
19
+ * node_unavailable → 503
20
+ * - StrandError
21
+ * invalid_id → 400
22
+ * confirmation_required → 428
23
+ * node_unavailable → 503
24
+ * internal → 500
25
+ * - UpdateErrorException
26
+ * manifest_invalid, no_update_available,
27
+ * min_previous_version → 400
28
+ * apply_in_progress → 409
29
+ * signature_invalid, unsupported_state_version,
30
+ * apply_failed, rollback_failed, storage_error → 500
31
+ * - GrantError
32
+ * invalid_label, invalid_max_nodes,
33
+ * invalid_ttl → 400
34
+ * not_found → 404
35
+ * storage_error → 500
36
+ * - DonationError
37
+ * invalid_request → 400
38
+ * unauthorized → 401
39
+ * forbidden → 403
40
+ * not_found → 404
41
+ * invalid_state → 409
42
+ * quota_exceeded → 429
43
+ * orchestrator_error, storage_error → 500
44
+ * seed_failed → 502
45
+ * peer_unavailable → 503
46
+ * - everything else → 500 (code "internal")
47
+ */
48
+
49
+ import type { FastifyError, FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
50
+ import debug from 'debug';
51
+
52
+ import { TrustCircleError, type TrustCircleErrorCode } from '../auth/types.js';
53
+ import { NatError, type NatErrorCode } from '../nat/types.js';
54
+ import { StrandError, type StrandErrorCode } from '../strands/types.js';
55
+ import { UpdateErrorException, type UpdateErrorCode } from '../update/types.js';
56
+ import { GrantError, type GrantErrorCode, DonationError, type DonationErrorCode } from '../donation/types.js';
57
+
58
+ const log = debug('cadre:host:error-handler');
59
+
60
+ const TRUST_STATUS: Record<TrustCircleErrorCode, number> = {
61
+ invalid_label: 400,
62
+ invalid_token: 400,
63
+ not_found: 404,
64
+ already_redeemed: 404,
65
+ expired: 410,
66
+ storage_error: 500,
67
+ node_unavailable: 503,
68
+ };
69
+
70
+ const NAT_STATUS: Record<NatErrorCode, number> = {
71
+ invalid_config: 400,
72
+ ddns_provider_unknown: 400,
73
+ ddns_credentials_missing: 400,
74
+ secrets_unavailable: 500,
75
+ storage_error: 500,
76
+ mapping_failed: 500,
77
+ router_unreachable: 500,
78
+ ip_detection_failed: 500,
79
+ ddns_update_failed: 500,
80
+ node_unavailable: 503,
81
+ };
82
+
83
+ /**
84
+ * 428 (Precondition Required) for `confirmation_required`: the node refused a
85
+ * closed-strand removal because the caller had not confirmed. It is not a 400
86
+ * (the request was well-formed) and not a 409 (nothing conflicts) — the caller
87
+ * must re-send with the precondition satisfied.
88
+ */
89
+ const STRAND_STATUS: Record<StrandErrorCode, number> = {
90
+ invalid_id: 400,
91
+ confirmation_required: 428,
92
+ node_unavailable: 503,
93
+ internal: 500,
94
+ };
95
+
96
+ const GRANT_STATUS: Record<GrantErrorCode, number> = {
97
+ invalid_label: 400,
98
+ invalid_max_nodes: 400,
99
+ invalid_ttl: 400,
100
+ not_found: 404,
101
+ storage_error: 500,
102
+ };
103
+
104
+ const DONATION_STATUS: Record<DonationErrorCode, number> = {
105
+ unauthorized: 401,
106
+ forbidden: 403,
107
+ quota_exceeded: 429,
108
+ invalid_request: 400,
109
+ not_found: 404,
110
+ invalid_state: 409,
111
+ seed_failed: 502,
112
+ peer_unavailable: 503,
113
+ orchestrator_error: 500,
114
+ storage_error: 500,
115
+ };
116
+
117
+ const UPDATE_STATUS: Record<UpdateErrorCode, number> = {
118
+ manifest_invalid: 400,
119
+ no_update_available: 400,
120
+ min_previous_version: 400,
121
+ apply_in_progress: 409,
122
+ signature_invalid: 500,
123
+ unsupported_state_version: 500,
124
+ apply_failed: 500,
125
+ rollback_failed: 500,
126
+ storage_error: 500,
127
+ };
128
+
129
+ export function registerErrorHandler(app: FastifyInstance): void {
130
+ app.setErrorHandler((err: FastifyError, request: FastifyRequest, reply: FastifyReply) => {
131
+ const { status, code, message } = classify(err);
132
+ if (status >= 500) {
133
+ log('5xx %s %s: [%s] %s', request.method, request.url, code, message);
134
+ } else {
135
+ log('%d %s %s: [%s] %s', status, request.method, request.url, code, message);
136
+ }
137
+ return reply.code(status).send({
138
+ ok: false,
139
+ error: { code, message },
140
+ });
141
+ });
142
+ }
143
+
144
+ interface Classified {
145
+ status: number;
146
+ code: string;
147
+ message: string;
148
+ }
149
+
150
+ function classify(err: FastifyError): Classified {
151
+ if (err instanceof TrustCircleError) {
152
+ return { status: TRUST_STATUS[err.code] ?? 500, code: err.code, message: err.message };
153
+ }
154
+ if (err instanceof NatError) {
155
+ return { status: NAT_STATUS[err.code] ?? 500, code: err.code, message: err.message };
156
+ }
157
+ if (err instanceof StrandError) {
158
+ return { status: STRAND_STATUS[err.code] ?? 500, code: err.code, message: err.message };
159
+ }
160
+ if (err instanceof UpdateErrorException) {
161
+ return { status: UPDATE_STATUS[err.code] ?? 500, code: err.code, message: err.message };
162
+ }
163
+ if (err instanceof GrantError) {
164
+ return { status: GRANT_STATUS[err.code] ?? 500, code: err.code, message: err.message };
165
+ }
166
+ if (err instanceof DonationError) {
167
+ return { status: DONATION_STATUS[err.code] ?? 500, code: err.code, message: err.message };
168
+ }
169
+ // Fastify body-parsing / validation errors have a statusCode we should honour.
170
+ if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) {
171
+ return {
172
+ status: err.statusCode,
173
+ code: err.code ?? (err.statusCode === 404 ? 'not_found' : 'bad_request'),
174
+ message: err.message ?? 'request failed',
175
+ };
176
+ }
177
+ return { status: 500, code: 'internal', message: err.message || 'internal error' };
178
+ }
@@ -1,42 +1,42 @@
1
- /**
2
- * In-memory event bus for the local UI.
3
- *
4
- * Tiny synchronous fan-out: publishers (route adapters, orchestrator hook,
5
- * update observer) call `publish`; SSE connections subscribe and receive every
6
- * event until they unsubscribe. Listener errors are caught so one broken
7
- * client cannot break others.
8
- */
9
-
10
- import debug from 'debug';
11
-
12
- import type { LocalUiEvent } from './types.js';
13
-
14
- const log = debug('cadre:host:event-bus');
15
-
16
- export type LocalUiEventListener = (event: LocalUiEvent) => void;
17
-
18
- export class EventBus {
19
- private readonly listeners = new Set<LocalUiEventListener>();
20
-
21
- publish(event: LocalUiEvent): void {
22
- for (const listener of this.listeners) {
23
- try {
24
- listener(event);
25
- } catch (err) {
26
- log('listener threw for event %s: %s', event.type, (err as Error).message);
27
- }
28
- }
29
- }
30
-
31
- subscribe(listener: LocalUiEventListener): () => void {
32
- this.listeners.add(listener);
33
- return () => {
34
- this.listeners.delete(listener);
35
- };
36
- }
37
-
38
- /** Test helper. */
39
- listenerCount(): number {
40
- return this.listeners.size;
41
- }
42
- }
1
+ /**
2
+ * In-memory event bus for the local UI.
3
+ *
4
+ * Tiny synchronous fan-out: publishers (route adapters, orchestrator hook,
5
+ * update observer) call `publish`; SSE connections subscribe and receive every
6
+ * event until they unsubscribe. Listener errors are caught so one broken
7
+ * client cannot break others.
8
+ */
9
+
10
+ import debug from 'debug';
11
+
12
+ import type { LocalUiEvent } from './types.js';
13
+
14
+ const log = debug('cadre:host:event-bus');
15
+
16
+ export type LocalUiEventListener = (event: LocalUiEvent) => void;
17
+
18
+ export class EventBus {
19
+ private readonly listeners = new Set<LocalUiEventListener>();
20
+
21
+ publish(event: LocalUiEvent): void {
22
+ for (const listener of this.listeners) {
23
+ try {
24
+ listener(event);
25
+ } catch (err) {
26
+ log('listener threw for event %s: %s', event.type, (err as Error).message);
27
+ }
28
+ }
29
+ }
30
+
31
+ subscribe(listener: LocalUiEventListener): () => void {
32
+ this.listeners.add(listener);
33
+ return () => {
34
+ this.listeners.delete(listener);
35
+ };
36
+ }
37
+
38
+ /** Test helper. */
39
+ listenerCount(): number {
40
+ return this.listeners.size;
41
+ }
42
+ }
@@ -1,81 +1,81 @@
1
- /**
2
- * Server-Sent Events route — `GET /api/events`.
3
- *
4
- * Hand-rolled (~40 lines vs. the 30 KB @fastify/sse-v2 dep). The wire format:
5
- *
6
- * retry: 5000\n\n ← reconnect hint
7
- * : heartbeat\n\n ← comment line, every 15 s
8
- * event: <type>\n ← event name
9
- * data: <json>\n\n ← payload
10
- *
11
- * The handler subscribes to the bus on connect, unsubscribes on client
12
- * disconnect, and ticks a heartbeat so corporate proxies don't close the
13
- * connection at the idle timeout.
14
- */
15
-
16
- import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
17
- import debug from 'debug';
18
-
19
- import type { EventBus } from './bus.js';
20
- import type { LocalUiEvent } from './types.js';
21
-
22
- const log = debug('cadre:host:sse');
23
-
24
- const HEARTBEAT_INTERVAL_MS = 15_000;
25
- const RECONNECT_HINT_MS = 5_000;
26
-
27
- export interface SseRouteOptions {
28
- events: EventBus;
29
- /** Test override: shorter heartbeat. */
30
- heartbeatIntervalMs?: number;
31
- }
32
-
33
- export function registerSseRoute(app: FastifyInstance, opts: SseRouteOptions): void {
34
- const heartbeatMs = opts.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS;
35
-
36
- app.get('/api/events', (request: FastifyRequest, reply: FastifyReply) => {
37
- // Tell Fastify we're handling the reply ourselves — it won't try to
38
- // serialise or send a payload.
39
- reply.hijack();
40
- reply.raw.writeHead(200, {
41
- 'Content-Type': 'text/event-stream',
42
- 'Cache-Control': 'no-cache, no-transform',
43
- Connection: 'keep-alive',
44
- 'X-Accel-Buffering': 'no',
45
- });
46
- reply.raw.write(`retry: ${RECONNECT_HINT_MS}\n\n`);
47
- reply.raw.write(`: connected\n\n`);
48
-
49
- const onEvent = (event: LocalUiEvent): void => {
50
- try {
51
- reply.raw.write(`event: ${event.type}\n`);
52
- reply.raw.write(`data: ${JSON.stringify(event)}\n\n`);
53
- } catch (err) {
54
- log('write failed (client likely gone): %s', (err as Error).message);
55
- }
56
- };
57
- const unsubscribe = opts.events.subscribe(onEvent);
58
-
59
- const heartbeat = setInterval(() => {
60
- try {
61
- reply.raw.write(`: heartbeat\n\n`);
62
- } catch (err) {
63
- log('heartbeat write failed: %s', (err as Error).message);
64
- }
65
- }, heartbeatMs);
66
- // Don't hold the event loop open for the heartbeat alone.
67
- if (typeof heartbeat === 'object' && 'unref' in heartbeat) {
68
- (heartbeat as { unref?: () => void }).unref?.();
69
- }
70
-
71
- const cleanup = (): void => {
72
- clearInterval(heartbeat);
73
- unsubscribe();
74
- };
75
- request.raw.on('close', cleanup);
76
- request.raw.on('error', cleanup);
77
-
78
- // The reply object is intentionally not returned — Fastify must not
79
- // attempt to serialise an SSE response.
80
- });
81
- }
1
+ /**
2
+ * Server-Sent Events route — `GET /api/events`.
3
+ *
4
+ * Hand-rolled (~40 lines vs. the 30 KB @fastify/sse-v2 dep). The wire format:
5
+ *
6
+ * retry: 5000\n\n ← reconnect hint
7
+ * : heartbeat\n\n ← comment line, every 15 s
8
+ * event: <type>\n ← event name
9
+ * data: <json>\n\n ← payload
10
+ *
11
+ * The handler subscribes to the bus on connect, unsubscribes on client
12
+ * disconnect, and ticks a heartbeat so corporate proxies don't close the
13
+ * connection at the idle timeout.
14
+ */
15
+
16
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
17
+ import debug from 'debug';
18
+
19
+ import type { EventBus } from './bus.js';
20
+ import type { LocalUiEvent } from './types.js';
21
+
22
+ const log = debug('cadre:host:sse');
23
+
24
+ const HEARTBEAT_INTERVAL_MS = 15_000;
25
+ const RECONNECT_HINT_MS = 5_000;
26
+
27
+ export interface SseRouteOptions {
28
+ events: EventBus;
29
+ /** Test override: shorter heartbeat. */
30
+ heartbeatIntervalMs?: number;
31
+ }
32
+
33
+ export function registerSseRoute(app: FastifyInstance, opts: SseRouteOptions): void {
34
+ const heartbeatMs = opts.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS;
35
+
36
+ app.get('/api/events', (request: FastifyRequest, reply: FastifyReply) => {
37
+ // Tell Fastify we're handling the reply ourselves — it won't try to
38
+ // serialise or send a payload.
39
+ reply.hijack();
40
+ reply.raw.writeHead(200, {
41
+ 'Content-Type': 'text/event-stream',
42
+ 'Cache-Control': 'no-cache, no-transform',
43
+ Connection: 'keep-alive',
44
+ 'X-Accel-Buffering': 'no',
45
+ });
46
+ reply.raw.write(`retry: ${RECONNECT_HINT_MS}\n\n`);
47
+ reply.raw.write(`: connected\n\n`);
48
+
49
+ const onEvent = (event: LocalUiEvent): void => {
50
+ try {
51
+ reply.raw.write(`event: ${event.type}\n`);
52
+ reply.raw.write(`data: ${JSON.stringify(event)}\n\n`);
53
+ } catch (err) {
54
+ log('write failed (client likely gone): %s', (err as Error).message);
55
+ }
56
+ };
57
+ const unsubscribe = opts.events.subscribe(onEvent);
58
+
59
+ const heartbeat = setInterval(() => {
60
+ try {
61
+ reply.raw.write(`: heartbeat\n\n`);
62
+ } catch (err) {
63
+ log('heartbeat write failed: %s', (err as Error).message);
64
+ }
65
+ }, heartbeatMs);
66
+ // Don't hold the event loop open for the heartbeat alone.
67
+ if (typeof heartbeat === 'object' && 'unref' in heartbeat) {
68
+ (heartbeat as { unref?: () => void }).unref?.();
69
+ }
70
+
71
+ const cleanup = (): void => {
72
+ clearInterval(heartbeat);
73
+ unsubscribe();
74
+ };
75
+ request.raw.on('close', cleanup);
76
+ request.raw.on('error', cleanup);
77
+
78
+ // The reply object is intentionally not returned — Fastify must not
79
+ // attempt to serialise an SSE response.
80
+ });
81
+ }
@@ -1,23 +1,23 @@
1
- /**
2
- * Event types broadcast over the SPA's SSE channel.
3
- *
4
- * Publishers (orchestrator hook, route adapters, update observer) call
5
- * EventBus.publish; the `/api/events` route fan-outs to connected clients.
6
- */
7
-
8
- import type { ContainerStatus } from '@serfab/cadre-provider';
9
-
10
- import type { DirectReachability, PortForwardMode } from '../../nat/index.js';
11
-
12
- export type LocalUiEvent =
13
- | { type: 'node-state-changed'; nodeId: string; status: ContainerStatus }
14
- | { type: 'trust-circle-changed'; kind: 'invited' | 'redeemed' | 'revoked' }
15
- | { type: 'strands-changed'; kind: 'removed' }
16
- | {
17
- type: 'connectivity-changed';
18
- portMode: PortForwardMode;
19
- directReachability: DirectReachability;
20
- }
21
- | { type: 'update-available'; version: string; releaseNotesUrl?: string };
22
-
23
- export type LocalUiEventType = LocalUiEvent['type'];
1
+ /**
2
+ * Event types broadcast over the SPA's SSE channel.
3
+ *
4
+ * Publishers (orchestrator hook, route adapters, update observer) call
5
+ * EventBus.publish; the `/api/events` route fan-outs to connected clients.
6
+ */
7
+
8
+ import type { ContainerStatus } from '@serfab/cadre-provider';
9
+
10
+ import type { DirectReachability, PortForwardMode } from '../../nat/index.js';
11
+
12
+ export type LocalUiEvent =
13
+ | { type: 'node-state-changed'; nodeId: string; status: ContainerStatus }
14
+ | { type: 'trust-circle-changed'; kind: 'invited' | 'redeemed' | 'revoked' }
15
+ | { type: 'strands-changed'; kind: 'removed' }
16
+ | {
17
+ type: 'connectivity-changed';
18
+ portMode: PortForwardMode;
19
+ directReachability: DirectReachability;
20
+ }
21
+ | { type: 'update-available'; version: string; releaseNotesUrl?: string };
22
+
23
+ export type LocalUiEventType = LocalUiEvent['type'];