@profullstack/threatcrush 0.13.37 → 0.13.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6054,12 +6054,12 @@ var init_buffer = __esm({
6054
6054
  }
6055
6055
  /** Whole buffer as plain text. */
6056
6056
  toText(trimEnd2 = true) {
6057
- const rows = [];
6057
+ const rows2 = [];
6058
6058
  for (let y = 0; y < this.height; y++) {
6059
6059
  const r = this.rowText(y);
6060
- rows.push(trimEnd2 ? r.replace(/\s+$/, "") : r);
6060
+ rows2.push(trimEnd2 ? r.replace(/\s+$/, "") : r);
6061
6061
  }
6062
- return rows.join("\n");
6062
+ return rows2.join("\n");
6063
6063
  }
6064
6064
  };
6065
6065
  }
@@ -6158,7 +6158,7 @@ function encodeRows(buffer, options = {}) {
6158
6158
  const width = buffer.width;
6159
6159
  const row = new FrameBuffer(width, 1);
6160
6160
  const blank = new FrameBuffer(-1, -1);
6161
- const rows = [];
6161
+ const rows2 = [];
6162
6162
  for (let y = 0; y < buffer.height; y++) {
6163
6163
  const from = y * width;
6164
6164
  row.chars.set(buffer.chars.subarray(from, from + width));
@@ -6167,9 +6167,9 @@ function encodeRows(buffer, options = {}) {
6167
6167
  row.attrs.set(buffer.attrs.subarray(from, from + width));
6168
6168
  encoder.invalidateState();
6169
6169
  const line2 = encoder.encode(blank, row, true).output.replace(`${CSI}1;1H`, "");
6170
- rows.push(line2.replace(/[ ]+$/, "") + `${CSI}0m`);
6170
+ rows2.push(line2.replace(/[ ]+$/, "") + `${CSI}0m`);
6171
6171
  }
6172
- return rows;
6172
+ return rows2;
6173
6173
  }
6174
6174
  var GAP_MERGE, Encoder;
6175
6175
  var init_diff = __esm({
@@ -6874,22 +6874,22 @@ var init_terminal = __esm({
6874
6874
  * framebuffer is sized from.
6875
6875
  */
6876
6876
  viewportRect() {
6877
- const { columns, rows } = this.size();
6877
+ const { columns, rows: rows2 } = this.size();
6878
6878
  const v = this.viewportMode;
6879
6879
  if (v.mode === "inline") {
6880
- return { x: 0, y: 0, width: columns, height: Math.max(1, Math.min(v.height, rows)) };
6880
+ return { x: 0, y: 0, width: columns, height: Math.max(1, Math.min(v.height, rows2)) };
6881
6881
  }
6882
6882
  if (v.mode === "fixed") {
6883
6883
  const x = Math.max(0, Math.min(v.x, Math.max(0, columns - 1)));
6884
- const y = Math.max(0, Math.min(v.y, Math.max(0, rows - 1)));
6884
+ const y = Math.max(0, Math.min(v.y, Math.max(0, rows2 - 1)));
6885
6885
  return {
6886
6886
  x,
6887
6887
  y,
6888
6888
  width: Math.max(0, Math.min(v.width, columns - x)),
6889
- height: Math.max(0, Math.min(v.height, rows - y))
6889
+ height: Math.max(0, Math.min(v.height, rows2 - y))
6890
6890
  };
6891
6891
  }
6892
- return { x: 0, y: 0, width: columns, height: rows };
6892
+ return { x: 0, y: 0, width: columns, height: rows2 };
6893
6893
  }
6894
6894
  write(data) {
6895
6895
  if (data.length === 0)
@@ -8071,9 +8071,9 @@ var init_braille = __esm({
8071
8071
  cols;
8072
8072
  rows;
8073
8073
  dots;
8074
- constructor(cols, rows) {
8074
+ constructor(cols, rows2) {
8075
8075
  this.cols = Math.max(0, cols | 0);
8076
- this.rows = Math.max(0, rows | 0);
8076
+ this.rows = Math.max(0, rows2 | 0);
8077
8077
  this.width = this.cols * 2;
8078
8078
  this.height = this.rows * 4;
8079
8079
  this.dots = new Uint8Array(this.cols * this.rows);
@@ -8794,11 +8794,11 @@ function drawKeyValues(surface, options) {
8794
8794
  if (surface.empty)
8795
8795
  return;
8796
8796
  const theme = surface.theme;
8797
- const rows = options.rows;
8797
+ const rows2 = options.rows;
8798
8798
  const gap = options.gap ?? 1;
8799
- const labelWidth = options.labelWidth ?? Math.min(Math.max(0, ...rows.map((r) => stringWidth(r.label))) + 1, Math.max(4, Math.floor(surface.width * 0.6)));
8800
- for (let i = 0; i < rows.length && i < surface.height; i++) {
8801
- const row = rows[i];
8799
+ const labelWidth = options.labelWidth ?? Math.min(Math.max(0, ...rows2.map((r) => stringWidth(r.label))) + 1, Math.max(4, Math.floor(surface.width * 0.6)));
8800
+ for (let i = 0; i < rows2.length && i < surface.height; i++) {
8801
+ const row = rows2[i];
8802
8802
  surface.text(0, i, fit(truncate(row.label, labelWidth), labelWidth), {
8803
8803
  fg: row.labelColor ?? options.labelColor ?? theme.muted,
8804
8804
  bg: options.background
@@ -18519,24 +18519,24 @@ function emojiPickerItems(state, recent = []) {
18519
18519
  function tabIds(recent) {
18520
18520
  return [...recent.length ? [EMOJI_RECENT] : [], ...emojiGroups().map((_, i) => i)];
18521
18521
  }
18522
- function settle(state, count, columns, rows) {
18522
+ function settle(state, count, columns, rows2) {
18523
18523
  const index = count === 0 ? 0 : Math.max(0, Math.min(state.index, count - 1));
18524
18524
  const row = Math.floor(index / columns);
18525
- const lastOffset = Math.max(0, Math.ceil(count / columns) - rows);
18525
+ const lastOffset = Math.max(0, Math.ceil(count / columns) - rows2);
18526
18526
  let offset = Math.max(0, Math.min(state.offset, lastOffset));
18527
18527
  if (row < offset)
18528
18528
  offset = row;
18529
- if (row >= offset + rows)
18530
- offset = row - rows + 1;
18529
+ if (row >= offset + rows2)
18530
+ offset = row - rows2 + 1;
18531
18531
  return { ...state, index, offset };
18532
18532
  }
18533
18533
  function emojiPickerKey(state, event, options = {}) {
18534
18534
  const recent = options.recent ?? [];
18535
18535
  const columns = options.columns ?? 10;
18536
- const rows = options.rows ?? 7;
18536
+ const rows2 = options.rows ?? 7;
18537
18537
  const items = emojiPickerItems(state, recent);
18538
18538
  const move = (next) => ({
18539
- state: settle({ ...state, ...next }, emojiPickerItems({ ...state, ...next }, recent).length, columns, rows)
18539
+ state: settle({ ...state, ...next }, emojiPickerItems({ ...state, ...next }, recent).length, columns, rows2)
18540
18540
  });
18541
18541
  const switchTab = (step) => {
18542
18542
  const ids = tabIds(recent);
@@ -18558,9 +18558,9 @@ function emojiPickerKey(state, event, options = {}) {
18558
18558
  case "down":
18559
18559
  return move({ index: state.index + columns });
18560
18560
  case "pageup":
18561
- return move({ index: state.index - columns * rows, offset: state.offset - rows });
18561
+ return move({ index: state.index - columns * rows2, offset: state.offset - rows2 });
18562
18562
  case "pagedown":
18563
- return move({ index: state.index + columns * rows, offset: state.offset + rows });
18563
+ return move({ index: state.index + columns * rows2, offset: state.offset + rows2 });
18564
18564
  case "home":
18565
18565
  return move({ index: 0 });
18566
18566
  case "end":
@@ -18582,15 +18582,15 @@ function emojiPickerKey(state, event, options = {}) {
18582
18582
  }
18583
18583
  return { state };
18584
18584
  }
18585
- function emojiPickerSize(columns = 10, rows = 7) {
18586
- return { width: columns * 3 + 4, height: rows + 6 };
18585
+ function emojiPickerSize(columns = 10, rows2 = 7) {
18586
+ return { width: columns * 3 + 4, height: rows2 + 6 };
18587
18587
  }
18588
18588
  function drawEmojiPicker(root, options) {
18589
18589
  const theme = root.theme;
18590
18590
  const recent = options.recent ?? [];
18591
18591
  const columns = Math.max(4, Math.min(options.columns ?? 10, Math.floor((root.width - 4) / 3)));
18592
- const rows = Math.max(2, Math.min(options.rows ?? 7, root.height - 6));
18593
- const size = emojiPickerSize(columns, rows);
18592
+ const rows2 = Math.max(2, Math.min(options.rows ?? 7, root.height - 6));
18593
+ const size = emojiPickerSize(columns, rows2);
18594
18594
  const x = options.x ?? Math.max(0, Math.floor((root.width - size.width) / 2));
18595
18595
  const y = options.y ?? Math.max(0, Math.floor((root.height - size.height) / 2));
18596
18596
  const state = options.state;
@@ -18629,7 +18629,7 @@ function drawEmojiPicker(root, options) {
18629
18629
  const empty = query.trim() ? "No emoji match." : state.tab === EMOJI_RECENT ? "Nothing picked yet." : "";
18630
18630
  inner.text(Math.max(1, Math.floor((inner.width - stringWidth(empty)) / 2)), gridTop + 1, empty, { fg: theme.muted });
18631
18631
  }
18632
- for (let r = 0; r < rows; r++) {
18632
+ for (let r = 0; r < rows2; r++) {
18633
18633
  for (let c = 0; c < columns; c++) {
18634
18634
  const i = (state.offset + r) * columns + c;
18635
18635
  const e = items[i];
@@ -18642,13 +18642,13 @@ function drawEmojiPicker(root, options) {
18642
18642
  }
18643
18643
  }
18644
18644
  const totalRows = Math.ceil(items.length / columns);
18645
- if (totalRows > rows) {
18646
- const pos = Math.round(state.offset / Math.max(1, totalRows - rows) * (rows - 1));
18647
- for (let r = 0; r < rows; r++)
18645
+ if (totalRows > rows2) {
18646
+ const pos = Math.round(state.offset / Math.max(1, totalRows - rows2) * (rows2 - 1));
18647
+ for (let r = 0; r < rows2; r++)
18648
18648
  inner.text(inner.width - 1, gridTop + r, r === pos ? "\u2503" : "\u2502", { fg: r === pos ? theme.accent : theme.border });
18649
18649
  }
18650
18650
  const current = items[state.index];
18651
- const footerY = gridTop + rows;
18651
+ const footerY = gridTop + rows2;
18652
18652
  if (current) {
18653
18653
  const label = `:${current.shortcode.replace(/^oe_/, "")}: ${current.name}`;
18654
18654
  inner.text(1, footerY, truncate(label, inner.width - 2), { fg: theme.muted });
@@ -18658,9 +18658,9 @@ function drawEmojiPicker(root, options) {
18658
18658
  return {
18659
18659
  box: outer.hitRect(),
18660
18660
  tabs,
18661
- grid: { x: origin.x + 1, y: origin.y + gridTop, width: columns * 3, height: rows },
18661
+ grid: { x: origin.x + 1, y: origin.y + gridTop, width: columns * 3, height: rows2 },
18662
18662
  columns,
18663
- rows
18663
+ rows: rows2
18664
18664
  };
18665
18665
  }
18666
18666
  function emojiPickerIndexAt(state, layout, x, y) {
@@ -18735,8 +18735,8 @@ var init_markdown = __esm({
18735
18735
  text(value) {
18736
18736
  this.add(markdownText(toSpanLines(value).map((line2) => line2.map((s) => s.text).join("")).join("\n")));
18737
18737
  }
18738
- values(rows) {
18739
- this.add(rows.filter((row) => row.label || row.value).map(({ label, value }) => {
18738
+ values(rows2) {
18739
+ this.add(rows2.filter((row) => row.label || row.value).map(({ label, value }) => {
18740
18740
  const key = markdownText(label.replace(/:\s*$/, "")).replace(/\s*\n\s*/g, " ");
18741
18741
  const content = markdownText(value).replace(/\n/g, "\n ");
18742
18742
  return key ? `- **${key}:** ${content}` : `- ${content}`;
@@ -19040,9 +19040,9 @@ var init_ui = __esm({
19040
19040
  return this.add((s) => drawSpinner(s, { ...options, elapsed, frames, doneGlyph }), this.sizeOf(options, "auto", 1));
19041
19041
  }
19042
19042
  /** Aligned label/value pairs. */
19043
- keyValues(rows, options = {}) {
19044
- this.summary?.values(rows);
19045
- return this.add((s) => drawKeyValues(s, { ...options, rows }), this.sizeOf(options, "auto", rows.length));
19043
+ keyValues(rows2, options = {}) {
19044
+ this.summary?.values(rows2);
19045
+ return this.add((s) => drawKeyValues(s, { ...options, rows: rows2 }), this.sizeOf(options, "auto", rows2.length));
19046
19046
  }
19047
19047
  // ------------------------------------------------------------------ data
19048
19048
  /**
@@ -19129,8 +19129,8 @@ var init_ui = __esm({
19129
19129
  meters(items, options = {}) {
19130
19130
  this.summary?.values(items.map((item) => ({ label: item.label ?? "Value", value: item.text ?? `${Math.round((item.max ? item.value / item.max : item.value) * 100)}%` })));
19131
19131
  const columns = Math.max(1, options.columns ?? 1);
19132
- const rows = Math.ceil(items.length / columns);
19133
- return this.add((s) => drawMeters(s, { ...options, items }), this.sizeOf(options, "auto", rows));
19132
+ const rows2 = Math.ceil(items.length / columns);
19133
+ return this.add((s) => drawMeters(s, { ...options, items }), this.sizeOf(options, "auto", rows2));
19134
19134
  }
19135
19135
  progress(options) {
19136
19136
  this.summary?.values([{ label: options.label ?? "Progress", value: options.showCount ? `${options.value}/${options.max ?? 1}` : `${Math.round(options.value / (options.max ?? 1) * 100)}%` }]);
@@ -21010,13 +21010,13 @@ function cometPhase(ip, now, periodMs = 2400) {
21010
21010
  function liveOrigins(data, now, liveMs = 6e5, max = 24) {
21011
21011
  return data.origins.filter((o) => now - Date.parse(o.lastSeen) <= liveMs).sort((a, b) => SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity] || b.count - a.count).slice(0, max);
21012
21012
  }
21013
- function renderCells(data, cols, rows, opts = {}) {
21013
+ function renderCells(data, cols, rows2, opts = {}) {
21014
21014
  const now = opts.now ?? Date.now();
21015
21015
  const W = cols * 2;
21016
- const H = rows * 4;
21017
- const mask = new Uint8Array(cols * rows);
21018
- const tint = new Array(cols * rows);
21019
- const rank = new Int8Array(cols * rows).fill(-1);
21016
+ const H = rows2 * 4;
21017
+ const mask = new Uint8Array(cols * rows2);
21018
+ const tint = new Array(cols * rows2);
21019
+ const rank = new Int8Array(cols * rows2).fill(-1);
21020
21020
  const dot = (px, py, color, r = -1) => {
21021
21021
  const x = Math.round(px);
21022
21022
  const y = Math.round(py);
@@ -21044,7 +21044,7 @@ function renderCells(data, cols, rows, opts = {}) {
21044
21044
  }
21045
21045
  }
21046
21046
  const cells = [];
21047
- for (let r = 0; r < rows; r++) {
21047
+ for (let r = 0; r < rows2; r++) {
21048
21048
  const row = [];
21049
21049
  for (let c = 0; c < cols; c++) {
21050
21050
  const i = r * cols + c;
@@ -21055,7 +21055,7 @@ function renderCells(data, cols, rows, opts = {}) {
21055
21055
  const put2 = (lat, lon, ch, fg) => {
21056
21056
  const p = project(lat, lon);
21057
21057
  const c = Math.min(cols - 1, Math.floor(p.x * cols));
21058
- const r = Math.min(rows - 1, Math.floor(p.y * rows));
21058
+ const r = Math.min(rows2 - 1, Math.floor(p.y * rows2));
21059
21059
  cells[r][c] = { ch, fg, bold: true };
21060
21060
  return { c, r };
21061
21061
  };
@@ -21426,20 +21426,20 @@ function mapBody(ui, state, theme, opts) {
21426
21426
  const W = surface.width;
21427
21427
  const H = surface.height;
21428
21428
  let cols = W;
21429
- let rows = Math.round(cols / MAP_ASPECT / 2);
21430
- if (rows > H) {
21431
- rows = H;
21432
- cols = Math.min(W, Math.round(rows * 2 * MAP_ASPECT));
21429
+ let rows2 = Math.round(cols / MAP_ASPECT / 2);
21430
+ if (rows2 > H) {
21431
+ rows2 = H;
21432
+ cols = Math.min(W, Math.round(rows2 * 2 * MAP_ASPECT));
21433
21433
  }
21434
21434
  const x0 = Math.floor((W - cols) / 2);
21435
- const y0 = Math.floor((H - rows) / 2);
21435
+ const y0 = Math.floor((H - rows2) / 2);
21436
21436
  if (overlay?.enabled) {
21437
- surface.fillRect(x0, y0, cols, rows, { bg: hex(MAP_COLORS.ocean) }, 32);
21438
- overlay.place({ col: surface.rect.x + x0, row: surface.rect.y + y0, cols, rows });
21437
+ surface.fillRect(x0, y0, cols, rows2, { bg: hex(MAP_COLORS.ocean) }, 32);
21438
+ overlay.place({ col: surface.rect.x + x0, row: surface.rect.y + y0, cols, rows: rows2 });
21439
21439
  } else {
21440
21440
  overlay?.place(null);
21441
- const cells = renderCells(data, cols, rows, { now });
21442
- for (let y = 0; y < rows; y++) {
21441
+ const cells = renderCells(data, cols, rows2, { now });
21442
+ for (let y = 0; y < rows2; y++) {
21443
21443
  for (let x = 0; x < cols; x++) {
21444
21444
  const c = cells[y][x];
21445
21445
  if (c.ch !== " ") surface.char(x0 + x, y0 + y, c.ch, { fg: hex(c.fg), attrs: c.bold ? Attr.Bold : Attr.None });
@@ -22280,7 +22280,7 @@ async function startDashboard(options = {}) {
22280
22280
  quitKeys: []
22281
22281
  });
22282
22282
  let state = { ...initialState(), view: options.view ?? "dashboard" };
22283
- const dispatch = (action) => {
22283
+ const dispatch2 = (action) => {
22284
22284
  state = reducer(state, action);
22285
22285
  app.invalidate();
22286
22286
  };
@@ -22302,7 +22302,7 @@ async function startDashboard(options = {}) {
22302
22302
  const copyText = (text) => {
22303
22303
  if (!text) return;
22304
22304
  const result = copyToClipboard(text);
22305
- dispatch({ type: "notice", text: describeCopy(result), tone: result.via.length > 0 || result.file ? "ok" : "error" });
22305
+ dispatch2({ type: "notice", text: describeCopy(result), tone: result.via.length > 0 || result.file ? "ok" : "error" });
22306
22306
  };
22307
22307
  let client = null;
22308
22308
  let stopped = false;
@@ -22327,19 +22327,19 @@ async function startDashboard(options = {}) {
22327
22327
  client = null;
22328
22328
  };
22329
22329
  if (options.demo) {
22330
- dispatch({ type: "connection_lost", label: "demo mode \u2014 canned events, no daemon" });
22330
+ dispatch2({ type: "connection_lost", label: "demo mode \u2014 canned events, no daemon" });
22331
22331
  let i = 0;
22332
- every(900, () => dispatch({ type: "event", event: demoEvent(i++) }));
22332
+ every(900, () => dispatch2({ type: "event", event: demoEvent(i++) }));
22333
22333
  } else {
22334
22334
  const onEvent = (event) => {
22335
- if (!stopped) dispatch({ type: "event", event });
22335
+ if (!stopped) dispatch2({ type: "event", event });
22336
22336
  if (!stopped && event.module === "firewall-rules") void refreshBans();
22337
22337
  };
22338
22338
  refreshBans = async () => {
22339
22339
  if (!client || stopped) return;
22340
22340
  try {
22341
22341
  const reply = await client.blocklist();
22342
- dispatch({ type: "blocklist", reply });
22342
+ dispatch2({ type: "blocklist", reply });
22343
22343
  } catch {
22344
22344
  }
22345
22345
  };
@@ -22347,9 +22347,9 @@ async function startDashboard(options = {}) {
22347
22347
  if (!client || stopped) return;
22348
22348
  try {
22349
22349
  const status = await client.status();
22350
- dispatch({ type: "connected", label: `daemon pid ${status.pid}`, status });
22350
+ dispatch2({ type: "connected", label: `daemon pid ${status.pid}`, status });
22351
22351
  const top = await client.topSources(8).catch(() => []);
22352
- dispatch({ type: "top", top });
22352
+ dispatch2({ type: "top", top });
22353
22353
  await refreshBans();
22354
22354
  } catch {
22355
22355
  try {
@@ -22357,18 +22357,18 @@ async function startDashboard(options = {}) {
22357
22357
  } catch {
22358
22358
  }
22359
22359
  client = null;
22360
- dispatch({ type: "connection_lost", label: "daemon went away \u2014 retrying" });
22360
+ dispatch2({ type: "connection_lost", label: "daemon went away \u2014 retrying" });
22361
22361
  }
22362
22362
  };
22363
22363
  const connect2 = async () => {
22364
22364
  if (client || stopped) return;
22365
22365
  if (!IpcClient.isDaemonRunning()) {
22366
22366
  if (state.connection !== "lost") {
22367
- dispatch({ type: "connection_lost", label: `no daemon at ${PATHS.socket}` });
22367
+ dispatch2({ type: "connection_lost", label: `no daemon at ${PATHS.socket}` });
22368
22368
  }
22369
22369
  return;
22370
22370
  }
22371
- dispatch({ type: "searching", label: "connecting to threatcrushd..." });
22371
+ dispatch2({ type: "searching", label: "connecting to threatcrushd..." });
22372
22372
  const next = new IpcClient({ onEvent });
22373
22373
  try {
22374
22374
  await next.connect();
@@ -22376,11 +22376,11 @@ async function startDashboard(options = {}) {
22376
22376
  await next.subscribe(["event", "module"]).catch(() => {
22377
22377
  });
22378
22378
  client = next;
22379
- dispatch({ type: "connected", label: `daemon pid ${status.pid}`, status });
22379
+ dispatch2({ type: "connected", label: `daemon pid ${status.pid}`, status });
22380
22380
  try {
22381
22381
  const recent = await next.recentEvents(100);
22382
22382
  for (const event of recent) {
22383
- dispatch({ type: "event", event: { ...event, timestamp: new Date(event.timestamp) } });
22383
+ dispatch2({ type: "event", event: { ...event, timestamp: new Date(event.timestamp) } });
22384
22384
  }
22385
22385
  } catch {
22386
22386
  }
@@ -22390,7 +22390,7 @@ async function startDashboard(options = {}) {
22390
22390
  next.close();
22391
22391
  } catch {
22392
22392
  }
22393
- dispatch({ type: "connection_lost", label: `daemon unreachable: ${err.message}` });
22393
+ dispatch2({ type: "connection_lost", label: `daemon unreachable: ${err.message}` });
22394
22394
  }
22395
22395
  };
22396
22396
  void connect2();
@@ -22401,7 +22401,7 @@ async function startDashboard(options = {}) {
22401
22401
  void poll();
22402
22402
  });
22403
22403
  }
22404
- every(1e3, () => dispatch({ type: "tick" }));
22404
+ every(1e3, () => dispatch2({ type: "tick" }));
22405
22405
  every(100, () => {
22406
22406
  if (state.view === "map") app.invalidate();
22407
22407
  });
@@ -22413,26 +22413,26 @@ async function startDashboard(options = {}) {
22413
22413
  const ip = selectedIp(state);
22414
22414
  if (state.busy) return;
22415
22415
  if (!ip) {
22416
- dispatch({ type: "notice", text: "select a source first (tab)", tone: "error" });
22416
+ dispatch2({ type: "notice", text: "select a source first (tab)", tone: "error" });
22417
22417
  return;
22418
22418
  }
22419
22419
  if (!client) {
22420
- dispatch({ type: "notice", text: "no daemon \u2014 cannot ban", tone: "error" });
22420
+ dispatch2({ type: "notice", text: "no daemon \u2014 cannot ban", tone: "error" });
22421
22421
  return;
22422
22422
  }
22423
22423
  if (isBanned(state, ip)) {
22424
- dispatch({ type: "notice", text: `${ip} is already banned`, tone: "error" });
22424
+ dispatch2({ type: "notice", text: `${ip} is already banned`, tone: "error" });
22425
22425
  return;
22426
22426
  }
22427
- dispatch({ type: "busy", busy: true });
22427
+ dispatch2({ type: "busy", busy: true });
22428
22428
  try {
22429
22429
  const entry = await client.block(ip, "banned from dashboard");
22430
22430
  const ttl = formatDuration(Math.round((entry.expires_at - Date.now()) / 1e3));
22431
- dispatch({ type: "notice", text: `banned ${ip} for ${ttl} (#${entry.strikes})`, tone: "ok" });
22431
+ dispatch2({ type: "notice", text: `banned ${ip} for ${ttl} (#${entry.strikes})`, tone: "ok" });
22432
22432
  } catch (err) {
22433
- dispatch({ type: "notice", text: `ban failed: ${err.message}`, tone: "error" });
22433
+ dispatch2({ type: "notice", text: `ban failed: ${err.message}`, tone: "error" });
22434
22434
  } finally {
22435
- dispatch({ type: "busy", busy: false });
22435
+ dispatch2({ type: "busy", busy: false });
22436
22436
  await refreshBans();
22437
22437
  }
22438
22438
  };
@@ -22440,29 +22440,29 @@ async function startDashboard(options = {}) {
22440
22440
  const ip = selectedIp(state);
22441
22441
  if (state.busy) return;
22442
22442
  if (!ip) {
22443
- dispatch({ type: "notice", text: "select a source first (tab)", tone: "error" });
22443
+ dispatch2({ type: "notice", text: "select a source first (tab)", tone: "error" });
22444
22444
  return;
22445
22445
  }
22446
22446
  if (!client) {
22447
- dispatch({ type: "notice", text: "no daemon \u2014 cannot unban", tone: "error" });
22447
+ dispatch2({ type: "notice", text: "no daemon \u2014 cannot unban", tone: "error" });
22448
22448
  return;
22449
22449
  }
22450
- dispatch({ type: "busy", busy: true });
22450
+ dispatch2({ type: "busy", busy: true });
22451
22451
  try {
22452
22452
  await client.unblock(ip);
22453
- dispatch({ type: "notice", text: `unbanned ${ip}`, tone: "ok" });
22453
+ dispatch2({ type: "notice", text: `unbanned ${ip}`, tone: "ok" });
22454
22454
  } catch (err) {
22455
- dispatch({ type: "notice", text: `unban failed: ${err.message}`, tone: "error" });
22455
+ dispatch2({ type: "notice", text: `unban failed: ${err.message}`, tone: "error" });
22456
22456
  } finally {
22457
- dispatch({ type: "busy", busy: false });
22457
+ dispatch2({ type: "busy", busy: false });
22458
22458
  await refreshBans();
22459
22459
  }
22460
22460
  };
22461
22461
  app.on("key", (event) => {
22462
22462
  switch (event.key) {
22463
22463
  case "escape":
22464
- if (state.sourceFilter) dispatch({ type: "clear_source_filter" });
22465
- else if (state.moduleFilter) dispatch({ type: "clear_module_filter" });
22464
+ if (state.sourceFilter) dispatch2({ type: "clear_source_filter" });
22465
+ else if (state.moduleFilter) dispatch2({ type: "clear_module_filter" });
22466
22466
  else quit();
22467
22467
  break;
22468
22468
  case "q":
@@ -22470,7 +22470,7 @@ async function startDashboard(options = {}) {
22470
22470
  quit();
22471
22471
  break;
22472
22472
  case "m":
22473
- dispatch({ type: "toggle_view" });
22473
+ dispatch2({ type: "toggle_view" });
22474
22474
  if (state.view !== "map") {
22475
22475
  overlay.hide();
22476
22476
  app.redraw();
@@ -22478,27 +22478,27 @@ async function startDashboard(options = {}) {
22478
22478
  break;
22479
22479
  case "enter":
22480
22480
  case "return":
22481
- if (state.focus === "modules") dispatch({ type: "toggle_module_filter" });
22482
- else if (state.focus === "threats" || state.focus === "bans") dispatch({ type: "toggle_source_filter" });
22481
+ if (state.focus === "modules") dispatch2({ type: "toggle_module_filter" });
22482
+ else if (state.focus === "threats" || state.focus === "bans") dispatch2({ type: "toggle_source_filter" });
22483
22483
  break;
22484
22484
  case "p":
22485
22485
  case "space":
22486
- dispatch({ type: "pause" });
22486
+ dispatch2({ type: "pause" });
22487
22487
  break;
22488
22488
  case "r":
22489
- dispatch({ type: "reset" });
22489
+ dispatch2({ type: "reset" });
22490
22490
  break;
22491
22491
  case "n":
22492
- dispatch({ type: "toggle_noise" });
22492
+ dispatch2({ type: "toggle_noise" });
22493
22493
  break;
22494
22494
  case "c":
22495
- dispatch({ type: "toggle_cron" });
22495
+ dispatch2({ type: "toggle_cron" });
22496
22496
  break;
22497
22497
  case "y":
22498
22498
  copyText(state.notice?.tone === "error" ? state.notice.text : state.lastError ?? state.notice?.text ?? "");
22499
22499
  break;
22500
22500
  case "tab":
22501
- dispatch({ type: "focus_next" });
22501
+ dispatch2({ type: "focus_next" });
22502
22502
  break;
22503
22503
  case "b":
22504
22504
  void banSelected();
@@ -22508,23 +22508,23 @@ async function startDashboard(options = {}) {
22508
22508
  break;
22509
22509
  case "up":
22510
22510
  case "k":
22511
- if (state.focus === "feed") dispatch({ type: "scroll", delta: 1 });
22512
- else dispatch({ type: "select", delta: -1 });
22511
+ if (state.focus === "feed") dispatch2({ type: "scroll", delta: 1 });
22512
+ else dispatch2({ type: "select", delta: -1 });
22513
22513
  break;
22514
22514
  case "down":
22515
22515
  case "j":
22516
- if (state.focus === "feed") dispatch({ type: "scroll", delta: -1 });
22517
- else dispatch({ type: "select", delta: 1 });
22516
+ if (state.focus === "feed") dispatch2({ type: "scroll", delta: -1 });
22517
+ else dispatch2({ type: "select", delta: 1 });
22518
22518
  break;
22519
22519
  case "pageup":
22520
- dispatch({ type: "scroll", delta: 10 });
22520
+ dispatch2({ type: "scroll", delta: 10 });
22521
22521
  break;
22522
22522
  case "pagedown":
22523
- dispatch({ type: "scroll", delta: -10 });
22523
+ dispatch2({ type: "scroll", delta: -10 });
22524
22524
  break;
22525
22525
  case "end":
22526
22526
  case "g":
22527
- dispatch({ type: "scroll_end" });
22527
+ dispatch2({ type: "scroll_end" });
22528
22528
  break;
22529
22529
  default:
22530
22530
  break;
@@ -22536,26 +22536,26 @@ async function startDashboard(options = {}) {
22536
22536
  demo: options.demo,
22537
22537
  map: mapData ? { data: mapData, geo, overlay } : void 0,
22538
22538
  onCopy: copyText,
22539
- onFeedScroll: (delta) => dispatch({ type: "scroll", delta: -delta }),
22539
+ onFeedScroll: (delta) => dispatch2({ type: "scroll", delta: -delta }),
22540
22540
  // One click focuses the panel, picks the row, and filters the feed to that
22541
22541
  // source — "what has this one IP done" in a single click. Clicking the
22542
22542
  // same row again clears the filter.
22543
22543
  onThreatSelect: (row) => {
22544
- dispatch({ type: "focus", focus: "threats" });
22545
- dispatch({ type: "select_at", index: row });
22546
- dispatch({ type: "toggle_source_filter" });
22544
+ dispatch2({ type: "focus", focus: "threats" });
22545
+ dispatch2({ type: "select_at", index: row });
22546
+ dispatch2({ type: "toggle_source_filter" });
22547
22547
  },
22548
22548
  onBanSelect: (row) => {
22549
- dispatch({ type: "focus", focus: "bans" });
22550
- dispatch({ type: "select_at", index: row });
22551
- dispatch({ type: "toggle_source_filter" });
22549
+ dispatch2({ type: "focus", focus: "bans" });
22550
+ dispatch2({ type: "select_at", index: row });
22551
+ dispatch2({ type: "toggle_source_filter" });
22552
22552
  },
22553
22553
  // One click on a module both selects it and pins the feed to it; a
22554
22554
  // second click on the same module releases the feed.
22555
22555
  onModuleSelect: (row) => {
22556
- dispatch({ type: "focus", focus: "modules" });
22557
- dispatch({ type: "select_at", index: row });
22558
- dispatch({ type: "toggle_module_filter" });
22556
+ dispatch2({ type: "focus", focus: "modules" });
22557
+ dispatch2({ type: "select_at", index: row });
22558
+ dispatch2({ type: "toggle_module_filter" });
22559
22559
  }
22560
22560
  });
22561
22561
  });
@@ -24746,8 +24746,8 @@ var source_default = chalk;
24746
24746
  // src/index.ts
24747
24747
  var import_readline = __toESM(require("readline"));
24748
24748
  var import_node_child_process22 = require("child_process");
24749
- var import_node_fs49 = require("fs");
24750
- var import_node_path36 = require("path");
24749
+ var import_node_fs51 = require("fs");
24750
+ var import_node_path37 = require("path");
24751
24751
  var import_node_os13 = require("os");
24752
24752
 
24753
24753
  // src/commands/monitor.ts
@@ -31643,6 +31643,9 @@ function loadConfig(configPath) {
31643
31643
  threat_feeds: parsed.threat_feeds,
31644
31644
  privileged: parsed.privileged,
31645
31645
  storage: parsed.storage,
31646
+ // TOML's `[abuse-reporter]` parses to a hyphenated key; expose it under
31647
+ // the JS-friendly name the rest of the daemon reads.
31648
+ abuse_reporter: parsed["abuse-reporter"] ?? parsed.abuse_reporter,
31646
31649
  license: parsed.license
31647
31650
  };
31648
31651
  } catch {
@@ -31676,7 +31679,16 @@ function generateDefaultConfig(detectedServices) {
31676
31679
  // Written out so the opt-out is discoverable; these are also the defaults
31677
31680
  // when the section is absent.
31678
31681
  cloud: { enabled: true, min_severity: "medium" },
31679
- update: { auto: true, interval: "6h", min_age: "2h" }
31682
+ update: { auto: true, interval: "6h", min_age: "2h" },
31683
+ // Reporting to shared reputation feeds (PRD 0015). On by default but inert
31684
+ // until a key is set: nothing is reported without ABUSEIPDB_API_KEY or the
31685
+ // key below, and only corroborated, handshake-verified sources ever are.
31686
+ "abuse-reporter": {
31687
+ enabled: true,
31688
+ mode: "live",
31689
+ destinations: ["abuseipdb"]
31690
+ // abuseipdb_api_key = "..." # prefer the ABUSEIPDB_API_KEY env/secret
31691
+ }
31680
31692
  };
31681
31693
  return import_toml.default.stringify(config);
31682
31694
  }
@@ -31775,18 +31787,18 @@ function tryDb() {
31775
31787
  function getRecentEvents(limit = 50) {
31776
31788
  const database = tryDb();
31777
31789
  if (!database) return [];
31778
- const rows = database.prepare(`
31790
+ const rows2 = database.prepare(`
31779
31791
  SELECT * FROM events ORDER BY timestamp DESC LIMIT ?
31780
31792
  `).all(limit);
31781
- return rows.map(rowToEvent);
31793
+ return rows2.map(rowToEvent);
31782
31794
  }
31783
31795
  function getModuleEvents(module2, limit = 50) {
31784
31796
  const database = tryDb();
31785
31797
  if (!database) return [];
31786
- const rows = database.prepare(`
31798
+ const rows2 = database.prepare(`
31787
31799
  SELECT * FROM events WHERE module = ? ORDER BY id DESC LIMIT ?
31788
31800
  `).all(module2, limit);
31789
- return rows.map(rowToEvent);
31801
+ return rows2.map(rowToEvent);
31790
31802
  }
31791
31803
  var RECENT_WINDOW = 2e5;
31792
31804
  function eventsEverRecorded(database) {
@@ -31853,6 +31865,16 @@ function pruneEvents(opts = {}) {
31853
31865
  }
31854
31866
  return deleted;
31855
31867
  }
31868
+ function getEventsForIp(ip, sinceMs, limit = 500) {
31869
+ const database = tryDb();
31870
+ if (!database) return [];
31871
+ const rows2 = database.prepare(`
31872
+ SELECT * FROM events
31873
+ WHERE source_ip = ? AND timestamp >= ?
31874
+ ORDER BY timestamp DESC LIMIT ?
31875
+ `).all(ip, new Date(sinceMs).toISOString(), limit);
31876
+ return rows2.map(rowToEvent);
31877
+ }
31856
31878
  function getModuleState(module2, key) {
31857
31879
  const database = db || initStateDB();
31858
31880
  const row = database.prepare(`SELECT value FROM module_state WHERE module = ? AND key = ?`).get(module2, key);
@@ -35584,27 +35606,27 @@ function normalizeName(name) {
35584
35606
  function editDistance(a, b, cap = 3) {
35585
35607
  if (a === b) return 0;
35586
35608
  if (Math.abs(a.length - b.length) > cap) return cap + 1;
35587
- const rows = [];
35609
+ const rows2 = [];
35588
35610
  for (let i = 0; i <= a.length; i += 1) {
35589
- rows.push(new Array(b.length + 1).fill(0));
35590
- rows[i][0] = i;
35611
+ rows2.push(new Array(b.length + 1).fill(0));
35612
+ rows2[i][0] = i;
35591
35613
  }
35592
- for (let j = 0; j <= b.length; j += 1) rows[0][j] = j;
35614
+ for (let j = 0; j <= b.length; j += 1) rows2[0][j] = j;
35593
35615
  for (let i = 1; i <= a.length; i += 1) {
35594
35616
  for (let j = 1; j <= b.length; j += 1) {
35595
35617
  const cost = a[i - 1] === b[j - 1] ? 0 : 1;
35596
35618
  let best = Math.min(
35597
- rows[i - 1][j] + 1,
35598
- rows[i][j - 1] + 1,
35599
- rows[i - 1][j - 1] + cost
35619
+ rows2[i - 1][j] + 1,
35620
+ rows2[i][j - 1] + 1,
35621
+ rows2[i - 1][j - 1] + cost
35600
35622
  );
35601
35623
  if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
35602
- best = Math.min(best, rows[i - 2][j - 2] + 1);
35624
+ best = Math.min(best, rows2[i - 2][j - 2] + 1);
35603
35625
  }
35604
- rows[i][j] = best;
35626
+ rows2[i][j] = best;
35605
35627
  }
35606
35628
  }
35607
- return rows[a.length][b.length];
35629
+ return rows2[a.length][b.length];
35608
35630
  }
35609
35631
  function detectTyposquat(name, ecosystem) {
35610
35632
  const popular = ecosystem === "npm" ? POPULAR_NPM : POPULAR_PYPI;
@@ -37755,12 +37777,12 @@ async function initCommand(opts = {}) {
37755
37777
  const foundBinary = svc.binaries.find((b) => binaryExists(b));
37756
37778
  if (foundBinary) {
37757
37779
  const running = svc.binaries.some((b) => isProcessRunning(b));
37758
- const logPath = findLogPath(svc.logPaths);
37780
+ const logPath2 = findLogPath(svc.logPaths);
37759
37781
  detected2.push({
37760
37782
  name: svc.name,
37761
37783
  binary: foundBinary,
37762
37784
  running,
37763
- logPath
37785
+ logPath: logPath2
37764
37786
  });
37765
37787
  }
37766
37788
  }
@@ -39790,15 +39812,15 @@ async function sshConnect(options) {
39790
39812
 
39791
39813
  // src/commands/daemon.ts
39792
39814
  var import_node_child_process16 = require("child_process");
39793
- var import_node_fs40 = require("fs");
39794
- var import_node_path30 = require("path");
39795
39815
  var import_node_fs41 = require("fs");
39816
+ var import_node_path31 = require("path");
39817
+ var import_node_fs42 = require("fs");
39796
39818
 
39797
39819
  // src/daemon/index.ts
39798
- var import_node_fs39 = require("fs");
39820
+ var import_node_fs40 = require("fs");
39799
39821
  var import_node_child_process15 = require("child_process");
39800
39822
  var import_node_os11 = require("os");
39801
- var import_node_path29 = require("path");
39823
+ var import_node_path30 = require("path");
39802
39824
  var import_node_util = require("util");
39803
39825
  init_paths();
39804
39826
 
@@ -42430,16 +42452,425 @@ var CloudSync = class {
42430
42452
  }
42431
42453
  };
42432
42454
 
42455
+ // src/daemon/workers/abuse-reporter.ts
42456
+ var import_node_crypto7 = require("crypto");
42457
+
42458
+ // src/daemon/workers/abuse-evidence.ts
42459
+ var import_node_net7 = require("net");
42460
+ var NEVER_REPORT_RANGES = [
42461
+ ...DEFAULT_PROTECTED,
42462
+ "100.64.0.0/10",
42463
+ // RFC 6598 carrier-grade NAT
42464
+ "192.0.2.0/24",
42465
+ // TEST-NET-1 (documentation)
42466
+ "198.51.100.0/24",
42467
+ // TEST-NET-2
42468
+ "203.0.113.0/24",
42469
+ // TEST-NET-3
42470
+ "192.0.0.0/24",
42471
+ // IETF protocol assignments
42472
+ "198.18.0.0/15",
42473
+ // benchmarking
42474
+ "224.0.0.0/4",
42475
+ // multicast
42476
+ "240.0.0.0/4",
42477
+ // reserved
42478
+ "::/128",
42479
+ // unspecified
42480
+ "2001:db8::/32",
42481
+ // documentation
42482
+ "100::/64"
42483
+ // discard-only
42484
+ ];
42485
+ var CONNECTION_VERIFIED_CATEGORIES = /* @__PURE__ */ new Set(["auth", "web", "pentest"]);
42486
+ var CONNECTION_VERIFIED_MODULES = ["honeypot", "honey-pot", "webhoneypot"];
42487
+ function summarizeEvidence(events) {
42488
+ const modules = /* @__PURE__ */ new Set();
42489
+ const categories = /* @__PURE__ */ new Set();
42490
+ const ruleIds = /* @__PURE__ */ new Set();
42491
+ let connectionVerified = false;
42492
+ let firstSeen = Infinity;
42493
+ let lastSeen = 0;
42494
+ let total = 0;
42495
+ for (const event of events) {
42496
+ if (event.module === "firewall-rules") continue;
42497
+ total++;
42498
+ modules.add(event.module);
42499
+ categories.add(event.category);
42500
+ const ruleId = event.details?.rule_id;
42501
+ if (typeof ruleId === "string") ruleIds.add(ruleId);
42502
+ const t = event.timestamp.getTime();
42503
+ if (t < firstSeen) firstSeen = t;
42504
+ if (t > lastSeen) lastSeen = t;
42505
+ if (CONNECTION_VERIFIED_CATEGORIES.has(event.category) || CONNECTION_VERIFIED_MODULES.some((m) => event.module.includes(m))) {
42506
+ connectionVerified = true;
42507
+ }
42508
+ }
42509
+ return {
42510
+ signals: modules.size,
42511
+ connectionVerified,
42512
+ firstSeen: firstSeen === Infinity ? 0 : firstSeen,
42513
+ lastSeen,
42514
+ total,
42515
+ categories: [...categories],
42516
+ ruleIds: [...ruleIds]
42517
+ };
42518
+ }
42519
+ function isReportable(ip, evidence, config, now = Date.now()) {
42520
+ if ((0, import_node_net7.isIP)(ip) === 0) return { reportable: false, reason: "not an IP address" };
42521
+ if (isProtected(ip, config.neverReport)) {
42522
+ return { reportable: false, reason: "address is in a never-report range (private/CGNAT/reserved/allowlisted)" };
42523
+ }
42524
+ if (!evidence.connectionVerified) {
42525
+ return { reportable: false, reason: "no connection-verified (L7) signal \u2014 spoofable, not reportable" };
42526
+ }
42527
+ if (evidence.signals < config.minCorroboratingSignals) {
42528
+ return {
42529
+ reportable: false,
42530
+ reason: `only ${evidence.signals} corroborating signal(s), need ${config.minCorroboratingSignals}`
42531
+ };
42532
+ }
42533
+ const age = (now - evidence.firstSeen) / 1e3;
42534
+ if (evidence.firstSeen > 0 && age < config.coolingOffSeconds) {
42535
+ return { reportable: false, reason: "within cooling-off window", waitSeconds: Math.ceil(config.coolingOffSeconds - age) };
42536
+ }
42537
+ return { reportable: true };
42538
+ }
42539
+ function abuseipdbCategories(evidence) {
42540
+ const cats = /* @__PURE__ */ new Set();
42541
+ const rules = evidence.ruleIds.join(" ").toLowerCase();
42542
+ for (const category of evidence.categories) {
42543
+ switch (category) {
42544
+ case "auth":
42545
+ cats.add(18);
42546
+ cats.add(22);
42547
+ break;
42548
+ case "web":
42549
+ cats.add(21);
42550
+ break;
42551
+ case "scan":
42552
+ case "network":
42553
+ cats.add(14);
42554
+ break;
42555
+ case "pentest":
42556
+ cats.add(15);
42557
+ break;
42558
+ default:
42559
+ break;
42560
+ }
42561
+ }
42562
+ if (rules.includes("sql")) cats.add(16);
42563
+ if (rules.includes("xss") || rules.includes("rce") || rules.includes("lfi") || rules.includes("rfi")) cats.add(15);
42564
+ if (rules.includes("bot") || rules.includes("scrape") || rules.includes("paywall")) cats.add(19);
42565
+ if (cats.size === 0) cats.add(15);
42566
+ return [...cats].sort((a, b) => a - b);
42567
+ }
42568
+
42569
+ // src/daemon/workers/abuse-destinations.ts
42570
+ var TIMEOUT_MS = 15e3;
42571
+ function buildComment(evidence) {
42572
+ const hours = Math.max(1, Math.round((evidence.lastSeen - evidence.firstSeen) / 36e5));
42573
+ const kinds = evidence.categories.map((c) => ({ auth: "authentication", web: "web-application", scan: "scanning", network: "network", pentest: "exploitation" })[c] ?? c).join(", ");
42574
+ return `Automated report from ThreatCrush. ${evidence.total} malicious ${kinds || "attack"} event(s) observed from this address across ${evidence.signals} detector(s) over ~${hours}h, confirmed by a completed TCP handshake. Blocked by automated defence. No reply expected.`;
42575
+ }
42576
+ function buildPayload(ip, evidence) {
42577
+ return { ip, evidence, comment: buildComment(evidence), categories: abuseipdbCategories(evidence) };
42578
+ }
42579
+ async function reportToAbuseIPDB(payload, apiKey) {
42580
+ const body = new URLSearchParams({
42581
+ ip: payload.ip,
42582
+ categories: payload.categories.join(","),
42583
+ comment: payload.comment.slice(0, 1024)
42584
+ });
42585
+ try {
42586
+ const res = await fetch("https://api.abuseipdb.com/api/v2/report", {
42587
+ method: "POST",
42588
+ headers: {
42589
+ Key: apiKey,
42590
+ Accept: "application/json",
42591
+ "Content-Type": "application/x-www-form-urlencoded"
42592
+ },
42593
+ body,
42594
+ signal: AbortSignal.timeout(TIMEOUT_MS)
42595
+ });
42596
+ if (res.status === 429) {
42597
+ return { destination: "abuseipdb", ok: false, detail: "rate-limited by AbuseIPDB (daily cap)" };
42598
+ }
42599
+ const json = await res.json().catch(() => ({}));
42600
+ if (!res.ok) {
42601
+ const detail = json.errors?.map((e) => e.detail).filter(Boolean).join("; ") || `HTTP ${res.status}`;
42602
+ return { destination: "abuseipdb", ok: false, detail };
42603
+ }
42604
+ const score = json.data?.abuseConfidenceScore;
42605
+ return { destination: "abuseipdb", ok: true, detail: score !== void 0 ? `confidence ${score}` : "reported" };
42606
+ } catch (err) {
42607
+ return { destination: "abuseipdb", ok: false, detail: err.message };
42608
+ }
42609
+ }
42610
+ async function reportToStopForumSpam(payload, apiKey) {
42611
+ const body = new URLSearchParams({
42612
+ api_key: apiKey,
42613
+ ip: payload.ip,
42614
+ evidence: payload.comment.slice(0, 1e3)
42615
+ });
42616
+ try {
42617
+ const res = await fetch("https://www.stopforumspam.org/add.php", {
42618
+ method: "POST",
42619
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
42620
+ body,
42621
+ signal: AbortSignal.timeout(TIMEOUT_MS)
42622
+ });
42623
+ const text = await res.text().catch(() => "");
42624
+ if (!res.ok) return { destination: "stopforumspam", ok: false, detail: `HTTP ${res.status} ${text.slice(0, 120)}` };
42625
+ const ok = /success|"success"\s*:\s*true/i.test(text);
42626
+ return { destination: "stopforumspam", ok, detail: ok ? "reported" : text.slice(0, 120) || "refused" };
42627
+ } catch (err) {
42628
+ return { destination: "stopforumspam", ok: false, detail: err.message };
42629
+ }
42630
+ }
42631
+ async function dispatch(payload, destinations, keys) {
42632
+ const jobs = [];
42633
+ for (const dest of destinations) {
42634
+ if (dest === "abuseipdb" && keys.abuseipdb) jobs.push(reportToAbuseIPDB(payload, keys.abuseipdb));
42635
+ else if (dest === "stopforumspam" && keys.stopforumspam) jobs.push(reportToStopForumSpam(payload, keys.stopforumspam));
42636
+ }
42637
+ return Promise.all(jobs);
42638
+ }
42639
+
42640
+ // src/daemon/workers/abuse-config.ts
42641
+ init_backoff();
42642
+ function resolveConfig(section) {
42643
+ const s = section ?? {};
42644
+ const dryRun = s.mode === "dry_run" ? true : s.mode === "live" ? false : s.dry_run === true;
42645
+ const neverReport = [...NEVER_REPORT_RANGES, ...s.never_report ?? []];
42646
+ const cooling = parseDuration(s.cooling_off) ?? 3600;
42647
+ return {
42648
+ enabled: s.enabled !== false,
42649
+ dryRun,
42650
+ destinations: s.destinations && s.destinations.length > 0 ? s.destinations : ["abuseipdb"],
42651
+ keys: {
42652
+ abuseipdb: s.abuseipdb_api_key || process.env.ABUSEIPDB_API_KEY || void 0,
42653
+ stopforumspam: s.stopforumspam_api_key || process.env.STOPFORUMSPAM_API_KEY || void 0
42654
+ },
42655
+ minCorroboratingSignals: Math.max(1, s.min_corroborating_signals ?? 2),
42656
+ coolingOffSeconds: cooling,
42657
+ neverReport,
42658
+ maxReportsPerHour: Math.max(1, s.max_reports_per_hour ?? 50),
42659
+ maxPerSourcePerDay: Math.max(1, s.max_reports_per_source_per_day ?? 1)
42660
+ };
42661
+ }
42662
+
42663
+ // src/core/abuse-report-log.ts
42664
+ var import_node_fs32 = require("fs");
42665
+ var import_node_path23 = require("path");
42666
+ init_paths();
42667
+ var ABUSE_DIRNAME = "abuse-reports";
42668
+ var LOG_FILE2 = "reports.jsonl";
42669
+ function resolveAbuseDir(dir) {
42670
+ if (dir) return dir;
42671
+ if (process.env.THREATCRUSH_ABUSE_DIR) return process.env.THREATCRUSH_ABUSE_DIR;
42672
+ const system = (0, import_node_path23.join)("/var/lib/threatcrush", ABUSE_DIRNAME);
42673
+ if ((0, import_node_fs32.existsSync)(system)) return system;
42674
+ return (0, import_node_path23.join)(PATHS.stateDir, ABUSE_DIRNAME);
42675
+ }
42676
+ function logPath(dir) {
42677
+ return (0, import_node_path23.join)(resolveAbuseDir(dir), LOG_FILE2);
42678
+ }
42679
+ function appendReport(record, dir) {
42680
+ const path = logPath(dir);
42681
+ (0, import_node_fs32.mkdirSync)(resolveAbuseDir(dir), { recursive: true, mode: 493 });
42682
+ (0, import_node_fs32.appendFileSync)(path, `${JSON.stringify(record)}
42683
+ `, { mode: 420 });
42684
+ }
42685
+ function readReports(dir) {
42686
+ const path = logPath(dir);
42687
+ let raw;
42688
+ try {
42689
+ raw = (0, import_node_fs32.readFileSync)(path, "utf-8");
42690
+ } catch {
42691
+ return [];
42692
+ }
42693
+ const out = [];
42694
+ for (const line2 of raw.split("\n")) {
42695
+ if (!line2.trim()) continue;
42696
+ try {
42697
+ out.push(JSON.parse(line2));
42698
+ } catch {
42699
+ }
42700
+ }
42701
+ return out;
42702
+ }
42703
+ function findReport(id, dir) {
42704
+ const all = readReports(dir);
42705
+ for (let i = all.length - 1; i >= 0; i--) {
42706
+ if (all[i].id === id || all[i].id.startsWith(id)) return all[i];
42707
+ }
42708
+ return void 0;
42709
+ }
42710
+ function markRetracted(id, note, dir) {
42711
+ const record = findReport(id, dir);
42712
+ if (!record) return void 0;
42713
+ const retracted = {
42714
+ ...record,
42715
+ retracted_at: (/* @__PURE__ */ new Date()).toISOString(),
42716
+ retract_note: note
42717
+ };
42718
+ appendReport(retracted, dir);
42719
+ return retracted;
42720
+ }
42721
+ function currentReports(dir) {
42722
+ const byId = /* @__PURE__ */ new Map();
42723
+ for (const r of readReports(dir)) byId.set(r.id, r);
42724
+ return [...byId.values()].sort((a, b) => b.reported_at.localeCompare(a.reported_at));
42725
+ }
42726
+
42727
+ // src/daemon/workers/abuse-reporter.ts
42728
+ var EVIDENCE_LOOKBACK_MS = 24 * 60 * 60 * 1e3;
42729
+ var PENDING_TTL_MS = 24 * 60 * 60 * 1e3;
42730
+ var AbuseReporter = class {
42731
+ constructor(opts) {
42732
+ this.opts = opts;
42733
+ this.cfg = resolveConfig(opts.section);
42734
+ this.now = opts.now ?? (() => Date.now());
42735
+ this.flushMs = opts.flushMs ?? 6e4;
42736
+ }
42737
+ opts;
42738
+ cfg;
42739
+ now;
42740
+ flushMs;
42741
+ /** Sources seen blocked, awaiting enough evidence / cooling-off, with when first queued. */
42742
+ pending = /* @__PURE__ */ new Map();
42743
+ /** Epoch-ms of live reports sent this process, for the global hourly limit. */
42744
+ recentReports = [];
42745
+ timer = null;
42746
+ flushing = false;
42747
+ onEvent = (event) => this.capture(event);
42748
+ /** Active when it can do something: send live, or at least compute dry-run. */
42749
+ get active() {
42750
+ if (!this.cfg.enabled) return false;
42751
+ if (this.cfg.dryRun) return true;
42752
+ return Boolean(this.cfg.keys.abuseipdb || this.cfg.keys.stopforumspam);
42753
+ }
42754
+ start() {
42755
+ if (!this.cfg.enabled) {
42756
+ this.opts.log("[abuse] reporter disabled by [abuse-reporter] enabled = false");
42757
+ return;
42758
+ }
42759
+ if (!this.active) {
42760
+ this.opts.log(
42761
+ "[abuse] reporter on but inert: no destination API key set (ABUSEIPDB_API_KEY or [abuse-reporter] abuseipdb_api_key). Nothing will be reported."
42762
+ );
42763
+ return;
42764
+ }
42765
+ this.opts.bus.on("event", this.onEvent);
42766
+ const timer = setInterval(() => void this.flush(), this.flushMs);
42767
+ timer.unref?.();
42768
+ this.timer = timer;
42769
+ const mode = this.cfg.dryRun ? "dry_run (nothing sent)" : `live \u2192 ${this.cfg.destinations.join(", ")}`;
42770
+ this.opts.log(
42771
+ `[abuse] reporter ${mode}; bar: >=${this.cfg.minCorroboratingSignals} signals + completed handshake, cooling-off ${Math.round(this.cfg.coolingOffSeconds / 60)}m, <=${this.cfg.maxReportsPerHour}/h, ${this.cfg.maxPerSourcePerDay}/source/day`
42772
+ );
42773
+ }
42774
+ stop() {
42775
+ this.opts.bus.off("event", this.onEvent);
42776
+ if (this.timer) clearInterval(this.timer);
42777
+ this.timer = null;
42778
+ }
42779
+ get queued() {
42780
+ return this.pending.size;
42781
+ }
42782
+ /** Remember a blocked source as a candidate. No network here — that waits for flush. */
42783
+ capture(event) {
42784
+ if (event.module !== "firewall-rules") return;
42785
+ if (event.details?.action !== "block") return;
42786
+ if (event.details?.failed === true) return;
42787
+ const ip = event.source_ip;
42788
+ if (!ip) return;
42789
+ if (!this.pending.has(ip)) this.pending.set(ip, this.now());
42790
+ }
42791
+ /** Walk the candidates; report the ones that clear the bar and the limits. */
42792
+ async flush() {
42793
+ if (this.flushing || !this.active) return;
42794
+ this.flushing = true;
42795
+ try {
42796
+ const now = this.now();
42797
+ this.trimRecent(now);
42798
+ for (const [ip, queuedAt] of [...this.pending]) {
42799
+ if (now - queuedAt > PENDING_TTL_MS) {
42800
+ this.pending.delete(ip);
42801
+ continue;
42802
+ }
42803
+ if (!this.cfg.dryRun && this.recentReports.length >= this.cfg.maxReportsPerHour) break;
42804
+ const evidence = summarizeEvidence(getEventsForIp(ip, now - EVIDENCE_LOOKBACK_MS));
42805
+ const decision = isReportable(ip, evidence, this.cfg, now);
42806
+ if (!decision.reportable) {
42807
+ if (decision.waitSeconds === void 0) this.pending.delete(ip);
42808
+ continue;
42809
+ }
42810
+ if (this.reportedWithin(ip, now, 864e5 * this.cfg.maxPerSourcePerDay)) {
42811
+ this.pending.delete(ip);
42812
+ continue;
42813
+ }
42814
+ this.pending.delete(ip);
42815
+ await this.report(ip, evidence, now);
42816
+ if (!this.cfg.dryRun) this.recentReports.push(now);
42817
+ }
42818
+ } catch (err) {
42819
+ this.opts.log(`[abuse] flush error: ${err.message}`);
42820
+ } finally {
42821
+ this.flushing = false;
42822
+ }
42823
+ }
42824
+ async report(ip, evidence, now) {
42825
+ const payload = buildPayload(ip, evidence);
42826
+ const results = this.cfg.dryRun ? [] : await dispatch(payload, this.cfg.destinations, this.cfg.keys);
42827
+ const record = {
42828
+ id: (0, import_node_crypto7.randomUUID)().slice(0, 8),
42829
+ ip,
42830
+ reported_at: new Date(now).toISOString(),
42831
+ mode: this.cfg.dryRun ? "dry_run" : "live",
42832
+ categories: payload.categories,
42833
+ comment: payload.comment,
42834
+ signals: evidence.signals,
42835
+ total_events: evidence.total,
42836
+ destinations: results
42837
+ };
42838
+ try {
42839
+ appendReport(record, this.opts.dir);
42840
+ } catch (err) {
42841
+ this.opts.log(`[abuse] could not write audit record: ${err.message}`);
42842
+ }
42843
+ if (this.cfg.dryRun) {
42844
+ this.opts.log(`[abuse] [DRY-RUN] would report ${ip} (cats ${payload.categories.join(",")}, ${evidence.signals} signals)`);
42845
+ } else {
42846
+ const summary = results.map((r) => `${r.destination}:${r.ok ? "ok" : "FAIL"} ${r.detail}`).join("; ");
42847
+ this.opts.log(`[abuse] reported ${ip} [${record.id}] \u2192 ${summary || "no destinations"}`);
42848
+ }
42849
+ }
42850
+ trimRecent(now) {
42851
+ const cutoff = now - 36e5;
42852
+ this.recentReports = this.recentReports.filter((t) => t > cutoff);
42853
+ }
42854
+ /** Has this source had a live report inside `windowMs`, per the audit log? */
42855
+ reportedWithin(ip, now, windowMs) {
42856
+ for (const r of currentReports(this.opts.dir)) {
42857
+ if (r.ip !== ip || r.mode !== "live" || r.retracted_at) continue;
42858
+ if (now - Date.parse(r.reported_at) < windowMs) return true;
42859
+ }
42860
+ return false;
42861
+ }
42862
+ };
42863
+
42433
42864
  // src/daemon/workers/remediation-consumer.ts
42434
- var import_node_net8 = require("net");
42865
+ var import_node_net9 = require("net");
42435
42866
  init_cli_config();
42436
42867
 
42437
42868
  // src/daemon/workers/allowlist-sync.ts
42438
- var import_node_net7 = require("net");
42869
+ var import_node_net8 = require("net");
42439
42870
  init_cli_config();
42440
42871
  function isAddressOrCidr(value) {
42441
42872
  const [network, prefix, extra] = value.split("/");
42442
- const family = (0, import_node_net7.isIP)(network);
42873
+ const family = (0, import_node_net8.isIP)(network);
42443
42874
  if (family === 0 || extra !== void 0) return false;
42444
42875
  if (prefix === void 0) return true;
42445
42876
  if (!/^\d{1,3}$/.test(prefix)) return false;
@@ -42588,7 +43019,7 @@ var RemediationConsumer = class {
42588
43019
  try {
42589
43020
  switch (action.action_type) {
42590
43021
  case "block": {
42591
- if ((0, import_node_net8.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
43022
+ if ((0, import_node_net9.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
42592
43023
  let ttlSeconds = this.manager.status().max_ban_seconds;
42593
43024
  if (action.expires_at) {
42594
43025
  const until = Date.parse(action.expires_at);
@@ -42607,7 +43038,7 @@ var RemediationConsumer = class {
42607
43038
  return { status: "executed", dry_run: result.entry?.dry_run === true, executed_at };
42608
43039
  }
42609
43040
  case "unblock": {
42610
- if ((0, import_node_net8.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
43041
+ if ((0, import_node_net9.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
42611
43042
  const wasBanned = this.manager.getBlocklist().some((b) => b.ip === target);
42612
43043
  const result = await this.manager.unban(target, {
42613
43044
  forget: true,
@@ -42652,8 +43083,8 @@ var RemediationConsumer = class {
42652
43083
 
42653
43084
  // src/daemon/workers/auto-update.ts
42654
43085
  var import_node_child_process9 = require("child_process");
42655
- var import_node_fs32 = require("fs");
42656
- var import_node_path23 = require("path");
43086
+ var import_node_fs33 = require("fs");
43087
+ var import_node_path24 = require("path");
42657
43088
  init_backoff();
42658
43089
  var PKG_NAME = "@profullstack/threatcrush";
42659
43090
  var REGISTRY = `https://registry.npmjs.org/${PKG_NAME}`;
@@ -42680,23 +43111,29 @@ function pickUpdate(doc, current, opts) {
42680
43111
  if (!latest) return { version: null, reason: "registry has no latest tag" };
42681
43112
  if (!isNewer(latest, current)) return { version: null, reason: `up to date (${current})` };
42682
43113
  const major = (v) => Number.parseInt(v.replace(/^v/, ""), 10);
43114
+ let best = null;
43115
+ for (const [v, when] of Object.entries(doc.time ?? {})) {
43116
+ if (!/^\d+\.\d+\.\d+$/.test(v)) continue;
43117
+ if (!isNewer(v, current) || isNewer(v, latest)) continue;
43118
+ if (!opts.allowMajor && major(v) !== major(current)) continue;
43119
+ const published = Date.parse(when);
43120
+ if (!Number.isFinite(published) || opts.now - published < opts.minAgeMs) continue;
43121
+ if (!best || isNewer(v, best)) best = v;
43122
+ }
43123
+ if (best) return { version: best };
42683
43124
  if (!opts.allowMajor && major(latest) !== major(current)) {
42684
43125
  return { version: null, reason: `${latest} is a new major; set [update] allow_major = true to take it` };
42685
43126
  }
42686
- const published = Date.parse(doc.time?.[latest] ?? "");
42687
- if (!Number.isFinite(published)) return { version: null, reason: `no publish time for ${latest}` };
42688
- if (opts.now - published < opts.minAgeMs) {
42689
- return { version: null, reason: `${latest} is younger than min_age; waiting` };
42690
- }
42691
- return { version: latest };
43127
+ if (!Number.isFinite(Date.parse(doc.time?.[latest] ?? ""))) return { version: null, reason: `no publish time for ${latest}` };
43128
+ return { version: null, reason: `${latest} is younger than min_age, and nothing older is newer than ${current}; waiting` };
42692
43129
  }
42693
43130
  function installPlan(opts) {
42694
- const expected = `${import_node_path23.sep}lib${import_node_path23.sep}node_modules${import_node_path23.sep}@profullstack${import_node_path23.sep}threatcrush`;
43131
+ const expected = `${import_node_path24.sep}lib${import_node_path24.sep}node_modules${import_node_path24.sep}@profullstack${import_node_path24.sep}threatcrush`;
42695
43132
  if (!opts.pkgRoot.endsWith(expected)) {
42696
43133
  return { kind: "unsupported", reason: `not an npm global install (${opts.pkgRoot}); run \`threatcrush update\`` };
42697
43134
  }
42698
- const nodeBin = (0, import_node_path23.dirname)(opts.execPath);
42699
- const npm = (0, import_node_path23.join)(nodeBin, "npm");
43135
+ const nodeBin = (0, import_node_path24.dirname)(opts.execPath);
43136
+ const npm = (0, import_node_path24.join)(nodeBin, "npm");
42700
43137
  if (!opts.npmExists(npm)) return { kind: "unsupported", reason: `no npm beside ${opts.execPath}` };
42701
43138
  if (!opts.owner) return { kind: "unsupported", reason: `cannot tell who owns ${opts.pkgRoot}` };
42702
43139
  const npmArgs = [npm, "i", "-g", `${PKG_NAME}@${opts.version}`, "--no-fund", "--no-audit"];
@@ -42728,10 +43165,10 @@ function installPlan(opts) {
42728
43165
  }
42729
43166
  function ownerOf(path, passwd = "/etc/passwd") {
42730
43167
  try {
42731
- const st = (0, import_node_fs32.statSync)(path);
43168
+ const st = (0, import_node_fs33.statSync)(path);
42732
43169
  let home = st.uid === 0 ? "/root" : "";
42733
43170
  try {
42734
- for (const line2 of (0, import_node_fs32.readFileSync)(passwd, "utf8").split("\n")) {
43171
+ for (const line2 of (0, import_node_fs33.readFileSync)(passwd, "utf8").split("\n")) {
42735
43172
  const f = line2.split(":");
42736
43173
  if (Number(f[2]) === st.uid && f[5]) home = f[5];
42737
43174
  }
@@ -42823,7 +43260,7 @@ var AutoUpdate = class {
42823
43260
  minAgeMs: this.opts.settings.minAgeMs,
42824
43261
  now: this.now()
42825
43262
  });
42826
- if (pick.version === null) return this.note(pick.reason, false);
43263
+ if (pick.version === null) return this.note(pick.reason, !pick.reason.startsWith("up to date"));
42827
43264
  const target = pick.version;
42828
43265
  const last = this.lastAttempt();
42829
43266
  if (last?.version === target && this.now() - last.at < RETRY_AFTER_MS) {
@@ -42836,7 +43273,7 @@ var AutoUpdate = class {
42836
43273
  uid: process.getuid?.() ?? -1,
42837
43274
  owner: ownerOf(this.opts.pkgRoot),
42838
43275
  underSystemd: this.opts.underSystemd ?? Boolean(process.env.INVOCATION_ID),
42839
- npmExists: import_node_fs32.existsSync
43276
+ npmExists: import_node_fs33.existsSync
42840
43277
  });
42841
43278
  if (plan.kind === "unsupported") return this.note(`${target} is available but cannot self-install: ${plan.reason}`);
42842
43279
  this.recordAttempt(target);
@@ -42871,7 +43308,7 @@ var AutoUpdate = class {
42871
43308
  }
42872
43309
  lastAttempt() {
42873
43310
  try {
42874
- const v = JSON.parse((0, import_node_fs32.readFileSync)(this.opts.statePath, "utf8"));
43311
+ const v = JSON.parse((0, import_node_fs33.readFileSync)(this.opts.statePath, "utf8"));
42875
43312
  return v.version && typeof v.at === "number" ? { version: v.version, at: v.at } : null;
42876
43313
  } catch {
42877
43314
  return null;
@@ -42879,7 +43316,7 @@ var AutoUpdate = class {
42879
43316
  }
42880
43317
  recordAttempt(version) {
42881
43318
  try {
42882
- (0, import_node_fs32.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
43319
+ (0, import_node_fs33.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
42883
43320
  } catch (err) {
42884
43321
  this.opts.log(`[update] could not record attempt: ${err.message}`);
42885
43322
  }
@@ -42888,9 +43325,9 @@ var AutoUpdate = class {
42888
43325
 
42889
43326
  // src/daemon/workers/threat-feeds.ts
42890
43327
  var import_node_child_process10 = require("child_process");
42891
- var import_node_fs33 = require("fs");
42892
- var import_node_path24 = require("path");
42893
- var import_node_net9 = require("net");
43328
+ var import_node_fs34 = require("fs");
43329
+ var import_node_path25 = require("path");
43330
+ var import_node_net10 = require("net");
42894
43331
  init_backoff();
42895
43332
  var EGRESS_TABLE = "threatcrush_egress";
42896
43333
  var DEFAULT_REFRESH_MS = 36e5;
@@ -42909,8 +43346,8 @@ function threatFeedSettings(section) {
42909
43346
  };
42910
43347
  }
42911
43348
  function egressRuleset(ips) {
42912
- const v4 = ips.filter((ip) => (0, import_node_net9.isIP)(ip) === 4);
42913
- const v6 = ips.filter((ip) => (0, import_node_net9.isIP)(ip) === 6);
43349
+ const v4 = ips.filter((ip) => (0, import_node_net10.isIP)(ip) === 4);
43350
+ const v6 = ips.filter((ip) => (0, import_node_net10.isIP)(ip) === 6);
42914
43351
  const set = (name, type, items) => ` set ${name} { type ${type};${items.length ? ` elements = { ${items.join(", ")} }` : ""} }`;
42915
43352
  const chain = (name, hook) => [
42916
43353
  ` chain ${name} {`,
@@ -42935,7 +43372,7 @@ function splitAddr(addr) {
42935
43372
  const m = /^\[?(.+?)\]?:(\d+|\*)$/.exec(addr);
42936
43373
  if (!m) return null;
42937
43374
  const ip = m[1].replace(/%.*$/, "").replace(/^::ffff:/i, "");
42938
- return (0, import_node_net9.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
43375
+ return (0, import_node_net10.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
42939
43376
  }
42940
43377
  function parseSs(text) {
42941
43378
  const out = [];
@@ -43061,14 +43498,14 @@ var ThreatFeeds = class {
43061
43498
  */
43062
43499
  writeResolverFiles(set) {
43063
43500
  const domains = this.wantsDomainBlock ? Object.keys(set.domains).sort() : [];
43064
- const dir = this.opts.resolverDir ?? (0, import_node_path24.dirname)(this.opts.cachePath);
43501
+ const dir = this.opts.resolverDir ?? (0, import_node_path25.dirname)(this.opts.cachePath);
43065
43502
  const hooks = this.opts.resolverHooks ?? RESOLVER_HOOKS;
43066
43503
  const write = (name, content) => {
43067
- const path = (0, import_node_path24.join)(dir, name);
43504
+ const path = (0, import_node_path25.join)(dir, name);
43068
43505
  if (this.resolverWritten.get(name) === content) return false;
43069
43506
  try {
43070
- (0, import_node_fs33.writeFileSync)(`${path}.tmp`, content);
43071
- (0, import_node_fs33.renameSync)(`${path}.tmp`, path);
43507
+ (0, import_node_fs34.writeFileSync)(`${path}.tmp`, content);
43508
+ (0, import_node_fs34.renameSync)(`${path}.tmp`, path);
43072
43509
  this.resolverWritten.set(name, content);
43073
43510
  return true;
43074
43511
  } catch (err) {
@@ -43079,11 +43516,11 @@ var ThreatFeeds = class {
43079
43516
  const hostsChanged = write(RESOLVER_FILES.hosts, hostsBlocklist(domains));
43080
43517
  const unboundChanged = write(RESOLVER_FILES.unbound, unboundBlocklist(domains));
43081
43518
  const via = [];
43082
- if ((0, import_node_fs33.existsSync)(hooks.dnsmasq)) {
43519
+ if ((0, import_node_fs34.existsSync)(hooks.dnsmasq)) {
43083
43520
  via.push("dnsmasq");
43084
43521
  if (hostsChanged) this.run("systemctl", ["kill", "-s", "HUP", "dnsmasq.service"]);
43085
43522
  }
43086
- if ((0, import_node_fs33.existsSync)(hooks.unbound)) {
43523
+ if ((0, import_node_fs34.existsSync)(hooks.unbound)) {
43087
43524
  via.push("unbound");
43088
43525
  if (unboundChanged && this.run("unbound-control", ["reload"]) === null) {
43089
43526
  this.run("systemctl", ["reload", "unbound.service"]);
@@ -43144,12 +43581,12 @@ var ThreatFeeds = class {
43144
43581
  };
43145
43582
 
43146
43583
  // src/daemon/workers/privilege-watch.ts
43147
- var import_node_fs34 = require("fs");
43148
- var import_node_path25 = require("path");
43584
+ var import_node_fs35 = require("fs");
43585
+ var import_node_path26 = require("path");
43149
43586
  var import_node_child_process11 = require("child_process");
43150
43587
 
43151
43588
  // src/core/privileges/index.ts
43152
- var import_node_crypto7 = require("crypto");
43589
+ var import_node_crypto8 = require("crypto");
43153
43590
  var ADMIN_GROUPS = ["sudo", "wheel", "admin"];
43154
43591
  function parseUsers(text) {
43155
43592
  const out = [];
@@ -43190,7 +43627,7 @@ function sudoReadsIncluded(name) {
43190
43627
  }
43191
43628
  function keyFingerprint(blobBase64) {
43192
43629
  if (!/^[A-Za-z0-9+/]+=*$/.test(blobBase64)) return null;
43193
- const digest = (0, import_node_crypto7.createHash)("sha256").update(Buffer.from(blobBase64, "base64")).digest("base64");
43630
+ const digest = (0, import_node_crypto8.createHash)("sha256").update(Buffer.from(blobBase64, "base64")).digest("base64");
43194
43631
  return `SHA256:${digest.replace(/=+$/, "")}`;
43195
43632
  }
43196
43633
  function parseAuthorizedKeys(text) {
@@ -43336,31 +43773,31 @@ function countryName(code) {
43336
43773
  var fsIO = {
43337
43774
  readFile: (p) => {
43338
43775
  try {
43339
- return (0, import_node_fs34.readFileSync)(p, "utf-8");
43776
+ return (0, import_node_fs35.readFileSync)(p, "utf-8");
43340
43777
  } catch {
43341
43778
  return null;
43342
43779
  }
43343
43780
  },
43344
43781
  readDir: (p) => {
43345
43782
  try {
43346
- return (0, import_node_fs34.readdirSync)(p);
43783
+ return (0, import_node_fs35.readdirSync)(p);
43347
43784
  } catch {
43348
43785
  return null;
43349
43786
  }
43350
43787
  },
43351
- exists: (p) => (0, import_node_fs34.existsSync)(p)
43788
+ exists: (p) => (0, import_node_fs35.existsSync)(p)
43352
43789
  };
43353
43790
  function readJson(path) {
43354
43791
  try {
43355
- return JSON.parse((0, import_node_fs34.readFileSync)(path, "utf-8"));
43792
+ return JSON.parse((0, import_node_fs35.readFileSync)(path, "utf-8"));
43356
43793
  } catch {
43357
43794
  return null;
43358
43795
  }
43359
43796
  }
43360
43797
  function writeJson(path, value) {
43361
- (0, import_node_fs34.mkdirSync)((0, import_node_path25.dirname)(path), { recursive: true });
43362
- (0, import_node_fs34.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
43363
- (0, import_node_fs34.renameSync)(`${path}.tmp`, path);
43798
+ (0, import_node_fs35.mkdirSync)((0, import_node_path26.dirname)(path), { recursive: true });
43799
+ (0, import_node_fs35.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
43800
+ (0, import_node_fs35.renameSync)(`${path}.tmp`, path);
43364
43801
  }
43365
43802
  function defaultRun3(cmd, args) {
43366
43803
  const res = (0, import_node_child_process11.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 2e4, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
@@ -43516,7 +43953,7 @@ var PrivilegeWatch = class {
43516
43953
  * raised a "new country" alert on its first run; on dev2 it did, at once.
43517
43954
  */
43518
43955
  async backfillLogins() {
43519
- if ((0, import_node_fs34.existsSync)(this.opts.loginsPath)) return;
43956
+ if ((0, import_node_fs35.existsSync)(this.opts.loginsPath)) return;
43520
43957
  const out = this.run("journalctl", ["_COMM=sshd", "_COMM=sshd-session", "--since=-30d", "-o", "cat", "--no-pager"]);
43521
43958
  const byUser = parseAcceptedLogins(out ?? "");
43522
43959
  const ips = [...new Set([...byUser.values()].flatMap((s) => [...s]))];
@@ -43529,7 +43966,7 @@ var PrivilegeWatch = class {
43529
43966
  return;
43530
43967
  }
43531
43968
  }
43532
- if ((0, import_node_fs34.existsSync)(this.opts.loginsPath)) return;
43969
+ if ((0, import_node_fs35.existsSync)(this.opts.loginsPath)) return;
43533
43970
  const at = this.now().toISOString();
43534
43971
  const history = {};
43535
43972
  for (const [user, userIps] of byUser) {
@@ -43741,8 +44178,8 @@ var RuleEngine = class {
43741
44178
  };
43742
44179
 
43743
44180
  // src/daemon/rules/loader.ts
43744
- var import_node_fs35 = require("fs");
43745
- var import_node_path26 = require("path");
44181
+ var import_node_fs36 = require("fs");
44182
+ var import_node_path27 = require("path");
43746
44183
 
43747
44184
  // src/daemon/rules/default-rules.ts
43748
44185
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -44143,11 +44580,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
44143
44580
  function loadAllRules(customDir) {
44144
44581
  const rules = [...DEFAULT_RULES];
44145
44582
  const dir = customDir || RULES_DIR;
44146
- if ((0, import_node_fs35.existsSync)(dir)) {
44147
- const files = (0, import_node_fs35.readdirSync)(dir).filter((f) => f.endsWith(".json"));
44583
+ if ((0, import_node_fs36.existsSync)(dir)) {
44584
+ const files = (0, import_node_fs36.readdirSync)(dir).filter((f) => f.endsWith(".json"));
44148
44585
  for (const file of files) {
44149
44586
  try {
44150
- const raw = (0, import_node_fs35.readFileSync)((0, import_node_path26.join)(dir, file), "utf-8");
44587
+ const raw = (0, import_node_fs36.readFileSync)((0, import_node_path27.join)(dir, file), "utf-8");
44151
44588
  const parsed = JSON.parse(raw);
44152
44589
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
44153
44590
  for (const rule of customRules) {
@@ -44179,23 +44616,23 @@ function loadAllRules(customDir) {
44179
44616
 
44180
44617
  // src/daemon/firewall/adapters.ts
44181
44618
  var import_node_child_process12 = require("child_process");
44182
- var import_node_fs36 = require("fs");
44183
- var import_node_path27 = require("path");
44184
- var import_node_net10 = require("net");
44619
+ var import_node_fs37 = require("fs");
44620
+ var import_node_path28 = require("path");
44621
+ var import_node_net11 = require("net");
44185
44622
  function assertValidFirewallIp(ip) {
44186
- if ((0, import_node_net10.isIP)(ip) !== 4) {
44623
+ if ((0, import_node_net11.isIP)(ip) !== 4) {
44187
44624
  throw new Error(`Invalid IPv4 address: ${ip}`);
44188
44625
  }
44189
44626
  }
44190
44627
  function assertBannableIp(ip) {
44191
- if ((0, import_node_net10.isIP)(ip) === 0) {
44628
+ if ((0, import_node_net11.isIP)(ip) === 0) {
44192
44629
  throw new Error(`Invalid IP address: ${ip}`);
44193
44630
  }
44194
44631
  }
44195
44632
  function writeIfAbsent(path, contents) {
44196
- (0, import_node_fs36.mkdirSync)((0, import_node_path27.dirname)(path), { recursive: true });
44633
+ (0, import_node_fs37.mkdirSync)((0, import_node_path28.dirname)(path), { recursive: true });
44197
44634
  try {
44198
- (0, import_node_fs36.writeFileSync)(path, contents, { flag: "wx" });
44635
+ (0, import_node_fs37.writeFileSync)(path, contents, { flag: "wx" });
44199
44636
  } catch (err) {
44200
44637
  if (err.code !== "EEXIST") throw err;
44201
44638
  }
@@ -44294,7 +44731,7 @@ var Fail2banAdapter = class {
44294
44731
  const status = this.client(["status", this.jail]);
44295
44732
  const line2 = status.split("\n").find((l) => /Banned IP list:/i.test(l));
44296
44733
  if (!line2) return [];
44297
- return line2.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net10.isIP)(s) !== 0);
44734
+ return line2.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net11.isIP)(s) !== 0);
44298
44735
  } catch {
44299
44736
  return [];
44300
44737
  }
@@ -44304,10 +44741,10 @@ var Fail2banAdapter = class {
44304
44741
  function parseBannedList(output) {
44305
44742
  const found = [];
44306
44743
  for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
44307
- if ((0, import_node_net10.isIP)(match[1]) !== 0) found.push(match[1]);
44744
+ if ((0, import_node_net11.isIP)(match[1]) !== 0) found.push(match[1]);
44308
44745
  }
44309
44746
  if (found.length > 0) return found;
44310
- return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net10.isIP)(s) !== 0);
44747
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net11.isIP)(s) !== 0);
44311
44748
  }
44312
44749
  var NftablesAdapter = class {
44313
44750
  name = "nftables";
@@ -44454,9 +44891,9 @@ function detectFirewallAdapter(backend = "auto") {
44454
44891
  }
44455
44892
 
44456
44893
  // src/daemon/firewall/remediation.ts
44457
- var import_node_fs37 = require("fs");
44894
+ var import_node_fs38 = require("fs");
44458
44895
  var import_node_child_process13 = require("child_process");
44459
- var import_node_net11 = require("net");
44896
+ var import_node_net12 = require("net");
44460
44897
  init_paths();
44461
44898
  init_backoff();
44462
44899
 
@@ -44467,12 +44904,12 @@ var systemResolver = {
44467
44904
  reverse: (ip) => import_node_dns.promises.reverse(ip),
44468
44905
  lookup: async (host) => (await import_node_dns.promises.lookup(host, { all: true })).map((a) => a.address)
44469
44906
  };
44470
- var TIMEOUT_MS = 2e3;
44907
+ var TIMEOUT_MS2 = 2e3;
44471
44908
  var CACHE_MS = 6 * 36e5;
44472
44909
  function withTimeout(p) {
44473
44910
  return Promise.race([
44474
44911
  p,
44475
- new Promise((_, reject) => setTimeout(() => reject(new Error("dns timeout")), TIMEOUT_MS).unref())
44912
+ new Promise((_, reject) => setTimeout(() => reject(new Error("dns timeout")), TIMEOUT_MS2).unref())
44476
44913
  ]);
44477
44914
  }
44478
44915
  function inCrawlerDomain(host) {
@@ -44525,19 +44962,19 @@ var defaultDiscovery = {
44525
44962
  const snapshot = takeSnapshot({
44526
44963
  readFile: (p) => {
44527
44964
  try {
44528
- return (0, import_node_fs37.readFileSync)(p, "utf-8");
44965
+ return (0, import_node_fs38.readFileSync)(p, "utf-8");
44529
44966
  } catch {
44530
44967
  return null;
44531
44968
  }
44532
44969
  },
44533
44970
  readDir: (p) => {
44534
44971
  try {
44535
- return (0, import_node_fs37.readdirSync)(p);
44972
+ return (0, import_node_fs38.readdirSync)(p);
44536
44973
  } catch {
44537
44974
  return null;
44538
44975
  }
44539
44976
  },
44540
- exists: (p) => (0, import_node_fs37.existsSync)(p)
44977
+ exists: (p) => (0, import_node_fs38.existsSync)(p)
44541
44978
  });
44542
44979
  const out = /* @__PURE__ */ new Set();
44543
44980
  for (const keys of Object.values(snapshot.keys)) {
@@ -44672,7 +45109,7 @@ var RemediationManager = class {
44672
45109
  if (remediation?.action !== "block") return;
44673
45110
  }
44674
45111
  const ip = event.source_ip;
44675
- if (!ip || (0, import_node_net11.isIP)(ip) === 0) return;
45112
+ if (!ip || (0, import_node_net12.isIP)(ip) === 0) return;
44676
45113
  if (this.isAllowlisted(ip)) return;
44677
45114
  if (this.blocklist.some((b) => b.ip === ip)) return;
44678
45115
  if (this.config.spare_verified_crawlers) {
@@ -44691,7 +45128,7 @@ var RemediationManager = class {
44691
45128
  * 4th offence and so on, clamped to `max_ban_seconds`.
44692
45129
  */
44693
45130
  async ban(ip, reason, opts = {}) {
44694
- if ((0, import_node_net11.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
45131
+ if ((0, import_node_net12.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
44695
45132
  if (this.isAllowlisted(ip)) {
44696
45133
  return { ok: false, error: `${ip} is protected and can never be blocked` };
44697
45134
  }
@@ -44952,7 +45389,7 @@ var RemediationManager = class {
44952
45389
  if (saved && typeof saved === "object" && this.config.protect_recent_operators) {
44953
45390
  const cutoff = Date.now() - this.config.operator_memory_seconds * 1e3;
44954
45391
  for (const [ip, at] of Object.entries(saved)) {
44955
- if (typeof at !== "number" || at < cutoff || !(0, import_node_net11.isIP)(ip)) continue;
45392
+ if (typeof at !== "number" || at < cutoff || !(0, import_node_net12.isIP)(ip)) continue;
44956
45393
  this.operators[ip] = at;
44957
45394
  if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
44958
45395
  }
@@ -44976,7 +45413,7 @@ var RemediationManager = class {
44976
45413
  }
44977
45414
  logLine(line2) {
44978
45415
  try {
44979
- (0, import_node_fs37.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
45416
+ (0, import_node_fs38.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
44980
45417
  `);
44981
45418
  } catch {
44982
45419
  }
@@ -45019,19 +45456,19 @@ function remediationSettings(section) {
45019
45456
  init_backoff();
45020
45457
 
45021
45458
  // src/daemon/watchdog-service.ts
45022
- var import_node_fs38 = require("fs");
45023
- var import_node_path28 = require("path");
45459
+ var import_node_fs39 = require("fs");
45460
+ var import_node_path29 = require("path");
45024
45461
  function defaultShareGid() {
45025
45462
  const isRoot4 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
45026
45463
  if (!isRoot4) return void 0;
45027
45464
  try {
45028
- return (0, import_node_fs38.statSync)("/var/log/auth.log").gid;
45465
+ return (0, import_node_fs39.statSync)("/var/log/auth.log").gid;
45029
45466
  } catch {
45030
45467
  return void 0;
45031
45468
  }
45032
45469
  }
45033
45470
  function startWatchdog(opts) {
45034
- const dir = opts.config?.dir ?? (0, import_node_path28.join)(opts.stateDir, WATCHDOG_DIRNAME);
45471
+ const dir = opts.config?.dir ?? (0, import_node_path29.join)(opts.stateDir, WATCHDOG_DIRNAME);
45035
45472
  const base = { dir, logged: 0, answered: 0, errored: 0 };
45036
45473
  if (opts.config?.enabled === false) {
45037
45474
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -45146,7 +45583,7 @@ function versionOfNode(path) {
45146
45583
  // src/daemon/index.ts
45147
45584
  function readVersion2() {
45148
45585
  try {
45149
- const pkg = JSON.parse((0, import_node_fs39.readFileSync)((0, import_node_path29.join)(__dirname, "..", "package.json"), "utf-8"));
45586
+ const pkg = JSON.parse((0, import_node_fs40.readFileSync)((0, import_node_path30.join)(__dirname, "..", "package.json"), "utf-8"));
45150
45587
  return pkg.version || "0.0.0";
45151
45588
  } catch {
45152
45589
  return "0.0.0";
@@ -45155,7 +45592,7 @@ function readVersion2() {
45155
45592
  async function runHardeningChecks() {
45156
45593
  const { stdout } = await (0, import_node_util.promisify)(import_node_child_process15.execFile)(
45157
45594
  process.execPath,
45158
- [(0, import_node_path29.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
45595
+ [(0, import_node_path30.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
45159
45596
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
45160
45597
  );
45161
45598
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -45169,7 +45606,7 @@ async function runHardeningChecks() {
45169
45606
  async function runPatchCheck() {
45170
45607
  const { stdout } = await (0, import_node_util.promisify)(import_node_child_process15.execFile)(
45171
45608
  process.execPath,
45172
- [(0, import_node_path29.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
45609
+ [(0, import_node_path30.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
45173
45610
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
45174
45611
  );
45175
45612
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -45177,7 +45614,7 @@ async function runPatchCheck() {
45177
45614
  }
45178
45615
  function logLine(line2) {
45179
45616
  try {
45180
- (0, import_node_fs39.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
45617
+ (0, import_node_fs40.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
45181
45618
  `);
45182
45619
  } catch {
45183
45620
  }
@@ -45219,7 +45656,7 @@ async function runDaemon() {
45219
45656
  } catch (err) {
45220
45657
  logLine(`[daemon] state db unavailable: ${err.message}`);
45221
45658
  }
45222
- const config = loadConfig((0, import_node_fs39.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
45659
+ const config = loadConfig((0, import_node_fs40.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
45223
45660
  configureAttackDetection(config.detection);
45224
45661
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
45225
45662
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -45283,7 +45720,7 @@ async function runDaemon() {
45283
45720
  const threatFeeds = new ThreatFeeds({
45284
45721
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
45285
45722
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
45286
- cachePath: (0, import_node_path29.join)(PATHS.stateDir, "threat-feeds.json"),
45723
+ cachePath: (0, import_node_path30.join)(PATHS.stateDir, "threat-feeds.json"),
45287
45724
  bus,
45288
45725
  log: logLine
45289
45726
  });
@@ -45291,9 +45728,9 @@ async function runDaemon() {
45291
45728
  const privilegeWatch = new PrivilegeWatch({
45292
45729
  settings: privilegeSettings(config.privileged),
45293
45730
  bus,
45294
- snapshotPath: (0, import_node_path29.join)(PATHS.stateDir, "privileges.json"),
45295
- loginsPath: (0, import_node_path29.join)(PATHS.stateDir, "login-countries.json"),
45296
- cursorPath: (0, import_node_path29.join)(PATHS.stateDir, "sudo-cursor.json"),
45731
+ snapshotPath: (0, import_node_path30.join)(PATHS.stateDir, "privileges.json"),
45732
+ loginsPath: (0, import_node_path30.join)(PATHS.stateDir, "login-countries.json"),
45733
+ cursorPath: (0, import_node_path30.join)(PATHS.stateDir, "sudo-cursor.json"),
45297
45734
  log: logLine
45298
45735
  });
45299
45736
  privilegeWatch.start();
@@ -45316,7 +45753,7 @@ async function runDaemon() {
45316
45753
  version,
45317
45754
  hostname: (0, import_node_os11.hostname)(),
45318
45755
  minSeverity,
45319
- spoolPath: (0, import_node_path29.join)(PATHS.stateDir, "cloud-spool.jsonl"),
45756
+ spoolPath: (0, import_node_path30.join)(PATHS.stateDir, "cloud-spool.jsonl"),
45320
45757
  log: logLine,
45321
45758
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
45322
45759
  runHardening: runHardeningChecks
@@ -45329,12 +45766,14 @@ async function runDaemon() {
45329
45766
  const link = currentLink();
45330
45767
  logLine(link ? `[cloud] reporting as server ${link.serverId} (org ${link.orgId}), detections >= ${minSeverity}` : "[cloud] not linked; run `threatcrush login` and `threatcrush servers link` to report to the dashboard");
45331
45768
  }
45769
+ const abuseReporter = new AbuseReporter({ bus, section: config.abuse_reporter, log: logLine });
45770
+ abuseReporter.start();
45332
45771
  const watchdog = startWatchdog({ bus, config: config.watchdog, stateDir: PATHS.stateDir, log: logLine });
45333
45772
  const autoUpdate = new AutoUpdate({
45334
45773
  version,
45335
45774
  settings: updateSettings(config.update),
45336
- pkgRoot: (0, import_node_path29.join)(__dirname, ".."),
45337
- statePath: (0, import_node_path29.join)(PATHS.stateDir, "auto-update.json"),
45775
+ pkgRoot: (0, import_node_path30.join)(__dirname, ".."),
45776
+ statePath: (0, import_node_path30.join)(PATHS.stateDir, "auto-update.json"),
45338
45777
  bus,
45339
45778
  log: logLine,
45340
45779
  restartDaemon
@@ -45365,6 +45804,10 @@ async function runDaemon() {
45365
45804
  await cloudSync?.stop();
45366
45805
  } catch {
45367
45806
  }
45807
+ try {
45808
+ abuseReporter.stop();
45809
+ } catch {
45810
+ }
45368
45811
  try {
45369
45812
  await moduleHost.stop();
45370
45813
  } catch {
@@ -45420,7 +45863,7 @@ var SYSTEM_SOCKET = "/var/run/threatcrush/threatcrushd.sock";
45420
45863
  function isRoot2() {
45421
45864
  return typeof process.getuid === "function" && process.getuid() === 0;
45422
45865
  }
45423
- var DAEMON_ENTRY = (0, import_node_path30.join)(__dirname, "daemon.js");
45866
+ var DAEMON_ENTRY = (0, import_node_path31.join)(__dirname, "daemon.js");
45424
45867
  async function daemonForeground() {
45425
45868
  await runDaemon();
45426
45869
  }
@@ -45441,7 +45884,7 @@ async function daemonStart() {
45441
45884
  return;
45442
45885
  }
45443
45886
  ensureRuntimeDirs();
45444
- if (!(0, import_node_fs40.existsSync)(DAEMON_ENTRY)) {
45887
+ if (!(0, import_node_fs41.existsSync)(DAEMON_ENTRY)) {
45445
45888
  console.log(source_default.red(` Daemon entry not found at ${DAEMON_ENTRY}.`));
45446
45889
  console.log(source_default.dim(" Reinstall with `threatcrush update` or `pnpm run build` in the cli package."));
45447
45890
  return;
@@ -45449,8 +45892,8 @@ async function daemonStart() {
45449
45892
  let out;
45450
45893
  let err;
45451
45894
  try {
45452
- out = (0, import_node_fs41.openSync)(PATHS.logFile, "a");
45453
- err = (0, import_node_fs41.openSync)(PATHS.logFile, "a");
45895
+ out = (0, import_node_fs42.openSync)(PATHS.logFile, "a");
45896
+ err = (0, import_node_fs42.openSync)(PATHS.logFile, "a");
45454
45897
  } catch (e) {
45455
45898
  const code = e.code;
45456
45899
  console.log(source_default.red(` \u2717 Cannot write daemon log at ${PATHS.logFile} (${code ?? "error"}).`));
@@ -45538,12 +45981,12 @@ async function waitForExit(pid, timeoutMs) {
45538
45981
  }
45539
45982
  async function releaseStaleSocket() {
45540
45983
  const deadline = Date.now() + 2e3;
45541
- while ((0, import_node_fs40.existsSync)(PATHS.socket) && Date.now() < deadline) {
45984
+ while ((0, import_node_fs41.existsSync)(PATHS.socket) && Date.now() < deadline) {
45542
45985
  await new Promise((r) => setTimeout(r, 50));
45543
45986
  }
45544
- if ((0, import_node_fs40.existsSync)(PATHS.socket)) {
45987
+ if ((0, import_node_fs41.existsSync)(PATHS.socket)) {
45545
45988
  try {
45546
- (0, import_node_fs40.unlinkSync)(PATHS.socket);
45989
+ (0, import_node_fs41.unlinkSync)(PATHS.socket);
45547
45990
  } catch {
45548
45991
  }
45549
45992
  }
@@ -45551,26 +45994,26 @@ async function releaseStaleSocket() {
45551
45994
 
45552
45995
  // src/commands/service.ts
45553
45996
  var import_node_child_process17 = require("child_process");
45554
- var import_node_fs42 = require("fs");
45555
- var import_node_path31 = require("path");
45997
+ var import_node_fs43 = require("fs");
45998
+ var import_node_path32 = require("path");
45556
45999
  var import_node_os12 = require("os");
45557
46000
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
45558
46001
  var DAEMON_UNIT_NAME = "threatcrushd.service";
45559
46002
  function resolveTemplate() {
45560
- const templatePath = (0, import_node_path31.join)(__dirname, "systemd", "threatcrushd.service");
45561
- if (!(0, import_node_fs42.existsSync)(templatePath)) {
46003
+ const templatePath = (0, import_node_path32.join)(__dirname, "systemd", "threatcrushd.service");
46004
+ if (!(0, import_node_fs43.existsSync)(templatePath)) {
45562
46005
  throw new Error(`systemd unit template not found at ${templatePath}`);
45563
46006
  }
45564
- return (0, import_node_fs42.readFileSync)(templatePath, "utf-8");
46007
+ return (0, import_node_fs43.readFileSync)(templatePath, "utf-8");
45565
46008
  }
45566
46009
  function stableBinPath(binPath) {
45567
46010
  const stable = binPath.replace(/\/\.pnpm\/[^/]+\/node_modules\//, "/node_modules/");
45568
46011
  if (stable === binPath) return binPath;
45569
- return (0, import_node_fs42.existsSync)(stable) ? stable : binPath;
46012
+ return (0, import_node_fs43.existsSync)(stable) ? stable : binPath;
45570
46013
  }
45571
46014
  function resolveBinPath() {
45572
46015
  const arg = process.argv[1];
45573
- if (arg && (0, import_node_fs42.existsSync)(arg)) return stableBinPath(arg);
46016
+ if (arg && (0, import_node_fs43.existsSync)(arg)) return stableBinPath(arg);
45574
46017
  try {
45575
46018
  return (0, import_node_child_process17.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
45576
46019
  } catch {
@@ -45580,11 +46023,11 @@ function resolveBinPath() {
45580
46023
  function stableNodePath(execPath) {
45581
46024
  const stable = execPath.replace(/(\/installs\/node\/)[^/]+\//, "$1latest/");
45582
46025
  if (stable === execPath) return execPath;
45583
- return (0, import_node_fs42.existsSync)(stable) ? stable : execPath;
46026
+ return (0, import_node_fs43.existsSync)(stable) ? stable : execPath;
45584
46027
  }
45585
46028
  function looksLikeNodeScript(path) {
45586
46029
  try {
45587
- const head = (0, import_node_fs42.readFileSync)(path, "utf-8").slice(0, 120);
46030
+ const head = (0, import_node_fs43.readFileSync)(path, "utf-8").slice(0, 120);
45588
46031
  return /^#!.*\bnode\b/.test(head);
45589
46032
  } catch {
45590
46033
  return false;
@@ -45624,7 +46067,7 @@ function callerHome() {
45624
46067
  try {
45625
46068
  const line2 = (0, import_node_child_process17.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
45626
46069
  const home = line2.split(":")[5];
45627
- return home && (0, import_node_fs42.existsSync)(home) ? home : null;
46070
+ return home && (0, import_node_fs43.existsSync)(home) ? home : null;
45628
46071
  } catch {
45629
46072
  return null;
45630
46073
  }
@@ -45632,13 +46075,13 @@ function callerHome() {
45632
46075
  function stopUserModeDaemon() {
45633
46076
  const home = callerHome();
45634
46077
  if (!home) return;
45635
- const runDir = (0, import_node_path31.join)(home, ".threatcrush", "run");
45636
- const pidFile = (0, import_node_path31.join)(runDir, "threatcrushd.pid");
45637
- const socket = (0, import_node_path31.join)(runDir, "threatcrushd.sock");
45638
- if (!(0, import_node_fs42.existsSync)(pidFile) && !(0, import_node_fs42.existsSync)(socket)) return;
46078
+ const runDir = (0, import_node_path32.join)(home, ".threatcrush", "run");
46079
+ const pidFile = (0, import_node_path32.join)(runDir, "threatcrushd.pid");
46080
+ const socket = (0, import_node_path32.join)(runDir, "threatcrushd.sock");
46081
+ if (!(0, import_node_fs43.existsSync)(pidFile) && !(0, import_node_fs43.existsSync)(socket)) return;
45639
46082
  let pid = null;
45640
46083
  try {
45641
- pid = Number.parseInt((0, import_node_fs42.readFileSync)(pidFile, "utf-8").trim(), 10);
46084
+ pid = Number.parseInt((0, import_node_fs43.readFileSync)(pidFile, "utf-8").trim(), 10);
45642
46085
  } catch {
45643
46086
  pid = null;
45644
46087
  }
@@ -45651,7 +46094,7 @@ function stopUserModeDaemon() {
45651
46094
  }
45652
46095
  for (const path of [socket, pidFile]) {
45653
46096
  try {
45654
- if ((0, import_node_fs42.existsSync)(path)) (0, import_node_fs42.rmSync)(path);
46097
+ if ((0, import_node_fs43.existsSync)(path)) (0, import_node_fs43.rmSync)(path);
45655
46098
  } catch {
45656
46099
  }
45657
46100
  }
@@ -45669,7 +46112,7 @@ async function installServiceCommand() {
45669
46112
  }
45670
46113
  const noSystemd = systemdUnavailableReason({
45671
46114
  hasSystemctl: (0, import_node_child_process17.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
45672
- booted: (0, import_node_fs42.existsSync)("/run/systemd/system")
46115
+ booted: (0, import_node_fs43.existsSync)("/run/systemd/system")
45673
46116
  });
45674
46117
  if (noSystemd) {
45675
46118
  console.log(source_default.red(` \u2717 systemd isn't available here: ${noSystemd}.`));
@@ -45691,7 +46134,7 @@ async function installServiceCommand() {
45691
46134
  const isNodeScript = looksLikeNodeScript(binPath);
45692
46135
  let nodePath = stableNodePath(process.execPath);
45693
46136
  if (isNodeScript && nodeVersionDir(binPath)) {
45694
- binPath = (0, import_node_fs42.realpathSync)(binPath);
46137
+ binPath = (0, import_node_fs43.realpathSync)(binPath);
45695
46138
  nodePath = process.execPath;
45696
46139
  }
45697
46140
  if (isNodeScript) {
@@ -45704,9 +46147,9 @@ async function installServiceCommand() {
45704
46147
  }
45705
46148
  }
45706
46149
  const exec = execStartCommand(binPath, nodePath, isNodeScript);
45707
- const configDir = (0, import_node_path31.join)((0, import_node_os12.homedir)(), ".threatcrush");
46150
+ const configDir = (0, import_node_path32.join)((0, import_node_os12.homedir)(), ".threatcrush");
45708
46151
  const unit = renderUnit(resolveTemplate(), { exec, binPath, configDir });
45709
- (0, import_node_fs42.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
46152
+ (0, import_node_fs43.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
45710
46153
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
45711
46154
  console.log(source_default.dim(` ExecStart=${exec}`));
45712
46155
  const nodeDir = nodeVersionDir(nodePath);
@@ -45759,9 +46202,9 @@ function renderLogrotate(logDir = "/var/log/threatcrush") {
45759
46202
  ].join("\n");
45760
46203
  }
45761
46204
  function installLogrotate() {
45762
- if (!(0, import_node_fs42.existsSync)((0, import_node_path31.dirname)(LOGROTATE_PATH))) return;
46205
+ if (!(0, import_node_fs43.existsSync)((0, import_node_path32.dirname)(LOGROTATE_PATH))) return;
45763
46206
  try {
45764
- (0, import_node_fs42.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
46207
+ (0, import_node_fs43.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
45765
46208
  console.log(source_default.green(` \u2713 Log rotation: ${LOGROTATE_PATH} (daily or 200M, keeps 7)`));
45766
46209
  } catch (err) {
45767
46210
  console.log(source_default.yellow(` ! Could not install log rotation: ${err.message}`));
@@ -45783,20 +46226,20 @@ function ensureSystemDirs(configDir) {
45783
46226
  ];
45784
46227
  let admGid2 = null;
45785
46228
  try {
45786
- admGid2 = (0, import_node_fs42.statSync)("/var/log/auth.log").gid;
46229
+ admGid2 = (0, import_node_fs43.statSync)("/var/log/auth.log").gid;
45787
46230
  } catch {
45788
46231
  }
45789
46232
  for (const { path, groupWritable, sticky } of dirs) {
45790
46233
  try {
45791
- (0, import_node_fs42.mkdirSync)(path, { recursive: true });
46234
+ (0, import_node_fs43.mkdirSync)(path, { recursive: true });
45792
46235
  } catch {
45793
46236
  }
45794
46237
  try {
45795
46238
  if (groupWritable && admGid2 !== null) {
45796
- (0, import_node_fs42.chmodSync)(path, sticky ? 1533 : 509);
46239
+ (0, import_node_fs43.chmodSync)(path, sticky ? 1533 : 509);
45797
46240
  (0, import_node_child_process17.execSync)(`chgrp adm ${path}`, { stdio: "ignore" });
45798
46241
  } else {
45799
- (0, import_node_fs42.chmodSync)(path, 493);
46242
+ (0, import_node_fs43.chmodSync)(path, 493);
45800
46243
  }
45801
46244
  } catch {
45802
46245
  }
@@ -45824,7 +46267,7 @@ async function uninstallServiceCommand() {
45824
46267
  } catch {
45825
46268
  }
45826
46269
  try {
45827
- if ((0, import_node_fs42.existsSync)(UNIT_PATH)) {
46270
+ if ((0, import_node_fs43.existsSync)(UNIT_PATH)) {
45828
46271
  (0, import_node_child_process17.execSync)(`rm -f ${UNIT_PATH}`);
45829
46272
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
45830
46273
  }
@@ -45838,7 +46281,7 @@ async function uninstallServiceCommand() {
45838
46281
  }
45839
46282
 
45840
46283
  // src/commands/save.ts
45841
- var import_node_fs43 = require("fs");
46284
+ var import_node_fs44 = require("fs");
45842
46285
  var import_toml5 = __toESM(require_toml());
45843
46286
  init_cli_config();
45844
46287
  init_paths();
@@ -45877,9 +46320,9 @@ async function saveCommand(opts = {}) {
45877
46320
  }
45878
46321
  const path = opts.config ?? PATHS.configFile;
45879
46322
  let config = {};
45880
- if ((0, import_node_fs43.existsSync)(path)) {
46323
+ if ((0, import_node_fs44.existsSync)(path)) {
45881
46324
  try {
45882
- config = import_toml5.default.parse((0, import_node_fs43.readFileSync)(path, "utf-8"));
46325
+ config = import_toml5.default.parse((0, import_node_fs44.readFileSync)(path, "utf-8"));
45883
46326
  } catch (err) {
45884
46327
  console.log(source_default.red(` \u2717 ${path} is not valid TOML: ${err.message}
45885
46328
  `));
@@ -45992,8 +46435,8 @@ function welcomeCommand() {
45992
46435
  }
45993
46436
 
45994
46437
  // src/commands/properties.ts
45995
- var import_node_fs44 = require("fs");
45996
- var import_node_path32 = require("path");
46438
+ var import_node_fs45 = require("fs");
46439
+ var import_node_path33 = require("path");
45997
46440
  var import_node_readline4 = __toESM(require("readline"));
45998
46441
  init_cli_config();
45999
46442
  var API_URL5 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
@@ -46323,8 +46766,8 @@ async function propertiesRunsCommand(opts) {
46323
46766
  }
46324
46767
  }
46325
46768
  function parseImportFile(path) {
46326
- const ext = (0, import_node_path32.extname)(path).toLowerCase();
46327
- const raw = (0, import_node_fs44.readFileSync)(path, "utf-8");
46769
+ const ext = (0, import_node_path33.extname)(path).toLowerCase();
46770
+ const raw = (0, import_node_fs45.readFileSync)(path, "utf-8");
46328
46771
  if (ext === ".json") {
46329
46772
  const parsed = JSON.parse(raw);
46330
46773
  if (!Array.isArray(parsed)) throw new Error("JSON must be an array of objects");
@@ -46519,7 +46962,7 @@ async function rulesCommand(opts) {
46519
46962
  }
46520
46963
 
46521
46964
  // src/commands/harden.ts
46522
- var import_node_fs45 = require("fs");
46965
+ var import_node_fs46 = require("fs");
46523
46966
  var import_node_child_process18 = require("child_process");
46524
46967
  init_cli_config();
46525
46968
  function tryExec(cmd) {
@@ -46531,7 +46974,7 @@ function tryExec(cmd) {
46531
46974
  }
46532
46975
  function tryRead(path) {
46533
46976
  try {
46534
- return (0, import_node_fs45.readFileSync)(path, "utf-8");
46977
+ return (0, import_node_fs46.readFileSync)(path, "utf-8");
46535
46978
  } catch {
46536
46979
  return null;
46537
46980
  }
@@ -46635,8 +47078,8 @@ function checkSshWeakConfig() {
46635
47078
  };
46636
47079
  }
46637
47080
  function checkAutoUpdates() {
46638
- const unattended = (0, import_node_fs45.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs45.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
46639
- const dnfAuto = (0, import_node_fs45.existsSync)("/etc/dnf/automatic.conf");
47081
+ const unattended = (0, import_node_fs46.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs46.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
47082
+ const dnfAuto = (0, import_node_fs46.existsSync)("/etc/dnf/automatic.conf");
46640
47083
  if (unattended || dnfAuto) {
46641
47084
  return {
46642
47085
  key: "auto-updates",
@@ -46762,7 +47205,7 @@ function checkFail2ban() {
46762
47205
  explanation: "fail2ban is installed and running."
46763
47206
  };
46764
47207
  }
46765
- if ((0, import_node_fs45.existsSync)("/etc/fail2ban/fail2ban.conf")) {
47208
+ if ((0, import_node_fs46.existsSync)("/etc/fail2ban/fail2ban.conf")) {
46766
47209
  return {
46767
47210
  key: checkKey,
46768
47211
  status: "warn",
@@ -46948,8 +47391,8 @@ async function hardenCommand(opts) {
46948
47391
  }
46949
47392
 
46950
47393
  // src/core/patches/index.ts
46951
- var import_node_fs46 = require("fs");
46952
- var import_node_path33 = require("path");
47394
+ var import_node_fs47 = require("fs");
47395
+ var import_node_path34 = require("path");
46953
47396
  var import_node_child_process19 = require("child_process");
46954
47397
  var import_node_util2 = require("util");
46955
47398
 
@@ -47109,9 +47552,9 @@ async function osvRecords(doFetch, ecosystem, source, version) {
47109
47552
  function newestReleaseMtime(dir) {
47110
47553
  try {
47111
47554
  let newest = 0;
47112
- for (const name of (0, import_node_fs46.readdirSync)(dir)) {
47555
+ for (const name of (0, import_node_fs47.readdirSync)(dir)) {
47113
47556
  if (!/Release$/.test(name)) continue;
47114
- newest = Math.max(newest, (0, import_node_fs46.statSync)((0, import_node_path33.join)(dir, name)).mtimeMs);
47557
+ newest = Math.max(newest, (0, import_node_fs47.statSync)((0, import_node_path34.join)(dir, name)).mtimeMs);
47115
47558
  }
47116
47559
  return newest > 0 ? new Date(newest) : null;
47117
47560
  } catch {
@@ -47128,7 +47571,7 @@ async function checkPatches(opts = {}) {
47128
47571
  let osText = opts.osRelease;
47129
47572
  if (osText === void 0) {
47130
47573
  try {
47131
- osText = (0, import_node_fs46.readFileSync)("/etc/os-release", "utf-8");
47574
+ osText = (0, import_node_fs47.readFileSync)("/etc/os-release", "utf-8");
47132
47575
  } catch {
47133
47576
  osText = "";
47134
47577
  }
@@ -47354,25 +47797,25 @@ async function patchesCommand(opts) {
47354
47797
  }
47355
47798
 
47356
47799
  // src/commands/feeds.ts
47357
- var import_node_net12 = require("net");
47358
- var import_node_path35 = require("path");
47800
+ var import_node_net13 = require("net");
47801
+ var import_node_path36 = require("path");
47359
47802
  init_paths();
47360
47803
 
47361
47804
  // src/commands/feeds-resolver.ts
47362
47805
  var import_node_child_process20 = require("child_process");
47363
- var import_node_fs47 = require("fs");
47364
- var import_node_path34 = require("path");
47806
+ var import_node_fs48 = require("fs");
47807
+ var import_node_path35 = require("path");
47365
47808
  var realIO = {
47366
- exists: (p) => (0, import_node_fs47.existsSync)(p),
47809
+ exists: (p) => (0, import_node_fs48.existsSync)(p),
47367
47810
  read: (p) => {
47368
47811
  try {
47369
- return (0, import_node_fs47.readFileSync)(p, "utf-8");
47812
+ return (0, import_node_fs48.readFileSync)(p, "utf-8");
47370
47813
  } catch {
47371
47814
  return null;
47372
47815
  }
47373
47816
  },
47374
- write: (p, c) => (0, import_node_fs47.writeFileSync)(p, c),
47375
- remove: (p) => (0, import_node_fs47.rmSync)(p, { force: true }),
47817
+ write: (p, c) => (0, import_node_fs48.writeFileSync)(p, c),
47818
+ remove: (p) => (0, import_node_fs48.rmSync)(p, { force: true }),
47376
47819
  run: (cmd, args) => {
47377
47820
  const r = (0, import_node_child_process20.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 3e4 });
47378
47821
  return { code: r.status ?? 1, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() };
@@ -47382,17 +47825,17 @@ var APPARMOR_LOCAL = "/etc/apparmor.d/local/usr.sbin.unbound";
47382
47825
  var APPARMOR_PROFILE = "/etc/apparmor.d/usr.sbin.unbound";
47383
47826
  function hookContent(resolver, stateDir) {
47384
47827
  const head = "# Installed by `threatcrush feeds resolver install`; `threatcrush feeds resolver remove` takes it out.\n";
47385
- return resolver === "dnsmasq" ? `${head}addn-hosts=${(0, import_node_path34.join)(stateDir, RESOLVER_FILES.hosts)}
47386
- ` : `${head}include: "${(0, import_node_path34.join)(stateDir, RESOLVER_FILES.unbound)}"
47828
+ return resolver === "dnsmasq" ? `${head}addn-hosts=${(0, import_node_path35.join)(stateDir, RESOLVER_FILES.hosts)}
47829
+ ` : `${head}include: "${(0, import_node_path35.join)(stateDir, RESOLVER_FILES.unbound)}"
47387
47830
  `;
47388
47831
  }
47389
47832
  function apparmorRule(stateDir) {
47390
- return ` ${(0, import_node_path34.join)(stateDir, RESOLVER_FILES.unbound)} r, # threatcrush`;
47833
+ return ` ${(0, import_node_path35.join)(stateDir, RESOLVER_FILES.unbound)} r, # threatcrush`;
47391
47834
  }
47392
47835
  function detectResolvers(io = realIO) {
47393
47836
  const found = [];
47394
- if (io.exists((0, import_node_path34.dirname)(RESOLVER_HOOKS.dnsmasq)) && io.run("dnsmasq", ["--version"]).code === 0) found.push("dnsmasq");
47395
- if (io.exists((0, import_node_path34.dirname)(RESOLVER_HOOKS.unbound)) && io.run("unbound-checkconf", ["-h"]).code !== 127) found.push("unbound");
47837
+ if (io.exists((0, import_node_path35.dirname)(RESOLVER_HOOKS.dnsmasq)) && io.run("dnsmasq", ["--version"]).code === 0) found.push("dnsmasq");
47838
+ if (io.exists((0, import_node_path35.dirname)(RESOLVER_HOOKS.unbound)) && io.run("unbound-checkconf", ["-h"]).code !== 127) found.push("unbound");
47396
47839
  return found;
47397
47840
  }
47398
47841
  function check(resolver, io) {
@@ -47405,7 +47848,7 @@ function restartIfActive(resolver, io) {
47405
47848
  }
47406
47849
  function installHook(resolver, stateDir, io = realIO) {
47407
47850
  const hook = RESOLVER_HOOKS[resolver];
47408
- const file = (0, import_node_path34.join)(stateDir, resolver === "dnsmasq" ? RESOLVER_FILES.hosts : RESOLVER_FILES.unbound);
47851
+ const file = (0, import_node_path35.join)(stateDir, resolver === "dnsmasq" ? RESOLVER_FILES.hosts : RESOLVER_FILES.unbound);
47409
47852
  if (!io.exists(file)) io.write(file, resolver === "dnsmasq" ? hostsBlocklist([]) : unboundBlocklist([]));
47410
47853
  io.write(hook, hookContent(resolver, stateDir));
47411
47854
  if (resolver === "unbound" && io.exists(APPARMOR_LOCAL)) {
@@ -47466,8 +47909,8 @@ function resolverCommand(sub, stateDir, io = realIO) {
47466
47909
  }
47467
47910
  return failed ? 1 : 0;
47468
47911
  }
47469
- const hosts = io.read((0, import_node_path34.join)(stateDir, RESOLVER_FILES.hosts));
47470
- const unbound = io.read((0, import_node_path34.join)(stateDir, RESOLVER_FILES.unbound));
47912
+ const hosts = io.read((0, import_node_path35.join)(stateDir, RESOLVER_FILES.hosts));
47913
+ const unbound = io.read((0, import_node_path35.join)(stateDir, RESOLVER_FILES.unbound));
47471
47914
  console.log(` resolvers here: ${found.join(", ") || "none that can block (systemd-resolved only?)"}`);
47472
47915
  for (const r of ["dnsmasq", "unbound"]) {
47473
47916
  console.log(` ${r.padEnd(8)} hook ${io.exists(RESOLVER_HOOKS[r]) ? source_default.green("installed") : source_default.gray("not installed")}`);
@@ -47479,11 +47922,11 @@ function resolverCommand(sub, stateDir, io = realIO) {
47479
47922
  // src/commands/feeds.ts
47480
47923
  async function loadSet() {
47481
47924
  for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
47482
- const path = (0, import_node_path35.join)(dir, "threat-feeds.json");
47925
+ const path = (0, import_node_path36.join)(dir, "threat-feeds.json");
47483
47926
  const set = readFeedCache(path);
47484
47927
  if (set) return { set, from: path };
47485
47928
  }
47486
- const settings = threatFeedSettings(loadConfig((0, import_node_path35.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
47929
+ const settings = threatFeedSettings(loadConfig((0, import_node_path36.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
47487
47930
  return { set: await fetchFeeds(settings), from: "abuse.ch (live; no daemon cache readable)" };
47488
47931
  }
47489
47932
  async function feedsCommand(action, value, opts) {
@@ -47498,8 +47941,8 @@ async function feedsCommand(action, value, opts) {
47498
47941
  process.exitCode = 2;
47499
47942
  return;
47500
47943
  }
47501
- const ipHit = (0, import_node_net12.isIP)(value) ? matchIp(value, set) : null;
47502
- const domainHit = (0, import_node_net12.isIP)(value) ? null : matchDomain(value, set);
47944
+ const ipHit = (0, import_node_net13.isIP)(value) ? matchIp(value, set) : null;
47945
+ const domainHit = (0, import_node_net13.isIP)(value) ? null : matchDomain(value, set);
47503
47946
  const listed = ipHit ?? domainHit?.indicator ?? null;
47504
47947
  if (opts.json) {
47505
47948
  console.log(JSON.stringify({ value, listed: Boolean(listed), indicator: listed, matched: domainHit?.domain ?? (ipHit ? value : null), fetched_at: set.fetched_at }, null, 2));
@@ -47527,7 +47970,7 @@ async function feedsCommand(action, value, opts) {
47527
47970
  }
47528
47971
 
47529
47972
  // src/commands/privileged.ts
47530
- var import_node_fs48 = require("fs");
47973
+ var import_node_fs49 = require("fs");
47531
47974
  init_paths();
47532
47975
  var SEV2 = {
47533
47976
  critical: source_default.red.bold,
@@ -47540,19 +47983,19 @@ async function privilegedCommand(opts) {
47540
47983
  const snapshot = takeSnapshot({
47541
47984
  readFile: (p) => {
47542
47985
  try {
47543
- return (0, import_node_fs48.readFileSync)(p, "utf-8");
47986
+ return (0, import_node_fs49.readFileSync)(p, "utf-8");
47544
47987
  } catch {
47545
47988
  return null;
47546
47989
  }
47547
47990
  },
47548
47991
  readDir: (p) => {
47549
47992
  try {
47550
- return (0, import_node_fs48.readdirSync)(p);
47993
+ return (0, import_node_fs49.readdirSync)(p);
47551
47994
  } catch {
47552
47995
  return null;
47553
47996
  }
47554
47997
  },
47555
- exists: (p) => (0, import_node_fs48.existsSync)(p)
47998
+ exists: (p) => (0, import_node_fs49.existsSync)(p)
47556
47999
  });
47557
48000
  let events = [];
47558
48001
  let ledgerNote = "";
@@ -47733,6 +48176,86 @@ async function allowlistCommand(opts) {
47733
48176
  console.log();
47734
48177
  }
47735
48178
 
48179
+ // src/commands/abuse.ts
48180
+ var import_node_fs50 = require("fs");
48181
+ init_paths();
48182
+ function rows(records) {
48183
+ if (records.length === 0) {
48184
+ console.log(source_default.dim(" (none)"));
48185
+ return;
48186
+ }
48187
+ for (const r of records) {
48188
+ const when = r.reported_at.replace("T", " ").slice(0, 19);
48189
+ const tag = r.retracted_at ? source_default.yellow("retracted") : r.mode === "dry_run" ? source_default.cyan("would-report") : r.destinations.every((d) => d.ok) ? source_default.green("reported") : source_default.red("partial/failed");
48190
+ console.log(
48191
+ ` ${source_default.bold(r.id)} ${source_default.white(r.ip.padEnd(39))} ${source_default.dim(when)} ${tag} ${source_default.dim(`cats ${r.categories.join(",")} \xB7 ${r.signals} signals`)}`
48192
+ );
48193
+ if (r.destinations.length > 0) {
48194
+ console.log(source_default.dim(` ${r.destinations.map((d) => `${d.destination}: ${d.ok ? "ok" : "fail"} (${d.detail})`).join(" \xB7 ")}`));
48195
+ }
48196
+ if (r.retract_note) console.log(source_default.dim(` retracted: ${r.retract_note}`));
48197
+ }
48198
+ }
48199
+ function abuseHistoryCommand(opts = {}) {
48200
+ const all = currentReports(opts.dir);
48201
+ if (opts.json) {
48202
+ console.log(JSON.stringify(all, null, 2));
48203
+ return;
48204
+ }
48205
+ console.log(source_default.bold(`
48206
+ Abuse reports (${all.length})
48207
+ `));
48208
+ rows(all);
48209
+ console.log();
48210
+ }
48211
+ function abusePendingCommand(opts = {}) {
48212
+ const pending = currentReports(opts.dir).filter((r) => r.mode === "dry_run" && !r.retracted_at);
48213
+ if (opts.json) {
48214
+ console.log(JSON.stringify(pending, null, 2));
48215
+ return;
48216
+ }
48217
+ console.log(source_default.bold(`
48218
+ Would report (${pending.length}) \u2014 dry-run, nothing sent
48219
+ `));
48220
+ rows(pending);
48221
+ console.log();
48222
+ }
48223
+ function abuseRetractCommand(id, opts = {}) {
48224
+ const existing = findReport(id, opts.dir);
48225
+ if (!existing) {
48226
+ console.error(source_default.red(`No report with id ${id}.`));
48227
+ process.exitCode = 1;
48228
+ return;
48229
+ }
48230
+ const note = opts.note || "retracted by operator";
48231
+ const record = markRetracted(id, note, opts.dir);
48232
+ console.log(source_default.yellow(`Retracted ${record?.id} (${record?.ip}).`));
48233
+ console.log(
48234
+ source_default.dim(
48235
+ "Removed from our published feed. AbuseIPDB and StopForumSpam have no delete API \u2014 show this record to the upstream to have the report removed by hand."
48236
+ )
48237
+ );
48238
+ }
48239
+ function abuseStatusCommand(opts = {}) {
48240
+ const config = loadConfig((0, import_node_fs50.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
48241
+ const cfg = resolveConfig(config.abuse_reporter);
48242
+ const hasKey2 = Boolean(cfg.keys.abuseipdb || cfg.keys.stopforumspam);
48243
+ const active2 = cfg.enabled && (cfg.dryRun || hasKey2);
48244
+ console.log(source_default.bold("\nAbuse reporter\n"));
48245
+ console.log(` status ${active2 ? source_default.green("active") : source_default.yellow("inert")}${!cfg.enabled ? source_default.dim(" (disabled)") : !hasKey2 && !cfg.dryRun ? source_default.dim(" (no API key set)") : ""}`);
48246
+ console.log(` mode ${cfg.dryRun ? source_default.cyan("dry_run") : source_default.green("live")}`);
48247
+ console.log(` destinations ${cfg.destinations.join(", ")}`);
48248
+ console.log(` keys abuseipdb=${cfg.keys.abuseipdb ? "set" : "\u2014"} stopforumspam=${cfg.keys.stopforumspam ? "set" : "\u2014"}`);
48249
+ console.log(` evidence bar >=${cfg.minCorroboratingSignals} signals + completed handshake, cooling-off ${Math.round(cfg.coolingOffSeconds / 60)}m`);
48250
+ console.log(` rate limits <=${cfg.maxReportsPerHour}/h, ${cfg.maxPerSourcePerDay}/source/day`);
48251
+ const reports = currentReports(opts.dir);
48252
+ console.log(` reported ${reports.filter((r) => r.mode === "live" && !r.retracted_at).length} live, ${reports.filter((r) => r.mode === "dry_run").length} dry-run`);
48253
+ if (!hasKey2 && !cfg.dryRun) {
48254
+ console.log(source_default.dim("\n Set ABUSEIPDB_API_KEY (or [abuse-reporter] abuseipdb_api_key) to begin reporting."));
48255
+ }
48256
+ console.log();
48257
+ }
48258
+
47736
48259
  // src/index.ts
47737
48260
  init_paths();
47738
48261
 
@@ -47856,7 +48379,7 @@ ${source_default.dim(" C R U S H")}
47856
48379
  var API_URL6 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
47857
48380
  var PKG_NAME2 = "@profullstack/threatcrush";
47858
48381
  var DESKTOP_PKG_NAME = "@profullstack/threatcrush-desktop";
47859
- var INSTALL_CONFIG_PATH = (0, import_node_path36.join)((0, import_node_os13.homedir)(), ".threatcrush", "install.json");
48382
+ var INSTALL_CONFIG_PATH = (0, import_node_path37.join)((0, import_node_os13.homedir)(), ".threatcrush", "install.json");
47860
48383
  function detectPackageManager() {
47861
48384
  try {
47862
48385
  const npmGlobal = (0, import_node_child_process22.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
@@ -47882,7 +48405,7 @@ function detectPackageManager() {
47882
48405
  }
47883
48406
  function readInstallConfig() {
47884
48407
  try {
47885
- return JSON.parse((0, import_node_fs49.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
48408
+ return JSON.parse((0, import_node_fs51.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
47886
48409
  } catch {
47887
48410
  return {};
47888
48411
  }
@@ -48078,6 +48601,21 @@ watchdogCmd.command("mark <id> <status>").description("Record a verdict: hole |
48078
48601
  watchdogCmd.command("path").description("Print the watchdog log directory").action((_opts, cmd) => {
48079
48602
  watchdogPathCommand(cmd.optsWithGlobals());
48080
48603
  });
48604
+ var abuseCmd = program2.command("abuse").description("Report confirmed attack sources to shared feeds (AbuseIPDB), and see what was reported").option("--dir <dir>", "Abuse-report audit directory").action((_opts, cmd) => {
48605
+ abuseStatusCommand(cmd.optsWithGlobals());
48606
+ });
48607
+ abuseCmd.command("status").description("Whether reporting is active, the evidence bar, and the counts").action((_opts, cmd) => {
48608
+ abuseStatusCommand(cmd.optsWithGlobals());
48609
+ });
48610
+ abuseCmd.command("history").alias("list").alias("ls").description("Everything reported (or would-be, in dry-run), newest first").option("--json", "Output as JSON").action((_opts, cmd) => {
48611
+ abuseHistoryCommand(cmd.optsWithGlobals());
48612
+ });
48613
+ abuseCmd.command("pending").description("Sources judged reportable but not sent (dry-run), with their evidence").option("--json", "Output as JSON").action((_opts, cmd) => {
48614
+ abusePendingCommand(cmd.optsWithGlobals());
48615
+ });
48616
+ abuseCmd.command("retract <id>").description("Withdraw a report from our feed and record it for the upstream").option("--note <text>", "Why it was wrong").action((id, _opts, cmd) => {
48617
+ abuseRetractCommand(id, cmd.optsWithGlobals());
48618
+ });
48081
48619
  program2.command("init").description("Sign in, auto-detect services, and configure ThreatCrush").option("-y, --yes", "Don't ask; answer yes to every question").option("--offline", "Skip signing in to threatcrush.com").action(async (opts) => {
48082
48620
  await initCommand({ yes: opts.yes, offline: opts.offline });
48083
48621
  });
@@ -48193,16 +48731,16 @@ program2.command("uninstall-service").description("Remove the threatcrushd syste
48193
48731
  });
48194
48732
  program2.command("logs").description("Tail daemon logs").action(async () => {
48195
48733
  console.log(LOGO2);
48196
- const logPath = PATHS.logFile;
48197
- if (!(0, import_node_fs49.existsSync)(logPath)) {
48198
- console.log(source_default.yellow(` No log file found at ${logPath}`));
48734
+ const logPath2 = PATHS.logFile;
48735
+ if (!(0, import_node_fs51.existsSync)(logPath2)) {
48736
+ console.log(source_default.yellow(` No log file found at ${logPath2}`));
48199
48737
  console.log(source_default.dim(" Start the daemon first with `threatcrush start`\n"));
48200
48738
  return;
48201
48739
  }
48202
- console.log(source_default.green(` Tailing ${logPath}...
48740
+ console.log(source_default.green(` Tailing ${logPath2}...
48203
48741
  `));
48204
48742
  console.log(source_default.gray(" Press Ctrl+C to stop\n"));
48205
- (0, import_node_child_process22.execSync)(`tail -f ${logPath}`, { stdio: "inherit" });
48743
+ (0, import_node_child_process22.execSync)(`tail -f ${logPath2}`, { stdio: "inherit" });
48206
48744
  });
48207
48745
  program2.command("update").description("Update ThreatCrush CLI and installed bundle").option("--cli", "Update CLI only").option("--modules", "Update modules only").option("--desktop", "Update desktop app too").action(async (opts) => {
48208
48746
  console.log(LOGO2);
@@ -48367,10 +48905,10 @@ storeCmd.command("search <query>").description("Search for modules in the store"
48367
48905
  });
48368
48906
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
48369
48907
  console.log(LOGO2);
48370
- const configPath = (0, import_node_path36.join)((0, import_node_os13.homedir)(), ".threatcrush", "config.json");
48908
+ const configPath = (0, import_node_path37.join)((0, import_node_os13.homedir)(), ".threatcrush", "config.json");
48371
48909
  let email = "";
48372
48910
  try {
48373
- const config = JSON.parse((0, import_node_fs49.readFileSync)(configPath, "utf-8"));
48911
+ const config = JSON.parse((0, import_node_fs51.readFileSync)(configPath, "utf-8"));
48374
48912
  email = config.email || "";
48375
48913
  } catch {
48376
48914
  }
@@ -48387,9 +48925,9 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
48387
48925
  return;
48388
48926
  }
48389
48927
  try {
48390
- const dir = (0, import_node_path36.join)((0, import_node_os13.homedir)(), ".threatcrush");
48391
- if (!(0, import_node_fs49.existsSync)(dir)) (0, import_node_fs49.mkdirSync)(dir, { recursive: true });
48392
- (0, import_node_fs49.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
48928
+ const dir = (0, import_node_path37.join)((0, import_node_os13.homedir)(), ".threatcrush");
48929
+ if (!(0, import_node_fs51.existsSync)(dir)) (0, import_node_fs51.mkdirSync)(dir, { recursive: true });
48930
+ (0, import_node_fs51.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
48393
48931
  console.log(source_default.dim(` Saved email to ${configPath}`));
48394
48932
  } catch {
48395
48933
  }