@camstack/system 1.2.382 → 1.2.383

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 (100) hide show
  1. package/dist/addon-runner.js +1 -1
  2. package/dist/addon-runner.mjs +1 -1
  3. package/dist/addon-utils.js +1 -1
  4. package/dist/addon-utils.mjs +1 -1
  5. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  6. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  7. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  8. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  9. package/dist/builtins/alerts/alerts.addon.js +1 -1
  10. package/dist/builtins/alerts/alerts.addon.mjs +1 -1
  11. package/dist/builtins/autotrack/index.js +1 -1
  12. package/dist/builtins/autotrack/index.mjs +1 -1
  13. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  14. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  15. package/dist/builtins/calendars/calendars.addon.js +1 -1
  16. package/dist/builtins/calendars/calendars.addon.mjs +1 -1
  17. package/dist/builtins/camera-grid/index.js +1 -1
  18. package/dist/builtins/camera-grid/index.mjs +1 -1
  19. package/dist/builtins/composer/composer.addon.js +2 -2
  20. package/dist/builtins/composer/composer.addon.mjs +2 -2
  21. package/dist/builtins/console-logging/index.js +1 -1
  22. package/dist/builtins/console-logging/index.mjs +1 -1
  23. package/dist/builtins/core-blocks/core-blocks.addon.js +2 -2
  24. package/dist/builtins/core-blocks/core-blocks.addon.mjs +2 -2
  25. package/dist/builtins/device-manager/device-manager.addon.js +2 -2
  26. package/dist/builtins/device-manager/device-manager.addon.mjs +2 -2
  27. package/dist/builtins/hub-forwarder/index.js +1 -1
  28. package/dist/builtins/hub-forwarder/index.mjs +1 -1
  29. package/dist/builtins/keychain/index.js +5 -5
  30. package/dist/builtins/keychain/index.mjs +4 -4
  31. package/dist/builtins/keychain/system-held-secrets.d.ts +2 -1
  32. package/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  33. package/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  34. package/dist/builtins/local-auth/local-auth.addon.js +9 -178
  35. package/dist/builtins/local-auth/local-auth.addon.mjs +4 -161
  36. package/dist/builtins/local-network/local-network.addon.js +2 -2
  37. package/dist/builtins/local-network/local-network.addon.mjs +2 -2
  38. package/dist/builtins/loki-logging/index.js +1 -1
  39. package/dist/builtins/loki-logging/index.mjs +1 -1
  40. package/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  41. package/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  42. package/dist/builtins/platform-probe/index.js +1 -1
  43. package/dist/builtins/platform-probe/index.mjs +1 -1
  44. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  45. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  46. package/dist/builtins/snapshot/index.js +1 -1
  47. package/dist/builtins/snapshot/index.mjs +1 -1
  48. package/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  49. package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  50. package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +0 -0
  51. package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +0 -0
  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/index.d.ts +1 -0
  55. package/dist/builtins/system-config/index.js +2 -0
  56. package/dist/builtins/system-config/index.mjs +2 -2
  57. package/dist/builtins/system-config/mesh-actions.d.ts +19 -0
  58. package/dist/builtins/system-config/system-config.addon.d.ts +34 -1
  59. package/dist/builtins/system-config/system-config.addon.js +87538 -9
  60. package/dist/builtins/system-config/system-config.addon.mjs +87505 -4
  61. package/dist/builtins/winston-logging/index.js +1 -1
  62. package/dist/builtins/winston-logging/index.mjs +1 -1
  63. package/dist/{child-cap-dispatch-BrMdKHfp.js → child-cap-dispatch-BD8fhJ1b.js} +2 -2
  64. package/dist/{child-cap-dispatch-WsYPNvnK.mjs → child-cap-dispatch-C68N2a6Y.mjs} +2 -2
  65. package/dist/{composition-sources-C6ZynCZ2.js → composition-sources-ChpT_Yw4.js} +1 -1
  66. package/dist/{composition-sources-XqRX51db.mjs → composition-sources-DM7Ft_tp.mjs} +1 -1
  67. package/dist/{cluster-secret-BEPLh3LL.js → constants-CDpry1_T.js} +82 -1
  68. package/dist/{cluster-secret-DhPdZ0VA.mjs → constants-e3mCa1jG.mjs} +23 -2
  69. package/dist/{dist-tnAO12ak.js → dist-CUNGH0fs.js} +34 -0
  70. package/dist/{dist-CP5TTjwd.mjs → dist-osl3bkF0.mjs} +23 -1
  71. package/dist/{event-loop-stall-monitor-WkssIXjq.mjs → event-loop-stall-monitor-BeeWMnyT.mjs} +1 -1
  72. package/dist/{event-loop-stall-monitor-9kR0sAPS.js → event-loop-stall-monitor-Dk28EF8B.js} +1 -1
  73. package/dist/index.js +284 -86048
  74. package/dist/index.mjs +513 -86302
  75. package/dist/{jwt-signing-key-CAbozwvF.mjs → jwt-signing-key-MQLxLfgF.mjs} +1 -1
  76. package/dist/{jwt-signing-key-Dgf8sIXY.js → jwt-signing-key-WI6z7JBo.js} +1 -1
  77. package/dist/kernel/index.d.ts +6 -2
  78. package/dist/kernel/moleculer/agent-mesh-authenticator.d.ts +41 -0
  79. package/dist/kernel/moleculer/broker-factory.d.ts +19 -3
  80. package/dist/kernel/moleculer/mesh-access-middleware.d.ts +7 -2
  81. package/dist/kernel/moleculer/mesh-mtls/constants.d.ts +20 -0
  82. package/dist/kernel/moleculer/mesh-mtls/index.d.ts +9 -0
  83. package/dist/kernel/moleculer/mesh-mtls/mesh-ca-keeper.d.ts +55 -0
  84. package/dist/kernel/moleculer/mesh-mtls/mesh-ca.d.ts +45 -0
  85. package/dist/kernel/moleculer/mesh-mtls/mesh-crl.d.ts +16 -0
  86. package/dist/kernel/moleculer/mesh-mtls/mesh-enroll.d.ts +27 -0
  87. package/dist/kernel/moleculer/mesh-mtls/mesh-join-token.d.ts +55 -0
  88. package/dist/kernel/moleculer/mesh-mtls/mesh-tls-enabler.d.ts +5 -0
  89. package/dist/kernel/moleculer/mesh-mtls/tls-tcp-transporter.d.ts +92 -0
  90. package/dist/ms-DlIWNkkk.mjs +160 -0
  91. package/dist/ms-t68_FaqE.js +171 -0
  92. package/dist/{restore-archive-CbvrfPuB.js → restore-archive-C5f9yX90.js} +3 -3
  93. package/dist/{restore-archive-BV39nY46.mjs → restore-archive-CZRtI1k9.mjs} +2 -2
  94. package/dist/{retired-settings-keys-CzpIkwS-.mjs → retired-settings-keys-LuDd4y3M.mjs} +1 -1
  95. package/dist/{retired-settings-keys-4bHpL-0m.js → retired-settings-keys-WLrbzdPR.js} +1 -1
  96. package/dist/tls-BWpwU-d5.js +1160 -0
  97. package/dist/tls-C2NT-Orr.mjs +949 -0
  98. package/dist/{tls-CljF057D.js → x509.es-BhTzcFhZ.js} +65 -1108
  99. package/dist/{tls-4cRH24Id.mjs → x509.es-Xf3K_brW.mjs} +40 -950
  100. package/package.json +3 -2
