@camstack/system 1.2.274 → 1.2.276

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