@profullstack/threatcrush 0.13.31 → 0.13.32

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/README.md CHANGED
@@ -198,6 +198,20 @@ enabled = true # false: the daemon neither reports to nor takes actio
198
198
  min_severity = "medium" # info | low | medium | high | critical
199
199
  ```
200
200
 
201
+ ## Automatic updates
202
+
203
+ The daemon keeps itself on the latest release. About every 6 hours (plus up to an hour of jitter, so a fleet does not restart in step) it asks the npm registry for `latest`. When a newer version has been published for at least 2 hours, and is on the same major version, it installs it and restarts onto it. The update shows in the live feed as an info event (`auto-update`).
204
+
205
+ Under systemd the unit's sandbox keeps the daemon from writing its own install, so it hands `npm i -g` to a transient unit (`systemd-run`) run as whoever owns the install, then restarts the service. A user-mode daemon runs npm itself. Only the npm global layout the installer produces is updated in place. A daemon running from a pnpm store or a source checkout logs that `threatcrush update` is needed instead. A version that was tried and did not take is not retried for a day.
206
+
207
+ ```toml
208
+ [update]
209
+ auto = true # false (or THREATCRUSH_AUTO_UPDATE=0): upgrade by hand with `threatcrush update`
210
+ interval = "6h" # how often to check (at least 15m)
211
+ min_age = "2h" # how long a release must be public before it is taken
212
+ allow_major = false # true: also move to a new major version
213
+ ```
214
+
201
215
  ## Pricing
202
216
 
203
217
  The CLI is MIT-licensed (see [License](#license)). For pricing, [contact us for a quote](https://threatcrush.com/hire).
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_fs24 = require("fs");
2026
- var import_node_child_process7 = require("child_process");
2025
+ var import_node_fs25 = require("fs");
2026
+ var import_node_child_process8 = require("child_process");
2027
2027
  var import_node_os5 = require("os");
2028
- var import_node_path18 = require("path");
2028
+ var import_node_path19 = require("path");
2029
2029
  var import_node_util = require("util");
2030
2030
 
2031
2031
  // src/daemon/paths.ts
@@ -10495,6 +10495,7 @@ function loadConfig(configPath) {
10495
10495
  detection: parsed.detection,
10496
10496
  cloud: parsed.cloud,
10497
10497
  watchdog: parsed.watchdog,
10498
+ update: parsed.update,
10498
10499
  storage: parsed.storage,
10499
10500
  license: parsed.license
10500
10501
  };
@@ -16185,6 +16186,241 @@ var RemediationConsumer = class {
16185
16186
  }
16186
16187
  };
16187
16188
 
16189
+ // src/daemon/workers/auto-update.ts
16190
+ var import_node_child_process5 = require("child_process");
16191
+ var import_node_fs19 = require("fs");
16192
+ var import_node_path14 = require("path");
16193
+ var PKG_NAME = "@profullstack/threatcrush";
16194
+ var REGISTRY = `https://registry.npmjs.org/${PKG_NAME}`;
16195
+ var DEFAULT_INTERVAL_MS = 6 * 36e5;
16196
+ var DEFAULT_MIN_AGE_MS = 2 * 36e5;
16197
+ var RETRY_AFTER_MS = 24 * 36e5;
16198
+ function isNewer(a, b) {
16199
+ const parse = (v) => {
16200
+ const [core, pre] = v.replace(/^v/, "").split("-", 2);
16201
+ return { nums: core.split(".").map((n) => Number.parseInt(n, 10) || 0), pre: pre ?? null };
16202
+ };
16203
+ const x = parse(a);
16204
+ const y = parse(b);
16205
+ for (let i = 0; i < 3; i++) {
16206
+ if ((x.nums[i] ?? 0) !== (y.nums[i] ?? 0)) return (x.nums[i] ?? 0) > (y.nums[i] ?? 0);
16207
+ }
16208
+ if (x.pre === y.pre) return false;
16209
+ if (x.pre === null) return true;
16210
+ if (y.pre === null) return false;
16211
+ return x.pre > y.pre;
16212
+ }
16213
+ function pickUpdate(doc, current, opts) {
16214
+ const latest = doc["dist-tags"]?.latest;
16215
+ if (!latest) return { version: null, reason: "registry has no latest tag" };
16216
+ if (!isNewer(latest, current)) return { version: null, reason: `up to date (${current})` };
16217
+ const major = (v) => Number.parseInt(v.replace(/^v/, ""), 10);
16218
+ if (!opts.allowMajor && major(latest) !== major(current)) {
16219
+ return { version: null, reason: `${latest} is a new major; set [update] allow_major = true to take it` };
16220
+ }
16221
+ const published = Date.parse(doc.time?.[latest] ?? "");
16222
+ if (!Number.isFinite(published)) return { version: null, reason: `no publish time for ${latest}` };
16223
+ if (opts.now - published < opts.minAgeMs) {
16224
+ return { version: null, reason: `${latest} is younger than min_age; waiting` };
16225
+ }
16226
+ return { version: latest };
16227
+ }
16228
+ function installPlan(opts) {
16229
+ const expected = `${import_node_path14.sep}lib${import_node_path14.sep}node_modules${import_node_path14.sep}@profullstack${import_node_path14.sep}threatcrush`;
16230
+ if (!opts.pkgRoot.endsWith(expected)) {
16231
+ return { kind: "unsupported", reason: `not an npm global install (${opts.pkgRoot}); run \`threatcrush update\`` };
16232
+ }
16233
+ const nodeBin = (0, import_node_path14.dirname)(opts.execPath);
16234
+ const npm = (0, import_node_path14.join)(nodeBin, "npm");
16235
+ if (!opts.npmExists(npm)) return { kind: "unsupported", reason: `no npm beside ${opts.execPath}` };
16236
+ if (!opts.owner) return { kind: "unsupported", reason: `cannot tell who owns ${opts.pkgRoot}` };
16237
+ const npmArgs = [npm, "i", "-g", `${PKG_NAME}@${opts.version}`, "--no-fund", "--no-audit"];
16238
+ const path = `${nodeBin}:/usr/local/bin:/usr/bin:/bin`;
16239
+ if (opts.underSystemd && opts.uid === 0) {
16240
+ return {
16241
+ kind: "run",
16242
+ argv: [
16243
+ "systemd-run",
16244
+ "--wait",
16245
+ "--collect",
16246
+ "--quiet",
16247
+ `--unit=threatcrush-autoupdate-${opts.version.replace(/[^0-9A-Za-z]/g, "-")}`,
16248
+ `--uid=${opts.owner.uid}`,
16249
+ `--gid=${opts.owner.gid}`,
16250
+ `--setenv=HOME=${opts.owner.home}`,
16251
+ `--setenv=PATH=${path}`,
16252
+ ...npmArgs
16253
+ ]
16254
+ };
16255
+ }
16256
+ if (opts.uid === opts.owner.uid) {
16257
+ return { kind: "run", argv: npmArgs, env: { PATH: path } };
16258
+ }
16259
+ return {
16260
+ kind: "unsupported",
16261
+ reason: `install is owned by uid ${opts.owner.uid}, daemon runs as ${opts.uid}; run \`threatcrush update\` as that user`
16262
+ };
16263
+ }
16264
+ function ownerOf(path, passwd = "/etc/passwd") {
16265
+ try {
16266
+ const st = (0, import_node_fs19.statSync)(path);
16267
+ let home = st.uid === 0 ? "/root" : "";
16268
+ try {
16269
+ for (const line of (0, import_node_fs19.readFileSync)(passwd, "utf8").split("\n")) {
16270
+ const f = line.split(":");
16271
+ if (Number(f[2]) === st.uid && f[5]) home = f[5];
16272
+ }
16273
+ } catch {
16274
+ }
16275
+ return home ? { uid: st.uid, gid: st.gid, home } : null;
16276
+ } catch {
16277
+ return null;
16278
+ }
16279
+ }
16280
+ function updateSettings(section, env2 = process.env) {
16281
+ const interval = parseDuration(section?.interval);
16282
+ const minAge = parseDuration(section?.min_age);
16283
+ return {
16284
+ enabled: section?.auto !== false && env2.THREATCRUSH_AUTO_UPDATE !== "0",
16285
+ intervalMs: interval ? Math.max(15 * 60, interval) * 1e3 : DEFAULT_INTERVAL_MS,
16286
+ minAgeMs: minAge !== null ? minAge * 1e3 : DEFAULT_MIN_AGE_MS,
16287
+ allowMajor: section?.allow_major === true
16288
+ };
16289
+ }
16290
+ function defaultRun(argv, env2) {
16291
+ return new Promise((resolve3) => {
16292
+ const child = (0, import_node_child_process5.spawn)(argv[0], argv.slice(1), {
16293
+ env: { ...process.env, ...env2 },
16294
+ stdio: ["ignore", "pipe", "pipe"]
16295
+ });
16296
+ let output = "";
16297
+ const keep = (b) => {
16298
+ output = (output + b.toString()).slice(-4e3);
16299
+ };
16300
+ child.stdout?.on("data", keep);
16301
+ child.stderr?.on("data", keep);
16302
+ child.on("error", (err) => resolve3({ code: -1, output: err.message }));
16303
+ child.on("close", (code) => resolve3({ code: code ?? -1, output }));
16304
+ });
16305
+ }
16306
+ var AutoUpdate = class {
16307
+ constructor(opts) {
16308
+ this.opts = opts;
16309
+ this.fetchImpl = opts.fetchImpl ?? fetch;
16310
+ this.run = opts.run ?? defaultRun;
16311
+ this.now = opts.now ?? Date.now;
16312
+ this.random = opts.random ?? Math.random;
16313
+ }
16314
+ opts;
16315
+ timer = null;
16316
+ busy = false;
16317
+ fetchImpl;
16318
+ run;
16319
+ now;
16320
+ random;
16321
+ start() {
16322
+ if (!this.opts.settings.enabled) {
16323
+ this.opts.log("[update] auto-update off ([update] auto = false or THREATCRUSH_AUTO_UPDATE=0)");
16324
+ return;
16325
+ }
16326
+ this.schedule(10 * 6e4 + this.random() * 30 * 6e4);
16327
+ }
16328
+ stop() {
16329
+ if (this.timer) clearTimeout(this.timer);
16330
+ this.timer = null;
16331
+ }
16332
+ schedule(ms) {
16333
+ this.timer = setTimeout(() => {
16334
+ void this.check().finally(() => {
16335
+ if (this.timer !== null) this.schedule(this.opts.settings.intervalMs + this.random() * 36e5);
16336
+ });
16337
+ }, ms);
16338
+ this.timer.unref?.();
16339
+ }
16340
+ /** One check; returns what it did, for logs and tests. */
16341
+ async check() {
16342
+ if (this.busy) return "busy";
16343
+ this.busy = true;
16344
+ try {
16345
+ let doc;
16346
+ try {
16347
+ const res = await this.fetchImpl(REGISTRY, {
16348
+ headers: { accept: "application/json" },
16349
+ signal: AbortSignal.timeout(2e4)
16350
+ });
16351
+ if (!res.ok) return this.note(`registry answered ${res.status}`);
16352
+ doc = await res.json();
16353
+ } catch (err) {
16354
+ return this.note(`registry unreachable: ${err.message}`);
16355
+ }
16356
+ const pick = pickUpdate(doc, this.opts.version, {
16357
+ allowMajor: this.opts.settings.allowMajor,
16358
+ minAgeMs: this.opts.settings.minAgeMs,
16359
+ now: this.now()
16360
+ });
16361
+ if (pick.version === null) return this.note(pick.reason, false);
16362
+ const target = pick.version;
16363
+ const last = this.lastAttempt();
16364
+ if (last?.version === target && this.now() - last.at < RETRY_AFTER_MS) {
16365
+ return this.note(`${target} was tried at ${new Date(last.at).toISOString()} and did not take; retrying after a day`);
16366
+ }
16367
+ const plan = installPlan({
16368
+ version: target,
16369
+ pkgRoot: this.opts.pkgRoot,
16370
+ execPath: process.execPath,
16371
+ uid: process.getuid?.() ?? -1,
16372
+ owner: ownerOf(this.opts.pkgRoot),
16373
+ underSystemd: this.opts.underSystemd ?? Boolean(process.env.INVOCATION_ID),
16374
+ npmExists: import_node_fs19.existsSync
16375
+ });
16376
+ if (plan.kind === "unsupported") return this.note(`${target} is available but cannot self-install: ${plan.reason}`);
16377
+ this.recordAttempt(target);
16378
+ this.event(`updating ThreatCrush ${this.opts.version} \u2192 ${target}`, { from: this.opts.version, to: target });
16379
+ this.opts.log(`[update] installing ${target}: ${plan.argv.join(" ")}`);
16380
+ const { code, output } = await this.run(plan.argv, plan.env);
16381
+ if (code !== 0) {
16382
+ const tail = output.trim().split("\n").slice(-3).join(" | ");
16383
+ this.event(`auto-update to ${target} failed (exit ${code})`, { to: target, code, output: tail });
16384
+ return this.note(`install of ${target} failed (exit ${code}): ${tail}`);
16385
+ }
16386
+ this.opts.log(`[update] ${target} installed; restarting onto it`);
16387
+ this.opts.restartDaemon();
16388
+ return `updated to ${target}`;
16389
+ } finally {
16390
+ this.busy = false;
16391
+ }
16392
+ }
16393
+ note(line, log = true) {
16394
+ if (log) this.opts.log(`[update] ${line}`);
16395
+ return line;
16396
+ }
16397
+ event(message, details) {
16398
+ this.opts.bus.publish({
16399
+ timestamp: new Date(this.now()),
16400
+ module: "auto-update",
16401
+ category: "system",
16402
+ severity: "info",
16403
+ message,
16404
+ details
16405
+ });
16406
+ }
16407
+ lastAttempt() {
16408
+ try {
16409
+ const v = JSON.parse((0, import_node_fs19.readFileSync)(this.opts.statePath, "utf8"));
16410
+ return v.version && typeof v.at === "number" ? { version: v.version, at: v.at } : null;
16411
+ } catch {
16412
+ return null;
16413
+ }
16414
+ }
16415
+ recordAttempt(version) {
16416
+ try {
16417
+ (0, import_node_fs19.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
16418
+ } catch (err) {
16419
+ this.opts.log(`[update] could not record attempt: ${err.message}`);
16420
+ }
16421
+ }
16422
+ };
16423
+
16188
16424
  // src/daemon/rules/engine.ts
16189
16425
  var MAX_WINDOW_ENTRIES = 1e3;
16190
16426
  function live(window) {
@@ -16346,8 +16582,8 @@ var RuleEngine = class {
16346
16582
  };
16347
16583
 
16348
16584
  // src/daemon/rules/loader.ts
16349
- var import_node_fs19 = require("fs");
16350
- var import_node_path14 = require("path");
16585
+ var import_node_fs20 = require("fs");
16586
+ var import_node_path15 = require("path");
16351
16587
 
16352
16588
  // src/daemon/rules/default-rules.ts
16353
16589
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -16748,11 +16984,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
16748
16984
  function loadAllRules(customDir) {
16749
16985
  const rules = [...DEFAULT_RULES];
16750
16986
  const dir = customDir || RULES_DIR;
16751
- if ((0, import_node_fs19.existsSync)(dir)) {
16752
- const files = (0, import_node_fs19.readdirSync)(dir).filter((f) => f.endsWith(".json"));
16987
+ if ((0, import_node_fs20.existsSync)(dir)) {
16988
+ const files = (0, import_node_fs20.readdirSync)(dir).filter((f) => f.endsWith(".json"));
16753
16989
  for (const file of files) {
16754
16990
  try {
16755
- const raw = (0, import_node_fs19.readFileSync)((0, import_node_path14.join)(dir, file), "utf-8");
16991
+ const raw = (0, import_node_fs20.readFileSync)((0, import_node_path15.join)(dir, file), "utf-8");
16756
16992
  const parsed = JSON.parse(raw);
16757
16993
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
16758
16994
  for (const rule of customRules) {
@@ -16783,9 +17019,9 @@ function loadAllRules(customDir) {
16783
17019
  }
16784
17020
 
16785
17021
  // src/daemon/firewall/adapters.ts
16786
- var import_node_child_process5 = require("child_process");
16787
- var import_node_fs20 = require("fs");
16788
- var import_node_path15 = require("path");
17022
+ var import_node_child_process6 = require("child_process");
17023
+ var import_node_fs21 = require("fs");
17024
+ var import_node_path16 = require("path");
16789
17025
  var import_node_net6 = require("net");
16790
17026
  function assertValidFirewallIp(ip) {
16791
17027
  if ((0, import_node_net6.isIP)(ip) !== 4) {
@@ -16798,9 +17034,9 @@ function assertBannableIp(ip) {
16798
17034
  }
16799
17035
  }
16800
17036
  function writeIfAbsent(path, contents) {
16801
- (0, import_node_fs20.mkdirSync)((0, import_node_path15.dirname)(path), { recursive: true });
17037
+ (0, import_node_fs21.mkdirSync)((0, import_node_path16.dirname)(path), { recursive: true });
16802
17038
  try {
16803
- (0, import_node_fs20.writeFileSync)(path, contents, { flag: "wx" });
17039
+ (0, import_node_fs21.writeFileSync)(path, contents, { flag: "wx" });
16804
17040
  } catch (err) {
16805
17041
  if (err.code !== "EEXIST") throw err;
16806
17042
  }
@@ -16819,11 +17055,11 @@ var Fail2banAdapter = class {
16819
17055
  enforces = true;
16820
17056
  jailReady = false;
16821
17057
  isAvailable() {
16822
- const result = (0, import_node_child_process5.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
17058
+ const result = (0, import_node_child_process6.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
16823
17059
  return result.status === 0;
16824
17060
  }
16825
17061
  client(args) {
16826
- return (0, import_node_child_process5.execFileSync)("fail2ban-client", args, {
17062
+ return (0, import_node_child_process6.execFileSync)("fail2ban-client", args, {
16827
17063
  encoding: "utf-8",
16828
17064
  stdio: ["ignore", "pipe", "pipe"]
16829
17065
  });
@@ -16919,35 +17155,35 @@ var NftablesAdapter = class {
16919
17155
  table = "threatcrush";
16920
17156
  set = "blocklist";
16921
17157
  isAvailable() {
16922
- const result = (0, import_node_child_process5.spawnSync)("nft", ["--version"], { stdio: "pipe" });
17158
+ const result = (0, import_node_child_process6.spawnSync)("nft", ["--version"], { stdio: "pipe" });
16923
17159
  return result.status === 0;
16924
17160
  }
16925
17161
  ensureSetup() {
16926
17162
  try {
16927
- (0, import_node_child_process5.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
17163
+ (0, import_node_child_process6.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
16928
17164
  } catch {
16929
- (0, import_node_child_process5.execSync)(`nft add table inet ${this.table}`);
16930
- (0, import_node_child_process5.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
16931
- (0, import_node_child_process5.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
16932
- (0, import_node_child_process5.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
17165
+ (0, import_node_child_process6.execSync)(`nft add table inet ${this.table}`);
17166
+ (0, import_node_child_process6.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
17167
+ (0, import_node_child_process6.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
17168
+ (0, import_node_child_process6.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
16933
17169
  }
16934
17170
  }
16935
17171
  async block(ip) {
16936
17172
  assertValidFirewallIp(ip);
16937
17173
  this.ensureSetup();
16938
- (0, import_node_child_process5.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
17174
+ (0, import_node_child_process6.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
16939
17175
  }
16940
17176
  async unblock(ip) {
16941
17177
  assertValidFirewallIp(ip);
16942
17178
  try {
16943
- (0, import_node_child_process5.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
17179
+ (0, import_node_child_process6.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
16944
17180
  } catch {
16945
17181
  }
16946
17182
  }
16947
17183
  async isBlocked(ip) {
16948
17184
  assertValidFirewallIp(ip);
16949
17185
  try {
16950
- const output = (0, import_node_child_process5.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
17186
+ const output = (0, import_node_child_process6.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
16951
17187
  return output.includes(ip);
16952
17188
  } catch {
16953
17189
  return false;
@@ -16955,7 +17191,7 @@ var NftablesAdapter = class {
16955
17191
  }
16956
17192
  async listBlocked() {
16957
17193
  try {
16958
- const output = (0, import_node_child_process5.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
17194
+ const output = (0, import_node_child_process6.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
16959
17195
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
16960
17196
  if (!match) return [];
16961
17197
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -16968,34 +17204,34 @@ var IptablesAdapter = class {
16968
17204
  name = "iptables";
16969
17205
  chain = "THREATCRUSH";
16970
17206
  isAvailable() {
16971
- const result = (0, import_node_child_process5.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
17207
+ const result = (0, import_node_child_process6.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
16972
17208
  return result.status === 0;
16973
17209
  }
16974
17210
  ensureChain() {
16975
17211
  try {
16976
- (0, import_node_child_process5.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
17212
+ (0, import_node_child_process6.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
16977
17213
  } catch {
16978
- (0, import_node_child_process5.execSync)(`iptables -N ${this.chain}`);
16979
- (0, import_node_child_process5.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
17214
+ (0, import_node_child_process6.execSync)(`iptables -N ${this.chain}`);
17215
+ (0, import_node_child_process6.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
16980
17216
  }
16981
17217
  }
16982
17218
  async block(ip) {
16983
17219
  assertValidFirewallIp(ip);
16984
17220
  this.ensureChain();
16985
17221
  if (await this.isBlocked(ip)) return;
16986
- (0, import_node_child_process5.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
17222
+ (0, import_node_child_process6.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
16987
17223
  }
16988
17224
  async unblock(ip) {
16989
17225
  assertValidFirewallIp(ip);
16990
17226
  try {
16991
- (0, import_node_child_process5.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
17227
+ (0, import_node_child_process6.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
16992
17228
  } catch {
16993
17229
  }
16994
17230
  }
16995
17231
  async isBlocked(ip) {
16996
17232
  assertValidFirewallIp(ip);
16997
17233
  try {
16998
- const output = (0, import_node_child_process5.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
17234
+ const output = (0, import_node_child_process6.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
16999
17235
  return output.includes(ip);
17000
17236
  } catch {
17001
17237
  return false;
@@ -17003,7 +17239,7 @@ var IptablesAdapter = class {
17003
17239
  }
17004
17240
  async listBlocked() {
17005
17241
  try {
17006
- const output = (0, import_node_child_process5.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
17242
+ const output = (0, import_node_child_process6.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
17007
17243
  const ips = [];
17008
17244
  for (const line of output.split("\n")) {
17009
17245
  const match = line.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -17059,7 +17295,7 @@ function detectFirewallAdapter(backend = "auto") {
17059
17295
  }
17060
17296
 
17061
17297
  // src/daemon/firewall/remediation.ts
17062
- var import_node_fs21 = require("fs");
17298
+ var import_node_fs22 = require("fs");
17063
17299
  var import_node_net7 = require("net");
17064
17300
 
17065
17301
  // src/daemon/firewall/crawlers.ts
@@ -17471,7 +17707,7 @@ var RemediationManager = class {
17471
17707
  }
17472
17708
  logLine(line) {
17473
17709
  try {
17474
- (0, import_node_fs21.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
17710
+ (0, import_node_fs22.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
17475
17711
  `);
17476
17712
  } catch {
17477
17713
  }
@@ -17505,13 +17741,13 @@ function remediationSettings(section) {
17505
17741
  }
17506
17742
 
17507
17743
  // src/daemon/watchdog-service.ts
17508
- var import_node_fs23 = require("fs");
17509
- var import_node_path17 = require("path");
17744
+ var import_node_fs24 = require("fs");
17745
+ var import_node_path18 = require("path");
17510
17746
 
17511
17747
  // src/core/watchdog.ts
17512
- var import_node_fs22 = require("fs");
17748
+ var import_node_fs23 = require("fs");
17513
17749
  var import_node_crypto5 = require("crypto");
17514
- var import_node_path16 = require("path");
17750
+ var import_node_path17 = require("path");
17515
17751
  var WATCHDOG_DIRNAME = "watchdog";
17516
17752
  var LOG_FILE = "attacks.jsonl";
17517
17753
  var ROTATED_FILE = "attacks.1.jsonl";
@@ -17600,12 +17836,12 @@ var WatchdogLog = class {
17600
17836
  stats = { logged: 0, answered: 0, errored: 0 };
17601
17837
  constructor(dir, options = {}) {
17602
17838
  this.dir = dir;
17603
- this.file = (0, import_node_path16.join)(dir, LOG_FILE);
17839
+ this.file = (0, import_node_path17.join)(dir, LOG_FILE);
17604
17840
  this.shareGid = options.shareGid;
17605
- (0, import_node_fs22.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
17841
+ (0, import_node_fs23.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
17606
17842
  if (this.shareGid !== void 0) {
17607
- (0, import_node_fs22.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
17608
- (0, import_node_fs22.chmodSync)(dir, 1528);
17843
+ (0, import_node_fs23.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
17844
+ (0, import_node_fs23.chmodSync)(dir, 1528);
17609
17845
  }
17610
17846
  for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
17611
17847
  }
@@ -17634,16 +17870,16 @@ var WatchdogLog = class {
17634
17870
  const chunk = this.buffer.join("\n") + "\n";
17635
17871
  this.buffer = [];
17636
17872
  try {
17637
- if ((0, import_node_fs22.statSync)(this.file).size > ROTATE_BYTES) {
17638
- (0, import_node_fs22.renameSync)(this.file, (0, import_node_path16.join)(this.dir, ROTATED_FILE));
17873
+ if ((0, import_node_fs23.statSync)(this.file).size > ROTATE_BYTES) {
17874
+ (0, import_node_fs23.renameSync)(this.file, (0, import_node_path17.join)(this.dir, ROTATED_FILE));
17639
17875
  }
17640
17876
  } catch {
17641
17877
  }
17642
- (0, import_node_fs22.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
17878
+ (0, import_node_fs23.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
17643
17879
  if (this.shareGid !== void 0) {
17644
17880
  try {
17645
- (0, import_node_fs22.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
17646
- (0, import_node_fs22.chmodSync)(this.file, 432);
17881
+ (0, import_node_fs23.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
17882
+ (0, import_node_fs23.chmodSync)(this.file, 432);
17647
17883
  } catch {
17648
17884
  }
17649
17885
  }
@@ -17664,21 +17900,21 @@ function parseLines(text) {
17664
17900
  function readTail(file, bytes) {
17665
17901
  let fd;
17666
17902
  try {
17667
- fd = (0, import_node_fs22.openSync)(file, "r");
17903
+ fd = (0, import_node_fs23.openSync)(file, "r");
17668
17904
  } catch (err) {
17669
17905
  if (err.code === "ENOENT") return [];
17670
17906
  throw err;
17671
17907
  }
17672
17908
  try {
17673
- const size = (0, import_node_fs22.fstatSync)(fd).size;
17909
+ const size = (0, import_node_fs23.fstatSync)(fd).size;
17674
17910
  const start = Math.max(0, size - bytes);
17675
17911
  const buf = Buffer.alloc(size - start);
17676
- (0, import_node_fs22.readSync)(fd, buf, 0, buf.length, start);
17912
+ (0, import_node_fs23.readSync)(fd, buf, 0, buf.length, start);
17677
17913
  let text = buf.toString("utf8");
17678
17914
  if (start > 0) text = text.slice(text.indexOf("\n") + 1);
17679
17915
  return parseLines(text);
17680
17916
  } finally {
17681
- (0, import_node_fs22.closeSync)(fd);
17917
+ (0, import_node_fs23.closeSync)(fd);
17682
17918
  }
17683
17919
  }
17684
17920
 
@@ -17687,13 +17923,13 @@ function defaultShareGid() {
17687
17923
  const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
17688
17924
  if (!isRoot2) return void 0;
17689
17925
  try {
17690
- return (0, import_node_fs23.statSync)("/var/log/auth.log").gid;
17926
+ return (0, import_node_fs24.statSync)("/var/log/auth.log").gid;
17691
17927
  } catch {
17692
17928
  return void 0;
17693
17929
  }
17694
17930
  }
17695
17931
  function startWatchdog(opts) {
17696
- const dir = opts.config?.dir ?? (0, import_node_path17.join)(opts.stateDir, WATCHDOG_DIRNAME);
17932
+ const dir = opts.config?.dir ?? (0, import_node_path18.join)(opts.stateDir, WATCHDOG_DIRNAME);
17697
17933
  const base = { dir, logged: 0, answered: 0, errored: 0 };
17698
17934
  if (opts.config?.enabled === false) {
17699
17935
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -17784,7 +18020,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
17784
18020
  }
17785
18021
 
17786
18022
  // src/core/node-runtime.ts
17787
- var import_node_child_process6 = require("child_process");
18023
+ var import_node_child_process7 = require("child_process");
17788
18024
  var MIN_DAEMON_NODE_MAJOR = 22;
17789
18025
  function nodeMajor(version) {
17790
18026
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -17800,16 +18036,16 @@ function daemonNodeProblem(version) {
17800
18036
  // src/daemon/index.ts
17801
18037
  function readVersion2() {
17802
18038
  try {
17803
- const pkg = JSON.parse((0, import_node_fs24.readFileSync)((0, import_node_path18.join)(__dirname, "..", "package.json"), "utf-8"));
18039
+ const pkg = JSON.parse((0, import_node_fs25.readFileSync)((0, import_node_path19.join)(__dirname, "..", "package.json"), "utf-8"));
17804
18040
  return pkg.version || "0.0.0";
17805
18041
  } catch {
17806
18042
  return "0.0.0";
17807
18043
  }
17808
18044
  }
17809
18045
  async function runHardeningChecks() {
17810
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process7.execFile)(
18046
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process8.execFile)(
17811
18047
  process.execPath,
17812
- [(0, import_node_path18.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
18048
+ [(0, import_node_path19.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
17813
18049
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
17814
18050
  );
17815
18051
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -17817,7 +18053,7 @@ async function runHardeningChecks() {
17817
18053
  }
17818
18054
  function logLine(line) {
17819
18055
  try {
17820
- (0, import_node_fs24.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
18056
+ (0, import_node_fs25.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
17821
18057
  `);
17822
18058
  } catch {
17823
18059
  }
@@ -17842,9 +18078,9 @@ async function runDaemon() {
17842
18078
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
17843
18079
  const restartDaemon = () => {
17844
18080
  if (PATHS.mode === "system") {
17845
- (0, import_node_child_process7.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
18081
+ (0, import_node_child_process8.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
17846
18082
  } else {
17847
- (0, import_node_child_process7.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
18083
+ (0, import_node_child_process8.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
17848
18084
  setTimeout(() => process.exit(0), 500).unref();
17849
18085
  }
17850
18086
  };
@@ -17859,7 +18095,7 @@ async function runDaemon() {
17859
18095
  } catch (err) {
17860
18096
  logLine(`[daemon] state db unavailable: ${err.message}`);
17861
18097
  }
17862
- const config = loadConfig((0, import_node_fs24.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
18098
+ const config = loadConfig((0, import_node_fs25.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
17863
18099
  configureAttackDetection(config.detection);
17864
18100
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
17865
18101
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -17938,7 +18174,7 @@ async function runDaemon() {
17938
18174
  version,
17939
18175
  hostname: (0, import_node_os5.hostname)(),
17940
18176
  minSeverity,
17941
- spoolPath: (0, import_node_path18.join)(PATHS.stateDir, "cloud-spool.jsonl"),
18177
+ spoolPath: (0, import_node_path19.join)(PATHS.stateDir, "cloud-spool.jsonl"),
17942
18178
  log: logLine,
17943
18179
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
17944
18180
  runHardening: runHardeningChecks
@@ -17952,6 +18188,16 @@ async function runDaemon() {
17952
18188
  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");
17953
18189
  }
17954
18190
  const watchdog = startWatchdog({ bus, config: config.watchdog, stateDir: PATHS.stateDir, log: logLine });
18191
+ const autoUpdate = new AutoUpdate({
18192
+ version,
18193
+ settings: updateSettings(config.update),
18194
+ pkgRoot: (0, import_node_path19.join)(__dirname, ".."),
18195
+ statePath: (0, import_node_path19.join)(PATHS.stateDir, "auto-update.json"),
18196
+ bus,
18197
+ log: logLine,
18198
+ restartDaemon
18199
+ });
18200
+ autoUpdate.start();
17955
18201
  const ipc = new IpcServer(version, moduleHost, remediation, () => watchdog.status());
17956
18202
  await ipc.start();
17957
18203
  logLine(`[daemon] ipc listening on ${PATHS.socket}`);
@@ -17985,6 +18231,10 @@ async function runDaemon() {
17985
18231
  watchdog.stop();
17986
18232
  } catch {
17987
18233
  }
18234
+ try {
18235
+ autoUpdate.stop();
18236
+ } catch {
18237
+ }
17988
18238
  try {
17989
18239
  await ipc.stop();
17990
18240
  } catch {