@camstack/system 1.2.431 → 1.2.433

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 (97) hide show
  1. package/dist/{tls-C5IYg3V5.js → agent-https-CHZTxK-q.js} +123 -759
  2. package/dist/{tls-CpcGkeJV.mjs → agent-https-DtRU9A7I.mjs} +89 -611
  3. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  4. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  5. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  6. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  7. package/dist/builtins/alerts/alerts.addon.js +1 -1
  8. package/dist/builtins/alerts/alerts.addon.mjs +1 -1
  9. package/dist/builtins/autotrack/index.js +1 -1
  10. package/dist/builtins/autotrack/index.mjs +1 -1
  11. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  12. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  13. package/dist/builtins/calendars/calendars.addon.js +1 -1
  14. package/dist/builtins/calendars/calendars.addon.mjs +1 -1
  15. package/dist/builtins/camera-grid/index.js +1 -1
  16. package/dist/builtins/camera-grid/index.mjs +1 -1
  17. package/dist/builtins/composer/composer.addon.js +2 -2
  18. package/dist/builtins/composer/composer.addon.mjs +2 -2
  19. package/dist/builtins/console-logging/index.js +1 -1
  20. package/dist/builtins/console-logging/index.mjs +1 -1
  21. package/dist/builtins/core-blocks/core-blocks.addon.js +2 -2
  22. package/dist/builtins/core-blocks/core-blocks.addon.mjs +2 -2
  23. package/dist/builtins/device-manager/device-manager.addon.js +2 -2
  24. package/dist/builtins/device-manager/device-manager.addon.mjs +2 -2
  25. package/dist/builtins/hub-forwarder/index.js +1 -1
  26. package/dist/builtins/hub-forwarder/index.mjs +1 -1
  27. package/dist/builtins/keychain/index.js +3 -3
  28. package/dist/builtins/keychain/index.mjs +3 -3
  29. package/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  30. package/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  31. package/dist/builtins/local-auth/local-auth.addon.js +2 -2
  32. package/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  33. package/dist/builtins/local-network/agent-mdns.d.ts +51 -0
  34. package/dist/builtins/local-network/local-network.addon.js +20 -45
  35. package/dist/builtins/local-network/local-network.addon.mjs +2 -28
  36. package/dist/builtins/loki-logging/index.js +1 -1
  37. package/dist/builtins/loki-logging/index.mjs +1 -1
  38. package/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  39. package/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  40. package/dist/builtins/platform-probe/index.js +1 -1
  41. package/dist/builtins/platform-probe/index.mjs +1 -1
  42. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  43. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  44. package/dist/builtins/snapshot/index.js +1 -1
  45. package/dist/builtins/snapshot/index.mjs +1 -1
  46. package/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  47. package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  48. package/dist/builtins/sqlite-storage/index.js +1 -1
  49. package/dist/builtins/sqlite-storage/index.mjs +1 -1
  50. package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  51. package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  52. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  53. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  54. package/dist/builtins/system-config/system-config.addon.js +1370 -28
  55. package/dist/builtins/system-config/system-config.addon.mjs +1344 -25
  56. package/dist/builtins/winston-logging/index.js +1 -1
  57. package/dist/builtins/winston-logging/index.mjs +1 -1
  58. package/dist/{composition-sources-Cw_TXEq9.mjs → composition-sources-8-cpAt1c.mjs} +1 -1
  59. package/dist/{composition-sources-o5MPSlk6.js → composition-sources-BgJWQMjr.js} +1 -1
  60. package/dist/{constants-BcNaVkvI.js → constants-Ah3T_KAW.js} +2 -2
  61. package/dist/{constants-CttE77VF.mjs → constants-Cg9ve13y.mjs} +2 -2
  62. package/dist/{device-ca-B-BTxeCj.mjs → device-ca-DUrcTW5h.mjs} +1 -1
  63. package/dist/{device-ca-CKiqh2Iu.js → device-ca-NNP4Jz0P.js} +1 -1
  64. package/dist/{dist-DxJdci75.js → dist-C6Yvfhpq.js} +360 -1
  65. package/dist/{dist-CXG6muCR.mjs → dist-DJnlnL7P.mjs} +349 -2
  66. package/dist/file-host-worker.js +1 -1
  67. package/dist/file-host-worker.mjs +1 -1
  68. package/dist/hub-mdns-ciao-8_Ed1Za5.mjs +648 -0
  69. package/dist/hub-mdns-ciao-B50jAU5C.js +821 -0
  70. package/dist/index.d.ts +3 -0
  71. package/dist/index.js +176 -67
  72. package/dist/index.mjs +96 -13
  73. package/dist/kernel/index.d.ts +5 -4
  74. package/dist/kernel/moleculer/agent-mesh-authenticator.d.ts +12 -1
  75. package/dist/kernel/moleculer/agent-ui-unlock.d.ts +40 -0
  76. package/dist/kernel/moleculer/mesh-authenticator.d.ts +6 -0
  77. package/dist/kernel/moleculer/mesh-mtls/constants.d.ts +1 -1
  78. package/dist/kernel/moleculer/mesh-mtls/index.d.ts +3 -2
  79. package/dist/kernel/moleculer/mesh-mtls/mesh-ca.d.ts +4 -0
  80. package/dist/kernel/moleculer/mesh-mtls/mesh-certificate-registry.d.ts +2 -2
  81. package/dist/kernel/moleculer/mesh-mtls/mesh-join-token.d.ts +3 -2
  82. package/dist/kernel/moleculer/mesh-mtls/mesh-peer-transport.d.ts +7 -0
  83. package/dist/kernel/moleculer/mesh-mtls/pairing/agent-pairing.d.ts +204 -0
  84. package/dist/kernel/moleculer/mesh-mtls/pairing/hub-pairing.d.ts +115 -0
  85. package/dist/kernel/moleculer/mesh-mtls/pairing/index.d.ts +3 -0
  86. package/dist/kernel/moleculer/mesh-mtls/pairing/pairing-protocol.d.ts +107 -0
  87. package/dist/kernel/moleculer/mesh-mtls/tls-tcp-transporter.d.ts +18 -0
  88. package/dist/{restore-archive-D_wBL1OO.mjs → restore-archive-C3_rzOCx.mjs} +1 -1
  89. package/dist/{restore-archive-CQJNoqRK.js → restore-archive-DqPaRjjY.js} +1 -1
  90. package/dist/{retired-settings-keys-EmDe11cP.mjs → retired-settings-keys-CAWHWDwy.mjs} +1 -1
  91. package/dist/{retired-settings-keys-g1oifXxR.js → retired-settings-keys-DJBQkZok.js} +1 -1
  92. package/dist/tls/agent-https-names.d.ts +2 -0
  93. package/dist/{wal-maintenance-vhPZLYuA.mjs → wal-maintenance-Bc38yI3r.mjs} +0 -0
  94. package/dist/{wal-maintenance-BW1LIHi0.js → wal-maintenance-CPLvZbzA.js} +0 -0
  95. package/package.json +1 -1
  96. package/dist/agent-https-names-CpUSuP4w.js +0 -120
  97. package/dist/agent-https-names-uetr4OQl.mjs +0 -91
