@profullstack/threatcrush 0.13.33 → 0.13.35

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
@@ -6241,22 +6241,22 @@ var init_diff = __esm({
6241
6241
  s.fg = DEFAULT_COLOR;
6242
6242
  s.bg = DEFAULT_COLOR;
6243
6243
  }
6244
- const added = attrs & ~s.attrs;
6245
- if (added !== 0) {
6244
+ const added2 = attrs & ~s.attrs;
6245
+ if (added2 !== 0) {
6246
6246
  const codes = [];
6247
- if (added & Attr.Bold)
6247
+ if (added2 & Attr.Bold)
6248
6248
  codes.push(1);
6249
- if (added & Attr.Dim)
6249
+ if (added2 & Attr.Dim)
6250
6250
  codes.push(2);
6251
- if (added & Attr.Italic)
6251
+ if (added2 & Attr.Italic)
6252
6252
  codes.push(3);
6253
- if (added & Attr.Underline)
6253
+ if (added2 & Attr.Underline)
6254
6254
  codes.push(4);
6255
- if (added & Attr.Blink)
6255
+ if (added2 & Attr.Blink)
6256
6256
  codes.push(5);
6257
- if (added & Attr.Reverse)
6257
+ if (added2 & Attr.Reverse)
6258
6258
  codes.push(7);
6259
- if (added & Attr.Strike)
6259
+ if (added2 & Attr.Strike)
6260
6260
  codes.push(9);
6261
6261
  if (codes.length)
6262
6262
  this.parts.push(`${CSI}${codes.join(";")}m`);
@@ -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;
@@ -21537,7 +21537,7 @@ var init_map = __esm({
21537
21537
  this.selfAsked = true;
21538
21538
  void this.lookupSelf();
21539
21539
  }
21540
- let added = false;
21540
+ let added2 = false;
21541
21541
  for (const ip of ips) {
21542
21542
  if (this.known.has(ip) || this.queue.has(ip)) continue;
21543
21543
  if (!isPublicAddress(ip)) {
@@ -21545,9 +21545,9 @@ var init_map = __esm({
21545
21545
  continue;
21546
21546
  }
21547
21547
  this.queue.add(ip);
21548
- added = true;
21548
+ added2 = true;
21549
21549
  }
21550
- if (added && !this.timer) {
21550
+ if (added2 && !this.timer) {
21551
21551
  this.timer = setTimeout(() => {
21552
21552
  this.timer = null;
21553
21553
  void this.flush();
@@ -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_process18 = require("child_process");
24749
- var import_node_fs43 = require("fs");
24750
- var import_node_path31 = require("path");
24748
+ var import_node_child_process20 = require("child_process");
24749
+ var import_node_fs46 = require("fs");
24750
+ var import_node_path34 = require("path");
24751
24751
  var import_node_os13 = require("os");
24752
24752
 
24753
24753
  // src/commands/monitor.ts
@@ -31640,6 +31640,8 @@ function loadConfig(configPath) {
31640
31640
  cloud: parsed.cloud,
31641
31641
  watchdog: parsed.watchdog,
31642
31642
  update: parsed.update,
31643
+ threat_feeds: parsed.threat_feeds,
31644
+ privileged: parsed.privileged,
31643
31645
  storage: parsed.storage,
31644
31646
  license: parsed.license
31645
31647
  };
@@ -31778,6 +31780,14 @@ function getRecentEvents(limit = 50) {
31778
31780
  `).all(limit);
31779
31781
  return rows.map(rowToEvent);
31780
31782
  }
31783
+ function getModuleEvents(module2, limit = 50) {
31784
+ const database = tryDb();
31785
+ if (!database) return [];
31786
+ const rows = database.prepare(`
31787
+ SELECT * FROM events WHERE module = ? ORDER BY id DESC LIMIT ?
31788
+ `).all(module2, limit);
31789
+ return rows.map(rowToEvent);
31790
+ }
31781
31791
  var RECENT_WINDOW = 2e5;
31782
31792
  function eventsEverRecorded(database) {
31783
31793
  const row = database.prepare(`SELECT seq FROM sqlite_sequence WHERE name = 'events'`).get();
@@ -39779,16 +39789,16 @@ async function sshConnect(options) {
39779
39789
  }
39780
39790
 
39781
39791
  // 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");
39785
- var import_node_fs37 = require("fs");
39792
+ var import_node_child_process15 = require("child_process");
39793
+ var import_node_fs38 = require("fs");
39794
+ var import_node_path29 = require("path");
39795
+ var import_node_fs39 = require("fs");
39786
39796
 
39787
39797
  // src/daemon/index.ts
39788
- var import_node_fs35 = require("fs");
39789
- var import_node_child_process12 = require("child_process");
39798
+ var import_node_fs37 = require("fs");
39799
+ var import_node_child_process14 = require("child_process");
39790
39800
  var import_node_os11 = require("os");
39791
- var import_node_path26 = require("path");
39801
+ var import_node_path28 = require("path");
39792
39802
  var import_node_util = require("util");
39793
39803
  init_paths();
39794
39804
 
@@ -40091,8 +40101,8 @@ function admGid(readGroup = () => (0, import_node_fs24.readFileSync)("/etc/group
40091
40101
  }
40092
40102
 
40093
40103
  // src/daemon/module-host.ts
40094
- var import_node_fs28 = require("fs");
40095
- var import_node_path20 = require("path");
40104
+ var import_node_fs29 = require("fs");
40105
+ var import_node_path21 = require("path");
40096
40106
  var import_node_url = require("url");
40097
40107
  var import_toml4 = __toESM(require_toml());
40098
40108
  init_paths();
@@ -40668,9 +40678,347 @@ var NetworkMonitor = class {
40668
40678
  };
40669
40679
 
40670
40680
  // src/modules/dns-monitor/index.ts
40681
+ var import_node_fs28 = require("fs");
40682
+ var import_node_child_process8 = require("child_process");
40683
+ var import_node_readline3 = require("readline");
40684
+
40685
+ // src/core/threat-feeds/index.ts
40671
40686
  var import_node_fs27 = require("fs");
40687
+ var import_node_path20 = require("path");
40688
+ var import_node_net5 = require("net");
40689
+
40690
+ // src/daemon/firewall/protected.ts
40672
40691
  var import_node_child_process7 = require("child_process");
40673
- var import_node_readline3 = require("readline");
40692
+ var import_node_net4 = require("net");
40693
+ var DEFAULT_PROTECTED = [
40694
+ "127.0.0.0/8",
40695
+ "::1/128",
40696
+ "10.0.0.0/8",
40697
+ "172.16.0.0/12",
40698
+ "192.168.0.0/16",
40699
+ "169.254.0.0/16",
40700
+ "fc00::/7",
40701
+ "fe80::/10"
40702
+ ];
40703
+ function ipToBytes(ip) {
40704
+ const version = (0, import_node_net4.isIP)(ip);
40705
+ if (version === 4) return v4ToBytes(ip);
40706
+ if (version === 6) return v6ToBytes(ip);
40707
+ return null;
40708
+ }
40709
+ function v4ToBytes(ip) {
40710
+ const parts = ip.split(".");
40711
+ if (parts.length !== 4) return null;
40712
+ const bytes = new Uint8Array(4);
40713
+ for (let i = 0; i < 4; i++) {
40714
+ const n = Number(parts[i]);
40715
+ if (!Number.isInteger(n) || n < 0 || n > 255) return null;
40716
+ bytes[i] = n;
40717
+ }
40718
+ return bytes;
40719
+ }
40720
+ function v6ToBytes(ip) {
40721
+ const bare = ip.split("%")[0];
40722
+ const [headText, tailText] = bare.split("::", 2);
40723
+ const head = headText ? headText.split(":") : [];
40724
+ const tail = tailText !== void 0 ? tailText ? tailText.split(":") : [] : null;
40725
+ const groups = [];
40726
+ const pushGroup = (group) => {
40727
+ if (group.includes(".")) {
40728
+ const v4 = v4ToBytes(group);
40729
+ if (!v4) return false;
40730
+ groups.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
40731
+ return true;
40732
+ }
40733
+ if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return false;
40734
+ groups.push(parseInt(group, 16));
40735
+ return true;
40736
+ };
40737
+ for (const group of head) if (!pushGroup(group)) return null;
40738
+ const headCount = groups.length;
40739
+ if (tail === null) {
40740
+ if (headCount !== 8) return null;
40741
+ } else {
40742
+ const tailGroups = [];
40743
+ const saved = groups.length;
40744
+ for (const group of tail) if (!pushGroup(group)) return null;
40745
+ tailGroups.push(...groups.splice(saved));
40746
+ const zeros = 8 - headCount - tailGroups.length;
40747
+ if (zeros < 0) return null;
40748
+ for (let i = 0; i < zeros; i++) groups.push(0);
40749
+ groups.push(...tailGroups);
40750
+ }
40751
+ if (groups.length !== 8) return null;
40752
+ const bytes = new Uint8Array(16);
40753
+ for (let i = 0; i < 8; i++) {
40754
+ bytes[i * 2] = groups[i] >> 8 & 255;
40755
+ bytes[i * 2 + 1] = groups[i] & 255;
40756
+ }
40757
+ return bytes;
40758
+ }
40759
+ function ipMatches(ip, entry) {
40760
+ const [network, prefixText] = entry.trim().split("/");
40761
+ const target = ipToBytes(ip);
40762
+ const base = ipToBytes(network);
40763
+ if (!target || !base || target.length !== base.length) return false;
40764
+ const bits2 = prefixText === void 0 ? base.length * 8 : Number(prefixText);
40765
+ if (!Number.isInteger(bits2) || bits2 < 0 || bits2 > base.length * 8) return false;
40766
+ const wholeBytes = Math.floor(bits2 / 8);
40767
+ for (let i = 0; i < wholeBytes; i++) {
40768
+ if (target[i] !== base[i]) return false;
40769
+ }
40770
+ const remainder = bits2 % 8;
40771
+ if (remainder === 0) return true;
40772
+ const mask = 255 << 8 - remainder & 255;
40773
+ return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
40774
+ }
40775
+ function isProtected(ip, list) {
40776
+ return list.some((entry) => ipMatches(ip, entry));
40777
+ }
40778
+ function currentSshClient(env2 = process.env) {
40779
+ const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
40780
+ if (!source) return null;
40781
+ const ip = source.trim().split(/\s+/)[0];
40782
+ return ip && (0, import_node_net4.isIP)(ip) ? ip : null;
40783
+ }
40784
+ function establishedSshPeers() {
40785
+ const peers = /* @__PURE__ */ new Set();
40786
+ try {
40787
+ const out = (0, import_node_child_process7.execFileSync)("ss", ["-tnpH"], {
40788
+ encoding: "utf-8",
40789
+ stdio: ["ignore", "pipe", "ignore"],
40790
+ timeout: 3e3
40791
+ });
40792
+ for (const line2 of out.split("\n")) {
40793
+ if (!/users:\(\("sshd/.test(line2)) continue;
40794
+ const parts = line2.trim().split(/\s+/);
40795
+ const peer = parts[4];
40796
+ if (!peer) continue;
40797
+ const ip = peer.slice(0, peer.lastIndexOf(":")).replace(/^\[|\]$/g, "");
40798
+ if (ip && (0, import_node_net4.isIP)(ip)) peers.add(ip);
40799
+ }
40800
+ } catch {
40801
+ }
40802
+ return [...peers];
40803
+ }
40804
+ function defaultGateways() {
40805
+ const found = /* @__PURE__ */ new Set();
40806
+ for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
40807
+ try {
40808
+ const out = (0, import_node_child_process7.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
40809
+ for (const line2 of out.split("\n")) {
40810
+ const match = line2.match(/\bvia\s+(\S+)/);
40811
+ if (match && (0, import_node_net4.isIP)(match[1])) found.add(match[1]);
40812
+ }
40813
+ } catch {
40814
+ }
40815
+ }
40816
+ return [...found];
40817
+ }
40818
+
40819
+ // src/core/threat-feeds/index.ts
40820
+ var FEEDS = {
40821
+ threatfoxRecent: "https://threatfox.abuse.ch/export/json/recent/",
40822
+ threatfoxHosts: "https://threatfox.abuse.ch/downloads/hostfile/",
40823
+ urlhausHosts: "https://urlhaus.abuse.ch/downloads/hostfile/",
40824
+ feodoIps: "https://feodotracker.abuse.ch/downloads/ipblocklist.txt"
40825
+ };
40826
+ var SHARED_RANGES = [
40827
+ "173.245.48.0/20",
40828
+ "103.21.244.0/22",
40829
+ "103.22.200.0/22",
40830
+ "103.31.4.0/22",
40831
+ "141.101.64.0/18",
40832
+ "108.162.192.0/18",
40833
+ "190.93.240.0/20",
40834
+ "188.114.96.0/20",
40835
+ "197.234.240.0/22",
40836
+ "198.41.128.0/17",
40837
+ "162.158.0.0/15",
40838
+ "104.16.0.0/13",
40839
+ "104.24.0.0/14",
40840
+ "172.64.0.0/13",
40841
+ "131.0.72.0/22",
40842
+ "2400:cb00::/32",
40843
+ "2606:4700::/32",
40844
+ "2803:f800::/32",
40845
+ "2405:b500::/32",
40846
+ "2405:8100::/32",
40847
+ "2a06:98c0::/29",
40848
+ "2c0f:f248::/32",
40849
+ "1.1.1.1/32",
40850
+ "1.0.0.1/32",
40851
+ "8.8.8.8/32",
40852
+ "8.8.4.4/32",
40853
+ "9.9.9.9/32",
40854
+ "149.112.112.112/32",
40855
+ "208.67.222.222/32",
40856
+ "208.67.220.220/32"
40857
+ ];
40858
+ var SHARED_DOMAINS = /* @__PURE__ */ new Set([
40859
+ "workers.dev",
40860
+ "pages.dev",
40861
+ "github.io",
40862
+ "githubusercontent.com",
40863
+ "herokuapp.com",
40864
+ "vercel.app",
40865
+ "netlify.app",
40866
+ "azurewebsites.net",
40867
+ "blob.core.windows.net",
40868
+ "amazonaws.com",
40869
+ "cloudfront.net",
40870
+ "googleusercontent.com",
40871
+ "appspot.com",
40872
+ "firebaseapp.com",
40873
+ "web.app",
40874
+ "r2.dev",
40875
+ "ngrok.io",
40876
+ "ngrok-free.app",
40877
+ "duckdns.org",
40878
+ "discord.com",
40879
+ "discordapp.com",
40880
+ "telegram.org",
40881
+ "dropbox.com",
40882
+ "google.com"
40883
+ ]);
40884
+ function parseThreatFoxJson(text, minConfidence) {
40885
+ const ips = /* @__PURE__ */ new Map();
40886
+ const domains = /* @__PURE__ */ new Map();
40887
+ const data = JSON.parse(text);
40888
+ for (const entries of Object.values(data)) {
40889
+ for (const ioc of Array.isArray(entries) ? entries : []) {
40890
+ const confidence = typeof ioc.confidence_level === "number" ? ioc.confidence_level : 0;
40891
+ if (confidence < minConfidence) continue;
40892
+ const value = String(ioc.ioc_value ?? "").trim();
40893
+ const ind = {
40894
+ malware: String(ioc.malware_printable ?? ioc.malware ?? "unknown"),
40895
+ threat: String(ioc.threat_type ?? "unknown"),
40896
+ feed: "threatfox"
40897
+ };
40898
+ if (ioc.ioc_type === "ip:port") {
40899
+ if (ind.threat !== "botnet_cc" && ind.threat !== "payload_delivery") continue;
40900
+ const ip = stripPort(value);
40901
+ if (ip) ips.set(ip, ind);
40902
+ } else if (ioc.ioc_type === "domain") {
40903
+ const domain = normalizeDomain(value);
40904
+ if (domain) domains.set(domain, ind);
40905
+ }
40906
+ }
40907
+ }
40908
+ return { ips, domains };
40909
+ }
40910
+ function parseHostfile(text, feed) {
40911
+ const out = /* @__PURE__ */ new Map();
40912
+ for (const line2 of text.split("\n")) {
40913
+ const trimmed = line2.trim();
40914
+ if (!trimmed || trimmed.startsWith("#")) continue;
40915
+ const domain = normalizeDomain(trimmed.split(/\s+/)[1] ?? "");
40916
+ if (domain) out.set(domain, { malware: "unknown", threat: "malware_host", feed });
40917
+ }
40918
+ return out;
40919
+ }
40920
+ function parseIpList(text, feed) {
40921
+ const out = /* @__PURE__ */ new Map();
40922
+ for (const line2 of text.split("\n")) {
40923
+ const ip = line2.trim();
40924
+ if (ip && !ip.startsWith("#") && (0, import_node_net5.isIP)(ip)) out.set(ip, { malware: "unknown", threat: "botnet_cc", feed });
40925
+ }
40926
+ return out;
40927
+ }
40928
+ function stripPort(value) {
40929
+ const v6 = /^\[([^\]]+)\]:\d+$/.exec(value);
40930
+ const ip = v6 ? v6[1] : value.replace(/:\d+$/, "");
40931
+ return (0, import_node_net5.isIP)(ip) ? ip : null;
40932
+ }
40933
+ function normalizeDomain(value) {
40934
+ const d = value.trim().toLowerCase().replace(/\.$/, "");
40935
+ if (!d || d === "localhost" || (0, import_node_net5.isIP)(d) || !/^[a-z0-9_.-]+\.[a-z0-9-]{2,}$/.test(d)) return null;
40936
+ return d;
40937
+ }
40938
+ function allowedDomain(domain, allow) {
40939
+ return allow.some((a) => domain === a || domain.endsWith(`.${a}`));
40940
+ }
40941
+ function buildFeedSet(parts, allow, sources, now = /* @__PURE__ */ new Date()) {
40942
+ const neverIps = [...DEFAULT_PROTECTED, ...SHARED_RANGES, ...allow.filter((a) => (0, import_node_net5.isIP)(a.split("/")[0]))];
40943
+ const allowDomains = allow.filter((a) => !(0, import_node_net5.isIP)(a.split("/")[0])).map((a) => a.toLowerCase());
40944
+ const ips = {};
40945
+ const domains = {};
40946
+ let skipped = 0;
40947
+ for (const part of parts) {
40948
+ for (const [ip, ind] of part.ips ?? []) {
40949
+ if (isProtected(ip, neverIps)) {
40950
+ skipped++;
40951
+ continue;
40952
+ }
40953
+ ips[ip] ??= ind;
40954
+ }
40955
+ for (const [domain, ind] of part.domains ?? []) {
40956
+ if (SHARED_DOMAINS.has(domain) || allowedDomain(domain, allowDomains)) {
40957
+ skipped++;
40958
+ continue;
40959
+ }
40960
+ domains[domain] ??= ind;
40961
+ }
40962
+ }
40963
+ return { fetched_at: now.toISOString(), ips, domains, sources, skipped_shared: skipped };
40964
+ }
40965
+ async function fetchFeeds(settings, fetchImpl = fetch) {
40966
+ const sources = [];
40967
+ const parts = [];
40968
+ const get = async (feed, url, parse3) => {
40969
+ try {
40970
+ const res = await fetchImpl(url, { signal: AbortSignal.timeout(6e4), headers: { "User-Agent": "threatcrush (+https://threatcrush.com)" } });
40971
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
40972
+ const part = parse3(await res.text());
40973
+ parts.push(part);
40974
+ sources.push({ feed, ok: true, count: (part.ips?.size ?? 0) + (part.domains?.size ?? 0) });
40975
+ } catch (err) {
40976
+ sources.push({ feed, ok: false, count: 0, error: err.message });
40977
+ }
40978
+ };
40979
+ await Promise.all([
40980
+ get("threatfox", FEEDS.threatfoxRecent, (t) => parseThreatFoxJson(t, settings.minConfidence)),
40981
+ get("threatfox-hosts", FEEDS.threatfoxHosts, (t) => ({ domains: parseHostfile(t, "threatfox") })),
40982
+ get("urlhaus-hosts", FEEDS.urlhausHosts, (t) => ({ domains: parseHostfile(t, "urlhaus") })),
40983
+ get("feodo", FEEDS.feodoIps, (t) => ({ ips: parseIpList(t, "feodo") }))
40984
+ ]);
40985
+ return buildFeedSet(parts, settings.allow, sources);
40986
+ }
40987
+ function readFeedCache(path) {
40988
+ try {
40989
+ const set = JSON.parse((0, import_node_fs27.readFileSync)(path, "utf-8"));
40990
+ return set && typeof set.ips === "object" && typeof set.domains === "object" ? set : null;
40991
+ } catch {
40992
+ return null;
40993
+ }
40994
+ }
40995
+ function writeFeedCache(path, set) {
40996
+ (0, import_node_fs27.mkdirSync)((0, import_node_path20.dirname)(path), { recursive: true });
40997
+ const tmp = `${path}.tmp`;
40998
+ (0, import_node_fs27.writeFileSync)(tmp, JSON.stringify(set));
40999
+ (0, import_node_fs27.renameSync)(tmp, path);
41000
+ }
41001
+ var active = null;
41002
+ function setActiveFeeds(set) {
41003
+ active = set;
41004
+ }
41005
+ function matchIp(ip, set = active) {
41006
+ if (!set) return null;
41007
+ const bare = ip.replace(/^::ffff:/i, "");
41008
+ return set.ips[bare] ?? null;
41009
+ }
41010
+ function matchDomain(name, set = active) {
41011
+ if (!set) return null;
41012
+ const labels = (normalizeDomain(name) ?? "").split(".");
41013
+ for (let i = 0; i < labels.length - 1; i++) {
41014
+ const candidate = labels.slice(i).join(".");
41015
+ const hit = set.domains[candidate];
41016
+ if (hit) return { domain: candidate, indicator: hit };
41017
+ }
41018
+ return null;
41019
+ }
41020
+
41021
+ // src/modules/dns-monitor/index.ts
40674
41022
  var DNS_LOG_SOURCES = [
40675
41023
  "/var/log/syslog",
40676
41024
  // systemd-resolved logs here
@@ -40715,6 +41063,8 @@ var DnsMonitor = class {
40715
41063
  // Tracking windows
40716
41064
  txtQueryCounts = /* @__PURE__ */ new Map();
40717
41065
  domainBuffer = [];
41066
+ /** Last threat-feed alert per domain and client. */
41067
+ feedAlerts = /* @__PURE__ */ new Map();
40718
41068
  // Config
40719
41069
  txtRateThreshold = 20;
40720
41070
  // TXT queries per source per window
@@ -40738,7 +41088,7 @@ var DnsMonitor = class {
40738
41088
  /** True if a systemd unit is loaded on this host (so we do not tail nothing). */
40739
41089
  unitExists(unit) {
40740
41090
  try {
40741
- const r = (0, import_node_child_process7.spawnSync)("systemctl", ["show", unit, "--property=LoadState", "--value"], {
41091
+ const r = (0, import_node_child_process8.spawnSync)("systemctl", ["show", unit, "--property=LoadState", "--value"], {
40742
41092
  encoding: "utf-8",
40743
41093
  stdio: ["ignore", "pipe", "ignore"],
40744
41094
  timeout: 3e3
@@ -40750,9 +41100,9 @@ var DnsMonitor = class {
40750
41100
  }
40751
41101
  start() {
40752
41102
  const sources = [...DNS_LOG_SOURCES, ...this.extraPaths].filter((p) => {
40753
- if (!(0, import_node_fs27.existsSync)(p)) return false;
41103
+ if (!(0, import_node_fs28.existsSync)(p)) return false;
40754
41104
  try {
40755
- (0, import_node_fs27.accessSync)(p, import_node_fs27.constants.R_OK);
41105
+ (0, import_node_fs28.accessSync)(p, import_node_fs28.constants.R_OK);
40756
41106
  return true;
40757
41107
  } catch {
40758
41108
  return false;
@@ -40811,7 +41161,7 @@ var DnsMonitor = class {
40811
41161
  /** Follow one systemd unit's journal, feeding its lines to the same parser. */
40812
41162
  tailJournalUnit(unit) {
40813
41163
  try {
40814
- const child = (0, import_node_child_process7.spawn)("journalctl", ["-u", unit, "-f", "-n", "0", "--output=cat"], {
41164
+ const child = (0, import_node_child_process8.spawn)("journalctl", ["-u", unit, "-f", "-n", "0", "--output=cat"], {
40815
41165
  stdio: ["ignore", "pipe", "ignore"]
40816
41166
  });
40817
41167
  if (!child.stdout) return;
@@ -40952,6 +41302,30 @@ var DnsMonitor = class {
40952
41302
  record(q) {
40953
41303
  this.domainBuffer.push(q);
40954
41304
  this.observed++;
41305
+ this.checkFeeds(q);
41306
+ }
41307
+ /**
41308
+ * A lookup of a domain on the abuse.ch lists (`threat-feeds`). The client
41309
+ * goes in details, never `source_ip`: it is whoever asked, and on a public
41310
+ * resolver that is an outside user auto-defence must not ban. Only a lookup
41311
+ * from this box or a private-range client (a container) is about us.
41312
+ */
41313
+ checkFeeds(q) {
41314
+ const hit = matchDomain(q.domain);
41315
+ if (!hit) return;
41316
+ const now = Date.now();
41317
+ const key = `${hit.domain}|${q.source_ip ?? ""}`;
41318
+ if (now - (this.feedAlerts.get(key) ?? 0) < 36e5) return;
41319
+ this.feedAlerts.set(key, now);
41320
+ if (this.feedAlerts.size > 1e4) this.feedAlerts.clear();
41321
+ const local = !q.source_ip || isProtected(q.source_ip, DEFAULT_PROTECTED);
41322
+ const { malware, threat, feed } = hit.indicator;
41323
+ this.emitEvent(
41324
+ local ? "critical" : "low",
41325
+ `DNS lookup of known ${malware === "unknown" ? "malware" : malware} ${threat === "botnet_cc" ? "C2" : "host"} ${q.domain}${q.source_ip ? ` by ${q.source_ip}` : ""}`,
41326
+ void 0,
41327
+ { rule_id: "threat-feed-dns", domain: q.domain, listed: hit.domain, client_ip: q.source_ip, qtype: q.type, malware, threat, feed }
41328
+ );
40955
41329
  }
40956
41330
  emitEvent(severity, message, sourceIp, details) {
40957
41331
  const event = {
@@ -41085,15 +41459,15 @@ var ModuleHost = class {
41085
41459
  }
41086
41460
  }
41087
41461
  async discoverAndStartInstalled() {
41088
- if (!(0, import_node_fs28.existsSync)(PATHS.moduleDir)) return;
41462
+ if (!(0, import_node_fs29.existsSync)(PATHS.moduleDir)) return;
41089
41463
  const configs = loadModuleConfigs(PATHS.confD);
41090
- const entries = (0, import_node_fs28.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
41464
+ const entries = (0, import_node_fs29.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
41091
41465
  for (const entry of entries) {
41092
41466
  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;
41467
+ const manifestPath = (0, import_node_path21.join)(PATHS.moduleDir, entry.name, "mod.toml");
41468
+ if (!(0, import_node_fs29.existsSync)(manifestPath)) continue;
41095
41469
  try {
41096
- const manifest = import_toml4.default.parse((0, import_node_fs28.readFileSync)(manifestPath, "utf-8"));
41470
+ const manifest = import_toml4.default.parse((0, import_node_fs29.readFileSync)(manifestPath, "utf-8"));
41097
41471
  const name = manifest.module?.name || entry.name;
41098
41472
  const defaults = manifest.module?.config?.defaults || {};
41099
41473
  const config = {
@@ -41107,7 +41481,7 @@ var ModuleHost = class {
41107
41481
  source: "installed",
41108
41482
  status: config.enabled === false ? "disabled" : "loaded",
41109
41483
  events: 0,
41110
- path: (0, import_node_path20.join)(PATHS.moduleDir, entry.name),
41484
+ path: (0, import_node_path21.join)(PATHS.moduleDir, entry.name),
41111
41485
  config
41112
41486
  };
41113
41487
  this.modules.set(name, hosted);
@@ -41122,7 +41496,7 @@ var ModuleHost = class {
41122
41496
  status: "error",
41123
41497
  events: 0,
41124
41498
  detail: `manifest load failed: ${String(err.message || err)}`,
41125
- path: (0, import_node_path20.join)(PATHS.moduleDir, entry.name)
41499
+ path: (0, import_node_path21.join)(PATHS.moduleDir, entry.name)
41126
41500
  });
41127
41501
  }
41128
41502
  }
@@ -41161,17 +41535,17 @@ var ModuleHost = class {
41161
41535
  }
41162
41536
  }
41163
41537
  installedEntrypoint(modulePath) {
41164
- const packageJson = (0, import_node_path20.join)(modulePath, "package.json");
41538
+ const packageJson = (0, import_node_path21.join)(modulePath, "package.json");
41165
41539
  const candidates = [];
41166
- if ((0, import_node_fs28.existsSync)(packageJson)) {
41540
+ if ((0, import_node_fs29.existsSync)(packageJson)) {
41167
41541
  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));
41542
+ const pkg = JSON.parse((0, import_node_fs29.readFileSync)(packageJson, "utf-8"));
41543
+ if (pkg.main) candidates.push((0, import_node_path21.join)(modulePath, pkg.main));
41170
41544
  } catch {
41171
41545
  }
41172
41546
  }
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;
41547
+ candidates.push((0, import_node_path21.join)(modulePath, "dist", "index.js"), (0, import_node_path21.join)(modulePath, "index.js"));
41548
+ return candidates.find((candidate) => (0, import_node_fs29.existsSync)(candidate)) || null;
41175
41549
  }
41176
41550
  isThreatCrushModule(value) {
41177
41551
  return Boolean(
@@ -41580,7 +41954,7 @@ init_cli_config();
41580
41954
 
41581
41955
  // src/core/cloud-events.ts
41582
41956
  var import_node_crypto6 = require("crypto");
41583
- var import_node_net4 = require("net");
41957
+ var import_node_net6 = require("net");
41584
41958
  init_cli_config();
41585
41959
  function currentLink() {
41586
41960
  if (!hasSession()) return null;
@@ -41638,7 +42012,7 @@ function detectionEvent(serverId, event) {
41638
42012
  title: title.slice(0, MAX_TITLE_CHARS) || event.module,
41639
42013
  rule_id: str2(rule_id) ?? event.module,
41640
42014
  description: str2(description),
41641
- source_ip: event.source_ip && (0, import_node_net4.isIP)(event.source_ip) ? event.source_ip : void 0,
42015
+ source_ip: event.source_ip && (0, import_node_net6.isIP)(event.source_ip) ? event.source_ip : void 0,
41642
42016
  username: str2(username) ?? str2(user),
41643
42017
  raw_metadata: trimMetadata({ module: event.module, category: event.category, ...rest }),
41644
42018
  detected_at: event.timestamp.toISOString()
@@ -41680,16 +42054,16 @@ function findingEvents(serverId, results, observedAt = /* @__PURE__ */ new Date(
41680
42054
  }
41681
42055
 
41682
42056
  // src/daemon/workers/cloud-spool.ts
41683
- var import_node_fs29 = require("fs");
42057
+ var import_node_fs30 = require("fs");
41684
42058
  var import_promises = require("fs/promises");
41685
- var import_node_path21 = require("path");
42059
+ var import_node_path22 = require("path");
41686
42060
  var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
41687
42061
  var CloudSpool = class {
41688
42062
  constructor(path, limits = DEFAULT_SPOOL_LIMITS) {
41689
42063
  this.path = path;
41690
42064
  this.limits = limits;
41691
42065
  try {
41692
- (0, import_node_fs29.mkdirSync)((0, import_node_path21.dirname)(path), { recursive: true });
42066
+ (0, import_node_fs30.mkdirSync)((0, import_node_path22.dirname)(path), { recursive: true });
41693
42067
  } catch {
41694
42068
  }
41695
42069
  this.load();
@@ -41758,7 +42132,7 @@ var CloudSpool = class {
41758
42132
  load() {
41759
42133
  let raw;
41760
42134
  try {
41761
- raw = (0, import_node_fs29.readFileSync)(this.path, "utf-8");
42135
+ raw = (0, import_node_fs30.readFileSync)(this.path, "utf-8");
41762
42136
  } catch {
41763
42137
  return;
41764
42138
  }
@@ -41996,144 +42370,15 @@ var CloudSync = class {
41996
42370
  };
41997
42371
 
41998
42372
  // src/daemon/workers/remediation-consumer.ts
41999
- var import_node_net7 = require("net");
42373
+ var import_node_net8 = require("net");
42000
42374
  init_cli_config();
42001
42375
 
42002
- // src/daemon/firewall/protected.ts
42003
- var import_node_child_process8 = require("child_process");
42004
- var import_node_net5 = require("net");
42005
- var DEFAULT_PROTECTED = [
42006
- "127.0.0.0/8",
42007
- "::1/128",
42008
- "10.0.0.0/8",
42009
- "172.16.0.0/12",
42010
- "192.168.0.0/16",
42011
- "169.254.0.0/16",
42012
- "fc00::/7",
42013
- "fe80::/10"
42014
- ];
42015
- function ipToBytes(ip) {
42016
- const version = (0, import_node_net5.isIP)(ip);
42017
- if (version === 4) return v4ToBytes(ip);
42018
- if (version === 6) return v6ToBytes(ip);
42019
- return null;
42020
- }
42021
- function v4ToBytes(ip) {
42022
- const parts = ip.split(".");
42023
- if (parts.length !== 4) return null;
42024
- const bytes = new Uint8Array(4);
42025
- for (let i = 0; i < 4; i++) {
42026
- const n = Number(parts[i]);
42027
- if (!Number.isInteger(n) || n < 0 || n > 255) return null;
42028
- bytes[i] = n;
42029
- }
42030
- return bytes;
42031
- }
42032
- function v6ToBytes(ip) {
42033
- const bare = ip.split("%")[0];
42034
- const [headText, tailText] = bare.split("::", 2);
42035
- const head = headText ? headText.split(":") : [];
42036
- const tail = tailText !== void 0 ? tailText ? tailText.split(":") : [] : null;
42037
- const groups = [];
42038
- const pushGroup = (group) => {
42039
- if (group.includes(".")) {
42040
- const v4 = v4ToBytes(group);
42041
- if (!v4) return false;
42042
- groups.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
42043
- return true;
42044
- }
42045
- if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return false;
42046
- groups.push(parseInt(group, 16));
42047
- return true;
42048
- };
42049
- for (const group of head) if (!pushGroup(group)) return null;
42050
- const headCount = groups.length;
42051
- if (tail === null) {
42052
- if (headCount !== 8) return null;
42053
- } else {
42054
- const tailGroups = [];
42055
- const saved = groups.length;
42056
- for (const group of tail) if (!pushGroup(group)) return null;
42057
- tailGroups.push(...groups.splice(saved));
42058
- const zeros = 8 - headCount - tailGroups.length;
42059
- if (zeros < 0) return null;
42060
- for (let i = 0; i < zeros; i++) groups.push(0);
42061
- groups.push(...tailGroups);
42062
- }
42063
- if (groups.length !== 8) return null;
42064
- const bytes = new Uint8Array(16);
42065
- for (let i = 0; i < 8; i++) {
42066
- bytes[i * 2] = groups[i] >> 8 & 255;
42067
- bytes[i * 2 + 1] = groups[i] & 255;
42068
- }
42069
- return bytes;
42070
- }
42071
- function ipMatches(ip, entry) {
42072
- const [network, prefixText] = entry.trim().split("/");
42073
- const target = ipToBytes(ip);
42074
- const base = ipToBytes(network);
42075
- if (!target || !base || target.length !== base.length) return false;
42076
- const bits2 = prefixText === void 0 ? base.length * 8 : Number(prefixText);
42077
- if (!Number.isInteger(bits2) || bits2 < 0 || bits2 > base.length * 8) return false;
42078
- const wholeBytes = Math.floor(bits2 / 8);
42079
- for (let i = 0; i < wholeBytes; i++) {
42080
- if (target[i] !== base[i]) return false;
42081
- }
42082
- const remainder = bits2 % 8;
42083
- if (remainder === 0) return true;
42084
- const mask = 255 << 8 - remainder & 255;
42085
- return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
42086
- }
42087
- function isProtected(ip, list) {
42088
- return list.some((entry) => ipMatches(ip, entry));
42089
- }
42090
- function currentSshClient(env2 = process.env) {
42091
- const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
42092
- if (!source) return null;
42093
- const ip = source.trim().split(/\s+/)[0];
42094
- return ip && (0, import_node_net5.isIP)(ip) ? ip : null;
42095
- }
42096
- function establishedSshPeers() {
42097
- const peers = /* @__PURE__ */ new Set();
42098
- try {
42099
- const out = (0, import_node_child_process8.execFileSync)("ss", ["-tnpH"], {
42100
- encoding: "utf-8",
42101
- stdio: ["ignore", "pipe", "ignore"],
42102
- timeout: 3e3
42103
- });
42104
- for (const line2 of out.split("\n")) {
42105
- if (!/users:\(\("sshd/.test(line2)) continue;
42106
- const parts = line2.trim().split(/\s+/);
42107
- const peer = parts[4];
42108
- if (!peer) continue;
42109
- const ip = peer.slice(0, peer.lastIndexOf(":")).replace(/^\[|\]$/g, "");
42110
- if (ip && (0, import_node_net5.isIP)(ip)) peers.add(ip);
42111
- }
42112
- } catch {
42113
- }
42114
- return [...peers];
42115
- }
42116
- function defaultGateways() {
42117
- const found = /* @__PURE__ */ new Set();
42118
- for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
42119
- try {
42120
- const out = (0, import_node_child_process8.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
42121
- for (const line2 of out.split("\n")) {
42122
- const match = line2.match(/\bvia\s+(\S+)/);
42123
- if (match && (0, import_node_net5.isIP)(match[1])) found.add(match[1]);
42124
- }
42125
- } catch {
42126
- }
42127
- }
42128
- return [...found];
42129
- }
42130
-
42131
42376
  // src/daemon/workers/allowlist-sync.ts
42132
- var import_node_net6 = require("net");
42377
+ var import_node_net7 = require("net");
42133
42378
  init_cli_config();
42134
42379
  function isAddressOrCidr(value) {
42135
42380
  const [network, prefix, extra] = value.split("/");
42136
- const family = (0, import_node_net6.isIP)(network);
42381
+ const family = (0, import_node_net7.isIP)(network);
42137
42382
  if (family === 0 || extra !== void 0) return false;
42138
42383
  if (prefix === void 0) return true;
42139
42384
  if (!/^\d{1,3}$/.test(prefix)) return false;
@@ -42176,13 +42421,13 @@ var AllowlistSync = class {
42176
42421
  const value = String(entry.value ?? "").trim();
42177
42422
  if (isAddressOrCidr(value)) wanted.add(value);
42178
42423
  }
42179
- const added = [];
42424
+ const added2 = [];
42180
42425
  const protectedNow = new Set(this.manager.getProtected());
42181
42426
  for (const value of wanted) {
42182
42427
  if (this.owned.has(value) || protectedNow.has(value)) continue;
42183
42428
  this.manager.addToAllowlist(value);
42184
42429
  this.owned.add(value);
42185
- added.push(value);
42430
+ added2.push(value);
42186
42431
  }
42187
42432
  const removed = [];
42188
42433
  for (const value of this.owned) {
@@ -42191,9 +42436,9 @@ var AllowlistSync = class {
42191
42436
  this.owned.delete(value);
42192
42437
  removed.push(value);
42193
42438
  }
42194
- if (added.length > 0 || removed.length > 0) {
42439
+ if (added2.length > 0 || removed.length > 0) {
42195
42440
  this.opts.log(
42196
- `[cloud] org allowlist: +${added.length} -${removed.length} (${[...added.map((v) => `+${v}`), ...removed.map((v) => `-${v}`)].slice(0, 10).join(" ")})`
42441
+ `[cloud] org allowlist: +${added2.length} -${removed.length} (${[...added2.map((v) => `+${v}`), ...removed.map((v) => `-${v}`)].slice(0, 10).join(" ")})`
42197
42442
  );
42198
42443
  }
42199
42444
  }
@@ -42282,7 +42527,7 @@ var RemediationConsumer = class {
42282
42527
  try {
42283
42528
  switch (action.action_type) {
42284
42529
  case "block": {
42285
- if ((0, import_node_net7.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
42530
+ if ((0, import_node_net8.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
42286
42531
  let ttlSeconds = this.manager.status().max_ban_seconds;
42287
42532
  if (action.expires_at) {
42288
42533
  const until = Date.parse(action.expires_at);
@@ -42301,7 +42546,7 @@ var RemediationConsumer = class {
42301
42546
  return { status: "executed", dry_run: result.entry?.dry_run === true, executed_at };
42302
42547
  }
42303
42548
  case "unblock": {
42304
- if ((0, import_node_net7.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
42549
+ if ((0, import_node_net8.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
42305
42550
  const wasBanned = this.manager.getBlocklist().some((b) => b.ip === target);
42306
42551
  const result = await this.manager.unban(target, {
42307
42552
  forget: true,
@@ -42346,8 +42591,8 @@ var RemediationConsumer = class {
42346
42591
 
42347
42592
  // src/daemon/workers/auto-update.ts
42348
42593
  var import_node_child_process9 = require("child_process");
42349
- var import_node_fs30 = require("fs");
42350
- var import_node_path22 = require("path");
42594
+ var import_node_fs31 = require("fs");
42595
+ var import_node_path23 = require("path");
42351
42596
  init_backoff();
42352
42597
  var PKG_NAME = "@profullstack/threatcrush";
42353
42598
  var REGISTRY = `https://registry.npmjs.org/${PKG_NAME}`;
@@ -42385,12 +42630,12 @@ function pickUpdate(doc, current, opts) {
42385
42630
  return { version: latest };
42386
42631
  }
42387
42632
  function installPlan(opts) {
42388
- const expected = `${import_node_path22.sep}lib${import_node_path22.sep}node_modules${import_node_path22.sep}@profullstack${import_node_path22.sep}threatcrush`;
42633
+ const expected = `${import_node_path23.sep}lib${import_node_path23.sep}node_modules${import_node_path23.sep}@profullstack${import_node_path23.sep}threatcrush`;
42389
42634
  if (!opts.pkgRoot.endsWith(expected)) {
42390
42635
  return { kind: "unsupported", reason: `not an npm global install (${opts.pkgRoot}); run \`threatcrush update\`` };
42391
42636
  }
42392
- const nodeBin = (0, import_node_path22.dirname)(opts.execPath);
42393
- const npm = (0, import_node_path22.join)(nodeBin, "npm");
42637
+ const nodeBin = (0, import_node_path23.dirname)(opts.execPath);
42638
+ const npm = (0, import_node_path23.join)(nodeBin, "npm");
42394
42639
  if (!opts.npmExists(npm)) return { kind: "unsupported", reason: `no npm beside ${opts.execPath}` };
42395
42640
  if (!opts.owner) return { kind: "unsupported", reason: `cannot tell who owns ${opts.pkgRoot}` };
42396
42641
  const npmArgs = [npm, "i", "-g", `${PKG_NAME}@${opts.version}`, "--no-fund", "--no-audit"];
@@ -42422,10 +42667,10 @@ function installPlan(opts) {
42422
42667
  }
42423
42668
  function ownerOf(path, passwd = "/etc/passwd") {
42424
42669
  try {
42425
- const st = (0, import_node_fs30.statSync)(path);
42670
+ const st = (0, import_node_fs31.statSync)(path);
42426
42671
  let home = st.uid === 0 ? "/root" : "";
42427
42672
  try {
42428
- for (const line2 of (0, import_node_fs30.readFileSync)(passwd, "utf8").split("\n")) {
42673
+ for (const line2 of (0, import_node_fs31.readFileSync)(passwd, "utf8").split("\n")) {
42429
42674
  const f = line2.split(":");
42430
42675
  if (Number(f[2]) === st.uid && f[5]) home = f[5];
42431
42676
  }
@@ -42530,7 +42775,7 @@ var AutoUpdate = class {
42530
42775
  uid: process.getuid?.() ?? -1,
42531
42776
  owner: ownerOf(this.opts.pkgRoot),
42532
42777
  underSystemd: this.opts.underSystemd ?? Boolean(process.env.INVOCATION_ID),
42533
- npmExists: import_node_fs30.existsSync
42778
+ npmExists: import_node_fs31.existsSync
42534
42779
  });
42535
42780
  if (plan.kind === "unsupported") return this.note(`${target} is available but cannot self-install: ${plan.reason}`);
42536
42781
  this.recordAttempt(target);
@@ -42565,7 +42810,7 @@ var AutoUpdate = class {
42565
42810
  }
42566
42811
  lastAttempt() {
42567
42812
  try {
42568
- const v = JSON.parse((0, import_node_fs30.readFileSync)(this.opts.statePath, "utf8"));
42813
+ const v = JSON.parse((0, import_node_fs31.readFileSync)(this.opts.statePath, "utf8"));
42569
42814
  return v.version && typeof v.at === "number" ? { version: v.version, at: v.at } : null;
42570
42815
  } catch {
42571
42816
  return null;
@@ -42573,13 +42818,588 @@ var AutoUpdate = class {
42573
42818
  }
42574
42819
  recordAttempt(version) {
42575
42820
  try {
42576
- (0, import_node_fs30.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
42821
+ (0, import_node_fs31.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
42577
42822
  } catch (err) {
42578
42823
  this.opts.log(`[update] could not record attempt: ${err.message}`);
42579
42824
  }
42580
42825
  }
42581
42826
  };
42582
42827
 
42828
+ // src/daemon/workers/threat-feeds.ts
42829
+ var import_node_child_process10 = require("child_process");
42830
+ var import_node_net9 = require("net");
42831
+ init_backoff();
42832
+ var EGRESS_TABLE = "threatcrush_egress";
42833
+ var DEFAULT_REFRESH_MS = 36e5;
42834
+ var POLL_MS2 = 15e3;
42835
+ var REALERT_MS = 36e5;
42836
+ function threatFeedSettings(section) {
42837
+ const refresh = parseDuration(section?.refresh);
42838
+ return {
42839
+ enabled: section?.enabled !== false,
42840
+ block: section?.block === true,
42841
+ // abuse.ch asks for no more than one fetch per 5 minutes; hourly is plenty.
42842
+ refreshMs: refresh ? Math.max(900, refresh) * 1e3 : DEFAULT_REFRESH_MS,
42843
+ minConfidence: typeof section?.min_confidence === "number" ? section.min_confidence : 75,
42844
+ allow: Array.isArray(section?.allow) ? section.allow.map(String) : []
42845
+ };
42846
+ }
42847
+ function egressRuleset(ips) {
42848
+ const v4 = ips.filter((ip) => (0, import_node_net9.isIP)(ip) === 4);
42849
+ const v6 = ips.filter((ip) => (0, import_node_net9.isIP)(ip) === 6);
42850
+ const set = (name, type, items) => ` set ${name} { type ${type};${items.length ? ` elements = { ${items.join(", ")} }` : ""} }`;
42851
+ const chain = (name, hook) => [
42852
+ ` chain ${name} {`,
42853
+ ` type filter hook ${hook} priority -1; policy accept;`,
42854
+ ` ip daddr @c2_v4 counter drop`,
42855
+ ` ip6 daddr @c2_v6 counter drop`,
42856
+ ` }`
42857
+ ].join("\n");
42858
+ return [
42859
+ `table inet ${EGRESS_TABLE}`,
42860
+ `delete table inet ${EGRESS_TABLE}`,
42861
+ `table inet ${EGRESS_TABLE} {`,
42862
+ set("c2_v4", "ipv4_addr", v4),
42863
+ set("c2_v6", "ipv6_addr", v6),
42864
+ chain("output", "output"),
42865
+ chain("forward", "forward"),
42866
+ `}`,
42867
+ ""
42868
+ ].join("\n");
42869
+ }
42870
+ function splitAddr(addr) {
42871
+ const m = /^\[?(.+?)\]?:(\d+|\*)$/.exec(addr);
42872
+ if (!m) return null;
42873
+ const ip = m[1].replace(/%.*$/, "").replace(/^::ffff:/i, "");
42874
+ return (0, import_node_net9.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
42875
+ }
42876
+ function parseSs(text) {
42877
+ const out = [];
42878
+ for (const line2 of text.split("\n")) {
42879
+ const cols = line2.trim().split(/\s+/);
42880
+ if (cols.length < 5) continue;
42881
+ const local = splitAddr(cols[3]);
42882
+ const peer = splitAddr(cols[4]);
42883
+ if (!local || !peer) continue;
42884
+ const proc = /users:\(\("([^"]+)",pid=(\d+)/.exec(line2);
42885
+ out.push({
42886
+ state: cols[0],
42887
+ localPort: local.port,
42888
+ peerIp: peer.ip,
42889
+ peerPort: peer.port,
42890
+ process: proc?.[1] ?? null,
42891
+ pid: proc ? Number(proc[2]) : null
42892
+ });
42893
+ }
42894
+ return out;
42895
+ }
42896
+ function parseListeningPorts(text) {
42897
+ const ports = /* @__PURE__ */ new Set();
42898
+ for (const line2 of text.split("\n")) {
42899
+ const cols = line2.trim().split(/\s+/);
42900
+ const local = cols.length >= 4 ? splitAddr(cols[3]) : null;
42901
+ if (local) ports.add(local.port);
42902
+ }
42903
+ return ports;
42904
+ }
42905
+ function defaultRun2(cmd, args, input) {
42906
+ const res = (0, import_node_child_process10.spawnSync)(cmd, args, { encoding: "utf-8", input, timeout: 15e3, stdio: ["pipe", "pipe", "pipe"] });
42907
+ return res.status === 0 ? res.stdout : null;
42908
+ }
42909
+ var ThreatFeeds = class {
42910
+ constructor(opts) {
42911
+ this.opts = opts;
42912
+ this.run = opts.run ?? defaultRun2;
42913
+ this.now = opts.now ?? Date.now;
42914
+ }
42915
+ opts;
42916
+ timers = [];
42917
+ set = null;
42918
+ alerted = /* @__PURE__ */ new Map();
42919
+ blocking = false;
42920
+ run;
42921
+ now;
42922
+ get wantsBlock() {
42923
+ return this.opts.settings.block && this.opts.enforcing;
42924
+ }
42925
+ start() {
42926
+ const { settings } = this.opts;
42927
+ if (!settings.enabled) {
42928
+ this.opts.log("[threat-feeds] disabled by [threat_feeds] enabled = false");
42929
+ this.removeBlocking();
42930
+ return;
42931
+ }
42932
+ if (settings.block && !this.opts.enforcing) {
42933
+ this.opts.log("[threat-feeds] block = true but remediation is in dry_run (or has no firewall): detecting only");
42934
+ }
42935
+ const cached = readFeedCache(this.opts.cachePath);
42936
+ if (cached) this.apply(cached, "cache");
42937
+ if (!this.wantsBlock) this.removeBlocking();
42938
+ const stale = !cached || this.now() - Date.parse(cached.fetched_at) > settings.refreshMs;
42939
+ const first = setTimeout(() => void this.refresh(), stale ? 1e4 : settings.refreshMs);
42940
+ first.unref?.();
42941
+ const every = setInterval(() => void this.refresh(), settings.refreshMs);
42942
+ every.unref?.();
42943
+ const poll = setInterval(() => this.pollConnections(), POLL_MS2);
42944
+ poll.unref?.();
42945
+ this.timers.push(first, every, poll);
42946
+ }
42947
+ stop() {
42948
+ for (const t of this.timers) clearInterval(t);
42949
+ this.timers = [];
42950
+ }
42951
+ async refresh() {
42952
+ try {
42953
+ const set = await fetchFeeds(this.opts.settings, this.opts.fetchImpl);
42954
+ const failed = set.sources.filter((s) => !s.ok);
42955
+ if (failed.length === set.sources.length) {
42956
+ this.opts.log(`[threat-feeds] refresh failed, keeping previous list: ${failed.map((s) => `${s.feed}: ${s.error}`).join("; ")}`);
42957
+ return;
42958
+ }
42959
+ for (const f of failed) this.opts.log(`[threat-feeds] ${f.feed} unavailable: ${f.error}`);
42960
+ try {
42961
+ writeFeedCache(this.opts.cachePath, set);
42962
+ } catch (err) {
42963
+ this.opts.log(`[threat-feeds] could not write cache: ${err.message}`);
42964
+ }
42965
+ this.apply(set, "refresh");
42966
+ } catch (err) {
42967
+ this.opts.log(`[threat-feeds] refresh failed: ${err.message}`);
42968
+ }
42969
+ }
42970
+ apply(set, from) {
42971
+ this.set = set;
42972
+ setActiveFeeds(set);
42973
+ const ips = Object.keys(set.ips);
42974
+ const domains = Object.keys(set.domains).length;
42975
+ let mode = "detecting";
42976
+ if (this.wantsBlock) {
42977
+ const ok = this.run("nft", ["-f", "-"], egressRuleset(ips)) !== null;
42978
+ this.blocking = ok;
42979
+ mode = ok ? "blocking egress" : "detecting (nft load failed)";
42980
+ }
42981
+ const detail = `${ips.length} IPs, ${domains} domains, ${mode}`;
42982
+ this.opts.log(`[threat-feeds] ${from === "cache" ? "loaded cached" : "refreshed"} list: ${detail} (${set.skipped_shared} shared/protected entries skipped)`);
42983
+ this.opts.bus.announceModule("threat-feeds", "running", detail);
42984
+ }
42985
+ removeBlocking() {
42986
+ if (this.run("nft", ["list", "table", "inet", EGRESS_TABLE]) !== null) {
42987
+ this.run("nft", ["delete", "table", "inet", EGRESS_TABLE]);
42988
+ this.opts.log(`[threat-feeds] removed egress table ${EGRESS_TABLE} (blocking is off)`);
42989
+ }
42990
+ this.blocking = false;
42991
+ }
42992
+ /** Outbound connections to listed IPs, one alert per IP and process per hour. */
42993
+ pollConnections() {
42994
+ if (!this.set || Object.keys(this.set.ips).length === 0) return;
42995
+ const conns = this.run("ss", ["-tnpH"]);
42996
+ if (conns === null) return;
42997
+ const listening = parseListeningPorts(this.run("ss", ["-ltnH"]) ?? "");
42998
+ const now = this.now();
42999
+ for (const c of parseSs(conns)) {
43000
+ if (listening.has(c.localPort)) continue;
43001
+ const ind = matchIp(c.peerIp, this.set);
43002
+ if (!ind) continue;
43003
+ const key = `${c.peerIp}|${c.process ?? "?"}`;
43004
+ if (now - (this.alerted.get(key) ?? 0) < REALERT_MS) continue;
43005
+ this.alerted.set(key, now);
43006
+ const who = c.process ? `${c.process} (pid ${c.pid})` : "an unknown process";
43007
+ const blocked = this.blocking ? " \u2014 blocked" : "";
43008
+ this.opts.bus.publish({
43009
+ timestamp: new Date(now),
43010
+ module: "threat-feeds",
43011
+ category: "network",
43012
+ severity: "critical",
43013
+ message: `Outbound connection to known ${ind.malware} ${ind.threat === "botnet_cc" ? "C2" : "malware host"} ${c.peerIp}:${c.peerPort} by ${who}${blocked}`,
43014
+ // No source_ip on purpose: the remote end is not an attacker to ban
43015
+ // inbound, so remediation has nothing to act on and the egress table
43016
+ // stays the only enforcement.
43017
+ details: {
43018
+ rule_id: "threat-feed-outbound",
43019
+ destination_ip: c.peerIp,
43020
+ destination_port: c.peerPort,
43021
+ state: c.state,
43022
+ process: c.process,
43023
+ pid: c.pid,
43024
+ malware: ind.malware,
43025
+ threat: ind.threat,
43026
+ feed: ind.feed,
43027
+ blocked: this.blocking
43028
+ }
43029
+ });
43030
+ }
43031
+ for (const [key, at] of this.alerted) if (now - at > REALERT_MS) this.alerted.delete(key);
43032
+ }
43033
+ };
43034
+
43035
+ // src/daemon/workers/privilege-watch.ts
43036
+ var import_node_fs32 = require("fs");
43037
+ var import_node_path24 = require("path");
43038
+ var import_node_child_process11 = require("child_process");
43039
+
43040
+ // src/core/privileges/index.ts
43041
+ var import_node_crypto7 = require("crypto");
43042
+ var ADMIN_GROUPS = ["sudo", "wheel", "admin"];
43043
+ function parseUsers(text) {
43044
+ const out = [];
43045
+ for (const line2 of text.split("\n")) {
43046
+ const f = line2.split(":");
43047
+ if (f.length < 7 || line2.startsWith("#")) continue;
43048
+ const uid = Number(f[2]);
43049
+ if (!f[0] || !Number.isInteger(uid)) continue;
43050
+ out.push({ name: f[0], uid, home: f[5], shell: f[6].trim() });
43051
+ }
43052
+ return out;
43053
+ }
43054
+ function parseAdminGroups(text) {
43055
+ const out = {};
43056
+ for (const line2 of text.split("\n")) {
43057
+ const f = line2.split(":");
43058
+ if (f.length < 4 || !ADMIN_GROUPS.includes(f[0])) continue;
43059
+ out[f[0]] = f[3].trim().split(",").map((m) => m.trim()).filter(Boolean).sort();
43060
+ }
43061
+ return out;
43062
+ }
43063
+ function canLogIn(user) {
43064
+ return !/(nologin|\/false|\/sync|\/shutdown|\/halt)$/.test(user.shell);
43065
+ }
43066
+ function sudoersRules(text) {
43067
+ const joined = text.replace(/\\\n/g, " ");
43068
+ const rules = [];
43069
+ for (const raw of joined.split("\n")) {
43070
+ const line2 = raw.trim();
43071
+ if (!line2) continue;
43072
+ if (line2.startsWith("#") && !/^#include(dir)?\s/.test(line2)) continue;
43073
+ rules.push(line2.replace(/\s+/g, " "));
43074
+ }
43075
+ return rules;
43076
+ }
43077
+ function sudoReadsIncluded(name) {
43078
+ return !name.endsWith("~") && !name.includes(".");
43079
+ }
43080
+ function keyFingerprint(blobBase64) {
43081
+ if (!/^[A-Za-z0-9+/]+=*$/.test(blobBase64)) return null;
43082
+ const digest = (0, import_node_crypto7.createHash)("sha256").update(Buffer.from(blobBase64, "base64")).digest("base64");
43083
+ return `SHA256:${digest.replace(/=+$/, "")}`;
43084
+ }
43085
+ function parseAuthorizedKeys(text) {
43086
+ const out = [];
43087
+ for (const raw of text.split("\n")) {
43088
+ const line2 = raw.trim();
43089
+ if (!line2 || line2.startsWith("#")) continue;
43090
+ const m = /(?:^|\s)((?:ssh|ecdsa|sk)-[\w@.-]+)\s+([A-Za-z0-9+/]+=*)(?:\s+(.*))?$/.exec(line2);
43091
+ if (!m) continue;
43092
+ const fingerprint = keyFingerprint(m[2]);
43093
+ if (fingerprint) out.push({ fingerprint, type: m[1], comment: (m[3] ?? "").trim() });
43094
+ }
43095
+ return out;
43096
+ }
43097
+ function takeSnapshot(io, now = /* @__PURE__ */ new Date()) {
43098
+ const unreadable = [];
43099
+ const read = (path) => {
43100
+ const text = io.readFile(path);
43101
+ if (text === null && io.exists(path)) unreadable.push(path);
43102
+ return text;
43103
+ };
43104
+ const users = parseUsers(read("/etc/passwd") ?? "");
43105
+ const snapshot = {
43106
+ taken_at: now.toISOString(),
43107
+ uid0: users.filter((a) => a.uid === 0).map((a) => a.name).sort(),
43108
+ admin_groups: parseAdminGroups(read("/etc/group") ?? ""),
43109
+ sudoers: {},
43110
+ keys: {},
43111
+ unreadable
43112
+ };
43113
+ const sudoersFiles = ["/etc/sudoers"];
43114
+ for (const name of (io.readDir("/etc/sudoers.d") ?? []).sort()) {
43115
+ if (sudoReadsIncluded(name)) sudoersFiles.push(`/etc/sudoers.d/${name}`);
43116
+ }
43117
+ for (const path of sudoersFiles) {
43118
+ const text = read(path);
43119
+ if (text !== null) snapshot.sudoers[path] = sudoersRules(text);
43120
+ }
43121
+ for (const user of users) {
43122
+ if (user.uid !== 0 && (!canLogIn(user) || !user.home || user.home === "/")) continue;
43123
+ const keys = {};
43124
+ for (const file of ["authorized_keys", "authorized_keys2"]) {
43125
+ const text = read(`${user.home.replace(/\/$/, "")}/.ssh/${file}`);
43126
+ for (const k of parseAuthorizedKeys(text ?? "")) keys[k.fingerprint] = { type: k.type, comment: k.comment };
43127
+ }
43128
+ if (Object.keys(keys).length > 0) snapshot.keys[user.name] = keys;
43129
+ }
43130
+ return snapshot;
43131
+ }
43132
+ var added = (before2, after) => after.filter((x) => !before2.includes(x));
43133
+ function diffSnapshots(prev, next) {
43134
+ const changes = [];
43135
+ for (const name of added(prev.uid0, next.uid0)) {
43136
+ changes.push({ severity: "critical", message: `New uid 0 account: ${name}`, details: { rule_id: "priv-uid0-added", account: name } });
43137
+ }
43138
+ for (const name of added(next.uid0, prev.uid0)) {
43139
+ changes.push({ severity: "low", message: `uid 0 account removed: ${name}`, details: { rule_id: "priv-uid0-removed", account: name } });
43140
+ }
43141
+ for (const group of /* @__PURE__ */ new Set([...Object.keys(prev.admin_groups), ...Object.keys(next.admin_groups)])) {
43142
+ const before2 = prev.admin_groups[group] ?? [];
43143
+ const after = next.admin_groups[group] ?? [];
43144
+ for (const m of added(before2, after)) {
43145
+ changes.push({ severity: "high", message: `${m} added to the ${group} group (can run anything as root)`, details: { rule_id: "priv-admin-group-added", group, account: m } });
43146
+ }
43147
+ for (const m of added(after, before2)) {
43148
+ changes.push({ severity: "low", message: `${m} removed from the ${group} group`, details: { rule_id: "priv-admin-group-removed", group, account: m } });
43149
+ }
43150
+ }
43151
+ for (const path of /* @__PURE__ */ new Set([...Object.keys(prev.sudoers), ...Object.keys(next.sudoers)])) {
43152
+ if (next.unreadable.includes(path) || prev.unreadable.includes(path)) continue;
43153
+ const before2 = prev.sudoers[path];
43154
+ const after = next.sudoers[path];
43155
+ if (!before2 && after) {
43156
+ changes.push({ severity: "high", message: `New sudoers file ${path}${after.length ? `: ${after.slice(0, 3).join(" | ")}` : ""}`, details: { rule_id: "priv-sudoers-added", path, rules: after.slice(0, 20) } });
43157
+ continue;
43158
+ }
43159
+ if (before2 && !after) {
43160
+ changes.push({ severity: "low", message: `Sudoers file removed: ${path}`, details: { rule_id: "priv-sudoers-removed", path } });
43161
+ continue;
43162
+ }
43163
+ const plus = added(before2 ?? [], after ?? []);
43164
+ const minus = added(after ?? [], before2 ?? []);
43165
+ if (plus.length) {
43166
+ changes.push({ severity: "high", message: `Sudoers rule added in ${path}: ${plus.slice(0, 3).join(" | ")}`, details: { rule_id: "priv-sudoers-changed", path, added: plus.slice(0, 20), removed: minus.slice(0, 20) } });
43167
+ } else if (minus.length) {
43168
+ changes.push({ severity: "low", message: `Sudoers rule removed in ${path}: ${minus.slice(0, 3).join(" | ")}`, details: { rule_id: "priv-sudoers-changed", path, removed: minus.slice(0, 20) } });
43169
+ }
43170
+ }
43171
+ for (const user of /* @__PURE__ */ new Set([...Object.keys(prev.keys), ...Object.keys(next.keys)])) {
43172
+ const before2 = prev.keys[user] ?? {};
43173
+ const after = next.keys[user] ?? {};
43174
+ for (const fp of Object.keys(after)) {
43175
+ if (before2[fp]) continue;
43176
+ const { type, comment } = after[fp];
43177
+ changes.push({
43178
+ severity: "high",
43179
+ message: `New SSH key for ${user}: ${type} ${fp}${comment ? ` (${comment})` : ""}`,
43180
+ details: { rule_id: "priv-authorized-key-added", account: user, fingerprint: fp, key_type: type, comment }
43181
+ });
43182
+ }
43183
+ for (const fp of Object.keys(before2)) {
43184
+ if (after[fp]) continue;
43185
+ changes.push({ severity: "low", message: `SSH key removed for ${user}: ${fp}`, details: { rule_id: "priv-authorized-key-removed", account: user, fingerprint: fp } });
43186
+ }
43187
+ }
43188
+ const rank = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
43189
+ return changes.sort((a, b) => rank[b.severity] - rank[a.severity]);
43190
+ }
43191
+ function parseSudoMessage(message) {
43192
+ const m = /^\s*(\S+)\s+:\s+(.*)$/.exec(message);
43193
+ if (!m) return null;
43194
+ const fields = {};
43195
+ let reason = "";
43196
+ for (const part of m[2].split(" ; ")) {
43197
+ const kv = /^([A-Z]+)=(.*)$/.exec(part.trim());
43198
+ if (kv) fields[kv[1]] = kv[2];
43199
+ else if (!reason) reason = part.trim();
43200
+ }
43201
+ if (!fields.COMMAND) return null;
43202
+ if (/incorrect password|authentication failure/i.test(reason)) return null;
43203
+ return {
43204
+ user: m[1],
43205
+ runas: fields.USER ?? "root",
43206
+ command: fields.COMMAND,
43207
+ tty: fields.TTY,
43208
+ pwd: fields.PWD,
43209
+ denied: /not allowed|not in the sudoers|NOT in sudoers|command not allowed/i.test(reason)
43210
+ };
43211
+ }
43212
+
43213
+ // src/daemon/workers/privilege-watch.ts
43214
+ function privilegeSettings(section) {
43215
+ return { enabled: section?.enabled !== false, geo: section?.geo !== false, pollMs: 6e4 };
43216
+ }
43217
+ var COUNTRY_NAMES = new Intl.DisplayNames(["en"], { type: "region" });
43218
+ function countryName(code) {
43219
+ try {
43220
+ return COUNTRY_NAMES.of(code) ?? code;
43221
+ } catch {
43222
+ return code;
43223
+ }
43224
+ }
43225
+ var fsIO = {
43226
+ readFile: (p) => {
43227
+ try {
43228
+ return (0, import_node_fs32.readFileSync)(p, "utf-8");
43229
+ } catch {
43230
+ return null;
43231
+ }
43232
+ },
43233
+ readDir: (p) => {
43234
+ try {
43235
+ return (0, import_node_fs32.readdirSync)(p);
43236
+ } catch {
43237
+ return null;
43238
+ }
43239
+ },
43240
+ exists: (p) => (0, import_node_fs32.existsSync)(p)
43241
+ };
43242
+ function readJson(path) {
43243
+ try {
43244
+ return JSON.parse((0, import_node_fs32.readFileSync)(path, "utf-8"));
43245
+ } catch {
43246
+ return null;
43247
+ }
43248
+ }
43249
+ function writeJson(path, value) {
43250
+ (0, import_node_fs32.mkdirSync)((0, import_node_path24.dirname)(path), { recursive: true });
43251
+ (0, import_node_fs32.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
43252
+ (0, import_node_fs32.renameSync)(`${path}.tmp`, path);
43253
+ }
43254
+ function defaultRun3(cmd, args) {
43255
+ const res = (0, import_node_child_process11.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 2e4, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
43256
+ return res.status === 0 ? res.stdout : null;
43257
+ }
43258
+ async function geolocateViaThreatcrush(ip, fetchImpl = fetch) {
43259
+ const res = await fetchImpl("https://threatcrush.com/api/geo", {
43260
+ method: "POST",
43261
+ headers: { "Content-Type": "application/json" },
43262
+ body: JSON.stringify({ ips: [ip] }),
43263
+ signal: AbortSignal.timeout(8e3)
43264
+ });
43265
+ if (!res.ok) return null;
43266
+ const body = await res.json();
43267
+ const code = body.results?.[ip]?.countryCode;
43268
+ return typeof code === "string" && /^[A-Z]{2}$/.test(code) ? { countryCode: code } : null;
43269
+ }
43270
+ var PrivilegeWatch = class {
43271
+ constructor(opts) {
43272
+ this.opts = opts;
43273
+ this.io = opts.io ?? fsIO;
43274
+ this.run = opts.run ?? defaultRun3;
43275
+ this.now = opts.now ?? (() => /* @__PURE__ */ new Date());
43276
+ }
43277
+ opts;
43278
+ timers = [];
43279
+ io;
43280
+ run;
43281
+ now;
43282
+ warnedUnreadable = false;
43283
+ onEvent = (event) => {
43284
+ void this.checkLogin(event);
43285
+ };
43286
+ start() {
43287
+ if (!this.opts.settings.enabled) {
43288
+ this.opts.log("[privileged] disabled by [privileged] enabled = false");
43289
+ return;
43290
+ }
43291
+ this.checkSnapshot();
43292
+ this.readSudoLedger();
43293
+ if (this.opts.settings.geo) this.opts.bus.on("event", this.onEvent);
43294
+ const timer = setInterval(() => {
43295
+ this.checkSnapshot();
43296
+ this.readSudoLedger();
43297
+ }, this.opts.settings.pollMs);
43298
+ timer.unref?.();
43299
+ this.timers.push(timer);
43300
+ }
43301
+ stop() {
43302
+ for (const t of this.timers) clearInterval(t);
43303
+ this.timers = [];
43304
+ this.opts.bus.off("event", this.onEvent);
43305
+ }
43306
+ emit(severity, message, details) {
43307
+ const event = { timestamp: this.now(), module: "privileged-access", category: "auth", severity, message, details };
43308
+ try {
43309
+ insertEvent(event);
43310
+ } catch {
43311
+ }
43312
+ this.opts.bus.publish(event);
43313
+ }
43314
+ checkSnapshot() {
43315
+ const next = takeSnapshot(this.io, this.now());
43316
+ if (next.unreadable.length && !this.warnedUnreadable) {
43317
+ this.warnedUnreadable = true;
43318
+ this.opts.log(`[privileged] cannot read ${next.unreadable.join(", ")}; run the daemon as root to watch them`);
43319
+ }
43320
+ const prev = readJson(this.opts.snapshotPath);
43321
+ if (!prev) {
43322
+ const keys = Object.values(next.keys).reduce((n, k) => n + Object.keys(k).length, 0);
43323
+ this.opts.log(`[privileged] baseline recorded: uid0 [${next.uid0.join(", ")}], ${Object.values(next.admin_groups).flat().length} admin-group member(s), ${Object.keys(next.sudoers).length} sudoers file(s), ${keys} authorized key(s)`);
43324
+ } else {
43325
+ for (const change of diffSnapshots(prev, next)) this.emit(change.severity, change.message, change.details);
43326
+ }
43327
+ try {
43328
+ writeJson(this.opts.snapshotPath, next);
43329
+ } catch (err) {
43330
+ this.opts.log(`[privileged] could not save snapshot: ${err.message}`);
43331
+ }
43332
+ }
43333
+ /**
43334
+ * New sudo records since the saved journal cursor. The first run only finds
43335
+ * the current end of the journal, so history from before the daemon is not
43336
+ * replayed as if it had just happened.
43337
+ */
43338
+ readSudoLedger() {
43339
+ const cursor = readJson(this.opts.cursorPath)?.cursor;
43340
+ const args = cursor ? ["-t", "sudo", "-o", "json", "--no-pager", `--after-cursor=${cursor}`] : ["-o", "json", "--no-pager", "-n", "0", "--show-cursor"];
43341
+ const out = this.run("journalctl", args);
43342
+ if (out === null) return;
43343
+ let last = cursor ?? /^-- cursor: (\S+)/m.exec(out)?.[1];
43344
+ for (const line2 of cursor ? out.split("\n") : []) {
43345
+ if (!line2.trim()) continue;
43346
+ let rec;
43347
+ try {
43348
+ rec = JSON.parse(line2);
43349
+ } catch {
43350
+ continue;
43351
+ }
43352
+ if (typeof rec.__CURSOR === "string") last = rec.__CURSOR;
43353
+ const entry = typeof rec.MESSAGE === "string" ? parseSudoMessage(rec.MESSAGE) : null;
43354
+ if (!entry) continue;
43355
+ this.emit(
43356
+ entry.denied ? "medium" : "info",
43357
+ entry.denied ? `sudo denied: ${entry.user} tried ${entry.command} as ${entry.runas}` : `sudo: ${entry.user} ran ${entry.command} as ${entry.runas}`,
43358
+ { rule_id: entry.denied ? "priv-sudo-denied" : "priv-sudo-command", account: entry.user, runas: entry.runas, command: entry.command, tty: entry.tty, pwd: entry.pwd }
43359
+ );
43360
+ }
43361
+ if (last && last !== cursor) {
43362
+ try {
43363
+ writeJson(this.opts.cursorPath, { cursor: last });
43364
+ } catch {
43365
+ }
43366
+ }
43367
+ }
43368
+ /** An accepted SSH login from a country new for that user. */
43369
+ async checkLogin(event) {
43370
+ if (event.module !== "ssh-guard" || !event.source_ip) return;
43371
+ const user = /SSH login accepted for (\S+)/.exec(event.message)?.[1];
43372
+ if (!user || user === "unknown" || isProtected(event.source_ip, DEFAULT_PROTECTED)) return;
43373
+ let geo = null;
43374
+ try {
43375
+ geo = await (this.opts.geolocate ?? geolocateViaThreatcrush)(event.source_ip);
43376
+ } catch (err) {
43377
+ this.opts.log(`[privileged] geolocation failed for ${event.source_ip}: ${err.message}`);
43378
+ }
43379
+ const country = geo?.countryCode;
43380
+ if (!country || !/^[A-Z]{2}$/.test(country)) return;
43381
+ const history = readJson(this.opts.loginsPath) ?? {};
43382
+ const seen = history[user] ?? {};
43383
+ const at = this.now().toISOString();
43384
+ const known = Object.keys(seen);
43385
+ if (known.length > 0 && !seen[country]) {
43386
+ this.emit("high", `SSH login for ${user} from a new country: ${countryName(country)}, ${event.source_ip}; seen before from ${known.join(", ")}`, {
43387
+ rule_id: "priv-login-new-country",
43388
+ account: user,
43389
+ login_ip: event.source_ip,
43390
+ country,
43391
+ known_countries: known
43392
+ });
43393
+ }
43394
+ seen[country] = { first: seen[country]?.first ?? at, last: at };
43395
+ history[user] = seen;
43396
+ try {
43397
+ writeJson(this.opts.loginsPath, history);
43398
+ } catch {
43399
+ }
43400
+ }
43401
+ };
43402
+
42583
43403
  // src/daemon/rules/engine.ts
42584
43404
  var MAX_WINDOW_ENTRIES = 1e3;
42585
43405
  function live(window) {
@@ -42741,8 +43561,8 @@ var RuleEngine = class {
42741
43561
  };
42742
43562
 
42743
43563
  // src/daemon/rules/loader.ts
42744
- var import_node_fs31 = require("fs");
42745
- var import_node_path23 = require("path");
43564
+ var import_node_fs33 = require("fs");
43565
+ var import_node_path25 = require("path");
42746
43566
 
42747
43567
  // src/daemon/rules/default-rules.ts
42748
43568
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -43143,11 +43963,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
43143
43963
  function loadAllRules(customDir) {
43144
43964
  const rules = [...DEFAULT_RULES];
43145
43965
  const dir = customDir || RULES_DIR;
43146
- if ((0, import_node_fs31.existsSync)(dir)) {
43147
- const files = (0, import_node_fs31.readdirSync)(dir).filter((f) => f.endsWith(".json"));
43966
+ if ((0, import_node_fs33.existsSync)(dir)) {
43967
+ const files = (0, import_node_fs33.readdirSync)(dir).filter((f) => f.endsWith(".json"));
43148
43968
  for (const file of files) {
43149
43969
  try {
43150
- const raw = (0, import_node_fs31.readFileSync)((0, import_node_path23.join)(dir, file), "utf-8");
43970
+ const raw = (0, import_node_fs33.readFileSync)((0, import_node_path25.join)(dir, file), "utf-8");
43151
43971
  const parsed = JSON.parse(raw);
43152
43972
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
43153
43973
  for (const rule of customRules) {
@@ -43178,24 +43998,24 @@ function loadAllRules(customDir) {
43178
43998
  }
43179
43999
 
43180
44000
  // src/daemon/firewall/adapters.ts
43181
- var import_node_child_process10 = require("child_process");
43182
- var import_node_fs32 = require("fs");
43183
- var import_node_path24 = require("path");
43184
- var import_node_net8 = require("net");
44001
+ var import_node_child_process12 = require("child_process");
44002
+ var import_node_fs34 = require("fs");
44003
+ var import_node_path26 = require("path");
44004
+ var import_node_net10 = require("net");
43185
44005
  function assertValidFirewallIp(ip) {
43186
- if ((0, import_node_net8.isIP)(ip) !== 4) {
44006
+ if ((0, import_node_net10.isIP)(ip) !== 4) {
43187
44007
  throw new Error(`Invalid IPv4 address: ${ip}`);
43188
44008
  }
43189
44009
  }
43190
44010
  function assertBannableIp(ip) {
43191
- if ((0, import_node_net8.isIP)(ip) === 0) {
44011
+ if ((0, import_node_net10.isIP)(ip) === 0) {
43192
44012
  throw new Error(`Invalid IP address: ${ip}`);
43193
44013
  }
43194
44014
  }
43195
44015
  function writeIfAbsent(path, contents) {
43196
- (0, import_node_fs32.mkdirSync)((0, import_node_path24.dirname)(path), { recursive: true });
44016
+ (0, import_node_fs34.mkdirSync)((0, import_node_path26.dirname)(path), { recursive: true });
43197
44017
  try {
43198
- (0, import_node_fs32.writeFileSync)(path, contents, { flag: "wx" });
44018
+ (0, import_node_fs34.writeFileSync)(path, contents, { flag: "wx" });
43199
44019
  } catch (err) {
43200
44020
  if (err.code !== "EEXIST") throw err;
43201
44021
  }
@@ -43214,11 +44034,11 @@ var Fail2banAdapter = class {
43214
44034
  enforces = true;
43215
44035
  jailReady = false;
43216
44036
  isAvailable() {
43217
- const result = (0, import_node_child_process10.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
44037
+ const result = (0, import_node_child_process12.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
43218
44038
  return result.status === 0;
43219
44039
  }
43220
44040
  client(args) {
43221
- return (0, import_node_child_process10.execFileSync)("fail2ban-client", args, {
44041
+ return (0, import_node_child_process12.execFileSync)("fail2ban-client", args, {
43222
44042
  encoding: "utf-8",
43223
44043
  stdio: ["ignore", "pipe", "pipe"]
43224
44044
  });
@@ -43294,7 +44114,7 @@ var Fail2banAdapter = class {
43294
44114
  const status = this.client(["status", this.jail]);
43295
44115
  const line2 = status.split("\n").find((l) => /Banned IP list:/i.test(l));
43296
44116
  if (!line2) return [];
43297
- return line2.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net8.isIP)(s) !== 0);
44117
+ return line2.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net10.isIP)(s) !== 0);
43298
44118
  } catch {
43299
44119
  return [];
43300
44120
  }
@@ -43304,45 +44124,45 @@ var Fail2banAdapter = class {
43304
44124
  function parseBannedList(output) {
43305
44125
  const found = [];
43306
44126
  for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
43307
- if ((0, import_node_net8.isIP)(match[1]) !== 0) found.push(match[1]);
44127
+ if ((0, import_node_net10.isIP)(match[1]) !== 0) found.push(match[1]);
43308
44128
  }
43309
44129
  if (found.length > 0) return found;
43310
- return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net8.isIP)(s) !== 0);
44130
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net10.isIP)(s) !== 0);
43311
44131
  }
43312
44132
  var NftablesAdapter = class {
43313
44133
  name = "nftables";
43314
44134
  table = "threatcrush";
43315
44135
  set = "blocklist";
43316
44136
  isAvailable() {
43317
- const result = (0, import_node_child_process10.spawnSync)("nft", ["--version"], { stdio: "pipe" });
44137
+ const result = (0, import_node_child_process12.spawnSync)("nft", ["--version"], { stdio: "pipe" });
43318
44138
  return result.status === 0;
43319
44139
  }
43320
44140
  ensureSetup() {
43321
44141
  try {
43322
- (0, import_node_child_process10.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
44142
+ (0, import_node_child_process12.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
43323
44143
  } catch {
43324
- (0, import_node_child_process10.execSync)(`nft add table inet ${this.table}`);
43325
- (0, import_node_child_process10.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
43326
- (0, import_node_child_process10.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
43327
- (0, import_node_child_process10.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
44144
+ (0, import_node_child_process12.execSync)(`nft add table inet ${this.table}`);
44145
+ (0, import_node_child_process12.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
44146
+ (0, import_node_child_process12.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
44147
+ (0, import_node_child_process12.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
43328
44148
  }
43329
44149
  }
43330
44150
  async block(ip) {
43331
44151
  assertValidFirewallIp(ip);
43332
44152
  this.ensureSetup();
43333
- (0, import_node_child_process10.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
44153
+ (0, import_node_child_process12.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
43334
44154
  }
43335
44155
  async unblock(ip) {
43336
44156
  assertValidFirewallIp(ip);
43337
44157
  try {
43338
- (0, import_node_child_process10.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
44158
+ (0, import_node_child_process12.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
43339
44159
  } catch {
43340
44160
  }
43341
44161
  }
43342
44162
  async isBlocked(ip) {
43343
44163
  assertValidFirewallIp(ip);
43344
44164
  try {
43345
- const output = (0, import_node_child_process10.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
44165
+ const output = (0, import_node_child_process12.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
43346
44166
  return output.includes(ip);
43347
44167
  } catch {
43348
44168
  return false;
@@ -43350,7 +44170,7 @@ var NftablesAdapter = class {
43350
44170
  }
43351
44171
  async listBlocked() {
43352
44172
  try {
43353
- const output = (0, import_node_child_process10.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
44173
+ const output = (0, import_node_child_process12.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
43354
44174
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
43355
44175
  if (!match) return [];
43356
44176
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -43363,34 +44183,34 @@ var IptablesAdapter = class {
43363
44183
  name = "iptables";
43364
44184
  chain = "THREATCRUSH";
43365
44185
  isAvailable() {
43366
- const result = (0, import_node_child_process10.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
44186
+ const result = (0, import_node_child_process12.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
43367
44187
  return result.status === 0;
43368
44188
  }
43369
44189
  ensureChain() {
43370
44190
  try {
43371
- (0, import_node_child_process10.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
44191
+ (0, import_node_child_process12.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
43372
44192
  } catch {
43373
- (0, import_node_child_process10.execSync)(`iptables -N ${this.chain}`);
43374
- (0, import_node_child_process10.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
44193
+ (0, import_node_child_process12.execSync)(`iptables -N ${this.chain}`);
44194
+ (0, import_node_child_process12.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
43375
44195
  }
43376
44196
  }
43377
44197
  async block(ip) {
43378
44198
  assertValidFirewallIp(ip);
43379
44199
  this.ensureChain();
43380
44200
  if (await this.isBlocked(ip)) return;
43381
- (0, import_node_child_process10.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
44201
+ (0, import_node_child_process12.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
43382
44202
  }
43383
44203
  async unblock(ip) {
43384
44204
  assertValidFirewallIp(ip);
43385
44205
  try {
43386
- (0, import_node_child_process10.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
44206
+ (0, import_node_child_process12.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
43387
44207
  } catch {
43388
44208
  }
43389
44209
  }
43390
44210
  async isBlocked(ip) {
43391
44211
  assertValidFirewallIp(ip);
43392
44212
  try {
43393
- const output = (0, import_node_child_process10.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
44213
+ const output = (0, import_node_child_process12.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
43394
44214
  return output.includes(ip);
43395
44215
  } catch {
43396
44216
  return false;
@@ -43398,7 +44218,7 @@ var IptablesAdapter = class {
43398
44218
  }
43399
44219
  async listBlocked() {
43400
44220
  try {
43401
- const output = (0, import_node_child_process10.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
44221
+ const output = (0, import_node_child_process12.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
43402
44222
  const ips = [];
43403
44223
  for (const line2 of output.split("\n")) {
43404
44224
  const match = line2.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -43454,8 +44274,8 @@ function detectFirewallAdapter(backend = "auto") {
43454
44274
  }
43455
44275
 
43456
44276
  // src/daemon/firewall/remediation.ts
43457
- var import_node_fs33 = require("fs");
43458
- var import_node_net9 = require("net");
44277
+ var import_node_fs35 = require("fs");
44278
+ var import_node_net11 = require("net");
43459
44279
  init_paths();
43460
44280
  init_backoff();
43461
44281
 
@@ -43592,7 +44412,7 @@ var RemediationManager = class {
43592
44412
  if (remediation?.action !== "block") return;
43593
44413
  }
43594
44414
  const ip = event.source_ip;
43595
- if (!ip || (0, import_node_net9.isIP)(ip) === 0) return;
44415
+ if (!ip || (0, import_node_net11.isIP)(ip) === 0) return;
43596
44416
  if (this.isAllowlisted(ip)) return;
43597
44417
  if (this.blocklist.some((b) => b.ip === ip)) return;
43598
44418
  if (this.config.spare_verified_crawlers) {
@@ -43611,7 +44431,7 @@ var RemediationManager = class {
43611
44431
  * 4th offence and so on, clamped to `max_ban_seconds`.
43612
44432
  */
43613
44433
  async ban(ip, reason, opts = {}) {
43614
- if ((0, import_node_net9.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
44434
+ if ((0, import_node_net11.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
43615
44435
  if (this.isAllowlisted(ip)) {
43616
44436
  return { ok: false, error: `${ip} is protected and can never be blocked` };
43617
44437
  }
@@ -43868,7 +44688,7 @@ var RemediationManager = class {
43868
44688
  }
43869
44689
  logLine(line2) {
43870
44690
  try {
43871
- (0, import_node_fs33.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
44691
+ (0, import_node_fs35.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
43872
44692
  `);
43873
44693
  } catch {
43874
44694
  }
@@ -43906,19 +44726,19 @@ function remediationSettings(section) {
43906
44726
  init_backoff();
43907
44727
 
43908
44728
  // src/daemon/watchdog-service.ts
43909
- var import_node_fs34 = require("fs");
43910
- var import_node_path25 = require("path");
44729
+ var import_node_fs36 = require("fs");
44730
+ var import_node_path27 = require("path");
43911
44731
  function defaultShareGid() {
43912
44732
  const isRoot4 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
43913
44733
  if (!isRoot4) return void 0;
43914
44734
  try {
43915
- return (0, import_node_fs34.statSync)("/var/log/auth.log").gid;
44735
+ return (0, import_node_fs36.statSync)("/var/log/auth.log").gid;
43916
44736
  } catch {
43917
44737
  return void 0;
43918
44738
  }
43919
44739
  }
43920
44740
  function startWatchdog(opts) {
43921
- const dir = opts.config?.dir ?? (0, import_node_path25.join)(opts.stateDir, WATCHDOG_DIRNAME);
44741
+ const dir = opts.config?.dir ?? (0, import_node_path27.join)(opts.stateDir, WATCHDOG_DIRNAME);
43922
44742
  const base = { dir, logged: 0, answered: 0, errored: 0 };
43923
44743
  if (opts.config?.enabled === false) {
43924
44744
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -44012,7 +44832,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
44012
44832
  }
44013
44833
 
44014
44834
  // src/core/node-runtime.ts
44015
- var import_node_child_process11 = require("child_process");
44835
+ var import_node_child_process13 = require("child_process");
44016
44836
  var MIN_DAEMON_NODE_MAJOR = 22;
44017
44837
  function nodeMajor(version) {
44018
44838
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -44026,23 +44846,23 @@ function daemonNodeProblem(version) {
44026
44846
  }
44027
44847
  function versionOfNode(path) {
44028
44848
  if (path === process.execPath) return process.versions.node;
44029
- const res = (0, import_node_child_process11.spawnSync)(path, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
44849
+ const res = (0, import_node_child_process13.spawnSync)(path, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
44030
44850
  return res.status === 0 ? res.stdout.trim() : null;
44031
44851
  }
44032
44852
 
44033
44853
  // src/daemon/index.ts
44034
44854
  function readVersion2() {
44035
44855
  try {
44036
- const pkg = JSON.parse((0, import_node_fs35.readFileSync)((0, import_node_path26.join)(__dirname, "..", "package.json"), "utf-8"));
44856
+ const pkg = JSON.parse((0, import_node_fs37.readFileSync)((0, import_node_path28.join)(__dirname, "..", "package.json"), "utf-8"));
44037
44857
  return pkg.version || "0.0.0";
44038
44858
  } catch {
44039
44859
  return "0.0.0";
44040
44860
  }
44041
44861
  }
44042
44862
  async function runHardeningChecks() {
44043
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process12.execFile)(
44863
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process14.execFile)(
44044
44864
  process.execPath,
44045
- [(0, import_node_path26.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
44865
+ [(0, import_node_path28.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
44046
44866
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
44047
44867
  );
44048
44868
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -44054,9 +44874,9 @@ async function runHardeningChecks() {
44054
44874
  return patches ? [...findings, patches] : findings;
44055
44875
  }
44056
44876
  async function runPatchCheck() {
44057
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process12.execFile)(
44877
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process14.execFile)(
44058
44878
  process.execPath,
44059
- [(0, import_node_path26.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
44879
+ [(0, import_node_path28.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
44060
44880
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
44061
44881
  );
44062
44882
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -44064,7 +44884,7 @@ async function runPatchCheck() {
44064
44884
  }
44065
44885
  function logLine(line2) {
44066
44886
  try {
44067
- (0, import_node_fs35.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
44887
+ (0, import_node_fs37.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
44068
44888
  `);
44069
44889
  } catch {
44070
44890
  }
@@ -44089,9 +44909,9 @@ async function runDaemon() {
44089
44909
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
44090
44910
  const restartDaemon = () => {
44091
44911
  if (PATHS.mode === "system") {
44092
- (0, import_node_child_process12.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
44912
+ (0, import_node_child_process14.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
44093
44913
  } else {
44094
- (0, import_node_child_process12.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
44914
+ (0, import_node_child_process14.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
44095
44915
  setTimeout(() => process.exit(0), 500).unref();
44096
44916
  }
44097
44917
  };
@@ -44106,7 +44926,7 @@ async function runDaemon() {
44106
44926
  } catch (err) {
44107
44927
  logLine(`[daemon] state db unavailable: ${err.message}`);
44108
44928
  }
44109
- const config = loadConfig((0, import_node_fs35.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
44929
+ const config = loadConfig((0, import_node_fs37.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
44110
44930
  configureAttackDetection(config.detection);
44111
44931
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
44112
44932
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -44166,6 +44986,24 @@ async function runDaemon() {
44166
44986
  if (firewallAdapter.enforces === false) {
44167
44987
  logLine("[daemon] no manageable firewall found (need fail2ban, nftables or iptables) \u2014 bans are simulated");
44168
44988
  }
44989
+ const feedSettings = threatFeedSettings(config.threat_feeds);
44990
+ const threatFeeds = new ThreatFeeds({
44991
+ settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
44992
+ enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
44993
+ cachePath: (0, import_node_path28.join)(PATHS.stateDir, "threat-feeds.json"),
44994
+ bus,
44995
+ log: logLine
44996
+ });
44997
+ threatFeeds.start();
44998
+ const privilegeWatch = new PrivilegeWatch({
44999
+ settings: privilegeSettings(config.privileged),
45000
+ bus,
45001
+ snapshotPath: (0, import_node_path28.join)(PATHS.stateDir, "privileges.json"),
45002
+ loginsPath: (0, import_node_path28.join)(PATHS.stateDir, "login-countries.json"),
45003
+ cursorPath: (0, import_node_path28.join)(PATHS.stateDir, "sudo-cursor.json"),
45004
+ log: logLine
45005
+ });
45006
+ privilegeWatch.start();
44169
45007
  new AlertDispatcher(bus, config);
44170
45008
  const runsWorker = new RunsWorker(bus);
44171
45009
  try {
@@ -44185,7 +45023,7 @@ async function runDaemon() {
44185
45023
  version,
44186
45024
  hostname: (0, import_node_os11.hostname)(),
44187
45025
  minSeverity,
44188
- spoolPath: (0, import_node_path26.join)(PATHS.stateDir, "cloud-spool.jsonl"),
45026
+ spoolPath: (0, import_node_path28.join)(PATHS.stateDir, "cloud-spool.jsonl"),
44189
45027
  log: logLine,
44190
45028
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
44191
45029
  runHardening: runHardeningChecks
@@ -44202,8 +45040,8 @@ async function runDaemon() {
44202
45040
  const autoUpdate = new AutoUpdate({
44203
45041
  version,
44204
45042
  settings: updateSettings(config.update),
44205
- pkgRoot: (0, import_node_path26.join)(__dirname, ".."),
44206
- statePath: (0, import_node_path26.join)(PATHS.stateDir, "auto-update.json"),
45043
+ pkgRoot: (0, import_node_path28.join)(__dirname, ".."),
45044
+ statePath: (0, import_node_path28.join)(PATHS.stateDir, "auto-update.json"),
44207
45045
  bus,
44208
45046
  log: logLine,
44209
45047
  restartDaemon
@@ -44246,6 +45084,14 @@ async function runDaemon() {
44246
45084
  autoUpdate.stop();
44247
45085
  } catch {
44248
45086
  }
45087
+ try {
45088
+ threatFeeds.stop();
45089
+ } catch {
45090
+ }
45091
+ try {
45092
+ privilegeWatch.stop();
45093
+ } catch {
45094
+ }
44249
45095
  try {
44250
45096
  await ipc.stop();
44251
45097
  } catch {
@@ -44281,7 +45127,7 @@ var SYSTEM_SOCKET = "/var/run/threatcrush/threatcrushd.sock";
44281
45127
  function isRoot2() {
44282
45128
  return typeof process.getuid === "function" && process.getuid() === 0;
44283
45129
  }
44284
- var DAEMON_ENTRY = (0, import_node_path27.join)(__dirname, "daemon.js");
45130
+ var DAEMON_ENTRY = (0, import_node_path29.join)(__dirname, "daemon.js");
44285
45131
  async function daemonForeground() {
44286
45132
  await runDaemon();
44287
45133
  }
@@ -44302,7 +45148,7 @@ async function daemonStart() {
44302
45148
  return;
44303
45149
  }
44304
45150
  ensureRuntimeDirs();
44305
- if (!(0, import_node_fs36.existsSync)(DAEMON_ENTRY)) {
45151
+ if (!(0, import_node_fs38.existsSync)(DAEMON_ENTRY)) {
44306
45152
  console.log(source_default.red(` Daemon entry not found at ${DAEMON_ENTRY}.`));
44307
45153
  console.log(source_default.dim(" Reinstall with `threatcrush update` or `pnpm run build` in the cli package."));
44308
45154
  return;
@@ -44310,8 +45156,8 @@ async function daemonStart() {
44310
45156
  let out;
44311
45157
  let err;
44312
45158
  try {
44313
- out = (0, import_node_fs37.openSync)(PATHS.logFile, "a");
44314
- err = (0, import_node_fs37.openSync)(PATHS.logFile, "a");
45159
+ out = (0, import_node_fs39.openSync)(PATHS.logFile, "a");
45160
+ err = (0, import_node_fs39.openSync)(PATHS.logFile, "a");
44315
45161
  } catch (e) {
44316
45162
  const code = e.code;
44317
45163
  console.log(source_default.red(` \u2717 Cannot write daemon log at ${PATHS.logFile} (${code ?? "error"}).`));
@@ -44324,7 +45170,7 @@ async function daemonStart() {
44324
45170
  }
44325
45171
  return;
44326
45172
  }
44327
- const child = (0, import_node_child_process13.spawn)(process.execPath, [DAEMON_ENTRY], {
45173
+ const child = (0, import_node_child_process15.spawn)(process.execPath, [DAEMON_ENTRY], {
44328
45174
  detached: true,
44329
45175
  stdio: ["ignore", out, err],
44330
45176
  env: { ...process.env, THREATCRUSH_DAEMON: "1" }
@@ -44399,41 +45245,41 @@ async function waitForExit(pid, timeoutMs) {
44399
45245
  }
44400
45246
  async function releaseStaleSocket() {
44401
45247
  const deadline = Date.now() + 2e3;
44402
- while ((0, import_node_fs36.existsSync)(PATHS.socket) && Date.now() < deadline) {
45248
+ while ((0, import_node_fs38.existsSync)(PATHS.socket) && Date.now() < deadline) {
44403
45249
  await new Promise((r) => setTimeout(r, 50));
44404
45250
  }
44405
- if ((0, import_node_fs36.existsSync)(PATHS.socket)) {
45251
+ if ((0, import_node_fs38.existsSync)(PATHS.socket)) {
44406
45252
  try {
44407
- (0, import_node_fs36.unlinkSync)(PATHS.socket);
45253
+ (0, import_node_fs38.unlinkSync)(PATHS.socket);
44408
45254
  } catch {
44409
45255
  }
44410
45256
  }
44411
45257
  }
44412
45258
 
44413
45259
  // src/commands/service.ts
44414
- var import_node_child_process14 = require("child_process");
44415
- var import_node_fs38 = require("fs");
44416
- var import_node_path28 = require("path");
45260
+ var import_node_child_process16 = require("child_process");
45261
+ var import_node_fs40 = require("fs");
45262
+ var import_node_path30 = require("path");
44417
45263
  var import_node_os12 = require("os");
44418
45264
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
44419
45265
  var DAEMON_UNIT_NAME = "threatcrushd.service";
44420
45266
  function resolveTemplate() {
44421
- const templatePath = (0, import_node_path28.join)(__dirname, "systemd", "threatcrushd.service");
44422
- if (!(0, import_node_fs38.existsSync)(templatePath)) {
45267
+ const templatePath = (0, import_node_path30.join)(__dirname, "systemd", "threatcrushd.service");
45268
+ if (!(0, import_node_fs40.existsSync)(templatePath)) {
44423
45269
  throw new Error(`systemd unit template not found at ${templatePath}`);
44424
45270
  }
44425
- return (0, import_node_fs38.readFileSync)(templatePath, "utf-8");
45271
+ return (0, import_node_fs40.readFileSync)(templatePath, "utf-8");
44426
45272
  }
44427
45273
  function stableBinPath(binPath) {
44428
45274
  const stable = binPath.replace(/\/\.pnpm\/[^/]+\/node_modules\//, "/node_modules/");
44429
45275
  if (stable === binPath) return binPath;
44430
- return (0, import_node_fs38.existsSync)(stable) ? stable : binPath;
45276
+ return (0, import_node_fs40.existsSync)(stable) ? stable : binPath;
44431
45277
  }
44432
45278
  function resolveBinPath() {
44433
45279
  const arg = process.argv[1];
44434
- if (arg && (0, import_node_fs38.existsSync)(arg)) return stableBinPath(arg);
45280
+ if (arg && (0, import_node_fs40.existsSync)(arg)) return stableBinPath(arg);
44435
45281
  try {
44436
- return (0, import_node_child_process14.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
45282
+ return (0, import_node_child_process16.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
44437
45283
  } catch {
44438
45284
  return "threatcrush";
44439
45285
  }
@@ -44441,11 +45287,11 @@ function resolveBinPath() {
44441
45287
  function stableNodePath(execPath) {
44442
45288
  const stable = execPath.replace(/(\/installs\/node\/)[^/]+\//, "$1latest/");
44443
45289
  if (stable === execPath) return execPath;
44444
- return (0, import_node_fs38.existsSync)(stable) ? stable : execPath;
45290
+ return (0, import_node_fs40.existsSync)(stable) ? stable : execPath;
44445
45291
  }
44446
45292
  function looksLikeNodeScript(path) {
44447
45293
  try {
44448
- const head = (0, import_node_fs38.readFileSync)(path, "utf-8").slice(0, 120);
45294
+ const head = (0, import_node_fs40.readFileSync)(path, "utf-8").slice(0, 120);
44449
45295
  return /^#!.*\bnode\b/.test(head);
44450
45296
  } catch {
44451
45297
  return false;
@@ -44472,20 +45318,20 @@ function isRoot3() {
44472
45318
  return typeof process.getuid === "function" && process.getuid() === 0;
44473
45319
  }
44474
45320
  function reexecWithSudo(args) {
44475
- if ((0, import_node_child_process14.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
45321
+ if ((0, import_node_child_process16.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
44476
45322
  console.log(source_default.dim(" This needs root \u2014 sudo will ask for your password.\n"));
44477
45323
  const bin = resolveBinPath();
44478
45324
  const argv = looksLikeNodeScript(bin) ? [stableNodePath(process.execPath), bin, ...args] : [bin, ...args];
44479
- const result = (0, import_node_child_process14.spawnSync)("sudo", argv, { stdio: "inherit" });
45325
+ const result = (0, import_node_child_process16.spawnSync)("sudo", argv, { stdio: "inherit" });
44480
45326
  return result.status === 0;
44481
45327
  }
44482
45328
  function callerHome() {
44483
45329
  const user = process.env.SUDO_USER;
44484
45330
  if (!user) return null;
44485
45331
  try {
44486
- const line2 = (0, import_node_child_process14.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
45332
+ const line2 = (0, import_node_child_process16.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
44487
45333
  const home = line2.split(":")[5];
44488
- return home && (0, import_node_fs38.existsSync)(home) ? home : null;
45334
+ return home && (0, import_node_fs40.existsSync)(home) ? home : null;
44489
45335
  } catch {
44490
45336
  return null;
44491
45337
  }
@@ -44493,13 +45339,13 @@ function callerHome() {
44493
45339
  function stopUserModeDaemon() {
44494
45340
  const home = callerHome();
44495
45341
  if (!home) return;
44496
- const runDir = (0, import_node_path28.join)(home, ".threatcrush", "run");
44497
- const pidFile = (0, import_node_path28.join)(runDir, "threatcrushd.pid");
44498
- const socket = (0, import_node_path28.join)(runDir, "threatcrushd.sock");
44499
- if (!(0, import_node_fs38.existsSync)(pidFile) && !(0, import_node_fs38.existsSync)(socket)) return;
45342
+ const runDir = (0, import_node_path30.join)(home, ".threatcrush", "run");
45343
+ const pidFile = (0, import_node_path30.join)(runDir, "threatcrushd.pid");
45344
+ const socket = (0, import_node_path30.join)(runDir, "threatcrushd.sock");
45345
+ if (!(0, import_node_fs40.existsSync)(pidFile) && !(0, import_node_fs40.existsSync)(socket)) return;
44500
45346
  let pid = null;
44501
45347
  try {
44502
- pid = Number.parseInt((0, import_node_fs38.readFileSync)(pidFile, "utf-8").trim(), 10);
45348
+ pid = Number.parseInt((0, import_node_fs40.readFileSync)(pidFile, "utf-8").trim(), 10);
44503
45349
  } catch {
44504
45350
  pid = null;
44505
45351
  }
@@ -44512,13 +45358,13 @@ function stopUserModeDaemon() {
44512
45358
  }
44513
45359
  for (const path of [socket, pidFile]) {
44514
45360
  try {
44515
- if ((0, import_node_fs38.existsSync)(path)) (0, import_node_fs38.rmSync)(path);
45361
+ if ((0, import_node_fs40.existsSync)(path)) (0, import_node_fs40.rmSync)(path);
44516
45362
  } catch {
44517
45363
  }
44518
45364
  }
44519
45365
  }
44520
45366
  function unitIsActive() {
44521
- const result = (0, import_node_child_process14.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
45367
+ const result = (0, import_node_child_process16.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
44522
45368
  return result.status === 0;
44523
45369
  }
44524
45370
  async function installServiceCommand() {
@@ -44529,8 +45375,8 @@ async function installServiceCommand() {
44529
45375
  return;
44530
45376
  }
44531
45377
  const noSystemd = systemdUnavailableReason({
44532
- hasSystemctl: (0, import_node_child_process14.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
44533
- booted: (0, import_node_fs38.existsSync)("/run/systemd/system")
45378
+ hasSystemctl: (0, import_node_child_process16.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
45379
+ booted: (0, import_node_fs40.existsSync)("/run/systemd/system")
44534
45380
  });
44535
45381
  if (noSystemd) {
44536
45382
  console.log(source_default.red(` \u2717 systemd isn't available here: ${noSystemd}.`));
@@ -44552,7 +45398,7 @@ async function installServiceCommand() {
44552
45398
  const isNodeScript = looksLikeNodeScript(binPath);
44553
45399
  let nodePath = stableNodePath(process.execPath);
44554
45400
  if (isNodeScript && nodeVersionDir(binPath)) {
44555
- binPath = (0, import_node_fs38.realpathSync)(binPath);
45401
+ binPath = (0, import_node_fs40.realpathSync)(binPath);
44556
45402
  nodePath = process.execPath;
44557
45403
  }
44558
45404
  if (isNodeScript) {
@@ -44565,9 +45411,9 @@ async function installServiceCommand() {
44565
45411
  }
44566
45412
  }
44567
45413
  const exec = execStartCommand(binPath, nodePath, isNodeScript);
44568
- const configDir = (0, import_node_path28.join)((0, import_node_os12.homedir)(), ".threatcrush");
45414
+ const configDir = (0, import_node_path30.join)((0, import_node_os12.homedir)(), ".threatcrush");
44569
45415
  const unit = renderUnit(resolveTemplate(), { exec, binPath, configDir });
44570
- (0, import_node_fs38.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
45416
+ (0, import_node_fs40.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
44571
45417
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
44572
45418
  console.log(source_default.dim(` ExecStart=${exec}`));
44573
45419
  const nodeDir = nodeVersionDir(nodePath);
@@ -44582,8 +45428,8 @@ async function installServiceCommand() {
44582
45428
  installLogrotate();
44583
45429
  stopUserModeDaemon();
44584
45430
  try {
44585
- (0, import_node_child_process14.execSync)("systemctl daemon-reload", { stdio: "inherit" });
44586
- (0, import_node_child_process14.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
45431
+ (0, import_node_child_process16.execSync)("systemctl daemon-reload", { stdio: "inherit" });
45432
+ (0, import_node_child_process16.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
44587
45433
  } catch (err) {
44588
45434
  console.log(source_default.yellow(` ! systemctl error: ${err.message}`));
44589
45435
  console.log(source_default.dim(` Logs: journalctl -u ${DAEMON_UNIT_NAME} -n 50`));
@@ -44620,9 +45466,9 @@ function renderLogrotate(logDir = "/var/log/threatcrush") {
44620
45466
  ].join("\n");
44621
45467
  }
44622
45468
  function installLogrotate() {
44623
- if (!(0, import_node_fs38.existsSync)((0, import_node_path28.dirname)(LOGROTATE_PATH))) return;
45469
+ if (!(0, import_node_fs40.existsSync)((0, import_node_path30.dirname)(LOGROTATE_PATH))) return;
44624
45470
  try {
44625
- (0, import_node_fs38.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
45471
+ (0, import_node_fs40.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
44626
45472
  console.log(source_default.green(` \u2713 Log rotation: ${LOGROTATE_PATH} (daily or 200M, keeps 7)`));
44627
45473
  } catch (err) {
44628
45474
  console.log(source_default.yellow(` ! Could not install log rotation: ${err.message}`));
@@ -44644,20 +45490,20 @@ function ensureSystemDirs(configDir) {
44644
45490
  ];
44645
45491
  let admGid2 = null;
44646
45492
  try {
44647
- admGid2 = (0, import_node_fs38.statSync)("/var/log/auth.log").gid;
45493
+ admGid2 = (0, import_node_fs40.statSync)("/var/log/auth.log").gid;
44648
45494
  } catch {
44649
45495
  }
44650
45496
  for (const { path, groupWritable, sticky } of dirs) {
44651
45497
  try {
44652
- (0, import_node_fs38.mkdirSync)(path, { recursive: true });
45498
+ (0, import_node_fs40.mkdirSync)(path, { recursive: true });
44653
45499
  } catch {
44654
45500
  }
44655
45501
  try {
44656
45502
  if (groupWritable && admGid2 !== null) {
44657
- (0, import_node_fs38.chmodSync)(path, sticky ? 1533 : 509);
44658
- (0, import_node_child_process14.execSync)(`chgrp adm ${path}`, { stdio: "ignore" });
45503
+ (0, import_node_fs40.chmodSync)(path, sticky ? 1533 : 509);
45504
+ (0, import_node_child_process16.execSync)(`chgrp adm ${path}`, { stdio: "ignore" });
44659
45505
  } else {
44660
- (0, import_node_fs38.chmodSync)(path, 493);
45506
+ (0, import_node_fs40.chmodSync)(path, 493);
44661
45507
  }
44662
45508
  } catch {
44663
45509
  }
@@ -44677,29 +45523,29 @@ async function uninstallServiceCommand() {
44677
45523
  return;
44678
45524
  }
44679
45525
  try {
44680
- (0, import_node_child_process14.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
45526
+ (0, import_node_child_process16.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
44681
45527
  } catch {
44682
45528
  }
44683
45529
  try {
44684
- (0, import_node_child_process14.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
45530
+ (0, import_node_child_process16.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
44685
45531
  } catch {
44686
45532
  }
44687
45533
  try {
44688
- if ((0, import_node_fs38.existsSync)(UNIT_PATH)) {
44689
- (0, import_node_child_process14.execSync)(`rm -f ${UNIT_PATH}`);
45534
+ if ((0, import_node_fs40.existsSync)(UNIT_PATH)) {
45535
+ (0, import_node_child_process16.execSync)(`rm -f ${UNIT_PATH}`);
44690
45536
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
44691
45537
  }
44692
45538
  } catch {
44693
45539
  }
44694
45540
  try {
44695
- (0, import_node_child_process14.execSync)("systemctl daemon-reload", { stdio: "inherit" });
45541
+ (0, import_node_child_process16.execSync)("systemctl daemon-reload", { stdio: "inherit" });
44696
45542
  } catch {
44697
45543
  }
44698
45544
  console.log(source_default.green(" \u2713 threatcrushd service removed."));
44699
45545
  }
44700
45546
 
44701
45547
  // src/commands/save.ts
44702
- var import_node_fs39 = require("fs");
45548
+ var import_node_fs41 = require("fs");
44703
45549
  var import_toml5 = __toESM(require_toml());
44704
45550
  init_cli_config();
44705
45551
  init_paths();
@@ -44738,9 +45584,9 @@ async function saveCommand(opts = {}) {
44738
45584
  }
44739
45585
  const path = opts.config ?? PATHS.configFile;
44740
45586
  let config = {};
44741
- if ((0, import_node_fs39.existsSync)(path)) {
45587
+ if ((0, import_node_fs41.existsSync)(path)) {
44742
45588
  try {
44743
- config = import_toml5.default.parse((0, import_node_fs39.readFileSync)(path, "utf-8"));
45589
+ config = import_toml5.default.parse((0, import_node_fs41.readFileSync)(path, "utf-8"));
44744
45590
  } catch (err) {
44745
45591
  console.log(source_default.red(` \u2717 ${path} is not valid TOML: ${err.message}
44746
45592
  `));
@@ -44853,8 +45699,8 @@ function welcomeCommand() {
44853
45699
  }
44854
45700
 
44855
45701
  // src/commands/properties.ts
44856
- var import_node_fs40 = require("fs");
44857
- var import_node_path29 = require("path");
45702
+ var import_node_fs42 = require("fs");
45703
+ var import_node_path31 = require("path");
44858
45704
  var import_node_readline4 = __toESM(require("readline"));
44859
45705
  init_cli_config();
44860
45706
  var API_URL5 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
@@ -45184,8 +46030,8 @@ async function propertiesRunsCommand(opts) {
45184
46030
  }
45185
46031
  }
45186
46032
  function parseImportFile(path) {
45187
- const ext = (0, import_node_path29.extname)(path).toLowerCase();
45188
- const raw = (0, import_node_fs40.readFileSync)(path, "utf-8");
46033
+ const ext = (0, import_node_path31.extname)(path).toLowerCase();
46034
+ const raw = (0, import_node_fs42.readFileSync)(path, "utf-8");
45189
46035
  if (ext === ".json") {
45190
46036
  const parsed = JSON.parse(raw);
45191
46037
  if (!Array.isArray(parsed)) throw new Error("JSON must be an array of objects");
@@ -45380,19 +46226,19 @@ async function rulesCommand(opts) {
45380
46226
  }
45381
46227
 
45382
46228
  // src/commands/harden.ts
45383
- var import_node_fs41 = require("fs");
45384
- var import_node_child_process15 = require("child_process");
46229
+ var import_node_fs43 = require("fs");
46230
+ var import_node_child_process17 = require("child_process");
45385
46231
  init_cli_config();
45386
46232
  function tryExec(cmd) {
45387
46233
  try {
45388
- return (0, import_node_child_process15.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
46234
+ return (0, import_node_child_process17.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
45389
46235
  } catch {
45390
46236
  return null;
45391
46237
  }
45392
46238
  }
45393
46239
  function tryRead(path) {
45394
46240
  try {
45395
- return (0, import_node_fs41.readFileSync)(path, "utf-8");
46241
+ return (0, import_node_fs43.readFileSync)(path, "utf-8");
45396
46242
  } catch {
45397
46243
  return null;
45398
46244
  }
@@ -45496,8 +46342,8 @@ function checkSshWeakConfig() {
45496
46342
  };
45497
46343
  }
45498
46344
  function checkAutoUpdates() {
45499
- 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");
45500
- const dnfAuto = (0, import_node_fs41.existsSync)("/etc/dnf/automatic.conf");
46345
+ const unattended = (0, import_node_fs43.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs43.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
46346
+ const dnfAuto = (0, import_node_fs43.existsSync)("/etc/dnf/automatic.conf");
45501
46347
  if (unattended || dnfAuto) {
45502
46348
  return {
45503
46349
  key: "auto-updates",
@@ -45623,7 +46469,7 @@ function checkFail2ban() {
45623
46469
  explanation: "fail2ban is installed and running."
45624
46470
  };
45625
46471
  }
45626
- if ((0, import_node_fs41.existsSync)("/etc/fail2ban/fail2ban.conf")) {
46472
+ if ((0, import_node_fs43.existsSync)("/etc/fail2ban/fail2ban.conf")) {
45627
46473
  return {
45628
46474
  key: checkKey,
45629
46475
  status: "warn",
@@ -45809,9 +46655,9 @@ async function hardenCommand(opts) {
45809
46655
  }
45810
46656
 
45811
46657
  // src/core/patches/index.ts
45812
- var import_node_fs42 = require("fs");
45813
- var import_node_path30 = require("path");
45814
- var import_node_child_process16 = require("child_process");
46658
+ var import_node_fs44 = require("fs");
46659
+ var import_node_path32 = require("path");
46660
+ var import_node_child_process18 = require("child_process");
45815
46661
  var import_node_util2 = require("util");
45816
46662
 
45817
46663
  // src/core/patches/dpkg-version.ts
@@ -45871,7 +46717,7 @@ var STALE_AFTER_MS = 2 * 864e5;
45871
46717
  var SEVERITIES2 = ["info", "low", "medium", "high", "critical"];
45872
46718
  var RANK = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
45873
46719
  var defaultExec = async (file, args) => {
45874
- const { stdout } = await (0, import_node_util2.promisify)(import_node_child_process16.execFile)(file, args, {
46720
+ const { stdout } = await (0, import_node_util2.promisify)(import_node_child_process18.execFile)(file, args, {
45875
46721
  timeout: 12e4,
45876
46722
  maxBuffer: 32 * 1024 * 1024,
45877
46723
  env: { ...process.env, LC_ALL: "C" }
@@ -45970,9 +46816,9 @@ async function osvRecords(doFetch, ecosystem, source, version) {
45970
46816
  function newestReleaseMtime(dir) {
45971
46817
  try {
45972
46818
  let newest = 0;
45973
- for (const name of (0, import_node_fs42.readdirSync)(dir)) {
46819
+ for (const name of (0, import_node_fs44.readdirSync)(dir)) {
45974
46820
  if (!/Release$/.test(name)) continue;
45975
- newest = Math.max(newest, (0, import_node_fs42.statSync)((0, import_node_path30.join)(dir, name)).mtimeMs);
46821
+ newest = Math.max(newest, (0, import_node_fs44.statSync)((0, import_node_path32.join)(dir, name)).mtimeMs);
45976
46822
  }
45977
46823
  return newest > 0 ? new Date(newest) : null;
45978
46824
  } catch {
@@ -45989,7 +46835,7 @@ async function checkPatches(opts = {}) {
45989
46835
  let osText = opts.osRelease;
45990
46836
  if (osText === void 0) {
45991
46837
  try {
45992
- osText = (0, import_node_fs42.readFileSync)("/etc/os-release", "utf-8");
46838
+ osText = (0, import_node_fs44.readFileSync)("/etc/os-release", "utf-8");
45993
46839
  } catch {
45994
46840
  osText = "";
45995
46841
  }
@@ -46214,6 +47060,122 @@ async function patchesCommand(opts) {
46214
47060
  if (opts.upload !== false) await uploadFindings([finding], false);
46215
47061
  }
46216
47062
 
47063
+ // src/commands/feeds.ts
47064
+ var import_node_net12 = require("net");
47065
+ var import_node_path33 = require("path");
47066
+ init_paths();
47067
+ async function loadSet() {
47068
+ for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
47069
+ const path = (0, import_node_path33.join)(dir, "threat-feeds.json");
47070
+ const set = readFeedCache(path);
47071
+ if (set) return { set, from: path };
47072
+ }
47073
+ const settings = threatFeedSettings(loadConfig((0, import_node_path33.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
47074
+ return { set: await fetchFeeds(settings), from: "abuse.ch (live; no daemon cache readable)" };
47075
+ }
47076
+ async function feedsCommand(action, value, opts) {
47077
+ const { set, from } = await loadSet();
47078
+ if (action === "check") {
47079
+ if (!value) {
47080
+ console.error("Usage: threatcrush feeds check <ip|domain>");
47081
+ process.exitCode = 2;
47082
+ return;
47083
+ }
47084
+ const ipHit = (0, import_node_net12.isIP)(value) ? matchIp(value, set) : null;
47085
+ const domainHit = (0, import_node_net12.isIP)(value) ? null : matchDomain(value, set);
47086
+ const listed = ipHit ?? domainHit?.indicator ?? null;
47087
+ if (opts.json) {
47088
+ console.log(JSON.stringify({ value, listed: Boolean(listed), indicator: listed, matched: domainHit?.domain ?? (ipHit ? value : null), fetched_at: set.fetched_at }, null, 2));
47089
+ } else if (listed) {
47090
+ console.log(`${source_default.red("LISTED")} ${value}${domainHit && domainHit.domain !== value ? ` (via ${domainHit.domain})` : ""}: ${listed.malware} ${listed.threat} [${listed.feed}]`);
47091
+ } else {
47092
+ console.log(`${source_default.green("not listed")} ${value}`);
47093
+ }
47094
+ process.exitCode = listed ? 1 : 0;
47095
+ return;
47096
+ }
47097
+ const ips = Object.keys(set.ips).length;
47098
+ const domains = Object.keys(set.domains).length;
47099
+ if (opts.json) {
47100
+ console.log(JSON.stringify({ from, fetched_at: set.fetched_at, ips, domains, skipped_shared: set.skipped_shared, sources: set.sources }, null, 2));
47101
+ return;
47102
+ }
47103
+ console.log(` ${source_default.white.bold("Threat feeds")} ${source_default.gray(`(${from})`)}`);
47104
+ console.log(` Fetched: ${set.fetched_at.replace("T", " ").slice(0, 16)} UTC`);
47105
+ console.log(` ${ips} C2/payload IPs, ${domains} malware domains; ${set.skipped_shared} shared or protected entries skipped`);
47106
+ for (const s of set.sources) {
47107
+ 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")}`);
47108
+ }
47109
+ console.log(source_default.gray("\n Blocking egress needs [threat_feeds] block = true and [remediation] in enforce mode."));
47110
+ }
47111
+
47112
+ // src/commands/privileged.ts
47113
+ var import_node_fs45 = require("fs");
47114
+ init_paths();
47115
+ var SEV2 = {
47116
+ critical: source_default.red.bold,
47117
+ high: source_default.red,
47118
+ medium: source_default.yellow,
47119
+ low: source_default.cyan,
47120
+ info: source_default.gray
47121
+ };
47122
+ async function privilegedCommand(opts) {
47123
+ const snapshot = takeSnapshot({
47124
+ readFile: (p) => {
47125
+ try {
47126
+ return (0, import_node_fs45.readFileSync)(p, "utf-8");
47127
+ } catch {
47128
+ return null;
47129
+ }
47130
+ },
47131
+ readDir: (p) => {
47132
+ try {
47133
+ return (0, import_node_fs45.readdirSync)(p);
47134
+ } catch {
47135
+ return null;
47136
+ }
47137
+ },
47138
+ exists: (p) => (0, import_node_fs45.existsSync)(p)
47139
+ });
47140
+ let events = [];
47141
+ let ledgerNote = "";
47142
+ try {
47143
+ initStateDB(PATHS.stateDb);
47144
+ events = getModuleEvents("privileged-access", Number(opts.limit) || 25);
47145
+ } catch {
47146
+ ledgerNote = `the daemon's state database (${PATHS.stateDb}) is not readable here`;
47147
+ }
47148
+ if (opts.json) {
47149
+ console.log(JSON.stringify({ snapshot, events }, null, 2));
47150
+ return;
47151
+ }
47152
+ console.log(` ${source_default.white.bold("uid 0 accounts:")} ${snapshot.uid0.join(", ") || "\u2014"}`);
47153
+ for (const [group, members] of Object.entries(snapshot.admin_groups)) {
47154
+ console.log(` ${source_default.white.bold(`${group} group:`)} ${members.join(", ") || "\u2014"}`);
47155
+ }
47156
+ const rules = Object.entries(snapshot.sudoers).filter(([, r]) => r.length > 0);
47157
+ console.log(` ${source_default.white.bold("sudoers:")} ${rules.length} file(s) with rules`);
47158
+ for (const [path, r] of rules) {
47159
+ for (const rule of r.filter((x) => !/^Defaults\b/.test(x))) console.log(source_default.gray(` ${path.replace("/etc/", "")}: ${rule}`));
47160
+ }
47161
+ console.log(` ${source_default.white.bold("authorized keys:")}`);
47162
+ for (const [user, keys] of Object.entries(snapshot.keys)) {
47163
+ for (const [fp, k] of Object.entries(keys)) console.log(` ${user.padEnd(12)} ${k.type.padEnd(20)} ${fp} ${source_default.gray(k.comment)}`);
47164
+ }
47165
+ if (snapshot.unreadable.length) {
47166
+ console.log(source_default.yellow(` ! not readable as this user: ${snapshot.unreadable.join(", ")} (run with sudo for the full picture)`));
47167
+ }
47168
+ console.log(`
47169
+ ${source_default.white.bold("Recent changes and sudo commands")}`);
47170
+ if (ledgerNote) console.log(source_default.gray(` ${ledgerNote}`));
47171
+ else if (events.length === 0) console.log(source_default.gray(" none recorded yet (the daemon records them from its first run on)"));
47172
+ for (const e of events) {
47173
+ const at = new Date(e.timestamp).toISOString().replace("T", " ").slice(0, 19);
47174
+ console.log(` ${source_default.gray(at)} ${(SEV2[e.severity] ?? source_default.white)(e.severity.padEnd(8))} ${e.message}`);
47175
+ }
47176
+ console.log();
47177
+ }
47178
+
46217
47179
  // src/commands/firewall.ts
46218
47180
  init_ipc_client();
46219
47181
  init_paths();
@@ -46358,11 +47320,11 @@ async function allowlistCommand(opts) {
46358
47320
  init_paths();
46359
47321
 
46360
47322
  // src/upgrade.ts
46361
- var import_node_child_process17 = require("child_process");
47323
+ var import_node_child_process19 = require("child_process");
46362
47324
  var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
46363
47325
  var defaultRunner = (cmd) => {
46364
47326
  try {
46365
- return (0, import_node_child_process17.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
47327
+ return (0, import_node_child_process19.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
46366
47328
  } catch {
46367
47329
  return null;
46368
47330
  }
@@ -46449,12 +47411,12 @@ function staleDaemonWarning(cliVersion, daemonVersion, restartCommand = "threatc
46449
47411
  ` ${restartCommand}`
46450
47412
  ];
46451
47413
  }
46452
- function shadowedUpdateWarning(latest, active, activePath) {
46453
- if (!latest || !active || latest === active) return null;
47414
+ function shadowedUpdateWarning(latest, active2, activePath) {
47415
+ if (!latest || !active2 || latest === active2) return null;
46454
47416
  return [
46455
47417
  "\u26A0 The update ran, but PATH still resolves to an older ThreatCrush.",
46456
47418
  ` Latest published: ${latest}`,
46457
- ` Running from PATH: ${active} (${activePath || "unknown"})`,
47419
+ ` Running from PATH: ${active2} (${activePath || "unknown"})`,
46458
47420
  "",
46459
47421
  " Usually a stale shell hash. Try first:",
46460
47422
  " hash -r # or open a new terminal",
@@ -46477,25 +47439,25 @@ ${source_default.dim(" C R U S H")}
46477
47439
  var API_URL6 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
46478
47440
  var PKG_NAME2 = "@profullstack/threatcrush";
46479
47441
  var DESKTOP_PKG_NAME = "@profullstack/threatcrush-desktop";
46480
- var INSTALL_CONFIG_PATH = (0, import_node_path31.join)((0, import_node_os13.homedir)(), ".threatcrush", "install.json");
47442
+ var INSTALL_CONFIG_PATH = (0, import_node_path34.join)((0, import_node_os13.homedir)(), ".threatcrush", "install.json");
46481
47443
  function detectPackageManager() {
46482
47444
  try {
46483
- const npmGlobal = (0, import_node_child_process18.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
47445
+ const npmGlobal = (0, import_node_child_process20.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
46484
47446
  if (npmGlobal.includes(PKG_NAME2)) return "npm";
46485
47447
  } catch {
46486
47448
  }
46487
47449
  try {
46488
- (0, import_node_child_process18.execSync)("pnpm --version", { stdio: "pipe" });
47450
+ (0, import_node_child_process20.execSync)("pnpm --version", { stdio: "pipe" });
46489
47451
  return "pnpm";
46490
47452
  } catch {
46491
47453
  }
46492
47454
  try {
46493
- (0, import_node_child_process18.execSync)("yarn --version", { stdio: "pipe" });
47455
+ (0, import_node_child_process20.execSync)("yarn --version", { stdio: "pipe" });
46494
47456
  return "yarn";
46495
47457
  } catch {
46496
47458
  }
46497
47459
  try {
46498
- (0, import_node_child_process18.execSync)("bun --version", { stdio: "pipe" });
47460
+ (0, import_node_child_process20.execSync)("bun --version", { stdio: "pipe" });
46499
47461
  return "bun";
46500
47462
  } catch {
46501
47463
  }
@@ -46503,14 +47465,14 @@ function detectPackageManager() {
46503
47465
  }
46504
47466
  function readInstallConfig() {
46505
47467
  try {
46506
- return JSON.parse((0, import_node_fs43.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
47468
+ return JSON.parse((0, import_node_fs46.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
46507
47469
  } catch {
46508
47470
  return {};
46509
47471
  }
46510
47472
  }
46511
47473
  function packageLooksInstalled(pm, pkgName) {
46512
47474
  try {
46513
- const output = (0, import_node_child_process18.execSync)(globalListCommand(pm, pkgName), {
47475
+ const output = (0, import_node_child_process20.execSync)(globalListCommand(pm, pkgName), {
46514
47476
  encoding: "utf-8",
46515
47477
  stdio: ["pipe", "pipe", "pipe"]
46516
47478
  });
@@ -46613,14 +47575,14 @@ async function promoteUnprivilegedDaemon() {
46613
47575
  function restartSystemdDaemon() {
46614
47576
  const asRoot = typeof process.getuid === "function" && process.getuid() === 0;
46615
47577
  const argv = asRoot ? ["systemctl", "restart", DAEMON_UNIT] : ["sudo", "systemctl", "restart", DAEMON_UNIT];
46616
- if (!asRoot && (0, import_node_child_process18.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
47578
+ if (!asRoot && (0, import_node_child_process20.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
46617
47579
  const [cmd, ...args] = argv;
46618
- if ((0, import_node_child_process18.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
46619
- return (0, import_node_child_process18.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
47580
+ if ((0, import_node_child_process20.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
47581
+ return (0, import_node_child_process20.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
46620
47582
  }
46621
47583
  function execQuiet(cmd) {
46622
47584
  try {
46623
- return (0, import_node_child_process18.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
47585
+ return (0, import_node_child_process20.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
46624
47586
  } catch {
46625
47587
  return null;
46626
47588
  }
@@ -46773,6 +47735,12 @@ program2.command("harden").description("Run hardening security scan").option("--
46773
47735
  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) => {
46774
47736
  await patchesCommand(opts);
46775
47737
  });
47738
+ 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) => {
47739
+ await feedsCommand(action, value, opts);
47740
+ });
47741
+ program2.command("privileged").description("Who can become root here (uid 0, sudo groups, sudoers, SSH keys) and the daemon's record of changes and sudo commands").option("--json", "Output as JSON").option("--limit <n>", "How many recent events to show", "25").action(async (opts) => {
47742
+ await privilegedCommand(opts);
47743
+ });
46776
47744
  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) => {
46777
47745
  await blockCommand(ip, opts);
46778
47746
  });
@@ -46809,7 +47777,7 @@ program2.command("uninstall-service").description("Remove the threatcrushd syste
46809
47777
  program2.command("logs").description("Tail daemon logs").action(async () => {
46810
47778
  console.log(LOGO2);
46811
47779
  const logPath = PATHS.logFile;
46812
- if (!(0, import_node_fs43.existsSync)(logPath)) {
47780
+ if (!(0, import_node_fs46.existsSync)(logPath)) {
46813
47781
  console.log(source_default.yellow(` No log file found at ${logPath}`));
46814
47782
  console.log(source_default.dim(" Start the daemon first with `threatcrush start`\n"));
46815
47783
  return;
@@ -46817,7 +47785,7 @@ program2.command("logs").description("Tail daemon logs").action(async () => {
46817
47785
  console.log(source_default.green(` Tailing ${logPath}...
46818
47786
  `));
46819
47787
  console.log(source_default.gray(" Press Ctrl+C to stop\n"));
46820
- (0, import_node_child_process18.execSync)(`tail -f ${logPath}`, { stdio: "inherit" });
47788
+ (0, import_node_child_process20.execSync)(`tail -f ${logPath}`, { stdio: "inherit" });
46821
47789
  });
46822
47790
  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) => {
46823
47791
  console.log(LOGO2);
@@ -46829,7 +47797,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
46829
47797
  for (const cmd of commands2) {
46830
47798
  console.log(source_default.green(` \u2192 ${cmd}
46831
47799
  `));
46832
- (0, import_node_child_process18.execSync)(cmd, { stdio: "inherit" });
47800
+ (0, import_node_child_process20.execSync)(cmd, { stdio: "inherit" });
46833
47801
  }
46834
47802
  console.log(source_default.green("\n \u2713 Modules updated successfully!\n"));
46835
47803
  await reportIfStillStale();
@@ -46854,7 +47822,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
46854
47822
  for (const cmd of commands) {
46855
47823
  console.log(source_default.green(` \u2192 ${cmd}
46856
47824
  `));
46857
- (0, import_node_child_process18.execSync)(cmd, { stdio: "inherit" });
47825
+ (0, import_node_child_process20.execSync)(cmd, { stdio: "inherit" });
46858
47826
  }
46859
47827
  console.log(source_default.green("\n \u2713 ThreatCrush updated successfully!\n"));
46860
47828
  if (installMode === "desktop") {
@@ -46905,7 +47873,7 @@ program2.command("remove").description("Uninstall ThreatCrush and the installed
46905
47873
  for (const cmd of commands) {
46906
47874
  console.log(source_default.green(` \u2192 ${cmd}
46907
47875
  `));
46908
- (0, import_node_child_process18.execSync)(cmd, { stdio: "inherit" });
47876
+ (0, import_node_child_process20.execSync)(cmd, { stdio: "inherit" });
46909
47877
  }
46910
47878
  console.log(source_default.green("\n \u2713 ThreatCrush has been uninstalled.\n"));
46911
47879
  console.log(source_default.dim(" We're sorry to see you go! \u{1F44B}\n"));
@@ -46982,10 +47950,10 @@ storeCmd.command("search <query>").description("Search for modules in the store"
46982
47950
  });
46983
47951
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
46984
47952
  console.log(LOGO2);
46985
- const configPath = (0, import_node_path31.join)((0, import_node_os13.homedir)(), ".threatcrush", "config.json");
47953
+ const configPath = (0, import_node_path34.join)((0, import_node_os13.homedir)(), ".threatcrush", "config.json");
46986
47954
  let email = "";
46987
47955
  try {
46988
- const config = JSON.parse((0, import_node_fs43.readFileSync)(configPath, "utf-8"));
47956
+ const config = JSON.parse((0, import_node_fs46.readFileSync)(configPath, "utf-8"));
46989
47957
  email = config.email || "";
46990
47958
  } catch {
46991
47959
  }
@@ -47002,9 +47970,9 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
47002
47970
  return;
47003
47971
  }
47004
47972
  try {
47005
- const dir = (0, import_node_path31.join)((0, import_node_os13.homedir)(), ".threatcrush");
47006
- if (!(0, import_node_fs43.existsSync)(dir)) (0, import_node_fs43.mkdirSync)(dir, { recursive: true });
47007
- (0, import_node_fs43.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
47973
+ const dir = (0, import_node_path34.join)((0, import_node_os13.homedir)(), ".threatcrush");
47974
+ if (!(0, import_node_fs46.existsSync)(dir)) (0, import_node_fs46.mkdirSync)(dir, { recursive: true });
47975
+ (0, import_node_fs46.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
47008
47976
  console.log(source_default.dim(` Saved email to ${configPath}`));
47009
47977
  } catch {
47010
47978
  }