@@ -0,0 +1,1160 @@
1
+ const require_chunk = require("./chunk-Cek0wNdY.js");
2
+ const require_x509_es = require("./x509.es-BhTzcFhZ.js");
3
+ let node_crypto = require("node:crypto");
4
+ let node_net = require("node:net");
5
+ let node_fs_promises = require("node:fs/promises");
6
+ let node_path = require("node:path");
7
+ let node_os = require("node:os");
8
+ node_os = require_chunk.__toESM(node_os);
9
+ let node_fs = require("node:fs");
10
+ let node_http = require("node:http");
11
+ //#region src/http/lan-http-bind.ts
12
+ /**
13
+ * Second HTTP listener that shares the hub's existing request handler.
14
+ *
15
+ * Fastify is one protocol per instance; HTTPS stays on :4443 and this
16
+ * binds a plain `http.Server` that emits `request` AND `upgrade` onto the
17
+ * same handler graph (tRPC HTTP, cookies, data-plane, static, tRPC WS).
18
+ *
19
+ * Forwarding only `request` is not enough: the viewer speaks tRPC exclusively
20
+ * over WebSocket (`wsLink`). `/health` wins the LAN race, then `ws://…/trpc`
21
+ * hangs because nobody handles the upgrade on this socket.
22
+ */
23
+ var DEFAULT_HTTP_PORT = 4480;
24
+ var handlers = null;
25
+ var server = null;
26
+ var pending = null;
27
+ var state = {
28
+ listening: false,
29
+ error: null,
30
+ port: DEFAULT_HTTP_PORT
31
+ };
32
+ var boundRequestedHost = null;
33
+ var DEFAULT_LAN_HTTP_PORT = DEFAULT_HTTP_PORT;
34
+ /** Map "all IPv4" to dual-stack IPv6 (`::`, ipv6Only false) so IPv4 still works. */
35
+ function allFamiliesListenHost(host) {
36
+ if (host === "0.0.0.0" || host === "*" || host === "") return {
37
+ host: "::",
38
+ ipv6Only: false
39
+ };
40
+ return {
41
+ host,
42
+ ipv6Only: false
43
+ };
44
+ }
45
+ function registerLanHttpHandler(next) {
46
+ handlers = next;
47
+ }
48
+ function readLanHttpState() {
49
+ return state;
50
+ }
51
+ async function applyLanHttp(options) {
52
+ pending = options;
53
+ if (!options.enabled) {
54
+ await closeLanHttp();
55
+ state = {
56
+ listening: false,
57
+ error: null,
58
+ port: options.port
59
+ };
60
+ return state;
61
+ }
62
+ if (handlers === null) {
63
+ state = {
64
+ listening: false,
65
+ error: "HTTP listener is not registered yet",
66
+ port: options.port
67
+ };
68
+ return state;
69
+ }
70
+ if (server !== null && state.listening && (options.port === 0 || state.port === options.port) && boundRequestedHost === options.host) return state;
71
+ await closeLanHttp();
72
+ try {
73
+ const bound = await listenHttp(options.port, options.host, handlers);
74
+ server = bound;
75
+ boundRequestedHost = options.host;
76
+ const addr = bound.address();
77
+ state = {
78
+ listening: true,
79
+ error: null,
80
+ port: typeof addr === "object" && addr !== null ? addr.port : options.port
81
+ };
82
+ return state;
83
+ } catch (err) {
84
+ server = null;
85
+ state = {
86
+ listening: false,
87
+ error: err instanceof Error ? err.message : String(err),
88
+ port: options.port
89
+ };
90
+ return state;
91
+ }
92
+ }
93
+ /** After the hub registers the Fastify request handler, bind whatever was pending. */
94
+ async function bindPendingLanHttp() {
95
+ if (pending === null) return applyLanHttp({
96
+ enabled: true,
97
+ port: DEFAULT_HTTP_PORT,
98
+ host: "0.0.0.0"
99
+ });
100
+ return applyLanHttp(pending);
101
+ }
102
+ async function closeLanHttp() {
103
+ const current = server;
104
+ server = null;
105
+ boundRequestedHost = null;
106
+ if (current === null) return;
107
+ await new Promise((resolve) => {
108
+ current.close(() => resolve());
109
+ });
110
+ }
111
+ function listenHttp(port, host, next) {
112
+ const resolved = allFamiliesListenHost(host);
113
+ return listenOn(port, resolved, next).catch((err) => {
114
+ if (resolved.host === "::" && host !== "::") return listenOn(port, {
115
+ host: "0.0.0.0",
116
+ ipv6Only: false
117
+ }, next);
118
+ throw err;
119
+ });
120
+ }
121
+ function listenOn(port, bind, next) {
122
+ return new Promise((resolve, reject) => {
123
+ const created = (0, node_http.createServer)(next.onRequest);
124
+ created.on("upgrade", next.onUpgrade);
125
+ const onError = (err) => {
126
+ created.off("listening", onListening);
127
+ created.close();
128
+ reject(err);
129
+ };
130
+ const onListening = () => {
131
+ created.off("error", onError);
132
+ resolve(created);
133
+ };
134
+ created.once("error", onError);
135
+ created.once("listening", onListening);
136
+ created.listen({
137
+ port,
138
+ host: bind.host,
139
+ ipv6Only: bind.ipv6Only
140
+ });
141
+ });
142
+ }
143
+ //#endregion
144
+ //#region src/tls/cert-evaluation.ts
145
+ /**
146
+ * The regeneration rule (D227), as a pure function.
147
+ *
148
+ * `ensureTlsCert` reissues **only** when the material on disk cannot do
149
+ * its job. Never because it is old, never because the machine picked up
150
+ * an address the certificate does not need, never because a new build
151
+ * shipped. The decision is a function of (files on disk, machine
152
+ * identity, clock) alone, so the same inputs always produce the same
153
+ * answer — which is what makes a reissue happen once and then stop.
154
+ */
155
+ /** OID `id-kp-serverAuth`. Apple's trustd requires it on the leaf. */
156
+ var SERVER_AUTH_OID = "1.3.6.1.5.5.7.3.1";
157
+ /**
158
+ * Apple's `SecPolicyCheckOtherTrustValidityPeriod` ceiling is 825 days;
159
+ * the CA/Browser Forum's recommended maximum is 397. We sit at 397.
160
+ */
161
+ var MAX_LEAF_VALIDITY_DAYS = 397;
162
+ /** Reissue this long before the leaf dies, so nobody serves an expired one. */
163
+ var LEAF_RENEWAL_WINDOW_DAYS = 30;
164
+ /** A local root outlives many leaves — it is the anchor an operator trusts. */
165
+ var CA_VALIDITY_DAYS = 3650;
166
+ var MS_PER_DAY$1 = 864e5;
167
+ /** Reasons that invalidate the root as well as the leaf. */
168
+ var REASONS_REQUIRING_NEW_CA = [
169
+ "missing",
170
+ "unreadable",
171
+ "no-local-ca",
172
+ "ca-expiring"
173
+ ];
174
+ function reasonRequiresNewCa(reason) {
175
+ return REASONS_REQUIRING_NEW_CA.includes(reason);
176
+ }
177
+ function parse(pem) {
178
+ try {
179
+ return new node_crypto.X509Certificate(pem);
180
+ } catch {
181
+ return null;
182
+ }
183
+ }
184
+ function daysBetween(from, to) {
185
+ return (to.getTime() - from.getTime()) / MS_PER_DAY$1;
186
+ }
187
+ function hasServerAuthEku(leaf) {
188
+ const eku = leaf.keyUsage;
189
+ return eku !== void 0 && eku.length === 1 && eku[0] === "1.3.6.1.5.5.7.3.1";
190
+ }
191
+ function keyMatches(leaf, keyPem) {
192
+ try {
193
+ return leaf.checkPrivateKey((0, node_crypto.createPrivateKey)(keyPem));
194
+ } catch {
195
+ return false;
196
+ }
197
+ }
198
+ function coversIdentity(leaf, identity) {
199
+ for (const name of identity.requiredDnsNames) if (leaf.checkHost(name) === void 0) return false;
200
+ for (const ip of identity.requiredIpAddresses) if (leaf.checkIP(ip) === void 0) return false;
201
+ return true;
202
+ }
203
+ /**
204
+ * `null` when the material on disk is fit to keep serving.
205
+ *
206
+ * Order matters only for the quality of the reported reason; any
207
+ * non-null answer produces the same action.
208
+ */
209
+ function evaluateExistingCert(input) {
210
+ const leaf = parse(input.chainPem);
211
+ const ca = parse(input.caPem);
212
+ if (leaf === null || ca === null) return "unreadable";
213
+ if (daysBetween(input.now, new Date(ca.validTo)) < 427) return "ca-expiring";
214
+ if (!keyMatches(leaf, input.keyPem)) return "key-mismatch";
215
+ if (daysBetween(input.now, new Date(leaf.validTo)) < 30) return "expiring";
216
+ if (!hasServerAuthEku(leaf)) return "missing-server-auth-eku";
217
+ if (leaf.ca || !leaf.checkIssued(ca) || !leaf.verify(ca.publicKey)) return "not-issued-by-local-ca";
218
+ if (daysBetween(new Date(leaf.validFrom), new Date(leaf.validTo)) > 398) return "validity-too-long";
219
+ if (!coversIdentity(leaf, input.identity)) return "san-coverage-gap";
220
+ return null;
221
+ }
222
+ //#endregion
223
+ //#region src/tls/cert-identity.ts
224
+ /**
225
+ * What names and addresses the hub's certificate has to answer for.
226
+ *
227
+ * Split out of `cert-manager.ts` because it is pure and because the
228
+ * regeneration rule (D227) is decided entirely by the difference between
229
+ * *this* and what the certificate on disk already carries.
230
+ */
231
+ /** The real machine. The only place in `tls/` that touches `os`. */
232
+ function systemHostFacts() {
233
+ return {
234
+ hostname: node_os.hostname(),
235
+ networkInterfaces: node_os.networkInterfaces()
236
+ };
237
+ }
238
+ /**
239
+ * Interfaces whose addresses are certified but never gate a reissue:
240
+ * container bridges, VPN tunnels and mesh overlays hand out addresses
241
+ * that change without the hub moving.
242
+ */
243
+ var VOLATILE_INTERFACE_PREFIXES = [
244
+ "docker",
245
+ "br-",
246
+ "veth",
247
+ "virbr",
248
+ "cni",
249
+ "flannel",
250
+ "tun",
251
+ "utun",
252
+ "tap",
253
+ "wg",
254
+ "zt",
255
+ "tailscale",
256
+ "ppp",
257
+ "awdl",
258
+ "llw"
259
+ ];
260
+ /** A DNS name we are willing to put in a SAN. */
261
+ var DNS_NAME_PATTERN = /^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$/;
262
+ function isIpv4(value) {
263
+ return (0, node_net.isIP)(value) === 4;
264
+ }
265
+ function isIpv6(value) {
266
+ return (0, node_net.isIP)(value) === 6;
267
+ }
268
+ /**
269
+ * `fe80::/10` and `169.254.0.0/16`. An IPv6 link-local address needs a
270
+ * zone index to be usable and a SAN cannot carry one, so such an entry
271
+ * can never match anything — it is noise that makes the certificate look
272
+ * broader than it is.
273
+ */
274
+ function isLinkLocal(value) {
275
+ if (isIpv4(value)) return value.startsWith("169.254.");
276
+ if (!isIpv6(value)) return false;
277
+ const firstGroup = value.split(":")[0] ?? "";
278
+ if (firstGroup === "") return false;
279
+ const parsed = Number.parseInt(firstGroup, 16);
280
+ return Number.isFinite(parsed) && (parsed & 65472) === 65152;
281
+ }
282
+ function isVolatileInterface(name) {
283
+ const lower = name.toLowerCase();
284
+ return VOLATILE_INTERFACE_PREFIXES.some((prefix) => lower.startsWith(prefix));
285
+ }
286
+ /**
287
+ * Only IPv4 gates a reissue. Every IPv6 address we see — global **or**
288
+ * ULA — is certified but never required: `os` cannot tell a temporary
289
+ * address from a permanent one, and the live hub's ULA interface-id
290
+ * rotated on every restart (eight leaf reissues in one day under
291
+ * `san-coverage-gap`). Gating on ULA reproduced the churn D227 exists
292
+ * to prevent. Operators who need a fixed IPv6 declare it via `extraSans`.
293
+ */
294
+ function isStableGateAddress(address) {
295
+ if (isLinkLocal(address)) return false;
296
+ return isIpv4(address);
297
+ }
298
+ function addSan(dns, ips, value) {
299
+ const trimmed = value.trim();
300
+ if (trimmed === "") return;
301
+ if ((0, node_net.isIP)(trimmed) !== 0) {
302
+ if (!isLinkLocal(trimmed)) ips.add(trimmed);
303
+ return;
304
+ }
305
+ if (DNS_NAME_PATTERN.test(trimmed)) dns.add(trimmed);
306
+ }
307
+ /**
308
+ * Snapshot the machine's identity. Called once per `ensureTlsCert`; the
309
+ * result is both the SAN list for a new leaf and the yardstick the
310
+ * existing leaf is measured against.
311
+ */
312
+ function collectCertIdentity(options) {
313
+ const host = options.hostFacts ?? systemHostFacts();
314
+ const dnsNames = /* @__PURE__ */ new Set();
315
+ const ipAddresses = new Set(["127.0.0.1", "::1"]);
316
+ const requiredDnsNames = /* @__PURE__ */ new Set();
317
+ const requiredIpAddresses = new Set(["127.0.0.1"]);
318
+ for (const name of [
319
+ "localhost",
320
+ options.commonName,
321
+ host.hostname
322
+ ]) {
323
+ addSan(dnsNames, ipAddresses, name);
324
+ addSan(requiredDnsNames, requiredIpAddresses, name);
325
+ }
326
+ for (const [ifaceName, addrs] of Object.entries(host.networkInterfaces)) for (const addr of addrs ?? []) {
327
+ if (addr.internal) continue;
328
+ if (isLinkLocal(addr.address)) continue;
329
+ ipAddresses.add(addr.address);
330
+ if (isVolatileInterface(ifaceName)) continue;
331
+ if (isStableGateAddress(addr.address)) requiredIpAddresses.add(addr.address);
332
+ }
333
+ for (const san of options.extraSans) {
334
+ addSan(dnsNames, ipAddresses, san);
335
+ addSan(requiredDnsNames, requiredIpAddresses, san);
336
+ }
337
+ return {
338
+ dnsNames: [...dnsNames],
339
+ ipAddresses: [...ipAddresses],
340
+ requiredDnsNames: [...requiredDnsNames],
341
+ requiredIpAddresses: [...requiredIpAddresses]
342
+ };
343
+ }
344
+ //#endregion
345
+ //#region src/tls/cert-issue.ts
346
+ require_x509_es.cryptoProvider.set(node_crypto.webcrypto);
347
+ /** Subject of the local root. Distinct from the leaf's CN by construction. */
348
+ var CA_COMMON_NAME = "CamStack Local CA";
349
+ var MS_PER_DAY = 864e5;
350
+ /**
351
+ * RSA-2048 / SHA-256. Unchanged from the openssl invocation this replaces:
352
+ * every client that trusted the previous material still understands this.
353
+ */
354
+ var SIGNING_ALGORITHM = {
355
+ name: "RSASSA-PKCS1-v1_5",
356
+ hash: "SHA-256",
357
+ publicExponent: new Uint8Array([
358
+ 1,
359
+ 0,
360
+ 1
361
+ ]),
362
+ modulusLength: 2048
363
+ };
364
+ /**
365
+ * A serial number that is positive and unpredictable. `00` prefix for the
366
+ * same reason the openssl invocation carried one: a leading bit of 1 would
367
+ * make the DER INTEGER negative.
368
+ */
369
+ function freshSerial() {
370
+ return `00${(0, node_crypto.randomBytes)(16).toString("hex")}`;
371
+ }
372
+ function toPkcs8Pem(pkcs8) {
373
+ return `${require_x509_es.PemConverter.encode(pkcs8, "PRIVATE KEY")}\n`;
374
+ }
375
+ function toCertPem(cert) {
376
+ return `${cert.toString("pem")}\n`;
377
+ }
378
+ async function exportKeyPem(key) {
379
+ return toPkcs8Pem(await node_crypto.webcrypto.subtle.exportKey("pkcs8", key));
380
+ }
381
+ /** SAN entries, in the order `cert-identity` produced them. */
382
+ function subjectAltNames(identity) {
383
+ const names = [];
384
+ for (const dns of identity.dnsNames) names.push({
385
+ type: "dns",
386
+ value: dns
387
+ });
388
+ for (const ip of identity.ipAddresses) if ((0, node_net.isIP)(ip) !== 0) names.push({
389
+ type: "ip",
390
+ value: ip
391
+ });
392
+ return names;
393
+ }
394
+ /**
395
+ * A local root: 10 years, `pathlen:0` so it can sign leaves and nothing
396
+ * else, and **no EKU** — Apple rejects an anchor asserting
397
+ * `anyExtendedKeyUsage`, and a root with no EKU constrains nothing.
398
+ */
399
+ async function generateCa(now) {
400
+ const keys = await node_crypto.webcrypto.subtle.generateKey(SIGNING_ALGORITHM, true, ["sign", "verify"]);
401
+ const extensions = [
402
+ new require_x509_es.BasicConstraintsExtension(true, 0, true),
403
+ new require_x509_es.KeyUsagesExtension(require_x509_es.KeyUsageFlags.keyCertSign | require_x509_es.KeyUsageFlags.cRLSign, true),
404
+ await require_x509_es.SubjectKeyIdentifierExtension.create(keys.publicKey)
405
+ ];
406
+ const cert = await require_x509_es.X509CertificateGenerator.createSelfSigned({
407
+ serialNumber: freshSerial(),
408
+ name: `CN=${CA_COMMON_NAME}`,
409
+ notBefore: now,
410
+ notAfter: new Date(now.getTime() + CA_VALIDITY_DAYS * MS_PER_DAY),
411
+ keys,
412
+ signingAlgorithm: SIGNING_ALGORITHM,
413
+ extensions
414
+ });
415
+ return {
416
+ certPem: toCertPem(cert),
417
+ keyPem: await exportKeyPem(keys.privateKey),
418
+ cert,
419
+ privateKey: keys.privateKey
420
+ };
421
+ }
422
+ /** Re-open a root already on disk so a leaf can be issued under it. */
423
+ async function loadCa(certPem, keyPem) {
424
+ return {
425
+ certPem,
426
+ keyPem,
427
+ cert: new require_x509_es.X509Certificate(certPem),
428
+ privateKey: await node_crypto.webcrypto.subtle.importKey("pkcs8", require_x509_es.PemConverter.decodeFirst(keyPem), SIGNING_ALGORITHM, true, ["sign"])
429
+ };
430
+ }
431
+ /**
432
+ * A server leaf signed by the local root: `CA:FALSE`, and
433
+ * `extendedKeyUsage=serverAuth` — not `anyExtendedKeyUsage`, which
434
+ * Apple's `testAppTrustRoot_AnyEKU_AfterJul2019` asserts must fail.
435
+ */
436
+ async function issueLeaf(ca, identity, commonName, validDays, now) {
437
+ const keys = await node_crypto.webcrypto.subtle.generateKey(SIGNING_ALGORITHM, true, ["sign", "verify"]);
438
+ const extensions = [
439
+ new require_x509_es.BasicConstraintsExtension(false, void 0, true),
440
+ new require_x509_es.KeyUsagesExtension(require_x509_es.KeyUsageFlags.digitalSignature | require_x509_es.KeyUsageFlags.keyEncipherment, true),
441
+ new require_x509_es.ExtendedKeyUsageExtension([SERVER_AUTH_OID]),
442
+ await require_x509_es.SubjectKeyIdentifierExtension.create(keys.publicKey),
443
+ await require_x509_es.AuthorityKeyIdentifierExtension.create(ca.cert),
444
+ new require_x509_es.SubjectAlternativeNameExtension(subjectAltNames(identity))
445
+ ];
446
+ return {
447
+ certPem: toCertPem(await require_x509_es.X509CertificateGenerator.create({
448
+ serialNumber: freshSerial(),
449
+ subject: `CN=${commonName}`,
450
+ issuer: ca.cert.subject,
451
+ notBefore: now,
452
+ notAfter: new Date(now.getTime() + validDays * MS_PER_DAY),
453
+ publicKey: keys.publicKey,
454
+ signingKey: ca.privateKey,
455
+ signingAlgorithm: SIGNING_ALGORITHM,
456
+ extensions
457
+ })),
458
+ keyPem: await exportKeyPem(keys.privateKey)
459
+ };
460
+ }
461
+ //#endregion
462
+ //#region src/tls/cert-manager.ts
463
+ var DEFAULT_COMMON_NAME = "camstack.local";
464
+ /**
465
+ * Ensure the hub has a usable TLS identity under `<dataDir>/tls`, made of
466
+ * a long-lived local **root** (`camstack-ca.crt`) and a short **leaf**
467
+ * chained to it (`camstack.crt` = leaf + root, `camstack.key`).
468
+ *
469
+ * ## The regeneration rule (D227)
470
+ *
471
+ * Reissue happens when, and only when, the material on disk **cannot do
472
+ * its job**:
473
+ *
474
+ * - it is absent, unreadable, or the key does not match the certificate;
475
+ * - the root is absent (every pre-2026-08 install: one self-signed
476
+ * `CA:TRUE` leaf and no root) or is inside its renewal window;
477
+ * - the leaf is inside its 30-day renewal window;
478
+ * - the leaf lacks `extendedKeyUsage = serverAuth` — Apple's trustd
479
+ * rejects an app-supplied anchor without it;
480
+ * - the leaf is not actually issued by the root on disk;
481
+ * - the leaf's validity span exceeds {@link MAX_LEAF_VALIDITY_DAYS};
482
+ * - **a name or address the hub must answer for is missing from the SAN
483
+ * list** — a DHCP move, a new interface or a new hostname.
484
+ *
485
+ * And explicitly NOT when: the certificate names an address the machine
486
+ * no longer has (a superset still works — the check is one-directional),
487
+ * a volatile interface (docker/VPN/mesh) or **any** IPv6 address changed
488
+ * (global and ULA both rotate under privacy extensions / interface-id
489
+ * churn — `os` cannot tell temporary from permanent), or a new build shipped.
490
+ *
491
+ * Every trigger is derived from the files plus the machine, so once a
492
+ * reissue clears them it clears them for good: the next boot returns
493
+ * `generated: false`. A certificate that moved on every boot would
494
+ * invalidate every trust an operator granted by hand — worse than the
495
+ * bugs this rule fixes.
496
+ *
497
+ * **The root is rotated only for root-level reasons.** SAN drift rotates
498
+ * the leaf alone, so trust granted to `camstack-ca.crt` survives every
499
+ * address change the hub will ever see.
500
+ */
501
+ async function ensureTlsCert(dataDir, options) {
502
+ const tlsDir = (0, node_path.join)(dataDir, "tls");
503
+ const paths = {
504
+ certPath: (0, node_path.join)(tlsDir, "camstack.crt"),
505
+ keyPath: (0, node_path.join)(tlsDir, "camstack.key"),
506
+ caCertPath: (0, node_path.join)(tlsDir, "camstack-ca.crt"),
507
+ caKeyPath: (0, node_path.join)(tlsDir, "camstack-ca.key")
508
+ };
509
+ const commonName = options?.commonName ?? DEFAULT_COMMON_NAME;
510
+ const validDays = Math.min(options?.validDays ?? 397, 397);
511
+ const identity = collectCertIdentity({
512
+ commonName,
513
+ extraSans: options?.extraSans ?? [],
514
+ ...options?.hostFacts === void 0 ? {} : { hostFacts: options.hostFacts }
515
+ });
516
+ const reason = decideRegeneration(paths, identity);
517
+ if (reason === null) return describe(paths, false, null, false, null, null);
518
+ const previousFingerprint = readFingerprint(paths.certPath);
519
+ const caRotated = reasonRequiresNewCa(reason);
520
+ (0, node_fs.mkdirSync)(tlsDir, { recursive: true });
521
+ try {
522
+ await regenerate(paths, identity, commonName, validDays, caRotated);
523
+ } catch (err) {
524
+ const message = err instanceof Error ? err.message : String(err);
525
+ if (!canKeepServing(paths)) throw err;
526
+ return describe(paths, false, null, false, null, message);
527
+ }
528
+ return describe(paths, true, reason, caRotated, previousFingerprint, null);
529
+ }
530
+ /**
531
+ * Operator "Regenerate": issue a new leaf under the existing local CA.
532
+ * Never rotates the root — trust granted to `camstack-ca.crt` survives.
533
+ */
534
+ async function reissueTlsLeaf(dataDir, options) {
535
+ const tlsDir = (0, node_path.join)(dataDir, "tls");
536
+ const paths = {
537
+ certPath: (0, node_path.join)(tlsDir, "camstack.crt"),
538
+ keyPath: (0, node_path.join)(tlsDir, "camstack.key"),
539
+ caCertPath: (0, node_path.join)(tlsDir, "camstack-ca.crt"),
540
+ caKeyPath: (0, node_path.join)(tlsDir, "camstack-ca.key")
541
+ };
542
+ if (!(0, node_fs.existsSync)(paths.caCertPath) || !(0, node_fs.existsSync)(paths.caKeyPath)) return ensureTlsCert(dataDir, options);
543
+ const commonName = options?.commonName ?? DEFAULT_COMMON_NAME;
544
+ const validDays = Math.min(options?.validDays ?? 397, 397);
545
+ const identity = collectCertIdentity({
546
+ commonName,
547
+ extraSans: options?.extraSans ?? [],
548
+ ...options?.hostFacts === void 0 ? {} : { hostFacts: options.hostFacts }
549
+ });
550
+ const previousFingerprint = readFingerprint(paths.certPath);
551
+ (0, node_fs.mkdirSync)(tlsDir, { recursive: true });
552
+ await regenerate(paths, identity, commonName, validDays, false);
553
+ return describe(paths, true, "san-coverage-gap", false, previousFingerprint, null);
554
+ }
555
+ /** True when the material already on disk can still terminate TLS. */
556
+ function canKeepServing(paths) {
557
+ if (!(0, node_fs.existsSync)(paths.certPath) || !(0, node_fs.existsSync)(paths.keyPath)) return false;
558
+ if (!(0, node_fs.existsSync)(paths.caCertPath)) return false;
559
+ return readFingerprint(paths.certPath) !== null;
560
+ }
561
+ /** Fingerprint of whatever is on disk, or `null` if there is nothing readable. */
562
+ function readFingerprint(certPath) {
563
+ try {
564
+ return new node_crypto.X509Certificate((0, node_fs.readFileSync)(certPath)).fingerprint256;
565
+ } catch {
566
+ return null;
567
+ }
568
+ }
569
+ function decideRegeneration(paths, identity) {
570
+ if (!(0, node_fs.existsSync)(paths.certPath) || !(0, node_fs.existsSync)(paths.keyPath)) return "missing";
571
+ if (!(0, node_fs.existsSync)(paths.caCertPath) || !(0, node_fs.existsSync)(paths.caKeyPath)) return "no-local-ca";
572
+ try {
573
+ return evaluateExistingCert({
574
+ chainPem: (0, node_fs.readFileSync)(paths.certPath, "utf-8"),
575
+ keyPem: (0, node_fs.readFileSync)(paths.keyPath, "utf-8"),
576
+ caPem: (0, node_fs.readFileSync)(paths.caCertPath, "utf-8"),
577
+ identity,
578
+ now: /* @__PURE__ */ new Date()
579
+ });
580
+ } catch {
581
+ return "unreadable";
582
+ }
583
+ }
584
+ /**
585
+ * Build every byte in memory, then move the files into place. A crash
586
+ * mid-way leaves the previous material untouched; a crash between the
587
+ * moves leaves a key/certificate mismatch, which the evaluator reports as
588
+ * `key-mismatch` and heals on the next boot.
589
+ */
590
+ async function regenerate(paths, identity, commonName, validDays, newCa) {
591
+ const now = /* @__PURE__ */ new Date();
592
+ const ca = newCa ? await generateCa(now) : await loadCa((0, node_fs.readFileSync)(paths.caCertPath, "utf-8"), (0, node_fs.readFileSync)(paths.caKeyPath, "utf-8"));
593
+ const leaf = await issueLeaf(ca, identity, commonName, validDays, now);
594
+ const chainPem = `${leaf.certPem.trimEnd()}\n${ca.certPem.trimEnd()}\n`;
595
+ if (newCa) {
596
+ await (0, node_fs_promises.writeFile)(`${paths.caCertPath}.new`, ca.certPem, "utf-8");
597
+ await (0, node_fs_promises.writeFile)(`${paths.caKeyPath}.new`, ca.keyPem, {
598
+ encoding: "utf-8",
599
+ mode: 384
600
+ });
601
+ (0, node_fs.renameSync)(`${paths.caCertPath}.new`, paths.caCertPath);
602
+ (0, node_fs.renameSync)(`${paths.caKeyPath}.new`, paths.caKeyPath);
603
+ await (0, node_fs_promises.chmod)(paths.caKeyPath, 384);
604
+ }
605
+ await (0, node_fs_promises.writeFile)(`${paths.keyPath}.new`, leaf.keyPem, {
606
+ encoding: "utf-8",
607
+ mode: 384
608
+ });
609
+ await (0, node_fs_promises.writeFile)(`${paths.certPath}.new`, chainPem, "utf-8");
610
+ (0, node_fs.renameSync)(`${paths.keyPath}.new`, paths.keyPath);
611
+ (0, node_fs.renameSync)(`${paths.certPath}.new`, paths.certPath);
612
+ await (0, node_fs_promises.chmod)(paths.keyPath, 384);
613
+ }
614
+ function describe(paths, generated, reason, caRotated, previousFingerprintSha256, reissueError) {
615
+ const leaf = new node_crypto.X509Certificate((0, node_fs.readFileSync)(paths.certPath));
616
+ const ca = new node_crypto.X509Certificate((0, node_fs.readFileSync)(paths.caCertPath));
617
+ const san = leaf.subjectAltName ?? "";
618
+ return {
619
+ ...paths,
620
+ generated,
621
+ reason,
622
+ caRotated,
623
+ fingerprintSha256: leaf.fingerprint256,
624
+ previousFingerprintSha256,
625
+ caFingerprintSha256: ca.fingerprint256,
626
+ validTo: new Date(leaf.validTo).toISOString(),
627
+ sans: san === "" ? [] : san.split(", "),
628
+ reissueError
629
+ };
630
+ }
631
+ /**
632
+ * Load TLS cert+key from files. Returns Buffers suitable for Node.js TLS
633
+ * options. `certPath` is a full chain, so the listener presents the local
634
+ * root alongside the leaf.
635
+ */
636
+ function loadTlsCert(certPath, keyPath) {
637
+ return {
638
+ cert: (0, node_fs.readFileSync)(certPath),
639
+ key: (0, node_fs.readFileSync)(keyPath)
640
+ };
641
+ }
642
+ //#endregion
643
+ //#region src/tls/tls-status.ts
644
+ function tlsDir(dataDir) {
645
+ return (0, node_path.join)(dataDir, "tls");
646
+ }
647
+ function readTlsMode(dataDir) {
648
+ const marker = (0, node_path.join)(tlsDir(dataDir), "mode");
649
+ if ((0, node_fs.existsSync)(marker)) {
650
+ const raw = (0, node_fs.readFileSync)(marker, "utf-8").trim();
651
+ if (raw === "uploaded") return "uploaded";
652
+ if (raw === "disabled") return "disabled";
653
+ }
654
+ return (0, node_fs.existsSync)((0, node_path.join)(tlsDir(dataDir), "camstack.crt")) ? "generated" : "disabled";
655
+ }
656
+ function writeTlsMode(dataDir, mode) {
657
+ (0, node_fs.mkdirSync)(tlsDir(dataDir), { recursive: true });
658
+ (0, node_fs.writeFileSync)((0, node_path.join)(tlsDir(dataDir), "mode"), `${mode}\n`, "utf-8");
659
+ }
660
+ function readExtraSans(dataDir) {
661
+ const path = (0, node_path.join)(tlsDir(dataDir), "extra-sans.json");
662
+ if (!(0, node_fs.existsSync)(path)) return [];
663
+ try {
664
+ const parsed = JSON.parse((0, node_fs.readFileSync)(path, "utf-8"));
665
+ if (!Array.isArray(parsed)) return [];
666
+ return parsed.filter((entry) => typeof entry === "string" && entry.length > 0);
667
+ } catch {
668
+ return [];
669
+ }
670
+ }
671
+ function writeExtraSans(dataDir, sans) {
672
+ (0, node_fs.mkdirSync)(tlsDir(dataDir), { recursive: true });
673
+ (0, node_fs.writeFileSync)((0, node_path.join)(tlsDir(dataDir), "extra-sans.json"), `${JSON.stringify(sans)}\n`, "utf-8");
674
+ }
675
+ /** Where an upload's own CA is kept — never over the local CA's `camstack-ca.crt`. */
676
+ var UPLOADED_CA_FILE = "uploaded-ca.crt";
677
+ /** Every certificate in a PEM bundle, in order. */
678
+ function splitPemCertificates(pem) {
679
+ const blocks = pem.match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g);
680
+ return blocks === null ? [] : blocks.map((block) => `${block}\n`);
681
+ }
682
+ /**
683
+ * The certificate that signed `leaf`, from the upload itself: the CA the
684
+ * operator supplied, else the rest of the uploaded chain. `null` when the
685
+ * upload did not include it — and then nothing may stand in for it: the
686
+ * local CA did not sign an uploaded leaf, so handing it out as "the CA" would
687
+ * tell a client to trust a root that verifies nothing it is served.
688
+ */
689
+ function uploadedIssuer(dir, leaf, chainPem) {
690
+ const caPath = (0, node_path.join)(dir, UPLOADED_CA_FILE);
691
+ const candidates = [...(0, node_fs.existsSync)(caPath) ? splitPemCertificates((0, node_fs.readFileSync)(caPath, "utf-8")) : [], ...splitPemCertificates(chainPem).slice(1)];
692
+ for (const pem of candidates) try {
693
+ const cert = new node_crypto.X509Certificate(pem);
694
+ if (leaf.checkIssued(cert) && leaf.verify(cert.publicKey)) return {
695
+ pem,
696
+ cert
697
+ };
698
+ } catch {}
699
+ return null;
700
+ }
701
+ function generatedIssuer(dir) {
702
+ const caPath = (0, node_path.join)(dir, "camstack-ca.crt");
703
+ if (!(0, node_fs.existsSync)(caPath)) return null;
704
+ const pem = (0, node_fs.readFileSync)(caPath, "utf-8");
705
+ return {
706
+ pem,
707
+ cert: new node_crypto.X509Certificate(pem)
708
+ };
709
+ }
710
+ /**
711
+ * What the node's certificate is, and whether the listener serves it.
712
+ * `servedLeafFingerprint` is the leaf the HTTPS listener presents right now
713
+ * (`servedHttpsLeafFingerprint()`), or `null` when unknown; a restart is
714
+ * required exactly when the listener serves a different leaf than the one
715
+ * on disk — a measured fact, not a flag a mutation remembered to set.
716
+ */
717
+ function readTlsAccessStatus(dataDir, servedLeafFingerprint) {
718
+ const dir = tlsDir(dataDir);
719
+ const certPath = (0, node_path.join)(dir, "camstack.crt");
720
+ const mode = readTlsMode(dataDir);
721
+ if (!(0, node_fs.existsSync)(certPath)) return {
722
+ mode: "disabled",
723
+ leafFingerprintSha256: null,
724
+ caFingerprintSha256: null,
725
+ validTo: null,
726
+ sans: [],
727
+ caCertPem: (mode === "uploaded" ? null : generatedIssuer(dir))?.pem ?? null,
728
+ reissueError: null,
729
+ restartRequired: false
730
+ };
731
+ try {
732
+ const chainPem = (0, node_fs.readFileSync)(certPath, "utf-8");
733
+ const leaf = new node_crypto.X509Certificate(chainPem);
734
+ const ca = mode === "uploaded" ? uploadedIssuer(dir, leaf, chainPem) : generatedIssuer(dir);
735
+ const san = leaf.subjectAltName ?? "";
736
+ return {
737
+ mode,
738
+ leafFingerprintSha256: leaf.fingerprint256,
739
+ caFingerprintSha256: ca?.cert.fingerprint256 ?? null,
740
+ validTo: new Date(leaf.validTo).toISOString(),
741
+ sans: san === "" ? [] : san.split(", "),
742
+ caCertPem: ca?.pem ?? null,
743
+ reissueError: null,
744
+ restartRequired: servedLeafFingerprint !== null && servedLeafFingerprint !== leaf.fingerprint256
745
+ };
746
+ } catch {
747
+ return {
748
+ mode,
749
+ leafFingerprintSha256: null,
750
+ caFingerprintSha256: null,
751
+ validTo: null,
752
+ sans: [],
753
+ caCertPem: null,
754
+ reissueError: "Certificate on disk could not be parsed.",
755
+ restartRequired: false
756
+ };
757
+ }
758
+ }
759
+ //#endregion
760
+ //#region src/tls/boot-tls.ts
761
+ /**
762
+ * Decide what the listener serves at boot. The admin UI (Network → Local
763
+ * access) is the only way to set a certificate (D726): it either leaves the
764
+ * hub on its generated local-CA leaf (D227) or uploads one, recorded by the
765
+ * `tls/mode` marker. An uploaded certificate is served verbatim — running it
766
+ * through `ensureTlsCert` would replace it on the first restart, because a
767
+ * leaf the local root did not issue is one of that rule's reissue triggers.
768
+ */
769
+ async function prepareBootTls(dataDir, options) {
770
+ const certPath = (0, node_path.join)(dataDir, "tls", "camstack.crt");
771
+ const keyPath = (0, node_path.join)(dataDir, "tls", "camstack.key");
772
+ const marked = readTlsMode(dataDir);
773
+ if (marked === "uploaded" && (0, node_fs.existsSync)(certPath) && (0, node_fs.existsSync)(keyPath)) return {
774
+ mode: "uploaded",
775
+ pair: loadTlsCert(certPath, keyPath),
776
+ ensured: void 0,
777
+ uploadedMissing: false
778
+ };
779
+ const uploadedMissing = marked === "uploaded";
780
+ if (uploadedMissing) writeTlsMode(dataDir, "generated");
781
+ const ensured = await ensureTlsCert(dataDir, options);
782
+ return {
783
+ mode: "generated",
784
+ pair: loadTlsCert(ensured.certPath, ensured.keyPath),
785
+ ensured,
786
+ uploadedMissing
787
+ };
788
+ }
789
+ //#endregion
790
+ //#region src/tls/https-listener.ts
791
+ var SLOT_KEY = Symbol.for("camstack.tls.https-listener");
792
+ var EMPTY_SLOT = {
793
+ reload: null,
794
+ servedLeafFingerprint: null
795
+ };
796
+ function isSlot(value) {
797
+ if (typeof value !== "object" || value === null) return false;
798
+ if (!("reload" in value) || !("servedLeafFingerprint" in value)) return false;
799
+ const reload = value.reload;
800
+ const served = value.servedLeafFingerprint;
801
+ return (reload === null || typeof reload === "function") && (served === null || typeof served === "string");
802
+ }
803
+ function readSlot() {
804
+ const current = Reflect.get(globalThis, SLOT_KEY);
805
+ return isSlot(current) ? current : EMPTY_SLOT;
806
+ }
807
+ function writeSlot(next) {
808
+ Reflect.set(globalThis, SLOT_KEY, next);
809
+ }
810
+ /** SHA-256 fingerprint of the first certificate (the leaf) in a PEM chain. */
811
+ function leafFingerprintOf(chain) {
812
+ return new node_crypto.X509Certificate(chain).fingerprint256;
813
+ }
814
+ /**
815
+ * Called once by the server after its HTTPS listener is up, with the pair it
816
+ * was started on. From here on a certificate action swaps the served
817
+ * certificate in place (`setSecureContext`) — new handshakes get the new
818
+ * leaf, open connections keep theirs, nothing restarts.
819
+ */
820
+ function registerHttpsListener(server, pair) {
821
+ writeSlot({
822
+ reload: (next) => server.setSecureContext({
823
+ cert: next.cert,
824
+ key: next.key
825
+ }),
826
+ servedLeafFingerprint: leafFingerprintOf(pair.cert)
827
+ });
828
+ }
829
+ /** Forget the listener — on shutdown, and between specs. */
830
+ function clearHttpsListener() {
831
+ writeSlot(EMPTY_SLOT);
832
+ }
833
+ /**
834
+ * The leaf the HTTPS listener serves now, or `null` when this process has no
835
+ * registered listener (TLS off, or a process that does not own one) — in
836
+ * which case nobody can say, and `null` is the honest answer.
837
+ */
838
+ function servedHttpsLeafFingerprint() {
839
+ return readSlot().servedLeafFingerprint;
840
+ }
841
+ /** Serve `pair` from now on. Never throws: the outcome says what happened. */
842
+ function reloadHttpsListener(pair) {
843
+ const slot = readSlot();
844
+ if (slot.reload === null) return { kind: "no-listener" };
845
+ try {
846
+ const servedLeafFingerprint = leafFingerprintOf(pair.cert);
847
+ slot.reload(pair);
848
+ writeSlot({
849
+ reload: slot.reload,
850
+ servedLeafFingerprint
851
+ });
852
+ return {
853
+ kind: "reloaded",
854
+ servedLeafFingerprint
855
+ };
856
+ } catch (err) {
857
+ return {
858
+ kind: "failed",
859
+ error: err instanceof Error ? err.message : String(err)
860
+ };
861
+ }
862
+ }
863
+ //#endregion
864
+ //#region src/tls/uploaded-cert.ts
865
+ /**
866
+ * Operator-supplied material must parse, match its key, and carry
867
+ * `extendedKeyUsage = serverAuth` — the same leaf defects D227 refused
868
+ * to keep generating.
869
+ */
870
+ function validateUploadedTls(certPem, keyPem) {
871
+ let leaf;
872
+ try {
873
+ leaf = new node_crypto.X509Certificate(certPem);
874
+ } catch {
875
+ return {
876
+ ok: false,
877
+ error: "Certificate PEM could not be parsed."
878
+ };
879
+ }
880
+ try {
881
+ if (!leaf.checkPrivateKey((0, node_crypto.createPrivateKey)(keyPem))) return {
882
+ ok: false,
883
+ error: "Private key does not match the certificate."
884
+ };
885
+ } catch {
886
+ return {
887
+ ok: false,
888
+ error: "Private key PEM could not be parsed."
889
+ };
890
+ }
891
+ const eku = leaf.keyUsage;
892
+ if (eku === void 0 || !eku.includes("1.3.6.1.5.5.7.3.1")) return {
893
+ ok: false,
894
+ error: "Certificate is missing extendedKeyUsage = serverAuth."
895
+ };
896
+ return {
897
+ ok: true,
898
+ fingerprintSha256: leaf.fingerprint256,
899
+ validTo: new Date(leaf.validTo).toISOString()
900
+ };
901
+ }
902
+ //#endregion
903
+ //#region src/tls/tls-actions.ts
904
+ function withNewline(pem) {
905
+ return pem.endsWith("\n") ? pem : `${pem}\n`;
906
+ }
907
+ /**
908
+ * Store an operator's certificate. The leaf (or chain) and key replace the
909
+ * served pair; a CA, when given, goes to its own file. The local CA
910
+ * (`camstack-ca.crt` + key) is never touched — it did not sign the upload,
911
+ * and it is what "Revert to generated" and every device that trusts it
912
+ * still need.
913
+ */
914
+ async function storeUploadedCertificate(dataDir, input) {
915
+ const valid = validateUploadedTls(input.certPem, input.keyPem);
916
+ if (!valid.ok) throw new Error(valid.error);
917
+ const dir = (0, node_path.join)(dataDir, "tls");
918
+ await (0, node_fs_promises.mkdir)(dir, { recursive: true });
919
+ await (0, node_fs_promises.writeFile)((0, node_path.join)(dir, "camstack.crt"), withNewline(input.certPem));
920
+ await (0, node_fs_promises.writeFile)((0, node_path.join)(dir, "camstack.key"), withNewline(input.keyPem), { mode: 384 });
921
+ const caPath = (0, node_path.join)(dir, UPLOADED_CA_FILE);
922
+ if (input.caPem !== void 0 && input.caPem.trim() !== "") await (0, node_fs_promises.writeFile)(caPath, withNewline(input.caPem));
923
+ else (0, node_fs.rmSync)(caPath, { force: true });
924
+ writeTlsMode(dataDir, "uploaded");
925
+ }
926
+ /** Issue a new generated leaf under the local CA. Refused while an upload is served. */
927
+ async function regenerateCertificate(dataDir, options) {
928
+ if (readTlsMode(dataDir) === "uploaded") throw new Error("Cannot regenerate an uploaded certificate — revert to generated first.");
929
+ await reissueTlsLeaf(dataDir, options);
930
+ }
931
+ /** Drop the upload and serve the generated local-CA leaf again (D227). */
932
+ async function revertToGeneratedCertificate(dataDir, options) {
933
+ writeTlsMode(dataDir, "generated");
934
+ (0, node_fs.rmSync)((0, node_path.join)(dataDir, "tls", UPLOADED_CA_FILE), { force: true });
935
+ await ensureTlsCert(dataDir, options);
936
+ }
937
+ /**
938
+ * Put the pair on disk on the HTTPS listener. Called after every action, so
939
+ * "the certificate changed" and "clients see it" are the same moment.
940
+ */
941
+ function applyCertificateToListener(dataDir) {
942
+ const certPath = (0, node_path.join)(dataDir, "tls", "camstack.crt");
943
+ const keyPath = (0, node_path.join)(dataDir, "tls", "camstack.key");
944
+ if (!(0, node_fs.existsSync)(certPath) || !(0, node_fs.existsSync)(keyPath)) return {
945
+ kind: "failed",
946
+ error: `No certificate pair under ${(0, node_path.join)(dataDir, "tls")}`
947
+ };
948
+ return reloadHttpsListener(loadTlsCert(certPath, keyPath));
949
+ }
950
+ //#endregion
951
+ Object.defineProperty(exports, "CA_COMMON_NAME", {
952
+ enumerable: true,
953
+ get: function() {
954
+ return CA_COMMON_NAME;
955
+ }
956
+ });
957
+ Object.defineProperty(exports, "CA_VALIDITY_DAYS", {
958
+ enumerable: true,
959
+ get: function() {
960
+ return CA_VALIDITY_DAYS;
961
+ }
962
+ });
963
+ Object.defineProperty(exports, "DEFAULT_LAN_HTTP_PORT", {
964
+ enumerable: true,
965
+ get: function() {
966
+ return DEFAULT_LAN_HTTP_PORT;
967
+ }
968
+ });
969
+ Object.defineProperty(exports, "LEAF_RENEWAL_WINDOW_DAYS", {
970
+ enumerable: true,
971
+ get: function() {
972
+ return LEAF_RENEWAL_WINDOW_DAYS;
973
+ }
974
+ });
975
+ Object.defineProperty(exports, "MAX_LEAF_VALIDITY_DAYS", {
976
+ enumerable: true,
977
+ get: function() {
978
+ return MAX_LEAF_VALIDITY_DAYS;
979
+ }
980
+ });
981
+ Object.defineProperty(exports, "SERVER_AUTH_OID", {
982
+ enumerable: true,
983
+ get: function() {
984
+ return SERVER_AUTH_OID;
985
+ }
986
+ });
987
+ Object.defineProperty(exports, "UPLOADED_CA_FILE", {
988
+ enumerable: true,
989
+ get: function() {
990
+ return UPLOADED_CA_FILE;
991
+ }
992
+ });
993
+ Object.defineProperty(exports, "allFamiliesListenHost", {
994
+ enumerable: true,
995
+ get: function() {
996
+ return allFamiliesListenHost;
997
+ }
998
+ });
999
+ Object.defineProperty(exports, "applyCertificateToListener", {
1000
+ enumerable: true,
1001
+ get: function() {
1002
+ return applyCertificateToListener;
1003
+ }
1004
+ });
1005
+ Object.defineProperty(exports, "applyLanHttp", {
1006
+ enumerable: true,
1007
+ get: function() {
1008
+ return applyLanHttp;
1009
+ }
1010
+ });
1011
+ Object.defineProperty(exports, "bindPendingLanHttp", {
1012
+ enumerable: true,
1013
+ get: function() {
1014
+ return bindPendingLanHttp;
1015
+ }
1016
+ });
1017
+ Object.defineProperty(exports, "clearHttpsListener", {
1018
+ enumerable: true,
1019
+ get: function() {
1020
+ return clearHttpsListener;
1021
+ }
1022
+ });
1023
+ Object.defineProperty(exports, "closeLanHttp", {
1024
+ enumerable: true,
1025
+ get: function() {
1026
+ return closeLanHttp;
1027
+ }
1028
+ });
1029
+ Object.defineProperty(exports, "collectCertIdentity", {
1030
+ enumerable: true,
1031
+ get: function() {
1032
+ return collectCertIdentity;
1033
+ }
1034
+ });
1035
+ Object.defineProperty(exports, "ensureTlsCert", {
1036
+ enumerable: true,
1037
+ get: function() {
1038
+ return ensureTlsCert;
1039
+ }
1040
+ });
1041
+ Object.defineProperty(exports, "evaluateExistingCert", {
1042
+ enumerable: true,
1043
+ get: function() {
1044
+ return evaluateExistingCert;
1045
+ }
1046
+ });
1047
+ Object.defineProperty(exports, "leafFingerprintOf", {
1048
+ enumerable: true,
1049
+ get: function() {
1050
+ return leafFingerprintOf;
1051
+ }
1052
+ });
1053
+ Object.defineProperty(exports, "loadTlsCert", {
1054
+ enumerable: true,
1055
+ get: function() {
1056
+ return loadTlsCert;
1057
+ }
1058
+ });
1059
+ Object.defineProperty(exports, "prepareBootTls", {
1060
+ enumerable: true,
1061
+ get: function() {
1062
+ return prepareBootTls;
1063
+ }
1064
+ });
1065
+ Object.defineProperty(exports, "readExtraSans", {
1066
+ enumerable: true,
1067
+ get: function() {
1068
+ return readExtraSans;
1069
+ }
1070
+ });
1071
+ Object.defineProperty(exports, "readLanHttpState", {
1072
+ enumerable: true,
1073
+ get: function() {
1074
+ return readLanHttpState;
1075
+ }
1076
+ });
1077
+ Object.defineProperty(exports, "readTlsAccessStatus", {
1078
+ enumerable: true,
1079
+ get: function() {
1080
+ return readTlsAccessStatus;
1081
+ }
1082
+ });
1083
+ Object.defineProperty(exports, "readTlsMode", {
1084
+ enumerable: true,
1085
+ get: function() {
1086
+ return readTlsMode;
1087
+ }
1088
+ });
1089
+ Object.defineProperty(exports, "regenerateCertificate", {
1090
+ enumerable: true,
1091
+ get: function() {
1092
+ return regenerateCertificate;
1093
+ }
1094
+ });
1095
+ Object.defineProperty(exports, "registerHttpsListener", {
1096
+ enumerable: true,
1097
+ get: function() {
1098
+ return registerHttpsListener;
1099
+ }
1100
+ });
1101
+ Object.defineProperty(exports, "registerLanHttpHandler", {
1102
+ enumerable: true,
1103
+ get: function() {
1104
+ return registerLanHttpHandler;
1105
+ }
1106
+ });
1107
+ Object.defineProperty(exports, "reissueTlsLeaf", {
1108
+ enumerable: true,
1109
+ get: function() {
1110
+ return reissueTlsLeaf;
1111
+ }
1112
+ });
1113
+ Object.defineProperty(exports, "reloadHttpsListener", {
1114
+ enumerable: true,
1115
+ get: function() {
1116
+ return reloadHttpsListener;
1117
+ }
1118
+ });
1119
+ Object.defineProperty(exports, "revertToGeneratedCertificate", {
1120
+ enumerable: true,
1121
+ get: function() {
1122
+ return revertToGeneratedCertificate;
1123
+ }
1124
+ });
1125
+ Object.defineProperty(exports, "servedHttpsLeafFingerprint", {
1126
+ enumerable: true,
1127
+ get: function() {
1128
+ return servedHttpsLeafFingerprint;
1129
+ }
1130
+ });
1131
+ Object.defineProperty(exports, "splitPemCertificates", {
1132
+ enumerable: true,
1133
+ get: function() {
1134
+ return splitPemCertificates;
1135
+ }
1136
+ });
1137
+ Object.defineProperty(exports, "storeUploadedCertificate", {
1138
+ enumerable: true,
1139
+ get: function() {
1140
+ return storeUploadedCertificate;
1141
+ }
1142
+ });
1143
+ Object.defineProperty(exports, "validateUploadedTls", {
1144
+ enumerable: true,
1145
+ get: function() {
1146
+ return validateUploadedTls;
1147
+ }
1148
+ });
1149
+ Object.defineProperty(exports, "writeExtraSans", {
1150
+ enumerable: true,
1151
+ get: function() {
1152
+ return writeExtraSans;
1153
+ }
1154
+ });
1155
+ Object.defineProperty(exports, "writeTlsMode", {
1156
+ enumerable: true,
1157
+ get: function() {
1158
+ return writeTlsMode;
1159
+ }
1160
+ });