@camstack/server 1.2.730 → 1.2.732

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 (105) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/api/core/cap-providers.js +1 -0
  3. package/dist/api/core/logging-settings.js +88 -1
  4. package/dist/api/core/server-management.provider.js +10 -3
  5. package/dist/api/trpc/generated-cap-mounts.js +2 -1
  6. package/dist/api/trpc/generated-cap-routers.js +1850 -1777
  7. package/dist/boot/boot-config.js +2 -46
  8. package/dist/core/addon/addon-registry.service.js +61 -59
  9. package/dist/launch-args.js +72 -34
  10. package/dist/main.js +2 -1
  11. package/package.json +14 -19
  12. package/system/dist/addon-runner.js +82911 -12
  13. package/system/dist/addon-runner.mjs +82910 -11
  14. package/system/dist/{agent-https-DZq8uf8L.mjs → agent-https-CDtAIEne.mjs} +1 -1
  15. package/system/dist/{agent-https-C8Gz2jjS.js → agent-https-DKMO-__h.js} +1 -1
  16. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  17. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  18. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  19. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  20. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  21. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  22. package/system/dist/builtins/autotrack/index.js +1 -1
  23. package/system/dist/builtins/autotrack/index.mjs +1 -1
  24. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  25. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  26. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  27. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  28. package/system/dist/builtins/camera-grid/index.js +1 -1
  29. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  30. package/system/dist/builtins/composer/composer.addon.js +3 -3
  31. package/system/dist/builtins/composer/composer.addon.mjs +3 -3
  32. package/system/dist/builtins/console-logging/index.js +1 -1
  33. package/system/dist/builtins/console-logging/index.mjs +1 -1
  34. package/system/dist/builtins/core-blocks/core-blocks.addon.js +2 -2
  35. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +2 -2
  36. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  37. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  38. package/system/dist/builtins/device-manager/device-manager.addon.js +220 -16
  39. package/system/dist/builtins/device-manager/device-manager.addon.mjs +220 -16
  40. package/system/dist/builtins/device-manager/discovery-proposal-service.d.ts +38 -0
  41. package/system/dist/builtins/device-manager/discovery-proposal-store.d.ts +28 -0
  42. package/system/dist/builtins/device-manager/record-kinds.d.ts +2 -1
  43. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  44. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  45. package/system/dist/builtins/keychain/index.js +3 -3
  46. package/system/dist/builtins/keychain/index.mjs +3 -3
  47. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  48. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  49. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  50. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  51. package/system/dist/builtins/local-network/local-network.addon.d.ts +10 -0
  52. package/system/dist/builtins/local-network/local-network.addon.js +250 -181
  53. package/system/dist/builtins/local-network/local-network.addon.mjs +244 -175
  54. package/system/dist/builtins/local-network/passive/discovery-watcher.d.ts +60 -0
  55. package/system/dist/builtins/local-network/passive/passive-io-node.d.ts +2 -0
  56. package/system/dist/builtins/local-network/passive/passive-packets.d.ts +10 -0
  57. package/system/dist/builtins/loki-logging/index.js +1 -1
  58. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  59. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  60. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  61. package/system/dist/builtins/platform-probe/index.js +1 -1
  62. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  63. package/system/dist/builtins/record-entries/index.js +1 -1
  64. package/system/dist/builtins/record-entries/index.mjs +1 -1
  65. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  66. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  67. package/system/dist/builtins/snapshot/index.js +1 -1
  68. package/system/dist/builtins/snapshot/index.mjs +1 -1
  69. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  70. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  71. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  72. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  73. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +2 -2
  74. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +2 -2
  75. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  76. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  77. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  78. package/system/dist/builtins/system-config/system-config.addon.mjs +3 -3
  79. package/system/dist/builtins/winston-logging/index.js +1 -1
  80. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  81. package/system/dist/{composition-sources-4M_NnTnV.mjs → composition-sources-Ca7JEbmu.mjs} +1 -1
  82. package/system/dist/{composition-sources-hokiaS3J.js → composition-sources-UQohOHgd.js} +1 -1
  83. package/system/dist/{constants-B0L3suFC.js → constants-CLA4ogvA.js} +1 -1
  84. package/system/dist/{constants-DTVU00LZ.mjs → constants-iG57sUNp.mjs} +1 -1
  85. package/system/dist/{device-ca-C_y2GrU5.mjs → device-ca--iHw76cR.mjs} +1 -1
  86. package/system/dist/{device-ca-DaTT1Y9v.js → device-ca-BUcHAAew.js} +1 -1
  87. package/system/dist/{dist-9lvgpcnm.mjs → dist-C_cZ9rGK.mjs} +404 -18
  88. package/system/dist/{dist-B3S0ruBa.js → dist-qO48FNMZ.js} +427 -17
  89. package/system/dist/dns-wire-CHXO1qSl.js +199 -0
  90. package/system/dist/dns-wire-DcL6a0L-.mjs +170 -0
  91. package/system/dist/file-host-worker.js +1 -1
  92. package/system/dist/file-host-worker.mjs +1 -1
  93. package/system/dist/{hub-mdns-ciao-xgLfZIVx.mjs → hub-mdns-ciao-9wPOmsXd.mjs} +2 -2
  94. package/system/dist/{hub-mdns-ciao-Dkw38L-g.js → hub-mdns-ciao-DDmMPZCN.js} +2 -2
  95. package/system/dist/index.d.ts +1 -1
  96. package/system/dist/index.js +36 -9
  97. package/system/dist/index.mjs +36 -10
  98. package/system/dist/kernel/heap-watch.d.ts +7 -2
  99. package/system/dist/{restore-archive-cxnuWxQM.mjs → restore-archive-BHVjOlza.mjs} +1 -1
  100. package/system/dist/{restore-archive-orP6eHBd.js → restore-archive-Cravj5LG.js} +1 -1
  101. package/system/dist/{retention-CB2cyW9k.js → retention-B_eloRtb.js} +1 -1
  102. package/system/dist/{retention-Me4u6zMp.mjs → retention-C_9dxCQn.mjs} +1 -1
  103. package/system/dist/{wal-maintenance-_PXj626-.js → wal-maintenance-CfKeIQAG.js} +0 -0
  104. package/system/dist/{wal-maintenance-De7Ifvph.mjs → wal-maintenance-Dw7rplkv.mjs} +0 -0
  105. package/system/package.json +4 -1
