@profullstack/threatcrush 0.13.21 → 0.13.23

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,7 +2022,7 @@ var require_toml = __commonJS({
2022
2022
  });
2023
2023
 
2024
2024
  // src/daemon/index.ts
2025
- var import_node_fs23 = 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
2028
  var import_node_path18 = require("path");
@@ -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();
@@ -2623,7 +2658,7 @@ var IpcServer = class {
2623
2658
  };
2624
2659
 
2625
2660
  // src/daemon/module-host.ts
2626
- var import_node_fs11 = require("fs");
2661
+ var import_node_fs12 = require("fs");
2627
2662
  var import_node_path6 = require("path");
2628
2663
  var import_node_url = require("url");
2629
2664
  var import_toml2 = __toESM(require_toml());
@@ -2750,8 +2785,76 @@ function verifyModuleTrust(name, modulePath) {
2750
2785
  }
2751
2786
 
2752
2787
  // src/daemon/watchers/log-watcher.ts
2753
- var import_node_fs7 = require("fs");
2754
- 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
+ };
2755
2858
 
2756
2859
  // src/core/crs/rules.generated.ts
2757
2860
  var CRS_RULES = [
@@ -8941,12 +9044,12 @@ var TRANSFORMS = {
8941
9044
  };
8942
9045
 
8943
9046
  // src/core/crs/libinjection.ts
8944
- var import_node_fs6 = require("fs");
9047
+ var import_node_fs7 = require("fs");
8945
9048
  var import_node_path4 = require("path");
8946
9049
  var wasm;
8947
9050
  function loadLibinjection() {
8948
9051
  if (!wasm) {
8949
- 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"));
8950
9053
  wasm = new WebAssembly.Instance(new WebAssembly.Module(bytes), {}).exports;
8951
9054
  wasm._initialize();
8952
9055
  }
@@ -9457,14 +9560,14 @@ var LogWatcher = class {
9457
9560
  bus;
9458
9561
  sources;
9459
9562
  timers = /* @__PURE__ */ new Map();
9460
- positions = /* @__PURE__ */ new Map();
9563
+ tails = /* @__PURE__ */ new Map();
9461
9564
  active = /* @__PURE__ */ new Set();
9462
9565
  start() {
9463
9566
  const started = [];
9464
9567
  for (const src of this.sources) {
9465
- if (!(0, import_node_fs7.existsSync)(src.path)) continue;
9568
+ if (!(0, import_node_fs8.existsSync)(src.path)) continue;
9466
9569
  try {
9467
- (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);
9468
9571
  } catch {
9469
9572
  continue;
9470
9573
  }
@@ -9476,7 +9579,7 @@ var LogWatcher = class {
9476
9579
  stop() {
9477
9580
  for (const t of this.timers.values()) clearInterval(t);
9478
9581
  this.timers.clear();
9479
- this.positions.clear();
9582
+ this.tails.clear();
9480
9583
  this.active.clear();
9481
9584
  }
9482
9585
  activeModules() {
@@ -9491,38 +9594,22 @@ var LogWatcher = class {
9491
9594
  return this.sources.filter((s) => s.category === "auth" && this.timers.has(s.path)).map((s) => s.path);
9492
9595
  }
9493
9596
  tail(src) {
9494
- try {
9495
- this.positions.set(src.path, (0, import_node_fs7.statSync)(src.path).size);
9496
- } catch {
9497
- this.positions.set(src.path, 0);
9498
- }
9597
+ const tail = new LogTail(src.path);
9598
+ this.tails.set(src.path, tail);
9499
9599
  const timer = setInterval(() => this.poll(src), 1e3);
9500
9600
  this.timers.set(src.path, timer);
9501
9601
  this.active.add(src.module);
9502
9602
  }
9603
+ /** Each new line exactly once; see LogTail for why this is synchronous. */
9503
9604
  poll(src) {
9504
- let stat;
9505
- try {
9506
- stat = (0, import_node_fs7.statSync)(src.path);
9507
- } catch {
9508
- return;
9509
- }
9510
- const prev = this.positions.get(src.path) ?? 0;
9511
- if (stat.size < prev) {
9512
- this.positions.set(src.path, 0);
9513
- return;
9514
- }
9515
- if (stat.size === prev) return;
9516
- const stream = (0, import_node_fs7.createReadStream)(src.path, { start: prev, encoding: "utf-8" });
9517
- stream.on("error", () => this.positions.set(src.path, stat.size));
9518
- const rl = (0, import_node_readline.createInterface)({ input: stream });
9519
- rl.on("error", () => {
9520
- });
9521
- rl.on("line", (line) => {
9522
- if (!line.trim()) return;
9523
- 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
+ }
9524
9612
  });
9525
- rl.on("close", () => this.positions.set(src.path, stat.size));
9526
9613
  }
9527
9614
  process(line, src) {
9528
9615
  const parsed = autoDetectParser(line);
@@ -9777,7 +9864,7 @@ function realtimeToDate(rt) {
9777
9864
 
9778
9865
  // src/modules/network-monitor/index.ts
9779
9866
  var import_node_child_process2 = require("child_process");
9780
- var import_node_fs8 = require("fs");
9867
+ var import_node_fs9 = require("fs");
9781
9868
  var NetworkMonitor = class {
9782
9869
  constructor(bus2) {
9783
9870
  this.bus = bus2;
@@ -9841,7 +9928,7 @@ var NetworkMonitor = class {
9841
9928
  hasConntrackOrSs() {
9842
9929
  const ss = (0, import_node_child_process2.spawnSync)("ss", ["--version"], { stdio: "pipe" });
9843
9930
  if (ss.status === 0) return true;
9844
- return (0, import_node_fs8.existsSync)("/proc/net/tcp");
9931
+ return (0, import_node_fs9.existsSync)("/proc/net/tcp");
9845
9932
  }
9846
9933
  /**
9847
9934
  * The TCP ports this host actually listens on.
@@ -10028,9 +10115,9 @@ var NetworkMonitor = class {
10028
10115
  };
10029
10116
 
10030
10117
  // src/modules/dns-monitor/index.ts
10031
- var import_node_fs9 = require("fs");
10118
+ var import_node_fs10 = require("fs");
10032
10119
  var import_node_child_process3 = require("child_process");
10033
- var import_node_readline2 = require("readline");
10120
+ var import_node_readline = require("readline");
10034
10121
  var DNS_LOG_SOURCES = [
10035
10122
  "/var/log/syslog",
10036
10123
  // systemd-resolved logs here
@@ -10071,7 +10158,7 @@ var DnsMonitor = class {
10071
10158
  bus;
10072
10159
  active = false;
10073
10160
  timers = /* @__PURE__ */ new Map();
10074
- positions = /* @__PURE__ */ new Map();
10161
+ tails = /* @__PURE__ */ new Map();
10075
10162
  // Tracking windows
10076
10163
  txtQueryCounts = /* @__PURE__ */ new Map();
10077
10164
  domainBuffer = [];
@@ -10110,9 +10197,9 @@ var DnsMonitor = class {
10110
10197
  }
10111
10198
  start() {
10112
10199
  const sources = [...DNS_LOG_SOURCES, ...this.extraPaths].filter((p) => {
10113
- if (!(0, import_node_fs9.existsSync)(p)) return false;
10200
+ if (!(0, import_node_fs10.existsSync)(p)) return false;
10114
10201
  try {
10115
- (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);
10116
10203
  return true;
10117
10204
  } catch {
10118
10205
  return false;
@@ -10175,7 +10262,7 @@ var DnsMonitor = class {
10175
10262
  stdio: ["ignore", "pipe", "ignore"]
10176
10263
  });
10177
10264
  if (!child.stdout) return;
10178
- const rl = (0, import_node_readline2.createInterface)({ input: child.stdout });
10265
+ const rl = (0, import_node_readline.createInterface)({ input: child.stdout });
10179
10266
  rl.on("line", (line) => this.parseDnsLine(line));
10180
10267
  child.on("error", () => {
10181
10268
  });
@@ -10187,33 +10274,11 @@ var DnsMonitor = class {
10187
10274
  return this.active;
10188
10275
  }
10189
10276
  tailLog(path) {
10190
- try {
10191
- this.positions.set(path, (0, import_node_fs9.statSync)(path).size);
10192
- } catch {
10193
- this.positions.set(path, 0);
10194
- }
10195
- 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);
10196
10280
  this.timers.set(path, timer);
10197
10281
  }
10198
- pollLog(path) {
10199
- let stat;
10200
- try {
10201
- stat = (0, import_node_fs9.statSync)(path);
10202
- } catch {
10203
- return;
10204
- }
10205
- const prev = this.positions.get(path) ?? 0;
10206
- if (stat.size < prev) {
10207
- this.positions.set(path, 0);
10208
- return;
10209
- }
10210
- if (stat.size === prev) return;
10211
- const stream = (0, import_node_fs9.createReadStream)(path, { start: prev, encoding: "utf-8" });
10212
- stream.on("error", () => this.positions.set(path, stat.size));
10213
- const rl = (0, import_node_readline2.createInterface)({ input: stream });
10214
- rl.on("line", (line) => this.parseDnsLine(line));
10215
- rl.on("close", () => this.positions.set(path, stat.size));
10216
- }
10217
10282
  parseDnsLine(line) {
10218
10283
  const moshpit = line.match(
10219
10284
  /\[dns\]\s+(?:udp|tcp|doh)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\w+)/i
@@ -10354,7 +10419,7 @@ var DnsMonitor = class {
10354
10419
  };
10355
10420
 
10356
10421
  // src/core/config.ts
10357
- var import_node_fs10 = require("fs");
10422
+ var import_node_fs11 = require("fs");
10358
10423
  var import_node_path5 = require("path");
10359
10424
  var import_toml = __toESM(require_toml());
10360
10425
  var DEFAULT_CONFIG_PATH = "/etc/threatcrush/threatcrushd.conf";
@@ -10381,11 +10446,11 @@ var DEFAULT_CONFIG = {
10381
10446
  };
10382
10447
  function loadConfig(configPath) {
10383
10448
  const path = configPath || DEFAULT_CONFIG_PATH;
10384
- if (!(0, import_node_fs10.existsSync)(path)) {
10449
+ if (!(0, import_node_fs11.existsSync)(path)) {
10385
10450
  return { ...DEFAULT_CONFIG };
10386
10451
  }
10387
10452
  try {
10388
- const raw = (0, import_node_fs10.readFileSync)(path, "utf-8");
10453
+ const raw = (0, import_node_fs11.readFileSync)(path, "utf-8");
10389
10454
  const parsed = import_toml.default.parse(raw);
10390
10455
  return {
10391
10456
  daemon: { ...DEFAULT_CONFIG.daemon, ...parsed.daemon },
@@ -10396,6 +10461,7 @@ function loadConfig(configPath) {
10396
10461
  detection: parsed.detection,
10397
10462
  cloud: parsed.cloud,
10398
10463
  watchdog: parsed.watchdog,
10464
+ storage: parsed.storage,
10399
10465
  license: parsed.license
10400
10466
  };
10401
10467
  } catch {
@@ -10405,13 +10471,13 @@ function loadConfig(configPath) {
10405
10471
  function loadModuleConfigs(confDir) {
10406
10472
  const dir = confDir || DEFAULT_CONFDIR;
10407
10473
  const configs = /* @__PURE__ */ new Map();
10408
- if (!(0, import_node_fs10.existsSync)(dir)) {
10474
+ if (!(0, import_node_fs11.existsSync)(dir)) {
10409
10475
  return configs;
10410
10476
  }
10411
- 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"));
10412
10478
  for (const file of files) {
10413
10479
  try {
10414
- 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");
10415
10481
  const parsed = import_toml.default.parse(raw);
10416
10482
  for (const [name, config] of Object.entries(parsed)) {
10417
10483
  configs.set(name, config);
@@ -10545,15 +10611,15 @@ var ModuleHost = class {
10545
10611
  }
10546
10612
  }
10547
10613
  async discoverAndStartInstalled() {
10548
- if (!(0, import_node_fs11.existsSync)(PATHS.moduleDir)) return;
10614
+ if (!(0, import_node_fs12.existsSync)(PATHS.moduleDir)) return;
10549
10615
  const configs = loadModuleConfigs(PATHS.confD);
10550
- const entries = (0, import_node_fs11.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
10616
+ const entries = (0, import_node_fs12.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
10551
10617
  for (const entry of entries) {
10552
10618
  if (!entry.isDirectory()) continue;
10553
10619
  const manifestPath = (0, import_node_path6.join)(PATHS.moduleDir, entry.name, "mod.toml");
10554
- if (!(0, import_node_fs11.existsSync)(manifestPath)) continue;
10620
+ if (!(0, import_node_fs12.existsSync)(manifestPath)) continue;
10555
10621
  try {
10556
- 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"));
10557
10623
  const name = manifest.module?.name || entry.name;
10558
10624
  const defaults = manifest.module?.config?.defaults || {};
10559
10625
  const config = {
@@ -10623,15 +10689,15 @@ var ModuleHost = class {
10623
10689
  installedEntrypoint(modulePath) {
10624
10690
  const packageJson = (0, import_node_path6.join)(modulePath, "package.json");
10625
10691
  const candidates = [];
10626
- if ((0, import_node_fs11.existsSync)(packageJson)) {
10692
+ if ((0, import_node_fs12.existsSync)(packageJson)) {
10627
10693
  try {
10628
- 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"));
10629
10695
  if (pkg.main) candidates.push((0, import_node_path6.join)(modulePath, pkg.main));
10630
10696
  } catch {
10631
10697
  }
10632
10698
  }
10633
10699
  candidates.push((0, import_node_path6.join)(modulePath, "dist", "index.js"), (0, import_node_path6.join)(modulePath, "index.js"));
10634
- return candidates.find((candidate) => (0, import_node_fs11.existsSync)(candidate)) || null;
10700
+ return candidates.find((candidate) => (0, import_node_fs12.existsSync)(candidate)) || null;
10635
10701
  }
10636
10702
  isThreatCrushModule(value) {
10637
10703
  return Boolean(
@@ -10903,7 +10969,7 @@ function slackChannel(webhookUrl) {
10903
10969
  }
10904
10970
 
10905
10971
  // src/core/cli-config.ts
10906
- var import_node_fs12 = require("fs");
10972
+ var import_node_fs13 = require("fs");
10907
10973
  var import_node_path7 = require("path");
10908
10974
  var import_node_os2 = require("os");
10909
10975
  var CLI_CONFIG_DIR = (0, import_node_path7.join)((0, import_node_os2.homedir)(), ".threatcrush");
@@ -10913,16 +10979,16 @@ function apiUrl() {
10913
10979
  }
10914
10980
  function readCliConfig() {
10915
10981
  try {
10916
- 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"));
10917
10983
  } catch {
10918
10984
  return {};
10919
10985
  }
10920
10986
  }
10921
10987
  function writeCliConfig(config) {
10922
- if (!(0, import_node_fs12.existsSync)(CLI_CONFIG_DIR)) (0, import_node_fs12.mkdirSync)(CLI_CONFIG_DIR, { recursive: true });
10923
- (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");
10924
10990
  try {
10925
- (0, import_node_fs12.chmodSync)(CLI_CONFIG_PATH, 384);
10991
+ (0, import_node_fs13.chmodSync)(CLI_CONFIG_PATH, 384);
10926
10992
  } catch {
10927
10993
  }
10928
10994
  }
@@ -10998,7 +11064,7 @@ async function cloudFetch(path, init = {}) {
10998
11064
  }
10999
11065
 
11000
11066
  // src/commands/scan.ts
11001
- var import_node_fs16 = require("fs");
11067
+ var import_node_fs17 = require("fs");
11002
11068
  var import_node_path12 = require("path");
11003
11069
 
11004
11070
  // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
@@ -11497,13 +11563,13 @@ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
11497
11563
  var source_default = chalk;
11498
11564
 
11499
11565
  // src/core/version.ts
11500
- var import_node_fs13 = require("fs");
11566
+ var import_node_fs14 = require("fs");
11501
11567
  var import_node_path8 = require("path");
11502
11568
  var FALLBACK_VERSION = "0.0.0";
11503
11569
  function readPackageVersion() {
11504
11570
  try {
11505
11571
  const pkg = JSON.parse(
11506
- (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")
11507
11573
  );
11508
11574
  return pkg.version || FALLBACK_VERSION;
11509
11575
  } catch {
@@ -14510,7 +14576,7 @@ function scanManifest(relativePath, filename, text) {
14510
14576
  }
14511
14577
 
14512
14578
  // ../../packages/scan/src/node/walk.ts
14513
- var import_node_fs14 = require("fs");
14579
+ var import_node_fs15 = require("fs");
14514
14580
  var import_node_path9 = require("path");
14515
14581
  function compileExcludes(patterns) {
14516
14582
  const matchers = patterns.map((p) => p.trim()).filter((p) => p.length > 0 && !p.startsWith("#")).map(compilePattern);
@@ -14582,7 +14648,7 @@ function matchPrefix(parts, segs) {
14582
14648
  }
14583
14649
  function readIgnoreFile(root) {
14584
14650
  try {
14585
- 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");
14586
14652
  } catch {
14587
14653
  return [];
14588
14654
  }
@@ -14598,7 +14664,7 @@ function scanPath(targetPath, options = {}) {
14598
14664
  let excluded = 0;
14599
14665
  const rootIsDirectory = (() => {
14600
14666
  try {
14601
- return (0, import_node_fs14.statSync)(targetPath).isDirectory();
14667
+ return (0, import_node_fs15.statSync)(targetPath).isDirectory();
14602
14668
  } catch {
14603
14669
  return true;
14604
14670
  }
@@ -14619,26 +14685,26 @@ function scanPath(targetPath, options = {}) {
14619
14685
  let handle;
14620
14686
  let declared = null;
14621
14687
  try {
14622
- handle = (0, import_node_fs14.openSync)(fullPath, "r");
14688
+ handle = (0, import_node_fs15.openSync)(fullPath, "r");
14623
14689
  } catch {
14624
14690
  unreadable.push(relativePath);
14625
14691
  return;
14626
14692
  }
14627
14693
  try {
14628
- if ((0, import_node_fs14.fstatSync)(handle).size > maxFileBytes) return;
14694
+ if ((0, import_node_fs15.fstatSync)(handle).size > maxFileBytes) return;
14629
14695
  if (mayDeclareInterpreter) {
14630
14696
  const prefix = Buffer.alloc(128);
14631
- 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);
14632
14698
  declared = languageOfShebang(prefix.subarray(0, read).toString("utf-8").split("\n", 1)[0] ?? "");
14633
14699
  if (!declared) return;
14634
14700
  }
14635
- text = (0, import_node_fs14.readFileSync)(handle, "utf-8");
14701
+ text = (0, import_node_fs15.readFileSync)(handle, "utf-8");
14636
14702
  } catch {
14637
14703
  unreadable.push(relativePath);
14638
14704
  return;
14639
14705
  } finally {
14640
14706
  try {
14641
- (0, import_node_fs14.closeSync)(handle);
14707
+ (0, import_node_fs15.closeSync)(handle);
14642
14708
  } catch {
14643
14709
  }
14644
14710
  }
@@ -14656,7 +14722,7 @@ function scanPath(targetPath, options = {}) {
14656
14722
  const walk = (currentPath) => {
14657
14723
  let entries;
14658
14724
  try {
14659
- entries = (0, import_node_fs14.readdirSync)(currentPath, { withFileTypes: true });
14725
+ entries = (0, import_node_fs15.readdirSync)(currentPath, { withFileTypes: true });
14660
14726
  } catch {
14661
14727
  unreadable.push(toRelative(walkRoot, currentPath));
14662
14728
  return;
@@ -14723,17 +14789,17 @@ function toRelative(base, target) {
14723
14789
  }
14724
14790
 
14725
14791
  // ../../packages/scan/src/node/dependencies.ts
14726
- var import_node_fs15 = require("fs");
14792
+ var import_node_fs16 = require("fs");
14727
14793
  var import_node_path10 = require("path");
14728
14794
  var MAX_DEPS_PER_LOCKFILE = 50;
14729
14795
  async function scanDependencies(targetPath) {
14730
14796
  const findings = [];
14731
14797
  for (const { file, ecosystem, parse } of LOCKFILES) {
14732
14798
  const lockPath = (0, import_node_path10.join)(targetPath, file);
14733
- if (!(0, import_node_fs15.existsSync)(lockPath)) continue;
14799
+ if (!(0, import_node_fs16.existsSync)(lockPath)) continue;
14734
14800
  let deps;
14735
14801
  try {
14736
- deps = dedupe(parse((0, import_node_fs15.readFileSync)(lockPath, "utf-8")));
14802
+ deps = dedupe(parse((0, import_node_fs16.readFileSync)(lockPath, "utf-8")));
14737
14803
  } catch {
14738
14804
  continue;
14739
14805
  }
@@ -14957,7 +15023,7 @@ function readVersion() {
14957
15023
  (0, import_node_path12.join)(__dirname, "..", "..", "package.json")
14958
15024
  ]) {
14959
15025
  try {
14960
- 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";
14961
15027
  } catch {
14962
15028
  }
14963
15029
  }
@@ -15400,7 +15466,7 @@ function findingEvents(serverId, results, observedAt = /* @__PURE__ */ new Date(
15400
15466
  }
15401
15467
 
15402
15468
  // src/daemon/workers/cloud-spool.ts
15403
- var import_node_fs17 = require("fs");
15469
+ var import_node_fs18 = require("fs");
15404
15470
  var import_promises = require("fs/promises");
15405
15471
  var import_node_path13 = require("path");
15406
15472
  var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
@@ -15409,7 +15475,7 @@ var CloudSpool = class {
15409
15475
  this.path = path;
15410
15476
  this.limits = limits;
15411
15477
  try {
15412
- (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 });
15413
15479
  } catch {
15414
15480
  }
15415
15481
  this.load();
@@ -15478,7 +15544,7 @@ var CloudSpool = class {
15478
15544
  load() {
15479
15545
  let raw;
15480
15546
  try {
15481
- raw = (0, import_node_fs17.readFileSync)(this.path, "utf-8");
15547
+ raw = (0, import_node_fs18.readFileSync)(this.path, "utf-8");
15482
15548
  } catch {
15483
15549
  return;
15484
15550
  }
@@ -16063,6 +16129,19 @@ var RemediationConsumer = class {
16063
16129
  };
16064
16130
 
16065
16131
  // src/daemon/rules/engine.ts
16132
+ var MAX_WINDOW_ENTRIES = 1e3;
16133
+ function live(window) {
16134
+ return window.times.length - window.head;
16135
+ }
16136
+ function expire(window, now) {
16137
+ const cutoff = now - window.windowMs;
16138
+ while (window.head < window.times.length && window.times[window.head] < cutoff) window.head++;
16139
+ if (window.head > 64 && window.head * 2 > window.times.length) {
16140
+ window.times = window.times.slice(window.head);
16141
+ window.ips = window.ips.slice(window.head);
16142
+ window.head = 0;
16143
+ }
16144
+ }
16066
16145
  var RuleEngine = class {
16067
16146
  constructor(onDetection) {
16068
16147
  this.onDetection = onDetection;
@@ -16088,27 +16167,42 @@ var RuleEngine = class {
16088
16167
  const windowKey = `${rule.id}:${groupBy}:${groupValue}`;
16089
16168
  let window = this.windows.get(windowKey);
16090
16169
  if (!window) {
16091
- window = { events: [], lastAlert: 0 };
16170
+ window = {
16171
+ times: [],
16172
+ ips: [],
16173
+ head: 0,
16174
+ lastAlert: 0,
16175
+ windowMs: rule.window_seconds * 1e3,
16176
+ cooldownMs: rule.cooldown_seconds * 1e3
16177
+ };
16092
16178
  this.windows.set(windowKey, window);
16093
16179
  }
16094
- window.events.push({ timestamp: now, event });
16095
- const cutoff = now - rule.window_seconds * 1e3;
16096
- window.events = window.events.filter((e) => e.timestamp >= cutoff);
16097
- if (window.events.length < rule.threshold) continue;
16098
- if (window.lastAlert > 0 && now - window.lastAlert < rule.cooldown_seconds * 1e3) continue;
16099
- const hits = window.events.length;
16100
- const distinctIps = new Set(
16101
- window.events.map((e) => e.event.source_ip).filter(Boolean)
16102
- ).size;
16180
+ window.times.push(now);
16181
+ window.ips.push(event.source_ip);
16182
+ expire(window, now);
16183
+ const cap = Math.max(rule.threshold, MAX_WINDOW_ENTRIES);
16184
+ let capped = false;
16185
+ if (live(window) > cap) {
16186
+ window.head = window.times.length - cap;
16187
+ capped = true;
16188
+ expire(window, now);
16189
+ }
16190
+ if (live(window) < rule.threshold) continue;
16191
+ if (window.lastAlert > 0 && now - window.lastAlert < window.cooldownMs) continue;
16192
+ const hits = live(window);
16193
+ const distinctIps = new Set(window.ips.slice(window.head).filter(Boolean)).size;
16103
16194
  window.lastAlert = now;
16104
- window.events = [];
16195
+ window.times = [];
16196
+ window.ips = [];
16197
+ window.head = 0;
16198
+ const hitsLabel = capped ? `${hits}+` : String(hits);
16105
16199
  const aggregate = groupBy !== "source_ip";
16106
16200
  const spread = aggregate ? ` from ${distinctIps} address${distinctIps === 1 ? "" : "es"}${groupBy === "endpoint" ? ` against ${groupValue}` : ""}` : "";
16107
16201
  this.onDetection({
16108
16202
  rule_id: rule.id,
16109
16203
  severity: rule.severity,
16110
16204
  title: rule.title,
16111
- description: `${rule.description} (${hits} events in ${rule.window_seconds}s${spread})`,
16205
+ description: `${rule.description} (${hitsLabel} events in ${rule.window_seconds}s${spread})`,
16112
16206
  source_ip: aggregate ? void 0 : event.source_ip,
16113
16207
  username: event.details?.user || void 0,
16114
16208
  raw_metadata: {
@@ -16171,19 +16265,31 @@ var RuleEngine = class {
16171
16265
  return event.details?.[field];
16172
16266
  }
16173
16267
  }
16174
- // Periodic cleanup of stale windows
16175
- cleanup() {
16176
- const now = Date.now();
16177
- for (const [key, window] of this.windows.entries()) {
16178
- if (window.events.length === 0 && now - window.lastAlert > 36e5) {
16268
+ /**
16269
+ * Expire every window by its own rule's length, and forget windows with
16270
+ * nothing left in them once their cooldown is over (a cooldown must outlive
16271
+ * an empty window, or a source could re-trigger the moment it was forgotten).
16272
+ * Without the expiry, a window whose address never came back was kept forever.
16273
+ */
16274
+ cleanup(now = Date.now()) {
16275
+ let removed = 0;
16276
+ for (const [key, window] of this.windows) {
16277
+ expire(window, now);
16278
+ if (live(window) === 0 && (window.lastAlert === 0 || now - window.lastAlert >= window.cooldownMs)) {
16179
16279
  this.windows.delete(key);
16280
+ removed++;
16180
16281
  }
16181
16282
  }
16283
+ return removed;
16284
+ }
16285
+ /** How many windows are open, for tests and the status report. */
16286
+ windowCount() {
16287
+ return this.windows.size;
16182
16288
  }
16183
16289
  };
16184
16290
 
16185
16291
  // src/daemon/rules/loader.ts
16186
- var import_node_fs18 = require("fs");
16292
+ var import_node_fs19 = require("fs");
16187
16293
  var import_node_path14 = require("path");
16188
16294
 
16189
16295
  // src/daemon/rules/default-rules.ts
@@ -16585,11 +16691,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
16585
16691
  function loadAllRules(customDir) {
16586
16692
  const rules = [...DEFAULT_RULES];
16587
16693
  const dir = customDir || RULES_DIR;
16588
- if ((0, import_node_fs18.existsSync)(dir)) {
16589
- const files = (0, import_node_fs18.readdirSync)(dir).filter((f) => f.endsWith(".json"));
16694
+ if ((0, import_node_fs19.existsSync)(dir)) {
16695
+ const files = (0, import_node_fs19.readdirSync)(dir).filter((f) => f.endsWith(".json"));
16590
16696
  for (const file of files) {
16591
16697
  try {
16592
- const raw = (0, import_node_fs18.readFileSync)((0, import_node_path14.join)(dir, file), "utf-8");
16698
+ const raw = (0, import_node_fs19.readFileSync)((0, import_node_path14.join)(dir, file), "utf-8");
16593
16699
  const parsed = JSON.parse(raw);
16594
16700
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
16595
16701
  for (const rule of customRules) {
@@ -16621,7 +16727,7 @@ function loadAllRules(customDir) {
16621
16727
 
16622
16728
  // src/daemon/firewall/adapters.ts
16623
16729
  var import_node_child_process5 = require("child_process");
16624
- var import_node_fs19 = require("fs");
16730
+ var import_node_fs20 = require("fs");
16625
16731
  var import_node_path15 = require("path");
16626
16732
  var import_node_net6 = require("net");
16627
16733
  function assertValidFirewallIp(ip) {
@@ -16635,9 +16741,9 @@ function assertBannableIp(ip) {
16635
16741
  }
16636
16742
  }
16637
16743
  function writeIfAbsent(path, contents) {
16638
- (0, import_node_fs19.mkdirSync)((0, import_node_path15.dirname)(path), { recursive: true });
16744
+ (0, import_node_fs20.mkdirSync)((0, import_node_path15.dirname)(path), { recursive: true });
16639
16745
  try {
16640
- (0, import_node_fs19.writeFileSync)(path, contents, { flag: "wx" });
16746
+ (0, import_node_fs20.writeFileSync)(path, contents, { flag: "wx" });
16641
16747
  } catch (err) {
16642
16748
  if (err.code !== "EEXIST") throw err;
16643
16749
  }
@@ -16892,7 +16998,7 @@ function detectFirewallAdapter(backend = "auto") {
16892
16998
  }
16893
16999
 
16894
17000
  // src/daemon/firewall/remediation.ts
16895
- var import_node_fs20 = require("fs");
17001
+ var import_node_fs21 = require("fs");
16896
17002
  var import_node_net7 = require("net");
16897
17003
 
16898
17004
  // src/daemon/firewall/crawlers.ts
@@ -17216,7 +17322,7 @@ var RemediationManager = class {
17216
17322
  */
17217
17323
  async reconcile() {
17218
17324
  const now = Date.now();
17219
- const live = this.blocklist.filter((b) => b.expires_at > now);
17325
+ const live2 = this.blocklist.filter((b) => b.expires_at > now);
17220
17326
  const stale = this.blocklist.filter((b) => b.expires_at <= now);
17221
17327
  for (const entry of stale) {
17222
17328
  if (!entry.dry_run) {
@@ -17226,7 +17332,7 @@ var RemediationManager = class {
17226
17332
  }
17227
17333
  }
17228
17334
  }
17229
- this.blocklist = live;
17335
+ this.blocklist = live2;
17230
17336
  this.saveState();
17231
17337
  let applied = null;
17232
17338
  try {
@@ -17234,7 +17340,7 @@ var RemediationManager = class {
17234
17340
  } catch {
17235
17341
  }
17236
17342
  if (applied) {
17237
- const known = new Set(live.filter((b) => !b.dry_run).map((b) => b.ip));
17343
+ const known = new Set(live2.filter((b) => !b.dry_run).map((b) => b.ip));
17238
17344
  for (const ip of applied) {
17239
17345
  if (known.has(ip)) continue;
17240
17346
  this.logLine(`[firewall] reconcile: dropping stale rule for ${ip} (no record of why)`);
@@ -17245,7 +17351,7 @@ var RemediationManager = class {
17245
17351
  }
17246
17352
  }
17247
17353
  if (this.config.dry_run) return;
17248
- for (const entry of live) {
17354
+ for (const entry of live2) {
17249
17355
  if (applied?.includes(entry.ip)) continue;
17250
17356
  try {
17251
17357
  await this.adapter.block(entry.ip);
@@ -17300,7 +17406,7 @@ var RemediationManager = class {
17300
17406
  }
17301
17407
  logLine(line) {
17302
17408
  try {
17303
- (0, import_node_fs20.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
17409
+ (0, import_node_fs21.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
17304
17410
  `);
17305
17411
  } catch {
17306
17412
  }
@@ -17334,11 +17440,11 @@ function remediationSettings(section) {
17334
17440
  }
17335
17441
 
17336
17442
  // src/daemon/watchdog-service.ts
17337
- var import_node_fs22 = require("fs");
17443
+ var import_node_fs23 = require("fs");
17338
17444
  var import_node_path17 = require("path");
17339
17445
 
17340
17446
  // src/core/watchdog.ts
17341
- var import_node_fs21 = require("fs");
17447
+ var import_node_fs22 = require("fs");
17342
17448
  var import_node_crypto5 = require("crypto");
17343
17449
  var import_node_path16 = require("path");
17344
17450
  var WATCHDOG_DIRNAME = "watchdog";
@@ -17431,10 +17537,10 @@ var WatchdogLog = class {
17431
17537
  this.dir = dir;
17432
17538
  this.file = (0, import_node_path16.join)(dir, LOG_FILE);
17433
17539
  this.shareGid = options.shareGid;
17434
- (0, import_node_fs21.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
17540
+ (0, import_node_fs22.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
17435
17541
  if (this.shareGid !== void 0) {
17436
- (0, import_node_fs21.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
17437
- (0, import_node_fs21.chmodSync)(dir, 1528);
17542
+ (0, import_node_fs22.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
17543
+ (0, import_node_fs22.chmodSync)(dir, 1528);
17438
17544
  }
17439
17545
  for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
17440
17546
  }
@@ -17463,16 +17569,16 @@ var WatchdogLog = class {
17463
17569
  const chunk = this.buffer.join("\n") + "\n";
17464
17570
  this.buffer = [];
17465
17571
  try {
17466
- if ((0, import_node_fs21.statSync)(this.file).size > ROTATE_BYTES) {
17467
- (0, import_node_fs21.renameSync)(this.file, (0, import_node_path16.join)(this.dir, ROTATED_FILE));
17572
+ if ((0, import_node_fs22.statSync)(this.file).size > ROTATE_BYTES) {
17573
+ (0, import_node_fs22.renameSync)(this.file, (0, import_node_path16.join)(this.dir, ROTATED_FILE));
17468
17574
  }
17469
17575
  } catch {
17470
17576
  }
17471
- (0, import_node_fs21.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
17577
+ (0, import_node_fs22.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
17472
17578
  if (this.shareGid !== void 0) {
17473
17579
  try {
17474
- (0, import_node_fs21.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
17475
- (0, import_node_fs21.chmodSync)(this.file, 432);
17580
+ (0, import_node_fs22.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
17581
+ (0, import_node_fs22.chmodSync)(this.file, 432);
17476
17582
  } catch {
17477
17583
  }
17478
17584
  }
@@ -17493,21 +17599,21 @@ function parseLines(text) {
17493
17599
  function readTail(file, bytes) {
17494
17600
  let fd;
17495
17601
  try {
17496
- fd = (0, import_node_fs21.openSync)(file, "r");
17602
+ fd = (0, import_node_fs22.openSync)(file, "r");
17497
17603
  } catch (err) {
17498
17604
  if (err.code === "ENOENT") return [];
17499
17605
  throw err;
17500
17606
  }
17501
17607
  try {
17502
- const size = (0, import_node_fs21.fstatSync)(fd).size;
17608
+ const size = (0, import_node_fs22.fstatSync)(fd).size;
17503
17609
  const start = Math.max(0, size - bytes);
17504
17610
  const buf = Buffer.alloc(size - start);
17505
- (0, import_node_fs21.readSync)(fd, buf, 0, buf.length, start);
17611
+ (0, import_node_fs22.readSync)(fd, buf, 0, buf.length, start);
17506
17612
  let text = buf.toString("utf8");
17507
17613
  if (start > 0) text = text.slice(text.indexOf("\n") + 1);
17508
17614
  return parseLines(text);
17509
17615
  } finally {
17510
- (0, import_node_fs21.closeSync)(fd);
17616
+ (0, import_node_fs22.closeSync)(fd);
17511
17617
  }
17512
17618
  }
17513
17619
 
@@ -17516,7 +17622,7 @@ function defaultShareGid() {
17516
17622
  const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
17517
17623
  if (!isRoot2) return void 0;
17518
17624
  try {
17519
- return (0, import_node_fs22.statSync)("/var/log/auth.log").gid;
17625
+ return (0, import_node_fs23.statSync)("/var/log/auth.log").gid;
17520
17626
  } catch {
17521
17627
  return void 0;
17522
17628
  }
@@ -17629,7 +17735,7 @@ function daemonNodeProblem(version) {
17629
17735
  // src/daemon/index.ts
17630
17736
  function readVersion2() {
17631
17737
  try {
17632
- const pkg = JSON.parse((0, import_node_fs23.readFileSync)((0, import_node_path18.join)(__dirname, "..", "package.json"), "utf-8"));
17738
+ const pkg = JSON.parse((0, import_node_fs24.readFileSync)((0, import_node_path18.join)(__dirname, "..", "package.json"), "utf-8"));
17633
17739
  return pkg.version || "0.0.0";
17634
17740
  } catch {
17635
17741
  return "0.0.0";
@@ -17646,7 +17752,7 @@ async function runHardeningChecks() {
17646
17752
  }
17647
17753
  function logLine(line) {
17648
17754
  try {
17649
- (0, import_node_fs23.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
17755
+ (0, import_node_fs24.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
17650
17756
  `);
17651
17757
  } catch {
17652
17758
  }
@@ -17688,8 +17794,20 @@ async function runDaemon() {
17688
17794
  } catch (err) {
17689
17795
  logLine(`[daemon] state db unavailable: ${err.message}`);
17690
17796
  }
17691
- const config = loadConfig((0, import_node_fs23.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
17797
+ const config = loadConfig((0, import_node_fs24.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
17692
17798
  configureAttackDetection(config.detection);
17799
+ const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
17800
+ const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
17801
+ const prune = () => {
17802
+ try {
17803
+ const n = pruneEvents({ retentionSeconds, maxEvents });
17804
+ if (n) logLine(`[daemon] pruned ${n} events (keep ${config.storage?.event_retention ?? "14d"}, at most ${maxEvents})`);
17805
+ } catch (err) {
17806
+ logLine(`[daemon] event pruning failed: ${err.message}`);
17807
+ }
17808
+ };
17809
+ setTimeout(prune, 5e3);
17810
+ setInterval(prune, 6e4);
17693
17811
  bus.on("event", (event) => {
17694
17812
  logLine(`[event] ${event.severity} ${event.module} ${event.message}`);
17695
17813
  });
@@ -17717,7 +17835,7 @@ async function runDaemon() {
17717
17835
  if (event.module !== "rule-engine") ruleEngine.evaluate(event);
17718
17836
  });
17719
17837
  logLine(`[daemon] rule engine loaded ${ruleEngine.getRules().length} rules`);
17720
- setInterval(() => ruleEngine.cleanup(), 3e5);
17838
+ setInterval(() => ruleEngine.cleanup(), 6e4);
17721
17839
  const settings = remediationSettings(config.remediation);
17722
17840
  const firewallAdapter = detectFirewallAdapter(config.remediation?.backend ?? "auto");
17723
17841
  const remediation = new RemediationManager(firewallAdapter, bus, settings);