@profullstack/threatcrush 0.13.20 → 0.13.22

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
@@ -63,9 +63,9 @@ var require_parser = __commonJS({
63
63
  this.ii = 0;
64
64
  this.state = new State(this.parseStart);
65
65
  }
66
- parse(str2) {
67
- if (str2.length === 0 || str2.length == null) return;
68
- this._buf = String(str2);
66
+ parse(str3) {
67
+ if (str3.length === 0 || str3.length == null) return;
68
+ this._buf = String(str3);
69
69
  this.ii = -1;
70
70
  this.char = -1;
71
71
  let getNext;
@@ -1612,16 +1612,16 @@ var require_parse_string = __commonJS({
1612
1612
  module2.exports = parseString;
1613
1613
  var TOMLParser = require_toml_parser();
1614
1614
  var prettyError = require_parse_pretty_error();
1615
- function parseString(str2) {
1616
- if (global.Buffer && global.Buffer.isBuffer(str2)) {
1617
- str2 = str2.toString("utf8");
1615
+ function parseString(str3) {
1616
+ if (global.Buffer && global.Buffer.isBuffer(str3)) {
1617
+ str3 = str3.toString("utf8");
1618
1618
  }
1619
1619
  const parser = new TOMLParser();
1620
1620
  try {
1621
- parser.parse(str2);
1621
+ parser.parse(str3);
1622
1622
  return parser.finish();
1623
1623
  } catch (err) {
1624
- throw prettyError(err, str2);
1624
+ throw prettyError(err, str3);
1625
1625
  }
1626
1626
  }
1627
1627
  }
@@ -1634,7 +1634,7 @@ var require_parse_async = __commonJS({
1634
1634
  module2.exports = parseAsync;
1635
1635
  var TOMLParser = require_toml_parser();
1636
1636
  var prettyError = require_parse_pretty_error();
1637
- function parseAsync(str2, opts) {
1637
+ function parseAsync(str3, opts) {
1638
1638
  if (!opts) opts = {};
1639
1639
  const index = 0;
1640
1640
  const blocksize = opts.blocksize || 40960;
@@ -1643,18 +1643,18 @@ var require_parse_async = __commonJS({
1643
1643
  setImmediate(parseAsyncNext, index, blocksize, resolve3, reject);
1644
1644
  });
1645
1645
  function parseAsyncNext(index2, blocksize2, resolve3, reject) {
1646
- if (index2 >= str2.length) {
1646
+ if (index2 >= str3.length) {
1647
1647
  try {
1648
1648
  return resolve3(parser.finish());
1649
1649
  } catch (err) {
1650
- return reject(prettyError(err, str2));
1650
+ return reject(prettyError(err, str3));
1651
1651
  }
1652
1652
  }
1653
1653
  try {
1654
- parser.parse(str2.slice(index2, index2 + blocksize2));
1654
+ parser.parse(str3.slice(index2, index2 + blocksize2));
1655
1655
  setImmediate(parseAsyncNext, index2 + blocksize2, blocksize2, resolve3, reject);
1656
1656
  } catch (err) {
1657
- reject(prettyError(err, str2));
1657
+ reject(prettyError(err, str3));
1658
1658
  }
1659
1659
  }
1660
1660
  }
@@ -1860,22 +1860,22 @@ var require_stringify = __commonJS({
1860
1860
  return stringifyBasicString(keyStr);
1861
1861
  }
1862
1862
  }
1863
- function stringifyBasicString(str2) {
1864
- return '"' + escapeString(str2).replace(/"/g, '\\"') + '"';
1863
+ function stringifyBasicString(str3) {
1864
+ return '"' + escapeString(str3).replace(/"/g, '\\"') + '"';
1865
1865
  }
1866
- function stringifyLiteralString(str2) {
1867
- return "'" + str2 + "'";
1866
+ function stringifyLiteralString(str3) {
1867
+ return "'" + str3 + "'";
1868
1868
  }
1869
- function numpad(num, str2) {
1870
- while (str2.length < num) str2 = "0" + str2;
1871
- return str2;
1869
+ function numpad(num, str3) {
1870
+ while (str3.length < num) str3 = "0" + str3;
1871
+ return str3;
1872
1872
  }
1873
- function escapeString(str2) {
1874
- return str2.replace(/\\/g, "\\\\").replace(/[\b]/g, "\\b").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\f/g, "\\f").replace(/\r/g, "\\r").replace(/([\u0000-\u001f\u007f])/, (c) => "\\u" + numpad(4, c.codePointAt(0).toString(16)));
1873
+ function escapeString(str3) {
1874
+ return str3.replace(/\\/g, "\\\\").replace(/[\b]/g, "\\b").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\f/g, "\\f").replace(/\r/g, "\\r").replace(/([\u0000-\u001f\u007f])/, (c) => "\\u" + numpad(4, c.codePointAt(0).toString(16)));
1875
1875
  }
1876
- function stringifyMultilineString(str2) {
1877
- let escaped = str2.split(/\n/).map((str3) => {
1878
- return escapeString(str3).replace(/"(?="")/g, '\\"');
1876
+ function stringifyMultilineString(str3) {
1877
+ let escaped = str3.split(/\n/).map((str4) => {
1878
+ return escapeString(str4).replace(/"(?="")/g, '\\"');
1879
1879
  }).join("\n");
1880
1880
  if (escaped.slice(-1) === '"') escaped += "\\\n";
1881
1881
  return '"""\n' + escaped + '"""';
@@ -2022,10 +2022,10 @@ var require_toml = __commonJS({
2022
2022
  });
2023
2023
 
2024
2024
  // src/daemon/index.ts
2025
- var import_node_fs21 = require("fs");
2025
+ var import_node_fs24 = require("fs");
2026
2026
  var import_node_child_process7 = require("child_process");
2027
2027
  var import_node_os5 = require("os");
2028
- var import_node_path16 = require("path");
2028
+ var import_node_path18 = require("path");
2029
2029
  var import_node_util = require("util");
2030
2030
 
2031
2031
  // src/daemon/paths.ts
@@ -2254,35 +2254,70 @@ function getRecentEvents(limit = 50) {
2254
2254
  `).all(limit);
2255
2255
  return rows.map(rowToEvent);
2256
2256
  }
2257
+ var RECENT_WINDOW = 2e5;
2258
+ function eventsEverRecorded(database) {
2259
+ const row = database.prepare(`SELECT seq FROM sqlite_sequence WHERE name = 'events'`).get();
2260
+ return row?.seq ?? 0;
2261
+ }
2257
2262
  function getEventCount(since) {
2258
2263
  const database = tryDb();
2259
2264
  if (!database) return 0;
2260
2265
  if (since) {
2261
- return database.prepare(`SELECT COUNT(*) as count FROM events WHERE timestamp >= ?`).get(since.toISOString()).count;
2266
+ return database.prepare(
2267
+ `SELECT COUNT(*) as count FROM (SELECT timestamp FROM events ORDER BY id DESC LIMIT ?) WHERE timestamp >= ?`
2268
+ ).get(RECENT_WINDOW, since.toISOString()).count;
2262
2269
  }
2263
- return database.prepare(`SELECT COUNT(*) as count FROM events`).get().count;
2270
+ return eventsEverRecorded(database);
2264
2271
  }
2265
2272
  function getThreatCount(since) {
2266
2273
  const database = tryDb();
2267
2274
  if (!database) return 0;
2268
2275
  const severities = "('medium','high','critical')";
2269
- if (since) {
2270
- return database.prepare(
2271
- `SELECT COUNT(*) as count FROM events WHERE severity IN ${severities} AND timestamp >= ?`
2272
- ).get(since.toISOString()).count;
2273
- }
2276
+ const cutoff = since ? since.toISOString() : "";
2274
2277
  return database.prepare(
2275
- `SELECT COUNT(*) as count FROM events WHERE severity IN ${severities}`
2276
- ).get().count;
2278
+ `SELECT COUNT(*) as count FROM (SELECT severity, timestamp FROM events ORDER BY id DESC LIMIT ?)
2279
+ WHERE severity IN ${severities} AND timestamp >= ?`
2280
+ ).get(RECENT_WINDOW, cutoff).count;
2277
2281
  }
2278
2282
  function getTopSources(limit = 10) {
2279
2283
  const database = tryDb();
2280
2284
  if (!database) return [];
2281
2285
  return database.prepare(`
2282
- SELECT source_ip as ip, COUNT(*) as count FROM events
2286
+ SELECT source_ip as ip, COUNT(*) as count
2287
+ FROM (SELECT source_ip FROM events ORDER BY id DESC LIMIT ?)
2283
2288
  WHERE source_ip IS NOT NULL
2284
2289
  GROUP BY source_ip ORDER BY count DESC LIMIT ?
2285
- `).all(limit);
2290
+ `).all(RECENT_WINDOW, limit);
2291
+ }
2292
+ var DEFAULT_EVENT_RETENTION_SECONDS = 14 * 86400;
2293
+ var DEFAULT_MAX_EVENTS = 2e6;
2294
+ function pruneEvents(opts = {}) {
2295
+ const database = tryDb();
2296
+ if (!database) return 0;
2297
+ const retention = opts.retentionSeconds ?? DEFAULT_EVENT_RETENTION_SECONDS;
2298
+ const maxEvents = opts.maxEvents ?? DEFAULT_MAX_EVENTS;
2299
+ const batch = opts.batch ?? 5e3;
2300
+ const maxBatches = opts.maxBatches ?? 20;
2301
+ const cutoff = new Date((opts.now ?? Date.now()) - retention * 1e3).toISOString();
2302
+ const byAge = database.prepare(
2303
+ `DELETE FROM events WHERE id IN (SELECT id FROM events WHERE timestamp < ? ORDER BY id LIMIT ?)`
2304
+ );
2305
+ const lowest = database.prepare(`SELECT MIN(id) as lo, MAX(id) as hi FROM events`);
2306
+ const byCount = database.prepare(`DELETE FROM events WHERE id < ?`);
2307
+ let deleted = 0;
2308
+ for (let i = 0; i < maxBatches; i++) {
2309
+ const n = byAge.run(cutoff, batch).changes;
2310
+ deleted += n;
2311
+ if (n < batch) break;
2312
+ }
2313
+ for (let i = 0; i < maxBatches; i++) {
2314
+ const { lo, hi } = lowest.get();
2315
+ if (lo === null || hi === null || hi - lo + 1 <= maxEvents) break;
2316
+ const n = byCount.run(Math.min(lo + batch, hi - maxEvents + 1)).changes;
2317
+ deleted += n;
2318
+ if (n === 0) break;
2319
+ }
2320
+ return deleted;
2286
2321
  }
2287
2322
  function getModuleState(module2, key) {
2288
2323
  const database = db || initStateDB();
@@ -2365,10 +2400,11 @@ function formatDuration(seconds) {
2365
2400
 
2366
2401
  // src/daemon/ipc-server.ts
2367
2402
  var IpcServer = class {
2368
- constructor(version, moduleHost, remediation) {
2403
+ constructor(version, moduleHost, remediation, watchdog) {
2369
2404
  this.version = version;
2370
2405
  this.moduleHost = moduleHost;
2371
2406
  this.remediation = remediation;
2407
+ this.watchdog = watchdog;
2372
2408
  bus.on("event", (event) => {
2373
2409
  this.counters.events++;
2374
2410
  if (event.severity === "medium" || event.severity === "high" || event.severity === "critical") {
@@ -2386,6 +2422,7 @@ var IpcServer = class {
2386
2422
  version;
2387
2423
  moduleHost;
2388
2424
  remediation;
2425
+ watchdog;
2389
2426
  server = null;
2390
2427
  clients = /* @__PURE__ */ new Map();
2391
2428
  nextClientId = 1;
@@ -2510,7 +2547,8 @@ var IpcServer = class {
2510
2547
  },
2511
2548
  modules: this.moduleHost.summary(),
2512
2549
  counters: { ...this.counters },
2513
- stateDb: isStateDbAvailable()
2550
+ stateDb: isStateDbAvailable(),
2551
+ ...this.watchdog ? { watchdog: this.watchdog() } : {}
2514
2552
  };
2515
2553
  return this.send(client, { id: req.id, ok: true, result: status });
2516
2554
  }
@@ -2620,7 +2658,7 @@ var IpcServer = class {
2620
2658
  };
2621
2659
 
2622
2660
  // src/daemon/module-host.ts
2623
- var import_node_fs11 = require("fs");
2661
+ var import_node_fs12 = require("fs");
2624
2662
  var import_node_path6 = require("path");
2625
2663
  var import_node_url = require("url");
2626
2664
  var import_toml2 = __toESM(require_toml());
@@ -2747,8 +2785,76 @@ function verifyModuleTrust(name, modulePath) {
2747
2785
  }
2748
2786
 
2749
2787
  // src/daemon/watchers/log-watcher.ts
2750
- var import_node_fs7 = require("fs");
2751
- var import_node_readline = require("readline");
2788
+ var import_node_fs8 = require("fs");
2789
+
2790
+ // src/core/log-tail.ts
2791
+ var import_node_fs6 = require("fs");
2792
+ var LogTail = class {
2793
+ /** Starts at the end of the file: history is not replayed. */
2794
+ constructor(path, fromStart = false) {
2795
+ this.path = path;
2796
+ try {
2797
+ const st = (0, import_node_fs6.statSync)(path);
2798
+ this.pos = fromStart ? 0 : st.size;
2799
+ this.inode = st.ino;
2800
+ } catch {
2801
+ this.pos = 0;
2802
+ }
2803
+ }
2804
+ path;
2805
+ pos;
2806
+ partial = "";
2807
+ inode;
2808
+ get position() {
2809
+ return this.pos;
2810
+ }
2811
+ /**
2812
+ * Hands each complete new line to onLine. A line still being written (no
2813
+ * newline yet) waits for the next poll. Rotation (a new inode, or a file
2814
+ * shorter than our position) restarts at the top of the new file.
2815
+ * At most maxBytes are read per poll, so a burst is spread over polls
2816
+ * instead of blocking the daemon.
2817
+ */
2818
+ poll(onLine, maxBytes = 4 << 20) {
2819
+ let fd;
2820
+ try {
2821
+ fd = (0, import_node_fs6.openSync)(this.path, "r");
2822
+ } catch {
2823
+ return 0;
2824
+ }
2825
+ try {
2826
+ const st = (0, import_node_fs6.fstatSync)(fd);
2827
+ if (this.inode !== void 0 && st.ino !== this.inode || st.size < this.pos) {
2828
+ this.pos = 0;
2829
+ this.partial = "";
2830
+ }
2831
+ this.inode = st.ino;
2832
+ const end = Math.min(st.size, this.pos + maxBytes);
2833
+ if (end <= this.pos) return 0;
2834
+ const buf = Buffer.allocUnsafe(Math.min(end - this.pos, 1 << 20));
2835
+ let lines = 0;
2836
+ while (this.pos < end) {
2837
+ const want = Math.min(buf.length, end - this.pos);
2838
+ const n = (0, import_node_fs6.readSync)(fd, buf, 0, want, this.pos);
2839
+ if (n <= 0) break;
2840
+ this.pos += n;
2841
+ const text = this.partial + buf.toString("utf-8", 0, n);
2842
+ const parts = text.split("\n");
2843
+ this.partial = parts.pop() ?? "";
2844
+ for (const line of parts) {
2845
+ if (line.trim()) {
2846
+ lines++;
2847
+ onLine(line);
2848
+ }
2849
+ }
2850
+ }
2851
+ if (this.partial.length > 1 << 20) this.partial = "";
2852
+ return lines;
2853
+ } finally {
2854
+ (0, import_node_fs6.closeSync)(fd);
2855
+ }
2856
+ }
2857
+ };
2752
2858
 
2753
2859
  // src/core/crs/rules.generated.ts
2754
2860
  var CRS_RULES = [
@@ -8938,12 +9044,12 @@ var TRANSFORMS = {
8938
9044
  };
8939
9045
 
8940
9046
  // src/core/crs/libinjection.ts
8941
- var import_node_fs6 = require("fs");
9047
+ var import_node_fs7 = require("fs");
8942
9048
  var import_node_path4 = require("path");
8943
9049
  var wasm;
8944
9050
  function loadLibinjection() {
8945
9051
  if (!wasm) {
8946
- const bytes = (0, import_node_fs6.readFileSync)((0, import_node_path4.join)(__dirname, "libinjection", "libinjection.wasm"));
9052
+ const bytes = (0, import_node_fs7.readFileSync)((0, import_node_path4.join)(__dirname, "libinjection", "libinjection.wasm"));
8947
9053
  wasm = new WebAssembly.Instance(new WebAssembly.Module(bytes), {}).exports;
8948
9054
  wasm._initialize();
8949
9055
  }
@@ -9454,14 +9560,14 @@ var LogWatcher = class {
9454
9560
  bus;
9455
9561
  sources;
9456
9562
  timers = /* @__PURE__ */ new Map();
9457
- positions = /* @__PURE__ */ new Map();
9563
+ tails = /* @__PURE__ */ new Map();
9458
9564
  active = /* @__PURE__ */ new Set();
9459
9565
  start() {
9460
9566
  const started = [];
9461
9567
  for (const src of this.sources) {
9462
- if (!(0, import_node_fs7.existsSync)(src.path)) continue;
9568
+ if (!(0, import_node_fs8.existsSync)(src.path)) continue;
9463
9569
  try {
9464
- (0, import_node_fs7.accessSync)(src.path, import_node_fs7.constants.R_OK);
9570
+ (0, import_node_fs8.accessSync)(src.path, import_node_fs8.constants.R_OK);
9465
9571
  } catch {
9466
9572
  continue;
9467
9573
  }
@@ -9473,7 +9579,7 @@ var LogWatcher = class {
9473
9579
  stop() {
9474
9580
  for (const t of this.timers.values()) clearInterval(t);
9475
9581
  this.timers.clear();
9476
- this.positions.clear();
9582
+ this.tails.clear();
9477
9583
  this.active.clear();
9478
9584
  }
9479
9585
  activeModules() {
@@ -9488,38 +9594,22 @@ var LogWatcher = class {
9488
9594
  return this.sources.filter((s) => s.category === "auth" && this.timers.has(s.path)).map((s) => s.path);
9489
9595
  }
9490
9596
  tail(src) {
9491
- try {
9492
- this.positions.set(src.path, (0, import_node_fs7.statSync)(src.path).size);
9493
- } catch {
9494
- this.positions.set(src.path, 0);
9495
- }
9597
+ const tail = new LogTail(src.path);
9598
+ this.tails.set(src.path, tail);
9496
9599
  const timer = setInterval(() => this.poll(src), 1e3);
9497
9600
  this.timers.set(src.path, timer);
9498
9601
  this.active.add(src.module);
9499
9602
  }
9603
+ /** Each new line exactly once; see LogTail for why this is synchronous. */
9500
9604
  poll(src) {
9501
- let stat;
9502
- try {
9503
- stat = (0, import_node_fs7.statSync)(src.path);
9504
- } catch {
9505
- return;
9506
- }
9507
- const prev = this.positions.get(src.path) ?? 0;
9508
- if (stat.size < prev) {
9509
- this.positions.set(src.path, 0);
9510
- return;
9511
- }
9512
- if (stat.size === prev) return;
9513
- const stream = (0, import_node_fs7.createReadStream)(src.path, { start: prev, encoding: "utf-8" });
9514
- stream.on("error", () => this.positions.set(src.path, stat.size));
9515
- const rl = (0, import_node_readline.createInterface)({ input: stream });
9516
- rl.on("error", () => {
9517
- });
9518
- rl.on("line", (line) => {
9519
- if (!line.trim()) return;
9520
- this.process(line, src);
9605
+ const tail = this.tails.get(src.path);
9606
+ if (!tail) return 0;
9607
+ return tail.poll((line) => {
9608
+ try {
9609
+ this.process(line, src);
9610
+ } catch {
9611
+ }
9521
9612
  });
9522
- rl.on("close", () => this.positions.set(src.path, stat.size));
9523
9613
  }
9524
9614
  process(line, src) {
9525
9615
  const parsed = autoDetectParser(line);
@@ -9546,6 +9636,9 @@ var LogWatcher = class {
9546
9636
  const reqPath = (entry.fields.path || "").split("?")[0];
9547
9637
  if (reqPath) details.path = reqPath;
9548
9638
  if (entry.fields.user_agent) details.ua = entry.fields.user_agent;
9639
+ if (Number.isFinite(status)) details.status = status;
9640
+ if (entry.fields.method) details.method = entry.fields.method;
9641
+ if (entry.fields.path) details.url = entry.fields.path.slice(0, 2048);
9549
9642
  if (crs.score > 0) {
9550
9643
  Object.assign(details, {
9551
9644
  attack_type: crs.attackType,
@@ -9771,7 +9864,7 @@ function realtimeToDate(rt) {
9771
9864
 
9772
9865
  // src/modules/network-monitor/index.ts
9773
9866
  var import_node_child_process2 = require("child_process");
9774
- var import_node_fs8 = require("fs");
9867
+ var import_node_fs9 = require("fs");
9775
9868
  var NetworkMonitor = class {
9776
9869
  constructor(bus2) {
9777
9870
  this.bus = bus2;
@@ -9835,7 +9928,7 @@ var NetworkMonitor = class {
9835
9928
  hasConntrackOrSs() {
9836
9929
  const ss = (0, import_node_child_process2.spawnSync)("ss", ["--version"], { stdio: "pipe" });
9837
9930
  if (ss.status === 0) return true;
9838
- return (0, import_node_fs8.existsSync)("/proc/net/tcp");
9931
+ return (0, import_node_fs9.existsSync)("/proc/net/tcp");
9839
9932
  }
9840
9933
  /**
9841
9934
  * The TCP ports this host actually listens on.
@@ -10022,9 +10115,9 @@ var NetworkMonitor = class {
10022
10115
  };
10023
10116
 
10024
10117
  // src/modules/dns-monitor/index.ts
10025
- var import_node_fs9 = require("fs");
10118
+ var import_node_fs10 = require("fs");
10026
10119
  var import_node_child_process3 = require("child_process");
10027
- var import_node_readline2 = require("readline");
10120
+ var import_node_readline = require("readline");
10028
10121
  var DNS_LOG_SOURCES = [
10029
10122
  "/var/log/syslog",
10030
10123
  // systemd-resolved logs here
@@ -10065,7 +10158,7 @@ var DnsMonitor = class {
10065
10158
  bus;
10066
10159
  active = false;
10067
10160
  timers = /* @__PURE__ */ new Map();
10068
- positions = /* @__PURE__ */ new Map();
10161
+ tails = /* @__PURE__ */ new Map();
10069
10162
  // Tracking windows
10070
10163
  txtQueryCounts = /* @__PURE__ */ new Map();
10071
10164
  domainBuffer = [];
@@ -10104,9 +10197,9 @@ var DnsMonitor = class {
10104
10197
  }
10105
10198
  start() {
10106
10199
  const sources = [...DNS_LOG_SOURCES, ...this.extraPaths].filter((p) => {
10107
- if (!(0, import_node_fs9.existsSync)(p)) return false;
10200
+ if (!(0, import_node_fs10.existsSync)(p)) return false;
10108
10201
  try {
10109
- (0, import_node_fs9.accessSync)(p, import_node_fs9.constants.R_OK);
10202
+ (0, import_node_fs10.accessSync)(p, import_node_fs10.constants.R_OK);
10110
10203
  return true;
10111
10204
  } catch {
10112
10205
  return false;
@@ -10169,7 +10262,7 @@ var DnsMonitor = class {
10169
10262
  stdio: ["ignore", "pipe", "ignore"]
10170
10263
  });
10171
10264
  if (!child.stdout) return;
10172
- const rl = (0, import_node_readline2.createInterface)({ input: child.stdout });
10265
+ const rl = (0, import_node_readline.createInterface)({ input: child.stdout });
10173
10266
  rl.on("line", (line) => this.parseDnsLine(line));
10174
10267
  child.on("error", () => {
10175
10268
  });
@@ -10181,33 +10274,11 @@ var DnsMonitor = class {
10181
10274
  return this.active;
10182
10275
  }
10183
10276
  tailLog(path) {
10184
- try {
10185
- this.positions.set(path, (0, import_node_fs9.statSync)(path).size);
10186
- } catch {
10187
- this.positions.set(path, 0);
10188
- }
10189
- const timer = setInterval(() => this.pollLog(path), 2e3);
10277
+ const tail = new LogTail(path);
10278
+ this.tails.set(path, tail);
10279
+ const timer = setInterval(() => tail.poll((line) => this.parseDnsLine(line)), 2e3);
10190
10280
  this.timers.set(path, timer);
10191
10281
  }
10192
- pollLog(path) {
10193
- let stat;
10194
- try {
10195
- stat = (0, import_node_fs9.statSync)(path);
10196
- } catch {
10197
- return;
10198
- }
10199
- const prev = this.positions.get(path) ?? 0;
10200
- if (stat.size < prev) {
10201
- this.positions.set(path, 0);
10202
- return;
10203
- }
10204
- if (stat.size === prev) return;
10205
- const stream = (0, import_node_fs9.createReadStream)(path, { start: prev, encoding: "utf-8" });
10206
- stream.on("error", () => this.positions.set(path, stat.size));
10207
- const rl = (0, import_node_readline2.createInterface)({ input: stream });
10208
- rl.on("line", (line) => this.parseDnsLine(line));
10209
- rl.on("close", () => this.positions.set(path, stat.size));
10210
- }
10211
10282
  parseDnsLine(line) {
10212
10283
  const moshpit = line.match(
10213
10284
  /\[dns\]\s+(?:udp|tcp|doh)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\w+)/i
@@ -10312,14 +10383,14 @@ var DnsMonitor = class {
10312
10383
  );
10313
10384
  }
10314
10385
  }
10315
- shannonEntropy(str2) {
10386
+ shannonEntropy(str3) {
10316
10387
  const freq = /* @__PURE__ */ new Map();
10317
- for (const ch of str2) {
10388
+ for (const ch of str3) {
10318
10389
  freq.set(ch, (freq.get(ch) || 0) + 1);
10319
10390
  }
10320
10391
  let entropy = 0;
10321
10392
  for (const count of freq.values()) {
10322
- const p = count / str2.length;
10393
+ const p = count / str3.length;
10323
10394
  if (p > 0) entropy -= p * Math.log2(p);
10324
10395
  }
10325
10396
  return entropy;
@@ -10348,7 +10419,7 @@ var DnsMonitor = class {
10348
10419
  };
10349
10420
 
10350
10421
  // src/core/config.ts
10351
- var import_node_fs10 = require("fs");
10422
+ var import_node_fs11 = require("fs");
10352
10423
  var import_node_path5 = require("path");
10353
10424
  var import_toml = __toESM(require_toml());
10354
10425
  var DEFAULT_CONFIG_PATH = "/etc/threatcrush/threatcrushd.conf";
@@ -10375,11 +10446,11 @@ var DEFAULT_CONFIG = {
10375
10446
  };
10376
10447
  function loadConfig(configPath) {
10377
10448
  const path = configPath || DEFAULT_CONFIG_PATH;
10378
- if (!(0, import_node_fs10.existsSync)(path)) {
10449
+ if (!(0, import_node_fs11.existsSync)(path)) {
10379
10450
  return { ...DEFAULT_CONFIG };
10380
10451
  }
10381
10452
  try {
10382
- const raw = (0, import_node_fs10.readFileSync)(path, "utf-8");
10453
+ const raw = (0, import_node_fs11.readFileSync)(path, "utf-8");
10383
10454
  const parsed = import_toml.default.parse(raw);
10384
10455
  return {
10385
10456
  daemon: { ...DEFAULT_CONFIG.daemon, ...parsed.daemon },
@@ -10389,6 +10460,8 @@ function loadConfig(configPath) {
10389
10460
  remediation: parsed.remediation,
10390
10461
  detection: parsed.detection,
10391
10462
  cloud: parsed.cloud,
10463
+ watchdog: parsed.watchdog,
10464
+ storage: parsed.storage,
10392
10465
  license: parsed.license
10393
10466
  };
10394
10467
  } catch {
@@ -10398,13 +10471,13 @@ function loadConfig(configPath) {
10398
10471
  function loadModuleConfigs(confDir) {
10399
10472
  const dir = confDir || DEFAULT_CONFDIR;
10400
10473
  const configs = /* @__PURE__ */ new Map();
10401
- if (!(0, import_node_fs10.existsSync)(dir)) {
10474
+ if (!(0, import_node_fs11.existsSync)(dir)) {
10402
10475
  return configs;
10403
10476
  }
10404
- const files = (0, import_node_fs10.readdirSync)(dir).filter((f) => f.endsWith(".conf"));
10477
+ const files = (0, import_node_fs11.readdirSync)(dir).filter((f) => f.endsWith(".conf"));
10405
10478
  for (const file of files) {
10406
10479
  try {
10407
- const raw = (0, import_node_fs10.readFileSync)((0, import_node_path5.join)(dir, file), "utf-8");
10480
+ const raw = (0, import_node_fs11.readFileSync)((0, import_node_path5.join)(dir, file), "utf-8");
10408
10481
  const parsed = import_toml.default.parse(raw);
10409
10482
  for (const [name, config] of Object.entries(parsed)) {
10410
10483
  configs.set(name, config);
@@ -10538,15 +10611,15 @@ var ModuleHost = class {
10538
10611
  }
10539
10612
  }
10540
10613
  async discoverAndStartInstalled() {
10541
- if (!(0, import_node_fs11.existsSync)(PATHS.moduleDir)) return;
10614
+ if (!(0, import_node_fs12.existsSync)(PATHS.moduleDir)) return;
10542
10615
  const configs = loadModuleConfigs(PATHS.confD);
10543
- const entries = (0, import_node_fs11.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
10616
+ const entries = (0, import_node_fs12.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
10544
10617
  for (const entry of entries) {
10545
10618
  if (!entry.isDirectory()) continue;
10546
10619
  const manifestPath = (0, import_node_path6.join)(PATHS.moduleDir, entry.name, "mod.toml");
10547
- if (!(0, import_node_fs11.existsSync)(manifestPath)) continue;
10620
+ if (!(0, import_node_fs12.existsSync)(manifestPath)) continue;
10548
10621
  try {
10549
- const manifest = import_toml2.default.parse((0, import_node_fs11.readFileSync)(manifestPath, "utf-8"));
10622
+ const manifest = import_toml2.default.parse((0, import_node_fs12.readFileSync)(manifestPath, "utf-8"));
10550
10623
  const name = manifest.module?.name || entry.name;
10551
10624
  const defaults = manifest.module?.config?.defaults || {};
10552
10625
  const config = {
@@ -10616,15 +10689,15 @@ var ModuleHost = class {
10616
10689
  installedEntrypoint(modulePath) {
10617
10690
  const packageJson = (0, import_node_path6.join)(modulePath, "package.json");
10618
10691
  const candidates = [];
10619
- if ((0, import_node_fs11.existsSync)(packageJson)) {
10692
+ if ((0, import_node_fs12.existsSync)(packageJson)) {
10620
10693
  try {
10621
- const pkg = JSON.parse((0, import_node_fs11.readFileSync)(packageJson, "utf-8"));
10694
+ const pkg = JSON.parse((0, import_node_fs12.readFileSync)(packageJson, "utf-8"));
10622
10695
  if (pkg.main) candidates.push((0, import_node_path6.join)(modulePath, pkg.main));
10623
10696
  } catch {
10624
10697
  }
10625
10698
  }
10626
10699
  candidates.push((0, import_node_path6.join)(modulePath, "dist", "index.js"), (0, import_node_path6.join)(modulePath, "index.js"));
10627
- return candidates.find((candidate) => (0, import_node_fs11.existsSync)(candidate)) || null;
10700
+ return candidates.find((candidate) => (0, import_node_fs12.existsSync)(candidate)) || null;
10628
10701
  }
10629
10702
  isThreatCrushModule(value) {
10630
10703
  return Boolean(
@@ -10896,7 +10969,7 @@ function slackChannel(webhookUrl) {
10896
10969
  }
10897
10970
 
10898
10971
  // src/core/cli-config.ts
10899
- var import_node_fs12 = require("fs");
10972
+ var import_node_fs13 = require("fs");
10900
10973
  var import_node_path7 = require("path");
10901
10974
  var import_node_os2 = require("os");
10902
10975
  var CLI_CONFIG_DIR = (0, import_node_path7.join)((0, import_node_os2.homedir)(), ".threatcrush");
@@ -10906,16 +10979,16 @@ function apiUrl() {
10906
10979
  }
10907
10980
  function readCliConfig() {
10908
10981
  try {
10909
- return JSON.parse((0, import_node_fs12.readFileSync)(CLI_CONFIG_PATH, "utf-8"));
10982
+ return JSON.parse((0, import_node_fs13.readFileSync)(CLI_CONFIG_PATH, "utf-8"));
10910
10983
  } catch {
10911
10984
  return {};
10912
10985
  }
10913
10986
  }
10914
10987
  function writeCliConfig(config) {
10915
- if (!(0, import_node_fs12.existsSync)(CLI_CONFIG_DIR)) (0, import_node_fs12.mkdirSync)(CLI_CONFIG_DIR, { recursive: true });
10916
- (0, import_node_fs12.writeFileSync)(CLI_CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
10988
+ if (!(0, import_node_fs13.existsSync)(CLI_CONFIG_DIR)) (0, import_node_fs13.mkdirSync)(CLI_CONFIG_DIR, { recursive: true });
10989
+ (0, import_node_fs13.writeFileSync)(CLI_CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
10917
10990
  try {
10918
- (0, import_node_fs12.chmodSync)(CLI_CONFIG_PATH, 384);
10991
+ (0, import_node_fs13.chmodSync)(CLI_CONFIG_PATH, 384);
10919
10992
  } catch {
10920
10993
  }
10921
10994
  }
@@ -10991,7 +11064,7 @@ async function cloudFetch(path, init = {}) {
10991
11064
  }
10992
11065
 
10993
11066
  // src/commands/scan.ts
10994
- var import_node_fs16 = require("fs");
11067
+ var import_node_fs17 = require("fs");
10995
11068
  var import_node_path12 = require("path");
10996
11069
 
10997
11070
  // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
@@ -11490,13 +11563,13 @@ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
11490
11563
  var source_default = chalk;
11491
11564
 
11492
11565
  // src/core/version.ts
11493
- var import_node_fs13 = require("fs");
11566
+ var import_node_fs14 = require("fs");
11494
11567
  var import_node_path8 = require("path");
11495
11568
  var FALLBACK_VERSION = "0.0.0";
11496
11569
  function readPackageVersion() {
11497
11570
  try {
11498
11571
  const pkg = JSON.parse(
11499
- (0, import_node_fs13.readFileSync)((0, import_node_path8.join)(__dirname, "..", "package.json"), "utf-8")
11572
+ (0, import_node_fs14.readFileSync)((0, import_node_path8.join)(__dirname, "..", "package.json"), "utf-8")
11500
11573
  );
11501
11574
  return pkg.version || FALLBACK_VERSION;
11502
11575
  } catch {
@@ -14223,7 +14296,7 @@ function isTestPath(relativePath) {
14223
14296
  function rustCodeLines(lines) {
14224
14297
  const out = [];
14225
14298
  let commentDepth = 0;
14226
- let str2 = null;
14299
+ let str3 = null;
14227
14300
  for (const line of lines) {
14228
14301
  let code = "";
14229
14302
  let i = 0;
@@ -14247,15 +14320,15 @@ function rustCodeLines(lines) {
14247
14320
  i += 1;
14248
14321
  continue;
14249
14322
  }
14250
- if (str2) {
14251
- if (str2.raw) {
14323
+ if (str3) {
14324
+ if (str3.raw) {
14252
14325
  if (c === '"') {
14253
14326
  let hashes = 0;
14254
14327
  while (line[i + 1 + hashes] === "#") hashes += 1;
14255
- if (hashes >= str2.hashes) {
14256
- code += " ".repeat(1 + str2.hashes);
14257
- i += 1 + str2.hashes;
14258
- str2 = null;
14328
+ if (hashes >= str3.hashes) {
14329
+ code += " ".repeat(1 + str3.hashes);
14330
+ i += 1 + str3.hashes;
14331
+ str3 = null;
14259
14332
  continue;
14260
14333
  }
14261
14334
  }
@@ -14269,7 +14342,7 @@ function rustCodeLines(lines) {
14269
14342
  continue;
14270
14343
  }
14271
14344
  if (c === '"') {
14272
- str2 = null;
14345
+ str3 = null;
14273
14346
  code += " ";
14274
14347
  i += 1;
14275
14348
  continue;
@@ -14291,14 +14364,14 @@ function rustCodeLines(lines) {
14291
14364
  if (i === 0 || !/[A-Za-z0-9_]/.test(line[i - 1])) {
14292
14365
  const raw = /^b?r(#*)"/.exec(line.slice(i));
14293
14366
  if (raw) {
14294
- str2 = { raw: true, hashes: raw[1].length };
14367
+ str3 = { raw: true, hashes: raw[1].length };
14295
14368
  code += " ".repeat(raw[0].length);
14296
14369
  i += raw[0].length;
14297
14370
  continue;
14298
14371
  }
14299
14372
  }
14300
14373
  if (c === '"') {
14301
- str2 = { raw: false, hashes: 0 };
14374
+ str3 = { raw: false, hashes: 0 };
14302
14375
  code += " ";
14303
14376
  i += 1;
14304
14377
  continue;
@@ -14503,7 +14576,7 @@ function scanManifest(relativePath, filename, text) {
14503
14576
  }
14504
14577
 
14505
14578
  // ../../packages/scan/src/node/walk.ts
14506
- var import_node_fs14 = require("fs");
14579
+ var import_node_fs15 = require("fs");
14507
14580
  var import_node_path9 = require("path");
14508
14581
  function compileExcludes(patterns) {
14509
14582
  const matchers = patterns.map((p) => p.trim()).filter((p) => p.length > 0 && !p.startsWith("#")).map(compilePattern);
@@ -14575,7 +14648,7 @@ function matchPrefix(parts, segs) {
14575
14648
  }
14576
14649
  function readIgnoreFile(root) {
14577
14650
  try {
14578
- return (0, import_node_fs14.readFileSync)((0, import_node_path9.join)(root, ".threatcrushignore"), "utf-8").split("\n");
14651
+ return (0, import_node_fs15.readFileSync)((0, import_node_path9.join)(root, ".threatcrushignore"), "utf-8").split("\n");
14579
14652
  } catch {
14580
14653
  return [];
14581
14654
  }
@@ -14591,7 +14664,7 @@ function scanPath(targetPath, options = {}) {
14591
14664
  let excluded = 0;
14592
14665
  const rootIsDirectory = (() => {
14593
14666
  try {
14594
- return (0, import_node_fs14.statSync)(targetPath).isDirectory();
14667
+ return (0, import_node_fs15.statSync)(targetPath).isDirectory();
14595
14668
  } catch {
14596
14669
  return true;
14597
14670
  }
@@ -14612,26 +14685,26 @@ function scanPath(targetPath, options = {}) {
14612
14685
  let handle;
14613
14686
  let declared = null;
14614
14687
  try {
14615
- handle = (0, import_node_fs14.openSync)(fullPath, "r");
14688
+ handle = (0, import_node_fs15.openSync)(fullPath, "r");
14616
14689
  } catch {
14617
14690
  unreadable.push(relativePath);
14618
14691
  return;
14619
14692
  }
14620
14693
  try {
14621
- if ((0, import_node_fs14.fstatSync)(handle).size > maxFileBytes) return;
14694
+ if ((0, import_node_fs15.fstatSync)(handle).size > maxFileBytes) return;
14622
14695
  if (mayDeclareInterpreter) {
14623
14696
  const prefix = Buffer.alloc(128);
14624
- const read = (0, import_node_fs14.readSync)(handle, prefix, 0, prefix.length, 0);
14697
+ const read = (0, import_node_fs15.readSync)(handle, prefix, 0, prefix.length, 0);
14625
14698
  declared = languageOfShebang(prefix.subarray(0, read).toString("utf-8").split("\n", 1)[0] ?? "");
14626
14699
  if (!declared) return;
14627
14700
  }
14628
- text = (0, import_node_fs14.readFileSync)(handle, "utf-8");
14701
+ text = (0, import_node_fs15.readFileSync)(handle, "utf-8");
14629
14702
  } catch {
14630
14703
  unreadable.push(relativePath);
14631
14704
  return;
14632
14705
  } finally {
14633
14706
  try {
14634
- (0, import_node_fs14.closeSync)(handle);
14707
+ (0, import_node_fs15.closeSync)(handle);
14635
14708
  } catch {
14636
14709
  }
14637
14710
  }
@@ -14649,7 +14722,7 @@ function scanPath(targetPath, options = {}) {
14649
14722
  const walk = (currentPath) => {
14650
14723
  let entries;
14651
14724
  try {
14652
- entries = (0, import_node_fs14.readdirSync)(currentPath, { withFileTypes: true });
14725
+ entries = (0, import_node_fs15.readdirSync)(currentPath, { withFileTypes: true });
14653
14726
  } catch {
14654
14727
  unreadable.push(toRelative(walkRoot, currentPath));
14655
14728
  return;
@@ -14716,17 +14789,17 @@ function toRelative(base, target) {
14716
14789
  }
14717
14790
 
14718
14791
  // ../../packages/scan/src/node/dependencies.ts
14719
- var import_node_fs15 = require("fs");
14792
+ var import_node_fs16 = require("fs");
14720
14793
  var import_node_path10 = require("path");
14721
14794
  var MAX_DEPS_PER_LOCKFILE = 50;
14722
14795
  async function scanDependencies(targetPath) {
14723
14796
  const findings = [];
14724
14797
  for (const { file, ecosystem, parse } of LOCKFILES) {
14725
14798
  const lockPath = (0, import_node_path10.join)(targetPath, file);
14726
- if (!(0, import_node_fs15.existsSync)(lockPath)) continue;
14799
+ if (!(0, import_node_fs16.existsSync)(lockPath)) continue;
14727
14800
  let deps;
14728
14801
  try {
14729
- deps = dedupe(parse((0, import_node_fs15.readFileSync)(lockPath, "utf-8")));
14802
+ deps = dedupe(parse((0, import_node_fs16.readFileSync)(lockPath, "utf-8")));
14730
14803
  } catch {
14731
14804
  continue;
14732
14805
  }
@@ -14950,7 +15023,7 @@ function readVersion() {
14950
15023
  (0, import_node_path12.join)(__dirname, "..", "..", "package.json")
14951
15024
  ]) {
14952
15025
  try {
14953
- return JSON.parse((0, import_node_fs16.readFileSync)(candidate, "utf-8")).version ?? "0.0.0";
15026
+ return JSON.parse((0, import_node_fs17.readFileSync)(candidate, "utf-8")).version ?? "0.0.0";
14954
15027
  } catch {
14955
15028
  }
14956
15029
  }
@@ -15393,7 +15466,7 @@ function findingEvents(serverId, results, observedAt = /* @__PURE__ */ new Date(
15393
15466
  }
15394
15467
 
15395
15468
  // src/daemon/workers/cloud-spool.ts
15396
- var import_node_fs17 = require("fs");
15469
+ var import_node_fs18 = require("fs");
15397
15470
  var import_promises = require("fs/promises");
15398
15471
  var import_node_path13 = require("path");
15399
15472
  var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
@@ -15402,7 +15475,7 @@ var CloudSpool = class {
15402
15475
  this.path = path;
15403
15476
  this.limits = limits;
15404
15477
  try {
15405
- (0, import_node_fs17.mkdirSync)((0, import_node_path13.dirname)(path), { recursive: true });
15478
+ (0, import_node_fs18.mkdirSync)((0, import_node_path13.dirname)(path), { recursive: true });
15406
15479
  } catch {
15407
15480
  }
15408
15481
  this.load();
@@ -15471,7 +15544,7 @@ var CloudSpool = class {
15471
15544
  load() {
15472
15545
  let raw;
15473
15546
  try {
15474
- raw = (0, import_node_fs17.readFileSync)(this.path, "utf-8");
15547
+ raw = (0, import_node_fs18.readFileSync)(this.path, "utf-8");
15475
15548
  } catch {
15476
15549
  return;
15477
15550
  }
@@ -16176,7 +16249,7 @@ var RuleEngine = class {
16176
16249
  };
16177
16250
 
16178
16251
  // src/daemon/rules/loader.ts
16179
- var import_node_fs18 = require("fs");
16252
+ var import_node_fs19 = require("fs");
16180
16253
  var import_node_path14 = require("path");
16181
16254
 
16182
16255
  // src/daemon/rules/default-rules.ts
@@ -16578,11 +16651,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
16578
16651
  function loadAllRules(customDir) {
16579
16652
  const rules = [...DEFAULT_RULES];
16580
16653
  const dir = customDir || RULES_DIR;
16581
- if ((0, import_node_fs18.existsSync)(dir)) {
16582
- const files = (0, import_node_fs18.readdirSync)(dir).filter((f) => f.endsWith(".json"));
16654
+ if ((0, import_node_fs19.existsSync)(dir)) {
16655
+ const files = (0, import_node_fs19.readdirSync)(dir).filter((f) => f.endsWith(".json"));
16583
16656
  for (const file of files) {
16584
16657
  try {
16585
- const raw = (0, import_node_fs18.readFileSync)((0, import_node_path14.join)(dir, file), "utf-8");
16658
+ const raw = (0, import_node_fs19.readFileSync)((0, import_node_path14.join)(dir, file), "utf-8");
16586
16659
  const parsed = JSON.parse(raw);
16587
16660
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
16588
16661
  for (const rule of customRules) {
@@ -16614,7 +16687,7 @@ function loadAllRules(customDir) {
16614
16687
 
16615
16688
  // src/daemon/firewall/adapters.ts
16616
16689
  var import_node_child_process5 = require("child_process");
16617
- var import_node_fs19 = require("fs");
16690
+ var import_node_fs20 = require("fs");
16618
16691
  var import_node_path15 = require("path");
16619
16692
  var import_node_net6 = require("net");
16620
16693
  function assertValidFirewallIp(ip) {
@@ -16628,9 +16701,9 @@ function assertBannableIp(ip) {
16628
16701
  }
16629
16702
  }
16630
16703
  function writeIfAbsent(path, contents) {
16631
- (0, import_node_fs19.mkdirSync)((0, import_node_path15.dirname)(path), { recursive: true });
16704
+ (0, import_node_fs20.mkdirSync)((0, import_node_path15.dirname)(path), { recursive: true });
16632
16705
  try {
16633
- (0, import_node_fs19.writeFileSync)(path, contents, { flag: "wx" });
16706
+ (0, import_node_fs20.writeFileSync)(path, contents, { flag: "wx" });
16634
16707
  } catch (err) {
16635
16708
  if (err.code !== "EEXIST") throw err;
16636
16709
  }
@@ -16885,7 +16958,7 @@ function detectFirewallAdapter(backend = "auto") {
16885
16958
  }
16886
16959
 
16887
16960
  // src/daemon/firewall/remediation.ts
16888
- var import_node_fs20 = require("fs");
16961
+ var import_node_fs21 = require("fs");
16889
16962
  var import_node_net7 = require("net");
16890
16963
 
16891
16964
  // src/daemon/firewall/crawlers.ts
@@ -17293,7 +17366,7 @@ var RemediationManager = class {
17293
17366
  }
17294
17367
  logLine(line) {
17295
17368
  try {
17296
- (0, import_node_fs20.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
17369
+ (0, import_node_fs21.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
17297
17370
  `);
17298
17371
  } catch {
17299
17372
  }
@@ -17326,6 +17399,239 @@ function remediationSettings(section) {
17326
17399
  return settings;
17327
17400
  }
17328
17401
 
17402
+ // src/daemon/watchdog-service.ts
17403
+ var import_node_fs23 = require("fs");
17404
+ var import_node_path17 = require("path");
17405
+
17406
+ // src/core/watchdog.ts
17407
+ var import_node_fs22 = require("fs");
17408
+ var import_node_crypto5 = require("crypto");
17409
+ var import_node_path16 = require("path");
17410
+ var WATCHDOG_DIRNAME = "watchdog";
17411
+ var LOG_FILE = "attacks.jsonl";
17412
+ var ROTATED_FILE = "attacks.1.jsonl";
17413
+ var ROTATE_BYTES = 50 * 1024 * 1024;
17414
+ var SEEN_LIMIT = 5e3;
17415
+ var SEVERITY_RANK6 = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
17416
+ function str2(v) {
17417
+ return typeof v === "string" && v !== "" && v !== "-" ? v : void 0;
17418
+ }
17419
+ function isAttack(event) {
17420
+ if (event.module === "firewall-rules") return false;
17421
+ const d = event.details ?? {};
17422
+ if (d.heartbeat) return false;
17423
+ const crs = typeof d.crs_score === "number" ? d.crs_score : 0;
17424
+ if (crs > 0 || str2(d.attack_type)) return true;
17425
+ if (event.category === "web" && typeof d.status === "number" && !str2(d.rule_id)) return false;
17426
+ return SEVERITY_RANK6[event.severity] >= SEVERITY_RANK6.medium;
17427
+ }
17428
+ function outcomeFor(status) {
17429
+ if (typeof status !== "number" || !Number.isFinite(status)) return "unknown";
17430
+ if (status >= 500) return "errored";
17431
+ if (status >= 400) return "refused";
17432
+ if (status >= 300) return "redirected";
17433
+ if (status >= 100) return "answered";
17434
+ return "unknown";
17435
+ }
17436
+ function requestFromMessage(message) {
17437
+ const m = /\b(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|CONNECT|TRACE|PROPFIND)\s+(\S+)/.exec(message);
17438
+ return m ? { method: m[1], url: m[2] } : {};
17439
+ }
17440
+ function signatureOf(r) {
17441
+ if (r.path) {
17442
+ return ["web", r.host ?? "", r.method ?? "", r.path, r.attack_type ?? r.rule_id ?? ""].join("|");
17443
+ }
17444
+ if (r.rule_id) return ["rule", r.module, r.rule_id].join("|");
17445
+ const shape = r.message.replace(/\b\d{1,3}(?:\.\d{1,3}){3}(?:\/\d+)?\b/g, "<ip>").replace(/\b[0-9a-f]*:[0-9a-f:]+\b/gi, "<ip>").replace(/\d+/g, "#");
17446
+ return ["msg", r.module, shape].join("|");
17447
+ }
17448
+ function findingId(signature) {
17449
+ return (0, import_node_crypto5.createHash)("sha1").update(signature).digest("hex").slice(0, 10);
17450
+ }
17451
+ function toRecord(event) {
17452
+ const d = event.details ?? {};
17453
+ const fromMsg = requestFromMessage(event.message);
17454
+ const url = str2(d.url) ?? fromMsg.url;
17455
+ const path = str2(d.path) ?? (url ? url.split("?")[0] : void 0);
17456
+ const status = typeof d.status === "number" ? d.status : void 0;
17457
+ const base = {
17458
+ module: event.module,
17459
+ host: str2(d.host),
17460
+ method: str2(d.method) ?? fromMsg.method,
17461
+ path,
17462
+ attack_type: str2(d.attack_type),
17463
+ rule_id: str2(d.rule_id),
17464
+ message: event.message
17465
+ };
17466
+ const timestamp = event.timestamp instanceof Date ? event.timestamp : new Date(event.timestamp);
17467
+ const record = {
17468
+ v: 1,
17469
+ id: findingId(signatureOf(base)),
17470
+ at: (Number.isNaN(timestamp.getTime()) ? /* @__PURE__ */ new Date() : timestamp).toISOString(),
17471
+ category: event.category,
17472
+ severity: event.severity,
17473
+ ...base,
17474
+ ip: event.source_ip,
17475
+ url,
17476
+ status,
17477
+ outcome: outcomeFor(status),
17478
+ crs_score: typeof d.crs_score === "number" ? d.crs_score : void 0,
17479
+ ua: str2(d.ua)
17480
+ };
17481
+ for (const k of Object.keys(record)) {
17482
+ if (record[k] === void 0) delete record[k];
17483
+ }
17484
+ return record;
17485
+ }
17486
+ function dedupeKey(r) {
17487
+ return `${r.at}|${r.ip ?? ""}|${r.message}`;
17488
+ }
17489
+ var WatchdogLog = class {
17490
+ dir;
17491
+ file;
17492
+ buffer = [];
17493
+ seen = /* @__PURE__ */ new Set();
17494
+ shareGid;
17495
+ stats = { logged: 0, answered: 0, errored: 0 };
17496
+ constructor(dir, options = {}) {
17497
+ this.dir = dir;
17498
+ this.file = (0, import_node_path16.join)(dir, LOG_FILE);
17499
+ this.shareGid = options.shareGid;
17500
+ (0, import_node_fs22.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
17501
+ if (this.shareGid !== void 0) {
17502
+ (0, import_node_fs22.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
17503
+ (0, import_node_fs22.chmodSync)(dir, 1528);
17504
+ }
17505
+ for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
17506
+ }
17507
+ remember(key) {
17508
+ this.seen.add(key);
17509
+ if (this.seen.size > SEEN_LIMIT) {
17510
+ const oldest = this.seen.values().next().value;
17511
+ if (oldest !== void 0) this.seen.delete(oldest);
17512
+ }
17513
+ }
17514
+ /** Logs the event if it is an attack not already logged. Returns the record when it was. */
17515
+ record(event) {
17516
+ if (!isAttack(event)) return null;
17517
+ const rec = toRecord(event);
17518
+ const key = dedupeKey(rec);
17519
+ if (this.seen.has(key)) return null;
17520
+ this.remember(key);
17521
+ this.buffer.push(JSON.stringify(rec));
17522
+ this.stats.logged++;
17523
+ if (rec.outcome === "answered") this.stats.answered++;
17524
+ if (rec.outcome === "errored") this.stats.errored++;
17525
+ return rec;
17526
+ }
17527
+ flush() {
17528
+ if (this.buffer.length === 0) return;
17529
+ const chunk = this.buffer.join("\n") + "\n";
17530
+ this.buffer = [];
17531
+ try {
17532
+ if ((0, import_node_fs22.statSync)(this.file).size > ROTATE_BYTES) {
17533
+ (0, import_node_fs22.renameSync)(this.file, (0, import_node_path16.join)(this.dir, ROTATED_FILE));
17534
+ }
17535
+ } catch {
17536
+ }
17537
+ (0, import_node_fs22.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
17538
+ if (this.shareGid !== void 0) {
17539
+ try {
17540
+ (0, import_node_fs22.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
17541
+ (0, import_node_fs22.chmodSync)(this.file, 432);
17542
+ } catch {
17543
+ }
17544
+ }
17545
+ }
17546
+ };
17547
+ function parseLines(text) {
17548
+ const out = [];
17549
+ for (const line of text.split("\n")) {
17550
+ if (!line) continue;
17551
+ try {
17552
+ const r = JSON.parse(line);
17553
+ if (r && r.v === 1 && typeof r.id === "string") out.push(r);
17554
+ } catch {
17555
+ }
17556
+ }
17557
+ return out;
17558
+ }
17559
+ function readTail(file, bytes) {
17560
+ let fd;
17561
+ try {
17562
+ fd = (0, import_node_fs22.openSync)(file, "r");
17563
+ } catch (err) {
17564
+ if (err.code === "ENOENT") return [];
17565
+ throw err;
17566
+ }
17567
+ try {
17568
+ const size = (0, import_node_fs22.fstatSync)(fd).size;
17569
+ const start = Math.max(0, size - bytes);
17570
+ const buf = Buffer.alloc(size - start);
17571
+ (0, import_node_fs22.readSync)(fd, buf, 0, buf.length, start);
17572
+ let text = buf.toString("utf8");
17573
+ if (start > 0) text = text.slice(text.indexOf("\n") + 1);
17574
+ return parseLines(text);
17575
+ } finally {
17576
+ (0, import_node_fs22.closeSync)(fd);
17577
+ }
17578
+ }
17579
+
17580
+ // src/daemon/watchdog-service.ts
17581
+ function defaultShareGid() {
17582
+ const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
17583
+ if (!isRoot2) return void 0;
17584
+ try {
17585
+ return (0, import_node_fs23.statSync)("/var/log/auth.log").gid;
17586
+ } catch {
17587
+ return void 0;
17588
+ }
17589
+ }
17590
+ function startWatchdog(opts) {
17591
+ const dir = opts.config?.dir ?? (0, import_node_path17.join)(opts.stateDir, WATCHDOG_DIRNAME);
17592
+ const base = { dir, logged: 0, answered: 0, errored: 0 };
17593
+ if (opts.config?.enabled === false) {
17594
+ opts.log("[watchdog] off ([watchdog] enabled = false)");
17595
+ return { status: () => ({ enabled: false, ...base }), stop: () => {
17596
+ } };
17597
+ }
17598
+ let log;
17599
+ try {
17600
+ log = new WatchdogLog(dir, { shareGid: opts.shareGid ?? defaultShareGid() });
17601
+ } catch (err) {
17602
+ const error2 = err.message;
17603
+ opts.log(`[watchdog] cannot open ${dir}: ${error2}`);
17604
+ return { status: () => ({ enabled: false, ...base, error: error2 }), stop: () => {
17605
+ } };
17606
+ }
17607
+ let error;
17608
+ const onEvent = (event) => {
17609
+ log.record(event);
17610
+ };
17611
+ const flush = () => {
17612
+ try {
17613
+ log.flush();
17614
+ error = void 0;
17615
+ } catch (err) {
17616
+ const message = err.message;
17617
+ if (message !== error) opts.log(`[watchdog] write failed: ${message}`);
17618
+ error = message;
17619
+ }
17620
+ };
17621
+ opts.bus.on("event", onEvent);
17622
+ const timer = setInterval(flush, opts.flushMs ?? 1e3);
17623
+ timer.unref?.();
17624
+ opts.log(`[watchdog] logging attacks to ${log.file}`);
17625
+ return {
17626
+ status: () => ({ enabled: true, dir, ...log.stats, ...error ? { error } : {} }),
17627
+ stop: () => {
17628
+ clearInterval(timer);
17629
+ opts.bus.off("event", onEvent);
17630
+ flush();
17631
+ }
17632
+ };
17633
+ }
17634
+
17329
17635
  // src/core/telemetry.ts
17330
17636
  var ready = false;
17331
17637
  var sentry = null;
@@ -17389,7 +17695,7 @@ function daemonNodeProblem(version) {
17389
17695
  // src/daemon/index.ts
17390
17696
  function readVersion2() {
17391
17697
  try {
17392
- const pkg = JSON.parse((0, import_node_fs21.readFileSync)((0, import_node_path16.join)(__dirname, "..", "package.json"), "utf-8"));
17698
+ const pkg = JSON.parse((0, import_node_fs24.readFileSync)((0, import_node_path18.join)(__dirname, "..", "package.json"), "utf-8"));
17393
17699
  return pkg.version || "0.0.0";
17394
17700
  } catch {
17395
17701
  return "0.0.0";
@@ -17398,7 +17704,7 @@ function readVersion2() {
17398
17704
  async function runHardeningChecks() {
17399
17705
  const { stdout } = await (0, import_node_util.promisify)(import_node_child_process7.execFile)(
17400
17706
  process.execPath,
17401
- [(0, import_node_path16.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
17707
+ [(0, import_node_path18.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
17402
17708
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
17403
17709
  );
17404
17710
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -17406,7 +17712,7 @@ async function runHardeningChecks() {
17406
17712
  }
17407
17713
  function logLine(line) {
17408
17714
  try {
17409
- (0, import_node_fs21.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
17715
+ (0, import_node_fs24.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
17410
17716
  `);
17411
17717
  } catch {
17412
17718
  }
@@ -17448,8 +17754,20 @@ async function runDaemon() {
17448
17754
  } catch (err) {
17449
17755
  logLine(`[daemon] state db unavailable: ${err.message}`);
17450
17756
  }
17451
- const config = loadConfig((0, import_node_fs21.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
17757
+ const config = loadConfig((0, import_node_fs24.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
17452
17758
  configureAttackDetection(config.detection);
17759
+ const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
17760
+ const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
17761
+ const prune = () => {
17762
+ try {
17763
+ const n = pruneEvents({ retentionSeconds, maxEvents });
17764
+ if (n) logLine(`[daemon] pruned ${n} events (keep ${config.storage?.event_retention ?? "14d"}, at most ${maxEvents})`);
17765
+ } catch (err) {
17766
+ logLine(`[daemon] event pruning failed: ${err.message}`);
17767
+ }
17768
+ };
17769
+ setTimeout(prune, 5e3);
17770
+ setInterval(prune, 6e4);
17453
17771
  bus.on("event", (event) => {
17454
17772
  logLine(`[event] ${event.severity} ${event.module} ${event.message}`);
17455
17773
  });
@@ -17515,7 +17833,7 @@ async function runDaemon() {
17515
17833
  version,
17516
17834
  hostname: (0, import_node_os5.hostname)(),
17517
17835
  minSeverity,
17518
- spoolPath: (0, import_node_path16.join)(PATHS.stateDir, "cloud-spool.jsonl"),
17836
+ spoolPath: (0, import_node_path18.join)(PATHS.stateDir, "cloud-spool.jsonl"),
17519
17837
  log: logLine,
17520
17838
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
17521
17839
  runHardening: runHardeningChecks
@@ -17528,7 +17846,8 @@ async function runDaemon() {
17528
17846
  const link = currentLink();
17529
17847
  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");
17530
17848
  }
17531
- const ipc = new IpcServer(version, moduleHost, remediation);
17849
+ const watchdog = startWatchdog({ bus, config: config.watchdog, stateDir: PATHS.stateDir, log: logLine });
17850
+ const ipc = new IpcServer(version, moduleHost, remediation, () => watchdog.status());
17532
17851
  await ipc.start();
17533
17852
  logLine(`[daemon] ipc listening on ${PATHS.socket}`);
17534
17853
  const shutdown = async (signal) => {
@@ -17557,6 +17876,10 @@ async function runDaemon() {
17557
17876
  await moduleHost.stop();
17558
17877
  } catch {
17559
17878
  }
17879
+ try {
17880
+ watchdog.stop();
17881
+ } catch {
17882
+ }
17560
17883
  try {
17561
17884
  await ipc.stop();
17562
17885
  } catch {