@profullstack/threatcrush 0.13.37 → 0.13.39

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
@@ -2022,10 +2022,10 @@ var require_toml = __commonJS({
2022
2022
  });
2023
2023
 
2024
2024
  // src/daemon/index.ts
2025
- var import_node_fs29 = require("fs");
2025
+ var import_node_fs30 = require("fs");
2026
2026
  var import_node_child_process11 = require("child_process");
2027
2027
  var import_node_os5 = require("os");
2028
- var import_node_path22 = require("path");
2028
+ var import_node_path23 = require("path");
2029
2029
  var import_node_util = require("util");
2030
2030
 
2031
2031
  // src/daemon/paths.ts
@@ -2319,6 +2319,16 @@ function pruneEvents(opts = {}) {
2319
2319
  }
2320
2320
  return deleted;
2321
2321
  }
2322
+ function getEventsForIp(ip, sinceMs, limit = 500) {
2323
+ const database = tryDb();
2324
+ if (!database) return [];
2325
+ const rows = database.prepare(`
2326
+ SELECT * FROM events
2327
+ WHERE source_ip = ? AND timestamp >= ?
2328
+ ORDER BY timestamp DESC LIMIT ?
2329
+ `).all(ip, new Date(sinceMs).toISOString(), limit);
2330
+ return rows.map(rowToEvent);
2331
+ }
2322
2332
  function getModuleState(module2, key) {
2323
2333
  const database = db || initStateDB();
2324
2334
  const row = database.prepare(`SELECT value FROM module_state WHERE module = ? AND key = ?`).get(module2, key);
@@ -10924,6 +10934,9 @@ function loadConfig(configPath) {
10924
10934
  threat_feeds: parsed.threat_feeds,
10925
10935
  privileged: parsed.privileged,
10926
10936
  storage: parsed.storage,
10937
+ // TOML's `[abuse-reporter]` parses to a hyphenated key; expose it under
10938
+ // the JS-friendly name the rest of the daemon reads.
10939
+ abuse_reporter: parsed["abuse-reporter"] ?? parsed.abuse_reporter,
10927
10940
  license: parsed.license
10928
10941
  };
10929
10942
  } catch {
@@ -16267,14 +16280,403 @@ var CloudSync = class {
16267
16280
  }
16268
16281
  };
16269
16282
 
