@astrofoundry/pi-astro 0.36.0 → 0.37.0

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.
@@ -45,6 +45,9 @@ ${Object.entries(OBS_COMMANDS)
45
45
  .map(([name, c]) => ` ${name.padEnd(14)} ${c.help}`)
46
46
  .join("\n")}
47
47
  wazuh-vulns <days> [agent] Wazuh vulnerability alerts: package, installed version, fix condition, score, status (built from wazuh-alerts)
48
+ wazuh-events <minutes> <minLevel> every Wazuh alert of the last N minutes at or above a level, oldest first, without
49
+ vulnerability findings: id, rule, agent, file path, change and SHA-256 (built from wazuh-alerts)
50
+ wazuh-vuln-events <days> every vulnerability finding of the last N days, oldest first, compact (built from wazuh-alerts)
48
51
 
49
52
  Read-only. Bans, unbans, and rule changes are out of scope; describe them for the operator.`;
50
53
 
@@ -117,6 +120,44 @@ export interface AlertSummary {
117
120
  topIps: { ip: string; count: number; last: string; as?: string }[];
118
121
  scenarios: { scenario: string; count: number }[];
119
122
  latest: CompactAlert[];
123
+ /** Alerts per original ban length (`4 h`, `24 h`, `7 days`): time left plus time since the alert, to the nearest hour. */
124
+ bans: { length: string; hours: number; count: number }[];
125
+ /** Alerts banned for longer than CrowdSec's default 4 hours, newest first (at most 20): repeat offenders our profiles escalated. */
126
+ escalated: { at: string; ip: string; ban: string; country?: string; as?: string }[];
127
+ countries: { country: string; count: number }[];
128
+ networks: { as: string; count: number }[];
129
+ }
130
+
131
+ /** Go duration as cscli prints it (`161h53m43s`, `-29m44s`, `500ms`), in milliseconds; null when it does not parse. */
132
+ export function parseGoDuration(value: string): number | null {
133
+ const m = /^(-?)((?:\d+(?:\.\d+)?(?:h|ms|m|s|us|µs|ns))+)$/.exec(value.trim());
134
+ if (!m) return null;
135
+ const unit: Record<string, number> = { h: 3_600_000, m: 60_000, s: 1000, ms: 1, us: 0.001, µs: 0.001, ns: 0.000_001 };
136
+ let total = 0;
137
+ for (const part of m[2].matchAll(/(\d+(?:\.\d+)?)(h|ms|m|s|us|µs|ns)/g)) total += Number(part[1]) * unit[part[2]];
138
+ return m[1] === "-" ? -total : total;
139
+ }
140
+
141
+ export function banLength(hours: number): string {
142
+ return hours < 48 ? `${hours} h` : `${Math.round(hours / 24)} days`;
143
+ }
144
+
145
+ /** The ban's whole length in hours: what is left of it when cscli ran plus how long ago the alert was. */
146
+ function banHours(a: CrowdsecAlert, now: number): number | null {
147
+ const ban = (a.decisions ?? []).find((d) => d.type === "ban");
148
+ const left = ban?.duration === undefined ? null : parseGoDuration(ban.duration);
149
+ const created = Date.parse(a.created_at ?? "");
150
+ if (left === null || Number.isNaN(created)) return null;
151
+ return Math.max(0, Math.round((left + now - created) / 3_600_000));
152
+ }
153
+
154
+ function topCounts(values: (string | undefined)[], limit: number): { value: string; count: number }[] {
155
+ const counts = new Map<string, number>();
156
+ for (const v of values) if (v !== undefined) counts.set(v, (counts.get(v) ?? 0) + 1);
157
+ return [...counts.entries()]
158
+ .map(([value, count]) => ({ value, count }))
159
+ .sort((x, y) => y.count - x.count || x.value.localeCompare(y.value))
160
+ .slice(0, limit);
120
161
  }
121
162
 
122
163
  function parseJsonArray<T>(text: string, what: string): T[] {
@@ -144,8 +185,8 @@ function compactAlert(a: CrowdsecAlert): CompactAlert {
144
185
  };
145
186
  }
146
187
 
147
- /** Compacts `cscli alerts list -o json` to counts, per-day activity, repeat sources, scenarios, and the latest alerts. */
148
- export function summariseAlerts(text: string, days: number, ip?: string): AlertSummary {
188
+ /** Compacts `cscli alerts list -o json` to counts, per-day activity, repeat sources, scenarios, ban lengths, and the latest alerts. */
189
+ export function summariseAlerts(text: string, days: number, ip?: string, now = Date.now()): AlertSummary {
149
190
  const alerts = parseJsonArray<CrowdsecAlert>(text, "alerts").filter((a) => a.source?.ip !== undefined && (ip === undefined || a.source.ip === ip));
150
191
  const byIp = new Map<string, CrowdsecAlert[]>();
151
192
  const byDay = new Map<string, CrowdsecAlert[]>();
@@ -158,6 +199,9 @@ export function summariseAlerts(text: string, days: number, ip?: string): AlertS
158
199
  byScenario.set(a.scenario ?? "?", (byScenario.get(a.scenario ?? "?") ?? 0) + 1);
159
200
  }
160
201
  const sorted = [...alerts].sort((x, y) => (y.created_at ?? "").localeCompare(x.created_at ?? ""));
202
+ const hours = new Map(alerts.map((a) => [a, banHours(a, now)]));
203
+ const lengths = new Map<number, number>();
204
+ for (const h of hours.values()) if (h !== null) lengths.set(h, (lengths.get(h) ?? 0) + 1);
161
205
  return {
162
206
  days,
163
207
  ip,
@@ -176,6 +220,16 @@ export function summariseAlerts(text: string, days: number, ip?: string): AlertS
176
220
  .slice(0, 10),
177
221
  scenarios: [...byScenario.entries()].map(([scenario, count]) => ({ scenario, count })).sort((x, y) => y.count - x.count),
178
222
  latest: (ip === undefined ? sorted.slice(0, 20) : sorted).map(compactAlert),
223
+ bans: [...lengths.entries()].sort((x, y) => x[0] - y[0]).map(([h, count]) => ({ length: banLength(h), hours: h, count })),
224
+ escalated: sorted
225
+ .filter((a) => (hours.get(a) ?? 0) > 4)
226
+ .slice(0, 20)
227
+ .map((a) => {
228
+ const c = compactAlert(a);
229
+ return { at: c.at, ip: c.ip, ban: banLength(hours.get(a) ?? 0), ...(c.country ? { country: c.country } : {}), ...(c.as ? { as: c.as } : {}) };
230
+ }),
231
+ countries: topCounts(alerts.map((a) => a.source?.cn), 5).map(({ value, count }) => ({ country: value, count })),
232
+ networks: topCounts(alerts.map((a) => compactAlert(a).as), 5).map(({ value, count }) => ({ as: value, count })),
179
233
  };
180
234
  }
181
235
 
@@ -234,10 +288,12 @@ interface WazuhVulnerability {
234
288
  }
235
289
 
236
290
  interface WazuhAlert {
291
+ id?: string;
237
292
  timestamp?: string;
238
- rule?: { id?: string; level?: number; description?: string };
293
+ rule?: { id?: string; level?: number; description?: string; groups?: string[] };
239
294
  agent?: { name?: string };
240
295
  data?: { srcip?: string; vulnerability?: WazuhVulnerability };
296
+ syscheck?: { path?: string; event?: string; sha256_after?: string };
241
297
  full_log?: string;
242
298
  }
243
299
 
@@ -289,6 +345,105 @@ export interface WazuhSummary {
289
345
  latest: { timestamp: string; agent: string; rule: string; level: number; description: string; srcip?: string; log?: string }[];
290
346
  }
291
347
 
348
+ /** One Wazuh alert as the Discord bridge classifies it; `path`, `event`, and `sha256` come from file integrity monitoring. */
349
+ export interface WazuhEvent {
350
+ id: string;
351
+ timestamp: string;
352
+ agent: string;
353
+ rule: string;
354
+ level: number;
355
+ description: string;
356
+ groups: string[];
357
+ path?: string;
358
+ event?: string;
359
+ sha256?: string;
360
+ srcip?: string;
361
+ log?: string;
362
+ }
363
+
364
+ export interface WazuhEvents {
365
+ minutes: number;
366
+ minLevel: number;
367
+ count: number;
368
+ /** The oldest events left out beyond MAX_EVENTS. */
369
+ omitted: number;
370
+ events: WazuhEvent[];
371
+ }
372
+
373
+ const MAX_EVENTS = 1000;
374
+
375
+ /** Every alert line of the dump that parses, with a valid timestamp. */
376
+ function alertLines(text: string): { alert: WazuhAlert; time: number }[] {
377
+ const out: { alert: WazuhAlert; time: number }[] = [];
378
+ for (const line of text.split("\n")) {
379
+ const trimmed = line.trim();
380
+ if (trimmed.length === 0) continue;
381
+ let alert: WazuhAlert;
382
+ try {
383
+ alert = JSON.parse(trimmed) as WazuhAlert;
384
+ } catch {
385
+ continue;
386
+ }
387
+ const time = alert.timestamp === undefined ? Number.NaN : Date.parse(alert.timestamp);
388
+ if (!Number.isNaN(time)) out.push({ alert, time });
389
+ }
390
+ return out;
391
+ }
392
+
393
+ /** Non-vulnerability alerts of the last N minutes at or above a level, oldest first; the newest MAX_EVENTS when there are more. */
394
+ export function wazuhEvents(text: string, minutes: number, minLevel: number, now = Date.now()): WazuhEvents {
395
+ const cutoff = now - minutes * 60_000;
396
+ const seen = new Set<string>();
397
+ const events: WazuhEvent[] = [];
398
+ for (const { alert, time } of alertLines(text)) {
399
+ const level = alert.rule?.level ?? 0;
400
+ if (time < cutoff || level < minLevel || alert.data?.vulnerability !== undefined) continue;
401
+ const id = alert.id ?? `${alert.timestamp}|${alert.rule?.id}|${alert.agent?.name}`;
402
+ // The dump can hold a rotated file and the live file at midnight; the id keeps each alert once.
403
+ if (seen.has(id)) continue;
404
+ seen.add(id);
405
+ const s = alert.syscheck;
406
+ events.push({
407
+ id,
408
+ timestamp: alert.timestamp ?? "",
409
+ agent: alert.agent?.name ?? "?",
410
+ rule: alert.rule?.id ?? "?",
411
+ level,
412
+ description: alert.rule?.description ?? "",
413
+ groups: alert.rule?.groups ?? [],
414
+ ...(s?.path ? { path: s.path } : {}),
415
+ ...(s?.event ? { event: s.event } : {}),
416
+ ...(s?.sha256_after ? { sha256: s.sha256_after } : {}),
417
+ ...(alert.data?.srcip ? { srcip: alert.data.srcip } : {}),
418
+ ...(alert.full_log ? { log: alert.full_log.slice(0, 300) } : {}),
419
+ });
420
+ }
421
+ events.sort((x, y) => x.timestamp.localeCompare(y.timestamp));
422
+ const omitted = Math.max(0, events.length - MAX_EVENTS);
423
+ return { minutes, minLevel, count: events.length, omitted, events: events.slice(omitted) };
424
+ }
425
+
426
+ /** One vulnerability finding, compact enough to list every one of a week. */
427
+ export interface VulnEvent {
428
+ timestamp: string;
429
+ agent: string;
430
+ cve: string;
431
+ status: string;
432
+ package: string;
433
+ version: string;
434
+ severity: string;
435
+ score: number | null;
436
+ condition: string;
437
+ }
438
+
439
+ /** Every vulnerability finding of the last N days, oldest first. */
440
+ export function vulnEvents(text: string, days: number, now = Date.now()): { days: number; count: number; events: VulnEvent[] } {
441
+ const events = summariseVulnItems(text, days, null, now)
442
+ .map((i): VulnEvent => ({ timestamp: i.timestamp, agent: i.agent, cve: i.cve, status: i.status, package: i.package, version: i.version, severity: i.severity, score: i.score, condition: i.condition }))
443
+ .reverse();
444
+ return { days, count: events.length, events };
445
+ }
446
+
292
447
  /** Filters newline-delimited Wazuh alerts by age and level, grouped by rule and agent. */
293
448
  export function summariseWazuh(text: string, days: number, minLevel: number, now = Date.now()): WazuhSummary {
294
449
  const cutoff = now - days * 86_400_000;
@@ -341,21 +496,32 @@ export function summariseWazuh(text: string, days: number, minLevel: number, now
341
496
 
342
497
  /** Reads every alert line and keeps the vulnerability-detector ones, newest first, with the fields an operator needs to patch. */
343
498
  export function summariseVulns(text: string, days: number, agent: string | null, now = Date.now()): VulnerabilitySummary {
499
+ const items = summariseVulnItems(text, days, agent, now);
500
+ const latest = new Map<string, VulnerabilityItem>();
501
+ for (const item of items) {
502
+ const key = `${item.agent}|${item.package}|${item.version}|${item.cve}`;
503
+ if (!latest.has(key)) latest.set(key, item);
504
+ }
505
+ const open = [...latest.values()].filter((i) => i.status.toLowerCase() === "active");
506
+ return {
507
+ days,
508
+ agent,
509
+ count: items.length,
510
+ active: items.filter((i) => i.status.toLowerCase() === "active").length,
511
+ solved: items.filter((i) => i.status.toLowerCase() === "solved").length,
512
+ open: open.slice(0, 50),
513
+ openWithoutFixVersion: open.filter((i) => i.condition === "Package default status").length,
514
+ items: items.slice(0, 50),
515
+ };
516
+ }
517
+
518
+ /** Every vulnerability-detector alert of the window, newest first. */
519
+ function summariseVulnItems(text: string, days: number, agent: string | null, now: number): VulnerabilityItem[] {
344
520
  const cutoff = now - days * 86_400_000;
345
521
  const items: VulnerabilityItem[] = [];
346
- for (const line of text.split("\n")) {
347
- const trimmed = line.trim();
348
- if (trimmed.length === 0) continue;
349
- let parsed: WazuhAlert;
350
- try {
351
- parsed = JSON.parse(trimmed) as WazuhAlert;
352
- } catch {
353
- continue;
354
- }
522
+ for (const { alert: parsed, time } of alertLines(text)) {
355
523
  const v = parsed.data?.vulnerability;
356
- if (!v) continue;
357
- const time = parsed.timestamp === undefined ? Number.NaN : Date.parse(parsed.timestamp);
358
- if (Number.isNaN(time) || time < cutoff) continue;
524
+ if (!v || time < cutoff) continue;
359
525
  const name = parsed.agent?.name ?? "?";
360
526
  if (agent !== null && name !== agent) continue;
361
527
  const rawScore = v.score?.base ?? v.cvss?.cvss3?.base_score ?? v.cvss?.cvss2?.base_score;
@@ -379,22 +545,7 @@ export function summariseVulns(text: string, days: number, agent: string | null,
379
545
  });
380
546
  }
381
547
  items.sort((x, y) => y.timestamp.localeCompare(x.timestamp));
382
- const latest = new Map<string, VulnerabilityItem>();
383
- for (const item of items) {
384
- const key = `${item.agent}|${item.package}|${item.version}|${item.cve}`;
385
- if (!latest.has(key)) latest.set(key, item);
386
- }
387
- const open = [...latest.values()].filter((i) => i.status.toLowerCase() === "active");
388
- return {
389
- days,
390
- agent,
391
- count: items.length,
392
- active: items.filter((i) => i.status.toLowerCase() === "active").length,
393
- solved: items.filter((i) => i.status.toLowerCase() === "solved").length,
394
- open: open.slice(0, 50),
395
- openWithoutFixVersion: open.filter((i) => i.condition === "Package default status").length,
396
- items: items.slice(0, 50),
397
- };
548
+ return items;
398
549
  }
399
550
 
400
551
  export async function command(args: string[]): Promise<number> {
@@ -420,6 +571,17 @@ export async function command(args: string[]): Promise<number> {
420
571
  // The guest command is the plain alert dump; the vulnerability view is built here.
421
572
  remoteArgs = ["wazuh-alerts", args[1]];
422
573
  }
574
+ let minutes = 0;
575
+ if (args[0] === "wazuh-events") {
576
+ if (args.length !== 3) throw new UsageError("wazuh-events <minutes> <minLevel>");
577
+ minutes = positiveInt(args[1], "minutes", 30 * 1440);
578
+ minLevel = positiveInt(args[2], "minLevel", 16);
579
+ remoteArgs = ["wazuh-alerts", String(Math.ceil(minutes / 1440))];
580
+ }
581
+ if (args[0] === "wazuh-vuln-events") {
582
+ if (args.length !== 2) throw new UsageError("wazuh-vuln-events <days>");
583
+ remoteArgs = ["wazuh-alerts", args[1]];
584
+ }
423
585
  const remote = buildObsRemote(remoteArgs);
424
586
  const result = await sshFixed(
425
587
  {
@@ -439,6 +601,12 @@ export async function command(args: string[]): Promise<number> {
439
601
  case "wazuh-vulns":
440
602
  printJson(summariseVulns(result.stdout, Number(args[1]), vulnAgent));
441
603
  return 0;
604
+ case "wazuh-events":
605
+ printJson(wazuhEvents(result.stdout, minutes, minLevel ?? 1));
606
+ return 0;
607
+ case "wazuh-vuln-events":
608
+ printJson(vulnEvents(result.stdout, Number(args[1])));
609
+ return 0;
442
610
  case "alerts":
443
611
  printJson(summariseAlerts(result.stdout, Number(args[1]), args[2]));
444
612
  return 0;
@@ -13,7 +13,7 @@ import { ServiceError, UsageError } from "./lib/errors.ts";
13
13
  import { safeRepoPath, safeWritePath } from "./lib/repo.ts";
14
14
  import { POLICY_REQUIRED, buildPulsarRemote, parseQuery, policyWrite, unifiPath, command as networkCommand } from "./network/run.ts";
15
15
  import { buildHostRemote, needsConfirm, parseSetPairs, parseVmid, validateApiPath as validatePvePath, command as proxmoxCommand } from "./proxmox/run.ts";
16
- import { buildObsRemote, compactDecisions, summariseAlerts, summariseVulns, summariseWazuh, command as securityCommand } from "./security/run.ts";
16
+ import { banLength, buildObsRemote, compactDecisions, parseGoDuration, summariseAlerts, summariseVulns, summariseWazuh, vulnEvents, wazuhEvents, command as securityCommand } from "./security/run.ts";
17
17
 
18
18
  describe("arcane wrapper", () => {
19
19
  it("refuses only the wrapper's own setup paths", () => {
@@ -45,9 +45,27 @@ describe("arcane wrapper", () => {
45
45
  expect(String(write.mock.calls[0][0])).toContain("git write");
46
46
  expect(String(write.mock.calls[0][0])).toContain("git show");
47
47
  expect(String(write.mock.calls[0][0])).toContain("stack-update <stack> [--confirm]");
48
+ expect(String(write.mock.calls[0][0])).toContain("change-origin <path> <sha256|-> <utc>");
48
49
  expect(String(write.mock.calls[0][0])).not.toMatch(/^\s+gitops /m);
49
50
  write.mockRestore();
50
51
  });
52
+
53
+ it("checks change-origin arguments before touching the checkout", async () => {
54
+ const home = mkdtempSync(join(tmpdir(), "spc-arc-"));
55
+ const prev = process.env.HOME;
56
+ process.env.HOME = home;
57
+ try {
58
+ mkdirSync(join(home, ".specialists", "config"), { recursive: true });
59
+ const config = { serverUrl: "https://arcane", zitadelDomain: "z", audience: "a", arcaneCli: "/x", arcaneCliConfig: "/y", gitopsRemote: "git@github.com:x/y.git", gitopsBranch: "main" };
60
+ writeFileSync(join(home, ".specialists", "config", "arcane.json"), JSON.stringify(config));
61
+ await expect(arcaneCommand(["change-origin", "/etc/passwd", "-", "2026-10-20T12:50:12Z"])).rejects.toThrow(/path must be/);
62
+ await expect(arcaneCommand(["change-origin", "/opt/docker/x/compose.yaml", "-"])).rejects.toThrow(/change-origin <path>/);
63
+ expect(existsSync(join(home, ".specialists", "work"))).toBe(false);
64
+ } finally {
65
+ process.env.HOME = prev;
66
+ rmSync(home, { recursive: true, force: true });
67
+ }
68
+ });
51
69
  });
52
70
 
53
71
  describe("identity wrapper", () => {
@@ -363,10 +381,102 @@ describe("security wrapper", () => {
363
381
  expect(() => summariseAlerts("not json", 7)).toThrow(/no JSON/);
364
382
  });
365
383
 
384
+ it("lists recent Wazuh events with file fields, without vulnerability findings, oldest first", () => {
385
+ const now = Date.parse("2026-10-20T13:00:00Z");
386
+ const fim = {
387
+ id: "1792500612.123",
388
+ timestamp: "2026-10-20T12:50:12.142+0000",
389
+ rule: { id: "100020", level: 10, description: "Deployment file changed: /opt/docker/grimoire/compose.yaml.", groups: ["critical_file_integrity"] },
390
+ agent: { name: "arcane" },
391
+ syscheck: { path: "/opt/docker/grimoire/compose.yaml", event: "modified", sha256_after: "a".repeat(64) },
392
+ full_log: "File '/opt/docker/grimoire/compose.yaml' modified\nMode: realtime",
393
+ };
394
+ const older = { id: "1792500000.1", timestamp: "2026-10-20T12:40:00.000+0000", rule: { id: "5712", level: 12, description: "brute force" }, agent: { name: "dmz" }, data: { srcip: "1.2.3.4" } };
395
+ const vuln = { id: "v", timestamp: "2026-10-20T12:45:00.000+0000", rule: { id: "23506", level: 13 }, agent: { name: "dmz" }, data: { vulnerability: { cve: "CVE-1", status: "Active" } } };
396
+ const low = { id: "l", timestamp: "2026-10-20T12:46:00.000+0000", rule: { id: "5501", level: 3 }, agent: { name: "dmz" } };
397
+ const stale = { id: "s", timestamp: "2026-10-20T10:00:00.000+0000", rule: { id: "5712", level: 12 }, agent: { name: "dmz" } };
398
+ const text = [fim, older, vuln, low, stale, fim, "junk"].map((x) => (typeof x === "string" ? x : JSON.stringify(x))).join("\n");
399
+ const out = wazuhEvents(text, 30, 10, now);
400
+ expect(out).toMatchObject({ minutes: 30, minLevel: 10, count: 2, omitted: 0 });
401
+ expect(out.events.map((e) => e.id)).toEqual(["1792500000.1", "1792500612.123"]);
402
+ expect(out.events[0]).toEqual({ id: "1792500000.1", timestamp: older.timestamp, agent: "dmz", rule: "5712", level: 12, description: "brute force", groups: [], srcip: "1.2.3.4" });
403
+ expect(out.events[1]).toMatchObject({ path: fim.syscheck.path, event: "modified", sha256: "a".repeat(64), groups: ["critical_file_integrity"] });
404
+ const many = Array.from({ length: 1005 }, (_, i) => JSON.stringify({ ...older, id: String(i), timestamp: `2026-10-20T12:${String(10 + Math.floor(i / 60)).padStart(2, "0")}:${String(i % 60).padStart(2, "0")}.000+0000` })).join("\n");
405
+ const capped = wazuhEvents(many, 60, 10, now);
406
+ expect(capped).toMatchObject({ count: 1005, omitted: 5 });
407
+ expect(capped.events[0].id).toBe("5");
408
+ });
409
+
410
+ it("lists every vulnerability finding compactly, oldest first", () => {
411
+ const now = Date.parse("2026-10-20T13:00:00Z");
412
+ const line = (ts: string, status: string, version: string) =>
413
+ JSON.stringify({ timestamp: ts, rule: { id: "23505", level: 10 }, agent: { name: "arcane" }, data: { vulnerability: { cve: "CVE-K", status, severity: "High", score: { base: 7.8 }, package: { name: "linux-image-cloud-amd64", version, condition: "Package default status" } } } });
414
+ const out = vulnEvents([line("2026-10-20T04:40:47.000+0000", "Solved", "6.12.111-1"), line("2026-10-20T04:40:38.000+0000", "Active", "6.12.113-1"), line("2026-10-10T04:00:00.000+0000", "Active", "6.12.100-1")].join("\n"), 1, now);
415
+ expect(out.count).toBe(2);
416
+ expect(out.events).toEqual([
417
+ { timestamp: "2026-10-20T04:40:38.000+0000", agent: "arcane", cve: "CVE-K", status: "Active", package: "linux-image-cloud-amd64", version: "6.12.113-1", severity: "High", score: 7.8, condition: "Package default status" },
418
+ { timestamp: "2026-10-20T04:40:47.000+0000", agent: "arcane", cve: "CVE-K", status: "Solved", package: "linux-image-cloud-amd64", version: "6.12.111-1", severity: "High", score: 7.8, condition: "Package default status" },
419
+ ]);
420
+ });
421
+
422
+ it("works out each ban's whole length from the time left and the alert's age", () => {
423
+ expect(parseGoDuration("161h53m43s")).toBe((161 * 3600 + 53 * 60 + 43) * 1000);
424
+ expect(parseGoDuration("-29m44s")).toBe(-(29 * 60 + 44) * 1000);
425
+ expect(parseGoDuration("500ms")).toBe(500);
426
+ expect(parseGoDuration("4h")).toBe(14_400_000);
427
+ expect(parseGoDuration("soon")).toBeNull();
428
+ expect(banLength(4)).toBe("4 h");
429
+ expect(banLength(24)).toBe("24 h");
430
+ expect(banLength(168)).toBe("7 days");
431
+ expect(banLength(2160)).toBe("90 days");
432
+ const queried = Date.parse("2026-10-21T21:00:00Z");
433
+ const alert = (id: number, at: string, ban: string, ip: string, cn?: string) => ({ id, created_at: at, scenario: "37pla/frontdoor-sni-scanning", source: { ip, cn, as_number: "16509", as_name: "AMAZON-02" }, decisions: [{ type: "ban", duration: ban }] });
434
+ const text = JSON.stringify([
435
+ alert(1057, "2026-10-21T14:51:55Z", "161h53m43s", "54.204.58.226", "US"),
436
+ alert(1058, "2026-10-21T16:28:28Z", "-29m44s", "66.132.195.99", "US"),
437
+ alert(1059, "2026-10-21T18:53:16Z", "21h55m4s", "195.178.110.137", "BG"),
438
+ { id: 1, created_at: "2026-10-21T18:00:00Z", source: { ip: "9.9.9.9" } },
439
+ ]);
440
+ const s = summariseAlerts(text, 1, undefined, queried);
441
+ expect(s.bans).toEqual([
442
+ { length: "4 h", hours: 4, count: 1 },
443
+ { length: "24 h", hours: 24, count: 1 },
444
+ { length: "7 days", hours: 168, count: 1 },
445
+ ]);
446
+ expect(s.escalated).toEqual([
447
+ { at: "2026-10-21T18:53:16Z", ip: "195.178.110.137", ban: "24 h", country: "BG", as: "AS16509 AMAZON-02" },
448
+ { at: "2026-10-21T14:51:55Z", ip: "54.204.58.226", ban: "7 days", country: "US", as: "AS16509 AMAZON-02" },
449
+ ]);
450
+ expect(s.countries).toEqual([
451
+ { country: "US", count: 2 },
452
+ { country: "BG", count: 1 },
453
+ ]);
454
+ expect(s.networks).toEqual([{ as: "AS16509 AMAZON-02", count: 3 }]);
455
+ });
456
+
457
+ it("checks the new commands' arguments before any SSH call", async () => {
458
+ const home = mkdtempSync(join(tmpdir(), "spc-sec-"));
459
+ const prev = process.env.HOME;
460
+ process.env.HOME = home;
461
+ try {
462
+ mkdirSync(join(home, ".specialists", "config"), { recursive: true });
463
+ writeFileSync(join(home, ".specialists", "config", "security.json"), JSON.stringify({ obsHost: "10.0.90.10", obsUser: "observability" }));
464
+ await expect(securityCommand(["wazuh-events", "0", "10"])).rejects.toThrow(/minutes/);
465
+ await expect(securityCommand(["wazuh-events", "60", "17"])).rejects.toThrow(/minLevel/);
466
+ await expect(securityCommand(["wazuh-events", "60"])).rejects.toThrow(/wazuh-events <minutes> <minLevel>/);
467
+ await expect(securityCommand(["wazuh-vuln-events", "31"])).rejects.toThrow(/days/);
468
+ await expect(securityCommand(["wazuh-vuln-events"])).rejects.toThrow(/wazuh-vuln-events <days>/);
469
+ } finally {
470
+ process.env.HOME = prev;
471
+ rmSync(home, { recursive: true, force: true });
472
+ }
473
+ });
474
+
366
475
  it("prints help without touching config", async () => {
367
476
  const write = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
368
477
  expect(await securityCommand(["help"])).toBe(0);
369
478
  expect(String(write.mock.calls[0][0])).toContain("remote-log <host> <program> <lines>");
479
+ expect(String(write.mock.calls[0][0])).toContain("wazuh-events <minutes> <minLevel>");
370
480
  write.mockRestore();
371
481
  });
372
482
  });