@profullstack/threatcrush 0.13.32 → 0.13.34

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.
package/dist/index.js CHANGED
@@ -7380,11 +7380,11 @@ function solve(total, items, gap = 0) {
7380
7380
  }
7381
7381
  }
7382
7382
  let assigned = 0;
7383
- const order = [...pending];
7384
- order.forEach((i, k) => {
7383
+ const order2 = [...pending];
7384
+ order2.forEach((i, k) => {
7385
7385
  const p = parsed[i];
7386
7386
  const exact = remainingFr > 0 ? pool * p.fr / remainingFr : 0;
7387
- const v = k === order.length - 1 ? Math.max(0, pool - assigned) : Math.floor(exact);
7387
+ const v = k === order2.length - 1 ? Math.max(0, pool - assigned) : Math.floor(exact);
7388
7388
  out[i] = v;
7389
7389
  assigned += v;
7390
7390
  });
@@ -11312,9 +11312,9 @@ function drawTabs(surface, options) {
11312
11312
  const total = options.tabs.reduce((a, t) => a + stringWidth(t) + 4, 0);
11313
11313
  let x = options.align === "center" ? Math.max(0, Math.floor((surface.width - total) / 2)) : options.align === "right" ? Math.max(0, surface.width - total) : 0;
11314
11314
  options.tabs.forEach((tab, i) => {
11315
- const active = i === options.active;
11315
+ const active2 = i === options.active;
11316
11316
  const label = ` ${tab} `;
11317
- const style = active ? variant2 === "filled" ? { fg: theme.dark ? theme.background : theme.surface, bg: color, attrs: Attr.Bold } : { fg: color, attrs: Attr.Bold | Attr.Underline } : { fg: theme.muted };
11317
+ const style = active2 ? variant2 === "filled" ? { fg: theme.dark ? theme.background : theme.surface, bg: color, attrs: Attr.Bold } : { fg: color, attrs: Attr.Bold | Attr.Underline } : { fg: theme.muted };
11318
11318
  x += surface.text(x, 0, label, style);
11319
11319
  });
11320
11320
  }
@@ -11450,9 +11450,9 @@ function drawSpinner(surface, options) {
11450
11450
  const theme = surface.theme;
11451
11451
  const named = typeof options.frames === "string" ? SPINNER_FRAMES[options.frames] : options.frames;
11452
11452
  const frames = named ?? SPINNER_FRAMES.dots;
11453
- const active = options.active ?? true;
11454
- const glyph = active ? spinnerFrame(options.elapsed, frames, options.interval) : options.doneGlyph ?? "\u2713";
11455
- const color = options.color ?? (active ? theme.accent : theme.success);
11453
+ const active2 = options.active ?? true;
11454
+ const glyph = active2 ? spinnerFrame(options.elapsed, frames, options.interval) : options.doneGlyph ?? "\u2713";
11455
+ const color = options.color ?? (active2 ? theme.accent : theme.success);
11456
11456
  const labelColor = options.labelColor ?? theme.foreground;
11457
11457
  const bg = options.background;
11458
11458
  const glyphWidth = stringWidth(glyph);
@@ -18611,14 +18611,14 @@ function drawEmojiPicker(root, options) {
18611
18611
  const tx = 1 + i * 3;
18612
18612
  if (tx + 3 > inner.width)
18613
18613
  return;
18614
- const active = tab === state.tab;
18614
+ const active2 = tab === state.tab;
18615
18615
  const glyph = icon(tab === EMOJI_RECENT ? "clock" : GROUP_ICONS[tab] ?? "smile");
18616
- if (active)
18616
+ if (active2)
18617
18617
  inner.fillRect(tx, 1, 3, 1, { bg: theme.selection });
18618
18618
  inner.text(tx, 1, fit(glyph, 3, "center"), {
18619
- fg: active ? theme.selectionText : muted,
18620
- bg: active ? theme.selection : void 0,
18621
- attrs: active ? Attr.Bold : 0
18619
+ fg: active2 ? theme.selectionText : muted,
18620
+ bg: active2 ? theme.selection : void 0,
18621
+ attrs: active2 ? Attr.Bold : 0
18622
18622
  });
18623
18623
  tabs.push({ rect: { x: origin.x + tx, y: origin.y + 1, width: 3, height: 1 }, tab });
18624
18624
  });
@@ -19911,9 +19911,9 @@ var init_app = __esm({
19911
19911
  return;
19912
19912
  } else if (event.name === "enter" || event.name === "space") {
19913
19913
  const copyFocused = this.focusConsumesKey[this.focusIndex];
19914
- const active = !copyFocused || this.focusEngaged || this.modal;
19915
- const consumed = active && (this.modal || copyFocused) && this.focusActions[this.focusIndex];
19916
- if (active)
19914
+ const active2 = !copyFocused || this.focusEngaged || this.modal;
19915
+ const consumed = active2 && (this.modal || copyFocused) && this.focusActions[this.focusIndex];
19916
+ if (active2)
19917
19917
  this.activateFocused();
19918
19918
  if (consumed)
19919
19919
  return;
@@ -24745,9 +24745,9 @@ var source_default = chalk;
24745
24745
 
24746
24746
  // src/index.ts
24747
24747
  var import_readline = __toESM(require("readline"));
24748
- var import_node_child_process17 = require("child_process");
24749
- var import_node_fs42 = require("fs");
24750
- var import_node_path30 = require("path");
24748
+ var import_node_child_process19 = require("child_process");
24749
+ var import_node_fs44 = require("fs");
24750
+ var import_node_path33 = require("path");
24751
24751
  var import_node_os13 = require("os");
24752
24752
 
24753
24753
  // src/commands/monitor.ts
@@ -31640,6 +31640,7 @@ function loadConfig(configPath) {
31640
31640
  cloud: parsed.cloud,
31641
31641
  watchdog: parsed.watchdog,
31642
31642
  update: parsed.update,
31643
+ threat_feeds: parsed.threat_feeds,
31643
31644
  storage: parsed.storage,
31644
31645
  license: parsed.license
31645
31646
  };
@@ -36680,12 +36681,12 @@ var import_node_path12 = require("path");
36680
36681
  var MAX_DEPS_PER_LOCKFILE = 50;
36681
36682
  async function scanDependencies(targetPath) {
36682
36683
  const findings = [];
36683
- for (const { file, ecosystem, parse: parse2 } of LOCKFILES) {
36684
+ for (const { file, ecosystem, parse: parse3 } of LOCKFILES) {
36684
36685
  const lockPath = (0, import_node_path12.join)(targetPath, file);
36685
36686
  if (!(0, import_node_fs14.existsSync)(lockPath)) continue;
36686
36687
  let deps;
36687
36688
  try {
36688
- deps = dedupe(parse2((0, import_node_fs14.readFileSync)(lockPath, "utf-8")));
36689
+ deps = dedupe(parse3((0, import_node_fs14.readFileSync)(lockPath, "utf-8")));
36689
36690
  } catch {
36690
36691
  continue;
36691
36692
  }
@@ -39779,16 +39780,16 @@ async function sshConnect(options) {
39779
39780
  }
39780
39781
 
39781
39782
  // src/commands/daemon.ts
39782
- var import_node_child_process13 = require("child_process");
39783
- var import_node_fs36 = require("fs");
39784
- var import_node_path27 = require("path");
39783
+ var import_node_child_process14 = require("child_process");
39785
39784
  var import_node_fs37 = require("fs");
39785
+ var import_node_path28 = require("path");
39786
+ var import_node_fs38 = require("fs");
39786
39787
 
39787
39788
  // src/daemon/index.ts
39788
- var import_node_fs35 = require("fs");
39789
- var import_node_child_process12 = require("child_process");
39789
+ var import_node_fs36 = require("fs");
39790
+ var import_node_child_process13 = require("child_process");
39790
39791
  var import_node_os11 = require("os");
39791
- var import_node_path26 = require("path");
39792
+ var import_node_path27 = require("path");
39792
39793
  var import_node_util = require("util");
39793
39794
  init_paths();
39794
39795
 
@@ -40091,8 +40092,8 @@ function admGid(readGroup = () => (0, import_node_fs24.readFileSync)("/etc/group
40091
40092
  }
40092
40093
 
40093
40094
  // src/daemon/module-host.ts
40094
- var import_node_fs28 = require("fs");
40095
- var import_node_path20 = require("path");
40095
+ var import_node_fs29 = require("fs");
40096
+ var import_node_path21 = require("path");
40096
40097
  var import_node_url = require("url");
40097
40098
  var import_toml4 = __toESM(require_toml());
40098
40099
  init_paths();
@@ -40668,9 +40669,347 @@ var NetworkMonitor = class {
40668
40669
  };
40669
40670
 
40670
40671
  // src/modules/dns-monitor/index.ts
40672
+ var import_node_fs28 = require("fs");
40673
+ var import_node_child_process8 = require("child_process");
40674
+ var import_node_readline3 = require("readline");
40675
+
40676
+ // src/core/threat-feeds/index.ts
40671
40677
  var import_node_fs27 = require("fs");
40678
+ var import_node_path20 = require("path");
40679
+ var import_node_net5 = require("net");
40680
+
40681
+ // src/daemon/firewall/protected.ts
40672
40682
  var import_node_child_process7 = require("child_process");
40673
- var import_node_readline3 = require("readline");
40683
+ var import_node_net4 = require("net");
40684
+ var DEFAULT_PROTECTED = [
40685
+ "127.0.0.0/8",
40686
+ "::1/128",
40687
+ "10.0.0.0/8",
40688
+ "172.16.0.0/12",
40689
+ "192.168.0.0/16",
40690
+ "169.254.0.0/16",
40691
+ "fc00::/7",
40692
+ "fe80::/10"
40693
+ ];
40694
+ function ipToBytes(ip) {
40695
+ const version = (0, import_node_net4.isIP)(ip);
40696
+ if (version === 4) return v4ToBytes(ip);
40697
+ if (version === 6) return v6ToBytes(ip);
40698
+ return null;
40699
+ }
40700
+ function v4ToBytes(ip) {
40701
+ const parts = ip.split(".");
40702
+ if (parts.length !== 4) return null;
40703
+ const bytes = new Uint8Array(4);
40704
+ for (let i = 0; i < 4; i++) {
40705
+ const n = Number(parts[i]);
40706
+ if (!Number.isInteger(n) || n < 0 || n > 255) return null;
40707
+ bytes[i] = n;
40708
+ }
40709
+ return bytes;
40710
+ }
40711
+ function v6ToBytes(ip) {
40712
+ const bare = ip.split("%")[0];
40713
+ const [headText, tailText] = bare.split("::", 2);
40714
+ const head = headText ? headText.split(":") : [];
40715
+ const tail = tailText !== void 0 ? tailText ? tailText.split(":") : [] : null;
40716
+ const groups = [];
40717
+ const pushGroup = (group) => {
40718
+ if (group.includes(".")) {
40719
+ const v4 = v4ToBytes(group);
40720
+ if (!v4) return false;
40721
+ groups.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
40722
+ return true;
40723
+ }
40724
+ if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return false;
40725
+ groups.push(parseInt(group, 16));
40726
+ return true;
40727
+ };
40728
+ for (const group of head) if (!pushGroup(group)) return null;
40729
+ const headCount = groups.length;
40730
+ if (tail === null) {
40731
+ if (headCount !== 8) return null;
40732
+ } else {
40733
+ const tailGroups = [];
40734
+ const saved = groups.length;
40735
+ for (const group of tail) if (!pushGroup(group)) return null;
40736
+ tailGroups.push(...groups.splice(saved));
40737
+ const zeros = 8 - headCount - tailGroups.length;
40738
+ if (zeros < 0) return null;
40739
+ for (let i = 0; i < zeros; i++) groups.push(0);
40740
+ groups.push(...tailGroups);
40741
+ }
40742
+ if (groups.length !== 8) return null;
40743
+ const bytes = new Uint8Array(16);
40744
+ for (let i = 0; i < 8; i++) {
40745
+ bytes[i * 2] = groups[i] >> 8 & 255;
40746
+ bytes[i * 2 + 1] = groups[i] & 255;
40747
+ }
40748
+ return bytes;
40749
+ }
40750
+ function ipMatches(ip, entry) {
40751
+ const [network, prefixText] = entry.trim().split("/");
40752
+ const target = ipToBytes(ip);
40753
+ const base = ipToBytes(network);
40754
+ if (!target || !base || target.length !== base.length) return false;
40755
+ const bits2 = prefixText === void 0 ? base.length * 8 : Number(prefixText);
40756
+ if (!Number.isInteger(bits2) || bits2 < 0 || bits2 > base.length * 8) return false;
40757
+ const wholeBytes = Math.floor(bits2 / 8);
40758
+ for (let i = 0; i < wholeBytes; i++) {
40759
+ if (target[i] !== base[i]) return false;
40760
+ }
40761
+ const remainder = bits2 % 8;
40762
+ if (remainder === 0) return true;
40763
+ const mask = 255 << 8 - remainder & 255;
40764
+ return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
40765
+ }
40766
+ function isProtected(ip, list) {
40767
+ return list.some((entry) => ipMatches(ip, entry));
40768
+ }
40769
+ function currentSshClient(env2 = process.env) {
40770
+ const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
40771
+ if (!source) return null;
40772
+ const ip = source.trim().split(/\s+/)[0];
40773
+ return ip && (0, import_node_net4.isIP)(ip) ? ip : null;
40774
+ }
40775
+ function establishedSshPeers() {
40776
+ const peers = /* @__PURE__ */ new Set();
40777
+ try {
40778
+ const out = (0, import_node_child_process7.execFileSync)("ss", ["-tnpH"], {
40779
+ encoding: "utf-8",
40780
+ stdio: ["ignore", "pipe", "ignore"],
40781
+ timeout: 3e3
40782
+ });
40783
+ for (const line2 of out.split("\n")) {
40784
+ if (!/users:\(\("sshd/.test(line2)) continue;
40785
+ const parts = line2.trim().split(/\s+/);
40786
+ const peer = parts[4];
40787
+ if (!peer) continue;
40788
+ const ip = peer.slice(0, peer.lastIndexOf(":")).replace(/^\[|\]$/g, "");
40789
+ if (ip && (0, import_node_net4.isIP)(ip)) peers.add(ip);
40790
+ }
40791
+ } catch {
40792
+ }
40793
+ return [...peers];
40794
+ }
40795
+ function defaultGateways() {
40796
+ const found = /* @__PURE__ */ new Set();
40797
+ for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
40798
+ try {
40799
+ const out = (0, import_node_child_process7.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
40800
+ for (const line2 of out.split("\n")) {
40801
+ const match = line2.match(/\bvia\s+(\S+)/);
40802
+ if (match && (0, import_node_net4.isIP)(match[1])) found.add(match[1]);
40803
+ }
40804
+ } catch {
40805
+ }
40806
+ }
40807
+ return [...found];
40808
+ }
40809
+
40810
+ // src/core/threat-feeds/index.ts
40811
+ var FEEDS = {
40812
+ threatfoxRecent: "https://threatfox.abuse.ch/export/json/recent/",
40813
+ threatfoxHosts: "https://threatfox.abuse.ch/downloads/hostfile/",
40814
+ urlhausHosts: "https://urlhaus.abuse.ch/downloads/hostfile/",
40815
+ feodoIps: "https://feodotracker.abuse.ch/downloads/ipblocklist.txt"
40816
+ };
40817
+ var SHARED_RANGES = [
40818
+ "173.245.48.0/20",
40819
+ "103.21.244.0/22",
40820
+ "103.22.200.0/22",
40821
+ "103.31.4.0/22",
40822
+ "141.101.64.0/18",
40823
+ "108.162.192.0/18",
40824
+ "190.93.240.0/20",
40825
+ "188.114.96.0/20",
40826
+ "197.234.240.0/22",
40827
+ "198.41.128.0/17",
40828
+ "162.158.0.0/15",
40829
+ "104.16.0.0/13",
40830
+ "104.24.0.0/14",
40831
+ "172.64.0.0/13",
40832
+ "131.0.72.0/22",
40833
+ "2400:cb00::/32",
40834
+ "2606:4700::/32",
40835
+ "2803:f800::/32",
40836
+ "2405:b500::/32",
40837
+ "2405:8100::/32",
40838
+ "2a06:98c0::/29",
40839
+ "2c0f:f248::/32",
40840
+ "1.1.1.1/32",
40841
+ "1.0.0.1/32",
40842
+ "8.8.8.8/32",
40843
+ "8.8.4.4/32",
40844
+ "9.9.9.9/32",
40845
+ "149.112.112.112/32",
40846
+ "208.67.222.222/32",
40847
+ "208.67.220.220/32"
40848
+ ];
40849
+ var SHARED_DOMAINS = /* @__PURE__ */ new Set([
40850
+ "workers.dev",
40851
+ "pages.dev",
40852
+ "github.io",
40853
+ "githubusercontent.com",
40854
+ "herokuapp.com",
40855
+ "vercel.app",
40856
+ "netlify.app",
40857
+ "azurewebsites.net",
40858
+ "blob.core.windows.net",
40859
+ "amazonaws.com",
40860
+ "cloudfront.net",
40861
+ "googleusercontent.com",
40862
+ "appspot.com",
40863
+ "firebaseapp.com",
40864
+ "web.app",
40865
+ "r2.dev",
40866
+ "ngrok.io",
40867
+ "ngrok-free.app",
40868
+ "duckdns.org",
40869
+ "discord.com",
40870
+ "discordapp.com",
40871
+ "telegram.org",
40872
+ "dropbox.com",
40873
+ "google.com"
40874
+ ]);
40875
+ function parseThreatFoxJson(text, minConfidence) {
40876
+ const ips = /* @__PURE__ */ new Map();
40877
+ const domains = /* @__PURE__ */ new Map();
40878
+ const data = JSON.parse(text);
40879
+ for (const entries of Object.values(data)) {
40880
+ for (const ioc of Array.isArray(entries) ? entries : []) {
40881
+ const confidence = typeof ioc.confidence_level === "number" ? ioc.confidence_level : 0;
40882
+ if (confidence < minConfidence) continue;
40883
+ const value = String(ioc.ioc_value ?? "").trim();
40884
+ const ind = {
40885
+ malware: String(ioc.malware_printable ?? ioc.malware ?? "unknown"),
40886
+ threat: String(ioc.threat_type ?? "unknown"),
40887
+ feed: "threatfox"
40888
+ };
40889
+ if (ioc.ioc_type === "ip:port") {
40890
+ if (ind.threat !== "botnet_cc" && ind.threat !== "payload_delivery") continue;
40891
+ const ip = stripPort(value);
40892
+ if (ip) ips.set(ip, ind);
40893
+ } else if (ioc.ioc_type === "domain") {
40894
+ const domain = normalizeDomain(value);
40895
+ if (domain) domains.set(domain, ind);
40896
+ }
40897
+ }
40898
+ }
40899
+ return { ips, domains };
40900
+ }
40901
+ function parseHostfile(text, feed) {
40902
+ const out = /* @__PURE__ */ new Map();
40903
+ for (const line2 of text.split("\n")) {
40904
+ const trimmed = line2.trim();
40905
+ if (!trimmed || trimmed.startsWith("#")) continue;
40906
+ const domain = normalizeDomain(trimmed.split(/\s+/)[1] ?? "");
40907
+ if (domain) out.set(domain, { malware: "unknown", threat: "malware_host", feed });
40908
+ }
40909
+ return out;
40910
+ }
40911
+ function parseIpList(text, feed) {
40912
+ const out = /* @__PURE__ */ new Map();
40913
+ for (const line2 of text.split("\n")) {
40914
+ const ip = line2.trim();
40915
+ if (ip && !ip.startsWith("#") && (0, import_node_net5.isIP)(ip)) out.set(ip, { malware: "unknown", threat: "botnet_cc", feed });
40916
+ }
40917
+ return out;
40918
+ }
40919
+ function stripPort(value) {
40920
+ const v6 = /^\[([^\]]+)\]:\d+$/.exec(value);
40921
+ const ip = v6 ? v6[1] : value.replace(/:\d+$/, "");
40922
+ return (0, import_node_net5.isIP)(ip) ? ip : null;
40923
+ }
40924
+ function normalizeDomain(value) {
40925
+ const d = value.trim().toLowerCase().replace(/\.$/, "");
40926
+ if (!d || d === "localhost" || (0, import_node_net5.isIP)(d) || !/^[a-z0-9_.-]+\.[a-z0-9-]{2,}$/.test(d)) return null;
40927
+ return d;
40928
+ }
40929
+ function allowedDomain(domain, allow) {
40930
+ return allow.some((a) => domain === a || domain.endsWith(`.${a}`));
40931
+ }
40932
+ function buildFeedSet(parts, allow, sources, now = /* @__PURE__ */ new Date()) {
40933
+ const neverIps = [...DEFAULT_PROTECTED, ...SHARED_RANGES, ...allow.filter((a) => (0, import_node_net5.isIP)(a.split("/")[0]))];
40934
+ const allowDomains = allow.filter((a) => !(0, import_node_net5.isIP)(a.split("/")[0])).map((a) => a.toLowerCase());
40935
+ const ips = {};
40936
+ const domains = {};
40937
+ let skipped = 0;
40938
+ for (const part of parts) {
40939
+ for (const [ip, ind] of part.ips ?? []) {
40940
+ if (isProtected(ip, neverIps)) {
40941
+ skipped++;
40942
+ continue;
40943
+ }
40944
+ ips[ip] ??= ind;
40945
+ }
40946
+ for (const [domain, ind] of part.domains ?? []) {
40947
+ if (SHARED_DOMAINS.has(domain) || allowedDomain(domain, allowDomains)) {
40948
+ skipped++;
40949
+ continue;
40950
+ }
40951
+ domains[domain] ??= ind;
40952
+ }
40953
+ }
40954
+ return { fetched_at: now.toISOString(), ips, domains, sources, skipped_shared: skipped };
40955
+ }
40956
+ async function fetchFeeds(settings, fetchImpl = fetch) {
40957
+ const sources = [];
40958
+ const parts = [];
40959
+ const get = async (feed, url, parse3) => {
40960
+ try {
40961
+ const res = await fetchImpl(url, { signal: AbortSignal.timeout(6e4), headers: { "User-Agent": "threatcrush (+https://threatcrush.com)" } });
40962
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
40963
+ const part = parse3(await res.text());
40964
+ parts.push(part);
40965
+ sources.push({ feed, ok: true, count: (part.ips?.size ?? 0) + (part.domains?.size ?? 0) });
40966
+ } catch (err) {
40967
+ sources.push({ feed, ok: false, count: 0, error: err.message });
40968
+ }
40969
+ };
40970
+ await Promise.all([
40971
+ get("threatfox", FEEDS.threatfoxRecent, (t) => parseThreatFoxJson(t, settings.minConfidence)),
40972
+ get("threatfox-hosts", FEEDS.threatfoxHosts, (t) => ({ domains: parseHostfile(t, "threatfox") })),
40973
+ get("urlhaus-hosts", FEEDS.urlhausHosts, (t) => ({ domains: parseHostfile(t, "urlhaus") })),
40974
+ get("feodo", FEEDS.feodoIps, (t) => ({ ips: parseIpList(t, "feodo") }))
40975
+ ]);
40976
+ return buildFeedSet(parts, settings.allow, sources);
40977
+ }
40978
+ function readFeedCache(path) {
40979
+ try {
40980
+ const set = JSON.parse((0, import_node_fs27.readFileSync)(path, "utf-8"));
40981
+ return set && typeof set.ips === "object" && typeof set.domains === "object" ? set : null;
40982
+ } catch {
40983
+ return null;
40984
+ }
40985
+ }
40986
+ function writeFeedCache(path, set) {
40987
+ (0, import_node_fs27.mkdirSync)((0, import_node_path20.dirname)(path), { recursive: true });
40988
+ const tmp = `${path}.tmp`;
40989
+ (0, import_node_fs27.writeFileSync)(tmp, JSON.stringify(set));
40990
+ (0, import_node_fs27.renameSync)(tmp, path);
40991
+ }
40992
+ var active = null;
40993
+ function setActiveFeeds(set) {
40994
+ active = set;
40995
+ }
40996
+ function matchIp(ip, set = active) {
40997
+ if (!set) return null;
40998
+ const bare = ip.replace(/^::ffff:/i, "");
40999
+ return set.ips[bare] ?? null;
41000
+ }
41001
+ function matchDomain(name, set = active) {
41002
+ if (!set) return null;
41003
+ const labels = (normalizeDomain(name) ?? "").split(".");
41004
+ for (let i = 0; i < labels.length - 1; i++) {
41005
+ const candidate = labels.slice(i).join(".");
41006
+ const hit = set.domains[candidate];
41007
+ if (hit) return { domain: candidate, indicator: hit };
41008
+ }
41009
+ return null;
41010
+ }
41011
+
41012
+ // src/modules/dns-monitor/index.ts
40674
41013
  var DNS_LOG_SOURCES = [
40675
41014
  "/var/log/syslog",
40676
41015
  // systemd-resolved logs here
@@ -40715,6 +41054,8 @@ var DnsMonitor = class {
40715
41054
  // Tracking windows
40716
41055
  txtQueryCounts = /* @__PURE__ */ new Map();
40717
41056
  domainBuffer = [];
41057
+ /** Last threat-feed alert per domain and client. */
41058
+ feedAlerts = /* @__PURE__ */ new Map();
40718
41059
  // Config
40719
41060
  txtRateThreshold = 20;
40720
41061
  // TXT queries per source per window
@@ -40738,7 +41079,7 @@ var DnsMonitor = class {
40738
41079
  /** True if a systemd unit is loaded on this host (so we do not tail nothing). */
40739
41080
  unitExists(unit) {
40740
41081
  try {
40741
- const r = (0, import_node_child_process7.spawnSync)("systemctl", ["show", unit, "--property=LoadState", "--value"], {
41082
+ const r = (0, import_node_child_process8.spawnSync)("systemctl", ["show", unit, "--property=LoadState", "--value"], {
40742
41083
  encoding: "utf-8",
40743
41084
  stdio: ["ignore", "pipe", "ignore"],
40744
41085
  timeout: 3e3
@@ -40750,9 +41091,9 @@ var DnsMonitor = class {
40750
41091
  }
40751
41092
  start() {
40752
41093
  const sources = [...DNS_LOG_SOURCES, ...this.extraPaths].filter((p) => {
40753
- if (!(0, import_node_fs27.existsSync)(p)) return false;
41094
+ if (!(0, import_node_fs28.existsSync)(p)) return false;
40754
41095
  try {
40755
- (0, import_node_fs27.accessSync)(p, import_node_fs27.constants.R_OK);
41096
+ (0, import_node_fs28.accessSync)(p, import_node_fs28.constants.R_OK);
40756
41097
  return true;
40757
41098
  } catch {
40758
41099
  return false;
@@ -40811,7 +41152,7 @@ var DnsMonitor = class {
40811
41152
  /** Follow one systemd unit's journal, feeding its lines to the same parser. */
40812
41153
  tailJournalUnit(unit) {
40813
41154
  try {
40814
- const child = (0, import_node_child_process7.spawn)("journalctl", ["-u", unit, "-f", "-n", "0", "--output=cat"], {
41155
+ const child = (0, import_node_child_process8.spawn)("journalctl", ["-u", unit, "-f", "-n", "0", "--output=cat"], {
40815
41156
  stdio: ["ignore", "pipe", "ignore"]
40816
41157
  });
40817
41158
  if (!child.stdout) return;
@@ -40952,6 +41293,30 @@ var DnsMonitor = class {
40952
41293
  record(q) {
40953
41294
  this.domainBuffer.push(q);
40954
41295
  this.observed++;
41296
+ this.checkFeeds(q);
41297
+ }
41298
+ /**
41299
+ * A lookup of a domain on the abuse.ch lists (`threat-feeds`). The client
41300
+ * goes in details, never `source_ip`: it is whoever asked, and on a public
41301
+ * resolver that is an outside user auto-defence must not ban. Only a lookup
41302
+ * from this box or a private-range client (a container) is about us.
41303
+ */
41304
+ checkFeeds(q) {
41305
+ const hit = matchDomain(q.domain);
41306
+ if (!hit) return;
41307
+ const now = Date.now();
41308
+ const key = `${hit.domain}|${q.source_ip ?? ""}`;
41309
+ if (now - (this.feedAlerts.get(key) ?? 0) < 36e5) return;
41310
+ this.feedAlerts.set(key, now);
41311
+ if (this.feedAlerts.size > 1e4) this.feedAlerts.clear();
41312
+ const local = !q.source_ip || isProtected(q.source_ip, DEFAULT_PROTECTED);
41313
+ const { malware, threat, feed } = hit.indicator;
41314
+ this.emitEvent(
41315
+ local ? "critical" : "low",
41316
+ `DNS lookup of known ${malware === "unknown" ? "malware" : malware} ${threat === "botnet_cc" ? "C2" : "host"} ${q.domain}${q.source_ip ? ` by ${q.source_ip}` : ""}`,
41317
+ void 0,
41318
+ { rule_id: "threat-feed-dns", domain: q.domain, listed: hit.domain, client_ip: q.source_ip, qtype: q.type, malware, threat, feed }
41319
+ );
40955
41320
  }
40956
41321
  emitEvent(severity, message, sourceIp, details) {
40957
41322
  const event = {
@@ -41085,15 +41450,15 @@ var ModuleHost = class {
41085
41450
  }
41086
41451
  }
41087
41452
  async discoverAndStartInstalled() {
41088
- if (!(0, import_node_fs28.existsSync)(PATHS.moduleDir)) return;
41453
+ if (!(0, import_node_fs29.existsSync)(PATHS.moduleDir)) return;
41089
41454
  const configs = loadModuleConfigs(PATHS.confD);
41090
- const entries = (0, import_node_fs28.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
41455
+ const entries = (0, import_node_fs29.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
41091
41456
  for (const entry of entries) {
41092
41457
  if (!entry.isDirectory()) continue;
41093
- const manifestPath = (0, import_node_path20.join)(PATHS.moduleDir, entry.name, "mod.toml");
41094
- if (!(0, import_node_fs28.existsSync)(manifestPath)) continue;
41458
+ const manifestPath = (0, import_node_path21.join)(PATHS.moduleDir, entry.name, "mod.toml");
41459
+ if (!(0, import_node_fs29.existsSync)(manifestPath)) continue;
41095
41460
  try {
41096
- const manifest = import_toml4.default.parse((0, import_node_fs28.readFileSync)(manifestPath, "utf-8"));
41461
+ const manifest = import_toml4.default.parse((0, import_node_fs29.readFileSync)(manifestPath, "utf-8"));
41097
41462
  const name = manifest.module?.name || entry.name;
41098
41463
  const defaults = manifest.module?.config?.defaults || {};
41099
41464
  const config = {
@@ -41107,7 +41472,7 @@ var ModuleHost = class {
41107
41472
  source: "installed",
41108
41473
  status: config.enabled === false ? "disabled" : "loaded",
41109
41474
  events: 0,
41110
- path: (0, import_node_path20.join)(PATHS.moduleDir, entry.name),
41475
+ path: (0, import_node_path21.join)(PATHS.moduleDir, entry.name),
41111
41476
  config
41112
41477
  };
41113
41478
  this.modules.set(name, hosted);
@@ -41122,7 +41487,7 @@ var ModuleHost = class {
41122
41487
  status: "error",
41123
41488
  events: 0,
41124
41489
  detail: `manifest load failed: ${String(err.message || err)}`,
41125
- path: (0, import_node_path20.join)(PATHS.moduleDir, entry.name)
41490
+ path: (0, import_node_path21.join)(PATHS.moduleDir, entry.name)
41126
41491
  });
41127
41492
  }
41128
41493
  }
@@ -41161,17 +41526,17 @@ var ModuleHost = class {
41161
41526
  }
41162
41527
  }
41163
41528
  installedEntrypoint(modulePath) {
41164
- const packageJson = (0, import_node_path20.join)(modulePath, "package.json");
41529
+ const packageJson = (0, import_node_path21.join)(modulePath, "package.json");
41165
41530
  const candidates = [];
41166
- if ((0, import_node_fs28.existsSync)(packageJson)) {
41531
+ if ((0, import_node_fs29.existsSync)(packageJson)) {
41167
41532
  try {
41168
- const pkg = JSON.parse((0, import_node_fs28.readFileSync)(packageJson, "utf-8"));
41169
- if (pkg.main) candidates.push((0, import_node_path20.join)(modulePath, pkg.main));
41533
+ const pkg = JSON.parse((0, import_node_fs29.readFileSync)(packageJson, "utf-8"));
41534
+ if (pkg.main) candidates.push((0, import_node_path21.join)(modulePath, pkg.main));
41170
41535
  } catch {
41171
41536
  }
41172
41537
  }
41173
- candidates.push((0, import_node_path20.join)(modulePath, "dist", "index.js"), (0, import_node_path20.join)(modulePath, "index.js"));
41174
- return candidates.find((candidate) => (0, import_node_fs28.existsSync)(candidate)) || null;
41538
+ candidates.push((0, import_node_path21.join)(modulePath, "dist", "index.js"), (0, import_node_path21.join)(modulePath, "index.js"));
41539
+ return candidates.find((candidate) => (0, import_node_fs29.existsSync)(candidate)) || null;
41175
41540
  }
41176
41541
  isThreatCrushModule(value) {
41177
41542
  return Boolean(
@@ -41580,7 +41945,7 @@ init_cli_config();
41580
41945
 
41581
41946
  // src/core/cloud-events.ts
41582
41947
  var import_node_crypto6 = require("crypto");
41583
- var import_node_net4 = require("net");
41948
+ var import_node_net6 = require("net");
41584
41949
  init_cli_config();
41585
41950
  function currentLink() {
41586
41951
  if (!hasSession()) return null;
@@ -41638,7 +42003,7 @@ function detectionEvent(serverId, event) {
41638
42003
  title: title.slice(0, MAX_TITLE_CHARS) || event.module,
41639
42004
  rule_id: str2(rule_id) ?? event.module,
41640
42005
  description: str2(description),
41641
- source_ip: event.source_ip && (0, import_node_net4.isIP)(event.source_ip) ? event.source_ip : void 0,
42006
+ source_ip: event.source_ip && (0, import_node_net6.isIP)(event.source_ip) ? event.source_ip : void 0,
41642
42007
  username: str2(username) ?? str2(user),
41643
42008
  raw_metadata: trimMetadata({ module: event.module, category: event.category, ...rest }),
41644
42009
  detected_at: event.timestamp.toISOString()
@@ -41674,21 +42039,22 @@ function findingEvents(serverId, results, observedAt = /* @__PURE__ */ new Date(
41674
42039
  severity: r.severity,
41675
42040
  title: r.title.slice(0, MAX_TITLE_CHARS),
41676
42041
  recommendation: r.recommendation,
41677
- observed_at: observedAt.toISOString()
42042
+ observed_at: observedAt.toISOString(),
42043
+ ...r.details ? { details: trimMetadata(r.details) } : {}
41678
42044
  }));
41679
42045
  }
41680
42046
 
41681
42047
  // src/daemon/workers/cloud-spool.ts
41682
- var import_node_fs29 = require("fs");
42048
+ var import_node_fs30 = require("fs");
41683
42049
  var import_promises = require("fs/promises");
41684
- var import_node_path21 = require("path");
42050
+ var import_node_path22 = require("path");
41685
42051
  var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
41686
42052
  var CloudSpool = class {
41687
42053
  constructor(path, limits = DEFAULT_SPOOL_LIMITS) {
41688
42054
  this.path = path;
41689
42055
  this.limits = limits;
41690
42056
  try {
41691
- (0, import_node_fs29.mkdirSync)((0, import_node_path21.dirname)(path), { recursive: true });
42057
+ (0, import_node_fs30.mkdirSync)((0, import_node_path22.dirname)(path), { recursive: true });
41692
42058
  } catch {
41693
42059
  }
41694
42060
  this.load();
@@ -41757,7 +42123,7 @@ var CloudSpool = class {
41757
42123
  load() {
41758
42124
  let raw;
41759
42125
  try {
41760
- raw = (0, import_node_fs29.readFileSync)(this.path, "utf-8");
42126
+ raw = (0, import_node_fs30.readFileSync)(this.path, "utf-8");
41761
42127
  } catch {
41762
42128
  return;
41763
42129
  }
@@ -41995,144 +42361,15 @@ var CloudSync = class {
41995
42361
  };
41996
42362
 
41997
42363
  // src/daemon/workers/remediation-consumer.ts
41998
- var import_node_net7 = require("net");
42364
+ var import_node_net8 = require("net");
41999
42365
  init_cli_config();
42000
42366
 
42001
- // src/daemon/firewall/protected.ts
42002
- var import_node_child_process8 = require("child_process");
42003
- var import_node_net5 = require("net");
42004
- var DEFAULT_PROTECTED = [
42005
- "127.0.0.0/8",
42006
- "::1/128",
42007
- "10.0.0.0/8",
42008
- "172.16.0.0/12",
42009
- "192.168.0.0/16",
42010
- "169.254.0.0/16",
42011
- "fc00::/7",
42012
- "fe80::/10"
42013
- ];
42014
- function ipToBytes(ip) {
42015
- const version = (0, import_node_net5.isIP)(ip);
42016
- if (version === 4) return v4ToBytes(ip);
42017
- if (version === 6) return v6ToBytes(ip);
42018
- return null;
42019
- }
42020
- function v4ToBytes(ip) {
42021
- const parts = ip.split(".");
42022
- if (parts.length !== 4) return null;
42023
- const bytes = new Uint8Array(4);
42024
- for (let i = 0; i < 4; i++) {
42025
- const n = Number(parts[i]);
42026
- if (!Number.isInteger(n) || n < 0 || n > 255) return null;
42027
- bytes[i] = n;
42028
- }
42029
- return bytes;
42030
- }
42031
- function v6ToBytes(ip) {
42032
- const bare = ip.split("%")[0];
42033
- const [headText, tailText] = bare.split("::", 2);
42034
- const head = headText ? headText.split(":") : [];
42035
- const tail = tailText !== void 0 ? tailText ? tailText.split(":") : [] : null;
42036
- const groups = [];
42037
- const pushGroup = (group) => {
42038
- if (group.includes(".")) {
42039
- const v4 = v4ToBytes(group);
42040
- if (!v4) return false;
42041
- groups.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
42042
- return true;
42043
- }
42044
- if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return false;
42045
- groups.push(parseInt(group, 16));
42046
- return true;
42047
- };
42048
- for (const group of head) if (!pushGroup(group)) return null;
42049
- const headCount = groups.length;
42050
- if (tail === null) {
42051
- if (headCount !== 8) return null;
42052
- } else {
42053
- const tailGroups = [];
42054
- const saved = groups.length;
42055
- for (const group of tail) if (!pushGroup(group)) return null;
42056
- tailGroups.push(...groups.splice(saved));
42057
- const zeros = 8 - headCount - tailGroups.length;
42058
- if (zeros < 0) return null;
42059
- for (let i = 0; i < zeros; i++) groups.push(0);
42060
- groups.push(...tailGroups);
42061
- }
42062
- if (groups.length !== 8) return null;
42063
- const bytes = new Uint8Array(16);
42064
- for (let i = 0; i < 8; i++) {
42065
- bytes[i * 2] = groups[i] >> 8 & 255;
42066
- bytes[i * 2 + 1] = groups[i] & 255;
42067
- }
42068
- return bytes;
42069
- }
42070
- function ipMatches(ip, entry) {
42071
- const [network, prefixText] = entry.trim().split("/");
42072
- const target = ipToBytes(ip);
42073
- const base = ipToBytes(network);
42074
- if (!target || !base || target.length !== base.length) return false;
42075
- const bits2 = prefixText === void 0 ? base.length * 8 : Number(prefixText);
42076
- if (!Number.isInteger(bits2) || bits2 < 0 || bits2 > base.length * 8) return false;
42077
- const wholeBytes = Math.floor(bits2 / 8);
42078
- for (let i = 0; i < wholeBytes; i++) {
42079
- if (target[i] !== base[i]) return false;
42080
- }
42081
- const remainder = bits2 % 8;
42082
- if (remainder === 0) return true;
42083
- const mask = 255 << 8 - remainder & 255;
42084
- return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
42085
- }
42086
- function isProtected(ip, list) {
42087
- return list.some((entry) => ipMatches(ip, entry));
42088
- }
42089
- function currentSshClient(env2 = process.env) {
42090
- const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
42091
- if (!source) return null;
42092
- const ip = source.trim().split(/\s+/)[0];
42093
- return ip && (0, import_node_net5.isIP)(ip) ? ip : null;
42094
- }
42095
- function establishedSshPeers() {
42096
- const peers = /* @__PURE__ */ new Set();
42097
- try {
42098
- const out = (0, import_node_child_process8.execFileSync)("ss", ["-tnpH"], {
42099
- encoding: "utf-8",
42100
- stdio: ["ignore", "pipe", "ignore"],
42101
- timeout: 3e3
42102
- });
42103
- for (const line2 of out.split("\n")) {
42104
- if (!/users:\(\("sshd/.test(line2)) continue;
42105
- const parts = line2.trim().split(/\s+/);
42106
- const peer = parts[4];
42107
- if (!peer) continue;
42108
- const ip = peer.slice(0, peer.lastIndexOf(":")).replace(/^\[|\]$/g, "");
42109
- if (ip && (0, import_node_net5.isIP)(ip)) peers.add(ip);
42110
- }
42111
- } catch {
42112
- }
42113
- return [...peers];
42114
- }
42115
- function defaultGateways() {
42116
- const found = /* @__PURE__ */ new Set();
42117
- for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
42118
- try {
42119
- const out = (0, import_node_child_process8.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
42120
- for (const line2 of out.split("\n")) {
42121
- const match = line2.match(/\bvia\s+(\S+)/);
42122
- if (match && (0, import_node_net5.isIP)(match[1])) found.add(match[1]);
42123
- }
42124
- } catch {
42125
- }
42126
- }
42127
- return [...found];
42128
- }
42129
-
42130
42367
  // src/daemon/workers/allowlist-sync.ts
42131
- var import_node_net6 = require("net");
42368
+ var import_node_net7 = require("net");
42132
42369
  init_cli_config();
42133
42370
  function isAddressOrCidr(value) {
42134
42371
  const [network, prefix, extra] = value.split("/");
42135
- const family = (0, import_node_net6.isIP)(network);
42372
+ const family = (0, import_node_net7.isIP)(network);
42136
42373
  if (family === 0 || extra !== void 0) return false;
42137
42374
  if (prefix === void 0) return true;
42138
42375
  if (!/^\d{1,3}$/.test(prefix)) return false;
@@ -42281,7 +42518,7 @@ var RemediationConsumer = class {
42281
42518
  try {
42282
42519
  switch (action.action_type) {
42283
42520
  case "block": {
42284
- if ((0, import_node_net7.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
42521
+ if ((0, import_node_net8.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
42285
42522
  let ttlSeconds = this.manager.status().max_ban_seconds;
42286
42523
  if (action.expires_at) {
42287
42524
  const until = Date.parse(action.expires_at);
@@ -42300,7 +42537,7 @@ var RemediationConsumer = class {
42300
42537
  return { status: "executed", dry_run: result.entry?.dry_run === true, executed_at };
42301
42538
  }
42302
42539
  case "unblock": {
42303
- if ((0, import_node_net7.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
42540
+ if ((0, import_node_net8.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
42304
42541
  const wasBanned = this.manager.getBlocklist().some((b) => b.ip === target);
42305
42542
  const result = await this.manager.unban(target, {
42306
42543
  forget: true,
@@ -42345,8 +42582,8 @@ var RemediationConsumer = class {
42345
42582
 
42346
42583
  // src/daemon/workers/auto-update.ts
42347
42584
  var import_node_child_process9 = require("child_process");
42348
- var import_node_fs30 = require("fs");
42349
- var import_node_path22 = require("path");
42585
+ var import_node_fs31 = require("fs");
42586
+ var import_node_path23 = require("path");
42350
42587
  init_backoff();
42351
42588
  var PKG_NAME = "@profullstack/threatcrush";
42352
42589
  var REGISTRY = `https://registry.npmjs.org/${PKG_NAME}`;
@@ -42354,12 +42591,12 @@ var DEFAULT_INTERVAL_MS = 6 * 36e5;
42354
42591
  var DEFAULT_MIN_AGE_MS = 2 * 36e5;
42355
42592
  var RETRY_AFTER_MS = 24 * 36e5;
42356
42593
  function isNewer(a, b) {
42357
- const parse2 = (v) => {
42594
+ const parse3 = (v) => {
42358
42595
  const [core, pre] = v.replace(/^v/, "").split("-", 2);
42359
42596
  return { nums: core.split(".").map((n) => Number.parseInt(n, 10) || 0), pre: pre ?? null };
42360
42597
  };
42361
- const x = parse2(a);
42362
- const y = parse2(b);
42598
+ const x = parse3(a);
42599
+ const y = parse3(b);
42363
42600
  for (let i = 0; i < 3; i++) {
42364
42601
  if ((x.nums[i] ?? 0) !== (y.nums[i] ?? 0)) return (x.nums[i] ?? 0) > (y.nums[i] ?? 0);
42365
42602
  }
@@ -42384,12 +42621,12 @@ function pickUpdate(doc, current, opts) {
42384
42621
  return { version: latest };
42385
42622
  }
42386
42623
  function installPlan(opts) {
42387
- const expected = `${import_node_path22.sep}lib${import_node_path22.sep}node_modules${import_node_path22.sep}@profullstack${import_node_path22.sep}threatcrush`;
42624
+ const expected = `${import_node_path23.sep}lib${import_node_path23.sep}node_modules${import_node_path23.sep}@profullstack${import_node_path23.sep}threatcrush`;
42388
42625
  if (!opts.pkgRoot.endsWith(expected)) {
42389
42626
  return { kind: "unsupported", reason: `not an npm global install (${opts.pkgRoot}); run \`threatcrush update\`` };
42390
42627
  }
42391
- const nodeBin = (0, import_node_path22.dirname)(opts.execPath);
42392
- const npm = (0, import_node_path22.join)(nodeBin, "npm");
42628
+ const nodeBin = (0, import_node_path23.dirname)(opts.execPath);
42629
+ const npm = (0, import_node_path23.join)(nodeBin, "npm");
42393
42630
  if (!opts.npmExists(npm)) return { kind: "unsupported", reason: `no npm beside ${opts.execPath}` };
42394
42631
  if (!opts.owner) return { kind: "unsupported", reason: `cannot tell who owns ${opts.pkgRoot}` };
42395
42632
  const npmArgs = [npm, "i", "-g", `${PKG_NAME}@${opts.version}`, "--no-fund", "--no-audit"];
@@ -42421,10 +42658,10 @@ function installPlan(opts) {
42421
42658
  }
42422
42659
  function ownerOf(path, passwd = "/etc/passwd") {
42423
42660
  try {
42424
- const st = (0, import_node_fs30.statSync)(path);
42661
+ const st = (0, import_node_fs31.statSync)(path);
42425
42662
  let home = st.uid === 0 ? "/root" : "";
42426
42663
  try {
42427
- for (const line2 of (0, import_node_fs30.readFileSync)(passwd, "utf8").split("\n")) {
42664
+ for (const line2 of (0, import_node_fs31.readFileSync)(passwd, "utf8").split("\n")) {
42428
42665
  const f = line2.split(":");
42429
42666
  if (Number(f[2]) === st.uid && f[5]) home = f[5];
42430
42667
  }
@@ -42529,7 +42766,7 @@ var AutoUpdate = class {
42529
42766
  uid: process.getuid?.() ?? -1,
42530
42767
  owner: ownerOf(this.opts.pkgRoot),
42531
42768
  underSystemd: this.opts.underSystemd ?? Boolean(process.env.INVOCATION_ID),
42532
- npmExists: import_node_fs30.existsSync
42769
+ npmExists: import_node_fs31.existsSync
42533
42770
  });
42534
42771
  if (plan.kind === "unsupported") return this.note(`${target} is available but cannot self-install: ${plan.reason}`);
42535
42772
  this.recordAttempt(target);
@@ -42564,7 +42801,7 @@ var AutoUpdate = class {
42564
42801
  }
42565
42802
  lastAttempt() {
42566
42803
  try {
42567
- const v = JSON.parse((0, import_node_fs30.readFileSync)(this.opts.statePath, "utf8"));
42804
+ const v = JSON.parse((0, import_node_fs31.readFileSync)(this.opts.statePath, "utf8"));
42568
42805
  return v.version && typeof v.at === "number" ? { version: v.version, at: v.at } : null;
42569
42806
  } catch {
42570
42807
  return null;
@@ -42572,13 +42809,220 @@ var AutoUpdate = class {
42572
42809
  }
42573
42810
  recordAttempt(version) {
42574
42811
  try {
42575
- (0, import_node_fs30.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
42812
+ (0, import_node_fs31.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
42576
42813
  } catch (err) {
42577
42814
  this.opts.log(`[update] could not record attempt: ${err.message}`);
42578
42815
  }
42579
42816
  }
42580
42817
  };
42581
42818
 
42819
+ // src/daemon/workers/threat-feeds.ts
42820
+ var import_node_child_process10 = require("child_process");
42821
+ var import_node_net9 = require("net");
42822
+ init_backoff();
42823
+ var EGRESS_TABLE = "threatcrush_egress";
42824
+ var DEFAULT_REFRESH_MS = 36e5;
42825
+ var POLL_MS2 = 15e3;
42826
+ var REALERT_MS = 36e5;
42827
+ function threatFeedSettings(section) {
42828
+ const refresh = parseDuration(section?.refresh);
42829
+ return {
42830
+ enabled: section?.enabled !== false,
42831
+ block: section?.block === true,
42832
+ // abuse.ch asks for no more than one fetch per 5 minutes; hourly is plenty.
42833
+ refreshMs: refresh ? Math.max(900, refresh) * 1e3 : DEFAULT_REFRESH_MS,
42834
+ minConfidence: typeof section?.min_confidence === "number" ? section.min_confidence : 75,
42835
+ allow: Array.isArray(section?.allow) ? section.allow.map(String) : []
42836
+ };
42837
+ }
42838
+ function egressRuleset(ips) {
42839
+ const v4 = ips.filter((ip) => (0, import_node_net9.isIP)(ip) === 4);
42840
+ const v6 = ips.filter((ip) => (0, import_node_net9.isIP)(ip) === 6);
42841
+ const set = (name, type, items) => ` set ${name} { type ${type};${items.length ? ` elements = { ${items.join(", ")} }` : ""} }`;
42842
+ const chain = (name, hook) => [
42843
+ ` chain ${name} {`,
42844
+ ` type filter hook ${hook} priority -1; policy accept;`,
42845
+ ` ip daddr @c2_v4 counter drop`,
42846
+ ` ip6 daddr @c2_v6 counter drop`,
42847
+ ` }`
42848
+ ].join("\n");
42849
+ return [
42850
+ `table inet ${EGRESS_TABLE}`,
42851
+ `delete table inet ${EGRESS_TABLE}`,
42852
+ `table inet ${EGRESS_TABLE} {`,
42853
+ set("c2_v4", "ipv4_addr", v4),
42854
+ set("c2_v6", "ipv6_addr", v6),
42855
+ chain("output", "output"),
42856
+ chain("forward", "forward"),
42857
+ `}`,
42858
+ ""
42859
+ ].join("\n");
42860
+ }
42861
+ function splitAddr(addr) {
42862
+ const m = /^\[?(.+?)\]?:(\d+|\*)$/.exec(addr);
42863
+ if (!m) return null;
42864
+ const ip = m[1].replace(/%.*$/, "").replace(/^::ffff:/i, "");
42865
+ return (0, import_node_net9.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
42866
+ }
42867
+ function parseSs(text) {
42868
+ const out = [];
42869
+ for (const line2 of text.split("\n")) {
42870
+ const cols = line2.trim().split(/\s+/);
42871
+ if (cols.length < 5) continue;
42872
+ const local = splitAddr(cols[3]);
42873
+ const peer = splitAddr(cols[4]);
42874
+ if (!local || !peer) continue;
42875
+ const proc = /users:\(\("([^"]+)",pid=(\d+)/.exec(line2);
42876
+ out.push({
42877
+ state: cols[0],
42878
+ localPort: local.port,
42879
+ peerIp: peer.ip,
42880
+ peerPort: peer.port,
42881
+ process: proc?.[1] ?? null,
42882
+ pid: proc ? Number(proc[2]) : null
42883
+ });
42884
+ }
42885
+ return out;
42886
+ }
42887
+ function parseListeningPorts(text) {
42888
+ const ports = /* @__PURE__ */ new Set();
42889
+ for (const line2 of text.split("\n")) {
42890
+ const cols = line2.trim().split(/\s+/);
42891
+ const local = cols.length >= 4 ? splitAddr(cols[3]) : null;
42892
+ if (local) ports.add(local.port);
42893
+ }
42894
+ return ports;
42895
+ }
42896
+ function defaultRun2(cmd, args, input) {
42897
+ const res = (0, import_node_child_process10.spawnSync)(cmd, args, { encoding: "utf-8", input, timeout: 15e3, stdio: ["pipe", "pipe", "pipe"] });
42898
+ return res.status === 0 ? res.stdout : null;
42899
+ }
42900
+ var ThreatFeeds = class {
42901
+ constructor(opts) {
42902
+ this.opts = opts;
42903
+ this.run = opts.run ?? defaultRun2;
42904
+ this.now = opts.now ?? Date.now;
42905
+ }
42906
+ opts;
42907
+ timers = [];
42908
+ set = null;
42909
+ alerted = /* @__PURE__ */ new Map();
42910
+ blocking = false;
42911
+ run;
42912
+ now;
42913
+ get wantsBlock() {
42914
+ return this.opts.settings.block && this.opts.enforcing;
42915
+ }
42916
+ start() {
42917
+ const { settings } = this.opts;
42918
+ if (!settings.enabled) {
42919
+ this.opts.log("[threat-feeds] disabled by [threat_feeds] enabled = false");
42920
+ this.removeBlocking();
42921
+ return;
42922
+ }
42923
+ if (settings.block && !this.opts.enforcing) {
42924
+ this.opts.log("[threat-feeds] block = true but remediation is in dry_run (or has no firewall): detecting only");
42925
+ }
42926
+ const cached = readFeedCache(this.opts.cachePath);
42927
+ if (cached) this.apply(cached, "cache");
42928
+ if (!this.wantsBlock) this.removeBlocking();
42929
+ const stale = !cached || this.now() - Date.parse(cached.fetched_at) > settings.refreshMs;
42930
+ const first = setTimeout(() => void this.refresh(), stale ? 1e4 : settings.refreshMs);
42931
+ first.unref?.();
42932
+ const every = setInterval(() => void this.refresh(), settings.refreshMs);
42933
+ every.unref?.();
42934
+ const poll = setInterval(() => this.pollConnections(), POLL_MS2);
42935
+ poll.unref?.();
42936
+ this.timers.push(first, every, poll);
42937
+ }
42938
+ stop() {
42939
+ for (const t of this.timers) clearInterval(t);
42940
+ this.timers = [];
42941
+ }
42942
+ async refresh() {
42943
+ try {
42944
+ const set = await fetchFeeds(this.opts.settings, this.opts.fetchImpl);
42945
+ const failed = set.sources.filter((s) => !s.ok);
42946
+ if (failed.length === set.sources.length) {
42947
+ this.opts.log(`[threat-feeds] refresh failed, keeping previous list: ${failed.map((s) => `${s.feed}: ${s.error}`).join("; ")}`);
42948
+ return;
42949
+ }
42950
+ for (const f of failed) this.opts.log(`[threat-feeds] ${f.feed} unavailable: ${f.error}`);
42951
+ try {
42952
+ writeFeedCache(this.opts.cachePath, set);
42953
+ } catch (err) {
42954
+ this.opts.log(`[threat-feeds] could not write cache: ${err.message}`);
42955
+ }
42956
+ this.apply(set, "refresh");
42957
+ } catch (err) {
42958
+ this.opts.log(`[threat-feeds] refresh failed: ${err.message}`);
42959
+ }
42960
+ }
42961
+ apply(set, from) {
42962
+ this.set = set;
42963
+ setActiveFeeds(set);
42964
+ const ips = Object.keys(set.ips);
42965
+ const domains = Object.keys(set.domains).length;
42966
+ let mode = "detecting";
42967
+ if (this.wantsBlock) {
42968
+ const ok = this.run("nft", ["-f", "-"], egressRuleset(ips)) !== null;
42969
+ this.blocking = ok;
42970
+ mode = ok ? "blocking egress" : "detecting (nft load failed)";
42971
+ }
42972
+ const detail = `${ips.length} IPs, ${domains} domains, ${mode}`;
42973
+ this.opts.log(`[threat-feeds] ${from === "cache" ? "loaded cached" : "refreshed"} list: ${detail} (${set.skipped_shared} shared/protected entries skipped)`);
42974
+ this.opts.bus.announceModule("threat-feeds", "running", detail);
42975
+ }
42976
+ removeBlocking() {
42977
+ if (this.run("nft", ["list", "table", "inet", EGRESS_TABLE]) !== null) {
42978
+ this.run("nft", ["delete", "table", "inet", EGRESS_TABLE]);
42979
+ this.opts.log(`[threat-feeds] removed egress table ${EGRESS_TABLE} (blocking is off)`);
42980
+ }
42981
+ this.blocking = false;
42982
+ }
42983
+ /** Outbound connections to listed IPs, one alert per IP and process per hour. */
42984
+ pollConnections() {
42985
+ if (!this.set || Object.keys(this.set.ips).length === 0) return;
42986
+ const conns = this.run("ss", ["-tnpH"]);
42987
+ if (conns === null) return;
42988
+ const listening = parseListeningPorts(this.run("ss", ["-ltnH"]) ?? "");
42989
+ const now = this.now();
42990
+ for (const c of parseSs(conns)) {
42991
+ if (listening.has(c.localPort)) continue;
42992
+ const ind = matchIp(c.peerIp, this.set);
42993
+ if (!ind) continue;
42994
+ const key = `${c.peerIp}|${c.process ?? "?"}`;
42995
+ if (now - (this.alerted.get(key) ?? 0) < REALERT_MS) continue;
42996
+ this.alerted.set(key, now);
42997
+ const who = c.process ? `${c.process} (pid ${c.pid})` : "an unknown process";
42998
+ const blocked = this.blocking ? " \u2014 blocked" : "";
42999
+ this.opts.bus.publish({
43000
+ timestamp: new Date(now),
43001
+ module: "threat-feeds",
43002
+ category: "network",
43003
+ severity: "critical",
43004
+ message: `Outbound connection to known ${ind.malware} ${ind.threat === "botnet_cc" ? "C2" : "malware host"} ${c.peerIp}:${c.peerPort} by ${who}${blocked}`,
43005
+ // No source_ip on purpose: the remote end is not an attacker to ban
43006
+ // inbound, so remediation has nothing to act on and the egress table
43007
+ // stays the only enforcement.
43008
+ details: {
43009
+ rule_id: "threat-feed-outbound",
43010
+ destination_ip: c.peerIp,
43011
+ destination_port: c.peerPort,
43012
+ state: c.state,
43013
+ process: c.process,
43014
+ pid: c.pid,
43015
+ malware: ind.malware,
43016
+ threat: ind.threat,
43017
+ feed: ind.feed,
43018
+ blocked: this.blocking
43019
+ }
43020
+ });
43021
+ }
43022
+ for (const [key, at] of this.alerted) if (now - at > REALERT_MS) this.alerted.delete(key);
43023
+ }
43024
+ };
43025
+
42582
43026
  // src/daemon/rules/engine.ts
42583
43027
  var MAX_WINDOW_ENTRIES = 1e3;
42584
43028
  function live(window) {
@@ -42740,8 +43184,8 @@ var RuleEngine = class {
42740
43184
  };
42741
43185
 
42742
43186
  // src/daemon/rules/loader.ts
42743
- var import_node_fs31 = require("fs");
42744
- var import_node_path23 = require("path");
43187
+ var import_node_fs32 = require("fs");
43188
+ var import_node_path24 = require("path");
42745
43189
 
42746
43190
  // src/daemon/rules/default-rules.ts
42747
43191
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -43142,11 +43586,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
43142
43586
  function loadAllRules(customDir) {
43143
43587
  const rules = [...DEFAULT_RULES];
43144
43588
  const dir = customDir || RULES_DIR;
43145
- if ((0, import_node_fs31.existsSync)(dir)) {
43146
- const files = (0, import_node_fs31.readdirSync)(dir).filter((f) => f.endsWith(".json"));
43589
+ if ((0, import_node_fs32.existsSync)(dir)) {
43590
+ const files = (0, import_node_fs32.readdirSync)(dir).filter((f) => f.endsWith(".json"));
43147
43591
  for (const file of files) {
43148
43592
  try {
43149
- const raw = (0, import_node_fs31.readFileSync)((0, import_node_path23.join)(dir, file), "utf-8");
43593
+ const raw = (0, import_node_fs32.readFileSync)((0, import_node_path24.join)(dir, file), "utf-8");
43150
43594
  const parsed = JSON.parse(raw);
43151
43595
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
43152
43596
  for (const rule of customRules) {
@@ -43177,24 +43621,24 @@ function loadAllRules(customDir) {
43177
43621
  }
43178
43622
 
43179
43623
  // src/daemon/firewall/adapters.ts
43180
- var import_node_child_process10 = require("child_process");
43181
- var import_node_fs32 = require("fs");
43182
- var import_node_path24 = require("path");
43183
- var import_node_net8 = require("net");
43624
+ var import_node_child_process11 = require("child_process");
43625
+ var import_node_fs33 = require("fs");
43626
+ var import_node_path25 = require("path");
43627
+ var import_node_net10 = require("net");
43184
43628
  function assertValidFirewallIp(ip) {
43185
- if ((0, import_node_net8.isIP)(ip) !== 4) {
43629
+ if ((0, import_node_net10.isIP)(ip) !== 4) {
43186
43630
  throw new Error(`Invalid IPv4 address: ${ip}`);
43187
43631
  }
43188
43632
  }
43189
43633
  function assertBannableIp(ip) {
43190
- if ((0, import_node_net8.isIP)(ip) === 0) {
43634
+ if ((0, import_node_net10.isIP)(ip) === 0) {
43191
43635
  throw new Error(`Invalid IP address: ${ip}`);
43192
43636
  }
43193
43637
  }
43194
43638
  function writeIfAbsent(path, contents) {
43195
- (0, import_node_fs32.mkdirSync)((0, import_node_path24.dirname)(path), { recursive: true });
43639
+ (0, import_node_fs33.mkdirSync)((0, import_node_path25.dirname)(path), { recursive: true });
43196
43640
  try {
43197
- (0, import_node_fs32.writeFileSync)(path, contents, { flag: "wx" });
43641
+ (0, import_node_fs33.writeFileSync)(path, contents, { flag: "wx" });
43198
43642
  } catch (err) {
43199
43643
  if (err.code !== "EEXIST") throw err;
43200
43644
  }
@@ -43213,11 +43657,11 @@ var Fail2banAdapter = class {
43213
43657
  enforces = true;
43214
43658
  jailReady = false;
43215
43659
  isAvailable() {
43216
- const result = (0, import_node_child_process10.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
43660
+ const result = (0, import_node_child_process11.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
43217
43661
  return result.status === 0;
43218
43662
  }
43219
43663
  client(args) {
43220
- return (0, import_node_child_process10.execFileSync)("fail2ban-client", args, {
43664
+ return (0, import_node_child_process11.execFileSync)("fail2ban-client", args, {
43221
43665
  encoding: "utf-8",
43222
43666
  stdio: ["ignore", "pipe", "pipe"]
43223
43667
  });
@@ -43293,7 +43737,7 @@ var Fail2banAdapter = class {
43293
43737
  const status = this.client(["status", this.jail]);
43294
43738
  const line2 = status.split("\n").find((l) => /Banned IP list:/i.test(l));
43295
43739
  if (!line2) return [];
43296
- return line2.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net8.isIP)(s) !== 0);
43740
+ return line2.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net10.isIP)(s) !== 0);
43297
43741
  } catch {
43298
43742
  return [];
43299
43743
  }
@@ -43303,45 +43747,45 @@ var Fail2banAdapter = class {
43303
43747
  function parseBannedList(output) {
43304
43748
  const found = [];
43305
43749
  for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
43306
- if ((0, import_node_net8.isIP)(match[1]) !== 0) found.push(match[1]);
43750
+ if ((0, import_node_net10.isIP)(match[1]) !== 0) found.push(match[1]);
43307
43751
  }
43308
43752
  if (found.length > 0) return found;
43309
- return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net8.isIP)(s) !== 0);
43753
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net10.isIP)(s) !== 0);
43310
43754
  }
43311
43755
  var NftablesAdapter = class {
43312
43756
  name = "nftables";
43313
43757
  table = "threatcrush";
43314
43758
  set = "blocklist";
43315
43759
  isAvailable() {
43316
- const result = (0, import_node_child_process10.spawnSync)("nft", ["--version"], { stdio: "pipe" });
43760
+ const result = (0, import_node_child_process11.spawnSync)("nft", ["--version"], { stdio: "pipe" });
43317
43761
  return result.status === 0;
43318
43762
  }
43319
43763
  ensureSetup() {
43320
43764
  try {
43321
- (0, import_node_child_process10.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
43765
+ (0, import_node_child_process11.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
43322
43766
  } catch {
43323
- (0, import_node_child_process10.execSync)(`nft add table inet ${this.table}`);
43324
- (0, import_node_child_process10.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
43325
- (0, import_node_child_process10.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
43326
- (0, import_node_child_process10.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
43767
+ (0, import_node_child_process11.execSync)(`nft add table inet ${this.table}`);
43768
+ (0, import_node_child_process11.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
43769
+ (0, import_node_child_process11.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
43770
+ (0, import_node_child_process11.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
43327
43771
  }
43328
43772
  }
43329
43773
  async block(ip) {
43330
43774
  assertValidFirewallIp(ip);
43331
43775
  this.ensureSetup();
43332
- (0, import_node_child_process10.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
43776
+ (0, import_node_child_process11.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
43333
43777
  }
43334
43778
  async unblock(ip) {
43335
43779
  assertValidFirewallIp(ip);
43336
43780
  try {
43337
- (0, import_node_child_process10.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
43781
+ (0, import_node_child_process11.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
43338
43782
  } catch {
43339
43783
  }
43340
43784
  }
43341
43785
  async isBlocked(ip) {
43342
43786
  assertValidFirewallIp(ip);
43343
43787
  try {
43344
- const output = (0, import_node_child_process10.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
43788
+ const output = (0, import_node_child_process11.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
43345
43789
  return output.includes(ip);
43346
43790
  } catch {
43347
43791
  return false;
@@ -43349,7 +43793,7 @@ var NftablesAdapter = class {
43349
43793
  }
43350
43794
  async listBlocked() {
43351
43795
  try {
43352
- const output = (0, import_node_child_process10.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
43796
+ const output = (0, import_node_child_process11.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
43353
43797
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
43354
43798
  if (!match) return [];
43355
43799
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -43362,34 +43806,34 @@ var IptablesAdapter = class {
43362
43806
  name = "iptables";
43363
43807
  chain = "THREATCRUSH";
43364
43808
  isAvailable() {
43365
- const result = (0, import_node_child_process10.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
43809
+ const result = (0, import_node_child_process11.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
43366
43810
  return result.status === 0;
43367
43811
  }
43368
43812
  ensureChain() {
43369
43813
  try {
43370
- (0, import_node_child_process10.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
43814
+ (0, import_node_child_process11.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
43371
43815
  } catch {
43372
- (0, import_node_child_process10.execSync)(`iptables -N ${this.chain}`);
43373
- (0, import_node_child_process10.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
43816
+ (0, import_node_child_process11.execSync)(`iptables -N ${this.chain}`);
43817
+ (0, import_node_child_process11.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
43374
43818
  }
43375
43819
  }
43376
43820
  async block(ip) {
43377
43821
  assertValidFirewallIp(ip);
43378
43822
  this.ensureChain();
43379
43823
  if (await this.isBlocked(ip)) return;
43380
- (0, import_node_child_process10.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
43824
+ (0, import_node_child_process11.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
43381
43825
  }
43382
43826
  async unblock(ip) {
43383
43827
  assertValidFirewallIp(ip);
43384
43828
  try {
43385
- (0, import_node_child_process10.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
43829
+ (0, import_node_child_process11.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
43386
43830
  } catch {
43387
43831
  }
43388
43832
  }
43389
43833
  async isBlocked(ip) {
43390
43834
  assertValidFirewallIp(ip);
43391
43835
  try {
43392
- const output = (0, import_node_child_process10.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
43836
+ const output = (0, import_node_child_process11.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
43393
43837
  return output.includes(ip);
43394
43838
  } catch {
43395
43839
  return false;
@@ -43397,7 +43841,7 @@ var IptablesAdapter = class {
43397
43841
  }
43398
43842
  async listBlocked() {
43399
43843
  try {
43400
- const output = (0, import_node_child_process10.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
43844
+ const output = (0, import_node_child_process11.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
43401
43845
  const ips = [];
43402
43846
  for (const line2 of output.split("\n")) {
43403
43847
  const match = line2.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -43453,8 +43897,8 @@ function detectFirewallAdapter(backend = "auto") {
43453
43897
  }
43454
43898
 
43455
43899
  // src/daemon/firewall/remediation.ts
43456
- var import_node_fs33 = require("fs");
43457
- var import_node_net9 = require("net");
43900
+ var import_node_fs34 = require("fs");
43901
+ var import_node_net11 = require("net");
43458
43902
  init_paths();
43459
43903
  init_backoff();
43460
43904
 
@@ -43591,7 +44035,7 @@ var RemediationManager = class {
43591
44035
  if (remediation?.action !== "block") return;
43592
44036
  }
43593
44037
  const ip = event.source_ip;
43594
- if (!ip || (0, import_node_net9.isIP)(ip) === 0) return;
44038
+ if (!ip || (0, import_node_net11.isIP)(ip) === 0) return;
43595
44039
  if (this.isAllowlisted(ip)) return;
43596
44040
  if (this.blocklist.some((b) => b.ip === ip)) return;
43597
44041
  if (this.config.spare_verified_crawlers) {
@@ -43610,7 +44054,7 @@ var RemediationManager = class {
43610
44054
  * 4th offence and so on, clamped to `max_ban_seconds`.
43611
44055
  */
43612
44056
  async ban(ip, reason, opts = {}) {
43613
- if ((0, import_node_net9.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
44057
+ if ((0, import_node_net11.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
43614
44058
  if (this.isAllowlisted(ip)) {
43615
44059
  return { ok: false, error: `${ip} is protected and can never be blocked` };
43616
44060
  }
@@ -43867,7 +44311,7 @@ var RemediationManager = class {
43867
44311
  }
43868
44312
  logLine(line2) {
43869
44313
  try {
43870
- (0, import_node_fs33.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
44314
+ (0, import_node_fs34.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
43871
44315
  `);
43872
44316
  } catch {
43873
44317
  }
@@ -43905,19 +44349,19 @@ function remediationSettings(section) {
43905
44349
  init_backoff();
43906
44350
 
43907
44351
  // src/daemon/watchdog-service.ts
43908
- var import_node_fs34 = require("fs");
43909
- var import_node_path25 = require("path");
44352
+ var import_node_fs35 = require("fs");
44353
+ var import_node_path26 = require("path");
43910
44354
  function defaultShareGid() {
43911
44355
  const isRoot4 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
43912
44356
  if (!isRoot4) return void 0;
43913
44357
  try {
43914
- return (0, import_node_fs34.statSync)("/var/log/auth.log").gid;
44358
+ return (0, import_node_fs35.statSync)("/var/log/auth.log").gid;
43915
44359
  } catch {
43916
44360
  return void 0;
43917
44361
  }
43918
44362
  }
43919
44363
  function startWatchdog(opts) {
43920
- const dir = opts.config?.dir ?? (0, import_node_path25.join)(opts.stateDir, WATCHDOG_DIRNAME);
44364
+ const dir = opts.config?.dir ?? (0, import_node_path26.join)(opts.stateDir, WATCHDOG_DIRNAME);
43921
44365
  const base = { dir, logged: 0, answered: 0, errored: 0 };
43922
44366
  if (opts.config?.enabled === false) {
43923
44367
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -44011,7 +44455,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
44011
44455
  }
44012
44456
 
44013
44457
  // src/core/node-runtime.ts
44014
- var import_node_child_process11 = require("child_process");
44458
+ var import_node_child_process12 = require("child_process");
44015
44459
  var MIN_DAEMON_NODE_MAJOR = 22;
44016
44460
  function nodeMajor(version) {
44017
44461
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -44025,31 +44469,45 @@ function daemonNodeProblem(version) {
44025
44469
  }
44026
44470
  function versionOfNode(path) {
44027
44471
  if (path === process.execPath) return process.versions.node;
44028
- const res = (0, import_node_child_process11.spawnSync)(path, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
44472
+ const res = (0, import_node_child_process12.spawnSync)(path, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
44029
44473
  return res.status === 0 ? res.stdout.trim() : null;
44030
44474
  }
44031
44475
 
44032
44476
  // src/daemon/index.ts
44033
44477
  function readVersion2() {
44034
44478
  try {
44035
- const pkg = JSON.parse((0, import_node_fs35.readFileSync)((0, import_node_path26.join)(__dirname, "..", "package.json"), "utf-8"));
44479
+ const pkg = JSON.parse((0, import_node_fs36.readFileSync)((0, import_node_path27.join)(__dirname, "..", "package.json"), "utf-8"));
44036
44480
  return pkg.version || "0.0.0";
44037
44481
  } catch {
44038
44482
  return "0.0.0";
44039
44483
  }
44040
44484
  }
44041
44485
  async function runHardeningChecks() {
44042
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process12.execFile)(
44486
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process13.execFile)(
44043
44487
  process.execPath,
44044
- [(0, import_node_path26.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
44488
+ [(0, import_node_path27.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
44045
44489
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
44046
44490
  );
44047
44491
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
44048
- return Array.isArray(parsed.findings) ? parsed.findings : [];
44492
+ const findings = Array.isArray(parsed.findings) ? parsed.findings : [];
44493
+ const patches = await runPatchCheck().catch((err) => {
44494
+ logLine(`[cloud] patch check failed: ${err.message.split("\n")[0]}`);
44495
+ return null;
44496
+ });
44497
+ return patches ? [...findings, patches] : findings;
44498
+ }
44499
+ async function runPatchCheck() {
44500
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process13.execFile)(
44501
+ process.execPath,
44502
+ [(0, import_node_path27.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
44503
+ { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
44504
+ );
44505
+ const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
44506
+ return parsed.finding ?? null;
44049
44507
  }
44050
44508
  function logLine(line2) {
44051
44509
  try {
44052
- (0, import_node_fs35.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
44510
+ (0, import_node_fs36.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
44053
44511
  `);
44054
44512
  } catch {
44055
44513
  }
@@ -44074,9 +44532,9 @@ async function runDaemon() {
44074
44532
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
44075
44533
  const restartDaemon = () => {
44076
44534
  if (PATHS.mode === "system") {
44077
- (0, import_node_child_process12.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
44535
+ (0, import_node_child_process13.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
44078
44536
  } else {
44079
- (0, import_node_child_process12.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
44537
+ (0, import_node_child_process13.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
44080
44538
  setTimeout(() => process.exit(0), 500).unref();
44081
44539
  }
44082
44540
  };
@@ -44091,7 +44549,7 @@ async function runDaemon() {
44091
44549
  } catch (err) {
44092
44550
  logLine(`[daemon] state db unavailable: ${err.message}`);
44093
44551
  }
44094
- const config = loadConfig((0, import_node_fs35.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
44552
+ const config = loadConfig((0, import_node_fs36.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
44095
44553
  configureAttackDetection(config.detection);
44096
44554
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
44097
44555
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -44151,6 +44609,15 @@ async function runDaemon() {
44151
44609
  if (firewallAdapter.enforces === false) {
44152
44610
  logLine("[daemon] no manageable firewall found (need fail2ban, nftables or iptables) \u2014 bans are simulated");
44153
44611
  }
44612
+ const feedSettings = threatFeedSettings(config.threat_feeds);
44613
+ const threatFeeds = new ThreatFeeds({
44614
+ settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
44615
+ enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
44616
+ cachePath: (0, import_node_path27.join)(PATHS.stateDir, "threat-feeds.json"),
44617
+ bus,
44618
+ log: logLine
44619
+ });
44620
+ threatFeeds.start();
44154
44621
  new AlertDispatcher(bus, config);
44155
44622
  const runsWorker = new RunsWorker(bus);
44156
44623
  try {
@@ -44170,7 +44637,7 @@ async function runDaemon() {
44170
44637
  version,
44171
44638
  hostname: (0, import_node_os11.hostname)(),
44172
44639
  minSeverity,
44173
- spoolPath: (0, import_node_path26.join)(PATHS.stateDir, "cloud-spool.jsonl"),
44640
+ spoolPath: (0, import_node_path27.join)(PATHS.stateDir, "cloud-spool.jsonl"),
44174
44641
  log: logLine,
44175
44642
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
44176
44643
  runHardening: runHardeningChecks
@@ -44187,8 +44654,8 @@ async function runDaemon() {
44187
44654
  const autoUpdate = new AutoUpdate({
44188
44655
  version,
44189
44656
  settings: updateSettings(config.update),
44190
- pkgRoot: (0, import_node_path26.join)(__dirname, ".."),
44191
- statePath: (0, import_node_path26.join)(PATHS.stateDir, "auto-update.json"),
44657
+ pkgRoot: (0, import_node_path27.join)(__dirname, ".."),
44658
+ statePath: (0, import_node_path27.join)(PATHS.stateDir, "auto-update.json"),
44192
44659
  bus,
44193
44660
  log: logLine,
44194
44661
  restartDaemon
@@ -44231,6 +44698,10 @@ async function runDaemon() {
44231
44698
  autoUpdate.stop();
44232
44699
  } catch {
44233
44700
  }
44701
+ try {
44702
+ threatFeeds.stop();
44703
+ } catch {
44704
+ }
44234
44705
  try {
44235
44706
  await ipc.stop();
44236
44707
  } catch {
@@ -44266,7 +44737,7 @@ var SYSTEM_SOCKET = "/var/run/threatcrush/threatcrushd.sock";
44266
44737
  function isRoot2() {
44267
44738
  return typeof process.getuid === "function" && process.getuid() === 0;
44268
44739
  }
44269
- var DAEMON_ENTRY = (0, import_node_path27.join)(__dirname, "daemon.js");
44740
+ var DAEMON_ENTRY = (0, import_node_path28.join)(__dirname, "daemon.js");
44270
44741
  async function daemonForeground() {
44271
44742
  await runDaemon();
44272
44743
  }
@@ -44287,7 +44758,7 @@ async function daemonStart() {
44287
44758
  return;
44288
44759
  }
44289
44760
  ensureRuntimeDirs();
44290
- if (!(0, import_node_fs36.existsSync)(DAEMON_ENTRY)) {
44761
+ if (!(0, import_node_fs37.existsSync)(DAEMON_ENTRY)) {
44291
44762
  console.log(source_default.red(` Daemon entry not found at ${DAEMON_ENTRY}.`));
44292
44763
  console.log(source_default.dim(" Reinstall with `threatcrush update` or `pnpm run build` in the cli package."));
44293
44764
  return;
@@ -44295,8 +44766,8 @@ async function daemonStart() {
44295
44766
  let out;
44296
44767
  let err;
44297
44768
  try {
44298
- out = (0, import_node_fs37.openSync)(PATHS.logFile, "a");
44299
- err = (0, import_node_fs37.openSync)(PATHS.logFile, "a");
44769
+ out = (0, import_node_fs38.openSync)(PATHS.logFile, "a");
44770
+ err = (0, import_node_fs38.openSync)(PATHS.logFile, "a");
44300
44771
  } catch (e) {
44301
44772
  const code = e.code;
44302
44773
  console.log(source_default.red(` \u2717 Cannot write daemon log at ${PATHS.logFile} (${code ?? "error"}).`));
@@ -44309,7 +44780,7 @@ async function daemonStart() {
44309
44780
  }
44310
44781
  return;
44311
44782
  }
44312
- const child = (0, import_node_child_process13.spawn)(process.execPath, [DAEMON_ENTRY], {
44783
+ const child = (0, import_node_child_process14.spawn)(process.execPath, [DAEMON_ENTRY], {
44313
44784
  detached: true,
44314
44785
  stdio: ["ignore", out, err],
44315
44786
  env: { ...process.env, THREATCRUSH_DAEMON: "1" }
@@ -44384,41 +44855,41 @@ async function waitForExit(pid, timeoutMs) {
44384
44855
  }
44385
44856
  async function releaseStaleSocket() {
44386
44857
  const deadline = Date.now() + 2e3;
44387
- while ((0, import_node_fs36.existsSync)(PATHS.socket) && Date.now() < deadline) {
44858
+ while ((0, import_node_fs37.existsSync)(PATHS.socket) && Date.now() < deadline) {
44388
44859
  await new Promise((r) => setTimeout(r, 50));
44389
44860
  }
44390
- if ((0, import_node_fs36.existsSync)(PATHS.socket)) {
44861
+ if ((0, import_node_fs37.existsSync)(PATHS.socket)) {
44391
44862
  try {
44392
- (0, import_node_fs36.unlinkSync)(PATHS.socket);
44863
+ (0, import_node_fs37.unlinkSync)(PATHS.socket);
44393
44864
  } catch {
44394
44865
  }
44395
44866
  }
44396
44867
  }
44397
44868
 
44398
44869
  // src/commands/service.ts
44399
- var import_node_child_process14 = require("child_process");
44400
- var import_node_fs38 = require("fs");
44401
- var import_node_path28 = require("path");
44870
+ var import_node_child_process15 = require("child_process");
44871
+ var import_node_fs39 = require("fs");
44872
+ var import_node_path29 = require("path");
44402
44873
  var import_node_os12 = require("os");
44403
44874
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
44404
44875
  var DAEMON_UNIT_NAME = "threatcrushd.service";
44405
44876
  function resolveTemplate() {
44406
- const templatePath = (0, import_node_path28.join)(__dirname, "systemd", "threatcrushd.service");
44407
- if (!(0, import_node_fs38.existsSync)(templatePath)) {
44877
+ const templatePath = (0, import_node_path29.join)(__dirname, "systemd", "threatcrushd.service");
44878
+ if (!(0, import_node_fs39.existsSync)(templatePath)) {
44408
44879
  throw new Error(`systemd unit template not found at ${templatePath}`);
44409
44880
  }
44410
- return (0, import_node_fs38.readFileSync)(templatePath, "utf-8");
44881
+ return (0, import_node_fs39.readFileSync)(templatePath, "utf-8");
44411
44882
  }
44412
44883
  function stableBinPath(binPath) {
44413
44884
  const stable = binPath.replace(/\/\.pnpm\/[^/]+\/node_modules\//, "/node_modules/");
44414
44885
  if (stable === binPath) return binPath;
44415
- return (0, import_node_fs38.existsSync)(stable) ? stable : binPath;
44886
+ return (0, import_node_fs39.existsSync)(stable) ? stable : binPath;
44416
44887
  }
44417
44888
  function resolveBinPath() {
44418
44889
  const arg = process.argv[1];
44419
- if (arg && (0, import_node_fs38.existsSync)(arg)) return stableBinPath(arg);
44890
+ if (arg && (0, import_node_fs39.existsSync)(arg)) return stableBinPath(arg);
44420
44891
  try {
44421
- return (0, import_node_child_process14.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
44892
+ return (0, import_node_child_process15.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
44422
44893
  } catch {
44423
44894
  return "threatcrush";
44424
44895
  }
@@ -44426,11 +44897,11 @@ function resolveBinPath() {
44426
44897
  function stableNodePath(execPath) {
44427
44898
  const stable = execPath.replace(/(\/installs\/node\/)[^/]+\//, "$1latest/");
44428
44899
  if (stable === execPath) return execPath;
44429
- return (0, import_node_fs38.existsSync)(stable) ? stable : execPath;
44900
+ return (0, import_node_fs39.existsSync)(stable) ? stable : execPath;
44430
44901
  }
44431
44902
  function looksLikeNodeScript(path) {
44432
44903
  try {
44433
- const head = (0, import_node_fs38.readFileSync)(path, "utf-8").slice(0, 120);
44904
+ const head = (0, import_node_fs39.readFileSync)(path, "utf-8").slice(0, 120);
44434
44905
  return /^#!.*\bnode\b/.test(head);
44435
44906
  } catch {
44436
44907
  return false;
@@ -44457,20 +44928,20 @@ function isRoot3() {
44457
44928
  return typeof process.getuid === "function" && process.getuid() === 0;
44458
44929
  }
44459
44930
  function reexecWithSudo(args) {
44460
- if ((0, import_node_child_process14.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
44931
+ if ((0, import_node_child_process15.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
44461
44932
  console.log(source_default.dim(" This needs root \u2014 sudo will ask for your password.\n"));
44462
44933
  const bin = resolveBinPath();
44463
44934
  const argv = looksLikeNodeScript(bin) ? [stableNodePath(process.execPath), bin, ...args] : [bin, ...args];
44464
- const result = (0, import_node_child_process14.spawnSync)("sudo", argv, { stdio: "inherit" });
44935
+ const result = (0, import_node_child_process15.spawnSync)("sudo", argv, { stdio: "inherit" });
44465
44936
  return result.status === 0;
44466
44937
  }
44467
44938
  function callerHome() {
44468
44939
  const user = process.env.SUDO_USER;
44469
44940
  if (!user) return null;
44470
44941
  try {
44471
- const line2 = (0, import_node_child_process14.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
44942
+ const line2 = (0, import_node_child_process15.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
44472
44943
  const home = line2.split(":")[5];
44473
- return home && (0, import_node_fs38.existsSync)(home) ? home : null;
44944
+ return home && (0, import_node_fs39.existsSync)(home) ? home : null;
44474
44945
  } catch {
44475
44946
  return null;
44476
44947
  }
@@ -44478,13 +44949,13 @@ function callerHome() {
44478
44949
  function stopUserModeDaemon() {
44479
44950
  const home = callerHome();
44480
44951
  if (!home) return;
44481
- const runDir = (0, import_node_path28.join)(home, ".threatcrush", "run");
44482
- const pidFile = (0, import_node_path28.join)(runDir, "threatcrushd.pid");
44483
- const socket = (0, import_node_path28.join)(runDir, "threatcrushd.sock");
44484
- if (!(0, import_node_fs38.existsSync)(pidFile) && !(0, import_node_fs38.existsSync)(socket)) return;
44952
+ const runDir = (0, import_node_path29.join)(home, ".threatcrush", "run");
44953
+ const pidFile = (0, import_node_path29.join)(runDir, "threatcrushd.pid");
44954
+ const socket = (0, import_node_path29.join)(runDir, "threatcrushd.sock");
44955
+ if (!(0, import_node_fs39.existsSync)(pidFile) && !(0, import_node_fs39.existsSync)(socket)) return;
44485
44956
  let pid = null;
44486
44957
  try {
44487
- pid = Number.parseInt((0, import_node_fs38.readFileSync)(pidFile, "utf-8").trim(), 10);
44958
+ pid = Number.parseInt((0, import_node_fs39.readFileSync)(pidFile, "utf-8").trim(), 10);
44488
44959
  } catch {
44489
44960
  pid = null;
44490
44961
  }
@@ -44497,13 +44968,13 @@ function stopUserModeDaemon() {
44497
44968
  }
44498
44969
  for (const path of [socket, pidFile]) {
44499
44970
  try {
44500
- if ((0, import_node_fs38.existsSync)(path)) (0, import_node_fs38.rmSync)(path);
44971
+ if ((0, import_node_fs39.existsSync)(path)) (0, import_node_fs39.rmSync)(path);
44501
44972
  } catch {
44502
44973
  }
44503
44974
  }
44504
44975
  }
44505
44976
  function unitIsActive() {
44506
- const result = (0, import_node_child_process14.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
44977
+ const result = (0, import_node_child_process15.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
44507
44978
  return result.status === 0;
44508
44979
  }
44509
44980
  async function installServiceCommand() {
@@ -44514,8 +44985,8 @@ async function installServiceCommand() {
44514
44985
  return;
44515
44986
  }
44516
44987
  const noSystemd = systemdUnavailableReason({
44517
- hasSystemctl: (0, import_node_child_process14.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
44518
- booted: (0, import_node_fs38.existsSync)("/run/systemd/system")
44988
+ hasSystemctl: (0, import_node_child_process15.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
44989
+ booted: (0, import_node_fs39.existsSync)("/run/systemd/system")
44519
44990
  });
44520
44991
  if (noSystemd) {
44521
44992
  console.log(source_default.red(` \u2717 systemd isn't available here: ${noSystemd}.`));
@@ -44537,7 +45008,7 @@ async function installServiceCommand() {
44537
45008
  const isNodeScript = looksLikeNodeScript(binPath);
44538
45009
  let nodePath = stableNodePath(process.execPath);
44539
45010
  if (isNodeScript && nodeVersionDir(binPath)) {
44540
- binPath = (0, import_node_fs38.realpathSync)(binPath);
45011
+ binPath = (0, import_node_fs39.realpathSync)(binPath);
44541
45012
  nodePath = process.execPath;
44542
45013
  }
44543
45014
  if (isNodeScript) {
@@ -44550,9 +45021,9 @@ async function installServiceCommand() {
44550
45021
  }
44551
45022
  }
44552
45023
  const exec = execStartCommand(binPath, nodePath, isNodeScript);
44553
- const configDir = (0, import_node_path28.join)((0, import_node_os12.homedir)(), ".threatcrush");
45024
+ const configDir = (0, import_node_path29.join)((0, import_node_os12.homedir)(), ".threatcrush");
44554
45025
  const unit = renderUnit(resolveTemplate(), { exec, binPath, configDir });
44555
- (0, import_node_fs38.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
45026
+ (0, import_node_fs39.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
44556
45027
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
44557
45028
  console.log(source_default.dim(` ExecStart=${exec}`));
44558
45029
  const nodeDir = nodeVersionDir(nodePath);
@@ -44567,8 +45038,8 @@ async function installServiceCommand() {
44567
45038
  installLogrotate();
44568
45039
  stopUserModeDaemon();
44569
45040
  try {
44570
- (0, import_node_child_process14.execSync)("systemctl daemon-reload", { stdio: "inherit" });
44571
- (0, import_node_child_process14.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
45041
+ (0, import_node_child_process15.execSync)("systemctl daemon-reload", { stdio: "inherit" });
45042
+ (0, import_node_child_process15.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
44572
45043
  } catch (err) {
44573
45044
  console.log(source_default.yellow(` ! systemctl error: ${err.message}`));
44574
45045
  console.log(source_default.dim(` Logs: journalctl -u ${DAEMON_UNIT_NAME} -n 50`));
@@ -44605,9 +45076,9 @@ function renderLogrotate(logDir = "/var/log/threatcrush") {
44605
45076
  ].join("\n");
44606
45077
  }
44607
45078
  function installLogrotate() {
44608
- if (!(0, import_node_fs38.existsSync)((0, import_node_path28.dirname)(LOGROTATE_PATH))) return;
45079
+ if (!(0, import_node_fs39.existsSync)((0, import_node_path29.dirname)(LOGROTATE_PATH))) return;
44609
45080
  try {
44610
- (0, import_node_fs38.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
45081
+ (0, import_node_fs39.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
44611
45082
  console.log(source_default.green(` \u2713 Log rotation: ${LOGROTATE_PATH} (daily or 200M, keeps 7)`));
44612
45083
  } catch (err) {
44613
45084
  console.log(source_default.yellow(` ! Could not install log rotation: ${err.message}`));
@@ -44629,20 +45100,20 @@ function ensureSystemDirs(configDir) {
44629
45100
  ];
44630
45101
  let admGid2 = null;
44631
45102
  try {
44632
- admGid2 = (0, import_node_fs38.statSync)("/var/log/auth.log").gid;
45103
+ admGid2 = (0, import_node_fs39.statSync)("/var/log/auth.log").gid;
44633
45104
  } catch {
44634
45105
  }
44635
45106
  for (const { path, groupWritable, sticky } of dirs) {
44636
45107
  try {
44637
- (0, import_node_fs38.mkdirSync)(path, { recursive: true });
45108
+ (0, import_node_fs39.mkdirSync)(path, { recursive: true });
44638
45109
  } catch {
44639
45110
  }
44640
45111
  try {
44641
45112
  if (groupWritable && admGid2 !== null) {
44642
- (0, import_node_fs38.chmodSync)(path, sticky ? 1533 : 509);
44643
- (0, import_node_child_process14.execSync)(`chgrp adm ${path}`, { stdio: "ignore" });
45113
+ (0, import_node_fs39.chmodSync)(path, sticky ? 1533 : 509);
45114
+ (0, import_node_child_process15.execSync)(`chgrp adm ${path}`, { stdio: "ignore" });
44644
45115
  } else {
44645
- (0, import_node_fs38.chmodSync)(path, 493);
45116
+ (0, import_node_fs39.chmodSync)(path, 493);
44646
45117
  }
44647
45118
  } catch {
44648
45119
  }
@@ -44662,29 +45133,29 @@ async function uninstallServiceCommand() {
44662
45133
  return;
44663
45134
  }
44664
45135
  try {
44665
- (0, import_node_child_process14.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
45136
+ (0, import_node_child_process15.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
44666
45137
  } catch {
44667
45138
  }
44668
45139
  try {
44669
- (0, import_node_child_process14.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
45140
+ (0, import_node_child_process15.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
44670
45141
  } catch {
44671
45142
  }
44672
45143
  try {
44673
- if ((0, import_node_fs38.existsSync)(UNIT_PATH)) {
44674
- (0, import_node_child_process14.execSync)(`rm -f ${UNIT_PATH}`);
45144
+ if ((0, import_node_fs39.existsSync)(UNIT_PATH)) {
45145
+ (0, import_node_child_process15.execSync)(`rm -f ${UNIT_PATH}`);
44675
45146
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
44676
45147
  }
44677
45148
  } catch {
44678
45149
  }
44679
45150
  try {
44680
- (0, import_node_child_process14.execSync)("systemctl daemon-reload", { stdio: "inherit" });
45151
+ (0, import_node_child_process15.execSync)("systemctl daemon-reload", { stdio: "inherit" });
44681
45152
  } catch {
44682
45153
  }
44683
45154
  console.log(source_default.green(" \u2713 threatcrushd service removed."));
44684
45155
  }
44685
45156
 
44686
45157
  // src/commands/save.ts
44687
- var import_node_fs39 = require("fs");
45158
+ var import_node_fs40 = require("fs");
44688
45159
  var import_toml5 = __toESM(require_toml());
44689
45160
  init_cli_config();
44690
45161
  init_paths();
@@ -44723,9 +45194,9 @@ async function saveCommand(opts = {}) {
44723
45194
  }
44724
45195
  const path = opts.config ?? PATHS.configFile;
44725
45196
  let config = {};
44726
- if ((0, import_node_fs39.existsSync)(path)) {
45197
+ if ((0, import_node_fs40.existsSync)(path)) {
44727
45198
  try {
44728
- config = import_toml5.default.parse((0, import_node_fs39.readFileSync)(path, "utf-8"));
45199
+ config = import_toml5.default.parse((0, import_node_fs40.readFileSync)(path, "utf-8"));
44729
45200
  } catch (err) {
44730
45201
  console.log(source_default.red(` \u2717 ${path} is not valid TOML: ${err.message}
44731
45202
  `));
@@ -44838,8 +45309,8 @@ function welcomeCommand() {
44838
45309
  }
44839
45310
 
44840
45311
  // src/commands/properties.ts
44841
- var import_node_fs40 = require("fs");
44842
- var import_node_path29 = require("path");
45312
+ var import_node_fs41 = require("fs");
45313
+ var import_node_path30 = require("path");
44843
45314
  var import_node_readline4 = __toESM(require("readline"));
44844
45315
  init_cli_config();
44845
45316
  var API_URL5 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
@@ -45169,8 +45640,8 @@ async function propertiesRunsCommand(opts) {
45169
45640
  }
45170
45641
  }
45171
45642
  function parseImportFile(path) {
45172
- const ext = (0, import_node_path29.extname)(path).toLowerCase();
45173
- const raw = (0, import_node_fs40.readFileSync)(path, "utf-8");
45643
+ const ext = (0, import_node_path30.extname)(path).toLowerCase();
45644
+ const raw = (0, import_node_fs41.readFileSync)(path, "utf-8");
45174
45645
  if (ext === ".json") {
45175
45646
  const parsed = JSON.parse(raw);
45176
45647
  if (!Array.isArray(parsed)) throw new Error("JSON must be an array of objects");
@@ -45365,19 +45836,19 @@ async function rulesCommand(opts) {
45365
45836
  }
45366
45837
 
45367
45838
  // src/commands/harden.ts
45368
- var import_node_fs41 = require("fs");
45369
- var import_node_child_process15 = require("child_process");
45839
+ var import_node_fs42 = require("fs");
45840
+ var import_node_child_process16 = require("child_process");
45370
45841
  init_cli_config();
45371
45842
  function tryExec(cmd) {
45372
45843
  try {
45373
- return (0, import_node_child_process15.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
45844
+ return (0, import_node_child_process16.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
45374
45845
  } catch {
45375
45846
  return null;
45376
45847
  }
45377
45848
  }
45378
45849
  function tryRead(path) {
45379
45850
  try {
45380
- return (0, import_node_fs41.readFileSync)(path, "utf-8");
45851
+ return (0, import_node_fs42.readFileSync)(path, "utf-8");
45381
45852
  } catch {
45382
45853
  return null;
45383
45854
  }
@@ -45481,8 +45952,8 @@ function checkSshWeakConfig() {
45481
45952
  };
45482
45953
  }
45483
45954
  function checkAutoUpdates() {
45484
- const unattended = (0, import_node_fs41.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs41.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
45485
- const dnfAuto = (0, import_node_fs41.existsSync)("/etc/dnf/automatic.conf");
45955
+ const unattended = (0, import_node_fs42.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs42.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
45956
+ const dnfAuto = (0, import_node_fs42.existsSync)("/etc/dnf/automatic.conf");
45486
45957
  if (unattended || dnfAuto) {
45487
45958
  return {
45488
45959
  key: "auto-updates",
@@ -45608,7 +46079,7 @@ function checkFail2ban() {
45608
46079
  explanation: "fail2ban is installed and running."
45609
46080
  };
45610
46081
  }
45611
- if ((0, import_node_fs41.existsSync)("/etc/fail2ban/fail2ban.conf")) {
46082
+ if ((0, import_node_fs42.existsSync)("/etc/fail2ban/fail2ban.conf")) {
45612
46083
  return {
45613
46084
  key: checkKey,
45614
46085
  status: "warn",
@@ -45793,6 +46264,461 @@ async function hardenCommand(opts) {
45793
46264
  if (opts.upload !== false) await uploadFindings(results, false);
45794
46265
  }
45795
46266
 
46267
+ // src/core/patches/index.ts
46268
+ var import_node_fs43 = require("fs");
46269
+ var import_node_path31 = require("path");
46270
+ var import_node_child_process17 = require("child_process");
46271
+ var import_node_util2 = require("util");
46272
+
46273
+ // src/core/patches/dpkg-version.ts
46274
+ function parse2(version) {
46275
+ let rest = version.trim();
46276
+ let epoch = 0;
46277
+ const colon = rest.indexOf(":");
46278
+ if (colon > 0 && /^\d+$/.test(rest.slice(0, colon))) {
46279
+ epoch = Number(rest.slice(0, colon));
46280
+ rest = rest.slice(colon + 1);
46281
+ }
46282
+ const dash = rest.lastIndexOf("-");
46283
+ return dash >= 0 ? { epoch, upstream: rest.slice(0, dash), revision: rest.slice(dash + 1) } : { epoch, upstream: rest, revision: "" };
46284
+ }
46285
+ function order(ch) {
46286
+ if (ch === void 0) return 0;
46287
+ if (ch === "~") return -1;
46288
+ if (/[A-Za-z]/.test(ch)) return ch.charCodeAt(0);
46289
+ return ch.charCodeAt(0) + 256;
46290
+ }
46291
+ function compareFragment(a, b) {
46292
+ let i = 0;
46293
+ let j = 0;
46294
+ while (i < a.length || j < b.length) {
46295
+ let firstDiff = 0;
46296
+ while (i < a.length && !/\d/.test(a[i]) || j < b.length && !/\d/.test(b[j])) {
46297
+ const ac = i < a.length && !/\d/.test(a[i]) ? a[i] : void 0;
46298
+ const bc = j < b.length && !/\d/.test(b[j]) ? b[j] : void 0;
46299
+ const diff = order(ac) - order(bc);
46300
+ if (diff !== 0) return diff;
46301
+ i++;
46302
+ j++;
46303
+ }
46304
+ while (a[i] === "0") i++;
46305
+ while (b[j] === "0") j++;
46306
+ while (i < a.length && /\d/.test(a[i]) && j < b.length && /\d/.test(b[j])) {
46307
+ if (!firstDiff) firstDiff = a.charCodeAt(i) - b.charCodeAt(j);
46308
+ i++;
46309
+ j++;
46310
+ }
46311
+ if (i < a.length && /\d/.test(a[i])) return 1;
46312
+ if (j < b.length && /\d/.test(b[j])) return -1;
46313
+ if (firstDiff) return firstDiff;
46314
+ }
46315
+ return 0;
46316
+ }
46317
+ function compareDebianVersions(a, b) {
46318
+ const x = parse2(a);
46319
+ const y = parse2(b);
46320
+ if (x.epoch !== y.epoch) return x.epoch - y.epoch;
46321
+ return compareFragment(x.upstream, y.upstream) || compareFragment(x.revision, y.revision);
46322
+ }
46323
+
46324
+ // src/core/patches/index.ts
46325
+ var OSV_QUERY = "https://api.osv.dev/v1/query";
46326
+ var STALE_AFTER_MS = 2 * 864e5;
46327
+ var SEVERITIES2 = ["info", "low", "medium", "high", "critical"];
46328
+ var RANK = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
46329
+ var defaultExec = async (file, args) => {
46330
+ const { stdout } = await (0, import_node_util2.promisify)(import_node_child_process17.execFile)(file, args, {
46331
+ timeout: 12e4,
46332
+ maxBuffer: 32 * 1024 * 1024,
46333
+ env: { ...process.env, LC_ALL: "C" }
46334
+ });
46335
+ return stdout;
46336
+ };
46337
+ function parseOsRelease(text) {
46338
+ const out = {};
46339
+ for (const line2 of text.split("\n")) {
46340
+ const m = /^([A-Z_]+)=(.*)$/.exec(line2.trim());
46341
+ if (m) out[m[1]] = m[2].replace(/^["']|["']$/g, "");
46342
+ }
46343
+ return out;
46344
+ }
46345
+ function osvEcosystem(os3) {
46346
+ if (os3.ID === "ubuntu" && os3.VERSION_ID) {
46347
+ return /LTS/.test(os3.VERSION ?? "") ? `Ubuntu:${os3.VERSION_ID}:LTS` : `Ubuntu:${os3.VERSION_ID}`;
46348
+ }
46349
+ if (os3.ID === "debian" && os3.VERSION_ID) return `Debian:${os3.VERSION_ID.split(".")[0]}`;
46350
+ return null;
46351
+ }
46352
+ function parseAptSimulation(text) {
46353
+ const out = [];
46354
+ for (const line2 of text.split("\n")) {
46355
+ const m = /^Inst (\S+) \[([^\]]+)\] \((\S+) ([^[)]*)/.exec(line2);
46356
+ if (!m) continue;
46357
+ const origins = m[4];
46358
+ out.push({
46359
+ name: m[1],
46360
+ installed: m[2],
46361
+ candidate: m[3],
46362
+ security: /-security\b|Debian-Security/i.test(origins)
46363
+ });
46364
+ }
46365
+ return out;
46366
+ }
46367
+ function parseSourceMap(text) {
46368
+ const out = /* @__PURE__ */ new Map();
46369
+ for (const line2 of text.split("\n")) {
46370
+ const [binary, source, version] = line2.trim().split("|");
46371
+ if (binary && source && version) out.set(binary.split(":")[0], { source, version });
46372
+ }
46373
+ return out;
46374
+ }
46375
+ function parseCandidateSources(text) {
46376
+ const out = /* @__PURE__ */ new Map();
46377
+ for (const stanza of text.split(/\n\s*\n/)) {
46378
+ const pkg = /^Package: (\S+)/m.exec(stanza)?.[1];
46379
+ const version = /^Version: (\S+)/m.exec(stanza)?.[1];
46380
+ if (!pkg || !version) continue;
46381
+ const src = /^Source: (\S+)(?: \(([^)]+)\))?/m.exec(stanza);
46382
+ out.set(`${pkg}=${version}`, { source: src?.[1] ?? pkg, version: src?.[2] ?? version });
46383
+ }
46384
+ return out;
46385
+ }
46386
+ function advisorySeverity(rec, ecosystem, source) {
46387
+ const label = (rec.severity?.find((s) => s.type === "Ubuntu")?.score ?? rec.database_specific?.severity ?? rec.affected?.find((a) => a.package?.ecosystem === ecosystem && a.package?.name === source)?.ecosystem_specific?.urgency ?? "").toLowerCase();
46388
+ if (label === "negligible" || label === "unimportant") return "info";
46389
+ if (label === "moderate") return "medium";
46390
+ if (SEVERITIES2.includes(label)) return label;
46391
+ return "medium";
46392
+ }
46393
+ function fixedByUpdate(rec, ecosystem, source, installed, candidate) {
46394
+ for (const a of rec.affected ?? []) {
46395
+ if (a.package?.ecosystem !== ecosystem || a.package?.name !== source) continue;
46396
+ for (const range of a.ranges ?? []) {
46397
+ for (const ev of range.events ?? []) {
46398
+ const fixed = ev.fixed;
46399
+ if (!fixed) continue;
46400
+ if (compareDebianVersions(installed, fixed) < 0 && compareDebianVersions(fixed, candidate) <= 0) return true;
46401
+ }
46402
+ }
46403
+ }
46404
+ return false;
46405
+ }
46406
+ function displayId(rec) {
46407
+ return rec.upstream?.find((u) => u.startsWith("CVE-")) ?? rec.aliases?.find((u) => u.startsWith("CVE-")) ?? rec.id;
46408
+ }
46409
+ async function osvRecords(doFetch, ecosystem, source, version) {
46410
+ const out = [];
46411
+ let pageToken;
46412
+ for (let page = 0; page < 20; page++) {
46413
+ const res = await doFetch(OSV_QUERY, {
46414
+ method: "POST",
46415
+ headers: { "Content-Type": "application/json" },
46416
+ body: JSON.stringify({ package: { name: source, ecosystem }, version, ...pageToken ? { page_token: pageToken } : {} })
46417
+ });
46418
+ if (!res.ok) throw new Error(`OSV query for ${source} failed: HTTP ${res.status}`);
46419
+ const body = await res.json();
46420
+ out.push(...body.vulns ?? []);
46421
+ pageToken = body.next_page_token;
46422
+ if (!pageToken) break;
46423
+ }
46424
+ return out;
46425
+ }
46426
+ function newestReleaseMtime(dir) {
46427
+ try {
46428
+ let newest = 0;
46429
+ for (const name of (0, import_node_fs43.readdirSync)(dir)) {
46430
+ if (!/Release$/.test(name)) continue;
46431
+ newest = Math.max(newest, (0, import_node_fs43.statSync)((0, import_node_path31.join)(dir, name)).mtimeMs);
46432
+ }
46433
+ return newest > 0 ? new Date(newest) : null;
46434
+ } catch {
46435
+ return null;
46436
+ }
46437
+ }
46438
+ function emptyCounts2() {
46439
+ return { info: 0, low: 0, medium: 0, high: 0, critical: 0, cves: 0, packages: 0 };
46440
+ }
46441
+ async function checkPatches(opts = {}) {
46442
+ const exec = opts.exec ?? defaultExec;
46443
+ const doFetch = opts.fetchImpl ?? globalThis.fetch;
46444
+ const now = opts.now ?? /* @__PURE__ */ new Date();
46445
+ let osText = opts.osRelease;
46446
+ if (osText === void 0) {
46447
+ try {
46448
+ osText = (0, import_node_fs43.readFileSync)("/etc/os-release", "utf-8");
46449
+ } catch {
46450
+ osText = "";
46451
+ }
46452
+ }
46453
+ const os3 = parseOsRelease(osText);
46454
+ const ecosystem = osvEcosystem(os3);
46455
+ const base = {
46456
+ supported: false,
46457
+ os: os3.PRETTY_NAME ?? os3.ID ?? "unknown",
46458
+ ecosystem,
46459
+ checked_at: now.toISOString(),
46460
+ lists_updated_at: null,
46461
+ lists_stale: false,
46462
+ upgradable: 0,
46463
+ packages: [],
46464
+ counts: emptyCounts2()
46465
+ };
46466
+ if (!ecosystem) {
46467
+ return { ...base, reason: `patch status supports Debian and Ubuntu; this is ${base.os}` };
46468
+ }
46469
+ let simulation;
46470
+ try {
46471
+ simulation = await exec("apt-get", ["-s", "-o", "Debug::NoLocking=1", "dist-upgrade"]);
46472
+ } catch (err) {
46473
+ return { ...base, reason: `apt-get simulation failed: ${err.message.split("\n")[0]}` };
46474
+ }
46475
+ const listsAt = newestReleaseMtime(opts.aptListsDir ?? "/var/lib/apt/lists");
46476
+ const report = {
46477
+ ...base,
46478
+ supported: true,
46479
+ lists_updated_at: listsAt?.toISOString() ?? null,
46480
+ lists_stale: !listsAt || now.getTime() - listsAt.getTime() > (opts.staleAfterMs ?? STALE_AFTER_MS)
46481
+ };
46482
+ const upgrades = parseAptSimulation(simulation);
46483
+ report.upgradable = upgrades.length;
46484
+ const security = upgrades.filter((u) => u.security);
46485
+ if (security.length === 0) return report;
46486
+ const installedSources = parseSourceMap(await exec("dpkg-query", [
46487
+ "-W",
46488
+ "-f=${Package}|${source:Package}|${source:Version}\n",
46489
+ ...security.map((u) => u.name)
46490
+ ]).catch(() => ""));
46491
+ const candidateSources = parseCandidateSources(await exec("apt-cache", [
46492
+ "show",
46493
+ "--no-all-versions",
46494
+ ...security.map((u) => `${u.name}=${u.candidate}`)
46495
+ ]).catch(() => ""));
46496
+ const bySource = /* @__PURE__ */ new Map();
46497
+ for (const u of security) {
46498
+ const inst = installedSources.get(u.name) ?? { source: u.name, version: u.installed };
46499
+ const cand = candidateSources.get(`${u.name}=${u.candidate}`) ?? { source: inst.source, version: u.candidate };
46500
+ const key = `${inst.source}|${inst.version}`;
46501
+ const entry = bySource.get(key);
46502
+ if (entry) {
46503
+ entry.binaries.push(u.name);
46504
+ if (compareDebianVersions(cand.version, entry.candidate) > 0) entry.candidate = cand.version;
46505
+ } else {
46506
+ bySource.set(key, {
46507
+ binaries: [u.name],
46508
+ source: inst.source,
46509
+ installed: inst.version,
46510
+ candidate: cand.version,
46511
+ severity: "medium",
46512
+ cves: []
46513
+ });
46514
+ }
46515
+ }
46516
+ for (const pkg of bySource.values()) {
46517
+ try {
46518
+ const seen = /* @__PURE__ */ new Set();
46519
+ for (const rec of await osvRecords(doFetch, ecosystem, pkg.source, pkg.installed)) {
46520
+ if (!fixedByUpdate(rec, ecosystem, pkg.source, pkg.installed, pkg.candidate)) continue;
46521
+ const id = displayId(rec);
46522
+ if (seen.has(id)) continue;
46523
+ seen.add(id);
46524
+ pkg.cves.push({ id, severity: advisorySeverity(rec, ecosystem, pkg.source) });
46525
+ }
46526
+ } catch (err) {
46527
+ report.osv_error ??= err.message;
46528
+ }
46529
+ pkg.cves.sort((a, b) => RANK[b.severity] - RANK[a.severity] || a.id.localeCompare(b.id));
46530
+ if (pkg.cves.length > 0) pkg.severity = pkg.cves[0].severity;
46531
+ pkg.binaries.sort();
46532
+ }
46533
+ report.packages = [...bySource.values()].sort(
46534
+ (a, b) => RANK[b.severity] - RANK[a.severity] || b.cves.length - a.cves.length || a.source.localeCompare(b.source)
46535
+ );
46536
+ const counts = emptyCounts2();
46537
+ counts.packages = report.packages.length;
46538
+ for (const pkg of report.packages) {
46539
+ counts.cves += pkg.cves.length;
46540
+ for (const cve of pkg.cves) counts[cve.severity]++;
46541
+ }
46542
+ report.counts = counts;
46543
+ return report;
46544
+ }
46545
+ function worstSeverity(report) {
46546
+ if (report.packages.length === 0) return null;
46547
+ return report.packages.reduce((w, p) => RANK[p.severity] > RANK[w] ? p.severity : w, "info");
46548
+ }
46549
+ var MAX_DETAIL_PACKAGES = 30;
46550
+ function patchFinding(report) {
46551
+ const details = {
46552
+ kind: "os-patches",
46553
+ supported: report.supported,
46554
+ os: report.os,
46555
+ ecosystem: report.ecosystem,
46556
+ checked_at: report.checked_at,
46557
+ lists_updated_at: report.lists_updated_at,
46558
+ lists_stale: report.lists_stale,
46559
+ upgradable: report.upgradable,
46560
+ counts: report.counts,
46561
+ packages: report.packages.slice(0, MAX_DETAIL_PACKAGES).map((p) => ({
46562
+ source: p.source,
46563
+ installed: p.installed,
46564
+ candidate: p.candidate,
46565
+ severity: p.severity,
46566
+ binaries: p.binaries.slice(0, 10),
46567
+ cve_count: p.cves.length,
46568
+ cves: p.cves.slice(0, 10).map((c2) => c2.id)
46569
+ })),
46570
+ ...report.packages.length > MAX_DETAIL_PACKAGES ? { packages_truncated: report.packages.length } : {},
46571
+ ...report.osv_error ? { osv_error: report.osv_error } : {}
46572
+ };
46573
+ if (!report.supported) {
46574
+ return {
46575
+ key: "os-patches",
46576
+ status: "warn",
46577
+ severity: "info",
46578
+ title: "OS patch status unavailable",
46579
+ explanation: report.reason ?? "Patch status could not be checked on this system.",
46580
+ details
46581
+ };
46582
+ }
46583
+ const worst = worstSeverity(report);
46584
+ const staleNote = report.lists_stale ? ` Package lists were last refreshed ${report.lists_updated_at ? report.lists_updated_at.slice(0, 10) : "never"}, so newer fixes may be missing.` : "";
46585
+ if (!worst) {
46586
+ return {
46587
+ key: "os-patches",
46588
+ status: report.lists_stale ? "warn" : "pass",
46589
+ severity: report.lists_stale ? "low" : "high",
46590
+ title: report.lists_stale ? "No pending security updates (package lists stale)" : "No pending security updates",
46591
+ explanation: `apt has no security updates waiting.${staleNote}`,
46592
+ recommendation: report.lists_stale ? "Run `sudo apt-get update` (or enable unattended-upgrades) so fixes are seen." : void 0,
46593
+ details
46594
+ };
46595
+ }
46596
+ const c = report.counts;
46597
+ const parts = [c.critical && `${c.critical} critical`, c.high && `${c.high} high`].filter(Boolean);
46598
+ const cveText = c.cves > 0 ? `${c.cves} CVE${c.cves === 1 ? "" : "s"}${parts.length ? ` (${parts.join(", ")})` : ""}` : "unnamed advisories";
46599
+ const top = report.packages.slice(0, 5).map((p) => `${p.source} ${p.installed} \u2192 ${p.candidate}`).join("; ");
46600
+ return {
46601
+ key: "os-patches",
46602
+ status: worst === "critical" || worst === "high" ? "fail" : "warn",
46603
+ severity: worst,
46604
+ title: `${c.packages} package${c.packages === 1 ? "" : "s"} with security fixes available: ${cveText}`,
46605
+ explanation: `Security updates are waiting for ${c.packages} source package${c.packages === 1 ? "" : "s"}: ${top}${report.packages.length > 5 ? "; \u2026" : ""}.${staleNote}`,
46606
+ recommendation: "Apply them: `sudo apt-get update && sudo apt-get upgrade`, then restart affected services (or reboot for a kernel or libc update).",
46607
+ details
46608
+ };
46609
+ }
46610
+
46611
+ // src/commands/patches.ts
46612
+ var SEVERITY_COLOR = {
46613
+ critical: source_default.red.bold,
46614
+ high: source_default.red,
46615
+ medium: source_default.yellow,
46616
+ low: source_default.cyan,
46617
+ info: source_default.gray
46618
+ };
46619
+ async function patchesCommand(opts) {
46620
+ if (!opts.json) {
46621
+ banner();
46622
+ logger.info("Checking OS packages for pending security updates...\n");
46623
+ }
46624
+ const spinner = opts.json ? null : ora({ text: "Asking apt and OSV...", color: "green" }).start();
46625
+ const report = await checkPatches();
46626
+ const finding = patchFinding(report);
46627
+ if (opts.json) {
46628
+ console.log(JSON.stringify({ report, finding }, null, 2));
46629
+ if (opts.upload !== false) await uploadFindings([finding], true);
46630
+ return;
46631
+ }
46632
+ if (!report.supported) {
46633
+ spinner?.warn(report.reason ?? "Patch status unavailable on this system\n");
46634
+ console.log();
46635
+ return;
46636
+ }
46637
+ spinner?.succeed("Patch check complete\n");
46638
+ console.log(` ${source_default.white.bold("System:")} ${report.os} ${source_default.gray(`(${report.ecosystem})`)}`);
46639
+ const listsAge = report.lists_updated_at ? report.lists_updated_at.replace("T", " ").slice(0, 16) + " UTC" : "unknown";
46640
+ console.log(` ${source_default.white.bold("Package lists:")} ${report.lists_stale ? source_default.yellow(`${listsAge} (stale; run sudo apt-get update)`) : listsAge}`);
46641
+ console.log(` ${source_default.white.bold("Upgradable:")} ${report.upgradable} package(s), ${report.counts.packages} with security fixes`);
46642
+ console.log(source_default.gray(" " + "\u2500".repeat(60)));
46643
+ console.log();
46644
+ if (report.packages.length === 0) {
46645
+ console.log(` ${source_default.green("\u2713")} No security updates waiting.
46646
+ `);
46647
+ } else {
46648
+ for (const p of report.packages) {
46649
+ const sev = SEVERITY_COLOR[p.severity](p.severity.toUpperCase().padEnd(8));
46650
+ console.log(` ${sev} ${source_default.white.bold(p.source)} ${source_default.gray(p.installed)} \u2192 ${source_default.green(p.candidate)}`);
46651
+ if (p.cves.length > 0) {
46652
+ const shown = p.cves.slice(0, 6).map((c2) => SEVERITY_COLOR[c2.severity](c2.id)).join(" ");
46653
+ console.log(` ${shown}${p.cves.length > 6 ? source_default.gray(` +${p.cves.length - 6} more`) : ""}`);
46654
+ } else {
46655
+ console.log(source_default.gray(" security update; no matching advisory in OSV"));
46656
+ }
46657
+ if (p.binaries.length > 1 || p.binaries[0] !== p.source) {
46658
+ console.log(source_default.gray(` packages: ${p.binaries.join(", ")}`));
46659
+ }
46660
+ }
46661
+ console.log();
46662
+ const c = report.counts;
46663
+ console.log(source_default.gray(" " + "\u2500".repeat(60)));
46664
+ console.log(` ${source_default.white.bold(`${c.cves} CVE(s) fixed by pending updates:`)} ${source_default.red(`${c.critical} critical`)} ${source_default.red(`${c.high} high`)} ${source_default.yellow(`${c.medium} medium`)} ${source_default.cyan(`${c.low} low`)}`);
46665
+ if (finding.recommendation) console.log(` ${source_default.yellow("Fix:")} ${finding.recommendation}`);
46666
+ console.log();
46667
+ }
46668
+ if (report.osv_error) console.log(source_default.yellow(` ! CVE lookup incomplete: ${report.osv_error}
46669
+ `));
46670
+ if (opts.upload !== false) await uploadFindings([finding], false);
46671
+ }
46672
+
46673
+ // src/commands/feeds.ts
46674
+ var import_node_net12 = require("net");
46675
+ var import_node_path32 = require("path");
46676
+ init_paths();
46677
+ async function loadSet() {
46678
+ for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
46679
+ const path = (0, import_node_path32.join)(dir, "threat-feeds.json");
46680
+ const set = readFeedCache(path);
46681
+ if (set) return { set, from: path };
46682
+ }
46683
+ const settings = threatFeedSettings(loadConfig((0, import_node_path32.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
46684
+ return { set: await fetchFeeds(settings), from: "abuse.ch (live; no daemon cache readable)" };
46685
+ }
46686
+ async function feedsCommand(action, value, opts) {
46687
+ const { set, from } = await loadSet();
46688
+ if (action === "check") {
46689
+ if (!value) {
46690
+ console.error("Usage: threatcrush feeds check <ip|domain>");
46691
+ process.exitCode = 2;
46692
+ return;
46693
+ }
46694
+ const ipHit = (0, import_node_net12.isIP)(value) ? matchIp(value, set) : null;
46695
+ const domainHit = (0, import_node_net12.isIP)(value) ? null : matchDomain(value, set);
46696
+ const listed = ipHit ?? domainHit?.indicator ?? null;
46697
+ if (opts.json) {
46698
+ console.log(JSON.stringify({ value, listed: Boolean(listed), indicator: listed, matched: domainHit?.domain ?? (ipHit ? value : null), fetched_at: set.fetched_at }, null, 2));
46699
+ } else if (listed) {
46700
+ console.log(`${source_default.red("LISTED")} ${value}${domainHit && domainHit.domain !== value ? ` (via ${domainHit.domain})` : ""}: ${listed.malware} ${listed.threat} [${listed.feed}]`);
46701
+ } else {
46702
+ console.log(`${source_default.green("not listed")} ${value}`);
46703
+ }
46704
+ process.exitCode = listed ? 1 : 0;
46705
+ return;
46706
+ }
46707
+ const ips = Object.keys(set.ips).length;
46708
+ const domains = Object.keys(set.domains).length;
46709
+ if (opts.json) {
46710
+ console.log(JSON.stringify({ from, fetched_at: set.fetched_at, ips, domains, skipped_shared: set.skipped_shared, sources: set.sources }, null, 2));
46711
+ return;
46712
+ }
46713
+ console.log(` ${source_default.white.bold("Threat feeds")} ${source_default.gray(`(${from})`)}`);
46714
+ console.log(` Fetched: ${set.fetched_at.replace("T", " ").slice(0, 16)} UTC`);
46715
+ console.log(` ${ips} C2/payload IPs, ${domains} malware domains; ${set.skipped_shared} shared or protected entries skipped`);
46716
+ for (const s of set.sources) {
46717
+ console.log(` ${s.ok ? source_default.green("\u2713") : source_default.red("\u2717")} ${s.feed.padEnd(16)} ${s.ok ? `${s.count}` : source_default.red(s.error ?? "failed")}`);
46718
+ }
46719
+ console.log(source_default.gray("\n Blocking egress needs [threat_feeds] block = true and [remediation] in enforce mode."));
46720
+ }
46721
+
45796
46722
  // src/commands/firewall.ts
45797
46723
  init_ipc_client();
45798
46724
  init_paths();
@@ -45937,11 +46863,11 @@ async function allowlistCommand(opts) {
45937
46863
  init_paths();
45938
46864
 
45939
46865
  // src/upgrade.ts
45940
- var import_node_child_process16 = require("child_process");
46866
+ var import_node_child_process18 = require("child_process");
45941
46867
  var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
45942
46868
  var defaultRunner = (cmd) => {
45943
46869
  try {
45944
- return (0, import_node_child_process16.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
46870
+ return (0, import_node_child_process18.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
45945
46871
  } catch {
45946
46872
  return null;
45947
46873
  }
@@ -46028,12 +46954,12 @@ function staleDaemonWarning(cliVersion, daemonVersion, restartCommand = "threatc
46028
46954
  ` ${restartCommand}`
46029
46955
  ];
46030
46956
  }
46031
- function shadowedUpdateWarning(latest, active, activePath) {
46032
- if (!latest || !active || latest === active) return null;
46957
+ function shadowedUpdateWarning(latest, active2, activePath) {
46958
+ if (!latest || !active2 || latest === active2) return null;
46033
46959
  return [
46034
46960
  "\u26A0 The update ran, but PATH still resolves to an older ThreatCrush.",
46035
46961
  ` Latest published: ${latest}`,
46036
- ` Running from PATH: ${active} (${activePath || "unknown"})`,
46962
+ ` Running from PATH: ${active2} (${activePath || "unknown"})`,
46037
46963
  "",
46038
46964
  " Usually a stale shell hash. Try first:",
46039
46965
  " hash -r # or open a new terminal",
@@ -46056,25 +46982,25 @@ ${source_default.dim(" C R U S H")}
46056
46982
  var API_URL6 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
46057
46983
  var PKG_NAME2 = "@profullstack/threatcrush";
46058
46984
  var DESKTOP_PKG_NAME = "@profullstack/threatcrush-desktop";
46059
- var INSTALL_CONFIG_PATH = (0, import_node_path30.join)((0, import_node_os13.homedir)(), ".threatcrush", "install.json");
46985
+ var INSTALL_CONFIG_PATH = (0, import_node_path33.join)((0, import_node_os13.homedir)(), ".threatcrush", "install.json");
46060
46986
  function detectPackageManager() {
46061
46987
  try {
46062
- const npmGlobal = (0, import_node_child_process17.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
46988
+ const npmGlobal = (0, import_node_child_process19.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
46063
46989
  if (npmGlobal.includes(PKG_NAME2)) return "npm";
46064
46990
  } catch {
46065
46991
  }
46066
46992
  try {
46067
- (0, import_node_child_process17.execSync)("pnpm --version", { stdio: "pipe" });
46993
+ (0, import_node_child_process19.execSync)("pnpm --version", { stdio: "pipe" });
46068
46994
  return "pnpm";
46069
46995
  } catch {
46070
46996
  }
46071
46997
  try {
46072
- (0, import_node_child_process17.execSync)("yarn --version", { stdio: "pipe" });
46998
+ (0, import_node_child_process19.execSync)("yarn --version", { stdio: "pipe" });
46073
46999
  return "yarn";
46074
47000
  } catch {
46075
47001
  }
46076
47002
  try {
46077
- (0, import_node_child_process17.execSync)("bun --version", { stdio: "pipe" });
47003
+ (0, import_node_child_process19.execSync)("bun --version", { stdio: "pipe" });
46078
47004
  return "bun";
46079
47005
  } catch {
46080
47006
  }
@@ -46082,14 +47008,14 @@ function detectPackageManager() {
46082
47008
  }
46083
47009
  function readInstallConfig() {
46084
47010
  try {
46085
- return JSON.parse((0, import_node_fs42.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
47011
+ return JSON.parse((0, import_node_fs44.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
46086
47012
  } catch {
46087
47013
  return {};
46088
47014
  }
46089
47015
  }
46090
47016
  function packageLooksInstalled(pm, pkgName) {
46091
47017
  try {
46092
- const output = (0, import_node_child_process17.execSync)(globalListCommand(pm, pkgName), {
47018
+ const output = (0, import_node_child_process19.execSync)(globalListCommand(pm, pkgName), {
46093
47019
  encoding: "utf-8",
46094
47020
  stdio: ["pipe", "pipe", "pipe"]
46095
47021
  });
@@ -46192,14 +47118,14 @@ async function promoteUnprivilegedDaemon() {
46192
47118
  function restartSystemdDaemon() {
46193
47119
  const asRoot = typeof process.getuid === "function" && process.getuid() === 0;
46194
47120
  const argv = asRoot ? ["systemctl", "restart", DAEMON_UNIT] : ["sudo", "systemctl", "restart", DAEMON_UNIT];
46195
- if (!asRoot && (0, import_node_child_process17.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
47121
+ if (!asRoot && (0, import_node_child_process19.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
46196
47122
  const [cmd, ...args] = argv;
46197
- if ((0, import_node_child_process17.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
46198
- return (0, import_node_child_process17.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
47123
+ if ((0, import_node_child_process19.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
47124
+ return (0, import_node_child_process19.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
46199
47125
  }
46200
47126
  function execQuiet(cmd) {
46201
47127
  try {
46202
- return (0, import_node_child_process17.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
47128
+ return (0, import_node_child_process19.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
46203
47129
  } catch {
46204
47130
  return null;
46205
47131
  }
@@ -46349,6 +47275,12 @@ program2.command("rules").description("Manage detection rules").argument("[actio
46349
47275
  program2.command("harden").description("Run hardening security scan").option("--json", "Output results as JSON").option("--no-upload", "Do not upload findings to the dashboard (uploaded when this machine is linked)").action(async (opts) => {
46350
47276
  await hardenCommand(opts);
46351
47277
  });
47278
+ program2.command("patches").description("List OS packages with a security update waiting, and the CVEs it fixes (Debian/Ubuntu)").option("--json", "Output the report as JSON").option("--no-upload", "Do not upload the result to the dashboard (uploaded when this machine is linked)").action(async (opts) => {
47279
+ await patchesCommand(opts);
47280
+ });
47281
+ program2.command("feeds [action] [value]").description("Show the abuse.ch C2/malware list the daemon matches; `feeds check <ip|domain>` looks one up (exit 1 when listed)").option("--json", "Output as JSON").action(async (action, value, opts) => {
47282
+ await feedsCommand(action, value, opts);
47283
+ });
46352
47284
  program2.command("block").description("Block an IP address via the firewall").argument("<ip>", "IP address to block").option("--ttl <duration>", "Block duration (e.g. 1h, 30m, 1d)").action(async (ip, opts) => {
46353
47285
  await blockCommand(ip, opts);
46354
47286
  });
@@ -46385,7 +47317,7 @@ program2.command("uninstall-service").description("Remove the threatcrushd syste
46385
47317
  program2.command("logs").description("Tail daemon logs").action(async () => {
46386
47318
  console.log(LOGO2);
46387
47319
  const logPath = PATHS.logFile;
46388
- if (!(0, import_node_fs42.existsSync)(logPath)) {
47320
+ if (!(0, import_node_fs44.existsSync)(logPath)) {
46389
47321
  console.log(source_default.yellow(` No log file found at ${logPath}`));
46390
47322
  console.log(source_default.dim(" Start the daemon first with `threatcrush start`\n"));
46391
47323
  return;
@@ -46393,7 +47325,7 @@ program2.command("logs").description("Tail daemon logs").action(async () => {
46393
47325
  console.log(source_default.green(` Tailing ${logPath}...
46394
47326
  `));
46395
47327
  console.log(source_default.gray(" Press Ctrl+C to stop\n"));
46396
- (0, import_node_child_process17.execSync)(`tail -f ${logPath}`, { stdio: "inherit" });
47328
+ (0, import_node_child_process19.execSync)(`tail -f ${logPath}`, { stdio: "inherit" });
46397
47329
  });
46398
47330
  program2.command("update").description("Update ThreatCrush CLI and installed bundle").option("--cli", "Update CLI only").option("--modules", "Update modules only").option("--desktop", "Update desktop app too").action(async (opts) => {
46399
47331
  console.log(LOGO2);
@@ -46405,7 +47337,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
46405
47337
  for (const cmd of commands2) {
46406
47338
  console.log(source_default.green(` \u2192 ${cmd}
46407
47339
  `));
46408
- (0, import_node_child_process17.execSync)(cmd, { stdio: "inherit" });
47340
+ (0, import_node_child_process19.execSync)(cmd, { stdio: "inherit" });
46409
47341
  }
46410
47342
  console.log(source_default.green("\n \u2713 Modules updated successfully!\n"));
46411
47343
  await reportIfStillStale();
@@ -46430,7 +47362,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
46430
47362
  for (const cmd of commands) {
46431
47363
  console.log(source_default.green(` \u2192 ${cmd}
46432
47364
  `));
46433
- (0, import_node_child_process17.execSync)(cmd, { stdio: "inherit" });
47365
+ (0, import_node_child_process19.execSync)(cmd, { stdio: "inherit" });
46434
47366
  }
46435
47367
  console.log(source_default.green("\n \u2713 ThreatCrush updated successfully!\n"));
46436
47368
  if (installMode === "desktop") {
@@ -46481,7 +47413,7 @@ program2.command("remove").description("Uninstall ThreatCrush and the installed
46481
47413
  for (const cmd of commands) {
46482
47414
  console.log(source_default.green(` \u2192 ${cmd}
46483
47415
  `));
46484
- (0, import_node_child_process17.execSync)(cmd, { stdio: "inherit" });
47416
+ (0, import_node_child_process19.execSync)(cmd, { stdio: "inherit" });
46485
47417
  }
46486
47418
  console.log(source_default.green("\n \u2713 ThreatCrush has been uninstalled.\n"));
46487
47419
  console.log(source_default.dim(" We're sorry to see you go! \u{1F44B}\n"));
@@ -46558,10 +47490,10 @@ storeCmd.command("search <query>").description("Search for modules in the store"
46558
47490
  });
46559
47491
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
46560
47492
  console.log(LOGO2);
46561
- const configPath = (0, import_node_path30.join)((0, import_node_os13.homedir)(), ".threatcrush", "config.json");
47493
+ const configPath = (0, import_node_path33.join)((0, import_node_os13.homedir)(), ".threatcrush", "config.json");
46562
47494
  let email = "";
46563
47495
  try {
46564
- const config = JSON.parse((0, import_node_fs42.readFileSync)(configPath, "utf-8"));
47496
+ const config = JSON.parse((0, import_node_fs44.readFileSync)(configPath, "utf-8"));
46565
47497
  email = config.email || "";
46566
47498
  } catch {
46567
47499
  }
@@ -46578,9 +47510,9 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
46578
47510
  return;
46579
47511
  }
46580
47512
  try {
46581
- const dir = (0, import_node_path30.join)((0, import_node_os13.homedir)(), ".threatcrush");
46582
- if (!(0, import_node_fs42.existsSync)(dir)) (0, import_node_fs42.mkdirSync)(dir, { recursive: true });
46583
- (0, import_node_fs42.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
47513
+ const dir = (0, import_node_path33.join)((0, import_node_os13.homedir)(), ".threatcrush");
47514
+ if (!(0, import_node_fs44.existsSync)(dir)) (0, import_node_fs44.mkdirSync)(dir, { recursive: true });
47515
+ (0, import_node_fs44.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
46584
47516
  console.log(source_default.dim(` Saved email to ${configPath}`));
46585
47517
  } catch {
46586
47518
  }