@profullstack/threatcrush 0.15.0 → 0.15.2

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
@@ -56786,6 +56786,7 @@ var import_node_readline3 = require("readline");
56786
56786
  var import_node_fs44 = require("fs");
56787
56787
  var import_node_path30 = require("path");
56788
56788
  var import_node_net10 = require("net");
56789
+ var CARRY_MAX_MS = 24 * 36e5;
56789
56790
  var FEEDS = {
56790
56791
  /** POST `{ query: 'get_iocs', days }` with an `Auth-Key` header. */
56791
56792
  threatfoxApi: "https://threatfox-api.abuse.ch/api/v1/",
@@ -57009,11 +57010,14 @@ function buildFeedSet(parts, allow, sources, now = /* @__PURE__ */ new Date()) {
57009
57010
  }
57010
57011
  return { fetched_at: now.toISOString(), ips, domains, sources, skipped_shared: skipped };
57011
57012
  }
57013
+ var FETCH_ATTEMPTS = 3;
57014
+ var FatalFeedError = class extends Error {
57015
+ };
57012
57016
  function redact(message, key) {
57013
57017
  if (!key) return message;
57014
57018
  return message.split(key).join("<auth-key>").split(encodeURIComponent(key)).join("<auth-key>");
57015
57019
  }
57016
- async function fetchFeeds(settings, fetchImpl = fetch) {
57020
+ async function fetchFeeds(settings, fetchImpl = fetch, retryDelayMs = 5e3, previous = null, now = /* @__PURE__ */ new Date()) {
57017
57021
  const sources = [];
57018
57022
  const parts = [];
57019
57023
  const key = settings.authKey?.trim() || void 0;
@@ -57025,17 +57029,31 @@ async function fetchFeeds(settings, fetchImpl = fetch) {
57025
57029
  }
57026
57030
  try {
57027
57031
  const extra = request2.init?.headers ?? {};
57028
- const res = await fetchImpl(request2.url, { ...request2.init, signal: AbortSignal.timeout(6e4), headers: { ...ua, ...extra } });
57029
- if (res.status === 401 || res.status === 403) throw new Error(`HTTP ${res.status}: abuse.ch refused the Auth-Key`);
57030
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
57031
- const text = await res.text();
57032
- const type = res.headers.get("content-type") ?? "";
57033
- if (type.includes("text/html") || /^\s*<(!doctype|html)/i.test(text)) throw new Error(`HTTP ${res.status} but an HTML page, not feed data`);
57034
- const part = parse3(text);
57032
+ let part;
57033
+ for (let attempt = 1; ; attempt++) {
57034
+ try {
57035
+ const res = await fetchImpl(request2.url, { ...request2.init, signal: AbortSignal.timeout(6e4), headers: { ...ua, ...extra } });
57036
+ if (res.status === 401 || res.status === 403) throw new FatalFeedError(`HTTP ${res.status}: abuse.ch refused the Auth-Key`);
57037
+ if (res.status >= 400 && res.status < 500) throw new FatalFeedError(`HTTP ${res.status}`);
57038
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
57039
+ const text = await res.text();
57040
+ const type = res.headers.get("content-type") ?? "";
57041
+ if (type.includes("text/html") || /^\s*<(!doctype|html)/i.test(text)) throw new FatalFeedError(`HTTP ${res.status} but an HTML page, not feed data`);
57042
+ part = parse3(text);
57043
+ break;
57044
+ } catch (err) {
57045
+ const retryable = !(err instanceof FatalFeedError) && !/^ThreatFox API: /.test(err.message);
57046
+ if (!retryable || attempt >= FETCH_ATTEMPTS) throw err;
57047
+ await new Promise((r) => setTimeout(r, retryDelayMs * attempt));
57048
+ }
57049
+ }
57035
57050
  const count = (part.ips?.size ?? 0) + (part.domains?.size ?? 0);
57036
57051
  if (count === 0 && !emptyOk) throw new Error("no entries in the response");
57052
+ for (const map of [part.ips, part.domains]) {
57053
+ for (const [k, ind] of map ?? []) map.set(k, { ...ind, source: feed });
57054
+ }
57037
57055
  parts.push(part);
57038
- sources.push({ feed, ok: true, count });
57056
+ sources.push({ feed, ok: true, count, last_ok_at: now.toISOString() });
57039
57057
  } catch (err) {
57040
57058
  sources.push({ feed, ok: false, count: 0, error: redact(err.message, key) });
57041
57059
  }
@@ -57055,8 +57073,26 @@ async function fetchFeeds(settings, fetchImpl = fetch) {
57055
57073
  // Feodo has been near-empty since 2025; an empty list there is real.
57056
57074
  get2("feodo", { url: FEEDS.feodoIps }, (t) => ({ ips: parseIpList(t, "feodo") }), true)
57057
57075
  ]);
57076
+ carryForward(previous, sources, parts, now);
57058
57077
  sources.sort((a, b) => a.feed.localeCompare(b.feed));
57059
- return buildFeedSet(parts, settings.allow, sources);
57078
+ return buildFeedSet(parts, settings.allow, sources, now);
57079
+ }
57080
+ function carryForward(previous, sources, parts, now) {
57081
+ if (!previous) return;
57082
+ for (const s of sources) {
57083
+ if (s.ok || s.error === NEEDS_KEY) continue;
57084
+ const prev = previous.sources?.find((p) => p.feed === s.feed);
57085
+ const lastOk = prev?.last_ok_at;
57086
+ if (!lastOk || now.getTime() - Date.parse(lastOk) > CARRY_MAX_MS) continue;
57087
+ const part = { ips: /* @__PURE__ */ new Map(), domains: /* @__PURE__ */ new Map() };
57088
+ for (const [ip, ind] of Object.entries(previous.ips)) if (ind.source === s.feed) part.ips.set(ip, ind);
57089
+ for (const [d, ind] of Object.entries(previous.domains)) if (ind.source === s.feed) part.domains.set(d, ind);
57090
+ const kept = part.ips.size + part.domains.size;
57091
+ s.last_ok_at = lastOk;
57092
+ if (!kept) continue;
57093
+ parts.push(part);
57094
+ s.carried = kept;
57095
+ }
57060
57096
  }
