@profullstack/threatcrush 0.13.34 → 0.13.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6241,22 +6241,22 @@ var init_diff = __esm({
6241
6241
  s.fg = DEFAULT_COLOR;
6242
6242
  s.bg = DEFAULT_COLOR;
6243
6243
  }
6244
- const added = attrs & ~s.attrs;
6245
- if (added !== 0) {
6244
+ const added2 = attrs & ~s.attrs;
6245
+ if (added2 !== 0) {
6246
6246
  const codes = [];
6247
- if (added & Attr.Bold)
6247
+ if (added2 & Attr.Bold)
6248
6248
  codes.push(1);
6249
- if (added & Attr.Dim)
6249
+ if (added2 & Attr.Dim)
6250
6250
  codes.push(2);
6251
- if (added & Attr.Italic)
6251
+ if (added2 & Attr.Italic)
6252
6252
  codes.push(3);
6253
- if (added & Attr.Underline)
6253
+ if (added2 & Attr.Underline)
6254
6254
  codes.push(4);
6255
- if (added & Attr.Blink)
6255
+ if (added2 & Attr.Blink)
6256
6256
  codes.push(5);
6257
- if (added & Attr.Reverse)
6257
+ if (added2 & Attr.Reverse)
6258
6258
  codes.push(7);
6259
- if (added & Attr.Strike)
6259
+ if (added2 & Attr.Strike)
6260
6260
  codes.push(9);
6261
6261
  if (codes.length)
6262
6262
  this.parts.push(`${CSI}${codes.join(";")}m`);
@@ -21537,7 +21537,7 @@ var init_map = __esm({
21537
21537
  this.selfAsked = true;
21538
21538
  void this.lookupSelf();
21539
21539
  }
21540
- let added = false;
21540
+ let added2 = false;
21541
21541
  for (const ip of ips) {
21542
21542
  if (this.known.has(ip) || this.queue.has(ip)) continue;
21543
21543
  if (!isPublicAddress(ip)) {
@@ -21545,9 +21545,9 @@ var init_map = __esm({
21545
21545
  continue;
21546
21546
  }
21547
21547
  this.queue.add(ip);
21548
- added = true;
21548
+ added2 = true;
21549
21549
  }
21550
- if (added && !this.timer) {
21550
+ if (added2 && !this.timer) {
21551
21551
  this.timer = setTimeout(() => {
21552
21552
  this.timer = null;
21553
21553
  void this.flush();
@@ -24745,9 +24745,9 @@ var source_default = chalk;
24745
24745
 
24746
24746
  // src/index.ts
24747
24747
  var import_readline = __toESM(require("readline"));
24748
- var import_node_child_process19 = require("child_process");
24749
- var import_node_fs44 = require("fs");
24750
- var import_node_path33 = require("path");
24748
+ var import_node_child_process20 = require("child_process");
24749
+ var import_node_fs46 = require("fs");
24750
+ var import_node_path34 = require("path");
24751
24751
  var import_node_os13 = require("os");
24752
24752
 
24753
24753
  // src/commands/monitor.ts
@@ -31641,6 +31641,7 @@ function loadConfig(configPath) {
31641
31641
  watchdog: parsed.watchdog,
31642
31642
  update: parsed.update,
31643
31643
  threat_feeds: parsed.threat_feeds,
31644
+ privileged: parsed.privileged,
31644
31645
  storage: parsed.storage,
31645
31646
  license: parsed.license
31646
31647
  };
@@ -31779,6 +31780,14 @@ function getRecentEvents(limit = 50) {
31779
31780
  `).all(limit);
31780
31781
  return rows.map(rowToEvent);
31781
31782
  }
31783
+ function getModuleEvents(module2, limit = 50) {
31784
+ const database = tryDb();
31785
+ if (!database) return [];
31786
+ const rows = database.prepare(`
31787
+ SELECT * FROM events WHERE module = ? ORDER BY id DESC LIMIT ?
31788
+ `).all(module2, limit);
31789
+ return rows.map(rowToEvent);
31790
+ }
31782
31791
  var RECENT_WINDOW = 2e5;
31783
31792
  function eventsEverRecorded(database) {
31784
31793
  const row = database.prepare(`SELECT seq FROM sqlite_sequence WHERE name = 'events'`).get();
@@ -39780,16 +39789,16 @@ async function sshConnect(options) {
39780
39789
  }
39781
39790
 
39782
39791
  // src/commands/daemon.ts
39783
- var import_node_child_process14 = require("child_process");
39784
- var import_node_fs37 = require("fs");
39785
- var import_node_path28 = require("path");
39792
+ var import_node_child_process15 = require("child_process");
39786
39793
  var import_node_fs38 = require("fs");
39794
+ var import_node_path29 = require("path");
39795
+ var import_node_fs39 = require("fs");
39787
39796
 
39788
39797
  // src/daemon/index.ts
39789
- var import_node_fs36 = require("fs");
39790
- var import_node_child_process13 = require("child_process");
39798
+ var import_node_fs37 = require("fs");
39799
+ var import_node_child_process14 = require("child_process");
39791
39800
  var import_node_os11 = require("os");
39792
- var import_node_path27 = require("path");
39801
+ var import_node_path28 = require("path");
39793
39802
  var import_node_util = require("util");
39794
39803
  init_paths();
39795
39804
 
@@ -42412,13 +42421,13 @@ var AllowlistSync = class {
42412
42421
  const value = String(entry.value ?? "").trim();
42413
42422
  if (isAddressOrCidr(value)) wanted.add(value);
42414
42423
  }
42415
- const added = [];
42424
+ const added2 = [];
42416
42425
  const protectedNow = new Set(this.manager.getProtected());
42417
42426
  for (const value of wanted) {
42418
42427
  if (this.owned.has(value) || protectedNow.has(value)) continue;
42419
42428
  this.manager.addToAllowlist(value);
42420
42429
  this.owned.add(value);
42421
- added.push(value);
42430
+ added2.push(value);
42422
42431
  }
42423
42432
  const removed = [];
42424
42433
  for (const value of this.owned) {
@@ -42427,9 +42436,9 @@ var AllowlistSync = class {
42427
42436
  this.owned.delete(value);
42428
42437
  removed.push(value);
42429
42438
  }
42430
- if (added.length > 0 || removed.length > 0) {
42439
+ if (added2.length > 0 || removed.length > 0) {
42431
42440
  this.opts.log(
42432
- `[cloud] org allowlist: +${added.length} -${removed.length} (${[...added.map((v) => `+${v}`), ...removed.map((v) => `-${v}`)].slice(0, 10).join(" ")})`
42441
+ `[cloud] org allowlist: +${added2.length} -${removed.length} (${[...added2.map((v) => `+${v}`), ...removed.map((v) => `-${v}`)].slice(0, 10).join(" ")})`
42433
42442
  );
42434
42443
  }
42435
42444
  }
@@ -43023,6 +43032,374 @@ var ThreatFeeds = class {
43023
43032
  }
43024
43033
  };
43025
43034
 
43035
+ // src/daemon/workers/privilege-watch.ts
43036
+ var import_node_fs32 = require("fs");
43037
+ var import_node_path24 = require("path");
43038
+ var import_node_child_process11 = require("child_process");
43039
+
43040
+ // src/core/privileges/index.ts
43041
+ var import_node_crypto7 = require("crypto");
43042
+ var ADMIN_GROUPS = ["sudo", "wheel", "admin"];
43043
+ function parseUsers(text) {
43044
+ const out = [];
43045
+ for (const line2 of text.split("\n")) {
43046
+ const f = line2.split(":");
43047
+ if (f.length < 7 || line2.startsWith("#")) continue;
43048
+ const uid = Number(f[2]);
43049
+ if (!f[0] || !Number.isInteger(uid)) continue;
43050
+ out.push({ name: f[0], uid, home: f[5], shell: f[6].trim() });
43051
+ }
43052
+ return out;
43053
+ }
43054
+ function parseAdminGroups(text) {
43055
+ const out = {};
43056
+ for (const line2 of text.split("\n")) {
43057
+ const f = line2.split(":");
43058
+ if (f.length < 4 || !ADMIN_GROUPS.includes(f[0])) continue;
43059
+ out[f[0]] = f[3].trim().split(",").map((m) => m.trim()).filter(Boolean).sort();
43060
+ }
43061
+ return out;
43062
+ }
43063
+ function canLogIn(user) {
43064
+ return !/(nologin|\/false|\/sync|\/shutdown|\/halt)$/.test(user.shell);
43065
+ }
43066
+ function sudoersRules(text) {
43067
+ const joined = text.replace(/\\\n/g, " ");
43068
+ const rules = [];
43069
+ for (const raw of joined.split("\n")) {
43070
+ const line2 = raw.trim();
43071
+ if (!line2) continue;
43072
+ if (line2.startsWith("#") && !/^#include(dir)?\s/.test(line2)) continue;
43073
+ rules.push(line2.replace(/\s+/g, " "));
43074
+ }
43075
+ return rules;
43076
+ }
43077
+ function sudoReadsIncluded(name) {
43078
+ return !name.endsWith("~") && !name.includes(".");
43079
+ }
43080
+ function keyFingerprint(blobBase64) {
43081
+ if (!/^[A-Za-z0-9+/]+=*$/.test(blobBase64)) return null;
43082
+ const digest = (0, import_node_crypto7.createHash)("sha256").update(Buffer.from(blobBase64, "base64")).digest("base64");
43083
+ return `SHA256:${digest.replace(/=+$/, "")}`;
43084
+ }
43085
+ function parseAuthorizedKeys(text) {
43086
+ const out = [];
43087
+ for (const raw of text.split("\n")) {
43088
+ const line2 = raw.trim();
43089
+ if (!line2 || line2.startsWith("#")) continue;
43090
+ const m = /(?:^|\s)((?:ssh|ecdsa|sk)-[\w@.-]+)\s+([A-Za-z0-9+/]+=*)(?:\s+(.*))?$/.exec(line2);
43091
+ if (!m) continue;
43092
+ const fingerprint = keyFingerprint(m[2]);
43093
+ if (fingerprint) out.push({ fingerprint, type: m[1], comment: (m[3] ?? "").trim() });
43094
+ }
43095
+ return out;
43096
+ }
43097
+ function takeSnapshot(io, now = /* @__PURE__ */ new Date()) {
43098
+ const unreadable = [];
43099
+ const read = (path) => {
43100
+ const text = io.readFile(path);
43101
+ if (text === null && io.exists(path)) unreadable.push(path);
43102
+ return text;
43103
+ };
43104
+ const users = parseUsers(read("/etc/passwd") ?? "");
43105
+ const snapshot = {
43106
+ taken_at: now.toISOString(),
43107
+ uid0: users.filter((a) => a.uid === 0).map((a) => a.name).sort(),
43108
+ admin_groups: parseAdminGroups(read("/etc/group") ?? ""),
43109
+ sudoers: {},
43110
+ keys: {},
43111
+ unreadable
43112
+ };
43113
+ const sudoersFiles = ["/etc/sudoers"];
43114
+ for (const name of (io.readDir("/etc/sudoers.d") ?? []).sort()) {
43115
+ if (sudoReadsIncluded(name)) sudoersFiles.push(`/etc/sudoers.d/${name}`);
43116
+ }
43117
+ for (const path of sudoersFiles) {
43118
+ const text = read(path);
43119
+ if (text !== null) snapshot.sudoers[path] = sudoersRules(text);
43120
+ }
43121
+ for (const user of users) {
43122
+ if (user.uid !== 0 && (!canLogIn(user) || !user.home || user.home === "/")) continue;
43123
+ const keys = {};
43124
+ for (const file of ["authorized_keys", "authorized_keys2"]) {
43125
+ const text = read(`${user.home.replace(/\/$/, "")}/.ssh/${file}`);
43126
+ for (const k of parseAuthorizedKeys(text ?? "")) keys[k.fingerprint] = { type: k.type, comment: k.comment };
43127
+ }
43128
+ if (Object.keys(keys).length > 0) snapshot.keys[user.name] = keys;
43129
+ }
43130
+ return snapshot;
43131
+ }
43132
+ var added = (before2, after) => after.filter((x) => !before2.includes(x));
43133
+ function diffSnapshots(prev, next) {
43134
+ const changes = [];
43135
+ for (const name of added(prev.uid0, next.uid0)) {
43136
+ changes.push({ severity: "critical", message: `New uid 0 account: ${name}`, details: { rule_id: "priv-uid0-added", account: name } });
43137
+ }
43138
+ for (const name of added(next.uid0, prev.uid0)) {
43139
+ changes.push({ severity: "low", message: `uid 0 account removed: ${name}`, details: { rule_id: "priv-uid0-removed", account: name } });
43140
+ }
43141
+ for (const group of /* @__PURE__ */ new Set([...Object.keys(prev.admin_groups), ...Object.keys(next.admin_groups)])) {
43142
+ const before2 = prev.admin_groups[group] ?? [];
43143
+ const after = next.admin_groups[group] ?? [];
43144
+ for (const m of added(before2, after)) {
43145
+ changes.push({ severity: "high", message: `${m} added to the ${group} group (can run anything as root)`, details: { rule_id: "priv-admin-group-added", group, account: m } });
43146
+ }
43147
+ for (const m of added(after, before2)) {
43148
+ changes.push({ severity: "low", message: `${m} removed from the ${group} group`, details: { rule_id: "priv-admin-group-removed", group, account: m } });
43149
+ }
43150
+ }
43151
+ for (const path of /* @__PURE__ */ new Set([...Object.keys(prev.sudoers), ...Object.keys(next.sudoers)])) {
43152
+ if (next.unreadable.includes(path) || prev.unreadable.includes(path)) continue;
43153
+ const before2 = prev.sudoers[path];
43154
+ const after = next.sudoers[path];
43155
+ if (!before2 && after) {
43156
+ changes.push({ severity: "high", message: `New sudoers file ${path}${after.length ? `: ${after.slice(0, 3).join(" | ")}` : ""}`, details: { rule_id: "priv-sudoers-added", path, rules: after.slice(0, 20) } });
43157
+ continue;
43158
+ }
43159
+ if (before2 && !after) {
43160
+ changes.push({ severity: "low", message: `Sudoers file removed: ${path}`, details: { rule_id: "priv-sudoers-removed", path } });
43161
+ continue;
43162
+ }
43163
+ const plus = added(before2 ?? [], after ?? []);
43164
+ const minus = added(after ?? [], before2 ?? []);
43165
+ if (plus.length) {
43166
+ changes.push({ severity: "high", message: `Sudoers rule added in ${path}: ${plus.slice(0, 3).join(" | ")}`, details: { rule_id: "priv-sudoers-changed", path, added: plus.slice(0, 20), removed: minus.slice(0, 20) } });
43167
+ } else if (minus.length) {
43168
+ changes.push({ severity: "low", message: `Sudoers rule removed in ${path}: ${minus.slice(0, 3).join(" | ")}`, details: { rule_id: "priv-sudoers-changed", path, removed: minus.slice(0, 20) } });
43169
+ }
43170
+ }
43171
+ for (const user of /* @__PURE__ */ new Set([...Object.keys(prev.keys), ...Object.keys(next.keys)])) {
43172
+ const before2 = prev.keys[user] ?? {};
43173
+ const after = next.keys[user] ?? {};
43174
+ for (const fp of Object.keys(after)) {
43175
+ if (before2[fp]) continue;
43176
+ const { type, comment } = after[fp];
43177
+ changes.push({
43178
+ severity: "high",
43179
+ message: `New SSH key for ${user}: ${type} ${fp}${comment ? ` (${comment})` : ""}`,
43180
+ details: { rule_id: "priv-authorized-key-added", account: user, fingerprint: fp, key_type: type, comment }
43181
+ });
43182
+ }
43183
+ for (const fp of Object.keys(before2)) {
43184
+ if (after[fp]) continue;
43185
+ changes.push({ severity: "low", message: `SSH key removed for ${user}: ${fp}`, details: { rule_id: "priv-authorized-key-removed", account: user, fingerprint: fp } });
43186
+ }
43187
+ }
43188
+ const rank = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
43189
+ return changes.sort((a, b) => rank[b.severity] - rank[a.severity]);
43190
+ }
43191
+ function parseSudoMessage(message) {
43192
+ const m = /^\s*(\S+)\s+:\s+(.*)$/.exec(message);
43193
+ if (!m) return null;
43194
+ const fields = {};
43195
+ let reason = "";
43196
+ for (const part of m[2].split(" ; ")) {
43197
+ const kv = /^([A-Z]+)=(.*)$/.exec(part.trim());
43198
+ if (kv) fields[kv[1]] = kv[2];
43199
+ else if (!reason) reason = part.trim();
43200
+ }
43201
+ if (!fields.COMMAND) return null;
43202
+ if (/incorrect password|authentication failure/i.test(reason)) return null;
43203
+ return {
43204
+ user: m[1],
43205
+ runas: fields.USER ?? "root",
43206
+ command: fields.COMMAND,
43207
+ tty: fields.TTY,
43208
+ pwd: fields.PWD,
43209
+ denied: /not allowed|not in the sudoers|NOT in sudoers|command not allowed/i.test(reason)
43210
+ };
43211
+ }
43212
+
43213
+ // src/daemon/workers/privilege-watch.ts
43214
+ function privilegeSettings(section) {
43215
+ return { enabled: section?.enabled !== false, geo: section?.geo !== false, pollMs: 6e4 };
43216
+ }
43217
+ var COUNTRY_NAMES = new Intl.DisplayNames(["en"], { type: "region" });
43218
+ function countryName(code) {
43219
+ try {
43220
+ return COUNTRY_NAMES.of(code) ?? code;
43221
+ } catch {
43222
+ return code;
43223
+ }
43224
+ }
43225
+ var fsIO = {
43226
+ readFile: (p) => {
43227
+ try {
43228
+ return (0, import_node_fs32.readFileSync)(p, "utf-8");
43229
+ } catch {
43230
+ return null;
43231
+ }
43232
+ },
43233
+ readDir: (p) => {
43234
+ try {
43235
+ return (0, import_node_fs32.readdirSync)(p);
43236
+ } catch {
43237
+ return null;
43238
+ }
43239
+ },
43240
+ exists: (p) => (0, import_node_fs32.existsSync)(p)
43241
+ };
43242
+ function readJson(path) {
43243
+ try {
43244
+ return JSON.parse((0, import_node_fs32.readFileSync)(path, "utf-8"));
43245
+ } catch {
43246
+ return null;
43247
+ }
43248
+ }
43249
+ function writeJson(path, value) {
43250
+ (0, import_node_fs32.mkdirSync)((0, import_node_path24.dirname)(path), { recursive: true });
43251
+ (0, import_node_fs32.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
43252
+ (0, import_node_fs32.renameSync)(`${path}.tmp`, path);
43253
+ }
43254
+ function defaultRun3(cmd, args) {
43255
+ const res = (0, import_node_child_process11.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 2e4, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
43256
+ return res.status === 0 ? res.stdout : null;
43257
+ }
43258
+ async function geolocateViaThreatcrush(ip, fetchImpl = fetch) {
43259
+ const res = await fetchImpl("https://threatcrush.com/api/geo", {
43260
+ method: "POST",
43261
+ headers: { "Content-Type": "application/json" },
43262
+ body: JSON.stringify({ ips: [ip] }),
43263
+ signal: AbortSignal.timeout(8e3)
43264
+ });
43265
+ if (!res.ok) return null;
43266
+ const body = await res.json();
43267
+ const code = body.results?.[ip]?.countryCode;
43268
+ return typeof code === "string" && /^[A-Z]{2}$/.test(code) ? { countryCode: code } : null;
43269
+ }
43270
+ var PrivilegeWatch = class {
43271
+ constructor(opts) {
43272
+ this.opts = opts;
43273
+ this.io = opts.io ?? fsIO;
43274
+ this.run = opts.run ?? defaultRun3;
43275
+ this.now = opts.now ?? (() => /* @__PURE__ */ new Date());
43276
+ }
43277
+ opts;
43278
+ timers = [];
43279
+ io;
43280
+ run;
43281
+ now;
43282
+ warnedUnreadable = false;
43283
+ onEvent = (event) => {
43284
+ void this.checkLogin(event);
43285
+ };
43286
+ start() {
43287
+ if (!this.opts.settings.enabled) {
43288
+ this.opts.log("[privileged] disabled by [privileged] enabled = false");
43289
+ return;
43290
+ }
43291
+ this.checkSnapshot();
43292
+ this.readSudoLedger();
43293
+ if (this.opts.settings.geo) this.opts.bus.on("event", this.onEvent);
43294
+ const timer = setInterval(() => {
43295
+ this.checkSnapshot();
43296
+ this.readSudoLedger();
43297
+ }, this.opts.settings.pollMs);
43298
+ timer.unref?.();
43299
+ this.timers.push(timer);
43300
+ }
43301
+ stop() {
43302
+ for (const t of this.timers) clearInterval(t);
43303
+ this.timers = [];
43304
+ this.opts.bus.off("event", this.onEvent);
43305
+ }
43306
+ emit(severity, message, details) {
43307
+ const event = { timestamp: this.now(), module: "privileged-access", category: "auth", severity, message, details };
43308
+ try {
43309
+ insertEvent(event);
43310
+ } catch {
43311
+ }
43312
+ this.opts.bus.publish(event);
43313
+ }
43314
+ checkSnapshot() {
43315
+ const next = takeSnapshot(this.io, this.now());
43316
+ if (next.unreadable.length && !this.warnedUnreadable) {
43317
+ this.warnedUnreadable = true;
43318
+ this.opts.log(`[privileged] cannot read ${next.unreadable.join(", ")}; run the daemon as root to watch them`);
43319
+ }
43320
+ const prev = readJson(this.opts.snapshotPath);
43321
+ if (!prev) {
43322
+ const keys = Object.values(next.keys).reduce((n, k) => n + Object.keys(k).length, 0);
43323
+ this.opts.log(`[privileged] baseline recorded: uid0 [${next.uid0.join(", ")}], ${Object.values(next.admin_groups).flat().length} admin-group member(s), ${Object.keys(next.sudoers).length} sudoers file(s), ${keys} authorized key(s)`);
43324
+ } else {
43325
+ for (const change of diffSnapshots(prev, next)) this.emit(change.severity, change.message, change.details);
43326
+ }
43327
+ try {
43328
+ writeJson(this.opts.snapshotPath, next);
43329
+ } catch (err) {
43330
+ this.opts.log(`[privileged] could not save snapshot: ${err.message}`);
43331
+ }
43332
+ }
43333
+ /**
43334
+ * New sudo records since the saved journal cursor. The first run only finds
43335
+ * the current end of the journal, so history from before the daemon is not
43336
+ * replayed as if it had just happened.
43337
+ */
43338
+ readSudoLedger() {
43339
+ const cursor = readJson(this.opts.cursorPath)?.cursor;
43340
+ const args = cursor ? ["-t", "sudo", "-o", "json", "--no-pager", `--after-cursor=${cursor}`] : ["-o", "json", "--no-pager", "-n", "0", "--show-cursor"];
43341
+ const out = this.run("journalctl", args);
43342
+ if (out === null) return;
43343
+ let last = cursor ?? /^-- cursor: (\S+)/m.exec(out)?.[1];
43344
+ for (const line2 of cursor ? out.split("\n") : []) {
43345
+ if (!line2.trim()) continue;
43346
+ let rec;
43347
+ try {
43348
+ rec = JSON.parse(line2);
43349
+ } catch {
43350
+ continue;
43351
+ }
43352
+ if (typeof rec.__CURSOR === "string") last = rec.__CURSOR;
43353
+ const entry = typeof rec.MESSAGE === "string" ? parseSudoMessage(rec.MESSAGE) : null;
43354
+ if (!entry) continue;
43355
+ this.emit(
43356
+ entry.denied ? "medium" : "info",
43357
+ entry.denied ? `sudo denied: ${entry.user} tried ${entry.command} as ${entry.runas}` : `sudo: ${entry.user} ran ${entry.command} as ${entry.runas}`,
43358
+ { rule_id: entry.denied ? "priv-sudo-denied" : "priv-sudo-command", account: entry.user, runas: entry.runas, command: entry.command, tty: entry.tty, pwd: entry.pwd }
43359
+ );
43360
+ }
43361
+ if (last && last !== cursor) {
43362
+ try {
43363
+ writeJson(this.opts.cursorPath, { cursor: last });
43364
+ } catch {
43365
+ }
43366
+ }
43367
+ }
43368
+ /** An accepted SSH login from a country new for that user. */
43369
+ async checkLogin(event) {
43370
+ if (event.module !== "ssh-guard" || !event.source_ip) return;
43371
+ const user = /SSH login accepted for (\S+)/.exec(event.message)?.[1];
43372
+ if (!user || user === "unknown" || isProtected(event.source_ip, DEFAULT_PROTECTED)) return;
43373
+ let geo = null;
43374
+ try {
43375
+ geo = await (this.opts.geolocate ?? geolocateViaThreatcrush)(event.source_ip);
43376
+ } catch (err) {
43377
+ this.opts.log(`[privileged] geolocation failed for ${event.source_ip}: ${err.message}`);
43378
+ }
43379
+ const country = geo?.countryCode;
43380
+ if (!country || !/^[A-Z]{2}$/.test(country)) return;
43381
+ const history = readJson(this.opts.loginsPath) ?? {};
43382
+ const seen = history[user] ?? {};
43383
+ const at = this.now().toISOString();
43384
+ const known = Object.keys(seen);
43385
+ if (known.length > 0 && !seen[country]) {
43386
+ this.emit("high", `SSH login for ${user} from a new country: ${countryName(country)}, ${event.source_ip}; seen before from ${known.join(", ")}`, {
43387
+ rule_id: "priv-login-new-country",
43388
+ account: user,
43389
+ login_ip: event.source_ip,
43390
+ country,
43391
+ known_countries: known
43392
+ });
43393
+ }
43394
+ seen[country] = { first: seen[country]?.first ?? at, last: at };
43395
+ history[user] = seen;
43396
+ try {
43397
+ writeJson(this.opts.loginsPath, history);
43398
+ } catch {
43399
+ }
43400
+ }
43401
+ };
43402
+
43026
43403
  // src/daemon/rules/engine.ts
43027
43404
  var MAX_WINDOW_ENTRIES = 1e3;
43028
43405
  function live(window) {
@@ -43184,8 +43561,8 @@ var RuleEngine = class {
43184
43561
  };
43185
43562
 
43186
43563
  // src/daemon/rules/loader.ts
43187
- var import_node_fs32 = require("fs");
43188
- var import_node_path24 = require("path");
43564
+ var import_node_fs33 = require("fs");
43565
+ var import_node_path25 = require("path");
43189
43566
 
43190
43567
  // src/daemon/rules/default-rules.ts
43191
43568
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -43586,11 +43963,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
43586
43963
  function loadAllRules(customDir) {
43587
43964
  const rules = [...DEFAULT_RULES];
43588
43965
  const dir = customDir || RULES_DIR;
43589
- if ((0, import_node_fs32.existsSync)(dir)) {
43590
- const files = (0, import_node_fs32.readdirSync)(dir).filter((f) => f.endsWith(".json"));
43966
+ if ((0, import_node_fs33.existsSync)(dir)) {
43967
+ const files = (0, import_node_fs33.readdirSync)(dir).filter((f) => f.endsWith(".json"));
43591
43968
  for (const file of files) {
43592
43969
  try {
43593
- const raw = (0, import_node_fs32.readFileSync)((0, import_node_path24.join)(dir, file), "utf-8");
43970
+ const raw = (0, import_node_fs33.readFileSync)((0, import_node_path25.join)(dir, file), "utf-8");
43594
43971
  const parsed = JSON.parse(raw);
43595
43972
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
43596
43973
  for (const rule of customRules) {
@@ -43621,9 +43998,9 @@ function loadAllRules(customDir) {
43621
43998
  }
43622
43999
 
43623
44000
  // src/daemon/firewall/adapters.ts
43624
- var import_node_child_process11 = require("child_process");
43625
- var import_node_fs33 = require("fs");
43626
- var import_node_path25 = require("path");
44001
+ var import_node_child_process12 = require("child_process");
44002
+ var import_node_fs34 = require("fs");
44003
+ var import_node_path26 = require("path");
43627
44004
  var import_node_net10 = require("net");
43628
44005
  function assertValidFirewallIp(ip) {
43629
44006
  if ((0, import_node_net10.isIP)(ip) !== 4) {
@@ -43636,9 +44013,9 @@ function assertBannableIp(ip) {
43636
44013
  }
43637
44014
  }
43638
44015
  function writeIfAbsent(path, contents) {
43639
- (0, import_node_fs33.mkdirSync)((0, import_node_path25.dirname)(path), { recursive: true });
44016
+ (0, import_node_fs34.mkdirSync)((0, import_node_path26.dirname)(path), { recursive: true });
43640
44017
  try {
43641
- (0, import_node_fs33.writeFileSync)(path, contents, { flag: "wx" });
44018
+ (0, import_node_fs34.writeFileSync)(path, contents, { flag: "wx" });
43642
44019
  } catch (err) {
43643
44020
  if (err.code !== "EEXIST") throw err;
43644
44021
  }
@@ -43657,11 +44034,11 @@ var Fail2banAdapter = class {
43657
44034
  enforces = true;
43658
44035
  jailReady = false;
43659
44036
  isAvailable() {
43660
- const result = (0, import_node_child_process11.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
44037
+ const result = (0, import_node_child_process12.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
43661
44038
  return result.status === 0;
43662
44039
  }
43663
44040
  client(args) {
43664
- return (0, import_node_child_process11.execFileSync)("fail2ban-client", args, {
44041
+ return (0, import_node_child_process12.execFileSync)("fail2ban-client", args, {
43665
44042
  encoding: "utf-8",
43666
44043
  stdio: ["ignore", "pipe", "pipe"]
43667
44044
  });
@@ -43757,35 +44134,35 @@ var NftablesAdapter = class {
43757
44134
  table = "threatcrush";
43758
44135
  set = "blocklist";
43759
44136
  isAvailable() {
43760
- const result = (0, import_node_child_process11.spawnSync)("nft", ["--version"], { stdio: "pipe" });
44137
+ const result = (0, import_node_child_process12.spawnSync)("nft", ["--version"], { stdio: "pipe" });
43761
44138
  return result.status === 0;
43762
44139
  }
43763
44140
  ensureSetup() {
43764
44141
  try {
43765
- (0, import_node_child_process11.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
44142
+ (0, import_node_child_process12.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
43766
44143
  } catch {
43767
- (0, import_node_child_process11.execSync)(`nft add table inet ${this.table}`);
43768
- (0, import_node_child_process11.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
43769
- (0, import_node_child_process11.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
43770
- (0, import_node_child_process11.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
44144
+ (0, import_node_child_process12.execSync)(`nft add table inet ${this.table}`);
44145
+ (0, import_node_child_process12.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
44146
+ (0, import_node_child_process12.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
44147
+ (0, import_node_child_process12.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
43771
44148
  }
43772
44149
  }
43773
44150
  async block(ip) {
43774
44151
  assertValidFirewallIp(ip);
43775
44152
  this.ensureSetup();
43776
- (0, import_node_child_process11.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
44153
+ (0, import_node_child_process12.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
43777
44154
  }
43778
44155
  async unblock(ip) {
43779
44156
  assertValidFirewallIp(ip);
43780
44157
  try {
43781
- (0, import_node_child_process11.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
44158
+ (0, import_node_child_process12.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
43782
44159
  } catch {
43783
44160
  }
43784
44161
  }
43785
44162
  async isBlocked(ip) {
43786
44163
  assertValidFirewallIp(ip);
43787
44164
  try {
43788
- const output = (0, import_node_child_process11.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
44165
+ const output = (0, import_node_child_process12.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
43789
44166
  return output.includes(ip);
43790
44167
  } catch {
43791
44168
  return false;
@@ -43793,7 +44170,7 @@ var NftablesAdapter = class {
43793
44170
  }
43794
44171
  async listBlocked() {
43795
44172
  try {
43796
- const output = (0, import_node_child_process11.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
44173
+ const output = (0, import_node_child_process12.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
43797
44174
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
43798
44175
  if (!match) return [];
43799
44176
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -43806,34 +44183,34 @@ var IptablesAdapter = class {
43806
44183
  name = "iptables";
43807
44184
  chain = "THREATCRUSH";
43808
44185
  isAvailable() {
43809
- const result = (0, import_node_child_process11.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
44186
+ const result = (0, import_node_child_process12.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
43810
44187
  return result.status === 0;
43811
44188
  }
43812
44189
  ensureChain() {
43813
44190
  try {
43814
- (0, import_node_child_process11.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
44191
+ (0, import_node_child_process12.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
43815
44192
  } catch {
43816
- (0, import_node_child_process11.execSync)(`iptables -N ${this.chain}`);
43817
- (0, import_node_child_process11.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
44193
+ (0, import_node_child_process12.execSync)(`iptables -N ${this.chain}`);
44194
+ (0, import_node_child_process12.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
43818
44195
  }
43819
44196
  }
43820
44197
  async block(ip) {
43821
44198
  assertValidFirewallIp(ip);
43822
44199
  this.ensureChain();
43823
44200
  if (await this.isBlocked(ip)) return;
43824
- (0, import_node_child_process11.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
44201
+ (0, import_node_child_process12.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
43825
44202
  }
43826
44203
  async unblock(ip) {
43827
44204
  assertValidFirewallIp(ip);
43828
44205
  try {
43829
- (0, import_node_child_process11.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
44206
+ (0, import_node_child_process12.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
43830
44207
  } catch {
43831
44208
  }
43832
44209
  }
43833
44210
  async isBlocked(ip) {
43834
44211
  assertValidFirewallIp(ip);
43835
44212
  try {
43836
- const output = (0, import_node_child_process11.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
44213
+ const output = (0, import_node_child_process12.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
43837
44214
  return output.includes(ip);
43838
44215
  } catch {
43839
44216
  return false;
@@ -43841,7 +44218,7 @@ var IptablesAdapter = class {
43841
44218
  }
43842
44219
  async listBlocked() {
43843
44220
  try {
43844
- const output = (0, import_node_child_process11.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
44221
+ const output = (0, import_node_child_process12.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
43845
44222
  const ips = [];
43846
44223
  for (const line2 of output.split("\n")) {
43847
44224
  const match = line2.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -43897,7 +44274,7 @@ function detectFirewallAdapter(backend = "auto") {
43897
44274
  }
43898
44275
 
43899
44276
  // src/daemon/firewall/remediation.ts
43900
- var import_node_fs34 = require("fs");
44277
+ var import_node_fs35 = require("fs");
43901
44278
  var import_node_net11 = require("net");
43902
44279
  init_paths();
43903
44280
  init_backoff();
@@ -44311,7 +44688,7 @@ var RemediationManager = class {
44311
44688
  }
44312
44689
  logLine(line2) {
44313
44690
  try {
44314
- (0, import_node_fs34.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
44691
+ (0, import_node_fs35.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
44315
44692
  `);
44316
44693
  } catch {
44317
44694
  }
@@ -44349,19 +44726,19 @@ function remediationSettings(section) {
44349
44726
  init_backoff();
44350
44727
 
44351
44728
  // src/daemon/watchdog-service.ts
44352
- var import_node_fs35 = require("fs");
44353
- var import_node_path26 = require("path");
44729
+ var import_node_fs36 = require("fs");
44730
+ var import_node_path27 = require("path");
44354
44731
  function defaultShareGid() {
44355
44732
  const isRoot4 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
44356
44733
  if (!isRoot4) return void 0;
44357
44734
  try {
44358
- return (0, import_node_fs35.statSync)("/var/log/auth.log").gid;
44735
+ return (0, import_node_fs36.statSync)("/var/log/auth.log").gid;
44359
44736
  } catch {
44360
44737
  return void 0;
44361
44738
  }
44362
44739
  }
44363
44740
  function startWatchdog(opts) {
44364
- const dir = opts.config?.dir ?? (0, import_node_path26.join)(opts.stateDir, WATCHDOG_DIRNAME);
44741
+ const dir = opts.config?.dir ?? (0, import_node_path27.join)(opts.stateDir, WATCHDOG_DIRNAME);
44365
44742
  const base = { dir, logged: 0, answered: 0, errored: 0 };
44366
44743
  if (opts.config?.enabled === false) {
44367
44744
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -44455,7 +44832,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
44455
44832
  }
44456
44833
 
44457
44834
  // src/core/node-runtime.ts
44458
- var import_node_child_process12 = require("child_process");
44835
+ var import_node_child_process13 = require("child_process");
44459
44836
  var MIN_DAEMON_NODE_MAJOR = 22;
44460
44837
  function nodeMajor(version) {
44461
44838
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -44469,23 +44846,23 @@ function daemonNodeProblem(version) {
44469
44846
  }
44470
44847
  function versionOfNode(path) {
44471
44848
  if (path === process.execPath) return process.versions.node;
44472
- const res = (0, import_node_child_process12.spawnSync)(path, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
44849
+ const res = (0, import_node_child_process13.spawnSync)(path, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
44473
44850
  return res.status === 0 ? res.stdout.trim() : null;
44474
44851
  }
44475
44852
 
44476
44853
  // src/daemon/index.ts
44477
44854
  function readVersion2() {
44478
44855
  try {
44479
- const pkg = JSON.parse((0, import_node_fs36.readFileSync)((0, import_node_path27.join)(__dirname, "..", "package.json"), "utf-8"));
44856
+ const pkg = JSON.parse((0, import_node_fs37.readFileSync)((0, import_node_path28.join)(__dirname, "..", "package.json"), "utf-8"));
44480
44857
  return pkg.version || "0.0.0";
44481
44858
  } catch {
44482
44859
  return "0.0.0";
44483
44860
  }
44484
44861
  }
44485
44862
  async function runHardeningChecks() {
44486
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process13.execFile)(
44863
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process14.execFile)(
44487
44864
  process.execPath,
44488
- [(0, import_node_path27.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
44865
+ [(0, import_node_path28.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
44489
44866
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
44490
44867
  );
44491
44868
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -44497,9 +44874,9 @@ async function runHardeningChecks() {
44497
44874
  return patches ? [...findings, patches] : findings;
44498
44875
  }
44499
44876
  async function runPatchCheck() {
44500
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process13.execFile)(
44877
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process14.execFile)(
44501
44878
  process.execPath,
44502
- [(0, import_node_path27.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
44879
+ [(0, import_node_path28.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
44503
44880
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
44504
44881
  );
44505
44882
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -44507,7 +44884,7 @@ async function runPatchCheck() {
44507
44884
  }
44508
44885
  function logLine(line2) {
44509
44886
  try {
44510
- (0, import_node_fs36.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
44887
+ (0, import_node_fs37.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
44511
44888
  `);
44512
44889
  } catch {
44513
44890
  }
@@ -44532,9 +44909,9 @@ async function runDaemon() {
44532
44909
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
44533
44910
  const restartDaemon = () => {
44534
44911
  if (PATHS.mode === "system") {
44535
- (0, import_node_child_process13.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
44912
+ (0, import_node_child_process14.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
44536
44913
  } else {
44537
- (0, import_node_child_process13.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
44914
+ (0, import_node_child_process14.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
44538
44915
  setTimeout(() => process.exit(0), 500).unref();
44539
44916
  }
44540
44917
  };
@@ -44549,7 +44926,7 @@ async function runDaemon() {
44549
44926
  } catch (err) {
44550
44927
  logLine(`[daemon] state db unavailable: ${err.message}`);
44551
44928
  }
44552
- const config = loadConfig((0, import_node_fs36.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
44929
+ const config = loadConfig((0, import_node_fs37.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
44553
44930
  configureAttackDetection(config.detection);
44554
44931
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
44555
44932
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -44613,11 +44990,20 @@ async function runDaemon() {
44613
44990
  const threatFeeds = new ThreatFeeds({
44614
44991
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
44615
44992
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
44616
- cachePath: (0, import_node_path27.join)(PATHS.stateDir, "threat-feeds.json"),
44993
+ cachePath: (0, import_node_path28.join)(PATHS.stateDir, "threat-feeds.json"),
44617
44994
  bus,
44618
44995
  log: logLine
44619
44996
  });
44620
44997
  threatFeeds.start();
44998
+ const privilegeWatch = new PrivilegeWatch({
44999
+ settings: privilegeSettings(config.privileged),
45000
+ bus,
45001
+ snapshotPath: (0, import_node_path28.join)(PATHS.stateDir, "privileges.json"),
45002
+ loginsPath: (0, import_node_path28.join)(PATHS.stateDir, "login-countries.json"),
45003
+ cursorPath: (0, import_node_path28.join)(PATHS.stateDir, "sudo-cursor.json"),
45004
+ log: logLine
45005
+ });
45006
+ privilegeWatch.start();
44621
45007
  new AlertDispatcher(bus, config);
44622
45008
  const runsWorker = new RunsWorker(bus);
44623
45009
  try {
@@ -44637,7 +45023,7 @@ async function runDaemon() {
44637
45023
  version,
44638
45024
  hostname: (0, import_node_os11.hostname)(),
44639
45025
  minSeverity,
44640
- spoolPath: (0, import_node_path27.join)(PATHS.stateDir, "cloud-spool.jsonl"),
45026
+ spoolPath: (0, import_node_path28.join)(PATHS.stateDir, "cloud-spool.jsonl"),
44641
45027
  log: logLine,
44642
45028
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
44643
45029
  runHardening: runHardeningChecks
@@ -44654,8 +45040,8 @@ async function runDaemon() {
44654
45040
  const autoUpdate = new AutoUpdate({
44655
45041
  version,
44656
45042
  settings: updateSettings(config.update),
44657
- pkgRoot: (0, import_node_path27.join)(__dirname, ".."),
44658
- statePath: (0, import_node_path27.join)(PATHS.stateDir, "auto-update.json"),
45043
+ pkgRoot: (0, import_node_path28.join)(__dirname, ".."),
45044
+ statePath: (0, import_node_path28.join)(PATHS.stateDir, "auto-update.json"),
44659
45045
  bus,
44660
45046
  log: logLine,
44661
45047
  restartDaemon
@@ -44702,6 +45088,10 @@ async function runDaemon() {
44702
45088
  threatFeeds.stop();
44703
45089
  } catch {
44704
45090
  }
45091
+ try {
45092
+ privilegeWatch.stop();
45093
+ } catch {
45094
+ }
44705
45095
  try {
44706
45096
  await ipc.stop();
44707
45097
  } catch {
@@ -44737,7 +45127,7 @@ var SYSTEM_SOCKET = "/var/run/threatcrush/threatcrushd.sock";
44737
45127
  function isRoot2() {
44738
45128
  return typeof process.getuid === "function" && process.getuid() === 0;
44739
45129
  }
44740
- var DAEMON_ENTRY = (0, import_node_path28.join)(__dirname, "daemon.js");
45130
+ var DAEMON_ENTRY = (0, import_node_path29.join)(__dirname, "daemon.js");
44741
45131
  async function daemonForeground() {
44742
45132
  await runDaemon();
44743
45133
  }
@@ -44758,7 +45148,7 @@ async function daemonStart() {
44758
45148
  return;
44759
45149
  }
44760
45150
  ensureRuntimeDirs();
44761
- if (!(0, import_node_fs37.existsSync)(DAEMON_ENTRY)) {
45151
+ if (!(0, import_node_fs38.existsSync)(DAEMON_ENTRY)) {
44762
45152
  console.log(source_default.red(` Daemon entry not found at ${DAEMON_ENTRY}.`));
44763
45153
  console.log(source_default.dim(" Reinstall with `threatcrush update` or `pnpm run build` in the cli package."));
44764
45154
  return;
@@ -44766,8 +45156,8 @@ async function daemonStart() {
44766
45156
  let out;
44767
45157
  let err;
44768
45158
  try {
44769
- out = (0, import_node_fs38.openSync)(PATHS.logFile, "a");
44770
- err = (0, import_node_fs38.openSync)(PATHS.logFile, "a");
45159
+ out = (0, import_node_fs39.openSync)(PATHS.logFile, "a");
45160
+ err = (0, import_node_fs39.openSync)(PATHS.logFile, "a");
44771
45161
  } catch (e) {
44772
45162
  const code = e.code;
44773
45163
  console.log(source_default.red(` \u2717 Cannot write daemon log at ${PATHS.logFile} (${code ?? "error"}).`));
@@ -44780,7 +45170,7 @@ async function daemonStart() {
44780
45170
  }
44781
45171
  return;
44782
45172
  }
44783
- const child = (0, import_node_child_process14.spawn)(process.execPath, [DAEMON_ENTRY], {
45173
+ const child = (0, import_node_child_process15.spawn)(process.execPath, [DAEMON_ENTRY], {
44784
45174
  detached: true,
44785
45175
  stdio: ["ignore", out, err],
44786
45176
  env: { ...process.env, THREATCRUSH_DAEMON: "1" }
@@ -44855,41 +45245,41 @@ async function waitForExit(pid, timeoutMs) {
44855
45245
  }
44856
45246
  async function releaseStaleSocket() {
44857
45247
  const deadline = Date.now() + 2e3;
44858
- while ((0, import_node_fs37.existsSync)(PATHS.socket) && Date.now() < deadline) {
45248
+ while ((0, import_node_fs38.existsSync)(PATHS.socket) && Date.now() < deadline) {
44859
45249
  await new Promise((r) => setTimeout(r, 50));
44860
45250
  }
44861
- if ((0, import_node_fs37.existsSync)(PATHS.socket)) {
45251
+ if ((0, import_node_fs38.existsSync)(PATHS.socket)) {
44862
45252
  try {
44863
- (0, import_node_fs37.unlinkSync)(PATHS.socket);
45253
+ (0, import_node_fs38.unlinkSync)(PATHS.socket);
44864
45254
  } catch {
44865
45255
  }
44866
45256
  }
44867
45257
  }
44868
45258
 
44869
45259
  // src/commands/service.ts
44870
- var import_node_child_process15 = require("child_process");
44871
- var import_node_fs39 = require("fs");
44872
- var import_node_path29 = require("path");
45260
+ var import_node_child_process16 = require("child_process");
45261
+ var import_node_fs40 = require("fs");
45262
+ var import_node_path30 = require("path");
44873
45263
  var import_node_os12 = require("os");
44874
45264
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
44875
45265
  var DAEMON_UNIT_NAME = "threatcrushd.service";
44876
45266
  function resolveTemplate() {
44877
- const templatePath = (0, import_node_path29.join)(__dirname, "systemd", "threatcrushd.service");
44878
- if (!(0, import_node_fs39.existsSync)(templatePath)) {
45267
+ const templatePath = (0, import_node_path30.join)(__dirname, "systemd", "threatcrushd.service");
45268
+ if (!(0, import_node_fs40.existsSync)(templatePath)) {
44879
45269
  throw new Error(`systemd unit template not found at ${templatePath}`);
44880
45270
  }
44881
- return (0, import_node_fs39.readFileSync)(templatePath, "utf-8");
45271
+ return (0, import_node_fs40.readFileSync)(templatePath, "utf-8");
44882
45272
  }
44883
45273
  function stableBinPath(binPath) {
44884
45274
  const stable = binPath.replace(/\/\.pnpm\/[^/]+\/node_modules\//, "/node_modules/");
44885
45275
  if (stable === binPath) return binPath;
44886
- return (0, import_node_fs39.existsSync)(stable) ? stable : binPath;
45276
+ return (0, import_node_fs40.existsSync)(stable) ? stable : binPath;
44887
45277
  }
44888
45278
  function resolveBinPath() {
44889
45279
  const arg = process.argv[1];
44890
- if (arg && (0, import_node_fs39.existsSync)(arg)) return stableBinPath(arg);
45280
+ if (arg && (0, import_node_fs40.existsSync)(arg)) return stableBinPath(arg);
44891
45281
  try {
44892
- return (0, import_node_child_process15.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
45282
+ return (0, import_node_child_process16.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
44893
45283
  } catch {
44894
45284
  return "threatcrush";
44895
45285
  }
@@ -44897,11 +45287,11 @@ function resolveBinPath() {
44897
45287
  function stableNodePath(execPath) {
44898
45288
  const stable = execPath.replace(/(\/installs\/node\/)[^/]+\//, "$1latest/");
44899
45289
  if (stable === execPath) return execPath;
44900
- return (0, import_node_fs39.existsSync)(stable) ? stable : execPath;
45290
+ return (0, import_node_fs40.existsSync)(stable) ? stable : execPath;
44901
45291
  }
44902
45292
  function looksLikeNodeScript(path) {
44903
45293
  try {
44904
- const head = (0, import_node_fs39.readFileSync)(path, "utf-8").slice(0, 120);
45294
+ const head = (0, import_node_fs40.readFileSync)(path, "utf-8").slice(0, 120);
44905
45295
  return /^#!.*\bnode\b/.test(head);
44906
45296
  } catch {
44907
45297
  return false;
@@ -44928,20 +45318,20 @@ function isRoot3() {
44928
45318
  return typeof process.getuid === "function" && process.getuid() === 0;
44929
45319
  }
44930
45320
  function reexecWithSudo(args) {
44931
- if ((0, import_node_child_process15.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
45321
+ if ((0, import_node_child_process16.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
44932
45322
  console.log(source_default.dim(" This needs root \u2014 sudo will ask for your password.\n"));
44933
45323
  const bin = resolveBinPath();
44934
45324
  const argv = looksLikeNodeScript(bin) ? [stableNodePath(process.execPath), bin, ...args] : [bin, ...args];
44935
- const result = (0, import_node_child_process15.spawnSync)("sudo", argv, { stdio: "inherit" });
45325
+ const result = (0, import_node_child_process16.spawnSync)("sudo", argv, { stdio: "inherit" });
44936
45326
  return result.status === 0;
44937
45327
  }
44938
45328
  function callerHome() {
44939
45329
  const user = process.env.SUDO_USER;
44940
45330
  if (!user) return null;
44941
45331
  try {
44942
- const line2 = (0, import_node_child_process15.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
45332
+ const line2 = (0, import_node_child_process16.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
44943
45333
  const home = line2.split(":")[5];
44944
- return home && (0, import_node_fs39.existsSync)(home) ? home : null;
45334
+ return home && (0, import_node_fs40.existsSync)(home) ? home : null;
44945
45335
  } catch {
44946
45336
  return null;
44947
45337
  }
@@ -44949,13 +45339,13 @@ function callerHome() {
44949
45339
  function stopUserModeDaemon() {
44950
45340
  const home = callerHome();
44951
45341
  if (!home) return;
44952
- const runDir = (0, import_node_path29.join)(home, ".threatcrush", "run");
44953
- const pidFile = (0, import_node_path29.join)(runDir, "threatcrushd.pid");
44954
- const socket = (0, import_node_path29.join)(runDir, "threatcrushd.sock");
44955
- if (!(0, import_node_fs39.existsSync)(pidFile) && !(0, import_node_fs39.existsSync)(socket)) return;
45342
+ const runDir = (0, import_node_path30.join)(home, ".threatcrush", "run");
45343
+ const pidFile = (0, import_node_path30.join)(runDir, "threatcrushd.pid");
45344
+ const socket = (0, import_node_path30.join)(runDir, "threatcrushd.sock");
45345
+ if (!(0, import_node_fs40.existsSync)(pidFile) && !(0, import_node_fs40.existsSync)(socket)) return;
44956
45346
  let pid = null;
44957
45347
  try {
44958
- pid = Number.parseInt((0, import_node_fs39.readFileSync)(pidFile, "utf-8").trim(), 10);
45348
+ pid = Number.parseInt((0, import_node_fs40.readFileSync)(pidFile, "utf-8").trim(), 10);
44959
45349
  } catch {
44960
45350
  pid = null;
44961
45351
  }
@@ -44968,13 +45358,13 @@ function stopUserModeDaemon() {
44968
45358
  }
44969
45359
  for (const path of [socket, pidFile]) {
44970
45360
  try {
44971
- if ((0, import_node_fs39.existsSync)(path)) (0, import_node_fs39.rmSync)(path);
45361
+ if ((0, import_node_fs40.existsSync)(path)) (0, import_node_fs40.rmSync)(path);
44972
45362
  } catch {
44973
45363
  }
44974
45364
  }
44975
45365
  }
44976
45366
  function unitIsActive() {
44977
- const result = (0, import_node_child_process15.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
45367
+ const result = (0, import_node_child_process16.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
44978
45368
  return result.status === 0;
44979
45369
  }
44980
45370
  async function installServiceCommand() {
@@ -44985,8 +45375,8 @@ async function installServiceCommand() {
44985
45375
  return;
44986
45376
  }
44987
45377
  const noSystemd = systemdUnavailableReason({
44988
- hasSystemctl: (0, import_node_child_process15.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
44989
- booted: (0, import_node_fs39.existsSync)("/run/systemd/system")
45378
+ hasSystemctl: (0, import_node_child_process16.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
45379
+ booted: (0, import_node_fs40.existsSync)("/run/systemd/system")
44990
45380
  });
44991
45381
  if (noSystemd) {
44992
45382
  console.log(source_default.red(` \u2717 systemd isn't available here: ${noSystemd}.`));
@@ -45008,7 +45398,7 @@ async function installServiceCommand() {
45008
45398
  const isNodeScript = looksLikeNodeScript(binPath);
45009
45399
  let nodePath = stableNodePath(process.execPath);
45010
45400
  if (isNodeScript && nodeVersionDir(binPath)) {
45011
- binPath = (0, import_node_fs39.realpathSync)(binPath);
45401
+ binPath = (0, import_node_fs40.realpathSync)(binPath);
45012
45402
  nodePath = process.execPath;
45013
45403
  }
45014
45404
  if (isNodeScript) {
@@ -45021,9 +45411,9 @@ async function installServiceCommand() {
45021
45411
  }
45022
45412
  }
45023
45413
  const exec = execStartCommand(binPath, nodePath, isNodeScript);
45024
- const configDir = (0, import_node_path29.join)((0, import_node_os12.homedir)(), ".threatcrush");
45414
+ const configDir = (0, import_node_path30.join)((0, import_node_os12.homedir)(), ".threatcrush");
45025
45415
  const unit = renderUnit(resolveTemplate(), { exec, binPath, configDir });
45026
- (0, import_node_fs39.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
45416
+ (0, import_node_fs40.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
45027
45417
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
45028
45418
  console.log(source_default.dim(` ExecStart=${exec}`));
45029
45419
  const nodeDir = nodeVersionDir(nodePath);
@@ -45038,8 +45428,8 @@ async function installServiceCommand() {
45038
45428
  installLogrotate();
45039
45429
  stopUserModeDaemon();
45040
45430
  try {
45041
- (0, import_node_child_process15.execSync)("systemctl daemon-reload", { stdio: "inherit" });
45042
- (0, import_node_child_process15.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
45431
+ (0, import_node_child_process16.execSync)("systemctl daemon-reload", { stdio: "inherit" });
45432
+ (0, import_node_child_process16.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
45043
45433
  } catch (err) {
45044
45434
  console.log(source_default.yellow(` ! systemctl error: ${err.message}`));
45045
45435
  console.log(source_default.dim(` Logs: journalctl -u ${DAEMON_UNIT_NAME} -n 50`));
@@ -45076,9 +45466,9 @@ function renderLogrotate(logDir = "/var/log/threatcrush") {
45076
45466
  ].join("\n");
45077
45467
  }
45078
45468
  function installLogrotate() {
45079
- if (!(0, import_node_fs39.existsSync)((0, import_node_path29.dirname)(LOGROTATE_PATH))) return;
45469
+ if (!(0, import_node_fs40.existsSync)((0, import_node_path30.dirname)(LOGROTATE_PATH))) return;
45080
45470
  try {
45081
- (0, import_node_fs39.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
45471
+ (0, import_node_fs40.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
45082
45472
  console.log(source_default.green(` \u2713 Log rotation: ${LOGROTATE_PATH} (daily or 200M, keeps 7)`));
45083
45473
  } catch (err) {
45084
45474
  console.log(source_default.yellow(` ! Could not install log rotation: ${err.message}`));
@@ -45100,20 +45490,20 @@ function ensureSystemDirs(configDir) {
45100
45490
  ];
45101
45491
  let admGid2 = null;
45102
45492
  try {
45103
- admGid2 = (0, import_node_fs39.statSync)("/var/log/auth.log").gid;
45493
+ admGid2 = (0, import_node_fs40.statSync)("/var/log/auth.log").gid;
45104
45494
  } catch {
45105
45495
  }
45106
45496
  for (const { path, groupWritable, sticky } of dirs) {
45107
45497
  try {
45108
- (0, import_node_fs39.mkdirSync)(path, { recursive: true });
45498
+ (0, import_node_fs40.mkdirSync)(path, { recursive: true });
45109
45499
  } catch {
45110
45500
  }
45111
45501
  try {
45112
45502
  if (groupWritable && admGid2 !== null) {
45113
- (0, import_node_fs39.chmodSync)(path, sticky ? 1533 : 509);
45114
- (0, import_node_child_process15.execSync)(`chgrp adm ${path}`, { stdio: "ignore" });
45503
+ (0, import_node_fs40.chmodSync)(path, sticky ? 1533 : 509);
45504
+ (0, import_node_child_process16.execSync)(`chgrp adm ${path}`, { stdio: "ignore" });
45115
45505
  } else {
45116
- (0, import_node_fs39.chmodSync)(path, 493);
45506
+ (0, import_node_fs40.chmodSync)(path, 493);
45117
45507
  }
45118
45508
  } catch {
45119
45509
  }
@@ -45133,29 +45523,29 @@ async function uninstallServiceCommand() {
45133
45523
  return;
45134
45524
  }
45135
45525
  try {
45136
- (0, import_node_child_process15.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
45526
+ (0, import_node_child_process16.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
45137
45527
  } catch {
45138
45528
  }
45139
45529
  try {
45140
- (0, import_node_child_process15.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
45530
+ (0, import_node_child_process16.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
45141
45531
  } catch {
45142
45532
  }
45143
45533
  try {
45144
- if ((0, import_node_fs39.existsSync)(UNIT_PATH)) {
45145
- (0, import_node_child_process15.execSync)(`rm -f ${UNIT_PATH}`);
45534
+ if ((0, import_node_fs40.existsSync)(UNIT_PATH)) {
45535
+ (0, import_node_child_process16.execSync)(`rm -f ${UNIT_PATH}`);
45146
45536
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
45147
45537
  }
45148
45538
  } catch {
45149
45539
  }
45150
45540
  try {
45151
- (0, import_node_child_process15.execSync)("systemctl daemon-reload", { stdio: "inherit" });
45541
+ (0, import_node_child_process16.execSync)("systemctl daemon-reload", { stdio: "inherit" });
45152
45542
  } catch {
45153
45543
  }
45154
45544
  console.log(source_default.green(" \u2713 threatcrushd service removed."));
45155
45545
  }
45156
45546
 
45157
45547
  // src/commands/save.ts
45158
- var import_node_fs40 = require("fs");
45548
+ var import_node_fs41 = require("fs");
45159
45549
  var import_toml5 = __toESM(require_toml());
45160
45550
  init_cli_config();
45161
45551
  init_paths();
@@ -45194,9 +45584,9 @@ async function saveCommand(opts = {}) {
45194
45584
  }
45195
45585
  const path = opts.config ?? PATHS.configFile;
45196
45586
  let config = {};
45197
- if ((0, import_node_fs40.existsSync)(path)) {
45587
+ if ((0, import_node_fs41.existsSync)(path)) {
45198
45588
  try {
45199
- config = import_toml5.default.parse((0, import_node_fs40.readFileSync)(path, "utf-8"));
45589
+ config = import_toml5.default.parse((0, import_node_fs41.readFileSync)(path, "utf-8"));
45200
45590
  } catch (err) {
45201
45591
  console.log(source_default.red(` \u2717 ${path} is not valid TOML: ${err.message}
45202
45592
  `));
@@ -45309,8 +45699,8 @@ function welcomeCommand() {
45309
45699
  }
45310
45700
 
45311
45701
  // src/commands/properties.ts
45312
- var import_node_fs41 = require("fs");
45313
- var import_node_path30 = require("path");
45702
+ var import_node_fs42 = require("fs");
45703
+ var import_node_path31 = require("path");
45314
45704
  var import_node_readline4 = __toESM(require("readline"));
45315
45705
  init_cli_config();
45316
45706
  var API_URL5 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
@@ -45640,8 +46030,8 @@ async function propertiesRunsCommand(opts) {
45640
46030
  }
45641
46031
  }
45642
46032
  function parseImportFile(path) {
45643
- const ext = (0, import_node_path30.extname)(path).toLowerCase();
45644
- const raw = (0, import_node_fs41.readFileSync)(path, "utf-8");
46033
+ const ext = (0, import_node_path31.extname)(path).toLowerCase();
46034
+ const raw = (0, import_node_fs42.readFileSync)(path, "utf-8");
45645
46035
  if (ext === ".json") {
45646
46036
  const parsed = JSON.parse(raw);
45647
46037
  if (!Array.isArray(parsed)) throw new Error("JSON must be an array of objects");
@@ -45836,19 +46226,19 @@ async function rulesCommand(opts) {
45836
46226
  }
45837
46227
 
45838
46228
  // src/commands/harden.ts
45839
- var import_node_fs42 = require("fs");
45840
- var import_node_child_process16 = require("child_process");
46229
+ var import_node_fs43 = require("fs");
46230
+ var import_node_child_process17 = require("child_process");
45841
46231
  init_cli_config();
45842
46232
  function tryExec(cmd) {
45843
46233
  try {
45844
- return (0, import_node_child_process16.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
46234
+ return (0, import_node_child_process17.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
45845
46235
  } catch {
45846
46236
  return null;
45847
46237
  }
45848
46238
  }
45849
46239
  function tryRead(path) {
45850
46240
  try {
45851
- return (0, import_node_fs42.readFileSync)(path, "utf-8");
46241
+ return (0, import_node_fs43.readFileSync)(path, "utf-8");
45852
46242
  } catch {
45853
46243
  return null;
45854
46244
  }
@@ -45952,8 +46342,8 @@ function checkSshWeakConfig() {
45952
46342
  };
45953
46343
  }
45954
46344
  function checkAutoUpdates() {
45955
- const unattended = (0, import_node_fs42.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs42.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
45956
- const dnfAuto = (0, import_node_fs42.existsSync)("/etc/dnf/automatic.conf");
46345
+ const unattended = (0, import_node_fs43.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs43.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
46346
+ const dnfAuto = (0, import_node_fs43.existsSync)("/etc/dnf/automatic.conf");
45957
46347
  if (unattended || dnfAuto) {
45958
46348
  return {
45959
46349
  key: "auto-updates",
@@ -46079,7 +46469,7 @@ function checkFail2ban() {
46079
46469
  explanation: "fail2ban is installed and running."
46080
46470
  };
46081
46471
  }
46082
- if ((0, import_node_fs42.existsSync)("/etc/fail2ban/fail2ban.conf")) {
46472
+ if ((0, import_node_fs43.existsSync)("/etc/fail2ban/fail2ban.conf")) {
46083
46473
  return {
46084
46474
  key: checkKey,
46085
46475
  status: "warn",
@@ -46265,9 +46655,9 @@ async function hardenCommand(opts) {
46265
46655
  }
46266
46656
 
46267
46657
  // src/core/patches/index.ts
46268
- var import_node_fs43 = require("fs");
46269
- var import_node_path31 = require("path");
46270
- var import_node_child_process17 = require("child_process");
46658
+ var import_node_fs44 = require("fs");
46659
+ var import_node_path32 = require("path");
46660
+ var import_node_child_process18 = require("child_process");
46271
46661
  var import_node_util2 = require("util");
46272
46662
 
46273
46663
  // src/core/patches/dpkg-version.ts
@@ -46327,7 +46717,7 @@ var STALE_AFTER_MS = 2 * 864e5;
46327
46717
  var SEVERITIES2 = ["info", "low", "medium", "high", "critical"];
46328
46718
  var RANK = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
46329
46719
  var defaultExec = async (file, args) => {
46330
- const { stdout } = await (0, import_node_util2.promisify)(import_node_child_process17.execFile)(file, args, {
46720
+ const { stdout } = await (0, import_node_util2.promisify)(import_node_child_process18.execFile)(file, args, {
46331
46721
  timeout: 12e4,
46332
46722
  maxBuffer: 32 * 1024 * 1024,
46333
46723
  env: { ...process.env, LC_ALL: "C" }
@@ -46426,9 +46816,9 @@ async function osvRecords(doFetch, ecosystem, source, version) {
46426
46816
  function newestReleaseMtime(dir) {
46427
46817
  try {
46428
46818
  let newest = 0;
46429
- for (const name of (0, import_node_fs43.readdirSync)(dir)) {
46819
+ for (const name of (0, import_node_fs44.readdirSync)(dir)) {
46430
46820
  if (!/Release$/.test(name)) continue;
46431
- newest = Math.max(newest, (0, import_node_fs43.statSync)((0, import_node_path31.join)(dir, name)).mtimeMs);
46821
+ newest = Math.max(newest, (0, import_node_fs44.statSync)((0, import_node_path32.join)(dir, name)).mtimeMs);
46432
46822
  }
46433
46823
  return newest > 0 ? new Date(newest) : null;
46434
46824
  } catch {
@@ -46445,7 +46835,7 @@ async function checkPatches(opts = {}) {
46445
46835
  let osText = opts.osRelease;
46446
46836
  if (osText === void 0) {
46447
46837
  try {
46448
- osText = (0, import_node_fs43.readFileSync)("/etc/os-release", "utf-8");
46838
+ osText = (0, import_node_fs44.readFileSync)("/etc/os-release", "utf-8");
46449
46839
  } catch {
46450
46840
  osText = "";
46451
46841
  }
@@ -46672,15 +47062,15 @@ async function patchesCommand(opts) {
46672
47062
 
46673
47063
  // src/commands/feeds.ts
46674
47064
  var import_node_net12 = require("net");
46675
- var import_node_path32 = require("path");
47065
+ var import_node_path33 = require("path");
46676
47066
  init_paths();
46677
47067
  async function loadSet() {
46678
47068
  for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
46679
- const path = (0, import_node_path32.join)(dir, "threat-feeds.json");
47069
+ const path = (0, import_node_path33.join)(dir, "threat-feeds.json");
46680
47070
  const set = readFeedCache(path);
46681
47071
  if (set) return { set, from: path };
46682
47072
  }
46683
- const settings = threatFeedSettings(loadConfig((0, import_node_path32.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
47073
+ const settings = threatFeedSettings(loadConfig((0, import_node_path33.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
46684
47074
  return { set: await fetchFeeds(settings), from: "abuse.ch (live; no daemon cache readable)" };
46685
47075
  }
46686
47076
  async function feedsCommand(action, value, opts) {
@@ -46719,6 +47109,73 @@ async function feedsCommand(action, value, opts) {
46719
47109
  console.log(source_default.gray("\n Blocking egress needs [threat_feeds] block = true and [remediation] in enforce mode."));
46720
47110
  }
46721
47111
 
47112
+ // src/commands/privileged.ts
47113
+ var import_node_fs45 = require("fs");
47114
+ init_paths();
47115
+ var SEV2 = {
47116
+ critical: source_default.red.bold,
47117
+ high: source_default.red,
47118
+ medium: source_default.yellow,
47119
+ low: source_default.cyan,
47120
+ info: source_default.gray
47121
+ };
47122
+ async function privilegedCommand(opts) {
47123
+ const snapshot = takeSnapshot({
47124
+ readFile: (p) => {
47125
+ try {
47126
+ return (0, import_node_fs45.readFileSync)(p, "utf-8");
47127
+ } catch {
47128
+ return null;
47129
+ }
47130
+ },
47131
+ readDir: (p) => {
47132
+ try {
47133
+ return (0, import_node_fs45.readdirSync)(p);
47134
+ } catch {
47135
+ return null;
47136
+ }
47137
+ },
47138
+ exists: (p) => (0, import_node_fs45.existsSync)(p)
47139
+ });
47140
+ let events = [];
47141
+ let ledgerNote = "";
47142
+ try {
47143
+ initStateDB(PATHS.stateDb);
47144
+ events = getModuleEvents("privileged-access", Number(opts.limit) || 25);
47145
+ } catch {
47146
+ ledgerNote = `the daemon's state database (${PATHS.stateDb}) is not readable here`;
47147
+ }
47148
+ if (opts.json) {
47149
+ console.log(JSON.stringify({ snapshot, events }, null, 2));
47150
+ return;
47151
+ }
47152
+ console.log(` ${source_default.white.bold("uid 0 accounts:")} ${snapshot.uid0.join(", ") || "\u2014"}`);
47153
+ for (const [group, members] of Object.entries(snapshot.admin_groups)) {
47154
+ console.log(` ${source_default.white.bold(`${group} group:`)} ${members.join(", ") || "\u2014"}`);
47155
+ }
47156
+ const rules = Object.entries(snapshot.sudoers).filter(([, r]) => r.length > 0);
47157
+ console.log(` ${source_default.white.bold("sudoers:")} ${rules.length} file(s) with rules`);
47158
+ for (const [path, r] of rules) {
47159
+ for (const rule of r.filter((x) => !/^Defaults\b/.test(x))) console.log(source_default.gray(` ${path.replace("/etc/", "")}: ${rule}`));
47160
+ }
47161
+ console.log(` ${source_default.white.bold("authorized keys:")}`);
47162
+ for (const [user, keys] of Object.entries(snapshot.keys)) {
47163
+ for (const [fp, k] of Object.entries(keys)) console.log(` ${user.padEnd(12)} ${k.type.padEnd(20)} ${fp} ${source_default.gray(k.comment)}`);
47164
+ }
47165
+ if (snapshot.unreadable.length) {
47166
+ console.log(source_default.yellow(` ! not readable as this user: ${snapshot.unreadable.join(", ")} (run with sudo for the full picture)`));
47167
+ }
47168
+ console.log(`
47169
+ ${source_default.white.bold("Recent changes and sudo commands")}`);
47170
+ if (ledgerNote) console.log(source_default.gray(` ${ledgerNote}`));
47171
+ else if (events.length === 0) console.log(source_default.gray(" none recorded yet (the daemon records them from its first run on)"));
47172
+ for (const e of events) {
47173
+ const at = new Date(e.timestamp).toISOString().replace("T", " ").slice(0, 19);
47174
+ console.log(` ${source_default.gray(at)} ${(SEV2[e.severity] ?? source_default.white)(e.severity.padEnd(8))} ${e.message}`);
47175
+ }
47176
+ console.log();
47177
+ }
47178
+
46722
47179
  // src/commands/firewall.ts
46723
47180
  init_ipc_client();
46724
47181
  init_paths();
@@ -46863,11 +47320,11 @@ async function allowlistCommand(opts) {
46863
47320
  init_paths();
46864
47321
 
46865
47322
  // src/upgrade.ts
46866
- var import_node_child_process18 = require("child_process");
47323
+ var import_node_child_process19 = require("child_process");
46867
47324
  var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
46868
47325
  var defaultRunner = (cmd) => {
46869
47326
  try {
46870
- return (0, import_node_child_process18.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
47327
+ return (0, import_node_child_process19.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
46871
47328
  } catch {
46872
47329
  return null;
46873
47330
  }
@@ -46982,25 +47439,25 @@ ${source_default.dim(" C R U S H")}
46982
47439
  var API_URL6 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
46983
47440
  var PKG_NAME2 = "@profullstack/threatcrush";
46984
47441
  var DESKTOP_PKG_NAME = "@profullstack/threatcrush-desktop";
46985
- var INSTALL_CONFIG_PATH = (0, import_node_path33.join)((0, import_node_os13.homedir)(), ".threatcrush", "install.json");
47442
+ var INSTALL_CONFIG_PATH = (0, import_node_path34.join)((0, import_node_os13.homedir)(), ".threatcrush", "install.json");
46986
47443
  function detectPackageManager() {
46987
47444
  try {
46988
- const npmGlobal = (0, import_node_child_process19.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
47445
+ const npmGlobal = (0, import_node_child_process20.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
46989
47446
  if (npmGlobal.includes(PKG_NAME2)) return "npm";
46990
47447
  } catch {
46991
47448
  }
46992
47449
  try {
46993
- (0, import_node_child_process19.execSync)("pnpm --version", { stdio: "pipe" });
47450
+ (0, import_node_child_process20.execSync)("pnpm --version", { stdio: "pipe" });
46994
47451
  return "pnpm";
46995
47452
  } catch {
46996
47453
  }
46997
47454
  try {
46998
- (0, import_node_child_process19.execSync)("yarn --version", { stdio: "pipe" });
47455
+ (0, import_node_child_process20.execSync)("yarn --version", { stdio: "pipe" });
46999
47456
  return "yarn";
47000
47457
  } catch {
47001
47458
  }
47002
47459
  try {
47003
- (0, import_node_child_process19.execSync)("bun --version", { stdio: "pipe" });
47460
+ (0, import_node_child_process20.execSync)("bun --version", { stdio: "pipe" });
47004
47461
  return "bun";
47005
47462
  } catch {
47006
47463
  }
@@ -47008,14 +47465,14 @@ function detectPackageManager() {
47008
47465
  }
47009
47466
  function readInstallConfig() {
47010
47467
  try {
47011
- return JSON.parse((0, import_node_fs44.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
47468
+ return JSON.parse((0, import_node_fs46.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
47012
47469
  } catch {
47013
47470
  return {};
47014
47471
  }
47015
47472
  }
47016
47473
  function packageLooksInstalled(pm, pkgName) {
47017
47474
  try {
47018
- const output = (0, import_node_child_process19.execSync)(globalListCommand(pm, pkgName), {
47475
+ const output = (0, import_node_child_process20.execSync)(globalListCommand(pm, pkgName), {
47019
47476
  encoding: "utf-8",
47020
47477
  stdio: ["pipe", "pipe", "pipe"]
47021
47478
  });
@@ -47118,14 +47575,14 @@ async function promoteUnprivilegedDaemon() {
47118
47575
  function restartSystemdDaemon() {
47119
47576
  const asRoot = typeof process.getuid === "function" && process.getuid() === 0;
47120
47577
  const argv = asRoot ? ["systemctl", "restart", DAEMON_UNIT] : ["sudo", "systemctl", "restart", DAEMON_UNIT];
47121
- if (!asRoot && (0, import_node_child_process19.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
47578
+ if (!asRoot && (0, import_node_child_process20.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
47122
47579
  const [cmd, ...args] = argv;
47123
- if ((0, import_node_child_process19.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
47124
- return (0, import_node_child_process19.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
47580
+ if ((0, import_node_child_process20.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
47581
+ return (0, import_node_child_process20.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
47125
47582
  }
47126
47583
  function execQuiet(cmd) {
47127
47584
  try {
47128
- return (0, import_node_child_process19.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
47585
+ return (0, import_node_child_process20.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
47129
47586
  } catch {
47130
47587
  return null;
47131
47588
  }
@@ -47281,6 +47738,9 @@ program2.command("patches").description("List OS packages with a security update
47281
47738
  program2.command("feeds [action] [value]").description("Show the abuse.ch C2/malware list the daemon matches; `feeds check <ip|domain>` looks one up (exit 1 when listed)").option("--json", "Output as JSON").action(async (action, value, opts) => {
47282
47739
  await feedsCommand(action, value, opts);
47283
47740
  });
47741
+ program2.command("privileged").description("Who can become root here (uid 0, sudo groups, sudoers, SSH keys) and the daemon's record of changes and sudo commands").option("--json", "Output as JSON").option("--limit <n>", "How many recent events to show", "25").action(async (opts) => {
47742
+ await privilegedCommand(opts);
47743
+ });
47284
47744
  program2.command("block").description("Block an IP address via the firewall").argument("<ip>", "IP address to block").option("--ttl <duration>", "Block duration (e.g. 1h, 30m, 1d)").action(async (ip, opts) => {
47285
47745
  await blockCommand(ip, opts);
47286
47746
  });
@@ -47317,7 +47777,7 @@ program2.command("uninstall-service").description("Remove the threatcrushd syste
47317
47777
  program2.command("logs").description("Tail daemon logs").action(async () => {
47318
47778
  console.log(LOGO2);
47319
47779
  const logPath = PATHS.logFile;
47320
- if (!(0, import_node_fs44.existsSync)(logPath)) {
47780
+ if (!(0, import_node_fs46.existsSync)(logPath)) {
47321
47781
  console.log(source_default.yellow(` No log file found at ${logPath}`));
47322
47782
  console.log(source_default.dim(" Start the daemon first with `threatcrush start`\n"));
47323
47783
  return;
@@ -47325,7 +47785,7 @@ program2.command("logs").description("Tail daemon logs").action(async () => {
47325
47785
  console.log(source_default.green(` Tailing ${logPath}...
47326
47786
  `));
47327
47787
  console.log(source_default.gray(" Press Ctrl+C to stop\n"));
47328
- (0, import_node_child_process19.execSync)(`tail -f ${logPath}`, { stdio: "inherit" });
47788
+ (0, import_node_child_process20.execSync)(`tail -f ${logPath}`, { stdio: "inherit" });
47329
47789
  });
47330
47790
  program2.command("update").description("Update ThreatCrush CLI and installed bundle").option("--cli", "Update CLI only").option("--modules", "Update modules only").option("--desktop", "Update desktop app too").action(async (opts) => {
47331
47791
  console.log(LOGO2);
@@ -47337,7 +47797,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
47337
47797
  for (const cmd of commands2) {
47338
47798
  console.log(source_default.green(` \u2192 ${cmd}
47339
47799
  `));
47340
- (0, import_node_child_process19.execSync)(cmd, { stdio: "inherit" });
47800
+ (0, import_node_child_process20.execSync)(cmd, { stdio: "inherit" });
47341
47801
  }
47342
47802
  console.log(source_default.green("\n \u2713 Modules updated successfully!\n"));
47343
47803
  await reportIfStillStale();
@@ -47362,7 +47822,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
47362
47822
  for (const cmd of commands) {
47363
47823
  console.log(source_default.green(` \u2192 ${cmd}
47364
47824
  `));
47365
- (0, import_node_child_process19.execSync)(cmd, { stdio: "inherit" });
47825
+ (0, import_node_child_process20.execSync)(cmd, { stdio: "inherit" });
47366
47826
  }
47367
47827
  console.log(source_default.green("\n \u2713 ThreatCrush updated successfully!\n"));
47368
47828
  if (installMode === "desktop") {
@@ -47413,7 +47873,7 @@ program2.command("remove").description("Uninstall ThreatCrush and the installed
47413
47873
  for (const cmd of commands) {
47414
47874
  console.log(source_default.green(` \u2192 ${cmd}
47415
47875
  `));
47416
- (0, import_node_child_process19.execSync)(cmd, { stdio: "inherit" });
47876
+ (0, import_node_child_process20.execSync)(cmd, { stdio: "inherit" });
47417
47877
  }
47418
47878
  console.log(source_default.green("\n \u2713 ThreatCrush has been uninstalled.\n"));
47419
47879
  console.log(source_default.dim(" We're sorry to see you go! \u{1F44B}\n"));
@@ -47490,10 +47950,10 @@ storeCmd.command("search <query>").description("Search for modules in the store"
47490
47950
  });
47491
47951
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
47492
47952
  console.log(LOGO2);
47493
- const configPath = (0, import_node_path33.join)((0, import_node_os13.homedir)(), ".threatcrush", "config.json");
47953
+ const configPath = (0, import_node_path34.join)((0, import_node_os13.homedir)(), ".threatcrush", "config.json");
47494
47954
  let email = "";
47495
47955
  try {
47496
- const config = JSON.parse((0, import_node_fs44.readFileSync)(configPath, "utf-8"));
47956
+ const config = JSON.parse((0, import_node_fs46.readFileSync)(configPath, "utf-8"));
47497
47957
  email = config.email || "";
47498
47958
  } catch {
47499
47959
  }
@@ -47510,9 +47970,9 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
47510
47970
  return;
47511
47971
  }
47512
47972
  try {
47513
- const dir = (0, import_node_path33.join)((0, import_node_os13.homedir)(), ".threatcrush");
47514
- if (!(0, import_node_fs44.existsSync)(dir)) (0, import_node_fs44.mkdirSync)(dir, { recursive: true });
47515
- (0, import_node_fs44.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
47973
+ const dir = (0, import_node_path34.join)((0, import_node_os13.homedir)(), ".threatcrush");
47974
+ if (!(0, import_node_fs46.existsSync)(dir)) (0, import_node_fs46.mkdirSync)(dir, { recursive: true });
47975
+ (0, import_node_fs46.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
47516
47976
  console.log(source_default.dim(` Saved email to ${configPath}`));
47517
47977
  } catch {
47518
47978
  }