@camstack/system 1.2.382 → 1.2.384

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