@profullstack/threatcrush 0.13.9 → 0.13.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/daemon.js CHANGED
@@ -63,9 +63,9 @@ var require_parser = __commonJS({
63
63
  this.ii = 0;
64
64
  this.state = new State(this.parseStart);
65
65
  }
66
- parse(str) {
67
- if (str.length === 0 || str.length == null) return;
68
- this._buf = String(str);
66
+ parse(str2) {
67
+ if (str2.length === 0 || str2.length == null) return;
68
+ this._buf = String(str2);
69
69
  this.ii = -1;
70
70
  this.char = -1;
71
71
  let getNext;
@@ -1612,16 +1612,16 @@ var require_parse_string = __commonJS({
1612
1612
  module2.exports = parseString;
1613
1613
  var TOMLParser = require_toml_parser();
1614
1614
  var prettyError = require_parse_pretty_error();
1615
- function parseString(str) {
1616
- if (global.Buffer && global.Buffer.isBuffer(str)) {
1617
- str = str.toString("utf8");
1615
+ function parseString(str2) {
1616
+ if (global.Buffer && global.Buffer.isBuffer(str2)) {
1617
+ str2 = str2.toString("utf8");
1618
1618
  }
1619
1619
  const parser = new TOMLParser();
1620
1620
  try {
1621
- parser.parse(str);
1621
+ parser.parse(str2);
1622
1622
  return parser.finish();
1623
1623
  } catch (err) {
1624
- throw prettyError(err, str);
1624
+ throw prettyError(err, str2);
1625
1625
  }
1626
1626
  }
1627
1627
  }
@@ -1634,7 +1634,7 @@ var require_parse_async = __commonJS({
1634
1634
  module2.exports = parseAsync;
1635
1635
  var TOMLParser = require_toml_parser();
1636
1636
  var prettyError = require_parse_pretty_error();
1637
- function parseAsync(str, opts) {
1637
+ function parseAsync(str2, opts) {
1638
1638
  if (!opts) opts = {};
1639
1639
  const index = 0;
1640
1640
  const blocksize = opts.blocksize || 40960;
@@ -1643,18 +1643,18 @@ var require_parse_async = __commonJS({
1643
1643
  setImmediate(parseAsyncNext, index, blocksize, resolve3, reject);
1644
1644
  });
1645
1645
  function parseAsyncNext(index2, blocksize2, resolve3, reject) {
1646
- if (index2 >= str.length) {
1646
+ if (index2 >= str2.length) {
1647
1647
  try {
1648
1648
  return resolve3(parser.finish());
1649
1649
  } catch (err) {
1650
- return reject(prettyError(err, str));
1650
+ return reject(prettyError(err, str2));
1651
1651
  }
1652
1652
  }
1653
1653
  try {
1654
- parser.parse(str.slice(index2, index2 + blocksize2));
1654
+ parser.parse(str2.slice(index2, index2 + blocksize2));
1655
1655
  setImmediate(parseAsyncNext, index2 + blocksize2, blocksize2, resolve3, reject);
1656
1656
  } catch (err) {
1657
- reject(prettyError(err, str));
1657
+ reject(prettyError(err, str2));
1658
1658
  }
1659
1659
  }
1660
1660
  }
@@ -1860,22 +1860,22 @@ var require_stringify = __commonJS({
1860
1860
  return stringifyBasicString(keyStr);
1861
1861
  }
1862
1862
  }
1863
- function stringifyBasicString(str) {
1864
- return '"' + escapeString(str).replace(/"/g, '\\"') + '"';
1863
+ function stringifyBasicString(str2) {
1864
+ return '"' + escapeString(str2).replace(/"/g, '\\"') + '"';
1865
1865
  }
1866
- function stringifyLiteralString(str) {
1867
- return "'" + str + "'";
1866
+ function stringifyLiteralString(str2) {
1867
+ return "'" + str2 + "'";
1868
1868
  }
1869
- function numpad(num, str) {
1870
- while (str.length < num) str = "0" + str;
1871
- return str;
1869
+ function numpad(num, str2) {
1870
+ while (str2.length < num) str2 = "0" + str2;
1871
+ return str2;
1872
1872
  }
1873
- function escapeString(str) {
1874
- return str.replace(/\\/g, "\\\\").replace(/[\b]/g, "\\b").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\f/g, "\\f").replace(/\r/g, "\\r").replace(/([\u0000-\u001f\u007f])/, (c) => "\\u" + numpad(4, c.codePointAt(0).toString(16)));
1873
+ function escapeString(str2) {
1874
+ return str2.replace(/\\/g, "\\\\").replace(/[\b]/g, "\\b").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\f/g, "\\f").replace(/\r/g, "\\r").replace(/([\u0000-\u001f\u007f])/, (c) => "\\u" + numpad(4, c.codePointAt(0).toString(16)));
1875
1875
  }
1876
- function stringifyMultilineString(str) {
1877
- let escaped = str.split(/\n/).map((str2) => {
1878
- return escapeString(str2).replace(/"(?="")/g, '\\"');
1876
+ function stringifyMultilineString(str2) {
1877
+ let escaped = str2.split(/\n/).map((str3) => {
1878
+ return escapeString(str3).replace(/"(?="")/g, '\\"');
1879
1879
  }).join("\n");
1880
1880
  if (escaped.slice(-1) === '"') escaped += "\\\n";
1881
1881
  return '"""\n' + escaped + '"""';
@@ -2022,8 +2022,11 @@ var require_toml = __commonJS({
2022
2022
  });
2023
2023
 
2024
2024
  // src/daemon/index.ts
2025
- var import_node_fs20 = require("fs");
2026
- var import_node_path15 = require("path");
2025
+ var import_node_fs21 = require("fs");
2026
+ var import_node_child_process6 = require("child_process");
2027
+ var import_node_os5 = require("os");
2028
+ var import_node_path16 = require("path");
2029
+ var import_node_util = require("util");
2027
2030
 
2028
2031
  // src/daemon/paths.ts
2029
2032
  var import_node_fs = require("fs");
@@ -2089,14 +2092,29 @@ function removePidFile() {
2089
2092
  } catch {
2090
2093
  }
2091
2094
  }
2095
+ function procStatState(stat) {
2096
+ const close = stat.lastIndexOf(")");
2097
+ if (close === -1) return null;
2098
+ return stat.slice(close + 1).trim().charAt(0) || null;
2099
+ }
2100
+ function isZombie(pid) {
2101
+ let stat;
2102
+ try {
2103
+ stat = (0, import_node_fs2.readFileSync)(`/proc/${pid}/stat`, "utf-8");
2104
+ } catch {
2105
+ return false;
2106
+ }
2107
+ const state = procStatState(stat);
2108
+ return state === "Z" || state === "X";
2109
+ }
2092
2110
  function isProcessAlive(pid) {
2093
2111
  try {
2094
2112
  process.kill(pid, 0);
2095
- return true;
2096
2113
  } catch (err) {
2097
2114
  const code = err.code;
2098
- return code === "EPERM";
2115
+ if (code !== "EPERM") return false;
2099
2116
  }
2117
+ return !isZombie(pid);
2100
2118
  }
2101
2119
  function findRunningDaemon() {
2102
2120
  const pid = readPidFile();
@@ -10300,14 +10318,14 @@ var DnsMonitor = class {
10300
10318
  );
10301
10319
  }
10302
10320
  }
10303
- shannonEntropy(str) {
10321
+ shannonEntropy(str2) {
10304
10322
  const freq = /* @__PURE__ */ new Map();
10305
- for (const ch of str) {
10323
+ for (const ch of str2) {
10306
10324
  freq.set(ch, (freq.get(ch) || 0) + 1);
10307
10325
  }
10308
10326
  let entropy = 0;
10309
10327
  for (const count of freq.values()) {
10310
- const p = count / str.length;
10328
+ const p = count / str2.length;
10311
10329
  if (p > 0) entropy -= p * Math.log2(p);
10312
10330
  }
10313
10331
  return entropy;
@@ -10376,6 +10394,7 @@ function loadConfig(configPath) {
10376
10394
  modules: { ...DEFAULT_CONFIG.modules, ...parsed.modules },
10377
10395
  remediation: parsed.remediation,
10378
10396
  detection: parsed.detection,
10397
+ cloud: parsed.cloud,
10379
10398
  license: parsed.license
10380
10399
  };
10381
10400
  } catch {
@@ -10402,6 +10421,15 @@ function loadModuleConfigs(confDir) {
10402
10421
  return configs;
10403
10422
  }
10404
10423
 
10424
+ // src/core/builtin-modules.ts
10425
+ var BUILTIN_MODULES = [
10426
+ { name: "log-watcher", version: "0.1.0", description: "Web and system log attacks (nginx, syslog)" },
10427
+ { name: "ssh-guard", version: "0.1.0", description: "SSH brute force (auth.log or the sshd journal)" },
10428
+ { name: "user-journal", version: "0.1.0", description: "Events from the systemd journal" },
10429
+ { name: "network-monitor", version: "0.1.0", description: "Inbound connections and port scans" },
10430
+ { name: "dns-monitor", version: "0.1.0", description: "DNS tunneling and DGA indicators" }
10431
+ ];
10432
+
10405
10433
  // src/daemon/module-host.ts
10406
10434
  var ModuleHost = class {
10407
10435
  constructor(bus2) {
@@ -10511,14 +10539,9 @@ var ModuleHost = class {
10511
10539
  }));
10512
10540
  }
10513
10541
  registerBuiltins() {
10514
- const builtins = [
10515
- { name: "log-watcher", version: "0.1.0", source: "builtin", status: "loaded", events: 0 },
10516
- { name: "ssh-guard", version: "0.1.0", source: "builtin", status: "loaded", events: 0 },
10517
- { name: "user-journal", version: "0.1.0", source: "builtin", status: "loaded", events: 0 },
10518
- { name: "network-monitor", version: "0.1.0", source: "builtin", status: "loaded", events: 0 },
10519
- { name: "dns-monitor", version: "0.1.0", source: "builtin", status: "loaded", events: 0 }
10520
- ];
10521
- for (const m of builtins) this.modules.set(m.name, m);
10542
+ for (const { name, version } of BUILTIN_MODULES) {
10543
+ this.modules.set(name, { name, version, source: "builtin", status: "loaded", events: 0 });
10544
+ }
10522
10545
  }
10523
10546
  async discoverAndStartInstalled() {
10524
10547
  if (!(0, import_node_fs11.existsSync)(PATHS.moduleDir)) return;
@@ -10884,6 +10907,9 @@ var import_node_path7 = require("path");
10884
10907
  var import_node_os2 = require("os");
10885
10908
  var CLI_CONFIG_DIR = (0, import_node_path7.join)((0, import_node_os2.homedir)(), ".threatcrush");
10886
10909
  var CLI_CONFIG_PATH = (0, import_node_path7.join)(CLI_CONFIG_DIR, "config.json");
10910
+ function apiUrl() {
10911
+ return process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
10912
+ }
10887
10913
  function readCliConfig() {
10888
10914
  try {
10889
10915
  return JSON.parse((0, import_node_fs12.readFileSync)(CLI_CONFIG_PATH, "utf-8"));
@@ -10891,11 +10917,23 @@ function readCliConfig() {
10891
10917
  return {};
10892
10918
  }
10893
10919
  }
10894
- function isLoggedIn() {
10920
+ function writeCliConfig(config) {
10921
+ if (!(0, import_node_fs12.existsSync)(CLI_CONFIG_DIR)) (0, import_node_fs12.mkdirSync)(CLI_CONFIG_DIR, { recursive: true });
10922
+ (0, import_node_fs12.writeFileSync)(CLI_CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
10923
+ try {
10924
+ (0, import_node_fs12.chmodSync)(CLI_CONFIG_PATH, 384);
10925
+ } catch {
10926
+ }
10927
+ }
10928
+ function updateCliConfig(patch) {
10929
+ const current = readCliConfig();
10930
+ const next = { ...current, ...patch };
10931
+ writeCliConfig(next);
10932
+ return next;
10933
+ }
10934
+ function hasSession() {
10895
10935
  const cfg = readCliConfig();
10896
- if (!cfg.token) return false;
10897
- if (cfg.expires_at && cfg.expires_at * 1e3 < Date.now()) return false;
10898
- return true;
10936
+ return Boolean(cfg.token || cfg.refresh_token);
10899
10937
  }
10900
10938
  function authHeaders() {
10901
10939
  const cfg = readCliConfig();
@@ -10903,6 +10941,60 @@ function authHeaders() {
10903
10941
  if (cfg.token) headers["Authorization"] = `Bearer ${cfg.token}`;
10904
10942
  return headers;
10905
10943
  }
10944
+ var refreshInFlight = null;
10945
+ function refreshSession() {
10946
+ refreshInFlight ??= doRefresh().finally(() => {
10947
+ refreshInFlight = null;
10948
+ });
10949
+ return refreshInFlight;
10950
+ }
10951
+ async function doRefresh() {
10952
+ const sent = readCliConfig().refresh_token;
10953
+ if (!sent) return "unavailable";
10954
+ let res;
10955
+ try {
10956
+ res = await fetch(`${apiUrl()}/api/auth/refresh`, {
10957
+ method: "POST",
10958
+ headers: { "Content-Type": "application/json" },
10959
+ body: JSON.stringify({ refresh_token: sent }),
10960
+ signal: AbortSignal.timeout(15e3)
10961
+ });
10962
+ } catch {
10963
+ return "unavailable";
10964
+ }
10965
+ if (res.ok) {
10966
+ const data = await res.json().catch(() => null);
10967
+ const session = data?.session;
10968
+ if (!session?.access_token || !session.refresh_token) return "unavailable";
10969
+ updateCliConfig({
10970
+ token: session.access_token,
10971
+ refresh_token: session.refresh_token,
10972
+ expires_at: session.expires_at ?? void 0
10973
+ });
10974
+ return "refreshed";
10975
+ }
10976
+ if (res.status === 401 || res.status === 400) {
10977
+ return readCliConfig().refresh_token !== sent ? "refreshed" : "dead";
10978
+ }
10979
+ return "unavailable";
10980
+ }
10981
+ var EXPIRY_SKEW_SECONDS = 60;
10982
+ async function cloudFetch(path, init = {}) {
10983
+ const cfg = readCliConfig();
10984
+ if (cfg.refresh_token && cfg.expires_at && cfg.expires_at - EXPIRY_SKEW_SECONDS < Date.now() / 1e3) {
10985
+ await refreshSession();
10986
+ }
10987
+ const send = () => fetch(`${apiUrl()}${path}`, {
10988
+ method: init.method ?? "GET",
10989
+ headers: authHeaders(),
10990
+ body: init.body,
10991
+ signal: AbortSignal.timeout(init.timeoutMs ?? 3e4)
10992
+ });
10993
+ const res = await send();
10994
+ if (res.status !== 401) return res;
10995
+ if (await refreshSession() !== "refreshed") return res;
10996
+ return send();
10997
+ }
10906
10998
 
10907
10999
  // src/commands/scan.ts
10908
11000
  var import_node_fs16 = require("fs");
@@ -14137,7 +14229,7 @@ function isTestPath(relativePath) {
14137
14229
  function rustCodeLines(lines) {
14138
14230
  const out = [];
14139
14231
  let commentDepth = 0;
14140
- let str = null;
14232
+ let str2 = null;
14141
14233
  for (const line of lines) {
14142
14234
  let code = "";
14143
14235
  let i = 0;
@@ -14161,15 +14253,15 @@ function rustCodeLines(lines) {
14161
14253
  i += 1;
14162
14254
  continue;
14163
14255
  }
14164
- if (str) {
14165
- if (str.raw) {
14256
+ if (str2) {
14257
+ if (str2.raw) {
14166
14258
  if (c === '"') {
14167
14259
  let hashes = 0;
14168
14260
  while (line[i + 1 + hashes] === "#") hashes += 1;
14169
- if (hashes >= str.hashes) {
14170
- code += " ".repeat(1 + str.hashes);
14171
- i += 1 + str.hashes;
14172
- str = null;
14261
+ if (hashes >= str2.hashes) {
14262
+ code += " ".repeat(1 + str2.hashes);
14263
+ i += 1 + str2.hashes;
14264
+ str2 = null;
14173
14265
  continue;
14174
14266
  }
14175
14267
  }
@@ -14183,7 +14275,7 @@ function rustCodeLines(lines) {
14183
14275
  continue;
14184
14276
  }
14185
14277
  if (c === '"') {
14186
- str = null;
14278
+ str2 = null;
14187
14279
  code += " ";
14188
14280
  i += 1;
14189
14281
  continue;
@@ -14205,14 +14297,14 @@ function rustCodeLines(lines) {
14205
14297
  if (i === 0 || !/[A-Za-z0-9_]/.test(line[i - 1])) {
14206
14298
  const raw = /^b?r(#*)"/.exec(line.slice(i));
14207
14299
  if (raw) {
14208
- str = { raw: true, hashes: raw[1].length };
14300
+ str2 = { raw: true, hashes: raw[1].length };
14209
14301
  code += " ".repeat(raw[0].length);
14210
14302
  i += raw[0].length;
14211
14303
  continue;
14212
14304
  }
14213
14305
  }
14214
14306
  if (c === '"') {
14215
- str = { raw: false, hashes: 0 };
14307
+ str2 = { raw: false, hashes: 0 };
14216
14308
  code += " ";
14217
14309
  i += 1;
14218
14310
  continue;
@@ -15076,7 +15168,6 @@ async function collectPentestResults(targetUrl) {
15076
15168
  }
15077
15169
 
15078
15170
  // src/daemon/workers/runs-worker.ts
15079
- var API_URL = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
15080
15171
  var POLL_INTERVAL_MS = 3e4;
15081
15172
  var SCHEDULE_INTERVAL_MS = 12e4;
15082
15173
  var RunsWorker = class {
@@ -15089,7 +15180,7 @@ var RunsWorker = class {
15089
15180
  running = false;
15090
15181
  orgIds = [];
15091
15182
  async start() {
15092
- if (!isLoggedIn()) return;
15183
+ if (!hasSession()) return;
15093
15184
  try {
15094
15185
  await this.refreshOrgs();
15095
15186
  } catch {
@@ -15108,15 +15199,12 @@ var RunsWorker = class {
15108
15199
  this.bus.announceModule("runs-worker", "stopped");
15109
15200
  }
15110
15201
  async scheduleTick() {
15111
- if (!isLoggedIn()) return;
15202
+ if (!hasSession()) return;
15112
15203
  try {
15113
15204
  if (this.orgIds.length === 0) await this.refreshOrgs();
15114
15205
  for (const orgId of this.orgIds) {
15115
15206
  try {
15116
- await fetch(`${API_URL}/api/orgs/${orgId}/schedules/tick`, {
15117
- method: "POST",
15118
- headers: authHeaders()
15119
- });
15207
+ await cloudFetch(`/api/orgs/${orgId}/schedules/tick`, { method: "POST" });
15120
15208
  } catch {
15121
15209
  }
15122
15210
  }
@@ -15125,7 +15213,7 @@ var RunsWorker = class {
15125
15213
  }
15126
15214
  async tick() {
15127
15215
  if (this.running) return;
15128
- if (!isLoggedIn()) return;
15216
+ if (!hasSession()) return;
15129
15217
  this.running = true;
15130
15218
  try {
15131
15219
  if (this.orgIds.length === 0) await this.refreshOrgs();
@@ -15141,16 +15229,15 @@ var RunsWorker = class {
15141
15229
  }
15142
15230
  }
15143
15231
  async refreshOrgs() {
15144
- const res = await fetch(`${API_URL}/api/orgs`, { headers: authHeaders() });
15232
+ const res = await cloudFetch("/api/orgs");
15145
15233
  if (!res.ok) return;
15146
15234
  const data = await res.json();
15147
15235
  this.orgIds = (data.organizations || []).map((o) => o.id);
15148
15236
  }
15149
15237
  async claimOne(orgId) {
15150
15238
  try {
15151
- const res = await fetch(`${API_URL}/api/orgs/${orgId}/runs/pending`, {
15239
+ const res = await cloudFetch(`/api/orgs/${orgId}/runs/pending`, {
15152
15240
  method: "POST",
15153
- headers: authHeaders(),
15154
15241
  body: JSON.stringify({ worker_id: workerId() })
15155
15242
  });
15156
15243
  if (!res.ok) return null;
@@ -15189,11 +15276,10 @@ var RunsWorker = class {
15189
15276
  }
15190
15277
  async finalize(orgId, claimed, result) {
15191
15278
  try {
15192
- await fetch(
15193
- `${API_URL}/api/orgs/${orgId}/properties/${claimed.property_id}/runs/${claimed.id}`,
15279
+ await cloudFetch(
15280
+ `/api/orgs/${orgId}/properties/${claimed.property_id}/runs/${claimed.id}`,
15194
15281
  {
15195
15282
  method: "PATCH",
15196
- headers: authHeaders(),
15197
15283
  body: JSON.stringify({
15198
15284
  status: result.error ? "failed" : "succeeded",
15199
15285
  findings_count: result.findings.length,
@@ -15213,6 +15299,756 @@ var RunsWorker = class {
15213
15299
  }
15214
15300
  };
15215
15301
 
15302
+ // src/core/cloud-events.ts
15303
+ var import_node_crypto4 = require("crypto");
15304
+ var import_node_net2 = require("net");
15305
+ function currentLink() {
15306
+ if (!hasSession()) return null;
15307
+ const cfg = readCliConfig();
15308
+ if (!cfg.server_id || !cfg.server_org_id) return null;
15309
+ return { serverId: cfg.server_id, orgId: cfg.server_org_id };
15310
+ }
15311
+ var SEVERITY_RANK4 = {
15312
+ info: 0,
15313
+ low: 1,
15314
+ medium: 2,
15315
+ high: 3,
15316
+ critical: 4
15317
+ };
15318
+ var MAX_TITLE_CHARS = 300;
15319
+ var MAX_METADATA_BYTES = 16 * 1024;
15320
+ var MAX_STRING_CHARS = 1024;
15321
+ function jsonBytes(value) {
15322
+ try {
15323
+ return Buffer.byteLength(JSON.stringify(value) ?? "");
15324
+ } catch {
15325
+ return Infinity;
15326
+ }
15327
+ }
15328
+ function trimMetadata(meta) {
15329
+ const entries = [];
15330
+ for (const [key, value] of Object.entries(meta)) {
15331
+ if (value === void 0 || typeof value === "function") continue;
15332
+ const cut = typeof value === "string" && value.length > MAX_STRING_CHARS ? `${value.slice(0, MAX_STRING_CHARS)}\u2026` : value;
15333
+ if (jsonBytes(cut) === Infinity) continue;
15334
+ entries.push([key, cut]);
15335
+ }
15336
+ let out = Object.fromEntries(entries);
15337
+ let truncated = entries.length !== Object.keys(meta).length;
15338
+ if (jsonBytes(out) > MAX_METADATA_BYTES) {
15339
+ truncated = true;
15340
+ const bySize = [...entries].sort((a, b) => jsonBytes(a[1]) - jsonBytes(b[1]));
15341
+ while (bySize.length > 0 && jsonBytes({ ...Object.fromEntries(bySize), _truncated: true }) > MAX_METADATA_BYTES) {
15342
+ bySize.pop();
15343
+ }
15344
+ out = Object.fromEntries(bySize);
15345
+ }
15346
+ return truncated ? { ...out, _truncated: true } : out;
15347
+ }
15348
+ function str(value) {
15349
+ return typeof value === "string" && value ? value : void 0;
15350
+ }
15351
+ function detectionEvent(serverId, event) {
15352
+ const { rule_id, username, user, description, ...rest } = event.details ?? {};
15353
+ const title = event.module === "rule-engine" ? event.message.replace(/^\[DETECTION\]\s*/, "") : event.message;
15354
+ return {
15355
+ type: "detection",
15356
+ server_id: serverId,
15357
+ severity: event.severity,
15358
+ title: title.slice(0, MAX_TITLE_CHARS) || event.module,
15359
+ rule_id: str(rule_id) ?? event.module,
15360
+ description: str(description),
15361
+ source_ip: event.source_ip && (0, import_node_net2.isIP)(event.source_ip) ? event.source_ip : void 0,
15362
+ username: str(username) ?? str(user),
15363
+ raw_metadata: trimMetadata({ module: event.module, category: event.category, ...rest }),
15364
+ detected_at: event.timestamp.toISOString()
15365
+ };
15366
+ }
15367
+ function remediationEvent(serverId, event) {
15368
+ const d = event.details ?? {};
15369
+ if (d.action !== "block" && d.action !== "unblock") return null;
15370
+ if (d.origin === "cloud" || !event.source_ip) return null;
15371
+ const at = event.timestamp;
15372
+ const ttl = typeof d.ttl_seconds === "number" ? d.ttl_seconds : null;
15373
+ return {
15374
+ type: "remediation",
15375
+ server_id: serverId,
15376
+ event_id: (0, import_node_crypto4.randomUUID)(),
15377
+ action_type: d.action,
15378
+ target_value: event.source_ip,
15379
+ status: d.failed === true ? "failed" : "executed",
15380
+ rule_id: str(d.rule_id),
15381
+ reason: str(d.reason),
15382
+ error: str(d.error),
15383
+ dry_run: d.dry_run === true,
15384
+ executed_at: at.toISOString(),
15385
+ expires_at: d.action === "block" && ttl !== null && d.failed !== true ? new Date(at.getTime() + ttl * 1e3).toISOString() : null
15386
+ };
15387
+ }
15388
+ function findingEvents(serverId, results, observedAt = /* @__PURE__ */ new Date()) {
15389
+ return results.map((r) => ({
15390
+ type: "hardening_finding",
15391
+ server_id: serverId,
15392
+ finding_key: r.key,
15393
+ status: r.status,
15394
+ severity: r.severity,
15395
+ title: r.title.slice(0, MAX_TITLE_CHARS),
15396
+ recommendation: r.recommendation,
15397
+ observed_at: observedAt.toISOString()
15398
+ }));
15399
+ }
15400
+
15401
+ // src/daemon/workers/cloud-spool.ts
15402
+ var import_node_fs17 = require("fs");
15403
+ var import_promises = require("fs/promises");
15404
+ var import_node_path13 = require("path");
15405
+ var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
15406
+ var CloudSpool = class {
15407
+ constructor(path, limits = DEFAULT_SPOOL_LIMITS) {
15408
+ this.path = path;
15409
+ this.limits = limits;
15410
+ try {
15411
+ (0, import_node_fs17.mkdirSync)((0, import_node_path13.dirname)(path), { recursive: true });
15412
+ } catch {
15413
+ }
15414
+ this.load();
15415
+ }
15416
+ path;
15417
+ limits;
15418
+ lines = [];
15419
+ bytes = 0;
15420
+ pendingAppend = [];
15421
+ needsRewrite = false;
15422
+ scheduled = false;
15423
+ writes = Promise.resolve();
15424
+ droppedSinceReport = 0;
15425
+ get size() {
15426
+ return this.lines.length;
15427
+ }
15428
+ push(event) {
15429
+ const line = JSON.stringify(event);
15430
+ this.lines.push(line);
15431
+ this.bytes += Buffer.byteLength(line) + 1;
15432
+ this.pendingAppend.push(line);
15433
+ this.enforceLimits();
15434
+ this.schedule();
15435
+ }
15436
+ /** Up to `maxEvents` of the oldest events whose JSON fits in `maxBytes`. */
15437
+ peek(maxEvents, maxBytes) {
15438
+ const out = [];
15439
+ let bytes = 0;
15440
+ for (const line of this.lines) {
15441
+ if (out.length >= maxEvents) break;
15442
+ const size = Buffer.byteLength(line) + 1;
15443
+ if (out.length > 0 && bytes + size > maxBytes) break;
15444
+ bytes += size;
15445
+ out.push(JSON.parse(line));
15446
+ }
15447
+ return out;
15448
+ }
15449
+ /** Forget the `count` oldest events: they were delivered or will never be. */
15450
+ ack(count) {
15451
+ if (count <= 0) return;
15452
+ for (const line of this.lines.splice(0, count)) this.bytes -= Buffer.byteLength(line) + 1;
15453
+ this.needsRewrite = true;
15454
+ this.schedule();
15455
+ }
15456
+ /** Events dropped by the bound since the last call, for a single log line. */
15457
+ takeDropped() {
15458
+ const n = this.droppedSinceReport;
15459
+ this.droppedSinceReport = 0;
15460
+ return n;
15461
+ }
15462
+ /** Resolves once everything queued so far is on disk. */
15463
+ settled() {
15464
+ return this.writes;
15465
+ }
15466
+ enforceLimits() {
15467
+ let dropped = 0;
15468
+ while (this.lines.length > 0 && (this.lines.length > this.limits.maxEvents || this.bytes > this.limits.maxBytes)) {
15469
+ this.bytes -= Buffer.byteLength(this.lines.shift()) + 1;
15470
+ dropped++;
15471
+ }
15472
+ if (dropped > 0) {
15473
+ this.droppedSinceReport += dropped;
15474
+ this.needsRewrite = true;
15475
+ }
15476
+ }
15477
+ load() {
15478
+ let raw;
15479
+ try {
15480
+ raw = (0, import_node_fs17.readFileSync)(this.path, "utf-8");
15481
+ } catch {
15482
+ return;
15483
+ }
15484
+ let invalid = false;
15485
+ for (const line of raw.split("\n")) {
15486
+ if (!line.trim()) continue;
15487
+ try {
15488
+ JSON.parse(line);
15489
+ } catch {
15490
+ invalid = true;
15491
+ continue;
15492
+ }
15493
+ this.lines.push(line);
15494
+ this.bytes += Buffer.byteLength(line) + 1;
15495
+ }
15496
+ this.enforceLimits();
15497
+ if (invalid) this.needsRewrite = true;
15498
+ if (this.needsRewrite) this.schedule();
15499
+ }
15500
+ schedule() {
15501
+ if (this.scheduled) return;
15502
+ this.scheduled = true;
15503
+ this.writes = this.writes.then(async () => {
15504
+ this.scheduled = false;
15505
+ if (this.needsRewrite) {
15506
+ this.needsRewrite = false;
15507
+ this.pendingAppend = [];
15508
+ const body = this.lines.length > 0 ? `${this.lines.join("\n")}
15509
+ ` : "";
15510
+ const tmp = `${this.path}.tmp`;
15511
+ await (0, import_promises.writeFile)(tmp, body, { mode: 384 });
15512
+ await (0, import_promises.rename)(tmp, this.path);
15513
+ } else if (this.pendingAppend.length > 0) {
15514
+ const chunk = `${this.pendingAppend.join("\n")}
15515
+ `;
15516
+ this.pendingAppend = [];
15517
+ await (0, import_promises.appendFile)(this.path, chunk, { mode: 384 });
15518
+ }
15519
+ }).catch(() => {
15520
+ this.needsRewrite = true;
15521
+ });
15522
+ }
15523
+ };
15524
+
15525
+ // src/daemon/workers/cloud-sync.ts
15526
+ var MAX_BATCH_BYTES = 900 * 1024;
15527
+ var CloudSync = class {
15528
+ constructor(opts) {
15529
+ this.opts = opts;
15530
+ this.spool = new CloudSpool(opts.spoolPath, opts.spoolLimits ?? DEFAULT_SPOOL_LIMITS);
15531
+ this.batchSize = opts.batchSize ?? 100;
15532
+ this.flushMs = opts.flushMs ?? 1e4;
15533
+ this.heartbeatMs = opts.heartbeatMs ?? 6e4;
15534
+ this.baseBackoffMs = opts.baseBackoffMs ?? 5e3;
15535
+ this.maxBackoffMs = opts.maxBackoffMs ?? 3e5;
15536
+ }
15537
+ opts;
15538
+ spool;
15539
+ batchSize;
15540
+ flushMs;
15541
+ heartbeatMs;
15542
+ baseBackoffMs;
15543
+ maxBackoffMs;
15544
+ timers = [];
15545
+ flushing = null;
15546
+ backoffMs = 0;
15547
+ retryAt = 0;
15548
+ link = null;
15549
+ lastProblem = "";
15550
+ onEvent = (event) => this.capture(event);
15551
+ start() {
15552
+ this.link = currentLink();
15553
+ this.opts.bus.on("event", this.onEvent);
15554
+ const every = (ms, fn) => {
15555
+ const timer = setInterval(fn, ms);
15556
+ timer.unref?.();
15557
+ this.timers.push(timer);
15558
+ };
15559
+ every(this.flushMs, () => void this.flush());
15560
+ every(this.heartbeatMs, () => void this.heartbeat());
15561
+ void this.heartbeat();
15562
+ if (this.opts.runHardening) {
15563
+ const first = setTimeout(() => void this.reportHardening(), this.opts.hardeningDelayMs ?? 6e4);
15564
+ first.unref?.();
15565
+ this.timers.push(first);
15566
+ every(this.opts.hardeningIntervalMs ?? 864e5, () => void this.reportHardening());
15567
+ }
15568
+ if (this.spool.size > 0) {
15569
+ this.opts.log(`[cloud] ${this.spool.size} event(s) waiting in the spool from before`);
15570
+ void this.flush();
15571
+ }
15572
+ }
15573
+ async stop() {
15574
+ this.opts.bus.off("event", this.onEvent);
15575
+ for (const timer of this.timers) clearInterval(timer);
15576
+ this.timers = [];
15577
+ await this.spool.settled();
15578
+ }
15579
+ get queued() {
15580
+ return this.spool.size;
15581
+ }
15582
+ /** Queue hardening results for upload (the CLI posts its own directly). */
15583
+ enqueueFindings(results) {
15584
+ const link = this.refreshLink();
15585
+ if (!link) return 0;
15586
+ for (const event of findingEvents(link.serverId, results)) this.spool.push(event);
15587
+ this.kick();
15588
+ return results.length;
15589
+ }
15590
+ /**
15591
+ * Upload everything queued, oldest first, until the spool is empty or the
15592
+ * dashboard stops answering. Concurrent calls share one run.
15593
+ */
15594
+ flush() {
15595
+ this.flushing ??= this.drain().finally(() => {
15596
+ this.flushing = null;
15597
+ });
15598
+ return this.flushing;
15599
+ }
15600
+ capture(event) {
15601
+ const link = this.link;
15602
+ if (!link) return;
15603
+ let out = null;
15604
+ if (event.module === "firewall-rules") {
15605
+ out = remediationEvent(link.serverId, event);
15606
+ } else if ((event.module === "rule-engine" || !this.opts.ruleModules.has(event.module)) && event.details?.heartbeat !== true && SEVERITY_RANK4[event.severity] >= SEVERITY_RANK4[this.opts.minSeverity]) {
15607
+ out = detectionEvent(link.serverId, event);
15608
+ }
15609
+ if (!out) return;
15610
+ this.spool.push(out);
15611
+ if (this.spool.size >= this.batchSize) this.kick();
15612
+ }
15613
+ /** Flush soon, off the caller's stack, unless we are backing off. */
15614
+ kick() {
15615
+ if (Date.now() < this.retryAt) return;
15616
+ setImmediate(() => void this.flush());
15617
+ }
15618
+ refreshLink() {
15619
+ this.link = currentLink();
15620
+ return this.link;
15621
+ }
15622
+ async drain() {
15623
+ this.reportDropped();
15624
+ if (Date.now() < this.retryAt) return;
15625
+ if (!this.refreshLink()) return;
15626
+ while (this.spool.size > 0) {
15627
+ const batch = this.spool.peek(this.batchSize, MAX_BATCH_BYTES);
15628
+ const outcome = await this.post(batch);
15629
+ if (outcome === "retry") return;
15630
+ this.spool.ack(batch.length);
15631
+ }
15632
+ }
15633
+ async post(events) {
15634
+ let res;
15635
+ try {
15636
+ res = await cloudFetch("/api/ingest", { method: "POST", body: JSON.stringify({ events }) });
15637
+ } catch (err) {
15638
+ this.backOff(`dashboard unreachable (${err.message})`);
15639
+ return "retry";
15640
+ }
15641
+ if (res.ok) {
15642
+ const body = await res.json().catch(() => ({}));
15643
+ const rejected = body.rejected ?? [];
15644
+ if (rejected.length > 0) {
15645
+ const sample = rejected.slice(0, 3).map((r) => `#${r.index}: ${r.error}`).join("; ");
15646
+ this.opts.log(`[cloud] ingest rejected ${rejected.length} of ${events.length} event(s): ${sample}`);
15647
+ }
15648
+ if (this.backoffMs > 0 || this.lastProblem) {
15649
+ this.opts.log(`[cloud] dashboard reachable again; uploading ${this.spool.size} queued event(s)`);
15650
+ }
15651
+ this.backoffMs = 0;
15652
+ this.retryAt = 0;
15653
+ this.lastProblem = "";
15654
+ return "sent";
15655
+ }
15656
+ if (res.status === 401) {
15657
+ this.backOff("session expired and could not be refreshed \u2014 run `threatcrush login`");
15658
+ return "retry";
15659
+ }
15660
+ if (res.status === 429 || res.status >= 500) {
15661
+ this.backOff(`dashboard answered ${res.status}`);
15662
+ return "retry";
15663
+ }
15664
+ const detail = await res.text().catch(() => "");
15665
+ this.opts.log(`[cloud] ingest refused a batch (${res.status} ${detail.slice(0, 200)}); dropped ${events.length} event(s)`);
15666
+ return "dropped";
15667
+ }
15668
+ backOff(problem) {
15669
+ this.backoffMs = this.backoffMs === 0 ? this.baseBackoffMs : Math.min(this.backoffMs * 2, this.maxBackoffMs);
15670
+ this.retryAt = Date.now() + this.backoffMs;
15671
+ if (problem !== this.lastProblem) {
15672
+ this.opts.log(`[cloud] ${problem}; ${this.spool.size} event(s) spooled, retrying with backoff`);
15673
+ this.lastProblem = problem;
15674
+ }
15675
+ }
15676
+ reportDropped() {
15677
+ const dropped = this.spool.takeDropped();
15678
+ if (dropped > 0) {
15679
+ this.opts.log(`[cloud] spool full: dropped the ${dropped} oldest event(s)`);
15680
+ }
15681
+ }
15682
+ /**
15683
+ * Proof of life for the dashboard's online/offline badge. Not spooled: a
15684
+ * heartbeat replayed late would claim the box was up when nobody knew. A
15685
+ * heartbeat that gets through also ends a backoff early.
15686
+ */
15687
+ async heartbeat() {
15688
+ const link = this.refreshLink();
15689
+ if (!link) return;
15690
+ const event = {
15691
+ type: "heartbeat",
15692
+ server_id: link.serverId,
15693
+ version: this.opts.version,
15694
+ hostname: this.opts.hostname
15695
+ };
15696
+ try {
15697
+ const res = await cloudFetch("/api/ingest", { method: "POST", body: JSON.stringify({ events: [event] }) });
15698
+ if (res.ok && this.retryAt > 0) {
15699
+ this.retryAt = 0;
15700
+ void this.flush();
15701
+ }
15702
+ } catch {
15703
+ }
15704
+ }
15705
+ async reportHardening() {
15706
+ if (!this.refreshLink() || !this.opts.runHardening) return;
15707
+ try {
15708
+ const results = await this.opts.runHardening();
15709
+ const n = this.enqueueFindings(results);
15710
+ this.opts.log(`[cloud] hardening checks: queued ${n} finding(s) for upload`);
15711
+ } catch (err) {
15712
+ this.opts.log(`[cloud] hardening checks failed: ${err.message}`);
15713
+ }
15714
+ }
15715
+ };
15716
+
15717
+ // src/daemon/workers/remediation-consumer.ts
15718
+ var import_node_net5 = require("net");
15719
+
15720
+ // src/daemon/firewall/protected.ts
15721
+ var import_node_child_process4 = require("child_process");
15722
+ var import_node_net3 = require("net");
15723
+ var DEFAULT_PROTECTED = [
15724
+ "127.0.0.0/8",
15725
+ "::1/128",
15726
+ "10.0.0.0/8",
15727
+ "172.16.0.0/12",
15728
+ "192.168.0.0/16",
15729
+ "169.254.0.0/16",
15730
+ "fc00::/7",
15731
+ "fe80::/10"
15732
+ ];
15733
+ function ipToBytes(ip) {
15734
+ const version = (0, import_node_net3.isIP)(ip);
15735
+ if (version === 4) return v4ToBytes(ip);
15736
+ if (version === 6) return v6ToBytes(ip);
15737
+ return null;
15738
+ }
15739
+ function v4ToBytes(ip) {
15740
+ const parts = ip.split(".");
15741
+ if (parts.length !== 4) return null;
15742
+ const bytes = new Uint8Array(4);
15743
+ for (let i = 0; i < 4; i++) {
15744
+ const n = Number(parts[i]);
15745
+ if (!Number.isInteger(n) || n < 0 || n > 255) return null;
15746
+ bytes[i] = n;
15747
+ }
15748
+ return bytes;
15749
+ }
15750
+ function v6ToBytes(ip) {
15751
+ const bare = ip.split("%")[0];
15752
+ const [headText, tailText] = bare.split("::", 2);
15753
+ const head = headText ? headText.split(":") : [];
15754
+ const tail = tailText !== void 0 ? tailText ? tailText.split(":") : [] : null;
15755
+ const groups = [];
15756
+ const pushGroup = (group) => {
15757
+ if (group.includes(".")) {
15758
+ const v4 = v4ToBytes(group);
15759
+ if (!v4) return false;
15760
+ groups.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
15761
+ return true;
15762
+ }
15763
+ if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return false;
15764
+ groups.push(parseInt(group, 16));
15765
+ return true;
15766
+ };
15767
+ for (const group of head) if (!pushGroup(group)) return null;
15768
+ const headCount = groups.length;
15769
+ if (tail === null) {
15770
+ if (headCount !== 8) return null;
15771
+ } else {
15772
+ const tailGroups = [];
15773
+ const saved = groups.length;
15774
+ for (const group of tail) if (!pushGroup(group)) return null;
15775
+ tailGroups.push(...groups.splice(saved));
15776
+ const zeros = 8 - headCount - tailGroups.length;
15777
+ if (zeros < 0) return null;
15778
+ for (let i = 0; i < zeros; i++) groups.push(0);
15779
+ groups.push(...tailGroups);
15780
+ }
15781
+ if (groups.length !== 8) return null;
15782
+ const bytes = new Uint8Array(16);
15783
+ for (let i = 0; i < 8; i++) {
15784
+ bytes[i * 2] = groups[i] >> 8 & 255;
15785
+ bytes[i * 2 + 1] = groups[i] & 255;
15786
+ }
15787
+ return bytes;
15788
+ }
15789
+ function ipMatches(ip, entry) {
15790
+ const [network, prefixText] = entry.trim().split("/");
15791
+ const target = ipToBytes(ip);
15792
+ const base = ipToBytes(network);
15793
+ if (!target || !base || target.length !== base.length) return false;
15794
+ const bits = prefixText === void 0 ? base.length * 8 : Number(prefixText);
15795
+ if (!Number.isInteger(bits) || bits < 0 || bits > base.length * 8) return false;
15796
+ const wholeBytes = Math.floor(bits / 8);
15797
+ for (let i = 0; i < wholeBytes; i++) {
15798
+ if (target[i] !== base[i]) return false;
15799
+ }
15800
+ const remainder = bits % 8;
15801
+ if (remainder === 0) return true;
15802
+ const mask = 255 << 8 - remainder & 255;
15803
+ return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
15804
+ }
15805
+ function isProtected(ip, list) {
15806
+ return list.some((entry) => ipMatches(ip, entry));
15807
+ }
15808
+ function currentSshClient(env2 = process.env) {
15809
+ const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
15810
+ if (!source) return null;
15811
+ const ip = source.trim().split(/\s+/)[0];
15812
+ return ip && (0, import_node_net3.isIP)(ip) ? ip : null;
15813
+ }
15814
+ function establishedSshPeers() {
15815
+ const peers = /* @__PURE__ */ new Set();
15816
+ try {
15817
+ const out = (0, import_node_child_process4.execFileSync)("ss", ["-tnpH"], {
15818
+ encoding: "utf-8",
15819
+ stdio: ["ignore", "pipe", "ignore"],
15820
+ timeout: 3e3
15821
+ });
15822
+ for (const line of out.split("\n")) {
15823
+ if (!/users:\(\("sshd/.test(line)) continue;
15824
+ const parts = line.trim().split(/\s+/);
15825
+ const peer = parts[4];
15826
+ if (!peer) continue;
15827
+ const ip = peer.slice(0, peer.lastIndexOf(":")).replace(/^\[|\]$/g, "");
15828
+ if (ip && (0, import_node_net3.isIP)(ip)) peers.add(ip);
15829
+ }
15830
+ } catch {
15831
+ }
15832
+ return [...peers];
15833
+ }
15834
+ function defaultGateways() {
15835
+ const found = /* @__PURE__ */ new Set();
15836
+ for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
15837
+ try {
15838
+ const out = (0, import_node_child_process4.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
15839
+ for (const line of out.split("\n")) {
15840
+ const match = line.match(/\bvia\s+(\S+)/);
15841
+ if (match && (0, import_node_net3.isIP)(match[1])) found.add(match[1]);
15842
+ }
15843
+ } catch {
15844
+ }
15845
+ }
15846
+ return [...found];
15847
+ }
15848
+
15849
+ // src/daemon/workers/allowlist-sync.ts
15850
+ var import_node_net4 = require("net");
15851
+ function isAddressOrCidr(value) {
15852
+ const [network, prefix, extra] = value.split("/");
15853
+ const family = (0, import_node_net4.isIP)(network);
15854
+ if (family === 0 || extra !== void 0) return false;
15855
+ if (prefix === void 0) return true;
15856
+ if (!/^\d{1,3}$/.test(prefix)) return false;
15857
+ return Number(prefix) <= (family === 4 ? 32 : 128);
15858
+ }
15859
+ var AllowlistSync = class {
15860
+ constructor(manager, opts) {
15861
+ this.manager = manager;
15862
+ this.opts = opts;
15863
+ }
15864
+ manager;
15865
+ opts;
15866
+ timer = null;
15867
+ owned = /* @__PURE__ */ new Set();
15868
+ start() {
15869
+ this.timer = setInterval(() => void this.sync(), this.opts.intervalMs ?? 3e5);
15870
+ this.timer.unref?.();
15871
+ void this.sync();
15872
+ }
15873
+ stop() {
15874
+ if (this.timer) clearInterval(this.timer);
15875
+ this.timer = null;
15876
+ }
15877
+ async sync() {
15878
+ const link = currentLink();
15879
+ if (!link) return;
15880
+ let entries;
15881
+ try {
15882
+ const res = await cloudFetch(`/api/orgs/${link.orgId}/allowlists`);
15883
+ if (!res.ok) return;
15884
+ const data = await res.json();
15885
+ if (!Array.isArray(data.entries)) return;
15886
+ entries = data.entries;
15887
+ } catch {
15888
+ return;
15889
+ }
15890
+ const wanted = /* @__PURE__ */ new Set();
15891
+ for (const entry of entries) {
15892
+ if (entry.type !== "ip" && entry.type !== "cidr") continue;
15893
+ const value = String(entry.value ?? "").trim();
15894
+ if (isAddressOrCidr(value)) wanted.add(value);
15895
+ }
15896
+ const added = [];
15897
+ const protectedNow = new Set(this.manager.getProtected());
15898
+ for (const value of wanted) {
15899
+ if (this.owned.has(value) || protectedNow.has(value)) continue;
15900
+ this.manager.addToAllowlist(value);
15901
+ this.owned.add(value);
15902
+ added.push(value);
15903
+ }
15904
+ const removed = [];
15905
+ for (const value of this.owned) {
15906
+ if (wanted.has(value)) continue;
15907
+ this.manager.removeFromAllowlist(value);
15908
+ this.owned.delete(value);
15909
+ removed.push(value);
15910
+ }
15911
+ if (added.length > 0 || removed.length > 0) {
15912
+ this.opts.log(
15913
+ `[cloud] org allowlist: +${added.length} -${removed.length} (${[...added.map((v) => `+${v}`), ...removed.map((v) => `-${v}`)].slice(0, 10).join(" ")})`
15914
+ );
15915
+ }
15916
+ }
15917
+ };
15918
+
15919
+ // src/daemon/workers/remediation-consumer.ts
15920
+ var MAX_UNSENT = 200;
15921
+ var RemediationConsumer = class {
15922
+ constructor(manager, opts) {
15923
+ this.manager = manager;
15924
+ this.opts = opts;
15925
+ }
15926
+ manager;
15927
+ opts;
15928
+ timer = null;
15929
+ running = false;
15930
+ lastError = "";
15931
+ unsent = /* @__PURE__ */ new Map();
15932
+ start() {
15933
+ this.timer = setInterval(() => void this.tick(), this.opts.pollMs ?? 15e3);
15934
+ this.timer.unref?.();
15935
+ void this.tick();
15936
+ }
15937
+ stop() {
15938
+ if (this.timer) clearInterval(this.timer);
15939
+ this.timer = null;
15940
+ }
15941
+ async tick() {
15942
+ if (this.running) return;
15943
+ const link = currentLink();
15944
+ if (!link) return;
15945
+ this.running = true;
15946
+ try {
15947
+ for (const [id, { orgId, result }] of [...this.unsent]) {
15948
+ if (await this.report(orgId, id, result)) this.unsent.delete(id);
15949
+ }
15950
+ for (const action of await this.claim(link)) {
15951
+ const result = await this.execute(action);
15952
+ this.opts.log(
15953
+ `[cloud] dashboard ${action.action_type} ${action.target_value} \u2192 ${result.status}${result.dry_run ? " (dry-run)" : ""}${result.error ? `: ${result.error}` : ""}`
15954
+ );
15955
+ if (!await this.report(link.orgId, action.id, result) && this.unsent.size < MAX_UNSENT) {
15956
+ this.unsent.set(action.id, { orgId: link.orgId, result });
15957
+ }
15958
+ }
15959
+ } catch (err) {
15960
+ const message = err.message;
15961
+ if (message !== this.lastError) this.opts.log(`[cloud] remediation poll failed: ${message}`);
15962
+ this.lastError = message;
15963
+ } finally {
15964
+ this.running = false;
15965
+ }
15966
+ }
15967
+ async claim(link) {
15968
+ const res = await cloudFetch(
15969
+ `/api/orgs/${link.orgId}/servers/${link.serverId}/remediations/claim`,
15970
+ { method: "POST", body: "{}" }
15971
+ );
15972
+ this.lastError = "";
15973
+ if (!res.ok) return [];
15974
+ const data = await res.json().catch(() => ({}));
15975
+ return Array.isArray(data.actions) ? data.actions : [];
15976
+ }
15977
+ /** True once the dashboard has the result, or can never take it (409/404). */
15978
+ async report(orgId, id, result) {
15979
+ try {
15980
+ const res = await cloudFetch(`/api/orgs/${orgId}/remediations/${id}`, {
15981
+ method: "PATCH",
15982
+ body: JSON.stringify(result)
15983
+ });
15984
+ if (res.ok) return true;
15985
+ if (res.status === 409 || res.status === 404 || res.status === 400) {
15986
+ this.opts.log(`[cloud] dashboard would not take the result for ${id} (${res.status})`);
15987
+ return true;
15988
+ }
15989
+ return false;
15990
+ } catch {
15991
+ return false;
15992
+ }
15993
+ }
15994
+ async execute(action) {
15995
+ const executed_at = (/* @__PURE__ */ new Date()).toISOString();
15996
+ const failed = (error) => ({ status: "failed", error, executed_at });
15997
+ const target = String(action.target_value ?? "").trim();
15998
+ const meta = action.metadata ?? {};
15999
+ try {
16000
+ switch (action.action_type) {
16001
+ case "block": {
16002
+ if ((0, import_node_net5.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
16003
+ let ttlSeconds = this.manager.status().max_ban_seconds;
16004
+ if (action.expires_at) {
16005
+ const until = Date.parse(action.expires_at);
16006
+ if (Number.isNaN(until)) return failed(`unreadable expires_at: ${action.expires_at}`);
16007
+ ttlSeconds = Math.ceil((until - Date.now()) / 1e3);
16008
+ if (ttlSeconds <= 0) return failed("expired before this server picked it up");
16009
+ }
16010
+ const reason = typeof meta.reason === "string" && meta.reason ? meta.reason : "blocked from the ThreatCrush dashboard";
16011
+ const result = await this.manager.ban(target, reason, {
16012
+ ttlSeconds,
16013
+ source: "manual",
16014
+ origin: "cloud",
16015
+ ruleId: typeof meta.rule_id === "string" ? meta.rule_id : void 0
16016
+ });
16017
+ if (!result.ok) return failed(result.error ?? "block failed");
16018
+ return { status: "executed", dry_run: result.entry?.dry_run === true, executed_at };
16019
+ }
16020
+ case "unblock": {
16021
+ if ((0, import_node_net5.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
16022
+ const wasBanned = this.manager.getBlocklist().some((b) => b.ip === target);
16023
+ const result = await this.manager.unban(target, {
16024
+ forget: true,
16025
+ origin: "cloud",
16026
+ reason: "unblocked from the ThreatCrush dashboard"
16027
+ });
16028
+ if (!result.ok && wasBanned) {
16029
+ return failed(result.error ?? "unblock failed");
16030
+ }
16031
+ return { status: "executed", dry_run: this.manager.status().dry_run, executed_at };
16032
+ }
16033
+ case "allowlist_add":
16034
+ if (!isAddressOrCidr(target)) return failed(`not an IP address or CIDR: ${target}`);
16035
+ this.manager.addToAllowlist(target);
16036
+ return { status: "executed", executed_at };
16037
+ case "allowlist_remove":
16038
+ if (DEFAULT_PROTECTED.includes(target)) {
16039
+ return failed(`${target} is a built-in protected range and cannot be removed`);
16040
+ }
16041
+ this.manager.removeFromAllowlist(target);
16042
+ return { status: "executed", executed_at };
16043
+ default:
16044
+ return failed(`unsupported action_type: ${action.action_type}`);
16045
+ }
16046
+ } catch (err) {
16047
+ return failed(err.message);
16048
+ }
16049
+ }
16050
+ };
16051
+
15216
16052
  // src/daemon/rules/engine.ts
15217
16053
  var RuleEngine = class {
15218
16054
  constructor(onDetection) {
@@ -15334,8 +16170,8 @@ var RuleEngine = class {
15334
16170
  };
15335
16171
 
15336
16172
  // src/daemon/rules/loader.ts
15337
- var import_node_fs17 = require("fs");
15338
- var import_node_path13 = require("path");
16173
+ var import_node_fs18 = require("fs");
16174
+ var import_node_path14 = require("path");
15339
16175
 
15340
16176
  // src/daemon/rules/default-rules.ts
15341
16177
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -15696,11 +16532,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
15696
16532
  function loadAllRules(customDir) {
15697
16533
  const rules = [...DEFAULT_RULES];
15698
16534
  const dir = customDir || RULES_DIR;
15699
- if ((0, import_node_fs17.existsSync)(dir)) {
15700
- const files = (0, import_node_fs17.readdirSync)(dir).filter((f) => f.endsWith(".json"));
16535
+ if ((0, import_node_fs18.existsSync)(dir)) {
16536
+ const files = (0, import_node_fs18.readdirSync)(dir).filter((f) => f.endsWith(".json"));
15701
16537
  for (const file of files) {
15702
16538
  try {
15703
- const raw = (0, import_node_fs17.readFileSync)((0, import_node_path13.join)(dir, file), "utf-8");
16539
+ const raw = (0, import_node_fs18.readFileSync)((0, import_node_path14.join)(dir, file), "utf-8");
15704
16540
  const parsed = JSON.parse(raw);
15705
16541
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
15706
16542
  for (const rule of customRules) {
@@ -15731,24 +16567,24 @@ function loadAllRules(customDir) {
15731
16567
  }
15732
16568
 
15733
16569
  // src/daemon/firewall/adapters.ts
15734
- var import_node_child_process4 = require("child_process");
15735
- var import_node_fs18 = require("fs");
15736
- var import_node_path14 = require("path");
15737
- var import_node_net2 = require("net");
16570
+ var import_node_child_process5 = require("child_process");
16571
+ var import_node_fs19 = require("fs");
16572
+ var import_node_path15 = require("path");
16573
+ var import_node_net6 = require("net");
15738
16574
  function assertValidFirewallIp(ip) {
15739
- if ((0, import_node_net2.isIP)(ip) !== 4) {
16575
+ if ((0, import_node_net6.isIP)(ip) !== 4) {
15740
16576
  throw new Error(`Invalid IPv4 address: ${ip}`);
15741
16577
  }
15742
16578
  }
15743
16579
  function assertBannableIp(ip) {
15744
- if ((0, import_node_net2.isIP)(ip) === 0) {
16580
+ if ((0, import_node_net6.isIP)(ip) === 0) {
15745
16581
  throw new Error(`Invalid IP address: ${ip}`);
15746
16582
  }
15747
16583
  }
15748
16584
  function writeIfAbsent(path, contents) {
15749
- (0, import_node_fs18.mkdirSync)((0, import_node_path14.dirname)(path), { recursive: true });
16585
+ (0, import_node_fs19.mkdirSync)((0, import_node_path15.dirname)(path), { recursive: true });
15750
16586
  try {
15751
- (0, import_node_fs18.writeFileSync)(path, contents, { flag: "wx" });
16587
+ (0, import_node_fs19.writeFileSync)(path, contents, { flag: "wx" });
15752
16588
  } catch (err) {
15753
16589
  if (err.code !== "EEXIST") throw err;
15754
16590
  }
@@ -15767,11 +16603,11 @@ var Fail2banAdapter = class {
15767
16603
  enforces = true;
15768
16604
  jailReady = false;
15769
16605
  isAvailable() {
15770
- const result = (0, import_node_child_process4.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
16606
+ const result = (0, import_node_child_process5.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
15771
16607
  return result.status === 0;
15772
16608
  }
15773
16609
  client(args) {
15774
- return (0, import_node_child_process4.execFileSync)("fail2ban-client", args, {
16610
+ return (0, import_node_child_process5.execFileSync)("fail2ban-client", args, {
15775
16611
  encoding: "utf-8",
15776
16612
  stdio: ["ignore", "pipe", "pipe"]
15777
16613
  });
@@ -15843,7 +16679,7 @@ var Fail2banAdapter = class {
15843
16679
  const status = this.client(["status", this.jail]);
15844
16680
  const line = status.split("\n").find((l) => /Banned IP list:/i.test(l));
15845
16681
  if (!line) return [];
15846
- return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net2.isIP)(s) !== 0);
16682
+ return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net6.isIP)(s) !== 0);
15847
16683
  } catch {
15848
16684
  return [];
15849
16685
  }
@@ -15853,45 +16689,45 @@ var Fail2banAdapter = class {
15853
16689
  function parseBannedList(output) {
15854
16690
  const found = [];
15855
16691
  for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
15856
- if ((0, import_node_net2.isIP)(match[1]) !== 0) found.push(match[1]);
16692
+ if ((0, import_node_net6.isIP)(match[1]) !== 0) found.push(match[1]);
15857
16693
  }
15858
16694
  if (found.length > 0) return found;
15859
- return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net2.isIP)(s) !== 0);
16695
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net6.isIP)(s) !== 0);
15860
16696
  }
15861
16697
  var NftablesAdapter = class {
15862
16698
  name = "nftables";
15863
16699
  table = "threatcrush";
15864
16700
  set = "blocklist";
15865
16701
  isAvailable() {
15866
- const result = (0, import_node_child_process4.spawnSync)("nft", ["--version"], { stdio: "pipe" });
16702
+ const result = (0, import_node_child_process5.spawnSync)("nft", ["--version"], { stdio: "pipe" });
15867
16703
  return result.status === 0;
15868
16704
  }
15869
16705
  ensureSetup() {
15870
16706
  try {
15871
- (0, import_node_child_process4.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
16707
+ (0, import_node_child_process5.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
15872
16708
  } catch {
15873
- (0, import_node_child_process4.execSync)(`nft add table inet ${this.table}`);
15874
- (0, import_node_child_process4.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
15875
- (0, import_node_child_process4.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
15876
- (0, import_node_child_process4.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
16709
+ (0, import_node_child_process5.execSync)(`nft add table inet ${this.table}`);
16710
+ (0, import_node_child_process5.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
16711
+ (0, import_node_child_process5.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
16712
+ (0, import_node_child_process5.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
15877
16713
  }
15878
16714
  }
15879
16715
  async block(ip) {
15880
16716
  assertValidFirewallIp(ip);
15881
16717
  this.ensureSetup();
15882
- (0, import_node_child_process4.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
16718
+ (0, import_node_child_process5.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
15883
16719
  }
15884
16720
  async unblock(ip) {
15885
16721
  assertValidFirewallIp(ip);
15886
16722
  try {
15887
- (0, import_node_child_process4.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
16723
+ (0, import_node_child_process5.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
15888
16724
  } catch {
15889
16725
  }
15890
16726
  }
15891
16727
  async isBlocked(ip) {
15892
16728
  assertValidFirewallIp(ip);
15893
16729
  try {
15894
- const output = (0, import_node_child_process4.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
16730
+ const output = (0, import_node_child_process5.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
15895
16731
  return output.includes(ip);
15896
16732
  } catch {
15897
16733
  return false;
@@ -15899,7 +16735,7 @@ var NftablesAdapter = class {
15899
16735
  }
15900
16736
  async listBlocked() {
15901
16737
  try {
15902
- const output = (0, import_node_child_process4.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
16738
+ const output = (0, import_node_child_process5.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
15903
16739
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
15904
16740
  if (!match) return [];
15905
16741
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -15912,34 +16748,34 @@ var IptablesAdapter = class {
15912
16748
  name = "iptables";
15913
16749
  chain = "THREATCRUSH";
15914
16750
  isAvailable() {
15915
- const result = (0, import_node_child_process4.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
16751
+ const result = (0, import_node_child_process5.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
15916
16752
  return result.status === 0;
15917
16753
  }
15918
16754
  ensureChain() {
15919
16755
  try {
15920
- (0, import_node_child_process4.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
16756
+ (0, import_node_child_process5.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
15921
16757
  } catch {
15922
- (0, import_node_child_process4.execSync)(`iptables -N ${this.chain}`);
15923
- (0, import_node_child_process4.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
16758
+ (0, import_node_child_process5.execSync)(`iptables -N ${this.chain}`);
16759
+ (0, import_node_child_process5.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
15924
16760
  }
15925
16761
  }
15926
16762
  async block(ip) {
15927
16763
  assertValidFirewallIp(ip);
15928
16764
  this.ensureChain();
15929
16765
  if (await this.isBlocked(ip)) return;
15930
- (0, import_node_child_process4.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
16766
+ (0, import_node_child_process5.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
15931
16767
  }
15932
16768
  async unblock(ip) {
15933
16769
  assertValidFirewallIp(ip);
15934
16770
  try {
15935
- (0, import_node_child_process4.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
16771
+ (0, import_node_child_process5.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
15936
16772
  } catch {
15937
16773
  }
15938
16774
  }
15939
16775
  async isBlocked(ip) {
15940
16776
  assertValidFirewallIp(ip);
15941
16777
  try {
15942
- const output = (0, import_node_child_process4.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
16778
+ const output = (0, import_node_child_process5.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
15943
16779
  return output.includes(ip);
15944
16780
  } catch {
15945
16781
  return false;
@@ -15947,7 +16783,7 @@ var IptablesAdapter = class {
15947
16783
  }
15948
16784
  async listBlocked() {
15949
16785
  try {
15950
- const output = (0, import_node_child_process4.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
16786
+ const output = (0, import_node_child_process5.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
15951
16787
  const ips = [];
15952
16788
  for (const line of output.split("\n")) {
15953
16789
  const match = line.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -16003,137 +16839,8 @@ function detectFirewallAdapter(backend = "auto") {
16003
16839
  }
16004
16840
 
16005
16841
  // src/daemon/firewall/remediation.ts
16006
- var import_node_fs19 = require("fs");
16007
- var import_node_net4 = require("net");
16008
-
16009
- // src/daemon/firewall/protected.ts
16010
- var import_node_child_process5 = require("child_process");
16011
- var import_node_net3 = require("net");
16012
- var DEFAULT_PROTECTED = [
16013
- "127.0.0.0/8",
16014
- "::1/128",
16015
- "10.0.0.0/8",
16016
- "172.16.0.0/12",
16017
- "192.168.0.0/16",
16018
- "169.254.0.0/16",
16019
- "fc00::/7",
16020
- "fe80::/10"
16021
- ];
16022
- function ipToBytes(ip) {
16023
- const version = (0, import_node_net3.isIP)(ip);
16024
- if (version === 4) return v4ToBytes(ip);
16025
- if (version === 6) return v6ToBytes(ip);
16026
- return null;
16027
- }
16028
- function v4ToBytes(ip) {
16029
- const parts = ip.split(".");
16030
- if (parts.length !== 4) return null;
16031
- const bytes = new Uint8Array(4);
16032
- for (let i = 0; i < 4; i++) {
16033
- const n = Number(parts[i]);
16034
- if (!Number.isInteger(n) || n < 0 || n > 255) return null;
16035
- bytes[i] = n;
16036
- }
16037
- return bytes;
16038
- }
16039
- function v6ToBytes(ip) {
16040
- const bare = ip.split("%")[0];
16041
- const [headText, tailText] = bare.split("::", 2);
16042
- const head = headText ? headText.split(":") : [];
16043
- const tail = tailText !== void 0 ? tailText ? tailText.split(":") : [] : null;
16044
- const groups = [];
16045
- const pushGroup = (group) => {
16046
- if (group.includes(".")) {
16047
- const v4 = v4ToBytes(group);
16048
- if (!v4) return false;
16049
- groups.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
16050
- return true;
16051
- }
16052
- if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return false;
16053
- groups.push(parseInt(group, 16));
16054
- return true;
16055
- };
16056
- for (const group of head) if (!pushGroup(group)) return null;
16057
- const headCount = groups.length;
16058
- if (tail === null) {
16059
- if (headCount !== 8) return null;
16060
- } else {
16061
- const tailGroups = [];
16062
- const saved = groups.length;
16063
- for (const group of tail) if (!pushGroup(group)) return null;
16064
- tailGroups.push(...groups.splice(saved));
16065
- const zeros = 8 - headCount - tailGroups.length;
16066
- if (zeros < 0) return null;
16067
- for (let i = 0; i < zeros; i++) groups.push(0);
16068
- groups.push(...tailGroups);
16069
- }
16070
- if (groups.length !== 8) return null;
16071
- const bytes = new Uint8Array(16);
16072
- for (let i = 0; i < 8; i++) {
16073
- bytes[i * 2] = groups[i] >> 8 & 255;
16074
- bytes[i * 2 + 1] = groups[i] & 255;
16075
- }
16076
- return bytes;
16077
- }
16078
- function ipMatches(ip, entry) {
16079
- const [network, prefixText] = entry.trim().split("/");
16080
- const target = ipToBytes(ip);
16081
- const base = ipToBytes(network);
16082
- if (!target || !base || target.length !== base.length) return false;
16083
- const bits = prefixText === void 0 ? base.length * 8 : Number(prefixText);
16084
- if (!Number.isInteger(bits) || bits < 0 || bits > base.length * 8) return false;
16085
- const wholeBytes = Math.floor(bits / 8);
16086
- for (let i = 0; i < wholeBytes; i++) {
16087
- if (target[i] !== base[i]) return false;
16088
- }
16089
- const remainder = bits % 8;
16090
- if (remainder === 0) return true;
16091
- const mask = 255 << 8 - remainder & 255;
16092
- return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
16093
- }
16094
- function isProtected(ip, list) {
16095
- return list.some((entry) => ipMatches(ip, entry));
16096
- }
16097
- function currentSshClient(env2 = process.env) {
16098
- const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
16099
- if (!source) return null;
16100
- const ip = source.trim().split(/\s+/)[0];
16101
- return ip && (0, import_node_net3.isIP)(ip) ? ip : null;
16102
- }
16103
- function establishedSshPeers() {
16104
- const peers = /* @__PURE__ */ new Set();
16105
- try {
16106
- const out = (0, import_node_child_process5.execFileSync)("ss", ["-tnpH"], {
16107
- encoding: "utf-8",
16108
- stdio: ["ignore", "pipe", "ignore"],
16109
- timeout: 3e3
16110
- });
16111
- for (const line of out.split("\n")) {
16112
- if (!/users:\(\("sshd/.test(line)) continue;
16113
- const parts = line.trim().split(/\s+/);
16114
- const peer = parts[4];
16115
- if (!peer) continue;
16116
- const ip = peer.slice(0, peer.lastIndexOf(":")).replace(/^\[|\]$/g, "");
16117
- if (ip && (0, import_node_net3.isIP)(ip)) peers.add(ip);
16118
- }
16119
- } catch {
16120
- }
16121
- return [...peers];
16122
- }
16123
- function defaultGateways() {
16124
- const found = /* @__PURE__ */ new Set();
16125
- for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
16126
- try {
16127
- const out = (0, import_node_child_process5.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
16128
- for (const line of out.split("\n")) {
16129
- const match = line.match(/\bvia\s+(\S+)/);
16130
- if (match && (0, import_node_net3.isIP)(match[1])) found.add(match[1]);
16131
- }
16132
- } catch {
16133
- }
16134
- }
16135
- return [...found];
16136
- }
16842
+ var import_node_fs20 = require("fs");
16843
+ var import_node_net7 = require("net");
16137
16844
 
16138
16845
  // src/daemon/firewall/crawlers.ts
16139
16846
  var import_node_dns = require("dns");
@@ -16188,7 +16895,7 @@ var DEFAULT_CONFIG2 = {
16188
16895
  protect_current_ssh_client: true,
16189
16896
  spare_verified_crawlers: true
16190
16897
  };
16191
- var SEVERITY_RANK4 = {
16898
+ var SEVERITY_RANK5 = {
16192
16899
  info: 0,
16193
16900
  low: 1,
16194
16901
  medium: 2,
@@ -16211,6 +16918,7 @@ var RemediationManager = class {
16211
16918
  this.bus = bus2;
16212
16919
  this.verifyCrawler = verifyCrawler;
16213
16920
  this.config = { ...DEFAULT_CONFIG2, ...config };
16921
+ this.config.allowlist = [...this.config.allowlist];
16214
16922
  this.protectedList = [...DEFAULT_PROTECTED, ...this.config.allowlist];
16215
16923
  for (const gateway of defaultGateways()) this.protectedList.push(gateway);
16216
16924
  this.refreshSshProtection();
@@ -16251,8 +16959,8 @@ var RemediationManager = class {
16251
16959
  }
16252
16960
  async handleDetection(event) {
16253
16961
  if (!this.config.enabled) return;
16254
- const eventRank = SEVERITY_RANK4[event.severity] ?? 0;
16255
- const minRank = SEVERITY_RANK4[this.config.min_severity] ?? 3;
16962
+ const eventRank = SEVERITY_RANK5[event.severity] ?? 0;
16963
+ const minRank = SEVERITY_RANK5[this.config.min_severity] ?? 3;
16256
16964
  if (eventRank < minRank) return;
16257
16965
  if (isSuccessfulAuth(event.message)) return;
16258
16966
  if (event.details?.rule_id) {
@@ -16260,7 +16968,7 @@ var RemediationManager = class {
16260
16968
  if (remediation?.action !== "block") return;
16261
16969
  }
16262
16970
  const ip = event.source_ip;
16263
- if (!ip || (0, import_node_net4.isIP)(ip) === 0) return;
16971
+ if (!ip || (0, import_node_net7.isIP)(ip) === 0) return;
16264
16972
  if (this.isAllowlisted(ip)) return;
16265
16973
  if (this.blocklist.some((b) => b.ip === ip)) return;
16266
16974
  if (this.config.spare_verified_crawlers) {
@@ -16279,7 +16987,7 @@ var RemediationManager = class {
16279
16987
  * to `max_ban_seconds`.
16280
16988
  */
16281
16989
  async ban(ip, reason, opts = {}) {
16282
- if ((0, import_node_net4.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
16990
+ if ((0, import_node_net7.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
16283
16991
  if (this.isAllowlisted(ip)) {
16284
16992
  return { ok: false, error: `${ip} is protected and can never be blocked` };
16285
16993
  }
@@ -16300,7 +17008,15 @@ var RemediationManager = class {
16300
17008
  category: "system",
16301
17009
  severity: "medium",
16302
17010
  message: `Failed to block ${ip}: ${message}`,
16303
- source_ip: ip
17011
+ source_ip: ip,
17012
+ details: {
17013
+ action: "block",
17014
+ failed: true,
17015
+ error: message,
17016
+ reason,
17017
+ rule_id: opts.ruleId,
17018
+ origin: opts.origin
17019
+ }
16304
17020
  });
16305
17021
  return { ok: false, error: message };
16306
17022
  }
@@ -16333,6 +17049,8 @@ var RemediationManager = class {
16333
17049
  details: {
16334
17050
  action: "block",
16335
17051
  rule_id: opts.ruleId,
17052
+ reason,
17053
+ origin: opts.origin,
16336
17054
  dry_run: this.config.dry_run,
16337
17055
  ttl_seconds: ttl,
16338
17056
  strikes: strike,
@@ -16371,7 +17089,13 @@ var RemediationManager = class {
16371
17089
  severity: "info",
16372
17090
  message: `Unbanned ${ip}`,
16373
17091
  source_ip: ip,
16374
- details: { action: "unblock", forget: opts.forget === true }
17092
+ details: {
17093
+ action: "unblock",
17094
+ forget: opts.forget === true,
17095
+ reason: opts.reason,
17096
+ origin: opts.origin,
17097
+ dry_run: entry?.dry_run === true
17098
+ }
16375
17099
  });
16376
17100
  return { ok: true };
16377
17101
  }
@@ -16480,7 +17204,7 @@ var RemediationManager = class {
16480
17204
  const now = Date.now();
16481
17205
  this.refreshSshProtection();
16482
17206
  for (const entry of this.blocklist.filter((b) => b.expires_at <= now)) {
16483
- await this.unban(entry.ip);
17207
+ await this.unban(entry.ip, { reason: "ban expired" });
16484
17208
  }
16485
17209
  const pruned = pruneStrikes(this.strikes, now, this.config.strike_memory_seconds);
16486
17210
  if (Object.keys(pruned).length !== Object.keys(this.strikes).length) {
@@ -16519,7 +17243,7 @@ var RemediationManager = class {
16519
17243
  }
16520
17244
  logLine(line) {
16521
17245
  try {
16522
- (0, import_node_fs19.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
17246
+ (0, import_node_fs20.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
16523
17247
  `);
16524
17248
  } catch {
16525
17249
  }
@@ -16599,15 +17323,24 @@ async function flushTelemetry(timeoutMs = 2e3) {
16599
17323
  // src/daemon/index.ts
16600
17324
  function readVersion2() {
16601
17325
  try {
16602
- const pkg = JSON.parse((0, import_node_fs20.readFileSync)((0, import_node_path15.join)(__dirname, "..", "package.json"), "utf-8"));
17326
+ const pkg = JSON.parse((0, import_node_fs21.readFileSync)((0, import_node_path16.join)(__dirname, "..", "package.json"), "utf-8"));
16603
17327
  return pkg.version || "0.0.0";
16604
17328
  } catch {
16605
17329
  return "0.0.0";
16606
17330
  }
16607
17331
  }
17332
+ async function runHardeningChecks() {
17333
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process6.execFile)(
17334
+ process.execPath,
17335
+ [(0, import_node_path16.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
17336
+ { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
17337
+ );
17338
+ const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
17339
+ return Array.isArray(parsed.findings) ? parsed.findings : [];
17340
+ }
16608
17341
  function logLine(line) {
16609
17342
  try {
16610
- (0, import_node_fs20.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
17343
+ (0, import_node_fs21.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
16611
17344
  `);
16612
17345
  } catch {
16613
17346
  }
@@ -16635,7 +17368,7 @@ async function runDaemon() {
16635
17368
  } catch (err) {
16636
17369
  logLine(`[daemon] state db unavailable: ${err.message}`);
16637
17370
  }
16638
- const config = loadConfig((0, import_node_fs20.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
17371
+ const config = loadConfig((0, import_node_fs21.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
16639
17372
  configureAttackDetection(config.detection);
16640
17373
  bus.on("event", (event) => {
16641
17374
  logLine(`[event] ${event.severity} ${event.module} ${event.message}`);
@@ -16652,6 +17385,7 @@ async function runDaemon() {
16652
17385
  source_ip: detection.source_ip,
16653
17386
  details: {
16654
17387
  rule_id: detection.rule_id,
17388
+ description: detection.description,
16655
17389
  username: detection.username,
16656
17390
  ...detection.raw_metadata
16657
17391
  }
@@ -16689,6 +17423,31 @@ async function runDaemon() {
16689
17423
  } catch (err) {
16690
17424
  logLine(`[daemon] runs-worker failed to start: ${err.message}`);
16691
17425
  }
17426
+ let cloudSync = null;
17427
+ let remediationConsumer = null;
17428
+ let allowlistSync = null;
17429
+ if (config.cloud?.enabled === false) {
17430
+ logLine("[cloud] disabled by [cloud] enabled = false");
17431
+ } else {
17432
+ const minSeverity = config.cloud?.min_severity ?? "medium";
17433
+ cloudSync = new CloudSync({
17434
+ bus,
17435
+ version,
17436
+ hostname: (0, import_node_os5.hostname)(),
17437
+ minSeverity,
17438
+ spoolPath: (0, import_node_path16.join)(PATHS.stateDir, "cloud-spool.jsonl"),
17439
+ log: logLine,
17440
+ ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
17441
+ runHardening: runHardeningChecks
17442
+ });
17443
+ cloudSync.start();
17444
+ remediationConsumer = new RemediationConsumer(remediation, { log: logLine });
17445
+ remediationConsumer.start();
17446
+ allowlistSync = new AllowlistSync(remediation, { log: logLine });
17447
+ allowlistSync.start();
17448
+ const link = currentLink();
17449
+ 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");
17450
+ }
16692
17451
  const ipc = new IpcServer(version, moduleHost, remediation);
16693
17452
  await ipc.start();
16694
17453
  logLine(`[daemon] ipc listening on ${PATHS.socket}`);
@@ -16702,6 +17461,18 @@ async function runDaemon() {
16702
17461
  runsWorker.stop();
16703
17462
  } catch {
16704
17463
  }
17464
+ try {
17465
+ remediationConsumer?.stop();
17466
+ } catch {
17467
+ }
17468
+ try {
17469
+ allowlistSync?.stop();
17470
+ } catch {
17471
+ }
17472
+ try {
17473
+ await cloudSync?.stop();
17474
+ } catch {
17475
+ }
16705
17476
  try {
16706
17477
  await moduleHost.stop();
16707
17478
  } catch {