@@ -1,5 +1,6 @@
1
- import { Bi as resolveHubAddressRoles, Ca as validateCustomAddress, En as checkRoleAddress, Gr as localNetworkCapability, Ii as resolveAppConnections, Nr as isDefaultAppConnectionEndpoint, Tt as NetworkTunnelStartedDataSchema, Us as errMsg, Wi as resolveNotificationTapAddress, Ws as EventCategory, _ as CAMSTACK_APP_LINK_ORIGIN, bi as pickAppLinkHub, kr as isAppLinkBase, lt as HUB_MDNS_SERVICE_TYPE, ra as shortHostname, uo as BaseAddon, ut as HUB_MDNS_TXT_KEYS } from "../../dist-9lvgpcnm.mjs";
2
- import { E as ensureTlsCert, I as readLanHttpState, N as applyLanHttp, _ as readTlsMode, a as storeUploadedCertificate, b as writeTlsEnabled, d as servedHttpsLeafFingerprint, h as readTlsAccessStatus, i as revertToGeneratedCertificate, j as DEFAULT_LAN_HTTP_PORT, m as readExtraSans, n as applyCertificateToListener, o as useStoredUploadedCertificate, r as regenerateCertificate, t as createCiaoPublisher, y as writeExtraSans } from "../../hub-mdns-ciao-xgLfZIVx.mjs";
1
+ import { Bi as resolveAppConnections, Da as validateCustomAddress, Dn as checkRoleAddress, Et as NetworkTunnelStartedDataSchema, Ji as resolveNotificationTapAddress, Js as EventCategory, Lr as isDefaultAppConnectionEndpoint, Mr as isAppLinkBase, Wi as resolveHubAddressRoles, Yr as localNetworkCapability, _ as CAMSTACK_APP_LINK_ORIGIN, dt as HUB_MDNS_TXT_KEYS, mo as BaseAddon, qs as errMsg, sa as shortHostname, ut as HUB_MDNS_SERVICE_TYPE, wi as pickAppLinkHub } from "../../dist-C_cZ9rGK.mjs";
2
+ import { a as parseMdnsMessage, i as normalizeServiceType, n as MDNS_PORT, r as buildPtrQuery, t as MDNS_GROUP } from "../../dns-wire-DcL6a0L-.mjs";
3
+ import { E as ensureTlsCert, I as readLanHttpState, N as applyLanHttp, _ as readTlsMode, a as storeUploadedCertificate, b as writeTlsEnabled, d as servedHttpsLeafFingerprint, h as readTlsAccessStatus, i as revertToGeneratedCertificate, j as DEFAULT_LAN_HTTP_PORT, m as readExtraSans, n as applyCertificateToListener, o as useStoredUploadedCertificate, r as regenerateCertificate, t as createCiaoPublisher, y as writeExtraSans } from "../../hub-mdns-ciao-9wPOmsXd.mjs";
3
4
  import { z } from "zod";
4
5
  import { isIP } from "node:net";
5
6
  import * as os$1 from "node:os";
@@ -567,175 +568,6 @@ function parseLocalHostname(raw) {
567
568
  };
568
569
  }
569
570
  //#endregion
