@profullstack/threatcrush 0.13.60 → 0.13.62

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/daemon.js CHANGED
@@ -2026,10 +2026,10 @@ var require_toml = __commonJS({
2026
2026
  });
2027
2027
 
2028
2028
  // src/daemon/index.ts
2029
- var import_node_fs31 = require("fs");
2030
- var import_node_child_process11 = require("child_process");
2031
- var import_node_os5 = require("os");
2032
- var import_node_path24 = require("path");
2029
+ var import_node_fs34 = require("fs");
2030
+ var import_node_child_process12 = require("child_process");
2031
+ var import_node_os6 = require("os");
2032
+ var import_node_path26 = require("path");
2033
2033
  var import_node_util = require("util");
2034
2034
 
2035
2035
  // src/daemon/paths.ts
@@ -2161,6 +2161,10 @@ var EventBus = class extends import_node_events.EventEmitter {
2161
2161
  this.emit("alert", event);
2162
2162
  }
2163
2163
  }
2164
+ /** A raw sshd line with a peer address; not an event, nothing is stored or uploaded. */
2165
+ sshdLine(line) {
2166
+ this.emit("sshd", line);
2167
+ }
2164
2168
  announceModule(name, status, detail) {
2165
2169
  this.emit("module", { name, status, detail });
2166
2170
  }
@@ -2886,6 +2890,9 @@ var LogTail = class {
2886
2890
  }
2887
2891
  };
2888
2892
 
2893
+ // src/core/log-parser.ts
2894
+ var import_node_net2 = require("net");
2895
+
2889
2896
  // src/core/crs/rules.generated.ts
2890
2897
  var CRS_RULES = [
2891
2898
  {
@@ -9577,6 +9584,29 @@ function parseAuthMessage(process3, message, timestamp, raw = message) {
9577
9584
  }
9578
9585
  };
9579
9586
  }
