@profullstack/threatcrush 0.13.36 → 0.13.38

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
@@ -2022,10 +2022,10 @@ var require_toml = __commonJS({
2022
2022
  });
2023
2023
 
2024
2024
  // src/daemon/index.ts
2025
- var import_node_fs27 = require("fs");
2026
- var import_node_child_process10 = require("child_process");
2025
+ var import_node_fs29 = require("fs");
2026
+ var import_node_child_process11 = require("child_process");
2027
2027
  var import_node_os5 = require("os");
2028
- var import_node_path21 = require("path");
2028
+ var import_node_path22 = require("path");
2029
2029
  var import_node_util = require("util");
2030
2030
 
2031
2031
  // src/daemon/paths.ts
@@ -2674,7 +2674,7 @@ function admGid(readGroup = () => (0, import_node_fs4.readFileSync)("/etc/group"
2674
2674
  }
2675
2675
 
2676
2676
  // src/daemon/module-host.ts
2677
- var import_node_fs13 = require("fs");
2677
+ var import_node_fs14 = require("fs");
2678
2678
  var import_node_path7 = require("path");
2679
2679
  var import_node_url = require("url");
2680
2680
  var import_toml2 = __toESM(require_toml());
@@ -10149,17 +10149,18 @@ var NetworkMonitor = class {
10149
10149
  };
10150
10150
 
10151
10151
  // src/modules/dns-monitor/index.ts
10152
- var import_node_fs11 = require("fs");
10152
+ var import_node_fs12 = require("fs");
10153
10153
  var import_node_child_process4 = require("child_process");
10154
10154
  var import_node_readline = require("readline");
10155
10155
 
10156
10156
  // src/core/threat-feeds/index.ts
10157
- var import_node_fs10 = require("fs");
10157
+ var import_node_fs11 = require("fs");
10158
10158
  var import_node_path5 = require("path");
10159
10159
  var import_node_net3 = require("net");
10160
10160
 
10161
10161
  // src/daemon/firewall/protected.ts
10162
10162
  var import_node_child_process3 = require("child_process");
10163
+ var import_node_fs10 = require("fs");
10163
10164
  var import_node_net2 = require("net");
10164
10165
  var DEFAULT_PROTECTED = [
10165
10166
  "127.0.0.0/8",
@@ -10272,6 +10273,45 @@ function establishedSshPeers() {
10272
10273
  }
10273
10274
  return [...peers];
10274
10275
  }
10276
+ function sshClientFromEnviron(environ) {
10277
+ for (const entry of environ.split("\0")) {
10278
+ const m = /^SSH_(?:CONNECTION|CLIENT)=(\S+)/.exec(entry);
10279
+ if (m && (0, import_node_net2.isIP)(m[1])) return m[1];
10280
+ }
10281
+ return null;
10282
+ }
10283
+ function moshClients(procDir = "/proc") {
10284
+ const found = /* @__PURE__ */ new Set();
10285
+ let pids = [];
10286
+ try {
10287
+ pids = (0, import_node_fs10.readdirSync)(procDir).filter((p) => /^\d+$/.test(p));
10288
+ } catch {
10289
+ return [];
10290
+ }
10291
+ for (const pid of pids) {
10292
+ try {
10293
+ if ((0, import_node_fs10.readFileSync)(`${procDir}/${pid}/comm`, "utf-8").trim() !== "mosh-server") continue;
10294
+ const ip = sshClientFromEnviron((0, import_node_fs10.readFileSync)(`${procDir}/${pid}/environ`, "latin1"));
10295
+ if (ip) found.add(ip);
10296
+ } catch {
10297
+ }
10298
+ }
10299
+ return [...found];
10300
+ }
10301
+ function parseKeyLogins(text, skip = () => false) {
10302
+ const out = /* @__PURE__ */ new Map();
10303
+ for (const line of text.split("\n")) {
10304
+ const m = /^(\d+(?:\.\d+)?)\s.*Accepted publickey for \S+ from (\S+) port \d+ [^\s:]+(?:: \S+ (SHA256:\S+))?/.exec(line);
10305
+ if (!m || !(0, import_node_net2.isIP)(m[2])) continue;
10306
+ if (m[3] && skip(m[3])) continue;
10307
+ const at = Math.round(Number(m[1]) * 1e3);
10308
+ if (at > (out.get(m[2]) ?? 0)) out.set(m[2], at);
10309
+ }
10310
+ return out;
10311
+ }
10312
+ function isAutomationKeyComment(comment) {
10313
+ return /github-actions|gitlab|jenkins|buildkite|circleci|drone|\bci\b|runner|deploy|backup|automation|\bbot\b/i.test(comment);
10314
+ }
10275
10315
  function defaultGateways() {
10276
10316
  const found = /* @__PURE__ */ new Set();
10277
10317
  for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
@@ -10457,17 +10497,38 @@ async function fetchFeeds(settings, fetchImpl = fetch) {
10457
10497
  }
10458
10498
  function readFeedCache(path) {
10459
10499
  try {
10460
- const set = JSON.parse((0, import_node_fs10.readFileSync)(path, "utf-8"));
10500
+ const set = JSON.parse((0, import_node_fs11.readFileSync)(path, "utf-8"));
10461
10501
  return set && typeof set.ips === "object" && typeof set.domains === "object" ? set : null;
10462
10502
  } catch {
10463
10503
  return null;
10464
10504
  }
10465
10505
  }
10466
10506
  function writeFeedCache(path, set) {
10467
- (0, import_node_fs10.mkdirSync)((0, import_node_path5.dirname)(path), { recursive: true });
10507
+ (0, import_node_fs11.mkdirSync)((0, import_node_path5.dirname)(path), { recursive: true });
10468
10508
  const tmp = `${path}.tmp`;
10469
- (0, import_node_fs10.writeFileSync)(tmp, JSON.stringify(set));
10470
- (0, import_node_fs10.renameSync)(tmp, path);
10509
+ (0, import_node_fs11.writeFileSync)(tmp, JSON.stringify(set));
10510
+ (0, import_node_fs11.renameSync)(tmp, path);
10511
+ }
10512
+ var RESOLVER_FILES = {
10513
+ hosts: "blocked-domains.hosts",
10514
+ unbound: "blocked-domains.unbound.conf"
10515
+ };
10516
+ var RESOLVER_HOOKS = {
10517
+ dnsmasq: "/etc/dnsmasq.d/threatcrush.conf",
10518
+ unbound: "/etc/unbound/unbound.conf.d/threatcrush.conf"
10519
+ };
10520
+ var GENERATED = "# Written by threatcrushd from abuse.ch feeds; rewritten every refresh. Do not edit.";
10521
+ function hostsBlocklist(domains) {
10522
+ const lines = [GENERATED];
10523
+ for (const d of domains) lines.push(`0.0.0.0 ${d}`, `:: ${d}`);
10524
+ return `${lines.join("\n")}
10525
+ `;
10526
+ }
10527
+ function unboundBlocklist(domains) {
10528
+ const lines = [GENERATED, "server:"];
10529
+ for (const d of domains) lines.push(` local-zone: "${d}." always_nxdomain`);
10530
+ return `${lines.join("\n")}
10531
+ `;
10471
10532
  }
10472
10533
  var active = null;
10473
10534
  function setActiveFeeds(set) {
@@ -10571,9 +10632,9 @@ var DnsMonitor = class {
10571
10632
  }
10572
10633
  start() {
10573
10634
  const sources = [...DNS_LOG_SOURCES, ...this.extraPaths].filter((p) => {
10574
- if (!(0, import_node_fs11.existsSync)(p)) return false;
10635
+ if (!(0, import_node_fs12.existsSync)(p)) return false;
10575
10636
  try {
10576
- (0, import_node_fs11.accessSync)(p, import_node_fs11.constants.R_OK);
10637
+ (0, import_node_fs12.accessSync)(p, import_node_fs12.constants.R_OK);
10577
10638
  return true;
10578
10639
  } catch {
10579
10640
  return false;
@@ -10817,7 +10878,7 @@ var DnsMonitor = class {
10817
10878
  };
10818
10879
 
10819
10880
  // src/core/config.ts
10820
- var import_node_fs12 = require("fs");
10881
+ var import_node_fs13 = require("fs");
10821
10882
  var import_node_path6 = require("path");
10822
10883
  var import_toml = __toESM(require_toml());
10823
10884
  var DEFAULT_CONFIG_PATH = "/etc/threatcrush/threatcrushd.conf";
@@ -10844,11 +10905,11 @@ var DEFAULT_CONFIG = {
10844
10905
  };
10845
10906
  function loadConfig(configPath) {
10846
10907
  const path = configPath || DEFAULT_CONFIG_PATH;
10847
- if (!(0, import_node_fs12.existsSync)(path)) {
10908
+ if (!(0, import_node_fs13.existsSync)(path)) {
10848
10909
  return { ...DEFAULT_CONFIG };
10849
10910
  }
10850
10911
  try {
10851
- const raw = (0, import_node_fs12.readFileSync)(path, "utf-8");
10912
+ const raw = (0, import_node_fs13.readFileSync)(path, "utf-8");
10852
10913
  const parsed = import_toml.default.parse(raw);
10853
10914
  return {
10854
10915
  daemon: { ...DEFAULT_CONFIG.daemon, ...parsed.daemon },
@@ -10872,13 +10933,13 @@ function loadConfig(configPath) {
10872
10933
  function loadModuleConfigs(confDir) {
10873
10934
  const dir = confDir || DEFAULT_CONFDIR;
10874
10935
  const configs = /* @__PURE__ */ new Map();
10875
- if (!(0, import_node_fs12.existsSync)(dir)) {
10936
+ if (!(0, import_node_fs13.existsSync)(dir)) {
10876
10937
  return configs;
10877
10938
  }
10878
- const files = (0, import_node_fs12.readdirSync)(dir).filter((f) => f.endsWith(".conf"));
10939
+ const files = (0, import_node_fs13.readdirSync)(dir).filter((f) => f.endsWith(".conf"));
10879
10940
  for (const file of files) {
10880
10941
  try {
10881
- const raw = (0, import_node_fs12.readFileSync)((0, import_node_path6.join)(dir, file), "utf-8");
10942
+ const raw = (0, import_node_fs13.readFileSync)((0, import_node_path6.join)(dir, file), "utf-8");
10882
10943
  const parsed = import_toml.default.parse(raw);
10883
10944
  for (const [name, config] of Object.entries(parsed)) {
10884
10945
  configs.set(name, config);
@@ -11012,15 +11073,15 @@ var ModuleHost = class {
11012
11073
  }
11013
11074
  }
11014
11075
  async discoverAndStartInstalled() {
11015
- if (!(0, import_node_fs13.existsSync)(PATHS.moduleDir)) return;
11076
+ if (!(0, import_node_fs14.existsSync)(PATHS.moduleDir)) return;
11016
11077
  const configs = loadModuleConfigs(PATHS.confD);
11017
- const entries = (0, import_node_fs13.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
11078
+ const entries = (0, import_node_fs14.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
11018
11079
  for (const entry of entries) {
11019
11080
  if (!entry.isDirectory()) continue;
11020
11081
  const manifestPath = (0, import_node_path7.join)(PATHS.moduleDir, entry.name, "mod.toml");
11021
- if (!(0, import_node_fs13.existsSync)(manifestPath)) continue;
11082
+ if (!(0, import_node_fs14.existsSync)(manifestPath)) continue;
11022
11083
  try {
11023
- const manifest = import_toml2.default.parse((0, import_node_fs13.readFileSync)(manifestPath, "utf-8"));
11084
+ const manifest = import_toml2.default.parse((0, import_node_fs14.readFileSync)(manifestPath, "utf-8"));
11024
11085
  const name = manifest.module?.name || entry.name;
11025
11086
  const defaults = manifest.module?.config?.defaults || {};
11026
11087
  const config = {
@@ -11090,15 +11151,15 @@ var ModuleHost = class {
11090
11151
  installedEntrypoint(modulePath) {
11091
11152
  const packageJson = (0, import_node_path7.join)(modulePath, "package.json");
11092
11153
  const candidates = [];
11093
- if ((0, import_node_fs13.existsSync)(packageJson)) {
11154
+ if ((0, import_node_fs14.existsSync)(packageJson)) {
11094
11155
  try {
11095
- const pkg = JSON.parse((0, import_node_fs13.readFileSync)(packageJson, "utf-8"));
11156
+ const pkg = JSON.parse((0, import_node_fs14.readFileSync)(packageJson, "utf-8"));
11096
11157
  if (pkg.main) candidates.push((0, import_node_path7.join)(modulePath, pkg.main));
11097
11158
  } catch {
11098
11159
  }
11099
11160
  }
11100
11161
  candidates.push((0, import_node_path7.join)(modulePath, "dist", "index.js"), (0, import_node_path7.join)(modulePath, "index.js"));
11101
- return candidates.find((candidate) => (0, import_node_fs13.existsSync)(candidate)) || null;
11162
+ return candidates.find((candidate) => (0, import_node_fs14.existsSync)(candidate)) || null;
11102
11163
  }
11103
11164
  isThreatCrushModule(value) {
11104
11165
  return Boolean(
@@ -11370,7 +11431,7 @@ function slackChannel(webhookUrl) {
11370
11431
  }
11371
11432
 
11372
11433
  // src/core/cli-config.ts
11373
- var import_node_fs14 = require("fs");
11434
+ var import_node_fs15 = require("fs");
11374
11435
  var import_node_path8 = require("path");
11375
11436
  var import_node_os2 = require("os");
11376
11437
  var CLI_CONFIG_DIR = (0, import_node_path8.join)((0, import_node_os2.homedir)(), ".threatcrush");
@@ -11380,16 +11441,16 @@ function apiUrl() {
11380
11441
  }
11381
11442
  function readCliConfig() {
11382
11443
  try {
11383
- return JSON.parse((0, import_node_fs14.readFileSync)(CLI_CONFIG_PATH, "utf-8"));
11444
+ return JSON.parse((0, import_node_fs15.readFileSync)(CLI_CONFIG_PATH, "utf-8"));
11384
11445
  } catch {
11385
11446
  return {};
11386
11447
  }
11387
11448
  }
11388
11449
  function writeCliConfig(config) {
11389
- if (!(0, import_node_fs14.existsSync)(CLI_CONFIG_DIR)) (0, import_node_fs14.mkdirSync)(CLI_CONFIG_DIR, { recursive: true });
11390
- (0, import_node_fs14.writeFileSync)(CLI_CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
11450
+ if (!(0, import_node_fs15.existsSync)(CLI_CONFIG_DIR)) (0, import_node_fs15.mkdirSync)(CLI_CONFIG_DIR, { recursive: true });
11451
+ (0, import_node_fs15.writeFileSync)(CLI_CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
11391
11452
  try {
11392
- (0, import_node_fs14.chmodSync)(CLI_CONFIG_PATH, 384);
11453
+ (0, import_node_fs15.chmodSync)(CLI_CONFIG_PATH, 384);
11393
11454
  } catch {
11394
11455
  }
11395
11456
  }
@@ -11465,7 +11526,7 @@ async function cloudFetch(path, init = {}) {
11465
11526
  }
11466
11527
 
11467
11528
  // src/commands/scan.ts
11468
- var import_node_fs18 = require("fs");
11529
+ var import_node_fs19 = require("fs");
11469
11530
  var import_node_path13 = require("path");
11470
11531
 
11471
11532
  // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
@@ -11964,13 +12025,13 @@ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
11964
12025
  var source_default = chalk;
11965
12026
 
11966
12027
  // src/core/version.ts
11967
- var import_node_fs15 = require("fs");
12028
+ var import_node_fs16 = require("fs");
11968
12029
  var import_node_path9 = require("path");
11969
12030
  var FALLBACK_VERSION = "0.0.0";
11970
12031
  function readPackageVersion() {
11971
12032
  try {
11972
12033
  const pkg = JSON.parse(
11973
- (0, import_node_fs15.readFileSync)((0, import_node_path9.join)(__dirname, "..", "package.json"), "utf-8")
12034
+ (0, import_node_fs16.readFileSync)((0, import_node_path9.join)(__dirname, "..", "package.json"), "utf-8")
11974
12035
  );
11975
12036
  return pkg.version || FALLBACK_VERSION;
11976
12037
  } catch {
@@ -15000,7 +15061,7 @@ function scanManifest(relativePath, filename, text) {
15000
15061
  }
15001
15062
 
15002
15063
  // ../../packages/scan/src/node/walk.ts
15003
- var import_node_fs16 = require("fs");
15064
+ var import_node_fs17 = require("fs");
15004
15065
  var import_node_path10 = require("path");
15005
15066
  function compileExcludes(patterns) {
15006
15067
  const matchers = patterns.map((p) => p.trim()).filter((p) => p.length > 0 && !p.startsWith("#")).map(compilePattern);
@@ -15072,7 +15133,7 @@ function matchPrefix(parts, segs) {
15072
15133
  }
15073
15134
  function readIgnoreFile(root) {
15074
15135
  try {
15075
- return (0, import_node_fs16.readFileSync)((0, import_node_path10.join)(root, ".threatcrushignore"), "utf-8").split("\n");
15136
+ return (0, import_node_fs17.readFileSync)((0, import_node_path10.join)(root, ".threatcrushignore"), "utf-8").split("\n");
15076
15137
  } catch {
15077
15138
  return [];
15078
15139
  }
@@ -15088,7 +15149,7 @@ function scanPath(targetPath, options = {}) {
15088
15149
  let excluded = 0;
15089
15150
  const rootIsDirectory = (() => {
15090
15151
  try {
15091
- return (0, import_node_fs16.statSync)(targetPath).isDirectory();
15152
+ return (0, import_node_fs17.statSync)(targetPath).isDirectory();
15092
15153
  } catch {
15093
15154
  return true;
15094
15155
  }
@@ -15109,26 +15170,26 @@ function scanPath(targetPath, options = {}) {
15109
15170
  let handle;
15110
15171
  let declared = null;
15111
15172
  try {
15112
- handle = (0, import_node_fs16.openSync)(fullPath, "r");
15173
+ handle = (0, import_node_fs17.openSync)(fullPath, "r");
15113
15174
  } catch {
15114
15175
  unreadable.push(relativePath);
15115
15176
  return;
15116
15177
  }
15117
15178
  try {
15118
- if ((0, import_node_fs16.fstatSync)(handle).size > maxFileBytes) return;
15179
+ if ((0, import_node_fs17.fstatSync)(handle).size > maxFileBytes) return;
15119
15180
  if (mayDeclareInterpreter) {
15120
15181
  const prefix = Buffer.alloc(128);
15121
- const read = (0, import_node_fs16.readSync)(handle, prefix, 0, prefix.length, 0);
15182
+ const read = (0, import_node_fs17.readSync)(handle, prefix, 0, prefix.length, 0);
15122
15183
  declared = languageOfShebang(prefix.subarray(0, read).toString("utf-8").split("\n", 1)[0] ?? "");
15123
15184
  if (!declared) return;
15124
15185
  }
15125
- text = (0, import_node_fs16.readFileSync)(handle, "utf-8");
15186
+ text = (0, import_node_fs17.readFileSync)(handle, "utf-8");
15126
15187
  } catch {
15127
15188
  unreadable.push(relativePath);
15128
15189
  return;
15129
15190
  } finally {
15130
15191
  try {
15131
- (0, import_node_fs16.closeSync)(handle);
15192
+ (0, import_node_fs17.closeSync)(handle);
15132
15193
  } catch {
15133
15194
  }
15134
15195
  }
@@ -15146,7 +15207,7 @@ function scanPath(targetPath, options = {}) {
15146
15207
  const walk = (currentPath) => {
15147
15208
  let entries;
15148
15209
  try {
15149
- entries = (0, import_node_fs16.readdirSync)(currentPath, { withFileTypes: true });
15210
+ entries = (0, import_node_fs17.readdirSync)(currentPath, { withFileTypes: true });
15150
15211
  } catch {
15151
15212
  unreadable.push(toRelative(walkRoot, currentPath));
15152
15213
  return;
@@ -15213,17 +15274,17 @@ function toRelative(base, target) {
15213
15274
  }
15214
15275
 
15215
15276
  // ../../packages/scan/src/node/dependencies.ts
15216
- var import_node_fs17 = require("fs");
15277
+ var import_node_fs18 = require("fs");
15217
15278
  var import_node_path11 = require("path");
15218
15279
  var MAX_DEPS_PER_LOCKFILE = 50;
15219
15280
  async function scanDependencies(targetPath) {
15220
15281
  const findings = [];
15221
15282
  for (const { file, ecosystem, parse } of LOCKFILES) {
15222
15283
  const lockPath = (0, import_node_path11.join)(targetPath, file);
15223
- if (!(0, import_node_fs17.existsSync)(lockPath)) continue;
15284
+ if (!(0, import_node_fs18.existsSync)(lockPath)) continue;
15224
15285
  let deps;
15225
15286
  try {
15226
- deps = dedupe(parse((0, import_node_fs17.readFileSync)(lockPath, "utf-8")));
15287
+ deps = dedupe(parse((0, import_node_fs18.readFileSync)(lockPath, "utf-8")));
15227
15288
  } catch {
15228
15289
  continue;
15229
15290
  }
@@ -15447,7 +15508,7 @@ function readVersion() {
15447
15508
  (0, import_node_path13.join)(__dirname, "..", "..", "package.json")
15448
15509
  ]) {
15449
15510
  try {
15450
- return JSON.parse((0, import_node_fs18.readFileSync)(candidate, "utf-8")).version ?? "0.0.0";
15511
+ return JSON.parse((0, import_node_fs19.readFileSync)(candidate, "utf-8")).version ?? "0.0.0";
15451
15512
  } catch {
15452
15513
  }
15453
15514
  }
@@ -15891,7 +15952,7 @@ function findingEvents(serverId, results, observedAt = /* @__PURE__ */ new Date(
15891
15952
  }
15892
15953
 
15893
15954
  // src/daemon/workers/cloud-spool.ts
15894
- var import_node_fs19 = require("fs");
15955
+ var import_node_fs20 = require("fs");
15895
15956
  var import_promises = require("fs/promises");
15896
15957
  var import_node_path14 = require("path");
15897
15958
  var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
@@ -15900,7 +15961,7 @@ var CloudSpool = class {
15900
15961
  this.path = path;
15901
15962
  this.limits = limits;
15902
15963
  try {
15903
- (0, import_node_fs19.mkdirSync)((0, import_node_path14.dirname)(path), { recursive: true });
15964
+ (0, import_node_fs20.mkdirSync)((0, import_node_path14.dirname)(path), { recursive: true });
15904
15965
  } catch {
15905
15966
  }
15906
15967
  this.load();
@@ -15969,7 +16030,7 @@ var CloudSpool = class {
15969
16030
  load() {
15970
16031
  let raw;
15971
16032
  try {
15972
- raw = (0, import_node_fs19.readFileSync)(this.path, "utf-8");
16033
+ raw = (0, import_node_fs20.readFileSync)(this.path, "utf-8");
15973
16034
  } catch {
15974
16035
  return;
15975
16036
  }
@@ -16426,7 +16487,7 @@ var RemediationConsumer = class {
16426
16487
 
16427
16488
  // src/daemon/workers/auto-update.ts
16428
16489
  var import_node_child_process5 = require("child_process");
16429
- var import_node_fs20 = require("fs");
16490
+ var import_node_fs21 = require("fs");
16430
16491
  var import_node_path15 = require("path");
16431
16492
  var PKG_NAME = "@profullstack/threatcrush";
16432
16493
  var REGISTRY = `https://registry.npmjs.org/${PKG_NAME}`;
@@ -16453,15 +16514,21 @@ function pickUpdate(doc, current, opts) {
16453
16514
  if (!latest) return { version: null, reason: "registry has no latest tag" };
16454
16515
  if (!isNewer(latest, current)) return { version: null, reason: `up to date (${current})` };
16455
16516
  const major = (v) => Number.parseInt(v.replace(/^v/, ""), 10);
16517
+ let best = null;
16518
+ for (const [v, when] of Object.entries(doc.time ?? {})) {
16519
+ if (!/^\d+\.\d+\.\d+$/.test(v)) continue;
16520
+ if (!isNewer(v, current) || isNewer(v, latest)) continue;
16521
+ if (!opts.allowMajor && major(v) !== major(current)) continue;
16522
+ const published = Date.parse(when);
16523
+ if (!Number.isFinite(published) || opts.now - published < opts.minAgeMs) continue;
16524
+ if (!best || isNewer(v, best)) best = v;
16525
+ }
16526
+ if (best) return { version: best };
16456
16527
  if (!opts.allowMajor && major(latest) !== major(current)) {
16457
16528
  return { version: null, reason: `${latest} is a new major; set [update] allow_major = true to take it` };
16458
16529
  }
16459
- const published = Date.parse(doc.time?.[latest] ?? "");
16460
- if (!Number.isFinite(published)) return { version: null, reason: `no publish time for ${latest}` };
16461
- if (opts.now - published < opts.minAgeMs) {
16462
- return { version: null, reason: `${latest} is younger than min_age; waiting` };
16463
- }
16464
- return { version: latest };
16530
+ if (!Number.isFinite(Date.parse(doc.time?.[latest] ?? ""))) return { version: null, reason: `no publish time for ${latest}` };
16531
+ return { version: null, reason: `${latest} is younger than min_age, and nothing older is newer than ${current}; waiting` };
16465
16532
  }
16466
16533
  function installPlan(opts) {
16467
16534
  const expected = `${import_node_path15.sep}lib${import_node_path15.sep}node_modules${import_node_path15.sep}@profullstack${import_node_path15.sep}threatcrush`;
@@ -16501,10 +16568,10 @@ function installPlan(opts) {
16501
16568
  }
16502
16569
  function ownerOf(path, passwd = "/etc/passwd") {
16503
16570
  try {
16504
- const st = (0, import_node_fs20.statSync)(path);
16571
+ const st = (0, import_node_fs21.statSync)(path);
16505
16572
  let home = st.uid === 0 ? "/root" : "";
16506
16573
  try {
16507
- for (const line of (0, import_node_fs20.readFileSync)(passwd, "utf8").split("\n")) {
16574
+ for (const line of (0, import_node_fs21.readFileSync)(passwd, "utf8").split("\n")) {
16508
16575
  const f = line.split(":");
16509
16576
  if (Number(f[2]) === st.uid && f[5]) home = f[5];
16510
16577
  }
@@ -16596,7 +16663,7 @@ var AutoUpdate = class {
16596
16663
  minAgeMs: this.opts.settings.minAgeMs,
16597
16664
  now: this.now()
16598
16665
  });
16599
- if (pick.version === null) return this.note(pick.reason, false);
16666
+ if (pick.version === null) return this.note(pick.reason, !pick.reason.startsWith("up to date"));
16600
16667
  const target = pick.version;
16601
16668
  const last = this.lastAttempt();
16602
16669
  if (last?.version === target && this.now() - last.at < RETRY_AFTER_MS) {
@@ -16609,7 +16676,7 @@ var AutoUpdate = class {
16609
16676
  uid: process.getuid?.() ?? -1,
16610
16677
  owner: ownerOf(this.opts.pkgRoot),
16611
16678
  underSystemd: this.opts.underSystemd ?? Boolean(process.env.INVOCATION_ID),
16612
- npmExists: import_node_fs20.existsSync
16679
+ npmExists: import_node_fs21.existsSync
16613
16680
  });
16614
16681
  if (plan.kind === "unsupported") return this.note(`${target} is available but cannot self-install: ${plan.reason}`);
16615
16682
  this.recordAttempt(target);
@@ -16644,7 +16711,7 @@ var AutoUpdate = class {
16644
16711
  }
16645
16712
  lastAttempt() {
16646
16713
  try {
16647
- const v = JSON.parse((0, import_node_fs20.readFileSync)(this.opts.statePath, "utf8"));
16714
+ const v = JSON.parse((0, import_node_fs21.readFileSync)(this.opts.statePath, "utf8"));
16648
16715
  return v.version && typeof v.at === "number" ? { version: v.version, at: v.at } : null;
16649
16716
  } catch {
16650
16717
  return null;
@@ -16652,7 +16719,7 @@ var AutoUpdate = class {
16652
16719
  }
16653
16720
  recordAttempt(version) {
16654
16721
  try {
16655
- (0, import_node_fs20.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
16722
+ (0, import_node_fs21.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
16656
16723
  } catch (err) {
16657
16724
  this.opts.log(`[update] could not record attempt: ${err.message}`);
16658
16725
  }
@@ -16661,6 +16728,8 @@ var AutoUpdate = class {
16661
16728
 
16662
16729
  // src/daemon/workers/threat-feeds.ts
16663
16730
  var import_node_child_process6 = require("child_process");
16731
+ var import_node_fs22 = require("fs");
16732
+ var import_node_path16 = require("path");
16664
16733
  var import_node_net7 = require("net");
16665
16734
  var EGRESS_TABLE = "threatcrush_egress";
16666
16735
  var DEFAULT_REFRESH_MS = 36e5;
@@ -16671,6 +16740,7 @@ function threatFeedSettings(section) {
16671
16740
  return {
16672
16741
  enabled: section?.enabled !== false,
16673
16742
  block: section?.block === true,
16743
+ blockDomains: section?.block_domains === true,
16674
16744
  // abuse.ch asks for no more than one fetch per 5 minutes; hourly is plenty.
16675
16745
  refreshMs: refresh ? Math.max(900, refresh) * 1e3 : DEFAULT_REFRESH_MS,
16676
16746
  minConfidence: typeof section?.min_confidence === "number" ? section.min_confidence : 75,
@@ -16750,6 +16820,8 @@ var ThreatFeeds = class {
16750
16820
  set = null;
16751
16821
  alerted = /* @__PURE__ */ new Map();
16752
16822
  blocking = false;
16823
+ /** Resolver blocklist content last written, by file name (see writeResolverFiles). */
16824
+ resolverWritten = /* @__PURE__ */ new Map();
16753
16825
  run;
16754
16826
  now;
16755
16827
  get wantsBlock() {
@@ -16811,10 +16883,55 @@ var ThreatFeeds = class {
16811
16883
  this.blocking = ok;
16812
16884
  mode = ok ? "blocking egress" : "detecting (nft load failed)";
16813
16885
  }
16814
- const detail = `${ips.length} IPs, ${domains} domains, ${mode}`;
16886
+ const detail = `${ips.length} IPs, ${domains} domains, ${mode}${this.writeResolverFiles(set)}`;
16815
16887
  this.opts.log(`[threat-feeds] ${from === "cache" ? "loaded cached" : "refreshed"} list: ${detail} (${set.skipped_shared} shared/protected entries skipped)`);
16816
16888
  this.opts.bus.announceModule("threat-feeds", "running", detail);
16817
16889
  }
16890
+ /** Whether listed domains are refused at the resolver: opted in and enforcing. */
16891
+ get wantsDomainBlock() {
16892
+ return this.opts.settings.blockDomains && this.opts.enforcing;
16893
+ }
16894
+ /**
16895
+ * Rewrite the resolver blocklists in the state dir and reload any resolver
16896
+ * whose hook is installed — only when the content changed, so an hourly
16897
+ * refresh with nothing new costs no reload. With domain blocking off the
16898
+ * files are emptied, so an installed hook blocks nothing and the config
16899
+ * stays the one switch. Returns a status suffix for the log line.
16900
+ */
16901
+ writeResolverFiles(set) {
16902
+ const domains = this.wantsDomainBlock ? Object.keys(set.domains).sort() : [];
16903
+ const dir = this.opts.resolverDir ?? (0, import_node_path16.dirname)(this.opts.cachePath);
16904
+ const hooks = this.opts.resolverHooks ?? RESOLVER_HOOKS;
16905
+ const write = (name, content) => {
16906
+ const path = (0, import_node_path16.join)(dir, name);
16907
+ if (this.resolverWritten.get(name) === content) return false;
16908
+ try {
16909
+ (0, import_node_fs22.writeFileSync)(`${path}.tmp`, content);
16910
+ (0, import_node_fs22.renameSync)(`${path}.tmp`, path);
16911
+ this.resolverWritten.set(name, content);
16912
+ return true;
16913
+ } catch (err) {
16914
+ this.opts.log(`[threat-feeds] could not write ${path}: ${err.message}`);
16915
+ return false;
16916
+ }
16917
+ };
16918
+ const hostsChanged = write(RESOLVER_FILES.hosts, hostsBlocklist(domains));
16919
+ const unboundChanged = write(RESOLVER_FILES.unbound, unboundBlocklist(domains));
16920
+ const via = [];
16921
+ if ((0, import_node_fs22.existsSync)(hooks.dnsmasq)) {
16922
+ via.push("dnsmasq");
16923
+ if (hostsChanged) this.run("systemctl", ["kill", "-s", "HUP", "dnsmasq.service"]);
16924
+ }
16925
+ if ((0, import_node_fs22.existsSync)(hooks.unbound)) {
16926
+ via.push("unbound");
16927
+ if (unboundChanged && this.run("unbound-control", ["reload"]) === null) {
16928
+ this.run("systemctl", ["reload", "unbound.service"]);
16929
+ }
16930
+ }
16931
+ if (!this.opts.settings.blockDomains) return "";
16932
+ if (!this.opts.enforcing) return "; domain blocking set but remediation is dry_run";
16933
+ return via.length ? `; ${domains.length} domains refused via ${via.join(" + ")}` : "; domain blocking set but no resolver hook (run `threatcrush feeds resolver install`)";
16934
+ }
16818
16935
  removeBlocking() {
16819
16936
  if (this.run("nft", ["list", "table", "inet", EGRESS_TABLE]) !== null) {
16820
16937
  this.run("nft", ["delete", "table", "inet", EGRESS_TABLE]);
@@ -16866,8 +16983,8 @@ var ThreatFeeds = class {
16866
16983
  };
16867
16984
 
16868
16985
  // src/daemon/workers/privilege-watch.ts
16869
- var import_node_fs21 = require("fs");
16870
- var import_node_path16 = require("path");
16986
+ var import_node_fs23 = require("fs");
16987
+ var import_node_path17 = require("path");
16871
16988
  var import_node_child_process7 = require("child_process");
16872
16989
 
16873
16990
  // src/core/privileges/index.ts
@@ -17058,31 +17175,31 @@ function countryName(code) {
17058
17175
  var fsIO = {
17059
17176
  readFile: (p) => {
17060
17177
  try {
17061
- return (0, import_node_fs21.readFileSync)(p, "utf-8");
17178
+ return (0, import_node_fs23.readFileSync)(p, "utf-8");
17062
17179
  } catch {
17063
17180
  return null;
17064
17181
  }
17065
17182
  },
17066
17183
  readDir: (p) => {
17067
17184
  try {
17068
- return (0, import_node_fs21.readdirSync)(p);
17185
+ return (0, import_node_fs23.readdirSync)(p);
17069
17186
  } catch {
17070
17187
  return null;
17071
17188
  }
17072
17189
  },
17073
- exists: (p) => (0, import_node_fs21.existsSync)(p)
17190
+ exists: (p) => (0, import_node_fs23.existsSync)(p)
17074
17191
  };
17075
17192
  function readJson(path) {
17076
17193
  try {
17077
- return JSON.parse((0, import_node_fs21.readFileSync)(path, "utf-8"));
17194
+ return JSON.parse((0, import_node_fs23.readFileSync)(path, "utf-8"));
17078
17195
  } catch {
17079
17196
  return null;
17080
17197
  }
17081
17198
  }
17082
17199
  function writeJson(path, value) {
17083
- (0, import_node_fs21.mkdirSync)((0, import_node_path16.dirname)(path), { recursive: true });
17084
- (0, import_node_fs21.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
17085
- (0, import_node_fs21.renameSync)(`${path}.tmp`, path);
17200
+ (0, import_node_fs23.mkdirSync)((0, import_node_path17.dirname)(path), { recursive: true });
17201
+ (0, import_node_fs23.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
17202
+ (0, import_node_fs23.renameSync)(`${path}.tmp`, path);
17086
17203
  }
17087
17204
  function defaultRun3(cmd, args) {
17088
17205
  const res = (0, import_node_child_process7.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 2e4, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
@@ -17238,7 +17355,7 @@ var PrivilegeWatch = class {
17238
17355
  * raised a "new country" alert on its first run; on dev2 it did, at once.
17239
17356
  */
17240
17357
  async backfillLogins() {
17241
- if ((0, import_node_fs21.existsSync)(this.opts.loginsPath)) return;
17358
+ if ((0, import_node_fs23.existsSync)(this.opts.loginsPath)) return;
17242
17359
  const out = this.run("journalctl", ["_COMM=sshd", "_COMM=sshd-session", "--since=-30d", "-o", "cat", "--no-pager"]);
17243
17360
  const byUser = parseAcceptedLogins(out ?? "");
17244
17361
  const ips = [...new Set([...byUser.values()].flatMap((s) => [...s]))];
@@ -17251,7 +17368,7 @@ var PrivilegeWatch = class {
17251
17368
  return;
17252
17369
  }
17253
17370
  }
17254
- if ((0, import_node_fs21.existsSync)(this.opts.loginsPath)) return;
17371
+ if ((0, import_node_fs23.existsSync)(this.opts.loginsPath)) return;
17255
17372
  const at = this.now().toISOString();
17256
17373
  const history = {};
17257
17374
  for (const [user, userIps] of byUser) {
@@ -17463,8 +17580,8 @@ var RuleEngine = class {
17463
17580
  };
17464
17581
 
17465
17582
  // src/daemon/rules/loader.ts
17466
- var import_node_fs22 = require("fs");
17467
- var import_node_path17 = require("path");
17583
+ var import_node_fs24 = require("fs");
17584
+ var import_node_path18 = require("path");
17468
17585
 
17469
17586
  // src/daemon/rules/default-rules.ts
17470
17587
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -17865,11 +17982,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
17865
17982
  function loadAllRules(customDir) {
17866
17983
  const rules = [...DEFAULT_RULES];
17867
17984
  const dir = customDir || RULES_DIR;
17868
- if ((0, import_node_fs22.existsSync)(dir)) {
17869
- const files = (0, import_node_fs22.readdirSync)(dir).filter((f) => f.endsWith(".json"));
17985
+ if ((0, import_node_fs24.existsSync)(dir)) {
17986
+ const files = (0, import_node_fs24.readdirSync)(dir).filter((f) => f.endsWith(".json"));
17870
17987
  for (const file of files) {
17871
17988
  try {
17872
- const raw = (0, import_node_fs22.readFileSync)((0, import_node_path17.join)(dir, file), "utf-8");
17989
+ const raw = (0, import_node_fs24.readFileSync)((0, import_node_path18.join)(dir, file), "utf-8");
17873
17990
  const parsed = JSON.parse(raw);
17874
17991
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
17875
17992
  for (const rule of customRules) {
@@ -17901,8 +18018,8 @@ function loadAllRules(customDir) {
17901
18018
 
17902
18019
  // src/daemon/firewall/adapters.ts
17903
18020
  var import_node_child_process8 = require("child_process");
17904
- var import_node_fs23 = require("fs");
17905
- var import_node_path18 = require("path");
18021
+ var import_node_fs25 = require("fs");
18022
+ var import_node_path19 = require("path");
17906
18023
  var import_node_net8 = require("net");
17907
18024
  function assertValidFirewallIp(ip) {
17908
18025
  if ((0, import_node_net8.isIP)(ip) !== 4) {
@@ -17915,9 +18032,9 @@ function assertBannableIp(ip) {
17915
18032
  }
17916
18033
  }
17917
18034
  function writeIfAbsent(path, contents) {
17918
- (0, import_node_fs23.mkdirSync)((0, import_node_path18.dirname)(path), { recursive: true });
18035
+ (0, import_node_fs25.mkdirSync)((0, import_node_path19.dirname)(path), { recursive: true });
17919
18036
  try {
17920
- (0, import_node_fs23.writeFileSync)(path, contents, { flag: "wx" });
18037
+ (0, import_node_fs25.writeFileSync)(path, contents, { flag: "wx" });
17921
18038
  } catch (err) {
17922
18039
  if (err.code !== "EEXIST") throw err;
17923
18040
  }
@@ -18176,7 +18293,8 @@ function detectFirewallAdapter(backend = "auto") {
18176
18293
  }
18177
18294
 
18178
18295
  // src/daemon/firewall/remediation.ts
18179
- var import_node_fs24 = require("fs");
18296
+ var import_node_fs26 = require("fs");
18297
+ var import_node_child_process9 = require("child_process");
18180
18298
  var import_node_net9 = require("net");
18181
18299
 
18182
18300
  // src/daemon/firewall/crawlers.ts
@@ -18233,8 +18351,46 @@ var DEFAULT_CONFIG2 = {
18233
18351
  strike_memory_seconds: 30 * 86400,
18234
18352
  allowlist: [],
18235
18353
  protect_current_ssh_client: true,
18354
+ protect_recent_operators: true,
18355
+ operator_memory_seconds: 30 * 86400,
18236
18356
  spare_verified_crawlers: true
18237
18357
  };
18358
+ var defaultDiscovery = {
18359
+ sshPeers: () => [currentSshClient(), ...establishedSshPeers()].filter((ip) => Boolean(ip)),
18360
+ moshClients: () => moshClients(),
18361
+ automationKeys: () => {
18362
+ const snapshot = takeSnapshot({
18363
+ readFile: (p) => {
18364
+ try {
18365
+ return (0, import_node_fs26.readFileSync)(p, "utf-8");
18366
+ } catch {
18367
+ return null;
18368
+ }
18369
+ },
18370
+ readDir: (p) => {
18371
+ try {
18372
+ return (0, import_node_fs26.readdirSync)(p);
18373
+ } catch {
18374
+ return null;
18375
+ }
18376
+ },
18377
+ exists: (p) => (0, import_node_fs26.existsSync)(p)
18378
+ });
18379
+ const out = /* @__PURE__ */ new Set();
18380
+ for (const keys of Object.values(snapshot.keys)) {
18381
+ for (const [fp, k] of Object.entries(keys)) if (isAutomationKeyComment(k.comment)) out.add(fp);
18382
+ }
18383
+ return out;
18384
+ },
18385
+ keyLoginJournal: (sinceSeconds) => new Promise((resolve3) => {
18386
+ (0, import_node_child_process9.execFile)(
18387
+ "journalctl",
18388
+ ["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
18389
+ { maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
18390
+ (_err, stdout) => resolve3(stdout ?? "")
18391
+ );
18392
+ })
18393
+ };
18238
18394
  var SEVERITY_RANK5 = {
18239
18395
  info: 0,
18240
18396
  low: 1,
@@ -18257,28 +18413,70 @@ function explainBlockFailure(err, backend) {
18257
18413
  return `threatcrushd is running ${who} and cannot manage ${backend}. A ban is written by the daemon, not by whoever asked for it. Fix it with one command, which asks for root itself: threatcrush install-service`;
18258
18414
  }
18259
18415
  var RemediationManager = class {
18260
- constructor(adapter, bus2, config, verifyCrawler = crawlerVerifier()) {
18416
+ constructor(adapter, bus2, config, verifyCrawler = crawlerVerifier(), discovery = defaultDiscovery) {
18261
18417
  this.adapter = adapter;
18262
18418
  this.bus = bus2;
18263
18419
  this.verifyCrawler = verifyCrawler;
18420
+ this.discovery = discovery;
18264
18421
  this.config = { ...DEFAULT_CONFIG2, ...config };
18265
18422
  this.config.allowlist = [...this.config.allowlist];
18266
18423
  this.protectedList = [...DEFAULT_PROTECTED, ...this.config.allowlist];
18267
18424
  for (const gateway of defaultGateways()) this.protectedList.push(gateway);
18268
- this.refreshSshProtection();
18269
18425
  if (this.adapter.enforces === false) this.config.dry_run = true;
18270
18426
  this.loadState();
18427
+ this.refreshSshProtection();
18271
18428
  void this.reconcile();
18272
18429
  this.startExpiryWorker();
18430
+ if (this.config.protect_recent_operators) void this.seedOperatorsFromJournal();
18273
18431
  }
18274
18432
  adapter;
18275
18433
  bus;
18276
18434
  verifyCrawler;
18435
+ discovery;
18277
18436
  config;
18278
18437
  blocklist = [];
18279
18438
  strikes = {};
18280
18439
  protectedList = [];
18440
+ /** Operator address → last time seen (ms), persisted. */
18441
+ operators = {};
18281
18442
  expiryTimer = null;
18443
+ operatorTimer = null;
18444
+ /** Remembered operator addresses and when each was last seen. */
18445
+ getOperators() {
18446
+ return { ...this.operators };
18447
+ }
18448
+ /**
18449
+ * An address an operator really came from: never ban it, remember it, and
18450
+ * lift a ban that is already on it — the operator is the one who needs in.
18451
+ */
18452
+ noteOperator(ip, at, remember = true) {
18453
+ if (Date.now() - at > this.config.operator_memory_seconds * 1e3) return;
18454
+ if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
18455
+ if (!remember || !this.config.protect_recent_operators || isProtected(ip, DEFAULT_PROTECTED)) return;
18456
+ const known = this.operators[ip] ?? 0;
18457
+ if (at > known) {
18458
+ this.operators[ip] = at;
18459
+ if (!known) this.logLine(`[firewall] operator address remembered: ${ip}`);
18460
+ this.saveState();
18461
+ }
18462
+ if (this.blocklist.some((b) => b.ip === ip)) {
18463
+ void this.unban(ip, { forget: true, reason: "operator address (key login or live session)" });
18464
+ }
18465
+ }
18466
+ /**
18467
+ * Key-based SSH logins in the memory window, by keys that belong to people:
18468
+ * a key whose comment marks automation (a CI deploy key) logs in from
18469
+ * shared cloud runners, and remembering those would allowlist hundreds of
18470
+ * strangers' addresses — dev2 saw 308 distinct key-login IPs in 30 days.
18471
+ */
18472
+ async seedOperatorsFromJournal() {
18473
+ try {
18474
+ const automation = this.discovery.automationKeys();
18475
+ const journal = await this.discovery.keyLoginJournal(this.config.operator_memory_seconds);
18476
+ for (const [ip, at] of parseKeyLogins(journal, (fp) => automation.has(fp))) this.noteOperator(ip, at);
18477
+ } catch {
18478
+ }
18479
+ }
18282
18480
  /** Every address that can never be blocked, built-ins included. */
18283
18481
  getProtected() {
18284
18482
  return [...this.protectedList];
@@ -18293,10 +18491,9 @@ var RemediationManager = class {
18293
18491
  */
18294
18492
  refreshSshProtection() {
18295
18493
  if (!this.config.protect_current_ssh_client) return;
18296
- const candidates = [currentSshClient(), ...establishedSshPeers()];
18297
- for (const ip of candidates) {
18298
- if (ip && !this.protectedList.includes(ip)) this.protectedList.push(ip);
18299
- }
18494
+ const now = Date.now();
18495
+ for (const ip of this.discovery.sshPeers()) this.noteOperator(ip, now, false);
18496
+ for (const ip of this.discovery.moshClients()) this.noteOperator(ip, now);
18300
18497
  }
18301
18498
  isAllowlisted(ip) {
18302
18499
  return isProtected(ip, this.protectedList);
@@ -18495,7 +18692,9 @@ var RemediationManager = class {
18495
18692
  }
18496
18693
  stop() {
18497
18694
  if (this.expiryTimer) clearInterval(this.expiryTimer);
18695
+ if (this.operatorTimer) clearInterval(this.operatorTimer);
18498
18696
  this.expiryTimer = null;
18697
+ this.operatorTimer = null;
18499
18698
  }
18500
18699
  /**
18501
18700
  * R5: bans survive a restart, their TTLs do not. Anything that expired while
@@ -18544,6 +18743,10 @@ var RemediationManager = class {
18544
18743
  startExpiryWorker() {
18545
18744
  this.expiryTimer = setInterval(() => void this.processExpiries(), 1e4);
18546
18745
  this.expiryTimer.unref?.();
18746
+ if (this.config.protect_recent_operators) {
18747
+ this.operatorTimer = setInterval(() => void this.seedOperatorsFromJournal(), 36e5);
18748
+ this.operatorTimer.unref?.();
18749
+ }
18547
18750
  }
18548
18751
  async processExpiries() {
18549
18752
  const now = Date.now();
@@ -18556,6 +18759,12 @@ var RemediationManager = class {
18556
18759
  this.strikes = pruned;
18557
18760
  this.saveState();
18558
18761
  }
18762
+ const cutoff = now - this.config.operator_memory_seconds * 1e3;
18763
+ const stale = Object.keys(this.operators).filter((ip) => this.operators[ip] < cutoff);
18764
+ if (stale.length > 0) {
18765
+ for (const ip of stale) delete this.operators[ip];
18766
+ this.saveState();
18767
+ }
18559
18768
  }
18560
18769
  loadState() {
18561
18770
  try {
@@ -18575,6 +18784,18 @@ var RemediationManager = class {
18575
18784
  if (saved && typeof saved === "object") this.strikes = saved;
18576
18785
  } catch {
18577
18786
  }
18787
+ try {
18788
+ const saved = getModuleState("firewall-rules", "operators");
18789
+ if (saved && typeof saved === "object" && this.config.protect_recent_operators) {
18790
+ const cutoff = Date.now() - this.config.operator_memory_seconds * 1e3;
18791
+ for (const [ip, at] of Object.entries(saved)) {
18792
+ if (typeof at !== "number" || at < cutoff || !(0, import_node_net9.isIP)(ip)) continue;
18793
+ this.operators[ip] = at;
18794
+ if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
18795
+ }
18796
+ }
18797
+ } catch {
18798
+ }
18578
18799
  }
18579
18800
  saveState() {
18580
18801
  try {
@@ -18585,10 +18806,14 @@ var RemediationManager = class {
18585
18806
  setModuleState("firewall-rules", "strikes", this.strikes);
18586
18807
  } catch {
18587
18808
  }
18809
+ try {
18810
+ setModuleState("firewall-rules", "operators", this.operators);
18811
+ } catch {
18812
+ }
18588
18813
  }
18589
18814
  logLine(line) {
18590
18815
  try {
18591
- (0, import_node_fs24.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
18816
+ (0, import_node_fs26.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
18592
18817
  `);
18593
18818
  } catch {
18594
18819
  }
@@ -18615,6 +18840,11 @@ function remediationSettings(section) {
18615
18840
  if (typeof section.protect_current_ssh_client === "boolean") {
18616
18841
  settings.protect_current_ssh_client = section.protect_current_ssh_client;
18617
18842
  }
18843
+ if (typeof section.protect_recent_operators === "boolean") {
18844
+ settings.protect_recent_operators = section.protect_recent_operators;
18845
+ }
18846
+ const operatorMemory = parseDuration(section.operator_memory);
18847
+ if (operatorMemory) settings.operator_memory_seconds = operatorMemory;
18618
18848
  if (typeof section.spare_verified_crawlers === "boolean") {
18619
18849
  settings.spare_verified_crawlers = section.spare_verified_crawlers;
18620
18850
  }
@@ -18622,13 +18852,13 @@ function remediationSettings(section) {
18622
18852
  }
18623
18853
 
18624
18854
  // src/daemon/watchdog-service.ts
18625
- var import_node_fs26 = require("fs");
18626
- var import_node_path20 = require("path");
18855
+ var import_node_fs28 = require("fs");
18856
+ var import_node_path21 = require("path");
18627
18857
 
18628
18858
  // src/core/watchdog.ts
18629
- var import_node_fs25 = require("fs");
18859
+ var import_node_fs27 = require("fs");
18630
18860
  var import_node_crypto6 = require("crypto");
18631
- var import_node_path19 = require("path");
18861
+ var import_node_path20 = require("path");
18632
18862
  var WATCHDOG_DIRNAME = "watchdog";
18633
18863
  var LOG_FILE = "attacks.jsonl";
18634
18864
  var ROTATED_FILE = "attacks.1.jsonl";
@@ -18717,12 +18947,12 @@ var WatchdogLog = class {
18717
18947
  stats = { logged: 0, answered: 0, errored: 0 };
18718
18948
  constructor(dir, options = {}) {
18719
18949
  this.dir = dir;
18720
- this.file = (0, import_node_path19.join)(dir, LOG_FILE);
18950
+ this.file = (0, import_node_path20.join)(dir, LOG_FILE);
18721
18951
  this.shareGid = options.shareGid;
18722
- (0, import_node_fs25.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
18952
+ (0, import_node_fs27.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
18723
18953
  if (this.shareGid !== void 0) {
18724
- (0, import_node_fs25.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
18725
- (0, import_node_fs25.chmodSync)(dir, 1528);
18954
+ (0, import_node_fs27.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
18955
+ (0, import_node_fs27.chmodSync)(dir, 1528);
18726
18956
  }
18727
18957
  for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
18728
18958
  }
@@ -18751,16 +18981,16 @@ var WatchdogLog = class {
18751
18981
  const chunk = this.buffer.join("\n") + "\n";
18752
18982
  this.buffer = [];
18753
18983
  try {
18754
- if ((0, import_node_fs25.statSync)(this.file).size > ROTATE_BYTES) {
18755
- (0, import_node_fs25.renameSync)(this.file, (0, import_node_path19.join)(this.dir, ROTATED_FILE));
18984
+ if ((0, import_node_fs27.statSync)(this.file).size > ROTATE_BYTES) {
18985
+ (0, import_node_fs27.renameSync)(this.file, (0, import_node_path20.join)(this.dir, ROTATED_FILE));
18756
18986
  }
18757
18987
  } catch {
18758
18988
  }
18759
- (0, import_node_fs25.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
18989
+ (0, import_node_fs27.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
18760
18990
  if (this.shareGid !== void 0) {
18761
18991
  try {
18762
- (0, import_node_fs25.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
18763
- (0, import_node_fs25.chmodSync)(this.file, 432);
18992
+ (0, import_node_fs27.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
18993
+ (0, import_node_fs27.chmodSync)(this.file, 432);
18764
18994
  } catch {
18765
18995
  }
18766
18996
  }
@@ -18781,21 +19011,21 @@ function parseLines(text) {
18781
19011
  function readTail(file, bytes) {
18782
19012
  let fd;
18783
19013
  try {
18784
- fd = (0, import_node_fs25.openSync)(file, "r");
19014
+ fd = (0, import_node_fs27.openSync)(file, "r");
18785
19015
  } catch (err) {
18786
19016
  if (err.code === "ENOENT") return [];
18787
19017
  throw err;
18788
19018
  }
18789
19019
  try {
18790
- const size = (0, import_node_fs25.fstatSync)(fd).size;
19020
+ const size = (0, import_node_fs27.fstatSync)(fd).size;
18791
19021
  const start = Math.max(0, size - bytes);
18792
19022
  const buf = Buffer.alloc(size - start);
18793
- (0, import_node_fs25.readSync)(fd, buf, 0, buf.length, start);
19023
+ (0, import_node_fs27.readSync)(fd, buf, 0, buf.length, start);
18794
19024
  let text = buf.toString("utf8");
18795
19025
  if (start > 0) text = text.slice(text.indexOf("\n") + 1);
18796
19026
  return parseLines(text);
18797
19027
  } finally {
18798
- (0, import_node_fs25.closeSync)(fd);
19028
+ (0, import_node_fs27.closeSync)(fd);
18799
19029
  }
18800
19030
  }
18801
19031
 
@@ -18804,13 +19034,13 @@ function defaultShareGid() {
18804
19034
  const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
18805
19035
  if (!isRoot2) return void 0;
18806
19036
  try {
18807
- return (0, import_node_fs26.statSync)("/var/log/auth.log").gid;
19037
+ return (0, import_node_fs28.statSync)("/var/log/auth.log").gid;
18808
19038
  } catch {
18809
19039
  return void 0;
18810
19040
  }
18811
19041
  }
18812
19042
  function startWatchdog(opts) {
18813
- const dir = opts.config?.dir ?? (0, import_node_path20.join)(opts.stateDir, WATCHDOG_DIRNAME);
19043
+ const dir = opts.config?.dir ?? (0, import_node_path21.join)(opts.stateDir, WATCHDOG_DIRNAME);
18814
19044
  const base = { dir, logged: 0, answered: 0, errored: 0 };
18815
19045
  if (opts.config?.enabled === false) {
18816
19046
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -18901,7 +19131,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
18901
19131
  }
18902
19132
 
18903
19133
  // src/core/node-runtime.ts
18904
- var import_node_child_process9 = require("child_process");
19134
+ var import_node_child_process10 = require("child_process");
18905
19135
  var MIN_DAEMON_NODE_MAJOR = 22;
18906
19136
  function nodeMajor(version) {
18907
19137
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -18917,16 +19147,16 @@ function daemonNodeProblem(version) {
18917
19147
  // src/daemon/index.ts
18918
19148
  function readVersion2() {
18919
19149
  try {
18920
- const pkg = JSON.parse((0, import_node_fs27.readFileSync)((0, import_node_path21.join)(__dirname, "..", "package.json"), "utf-8"));
19150
+ const pkg = JSON.parse((0, import_node_fs29.readFileSync)((0, import_node_path22.join)(__dirname, "..", "package.json"), "utf-8"));
18921
19151
  return pkg.version || "0.0.0";
18922
19152
  } catch {
18923
19153
  return "0.0.0";
18924
19154
  }
18925
19155
  }
18926
19156
  async function runHardeningChecks() {
18927
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process10.execFile)(
19157
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process11.execFile)(
18928
19158
  process.execPath,
18929
- [(0, import_node_path21.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
19159
+ [(0, import_node_path22.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
18930
19160
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
18931
19161
  );
18932
19162
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -18938,9 +19168,9 @@ async function runHardeningChecks() {
18938
19168
  return patches ? [...findings, patches] : findings;
18939
19169
  }
18940
19170
  async function runPatchCheck() {
18941
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process10.execFile)(
19171
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process11.execFile)(
18942
19172
  process.execPath,
18943
- [(0, import_node_path21.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
19173
+ [(0, import_node_path22.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
18944
19174
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
18945
19175
  );
18946
19176
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -18948,7 +19178,7 @@ async function runPatchCheck() {
18948
19178
  }
18949
19179
  function logLine(line) {
18950
19180
  try {
18951
- (0, import_node_fs27.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
19181
+ (0, import_node_fs29.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
18952
19182
  `);
18953
19183
  } catch {
18954
19184
  }
@@ -18973,9 +19203,9 @@ async function runDaemon() {
18973
19203
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
18974
19204
  const restartDaemon = () => {
18975
19205
  if (PATHS.mode === "system") {
18976
- (0, import_node_child_process10.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
19206
+ (0, import_node_child_process11.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
18977
19207
  } else {
18978
- (0, import_node_child_process10.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
19208
+ (0, import_node_child_process11.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
18979
19209
  setTimeout(() => process.exit(0), 500).unref();
18980
19210
  }
18981
19211
  };
@@ -18990,7 +19220,7 @@ async function runDaemon() {
18990
19220
  } catch (err) {
18991
19221
  logLine(`[daemon] state db unavailable: ${err.message}`);
18992
19222
  }
18993
- const config = loadConfig((0, import_node_fs27.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
19223
+ const config = loadConfig((0, import_node_fs29.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
18994
19224
  configureAttackDetection(config.detection);
18995
19225
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
18996
19226
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -19054,7 +19284,7 @@ async function runDaemon() {
19054
19284
  const threatFeeds = new ThreatFeeds({
19055
19285
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
19056
19286
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
19057
- cachePath: (0, import_node_path21.join)(PATHS.stateDir, "threat-feeds.json"),
19287
+ cachePath: (0, import_node_path22.join)(PATHS.stateDir, "threat-feeds.json"),
19058
19288
  bus,
19059
19289
  log: logLine
19060
19290
  });
@@ -19062,9 +19292,9 @@ async function runDaemon() {
19062
19292
  const privilegeWatch = new PrivilegeWatch({
19063
19293
  settings: privilegeSettings(config.privileged),
19064
19294
  bus,
19065
- snapshotPath: (0, import_node_path21.join)(PATHS.stateDir, "privileges.json"),
19066
- loginsPath: (0, import_node_path21.join)(PATHS.stateDir, "login-countries.json"),
19067
- cursorPath: (0, import_node_path21.join)(PATHS.stateDir, "sudo-cursor.json"),
19295
+ snapshotPath: (0, import_node_path22.join)(PATHS.stateDir, "privileges.json"),
19296
+ loginsPath: (0, import_node_path22.join)(PATHS.stateDir, "login-countries.json"),
19297
+ cursorPath: (0, import_node_path22.join)(PATHS.stateDir, "sudo-cursor.json"),
19068
19298
  log: logLine
19069
19299
  });
19070
19300
  privilegeWatch.start();
@@ -19087,7 +19317,7 @@ async function runDaemon() {
19087
19317
  version,
19088
19318
  hostname: (0, import_node_os5.hostname)(),
19089
19319
  minSeverity,
19090
- spoolPath: (0, import_node_path21.join)(PATHS.stateDir, "cloud-spool.jsonl"),
19320
+ spoolPath: (0, import_node_path22.join)(PATHS.stateDir, "cloud-spool.jsonl"),
19091
19321
  log: logLine,
19092
19322
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
19093
19323
  runHardening: runHardeningChecks
@@ -19104,8 +19334,8 @@ async function runDaemon() {
19104
19334
  const autoUpdate = new AutoUpdate({
19105
19335
  version,
19106
19336
  settings: updateSettings(config.update),
19107
- pkgRoot: (0, import_node_path21.join)(__dirname, ".."),
19108
- statePath: (0, import_node_path21.join)(PATHS.stateDir, "auto-update.json"),
19337
+ pkgRoot: (0, import_node_path22.join)(__dirname, ".."),
19338
+ statePath: (0, import_node_path22.join)(PATHS.stateDir, "auto-update.json"),
19109
19339
  bus,
19110
19340
  log: logLine,
19111
19341
  restartDaemon