@profullstack/threatcrush 0.15.3 → 0.16.0

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
@@ -7972,11 +7972,11 @@ function drawSelect(surface, options) {
7972
7972
  });
7973
7973
  surface.text(width - 2, 0, options.open ? " \u25B4" : " \u25BE", { fg: color, bg: elevate(theme, 0.05) });
7974
7974
  if (options.open && options.options?.length) {
7975
- const list2 = options.options;
7976
- const height = Math.min(list2.length, surface.height - 1);
7975
+ const list3 = options.options;
7976
+ const height = Math.min(list3.length, surface.height - 1);
7977
7977
  for (let i = 0; i < height; i++) {
7978
7978
  const selected = i === (options.selectedIndex ?? 0);
7979
- surface.text(0, i + 1, fit(` ${truncate(list2[i], width - 2)}`, width), {
7979
+ surface.text(0, i + 1, fit(` ${truncate(list3[i], width - 2)}`, width), {
7980
7980
  fg: selected ? theme.selectionText : theme.foreground,
7981
7981
  bg: selected ? theme.selection : elevate(theme, 0.08)
7982
7982
  });
@@ -18276,7 +18276,7 @@ function isPublicAddress(ip) {
18276
18276
  if (v === 6) return !/^(::1?$|f[cd]|fe[89ab]|ff)/i.test(ip);
18277
18277
  return false;
18278
18278
  }
18279
- function localMapData(state, geo, hostname7, now = Date.now()) {
18279
+ function localMapData(state, geo, hostname8, now = Date.now()) {
18280
18280
  const by = /* @__PURE__ */ new Map();
18281
18281
  for (const e of state.events) {
18282
18282
  const ip = e.source_ip;
@@ -18300,7 +18300,7 @@ function localMapData(state, geo, hostname7, now = Date.now()) {
18300
18300
  const o = by.get(t.ip);
18301
18301
  if (o) o.count = Math.max(o.count, t.count);
18302
18302
  }
18303
- const servers = geo.self ? [{ id: "self", name: hostname7, ...geo.self, online: state.connection === "live" }] : [];
18303
+ const servers = geo.self ? [{ id: "self", name: hostname8, ...geo.self, online: state.connection === "live" }] : [];
18304
18304
  return { servers, origins: [...by.values()], windowMinutes: 0, generatedAt: new Date(now).toISOString() };
18305
18305
  }
18306
18306
  function sourceAddresses(state) {
@@ -25807,15 +25807,15 @@ var require_parser2 = __commonJS({
25807
25807
  var node_process = require("process");
25808
25808
  var cst = require_cst();
25809
25809
  var lexer = require_lexer();
25810
- function includesToken(list2, type) {
25811
- for (let i = 0; i < list2.length; ++i)
25812
- if (list2[i].type === type)
25810
+ function includesToken(list3, type) {
25811
+ for (let i = 0; i < list3.length; ++i)
25812
+ if (list3[i].type === type)
25813
25813
  return true;
25814
25814
  return false;
25815
25815
  }
25816
- function findNonEmptyIndex(list2) {
25817
- for (let i = 0; i < list2.length; ++i) {
25818
- switch (list2[i].type) {
25816
+ function findNonEmptyIndex(list3) {
25817
+ for (let i = 0; i < list3.length; ++i) {
25818
+ switch (list3[i].type) {
25819
25819
  case "space":
25820
25820
  case "comment":
25821
25821
  case "newline":
@@ -27066,9 +27066,9 @@ async function startActionCenter() {
27066
27066
  row.text(error2 || warning2 || "Fleet detections, server health, and queued actions", { fg: error2 ? severityColors.high : theme.muted, size: "fill" });
27067
27067
  });
27068
27068
  });
27069
- const list2 = filtered();
27070
- selected = Math.min(selected, Math.max(0, list2.length - 1));
27071
- const selectedDetection = list2[selected];
27069
+ const list3 = filtered();
27070
+ selected = Math.min(selected, Math.max(0, list3.length - 1));
27071
+ const selectedDetection = list3[selected];
27072
27072
  const serverMap = serverById();
27073
27073
  const online = data.servers.filter((server) => server.connection === "online").length;
27074
27074
  const pending = data.actions.length;
@@ -27076,7 +27076,7 @@ async function startActionCenter() {
27076
27076
  summary(row, theme, "SERVERS ONLINE", `${online}/${data.servers.length}`, theme.success);
27077
27077
  summary(row, theme, "DETECTIONS", String(data.detections.length), severityColors.high);
27078
27078
  summary(row, theme, "QUEUED ACTIONS", String(pending), theme.warning);
27079
- summary(row, theme, "FILTERED EVENTS", String(list2.length), theme.accent);
27079
+ summary(row, theme, "FILTERED EVENTS", String(list3.length), theme.accent);
27080
27080
  });
27081
27081
  ui.row({ size: 1 }, (row) => {
27082
27082
  const selectedHost = serverMap.get(serverId);
@@ -27090,12 +27090,12 @@ async function startActionCenter() {
27090
27090
  panel.label("Loading detections\u2026", { fg: theme.muted });
27091
27091
  return;
27092
27092
  }
27093
- if (list2.length === 0) {
27093
+ if (list3.length === 0) {
27094
27094
  panel.label(error2 ? "Sign in and refresh to load fleet activity." : "No detections match these filters.", { fg: theme.muted });
27095
27095
  return;
27096
27096
  }
27097
27097
  panel.table({
27098
- rows: list2,
27098
+ rows: list3,
27099
27099
  header: true,
27100
27100
  selected,
27101
27101
  followSelection: true,
@@ -31116,10 +31116,10 @@ var source_default = chalk;
31116
31116
 
31117
31117
  // src/index.ts
31118
31118
  var import_readline = __toESM(require("readline"));
31119
- var import_node_child_process36 = require("child_process");
31120
- var import_node_fs85 = require("fs");
31121
- var import_node_path61 = require("path");
31122
- var import_node_os25 = require("os");
31119
+ var import_node_child_process37 = require("child_process");
31120
+ var import_node_fs87 = require("fs");
31121
+ var import_node_path62 = require("path");
31122
+ var import_node_os27 = require("os");
31123
31123
 
31124
31124
  // src/commands/monitor.ts
31125
31125
  var import_node_fs11 = require("fs");
@@ -37829,9 +37829,9 @@ var CrsEngine = class {
37829
37829
  continue;
37830
37830
  }
37831
37831
  for (const target of compiled.rule.targets) {
37832
- const list2 = this.byTarget.get(target) ?? [];
37833
- list2.push(compiled);
37834
- this.byTarget.set(target, list2);
37832
+ const list3 = this.byTarget.get(target) ?? [];
37833
+ list3.push(compiled);
37834
+ this.byTarget.set(target, list3);
37835
37835
  }
37836
37836
  }
37837
37837
  }
@@ -38179,6 +38179,7 @@ function parseConfigText(raw) {
38179
38179
  docker_logs: parsed.docker_logs,
38180
38180
  postgres_shell: parsed.postgres_shell,
38181
38181
  login_watch: parsed.login_watch,
38182
+ ssh_context: parsed.ssh_context,
38182
38183
  storage: parsed.storage,
38183
38184
  // TOML's `[abuse-reporter]` parses to a hyphenated key; expose it under
38184
38185
  // the JS-friendly name the rest of the daemon reads.
@@ -39756,15 +39757,15 @@ var Emitter = class {
39756
39757
  this.listeners[ev].push(fn);
39757
39758
  }
39758
39759
  removeListener(ev, fn) {
39759
- const list2 = this.listeners[ev];
39760
- const i = list2.indexOf(fn);
39760
+ const list3 = this.listeners[ev];
39761
+ const i = list3.indexOf(fn);
39761
39762
  if (i === -1) {
39762
39763
  return;
39763
39764
  }
39764
- if (i === 0 && list2.length === 1) {
39765
- list2.length = 0;
39765
+ if (i === 0 && list3.length === 1) {
39766
+ list3.length = 0;
39766
39767
  } else {
39767
- list2.splice(i, 1);
39768
+ list3.splice(i, 1);
39768
39769
  }
39769
39770
  }
39770
39771
  emit(ev, code, signal) {
@@ -45464,7 +45465,7 @@ function parseAuthorizedKeyLines(text) {
45464
45465
  text.split("\n").forEach((raw, idx) => {
45465
45466
  const line2 = raw.replace(/\r$/, "").trim();
45466
45467
  if (!line2 || line2.startsWith("#")) return;
45467
- let optionText = "";
45468
+ let optionText2 = "";
45468
45469
  let rest = line2;
45469
45470
  if (!KEY_TYPE.test(line2.split(/\s+/, 1)[0] ?? "")) {
45470
45471
  let inQuote = false;
@@ -45482,13 +45483,13 @@ function parseAuthorizedKeyLines(text) {
45482
45483
  }
45483
45484
  }
45484
45485
  if (cut === -1) return;
45485
- optionText = line2.slice(0, cut);
45486
+ optionText2 = line2.slice(0, cut);
45486
45487
  rest = line2.slice(cut).trimStart();
45487
45488
  }
45488
45489
  const parts = rest.split(/\s+/);
45489
45490
  if (!KEY_TYPE.test(parts[0] ?? "") || !parts[1]) return;
45490
45491
  const options = /* @__PURE__ */ new Map();
45491
- for (const m of optionText.matchAll(/([A-Za-z-]+)(?:="((?:[^"\\]|\\.)*)")?/g)) {
45492
+ for (const m of optionText2.matchAll(/([A-Za-z-]+)(?:="((?:[^"\\]|\\.)*)")?/g)) {
45492
45493
  options.set(m[1].toLowerCase(), m[2] ?? null);
45493
45494
  }
45494
45495
  out.push({ line: idx + 1, type: parts[0], comment: parts.slice(2).join(" "), options });
@@ -48199,19 +48200,19 @@ function parseAuthorizedKeys(text, file = "authorized_keys") {
48199
48200
  text.split("\n").forEach((raw, idx) => {
48200
48201
  const line2 = raw.replace(/\r$/, "").trim();
48201
48202
  if (!line2 || line2.startsWith("#")) return;
48202
- let optionText = "";
48203
+ let optionText2 = "";
48203
48204
  let rest = line2;
48204
48205
  const first = line2.split(/\s+/, 1)[0];
48205
48206
  if (!KEY_TYPE2.test(first)) {
48206
48207
  const split = splitOptionsPrefix(line2);
48207
- optionText = split.options;
48208
+ optionText2 = split.options;
48208
48209
  rest = split.rest;
48209
48210
  }
48210
48211
  const parts = rest.split(/\s+/);
48211
48212
  const type = parts[0] ?? "";
48212
48213
  const blob = parts[1] ?? "";
48213
48214
  if (!KEY_TYPE2.test(type) || !blob) return;
48214
- const options = optionText ? parseOptionList(optionText) : [];
48215
+ const options = optionText2 ? parseOptionList(optionText2) : [];
48215
48216
  const get2 = (n) => options.find((o) => o.name === n)?.value ?? null;
48216
48217
  keys.push({
48217
48218
  file,
@@ -48303,9 +48304,9 @@ function parseSshdT(text) {
48303
48304
  const m = /^(\S+)\s+(.*)$/.exec(line2);
48304
48305
  if (!m) continue;
48305
48306
  const key = m[1].toLowerCase();
48306
- const list2 = out.get(key) ?? [];
48307
- list2.push(m[2]);
48308
- out.set(key, list2);
48307
+ const list3 = out.get(key) ?? [];
48308
+ list3.push(m[2]);
48309
+ out.set(key, list3);
48309
48310
  }
48310
48311
  return out;
48311
48312
  }
@@ -48355,15 +48356,15 @@ function parseProcModules(text) {
48355
48356
  }
48356
48357
  var RISKY_SOURCES = /* @__PURE__ */ new Set(["/", "/var/run/docker.sock", "/run/docker.sock"]);
48357
48358
  function judgeDockerInspect(json2) {
48358
- let list2;
48359
+ let list3;
48359
48360
  try {
48360
- list2 = JSON.parse(json2);
48361
+ list3 = JSON.parse(json2);
48361
48362
  } catch {
48362
48363
  return [];
48363
48364
  }
48364
- if (!Array.isArray(list2)) return [];
48365
+ if (!Array.isArray(list3)) return [];
48365
48366
  const out = [];
48366
- for (const c of list2) {
48367
+ for (const c of list3) {
48367
48368
  const reasons = [];
48368
48369
  const hc = c.HostConfig ?? {};
48369
48370
  if (hc.Privileged === true) reasons.push("--privileged");
@@ -48527,14 +48528,14 @@ function hexToV6(h) {
48527
48528
  }
48528
48529
  return full;
48529
48530
  }
48530
- function parseProcNetTcp(text, family) {
48531
+ function parseProcNetTcp(text, family2) {
48531
48532
  const out = [];
48532
48533
  for (const line2 of text.split("\n").slice(1)) {
48533
48534
  const f = line2.trim().split(/\s+/);
48534
48535
  if (f.length < 10 || f[3] !== "0A") continue;
48535
48536
  const [hexAddr, hexPort] = f[1].split(":");
48536
- const addr = family === 4 ? hexToV4(hexAddr) : hexToV6(hexAddr);
48537
- out.push({ addr, port: parseInt(hexPort, 16), family, inode: f[9] });
48537
+ const addr = family2 === 4 ? hexToV4(hexAddr) : hexToV6(hexAddr);
48538
+ out.push({ addr, port: parseInt(hexPort, 16), family: family2, inode: f[9] });
48538
48539
  }
48539
48540
  return out;
48540
48541
  }
@@ -48562,7 +48563,7 @@ function classifyExposures(listeners, mappings, opts) {
48562
48563
  const sensitive = [];
48563
48564
  const seen = /* @__PURE__ */ new Set();
48564
48565
  let publicCount = 0;
48565
- const reachable = (addr, family) => !isLoopback(addr) && !isPrivate(addr) && (family === 4 || opts.hasGlobalV6);
48566
+ const reachable = (addr, family2) => !isLoopback(addr) && !isPrivate(addr) && (family2 === 4 || opts.hasGlobalV6);
48566
48567
  const add = (e) => {
48567
48568
  const key = `${e.kind}|${e.family}|${e.hostPort}`;
48568
48569
  if (seen.has(key)) return;
@@ -48580,17 +48581,17 @@ function classifyExposures(listeners, mappings, opts) {
48580
48581
  add({ kind: "docker", addr: m.hostIp, family: m.family, hostPort: m.hostPort, containerPort: m.containerPort, container: m.container, service });
48581
48582
  }
48582
48583
  for (const l of listeners) {
48583
- for (const family of l.family === 46 ? [4, 6] : [l.family]) {
48584
- if (!reachable(l.addr, family)) continue;
48584
+ for (const family2 of l.family === 46 ? [4, 6] : [l.family]) {
48585
+ if (!reachable(l.addr, family2)) continue;
48585
48586
  if (l.process === "docker-proxy" && opts.dockerKnown) continue;
48586
- if (dockerHostPorts.has(`${family}|${l.port}`)) continue;
48587
+ if (dockerHostPorts.has(`${family2}|${l.port}`)) continue;
48587
48588
  publicCount++;
48588
48589
  const service = sensitiveService(l.port);
48589
48590
  if (!service) continue;
48590
48591
  if (l.process === "docker-proxy") {
48591
- add({ kind: "docker", addr: l.addr, family, hostPort: l.port, process: l.process, pid: l.pid, service });
48592
+ add({ kind: "docker", addr: l.addr, family: family2, hostPort: l.port, process: l.process, pid: l.pid, service });
48592
48593
  } else {
48593
- add({ kind: "host", addr: l.addr, family, hostPort: l.port, process: l.process, pid: l.pid, service });
48594
+ add({ kind: "host", addr: l.addr, family: family2, hostPort: l.port, process: l.process, pid: l.pid, service });
48594
48595
  }
48595
48596
  }
48596
48597
  }
@@ -48743,11 +48744,11 @@ function ufwToMatches(to, port) {
48743
48744
  if (m[2] === "udp") return false;
48744
48745
  return inRange(port, parsePorts(m[1]));
48745
48746
  }
48746
- function evaluateUfw(status, port, family) {
48747
+ function evaluateUfw(status, port, family2) {
48747
48748
  if (!status.active) return { verdict: "unknown", by: "ufw inactive" };
48748
48749
  const allowlisted = [];
48749
48750
  for (const r of status.rules) {
48750
- if (r.v6 !== (family === 6)) continue;
48751
+ if (r.v6 !== (family2 === 6)) continue;
48751
48752
  if (/\bFWD\b|\bOUT\b/.test(r.action)) continue;
48752
48753
  if (!ufwToMatches(r.to, port)) continue;
48753
48754
  const anywhere = /^Anywhere/i.test(r.from);
@@ -48763,20 +48764,20 @@ function evaluateUfw(status, port, family) {
48763
48764
  }
48764
48765
  function parseNftInputChains(text) {
48765
48766
  const out = [];
48766
- let family = "";
48767
+ let family2 = "";
48767
48768
  let table2 = "";
48768
48769
  let cur = null;
48769
48770
  for (const raw of text.split("\n")) {
48770
48771
  const line2 = raw.trim();
48771
48772
  const t = /^table\s+(\S+)\s+(\S+)\s*\{/.exec(line2);
48772
48773
  if (t) {
48773
- family = t[1];
48774
+ family2 = t[1];
48774
48775
  table2 = t[2];
48775
48776
  continue;
48776
48777
  }
48777
48778
  const c = /^chain\s+(\S+)\s*\{/.exec(line2);
48778
48779
  if (c) {
48779
- cur = { family, table: table2, name: c[1], hook: "", policy: "accept", rules: [] };
48780
+ cur = { family: family2, table: table2, name: c[1], hook: "", policy: "accept", rules: [] };
48780
48781
  continue;
48781
48782
  }
48782
48783
  if (!cur) continue;
@@ -48801,8 +48802,8 @@ function nftPortSet(spec) {
48801
48802
  return [Number(a), Number(b ?? a)];
48802
48803
  }).filter(([a, b]) => Number.isFinite(a) && Number.isFinite(b));
48803
48804
  }
48804
- function evaluateNftChain(chain, port, family) {
48805
- if (chain.family === "ip" && family === 6 || chain.family === "ip6" && family === 4) return { verdict: "unknown", by: "other family" };
48805
+ function evaluateNftChain(chain, port, family2) {
48806
+ if (chain.family === "ip" && family2 === 6 || chain.family === "ip6" && family2 === 4) return { verdict: "unknown", by: "other family" };
48806
48807
  const label = `nft ${chain.family} ${chain.table} ${chain.name}`;
48807
48808
  for (const rule of chain.rules) {
48808
48809
  const verdict = /\b(accept|drop|reject)\b\s*(?:with .*)?$/.exec(rule)?.[1];
@@ -49019,12 +49020,12 @@ function checkNetworkExposure(ctx) {
49019
49020
  if (r.code === 0) nft = parseNftInputChains(r.stdout);
49020
49021
  }
49021
49022
  }
49022
- const hostVerdict = (port, family) => {
49023
+ const hostVerdict = (port, family2) => {
49023
49024
  const layers = [];
49024
- if (ufw?.active) layers.push(evaluateUfw(ufw, port, family));
49025
- else if (input[family]) layers.push(evaluateIptChain(input[family], { dport: port, origDport: port }));
49025
+ if (ufw?.active) layers.push(evaluateUfw(ufw, port, family2));
49026
+ else if (input[family2]) layers.push(evaluateIptChain(input[family2], { dport: port, origDport: port }));
49026
49027
  for (const ch of nft) {
49027
- const v = evaluateNftChain(ch, port, family);
49028
+ const v = evaluateNftChain(ch, port, family2);
49028
49029
  if (v.verdict !== "unknown") layers.push(v);
49029
49030
  }
49030
49031
  const blocked = layers.find((l) => l.verdict === "blocked");
@@ -50366,8 +50367,8 @@ function ipMatches(ip, entry) {
50366
50367
  const mask = 255 << 8 - remainder & 255;
50367
50368
  return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
50368
50369
  }
50369
- function isProtected(ip, list2) {
50370
- return list2.some((entry) => ipMatches(ip, entry));
50370
+ function isProtected(ip, list3) {
50371
+ return list3.some((entry) => ipMatches(ip, entry));
50371
50372
  }
50372
50373
  function currentSshClient(env3 = process.env) {
50373
50374
  const source = env3.SSH_CLIENT || env3.SSH_CONNECTION;
@@ -50452,7 +50453,7 @@ function defaultGateways() {
50452
50453
  // src/core/respond/ip.ts
50453
50454
  function refuseIp(ip, ctx) {
50454
50455
  if ((0, import_node_net6.isIP)(ip) === 0) return `not an IP address: ${ip}`;
50455
- const hit = (list2) => list2.find((entry) => ipMatches(ip, entry));
50456
+ const hit = (list3) => list3.find((entry) => ipMatches(ip, entry));
50456
50457
  let m = hit(DEFAULT_PROTECTED);
50457
50458
  if (m) return `${ip} is in a private/loopback range (${m}); refusing`;
50458
50459
  m = hit(SHARED_INFRASTRUCTURE);
@@ -54067,9 +54068,9 @@ function parseClamOutput(stdout) {
54067
54068
  for (const line2 of stdout.split(/\r?\n/)) {
54068
54069
  const m = /^(.*): (\S+) FOUND$/.exec(line2.trim());
54069
54070
  if (!m) continue;
54070
- const list2 = out.get(m[1]) ?? [];
54071
- list2.push(m[2]);
54072
- out.set(m[1], list2);
54071
+ const list3 = out.get(m[1]) ?? [];
54072
+ list3.push(m[2]);
54073
+ out.set(m[1], list3);
54073
54074
  }
54074
54075
  return out;
54075
54076
  }
@@ -54089,11 +54090,11 @@ async function clamScanFiles(info2, files, opts = {}) {
54089
54090
  const detections = /* @__PURE__ */ new Map();
54090
54091
  if (!info2.available || !info2.binary || files.length === 0) return { detections, error: null };
54091
54092
  const dir = await (0, import_promises2.mkdtemp)((0, import_node_path21.join)((0, import_node_os11.tmpdir)(), "crushav-"));
54092
- const list2 = (0, import_node_path21.join)(dir, "files.txt");
54093
+ const list3 = (0, import_node_path21.join)(dir, "files.txt");
54093
54094
  try {
54094
- await (0, import_promises2.writeFile)(list2, `${files.join("\n")}
54095
+ await (0, import_promises2.writeFile)(list3, `${files.join("\n")}
54095
54096
  `);
54096
- const args = ["--no-summary", "--infected", "--stdout", `--file-list=${list2}`];
54097
+ const args = ["--no-summary", "--infected", "--stdout", `--file-list=${list3}`];
54097
54098
  if (info2.mode === "clamdscan") args.push("--fdpass", "--multiscan");
54098
54099
  const r = await run2(info2.binary, args, opts.timeoutMs ?? 60 * 60 * 1e3, opts.signal);
54099
54100
  for (const [path2, sigs] of parseClamOutput(r.stdout)) detections.set(path2, sigs.map(clamDetection));
@@ -55725,23 +55726,23 @@ function sshArgv(options) {
55725
55726
  return args;
55726
55727
  }
55727
55728
  async function sshConnect(options) {
55728
- const { hostname: hostname7, port, username, identity } = options;
55729
- if (!hostname7) {
55729
+ const { hostname: hostname8, port, username, identity } = options;
55730
+ if (!hostname8) {
55730
55731
  console.log(source_default.red(" No hostname available for this server.\n"));
55731
55732
  return;
55732
55733
  }
55733
55734
  const user = username || "root";
55734
- const problem = sshTargetError({ hostname: hostname7, username: user, port });
55735
+ const problem = sshTargetError({ hostname: hostname8, username: user, port });
55735
55736
  if (problem) {
55736
55737
  console.log(source_default.red(` ${problem}
55737
55738
  `));
55738
55739
  process.exitCode = 1;
55739
55740
  return;
55740
55741
  }
55741
- console.log(source_default.green(` Connecting to ${user}@${hostname7}:${port}...
55742
+ console.log(source_default.green(` Connecting to ${user}@${hostname8}:${port}...
55742
55743
  `));
55743
55744
  console.log(source_default.dim(" (Spawning SSH session \u2014 exit with Ctrl+D or type 'exit')\n"));
55744
- const sshArgs = sshArgv({ hostname: hostname7, username: user, port, identity });
55745
+ const sshArgs = sshArgv({ hostname: hostname8, username: user, port, identity });
55745
55746
  const ssh = (0, import_node_child_process11.spawn)("ssh", sshArgs, { stdio: "inherit" });
55746
55747
  ssh.on("error", (err) => {
55747
55748
  console.log(source_default.red(`
@@ -55760,16 +55761,16 @@ async function sshConnect(options) {
55760
55761
  }
55761
55762
 
55762
55763
  // src/commands/daemon.ts
55763
- var import_node_child_process28 = require("child_process");
55764
- var import_node_fs69 = require("fs");
55765
- var import_node_path49 = require("path");
55766
- var import_node_fs70 = require("fs");
55764
+ var import_node_child_process29 = require("child_process");
55765
+ var import_node_fs71 = require("fs");
55766
+ var import_node_path50 = require("path");
55767
+ var import_node_fs72 = require("fs");
55767
55768
 
55768
55769
  // src/daemon/index.ts
55769
- var import_node_fs68 = require("fs");
55770
- var import_node_child_process27 = require("child_process");
55771
- var import_node_os20 = require("os");
55772
- var import_node_path48 = require("path");
55770
+ var import_node_fs70 = require("fs");
55771
+ var import_node_child_process28 = require("child_process");
55772
+ var import_node_os22 = require("os");
55773
+ var import_node_path49 = require("path");
55773
55774
  var import_node_util4 = require("util");
55774
55775
  init_paths();
55775
55776
 
@@ -58455,6 +58456,10 @@ var CloudSpool = class {
58455
58456
 
58456
58457
  // src/daemon/workers/cloud-sync.ts
58457
58458
  var MAX_BATCH_BYTES = 900 * 1024;
58459
+ function uploadSeverity(event) {
58460
+ const rule = event.details?.rule_severity;
58461
+ return typeof rule === "string" && rule in SEVERITY_RANK7 ? rule : event.severity;
58462
+ }
58458
58463
  var CloudSync = class {
58459
58464
  constructor(opts) {
58460
58465
  this.opts = opts;
@@ -58539,7 +58544,7 @@ var CloudSync = class {
58539
58544
  let out = null;
58540
58545
  if (event.module === "firewall-rules") {
58541
58546
  out = remediationEvent(link.serverId, event);
58542
- } else if ((event.module === "rule-engine" || !this.opts.ruleModules.has(event.module)) && event.details?.heartbeat !== true && SEVERITY_RANK7[event.severity] >= SEVERITY_RANK7[this.opts.minSeverity]) {
58547
+ } else if ((event.module === "rule-engine" || !this.opts.ruleModules.has(event.module)) && event.details?.heartbeat !== true && SEVERITY_RANK7[uploadSeverity(event)] >= SEVERITY_RANK7[this.opts.minSeverity]) {
58543
58548
  out = detectionEvent(link.serverId, event);
58544
58549
  }
58545
58550
  if (!out) return;
@@ -59091,11 +59096,11 @@ var import_node_net14 = require("net");
59091
59096
  init_cli_config();
59092
59097
  function isAddressOrCidr(value) {
59093
59098
  const [network, prefix, extra] = value.split("/");
59094
- const family = (0, import_node_net14.isIP)(network);
59095
- if (family === 0 || extra !== void 0) return false;
59099
+ const family2 = (0, import_node_net14.isIP)(network);
59100
+ if (family2 === 0 || extra !== void 0) return false;
59096
59101
  if (prefix === void 0) return true;
59097
59102
  if (!/^\d{1,3}$/.test(prefix)) return false;
59098
- return Number(prefix) <= (family === 4 ? 32 : 128);
59103
+ return Number(prefix) <= (family2 === 4 ? 32 : 128);
59099
59104
  }
59100
59105
  var CLOUD_MIN_PREFIX = { 4: 8, 6: 16 };
59101
59106
  function isCloudAllowEntry(value) {
@@ -63116,9 +63121,9 @@ var PostgresShellWatch = class {
63116
63121
  if (!root) return [];
63117
63122
  const children = /* @__PURE__ */ new Map();
63118
63123
  for (const e of entries2.values()) {
63119
- const list2 = children.get(e.ppid) ?? [];
63120
- list2.push(e.pid);
63121
- children.set(e.ppid, list2);
63124
+ const list3 = children.get(e.ppid) ?? [];
63125
+ list3.push(e.pid);
63126
+ children.set(e.ppid, list3);
63122
63127
  }
63123
63128
  const order2 = [];
63124
63129
  const visit = (pid, depth) => {
@@ -63367,9 +63372,9 @@ var DockerLogsWatch = class {
63367
63372
  if (this.stopped) return;
63368
63373
  const now = Date.now();
63369
63374
  const previous = this.lastPoll;
63370
- let list2;
63375
+ let list3;
63371
63376
  try {
63372
- list2 = await this.deps.getJson("/containers/json");
63377
+ list3 = await this.deps.getJson("/containers/json");
63373
63378
  this.warned = false;
63374
63379
  } catch (err) {
63375
63380
  if (!this.warned) this.opts.log(`[docker-logs] cannot list containers: ${err.message}`);
@@ -63378,7 +63383,7 @@ var DockerLogsWatch = class {
63378
63383
  }
63379
63384
  this.lastPoll = now;
63380
63385
  const running = /* @__PURE__ */ new Set();
63381
- for (const c of Array.isArray(list2) ? list2 : []) {
63386
+ for (const c of Array.isArray(list3) ? list3 : []) {
63382
63387
  if (!c?.Id || !this.matches(c)) continue;
63383
63388
  running.add(c.Id);
63384
63389
  if (this.follows.has(c.Id)) continue;
@@ -64106,6 +64111,8 @@ function evidenceOf(event) {
64106
64111
  const v = details[k];
64107
64112
  if (typeof v === "string" || typeof v === "number") out[k] = String(v).slice(0, EVIDENCE_FIELD_CHARS);
64108
64113
  }
64114
+ const ctx = details.ssh_context;
64115
+ if (ctx && typeof ctx === "object" && !Array.isArray(ctx) && ctx.v === 1) out.ssh_context = ctx;
64109
64116
  return out;
64110
64117
  }
64111
64118
  var RuleEngine = class {
@@ -64257,10 +64264,655 @@ var RuleEngine = class {
64257
64264
  }
64258
64265
  };
64259
64266
 
64260
- // src/daemon/rules/loader.ts
64261
- var import_node_fs64 = require("fs");
64267
+ // src/daemon/ssh-context/index.ts
64268
+ var import_node_os21 = require("os");
64262
64269
  var import_node_path45 = require("path");
64263
64270
 
64271
+ // ../../packages/event-detail/src/verdict.ts
64272
+ var RANK = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
64273
+ function maxSeverity2(a, b) {
64274
+ return RANK[a] >= RANK[b] ? a : b;
64275
+ }
64276
+ function severityRank2(s) {
64277
+ return RANK[s ?? "info"] ?? 0;
64278
+ }
64279
+ function describeFailures(f, ip) {
64280
+ if (!f) return null;
64281
+ const mins = Math.max(1, Math.round(f.window_s / 60));
64282
+ if (f.total === 0) {
64283
+ return `No failed SSH attempts in the ${mins} min before this login (the rule fires on every accepted login).`;
64284
+ }
64285
+ const top = (f.ips ?? []).filter((x) => x.ip !== ip).slice(0, 3).map((x) => `${x.ip} x${x.count}`).join(", ");
64286
+ const users = (f.users ?? []).slice(0, 4).map((u) => u.user).join(", ");
64287
+ const span2 = f.first && f.last ? ` between ${hhmmss(f.first)} and ${hhmmss(f.last)} UTC` : "";
64288
+ if (f.same_ip > 0 && f.other_ips === 0) {
64289
+ return `${f.same_ip} failed attempt${f.same_ip === 1 ? "" : "s"} from this same address${span2}${users ? ` (users: ${users})` : ""}, then this login succeeded: a guessed or brute-forced credential is possible.`;
64290
+ }
64291
+ if (f.same_ip === 0) {
64292
+ return `${f.total} failed attempt${f.total === 1 ? "" : "s"} in the ${mins} min before, all from OTHER addresses${top ? ` (${top})` : ""}${users ? `, users: ${users}` : ""}. None came from this address, so this is not a brute force that succeeded.`;
64293
+ }
64294
+ return `${f.total} failed attempt${f.total === 1 ? "" : "s"} in the ${mins} min before: ${f.same_ip} from this address and ${f.other_ips} from others${top ? ` (${top})` : ""}${users ? `, users: ${users}` : ""}.`;
64295
+ }
64296
+ function hhmmss(iso) {
64297
+ const d = new Date(iso);
64298
+ return Number.isNaN(d.getTime()) ? iso : d.toISOString().slice(11, 19);
64299
+ }
64300
+ function computeVerdict(ctx) {
64301
+ const reasons = [];
64302
+ const key = ctx.key;
64303
+ const src = ctx.source;
64304
+ const ci = ctx.session?.ci_deploy;
64305
+ const forced = !!key?.command;
64306
+ const restricted = forced || !!key?.from;
64307
+ const publicSrc = !src || src.kind === "public" || src.kind === "github-actions";
64308
+ const ghActions = src?.kind === "github-actions";
64309
+ let severity = "info";
64310
+ let level = "review";
64311
+ const raise = (s, why) => {
64312
+ severity = maxSeverity2(severity, s);
64313
+ reasons.push(why);
64314
+ };
64315
+ if (key?.in_root_and_user) raise("critical", "the same key authorizes root and another account");
64316
+ if (key?.suspicious_comment) raise(restricted ? "high" : "critical", `key comment "${key.comment}" looks like a dated temporary CI/diagnostic key`);
64317
+ if (ctx.failures && ctx.failures.same_ip > 0) raise("critical", `${ctx.failures.same_ip} failed attempt(s) from this same address before it succeeded`);
64318
+ if (ci && /^deny/i.test(ci.decision)) raise("high", `ci-deploy DENIED${ci.repo ? ` ${ci.repo}` : ""}`);
64319
+ if (publicSrc && ctx.auth_method === "password") raise("critical", "password login from a public address");
64320
+ if (publicSrc && !ghActions && key?.found && !restricted && !key.restrict) raise("critical", "unrestricted key (no command=, from= or restrict) from a non-CI address");
64321
+ if (publicSrc && key && !key.found && ctx.auth_method === "publickey") raise("high", "key not found in any readable authorized_keys (another account, or AuthorizedKeysCommand)");
64322
+ if (forced && publicSrc && !ghActions) raise("medium", "forced-command key used from an address outside GitHub Actions");
64323
+ const red3 = severityRank2(severity) >= RANK.high;
64324
+ if (key?.expected && !red3) {
64325
+ level = "expected";
64326
+ severity = "info";
64327
+ reasons.unshift(`key marked as expected CI${key.comment ? ` (${key.comment})` : ""}`);
64328
+ } else if (ghActions && forced && !red3) {
64329
+ level = "likely-ci";
64330
+ severity = "low";
64331
+ reasons.unshift("GitHub Actions IP", "forced-command deploy key");
64332
+ if (ci && /^allow/i.test(ci.decision)) reasons.push(`ci-deploy ALLOW ${ci.action || ci.repo || ""}`.trim());
64333
+ } else if (src && ["loopback", "self", "tailscale", "private"].includes(src.kind) && !red3) {
64334
+ level = "internal";
64335
+ severity = maxSeverity2("low", severity);
64336
+ reasons.unshift(src.kind === "tailscale" ? "Tailscale address" : src.kind === "self" ? "one of this host's own addresses" : src.kind === "loopback" ? "loopback" : "private address");
64337
+ } else if (red3) {
64338
+ level = "suspicious";
64339
+ } else {
64340
+ severity = maxSeverity2("high", severity);
64341
+ if (!reasons.length) reasons.push(ghActions ? "GitHub Actions address but not a forced-command key" : "login from a public address");
64342
+ }
64343
+ return { level, severity, summary: verdictSummary(level, reasons, ctx), reasons };
64344
+ }
64345
+ function verdictSummary(level, reasons, ctx) {
64346
+ const head2 = {
64347
+ expected: "Expected CI key",
64348
+ "likely-ci": "Likely CI deploy",
64349
+ internal: "Internal login",
64350
+ review: "Review",
64351
+ suspicious: "Suspicious login"
64352
+ };
64353
+ if (level === "review" && reasons.length === 1 && /public address$/.test(reasons[0])) {
64354
+ const restricted = ctx.key?.command || ctx.key?.from;
64355
+ return `${head2.review}: ${restricted ? "restricted" : "unrestricted"} ${ctx.auth_method ?? "login"} from ${ctx.source?.ip ?? "a public address"}`;
64356
+ }
64357
+ return `${head2[level]}: ${reasons.join(", ")}`;
64358
+ }
64359
+
64360
+ // src/daemon/ssh-context/auth-history.ts
64361
+ var MAX_ENTRIES2 = 2e4;
64362
+ var KEEP_MS = 60 * 60 * 1e3;
64363
+ var SAME_ATTEMPT_MS = 1e4;
64364
+ function classifySshdMessage(message) {
64365
+ let m = /^Failed (?:password|publickey|none|keyboard-interactive\/pam|keyboard-interactive|hostbased) for (?:invalid user )?(\S+) from \S+ port (\d+)/.exec(message);
64366
+ if (m) return { kind: "failed", user: m[1], port: Number(m[2]) };
64367
+ m = /^Invalid user (\S*) from \S+(?: port (\d+))?/.exec(message);
64368
+ if (m) return { kind: "invalid", user: m[1] || "(empty)", port: m[2] ? Number(m[2]) : void 0 };
64369
+ m = /^(?:Connection closed by|Disconnected from) (?:authenticating|invalid) user (\S+) \S+ port (\d+)/.exec(message);
64370
+ if (m) return { kind: "preauth-close", user: m[1], port: Number(m[2]) };
64371
+ m = /^Disconnected from user (\S+) \S+ port (\d+)/.exec(message);
64372
+ if (m) return { kind: "close", user: m[1], port: Number(m[2]) };
64373
+ m = /^Received disconnect from \S+ port (\d+):\d+: .*disconnected by user/i.exec(message);
64374
+ if (m && !/\[preauth\]/.test(message)) return { kind: "close", port: Number(m[1]) };
64375
+ return null;
64376
+ }
64377
+ var SshAuthHistory = class {
64378
+ constructor(now = Date.now) {
64379
+ this.now = now;
64380
+ }
64381
+ now;
64382
+ failures = [];
64383
+ closes = [];
64384
+ seen = /* @__PURE__ */ new Map();
64385
+ record(line2) {
64386
+ const at = line2.timestamp instanceof Date ? line2.timestamp.getTime() : Date.now();
64387
+ if (Number.isNaN(at)) return;
64388
+ const key = `${at}|${line2.message}`;
64389
+ if (this.seen.has(key)) return;
64390
+ this.seen.set(key, at);
64391
+ const c = classifySshdMessage(line2.message);
64392
+ if (!c) return;
64393
+ if (c.kind === "close") {
64394
+ if (c.port) this.closes.push({ at, ip: line2.ip, port: c.port, user: c.user });
64395
+ } else {
64396
+ const user = c.user ?? "unknown";
64397
+ const same = [];
64398
+ if (c.port !== void 0) {
64399
+ for (let i = this.failures.length - 1; i >= 0; i--) {
64400
+ const f = this.failures[i];
64401
+ if (f.at < at - SAME_ATTEMPT_MS) break;
64402
+ if (f.ip === line2.ip && f.port === c.port) same.push(f);
64403
+ }
64404
+ }
64405
+ if (c.kind === "failed") {
64406
+ const placeholder = same.find((f) => f.kind !== "failed");
64407
+ if (placeholder) {
64408
+ placeholder.kind = "failed";
64409
+ placeholder.user = user;
64410
+ } else this.failures.push({ at, ip: line2.ip, user, kind: c.kind, port: c.port });
64411
+ } else if (same.length === 0) {
64412
+ this.failures.push({ at, ip: line2.ip, user, kind: c.kind, port: c.port });
64413
+ }
64414
+ }
64415
+ this.prune();
64416
+ }
64417
+ prune() {
64418
+ const cutoff = this.now() - KEEP_MS;
64419
+ if (this.failures.length > MAX_ENTRIES2) this.failures.splice(0, this.failures.length - MAX_ENTRIES2);
64420
+ if (this.closes.length > MAX_ENTRIES2) this.closes.splice(0, this.closes.length - MAX_ENTRIES2);
64421
+ while (this.failures.length && this.failures[0].at < cutoff) this.failures.shift();
64422
+ while (this.closes.length && this.closes[0].at < cutoff) this.closes.shift();
64423
+ if (this.seen.size > MAX_ENTRIES2) {
64424
+ let drop = this.seen.size - MAX_ENTRIES2 / 2;
64425
+ for (const k of this.seen.keys()) {
64426
+ if (drop-- <= 0) break;
64427
+ this.seen.delete(k);
64428
+ }
64429
+ }
64430
+ }
64431
+ /** Failures in the `windowS` seconds up to `atMs`, grouped, relative to the address that logged in. */
64432
+ failuresBefore(atMs, ip, windowS = 600) {
64433
+ const from = atMs - windowS * 1e3;
64434
+ const hits = this.failures.filter((f) => f.at >= from && f.at <= atMs + 1e3);
64435
+ const byIp = /* @__PURE__ */ new Map();
64436
+ const byUser = /* @__PURE__ */ new Map();
64437
+ for (const f of hits) {
64438
+ byIp.set(f.ip, (byIp.get(f.ip) ?? 0) + 1);
64439
+ byUser.set(f.user, (byUser.get(f.user) ?? 0) + 1);
64440
+ }
64441
+ const sameIp = byIp.get(ip) ?? 0;
64442
+ const top = (m, k) => [...m.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10).map(([v, count]) => ({ [k]: v, count }));
64443
+ return {
64444
+ window_s: windowS,
64445
+ total: hits.length,
64446
+ same_ip: sameIp,
64447
+ other_ips: hits.length - sameIp,
64448
+ ...hits.length ? {
64449
+ ips: top(byIp, "ip"),
64450
+ users: top(byUser, "user"),
64451
+ first: new Date(Math.min(...hits.map((h) => h.at))).toISOString(),
64452
+ last: new Date(Math.max(...hits.map((h) => h.at))).toISOString()
64453
+ } : {}
64454
+ };
64455
+ }
64456
+ /** When the session from `ip`:`port` closed, if it has. */
64457
+ closeOf(ip, port, afterMs) {
64458
+ if (!port) return null;
64459
+ const c = this.closes.find((x) => x.ip === ip && x.port === port && x.at >= afterMs - 1e3);
64460
+ return c ? c.at : null;
64461
+ }
64462
+ };
64463
+
64464
+ // src/daemon/ssh-context/authorized-keys.ts
64465
+ var import_node_fs64 = require("fs");
64466
+ var realKeyFilesIO = {
64467
+ passwd: () => {
64468
+ try {
64469
+ return (0, import_node_fs64.readFileSync)("/etc/passwd", "utf-8");
64470
+ } catch {
64471
+ return "";
64472
+ }
64473
+ },
64474
+ mtime: (p) => {
64475
+ try {
64476
+ return (0, import_node_fs64.statSync)(p).mtimeMs;
64477
+ } catch {
64478
+ return null;
64479
+ }
64480
+ },
64481
+ read: (p) => {
64482
+ try {
64483
+ return (0, import_node_fs64.readFileSync)(p, "utf-8");
64484
+ } catch {
64485
+ return null;
64486
+ }
64487
+ }
64488
+ };
64489
+ var NOLOGIN = /(?:nologin|false|sync|halt|shutdown)$/;
64490
+ function maskBlob(blob) {
64491
+ return `${blob.slice(0, 8)}\u2026[masked]`;
64492
+ }
64493
+ function optionText(o) {
64494
+ return o.value === null ? o.name : `${o.name}="${o.value.replace(/"/g, '\\"')}"`;
64495
+ }
64496
+ var MAX_OPTION_CHARS = 300;
64497
+ function maskedLine(k) {
64498
+ const opts = k.options.map((o) => optionText(o).slice(0, MAX_OPTION_CHARS)).join(",");
64499
+ return [opts, k.type, maskBlob(k.blob), k.comment].filter(Boolean).join(" ");
64500
+ }
64501
+ var AuthorizedKeysIndex = class {
64502
+ constructor(io = realKeyFilesIO) {
64503
+ this.io = io;
64504
+ }
64505
+ io;
64506
+ files = /* @__PURE__ */ new Map();
64507
+ accounts() {
64508
+ return parsePasswd(this.io.passwd()).filter((p) => p.uid === 0 || p.home && p.home !== "/" && !NOLOGIN.test(p.shell)).map((p) => ({ name: p.name, home: p.home.replace(/\/$/, "") }));
64509
+ }
64510
+ keysIn(path2, user) {
64511
+ const mtime = this.io.mtime(path2);
64512
+ if (mtime === null) {
64513
+ this.files.delete(path2);
64514
+ return [];
64515
+ }
64516
+ const cached = this.files.get(path2);
64517
+ if (cached && cached.mtime === mtime) return cached.keys;
64518
+ const keys = parseAuthorizedKeys(this.io.read(path2) ?? "", path2).map((k) => ({ ...k, user }));
64519
+ this.files.set(path2, { mtime, keys });
64520
+ return keys;
64521
+ }
64522
+ /** Every authorized_keys line carrying `fingerprint`, as login context. */
64523
+ lookup(fingerprint, expected = /* @__PURE__ */ new Set()) {
64524
+ const matches2 = [];
64525
+ for (const { name, home } of this.accounts()) {
64526
+ for (const f of ["authorized_keys", "authorized_keys2"]) {
64527
+ for (const k2 of this.keysIn(`${home}/.ssh/${f}`, name)) if (k2.fingerprint === fingerprint) matches2.push(k2);
64528
+ }
64529
+ }
64530
+ if (!matches2.length) return { found: false, fingerprint, ...expected.has(fingerprint) ? { expected: true } : {} };
64531
+ const k = matches2.find((m) => !m.command && !m.from && !m.restrict) ?? matches2[0];
64532
+ const accounts = [...new Set(matches2.map((m) => m.user))];
64533
+ const inRoot = matches2.some((m) => m.user === "root" || m.file.startsWith("/root/"));
64534
+ const inOther = matches2.some((m) => m.user !== "root" && !m.file.startsWith("/root/"));
64535
+ return {
64536
+ found: true,
64537
+ type: k.type,
64538
+ fingerprint,
64539
+ comment: k.comment.slice(0, 200) || void 0,
64540
+ options: k.options.map((o) => optionText(o).slice(0, MAX_OPTION_CHARS)),
64541
+ command: k.command ? k.command.slice(0, 500) : null,
64542
+ from: k.from ? k.from.slice(0, 300) : null,
64543
+ restrict: k.restrict,
64544
+ files: matches2.map((m) => `${m.file}:${m.line}`).slice(0, 10),
64545
+ accounts,
64546
+ line_masked: maskedLine(k).slice(0, 800),
64547
+ in_root_and_user: inRoot && inOther,
64548
+ suspicious_comment: suspiciousKeyComment(k.comment),
64549
+ ...expected.has(fingerprint) ? { expected: true } : {}
64550
+ };
64551
+ }
64552
+ };
64553
+
64554
+ // src/daemon/ssh-context/ip-intel.ts
64555
+ var import_node_net22 = require("net");
64556
+ var import_node_os20 = require("os");
64557
+ var import_node_dns2 = require("dns");
64558
+ var import_node_fs65 = require("fs");
64559
+ function list2(entries2) {
64560
+ const b = new import_node_net22.BlockList();
64561
+ for (const [a, p, f] of entries2) b.addSubnet(a, p, f);
64562
+ return b;
64563
+ }
64564
+ var LOOPBACK = list2([["127.0.0.0", 8, "ipv4"], ["::1", 128, "ipv6"]]);
64565
+ var TAILSCALE = list2([["100.64.0.0", 10, "ipv4"], ["fd7a:115c:a1e0::", 48, "ipv6"]]);
64566
+ var PRIVATE = list2([
64567
+ ["10.0.0.0", 8, "ipv4"],
64568
+ ["172.16.0.0", 12, "ipv4"],
64569
+ ["192.168.0.0", 16, "ipv4"],
64570
+ ["169.254.0.0", 16, "ipv4"],
64571
+ ["fc00::", 7, "ipv6"],
64572
+ ["fe80::", 10, "ipv6"]
64573
+ ]);
64574
+ function family(ip) {
64575
+ const f = (0, import_node_net22.isIP)(ip);
64576
+ return f === 4 ? "ipv4" : f === 6 ? "ipv6" : null;
64577
+ }
64578
+ function normalizeIp2(ip) {
64579
+ const m = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(ip);
64580
+ return m ? m[1] : ip;
64581
+ }
64582
+ function ownAddresses() {
64583
+ const out = /* @__PURE__ */ new Set();
64584
+ try {
64585
+ for (const list3 of Object.values((0, import_node_os20.networkInterfaces)())) for (const a of list3 ?? []) out.add(a.address.split("%")[0]);
64586
+ } catch {
64587
+ }
64588
+ return out;
64589
+ }
64590
+ function classifyAddress(raw, c) {
64591
+ const ip = normalizeIp2(raw);
64592
+ const f = family(ip);
64593
+ if (!f) return "public";
64594
+ if (LOOPBACK.check(ip, f)) return "loopback";
64595
+ if (c.own().has(ip)) return "self";
64596
+ if (TAILSCALE.check(ip, f)) return "tailscale";
64597
+ if (PRIVATE.check(ip, f)) return "private";
64598
+ if (c.isGitHubActions(ip)) return "github-actions";
64599
+ return "public";
64600
+ }
64601
+ var META_URL = "https://api.github.com/meta";
64602
+ var DAY_MS = 24 * 60 * 60 * 1e3;
64603
+ var RETRY_MS = 30 * 60 * 1e3;
64604
+ function rangesDeps(cacheFile) {
64605
+ return {
64606
+ fetchJson: async (url) => {
64607
+ const res = await fetch(url, {
64608
+ headers: { accept: "application/vnd.github+json", "user-agent": "threatcrush-agent" },
64609
+ signal: AbortSignal.timeout(15e3)
64610
+ });
64611
+ if (!res.ok) throw new Error(`GitHub meta ${res.status}`);
64612
+ return res.json();
64613
+ },
64614
+ load: () => {
64615
+ try {
64616
+ const v = JSON.parse((0, import_node_fs65.readFileSync)(cacheFile, "utf-8"));
64617
+ return typeof v.at === "number" && Array.isArray(v.cidrs) ? { at: v.at, cidrs: v.cidrs.map(String) } : null;
64618
+ } catch {
64619
+ return null;
64620
+ }
64621
+ },
64622
+ save: (v) => {
64623
+ try {
64624
+ (0, import_node_fs65.writeFileSync)(cacheFile, JSON.stringify(v), { mode: 420 });
64625
+ } catch {
64626
+ }
64627
+ },
64628
+ now: Date.now
64629
+ };
64630
+ }
64631
+ var GitHubActionsRanges = class {
64632
+ constructor(deps, enabled = true) {
64633
+ this.deps = deps;
64634
+ this.enabled = enabled;
64635
+ const saved = enabled ? deps.load() : null;
64636
+ if (saved?.cidrs.length) this.set(saved.cidrs, saved.at);
64637
+ }
64638
+ deps;
64639
+ enabled;
64640
+ list = null;
64641
+ count = 0;
64642
+ at = 0;
64643
+ lastTry = 0;
64644
+ inflight = null;
64645
+ set(cidrs, at) {
64646
+ const b = new import_node_net22.BlockList();
64647
+ let n = 0;
64648
+ for (const c of cidrs) {
64649
+ const [addr, bits2] = c.split("/");
64650
+ const f = family(addr);
64651
+ const p = Number(bits2);
64652
+ if (!f || !Number.isInteger(p)) continue;
64653
+ try {
64654
+ b.addSubnet(addr, p, f);
64655
+ n++;
64656
+ } catch {
64657
+ }
64658
+ }
64659
+ if (n) {
64660
+ this.list = b;
64661
+ this.count = n;
64662
+ this.at = at;
64663
+ }
64664
+ }
64665
+ size() {
64666
+ return this.count;
64667
+ }
64668
+ /** Refresh when stale; never throws, never blocks a lookup for long. */
64669
+ async refresh() {
64670
+ if (!this.enabled) return;
64671
+ const now = this.deps.now();
64672
+ if (this.list && now - this.at < DAY_MS) return;
64673
+ if (now - this.lastTry < RETRY_MS) return;
64674
+ this.inflight ??= (async () => {
64675
+ this.lastTry = now;
64676
+ try {
64677
+ const body = await this.deps.fetchJson(META_URL);
64678
+ const cidrs = Array.isArray(body?.actions) ? body.actions.filter((c) => typeof c === "string") : [];
64679
+ if (cidrs.length) {
64680
+ this.set(cidrs, now);
64681
+ this.deps.save({ at: now, cidrs });
64682
+ }
64683
+ } catch {
64684
+ }
64685
+ })().finally(() => {
64686
+ this.inflight = null;
64687
+ });
64688
+ return this.inflight;
64689
+ }
64690
+ has(raw) {
64691
+ const ip = normalizeIp2(raw);
64692
+ const f = family(ip);
64693
+ return !!(this.list && f && this.list.check(ip, f));
64694
+ }
64695
+ };
64696
+ var realNetLookup = {
64697
+ reverse: (ip) => import_node_dns2.promises.reverse(ip),
64698
+ txt: (name) => import_node_dns2.promises.resolveTxt(name)
64699
+ };
64700
+ function withTimeout2(p, ms) {
64701
+ return Promise.race([p.catch(() => null), new Promise((r) => setTimeout(() => r(null), ms).unref?.())]);
64702
+ }
64703
+ function cymruOriginName2(raw) {
64704
+ const ip = normalizeIp2(raw);
64705
+ const f = (0, import_node_net22.isIP)(ip);
64706
+ if (f === 4) return `${ip.split(".").reverse().join(".")}.origin.asn.cymru.com`;
64707
+ if (f !== 6) return null;
64708
+ const parts = ip.split("::");
64709
+ const head2 = parts[0] ? parts[0].split(":") : [];
64710
+ const tail = parts.length > 1 && parts[1] ? parts[1].split(":") : [];
64711
+ const groups = [...head2, ...Array(8 - head2.length - tail.length).fill("0"), ...tail].map((g) => g.padStart(4, "0"));
64712
+ return `${groups.join("").split("").reverse().join(".")}.origin6.asn.cymru.com`;
64713
+ }
64714
+ function parseCymruOrigin2(txt) {
64715
+ const f = txt.split("|").map((s) => s.trim());
64716
+ const asn = Number((f[0] ?? "").split(/\s+/)[0]);
64717
+ if (!Number.isInteger(asn) || asn <= 0) return null;
64718
+ return { asn, country: f[2] && /^[A-Z]{2}$/.test(f[2]) ? f[2] : null };
64719
+ }
64720
+ function parseCymruAsName(txt) {
64721
+ const f = txt.split("|").map((s) => s.trim());
64722
+ const name = f[4]?.replace(/,\s*[A-Z]{2}$/, "").trim();
64723
+ return name ? name.slice(0, 120) : null;
64724
+ }
64725
+ var NetLookup = class {
64726
+ constructor(deps = realNetLookup, timeoutMs = 2500, now = Date.now) {
64727
+ this.deps = deps;
64728
+ this.timeoutMs = timeoutMs;
64729
+ this.now = now;
64730
+ }
64731
+ deps;
64732
+ timeoutMs;
64733
+ now;
64734
+ cache = /* @__PURE__ */ new Map();
64735
+ async lookup(ip) {
64736
+ const hit = this.cache.get(ip);
64737
+ if (hit && this.now() - hit.at < 6 * 60 * 60 * 1e3) return hit.v;
64738
+ const originName = cymruOriginName2(ip);
64739
+ const [names, origin] = await Promise.all([
64740
+ withTimeout2(this.deps.reverse(normalizeIp2(ip)), this.timeoutMs),
64741
+ originName ? withTimeout2(this.deps.txt(originName), this.timeoutMs) : Promise.resolve(null)
64742
+ ]);
64743
+ const o = origin?.[0] ? parseCymruOrigin2(origin[0].join("")) : null;
64744
+ let asOrg = null;
64745
+ if (o) {
64746
+ const named = await withTimeout2(this.deps.txt(`AS${o.asn}.asn.cymru.com`), this.timeoutMs);
64747
+ asOrg = named?.[0] ? parseCymruAsName(named[0].join("")) : null;
64748
+ }
64749
+ const v = { rdns: names?.[0]?.slice(0, 253) ?? null, asn: o?.asn ?? null, as_org: asOrg, country: o?.country ?? null };
64750
+ if (this.cache.size > 2e3) this.cache.clear();
64751
+ this.cache.set(ip, { at: this.now(), v });
64752
+ return v;
64753
+ }
64754
+ };
64755
+
64756
+ // src/daemon/ssh-context/ci-deploy.ts
64757
+ var import_node_child_process24 = require("child_process");
64758
+ var SECRETISH = /\b([A-Za-z_]*(?:token|secret|password|passwd|apikey|api_key|key|auth)[A-Za-z_]*)=("[^"]*"|'[^']*'|\S+)/gi;
64759
+ function redactCommand(cmd) {
64760
+ return cmd.replace(SECRETISH, "$1=[redacted]").slice(0, 300);
64761
+ }
64762
+ function parseCiDeployMessage(message) {
64763
+ const m = /^\s*(ALLOW|DENY|DENIED|REJECT(?:ED)?)\b\s*(?:\(([^)]*)\))?(.*)$/i.exec(message);
64764
+ if (!m) return null;
64765
+ const rest = m[3] ?? "";
64766
+ const repo = /\brepo=(\S+)/.exec(rest)?.[1];
64767
+ const from = /\bfrom=(\S+)/.exec(rest)?.[1];
64768
+ const cmd = /\bcmd=(.*)$/.exec(rest)?.[1]?.trim();
64769
+ return {
64770
+ decision: m[1].toUpperCase().startsWith("ALLOW") ? "ALLOW" : "DENY",
64771
+ ...m[2] ? { action: m[2].trim().slice(0, 200) } : {},
64772
+ ...repo ? { repo: repo.slice(0, 200) } : {},
64773
+ ...from ? { from } : {},
64774
+ ...cmd ? { command: redactCommand(cmd) } : {}
64775
+ };
64776
+ }
64777
+ function parseCiDeployJournal(text, tag = "ci-deploy") {
64778
+ const out = [];
64779
+ const esc = tag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
64780
+ const re = new RegExp(`^(\\d+(?:\\.\\d+)?)\\s+\\S+\\s+${esc}(?:\\[\\d+\\])?:\\s(.*)$`);
64781
+ for (const line2 of text.split("\n")) {
64782
+ const m = re.exec(line2);
64783
+ if (!m) continue;
64784
+ const parsed = parseCiDeployMessage(m[2]);
64785
+ if (!parsed) continue;
64786
+ const atMs = Math.round(Number(m[1]) * 1e3);
64787
+ out.push({ ...parsed, atMs, at: new Date(atMs).toISOString() });
64788
+ }
64789
+ return out;
64790
+ }
64791
+ function pickCiDeploy(lines, ip, atMs) {
64792
+ const near = lines.filter((l) => l.from === ip && l.atMs !== void 0 && l.atMs >= atMs - 5e3 && l.atMs <= atMs + 6e4).sort((a, b) => Math.abs(a.atMs - atMs) - Math.abs(b.atMs - atMs));
64793
+ if (!near.length) return null;
64794
+ const { from: _from, atMs: _at, ...ctx } = near[0];
64795
+ return ctx;
64796
+ }
64797
+ var realJournal = (args) => new Promise((resolve9) => {
64798
+ (0, import_node_child_process24.execFile)("journalctl", args, { timeout: 4e3, maxBuffer: 1024 * 1024, encoding: "utf-8" }, (err, stdout) => resolve9(err ? null : stdout));
64799
+ });
64800
+ async function findCiDeploy(ip, atMs, tag = "ci-deploy", run3 = realJournal) {
64801
+ const s = Math.floor(atMs / 1e3);
64802
+ const out = await run3(["-t", tag, `--since=@${s - 5}`, `--until=@${s + 60}`, "-o", "short-unix", "--no-pager", "-q"]);
64803
+ return out ? pickCiDeploy(parseCiDeployJournal(out, tag), ip, atMs) : null;
64804
+ }
64805
+
64806
+ // src/daemon/ssh-context/index.ts
64807
+ function sshContextSettings(s) {
64808
+ const settle2 = Number(s?.settle_ms);
64809
+ const win = Number(s?.failure_window_seconds);
64810
+ return {
64811
+ enabled: s?.enabled !== false,
64812
+ networkLookups: s?.network_lookups !== false,
64813
+ githubRanges: s?.github_actions_ranges !== false,
64814
+ expectedKeys: new Set((Array.isArray(s?.expected_keys) ? s.expected_keys : []).map(String).filter((k) => k.startsWith("SHA256:"))),
64815
+ ciDeployTag: typeof s?.ci_deploy_tag === "string" && /^[\w.-]{1,64}$/.test(s.ci_deploy_tag) ? s.ci_deploy_tag : "ci-deploy",
64816
+ failureWindowS: Number.isFinite(win) && win >= 60 && win <= 86400 ? win : 600,
64817
+ settleMs: Number.isFinite(settle2) && settle2 >= 0 ? Math.min(settle2, 2e4) : 5e3
64818
+ };
64819
+ }
64820
+ function isAcceptedLogin(event) {
64821
+ return event.module === "ssh-guard" && /SSH login accepted/.test(event.message) && !!event.source_ip;
64822
+ }
64823
+ var SshLoginEnricher = class {
64824
+ constructor(settings, deps = {}) {
64825
+ this.settings = settings;
64826
+ this.deps = deps;
64827
+ const now = deps.now ?? Date.now;
64828
+ this.history = deps.history ?? new SshAuthHistory(now);
64829
+ this.keys = deps.keys ?? new AuthorizedKeysIndex();
64830
+ this.ranges = deps.ranges ?? new GitHubActionsRanges(rangesDeps((0, import_node_path45.join)(deps.stateDir ?? ".", "github-actions-ranges.json")), settings.githubRanges);
64831
+ this.net = deps.net ?? new NetLookup();
64832
+ this.sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
64833
+ this.host = deps.host ?? (0, import_node_os21.hostname)();
64834
+ const own = deps.own ?? (() => {
64835
+ if (now() - this.ownCache.at > 6e4) this.ownCache = { at: now(), v: ownAddresses() };
64836
+ return this.ownCache.v;
64837
+ });
64838
+ this.classifier = { own, isGitHubActions: (ip) => this.ranges.has(ip) };
64839
+ }
64840
+ settings;
64841
+ deps;
64842
+ history;
64843
+ keys;
64844
+ ranges;
64845
+ net;
64846
+ classifier;
64847
+ sleep;
64848
+ host;
64849
+ ownCache = { at: -Infinity, v: /* @__PURE__ */ new Set() };
64850
+ /** Warm the GitHub ranges at start-up; safe to call any time. */
64851
+ start() {
64852
+ if (this.settings.enabled) void this.ranges.refresh();
64853
+ }
64854
+ recordSshd(line2) {
64855
+ if (this.settings.enabled) this.history.record(line2);
64856
+ }
64857
+ wants(event) {
64858
+ return this.settings.enabled && isAcceptedLogin(event) && !("ssh_context" in (event.details ?? {}));
64859
+ }
64860
+ /** Adds `details.ssh_context` to the event in place and returns it. Never throws. */
64861
+ async enrich(event) {
64862
+ try {
64863
+ const d = event.details ??= {};
64864
+ const ip = normalizeIp2(event.source_ip ?? "");
64865
+ const atMs = event.timestamp instanceof Date ? event.timestamp.getTime() : Date.now();
64866
+ const user = typeof d.ssh_user === "string" ? d.ssh_user : /SSH login accepted for (\S+)/.exec(event.message)?.[1];
64867
+ const method = typeof d.auth_method === "string" ? d.auth_method : void 0;
64868
+ const fp = typeof d.fingerprint === "string" && d.fingerprint.startsWith("SHA256:") ? d.fingerprint : void 0;
64869
+ const port = typeof d.port === "number" ? d.port : Number(d.port) || void 0;
64870
+ await this.ranges.refresh();
64871
+ const kind = classifyAddress(ip, this.classifier);
64872
+ const key = fp ? this.keys.lookup(fp, this.settings.expectedKeys) : void 0;
64873
+ if (key && !key.type && typeof d.key_type === "string") key.type = d.key_type;
64874
+ const failures = this.history.failuresBefore(atMs, ip, this.settings.failureWindowS);
64875
+ const netP = this.settings.networkLookups && (kind === "public" || kind === "github-actions") ? this.net.lookup(ip).catch(() => null) : Promise.resolve(null);
64876
+ const settle2 = this.sleep(this.settings.settleMs);
64877
+ const [net] = await Promise.all([netP, settle2]);
64878
+ const ci = key?.command ? await findCiDeploy(ip, atMs, this.settings.ciDeployTag, this.deps.journal).catch(() => null) : null;
64879
+ const closed = this.history.closeOf(ip, port, atMs);
64880
+ let tz;
64881
+ try {
64882
+ tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
64883
+ } catch {
64884
+ tz = void 0;
64885
+ }
64886
+ const base = {
64887
+ v: 1,
64888
+ at: new Date(atMs).toISOString(),
64889
+ host: this.host,
64890
+ tz_offset_min: -new Date(atMs).getTimezoneOffset(),
64891
+ ...tz ? { tz } : {},
64892
+ ...user ? { user } : {},
64893
+ ...method ? { auth_method: method } : {},
64894
+ ...port ? { port } : {},
64895
+ ...key ? { key } : {},
64896
+ source: { ip, kind, ...net ?? {} },
64897
+ failures,
64898
+ session: {
64899
+ ...ci ? { ci_deploy: ci } : {},
64900
+ ...closed !== null ? { closed_at: new Date(closed).toISOString(), duration_s: Math.max(0, Math.round((closed - atMs) / 1e3)) } : { open: true }
64901
+ }
64902
+ };
64903
+ const ctx = { ...base, verdict: computeVerdict(base) };
64904
+ d.ssh_context = ctx;
64905
+ return ctx;
64906
+ } catch {
64907
+ return null;
64908
+ }
64909
+ }
64910
+ };
64911
+
64912
+ // src/daemon/rules/loader.ts
64913
+ var import_node_fs66 = require("fs");
64914
+ var import_node_path46 = require("path");
64915
+
64264
64916
  // src/daemon/rules/default-rules.ts
64265
64917
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
64266
64918
  var SSHD_IDENT = String.raw`\[sshd(?:-session|-auth)?\]`;
@@ -64293,12 +64945,16 @@ var DEFAULT_RULES = [
64293
64945
  {
64294
64946
  id: "ssh-success-after-failures",
64295
64947
  title: "SSH Login Accepted",
64296
- // Honest description: this rule does NOT correlate with earlier failures —
64297
- // it matches any accepted login. It is an alert, and it declares no
64298
- // remediation precisely because banning the person who just logged in is
64299
- // never the right response.
64948
+ // Matches every accepted login, not only one after failures (the id is
64949
+ // kept for dashboards and incidents keyed on it). What came before it is
64950
+ // in the login's ssh_context: the failures in the window and whether they
64951
+ // came from the same address. With [ssh_context] on (the default) the
64952
+ // detection's severity is the context's verdict: a GitHub Actions deploy
64953
+ // with a forced-command key is low, an operator-expected CI key is info,
64954
+ // an unrestricted key from the internet stays critical. It declares no
64955
+ // remediation: banning the person who just logged in is never the answer.
64300
64956
  description: "Successful SSH login (alert only \u2014 never grounds for a ban)",
64301
- version: "1.0.0",
64957
+ version: "1.1.0",
64302
64958
  category: "auth",
64303
64959
  severity: "critical",
64304
64960
  source_types: ["ssh-guard", "auth"],
@@ -64310,7 +64966,7 @@ var DEFAULT_RULES = [
64310
64966
  threshold: 1,
64311
64967
  window_seconds: 60,
64312
64968
  cooldown_seconds: 300,
64313
- tags: ["ssh", "compromise-indicator"],
64969
+ tags: ["ssh", "compromise-indicator", "ssh-login-verdict"],
64314
64970
  enabled: true
64315
64971
  },
64316
64972
  {
@@ -64931,16 +65587,16 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
64931
65587
  function loadAllRules(customDir) {
64932
65588
  const rules = [...DEFAULT_RULES];
64933
65589
  const dir = customDir || RULES_DIR;
64934
- if ((0, import_node_fs64.existsSync)(dir)) {
65590
+ if ((0, import_node_fs66.existsSync)(dir)) {
64935
65591
  let files = [];
64936
65592
  try {
64937
- files = (0, import_node_fs64.readdirSync)(dir).filter((f) => f.endsWith(".json"));
65593
+ files = (0, import_node_fs66.readdirSync)(dir).filter((f) => f.endsWith(".json"));
64938
65594
  } catch (err) {
64939
65595
  console.warn(`[rules] cannot read ${dir}: ${err.message}; custom rules not loaded`);
64940
65596
  }
64941
65597
  for (const file of files) {
64942
65598
  try {
64943
- const raw = (0, import_node_fs64.readFileSync)((0, import_node_path45.join)(dir, file), "utf-8");
65599
+ const raw = (0, import_node_fs66.readFileSync)((0, import_node_path46.join)(dir, file), "utf-8");
64944
65600
  const parsed = JSON.parse(raw);
64945
65601
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
64946
65602
  for (const rule of customRules) {
@@ -64971,24 +65627,24 @@ function loadAllRules(customDir) {
64971
65627
  }
64972
65628
 
64973
65629
  // src/daemon/firewall/adapters.ts
64974
- var import_node_child_process24 = require("child_process");
64975
- var import_node_fs65 = require("fs");
64976
- var import_node_path46 = require("path");
64977
- var import_node_net22 = require("net");
65630
+ var import_node_child_process25 = require("child_process");
65631
+ var import_node_fs67 = require("fs");
65632
+ var import_node_path47 = require("path");
65633
+ var import_node_net23 = require("net");
64978
65634
  function assertValidFirewallIp(ip) {
64979
- if ((0, import_node_net22.isIP)(ip) !== 4) {
65635
+ if ((0, import_node_net23.isIP)(ip) !== 4) {
64980
65636
  throw new Error(`Invalid IPv4 address: ${ip}`);
64981
65637
  }
64982
65638
  }
64983
65639
  function assertBannableIp(ip) {
64984
- if ((0, import_node_net22.isIP)(ip) === 0) {
65640
+ if ((0, import_node_net23.isIP)(ip) === 0) {
64985
65641
  throw new Error(`Invalid IP address: ${ip}`);
64986
65642
  }
64987
65643
  }
64988
65644
  function writeIfAbsent(path2, contents) {
64989
- (0, import_node_fs65.mkdirSync)((0, import_node_path46.dirname)(path2), { recursive: true });
65645
+ (0, import_node_fs67.mkdirSync)((0, import_node_path47.dirname)(path2), { recursive: true });
64990
65646
  try {
64991
- (0, import_node_fs65.writeFileSync)(path2, contents, { flag: "wx" });
65647
+ (0, import_node_fs67.writeFileSync)(path2, contents, { flag: "wx" });
64992
65648
  } catch (err) {
64993
65649
  if (err.code !== "EEXIST") throw err;
64994
65650
  }
@@ -65007,11 +65663,11 @@ var Fail2banAdapter = class {
65007
65663
  enforces = true;
65008
65664
  jailReady = false;
65009
65665
  isAvailable() {
65010
- const result = (0, import_node_child_process24.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
65666
+ const result = (0, import_node_child_process25.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
65011
65667
  return result.status === 0;
65012
65668
  }
65013
65669
  client(args) {
65014
- return (0, import_node_child_process24.execFileSync)("fail2ban-client", args, {
65670
+ return (0, import_node_child_process25.execFileSync)("fail2ban-client", args, {
65015
65671
  encoding: "utf-8",
65016
65672
  stdio: ["ignore", "pipe", "pipe"]
65017
65673
  });
@@ -65087,7 +65743,7 @@ var Fail2banAdapter = class {
65087
65743
  const status = this.client(["status", this.jail]);
65088
65744
  const line2 = status.split("\n").find((l) => /Banned IP list:/i.test(l));
65089
65745
  if (!line2) return [];
65090
- return line2.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net22.isIP)(s) !== 0);
65746
+ return line2.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net23.isIP)(s) !== 0);
65091
65747
  } catch {
65092
65748
  return [];
65093
65749
  }
@@ -65097,45 +65753,45 @@ var Fail2banAdapter = class {
65097
65753
  function parseBannedList(output) {
65098
65754
  const found = [];
65099
65755
  for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
65100
- if ((0, import_node_net22.isIP)(match[1]) !== 0) found.push(match[1]);
65756
+ if ((0, import_node_net23.isIP)(match[1]) !== 0) found.push(match[1]);
65101
65757
  }
65102
65758
  if (found.length > 0) return found;
65103
- return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net22.isIP)(s) !== 0);
65759
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net23.isIP)(s) !== 0);
65104
65760
  }
65105
65761
  var NftablesAdapter = class {
65106
65762
  name = "nftables";
65107
65763
  table = "threatcrush";
65108
65764
  set = "blocklist";
65109
65765
  isAvailable() {
65110
- const result = (0, import_node_child_process24.spawnSync)("nft", ["--version"], { stdio: "pipe" });
65766
+ const result = (0, import_node_child_process25.spawnSync)("nft", ["--version"], { stdio: "pipe" });
65111
65767
  return result.status === 0;
65112
65768
  }
65113
65769
  ensureSetup() {
65114
65770
  try {
65115
- (0, import_node_child_process24.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
65771
+ (0, import_node_child_process25.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
65116
65772
  } catch {
65117
- (0, import_node_child_process24.execSync)(`nft add table inet ${this.table}`);
65118
- (0, import_node_child_process24.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
65119
- (0, import_node_child_process24.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
65120
- (0, import_node_child_process24.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
65773
+ (0, import_node_child_process25.execSync)(`nft add table inet ${this.table}`);
65774
+ (0, import_node_child_process25.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
65775
+ (0, import_node_child_process25.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
65776
+ (0, import_node_child_process25.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
65121
65777
  }
65122
65778
  }
65123
65779
  async block(ip) {
65124
65780
  assertValidFirewallIp(ip);
65125
65781
  this.ensureSetup();
65126
- (0, import_node_child_process24.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
65782
+ (0, import_node_child_process25.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
65127
65783
  }
65128
65784
  async unblock(ip) {
65129
65785
  assertValidFirewallIp(ip);
65130
65786
  try {
65131
- (0, import_node_child_process24.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
65787
+ (0, import_node_child_process25.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
65132
65788
  } catch {
65133
65789
  }
65134
65790
  }
65135
65791
  async isBlocked(ip) {
65136
65792
  assertValidFirewallIp(ip);
65137
65793
  try {
65138
- const output = (0, import_node_child_process24.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
65794
+ const output = (0, import_node_child_process25.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
65139
65795
  return output.includes(ip);
65140
65796
  } catch {
65141
65797
  return false;
@@ -65143,7 +65799,7 @@ var NftablesAdapter = class {
65143
65799
  }
65144
65800
  async listBlocked() {
65145
65801
  try {
65146
- const output = (0, import_node_child_process24.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
65802
+ const output = (0, import_node_child_process25.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
65147
65803
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
65148
65804
  if (!match) return [];
65149
65805
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -65156,34 +65812,34 @@ var IptablesAdapter = class {
65156
65812
  name = "iptables";
65157
65813
  chain = "THREATCRUSH";
65158
65814
  isAvailable() {
65159
- const result = (0, import_node_child_process24.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
65815
+ const result = (0, import_node_child_process25.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
65160
65816
  return result.status === 0;
65161
65817
  }
65162
65818
  ensureChain() {
65163
65819
  try {
65164
- (0, import_node_child_process24.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
65820
+ (0, import_node_child_process25.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
65165
65821
  } catch {
65166
- (0, import_node_child_process24.execSync)(`iptables -N ${this.chain}`);
65167
- (0, import_node_child_process24.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
65822
+ (0, import_node_child_process25.execSync)(`iptables -N ${this.chain}`);
65823
+ (0, import_node_child_process25.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
65168
65824
  }
65169
65825
  }
65170
65826
  async block(ip) {
65171
65827
  assertValidFirewallIp(ip);
65172
65828
  this.ensureChain();
65173
65829
  if (await this.isBlocked(ip)) return;
65174
- (0, import_node_child_process24.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
65830
+ (0, import_node_child_process25.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
65175
65831
  }
65176
65832
  async unblock(ip) {
65177
65833
  assertValidFirewallIp(ip);
65178
65834
  try {
65179
- (0, import_node_child_process24.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
65835
+ (0, import_node_child_process25.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
65180
65836
  } catch {
65181
65837
  }
65182
65838
  }
65183
65839
  async isBlocked(ip) {
65184
65840
  assertValidFirewallIp(ip);
65185
65841
  try {
65186
- const output = (0, import_node_child_process24.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
65842
+ const output = (0, import_node_child_process25.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
65187
65843
  return output.includes(ip);
65188
65844
  } catch {
65189
65845
  return false;
@@ -65191,7 +65847,7 @@ var IptablesAdapter = class {
65191
65847
  }
65192
65848
  async listBlocked() {
65193
65849
  try {
65194
- const output = (0, import_node_child_process24.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
65850
+ const output = (0, import_node_child_process25.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
65195
65851
  const ips = [];
65196
65852
  for (const line2 of output.split("\n")) {
65197
65853
  const match = line2.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -65247,22 +65903,22 @@ function detectFirewallAdapter(backend = "auto") {
65247
65903
  }
65248
65904
 
65249
65905
  // src/daemon/firewall/remediation.ts
65250
- var import_node_fs66 = require("fs");
65251
- var import_node_child_process25 = require("child_process");
65252
- var import_node_net23 = require("net");
65906
+ var import_node_fs68 = require("fs");
65907
+ var import_node_child_process26 = require("child_process");
65908
+ var import_node_net24 = require("net");
65253
65909
  init_paths();
65254
65910
  init_backoff();
65255
65911
 
65256
65912
  // src/daemon/firewall/crawlers.ts
65257
- var import_node_dns2 = require("dns");
65913
+ var import_node_dns3 = require("dns");
65258
65914
  var CRAWLER_DOMAINS = ["googlebot.com", "google.com", "search.msn.com", "applebot.apple.com"];
65259
65915
  var systemResolver = {
65260
- reverse: (ip) => import_node_dns2.promises.reverse(ip),
65261
- lookup: async (host) => (await import_node_dns2.promises.lookup(host, { all: true })).map((a) => a.address)
65916
+ reverse: (ip) => import_node_dns3.promises.reverse(ip),
65917
+ lookup: async (host) => (await import_node_dns3.promises.lookup(host, { all: true })).map((a) => a.address)
65262
65918
  };
65263
65919
  var TIMEOUT_MS2 = 2e3;
65264
65920
  var CACHE_MS = 6 * 36e5;
65265
- function withTimeout2(p) {
65921
+ function withTimeout3(p) {
65266
65922
  return Promise.race([
65267
65923
  p,
65268
65924
  new Promise((_, reject) => setTimeout(() => reject(new Error("dns timeout")), TIMEOUT_MS2).unref())
@@ -65279,9 +65935,9 @@ function crawlerVerifier(resolver = systemResolver) {
65279
65935
  if (hit && hit.until > Date.now()) return hit.host;
65280
65936
  let host = null;
65281
65937
  try {
65282
- const names = await withTimeout2(resolver.reverse(ip));
65938
+ const names = await withTimeout3(resolver.reverse(ip));
65283
65939
  for (const name of names.filter(inCrawlerDomain)) {
65284
- const addrs = await withTimeout2(resolver.lookup(name));
65940
+ const addrs = await withTimeout3(resolver.lookup(name));
65285
65941
  if (addrs.includes(ip)) {
65286
65942
  host = name.replace(/\.$/, "");
65287
65943
  break;
@@ -65319,19 +65975,19 @@ var defaultDiscovery = {
65319
65975
  const snapshot = takeSnapshot({
65320
65976
  readFile: (p) => {
65321
65977
  try {
65322
- return (0, import_node_fs66.readFileSync)(p, "utf-8");
65978
+ return (0, import_node_fs68.readFileSync)(p, "utf-8");
65323
65979
  } catch {
65324
65980
  return null;
65325
65981
  }
65326
65982
  },
65327
65983
  readDir: (p) => {
65328
65984
  try {
65329
- return (0, import_node_fs66.readdirSync)(p);
65985
+ return (0, import_node_fs68.readdirSync)(p);
65330
65986
  } catch {
65331
65987
  return null;
65332
65988
  }
65333
65989
  },
65334
- exists: (p) => (0, import_node_fs66.existsSync)(p)
65990
+ exists: (p) => (0, import_node_fs68.existsSync)(p)
65335
65991
  });
65336
65992
  const out = /* @__PURE__ */ new Set();
65337
65993
  for (const keys of Object.values(snapshot.keys)) {
@@ -65340,7 +65996,7 @@ var defaultDiscovery = {
65340
65996
  return out;
65341
65997
  },
65342
65998
  keyLoginJournal: (sinceSeconds) => new Promise((resolve9) => {
65343
- (0, import_node_child_process25.execFile)(
65999
+ (0, import_node_child_process26.execFile)(
65344
66000
  "journalctl",
65345
66001
  ["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
65346
66002
  { maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
@@ -65420,7 +66076,7 @@ var RemediationManager = class {
65420
66076
  setTorExitCheck(check2) {
65421
66077
  this.isTorExit = check2;
65422
66078
  let dropped = 0;
65423
- this.protectedList = this.protectedList.filter((a) => !(0, import_node_net23.isIP)(a) || !check2(a) || this.pinned.has(a) || this.config.allowlist.includes(a));
66079
+ this.protectedList = this.protectedList.filter((a) => !(0, import_node_net24.isIP)(a) || !check2(a) || this.pinned.has(a) || this.config.allowlist.includes(a));
65424
66080
  for (const ip of Object.keys(this.operators)) {
65425
66081
  if (!check2(ip)) continue;
65426
66082
  delete this.operators[ip];
@@ -65513,7 +66169,7 @@ var RemediationManager = class {
65513
66169
  if (remediation?.action !== "block") return;
65514
66170
  }
65515
66171
  const ip = event.source_ip;
65516
- if (!ip || (0, import_node_net23.isIP)(ip) === 0) return;
66172
+ if (!ip || (0, import_node_net24.isIP)(ip) === 0) return;
65517
66173
  const strict = remediation?.override_operator_protection === true;
65518
66174
  if (strict ? this.isFleetAddress(ip) : this.isAllowlisted(ip)) {
65519
66175
  if (strict) this.logLine(`[remediation] not banning ${ip}: it is one of our own addresses (${event.message})`);
@@ -65542,7 +66198,7 @@ var RemediationManager = class {
65542
66198
  * 4th offence and so on, clamped to `max_ban_seconds`.
65543
66199
  */
65544
66200
  async ban(ip, reason, opts = {}) {
65545
- if ((0, import_node_net23.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
66201
+ if ((0, import_node_net24.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
65546
66202
  if (opts.strict ? this.isFleetAddress(ip) : this.isAllowlisted(ip)) {
65547
66203
  return { ok: false, error: `${ip} is protected and can never be blocked` };
65548
66204
  }
@@ -65819,7 +66475,7 @@ var RemediationManager = class {
65819
66475
  if (saved && typeof saved === "object" && this.config.protect_recent_operators) {
65820
66476
  const cutoff = Date.now() - this.config.operator_memory_seconds * 1e3;
65821
66477
  for (const [ip, at] of Object.entries(saved)) {
65822
- if (typeof at !== "number" || at < cutoff || !(0, import_node_net23.isIP)(ip)) continue;
66478
+ if (typeof at !== "number" || at < cutoff || !(0, import_node_net24.isIP)(ip)) continue;
65823
66479
  if (this.blocklist.some((b) => b.ip === ip && b.strict)) continue;
65824
66480
  this.operators[ip] = at;
65825
66481
  if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
@@ -65844,7 +66500,7 @@ var RemediationManager = class {
65844
66500
  }
65845
66501
  logLine(line2) {
65846
66502
  try {
65847
- (0, import_node_fs66.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
66503
+ (0, import_node_fs68.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
65848
66504
  `);
65849
66505
  } catch {
65850
66506
  }
@@ -65888,19 +66544,19 @@ function remediationSettings(section) {
65888
66544
  init_backoff();
65889
66545
 
65890
66546
  // src/daemon/watchdog-service.ts
65891
- var import_node_fs67 = require("fs");
65892
- var import_node_path47 = require("path");
66547
+ var import_node_fs69 = require("fs");
66548
+ var import_node_path48 = require("path");
65893
66549
  function defaultShareGid() {
65894
66550
  const isRoot4 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
65895
66551
  if (!isRoot4) return void 0;
65896
66552
  try {
65897
- return (0, import_node_fs67.statSync)("/var/log/auth.log").gid;
66553
+ return (0, import_node_fs69.statSync)("/var/log/auth.log").gid;
65898
66554
  } catch {
65899
66555
  return void 0;
65900
66556
  }
65901
66557
  }
65902
66558
  function startWatchdog(opts) {
65903
- const dir = opts.config?.dir ?? (0, import_node_path47.join)(opts.stateDir, WATCHDOG_DIRNAME);
66559
+ const dir = opts.config?.dir ?? (0, import_node_path48.join)(opts.stateDir, WATCHDOG_DIRNAME);
65904
66560
  const base = { dir, logged: 0, answered: 0, errored: 0 };
65905
66561
  if (opts.config?.enabled === false) {
65906
66562
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -65994,7 +66650,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
65994
66650
  }
65995
66651
 
65996
66652
  // src/core/node-runtime.ts
65997
- var import_node_child_process26 = require("child_process");
66653
+ var import_node_child_process27 = require("child_process");
65998
66654
  var MIN_DAEMON_NODE_MAJOR = 22;
65999
66655
  function nodeMajor(version) {
66000
66656
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -66008,23 +66664,23 @@ function daemonNodeProblem(version) {
66008
66664
  }
66009
66665
  function versionOfNode(path2) {
66010
66666
  if (path2 === process.execPath) return process.versions.node;
66011
- const res = (0, import_node_child_process26.spawnSync)(path2, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
66667
+ const res = (0, import_node_child_process27.spawnSync)(path2, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
66012
66668
  return res.status === 0 ? res.stdout.trim() : null;
66013
66669
  }
66014
66670
 
66015
66671
  // src/daemon/index.ts
66016
66672
  function readVersion2() {
66017
66673
  try {
66018
- const pkg = JSON.parse((0, import_node_fs68.readFileSync)((0, import_node_path48.join)(__dirname, "..", "package.json"), "utf-8"));
66674
+ const pkg = JSON.parse((0, import_node_fs70.readFileSync)((0, import_node_path49.join)(__dirname, "..", "package.json"), "utf-8"));
66019
66675
  return pkg.version || "0.0.0";
66020
66676
  } catch {
66021
66677
  return "0.0.0";
66022
66678
  }
66023
66679
  }
66024
66680
  async function runHardeningChecks() {
66025
- const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process27.execFile)(
66681
+ const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process28.execFile)(
66026
66682
  process.execPath,
66027
- [(0, import_node_path48.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
66683
+ [(0, import_node_path49.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
66028
66684
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
66029
66685
  );
66030
66686
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -66036,9 +66692,9 @@ async function runHardeningChecks() {
66036
66692
  return patches ? [...findings2, patches] : findings2;
66037
66693
  }
66038
66694
  async function runPatchCheck() {
66039
- const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process27.execFile)(
66695
+ const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process28.execFile)(
66040
66696
  process.execPath,
66041
- [(0, import_node_path48.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
66697
+ [(0, import_node_path49.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
66042
66698
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
66043
66699
  );
66044
66700
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -66046,7 +66702,7 @@ async function runPatchCheck() {
66046
66702
  }
66047
66703
  function logLine(line2) {
66048
66704
  try {
66049
- (0, import_node_fs68.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
66705
+ (0, import_node_fs70.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
66050
66706
  `);
66051
66707
  } catch {
66052
66708
  }
@@ -66071,9 +66727,9 @@ async function runDaemon() {
66071
66727
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
66072
66728
  const restartDaemon = () => {
66073
66729
  if (PATHS.mode === "system") {
66074
- (0, import_node_child_process27.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
66730
+ (0, import_node_child_process28.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
66075
66731
  } else {
66076
- (0, import_node_child_process27.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
66732
+ (0, import_node_child_process28.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
66077
66733
  setTimeout(() => process.exit(0), 500).unref();
66078
66734
  }
66079
66735
  };
@@ -66088,7 +66744,7 @@ async function runDaemon() {
66088
66744
  } catch (err) {
66089
66745
  logLine(`[daemon] state db unavailable: ${err.message}`);
66090
66746
  }
66091
- const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path48.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
66747
+ const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path49.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
66092
66748
  const config = loaded.config;
66093
66749
  if (loaded.error) {
66094
66750
  logLine(`[daemon] CONFIG ERROR: ${loaded.error}; ${loaded.usedLastGood ? "running on the last config that parsed" : "no earlier good copy, running on DEFAULTS (no protected list)"}`);
@@ -66112,27 +66768,37 @@ async function runDaemon() {
66112
66768
  const moduleHost = new ModuleHost(bus);
66113
66769
  await moduleHost.start();
66114
66770
  const ruleEngine = new RuleEngine((detection) => {
66771
+ const ctx = detection.raw_metadata?.evidence?.ssh_context;
66772
+ const useVerdict = !!ctx?.verdict && Array.isArray(detection.raw_metadata?.tags) && detection.raw_metadata.tags.includes("ssh-login-verdict");
66115
66773
  const event = {
66116
66774
  timestamp: /* @__PURE__ */ new Date(),
66117
66775
  module: "rule-engine",
66118
66776
  category: detection.raw_metadata?.category || "system",
66119
- severity: detection.severity,
66777
+ severity: useVerdict ? ctx.verdict.severity : detection.severity,
66120
66778
  message: `[DETECTION] ${detection.title}`,
66121
66779
  source_ip: detection.source_ip,
66122
66780
  details: {
66123
66781
  rule_id: detection.rule_id,
66124
- description: detection.description,
66782
+ description: useVerdict ? [ctx.verdict.summary, describeFailures(ctx.failures, ctx.source?.ip)].filter(Boolean).join(". ") : detection.description,
66125
66783
  username: detection.username,
66126
- ...detection.raw_metadata
66784
+ ...detection.raw_metadata,
66785
+ ...useVerdict && ctx.verdict.severity !== detection.severity ? { rule_severity: detection.severity } : {}
66127
66786
  }
66128
66787
  };
66129
66788
  bus.publish(event);
66130
66789
  });
66131
66790
  ruleEngine.loadRules(loadAllRules());
66132
66791
  const keyDirectory = new KeyDirectory();
66792
+ const sshContext = new SshLoginEnricher(sshContextSettings(config.ssh_context), { stateDir: PATHS.stateDir });
66793
+ sshContext.start();
66794
+ bus.on("sshd", (line2) => sshContext.recordSshd(line2));
66133
66795
  bus.on("event", (event) => {
66134
66796
  if (event.module === "rule-engine") return;
66135
66797
  enrichLoginEvent(event, keyDirectory);
66798
+ if (sshContext.wants(event)) {
66799
+ void sshContext.enrich(event).finally(() => ruleEngine.evaluate(event));
66800
+ return;
66801
+ }
66136
66802
  ruleEngine.evaluate(event);
66137
66803
  });
66138
66804
  logLine(`[daemon] rule engine loaded ${ruleEngine.getRules().length} rules`);
@@ -66159,7 +66825,7 @@ async function runDaemon() {
66159
66825
  const threatFeeds = new ThreatFeeds({
66160
66826
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
66161
66827
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
66162
- cachePath: (0, import_node_path48.join)(PATHS.stateDir, "threat-feeds.json"),
66828
+ cachePath: (0, import_node_path49.join)(PATHS.stateDir, "threat-feeds.json"),
66163
66829
  bus,
66164
66830
  log: logLine
66165
66831
  });
@@ -66167,9 +66833,9 @@ async function runDaemon() {
66167
66833
  const privilegeWatch = new PrivilegeWatch({
66168
66834
  settings: privilegeSettings(config.privileged),
66169
66835
  bus,
66170
- snapshotPath: (0, import_node_path48.join)(PATHS.stateDir, "privileges.json"),
66171
- loginsPath: (0, import_node_path48.join)(PATHS.stateDir, "login-countries.json"),
66172
- cursorPath: (0, import_node_path48.join)(PATHS.stateDir, "sudo-cursor.json"),
66836
+ snapshotPath: (0, import_node_path49.join)(PATHS.stateDir, "privileges.json"),
66837
+ loginsPath: (0, import_node_path49.join)(PATHS.stateDir, "login-countries.json"),
66838
+ cursorPath: (0, import_node_path49.join)(PATHS.stateDir, "sudo-cursor.json"),
66173
66839
  log: logLine
66174
66840
  });
66175
66841
  privilegeWatch.start();
@@ -66183,8 +66849,8 @@ async function runDaemon() {
66183
66849
  const fileIntegrity = new FileIntegrityWatch({
66184
66850
  bus,
66185
66851
  settings: fileIntegritySettings(config.file_integrity),
66186
- baselinePath: (0, import_node_path48.join)(PATHS.stateDir, "file-integrity-baseline.json"),
66187
- observedPath: (0, import_node_path48.join)(PATHS.stateDir, "file-integrity-observed.json"),
66852
+ baselinePath: (0, import_node_path49.join)(PATHS.stateDir, "file-integrity-baseline.json"),
66853
+ observedPath: (0, import_node_path49.join)(PATHS.stateDir, "file-integrity-observed.json"),
66188
66854
  // `[remediation] dry_run` also covers the opt-in contain_writer response.
66189
66855
  dryRun: () => remediation.status().dry_run,
66190
66856
  log: logLine
@@ -66193,13 +66859,13 @@ async function runDaemon() {
66193
66859
  const edr = new EdrWatch({
66194
66860
  bus,
66195
66861
  settings: edrSettings(config.edr),
66196
- networkBaselinePath: (0, import_node_path48.join)(PATHS.stateDir, "edr-outbound-executables.json"),
66197
- sourceStatusPath: (0, import_node_path48.join)(PATHS.stateDir, "edr-source.json"),
66862
+ networkBaselinePath: (0, import_node_path49.join)(PATHS.stateDir, "edr-outbound-executables.json"),
66863
+ sourceStatusPath: (0, import_node_path49.join)(PATHS.stateDir, "edr-source.json"),
66198
66864
  log: logLine
66199
66865
  });
66200
66866
  edr.start();
66201
66867
  const torExits = new TorExitList({
66202
- cachePath: (0, import_node_path48.join)(PATHS.stateDir, "tor-exits.txt"),
66868
+ cachePath: (0, import_node_path49.join)(PATHS.stateDir, "tor-exits.txt"),
66203
66869
  url: config.remediation?.tor_exit_list_url,
66204
66870
  log: logLine
66205
66871
  });
@@ -66207,7 +66873,7 @@ async function runDaemon() {
66207
66873
  bus,
66208
66874
  manager: remediation,
66209
66875
  tor: torExits,
66210
- historyPath: (0, import_node_path48.join)(PATHS.stateDir, "key-logins.json"),
66876
+ historyPath: (0, import_node_path49.join)(PATHS.stateDir, "key-logins.json"),
66211
66877
  keyLoginWatch: config.privileged?.key_login_watch !== false,
66212
66878
  log: logLine
66213
66879
  });
@@ -66280,9 +66946,9 @@ async function runDaemon() {
66280
66946
  cloudSync = new CloudSync({
66281
66947
  bus,
66282
66948
  version,
66283
- hostname: (0, import_node_os20.hostname)(),
66949
+ hostname: (0, import_node_os22.hostname)(),
66284
66950
  minSeverity,
66285
- spoolPath: (0, import_node_path48.join)(PATHS.stateDir, "cloud-spool.jsonl"),
66951
+ spoolPath: (0, import_node_path49.join)(PATHS.stateDir, "cloud-spool.jsonl"),
66286
66952
  log: logLine,
66287
66953
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
66288
66954
  runHardening: runHardeningChecks
@@ -66316,8 +66982,8 @@ async function runDaemon() {
66316
66982
  const autoUpdate = autoUpdateRef = new AutoUpdate({
66317
66983
  version,
66318
66984
  settings: updateSettings(config.update),
66319
- pkgRoot: (0, import_node_path48.join)(__dirname, ".."),
66320
- statePath: (0, import_node_path48.join)(PATHS.stateDir, "auto-update.json"),
66985
+ pkgRoot: (0, import_node_path49.join)(__dirname, ".."),
66986
+ statePath: (0, import_node_path49.join)(PATHS.stateDir, "auto-update.json"),
66321
66987
  bus,
66322
66988
  log: logLine,
66323
66989
  restartDaemon
@@ -66439,7 +67105,7 @@ var SYSTEM_SOCKET = "/var/run/threatcrush/threatcrushd.sock";
66439
67105
  function isRoot2() {
66440
67106
  return typeof process.getuid === "function" && process.getuid() === 0;
66441
67107
  }
66442
- var DAEMON_ENTRY = (0, import_node_path49.join)(__dirname, "daemon.js");
67108
+ var DAEMON_ENTRY = (0, import_node_path50.join)(__dirname, "daemon.js");
66443
67109
  async function daemonForeground() {
66444
67110
  await runDaemon();
66445
67111
  }
@@ -66460,7 +67126,7 @@ async function daemonStart() {
66460
67126
  return;
66461
67127
  }
66462
67128
  ensureRuntimeDirs();
66463
- if (!(0, import_node_fs69.existsSync)(DAEMON_ENTRY)) {
67129
+ if (!(0, import_node_fs71.existsSync)(DAEMON_ENTRY)) {
66464
67130
  console.log(source_default.red(` Daemon entry not found at ${DAEMON_ENTRY}.`));
66465
67131
  console.log(source_default.dim(" Reinstall with `threatcrush update` or `pnpm run build` in the cli package."));
66466
67132
  return;
@@ -66468,8 +67134,8 @@ async function daemonStart() {
66468
67134
  let out;
66469
67135
  let err;
66470
67136
  try {
66471
- out = (0, import_node_fs70.openSync)(PATHS.logFile, "a");
66472
- err = (0, import_node_fs70.openSync)(PATHS.logFile, "a");
67137
+ out = (0, import_node_fs72.openSync)(PATHS.logFile, "a");
67138
+ err = (0, import_node_fs72.openSync)(PATHS.logFile, "a");
66473
67139
  } catch (e) {
66474
67140
  const code = e.code;
66475
67141
  console.log(source_default.red(` \u2717 Cannot write daemon log at ${PATHS.logFile} (${code ?? "error"}).`));
@@ -66482,7 +67148,7 @@ async function daemonStart() {
66482
67148
  }
66483
67149
  return;
66484
67150
  }
66485
- const child = (0, import_node_child_process28.spawn)(process.execPath, [DAEMON_ENTRY], {
67151
+ const child = (0, import_node_child_process29.spawn)(process.execPath, [DAEMON_ENTRY], {
66486
67152
  detached: true,
66487
67153
  stdio: ["ignore", out, err],
66488
67154
  env: { ...process.env, THREATCRUSH_DAEMON: "1" }
@@ -66557,41 +67223,41 @@ async function waitForExit(pid, timeoutMs) {
66557
67223
  }
66558
67224
  async function releaseStaleSocket() {
66559
67225
  const deadline = Date.now() + 2e3;
66560
- while ((0, import_node_fs69.existsSync)(PATHS.socket) && Date.now() < deadline) {
67226
+ while ((0, import_node_fs71.existsSync)(PATHS.socket) && Date.now() < deadline) {
66561
67227
  await new Promise((r) => setTimeout(r, 50));
66562
67228
  }
66563
- if ((0, import_node_fs69.existsSync)(PATHS.socket)) {
67229
+ if ((0, import_node_fs71.existsSync)(PATHS.socket)) {
66564
67230
  try {
66565
- (0, import_node_fs69.unlinkSync)(PATHS.socket);
67231
+ (0, import_node_fs71.unlinkSync)(PATHS.socket);
66566
67232
  } catch {
66567
67233
  }
66568
67234
  }
66569
67235
  }
66570
67236
 
66571
67237
  // src/commands/service.ts
66572
- var import_node_child_process29 = require("child_process");
66573
- var import_node_fs71 = require("fs");
66574
- var import_node_path50 = require("path");
66575
- var import_node_os21 = require("os");
67238
+ var import_node_child_process30 = require("child_process");
67239
+ var import_node_fs73 = require("fs");
67240
+ var import_node_path51 = require("path");
67241
+ var import_node_os23 = require("os");
66576
67242
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
66577
67243
  var DAEMON_UNIT_NAME = "threatcrushd.service";
66578
67244
  function resolveTemplate() {
66579
- const templatePath = (0, import_node_path50.join)(__dirname, "systemd", "threatcrushd.service");
66580
- if (!(0, import_node_fs71.existsSync)(templatePath)) {
67245
+ const templatePath = (0, import_node_path51.join)(__dirname, "systemd", "threatcrushd.service");
67246
+ if (!(0, import_node_fs73.existsSync)(templatePath)) {
66581
67247
  throw new Error(`systemd unit template not found at ${templatePath}`);
66582
67248
  }
66583
- return (0, import_node_fs71.readFileSync)(templatePath, "utf-8");
67249
+ return (0, import_node_fs73.readFileSync)(templatePath, "utf-8");
66584
67250
  }
66585
67251
  function stableBinPath(binPath) {
66586
67252
  const stable = binPath.replace(/\/\.pnpm\/[^/]+\/node_modules\//, "/node_modules/");
66587
67253
  if (stable === binPath) return binPath;
66588
- return (0, import_node_fs71.existsSync)(stable) ? stable : binPath;
67254
+ return (0, import_node_fs73.existsSync)(stable) ? stable : binPath;
66589
67255
  }
66590
67256
  function resolveBinPath() {
66591
67257
  const arg = process.argv[1];
66592
- if (arg && (0, import_node_fs71.existsSync)(arg)) return stableBinPath(arg);
67258
+ if (arg && (0, import_node_fs73.existsSync)(arg)) return stableBinPath(arg);
66593
67259
  try {
66594
- return (0, import_node_child_process29.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
67260
+ return (0, import_node_child_process30.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
66595
67261
  } catch {
66596
67262
  return "threatcrush";
66597
67263
  }
@@ -66599,11 +67265,11 @@ function resolveBinPath() {
66599
67265
  function stableNodePath(execPath) {
66600
67266
  const stable = execPath.replace(/(\/installs\/node\/)[^/]+\//, "$1latest/");
66601
67267
  if (stable === execPath) return execPath;
66602
- return (0, import_node_fs71.existsSync)(stable) ? stable : execPath;
67268
+ return (0, import_node_fs73.existsSync)(stable) ? stable : execPath;
66603
67269
  }
66604
67270
  function looksLikeNodeScript(path2) {
66605
67271
  try {
66606
- const head2 = (0, import_node_fs71.readFileSync)(path2, "utf-8").slice(0, 120);
67272
+ const head2 = (0, import_node_fs73.readFileSync)(path2, "utf-8").slice(0, 120);
66607
67273
  return /^#!.*\bnode\b/.test(head2);
66608
67274
  } catch {
66609
67275
  return false;
@@ -66631,20 +67297,20 @@ function isRoot3() {
66631
67297
  return typeof process.getuid === "function" && process.getuid() === 0;
66632
67298
  }
66633
67299
  function reexecWithSudo(args) {
66634
- if ((0, import_node_child_process29.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
67300
+ if ((0, import_node_child_process30.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
66635
67301
  console.log(source_default.dim(" This needs root \u2014 sudo will ask for your password.\n"));
66636
67302
  const bin = resolveBinPath();
66637
67303
  const argv = looksLikeNodeScript(bin) ? [stableNodePath(process.execPath), bin, ...args] : [bin, ...args];
66638
- const result = (0, import_node_child_process29.spawnSync)("sudo", argv, { stdio: "inherit" });
67304
+ const result = (0, import_node_child_process30.spawnSync)("sudo", argv, { stdio: "inherit" });
66639
67305
  return result.status === 0;
66640
67306
  }
66641
67307
  function callerHome() {
66642
67308
  const user = process.env.SUDO_USER;
66643
67309
  if (!user) return null;
66644
67310
  try {
66645
- const line2 = (0, import_node_child_process29.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
67311
+ const line2 = (0, import_node_child_process30.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
66646
67312
  const home = line2.split(":")[5];
66647
- return home && (0, import_node_fs71.existsSync)(home) ? home : null;
67313
+ return home && (0, import_node_fs73.existsSync)(home) ? home : null;
66648
67314
  } catch {
66649
67315
  return null;
66650
67316
  }
@@ -66652,13 +67318,13 @@ function callerHome() {
66652
67318
  function stopUserModeDaemon() {
66653
67319
  const home = callerHome();
66654
67320
  if (!home) return;
66655
- const runDir = (0, import_node_path50.join)(home, ".threatcrush", "run");
66656
- const pidFile = (0, import_node_path50.join)(runDir, "threatcrushd.pid");
66657
- const socket = (0, import_node_path50.join)(runDir, "threatcrushd.sock");
66658
- if (!(0, import_node_fs71.existsSync)(pidFile) && !(0, import_node_fs71.existsSync)(socket)) return;
67321
+ const runDir = (0, import_node_path51.join)(home, ".threatcrush", "run");
67322
+ const pidFile = (0, import_node_path51.join)(runDir, "threatcrushd.pid");
67323
+ const socket = (0, import_node_path51.join)(runDir, "threatcrushd.sock");
67324
+ if (!(0, import_node_fs73.existsSync)(pidFile) && !(0, import_node_fs73.existsSync)(socket)) return;
66659
67325
  let pid = null;
66660
67326
  try {
66661
- pid = Number.parseInt((0, import_node_fs71.readFileSync)(pidFile, "utf-8").trim(), 10);
67327
+ pid = Number.parseInt((0, import_node_fs73.readFileSync)(pidFile, "utf-8").trim(), 10);
66662
67328
  } catch {
66663
67329
  pid = null;
66664
67330
  }
@@ -66671,13 +67337,13 @@ function stopUserModeDaemon() {
66671
67337
  }
66672
67338
  for (const path2 of [socket, pidFile]) {
66673
67339
  try {
66674
- if ((0, import_node_fs71.existsSync)(path2)) (0, import_node_fs71.rmSync)(path2);
67340
+ if ((0, import_node_fs73.existsSync)(path2)) (0, import_node_fs73.rmSync)(path2);
66675
67341
  } catch {
66676
67342
  }
66677
67343
  }
66678
67344
  }
66679
67345
  function unitIsActive() {
66680
- const result = (0, import_node_child_process29.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
67346
+ const result = (0, import_node_child_process30.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
66681
67347
  return result.status === 0;
66682
67348
  }
66683
67349
  async function installServiceCommand() {
@@ -66688,8 +67354,8 @@ async function installServiceCommand() {
66688
67354
  return;
66689
67355
  }
66690
67356
  const noSystemd = systemdUnavailableReason({
66691
- hasSystemctl: (0, import_node_child_process29.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
66692
- booted: (0, import_node_fs71.existsSync)("/run/systemd/system")
67357
+ hasSystemctl: (0, import_node_child_process30.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
67358
+ booted: (0, import_node_fs73.existsSync)("/run/systemd/system")
66693
67359
  });
66694
67360
  if (noSystemd) {
66695
67361
  console.log(source_default.red(` \u2717 systemd isn't available here: ${noSystemd}.`));
@@ -66711,7 +67377,7 @@ async function installServiceCommand() {
66711
67377
  const isNodeScript = looksLikeNodeScript(binPath);
66712
67378
  let nodePath = stableNodePath(process.execPath);
66713
67379
  if (isNodeScript && nodeVersionDir(binPath)) {
66714
- binPath = (0, import_node_fs71.realpathSync)(binPath);
67380
+ binPath = (0, import_node_fs73.realpathSync)(binPath);
66715
67381
  nodePath = process.execPath;
66716
67382
  }
66717
67383
  if (isNodeScript) {
@@ -66724,13 +67390,13 @@ async function installServiceCommand() {
66724
67390
  }
66725
67391
  }
66726
67392
  const exec = execStartCommand(binPath, nodePath, isNodeScript);
66727
- const configDir = (0, import_node_path50.join)((0, import_node_os21.homedir)(), ".threatcrush");
67393
+ const configDir = (0, import_node_path51.join)((0, import_node_os23.homedir)(), ".threatcrush");
66728
67394
  const commandHistoryEnabled = commandHistorySettings(loadConfig().command_history).enabled;
66729
67395
  const historyPaths = commandHistoryEnabled ? historyWritableHomes() : [];
66730
67396
  const containWriter = containWriterSettings(loadConfig().file_integrity).mode !== "off";
66731
67397
  const extraCapabilities = containWriter ? ["CAP_SYS_PTRACE"] : [];
66732
67398
  const unit = renderUnit(resolveTemplate(), { exec, binPath, configDir, historyPaths, extraCapabilities });
66733
- (0, import_node_fs71.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
67399
+ (0, import_node_fs73.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
66734
67400
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
66735
67401
  console.log(source_default.dim(` ExecStart=${exec}`));
66736
67402
  if (containWriter) console.log(source_default.dim(" CAP_SYS_PTRACE granted for [file_integrity] contain_writer (reads /proc/<pid>/fd)"));
@@ -66746,8 +67412,8 @@ async function installServiceCommand() {
66746
67412
  installLogrotate();
66747
67413
  stopUserModeDaemon();
66748
67414
  try {
66749
- (0, import_node_child_process29.execSync)("systemctl daemon-reload", { stdio: "inherit" });
66750
- (0, import_node_child_process29.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
67415
+ (0, import_node_child_process30.execSync)("systemctl daemon-reload", { stdio: "inherit" });
67416
+ (0, import_node_child_process30.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
66751
67417
  } catch (err) {
66752
67418
  console.log(source_default.yellow(` ! systemctl error: ${err.message}`));
66753
67419
  console.log(source_default.dim(` Logs: journalctl -u ${DAEMON_UNIT_NAME} -n 50`));
@@ -66784,9 +67450,9 @@ function renderLogrotate(logDir = "/var/log/threatcrush") {
66784
67450
  ].join("\n");
66785
67451
  }
66786
67452
  function installLogrotate() {
66787
- if (!(0, import_node_fs71.existsSync)((0, import_node_path50.dirname)(LOGROTATE_PATH))) return;
67453
+ if (!(0, import_node_fs73.existsSync)((0, import_node_path51.dirname)(LOGROTATE_PATH))) return;
66788
67454
  try {
66789
- (0, import_node_fs71.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
67455
+ (0, import_node_fs73.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
66790
67456
  console.log(source_default.green(` \u2713 Log rotation: ${LOGROTATE_PATH} (daily or 200M, keeps 7)`));
66791
67457
  } catch (err) {
66792
67458
  console.log(source_default.yellow(` ! Could not install log rotation: ${err.message}`));
@@ -66808,20 +67474,20 @@ function ensureSystemDirs(configDir) {
66808
67474
  ];
66809
67475
  let admGid2 = null;
66810
67476
  try {
66811
- admGid2 = (0, import_node_fs71.statSync)("/var/log/auth.log").gid;
67477
+ admGid2 = (0, import_node_fs73.statSync)("/var/log/auth.log").gid;
66812
67478
  } catch {
66813
67479
  }
66814
67480
  for (const { path: path2, groupWritable, sticky } of dirs) {
66815
67481
  try {
66816
- (0, import_node_fs71.mkdirSync)(path2, { recursive: true });
67482
+ (0, import_node_fs73.mkdirSync)(path2, { recursive: true });
66817
67483
  } catch {
66818
67484
  }
66819
67485
  try {
66820
67486
  if (groupWritable && admGid2 !== null) {
66821
- (0, import_node_fs71.chmodSync)(path2, sticky ? 1533 : 509);
66822
- (0, import_node_child_process29.execSync)(`chgrp adm ${path2}`, { stdio: "ignore" });
67487
+ (0, import_node_fs73.chmodSync)(path2, sticky ? 1533 : 509);
67488
+ (0, import_node_child_process30.execSync)(`chgrp adm ${path2}`, { stdio: "ignore" });
66823
67489
  } else {
66824
- (0, import_node_fs71.chmodSync)(path2, 493);
67490
+ (0, import_node_fs73.chmodSync)(path2, 493);
66825
67491
  }
66826
67492
  } catch {
66827
67493
  }
@@ -66841,29 +67507,29 @@ async function uninstallServiceCommand() {
66841
67507
  return;
66842
67508
  }
66843
67509
  try {
66844
- (0, import_node_child_process29.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
67510
+ (0, import_node_child_process30.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
66845
67511
  } catch {
66846
67512
  }
66847
67513
  try {
66848
- (0, import_node_child_process29.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
67514
+ (0, import_node_child_process30.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
66849
67515
  } catch {
66850
67516
  }
66851
67517
  try {
66852
- if ((0, import_node_fs71.existsSync)(UNIT_PATH)) {
66853
- (0, import_node_child_process29.execSync)(`rm -f ${UNIT_PATH}`);
67518
+ if ((0, import_node_fs73.existsSync)(UNIT_PATH)) {
67519
+ (0, import_node_child_process30.execSync)(`rm -f ${UNIT_PATH}`);
66854
67520
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
66855
67521
  }
66856
67522
  } catch {
66857
67523
  }
66858
67524
  try {
66859
- (0, import_node_child_process29.execSync)("systemctl daemon-reload", { stdio: "inherit" });
67525
+ (0, import_node_child_process30.execSync)("systemctl daemon-reload", { stdio: "inherit" });
66860
67526
  } catch {
66861
67527
  }
66862
67528
  console.log(source_default.green(" \u2713 threatcrushd service removed."));
66863
67529
  }
66864
67530
 
66865
67531
  // src/commands/save.ts
66866
- var import_node_fs72 = require("fs");
67532
+ var import_node_fs74 = require("fs");
66867
67533
  var import_toml6 = __toESM(require_toml());
66868
67534
  init_cli_config();
66869
67535
  init_paths();
@@ -66902,9 +67568,9 @@ async function saveCommand(opts = {}) {
66902
67568
  }
66903
67569
  const path2 = opts.config ?? PATHS.configFile;
66904
67570
  let config = {};
66905
- if ((0, import_node_fs72.existsSync)(path2)) {
67571
+ if ((0, import_node_fs74.existsSync)(path2)) {
66906
67572
  try {
66907
- config = import_toml6.default.parse((0, import_node_fs72.readFileSync)(path2, "utf-8"));
67573
+ config = import_toml6.default.parse((0, import_node_fs74.readFileSync)(path2, "utf-8"));
66908
67574
  } catch (err) {
66909
67575
  console.log(source_default.red(` \u2717 ${path2} is not valid TOML: ${err.message}
66910
67576
  `));
@@ -67017,8 +67683,8 @@ function welcomeCommand() {
67017
67683
  }
67018
67684
 
67019
67685
  // src/commands/properties.ts
67020
- var import_node_fs73 = require("fs");
67021
- var import_node_path51 = require("path");
67686
+ var import_node_fs75 = require("fs");
67687
+ var import_node_path52 = require("path");
67022
67688
  var import_node_readline4 = __toESM(require("readline"));
67023
67689
  init_cli_config();
67024
67690
  var API_URL6 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
@@ -67348,8 +68014,8 @@ async function propertiesRunsCommand(opts) {
67348
68014
  }
67349
68015
  }
67350
68016
  function parseImportFile(path2) {
67351
- const ext = (0, import_node_path51.extname)(path2).toLowerCase();
67352
- const raw = (0, import_node_fs73.readFileSync)(path2, "utf-8");
68017
+ const ext = (0, import_node_path52.extname)(path2).toLowerCase();
68018
+ const raw = (0, import_node_fs75.readFileSync)(path2, "utf-8");
67353
68019
  if (ext === ".json") {
67354
68020
  const parsed = JSON.parse(raw);
67355
68021
  if (!Array.isArray(parsed)) throw new Error("JSON must be an array of objects");
@@ -67591,13 +68257,13 @@ async function rulesCommand(opts) {
67591
68257
  }
67592
68258
 
67593
68259
  // src/commands/harden.ts
67594
- var import_node_fs75 = require("fs");
67595
- var import_node_child_process30 = require("child_process");
68260
+ var import_node_fs77 = require("fs");
68261
+ var import_node_child_process31 = require("child_process");
67596
68262
  init_cli_config();
67597
68263
 
67598
68264
  // src/commands/cis-report.ts
67599
- var import_node_os22 = require("os");
67600
- var import_node_fs74 = require("fs");
68265
+ var import_node_os24 = require("os");
68266
+ var import_node_fs76 = require("fs");
67601
68267
 
67602
68268
  // ../../packages/scan/src/cis/crosswalk.ts
67603
68269
  var CAC_TAG = "v0.1.82";
@@ -67917,7 +68583,7 @@ ${xref}
67917
68583
  function osRelease() {
67918
68584
  let raw = "";
67919
68585
  try {
67920
- raw = (0, import_node_fs74.readFileSync)("/etc/os-release", "utf8");
68586
+ raw = (0, import_node_fs76.readFileSync)("/etc/os-release", "utf8");
67921
68587
  } catch {
67922
68588
  return {};
67923
68589
  }
@@ -67980,7 +68646,7 @@ function buildCisEvidenceReport(findings2, score, now = /* @__PURE__ */ new Date
67980
68646
  generated_at: now.toISOString(),
67981
68647
  disclaimer: CIS_DISCLAIMER,
67982
68648
  benchmark_catalog_checked_at: CIS_CATALOG_CHECKED_AT,
67983
- host: { hostname: (0, import_node_os22.hostname)(), os_id: id, os_version: version, pretty_name: os5.PRETTY_NAME ?? null },
68649
+ host: { hostname: (0, import_node_os24.hostname)(), os_id: id, os_version: version, pretty_name: os5.PRETTY_NAME ?? null },
67984
68650
  benchmark: edition ? { ...edition } : null,
67985
68651
  mapping_profile: profile2 ? {
67986
68652
  name: profile2.benchmarkName,
@@ -68051,20 +68717,20 @@ function writeCisReport(path2, format2, report) {
68051
68717
  const markdown = renderCisMarkdown(report);
68052
68718
  const content = format2 === "json" ? `${JSON.stringify(report, null, 2)}
68053
68719
  ` : format2 === "pdf" ? renderCisPdf(markdown) : markdown;
68054
- (0, import_node_fs74.writeFileSync)(path2, content);
68720
+ (0, import_node_fs76.writeFileSync)(path2, content);
68055
68721
  }
68056
68722
 
68057
68723
  // src/commands/harden.ts
68058
68724
  function tryExec(cmd) {
68059
68725
  try {
68060
- return (0, import_node_child_process30.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
68726
+ return (0, import_node_child_process31.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
68061
68727
  } catch {
68062
68728
  return null;
68063
68729
  }
68064
68730
  }
68065
68731
  function tryRead(path2) {
68066
68732
  try {
68067
- return (0, import_node_fs75.readFileSync)(path2, "utf-8");
68733
+ return (0, import_node_fs77.readFileSync)(path2, "utf-8");
68068
68734
  } catch {
68069
68735
  return null;
68070
68736
  }
@@ -68178,8 +68844,8 @@ function checkSshWeakConfig() {
68178
68844
  };
68179
68845
  }
68180
68846
  function checkAutoUpdates() {
68181
- const unattended = (0, import_node_fs75.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs75.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
68182
- const dnfAuto = (0, import_node_fs75.existsSync)("/etc/dnf/automatic.conf");
68847
+ const unattended = (0, import_node_fs77.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs77.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
68848
+ const dnfAuto = (0, import_node_fs77.existsSync)("/etc/dnf/automatic.conf");
68183
68849
  if (unattended || dnfAuto) {
68184
68850
  return {
68185
68851
  key: "auto-updates",
@@ -68305,7 +68971,7 @@ function checkFail2ban() {
68305
68971
  explanation: "fail2ban is installed and running."
68306
68972
  };
68307
68973
  }
68308
- if ((0, import_node_fs75.existsSync)("/etc/fail2ban/fail2ban.conf")) {
68974
+ if ((0, import_node_fs77.existsSync)("/etc/fail2ban/fail2ban.conf")) {
68309
68975
  return {
68310
68976
  key: checkKey,
68311
68977
  status: "warn",
@@ -68530,9 +69196,9 @@ async function hardenCommand(opts) {
68530
69196
  }
68531
69197
 
68532
69198
  // src/core/patches/index.ts
68533
- var import_node_fs76 = require("fs");
68534
- var import_node_path52 = require("path");
68535
- var import_node_child_process31 = require("child_process");
69199
+ var import_node_fs78 = require("fs");
69200
+ var import_node_path53 = require("path");
69201
+ var import_node_child_process32 = require("child_process");
68536
69202
  var import_node_util5 = require("util");
68537
69203
 
68538
69204
  // src/core/patches/dpkg-version.ts
@@ -68590,9 +69256,9 @@ function compareDebianVersions(a, b) {
68590
69256
  var OSV_QUERY = "https://api.osv.dev/v1/query";
68591
69257
  var STALE_AFTER_MS = 2 * 864e5;
68592
69258
  var SEVERITIES2 = ["info", "low", "medium", "high", "critical"];
68593
- var RANK = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
69259
+ var RANK2 = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
68594
69260
  var defaultExec = async (file, args) => {
68595
- const { stdout } = await (0, import_node_util5.promisify)(import_node_child_process31.execFile)(file, args, {
69261
+ const { stdout } = await (0, import_node_util5.promisify)(import_node_child_process32.execFile)(file, args, {
68596
69262
  timeout: 12e4,
68597
69263
  maxBuffer: 32 * 1024 * 1024,
68598
69264
  env: { ...process.env, LC_ALL: "C" }
@@ -68691,9 +69357,9 @@ async function osvRecords(doFetch, ecosystem, source, version) {
68691
69357
  function newestReleaseMtime(dir) {
68692
69358
  try {
68693
69359
  let newest = 0;
68694
- for (const name of (0, import_node_fs76.readdirSync)(dir)) {
69360
+ for (const name of (0, import_node_fs78.readdirSync)(dir)) {
68695
69361
  if (!/Release$/.test(name)) continue;
68696
- newest = Math.max(newest, (0, import_node_fs76.statSync)((0, import_node_path52.join)(dir, name)).mtimeMs);
69362
+ newest = Math.max(newest, (0, import_node_fs78.statSync)((0, import_node_path53.join)(dir, name)).mtimeMs);
68697
69363
  }
68698
69364
  return newest > 0 ? new Date(newest) : null;
68699
69365
  } catch {
@@ -68710,7 +69376,7 @@ async function checkPatches(opts = {}) {
68710
69376
  let osText = opts.osRelease;
68711
69377
  if (osText === void 0) {
68712
69378
  try {
68713
- osText = (0, import_node_fs76.readFileSync)("/etc/os-release", "utf-8");
69379
+ osText = (0, import_node_fs78.readFileSync)("/etc/os-release", "utf-8");
68714
69380
  } catch {
68715
69381
  osText = "";
68716
69382
  }
@@ -68791,12 +69457,12 @@ async function checkPatches(opts = {}) {
68791
69457
  } catch (err) {
68792
69458
  report.osv_error ??= err.message;
68793
69459
  }
68794
- pkg.cves.sort((a, b) => RANK[b.severity] - RANK[a.severity] || a.id.localeCompare(b.id));
69460
+ pkg.cves.sort((a, b) => RANK2[b.severity] - RANK2[a.severity] || a.id.localeCompare(b.id));
68795
69461
  if (pkg.cves.length > 0) pkg.severity = pkg.cves[0].severity;
68796
69462
  pkg.binaries.sort();
68797
69463
  }
68798
69464
  report.packages = [...bySource.values()].sort(
68799
- (a, b) => RANK[b.severity] - RANK[a.severity] || b.cves.length - a.cves.length || a.source.localeCompare(b.source)
69465
+ (a, b) => RANK2[b.severity] - RANK2[a.severity] || b.cves.length - a.cves.length || a.source.localeCompare(b.source)
68800
69466
  );
68801
69467
  const counts = emptyCounts2();
68802
69468
  counts.packages = report.packages.length;
@@ -68809,7 +69475,7 @@ async function checkPatches(opts = {}) {
68809
69475
  }
68810
69476
  function worstSeverity(report) {
68811
69477
  if (report.packages.length === 0) return null;
68812
- return report.packages.reduce((w, p) => RANK[p.severity] > RANK[w] ? p.severity : w, "info");
69478
+ return report.packages.reduce((w, p) => RANK2[p.severity] > RANK2[w] ? p.severity : w, "info");
68813
69479
  }
68814
69480
  var MAX_DETAIL_PACKAGES = 30;
68815
69481
  function patchFinding(report) {
@@ -68936,27 +69602,27 @@ async function patchesCommand(opts) {
68936
69602
  }
68937
69603
 
68938
69604
  // src/commands/feeds.ts
68939
- var import_node_net24 = require("net");
68940
- var import_node_path54 = require("path");
69605
+ var import_node_net25 = require("net");
69606
+ var import_node_path55 = require("path");
68941
69607
  init_paths();
68942
69608
 
68943
69609
  // src/commands/feeds-resolver.ts
68944
- var import_node_child_process32 = require("child_process");
68945
- var import_node_fs77 = require("fs");
68946
- var import_node_path53 = require("path");
69610
+ var import_node_child_process33 = require("child_process");
69611
+ var import_node_fs79 = require("fs");
69612
+ var import_node_path54 = require("path");
68947
69613
  var realIO = {
68948
- exists: (p) => (0, import_node_fs77.existsSync)(p),
69614
+ exists: (p) => (0, import_node_fs79.existsSync)(p),
68949
69615
  read: (p) => {
68950
69616
  try {
68951
- return (0, import_node_fs77.readFileSync)(p, "utf-8");
69617
+ return (0, import_node_fs79.readFileSync)(p, "utf-8");
68952
69618
  } catch {
68953
69619
  return null;
68954
69620
  }
68955
69621
  },
68956
- write: (p, c) => (0, import_node_fs77.writeFileSync)(p, c),
68957
- remove: (p) => (0, import_node_fs77.rmSync)(p, { force: true }),
69622
+ write: (p, c) => (0, import_node_fs79.writeFileSync)(p, c),
69623
+ remove: (p) => (0, import_node_fs79.rmSync)(p, { force: true }),
68958
69624
  run: (cmd, args) => {
68959
- const r = (0, import_node_child_process32.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 3e4 });
69625
+ const r = (0, import_node_child_process33.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 3e4 });
68960
69626
  return { code: r.status ?? 1, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() };
68961
69627
  }
68962
69628
  };
@@ -68964,17 +69630,17 @@ var APPARMOR_LOCAL = "/etc/apparmor.d/local/usr.sbin.unbound";
68964
69630
  var APPARMOR_PROFILE = "/etc/apparmor.d/usr.sbin.unbound";
68965
69631
  function hookContent(resolver, stateDir) {
68966
69632
  const head2 = "# Installed by `threatcrush feeds resolver install`; `threatcrush feeds resolver remove` takes it out.\n";
68967
- return resolver === "dnsmasq" ? `${head2}addn-hosts=${(0, import_node_path53.join)(stateDir, RESOLVER_FILES.hosts)}
68968
- ` : `${head2}include: "${(0, import_node_path53.join)(stateDir, RESOLVER_FILES.unbound)}"
69633
+ return resolver === "dnsmasq" ? `${head2}addn-hosts=${(0, import_node_path54.join)(stateDir, RESOLVER_FILES.hosts)}
69634
+ ` : `${head2}include: "${(0, import_node_path54.join)(stateDir, RESOLVER_FILES.unbound)}"
68969
69635
  `;
68970
69636
  }
68971
69637
  function apparmorRule(stateDir) {
68972
- return ` ${(0, import_node_path53.join)(stateDir, RESOLVER_FILES.unbound)} r, # threatcrush`;
69638
+ return ` ${(0, import_node_path54.join)(stateDir, RESOLVER_FILES.unbound)} r, # threatcrush`;
68973
69639
  }
68974
69640
  function detectResolvers(io = realIO) {
68975
69641
  const found = [];
68976
- if (io.exists((0, import_node_path53.dirname)(RESOLVER_HOOKS.dnsmasq)) && io.run("dnsmasq", ["--version"]).code === 0) found.push("dnsmasq");
68977
- if (io.exists((0, import_node_path53.dirname)(RESOLVER_HOOKS.unbound)) && io.run("unbound-checkconf", ["-h"]).code !== 127) found.push("unbound");
69642
+ if (io.exists((0, import_node_path54.dirname)(RESOLVER_HOOKS.dnsmasq)) && io.run("dnsmasq", ["--version"]).code === 0) found.push("dnsmasq");
69643
+ if (io.exists((0, import_node_path54.dirname)(RESOLVER_HOOKS.unbound)) && io.run("unbound-checkconf", ["-h"]).code !== 127) found.push("unbound");
68978
69644
  return found;
68979
69645
  }
68980
69646
  function check(resolver, io) {
@@ -68987,7 +69653,7 @@ function restartIfActive(resolver, io) {
68987
69653
  }
68988
69654
  function installHook(resolver, stateDir, io = realIO) {
68989
69655
  const hook = RESOLVER_HOOKS[resolver];
68990
- const file = (0, import_node_path53.join)(stateDir, resolver === "dnsmasq" ? RESOLVER_FILES.hosts : RESOLVER_FILES.unbound);
69656
+ const file = (0, import_node_path54.join)(stateDir, resolver === "dnsmasq" ? RESOLVER_FILES.hosts : RESOLVER_FILES.unbound);
68991
69657
  if (!io.exists(file)) io.write(file, resolver === "dnsmasq" ? hostsBlocklist([]) : unboundBlocklist([]));
68992
69658
  io.write(hook, hookContent(resolver, stateDir));
68993
69659
  if (resolver === "unbound" && io.exists(APPARMOR_LOCAL)) {
@@ -69048,8 +69714,8 @@ function resolverCommand(sub, stateDir, io = realIO) {
69048
69714
  }
69049
69715
  return failed ? 1 : 0;
69050
69716
  }
69051
- const hosts = io.read((0, import_node_path53.join)(stateDir, RESOLVER_FILES.hosts));
69052
- const unbound = io.read((0, import_node_path53.join)(stateDir, RESOLVER_FILES.unbound));
69717
+ const hosts = io.read((0, import_node_path54.join)(stateDir, RESOLVER_FILES.hosts));
69718
+ const unbound = io.read((0, import_node_path54.join)(stateDir, RESOLVER_FILES.unbound));
69053
69719
  console.log(` resolvers here: ${found.join(", ") || "none that can block (systemd-resolved only?)"}`);
69054
69720
  for (const r of ["dnsmasq", "unbound"]) {
69055
69721
  console.log(` ${r.padEnd(8)} hook ${io.exists(RESOLVER_HOOKS[r]) ? source_default.green("installed") : source_default.gray("not installed")}`);
@@ -69061,11 +69727,11 @@ function resolverCommand(sub, stateDir, io = realIO) {
69061
69727
  // src/commands/feeds.ts
69062
69728
  async function loadSet() {
69063
69729
  for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
69064
- const path2 = (0, import_node_path54.join)(dir, "threat-feeds.json");
69730
+ const path2 = (0, import_node_path55.join)(dir, "threat-feeds.json");
69065
69731
  const set = readFeedCache(path2);
69066
69732
  if (set) return { set, from: path2 };
69067
69733
  }
69068
- const settings = threatFeedSettings(loadConfig((0, import_node_path54.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
69734
+ const settings = threatFeedSettings(loadConfig((0, import_node_path55.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
69069
69735
  return { set: await fetchFeeds(settings), from: "abuse.ch (live; no daemon cache readable)" };
69070
69736
  }
69071
69737
  async function feedsCommand(action, value, opts) {
@@ -69080,8 +69746,8 @@ async function feedsCommand(action, value, opts) {
69080
69746
  process.exitCode = 2;
69081
69747
  return;
69082
69748
  }
69083
- const ipHit = (0, import_node_net24.isIP)(value) ? matchIp(value, set) : null;
69084
- const domainHit = (0, import_node_net24.isIP)(value) ? null : matchDomain(value, set);
69749
+ const ipHit = (0, import_node_net25.isIP)(value) ? matchIp(value, set) : null;
69750
+ const domainHit = (0, import_node_net25.isIP)(value) ? null : matchDomain(value, set);
69085
69751
  const listed = ipHit ?? domainHit?.indicator ?? null;
69086
69752
  if (opts.json) {
69087
69753
  console.log(JSON.stringify({ value, listed: Boolean(listed), indicator: listed, matched: domainHit?.domain ?? (ipHit ? value : null), fetched_at: set.fetched_at }, null, 2));
@@ -69119,21 +69785,21 @@ async function feedsCommand(action, value, opts) {
69119
69785
  }
69120
69786
 
69121
69787
  // src/commands/tor.ts
69122
- var import_node_fs78 = require("fs");
69123
- var import_node_net25 = require("net");
69124
- var import_node_path55 = require("path");
69788
+ var import_node_fs80 = require("fs");
69789
+ var import_node_net26 = require("net");
69790
+ var import_node_path56 = require("path");
69125
69791
  init_paths();
69126
69792
  async function torCommand(action, value, opts) {
69127
69793
  let exits = /* @__PURE__ */ new Set();
69128
69794
  let from = "";
69129
69795
  let updated = null;
69130
69796
  for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
69131
- const path2 = (0, import_node_path55.join)(dir, "tor-exits.txt");
69797
+ const path2 = (0, import_node_path56.join)(dir, "tor-exits.txt");
69132
69798
  try {
69133
- if (!(0, import_node_fs78.existsSync)(path2)) continue;
69134
- exits = parseTorExitList((0, import_node_fs78.readFileSync)(path2, "utf-8"));
69799
+ if (!(0, import_node_fs80.existsSync)(path2)) continue;
69800
+ exits = parseTorExitList((0, import_node_fs80.readFileSync)(path2, "utf-8"));
69135
69801
  from = path2;
69136
- updated = (0, import_node_fs78.statSync)(path2).mtime;
69802
+ updated = (0, import_node_fs80.statSync)(path2).mtime;
69137
69803
  break;
69138
69804
  } catch {
69139
69805
  }
@@ -69149,10 +69815,10 @@ async function torCommand(action, value, opts) {
69149
69815
  } catch {
69150
69816
  }
69151
69817
  }
69152
- const remediation = loadConfig((0, import_node_path55.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).remediation;
69818
+ const remediation = loadConfig((0, import_node_path56.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).remediation;
69153
69819
  const ban = remediation?.block_tor_ssh !== false && remediation?.enabled !== false;
69154
69820
  if (action === "check") {
69155
- if (!value || !(0, import_node_net25.isIP)(value)) {
69821
+ if (!value || !(0, import_node_net26.isIP)(value)) {
69156
69822
  console.error("Usage: threatcrush tor check <ip>");
69157
69823
  process.exitCode = 2;
69158
69824
  return;
@@ -69180,14 +69846,14 @@ async function torCommand(action, value, opts) {
69180
69846
  }
69181
69847
 
69182
69848
  // src/commands/reputation.ts
69183
- var import_node_os23 = require("os");
69184
- var import_node_fs79 = require("fs");
69185
- var import_node_path56 = require("path");
69849
+ var import_node_os25 = require("os");
69850
+ var import_node_fs81 = require("fs");
69851
+ var import_node_path57 = require("path");
69186
69852
  var API_URL7 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
69187
- var CONFIG_PATH4 = (0, import_node_path56.join)((0, import_node_os23.homedir)(), ".threatcrush", "config.json");
69853
+ var CONFIG_PATH4 = (0, import_node_path57.join)((0, import_node_os25.homedir)(), ".threatcrush", "config.json");
69188
69854
  function readConfig3() {
69189
69855
  try {
69190
- return JSON.parse((0, import_node_fs79.readFileSync)(CONFIG_PATH4, "utf-8"));
69856
+ return JSON.parse((0, import_node_fs81.readFileSync)(CONFIG_PATH4, "utf-8"));
69191
69857
  } catch {
69192
69858
  return {};
69193
69859
  }
@@ -69375,7 +70041,7 @@ async function reputationSubscribeCommand(opts) {
69375
70041
  }
69376
70042
 
69377
70043
  // src/commands/privileged.ts
69378
- var import_node_fs80 = require("fs");
70044
+ var import_node_fs82 = require("fs");
69379
70045
  init_paths();
69380
70046
  var SEV2 = {
69381
70047
  critical: source_default.red.bold,
@@ -69388,19 +70054,19 @@ async function privilegedCommand(opts) {
69388
70054
  const snapshot = takeSnapshot({
69389
70055
  readFile: (p) => {
69390
70056
  try {
69391
- return (0, import_node_fs80.readFileSync)(p, "utf-8");
70057
+ return (0, import_node_fs82.readFileSync)(p, "utf-8");
69392
70058
  } catch {
69393
70059
  return null;
69394
70060
  }
69395
70061
  },
69396
70062
  readDir: (p) => {
69397
70063
  try {
69398
- return (0, import_node_fs80.readdirSync)(p);
70064
+ return (0, import_node_fs82.readdirSync)(p);
69399
70065
  } catch {
69400
70066
  return null;
69401
70067
  }
69402
70068
  },
69403
- exists: (p) => (0, import_node_fs80.existsSync)(p)
70069
+ exists: (p) => (0, import_node_fs82.existsSync)(p)
69404
70070
  });
69405
70071
  let events = [];
69406
70072
  let ledgerNote = "";
@@ -69442,12 +70108,12 @@ async function privilegedCommand(opts) {
69442
70108
  }
69443
70109
 
69444
70110
  // src/commands/integrity.ts
69445
- var import_node_fs81 = require("fs");
69446
- var import_node_path57 = require("path");
70111
+ var import_node_fs83 = require("fs");
70112
+ var import_node_path58 = require("path");
69447
70113
  init_paths();
69448
70114
  function readState2(path2) {
69449
70115
  try {
69450
- return JSON.parse((0, import_node_fs81.readFileSync)(path2, "utf8"));
70116
+ return JSON.parse((0, import_node_fs83.readFileSync)(path2, "utf8"));
69451
70117
  } catch {
69452
70118
  return null;
69453
70119
  }
@@ -69467,11 +70133,11 @@ function changedCount(baseline, observed) {
69467
70133
  async function integrityCommand(action = "status", opts = {}) {
69468
70134
  const config = loadConfig();
69469
70135
  const settings = fileIntegritySettings(config.file_integrity);
69470
- const systemBaseline = (0, import_node_path57.join)(SYSTEM_PATHS.stateDir, "file-integrity-baseline.json");
69471
- const useSystemState = PATHS.mode === "system" || systemDaemonPresent() || (0, import_node_fs81.existsSync)(systemBaseline);
70136
+ const systemBaseline = (0, import_node_path58.join)(SYSTEM_PATHS.stateDir, "file-integrity-baseline.json");
70137
+ const useSystemState = PATHS.mode === "system" || systemDaemonPresent() || (0, import_node_fs83.existsSync)(systemBaseline);
69472
70138
  const stateDir = useSystemState ? SYSTEM_PATHS.stateDir : PATHS.stateDir;
69473
- const baselinePath = (0, import_node_path57.join)(stateDir, "file-integrity-baseline.json");
69474
- const observedPath = (0, import_node_path57.join)(stateDir, "file-integrity-observed.json");
70139
+ const baselinePath = (0, import_node_path58.join)(stateDir, "file-integrity-baseline.json");
70140
+ const observedPath = (0, import_node_path58.join)(stateDir, "file-integrity-observed.json");
69475
70141
  if (action === "rebaseline") {
69476
70142
  const watch4 = new FileIntegrityWatch({
69477
70143
  bus: { publish: () => void 0 },
@@ -69539,13 +70205,13 @@ async function integrityCommand(action = "status", opts = {}) {
69539
70205
  }
69540
70206
 
69541
70207
  // src/commands/edr.ts
69542
- var import_node_fs83 = require("fs");
70208
+ var import_node_fs85 = require("fs");
69543
70209
  init_paths();
69544
70210
 
69545
70211
  // src/daemon/auditd/rules.ts
69546
- var import_node_fs82 = require("fs");
69547
- var import_node_child_process33 = require("child_process");
69548
- var import_node_path58 = require("path");
70212
+ var import_node_fs84 = require("fs");
70213
+ var import_node_child_process34 = require("child_process");
70214
+ var import_node_path59 = require("path");
69549
70215
  var WEB_TOOLS = ["sh", "bash", "dash", "zsh", "curl", "wget"];
69550
70216
  var MINER_NAMES = ["xmrig", "minerd", "cpuminer", "cpuminer-multi", "kdevtmpfsi", "kinsing", "cryptonight"];
69551
70217
  var CONNECT_KEY2 = "threatcrush_edr_connect";
@@ -69553,10 +70219,10 @@ var LISTEN_KEY2 = "threatcrush_edr_listen";
69553
70219
  function passwdByName() {
69554
70220
  let raw = "";
69555
70221
  try {
69556
- raw = (0, import_node_child_process33.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
70222
+ raw = (0, import_node_child_process34.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
69557
70223
  } catch {
69558
70224
  try {
69559
- raw = (0, import_node_fs82.readFileSync)("/etc/passwd", "utf8");
70225
+ raw = (0, import_node_fs84.readFileSync)("/etc/passwd", "utf8");
69560
70226
  } catch {
69561
70227
  return /* @__PURE__ */ new Map();
69562
70228
  }
@@ -69575,8 +70241,8 @@ function existingExecutables(names) {
69575
70241
  for (const prefix of ["/bin", "/usr/bin", "/usr/local/bin"]) {
69576
70242
  const candidate = `${prefix}/${name}`;
69577
70243
  try {
69578
- if (!(0, import_node_fs82.existsSync)(candidate) || !(0, import_node_fs82.statSync)(candidate).isFile()) continue;
69579
- paths.add((0, import_node_fs82.realpathSync)(candidate));
70244
+ if (!(0, import_node_fs84.existsSync)(candidate) || !(0, import_node_fs84.statSync)(candidate).isFile()) continue;
70245
+ paths.add((0, import_node_fs84.realpathSync)(candidate));
69580
70246
  } catch {
69581
70247
  }
69582
70248
  }
@@ -69585,9 +70251,9 @@ function existingExecutables(names) {
69585
70251
  }
69586
70252
  function existingDirectories(paths) {
69587
70253
  return [...new Set(paths)].filter((path2) => {
69588
- if (!(0, import_node_path58.isAbsolute)(path2) || /[\s\r\n]/.test(path2)) return false;
70254
+ if (!(0, import_node_path59.isAbsolute)(path2) || /[\s\r\n]/.test(path2)) return false;
69589
70255
  try {
69590
- return (0, import_node_fs82.statSync)(path2).isDirectory();
70256
+ return (0, import_node_fs84.statSync)(path2).isDirectory();
69591
70257
  } catch {
69592
70258
  return false;
69593
70259
  }
@@ -69630,7 +70296,7 @@ function generateAuditRules(settings) {
69630
70296
  }
69631
70297
 
69632
70298
  // src/commands/edr.ts
69633
- var import_node_path59 = require("path");
70299
+ var import_node_path60 = require("path");
69634
70300
  async function edrCommand(action = "status", opts = {}) {
69635
70301
  const settings = edrSettings(loadConfig().edr);
69636
70302
  if (action === "rules") {
@@ -69655,8 +70321,8 @@ async function edrCommand(action = "status", opts = {}) {
69655
70321
  }
69656
70322
  let readable = false;
69657
70323
  try {
69658
- if ((0, import_node_fs83.existsSync)(settings.auditLogPath)) (0, import_node_fs83.accessSync)(settings.auditLogPath, import_node_fs83.constants.R_OK);
69659
- readable = (0, import_node_fs83.existsSync)(settings.auditLogPath);
70324
+ if ((0, import_node_fs85.existsSync)(settings.auditLogPath)) (0, import_node_fs85.accessSync)(settings.auditLogPath, import_node_fs85.constants.R_OK);
70325
+ readable = (0, import_node_fs85.existsSync)(settings.auditLogPath);
69660
70326
  } catch {
69661
70327
  }
69662
70328
  let events = [];
@@ -69668,7 +70334,7 @@ async function edrCommand(action = "status", opts = {}) {
69668
70334
  stateNote = `the daemon state database (${PATHS.stateDb}) is not readable here`;
69669
70335
  }
69670
70336
  const selection = selectEdrSource(settings.source === "auditd" ? { configured: "auditd", bpftracePath: null, btfPresent: false, isRoot: false } : probeHost(settings.source));
69671
- const daemonSource = readEdrSourceStatus((0, import_node_path59.join)(PATHS.stateDir, "edr-source.json"));
70337
+ const daemonSource = readEdrSourceStatus((0, import_node_path60.join)(PATHS.stateDir, "edr-source.json"));
69672
70338
  const report = {
69673
70339
  enabled: settings.enabled,
69674
70340
  source: settings.source,
@@ -69854,7 +70520,7 @@ async function allowlistCommand(opts) {
69854
70520
  }
69855
70521
 
69856
70522
  // src/commands/abuse.ts
69857
- var import_node_fs84 = require("fs");
70523
+ var import_node_fs86 = require("fs");
69858
70524
  init_paths();
69859
70525
  function rows(records) {
69860
70526
  if (records.length === 0) {
@@ -69914,7 +70580,7 @@ function abuseRetractCommand(id, opts = {}) {
69914
70580
  );
69915
70581
  }
69916
70582
  function abuseStatusCommand(opts = {}) {
69917
- const config = loadConfig((0, import_node_fs84.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
70583
+ const config = loadConfig((0, import_node_fs86.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
69918
70584
  const cfg = resolveConfig(config.abuse_reporter);
69919
70585
  const hasKey2 = Boolean(cfg.keys.abuseipdb || cfg.keys.stopforumspam);
69920
70586
  const active2 = cfg.enabled && (cfg.dryRun || hasKey2);
@@ -69937,11 +70603,11 @@ function abuseStatusCommand(opts = {}) {
69937
70603
  init_paths();
69938
70604
 
69939
70605
  // src/upgrade.ts
69940
- var import_node_child_process34 = require("child_process");
70606
+ var import_node_child_process35 = require("child_process");
69941
70607
  var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
69942
70608
  var defaultRunner = (cmd) => {
69943
70609
  try {
69944
- return (0, import_node_child_process34.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
70610
+ return (0, import_node_child_process35.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
69945
70611
  } catch {
69946
70612
  return null;
69947
70613
  }
@@ -70082,9 +70748,9 @@ function installUserAgent(target = globalThis) {
70082
70748
  }
70083
70749
 
70084
70750
  // src/core/cloud-upload.ts
70085
- var import_node_child_process35 = require("child_process");
70086
- var import_node_os24 = require("os");
70087
- var import_node_path60 = require("path");
70751
+ var import_node_child_process36 = require("child_process");
70752
+ var import_node_os26 = require("os");
70753
+ var import_node_path61 = require("path");
70088
70754
  init_cli_config();
70089
70755
  function uploadDisabled(upload, env3 = process.env) {
70090
70756
  if (upload === false) return true;
@@ -70103,8 +70769,8 @@ function cleanUrl(raw) {
70103
70769
  return raw.split(/[?#]/)[0];
70104
70770
  }
70105
70771
  }
70106
- function repoTarget(path2, run3 = (args) => (0, import_node_child_process35.execFileSync)("git", args, { cwd: (0, import_node_path60.resolve)(path2), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 }).trim()) {
70107
- const abs = (0, import_node_path60.resolve)(path2);
70772
+ function repoTarget(path2, run3 = (args) => (0, import_node_child_process36.execFileSync)("git", args, { cwd: (0, import_node_path61.resolve)(path2), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 }).trim()) {
70773
+ const abs = (0, import_node_path61.resolve)(path2);
70108
70774
  try {
70109
70775
  const root = run3(["rev-parse", "--show-toplevel"]);
70110
70776
  const sub = abs === root ? "." : abs.slice(root.length + 1);
@@ -70117,9 +70783,9 @@ function repoTarget(path2, run3 = (args) => (0, import_node_child_process35.exec
70117
70783
  const m = /^(?:[a-z+]+:\/\/)?(?:[^@/]+@)?([^/:]+)[:/](.+?)(?:\.git)?\/?$/i.exec(remote);
70118
70784
  if (m) return { target: `${m[1]}/${m[2]}`, root, sub };
70119
70785
  }
70120
- return { target: `${(0, import_node_os24.hostname)()}:${root}`, root, sub };
70786
+ return { target: `${(0, import_node_os26.hostname)()}:${root}`, root, sub };
70121
70787
  } catch {
70122
- return { target: `${(0, import_node_os24.hostname)()}:${abs}`, root: abs, sub: "." };
70788
+ return { target: `${(0, import_node_os26.hostname)()}:${abs}`, root: abs, sub: "." };
70123
70789
  }
70124
70790
  }
70125
70791
  async function uploadResult(result, opts) {
@@ -70476,25 +71142,25 @@ ${source_default.dim(" C R U S H")}
70476
71142
  var API_URL8 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
70477
71143
  var PKG_NAME2 = "@profullstack/threatcrush";
70478
71144
  var DESKTOP_PKG_NAME = "@profullstack/threatcrush-desktop";
70479
- var INSTALL_CONFIG_PATH = (0, import_node_path61.join)((0, import_node_os25.homedir)(), ".threatcrush", "install.json");
71145
+ var INSTALL_CONFIG_PATH = (0, import_node_path62.join)((0, import_node_os27.homedir)(), ".threatcrush", "install.json");
70480
71146
  function detectPackageManager2() {
70481
71147
  try {
70482
- const npmGlobal = (0, import_node_child_process36.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
71148
+ const npmGlobal = (0, import_node_child_process37.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
70483
71149
  if (npmGlobal.includes(PKG_NAME2)) return "npm";
70484
71150
  } catch {
70485
71151
  }
70486
71152
  try {
70487
- (0, import_node_child_process36.execSync)("pnpm --version", { stdio: "pipe" });
71153
+ (0, import_node_child_process37.execSync)("pnpm --version", { stdio: "pipe" });
70488
71154
  return "pnpm";
70489
71155
  } catch {
70490
71156
  }
70491
71157
  try {
70492
- (0, import_node_child_process36.execSync)("yarn --version", { stdio: "pipe" });
71158
+ (0, import_node_child_process37.execSync)("yarn --version", { stdio: "pipe" });
70493
71159
  return "yarn";
70494
71160
  } catch {
70495
71161
  }
70496
71162
  try {
70497
- (0, import_node_child_process36.execSync)("bun --version", { stdio: "pipe" });
71163
+ (0, import_node_child_process37.execSync)("bun --version", { stdio: "pipe" });
70498
71164
  return "bun";
70499
71165
  } catch {
70500
71166
  }
@@ -70502,14 +71168,14 @@ function detectPackageManager2() {
70502
71168
  }
70503
71169
  function readInstallConfig() {
70504
71170
  try {
70505
- return JSON.parse((0, import_node_fs85.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
71171
+ return JSON.parse((0, import_node_fs87.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
70506
71172
  } catch {
70507
71173
  return {};
70508
71174
  }
70509
71175
  }
70510
71176
  function packageLooksInstalled(pm, pkgName) {
70511
71177
  try {
70512
- const output = (0, import_node_child_process36.execSync)(globalListCommand(pm, pkgName), {
71178
+ const output = (0, import_node_child_process37.execSync)(globalListCommand(pm, pkgName), {
70513
71179
  encoding: "utf-8",
70514
71180
  stdio: ["pipe", "pipe", "pipe"]
70515
71181
  });
@@ -70612,14 +71278,14 @@ async function promoteUnprivilegedDaemon() {
70612
71278
  function restartSystemdDaemon() {
70613
71279
  const asRoot = typeof process.getuid === "function" && process.getuid() === 0;
70614
71280
  const argv = asRoot ? ["systemctl", "restart", DAEMON_UNIT] : ["sudo", "systemctl", "restart", DAEMON_UNIT];
70615
- if (!asRoot && (0, import_node_child_process36.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
71281
+ if (!asRoot && (0, import_node_child_process37.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
70616
71282
  const [cmd, ...args] = argv;
70617
- if ((0, import_node_child_process36.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
70618
- return (0, import_node_child_process36.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
71283
+ if ((0, import_node_child_process37.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
71284
+ return (0, import_node_child_process37.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
70619
71285
  }
70620
71286
  function execQuiet(cmd) {
70621
71287
  try {
70622
- return (0, import_node_child_process36.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
71288
+ return (0, import_node_child_process37.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
70623
71289
  } catch {
70624
71290
  return null;
70625
71291
  }
@@ -70951,7 +71617,7 @@ program2.command("uninstall-service").description("Remove the threatcrushd syste
70951
71617
  program2.command("logs").description("Tail daemon logs").action(async () => {
70952
71618
  console.log(LOGO2);
70953
71619
  const logPath2 = PATHS.logFile;
70954
- if (!(0, import_node_fs85.existsSync)(logPath2)) {
71620
+ if (!(0, import_node_fs87.existsSync)(logPath2)) {
70955
71621
  console.log(source_default.yellow(` No log file found at ${logPath2}`));
70956
71622
  console.log(source_default.dim(" Start the daemon first with `threatcrush start`\n"));
70957
71623
  return;
@@ -70959,7 +71625,7 @@ program2.command("logs").description("Tail daemon logs").action(async () => {
70959
71625
  console.log(source_default.green(` Tailing ${logPath2}...
70960
71626
  `));
70961
71627
  console.log(source_default.gray(" Press Ctrl+C to stop\n"));
70962
- (0, import_node_child_process36.execSync)(`tail -f ${logPath2}`, { stdio: "inherit" });
71628
+ (0, import_node_child_process37.execSync)(`tail -f ${logPath2}`, { stdio: "inherit" });
70963
71629
  });
70964
71630
  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) => {
70965
71631
  console.log(LOGO2);
@@ -70971,7 +71637,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
70971
71637
  for (const cmd of commands2) {
70972
71638
  console.log(source_default.green(` \u2192 ${cmd}
70973
71639
  `));
70974
- (0, import_node_child_process36.execSync)(cmd, { stdio: "inherit" });
71640
+ (0, import_node_child_process37.execSync)(cmd, { stdio: "inherit" });
70975
71641
  }
70976
71642
  console.log(source_default.green("\n \u2713 Modules updated successfully!\n"));
70977
71643
  await reportIfStillStale();
@@ -70996,7 +71662,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
70996
71662
  for (const cmd of commands) {
70997
71663
  console.log(source_default.green(` \u2192 ${cmd}
70998
71664
  `));
70999
- (0, import_node_child_process36.execSync)(cmd, { stdio: "inherit" });
71665
+ (0, import_node_child_process37.execSync)(cmd, { stdio: "inherit" });
71000
71666
  }
71001
71667
  console.log(source_default.green("\n \u2713 ThreatCrush updated successfully!\n"));
71002
71668
  if (installMode === "desktop") {
@@ -71047,7 +71713,7 @@ program2.command("remove").description("Uninstall ThreatCrush and the installed
71047
71713
  for (const cmd of commands) {
71048
71714
  console.log(source_default.green(` \u2192 ${cmd}
71049
71715
  `));
71050
- (0, import_node_child_process36.execSync)(cmd, { stdio: "inherit" });
71716
+ (0, import_node_child_process37.execSync)(cmd, { stdio: "inherit" });
71051
71717
  }
71052
71718
  console.log(source_default.green("\n \u2713 ThreatCrush has been uninstalled.\n"));
71053
71719
  console.log(source_default.dim(" We're sorry to see you go! \u{1F44B}\n"));
@@ -71124,10 +71790,10 @@ storeCmd.command("search <query>").description("Search for modules in the store"
71124
71790
  });
71125
71791
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
71126
71792
  console.log(LOGO2);
71127
- const configPath = (0, import_node_path61.join)((0, import_node_os25.homedir)(), ".threatcrush", "config.json");
71793
+ const configPath = (0, import_node_path62.join)((0, import_node_os27.homedir)(), ".threatcrush", "config.json");
71128
71794
  let email = "";
71129
71795
  try {
71130
- const config = JSON.parse((0, import_node_fs85.readFileSync)(configPath, "utf-8"));
71796
+ const config = JSON.parse((0, import_node_fs87.readFileSync)(configPath, "utf-8"));
71131
71797
  email = config.email || "";
71132
71798
  } catch {
71133
71799
  }
@@ -71144,9 +71810,9 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
71144
71810
  return;
71145
71811
  }
71146
71812
  try {
71147
- const dir = (0, import_node_path61.join)((0, import_node_os25.homedir)(), ".threatcrush");
71148
- if (!(0, import_node_fs85.existsSync)(dir)) (0, import_node_fs85.mkdirSync)(dir, { recursive: true });
71149
- (0, import_node_fs85.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
71813
+ const dir = (0, import_node_path62.join)((0, import_node_os27.homedir)(), ".threatcrush");
71814
+ if (!(0, import_node_fs87.existsSync)(dir)) (0, import_node_fs87.mkdirSync)(dir, { recursive: true });
71815
+ (0, import_node_fs87.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
71150
71816
  console.log(source_default.dim(` Saved email to ${configPath}`));
71151
71817
  } catch {
71152
71818
  }