16283
+ // src/daemon/workers/abuse-reporter.ts
16284
+ var import_node_crypto5 = require("crypto");
16285
+
16286
+ // src/daemon/workers/abuse-evidence.ts
16287
+ var import_node_net5 = require("net");
16288
+ var NEVER_REPORT_RANGES = [
16289
+ ...DEFAULT_PROTECTED,
16290
+ "100.64.0.0/10",
16291
+ // RFC 6598 carrier-grade NAT
16292
+ "192.0.2.0/24",
16293
+ // TEST-NET-1 (documentation)
16294
+ "198.51.100.0/24",
16295
+ // TEST-NET-2
16296
+ "203.0.113.0/24",
16297
+ // TEST-NET-3
16298
+ "192.0.0.0/24",
16299
+ // IETF protocol assignments
16300
+ "198.18.0.0/15",
16301
+ // benchmarking
16302
+ "224.0.0.0/4",
16303
+ // multicast
16304
+ "240.0.0.0/4",
16305
+ // reserved
16306
+ "::/128",
16307
+ // unspecified
16308
+ "2001:db8::/32",
16309
+ // documentation
16310
+ "100::/64"
16311
+ // discard-only
16312
+ ];
16313
+ var CONNECTION_VERIFIED_CATEGORIES = /* @__PURE__ */ new Set(["auth", "web", "pentest"]);
16314
+ var CONNECTION_VERIFIED_MODULES = ["honeypot", "honey-pot", "webhoneypot"];
16315
+ function summarizeEvidence(events) {
16316
+ const modules = /* @__PURE__ */ new Set();
16317
+ const categories = /* @__PURE__ */ new Set();
16318
+ const ruleIds = /* @__PURE__ */ new Set();
16319
+ let connectionVerified = false;
16320
+ let firstSeen = Infinity;
16321
+ let lastSeen = 0;
16322
+ let total = 0;
16323
+ for (const event of events) {
16324
+ if (event.module === "firewall-rules") continue;
16325
+ total++;
16326
+ modules.add(event.module);
16327
+ categories.add(event.category);
16328
+ const ruleId = event.details?.rule_id;
16329
+ if (typeof ruleId === "string") ruleIds.add(ruleId);
16330
+ const t = event.timestamp.getTime();
16331
+ if (t < firstSeen) firstSeen = t;
16332
+ if (t > lastSeen) lastSeen = t;
16333
+ if (CONNECTION_VERIFIED_CATEGORIES.has(event.category) || CONNECTION_VERIFIED_MODULES.some((m) => event.module.includes(m))) {
16334
+ connectionVerified = true;
16335
+ }
16336
+ }
16337
+ return {
16338
+ signals: modules.size,
16339
+ connectionVerified,
16340
+ firstSeen: firstSeen === Infinity ? 0 : firstSeen,
16341
+ lastSeen,
16342
+ total,
16343
+ categories: [...categories],
16344
+ ruleIds: [...ruleIds]
16345
+ };
16346
+ }
16347
+ function isReportable(ip, evidence, config, now = Date.now()) {
16348
+ if ((0, import_node_net5.isIP)(ip) === 0) return { reportable: false, reason: "not an IP address" };
16349
+ if (isProtected(ip, config.neverReport)) {
16350
+ return { reportable: false, reason: "address is in a never-report range (private/CGNAT/reserved/allowlisted)" };
16351
+ }
16352
+ if (!evidence.connectionVerified) {
16353
+ return { reportable: false, reason: "no connection-verified (L7) signal \u2014 spoofable, not reportable" };
16354
+ }
16355
+ if (evidence.signals < config.minCorroboratingSignals) {
16356
+ return {
16357
+ reportable: false,
16358
+ reason: `only ${evidence.signals} corroborating signal(s), need ${config.minCorroboratingSignals}`
16359
+ };
16360
+ }
16361
+ const age = (now - evidence.firstSeen) / 1e3;
16362
+ if (evidence.firstSeen > 0 && age < config.coolingOffSeconds) {
16363
+ return { reportable: false, reason: "within cooling-off window", waitSeconds: Math.ceil(config.coolingOffSeconds - age) };
16364
+ }
16365
+ return { reportable: true };
16366
+ }
16367
+ function abuseipdbCategories(evidence) {
16368
+ const cats = /* @__PURE__ */ new Set();
16369
+ const rules = evidence.ruleIds.join(" ").toLowerCase();
16370
+ for (const category of evidence.categories) {
16371
+ switch (category) {
16372
+ case "auth":
16373
+ cats.add(18);
16374
+ cats.add(22);
16375
+ break;
16376
+ case "web":
16377
+ cats.add(21);
16378
+ break;
16379
+ case "scan":
16380
+ case "network":
16381
+ cats.add(14);
16382
+ break;
16383
+ case "pentest":
16384
+ cats.add(15);
16385
+ break;
16386
+ default:
16387
+ break;
16388
+ }
16389
+ }
16390
+ if (rules.includes("sql")) cats.add(16);
16391
+ if (rules.includes("xss") || rules.includes("rce") || rules.includes("lfi") || rules.includes("rfi")) cats.add(15);
16392
+ if (rules.includes("bot") || rules.includes("scrape") || rules.includes("paywall")) cats.add(19);
16393
+ if (cats.size === 0) cats.add(15);
16394
+ return [...cats].sort((a, b) => a - b);
16395
+ }
16396
+
16397
+ // src/daemon/workers/abuse-destinations.ts
16398
+ var TIMEOUT_MS = 15e3;
16399
+ function buildComment(evidence) {
16400
+ const hours = Math.max(1, Math.round((evidence.lastSeen - evidence.firstSeen) / 36e5));
16401
+ const kinds = evidence.categories.map((c) => ({ auth: "authentication", web: "web-application", scan: "scanning", network: "network", pentest: "exploitation" })[c] ?? c).join(", ");
16402
+ return `Automated report from ThreatCrush. ${evidence.total} malicious ${kinds || "attack"} event(s) observed from this address across ${evidence.signals} detector(s) over ~${hours}h, confirmed by a completed TCP handshake. Blocked by automated defence. No reply expected.`;
16403
+ }
16404
+ function buildPayload(ip, evidence) {
16405
+ return { ip, evidence, comment: buildComment(evidence), categories: abuseipdbCategories(evidence) };
16406
+ }
16407
+ async function reportToAbuseIPDB(payload, apiKey) {
16408
+ const body = new URLSearchParams({
16409
+ ip: payload.ip,
16410
+ categories: payload.categories.join(","),
16411
+ comment: payload.comment.slice(0, 1024)
16412
+ });
16413
+ try {
16414
+ const res = await fetch("https://api.abuseipdb.com/api/v2/report", {
16415
+ method: "POST",
16416
+ headers: {
16417
+ Key: apiKey,
16418
+ Accept: "application/json",
16419
+ "Content-Type": "application/x-www-form-urlencoded"
16420
+ },
16421
+ body,
16422
+ signal: AbortSignal.timeout(TIMEOUT_MS)
16423
+ });
16424
+ if (res.status === 429) {
16425
+ return { destination: "abuseipdb", ok: false, detail: "rate-limited by AbuseIPDB (daily cap)" };
16426
+ }
16427
+ const json = await res.json().catch(() => ({}));
16428
+ if (!res.ok) {
16429
+ const detail = json.errors?.map((e) => e.detail).filter(Boolean).join("; ") || `HTTP ${res.status}`;
16430
+ return { destination: "abuseipdb", ok: false, detail };
16431
+ }
16432
+ const score = json.data?.abuseConfidenceScore;
16433
+ return { destination: "abuseipdb", ok: true, detail: score !== void 0 ? `confidence ${score}` : "reported" };
16434
+ } catch (err) {
16435
+ return { destination: "abuseipdb", ok: false, detail: err.message };
16436
+ }
16437
+ }
16438
+ async function reportToStopForumSpam(payload, apiKey) {
16439
+ const body = new URLSearchParams({
16440
+ api_key: apiKey,
16441
+ ip: payload.ip,
16442
+ evidence: payload.comment.slice(0, 1e3)
16443
+ });
16444
+ try {
16445
+ const res = await fetch("https://www.stopforumspam.org/add.php", {
16446
+ method: "POST",
16447
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
16448
+ body,
16449
+ signal: AbortSignal.timeout(TIMEOUT_MS)
16450
+ });
16451
+ const text = await res.text().catch(() => "");
16452
+ if (!res.ok) return { destination: "stopforumspam", ok: false, detail: `HTTP ${res.status} ${text.slice(0, 120)}` };
16453
+ const ok = /success|"success"\s*:\s*true/i.test(text);
16454
+ return { destination: "stopforumspam", ok, detail: ok ? "reported" : text.slice(0, 120) || "refused" };
16455
+ } catch (err) {
16456
+ return { destination: "stopforumspam", ok: false, detail: err.message };
16457
+ }
16458
+ }
16459
+ async function dispatch(payload, destinations, keys) {
16460
+ const jobs = [];
16461
+ for (const dest of destinations) {
16462
+ if (dest === "abuseipdb" && keys.abuseipdb) jobs.push(reportToAbuseIPDB(payload, keys.abuseipdb));
16463
+ else if (dest === "stopforumspam" && keys.stopforumspam) jobs.push(reportToStopForumSpam(payload, keys.stopforumspam));
16464
+ }
16465
+ return Promise.all(jobs);
16466
+ }
16467
+
16468
+ // src/daemon/workers/abuse-config.ts
16469
+ function resolveConfig(section) {
16470
+ const s = section ?? {};
16471
+ const dryRun = s.mode === "dry_run" ? true : s.mode === "live" ? false : s.dry_run === true;
16472
+ const neverReport = [...NEVER_REPORT_RANGES, ...s.never_report ?? []];
16473
+ const cooling = parseDuration(s.cooling_off) ?? 3600;
16474
+ return {
16475
+ enabled: s.enabled !== false,
16476
+ dryRun,
16477
+ destinations: s.destinations && s.destinations.length > 0 ? s.destinations : ["abuseipdb"],
16478
+ keys: {
16479
+ abuseipdb: s.abuseipdb_api_key || process.env.ABUSEIPDB_API_KEY || void 0,
16480
+ stopforumspam: s.stopforumspam_api_key || process.env.STOPFORUMSPAM_API_KEY || void 0
16481
+ },
16482
+ minCorroboratingSignals: Math.max(1, s.min_corroborating_signals ?? 2),
16483
+ coolingOffSeconds: cooling,
16484
+ neverReport,
16485
+ maxReportsPerHour: Math.max(1, s.max_reports_per_hour ?? 50),
16486
+ maxPerSourcePerDay: Math.max(1, s.max_reports_per_source_per_day ?? 1)
16487
+ };
16488
+ }
16489
+
16490
+ // src/core/abuse-report-log.ts
16491
+ var import_node_fs21 = require("fs");
16492
+ var import_node_path15 = require("path");
16493
+ var ABUSE_DIRNAME = "abuse-reports";
16494
+ var LOG_FILE = "reports.jsonl";
16495
+ function resolveAbuseDir(dir) {
16496
+ if (dir) return dir;
16497
+ if (process.env.THREATCRUSH_ABUSE_DIR) return process.env.THREATCRUSH_ABUSE_DIR;
16498
+ const system = (0, import_node_path15.join)("/var/lib/threatcrush", ABUSE_DIRNAME);
16499
+ if ((0, import_node_fs21.existsSync)(system)) return system;
16500
+ return (0, import_node_path15.join)(PATHS.stateDir, ABUSE_DIRNAME);
16501
+ }
16502
+ function logPath(dir) {
16503
+ return (0, import_node_path15.join)(resolveAbuseDir(dir), LOG_FILE);
16504
+ }
16505
+ function appendReport(record, dir) {
16506
+ const path = logPath(dir);
16507
+ (0, import_node_fs21.mkdirSync)(resolveAbuseDir(dir), { recursive: true, mode: 493 });
16508
+ (0, import_node_fs21.appendFileSync)(path, `${JSON.stringify(record)}
16509
+ `, { mode: 420 });
16510
+ }
16511
+ function readReports(dir) {
16512
+ const path = logPath(dir);
16513
+ let raw;
16514
+ try {
16515
+ raw = (0, import_node_fs21.readFileSync)(path, "utf-8");
16516
+ } catch {
16517
+ return [];
16518
+ }
16519
+ const out = [];
16520
+ for (const line of raw.split("\n")) {
16521
+ if (!line.trim()) continue;
16522
+ try {
16523
+ out.push(JSON.parse(line));
16524
+ } catch {
16525
+ }
16526
+ }
16527
+ return out;
16528
+ }
16529
+ function currentReports(dir) {
16530
+ const byId = /* @__PURE__ */ new Map();
16531
+ for (const r of readReports(dir)) byId.set(r.id, r);
16532
+ return [...byId.values()].sort((a, b) => b.reported_at.localeCompare(a.reported_at));
16533
+ }
16534
+
16535
+ // src/daemon/workers/abuse-reporter.ts
16536
+ var EVIDENCE_LOOKBACK_MS = 24 * 60 * 60 * 1e3;
16537
+ var PENDING_TTL_MS = 24 * 60 * 60 * 1e3;
16538
+ var AbuseReporter = class {
16539
+ constructor(opts) {
16540
+ this.opts = opts;
16541
+ this.cfg = resolveConfig(opts.section);
16542
+ this.now = opts.now ?? (() => Date.now());
16543
+ this.flushMs = opts.flushMs ?? 6e4;
16544
+ }
16545
+ opts;
16546
+ cfg;
16547
+ now;
16548
+ flushMs;
16549
+ /** Sources seen blocked, awaiting enough evidence / cooling-off, with when first queued. */
16550
+ pending = /* @__PURE__ */ new Map();
16551
+ /** Epoch-ms of live reports sent this process, for the global hourly limit. */
16552
+ recentReports = [];
16553
+ timer = null;
16554
+ flushing = false;
16555
+ onEvent = (event) => this.capture(event);
16556
+ /** Active when it can do something: send live, or at least compute dry-run. */
16557
+ get active() {
16558
+ if (!this.cfg.enabled) return false;
16559
+ if (this.cfg.dryRun) return true;
16560
+ return Boolean(this.cfg.keys.abuseipdb || this.cfg.keys.stopforumspam);
16561
+ }
16562
+ start() {
16563
+ if (!this.cfg.enabled) {
16564
+ this.opts.log("[abuse] reporter disabled by [abuse-reporter] enabled = false");
16565
+ return;
16566
+ }
16567
+ if (!this.active) {
16568
+ this.opts.log(
16569
+ "[abuse] reporter on but inert: no destination API key set (ABUSEIPDB_API_KEY or [abuse-reporter] abuseipdb_api_key). Nothing will be reported."
16570
+ );
16571
+ return;
16572
+ }
16573
+ this.opts.bus.on("event", this.onEvent);
16574
+ const timer = setInterval(() => void this.flush(), this.flushMs);
16575
+ timer.unref?.();
16576
+ this.timer = timer;
16577
+ const mode = this.cfg.dryRun ? "dry_run (nothing sent)" : `live \u2192 ${this.cfg.destinations.join(", ")}`;
16578
+ this.opts.log(
16579
+ `[abuse] reporter ${mode}; bar: >=${this.cfg.minCorroboratingSignals} signals + completed handshake, cooling-off ${Math.round(this.cfg.coolingOffSeconds / 60)}m, <=${this.cfg.maxReportsPerHour}/h, ${this.cfg.maxPerSourcePerDay}/source/day`
16580
+ );
16581
+ }
16582
+ stop() {
16583
+ this.opts.bus.off("event", this.onEvent);
16584
+ if (this.timer) clearInterval(this.timer);
16585
+ this.timer = null;
16586
+ }
16587
+ get queued() {
16588
+ return this.pending.size;
16589
+ }
16590
+ /** Remember a blocked source as a candidate. No network here — that waits for flush. */
16591
+ capture(event) {
16592
+ if (event.module !== "firewall-rules") return;
16593
+ if (event.details?.action !== "block") return;
16594
+ if (event.details?.failed === true) return;
16595
+ const ip = event.source_ip;
16596
+ if (!ip) return;
16597
+ if (!this.pending.has(ip)) this.pending.set(ip, this.now());
16598
+ }
16599
+ /** Walk the candidates; report the ones that clear the bar and the limits. */
16600
+ async flush() {
16601
+ if (this.flushing || !this.active) return;
16602
+ this.flushing = true;
16603
+ try {
16604
+ const now = this.now();
16605
+ this.trimRecent(now);
16606
+ for (const [ip, queuedAt] of [...this.pending]) {
16607
+ if (now - queuedAt > PENDING_TTL_MS) {
16608
+ this.pending.delete(ip);
16609
+ continue;
16610
+ }
16611
+ if (!this.cfg.dryRun && this.recentReports.length >= this.cfg.maxReportsPerHour) break;
16612
+ const evidence = summarizeEvidence(getEventsForIp(ip, now - EVIDENCE_LOOKBACK_MS));
16613
+ const decision = isReportable(ip, evidence, this.cfg, now);
16614
+ if (!decision.reportable) {
16615
+ if (decision.waitSeconds === void 0) this.pending.delete(ip);
16616
+ continue;
16617
+ }
16618
+ if (this.reportedWithin(ip, now, 864e5 * this.cfg.maxPerSourcePerDay)) {
16619
+ this.pending.delete(ip);
16620
+ continue;
16621
+ }
16622
+ this.pending.delete(ip);
16623
+ await this.report(ip, evidence, now);
16624
+ if (!this.cfg.dryRun) this.recentReports.push(now);
16625
+ }
16626
+ } catch (err) {
16627
+ this.opts.log(`[abuse] flush error: ${err.message}`);
16628
+ } finally {
16629
+ this.flushing = false;
16630
+ }
16631
+ }
16632
+ async report(ip, evidence, now) {
16633
+ const payload = buildPayload(ip, evidence);
16634
+ const results = this.cfg.dryRun ? [] : await dispatch(payload, this.cfg.destinations, this.cfg.keys);
16635
+ const record = {
16636
+ id: (0, import_node_crypto5.randomUUID)().slice(0, 8),
16637
+ ip,
16638
+ reported_at: new Date(now).toISOString(),
16639
+ mode: this.cfg.dryRun ? "dry_run" : "live",
16640
+ categories: payload.categories,
16641
+ comment: payload.comment,
16642
+ signals: evidence.signals,
16643
+ total_events: evidence.total,
16644
+ destinations: results
16645
+ };
16646
+ try {
16647
+ appendReport(record, this.opts.dir);
16648
+ } catch (err) {
16649
+ this.opts.log(`[abuse] could not write audit record: ${err.message}`);
16650
+ }
16651
+ if (this.cfg.dryRun) {
16652
+ this.opts.log(`[abuse] [DRY-RUN] would report ${ip} (cats ${payload.categories.join(",")}, ${evidence.signals} signals)`);
16653
+ } else {
16654
+ const summary = results.map((r) => `${r.destination}:${r.ok ? "ok" : "FAIL"} ${r.detail}`).join("; ");
16655
+ this.opts.log(`[abuse] reported ${ip} [${record.id}] \u2192 ${summary || "no destinations"}`);
16656
+ }
16657
+ }
16658
+ trimRecent(now) {
16659
+ const cutoff = now - 36e5;
16660
+ this.recentReports = this.recentReports.filter((t) => t > cutoff);
16661
+ }
16662
+ /** Has this source had a live report inside `windowMs`, per the audit log? */
16663
+ reportedWithin(ip, now, windowMs) {
16664
+ for (const r of currentReports(this.opts.dir)) {
16665
+ if (r.ip !== ip || r.mode !== "live" || r.retracted_at) continue;
16666
+ if (now - Date.parse(r.reported_at) < windowMs) return true;
16667
+ }
16668
+ return false;
16669
+ }
16670
+ };
16671
+
16270
16672
  // src/daemon/workers/remediation-consumer.ts