57061
57097
  function readFeedCache(path2) {
57062
57098
  try {
@@ -59680,7 +59716,7 @@ var ThreatFeeds = class {
59680
59716
  }
59681
59717
  async refresh() {
59682
59718
  try {
59683
- const set = await fetchFeeds(this.opts.settings, this.opts.fetchImpl);
59719
+ const set = await fetchFeeds(this.opts.settings, this.opts.fetchImpl, this.opts.retryDelayMs, this.set, new Date(this.now()));
59684
59720
  const failed = set.sources.filter((s) => !s.ok);
59685
59721
  if (failed.length === set.sources.length) {
59686
59722
  this.opts.log(`[threat-feeds] refresh failed, keeping previous list: ${failed.map((s) => `${s.feed}: ${s.error}`).join("; ")}`);
@@ -59708,7 +59744,7 @@ var ThreatFeeds = class {
59708
59744
  this.blocking = ok;
59709
59745
  mode = ok ? "blocking egress" : "detecting (nft load failed)";
59710
59746
  }
59711
- const failed = (set.sources ?? []).filter((s) => !s.ok).map((s) => s.feed);
59747
+ const failed = (set.sources ?? []).filter((s) => !s.ok).map((s) => s.carried ? `${s.feed}: kept ${s.carried} from ${s.last_ok_at?.slice(11, 16)} UTC` : s.feed);
59712
59748
  const failing = failed.length ? `; ${failed.length}/${set.sources.length} feeds failing (${failed.join(", ")}), see \`threatcrush feeds\`` : "";
59713
59749
  const detail = `${ips.length} IPs, ${domains} domains, ${mode}${this.writeResolverFiles(set)}${failing}`;
59714
59750
  this.opts.log(`[threat-feeds] ${from === "cache" ? "loaded cached" : "refreshed"} list: ${detail} (${set.skipped_shared} shared/protected entries skipped)`);
@@ -69062,7 +69098,8 @@ async function feedsCommand(action, value, opts) {
69062
69098
  console.log(` Fetched: ${set.fetched_at.replace("T", " ").slice(0, 16)} UTC`);
69063
69099
  console.log(` ${ips} C2/payload IPs, ${domains} malware domains; ${set.skipped_shared} shared or protected entries skipped`);
69064
69100
  for (const s of set.sources) {
69065
- console.log(` ${s.ok ? source_default.green("\u2713") : source_default.red("\u2717")} ${s.feed.padEnd(16)} ${s.ok ? `${s.count}` : source_default.red(s.error ?? "failed")}`);
69101
+ const kept = s.carried ? source_default.yellow(` (keeping ${s.carried} from ${s.last_ok_at?.replace("T", " ").slice(0, 16)} UTC)`) : "";
69102
+ console.log(` ${s.ok ? source_default.green("\u2713") : source_default.red("\u2717")} ${s.feed.padEnd(16)} ${s.ok ? `${s.count}` : source_default.red(s.error ?? "failed")}${kept}`);
69066
69103
  }
69067
69104
  const failed = set.sources.filter((s) => !s.ok);
69068
69105
  if (failed.length) {