@camstack/server 1.2.731 → 1.2.733

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 (104) hide show
  1. package/CHANGELOG.md +13 -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/trpc/generated-cap-routers.js +49 -0
  5. package/dist/core/addon/addon-registry.service.js +61 -59
  6. package/package.json +11 -19
  7. package/system/dist/addon-runner.js +1 -0
  8. package/system/dist/addon-runner.mjs +2 -1
  9. package/system/dist/addon-utils.mjs +1 -1
  10. package/system/dist/{agent-https-AJPmB73W.mjs → agent-https-D3dptveB.mjs} +1 -1
  11. package/system/dist/{agent-https-CLJhq0GZ.js → agent-https-v5uyVgpk.js} +1 -1
  12. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  13. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +4 -4
  14. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  15. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +5 -5
  16. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  17. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  18. package/system/dist/builtins/autotrack/index.js +1 -1
  19. package/system/dist/builtins/autotrack/index.mjs +1 -1
  20. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  21. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +5 -5
  22. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  23. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  24. package/system/dist/builtins/camera-grid/index.js +1 -1
  25. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  26. package/system/dist/builtins/composer/composer.addon.js +3 -3
  27. package/system/dist/builtins/composer/composer.addon.mjs +3 -3
  28. package/system/dist/builtins/console-logging/index.js +1 -1
  29. package/system/dist/builtins/console-logging/index.mjs +1 -1
  30. package/system/dist/builtins/core-blocks/core-blocks.addon.js +2 -2
  31. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +2 -2
  32. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  33. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  34. package/system/dist/builtins/device-manager/device-manager.addon.js +220 -16
  35. package/system/dist/builtins/device-manager/device-manager.addon.mjs +220 -16
  36. package/system/dist/builtins/device-manager/discovery-proposal-service.d.ts +38 -0
  37. package/system/dist/builtins/device-manager/discovery-proposal-store.d.ts +28 -0
  38. package/system/dist/builtins/device-manager/record-kinds.d.ts +2 -1
  39. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  40. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  41. package/system/dist/builtins/keychain/index.js +3 -3
  42. package/system/dist/builtins/keychain/index.mjs +3 -3
  43. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  44. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  45. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  46. package/system/dist/builtins/local-auth/local-auth.addon.mjs +5 -5
  47. package/system/dist/builtins/local-network/local-network.addon.d.ts +10 -0
  48. package/system/dist/builtins/local-network/local-network.addon.js +297 -190
  49. package/system/dist/builtins/local-network/local-network.addon.mjs +294 -187
  50. package/system/dist/builtins/local-network/passive/discovery-watcher.d.ts +60 -0
  51. package/system/dist/builtins/local-network/passive/passive-io-node.d.ts +2 -0
  52. package/system/dist/builtins/local-network/passive/passive-packets.d.ts +10 -0
  53. package/system/dist/builtins/local-network/scan/dns-wire.d.ts +6 -2
  54. package/system/dist/builtins/local-network/scan/scan-engine.d.ts +1 -1
  55. package/system/dist/builtins/local-network/scan/scan-io.d.ts +6 -0
  56. package/system/dist/builtins/loki-logging/index.js +1 -1
  57. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  58. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  59. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +10 -10
  60. package/system/dist/builtins/platform-probe/index.js +1 -1
  61. package/system/dist/builtins/platform-probe/index.mjs +10 -10
  62. package/system/dist/builtins/record-entries/index.js +1 -1
  63. package/system/dist/builtins/record-entries/index.mjs +1 -1
  64. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  65. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  66. package/system/dist/builtins/snapshot/index.js +1 -1
  67. package/system/dist/builtins/snapshot/index.mjs +1 -1
  68. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  69. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +20 -20
  70. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  71. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  72. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +2 -2
  73. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +2 -2
  74. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  75. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  76. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  77. package/system/dist/builtins/system-config/system-config.addon.mjs +115 -115
  78. package/system/dist/builtins/winston-logging/index.js +1 -1
  79. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  80. package/system/dist/{composition-sources-D-S2hhdw.mjs → composition-sources-Dnyu7-1p.mjs} +1 -1
  81. package/system/dist/{composition-sources-BNBlJAgu.js → composition-sources-j_bFq7Tx.js} +1 -1
  82. package/system/dist/{constants-CKwdQTnw.js → constants-C6zJ_38f.js} +1 -1
  83. package/system/dist/{constants-DmithOex.mjs → constants-GDBin8zB.mjs} +1 -1
  84. package/system/dist/{coral-accelerators-BW3OcrLD.mjs → coral-accelerators-DBlgWB8k.mjs} +6 -6
  85. package/system/dist/{custom-action-registry-BIJZBObd.mjs → custom-action-registry-oHl1xltx.mjs} +37 -37
  86. package/system/dist/{device-ca-D-Cvxobt.mjs → device-ca-Bpqrad00.mjs} +1 -1
  87. package/system/dist/{device-ca-TbdQfW4d.js → device-ca-CV9QZvoy.js} +1 -1
  88. package/system/dist/{dist-dQKZfa3-.js → dist-CwYYyGAB.js} +227 -3
  89. package/system/dist/{dist-yrk6fm65.mjs → dist-DcHvuBfD.mjs} +210 -4
  90. package/system/dist/dns-wire-CqgMi_uB.js +202 -0
  91. package/system/dist/dns-wire-DO56tOHL.mjs +173 -0
  92. package/system/dist/file-host-worker.js +1 -1
  93. package/system/dist/file-host-worker.mjs +1 -1
  94. package/system/dist/{hub-mdns-ciao-Cae5VWUc.mjs → hub-mdns-ciao-D2sU6sKd.mjs} +2 -2
  95. package/system/dist/{hub-mdns-ciao-DP3_GNZw.js → hub-mdns-ciao-DNLnbJNG.js} +2 -2
  96. package/system/dist/index.js +24 -7
  97. package/system/dist/index.mjs +236 -219
  98. package/system/dist/{restore-archive-BJ5gxMvf.mjs → restore-archive-BGK6EnYj.mjs} +94 -94
  99. package/system/dist/{restore-archive-X9c_wEBY.js → restore-archive-xTqhDFkW.js} +1 -1
  100. package/system/dist/{retention-DBrdAv12.mjs → retention-CXu8PB2L.mjs} +1 -1
  101. package/system/dist/{retention-DRT2wUyB.js → retention-gQ3GIUA3.js} +1 -1
  102. package/system/dist/{wal-maintenance-Bi4yImEY.mjs → wal-maintenance-D7XmFaUD.mjs} +0 -0
  103. package/system/dist/{wal-maintenance-hsgNGrjh.js → wal-maintenance-Hwzm3DCe.js} +0 -0
  104. package/system/package.json +1 -1