570
- //#region src/builtins/local-network/scan/dns-wire.ts
571
- /**
572
- * DNS-SD wire format for the scan engine: one PTR question per service type,
573
- * and a parser that turns an answer into services (instance, host, port, TXT).
574
- */
575
- /** Top bit of the question class: ask for a unicast reply (RFC 6762). */
576
- var MDNS_QU_CLASS = 32769;
577
- var A = 1;
578
- var PTR = 12;
579
- var TXT = 16;
580
- var SRV = 33;
581
- var SRV_FIXED = 6;
582
- var MAX_NAME_HOPS = 16;
583
- var MDNS_PORT = 5353;
584
- var MDNS_GROUP = "224.0.0.251";
585
- /** `_esphomelib._tcp` and `_esphomelib._tcp.local.` name the same service. */
586
- function normalizeServiceType(serviceType) {
587
- const lower = serviceType.trim().toLowerCase().replace(/\.$/, "");
588
- return lower.endsWith(".local") ? lower.slice(0, -6) : lower;
589
- }
590
- function readName(buf, start) {
591
- const labels = [];
592
- let pos = start;
593
- let end = start;
594
- let jumped = false;
595
- for (let hops = 0; hops < MAX_NAME_HOPS; hops++) {
596
- if (pos < 0 || pos >= buf.length) return null;
597
- const len = buf[pos] ?? 0;
598
- if (len === 0) {
599
- if (!jumped) end = pos + 1;
600
- return {
601
- name: labels.join("."),
602
- end
603
- };
604
- }
605
- if ((len & 192) === 192) {
606
- if (pos + 1 >= buf.length) return null;
607
- if (!jumped) end = pos + 2;
608
- jumped = true;
609
- pos = (len & 63) << 8 | (buf[pos + 1] ?? 0);
610
- continue;
611
- }
612
- if ((len & 192) !== 0 || pos + 1 + len > buf.length) return null;
613
- labels.push(buf.subarray(pos + 1, pos + 1 + len).toString("utf8"));
614
- pos += 1 + len;
615
- if (!jumped) end = pos;
616
- }
617
- return null;
618
- }
619
- function readRecords(buf, offset, count) {
620
- const records = [];
621
- let pos = offset;
622
- for (let i = 0; i < count; i++) {
623
- const name = readName(buf, pos);
624
- if (name === null || name.end + 10 > buf.length) return null;
625
- const type = buf.readUInt16BE(name.end);
626
- const dataLength = buf.readUInt16BE(name.end + 8);
627
- const dataOffset = name.end + 10;
628
- if (dataOffset + dataLength > buf.length) return null;
629
- records.push({
630
- name: name.name,
631
- type,
632
- dataOffset,
633
- dataLength
634
- });
635
- pos = dataOffset + dataLength;
636
- }
637
- return {
638
- records,
639
- next: pos
640
- };
641
- }
642
- function parseTxt(buf, offset, length) {
643
- const out = {};
644
- let pos = offset;
645
- const end = offset + length;
646
- while (pos < end) {
647
- const len = buf[pos] ?? 0;
648
- pos += 1;
649
- if (len === 0 || pos + len > end) break;
650
- const entry = buf.subarray(pos, pos + len).toString("utf8");
651
- pos += len;
652
- const eq = entry.indexOf("=");
653
- if (eq < 0) out[entry] = "";
654
- else out[entry.slice(0, eq)] = entry.slice(eq + 1);
655
- }
656
- return out;
657
- }
658
- /** One PTR question per service type, all with the unicast-reply bit. */
659
- function buildPtrQuery(serviceTypes) {
660
- const header = Buffer.alloc(12);
661
- header.writeUInt16BE(serviceTypes.length, 4);
662
- const questions = serviceTypes.map((type) => {
663
- const encoded = `${normalizeServiceType(type)}.local`.split(".").filter((part) => part.length > 0).map((l) => Buffer.concat([Buffer.from([l.length]), Buffer.from(l)]));
664
- const tail = Buffer.alloc(4);
665
- tail.writeUInt16BE(PTR, 0);
666
- tail.writeUInt16BE(MDNS_QU_CLASS, 2);
667
- return Buffer.concat([
668
- ...encoded,
669
- Buffer.from([0]),
670
- tail
671
- ]);
672
- });
673
- return Buffer.concat([header, ...questions]);
674
- }
675
- /** The services advertised on one mDNS message; a malformed packet yields none. */
676
- function parseMdnsMessage(buf) {
677
- if (buf.length < 12) return [];
678
- const [questions = 0, answers = 0, authorities = 0, extra = 0] = [
679
- 4,
680
- 6,
681
- 8,
682
- 10
683
- ].map((o) => buf.readUInt16BE(o));
684
- let pos = 12;
685
- for (let i = 0; i < questions; i++) {
686
- const name = readName(buf, pos);
687
- if (name === null) return [];
688
- pos = name.end + 4;
689
- if (pos > buf.length) return [];
690
- }
691
- const records = [];
692
- for (const count of [
693
- answers,
694
- authorities,
695
- extra
696
- ]) {
697
- const read = readRecords(buf, pos, count);
698
- if (read === null) return [];
699
- records.push(...read.records);
700
- pos = read.next;
701
- }
702
- const ptrs = [];
703
- const srv = /* @__PURE__ */ new Map();
704
- const txt = /* @__PURE__ */ new Map();
705
- const addresses = /* @__PURE__ */ new Map();
706
- for (const rec of records) {
707
- const key = rec.name.toLowerCase();
708
- if (rec.type === PTR) {
709
- const target = readName(buf, rec.dataOffset);
710
- if (target !== null) ptrs.push({
711
- serviceType: rec.name,
712
- instance: target.name
713
- });
714
- } else if (rec.type === SRV && rec.dataLength >= SRV_FIXED) {
715
- const target = readName(buf, rec.dataOffset + SRV_FIXED);
716
- if (target !== null) srv.set(key, {
717
- target: target.name,
718
- port: buf.readUInt16BE(rec.dataOffset + 4)
719
- });
720
- } else if (rec.type === TXT) txt.set(key, parseTxt(buf, rec.dataOffset, rec.dataLength));
721
- else if (rec.type === A && rec.dataLength === 4) addresses.set(key, `${buf[rec.dataOffset]}.${buf[rec.dataOffset + 1]}.${buf[rec.dataOffset + 2]}.${buf[rec.dataOffset + 3]}`);
722
- }
723
- const out = [];
724
- for (const { serviceType, instance } of ptrs) {
725
- const service = srv.get(instance.toLowerCase());
726
- const target = service?.target ?? instance;
727
- out.push({
728
- serviceType: normalizeServiceType(serviceType),
729
- instance,
730
- address: addresses.get(target.toLowerCase()) ?? addresses.get(instance.toLowerCase()) ?? null,
731
- host: target,
732
- port: service?.port ?? 0,
733
- txt: txt.get(instance.toLowerCase()) ?? {}
734
- });
735
- }
736
- return out;
737
- }
738
- //#endregion
739
571
  //#region src/builtins/local-network/scan/scan-io.ts
