@profullstack/threatcrush 0.13.22 → 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/index.js CHANGED
@@ -29641,24 +29641,24 @@ async function statusCommand() {
29641
29641
  banner();
29642
29642
  const pid = findRunningDaemon();
29643
29643
  const client = new IpcClient();
29644
- let live = null;
29644
+ let live2 = null;
29645
29645
  try {
29646
29646
  await client.connect();
29647
- live = await client.status();
29647
+ live2 = await client.status();
29648
29648
  } catch {
29649
29649
  } finally {
29650
29650
  client.close();
29651
29651
  }
29652
29652
  console.log(source_default.green.bold(" Daemon Status"));
29653
29653
  console.log(source_default.gray(" " + "\u2500".repeat(60)));
29654
- if (live) {
29654
+ if (live2) {
29655
29655
  console.log(` Status: ${source_default.green.bold("\u25CF RUNNING")}`);
29656
- console.log(` PID: ${source_default.white(String(live.pid))}`);
29657
- console.log(` Started: ${source_default.white(live.startedAt)}`);
29658
- console.log(` Uptime: ${source_default.white(formatUptime2(live.uptimeSeconds))}`);
29659
- console.log(` Version: ${source_default.white(live.version)}`);
29660
- console.log(` Mode: ${source_default.white(live.mode)}`);
29661
- console.log(` Socket: ${source_default.gray(live.paths.socket)}`);
29656
+ console.log(` PID: ${source_default.white(String(live2.pid))}`);
29657
+ console.log(` Started: ${source_default.white(live2.startedAt)}`);
29658
+ console.log(` Uptime: ${source_default.white(formatUptime2(live2.uptimeSeconds))}`);
29659
+ console.log(` Version: ${source_default.white(live2.version)}`);
29660
+ console.log(` Mode: ${source_default.white(live2.mode)}`);
29661
+ console.log(` Socket: ${source_default.gray(live2.paths.socket)}`);
29662
29662
  } else if (pid) {
29663
29663
  console.log(` Status: ${source_default.yellow.bold("\u25CF RUNNING (IPC unreachable)")}`);
29664
29664
  console.log(` PID: ${source_default.white(String(pid))}`);
@@ -29670,8 +29670,8 @@ async function statusCommand() {
29670
29670
  console.log();
29671
29671
  console.log(source_default.green.bold(" Modules"));
29672
29672
  console.log(source_default.gray(" " + "\u2500".repeat(60)));
29673
- if (live && live.modules.length > 0) {
29674
- for (const mod of live.modules) {
29673
+ if (live2 && live2.modules.length > 0) {
29674
+ for (const mod of live2.modules) {
29675
29675
  const dot = mod.status === "running" ? source_default.green("\u25CF") : mod.status === "loaded" ? source_default.cyan("\u25CB") : mod.status === "error" ? source_default.red("\u2717") : source_default.gray("\u25CB");
29676
29676
  console.log(` ${dot} ${source_default.white.bold(mod.name.padEnd(18))} ${source_default.gray(mod.status.padEnd(10))} ${source_default.dim(`${mod.events} events`)}`);
29677
29677
  }
@@ -29700,9 +29700,9 @@ async function statusCommand() {
29700
29700
  }
29701
29701
  console.log();
29702
29702
  try {
29703
- if (!live) initStateDB(PATHS.stateDb);
29704
- const total = live ? live.counters.events : getEventCount();
29705
- const threats = live ? live.counters.threats : getThreatCount();
29703
+ if (!live2) initStateDB(PATHS.stateDb);
29704
+ const total = live2 ? live2.counters.events : getEventCount();
29705
+ const threats = live2 ? live2.counters.threats : getThreatCount();
29706
29706
  const last24h = getEventCount(new Date(Date.now() - 864e5));
29707
29707
  const threats24h = getThreatCount(new Date(Date.now() - 864e5));
29708
29708
  console.log(source_default.green.bold(" Event Statistics"));
@@ -34007,6 +34007,19 @@ var RemediationConsumer = class {
34007
34007
  };
34008
34008
 
34009
34009
  // src/daemon/rules/engine.ts
34010
+ var MAX_WINDOW_ENTRIES = 1e3;
34011
+ function live(window) {
34012
+ return window.times.length - window.head;
34013
+ }
34014
+ function expire(window, now) {
34015
+ const cutoff = now - window.windowMs;
34016
+ while (window.head < window.times.length && window.times[window.head] < cutoff) window.head++;
34017
+ if (window.head > 64 && window.head * 2 > window.times.length) {
34018
+ window.times = window.times.slice(window.head);
34019
+ window.ips = window.ips.slice(window.head);
34020
+ window.head = 0;
34021
+ }
34022
+ }
34010
34023
  var RuleEngine = class {
34011
34024
  constructor(onDetection) {
34012
34025
  this.onDetection = onDetection;
@@ -34032,27 +34045,42 @@ var RuleEngine = class {
34032
34045
  const windowKey = `${rule.id}:${groupBy}:${groupValue}`;
34033
34046
  let window = this.windows.get(windowKey);
34034
34047
  if (!window) {
34035
- window = { events: [], lastAlert: 0 };
34048
+ window = {
34049
+ times: [],
34050
+ ips: [],
34051
+ head: 0,
34052
+ lastAlert: 0,
34053
+ windowMs: rule.window_seconds * 1e3,
34054
+ cooldownMs: rule.cooldown_seconds * 1e3
34055
+ };
34036
34056
  this.windows.set(windowKey, window);
34037
34057
  }
34038
- window.events.push({ timestamp: now, event });
34039
- const cutoff = now - rule.window_seconds * 1e3;
34040
- window.events = window.events.filter((e) => e.timestamp >= cutoff);
34041
- if (window.events.length < rule.threshold) continue;
34042
- if (window.lastAlert > 0 && now - window.lastAlert < rule.cooldown_seconds * 1e3) continue;
34043
- const hits = window.events.length;
34044
- const distinctIps = new Set(
34045
- window.events.map((e) => e.event.source_ip).filter(Boolean)
34046
- ).size;
34058
+ window.times.push(now);
34059
+ window.ips.push(event.source_ip);
34060
+ expire(window, now);
34061
+ const cap = Math.max(rule.threshold, MAX_WINDOW_ENTRIES);
34062
+ let capped = false;
34063
+ if (live(window) > cap) {
34064
+ window.head = window.times.length - cap;
34065
+ capped = true;
34066
+ expire(window, now);
34067
+ }
34068
+ if (live(window) < rule.threshold) continue;
34069
+ if (window.lastAlert > 0 && now - window.lastAlert < window.cooldownMs) continue;
34070
+ const hits = live(window);
34071
+ const distinctIps = new Set(window.ips.slice(window.head).filter(Boolean)).size;
34047
34072
  window.lastAlert = now;
34048
- window.events = [];
34073
+ window.times = [];
34074
+ window.ips = [];
34075
+ window.head = 0;
34076
+ const hitsLabel = capped ? `${hits}+` : String(hits);
34049
34077
  const aggregate = groupBy !== "source_ip";
34050
34078
  const spread = aggregate ? ` from ${distinctIps} address${distinctIps === 1 ? "" : "es"}${groupBy === "endpoint" ? ` against ${groupValue}` : ""}` : "";
34051
34079
  this.onDetection({
34052
34080
  rule_id: rule.id,
34053
34081
  severity: rule.severity,
34054
34082
  title: rule.title,
34055
- description: `${rule.description} (${hits} events in ${rule.window_seconds}s${spread})`,
34083
+ description: `${rule.description} (${hitsLabel} events in ${rule.window_seconds}s${spread})`,
34056
34084
  source_ip: aggregate ? void 0 : event.source_ip,
34057
34085
  username: event.details?.user || void 0,
34058
34086
  raw_metadata: {
@@ -34115,14 +34143,26 @@ var RuleEngine = class {
34115
34143
  return event.details?.[field];
34116
34144
  }
34117
34145
  }
34118
- // Periodic cleanup of stale windows
34119
- cleanup() {
34120
- const now = Date.now();
34121
- for (const [key, window] of this.windows.entries()) {
34122
- if (window.events.length === 0 && now - window.lastAlert > 36e5) {
34146
+ /**
34147
+ * Expire every window by its own rule's length, and forget windows with
34148
+ * nothing left in them once their cooldown is over (a cooldown must outlive
34149
+ * an empty window, or a source could re-trigger the moment it was forgotten).
34150
+ * Without the expiry, a window whose address never came back was kept forever.
34151
+ */
34152
+ cleanup(now = Date.now()) {
34153
+ let removed = 0;
34154
+ for (const [key, window] of this.windows) {
34155
+ expire(window, now);
34156
+ if (live(window) === 0 && (window.lastAlert === 0 || now - window.lastAlert >= window.cooldownMs)) {
34123
34157
  this.windows.delete(key);
34158
+ removed++;
34124
34159
  }
34125
34160
  }
34161
+ return removed;
34162
+ }
34163
+ /** How many windows are open, for tests and the status report. */
34164
+ windowCount() {
34165
+ return this.windows.size;
34126
34166
  }
34127
34167
  };
34128
34168
 
@@ -35162,7 +35202,7 @@ var RemediationManager = class {
35162
35202
  */
35163
35203
  async reconcile() {
35164
35204
  const now = Date.now();
35165
- const live = this.blocklist.filter((b) => b.expires_at > now);
35205
+ const live2 = this.blocklist.filter((b) => b.expires_at > now);
35166
35206
  const stale = this.blocklist.filter((b) => b.expires_at <= now);
35167
35207
  for (const entry of stale) {
35168
35208
  if (!entry.dry_run) {
@@ -35172,7 +35212,7 @@ var RemediationManager = class {
35172
35212
  }
35173
35213
  }
35174
35214
  }
35175
- this.blocklist = live;
35215
+ this.blocklist = live2;
35176
35216
  this.saveState();
35177
35217
  let applied = null;
35178
35218
  try {
@@ -35180,7 +35220,7 @@ var RemediationManager = class {
35180
35220
  } catch {
35181
35221
  }
35182
35222
  if (applied) {
35183
- const known = new Set(live.filter((b) => !b.dry_run).map((b) => b.ip));
35223
+ const known = new Set(live2.filter((b) => !b.dry_run).map((b) => b.ip));
35184
35224
  for (const ip of applied) {
35185
35225
  if (known.has(ip)) continue;
35186
35226
  this.logLine(`[firewall] reconcile: dropping stale rule for ${ip} (no record of why)`);
@@ -35191,7 +35231,7 @@ var RemediationManager = class {
35191
35231
  }
35192
35232
  }
35193
35233
  if (this.config.dry_run) return;
35194
- for (const entry of live) {
35234
+ for (const entry of live2) {
35195
35235
  if (applied?.includes(entry.ip)) continue;
35196
35236
  try {
35197
35237
  await this.adapter.block(entry.ip);
@@ -35511,7 +35551,7 @@ async function runDaemon() {
35511
35551
  if (event.module !== "rule-engine") ruleEngine.evaluate(event);
35512
35552
  });
35513
35553
  logLine(`[daemon] rule engine loaded ${ruleEngine.getRules().length} rules`);
35514
- setInterval(() => ruleEngine.cleanup(), 3e5);
35554
+ setInterval(() => ruleEngine.cleanup(), 6e4);
35515
35555
  const settings = remediationSettings(config.remediation);
35516
35556
  const firewallAdapter = detectFirewallAdapter(config.remediation?.backend ?? "auto");
35517
35557
  const remediation = new RemediationManager(firewallAdapter, bus, settings);
@@ -37455,8 +37495,8 @@ async function liveDaemon() {
37455
37495
  const client = new IpcClient();
37456
37496
  try {
37457
37497
  await client.connect();
37458
- const live = await client.status();
37459
- return { pid, version: live.version ?? null };
37498
+ const live2 = await client.status();
37499
+ return { pid, version: live2.version ?? null };
37460
37500
  } catch {
37461
37501
  return { pid, version: null };
37462
37502
  } finally {