@camstack/system 1.2.457 → 1.2.459

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 (106) hide show
  1. package/dist/addon-runner.js +163 -27
  2. package/dist/addon-runner.mjs +193 -57
  3. package/dist/{agent-https-CoyOZ3pC.js → agent-https-Dnr_nIVx.js} +3 -723
  4. package/dist/{agent-https-CK9Z4sSR.mjs → agent-https-Iw3RSQup.mjs} +4 -616
  5. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  6. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  7. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  8. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  9. package/dist/builtins/alerts/alerts.addon.js +5 -7
  10. package/dist/builtins/alerts/alerts.addon.mjs +5 -7
  11. package/dist/builtins/alerts/record-kinds.d.ts +1 -1
  12. package/dist/builtins/autotrack/index.js +1 -1
  13. package/dist/builtins/autotrack/index.mjs +1 -1
  14. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +242 -4
  15. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +240 -2
  16. package/dist/builtins/calendars/calendars.addon.js +2 -10
  17. package/dist/builtins/calendars/calendars.addon.mjs +2 -3
  18. package/dist/builtins/calendars/record-kinds.d.ts +1 -1
  19. package/dist/builtins/camera-grid/index.js +1 -1
  20. package/dist/builtins/camera-grid/index.mjs +1 -1
  21. package/dist/builtins/composer/composer.addon.js +2 -2
  22. package/dist/builtins/composer/composer.addon.mjs +2 -2
  23. package/dist/builtins/console-logging/index.js +1 -1
  24. package/dist/builtins/console-logging/index.mjs +1 -1
  25. package/dist/builtins/core-blocks/core-blocks.addon.js +4 -6
  26. package/dist/builtins/core-blocks/core-blocks.addon.mjs +4 -6
  27. package/dist/builtins/device-history/device-history.addon.d.ts +13 -0
  28. package/dist/builtins/device-history/device-history.addon.js +296 -233
  29. package/dist/builtins/device-history/device-history.addon.mjs +296 -233
  30. package/dist/builtins/device-history/ingest/producer-ingest.d.ts +11 -1
  31. package/dist/builtins/device-manager/device-manager.addon.js +2 -4
  32. package/dist/builtins/device-manager/device-manager.addon.mjs +2 -4
  33. package/dist/builtins/hub-forwarder/index.js +1 -1
  34. package/dist/builtins/hub-forwarder/index.mjs +1 -1
  35. package/dist/builtins/keychain/index.js +41 -43
  36. package/dist/builtins/keychain/index.mjs +41 -43
  37. package/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  38. package/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  39. package/dist/builtins/local-auth/local-auth.addon.js +24 -40
  40. package/dist/builtins/local-auth/local-auth.addon.mjs +24 -40
  41. package/dist/builtins/local-network/local-network.addon.js +2 -2
  42. package/dist/builtins/local-network/local-network.addon.mjs +2 -2
  43. package/dist/builtins/loki-logging/index.js +1 -1
  44. package/dist/builtins/loki-logging/index.mjs +1 -1
  45. package/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  46. package/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  47. package/dist/builtins/native-metrics/node-metrics-history-recorder.d.ts +1 -2
  48. package/dist/builtins/platform-probe/coral-accelerators.d.ts +26 -9
  49. package/dist/builtins/platform-probe/index.js +11 -68
  50. package/dist/builtins/platform-probe/index.mjs +11 -68
  51. package/dist/builtins/record-entries/index.js +1 -1
  52. package/dist/builtins/record-entries/index.mjs +1 -1
  53. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  54. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  55. package/dist/builtins/snapshot/index.js +1 -1
  56. package/dist/builtins/snapshot/index.mjs +1 -1
  57. package/dist/builtins/sqlite-storage/file-host-protocol.d.ts +0 -15
  58. package/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  59. package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  60. package/dist/builtins/sqlite-storage/index.js +1 -1
  61. package/dist/builtins/sqlite-storage/index.mjs +1 -1
  62. package/dist/builtins/sqlite-storage/owned-sqlite-file.d.ts +0 -44
  63. package/dist/builtins/sqlite-storage/records/records-catalog.d.ts +0 -2
  64. package/dist/builtins/sqlite-storage/records/records-engine-types.d.ts +0 -21
  65. package/dist/builtins/sqlite-storage/records/records-engine.d.ts +3 -20
  66. package/dist/builtins/sqlite-storage/records/records-provider.d.ts +4 -18
  67. package/dist/builtins/sqlite-storage/records/records-sql.d.ts +1 -1
  68. package/dist/builtins/sqlite-storage/sqlite-settings-backend.d.ts +0 -17
  69. package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +21 -196
  70. package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +21 -196
  71. package/dist/builtins/sqlite-storage/storage-admin-provider.d.ts +6 -14
  72. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.d.ts +2 -2
  73. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +7 -9
  74. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +7 -9
  75. package/dist/builtins/system-config/system-config.addon.js +667 -40
  76. package/dist/builtins/system-config/system-config.addon.mjs +625 -15
  77. package/dist/builtins/winston-logging/index.js +1 -1
  78. package/dist/builtins/winston-logging/index.mjs +1 -1
  79. package/dist/{composition-sources-B_jeZDRJ.mjs → composition-sources-DNRZWR1j.mjs} +1 -1
  80. package/dist/{composition-sources-qKyvMAvc.js → composition-sources-b0e_2I-D.js} +1 -1
  81. package/dist/{constants-B_X9cWEK.js → constants-6OeJiZgi.js} +1 -1
  82. package/dist/{constants-cxKcZRMi.mjs → constants-BnkOdj9Q.mjs} +1 -1
  83. package/dist/coral-accelerators-Bi_c3Rft.js +175 -0
  84. package/dist/coral-accelerators-DcnZvctM.mjs +162 -0
  85. package/dist/{device-ca-BB6nHAL5.mjs → device-ca-Bnkw8GyU.mjs} +1 -1
  86. package/dist/{device-ca-CVK3YcR_.js → device-ca-CPTDs--d.js} +1 -1
  87. package/dist/{dist-C89nqNnn.js → dist-Bn-RNanh.js} +84 -140
  88. package/dist/{dist-Dhux90yB.mjs → dist-Wy8cTxg6.mjs} +85 -123
  89. package/dist/file-host-worker.js +1 -1
  90. package/dist/file-host-worker.mjs +1 -1
  91. package/dist/{hub-mdns-ciao-B8olZqqd.mjs → hub-mdns-ciao-CJu0nhla.mjs} +2 -2
  92. package/dist/{hub-mdns-ciao-DB1Y9agt.js → hub-mdns-ciao-CTBTlia4.js} +2 -2
  93. package/dist/index.js +32 -58
  94. package/dist/index.mjs +16 -42
  95. package/dist/kernel/hwaccel/hwaccel-resolver.d.ts +7 -3
  96. package/dist/{restore-archive-DyOaPeAr.mjs → restore-archive-CmP-iiG9.mjs} +84 -331
  97. package/dist/{restore-archive-4DOUR5Gu.js → restore-archive-DM1OBYq4.js} +89 -342
  98. package/dist/{wal-maintenance-DVN-DiVP.js → wal-maintenance-DUHEp_09.js} +0 -0
  99. package/dist/{wal-maintenance-BMiX6UIa.mjs → wal-maintenance-NKbwWovZ.mjs} +0 -0
  100. package/package.json +1 -1
  101. package/dist/builtins/records/legacy-table-row-count.d.ts +0 -5
  102. package/dist/builtins/records/phase6-declare-gate.d.ts +0 -28
  103. package/dist/builtins/sqlite-storage/records/count-settings-array-legacy.d.ts +0 -5
  104. package/dist/builtins/sqlite-storage/records/count-settings-brokers-legacy.d.ts +0 -6
  105. package/dist/phase6-declare-gate-BO-_jLh_.js +0 -98
  106. package/dist/phase6-declare-gate-x9ZCbQJP.mjs +0 -93