740
572
  /** A hit carries at most this much of a response body. */
741
573
  var MAX_HIT_BODY_BYTES = 16 * 1024;
@@ -884,7 +716,7 @@ var UNICAST_RESEND_AT_MS = [900];
884
716
  var UNICAST_LISTEN_MS = 2e3;
885
717
  var WSD_GROUP = "239.255.255.250";
886
718
  var WSD_PORT = 3702;
887
- var SSDP_PORT = 1900;
719
+ var SSDP_PORT$2 = 1900;
888
720
  var MAX_HEADERS_PER_HIT = 32;
889
721
  function bucket(c, kind) {
890
722
  const existing = c.stats.get(kind);
@@ -1109,10 +941,10 @@ function parseSsdp(data) {
1109
941
  }
1110
942
  async function runSsdp(deps, entries, subnets, c) {
1111
943
  for (const target of new Set(entries.map((e) => e.mode.searchTarget))) {
1112
- const replies = await exchangeEverywhere(deps, "ssdp", Buffer.from(`M-SEARCH * HTTP/1.1\r\nHOST: ${WSD_GROUP}:${SSDP_PORT}\r\nMAN: "ssdp:discover"\r\nMX: 1\r\nST: ${target}\r\n\r\n`), {
944
+ const replies = await exchangeEverywhere(deps, "ssdp", Buffer.from(`M-SEARCH * HTTP/1.1\r\nHOST: ${WSD_GROUP}:${SSDP_PORT$2}\r\nMAN: "ssdp:discover"\r\nMX: 1\r\nST: ${target}\r\n\r\n`), {
1113
945
  host: WSD_GROUP,
1114
- port: SSDP_PORT
1115
- }, SSDP_PORT, subnets, c);
946
+ port: SSDP_PORT$2
947
+ }, SSDP_PORT$2, subnets, c);
1116
948
  for (const reply of replies) {
1117
949
  const parsed = parseSsdp(reply.data);
1118
950
  if (parsed === null) continue;
@@ -1285,6 +1117,198 @@ async function runScan(deps, input) {
1285
1117
  };
1286
1118
  }
1287
1119
  //#endregion
1120
+ //#region src/builtins/local-network/passive/passive-packets.ts
1121
+ var MAX_HEADERS = 32;
1122
+ var SSDP_PORT$1 = 1900;
1123
+ function parseMdnsPacket(data) {
1124
+ return parseMdnsMessage(data).filter((service) => service.port > 0).map((service) => ({
1125
+ kind: "mdns",
1126
+ serviceType: service.serviceType,
1127
+ instance: service.instance,
1128
+ host: service.host,
1129
+ address: service.address,
1130
+ port: service.port,
1131
+ txt: service.txt
1132
+ }));
1133
+ }
1134
+ /** A NOTIFY (`NT`) or a search response (`ST`); an M-SEARCH request is somebody asking. */
1135
+ function parseSsdpPacket(data, from) {
1136
+ const lines = data.toString("utf8").split(/\r?\n/);
1137
+ const first = lines[0] ?? "";
1138
+ const isNotify = /^NOTIFY\s/i.test(first);
1139
+ if (!isNotify && !/^HTTP\/1\.[01]\s+200/.test(first)) return null;
1140
+ const headers = {};
1141
+ for (const line of lines.slice(1)) {
1142
+ const colon = line.indexOf(":");
1143
+ if (colon <= 0) continue;
1144
+ if (Object.keys(headers).length >= MAX_HEADERS) break;
1145
+ headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
1146
+ }
1147
+ if (isNotify && headers["nts"] !== "ssdp:alive") return null;
1148
+ const target = isNotify ? headers["nt"] : headers["st"];
1149
+ if (target === void 0 || target.length === 0) return null;
1150
+ return {
1151
+ kind: "ssdp",
1152
+ host: from,
1153
+ port: SSDP_PORT$1,
1154
+ target,
1155
+ headers
1156
+ };
1157
+ }
1158
+ /** What identifies a sighting for de-duplication: who said it and about what. */
1159
+ function observationKey(o) {
1160
+ return o.kind === "mdns" ? `mdns|${o.address ?? o.host}|${o.serviceType}|${o.instance}` : `ssdp|${o.host}|${o.target}`;
1161
+ }
1162
+ //#endregion
1163
+ //#region src/builtins/local-network/passive/discovery-watcher.ts
1164
+ /**
1165
+ * Passive discovery for the hub (D994): a listener on the mDNS and SSDP
1166
+ * multicast groups plus a low-cost sweep on a fixed schedule. Both end in the
1167
+ * same place, `device-manager`'s proposal stream, which persists them.
1168
+ *
1169
+ * The listener never asks anything on the wire. It de-duplicates what it hears
1170
+ * (a chatty device announces every few seconds), batches it, and hands the batch
1171
+ * over; the sweep runs the discovery the integrations already offer, at most one
1172
+ * at a time, once per {@link SWEEP_INTERVAL_MS}.
1173
+ */
1174
+ var SWEEP_INTERVAL_MS = 1800 * 1e3;
1175
+ var FLUSH_INTERVAL_MS = 5e3;
1176
+ /** Bound on the de-duplication memory. */
1177
+ var MAX_SEEN = 4096;
1178
+ var DiscoveryWatcher = class {
1179
+ deps;
1180
+ now;
1181
+ seen = /* @__PURE__ */ new Map();
1182
+ pending = [];
1183
+ dropped = 0;
1184
+ listener = null;
1185
+ flushTimer = null;
1186
+ sweepTimer = null;
1187
+ sweeping = false;
1188
+ running = false;
1189
+ constructor(deps) {
1190
+ this.deps = deps;
1191
+ this.now = deps.now ?? (() => Date.now());
1192
+ }
1193
+ async start(options) {
1194
+ if (this.running) return;
1195
+ this.running = true;
1196
+ this.sweepTimer = setInterval(() => void this.runSweep(), SWEEP_INTERVAL_MS);
1197
+ this.sweepTimer.unref?.();
1198
+ if (!options.passive) return;
1199
+ this.flushTimer = setInterval(() => void this.flush(), FLUSH_INTERVAL_MS);
1200
+ this.flushTimer.unref?.();
1201
+ this.listener = await this.deps.io.open((packet) => this.onPacket(packet), (protocol, error) => this.deps.logger.warn("passive discovery: listener unavailable", { meta: {
1202
+ protocol,
1203
+ error: errMsg(error)
1204
+ } }));
1205
+ }
1206
+ async stop() {
1207
+ this.running = false;
1208
+ if (this.sweepTimer !== null) clearInterval(this.sweepTimer);
1209
+ if (this.flushTimer !== null) clearInterval(this.flushTimer);
1210
+ this.sweepTimer = null;
1211
+ this.flushTimer = null;
1212
+ this.listener?.close();
1213
+ this.listener = null;
1214
+ this.pending = [];
1215
+ }
1216
+ onPacket(packet) {
1217
+ const sightings = packet.protocol === "mdns" ? parseMdnsPacket(packet.data) : [parseSsdpPacket(packet.data, packet.from)].filter((o) => o !== null);
1218
+ const at = this.now();
1219
+ for (const sighting of sightings) {
1220
+ const key = observationKey(sighting);
1221
+ const last = this.seen.get(key);
1222
+ if (last !== void 0 && at - last < 6e5) continue;
1223
+ if (this.pending.length >= 512) {
1224
+ this.dropped += 1;
1225
+ continue;
1226
+ }
1227
+ this.remember(key, at);
1228
+ this.pending.push(sighting);
1229
+ }
1230
+ }
1231
+ remember(key, at) {
1232
+ if (this.seen.size >= MAX_SEEN) {
1233
+ for (const [k, t] of this.seen) if (at - t >= 6e5) this.seen.delete(k);
1234
+ if (this.seen.size >= MAX_SEEN) this.seen.clear();
1235
+ }
1236
+ this.seen.set(key, at);
1237
+ }
1238
+ /** Hand the batch over. A failed hand-over puts nothing back: a later sighting repeats it. */
1239
+ async flush() {
1240
+ if (this.dropped > 0) {
1241
+ this.deps.logger.warn("passive discovery: sightings dropped, queue full", { meta: { dropped: this.dropped } });
1242
+ this.dropped = 0;
1243
+ }
1244
+ if (this.pending.length === 0) return;
1245
+ const batch = this.pending;
1246
+ this.pending = [];
1247
+ try {
1248
+ await this.deps.sink.report(batch);
1249
+ } catch (err) {
1250
+ this.deps.logger.warn("passive discovery: could not report sightings", { meta: {
1251
+ count: batch.length,
1252
+ error: errMsg(err)
1253
+ } });
1254
+ }
1255
+ }
1256
+ async runSweep() {
1257
+ if (this.sweeping) return;
1258
+ this.sweeping = true;
1259
+ try {
1260
+ await this.deps.sink.sweep();
1261
+ } catch (err) {
1262
+ this.deps.logger.warn("discovery sweep failed", { meta: { error: errMsg(err) } });
1263
+ } finally {
1264
+ this.sweeping = false;
1265
+ }
1266
+ }
1267
+ };
1268
+ //#endregion
1269
+ //#region src/builtins/local-network/passive/passive-io-node.ts
1270
+ /** The real {@link PassiveListenIo}: two multicast UDP sockets. Not unit-tested; the watcher is. */
1271
+ var SSDP_GROUP = "239.255.255.250";
1272
+ var SSDP_PORT = 1900;
1273
+ function listenOn(protocol, port, group, onPacket, onError) {
1274
+ return new Promise((resolve) => {
1275
+ const socket = createSocket({
1276
+ type: "udp4",
1277
+ reuseAddr: true
1278
+ });
1279
+ socket.on("error", (err) => {
1280
+ onError(protocol, err);
1281
+ try {
1282
+ socket.close();
1283
+ } catch {}
1284
+ resolve(null);
1285
+ });
1286
+ socket.on("message", (data, rinfo) => onPacket({
1287
+ protocol,
1288
+ data,
1289
+ from: rinfo.address
1290
+ }));
1291
+ socket.bind(port, () => {
1292
+ try {
1293
+ socket.addMembership(group);
1294
+ resolve(socket);
1295
+ } catch (err) {
1296
+ onError(protocol, err instanceof Error ? err : new Error(String(err)));
1297
+ socket.close();
1298
+ resolve(null);
1299
+ }
1300
+ });
1301
+ });
1302
+ }
1303
+ var nodePassiveListenIo = { async open(onPacket, onError) {
1304
+ const sockets = (await Promise.all([listenOn("mdns", MDNS_PORT, MDNS_GROUP, onPacket, onError), listenOn("ssdp", SSDP_PORT, SSDP_GROUP, onPacket, onError)])).filter((s) => s !== null);
1305
+ return { close: () => {
1306
+ for (const s of sockets) try {
1307
+ s.close();
1308
+ } catch {}
1309
+ } };
1310
+ } };
1311
+ //#endregion
1288
1312
  //#region src/builtins/local-network/scan/scan-io-node.ts
1289
1313
  /** The real {@link ScanIo}: node `dgram`, `http` and `https`. Not unit-tested; the engine is. */
1290
1314
  function udpExchange(request) {
@@ -1441,6 +1465,8 @@ var LocalNetworkAddon = class extends BaseAddon {
1441
1465
  */
1442
1466
  meshEndpoint = null;
1443
1467
  mdns = null;
1468
+ discoveryWatcher = null;
1469
+ watcherPassive = true;
1444
1470
  constructor() {
1445
1471
  super({
1446
1472
  allowedAddresses: [],
@@ -1455,6 +1481,7 @@ var LocalNetworkAddon = class extends BaseAddon {
1455
1481
  internalUrl: "",
1456
1482
  publicEndpointUrl: "",
1457
1483
  mdnsAdvertise: true,
1484
+ passiveDiscovery: true,
1458
1485
  scanSubnets: []
1459
1486
  });
1460
1487
  }
@@ -1796,6 +1823,9 @@ var LocalNetworkAddon = class extends BaseAddon {
1796
1823
  this.ctx.logger.warn("local-network: LAN HTTP not applied at boot", { meta: { error: err instanceof Error ? err.message : String(err) } });
1797
1824
  }
1798
1825
  await this.applyMdnsAdvertisement();
1826
+ this.applyDiscoveryWatcher().catch((err) => {
1827
+ this.ctx.logger.warn("local-network: discovery watcher not started", { meta: { error: err instanceof Error ? err.message : String(err) } });
1828
+ });
1799
1829
  return [{
1800
1830
  capability: localNetworkCapability,
1801
1831
  provider
@@ -1854,6 +1884,16 @@ var LocalNetworkAddon = class extends BaseAddon {
1854
1884
  style: "switch",
1855
1885
  default: true
1856
1886
  }),
1887
+ this.field({
1888
+ type: "boolean",
1889
+ key: "passiveDiscovery",
1890
+ label: "Find new devices on the LAN by listening",
1891
+ labelKey: "server:globalSettings.s_local-access.passiveDiscovery.label",
1892
+ description: "On by default. Listens for mDNS and SSDP announcements and proposes the devices an integration can adopt; a low-cost scan also runs every 30 minutes. It never sends a probe of its own. Needs UDP multicast to reach the LAN (host networking or a dedicated container IP).",
1893
+ descriptionKey: "server:globalSettings.s_local-access.passiveDiscovery.description",
1894
+ style: "switch",
1895
+ default: true
1896
+ }),
1857
1897
  this.field({
1858
1898
  type: "text",
1859
1899
  key: "localHostname",
@@ -1870,6 +1910,33 @@ var LocalNetworkAddon = class extends BaseAddon {
1870
1910
  async onConfigChanged() {
1871
1911
  await this.applyLanAccessFromSettings();
1872
1912
  await this.applyMdnsAdvertisement();
1913
+ await this.applyDiscoveryWatcher();
1914
+ }
1915
+ /**
1916
+ * (Re)start the passive listener and the 30-minute sweep, both feeding the
1917
+ * proposal stream of device-manager. Never throws: a socket that cannot open
1918
+ * is logged by the watcher and the sweep still runs.
1919
+ */
1920
+ async applyDiscoveryWatcher() {
1921
+ const passive = this.config.passiveDiscovery !== false;
1922
+ if (this.discoveryWatcher !== null && passive === this.watcherPassive) return;
1923
+ await this.discoveryWatcher?.stop();
1924
+ const api = this.ctx.api;
1925
+ if (api === void 0) return;
1926
+ this.watcherPassive = passive;
1927
+ this.discoveryWatcher = new DiscoveryWatcher({
1928
+ io: nodePassiveListenIo,
1929
+ logger: this.ctx.logger.child("discovery"),
1930
+ sink: {
1931
+ report: async (observations) => {
1932
+ await api.deviceManager.reportDiscoveryObservations.mutate({ observations: [...observations] });
1933
+ },
1934
+ sweep: async () => {
1935
+ await api.deviceManager.runDiscoverySweep.mutate({});
1936
+ }
1937
+ }
1938
+ });
1939
+ await this.discoveryWatcher.start({ passive });
1873
1940
  }
1874
1941
  /**
1875
1942
  * Start, re-announce or stop the hub's mDNS service (D838). Never throws:
@@ -1890,6 +1957,8 @@ var LocalNetworkAddon = class extends BaseAddon {
1890
1957
  await this.mdns.start();
1891
1958
  }
1892
1959
  async onShutdown() {
1960
+ await this.discoveryWatcher?.stop();
1961
+ this.discoveryWatcher = null;
1893
1962
  await this.mdns?.stop();
1894
1963
  this.mdns = null;
1895
1964
  if (this.pollTimer) {
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Passive discovery for the hub (D994): a listener on the mDNS and SSDP
3
+ * multicast groups plus a low-cost sweep on a fixed schedule. Both end in the
4
+ * same place, `device-manager`'s proposal stream, which persists them.
5
+ *
6
+ * The listener never asks anything on the wire. It de-duplicates what it hears
7
+ * (a chatty device announces every few seconds), batches it, and hands the batch
8
+ * over; the sweep runs the discovery the integrations already offer, at most one
9
+ * at a time, once per {@link SWEEP_INTERVAL_MS}.
10
+ */
11
+ import { type DiscoveryObservation, type IScopedLogger } from "@camstack/types";
12
+ export declare const SWEEP_INTERVAL_MS: number;
13
+ /** A sighting already reported within this window is not reported again. */
14
+ export declare const SEEN_WINDOW_MS: number;
15
+ export declare const FLUSH_INTERVAL_MS = 5e3;
16
+ /** More distinct sightings than this between two flushes are dropped, and said so. */
17
+ export declare const MAX_PENDING = 512;
18
+ export interface PassivePacket {
19
+ readonly protocol: "mdns" | "ssdp";
20
+ readonly data: Buffer;
21
+ readonly from: string;
22
+ }
23
+ export interface PassiveListenIo {
24
+ open(onPacket: (packet: PassivePacket) => void, onError: (protocol: PassivePacket["protocol"], error: Error) => void): Promise<{
25
+ close(): void;
26
+ }>;
27
+ }
28
+ /** Where sightings and sweeps go: device-manager through `ctx.api`. */
29
+ export interface DiscoverySink {
30
+ report(observations: readonly DiscoveryObservation[]): Promise<void>;
31
+ sweep(): Promise<void>;
32
+ }
33
+ export interface DiscoveryWatcherDeps {
34
+ readonly io: PassiveListenIo;
35
+ readonly sink: DiscoverySink;
36
+ readonly logger: IScopedLogger;
37
+ readonly now?: () => number;
38
+ }
39
+ export declare class DiscoveryWatcher {
40
+ private readonly deps;
41
+ private readonly now;
42
+ private readonly seen;
43
+ private pending;
44
+ private dropped;
45
+ private listener;
46
+ private flushTimer;
47
+ private sweepTimer;
48
+ private sweeping;
49
+ private running;
50
+ constructor(deps: DiscoveryWatcherDeps);
51
+ start(options: {
52
+ readonly passive: boolean;
53
+ }): Promise<void>;
54
+ stop(): Promise<void>;
55
+ private onPacket;
56
+ private remember;
57
+ /** Hand the batch over. A failed hand-over puts nothing back: a later sighting repeats it. */
58
+ flush(): Promise<void>;
59
+ runSweep(): Promise<void>;
60
+ }
@@ -0,0 +1,2 @@
1
+ import type { PassiveListenIo } from "./discovery-watcher.js";
2
+ export declare const nodePassiveListenIo: PassiveListenIo;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Turn one multicast datagram into what the proposal stream understands.
3
+ * Pure: a malformed or irrelevant packet yields nothing.
4
+ */
5
+ import type { DiscoveryObservation } from "@camstack/types";
6
+ export declare function parseMdnsPacket(data: Buffer): readonly DiscoveryObservation[];
7
+ /** A NOTIFY (`NT`) or a search response (`ST`); an M-SEARCH request is somebody asking. */
8
+ export declare function parseSsdpPacket(data: Buffer, from: string): DiscoveryObservation | null;
9
+ /** What identifies a sighting for de-duplication: who said it and about what. */
10
+ export declare function observationKey(o: DiscoveryObservation): string;
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-B3S0ruBa.js");
6
+ const require_dist = require("../../dist-qO48FNMZ.js");
7
7
  const require_log_read_filter = require("../../log-read-filter-Bi066jwU.js");
8
8
  let zod = require("zod");
9
9
  //#region src/builtins/loki-logging/loki-payload.ts
@@ -1,4 +1,4 @@
1
- import { Yr as logDestinationCapability, uo as BaseAddon } from "../../dist-9lvgpcnm.mjs";
1
+ import { $r as logDestinationCapability, mo as BaseAddon } from "../../dist-C_cZ9rGK.mjs";
2
2
  import { n as compileLogFilter, o as lineMatches } from "../../log-read-filter-D7Ev3zm-.mjs";
3
3
  import { z } from "zod";
4
4
  //#region src/builtins/loki-logging/loki-payload.ts
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-B3S0ruBa.js");
6
+ const require_dist = require("../../dist-qO48FNMZ.js");
7
7
  let node_fs_promises = require("node:fs/promises");
8
8
  let node_util = require("node:util");
9
9
  let node_os = require("node:os");
@@ -1,4 +1,4 @@
1
- import { Li as resolveBucketMs, Mt as ROOT_BUCKET_KEY, Us as errMsg, Ws as EventCategory, Zt as UNATTRIBUTED_BUCKET_KEY, es as createEvent, ji as reducePoints, ri as metricsProviderCapability, uo as BaseAddon, yr as foldSnapshotByFunction } from "../../dist-9lvgpcnm.mjs";
1
+ import { Fi as reducePoints, Js as EventCategory, Nt as ROOT_BUCKET_KEY, Qt as UNATTRIBUTED_BUCKET_KEY, Vi as resolveBucketMs, is as createEvent, mo as BaseAddon, qs as errMsg, si as metricsProviderCapability, xr as foldSnapshotByFunction } from "../../dist-C_cZ9rGK.mjs";
2
2
  import { access, readFile, readdir } from "node:fs/promises";
3
3
  import { promisify } from "node:util";
4
4
  import * as os$1 from "node:os";
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-B3S0ruBa.js");
6
+ const require_dist = require("../../dist-qO48FNMZ.js");
7
7
  const require_coral_accelerators = require("../../coral-accelerators-BSVsBVzt.js");
8
8
  let node_path = require("node:path");
9
9
  node_path = require_chunk.__toESM(node_path);
@@ -1,5 +1,5 @@
1
1
  import { o as __toESM, r as __exportAll } from "../../chunk-CNf5ZN-e.mjs";
2
- import { Qi as scoreRuntimes, Si as platformProbeCapability, Us as errMsg, Ws as EventCategory, _i as parseAcceleratorFactsJson, ar as enumerateInferenceDevices, as as emitReadiness, uo as BaseAddon } from "../../dist-9lvgpcnm.mjs";
2
+ import { Ei as platformProbeCapability, Js as EventCategory, ls as emitReadiness, mo as BaseAddon, na as scoreRuntimes, qs as errMsg, sr as enumerateInferenceDevices, xi as parseAcceleratorFactsJson } from "../../dist-C_cZ9rGK.mjs";
3
3
  import { n as detectCoralAccelerator, r as nodeCoralFs } from "../../coral-accelerators-DBlgWB8k.mjs";
4
4
  import * as path$1 from "node:path";
5
5
  import { promisify } from "node:util";
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-B3S0ruBa.js");
6
+ const require_dist = require("../../dist-qO48FNMZ.js");
7
7
  let zod = require("zod");
8
8
  let node_crypto = require("node:crypto");
9
9
  //#region src/builtins/record-entries/entries-service.ts
@@ -1,4 +1,4 @@
1
- import { Ho as UnknownRecordKindError, Os as recordSecretRef, bo as InvalidRecordError, bs as mapSecretLeaves, ki as recordEntriesCapability, uo as BaseAddon } from "../../dist-9lvgpcnm.mjs";
1
+ import { Ko as UnknownRecordKindError, Ms as recordSecretRef, Ni as recordEntriesCapability, mo as BaseAddon, wo as InvalidRecordError, ws as mapSecretLeaves } from "../../dist-C_cZ9rGK.mjs";
2
2
  import { z } from "zod";
3
3
  import { randomUUID } from "node:crypto";
4
4
  //#region src/builtins/record-entries/entries-service.ts
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-B3S0ruBa.js");
6
+ const require_dist = require("../../dist-qO48FNMZ.js");
7
7
  //#region src/builtins/remote-access-orchestrator/enabled-providers-reconcile.ts
8
8
  /**
9
9
  * Reconcile the durable `enabledProviders` set against authoritative
@@ -1,4 +1,4 @@
1
- import { Ws as EventCategory, uo as BaseAddon } from "../../dist-9lvgpcnm.mjs";
1
+ import { Js as EventCategory, mo as BaseAddon } from "../../dist-C_cZ9rGK.mjs";
2
2
  //#region src/builtins/remote-access-orchestrator/enabled-providers-reconcile.ts
3
3
  /**
4
4
  * Reconcile the durable `enabledProviders` set against authoritative
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-B3S0ruBa.js");
6
+ const require_dist = require("../../dist-qO48FNMZ.js");
7
7
  const require_snapshot_courtesy = require("../../snapshot-courtesy-D_C5-nC0.js");
8
8
  let zod = require("zod");
9
9
  let node_crypto = require("node:crypto");
@@ -1,4 +1,4 @@
1
- import { Bs as DeviceFeature, Hs as DeviceType, Us as errMsg, Ws as EventCategory, Yn as deriveBatteryPresence, h as BatteryStatusSchema, ma as streamQualityLabel, mn as batteryCapability, oa as snapshotCapability, pn as bareAddonId, ti as memoizePinnedFfmpeg, uo as BaseAddon, xs as nodePin } from "../../dist-9lvgpcnm.mjs";
1
+ import { Js as EventCategory, Ks as DeviceType, Ts as nodePin, Ws as DeviceFeature, Zn as deriveBatteryPresence, ai as memoizePinnedFfmpeg, h as BatteryStatusSchema, hn as batteryCapability, mn as bareAddonId, mo as BaseAddon, qs as errMsg, ua as snapshotCapability, va as streamQualityLabel } from "../../dist-C_cZ9rGK.mjs";
2
2
  import { i as renderCourtesyOverlayJpeg, n as courtesyCacheKey, r as renderCourtesyJpeg } from "../../snapshot-courtesy-CyFs1M3I.mjs";
3
3
  import { z } from "zod";
4
4
  import { randomUUID } from "node:crypto";