@profullstack/threatcrush 0.13.61 → 0.13.63

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;
@@ -11001,7 +11053,6 @@ var DnsMonitor = class {
11001
11053
  var import_node_fs13 = require("fs");
11002
11054
  var import_node_path6 = require("path");
11003
11055
  var import_toml = __toESM(require_toml());
11004
- var DEFAULT_CONFIG_PATH = "/etc/threatcrush/threatcrushd.conf";
11005
11056
  var DEFAULT_CONFDIR = "/etc/threatcrush/threatcrushd.conf.d";
11006
11057
  var DEFAULT_CONFIG = {
11007
11058
  daemon: {
@@ -11023,34 +11074,49 @@ var DEFAULT_CONFIG = {
11023
11074
  config_dir: DEFAULT_CONFDIR
11024
11075
  }
11025
11076
  };
11026
- function loadConfig(configPath) {
11027
- const path = configPath || DEFAULT_CONFIG_PATH;
11028
- if (!(0, import_node_fs13.existsSync)(path)) {
11029
- return { ...DEFAULT_CONFIG };
11030
- }
11077
+ function parseConfigText(raw) {
11078
+ const parsed = import_toml.default.parse(raw);
11079
+ return {
11080
+ daemon: { ...DEFAULT_CONFIG.daemon, ...parsed.daemon },
11081
+ api: { ...DEFAULT_CONFIG.api, ...parsed.api },
11082
+ alerts: parsed.alerts || {},
11083
+ modules: { ...DEFAULT_CONFIG.modules, ...parsed.modules },
11084
+ remediation: parsed.remediation,
11085
+ detection: parsed.detection,
11086
+ cloud: parsed.cloud,
11087
+ watchdog: parsed.watchdog,
11088
+ update: parsed.update,
11089
+ threat_feeds: parsed.threat_feeds,
11090
+ privileged: parsed.privileged,
11091
+ lightning: parsed.lightning,
11092
+ storage: parsed.storage,
11093
+ // TOML's `[abuse-reporter]` parses to a hyphenated key; expose it under
11094
+ // the JS-friendly name the rest of the daemon reads.
11095
+ abuse_reporter: parsed["abuse-reporter"] ?? parsed.abuse_reporter,
11096
+ license: parsed.license
11097
+ };
11098
+ }
11099
+ function loadDaemonConfig(configPath, lastGoodPath) {
11100
+ if (!(0, import_node_fs13.existsSync)(configPath)) return { config: { ...DEFAULT_CONFIG }, usedLastGood: false };
11101
+ let raw = "";
11031
11102
  try {
11032
- const raw = (0, import_node_fs13.readFileSync)(path, "utf-8");
11033
- const parsed = import_toml.default.parse(raw);
11034
- return {
11035
- daemon: { ...DEFAULT_CONFIG.daemon, ...parsed.daemon },
11036
- api: { ...DEFAULT_CONFIG.api, ...parsed.api },
11037
- alerts: parsed.alerts || {},
11038
- modules: { ...DEFAULT_CONFIG.modules, ...parsed.modules },
11039
- remediation: parsed.remediation,
11040
- detection: parsed.detection,
11041
- cloud: parsed.cloud,
11042
- watchdog: parsed.watchdog,
11043
- update: parsed.update,
11044
- threat_feeds: parsed.threat_feeds,
11045
- privileged: parsed.privileged,
11046
- storage: parsed.storage,
11047
- // TOML's `[abuse-reporter]` parses to a hyphenated key; expose it under
11048
- // the JS-friendly name the rest of the daemon reads.
11049
- abuse_reporter: parsed["abuse-reporter"] ?? parsed.abuse_reporter,
11050
- license: parsed.license
11051
- };
11052
- } catch {
11053
- return { ...DEFAULT_CONFIG };
11103
+ raw = (0, import_node_fs13.readFileSync)(configPath, "utf-8");
11104
+ const config = parseConfigText(raw);
11105
+ try {
11106
+ (0, import_node_fs13.mkdirSync)((0, import_node_path6.dirname)(lastGoodPath), { recursive: true });
11107
+ (0, import_node_fs13.writeFileSync)(lastGoodPath, raw, { mode: 384 });
11108
+ } catch {
11109
+ }
11110
+ return { config, usedLastGood: false };
11111
+ } catch (err) {
11112
+ const error = `${configPath} is not valid TOML: ${err.message.split("\n")[0]}`;
11113
+ try {
11114
+ if ((0, import_node_fs13.existsSync)(lastGoodPath)) {
11115
+ return { config: parseConfigText((0, import_node_fs13.readFileSync)(lastGoodPath, "utf-8")), error, usedLastGood: true };
11116
+ }
11117
+ } catch {
11118
+ }
11119
+ return { config: { ...DEFAULT_CONFIG }, error, usedLastGood: false };
11054
11120
  }
11055
11121
  }
11056
11122
  function loadModuleConfigs(confDir) {
@@ -11478,11 +11544,55 @@ function pagerdutyChannel(config) {
11478
11544
  };
11479
11545
  }
11480
11546
 
11547
+ // src/daemon/alerts/smshub.ts
11548
+ var import_node_os2 = require("os");
11549
+ var SEVERITY_RANK4 = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
11550
+ var DEDUPE_MS = 10 * 6e4;
11551
+ var MAX_PER_HOUR = 6;
11552
+ function smshubText(event, host = (0, import_node_os2.hostname)()) {
11553
+ const evidence = event.details?.evidence?.message;
11554
+ const text = `ThreatCrush ${event.severity.toUpperCase()} on ${host}: ${event.message}${evidence && !event.message.includes(evidence) ? ` | ${evidence}` : ""}`;
11555
+ return text.replace(/\s+/g, " ").slice(0, 600);
11556
+ }
11557
+ function smshubChannel(config, opts = {}) {
11558
+ const sent = /* @__PURE__ */ new Map();
11559
+ const recent = [];
11560
+ const now = opts.now ?? Date.now;
11561
+ const doFetch = opts.fetchImpl ?? fetch;
11562
+ return async (event) => {
11563
+ const key = config.api_key || (config.api_key_env ? process.env[config.api_key_env] : void 0) || process.env.SMSHUB_ALERT_API_KEY;
11564
+ if (!key) return;
11565
+ if ((SEVERITY_RANK4[event.severity] ?? 0) < (SEVERITY_RANK4[config.min_severity ?? "critical"] ?? 4)) return;
11566
+ if (config.fallback_only !== false && opts.cloudHealthy?.()) return;
11567
+ const message = smshubText(event);
11568
+ const at = now();
11569
+ const dedupe2 = `${event.details?.rule_id ?? event.module}|${event.source_ip ?? ""}|${event.details?.fingerprint ?? ""}`;
11570
+ if (at - (sent.get(dedupe2) ?? 0) < DEDUPE_MS) return;
11571
+ while (recent.length && recent[0] < at - 36e5) recent.shift();
11572
+ if (recent.length >= MAX_PER_HOUR) return;
11573
+ sent.set(dedupe2, at);
11574
+ recent.push(at);
11575
+ const base = (config.url || "https://smshub.dev").replace(/\/$/, "");
11576
+ try {
11577
+ const res = await doFetch(`${base}/api/v1/alerts`, {
11578
+ method: "POST",
11579
+ headers: { "X-API-Key": key, "Content-Type": "application/json", "User-Agent": "threatcrush-daemon" },
11580
+ body: JSON.stringify({ message, severity: event.severity === "critical" ? "critical" : "warning", ...config.to ? { to: config.to } : {} }),
11581
+ signal: AbortSignal.timeout(15e3)
11582
+ });
11583
+ opts.log?.(`[alerts] smshub ${res.ok ? "paged" : `failed HTTP ${res.status}`}: ${message.slice(0, 160)}`);
11584
+ } catch (err) {
11585
+ opts.log?.(`[alerts] smshub failed: ${err.message}`);
11586
+ }
11587
+ };
11588
+ }
11589
+
11481
11590
  // src/daemon/alerts/index.ts
11482
11591
  var AlertDispatcher = class {
11483
- constructor(bus2, config) {
11592
+ constructor(bus2, config, hooks = {}) {
11484
11593
  this.bus = bus2;
11485
11594
  this.config = config;
11595
+ this.hooks = hooks;
11486
11596
  this.bindChannels();
11487
11597
  bus2.on("alert", (event) => {
11488
11598
  void this.dispatch(event);
@@ -11490,6 +11600,7 @@ var AlertDispatcher = class {
11490
11600
  }
11491
11601
  bus;
11492
11602
  config;
11603
+ hooks;
11493
11604
  channels = [];
11494
11605
  rateLimits = /* @__PURE__ */ new Map();
11495
11606
  bindChannels() {
@@ -11509,6 +11620,9 @@ var AlertDispatcher = class {
11509
11620
  if (name === "discord" && typeof cfg.webhook_url === "string") {
11510
11621
  this.channels.push(discordChannel(cfg));
11511
11622
  }
11623
+ if (name === "smshub") {
11624
+ this.channels.push(smshubChannel(cfg, this.hooks));
11625
+ }
11512
11626
  if (name === "pagerduty" && typeof cfg.routing_key === "string") {
11513
11627
  this.channels.push(pagerdutyChannel(cfg));
11514
11628
  }
@@ -11556,14 +11670,14 @@ function slackChannel(webhookUrl) {
11556
11670
  // src/daemon/workers/runs-worker.ts
11557
11671
  var import_promises = require("dns/promises");
11558
11672
  var import_node_fs20 = require("fs");
11559
- var import_node_net5 = require("net");
11673
+ var import_node_net6 = require("net");
11560
11674
  var import_node_path14 = require("path");
11561
11675
 
11562
11676
  // src/core/cli-config.ts
11563
11677
  var import_node_fs15 = require("fs");
11564
11678
  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");
11679
+ var import_node_os3 = require("os");
11680
+ var CLI_CONFIG_DIR = (0, import_node_path8.join)((0, import_node_os3.homedir)(), ".threatcrush");
11567
11681
  var CLI_CONFIG_PATH = (0, import_node_path8.join)(CLI_CONFIG_DIR, "config.json");
11568
11682
  function apiUrl() {
11569
11683
  return process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
@@ -11656,14 +11770,14 @@ async function cloudFetch(path, init = {}) {
11656
11770
 
11657
11771
  // src/core/cloud-events.ts
11658
11772
  var import_node_crypto3 = require("crypto");
11659
- var import_node_net4 = require("net");
11773
+ var import_node_net5 = require("net");
11660
11774
  function currentLink() {
11661
11775
  if (!hasSession()) return null;
11662
11776
  const cfg = readCliConfig();
11663
11777
  if (!cfg.server_id || !cfg.server_org_id) return null;
11664
11778
  return { serverId: cfg.server_id, orgId: cfg.server_org_id };
11665
11779
  }
11666
- var SEVERITY_RANK4 = {
11780
+ var SEVERITY_RANK5 = {
11667
11781
  info: 0,
11668
11782
  low: 1,
11669
11783
  medium: 2,
@@ -11723,7 +11837,7 @@ function detectionEvent(serverId, event) {
11723
11837
  title: title.slice(0, MAX_TITLE_CHARS) || event.module,
11724
11838
  rule_id: str(rule_id) ?? event.module,
11725
11839
  description: str(description),
11726
- source_ip: event.source_ip && (0, import_node_net4.isIP)(event.source_ip) ? event.source_ip : void 0,
11840
+ source_ip: event.source_ip && (0, import_node_net5.isIP)(event.source_ip) ? event.source_ip : void 0,
11727
11841
  username: str(username) ?? str(user),
11728
11842
  raw_metadata: trimMetadata({ module: event.module, category: event.category, ...rest }),
11729
11843
  detected_at: event.timestamp.toISOString()
@@ -12022,7 +12136,7 @@ var ansi_styles_default = ansiStyles;
12022
12136
 
12023
12137
  // ../../node_modules/.pnpm/chalk@6.0.1/node_modules/chalk/source/vendor/supports-color/index.js
12024
12138
  var import_node_process = __toESM(require("process"), 1);
12025
- var import_node_os3 = __toESM(require("os"), 1);
12139
+ var import_node_os4 = __toESM(require("os"), 1);
12026
12140
  var import_node_tty = __toESM(require("tty"), 1);
12027
12141
  function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
12028
12142
  const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
@@ -12097,7 +12211,7 @@ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
12097
12211
  return min;
12098
12212
  }
12099
12213
  if (import_node_process.default.platform === "win32") {
12100
- const osRelease = import_node_os3.default.release().split(".");
12214
+ const osRelease = import_node_os4.default.release().split(".");
12101
12215
  if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
12102
12216
  return Number(osRelease[2]) >= 14931 ? 3 : 2;
12103
12217
  }
@@ -12362,7 +12476,7 @@ var LEVEL_COLORS = {
12362
12476
  };
12363
12477
 
12364
12478
  // src/core/run-result.ts
12365
- var import_node_os4 = __toESM(require("os"));
12479
+ var import_node_os5 = __toESM(require("os"));
12366
12480
  function emptyCounts() {
12367
12481
  return { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
12368
12482
  }
@@ -12372,7 +12486,7 @@ function summarize(findings) {
12372
12486
  return counts;
12373
12487
  }
12374
12488
  function workerId() {
12375
- return `${import_node_os4.default.hostname()}/${process.pid}`;
12489
+ return `${import_node_os5.default.hostname()}/${process.pid}`;
12376
12490
  }
12377
12491
 
12378
12492
  // ../../packages/scan/src/node-rules.ts
@@ -16078,7 +16192,7 @@ var NOT_PUBLIC = [
16078
16192
  "ff00::/8"
16079
16193
  ];
16080
16194
  function isPublicTarget(ip) {
16081
- return (0, import_node_net5.isIP)(ip) !== 0 && !isProtected(ip, NOT_PUBLIC);
16195
+ return (0, import_node_net6.isIP)(ip) !== 0 && !isProtected(ip, NOT_PUBLIC);
16082
16196
  }
16083
16197
  async function pentestTargetError(rawUrl, resolveHost = async (h) => (await (0, import_promises.lookup)(h, { all: true })).map((a) => a.address)) {
16084
16198
  let url;
@@ -16091,7 +16205,7 @@ async function pentestTargetError(rawUrl, resolveHost = async (h) => (await (0,
16091
16205
  const host = url.hostname.replace(/^\[|\]$/g, "");
16092
16206
  let addresses;
16093
16207
  try {
16094
- addresses = (0, import_node_net5.isIP)(host) ? [host] : await resolveHost(host);
16208
+ addresses = (0, import_node_net6.isIP)(host) ? [host] : await resolveHost(host);
16095
16209
  } catch (err) {
16096
16210
  return `cannot resolve ${host}: ${err.message}`;
16097
16211
  }
@@ -16415,6 +16529,7 @@ var CloudSync = class {
16415
16529
  retryAt = 0;
16416
16530
  link = null;
16417
16531
  lastProblem = "";
16532
+ lastOkAt = 0;
16418
16533
  onEvent = (event) => this.capture(event);
16419
16534
  start() {
16420
16535
  this.link = currentLink();
@@ -16447,6 +16562,10 @@ var CloudSync = class {
16447
16562
  get queued() {
16448
16563
  return this.spool.size;
16449
16564
  }
16565
+ /** Linked, and the dashboard accepted an upload or heartbeat in the last 3 minutes. */
16566
+ get healthy() {
16567
+ return !!this.link && !this.lastProblem && Date.now() - this.lastOkAt < 18e4;
16568
+ }
16450
16569
  /** Queue hardening results for upload (the CLI posts its own directly). */
16451
16570
  enqueueFindings(results) {
16452
16571
  const link = this.refreshLink();
@@ -16471,7 +16590,7 @@ var CloudSync = class {
16471
16590
  let out = null;
16472
16591
  if (event.module === "firewall-rules") {
16473
16592
  out = remediationEvent(link.serverId, event);
16474
- } 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]) {
16593
+ } 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]) {
16475
16594
  out = detectionEvent(link.serverId, event);
16476
16595
  }
16477
16596
  if (!out) return;
@@ -16519,6 +16638,7 @@ var CloudSync = class {
16519
16638
  this.backoffMs = 0;
16520
16639
  this.retryAt = 0;
16521
16640
  this.lastProblem = "";
16641
+ this.lastOkAt = Date.now();
16522
16642
  return "sent";
16523
16643
  }
16524
16644
  if (res.status === 401) {
@@ -16563,6 +16683,7 @@ var CloudSync = class {
16563
16683
  };
16564
16684
  try {
16565
16685
  const res = await cloudFetch("/api/ingest", { method: "POST", body: JSON.stringify({ events: [event] }) });
16686
+ if (res.ok) this.lastOkAt = Date.now();
16566
16687
  if (res.ok && this.retryAt > 0) {
16567
16688
  this.retryAt = 0;
16568
16689
  void this.flush();
@@ -16586,7 +16707,7 @@ var CloudSync = class {
16586
16707
  var import_node_crypto5 = require("crypto");
16587
16708
 
16588
16709
  // src/daemon/workers/abuse-evidence.ts
16589
- var import_node_net6 = require("net");
16710
+ var import_node_net7 = require("net");
16590
16711
  var NEVER_REPORT_RANGES = [
16591
16712
  ...DEFAULT_PROTECTED,
16592
16713
  "100.64.0.0/10",
@@ -16662,7 +16783,7 @@ function summarizeEvidence(events) {
16662
16783
  };
16663
16784
  }
16664
16785
  function isReportable(ip, evidence, config, now = Date.now()) {
16665
- if ((0, import_node_net6.isIP)(ip) === 0) return { reportable: false, reason: "not an IP address" };
16786
+ if ((0, import_node_net7.isIP)(ip) === 0) return { reportable: false, reason: "not an IP address" };
16666
16787
  if (isProtected(ip, config.neverReport)) {
16667
16788
  return { reportable: false, reason: "address is in a never-report range (private/CGNAT/reserved/allowlisted)" };
16668
16789
  }
@@ -16993,13 +17114,13 @@ var AbuseReporter = class {
16993
17114
  };
16994
17115
 
16995
17116
  // src/daemon/workers/remediation-consumer.ts
16996
- var import_node_net8 = require("net");
17117
+ var import_node_net9 = require("net");
16997
17118
 
16998
17119
  // src/daemon/workers/allowlist-sync.ts
16999
- var import_node_net7 = require("net");
17120
+ var import_node_net8 = require("net");
17000
17121
  function isAddressOrCidr(value) {
17001
17122
  const [network, prefix, extra] = value.split("/");
17002
- const family = (0, import_node_net7.isIP)(network);
17123
+ const family = (0, import_node_net8.isIP)(network);
17003
17124
  if (family === 0 || extra !== void 0) return false;
17004
17125
  if (prefix === void 0) return true;
17005
17126
  if (!/^\d{1,3}$/.test(prefix)) return false;
@@ -17010,7 +17131,7 @@ function isCloudAllowEntry(value) {
17010
17131
  if (!isAddressOrCidr(value)) return false;
17011
17132
  const [network, prefix] = value.split("/");
17012
17133
  if (prefix === void 0) return true;
17013
- return Number(prefix) >= CLOUD_MIN_PREFIX[(0, import_node_net7.isIP)(network)];
17134
+ return Number(prefix) >= CLOUD_MIN_PREFIX[(0, import_node_net8.isIP)(network)];
17014
17135
  }
17015
17136
  var AllowlistSync = class {
17016
17137
  constructor(manager, opts) {
@@ -17033,6 +17154,17 @@ var AllowlistSync = class {
17033
17154
  async sync() {
17034
17155
  const link = currentLink();
17035
17156
  if (!link) return;
17157
+ if (this.opts.onOrgSettings) {
17158
+ try {
17159
+ const res = await cloudFetch(`/api/orgs/${link.orgId}`);
17160
+ if (res.ok) {
17161
+ const data = await res.json();
17162
+ const v = data.organization?.block_tor_ssh;
17163
+ if (typeof v === "boolean") this.opts.onOrgSettings({ block_tor_ssh: v });
17164
+ }
17165
+ } catch {
17166
+ }
17167
+ }
17036
17168
  let entries;
17037
17169
  try {
17038
17170
  const res = await cloudFetch(`/api/orgs/${link.orgId}/allowlists`);
@@ -17048,7 +17180,7 @@ var AllowlistSync = class {
17048
17180
  if (entry.type !== "ip" && entry.type !== "cidr") continue;
17049
17181
  const value = String(entry.value ?? "").trim();
17050
17182
  if (isCloudAllowEntry(value)) wanted.add(value);
17051
- 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])]})`);
17183
+ 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])]})`);
17052
17184
  }
17053
17185
  const added2 = [];
17054
17186
  const protectedNow = new Set(this.manager.getProtected());
@@ -17156,7 +17288,7 @@ var RemediationConsumer = class {
17156
17288
  try {
17157
17289
  switch (action.action_type) {
17158
17290
  case "block": {
17159
- if ((0, import_node_net8.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
17291
+ if ((0, import_node_net9.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
17160
17292
  let ttlSeconds = this.manager.status().max_ban_seconds;
17161
17293
  if (action.expires_at) {
17162
17294
  const until = Date.parse(action.expires_at);
@@ -17175,7 +17307,7 @@ var RemediationConsumer = class {
17175
17307
  return { status: "executed", dry_run: result.entry?.dry_run === true, executed_at };
17176
17308
  }
17177
17309
  case "unblock": {
17178
- if ((0, import_node_net8.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
17310
+ if ((0, import_node_net9.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
17179
17311
  const wasBanned = this.manager.getBlocklist().some((b) => b.ip === target);
17180
17312
  const result = await this.manager.unban(target, {
17181
17313
  forget: true,
@@ -17479,7 +17611,7 @@ var AutoUpdate = class {
17479
17611
  var import_node_child_process6 = require("child_process");
17480
17612
  var import_node_fs24 = require("fs");
17481
17613
  var import_node_path18 = require("path");
17482
- var import_node_net9 = require("net");
17614
+ var import_node_net10 = require("net");
17483
17615
  var EGRESS_TABLE = "threatcrush_egress";
17484
17616
  var DEFAULT_REFRESH_MS = 36e5;
17485
17617
  var POLL_MS = 15e3;
@@ -17497,8 +17629,8 @@ function threatFeedSettings(section) {
17497
17629
  };
17498
17630
  }
17499
17631
  function egressRuleset(ips) {
17500
- const v4 = ips.filter((ip) => (0, import_node_net9.isIP)(ip) === 4);
17501
- const v6 = ips.filter((ip) => (0, import_node_net9.isIP)(ip) === 6);
17632
+ const v4 = ips.filter((ip) => (0, import_node_net10.isIP)(ip) === 4);
17633
+ const v6 = ips.filter((ip) => (0, import_node_net10.isIP)(ip) === 6);
17502
17634
  const set = (name, type, items) => ` set ${name} { type ${type};${items.length ? ` elements = { ${items.join(", ")} }` : ""} }`;
17503
17635
  const chain = (name, hook) => [
17504
17636
  ` chain ${name} {`,
@@ -17523,7 +17655,7 @@ function splitAddr(addr) {
17523
17655
  const m = /^\[?(.+?)\]?:(\d+|\*)$/.exec(addr);
17524
17656
  if (!m) return null;
17525
17657
  const ip = m[1].replace(/%.*$/, "").replace(/^::ffff:/i, "");
17526
- return (0, import_node_net9.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
17658
+ return (0, import_node_net10.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
17527
17659
  }
17528
17660
  function parseSs(text) {
17529
17661
  const out = [];
@@ -17911,7 +18043,42 @@ function parseSudoMessage(message) {
17911
18043
 
17912
18044
  // src/daemon/workers/privilege-watch.ts
17913
18045
  function privilegeSettings(section) {
17914
- return { enabled: section?.enabled !== false, geo: section?.geo !== false, pollMs: 6e4 };
18046
+ return {
18047
+ enabled: section?.enabled !== false,
18048
+ geo: section?.geo !== false,
18049
+ pollMs: 6e4,
18050
+ expectedKeys: Array.isArray(section?.expected_keys) ? section.expected_keys.map(String).filter(Boolean) : [],
18051
+ watchFiles: true
18052
+ };
18053
+ }
18054
+ function keyIsExpected(fingerprint, comment, expected) {
18055
+ return expected.some((pattern) => {
18056
+ if (pattern.startsWith("SHA256:")) return pattern === fingerprint;
18057
+ const re = new RegExp(`^${pattern.split("*").map((p) => p.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`, "i");
18058
+ return re.test(comment);
18059
+ });
18060
+ }
18061
+ var SELFTEST_KEY_COMMENT = "threatcrush-selftest";
18062
+ function classifyKeyAddition(change, expected) {
18063
+ if (change.details.rule_id !== "priv-authorized-key-added") return change;
18064
+ const fp = String(change.details.fingerprint ?? "");
18065
+ const comment = String(change.details.comment ?? "");
18066
+ const account = String(change.details.account ?? "?");
18067
+ if (comment.includes(SELFTEST_KEY_COMMENT)) {
18068
+ return {
18069
+ severity: "critical",
18070
+ message: `[TEST] ThreatCrush self-test: new SSH key for ${account} detected (${fp}, ${comment}). This is a test, nothing is wrong.`,
18071
+ details: { ...change.details, rule_id: "priv-authorized-key-selftest", selftest: true }
18072
+ };
18073
+ }
18074
+ if (keyIsExpected(fp, comment, expected)) {
18075
+ return { ...change, severity: "high", details: { ...change.details, expected: true } };
18076
+ }
18077
+ return {
18078
+ severity: "critical",
18079
+ 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`,
18080
+ details: { ...change.details, expected: false }
18081
+ };
17915
18082
  }
17916
18083
  var COUNTRY_NAMES = new Intl.DisplayNames(["en"], { type: "region" });
17917
18084
  function countryName(code) {
@@ -18009,6 +18176,8 @@ var PrivilegeWatch = class {
18009
18176
  run;
18010
18177
  now;
18011
18178
  warnedUnreadable = false;
18179
+ watchers = /* @__PURE__ */ new Map();
18180
+ debounce = null;
18012
18181
  onEvent = (event) => {
18013
18182
  void this.checkLogin(event);
18014
18183
  };
@@ -18023,9 +18192,11 @@ var PrivilegeWatch = class {
18023
18192
  this.opts.bus.on("event", this.onEvent);
18024
18193
  void this.backfillLogins();
18025
18194
  }
18195
+ if (this.opts.settings.watchFiles) this.watchKeyDirs();
18026
18196
  const timer = setInterval(() => {
18027
18197
  this.checkSnapshot();
18028
18198
  this.readSudoLedger();
18199
+ if (this.opts.settings.watchFiles) this.watchKeyDirs();
18029
18200
  }, this.opts.settings.pollMs);
18030
18201
  timer.unref?.();
18031
18202
  this.timers.push(timer);
@@ -18033,8 +18204,55 @@ var PrivilegeWatch = class {
18033
18204
  stop() {
18034
18205
  for (const t of this.timers) clearInterval(t);
18035
18206
  this.timers = [];
18207
+ for (const w of this.watchers.values()) {
18208
+ try {
18209
+ w.close();
18210
+ } catch {
18211
+ }
18212
+ }
18213
+ this.watchers.clear();
18214
+ if (this.debounce) clearTimeout(this.debounce);
18036
18215
  this.opts.bus.off("event", this.onEvent);
18037
18216
  }
18217
+ /**
18218
+ * inotify on every login account's ~/.ssh (and /root/.ssh): a write there
18219
+ * re-checks the snapshot within a second, not at the next minute's poll.
18220
+ * Re-run each poll so a directory created later is picked up.
18221
+ */
18222
+ watchKeyDirs() {
18223
+ const dirs = /* @__PURE__ */ new Set();
18224
+ for (const line of (this.io.readFile("/etc/passwd") ?? "").split("\n")) {
18225
+ const f = line.split(":");
18226
+ if (f.length < 7) continue;
18227
+ const uid = Number(f[2]);
18228
+ const home = f[5];
18229
+ if (!home || home === "/" || uid !== 0 && /(nologin|\/false)$/.test(f[6].trim())) continue;
18230
+ dirs.add(`${home.replace(/\/$/, "")}/.ssh`);
18231
+ }
18232
+ for (const dir of dirs) {
18233
+ if (this.watchers.has(dir) || !this.io.exists(dir)) continue;
18234
+ try {
18235
+ const w = (0, import_node_fs25.watch)(dir, { persistent: false }, (_type2, name) => {
18236
+ if (name && !String(name).startsWith("authorized_keys")) return;
18237
+ if (this.debounce) clearTimeout(this.debounce);
18238
+ this.debounce = setTimeout(() => {
18239
+ this.debounce = null;
18240
+ this.checkSnapshot();
18241
+ }, 750);
18242
+ this.debounce.unref?.();
18243
+ });
18244
+ w.on("error", () => {
18245
+ try {
18246
+ w.close();
18247
+ } catch {
18248
+ }
18249
+ this.watchers.delete(dir);
18250
+ });
18251
+ this.watchers.set(dir, w);
18252
+ } catch {
18253
+ }
18254
+ }
18255
+ }
18038
18256
  emit(severity, message, details) {
18039
18257
  const event = { timestamp: this.now(), module: "privileged-access", category: "auth", severity, message, details };
18040
18258
  try {
@@ -18054,7 +18272,16 @@ var PrivilegeWatch = class {
18054
18272
  const keys = Object.values(next.keys).reduce((n, k) => n + Object.keys(k).length, 0);
18055
18273
  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)`);
18056
18274
  } else {
18057
- for (const change of diffSnapshots(prev, next)) this.emit(change.severity, change.message, change.details);
18275
+ for (const raw of diffSnapshots(prev, next)) {
18276
+ const change = classifyKeyAddition(raw, this.opts.settings.expectedKeys ?? []);
18277
+ if (change.details.rule_id === "priv-authorized-key-added" || change.details.rule_id === "priv-authorized-key-selftest") {
18278
+ this.opts.log(`[privileged] ${change.severity.toUpperCase()} ${change.message}`);
18279
+ }
18280
+ this.emit(change.severity, change.message, {
18281
+ ...change.details,
18282
+ evidence: { at: this.now().toISOString(), module: "privileged-access", message: change.message.slice(0, 500) }
18283
+ });
18284
+ }
18058
18285
  }
18059
18286
  try {
18060
18287
  writeJson(this.opts.snapshotPath, next);
@@ -18168,6 +18395,636 @@ var PrivilegeWatch = class {
18168
18395
  }
18169
18396
  };
18170
18397
 
18398
+ // src/daemon/workers/ssh-intrusion.ts
18399
+ var import_node_fs26 = require("fs");
18400
+ var import_node_path20 = require("path");
18401
+ var import_node_child_process8 = require("child_process");
18402
+
18403
+ // src/core/asn.ts
18404
+ var import_node_dns = require("dns");
18405
+ var import_node_net11 = require("net");
18406
+ var CI_ASNS = /* @__PURE__ */ new Set([8075, 36459, 8068, 8069, 12076]);
18407
+ var HOSTING_ASNS = /* @__PURE__ */ new Set([
18408
+ 15169,
18409
+ 396982,
18410
+ 19527,
18411
+ // Google, Google Cloud
18412
+ 16509,
18413
+ 14618,
18414
+ // Amazon / AWS
18415
+ 16276,
18416
+ // OVH
18417
+ 24940,
18418
+ 213230,
18419
+ // Hetzner
18420
+ 14061,
18421
+ // DigitalOcean
18422
+ 63949,
18423
+ // Linode / Akamai
18424
+ 20473,
18425
+ // Vultr (Choopa)
18426
+ 12876,
18427
+ // Scaleway
18428
+ 51167,
18429
+ // Contabo
18430
+ 31898,
18431
+ // Oracle Cloud
18432
+ 45102,
18433
+ // Alibaba
18434
+ 132203,
18435
+ 45090,
18436
+ // Tencent
18437
+ 36352,
18438
+ // ColoCrossing
18439
+ 53667,
18440
+ // FranTech / BuyVM
18441
+ 197540,
18442
+ // netcup
18443
+ 9009,
18444
+ // M247
18445
+ 60068,
18446
+ // Datacamp / CDN77
18447
+ 212238,
18448
+ // Datacamp
18449
+ 202425,
18450
+ // IP Volume
18451
+ 210644,
18452
+ // Aeza
18453
+ 49981,
18454
+ // WorldStream
18455
+ 62240,
18456
+ // Clouvider
18457
+ 136907,
18458
+ // Huawei Cloud
18459
+ 8100,
18460
+ // QuadraNet
18461
+ 46606,
18462
+ // Unified Layer
18463
+ 29802,
18464
+ // HVC
18465
+ 40021,
18466
+ // Contabo US / Nubes
18467
+ 398324,
18468
+ 399629
18469
+ // Censys and friends
18470
+ ]);
18471
+ var VPN_ASNS = /* @__PURE__ */ new Set([
18472
+ 9009,
18473
+ // M247 (most commercial VPN exits)
18474
+ 212238,
18475
+ 60068,
18476
+ // Datacamp (NordVPN, Proton, ...)
18477
+ 209854,
18478
+ // Surfshark
18479
+ 39351,
18480
+ // 31173 Services (Mullvad)
18481
+ 136787,
18482
+ // TEFINCOM (NordVPN)
18483
+ 147049
18484
+ // PacketHub (NordVPN)
18485
+ ]);
18486
+ 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;
18487
+ var VPN_NAME = /\bvpn\b|proton|mullvad|nordvpn|surfshark|expressvpn|private internet access|tefincom|packethub|31173 services|anonymi[sz]|privacy|proxy/i;
18488
+ function classifyAsn(info) {
18489
+ if (!info) return "unknown";
18490
+ if (CI_ASNS.has(info.asn)) return "ci";
18491
+ if (VPN_ASNS.has(info.asn) || VPN_NAME.test(info.name)) return "vpn";
18492
+ if (HOSTING_ASNS.has(info.asn) || HOSTING_NAME.test(info.name)) return "hosting";
18493
+ return "unknown";
18494
+ }
18495
+ function cymruOriginName(ip) {
18496
+ const bytes = ipToBytes(ip);
18497
+ if (!bytes) return null;
18498
+ if (bytes.length === 4) return `${[...bytes].reverse().join(".")}.origin.asn.cymru.com`;
18499
+ const nibbles = [];
18500
+ for (const b of bytes) nibbles.push((b >> 4).toString(16), (b & 15).toString(16));
18501
+ return `${nibbles.reverse().join(".")}.origin6.asn.cymru.com`;
18502
+ }
18503
+ function parseCymruOrigin(txt) {
18504
+ const fields = txt.split("|").map((f) => f.trim());
18505
+ const asn = Number(fields[0]?.split(/\s+/)[0]);
18506
+ if (!Number.isInteger(asn) || asn <= 0) return null;
18507
+ return { asn, prefix: fields[1] || void 0, country: /^[A-Z]{2}$/.test(fields[2] ?? "") ? fields[2] : void 0 };
18508
+ }
18509
+ function parseCymruName(txt) {
18510
+ const fields = txt.split("|").map((f) => f.trim());
18511
+ return (fields[4] ?? "").slice(0, 120);
18512
+ }
18513
+ var AsnLookup = class {
18514
+ constructor(resolveTxt = (name) => import_node_dns.promises.resolveTxt(name), ttlMs = 24 * 36e5, now = Date.now) {
18515
+ this.resolveTxt = resolveTxt;
18516
+ this.ttlMs = ttlMs;
18517
+ this.now = now;
18518
+ }
18519
+ resolveTxt;
18520
+ ttlMs;
18521
+ now;
18522
+ cache = /* @__PURE__ */ new Map();
18523
+ async lookup(ip) {
18524
+ if ((0, import_node_net11.isIP)(ip) === 0) return null;
18525
+ const hit = this.cache.get(ip);
18526
+ if (hit && this.now() - hit.at < this.ttlMs) return hit.info;
18527
+ let info = null;
18528
+ try {
18529
+ const origin = cymruOriginName(ip);
18530
+ if (origin) {
18531
+ const rec = await withTimeout(this.resolveTxt(origin), 5e3);
18532
+ const parsed = parseCymruOrigin(rec.map((r) => r.join("")).find(Boolean) ?? "");
18533
+ if (parsed) {
18534
+ let name = "";
18535
+ try {
18536
+ const names = await withTimeout(this.resolveTxt(`AS${parsed.asn}.asn.cymru.com`), 5e3);
18537
+ name = parseCymruName(names.map((r) => r.join("")).find(Boolean) ?? "");
18538
+ } catch {
18539
+ }
18540
+ info = { asn: parsed.asn, name, country: parsed.country, prefix: parsed.prefix };
18541
+ }
18542
+ }
18543
+ } catch {
18544
+ info = null;
18545
+ }
18546
+ if (this.cache.size > 5e3) this.cache.clear();
18547
+ this.cache.set(ip, { at: this.now(), info });
18548
+ return info;
18549
+ }
18550
+ };
18551
+ function withTimeout(p, ms) {
18552
+ return new Promise((resolve4, reject) => {
18553
+ const t = setTimeout(() => reject(new Error("timeout")), ms);
18554
+ p.then((v) => {
18555
+ clearTimeout(t);
18556
+ resolve4(v);
18557
+ }, (e) => {
18558
+ clearTimeout(t);
18559
+ reject(e);
18560
+ });
18561
+ });
18562
+ }
18563
+ function describeNetwork(info, kind) {
18564
+ if (kind === "tor") return info ? `Tor exit, AS${info.asn} ${info.name}`.trim() : "Tor exit";
18565
+ if (!info) return `unknown network (${kind})`;
18566
+ return `AS${info.asn}${info.name ? ` ${info.name}` : ""} (${kind === "unknown" ? "ISP or unclassified" : kind})`;
18567
+ }
18568
+
18569
+ // src/daemon/workers/ssh-intrusion.ts
18570
+ var TOR_REALERT_MS = 10 * 6e4;
18571
+ var HOSTING_REALERT_MS = 24 * 36e5;
18572
+ var TOR_REMEDIATION = {
18573
+ action: "block",
18574
+ description: "Ban the Tor exit at once, for max_ban, even in dry_run and even after a successful login",
18575
+ enforce_in_dry_run: true,
18576
+ ban_on_login: true,
18577
+ override_operator_protection: true,
18578
+ max_ban: true
18579
+ };
18580
+ function parseKeyLoginsByFingerprint(text) {
18581
+ const out = /* @__PURE__ */ new Map();
18582
+ for (const line of text.split("\n")) {
18583
+ const m = /^(\d+(?:\.\d+)?)\s.*Accepted publickey for \S+ from (\S+) port \d+ \S+?:\s+\S+\s+(SHA256:[A-Za-z0-9+/=]+)/.exec(line);
18584
+ if (!m) continue;
18585
+ const at = Math.round(Number(m[1]) * 1e3);
18586
+ const ips = out.get(m[3]) ?? /* @__PURE__ */ new Map();
18587
+ if (at > (ips.get(m[2]) ?? 0)) ips.set(m[2], at);
18588
+ out.set(m[3], ips);
18589
+ }
18590
+ return out;
18591
+ }
18592
+ function readJson2(path) {
18593
+ try {
18594
+ return JSON.parse((0, import_node_fs26.readFileSync)(path, "utf-8"));
18595
+ } catch {
18596
+ return null;
18597
+ }
18598
+ }
18599
+ function writeJson2(path, value) {
18600
+ (0, import_node_fs26.mkdirSync)((0, import_node_path20.dirname)(path), { recursive: true });
18601
+ (0, import_node_fs26.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
18602
+ (0, import_node_fs26.renameSync)(`${path}.tmp`, path);
18603
+ }
18604
+ var fsIO2 = {
18605
+ readFile: (p) => {
18606
+ try {
18607
+ return (0, import_node_fs26.readFileSync)(p, "utf-8");
18608
+ } catch {
18609
+ return null;
18610
+ }
18611
+ },
18612
+ readDir: (p) => {
18613
+ try {
18614
+ return (0, import_node_fs26.readdirSync)(p);
18615
+ } catch {
18616
+ return null;
18617
+ }
18618
+ },
18619
+ exists: (p) => (0, import_node_fs26.existsSync)(p)
18620
+ };
18621
+ function defaultRun4(cmd, args) {
18622
+ const res = (0, import_node_child_process8.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
18623
+ return res.status === 0 ? res.stdout : null;
18624
+ }
18625
+ var SshIntrusionWatch = class {
18626
+ constructor(opts) {
18627
+ this.opts = opts;
18628
+ this.now = opts.now ?? Date.now;
18629
+ this.asn = opts.asn ?? new AsnLookup();
18630
+ this.io = opts.io ?? fsIO2;
18631
+ this.run = opts.run ?? defaultRun4;
18632
+ }
18633
+ opts;
18634
+ now;
18635
+ asn;
18636
+ io;
18637
+ run;
18638
+ torAlerted = /* @__PURE__ */ new Map();
18639
+ hostingAlerted = /* @__PURE__ */ new Map();
18640
+ history = {};
18641
+ keyComments = { at: 0, byFp: /* @__PURE__ */ new Map() };
18642
+ baselineReady = false;
18643
+ onLine = (line) => {
18644
+ this.checkTorLine(line);
18645
+ };
18646
+ onEvent = (event) => {
18647
+ void this.checkKeyLogin(event);
18648
+ };
18649
+ start() {
18650
+ this.opts.tor.start();
18651
+ this.opts.manager.setTorExitCheck((ip) => this.opts.tor.has(ip));
18652
+ this.opts.bus.on("sshd", this.onLine);
18653
+ if (this.opts.keyLoginWatch !== false) {
18654
+ this.opts.bus.on("event", this.onEvent);
18655
+ this.loadHistory();
18656
+ }
18657
+ 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"}`);
18658
+ }
18659
+ stop() {
18660
+ this.opts.tor.stop();
18661
+ this.opts.bus.off("sshd", this.onLine);
18662
+ this.opts.bus.off("event", this.onEvent);
18663
+ }
18664
+ emit(event) {
18665
+ try {
18666
+ insertEvent(event);
18667
+ } catch {
18668
+ }
18669
+ this.opts.bus.publish(event);
18670
+ }
18671
+ /** One sshd line: a Tor exit anywhere in it is an intrusion attempt. */
18672
+ checkTorLine(line) {
18673
+ const ip = line.ip;
18674
+ if (!this.opts.tor.has(ip)) return false;
18675
+ if (isProtected(ip, DEFAULT_PROTECTED) || this.opts.manager.isFleetAddress(ip)) return false;
18676
+ const at = this.now();
18677
+ const last = this.torAlerted.get(ip) ?? 0;
18678
+ const accepted = /Accepted \S+ for /.test(line.message);
18679
+ if (!accepted && at - last < TOR_REALERT_MS) return false;
18680
+ this.torAlerted.set(ip, at);
18681
+ if (this.torAlerted.size > 1e4) this.torAlerted.clear();
18682
+ const ban = this.opts.manager.blockTorSsh;
18683
+ const user = /for (?:invalid user )?(\S+) from/.exec(line.message)?.[1];
18684
+ const what = accepted ? `LOGGED IN${user ? ` as ${user}` : ""}` : "connection attempt";
18685
+ this.emit({
18686
+ timestamp: line.timestamp,
18687
+ module: "ssh-intrusion",
18688
+ category: "auth",
18689
+ severity: accepted || ban ? "critical" : "high",
18690
+ message: `SSH from Tor exit ${ip} (${what})${ban ? ": banned" : ""}`,
18691
+ source_ip: ip,
18692
+ details: {
18693
+ rule_id: "ssh-from-tor",
18694
+ description: "Nobody we operate for uses SSH through Tor. A Tor login means a stolen key or password.",
18695
+ tor_exit: true,
18696
+ accepted,
18697
+ ...user ? { ssh_user: user } : {},
18698
+ ...ban ? { remediation: TOR_REMEDIATION } : {},
18699
+ evidence: { at: line.timestamp.toISOString(), module: "ssh-guard", message: line.raw.slice(0, 500) }
18700
+ }
18701
+ });
18702
+ return true;
18703
+ }
18704
+ loadHistory() {
18705
+ const saved = readJson2(this.opts.historyPath);
18706
+ if (saved) {
18707
+ this.history = saved;
18708
+ this.baselineReady = true;
18709
+ return;
18710
+ }
18711
+ const out = this.run("journalctl", ["_COMM=sshd", "_COMM=sshd-session", "--since=-30d", "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"]);
18712
+ const iso = (ms) => new Date(ms).toISOString();
18713
+ let pairs = 0;
18714
+ for (const [fp, ips] of parseKeyLoginsByFingerprint(out ?? "")) {
18715
+ for (const [ip, at] of ips) {
18716
+ if (this.opts.tor.has(ip)) continue;
18717
+ (this.history[fp] ??= {})[ip] = { first: iso(at), last: iso(at), count: 1 };
18718
+ pairs++;
18719
+ }
18720
+ }
18721
+ this.save();
18722
+ this.baselineReady = true;
18723
+ 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)`);
18724
+ }
18725
+ save() {
18726
+ try {
18727
+ writeJson2(this.opts.historyPath, this.history);
18728
+ } catch (err) {
18729
+ this.opts.log(`[ssh-intrusion] could not save key-login history: ${err.message}`);
18730
+ }
18731
+ }
18732
+ /** Which account a key is authorized for, and its comment (cached 5 minutes). */
18733
+ keyInfo(fp) {
18734
+ if (this.now() - this.keyComments.at > 3e5) {
18735
+ const snap = takeSnapshot(this.io);
18736
+ const byFp = /* @__PURE__ */ new Map();
18737
+ for (const [user, keys] of Object.entries(snap.keys)) {
18738
+ for (const [f, k] of Object.entries(keys)) if (!byFp.has(f)) byFp.set(f, { user, comment: k.comment });
18739
+ }
18740
+ this.keyComments = { at: this.now(), byFp };
18741
+ }
18742
+ return this.keyComments.byFp.get(fp) ?? null;
18743
+ }
18744
+ async checkKeyLogin(event) {
18745
+ if (event.module !== "ssh-guard" || !this.baselineReady) return null;
18746
+ const fp = event.details?.fingerprint;
18747
+ const ip = event.source_ip;
18748
+ if (typeof fp !== "string" || !ip || isProtected(ip, DEFAULT_PROTECTED)) return null;
18749
+ const seen = this.history[fp] ?? {};
18750
+ const isNew = !seen[ip];
18751
+ const nowIso = new Date(this.now()).toISOString();
18752
+ seen[ip] = { first: seen[ip]?.first ?? nowIso, last: nowIso, count: (seen[ip]?.count ?? 0) + 1 };
18753
+ this.history[fp] = seen;
18754
+ this.save();
18755
+ const tor = this.opts.tor.has(ip);
18756
+ const fleet = this.opts.manager.isFleetAddress(ip);
18757
+ if (fleet) return null;
18758
+ const key = this.keyInfo(fp);
18759
+ const automation = key ? isAutomationKeyComment(key.comment) : false;
18760
+ let info = null;
18761
+ try {
18762
+ info = await this.asn.lookup(ip);
18763
+ } catch {
18764
+ info = null;
18765
+ }
18766
+ const kind = tor ? "tor" : classifyAsn(info);
18767
+ const network = describeNetwork(info, kind);
18768
+ const user = typeof event.details?.ssh_user === "string" ? event.details.ssh_user : /accepted for (\S+)/i.exec(event.message)?.[1] ?? "unknown";
18769
+ const keyLabel = `${fp}${key?.comment ? ` (${key.comment})` : ""}`;
18770
+ const known = Object.keys(seen).filter((a) => a !== ip).length;
18771
+ const anonymous = kind === "hosting" || kind === "vpn" || kind === "tor";
18772
+ const hostingHit = !automation && anonymous;
18773
+ const pairKey = `${fp}|${ip}`;
18774
+ const hostingDue = hostingHit && this.now() - (this.hostingAlerted.get(pairKey) ?? 0) >= HOSTING_REALERT_MS;
18775
+ if (!isNew && !hostingDue) return null;
18776
+ if (tor && this.opts.manager.blockTorSsh) return null;
18777
+ let ruleId;
18778
+ let severity;
18779
+ let message;
18780
+ if (hostingHit) {
18781
+ this.hostingAlerted.set(pairKey, this.now());
18782
+ ruleId = "ssh-human-key-hosting-login";
18783
+ severity = "high";
18784
+ 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" : ""}`;
18785
+ } else if (automation && kind === "ci") {
18786
+ ruleId = "ssh-key-new-ip";
18787
+ severity = "info";
18788
+ message = `SSH deploy key logged in as ${user} from a new CI address ${ip} (${network}), expected`;
18789
+ } else {
18790
+ ruleId = "ssh-key-new-ip";
18791
+ severity = "high";
18792
+ message = `SSH key logged in as ${user} from an address it never used: ${ip}, ${network}${known ? `; ${known} address(es) known for this key` : ""}`;
18793
+ }
18794
+ const out = {
18795
+ timestamp: event.timestamp,
18796
+ module: "ssh-intrusion",
18797
+ category: "auth",
18798
+ severity,
18799
+ message,
18800
+ details: {
18801
+ rule_id: ruleId,
18802
+ account: user,
18803
+ login_ip: ip,
18804
+ fingerprint: fp,
18805
+ key_comment: key?.comment ?? null,
18806
+ key_kind: automation ? "automation" : "person",
18807
+ network_kind: kind,
18808
+ ...info ? { asn: info.asn, as_name: info.name, as_country: info.country } : {},
18809
+ first_time_for_key: isNew,
18810
+ known_addresses_for_key: known,
18811
+ evidence: { at: event.timestamp.toISOString(), module: "ssh-guard", message: `Accepted publickey for ${user} from ${ip} ${fp}` }
18812
+ }
18813
+ };
18814
+ this.emit(out);
18815
+ return out;
18816
+ }
18817
+ };
18818
+
18819
+ // src/daemon/workers/lightning-watch.ts
18820
+ var import_node_fs27 = require("fs");
18821
+ var DEFAULT_CLN_LOGS = [
18822
+ "/home/lightning/.lightning/cln.log",
18823
+ "/root/.lightning/cln.log",
18824
+ "/var/lib/clightning/cln.log",
18825
+ "/home/lightning/.lightning/bitcoin/cln.log"
18826
+ ];
18827
+ 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)/;
18828
+ function parseChannelClose(line) {
18829
+ const m = CLOSE_RE.exec(line);
18830
+ if (!m) return null;
18831
+ const at = new Date(m[1]);
18832
+ 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) };
18833
+ }
18834
+ var BURST_WINDOW_MS = 10 * 6e4;
18835
+ var BURST_REALERT_MS = 30 * 6e4;
18836
+ var ChannelCloseDetector = class {
18837
+ recent = [];
18838
+ lastBurst = 0;
18839
+ /** Events for one log line (none, a close, or a close and a burst). */
18840
+ feed(line) {
18841
+ const close = parseChannelClose(line);
18842
+ if (!close) return [];
18843
+ const t = close.at.getTime();
18844
+ this.recent = this.recent.filter((c) => t - c.at.getTime() < BURST_WINDOW_MS && c.channel !== close.channel);
18845
+ this.recent.push(close);
18846
+ const out = [{
18847
+ timestamp: close.at,
18848
+ severity: "high",
18849
+ message: `Lightning channel ${close.channel} closing (${close.to})`,
18850
+ details: { rule_id: "ln-channel-close", peer: close.peer, to_state: close.to, evidence: { at: close.at.toISOString(), module: "lightning", message: close.line } }
18851
+ }];
18852
+ if (this.recent.length >= 2 && t - this.lastBurst >= BURST_REALERT_MS) {
18853
+ this.lastBurst = t;
18854
+ out.push({
18855
+ timestamp: close.at,
18856
+ severity: "critical",
18857
+ 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.`,
18858
+ details: { rule_id: "ln-channel-close-burst", channels: this.recent.map((c) => c.channel), evidence: { at: close.at.toISOString(), module: "lightning", message: close.line } }
18859
+ });
18860
+ }
18861
+ return out;
18862
+ }
18863
+ };
18864
+ var LightningWatch = class {
18865
+ constructor(opts) {
18866
+ this.opts = opts;
18867
+ }
18868
+ opts;
18869
+ tails = [];
18870
+ timer = null;
18871
+ detector = new ChannelCloseDetector();
18872
+ start() {
18873
+ if (this.opts.enabled === false) return [];
18874
+ const found = [];
18875
+ for (const path of this.opts.paths?.length ? this.opts.paths : DEFAULT_CLN_LOGS) {
18876
+ if (!(0, import_node_fs27.existsSync)(path)) continue;
18877
+ try {
18878
+ (0, import_node_fs27.accessSync)(path, import_node_fs27.constants.R_OK);
18879
+ } catch {
18880
+ continue;
18881
+ }
18882
+ this.tails.push(new LogTail(path));
18883
+ found.push(path);
18884
+ }
18885
+ if (!found.length) return [];
18886
+ this.timer = setInterval(() => this.poll(), 2e3);
18887
+ this.timer.unref?.();
18888
+ this.opts.log(`[lightning] watching channel closes in ${found.join(", ")}`);
18889
+ return found;
18890
+ }
18891
+ stop() {
18892
+ if (this.timer) clearInterval(this.timer);
18893
+ this.timer = null;
18894
+ this.tails = [];
18895
+ }
18896
+ poll() {
18897
+ for (const tail of this.tails) {
18898
+ tail.poll((line) => {
18899
+ for (const e of this.detector.feed(line)) {
18900
+ const event = { module: "lightning", category: "system", ...e };
18901
+ try {
18902
+ insertEvent(event);
18903
+ } catch {
18904
+ }
18905
+ this.opts.bus.publish(event);
18906
+ }
18907
+ });
18908
+ }
18909
+ }
18910
+ };
18911
+
18912
+ // src/core/tor-exits.ts
18913
+ var import_node_fs28 = require("fs");
18914
+ var import_node_path21 = require("path");
18915
+ var import_node_net12 = require("net");
18916
+ var TOR_BULK_EXIT_LIST_URL = "https://check.torproject.org/torbulkexitlist";
18917
+ function parseTorExitList(text) {
18918
+ const out = /* @__PURE__ */ new Set();
18919
+ for (const raw of text.split("\n")) {
18920
+ const line = raw.trim();
18921
+ if (!line || line.startsWith("#")) continue;
18922
+ const ip = line.split(/\s+/)[0];
18923
+ if ((0, import_node_net12.isIP)(ip)) out.add(normalizeIp(ip));
18924
+ }
18925
+ return out;
18926
+ }
18927
+ function normalizeIp(ip) {
18928
+ const bare = ip.trim().replace(/^\[|\]$/g, "").replace(/%.*$/, "");
18929
+ const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(bare);
18930
+ return mapped ? mapped[1] : bare.toLowerCase();
18931
+ }
18932
+ var TorExitList = class _TorExitList {
18933
+ constructor(opts) {
18934
+ this.opts = opts;
18935
+ this.url = opts.url ?? TOR_BULK_EXIT_LIST_URL;
18936
+ this.refreshMs = Math.max(15 * 6e4, opts.refreshMs ?? 36e5);
18937
+ this.fetchImpl = opts.fetchImpl ?? fetch;
18938
+ this.log = opts.log ?? (() => {
18939
+ });
18940
+ this.now = opts.now ?? Date.now;
18941
+ }
18942
+ opts;
18943
+ exits = /* @__PURE__ */ new Set();
18944
+ updatedAt = 0;
18945
+ timer = null;
18946
+ url;
18947
+ refreshMs;
18948
+ fetchImpl;
18949
+ log;
18950
+ now;
18951
+ /** Fewer than this many exits is a broken download, not the Tor network (it has ~1,000+). */
18952
+ static MIN_PLAUSIBLE = 100;
18953
+ /** Load the cache, then refresh now and every `refreshMs`. */
18954
+ start() {
18955
+ this.loadCache();
18956
+ void this.refresh();
18957
+ this.timer = setInterval(() => void this.refresh(), this.refreshMs);
18958
+ this.timer.unref?.();
18959
+ }
18960
+ stop() {
18961
+ if (this.timer) clearInterval(this.timer);
18962
+ this.timer = null;
18963
+ }
18964
+ has(ip) {
18965
+ if (!ip) return false;
18966
+ return this.exits.has(normalizeIp(ip));
18967
+ }
18968
+ get size() {
18969
+ return this.exits.size;
18970
+ }
18971
+ /** When the list in memory was downloaded (ms), 0 if never. */
18972
+ get updated() {
18973
+ return this.updatedAt;
18974
+ }
18975
+ /** Replace the list directly (tests, and the CLI reading the cache). */
18976
+ load(ips, at = this.now()) {
18977
+ this.exits = new Set([...ips].map(normalizeIp));
18978
+ this.updatedAt = at;
18979
+ }
18980
+ loadCache() {
18981
+ try {
18982
+ if (!(0, import_node_fs28.existsSync)(this.opts.cachePath)) return false;
18983
+ const parsed = parseTorExitList((0, import_node_fs28.readFileSync)(this.opts.cachePath, "utf-8"));
18984
+ if (parsed.size === 0) return false;
18985
+ this.load(parsed, (0, import_node_fs28.statSync)(this.opts.cachePath).mtimeMs);
18986
+ this.log(`[tor] loaded ${parsed.size} Tor exit addresses from cache (${new Date(this.updatedAt).toISOString()})`);
18987
+ return true;
18988
+ } catch (err) {
18989
+ this.log(`[tor] could not read the exit list cache: ${err.message}`);
18990
+ return false;
18991
+ }
18992
+ }
18993
+ async refresh() {
18994
+ let text;
18995
+ try {
18996
+ const res = await this.fetchImpl(this.url, {
18997
+ signal: AbortSignal.timeout(3e4),
18998
+ headers: { "User-Agent": "threatcrush-daemon (tor exit list)" }
18999
+ });
19000
+ if (!res.ok) {
19001
+ this.log(`[tor] exit list download failed: HTTP ${res.status}; keeping ${this.exits.size} cached`);
19002
+ return false;
19003
+ }
19004
+ text = await res.text();
19005
+ } catch (err) {
19006
+ this.log(`[tor] exit list download failed: ${err.message}; keeping ${this.exits.size} cached`);
19007
+ return false;
19008
+ }
19009
+ const parsed = parseTorExitList(text);
19010
+ if (parsed.size < _TorExitList.MIN_PLAUSIBLE) {
19011
+ this.log(`[tor] exit list download had only ${parsed.size} addresses; keeping ${this.exits.size} cached`);
19012
+ return false;
19013
+ }
19014
+ const before = this.exits.size;
19015
+ this.load(parsed);
19016
+ try {
19017
+ (0, import_node_fs28.mkdirSync)((0, import_node_path21.dirname)(this.opts.cachePath), { recursive: true });
19018
+ (0, import_node_fs28.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
19019
+ (0, import_node_fs28.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
19020
+ } catch (err) {
19021
+ this.log(`[tor] could not save the exit list cache: ${err.message}`);
19022
+ }
19023
+ if (before !== parsed.size || before === 0) this.log(`[tor] loaded ${parsed.size} Tor exit addresses from ${this.url}`);
19024
+ return true;
19025
+ }
19026
+ };
19027
+
18171
19028
  // src/daemon/rules/engine.ts
18172
19029
  var MAX_WINDOW_ENTRIES = 1e3;
18173
19030
  function live(window) {
@@ -18349,8 +19206,8 @@ var RuleEngine = class {
18349
19206
  };
18350
19207
 
18351
19208
  // src/daemon/rules/loader.ts
18352
- var import_node_fs26 = require("fs");
18353
- var import_node_path20 = require("path");
19209
+ var import_node_fs29 = require("fs");
19210
+ var import_node_path22 = require("path");
18354
19211
 
18355
19212
  // src/daemon/rules/default-rules.ts
18356
19213
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -18820,11 +19677,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
18820
19677
  function loadAllRules(customDir) {
18821
19678
  const rules = [...DEFAULT_RULES];
18822
19679
  const dir = customDir || RULES_DIR;
18823
- if ((0, import_node_fs26.existsSync)(dir)) {
18824
- const files = (0, import_node_fs26.readdirSync)(dir).filter((f) => f.endsWith(".json"));
19680
+ if ((0, import_node_fs29.existsSync)(dir)) {
19681
+ const files = (0, import_node_fs29.readdirSync)(dir).filter((f) => f.endsWith(".json"));
18825
19682
  for (const file of files) {
18826
19683
  try {
18827
- const raw = (0, import_node_fs26.readFileSync)((0, import_node_path20.join)(dir, file), "utf-8");
19684
+ const raw = (0, import_node_fs29.readFileSync)((0, import_node_path22.join)(dir, file), "utf-8");
18828
19685
  const parsed = JSON.parse(raw);
18829
19686
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
18830
19687
  for (const rule of customRules) {
@@ -18855,24 +19712,24 @@ function loadAllRules(customDir) {
18855
19712
  }
18856
19713
 
18857
19714
  // src/daemon/firewall/adapters.ts
18858
- var import_node_child_process8 = require("child_process");
18859
- var import_node_fs27 = require("fs");
18860
- var import_node_path21 = require("path");
18861
- var import_node_net10 = require("net");
19715
+ var import_node_child_process9 = require("child_process");
19716
+ var import_node_fs30 = require("fs");
19717
+ var import_node_path23 = require("path");
19718
+ var import_node_net13 = require("net");
18862
19719
  function assertValidFirewallIp(ip) {
18863
- if ((0, import_node_net10.isIP)(ip) !== 4) {
19720
+ if ((0, import_node_net13.isIP)(ip) !== 4) {
18864
19721
  throw new Error(`Invalid IPv4 address: ${ip}`);
18865
19722
  }
18866
19723
  }
18867
19724
  function assertBannableIp(ip) {
18868
- if ((0, import_node_net10.isIP)(ip) === 0) {
19725
+ if ((0, import_node_net13.isIP)(ip) === 0) {
18869
19726
  throw new Error(`Invalid IP address: ${ip}`);
18870
19727
  }
18871
19728
  }
18872
19729
  function writeIfAbsent(path, contents) {
18873
- (0, import_node_fs27.mkdirSync)((0, import_node_path21.dirname)(path), { recursive: true });
19730
+ (0, import_node_fs30.mkdirSync)((0, import_node_path23.dirname)(path), { recursive: true });
18874
19731
  try {
18875
- (0, import_node_fs27.writeFileSync)(path, contents, { flag: "wx" });
19732
+ (0, import_node_fs30.writeFileSync)(path, contents, { flag: "wx" });
18876
19733
  } catch (err) {
18877
19734
  if (err.code !== "EEXIST") throw err;
18878
19735
  }
@@ -18891,11 +19748,11 @@ var Fail2banAdapter = class {
18891
19748
  enforces = true;
18892
19749
  jailReady = false;
18893
19750
  isAvailable() {
18894
- const result = (0, import_node_child_process8.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
19751
+ const result = (0, import_node_child_process9.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
18895
19752
  return result.status === 0;
18896
19753
  }
18897
19754
  client(args) {
18898
- return (0, import_node_child_process8.execFileSync)("fail2ban-client", args, {
19755
+ return (0, import_node_child_process9.execFileSync)("fail2ban-client", args, {
18899
19756
  encoding: "utf-8",
18900
19757
  stdio: ["ignore", "pipe", "pipe"]
18901
19758
  });
@@ -18971,7 +19828,7 @@ var Fail2banAdapter = class {
18971
19828
  const status = this.client(["status", this.jail]);
18972
19829
  const line = status.split("\n").find((l) => /Banned IP list:/i.test(l));
18973
19830
  if (!line) return [];
18974
- return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net10.isIP)(s) !== 0);
19831
+ return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net13.isIP)(s) !== 0);
18975
19832
  } catch {
18976
19833
  return [];
18977
19834
  }
@@ -18981,45 +19838,45 @@ var Fail2banAdapter = class {
18981
19838
  function parseBannedList(output) {
18982
19839
  const found = [];
18983
19840
  for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
18984
- if ((0, import_node_net10.isIP)(match[1]) !== 0) found.push(match[1]);
19841
+ if ((0, import_node_net13.isIP)(match[1]) !== 0) found.push(match[1]);
18985
19842
  }
18986
19843
  if (found.length > 0) return found;
18987
- return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net10.isIP)(s) !== 0);
19844
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net13.isIP)(s) !== 0);
18988
19845
  }
18989
19846
  var NftablesAdapter = class {
18990
19847
  name = "nftables";
18991
19848
  table = "threatcrush";
18992
19849
  set = "blocklist";
18993
19850
  isAvailable() {
18994
- const result = (0, import_node_child_process8.spawnSync)("nft", ["--version"], { stdio: "pipe" });
19851
+ const result = (0, import_node_child_process9.spawnSync)("nft", ["--version"], { stdio: "pipe" });
18995
19852
  return result.status === 0;
18996
19853
  }
18997
19854
  ensureSetup() {
18998
19855
  try {
18999
- (0, import_node_child_process8.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
19856
+ (0, import_node_child_process9.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
19000
19857
  } catch {
19001
- (0, import_node_child_process8.execSync)(`nft add table inet ${this.table}`);
19002
- (0, import_node_child_process8.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
19003
- (0, import_node_child_process8.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
19004
- (0, import_node_child_process8.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
19858
+ (0, import_node_child_process9.execSync)(`nft add table inet ${this.table}`);
19859
+ (0, import_node_child_process9.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
19860
+ (0, import_node_child_process9.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
19861
+ (0, import_node_child_process9.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
19005
19862
  }
19006
19863
  }
19007
19864
  async block(ip) {
19008
19865
  assertValidFirewallIp(ip);
19009
19866
  this.ensureSetup();
19010
- (0, import_node_child_process8.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
19867
+ (0, import_node_child_process9.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
19011
19868
  }
19012
19869
  async unblock(ip) {
19013
19870
  assertValidFirewallIp(ip);
19014
19871
  try {
19015
- (0, import_node_child_process8.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
19872
+ (0, import_node_child_process9.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
19016
19873
  } catch {
19017
19874
  }
19018
19875
  }
19019
19876
  async isBlocked(ip) {
19020
19877
  assertValidFirewallIp(ip);
19021
19878
  try {
19022
- const output = (0, import_node_child_process8.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
19879
+ const output = (0, import_node_child_process9.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
19023
19880
  return output.includes(ip);
19024
19881
  } catch {
19025
19882
  return false;
@@ -19027,7 +19884,7 @@ var NftablesAdapter = class {
19027
19884
  }
19028
19885
  async listBlocked() {
19029
19886
  try {
19030
- const output = (0, import_node_child_process8.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
19887
+ const output = (0, import_node_child_process9.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
19031
19888
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
19032
19889
  if (!match) return [];
19033
19890
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -19040,34 +19897,34 @@ var IptablesAdapter = class {
19040
19897
  name = "iptables";
19041
19898
  chain = "THREATCRUSH";
19042
19899
  isAvailable() {
19043
- const result = (0, import_node_child_process8.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
19900
+ const result = (0, import_node_child_process9.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
19044
19901
  return result.status === 0;
19045
19902
  }
19046
19903
  ensureChain() {
19047
19904
  try {
19048
- (0, import_node_child_process8.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
19905
+ (0, import_node_child_process9.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
19049
19906
  } catch {
19050
- (0, import_node_child_process8.execSync)(`iptables -N ${this.chain}`);
19051
- (0, import_node_child_process8.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
19907
+ (0, import_node_child_process9.execSync)(`iptables -N ${this.chain}`);
19908
+ (0, import_node_child_process9.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
19052
19909
  }
19053
19910
  }
19054
19911
  async block(ip) {
19055
19912
  assertValidFirewallIp(ip);
19056
19913
  this.ensureChain();
19057
19914
  if (await this.isBlocked(ip)) return;
19058
- (0, import_node_child_process8.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
19915
+ (0, import_node_child_process9.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
19059
19916
  }
19060
19917
  async unblock(ip) {
19061
19918
  assertValidFirewallIp(ip);
19062
19919
  try {
19063
- (0, import_node_child_process8.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
19920
+ (0, import_node_child_process9.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
19064
19921
  } catch {
19065
19922
  }
19066
19923
  }
19067
19924
  async isBlocked(ip) {
19068
19925
  assertValidFirewallIp(ip);
19069
19926
  try {
19070
- const output = (0, import_node_child_process8.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
19927
+ const output = (0, import_node_child_process9.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
19071
19928
  return output.includes(ip);
19072
19929
  } catch {
19073
19930
  return false;
@@ -19075,7 +19932,7 @@ var IptablesAdapter = class {
19075
19932
  }
19076
19933
  async listBlocked() {
19077
19934
  try {
19078
- const output = (0, import_node_child_process8.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
19935
+ const output = (0, import_node_child_process9.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
19079
19936
  const ips = [];
19080
19937
  for (const line of output.split("\n")) {
19081
19938
  const match = line.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -19131,20 +19988,20 @@ function detectFirewallAdapter(backend = "auto") {
19131
19988
  }
19132
19989
 
19133
19990
  // src/daemon/firewall/remediation.ts
19134
- var import_node_fs28 = require("fs");
19135
- var import_node_child_process9 = require("child_process");
19136
- var import_node_net11 = require("net");
19991
+ var import_node_fs31 = require("fs");
19992
+ var import_node_child_process10 = require("child_process");
19993
+ var import_node_net14 = require("net");
19137
19994
 
19138
19995
  // src/daemon/firewall/crawlers.ts
19139
- var import_node_dns = require("dns");
19996
+ var import_node_dns2 = require("dns");
19140
19997
  var CRAWLER_DOMAINS = ["googlebot.com", "google.com", "search.msn.com", "applebot.apple.com"];
19141
19998
  var systemResolver = {
19142
- reverse: (ip) => import_node_dns.promises.reverse(ip),
19143
- lookup: async (host) => (await import_node_dns.promises.lookup(host, { all: true })).map((a) => a.address)
19999
+ reverse: (ip) => import_node_dns2.promises.reverse(ip),
20000
+ lookup: async (host) => (await import_node_dns2.promises.lookup(host, { all: true })).map((a) => a.address)
19144
20001
  };
19145
20002
  var TIMEOUT_MS2 = 2e3;
19146
20003
  var CACHE_MS = 6 * 36e5;
19147
- function withTimeout(p) {
20004
+ function withTimeout2(p) {
19148
20005
  return Promise.race([
19149
20006
  p,
19150
20007
  new Promise((_, reject) => setTimeout(() => reject(new Error("dns timeout")), TIMEOUT_MS2).unref())
@@ -19161,9 +20018,9 @@ function crawlerVerifier(resolver = systemResolver) {
19161
20018
  if (hit && hit.until > Date.now()) return hit.host;
19162
20019
  let host = null;
19163
20020
  try {
19164
- const names = await withTimeout(resolver.reverse(ip));
20021
+ const names = await withTimeout2(resolver.reverse(ip));
19165
20022
  for (const name of names.filter(inCrawlerDomain)) {
19166
- const addrs = await withTimeout(resolver.lookup(name));
20023
+ const addrs = await withTimeout2(resolver.lookup(name));
19167
20024
  if (addrs.includes(ip)) {
19168
20025
  host = name.replace(/\.$/, "");
19169
20026
  break;
@@ -19191,7 +20048,8 @@ var DEFAULT_CONFIG2 = {
19191
20048
  protect_current_ssh_client: true,
19192
20049
  protect_recent_operators: true,
19193
20050
  operator_memory_seconds: 30 * 86400,
19194
- spare_verified_crawlers: true
20051
+ spare_verified_crawlers: true,
20052
+ block_tor_ssh: true
19195
20053
  };
19196
20054
  var defaultDiscovery = {
19197
20055
  sshPeers: () => [currentSshClient(), ...establishedSshPeers()].filter((ip) => Boolean(ip)),
@@ -19200,19 +20058,19 @@ var defaultDiscovery = {
19200
20058
  const snapshot = takeSnapshot({
19201
20059
  readFile: (p) => {
19202
20060
  try {
19203
- return (0, import_node_fs28.readFileSync)(p, "utf-8");
20061
+ return (0, import_node_fs31.readFileSync)(p, "utf-8");
19204
20062
  } catch {
19205
20063
  return null;
19206
20064
  }
19207
20065
  },
19208
20066
  readDir: (p) => {
19209
20067
  try {
19210
- return (0, import_node_fs28.readdirSync)(p);
20068
+ return (0, import_node_fs31.readdirSync)(p);
19211
20069
  } catch {
19212
20070
  return null;
19213
20071
  }
19214
20072
  },
19215
- exists: (p) => (0, import_node_fs28.existsSync)(p)
20073
+ exists: (p) => (0, import_node_fs31.existsSync)(p)
19216
20074
  });
19217
20075
  const out = /* @__PURE__ */ new Set();
19218
20076
  for (const keys of Object.values(snapshot.keys)) {
@@ -19221,7 +20079,7 @@ var defaultDiscovery = {
19221
20079
  return out;
19222
20080
  },
19223
20081
  keyLoginJournal: (sinceSeconds) => new Promise((resolve4) => {
19224
- (0, import_node_child_process9.execFile)(
20082
+ (0, import_node_child_process10.execFile)(
19225
20083
  "journalctl",
19226
20084
  ["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
19227
20085
  { maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
@@ -19229,7 +20087,7 @@ var defaultDiscovery = {
19229
20087
  );
19230
20088
  })
19231
20089
  };
19232
- var SEVERITY_RANK5 = {
20090
+ var SEVERITY_RANK6 = {
19233
20091
  info: 0,
19234
20092
  low: 1,
19235
20093
  medium: 2,
@@ -19286,16 +20144,56 @@ var RemediationManager = class {
19286
20144
  operators = {};
19287
20145
  expiryTimer = null;
19288
20146
  operatorTimer = null;
20147
+ /** True for a Tor exit address; such an address is never an operator. */
20148
+ isTorExit = () => false;
19289
20149
  /** Remembered operator addresses and when each was last seen. */
19290
20150
  getOperators() {
19291
20151
  return { ...this.operators };
19292
20152
  }
20153
+ /**
20154
+ * Teach the manager which addresses are Tor exits. They are never
20155
+ * remembered as operators and never protected as a live session: on dev2
20156
+ * the 2026-10-27 intruder logged in with a stolen key from Tor, which made
20157
+ * the exit an "operator" that nothing could ban for 30 days.
20158
+ */
20159
+ setTorExitCheck(check) {
20160
+ this.isTorExit = check;
20161
+ let dropped = 0;
20162
+ this.protectedList = this.protectedList.filter((a) => !(0, import_node_net14.isIP)(a) || !check(a) || this.pinned.has(a) || this.config.allowlist.includes(a));
20163
+ for (const ip of Object.keys(this.operators)) {
20164
+ if (!check(ip)) continue;
20165
+ delete this.operators[ip];
20166
+ this.protectedList = this.protectedList.filter((a) => a !== ip || this.pinned.has(a) || this.config.allowlist.includes(a));
20167
+ dropped++;
20168
+ }
20169
+ if (dropped) {
20170
+ this.logLine(`[firewall] forgot ${dropped} remembered operator address(es) that are Tor exits`);
20171
+ this.saveState();
20172
+ }
20173
+ }
20174
+ /** Tor SSH bans on (setting) — the cloud may change it unless config pinned it. */
20175
+ get blockTorSsh() {
20176
+ return this.config.enabled && this.config.block_tor_ssh;
20177
+ }
20178
+ setBlockTorSsh(on) {
20179
+ this.config.block_tor_ssh = on;
20180
+ }
20181
+ /**
20182
+ * Our own addresses: built-ins, shared infrastructure, gateways, the
20183
+ * operator's `[remediation] protected` and the dashboard's org allowlist
20184
+ * (Known IPs). Not remembered operators or live sessions.
20185
+ */
20186
+ isFleetAddress(ip) {
20187
+ return isProtected(ip, [...this.pinned, ...this.config.allowlist]);
20188
+ }
19293
20189
  /**
19294
20190
  * An address an operator really came from: never ban it, remember it, and
19295
20191
  * lift a ban that is already on it — the operator is the one who needs in.
19296
20192
  */
19297
20193
  noteOperator(ip, at, remember = true) {
19298
20194
  if (Date.now() - at > this.config.operator_memory_seconds * 1e3) return;
20195
+ if (this.isTorExit(ip) && !this.isFleetAddress(ip)) return;
20196
+ if (this.blocklist.some((b) => b.ip === ip && b.strict)) return;
19299
20197
  if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
19300
20198
  if (!remember || !this.config.protect_recent_operators || isProtected(ip, DEFAULT_PROTECTED)) return;
19301
20199
  const known = this.operators[ip] ?? 0;
@@ -19345,17 +20243,21 @@ var RemediationManager = class {
19345
20243
  }
19346
20244
  async handleDetection(event) {
19347
20245
  if (!this.config.enabled) return;
19348
- const eventRank = SEVERITY_RANK5[event.severity] ?? 0;
19349
- const minRank = SEVERITY_RANK5[this.config.min_severity] ?? 3;
20246
+ const eventRank = SEVERITY_RANK6[event.severity] ?? 0;
20247
+ const minRank = SEVERITY_RANK6[this.config.min_severity] ?? 3;
19350
20248
  if (eventRank < minRank) return;
19351
- if (isSuccessfulAuth(event.message)) return;
20249
+ const remediation = event.details?.remediation;
20250
+ if (isSuccessfulAuth(event.message) && remediation?.ban_on_login !== true) return;
19352
20251
  if (event.details?.rule_id) {
19353
- const remediation = event.details?.remediation;
19354
20252
  if (remediation?.action !== "block") return;
19355
20253
  }
19356
20254
  const ip = event.source_ip;
19357
- if (!ip || (0, import_node_net11.isIP)(ip) === 0) return;
19358
- if (this.isAllowlisted(ip)) return;
20255
+ if (!ip || (0, import_node_net14.isIP)(ip) === 0) return;
20256
+ const strict = remediation?.override_operator_protection === true;
20257
+ if (strict ? this.isFleetAddress(ip) : this.isAllowlisted(ip)) {
20258
+ if (strict) this.logLine(`[remediation] not banning ${ip}: it is one of our own addresses (${event.message})`);
20259
+ return;
20260
+ }
19359
20261
  if (this.blocklist.some((b) => b.ip === ip)) return;
19360
20262
  if (this.config.spare_verified_crawlers) {
19361
20263
  const crawler = await this.verifyCrawler(ip);
@@ -19365,7 +20267,13 @@ var RemediationManager = class {
19365
20267
  }
19366
20268
  }
19367
20269
  const ruleId = event.details?.rule_id;
19368
- await this.ban(ip, event.message, { ruleId, source: "auto" });
20270
+ await this.ban(ip, event.message, {
20271
+ ruleId,
20272
+ source: "auto",
20273
+ enforceInDryRun: remediation?.enforce_in_dry_run === true,
20274
+ strict,
20275
+ ...remediation?.max_ban ? { ttlSeconds: this.config.max_ban_seconds } : {}
20276
+ });
19369
20277
  }
19370
20278
  /**
19371
20279
  * Ban `ip`. With no explicit TTL the length comes from the doubling ladder:
@@ -19373,8 +20281,8 @@ var RemediationManager = class {
19373
20281
  * 4th offence and so on, clamped to `max_ban_seconds`.
19374
20282
  */
19375
20283
  async ban(ip, reason, opts = {}) {
19376
- if ((0, import_node_net11.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
19377
- if (this.isAllowlisted(ip)) {
20284
+ if ((0, import_node_net14.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
20285
+ if (opts.strict ? this.isFleetAddress(ip) : this.isAllowlisted(ip)) {
19378
20286
  return { ok: false, error: `${ip} is protected and can never be blocked` };
19379
20287
  }
19380
20288
  const now = Date.now();
@@ -19382,7 +20290,8 @@ var RemediationManager = class {
19382
20290
  if (existing && !opts.ttlSeconds) {
19383
20291
  return { ok: false, error: `${ip} is already banned` };
19384
20292
  }
19385
- if (!this.config.dry_run) {
20293
+ const dryRun = this.config.dry_run && !(opts.enforceInDryRun && this.adapter.enforces !== false);
20294
+ if (!dryRun) {
19386
20295
  try {
19387
20296
  await this.adapter.block(ip);
19388
20297
  } catch (err) {
@@ -19415,14 +20324,19 @@ var RemediationManager = class {
19415
20324
  rule_id: opts.ruleId,
19416
20325
  blocked_at: now,
19417
20326
  expires_at: now + ttl * 1e3,
19418
- dry_run: this.config.dry_run,
20327
+ dry_run: dryRun,
19419
20328
  strikes: strike,
19420
- source: opts.source ?? "manual"
20329
+ source: opts.source ?? "manual",
20330
+ ...opts.strict ? { strict: true } : {}
19421
20331
  };
20332
+ if (opts.strict) {
20333
+ delete this.operators[ip];
20334
+ this.protectedList = this.protectedList.filter((a) => a !== ip || this.pinned.has(a) || this.config.allowlist.includes(a));
20335
+ }
19422
20336
  this.blocklist = this.blocklist.filter((b) => b.ip !== ip);
19423
20337
  this.blocklist.push(entry);
19424
20338
  this.saveState();
19425
- const mode = this.config.dry_run ? "[DRY-RUN] " : "";
20339
+ const mode = dryRun ? "[DRY-RUN] " : this.config.dry_run ? "[ENFORCED IN DRY-RUN] " : "";
19426
20340
  const label = `${mode}Banned ${ip} for ${formatDuration(ttl)} (offence #${strike}): ${reason}`;
19427
20341
  this.logLine(`[firewall] ${label}`);
19428
20342
  this.bus.publish({
@@ -19437,7 +20351,7 @@ var RemediationManager = class {
19437
20351
  rule_id: opts.ruleId,
19438
20352
  reason,
19439
20353
  origin: opts.origin,
19440
- dry_run: this.config.dry_run,
20354
+ dry_run: dryRun,
19441
20355
  ttl_seconds: ttl,
19442
20356
  strikes: strike,
19443
20357
  source: entry.source,
@@ -19520,10 +20434,13 @@ var RemediationManager = class {
19520
20434
  * Saying so up front beats a dashboard that looks armed and is not.
19521
20435
  */
19522
20436
  privilegeWarning() {
19523
- if (!this.config.enabled || this.config.dry_run) return void 0;
20437
+ if (!this.config.enabled) return void 0;
19524
20438
  if (this.adapter.enforces === false) return void 0;
19525
20439
  const uid = typeof process.getuid === "function" ? process.getuid() : 0;
19526
20440
  if (uid === 0) return void 0;
20441
+ if (this.config.dry_run) {
20442
+ 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;
20443
+ }
19527
20444
  return `daemon runs as uid ${uid} and cannot write ${this.adapter.name} rules \u2014 bans will fail`;
19528
20445
  }
19529
20446
  addToAllowlist(ip) {
@@ -19552,10 +20469,11 @@ var RemediationManager = class {
19552
20469
  */
19553
20470
  async reconcile() {
19554
20471
  const now = Date.now();
19555
- const lifted = this.blocklist.filter((b) => this.isAllowlisted(b.ip));
20472
+ const guarded = (b) => b.strict ? this.isFleetAddress(b.ip) : this.isAllowlisted(b.ip);
20473
+ const lifted = this.blocklist.filter(guarded);
19556
20474
  for (const entry of lifted) this.logLine(`[firewall] reconcile: lifting ban on protected ${entry.ip}`);
19557
- const live2 = this.blocklist.filter((b) => b.expires_at > now && !this.isAllowlisted(b.ip));
19558
- const stale = this.blocklist.filter((b) => b.expires_at <= now || this.isAllowlisted(b.ip));
20475
+ const live2 = this.blocklist.filter((b) => b.expires_at > now && !guarded(b));
20476
+ const stale = this.blocklist.filter((b) => b.expires_at <= now || guarded(b));
19559
20477
  for (const entry of stale) {
19560
20478
  if (!entry.dry_run) {
19561
20479
  try {
@@ -19582,8 +20500,8 @@ var RemediationManager = class {
19582
20500
  }
19583
20501
  }
19584
20502
  }
19585
- if (this.config.dry_run) return;
19586
20503
  for (const entry of live2) {
20504
+ if (entry.dry_run) continue;
19587
20505
  if (applied?.includes(entry.ip)) continue;
19588
20506
  try {
19589
20507
  await this.adapter.block(entry.ip);
@@ -19640,7 +20558,8 @@ var RemediationManager = class {
19640
20558
  if (saved && typeof saved === "object" && this.config.protect_recent_operators) {
19641
20559
  const cutoff = Date.now() - this.config.operator_memory_seconds * 1e3;
19642
20560
  for (const [ip, at] of Object.entries(saved)) {
19643
- if (typeof at !== "number" || at < cutoff || !(0, import_node_net11.isIP)(ip)) continue;
20561
+ if (typeof at !== "number" || at < cutoff || !(0, import_node_net14.isIP)(ip)) continue;
20562
+ if (this.blocklist.some((b) => b.ip === ip && b.strict)) continue;
19644
20563
  this.operators[ip] = at;
19645
20564
  if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
19646
20565
  }
@@ -19664,7 +20583,7 @@ var RemediationManager = class {
19664
20583
  }
19665
20584
  logLine(line) {
19666
20585
  try {
19667
- (0, import_node_fs28.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
20586
+ (0, import_node_fs31.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
19668
20587
  `);
19669
20588
  } catch {
19670
20589
  }
@@ -19696,6 +20615,7 @@ function remediationSettings(section) {
19696
20615
  }
19697
20616
  const operatorMemory = parseDuration(section.operator_memory);
19698
20617
  if (operatorMemory) settings.operator_memory_seconds = operatorMemory;
20618
+ if (typeof section.block_tor_ssh === "boolean") settings.block_tor_ssh = section.block_tor_ssh;
19699
20619
  if (typeof section.spare_verified_crawlers === "boolean") {
19700
20620
  settings.spare_verified_crawlers = section.spare_verified_crawlers;
19701
20621
  }
@@ -19703,19 +20623,19 @@ function remediationSettings(section) {
19703
20623
  }
19704
20624
 
19705
20625
  // src/daemon/watchdog-service.ts
19706
- var import_node_fs30 = require("fs");
19707
- var import_node_path23 = require("path");
20626
+ var import_node_fs33 = require("fs");
20627
+ var import_node_path25 = require("path");
19708
20628
 
19709
20629
  // src/core/watchdog.ts
19710
- var import_node_fs29 = require("fs");
20630
+ var import_node_fs32 = require("fs");
19711
20631
  var import_node_crypto7 = require("crypto");
19712
- var import_node_path22 = require("path");
20632
+ var import_node_path24 = require("path");
19713
20633
  var WATCHDOG_DIRNAME = "watchdog";
19714
20634
  var LOG_FILE2 = "attacks.jsonl";
19715
20635
  var ROTATED_FILE = "attacks.1.jsonl";
19716
20636
  var ROTATE_BYTES = 50 * 1024 * 1024;
19717
20637
  var SEEN_LIMIT = 5e3;
19718
- var SEVERITY_RANK6 = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
20638
+ var SEVERITY_RANK7 = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
19719
20639
  function str2(v) {
19720
20640
  return typeof v === "string" && v !== "" && v !== "-" ? v : void 0;
19721
20641
  }
@@ -19726,7 +20646,7 @@ function isAttack(event) {
19726
20646
  const crs = typeof d.crs_score === "number" ? d.crs_score : 0;
19727
20647
  if (crs > 0 || str2(d.attack_type)) return true;
19728
20648
  if (event.category === "web" && typeof d.status === "number" && !str2(d.rule_id)) return false;
19729
- return SEVERITY_RANK6[event.severity] >= SEVERITY_RANK6.medium;
20649
+ return SEVERITY_RANK7[event.severity] >= SEVERITY_RANK7.medium;
19730
20650
  }
19731
20651
  function outcomeFor(status) {
19732
20652
  if (typeof status !== "number" || !Number.isFinite(status)) return "unknown";
@@ -19798,12 +20718,12 @@ var WatchdogLog = class {
19798
20718
  stats = { logged: 0, answered: 0, errored: 0 };
19799
20719
  constructor(dir, options = {}) {
19800
20720
  this.dir = dir;
19801
- this.file = (0, import_node_path22.join)(dir, LOG_FILE2);
20721
+ this.file = (0, import_node_path24.join)(dir, LOG_FILE2);
19802
20722
  this.shareGid = options.shareGid;
19803
- (0, import_node_fs29.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
20723
+ (0, import_node_fs32.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
19804
20724
  if (this.shareGid !== void 0) {
19805
- (0, import_node_fs29.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
19806
- (0, import_node_fs29.chmodSync)(dir, 1528);
20725
+ (0, import_node_fs32.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
20726
+ (0, import_node_fs32.chmodSync)(dir, 1528);
19807
20727
  }
19808
20728
  for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
19809
20729
  }
@@ -19832,16 +20752,16 @@ var WatchdogLog = class {
19832
20752
  const chunk = this.buffer.join("\n") + "\n";
19833
20753
  this.buffer = [];
19834
20754
  try {
19835
- if ((0, import_node_fs29.statSync)(this.file).size > ROTATE_BYTES) {
19836
- (0, import_node_fs29.renameSync)(this.file, (0, import_node_path22.join)(this.dir, ROTATED_FILE));
20755
+ if ((0, import_node_fs32.statSync)(this.file).size > ROTATE_BYTES) {
20756
+ (0, import_node_fs32.renameSync)(this.file, (0, import_node_path24.join)(this.dir, ROTATED_FILE));
19837
20757
  }
19838
20758
  } catch {
19839
20759
  }
19840
- (0, import_node_fs29.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
20760
+ (0, import_node_fs32.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
19841
20761
  if (this.shareGid !== void 0) {
19842
20762
  try {
19843
- (0, import_node_fs29.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
19844
- (0, import_node_fs29.chmodSync)(this.file, 432);
20763
+ (0, import_node_fs32.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
20764
+ (0, import_node_fs32.chmodSync)(this.file, 432);
19845
20765
  } catch {
19846
20766
  }
19847
20767
  }
@@ -19862,21 +20782,21 @@ function parseLines(text) {
19862
20782
  function readTail(file, bytes) {
19863
20783
  let fd;
19864
20784
  try {
19865
- fd = (0, import_node_fs29.openSync)(file, "r");
20785
+ fd = (0, import_node_fs32.openSync)(file, "r");
19866
20786
  } catch (err) {
19867
20787
  if (err.code === "ENOENT") return [];
19868
20788
  throw err;
19869
20789
  }
19870
20790
  try {
19871
- const size = (0, import_node_fs29.fstatSync)(fd).size;
20791
+ const size = (0, import_node_fs32.fstatSync)(fd).size;
19872
20792
  const start = Math.max(0, size - bytes);
19873
20793
  const buf = Buffer.alloc(size - start);
19874
- (0, import_node_fs29.readSync)(fd, buf, 0, buf.length, start);
20794
+ (0, import_node_fs32.readSync)(fd, buf, 0, buf.length, start);
19875
20795
  let text = buf.toString("utf8");
19876
20796
  if (start > 0) text = text.slice(text.indexOf("\n") + 1);
19877
20797
  return parseLines(text);
19878
20798
  } finally {
19879
- (0, import_node_fs29.closeSync)(fd);
20799
+ (0, import_node_fs32.closeSync)(fd);
19880
20800
  }
19881
20801
  }
19882
20802
 
@@ -19885,13 +20805,13 @@ function defaultShareGid() {
19885
20805
  const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
19886
20806
  if (!isRoot2) return void 0;
19887
20807
  try {
19888
- return (0, import_node_fs30.statSync)("/var/log/auth.log").gid;
20808
+ return (0, import_node_fs33.statSync)("/var/log/auth.log").gid;
19889
20809
  } catch {
19890
20810
  return void 0;
19891
20811
  }
19892
20812
  }
19893
20813
  function startWatchdog(opts) {
19894
- const dir = opts.config?.dir ?? (0, import_node_path23.join)(opts.stateDir, WATCHDOG_DIRNAME);
20814
+ const dir = opts.config?.dir ?? (0, import_node_path25.join)(opts.stateDir, WATCHDOG_DIRNAME);
19895
20815
  const base = { dir, logged: 0, answered: 0, errored: 0 };
19896
20816
  if (opts.config?.enabled === false) {
19897
20817
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -19982,7 +20902,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
19982
20902
  }
19983
20903
 
19984
20904
  // src/core/node-runtime.ts
19985
- var import_node_child_process10 = require("child_process");
20905
+ var import_node_child_process11 = require("child_process");
19986
20906
  var MIN_DAEMON_NODE_MAJOR = 22;
19987
20907
  function nodeMajor(version) {
19988
20908
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -19998,16 +20918,16 @@ function daemonNodeProblem(version) {
19998
20918
  // src/daemon/index.ts
19999
20919
  function readVersion2() {
20000
20920
  try {
20001
- const pkg = JSON.parse((0, import_node_fs31.readFileSync)((0, import_node_path24.join)(__dirname, "..", "package.json"), "utf-8"));
20921
+ const pkg = JSON.parse((0, import_node_fs34.readFileSync)((0, import_node_path26.join)(__dirname, "..", "package.json"), "utf-8"));
20002
20922
  return pkg.version || "0.0.0";
20003
20923
  } catch {
20004
20924
  return "0.0.0";
20005
20925
  }
20006
20926
  }
20007
20927
  async function runHardeningChecks() {
20008
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process11.execFile)(
20928
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process12.execFile)(
20009
20929
  process.execPath,
20010
- [(0, import_node_path24.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
20930
+ [(0, import_node_path26.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
20011
20931
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
20012
20932
  );
20013
20933
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -20019,9 +20939,9 @@ async function runHardeningChecks() {
20019
20939
  return patches ? [...findings, patches] : findings;
20020
20940
  }
20021
20941
  async function runPatchCheck() {
20022
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process11.execFile)(
20942
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process12.execFile)(
20023
20943
  process.execPath,
20024
- [(0, import_node_path24.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
20944
+ [(0, import_node_path26.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
20025
20945
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
20026
20946
  );
20027
20947
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -20029,7 +20949,7 @@ async function runPatchCheck() {
20029
20949
  }
20030
20950
  function logLine(line) {
20031
20951
  try {
20032
- (0, import_node_fs31.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
20952
+ (0, import_node_fs34.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
20033
20953
  `);
20034
20954
  } catch {
20035
20955
  }
@@ -20054,9 +20974,9 @@ async function runDaemon() {
20054
20974
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
20055
20975
  const restartDaemon = () => {
20056
20976
  if (PATHS.mode === "system") {
20057
- (0, import_node_child_process11.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
20977
+ (0, import_node_child_process12.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
20058
20978
  } else {
20059
- (0, import_node_child_process11.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
20979
+ (0, import_node_child_process12.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
20060
20980
  setTimeout(() => process.exit(0), 500).unref();
20061
20981
  }
20062
20982
  };
@@ -20071,7 +20991,11 @@ async function runDaemon() {
20071
20991
  } catch (err) {
20072
20992
  logLine(`[daemon] state db unavailable: ${err.message}`);
20073
20993
  }
20074
- const config = loadConfig((0, import_node_fs31.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
20994
+ const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path26.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
20995
+ const config = loaded.config;
20996
+ if (loaded.error) {
20997
+ logLine(`[daemon] CONFIG ERROR: ${loaded.error}; ${loaded.usedLastGood ? "running on the last config that parsed" : "no earlier good copy, running on DEFAULTS (no protected list)"}`);
20998
+ }
20075
20999
  configureAttackDetection(config.detection);
20076
21000
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
20077
21001
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -20135,7 +21059,7 @@ async function runDaemon() {
20135
21059
  const threatFeeds = new ThreatFeeds({
20136
21060
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
20137
21061
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
20138
- cachePath: (0, import_node_path24.join)(PATHS.stateDir, "threat-feeds.json"),
21062
+ cachePath: (0, import_node_path26.join)(PATHS.stateDir, "threat-feeds.json"),
20139
21063
  bus,
20140
21064
  log: logLine
20141
21065
  });
@@ -20143,13 +21067,45 @@ async function runDaemon() {
20143
21067
  const privilegeWatch = new PrivilegeWatch({
20144
21068
  settings: privilegeSettings(config.privileged),
20145
21069
  bus,
20146
- snapshotPath: (0, import_node_path24.join)(PATHS.stateDir, "privileges.json"),
20147
- loginsPath: (0, import_node_path24.join)(PATHS.stateDir, "login-countries.json"),
20148
- cursorPath: (0, import_node_path24.join)(PATHS.stateDir, "sudo-cursor.json"),
21070
+ snapshotPath: (0, import_node_path26.join)(PATHS.stateDir, "privileges.json"),
21071
+ loginsPath: (0, import_node_path26.join)(PATHS.stateDir, "login-countries.json"),
21072
+ cursorPath: (0, import_node_path26.join)(PATHS.stateDir, "sudo-cursor.json"),
20149
21073
  log: logLine
20150
21074
  });
20151
21075
  privilegeWatch.start();
20152
- new AlertDispatcher(bus, config);
21076
+ const torExits = new TorExitList({
21077
+ cachePath: (0, import_node_path26.join)(PATHS.stateDir, "tor-exits.txt"),
21078
+ url: config.remediation?.tor_exit_list_url,
21079
+ log: logLine
21080
+ });
21081
+ const sshIntrusion = new SshIntrusionWatch({
21082
+ bus,
21083
+ manager: remediation,
21084
+ tor: torExits,
21085
+ historyPath: (0, import_node_path26.join)(PATHS.stateDir, "key-logins.json"),
21086
+ keyLoginWatch: config.privileged?.key_login_watch !== false,
21087
+ log: logLine
21088
+ });
21089
+ sshIntrusion.start();
21090
+ const lightningWatch = new LightningWatch({
21091
+ bus,
21092
+ enabled: config.lightning?.enabled !== false,
21093
+ paths: Array.isArray(config.lightning?.log_paths) ? config.lightning.log_paths.map(String) : void 0,
21094
+ log: logLine
21095
+ });
21096
+ lightningWatch.start();
21097
+ let cloudSyncRef = null;
21098
+ new AlertDispatcher(bus, config, { cloudHealthy: () => cloudSyncRef?.healthy ?? false, log: logLine });
21099
+ if (loaded.error) {
21100
+ setTimeout(() => bus.publish({
21101
+ timestamp: /* @__PURE__ */ new Date(),
21102
+ module: "daemon",
21103
+ category: "system",
21104
+ severity: "critical",
21105
+ message: `threatcrushd.conf does not parse; ${loaded.usedLastGood ? "running on the last good copy" : "running on defaults with NO protected list"}: ${loaded.error}`.slice(0, 500),
21106
+ details: { rule_id: "daemon-config-invalid", used_last_good: loaded.usedLastGood }
21107
+ }), 15e3).unref?.();
21108
+ }
20153
21109
  const runsWorker = new RunsWorker(bus, {
20154
21110
  enabled: config.cloud?.enabled !== false && config.cloud?.runs === true,
20155
21111
  scanRoots: Array.isArray(config.cloud?.run_scan_paths) ? config.cloud.run_scan_paths.filter((p) => typeof p === "string") : [],
@@ -20171,14 +21127,15 @@ async function runDaemon() {
20171
21127
  cloudSync = new CloudSync({
20172
21128
  bus,
20173
21129
  version,
20174
- hostname: (0, import_node_os5.hostname)(),
21130
+ hostname: (0, import_node_os6.hostname)(),
20175
21131
  minSeverity,
20176
- spoolPath: (0, import_node_path24.join)(PATHS.stateDir, "cloud-spool.jsonl"),
21132
+ spoolPath: (0, import_node_path26.join)(PATHS.stateDir, "cloud-spool.jsonl"),
20177
21133
  log: logLine,
20178
21134
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
20179
21135
  runHardening: runHardeningChecks
20180
21136
  });
20181
21137
  cloudSync.start();
21138
+ cloudSyncRef = cloudSync;
20182
21139
  remediationConsumer = new RemediationConsumer(remediation, {
20183
21140
  log: logLine,
20184
21141
  restartDaemon,
@@ -20186,7 +21143,15 @@ async function runDaemon() {
20186
21143
  updateNow: () => autoUpdateRef ? autoUpdateRef.check({ force: true, restartDelayMs: 3e3 }) : Promise.resolve("updater not started")
20187
21144
  });
20188
21145
  remediationConsumer.start();
20189
- allowlistSync = new AllowlistSync(remediation, { log: logLine });
21146
+ const torPinned = typeof config.remediation?.block_tor_ssh === "boolean";
21147
+ allowlistSync = new AllowlistSync(remediation, {
21148
+ log: logLine,
21149
+ onOrgSettings: ({ block_tor_ssh }) => {
21150
+ if (torPinned || typeof block_tor_ssh !== "boolean" || block_tor_ssh === remediation.blockTorSsh) return;
21151
+ remediation.setBlockTorSsh(block_tor_ssh);
21152
+ logLine(`[ssh-intrusion] Tor SSH ban ${block_tor_ssh ? "ON" : "OFF"} (org setting from the dashboard)`);
21153
+ }
21154
+ });
20190
21155
  allowlistSync.start();
20191
21156
  const link = currentLink();
20192
21157
  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");
@@ -20197,8 +21162,8 @@ async function runDaemon() {
20197
21162
  const autoUpdate = autoUpdateRef = new AutoUpdate({
20198
21163
  version,
20199
21164
  settings: updateSettings(config.update),
20200
- pkgRoot: (0, import_node_path24.join)(__dirname, ".."),
20201
- statePath: (0, import_node_path24.join)(PATHS.stateDir, "auto-update.json"),
21165
+ pkgRoot: (0, import_node_path26.join)(__dirname, ".."),
21166
+ statePath: (0, import_node_path26.join)(PATHS.stateDir, "auto-update.json"),
20202
21167
  bus,
20203
21168
  log: logLine,
20204
21169
  restartDaemon
@@ -20253,6 +21218,14 @@ async function runDaemon() {
20253
21218
  privilegeWatch.stop();
20254
21219
  } catch {
20255
21220
  }
21221
+ try {
21222
+ sshIntrusion.stop();
21223
+ } catch {
21224
+ }
21225
+ try {
21226
+ lightningWatch.stop();
21227
+ } catch {
21228
+ }
20256
21229
  try {
20257
21230
  await ipc.stop();
20258
21231
  } catch {