@@ -1,9 +1,9 @@
1
1
  import { a as __toCommonJS, i as __require, n as __esmMin, o as __toESM, r as __exportAll, t as __commonJSMin } from "../../chunk-CNf5ZN-e.mjs";
2
- import { Gi as defineCustomActions, Ui as customAction, Zi as hydrateSchema, ni as BaseAddon, ti as errMsg, ut as ServerNameSchema, xr as shortHostname } from "../../dist-Dhux90yB.mjs";
2
+ import { Ui as customAction, Wi as defineCustomActions, Xi as hydrateSchema, ni as BaseAddon, ti as errMsg, ut as ServerNameSchema, xr as shortHostname } from "../../dist-Wy8cTxg6.mjs";
3
3
  import { t as require_safe_buffer } from "../../safe-buffer-B1OjL1I9.mjs";
4
- import { c as Pkcs10CertificateRequest } from "../../x509.es-DK__ETIe.mjs";
5
- import { a as MESH_CA_KEY_REF, i as MESH_CA_FIELD, n as DEFAULT_HUB_TLS_TCP_PORT, o as MESH_CA_SETTINGS_KEY } from "../../constants-cxKcZRMi.mjs";
6
- import { $ as generateMeshCa, B as setProcessAgentHttpsNames, H as MESH_NODE_CERTIFICATES_COLLECTION, I as AGENT_HTTPS_NAMES_COLLECTION, J as setProcessMeshCertificateRegistry, K as describeMeshLeaf, L as AGENT_HTTPS_NAMES_COLUMNS, M as isLocalOnlyHostname, Q as exportMeshPrivateKeyPem, R as AgentHttpsNames, U as MESH_NODE_CERTIFICATES_COLUMNS, V as systemConfigRecordKinds, W as MeshCertificateRegistry, X as caFingerprintCompact, Z as createMeshCsrPem, at as subjectCn, et as generateMeshKeyPair, it as loadMeshCa, nt as issueMeshLeafForNode, rt as issueMeshLeafFromCsr, tt as isValidAgentNodeId, u as isPrivateAddress, z as getProcessAgentHttpsNames } from "../../agent-https-CK9Z4sSR.mjs";
4
+ import { S as backdatedNotBefore, a as KeyUsageFlags, c as Pkcs10CertificateRequest, d as SubjectKeyIdentifierExtension, f as X509Certificate$1, l as Pkcs10CertificateRequestGenerator, m as cryptoProvider, n as BasicConstraintsExtension, o as KeyUsagesExtension, p as X509CertificateGenerator, r as ExtendedKeyUsageExtension, s as PemConverter, t as AuthorityKeyIdentifierExtension } from "../../x509.es-DK__ETIe.mjs";
5
+ import { B as setProcessAgentHttpsNames, I as AGENT_HTTPS_NAMES_COLLECTION, L as AGENT_HTTPS_NAMES_COLUMNS, M as isLocalOnlyHostname, R as AgentHttpsNames, V as systemConfigRecordKinds, u as isPrivateAddress, z as getProcessAgentHttpsNames } from "../../agent-https-Iw3RSQup.mjs";
6
+ import { a as MESH_CA_KEY_REF, c as SERVER_AUTH_OID, i as MESH_CA_FIELD, n as DEFAULT_HUB_TLS_TCP_PORT, o as MESH_CA_SETTINGS_KEY, r as MESH_CA_COMMON_NAME, s as MESH_CA_VALIDITY_DAYS, t as CLIENT_AUTH_OID } from "../../constants-BnkOdj9Q.mjs";
7
7
  import { t as require_src } from "../../src-hG4grMU4.mjs";
8
8
  import { z } from "zod";
9
9
  import { X509Certificate, createHash, createPrivateKey, randomBytes, randomInt, sign, timingSafeEqual, verify, webcrypto } from "node:crypto";
@@ -288,8 +288,161 @@ function parsePayload(value) {
288
288
  };
289
289
  }
290
290
  //#endregion
