@camstack/system 1.2.431 → 1.2.433

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 (97) hide show
  1. package/dist/{tls-C5IYg3V5.js → agent-https-CHZTxK-q.js} +123 -759
  2. package/dist/{tls-CpcGkeJV.mjs → agent-https-DtRU9A7I.mjs} +89 -611
  3. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  4. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  5. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  6. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  7. package/dist/builtins/alerts/alerts.addon.js +1 -1
  8. package/dist/builtins/alerts/alerts.addon.mjs +1 -1
  9. package/dist/builtins/autotrack/index.js +1 -1
  10. package/dist/builtins/autotrack/index.mjs +1 -1
  11. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  12. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  13. package/dist/builtins/calendars/calendars.addon.js +1 -1
  14. package/dist/builtins/calendars/calendars.addon.mjs +1 -1
  15. package/dist/builtins/camera-grid/index.js +1 -1
  16. package/dist/builtins/camera-grid/index.mjs +1 -1
  17. package/dist/builtins/composer/composer.addon.js +2 -2
  18. package/dist/builtins/composer/composer.addon.mjs +2 -2
  19. package/dist/builtins/console-logging/index.js +1 -1
  20. package/dist/builtins/console-logging/index.mjs +1 -1
  21. package/dist/builtins/core-blocks/core-blocks.addon.js +2 -2
  22. package/dist/builtins/core-blocks/core-blocks.addon.mjs +2 -2
  23. package/dist/builtins/device-manager/device-manager.addon.js +2 -2
  24. package/dist/builtins/device-manager/device-manager.addon.mjs +2 -2
  25. package/dist/builtins/hub-forwarder/index.js +1 -1
  26. package/dist/builtins/hub-forwarder/index.mjs +1 -1
  27. package/dist/builtins/keychain/index.js +3 -3
  28. package/dist/builtins/keychain/index.mjs +3 -3
  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 +2 -2
  32. package/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  33. package/dist/builtins/local-network/agent-mdns.d.ts +51 -0
  34. package/dist/builtins/local-network/local-network.addon.js +20 -45
  35. package/dist/builtins/local-network/local-network.addon.mjs +2 -28
  36. package/dist/builtins/loki-logging/index.js +1 -1
  37. package/dist/builtins/loki-logging/index.mjs +1 -1
  38. package/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  39. package/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  40. package/dist/builtins/platform-probe/index.js +1 -1
  41. package/dist/builtins/platform-probe/index.mjs +1 -1
  42. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  43. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  44. package/dist/builtins/snapshot/index.js +1 -1
  45. package/dist/builtins/snapshot/index.mjs +1 -1
  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/index.js +1 -1
  49. package/dist/builtins/sqlite-storage/index.mjs +1 -1
  50. package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  51. package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  52. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  53. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  54. package/dist/builtins/system-config/system-config.addon.js +1370 -28
  55. package/dist/builtins/system-config/system-config.addon.mjs +1344 -25
  56. package/dist/builtins/winston-logging/index.js +1 -1
  57. package/dist/builtins/winston-logging/index.mjs +1 -1
  58. package/dist/{composition-sources-Cw_TXEq9.mjs → composition-sources-8-cpAt1c.mjs} +1 -1
  59. package/dist/{composition-sources-o5MPSlk6.js → composition-sources-BgJWQMjr.js} +1 -1
  60. package/dist/{constants-BcNaVkvI.js → constants-Ah3T_KAW.js} +2 -2
  61. package/dist/{constants-CttE77VF.mjs → constants-Cg9ve13y.mjs} +2 -2
  62. package/dist/{device-ca-B-BTxeCj.mjs → device-ca-DUrcTW5h.mjs} +1 -1
  63. package/dist/{device-ca-CKiqh2Iu.js → device-ca-NNP4Jz0P.js} +1 -1
  64. package/dist/{dist-DxJdci75.js → dist-C6Yvfhpq.js} +360 -1
  65. package/dist/{dist-CXG6muCR.mjs → dist-DJnlnL7P.mjs} +349 -2
  66. package/dist/file-host-worker.js +1 -1
  67. package/dist/file-host-worker.mjs +1 -1
  68. package/dist/hub-mdns-ciao-8_Ed1Za5.mjs +648 -0
  69. package/dist/hub-mdns-ciao-B50jAU5C.js +821 -0
  70. package/dist/index.d.ts +3 -0
  71. package/dist/index.js +176 -67
  72. package/dist/index.mjs +96 -13
  73. package/dist/kernel/index.d.ts +5 -4
  74. package/dist/kernel/moleculer/agent-mesh-authenticator.d.ts +12 -1
  75. package/dist/kernel/moleculer/agent-ui-unlock.d.ts +40 -0
  76. package/dist/kernel/moleculer/mesh-authenticator.d.ts +6 -0
  77. package/dist/kernel/moleculer/mesh-mtls/constants.d.ts +1 -1
  78. package/dist/kernel/moleculer/mesh-mtls/index.d.ts +3 -2
  79. package/dist/kernel/moleculer/mesh-mtls/mesh-ca.d.ts +4 -0
  80. package/dist/kernel/moleculer/mesh-mtls/mesh-certificate-registry.d.ts +2 -2
  81. package/dist/kernel/moleculer/mesh-mtls/mesh-join-token.d.ts +3 -2
  82. package/dist/kernel/moleculer/mesh-mtls/mesh-peer-transport.d.ts +7 -0
  83. package/dist/kernel/moleculer/mesh-mtls/pairing/agent-pairing.d.ts +204 -0
  84. package/dist/kernel/moleculer/mesh-mtls/pairing/hub-pairing.d.ts +115 -0
  85. package/dist/kernel/moleculer/mesh-mtls/pairing/index.d.ts +3 -0
  86. package/dist/kernel/moleculer/mesh-mtls/pairing/pairing-protocol.d.ts +107 -0
  87. package/dist/kernel/moleculer/mesh-mtls/tls-tcp-transporter.d.ts +18 -0
  88. package/dist/{restore-archive-D_wBL1OO.mjs → restore-archive-C3_rzOCx.mjs} +1 -1
  89. package/dist/{restore-archive-CQJNoqRK.js → restore-archive-DqPaRjjY.js} +1 -1
  90. package/dist/{retired-settings-keys-EmDe11cP.mjs → retired-settings-keys-CAWHWDwy.mjs} +1 -1
  91. package/dist/{retired-settings-keys-g1oifXxR.js → retired-settings-keys-DJBQkZok.js} +1 -1
  92. package/dist/tls/agent-https-names.d.ts +2 -0
  93. package/dist/{wal-maintenance-vhPZLYuA.mjs → wal-maintenance-Bc38yI3r.mjs} +0 -0
  94. package/dist/{wal-maintenance-BW1LIHi0.js → wal-maintenance-CPLvZbzA.js} +0 -0
  95. package/package.json +1 -1
  96. package/dist/agent-https-names-CpUSuP4w.js +0 -120
  97. package/dist/agent-https-names-uetr4OQl.mjs +0 -91
