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