9587
+ var ACCEPTED_REGEX = /Accepted (\S+) for (\S+) from (\S+) port (\d+)(?: [^\s:]+:\s+(\S+)\s+(SHA256:[A-Za-z0-9+/=]+))?/;
9588
+ function parseAcceptedLogin(message) {
9589
+ const m = ACCEPTED_REGEX.exec(message);
9590
+ if (!m) return null;
9591
+ return {
9592
+ method: m[1],
9593
+ user: m[2],
9594
+ ip: m[3],
9595
+ port: Number(m[4]),
9596
+ ...m[5] ? { key_type: m[5] } : {},
9597
+ ...m[6] ? { fingerprint: m[6] } : {}
9598
+ };
9599
+ }
9600
+ var SSHD_PROCESS = /^sshd(?:-session|-auth)?$/;
9601
+ function isSshdProcess(process3) {
9602
+ return !!process3 && SSHD_PROCESS.test(process3);
9603
+ }
9604
+ function sshdPeerIp(message) {
9605
+ const v4 = /(?<![\d.])(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?![\d.])/.exec(message);
9606
+ const v6 = /(?:from|by|user \S+|for connection from)\s+\[?([0-9a-fA-F]*:[0-9a-fA-F:]+)\]?/.exec(message);
9607
+ const cand = [v4 && { at: v4.index, ip: v4[1] }, v6 && { at: v6.index, ip: v6[1] }].filter((c) => !!c && (0, import_node_net2.isIP)(c.ip) !== 0).sort((a, b) => a.at - b.at);
9608
+ return cand[0]?.ip ?? null;
9609
+ }
9580
9610
  function classifySshAuth(entry) {
9581
9611
  const { ip, user, message } = entry.fields;
9582
9612
  if (/failed password/i.test(message)) {
@@ -9586,7 +9616,14 @@ function classifySshAuth(entry) {
9586
9616
  return { severity: "high", message: `Invalid SSH user: ${user || "unknown"} from ${ip || "unknown"}`, source_ip: ip };
9587
9617
  }
9588
9618
  if (/accepted/i.test(message)) {
9589
- return { severity: "info", message: `SSH login accepted for ${user || "unknown"}`, source_ip: ip };
9619
+ const login = parseAcceptedLogin(message);
9620
+ const sourceIp = ip ?? (login && (0, import_node_net2.isIP)(login.ip) ? login.ip : void 0);
9621
+ return {
9622
+ severity: "info",
9623
+ message: `SSH login accepted for ${login?.user || user || "unknown"}`,
9624
+ source_ip: sourceIp,
9625
+ ...login ? { details: { ssh_user: login.user, auth_method: login.method, port: login.port, ...login.key_type ? { key_type: login.key_type } : {}, ...login.fingerprint ? { fingerprint: login.fingerprint } : {} } } : {}
9626
+ };
9590
9627
  }
9591
9628
  return null;
9592
9629
  }
@@ -9743,9 +9780,14 @@ var LogWatcher = class {
9743
9780
  if (parsed.source === "auth") {
9744
9781
  const entry = parseAuthLog(line);
9745
9782
  if (!entry) return;
9783
+ if (isSshdProcess(entry.fields.process)) {
9784
+ const peer = sshdPeerIp(entry.fields.message);
9785
+ if (peer) this.bus.sshdLine?.({ timestamp: entry.timestamp, message: entry.fields.message, ip: peer, raw: line });
9786
+ }
9746
9787
  const verdict = classifySshAuth(entry);
9747
9788
  if (!verdict) return;
9748
9789
  ({ severity, message, source_ip: sourceIp } = verdict);
9790
+ if (verdict.details) Object.assign(details, verdict.details);
9749
9791
  } else if (parsed.source === "nginx") {
9750
9792
  const entry = parseNginxLog(line);
9751
9793
  if (!entry) return;
@@ -9821,9 +9863,17 @@ function sshEventFromJournal(entry) {
9821
9863
  category: "auth",
9822
9864
  severity: verdict.severity,
9823
9865
  message: verdict.message,
9824
- source_ip: verdict.source_ip
9866
+ source_ip: verdict.source_ip,
9867
+ ...verdict.details ? { details: verdict.details } : {}
9825
9868
  };
9826
9869
  }
9870
+ function sshdLineFromJournal(entry) {
9871
+ if (!isSshdRecord(entry) || typeof entry.MESSAGE !== "string") return null;
9872
+ const ip = sshdPeerIp(entry.MESSAGE);
9873
+ if (!ip) return null;
9874
+ const timestamp = realtimeToDate(entry.__REALTIME_TIMESTAMP) || /* @__PURE__ */ new Date();
9875
+ return { timestamp, message: entry.MESSAGE, ip, raw: entry.MESSAGE };
9876
+ }
9827
9877
  var JournalWatcher = class _JournalWatcher {
9828
9878
  constructor(bus2) {
9829
9879
  this.bus = bus2;
@@ -9890,6 +9940,8 @@ var JournalWatcher = class _JournalWatcher {
9890
9940
  child.stdout.setEncoding("utf-8");
9891
9941
  child.stdout.on("data", (chunk) => {
9892
9942
  this.sshdBuffer = this.drain(this.sshdBuffer + chunk, (entry) => {
9943
+ const line = sshdLineFromJournal(entry);
9944
+ if (line) this.bus.sshdLine?.(line);
9893
9945
  const event = sshEventFromJournal(entry);
9894
9946
  if (event) this.emit(event);
9895
9947
  });
@@ -10244,12 +10296,12 @@ var import_node_readline = require("readline");
10244
10296
  // src/core/threat-feeds/index.ts
10245
10297
  var import_node_fs11 = require("fs");
10246
10298
  var import_node_path5 = require("path");
10247
- var import_node_net3 = require("net");
10299
+ var import_node_net4 = require("net");
10248
10300
 
10249
10301
  // src/daemon/firewall/protected.ts
10250
10302
  var import_node_child_process3 = require("child_process");
10251
10303
  var import_node_fs10 = require("fs");
10252
- var import_node_net2 = require("net");
10304
+ var import_node_net3 = require("net");
10253
10305
  var DEFAULT_PROTECTED = [
10254
10306
  "127.0.0.0/8",
10255
10307
  "::1/128",
@@ -10293,7 +10345,7 @@ var SHARED_INFRASTRUCTURE = [
10293
10345
  "208.67.220.220/32"
10294
10346
  ];
10295
10347
  function ipToBytes(ip) {
10296
- const version = (0, import_node_net2.isIP)(ip);
10348
+ const version = (0, import_node_net3.isIP)(ip);
10297
10349
  if (version === 4) return v4ToBytes(ip);
10298
10350
  if (version === 6) return v6ToBytes(ip);
10299
10351
  return null;
@@ -10371,7 +10423,7 @@ function currentSshClient(env2 = process.env) {
10371
10423
  const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
10372
10424
  if (!source) return null;
10373
10425
  const ip = source.trim().split(/\s+/)[0];
10374
- return ip && (0, import_node_net2.isIP)(ip) ? ip : null;
10426
+ return ip && (0, import_node_net3.isIP)(ip) ? ip : null;
10375
10427
  }
10376
10428
  function establishedSshPeers() {
10377
10429
  const peers = /* @__PURE__ */ new Set();
@@ -10387,7 +10439,7 @@ function establishedSshPeers() {
10387
10439
  const peer = parts[4];
10388
10440
  if (!peer) continue;
10389
10441
  const ip = peer.slice(0, peer.lastIndexOf(":")).replace(/^\[|\]$/g, "");
10390
- if (ip && (0, import_node_net2.isIP)(ip)) peers.add(ip);
10442
+ if (ip && (0, import_node_net3.isIP)(ip)) peers.add(ip);
10391
10443
  }
10392
10444
  } catch {
10393
10445
  }
@@ -10396,7 +10448,7 @@ function establishedSshPeers() {
10396
10448
  function sshClientFromEnviron(environ) {
10397
10449
  for (const entry of environ.split("\0")) {
10398
10450
  const m = /^SSH_(?:CONNECTION|CLIENT)=(\S+)/.exec(entry);
10399
- if (m && (0, import_node_net2.isIP)(m[1])) return m[1];
10451
+ if (m && (0, import_node_net3.isIP)(m[1])) return m[1];
10400
10452
  }
10401
10453
  return null;
10402
10454
  }
@@ -10422,7 +10474,7 @@ function parseKeyLogins(text, skip = () => false) {
10422
10474
  const out = /* @__PURE__ */ new Map();
10423
10475
  for (const line of text.split("\n")) {
10424
10476
  const m = /^(\d+(?:\.\d+)?)\s.*Accepted publickey for \S+ from (\S+) port \d+ [^\s:]+(?:: \S+ (SHA256:\S+))?/.exec(line);
10425
- if (!m || !(0, import_node_net2.isIP)(m[2])) continue;
10477
+ if (!m || !(0, import_node_net3.isIP)(m[2])) continue;
10426
10478
  if (m[3] && skip(m[3])) continue;
10427
10479
  const at = Math.round(Number(m[1]) * 1e3);
10428
10480
  if (at > (out.get(m[2]) ?? 0)) out.set(m[2], at);
@@ -10439,7 +10491,7 @@ function defaultGateways() {
10439
10491
  const out = (0, import_node_child_process3.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
10440
10492
  for (const line of out.split("\n")) {
10441
10493
  const match = line.match(/\bvia\s+(\S+)/);
10442
- if (match && (0, import_node_net2.isIP)(match[1])) found.add(match[1]);
10494
+ if (match && (0, import_node_net3.isIP)(match[1])) found.add(match[1]);
10443
10495
  }
10444
10496
  } catch {
10445
10497
  }
@@ -10552,26 +10604,26 @@ function parseIpList(text, feed) {
10552
10604
  const out = /* @__PURE__ */ new Map();
10553
10605
  for (const line of text.split("\n")) {
10554
10606
  const ip = line.trim();
10555
- if (ip && !ip.startsWith("#") && (0, import_node_net3.isIP)(ip)) out.set(ip, { malware: "unknown", threat: "botnet_cc", feed });
10607
+ if (ip && !ip.startsWith("#") && (0, import_node_net4.isIP)(ip)) out.set(ip, { malware: "unknown", threat: "botnet_cc", feed });
10556
10608
  }
10557
10609
  return out;
10558
10610
  }
10559
10611
  function stripPort(value) {
10560
10612
  const v6 = /^\[([^\]]+)\]:\d+$/.exec(value);
10561
10613
  const ip = v6 ? v6[1] : value.replace(/:\d+$/, "");
10562
- return (0, import_node_net3.isIP)(ip) ? ip : null;
10614
+ return (0, import_node_net4.isIP)(ip) ? ip : null;
10563
10615
  }
10564
10616
  function normalizeDomain(value) {
10565
10617
  const d = value.trim().toLowerCase().replace(/\.$/, "");
10566
- if (!d || d === "localhost" || (0, import_node_net3.isIP)(d) || !/^[a-z0-9_.-]+\.[a-z0-9-]{2,}$/.test(d)) return null;
10618
+ if (!d || d === "localhost" || (0, import_node_net4.isIP)(d) || !/^[a-z0-9_.-]+\.[a-z0-9-]{2,}$/.test(d)) return null;
10567
10619
  return d;
10568
10620
  }
10569
10621
  function allowedDomain(domain, allow) {
10570
10622
  return allow.some((a) => domain === a || domain.endsWith(`.${a}`));
10571
10623
  }
10572
10624
  function buildFeedSet(parts, allow, sources, now = /* @__PURE__ */ new Date()) {
10573
- const neverIps = [...DEFAULT_PROTECTED, ...SHARED_RANGES, ...allow.filter((a) => (0, import_node_net3.isIP)(a.split("/")[0]))];
10574
- const allowDomains = allow.filter((a) => !(0, import_node_net3.isIP)(a.split("/")[0])).map((a) => a.toLowerCase());
10625
+ const neverIps = [...DEFAULT_PROTECTED, ...SHARED_RANGES, ...allow.filter((a) => (0, import_node_net4.isIP)(a.split("/")[0]))];
10626
+ const allowDomains = allow.filter((a) => !(0, import_node_net4.isIP)(a.split("/")[0])).map((a) => a.toLowerCase());
10575
10627
  const ips = {};
10576
10628
  const domains = {};
10577
10629
  let skipped = 0;
@@ -11043,6 +11095,7 @@ function loadConfig(configPath) {
11043
11095
  update: parsed.update,
11044
11096
  threat_feeds: parsed.threat_feeds,
11045
11097
  privileged: parsed.privileged,
11098
+ lightning: parsed.lightning,
11046
11099
  storage: parsed.storage,
11047
11100
  // TOML's `[abuse-reporter]` parses to a hyphenated key; expose it under
11048
11101
  // the JS-friendly name the rest of the daemon reads.
@@ -11478,11 +11531,55 @@ function pagerdutyChannel(config) {
11478
11531
  };
11479
11532
  }
11480
11533
 
11534
+ // src/daemon/alerts/smshub.ts
11535
+ var import_node_os2 = require("os");
11536
+ var SEVERITY_RANK4 = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
11537
+ var DEDUPE_MS = 10 * 6e4;
11538
+ var MAX_PER_HOUR = 6;
11539
+ function smshubText(event, host = (0, import_node_os2.hostname)()) {
11540
+ const evidence = event.details?.evidence?.message;
11541
+ const text = `ThreatCrush ${event.severity.toUpperCase()} on ${host}: ${event.message}${evidence && !event.message.includes(evidence) ? ` | ${evidence}` : ""}`;
11542
+ return text.replace(/\s+/g, " ").slice(0, 600);
11543
+ }
11544
+ function smshubChannel(config, opts = {}) {
11545
+ const sent = /* @__PURE__ */ new Map();
11546
+ const recent = [];
11547
+ const now = opts.now ?? Date.now;
11548
+ const doFetch = opts.fetchImpl ?? fetch;
11549
+ return async (event) => {
11550
+ const key = config.api_key || (config.api_key_env ? process.env[config.api_key_env] : void 0) || process.env.SMSHUB_ALERT_API_KEY;
11551
+ if (!key) return;
11552
+ if ((SEVERITY_RANK4[event.severity] ?? 0) < (SEVERITY_RANK4[config.min_severity ?? "critical"] ?? 4)) return;
11553
+ if (config.fallback_only !== false && opts.cloudHealthy?.()) return;
11554
+ const message = smshubText(event);
11555
+ const at = now();
11556
+ const dedupe2 = `${event.details?.rule_id ?? event.module}|${event.source_ip ?? ""}|${event.details?.fingerprint ?? ""}`;
11557
+ if (at - (sent.get(dedupe2) ?? 0) < DEDUPE_MS) return;
11558
+ while (recent.length && recent[0] < at - 36e5) recent.shift();
11559
+ if (recent.length >= MAX_PER_HOUR) return;
11560
+ sent.set(dedupe2, at);
11561
+ recent.push(at);
11562
+ const base = (config.url || "https://smshub.dev").replace(/\/$/, "");
11563
+ try {
11564
+ const res = await doFetch(`${base}/api/v1/alerts`, {
11565
+ method: "POST",
11566
+ headers: { "X-API-Key": key, "Content-Type": "application/json", "User-Agent": "threatcrush-daemon" },
11567
+ body: JSON.stringify({ message, severity: event.severity === "critical" ? "critical" : "warning", ...config.to ? { to: config.to } : {} }),
11568
+ signal: AbortSignal.timeout(15e3)
11569
+ });
11570
+ opts.log?.(`[alerts] smshub ${res.ok ? "paged" : `failed HTTP ${res.status}`}: ${message.slice(0, 160)}`);
11571
+ } catch (err) {
11572
+ opts.log?.(`[alerts] smshub failed: ${err.message}`);
11573
+ }
11574
+ };
11575
+ }
11576
+
11481
11577
  // src/daemon/alerts/index.ts
11482
11578
  var AlertDispatcher = class {
11483
- constructor(bus2, config) {
11579
+ constructor(bus2, config, hooks = {}) {
11484
11580
  this.bus = bus2;
11485
11581
  this.config = config;
11582
+ this.hooks = hooks;
11486
11583
  this.bindChannels();
11487
11584
  bus2.on("alert", (event) => {
11488
11585
  void this.dispatch(event);
@@ -11490,6 +11587,7 @@ var AlertDispatcher = class {
11490
11587
  }
11491
11588
  bus;
11492
11589
  config;
11590
+ hooks;
11493
11591
  channels = [];
11494
11592
  rateLimits = /* @__PURE__ */ new Map();
11495
11593
  bindChannels() {
@@ -11509,6 +11607,9 @@ var AlertDispatcher = class {
11509
11607
  if (name === "discord" && typeof cfg.webhook_url === "string") {
11510
11608
  this.channels.push(discordChannel(cfg));
11511
11609
  }
11610
+ if (name === "smshub") {
11611
+ this.channels.push(smshubChannel(cfg, this.hooks));
11612
+ }
11512
11613
  if (name === "pagerduty" && typeof cfg.routing_key === "string") {
11513
11614
  this.channels.push(pagerdutyChannel(cfg));
11514
11615
  }
@@ -11556,14 +11657,14 @@ function slackChannel(webhookUrl) {
11556
11657
  // src/daemon/workers/runs-worker.ts
11557
11658
  var import_promises = require("dns/promises");
11558
11659
  var import_node_fs20 = require("fs");
11559
- var import_node_net5 = require("net");
11660
+ var import_node_net6 = require("net");
11560
11661
  var import_node_path14 = require("path");
11561
11662
 
11562
11663
  // src/core/cli-config.ts
11563
11664
  var import_node_fs15 = require("fs");
11564
11665
  var import_node_path8 = require("path");
11565
- var import_node_os2 = require("os");
11566
- var CLI_CONFIG_DIR = (0, import_node_path8.join)((0, import_node_os2.homedir)(), ".threatcrush");
11666
+ var import_node_os3 = require("os");
11667
+ var CLI_CONFIG_DIR = (0, import_node_path8.join)((0, import_node_os3.homedir)(), ".threatcrush");
11567
11668
  var CLI_CONFIG_PATH = (0, import_node_path8.join)(CLI_CONFIG_DIR, "config.json");
11568
11669
  function apiUrl() {
11569
11670
  return process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
@@ -11656,14 +11757,14 @@ async function cloudFetch(path, init = {}) {
11656
11757
 
11657
11758
  // src/core/cloud-events.ts
11658
11759
  var import_node_crypto3 = require("crypto");
11659
- var import_node_net4 = require("net");
11760
+ var import_node_net5 = require("net");
11660
11761
  function currentLink() {
11661
11762
  if (!hasSession()) return null;
11662
11763
  const cfg = readCliConfig();
11663
11764
  if (!cfg.server_id || !cfg.server_org_id) return null;
11664
11765
  return { serverId: cfg.server_id, orgId: cfg.server_org_id };
11665
11766
  }
11666
- var SEVERITY_RANK4 = {
11767
+ var SEVERITY_RANK5 = {
11667
11768
  info: 0,
11668
11769
  low: 1,
11669
11770
  medium: 2,
@@ -11692,11 +11793,21 @@ function trimMetadata(meta) {
11692
11793
  let truncated = entries.length !== Object.keys(meta).length;
11693
11794
  if (jsonBytes(out) > MAX_METADATA_BYTES) {
11694
11795
  truncated = true;
11695
- const bySize = [...entries].sort((a, b) => jsonBytes(a[1]) - jsonBytes(b[1]));
11696
- while (bySize.length > 0 && jsonBytes({ ...Object.fromEntries(bySize), _truncated: true }) > MAX_METADATA_BYTES) {
11697
- bySize.pop();
11698
- }
11699
- out = Object.fromEntries(bySize);
11796
+ const work = new Map(entries);
11797
+ const shrunk = /* @__PURE__ */ new Set();
11798
+ const size = () => jsonBytes({ ...Object.fromEntries(work), _truncated: true });
11799
+ while (work.size > 0 && size() > MAX_METADATA_BYTES) {
11800
+ const [key] = [...work.entries()].filter(([k]) => k !== "evidence" || !shrunk.has(k)).sort((a, b) => jsonBytes(b[1]) - jsonBytes(a[1]))[0] ?? [];
11801
+ if (key === void 0) break;
11802
+ if (!shrunk.has(key)) {
11803
+ const text = typeof work.get(key) === "string" ? work.get(key) : JSON.stringify(work.get(key));
11804
+ work.set(key, text.length > MAX_STRING_CHARS ? `${text.slice(0, MAX_STRING_CHARS)}\u2026` : text);
11805
+ shrunk.add(key);
11806
+ } else if (key !== "evidence") {
11807
+ work.delete(key);
11808
+ } else break;
11809
+ }
11810
+ out = Object.fromEntries(work);
11700
11811
  }
11701
11812
  return truncated ? { ...out, _truncated: true } : out;
11702
11813
  }
@@ -11713,7 +11824,7 @@ function detectionEvent(serverId, event) {
11713
11824
  title: title.slice(0, MAX_TITLE_CHARS) || event.module,
11714
11825
  rule_id: str(rule_id) ?? event.module,
11715
11826
  description: str(description),
11716
- source_ip: event.source_ip && (0, import_node_net4.isIP)(event.source_ip) ? event.source_ip : void 0,
11827
+ source_ip: event.source_ip && (0, import_node_net5.isIP)(event.source_ip) ? event.source_ip : void 0,
11717
11828
  username: str(username) ?? str(user),
11718
11829
  raw_metadata: trimMetadata({ module: event.module, category: event.category, ...rest }),
11719
11830
  detected_at: event.timestamp.toISOString()
@@ -12012,7 +12123,7 @@ var ansi_styles_default = ansiStyles;
12012
12123
 
12013
12124
  // ../../node_modules/.pnpm/chalk@6.0.1/node_modules/chalk/source/vendor/supports-color/index.js
12014
12125
  var import_node_process = __toESM(require("process"), 1);
12015
- var import_node_os3 = __toESM(require("os"), 1);
12126
+ var import_node_os4 = __toESM(require("os"), 1);
12016
12127
  var import_node_tty = __toESM(require("tty"), 1);
12017
12128
  function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
12018
12129
  const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
@@ -12087,7 +12198,7 @@ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
12087
12198
  return min;
12088
12199
  }
12089
12200
  if (import_node_process.default.platform === "win32") {
12090
- const osRelease = import_node_os3.default.release().split(".");
12201
+ const osRelease = import_node_os4.default.release().split(".");
12091
12202
  if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
12092
12203
  return Number(osRelease[2]) >= 14931 ? 3 : 2;
12093
12204
  }
@@ -12352,7 +12463,7 @@ var LEVEL_COLORS = {
12352
12463
  };
12353
12464
 
12354
12465
  // src/core/run-result.ts
12355
- var import_node_os4 = __toESM(require("os"));
12466
+ var import_node_os5 = __toESM(require("os"));
12356
12467
  function emptyCounts() {
12357
12468
  return { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
12358
12469
  }
@@ -12362,7 +12473,7 @@ function summarize(findings) {
12362
12473
  return counts;
12363
12474
  }
12364
12475
  function workerId() {
12365
- return `${import_node_os4.default.hostname()}/${process.pid}`;
12476
+ return `${import_node_os5.default.hostname()}/${process.pid}`;
12366
12477
  }
12367
12478
 
12368
12479
  // ../../packages/scan/src/node-rules.ts
@@ -16068,7 +16179,7 @@ var NOT_PUBLIC = [
16068
16179
  "ff00::/8"
16069
16180
  ];
16070
16181
  function isPublicTarget(ip) {
16071
- return (0, import_node_net5.isIP)(ip) !== 0 && !isProtected(ip, NOT_PUBLIC);
16182
+ return (0, import_node_net6.isIP)(ip) !== 0 && !isProtected(ip, NOT_PUBLIC);
16072
16183
  }
16073
16184
  async function pentestTargetError(rawUrl, resolveHost = async (h) => (await (0, import_promises.lookup)(h, { all: true })).map((a) => a.address)) {
16074
16185
  let url;
@@ -16081,7 +16192,7 @@ async function pentestTargetError(rawUrl, resolveHost = async (h) => (await (0,
16081
16192
  const host = url.hostname.replace(/^\[|\]$/g, "");
16082
16193
  let addresses;
16083
16194
  try {
16084
- addresses = (0, import_node_net5.isIP)(host) ? [host] : await resolveHost(host);
16195
+ addresses = (0, import_node_net6.isIP)(host) ? [host] : await resolveHost(host);
16085
16196
  } catch (err) {
16086
16197
  return `cannot resolve ${host}: ${err.message}`;
16087
16198
  }
@@ -16405,6 +16516,7 @@ var CloudSync = class {
16405
16516
  retryAt = 0;
16406
16517
  link = null;
16407
16518
  lastProblem = "";
16519
+ lastOkAt = 0;
16408
16520
  onEvent = (event) => this.capture(event);
16409
16521
  start() {
16410
16522
  this.link = currentLink();
@@ -16437,6 +16549,10 @@ var CloudSync = class {
16437
16549
  get queued() {
16438
16550
  return this.spool.size;
16439
16551
  }
16552
+ /** Linked, and the dashboard accepted an upload or heartbeat in the last 3 minutes. */
16553
+ get healthy() {
16554
+ return !!this.link && !this.lastProblem && Date.now() - this.lastOkAt < 18e4;
16555
+ }
16440
16556
  /** Queue hardening results for upload (the CLI posts its own directly). */
16441
16557
  enqueueFindings(results) {
16442
16558
  const link = this.refreshLink();
@@ -16461,7 +16577,7 @@ var CloudSync = class {
16461
16577
  let out = null;
16462
16578
  if (event.module === "firewall-rules") {
16463
16579
  out = remediationEvent(link.serverId, event);
16464
- } else if ((event.module === "rule-engine" || !this.opts.ruleModules.has(event.module)) && event.details?.heartbeat !== true && SEVERITY_RANK4[event.severity] >= SEVERITY_RANK4[this.opts.minSeverity]) {
16580
+ } else if ((event.module === "rule-engine" || !this.opts.ruleModules.has(event.module)) && event.details?.heartbeat !== true && SEVERITY_RANK5[event.severity] >= SEVERITY_RANK5[this.opts.minSeverity]) {
16465
16581
  out = detectionEvent(link.serverId, event);
16466
16582
  }
16467
16583
  if (!out) return;
@@ -16509,6 +16625,7 @@ var CloudSync = class {
16509
16625
  this.backoffMs = 0;
16510
16626
  this.retryAt = 0;
16511
16627
  this.lastProblem = "";
16628
+ this.lastOkAt = Date.now();
16512
16629
  return "sent";
16513
16630
  }
16514
16631
  if (res.status === 401) {
@@ -16553,6 +16670,7 @@ var CloudSync = class {
16553
16670
  };
16554
16671
  try {
16555
16672
  const res = await cloudFetch("/api/ingest", { method: "POST", body: JSON.stringify({ events: [event] }) });
16673
+ if (res.ok) this.lastOkAt = Date.now();
16556
16674
  if (res.ok && this.retryAt > 0) {
16557
16675
  this.retryAt = 0;
16558
16676
  void this.flush();
@@ -16576,7 +16694,7 @@ var CloudSync = class {
16576
16694
  var import_node_crypto5 = require("crypto");
16577
16695
 
16578
16696
  // src/daemon/workers/abuse-evidence.ts
16579
- var import_node_net6 = require("net");
16697
+ var import_node_net7 = require("net");
16580
16698
  var NEVER_REPORT_RANGES = [
16581
16699
  ...DEFAULT_PROTECTED,
16582
16700
  "100.64.0.0/10",
@@ -16652,7 +16770,7 @@ function summarizeEvidence(events) {
16652
16770
  };
16653
16771
  }
16654
16772
  function isReportable(ip, evidence, config, now = Date.now()) {
16655
- if ((0, import_node_net6.isIP)(ip) === 0) return { reportable: false, reason: "not an IP address" };
16773
+ if ((0, import_node_net7.isIP)(ip) === 0) return { reportable: false, reason: "not an IP address" };
16656
16774
  if (isProtected(ip, config.neverReport)) {
16657
16775
  return { reportable: false, reason: "address is in a never-report range (private/CGNAT/reserved/allowlisted)" };
16658
16776
  }
@@ -16983,13 +17101,13 @@ var AbuseReporter = class {
16983
17101
  };
16984
17102
 
16985
17103
  // src/daemon/workers/remediation-consumer.ts
16986
- var import_node_net8 = require("net");
17104
+ var import_node_net9 = require("net");
16987
17105
 
16988
17106
  // src/daemon/workers/allowlist-sync.ts
16989
- var import_node_net7 = require("net");
17107
+ var import_node_net8 = require("net");
16990
17108
  function isAddressOrCidr(value) {
16991
17109
  const [network, prefix, extra] = value.split("/");
16992
- const family = (0, import_node_net7.isIP)(network);
17110
+ const family = (0, import_node_net8.isIP)(network);
16993
17111
  if (family === 0 || extra !== void 0) return false;
16994
17112
  if (prefix === void 0) return true;
16995
17113
  if (!/^\d{1,3}$/.test(prefix)) return false;
@@ -17000,7 +17118,7 @@ function isCloudAllowEntry(value) {
17000
17118
  if (!isAddressOrCidr(value)) return false;
17001
17119
  const [network, prefix] = value.split("/");
17002
17120
  if (prefix === void 0) return true;
17003
- return Number(prefix) >= CLOUD_MIN_PREFIX[(0, import_node_net7.isIP)(network)];
17121
+ return Number(prefix) >= CLOUD_MIN_PREFIX[(0, import_node_net8.isIP)(network)];
17004
17122
  }
17005
17123
  var AllowlistSync = class {
17006
17124
  constructor(manager, opts) {
@@ -17023,6 +17141,17 @@ var AllowlistSync = class {
17023
17141
  async sync() {
17024
17142
  const link = currentLink();
17025
17143
  if (!link) return;
17144
+ if (this.opts.onOrgSettings) {
17145
+ try {
17146
+ const res = await cloudFetch(`/api/orgs/${link.orgId}`);
17147
+ if (res.ok) {
17148
+ const data = await res.json();
17149
+ const v = data.organization?.block_tor_ssh;
17150
+ if (typeof v === "boolean") this.opts.onOrgSettings({ block_tor_ssh: v });
17151
+ }
17152
+ } catch {
17153
+ }
17154
+ }
17026
17155
  let entries;
17027
17156
  try {
17028
17157
  const res = await cloudFetch(`/api/orgs/${link.orgId}/allowlists`);
@@ -17038,7 +17167,7 @@ var AllowlistSync = class {
17038
17167
  if (entry.type !== "ip" && entry.type !== "cidr") continue;
17039
17168
  const value = String(entry.value ?? "").trim();
17040
17169
  if (isCloudAllowEntry(value)) wanted.add(value);
17041
- else if (isAddressOrCidr(value)) this.opts.log(`[cloud] org allowlist: ignoring ${value} (wider than /${CLOUD_MIN_PREFIX[(0, import_node_net7.isIP)(value.split("/")[0])]})`);
17170
+ else if (isAddressOrCidr(value)) this.opts.log(`[cloud] org allowlist: ignoring ${value} (wider than /${CLOUD_MIN_PREFIX[(0, import_node_net8.isIP)(value.split("/")[0])]})`);
17042
17171
  }
17043
17172
  const added2 = [];
17044
17173
  const protectedNow = new Set(this.manager.getProtected());
@@ -17146,7 +17275,7 @@ var RemediationConsumer = class {
17146
17275
  try {
17147
17276
  switch (action.action_type) {
17148
17277
  case "block": {
17149
- if ((0, import_node_net8.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
17278
+ if ((0, import_node_net9.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
17150
17279
  let ttlSeconds = this.manager.status().max_ban_seconds;
17151
17280
  if (action.expires_at) {
17152
17281
  const until = Date.parse(action.expires_at);
@@ -17165,7 +17294,7 @@ var RemediationConsumer = class {
17165
17294
  return { status: "executed", dry_run: result.entry?.dry_run === true, executed_at };
17166
17295
  }
17167
17296
  case "unblock": {
17168
- if ((0, import_node_net8.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
17297
+ if ((0, import_node_net9.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
17169
17298
  const wasBanned = this.manager.getBlocklist().some((b) => b.ip === target);
17170
17299
  const result = await this.manager.unban(target, {
17171
17300
  forget: true,
@@ -17469,7 +17598,7 @@ var AutoUpdate = class {
17469
17598
  var import_node_child_process6 = require("child_process");
17470
17599
  var import_node_fs24 = require("fs");
17471
17600
  var import_node_path18 = require("path");
17472
- var import_node_net9 = require("net");
17601
+ var import_node_net10 = require("net");
17473
17602
  var EGRESS_TABLE = "threatcrush_egress";
17474
17603
  var DEFAULT_REFRESH_MS = 36e5;
17475
17604
  var POLL_MS = 15e3;
@@ -17487,8 +17616,8 @@ function threatFeedSettings(section) {
17487
17616
  };
17488
17617
  }
17489
17618
  function egressRuleset(ips) {
17490
- const v4 = ips.filter((ip) => (0, import_node_net9.isIP)(ip) === 4);
17491
- const v6 = ips.filter((ip) => (0, import_node_net9.isIP)(ip) === 6);
17619
+ const v4 = ips.filter((ip) => (0, import_node_net10.isIP)(ip) === 4);
17620
+ const v6 = ips.filter((ip) => (0, import_node_net10.isIP)(ip) === 6);
17492
17621
  const set = (name, type, items) => ` set ${name} { type ${type};${items.length ? ` elements = { ${items.join(", ")} }` : ""} }`;
17493
17622
  const chain = (name, hook) => [
17494
17623
  ` chain ${name} {`,
@@ -17513,7 +17642,7 @@ function splitAddr(addr) {
17513
17642
  const m = /^\[?(.+?)\]?:(\d+|\*)$/.exec(addr);
17514
17643
  if (!m) return null;
17515
17644
  const ip = m[1].replace(/%.*$/, "").replace(/^::ffff:/i, "");
17516
- return (0, import_node_net9.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
17645
+ return (0, import_node_net10.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
17517
17646
  }
17518
17647
  function parseSs(text) {
17519
17648
  const out = [];
@@ -17901,7 +18030,42 @@ function parseSudoMessage(message) {
17901
18030
 
17902
18031
  // src/daemon/workers/privilege-watch.ts
17903
18032
  function privilegeSettings(section) {
17904
- return { enabled: section?.enabled !== false, geo: section?.geo !== false, pollMs: 6e4 };
18033
+ return {
18034
+ enabled: section?.enabled !== false,
18035
+ geo: section?.geo !== false,
18036
+ pollMs: 6e4,
18037
+ expectedKeys: Array.isArray(section?.expected_keys) ? section.expected_keys.map(String).filter(Boolean) : [],
18038
+ watchFiles: true
18039
+ };
18040
+ }
18041
+ function keyIsExpected(fingerprint, comment, expected) {
18042
+ return expected.some((pattern) => {
18043
+ if (pattern.startsWith("SHA256:")) return pattern === fingerprint;
18044
+ const re = new RegExp(`^${pattern.split("*").map((p) => p.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`, "i");
18045
+ return re.test(comment);
18046
+ });
18047
+ }
18048
+ var SELFTEST_KEY_COMMENT = "threatcrush-selftest";
18049
+ function classifyKeyAddition(change, expected) {
18050
+ if (change.details.rule_id !== "priv-authorized-key-added") return change;
18051
+ const fp = String(change.details.fingerprint ?? "");
18052
+ const comment = String(change.details.comment ?? "");
18053
+ const account = String(change.details.account ?? "?");
18054
+ if (comment.includes(SELFTEST_KEY_COMMENT)) {
18055
+ return {
18056
+ severity: "critical",
18057
+ message: `[TEST] ThreatCrush self-test: new SSH key for ${account} detected (${fp}, ${comment}). This is a test, nothing is wrong.`,
18058
+ details: { ...change.details, rule_id: "priv-authorized-key-selftest", selftest: true }
18059
+ };
18060
+ }
18061
+ if (keyIsExpected(fp, comment, expected)) {
18062
+ return { ...change, severity: "high", details: { ...change.details, expected: true } };
18063
+ }
18064
+ return {
18065
+ severity: "critical",
18066
+ message: `New SSH key added for ${account}: ${change.details.key_type ?? ""} ${fp}${comment ? ` "${comment}"` : " (no comment)"}, not an expected key; whoever holds it can log in`,
18067
+ details: { ...change.details, expected: false }
18068
+ };
17905
18069
  }
17906
18070
  var COUNTRY_NAMES = new Intl.DisplayNames(["en"], { type: "region" });
17907
18071
  function countryName(code) {
@@ -17999,6 +18163,8 @@ var PrivilegeWatch = class {
17999
18163
  run;
18000
18164
  now;
18001
18165
  warnedUnreadable = false;
18166
+ watchers = /* @__PURE__ */ new Map();
18167
+ debounce = null;
18002
18168
  onEvent = (event) => {
18003
18169
  void this.checkLogin(event);
18004
18170
  };
@@ -18013,9 +18179,11 @@ var PrivilegeWatch = class {
18013
18179
  this.opts.bus.on("event", this.onEvent);
18014
18180
  void this.backfillLogins();
18015
18181
  }
18182
+ if (this.opts.settings.watchFiles) this.watchKeyDirs();
18016
18183
  const timer = setInterval(() => {
18017
18184
  this.checkSnapshot();
18018
18185
  this.readSudoLedger();
18186
+ if (this.opts.settings.watchFiles) this.watchKeyDirs();
18019
18187
  }, this.opts.settings.pollMs);
18020
18188
  timer.unref?.();
18021
18189
  this.timers.push(timer);
@@ -18023,8 +18191,55 @@ var PrivilegeWatch = class {
18023
18191
  stop() {
18024
18192
  for (const t of this.timers) clearInterval(t);
18025
18193
  this.timers = [];
18194
+ for (const w of this.watchers.values()) {
18195
+ try {
18196
+ w.close();
18197
+ } catch {
18198
+ }
18199
+ }
18200
+ this.watchers.clear();
18201
+ if (this.debounce) clearTimeout(this.debounce);
18026
18202
  this.opts.bus.off("event", this.onEvent);
18027
18203
  }
18204
+ /**
18205
+ * inotify on every login account's ~/.ssh (and /root/.ssh): a write there
18206
+ * re-checks the snapshot within a second, not at the next minute's poll.
18207
+ * Re-run each poll so a directory created later is picked up.
18208
+ */
18209
+ watchKeyDirs() {
18210
+ const dirs = /* @__PURE__ */ new Set();
18211
+ for (const line of (this.io.readFile("/etc/passwd") ?? "").split("\n")) {
18212
+ const f = line.split(":");
18213
+ if (f.length < 7) continue;
18214
+ const uid = Number(f[2]);
18215
+ const home = f[5];
18216
+ if (!home || home === "/" || uid !== 0 && /(nologin|\/false)$/.test(f[6].trim())) continue;
18217
+ dirs.add(`${home.replace(/\/$/, "")}/.ssh`);
18218
+ }
18219
+ for (const dir of dirs) {
18220
+ if (this.watchers.has(dir) || !this.io.exists(dir)) continue;
18221
+ try {
18222
+ const w = (0, import_node_fs25.watch)(dir, { persistent: false }, (_type2, name) => {
18223
+ if (name && !String(name).startsWith("authorized_keys")) return;
18224
+ if (this.debounce) clearTimeout(this.debounce);
18225
+ this.debounce = setTimeout(() => {
18226
+ this.debounce = null;
18227
+ this.checkSnapshot();
18228
+ }, 750);
18229
+ this.debounce.unref?.();
18230
+ });
18231
+ w.on("error", () => {
18232
+ try {
18233
+ w.close();
18234
+ } catch {
18235
+ }
18236
+ this.watchers.delete(dir);
18237
+ });
18238
+ this.watchers.set(dir, w);
18239
+ } catch {
18240
+ }
18241
+ }
18242
+ }
18028
18243
  emit(severity, message, details) {
18029
18244
  const event = { timestamp: this.now(), module: "privileged-access", category: "auth", severity, message, details };
18030
18245
  try {
@@ -18044,7 +18259,16 @@ var PrivilegeWatch = class {
18044
18259
  const keys = Object.values(next.keys).reduce((n, k) => n + Object.keys(k).length, 0);
18045
18260
  this.opts.log(`[privileged] baseline recorded: uid0 [${next.uid0.join(", ")}], ${Object.values(next.admin_groups).flat().length} admin-group member(s), ${Object.keys(next.sudoers).length} sudoers file(s), ${keys} authorized key(s)`);
18046
18261
  } else {
18047
- for (const change of diffSnapshots(prev, next)) this.emit(change.severity, change.message, change.details);
18262
+ for (const raw of diffSnapshots(prev, next)) {
18263
+ const change = classifyKeyAddition(raw, this.opts.settings.expectedKeys ?? []);
18264
+ if (change.details.rule_id === "priv-authorized-key-added" || change.details.rule_id === "priv-authorized-key-selftest") {
18265
+ this.opts.log(`[privileged] ${change.severity.toUpperCase()} ${change.message}`);
18266
+ }
18267
+ this.emit(change.severity, change.message, {
18268
+ ...change.details,
18269
+ evidence: { at: this.now().toISOString(), module: "privileged-access", message: change.message.slice(0, 500) }
18270
+ });
18271
+ }
18048
18272
  }
18049
18273
  try {
18050
18274
  writeJson(this.opts.snapshotPath, next);
@@ -18158,6 +18382,636 @@ var PrivilegeWatch = class {
18158
18382
  }
18159
18383
  };
18160
18384
 
18385
+ // src/daemon/workers/ssh-intrusion.ts
18386
+ var import_node_fs26 = require("fs");
18387
+ var import_node_path20 = require("path");
18388
+ var import_node_child_process8 = require("child_process");
18389
+
18390
+ // src/core/asn.ts
18391
+ var import_node_dns = require("dns");
18392
+ var import_node_net11 = require("net");
18393
+ var CI_ASNS = /* @__PURE__ */ new Set([8075, 36459, 8068, 8069, 12076]);
18394
+ var HOSTING_ASNS = /* @__PURE__ */ new Set([
18395
+ 15169,
18396
+ 396982,
18397
+ 19527,
18398
+ // Google, Google Cloud
18399
+ 16509,
18400
+ 14618,
18401
+ // Amazon / AWS
18402
+ 16276,
18403
+ // OVH
18404
+ 24940,
18405
+ 213230,
18406
+ // Hetzner
18407
+ 14061,
18408
+ // DigitalOcean
18409
+ 63949,
18410
+ // Linode / Akamai
18411
+ 20473,
18412
+ // Vultr (Choopa)
18413
+ 12876,
18414
+ // Scaleway
18415
+ 51167,
18416
+ // Contabo
18417
+ 31898,
18418
+ // Oracle Cloud
18419
+ 45102,
18420
+ // Alibaba
18421
+ 132203,
18422
+ 45090,
18423
+ // Tencent
18424
+ 36352,
18425
+ // ColoCrossing
18426
+ 53667,
18427
+ // FranTech / BuyVM
18428
+ 197540,
18429
+ // netcup
18430
+ 9009,
18431
+ // M247
18432
+ 60068,
18433
+ // Datacamp / CDN77
18434
+ 212238,
18435
+ // Datacamp
18436
+ 202425,
18437
+ // IP Volume
18438
+ 210644,
18439
+ // Aeza
18440
+ 49981,
18441
+ // WorldStream
18442
+ 62240,
18443
+ // Clouvider
18444
+ 136907,
18445
+ // Huawei Cloud
18446
+ 8100,
18447
+ // QuadraNet
18448
+ 46606,
18449
+ // Unified Layer
18450
+ 29802,
18451
+ // HVC
18452
+ 40021,
18453
+ // Contabo US / Nubes
18454
+ 398324,
18455
+ 399629
18456
+ // Censys and friends
18457
+ ]);
18458
+ var VPN_ASNS = /* @__PURE__ */ new Set([
18459
+ 9009,
18460
+ // M247 (most commercial VPN exits)
18461
+ 212238,
18462
+ 60068,
18463
+ // Datacamp (NordVPN, Proton, ...)
18464
+ 209854,
18465
+ // Surfshark
18466
+ 39351,
18467
+ // 31173 Services (Mullvad)
18468
+ 136787,
18469
+ // TEFINCOM (NordVPN)
18470
+ 147049
18471
+ // PacketHub (NordVPN)
18472
+ ]);
18473
+ var HOSTING_NAME = /hosting|server|datacenter|data center|data-center|cloud|colo|vps|dedicated|ovh|hetzner|digitalocean|linode|vultr|choopa|amazon|aws|google|microsoft|azure|oracle|alibaba|tencent|contabo|scaleway|leaseweb|ionos|kamatera|frantech|buyvm|racknerd|quadranet|psychz|m247|datacamp|cdn77|aeza|serverius|worldstream|ipvolume|clouvider|netcup|gcore|g-core|selectel|timeweb|hostinger|godaddy|incapsula|fastly/i;
18474
+ var VPN_NAME = /\bvpn\b|proton|mullvad|nordvpn|surfshark|expressvpn|private internet access|tefincom|packethub|31173 services|anonymi[sz]|privacy|proxy/i;
18475
+ function classifyAsn(info) {
18476
+ if (!info) return "unknown";
18477
+ if (CI_ASNS.has(info.asn)) return "ci";
18478
+ if (VPN_ASNS.has(info.asn) || VPN_NAME.test(info.name)) return "vpn";
18479
+ if (HOSTING_ASNS.has(info.asn) || HOSTING_NAME.test(info.name)) return "hosting";
18480
+ return "unknown";
18481
+ }
18482
+ function cymruOriginName(ip) {
18483
+ const bytes = ipToBytes(ip);
18484
+ if (!bytes) return null;
18485
+ if (bytes.length === 4) return `${[...bytes].reverse().join(".")}.origin.asn.cymru.com`;
18486
+ const nibbles = [];
18487
+ for (const b of bytes) nibbles.push((b >> 4).toString(16), (b & 15).toString(16));
18488
+ return `${nibbles.reverse().join(".")}.origin6.asn.cymru.com`;
18489
+ }
18490
+ function parseCymruOrigin(txt) {
18491
+ const fields = txt.split("|").map((f) => f.trim());
18492
+ const asn = Number(fields[0]?.split(/\s+/)[0]);
18493
+ if (!Number.isInteger(asn) || asn <= 0) return null;
18494
+ return { asn, prefix: fields[1] || void 0, country: /^[A-Z]{2}$/.test(fields[2] ?? "") ? fields[2] : void 0 };
18495
+ }
18496
+ function parseCymruName(txt) {
18497
+ const fields = txt.split("|").map((f) => f.trim());
18498
+ return (fields[4] ?? "").slice(0, 120);
18499
+ }
18500
+ var AsnLookup = class {
18501
+ constructor(resolveTxt = (name) => import_node_dns.promises.resolveTxt(name), ttlMs = 24 * 36e5, now = Date.now) {
18502
+ this.resolveTxt = resolveTxt;
18503
+ this.ttlMs = ttlMs;
18504
+ this.now = now;
18505
+ }
18506
+ resolveTxt;
18507
+ ttlMs;
18508
+ now;
18509
+ cache = /* @__PURE__ */ new Map();
18510
+ async lookup(ip) {
18511
+ if ((0, import_node_net11.isIP)(ip) === 0) return null;
18512
+ const hit = this.cache.get(ip);
18513
+ if (hit && this.now() - hit.at < this.ttlMs) return hit.info;
18514
+ let info = null;
18515
+ try {
18516
+ const origin = cymruOriginName(ip);
18517
+ if (origin) {
18518
+ const rec = await withTimeout(this.resolveTxt(origin), 5e3);
18519
+ const parsed = parseCymruOrigin(rec.map((r) => r.join("")).find(Boolean) ?? "");
18520
+ if (parsed) {
18521
+ let name = "";
18522
+ try {
18523
+ const names = await withTimeout(this.resolveTxt(`AS${parsed.asn}.asn.cymru.com`), 5e3);
18524
+ name = parseCymruName(names.map((r) => r.join("")).find(Boolean) ?? "");
18525
+ } catch {
18526
+ }
18527
+ info = { asn: parsed.asn, name, country: parsed.country, prefix: parsed.prefix };
18528
+ }
18529
+ }
18530
+ } catch {
18531
+ info = null;
18532
+ }
18533
+ if (this.cache.size > 5e3) this.cache.clear();
18534
+ this.cache.set(ip, { at: this.now(), info });
18535
+ return info;
18536
+ }
18537
+ };
18538
+ function withTimeout(p, ms) {
18539
+ return new Promise((resolve4, reject) => {
18540
+ const t = setTimeout(() => reject(new Error("timeout")), ms);
18541
+ p.then((v) => {
18542
+ clearTimeout(t);
18543
+ resolve4(v);
18544
+ }, (e) => {
18545
+ clearTimeout(t);
18546
+ reject(e);
18547
+ });
18548
+ });
18549
+ }
18550
+ function describeNetwork(info, kind) {
18551
+ if (kind === "tor") return info ? `Tor exit, AS${info.asn} ${info.name}`.trim() : "Tor exit";
18552
+ if (!info) return `unknown network (${kind})`;
18553
+ return `AS${info.asn}${info.name ? ` ${info.name}` : ""} (${kind === "unknown" ? "ISP or unclassified" : kind})`;
18554
+ }
18555
+
18556
+ // src/daemon/workers/ssh-intrusion.ts
18557
+ var TOR_REALERT_MS = 10 * 6e4;
18558
+ var HOSTING_REALERT_MS = 24 * 36e5;
18559
+ var TOR_REMEDIATION = {
18560
+ action: "block",
18561
+ description: "Ban the Tor exit at once, for max_ban, even in dry_run and even after a successful login",
18562
+ enforce_in_dry_run: true,
18563
+ ban_on_login: true,
18564
+ override_operator_protection: true,
18565
+ max_ban: true
18566
+ };
18567
+ function parseKeyLoginsByFingerprint(text) {
18568
+ const out = /* @__PURE__ */ new Map();
18569
+ for (const line of text.split("\n")) {
18570
+ const m = /^(\d+(?:\.\d+)?)\s.*Accepted publickey for \S+ from (\S+) port \d+ \S+?:\s+\S+\s+(SHA256:[A-Za-z0-9+/=]+)/.exec(line);
18571
+ if (!m) continue;
18572
+ const at = Math.round(Number(m[1]) * 1e3);
18573
+ const ips = out.get(m[3]) ?? /* @__PURE__ */ new Map();
18574
+ if (at > (ips.get(m[2]) ?? 0)) ips.set(m[2], at);
18575
+ out.set(m[3], ips);
18576
+ }
18577
+ return out;
18578
+ }
18579
+ function readJson2(path) {
18580
+ try {
18581
+ return JSON.parse((0, import_node_fs26.readFileSync)(path, "utf-8"));
18582
+ } catch {
18583
+ return null;
18584
+ }
18585
+ }
18586
+ function writeJson2(path, value) {
18587
+ (0, import_node_fs26.mkdirSync)((0, import_node_path20.dirname)(path), { recursive: true });
18588
+ (0, import_node_fs26.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
18589
+ (0, import_node_fs26.renameSync)(`${path}.tmp`, path);
18590
+ }
18591
+ var fsIO2 = {
18592
+ readFile: (p) => {
18593
+ try {
18594
+ return (0, import_node_fs26.readFileSync)(p, "utf-8");
18595
+ } catch {
18596
+ return null;
18597
+ }
18598
+ },
18599
+ readDir: (p) => {
18600
+ try {
18601
+ return (0, import_node_fs26.readdirSync)(p);
18602
+ } catch {
18603
+ return null;
18604
+ }
18605
+ },
18606
+ exists: (p) => (0, import_node_fs26.existsSync)(p)
18607
+ };
18608
+ function defaultRun4(cmd, args) {
18609
+ const res = (0, import_node_child_process8.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
18610
+ return res.status === 0 ? res.stdout : null;
18611
+ }
18612
+ var SshIntrusionWatch = class {
18613
+ constructor(opts) {
18614
+ this.opts = opts;
18615
+ this.now = opts.now ?? Date.now;
18616
+ this.asn = opts.asn ?? new AsnLookup();
18617
+ this.io = opts.io ?? fsIO2;
18618
+ this.run = opts.run ?? defaultRun4;
18619
+ }
18620
+ opts;
18621
+ now;
18622
+ asn;
18623
+ io;
18624
+ run;
18625
+ torAlerted = /* @__PURE__ */ new Map();
18626
+ hostingAlerted = /* @__PURE__ */ new Map();
18627
+ history = {};
18628
+ keyComments = { at: 0, byFp: /* @__PURE__ */ new Map() };
18629
+ baselineReady = false;
18630
+ onLine = (line) => {
18631
+ this.checkTorLine(line);
18632
+ };
18633
+ onEvent = (event) => {
18634
+ void this.checkKeyLogin(event);
18635
+ };
18636
+ start() {
18637
+ this.opts.tor.start();
18638
+ this.opts.manager.setTorExitCheck((ip) => this.opts.tor.has(ip));
18639
+ this.opts.bus.on("sshd", this.onLine);
18640
+ if (this.opts.keyLoginWatch !== false) {
18641
+ this.opts.bus.on("event", this.onEvent);
18642
+ this.loadHistory();
18643
+ }
18644
+ this.opts.log(`[ssh-intrusion] Tor SSH ban ${this.opts.manager.blockTorSsh ? "ON (enforced even in dry_run)" : "OFF (alert only)"}; key-login watch ${this.opts.keyLoginWatch === false ? "off" : "on"}`);
18645
+ }
18646
+ stop() {
18647
+ this.opts.tor.stop();
18648
+ this.opts.bus.off("sshd", this.onLine);
18649
+ this.opts.bus.off("event", this.onEvent);
18650
+ }
18651
+ emit(event) {
18652
+ try {
18653
+ insertEvent(event);
18654
+ } catch {
18655
+ }
18656
+ this.opts.bus.publish(event);
18657
+ }
18658
+ /** One sshd line: a Tor exit anywhere in it is an intrusion attempt. */
18659
+ checkTorLine(line) {
18660
+ const ip = line.ip;
18661
+ if (!this.opts.tor.has(ip)) return false;
18662
+ if (isProtected(ip, DEFAULT_PROTECTED) || this.opts.manager.isFleetAddress(ip)) return false;
18663
+ const at = this.now();
18664
+ const last = this.torAlerted.get(ip) ?? 0;
18665
+ const accepted = /Accepted \S+ for /.test(line.message);
18666
+ if (!accepted && at - last < TOR_REALERT_MS) return false;
18667
+ this.torAlerted.set(ip, at);
18668
+ if (this.torAlerted.size > 1e4) this.torAlerted.clear();
18669
+ const ban = this.opts.manager.blockTorSsh;
18670
+ const user = /for (?:invalid user )?(\S+) from/.exec(line.message)?.[1];
18671
+ const what = accepted ? `LOGGED IN${user ? ` as ${user}` : ""}` : "connection attempt";
18672
+ this.emit({
18673
+ timestamp: line.timestamp,
18674
+ module: "ssh-intrusion",
18675
+ category: "auth",
18676
+ severity: accepted || ban ? "critical" : "high",
18677
+ message: `SSH from Tor exit ${ip} (${what})${ban ? ": banned" : ""}`,
18678
+ source_ip: ip,
18679
+ details: {
18680
+ rule_id: "ssh-from-tor",
18681
+ description: "Nobody we operate for uses SSH through Tor. A Tor login means a stolen key or password.",
18682
+ tor_exit: true,
18683
+ accepted,
18684
+ ...user ? { ssh_user: user } : {},
18685
+ ...ban ? { remediation: TOR_REMEDIATION } : {},
18686
+ evidence: { at: line.timestamp.toISOString(), module: "ssh-guard", message: line.raw.slice(0, 500) }
18687
+ }
18688
+ });
18689
+ return true;
18690
+ }
18691
+ loadHistory() {
18692
+ const saved = readJson2(this.opts.historyPath);
18693
+ if (saved) {
18694
+ this.history = saved;
18695
+ this.baselineReady = true;
18696
+ return;
18697
+ }
18698
+ const out = this.run("journalctl", ["_COMM=sshd", "_COMM=sshd-session", "--since=-30d", "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"]);
18699
+ const iso = (ms) => new Date(ms).toISOString();
18700
+ let pairs = 0;
18701
+ for (const [fp, ips] of parseKeyLoginsByFingerprint(out ?? "")) {
18702
+ for (const [ip, at] of ips) {
18703
+ if (this.opts.tor.has(ip)) continue;
18704
+ (this.history[fp] ??= {})[ip] = { first: iso(at), last: iso(at), count: 1 };
18705
+ pairs++;
18706
+ }
18707
+ }
18708
+ this.save();
18709
+ this.baselineReady = true;
18710
+ this.opts.log(`[ssh-intrusion] key-login baseline from the last 30 days: ${Object.keys(this.history).length} key(s), ${pairs} key/address pair(s)`);
18711
+ }
18712
+ save() {
18713
+ try {
18714
+ writeJson2(this.opts.historyPath, this.history);
18715
+ } catch (err) {
18716
+ this.opts.log(`[ssh-intrusion] could not save key-login history: ${err.message}`);
18717
+ }
18718
+ }
18719
+ /** Which account a key is authorized for, and its comment (cached 5 minutes). */
18720
+ keyInfo(fp) {
18721
+ if (this.now() - this.keyComments.at > 3e5) {
18722
+ const snap = takeSnapshot(this.io);
18723
+ const byFp = /* @__PURE__ */ new Map();
18724
+ for (const [user, keys] of Object.entries(snap.keys)) {
18725
+ for (const [f, k] of Object.entries(keys)) if (!byFp.has(f)) byFp.set(f, { user, comment: k.comment });
18726
+ }
18727
+ this.keyComments = { at: this.now(), byFp };
18728
+ }
18729
+ return this.keyComments.byFp.get(fp) ?? null;
18730
+ }
18731
+ async checkKeyLogin(event) {
18732
+ if (event.module !== "ssh-guard" || !this.baselineReady) return null;
18733
+ const fp = event.details?.fingerprint;
18734
+ const ip = event.source_ip;
18735
+ if (typeof fp !== "string" || !ip || isProtected(ip, DEFAULT_PROTECTED)) return null;
18736
+ const seen = this.history[fp] ?? {};
18737
+ const isNew = !seen[ip];
18738
+ const nowIso = new Date(this.now()).toISOString();
18739
+ seen[ip] = { first: seen[ip]?.first ?? nowIso, last: nowIso, count: (seen[ip]?.count ?? 0) + 1 };
18740
+ this.history[fp] = seen;
18741
+ this.save();
18742
+ const tor = this.opts.tor.has(ip);
18743
+ const fleet = this.opts.manager.isFleetAddress(ip);
18744
+ if (fleet) return null;
18745
+ const key = this.keyInfo(fp);
18746
+ const automation = key ? isAutomationKeyComment(key.comment) : false;
18747
+ let info = null;
18748
+ try {
18749
+ info = await this.asn.lookup(ip);
18750
+ } catch {
18751
+ info = null;
18752
+ }
18753
+ const kind = tor ? "tor" : classifyAsn(info);
18754
+ const network = describeNetwork(info, kind);
18755
+ const user = typeof event.details?.ssh_user === "string" ? event.details.ssh_user : /accepted for (\S+)/i.exec(event.message)?.[1] ?? "unknown";
18756
+ const keyLabel = `${fp}${key?.comment ? ` (${key.comment})` : ""}`;
18757
+ const known = Object.keys(seen).filter((a) => a !== ip).length;
18758
+ const anonymous = kind === "hosting" || kind === "vpn" || kind === "tor";
18759
+ const hostingHit = !automation && anonymous;
18760
+ const pairKey = `${fp}|${ip}`;
18761
+ const hostingDue = hostingHit && this.now() - (this.hostingAlerted.get(pairKey) ?? 0) >= HOSTING_REALERT_MS;
18762
+ if (!isNew && !hostingDue) return null;
18763
+ if (tor && this.opts.manager.blockTorSsh) return null;
18764
+ let ruleId;
18765
+ let severity;
18766
+ let message;
18767
+ if (hostingHit) {
18768
+ this.hostingAlerted.set(pairKey, this.now());
18769
+ ruleId = "ssh-human-key-hosting-login";
18770
+ severity = "high";
18771
+ message = `SSH login as ${user} with a person's key from a ${kind === "vpn" ? "VPN/anonymizer" : kind === "tor" ? "Tor" : "hosting/cloud"} network: ${ip}, ${network}${isNew ? ", first time for this key" : ""}`;
18772
+ } else if (automation && kind === "ci") {
18773
+ ruleId = "ssh-key-new-ip";
18774
+ severity = "info";
18775
+ message = `SSH deploy key logged in as ${user} from a new CI address ${ip} (${network}), expected`;
18776
+ } else {
18777
+ ruleId = "ssh-key-new-ip";
18778
+ severity = "high";
18779
+ message = `SSH key logged in as ${user} from an address it never used: ${ip}, ${network}${known ? `; ${known} address(es) known for this key` : ""}`;
18780
+ }
18781
+ const out = {
18782
+ timestamp: event.timestamp,
18783
+ module: "ssh-intrusion",
18784
+ category: "auth",
18785
+ severity,
18786
+ message,
18787
+ details: {
18788
+ rule_id: ruleId,
18789
+ account: user,
18790
+ login_ip: ip,
18791
+ fingerprint: fp,
18792
+ key_comment: key?.comment ?? null,
18793
+ key_kind: automation ? "automation" : "person",
18794
+ network_kind: kind,
18795
+ ...info ? { asn: info.asn, as_name: info.name, as_country: info.country } : {},
18796
+ first_time_for_key: isNew,
18797
+ known_addresses_for_key: known,
18798
+ evidence: { at: event.timestamp.toISOString(), module: "ssh-guard", message: `Accepted publickey for ${user} from ${ip} ${fp}` }
18799
+ }
18800
+ };
18801
+ this.emit(out);
18802
+ return out;
18803
+ }
18804
+ };
18805
+
18806
+ // src/daemon/workers/lightning-watch.ts
18807
+ var import_node_fs27 = require("fs");
18808
+ var DEFAULT_CLN_LOGS = [
18809
+ "/home/lightning/.lightning/cln.log",
18810
+ "/root/.lightning/cln.log",
18811
+ "/var/lib/clightning/cln.log",
18812
+ "/home/lightning/.lightning/bitcoin/cln.log"
18813
+ ];
18814
+ var CLOSE_RE = /^(\S+)\s+\S+\s+(\S+?)-chan#(\d+): State changed from CHANNELD_NORMAL to (CHANNELD_SHUTTING_DOWN|AWAITING_UNILATERAL|CLOSINGD_SIGEXCHANGE|CLOSINGD_COMPLETE)/;
18815
+ function parseChannelClose(line) {
18816
+ const m = CLOSE_RE.exec(line);
18817
+ if (!m) return null;
18818
+ const at = new Date(m[1]);
18819
+ return { at: Number.isNaN(at.getTime()) ? /* @__PURE__ */ new Date() : at, peer: m[2], channel: `${m[2].slice(0, 12)}\u2026#${m[3]}`, to: m[4], line: line.slice(0, 500) };
18820
+ }
18821
+ var BURST_WINDOW_MS = 10 * 6e4;
18822
+ var BURST_REALERT_MS = 30 * 6e4;
18823
+ var ChannelCloseDetector = class {
18824
+ recent = [];
18825
+ lastBurst = 0;
18826
+ /** Events for one log line (none, a close, or a close and a burst). */
18827
+ feed(line) {
18828
+ const close = parseChannelClose(line);
18829
+ if (!close) return [];
18830
+ const t = close.at.getTime();
18831
+ this.recent = this.recent.filter((c) => t - c.at.getTime() < BURST_WINDOW_MS && c.channel !== close.channel);
18832
+ this.recent.push(close);
18833
+ const out = [{
18834
+ timestamp: close.at,
18835
+ severity: "high",
18836
+ message: `Lightning channel ${close.channel} closing (${close.to})`,
18837
+ details: { rule_id: "ln-channel-close", peer: close.peer, to_state: close.to, evidence: { at: close.at.toISOString(), module: "lightning", message: close.line } }
18838
+ }];
18839
+ if (this.recent.length >= 2 && t - this.lastBurst >= BURST_REALERT_MS) {
18840
+ this.lastBurst = t;
18841
+ out.push({
18842
+ timestamp: close.at,
18843
+ severity: "critical",
18844
+ message: `Lightning channel-close burst: ${this.recent.length} channels closing within 10 minutes (${this.recent.map((c) => c.channel).join(", ")}). If nobody here did this, the node is being drained.`,
18845
+ details: { rule_id: "ln-channel-close-burst", channels: this.recent.map((c) => c.channel), evidence: { at: close.at.toISOString(), module: "lightning", message: close.line } }
18846
+ });
18847
+ }
18848
+ return out;
18849
+ }
18850
+ };
18851
+ var LightningWatch = class {
18852
+ constructor(opts) {
18853
+ this.opts = opts;
18854
+ }
18855
+ opts;
18856
+ tails = [];
18857
+ timer = null;
18858
+ detector = new ChannelCloseDetector();
18859
+ start() {
18860
+ if (this.opts.enabled === false) return [];
18861
+ const found = [];
18862
+ for (const path of this.opts.paths?.length ? this.opts.paths : DEFAULT_CLN_LOGS) {
18863
+ if (!(0, import_node_fs27.existsSync)(path)) continue;
18864
+ try {
18865
+ (0, import_node_fs27.accessSync)(path, import_node_fs27.constants.R_OK);
18866
+ } catch {
18867
+ continue;
18868
+ }
18869
+ this.tails.push(new LogTail(path));
18870
+ found.push(path);
18871
+ }
18872
+ if (!found.length) return [];
18873
+ this.timer = setInterval(() => this.poll(), 2e3);
18874
+ this.timer.unref?.();
18875
+ this.opts.log(`[lightning] watching channel closes in ${found.join(", ")}`);
18876
+ return found;
18877
+ }
18878
+ stop() {
18879
+ if (this.timer) clearInterval(this.timer);
18880
+ this.timer = null;
18881
+ this.tails = [];
18882
+ }
18883
+ poll() {
18884
+ for (const tail of this.tails) {
18885
+ tail.poll((line) => {
18886
+ for (const e of this.detector.feed(line)) {
18887
+ const event = { module: "lightning", category: "system", ...e };
18888
+ try {
18889
+ insertEvent(event);
18890
+ } catch {
18891
+ }
18892
+ this.opts.bus.publish(event);
18893
+ }
18894
+ });
18895
+ }
18896
+ }
18897
+ };
18898
+
18899
+ // src/core/tor-exits.ts
18900
+ var import_node_fs28 = require("fs");
18901
+ var import_node_path21 = require("path");
18902
+ var import_node_net12 = require("net");
18903
+ var TOR_BULK_EXIT_LIST_URL = "https://check.torproject.org/torbulkexitlist";
18904
+ function parseTorExitList(text) {
18905
+ const out = /* @__PURE__ */ new Set();
18906
+ for (const raw of text.split("\n")) {
18907
+ const line = raw.trim();
18908
+ if (!line || line.startsWith("#")) continue;
18909
+ const ip = line.split(/\s+/)[0];
18910
+ if ((0, import_node_net12.isIP)(ip)) out.add(normalizeIp(ip));
18911
+ }
18912
+ return out;
18913
+ }
18914
+ function normalizeIp(ip) {
18915
+ const bare = ip.trim().replace(/^\[|\]$/g, "").replace(/%.*$/, "");
18916
+ const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(bare);
18917
+ return mapped ? mapped[1] : bare.toLowerCase();
18918
+ }
18919
+ var TorExitList = class _TorExitList {
18920
+ constructor(opts) {
18921
+ this.opts = opts;
18922
+ this.url = opts.url ?? TOR_BULK_EXIT_LIST_URL;
18923
+ this.refreshMs = Math.max(15 * 6e4, opts.refreshMs ?? 36e5);
18924
+ this.fetchImpl = opts.fetchImpl ?? fetch;
18925
+ this.log = opts.log ?? (() => {
18926
+ });
18927
+ this.now = opts.now ?? Date.now;
18928
+ }
18929
+ opts;
18930
+ exits = /* @__PURE__ */ new Set();
18931
+ updatedAt = 0;
18932
+ timer = null;
18933
+ url;
18934
+ refreshMs;
18935
+ fetchImpl;
18936
+ log;
18937
+ now;
18938
+ /** Fewer than this many exits is a broken download, not the Tor network (it has ~1,000+). */
18939
+ static MIN_PLAUSIBLE = 100;
18940
+ /** Load the cache, then refresh now and every `refreshMs`. */
18941
+ start() {
18942
+ this.loadCache();
18943
+ void this.refresh();
18944
+ this.timer = setInterval(() => void this.refresh(), this.refreshMs);
18945
+ this.timer.unref?.();
18946
+ }
18947
+ stop() {
18948
+ if (this.timer) clearInterval(this.timer);
18949
+ this.timer = null;
18950
+ }
18951
+ has(ip) {
18952
+ if (!ip) return false;
18953
+ return this.exits.has(normalizeIp(ip));
18954
+ }
18955
+ get size() {
18956
+ return this.exits.size;
18957
+ }
18958
+ /** When the list in memory was downloaded (ms), 0 if never. */
18959
+ get updated() {
18960
+ return this.updatedAt;
18961
+ }
18962
+ /** Replace the list directly (tests, and the CLI reading the cache). */
18963
+ load(ips, at = this.now()) {
18964
+ this.exits = new Set([...ips].map(normalizeIp));
18965
+ this.updatedAt = at;
18966
+ }
18967
+ loadCache() {
18968
+ try {
18969
+ if (!(0, import_node_fs28.existsSync)(this.opts.cachePath)) return false;
18970
+ const parsed = parseTorExitList((0, import_node_fs28.readFileSync)(this.opts.cachePath, "utf-8"));
18971
+ if (parsed.size === 0) return false;
18972
+ this.load(parsed, (0, import_node_fs28.statSync)(this.opts.cachePath).mtimeMs);
18973
+ this.log(`[tor] loaded ${parsed.size} Tor exit addresses from cache (${new Date(this.updatedAt).toISOString()})`);
18974
+ return true;
18975
+ } catch (err) {
18976
+ this.log(`[tor] could not read the exit list cache: ${err.message}`);
18977
+ return false;
18978
+ }
18979
+ }
18980
+ async refresh() {
18981
+ let text;
18982
+ try {
18983
+ const res = await this.fetchImpl(this.url, {
18984
+ signal: AbortSignal.timeout(3e4),
18985
+ headers: { "User-Agent": "threatcrush-daemon (tor exit list)" }
18986
+ });
18987
+ if (!res.ok) {
18988
+ this.log(`[tor] exit list download failed: HTTP ${res.status}; keeping ${this.exits.size} cached`);
18989
+ return false;
18990
+ }
18991
+ text = await res.text();
18992
+ } catch (err) {
18993
+ this.log(`[tor] exit list download failed: ${err.message}; keeping ${this.exits.size} cached`);
18994
+ return false;
18995
+ }
18996
+ const parsed = parseTorExitList(text);
18997
+ if (parsed.size < _TorExitList.MIN_PLAUSIBLE) {
18998
+ this.log(`[tor] exit list download had only ${parsed.size} addresses; keeping ${this.exits.size} cached`);
18999
+ return false;
19000
+ }
19001
+ const before = this.exits.size;
19002
+ this.load(parsed);
19003
+ try {
19004
+ (0, import_node_fs28.mkdirSync)((0, import_node_path21.dirname)(this.opts.cachePath), { recursive: true });
19005
+ (0, import_node_fs28.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
19006
+ (0, import_node_fs28.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
19007
+ } catch (err) {
19008
+ this.log(`[tor] could not save the exit list cache: ${err.message}`);
19009
+ }
19010
+ if (before !== parsed.size || before === 0) this.log(`[tor] loaded ${parsed.size} Tor exit addresses from ${this.url}`);
19011
+ return true;
19012
+ }
19013
+ };
19014
+
18161
19015
  // src/daemon/rules/engine.ts
18162
19016
  var MAX_WINDOW_ENTRIES = 1e3;
18163
19017
  function live(window) {
@@ -18172,6 +19026,23 @@ function expire(window, now) {
18172
19026
  window.head = 0;
18173
19027
  }
18174
19028
  }
19029
+ var EVIDENCE_MESSAGE_CHARS = 500;
19030
+ var EVIDENCE_FIELD_CHARS = 200;
19031
+ var EVIDENCE_FIELDS = ["unit", "identifier", "process", "comm", "pid", "user", "path", "method", "status", "host", "priority"];
19032
+ function evidenceOf(event) {
19033
+ const details = event.details ?? {};
19034
+ const out = {
19035
+ at: event.timestamp instanceof Date ? event.timestamp.toISOString() : String(event.timestamp ?? ""),
19036
+ module: event.module,
19037
+ message: String(event.message ?? "").slice(0, EVIDENCE_MESSAGE_CHARS)
19038
+ };
19039
+ if (event.source_ip) out.source_ip = event.source_ip;
19040
+ for (const k of EVIDENCE_FIELDS) {
19041
+ const v = details[k];
19042
+ if (typeof v === "string" || typeof v === "number") out[k] = String(v).slice(0, EVIDENCE_FIELD_CHARS);
19043
+ }
19044
+ return out;
19045
+ }
18175
19046
  var RuleEngine = class {
18176
19047
  constructor(onDetection) {
18177
19048
  this.onDetection = onDetection;
@@ -18240,6 +19111,9 @@ var RuleEngine = class {
18240
19111
  tags: rule.tags,
18241
19112
  category: rule.category,
18242
19113
  remediation: rule.remediation,
19114
+ // What actually happened: without this every alert, page and incident
19115
+ // could only repeat the rule's description ("a critical log message").
19116
+ evidence: evidenceOf(event),
18243
19117
  ...aggregate ? { group_by: groupBy, group: groupValue, distinct_ips: distinctIps, hits } : {}
18244
19118
  }
18245
19119
  });
@@ -18319,8 +19193,8 @@ var RuleEngine = class {
18319
19193
  };
18320
19194
 
18321
19195
  // src/daemon/rules/loader.ts
18322
- var import_node_fs26 = require("fs");
18323
- var import_node_path20 = require("path");
19196
+ var import_node_fs29 = require("fs");
19197
+ var import_node_path22 = require("path");
18324
19198
 
18325
19199
  // src/daemon/rules/default-rules.ts
18326
19200
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -18790,11 +19664,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
18790
19664
  function loadAllRules(customDir) {
18791
19665
  const rules = [...DEFAULT_RULES];
18792
19666
  const dir = customDir || RULES_DIR;
18793
- if ((0, import_node_fs26.existsSync)(dir)) {
18794
- const files = (0, import_node_fs26.readdirSync)(dir).filter((f) => f.endsWith(".json"));
19667
+ if ((0, import_node_fs29.existsSync)(dir)) {
19668
+ const files = (0, import_node_fs29.readdirSync)(dir).filter((f) => f.endsWith(".json"));
18795
19669
  for (const file of files) {
18796
19670
  try {
18797
- const raw = (0, import_node_fs26.readFileSync)((0, import_node_path20.join)(dir, file), "utf-8");
19671
+ const raw = (0, import_node_fs29.readFileSync)((0, import_node_path22.join)(dir, file), "utf-8");
18798
19672
  const parsed = JSON.parse(raw);
18799
19673
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
18800
19674
  for (const rule of customRules) {
@@ -18825,24 +19699,24 @@ function loadAllRules(customDir) {
18825
19699
  }
18826
19700
 
18827
19701
  // src/daemon/firewall/adapters.ts
18828
- var import_node_child_process8 = require("child_process");
18829
- var import_node_fs27 = require("fs");
18830
- var import_node_path21 = require("path");
18831
- var import_node_net10 = require("net");
19702
+ var import_node_child_process9 = require("child_process");
19703
+ var import_node_fs30 = require("fs");
19704
+ var import_node_path23 = require("path");
19705
+ var import_node_net13 = require("net");
18832
19706
  function assertValidFirewallIp(ip) {
18833
- if ((0, import_node_net10.isIP)(ip) !== 4) {
19707
+ if ((0, import_node_net13.isIP)(ip) !== 4) {
18834
19708
  throw new Error(`Invalid IPv4 address: ${ip}`);
18835
19709
  }
18836
19710
  }
18837
19711
  function assertBannableIp(ip) {
18838
- if ((0, import_node_net10.isIP)(ip) === 0) {
19712
+ if ((0, import_node_net13.isIP)(ip) === 0) {
18839
19713
  throw new Error(`Invalid IP address: ${ip}`);
18840
19714
  }
18841
19715
  }
18842
19716
  function writeIfAbsent(path, contents) {
18843
- (0, import_node_fs27.mkdirSync)((0, import_node_path21.dirname)(path), { recursive: true });
19717
+ (0, import_node_fs30.mkdirSync)((0, import_node_path23.dirname)(path), { recursive: true });
18844
19718
  try {
18845
- (0, import_node_fs27.writeFileSync)(path, contents, { flag: "wx" });
19719
+ (0, import_node_fs30.writeFileSync)(path, contents, { flag: "wx" });
18846
19720
  } catch (err) {
18847
19721
  if (err.code !== "EEXIST") throw err;
18848
19722
  }
@@ -18861,11 +19735,11 @@ var Fail2banAdapter = class {
18861
19735
  enforces = true;
18862
19736
  jailReady = false;
18863
19737
  isAvailable() {
18864
- const result = (0, import_node_child_process8.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
19738
+ const result = (0, import_node_child_process9.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
18865
19739
  return result.status === 0;
18866
19740
  }
18867
19741
  client(args) {
18868
- return (0, import_node_child_process8.execFileSync)("fail2ban-client", args, {
19742
+ return (0, import_node_child_process9.execFileSync)("fail2ban-client", args, {
18869
19743
  encoding: "utf-8",
18870
19744
  stdio: ["ignore", "pipe", "pipe"]
18871
19745
  });
@@ -18941,7 +19815,7 @@ var Fail2banAdapter = class {
18941
19815
  const status = this.client(["status", this.jail]);
18942
19816
  const line = status.split("\n").find((l) => /Banned IP list:/i.test(l));
18943
19817
  if (!line) return [];
18944
- return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net10.isIP)(s) !== 0);
19818
+ return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net13.isIP)(s) !== 0);
18945
19819
  } catch {
18946
19820
  return [];
18947
19821
  }
@@ -18951,45 +19825,45 @@ var Fail2banAdapter = class {
18951
19825
  function parseBannedList(output) {
18952
19826
  const found = [];
18953
19827
  for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
18954
- if ((0, import_node_net10.isIP)(match[1]) !== 0) found.push(match[1]);
19828
+ if ((0, import_node_net13.isIP)(match[1]) !== 0) found.push(match[1]);
18955
19829
  }
18956
19830
  if (found.length > 0) return found;
18957
- return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net10.isIP)(s) !== 0);
19831
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net13.isIP)(s) !== 0);
18958
19832
  }
18959
19833
  var NftablesAdapter = class {
18960
19834
  name = "nftables";
18961
19835
  table = "threatcrush";
18962
19836
  set = "blocklist";
18963
19837
  isAvailable() {
18964
- const result = (0, import_node_child_process8.spawnSync)("nft", ["--version"], { stdio: "pipe" });
19838
+ const result = (0, import_node_child_process9.spawnSync)("nft", ["--version"], { stdio: "pipe" });
18965
19839
  return result.status === 0;
18966
19840
  }
18967
19841
  ensureSetup() {
18968
19842
  try {
18969
- (0, import_node_child_process8.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
19843
+ (0, import_node_child_process9.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
18970
19844
  } catch {
18971
- (0, import_node_child_process8.execSync)(`nft add table inet ${this.table}`);
18972
- (0, import_node_child_process8.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
18973
- (0, import_node_child_process8.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
18974
- (0, import_node_child_process8.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
19845
+ (0, import_node_child_process9.execSync)(`nft add table inet ${this.table}`);
19846
+ (0, import_node_child_process9.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
19847
+ (0, import_node_child_process9.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
19848
+ (0, import_node_child_process9.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
18975
19849
  }
18976
19850
  }
18977
19851
  async block(ip) {
18978
19852
  assertValidFirewallIp(ip);
18979
19853
  this.ensureSetup();
18980
- (0, import_node_child_process8.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
19854
+ (0, import_node_child_process9.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
18981
19855
  }
18982
19856
  async unblock(ip) {
18983
19857
  assertValidFirewallIp(ip);
18984
19858
  try {
18985
- (0, import_node_child_process8.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
19859
+ (0, import_node_child_process9.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
18986
19860
  } catch {
18987
19861
  }
18988
19862
  }
18989
19863
  async isBlocked(ip) {
18990
19864
  assertValidFirewallIp(ip);
18991
19865
  try {
18992
- const output = (0, import_node_child_process8.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
19866
+ const output = (0, import_node_child_process9.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
18993
19867
  return output.includes(ip);
18994
19868
  } catch {
18995
19869
  return false;
@@ -18997,7 +19871,7 @@ var NftablesAdapter = class {
18997
19871
  }
18998
19872
  async listBlocked() {
18999
19873
  try {
19000
- const output = (0, import_node_child_process8.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
19874
+ const output = (0, import_node_child_process9.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
19001
19875
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
19002
19876
  if (!match) return [];
19003
19877
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -19010,34 +19884,34 @@ var IptablesAdapter = class {
19010
19884
  name = "iptables";
19011
19885
  chain = "THREATCRUSH";
19012
19886
  isAvailable() {
19013
- const result = (0, import_node_child_process8.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
19887
+ const result = (0, import_node_child_process9.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
19014
19888
  return result.status === 0;
19015
19889
  }
19016
19890
  ensureChain() {
19017
19891
  try {
19018
- (0, import_node_child_process8.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
19892
+ (0, import_node_child_process9.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
19019
19893
  } catch {
19020
- (0, import_node_child_process8.execSync)(`iptables -N ${this.chain}`);
19021
- (0, import_node_child_process8.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
19894
+ (0, import_node_child_process9.execSync)(`iptables -N ${this.chain}`);
19895
+ (0, import_node_child_process9.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
19022
19896
  }
19023
19897
  }
19024
19898
  async block(ip) {
19025
19899
  assertValidFirewallIp(ip);
19026
19900
  this.ensureChain();
19027
19901
  if (await this.isBlocked(ip)) return;
19028
- (0, import_node_child_process8.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
19902
+ (0, import_node_child_process9.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
19029
19903
  }
19030
19904
  async unblock(ip) {
19031
19905
  assertValidFirewallIp(ip);
19032
19906
  try {
19033
- (0, import_node_child_process8.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
19907
+ (0, import_node_child_process9.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
19034
19908
  } catch {
19035
19909
  }
19036
19910
  }
19037
19911
  async isBlocked(ip) {
19038
19912
  assertValidFirewallIp(ip);
19039
19913
  try {
19040
- const output = (0, import_node_child_process8.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
19914
+ const output = (0, import_node_child_process9.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
19041
19915
  return output.includes(ip);
19042
19916
  } catch {
19043
19917
  return false;
@@ -19045,7 +19919,7 @@ var IptablesAdapter = class {
19045
19919
  }
19046
19920
  async listBlocked() {
19047
19921
  try {
19048
- const output = (0, import_node_child_process8.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
19922
+ const output = (0, import_node_child_process9.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
19049
19923
  const ips = [];
19050
19924
  for (const line of output.split("\n")) {
19051
19925
  const match = line.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -19101,20 +19975,20 @@ function detectFirewallAdapter(backend = "auto") {
19101
19975
  }
19102
19976
 
19103
19977
  // src/daemon/firewall/remediation.ts
19104
- var import_node_fs28 = require("fs");
19105
- var import_node_child_process9 = require("child_process");
19106
- var import_node_net11 = require("net");
19978
+ var import_node_fs31 = require("fs");
19979
+ var import_node_child_process10 = require("child_process");
19980
+ var import_node_net14 = require("net");
19107
19981
 
19108
19982
  // src/daemon/firewall/crawlers.ts
19109
- var import_node_dns = require("dns");
19983
+ var import_node_dns2 = require("dns");
19110
19984
  var CRAWLER_DOMAINS = ["googlebot.com", "google.com", "search.msn.com", "applebot.apple.com"];
19111
19985
  var systemResolver = {
19112
- reverse: (ip) => import_node_dns.promises.reverse(ip),
19113
- lookup: async (host) => (await import_node_dns.promises.lookup(host, { all: true })).map((a) => a.address)
19986
+ reverse: (ip) => import_node_dns2.promises.reverse(ip),
19987
+ lookup: async (host) => (await import_node_dns2.promises.lookup(host, { all: true })).map((a) => a.address)
19114
19988
  };
19115
19989
  var TIMEOUT_MS2 = 2e3;
19116
19990
  var CACHE_MS = 6 * 36e5;
19117
- function withTimeout(p) {
19991
+ function withTimeout2(p) {
19118
19992
  return Promise.race([
19119
19993
  p,
19120
19994
  new Promise((_, reject) => setTimeout(() => reject(new Error("dns timeout")), TIMEOUT_MS2).unref())
@@ -19131,9 +20005,9 @@ function crawlerVerifier(resolver = systemResolver) {
19131
20005
  if (hit && hit.until > Date.now()) return hit.host;
19132
20006
  let host = null;
19133
20007
  try {
19134
- const names = await withTimeout(resolver.reverse(ip));
20008
+ const names = await withTimeout2(resolver.reverse(ip));
19135
20009
  for (const name of names.filter(inCrawlerDomain)) {
19136
- const addrs = await withTimeout(resolver.lookup(name));
20010
+ const addrs = await withTimeout2(resolver.lookup(name));
19137
20011
  if (addrs.includes(ip)) {
19138
20012
  host = name.replace(/\.$/, "");
19139
20013
  break;
@@ -19161,7 +20035,8 @@ var DEFAULT_CONFIG2 = {
19161
20035
  protect_current_ssh_client: true,
19162
20036
  protect_recent_operators: true,
19163
20037
  operator_memory_seconds: 30 * 86400,
19164
- spare_verified_crawlers: true
20038
+ spare_verified_crawlers: true,
20039
+ block_tor_ssh: true
19165
20040
  };
19166
20041
  var defaultDiscovery = {
19167
20042
  sshPeers: () => [currentSshClient(), ...establishedSshPeers()].filter((ip) => Boolean(ip)),
@@ -19170,19 +20045,19 @@ var defaultDiscovery = {
19170
20045
  const snapshot = takeSnapshot({
19171
20046
  readFile: (p) => {
19172
20047
  try {
19173
- return (0, import_node_fs28.readFileSync)(p, "utf-8");
20048
+ return (0, import_node_fs31.readFileSync)(p, "utf-8");
19174
20049
  } catch {
19175
20050
  return null;
19176
20051
  }
19177
20052
  },
19178
20053
  readDir: (p) => {
19179
20054
  try {
19180
- return (0, import_node_fs28.readdirSync)(p);
20055
+ return (0, import_node_fs31.readdirSync)(p);
19181
20056
  } catch {
19182
20057
  return null;
19183
20058
  }
19184
20059
  },
19185
- exists: (p) => (0, import_node_fs28.existsSync)(p)
20060
+ exists: (p) => (0, import_node_fs31.existsSync)(p)
19186
20061
  });
19187
20062
  const out = /* @__PURE__ */ new Set();
19188
20063
  for (const keys of Object.values(snapshot.keys)) {
@@ -19191,7 +20066,7 @@ var defaultDiscovery = {
19191
20066
  return out;
19192
20067
  },
19193
20068
  keyLoginJournal: (sinceSeconds) => new Promise((resolve4) => {
19194
- (0, import_node_child_process9.execFile)(
20069
+ (0, import_node_child_process10.execFile)(
19195
20070
  "journalctl",
19196
20071
  ["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
19197
20072
  { maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
@@ -19199,7 +20074,7 @@ var defaultDiscovery = {
19199
20074
  );
19200
20075
  })
19201
20076
  };
19202
- var SEVERITY_RANK5 = {
20077
+ var SEVERITY_RANK6 = {
19203
20078
  info: 0,
19204
20079
  low: 1,
19205
20080
  medium: 2,
@@ -19256,16 +20131,56 @@ var RemediationManager = class {
19256
20131
  operators = {};
19257
20132
  expiryTimer = null;
19258
20133
  operatorTimer = null;
20134
+ /** True for a Tor exit address; such an address is never an operator. */
20135
+ isTorExit = () => false;
19259
20136
  /** Remembered operator addresses and when each was last seen. */
19260
20137
  getOperators() {
19261
20138
  return { ...this.operators };
19262
20139
  }
20140
+ /**
20141
+ * Teach the manager which addresses are Tor exits. They are never
20142
+ * remembered as operators and never protected as a live session: on dev2
20143
+ * the 2026-10-27 intruder logged in with a stolen key from Tor, which made
20144
+ * the exit an "operator" that nothing could ban for 30 days.
20145
+ */
20146
+ setTorExitCheck(check) {
20147
+ this.isTorExit = check;
20148
+ let dropped = 0;
20149
+ this.protectedList = this.protectedList.filter((a) => !(0, import_node_net14.isIP)(a) || !check(a) || this.pinned.has(a) || this.config.allowlist.includes(a));
20150
+ for (const ip of Object.keys(this.operators)) {
20151
+ if (!check(ip)) continue;
20152
+ delete this.operators[ip];
20153
+ this.protectedList = this.protectedList.filter((a) => a !== ip || this.pinned.has(a) || this.config.allowlist.includes(a));
20154
+ dropped++;
20155
+ }
20156
+ if (dropped) {
20157
+ this.logLine(`[firewall] forgot ${dropped} remembered operator address(es) that are Tor exits`);
20158
+ this.saveState();
20159
+ }
20160
+ }
20161
+ /** Tor SSH bans on (setting) — the cloud may change it unless config pinned it. */
20162
+ get blockTorSsh() {
20163
+ return this.config.enabled && this.config.block_tor_ssh;
20164
+ }
20165
+ setBlockTorSsh(on) {
20166
+ this.config.block_tor_ssh = on;
20167
+ }
20168
+ /**
20169
+ * Our own addresses: built-ins, shared infrastructure, gateways, the
20170
+ * operator's `[remediation] protected` and the dashboard's org allowlist
20171
+ * (Known IPs). Not remembered operators or live sessions.
20172
+ */
20173
+ isFleetAddress(ip) {
20174
+ return isProtected(ip, [...this.pinned, ...this.config.allowlist]);
20175
+ }
19263
20176
  /**
19264
20177
  * An address an operator really came from: never ban it, remember it, and
19265
20178
  * lift a ban that is already on it — the operator is the one who needs in.
19266
20179
  */
19267
20180
  noteOperator(ip, at, remember = true) {
19268
20181
  if (Date.now() - at > this.config.operator_memory_seconds * 1e3) return;
20182
+ if (this.isTorExit(ip) && !this.isFleetAddress(ip)) return;
20183
+ if (this.blocklist.some((b) => b.ip === ip && b.strict)) return;
19269
20184
  if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
19270
20185
  if (!remember || !this.config.protect_recent_operators || isProtected(ip, DEFAULT_PROTECTED)) return;
19271
20186
  const known = this.operators[ip] ?? 0;
@@ -19315,17 +20230,21 @@ var RemediationManager = class {
19315
20230
  }
19316
20231
  async handleDetection(event) {
19317
20232
  if (!this.config.enabled) return;
19318
- const eventRank = SEVERITY_RANK5[event.severity] ?? 0;
19319
- const minRank = SEVERITY_RANK5[this.config.min_severity] ?? 3;
20233
+ const eventRank = SEVERITY_RANK6[event.severity] ?? 0;
20234
+ const minRank = SEVERITY_RANK6[this.config.min_severity] ?? 3;
19320
20235
  if (eventRank < minRank) return;
19321
- if (isSuccessfulAuth(event.message)) return;
20236
+ const remediation = event.details?.remediation;
20237
+ if (isSuccessfulAuth(event.message) && remediation?.ban_on_login !== true) return;
19322
20238
  if (event.details?.rule_id) {
19323
- const remediation = event.details?.remediation;
19324
20239
  if (remediation?.action !== "block") return;
19325
20240
  }
19326
20241
  const ip = event.source_ip;
19327
- if (!ip || (0, import_node_net11.isIP)(ip) === 0) return;
19328
- if (this.isAllowlisted(ip)) return;
20242
+ if (!ip || (0, import_node_net14.isIP)(ip) === 0) return;
20243
+ const strict = remediation?.override_operator_protection === true;
20244
+ if (strict ? this.isFleetAddress(ip) : this.isAllowlisted(ip)) {
20245
+ if (strict) this.logLine(`[remediation] not banning ${ip}: it is one of our own addresses (${event.message})`);
20246
+ return;
20247
+ }
19329
20248
  if (this.blocklist.some((b) => b.ip === ip)) return;
19330
20249
  if (this.config.spare_verified_crawlers) {
19331
20250
  const crawler = await this.verifyCrawler(ip);
@@ -19335,7 +20254,13 @@ var RemediationManager = class {
19335
20254
  }
19336
20255
  }
19337
20256
  const ruleId = event.details?.rule_id;
19338
- await this.ban(ip, event.message, { ruleId, source: "auto" });
20257
+ await this.ban(ip, event.message, {
20258
+ ruleId,
20259
+ source: "auto",
20260
+ enforceInDryRun: remediation?.enforce_in_dry_run === true,
20261
+ strict,
20262
+ ...remediation?.max_ban ? { ttlSeconds: this.config.max_ban_seconds } : {}
20263
+ });
19339
20264
  }
19340
20265
  /**
19341
20266
  * Ban `ip`. With no explicit TTL the length comes from the doubling ladder:
@@ -19343,8 +20268,8 @@ var RemediationManager = class {
19343
20268
  * 4th offence and so on, clamped to `max_ban_seconds`.
19344
20269
  */
19345
20270
  async ban(ip, reason, opts = {}) {
19346
- if ((0, import_node_net11.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
19347
- if (this.isAllowlisted(ip)) {
20271
+ if ((0, import_node_net14.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
20272
+ if (opts.strict ? this.isFleetAddress(ip) : this.isAllowlisted(ip)) {
19348
20273
  return { ok: false, error: `${ip} is protected and can never be blocked` };
19349
20274
  }
19350
20275
  const now = Date.now();
@@ -19352,7 +20277,8 @@ var RemediationManager = class {
19352
20277
  if (existing && !opts.ttlSeconds) {
19353
20278
  return { ok: false, error: `${ip} is already banned` };
19354
20279
  }
19355
- if (!this.config.dry_run) {
20280
+ const dryRun = this.config.dry_run && !(opts.enforceInDryRun && this.adapter.enforces !== false);
20281
+ if (!dryRun) {
19356
20282
  try {
19357
20283
  await this.adapter.block(ip);
19358
20284
  } catch (err) {
@@ -19385,14 +20311,19 @@ var RemediationManager = class {
19385
20311
  rule_id: opts.ruleId,
19386
20312
  blocked_at: now,
19387
20313
  expires_at: now + ttl * 1e3,
19388
- dry_run: this.config.dry_run,
20314
+ dry_run: dryRun,
19389
20315
  strikes: strike,
19390
- source: opts.source ?? "manual"
20316
+ source: opts.source ?? "manual",
20317
+ ...opts.strict ? { strict: true } : {}
19391
20318
  };
20319
+ if (opts.strict) {
20320
+ delete this.operators[ip];
20321
+ this.protectedList = this.protectedList.filter((a) => a !== ip || this.pinned.has(a) || this.config.allowlist.includes(a));
20322
+ }
19392
20323
  this.blocklist = this.blocklist.filter((b) => b.ip !== ip);
19393
20324
  this.blocklist.push(entry);
19394
20325
  this.saveState();
19395
- const mode = this.config.dry_run ? "[DRY-RUN] " : "";
20326
+ const mode = dryRun ? "[DRY-RUN] " : this.config.dry_run ? "[ENFORCED IN DRY-RUN] " : "";
19396
20327
  const label = `${mode}Banned ${ip} for ${formatDuration(ttl)} (offence #${strike}): ${reason}`;
19397
20328
  this.logLine(`[firewall] ${label}`);
19398
20329
  this.bus.publish({
@@ -19407,7 +20338,7 @@ var RemediationManager = class {
19407
20338
  rule_id: opts.ruleId,
19408
20339
  reason,
19409
20340
  origin: opts.origin,
19410
- dry_run: this.config.dry_run,
20341
+ dry_run: dryRun,
19411
20342
  ttl_seconds: ttl,
19412
20343
  strikes: strike,
19413
20344
  source: entry.source,
@@ -19490,10 +20421,13 @@ var RemediationManager = class {
19490
20421
  * Saying so up front beats a dashboard that looks armed and is not.
19491
20422
  */
19492
20423
  privilegeWarning() {
19493
- if (!this.config.enabled || this.config.dry_run) return void 0;
20424
+ if (!this.config.enabled) return void 0;
19494
20425
  if (this.adapter.enforces === false) return void 0;
19495
20426
  const uid = typeof process.getuid === "function" ? process.getuid() : 0;
19496
20427
  if (uid === 0) return void 0;
20428
+ if (this.config.dry_run) {
20429
+ return this.config.block_tor_ssh ? `daemon runs as uid ${uid}: the Tor SSH ban (enforced even in dry_run) cannot write ${this.adapter.name} rules` : void 0;
20430
+ }
19497
20431
  return `daemon runs as uid ${uid} and cannot write ${this.adapter.name} rules \u2014 bans will fail`;
19498
20432
  }
19499
20433
  addToAllowlist(ip) {
@@ -19522,10 +20456,11 @@ var RemediationManager = class {
19522
20456
  */
19523
20457
  async reconcile() {
19524
20458
  const now = Date.now();
19525
- const lifted = this.blocklist.filter((b) => this.isAllowlisted(b.ip));
20459
+ const guarded = (b) => b.strict ? this.isFleetAddress(b.ip) : this.isAllowlisted(b.ip);
20460
+ const lifted = this.blocklist.filter(guarded);
19526
20461
  for (const entry of lifted) this.logLine(`[firewall] reconcile: lifting ban on protected ${entry.ip}`);
19527
- const live2 = this.blocklist.filter((b) => b.expires_at > now && !this.isAllowlisted(b.ip));
19528
- const stale = this.blocklist.filter((b) => b.expires_at <= now || this.isAllowlisted(b.ip));
20462
+ const live2 = this.blocklist.filter((b) => b.expires_at > now && !guarded(b));
20463
+ const stale = this.blocklist.filter((b) => b.expires_at <= now || guarded(b));
19529
20464
  for (const entry of stale) {
19530
20465
  if (!entry.dry_run) {
19531
20466
  try {
@@ -19552,8 +20487,8 @@ var RemediationManager = class {
19552
20487
  }
19553
20488
  }
19554
20489
  }
19555
- if (this.config.dry_run) return;
19556
20490
  for (const entry of live2) {
20491
+ if (entry.dry_run) continue;
19557
20492
  if (applied?.includes(entry.ip)) continue;
19558
20493
  try {
19559
20494
  await this.adapter.block(entry.ip);
@@ -19610,7 +20545,8 @@ var RemediationManager = class {
19610
20545
  if (saved && typeof saved === "object" && this.config.protect_recent_operators) {
19611
20546
  const cutoff = Date.now() - this.config.operator_memory_seconds * 1e3;
19612
20547
  for (const [ip, at] of Object.entries(saved)) {
19613
- if (typeof at !== "number" || at < cutoff || !(0, import_node_net11.isIP)(ip)) continue;
20548
+ if (typeof at !== "number" || at < cutoff || !(0, import_node_net14.isIP)(ip)) continue;
20549
+ if (this.blocklist.some((b) => b.ip === ip && b.strict)) continue;
19614
20550
  this.operators[ip] = at;
19615
20551
  if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
19616
20552
  }
@@ -19634,7 +20570,7 @@ var RemediationManager = class {
19634
20570
  }
19635
20571
  logLine(line) {
19636
20572
  try {
19637
- (0, import_node_fs28.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
20573
+ (0, import_node_fs31.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
19638
20574
  `);
19639
20575
  } catch {
19640
20576
  }
@@ -19666,6 +20602,7 @@ function remediationSettings(section) {
19666
20602
  }
19667
20603
  const operatorMemory = parseDuration(section.operator_memory);
19668
20604
  if (operatorMemory) settings.operator_memory_seconds = operatorMemory;
20605
+ if (typeof section.block_tor_ssh === "boolean") settings.block_tor_ssh = section.block_tor_ssh;
19669
20606
  if (typeof section.spare_verified_crawlers === "boolean") {
19670
20607
  settings.spare_verified_crawlers = section.spare_verified_crawlers;
19671
20608
  }
@@ -19673,19 +20610,19 @@ function remediationSettings(section) {
19673
20610
  }
19674
20611
 
19675
20612
  // src/daemon/watchdog-service.ts
19676
- var import_node_fs30 = require("fs");
19677
- var import_node_path23 = require("path");
20613
+ var import_node_fs33 = require("fs");
20614
+ var import_node_path25 = require("path");
19678
20615
 
19679
20616
  // src/core/watchdog.ts
19680
- var import_node_fs29 = require("fs");
20617
+ var import_node_fs32 = require("fs");
19681
20618
  var import_node_crypto7 = require("crypto");
19682
- var import_node_path22 = require("path");
20619
+ var import_node_path24 = require("path");
19683
20620
  var WATCHDOG_DIRNAME = "watchdog";
19684
20621
  var LOG_FILE2 = "attacks.jsonl";
19685
20622
  var ROTATED_FILE = "attacks.1.jsonl";
19686
20623
  var ROTATE_BYTES = 50 * 1024 * 1024;
19687
20624
  var SEEN_LIMIT = 5e3;
19688
- var SEVERITY_RANK6 = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
20625
+ var SEVERITY_RANK7 = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
19689
20626
  function str2(v) {
19690
20627
  return typeof v === "string" && v !== "" && v !== "-" ? v : void 0;
19691
20628
  }
@@ -19696,7 +20633,7 @@ function isAttack(event) {
19696
20633
  const crs = typeof d.crs_score === "number" ? d.crs_score : 0;
19697
20634
  if (crs > 0 || str2(d.attack_type)) return true;
19698
20635
  if (event.category === "web" && typeof d.status === "number" && !str2(d.rule_id)) return false;
19699
- return SEVERITY_RANK6[event.severity] >= SEVERITY_RANK6.medium;
20636
+ return SEVERITY_RANK7[event.severity] >= SEVERITY_RANK7.medium;
19700
20637
  }
19701
20638
  function outcomeFor(status) {
19702
20639
  if (typeof status !== "number" || !Number.isFinite(status)) return "unknown";
@@ -19768,12 +20705,12 @@ var WatchdogLog = class {
19768
20705
  stats = { logged: 0, answered: 0, errored: 0 };
19769
20706
  constructor(dir, options = {}) {
19770
20707
  this.dir = dir;
19771
- this.file = (0, import_node_path22.join)(dir, LOG_FILE2);
20708
+ this.file = (0, import_node_path24.join)(dir, LOG_FILE2);
19772
20709
  this.shareGid = options.shareGid;
19773
- (0, import_node_fs29.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
20710
+ (0, import_node_fs32.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
19774
20711
  if (this.shareGid !== void 0) {
19775
- (0, import_node_fs29.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
19776
- (0, import_node_fs29.chmodSync)(dir, 1528);
20712
+ (0, import_node_fs32.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
20713
+ (0, import_node_fs32.chmodSync)(dir, 1528);
19777
20714
  }
19778
20715
  for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
19779
20716
  }
@@ -19802,16 +20739,16 @@ var WatchdogLog = class {
19802
20739
  const chunk = this.buffer.join("\n") + "\n";
19803
20740
  this.buffer = [];
19804
20741
  try {
19805
- if ((0, import_node_fs29.statSync)(this.file).size > ROTATE_BYTES) {
19806
- (0, import_node_fs29.renameSync)(this.file, (0, import_node_path22.join)(this.dir, ROTATED_FILE));
20742
+ if ((0, import_node_fs32.statSync)(this.file).size > ROTATE_BYTES) {
20743
+ (0, import_node_fs32.renameSync)(this.file, (0, import_node_path24.join)(this.dir, ROTATED_FILE));
19807
20744
  }
19808
20745
  } catch {
19809
20746
  }
19810
- (0, import_node_fs29.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
20747
+ (0, import_node_fs32.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
19811
20748
  if (this.shareGid !== void 0) {
19812
20749
  try {
19813
- (0, import_node_fs29.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
19814
- (0, import_node_fs29.chmodSync)(this.file, 432);
20750
+ (0, import_node_fs32.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
20751
+ (0, import_node_fs32.chmodSync)(this.file, 432);
19815
20752
  } catch {
19816
20753
  }
19817
20754
  }
@@ -19832,21 +20769,21 @@ function parseLines(text) {
19832
20769
  function readTail(file, bytes) {
19833
20770
  let fd;
19834
20771
  try {
19835
- fd = (0, import_node_fs29.openSync)(file, "r");
20772
+ fd = (0, import_node_fs32.openSync)(file, "r");
19836
20773
  } catch (err) {
19837
20774
  if (err.code === "ENOENT") return [];
19838
20775
  throw err;
19839
20776
  }
19840
20777
  try {
19841
- const size = (0, import_node_fs29.fstatSync)(fd).size;
20778
+ const size = (0, import_node_fs32.fstatSync)(fd).size;
19842
20779
  const start = Math.max(0, size - bytes);
19843
20780
  const buf = Buffer.alloc(size - start);
19844
- (0, import_node_fs29.readSync)(fd, buf, 0, buf.length, start);
20781
+ (0, import_node_fs32.readSync)(fd, buf, 0, buf.length, start);
19845
20782
  let text = buf.toString("utf8");
19846
20783
  if (start > 0) text = text.slice(text.indexOf("\n") + 1);
19847
20784
  return parseLines(text);
19848
20785
  } finally {
19849
- (0, import_node_fs29.closeSync)(fd);
20786
+ (0, import_node_fs32.closeSync)(fd);
19850
20787
  }
19851
20788
  }
19852
20789
 
@@ -19855,13 +20792,13 @@ function defaultShareGid() {
19855
20792
  const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
19856
20793
  if (!isRoot2) return void 0;
19857
20794
  try {
19858
- return (0, import_node_fs30.statSync)("/var/log/auth.log").gid;
20795
+ return (0, import_node_fs33.statSync)("/var/log/auth.log").gid;
19859
20796
  } catch {
19860
20797
  return void 0;
19861
20798
  }
19862
20799
  }
19863
20800
  function startWatchdog(opts) {
19864
- const dir = opts.config?.dir ?? (0, import_node_path23.join)(opts.stateDir, WATCHDOG_DIRNAME);
20801
+ const dir = opts.config?.dir ?? (0, import_node_path25.join)(opts.stateDir, WATCHDOG_DIRNAME);
19865
20802
  const base = { dir, logged: 0, answered: 0, errored: 0 };
19866
20803
  if (opts.config?.enabled === false) {
19867
20804
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -19952,7 +20889,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
19952
20889
  }
19953
20890
 
19954
20891
  // src/core/node-runtime.ts
19955
- var import_node_child_process10 = require("child_process");
20892
+ var import_node_child_process11 = require("child_process");
19956
20893
  var MIN_DAEMON_NODE_MAJOR = 22;
19957
20894
  function nodeMajor(version) {
19958
20895
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -19968,16 +20905,16 @@ function daemonNodeProblem(version) {
19968
20905
  // src/daemon/index.ts
19969
20906
  function readVersion2() {
19970
20907
  try {
19971
- const pkg = JSON.parse((0, import_node_fs31.readFileSync)((0, import_node_path24.join)(__dirname, "..", "package.json"), "utf-8"));
20908
+ const pkg = JSON.parse((0, import_node_fs34.readFileSync)((0, import_node_path26.join)(__dirname, "..", "package.json"), "utf-8"));
19972
20909
  return pkg.version || "0.0.0";
19973
20910
  } catch {
19974
20911
  return "0.0.0";
19975
20912
  }
19976
20913
  }
19977
20914
  async function runHardeningChecks() {
19978
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process11.execFile)(
20915
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process12.execFile)(
19979
20916
  process.execPath,
19980
- [(0, import_node_path24.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
20917
+ [(0, import_node_path26.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
19981
20918
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
19982
20919
  );
19983
20920
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -19989,9 +20926,9 @@ async function runHardeningChecks() {
19989
20926
  return patches ? [...findings, patches] : findings;
19990
20927
  }
19991
20928
  async function runPatchCheck() {
19992
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process11.execFile)(
20929
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process12.execFile)(
19993
20930
  process.execPath,
19994
- [(0, import_node_path24.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
20931
+ [(0, import_node_path26.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
19995
20932
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
19996
20933
  );
19997
20934
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -19999,7 +20936,7 @@ async function runPatchCheck() {
19999
20936
  }
20000
20937
  function logLine(line) {
20001
20938
  try {
20002
- (0, import_node_fs31.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
20939
+ (0, import_node_fs34.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
20003
20940
  `);
20004
20941
  } catch {
20005
20942
  }
@@ -20024,9 +20961,9 @@ async function runDaemon() {
20024
20961
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
20025
20962
  const restartDaemon = () => {
20026
20963
  if (PATHS.mode === "system") {
20027
- (0, import_node_child_process11.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
20964
+ (0, import_node_child_process12.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
20028
20965
  } else {
20029
- (0, import_node_child_process11.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
20966
+ (0, import_node_child_process12.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
20030
20967
  setTimeout(() => process.exit(0), 500).unref();
20031
20968
  }
20032
20969
  };
@@ -20041,7 +20978,7 @@ async function runDaemon() {
20041
20978
  } catch (err) {
20042
20979
  logLine(`[daemon] state db unavailable: ${err.message}`);
20043
20980
  }
20044
- const config = loadConfig((0, import_node_fs31.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
20981
+ const config = loadConfig((0, import_node_fs34.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
20045
20982
  configureAttackDetection(config.detection);
20046
20983
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
20047
20984
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -20105,7 +21042,7 @@ async function runDaemon() {
20105
21042
  const threatFeeds = new ThreatFeeds({
20106
21043
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
20107
21044
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
20108
- cachePath: (0, import_node_path24.join)(PATHS.stateDir, "threat-feeds.json"),
21045
+ cachePath: (0, import_node_path26.join)(PATHS.stateDir, "threat-feeds.json"),
20109
21046
  bus,
20110
21047
  log: logLine
20111
21048
  });
@@ -20113,13 +21050,35 @@ async function runDaemon() {
20113
21050
  const privilegeWatch = new PrivilegeWatch({
20114
21051
  settings: privilegeSettings(config.privileged),
20115
21052
  bus,
20116
- snapshotPath: (0, import_node_path24.join)(PATHS.stateDir, "privileges.json"),
20117
- loginsPath: (0, import_node_path24.join)(PATHS.stateDir, "login-countries.json"),
20118
- cursorPath: (0, import_node_path24.join)(PATHS.stateDir, "sudo-cursor.json"),
21053
+ snapshotPath: (0, import_node_path26.join)(PATHS.stateDir, "privileges.json"),
21054
+ loginsPath: (0, import_node_path26.join)(PATHS.stateDir, "login-countries.json"),
21055
+ cursorPath: (0, import_node_path26.join)(PATHS.stateDir, "sudo-cursor.json"),
20119
21056
  log: logLine
20120
21057
  });
20121
21058
  privilegeWatch.start();
20122
- new AlertDispatcher(bus, config);
21059
+ const torExits = new TorExitList({
21060
+ cachePath: (0, import_node_path26.join)(PATHS.stateDir, "tor-exits.txt"),
21061
+ url: config.remediation?.tor_exit_list_url,
21062
+ log: logLine
21063
+ });
21064
+ const sshIntrusion = new SshIntrusionWatch({
21065
+ bus,
21066
+ manager: remediation,
21067
+ tor: torExits,
21068
+ historyPath: (0, import_node_path26.join)(PATHS.stateDir, "key-logins.json"),
21069
+ keyLoginWatch: config.privileged?.key_login_watch !== false,
21070
+ log: logLine
21071
+ });
21072
+ sshIntrusion.start();
21073
+ const lightningWatch = new LightningWatch({
21074
+ bus,
21075
+ enabled: config.lightning?.enabled !== false,
21076
+ paths: Array.isArray(config.lightning?.log_paths) ? config.lightning.log_paths.map(String) : void 0,
21077
+ log: logLine
21078
+ });
21079
+ lightningWatch.start();
21080
+ let cloudSyncRef = null;
21081
+ new AlertDispatcher(bus, config, { cloudHealthy: () => cloudSyncRef?.healthy ?? false, log: logLine });
20123
21082
  const runsWorker = new RunsWorker(bus, {
20124
21083
  enabled: config.cloud?.enabled !== false && config.cloud?.runs === true,
20125
21084
  scanRoots: Array.isArray(config.cloud?.run_scan_paths) ? config.cloud.run_scan_paths.filter((p) => typeof p === "string") : [],
@@ -20141,14 +21100,15 @@ async function runDaemon() {
20141
21100
  cloudSync = new CloudSync({
20142
21101
  bus,
20143
21102
  version,
20144
- hostname: (0, import_node_os5.hostname)(),
21103
+ hostname: (0, import_node_os6.hostname)(),
20145
21104
  minSeverity,
20146
- spoolPath: (0, import_node_path24.join)(PATHS.stateDir, "cloud-spool.jsonl"),
21105
+ spoolPath: (0, import_node_path26.join)(PATHS.stateDir, "cloud-spool.jsonl"),
20147
21106
  log: logLine,
20148
21107
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
20149
21108
  runHardening: runHardeningChecks
20150
21109
  });
20151
21110
  cloudSync.start();
21111
+ cloudSyncRef = cloudSync;
20152
21112
  remediationConsumer = new RemediationConsumer(remediation, {
20153
21113
  log: logLine,
20154
21114
  restartDaemon,
@@ -20156,7 +21116,15 @@ async function runDaemon() {
20156
21116
  updateNow: () => autoUpdateRef ? autoUpdateRef.check({ force: true, restartDelayMs: 3e3 }) : Promise.resolve("updater not started")
20157
21117
  });
20158
21118
  remediationConsumer.start();
20159
- allowlistSync = new AllowlistSync(remediation, { log: logLine });
21119
+ const torPinned = typeof config.remediation?.block_tor_ssh === "boolean";
21120
+ allowlistSync = new AllowlistSync(remediation, {
21121
+ log: logLine,
21122
+ onOrgSettings: ({ block_tor_ssh }) => {
21123
+ if (torPinned || typeof block_tor_ssh !== "boolean" || block_tor_ssh === remediation.blockTorSsh) return;
21124
+ remediation.setBlockTorSsh(block_tor_ssh);
21125
+ logLine(`[ssh-intrusion] Tor SSH ban ${block_tor_ssh ? "ON" : "OFF"} (org setting from the dashboard)`);
21126
+ }
21127
+ });
20160
21128
  allowlistSync.start();
20161
21129
  const link = currentLink();
20162
21130
  logLine(link ? `[cloud] reporting as server ${link.serverId} (org ${link.orgId}), detections >= ${minSeverity}` : "[cloud] not linked; run `threatcrush login` and `threatcrush servers link` to report to the dashboard");
@@ -20167,8 +21135,8 @@ async function runDaemon() {
20167
21135
  const autoUpdate = autoUpdateRef = new AutoUpdate({
20168
21136
  version,
20169
21137
  settings: updateSettings(config.update),
20170
- pkgRoot: (0, import_node_path24.join)(__dirname, ".."),
20171
- statePath: (0, import_node_path24.join)(PATHS.stateDir, "auto-update.json"),
21138
+ pkgRoot: (0, import_node_path26.join)(__dirname, ".."),
21139
+ statePath: (0, import_node_path26.join)(PATHS.stateDir, "auto-update.json"),
20172
21140
  bus,
20173
21141
  log: logLine,
20174
21142
  restartDaemon
@@ -20223,6 +21191,14 @@ async function runDaemon() {
20223
21191
  privilegeWatch.stop();
20224
21192
  } catch {
20225
21193
  }
21194
+ try {
21195
+ sshIntrusion.stop();
21196
+ } catch {
21197
+ }
21198
+ try {
21199
+ lightningWatch.stop();
21200
+ } catch {
21201
+ }
20226
21202
  try {
20227
21203
  await ipc.stop();
20228
21204
  } catch {