@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.
- package/README.md +1 -1
- package/extensions/astro-discord/config.ts +6 -2
- package/extensions/astro-discord/discord.test.ts +18 -0
- package/extensions/astro-discord/index.ts +68 -7
- package/extensions/astro-discord/reports.ts +15 -4
- package/extensions/astro-discord/rest.ts +15 -3
- package/extensions/astro-discord/security-monitor.test.ts +338 -0
- package/extensions/astro-discord/security-monitor.ts +602 -0
- package/extensions/astro-discord/security.test.ts +497 -0
- package/extensions/astro-discord/security.ts +740 -0
- package/extensions/astro-discord/tools-report.test.ts +31 -3
- package/extensions/astro-discord/tools-report.ts +36 -19
- package/package.json +1 -1
- package/skills/arcane/SKILL.md +2 -0
- package/skills/security/SKILL.md +6 -3
- package/specialists/AGENTS.md +2 -1
- package/specialists/README.md +2 -2
- package/specialists/arcane/run.ts +42 -1
- package/specialists/entry/remote/spc-security-obs-entry.sh +1 -1
- package/specialists/lib/change-origin.test.ts +97 -0
- package/specialists/lib/change-origin.ts +121 -0
- package/specialists/security/run.ts +199 -31
- package/specialists/wrappers.test.ts +111 -1
package/README.md
CHANGED
|
@@ -68,7 +68,7 @@ pi # launch; confirm [Extensions] lists astro-subagents, grimoire
|
|
|
68
68
|
- `multi-edit` - registers the enhanced `edit` tool
|
|
69
69
|
- `gemini-image` - registers `gemini_image` tool (requires a Gemini API key; prompts and saves on first use)
|
|
70
70
|
- `security-guard` - blocks/prompts destructive bash commands and sensitive file access; configure at `~/.pi/agent/security-guard.json` (example written on first run); `/security-guard status|reload|test`
|
|
71
|
-
- `astro-discord` - Discord access to the specialists: in the configured channels, `<specialist> <task>` runs `astro.<specialist>` and posts the answer as a reply (โณ running, ๐ waiting for an owner's approval of a risky call, โ
done, โ failed). Owners may use every specialist and approve risky calls with buttons; other users only the specialists listed for them; everyone else is ignored. Where the `media` specialist is present, `/trending`, `/search`, and `/downloads` answer without a model, with an Add button beside each title. Scheduled reports (`reports` in its config): the Arcane Daily Report, with a release-notes verdict on major versions and an Update button per stack that only owners can press,
|
|
71
|
+
- `astro-discord` - Discord access to the specialists: in the configured channels, `<specialist> <task>` runs `astro.<specialist>` and posts the answer as a reply (โณ running, ๐ waiting for an owner's approval of a risky call, โ
done, โ failed). Owners may use every specialist and approve risky calls with buttons; other users only the specialists listed for them; everyone else is ignored. Where the `media` specialist is present, `/trending`, `/search`, and `/downloads` answer without a model, with an Add button beside each title. Scheduled reports (`reports` in its config): the Arcane Daily Report, with a release-notes verdict on major versions and an Update button per stack that only owners can press, the Cortex Tools Report, which lists every tool on Cortex with a newer version, a release-notes verdict for the tools the specialists build on, and an Update button that only owners can press, and the Security Daily and Weekly Reports (CrowdSec, Wazuh, vulnerabilities, patches, health, backups), whose channel also gets urgent Wazuh alerts within two minutes, with Investigate (the security specialist answers in a thread) and Acknowledge buttons for owners. Inert unless the headless host sets `ASTRO_DISCORD=1`; setup with `d=$(mktemp -d) && cp ~/.pi/agent/npm/node_modules/@astrofoundry/pi-astro/extensions/astro-discord/*.ts "$d" && node --disable-warning=ExperimentalWarning "$d/setup.ts"` (Node refuses to strip types inside `node_modules`, hence the copy), which prompts for the bot token and ids, checks them against Discord, and writes the LaunchAgent. See [specialists/README.md](specialists/README.md#discord).
|
|
72
72
|
- `specialist-gate` - gives each specialist agent (`astro.arcane`, `astro.identity`, `astro.network`, `astro.dns`, `astro.edge`, `astro.security`, `astro.backup`, `astro.proxmox`, `astro.inference`, `astro.media`) its single tool, which runs the matching CLI wrapper as a dedicated macOS user through `sudo`, and blocks every other agent from calling those CLIs or reading their credentials. Inactive until the host has `~/.pi/agent/specialists.json`. `/specialists` prints the status. Host setup is described in [specialists/README.md](specialists/README.md).
|
|
73
73
|
- `notify-on-stop` - runs a shell command when the agent finishes a turn (sound, voice, desktop notification). **Default: off.** Enable with `/notify on` (state persists in `~/.pi/agent/notify-on-stop.json`); disable with `/notify off`. macOS default command: plays the Glass system sound and speaks "Agent done" via `say` using the **`Samantha (Enhanced)`** voice. Linux default: `notify-send "pi" "Agent done"`. Override the voice with `PI_STOP_NOTIFY_VOICE=<voice-name>` (macOS only; e.g. `Alex`, `Karen`, `Daniel (Enhanced)`). Replace the full command with `PI_STOP_NOTIFY='afplay /System/Library/Sounds/Glass.aiff && say "Done"'`. Hard-kill (overrides `/notify on`) with `PI_STOP_NOTIFY_OFF=1`. Commands: `/notify [on|off|status|test]`. See [extensions/notify-on-stop/README.md](extensions/notify-on-stop/README.md) for full details.
|
|
74
74
|
- **macOS voice install (required once for the default):** open **System Settings, Accessibility, Spoken Content, System Voice, Manage Voices...**, expand **English**, check **Samantha (Enhanced)**, click **Done** to download (~500 MB to 1 GB). Verify with `say -v "Samantha (Enhanced)" hi`. If the voice is missing, `say` errors silently and you'll only hear the Glass sound.
|
|
@@ -30,8 +30,12 @@ export interface DiscordConfig {
|
|
|
30
30
|
reports: ReportSchedule[];
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
/**
|
|
34
|
-
|
|
33
|
+
/**
|
|
34
|
+
* Reports the bridge can post on a schedule, without a model. `security` is the
|
|
35
|
+
* daily report and also turns on the urgent-alert check in its channel;
|
|
36
|
+
* `security-weekly` posts on Mondays only, in place of that day's daily report.
|
|
37
|
+
*/
|
|
38
|
+
export const REPORT_NAMES = ["arcane", "tools", "security", "security-weekly"] as const;
|
|
35
39
|
export type ReportName = (typeof REPORT_NAMES)[number];
|
|
36
40
|
|
|
37
41
|
/** One entry of `reports` in config.json: which report, where, and when. */
|
|
@@ -285,6 +285,24 @@ describe("rest", () => {
|
|
|
285
285
|
expect(calls[3].url).toBe(`https://discord.com/api/v10/channels/c1/messages/m1/reactions/${encodeURIComponent("โณ")}/@me`);
|
|
286
286
|
expect(calls[3].init.method).toBe("PUT");
|
|
287
287
|
});
|
|
288
|
+
|
|
289
|
+
it("pings only the listed users and opens a thread on a message", async () => {
|
|
290
|
+
const calls: { url: string; init: RequestInit }[] = [];
|
|
291
|
+
const fetchImpl = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
|
|
292
|
+
calls.push({ url: String(url), init: init ?? {} });
|
|
293
|
+
return new Response(JSON.stringify({ id: "m1", channel_id: "c1" }), { status: 200 });
|
|
294
|
+
}) as unknown as typeof fetch;
|
|
295
|
+
const rest = new DiscordRest("tok", fetchImpl);
|
|
296
|
+
await rest.createMessage("c1", { content: "<@1> alert", mentionUsers: ["178096425509453824"] });
|
|
297
|
+
expect(JSON.parse(calls[0].init.body as string).allowed_mentions).toEqual({ users: ["178096425509453824"] });
|
|
298
|
+
await rest.createComponentsMessage("c1", [{ type: 10, content: "x" }], ["178096425509453824"]);
|
|
299
|
+
expect(JSON.parse(calls[1].init.body as string)).toMatchObject({ flags: 1 << 15, allowed_mentions: { users: ["178096425509453824"] } });
|
|
300
|
+
await rest.createComponentsMessage("c1", [{ type: 10, content: "x" }]);
|
|
301
|
+
expect(JSON.parse(calls[2].init.body as string).allowed_mentions).toEqual({ parse: [] });
|
|
302
|
+
await rest.startThread("c1", "m9", "Rule 100021 on arcane");
|
|
303
|
+
expect(calls[3].url).toBe("https://discord.com/api/v10/channels/c1/messages/m9/threads");
|
|
304
|
+
expect(JSON.parse(calls[3].init.body as string)).toEqual({ name: "Rule 100021 on arcane", auto_archive_duration: 10080 });
|
|
305
|
+
});
|
|
288
306
|
});
|
|
289
307
|
|
|
290
308
|
describe("failure reply", () => {
|
|
@@ -34,7 +34,7 @@ import {
|
|
|
34
34
|
import { GatewayClient } from "./gateway.ts";
|
|
35
35
|
import { type CommandOption, IS_COMPONENTS_V2, KeyedQueue, MEDIA, MEDIA_COMMANDS, type MediaKind, type Outcome, addOutcome, applyOutcome, commandArgs, hasActiveButton, listMessage, mediaAccess, mediaPointer, parseAddButton, parseAddReport, parseMediaList, parseQueueState, queueLine } from "./media.ts";
|
|
36
36
|
import { cancelledApprovalText, interruptedTaskText, readOpenWork, type OpenWork, type StopReason, writeOpenWork } from "./open-work.ts";
|
|
37
|
-
import { isDue, readReportState, writeReportState } from "./reports.ts";
|
|
37
|
+
import { isDue, MONDAY, readReportState, writeReportState } from "./reports.ts";
|
|
38
38
|
import { ACTIVITY_COMMAND, type Activity, addRestarts, astrogateActivity, herdrActivity, needsPrompt, type PendingRestart, readRestarts, restartCommand, SERVICE_LABEL, SERVICE_ORDER, writeRestarts } from "./restarts.ts";
|
|
39
39
|
import {
|
|
40
40
|
arcaneServerVersion,
|
|
@@ -71,6 +71,7 @@ import {
|
|
|
71
71
|
} from "./tools-report.ts";
|
|
72
72
|
import { type Quote, type QuotedMessage, withQuotes } from "./quote.ts";
|
|
73
73
|
import { DiscordRest, type MessageComponent } from "./rest.ts";
|
|
74
|
+
import { type InvestigationRequest, SecurityMonitor } from "./security-monitor.ts";
|
|
74
75
|
|
|
75
76
|
const REACTION = { running: "โณ", waiting: "๐", done: "โ
", failed: "โ" } as const;
|
|
76
77
|
/** Answers longer than this go as a file attachment with a short summary. */
|
|
@@ -220,6 +221,7 @@ class Bridge {
|
|
|
220
221
|
private readonly parents = new Map<string, string | null>();
|
|
221
222
|
private readonly ctx: ExtensionContext;
|
|
222
223
|
private readonly token: string;
|
|
224
|
+
private readonly security: SecurityMonitor;
|
|
223
225
|
|
|
224
226
|
constructor(ctx: ExtensionContext, config: DiscordConfig, token: string) {
|
|
225
227
|
this.ctx = ctx;
|
|
@@ -228,6 +230,15 @@ class Bridge {
|
|
|
228
230
|
this.conversations = loadState();
|
|
229
231
|
this.rest = new DiscordRest(token);
|
|
230
232
|
this.approvals = new ApprovalServer({ onTicket: (t) => void this.askApproval(t), onExpired: (t) => void this.expireApproval(t) }, config.approvalTimeoutMinutes * 60_000);
|
|
233
|
+
this.security = new SecurityMonitor({
|
|
234
|
+
rest: this.rest,
|
|
235
|
+
runEntry: (service, caller, args, timeoutMs) => this.runEntry(service, caller, args, timeoutMs),
|
|
236
|
+
config: () => this.config,
|
|
237
|
+
log,
|
|
238
|
+
investigate: (request) => this.investigateSecurity(request),
|
|
239
|
+
stopping: () => this.stopping,
|
|
240
|
+
now: () => Date.now(),
|
|
241
|
+
});
|
|
231
242
|
}
|
|
232
243
|
|
|
233
244
|
/** Specialists configured for this host, as short names. */
|
|
@@ -329,13 +340,16 @@ class Bridge {
|
|
|
329
340
|
void this.registerMediaCommands();
|
|
330
341
|
await this.closeInterruptedUpdates();
|
|
331
342
|
await this.closeInterruptedArcane();
|
|
332
|
-
|
|
343
|
+
await this.security.closeInterrupted().catch((err) => log(`security: ${err instanceof Error ? err.message : String(err)}`));
|
|
344
|
+
// Checked every minute: each report decides whether today's is due, waiting restarts check whether their service is idle, and the security checks whether theirs is due.
|
|
333
345
|
this.reportTimer = setInterval(() => {
|
|
334
346
|
void this.maybeReports();
|
|
335
347
|
void this.processRestarts();
|
|
348
|
+
this.security.tick();
|
|
336
349
|
}, 60_000);
|
|
337
350
|
this.reportTimer.unref();
|
|
338
351
|
void this.maybeReports();
|
|
352
|
+
this.security.tick();
|
|
339
353
|
log(`connected as ${me.username} (${me.id}); channels ${Object.keys(this.config.channels).join(", ")}; specialists ${this.specialists().names.join(", ")}`);
|
|
340
354
|
}
|
|
341
355
|
|
|
@@ -425,7 +439,11 @@ class Bridge {
|
|
|
425
439
|
const task: ActiveTask = { specialist: command.specialist, channelId: message.channel_id, messageId: message.id, userId, startedAt: now, conversation, images };
|
|
426
440
|
const taskText = withQuotes(command.task, quotes);
|
|
427
441
|
const previous = this.queues.get(command.specialist) ?? Promise.resolve();
|
|
428
|
-
const next = previous
|
|
442
|
+
const next = previous
|
|
443
|
+
.then(async () => {
|
|
444
|
+
await this.runTask(agent, taskText, task);
|
|
445
|
+
})
|
|
446
|
+
.catch((err) => log(`run failed: ${err instanceof Error ? err.message : String(err)}`));
|
|
429
447
|
this.queues.set(command.specialist, next);
|
|
430
448
|
}
|
|
431
449
|
|
|
@@ -435,10 +453,17 @@ class Bridge {
|
|
|
435
453
|
this.refreshConfig();
|
|
436
454
|
for (const schedule of this.config.reports) {
|
|
437
455
|
if (this.reportsRunning.has(schedule.report)) continue;
|
|
438
|
-
const { due, date } = isDue(schedule, readReportState(schedule.report), new Date());
|
|
456
|
+
const { due, date } = isDue(schedule, readReportState(schedule.report), new Date(), schedule.report === "security-weekly" ? MONDAY : undefined);
|
|
439
457
|
if (!due) continue;
|
|
440
458
|
this.reportsRunning.add(schedule.report);
|
|
441
|
-
const run =
|
|
459
|
+
const run =
|
|
460
|
+
schedule.report === "arcane"
|
|
461
|
+
? this.arcaneReport(schedule, date)
|
|
462
|
+
: schedule.report === "tools"
|
|
463
|
+
? this.toolsReport(schedule, date)
|
|
464
|
+
: schedule.report === "security"
|
|
465
|
+
? this.security.dailyReport(schedule, date)
|
|
466
|
+
: this.security.weeklyReport(schedule, date);
|
|
442
467
|
void run
|
|
443
468
|
.catch((err) => log(`${schedule.report} report ${date}: ${err instanceof Error ? err.message : String(err)}`))
|
|
444
469
|
.finally(() => this.reportsRunning.delete(schedule.report));
|
|
@@ -1092,7 +1117,36 @@ class Bridge {
|
|
|
1092
1117
|
return quotes;
|
|
1093
1118
|
}
|
|
1094
1119
|
|
|
1095
|
-
|
|
1120
|
+
/**
|
|
1121
|
+
* Investigate on a security alert: astro.security in the alert's thread,
|
|
1122
|
+
* queued behind any other security task, as a fresh conversation that the
|
|
1123
|
+
* owner can continue by writing in the thread.
|
|
1124
|
+
*/
|
|
1125
|
+
private async investigateSecurity(request: InvestigationRequest): Promise<boolean> {
|
|
1126
|
+
const agent = this.specialists().agents.find((a) => a.name === "astro.security");
|
|
1127
|
+
if (!agent) {
|
|
1128
|
+
await this.rest.createMessage(request.threadId, { content: "โ astro.security is not configured on this host." }).catch(() => undefined);
|
|
1129
|
+
return false;
|
|
1130
|
+
}
|
|
1131
|
+
const now = Date.now();
|
|
1132
|
+
const conversation = resolveConversation(this.conversations, { channelId: request.threadId, specialist: "security", fresh: true, now }, () => newConversationId("security", now));
|
|
1133
|
+
this.conversations = startConversation(this.conversations, conversation.key, conversation.id, now);
|
|
1134
|
+
saveState(this.conversations);
|
|
1135
|
+
const task: ActiveTask = { specialist: "security", channelId: request.threadId, messageId: request.starterId, userId: request.userId, startedAt: now, conversation, images: [] };
|
|
1136
|
+
let failed = true;
|
|
1137
|
+
const previous = this.queues.get("security") ?? Promise.resolve();
|
|
1138
|
+
const next = previous
|
|
1139
|
+
.then(async () => {
|
|
1140
|
+
failed = await this.runTask(agent, request.task, task);
|
|
1141
|
+
})
|
|
1142
|
+
.catch((err) => log(`security investigation failed: ${err instanceof Error ? err.message : String(err)}`));
|
|
1143
|
+
this.queues.set("security", next);
|
|
1144
|
+
await next;
|
|
1145
|
+
return !failed;
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
/** Runs one specialist task and answers in Discord; resolves true when the run failed or was cut off. */
|
|
1149
|
+
private async runTask(agent: AgentConfig, taskText: string, task: ActiveTask): Promise<boolean> {
|
|
1096
1150
|
task.startedAt = Date.now();
|
|
1097
1151
|
task.abort = new AbortController();
|
|
1098
1152
|
this.active.set(task.specialist, task);
|
|
@@ -1167,12 +1221,13 @@ class Bridge {
|
|
|
1167
1221
|
if (images) await fs.rm(images.dir, { recursive: true, force: true }).catch(() => undefined);
|
|
1168
1222
|
}
|
|
1169
1223
|
// During shutdown the interrupted message was already written; an aborted run has nothing else to say.
|
|
1170
|
-
if (this.stopping) return;
|
|
1224
|
+
if (this.stopping) return true;
|
|
1171
1225
|
await this.rest.removeOwnReaction(task.channelId, task.messageId, REACTION.running).catch(() => undefined);
|
|
1172
1226
|
await this.rest.addReaction(task.channelId, task.messageId, failed ? REACTION.failed : REACTION.done).catch(() => undefined);
|
|
1173
1227
|
const answers = await this.deliver(task, placeholder, `${failed ? "โ" : "โ
"} **${task.specialist}**\n${output}`, attachment);
|
|
1174
1228
|
this.conversations = recordAnswer(this.conversations, task.conversation.key, answers, Date.now());
|
|
1175
1229
|
saveState(this.conversations);
|
|
1230
|
+
return failed;
|
|
1176
1231
|
}
|
|
1177
1232
|
|
|
1178
1233
|
/** Turns the "working" placeholder into the answer: edit it in place when it fits, otherwise replace it with chunks or an attachment. Returns the answer message ids. */
|
|
@@ -1242,6 +1297,12 @@ class Bridge {
|
|
|
1242
1297
|
await this.onArcaneButton(interaction, customId);
|
|
1243
1298
|
return;
|
|
1244
1299
|
}
|
|
1300
|
+
if (customId.startsWith("security:")) {
|
|
1301
|
+
this.refreshConfig();
|
|
1302
|
+
const userId = interaction.member?.user?.id ?? interaction.user?.id ?? "";
|
|
1303
|
+
await this.security.onButton({ interactionId: interaction.id, token: interaction.token, userId, messageId: interaction.message?.id ?? "", customId });
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1245
1306
|
const match = /^apr:([0-9a-f-]{36}):(approve|deny)$/.exec(customId);
|
|
1246
1307
|
if (!match) return;
|
|
1247
1308
|
const userId = interaction.member?.user?.id ?? interaction.user?.id ?? "";
|
|
@@ -5,7 +5,8 @@ import { configDir, type ReportName } from "./config.ts";
|
|
|
5
5
|
export interface ReportState {
|
|
6
6
|
/** Local date in the report's time zone, `YYYY-MM-DD`. */
|
|
7
7
|
date: string;
|
|
8
|
-
|
|
8
|
+
/** `skipped`: the Security Daily Report on a Monday, when the weekly report takes its place. */
|
|
9
|
+
status: "sending" | "sent" | "failed" | "skipped";
|
|
9
10
|
messageId?: string;
|
|
10
11
|
}
|
|
11
12
|
|
|
@@ -16,15 +17,25 @@ export function zonedNow(timeZone: string, now: Date): { date: string; minutes:
|
|
|
16
17
|
return { date: `${get("year")}-${get("month")}-${get("day")}`, minutes: Number(get("hour")) * 60 + Number(get("minute")) };
|
|
17
18
|
}
|
|
18
19
|
|
|
20
|
+
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
|
21
|
+
export const MONDAY = 1;
|
|
22
|
+
|
|
23
|
+
/** Local day of the week in a time zone, 0 for Sunday. */
|
|
24
|
+
export function zonedWeekday(timeZone: string, now: Date): number {
|
|
25
|
+
return WEEKDAYS.indexOf(new Intl.DateTimeFormat("en-US", { timeZone, weekday: "short" }).format(now));
|
|
26
|
+
}
|
|
27
|
+
|
|
19
28
|
/**
|
|
20
29
|
* Due once per local date, from the configured time on: a bridge that was down
|
|
21
30
|
* at the report's time posts when it comes back that day. Any record for today,
|
|
22
|
-
* even a failed or interrupted send, means no second message.
|
|
31
|
+
* even a failed or interrupted send, means no second message. With `weekday`,
|
|
32
|
+
* only on that local day of the week.
|
|
23
33
|
*/
|
|
24
|
-
export function isDue(schedule: { time: string; timeZone: string }, state: ReportState | null, now: Date): { due: boolean; date: string } {
|
|
34
|
+
export function isDue(schedule: { time: string; timeZone: string }, state: ReportState | null, now: Date, weekday?: number): { due: boolean; date: string } {
|
|
25
35
|
const { date, minutes } = zonedNow(schedule.timeZone, now);
|
|
26
36
|
const [h, m] = schedule.time.split(":").map(Number);
|
|
27
|
-
|
|
37
|
+
const onDay = weekday === undefined || zonedWeekday(schedule.timeZone, now) === weekday;
|
|
38
|
+
return { due: onDay && minutes >= h * 60 + m && state?.date !== date, date };
|
|
28
39
|
}
|
|
29
40
|
|
|
30
41
|
/** The Arcane report keeps the file it had before reports became a list, so the switch never posts twice on one day. */
|
|
@@ -28,6 +28,13 @@ export interface CreateMessage {
|
|
|
28
28
|
components?: MessageComponent[];
|
|
29
29
|
/** One optional text attachment. */
|
|
30
30
|
file?: { name: string; content: string };
|
|
31
|
+
/** Users the message may ping; every other mention stays silent. */
|
|
32
|
+
mentionUsers?: string[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** No mention pings unless the user is listed. */
|
|
36
|
+
function allowedMentions(users: readonly string[] | undefined): { parse: never[] } | { users: string[] } {
|
|
37
|
+
return users && users.length > 0 ? { users: [...users] } : { parse: [] };
|
|
31
38
|
}
|
|
32
39
|
|
|
33
40
|
export interface DiscordMessage {
|
|
@@ -68,7 +75,7 @@ export class DiscordRest {
|
|
|
68
75
|
}
|
|
69
76
|
|
|
70
77
|
async createMessage(channelId: string, message: CreateMessage): Promise<DiscordMessage> {
|
|
71
|
-
const payload: Record<string, unknown> = { content: message.content, allowed_mentions:
|
|
78
|
+
const payload: Record<string, unknown> = { content: message.content, allowed_mentions: allowedMentions(message.mentionUsers) };
|
|
72
79
|
if (message.replyTo) payload.message_reference = { message_id: message.replyTo, fail_if_not_exists: false };
|
|
73
80
|
if (message.components) payload.components = message.components;
|
|
74
81
|
if (message.file) {
|
|
@@ -82,8 +89,8 @@ export class DiscordRest {
|
|
|
82
89
|
}
|
|
83
90
|
|
|
84
91
|
/** A Components V2 message (flag `1 << 15`): text lives in Text Display components, there is no `content`. */
|
|
85
|
-
async createComponentsMessage(channelId: string, components: MessageComponent[]): Promise<DiscordMessage> {
|
|
86
|
-
const payload = { flags: 1 << 15, components, allowed_mentions:
|
|
92
|
+
async createComponentsMessage(channelId: string, components: MessageComponent[], mentionUsers?: string[]): Promise<DiscordMessage> {
|
|
93
|
+
const payload = { flags: 1 << 15, components, allowed_mentions: allowedMentions(mentionUsers) };
|
|
87
94
|
return (await this.call("POST", `/channels/${channelId}/messages`, JSON.stringify(payload), "application/json")).json() as Promise<DiscordMessage>;
|
|
88
95
|
}
|
|
89
96
|
|
|
@@ -96,6 +103,11 @@ export class DiscordRest {
|
|
|
96
103
|
await this.call("PATCH", `/channels/${channelId}/messages/${messageId}`, JSON.stringify({ content, components, allowed_mentions: { parse: [] } }), "application/json");
|
|
97
104
|
}
|
|
98
105
|
|
|
106
|
+
/** A public thread on a message; its id is the message's id, and a message can carry only one. */
|
|
107
|
+
async startThread(channelId: string, messageId: string, name: string): Promise<{ id: string }> {
|
|
108
|
+
return (await this.call("POST", `/channels/${channelId}/messages/${messageId}/threads`, JSON.stringify({ name: name.slice(0, 100), auto_archive_duration: 10080 }), "application/json")).json() as Promise<{ id: string }>;
|
|
109
|
+
}
|
|
110
|
+
|
|
99
111
|
/** Shows the "Cortex is typingโฆ" indicator for about ten seconds. */
|
|
100
112
|
async triggerTyping(channelId: string): Promise<void> {
|
|
101
113
|
await this.call("POST", `/channels/${channelId}/typing`);
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
5
|
+
import type { DiscordConfig } from "./config.ts";
|
|
6
|
+
import { readReportState } from "./reports.ts";
|
|
7
|
+
import type { CreateMessage, MessageComponent } from "./rest.ts";
|
|
8
|
+
import { type InvestigationRequest, parseAlertSummary, patchingFacts, SecurityMonitor, type SecurityRest } from "./security-monitor.ts";
|
|
9
|
+
import { readSecurityState, type WazuhEvent } from "./security.ts";
|
|
10
|
+
|
|
11
|
+
const OWNER = "178096425509453824";
|
|
12
|
+
const CHANNEL = "1562562637823344660";
|
|
13
|
+
const SCHEDULE = { report: "security" as const, channelId: CHANNEL, time: "06:00", timeZone: "Europe/Madrid" };
|
|
14
|
+
|
|
15
|
+
function config(weekly = false): DiscordConfig {
|
|
16
|
+
return {
|
|
17
|
+
applicationId: "1",
|
|
18
|
+
guildId: "2",
|
|
19
|
+
channels: { [CHANNEL]: { trigger: "always", specialists: ["security"] } },
|
|
20
|
+
adminChannelId: CHANNEL,
|
|
21
|
+
owners: [OWNER],
|
|
22
|
+
access: {},
|
|
23
|
+
approvalTimeoutMinutes: 10,
|
|
24
|
+
reports: [SCHEDULE, ...(weekly ? [{ ...SCHEDULE, report: "security-weekly" as const }] : [])],
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
class FakeRest implements SecurityRest {
|
|
29
|
+
messages: { channelId: string; message: CreateMessage }[] = [];
|
|
30
|
+
components: { channelId: string; components: MessageComponent[]; mentionUsers?: string[] }[] = [];
|
|
31
|
+
edits: { messageId: string; components: MessageComponent[] }[] = [];
|
|
32
|
+
replies: string[] = [];
|
|
33
|
+
deferred = 0;
|
|
34
|
+
threads: string[] = [];
|
|
35
|
+
failComponents = false;
|
|
36
|
+
private next = 100;
|
|
37
|
+
|
|
38
|
+
async createMessage(channelId: string, message: CreateMessage) {
|
|
39
|
+
this.messages.push({ channelId, message });
|
|
40
|
+
return { id: String(this.next++), channel_id: channelId };
|
|
41
|
+
}
|
|
42
|
+
async createComponentsMessage(channelId: string, components: MessageComponent[], mentionUsers?: string[]) {
|
|
43
|
+
if (this.failComponents) throw new Error("Discord POST answered 500");
|
|
44
|
+
this.components.push({ channelId, components, mentionUsers });
|
|
45
|
+
return { id: String(this.next++), channel_id: channelId };
|
|
46
|
+
}
|
|
47
|
+
async editComponents(_channelId: string, messageId: string, components: MessageComponent[]) {
|
|
48
|
+
this.edits.push({ messageId, components });
|
|
49
|
+
}
|
|
50
|
+
async ephemeralReply(_id: string, _token: string, content: string) {
|
|
51
|
+
this.replies.push(content);
|
|
52
|
+
}
|
|
53
|
+
async deferUpdate() {
|
|
54
|
+
this.deferred++;
|
|
55
|
+
}
|
|
56
|
+
async startThread(_channelId: string, messageId: string) {
|
|
57
|
+
this.threads.push(messageId);
|
|
58
|
+
return { id: messageId };
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function wazuh(over: Partial<WazuhEvent>): WazuhEvent {
|
|
63
|
+
return { id: "1", timestamp: "2026-10-21T10:00:00.000+0000", agent: "arcane", rule: "100021", level: 10, description: "Host security configuration changed: /etc/sudoers.d/x.", groups: [], path: "/etc/sudoers.d/x", event: "added", ...over };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface Harness {
|
|
67
|
+
rest: FakeRest;
|
|
68
|
+
monitor: SecurityMonitor;
|
|
69
|
+
calls: string[][];
|
|
70
|
+
investigations: InvestigationRequest[];
|
|
71
|
+
clock: { now: number };
|
|
72
|
+
answers: Map<string, () => string>;
|
|
73
|
+
weekly: { on: boolean };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function harness(): Harness {
|
|
77
|
+
const rest = new FakeRest();
|
|
78
|
+
const calls: string[][] = [];
|
|
79
|
+
const investigations: InvestigationRequest[] = [];
|
|
80
|
+
const clock = { now: Date.parse("2026-10-21T10:01:00Z") };
|
|
81
|
+
const answers = new Map<string, () => string>();
|
|
82
|
+
const weekly = { on: false };
|
|
83
|
+
const monitor = new SecurityMonitor({
|
|
84
|
+
rest,
|
|
85
|
+
runEntry: async (service, _caller, args) => {
|
|
86
|
+
calls.push([service, ...args]);
|
|
87
|
+
const answer = answers.get(`${service} ${args[0]}`);
|
|
88
|
+
if (!answer) throw new Error(`no answer for ${service} ${args.join(" ")}`);
|
|
89
|
+
return answer();
|
|
90
|
+
},
|
|
91
|
+
config: () => config(weekly.on),
|
|
92
|
+
log: () => undefined,
|
|
93
|
+
investigate: async (request) => {
|
|
94
|
+
investigations.push(request);
|
|
95
|
+
return true;
|
|
96
|
+
},
|
|
97
|
+
stopping: () => false,
|
|
98
|
+
now: () => clock.now,
|
|
99
|
+
});
|
|
100
|
+
return { rest, monitor, calls, investigations, clock, answers, weekly };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function events(list: WazuhEvent[]): () => string {
|
|
104
|
+
return () => JSON.stringify({ minutes: 10, minLevel: 10, count: list.length, omitted: 0, events: list });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
describe("security monitor", () => {
|
|
108
|
+
let dir: string;
|
|
109
|
+
beforeEach(() => {
|
|
110
|
+
dir = mkdtempSync(join(tmpdir(), "astro-security-"));
|
|
111
|
+
process.env.ASTRO_DISCORD_DIR = dir;
|
|
112
|
+
});
|
|
113
|
+
afterEach(() => {
|
|
114
|
+
delete process.env.ASTRO_DISCORD_DIR;
|
|
115
|
+
rmSync(dir, { recursive: true, force: true });
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it("posts an urgent alert once with a mention and buttons, and reads from the last check on", async () => {
|
|
119
|
+
const h = harness();
|
|
120
|
+
h.answers.set("security wazuh-events", events([wazuh({ id: "a1" }), wazuh({ id: "low", rule: "510", level: 7, path: undefined })]));
|
|
121
|
+
await h.monitor.poll(SCHEDULE);
|
|
122
|
+
expect(h.calls[0]).toEqual(["security", "wazuh-events", "15", "10"]);
|
|
123
|
+
expect(h.rest.components).toHaveLength(1);
|
|
124
|
+
expect(h.rest.components[0].mentionUsers).toEqual([OWNER]);
|
|
125
|
+
expect(h.rest.components[0].components[0].content).toContain("๐จ **Security alert** ยท level 10 ยท arcane ยท rule 100021");
|
|
126
|
+
h.clock.now += 2 * 60_000;
|
|
127
|
+
await h.monitor.poll(SCHEDULE);
|
|
128
|
+
expect(h.calls[1]).toEqual(["security", "wazuh-events", "10", "10"]);
|
|
129
|
+
expect(h.rest.components).toHaveLength(1);
|
|
130
|
+
expect(readSecurityState().occurrences).toHaveLength(1);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it("groups one key per check and keeps an acknowledged key quiet while counting it", async () => {
|
|
134
|
+
const h = harness();
|
|
135
|
+
h.answers.set("security wazuh-events", events([wazuh({ id: "a1" }), wazuh({ id: "a2", timestamp: "2026-10-21T10:00:01.000+0000" })]));
|
|
136
|
+
await h.monitor.poll(SCHEDULE);
|
|
137
|
+
expect(h.rest.components).toHaveLength(1);
|
|
138
|
+
expect(h.rest.components[0].components[0].content).toContain("first time this week ยท ร 2 in this check");
|
|
139
|
+
const messageId = readSecurityState().alerts[0].messageId;
|
|
140
|
+
await h.monitor.onButton({ interactionId: "i", token: "t", userId: OWNER, messageId, customId: "security:ack" });
|
|
141
|
+
expect(h.rest.deferred).toBe(1);
|
|
142
|
+
expect(h.rest.edits[0].components[0].content).toContain("Acknowledged by");
|
|
143
|
+
h.clock.now += 2 * 60_000;
|
|
144
|
+
h.answers.set("security wazuh-events", events([wazuh({ id: "a3", timestamp: "2026-10-21T10:02:00.000+0000" })]));
|
|
145
|
+
await h.monitor.poll(SCHEDULE);
|
|
146
|
+
expect(h.rest.components).toHaveLength(1);
|
|
147
|
+
expect(readSecurityState().occurrences).toHaveLength(3);
|
|
148
|
+
await h.monitor.onButton({ interactionId: "i", token: "t", userId: OWNER, messageId, customId: "security:ack" });
|
|
149
|
+
expect(h.rest.replies.at(-1)).toBe(`Already acknowledged by <@${OWNER}>.`);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it("does not page for a deployment change GitOps explains, and pages with the reason when nothing does", async () => {
|
|
153
|
+
const h = harness();
|
|
154
|
+
const known = wazuh({ id: "k1", rule: "100020", path: "/opt/docker/grimoire/compose.yaml", event: "modified", sha256: "a".repeat(64), description: "Deployment file changed" });
|
|
155
|
+
const unknown = { ...known, id: "u1", path: "/opt/docker/x/compose.yaml", sha256: "b".repeat(64) };
|
|
156
|
+
h.answers.set("security wazuh-events", events([known, unknown]));
|
|
157
|
+
h.answers.set("arcane change-origin", () => {
|
|
158
|
+
const last = h.calls.at(-1) ?? [];
|
|
159
|
+
return JSON.stringify(last[2] === known.path ? { verdict: "known", reason: "the new content matches GitOps commit 21d8d1b72c93" } : { verdict: "unknown", reason: "no GitOps commit has this content" });
|
|
160
|
+
});
|
|
161
|
+
await h.monitor.poll(SCHEDULE);
|
|
162
|
+
expect(h.calls.filter((c) => c[0] === "arcane")).toEqual([
|
|
163
|
+
["arcane", "change-origin", known.path, "a".repeat(64), known.timestamp],
|
|
164
|
+
["arcane", "change-origin", unknown.path, "b".repeat(64), unknown.timestamp],
|
|
165
|
+
]);
|
|
166
|
+
expect(h.rest.components).toHaveLength(1);
|
|
167
|
+
expect(h.rest.components[0].components[0].content).toContain("origin unknown: no GitOps commit has this content");
|
|
168
|
+
expect(readSecurityState().origins.k1.verdict).toBe("known");
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it("retries a failed origin check, then pages it as unchecked after ten minutes", async () => {
|
|
172
|
+
const h = harness();
|
|
173
|
+
const change = wazuh({ id: "c1", rule: "100020", path: "/opt/docker/x/compose.yaml", event: "modified", sha256: "c".repeat(64), description: "Deployment file changed" });
|
|
174
|
+
h.answers.set("security wazuh-events", events([change]));
|
|
175
|
+
h.answers.set("arcane change-origin", () => {
|
|
176
|
+
throw new Error("arcane: token request failed");
|
|
177
|
+
});
|
|
178
|
+
await h.monitor.poll(SCHEDULE);
|
|
179
|
+
expect(h.rest.components).toHaveLength(0);
|
|
180
|
+
expect(readSecurityState().pending).toHaveLength(1);
|
|
181
|
+
h.clock.now += 4 * 60_000;
|
|
182
|
+
await h.monitor.poll(SCHEDULE);
|
|
183
|
+
expect(h.rest.components).toHaveLength(0);
|
|
184
|
+
h.clock.now += 7 * 60_000;
|
|
185
|
+
await h.monitor.poll(SCHEDULE);
|
|
186
|
+
expect(h.rest.components).toHaveLength(1);
|
|
187
|
+
expect(h.rest.components[0].components[0].content).toContain("origin unchecked: the origin check kept failing: arcane: token request failed");
|
|
188
|
+
expect(readSecurityState().pending).toHaveLength(0);
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
it("keeps the cursor when a post fails, so the next check posts it", async () => {
|
|
192
|
+
const h = harness();
|
|
193
|
+
h.answers.set("security wazuh-events", events([wazuh({ id: "f1" })]));
|
|
194
|
+
h.rest.failComponents = true;
|
|
195
|
+
await h.monitor.poll(SCHEDULE);
|
|
196
|
+
expect(readSecurityState().cursor).toBe("2026-10-21T09:51:00.000Z");
|
|
197
|
+
expect(readSecurityState().seen.f1).toBeUndefined();
|
|
198
|
+
h.rest.failComponents = false;
|
|
199
|
+
h.clock.now += 2 * 60_000;
|
|
200
|
+
await h.monitor.poll(SCHEDULE);
|
|
201
|
+
expect(h.calls[1]).toEqual(["security", "wazuh-events", "17", "10"]);
|
|
202
|
+
expect(h.rest.components).toHaveLength(1);
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it("posts a NAS recovery as a notice and warns once when checks keep failing", async () => {
|
|
206
|
+
const h = harness();
|
|
207
|
+
h.answers.set("security wazuh-events", events([wazuh({ id: "n1", rule: "100013", description: "NAS MEDIA access is restored.", path: undefined })]));
|
|
208
|
+
await h.monitor.poll(SCHEDULE);
|
|
209
|
+
expect(h.rest.messages[0].message.content).toContain("โน๏ธ **Security notice**");
|
|
210
|
+
expect(h.rest.messages[0].message.mentionUsers).toBeUndefined();
|
|
211
|
+
h.answers.set("security wazuh-events", () => {
|
|
212
|
+
throw new Error("ssh: connect to host 10.0.90.10 port 22: Connection refused");
|
|
213
|
+
});
|
|
214
|
+
for (let i = 0; i < 16; i++) await h.monitor.poll(SCHEDULE);
|
|
215
|
+
const warnings = h.rest.messages.filter((m) => m.message.content.startsWith("โ ๏ธ **Security checks failing:**"));
|
|
216
|
+
expect(warnings).toHaveLength(1);
|
|
217
|
+
expect(warnings[0].message.mentionUsers).toEqual([OWNER]);
|
|
218
|
+
h.answers.set("security wazuh-events", events([]));
|
|
219
|
+
await h.monitor.poll(SCHEDULE);
|
|
220
|
+
expect(h.rest.messages.at(-1)?.message.content).toBe("โ
**Security checks** read Wazuh alerts again; anything from the gap is checked now.");
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
it("posts health changes: a new problem with a tag, recovery without", async () => {
|
|
224
|
+
const h = harness();
|
|
225
|
+
const attention = (issues: { code: string; message: string }[]) => () => JSON.stringify({ checked_at: "x", bouncer: { count: 1, oldest_pull_seconds: 3 }, wazuh_agents: { total: 8, active: 8 }, health_issues: issues });
|
|
226
|
+
h.answers.set("security attention", attention([]));
|
|
227
|
+
await h.monitor.checkHealth(SCHEDULE);
|
|
228
|
+
expect(h.rest.messages).toHaveLength(0);
|
|
229
|
+
h.answers.set("security attention", attention([{ code: "wazuh-agent:dmz", message: "Wazuh agent dmz is Disconnected." }]));
|
|
230
|
+
await h.monitor.checkHealth(SCHEDULE);
|
|
231
|
+
expect(h.rest.messages[0].message).toMatchObject({ mentionUsers: [OWNER] });
|
|
232
|
+
await h.monitor.checkHealth(SCHEDULE);
|
|
233
|
+
expect(h.rest.messages).toHaveLength(1);
|
|
234
|
+
h.answers.set("security attention", attention([]));
|
|
235
|
+
await h.monitor.checkHealth(SCHEDULE);
|
|
236
|
+
expect(h.rest.messages[1].message).toEqual({ content: "โ
**Security health recovered:** every check is clear again." });
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
it("lets only owners press the buttons, and only on a tracked alert", async () => {
|
|
240
|
+
const h = harness();
|
|
241
|
+
await h.monitor.onButton({ interactionId: "i", token: "t", userId: "999999999999999999", messageId: "m", customId: "security:ack" });
|
|
242
|
+
await h.monitor.onButton({ interactionId: "i", token: "t", userId: OWNER, messageId: "m", customId: "security:nope" });
|
|
243
|
+
await h.monitor.onButton({ interactionId: "i", token: "t", userId: OWNER, messageId: "unknown", customId: "security:investigate" });
|
|
244
|
+
expect(h.rest.replies).toEqual(["Only owners investigate or acknowledge security alerts.", "This button is no longer active.", "This alert is no longer tracked (older than 14 days); ask the security specialist in the channel."]);
|
|
245
|
+
expect(h.rest.deferred).toBe(0);
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
it("investigates in a thread on the alert and marks the button", async () => {
|
|
249
|
+
const h = harness();
|
|
250
|
+
h.answers.set("security wazuh-events", events([wazuh({ id: "a1" })]));
|
|
251
|
+
await h.monitor.poll(SCHEDULE);
|
|
252
|
+
const messageId = readSecurityState().alerts[0].messageId;
|
|
253
|
+
await h.monitor.onButton({ interactionId: "i", token: "t", userId: OWNER, messageId, customId: "security:investigate" });
|
|
254
|
+
expect(h.rest.threads).toEqual([messageId]);
|
|
255
|
+
expect(h.investigations).toHaveLength(1);
|
|
256
|
+
expect(h.investigations[0]).toMatchObject({ threadId: messageId, userId: OWNER });
|
|
257
|
+
expect(h.investigations[0].task).toContain("Read only: change nothing.");
|
|
258
|
+
expect(h.rest.messages[0].channelId).toBe(messageId);
|
|
259
|
+
expect(readSecurityState().alerts[0]).toMatchObject({ investigation: "done", threadId: messageId });
|
|
260
|
+
expect(h.rest.edits.at(-1)?.components[1].components?.[0].label).toBe("Investigate again");
|
|
261
|
+
await h.monitor.onButton({ interactionId: "i", token: "t", userId: OWNER, messageId, customId: "security:investigate" });
|
|
262
|
+
expect(h.rest.threads).toHaveLength(1);
|
|
263
|
+
expect(h.investigations).toHaveLength(2);
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it("re-enables an investigation a restart cut off", async () => {
|
|
267
|
+
const h = harness();
|
|
268
|
+
h.answers.set("security wazuh-events", events([wazuh({ id: "a1" })]));
|
|
269
|
+
await h.monitor.poll(SCHEDULE);
|
|
270
|
+
const state = readSecurityState();
|
|
271
|
+
state.alerts[0].investigation = "running";
|
|
272
|
+
const { writeSecurityState } = await import("./security.ts");
|
|
273
|
+
writeSecurityState(state);
|
|
274
|
+
await h.monitor.closeInterrupted();
|
|
275
|
+
expect(readSecurityState().alerts[0].investigation).toBe("failed");
|
|
276
|
+
expect(h.rest.edits.at(-1)?.components[1].components?.[0].label).toBe("Investigate (retry)");
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
it("skips the daily report on Mondays when the weekly report is configured", async () => {
|
|
280
|
+
const h = harness();
|
|
281
|
+
h.weekly.on = true;
|
|
282
|
+
h.clock.now = Date.parse("2026-10-19T04:05:00Z");
|
|
283
|
+
await h.monitor.dailyReport(SCHEDULE, "2026-10-19");
|
|
284
|
+
expect(readReportState("security")).toEqual({ date: "2026-10-19", status: "skipped" });
|
|
285
|
+
expect(h.calls).toEqual([]);
|
|
286
|
+
expect(h.rest.messages).toEqual([]);
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
it("posts the daily report from the wrapper outputs and moves the vulnerability record forward", async () => {
|
|
290
|
+
const h = harness();
|
|
291
|
+
h.clock.now = Date.parse("2026-10-21T04:05:00Z");
|
|
292
|
+
h.answers.set("security alerts", () => JSON.stringify({ days: 1, count: 2, uniqueIps: 2, repeatIps: 0, daily: [], topIps: [], scenarios: [{ scenario: "37pla/frontdoor-sni-scanning", count: 2 }], latest: [] }));
|
|
293
|
+
h.answers.set("security wazuh-events", events([]));
|
|
294
|
+
h.answers.set("security attention", () => JSON.stringify({ checked_at: "x", bouncer: { count: 1, oldest_pull_seconds: 3 }, wazuh_agents: { total: 8, active: 8 }, health_issues: [] }));
|
|
295
|
+
h.answers.set("security wazuh-vuln-events", () =>
|
|
296
|
+
JSON.stringify({ days: 2, count: 1, events: [{ timestamp: "2026-10-20T20:00:00.000+0000", agent: "dmz", cve: "CVE-1", status: "Active", package: "openssl", version: "3.5.1", severity: "High", score: 7.5, condition: "Package less than 3.5.2" }] }),
|
|
297
|
+
);
|
|
298
|
+
await h.monitor.dailyReport(SCHEDULE, "2026-10-21");
|
|
299
|
+
const text = h.rest.messages[0].message.content;
|
|
300
|
+
expect(text.split("\n")[0]).toBe("**Security Daily Report:** quiet day (24 h to 06:05 CEST)");
|
|
301
|
+
expect(text).toContain("CrowdSec ยท 2 bans, all front door SNI scanning");
|
|
302
|
+
expect(text).toContain("Vulnerabilities ยท 1 new CVE on 1 host: CVE-1 (openssl, High 7.5) on dmz ยท fixed versions exist");
|
|
303
|
+
expect(h.rest.messages[0].message.mentionUsers).toBeUndefined();
|
|
304
|
+
expect(readReportState("security")).toMatchObject({ date: "2026-10-21", status: "sent" });
|
|
305
|
+
expect(readSecurityState().vulns.reported["dmz|CVE-1"]).toMatchObject({ fix: true });
|
|
306
|
+
expect(h.calls.find((c) => c[1] === "wazuh-vuln-events")).toEqual(["security", "wazuh-vuln-events", "2"]);
|
|
307
|
+
});
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
describe("security monitor parsing", () => {
|
|
311
|
+
it("fills ban fields an older wrapper lacks", () => {
|
|
312
|
+
expect(parseAlertSummary({ count: 1, uniqueIps: 1, scenarios: [] })).toMatchObject({ bans: [], escalated: [], countries: [], networks: [] });
|
|
313
|
+
expect(parseAlertSummary({ count: "1" })).toBeNull();
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
it("reads installs, agent restarts, and pending reboots", () => {
|
|
317
|
+
const now = Date.parse("2026-10-20T04:00:00Z");
|
|
318
|
+
const summary = {
|
|
319
|
+
groups: [
|
|
320
|
+
{ rule: "100001", agent: "dmz", count: 7 },
|
|
321
|
+
{ rule: "100001", agent: "identity", count: 3 },
|
|
322
|
+
{ rule: "503", agent: "frontdoor-1337", count: 1, last: "2026-10-19T21:29:57.019+0000" },
|
|
323
|
+
{ rule: "5501", agent: "arcane", count: 30 },
|
|
324
|
+
],
|
|
325
|
+
};
|
|
326
|
+
const reboot = wazuh({ rule: "100010", agent: "dmz", timestamp: "2026-10-19T06:00:00.000+0000" });
|
|
327
|
+
const old = wazuh({ rule: "100010", agent: "identity", timestamp: "2026-10-15T06:00:00.000+0000" });
|
|
328
|
+
expect(patchingFacts(summary, [reboot, old], now)).toEqual({
|
|
329
|
+
installs: [
|
|
330
|
+
{ agent: "dmz", count: 7 },
|
|
331
|
+
{ agent: "identity", count: 3 },
|
|
332
|
+
],
|
|
333
|
+
restarts: [{ agent: "frontdoor-1337", last: "2026-10-19T21:29:57.019+0000" }],
|
|
334
|
+
rebootPending: ["dmz"],
|
|
335
|
+
});
|
|
336
|
+
expect(patchingFacts(null, [], now)).toBeNull();
|
|
337
|
+
});
|
|
338
|
+
});
|