@@ -0,0 +1,821 @@
1
+ const require_chunk = require("./chunk-Cek0wNdY.js");
2
+ const require_agent_https = require("./agent-https-CHZTxK-q.js");
3
+ let node_crypto = require("node:crypto");
4
+ let _camstack_types_node = require("@camstack/types/node");
5
+ let node_fs_promises = require("node:fs/promises");
6
+ let node_path = require("node:path");
7
+ let node_fs = require("node:fs");
8
+ let node_http = require("node:http");
9
+ //#region src/http/lan-http-bind.ts
10
+ /**
11
+ * Second HTTP listener that shares the hub's existing request handler.
12
+ *
13
+ * Fastify is one protocol per instance; HTTPS stays on :4443 and this
14
+ * binds a plain `http.Server` that emits `request` AND `upgrade` onto the
15
+ * same handler graph (tRPC HTTP, cookies, data-plane, static, tRPC WS).
16
+ *
17
+ * Forwarding only `request` is not enough: the viewer speaks tRPC exclusively
18
+ * over WebSocket (`wsLink`). `/health` wins the LAN race, then `ws://…/trpc`
19
+ * hangs because nobody handles the upgrade on this socket.
20
+ */
21
+ var DEFAULT_HTTP_PORT = 4480;
22
+ var handlers = null;
23
+ var server = null;
24
+ var pending = null;
25
+ var state = {
26
+ listening: false,
27
+ error: null,
28
+ port: DEFAULT_HTTP_PORT
29
+ };
30
+ var boundRequestedHost = null;
31
+ var DEFAULT_LAN_HTTP_PORT = DEFAULT_HTTP_PORT;
32
+ /** Map "all IPv4" to dual-stack IPv6 (`::`, ipv6Only false) so IPv4 still works. */
33
+ function allFamiliesListenHost(host) {
34
+ if (host === "0.0.0.0" || host === "*" || host === "") return {
35
+ host: "::",
36
+ ipv6Only: false
37
+ };
38
+ return {
39
+ host,
40
+ ipv6Only: false
41
+ };
42
+ }
43
+ function registerLanHttpHandler(next) {
44
+ handlers = next;
45
+ }
46
+ function readLanHttpState() {
47
+ return state;
48
+ }
49
+ async function applyLanHttp(options) {
50
+ pending = options;
51
+ if (!options.enabled) {
52
+ await closeLanHttp();
53
+ state = {
54
+ listening: false,
55
+ error: null,
56
+ port: options.port
57
+ };
58
+ return state;
59
+ }
60
+ if (handlers === null) {
61
+ state = {
62
+ listening: false,
63
+ error: "HTTP listener is not registered yet",
64
+ port: options.port
65
+ };
66
+ return state;
67
+ }
68
+ if (server !== null && state.listening && (options.port === 0 || state.port === options.port) && boundRequestedHost === options.host) return state;
69
+ await closeLanHttp();
70
+ try {
71
+ const bound = await listenHttp(options.port, options.host, handlers);
72
+ server = bound;
73
+ boundRequestedHost = options.host;
74
+ const addr = bound.address();
75
+ state = {
76
+ listening: true,
77
+ error: null,
78
+ port: typeof addr === "object" && addr !== null ? addr.port : options.port
79
+ };
80
+ return state;
81
+ } catch (err) {
82
+ server = null;
83
+ state = {
84
+ listening: false,
85
+ error: err instanceof Error ? err.message : String(err),
86
+ port: options.port
87
+ };
88
+ return state;
89
+ }
90
+ }
91
+ /** After the hub registers the Fastify request handler, bind whatever was pending. */
92
+ async function bindPendingLanHttp() {
93
+ if (pending === null) return applyLanHttp({
94
+ enabled: true,
95
+ port: DEFAULT_HTTP_PORT,
96
+ host: "0.0.0.0"
97
+ });
98
+ return applyLanHttp(pending);
99
+ }
100
+ async function closeLanHttp() {
101
+ const current = server;
102
+ server = null;
103
+ boundRequestedHost = null;
104
+ if (current === null) return;
105
+ await new Promise((resolve) => {
106
+ current.close(() => resolve());
107
+ });
108
+ }
109
+ function listenHttp(port, host, next) {
110
+ const resolved = allFamiliesListenHost(host);
111
+ return listenOn(port, resolved, next).catch((err) => {
112
+ if (resolved.host === "::" && host !== "::") return listenOn(port, {
113
+ host: "0.0.0.0",
114
+ ipv6Only: false
115
+ }, next);
116
+ throw err;
117
+ });
118
+ }
119
+ function listenOn(port, bind, next) {
120
+ return new Promise((resolve, reject) => {
121
+ const created = (0, node_http.createServer)(next.onRequest);
122
+ created.on("upgrade", next.onUpgrade);
123
+ const onError = (err) => {
124
+ created.off("listening", onListening);
125
+ created.close();
126
+ reject(err);
127
+ };
128
+ const onListening = () => {
129
+ created.off("error", onError);
130
+ resolve(created);
131
+ };
132
+ created.once("error", onError);
133
+ created.once("listening", onListening);
134
+ created.listen({
135
+ port,
136
+ host: bind.host,
137
+ ipv6Only: bind.ipv6Only
138
+ });
139
+ });
140
+ }
141
+ //#endregion
142
+ //#region src/tls/cert-manager.ts
143
+ var DEFAULT_COMMON_NAME = "camstack.local";
144
+ /**
145
+ * Ensure the hub has a usable TLS identity under `<dataDir>/tls`, made of
146
+ * a long-lived local **root** (`camstack-ca.crt`) and a short **leaf**
147
+ * chained to it (`camstack.crt` = leaf + root, `camstack.key`).
148
+ *
149
+ * ## The regeneration rule (D227)
150
+ *
151
+ * Reissue happens when, and only when, the material on disk **cannot do
152
+ * its job**:
153
+ *
154
+ * - it is absent, unreadable, or the key does not match the certificate;
155
+ * - the root is absent (every pre-2026-08 install: one self-signed
156
+ * `CA:TRUE` leaf and no root) or is inside its renewal window;
157
+ * - the leaf is inside its 30-day renewal window;
158
+ * - the leaf lacks `extendedKeyUsage = serverAuth` — Apple's trustd
159
+ * rejects an app-supplied anchor without it;
160
+ * - the leaf is not actually issued by the root on disk;
161
+ * - the leaf's validity span exceeds {@link MAX_LEAF_VALIDITY_DAYS};
162
+ * - **a name or address the hub must answer for is missing from the SAN
163
+ * list** — a DHCP move, a new interface or a new hostname.
164
+ *
165
+ * And explicitly NOT when: the certificate names an address the machine
166
+ * no longer has (a superset still works — the check is one-directional),
167
+ * a volatile interface (docker/VPN/mesh) or **any** IPv6 address changed
168
+ * (global and ULA both rotate under privacy extensions / interface-id
169
+ * churn — `os` cannot tell temporary from permanent), or a new build shipped.
170
+ *
171
+ * Every trigger is derived from the files plus the machine, so once a
172
+ * reissue clears them it clears them for good: the next boot returns
173
+ * `generated: false`. A certificate that moved on every boot would
174
+ * invalidate every trust an operator granted by hand — worse than the
175
+ * bugs this rule fixes.
176
+ *
177
+ * **The root is rotated only for root-level reasons.** SAN drift rotates
178
+ * the leaf alone, so trust granted to `camstack-ca.crt` survives every
179
+ * address change the hub will ever see.
180
+ */
181
+ async function ensureTlsCert(dataDir, options) {
182
+ const tlsDir = (0, node_path.join)(dataDir, "tls");
183
+ const paths = {
184
+ certPath: (0, node_path.join)(tlsDir, "camstack.crt"),
185
+ keyPath: (0, node_path.join)(tlsDir, "camstack.key"),
186
+ caCertPath: (0, node_path.join)(tlsDir, "camstack-ca.crt"),
187
+ caKeyPath: (0, node_path.join)(tlsDir, "camstack-ca.key")
188
+ };
189
+ const commonName = options?.commonName ?? DEFAULT_COMMON_NAME;
190
+ const validDays = Math.min(options?.validDays ?? 397, 397);
191
+ const identity = require_agent_https.collectCertIdentity({
192
+ commonName,
193
+ extraSans: options?.extraSans ?? [],
194
+ ...options?.hostFacts === void 0 ? {} : { hostFacts: options.hostFacts }
195
+ });
196
+ const reason = decideRegeneration(paths, identity);
197
+ if (reason === null) return describe(paths, false, null, false, null, null);
198
+ const previousFingerprint = readFingerprint(paths.certPath);
199
+ const caRotated = require_agent_https.reasonRequiresNewCa(reason);
200
+ (0, node_fs.mkdirSync)(tlsDir, { recursive: true });
201
+ try {
202
+ await regenerate(paths, identity, commonName, validDays, caRotated);
203
+ } catch (err) {
204
+ const message = err instanceof Error ? err.message : String(err);
205
+ if (!canKeepServing(paths)) throw err;
206
+ return describe(paths, false, null, false, null, message);
207
+ }
208
+ return describe(paths, true, reason, caRotated, previousFingerprint, null);
209
+ }
210
+ /**
211
+ * Operator "Regenerate": issue a new leaf under the existing local CA.
212
+ * Never rotates the root — trust granted to `camstack-ca.crt` survives.
213
+ */
214
+ async function reissueTlsLeaf(dataDir, options) {
215
+ const tlsDir = (0, node_path.join)(dataDir, "tls");
216
+ const paths = {
217
+ certPath: (0, node_path.join)(tlsDir, "camstack.crt"),
218
+ keyPath: (0, node_path.join)(tlsDir, "camstack.key"),
219
+ caCertPath: (0, node_path.join)(tlsDir, "camstack-ca.crt"),
220
+ caKeyPath: (0, node_path.join)(tlsDir, "camstack-ca.key")
221
+ };
222
+ if (!(0, node_fs.existsSync)(paths.caCertPath) || !(0, node_fs.existsSync)(paths.caKeyPath)) return ensureTlsCert(dataDir, options);
223
+ const commonName = options?.commonName ?? DEFAULT_COMMON_NAME;
224
+ const validDays = Math.min(options?.validDays ?? 397, 397);
225
+ const identity = require_agent_https.collectCertIdentity({
226
+ commonName,
227
+ extraSans: options?.extraSans ?? [],
228
+ ...options?.hostFacts === void 0 ? {} : { hostFacts: options.hostFacts }
229
+ });
230
+ const previousFingerprint = readFingerprint(paths.certPath);
231
+ (0, node_fs.mkdirSync)(tlsDir, { recursive: true });
232
+ await regenerate(paths, identity, commonName, validDays, false);
233
+ return describe(paths, true, "san-coverage-gap", false, previousFingerprint, null);
234
+ }
235
+ /** True when the material already on disk can still terminate TLS. */
236
+ function canKeepServing(paths) {
237
+ if (!(0, node_fs.existsSync)(paths.certPath) || !(0, node_fs.existsSync)(paths.keyPath)) return false;
238
+ if (!(0, node_fs.existsSync)(paths.caCertPath)) return false;
239
+ return readFingerprint(paths.certPath) !== null;
240
+ }
241
+ /** Fingerprint of whatever is on disk, or `null` if there is nothing readable. */
242
+ function readFingerprint(certPath) {
243
+ try {
244
+ return new node_crypto.X509Certificate((0, node_fs.readFileSync)(certPath)).fingerprint256;
245
+ } catch {
246
+ return null;
247
+ }
248
+ }
249
+ function decideRegeneration(paths, identity) {
250
+ if (!(0, node_fs.existsSync)(paths.certPath) || !(0, node_fs.existsSync)(paths.keyPath)) return "missing";
251
+ if (!(0, node_fs.existsSync)(paths.caCertPath) || !(0, node_fs.existsSync)(paths.caKeyPath)) return "no-local-ca";
252
+ try {
253
+ return require_agent_https.evaluateExistingCert({
254
+ chainPem: (0, node_fs.readFileSync)(paths.certPath, "utf-8"),
255
+ keyPem: (0, node_fs.readFileSync)(paths.keyPath, "utf-8"),
256
+ caPem: (0, node_fs.readFileSync)(paths.caCertPath, "utf-8"),
257
+ identity,
258
+ now: /* @__PURE__ */ new Date()
259
+ });
260
+ } catch {
261
+ return "unreadable";
262
+ }
263
+ }
264
+ /**
265
+ * Build every byte in memory, then move the files into place. A crash
266
+ * mid-way leaves the previous material untouched; a crash between the
267
+ * moves leaves a key/certificate mismatch, which the evaluator reports as
268
+ * `key-mismatch` and heals on the next boot.
269
+ */
270
+ async function regenerate(paths, identity, commonName, validDays, newCa) {
271
+ const now = /* @__PURE__ */ new Date();
272
+ const ca = newCa ? await require_agent_https.generateCa(now) : await require_agent_https.loadCa((0, node_fs.readFileSync)(paths.caCertPath, "utf-8"), (0, node_fs.readFileSync)(paths.caKeyPath, "utf-8"));
273
+ const leaf = await require_agent_https.issueLeaf(ca, identity, commonName, validDays, now);
274
+ const chainPem = `${leaf.certPem.trimEnd()}\n${ca.certPem.trimEnd()}\n`;
275
+ if (newCa) {
276
+ await (0, node_fs_promises.writeFile)(`${paths.caCertPath}.new`, ca.certPem, "utf-8");
277
+ (0, _camstack_types_node.writeOwnerOnlyFileSync)(`${paths.caKeyPath}.new`, ca.keyPem);
278
+ (0, node_fs.renameSync)(`${paths.caCertPath}.new`, paths.caCertPath);
279
+ (0, node_fs.renameSync)(`${paths.caKeyPath}.new`, paths.caKeyPath);
280
+ }
281
+ (0, _camstack_types_node.writeOwnerOnlyFileSync)(`${paths.keyPath}.new`, leaf.keyPem);
282
+ await (0, node_fs_promises.writeFile)(`${paths.certPath}.new`, chainPem, "utf-8");
283
+ (0, node_fs.renameSync)(`${paths.keyPath}.new`, paths.keyPath);
284
+ (0, node_fs.renameSync)(`${paths.certPath}.new`, paths.certPath);
285
+ }
286
+ function describe(paths, generated, reason, caRotated, previousFingerprintSha256, reissueError) {
287
+ const leaf = new node_crypto.X509Certificate((0, node_fs.readFileSync)(paths.certPath));
288
+ const ca = new node_crypto.X509Certificate((0, node_fs.readFileSync)(paths.caCertPath));
289
+ const san = leaf.subjectAltName ?? "";
290
+ return {
291
+ ...paths,
292
+ generated,
293
+ reason,
294
+ caRotated,
295
+ fingerprintSha256: leaf.fingerprint256,
296
+ previousFingerprintSha256,
297
+ caFingerprintSha256: ca.fingerprint256,
298
+ validTo: new Date(leaf.validTo).toISOString(),
299
+ sans: san === "" ? [] : san.split(", "),
300
+ reissueError
301
+ };
302
+ }
303
+ /**
304
+ * Load TLS cert+key from files. Returns Buffers suitable for Node.js TLS
305
+ * options. `certPath` is a full chain, so the listener presents the local
306
+ * root alongside the leaf.
307
+ */
308
+ function loadTlsCert(certPath, keyPath) {
309
+ return {
310
+ cert: (0, node_fs.readFileSync)(certPath),
311
+ key: (0, node_fs.readFileSync)(keyPath)
312
+ };
313
+ }
314
+ //#endregion
315
+ //#region src/tls/tls-status.ts
316
+ function tlsDir(dataDir) {
317
+ return (0, node_path.join)(dataDir, "tls");
318
+ }
319
+ function readTlsMode(dataDir) {
320
+ const marker = (0, node_path.join)(tlsDir(dataDir), "mode");
321
+ if ((0, node_fs.existsSync)(marker)) {
322
+ const raw = (0, node_fs.readFileSync)(marker, "utf-8").trim();
323
+ if (raw === "uploaded") return "uploaded";
324
+ if (raw === "disabled") return "disabled";
325
+ }
326
+ return (0, node_fs.existsSync)((0, node_path.join)(tlsDir(dataDir), "camstack.crt")) ? "generated" : "disabled";
327
+ }
328
+ function writeTlsMode(dataDir, mode) {
329
+ (0, node_fs.mkdirSync)(tlsDir(dataDir), { recursive: true });
330
+ (0, node_fs.writeFileSync)((0, node_path.join)(tlsDir(dataDir), "mode"), `${mode}\n`, "utf-8");
331
+ }
332
+ function readExtraSans(dataDir) {
333
+ const path = (0, node_path.join)(tlsDir(dataDir), "extra-sans.json");
334
+ if (!(0, node_fs.existsSync)(path)) return [];
335
+ try {
336
+ const parsed = JSON.parse((0, node_fs.readFileSync)(path, "utf-8"));
337
+ if (!Array.isArray(parsed)) return [];
338
+ return parsed.filter((entry) => typeof entry === "string" && entry.length > 0);
339
+ } catch {
340
+ return [];
341
+ }
342
+ }
343
+ function writeExtraSans(dataDir, sans) {
344
+ (0, node_fs.mkdirSync)(tlsDir(dataDir), { recursive: true });
345
+ (0, node_fs.writeFileSync)((0, node_path.join)(tlsDir(dataDir), "extra-sans.json"), `${JSON.stringify(sans)}\n`, "utf-8");
346
+ }
347
+ /** Where an upload's own CA is kept — never over the local CA's `camstack-ca.crt`. */
348
+ var UPLOADED_CA_FILE = "uploaded-ca.crt";
349
+ /** Every certificate in a PEM bundle, in order. */
350
+ function splitPemCertificates(pem) {
351
+ const blocks = pem.match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g);
352
+ return blocks === null ? [] : blocks.map((block) => `${block}\n`);
353
+ }
354
+ /**
355
+ * The certificate that signed `leaf`, from the upload itself: the CA the
356
+ * operator supplied, else the rest of the uploaded chain. `null` when the
357
+ * upload did not include it — and then nothing may stand in for it: the
358
+ * local CA did not sign an uploaded leaf, so handing it out as "the CA" would
359
+ * tell a client to trust a root that verifies nothing it is served.
360
+ */
361
+ function uploadedIssuer(dir, leaf, chainPem) {
362
+ const caPath = (0, node_path.join)(dir, UPLOADED_CA_FILE);
363
+ const candidates = [...(0, node_fs.existsSync)(caPath) ? splitPemCertificates((0, node_fs.readFileSync)(caPath, "utf-8")) : [], ...splitPemCertificates(chainPem).slice(1)];
364
+ for (const pem of candidates) try {
365
+ const cert = new node_crypto.X509Certificate(pem);
366
+ if (leaf.checkIssued(cert) && leaf.verify(cert.publicKey)) return {
367
+ pem,
368
+ cert
369
+ };
370
+ } catch {}
371
+ return null;
372
+ }
373
+ function generatedIssuer(dir) {
374
+ const caPath = (0, node_path.join)(dir, "camstack-ca.crt");
375
+ if (!(0, node_fs.existsSync)(caPath)) return null;
376
+ const pem = (0, node_fs.readFileSync)(caPath, "utf-8");
377
+ return {
378
+ pem,
379
+ cert: new node_crypto.X509Certificate(pem)
380
+ };
381
+ }
382
+ /**
383
+ * What the node's certificate is, and whether the listener serves it.
384
+ * `servedLeafFingerprint` is the leaf the HTTPS listener presents right now
385
+ * (`servedHttpsLeafFingerprint()`), or `null` when unknown; a restart is
386
+ * required exactly when the listener serves a different leaf than the one
387
+ * on disk — a measured fact, not a flag a mutation remembered to set.
388
+ */
389
+ function readTlsAccessStatus(dataDir, servedLeafFingerprint) {
390
+ const dir = tlsDir(dataDir);
391
+ const certPath = (0, node_path.join)(dir, "camstack.crt");
392
+ const mode = readTlsMode(dataDir);
393
+ if (!(0, node_fs.existsSync)(certPath)) return {
394
+ mode: "disabled",
395
+ leafFingerprintSha256: null,
396
+ caFingerprintSha256: null,
397
+ validTo: null,
398
+ sans: [],
399
+ caCertPem: (mode === "uploaded" ? null : generatedIssuer(dir))?.pem ?? null,
400
+ reissueError: null,
401
+ restartRequired: false
402
+ };
403
+ try {
404
+ const chainPem = (0, node_fs.readFileSync)(certPath, "utf-8");
405
+ const leaf = new node_crypto.X509Certificate(chainPem);
406
+ const ca = mode === "uploaded" ? uploadedIssuer(dir, leaf, chainPem) : generatedIssuer(dir);
407
+ const san = leaf.subjectAltName ?? "";
408
+ return {
409
+ mode,
410
+ leafFingerprintSha256: leaf.fingerprint256,
411
+ caFingerprintSha256: ca?.cert.fingerprint256 ?? null,
412
+ validTo: new Date(leaf.validTo).toISOString(),
413
+ sans: san === "" ? [] : san.split(", "),
414
+ caCertPem: ca?.pem ?? null,
415
+ reissueError: null,
416
+ restartRequired: servedLeafFingerprint !== null && servedLeafFingerprint !== leaf.fingerprint256
417
+ };
418
+ } catch {
419
+ return {
420
+ mode,
421
+ leafFingerprintSha256: null,
422
+ caFingerprintSha256: null,
423
+ validTo: null,
424
+ sans: [],
425
+ caCertPem: null,
426
+ reissueError: "Certificate on disk could not be parsed.",
427
+ restartRequired: false
428
+ };
429
+ }
430
+ }
431
+ //#endregion
432
+ //#region src/tls/boot-tls.ts
433
+ /**
434
+ * Decide what the listener serves at boot. The admin UI (Network → Local
435
+ * access) is the only way to set a certificate (D726): it either leaves the
436
+ * hub on its generated local-CA leaf (D227) or uploads one, recorded by the
437
+ * `tls/mode` marker. An uploaded certificate is served verbatim — running it
438
+ * through `ensureTlsCert` would replace it on the first restart, because a
439
+ * leaf the local root did not issue is one of that rule's reissue triggers.
440
+ */
441
+ async function prepareBootTls(dataDir, options) {
442
+ const certPath = (0, node_path.join)(dataDir, "tls", "camstack.crt");
443
+ const keyPath = (0, node_path.join)(dataDir, "tls", "camstack.key");
444
+ const marked = readTlsMode(dataDir);
445
+ if (marked === "uploaded" && (0, node_fs.existsSync)(certPath) && (0, node_fs.existsSync)(keyPath)) return {
446
+ mode: "uploaded",
447
+ pair: loadTlsCert(certPath, keyPath),
448
+ ensured: void 0,
449
+ uploadedMissing: false
450
+ };
451
+ const uploadedMissing = marked === "uploaded";
452
+ if (uploadedMissing) writeTlsMode(dataDir, "generated");
453
+ const ensured = await ensureTlsCert(dataDir, options);
454
+ return {
455
+ mode: "generated",
456
+ pair: loadTlsCert(ensured.certPath, ensured.keyPath),
457
+ ensured,
458
+ uploadedMissing
459
+ };
460
+ }
461
+ //#endregion
462
+ //#region src/tls/https-listener.ts
463
+ var SLOT_KEY = Symbol.for("camstack.tls.https-listener");
464
+ var EMPTY_SLOT = {
465
+ reload: null,
466
+ servedLeafFingerprint: null
467
+ };
468
+ function isSlot(value) {
469
+ if (typeof value !== "object" || value === null) return false;
470
+ if (!("reload" in value) || !("servedLeafFingerprint" in value)) return false;
471
+ const reload = value.reload;
472
+ const served = value.servedLeafFingerprint;
473
+ return (reload === null || typeof reload === "function") && (served === null || typeof served === "string");
474
+ }
475
+ function readSlot() {
476
+ const current = Reflect.get(globalThis, SLOT_KEY);
477
+ return isSlot(current) ? current : EMPTY_SLOT;
478
+ }
479
+ function writeSlot(next) {
480
+ Reflect.set(globalThis, SLOT_KEY, next);
481
+ }
482
+ /** SHA-256 fingerprint of the first certificate (the leaf) in a PEM chain. */
483
+ function leafFingerprintOf(chain) {
484
+ return new node_crypto.X509Certificate(chain).fingerprint256;
485
+ }
486
+ /**
487
+ * Called once by the server after its HTTPS listener is up, with the pair it
488
+ * was started on. From here on a certificate action swaps the served
489
+ * certificate in place (`setSecureContext`) — new handshakes get the new
490
+ * leaf, open connections keep theirs, nothing restarts.
491
+ */
492
+ function registerHttpsListener(server, pair) {
493
+ writeSlot({
494
+ reload: (next) => server.setSecureContext({
495
+ cert: next.cert,
496
+ key: next.key
497
+ }),
498
+ servedLeafFingerprint: leafFingerprintOf(pair.cert)
499
+ });
500
+ }
501
+ /** Forget the listener — on shutdown, and between specs. */
502
+ function clearHttpsListener() {
503
+ writeSlot(EMPTY_SLOT);
504
+ }
505
+ /**
506
+ * The leaf the HTTPS listener serves now, or `null` when this process has no
507
+ * registered listener (TLS off, or a process that does not own one) — in
508
+ * which case nobody can say, and `null` is the honest answer.
509
+ */
510
+ function servedHttpsLeafFingerprint() {
511
+ return readSlot().servedLeafFingerprint;
512
+ }
513
+ /** Serve `pair` from now on. Never throws: the outcome says what happened. */
514
+ function reloadHttpsListener(pair) {
515
+ const slot = readSlot();
516
+ if (slot.reload === null) return { kind: "no-listener" };
517
+ try {
518
+ const servedLeafFingerprint = leafFingerprintOf(pair.cert);
519
+ slot.reload(pair);
520
+ writeSlot({
521
+ reload: slot.reload,
522
+ servedLeafFingerprint
523
+ });
524
+ return {
525
+ kind: "reloaded",
526
+ servedLeafFingerprint
527
+ };
528
+ } catch (err) {
529
+ return {
530
+ kind: "failed",
531
+ error: err instanceof Error ? err.message : String(err)
532
+ };
533
+ }
534
+ }
535
+ //#endregion
536
+ //#region src/tls/uploaded-cert.ts
537
+ /**
538
+ * Operator-supplied material must parse, match its key, and carry
539
+ * `extendedKeyUsage = serverAuth` — the same leaf defects D227 refused
540
+ * to keep generating.
541
+ */
542
+ function validateUploadedTls(certPem, keyPem) {
543
+ let leaf;
544
+ try {
545
+ leaf = new node_crypto.X509Certificate(certPem);
546
+ } catch {
547
+ return {
548
+ ok: false,
549
+ error: "Certificate PEM could not be parsed."
550
+ };
551
+ }
552
+ try {
553
+ if (!leaf.checkPrivateKey((0, node_crypto.createPrivateKey)(keyPem))) return {
554
+ ok: false,
555
+ error: "Private key does not match the certificate."
556
+ };
557
+ } catch {
558
+ return {
559
+ ok: false,
560
+ error: "Private key PEM could not be parsed."
561
+ };
562
+ }
563
+ const eku = leaf.keyUsage;
564
+ if (eku === void 0 || !eku.includes("1.3.6.1.5.5.7.3.1")) return {
565
+ ok: false,
566
+ error: "Certificate is missing extendedKeyUsage = serverAuth."
567
+ };
568
+ return {
569
+ ok: true,
570
+ fingerprintSha256: leaf.fingerprint256,
571
+ validTo: new Date(leaf.validTo).toISOString()
572
+ };
573
+ }
574
+ //#endregion
575
+ //#region src/tls/tls-actions.ts
576
+ function withNewline(pem) {
577
+ return pem.endsWith("\n") ? pem : `${pem}\n`;
578
+ }
579
+ /**
580
+ * Store an operator's certificate. The leaf (or chain) and key replace the
581
+ * served pair; a CA, when given, goes to its own file. The local CA
582
+ * (`camstack-ca.crt` + key) is never touched — it did not sign the upload,
583
+ * and it is what "Revert to generated" and every device that trusts it
584
+ * still need.
585
+ */
586
+ async function storeUploadedCertificate(dataDir, input) {
587
+ const valid = validateUploadedTls(input.certPem, input.keyPem);
588
+ if (!valid.ok) throw new Error(valid.error);
589
+ const dir = (0, node_path.join)(dataDir, "tls");
590
+ await (0, node_fs_promises.mkdir)(dir, { recursive: true });
591
+ await (0, node_fs_promises.writeFile)((0, node_path.join)(dir, "camstack.crt"), withNewline(input.certPem));
592
+ (0, _camstack_types_node.writeOwnerOnlyFileSync)((0, node_path.join)(dir, "camstack.key"), withNewline(input.keyPem));
593
+ const caPath = (0, node_path.join)(dir, UPLOADED_CA_FILE);
594
+ if (input.caPem !== void 0 && input.caPem.trim() !== "") await (0, node_fs_promises.writeFile)(caPath, withNewline(input.caPem));
595
+ else (0, node_fs.rmSync)(caPath, { force: true });
596
+ writeTlsMode(dataDir, "uploaded");
597
+ }
598
+ /** Issue a new generated leaf under the local CA. Refused while an upload is served. */
599
+ async function regenerateCertificate(dataDir, options) {
600
+ if (readTlsMode(dataDir) === "uploaded") throw new Error("Cannot regenerate an uploaded certificate — revert to generated first.");
601
+ await reissueTlsLeaf(dataDir, options);
602
+ }
603
+ /** Drop the upload and serve the generated local-CA leaf again (D227). */
604
+ async function revertToGeneratedCertificate(dataDir, options) {
605
+ writeTlsMode(dataDir, "generated");
606
+ (0, node_fs.rmSync)((0, node_path.join)(dataDir, "tls", UPLOADED_CA_FILE), { force: true });
607
+ await ensureTlsCert(dataDir, options);
608
+ }
609
+ /**
610
+ * Put the pair on disk on the HTTPS listener. Called after every action, so
611
+ * "the certificate changed" and "clients see it" are the same moment.
612
+ */
613
+ function applyCertificateToListener(dataDir) {
614
+ const certPath = (0, node_path.join)(dataDir, "tls", "camstack.crt");
615
+ const keyPath = (0, node_path.join)(dataDir, "tls", "camstack.key");
616
+ if (!(0, node_fs.existsSync)(certPath) || !(0, node_fs.existsSync)(keyPath)) return {
617
+ kind: "failed",
618
+ error: `No certificate pair under ${(0, node_path.join)(dataDir, "tls")}`
619
+ };
620
+ return reloadHttpsListener(loadTlsCert(certPath, keyPath));
621
+ }
622
+ //#endregion
623
+ //#region src/builtins/local-network/hub-mdns-ciao.ts
624
+ function createCiaoPublisher() {
625
+ return { async publish(announcement) {
626
+ const { getResponder } = await Promise.resolve().then(() => /* @__PURE__ */ require_chunk.__toESM(require("./lib-DOJ5yyWA.js").default));
627
+ const responder = getResponder();
628
+ const service = responder.createService({
629
+ name: announcement.name,
630
+ type: announcement.type,
631
+ port: announcement.port,
632
+ txt: { ...announcement.txt },
633
+ ...announcement.address !== null ? { restrictedAddresses: [announcement.address] } : {}
634
+ });
635
+ try {
636
+ await service.advertise();
637
+ } catch (err) {
638
+ await responder.shutdown().catch(() => void 0);
639
+ throw err;
640
+ }
641
+ return { stop: async () => {
642
+ await service.destroy();
643
+ await responder.shutdown();
644
+ } };
645
+ } };
646
+ }
647
+ //#endregion
648
+ Object.defineProperty(exports, "DEFAULT_LAN_HTTP_PORT", {
649
+ enumerable: true,
650
+ get: function() {
651
+ return DEFAULT_LAN_HTTP_PORT;
652
+ }
653
+ });
654
+ Object.defineProperty(exports, "UPLOADED_CA_FILE", {
655
+ enumerable: true,
656
+ get: function() {
657
+ return UPLOADED_CA_FILE;
658
+ }
659
+ });
660
+ Object.defineProperty(exports, "allFamiliesListenHost", {
661
+ enumerable: true,
662
+ get: function() {
663
+ return allFamiliesListenHost;
664
+ }
665
+ });
666
+ Object.defineProperty(exports, "applyCertificateToListener", {
667
+ enumerable: true,
668
+ get: function() {
669
+ return applyCertificateToListener;
670
+ }
671
+ });
672
+ Object.defineProperty(exports, "applyLanHttp", {
673
+ enumerable: true,
674
+ get: function() {
675
+ return applyLanHttp;
676
+ }
677
+ });
678
+ Object.defineProperty(exports, "bindPendingLanHttp", {
679
+ enumerable: true,
680
+ get: function() {
681
+ return bindPendingLanHttp;
682
+ }
683
+ });
684
+ Object.defineProperty(exports, "clearHttpsListener", {
685
+ enumerable: true,
686
+ get: function() {
687
+ return clearHttpsListener;
688
+ }
689
+ });
690
+ Object.defineProperty(exports, "closeLanHttp", {
691
+ enumerable: true,
692
+ get: function() {
693
+ return closeLanHttp;
694
+ }
695
+ });
696
+ Object.defineProperty(exports, "createCiaoPublisher", {
697
+ enumerable: true,
698
+ get: function() {
699
+ return createCiaoPublisher;
700
+ }
701
+ });
702
+ Object.defineProperty(exports, "ensureTlsCert", {
703
+ enumerable: true,
704
+ get: function() {
705
+ return ensureTlsCert;
706
+ }
707
+ });
708
+ Object.defineProperty(exports, "leafFingerprintOf", {
709
+ enumerable: true,
710
+ get: function() {
711
+ return leafFingerprintOf;
712
+ }
713
+ });
714
+ Object.defineProperty(exports, "loadTlsCert", {
715
+ enumerable: true,
716
+ get: function() {
717
+ return loadTlsCert;
718
+ }
719
+ });
720
+ Object.defineProperty(exports, "prepareBootTls", {
721
+ enumerable: true,
722
+ get: function() {
723
+ return prepareBootTls;
724
+ }
725
+ });
726
+ Object.defineProperty(exports, "readExtraSans", {
727
+ enumerable: true,
728
+ get: function() {
729
+ return readExtraSans;
730
+ }
731
+ });
732
+ Object.defineProperty(exports, "readLanHttpState", {
733
+ enumerable: true,
734
+ get: function() {
735
+ return readLanHttpState;
736
+ }
737
+ });
738
+ Object.defineProperty(exports, "readTlsAccessStatus", {
739
+ enumerable: true,
740
+ get: function() {
741
+ return readTlsAccessStatus;
742
+ }
743
+ });
744
+ Object.defineProperty(exports, "readTlsMode", {
745
+ enumerable: true,
746
+ get: function() {
747
+ return readTlsMode;
748
+ }
749
+ });
750
+ Object.defineProperty(exports, "regenerateCertificate", {
751
+ enumerable: true,
752
+ get: function() {
753
+ return regenerateCertificate;
754
+ }
755
+ });
756
+ Object.defineProperty(exports, "registerHttpsListener", {
757
+ enumerable: true,
758
+ get: function() {
759
+ return registerHttpsListener;
760
+ }
761
+ });
762
+ Object.defineProperty(exports, "registerLanHttpHandler", {
763
+ enumerable: true,
764
+ get: function() {
765
+ return registerLanHttpHandler;
766
+ }
767
+ });
768
+ Object.defineProperty(exports, "reissueTlsLeaf", {
769
+ enumerable: true,
770
+ get: function() {
771
+ return reissueTlsLeaf;
772
+ }
773
+ });
774
+ Object.defineProperty(exports, "reloadHttpsListener", {
775
+ enumerable: true,
776
+ get: function() {
777
+ return reloadHttpsListener;
778
+ }
779
+ });
780
+ Object.defineProperty(exports, "revertToGeneratedCertificate", {
781
+ enumerable: true,
782
+ get: function() {
783
+ return revertToGeneratedCertificate;
784
+ }
785
+ });
786
+ Object.defineProperty(exports, "servedHttpsLeafFingerprint", {
787
+ enumerable: true,
788
+ get: function() {
789
+ return servedHttpsLeafFingerprint;
790
+ }
791
+ });
792
+ Object.defineProperty(exports, "splitPemCertificates", {
793
+ enumerable: true,
794
+ get: function() {
795
+ return splitPemCertificates;
796
+ }
797
+ });
798
+ Object.defineProperty(exports, "storeUploadedCertificate", {
799
+ enumerable: true,
800
+ get: function() {
801
+ return storeUploadedCertificate;
802
+ }
803
+ });
804
+ Object.defineProperty(exports, "validateUploadedTls", {
805
+ enumerable: true,
806
+ get: function() {
807
+ return validateUploadedTls;
808
+ }
809
+ });
810
+ Object.defineProperty(exports, "writeExtraSans", {
811
+ enumerable: true,
812
+ get: function() {
813
+ return writeExtraSans;
814
+ }
815
+ });
816
+ Object.defineProperty(exports, "writeTlsMode", {
817
+ enumerable: true,
818
+ get: function() {
819
+ return writeTlsMode;
820
+ }
821
+ });