@camstack/server 1.2.731 → 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 (101) hide show
  1. package/CHANGELOG.md +7 -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 +14 -19
  7. package/system/dist/addon-runner.js +82911 -12
  8. package/system/dist/addon-runner.mjs +82910 -11
  9. package/system/dist/addon-utils.mjs +1 -1
  10. package/system/dist/{agent-https-AJPmB73W.mjs → agent-https-CDtAIEne.mjs} +1 -1
  11. package/system/dist/{agent-https-CLJhq0GZ.js → agent-https-DKMO-__h.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 +250 -181
  49. package/system/dist/builtins/local-network/local-network.addon.mjs +244 -175
  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/loki-logging/index.js +1 -1
  54. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  55. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  56. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +10 -10
  57. package/system/dist/builtins/platform-probe/index.js +1 -1
  58. package/system/dist/builtins/platform-probe/index.mjs +10 -10
  59. package/system/dist/builtins/record-entries/index.js +1 -1
  60. package/system/dist/builtins/record-entries/index.mjs +1 -1
  61. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  62. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  63. package/system/dist/builtins/snapshot/index.js +1 -1
  64. package/system/dist/builtins/snapshot/index.mjs +1 -1
  65. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  66. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +20 -20
  67. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  68. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  69. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +2 -2
  70. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +2 -2
  71. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  72. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  73. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  74. package/system/dist/builtins/system-config/system-config.addon.mjs +115 -115
  75. package/system/dist/builtins/winston-logging/index.js +1 -1
  76. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  77. package/system/dist/{composition-sources-D-S2hhdw.mjs → composition-sources-Ca7JEbmu.mjs} +1 -1
  78. package/system/dist/{composition-sources-BNBlJAgu.js → composition-sources-UQohOHgd.js} +1 -1
  79. package/system/dist/{constants-CKwdQTnw.js → constants-CLA4ogvA.js} +1 -1
  80. package/system/dist/{constants-DmithOex.mjs → constants-iG57sUNp.mjs} +1 -1
  81. package/system/dist/{coral-accelerators-BW3OcrLD.mjs → coral-accelerators-DBlgWB8k.mjs} +6 -6
  82. package/system/dist/{custom-action-registry-BIJZBObd.mjs → custom-action-registry-oHl1xltx.mjs} +37 -37
  83. package/system/dist/{device-ca-D-Cvxobt.mjs → device-ca--iHw76cR.mjs} +1 -1
  84. package/system/dist/{device-ca-TbdQfW4d.js → device-ca-BUcHAAew.js} +1 -1
  85. package/system/dist/{dist-yrk6fm65.mjs → dist-C_cZ9rGK.mjs} +230 -3
  86. package/system/dist/{dist-dQKZfa3-.js → dist-qO48FNMZ.js} +253 -2
  87. package/system/dist/dns-wire-CHXO1qSl.js +199 -0
  88. package/system/dist/dns-wire-DcL6a0L-.mjs +170 -0
  89. package/system/dist/file-host-worker.js +1 -1
  90. package/system/dist/file-host-worker.mjs +1 -1
  91. package/system/dist/{hub-mdns-ciao-Cae5VWUc.mjs → hub-mdns-ciao-9wPOmsXd.mjs} +2 -2
  92. package/system/dist/{hub-mdns-ciao-DP3_GNZw.js → hub-mdns-ciao-DDmMPZCN.js} +2 -2
  93. package/system/dist/index.js +24 -7
  94. package/system/dist/index.mjs +235 -218
  95. package/system/dist/{restore-archive-BJ5gxMvf.mjs → restore-archive-BHVjOlza.mjs} +94 -94
  96. package/system/dist/{restore-archive-X9c_wEBY.js → restore-archive-Cravj5LG.js} +1 -1
  97. package/system/dist/{retention-DRT2wUyB.js → retention-B_eloRtb.js} +1 -1
  98. package/system/dist/{retention-DBrdAv12.mjs → retention-C_9dxCQn.mjs} +1 -1
  99. package/system/dist/{wal-maintenance-hsgNGrjh.js → wal-maintenance-CfKeIQAG.js} +0 -0
  100. package/system/dist/{wal-maintenance-Bi4yImEY.mjs → wal-maintenance-Dw7rplkv.mjs} +0 -0
  101. 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-qO48FNMZ.js");
4
+ const require_dns_wire = require("../../dns-wire-CHXO1qSl.js");
5
+ const require_hub_mdns_ciao = require("../../hub-mdns-ciao-DDmMPZCN.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);
@@ -969,7 +801,7 @@ function instanceLabel(instance) {
969
801
  }
970
802
  async function runMdns(deps, entries, subnets, c) {
971
803
  if (entries.length === 0) return;
972
- const query = buildPtrQuery([...new Set(entries.map((e) => normalizeServiceType(e.mode.serviceType)))]);
804
+ const query = require_dns_wire.buildPtrQuery([...new Set(entries.map((e) => require_dns_wire.normalizeServiceType(e.mode.serviceType)))]);
973
805
  const replies = [];
974
806
  const links = hubLinks(deps.interfaces());
975
807
  for (const link of links) {
@@ -977,8 +809,8 @@ async function runMdns(deps, entries, subnets, c) {
977
809
  replies.push(...await deps.io.udpExchange({
978
810
  payload: query,
979
811
  targets: [{
980
- host: MDNS_GROUP,
981
- port: MDNS_PORT
812
+ host: require_dns_wire.MDNS_GROUP,
813
+ port: require_dns_wire.MDNS_PORT
982
814
  }],
983
815
  localAddress: link.address,
984
816
  resendAtMs: MULTICAST_RESEND_AT_MS,
@@ -992,14 +824,14 @@ async function runMdns(deps, entries, subnets, c) {
992
824
  payload: query,
993
825
  targets: extraHosts.map((host) => ({
994
826
  host,
995
- port: MDNS_PORT
827
+ port: require_dns_wire.MDNS_PORT
996
828
  })),
997
829
  resendAtMs: UNICAST_RESEND_AT_MS,
998
830
  listenMs: UNICAST_LISTEN_MS
999
831
  }));
1000
832
  }
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;
833
+ for (const reply of dedupeReplies(replies)) for (const service of require_dns_wire.parseMdnsMessage(reply.data)) for (const entry of entries) {
834
+ if (require_dns_wire.normalizeServiceType(entry.mode.serviceType) !== service.serviceType) continue;
1003
835
  const label = instanceLabel(service.instance);
1004
836
  if (entry.mode.instancePattern !== void 0 && !matches(entry.mode.instancePattern, label)) continue;
1005
837
  emit(c, entry, {
@@ -1114,10 +946,10 @@ function parseSsdp(data) {
1114
946
  }
1115
947
  async function runSsdp(deps, entries, subnets, c) {
1116
948
  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`), {
949
+ 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
950
  host: WSD_GROUP,
1119
- port: SSDP_PORT
1120
- }, SSDP_PORT, subnets, c);
951
+ port: SSDP_PORT$2
952
+ }, SSDP_PORT$2, subnets, c);
1121
953
  for (const reply of replies) {
1122
954
  const parsed = parseSsdp(reply.data);
1123
955
  if (parsed === null) continue;
@@ -1290,6 +1122,198 @@ async function runScan(deps, input) {
1290
1122
  };
1291
1123
  }
1292
1124
  //#endregion
1125
+ //#region src/builtins/local-network/passive/passive-packets.ts
1126
+ var MAX_HEADERS = 32;
1127
+ var SSDP_PORT$1 = 1900;
1128
+ function parseMdnsPacket(data) {
1129
+ return require_dns_wire.parseMdnsMessage(data).filter((service) => service.port > 0).map((service) => ({
1130
+ kind: "mdns",
1131
+ serviceType: service.serviceType,
1132
+ instance: service.instance,
1133
+ host: service.host,
1134
+ address: service.address,
1135
+ port: service.port,
1136
+ txt: service.txt
1137
+ }));
1138
+ }
1139
+ /** A NOTIFY (`NT`) or a search response (`ST`); an M-SEARCH request is somebody asking. */
1140
+ function parseSsdpPacket(data, from) {
1141
+ const lines = data.toString("utf8").split(/\r?\n/);
1142
+ const first = lines[0] ?? "";
1143
+ const isNotify = /^NOTIFY\s/i.test(first);
1144
+ if (!isNotify && !/^HTTP\/1\.[01]\s+200/.test(first)) return null;
1145
+ const headers = {};
1146
+ for (const line of lines.slice(1)) {
1147
+ const colon = line.indexOf(":");
1148
+ if (colon <= 0) continue;
1149
+ if (Object.keys(headers).length >= MAX_HEADERS) break;
1150
+ headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
1151
+ }
1152
+ if (isNotify && headers["nts"] !== "ssdp:alive") return null;
1153
+ const target = isNotify ? headers["nt"] : headers["st"];
1154
+ if (target === void 0 || target.length === 0) return null;
1155
+ return {
1156
+ kind: "ssdp",
1157
+ host: from,
1158
+ port: SSDP_PORT$1,
1159
+ target,
1160
+ headers
1161
+ };
1162
+ }
1163
+ /** What identifies a sighting for de-duplication: who said it and about what. */
1164
+ function observationKey(o) {
1165
+ return o.kind === "mdns" ? `mdns|${o.address ?? o.host}|${o.serviceType}|${o.instance}` : `ssdp|${o.host}|${o.target}`;
1166
+ }
1167
+ //#endregion
1168
+ //#region src/builtins/local-network/passive/discovery-watcher.ts
1169
+ /**
1170
+ * Passive discovery for the hub (D994): a listener on the mDNS and SSDP
1171
+ * multicast groups plus a low-cost sweep on a fixed schedule. Both end in the
1172
+ * same place, `device-manager`'s proposal stream, which persists them.
1173
+ *
1174
+ * The listener never asks anything on the wire. It de-duplicates what it hears
1175
+ * (a chatty device announces every few seconds), batches it, and hands the batch
1176
+ * over; the sweep runs the discovery the integrations already offer, at most one
1177
+ * at a time, once per {@link SWEEP_INTERVAL_MS}.
1178
+ */
1179
+ var SWEEP_INTERVAL_MS = 1800 * 1e3;
1180
+ var FLUSH_INTERVAL_MS = 5e3;
1181
+ /** Bound on the de-duplication memory. */
1182
+ var MAX_SEEN = 4096;
1183
+ var DiscoveryWatcher = class {
1184
+ deps;
1185
+ now;
1186
+ seen = /* @__PURE__ */ new Map();
1187
+ pending = [];
1188
+ dropped = 0;
1189
+ listener = null;
1190
+ flushTimer = null;
1191
+ sweepTimer = null;
1192
+ sweeping = false;
1193
+ running = false;
1194
+ constructor(deps) {
1195
+ this.deps = deps;
1196
+ this.now = deps.now ?? (() => Date.now());
1197
+ }
1198
+ async start(options) {
1199
+ if (this.running) return;
1200
+ this.running = true;
1201
+ this.sweepTimer = setInterval(() => void this.runSweep(), SWEEP_INTERVAL_MS);
1202
+ this.sweepTimer.unref?.();
1203
+ if (!options.passive) return;
1204
+ this.flushTimer = setInterval(() => void this.flush(), FLUSH_INTERVAL_MS);
1205
+ this.flushTimer.unref?.();
1206
+ this.listener = await this.deps.io.open((packet) => this.onPacket(packet), (protocol, error) => this.deps.logger.warn("passive discovery: listener unavailable", { meta: {
1207
+ protocol,
1208
+ error: require_dist.errMsg(error)
1209
+ } }));
1210
+ }
1211
+ async stop() {
1212
+ this.running = false;
1213
+ if (this.sweepTimer !== null) clearInterval(this.sweepTimer);
1214
+ if (this.flushTimer !== null) clearInterval(this.flushTimer);
1215
+ this.sweepTimer = null;
1216
+ this.flushTimer = null;
1217
+ this.listener?.close();
1218
+ this.listener = null;
1219
+ this.pending = [];
1220
+ }
1221
+ onPacket(packet) {
1222
+ const sightings = packet.protocol === "mdns" ? parseMdnsPacket(packet.data) : [parseSsdpPacket(packet.data, packet.from)].filter((o) => o !== null);
1223
+ const at = this.now();
1224
+ for (const sighting of sightings) {
1225
+ const key = observationKey(sighting);
1226
+ const last = this.seen.get(key);
1227
+ if (last !== void 0 && at - last < 6e5) continue;
1228
+ if (this.pending.length >= 512) {
1229
+ this.dropped += 1;
1230
+ continue;
1231
+ }
1232
+ this.remember(key, at);
1233
+ this.pending.push(sighting);
1234
+ }
1235
+ }
1236
+ remember(key, at) {
1237
+ if (this.seen.size >= MAX_SEEN) {
1238
+ for (const [k, t] of this.seen) if (at - t >= 6e5) this.seen.delete(k);
1239
+ if (this.seen.size >= MAX_SEEN) this.seen.clear();
1240
+ }
1241
+ this.seen.set(key, at);
1242
+ }
1243
+ /** Hand the batch over. A failed hand-over puts nothing back: a later sighting repeats it. */
1244
+ async flush() {
1245
+ if (this.dropped > 0) {
1246
+ this.deps.logger.warn("passive discovery: sightings dropped, queue full", { meta: { dropped: this.dropped } });
1247
+ this.dropped = 0;
1248
+ }
1249
+ if (this.pending.length === 0) return;
1250
+ const batch = this.pending;
1251
+ this.pending = [];
1252
+ try {
1253
+ await this.deps.sink.report(batch);
1254
+ } catch (err) {
1255
+ this.deps.logger.warn("passive discovery: could not report sightings", { meta: {
1256
+ count: batch.length,
1257
+ error: require_dist.errMsg(err)
1258
+ } });
1259
+ }
1260
+ }
1261
+ async runSweep() {
1262
+ if (this.sweeping) return;
1263
+ this.sweeping = true;
1264
+ try {
1265
+ await this.deps.sink.sweep();
1266
+ } catch (err) {
1267
+ this.deps.logger.warn("discovery sweep failed", { meta: { error: require_dist.errMsg(err) } });
1268
+ } finally {
1269
+ this.sweeping = false;
1270
+ }
1271
+ }
1272
+ };
1273
+ //#endregion
1274
+ //#region src/builtins/local-network/passive/passive-io-node.ts
1275
+ /** The real {@link PassiveListenIo}: two multicast UDP sockets. Not unit-tested; the watcher is. */
1276
+ var SSDP_GROUP = "239.255.255.250";
1277
+ var SSDP_PORT = 1900;
1278
+ function listenOn(protocol, port, group, onPacket, onError) {
1279
+ return new Promise((resolve) => {
1280
+ const socket = (0, node_dgram.createSocket)({
1281
+ type: "udp4",
1282
+ reuseAddr: true
1283
+ });
1284
+ socket.on("error", (err) => {
1285
+ onError(protocol, err);
1286
+ try {
1287
+ socket.close();
1288
+ } catch {}
1289
+ resolve(null);
1290
+ });
1291
+ socket.on("message", (data, rinfo) => onPacket({
1292
+ protocol,
1293
+ data,
1294
+ from: rinfo.address
1295
+ }));
1296
+ socket.bind(port, () => {
1297
+ try {
1298
+ socket.addMembership(group);
1299
+ resolve(socket);
1300
+ } catch (err) {
1301
+ onError(protocol, err instanceof Error ? err : new Error(String(err)));
1302
+ socket.close();
1303
+ resolve(null);
1304
+ }
1305
+ });
1306
+ });
1307
+ }
1308
+ var nodePassiveListenIo = { async open(onPacket, onError) {
1309
+ 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);
1310
+ return { close: () => {
1311
+ for (const s of sockets) try {
1312
+ s.close();
1313
+ } catch {}
1314
+ } };
1315
+ } };
1316
+ //#endregion
1293
1317
  //#region src/builtins/local-network/scan/scan-io-node.ts
1294
1318
  /** The real {@link ScanIo}: node `dgram`, `http` and `https`. Not unit-tested; the engine is. */
1295
1319
  function udpExchange(request) {
@@ -1446,6 +1470,8 @@ var LocalNetworkAddon = class extends require_dist.BaseAddon {
1446
1470
  */
1447
1471
  meshEndpoint = null;
1448
1472
  mdns = null;
1473
+ discoveryWatcher = null;
1474
+ watcherPassive = true;
1449
1475
  constructor() {
1450
1476
  super({
1451
1477
  allowedAddresses: [],
@@ -1460,6 +1486,7 @@ var LocalNetworkAddon = class extends require_dist.BaseAddon {
1460
1486
  internalUrl: "",
1461
1487
  publicEndpointUrl: "",
1462
1488
  mdnsAdvertise: true,
1489
+ passiveDiscovery: true,
1463
1490
  scanSubnets: []
1464
1491
  });
1465
1492
  }
@@ -1801,6 +1828,9 @@ var LocalNetworkAddon = class extends require_dist.BaseAddon {
1801
1828
  this.ctx.logger.warn("local-network: LAN HTTP not applied at boot", { meta: { error: err instanceof Error ? err.message : String(err) } });
1802
1829
  }
1803
1830
  await this.applyMdnsAdvertisement();
1831
+ this.applyDiscoveryWatcher().catch((err) => {
1832
+ this.ctx.logger.warn("local-network: discovery watcher not started", { meta: { error: err instanceof Error ? err.message : String(err) } });
1833
+ });
1804
1834
  return [{
1805
1835
  capability: require_dist.localNetworkCapability,
1806
1836
  provider
@@ -1859,6 +1889,16 @@ var LocalNetworkAddon = class extends require_dist.BaseAddon {
1859
1889
  style: "switch",
1860
1890
  default: true
1861
1891
  }),
1892
+ this.field({
1893
+ type: "boolean",
1894
+ key: "passiveDiscovery",
1895
+ label: "Find new devices on the LAN by listening",
1896
+ labelKey: "server:globalSettings.s_local-access.passiveDiscovery.label",
1897
+ 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).",
1898
+ descriptionKey: "server:globalSettings.s_local-access.passiveDiscovery.description",
1899
+ style: "switch",
1900
+ default: true
1901
+ }),
1862
1902
  this.field({
1863
1903
  type: "text",
1864
1904
  key: "localHostname",
@@ -1875,6 +1915,33 @@ var LocalNetworkAddon = class extends require_dist.BaseAddon {
1875
1915
  async onConfigChanged() {
1876
1916
  await this.applyLanAccessFromSettings();
1877
1917
  await this.applyMdnsAdvertisement();
1918
+ await this.applyDiscoveryWatcher();
1919
+ }
1920
+ /**
1921
+ * (Re)start the passive listener and the 30-minute sweep, both feeding the
1922
+ * proposal stream of device-manager. Never throws: a socket that cannot open
1923
+ * is logged by the watcher and the sweep still runs.
1924
+ */
1925
+ async applyDiscoveryWatcher() {
1926
+ const passive = this.config.passiveDiscovery !== false;
1927
+ if (this.discoveryWatcher !== null && passive === this.watcherPassive) return;
1928
+ await this.discoveryWatcher?.stop();
1929
+ const api = this.ctx.api;
1930
+ if (api === void 0) return;
1931
+ this.watcherPassive = passive;
1932
+ this.discoveryWatcher = new DiscoveryWatcher({
1933
+ io: nodePassiveListenIo,
1934
+ logger: this.ctx.logger.child("discovery"),
1935
+ sink: {
1936
+ report: async (observations) => {
1937
+ await api.deviceManager.reportDiscoveryObservations.mutate({ observations: [...observations] });
1938
+ },
1939
+ sweep: async () => {
1940
+ await api.deviceManager.runDiscoverySweep.mutate({});
1941
+ }
1942
+ }
1943
+ });
1944
+ await this.discoveryWatcher.start({ passive });
1878
1945
  }
1879
1946
  /**
1880
1947
  * Start, re-announce or stop the hub's mDNS service (D838). Never throws:
@@ -1895,6 +1962,8 @@ var LocalNetworkAddon = class extends require_dist.BaseAddon {
1895
1962
  await this.mdns.start();
1896
1963
  }
1897
1964
  async onShutdown() {
1965
+ await this.discoveryWatcher?.stop();
1966
+ this.discoveryWatcher = null;
1898
1967
  await this.mdns?.stop();
1899
1968
  this.mdns = null;
1900
1969
  if (this.pollTimer) {