@camstack/system 1.2.115 → 1.2.117

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 (62) hide show
  1. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  2. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  3. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  4. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  5. package/dist/builtins/alerts/alerts.addon.js +1 -1
  6. package/dist/builtins/alerts/alerts.addon.mjs +1 -1
  7. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +1 -1
  8. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +1 -1
  9. package/dist/builtins/console-logging/index.js +1 -1
  10. package/dist/builtins/console-logging/index.mjs +1 -1
  11. package/dist/builtins/core-blocks/core-blocks.addon.js +1 -1
  12. package/dist/builtins/core-blocks/core-blocks.addon.mjs +1 -1
  13. package/dist/builtins/device-manager/device-manager.addon.js +2 -2
  14. package/dist/builtins/device-manager/device-manager.addon.mjs +2 -2
  15. package/dist/builtins/doorbell/virtual-doorbell.addon.js +1 -1
  16. package/dist/builtins/doorbell/virtual-doorbell.addon.mjs +1 -1
  17. package/dist/builtins/hub-forwarder/index.js +1 -1
  18. package/dist/builtins/hub-forwarder/index.mjs +1 -1
  19. package/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  20. package/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  21. package/dist/builtins/local-auth/local-auth.addon.js +1 -1
  22. package/dist/builtins/local-auth/local-auth.addon.mjs +1 -1
  23. package/dist/builtins/local-network/ipv6-lan.d.ts +26 -0
  24. package/dist/builtins/local-network/local-hostname.d.ts +15 -0
  25. package/dist/builtins/local-network/local-network.addon.d.ts +59 -21
  26. package/dist/builtins/local-network/local-network.addon.js +369 -50
  27. package/dist/builtins/local-network/local-network.addon.mjs +365 -51
  28. package/dist/builtins/loki-logging/index.js +1 -1
  29. package/dist/builtins/loki-logging/index.mjs +1 -1
  30. package/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  31. package/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  32. package/dist/builtins/platform-probe/index.js +1 -1
  33. package/dist/builtins/platform-probe/index.mjs +1 -1
  34. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  35. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  36. package/dist/builtins/snapshot/index.js +1 -1
  37. package/dist/builtins/snapshot/index.mjs +1 -1
  38. package/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  39. package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  40. package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +2 -2
  41. package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +2 -2
  42. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  43. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  44. package/dist/builtins/system-config/system-config.addon.js +1 -1
  45. package/dist/builtins/system-config/system-config.addon.mjs +1 -1
  46. package/dist/builtins/winston-logging/index.js +1 -1
  47. package/dist/builtins/winston-logging/index.mjs +1 -1
  48. package/dist/{dist-Drb54SZD.mjs → dist-D4Vmj8iw.mjs} +151 -9
  49. package/dist/{dist-iAwSA2_f.js → dist-DMEGlqg6.js} +151 -9
  50. package/dist/http/lan-http-bind.d.ts +30 -0
  51. package/dist/index.d.ts +1 -0
  52. package/dist/index.js +30 -472
  53. package/dist/index.mjs +11 -468
  54. package/dist/lan-http-bind-DmgpFP6_.js +890 -0
  55. package/dist/lan-http-bind-jKrj6OjQ.mjs +752 -0
  56. package/dist/{retired-settings-keys-Dz5-7gjt.mjs → retired-settings-keys--aM_vGF9.mjs} +1 -1
  57. package/dist/{retired-settings-keys-OfhqQio4.js → retired-settings-keys-DET4YkAU.js} +1 -1
  58. package/dist/tls/cert-manager.d.ts +11 -0
  59. package/dist/tls/index.d.ts +3 -1
  60. package/dist/tls/tls-status.d.ts +16 -0
  61. package/dist/tls/uploaded-cert.d.ts +14 -0
  62. package/package.json +1 -1
