@profullstack/threatcrush 0.11.11 → 0.12.1

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
@@ -10594,6 +10594,18 @@ var init_ipc_client = __esm({
10594
10594
  async subscribe(channels) {
10595
10595
  await this.request("subscribe", { channels });
10596
10596
  }
10597
+ async blocklist() {
10598
+ return this.request("blocklist");
10599
+ }
10600
+ /**
10601
+ * Ban an address.
10602
+ */
10603
+ async block(ip, reason, ttl) {
10604
+ return this.request("block", { ip, reason, ttl });
10605
+ }
10606
+ async unblock(ip, forget = true) {
10607
+ return this.request("unblock", { ip, forget });
10608
+ }
10597
10609
  async shutdown() {
10598
10610
  await this.request("shutdown", { token: readControlToken() });
10599
10611
  }
@@ -10651,9 +10663,25 @@ function initialState(now = Date.now()) {
10651
10663
  paused: false,
10652
10664
  parked: [],
10653
10665
  scrollBack: 0,
10654
- startedAt: now
10666
+ startedAt: now,
10667
+ bans: [],
10668
+ protectedList: [],
10669
+ firewall: null,
10670
+ focus: "feed",
10671
+ threatIndex: 0,
10672
+ banIndex: 0,
10673
+ notice: null,
10674
+ busy: false
10655
10675
  };
10656
10676
  }
10677
+ function isBanned(state, ip) {
10678
+ return state.bans.some((b) => b.ip === ip);
10679
+ }
10680
+ function selectedIp(state) {
10681
+ if (state.focus === "threats") return state.topSources[state.threatIndex]?.ip ?? null;
10682
+ if (state.focus === "bans") return state.bans[state.banIndex]?.ip ?? null;
10683
+ return null;
10684
+ }
10657
10685
  function accept(state, event) {
10658
10686
  const events = [...state.events, event].slice(-FEED_LIMIT);
10659
10687
  return {
@@ -10696,7 +10724,8 @@ function reducer(state, action) {
10696
10724
  }
10697
10725
  case "tick": {
10698
10726
  const timeline = [...state.timeline.slice(1), state.pending];
10699
- return { ...state, timeline, pending: 0 };
10727
+ const notice = state.notice && state.notice.until <= Date.now() ? null : state.notice;
10728
+ return { ...state, timeline, pending: 0, notice };
10700
10729
  }
10701
10730
  case "modules":
10702
10731
  return {
@@ -10704,8 +10733,66 @@ function reducer(state, action) {
10704
10733
  modules: action.modules,
10705
10734
  counters: { ...state.counters, modules: action.modules.length }
10706
10735
  };
10707
- case "top":
10708
- return { ...state, topSources: action.top };
10736
+ case "top": {
10737
+ const previous = state.topSources[state.threatIndex]?.ip;
10738
+ const moved = previous ? action.top.findIndex((s) => s.ip === previous) : -1;
10739
+ const threatIndex = moved >= 0 ? moved : Math.min(state.threatIndex, Math.max(0, action.top.length - 1));
10740
+ return { ...state, topSources: action.top, threatIndex };
10741
+ }
10742
+ case "blocklist": {
10743
+ const previous = state.bans[state.banIndex]?.ip;
10744
+ const moved = previous ? action.reply.entries.findIndex((b) => b.ip === previous) : -1;
10745
+ const banIndex = moved >= 0 ? moved : Math.min(state.banIndex, Math.max(0, action.reply.entries.length - 1));
10746
+ return {
10747
+ ...state,
10748
+ bans: action.reply.entries,
10749
+ protectedList: action.reply.protected,
10750
+ firewall: {
10751
+ enabled: action.reply.enabled,
10752
+ dry_run: action.reply.dry_run,
10753
+ backend: action.reply.backend,
10754
+ min_severity: action.reply.min_severity,
10755
+ warning: action.reply.warning
10756
+ },
10757
+ banIndex
10758
+ };
10759
+ }
10760
+ case "focus":
10761
+ return { ...state, focus: action.focus };
10762
+ case "focus_next": {
10763
+ const next = FOCUS_ORDER[(FOCUS_ORDER.indexOf(state.focus) + 1) % FOCUS_ORDER.length];
10764
+ return { ...state, focus: next };
10765
+ }
10766
+ case "select": {
10767
+ if (state.focus === "threats") {
10768
+ const max = Math.max(0, state.topSources.length - 1);
10769
+ return { ...state, threatIndex: Math.min(max, Math.max(0, state.threatIndex + action.delta)) };
10770
+ }
10771
+ if (state.focus === "bans") {
10772
+ const max = Math.max(0, state.bans.length - 1);
10773
+ return { ...state, banIndex: Math.min(max, Math.max(0, state.banIndex + action.delta)) };
10774
+ }
10775
+ return state;
10776
+ }
10777
+ case "select_at": {
10778
+ if (state.focus === "bans") {
10779
+ const max2 = Math.max(0, state.bans.length - 1);
10780
+ return { ...state, banIndex: Math.min(max2, Math.max(0, action.index)) };
10781
+ }
10782
+ const max = Math.max(0, state.topSources.length - 1);
10783
+ return { ...state, threatIndex: Math.min(max, Math.max(0, action.index)) };
10784
+ }
10785
+ case "notice":
10786
+ return {
10787
+ ...state,
10788
+ notice: {
10789
+ text: action.text,
10790
+ tone: action.tone,
10791
+ until: (action.now ?? Date.now()) + NOTICE_MS
10792
+ }
10793
+ };
10794
+ case "busy":
10795
+ return { ...state, busy: action.busy };
10709
10796
  case "counters":
10710
10797
  return {
10711
10798
  ...state,
@@ -10730,7 +10817,14 @@ function reducer(state, action) {
10730
10817
  connectionLabel: state.connectionLabel,
10731
10818
  daemon: state.daemon,
10732
10819
  modules: state.modules,
10733
- counters: { ...state.counters, events: 0, threats: 0 }
10820
+ counters: { ...state.counters, events: 0, threats: 0 },
10821
+ // Reset clears the *view*, never the firewall. Bans are the daemon's
10822
+ // state, and wiping them from the screen would make the dashboard
10823
+ // disagree with the host it is describing.
10824
+ bans: state.bans,
10825
+ protectedList: state.protectedList,
10826
+ firewall: state.firewall,
10827
+ focus: state.focus
10734
10828
  };
10735
10829
  }
10736
10830
  }
@@ -10759,16 +10853,73 @@ function formatCount(n) {
10759
10853
  if (n < 1e6) return `${(n / 1e3).toFixed(n < 1e4 ? 1 : 0)}k`;
10760
10854
  return `${(n / 1e6).toFixed(1)}M`;
10761
10855
  }
10762
- var TIMELINE_SLOTS, FEED_LIMIT, SEVERITIES;
10856
+ var FOCUS_ORDER, NOTICE_MS, TIMELINE_SLOTS, FEED_LIMIT, SEVERITIES;
10763
10857
  var init_state = __esm({
10764
10858
  "src/tui/state.ts"() {
10765
10859
  "use strict";
10860
+ FOCUS_ORDER = ["feed", "threats", "bans"];
10861
+ NOTICE_MS = 6e3;
10766
10862
  TIMELINE_SLOTS = 60;
10767
10863
  FEED_LIMIT = 500;
10768
10864
  SEVERITIES = ["info", "low", "medium", "high", "critical"];
10769
10865
  }
10770
10866
  });
10771
10867
 
10868
+ // src/daemon/firewall/backoff.ts
10869
+ function fibonacciMinutes(strike) {
10870
+ const n = Math.max(1, Math.floor(strike));
10871
+ let prev = 1;
10872
+ let curr = 1;
10873
+ for (let i = 1; i < n; i++) {
10874
+ const next = prev + curr;
10875
+ prev = curr;
10876
+ curr = next;
10877
+ }
10878
+ return curr;
10879
+ }
10880
+ function banSeconds(strike, maxSeconds) {
10881
+ const seconds = fibonacciMinutes(strike) * 60;
10882
+ return Math.min(seconds, Math.max(60, maxSeconds));
10883
+ }
10884
+ function recordStrike(strikes, ip, now, memorySeconds) {
10885
+ const existing = strikes[ip];
10886
+ const expired = !existing || now - existing.last > memorySeconds * 1e3;
10887
+ const count = expired ? 1 : existing.count + 1;
10888
+ strikes[ip] = { count, last: now };
10889
+ return count;
10890
+ }
10891
+ function pruneStrikes(strikes, now, memorySeconds) {
10892
+ const kept = {};
10893
+ for (const [ip, strike] of Object.entries(strikes)) {
10894
+ if (now - strike.last <= memorySeconds * 1e3) kept[ip] = strike;
10895
+ }
10896
+ return kept;
10897
+ }
10898
+ function parseDuration(value) {
10899
+ if (typeof value === "number") return Number.isFinite(value) && value > 0 ? value : null;
10900
+ if (!value) return null;
10901
+ const match = String(value).trim().match(/^(\d+)\s*(s|m|h|d)?$/i);
10902
+ if (!match) return null;
10903
+ const units = { s: 1, m: 60, h: 3600, d: 86400 };
10904
+ return Number(match[1]) * (units[(match[2] || "s").toLowerCase()] ?? 1);
10905
+ }
10906
+ function formatDuration(seconds) {
10907
+ if (!Number.isFinite(seconds) || seconds <= 0) return "0s";
10908
+ const d = Math.floor(seconds / 86400);
10909
+ const h = Math.floor(seconds % 86400 / 3600);
10910
+ const m = Math.floor(seconds % 3600 / 60);
10911
+ const s = Math.floor(seconds % 60);
10912
+ if (d > 0) return h > 0 ? `${d}d ${h}h` : `${d}d`;
10913
+ if (h > 0) return m > 0 ? `${h}h ${m}m` : `${h}h`;
10914
+ if (m > 0) return s > 0 && m < 10 ? `${m}m ${s}s` : `${m}m`;
10915
+ return `${s}s`;
10916
+ }
10917
+ var init_backoff = __esm({
10918
+ "src/daemon/firewall/backoff.ts"() {
10919
+ "use strict";
10920
+ }
10921
+ });
10922
+
10772
10923
  // src/tui/theme.ts
10773
10924
  var threatcrushTheme, severityColors, levelColors;
10774
10925
  var init_theme2 = __esm({
@@ -10996,9 +11147,19 @@ function feedPanel(parent, state, theme, options) {
10996
11147
  }
10997
11148
  );
10998
11149
  }
10999
- function threatsPanel(parent, state, theme) {
11150
+ function threatsPanel(parent, state, theme, options) {
11151
+ const focused = state.focus === "threats";
11000
11152
  parent.panel(
11001
- { title: " TOP THREATS ", size: "fill", border: "rounded", borderColor: theme.border, titleColor: theme.primary, padding: [0, 1] },
11153
+ {
11154
+ title: " TOP THREATS ",
11155
+ size: "fill",
11156
+ border: "rounded",
11157
+ borderColor: focused ? theme.borderFocused : theme.border,
11158
+ titleColor: theme.primary,
11159
+ subtitle: focused ? "b ban \xB7 u unban" : void 0,
11160
+ subtitleColor: theme.muted,
11161
+ padding: [0, 1]
11162
+ },
11002
11163
  (panel) => {
11003
11164
  if (state.topSources.length === 0) {
11004
11165
  if (state.daemon?.stateDb === false) {
@@ -11014,7 +11175,19 @@ function threatsPanel(parent, state, theme) {
11014
11175
  panel.table({
11015
11176
  rows: state.topSources,
11016
11177
  header: false,
11178
+ selected: focused ? state.threatIndex : -1,
11179
+ followSelection: true,
11180
+ scrollbar: true,
11181
+ onSelectRow: options.onThreatSelect,
11017
11182
  columns: [
11183
+ {
11184
+ // A source is either banned, protected, or neither — and which one
11185
+ // it is decides what the b key will do to it.
11186
+ key: "ip",
11187
+ width: 2,
11188
+ render: (s) => isBanned(state, s.ip) ? "\u2716" : isProtectedRow(state, s.ip) ? "\u26CA" : " ",
11189
+ color: (s) => isBanned(state, s.ip) ? severityColors.critical : isProtectedRow(state, s.ip) ? theme.success : theme.muted
11190
+ },
11018
11191
  { key: "ip", width: "fill", color: () => theme.foreground },
11019
11192
  {
11020
11193
  key: "count",
@@ -11029,6 +11202,97 @@ function threatsPanel(parent, state, theme) {
11029
11202
  }
11030
11203
  );
11031
11204
  }
11205
+ function isProtectedRow(state, ip) {
11206
+ return state.protectedList.some((entry) => entry === ip || ipInCidrLabel(ip, entry));
11207
+ }
11208
+ function ipInCidrLabel(ip, entry) {
11209
+ const slash = entry.indexOf("/");
11210
+ if (slash < 0) return false;
11211
+ const network = entry.slice(0, slash);
11212
+ const prefix = Number(entry.slice(slash + 1));
11213
+ if (!Number.isFinite(prefix)) return false;
11214
+ if (network.includes(":") !== ip.includes(":")) return false;
11215
+ if (ip.includes(":")) return ip.toLowerCase().startsWith(network.toLowerCase().replace(/:+$/, ""));
11216
+ const octets = Math.floor(prefix / 8);
11217
+ if (octets === 0) return false;
11218
+ return ip.split(".").slice(0, octets).join(".") === network.split(".").slice(0, octets).join(".");
11219
+ }
11220
+ function bansPanel(parent, state, theme, options) {
11221
+ const focused = state.focus === "bans";
11222
+ const fw = state.firewall;
11223
+ const footer2 = fw ? `${fw.backend}${fw.dry_run ? " \xB7 DRY-RUN" : ""} \xB7 \u2265${fw.min_severity}` : void 0;
11224
+ parent.panel(
11225
+ {
11226
+ title: " BANNED ",
11227
+ size: "fill",
11228
+ border: "rounded",
11229
+ borderColor: focused ? theme.borderFocused : theme.border,
11230
+ titleColor: theme.primary,
11231
+ subtitle: focused ? "u unban" : void 0,
11232
+ subtitleColor: theme.muted,
11233
+ footer: footer2,
11234
+ padding: [0, 1]
11235
+ },
11236
+ (panel) => {
11237
+ if (!fw) {
11238
+ panel.label("firewall state unknown", { fg: theme.muted });
11239
+ return;
11240
+ }
11241
+ if (!fw.enabled) {
11242
+ panel.text("auto-defence OFF", { fg: severityColors.high, bold: true });
11243
+ panel.label("[remediation] enabled = false", { fg: theme.muted });
11244
+ return;
11245
+ }
11246
+ if (fw.warning) {
11247
+ panel.text("NOT PRIVILEGED", { fg: severityColors.critical, bold: true });
11248
+ panel.label(fw.warning, { fg: severityColors.high });
11249
+ panel.label("sudo threatcrush install-service", { fg: theme.muted });
11250
+ panel.spacer(1);
11251
+ }
11252
+ if (state.bans.length === 0) {
11253
+ panel.label("nothing banned", { fg: theme.muted });
11254
+ panel.label(fw.dry_run ? "dry-run: bans are simulated" : "bans: 1m \u2192 2m \u2192 3m \u2192 5m \u2192 8m", {
11255
+ fg: fw.dry_run ? severityColors.medium : theme.muted
11256
+ });
11257
+ return;
11258
+ }
11259
+ const now = Date.now();
11260
+ panel.table({
11261
+ rows: state.bans,
11262
+ header: false,
11263
+ selected: focused ? state.banIndex : -1,
11264
+ followSelection: true,
11265
+ scrollbar: true,
11266
+ onSelectRow: options.onBanSelect,
11267
+ columns: [
11268
+ {
11269
+ key: "ip",
11270
+ width: 2,
11271
+ // A manual ban reads differently from one the daemon decided on.
11272
+ render: (b) => b.source === "manual" ? "\u2298" : "\u2716",
11273
+ color: (b) => b.dry_run ? theme.muted : severityColors.critical
11274
+ },
11275
+ { key: "ip", width: "fill", color: () => theme.foreground },
11276
+ {
11277
+ key: "strikes",
11278
+ width: 3,
11279
+ align: "right",
11280
+ // Which rung of the ladder produced this ban's length.
11281
+ render: (b) => `#${b.strikes}`,
11282
+ color: (b) => b.strikes > 1 ? severityColors.high : theme.muted
11283
+ },
11284
+ {
11285
+ key: "expires_at",
11286
+ width: 7,
11287
+ align: "right",
11288
+ render: (b) => formatDuration(Math.round((b.expires_at - now) / 1e3)),
11289
+ color: () => severityColors.medium
11290
+ }
11291
+ ]
11292
+ });
11293
+ }
11294
+ );
11295
+ }
11032
11296
  function throughputPanel(parent, state, theme) {
11033
11297
  parent.panel(
11034
11298
  { title: " THROUGHPUT ", size: 9, border: "rounded", borderColor: theme.border, titleColor: theme.primary, padding: [0, 1] },
@@ -11045,20 +11309,30 @@ function throughputPanel(parent, state, theme) {
11045
11309
  );
11046
11310
  }
11047
11311
  function footer(ui, state, theme) {
11312
+ const onFeed = state.focus === "feed";
11048
11313
  ui.statusBar({
11049
11314
  size: 1,
11050
11315
  items: [
11051
11316
  { key: "q", label: "quit" },
11317
+ { key: "tab", label: state.focus },
11318
+ { key: "\u2191\u2193", label: onFeed ? "scroll" : "select" },
11319
+ { key: "b", label: "ban" },
11320
+ { key: "u", label: "unban" },
11052
11321
  { key: "p", label: state.paused ? "resume" : "pause" },
11053
- { key: "r", label: "reset" },
11054
- { key: "\u2191\u2193", label: "scroll" },
11055
- { key: "end", label: "follow" }
11322
+ { key: "r", label: "reset" }
11056
11323
  ],
11057
11324
  right: [
11325
+ // The notice is the answer to "did my keypress do anything", so it takes
11326
+ // the slot for as long as it lives.
11327
+ { label: state.notice?.text ?? "", color: state.notice?.tone === "error" ? severityColors.high : theme.success },
11058
11328
  {
11059
11329
  label: state.paused && state.parked.length > 0 ? `${state.parked.length} held` : "",
11060
11330
  color: severityColors.medium
11061
11331
  },
11332
+ {
11333
+ label: state.firewall ? `${state.bans.length} banned${state.firewall.dry_run ? " (dry-run)" : ""}` : "",
11334
+ color: state.firewall?.dry_run ? severityColors.medium : theme.muted
11335
+ },
11062
11336
  { label: state.daemon ? `v${state.daemon.version} \xB7 ${state.daemon.mode}` : "no daemon", color: theme.muted }
11063
11337
  ].filter((item) => item.label !== ""),
11064
11338
  background: theme.surface
@@ -11076,7 +11350,8 @@ function renderDashboard(ui, state, theme, options = {}) {
11076
11350
  });
11077
11351
  feedPanel(row, state, theme, options);
11078
11352
  row.column({ size: "1fr" }, (right) => {
11079
- threatsPanel(right, state, theme);
11353
+ threatsPanel(right, state, theme, options);
11354
+ bansPanel(right, state, theme, options);
11080
11355
  throughputPanel(right, state, theme);
11081
11356
  });
11082
11357
  });
@@ -11088,6 +11363,7 @@ var init_view = __esm({
11088
11363
  "use strict";
11089
11364
  init_theme2();
11090
11365
  init_state();
11366
+ init_backoff();
11091
11367
  }
11092
11368
  });
11093
11369
 
@@ -11138,6 +11414,8 @@ async function startDashboard(options = {}) {
11138
11414
  let client = null;
11139
11415
  let stopped = false;
11140
11416
  const timers = [];
11417
+ let refreshBans = async () => {
11418
+ };
11141
11419
  const every = (ms, fn) => {
11142
11420
  const t = setInterval(fn, ms);
11143
11421
  t.unref?.();
@@ -11160,6 +11438,15 @@ async function startDashboard(options = {}) {
11160
11438
  } else {
11161
11439
  const onEvent = (event) => {
11162
11440
  if (!stopped) dispatch({ type: "event", event });
11441
+ if (!stopped && event.module === "firewall-rules") void refreshBans();
11442
+ };
11443
+ refreshBans = async () => {
11444
+ if (!client || stopped) return;
11445
+ try {
11446
+ const reply = await client.blocklist();
11447
+ dispatch({ type: "blocklist", reply });
11448
+ } catch {
11449
+ }
11163
11450
  };
11164
11451
  const poll = async () => {
11165
11452
  if (!client || stopped) return;
@@ -11168,6 +11455,7 @@ async function startDashboard(options = {}) {
11168
11455
  dispatch({ type: "connected", label: `daemon pid ${status.pid}`, status });
11169
11456
  const top = await client.topSources(8).catch(() => []);
11170
11457
  dispatch({ type: "top", top });
11458
+ await refreshBans();
11171
11459
  } catch {
11172
11460
  try {
11173
11461
  client?.close();
@@ -11177,7 +11465,7 @@ async function startDashboard(options = {}) {
11177
11465
  dispatch({ type: "connection_lost", label: "daemon went away \u2014 retrying" });
11178
11466
  }
11179
11467
  };
11180
- const connect = async () => {
11468
+ const connect2 = async () => {
11181
11469
  if (client || stopped) return;
11182
11470
  if (!IpcClient.isDaemonRunning()) {
11183
11471
  if (state.connection !== "lost") {
@@ -11210,9 +11498,9 @@ async function startDashboard(options = {}) {
11210
11498
  dispatch({ type: "connection_lost", label: `daemon unreachable: ${err.message}` });
11211
11499
  }
11212
11500
  };
11213
- void connect();
11501
+ void connect2();
11214
11502
  every(RECONNECT_MS, () => {
11215
- if (!client) void connect();
11503
+ if (!client) void connect2();
11216
11504
  });
11217
11505
  every(POLL_MS, () => {
11218
11506
  void poll();
@@ -11223,6 +11511,55 @@ async function startDashboard(options = {}) {
11223
11511
  teardown();
11224
11512
  app.stop();
11225
11513
  };
11514
+ const banSelected = async () => {
11515
+ const ip = selectedIp(state);
11516
+ if (state.busy) return;
11517
+ if (!ip) {
11518
+ dispatch({ type: "notice", text: "select a source first (tab)", tone: "error" });
11519
+ return;
11520
+ }
11521
+ if (!client) {
11522
+ dispatch({ type: "notice", text: "no daemon \u2014 cannot ban", tone: "error" });
11523
+ return;
11524
+ }
11525
+ if (isBanned(state, ip)) {
11526
+ dispatch({ type: "notice", text: `${ip} is already banned`, tone: "error" });
11527
+ return;
11528
+ }
11529
+ dispatch({ type: "busy", busy: true });
11530
+ try {
11531
+ const entry = await client.block(ip, "banned from dashboard");
11532
+ const ttl = formatDuration(Math.round((entry.expires_at - Date.now()) / 1e3));
11533
+ dispatch({ type: "notice", text: `banned ${ip} for ${ttl} (#${entry.strikes})`, tone: "ok" });
11534
+ } catch (err) {
11535
+ dispatch({ type: "notice", text: `ban failed: ${err.message}`, tone: "error" });
11536
+ } finally {
11537
+ dispatch({ type: "busy", busy: false });
11538
+ await refreshBans();
11539
+ }
11540
+ };
11541
+ const unbanSelected = async () => {
11542
+ const ip = selectedIp(state);
11543
+ if (state.busy) return;
11544
+ if (!ip) {
11545
+ dispatch({ type: "notice", text: "select a source first (tab)", tone: "error" });
11546
+ return;
11547
+ }
11548
+ if (!client) {
11549
+ dispatch({ type: "notice", text: "no daemon \u2014 cannot unban", tone: "error" });
11550
+ return;
11551
+ }
11552
+ dispatch({ type: "busy", busy: true });
11553
+ try {
11554
+ await client.unblock(ip);
11555
+ dispatch({ type: "notice", text: `unbanned ${ip}`, tone: "ok" });
11556
+ } catch (err) {
11557
+ dispatch({ type: "notice", text: `unban failed: ${err.message}`, tone: "error" });
11558
+ } finally {
11559
+ dispatch({ type: "busy", busy: false });
11560
+ await refreshBans();
11561
+ }
11562
+ };
11226
11563
  app.on("key", (event) => {
11227
11564
  switch (event.key) {
11228
11565
  case "q":
@@ -11237,13 +11574,24 @@ async function startDashboard(options = {}) {
11237
11574
  case "r":
11238
11575
  dispatch({ type: "reset" });
11239
11576
  break;
11577
+ case "tab":
11578
+ dispatch({ type: "focus_next" });
11579
+ break;
11580
+ case "b":
11581
+ void banSelected();
11582
+ break;
11583
+ case "u":
11584
+ void unbanSelected();
11585
+ break;
11240
11586
  case "up":
11241
11587
  case "k":
11242
- dispatch({ type: "scroll", delta: 1 });
11588
+ if (state.focus === "feed") dispatch({ type: "scroll", delta: 1 });
11589
+ else dispatch({ type: "select", delta: -1 });
11243
11590
  break;
11244
11591
  case "down":
11245
11592
  case "j":
11246
- dispatch({ type: "scroll", delta: -1 });
11593
+ if (state.focus === "feed") dispatch({ type: "scroll", delta: -1 });
11594
+ else dispatch({ type: "select", delta: 1 });
11247
11595
  break;
11248
11596
  case "pageup":
11249
11597
  dispatch({ type: "scroll", delta: 10 });
@@ -11262,7 +11610,17 @@ async function startDashboard(options = {}) {
11262
11610
  app.render(({ ui, theme }) => {
11263
11611
  renderDashboard(ui, state, theme, {
11264
11612
  demo: options.demo,
11265
- onFeedScroll: (delta) => dispatch({ type: "scroll", delta: -delta })
11613
+ onFeedScroll: (delta) => dispatch({ type: "scroll", delta: -delta }),
11614
+ // One click both focuses the panel and picks the row — the operator
11615
+ // should not have to click to focus and click again to select.
11616
+ onThreatSelect: (row) => {
11617
+ dispatch({ type: "focus", focus: "threats" });
11618
+ dispatch({ type: "select_at", index: row });
11619
+ },
11620
+ onBanSelect: (row) => {
11621
+ dispatch({ type: "focus", focus: "bans" });
11622
+ dispatch({ type: "select_at", index: row });
11623
+ }
11266
11624
  });
11267
11625
  });
11268
11626
  try {
@@ -11279,6 +11637,7 @@ var init_dashboard = __esm({
11279
11637
  init_ipc_client();
11280
11638
  init_paths();
11281
11639
  init_state();
11640
+ init_backoff();
11282
11641
  init_theme2();
11283
11642
  init_view();
11284
11643
  init_demo();
@@ -15441,9 +15800,9 @@ var source_default = chalk;
15441
15800
 
15442
15801
  // src/index.ts
15443
15802
  var import_readline = __toESM(require("readline"));
15444
- var import_node_child_process11 = require("child_process");
15445
- var import_node_fs32 = require("fs");
15446
- var import_node_path22 = require("path");
15803
+ var import_node_child_process12 = require("child_process");
15804
+ var import_node_fs33 = require("fs");
15805
+ var import_node_path23 = require("path");
15447
15806
  var import_node_os8 = require("os");
15448
15807
 
15449
15808
  // src/commands/monitor.ts
@@ -15518,9 +15877,10 @@ function banner() {
15518
15877
  }
15519
15878
 
15520
15879
  // src/core/log-parser.ts
15521
- var NGINX_REGEX = /^(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) \S+" (\d{3}) (\d+) "[^"]*" "([^"]*)"/;
15522
- var AUTH_REGEX = /^(\w+\s+\d+\s+[\d:]+)\s+\S+\s+(\S+?)(?:\[\d+\])?:\s+(.*)/;
15523
- var SYSLOG_REGEX = /^(\w+\s+\d+\s+[\d:]+)\s+\S+\s+(\S+?)(?:\[\d+\])?:\s+(.*)/;
15880
+ var NGINX_REGEX = /^(?:(\S+) )?(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) \S+" (\d{3}) (\d+) "[^"]*" "([^"]*)"/;
15881
+ var TIMESTAMP = String.raw`(\w{3}\s+\d+\s+[\d:]+|\d{4}-\d{2}-\d{2}T[\d:.]+(?:Z|[+-]\d{2}:?\d{2})?)`;
15882
+ var AUTH_REGEX = new RegExp(`^${TIMESTAMP}\\s+\\S+\\s+(\\S+?)(?:\\[\\d+\\])?:\\s+(.*)`);
15883
+ var SYSLOG_REGEX = new RegExp(`^${TIMESTAMP}\\s+\\S+\\s+(\\S+?)(?:\\[\\d+\\])?:\\s+(.*)`);
15524
15884
  var IP_REGEX = /(?:from|FROM)\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
15525
15885
  var INVALID_USER_REGEX = /(?:for\s+invalid\s+user)\s+(\S+?)(?:\s+from|\s*$)/;
15526
15886
  var USER_REGEX = /(?:for|user)\s+(\S+?)(?:\s+from|\s*$)/;
@@ -15550,26 +15910,37 @@ var ATTACK_PATTERNS = {
15550
15910
  /windows\/system32/i
15551
15911
  ],
15552
15912
  rfi: [
15553
- /(?:https?|ftp):\/\/.*\?/i,
15913
+ // A remote URL pointing at something executable — the actual shape of a
15914
+ // remote file include (`?page=http://evil.tld/shell.txt`).
15915
+ //
15916
+ // This used to be `(?:https?|ftp):\/\/.*\?`, i.e. *any* URL carrying a
15917
+ // query string. A URL inside a query parameter is ordinary web design —
15918
+ // readers, share links, oembed, feed proxies — so on rssamplifier.com every
15919
+ // `/<feed>/read?p=https://…` hit was logged as a CRITICAL attack. With
15920
+ // auto-defence enforcing, that pattern bans readers, which is precisely the
15921
+ // failure PRD 0010 is written to prevent.
15922
+ /(?:https?|ftp):\/\/\S+\.(?:php|phtml|phar|asp|aspx|jsp|txt|sh|pl|py|cgi)(?:[?#%\s]|$)/i,
15554
15923
  /php:\/\/(?:input|filter)/i,
15555
- /data:\/\//i
15924
+ /(?:data|expect|zip|phar):\/\//i
15556
15925
  ]
15557
15926
  };
15558
15927
  function parseNginxLog(line) {
15559
15928
  const match = line.match(NGINX_REGEX);
15560
15929
  if (!match) return null;
15930
+ const fields = {
15931
+ ip: match[2],
15932
+ method: match[4],
15933
+ path: match[5],
15934
+ status: match[6],
15935
+ size: match[7],
15936
+ user_agent: match[8]
15937
+ };
15938
+ if (match[1]) fields.host = match[1];
15561
15939
  return {
15562
- timestamp: parseNginxTimestamp(match[2]),
15940
+ timestamp: parseNginxTimestamp(match[3]),
15563
15941
  raw: line,
15564
15942
  source: "nginx",
15565
- fields: {
15566
- ip: match[1],
15567
- method: match[3],
15568
- path: match[4],
15569
- status: match[5],
15570
- size: match[6],
15571
- user_agent: match[7]
15572
- }
15943
+ fields
15573
15944
  };
15574
15945
  }
15575
15946
  function parseAuthLog(line) {
@@ -15605,17 +15976,23 @@ function parseSyslog(line) {
15605
15976
  }
15606
15977
  function detectAttackPattern(path) {
15607
15978
  const candidates = /* @__PURE__ */ new Set([path]);
15608
- let current = path;
15609
- for (let i = 0; i < 2; i++) {
15610
- let decoded = null;
15611
- try {
15612
- decoded = decodeURIComponent(current);
15613
- } catch {
15614
- decoded = null;
15979
+ const seeds = [path, path.includes("+") ? path.replace(/\+/g, " ") : null].filter(
15980
+ (s) => s !== null
15981
+ );
15982
+ for (const seed of seeds) {
15983
+ candidates.add(seed);
15984
+ let current = seed;
15985
+ for (let i = 0; i < 2; i++) {
15986
+ let decoded = null;
15987
+ try {
15988
+ decoded = decodeURIComponent(current);
15989
+ } catch {
15990
+ decoded = null;
15991
+ }
15992
+ if (decoded === null || decoded === current) break;
15993
+ candidates.add(decoded);
15994
+ current = decoded;
15615
15995
  }
15616
- if (decoded === null || decoded === current) break;
15617
- candidates.add(decoded);
15618
- current = decoded;
15619
15996
  }
15620
15997
  for (const [type, patterns] of Object.entries(ATTACK_PATTERNS)) {
15621
15998
  for (const pattern of patterns) {
@@ -15641,6 +16018,10 @@ function parseNginxTimestamp(s) {
15641
16018
  return Number.isNaN(d.getTime()) ? /* @__PURE__ */ new Date() : d;
15642
16019
  }
15643
16020
  function parseSyslogTimestamp(s) {
16021
+ if (/^\d{4}-\d{2}-\d{2}T/.test(s)) {
16022
+ const iso = new Date(s);
16023
+ return Number.isNaN(iso.getTime()) ? /* @__PURE__ */ new Date() : iso;
16024
+ }
15644
16025
  const now = /* @__PURE__ */ new Date();
15645
16026
  let d = /* @__PURE__ */ new Date(`${s} ${now.getFullYear()}`);
15646
16027
  if (Number.isNaN(d.getTime())) return now;
@@ -20731,6 +21112,7 @@ function loadConfig(configPath) {
20731
21112
  api: { ...DEFAULT_CONFIG.api, ...parsed.api },
20732
21113
  alerts: parsed.alerts || {},
20733
21114
  modules: { ...DEFAULT_CONFIG.modules, ...parsed.modules },
21115
+ remediation: parsed.remediation,
20734
21116
  license: parsed.license
20735
21117
  };
20736
21118
  } catch {
@@ -22698,14 +23080,14 @@ async function sshConnect(options) {
22698
23080
  }
22699
23081
 
22700
23082
  // src/commands/daemon.ts
22701
- var import_node_child_process7 = require("child_process");
22702
- var import_node_fs27 = require("fs");
22703
- var import_node_path19 = require("path");
23083
+ var import_node_child_process8 = require("child_process");
22704
23084
  var import_node_fs28 = require("fs");
23085
+ var import_node_path20 = require("path");
23086
+ var import_node_fs29 = require("fs");
22705
23087
 
22706
23088
  // src/daemon/index.ts
22707
- var import_node_fs26 = require("fs");
22708
- var import_node_path18 = require("path");
23089
+ var import_node_fs27 = require("fs");
23090
+ var import_node_path19 = require("path");
22709
23091
  init_paths();
22710
23092
 
22711
23093
  // src/daemon/ipc-server.ts
@@ -22731,10 +23113,12 @@ var bus = new EventBus();
22731
23113
  bus.setMaxListeners(50);
22732
23114
 
22733
23115
  // src/daemon/ipc-server.ts
23116
+ init_backoff();
22734
23117
  var IpcServer = class {
22735
- constructor(version, moduleHost) {
23118
+ constructor(version, moduleHost, remediation) {
22736
23119
  this.version = version;
22737
23120
  this.moduleHost = moduleHost;
23121
+ this.remediation = remediation;
22738
23122
  bus.on("event", (event) => {
22739
23123
  this.counters.events++;
22740
23124
  if (event.severity === "medium" || event.severity === "high" || event.severity === "critical") {
@@ -22751,6 +23135,7 @@ var IpcServer = class {
22751
23135
  }
22752
23136
  version;
22753
23137
  moduleHost;
23138
+ remediation;
22754
23139
  server = null;
22755
23140
  clients = /* @__PURE__ */ new Map();
22756
23141
  nextClientId = 1;
@@ -22890,6 +23275,54 @@ var IpcServer = class {
22890
23275
  case "subscribe":
22891
23276
  for (const ch of req.params.channels) client.subscriptions.add(ch);
22892
23277
  return this.send(client, { id: req.id, ok: true, result: { subscribed: [...client.subscriptions] } });
23278
+ case "blocklist": {
23279
+ if (!this.remediation) {
23280
+ return this.send(client, { id: req.id, ok: false, error: "remediation is not running" });
23281
+ }
23282
+ const status = this.remediation.status();
23283
+ const reply = {
23284
+ entries: this.remediation.getBlocklist().map((entry) => ({
23285
+ ip: entry.ip,
23286
+ reason: entry.reason,
23287
+ blocked_at: entry.blocked_at,
23288
+ expires_at: entry.expires_at,
23289
+ strikes: entry.strikes,
23290
+ source: entry.source,
23291
+ dry_run: entry.dry_run
23292
+ })),
23293
+ protected: this.remediation.getProtected(),
23294
+ enabled: status.enabled,
23295
+ dry_run: status.dry_run,
23296
+ backend: status.backend,
23297
+ min_severity: status.min_severity,
23298
+ warning: status.warning
23299
+ };
23300
+ return this.send(client, { id: req.id, ok: true, result: reply });
23301
+ }
23302
+ case "block": {
23303
+ if (!this.remediation) {
23304
+ return this.send(client, { id: req.id, ok: false, error: "remediation is not running" });
23305
+ }
23306
+ const ttl = parseDuration(req.params?.ttl) ?? void 0;
23307
+ const result = await this.remediation.ban(req.params.ip, req.params.reason || "banned by operator", {
23308
+ ttlSeconds: ttl,
23309
+ source: "manual"
23310
+ });
23311
+ if (!result.ok) {
23312
+ return this.send(client, { id: req.id, ok: false, error: result.error || "ban failed" });
23313
+ }
23314
+ return this.send(client, { id: req.id, ok: true, result: result.entry });
23315
+ }
23316
+ case "unblock": {
23317
+ if (!this.remediation) {
23318
+ return this.send(client, { id: req.id, ok: false, error: "remediation is not running" });
23319
+ }
23320
+ const result = await this.remediation.unban(req.params.ip, { forget: req.params.forget !== false });
23321
+ if (!result.ok) {
23322
+ return this.send(client, { id: req.id, ok: false, error: result.error || "unban failed" });
23323
+ }
23324
+ return this.send(client, { id: req.id, ok: true, result: { ip: req.params.ip } });
23325
+ }
22893
23326
  case "shutdown":
22894
23327
  if (!tokensMatch(this.controlToken, req.params?.token)) {
22895
23328
  return this.send(client, {
@@ -23006,6 +23439,7 @@ var LogWatcher = class {
23006
23439
  let severity = "info";
23007
23440
  let message = line;
23008
23441
  let sourceIp;
23442
+ let host;
23009
23443
  if (parsed.source === "auth") {
23010
23444
  const entry = parseAuthLog(line);
23011
23445
  if (!entry) return;
@@ -23029,6 +23463,7 @@ var LogWatcher = class {
23029
23463
  sourceIp = entry.fields.ip;
23030
23464
  const status = parseInt(entry.fields.status, 10);
23031
23465
  const attack = detectAttackPattern(entry.fields.path);
23466
+ host = entry.fields.host;
23032
23467
  if (attack) {
23033
23468
  severity = "critical";
23034
23469
  message = `Attack [${attack.toUpperCase()}]: ${entry.fields.method} ${entry.fields.path}`;
@@ -23050,7 +23485,8 @@ var LogWatcher = class {
23050
23485
  category: src.category,
23051
23486
  severity,
23052
23487
  message,
23053
- source_ip: sourceIp
23488
+ source_ip: sourceIp,
23489
+ ...host ? { details: { host } } : {}
23054
23490
  };
23055
23491
  try {
23056
23492
  insertEvent(event);
@@ -24590,12 +25026,132 @@ function loadAllRules(customDir) {
24590
25026
 
24591
25027
  // src/daemon/firewall/adapters.ts
24592
25028
  var import_node_child_process6 = require("child_process");
25029
+ var import_node_fs25 = require("fs");
25030
+ var import_node_path18 = require("path");
24593
25031
  var import_node_net3 = require("net");
24594
25032
  function assertValidFirewallIp(ip) {
24595
25033
  if ((0, import_node_net3.isIP)(ip) !== 4) {
24596
25034
  throw new Error(`Invalid IPv4 address: ${ip}`);
24597
25035
  }
24598
25036
  }
25037
+ function assertBannableIp(ip) {
25038
+ if ((0, import_node_net3.isIP)(ip) === 0) {
25039
+ throw new Error(`Invalid IP address: ${ip}`);
25040
+ }
25041
+ }
25042
+ function writeIfAbsent(path, contents) {
25043
+ (0, import_node_fs25.mkdirSync)((0, import_node_path18.dirname)(path), { recursive: true });
25044
+ try {
25045
+ (0, import_node_fs25.writeFileSync)(path, contents, { flag: "wx" });
25046
+ } catch (err) {
25047
+ if (err.code !== "EEXIST") throw err;
25048
+ }
25049
+ }
25050
+ var FAIL2BAN_JAIL = "threatcrush";
25051
+ var FAIL2BAN_FILTER_FILE = "/etc/fail2ban/filter.d/threatcrush.conf";
25052
+ var FAIL2BAN_JAIL_FILE = "/etc/fail2ban/jail.d/threatcrush.conf";
25053
+ var Fail2banAdapter = class {
25054
+ constructor(jail = FAIL2BAN_JAIL, backstopSeconds = 86400) {
25055
+ this.jail = jail;
25056
+ this.backstopSeconds = backstopSeconds;
25057
+ }
25058
+ jail;
25059
+ backstopSeconds;
25060
+ name = "fail2ban";
25061
+ enforces = true;
25062
+ jailReady = false;
25063
+ isAvailable() {
25064
+ const result = (0, import_node_child_process6.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
25065
+ return result.status === 0;
25066
+ }
25067
+ client(args) {
25068
+ return (0, import_node_child_process6.execFileSync)("fail2ban-client", args, {
25069
+ encoding: "utf-8",
25070
+ stdio: ["ignore", "pipe", "pipe"]
25071
+ });
25072
+ }
25073
+ /**
25074
+ * Create the jail if it is missing. Writing to /etc/fail2ban needs root; when
25075
+ * we cannot, the error surfaces to the caller instead of a ban that silently
25076
+ * goes nowhere.
25077
+ */
25078
+ ensureJail() {
25079
+ if (this.jailReady) return;
25080
+ try {
25081
+ this.client(["status", this.jail]);
25082
+ this.jailReady = true;
25083
+ return;
25084
+ } catch {
25085
+ }
25086
+ writeIfAbsent(
25087
+ FAIL2BAN_FILTER_FILE,
25088
+ [
25089
+ "# Installed by ThreatCrush. Intentionally matches nothing:",
25090
+ "# detection happens in threatcrushd, this jail only executes bans.",
25091
+ "[Definition]",
25092
+ "failregex = ^threatcrush-never-matches <HOST>$",
25093
+ "ignoreregex =",
25094
+ ""
25095
+ ].join("\n")
25096
+ );
25097
+ writeIfAbsent(
25098
+ FAIL2BAN_JAIL_FILE,
25099
+ [
25100
+ "# Installed by ThreatCrush \u2014 bans arrive via `fail2ban-client set threatcrush banip`.",
25101
+ "# bantime is only a backstop; threatcrushd unbans on its own schedule.",
25102
+ `[${this.jail}]`,
25103
+ "enabled = true",
25104
+ "filter = threatcrush",
25105
+ "backend = polling",
25106
+ "logpath = /var/log/threatcrush/threatcrushd.log",
25107
+ "maxretry = 1000000",
25108
+ "findtime = 1",
25109
+ `bantime = ${this.backstopSeconds}`,
25110
+ ""
25111
+ ].join("\n")
25112
+ );
25113
+ this.client(["reload", this.jail]);
25114
+ this.jailReady = true;
25115
+ }
25116
+ async block(ip) {
25117
+ assertBannableIp(ip);
25118
+ this.ensureJail();
25119
+ this.client(["set", this.jail, "banip", ip]);
25120
+ }
25121
+ async unblock(ip) {
25122
+ assertBannableIp(ip);
25123
+ try {
25124
+ this.client(["set", this.jail, "unbanip", ip]);
25125
+ } catch {
25126
+ }
25127
+ }
25128
+ async isBlocked(ip) {
25129
+ assertBannableIp(ip);
25130
+ return (await this.listBlocked()).includes(ip);
25131
+ }
25132
+ async listBlocked() {
25133
+ try {
25134
+ return parseBannedList(this.client(["get", this.jail, "banned"]));
25135
+ } catch {
25136
+ try {
25137
+ const status = this.client(["status", this.jail]);
25138
+ const line = status.split("\n").find((l) => /Banned IP list:/i.test(l));
25139
+ if (!line) return [];
25140
+ return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net3.isIP)(s) !== 0);
25141
+ } catch {
25142
+ return [];
25143
+ }
25144
+ }
25145
+ }
25146
+ };
25147
+ function parseBannedList(output) {
25148
+ const found = [];
25149
+ for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
25150
+ if ((0, import_node_net3.isIP)(match[1]) !== 0) found.push(match[1]);
25151
+ }
25152
+ if (found.length > 0) return found;
25153
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net3.isIP)(s) !== 0);
25154
+ }
24599
25155
  var NftablesAdapter = class {
24600
25156
  name = "nftables";
24601
25157
  table = "threatcrush";
@@ -24699,6 +25255,7 @@ var IptablesAdapter = class {
24699
25255
  };
24700
25256
  var DryRunAdapter = class {
24701
25257
  name = "dry-run";
25258
+ enforces = false;
24702
25259
  blocked = /* @__PURE__ */ new Set();
24703
25260
  isAvailable() {
24704
25261
  return true;
@@ -24719,7 +25276,19 @@ var DryRunAdapter = class {
24719
25276
  return [...this.blocked];
24720
25277
  }
24721
25278
  };
24722
- function detectFirewallAdapter() {
25279
+ function detectFirewallAdapter(backend = "auto") {
25280
+ const byName = {
25281
+ fail2ban: () => new Fail2banAdapter(),
25282
+ nftables: () => new NftablesAdapter(),
25283
+ iptables: () => new IptablesAdapter(),
25284
+ "dry-run": () => new DryRunAdapter()
25285
+ };
25286
+ if (backend !== "auto") {
25287
+ const chosen = byName[backend]?.();
25288
+ if (chosen?.isAvailable()) return chosen;
25289
+ }
25290
+ const f2b = new Fail2banAdapter();
25291
+ if (f2b.isAvailable()) return f2b;
24723
25292
  const nft = new NftablesAdapter();
24724
25293
  if (nft.isAvailable()) return nft;
24725
25294
  const ipt = new IptablesAdapter();
@@ -24728,14 +25297,129 @@ function detectFirewallAdapter() {
24728
25297
  }
24729
25298
 
24730
25299
  // src/daemon/firewall/remediation.ts
24731
- var import_node_fs25 = require("fs");
25300
+ var import_node_fs26 = require("fs");
25301
+ var import_node_net5 = require("net");
24732
25302
  init_paths();
25303
+ init_backoff();
25304
+
25305
+ // src/daemon/firewall/protected.ts
25306
+ var import_node_child_process7 = require("child_process");
25307
+ var import_node_net4 = require("net");
25308
+ var DEFAULT_PROTECTED = [
25309
+ "127.0.0.0/8",
25310
+ "::1/128",
25311
+ "10.0.0.0/8",
25312
+ "172.16.0.0/12",
25313
+ "192.168.0.0/16",
25314
+ "169.254.0.0/16",
25315
+ "fc00::/7",
25316
+ "fe80::/10"
25317
+ ];
25318
+ function ipToBytes(ip) {
25319
+ const version = (0, import_node_net4.isIP)(ip);
25320
+ if (version === 4) return v4ToBytes(ip);
25321
+ if (version === 6) return v6ToBytes(ip);
25322
+ return null;
25323
+ }
25324
+ function v4ToBytes(ip) {
25325
+ const parts = ip.split(".");
25326
+ if (parts.length !== 4) return null;
25327
+ const bytes = new Uint8Array(4);
25328
+ for (let i = 0; i < 4; i++) {
25329
+ const n = Number(parts[i]);
25330
+ if (!Number.isInteger(n) || n < 0 || n > 255) return null;
25331
+ bytes[i] = n;
25332
+ }
25333
+ return bytes;
25334
+ }
25335
+ function v6ToBytes(ip) {
25336
+ const bare = ip.split("%")[0];
25337
+ const [headText, tailText] = bare.split("::", 2);
25338
+ const head = headText ? headText.split(":") : [];
25339
+ const tail = tailText !== void 0 ? tailText ? tailText.split(":") : [] : null;
25340
+ const groups = [];
25341
+ const pushGroup = (group) => {
25342
+ if (group.includes(".")) {
25343
+ const v4 = v4ToBytes(group);
25344
+ if (!v4) return false;
25345
+ groups.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
25346
+ return true;
25347
+ }
25348
+ if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return false;
25349
+ groups.push(parseInt(group, 16));
25350
+ return true;
25351
+ };
25352
+ for (const group of head) if (!pushGroup(group)) return null;
25353
+ const headCount = groups.length;
25354
+ if (tail === null) {
25355
+ if (headCount !== 8) return null;
25356
+ } else {
25357
+ const tailGroups = [];
25358
+ const saved = groups.length;
25359
+ for (const group of tail) if (!pushGroup(group)) return null;
25360
+ tailGroups.push(...groups.splice(saved));
25361
+ const zeros = 8 - headCount - tailGroups.length;
25362
+ if (zeros < 0) return null;
25363
+ for (let i = 0; i < zeros; i++) groups.push(0);
25364
+ groups.push(...tailGroups);
25365
+ }
25366
+ if (groups.length !== 8) return null;
25367
+ const bytes = new Uint8Array(16);
25368
+ for (let i = 0; i < 8; i++) {
25369
+ bytes[i * 2] = groups[i] >> 8 & 255;
25370
+ bytes[i * 2 + 1] = groups[i] & 255;
25371
+ }
25372
+ return bytes;
25373
+ }
25374
+ function ipMatches(ip, entry) {
25375
+ const [network, prefixText] = entry.trim().split("/");
25376
+ const target = ipToBytes(ip);
25377
+ const base = ipToBytes(network);
25378
+ if (!target || !base || target.length !== base.length) return false;
25379
+ const bits = prefixText === void 0 ? base.length * 8 : Number(prefixText);
25380
+ if (!Number.isInteger(bits) || bits < 0 || bits > base.length * 8) return false;
25381
+ const wholeBytes = Math.floor(bits / 8);
25382
+ for (let i = 0; i < wholeBytes; i++) {
25383
+ if (target[i] !== base[i]) return false;
25384
+ }
25385
+ const remainder = bits % 8;
25386
+ if (remainder === 0) return true;
25387
+ const mask = 255 << 8 - remainder & 255;
25388
+ return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
25389
+ }
25390
+ function isProtected(ip, list) {
25391
+ return list.some((entry) => ipMatches(ip, entry));
25392
+ }
25393
+ function currentSshClient(env2 = process.env) {
25394
+ const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
25395
+ if (!source) return null;
25396
+ const ip = source.trim().split(/\s+/)[0];
25397
+ return ip && (0, import_node_net4.isIP)(ip) ? ip : null;
25398
+ }
25399
+ function defaultGateways() {
25400
+ const found = /* @__PURE__ */ new Set();
25401
+ for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
25402
+ try {
25403
+ const out = (0, import_node_child_process7.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
25404
+ for (const line of out.split("\n")) {
25405
+ const match = line.match(/\bvia\s+(\S+)/);
25406
+ if (match && (0, import_node_net4.isIP)(match[1])) found.add(match[1]);
25407
+ }
25408
+ } catch {
25409
+ }
25410
+ }
25411
+ return [...found];
25412
+ }
25413
+
25414
+ // src/daemon/firewall/remediation.ts
24733
25415
  var DEFAULT_CONFIG2 = {
24734
25416
  enabled: true,
24735
- dry_run: true,
24736
- default_ttl_seconds: 3600,
25417
+ dry_run: false,
24737
25418
  min_severity: "high",
24738
- allowlist: ["127.0.0.1", "::1"]
25419
+ max_ban_seconds: 86400,
25420
+ strike_memory_seconds: 86400,
25421
+ allowlist: [],
25422
+ protect_current_ssh_client: true
24739
25423
  };
24740
25424
  var SEVERITY_RANK4 = {
24741
25425
  info: 0,
@@ -24744,135 +25428,274 @@ var SEVERITY_RANK4 = {
24744
25428
  high: 3,
24745
25429
  critical: 4
24746
25430
  };
25431
+ function explainBlockFailure(err, backend) {
25432
+ const raw = err.message || String(err);
25433
+ const denied = /not permitted|EACCES|EPERM|permission denied|must be root/i.test(raw);
25434
+ if (!denied) return `${raw} (backend: ${backend})`;
25435
+ const who = typeof process.getuid === "function" && process.getuid() === 0 ? "as root" : `as uid ${typeof process.getuid === "function" ? process.getuid() : "?"}`;
25436
+ return `threatcrushd is running ${who} and cannot manage ${backend}. A ban is written by the daemon, not by whoever asked for it \u2014 run the daemon as root: sudo threatcrush install-service && sudo systemctl enable --now threatcrushd`;
25437
+ }
24747
25438
  var RemediationManager = class {
24748
25439
  constructor(adapter, bus2, config) {
24749
25440
  this.adapter = adapter;
24750
25441
  this.bus = bus2;
24751
25442
  this.config = { ...DEFAULT_CONFIG2, ...config };
25443
+ this.protectedList = [...DEFAULT_PROTECTED, ...this.config.allowlist];
25444
+ if (this.config.protect_current_ssh_client) {
25445
+ const ssh = currentSshClient();
25446
+ if (ssh) this.protectedList.push(ssh);
25447
+ }
25448
+ for (const gateway of defaultGateways()) this.protectedList.push(gateway);
25449
+ if (this.adapter.enforces === false) this.config.dry_run = true;
24752
25450
  this.loadState();
25451
+ void this.reconcile();
24753
25452
  this.startExpiryWorker();
24754
25453
  }
24755
25454
  adapter;
24756
25455
  bus;
24757
25456
  config;
24758
25457
  blocklist = [];
25458
+ strikes = {};
25459
+ protectedList = [];
24759
25460
  expiryTimer = null;
25461
+ /** Every address that can never be blocked, built-ins included. */
25462
+ getProtected() {
25463
+ return [...this.protectedList];
25464
+ }
25465
+ isAllowlisted(ip) {
25466
+ return isProtected(ip, this.protectedList);
25467
+ }
24760
25468
  async handleDetection(event) {
24761
25469
  if (!this.config.enabled) return;
24762
25470
  const eventRank = SEVERITY_RANK4[event.severity] ?? 0;
24763
25471
  const minRank = SEVERITY_RANK4[this.config.min_severity] ?? 3;
24764
25472
  if (eventRank < minRank) return;
24765
25473
  const ip = event.source_ip;
24766
- if (!ip) return;
25474
+ if (!ip || (0, import_node_net5.isIP)(ip) === 0) return;
24767
25475
  if (this.isAllowlisted(ip)) return;
24768
25476
  if (this.blocklist.some((b) => b.ip === ip)) return;
24769
- const ruleRemediation = event.details?.remediation;
24770
- const ttl = ruleRemediation?.ttl_seconds || this.config.default_ttl_seconds;
24771
25477
  const ruleId = event.details?.rule_id;
24772
- await this.blockIp(ip, event.message, ruleId, ttl);
25478
+ await this.ban(ip, event.message, { ruleId, source: "auto" });
24773
25479
  }
24774
- async blockIp(ip, reason, ruleId, ttlSeconds) {
24775
- if (this.isAllowlisted(ip)) return false;
25480
+ /**
25481
+ * Ban `ip`. With no explicit TTL the length comes from the Fibonacci ladder:
25482
+ * 1m, 2m, 3m, 5m, 8m, 13m … for the 1st, 2nd, 3rd offence and so on, clamped
25483
+ * to `max_ban_seconds`.
25484
+ */
25485
+ async ban(ip, reason, opts = {}) {
25486
+ if ((0, import_node_net5.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
25487
+ if (this.isAllowlisted(ip)) {
25488
+ return { ok: false, error: `${ip} is protected and can never be blocked` };
25489
+ }
25490
+ const now = Date.now();
25491
+ const existing = this.blocklist.find((b) => b.ip === ip);
25492
+ if (existing && !opts.ttlSeconds) {
25493
+ return { ok: false, error: `${ip} is already banned` };
25494
+ }
25495
+ const strike = recordStrike(this.strikes, ip, now, this.config.strike_memory_seconds);
25496
+ const ttl = opts.ttlSeconds ?? banSeconds(strike, this.config.max_ban_seconds);
24776
25497
  const entry = {
24777
25498
  ip,
24778
25499
  reason,
24779
- rule_id: ruleId,
24780
- blocked_at: Date.now(),
24781
- expires_at: ttlSeconds ? Date.now() + ttlSeconds * 1e3 : void 0,
24782
- dry_run: this.config.dry_run
25500
+ rule_id: opts.ruleId,
25501
+ blocked_at: now,
25502
+ expires_at: now + ttl * 1e3,
25503
+ dry_run: this.config.dry_run,
25504
+ strikes: strike,
25505
+ source: opts.source ?? "manual"
24783
25506
  };
24784
25507
  if (!this.config.dry_run) {
24785
25508
  try {
24786
25509
  await this.adapter.block(ip);
24787
25510
  } catch (err) {
24788
- this.logLine(`[firewall] EACCES or error blocking ${ip}: ${err.message}`);
25511
+ const message = explainBlockFailure(err, this.adapter.name);
25512
+ this.logLine(`[firewall] error blocking ${ip}: ${message}`);
24789
25513
  this.bus.publish({
24790
25514
  timestamp: /* @__PURE__ */ new Date(),
24791
25515
  module: "firewall-rules",
24792
25516
  category: "system",
24793
25517
  severity: "medium",
24794
- message: `Failed to block ${ip}: ${err.message}. Ensure daemon has CAP_NET_ADMIN.`
25518
+ message: `Failed to block ${ip}: ${message}`,
25519
+ source_ip: ip
24795
25520
  });
24796
- return false;
25521
+ return { ok: false, error: message };
24797
25522
  }
24798
25523
  }
25524
+ this.blocklist = this.blocklist.filter((b) => b.ip !== ip);
24799
25525
  this.blocklist.push(entry);
24800
25526
  this.saveState();
24801
25527
  const mode = this.config.dry_run ? "[DRY-RUN] " : "";
24802
- const expiryMsg = ttlSeconds ? ` (expires in ${ttlSeconds}s)` : " (permanent)";
24803
- this.logLine(`[firewall] ${mode}Blocked ${ip}: ${reason}${expiryMsg}`);
25528
+ const label = `${mode}Banned ${ip} for ${formatDuration(ttl)} (offence #${strike}): ${reason}`;
25529
+ this.logLine(`[firewall] ${label}`);
24804
25530
  this.bus.publish({
24805
25531
  timestamp: /* @__PURE__ */ new Date(),
24806
25532
  module: "firewall-rules",
24807
25533
  category: "system",
24808
25534
  severity: "info",
24809
- message: `${mode}Blocked ${ip}: ${reason}${expiryMsg}`,
25535
+ message: label,
24810
25536
  source_ip: ip,
24811
- details: { action: "block", rule_id: ruleId, dry_run: this.config.dry_run, ttl_seconds: ttlSeconds }
25537
+ details: {
25538
+ action: "block",
25539
+ rule_id: opts.ruleId,
25540
+ dry_run: this.config.dry_run,
25541
+ ttl_seconds: ttl,
25542
+ strikes: strike,
25543
+ source: entry.source,
25544
+ backend: this.adapter.name
25545
+ }
24812
25546
  });
24813
- return true;
25547
+ return { ok: true, entry };
24814
25548
  }
24815
- async unblockIp(ip) {
25549
+ /**
25550
+ * Lift a ban. `forget` also drops the strike ledger entry — an operator
25551
+ * unbanning by hand is overruling the detection, so the next offence should
25552
+ * start at one minute again rather than resuming the ladder.
25553
+ */
25554
+ async unban(ip, opts = {}) {
24816
25555
  const idx = this.blocklist.findIndex((b) => b.ip === ip);
24817
- if (idx < 0) return false;
24818
- const entry = this.blocklist[idx];
24819
- if (!entry.dry_run) {
25556
+ const entry = idx >= 0 ? this.blocklist[idx] : null;
25557
+ if (!entry?.dry_run) {
24820
25558
  try {
24821
25559
  await this.adapter.unblock(ip);
24822
25560
  } catch (err) {
24823
- this.logLine(`[firewall] Error unblocking ${ip}: ${err.message}`);
24824
- return false;
25561
+ const message = err.message;
25562
+ this.logLine(`[firewall] error unblocking ${ip}: ${message}`);
25563
+ return { ok: false, error: message };
24825
25564
  }
24826
25565
  }
24827
- this.blocklist.splice(idx, 1);
25566
+ if (idx >= 0) this.blocklist.splice(idx, 1);
25567
+ if (opts.forget) delete this.strikes[ip];
24828
25568
  this.saveState();
24829
- this.logLine(`[firewall] Unblocked ${ip}`);
25569
+ if (idx < 0) return { ok: false, error: `${ip} is not banned` };
25570
+ this.logLine(`[firewall] Unbanned ${ip}${opts.forget ? " (strikes cleared)" : ""}`);
24830
25571
  this.bus.publish({
24831
25572
  timestamp: /* @__PURE__ */ new Date(),
24832
25573
  module: "firewall-rules",
24833
25574
  category: "system",
24834
25575
  severity: "info",
24835
- message: `Unblocked ${ip}`,
25576
+ message: `Unbanned ${ip}`,
24836
25577
  source_ip: ip,
24837
- details: { action: "unblock" }
25578
+ details: { action: "unblock", forget: opts.forget === true }
24838
25579
  });
24839
- return true;
25580
+ return { ok: true };
24840
25581
  }
24841
- isAllowlisted(ip) {
24842
- return this.config.allowlist.includes(ip);
25582
+ /** Lifts every ban this module placed. The "undo it all" of R12. */
25583
+ async flush() {
25584
+ const entries = [...this.blocklist];
25585
+ for (const entry of entries) await this.unban(entry.ip);
25586
+ return entries.length;
25587
+ }
25588
+ getBlocklist() {
25589
+ return [...this.blocklist].sort((a, b) => b.blocked_at - a.blocked_at);
25590
+ }
25591
+ getAllowlist() {
25592
+ return [...this.protectedList];
25593
+ }
25594
+ /** Offence count per address, so the dashboard can show why a ban is long. */
25595
+ getStrikes() {
25596
+ return { ...this.strikes };
25597
+ }
25598
+ status() {
25599
+ return {
25600
+ enabled: this.config.enabled,
25601
+ dry_run: this.config.dry_run,
25602
+ backend: this.adapter.name,
25603
+ min_severity: this.config.min_severity,
25604
+ banned: this.blocklist.length,
25605
+ max_ban_seconds: this.config.max_ban_seconds,
25606
+ warning: this.privilegeWarning()
25607
+ };
25608
+ }
25609
+ /**
25610
+ * Set when the daemon intends to enforce but cannot. `nft --version` succeeds
25611
+ * for anybody, so backend detection alone will happily pick nftables inside
25612
+ * an unprivileged daemon — and then every ban fails at the moment it matters.
25613
+ * Saying so up front beats a dashboard that looks armed and is not.
25614
+ */
25615
+ privilegeWarning() {
25616
+ if (!this.config.enabled || this.config.dry_run) return void 0;
25617
+ if (this.adapter.enforces === false) return void 0;
25618
+ const uid = typeof process.getuid === "function" ? process.getuid() : 0;
25619
+ if (uid === 0) return void 0;
25620
+ return `daemon runs as uid ${uid} and cannot write ${this.adapter.name} rules \u2014 bans will fail`;
24843
25621
  }
24844
25622
  addToAllowlist(ip) {
24845
- if (!this.config.allowlist.includes(ip)) {
24846
- this.config.allowlist.push(ip);
24847
- }
25623
+ if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
25624
+ if (!this.config.allowlist.includes(ip)) this.config.allowlist.push(ip);
24848
25625
  }
24849
25626
  removeFromAllowlist(ip) {
25627
+ if (DEFAULT_PROTECTED.includes(ip)) return;
25628
+ this.protectedList = this.protectedList.filter((a) => a !== ip);
24850
25629
  this.config.allowlist = this.config.allowlist.filter((a) => a !== ip);
24851
25630
  }
24852
- getBlocklist() {
24853
- return [...this.blocklist];
24854
- }
24855
- getAllowlist() {
24856
- return [...this.config.allowlist];
24857
- }
24858
25631
  stop() {
24859
25632
  if (this.expiryTimer) clearInterval(this.expiryTimer);
24860
25633
  this.expiryTimer = null;
24861
25634
  }
25635
+ /**
25636
+ * R5: bans survive a restart, their TTLs do not. Anything that expired while
25637
+ * the daemon was down is dropped, and anything still live is re-applied —
25638
+ * the firewall may have been flushed by a reboot underneath us.
25639
+ */
25640
+ async reconcile() {
25641
+ const now = Date.now();
25642
+ const live = this.blocklist.filter((b) => b.expires_at > now);
25643
+ const stale = this.blocklist.filter((b) => b.expires_at <= now);
25644
+ for (const entry of stale) {
25645
+ if (!entry.dry_run) {
25646
+ try {
25647
+ await this.adapter.unblock(entry.ip);
25648
+ } catch {
25649
+ }
25650
+ }
25651
+ }
25652
+ this.blocklist = live;
25653
+ this.saveState();
25654
+ if (this.config.dry_run) return;
25655
+ let applied = [];
25656
+ try {
25657
+ applied = await this.adapter.listBlocked();
25658
+ } catch {
25659
+ }
25660
+ for (const entry of live) {
25661
+ if (applied.includes(entry.ip)) continue;
25662
+ try {
25663
+ await this.adapter.block(entry.ip);
25664
+ } catch {
25665
+ }
25666
+ }
25667
+ }
24862
25668
  startExpiryWorker() {
24863
- this.expiryTimer = setInterval(() => void this.processExpiries(), 3e4);
25669
+ this.expiryTimer = setInterval(() => void this.processExpiries(), 1e4);
25670
+ this.expiryTimer.unref?.();
24864
25671
  }
24865
25672
  async processExpiries() {
24866
25673
  const now = Date.now();
24867
- const expired = this.blocklist.filter((b) => b.expires_at && b.expires_at <= now);
24868
- for (const entry of expired) {
24869
- await this.unblockIp(entry.ip);
25674
+ for (const entry of this.blocklist.filter((b) => b.expires_at <= now)) {
25675
+ await this.unban(entry.ip);
25676
+ }
25677
+ const pruned = pruneStrikes(this.strikes, now, this.config.strike_memory_seconds);
25678
+ if (Object.keys(pruned).length !== Object.keys(this.strikes).length) {
25679
+ this.strikes = pruned;
25680
+ this.saveState();
24870
25681
  }
24871
25682
  }
24872
25683
  loadState() {
24873
25684
  try {
24874
25685
  const saved = getModuleState("firewall-rules", "blocklist");
24875
- if (Array.isArray(saved)) this.blocklist = saved;
25686
+ if (Array.isArray(saved)) {
25687
+ this.blocklist = saved.map((entry) => ({
25688
+ ...entry,
25689
+ strikes: entry.strikes ?? 1,
25690
+ source: entry.source ?? "auto",
25691
+ expires_at: entry.expires_at ?? entry.blocked_at + this.config.max_ban_seconds * 1e3
25692
+ }));
25693
+ }
25694
+ } catch {
25695
+ }
25696
+ try {
25697
+ const saved = getModuleState("firewall-rules", "strikes");
25698
+ if (saved && typeof saved === "object") this.strikes = saved;
24876
25699
  } catch {
24877
25700
  }
24878
25701
  }
@@ -24881,16 +25704,42 @@ var RemediationManager = class {
24881
25704
  setModuleState("firewall-rules", "blocklist", this.blocklist);
24882
25705
  } catch {
24883
25706
  }
25707
+ try {
25708
+ setModuleState("firewall-rules", "strikes", this.strikes);
25709
+ } catch {
25710
+ }
24884
25711
  }
24885
25712
  logLine(line) {
24886
25713
  try {
24887
- (0, import_node_fs25.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
25714
+ (0, import_node_fs26.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
24888
25715
  `);
24889
25716
  } catch {
24890
25717
  }
24891
25718
  }
24892
25719
  };
24893
25720
 
25721
+ // src/daemon/firewall/settings.ts
25722
+ init_backoff();
25723
+ function remediationSettings(section) {
25724
+ if (!section) return {};
25725
+ const settings = {};
25726
+ if (typeof section.enabled === "boolean") settings.enabled = section.enabled;
25727
+ if (section.mode === "dry_run") settings.dry_run = true;
25728
+ else if (section.mode === "enforce") settings.dry_run = false;
25729
+ else if (typeof section.dry_run === "boolean") settings.dry_run = section.dry_run;
25730
+ if (section.min_severity) settings.min_severity = section.min_severity;
25731
+ const maxBan = parseDuration(section.max_ban);
25732
+ if (maxBan) settings.max_ban_seconds = maxBan;
25733
+ const memory = parseDuration(section.strike_memory);
25734
+ if (memory) settings.strike_memory_seconds = memory;
25735
+ const allow = [...section.protected ?? [], ...section.allowlist ?? []];
25736
+ if (allow.length > 0) settings.allowlist = allow;
25737
+ if (typeof section.protect_current_ssh_client === "boolean") {
25738
+ settings.protect_current_ssh_client = section.protect_current_ssh_client;
25739
+ }
25740
+ return settings;
25741
+ }
25742
+
24894
25743
  // src/core/telemetry.ts
24895
25744
  var ready = false;
24896
25745
  var sentry = null;
@@ -24940,7 +25789,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
24940
25789
  // src/daemon/index.ts
24941
25790
  function readVersion2() {
24942
25791
  try {
24943
- const pkg = JSON.parse((0, import_node_fs26.readFileSync)((0, import_node_path18.join)(__dirname, "..", "package.json"), "utf-8"));
25792
+ const pkg = JSON.parse((0, import_node_fs27.readFileSync)((0, import_node_path19.join)(__dirname, "..", "package.json"), "utf-8"));
24944
25793
  return pkg.version || "0.0.0";
24945
25794
  } catch {
24946
25795
  return "0.0.0";
@@ -24948,7 +25797,7 @@ function readVersion2() {
24948
25797
  }
24949
25798
  function logLine(line) {
24950
25799
  try {
24951
- (0, import_node_fs26.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
25800
+ (0, import_node_fs27.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
24952
25801
  `);
24953
25802
  } catch {
24954
25803
  }
@@ -24976,7 +25825,7 @@ async function runDaemon() {
24976
25825
  } catch (err) {
24977
25826
  logLine(`[daemon] state db unavailable: ${err.message}`);
24978
25827
  }
24979
- const config = loadConfig((0, import_node_fs26.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
25828
+ const config = loadConfig((0, import_node_fs27.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
24980
25829
  bus.on("event", (event) => {
24981
25830
  logLine(`[event] ${event.severity} ${event.module} ${event.message}`);
24982
25831
  });
@@ -25004,14 +25853,24 @@ async function runDaemon() {
25004
25853
  });
25005
25854
  logLine(`[daemon] rule engine loaded ${ruleEngine.getRules().length} rules`);
25006
25855
  setInterval(() => ruleEngine.cleanup(), 3e5);
25007
- const firewallAdapter = detectFirewallAdapter();
25008
- const remediation = new RemediationManager(firewallAdapter, bus, config.remediation);
25856
+ const settings = remediationSettings(config.remediation);
25857
+ const firewallAdapter = detectFirewallAdapter(config.remediation?.backend ?? "auto");
25858
+ const remediation = new RemediationManager(firewallAdapter, bus, settings);
25009
25859
  bus.on("event", (event) => {
25010
25860
  if (event.module !== "firewall-rules") {
25011
25861
  void remediation.handleDetection(event);
25012
25862
  }
25013
25863
  });
25014
- logLine(`[daemon] firewall remediation active (backend=${firewallAdapter.name}, dry_run=${config.remediation?.dry_run ?? true})`);
25864
+ const remediationStatus = remediation.status();
25865
+ logLine(
25866
+ `[daemon] auto-defence ${remediationStatus.enabled ? "ON" : "OFF"} (backend=${remediationStatus.backend}, mode=${remediationStatus.dry_run ? "dry_run" : "enforce"}, min_severity=${remediationStatus.min_severity}, bans escalate 1m\u21922m\u21923m\u21925m\u21928m\u2026)`
25867
+ );
25868
+ if (remediationStatus.dry_run && firewallAdapter.enforces !== false) {
25869
+ logLine("[daemon] dry_run is set in [remediation] \u2014 detections will be logged, not blocked");
25870
+ }
25871
+ if (firewallAdapter.enforces === false) {
25872
+ logLine("[daemon] no manageable firewall found (need fail2ban, nftables or iptables) \u2014 bans are simulated");
25873
+ }
25015
25874
  new AlertDispatcher(bus, config);
25016
25875
  const runsWorker = new RunsWorker(bus);
25017
25876
  try {
@@ -25019,7 +25878,7 @@ async function runDaemon() {
25019
25878
  } catch (err) {
25020
25879
  logLine(`[daemon] runs-worker failed to start: ${err.message}`);
25021
25880
  }
25022
- const ipc = new IpcServer(version, moduleHost);
25881
+ const ipc = new IpcServer(version, moduleHost, remediation);
25023
25882
  await ipc.start();
25024
25883
  logLine(`[daemon] ipc listening on ${PATHS.socket}`);
25025
25884
  const shutdown = async (signal) => {
@@ -25067,7 +25926,7 @@ async function runDaemon() {
25067
25926
  // src/commands/daemon.ts
25068
25927
  init_paths();
25069
25928
  init_ipc_client();
25070
- var DAEMON_ENTRY = (0, import_node_path19.join)(__dirname, "daemon.js");
25929
+ var DAEMON_ENTRY = (0, import_node_path20.join)(__dirname, "daemon.js");
25071
25930
  async function daemonForeground() {
25072
25931
  await runDaemon();
25073
25932
  }
@@ -25078,7 +25937,7 @@ async function daemonStart() {
25078
25937
  return;
25079
25938
  }
25080
25939
  ensureRuntimeDirs();
25081
- if (!(0, import_node_fs27.existsSync)(DAEMON_ENTRY)) {
25940
+ if (!(0, import_node_fs28.existsSync)(DAEMON_ENTRY)) {
25082
25941
  console.log(source_default.red(` Daemon entry not found at ${DAEMON_ENTRY}.`));
25083
25942
  console.log(source_default.dim(" Reinstall with `threatcrush update` or `pnpm run build` in the cli package."));
25084
25943
  return;
@@ -25086,8 +25945,8 @@ async function daemonStart() {
25086
25945
  let out;
25087
25946
  let err;
25088
25947
  try {
25089
- out = (0, import_node_fs28.openSync)(PATHS.logFile, "a");
25090
- err = (0, import_node_fs28.openSync)(PATHS.logFile, "a");
25948
+ out = (0, import_node_fs29.openSync)(PATHS.logFile, "a");
25949
+ err = (0, import_node_fs29.openSync)(PATHS.logFile, "a");
25091
25950
  } catch (e) {
25092
25951
  const code = e.code;
25093
25952
  console.log(source_default.red(` \u2717 Cannot write daemon log at ${PATHS.logFile} (${code ?? "error"}).`));
@@ -25100,7 +25959,7 @@ async function daemonStart() {
25100
25959
  }
25101
25960
  return;
25102
25961
  }
25103
- const child = (0, import_node_child_process7.spawn)(process.execPath, [DAEMON_ENTRY], {
25962
+ const child = (0, import_node_child_process8.spawn)(process.execPath, [DAEMON_ENTRY], {
25104
25963
  detached: true,
25105
25964
  stdio: ["ignore", out, err],
25106
25965
  env: { ...process.env, THREATCRUSH_DAEMON: "1" }
@@ -25173,39 +26032,39 @@ async function waitForExit(pid, timeoutMs) {
25173
26032
  }
25174
26033
  async function releaseStaleSocket() {
25175
26034
  const deadline = Date.now() + 2e3;
25176
- while ((0, import_node_fs27.existsSync)(PATHS.socket) && Date.now() < deadline) {
26035
+ while ((0, import_node_fs28.existsSync)(PATHS.socket) && Date.now() < deadline) {
25177
26036
  await new Promise((r) => setTimeout(r, 50));
25178
26037
  }
25179
- if ((0, import_node_fs27.existsSync)(PATHS.socket)) {
26038
+ if ((0, import_node_fs28.existsSync)(PATHS.socket)) {
25180
26039
  try {
25181
- (0, import_node_fs27.unlinkSync)(PATHS.socket);
26040
+ (0, import_node_fs28.unlinkSync)(PATHS.socket);
25182
26041
  } catch {
25183
26042
  }
25184
26043
  }
25185
26044
  }
25186
26045
 
25187
26046
  // src/commands/service.ts
25188
- var import_node_child_process8 = require("child_process");
25189
- var import_node_fs29 = require("fs");
25190
- var import_node_path20 = require("path");
26047
+ var import_node_child_process9 = require("child_process");
26048
+ var import_node_fs30 = require("fs");
26049
+ var import_node_path21 = require("path");
25191
26050
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
25192
26051
  function resolveTemplate() {
25193
- const templatePath = (0, import_node_path20.join)(__dirname, "systemd", "threatcrushd.service");
25194
- if (!(0, import_node_fs29.existsSync)(templatePath)) {
26052
+ const templatePath = (0, import_node_path21.join)(__dirname, "systemd", "threatcrushd.service");
26053
+ if (!(0, import_node_fs30.existsSync)(templatePath)) {
25195
26054
  throw new Error(`systemd unit template not found at ${templatePath}`);
25196
26055
  }
25197
- return (0, import_node_fs29.readFileSync)(templatePath, "utf-8");
26056
+ return (0, import_node_fs30.readFileSync)(templatePath, "utf-8");
25198
26057
  }
25199
26058
  function stableBinPath(binPath) {
25200
26059
  const stable = binPath.replace(/\/\.pnpm\/[^/]+\/node_modules\//, "/node_modules/");
25201
26060
  if (stable === binPath) return binPath;
25202
- return (0, import_node_fs29.existsSync)(stable) ? stable : binPath;
26061
+ return (0, import_node_fs30.existsSync)(stable) ? stable : binPath;
25203
26062
  }
25204
26063
  function resolveBinPath() {
25205
26064
  const arg = process.argv[1];
25206
- if (arg && (0, import_node_fs29.existsSync)(arg)) return stableBinPath(arg);
26065
+ if (arg && (0, import_node_fs30.existsSync)(arg)) return stableBinPath(arg);
25207
26066
  try {
25208
- return (0, import_node_child_process8.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
26067
+ return (0, import_node_child_process9.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
25209
26068
  } catch {
25210
26069
  return "threatcrush";
25211
26070
  }
@@ -25224,12 +26083,12 @@ async function installServiceCommand() {
25224
26083
  return;
25225
26084
  }
25226
26085
  const unit = resolveTemplate().replace("{{BIN_PATH}}", resolveBinPath());
25227
- (0, import_node_fs29.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
26086
+ (0, import_node_fs30.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
25228
26087
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
25229
26088
  ensureSystemDirs();
25230
26089
  try {
25231
- (0, import_node_child_process8.execSync)("systemctl daemon-reload", { stdio: "inherit" });
25232
- (0, import_node_child_process8.execSync)("systemctl enable threatcrushd.service", { stdio: "inherit" });
26090
+ (0, import_node_child_process9.execSync)("systemctl daemon-reload", { stdio: "inherit" });
26091
+ (0, import_node_child_process9.execSync)("systemctl enable threatcrushd.service", { stdio: "inherit" });
25233
26092
  console.log(source_default.green(" \u2713 Service enabled on boot."));
25234
26093
  console.log(source_default.dim(" Start now with: systemctl start threatcrushd"));
25235
26094
  console.log(source_default.dim(" View logs with: journalctl -u threatcrushd -f"));
@@ -25250,20 +26109,20 @@ function ensureSystemDirs() {
25250
26109
  ];
25251
26110
  let admGid = null;
25252
26111
  try {
25253
- admGid = (0, import_node_fs29.statSync)("/var/log/auth.log").gid;
26112
+ admGid = (0, import_node_fs30.statSync)("/var/log/auth.log").gid;
25254
26113
  } catch {
25255
26114
  }
25256
26115
  for (const { path, groupWritable, sticky } of dirs) {
25257
26116
  try {
25258
- (0, import_node_fs29.mkdirSync)(path, { recursive: true });
26117
+ (0, import_node_fs30.mkdirSync)(path, { recursive: true });
25259
26118
  } catch {
25260
26119
  }
25261
26120
  try {
25262
26121
  if (groupWritable && admGid !== null) {
25263
- (0, import_node_fs29.chmodSync)(path, sticky ? 1533 : 509);
25264
- (0, import_node_child_process8.execSync)(`chgrp adm ${path}`, { stdio: "ignore" });
26122
+ (0, import_node_fs30.chmodSync)(path, sticky ? 1533 : 509);
26123
+ (0, import_node_child_process9.execSync)(`chgrp adm ${path}`, { stdio: "ignore" });
25265
26124
  } else {
25266
- (0, import_node_fs29.chmodSync)(path, 493);
26125
+ (0, import_node_fs30.chmodSync)(path, 493);
25267
26126
  }
25268
26127
  } catch {
25269
26128
  }
@@ -25281,22 +26140,22 @@ async function uninstallServiceCommand() {
25281
26140
  return;
25282
26141
  }
25283
26142
  try {
25284
- (0, import_node_child_process8.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
26143
+ (0, import_node_child_process9.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
25285
26144
  } catch {
25286
26145
  }
25287
26146
  try {
25288
- (0, import_node_child_process8.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
26147
+ (0, import_node_child_process9.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
25289
26148
  } catch {
25290
26149
  }
25291
26150
  try {
25292
- if ((0, import_node_fs29.existsSync)(UNIT_PATH)) {
25293
- (0, import_node_child_process8.execSync)(`rm -f ${UNIT_PATH}`);
26151
+ if ((0, import_node_fs30.existsSync)(UNIT_PATH)) {
26152
+ (0, import_node_child_process9.execSync)(`rm -f ${UNIT_PATH}`);
25294
26153
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
25295
26154
  }
25296
26155
  } catch {
25297
26156
  }
25298
26157
  try {
25299
- (0, import_node_child_process8.execSync)("systemctl daemon-reload", { stdio: "inherit" });
26158
+ (0, import_node_child_process9.execSync)("systemctl daemon-reload", { stdio: "inherit" });
25300
26159
  } catch {
25301
26160
  }
25302
26161
  console.log(source_default.green(" \u2713 threatcrushd service removed."));
@@ -25387,8 +26246,8 @@ function welcomeCommand() {
25387
26246
  }
25388
26247
 
25389
26248
  // src/commands/properties.ts
25390
- var import_node_fs30 = require("fs");
25391
- var import_node_path21 = require("path");
26249
+ var import_node_fs31 = require("fs");
26250
+ var import_node_path22 = require("path");
25392
26251
  var import_node_readline6 = __toESM(require("readline"));
25393
26252
  var API_URL7 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
25394
26253
  var KINDS = ["url", "api", "domain", "ip", "repo"];
@@ -25717,8 +26576,8 @@ async function propertiesRunsCommand(opts) {
25717
26576
  }
25718
26577
  }
25719
26578
  function parseImportFile(path) {
25720
- const ext = (0, import_node_path21.extname)(path).toLowerCase();
25721
- const raw = (0, import_node_fs30.readFileSync)(path, "utf-8");
26579
+ const ext = (0, import_node_path22.extname)(path).toLowerCase();
26580
+ const raw = (0, import_node_fs31.readFileSync)(path, "utf-8");
25722
26581
  if (ext === ".json") {
25723
26582
  const parsed = JSON.parse(raw);
25724
26583
  if (!Array.isArray(parsed)) throw new Error("JSON must be an array of objects");
@@ -25908,18 +26767,18 @@ async function rulesCommand(opts) {
25908
26767
  }
25909
26768
 
25910
26769
  // src/commands/harden.ts
25911
- var import_node_fs31 = require("fs");
25912
- var import_node_child_process9 = require("child_process");
26770
+ var import_node_fs32 = require("fs");
26771
+ var import_node_child_process10 = require("child_process");
25913
26772
  function tryExec(cmd) {
25914
26773
  try {
25915
- return (0, import_node_child_process9.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
26774
+ return (0, import_node_child_process10.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
25916
26775
  } catch {
25917
26776
  return null;
25918
26777
  }
25919
26778
  }
25920
26779
  function tryRead(path) {
25921
26780
  try {
25922
- return (0, import_node_fs31.readFileSync)(path, "utf-8");
26781
+ return (0, import_node_fs32.readFileSync)(path, "utf-8");
25923
26782
  } catch {
25924
26783
  return null;
25925
26784
  }
@@ -26023,8 +26882,8 @@ function checkSshWeakConfig() {
26023
26882
  };
26024
26883
  }
26025
26884
  function checkAutoUpdates() {
26026
- const unattended = (0, import_node_fs31.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs31.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
26027
- const dnfAuto = (0, import_node_fs31.existsSync)("/etc/dnf/automatic.conf");
26885
+ const unattended = (0, import_node_fs32.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs32.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
26886
+ const dnfAuto = (0, import_node_fs32.existsSync)("/etc/dnf/automatic.conf");
26028
26887
  if (unattended || dnfAuto) {
26029
26888
  return {
26030
26889
  key: "auto-updates",
@@ -26150,7 +27009,7 @@ function checkFail2ban() {
26150
27009
  explanation: "fail2ban is installed and running."
26151
27010
  };
26152
27011
  }
26153
- if ((0, import_node_fs31.existsSync)("/etc/fail2ban/fail2ban.conf")) {
27012
+ if ((0, import_node_fs32.existsSync)("/etc/fail2ban/fail2ban.conf")) {
26154
27013
  return {
26155
27014
  key: checkKey,
26156
27015
  status: "warn",
@@ -26301,79 +27160,131 @@ async function hardenCommand(opts) {
26301
27160
  }
26302
27161
 
26303
27162
  // src/commands/firewall.ts
27163
+ init_ipc_client();
27164
+ init_paths();
27165
+ init_backoff();
27166
+ async function connect() {
27167
+ if (!IpcClient.isDaemonRunning()) {
27168
+ console.log(source_default.red(` No daemon at ${PATHS.socket}.`));
27169
+ console.log(source_default.gray(" Start it first: threatcrush start"));
27170
+ console.log();
27171
+ return null;
27172
+ }
27173
+ const client = new IpcClient();
27174
+ try {
27175
+ await client.connect();
27176
+ return client;
27177
+ } catch (err) {
27178
+ console.log(source_default.red(` Cannot reach threatcrushd: ${err.message}`));
27179
+ console.log();
27180
+ return null;
27181
+ }
27182
+ }
26304
27183
  async function blockCommand(ip, opts) {
26305
27184
  banner();
26306
27185
  console.log(source_default.green.bold(" Firewall Block"));
26307
27186
  console.log(source_default.gray(" " + "\u2500".repeat(50)));
26308
- let ttlSeconds;
26309
- if (opts.ttl) {
26310
- const match = opts.ttl.match(/^(\d+)(s|m|h|d)?$/);
26311
- if (match) {
26312
- const value = parseInt(match[1]);
26313
- const unit = match[2] || "s";
26314
- const multipliers = { s: 1, m: 60, h: 3600, d: 86400 };
26315
- ttlSeconds = value * (multipliers[unit] || 1);
26316
- }
26317
- }
26318
- console.log(` Blocking ${source_default.red(ip)}${ttlSeconds ? ` for ${opts.ttl}` : " permanently"}...`);
26319
- console.log(source_default.gray(" Note: Requires running daemon with CAP_NET_ADMIN"));
26320
- console.log(source_default.gray(" Configure in /etc/threatcrush/threatcrushd.conf under [remediation]"));
26321
- console.log();
27187
+ const client = await connect();
27188
+ if (!client) return;
27189
+ try {
27190
+ const entry = await client.block(ip, "banned from CLI", opts.ttl);
27191
+ const ttl = formatDuration(Math.round((entry.expires_at - Date.now()) / 1e3));
27192
+ const mode = entry.dry_run ? source_default.yellow(" [DRY-RUN]") : "";
27193
+ console.log(` ${source_default.red("\u2716")} Banned ${source_default.white(ip)} for ${source_default.white(ttl)}${mode}`);
27194
+ console.log(source_default.gray(` Offence #${entry.strikes} \u2014 repeat offences escalate 1m \u2192 2m \u2192 3m \u2192 5m \u2192 8m \u2026`));
27195
+ } catch (err) {
27196
+ console.log(` ${source_default.red("\u2717")} ${err.message}`);
27197
+ } finally {
27198
+ client.close();
27199
+ console.log();
27200
+ }
26322
27201
  }
26323
27202
  async function unblockCommand(ip) {
26324
27203
  banner();
26325
27204
  console.log(source_default.green.bold(" Firewall Unblock"));
26326
27205
  console.log(source_default.gray(" " + "\u2500".repeat(50)));
26327
- console.log(` Unblocking ${source_default.white(ip)}...`);
26328
- console.log(source_default.gray(" Note: Requires running daemon"));
26329
- console.log();
27206
+ const client = await connect();
27207
+ if (!client) return;
27208
+ try {
27209
+ await client.unblock(ip);
27210
+ console.log(` ${source_default.green("\u2713")} Unbanned ${source_default.white(ip)} ${source_default.gray("(strike history cleared)")}`);
27211
+ } catch (err) {
27212
+ console.log(` ${source_default.red("\u2717")} ${err.message}`);
27213
+ } finally {
27214
+ client.close();
27215
+ console.log();
27216
+ }
26330
27217
  }
26331
27218
  async function blocklistCommand() {
26332
27219
  banner();
26333
27220
  console.log(source_default.green.bold(" Active Blocklist"));
26334
- console.log(source_default.gray(" " + "\u2500".repeat(60)));
26335
- console.log(source_default.gray(" Connect to running daemon for live blocklist data."));
26336
- console.log(source_default.gray(" Configure via /etc/threatcrush/threatcrushd.conf [remediation]"));
27221
+ console.log(source_default.gray(" " + "\u2500".repeat(70)));
27222
+ const client = await connect();
27223
+ if (!client) return;
27224
+ let reply;
27225
+ try {
27226
+ reply = await client.blocklist();
27227
+ } catch (err) {
27228
+ console.log(` ${source_default.red("\u2717")} ${err.message}`);
27229
+ client.close();
27230
+ console.log();
27231
+ return;
27232
+ }
27233
+ client.close();
27234
+ const mode = reply.dry_run ? source_default.yellow("dry-run") : source_default.green("enforcing");
27235
+ console.log(` Auto-defence: ${reply.enabled ? mode : source_default.red("disabled")}`);
27236
+ console.log(` Backend: ${source_default.white(reply.backend)}`);
27237
+ console.log(` Bans at: ${source_default.white(reply.min_severity)} severity and above`);
26337
27238
  console.log();
26338
- console.log(source_default.gray(" Remediation config options:"));
26339
- console.log(source_default.gray(" enabled = true"));
26340
- console.log(source_default.gray(" dry_run = true # Log only, no actual blocks"));
26341
- console.log(source_default.gray(' default_ttl = "1h" # Default block duration'));
26342
- console.log(source_default.gray(' min_severity = "high" # Minimum severity to auto-block'));
27239
+ if (reply.entries.length === 0) {
27240
+ console.log(source_default.gray(" Nothing is banned."));
27241
+ console.log();
27242
+ return;
27243
+ }
27244
+ const now = Date.now();
27245
+ console.log(
27246
+ source_default.gray(" ") + source_default.gray("IP".padEnd(40)) + source_default.gray("#".padEnd(5)) + source_default.gray("LEFT".padEnd(9)) + source_default.gray("SOURCE")
27247
+ );
27248
+ for (const entry of reply.entries) {
27249
+ const left = formatDuration(Math.round((entry.expires_at - now) / 1e3));
27250
+ console.log(
27251
+ " " + source_default.white(entry.ip.padEnd(40)) + source_default.gray(String(entry.strikes).padEnd(5)) + source_default.yellow(left.padEnd(9)) + source_default.gray(entry.source + (entry.dry_run ? " (dry-run)" : ""))
27252
+ );
27253
+ console.log(source_default.gray(` ${entry.reason}`));
27254
+ }
26343
27255
  console.log();
26344
27256
  }
26345
27257
  async function allowlistCommand(opts) {
26346
27258
  banner();
26347
27259
  const action = opts.action || "list";
26348
- console.log(source_default.green.bold(" Allowlist"));
27260
+ console.log(source_default.green.bold(" Allowlist (never banned)"));
26349
27261
  console.log(source_default.gray(" " + "\u2500".repeat(50)));
26350
- switch (action) {
26351
- case "list":
26352
- case "ls":
26353
- console.log(source_default.gray(" Allowlisted IPs/CIDRs (from config):"));
26354
- console.log(source_default.gray(" 127.0.0.1"));
26355
- console.log(source_default.gray(" ::1"));
26356
- console.log();
26357
- console.log(source_default.gray(" Add more via /etc/threatcrush/threatcrushd.conf [remediation] allowlist"));
26358
- break;
26359
- case "add":
26360
- if (!opts.value) {
26361
- console.log(source_default.red(" IP/CIDR required. Usage: threatcrush allowlist add <ip>"));
26362
- break;
26363
- }
26364
- console.log(source_default.green(` Added ${opts.value} to allowlist`));
26365
- break;
26366
- case "remove":
26367
- if (!opts.value) {
26368
- console.log(source_default.red(" IP/CIDR required. Usage: threatcrush allowlist remove <ip>"));
26369
- break;
27262
+ if (action === "list" || action === "ls") {
27263
+ const client = await connect();
27264
+ if (!client) return;
27265
+ try {
27266
+ const reply = await client.blocklist();
27267
+ for (const entry of reply.protected) {
27268
+ console.log(` ${source_default.green("\u26CA")} ${source_default.white(entry)}`);
26370
27269
  }
26371
- console.log(source_default.green(` Removed ${opts.value} from allowlist`));
26372
- break;
26373
- default:
26374
- console.log(source_default.yellow(` Unknown action: ${action}`));
26375
- console.log(source_default.gray(" Available: list, add, remove"));
27270
+ console.log();
27271
+ console.log(source_default.gray(" Loopback, private ranges, the default gateway and the SSH client"));
27272
+ console.log(source_default.gray(" that started the daemon are always protected. Add more under"));
27273
+ console.log(source_default.gray(` [remediation] protected = [...] in ${PATHS.configFile}`));
27274
+ } catch (err) {
27275
+ console.log(` ${source_default.red("\u2717")} ${err.message}`);
27276
+ } finally {
27277
+ client.close();
27278
+ console.log();
27279
+ }
27280
+ return;
26376
27281
  }
27282
+ console.log(source_default.gray(` Edit ${PATHS.configFile}:`));
27283
+ console.log();
27284
+ console.log(source_default.gray(" [remediation]"));
27285
+ console.log(source_default.gray(` protected = ["${opts.value || "203.0.113.7/32"}"]`));
27286
+ console.log();
27287
+ console.log(source_default.gray(" then: threatcrush restart"));
26377
27288
  console.log();
26378
27289
  }
26379
27290
 
@@ -26381,11 +27292,11 @@ async function allowlistCommand(opts) {
26381
27292
  init_paths();
26382
27293
 
26383
27294
  // src/upgrade.ts
26384
- var import_node_child_process10 = require("child_process");
27295
+ var import_node_child_process11 = require("child_process");
26385
27296
  var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
26386
27297
  var defaultRunner = (cmd) => {
26387
27298
  try {
26388
- return (0, import_node_child_process10.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
27299
+ return (0, import_node_child_process11.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
26389
27300
  } catch {
26390
27301
  return null;
26391
27302
  }
@@ -26500,25 +27411,25 @@ ${source_default.dim(" C R U S H")}
26500
27411
  var API_URL8 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
26501
27412
  var PKG_NAME = "@profullstack/threatcrush";
26502
27413
  var DESKTOP_PKG_NAME = "@profullstack/threatcrush-desktop";
26503
- var INSTALL_CONFIG_PATH = (0, import_node_path22.join)((0, import_node_os8.homedir)(), ".threatcrush", "install.json");
27414
+ var INSTALL_CONFIG_PATH = (0, import_node_path23.join)((0, import_node_os8.homedir)(), ".threatcrush", "install.json");
26504
27415
  function detectPackageManager() {
26505
27416
  try {
26506
- const npmGlobal = (0, import_node_child_process11.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
27417
+ const npmGlobal = (0, import_node_child_process12.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
26507
27418
  if (npmGlobal.includes(PKG_NAME)) return "npm";
26508
27419
  } catch {
26509
27420
  }
26510
27421
  try {
26511
- (0, import_node_child_process11.execSync)("pnpm --version", { stdio: "pipe" });
27422
+ (0, import_node_child_process12.execSync)("pnpm --version", { stdio: "pipe" });
26512
27423
  return "pnpm";
26513
27424
  } catch {
26514
27425
  }
26515
27426
  try {
26516
- (0, import_node_child_process11.execSync)("yarn --version", { stdio: "pipe" });
27427
+ (0, import_node_child_process12.execSync)("yarn --version", { stdio: "pipe" });
26517
27428
  return "yarn";
26518
27429
  } catch {
26519
27430
  }
26520
27431
  try {
26521
- (0, import_node_child_process11.execSync)("bun --version", { stdio: "pipe" });
27432
+ (0, import_node_child_process12.execSync)("bun --version", { stdio: "pipe" });
26522
27433
  return "bun";
26523
27434
  } catch {
26524
27435
  }
@@ -26526,14 +27437,14 @@ function detectPackageManager() {
26526
27437
  }
26527
27438
  function readInstallConfig() {
26528
27439
  try {
26529
- return JSON.parse((0, import_node_fs32.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
27440
+ return JSON.parse((0, import_node_fs33.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
26530
27441
  } catch {
26531
27442
  return {};
26532
27443
  }
26533
27444
  }
26534
27445
  function packageLooksInstalled(pm, pkgName) {
26535
27446
  try {
26536
- const output = (0, import_node_child_process11.execSync)(globalListCommand(pm, pkgName), {
27447
+ const output = (0, import_node_child_process12.execSync)(globalListCommand(pm, pkgName), {
26537
27448
  encoding: "utf-8",
26538
27449
  stdio: ["pipe", "pipe", "pipe"]
26539
27450
  });
@@ -26604,7 +27515,7 @@ async function refreshDaemonAfterUpgrade() {
26604
27515
  }
26605
27516
  function execQuiet(cmd) {
26606
27517
  try {
26607
- return (0, import_node_child_process11.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
27518
+ return (0, import_node_child_process12.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
26608
27519
  } catch {
26609
27520
  return null;
26610
27521
  }
@@ -26752,7 +27663,7 @@ program2.command("uninstall-service").description("Remove the threatcrushd syste
26752
27663
  program2.command("logs").description("Tail daemon logs").action(async () => {
26753
27664
  console.log(LOGO2);
26754
27665
  const logPath = PATHS.logFile;
26755
- if (!(0, import_node_fs32.existsSync)(logPath)) {
27666
+ if (!(0, import_node_fs33.existsSync)(logPath)) {
26756
27667
  console.log(source_default.yellow(` No log file found at ${logPath}`));
26757
27668
  console.log(source_default.dim(" Start the daemon first with `threatcrush start`\n"));
26758
27669
  return;
@@ -26760,7 +27671,7 @@ program2.command("logs").description("Tail daemon logs").action(async () => {
26760
27671
  console.log(source_default.green(` Tailing ${logPath}...
26761
27672
  `));
26762
27673
  console.log(source_default.gray(" Press Ctrl+C to stop\n"));
26763
- (0, import_node_child_process11.execSync)(`tail -f ${logPath}`, { stdio: "inherit" });
27674
+ (0, import_node_child_process12.execSync)(`tail -f ${logPath}`, { stdio: "inherit" });
26764
27675
  });
26765
27676
  program2.command("activate").description("Activate your license key").action(async () => {
26766
27677
  console.log(LOGO2);
@@ -26807,7 +27718,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
26807
27718
  for (const cmd of commands2) {
26808
27719
  console.log(source_default.green(` \u2192 ${cmd}
26809
27720
  `));
26810
- (0, import_node_child_process11.execSync)(cmd, { stdio: "inherit" });
27721
+ (0, import_node_child_process12.execSync)(cmd, { stdio: "inherit" });
26811
27722
  }
26812
27723
  console.log(source_default.green("\n \u2713 Modules updated successfully!\n"));
26813
27724
  await reportIfStillStale();
@@ -26832,7 +27743,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
26832
27743
  for (const cmd of commands) {
26833
27744
  console.log(source_default.green(` \u2192 ${cmd}
26834
27745
  `));
26835
- (0, import_node_child_process11.execSync)(cmd, { stdio: "inherit" });
27746
+ (0, import_node_child_process12.execSync)(cmd, { stdio: "inherit" });
26836
27747
  }
26837
27748
  console.log(source_default.green("\n \u2713 ThreatCrush updated successfully!\n"));
26838
27749
  if (installMode === "desktop") {
@@ -26882,7 +27793,7 @@ program2.command("remove").description("Uninstall ThreatCrush and the installed
26882
27793
  for (const cmd of commands) {
26883
27794
  console.log(source_default.green(` \u2192 ${cmd}
26884
27795
  `));
26885
- (0, import_node_child_process11.execSync)(cmd, { stdio: "inherit" });
27796
+ (0, import_node_child_process12.execSync)(cmd, { stdio: "inherit" });
26886
27797
  }
26887
27798
  console.log(source_default.green("\n \u2713 ThreatCrush has been uninstalled.\n"));
26888
27799
  console.log(source_default.dim(" We're sorry to see you go! \u{1F44B}\n"));
@@ -26959,10 +27870,10 @@ storeCmd.command("search <query>").description("Search for modules in the store"
26959
27870
  });
26960
27871
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
26961
27872
  console.log(LOGO2);
26962
- const configPath = (0, import_node_path22.join)((0, import_node_os8.homedir)(), ".threatcrush", "config.json");
27873
+ const configPath = (0, import_node_path23.join)((0, import_node_os8.homedir)(), ".threatcrush", "config.json");
26963
27874
  let email = "";
26964
27875
  try {
26965
- const config = JSON.parse((0, import_node_fs32.readFileSync)(configPath, "utf-8"));
27876
+ const config = JSON.parse((0, import_node_fs33.readFileSync)(configPath, "utf-8"));
26966
27877
  email = config.email || "";
26967
27878
  } catch {
26968
27879
  }
@@ -26979,9 +27890,9 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
26979
27890
  return;
26980
27891
  }
26981
27892
  try {
26982
- const dir = (0, import_node_path22.join)((0, import_node_os8.homedir)(), ".threatcrush");
26983
- if (!(0, import_node_fs32.existsSync)(dir)) (0, import_node_fs32.mkdirSync)(dir, { recursive: true });
26984
- (0, import_node_fs32.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
27893
+ const dir = (0, import_node_path23.join)((0, import_node_os8.homedir)(), ".threatcrush");
27894
+ if (!(0, import_node_fs33.existsSync)(dir)) (0, import_node_fs33.mkdirSync)(dir, { recursive: true });
27895
+ (0, import_node_fs33.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
26985
27896
  console.log(source_default.dim(` Saved email to ${configPath}`));
26986
27897
  } catch {
26987
27898
  }