@@ -2,142 +2,101 @@ import { a as KeyUsagesExtension, c as Pkcs10CertificateRequestGenerator, d as X
2
2
  import { X509Certificate, createHash, createPrivateKey, randomBytes, webcrypto } from "node:crypto";
3
3
  import { writeOwnerOnlyFileSync } from "@camstack/types/node";
4
4
  import { isIP } from "node:net";
5
- import { mkdir, writeFile } from "node:fs/promises";
6
5
  import { join } from "node:path";
7
6
  import * as os from "node:os";
8
- import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
9
- import { createServer as createServer$1 } from "node:http";
10
- //#region src/http/lan-http-bind.ts
11
- /**
12
- * Second HTTP listener that shares the hub's existing request handler.
13
- *
14
- * Fastify is one protocol per instance; HTTPS stays on :4443 and this
15
- * binds a plain `http.Server` that emits `request` AND `upgrade` onto the
16
- * same handler graph (tRPC HTTP, cookies, data-plane, static, tRPC WS).
17
- *
18
- * Forwarding only `request` is not enough: the viewer speaks tRPC exclusively
19
- * over WebSocket (`wsLink`). `/health` wins the LAN race, then `ws://…/trpc`
20
- * hangs because nobody handles the upgrade on this socket.
21
- */
22
- var DEFAULT_HTTP_PORT = 4480;
23
- var handlers = null;
24
- var server = null;
25
- var pending = null;
26
- var state = {
27
- listening: false,
28
- error: null,
29
- port: DEFAULT_HTTP_PORT
30
- };
31
- var boundRequestedHost = null;
32
- var DEFAULT_LAN_HTTP_PORT = DEFAULT_HTTP_PORT;
33
- /** Map "all IPv4" to dual-stack IPv6 (`::`, ipv6Only false) so IPv4 still works. */
34
- function allFamiliesListenHost(host) {
35
- if (host === "0.0.0.0" || host === "*" || host === "") return {
36
- host: "::",
37
- ipv6Only: false
38
- };
39
- return {
40
- host,
41
- ipv6Only: false
42
- };
43
- }
44
- function registerLanHttpHandler(next) {
45
- handlers = next;
46
- }
47
- function readLanHttpState() {
48
- return state;
49
- }
50
- async function applyLanHttp(options) {
51
- pending = options;
52
- if (!options.enabled) {
53
- await closeLanHttp();
54
- state = {
55
- listening: false,
56
- error: null,
57
- port: options.port
58
- };
59
- return state;
7
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
8
+ //#region src/tls/agent-https-names.ts
9
+ /**
10
+ * @durable class=config owner=system-config
11
+ * write="the hub records the names it signed into an agent's HTTPS leaf, replacing that
12
+ * node's previous row"
13
+ * retention="one row per node, replaced on every issue; a forgotten node's row stays until
14
+ * the node is issued again or an operator clears it (it only blocks reuse of its names)"
15
+ */
16
+ var AGENT_HTTPS_NAMES_COLLECTION = "agent_https_names";
17
+ var AGENT_HTTPS_NAMES_COLUMNS = [
18
+ {
19
+ name: "id",
20
+ type: "TEXT",
21
+ primaryKey: true,
22
+ notNull: true
23
+ },
24
+ {
25
+ name: "names",
26
+ type: "JSON",
27
+ notNull: true
28
+ },
29
+ {
30
+ name: "issuedAt",
31
+ type: "INTEGER",
32
+ notNull: true
60
33
  }
61
- if (handlers === null) {
62
- state = {
63
- listening: false,
64
- error: "HTTP listener is not registered yet",
65
- port: options.port
66
- };
67
- return state;
34
+ ];
35
+ var AgentHttpsNames = class {
36
+ store;
37
+ byNode = /* @__PURE__ */ new Map();
38
+ constructor(store) {
39
+ this.store = store;
68
40
  }
69
- if (server !== null && state.listening && (options.port === 0 || state.port === options.port) && boundRequestedHost === options.host) return state;
70
- await closeLanHttp();
71
- try {
72
- const bound = await listenHttp(options.port, options.host, handlers);
73
- server = bound;
74
- boundRequestedHost = options.host;
75
- const addr = bound.address();
76
- state = {
77
- listening: true,
78
- error: null,
79
- port: typeof addr === "object" && addr !== null ? addr.port : options.port
80
- };
81
- return state;
82
- } catch (err) {
83
- server = null;
84
- state = {
85
- listening: false,
86
- error: err instanceof Error ? err.message : String(err),
87
- port: options.port
88
- };
89
- return state;
41
+ async load() {
42
+ const rows = await this.store.query.query({ collection: AGENT_HTTPS_NAMES_COLLECTION });
43
+ for (const row of rows) {
44
+ const names = row.data["names"];
45
+ if (Array.isArray(names)) this.byNode.set(row.id, names.filter((n) => typeof n === "string").map((n) => n.toLowerCase()));
46
+ }
90
47
  }
91
- }
92
- /** After the hub registers the Fastify request handler, bind whatever was pending. */
93
- async function bindPendingLanHttp() {
94
- if (pending === null) return applyLanHttp({
95
- enabled: true,
96
- port: DEFAULT_HTTP_PORT,
97
- host: "0.0.0.0"
98
- });
99
- return applyLanHttp(pending);
100
- }
101
- async function closeLanHttp() {
102
- const current = server;
103
- server = null;
104
- boundRequestedHost = null;
105
- if (current === null) return;
106
- await new Promise((resolve) => {
107
- current.close(() => resolve());
108
- });
109
- }
110
- function listenHttp(port, host, next) {
111
- const resolved = allFamiliesListenHost(host);
112
- return listenOn(port, resolved, next).catch((err) => {
113
- if (resolved.host === "::" && host !== "::") return listenOn(port, {
114
- host: "0.0.0.0",
115
- ipv6Only: false
116
- }, next);
117
- throw err;
118
- });
119
- }
120
- function listenOn(port, bind, next) {
121
- return new Promise((resolve, reject) => {
122
- const created = createServer$1(next.onRequest);
123
- created.on("upgrade", next.onUpgrade);
124
- const onError = (err) => {
125
- created.off("listening", onListening);
126
- created.close();
127
- reject(err);
128
- };
129
- const onListening = () => {
130
- created.off("error", onError);
131
- resolve(created);
48
+ /** The names certified to `nodeId` (its id and the address of its live mesh socket), or `null`. */
49
+ namesOf(nodeId) {
50
+ return this.byNode.get(nodeId) ?? null;
51
+ }
52
+ /** Every name certified to a node other than `nodeId`. */
53
+ takenByOthers(nodeId) {
54
+ const out = /* @__PURE__ */ new Set();
55
+ for (const [id, names] of this.byNode) {
56
+ if (id === nodeId) continue;
57
+ for (const n of names) out.add(n);
58
+ }
59
+ return out;
60
+ }
61
+ /** Free every name certified to a node that was forgotten. */
62
+ async release(nodeId) {
63
+ if (!this.byNode.delete(nodeId)) return false;
64
+ await this.store.delete.mutate({
65
+ collection: AGENT_HTTPS_NAMES_COLLECTION,
66
+ key: nodeId
67
+ });
68
+ return true;
69
+ }
70
+ async record(nodeId, names) {
71
+ const lowered = names.map((n) => n.toLowerCase());
72
+ const existed = this.byNode.has(nodeId);
73
+ this.byNode.set(nodeId, lowered);
74
+ const data = {
75
+ names: lowered,
76
+ issuedAt: Date.now()
132
77
  };
133
- created.once("error", onError);
134
- created.once("listening", onListening);
135
- created.listen({
136
- port,
137
- host: bind.host,
138
- ipv6Only: bind.ipv6Only
78
+ if (existed) await this.store.update.mutate({
79
+ collection: AGENT_HTTPS_NAMES_COLLECTION,
80
+ id: nodeId,
81
+ data
139
82
  });
140
- });
83
+ else await this.store.insert.mutate({
84
+ collection: AGENT_HTTPS_NAMES_COLLECTION,
85
+ record: {
86
+ id: nodeId,
87
+ data
88
+ }
89
+ });
90
+ }
91
+ };
92
+ var SLOT = Symbol.for("camstack.agent-https.names");
93
+ function setProcessAgentHttpsNames(names) {
94
+ if (names === null) Reflect.deleteProperty(globalThis, SLOT);
95
+ else Reflect.set(globalThis, SLOT, names);
96
+ }
97
+ function getProcessAgentHttpsNames() {
98
+ const value = Reflect.get(globalThis, SLOT);
99
+ return value !== null && typeof value === "object" && typeof Reflect.get(value, "takenByOthers") === "function" ? value : null;
141
100
  }
142
101
  //#endregion
143
102
  //#region src/tls/cert-evaluation.ts
@@ -487,487 +446,6 @@ async function issueLeafFromCsr(ca, csrPem, identity, commonName, validDays, now
487
446
  }));
488
447
  }
489
448
  //#endregion
490
- //#region src/tls/cert-manager.ts
491
- var DEFAULT_COMMON_NAME = "camstack.local";
492
- /**
493
- * Ensure the hub has a usable TLS identity under `<dataDir>/tls`, made of
494
- * a long-lived local **root** (`camstack-ca.crt`) and a short **leaf**
495
- * chained to it (`camstack.crt` = leaf + root, `camstack.key`).
496
- *
497
- * ## The regeneration rule (D227)
498
- *
499
- * Reissue happens when, and only when, the material on disk **cannot do
500
- * its job**:
501
- *
502
- * - it is absent, unreadable, or the key does not match the certificate;
503
- * - the root is absent (every pre-2026-08 install: one self-signed
504
- * `CA:TRUE` leaf and no root) or is inside its renewal window;
505
- * - the leaf is inside its 30-day renewal window;
506
- * - the leaf lacks `extendedKeyUsage = serverAuth` — Apple's trustd
507
- * rejects an app-supplied anchor without it;
508
- * - the leaf is not actually issued by the root on disk;
509
- * - the leaf's validity span exceeds {@link MAX_LEAF_VALIDITY_DAYS};
510
- * - **a name or address the hub must answer for is missing from the SAN
511
- * list** — a DHCP move, a new interface or a new hostname.
512
- *
513
- * And explicitly NOT when: the certificate names an address the machine
514
- * no longer has (a superset still works — the check is one-directional),
515
- * a volatile interface (docker/VPN/mesh) or **any** IPv6 address changed
516
- * (global and ULA both rotate under privacy extensions / interface-id
517
- * churn — `os` cannot tell temporary from permanent), or a new build shipped.
518
- *
519
- * Every trigger is derived from the files plus the machine, so once a
520
- * reissue clears them it clears them for good: the next boot returns
521
- * `generated: false`. A certificate that moved on every boot would
522
- * invalidate every trust an operator granted by hand — worse than the
523
- * bugs this rule fixes.
524
- *
525
- * **The root is rotated only for root-level reasons.** SAN drift rotates
526
- * the leaf alone, so trust granted to `camstack-ca.crt` survives every
527
- * address change the hub will ever see.
528
- */
529
- async function ensureTlsCert(dataDir, options) {
530
- const tlsDir = join(dataDir, "tls");
531
- const paths = {
532
- certPath: join(tlsDir, "camstack.crt"),
533
- keyPath: join(tlsDir, "camstack.key"),
534
- caCertPath: join(tlsDir, "camstack-ca.crt"),
535
- caKeyPath: join(tlsDir, "camstack-ca.key")
536
- };
537
- const commonName = options?.commonName ?? DEFAULT_COMMON_NAME;
538
- const validDays = Math.min(options?.validDays ?? 397, 397);
539
- const identity = collectCertIdentity({
540
- commonName,
541
- extraSans: options?.extraSans ?? [],
542
- ...options?.hostFacts === void 0 ? {} : { hostFacts: options.hostFacts }
543
- });
544
- const reason = decideRegeneration(paths, identity);
545
- if (reason === null) return describe(paths, false, null, false, null, null);
546
- const previousFingerprint = readFingerprint(paths.certPath);
547
- const caRotated = reasonRequiresNewCa(reason);
548
- mkdirSync(tlsDir, { recursive: true });
549
- try {
550
- await regenerate(paths, identity, commonName, validDays, caRotated);
551
- } catch (err) {
552
- const message = err instanceof Error ? err.message : String(err);
553
- if (!canKeepServing(paths)) throw err;
554
- return describe(paths, false, null, false, null, message);
555
- }
556
- return describe(paths, true, reason, caRotated, previousFingerprint, null);
557
- }
558
- /**
559
- * Operator "Regenerate": issue a new leaf under the existing local CA.
560
- * Never rotates the root — trust granted to `camstack-ca.crt` survives.
561
- */
562
- async function reissueTlsLeaf(dataDir, options) {
563
- const tlsDir = join(dataDir, "tls");
564
- const paths = {
565
- certPath: join(tlsDir, "camstack.crt"),
566
- keyPath: join(tlsDir, "camstack.key"),
567
- caCertPath: join(tlsDir, "camstack-ca.crt"),
568
- caKeyPath: join(tlsDir, "camstack-ca.key")
569
- };
570
- if (!existsSync(paths.caCertPath) || !existsSync(paths.caKeyPath)) return ensureTlsCert(dataDir, options);
571
- const commonName = options?.commonName ?? DEFAULT_COMMON_NAME;
572
- const validDays = Math.min(options?.validDays ?? 397, 397);
573
- const identity = collectCertIdentity({
574
- commonName,
575
- extraSans: options?.extraSans ?? [],
576
- ...options?.hostFacts === void 0 ? {} : { hostFacts: options.hostFacts }
577
- });
578
- const previousFingerprint = readFingerprint(paths.certPath);
579
- mkdirSync(tlsDir, { recursive: true });
580
- await regenerate(paths, identity, commonName, validDays, false);
581
- return describe(paths, true, "san-coverage-gap", false, previousFingerprint, null);
582
- }
583
- /** True when the material already on disk can still terminate TLS. */
584
- function canKeepServing(paths) {
585
- if (!existsSync(paths.certPath) || !existsSync(paths.keyPath)) return false;
586
- if (!existsSync(paths.caCertPath)) return false;
587
- return readFingerprint(paths.certPath) !== null;
588
- }
589
- /** Fingerprint of whatever is on disk, or `null` if there is nothing readable. */
590
- function readFingerprint(certPath) {
591
- try {
592
- return new X509Certificate(readFileSync(certPath)).fingerprint256;
593
- } catch {
594
- return null;
595
- }
596
- }
597
- function decideRegeneration(paths, identity) {
598
- if (!existsSync(paths.certPath) || !existsSync(paths.keyPath)) return "missing";
599
- if (!existsSync(paths.caCertPath) || !existsSync(paths.caKeyPath)) return "no-local-ca";
600
- try {
601
- return evaluateExistingCert({
602
- chainPem: readFileSync(paths.certPath, "utf-8"),
603
- keyPem: readFileSync(paths.keyPath, "utf-8"),
604
- caPem: readFileSync(paths.caCertPath, "utf-8"),
605
- identity,
606
- now: /* @__PURE__ */ new Date()
607
- });
608
- } catch {
609
- return "unreadable";
610
- }
611
- }
612
- /**
613
- * Build every byte in memory, then move the files into place. A crash
614
- * mid-way leaves the previous material untouched; a crash between the
615
- * moves leaves a key/certificate mismatch, which the evaluator reports as
616
- * `key-mismatch` and heals on the next boot.
617
- */
618
- async function regenerate(paths, identity, commonName, validDays, newCa) {
619
- const now = /* @__PURE__ */ new Date();
620
- const ca = newCa ? await generateCa(now) : await loadCa(readFileSync(paths.caCertPath, "utf-8"), readFileSync(paths.caKeyPath, "utf-8"));
621
- const leaf = await issueLeaf(ca, identity, commonName, validDays, now);
622
- const chainPem = `${leaf.certPem.trimEnd()}\n${ca.certPem.trimEnd()}\n`;
623
- if (newCa) {
624
- await writeFile(`${paths.caCertPath}.new`, ca.certPem, "utf-8");
625
- writeOwnerOnlyFileSync(`${paths.caKeyPath}.new`, ca.keyPem);
626
- renameSync(`${paths.caCertPath}.new`, paths.caCertPath);
627
- renameSync(`${paths.caKeyPath}.new`, paths.caKeyPath);
628
- }
629
- writeOwnerOnlyFileSync(`${paths.keyPath}.new`, leaf.keyPem);
630
- await writeFile(`${paths.certPath}.new`, chainPem, "utf-8");
631
- renameSync(`${paths.keyPath}.new`, paths.keyPath);
632
- renameSync(`${paths.certPath}.new`, paths.certPath);
633
- }
634
- function describe(paths, generated, reason, caRotated, previousFingerprintSha256, reissueError) {
635
- const leaf = new X509Certificate(readFileSync(paths.certPath));
636
- const ca = new X509Certificate(readFileSync(paths.caCertPath));
637
- const san = leaf.subjectAltName ?? "";
638
- return {
639
- ...paths,
640
- generated,
641
- reason,
642
- caRotated,
643
- fingerprintSha256: leaf.fingerprint256,
644
- previousFingerprintSha256,
645
- caFingerprintSha256: ca.fingerprint256,
646
- validTo: new Date(leaf.validTo).toISOString(),
647
- sans: san === "" ? [] : san.split(", "),
648
- reissueError
649
- };
650
- }
651
- /**
652
- * Load TLS cert+key from files. Returns Buffers suitable for Node.js TLS
653
- * options. `certPath` is a full chain, so the listener presents the local
654
- * root alongside the leaf.
655
- */
656
- function loadTlsCert(certPath, keyPath) {
657
- return {
658
- cert: readFileSync(certPath),
659
- key: readFileSync(keyPath)
660
- };
661
- }
662
- //#endregion
663
- //#region src/tls/tls-status.ts
664
- function tlsDir(dataDir) {
665
- return join(dataDir, "tls");
666
- }
667
- function readTlsMode(dataDir) {
668
- const marker = join(tlsDir(dataDir), "mode");
669
- if (existsSync(marker)) {
670
- const raw = readFileSync(marker, "utf-8").trim();
671
- if (raw === "uploaded") return "uploaded";
672
- if (raw === "disabled") return "disabled";
673
- }
674
- return existsSync(join(tlsDir(dataDir), "camstack.crt")) ? "generated" : "disabled";
675
- }
676
- function writeTlsMode(dataDir, mode) {
677
- mkdirSync(tlsDir(dataDir), { recursive: true });
678
- writeFileSync(join(tlsDir(dataDir), "mode"), `${mode}\n`, "utf-8");
679
- }
680
- function readExtraSans(dataDir) {
681
- const path = join(tlsDir(dataDir), "extra-sans.json");
682
- if (!existsSync(path)) return [];
683
- try {
684
- const parsed = JSON.parse(readFileSync(path, "utf-8"));
685
- if (!Array.isArray(parsed)) return [];
686
- return parsed.filter((entry) => typeof entry === "string" && entry.length > 0);
687
- } catch {
688
- return [];
689
- }
690
- }
691
- function writeExtraSans(dataDir, sans) {
692
- mkdirSync(tlsDir(dataDir), { recursive: true });
693
- writeFileSync(join(tlsDir(dataDir), "extra-sans.json"), `${JSON.stringify(sans)}\n`, "utf-8");
694
- }
695
- /** Where an upload's own CA is kept — never over the local CA's `camstack-ca.crt`. */
696
- var UPLOADED_CA_FILE = "uploaded-ca.crt";
697
- /** Every certificate in a PEM bundle, in order. */
698
- function splitPemCertificates(pem) {
699
- const blocks = pem.match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g);
700
- return blocks === null ? [] : blocks.map((block) => `${block}\n`);
701
- }
702
- /**
703
- * The certificate that signed `leaf`, from the upload itself: the CA the
704
- * operator supplied, else the rest of the uploaded chain. `null` when the
705
- * upload did not include it — and then nothing may stand in for it: the
706
- * local CA did not sign an uploaded leaf, so handing it out as "the CA" would
707
- * tell a client to trust a root that verifies nothing it is served.
708
- */
709
- function uploadedIssuer(dir, leaf, chainPem) {
710
- const caPath = join(dir, UPLOADED_CA_FILE);
711
- const candidates = [...existsSync(caPath) ? splitPemCertificates(readFileSync(caPath, "utf-8")) : [], ...splitPemCertificates(chainPem).slice(1)];
712
- for (const pem of candidates) try {
713
- const cert = new X509Certificate(pem);
714
- if (leaf.checkIssued(cert) && leaf.verify(cert.publicKey)) return {
715
- pem,
716
- cert
717
- };
718
- } catch {}
719
- return null;
720
- }
721
- function generatedIssuer(dir) {
722
- const caPath = join(dir, "camstack-ca.crt");
723
- if (!existsSync(caPath)) return null;
724
- const pem = readFileSync(caPath, "utf-8");
725
- return {
726
- pem,
727
- cert: new X509Certificate(pem)
728
- };
729
- }
730
- /**
731
- * What the node's certificate is, and whether the listener serves it.
732
- * `servedLeafFingerprint` is the leaf the HTTPS listener presents right now
733
- * (`servedHttpsLeafFingerprint()`), or `null` when unknown; a restart is
734
- * required exactly when the listener serves a different leaf than the one
735
- * on disk — a measured fact, not a flag a mutation remembered to set.
736
- */
737
- function readTlsAccessStatus(dataDir, servedLeafFingerprint) {
738
- const dir = tlsDir(dataDir);
739
- const certPath = join(dir, "camstack.crt");
740
- const mode = readTlsMode(dataDir);
741
- if (!existsSync(certPath)) return {
742
- mode: "disabled",
743
- leafFingerprintSha256: null,
744
- caFingerprintSha256: null,
745
- validTo: null,
746
- sans: [],
747
- caCertPem: (mode === "uploaded" ? null : generatedIssuer(dir))?.pem ?? null,
748
- reissueError: null,
749
- restartRequired: false
750
- };
751
- try {
752
- const chainPem = readFileSync(certPath, "utf-8");
753
- const leaf = new X509Certificate(chainPem);
754
- const ca = mode === "uploaded" ? uploadedIssuer(dir, leaf, chainPem) : generatedIssuer(dir);
755
- const san = leaf.subjectAltName ?? "";
756
- return {
757
- mode,
758
- leafFingerprintSha256: leaf.fingerprint256,
759
- caFingerprintSha256: ca?.cert.fingerprint256 ?? null,
760
- validTo: new Date(leaf.validTo).toISOString(),
761
- sans: san === "" ? [] : san.split(", "),
762
- caCertPem: ca?.pem ?? null,
763
- reissueError: null,
764
- restartRequired: servedLeafFingerprint !== null && servedLeafFingerprint !== leaf.fingerprint256
765
- };
766
- } catch {
767
- return {
768
- mode,
769
- leafFingerprintSha256: null,
770
- caFingerprintSha256: null,
771
- validTo: null,
772
- sans: [],
773
- caCertPem: null,
774
- reissueError: "Certificate on disk could not be parsed.",
775
- restartRequired: false
776
- };
777
- }
778
- }
779
- //#endregion
780
- //#region src/tls/boot-tls.ts
781
- /**
782
- * Decide what the listener serves at boot. The admin UI (Network → Local
783
- * access) is the only way to set a certificate (D726): it either leaves the
784
- * hub on its generated local-CA leaf (D227) or uploads one, recorded by the
785
- * `tls/mode` marker. An uploaded certificate is served verbatim — running it
786
- * through `ensureTlsCert` would replace it on the first restart, because a
787
- * leaf the local root did not issue is one of that rule's reissue triggers.
788
- */
789
- async function prepareBootTls(dataDir, options) {
790
- const certPath = join(dataDir, "tls", "camstack.crt");
791
- const keyPath = join(dataDir, "tls", "camstack.key");
792
- const marked = readTlsMode(dataDir);
793
- if (marked === "uploaded" && existsSync(certPath) && existsSync(keyPath)) return {
794
- mode: "uploaded",
795
- pair: loadTlsCert(certPath, keyPath),
796
- ensured: void 0,
797
- uploadedMissing: false
798
- };
799
- const uploadedMissing = marked === "uploaded";
800
- if (uploadedMissing) writeTlsMode(dataDir, "generated");
801
- const ensured = await ensureTlsCert(dataDir, options);
802
- return {
803
- mode: "generated",
804
- pair: loadTlsCert(ensured.certPath, ensured.keyPath),
805
- ensured,
806
- uploadedMissing
807
- };
808
- }
809
- //#endregion
810
- //#region src/tls/https-listener.ts
811
- var SLOT_KEY = Symbol.for("camstack.tls.https-listener");
812
- var EMPTY_SLOT = {
813
- reload: null,
814
- servedLeafFingerprint: null
815
- };
816
- function isSlot(value) {
817
- if (typeof value !== "object" || value === null) return false;
818
- if (!("reload" in value) || !("servedLeafFingerprint" in value)) return false;
819
- const reload = value.reload;
820
- const served = value.servedLeafFingerprint;
821
- return (reload === null || typeof reload === "function") && (served === null || typeof served === "string");
822
- }
823
- function readSlot() {
824
- const current = Reflect.get(globalThis, SLOT_KEY);
825
- return isSlot(current) ? current : EMPTY_SLOT;
826
- }
827
- function writeSlot(next) {
828
- Reflect.set(globalThis, SLOT_KEY, next);
829
- }
830
- /** SHA-256 fingerprint of the first certificate (the leaf) in a PEM chain. */
831
- function leafFingerprintOf(chain) {
832
- return new X509Certificate(chain).fingerprint256;
833
- }
834
- /**
835
- * Called once by the server after its HTTPS listener is up, with the pair it
836
- * was started on. From here on a certificate action swaps the served
837
- * certificate in place (`setSecureContext`) — new handshakes get the new
838
- * leaf, open connections keep theirs, nothing restarts.
839
- */
840
- function registerHttpsListener(server, pair) {
841
- writeSlot({
842
- reload: (next) => server.setSecureContext({
843
- cert: next.cert,
844
- key: next.key
845
- }),
846
- servedLeafFingerprint: leafFingerprintOf(pair.cert)
847
- });
848
- }
849
- /** Forget the listener — on shutdown, and between specs. */
850
- function clearHttpsListener() {
851
- writeSlot(EMPTY_SLOT);
852
- }
853
- /**
854
- * The leaf the HTTPS listener serves now, or `null` when this process has no
855
- * registered listener (TLS off, or a process that does not own one) — in
856
- * which case nobody can say, and `null` is the honest answer.
857
- */
858
- function servedHttpsLeafFingerprint() {
859
- return readSlot().servedLeafFingerprint;
860
- }
861
- /** Serve `pair` from now on. Never throws: the outcome says what happened. */
862
- function reloadHttpsListener(pair) {
863
- const slot = readSlot();
864
- if (slot.reload === null) return { kind: "no-listener" };
865
- try {
866
- const servedLeafFingerprint = leafFingerprintOf(pair.cert);
867
- slot.reload(pair);
868
- writeSlot({
869
- reload: slot.reload,
870
- servedLeafFingerprint
871
- });
872
- return {
873
- kind: "reloaded",
874
- servedLeafFingerprint
875
- };
876
- } catch (err) {
877
- return {
878
- kind: "failed",
879
- error: err instanceof Error ? err.message : String(err)
880
- };
881
- }
882
- }
883
- //#endregion
884
- //#region src/tls/uploaded-cert.ts
885
- /**
886
- * Operator-supplied material must parse, match its key, and carry
887
- * `extendedKeyUsage = serverAuth` — the same leaf defects D227 refused
888
- * to keep generating.
889
- */
890
- function validateUploadedTls(certPem, keyPem) {
891
- let leaf;
892
- try {
893
- leaf = new X509Certificate(certPem);
894
- } catch {
895
- return {
896
- ok: false,
897
- error: "Certificate PEM could not be parsed."
898
- };
899
- }
900
- try {
901
- if (!leaf.checkPrivateKey(createPrivateKey(keyPem))) return {
902
- ok: false,
903
- error: "Private key does not match the certificate."
904
- };
905
- } catch {
906
- return {
907
- ok: false,
908
- error: "Private key PEM could not be parsed."
909
- };
910
- }
911
- const eku = leaf.keyUsage;
912
- if (eku === void 0 || !eku.includes("1.3.6.1.5.5.7.3.1")) return {
913
- ok: false,
914
- error: "Certificate is missing extendedKeyUsage = serverAuth."
915
- };
916
- return {
917
- ok: true,
918
- fingerprintSha256: leaf.fingerprint256,
919
- validTo: new Date(leaf.validTo).toISOString()
920
- };
921
- }
922
- //#endregion
923
- //#region src/tls/tls-actions.ts
924
- function withNewline(pem) {
925
- return pem.endsWith("\n") ? pem : `${pem}\n`;
926
- }
927
- /**
928
- * Store an operator's certificate. The leaf (or chain) and key replace the
929
- * served pair; a CA, when given, goes to its own file. The local CA
930
- * (`camstack-ca.crt` + key) is never touched — it did not sign the upload,
931
- * and it is what "Revert to generated" and every device that trusts it
932
- * still need.
933
- */
934
- async function storeUploadedCertificate(dataDir, input) {
935
- const valid = validateUploadedTls(input.certPem, input.keyPem);
936
- if (!valid.ok) throw new Error(valid.error);
937
- const dir = join(dataDir, "tls");
938
- await mkdir(dir, { recursive: true });
939
- await writeFile(join(dir, "camstack.crt"), withNewline(input.certPem));
940
- writeOwnerOnlyFileSync(join(dir, "camstack.key"), withNewline(input.keyPem));
941
- const caPath = join(dir, UPLOADED_CA_FILE);
942
- if (input.caPem !== void 0 && input.caPem.trim() !== "") await writeFile(caPath, withNewline(input.caPem));
943
- else rmSync(caPath, { force: true });
944
- writeTlsMode(dataDir, "uploaded");
945
- }
946
- /** Issue a new generated leaf under the local CA. Refused while an upload is served. */
947
- async function regenerateCertificate(dataDir, options) {
948
- if (readTlsMode(dataDir) === "uploaded") throw new Error("Cannot regenerate an uploaded certificate — revert to generated first.");
949
- await reissueTlsLeaf(dataDir, options);
950
- }
951
- /** Drop the upload and serve the generated local-CA leaf again (D227). */
952
- async function revertToGeneratedCertificate(dataDir, options) {
953
- writeTlsMode(dataDir, "generated");
954
- rmSync(join(dataDir, "tls", UPLOADED_CA_FILE), { force: true });
955
- await ensureTlsCert(dataDir, options);
956
- }
957
- /**
958
- * Put the pair on disk on the HTTPS listener. Called after every action, so
959
- * "the certificate changed" and "clients see it" are the same moment.
960
- */
961
- function applyCertificateToListener(dataDir) {
962
- const certPath = join(dataDir, "tls", "camstack.crt");
963
- const keyPath = join(dataDir, "tls", "camstack.key");
964
- if (!existsSync(certPath) || !existsSync(keyPath)) return {
965
- kind: "failed",
966
- error: `No certificate pair under ${join(dataDir, "tls")}`
967
- };
968
- return reloadHttpsListener(loadTlsCert(certPath, keyPath));
969
- }
970
- //#endregion
971
449
  //#region src/tls/agent-https.ts
972
450
  /**
973
451
  * HTTPS for agents (D856): a leaf from the hub's LOCAL CA, so a device that
@@ -1249,4 +727,4 @@ function pemDigest(pem) {
1249
727
  return createHash("sha256").update(pem).digest("hex").slice(0, 16);
1250
728
  }
1251
729
  //#endregion
1252
- export { readTlsMode as A, CA_VALIDITY_DAYS as B, registerHttpsListener as C, UPLOADED_CA_FILE as D, prepareBootTls as E, loadTlsCert as F, DEFAULT_LAN_HTTP_PORT as G, MAX_LEAF_VALIDITY_DAYS as H, reissueTlsLeaf as I, bindPendingLanHttp as J, allFamiliesListenHost as K, CA_COMMON_NAME as L, writeExtraSans as M, writeTlsMode as N, readExtraSans as O, ensureTlsCert as P, collectCertIdentity as R, leafFingerprintOf as S, servedHttpsLeafFingerprint as T, SERVER_AUTH_OID as U, LEAF_RENEWAL_WINDOW_DAYS as V, evaluateExistingCert as W, readLanHttpState as X, closeLanHttp as Y, registerLanHttpHandler as Z, regenerateCertificate as _, collectAgentNames as a, validateUploadedTls as b, installAgentHttps as c, isPrivateAddress as d, issueAgentHttpsLeaf as f, applyCertificateToListener as g, pinnedHttpsCaFingerprint as h, certificateNames as i, splitPemCertificates as j, readTlsAccessStatus as k, isContainerBridgeAddress as l, pemDigest as m, acceptAgentSans as n, createAgentHttpsRequest as o, loadAgentHttps as p, applyLanHttp as q, agentHttpsPaths as r, describeHttpsLeaf as s, AgentHttpsInstallError as t, isLocalOnlyHostname as u, revertToGeneratedCertificate as v, reloadHttpsListener as w, clearHttpsListener as x, storeUploadedCertificate as y, systemHostFacts as z };
730
+ export { AgentHttpsNames as A, LEAF_RENEWAL_WINDOW_DAYS as C, reasonRequiresNewCa as D, evaluateExistingCert as E, setProcessAgentHttpsNames as M, AGENT_HTTPS_NAMES_COLLECTION as O, CA_VALIDITY_DAYS as S, SERVER_AUTH_OID as T, generateCa as _, collectAgentNames as a, collectCertIdentity as b, installAgentHttps as c, isPrivateAddress as d, issueAgentHttpsLeaf as f, CA_COMMON_NAME as g, pinnedHttpsCaFingerprint as h, certificateNames as i, getProcessAgentHttpsNames as j, AGENT_HTTPS_NAMES_COLUMNS as k, isContainerBridgeAddress as l, pemDigest as m, acceptAgentSans as n, createAgentHttpsRequest as o, loadAgentHttps as p, agentHttpsPaths as r, describeHttpsLeaf as s, AgentHttpsInstallError as t, isLocalOnlyHostname as u, issueLeaf as v, MAX_LEAF_VALIDITY_DAYS as w, systemHostFacts as x, loadCa as y };