291
+ //#region src/kernel/moleculer/mesh-mtls/mesh-ca.ts
292
+ /**
293
+ * Hub mesh CA — EC P-256, key in the keychain, cert in `cluster.meshCa`.
294
+ *
295
+ * Distinct from the HTTPS local CA (`tls/cert-issue.ts`, RSA): the mesh CA
296
+ * signs node leaves (CN = nodeID) and unlock-ticket JWS (ES256). Issuance uses
297
+ * `@peculiar/x509` over WebCrypto — same library the HTTPS path already uses
298
+ * (installed `1.14.3`; registry latest at adoption time was `2.1.0` — stay on
299
+ * the pinned range already shipping).
300
+ */
301
+ cryptoProvider.set(webcrypto);
302
+ var MS_PER_DAY = 864e5;
303
+ /** Key generation — EC P-256 (plan). WebCrypto DOM names are not in @types/node. */
304
+ var MESH_KEY_ALGORITHM = {
305
+ name: "ECDSA",
306
+ namedCurve: "P-256"
307
+ };
308
+ /** Signing — ECDSA with SHA-256. */
309
+ var MESH_SIGNING_ALGORITHM = {
310
+ name: "ECDSA",
311
+ hash: "SHA-256"
312
+ };
313
+ /** A node id: letters, digits, `.`, `_`, `-`; at most 63 characters; starts with a letter or digit. */
314
+ var NODE_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,62}$/i;
315
+ /** Ids no agent may take: the hub's own, whatever the case (D857). */
316
+ var RESERVED_NODE_IDS = new Set(["hub"]);
317
+ /** True for an id an agent may carry: the pattern, and not a reserved name. */
318
+ function isValidAgentNodeId(nodeId) {
319
+ return NODE_ID_PATTERN.test(nodeId) && !RESERVED_NODE_IDS.has(nodeId.toLowerCase());
320
+ }
321
+ function freshSerial() {
322
+ return `00${randomBytes(16).toString("hex")}`;
323
+ }
324
+ function toPkcs8Pem(pkcs8) {
325
+ return `${PemConverter.encode(pkcs8, "PRIVATE KEY")}\n`;
326
+ }
327
+ function toCertPem(cert) {
328
+ return `${cert.toString("pem")}\n`;
329
+ }
330
+ async function exportKeyPem(key) {
331
+ return toPkcs8Pem(await webcrypto.subtle.exportKey("pkcs8", key));
332
+ }
333
+ /** SHA-256 fingerprint of the DER cert, colon-hex uppercase (Node style). */
334
+ function caFingerprint(certPem) {
335
+ return new X509Certificate(certPem).fingerprint256;
336
+ }
337
+ /** Compact fingerprint (lowercase hex, no colons). */
338
+ function caFingerprintCompact(certPem) {
339
+ return createHash("sha256").update(new X509Certificate(certPem).raw).digest("hex");
340
+ }
341
+ async function generateMeshCa(now = /* @__PURE__ */ new Date()) {
342
+ const keys = await webcrypto.subtle.generateKey(MESH_KEY_ALGORITHM, true, ["sign", "verify"]);
343
+ const extensions = [
344
+ new BasicConstraintsExtension(true, 0, true),
345
+ new KeyUsagesExtension(KeyUsageFlags.keyCertSign | KeyUsageFlags.cRLSign, true),
346
+ await SubjectKeyIdentifierExtension.create(keys.publicKey)
347
+ ];
348
+ const cert = await X509CertificateGenerator.createSelfSigned({
349
+ serialNumber: freshSerial(),
350
+ name: `CN=${MESH_CA_COMMON_NAME}`,
351
+ notBefore: backdatedNotBefore(now),
352
+ notAfter: new Date(now.getTime() + MESH_CA_VALIDITY_DAYS * MS_PER_DAY),
353
+ keys,
354
+ signingAlgorithm: MESH_SIGNING_ALGORITHM,
355
+ extensions
356
+ });
357
+ return {
358
+ certPem: toCertPem(cert),
359
+ keyPem: await exportKeyPem(keys.privateKey),
360
+ cert,
361
+ privateKey: keys.privateKey,
362
+ publicKey: keys.publicKey
363
+ };
364
+ }
365
+ async function loadMeshCa(certPem, keyPem) {
366
+ const cert = new X509Certificate$1(certPem);
367
+ return {
368
+ certPem,
369
+ keyPem,
370
+ cert,
371
+ privateKey: await webcrypto.subtle.importKey("pkcs8", PemConverter.decodeFirst(keyPem), MESH_KEY_ALGORITHM, true, ["sign"]),
372
+ publicKey: await cert.publicKey.export(webcrypto)
373
+ };
374
+ }
375
+ /**
376
+ * Issue a leaf from a CSR. CN must be present; when `expectedNodeId` is set
377
+ * it must match. Validity: 30 days.
378
+ */
379
+ async function issueMeshLeafFromCsr(ca, csrPem, opts = {}) {
380
+ const csr = new Pkcs10CertificateRequest(csrPem);
381
+ if (!await csr.verify(webcrypto)) throw new Error("CSR signature is invalid");
382
+ const cn = subjectCn(csr.subject);
383
+ if (cn === null || cn.length === 0) throw new Error("CSR subject has no CN");
384
+ if (opts.allowReserved !== true && !isValidAgentNodeId(cn)) throw new Error(`CSR CN '${cn}' is not an id an agent may carry`);
385
+ if (opts.expectedNodeId !== void 0 && opts.expectedNodeId !== cn) throw new Error(`CSR CN '${cn}' does not match the token nodeId '${opts.expectedNodeId}'`);
386
+ const now = opts.now ?? /* @__PURE__ */ new Date();
387
+ const validDays = opts.validDays ?? 30;
388
+ const serialNumber = freshSerial();
389
+ const notAfter = new Date(now.getTime() + validDays * MS_PER_DAY);
390
+ const extensions = [
391
+ new BasicConstraintsExtension(false, void 0, true),
392
+ new KeyUsagesExtension(KeyUsageFlags.digitalSignature, true),
393
+ new ExtendedKeyUsageExtension([SERVER_AUTH_OID, CLIENT_AUTH_OID]),
394
+ await SubjectKeyIdentifierExtension.create(csr.publicKey),
395
+ await AuthorityKeyIdentifierExtension.create(ca.cert)
396
+ ];
397
+ return {
398
+ certPem: toCertPem(await X509CertificateGenerator.create({
399
+ serialNumber,
400
+ subject: `CN=${cn}`,
401
+ issuer: ca.cert.subject,
402
+ notBefore: backdatedNotBefore(now),
403
+ notAfter,
404
+ publicKey: csr.publicKey,
405
+ signingKey: ca.privateKey,
406
+ signingAlgorithm: MESH_SIGNING_ALGORITHM,
407
+ extensions
408
+ })),
409
+ serialNumber,
410
+ notAfter,
411
+ commonName: cn
412
+ };
413
+ }
414
+ /** Issue a leaf for a known nodeID with a freshly generated key pair (tests / hub self). */
415
+ async function issueMeshLeafForNode(ca, nodeId, opts = {}) {
416
+ const keys = await webcrypto.subtle.generateKey(MESH_KEY_ALGORITHM, true, ["sign", "verify"]);
417
+ return {
418
+ ...await issueMeshLeafFromCsr(ca, await createMeshCsrPem(keys, nodeId), {
419
+ expectedNodeId: nodeId,
420
+ now: opts.now,
421
+ validDays: opts.validDays,
422
+ allowReserved: true
423
+ }),
424
+ keyPem: await exportKeyPem(keys.privateKey)
425
+ };
426
+ }
427
+ function subjectCn(subject) {
428
+ return /(?:^|,)\s*CN\s*=\s*([^,]+)/i.exec(subject)?.[1]?.trim() ?? null;
429
+ }
430
+ async function createMeshCsrPem(keys, commonName) {
431
+ return `${(await Pkcs10CertificateRequestGenerator.create({
432
+ name: `CN=${commonName}`,
433
+ keys,
434
+ signingAlgorithm: MESH_SIGNING_ALGORITHM
435
+ })).toString("pem")}\n`;
436
+ }
437
+ async function generateMeshKeyPair() {
438
+ return webcrypto.subtle.generateKey(MESH_KEY_ALGORITHM, true, ["sign", "verify"]);
439
+ }
440
+ async function exportMeshPrivateKeyPem(key) {
441
+ return exportKeyPem(key);
442
+ }
443
+ //#endregion
291
444
  //#region src/kernel/moleculer/mesh-mtls/mesh-ca-keeper.ts