16271
- var import_node_net6 = require("net");
16673
+ var import_node_net7 = require("net");
16272
16674
 
16273
16675
  // src/daemon/workers/allowlist-sync.ts
16274
- var import_node_net5 = require("net");
16676
+ var import_node_net6 = require("net");
16275
16677
  function isAddressOrCidr(value) {
16276
16678
  const [network, prefix, extra] = value.split("/");
16277
- const family = (0, import_node_net5.isIP)(network);
16679
+ const family = (0, import_node_net6.isIP)(network);
16278
16680
  if (family === 0 || extra !== void 0) return false;
16279
16681
  if (prefix === void 0) return true;
16280
16682
  if (!/^\d{1,3}$/.test(prefix)) return false;
@@ -16423,7 +16825,7 @@ var RemediationConsumer = class {
16423
16825
  try {
16424
16826
  switch (action.action_type) {
16425
16827
  case "block": {
16426
- if ((0, import_node_net6.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
16828
+ if ((0, import_node_net7.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
16427
16829
  let ttlSeconds = this.manager.status().max_ban_seconds;
16428
16830
  if (action.expires_at) {
16429
16831
  const until = Date.parse(action.expires_at);
@@ -16442,7 +16844,7 @@ var RemediationConsumer = class {
16442
16844
  return { status: "executed", dry_run: result.entry?.dry_run === true, executed_at };
16443
16845
  }
16444
16846
  case "unblock": {
16445
- if ((0, import_node_net6.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
16847
+ if ((0, import_node_net7.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
16446
16848
  const wasBanned = this.manager.getBlocklist().some((b) => b.ip === target);
16447
16849
  const result = await this.manager.unban(target, {
16448
16850
  forget: true,
@@ -16487,8 +16889,8 @@ var RemediationConsumer = class {
16487
16889
 
16488
16890
  // src/daemon/workers/auto-update.ts
16489
16891
  var import_node_child_process5 = require("child_process");
16490
- var import_node_fs21 = require("fs");
16491
- var import_node_path15 = require("path");
16892
+ var import_node_fs22 = require("fs");
16893
+ var import_node_path16 = require("path");
16492
16894
  var PKG_NAME = "@profullstack/threatcrush";
16493
16895
  var REGISTRY = `https://registry.npmjs.org/${PKG_NAME}`;
16494
16896
  var DEFAULT_INTERVAL_MS = 6 * 36e5;
@@ -16514,23 +16916,29 @@ function pickUpdate(doc, current, opts) {
16514
16916
  if (!latest) return { version: null, reason: "registry has no latest tag" };
16515
16917
  if (!isNewer(latest, current)) return { version: null, reason: `up to date (${current})` };
16516
16918
  const major = (v) => Number.parseInt(v.replace(/^v/, ""), 10);
16919
+ let best = null;
16920
+ for (const [v, when] of Object.entries(doc.time ?? {})) {
16921
+ if (!/^\d+\.\d+\.\d+$/.test(v)) continue;
16922
+ if (!isNewer(v, current) || isNewer(v, latest)) continue;
16923
+ if (!opts.allowMajor && major(v) !== major(current)) continue;
16924
+ const published = Date.parse(when);
16925
+ if (!Number.isFinite(published) || opts.now - published < opts.minAgeMs) continue;
16926
+ if (!best || isNewer(v, best)) best = v;
16927
+ }
16928
+ if (best) return { version: best };
16517
16929
  if (!opts.allowMajor && major(latest) !== major(current)) {
16518
16930
  return { version: null, reason: `${latest} is a new major; set [update] allow_major = true to take it` };
16519
16931
  }
16520
- const published = Date.parse(doc.time?.[latest] ?? "");
16521
- if (!Number.isFinite(published)) return { version: null, reason: `no publish time for ${latest}` };
16522
- if (opts.now - published < opts.minAgeMs) {
16523
- return { version: null, reason: `${latest} is younger than min_age; waiting` };
16524
- }
16525
- return { version: latest };
16932
+ if (!Number.isFinite(Date.parse(doc.time?.[latest] ?? ""))) return { version: null, reason: `no publish time for ${latest}` };
16933
+ return { version: null, reason: `${latest} is younger than min_age, and nothing older is newer than ${current}; waiting` };
16526
16934
  }
16527
16935
  function installPlan(opts) {
16528
- const expected = `${import_node_path15.sep}lib${import_node_path15.sep}node_modules${import_node_path15.sep}@profullstack${import_node_path15.sep}threatcrush`;
16936
+ const expected = `${import_node_path16.sep}lib${import_node_path16.sep}node_modules${import_node_path16.sep}@profullstack${import_node_path16.sep}threatcrush`;
16529
16937
  if (!opts.pkgRoot.endsWith(expected)) {
16530
16938
  return { kind: "unsupported", reason: `not an npm global install (${opts.pkgRoot}); run \`threatcrush update\`` };
16531
16939
  }
16532
- const nodeBin = (0, import_node_path15.dirname)(opts.execPath);
16533
- const npm = (0, import_node_path15.join)(nodeBin, "npm");
16940
+ const nodeBin = (0, import_node_path16.dirname)(opts.execPath);
16941
+ const npm = (0, import_node_path16.join)(nodeBin, "npm");
16534
16942
  if (!opts.npmExists(npm)) return { kind: "unsupported", reason: `no npm beside ${opts.execPath}` };
16535
16943
  if (!opts.owner) return { kind: "unsupported", reason: `cannot tell who owns ${opts.pkgRoot}` };
16536
16944
  const npmArgs = [npm, "i", "-g", `${PKG_NAME}@${opts.version}`, "--no-fund", "--no-audit"];
@@ -16562,10 +16970,10 @@ function installPlan(opts) {
16562
16970
  }
16563
16971
  function ownerOf(path, passwd = "/etc/passwd") {
16564
16972
  try {
16565
- const st = (0, import_node_fs21.statSync)(path);
16973
+ const st = (0, import_node_fs22.statSync)(path);
16566
16974
  let home = st.uid === 0 ? "/root" : "";
16567
16975
  try {
16568
- for (const line of (0, import_node_fs21.readFileSync)(passwd, "utf8").split("\n")) {
16976
+ for (const line of (0, import_node_fs22.readFileSync)(passwd, "utf8").split("\n")) {
16569
16977
  const f = line.split(":");
16570
16978
  if (Number(f[2]) === st.uid && f[5]) home = f[5];
16571
16979
  }
@@ -16657,7 +17065,7 @@ var AutoUpdate = class {
16657
17065
  minAgeMs: this.opts.settings.minAgeMs,
16658
17066
  now: this.now()
16659
17067
  });
16660
- if (pick.version === null) return this.note(pick.reason, false);
17068
+ if (pick.version === null) return this.note(pick.reason, !pick.reason.startsWith("up to date"));
16661
17069
  const target = pick.version;
16662
17070
  const last = this.lastAttempt();
16663
17071
  if (last?.version === target && this.now() - last.at < RETRY_AFTER_MS) {
@@ -16670,7 +17078,7 @@ var AutoUpdate = class {
16670
17078
  uid: process.getuid?.() ?? -1,
16671
17079
  owner: ownerOf(this.opts.pkgRoot),
16672
17080
  underSystemd: this.opts.underSystemd ?? Boolean(process.env.INVOCATION_ID),
16673
- npmExists: import_node_fs21.existsSync
17081
+ npmExists: import_node_fs22.existsSync
16674
17082
  });
16675
17083
  if (plan.kind === "unsupported") return this.note(`${target} is available but cannot self-install: ${plan.reason}`);
16676
17084
  this.recordAttempt(target);
@@ -16705,7 +17113,7 @@ var AutoUpdate = class {
16705
17113
  }
16706
17114
  lastAttempt() {
16707
17115
  try {
16708
- const v = JSON.parse((0, import_node_fs21.readFileSync)(this.opts.statePath, "utf8"));
17116
+ const v = JSON.parse((0, import_node_fs22.readFileSync)(this.opts.statePath, "utf8"));
16709
17117
  return v.version && typeof v.at === "number" ? { version: v.version, at: v.at } : null;
16710
17118
  } catch {
16711
17119
  return null;
@@ -16713,7 +17121,7 @@ var AutoUpdate = class {
16713
17121
  }
16714
17122
  recordAttempt(version) {
16715
17123
  try {
16716
- (0, import_node_fs21.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
17124
+ (0, import_node_fs22.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
16717
17125
  } catch (err) {
16718
17126
  this.opts.log(`[update] could not record attempt: ${err.message}`);
16719
17127
  }
@@ -16722,9 +17130,9 @@ var AutoUpdate = class {
16722
17130
 
16723
17131
  // src/daemon/workers/threat-feeds.ts
16724
17132
  var import_node_child_process6 = require("child_process");
16725
- var import_node_fs22 = require("fs");
16726
- var import_node_path16 = require("path");
16727
- var import_node_net7 = require("net");
17133
+ var import_node_fs23 = require("fs");
17134
+ var import_node_path17 = require("path");
17135
+ var import_node_net8 = require("net");
16728
17136
  var EGRESS_TABLE = "threatcrush_egress";
16729
17137
  var DEFAULT_REFRESH_MS = 36e5;
16730
17138
  var POLL_MS = 15e3;
@@ -16742,8 +17150,8 @@ function threatFeedSettings(section) {
16742
17150
  };
16743
17151
  }
16744
17152
  function egressRuleset(ips) {
16745
- const v4 = ips.filter((ip) => (0, import_node_net7.isIP)(ip) === 4);
16746
- const v6 = ips.filter((ip) => (0, import_node_net7.isIP)(ip) === 6);
17153
+ const v4 = ips.filter((ip) => (0, import_node_net8.isIP)(ip) === 4);
17154
+ const v6 = ips.filter((ip) => (0, import_node_net8.isIP)(ip) === 6);
16747
17155
  const set = (name, type, items) => ` set ${name} { type ${type};${items.length ? ` elements = { ${items.join(", ")} }` : ""} }`;
16748
17156
  const chain = (name, hook) => [
16749
17157
  ` chain ${name} {`,
@@ -16768,7 +17176,7 @@ function splitAddr(addr) {
16768
17176
  const m = /^\[?(.+?)\]?:(\d+|\*)$/.exec(addr);
16769
17177
  if (!m) return null;
16770
17178
  const ip = m[1].replace(/%.*$/, "").replace(/^::ffff:/i, "");
16771
- return (0, import_node_net7.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
17179
+ return (0, import_node_net8.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
16772
17180
  }
16773
17181
  function parseSs(text) {
16774
17182
  const out = [];
@@ -16894,14 +17302,14 @@ var ThreatFeeds = class {
16894
17302
  */
16895
17303
  writeResolverFiles(set) {
16896
17304
  const domains = this.wantsDomainBlock ? Object.keys(set.domains).sort() : [];
16897
- const dir = this.opts.resolverDir ?? (0, import_node_path16.dirname)(this.opts.cachePath);
17305
+ const dir = this.opts.resolverDir ?? (0, import_node_path17.dirname)(this.opts.cachePath);
16898
17306
  const hooks = this.opts.resolverHooks ?? RESOLVER_HOOKS;
16899
17307
  const write = (name, content) => {
16900
- const path = (0, import_node_path16.join)(dir, name);
17308
+ const path = (0, import_node_path17.join)(dir, name);
16901
17309
  if (this.resolverWritten.get(name) === content) return false;
16902
17310
  try {
16903
- (0, import_node_fs22.writeFileSync)(`${path}.tmp`, content);
16904
- (0, import_node_fs22.renameSync)(`${path}.tmp`, path);
17311
+ (0, import_node_fs23.writeFileSync)(`${path}.tmp`, content);
17312
+ (0, import_node_fs23.renameSync)(`${path}.tmp`, path);
16905
17313
  this.resolverWritten.set(name, content);
16906
17314
  return true;
16907
17315
  } catch (err) {
@@ -16912,11 +17320,11 @@ var ThreatFeeds = class {
16912
17320
  const hostsChanged = write(RESOLVER_FILES.hosts, hostsBlocklist(domains));
16913
17321
  const unboundChanged = write(RESOLVER_FILES.unbound, unboundBlocklist(domains));
16914
17322
  const via = [];
16915
- if ((0, import_node_fs22.existsSync)(hooks.dnsmasq)) {
17323
+ if ((0, import_node_fs23.existsSync)(hooks.dnsmasq)) {
16916
17324
  via.push("dnsmasq");
16917
17325
  if (hostsChanged) this.run("systemctl", ["kill", "-s", "HUP", "dnsmasq.service"]);
16918
17326
  }
16919
- if ((0, import_node_fs22.existsSync)(hooks.unbound)) {
17327
+ if ((0, import_node_fs23.existsSync)(hooks.unbound)) {
16920
17328
  via.push("unbound");
16921
17329
  if (unboundChanged && this.run("unbound-control", ["reload"]) === null) {
16922
17330
  this.run("systemctl", ["reload", "unbound.service"]);
@@ -16977,12 +17385,12 @@ var ThreatFeeds = class {
16977
17385
  };
16978
17386
 
16979
17387
  // src/daemon/workers/privilege-watch.ts
16980
- var import_node_fs23 = require("fs");
16981
- var import_node_path17 = require("path");
17388
+ var import_node_fs24 = require("fs");
17389
+ var import_node_path18 = require("path");
16982
17390
  var import_node_child_process7 = require("child_process");
16983
17391
 
16984
17392
  // src/core/privileges/index.ts
16985
- var import_node_crypto5 = require("crypto");
17393
+ var import_node_crypto6 = require("crypto");
16986
17394
  var ADMIN_GROUPS = ["sudo", "wheel", "admin"];
16987
17395
  function parseUsers(text) {
16988
17396
  const out = [];
@@ -17023,7 +17431,7 @@ function sudoReadsIncluded(name) {
17023
17431
  }
17024
17432
  function keyFingerprint(blobBase64) {
17025
17433
  if (!/^[A-Za-z0-9+/]+=*$/.test(blobBase64)) return null;
17026
- const digest = (0, import_node_crypto5.createHash)("sha256").update(Buffer.from(blobBase64, "base64")).digest("base64");
17434
+ const digest = (0, import_node_crypto6.createHash)("sha256").update(Buffer.from(blobBase64, "base64")).digest("base64");
17027
17435
  return `SHA256:${digest.replace(/=+$/, "")}`;
17028
17436
  }
17029
17437
  function parseAuthorizedKeys(text) {
@@ -17169,31 +17577,31 @@ function countryName(code) {
17169
17577
  var fsIO = {
17170
17578
  readFile: (p) => {
17171
17579
  try {
17172
- return (0, import_node_fs23.readFileSync)(p, "utf-8");
17580
+ return (0, import_node_fs24.readFileSync)(p, "utf-8");
17173
17581
  } catch {
17174
17582
  return null;
17175
17583
  }
17176
17584
  },
17177
17585
  readDir: (p) => {
17178
17586
  try {
17179
- return (0, import_node_fs23.readdirSync)(p);
17587
+ return (0, import_node_fs24.readdirSync)(p);
17180
17588
  } catch {
17181
17589
  return null;
17182
17590
  }
17183
17591
  },
17184
- exists: (p) => (0, import_node_fs23.existsSync)(p)
17592
+ exists: (p) => (0, import_node_fs24.existsSync)(p)
17185
17593
  };
17186
17594
  function readJson(path) {
17187
17595
  try {
17188
- return JSON.parse((0, import_node_fs23.readFileSync)(path, "utf-8"));
17596
+ return JSON.parse((0, import_node_fs24.readFileSync)(path, "utf-8"));
17189
17597
  } catch {
17190
17598
  return null;
17191
17599
  }
17192
17600
  }
17193
17601
  function writeJson(path, value) {
17194
- (0, import_node_fs23.mkdirSync)((0, import_node_path17.dirname)(path), { recursive: true });
17195
- (0, import_node_fs23.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
17196
- (0, import_node_fs23.renameSync)(`${path}.tmp`, path);
17602
+ (0, import_node_fs24.mkdirSync)((0, import_node_path18.dirname)(path), { recursive: true });
17603
+ (0, import_node_fs24.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
17604
+ (0, import_node_fs24.renameSync)(`${path}.tmp`, path);
17197
17605
  }
17198
17606
  function defaultRun3(cmd, args) {
17199
17607
  const res = (0, import_node_child_process7.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 2e4, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
@@ -17349,7 +17757,7 @@ var PrivilegeWatch = class {
17349
17757
  * raised a "new country" alert on its first run; on dev2 it did, at once.
17350
17758
  */
17351
17759
  async backfillLogins() {
17352
- if ((0, import_node_fs23.existsSync)(this.opts.loginsPath)) return;
17760
+ if ((0, import_node_fs24.existsSync)(this.opts.loginsPath)) return;
17353
17761
  const out = this.run("journalctl", ["_COMM=sshd", "_COMM=sshd-session", "--since=-30d", "-o", "cat", "--no-pager"]);
17354
17762
  const byUser = parseAcceptedLogins(out ?? "");
17355
17763
  const ips = [...new Set([...byUser.values()].flatMap((s) => [...s]))];
@@ -17362,7 +17770,7 @@ var PrivilegeWatch = class {
17362
17770
  return;
17363
17771
  }
17364
17772
  }
17365
- if ((0, import_node_fs23.existsSync)(this.opts.loginsPath)) return;
17773
+ if ((0, import_node_fs24.existsSync)(this.opts.loginsPath)) return;
17366
17774
  const at = this.now().toISOString();
17367
17775
  const history = {};
17368
17776
  for (const [user, userIps] of byUser) {
@@ -17574,8 +17982,8 @@ var RuleEngine = class {
17574
17982
  };
17575
17983
 
17576
17984
  // src/daemon/rules/loader.ts
17577
- var import_node_fs24 = require("fs");
17578
- var import_node_path18 = require("path");
17985
+ var import_node_fs25 = require("fs");
17986
+ var import_node_path19 = require("path");
17579
17987
 
17580
17988
  // src/daemon/rules/default-rules.ts
17581
17989
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -17976,11 +18384,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
17976
18384
  function loadAllRules(customDir) {
17977
18385
  const rules = [...DEFAULT_RULES];
17978
18386
  const dir = customDir || RULES_DIR;
17979
- if ((0, import_node_fs24.existsSync)(dir)) {
17980
- const files = (0, import_node_fs24.readdirSync)(dir).filter((f) => f.endsWith(".json"));
18387
+ if ((0, import_node_fs25.existsSync)(dir)) {
18388
+ const files = (0, import_node_fs25.readdirSync)(dir).filter((f) => f.endsWith(".json"));
17981
18389
  for (const file of files) {
17982
18390
  try {
17983
- const raw = (0, import_node_fs24.readFileSync)((0, import_node_path18.join)(dir, file), "utf-8");
18391
+ const raw = (0, import_node_fs25.readFileSync)((0, import_node_path19.join)(dir, file), "utf-8");
17984
18392
  const parsed = JSON.parse(raw);
17985
18393
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
17986
18394
  for (const rule of customRules) {
@@ -18012,23 +18420,23 @@ function loadAllRules(customDir) {
18012
18420
 
18013
18421
  // src/daemon/firewall/adapters.ts
18014
18422
  var import_node_child_process8 = require("child_process");
18015
- var import_node_fs25 = require("fs");
18016
- var import_node_path19 = require("path");
18017
- var import_node_net8 = require("net");
18423
+ var import_node_fs26 = require("fs");
18424
+ var import_node_path20 = require("path");
18425
+ var import_node_net9 = require("net");
18018
18426
  function assertValidFirewallIp(ip) {
18019
- if ((0, import_node_net8.isIP)(ip) !== 4) {
18427
+ if ((0, import_node_net9.isIP)(ip) !== 4) {
18020
18428
  throw new Error(`Invalid IPv4 address: ${ip}`);
18021
18429
  }
18022
18430
  }
18023
18431
  function assertBannableIp(ip) {
18024
- if ((0, import_node_net8.isIP)(ip) === 0) {
18432
+ if ((0, import_node_net9.isIP)(ip) === 0) {
18025
18433
  throw new Error(`Invalid IP address: ${ip}`);
18026
18434
  }
18027
18435
  }
18028
18436
  function writeIfAbsent(path, contents) {
18029
- (0, import_node_fs25.mkdirSync)((0, import_node_path19.dirname)(path), { recursive: true });
18437
+ (0, import_node_fs26.mkdirSync)((0, import_node_path20.dirname)(path), { recursive: true });
18030
18438
  try {
18031
- (0, import_node_fs25.writeFileSync)(path, contents, { flag: "wx" });
18439
+ (0, import_node_fs26.writeFileSync)(path, contents, { flag: "wx" });
18032
18440
  } catch (err) {
18033
18441
  if (err.code !== "EEXIST") throw err;
18034
18442
  }
@@ -18127,7 +18535,7 @@ var Fail2banAdapter = class {
18127
18535
  const status = this.client(["status", this.jail]);
18128
18536
  const line = status.split("\n").find((l) => /Banned IP list:/i.test(l));
18129
18537
  if (!line) return [];
18130
- return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net8.isIP)(s) !== 0);
18538
+ return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net9.isIP)(s) !== 0);
18131
18539
  } catch {
18132
18540
  return [];
18133
18541
  }
@@ -18137,10 +18545,10 @@ var Fail2banAdapter = class {
18137
18545
  function parseBannedList(output) {
18138
18546
  const found = [];
18139
18547
  for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
18140
- if ((0, import_node_net8.isIP)(match[1]) !== 0) found.push(match[1]);
18548
+ if ((0, import_node_net9.isIP)(match[1]) !== 0) found.push(match[1]);
18141
18549
  }
18142
18550
  if (found.length > 0) return found;
18143
- return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net8.isIP)(s) !== 0);
18551
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net9.isIP)(s) !== 0);
18144
18552
  }
18145
18553
  var NftablesAdapter = class {
18146
18554
  name = "nftables";
@@ -18287,9 +18695,9 @@ function detectFirewallAdapter(backend = "auto") {
18287
18695
  }
18288
18696
 
18289
18697
  // src/daemon/firewall/remediation.ts
18290
- var import_node_fs26 = require("fs");
18698
+ var import_node_fs27 = require("fs");
18291
18699
  var import_node_child_process9 = require("child_process");
18292
- var import_node_net9 = require("net");
18700
+ var import_node_net10 = require("net");
18293
18701
 
18294
18702
  // src/daemon/firewall/crawlers.ts
18295
18703
  var import_node_dns = require("dns");
@@ -18298,12 +18706,12 @@ var systemResolver = {
18298
18706
  reverse: (ip) => import_node_dns.promises.reverse(ip),
18299
18707
  lookup: async (host) => (await import_node_dns.promises.lookup(host, { all: true })).map((a) => a.address)
18300
18708
  };
18301
- var TIMEOUT_MS = 2e3;
18709
+ var TIMEOUT_MS2 = 2e3;
18302
18710
  var CACHE_MS = 6 * 36e5;
18303
18711
  function withTimeout(p) {
18304
18712
  return Promise.race([
18305
18713
  p,
18306
- new Promise((_, reject) => setTimeout(() => reject(new Error("dns timeout")), TIMEOUT_MS).unref())
18714
+ new Promise((_, reject) => setTimeout(() => reject(new Error("dns timeout")), TIMEOUT_MS2).unref())
18307
18715
  ]);
18308
18716
  }
18309
18717
  function inCrawlerDomain(host) {
@@ -18356,19 +18764,19 @@ var defaultDiscovery = {
18356
18764
  const snapshot = takeSnapshot({
18357
18765
  readFile: (p) => {
18358
18766
  try {
18359
- return (0, import_node_fs26.readFileSync)(p, "utf-8");
18767
+ return (0, import_node_fs27.readFileSync)(p, "utf-8");
18360
18768
  } catch {
18361
18769
  return null;
18362
18770
  }
18363
18771
  },
18364
18772
  readDir: (p) => {
18365
18773
  try {
18366
- return (0, import_node_fs26.readdirSync)(p);
18774
+ return (0, import_node_fs27.readdirSync)(p);
18367
18775
  } catch {
18368
18776
  return null;
18369
18777
  }
18370
18778
  },
18371
- exists: (p) => (0, import_node_fs26.existsSync)(p)
18779
+ exists: (p) => (0, import_node_fs27.existsSync)(p)
18372
18780
  });
18373
18781
  const out = /* @__PURE__ */ new Set();
18374
18782
  for (const keys of Object.values(snapshot.keys)) {
@@ -18503,7 +18911,7 @@ var RemediationManager = class {
18503
18911
  if (remediation?.action !== "block") return;
18504
18912
  }
18505
18913
  const ip = event.source_ip;
18506
- if (!ip || (0, import_node_net9.isIP)(ip) === 0) return;
18914
+ if (!ip || (0, import_node_net10.isIP)(ip) === 0) return;
18507
18915
  if (this.isAllowlisted(ip)) return;
18508
18916
  if (this.blocklist.some((b) => b.ip === ip)) return;
18509
18917
  if (this.config.spare_verified_crawlers) {
@@ -18522,7 +18930,7 @@ var RemediationManager = class {
18522
18930
  * 4th offence and so on, clamped to `max_ban_seconds`.
18523
18931
  */
18524
18932
  async ban(ip, reason, opts = {}) {
18525
- if ((0, import_node_net9.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
18933
+ if ((0, import_node_net10.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
18526
18934
  if (this.isAllowlisted(ip)) {
18527
18935
  return { ok: false, error: `${ip} is protected and can never be blocked` };
18528
18936
  }
@@ -18783,7 +19191,7 @@ var RemediationManager = class {
18783
19191
  if (saved && typeof saved === "object" && this.config.protect_recent_operators) {
18784
19192
  const cutoff = Date.now() - this.config.operator_memory_seconds * 1e3;
18785
19193
  for (const [ip, at] of Object.entries(saved)) {
18786
- if (typeof at !== "number" || at < cutoff || !(0, import_node_net9.isIP)(ip)) continue;
19194
+ if (typeof at !== "number" || at < cutoff || !(0, import_node_net10.isIP)(ip)) continue;
18787
19195
  this.operators[ip] = at;
18788
19196
  if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
18789
19197
  }
@@ -18807,7 +19215,7 @@ var RemediationManager = class {
18807
19215
  }
18808
19216
  logLine(line) {
18809
19217
  try {
18810
- (0, import_node_fs26.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
19218
+ (0, import_node_fs27.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
18811
19219
  `);
18812
19220
  } catch {
18813
19221
  }
@@ -18846,15 +19254,15 @@ function remediationSettings(section) {
18846
19254
  }
18847
19255
 
18848
19256
  // src/daemon/watchdog-service.ts
18849
- var import_node_fs28 = require("fs");
18850
- var import_node_path21 = require("path");
19257
+ var import_node_fs29 = require("fs");
19258
+ var import_node_path22 = require("path");
18851
19259
 
18852
19260
  // src/core/watchdog.ts
18853
- var import_node_fs27 = require("fs");
18854
- var import_node_crypto6 = require("crypto");
18855
- var import_node_path20 = require("path");
19261
+ var import_node_fs28 = require("fs");
19262
+ var import_node_crypto7 = require("crypto");
19263
+ var import_node_path21 = require("path");
18856
19264
  var WATCHDOG_DIRNAME = "watchdog";
18857
- var LOG_FILE = "attacks.jsonl";
19265
+ var LOG_FILE2 = "attacks.jsonl";
18858
19266
  var ROTATED_FILE = "attacks.1.jsonl";
18859
19267
  var ROTATE_BYTES = 50 * 1024 * 1024;
18860
19268
  var SEEN_LIMIT = 5e3;
@@ -18892,7 +19300,7 @@ function signatureOf(r) {
18892
19300
  return ["msg", r.module, shape].join("|");
18893
19301
  }
18894
19302
  function findingId(signature) {
18895
- return (0, import_node_crypto6.createHash)("sha1").update(signature).digest("hex").slice(0, 10);
19303
+ return (0, import_node_crypto7.createHash)("sha1").update(signature).digest("hex").slice(0, 10);
18896
19304
  }
18897
19305
  function toRecord(event) {
18898
19306
  const d = event.details ?? {};
@@ -18941,12 +19349,12 @@ var WatchdogLog = class {
18941
19349
  stats = { logged: 0, answered: 0, errored: 0 };
18942
19350
  constructor(dir, options = {}) {
18943
19351
  this.dir = dir;
18944
- this.file = (0, import_node_path20.join)(dir, LOG_FILE);
19352
+ this.file = (0, import_node_path21.join)(dir, LOG_FILE2);
18945
19353
  this.shareGid = options.shareGid;
18946
- (0, import_node_fs27.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
19354
+ (0, import_node_fs28.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
18947
19355
  if (this.shareGid !== void 0) {
18948
- (0, import_node_fs27.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
18949
- (0, import_node_fs27.chmodSync)(dir, 1528);
19356
+ (0, import_node_fs28.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
19357
+ (0, import_node_fs28.chmodSync)(dir, 1528);
18950
19358
  }
18951
19359
  for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
18952
19360
  }
@@ -18975,16 +19383,16 @@ var WatchdogLog = class {
18975
19383
  const chunk = this.buffer.join("\n") + "\n";
18976
19384
  this.buffer = [];
18977
19385
  try {
18978
- if ((0, import_node_fs27.statSync)(this.file).size > ROTATE_BYTES) {
18979
- (0, import_node_fs27.renameSync)(this.file, (0, import_node_path20.join)(this.dir, ROTATED_FILE));
19386
+ if ((0, import_node_fs28.statSync)(this.file).size > ROTATE_BYTES) {
19387
+ (0, import_node_fs28.renameSync)(this.file, (0, import_node_path21.join)(this.dir, ROTATED_FILE));
18980
19388
  }
18981
19389
  } catch {
18982
19390
  }
18983
- (0, import_node_fs27.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
19391
+ (0, import_node_fs28.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
18984
19392
  if (this.shareGid !== void 0) {
18985
19393
  try {
18986
- (0, import_node_fs27.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
18987
- (0, import_node_fs27.chmodSync)(this.file, 432);
19394
+ (0, import_node_fs28.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
19395
+ (0, import_node_fs28.chmodSync)(this.file, 432);
18988
19396
  } catch {
18989
19397
  }
18990
19398
  }
@@ -19005,21 +19413,21 @@ function parseLines(text) {
19005
19413
  function readTail(file, bytes) {
19006
19414
  let fd;
19007
19415
  try {
19008
- fd = (0, import_node_fs27.openSync)(file, "r");
19416
+ fd = (0, import_node_fs28.openSync)(file, "r");
19009
19417
  } catch (err) {
19010
19418
  if (err.code === "ENOENT") return [];
19011
19419
  throw err;
19012
19420
  }
19013
19421
  try {
19014
- const size = (0, import_node_fs27.fstatSync)(fd).size;
19422
+ const size = (0, import_node_fs28.fstatSync)(fd).size;
19015
19423
  const start = Math.max(0, size - bytes);
19016
19424
  const buf = Buffer.alloc(size - start);
19017
- (0, import_node_fs27.readSync)(fd, buf, 0, buf.length, start);
19425
+ (0, import_node_fs28.readSync)(fd, buf, 0, buf.length, start);
19018
19426
  let text = buf.toString("utf8");
19019
19427
  if (start > 0) text = text.slice(text.indexOf("\n") + 1);
19020
19428
  return parseLines(text);
19021
19429
  } finally {
19022
- (0, import_node_fs27.closeSync)(fd);
19430
+ (0, import_node_fs28.closeSync)(fd);
19023
19431
  }
19024
19432
  }
19025
19433
 
@@ -19028,13 +19436,13 @@ function defaultShareGid() {
19028
19436
  const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
19029
19437
  if (!isRoot2) return void 0;
19030
19438
  try {
19031
- return (0, import_node_fs28.statSync)("/var/log/auth.log").gid;
19439
+ return (0, import_node_fs29.statSync)("/var/log/auth.log").gid;
19032
19440
  } catch {
19033
19441
  return void 0;
19034
19442
  }
19035
19443
  }
19036
19444
  function startWatchdog(opts) {
19037
- const dir = opts.config?.dir ?? (0, import_node_path21.join)(opts.stateDir, WATCHDOG_DIRNAME);
19445
+ const dir = opts.config?.dir ?? (0, import_node_path22.join)(opts.stateDir, WATCHDOG_DIRNAME);
19038
19446
  const base = { dir, logged: 0, answered: 0, errored: 0 };
19039
19447
  if (opts.config?.enabled === false) {
19040
19448
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -19141,7 +19549,7 @@ function daemonNodeProblem(version) {
19141
19549
  // src/daemon/index.ts
19142
19550
  function readVersion2() {
19143
19551
  try {
19144
- const pkg = JSON.parse((0, import_node_fs29.readFileSync)((0, import_node_path22.join)(__dirname, "..", "package.json"), "utf-8"));
19552
+ const pkg = JSON.parse((0, import_node_fs30.readFileSync)((0, import_node_path23.join)(__dirname, "..", "package.json"), "utf-8"));
19145
19553
  return pkg.version || "0.0.0";
19146
19554
  } catch {
19147
19555
  return "0.0.0";
@@ -19150,7 +19558,7 @@ function readVersion2() {
19150
19558
  async function runHardeningChecks() {
19151
19559
  const { stdout } = await (0, import_node_util.promisify)(import_node_child_process11.execFile)(
19152
19560
  process.execPath,
19153
- [(0, import_node_path22.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
19561
+ [(0, import_node_path23.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
19154
19562
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
19155
19563
  );
19156
19564
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -19164,7 +19572,7 @@ async function runHardeningChecks() {
19164
19572
  async function runPatchCheck() {
19165
19573
  const { stdout } = await (0, import_node_util.promisify)(import_node_child_process11.execFile)(
19166
19574
  process.execPath,
19167
- [(0, import_node_path22.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
19575
+ [(0, import_node_path23.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
19168
19576
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
19169
19577
  );
19170
19578
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -19172,7 +19580,7 @@ async function runPatchCheck() {
19172
19580
  }
19173
19581
  function logLine(line) {
19174
19582
  try {
19175
- (0, import_node_fs29.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
19583
+ (0, import_node_fs30.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
19176
19584
  `);
19177
19585
  } catch {
19178
19586
  }
@@ -19214,7 +19622,7 @@ async function runDaemon() {
19214
19622
  } catch (err) {
19215
19623
  logLine(`[daemon] state db unavailable: ${err.message}`);
19216
19624
  }
19217
- const config = loadConfig((0, import_node_fs29.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
19625
+ const config = loadConfig((0, import_node_fs30.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
19218
19626
  configureAttackDetection(config.detection);
19219
19627
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
19220
19628
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -19278,7 +19686,7 @@ async function runDaemon() {
19278
19686
  const threatFeeds = new ThreatFeeds({
19279
19687
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
19280
19688
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
19281
- cachePath: (0, import_node_path22.join)(PATHS.stateDir, "threat-feeds.json"),
19689
+ cachePath: (0, import_node_path23.join)(PATHS.stateDir, "threat-feeds.json"),
19282
19690
  bus,
19283
19691
  log: logLine
19284
19692
  });
@@ -19286,9 +19694,9 @@ async function runDaemon() {
19286
19694
  const privilegeWatch = new PrivilegeWatch({
19287
19695
  settings: privilegeSettings(config.privileged),
19288
19696
  bus,
19289
- snapshotPath: (0, import_node_path22.join)(PATHS.stateDir, "privileges.json"),
19290
- loginsPath: (0, import_node_path22.join)(PATHS.stateDir, "login-countries.json"),
19291
- cursorPath: (0, import_node_path22.join)(PATHS.stateDir, "sudo-cursor.json"),
19697
+ snapshotPath: (0, import_node_path23.join)(PATHS.stateDir, "privileges.json"),
19698
+ loginsPath: (0, import_node_path23.join)(PATHS.stateDir, "login-countries.json"),
19699
+ cursorPath: (0, import_node_path23.join)(PATHS.stateDir, "sudo-cursor.json"),
19292
19700
  log: logLine
19293
19701
  });
19294
19702
  privilegeWatch.start();
@@ -19311,7 +19719,7 @@ async function runDaemon() {
19311
19719
  version,
19312
19720
  hostname: (0, import_node_os5.hostname)(),
19313
19721
  minSeverity,
19314
- spoolPath: (0, import_node_path22.join)(PATHS.stateDir, "cloud-spool.jsonl"),
19722
+ spoolPath: (0, import_node_path23.join)(PATHS.stateDir, "cloud-spool.jsonl"),
19315
19723
  log: logLine,
19316
19724
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
19317
19725
  runHardening: runHardeningChecks
@@ -19324,12 +19732,14 @@ async function runDaemon() {
19324
19732
  const link = currentLink();
19325
19733
  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");
19326
19734
  }
19735
+ const abuseReporter = new AbuseReporter({ bus, section: config.abuse_reporter, log: logLine });
19736
+ abuseReporter.start();
19327
19737
  const watchdog = startWatchdog({ bus, config: config.watchdog, stateDir: PATHS.stateDir, log: logLine });
19328
19738
  const autoUpdate = new AutoUpdate({
19329
19739
  version,
19330
19740
  settings: updateSettings(config.update),
19331
- pkgRoot: (0, import_node_path22.join)(__dirname, ".."),
19332
- statePath: (0, import_node_path22.join)(PATHS.stateDir, "auto-update.json"),
19741
+ pkgRoot: (0, import_node_path23.join)(__dirname, ".."),
19742
+ statePath: (0, import_node_path23.join)(PATHS.stateDir, "auto-update.json"),
19333
19743
  bus,
19334
19744
  log: logLine,
19335
19745
  restartDaemon
@@ -19360,6 +19770,10 @@ async function runDaemon() {
19360
19770
  await cloudSync?.stop();
19361
19771
  } catch {
19362
19772
  }
19773
+ try {
19774
+ abuseReporter.stop();
19775
+ } catch {
19776
+ }
19363
19777
  try {
19364
19778
  await moduleHost.stop();
19365
19779
  } catch {