A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.
fix(wazuh): consolidate views and indexer certificate handling (#7211)
Nerdy Technician5c0fc6149639
diff --git a/apps/docs/docs/integrations/wazuh/index.mdx b/apps/docs/docs/integrations/wazuh/index.mdxindex ca402af7b..c2e58a8ec 100644--- a/apps/docs/docs/integrations/wazuh/index.mdx+++ b/apps/docs/docs/integrations/wazuh/index.mdx@@ -11,7 +11,7 @@ import { wazuhIntegration } from ".";<IntegrationHeader integration={wazuhIntegration} categories={["Security"]} />-The Wazuh integration powers the **Wazuh agents**, **Wazuh alerts** and **Wazuh security summary** widgets.+The Wazuh integration powers the [Wazuh widget](/docs/widgets/wazuh), shows high and critical alerts in the [Notifications widget](/docs/widgets/notifications) and provides agent and alert counts to the [Stats widget](/docs/widgets/stats).Wazuh stores data in two places, and each uses its own users:@@ -26,7 +26,7 @@ Alerts and severity counts need the indexer. Without server API credentials, agePick the credential option that matches what you can reach:-| Option | URL field | Widgets |+| Option | URL field | Wazuh widget tabs || ----------------------------------- | -------------------------------------- | --------------------------- || Username & Password | Server API, e.g. `https://wazuh:55000` | Agents, manager version || Username & Password & Indexer … | Server API, indexer URL as a secret | All |@@ -49,5 +49,7 @@ Pick the credential option that matches what you can reach:### Notes-- Wazuh ships with self-signed certificates. The server API certificate can be trusted from the test connection dialog. The indexer certificate is signed by the Wazuh root CA (`/etc/wazuh-indexer/certs/root-ca.pem`), which has to be uploaded under **Settings → Certificates**.+- Wazuh ships with self-signed certificates, and the server API and the indexer each present their own. **Test connection** checks both endpoints and shows the certificate of whichever one fails, so the server API and the indexer certificate can both be handled from the same dialog: trust a self-signed certificate directly, or, when the certificate is signed by the Wazuh root CA, upload that CA (`/etc/wazuh-indexer/certs/root-ca.pem`) from the dialog. Run Test connection again afterwards to check the other endpoint. You can also upload the root CA up front under **Management → Tools → Certificates**.+- If the certificate is not issued for the host in the URL, Test connection offers to trust that hostname. Otherwise use a hostname or IP address listed in the certificate, or reissue the certificate with the name you use.+- An expired or not yet valid certificate cannot be trusted. Renew it and check that the clocks on the Homarr and Wazuh hosts are correct.- A default all-in-one install binds the indexer to `127.0.0.1`. Set `network.host` in `/etc/wazuh-indexer/opensearch.yml` if Homarr runs on another host.diff --git a/apps/docs/docs/widgets/notifications/index.mdx b/apps/docs/docs/widgets/notifications/index.mdxindex 93f4af04b..a2feb92f7 100644--- a/apps/docs/docs/widgets/notifications/index.mdx+++ b/apps/docs/docs/widgets/notifications/index.mdx@@ -12,6 +12,7 @@ import { notificationsWidget } from ".";import { ntfyIntegration } from "@site/docs/integrations/ntfy";import { nextcloudIntegration } from "@site/docs/integrations/nextcloud";import { gotifyIntegration } from "@site/docs/integrations/gotify";+import { wazuhIntegration } from "@site/docs/integrations/wazuh";<WidgetHeader widget={notificationsWidget} categories={["Notifications", "Messaging"]} />@@ -21,7 +22,12 @@ available service icons.### Supported Integrations<WidgetIntegrations- items={[{ integration: ntfyIntegration }, { integration: nextcloudIntegration }, { integration: gotifyIntegration }]}+ items={[+ { integration: ntfyIntegration },+ { integration: nextcloudIntegration },+ { integration: gotifyIntegration },+ { integration: wazuhIntegration },+ ]}/>### Adding the widgetdiff --git a/apps/docs/docs/widgets/stats/index.mdx b/apps/docs/docs/widgets/stats/index.mdxindex 2108ffb3b..9f56dacb8 100644--- a/apps/docs/docs/widgets/stats/index.mdx+++ b/apps/docs/docs/widgets/stats/index.mdx@@ -35,7 +35,7 @@ Opening a board reuses saved data. Multiple metrics from the same integration sh## New service integrations in v2-These 31 integrations work with Statistics, alongside existing providers such as Sonarr, Radarr, Paperless-ngx and Navidrome. The metric picker shows what's available for each source.+These 32 integrations work with Statistics, alongside existing providers such as Sonarr, Radarr, Paperless-ngx and Navidrome. The metric picker shows what's available for each source.<details><summary>Integration setup guides and available metrics</summary>@@ -73,5 +73,8 @@ These 31 integrations work with Statistics, alongside existing providers such as| [Komga](/docs/integrations/komga) | Libraries, series, books || [NetAlertX](/docs/integrations/netalertx) | Total, connected, new, down alerts || [Jackett](/docs/integrations/jackett) | Configured indexers; existing indexer widget |+| [Wazuh](/docs/integrations/wazuh) | Agents (total, active, disconnected); alerts (total, high, critical) |</details>++Wazuh alert metrics cover the last 24 hours and require indexer credentials. Agent metrics also work with server API credentials alone.diff --git a/apps/docs/docs/widgets/wazuh/index.mdx b/apps/docs/docs/widgets/wazuh/index.mdxnew file mode 100644index 000000000..83650b486--- /dev/null+++ b/apps/docs/docs/widgets/wazuh/index.mdx@@ -0,0 +1,65 @@+---+title: "Wazuh"+description: "Wazuh security overview with tabs for severity, alerts, timeline, top lists, agents, vulnerabilities, file integrity and authentication failures."+hide_title: true+---++import { WidgetInteractionGuide } from "@site/src/components/widgets/interactions";++import { WidgetHeader } from "@site/src/components/widgets/header";+import { AddingWidget } from "@site/src/components/widgets/adding";+import { WidgetConfig } from "@site/src/components/widgets/configuration";+import { WidgetIntegrations } from "@site/src/components/widgets/integrations";+import { wazuhWidget } from ".";+import { wazuhIntegration } from "@site/docs/integrations/wazuh";++<WidgetHeader widget={wazuhWidget} categories={["Security", "Monitoring"]} />++One widget for a Wazuh deployment. Hover the widget to show the tab switcher at the top; on touch devices it stays visible. The selected tab is saved with the widget, so the board opens on the same tab next time. Use **Visible tabs** to offer only some tabs, or pick a single tab to pin the widget to one view and hide the switcher.++Legacy Wazuh widgets are not automatically converted and no longer load. Replace them with the consolidated Wazuh widget.++| Tab | Shows |+| --------------- | ------------------------------------------------------------------------------------------------------- |+| Severity | Alerts in the time range split by severity, with the change against the previous period of equal length |+| Alerts | Recent alerts at or above a rule level with rule IDs, MITRE ATT&CK techniques, agent and source IP |+| Timeline | Stacked chart of alerts over time by severity |+| Top lists | Top rules, agents, source IPs or MITRE ATT&CK tactics and techniques by alert count |+| Agents | Agent status tiles and a sortable, reorderable and resizable agent table |+| Vulnerabilities | Vulnerability counts by severity, top CVEs and the most vulnerable agents |+| File integrity | Recent file integrity monitoring (syscheck) events |+| Auth failures | Failed logins and brute-force alerts per agent with sparklines and top source IPs |++Wazuh rule levels are grouped into four severities: **low** (0-6), **medium** (7-11), **high** (12-14) and **critical** (15 and above).++The Wazuh integration also feeds other widgets:++- [Notifications](/docs/widgets/notifications) lists recent high and critical alerts.+- [Stats](/docs/widgets/stats) offers agent counts and 24-hour alert counts as metrics.++### Supported Integrations++<WidgetIntegrations+ items={[+ {+ integration: wazuhIntegration,+ note: "Agents use the server API or the indexer; every other tab reads from the indexer",+ },+ ]}+/>++### Requirements++Alerts, vulnerabilities and file integrity events come from the Wazuh **indexer** (`wazuh-alerts-*`, `wazuh-states-vulnerabilities-*`). The agents tab works with server API credentials alone, or with indexer credentials using the latest `wazuh-monitoring-*` snapshot. See the [Wazuh integration](/docs/integrations/wazuh) for the credential options, certificates and the optional dashboard URL used for links.++<WidgetInteractionGuide advancedView={false} />++### Adding the widget++<AddingWidget />++### Configuration++Options that only affect one tab name that tab in their description.++<WidgetConfig configuration={wazuhWidget.configuration} />diff --git a/apps/docs/docs/widgets/wazuh/index.ts b/apps/docs/docs/widgets/wazuh/index.tsnew file mode 100644index 000000000..6f8a477c5--- /dev/null+++ b/apps/docs/docs/widgets/wazuh/index.ts@@ -0,0 +1,249 @@+import { WidgetDefinition } from "@site/src/types";+import { IconShieldHalfFilled } from "@tabler/icons-react";++const timeRanges = ["Last hour", "Last 24 hours", "Last 7 days", "Last 30 days"];++export const wazuhWidget: WidgetDefinition = {+ icon: IconShieldHalfFilled,+ name: "Wazuh",+ description:+ "Wazuh security overview with tabs for severity, alerts, timeline, top lists, agents, vulnerabilities, file integrity and authentication failures.",+ path: "../../widgets/wazuh",+ configuration: {+ items: [+ {+ name: "Visible tabs",+ description:+ "Tabs offered in the switcher. With a single tab the switcher is hidden, so the widget shows only that view.",+ values: {+ type: "select",+ options: [+ "Severity",+ "Alerts",+ "Timeline",+ "Top lists",+ "Agents",+ "Vulnerabilities",+ "File integrity",+ "Auth failures",+ ],+ },+ defaultValue: "All",+ },+ {+ name: "Time range",+ description:+ "Period used by the severity, alerts, timeline, top lists, file integrity and auth failures tabs. Agents and vulnerabilities always show the current state.",+ values: { type: "select", options: timeRanges },+ defaultValue: "Last 24 hours",+ },+ {+ name: "Minimum rule level (timeline and top lists)",+ description: "Ignore alerts below this Wazuh rule level.",+ values: "0-16",+ defaultValue: "0",+ },+ {+ name: "Show trend against the previous period",+ description: "Severity tab: show the change against the period right before the selected one.",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Show footer",+ description: "Severity tab: show the previous total, the highest rule level and the indexer health.",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Alerts: minimum rule level",+ description: "Alerts tab: only list alerts at or above this Wazuh rule level.",+ values: "0-16",+ defaultValue: "7",+ },+ {+ name: "Alerts: number of alerts",+ description: "Alerts tab: number of alerts listed.",+ values: "1-100",+ defaultValue: "25",+ },+ {+ name: "Show MITRE ATT&CK techniques",+ description: "Alerts tab: show technique tags on each alert.",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Show agent",+ description: "Alerts tab.",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Show source IP",+ description: "Alerts tab.",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Show rule ID",+ description: "Alerts tab.",+ values: { type: "boolean" },+ defaultValue: "no",+ },+ {+ name: "Interval",+ description: "Timeline tab: bucket size of the chart. Automatic picks one from the time range.",+ values: {+ type: "select",+ options: [+ "Automatic",+ "1 minute",+ "5 minutes",+ "15 minutes",+ "30 minutes",+ "1 hour",+ "3 hours",+ "6 hours",+ "12 hours",+ "1 day",+ ],+ },+ defaultValue: "Automatic",+ },+ {+ name: "Chart type",+ description: "Timeline tab: stacked area or stacked bars.",+ values: { type: "select", options: ["Stacked area", "Stacked bars"] },+ defaultValue: "Stacked area",+ },+ {+ name: "Y axis scale",+ description: "Timeline tab: square root keeps high and critical alerts visible next to thousands of low ones.",+ values: { type: "select", options: ["Linear", "Square root"] },+ defaultValue: "Linear",+ },+ {+ name: "Show legend with totals",+ description: "Timeline tab: show the totals per severity under the chart.",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Rank",+ description: "Top lists tab: what to rank by alert count.",+ values: {+ type: "select",+ options: [+ "Top rules",+ "Top agents by alerts",+ "Top source IPs",+ "Top MITRE ATT&CK tactics",+ "Top MITRE ATT&CK techniques",+ ],+ },+ defaultValue: "Top rules",+ },+ {+ name: "Top list entries",+ description: "Top lists tab: number of entries.",+ values: "1-50",+ defaultValue: "8",+ },+ {+ name: "Show bars",+ description: "Top lists tab: show a bar per entry.",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Show agents",+ description: "Agents tab: the status filter applied when the board loads. The status tiles toggle it.",+ values: { type: "select", options: ["All agents", "Active", "Disconnected", "Not active"] },+ defaultValue: "All agents",+ },+ {+ name: "Sort by",+ description:+ "Agents tab: initial sort column. Click a column header to sort, drag headers to reorder and drag edges to resize; the layout is saved with the widget.",+ values: {+ type: "select",+ options: ["Status", "Name", "IP address", "Operating system", "Wazuh version", "Last keepalive"],+ },+ defaultValue: "Status",+ },+ {+ name: "Agents: show Wazuh version column",+ description: "Agents tab: outdated agents are highlighted.",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Agents: show groups column",+ description: "Agents tab.",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Rank CVEs by",+ description: "Vulnerabilities tab.",+ values: { type: "select", options: ["Highest score", "Most affected agents"] },+ defaultValue: "Highest score",+ },+ {+ name: "CVE severity",+ description: "Vulnerabilities tab: lowest severity listed.",+ values: { type: "select", options: ["All severities", "Medium and above", "High and above", "Critical only"] },+ defaultValue: "All severities",+ },+ {+ name: "Number of CVEs",+ description: "Vulnerabilities tab: CVEs listed.",+ values: "1-50",+ defaultValue: "8",+ },+ {+ name: "Number of agents",+ description: "Vulnerabilities tab: most vulnerable agents listed.",+ values: "1-50",+ defaultValue: "5",+ },+ {+ name: "Show most vulnerable agents",+ description: "Vulnerabilities tab.",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Events",+ description: "File integrity tab: which syscheck events to list.",+ values: { type: "select", options: ["All events", "Added", "Modified", "Deleted"] },+ defaultValue: "All events",+ },+ {+ name: "File integrity events",+ description: "File integrity tab: number of events.",+ values: "1-100",+ defaultValue: "20",+ },+ {+ name: "Include Windows registry events",+ description: "File integrity tab.",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Authentication failure agents",+ description: "Auth failures tab: number of agents listed.",+ values: "1-25",+ defaultValue: "6",+ },+ {+ name: "Show top source IPs",+ description: "Auth failures tab.",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ ],+ },+};diff --git a/apps/docs/public/api/open-api-schema.json b/apps/docs/public/api/open-api-schema.jsonindex 5665963a2..cbc6acae8 100644--- a/apps/docs/public/api/open-api-schema.json+++ b/apps/docs/public/api/open-api-schema.json@@ -3155,14 +3155,7 @@"assistant","wud","llamacpp",- "wazuhAgents",- "wazuhAlerts",- "wazuhSummary",- "wazuhTimeline",- "wazuhTopList",- "wazuhVulnerabilities",- "wazuhFim",- "wazuhAuthFailures"+ "wazuh"]},"options": {@@ -3434,14 +3427,7 @@"assistant","wud","llamacpp",- "wazuhAgents",- "wazuhAlerts",- "wazuhSummary",- "wazuhTimeline",- "wazuhTopList",- "wazuhVulnerabilities",- "wazuhFim",- "wazuhAuthFailures"+ "wazuh"]},"options": {diff --git a/apps/nextjs/src/app/[locale]/manage/integrations/_components/test-connection/test-connection-certificate.tsx b/apps/nextjs/src/app/[locale]/manage/integrations/_components/test-connection/test-connection-certificate.tsxindex 40fc4d596..17b2cf8a3 100644--- a/apps/nextjs/src/app/[locale]/manage/integrations/_components/test-connection/test-connection-certificate.tsx+++ b/apps/nextjs/src/app/[locale]/manage/integrations/_components/test-connection/test-connection-certificate.tsx@@ -32,9 +32,12 @@ export const CertificateErrorDetails = ({ error, url }: CertificateErrorDetailsPclientApi.certificates.addCertificate.useMutation();const rootCertificate = getHeighestCertificate(error.data.certificate);+ // The certificate can belong to a secondary endpoint of the integration (for example a separate indexer URL).+ const certificateUrl = error.data.url;+ const isSecondaryUrl = getOrigin(certificateUrl) !== getOrigin(url);const handleTrustHostname = async () => {- const { hostname } = new URL(url);+ const { hostname } = new URL(certificateUrl);await trustHostnameAsync({hostname,@@ -59,7 +62,7 @@ export const CertificateErrorDetails = ({ error, url }: CertificateErrorDetailsP};const handleTrustSelfSigned = async () => {- const { hostname } = new URL(url);+ const { hostname } = new URL(certificateUrl);const formData = new FormData();formData.append("file",@@ -84,7 +87,16 @@ export const CertificateErrorDetails = ({ error, url }: CertificateErrorDetailsP});};- const description = <Text size="md">{tError(`certificate.description.${error.data.reason}`)}</Text>;+ const description = (+ <>+ <Text size="md">{tError(`certificate.description.${error.data.reason}`)}</Text>+ {isSecondaryUrl && (+ <Text size="sm" c="dimmed">+ {tError("certificate.secondaryUrl", { url: certificateUrl })}+ </Text>+ )}+ </>+ );let trustConfirmLabel = tError("certificate.selfSigned.confirm.title");if (error.data.reason === "hostnameMismatch") {trustConfirmLabel = tError("certificate.hostnameMismatch.confirm.title");@@ -324,6 +336,14 @@ const PemContentModal = createModal<{ content: string }>(({ actions, innerPropssize: "lg",});+const getOrigin = (value: string) => {+ try {+ return new URL(value).origin;+ } catch {+ return value;+ }+};+const getHeighestCertificate = (certificate: MappedCertificate): MappedCertificate => {if (certificate.issuerCertificate) return getHeighestCertificate(certificate.issuerCertificate);return certificate;diff --git a/packages/api/src/router/integration/map-test-connection-error.ts b/packages/api/src/router/integration/map-test-connection-error.tsindex d0805b6ec..d66a5a11a 100644--- a/packages/api/src/router/integration/map-test-connection-error.ts+++ b/packages/api/src/router/integration/map-test-connection-error.ts@@ -64,6 +64,7 @@ type MappedData<TType extends TestConnectionErrorType> = TType extends "unknown"type: TestConnectionErrorDataOfType<TType>["requestError"]["type"];reason: TestConnectionErrorDataOfType<TType>["requestError"]["reason"];certificate: MappedCertificate;+ url: TestConnectionErrorDataOfType<TType>["url"];}: TType extends "request"? {@@ -95,6 +96,7 @@ const mapData = (error: AnyTestConnectionError): AnyMappedData => {type: error.data.requestError.type,reason: error.data.requestError.reason,certificate: mapCertificate(error.data.certificate, error.data.requestError.code),+ url: error.data.url,};}if (error.type === "request") {diff --git a/packages/api/src/router/widgets/wazuh.ts b/packages/api/src/router/widgets/wazuh.tsindex f6302d20b..0b0fbb11b 100644--- a/packages/api/src/router/widgets/wazuh.ts+++ b/packages/api/src/router/widgets/wazuh.ts@@ -88,7 +88,7 @@ const mockResult = <TData>(data: TData): WazuhResult<TData> => ({const integrationIdHint = "REQUIRED: integrationId (single Wazuh integration ID from integration_all).";const indexerHint = "Requires indexer credentials on the integration.";-const wazuhProcedure = (widgetKind: WidgetKind & `wazuh${string}`, description: string) =>+const wazuhProcedure = (widgetKind: WidgetKind & "wazuh", description: string) =>publicProcedure.meta({ mcp: { enabled: true, description: `${description} ${integrationIdHint}` } }).concat(createOneWidgetIntegrationMiddleware("query", widgetKind));@@ -97,7 +97,7 @@ const timeRange = z.enum(wazuhTimeRanges);export const wazuhRouter = createTRPCRouter({getAgents: wazuhProcedure(- "wazuhAgents",+ "wazuh","Get Wazuh agent counts and the full agent list (status, IP, OS, version, last keepalive, groups).",).query(async ({ ctx }) => {if (ctx.integration.kind === "mock") return mockResult(mockWidgetData.wazuhAgents);@@ -106,7 +106,7 @@ export const wazuhRouter = createTRPCRouter({wazuhAgentsRequestHandler.handler(integration, {}).getDataAsync(),);}),- getAlerts: wazuhProcedure("wazuhAlerts", `Get recent Wazuh alerts at or above a rule level. ${indexerHint}`)+ getAlerts: wazuhProcedure("wazuh", `Get recent Wazuh alerts at or above a rule level. ${indexerHint}`).input(z.object({minLevel: z.number().int().min(0).max(16).default(7),@@ -124,7 +124,7 @@ export const wazuhRouter = createTRPCRouter({);}),getSummary: wazuhProcedure(- "wazuhSummary",+ "wazuh","Get Wazuh alert counts by severity for a time range compared with the previous period, plus manager version and indexer health.",).input(z.object({ range: timeRange.default("24h") }))@@ -136,7 +136,7 @@ export const wazuhRouter = createTRPCRouter({);}),getTimeline: wazuhProcedure(- "wazuhTimeline",+ "wazuh",`Get a histogram of Wazuh alerts over time split by severity (low, medium, high, critical). ${indexerHint}`,).input(@@ -154,7 +154,7 @@ export const wazuhRouter = createTRPCRouter({);}),getTopList: wazuhProcedure(- "wazuhTopList",+ "wazuh",`Get the top Wazuh rules, agents, source IPs, MITRE ATT&CK tactics or techniques by alert count. ${indexerHint}`,).input(@@ -173,7 +173,7 @@ export const wazuhRouter = createTRPCRouter({);}),getVulnerabilities: wazuhProcedure(- "wazuhVulnerabilities",+ "wazuh",`Get Wazuh vulnerability counts by severity, the top CVEs and the most vulnerable agents. ${indexerHint}`,).input(@@ -192,7 +192,7 @@ export const wazuhRouter = createTRPCRouter({);}),getFim: wazuhProcedure(- "wazuhFim",+ "wazuh",`Get recent Wazuh file integrity monitoring (syscheck) events with counts per event type. ${indexerHint}`,).input(@@ -211,12 +211,12 @@ export const wazuhRouter = createTRPCRouter({);}),getAuthFailures: wazuhProcedure(- "wazuhAuthFailures",+ "wazuh",`Get failed-login and brute-force alert counts per agent with hourly series and top source IPs. ${indexerHint}`,).input(z.object({- hours: z.number().int().min(1).max(168).default(24),+ hours: z.number().int().min(1).max(720).default(24),limit: z.number().int().min(1).max(25).default(6),}),)diff --git a/packages/definitions/src/docs/homarr-docs-sitemap.ts b/packages/definitions/src/docs/homarr-docs-sitemap.tsindex ddc6cedc5..403a3cf9a 100644--- a/packages/definitions/src/docs/homarr-docs-sitemap.ts+++ b/packages/definitions/src/docs/homarr-docs-sitemap.ts@@ -285,6 +285,7 @@ export type HomarrDocumentationPath =| "/docs/widgets/uptime-kuma"| "/docs/widgets/video"| "/docs/widgets/vpn"+ | "/docs/widgets/wazuh"| "/docs/widgets/weather"| "/docs/widgets/whats-up-docker"| "/docs/workshop"diff --git a/packages/definitions/src/docs/widget-doc-slugs.ts b/packages/definitions/src/docs/widget-doc-slugs.tsindex a3b502eb8..4e64405e2 100644--- a/packages/definitions/src/docs/widget-doc-slugs.ts+++ b/packages/definitions/src/docs/widget-doc-slugs.ts@@ -66,12 +66,5 @@ export const widgetDocSlugs = {assistant: "assistant",wud: "whats-up-docker",llamacpp: "llama-cpp",- wazuhAgents: null,- wazuhAlerts: null,- wazuhSummary: null,- wazuhTimeline: null,- wazuhTopList: null,- wazuhVulnerabilities: null,- wazuhFim: null,- wazuhAuthFailures: null,+ wazuh: "wazuh",} satisfies Record<WidgetKind, string | null>;diff --git a/packages/definitions/src/integration.ts b/packages/definitions/src/integration.tsindex 373238bc6..fe7aab5a7 100644--- a/packages/definitions/src/integration.ts+++ b/packages/definitions/src/integration.ts@@ -1008,7 +1008,7 @@ export const integrationDefs = {// Used for deep links from the widgets into the Wazuh dashboard.optionalSecretKinds: ["wazuhDashboardUrl"],iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/wazuh.svg",- category: ["security"],+ category: ["security", "notifications"],documentationSlug: "wazuh",defaultPort: 55000,features: { docker: { aliases: ["wazuh", "wazuh-manager", "wazuh.manager"] } },diff --git a/packages/definitions/src/test/widget-integration-map.spec.ts b/packages/definitions/src/test/widget-integration-map.spec.tsindex be2734267..a1833c7ae 100644--- a/packages/definitions/src/test/widget-integration-map.spec.ts+++ b/packages/definitions/src/test/widget-integration-map.spec.ts@@ -53,14 +53,7 @@ describe("widget integration config", () => {anchorNote: 1,wud: 1,llamacpp: 1,- wazuhAgents: 1,- wazuhAlerts: 1,- wazuhSummary: 1,- wazuhTimeline: 1,- wazuhTopList: 1,- wazuhVulnerabilities: 1,- wazuhFim: 1,- wazuhAuthFailures: 1,+ wazuh: 1,});});});diff --git a/packages/definitions/src/widget-integration-map.ts b/packages/definitions/src/widget-integration-map.tsindex a5e2ab127..96f69b529 100644--- a/packages/definitions/src/widget-integration-map.ts+++ b/packages/definitions/src/widget-integration-map.ts@@ -119,6 +119,7 @@ export const statsIntegrationKinds = ["archiveTeamWarrior","wud","llamacpp",+ "wazuh","mock",] as const satisfies readonly IntegrationKind[];@@ -184,14 +185,7 @@ export const widgetIntegrationConfigs = {traefik: { supportedIntegrations: ["traefik", "mock"] },wud: { supportedIntegrations: ["wud", "mock"], maxIntegrations: 1 },llamacpp: { supportedIntegrations: ["llamacpp", "mock"], maxIntegrations: 1 },- wazuhAgents: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },- wazuhAlerts: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },- wazuhSummary: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },- wazuhTimeline: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },- wazuhTopList: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },- wazuhVulnerabilities: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },- wazuhFim: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },- wazuhAuthFailures: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },+ wazuh: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },} satisfies Partial<Record<WidgetKind, WidgetIntegrationConfig>>;export type WidgetKindWithIntegration = keyof typeof widgetIntegrationConfigs;diff --git a/packages/definitions/src/widget.ts b/packages/definitions/src/widget.tsindex f84fbbf74..8d70d275a 100644--- a/packages/definitions/src/widget.ts+++ b/packages/definitions/src/widget.ts@@ -64,14 +64,7 @@ export const widgetKinds = ["assistant","wud","llamacpp",- "wazuhAgents",- "wazuhAlerts",- "wazuhSummary",- "wazuhTimeline",- "wazuhTopList",- "wazuhVulnerabilities",- "wazuhFim",- "wazuhAuthFailures",+ "wazuh",] as const;export type WidgetKind = (typeof widgetKinds)[number];@@ -101,12 +94,5 @@ export const widgetDefaultSizes: Partial<Record<WidgetKind, { width: number; heimediaMissing: { width: 2, height: 2 },bazarr: { width: 2, height: 2 },assistant: { width: 10, height: 4 },- wazuhAgents: { width: 6, height: 4 },- wazuhAlerts: { width: 4, height: 4 },- wazuhSummary: { width: 3, height: 3 },- wazuhTimeline: { width: 6, height: 3 },- wazuhTopList: { width: 3, height: 3 },- wazuhVulnerabilities: { width: 4, height: 4 },- wazuhFim: { width: 4, height: 3 },- wazuhAuthFailures: { width: 4, height: 3 },+ wazuh: { width: 4, height: 3 },};diff --git a/packages/integrations/src/base/errors/http/integration-request-error.ts b/packages/integrations/src/base/errors/http/integration-request-error.tsindex 2f5c9e934..0dbaf1b56 100644--- a/packages/integrations/src/base/errors/http/integration-request-error.ts+++ b/packages/integrations/src/base/errors/http/integration-request-error.ts@@ -8,9 +8,21 @@ export type IntegrationRequestErrorOfType<TType extends RequestErrorType> = Inte};export class IntegrationRequestError extends IntegrationError {- constructor(integration: IntegrationErrorData, { cause }: { cause: AnyRequestError }) {+ /**+ * URL of the endpoint the failed request was sent to. Defaults to the integration URL. Integrations that also talk+ * to a secondary endpoint (for example a separate indexer URL) set it, so that test connection inspects and offers+ * to trust the certificate of the endpoint that actually failed.+ */+ readonly #requestUrl: string;++ constructor(integration: IntegrationErrorData, { cause, url }: { cause: AnyRequestError; url?: string }) {super(integration, "Request to integration failed", { cause });this.name = IntegrationRequestError.name;+ this.#requestUrl = url ?? integration.url;+ }++ get requestUrl(): string {+ return this.#requestUrl;}get cause(): AnyRequestError {diff --git a/packages/integrations/src/base/test-connection/test-connection-error.ts b/packages/integrations/src/base/test-connection/test-connection-error.tsindex ffe5f240c..a7176e88a 100644--- a/packages/integrations/src/base/test-connection/test-connection-error.ts+++ b/packages/integrations/src/base/test-connection/test-connection-error.ts@@ -52,12 +52,13 @@ export class TestConnectionError<TType extends TestConnectionErrorType> extendsreturn this.Unknown(cause).toResult();}- private static Certificate(requestError: RequestError<"certificate">, certificate: X509Certificate) {+ private static Certificate(requestError: RequestError<"certificate">, certificate: X509Certificate, url: string) {return new TestConnectionError("certificate",{requestError,certificate,+ url,},{cause: requestError,@@ -65,8 +66,16 @@ export class TestConnectionError<TType extends TestConnectionErrorType> extends);}- public static CertificateResult(requestError: RequestError<"certificate">, certificate: X509Certificate) {- return this.Certificate(requestError, certificate).toResult();+ /**+ * @param url the URL whose certificate failed validation. It can differ from the integration URL when an+ * integration also requests a secondary endpoint.+ */+ public static CertificateResult(+ requestError: RequestError<"certificate">,+ certificate: X509Certificate,+ url: string,+ ) {+ return this.Certificate(requestError, certificate, url).toResult();}private static Authorization(statusCode: number) {@@ -169,6 +178,8 @@ interface TestConnectionErrorMap {certificate: {requestError: RequestError<"certificate">;certificate: X509Certificate;+ /** URL of the endpoint that presented the certificate. */+ url: string;};request: {requestError: Exclude<AnyRequestError, RequestError<"certificate">>;diff --git a/packages/integrations/src/base/test-connection/test-connection-service.ts b/packages/integrations/src/base/test-connection/test-connection-service.tsindex 4874d706d..12ee99388 100644--- a/packages/integrations/src/base/test-connection/test-connection-service.ts+++ b/packages/integrations/src/base/test-connection/test-connection-service.ts@@ -1,4 +1,5 @@import type { X509Certificate } from "node:crypto";+import net from "node:net";import tls from "node:tls";import { getPortFromUrl } from "@homarr/common";@@ -37,7 +38,7 @@ export class TestConnectionService {public async handleAsync(testingCallbackAsync: AsyncTestingCallback) {logger.debug("Testing connection", {- url: this.url.toString(),+ url: this.url.origin,});const testingResult = await testingCallbackAsync({@@ -73,14 +74,14 @@ export class TestConnectionService {if (testingResult.success) {logger.debug("Testing connection succeeded", {- url: this.url.toString(),+ url: this.url.origin,});return testingResult;}logger.debug("Testing connection failed", {- url: this.url.toString(),+ url: this.url.origin,error: `${testingResult.error.name}: ${testingResult.error.message}`,});@@ -88,27 +89,47 @@ export class TestConnectionService {return testingResult.error.toResult();}- const certificate = await this.fetchCertificateAsync();+ // The failing request may target a secondary endpoint (for example a separate indexer URL), so the+ // certificate has to be read from the URL of that request and not from the integration URL.+ // Certificate inspection only needs the origin. Keep credentials, paths and query parameters out of diagnostics.+ const certificateUrl = new URL(this.getCertificateUrl(testingResult.error).origin);+ const certificate = await this.fetchCertificateAsync(certificateUrl).catch((error: unknown) => {+ logger.debug("Fetching certificate failed", {+ url: certificateUrl.toString(),+ error: error instanceof Error ? `${error.name}: ${error.message}` : String(error),+ });+ return undefined;+ });if (!certificate) {return TestConnectionError.UnknownResult(new Error("Unable to fetch certificate"));}- return TestConnectionError.CertificateResult(testingResult.error.cause, certificate);+ return TestConnectionError.CertificateResult(testingResult.error.cause, certificate, certificateUrl.toString());+ }++ private getCertificateUrl(error: IntegrationRequestErrorOfType<"certificate">): URL {+ try {+ return new URL(error.requestUrl);+ } catch {+ return this.url;+ }}- private async fetchCertificateAsync(): Promise<X509Certificate | undefined> {+ private async fetchCertificateAsync(url: URL): Promise<X509Certificate | undefined> {logger.debug("Fetching certificate", {- url: this.url.toString(),+ url: url.toString(),});- const url = this.url;+ // URL.hostname keeps the brackets of IPv6 literals, tls.connect expects the bare address.+ const host = url.hostname.replace(/^\[(.*)\]$/, "$1");const port = getPortFromUrl(url);const socket = await new Promise<tls.TLSSocket>((resolve, reject) => {try {const innerSocket = tls.connect({- host: url.hostname,- servername: url.hostname,+ host,+ // SNI must not be an IP address (RFC 6066)+ ...(net.isIP(host) === 0 ? { servername: host } : {}),port,rejectUnauthorized: false,},@@ -116,6 +137,9 @@ export class TestConnectionService {resolve(innerSocket);},);+ innerSocket.once("error", (error) => {+ reject(new Error("Unable to fetch certificate", { cause: error }));+ });} catch (error) {reject(new Error("Unable to fetch certificate", { cause: error }));}@@ -125,7 +149,7 @@ export class TestConnectionService {socket.destroy();logger.debug("Fetched certificate", {- url: this.url.toString(),+ url: url.toString(),subject: x509?.subject,issuer: x509?.issuer,});diff --git a/packages/integrations/src/stats/existing.ts b/packages/integrations/src/stats/existing.tsindex bcdb916c5..05c867e91 100644--- a/packages/integrations/src/stats/existing.ts+++ b/packages/integrations/src/stats/existing.ts@@ -453,6 +453,33 @@ for (const kind of ["lidarr", "readarr"] as const) {(data) => data,);}+existingStatsProviders.wazuh = adapter(+ "wazuh",+ [+ metric("agents", "Agents"),+ metric("activeAgents", "Active agents"),+ metric("disconnectedAgents", "Disconnected agents"),+ metric("alerts24h", "Alerts (24h)"),+ metric("highAlerts24h", "High alerts (24h)"),+ metric("criticalAlerts24h", "Critical alerts (24h)"),+ ],+ async (client) => {+ const [agents, summary] = await Promise.all([+ client.getAgentsOverviewAsync(),+ // Alert counts need the indexer; agent counts still work with server API credentials only.+ client.getSecuritySummaryAsync({ range: "24h" }).catch(() => null),+ ]);+ return { agents: agents.counts, alerts: summary?.alerts ?? null };+ },+ ({ agents, alerts }) => ({+ agents: agents.total,+ activeAgents: agents.active,+ disconnectedAgents: agents.disconnected,+ alerts24h: alerts?.total ?? null,+ highAlerts24h: alerts?.high ?? null,+ criticalAlerts24h: alerts?.critical ?? null,+ }),+);existingStatsProviders.mock = {metrics: [metric("documents", "Documents"), metric("songs", "Songs"), metric("storage", "Storage", "bytes")],async fetchAsync() {diff --git a/packages/integrations/src/wazuh/test/wazuh-integration.spec.ts b/packages/integrations/src/wazuh/test/wazuh-integration.spec.tsnew file mode 100644index 000000000..9a06f1c7d--- /dev/null+++ b/packages/integrations/src/wazuh/test/wazuh-integration.spec.ts@@ -0,0 +1,296 @@+// @vitest-environment node+import { X509Certificate } from "node:crypto";+import tls from "node:tls";+import { Response } from "undici";+import { beforeEach, describe, expect, test, vi } from "vitest";++import type { IntegrationSecretKind } from "@homarr/definitions";++import { toWazuhPublicError, WazuhRequestError } from "../wazuh-errors";+import { WazuhIntegration } from "../wazuh-integration";++vi.hoisted(() => {+ process.env.SKIP_ENV_VALIDATION = "true";+ process.env.SECRET_ENCRYPTION_KEY = "ff3f4f7ce30e870c9630de9e5d244ffa81101a24ed0dfe5f064beb53a7e684f1";+ process.env.ENABLE_DNS_CACHING = "false";+});++const { testFetchMock, trustedFetchMock } = vi.hoisted(() => ({+ testFetchMock: vi.fn(),+ trustedFetchMock: vi.fn(),+}));++// Test connection uses undici fetch with a dispatcher built from the trusted certificates.+vi.mock("undici", async (importActual) => ({+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports+ ...(await importActual<typeof import("undici")>()),+ fetch: testFetchMock,+}));++vi.mock("@homarr/redis", () => ({+ getIntegrationSessionStoreKey: (integrationId: string) => `session-store:${integrationId}`,+ createGetSetChannel: () => ({+ getAsync: () => Promise.resolve(null),+ setAsync: () => Promise.resolve(),+ removeAsync: () => Promise.resolve(),+ }),+}));++vi.mock("@homarr/core/infrastructure/logs", () => ({+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));++vi.mock("@homarr/core/infrastructure/http", () => ({+ fetchWithTrustedCertificatesAsync: trustedFetchMock,+ createAxiosCertificateInstanceAsync: vi.fn().mockResolvedValue({}),+ createCertificateAgentAsync: vi.fn().mockResolvedValue({ close: vi.fn() }),+ createCustomCheckServerIdentity: vi.fn(() => () => undefined),+}));++vi.mock("@homarr/core/infrastructure/certificates", () => ({+ getAllTrustedCertificatesAsync: vi.fn().mockResolvedValue([]),+ getTrustedCertificateHostnamesAsync: vi.fn().mockResolvedValue([]),+}));++const API_URL = "https://wazuh-manager.example.com:55000";+const INDEXER_URL = "https://wazuh-indexer.example.com:9200";++const createIntegration = (+ url: string,+ secrets: Partial<Record<IntegrationSecretKind, string>> = {+ username: "wazuh-wui",+ password: "api-password",+ wazuhIndexerUrl: INDEXER_URL,+ wazuhIndexerUsername: "homarr",+ wazuhIndexerPassword: "indexer-password",+ },+) =>+ new WazuhIntegration({+ id: "wazuh",+ name: "Wazuh",+ kind: "wazuh",+ url,+ externalUrl: null,+ decryptedSecrets: Object.entries(secrets).map(([kind, value]) => ({+ kind: kind as IntegrationSecretKind,+ value,+ })),+ });++/** The error undici throws when the TLS handshake fails. */+const createTlsError = (code: string) =>+ new TypeError("fetch failed", { cause: Object.assign(new Error(`TLS failure ${code}`), { code }) });++const json = (body: unknown) =>+ new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } });++const toUrl = (input: unknown) => (input instanceof URL ? input.toString() : String(input));++const respond = (url: string) => {+ if (url.includes("/security/user/authenticate")) return new Response("api-token", { status: 200 });+ if (url.includes("/agents/summary/status")) {+ return json({ data: { connection: { active: 1, disconnected: 0, never_connected: 0, pending: 0, total: 1 } } });+ }+ if (url.includes("/agents")) return json({ data: { affected_items: [], total_affected_items: 0 } });+ if (url.includes("/_search")) return json({ hits: { total: { value: 0 }, hits: [] } });+ return new Response("not found", { status: 404 });+};++const peerCertificate = new X509Certificate(tls.rootCertificates[0] ?? "");++const mockCertificateFetch = () =>+ vi.spyOn(tls, "connect").mockImplementation(((_options: tls.ConnectionOptions, callback?: () => void) => {+ queueMicrotask(() => callback?.());+ return {+ getPeerX509Certificate: () => peerCertificate,+ destroy: vi.fn(),+ once: vi.fn(),+ } as unknown as tls.TLSSocket;+ }) as unknown as typeof tls.connect);++describe("WazuhIntegration certificates", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ trustedFetchMock.mockImplementation((input: unknown) => Promise.resolve(respond(toUrl(input))));+ testFetchMock.mockImplementation((input: unknown) => Promise.resolve(respond(toUrl(input))));+ });++ test("requests the server API and the indexer with Homarr's trusted certificates", async () => {+ const integration = createIntegration(API_URL);++ await integration.getAgentsOverviewAsync();+ await integration.getRecentAlertsAsync({ minLevel: 0, limit: 5, hours: 24 });++ const urls = trustedFetchMock.mock.calls.map(([input]) => toUrl(input));+ expect(urls.some((url) => url.startsWith(`${API_URL}/agents`))).toBe(true);+ expect(urls.some((url) => url.startsWith(`${INDEXER_URL}/wazuh-alerts-*/_search`))).toBe(true);+ });++ test("test connection offers the indexer certificate when only the indexer certificate is untrusted", async () => {+ const connectSpy = mockCertificateFetch();+ testFetchMock.mockImplementation((input: unknown) => {+ const url = toUrl(input);+ if (url.startsWith(INDEXER_URL)) return Promise.reject(createTlsError("UNABLE_TO_VERIFY_LEAF_SIGNATURE"));+ return Promise.resolve(respond(url));+ });++ const result = await createIntegration(API_URL).testConnectionAsync();++ expect(result.success).toBe(false);+ if (result.success || result.error.type !== "certificate") throw new Error("Expected a certificate error");+ expect(result.error.data.requestError.reason).toBe("untrusted");+ expect(result.error.data.url).toBe(`${INDEXER_URL}/`);+ expect(connectSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ host: "wazuh-indexer.example.com",+ servername: "wazuh-indexer.example.com",+ port: 9200,+ }),+ expect.any(Function),+ );+ });++ test("test connection offers the server API certificate when the server API certificate is untrusted", async () => {+ const connectSpy = mockCertificateFetch();+ testFetchMock.mockImplementation((input: unknown) => {+ const url = toUrl(input);+ if (url.startsWith(API_URL)) return Promise.reject(createTlsError("DEPTH_ZERO_SELF_SIGNED_CERT"));+ return Promise.resolve(respond(url));+ });++ const result = await createIntegration(API_URL).testConnectionAsync();++ expect(result.success).toBe(false);+ if (result.success || result.error.type !== "certificate") throw new Error("Expected a certificate error");+ expect(result.error.data.url).toBe(`${API_URL}/`);+ expect(connectSpy).toHaveBeenCalledWith(+ expect.objectContaining({ host: "wazuh-manager.example.com", port: 55000 }),+ expect.any(Function),+ );+ });++ test("test connection reads the certificate of an IP address without sending it as SNI", async () => {+ const connectSpy = mockCertificateFetch();+ const indexerUrl = "https://10.0.0.5:9200";+ testFetchMock.mockImplementation((input: unknown) => {+ const url = toUrl(input);+ if (url.startsWith(indexerUrl)) return Promise.reject(createTlsError("UNABLE_TO_VERIFY_LEAF_SIGNATURE"));+ return Promise.resolve(respond(url));+ });++ const result = await createIntegration(indexerUrl, {+ wazuhIndexerUsername: "homarr",+ wazuhIndexerPassword: "indexer-password",+ }).testConnectionAsync();++ expect(result.success).toBe(false);+ if (result.success || result.error.type !== "certificate") throw new Error("Expected a certificate error");+ expect(result.error.data.url).toBe(`${indexerUrl}/`);+ const [options] = connectSpy.mock.calls[0] as unknown as [tls.ConnectionOptions];+ expect(options).toMatchObject({ host: "10.0.0.5", port: 9200 });+ expect(options.servername).toBeUndefined();+ });++ test("test connection reports other indexer request errors without offering a certificate", async () => {+ const connectSpy = mockCertificateFetch();+ testFetchMock.mockImplementation((input: unknown) => {+ const url = toUrl(input);+ if (url.startsWith(INDEXER_URL)) return Promise.reject(createTlsError("ECONNREFUSED"));+ return Promise.resolve(respond(url));+ });++ const result = await createIntegration(API_URL).testConnectionAsync();++ expect(result.success).toBe(false);+ if (result.success) return;+ expect(result.error.type).toBe("request");+ expect(connectSpy).not.toHaveBeenCalled();+ });++ test.each([+ ["DEPTH_ZERO_SELF_SIGNED_CERT", "certificate"],+ ["UNABLE_TO_VERIFY_LEAF_SIGNATURE", "certificate"],+ ["ERR_TLS_CERT_ALTNAME_INVALID", "certificateHostname"],+ ["CERT_HAS_EXPIRED", "certificateExpired"],+ ["CERT_NOT_YET_VALID", "certificateExpired"],+ ] as const)("maps %s to the %s widget error", (code, reason) => {+ const error = WazuhRequestError.fromFetchError("indexer", createTlsError(code));++ expect(toWazuhPublicError(new Error("wrapped", { cause: error }))).toEqual({ reason, target: "indexer" });+ });+});++describe("WazuhIntegration notifications", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ });++ test("returns recent high and critical alerts from the indexer as notifications", async () => {+ trustedFetchMock.mockImplementation(() =>+ Promise.resolve(+ json({+ hits: {+ total: { value: 1 },+ hits: [+ {+ _id: "doc-1",+ _source: {+ id: "1790466949.5285465",+ timestamp: "2026-10-06T10:00:00.000Z",+ rule: { id: "5712", level: 12, description: "sshd: brute force trying to get access to the system." },+ agent: { id: "003", name: "web-01" },+ data: { srcip: "203.0.113.7" },+ },+ },+ ],+ },+ }),+ ),+ );+ const integration = createIntegration(INDEXER_URL, {+ wazuhIndexerUsername: "homarr",+ wazuhIndexerPassword: "indexer-password",+ wazuhDashboardUrl: "https://wazuh.example.com/",+ });++ const notifications = await integration.getNotificationsAsync();++ const [url, init] = trustedFetchMock.mock.calls[0] as [string, { body: string }];+ expect(url).toContain(`${INDEXER_URL}/wazuh-alerts-*/_search`);+ expect(JSON.stringify(JSON.parse(init.body))).toContain('{"range":{"rule.level":{"gte":12}}}');+ expect(notifications).toHaveLength(1);+ expect(notifications[0]).toMatchObject({+ id: "doc-1",+ time: new Date("2026-10-06T10:00:00.000Z"),+ title: "sshd: brute force trying to get access to the system.",+ body: "Level 12 · Rule 5712\nAgent: web-01 (003)\nSource IP: 203.0.113.7",+ });+ expect(notifications[0]?.href).toMatch(+ /^https:\/\/wazuh\.example\.com\/app\/threat-hunting#\/overview\/\?tab=general/,+ );+ expect(notifications[0]?.href).toContain("agentId=003");+ });++ test("leaves the link empty without a dashboard URL", async () => {+ trustedFetchMock.mockImplementation(() =>+ Promise.resolve(+ json({+ hits: {+ total: { value: 1 },+ hits: [{ _id: "doc-2", _source: { timestamp: "2026-10-06T10:00:00.000Z", rule: { level: 13 } } }],+ },+ }),+ ),+ );+ const integration = createIntegration(INDEXER_URL, {+ wazuhIndexerUsername: "homarr",+ wazuhIndexerPassword: "indexer-password",+ });++ const [notification] = await integration.getNotificationsAsync();++ expect(notification?.href).toBeUndefined();+ expect(notification?.title).toBe("Wazuh rule alert");+ expect(notification?.body).toBe("Level 13");+ });+});diff --git a/packages/integrations/src/wazuh/wazuh-errors.ts b/packages/integrations/src/wazuh/wazuh-errors.tsindex ce1e348b5..8dc33559b 100644--- a/packages/integrations/src/wazuh/wazuh-errors.ts+++ b/packages/integrations/src/wazuh/wazuh-errors.ts@@ -4,7 +4,12 @@ import type { WazuhDataSource } from "./wazuh-types";export type WazuhErrorReason =| "unauthorized"+ /** The certificate chain is not trusted (self-signed or unknown CA). */| "certificate"+ /** The certificate is trusted but not issued for the host in the URL. */+ | "certificateHostname"+ /** The certificate is expired or not valid yet. */+ | "certificateExpired"| "unreachable"| "timeout"| "status"@@ -47,7 +52,12 @@ export class WazuhRequestError extends Error {const reasonFromCode = (code: string): WazuhErrorReason | null => {const match = matchErrorCode(code);if (!match) return null;- if (match.type === "certificate") return "certificate";+ if (match.type === "certificate") {+ // Only an untrusted chain can be fixed by trusting a certificate or CA, so the other reasons are reported separately.+ if (match.reason === "hostnameMismatch") return "certificateHostname";+ if (match.reason === "expired" || match.reason === "notYetValid") return "certificateExpired";+ return "certificate";+ }if (match.type === "timeout") return "timeout";return "unreachable";};diff --git a/packages/integrations/src/wazuh/wazuh-integration.ts b/packages/integrations/src/wazuh/wazuh-integration.tsindex e7e279b2f..6cae9bb84 100644--- a/packages/integrations/src/wazuh/wazuh-integration.ts+++ b/packages/integrations/src/wazuh/wazuh-integration.ts@@ -1,21 +1,27 @@import { removeTrailingSlash } from "@homarr/common";+import { FetchHttpErrorHandler } from "@homarr/common/server";import { createLogger } from "@homarr/core/infrastructure/logs";import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";import type { fetch as undiciFetch } from "undici";import type { IntegrationInput, IntegrationTestingInput } from "../base/integration";import { Integration } from "../base/integration";+import { IntegrationRequestError } from "../base/errors/http/integration-request-error";import type { SessionStore } from "../base/session-store";import { createSessionStore } from "../base/session-store";import { TestConnectionError } from "../base/test-connection/test-connection-error";import type { TestingResult } from "../base/test-connection/test-connection-service";import type { IntegrationHttpAuthentication } from "../http-auth";+import type { Notification } from "../interfaces/notifications/notification-types";+import type { INotificationsIntegration } from "../interfaces/notifications/notifications-integration";import { WazuhRequestError } from "./wazuh-errors";import type { KeyedBucket, SeverityRangeResult } from "./wazuh-queries";import {alertSourceFields,authFailureQuery,bruteForceQuery,+ createAlertDashboardUrl,+ formatAlertNotificationBody,getTotalHits,mapAlertHit,normalizeAgentStatus,@@ -64,6 +70,10 @@ const TOKEN_TTL_SECONDS = 600;const MONITORING_SNAPSHOT_WINDOW_MS = 5 * 60 * 1000;/** Upper bound for agent lists; larger fleets should use the Wazuh dashboard. */const MAX_AGENTS = 1000;+/** Matches Wazuh's default email_alert_level: the notifications widget lists what Wazuh would send as email. */+const NOTIFICATION_MIN_LEVEL = 12;+const NOTIFICATION_WINDOW_HOURS = 24;+const NOTIFICATION_LIMIT = 25;interface WazuhSession {token: string;@@ -85,10 +95,12 @@ const findWazuhRequestError = (error: unknown): WazuhRequestError | null => {return null;};+const fetchHttpErrorHandler = new FetchHttpErrorHandler();+const basicAuth = (username: string, password: string) =>`Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;-export class WazuhIntegration extends Integration {+export class WazuhIntegration extends Integration implements INotificationsIntegration {private readonly sessionStore: SessionStore<WazuhSession>;constructor(integration: IntegrationInput) {@@ -418,6 +430,26 @@ export class WazuhIntegration extends Integration {return response.hits.hits.map(mapAlertHit);}+ /**+ * High and critical alerts of the last 24 hours for the notifications widget. Needs the indexer, like all alerts.+ */+ public async getNotificationsAsync(): Promise<Notification[]> {+ const alerts = await this.getRecentAlertsAsync({+ minLevel: NOTIFICATION_MIN_LEVEL,+ limit: NOTIFICATION_LIMIT,+ hours: NOTIFICATION_WINDOW_HOURS,+ });+ const dashboardUrl = this.getDashboardUrl();++ return alerts.map((alert) => ({+ id: alert.id,+ time: new Date(alert.timestamp),+ title: alert.description || `Wazuh rule ${alert.ruleId ?? "alert"}`,+ body: formatAlertNotificationBody(alert),+ href: dashboardUrl ? createAlertDashboardUrl(dashboardUrl, alert) : undefined,+ }));+ }+public async getAlertTimelineAsync(input: {range: WazuhTimeRange;interval: WazuhTimelineInterval;@@ -922,11 +954,15 @@ export class WazuhIntegration extends Integration {const error = findWazuhRequestError(thrown) ?? thrown;if (error instanceof WazuhRequestError) {if (error.reason === "unauthorized") return TestConnectionError.UnauthorizedResult(error.status ?? 401);+ const url = error.target === "indexer" ? (indexer?.url ?? this.integration.url) : this.integration.url;if (error.reason === "status" && error.status !== undefined) {- const url = error.target === "indexer" ? (indexer?.url ?? this.integration.url) : this.integration.url;return TestConnectionError.StatusResult({ status: error.status, url });}- // Rethrow the original fetch error so the shared test-connection flow can offer certificate trust.+ // Report TLS and network failures with the URL of the endpoint that failed. The shared test-connection+ // flow then reads and offers to trust the certificate of that endpoint (API or indexer), not always the+ // certificate of the integration URL.+ const requestError = fetchHttpErrorHandler.handleRequestError(error.cause);+ if (requestError) throw new IntegrationRequestError(this.publicIntegration, { cause: requestError, url });if (error.cause !== undefined) throw error.cause;}throw error;diff --git a/packages/integrations/src/wazuh/wazuh-queries.ts b/packages/integrations/src/wazuh/wazuh-queries.tsindex ae639a0cb..18f93b26d 100644--- a/packages/integrations/src/wazuh/wazuh-queries.ts+++ b/packages/integrations/src/wazuh/wazuh-queries.ts@@ -1,5 +1,6 @@import type {WazuhAgentStatus,+ WazuhAlert,WazuhAlertSeverityCounts,WazuhIndexerAlertSource,WazuhIndexerHit,@@ -148,3 +149,37 @@ export const normalizeAgentStatus = (status: string | undefined): WazuhAgentStatexport const normalizeGroups = (group: string[] | string | undefined) => asArray(group);export const normalizeVersion = (version: string | undefined) => version?.replace(/^Wazuh\s+/i, "") ?? null;++/** Plain text body of a Wazuh alert in the notifications widget. */+export const formatAlertNotificationBody = (alert: WazuhAlert) => {+ const lines = [`Level ${alert.level}${alert.ruleId ? ` · Rule ${alert.ruleId}` : ""}`];+ if (alert.agentName ?? alert.agentId) {+ lines.push(+ `Agent: ${alert.agentName ?? alert.agentId}${alert.agentName && alert.agentId ? ` (${alert.agentId})` : ""}`,+ );+ }+ if (alert.sourceIp) lines.push(`Source IP: ${alert.sourceIp}`);+ if (alert.mitre.ids.length > 0) lines.push(`MITRE ATT&CK: ${alert.mitre.ids.join(", ")}`);+ return lines.join("\n");+};++const kuery = (query: string) =>+ encodeURIComponent(+ `(filters:!(),query:(language:kuery,query:'${query.replaceAll("!", "!!").replaceAll("'", "!'")}'))`,+ );++/**+ * Link to an alert in the Wazuh dashboard (4.9+ routes). Mirrors the alert link of the Wazuh widgets: the events view+ * filtered by the alert id within five minutes of the alert.+ */+export const createAlertDashboardUrl = (dashboardUrl: string, alert: WazuhAlert) => {+ const time = new Date(alert.timestamp).getTime();+ const window = 5 * 60 * 1000;+ const from = new Date(time - window).toISOString();+ const to = new Date(time + window).toISOString();+ let url = `${dashboardUrl.replace(/\/+$/, "")}/app/threat-hunting#/overview/?tab=general&tabView=events`;+ if (alert.agentId) url += `&agentId=${encodeURIComponent(alert.agentId)}`;+ if (alert.alertId) url += `&_q=${kuery(`id:"${alert.alertId}"`)}`;+ url += `&_g=${encodeURIComponent(`(time:(from:'${from}',to:'${to}'))`)}`;+ return url;+};diff --git a/packages/integrations/test/base.spec.ts b/packages/integrations/test/base.spec.tsindex 4fcce3458..b5e93f861 100644--- a/packages/integrations/test/base.spec.ts+++ b/packages/integrations/test/base.spec.ts@@ -1,8 +1,11 @@-import { describe, expect, test, vi } from "vitest";+import { X509Certificate } from "node:crypto";+import tls from "node:tls";+import { afterEach, describe, expect, test, vi } from "vitest";-import { ResponseError } from "@homarr/common/server";+import { RequestError, ResponseError } from "@homarr/common/server";import { createDb } from "@homarr/db/test";+import { IntegrationRequestError } from "../src/base/errors/http/integration-request-error";import type { IntegrationTestingInput } from "../src/base/integration";import { Integration } from "../src/base/integration";import type { TestingResult } from "../src/base/test-connection/test-connection-service";@@ -27,7 +30,65 @@ vi.mock("@homarr/core/infrastructure/certificates", async (importActual) => {};});+const createCertificateRequestError = () =>+ new RequestError<"certificate">(+ { type: "certificate", reason: "untrusted", code: "DEPTH_ZERO_SELF_SIGNED_CERT" },+ { cause: new Error("self-signed certificate") },+ );++const mockCertificateFetch = () =>+ vi.spyOn(tls, "connect").mockImplementation(((_options: tls.ConnectionOptions, callback?: () => void) => {+ queueMicrotask(() => callback?.());+ return {+ getPeerX509Certificate: () => new X509Certificate(tls.rootCertificates[0] ?? ""),+ destroy: vi.fn(),+ once: vi.fn(),+ } as unknown as tls.TLSSocket;+ }) as unknown as typeof tls.connect);+describe("Base integration", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ test("testConnectionAsync should read the certificate from the integration URL by default", async () => {+ const connectSpy = mockCertificateFetch();+ const error = new IntegrationRequestError(+ { id: "test", name: "Test", url: "https://example.com" },+ { cause: createCertificateRequestError() },+ );+ const integration = new FakeIntegration(undefined, error);++ const result = await integration.testConnectionAsync();++ expect(result.success).toBe(false);+ if (result.success || result.error.type !== "certificate") throw new Error("Expected a certificate error");+ expect(result.error.data.url).toBe("https://example.com/");+ expect(connectSpy).toHaveBeenCalledWith(+ expect.objectContaining({ host: "example.com", servername: "example.com", port: 443 }),+ expect.any(Function),+ );+ });++ test("testConnectionAsync should read the certificate from the URL of the failed request", async () => {+ const connectSpy = mockCertificateFetch();+ const error = new IntegrationRequestError(+ { id: "test", name: "Test", url: "https://example.com" },+ { cause: createCertificateRequestError(), url: "https://secondary.example.com:9200" },+ );+ const integration = new FakeIntegration(undefined, error);++ const result = await integration.testConnectionAsync();++ expect(result.success).toBe(false);+ if (result.success || result.error.type !== "certificate") throw new Error("Expected a certificate error");+ expect(result.error.data.url).toBe("https://secondary.example.com:9200/");+ expect(connectSpy).toHaveBeenCalledWith(+ expect.objectContaining({ host: "secondary.example.com", port: 9200 }),+ expect.any(Function),+ );+ });+test("testConnectionAsync should handle errors", async () => {const responseError = new ResponseError({ status: 500, url: "https://example.com" });const integration = new FakeIntegration(undefined, responseError);diff --git a/packages/translation/src/lang/en.json b/packages/translation/src/lang/en.jsonindex 3de39c1bc..28f8c1f0b 100644--- a/packages/translation/src/lang/en.json+++ b/packages/translation/src/lang/en.json@@ -1559,6 +1559,7 @@"untrusted": "The certificate is not trusted.","hostnameMismatch": "The certificate hostname does not match the URL."},+ "secondaryUrl": "This certificate was presented by {url}, an additional endpoint configured on this integration.","alert": {"permission": {"title": "Not enough permissions",@@ -5756,6 +5757,8 @@"allHidden": "All metrics are hidden in this view. Use Customize this view to restore them."},"wazuh": {+ "name": "Wazuh",+ "description": "Wazuh security overview with tabs for alert severity, alerts, timeline, top lists, agents, vulnerabilities, file integrity and authentication failures","target": {"api": "Wazuh server API","indexer": "Wazuh indexer",@@ -5774,7 +5777,15 @@},"certificate": {"title": "{target} certificate is not trusted",- "description": "Wazuh uses a self-signed certificate by default. Run \"Test connection\" on the integration and trust the certificate, or add your CA under Settings → Certificates."+ "description": "Wazuh uses self-signed certificates by default, and the server API and the indexer use different ones. Run \"Test connection\" on the integration and trust each certificate, or add the Wazuh root CA under Management → Tools → Certificates."+ },+ "certificateHostname": {+ "title": "{target} certificate does not match the URL",+ "description": "The certificate is not issued for the host in the integration URL. Use a hostname or IP address listed in the certificate, reissue the certificate with that name, or trust the hostname with \"Test connection\"."+ },+ "certificateExpired": {+ "title": "{target} certificate has expired or is not valid yet",+ "description": "Renew the Wazuh certificate, and check that the clocks of the Homarr and Wazuh hosts are correct."},"unreachable": {"title": "Cannot reach {target}",@@ -5799,7 +5810,9 @@"unknown": {"title": "Could not load data from {target}","description": "Check the Homarr logs for details."- }+ },+ "viewSaveTitle": "Could not save the selected tab",+ "viewSaveMessage": "The tab is shown for now but will reset when the board reloads."},"range": {"1h": "1h",@@ -5807,93 +5820,138 @@"7d": "7d","30d": "30d"},- "levelTooltip": "Rule level {level} ({severity})"- },- "wazuhAgents": {- "name": "Wazuh agents",- "description": "Sortable list of Wazuh agents with status, OS, version and last keepalive",- "option": {- "statusFilter": {- "label": "Show agents"- },- "sortBy": {- "label": "Sort by"+ "levelTooltip": "Rule level {level} ({severity})",+ "summary": {+ "title": "Alert severity · {range}",+ "alerts": "alerts",+ "none": "No alerts",+ "trend": {+ "new": "new",+ "tooltip": "Previous period: {previous}"+ },+ "previous": "Previous {range}: {count}",+ "maxLevel": "Max level {level}",+ "health": "Indexer health: {status}",+ "manager": "Manager {version}"+ },+ "alerts": {+ "title": "Alerts · level {level}+ · {hours}h",+ "empty": "No alerts at this level. All quiet.",+ "rule": "Rule {id}",+ "openInDashboard": "Open this alert in the Wazuh dashboard"+ },+ "timeline": {+ "title": "Alerts timeline · {range}",+ "total": "{count} alerts",+ "interval": "per {interval}"+ },+ "top": {+ "title": {+ "rules": "Top rules · {range}",+ "agents": "Top agents · {range}",+ "sourceIps": "Top source IPs · {range}",+ "mitreTactics": "MITRE tactics · {range}",+ "mitreTechniques": "MITRE techniques · {range}"},- "showVersion": {- "label": "Show Wazuh version column"+ "empty": {+ "rules": "No alerts in this period",+ "agents": "No alerts in this period",+ "sourceIps": "No alerts with a source IP in this period",+ "mitreTactics": "No alerts mapped to MITRE ATT&CK in this period",+ "mitreTechniques": "No alerts mapped to MITRE ATT&CK in this period"+ },+ "totalTooltip": "{count} matching alerts",+ "private": "LAN",+ "public": "Public",+ "agents": "Seen on {count} agents",+ "others": "{count} more alerts in other entries"+ },+ "agents": {+ "title": "Agents",+ "total": "{count} agents",+ "status": {+ "active": "Active",+ "disconnected": "Disconnected",+ "neverConnected": "Never connected",+ "pending": "Pending"+ },+ "statusLabel": {+ "active": "Active",+ "disconnected": "Disconnected",+ "never_connected": "Never connected",+ "pending": "Pending",+ "unknown": "Unknown"},- "showGroups": {- "label": "Show groups column"- }- },- "title": "Agents",- "total": "{count} agents",- "status": {- "active": "Active",- "disconnected": "Disconnected",- "neverConnected": "Never connected",- "pending": "Pending"- },- "statusLabel": {- "active": "Active",- "disconnected": "Disconnected",- "never_connected": "Never connected",- "pending": "Pending",- "unknown": "Unknown"+ "live": "Live",+ "snapshot": "Snapshot {age} old",+ "snapshotHint": "Read from the Wazuh dashboard's agent snapshot (wazuh-monitoring) taken at {time}. Add server API credentials for live data.",+ "staleSnapshot": "The agent snapshot from {time} is outdated. Check that the Wazuh dashboard monitoring job is running, or add server API credentials.",+ "noDisconnected": "All agents are connected",+ "empty": "No agents match this filter",+ "column": {+ "status": "Status",+ "name": "Name",+ "ip": "IP",+ "os": "OS",+ "version": "Version",+ "lastKeepAlive": "Keepalive",+ "groups": "Groups"+ },+ "outdated": "Older than the newest agent version ({version})"+ },+ "vulnerabilities": {+ "title": "Vulnerabilities",+ "topCves": "Top CVEs",+ "score": "Score",+ "agentsShort": "Agents",+ "topAgents": "Most vulnerable agents",+ "criticalHigh": "Crit / High",+ "totalTooltip": "{count} findings on {agents} agents",+ "affected": "{count} agents",+ "empty": "No vulnerabilities detected",+ "distribution": "Severity distribution. {unscored} findings without a score are not shown.",+ "worst": "Worst: {id} ({score}) on {agents} agents"+ },+ "fim": {+ "title": "File integrity · {range}",+ "event": {+ "added": "Added",+ "modified": "Modified",+ "deleted": "Deleted",+ "unknown": "Changed"+ },+ "empty": "No file integrity events in this period",+ "user": "by {user}",+ "registry": "Registry"+ },+ "authFailures": {+ "title": "Auth failures · {hours}h",+ "seriesTooltip": "All agents over the last {hours}h",+ "peak": "Peak {count}/bucket",+ "empty": "No failed logins in this period",+ "failed": "Failed logins",+ "failedHint": "Single authentication failures (sshd, PAM, Windows logon, invalid users)",+ "bruteForce": "Brute force",+ "bruteForceHint": "Correlated brute-force rules (multiple failures in a short period, MITRE T1110)",+ "sourceIps": "Source IPs",+ "ipTooltip": "{ip}: {count} failures",+ "bruteForceCount": "{count} brute force"},- "live": "Live",- "snapshot": "Snapshot {age} old",- "snapshotHint": "Read from the Wazuh dashboard's agent snapshot (wazuh-monitoring) taken at {time}. Add server API credentials for live data.",- "staleSnapshot": "The agent snapshot from {time} is outdated. Check that the Wazuh dashboard monitoring job is running, or add server API credentials.",- "noDisconnected": "All agents are connected",- "empty": "No agents match this filter",- "column": {- "status": "Status",- "name": "Name",- "ip": "IP",- "os": "OS",- "version": "Version",- "lastKeepAlive": "Keepalive",- "groups": "Groups"+ "view": {+ "overview": "Severity",+ "alerts": "Alerts",+ "timeline": "Timeline",+ "top": "Top lists",+ "agents": "Agents",+ "vulnerabilities": "Vulnerabilities",+ "fim": "File integrity",+ "authFailures": "Auth failures"},- "outdated": "Older than the newest agent version ({version})"- },- "wazuhAlerts": {- "name": "Wazuh alerts feed",- "description": "Recent Wazuh alerts with level, MITRE ATT&CK techniques, agent and source IP","option": {- "minLevel": {- "label": "Minimum rule level",- "description": "Wazuh levels: 0-6 low, 7-11 medium, 12-14 high, 15+ critical"- },- "hours": {- "label": "Time window (hours)"- },- "limit": {- "label": "Number of alerts"- },- "showMitre": {- "label": "Show MITRE ATT&CK techniques"- },- "showAgent": {- "label": "Show agent"- },- "showSourceIp": {- "label": "Show source IP"+ "visibleViews": {+ "label": "Visible tabs",+ "description": "Only these tabs are offered in the tab switcher. With a single tab, the switcher is hidden."},- "showRuleId": {- "label": "Show rule ID"- }- },- "title": "Alerts · level {level}+ · {hours}h",- "empty": "No alerts at this level. All quiet.",- "rule": "Rule {id}",- "openInDashboard": "Open this alert in the Wazuh dashboard"- },- "wazuhSummary": {- "name": "Wazuh alert severity",- "description": "Alert severity breakdown with a trend against the previous period",- "option": {"range": {"label": "Time range"},@@ -5902,26 +5960,6 @@},"showFooter": {"label": "Show footer"- }- },- "title": "Alert severity · {range}",- "alerts": "alerts",- "none": "No alerts",- "trend": {- "new": "new",- "tooltip": "Previous period: {previous}"- },- "previous": "Previous {range}: {count}",- "maxLevel": "Max level {level}",- "health": "Indexer health: {status}",- "manager": "Manager {version}"- },- "wazuhTimeline": {- "name": "Wazuh alerts timeline",- "description": "Stacked chart of Wazuh alerts over time by severity",- "option": {- "range": {- "label": "Time range"},"interval": {"label": "Interval"@@ -5934,60 +5972,32 @@"description": "Square root keeps high and critical alerts visible next to thousands of low ones"},"minLevel": {- "label": "Minimum rule level"+ "label": "Minimum rule level (timeline and top lists)"},"showLegend": {"label": "Show legend with totals"- }- },- "title": "Alerts timeline · {range}",- "total": "{count} alerts",- "interval": "per {interval}"- },- "wazuhTopList": {- "name": "Wazuh top list",- "description": "Top rules, agents, source IPs or MITRE ATT&CK tactics and techniques by alert count",- "option": {- "kind": {- "label": "Rank"- },- "range": {- "label": "Time range"},- "limit": {- "label": "Number of entries"+ "topKind": {+ "label": "Rank"},- "minLevel": {- "label": "Minimum rule level"+ "topLimit": {+ "label": "Top list entries"},"showBars": {"label": "Show bars"- }- },- "title": {- "rules": "Top rules · {range}",- "agents": "Top agents · {range}",- "sourceIps": "Top source IPs · {range}",- "mitreTactics": "MITRE tactics · {range}",- "mitreTechniques": "MITRE techniques · {range}"- },- "empty": {- "rules": "No alerts in this period",- "agents": "No alerts in this period",- "sourceIps": "No alerts with a source IP in this period",- "mitreTactics": "No alerts mapped to MITRE ATT&CK in this period",- "mitreTechniques": "No alerts mapped to MITRE ATT&CK in this period"- },- "totalTooltip": "{count} matching alerts",- "private": "LAN",- "public": "Public",- "agents": "Seen on {count} agents",- "others": "{count} more alerts in other entries"- },- "wazuhVulnerabilities": {- "name": "Wazuh vulnerabilities",- "description": "Vulnerability counts, top CVEs and the most vulnerable agents",- "option": {+ },+ "agentStatusFilter": {+ "label": "Show agents"+ },+ "agentSortBy": {+ "label": "Sort by"+ },+ "showVersion": {+ "label": "Agents: show Wazuh version column"+ },+ "showGroups": {+ "label": "Agents: show groups column"+ },"cveOrder": {"label": "Rank CVEs by"},@@ -6002,73 +6012,42 @@},"showAgents": {"label": "Show most vulnerable agents"- }- },- "title": "Vulnerabilities",- "topCves": "Top CVEs",- "score": "Score",- "agentsShort": "Agents",- "topAgents": "Most vulnerable agents",- "criticalHigh": "Crit / High",- "totalTooltip": "{count} findings on {agents} agents",- "affected": "{count} agents",- "empty": "No vulnerabilities detected",- "distribution": "Severity distribution. {unscored} findings without a score are not shown.",- "worst": "Worst: {id} ({score}) on {agents} agents"- },- "wazuhFim": {- "name": "Wazuh file integrity",- "description": "Recent file integrity monitoring (syscheck) events",- "option": {- "range": {- "label": "Time range"},- "event": {+ "fimEvent": {"label": "Events"},- "limit": {- "label": "Number of events"+ "fimLimit": {+ "label": "File integrity events"},"includeRegistry": {"label": "Include Windows registry events"- }- },- "title": "File integrity · {range}",- "event": {- "added": "Added",- "modified": "Modified",- "deleted": "Deleted",- "unknown": "Changed"- },- "empty": "No file integrity events in this period",- "user": "by {user}",- "registry": "Registry"- },- "wazuhAuthFailures": {- "name": "Wazuh authentication failures",- "description": "Failed logins and brute-force alerts per agent with hourly sparklines",- "option": {- "hours": {- "label": "Time window (hours)"},- "limit": {- "label": "Number of agents"+ "authLimit": {+ "label": "Authentication failure agents"},"showSourceIps": {"label": "Show top source IPs"+ },+ "alertsMinLevel": {+ "label": "Alerts: minimum rule level",+ "description": "Wazuh levels: 0-6 low, 7-11 medium, 12-14 high, 15+ critical"+ },+ "alertsLimit": {+ "label": "Alerts: number of alerts"+ },+ "showMitre": {+ "label": "Show MITRE ATT&CK techniques"+ },+ "showAgent": {+ "label": "Show agent"+ },+ "showSourceIp": {+ "label": "Show source IP"+ },+ "showRuleId": {+ "label": "Show rule ID"}- },- "title": "Auth failures · {hours}h",- "seriesTooltip": "All agents over the last {hours}h",- "peak": "Peak {count}/bucket",- "empty": "No failed logins in this period",- "failed": "Failed logins",- "failedHint": "Single authentication failures (sshd, PAM, Windows logon, invalid users)",- "bruteForce": "Brute force",- "bruteForceHint": "Correlated brute-force rules (multiple failures in a short period, MITRE T1110)",- "sourceIps": "Source IPs",- "ipTooltip": "{ip}: {count} failures",- "bruteForceCount": "{count} brute force"+ }}},"widgetPreview": {diff --git a/packages/ui/src/widget-icons.ts b/packages/ui/src/widget-icons.tsindex 9cbb49748..21733e6fc 100644--- a/packages/ui/src/widget-icons.ts+++ b/packages/ui/src/widget-icons.ts@@ -47,13 +47,7 @@ import {IconServer2,IconShieldCheck,IconShieldLock,- IconShieldBolt,IconShieldHalfFilled,- IconDevicesPc,- IconListNumbers,- IconBug,- IconFileAlert,- IconLockExclamation,IconSpeedboat,IconTable,IconTicket,@@ -134,12 +128,5 @@ export const widgetCatalogIcons: Record<WidgetKind, TablerIcon> = {customApi: IconApi,wud: IconBrandDocker,llamacpp: IconCpu,- wazuhAgents: IconDevicesPc,- wazuhAlerts: IconShieldBolt,- wazuhSummary: IconShieldHalfFilled,- wazuhTimeline: IconChartAreaLine,- wazuhTopList: IconListNumbers,- wazuhVulnerabilities: IconBug,- wazuhFim: IconFileAlert,- wazuhAuthFailures: IconLockExclamation,+ wazuh: IconShieldHalfFilled,};diff --git a/packages/widgets/src/option-translation.ts b/packages/widgets/src/option-translation.tsindex a93863b91..f2e5296ea 100644--- a/packages/widgets/src/option-translation.ts+++ b/packages/widgets/src/option-translation.ts@@ -54,7 +54,10 @@ const getSharedOptionNamespace = (kind: WidgetKind, property: string): string |return "widget.beszel.options";}- if (["dockerContainers", "downloads", "beszelSystemTable"].includes(kind) && TABLE_OPTION_PROPERTIES.has(property)) {+ if (+ ["dockerContainers", "downloads", "beszelSystemTable", "wazuh"].includes(kind) &&+ TABLE_OPTION_PROPERTIES.has(property)+ ) {return "widget.common.tableOptions";}diff --git a/packages/widgets/src/registry.ts b/packages/widgets/src/registry.tsindex 8af84f511..011c46e49 100644--- a/packages/widgets/src/registry.ts+++ b/packages/widgets/src/registry.ts@@ -63,16 +63,9 @@ import type * as uptimeKuma from "./uptime-kuma";import type * as video from "./video";import type * as vpn from "./vpn";import type * as weather from "./weather";+import type * as wazuh from "./wazuh";import type * as wud from "./wud";import type * as llamacpp from "./llama-cpp";-import type * as wazuhAgents from "./wazuh-agents";-import type * as wazuhAlerts from "./wazuh-alerts";-import type * as wazuhSummary from "./wazuh-summary";-import type * as wazuhTimeline from "./wazuh-timeline";-import type * as wazuhTopList from "./wazuh-top-list";-import type * as wazuhVulnerabilities from "./wazuh-vulnerabilities";-import type * as wazuhFim from "./wazuh-fim";-import type * as wazuhAuthFailures from "./wazuh-auth-failures";// Keep these imports explicit so Next.js and Turbopack can discover every widget// module without loading any widget definition or component eagerly.@@ -142,14 +135,7 @@ export const widgetModuleLoaders = {weather: () => import("./weather"),wud: () => import("./wud"),llamacpp: () => import("./llama-cpp"),- wazuhAgents: () => import("./wazuh-agents"),- wazuhAlerts: () => import("./wazuh-alerts"),- wazuhSummary: () => import("./wazuh-summary"),- wazuhTimeline: () => import("./wazuh-timeline"),- wazuhTopList: () => import("./wazuh-top-list"),- wazuhVulnerabilities: () => import("./wazuh-vulnerabilities"),- wazuhFim: () => import("./wazuh-fim"),- wazuhAuthFailures: () => import("./wazuh-auth-failures"),+ wazuh: () => import("./wazuh"),} satisfies { [TKind in WidgetKind]: () => Promise<WidgetImports[TKind]> };export type WidgetImports = {@@ -218,14 +204,7 @@ export type WidgetImports = {weather: typeof weather;wud: typeof wud;llamacpp: typeof llamacpp;- wazuhAgents: typeof wazuhAgents;- wazuhAlerts: typeof wazuhAlerts;- wazuhSummary: typeof wazuhSummary;- wazuhTimeline: typeof wazuhTimeline;- wazuhTopList: typeof wazuhTopList;- wazuhVulnerabilities: typeof wazuhVulnerabilities;- wazuhFim: typeof wazuhFim;- wazuhAuthFailures: typeof wazuhAuthFailures;+ wazuh: typeof wazuh;};type WidgetComponentLoaders = {@@ -301,14 +280,7 @@ export const widgetComponentLoaders = {weather: () => import("./weather/component"),wud: () => import("./wud/component"),llamacpp: () => import("./llama-cpp/component"),- wazuhAgents: () => import("./wazuh-agents/component"),- wazuhAlerts: () => import("./wazuh-alerts/component"),- wazuhSummary: () => import("./wazuh-summary/component"),- wazuhTimeline: () => import("./wazuh-timeline/component"),- wazuhTopList: () => import("./wazuh-top-list/component"),- wazuhVulnerabilities: () => import("./wazuh-vulnerabilities/component"),- wazuhFim: () => import("./wazuh-fim/component"),- wazuhAuthFailures: () => import("./wazuh-auth-failures/component"),+ wazuh: () => import("./wazuh/component"),} satisfies WidgetComponentLoaders;export type WidgetImportKey = keyof WidgetImports;diff --git a/packages/widgets/src/wazuh-agents/component.tsx b/packages/widgets/src/wazuh-agents/component.tsxdeleted file mode 100644index 36b467ce6..000000000--- a/packages/widgets/src/wazuh-agents/component.tsx+++ /dev/null@@ -1,413 +0,0 @@-"use client";--import { useMemo, useState } from "react";-import { Anchor, Badge, Center, Group, ScrollArea, Stack, Text, Tooltip } from "@mantine/core";-import {- IconBrandAndroid,- IconBrandApple,- IconBrandDebian,- IconBrandRedhat,- IconBrandUbuntu,- IconBrandWindows,- IconChevronDown,- IconChevronUp,- IconDevicesPc,- IconServer,-} from "@tabler/icons-react";-import dayjs from "dayjs";--import { clientApi } from "@homarr/api/client";-import type { WazuhAgent } from "@homarr/integrations/types";-import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";-import type { TablerIcon } from "@homarr/ui";--import { WidgetEmptyState } from "../common/empty-state";-import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../common/query-state";-import { useWidgetNow } from "../common/use-widget-now";-import type { WidgetComponentProps } from "../definition";-import { WazuhChip } from "../wazuh/_shared/badges";-import { WazuhErrorState } from "../wazuh/_shared/error-state";-import { WazuhRelativeTime, WazuhPendingState, WazuhStatTile, WazuhWidgetFrame } from "../wazuh/_shared/frame";-import { useWazuhLinks } from "../wazuh/_shared/use-wazuh-links";-import classes from "../wazuh/_shared/wazuh.module.css";--type SortKey = "status" | "name" | "ip" | "os" | "version" | "lastKeepAlive";-type StatusFilter = "all" | "active" | "disconnected" | "inactive";--const statusOrder: Record<WazuhAgent["status"], number> = {- disconnected: 0,- pending: 1,- never_connected: 2,- unknown: 3,- active: 4,-};--const getOsIcon = (platform: string | null, name: string | null): TablerIcon => {- const value = `${platform ?? ""} ${name ?? ""}`.toLowerCase();- if (value.includes("windows")) return IconBrandWindows;- if (value.includes("ubuntu")) return IconBrandUbuntu;- if (value.includes("debian")) return IconBrandDebian;- if (value.includes("darwin") || value.includes("mac")) return IconBrandApple;- if (value.includes("android")) return IconBrandAndroid;- if (/(rhel|red ?hat|centos|rocky|alma|fedora|amzn|oracle)/.test(value)) return IconBrandRedhat;- return IconServer;-};--// Keep the OS cell readable in narrow columns: "Microsoft Windows 11 Pro" -> "Windows 11 Pro", "Debian GNU/Linux" -> "Debian".-const shortOsName = (name: string | null) =>- name- ?.replace(/^Microsoft\s+/i, "")- .replace(/\s*GNU\/Linux/i, "")- .replace(/\s*\(.*\)\s*$/, "")- .trim() ?? null;--const parseVersion = (value: string | null) =>- (value ?? "")- .replace(/^v/, "")- .split(".")- .map((part) => Number.parseInt(part, 10) || 0);--const compareVersions = (left: string | null, right: string | null) => {- const [a, b] = [parseVersion(left), parseVersion(right)];- for (let index = 0; index < Math.max(a.length, b.length); index++) {- const diff = (a[index] ?? 0) - (b[index] ?? 0);- if (diff !== 0) return diff;- }- return 0;-};--const ipToNumber = (ip: string | null) =>- (ip ?? "").split(".").reduce((total, part) => total * 256 + (Number.parseInt(part, 10) || 0), 0);--const compareIps = (left: string | null, right: string | null) => ipToNumber(left) - ipToNumber(right);--const sorters: Record<SortKey, (left: WazuhAgent, right: WazuhAgent) => number> = {- status: (left, right) => statusOrder[left.status] - statusOrder[right.status] || left.name.localeCompare(right.name),- name: (left, right) => left.name.localeCompare(right.name),- ip: (left, right) => compareIps(left.ip, right.ip),- os: (left, right) => (left.osName ?? "~").localeCompare(right.osName ?? "~") || left.name.localeCompare(right.name),- version: (left, right) => compareVersions(left.version, right.version) || left.name.localeCompare(right.name),- // Most recent first by default.- lastKeepAlive: (left, right) => (right.lastKeepAlive ?? "").localeCompare(left.lastKeepAlive ?? ""),-};--type SortState = { key: SortKey; descending: boolean };--const SortHeader = ({- column,- label,- ariaLabel,- sort,- onSort,-}: {- column: SortKey;- label: string;- ariaLabel?: string;- sort: SortState;- onSort: (column: SortKey) => void;-}) => (- <button type="button" className={classes.sortButton} onClick={() => onSort(column)} aria-label={ariaLabel ?? label}>- {label}- {sort.key === column &&- (sort.descending ? <IconChevronUp size={11} stroke={2.5} /> : <IconChevronDown size={11} stroke={2.5} />)}- </button>-);--const snapshotColor = (ageMs: number) => {- if (ageMs < 20 * 60_000) return "green";- if (ageMs < 2 * 60 * 60_000) return "yellow";- return "red";-};--export default function WazuhAgentsWidget({- integrationIds,- options,- width,- height,-}: WidgetComponentProps<"wazuhAgents">) {- const t = useI18n("widget.wazuhAgents");- const locale = useCurrentIntlLocale();- const now = useWidgetNow("minute");- const integrationId = integrationIds[0] ?? "";- const query = clientApi.widget.wazuh.getAgents.useQuery(- { integrationId },- { staleTime: 60_000, refetchInterval: 60_000 },- );- const result = getUsableWidgetQueryData(query);- const links = useWazuhLinks(result?.dashboardUrl);-- const [filter, setFilter] = useState<StatusFilter>(options.statusFilter);- const [sort, setSort] = useState<SortState>({ key: options.sortBy, descending: false });- const handleSort = (column: SortKey) =>- setSort((current) => ({ key: column, descending: current.key === column ? !current.descending : false }));-- const agents = result?.data?.agents;- const showTable = height >= 190;- const showVersion = showTable && options.showVersion && width >= 600;- const newestVersion = useMemo(() => {- if (!showVersion) return null;- return (agents ?? []).reduce<string | null>(- (newest, agent) => (compareVersions(agent.version, newest) > 0 ? agent.version : newest),- null,- );- }, [agents, showVersion]);- const visibleAgents = useMemo(() => {- if (!showTable) return [];- const filtered = (agents ?? []).filter((agent) => {- if (filter === "all") return true;- if (filter === "inactive") return agent.status !== "active";- return agent.status === filter;- });- const sorted = filtered.toSorted(sorters[sort.key]);- return sort.descending ? sorted.toReversed() : sorted;- }, [agents, filter, sort, showTable]);-- const compact = height < 170 || width < 260;-- if (isInitialWidgetQueryPending(query)) {- return (- <WazuhWidgetFrame icon={IconDevicesPc} title={t("title")} compact={compact} iconColor="teal">- <WazuhPendingState />- </WazuhWidgetFrame>- );- }- if (!result) return <WidgetEmptyState />;- if (result.error) return <WazuhErrorState error={result.error} compact={height < 160} />;-- const overview = result.data;- const counts = overview.counts;- const snapshotAgeMs = (now ?? new Date()).getTime() - new Date(overview.asOf).getTime();- const showIp = width >= 380;- const showOs = width >= 460;- const showGroups = options.showGroups && width >= 720;- const toggleFilter = (value: StatusFilter) => setFilter((current) => (current === value ? "all" : value));-- const sourceBadge =- overview.source === "api" ? (- <Badge size="sm" variant="dot" color="green" radius="sm">- {t("live")}- </Badge>- ) : (- <Tooltip- label={- snapshotAgeMs > 2 * 60 * 60_000- ? t("staleSnapshot", { time: new Date(overview.asOf).toLocaleString(locale) })- : t("snapshotHint", { time: new Date(overview.asOf).toLocaleString(locale) })- }- withArrow- multiline- w={260}- >- <Badge size="sm" variant="dot" color={snapshotColor(snapshotAgeMs)} radius="sm">- {width >= 300- ? t("snapshot", { age: dayjs(overview.asOf).fromNow(true) })- : dayjs(overview.asOf).fromNow(true)}- </Badge>- </Tooltip>- );-- return (- <WazuhWidgetFrame- icon={IconDevicesPc}- title={t("total", { count: String(counts.total) })}- href={links?.agents}- compact={compact}- iconColor="teal"- headerRight={sourceBadge}- >- <Stack h="100%" gap={8}>- <Group gap={6} wrap="nowrap" grow>- <WazuhStatTile- label={t("status.active")}- value={String(counts.active)}- color="green"- active={filter === "active"}- onClick={() => toggleFilter("active")}- compact={compact}- />- <WazuhStatTile- label={t("status.disconnected")}- value={String(counts.disconnected)}- color="red"- active={filter === "disconnected"}- onClick={() => toggleFilter("disconnected")}- compact={compact}- />- {width >= 300 && (- <WazuhStatTile- label={t("status.neverConnected")}- value={String(counts.neverConnected)}- color="gray"- active={filter === "inactive"}- onClick={() => toggleFilter("inactive")}- compact={compact}- />- )}- {width >= 380 && (- <WazuhStatTile- label={t("status.pending")}- value={String(counts.pending)}- color="yellow"- compact={compact}- />- )}- </Group>-- {showTable &&- (visibleAgents.length === 0 ? (- <Center style={{ flex: 1 }}>- <Text size="sm" c="dimmed">- {filter === "disconnected" ? t("noDisconnected") : t("empty")}- </Text>- </Center>- ) : (- <ScrollArea style={{ flex: 1 }} type="auto" scrollbarSize={6}>- <table className={classes.table}>- <colgroup>- <col style={{ width: 22 }} />- <col />- {/* Relative widths so the columns keep their proportions at every widget size. */}- {showIp && <col style={{ width: "15%" }} />}- {showOs && <col style={{ width: showGroups ? "23%" : "27%" }} />}- {showVersion && <col style={{ width: "9%" }} />}- <col style={{ width: showIp ? "14%" : "30%" }} />- {showGroups && <col style={{ width: "11%" }} />}- </colgroup>- <thead>- <tr>- <th>- <SortHeader- column="status"- label=""- ariaLabel={t("column.status")}- sort={sort}- onSort={handleSort}- />- </th>- <th>- <SortHeader column="name" label={t("column.name")} sort={sort} onSort={handleSort} />- </th>- {showIp && (- <th>- <SortHeader column="ip" label={t("column.ip")} sort={sort} onSort={handleSort} />- </th>- )}- {showOs && (- <th>- <SortHeader column="os" label={t("column.os")} sort={sort} onSort={handleSort} />- </th>- )}- {showVersion && (- <th>- <SortHeader column="version" label={t("column.version")} sort={sort} onSort={handleSort} />- </th>- )}- <th>- <SortHeader- column="lastKeepAlive"- label={t("column.lastKeepAlive")}- sort={sort}- onSort={handleSort}- />- </th>- {showGroups && <th>{t("column.groups")}</th>}- </tr>- </thead>- <tbody>- {visibleAgents.map((agent) => {- const OsIcon = getOsIcon(agent.osPlatform, agent.osName);- const outdated =- showVersion &&- agent.version !== null &&- newestVersion !== null &&- compareVersions(agent.version, newestVersion) < 0;- return (- <tr key={agent.id}>- <td aria-label={t(`statusLabel.${agent.status}`)}>- <Tooltip label={t(`statusLabel.${agent.status}`)} withArrow openDelay={200}>- <span className={classes.statusDot} data-status={agent.status} />- </Tooltip>- </td>- <td title={`${agent.name} (${agent.id})`}>- {links ? (- <Anchor- href={links.agent(agent.id)}- target="_blank"- rel="noopener noreferrer"- size="xs"- c="inherit"- fw={500}- >- {agent.name}- </Anchor>- ) : (- <Text size="xs" fw={500} span>- {agent.name}- </Text>- )}- {width >= 520 && (- <Text span size="10px" c="dimmed" ml={6} className={classes.mono}>- {agent.id}- </Text>- )}- </td>- {showIp && (- <td className={classes.mono} title={agent.ip ?? undefined}>- {agent.ip ?? "-"}- </td>- )}- {showOs && (- <td title={[agent.osName, agent.osVersion].filter(Boolean).join(" ")}>- <Group gap={5} wrap="nowrap">- <OsIcon size={14} stroke={1.6} style={{ flexShrink: 0, opacity: 0.85 }} />- <Text size="xs" truncate>- {shortOsName(agent.osName) ?? "-"}- {width >= 800 && agent.osVersion ? (- <Text span size="xs" c="dimmed">- {" "}- {agent.osVersion}- </Text>- ) : null}- </Text>- </Group>- </td>- )}- {showVersion && (- <td aria-label={agent.version ?? "-"}>- <Tooltip- label={- outdated ? t("outdated", { version: newestVersion ?? "" }) : (agent.version ?? "-")- }- withArrow- disabled={!agent.version}- >- <Text size="xs" c={outdated ? "yellow.5" : undefined} className={classes.mono}>- {agent.version ?? "-"}- </Text>- </Tooltip>- </td>- )}- <td>- <WazuhRelativeTime value={agent.lastKeepAlive} short />- </td>- {showGroups && (- <td>- <Group gap={3} wrap="nowrap" style={{ overflow: "hidden" }}>- {agent.groups.slice(0, 2).map((group) => (- <WazuhChip key={group}>{group}</WazuhChip>- ))}- {agent.groups.length > 2 && <WazuhChip>{`+${agent.groups.length - 2}`}</WazuhChip>}- </Group>- </td>- )}- </tr>- );- })}- </tbody>- </table>- </ScrollArea>- ))}- </Stack>- </WazuhWidgetFrame>- );-}diff --git a/packages/widgets/src/wazuh-agents/index.ts b/packages/widgets/src/wazuh-agents/index.tsdeleted file mode 100644index d0c488594..000000000--- a/packages/widgets/src/wazuh-agents/index.ts+++ /dev/null@@ -1,43 +0,0 @@-import { IconDevicesPc, IconServerOff } from "@tabler/icons-react";--import { getWidgetIntegrationConfig } from "@homarr/definitions";--import { createWidgetDefinition } from "../definition";-import { optionsBuilder } from "../options";--export const { definition, componentLoader } = createWidgetDefinition("wazuhAgents", {- icon: IconDevicesPc,- ...getWidgetIntegrationConfig("wazuhAgents"),- createOptions() {- return optionsBuilder.from((factory) => ({- statusFilter: factory.select({- defaultValue: "all",- options: [- { value: "all", label: "All agents" },- { value: "active", label: "Active" },- { value: "disconnected", label: "Disconnected" },- { value: "inactive", label: "Not active (disconnected, never connected, pending)" },- ],- }),- sortBy: factory.select({- defaultValue: "status",- options: [- { value: "status", label: "Status" },- { value: "name", label: "Name" },- { value: "ip", label: "IP address" },- { value: "os", label: "Operating system" },- { value: "version", label: "Wazuh version" },- { value: "lastKeepAlive", label: "Last keepalive" },- ],- }),- showVersion: factory.switch({ defaultValue: true }),- showGroups: factory.switch({ defaultValue: true }),- }));- },- errors: {- INTERNAL_SERVER_ERROR: {- icon: IconServerOff,- message: (t) => t("widget.wazuh.error.unknown.title", { target: "Wazuh" }),- },- },-}).withDynamicImport(() => import("./component"));diff --git a/packages/widgets/src/wazuh-alerts/index.ts b/packages/widgets/src/wazuh-alerts/index.tsdeleted file mode 100644index 375323bc4..000000000--- a/packages/widgets/src/wazuh-alerts/index.ts+++ /dev/null@@ -1,42 +0,0 @@-import { IconServerOff, IconShieldBolt } from "@tabler/icons-react";-import { z } from "zod/v4";--import { getWidgetIntegrationConfig } from "@homarr/definitions";--import { createWidgetDefinition } from "../definition";-import { optionsBuilder } from "../options";--export const { definition, componentLoader } = createWidgetDefinition("wazuhAlerts", {- icon: IconShieldBolt,- ...getWidgetIntegrationConfig("wazuhAlerts"),- createOptions() {- return optionsBuilder.from((factory) => ({- minLevel: factory.number({- defaultValue: 7,- step: 1,- withDescription: true,- validate: z.number().int().min(0).max(16),- }),- hours: factory.number({- defaultValue: 24,- step: 1,- validate: z.number().int().min(1).max(720),- }),- limit: factory.number({- defaultValue: 25,- step: 1,- validate: z.number().int().min(1).max(100),- }),- showMitre: factory.switch({ defaultValue: true }),- showAgent: factory.switch({ defaultValue: true }),- showSourceIp: factory.switch({ defaultValue: true }),- showRuleId: factory.switch({ defaultValue: false }),- }));- },- errors: {- INTERNAL_SERVER_ERROR: {- icon: IconServerOff,- message: (t) => t("widget.wazuh.error.unknown.title", { target: "Wazuh" }),- },- },-}).withDynamicImport(() => import("./component"));diff --git a/packages/widgets/src/wazuh-auth-failures/index.ts b/packages/widgets/src/wazuh-auth-failures/index.tsdeleted file mode 100644index 9443bb0d5..000000000--- a/packages/widgets/src/wazuh-auth-failures/index.ts+++ /dev/null@@ -1,25 +0,0 @@-import { IconLockExclamation, IconServerOff } from "@tabler/icons-react";-import { z } from "zod/v4";--import { getWidgetIntegrationConfig } from "@homarr/definitions";--import { createWidgetDefinition } from "../definition";-import { optionsBuilder } from "../options";--export const { definition, componentLoader } = createWidgetDefinition("wazuhAuthFailures", {- icon: IconLockExclamation,- ...getWidgetIntegrationConfig("wazuhAuthFailures"),- createOptions() {- return optionsBuilder.from((factory) => ({- hours: factory.number({ defaultValue: 24, step: 1, validate: z.number().int().min(1).max(168) }),- limit: factory.number({ defaultValue: 6, step: 1, validate: z.number().int().min(1).max(25) }),- showSourceIps: factory.switch({ defaultValue: true }),- }));- },- errors: {- INTERNAL_SERVER_ERROR: {- icon: IconServerOff,- message: (t) => t("widget.wazuh.error.unknown.title", { target: "Wazuh" }),- },- },-}).withDynamicImport(() => import("./component"));diff --git a/packages/widgets/src/wazuh-fim/index.ts b/packages/widgets/src/wazuh-fim/index.tsdeleted file mode 100644index 80aa6193d..000000000--- a/packages/widgets/src/wazuh-fim/index.ts+++ /dev/null@@ -1,35 +0,0 @@-import { IconFileAlert, IconServerOff } from "@tabler/icons-react";-import { z } from "zod/v4";--import { getWidgetIntegrationConfig } from "@homarr/definitions";--import { createWidgetDefinition } from "../definition";-import { optionsBuilder } from "../options";-import { wazuhTimeRangeOptions } from "../wazuh/_shared/options";--export const { definition, componentLoader } = createWidgetDefinition("wazuhFim", {- icon: IconFileAlert,- ...getWidgetIntegrationConfig("wazuhFim"),- createOptions() {- return optionsBuilder.from((factory) => ({- range: factory.select({ defaultValue: "24h", options: [...wazuhTimeRangeOptions] }),- event: factory.select({- defaultValue: "all",- options: [- { value: "all", label: "All events" },- { value: "added", label: "Added" },- { value: "modified", label: "Modified" },- { value: "deleted", label: "Deleted" },- ],- }),- limit: factory.number({ defaultValue: 20, step: 1, validate: z.number().int().min(1).max(100) }),- includeRegistry: factory.switch({ defaultValue: true }),- }));- },- errors: {- INTERNAL_SERVER_ERROR: {- icon: IconServerOff,- message: (t) => t("widget.wazuh.error.unknown.title", { target: "Wazuh" }),- },- },-}).withDynamicImport(() => import("./component"));diff --git a/packages/widgets/src/wazuh-summary/index.ts b/packages/widgets/src/wazuh-summary/index.tsdeleted file mode 100644index 9778b1974..000000000--- a/packages/widgets/src/wazuh-summary/index.ts+++ /dev/null@@ -1,25 +0,0 @@-import { IconServerOff, IconShieldHalfFilled } from "@tabler/icons-react";--import { getWidgetIntegrationConfig } from "@homarr/definitions";--import { createWidgetDefinition } from "../definition";-import { optionsBuilder } from "../options";-import { wazuhTimeRangeOptions } from "../wazuh/_shared/options";--export const { definition, componentLoader } = createWidgetDefinition("wazuhSummary", {- icon: IconShieldHalfFilled,- ...getWidgetIntegrationConfig("wazuhSummary"),- createOptions() {- return optionsBuilder.from((factory) => ({- range: factory.select({ defaultValue: "24h", options: [...wazuhTimeRangeOptions] }),- showTrend: factory.switch({ defaultValue: true }),- showFooter: factory.switch({ defaultValue: true }),- }));- },- errors: {- INTERNAL_SERVER_ERROR: {- icon: IconServerOff,- message: (t) => t("widget.wazuh.error.unknown.title", { target: "Wazuh" }),- },- },-}).withDynamicImport(() => import("./component"));diff --git a/packages/widgets/src/wazuh-timeline/index.ts b/packages/widgets/src/wazuh-timeline/index.tsdeleted file mode 100644index a481c1ad6..000000000--- a/packages/widgets/src/wazuh-timeline/index.ts+++ /dev/null@@ -1,56 +0,0 @@-import { IconChartAreaLine, IconServerOff } from "@tabler/icons-react";-import { z } from "zod/v4";--import { getWidgetIntegrationConfig } from "@homarr/definitions";--import { createWidgetDefinition } from "../definition";-import { optionsBuilder } from "../options";-import { wazuhTimeRangeOptions } from "../wazuh/_shared/options";--export const { definition, componentLoader } = createWidgetDefinition("wazuhTimeline", {- icon: IconChartAreaLine,- ...getWidgetIntegrationConfig("wazuhTimeline"),- createOptions() {- return optionsBuilder.from((factory) => ({- range: factory.select({ defaultValue: "24h", options: [...wazuhTimeRangeOptions] }),- interval: factory.select({- defaultValue: "auto",- options: [- { value: "auto", label: "Automatic" },- { value: "1m", label: "1 minute" },- { value: "5m", label: "5 minutes" },- { value: "15m", label: "15 minutes" },- { value: "30m", label: "30 minutes" },- { value: "1h", label: "1 hour" },- { value: "3h", label: "3 hours" },- { value: "6h", label: "6 hours" },- { value: "12h", label: "12 hours" },- { value: "1d", label: "1 day" },- ],- }),- chartType: factory.select({- defaultValue: "area",- options: [- { value: "area", label: "Stacked area" },- { value: "bar", label: "Stacked bars" },- ],- }),- yScale: factory.select({- defaultValue: "linear",- withDescription: true,- options: [- { value: "linear", label: "Linear" },- { value: "sqrt", label: "Square root (makes rare severities visible)" },- ],- }),- minLevel: factory.number({ defaultValue: 0, step: 1, validate: z.number().int().min(0).max(16) }),- showLegend: factory.switch({ defaultValue: true }),- }));- },- errors: {- INTERNAL_SERVER_ERROR: {- icon: IconServerOff,- message: (t) => t("widget.wazuh.error.unknown.title", { target: "Wazuh" }),- },- },-}).withDynamicImport(() => import("./component"));diff --git a/packages/widgets/src/wazuh-top-list/index.ts b/packages/widgets/src/wazuh-top-list/index.tsdeleted file mode 100644index 2b1d163f5..000000000--- a/packages/widgets/src/wazuh-top-list/index.ts+++ /dev/null@@ -1,37 +0,0 @@-import { IconListNumbers, IconServerOff } from "@tabler/icons-react";-import { z } from "zod/v4";--import { getWidgetIntegrationConfig } from "@homarr/definitions";--import { createWidgetDefinition } from "../definition";-import { optionsBuilder } from "../options";-import { wazuhTimeRangeOptions } from "../wazuh/_shared/options";--export const { definition, componentLoader } = createWidgetDefinition("wazuhTopList", {- icon: IconListNumbers,- ...getWidgetIntegrationConfig("wazuhTopList"),- createOptions() {- return optionsBuilder.from((factory) => ({- kind: factory.select({- defaultValue: "rules",- options: [- { value: "rules", label: "Top rules" },- { value: "agents", label: "Top agents by alerts" },- { value: "sourceIps", label: "Top source IPs" },- { value: "mitreTactics", label: "Top MITRE ATT&CK tactics" },- { value: "mitreTechniques", label: "Top MITRE ATT&CK techniques" },- ],- }),- range: factory.select({ defaultValue: "24h", options: [...wazuhTimeRangeOptions] }),- limit: factory.number({ defaultValue: 8, step: 1, validate: z.number().int().min(1).max(50) }),- minLevel: factory.number({ defaultValue: 0, step: 1, validate: z.number().int().min(0).max(16) }),- showBars: factory.switch({ defaultValue: true }),- }));- },- errors: {- INTERNAL_SERVER_ERROR: {- icon: IconServerOff,- message: (t) => t("widget.wazuh.error.unknown.title", { target: "Wazuh" }),- },- },-}).withDynamicImport(() => import("./component"));diff --git a/packages/widgets/src/wazuh-vulnerabilities/index.ts b/packages/widgets/src/wazuh-vulnerabilities/index.tsdeleted file mode 100644index 33d510e7e..000000000--- a/packages/widgets/src/wazuh-vulnerabilities/index.ts+++ /dev/null@@ -1,41 +0,0 @@-import { IconBug, IconServerOff } from "@tabler/icons-react";-import { z } from "zod/v4";--import { getWidgetIntegrationConfig } from "@homarr/definitions";--import { createWidgetDefinition } from "../definition";-import { optionsBuilder } from "../options";--export const { definition, componentLoader } = createWidgetDefinition("wazuhVulnerabilities", {- icon: IconBug,- ...getWidgetIntegrationConfig("wazuhVulnerabilities"),- createOptions() {- return optionsBuilder.from((factory) => ({- cveOrder: factory.select({- defaultValue: "score",- options: [- { value: "score", label: "Highest score" },- { value: "agents", label: "Most affected agents" },- ],- }),- minSeverity: factory.select({- defaultValue: "all",- options: [- { value: "all", label: "All severities" },- { value: "medium", label: "Medium and above" },- { value: "high", label: "High and above" },- { value: "critical", label: "Critical only" },- ],- }),- cveLimit: factory.number({ defaultValue: 8, step: 1, validate: z.number().int().min(1).max(50) }),- agentLimit: factory.number({ defaultValue: 5, step: 1, validate: z.number().int().min(1).max(50) }),- showAgents: factory.switch({ defaultValue: true }),- }));- },- errors: {- INTERNAL_SERVER_ERROR: {- icon: IconServerOff,- message: (t) => t("widget.wazuh.error.unknown.title", { target: "Wazuh" }),- },- },-}).withDynamicImport(() => import("./component"));diff --git a/packages/widgets/src/wazuh/_shared/error-state.tsx b/packages/widgets/src/wazuh/_shared/error-state.tsxindex 5c3858af2..593949e1c 100644--- a/packages/widgets/src/wazuh/_shared/error-state.tsx+++ b/packages/widgets/src/wazuh/_shared/error-state.tsx@@ -17,6 +17,8 @@ import type { TablerIcon } from "@homarr/ui";const errorIcons: Record<WazuhErrorReason, TablerIcon> = {unauthorized: IconLock,certificate: IconCertificateOff,+ certificateHostname: IconCertificateOff,+ certificateExpired: IconCertificateOff,unreachable: IconPlugConnectedX,timeout: IconClockExclamation,status: IconExclamationCircle,diff --git a/packages/widgets/src/wazuh/component.module.css b/packages/widgets/src/wazuh/component.module.cssnew file mode 100644index 000000000..b2e4d044c--- /dev/null+++ b/packages/widgets/src/wazuh/component.module.css@@ -0,0 +1,43 @@+.root {+ position: relative;+ height: 100%;+}++.panel {+ height: 100%;+}++.tabs {+ position: absolute;+ z-index: 2;+ top: 4px;+ left: 50%;+ transform: translateX(-50%);+ max-width: calc(100% - 8px);+ padding: 2px;+ border-radius: var(--mantine-radius-md);+ background: var(--mantine-color-body);+ box-shadow: var(--mantine-shadow-sm);+ opacity: 0;+ transition: opacity 150ms ease-out;+ pointer-events: none;+}++.root:hover .tabs,+.root:focus-within .tabs {+ opacity: 1;+ pointer-events: auto;+}++@media (any-pointer: coarse) {+ .tabs {+ opacity: 1;+ pointer-events: auto;+ }+}++@media (prefers-reduced-motion: reduce) {+ .tabs {+ transition: none;+ }+}diff --git a/packages/widgets/src/wazuh/component.tsx b/packages/widgets/src/wazuh/component.tsxnew file mode 100644index 000000000..f3678fc81--- /dev/null+++ b/packages/widgets/src/wazuh/component.tsx@@ -0,0 +1,138 @@+"use client";++import { useCallback, useRef } from "react";+import { Box, Tabs, Tooltip } from "@mantine/core";+import {+ IconChartAreaLine,+ IconDevicesPc,+ IconFileAlert,+ IconListNumbers,+ IconLockExclamation,+ IconShieldHalfFilled,+ IconBug,+ IconShieldBolt,+} from "@tabler/icons-react";++import { clientApi } from "@homarr/api/client";+import { useSession } from "@homarr/auth/client";+import { constructBoardPermissions } from "@homarr/auth/shared";+import { useOptionalBoard } from "@homarr/boards/context";+import { showErrorNotification } from "@homarr/notifications";+import { useI18n } from "@homarr/translation/client";+import type { TablerIcon } from "@homarr/ui";++import classes from "./component.module.css";++import type { WidgetComponentProps } from "../definition";+import type { WazuhView } from "./views";+import { getVisibleWazuhViews, resolveWazuhView } from "./views";+import { WazuhAgentsView } from "./views/agents";+import { WazuhAlertsView } from "./views/alerts";+import { WazuhAuthFailuresView } from "./views/auth-failures";+import { WazuhFimView } from "./views/fim";+import { WazuhOverviewView } from "./views/overview";+import { WazuhTimelineView } from "./views/timeline";+import { WazuhTopView } from "./views/top";+import { WazuhVulnerabilitiesView } from "./views/vulnerabilities";+import type { WazuhViewProps } from "./view-props";++const viewIcons: Record<WazuhView, TablerIcon> = {+ overview: IconShieldHalfFilled,+ alerts: IconShieldBolt,+ timeline: IconChartAreaLine,+ top: IconListNumbers,+ agents: IconDevicesPc,+ vulnerabilities: IconBug,+ fim: IconFileAlert,+ authFailures: IconLockExclamation,+};++const viewComponents: Record<WazuhView, (props: WazuhViewProps) => React.ReactNode> = {+ overview: WazuhOverviewView,+ alerts: WazuhAlertsView,+ timeline: WazuhTimelineView,+ top: WazuhTopView,+ agents: WazuhAgentsView,+ vulnerabilities: WazuhVulnerabilitiesView,+ fim: WazuhFimView,+ authFailures: WazuhAuthFailuresView,+};++export default function WazuhWidget(props: WidgetComponentProps<"wazuh">) {+ const { options, setOptions, boardId, itemId } = props;+ const t = useI18n("widget.wazuh");+ const board = useOptionalBoard();+ const { data: session } = useSession();+ const hasChangeAccess = board ? constructBoardPermissions(board, session).hasChangeAccess : false;+ const savePendingRef = useRef(false);+ const { mutate: saveItemOptions } = clientApi.widget.options.saveItemOptions.useMutation({+ onError: () => showErrorNotification({ title: t("error.viewSaveTitle"), message: t("error.viewSaveMessage") }),+ });++ const visibleViews = getVisibleWazuhViews(options.visibleViews);+ const view = resolveWazuhView(options.view, visibleViews);++ // Same flow as the Beszel system switcher: update locally first, then persist the invisible option.+ const handleViewChange = useCallback(+ (value: string | null) => {+ if (!value || value === options.view || savePendingRef.current) return;+ const previousValue = options.view;+ const newView = value as WazuhView;+ setOptions({ newOptions: { view: newView } });+ if (!hasChangeAccess || !boardId || !itemId) return;+ savePendingRef.current = true;+ saveItemOptions(+ { boardId, itemId, newOptions: { view: newView } },+ {+ onError: () => setOptions({ newOptions: { view: previousValue } }),+ onSettled: () => {+ savePendingRef.current = false;+ },+ },+ );+ },+ [boardId, hasChangeAccess, itemId, options.view, saveItemOptions, setOptions],+ );++ if (visibleViews.length <= 1) {+ const View = viewComponents[view];+ return (+ <Box className={classes.root} data-view={view}>+ <View {...props} />+ </Box>+ );+ }++ return (+ <Tabs+ value={view}+ onChange={handleViewChange}+ variant="pills"+ radius="sm"+ className={classes.root}+ data-view={view}+ >+ <Tabs.List className={classes.tabs} style={{ flexWrap: "nowrap" }} aria-label={t("name")}>+ {visibleViews.map((value) => {+ const Icon = viewIcons[value];+ return (+ <Tooltip key={value} label={t(`view.${value}`)} withArrow openDelay={200}>+ <Tabs.Tab value={value} px={8} py={4} aria-label={t(`view.${value}`)}>+ <Icon size={16} stroke={1.8} />+ </Tabs.Tab>+ </Tooltip>+ );+ })}+ </Tabs.List>+ {visibleViews.map((value) => {+ const View = viewComponents[value];+ // Every tab has a panel so aria-controls/aria-labelledby resolve; only the active one renders its view.+ return (+ <Tabs.Panel key={value} value={value} className={classes.panel}>+ <View {...props} />+ </Tabs.Panel>+ );+ })}+ </Tabs>+ );+}diff --git a/packages/widgets/src/wazuh/index.ts b/packages/widgets/src/wazuh/index.tsnew file mode 100644index 000000000..b2df4ee84--- /dev/null+++ b/packages/widgets/src/wazuh/index.ts@@ -0,0 +1,172 @@+import { IconServerOff, IconShieldHalfFilled } from "@tabler/icons-react";+import { z } from "zod/v4";++import { getWidgetIntegrationConfig } from "@homarr/definitions";++import { createWidgetDefinition } from "../definition";+import { optionsBuilder } from "../options";+import { wazuhTimeRangeOptions } from "./_shared/options";+import type { WazuhView } from "./views";+import { wazuhViews } from "./views";++const hidden = { shouldHide: () => true };++export const { definition, componentLoader } = createWidgetDefinition("wazuh", {+ icon: IconShieldHalfFilled,+ ...getWidgetIntegrationConfig("wazuh"),+ createOptions() {+ return optionsBuilder.from(+ (factory) => ({+ visibleViews: factory.multiSelect({+ withDescription: true,+ options: wazuhViews.map((value) => ({ value, label: (t) => t(`widget.wazuh.view.${value}`) })),+ defaultValue: [...wazuhViews],+ }),+ range: factory.select({ defaultValue: "24h", options: [...wazuhTimeRangeOptions] }),+ minLevel: factory.number({ defaultValue: 0, step: 1, validate: z.number().int().min(0).max(16) }),++ // Severity tab+ showTrend: factory.switch({ defaultValue: true }),+ showFooter: factory.switch({ defaultValue: true }),++ // Alerts tab+ alertsMinLevel: factory.number({+ defaultValue: 7,+ step: 1,+ withDescription: true,+ validate: z.number().int().min(0).max(16),+ }),+ alertsLimit: factory.number({ defaultValue: 25, step: 1, validate: z.number().int().min(1).max(100) }),+ showMitre: factory.switch({ defaultValue: true }),+ showAgent: factory.switch({ defaultValue: true }),+ showSourceIp: factory.switch({ defaultValue: true }),+ showRuleId: factory.switch({ defaultValue: false }),++ // Timeline tab+ interval: factory.select({+ defaultValue: "auto",+ options: [+ { value: "auto", label: "Automatic" },+ { value: "1m", label: "1 minute" },+ { value: "5m", label: "5 minutes" },+ { value: "15m", label: "15 minutes" },+ { value: "30m", label: "30 minutes" },+ { value: "1h", label: "1 hour" },+ { value: "3h", label: "3 hours" },+ { value: "6h", label: "6 hours" },+ { value: "12h", label: "12 hours" },+ { value: "1d", label: "1 day" },+ ],+ }),+ chartType: factory.select({+ defaultValue: "area",+ options: [+ { value: "area", label: "Stacked area" },+ { value: "bar", label: "Stacked bars" },+ ],+ }),+ yScale: factory.select({+ defaultValue: "linear",+ withDescription: true,+ options: [+ { value: "linear", label: "Linear" },+ { value: "sqrt", label: "Square root (makes rare severities visible)" },+ ],+ }),+ showLegend: factory.switch({ defaultValue: true }),++ // Top lists tab+ topKind: factory.select({+ defaultValue: "rules",+ options: [+ { value: "rules", label: "Top rules" },+ { value: "agents", label: "Top agents by alerts" },+ { value: "sourceIps", label: "Top source IPs" },+ { value: "mitreTactics", label: "Top MITRE ATT&CK tactics" },+ { value: "mitreTechniques", label: "Top MITRE ATT&CK techniques" },+ ],+ }),+ topLimit: factory.number({ defaultValue: 8, step: 1, validate: z.number().int().min(1).max(50) }),+ showBars: factory.switch({ defaultValue: true }),++ // Agents tab+ agentStatusFilter: factory.select({+ defaultValue: "all",+ options: [+ { value: "all", label: "All agents" },+ { value: "active", label: "Active" },+ { value: "disconnected", label: "Disconnected" },+ { value: "inactive", label: "Not active (disconnected, never connected, pending)" },+ ],+ }),+ agentSortBy: factory.select({+ defaultValue: "status",+ options: [+ { value: "status", label: "Status" },+ { value: "name", label: "Name" },+ { value: "ip", label: "IP address" },+ { value: "os", label: "Operating system" },+ { value: "version", label: "Wazuh version" },+ { value: "lastKeepAlive", label: "Last keepalive" },+ ],+ }),+ showVersion: factory.switch({ defaultValue: true }),+ showGroups: factory.switch({ defaultValue: true }),++ // Vulnerabilities tab+ cveOrder: factory.select({+ defaultValue: "score",+ options: [+ { value: "score", label: "Highest score" },+ { value: "agents", label: "Most affected agents" },+ ],+ }),+ minSeverity: factory.select({+ defaultValue: "all",+ options: [+ { value: "all", label: "All severities" },+ { value: "medium", label: "Medium and above" },+ { value: "high", label: "High and above" },+ { value: "critical", label: "Critical only" },+ ],+ }),+ cveLimit: factory.number({ defaultValue: 8, step: 1, validate: z.number().int().min(1).max(50) }),+ agentLimit: factory.number({ defaultValue: 5, step: 1, validate: z.number().int().min(1).max(50) }),+ showAgents: factory.switch({ defaultValue: true }),++ // File integrity tab+ fimEvent: factory.select({+ defaultValue: "all",+ options: [+ { value: "all", label: "All events" },+ { value: "added", label: "Added" },+ { value: "modified", label: "Modified" },+ { value: "deleted", label: "Deleted" },+ ],+ }),+ fimLimit: factory.number({ defaultValue: 20, step: 1, validate: z.number().int().min(1).max(100) }),+ includeRegistry: factory.switch({ defaultValue: true }),++ // Authentication failures tab+ authLimit: factory.number({ defaultValue: 6, step: 1, validate: z.number().int().min(1).max(25) }),+ showSourceIps: factory.switch({ defaultValue: true }),++ // Saved from the widget itself, like the qBittorrent table layout+ view: factory.internal<WazuhView>({ defaultValue: "overview" }),+ // Agents table layout+ columnOrder: factory.text({ defaultValue: "" }),+ columnWidths: factory.text({ defaultValue: "" }),+ }),+ {+ columnOrder: hidden,+ columnWidths: hidden,+ },+ );+ },+ errors: {+ INTERNAL_SERVER_ERROR: {+ icon: IconServerOff,+ message: (t) => t("widget.wazuh.error.unknown.title", { target: "Wazuh" }),+ },+ },+}).withDynamicImport(() => import("./component"));diff --git a/packages/widgets/src/wazuh/view-props.ts b/packages/widgets/src/wazuh/view-props.tsnew file mode 100644index 000000000..3a6a3a328--- /dev/null+++ b/packages/widgets/src/wazuh/view-props.ts@@ -0,0 +1,7 @@+import type { WidgetComponentProps } from "../definition";++/** Every tab renders with the props of the combined widget, so options are shared across tabs. */+export type WazuhViewProps = Pick<+ WidgetComponentProps<"wazuh">,+ "integrationIds" | "options" | "width" | "height" | "isEditMode" | "boardId" | "itemId" | "setOptions"+>;diff --git a/packages/widgets/src/wazuh/views.spec.ts b/packages/widgets/src/wazuh/views.spec.tsnew file mode 100644index 000000000..0636d4be2--- /dev/null+++ b/packages/widgets/src/wazuh/views.spec.ts@@ -0,0 +1,32 @@+import { describe, expect, test } from "vitest";++import { getVisibleWazuhViews, getWazuhRangeHours, resolveWazuhView, wazuhViews } from "./views";++describe("getVisibleWazuhViews", () => {+ test("keeps the canonical tab order", () => {+ expect(getVisibleWazuhViews(["fim", "overview"])).toEqual(["overview", "fim"]);+ });++ test("falls back to every tab when nothing valid is selected", () => {+ expect(getVisibleWazuhViews([])).toEqual([...wazuhViews]);+ expect(getVisibleWazuhViews(["removed"])).toEqual([...wazuhViews]);+ });+});++describe("resolveWazuhView", () => {+ test("uses the saved tab while it is visible", () => {+ expect(resolveWazuhView("agents", ["overview", "agents"])).toBe("agents");+ });++ test("falls back to the first visible tab", () => {+ expect(resolveWazuhView("agents", ["timeline", "fim"])).toBe("timeline");+ expect(resolveWazuhView(undefined, ["fim"])).toBe("fim");+ });+});++describe("getWazuhRangeHours", () => {+ test("converts the range to hours", () => {+ expect(getWazuhRangeHours("24h")).toBe(24);+ expect(getWazuhRangeHours("30d")).toBe(720);+ });+});diff --git a/packages/widgets/src/wazuh/views.ts b/packages/widgets/src/wazuh/views.tsnew file mode 100644index 000000000..7fed20c91--- /dev/null+++ b/packages/widgets/src/wazuh/views.ts@@ -0,0 +1,32 @@+import type { WazuhTimeRange } from "@homarr/integrations/types";++export const wazuhViews = [+ "overview",+ "alerts",+ "timeline",+ "top",+ "agents",+ "vulnerabilities",+ "fim",+ "authFailures",+] as const;+export type WazuhView = (typeof wazuhViews)[number];++const isWazuhView = (value: unknown): value is WazuhView =>+ typeof value === "string" && (wazuhViews as readonly string[]).includes(value);++/** Visible tabs in their canonical order. An empty or invalid selection falls back to all tabs. */+export const getVisibleWazuhViews = (visibleViews: readonly string[]): WazuhView[] => {+ const selected = wazuhViews.filter((view) => visibleViews.includes(view));+ return selected.length > 0 ? selected : [...wazuhViews];+};++/** The saved tab if it is still visible, otherwise the first visible tab. */+export const resolveWazuhView = (view: unknown, visibleViews: readonly WazuhView[]): WazuhView => {+ if (isWazuhView(view) && visibleViews.includes(view)) return view;+ return visibleViews[0] ?? "overview";+};++const rangeHours: Record<WazuhTimeRange, number> = { "1h": 1, "24h": 24, "7d": 168, "30d": 720 };++export const getWazuhRangeHours = (range: WazuhTimeRange) => rangeHours[range];diff --git a/packages/widgets/src/wazuh/views/agents.tsx b/packages/widgets/src/wazuh/views/agents.tsxnew file mode 100644index 000000000..f3b588354--- /dev/null+++ b/packages/widgets/src/wazuh/views/agents.tsx@@ -0,0 +1,429 @@+"use client";++import { useMemo, useState } from "react";+import { Anchor, Badge, Box, Center, Group, Stack, Text, Tooltip } from "@mantine/core";+import {+ IconBrandAndroid,+ IconBrandApple,+ IconBrandDebian,+ IconBrandRedhat,+ IconBrandUbuntu,+ IconBrandWindows,+ IconDevicesPc,+ IconServer,+} from "@tabler/icons-react";+import dayjs from "dayjs";+import type { DataTableColumn, DataTableSortStatus } from "mantine-datatable";++import { clientApi } from "@homarr/api/client";+import { useSession } from "@homarr/auth/client";+import { constructBoardPermissions } from "@homarr/auth/shared";+import { useOptionalBoard } from "@homarr/boards/context";+import type { WazuhAgent } from "@homarr/integrations/types";+import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";+import type { TablerIcon } from "@homarr/ui";++import { WidgetEmptyState } from "../../common/empty-state";+import { HomarrDataTable } from "../../common/homarr-data-table";+import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../../common/query-state";+import { usePersistedTableLayout, useTableLayoutPersistence } from "../../common/use-persisted-table-layout";+import { useWidgetNow } from "../../common/use-widget-now";+import type { WazuhViewProps } from "../view-props";+import { WazuhChip } from "../_shared/badges";+import { WazuhErrorState } from "../_shared/error-state";+import { WazuhRelativeTime, WazuhPendingState, WazuhStatTile, WazuhWidgetFrame } from "../_shared/frame";+import { useWazuhLinks } from "../_shared/use-wazuh-links";+import classes from "../_shared/wazuh.module.css";++type SortKey = "status" | "name" | "ip" | "os" | "version" | "lastKeepAlive";+type StatusFilter = "all" | "active" | "disconnected" | "inactive" | "never_connected";++const statusOrder: Record<WazuhAgent["status"], number> = {+ disconnected: 0,+ pending: 1,+ never_connected: 2,+ unknown: 3,+ active: 4,+};++const getOsIcon = (platform: string | null, name: string | null): TablerIcon => {+ const value = `${platform ?? ""} ${name ?? ""}`.toLowerCase();+ if (value.includes("windows")) return IconBrandWindows;+ if (value.includes("ubuntu")) return IconBrandUbuntu;+ if (value.includes("debian")) return IconBrandDebian;+ if (value.includes("darwin") || value.includes("mac")) return IconBrandApple;+ if (value.includes("android")) return IconBrandAndroid;+ if (/(rhel|red ?hat|centos|rocky|alma|fedora|amzn|oracle)/.test(value)) return IconBrandRedhat;+ return IconServer;+};++// Keep the OS cell readable in narrow columns: "Microsoft Windows 11 Pro" -> "Windows 11 Pro", "Debian GNU/Linux" -> "Debian".+const shortOsName = (name: string | null) =>+ name+ ?.replace(/^Microsoft\s+/i, "")+ .replace(/\s*GNU\/Linux/i, "")+ .replace(/\s*\(.*\)\s*$/, "")+ .trim() ?? null;++const parseVersion = (value: string | null) =>+ (value ?? "")+ .replace(/^v/, "")+ .split(".")+ .map((part) => Number.parseInt(part, 10) || 0);++const compareVersions = (left: string | null, right: string | null) => {+ const [a, b] = [parseVersion(left), parseVersion(right)];+ for (let index = 0; index < Math.max(a.length, b.length); index++) {+ const diff = (a[index] ?? 0) - (b[index] ?? 0);+ if (diff !== 0) return diff;+ }+ return 0;+};++const ipToNumber = (ip: string | null) =>+ (ip ?? "").split(".").reduce((total, part) => total * 256 + (Number.parseInt(part, 10) || 0), 0);++const compareIps = (left: string | null, right: string | null) => ipToNumber(left) - ipToNumber(right);++const sorters: Record<SortKey, (left: WazuhAgent, right: WazuhAgent) => number> = {+ status: (left, right) => statusOrder[left.status] - statusOrder[right.status] || left.name.localeCompare(right.name),+ name: (left, right) => left.name.localeCompare(right.name),+ ip: (left, right) => compareIps(left.ip, right.ip),+ os: (left, right) => (left.osName ?? "~").localeCompare(right.osName ?? "~") || left.name.localeCompare(right.name),+ version: (left, right) => compareVersions(left.version, right.version) || left.name.localeCompare(right.name),+ // Most recent first by default.+ lastKeepAlive: (left, right) => (right.lastKeepAlive ?? "").localeCompare(left.lastKeepAlive ?? ""),+};++const agentColumnAccessors = ["status", "name", "ip", "os", "version", "lastKeepAlive", "groups"] as const;++const snapshotColor = (ageMs: number) => {+ if (ageMs < 20 * 60_000) return "green";+ if (ageMs < 2 * 60 * 60_000) return "yellow";+ return "red";+};++export function WazuhAgentsView({+ integrationIds,+ options,+ width,+ height,+ isEditMode,+ boardId,+ itemId,+ setOptions,+}: WazuhViewProps) {+ const t = useI18n("widget.wazuh.agents");+ const locale = useCurrentIntlLocale();+ const now = useWidgetNow("minute");+ const integrationId = integrationIds[0] ?? "";+ const query = clientApi.widget.wazuh.getAgents.useQuery(+ { integrationId },+ { staleTime: 60_000, refetchInterval: 60_000 },+ );+ const result = getUsableWidgetQueryData(query);+ const links = useWazuhLinks(result?.dashboardUrl);++ const [filter, setFilter] = useState<StatusFilter>(options.agentStatusFilter);+ const [sortStatus, setSortStatus] = useState<DataTableSortStatus<WazuhAgent>>({+ columnAccessor: options.agentSortBy,+ direction: "asc",+ });++ const agents = result?.data?.agents;+ const showTable = height >= 190;+ const showVersion = showTable && options.showVersion && width >= 600;+ const newestVersion = useMemo(() => {+ if (!showVersion) return null;+ return (agents ?? []).reduce<string | null>(+ (newest, agent) => (compareVersions(agent.version, newest) > 0 ? agent.version : newest),+ null,+ );+ }, [agents, showVersion]);+ const visibleAgents = useMemo(() => {+ if (!showTable) return [];+ const filtered = (agents ?? []).filter((agent) => {+ if (filter === "all") return true;+ if (filter === "inactive") return agent.status !== "active";+ return agent.status === filter;+ });+ const sorter = sorters[sortStatus.columnAccessor as SortKey] ?? sorters.status;+ const sorted = filtered.toSorted(sorter);+ return sortStatus.direction === "desc" ? sorted.toReversed() : sorted;+ }, [agents, filter, sortStatus, showTable]);++ const board = useOptionalBoard();+ const { data: session } = useSession();+ const hasChangeAccess = board ? constructBoardPermissions(board, session).hasChangeAccess : false;+ const { mutate: saveItemOptions } = clientApi.widget.options.saveItemOptions.useMutation({+ scope: { id: `wazuh-agents-layout:${boardId ?? "preview"}:${itemId ?? "preview"}` },+ });+ const persistLayout = useTableLayoutPersistence({+ boardId,+ hasChangeAccess,+ itemId,+ saveItemOptions,+ setOptions,+ });++ const showIp = width >= 380;+ const showOs = width >= 460;+ const showGroups = options.showGroups && width >= 720;+ const columns = useMemo<DataTableColumn<WazuhAgent>[]>(() => {+ const all: (DataTableColumn<WazuhAgent> & { visible: boolean })[] = [+ {+ accessor: "status",+ title: "",+ width: 26,+ sortable: true,+ visible: true,+ render: (agent) => (+ <Tooltip label={t(`statusLabel.${agent.status}`)} withArrow openDelay={200}>+ <span+ className={classes.statusDot}+ data-status={agent.status}+ aria-label={t(`statusLabel.${agent.status}`)}+ />+ </Tooltip>+ ),+ },+ {+ accessor: "name",+ title: t("column.name"),+ width: 170,+ sortable: true,+ ellipsis: true,+ visible: true,+ render: (agent) => (+ <Group gap={6} wrap="nowrap" title={`${agent.name} (${agent.id})`} style={{ overflow: "hidden" }}>+ {links ? (+ <Anchor+ href={links.agent(agent.id)}+ target="_blank"+ rel="noopener noreferrer"+ size="xs"+ c="inherit"+ fw={500}+ truncate+ >+ {agent.name}+ </Anchor>+ ) : (+ <Text size="xs" fw={500} truncate>+ {agent.name}+ </Text>+ )}+ {width >= 520 && (+ <Text span size="10px" c="dimmed" className={classes.mono}>+ {agent.id}+ </Text>+ )}+ </Group>+ ),+ },+ {+ accessor: "ip",+ title: t("column.ip"),+ width: 110,+ sortable: true,+ ellipsis: true,+ visible: showIp,+ cellsClassName: classes.mono,+ render: (agent) => agent.ip ?? "-",+ },+ {+ accessor: "os",+ title: t("column.os"),+ width: 160,+ sortable: true,+ visible: showOs,+ render: (agent) => {+ const OsIcon = getOsIcon(agent.osPlatform, agent.osName);+ return (+ <Group gap={5} wrap="nowrap" title={[agent.osName, agent.osVersion].filter(Boolean).join(" ")}>+ <OsIcon size={14} stroke={1.6} style={{ flexShrink: 0, opacity: 0.85 }} />+ <Text size="xs" truncate>+ {shortOsName(agent.osName) ?? "-"}+ {width >= 800 && agent.osVersion ? (+ <Text span size="xs" c="dimmed">+ {" "}+ {agent.osVersion}+ </Text>+ ) : null}+ </Text>+ </Group>+ );+ },+ },+ {+ accessor: "version",+ title: t("column.version"),+ width: 80,+ sortable: true,+ visible: showVersion,+ render: (agent) => {+ const outdated =+ agent.version !== null && newestVersion !== null && compareVersions(agent.version, newestVersion) < 0;+ return (+ <Tooltip+ label={outdated ? t("outdated", { version: newestVersion ?? "" }) : (agent.version ?? "-")}+ withArrow+ disabled={!agent.version}+ >+ <Text size="xs" c={outdated ? "yellow.5" : undefined} className={classes.mono}>+ {agent.version ?? "-"}+ </Text>+ </Tooltip>+ );+ },+ },+ {+ accessor: "lastKeepAlive",+ title: t("column.lastKeepAlive"),+ width: 90,+ sortable: true,+ visible: true,+ render: (agent) => <WazuhRelativeTime value={agent.lastKeepAlive} short />,+ },+ {+ accessor: "groups",+ title: t("column.groups"),+ width: 110,+ visible: showGroups,+ render: (agent) => (+ <Group gap={3} wrap="nowrap" style={{ overflow: "hidden" }}>+ {agent.groups.slice(0, 2).map((group) => (+ <WazuhChip key={group}>{group}</WazuhChip>+ ))}+ {agent.groups.length > 2 && <WazuhChip>{`+${agent.groups.length - 2}`}</WazuhChip>}+ </Group>+ ),+ },+ ];+ return all.filter(({ visible }) => visible).map(({ visible: _visible, ...column }) => column);+ }, [links, newestVersion, showGroups, showIp, showOs, showVersion, t, width]);+ const { effectiveColumns, storeKey } = usePersistedTableLayout({+ columns,+ columnAccessors: agentColumnAccessors,+ columnOrder: options.columnOrder,+ columnWidths: options.columnWidths,+ itemId,+ storeKeyPrefix: "wazuh-agents",+ onLayoutChange: persistLayout,+ });++ const compact = height < 170 || width < 260;++ if (isInitialWidgetQueryPending(query)) {+ return (+ <WazuhWidgetFrame icon={IconDevicesPc} title={t("title")} compact={compact} iconColor="teal">+ <WazuhPendingState />+ </WazuhWidgetFrame>+ );+ }+ if (!result) return <WidgetEmptyState />;+ if (result.error) return <WazuhErrorState error={result.error} compact={height < 160} />;++ const overview = result.data;+ const counts = overview.counts;+ const snapshotAgeMs = (now ?? new Date()).getTime() - new Date(overview.asOf).getTime();+ const toggleFilter = (value: StatusFilter) => setFilter((current) => (current === value ? "all" : value));++ const sourceBadge =+ overview.source === "api" ? (+ <Badge size="sm" variant="dot" color="green" radius="sm">+ {t("live")}+ </Badge>+ ) : (+ <Tooltip+ label={+ snapshotAgeMs > 2 * 60 * 60_000+ ? t("staleSnapshot", { time: new Date(overview.asOf).toLocaleString(locale) })+ : t("snapshotHint", { time: new Date(overview.asOf).toLocaleString(locale) })+ }+ withArrow+ multiline+ w={260}+ >+ <Badge size="sm" variant="dot" color={snapshotColor(snapshotAgeMs)} radius="sm">+ {width >= 300+ ? t("snapshot", { age: dayjs(overview.asOf).fromNow(true) })+ : dayjs(overview.asOf).fromNow(true)}+ </Badge>+ </Tooltip>+ );++ return (+ <WazuhWidgetFrame+ icon={IconDevicesPc}+ title={t("total", { count: String(counts.total) })}+ href={links?.agents}+ compact={compact}+ iconColor="teal"+ headerRight={sourceBadge}+ >+ <Stack h="100%" gap={8}>+ <Group gap={6} wrap="nowrap" grow>+ <WazuhStatTile+ label={t("status.active")}+ value={String(counts.active)}+ color="green"+ active={filter === "active"}+ onClick={() => toggleFilter("active")}+ compact={compact}+ />+ <WazuhStatTile+ label={t("status.disconnected")}+ value={String(counts.disconnected)}+ color="red"+ active={filter === "disconnected"}+ onClick={() => toggleFilter("disconnected")}+ compact={compact}+ />+ {width >= 300 && (+ <WazuhStatTile+ label={t("status.neverConnected")}+ value={String(counts.neverConnected)}+ color="gray"+ active={filter === "never_connected"}+ onClick={() => toggleFilter("never_connected")}+ compact={compact}+ />+ )}+ {width >= 380 && (+ <WazuhStatTile+ label={t("status.pending")}+ value={String(counts.pending)}+ color="yellow"+ compact={compact}+ />+ )}+ </Group>++ {showTable &&+ (visibleAgents.length === 0 ? (+ <Center style={{ flex: 1 }}>+ <Text size="sm" c="dimmed">+ {filter === "disconnected" ? t("noDisconnected") : t("empty")}+ </Text>+ </Center>+ ) : (+ <Box style={{ flex: 1, minHeight: 0 }}>+ <HomarrDataTable+ isEditMode={isEditMode}+ cellPadding="2px 6px"+ rowCursor="default"+ fz="xs"+ records={visibleAgents}+ columns={effectiveColumns}+ storeColumnsKey={storeKey}+ sortStatus={sortStatus}+ onSortStatusChange={isEditMode ? undefined : setSortStatus}+ idAccessor="id"+ />+ </Box>+ ))}+ </Stack>+ </WazuhWidgetFrame>+ );+}diff --git a/packages/widgets/src/wazuh-alerts/component.tsx b/packages/widgets/src/wazuh/views/alerts.tsxsimilarity index 86%rename from packages/widgets/src/wazuh-alerts/component.tsxrename to packages/widgets/src/wazuh/views/alerts.tsxindex 41c49f65b..3645bce56 100644--- a/packages/widgets/src/wazuh-alerts/component.tsx+++ b/packages/widgets/src/wazuh/views/alerts.tsx@@ -6,32 +6,29 @@ import { IconDeviceDesktop, IconShieldBolt, IconShieldCheck, IconWorld } from "@import { clientApi } from "@homarr/api/client";import { useI18n } from "@homarr/translation/client";-import { WidgetEmptyState } from "../common/empty-state";-import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../common/query-state";-import type { WidgetComponentProps } from "../definition";-import { isPrivateIp, WazuhChip, WazuhLevelBadge } from "../wazuh/_shared/badges";-import { WazuhErrorState } from "../wazuh/_shared/error-state";-import { WazuhRelativeTime, WazuhPendingState, WazuhWidgetFrame } from "../wazuh/_shared/frame";-import { getWazuhSeverityForLevel, wazuhSeverities, wazuhSeverityColors } from "../wazuh/_shared/severity";-import { useWazuhLinks } from "../wazuh/_shared/use-wazuh-links";-import classes from "../wazuh/_shared/wazuh.module.css";+import { WidgetEmptyState } from "../../common/empty-state";+import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../../common/query-state";+import { getWazuhRangeHours } from "../views";+import type { WazuhViewProps } from "../view-props";+import { isPrivateIp, WazuhChip, WazuhLevelBadge } from "../_shared/badges";+import { WazuhErrorState } from "../_shared/error-state";+import { WazuhRelativeTime, WazuhPendingState, WazuhWidgetFrame } from "../_shared/frame";+import { getWazuhSeverityForLevel, wazuhSeverities, wazuhSeverityColors } from "../_shared/severity";+import { useWazuhLinks } from "../_shared/use-wazuh-links";+import classes from "../_shared/wazuh.module.css";-export default function WazuhAlertsWidget({- integrationIds,- options,- width,- height,-}: WidgetComponentProps<"wazuhAlerts">) {- const t = useI18n("widget.wazuhAlerts");+export function WazuhAlertsView({ integrationIds, options, width, height }: WazuhViewProps) {+ const t = useI18n("widget.wazuh.alerts");const integrationId = integrationIds[0] ?? "";+ const hours = getWazuhRangeHours(options.range);const query = clientApi.widget.wazuh.getAlerts.useQuery(- { integrationId, minLevel: options.minLevel, limit: options.limit, hours: options.hours },+ { integrationId, minLevel: options.alertsMinLevel, limit: options.alertsLimit, hours },{ staleTime: 60_000, refetchInterval: 60_000 },);const result = getUsableWidgetQueryData(query);const links = useWazuhLinks(result?.dashboardUrl);const compact = height < 170 || width < 260;- const title = t("title", { level: String(options.minLevel), hours: String(options.hours) });+ const title = t("title", { level: String(options.alertsMinLevel), hours: String(hours) });if (isInitialWidgetQueryPending(query)) {return (@@ -57,7 +54,7 @@ export default function WazuhAlertsWidget({<WazuhWidgetFrameicon={IconShieldBolt}title={title}- href={links?.events({ query: `rule.level >= ${options.minLevel}`, from: `now-${options.hours}h` })}+ href={links?.events({ query: `rule.level >= ${options.alertsMinLevel}`, from: `now-${hours}h` })}compact={compact}iconColor="orange"headerRight={diff --git a/packages/widgets/src/wazuh-auth-failures/component.tsx b/packages/widgets/src/wazuh/views/auth-failures.tsxsimilarity index 89%rename from packages/widgets/src/wazuh-auth-failures/component.tsxrename to packages/widgets/src/wazuh/views/auth-failures.tsxindex 4373f2f5d..de818df2d 100644--- a/packages/widgets/src/wazuh-auth-failures/component.tsx+++ b/packages/widgets/src/wazuh/views/auth-failures.tsx@@ -7,36 +7,33 @@ import { IconLockExclamation, IconShieldCheck } from "@tabler/icons-react";import { clientApi } from "@homarr/api/client";import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";-import { WidgetEmptyState } from "../common/empty-state";-import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../common/query-state";-import type { WidgetComponentProps } from "../definition";-import { isPrivateIp, WazuhChip } from "../wazuh/_shared/badges";-import { WazuhErrorState } from "../wazuh/_shared/error-state";-import { WazuhRelativeTime, WazuhPendingState, WazuhStatTile, WazuhWidgetFrame } from "../wazuh/_shared/frame";-import { formatWazuhCount } from "../wazuh/_shared/severity";-import { useWazuhLinks } from "../wazuh/_shared/use-wazuh-links";-import classes from "../wazuh/_shared/wazuh.module.css";+import { WidgetEmptyState } from "../../common/empty-state";+import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../../common/query-state";+import { getWazuhRangeHours } from "../views";+import type { WazuhViewProps } from "../view-props";+import { isPrivateIp, WazuhChip } from "../_shared/badges";+import { WazuhErrorState } from "../_shared/error-state";+import { WazuhRelativeTime, WazuhPendingState, WazuhStatTile, WazuhWidgetFrame } from "../_shared/frame";+import { formatWazuhCount } from "../_shared/severity";+import { useWazuhLinks } from "../_shared/use-wazuh-links";+import classes from "../_shared/wazuh.module.css";const authQuery ='rule.groups:"authentication_failed" or rule.groups:"authentication_failures" or rule.groups:"invalid_login" or rule.mitre.id:"T1110"';-export default function WazuhAuthFailuresWidget({- integrationIds,- options,- width,- height,-}: WidgetComponentProps<"wazuhAuthFailures">) {- const t = useI18n("widget.wazuhAuthFailures");+export function WazuhAuthFailuresView({ integrationIds, options, width, height }: WazuhViewProps) {+ const t = useI18n("widget.wazuh.authFailures");const locale = useCurrentIntlLocale();const integrationId = integrationIds[0] ?? "";+ const hours = getWazuhRangeHours(options.range);const query = clientApi.widget.wazuh.getAuthFailures.useQuery(- { integrationId, hours: options.hours, limit: options.limit },+ { integrationId, hours, limit: options.authLimit },{ staleTime: 60_000, refetchInterval: 60_000 },);const result = getUsableWidgetQueryData(query);const links = useWazuhLinks(result?.dashboardUrl);const compact = height < 170 || width < 260;- const title = t("title", { hours: String(options.hours) });+ const title = t("title", { hours: String(hours) });if (isInitialWidgetQueryPending(query)) {return (@@ -54,7 +51,7 @@ export default function WazuhAuthFailuresWidget({const showTrend = height >= 330 && data.series.length > 1;// Let the overall trend grow into whatever the agent rows leave free (roughly 58px per row).const trendHeight = Math.min(72, Math.max(40, height - 210 - data.agents.length * 58));- const eventsHref = links?.events({ query: authQuery, from: `now-${options.hours}h` });+ const eventsHref = links?.events({ query: authQuery, from: `now-${hours}h` });return (<WazuhWidgetFrame@@ -151,7 +148,7 @@ export default function WazuhAuthFailuresWidget({href={links.events({agentId: agent.agentId,query: authQuery,- from: `now-${options.hours}h`,+ from: `now-${hours}h`,})}target="_blank"rel="noopener noreferrer"diff --git a/packages/widgets/src/wazuh-fim/component.tsx b/packages/widgets/src/wazuh/views/fim.tsxsimilarity index 88%rename from packages/widgets/src/wazuh-fim/component.tsxrename to packages/widgets/src/wazuh/views/fim.tsxindex dd58ea976..708e7010c 100644--- a/packages/widgets/src/wazuh-fim/component.tsx+++ b/packages/widgets/src/wazuh/views/fim.tsx@@ -15,15 +15,15 @@ import type { WazuhFimEntry } from "@homarr/integrations/types";import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";import type { TablerIcon } from "@homarr/ui";-import { WidgetEmptyState } from "../common/empty-state";-import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../common/query-state";-import type { WidgetComponentProps } from "../definition";-import { WazuhChip } from "../wazuh/_shared/badges";-import { WazuhErrorState } from "../wazuh/_shared/error-state";-import { WazuhLegendChip, WazuhRelativeTime, WazuhPendingState, WazuhWidgetFrame } from "../wazuh/_shared/frame";-import { formatWazuhCount } from "../wazuh/_shared/severity";-import { useWazuhLinks } from "../wazuh/_shared/use-wazuh-links";-import classes from "../wazuh/_shared/wazuh.module.css";+import { WidgetEmptyState } from "../../common/empty-state";+import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../../common/query-state";+import type { WazuhViewProps } from "../view-props";+import { WazuhChip } from "../_shared/badges";+import { WazuhErrorState } from "../_shared/error-state";+import { WazuhLegendChip, WazuhRelativeTime, WazuhPendingState, WazuhWidgetFrame } from "../_shared/frame";+import { formatWazuhCount } from "../_shared/severity";+import { useWazuhLinks } from "../_shared/use-wazuh-links";+import classes from "../_shared/wazuh.module.css";const eventStyles: Record<WazuhFimEntry["event"], { icon: TablerIcon; color: string }> = {added: { icon: IconFilePlus, color: "green" },@@ -38,8 +38,8 @@ const formatPath = (entry: WazuhFimEntry) => {return entry.valueName ? `${path}\\${entry.valueName}` : path;};-export default function WazuhFimWidget({ integrationIds, options, width, height }: WidgetComponentProps<"wazuhFim">) {- const t = useI18n("widget.wazuhFim");+export function WazuhFimView({ integrationIds, options, width, height }: WazuhViewProps) {+ const t = useI18n("widget.wazuh.fim");const tShared = useI18n("widget.wazuh");const locale = useCurrentIntlLocale();const integrationId = integrationIds[0] ?? "";@@ -47,8 +47,8 @@ export default function WazuhFimWidget({ integrationIds, options, width, height{integrationId,range: options.range,- event: options.event,- limit: options.limit,+ event: options.fimEvent,+ limit: options.fimLimit,includeRegistry: options.includeRegistry,},{ staleTime: 60_000, refetchInterval: 60_000 },diff --git a/packages/widgets/src/wazuh-summary/component.tsx b/packages/widgets/src/wazuh/views/overview.tsxsimilarity index 93%rename from packages/widgets/src/wazuh-summary/component.tsxrename to packages/widgets/src/wazuh/views/overview.tsxindex 834b8005b..29674070f 100644--- a/packages/widgets/src/wazuh-summary/component.tsx+++ b/packages/widgets/src/wazuh/views/overview.tsx@@ -8,20 +8,20 @@ import { IconArrowDownRight, IconArrowUpRight, IconMinus, IconShieldHalfFilled }import { clientApi } from "@homarr/api/client";import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";-import { WidgetEmptyState } from "../common/empty-state";-import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../common/query-state";-import type { WidgetComponentProps } from "../definition";-import { WazuhErrorState } from "../wazuh/_shared/error-state";-import { WazuhPendingState, WazuhWidgetFrame } from "../wazuh/_shared/frame";+import { WidgetEmptyState } from "../../common/empty-state";+import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../../common/query-state";+import type { WazuhViewProps } from "../view-props";+import { WazuhErrorState } from "../_shared/error-state";+import { WazuhPendingState, WazuhWidgetFrame } from "../_shared/frame";import {formatWazuhCount,formatWazuhTrend,getWazuhTrend,wazuhSeverities,wazuhSeverityChartColors,-} from "../wazuh/_shared/severity";-import { useWazuhLinks } from "../wazuh/_shared/use-wazuh-links";-import classes from "../wazuh/_shared/wazuh.module.css";+} from "../_shared/severity";+import { useWazuhLinks } from "../_shared/use-wazuh-links";+import classes from "../_shared/wazuh.module.css";const healthColors = { green: "green", yellow: "yellow", red: "red" } as const;@@ -34,7 +34,7 @@ const TrendIndicator = ({previous: number;size?: "xs" | "sm";}) => {- const t = useI18n("widget.wazuhSummary");+ const t = useI18n("widget.wazuh.summary");const locale = useCurrentIntlLocale();if (current === 0 && previous === 0) {// Nothing now and nothing before: a percentage would only be noise.@@ -67,13 +67,8 @@ const TrendIndicator = ({);};-export default function WazuhSummaryWidget({- integrationIds,- options,- width,- height,-}: WidgetComponentProps<"wazuhSummary">) {- const t = useI18n("widget.wazuhSummary");+export function WazuhOverviewView({ integrationIds, options, width, height }: WazuhViewProps) {+ const t = useI18n("widget.wazuh.summary");const tShared = useI18n("widget.wazuh");const locale = useCurrentIntlLocale();const integrationId = integrationIds[0] ?? "";diff --git a/packages/widgets/src/wazuh-timeline/component.tsx b/packages/widgets/src/wazuh/views/timeline.tsxsimilarity index 91%rename from packages/widgets/src/wazuh-timeline/component.tsxrename to packages/widgets/src/wazuh/views/timeline.tsxindex fa0706236..01b3cade3 100644--- a/packages/widgets/src/wazuh-timeline/component.tsx+++ b/packages/widgets/src/wazuh/views/timeline.tsx@@ -8,13 +8,13 @@ import { IconChartAreaLine } from "@tabler/icons-react";import { clientApi } from "@homarr/api/client";import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";-import { WidgetEmptyState } from "../common/empty-state";-import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../common/query-state";-import type { WidgetComponentProps } from "../definition";-import { WazuhErrorState } from "../wazuh/_shared/error-state";-import { WazuhLegendChip, WazuhPendingState, WazuhWidgetFrame } from "../wazuh/_shared/frame";-import { formatWazuhCount, wazuhSeverityChartColors } from "../wazuh/_shared/severity";-import { useWazuhLinks } from "../wazuh/_shared/use-wazuh-links";+import { WidgetEmptyState } from "../../common/empty-state";+import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../../common/query-state";+import type { WazuhViewProps } from "../view-props";+import { WazuhErrorState } from "../_shared/error-state";+import { WazuhLegendChip, WazuhPendingState, WazuhWidgetFrame } from "../_shared/frame";+import { formatWazuhCount, wazuhSeverityChartColors } from "../_shared/severity";+import { useWazuhLinks } from "../_shared/use-wazuh-links";const rangeToRefetchMs = { "1h": 60_000, "24h": 60_000, "7d": 5 * 60_000, "30d": 5 * 60_000 } as const;const formatInterval = (intervalMs: number, locale: string) => {@@ -44,13 +44,8 @@ const formatTick = (timestamp: number, range: "1h" | "24h" | "7d" | "30d", local: date.toLocaleDateString(locale, { day: "numeric", month: "short" });};-export default function WazuhTimelineWidget({- integrationIds,- options,- width,- height,-}: WidgetComponentProps<"wazuhTimeline">) {- const t = useI18n("widget.wazuhTimeline");+export function WazuhTimelineView({ integrationIds, options, width, height }: WazuhViewProps) {+ const t = useI18n("widget.wazuh.timeline");const tShared = useI18n("widget.wazuh");const locale = useCurrentIntlLocale();const integrationId = integrationIds[0] ?? "";diff --git a/packages/widgets/src/wazuh-top-list/component.tsx b/packages/widgets/src/wazuh/views/top.tsxsimilarity index 78%rename from packages/widgets/src/wazuh-top-list/component.tsxrename to packages/widgets/src/wazuh/views/top.tsxindex 518c83bcb..cffc9d0aa 100644--- a/packages/widgets/src/wazuh-top-list/component.tsx+++ b/packages/widgets/src/wazuh/views/top.tsx@@ -8,16 +8,16 @@ import type { WazuhTopListEntry, WazuhTopListKind } from "@homarr/integrations/timport { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";import type { TablerIcon } from "@homarr/ui";-import { WidgetEmptyState } from "../common/empty-state";-import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../common/query-state";-import type { WidgetComponentProps } from "../definition";-import { isPrivateIp, WazuhChip, WazuhLevelBadge } from "../wazuh/_shared/badges";-import { WazuhErrorState } from "../wazuh/_shared/error-state";-import { WazuhPendingState, WazuhWidgetFrame } from "../wazuh/_shared/frame";-import type { WazuhDashboardLinks } from "../wazuh/_shared/links";-import { formatWazuhCount, getWazuhSeverityForLevel, wazuhSeverityChartColors } from "../wazuh/_shared/severity";-import { useWazuhLinks } from "../wazuh/_shared/use-wazuh-links";-import classes from "../wazuh/_shared/wazuh.module.css";+import { WidgetEmptyState } from "../../common/empty-state";+import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../../common/query-state";+import type { WazuhViewProps } from "../view-props";+import { isPrivateIp, WazuhChip, WazuhLevelBadge } from "../_shared/badges";+import { WazuhErrorState } from "../_shared/error-state";+import { WazuhPendingState, WazuhWidgetFrame } from "../_shared/frame";+import type { WazuhDashboardLinks } from "../_shared/links";+import { formatWazuhCount, getWazuhSeverityForLevel, wazuhSeverityChartColors } from "../_shared/severity";+import { useWazuhLinks } from "../_shared/use-wazuh-links";+import classes from "../_shared/wazuh.module.css";const kindIcons: Record<WazuhTopListKind, TablerIcon> = {rules: IconListNumbers,@@ -54,29 +54,24 @@ const getEntryHref = (}};-export default function WazuhTopListWidget({- integrationIds,- options,- width,- height,-}: WidgetComponentProps<"wazuhTopList">) {- const t = useI18n("widget.wazuhTopList");+export function WazuhTopView({ integrationIds, options, width, height }: WazuhViewProps) {+ const t = useI18n("widget.wazuh.top");const tShared = useI18n("widget.wazuh");const locale = useCurrentIntlLocale();const integrationId = integrationIds[0] ?? "";const query = clientApi.widget.wazuh.getTopList.useQuery(- { integrationId, kind: options.kind, range: options.range, limit: options.limit, minLevel: options.minLevel },+ { integrationId, kind: options.topKind, range: options.range, limit: options.topLimit, minLevel: options.minLevel },{ staleTime: 60_000, refetchInterval: 2 * 60_000 },);const result = getUsableWidgetQueryData(query);const links = useWazuhLinks(result?.dashboardUrl);const compact = height < 170 || width < 240;- const title = t(`title.${options.kind}`, { range: tShared(`range.${options.range}`) });- const Icon = kindIcons[options.kind];+ const title = t(`title.${options.topKind}`, { range: tShared(`range.${options.range}`) });+ const Icon = kindIcons[options.topKind];if (isInitialWidgetQueryPending(query)) {return (- <WazuhWidgetFrame icon={Icon} title={title} compact={compact} iconColor={kindColors[options.kind]}>+ <WazuhWidgetFrame icon={Icon} title={title} compact={compact} iconColor={kindColors[options.topKind]}><WazuhPendingState /></WazuhWidgetFrame>);@@ -87,13 +82,13 @@ export default function WazuhTopListWidget({const list = result.data;const max = Math.max(1, ...list.entries.map((entry) => entry.count));const headerHref =- options.kind === "mitreTactics" || options.kind === "mitreTechniques"+ options.topKind === "mitreTactics" || options.topKind === "mitreTechniques"? links?.mitre- : options.kind === "agents"+ : options.topKind === "agents"? links?.agents: links?.events({ from: `now-${options.range}` });const showDetailColumn = width >= 300;- const showAgentsColumn = width >= 380 && options.kind !== "agents";+ const showAgentsColumn = width >= 380 && options.topKind !== "agents";return (<WazuhWidgetFrame@@ -101,7 +96,7 @@ export default function WazuhTopListWidget({title={title}href={headerHref}compact={compact}- iconColor={kindColors[options.kind]}+ iconColor={kindColors[options.topKind]}headerRight={<Tooltip label={t("totalTooltip", { count: list.total.toLocaleString(locale) })} withArrow><Badge size="sm" variant="light" color="gray" radius="sm">@@ -113,17 +108,17 @@ export default function WazuhTopListWidget({{list.entries.length === 0 ? (<Center h="100%"><Text size="sm" c="dimmed" ta="center">- {t(`empty.${options.kind}`)}+ {t(`empty.${options.topKind}`)}</Text></Center>) : (<ScrollArea h="100%" type="auto" scrollbarSize={6} offsetScrollbars="y"><Stack gap={1}>{list.entries.map((entry, index) => {- const href = getEntryHref(options.kind, entry, links, options.range);+ const href = getEntryHref(options.topKind, entry, links, options.range);const severity = entry.maxLevel !== null ? getWazuhSeverityForLevel(entry.maxLevel) : "low";const share = entry.count / max;- const isIp = options.kind === "sourceIps";+ const isIp = options.topKind === "sourceIps";return (<Boxkey={entry.key}@@ -136,7 +131,9 @@ export default function WazuhTopListWidget({<Text size="xs" c="dimmed" w={14} ta="right" className={classes.numeric}>{index + 1}</Text>- {options.kind === "rules" && entry.maxLevel !== null && <WazuhLevelBadge level={entry.maxLevel} />}+ {options.topKind === "rules" && entry.maxLevel !== null && (+ <WazuhLevelBadge level={entry.maxLevel} />+ )}<Textsize="xs"fw={500}@@ -152,9 +149,9 @@ export default function WazuhTopListWidget({{isPrivateIp(entry.key) ? t("private") : t("public")}</WazuhChip>)}- {showDetailColumn && entry.detail && options.kind !== "agents" && (+ {showDetailColumn && entry.detail && options.topKind !== "agents" && (<Text size="xs" c="dimmed" className={`${classes.mono} ${classes.nowrap}`}>- {options.kind === "rules" ? `#${entry.detail}` : entry.detail}+ {options.topKind === "rules" ? `#${entry.detail}` : entry.detail}</Text>)}{showAgentsColumn && entry.agents !== null && (@@ -177,7 +174,7 @@ export default function WazuhTopListWidget({style={{width: `${Math.max(share * 100, 1)}%`,background:- options.kind === "mitreTactics" || options.kind === "mitreTechniques"+ options.topKind === "mitreTactics" || options.topKind === "mitreTechniques"? "var(--mantine-color-violet-5)": `var(--mantine-color-${wazuhSeverityChartColors[severity].replace(".", "-")})`,}}diff --git a/packages/widgets/src/wazuh-vulnerabilities/component.tsx b/packages/widgets/src/wazuh/views/vulnerabilities.tsxsimilarity index 92%rename from packages/widgets/src/wazuh-vulnerabilities/component.tsxrename to packages/widgets/src/wazuh/views/vulnerabilities.tsxindex 8f2ef8d02..99b40891e 100644--- a/packages/widgets/src/wazuh-vulnerabilities/component.tsx+++ b/packages/widgets/src/wazuh/views/vulnerabilities.tsx@@ -7,15 +7,15 @@ import { clientApi } from "@homarr/api/client";import type { WazuhVulnerabilityOverview } from "@homarr/integrations/types";import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";-import { WidgetEmptyState } from "../common/empty-state";-import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../common/query-state";-import type { WidgetComponentProps } from "../definition";-import { WazuhErrorState } from "../wazuh/_shared/error-state";-import { WazuhPendingState, WazuhStatTile, WazuhWidgetFrame } from "../wazuh/_shared/frame";-import type { WazuhDashboardLinks } from "../wazuh/_shared/links";-import { formatWazuhCount, getVulnerabilitySeverityColor } from "../wazuh/_shared/severity";-import { useWazuhLinks } from "../wazuh/_shared/use-wazuh-links";-import classes from "../wazuh/_shared/wazuh.module.css";+import { WidgetEmptyState } from "../../common/empty-state";+import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../../common/query-state";+import type { WazuhViewProps } from "../view-props";+import { WazuhErrorState } from "../_shared/error-state";+import { WazuhPendingState, WazuhStatTile, WazuhWidgetFrame } from "../_shared/frame";+import type { WazuhDashboardLinks } from "../_shared/links";+import { formatWazuhCount, getVulnerabilitySeverityColor } from "../_shared/severity";+import { useWazuhLinks } from "../_shared/use-wazuh-links";+import classes from "../_shared/wazuh.module.css";const severityKeys = ["critical", "high", "medium", "low"] as const;const severityColors = { critical: "red", high: "orange", medium: "yellow", low: "blue" } as const;@@ -32,7 +32,7 @@ const CveList = ({links: WazuhDashboardLinks | null;width: number;}) => {- const t = useI18n("widget.wazuhVulnerabilities");+ const t = useI18n("widget.wazuh.vulnerabilities");const showPackages = width >= 300;return (<Stack gap={1}>@@ -99,7 +99,7 @@ const AgentList = ({links: WazuhDashboardLinks | null;locale: string;}) => {- const t = useI18n("widget.wazuhVulnerabilities");+ const t = useI18n("widget.wazuh.vulnerabilities");const max = Math.max(1, ...data.topAgents.map((agent) => agent.total));return (<Stack gap={1}>@@ -152,13 +152,8 @@ const AgentList = ({);};-export default function WazuhVulnerabilitiesWidget({- integrationIds,- options,- width,- height,-}: WidgetComponentProps<"wazuhVulnerabilities">) {- const t = useI18n("widget.wazuhVulnerabilities");+export function WazuhVulnerabilitiesView({ integrationIds, options, width, height }: WazuhViewProps) {+ const t = useI18n("widget.wazuh.vulnerabilities");const tShared = useI18n("widget.wazuh");const locale = useCurrentIntlLocale();const integrationId = integrationIds[0] ?? "";