292
- var SLOT$2 = Symbol.for("camstack.mesh.ca");
445
+ var SLOT$3 = Symbol.for("camstack.mesh.ca");
293
446
  var NOT_LOADED = {
294
447
  state: "unavailable",
295
448
  reason: "not-loaded"
@@ -301,10 +454,10 @@ function isState(value) {
301
454
  return state === "unavailable" && typeof Reflect.get(value, "reason") === "string";
302
455
  }
303
456
  function setProcessMeshCa(state) {
304
- Reflect.set(globalThis, SLOT$2, state);
457
+ Reflect.set(globalThis, SLOT$3, state);
305
458
  }
306
459
  function getProcessMeshCaState() {
307
- const value = Reflect.get(globalThis, SLOT$2);
460
+ const value = Reflect.get(globalThis, SLOT$3);
308
461
  return isState(value) ? value : NOT_LOADED;
309
462
  }
310
463
  function requireProcessMeshCa() {
@@ -446,10 +599,10 @@ async function loadOrGenerateMeshCa(deps) {
446
599
  var MeshCrl = class {
447
600
  serials = /* @__PURE__ */ new Set();
448
601
  revoke(serialNumber) {
449
- this.serials.add(normalizeSerial(serialNumber));
602
+ this.serials.add(normalizeSerial$1(serialNumber));
450
603
  }
451
604
  isRevoked(serialNumber) {
452
- return this.serials.has(normalizeSerial(serialNumber));
605
+ return this.serials.has(normalizeSerial$1(serialNumber));
453
606
  }
454
607
  list() {
455
608
  return [...this.serials];
@@ -457,21 +610,478 @@ var MeshCrl = class {
457
610
  /** Restore from persisted serials (system-settings). */
458
611
  replaceAll(serials) {
459
612
  this.serials.clear();
460
- for (const s of serials) this.serials.add(normalizeSerial(s));
613
+ for (const s of serials) this.serials.add(normalizeSerial$1(s));
461
614
  }
462
615
  };
463
- function normalizeSerial(serial) {
616
+ function normalizeSerial$1(serial) {
464
617
  return serial.replace(/^0x/i, "").replace(/:/g, "").toLowerCase();
465
618
  }
466
- var SLOT$1 = Symbol.for("camstack.mesh.crl");
619
+ var SLOT$2 = Symbol.for("camstack.mesh.crl");
467
620
  function processMeshCrl() {
468
- const existing = Reflect.get(globalThis, SLOT$1);
621
+ const existing = Reflect.get(globalThis, SLOT$2);
469
622
  if (existing instanceof MeshCrl) return existing;
470
623
  const crl = new MeshCrl();
471
- Reflect.set(globalThis, SLOT$1, crl);
624
+ Reflect.set(globalThis, SLOT$2, crl);
472
625
  return crl;
473
626
  }
474
627
  //#endregion
628
+ //#region src/kernel/moleculer/mesh-mtls/mesh-certificate-registry.ts
629
+ /**
630
+ * The hub's record of every mesh leaf (D856): which certificate each node holds,
631
+ * when it expires, and which serials are revoked.
632
+ *
633
+ * Three ways a row appears:
634
+ * - `enroll` / `renewal` / `boot` - the hub issued it and wrote it down at the
635
+ * moment of issuing (the authoritative record);
636
+ * - `observed` - a node enrolled before this record existed (or by a path that
637
+ * did not write it) presented this leaf on its LIVE mutual-TLS connection.
638
+ *
639
+ * Revoked serials are persisted here and replayed into the in-memory CRL at boot,
640
+ * so a revocation survives a hub restart. Hub only: agents persist none of it.
641
+ */
642
+ /**
643
+ * @durable class=config owner=system-config
644
+ * write="the hub records every mesh leaf it issues (enroll, renewal, boot) and every
645
+ * leaf a connected node is observed presenting; a revocation stamps revokedAt"
646
+ * retention="a revoked or expired row is kept 90 days past its end, then reaped; a
647
+ * live row is never deleted. Forgetting a node does not delete its rows."
648
+ */
649
+ var MESH_NODE_CERTIFICATES_COLLECTION = "mesh_node_certificates";
650
+ var MESH_NODE_CERTIFICATES_COLUMNS = [
651
+ {
652
+ name: "id",
653
+ type: "TEXT",
654
+ primaryKey: true,
655
+ notNull: true
656
+ },
657
+ {
658
+ name: "nodeId",
659
+ type: "TEXT",
660
+ notNull: true
661
+ },
662
+ {
663
+ name: "serial",
664
+ type: "TEXT",
665
+ notNull: true
666
+ },
667
+ {
668
+ name: "fingerprint",
669
+ type: "TEXT",
670
+ notNull: true
671
+ },
672
+ {
673
+ name: "notBefore",
674
+ type: "INTEGER",
675
+ notNull: true
676
+ },
677
+ {
678
+ name: "notAfter",
679
+ type: "INTEGER",
680
+ notNull: true
681
+ },
682
+ {
683
+ name: "issuedAt",
684
+ type: "INTEGER",
685
+ notNull: true
686
+ },
687
+ {
688
+ name: "issuedVia",
689
+ type: "TEXT",
690
+ notNull: true
691
+ },
692
+ {
693
+ name: "revokedAt",
694
+ type: "INTEGER"
695
+ },
696
+ {
697
+ name: "revokedReason",
698
+ type: "TEXT"
699
+ }
700
+ ];
701
+ var RETENTION_MS = 90 * 864e5;
702
+ /**
703
+ * A leaf the hub signed for a renewal that did not complete. It must not be the node's
704
+ * `current` leaf, but it is NOT on the CRL: the node may still hold it (the swap
705
+ * could have landed without the hub seeing it), and cutting it off would be the
706
+ * outage the hand-over exists to prevent. If the node is later seen presenting it, it
707
+ * is reinstated.
708
+ */
709
+ var RENEWAL_ABANDONED = "renewal-abandoned";
710
+ var VIAS = [
711
+ "enroll",
712
+ "pairing",
713
+ "renewal",
714
+ "boot",
715
+ "observed"
716
+ ];
717
+ /** CN, serial, fingerprint and validity of a leaf PEM (or DER). */
718
+ function describeMeshLeaf(cert) {
719
+ const x509 = new X509Certificate(cert);
720
+ return {
721
+ cn: subjectCn(x509.subject) ?? "",
722
+ serial: x509.serialNumber,
723
+ fingerprint: x509.fingerprint256,
724
+ notBefore: Date.parse(x509.validFrom),
725
+ notAfter: Date.parse(x509.validTo)
726
+ };
727
+ }
728
+ function normalizeSerial(serial) {
729
+ return serial.replace(/^0x/i, "").replace(/:/g, "").toLowerCase();
730
+ }
731
+ function parse$2(data) {
732
+ const str = (k) => {
733
+ const v = data[k];
734
+ return typeof v === "string" && v.length > 0 ? v : null;
735
+ };
736
+ const num = (k) => {
737
+ const v = data[k];
738
+ return typeof v === "number" && Number.isFinite(v) ? v : null;
739
+ };
740
+ const nodeId = str("nodeId");
741
+ const serial = str("serial");
742
+ const fingerprint = str("fingerprint");
743
+ const notBefore = num("notBefore");
744
+ const notAfter = num("notAfter");
745
+ const issuedAt = num("issuedAt");
746
+ if (nodeId === null || serial === null || fingerprint === null || notBefore === null || notAfter === null || issuedAt === null) return null;
747
+ return {
748
+ nodeId,
749
+ serial,
750
+ fingerprint,
751
+ notBefore,
752
+ notAfter,
753
+ issuedAt,
754
+ issuedVia: VIAS.find((v) => v === data["issuedVia"]) ?? "observed",
755
+ revokedAt: num("revokedAt"),
756
+ revokedReason: str("revokedReason")
757
+ };
758
+ }
759
+ var MeshCertificateRegistry = class {
760
+ store;
761
+ deps;
762
+ rows = /* @__PURE__ */ new Map();
763
+ constructor(store, deps = {}) {
764
+ this.store = store;
765
+ this.deps = deps;
766
+ }
767
+ recordToBody(record) {
768
+ return {
769
+ nodeId: record.nodeId,
770
+ serial: record.serial,
771
+ fingerprint: record.fingerprint,
772
+ notBefore: record.notBefore,
773
+ notAfter: record.notAfter,
774
+ issuedAt: record.issuedAt,
775
+ issuedVia: record.issuedVia,
776
+ revokedAt: record.revokedAt,
777
+ revokedReason: record.revokedReason
778
+ };
779
+ }
780
+ now() {
781
+ return (this.deps.now ?? Date.now)();
782
+ }
783
+ async load() {
784
+ const kind = this.deps.meshKind ?? null;
785
+ if (kind !== null) {
786
+ const page = await kind.query({ limit: 1e4 });
787
+ for (const row of page.records) {
788
+ const { fingerprint: _fp, ...body } = row.data;
789
+ const record = parse$2({
790
+ ...body,
791
+ fingerprint: row.id
792
+ });
793
+ if (record !== null) this.rows.set(record.fingerprint, record);
794
+ }
795
+ return;
796
+ }
797
+ const rows = await this.store.query.query({ collection: MESH_NODE_CERTIFICATES_COLLECTION });
798
+ for (const row of rows) {
799
+ const record = parse$2(row.data);
800
+ if (record !== null) this.rows.set(record.fingerprint, record);
801
+ }
802
+ }
803
+ /** Write down a leaf the hub just issued. Idempotent per fingerprint. */
804
+ async recordIssued(nodeId, certPem, via) {
805
+ const leaf = describeMeshLeaf(certPem);
806
+ const existing = this.rows.get(leaf.fingerprint);
807
+ if (existing !== void 0) return existing;
808
+ const record = {
809
+ nodeId,
810
+ serial: leaf.serial,
811
+ fingerprint: leaf.fingerprint,
812
+ notBefore: leaf.notBefore,
813
+ notAfter: leaf.notAfter,
814
+ issuedAt: this.now(),
815
+ issuedVia: via,
816
+ revokedAt: null,
817
+ revokedReason: null
818
+ };
819
+ await this.insert(record);
820
+ this.deps.logger?.info("Mesh certificate recorded", {
821
+ tags: { nodeId },
822
+ meta: {
823
+ via,
824
+ serial: leaf.serial,
825
+ notAfter: new Date(leaf.notAfter).toISOString()
826
+ }
827
+ });
828
+ return record;
829
+ }
830
+ /**
831
+ * A node was seen presenting `leaf` on its live connection. A leaf the hub already
832
+ * knows is left alone; an unknown one is recorded `observed` (a node enrolled
833
+ * before this record existed).
834
+ */
835
+ async recordObserved(nodeId, leaf) {
836
+ const known = this.rows.get(leaf.fingerprint);
837
+ if (known !== void 0) {
838
+ if (known.revokedReason !== "renewal-abandoned") return known.revokedAt === null ? this.abandonRenewalsNewerThan(known) : false;
839
+ const reinstated = {
840
+ ...known,
841
+ revokedAt: null,
842
+ revokedReason: null
843
+ };
844
+ this.rows.set(known.fingerprint, reinstated);
845
+ await this.persist(reinstated);
846
+ this.deps.logger?.warn("An abandoned renewal leaf is in use - reinstated", {
847
+ tags: { nodeId },
848
+ meta: { serial: known.serial }
849
+ });
850
+ return true;
851
+ }
852
+ const record = {
853
+ nodeId,
854
+ serial: leaf.serial,
855
+ fingerprint: leaf.fingerprint,
856
+ notBefore: leaf.notBefore,
857
+ notAfter: leaf.notAfter,
858
+ issuedAt: this.now(),
859
+ issuedVia: "observed",
860
+ revokedAt: null,
861
+ revokedReason: null
862
+ };
863
+ await this.insert(record);
864
+ this.deps.logger?.info("Mesh certificate observed on a live connection and recorded", {
865
+ tags: { nodeId },
866
+ meta: {
867
+ serial: leaf.serial,
868
+ fingerprint: leaf.fingerprint
869
+ }
870
+ });
871
+ return true;
872
+ }
873
+ list(nodeId) {
874
+ return [...this.rows.values()].filter((r) => nodeId === void 0 || r.nodeId === nodeId).toSorted((a, b) => b.issuedAt - a.issuedAt);
875
+ }
876
+ /** The newest non-revoked leaf of a node, or `undefined`. */
877
+ currentFor(nodeId) {
878
+ return this.list(nodeId).find((r) => r.revokedAt === null);
879
+ }
880
+ /** Every non-revoked leaf of a node (a renewal in flight has two). */
881
+ liveFor(nodeId) {
882
+ return this.list(nodeId).filter((r) => r.revokedAt === null);
883
+ }
884
+ /** Stamp a leaf revoked (and mirror it into `crl`). `false` when unknown or already revoked. */
885
+ async revoke(fingerprint, reason, crl) {
886
+ const record = this.rows.get(fingerprint);
887
+ if (record === void 0 || record.revokedAt !== null) return false;
888
+ const revoked = {
889
+ ...record,
890
+ revokedAt: this.now(),
891
+ revokedReason: reason
892
+ };
893
+ this.rows.set(fingerprint, revoked);
894
+ crl?.revoke(record.serial);
895
+ await this.persist(revoked);
896
+ this.deps.logger?.warn("Mesh certificate revoked", {
897
+ tags: { nodeId: record.nodeId },
898
+ meta: {
899
+ serial: record.serial,
900
+ reason
901
+ }
902
+ });
903
+ return true;
904
+ }
905
+ /**
906
+ * Operator revocation of a whole node: EVERY leaf of the node that is not already on the
907
+ * CRL goes on it - the current one, an observed one, a renewal one, and a leaf that was set
908
+ * aside (`renewal-abandoned`: a copy of it may sit on a stolen box, and it must not stay
909
+ * valid just because the hub once set it aside). Returns the serials put on the CRL.
910
+ * A leaf revoked this way is never reinstated by `recordObserved`.
911
+ */
912
+ async revokeAllForNode(nodeId, reason, crl, keepFingerprint) {
913
+ const serials = [];
914
+ for (const record of this.list(nodeId)) {
915
+ if (keepFingerprint !== void 0 && record.fingerprint === keepFingerprint) continue;
916
+ if (record.revokedAt !== null && record.revokedReason !== "renewal-abandoned") continue;
917
+ const revoked = {
918
+ ...record,
919
+ revokedAt: record.revokedAt ?? this.now(),
920
+ revokedReason: reason
921
+ };
922
+ this.rows.set(record.fingerprint, revoked);
923
+ crl.revoke(record.serial);
924
+ await this.persist(revoked);
925
+ serials.push(record.serial);
926
+ }
927
+ if (serials.length > 0) this.deps.logger?.warn("Every mesh certificate of the node revoked", {
928
+ tags: { nodeId },
929
+ meta: {
930
+ serials,
931
+ reason
932
+ }
933
+ });
934
+ return serials;
935
+ }
936
+ /**
937
+ * At boot: a node with TWO live leaves had a renewal in flight when the hub stopped. The
938
+ * newer (renewal) one is set aside - it is not the node's current leaf until the node is
939
+ * seen presenting it, which reinstates it. It is NOT put on the CRL.
940
+ */
941
+ async settleInterruptedRenewals() {
942
+ let settled = 0;
943
+ const byNode = /* @__PURE__ */ new Map();
944
+ for (const record of this.rows.values()) {
945
+ if (record.revokedAt !== null) continue;
946
+ byNode.set(record.nodeId, [...byNode.get(record.nodeId) ?? [], record]);
947
+ }
948
+ for (const records of byNode.values()) {
949
+ if (records.length < 2) continue;
950
+ for (const record of records) if (record.issuedVia === "renewal" && await this.abandon(record.fingerprint)) settled += 1;
951
+ }
952
+ return settled;
953
+ }
954
+ /** Set a never-completed renewal leaf aside (not current, NOT on the CRL). */
955
+ /** Fingerprints of renewal leaves whose handover is running right now (this process only). */
956
+ renewalsInFlight = /* @__PURE__ */ new Set();
957
+ /**
958
+ * A renewal's leaf is "in flight" from signing until the handover ends. While it is, a node seen
959
+ * presenting its OLD leaf is simply not swapped yet: the new leaf is not set aside (that would
960
+ * flap set-aside / reinstate on the node's first connection with it).
961
+ */
962
+ beginRenewal(fingerprint) {
963
+ this.renewalsInFlight.add(fingerprint);
964
+ }
965
+ endRenewal(fingerprint) {
966
+ this.renewalsInFlight.delete(fingerprint);
967
+ }
968
+ async abandonRenewalsNewerThan(presented) {
969
+ let changed = false;
970
+ for (const record of this.liveFor(presented.nodeId)) {
971
+ if (record.fingerprint === presented.fingerprint) continue;
972
+ if (record.issuedVia !== "renewal" || record.issuedAt <= presented.issuedAt) continue;
973
+ if (this.renewalsInFlight.has(record.fingerprint)) continue;
974
+ if (await this.abandon(record.fingerprint)) changed = true;
975
+ }
976
+ return changed;
977
+ }
978
+ async abandon(fingerprint) {
979
+ const record = this.rows.get(fingerprint);
980
+ if (record === void 0 || record.revokedAt !== null) return false;
981
+ const abandoned = {
982
+ ...record,
983
+ revokedAt: this.now(),
984
+ revokedReason: RENEWAL_ABANDONED
985
+ };
986
+ this.rows.set(fingerprint, abandoned);
987
+ await this.persist(abandoned);
988
+ this.deps.logger?.warn("Renewal leaf set aside (not current, not on the CRL)", {
989
+ tags: { nodeId: record.nodeId },
990
+ meta: { serial: record.serial }
991
+ });
992
+ return true;
993
+ }
994
+ /** Replay every persisted revocation into `crl` (hub boot). Set-aside leaves are not revocations. */
995
+ restoreCrl(crl) {
996
+ let restored = 0;
997
+ for (const record of this.rows.values()) {
998
+ if (record.revokedAt === null || record.revokedReason === "renewal-abandoned") continue;
999
+ crl.revoke(record.serial);
1000
+ restored += 1;
1001
+ }
1002
+ return restored;
1003
+ }
1004
+ /** Is `serial` listed as revoked here? */
1005
+ isRevoked(serial) {
1006
+ const wanted = normalizeSerial(serial);
1007
+ for (const record of this.rows.values()) if (record.revokedAt !== null && record.revokedReason !== "renewal-abandoned" && normalizeSerial(record.serial) === wanted) return true;
1008
+ return false;
1009
+ }
1010
+ async reap() {
1011
+ const cutoff = this.now() - RETENTION_MS;
1012
+ const dead = [...this.rows.values()].filter((r) => (r.revokedAt ?? r.notAfter) < cutoff);
1013
+ for (const r of dead) {
1014
+ this.rows.delete(r.fingerprint);
1015
+ await this.deleteRow(r.fingerprint);
1016
+ }
1017
+ return dead.length;
1018
+ }
1019
+ async insert(record) {
1020
+ this.rows.set(record.fingerprint, record);
1021
+ const kind = this.deps.meshKind ?? null;
1022
+ if (kind !== null) {
1023
+ const parsed = systemConfigRecordKinds["mesh-node-certificates"].schema.safeParse(this.recordToBody(record));
1024
+ if (!parsed.success) throw new Error(parsed.error.message);
1025
+ await kind.put({
1026
+ id: record.fingerprint,
1027
+ data: parsed.data
1028
+ });
1029
+ return;
1030
+ }
1031
+ await this.store.insert.mutate({
1032
+ collection: MESH_NODE_CERTIFICATES_COLLECTION,
1033
+ record: {
1034
+ id: record.fingerprint,
1035
+ data: { ...record }
1036
+ }
1037
+ });
1038
+ }
1039
+ async deleteRow(fingerprint) {
1040
+ const kind = this.deps.meshKind ?? null;
1041
+ if (kind !== null) {
1042
+ await kind.delete(fingerprint);
1043
+ return;
1044
+ }
1045
+ await this.store.delete.mutate({
1046
+ collection: MESH_NODE_CERTIFICATES_COLLECTION,
1047
+ key: fingerprint
1048
+ });
1049
+ }
1050
+ async persist(record) {
1051
+ try {
1052
+ const kind = this.deps.meshKind ?? null;
1053
+ if (kind !== null) {
1054
+ const parsed = systemConfigRecordKinds["mesh-node-certificates"].schema.safeParse(this.recordToBody(record));
1055
+ if (!parsed.success) throw new Error(parsed.error.message);
1056
+ await kind.put({
1057
+ id: record.fingerprint,
1058
+ data: parsed.data
1059
+ });
1060
+ return;
1061
+ }
1062
+ await this.store.update.mutate({
1063
+ collection: MESH_NODE_CERTIFICATES_COLLECTION,
1064
+ id: record.fingerprint,
1065
+ data: { ...record }
1066
+ });
1067
+ } catch (error) {
1068
+ this.deps.logger?.error("Mesh certificate write failed - the change holds until restart", {
1069
+ tags: { nodeId: record.nodeId },
1070
+ meta: { error: error instanceof Error ? error.message : String(error) }
1071
+ });
1072
+ }
1073
+ }
1074
+ };
1075
+ var SLOT$1 = Symbol.for("camstack.mesh.certificate-registry");
1076
+ function setProcessMeshCertificateRegistry(registry) {
1077
+ if (registry === null) Reflect.deleteProperty(globalThis, SLOT$1);
1078
+ else Reflect.set(globalThis, SLOT$1, registry);
1079
+ }
1080
+ function getProcessMeshCertificateRegistry() {
1081
+ const value = Reflect.get(globalThis, SLOT$1);
1082
+ return value !== null && typeof value === "object" && typeof Reflect.get(value, "recordIssued") === "function" ? value : null;
1083
+ }
1084
+ //#endregion
475
1085
  //#region src/kernel/moleculer/mesh-mtls/mesh-tls-gate.ts
476
1086
  var STATE_SLOT = Symbol.for("camstack.mesh.tls-listener-state");
477
1087
  function setProcessMeshTlsListenerState(state) {
@@ -88264,4 +88874,4 @@ function parseMintUnlockInput(input) {
88264
88874
  };
88265
88875
  }
88266
88876
  //#endregion
88267
- export { parseCidrList as $, setProcessMeshPeerTransportLookup as A, requireProcessMeshCa as B, setProcessMeshTlsEnabler as C, getProcessPeerLeaf as D, getProcessNodeMeshTransport as E, setProcessMeshTlsListenerState as F, AGENT_UI_UNLOCK_VERSION as G, AGENT_UI_UNLOCK_TTL_MS as H, MeshCrl as I, mintAgentUiUnlockTicket as J, UnlockTicketJtiStore as K, processMeshCrl as L, revokeMeshCertificate as M, getProcessMeshTlsListenerState as N, isProcessVerifiedMeshPeer as O, openMeshTlsWhenRevocationsLoaded as P, normalizeIp as Q, MeshCaKeeper as R, ServiceBroker as S, SYSTEM_CONFIG_CLUSTER_SECTION_ID, SystemConfigAddon, SystemConfigAddon as default, emitProcessNodeRegistered as T, AGENT_UI_UNLOCK_TYP as U, AGENT_DASHBOARD_ORIGINS_FIELD as V, AGENT_UI_UNLOCK_USE as W, verifyAgentUiUnlockTicket as X, parseAgentDashboardOrigins as Y, createCidrMatcher as Z, signPairingProof as _, hubHostFromMeshAddress as a, TlsTcpTransporter as b, PAIRING_MAX_SESSIONS as c, PAIRING_PROTOCOL as d, readCidrSetting as et, PAIRING_TTL_MS as f, keyFingerprintShort as g, describeCsr as h, AgentPairing as i, renewMeshCertificate as j, onProcessNodeRegistered as k, PAIRING_PATHS as l, computePairingSas as m, HubPairing as n, PAIRING_CODE_DIGITS as o, computePairingCommitment as p, isAllowedAgentDashboardReturnTo as q, PairingHttpError as r, PAIRING_MAX_CODE_ATTEMPTS as s, systemConfigMeshActions as t, PAIRING_PIN_DIGITS as u, verifyPairingProof as v, dropProcessPeer as w, Errors as x, MESH_TLS_PORT_HELLO_FIELD as y, getProcessMeshCaState as z };
88877
+ export { generateMeshKeyPair as $, setProcessMeshPeerTransportLookup as A, describeMeshLeaf as B, setProcessMeshTlsEnabler as C, getProcessPeerLeaf as D, getProcessNodeMeshTransport as E, setProcessMeshTlsListenerState as F, MeshCaKeeper as G, setProcessMeshCertificateRegistry as H, MESH_NODE_CERTIFICATES_COLLECTION as I, caFingerprint as J, getProcessMeshCaState as K, MESH_NODE_CERTIFICATES_COLUMNS as L, revokeMeshCertificate as M, getProcessMeshTlsListenerState as N, isProcessVerifiedMeshPeer as O, openMeshTlsWhenRevocationsLoaded as P, generateMeshCa as Q, MeshCertificateRegistry as R, ServiceBroker as S, SYSTEM_CONFIG_CLUSTER_SECTION_ID, SystemConfigAddon, SystemConfigAddon as default, emitProcessNodeRegistered as T, MeshCrl as U, getProcessMeshCertificateRegistry as V, processMeshCrl as W, createMeshCsrPem as X, caFingerprintCompact as Y, exportMeshPrivateKeyPem as Z, signPairingProof as _, readCidrSetting as _t, hubHostFromMeshAddress as a, AGENT_UI_UNLOCK_TTL_MS as at, TlsTcpTransporter as b, PAIRING_MAX_SESSIONS as c, AGENT_UI_UNLOCK_VERSION as ct, PAIRING_PROTOCOL as d, mintAgentUiUnlockTicket as dt, isValidAgentNodeId as et, PAIRING_TTL_MS as f, parseAgentDashboardOrigins as ft, keyFingerprintShort as g, parseCidrList as gt, describeCsr as h, normalizeIp as ht, AgentPairing as i, AGENT_DASHBOARD_ORIGINS_FIELD as it, renewMeshCertificate as j, onProcessNodeRegistered as k, PAIRING_PATHS as l, UnlockTicketJtiStore as lt, computePairingSas as m, createCidrMatcher as mt, HubPairing as n, issueMeshLeafFromCsr as nt, PAIRING_CODE_DIGITS as o, AGENT_UI_UNLOCK_TYP as ot, computePairingCommitment as p, verifyAgentUiUnlockTicket as pt, requireProcessMeshCa as q, PairingHttpError as r, loadMeshCa as rt, PAIRING_MAX_CODE_ATTEMPTS as s, AGENT_UI_UNLOCK_USE as st, systemConfigMeshActions as t, issueMeshLeafForNode as tt, PAIRING_PIN_DIGITS as u, isAllowedAgentDashboardReturnTo as ut, verifyPairingProof as v, dropProcessPeer as w, Errors as x, MESH_TLS_PORT_HELLO_FIELD as y, RENEWAL_ABANDONED as z };