@@ -0,0 +1,752 @@
1
+ import { X509Certificate, createPrivateKey, randomBytes } from "node:crypto";
2
+ import { chmod, copyFile, mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { execFile } from "node:child_process";
5
+ import { promisify } from "node:util";
6
+ import * as os from "node:os";
7
+ import { tmpdir } from "node:os";
8
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
9
+ import { createServer } from "node:http";
10
+ import { isIP } from "node:net";
11
+ //#region src/tls/cert-evaluation.ts
12
+ /**
13
+ * The regeneration rule (D227), as a pure function.
14
+ *
15
+ * `ensureTlsCert` reissues **only** when the material on disk cannot do
16
+ * its job. Never because it is old, never because the machine picked up
17
+ * an address the certificate does not need, never because a new build
18
+ * shipped. The decision is a function of (files on disk, machine
19
+ * identity, clock) alone, so the same inputs always produce the same
20
+ * answer — which is what makes a reissue happen once and then stop.
21
+ */
22
+ /** OID `id-kp-serverAuth`. Apple's trustd requires it on the leaf. */
23
+ var SERVER_AUTH_OID = "1.3.6.1.5.5.7.3.1";
24
+ /**
25
+ * Apple's `SecPolicyCheckOtherTrustValidityPeriod` ceiling is 825 days;
26
+ * the CA/Browser Forum's recommended maximum is 397. We sit at 397.
27
+ */
28
+ var MAX_LEAF_VALIDITY_DAYS = 397;
29
+ /** Reissue this long before the leaf dies, so nobody serves an expired one. */
30
+ var LEAF_RENEWAL_WINDOW_DAYS = 30;
31
+ /** A local root outlives many leaves — it is the anchor an operator trusts. */
32
+ var CA_VALIDITY_DAYS = 3650;
33
+ var MS_PER_DAY = 864e5;
34
+ /** Reasons that invalidate the root as well as the leaf. */
35
+ var REASONS_REQUIRING_NEW_CA = [
36
+ "missing",
37
+ "unreadable",
38
+ "no-local-ca",
39
+ "ca-expiring"
40
+ ];
41
+ function reasonRequiresNewCa(reason) {
42
+ return REASONS_REQUIRING_NEW_CA.includes(reason);
43
+ }
44
+ function parse(pem) {
45
+ try {
46
+ return new X509Certificate(pem);
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+ function daysBetween(from, to) {
52
+ return (to.getTime() - from.getTime()) / MS_PER_DAY;
53
+ }
54
+ function hasServerAuthEku(leaf) {
55
+ const eku = leaf.keyUsage;
56
+ return eku !== void 0 && eku.length === 1 && eku[0] === "1.3.6.1.5.5.7.3.1";
57
+ }
58
+ function keyMatches(leaf, keyPem) {
59
+ try {
60
+ return leaf.checkPrivateKey(createPrivateKey(keyPem));
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+ function coversIdentity(leaf, identity) {
66
+ for (const name of identity.requiredDnsNames) if (leaf.checkHost(name) === void 0) return false;
67
+ for (const ip of identity.requiredIpAddresses) if (leaf.checkIP(ip) === void 0) return false;
68
+ return true;
69
+ }
70
+ /**
71
+ * `null` when the material on disk is fit to keep serving.
72
+ *
73
+ * Order matters only for the quality of the reported reason; any
74
+ * non-null answer produces the same action.
75
+ */
76
+ function evaluateExistingCert(input) {
77
+ const leaf = parse(input.chainPem);
78
+ const ca = parse(input.caPem);
79
+ if (leaf === null || ca === null) return "unreadable";
80
+ if (daysBetween(input.now, new Date(ca.validTo)) < 427) return "ca-expiring";
81
+ if (!keyMatches(leaf, input.keyPem)) return "key-mismatch";
82
+ if (daysBetween(input.now, new Date(leaf.validTo)) < 30) return "expiring";
83
+ if (!hasServerAuthEku(leaf)) return "missing-server-auth-eku";
84
+ if (leaf.ca || !leaf.checkIssued(ca) || !leaf.verify(ca.publicKey)) return "not-issued-by-local-ca";
85
+ if (daysBetween(new Date(leaf.validFrom), new Date(leaf.validTo)) > 398) return "validity-too-long";
86
+ if (!coversIdentity(leaf, input.identity)) return "san-coverage-gap";
87
+ return null;
88
+ }
89
+ //#endregion
90
+ //#region src/tls/cert-identity.ts
91
+ /**
92
+ * What names and addresses the hub's certificate has to answer for.
93
+ *
94
+ * Split out of `cert-manager.ts` because it is pure and because the
95
+ * regeneration rule (D227) is decided entirely by the difference between
96
+ * *this* and what the certificate on disk already carries.
97
+ */
98
+ /**
99
+ * Interfaces whose addresses are certified but never gate a reissue:
100
+ * container bridges, VPN tunnels and mesh overlays hand out addresses
101
+ * that change without the hub moving.
102
+ */
103
+ var VOLATILE_INTERFACE_PREFIXES = [
104
+ "docker",
105
+ "br-",
106
+ "veth",
107
+ "virbr",
108
+ "cni",
109
+ "flannel",
110
+ "tun",
111
+ "utun",
112
+ "tap",
113
+ "wg",
114
+ "zt",
115
+ "tailscale",
116
+ "ppp",
117
+ "awdl",
118
+ "llw"
119
+ ];
120
+ /** A DNS name we are willing to hand to openssl. */
121
+ var DNS_NAME_PATTERN = /^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$/;
122
+ function isIpv4(value) {
123
+ return isIP(value) === 4;
124
+ }
125
+ function isIpv6(value) {
126
+ return isIP(value) === 6;
127
+ }
128
+ /**
129
+ * `fe80::/10` and `169.254.0.0/16`. An IPv6 link-local address needs a
130
+ * zone index to be usable and a SAN cannot carry one, so such an entry
131
+ * can never match anything — it is noise that makes the certificate look
132
+ * broader than it is.
133
+ */
134
+ function isLinkLocal(value) {
135
+ if (isIpv4(value)) return value.startsWith("169.254.");
136
+ if (!isIpv6(value)) return false;
137
+ const firstGroup = value.split(":")[0] ?? "";
138
+ if (firstGroup === "") return false;
139
+ const parsed = Number.parseInt(firstGroup, 16);
140
+ return Number.isFinite(parsed) && (parsed & 65472) === 65152;
141
+ }
142
+ /** `fc00::/7` — the IPv6 range that behaves like RFC 1918 does for v4. */
143
+ function isUniqueLocalIpv6(value) {
144
+ if (!isIpv6(value)) return false;
145
+ const firstGroup = value.split(":")[0] ?? "";
146
+ const parsed = Number.parseInt(firstGroup, 16);
147
+ return Number.isFinite(parsed) && (parsed & 65024) === 64512;
148
+ }
149
+ function isVolatileInterface(name) {
150
+ const lower = name.toLowerCase();
151
+ return VOLATILE_INTERFACE_PREFIXES.some((prefix) => lower.startsWith(prefix));
152
+ }
153
+ /**
154
+ * A global-scope IPv6 address is NOT a stable identity: SLAAC privacy
155
+ * extensions rotate temporary addresses roughly daily, and `os` gives us
156
+ * no way to tell a temporary address from a permanent one. Gating on
157
+ * one would reissue the certificate every day.
158
+ */
159
+ function isStableGateAddress(address) {
160
+ if (isLinkLocal(address)) return false;
161
+ if (isIpv4(address)) return true;
162
+ return isUniqueLocalIpv6(address);
163
+ }
164
+ function addSan(dns, ips, value) {
165
+ const trimmed = value.trim();
166
+ if (trimmed === "") return;
167
+ if (isIP(trimmed) !== 0) {
168
+ if (!isLinkLocal(trimmed)) ips.add(trimmed);
169
+ return;
170
+ }
171
+ if (DNS_NAME_PATTERN.test(trimmed)) dns.add(trimmed);
172
+ }
173
+ /**
174
+ * Snapshot the machine's identity. Called once per `ensureTlsCert`; the
175
+ * result is both the SAN list for a new leaf and the yardstick the
176
+ * existing leaf is measured against.
177
+ */
178
+ function collectCertIdentity(options) {
179
+ const dnsNames = /* @__PURE__ */ new Set();
180
+ const ipAddresses = new Set(["127.0.0.1", "::1"]);
181
+ const requiredDnsNames = /* @__PURE__ */ new Set();
182
+ const requiredIpAddresses = new Set(["127.0.0.1"]);
183
+ for (const name of [
184
+ "localhost",
185
+ options.commonName,
186
+ os.hostname()
187
+ ]) {
188
+ addSan(dnsNames, ipAddresses, name);
189
+ addSan(requiredDnsNames, requiredIpAddresses, name);
190
+ }
191
+ for (const [ifaceName, addrs] of Object.entries(os.networkInterfaces())) for (const addr of addrs ?? []) {
192
+ if (addr.internal) continue;
193
+ if (isLinkLocal(addr.address)) continue;
194
+ ipAddresses.add(addr.address);
195
+ if (isVolatileInterface(ifaceName)) continue;
196
+ if (isStableGateAddress(addr.address)) requiredIpAddresses.add(addr.address);
197
+ }
198
+ for (const san of options.extraSans) {
199
+ addSan(dnsNames, ipAddresses, san);
200
+ addSan(requiredDnsNames, requiredIpAddresses, san);
201
+ }
202
+ return {
203
+ dnsNames: [...dnsNames],
204
+ ipAddresses: [...ipAddresses],
205
+ requiredDnsNames: [...requiredDnsNames],
206
+ requiredIpAddresses: [...requiredIpAddresses]
207
+ };
208
+ }
209
+ //#endregion
210
+ //#region src/tls/cert-openssl.ts
211
+ /**
212
+ * The openssl invocations. Isolated so `cert-manager.ts` reads as policy
213
+ * and this file reads as mechanics.
214
+ */
215
+ var execFileAsync = promisify(execFile);
216
+ /** Subject of the local root. Distinct from the leaf's CN by construction. */
217
+ var CA_COMMON_NAME = "CamStack Local CA";
218
+ function sanValue(identity) {
219
+ const parts = [];
220
+ for (const dns of identity.dnsNames) parts.push(`DNS:${dns}`);
221
+ for (const ip of identity.ipAddresses) if (isIP(ip) !== 0) parts.push(`IP:${ip}`);
222
+ return parts.join(",");
223
+ }
224
+ /**
225
+ * A local root: 10 years, `pathlen:0` so it can sign leaves and nothing
226
+ * else, and **no EKU** — Apple rejects an anchor asserting
227
+ * `anyExtendedKeyUsage`, and a root with no EKU constrains nothing.
228
+ */
229
+ async function generateCa(tmpDir) {
230
+ const caCertPath = join(tmpDir, "ca.crt");
231
+ const caKeyPath = join(tmpDir, "ca.key");
232
+ await execFileAsync("openssl", [
233
+ "req",
234
+ "-x509",
235
+ "-newkey",
236
+ "rsa:2048",
237
+ "-nodes",
238
+ "-sha256",
239
+ "-days",
240
+ String(CA_VALIDITY_DAYS),
241
+ "-keyout",
242
+ caKeyPath,
243
+ "-out",
244
+ caCertPath,
245
+ "-subj",
246
+ `/CN=${CA_COMMON_NAME}`,
247
+ "-addext",
248
+ "basicConstraints=critical,CA:TRUE,pathlen:0",
249
+ "-addext",
250
+ "keyUsage=critical,keyCertSign,cRLSign",
251
+ "-addext",
252
+ "subjectKeyIdentifier=hash"
253
+ ]);
254
+ await chmod(caKeyPath, 384);
255
+ return {
256
+ caCertPath,
257
+ caKeyPath
258
+ };
259
+ }
260
+ /**
261
+ * A server leaf signed by the local root: `CA:FALSE`, and
262
+ * `extendedKeyUsage=serverAuth` — not `anyExtendedKeyUsage`, which
263
+ * Apple's `testAppTrustRoot_AnyEKU_AfterJul2019` asserts must fail.
264
+ */
265
+ async function issueLeaf(tmpDir, ca, identity, commonName, validDays) {
266
+ const keyPath = join(tmpDir, "leaf.key");
267
+ const csrPath = join(tmpDir, "leaf.csr");
268
+ const certPath = join(tmpDir, "leaf.crt");
269
+ const extPath = join(tmpDir, "leaf.ext");
270
+ await writeFile(extPath, [
271
+ "basicConstraints=critical,CA:FALSE",
272
+ "keyUsage=critical,digitalSignature,keyEncipherment",
273
+ "extendedKeyUsage=serverAuth",
274
+ "subjectKeyIdentifier=hash",
275
+ "authorityKeyIdentifier=keyid,issuer",
276
+ `subjectAltName=${sanValue(identity)}`,
277
+ ""
278
+ ].join("\n"), "utf-8");
279
+ await execFileAsync("openssl", [
280
+ "req",
281
+ "-new",
282
+ "-newkey",
283
+ "rsa:2048",
284
+ "-nodes",
285
+ "-sha256",
286
+ "-keyout",
287
+ keyPath,
288
+ "-out",
289
+ csrPath,
290
+ "-subj",
291
+ `/CN=${commonName}`
292
+ ]);
293
+ await execFileAsync("openssl", [
294
+ "x509",
295
+ "-req",
296
+ "-in",
297
+ csrPath,
298
+ "-CA",
299
+ ca.caCertPath,
300
+ "-CAkey",
301
+ ca.caKeyPath,
302
+ "-set_serial",
303
+ `0x00${randomBytes(16).toString("hex")}`,
304
+ "-days",
305
+ String(validDays),
306
+ "-sha256",
307
+ "-extfile",
308
+ extPath,
309
+ "-out",
310
+ certPath
311
+ ]);
312
+ await chmod(keyPath, 384);
313
+ await rm(csrPath, { force: true });
314
+ await rm(extPath, { force: true });
315
+ return {
316
+ certPath,
317
+ keyPath
318
+ };
319
+ }
320
+ //#endregion
321
+ //#region src/tls/cert-manager.ts
322
+ var DEFAULT_COMMON_NAME = "camstack.local";
323
+ /**
324
+ * Ensure the hub has a usable TLS identity under `<dataDir>/tls`, made of
325
+ * a long-lived local **root** (`camstack-ca.crt`) and a short **leaf**
326
+ * chained to it (`camstack.crt` = leaf + root, `camstack.key`).
327
+ *
328
+ * ## The regeneration rule (D227)
329
+ *
330
+ * Reissue happens when, and only when, the material on disk **cannot do
331
+ * its job**:
332
+ *
333
+ * - it is absent, unreadable, or the key does not match the certificate;
334
+ * - the root is absent (every pre-2026-08 install: one self-signed
335
+ * `CA:TRUE` leaf and no root) or is inside its renewal window;
336
+ * - the leaf is inside its 30-day renewal window;
337
+ * - the leaf lacks `extendedKeyUsage = serverAuth` — Apple's trustd
338
+ * rejects an app-supplied anchor without it;
339
+ * - the leaf is not actually issued by the root on disk;
340
+ * - the leaf's validity span exceeds {@link MAX_LEAF_VALIDITY_DAYS};
341
+ * - **a name or address the hub must answer for is missing from the SAN
342
+ * list** — a DHCP move, a new interface or a new hostname.
343
+ *
344
+ * And explicitly NOT when: the certificate names an address the machine
345
+ * no longer has (a superset still works — the check is one-directional),
346
+ * a volatile interface (docker/VPN/mesh) or a global-scope IPv6 address
347
+ * changed (SLAAC privacy addresses rotate daily), or a new build shipped.
348
+ *
349
+ * Every trigger is derived from the files plus the machine, so once a
350
+ * reissue clears them it clears them for good: the next boot returns
351
+ * `generated: false`. A certificate that moved on every boot would
352
+ * invalidate every trust an operator granted by hand — worse than the
353
+ * bugs this rule fixes.
354
+ *
355
+ * **The root is rotated only for root-level reasons.** SAN drift rotates
356
+ * the leaf alone, so trust granted to `camstack-ca.crt` survives every
357
+ * address change the hub will ever see.
358
+ */
359
+ async function ensureTlsCert(dataDir, options) {
360
+ const tlsDir = join(dataDir, "tls");
361
+ const paths = {
362
+ certPath: join(tlsDir, "camstack.crt"),
363
+ keyPath: join(tlsDir, "camstack.key"),
364
+ caCertPath: join(tlsDir, "camstack-ca.crt"),
365
+ caKeyPath: join(tlsDir, "camstack-ca.key")
366
+ };
367
+ const commonName = options?.commonName ?? DEFAULT_COMMON_NAME;
368
+ const validDays = Math.min(options?.validDays ?? 397, 397);
369
+ const identity = collectCertIdentity({
370
+ commonName,
371
+ extraSans: options?.extraSans ?? []
372
+ });
373
+ const reason = decideRegeneration(paths, identity);
374
+ if (reason === null) return describe(paths, false, null, false, null, null);
375
+ const previousFingerprint = readFingerprint(paths.certPath);
376
+ const caRotated = reasonRequiresNewCa(reason);
377
+ mkdirSync(tlsDir, { recursive: true });
378
+ try {
379
+ await regenerate(paths, identity, commonName, validDays, caRotated);
380
+ } catch (err) {
381
+ const message = err instanceof Error ? err.message : String(err);
382
+ if (!canKeepServing(paths)) throw err;
383
+ return describe(paths, false, null, false, null, message);
384
+ }
385
+ return describe(paths, true, reason, caRotated, previousFingerprint, null);
386
+ }
387
+ /**
388
+ * Operator "Regenerate": issue a new leaf under the existing local CA.
389
+ * Never rotates the root — trust granted to `camstack-ca.crt` survives.
390
+ */
391
+ async function reissueTlsLeaf(dataDir, options) {
392
+ const tlsDir = join(dataDir, "tls");
393
+ const paths = {
394
+ certPath: join(tlsDir, "camstack.crt"),
395
+ keyPath: join(tlsDir, "camstack.key"),
396
+ caCertPath: join(tlsDir, "camstack-ca.crt"),
397
+ caKeyPath: join(tlsDir, "camstack-ca.key")
398
+ };
399
+ if (!existsSync(paths.caCertPath) || !existsSync(paths.caKeyPath)) return ensureTlsCert(dataDir, options);
400
+ const commonName = options?.commonName ?? DEFAULT_COMMON_NAME;
401
+ const validDays = Math.min(options?.validDays ?? 397, 397);
402
+ const identity = collectCertIdentity({
403
+ commonName,
404
+ extraSans: options?.extraSans ?? []
405
+ });
406
+ const previousFingerprint = readFingerprint(paths.certPath);
407
+ mkdirSync(tlsDir, { recursive: true });
408
+ await regenerate(paths, identity, commonName, validDays, false);
409
+ return describe(paths, true, "san-coverage-gap", false, previousFingerprint, null);
410
+ }
411
+ /** True when the material already on disk can still terminate TLS. */
412
+ function canKeepServing(paths) {
413
+ if (!existsSync(paths.certPath) || !existsSync(paths.keyPath)) return false;
414
+ if (!existsSync(paths.caCertPath)) return false;
415
+ return readFingerprint(paths.certPath) !== null;
416
+ }
417
+ /** Fingerprint of whatever is on disk, or `null` if there is nothing readable. */
418
+ function readFingerprint(certPath) {
419
+ try {
420
+ return new X509Certificate(readFileSync(certPath)).fingerprint256;
421
+ } catch {
422
+ return null;
423
+ }
424
+ }
425
+ function decideRegeneration(paths, identity) {
426
+ if (!existsSync(paths.certPath) || !existsSync(paths.keyPath)) return "missing";
427
+ if (!existsSync(paths.caCertPath) || !existsSync(paths.caKeyPath)) return "no-local-ca";
428
+ try {
429
+ return evaluateExistingCert({
430
+ chainPem: readFileSync(paths.certPath, "utf-8"),
431
+ keyPem: readFileSync(paths.keyPath, "utf-8"),
432
+ caPem: readFileSync(paths.caCertPath, "utf-8"),
433
+ identity,
434
+ now: /* @__PURE__ */ new Date()
435
+ });
436
+ } catch {
437
+ return "unreadable";
438
+ }
439
+ }
440
+ /**
441
+ * Build every file in a scratch directory, then move them into place.
442
+ * A crash mid-way leaves the previous material untouched; a crash
443
+ * between the moves leaves a key/certificate mismatch, which the
444
+ * evaluator reports as `key-mismatch` and heals on the next boot.
445
+ */
446
+ async function regenerate(paths, identity, commonName, validDays, newCa) {
447
+ const scratch = await mkdtemp(join(tmpdir(), "camstack-tls-"));
448
+ try {
449
+ const ca = newCa ? await generateCa(scratch) : {
450
+ caCertPath: paths.caCertPath,
451
+ caKeyPath: paths.caKeyPath
452
+ };
453
+ const leaf = await issueLeaf(scratch, ca, identity, commonName, validDays);
454
+ const chainPath = join(scratch, "chain.crt");
455
+ await writeFile(chainPath, `${readFileSync(leaf.certPath, "utf-8").trimEnd()}\n${readFileSync(ca.caCertPath, "utf-8").trimEnd()}\n`, "utf-8");
456
+ if (newCa) {
457
+ await copyFile(ca.caCertPath, `${paths.caCertPath}.new`);
458
+ await copyFile(ca.caKeyPath, `${paths.caKeyPath}.new`);
459
+ renameSync(`${paths.caCertPath}.new`, paths.caCertPath);
460
+ renameSync(`${paths.caKeyPath}.new`, paths.caKeyPath);
461
+ await chmod(paths.caKeyPath, 384);
462
+ }
463
+ await copyFile(leaf.keyPath, `${paths.keyPath}.new`);
464
+ await copyFile(chainPath, `${paths.certPath}.new`);
465
+ renameSync(`${paths.keyPath}.new`, paths.keyPath);
466
+ renameSync(`${paths.certPath}.new`, paths.certPath);
467
+ await chmod(paths.keyPath, 384);
468
+ } finally {
469
+ await rm(scratch, {
470
+ recursive: true,
471
+ force: true
472
+ });
473
+ }
474
+ }
475
+ function describe(paths, generated, reason, caRotated, previousFingerprintSha256, reissueError) {
476
+ const leaf = new X509Certificate(readFileSync(paths.certPath));
477
+ const ca = new X509Certificate(readFileSync(paths.caCertPath));
478
+ const san = leaf.subjectAltName ?? "";
479
+ return {
480
+ ...paths,
481
+ generated,
482
+ reason,
483
+ caRotated,
484
+ fingerprintSha256: leaf.fingerprint256,
485
+ previousFingerprintSha256,
486
+ caFingerprintSha256: ca.fingerprint256,
487
+ validTo: new Date(leaf.validTo).toISOString(),
488
+ sans: san === "" ? [] : san.split(", "),
489
+ reissueError
490
+ };
491
+ }
492
+ /**
493
+ * Load TLS cert+key from files. Returns Buffers suitable for Node.js TLS
494
+ * options. `certPath` is a full chain, so the listener presents the local
495
+ * root alongside the leaf.
496
+ */
497
+ function loadTlsCert(certPath, keyPath) {
498
+ return {
499
+ cert: readFileSync(certPath),
500
+ key: readFileSync(keyPath)
501
+ };
502
+ }
503
+ //#endregion
504
+ //#region src/tls/uploaded-cert.ts
505
+ /**
506
+ * Operator-supplied material must parse, match its key, and carry
507
+ * `extendedKeyUsage = serverAuth` — the same leaf defects D227 refused
508
+ * to keep generating.
509
+ */
510
+ function validateUploadedTls(certPem, keyPem) {
511
+ let leaf;
512
+ try {
513
+ leaf = new X509Certificate(certPem);
514
+ } catch {
515
+ return {
516
+ ok: false,
517
+ error: "Certificate PEM could not be parsed."
518
+ };
519
+ }
520
+ try {
521
+ if (!leaf.checkPrivateKey(createPrivateKey(keyPem))) return {
522
+ ok: false,
523
+ error: "Private key does not match the certificate."
524
+ };
525
+ } catch {
526
+ return {
527
+ ok: false,
528
+ error: "Private key PEM could not be parsed."
529
+ };
530
+ }
531
+ const eku = leaf.keyUsage;
532
+ if (eku === void 0 || !eku.includes("1.3.6.1.5.5.7.3.1")) return {
533
+ ok: false,
534
+ error: "Certificate is missing extendedKeyUsage = serverAuth."
535
+ };
536
+ return {
537
+ ok: true,
538
+ fingerprintSha256: leaf.fingerprint256,
539
+ validTo: new Date(leaf.validTo).toISOString()
540
+ };
541
+ }
542
+ //#endregion
543
+ //#region src/tls/tls-status.ts
544
+ function tlsDir(dataDir) {
545
+ return join(dataDir, "tls");
546
+ }
547
+ function readTlsMode(dataDir) {
548
+ const marker = join(tlsDir(dataDir), "mode");
549
+ if (existsSync(marker)) {
550
+ const raw = readFileSync(marker, "utf-8").trim();
551
+ if (raw === "uploaded") return "uploaded";
552
+ if (raw === "disabled") return "disabled";
553
+ }
554
+ return existsSync(join(tlsDir(dataDir), "camstack.crt")) ? "generated" : "disabled";
555
+ }
556
+ function writeTlsMode(dataDir, mode) {
557
+ mkdirSync(tlsDir(dataDir), { recursive: true });
558
+ writeFileSync(join(tlsDir(dataDir), "mode"), `${mode}\n`, "utf-8");
559
+ }
560
+ function readExtraSans(dataDir) {
561
+ const path = join(tlsDir(dataDir), "extra-sans.json");
562
+ if (!existsSync(path)) return [];
563
+ try {
564
+ const parsed = JSON.parse(readFileSync(path, "utf-8"));
565
+ if (!Array.isArray(parsed)) return [];
566
+ return parsed.filter((entry) => typeof entry === "string" && entry.length > 0);
567
+ } catch {
568
+ return [];
569
+ }
570
+ }
571
+ function writeExtraSans(dataDir, sans) {
572
+ mkdirSync(tlsDir(dataDir), { recursive: true });
573
+ writeFileSync(join(tlsDir(dataDir), "extra-sans.json"), `${JSON.stringify(sans)}\n`, "utf-8");
574
+ }
575
+ function readTlsAccessStatus(dataDir, restartRequired = false) {
576
+ const dir = tlsDir(dataDir);
577
+ const certPath = join(dir, "camstack.crt");
578
+ const caPath = join(dir, "camstack-ca.crt");
579
+ const mode = readTlsMode(dataDir);
580
+ if (!existsSync(certPath)) return {
581
+ mode: "disabled",
582
+ leafFingerprintSha256: null,
583
+ caFingerprintSha256: null,
584
+ validTo: null,
585
+ sans: [],
586
+ caCertPem: existsSync(caPath) ? readFileSync(caPath, "utf-8") : null,
587
+ reissueError: null,
588
+ restartRequired
589
+ };
590
+ try {
591
+ const leaf = new X509Certificate(readFileSync(certPath));
592
+ const caPem = existsSync(caPath) ? readFileSync(caPath, "utf-8") : null;
593
+ const ca = caPem !== null ? new X509Certificate(caPem) : null;
594
+ const san = leaf.subjectAltName ?? "";
595
+ return {
596
+ mode,
597
+ leafFingerprintSha256: leaf.fingerprint256,
598
+ caFingerprintSha256: ca?.fingerprint256 ?? null,
599
+ validTo: new Date(leaf.validTo).toISOString(),
600
+ sans: san === "" ? [] : san.split(", "),
601
+ caCertPem: caPem,
602
+ reissueError: null,
603
+ restartRequired
604
+ };
605
+ } catch {
606
+ return {
607
+ mode,
608
+ leafFingerprintSha256: null,
609
+ caFingerprintSha256: null,
610
+ validTo: null,
611
+ sans: [],
612
+ caCertPem: null,
613
+ reissueError: "Certificate on disk could not be parsed.",
614
+ restartRequired
615
+ };
616
+ }
617
+ }
618
+ //#endregion
619
+ //#region src/http/lan-http-bind.ts
620
+ /**
621
+ * Second HTTP listener that shares the hub's existing request handler.
622
+ *
623
+ * Fastify is one protocol per instance; HTTPS stays on :4443 and this
624
+ * binds a plain `http.Server` that emits `request` AND `upgrade` onto the
625
+ * same handler graph (tRPC HTTP, cookies, data-plane, static, tRPC WS).
626
+ *
627
+ * Forwarding only `request` is not enough: the viewer speaks tRPC exclusively
628
+ * over WebSocket (`wsLink`). `/health` wins the LAN race, then `ws://…/trpc`
629
+ * hangs because nobody handles the upgrade on this socket.
630
+ */
631
+ var DEFAULT_HTTP_PORT = 4480;
632
+ var handlers = null;
633
+ var server = null;
634
+ var pending = null;
635
+ var state = {
636
+ listening: false,
637
+ error: null,
638
+ port: DEFAULT_HTTP_PORT
639
+ };
640
+ var boundRequestedHost = null;
641
+ var DEFAULT_LAN_HTTP_PORT = DEFAULT_HTTP_PORT;
642
+ /** Map "all IPv4" to dual-stack IPv6 (`::`, ipv6Only false) so IPv4 still works. */
643
+ function allFamiliesListenHost(host) {
644
+ if (host === "0.0.0.0" || host === "*" || host === "") return {
645
+ host: "::",
646
+ ipv6Only: false
647
+ };
648
+ return {
649
+ host,
650
+ ipv6Only: false
651
+ };
652
+ }
653
+ function registerLanHttpHandler(next) {
654
+ handlers = next;
655
+ }
656
+ function readLanHttpState() {
657
+ return state;
658
+ }
659
+ async function applyLanHttp(options) {
660
+ pending = options;
661
+ if (!options.enabled) {
662
+ await closeLanHttp();
663
+ state = {
664
+ listening: false,
665
+ error: null,
666
+ port: options.port
667
+ };
668
+ return state;
669
+ }
670
+ if (handlers === null) {
671
+ state = {
672
+ listening: false,
673
+ error: "HTTP listener is not registered yet",
674
+ port: options.port
675
+ };
676
+ return state;
677
+ }
678
+ if (server !== null && state.listening && (options.port === 0 || state.port === options.port) && boundRequestedHost === options.host) return state;
679
+ await closeLanHttp();
680
+ try {
681
+ const bound = await listenHttp(options.port, options.host, handlers);
682
+ server = bound;
683
+ boundRequestedHost = options.host;
684
+ const addr = bound.address();
685
+ state = {
686
+ listening: true,
687
+ error: null,
688
+ port: typeof addr === "object" && addr !== null ? addr.port : options.port
689
+ };
690
+ return state;
691
+ } catch (err) {
692
+ server = null;
693
+ state = {
694
+ listening: false,
695
+ error: err instanceof Error ? err.message : String(err),
696
+ port: options.port
697
+ };
698
+ return state;
699
+ }
700
+ }
701
+ /** After the hub registers the Fastify request handler, bind whatever was pending. */
702
+ async function bindPendingLanHttp() {
703
+ if (pending === null) return applyLanHttp({
704
+ enabled: true,
705
+ port: DEFAULT_HTTP_PORT,
706
+ host: "0.0.0.0"
707
+ });
708
+ return applyLanHttp(pending);
709
+ }
710
+ async function closeLanHttp() {
711
+ const current = server;
712
+ server = null;
713
+ boundRequestedHost = null;
714
+ if (current === null) return;
715
+ await new Promise((resolve) => {
716
+ current.close(() => resolve());
717
+ });
718
+ }
719
+ function listenHttp(port, host, next) {
720
+ const resolved = allFamiliesListenHost(host);
721
+ return listenOn(port, resolved, next).catch((err) => {
722
+ if (resolved.host === "::" && host !== "::") return listenOn(port, {
723
+ host: "0.0.0.0",
724
+ ipv6Only: false
725
+ }, next);
726
+ throw err;
727
+ });
728
+ }
729
+ function listenOn(port, bind, next) {
730
+ return new Promise((resolve, reject) => {
731
+ const created = createServer(next.onRequest);
732
+ created.on("upgrade", next.onUpgrade);
733
+ const onError = (err) => {
734
+ created.off("listening", onListening);
735
+ created.close();
736
+ reject(err);
737
+ };
738
+ const onListening = () => {
739
+ created.off("error", onError);
740
+ resolve(created);
741
+ };
742
+ created.once("error", onError);
743
+ created.once("listening", onListening);
744
+ created.listen({
745
+ port,
746
+ host: bind.host,
747
+ ipv6Only: bind.ipv6Only
748
+ });
749
+ });
750
+ }
751
+ //#endregion
752
+ export { evaluateExistingCert as C, SERVER_AUTH_OID as S, CA_COMMON_NAME as _, closeLanHttp as a, LEAF_RENEWAL_WINDOW_DAYS as b, readExtraSans as c, writeExtraSans as d, writeTlsMode as f, reissueTlsLeaf as g, loadTlsCert as h, bindPendingLanHttp as i, readTlsAccessStatus as l, ensureTlsCert as m, allFamiliesListenHost as n, readLanHttpState as o, validateUploadedTls as p, applyLanHttp as r, registerLanHttpHandler as s, DEFAULT_LAN_HTTP_PORT as t, readTlsMode as u, collectCertIdentity as v, MAX_LEAF_VALIDITY_DAYS as x, CA_VALIDITY_DAYS as y };