@@ -1,7 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_chunk = require("../../chunk-Cek0wNdY.js");
3
- const require_dist = require("../../dist-dQKZfa3-.js");
4
- const require_hub_mdns_ciao = require("../../hub-mdns-ciao-DP3_GNZw.js");
3
+ const require_dist = require("../../dist-CwYYyGAB.js");
4
+ const require_dns_wire = require("../../dns-wire-CqgMi_uB.js");
5
+ const require_hub_mdns_ciao = require("../../hub-mdns-ciao-DNLnbJNG.js");
5
6
  let zod = require("zod");
6
7
  let node_net = require("node:net");
7
8
  let node_os = require("node:os");
@@ -572,175 +573,6 @@ function parseLocalHostname(raw) {
572
573
  };
573
574
  }
574
575
  //#endregion
575
- //#region src/builtins/local-network/scan/dns-wire.ts
576
- /**
577
- * DNS-SD wire format for the scan engine: one PTR question per service type,
578
- * and a parser that turns an answer into services (instance, host, port, TXT).
579
- */
580
- /** Top bit of the question class: ask for a unicast reply (RFC 6762). */
581
- var MDNS_QU_CLASS = 32769;
582
- var A = 1;
583
- var PTR = 12;
584
- var TXT = 16;
585
- var SRV = 33;
586
- var SRV_FIXED = 6;
587
- var MAX_NAME_HOPS = 16;
588
- var MDNS_PORT = 5353;
589
- var MDNS_GROUP = "224.0.0.251";
590
- /** `_esphomelib._tcp` and `_esphomelib._tcp.local.` name the same service. */
591
- function normalizeServiceType(serviceType) {
592
- const lower = serviceType.trim().toLowerCase().replace(/\.$/, "");
593
- return lower.endsWith(".local") ? lower.slice(0, -6) : lower;
594
- }
595
- function readName(buf, start) {
596
- const labels = [];
597
- let pos = start;
598
- let end = start;
599
- let jumped = false;
600
- for (let hops = 0; hops < MAX_NAME_HOPS; hops++) {
601
- if (pos < 0 || pos >= buf.length) return null;
602
- const len = buf[pos] ?? 0;
603
- if (len === 0) {
604
- if (!jumped) end = pos + 1;
605
- return {
606
- name: labels.join("."),
607
- end
608
- };
609
- }
610
- if ((len & 192) === 192) {
611
- if (pos + 1 >= buf.length) return null;
612
- if (!jumped) end = pos + 2;
613
- jumped = true;
614
- pos = (len & 63) << 8 | (buf[pos + 1] ?? 0);
615
- continue;
616
- }
617
- if ((len & 192) !== 0 || pos + 1 + len > buf.length) return null;
618
- labels.push(buf.subarray(pos + 1, pos + 1 + len).toString("utf8"));
619
- pos += 1 + len;
620
- if (!jumped) end = pos;
621
- }
622
- return null;
623
- }
624
- function readRecords(buf, offset, count) {
625
- const records = [];
626
- let pos = offset;
627
- for (let i = 0; i < count; i++) {
628
- const name = readName(buf, pos);
629
- if (name === null || name.end + 10 > buf.length) return null;
630
- const type = buf.readUInt16BE(name.end);
631
- const dataLength = buf.readUInt16BE(name.end + 8);
632
- const dataOffset = name.end + 10;
633
- if (dataOffset + dataLength > buf.length) return null;
634
- records.push({
635
- name: name.name,
636
- type,
637
- dataOffset,
638
- dataLength
639
- });
640
- pos = dataOffset + dataLength;
641
- }
642
- return {
643
- records,
644
- next: pos
645
- };
646
- }
647
- function parseTxt(buf, offset, length) {
648
- const out = {};
649
- let pos = offset;
650
- const end = offset + length;
651
- while (pos < end) {
652
- const len = buf[pos] ?? 0;
653
- pos += 1;
654
- if (len === 0 || pos + len > end) break;
655
- const entry = buf.subarray(pos, pos + len).toString("utf8");
656
- pos += len;
657
- const eq = entry.indexOf("=");
658
- if (eq < 0) out[entry] = "";
659
- else out[entry.slice(0, eq)] = entry.slice(eq + 1);
660
- }
661
- return out;
662
- }
663
- /** One PTR question per service type, all with the unicast-reply bit. */
664
- function buildPtrQuery(serviceTypes) {
665
- const header = Buffer.alloc(12);
666
- header.writeUInt16BE(serviceTypes.length, 4);
667
- const questions = serviceTypes.map((type) => {
668
- const encoded = `${normalizeServiceType(type)}.local`.split(".").filter((part) => part.length > 0).map((l) => Buffer.concat([Buffer.from([l.length]), Buffer.from(l)]));
669
- const tail = Buffer.alloc(4);
670
- tail.writeUInt16BE(PTR, 0);
671
- tail.writeUInt16BE(MDNS_QU_CLASS, 2);
672
- return Buffer.concat([
673
- ...encoded,
674
- Buffer.from([0]),
675
- tail
676
- ]);
677
- });
678
- return Buffer.concat([header, ...questions]);
679
- }
680
- /** The services advertised on one mDNS message; a malformed packet yields none. */
681
- function parseMdnsMessage(buf) {
682
- if (buf.length < 12) return [];
683
- const [questions = 0, answers = 0, authorities = 0, extra = 0] = [
684
- 4,
685
- 6,
686
- 8,
687
- 10
688
- ].map((o) => buf.readUInt16BE(o));
689
- let pos = 12;
690
- for (let i = 0; i < questions; i++) {
691
- const name = readName(buf, pos);
692
- if (name === null) return [];
693
- pos = name.end + 4;
694
- if (pos > buf.length) return [];
695
- }
696
- const records = [];
697
- for (const count of [
698
- answers,
699
- authorities,
700
- extra
701
- ]) {
702
- const read = readRecords(buf, pos, count);
703
- if (read === null) return [];
704
- records.push(...read.records);
705
- pos = read.next;
706
- }
707
- const ptrs = [];
708
- const srv = /* @__PURE__ */ new Map();
709
- const txt = /* @__PURE__ */ new Map();
710
- const addresses = /* @__PURE__ */ new Map();
711
- for (const rec of records) {
712
- const key = rec.name.toLowerCase();
713
- if (rec.type === PTR) {
714
- const target = readName(buf, rec.dataOffset);
715
- if (target !== null) ptrs.push({
716
- serviceType: rec.name,
717
- instance: target.name
718
- });
719
- } else if (rec.type === SRV && rec.dataLength >= SRV_FIXED) {
720
- const target = readName(buf, rec.dataOffset + SRV_FIXED);
721
- if (target !== null) srv.set(key, {
722
- target: target.name,
723
- port: buf.readUInt16BE(rec.dataOffset + 4)
724
- });
725
- } else if (rec.type === TXT) txt.set(key, parseTxt(buf, rec.dataOffset, rec.dataLength));
726
- 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]}`);
727
- }
728
- const out = [];
729
- for (const { serviceType, instance } of ptrs) {
730
- const service = srv.get(instance.toLowerCase());
731
- const target = service?.target ?? instance;
732
- out.push({
733
- serviceType: normalizeServiceType(serviceType),
734
- instance,
735
- address: addresses.get(target.toLowerCase()) ?? addresses.get(instance.toLowerCase()) ?? null,
736
- host: target,
737
- port: service?.port ?? 0,
738
- txt: txt.get(instance.toLowerCase()) ?? {}
739
- });
740
- }
741
- return out;
742
- }
743
- //#endregion
744
576
  //#region src/builtins/local-network/scan/scan-io.ts
745
577
  /** A hit carries at most this much of a response body. */
746
578
  var MAX_HIT_BODY_BYTES = 16 * 1024;
@@ -889,7 +721,7 @@ var UNICAST_RESEND_AT_MS = [900];
889
721
  var UNICAST_LISTEN_MS = 2e3;
890
722
  var WSD_GROUP = "239.255.255.250";
891
723
  var WSD_PORT = 3702;
892
- var SSDP_PORT = 1900;
724
+ var SSDP_PORT$2 = 1900;
893
725
  var MAX_HEADERS_PER_HIT = 32;
894
726
  function bucket(c, kind) {
895
727
  const existing = c.stats.get(kind);
@@ -967,23 +799,52 @@ function hubLinks(interfaces) {
967
799
  function instanceLabel(instance) {
968
800
  return instance.split("._")[0] ?? instance;
969
801
  }
802
+ /**
803
+ * One link: join 5353 on the group and ask QM, so the answer a router reflects from
804
+ * another VLAN (it arrives as multicast) is heard. A device on another VLAN ignores
805
+ * an off-link unicast-response query (RFC 6762 §11), so the old ephemeral-port QU
806
+ * query alone never found it. A bind or membership failure is a named skip and the
807
+ * link falls back to the QU query, which still finds same-link devices.
808
+ */
809
+ async function exchangeOnLink(deps, link, groupQuery, fallbackQuery) {
810
+ const request = {
811
+ targets: [{
812
+ host: require_dns_wire.MDNS_GROUP,
813
+ port: require_dns_wire.MDNS_PORT
814
+ }],
815
+ localAddress: link.address,
816
+ resendAtMs: MULTICAST_RESEND_AT_MS,
817
+ listenMs: MULTICAST_LISTEN_MS
818
+ };
819
+ try {
820
+ return await deps.io.udpExchange({
821
+ ...request,
822
+ payload: groupQuery,
823
+ bindPort: require_dns_wire.MDNS_PORT,
824
+ joinGroup: require_dns_wire.MDNS_GROUP
825
+ });
826
+ } catch (err) {
827
+ deps.logger.warn("local-network: mdns group listen skipped on link, using unicast-response query", { meta: {
828
+ link: link.address,
829
+ interface: link.name,
830
+ error: require_dist.errMsg(err)
831
+ } });
832
+ return deps.io.udpExchange({
833
+ ...request,
834
+ payload: fallbackQuery
835
+ });
836
+ }
837
+ }
970
838
  async function runMdns(deps, entries, subnets, c) {
971
839
  if (entries.length === 0) return;
972
- const query = buildPtrQuery([...new Set(entries.map((e) => normalizeServiceType(e.mode.serviceType)))]);
840
+ const types = [...new Set(entries.map((e) => require_dns_wire.normalizeServiceType(e.mode.serviceType)))];
841
+ const query = require_dns_wire.buildPtrQuery(types);
842
+ const groupQuery = require_dns_wire.buildPtrQuery(types, { unicastResponse: false });
973
843
  const replies = [];
974
844
  const links = hubLinks(deps.interfaces());
975
845
  for (const link of links) {
976
846
  bucket(c, "mdns").probed += 1;
977
- replies.push(...await deps.io.udpExchange({
978
- payload: query,
979
- targets: [{
980
- host: MDNS_GROUP,
981
- port: MDNS_PORT
982
- }],
983
- localAddress: link.address,
984
- resendAtMs: MULTICAST_RESEND_AT_MS,
985
- listenMs: MULTICAST_LISTEN_MS
986
- }));
847
+ replies.push(...await exchangeOnLink(deps, link, groupQuery, query));
987
848
  }
988
849
  const extraHosts = extraHostsOf(subnets);
989
850
  if (extraHosts.length > 0) {
@@ -992,14 +853,14 @@ async function runMdns(deps, entries, subnets, c) {
992
853
  payload: query,
993
854
  targets: extraHosts.map((host) => ({
994
855
  host,
995
- port: MDNS_PORT
856
+ port: require_dns_wire.MDNS_PORT
996
857
  })),
997
858
  resendAtMs: UNICAST_RESEND_AT_MS,
998
859
  listenMs: UNICAST_LISTEN_MS
999
860
  }));
1000
861
  }
1001
- for (const reply of dedupeReplies(replies)) for (const service of parseMdnsMessage(reply.data)) for (const entry of entries) {
1002
- if (normalizeServiceType(entry.mode.serviceType) !== service.serviceType) continue;
862
+ for (const reply of dedupeReplies(replies)) for (const service of require_dns_wire.parseMdnsMessage(reply.data)) for (const entry of entries) {
863
+ if (require_dns_wire.normalizeServiceType(entry.mode.serviceType) !== service.serviceType) continue;
1003
864
  const label = instanceLabel(service.instance);
1004
865
  if (entry.mode.instancePattern !== void 0 && !matches(entry.mode.instancePattern, label)) continue;
1005
866
  emit(c, entry, {
@@ -1114,10 +975,10 @@ function parseSsdp(data) {
1114
975
  }
1115
976
  async function runSsdp(deps, entries, subnets, c) {
1116
977
  for (const target of new Set(entries.map((e) => e.mode.searchTarget))) {
1117
- 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`), {
978
+ 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`), {
1118
979
  host: WSD_GROUP,
1119
- port: SSDP_PORT
1120
- }, SSDP_PORT, subnets, c);
980
+ port: SSDP_PORT$2
981
+ }, SSDP_PORT$2, subnets, c);
1121
982
  for (const reply of replies) {
1122
983
  const parsed = parseSsdp(reply.data);
1123
984
  if (parsed === null) continue;
@@ -1290,6 +1151,198 @@ async function runScan(deps, input) {
1290
1151
  };
1291
1152
  }
1292
1153
  //#endregion
1154
+ //#region src/builtins/local-network/passive/passive-packets.ts
1155
+ var MAX_HEADERS = 32;
1156
+ var SSDP_PORT$1 = 1900;
1157
+ function parseMdnsPacket(data) {
1158
+ return require_dns_wire.parseMdnsMessage(data).filter((service) => service.port > 0).map((service) => ({
1159
+ kind: "mdns",
1160
+ serviceType: service.serviceType,
1161
+ instance: service.instance,
1162
+ host: service.host,
1163
+ address: service.address,
1164
+ port: service.port,
1165
+ txt: service.txt
1166
+ }));
1167
+ }
1168
+ /** A NOTIFY (`NT`) or a search response (`ST`); an M-SEARCH request is somebody asking. */
1169
+ function parseSsdpPacket(data, from) {
1170
+ const lines = data.toString("utf8").split(/\r?\n/);
1171
+ const first = lines[0] ?? "";
1172
+ const isNotify = /^NOTIFY\s/i.test(first);
1173
+ if (!isNotify && !/^HTTP\/1\.[01]\s+200/.test(first)) return null;
1174
+ const headers = {};
1175
+ for (const line of lines.slice(1)) {
1176
+ const colon = line.indexOf(":");
1177
+ if (colon <= 0) continue;
1178
+ if (Object.keys(headers).length >= MAX_HEADERS) break;
1179
+ headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
1180
+ }
1181
+ if (isNotify && headers["nts"] !== "ssdp:alive") return null;
1182
+ const target = isNotify ? headers["nt"] : headers["st"];
1183
+ if (target === void 0 || target.length === 0) return null;
1184
+ return {
1185
+ kind: "ssdp",
1186
+ host: from,
1187
+ port: SSDP_PORT$1,
1188
+ target,
1189
+ headers
1190
+ };
1191
+ }
1192
+ /** What identifies a sighting for de-duplication: who said it and about what. */
1193
+ function observationKey(o) {
1194
+ return o.kind === "mdns" ? `mdns|${o.address ?? o.host}|${o.serviceType}|${o.instance}` : `ssdp|${o.host}|${o.target}`;
1195
+ }
1196
+ //#endregion
1197
+ //#region src/builtins/local-network/passive/discovery-watcher.ts
1198
+ /**
1199
+ * Passive discovery for the hub (D994): a listener on the mDNS and SSDP
1200
+ * multicast groups plus a low-cost sweep on a fixed schedule. Both end in the
1201
+ * same place, `device-manager`'s proposal stream, which persists them.
1202
+ *
1203
+ * The listener never asks anything on the wire. It de-duplicates what it hears
1204
+ * (a chatty device announces every few seconds), batches it, and hands the batch
1205
+ * over; the sweep runs the discovery the integrations already offer, at most one
1206
+ * at a time, once per {@link SWEEP_INTERVAL_MS}.
1207
+ */
1208
+ var SWEEP_INTERVAL_MS = 1800 * 1e3;
1209
+ var FLUSH_INTERVAL_MS = 5e3;
1210
+ /** Bound on the de-duplication memory. */
1211
+ var MAX_SEEN = 4096;
1212
+ var DiscoveryWatcher = class {
1213
+ deps;
1214
+ now;
1215
+ seen = /* @__PURE__ */ new Map();
1216
+ pending = [];
1217
+ dropped = 0;
1218
+ listener = null;
1219
+ flushTimer = null;
1220
+ sweepTimer = null;
1221
+ sweeping = false;
1222
+ running = false;
1223
+ constructor(deps) {
1224
+ this.deps = deps;
1225
+ this.now = deps.now ?? (() => Date.now());
1226
+ }
1227
+ async start(options) {
1228
+ if (this.running) return;
1229
+ this.running = true;
1230
+ this.sweepTimer = setInterval(() => void this.runSweep(), SWEEP_INTERVAL_MS);
1231
+ this.sweepTimer.unref?.();
1232
+ if (!options.passive) return;
1233
+ this.flushTimer = setInterval(() => void this.flush(), FLUSH_INTERVAL_MS);
1234
+ this.flushTimer.unref?.();
1235
+ this.listener = await this.deps.io.open((packet) => this.onPacket(packet), (protocol, error) => this.deps.logger.warn("passive discovery: listener unavailable", { meta: {
1236
+ protocol,
1237
+ error: require_dist.errMsg(error)
1238
+ } }));
1239
+ }
1240
+ async stop() {
1241
+ this.running = false;
1242
+ if (this.sweepTimer !== null) clearInterval(this.sweepTimer);
1243
+ if (this.flushTimer !== null) clearInterval(this.flushTimer);
1244
+ this.sweepTimer = null;
1245
+ this.flushTimer = null;
1246
+ this.listener?.close();
1247
+ this.listener = null;
1248
+ this.pending = [];
1249
+ }
1250
+ onPacket(packet) {
1251
+ const sightings = packet.protocol === "mdns" ? parseMdnsPacket(packet.data) : [parseSsdpPacket(packet.data, packet.from)].filter((o) => o !== null);
1252
+ const at = this.now();
1253
+ for (const sighting of sightings) {
1254
+ const key = observationKey(sighting);
1255
+ const last = this.seen.get(key);
1256
+ if (last !== void 0 && at - last < 6e5) continue;
1257
+ if (this.pending.length >= 512) {
1258
+ this.dropped += 1;
1259
+ continue;
1260
+ }
1261
+ this.remember(key, at);
1262
+ this.pending.push(sighting);
1263
+ }
1264
+ }
1265
+ remember(key, at) {
1266
+ if (this.seen.size >= MAX_SEEN) {
1267
+ for (const [k, t] of this.seen) if (at - t >= 6e5) this.seen.delete(k);
1268
+ if (this.seen.size >= MAX_SEEN) this.seen.clear();
1269
+ }
1270
+ this.seen.set(key, at);
1271
+ }
1272
+ /** Hand the batch over. A failed hand-over puts nothing back: a later sighting repeats it. */
1273
+ async flush() {
1274
+ if (this.dropped > 0) {
1275
+ this.deps.logger.warn("passive discovery: sightings dropped, queue full", { meta: { dropped: this.dropped } });
1276
+ this.dropped = 0;
1277
+ }
1278
+ if (this.pending.length === 0) return;
1279
+ const batch = this.pending;
1280
+ this.pending = [];
1281
+ try {
1282
+ await this.deps.sink.report(batch);
1283
+ } catch (err) {
1284
+ this.deps.logger.warn("passive discovery: could not report sightings", { meta: {
1285
+ count: batch.length,
1286
+ error: require_dist.errMsg(err)
1287
+ } });
1288
+ }
1289
+ }
1290
+ async runSweep() {
1291
+ if (this.sweeping) return;
1292
+ this.sweeping = true;
1293
+ try {
1294
+ await this.deps.sink.sweep();
1295
+ } catch (err) {
1296
+ this.deps.logger.warn("discovery sweep failed", { meta: { error: require_dist.errMsg(err) } });
1297
+ } finally {
1298
+ this.sweeping = false;
1299
+ }
1300
+ }
1301
+ };
1302
+ //#endregion
1303
+ //#region src/builtins/local-network/passive/passive-io-node.ts
1304
+ /** The real {@link PassiveListenIo}: two multicast UDP sockets. Not unit-tested; the watcher is. */
1305
+ var SSDP_GROUP = "239.255.255.250";
1306
+ var SSDP_PORT = 1900;
1307
+ function listenOn(protocol, port, group, onPacket, onError) {
1308
+ return new Promise((resolve) => {
1309
+ const socket = (0, node_dgram.createSocket)({
1310
+ type: "udp4",
1311
+ reuseAddr: true
1312
+ });
1313
+ socket.on("error", (err) => {
1314
+ onError(protocol, err);
1315
+ try {
1316
+ socket.close();
1317
+ } catch {}
1318
+ resolve(null);
1319
+ });
1320
+ socket.on("message", (data, rinfo) => onPacket({
1321
+ protocol,
1322
+ data,
1323
+ from: rinfo.address
1324
+ }));
1325
+ socket.bind(port, () => {
1326
+ try {
1327
+ socket.addMembership(group);
1328
+ resolve(socket);
1329
+ } catch (err) {
1330
+ onError(protocol, err instanceof Error ? err : new Error(String(err)));
1331
+ socket.close();
1332
+ resolve(null);
1333
+ }
1334
+ });
1335
+ });
1336
+ }
1337
+ var nodePassiveListenIo = { async open(onPacket, onError) {
1338
+ const sockets = (await Promise.all([listenOn("mdns", require_dns_wire.MDNS_PORT, require_dns_wire.MDNS_GROUP, onPacket, onError), listenOn("ssdp", SSDP_PORT, SSDP_GROUP, onPacket, onError)])).filter((s) => s !== null);
1339
+ return { close: () => {
1340
+ for (const s of sockets) try {
1341
+ s.close();
1342
+ } catch {}
1343
+ } };
1344
+ } };
1345
+ //#endregion
1293
1346
  //#region src/builtins/local-network/scan/scan-io-node.ts
1294
1347
  /** The real {@link ScanIo}: node `dgram`, `http` and `https`. Not unit-tested; the engine is. */
1295
1348
  function udpExchange(request) {
@@ -1300,9 +1353,13 @@ function udpExchange(request) {
1300
1353
  });
1301
1354
  const replies = [];
1302
1355
  let settled = false;
1356
+ let joined = false;
1303
1357
  const finish = (error) => {
1304
1358
  if (settled) return;
1305
1359
  settled = true;
1360
+ if (joined && request.joinGroup !== void 0) try {
1361
+ socket.dropMembership(request.joinGroup, request.localAddress);
1362
+ } catch {}
1306
1363
  try {
1307
1364
  socket.close();
1308
1365
  } catch {}
@@ -1317,8 +1374,13 @@ function udpExchange(request) {
1317
1374
  data
1318
1375
  });
1319
1376
  });
1320
- socket.bind(request.bindPort ?? 0, request.localAddress ?? void 0, () => {
1377
+ const bindAddress = request.joinGroup === void 0 ? request.localAddress : void 0;
1378
+ socket.bind(request.bindPort ?? 0, bindAddress, () => {
1321
1379
  try {
1380
+ if (request.joinGroup !== void 0) {
1381
+ socket.addMembership(request.joinGroup, request.localAddress);
1382
+ joined = true;
1383
+ }
1322
1384
  if (request.broadcast === true) socket.setBroadcast(true);
1323
1385
  if (request.localAddress !== void 0) socket.setMulticastInterface(request.localAddress);
1324
1386
  } catch (err) {
@@ -1446,6 +1508,8 @@ var LocalNetworkAddon = class extends require_dist.BaseAddon {
1446
1508
  */
1447
1509
  meshEndpoint = null;
1448
1510
  mdns = null;
1511
+ discoveryWatcher = null;
1512
+ watcherPassive = true;
1449
1513
  constructor() {
1450
1514
  super({
1451
1515
  allowedAddresses: [],
@@ -1460,6 +1524,7 @@ var LocalNetworkAddon = class extends require_dist.BaseAddon {
1460
1524
  internalUrl: "",
1461
1525
  publicEndpointUrl: "",
1462
1526
  mdnsAdvertise: true,
1527
+ passiveDiscovery: true,
1463
1528
  scanSubnets: []
1464
1529
  });
1465
1530
  }
@@ -1801,6 +1866,9 @@ var LocalNetworkAddon = class extends require_dist.BaseAddon {
1801
1866
  this.ctx.logger.warn("local-network: LAN HTTP not applied at boot", { meta: { error: err instanceof Error ? err.message : String(err) } });
1802
1867
  }
1803
1868
  await this.applyMdnsAdvertisement();
1869
+ this.applyDiscoveryWatcher().catch((err) => {
1870
+ this.ctx.logger.warn("local-network: discovery watcher not started", { meta: { error: err instanceof Error ? err.message : String(err) } });
1871
+ });
1804
1872
  return [{
1805
1873
  capability: require_dist.localNetworkCapability,
1806
1874
  provider
@@ -1859,6 +1927,16 @@ var LocalNetworkAddon = class extends require_dist.BaseAddon {
1859
1927
  style: "switch",
1860
1928
  default: true
1861
1929
  }),
1930
+ this.field({
1931
+ type: "boolean",
1932
+ key: "passiveDiscovery",
1933
+ label: "Find new devices on the LAN by listening",
1934
+ labelKey: "server:globalSettings.s_local-access.passiveDiscovery.label",
1935
+ 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).",
1936
+ descriptionKey: "server:globalSettings.s_local-access.passiveDiscovery.description",
1937
+ style: "switch",
1938
+ default: true
1939
+ }),
1862
1940
  this.field({
1863
1941
  type: "text",
1864
1942
  key: "localHostname",
@@ -1875,6 +1953,33 @@ var LocalNetworkAddon = class extends require_dist.BaseAddon {
1875
1953
  async onConfigChanged() {
1876
1954
  await this.applyLanAccessFromSettings();
1877
1955
  await this.applyMdnsAdvertisement();
1956
+ await this.applyDiscoveryWatcher();
1957
+ }
1958
+ /**
1959
+ * (Re)start the passive listener and the 30-minute sweep, both feeding the
1960
+ * proposal stream of device-manager. Never throws: a socket that cannot open
1961
+ * is logged by the watcher and the sweep still runs.
1962
+ */
1963
+ async applyDiscoveryWatcher() {
1964
+ const passive = this.config.passiveDiscovery !== false;
1965
+ if (this.discoveryWatcher !== null && passive === this.watcherPassive) return;
1966
+ await this.discoveryWatcher?.stop();
1967
+ const api = this.ctx.api;
1968
+ if (api === void 0) return;
1969
+ this.watcherPassive = passive;
1970
+ this.discoveryWatcher = new DiscoveryWatcher({
1971
+ io: nodePassiveListenIo,
1972
+ logger: this.ctx.logger.child("discovery"),
1973
+ sink: {
1974
+ report: async (observations) => {
1975
+ await api.deviceManager.reportDiscoveryObservations.mutate({ observations: [...observations] });
1976
+ },
1977
+ sweep: async () => {
1978
+ await api.deviceManager.runDiscoverySweep.mutate({});
1979
+ }
1980
+ }
1981
+ });
1982
+ await this.discoveryWatcher.start({ passive });
1878
1983
  }
1879
1984
  /**
1880
1985
  * Start, re-announce or stop the hub's mDNS service (D838). Never throws:
@@ -1895,6 +2000,8 @@ var LocalNetworkAddon = class extends require_dist.BaseAddon {
1895
2000
  await this.mdns.start();
1896
2001
  }
1897
2002
  async onShutdown() {
2003
+ await this.discoveryWatcher?.stop();
2004
+ this.discoveryWatcher = null;
1898
2005
  await this.mdns?.stop();
1899
2006
  this.mdns = null;
1900
2007
  if (this.pollTimer) {