Compare commits

..
Author SHA1 Message Date
Thomas Camlong def3ef8e15 fix: prevent icon selection on mobile when editing dashboard
Add user-select: none and -webkit-touch-callout: none to app icon
to prevent the browser from selecting the image when long-pressing,
which interferes with drag-to-move in edit mode on mobile devices.

Closes #2970
2026-06-14 17:20:46 +02:00
Thomas Camlong 2e709b102f feat(overlay): add integration avatars back to WidgetHoverOverlay 2026-06-14 17:18:44 +02:00
Thomas Camlong 875310f4d9 refactor(overlay): simplify WidgetHoverOverlay to bare minimum 2026-06-14 17:18:04 +02:00
Thomas Camlong 82064b2874 refactor(overlay): strip WidgetHoverOverlay to name-only 2026-06-14 17:17:31 +02:00
Thomas Camlong f1bed389e3 fix(overlay): make WidgetHoverOverlay purely visual with pointer-events none 2026-06-14 17:16:18 +02:00
ajnart b6c817123f style: auto-fix lint and format 2026-06-14 15:07:23 +00:00
Thomas 062ab1ad34 Merge branch 'dev' into feat/various-fixes 2026-06-14 17:06:10 +02:00
Thomas Camlong b7b7105f2d fix(overlay): show WidgetHoverOverlay only during edit mode 2026-06-14 17:05:40 +02:00
Thomas Camlong f0e20eb3da fix(beszel): correct unit scaling for system stats and container charts
Beszel API returns pre-scaled values, not raw bytes as the types claimed:
- Storage (du/mu/mb): GB — remove /BYTES_TO_GB division
- Disk I/O (dr/dw): MB/s — multiply by 1024² for formatters
- Container memory (m): MB — multiply by 1024² for formatters
- Container network (b/ns/nr): bytes/s — passthrough, unchanged

Also fix Recharts width(-1)/height(-1) warnings by adding w=100%
and minHeight:0 to BeszelAreaChart.
2026-06-14 17:05:34 +02:00
197 changed files with 4790 additions and 9491 deletions

No files matched your search

-4
View File
@@ -33,10 +33,6 @@ body:
options:
# The below comment is used to insert a new version with on-release.yml
#NEXT_VERSION#
- 1.67.0
- 1.66.1
- 1.66.0
- 1.65.0
- 1.64.0
- 1.62.0
- 1.61.0
@@ -66,7 +66,7 @@ jobs:
- uses: actions/setup-node@v6
if: env.SKIP_RELEASE == 'false'
with:
node-version: 24.17.0
node-version: 24.16.0
package-manager-cache: false
- run: npm i -g pnpm
if: env.SKIP_RELEASE == 'false'
@@ -3,7 +3,6 @@ name: "[Deployment] Automatic Weekly Release"
on:
schedule:
- cron: "0 19 * * 5" # https://crontab.guru/#0_19_*_*_5
timezone: Europe/Zurich
workflow_dispatch:
inputs:
send-notifications:
+1 -1
View File
@@ -1,2 +1,2 @@
[tools]
node = "24.17.0"
node = "24.16.0"
+1 -1
View File
@@ -1 +1 @@
24.17.0
24.16.0
+1 -1
View File
@@ -1,5 +1,5 @@
{
"js/ts.tsdk.path": "node_modules\\typescript\\lib",
"typescript.tsdk": "node_modules\\typescript\\lib",
"js/ts.implicitProjectConfig.experimentalDecorators": true,
"cSpell.words": [
"ajnart",
-13
View File
@@ -1,16 +1,3 @@
## [1.67.0](https://github.com/homarr-labs/homarr/compare/v1.66.1...v1.67.0) (2026-06-19)
### Features
* **analytics:** migrate from Umami to PostHog server-side analytics ([#5983](https://github.com/homarr-labs/homarr/issues/5983)) ([d059023](https://github.com/homarr-labs/homarr/commit/d059023b51a323df027c1cf033454440bd0d7e57))
* Calculate and display total CPU and memory usage ([#5911](https://github.com/homarr-labs/homarr/issues/5911)) ([d9cbd54](https://github.com/homarr-labs/homarr/commit/d9cbd5427d0e5be3e5dbecca8d6069dc8074d810))
### Bug Fixes
* **auth:** isolate session cookies from other Auth.js apps on same host ([#5996](https://github.com/homarr-labs/homarr/issues/5996)) ([e1a245f](https://github.com/homarr-labs/homarr/commit/e1a245ff2d8520d08957c4a7dbe01d039607a973))
* **deps:** update tailwindcss monorepo to ^4.3.1 ([#5988](https://github.com/homarr-labs/homarr/issues/5988)) ([78b6e52](https://github.com/homarr-labs/homarr/commit/78b6e520ac095129398d3da8f2441df408e93e9f))
* **downloads:** sort stalled torrents last when sorting by finish time ([#6011](https://github.com/homarr-labs/homarr/issues/6011)) ([c56d9d6](https://github.com/homarr-labs/homarr/commit/c56d9d6894c717b5c70ab75d6a100d4d1071c2d3)), closes [#5416](https://github.com/homarr-labs/homarr/issues/5416)
## [1.65.0](https://github.com/homarr-labs/homarr/compare/v1.64.0...v1.65.0) (2026-06-12)
### Features
-5
View File
@@ -1,11 +1,6 @@
# ── CODEOWNERS ───────────────────────────────────────
* @homarr-labs/maintainers
# Specific features / integrations
# Glueten
apps/docs/docs/integrations/glueten @Lok3sh-kumar
packages/integrations/src/gluetun @Lok3sh-kumar
# Exempt Renovate‑managed files (no owners)
package.json
**/package.json
+1 -15
View File
@@ -1,4 +1,4 @@
FROM node:24.17.0-alpine AS base
FROM node:24.16.0-alpine AS base
FROM base AS builder
RUN apk add --no-cache libc6-compat
@@ -20,17 +20,6 @@ ARG DISABLE_REDIS_LOGS='true'
RUN corepack enable pnpm && pnpm build
# The standalone output tracing omits server chunk source maps (.next/server/**/*.map), which is
# where production Node stack frames point. Copy the .map files into the standalone tree (preserving
# directory structure) so the existing standalone COPY ships them, keeping traces readable.
# See https://github.com/homarr-labs/homarr/issues/5891
RUN cd apps/nextjs/.next/server && \
find . -name '*.map' | while IFS= read -r map; do \
dest="../standalone/apps/nextjs/.next/server/$map"; \
mkdir -p "$(dirname "$dest")"; \
cp "$map" "$dest"; \
done
FROM base AS runner
WORKDIR /app
@@ -75,9 +64,6 @@ ENV DB_DRIVER='better-sqlite3'
ENV AUTH_PROVIDERS='credentials'
ENV REDIS_IS_EXTERNAL='false'
ENV NODE_ENV='production'
# Tell Node to symbolicate stack traces using the shipped .map files so production logs
# show original source locations instead of minified frames, see https://github.com/homarr-labs/homarr/issues/5891
ENV NODE_OPTIONS='--enable-source-maps'
ENTRYPOINT [ "/app/entrypoint.sh" ]
CMD ["sh", "run.sh"]
@@ -23,7 +23,6 @@ Homarr supports multiple authentication options, from internal userbase (credent
| AUTH_PROVIDERS | Select Which provider to use between *credentials*, *ldap* and *oidc*. <br /> Multiple providers can be enabled with by separating them with `,`, (ex. `AUTH_PROVIDERS=credentials,oidc`, it is highly recommended to just enable one provider). | credentials |
| AUTH_LOGOUT_REDIRECT_URL | URL to redirect to after clicking logging out. | --- |
| AUTH_SESSION_EXPIRY_TIME | Time for the session to time out. Can be set as pure number, which will automatically be used in seconds, or followed by s, m, h or d for seconds, minutes, hours or days. (ex: "30m") | "30d" |
| AUTH_COOKIE_PREFIX | Prefix used for all authentication cookies (session, csrf, callback, pkce, state, nonce). Change this if you run another Auth.js/NextAuth app on the same hostname as Homarr (browsers scope cookies by host, not by port) to avoid cookie name collisions. Only letters, numbers, hyphens and underscores are allowed. | `homarr` |
<Tabs>
<TabItem value="credentials" label="Credentials Provider" default>
@@ -125,8 +124,6 @@ Homarr supports multiple authentication options, from internal userbase (credent
Roles are fetched from group claims. This can also be changed to roles for example added to a azure app registration by using the `AUTH_OIDC_GROUPS_ATTRIBUTE`.
If you'd rather manage group memberships for OIDC users locally (instead of via the IdP), set `AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT=true`. While enabled, Homarr stops syncing OIDC users' group memberships from the groups claim, and admins can add/remove OIDC users on a group's members page. If you turn this back to `false`, the next login of each user resumes the regular sync and reconciles their groups with the IdP's claim again, which may remove memberships that were added manually while local management was enabled.
<details>
<summary>
Example Setup
@@ -200,7 +197,6 @@ Homarr supports multiple authentication options, from internal userbase (credent
| ``AUTH_OIDC_AUTO_LOGIN`` | Automatically redirect to OIDC login | false |
| ``AUTH_OIDC_SCOPE_OVERWRITE`` | Overwrite default scopes (openid, profile, email) | openid email profile groups |
| ``AUTH_OIDC_GROUPS_ATTRIBUTE`` | Attribute used for groups (roles) claim | groups |
| ``AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT`` | Stop syncing group memberships of OIDC users from the groups claim and manage them locally via the group members page instead | false |
| ``AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE`` | Overwrite name attribute. By default it will use preferred_username if it does not contain a `@` and otherwise name. | --- |
| ``AUTH_OIDC_FORCE_USERINFO`` | Force userinfo endpoint to be used for user information. | false |
| ``AUTH_OIDC_ENABLE_DANGEROUS_ACCOUNT_LINKING`` | Enable account linking for OIDC provider. This will link the OIDC accounts by email. Be sure that you have verified emails to prevent stealing accounts. | false |
@@ -395,7 +395,6 @@ All available values are listed on the [artifacthub](https://artifacthub.io/pack
| env.AUTH_LDAP_USERNAME_FILTER_EXTRA_ARG | string | `nil` | Extra arguments for user search filter (& based) |
| env.AUTH_LDAP_USER_MAIL_ATTRIBUTE | string | `"mail"` | Attribute used for mail field |
| env.AUTH_LOGOUT_REDIRECT_URL | string | `nil` | URL to redirect to after clicking logging out. |
| env.AUTH_COOKIE_PREFIX | string | `"homarr"` | Prefix used for all authentication cookies. Change if you run another Auth.js/NextAuth app on the same hostname to avoid cookie name collisions. Only letters, numbers, hyphens and underscores. |
| env.AUTH_OIDC_AUTO_LOGIN | string | `"false"` | Automatically redirect to OIDC login |
| env.AUTH_OIDC_CLIENT_NAME | string | `"OIDC"` | Display name of provider (in login screen) |
| env.AUTH_OIDC_GROUPS_ATTRIBUTE | string | `"groups"` | Attribute used for groups (roles) claim |
@@ -1,52 +0,0 @@
---
title: 'Gluetun'
description: 'Connect Gluetun to Homarr as a VPN integration.'
hide_title: true
---
import { IntegrationHeader } from '@site/src/components/integrations/header';
import { IntegrationCapabilites } from '@site/src/components/integrations/widgets';
import { AddingIntegration } from '@site/src/components/integrations/adding';
import { IntegrationSecrets } from '@site/src/components/integrations/secrets';
import { gluetunIntegration } from '.';
import { vpnWidget } from '@site/docs/widgets/vpn';
<IntegrationHeader
integration={gluetunIntegration}
categories={['VPN', 'Network']}
/>
[Gluetun](https://github.com/qdm12/gluetun) exposes a control server that Homarr can query to report the VPN tunnel
status, DNS status, public IP address, and active provider details in the VPN widget.
### Widgets & Capabilities
<IntegrationCapabilites
items={[{
widget: vpnWidget,
}]}
/>
### Setting up the Gluetun control server
Refer to the [Gluetun control server documentation](https://github.com/qdm12/gluetun-wiki/blob/main/setup/advanced/control-server.md#authentication) to enable and configure authentication.
### Adding the integration
<AddingIntegration />
### Secrets
Gluetun's control server can be left unprotected or secured with either an API key or HTTP Basic authentication.
Choose the option that matches how your Gluetun instance integration is set up.
<IntegrationSecrets secrets={[{
credentials: [],
steps: [],
},{
credentials: ['username', 'password'],
steps: [],
},{
credentials: ['apiKey'],
steps: [],
},,]} />
@@ -1,8 +0,0 @@
import { IntegrationDefinition } from "@site/src/types";
export const gluetunIntegration: IntegrationDefinition = {
name: "Gluetun",
description: "VPN control server integration for Homarr's VPN widget.",
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/svg/gluetun.svg",
path: "../../integrations/gluetun",
};
@@ -1,33 +0,0 @@
---
title: 'Gotify'
description: "Gotify is a simple, self-hosted server for sending and receiving messages in real time."
hide_title: true
---
import { notificationsWidget } from '@site/docs/widgets/notifications';
import { AddingIntegration } from '@site/src/components/integrations/adding';
import { IntegrationHeader } from '@site/src/components/integrations/header';
import { IntegrationSecrets } from '@site/src/components/integrations/secrets';
import { IntegrationCapabilites } from '@site/src/components/integrations/widgets';
import { gotifyIntegration } from '.';
<IntegrationHeader
integration={gotifyIntegration}
categories={['Notifications', 'Messaging']}
/>
### Widgets & Capabilities
<IntegrationCapabilites
items={[{
widget: notificationsWidget
}]}
/>
### Adding the integration
<AddingIntegration />
### Secrets
<IntegrationSecrets secrets={[{
credentials: ['username', 'password'],
steps: []
}]} />
@@ -1,8 +0,0 @@
import { IntegrationDefinition } from "@site/src/types";
export const gotifyIntegration: IntegrationDefinition = {
name: "Gotify",
description: "Gotify is a simple, self-hosted server for sending and receiving messages in real time.",
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/svg/gotify.svg",
path: "../../integrations/gotify",
};
-2
View File
@@ -130,7 +130,6 @@ Homarr exposes 50+ tools organized by namespace. Each tool is either a **query**
| ------------------ | -------------------------------------------------------- | ---------- |
| `app` | List all apps, get app by ID, create/update/delete app | GET + POST |
| `apiKeys` | List API keys | GET |
| `beszel` | Systems status, alerts, historical system metrics | GET |
| `board` | List boards, get board by ID, create/update/delete board | GET + POST |
| `docker` | List containers, inspect container, start/stop/restart | GET + POST |
| `icon` | Search icons | GET |
@@ -163,4 +162,3 @@ The tools table on the MCP tab is dynamically generated - it always reflects the
- **"Create a new app pointing to my Grafana instance"** - AI creates an app with the correct icon and URL
- **"How many users are on my Homarr instance?"** - AI lists all users (admin only)
- **"Toggle Pi-hole blocking for 5 minutes"** - AI interacts with DNS controls
- **"How are my servers doing?"** - AI fetches Beszel system stats including CPU, memory, disk, and alerts
@@ -0,0 +1,5 @@
{
"label": "Tools",
"collapsed": true,
"position": 10
}
@@ -0,0 +1,66 @@
---
title: SQLite Backup & Restore
tags:
- Management
- Backup
- Restore
- SQLite
---
The SQLite Backup & Restore feature allows you to export and import your entire Homarr database as a portable ZIP file. This is useful for creating backups, migrating between instances, or recovering from failures.
:::info SQLite only
This feature is only available when using the SQLite database driver (`DB_DRIVER=better-sqlite3`). MySQL and PostgreSQL users should use their respective database backup tools.
:::
## Accessing Backup & Restore
Navigate to **Management → Tools → Backup** from the sidebar. This page is only visible when running with SQLite.
## Exporting a Backup
Click the **Export** button to download a ZIP archive containing:
- **`db.sqlite`** — A consistent snapshot of your database (created via `VACUUM INTO`)
- **`metadata.json`** — Contains:
- `homarrVersion` — The version of Homarr that created the backup
- `exportedAt` — Timestamp of the export
- `dbDialect` — The database dialect (`sqlite`)
- `encryptionKey` — Your `SECRET_ENCRYPTION_KEY` (needed to decrypt integration secrets)
:::caution
The exported ZIP contains your encryption key and database. Store it securely and do not share it publicly.
:::
A confirmation dialog will ask you to type **"I understand"** before the export proceeds.
## Importing a Backup
1. Click the **Import** button and upload a previously exported ZIP file
2. Homarr analyzes the backup **entirely in your browser** using WebAssembly (sql.js) — no data is sent to the server during preview
3. The preview shows:
- **Entity counts** — How many boards, apps, users, integrations, etc. are in the backup
- **Board names** — A list of all boards contained in the backup
- **Migration status** — If the backup is from an older version, Homarr shows each pending database migration as animated timeline steps
4. Review the preview and type **"I understand"** to confirm
5. Homarr applies any pending migrations, re-encrypts integration secrets if the `SECRET_ENCRYPTION_KEY` differs between instances, and replaces the live database
6. The server automatically restarts to pick up the new database
:::tip
The import process is **backward-compatible** with older backups that used a separate `encryption-key.txt` file instead of embedding the key in `metadata.json`.
:::
## Onboarding Integration
When setting up a fresh Homarr instance with SQLite, the onboarding wizard includes a **"Restore from SQLite backup"** option. This lets you upload a backup ZIP to bootstrap your new instance with data from a previous installation.
## Docker Restart Behavior
After a successful import, only the Next.js process restarts — nginx and Redis remain running. The `run.sh` script automatically restarts Next.js in a loop, so the application comes back online within seconds. Running `docker stop` still works gracefully.
## Best Practices
- **Back up regularly** — Create exports before major updates or configuration changes
- **Test restores** — Periodically verify your backups by importing them on a test instance
- **Secure storage** — Keep backups in an encrypted or access-controlled location since they contain your encryption key
- **Check versions** — Backups from newer versions cannot be imported into older Homarr instances; always import into the same or newer version
@@ -8,19 +8,12 @@ export const beszelSystemStatsWidget: WidgetDefinition = {
path: "../../widgets/beszel-system-stats",
configuration: {
items: [
{
name: "System",
description: "The Beszel system to display stats for. Searchable select populated from the integration.",
values: { type: "string" },
defaultValue: "First available system",
},
{
name: "Time period",
description:
"The time range for chart data. '1 Minute' enables live streaming via PocketBase SSE (requires Beszel agent >= 0.13.0)",
description: "The time range for chart data",
values: {
type: "select",
options: ["1 Minute", "1 Hour", "12 Hours", "24 Hours", "1 Week", "30 Days"],
options: ["1 Hour", "12 Hours", "24 Hours", "1 Week", "30 Days"],
},
defaultValue: "1 Hour",
},
@@ -1,17 +1,16 @@
import { WidgetDefinition } from "@site/src/types";
import { IconDeviceGamepad } from "@tabler/icons-react";
import { integrations } from "../dns-hole-summary";
export const dnsHoleControlsWidget: WidgetDefinition = {
icon: IconDeviceGamepad,
name: "DNS Hole Controls",
description: `Control the blocking feature of your ${integrations} from your dashboard`,
description: "Control PiHole or AdGuard from your dashboard",
path: "../../widgets/dns-hole-controls",
configuration: {
items: [
{
name: "Show Toggle All Buttons",
description: "Show or not the 2 buttons that may be redundant when having only one DNS Hole.",
description: "Show or not the 2 buttons that may be redundant when having only one DNS-hole.",
values: { type: "boolean" },
defaultValue: "yes",
},
@@ -1,12 +1,10 @@
import { WidgetDefinition } from "@site/src/types";
import { IconAd } from "@tabler/icons-react";
export const integrations = "Pi-hole, AdGuard Home or Technitium DNS";
export const dnsHoleSummaryWidget: WidgetDefinition = {
icon: IconAd,
name: "DNS Hole Summary",
description: `Displays the summary of your ${integrations} blocks and queries statistics`,
description: "Displays the summary of your DNS Hole",
path: "../../widgets/dns-hole-summary",
configuration: {
items: [
@@ -21,7 +19,7 @@ export const dnsHoleSummaryWidget: WidgetDefinition = {
},
{
name: "Use Pi-Hole colors",
description: `Color the tiles using the background color, that is used by default in ${integrations}.`,
description: "Color the tiles using the background color, that is used by default in PiHole.",
values: { type: "boolean" },
defaultValue: "yes",
},
@@ -13,8 +13,7 @@ import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
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 { nextcloudIntegration } from '@site/docs/integrations/nextcloud'
<WidgetHeader
widget={notificationsWidget}
@@ -34,8 +33,7 @@ import notificationsScreenshot from './img/notifications.png';
<WidgetIntegrations
items={[
{ integration: ntfyIntegration },
{ integration: nextcloudIntegration },
{ integration: gotifyIntegration }
{ integration: nextcloudIntegration }
]}
/>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

-40
View File
@@ -1,40 +0,0 @@
---
title: 'VPN'
description: 'Monitor the status of your VPN integrations.'
hide_title: true
---
import { WidgetHeader } from '@site/src/components/widgets/header';
import { AddingWidget } from '@site/src/components/widgets/adding';
import { WidgetIntegrations } from '@site/src/components/widgets/integrations';
import { vpnWidget } from '.';
import { gluetunIntegration } from '@site/docs/integrations/gluetun';
<WidgetHeader
widget={vpnWidget}
categories={['Network', 'Security']}
/>
The VPN widget provides a compact overview of each configured VPN integration. It shows whether the tunnel and DNS
services are up, the currently exposed public IP address, and the VPN provider and protocol being used.
When multiple VPN integrations are attached, the widget renders one card per integration so you can compare their
current status at a glance.
### Screenshots
import singleIntegrationImage from './img/single.png';
<div>
<img src={singleIntegrationImage} alt="VPN widget showing a single integration" width={128 * 3} />
</div>
### Supported Integrations
<WidgetIntegrations items={[{
integration: gluetunIntegration,
}]} />
### Adding the widget
<AddingWidget />
-9
View File
@@ -1,9 +0,0 @@
import { WidgetDefinition } from "@site/src/types";
import { IconShieldLock } from "@tabler/icons-react";
export const vpnWidget: WidgetDefinition = {
icon: IconShieldLock,
name: "VPN",
description: "Monitor the connection status, public IP, and provider details of your VPN integrations.",
path: "../../widgets/vpn",
};
+3 -3
View File
@@ -32,19 +32,19 @@
"@scalar/api-reference-react": "catalog:",
"@signalwire/docusaurus-plugin-llms-txt": "^1.2.2",
"@tabler/icons-react": "catalog:",
"@tailwindcss/postcss": "^4.3.1",
"@tailwindcss/postcss": "^4.3.0",
"clsx": "catalog:",
"dayjs": "catalog:",
"docusaurus-plugin-image-zoom": "^3.0.1",
"leader-line-new": "^1.1.9",
"postcss": "^8.5.15",
"postcss": "^8.5.10",
"posthog-docusaurus": "^2.0.5",
"prism-react-renderer": "^2.4.1",
"random-word-slugs": "^0.1.7",
"react": "catalog:",
"react-dom": "catalog:",
"swiper": "^12.2.0",
"tailwindcss": "^4.3.1"
"tailwindcss": "^4.3.0"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "^3.10.1",
-4
View File
@@ -31,8 +31,6 @@ const nextConfig: NextConfig = {
},
output: "standalone",
reactStrictMode: true,
// Ship browser source maps so production client stack traces are readable, see https://github.com/homarr-labs/homarr/issues/5891
productionBrowserSourceMaps: true,
// react compiler breaks mantine-react-table, so disabled for now
//reactCompiler: true,
/** We already do typechecking as separate tasks in CI */
@@ -43,8 +41,6 @@ const nextConfig: NextConfig = {
*/
serverExternalPackages: ["dockerode", "isomorphic-dompurify", "jsdom", "better-sqlite3"],
experimental: {
// Ship server source maps so production Node stack traces in logs reference original source, see https://github.com/homarr-labs/homarr/issues/5891
serverSourceMaps: true,
optimizePackageImports: ["@mantine/core", "@mantine/hooks", "@tabler/icons-react"],
turbopackFileSystemCacheForDev: true,
preloadEntriesOnStart: false,
-1
View File
@@ -89,7 +89,6 @@
"mcp-handler": "catalog:",
"next": "catalog:",
"postcss-preset-mantine": "catalog:",
"posthog-js": "catalog:",
"prismjs": "catalog:",
"react": "catalog:",
"react-dom": "catalog:",
+1 -1
View File
@@ -139,11 +139,11 @@ export default async function Layout(props: {
suppressHydrationWarning
>
<head>
<Analytics />
<SearchEngineOptimization />
<CrowdinLiveTranslation locale={locale} />
</head>
<body className={["font-sans", fontSans.variable].join(" ")}>
<Analytics enabled={serverSettings.analytics.enableGeneral} />
<StackedProvider>
<Notifications pauseResetOnHover="notification" />
<ServiceWorkerRegistration />
@@ -57,13 +57,13 @@ export const CustomWidgetList = ({ definitions }: CustomWidgetListProps) => {
{definitions.map((def) => (
<Table.Tr key={def.id} style={{ opacity: def.enabled ? undefined : 0.5 }}>
<Table.Td>
<Group gap="xs" wrap="nowrap">
<Group gap="xs">
{def.iconUrl ? (
<Avatar size={20} radius="sm" src={def.iconUrl} styles={{ image: { objectFit: "contain" } }} />
) : (
<IconApi size={16} />
)}
<Text size="sm" fw={500} lineClamp={1} c={def.enabled ? undefined : "dimmed"} style={{ minWidth: 0 }}>
<Text size="sm" fw={500} lineClamp={1} c={def.enabled ? undefined : "dimmed"}>
{def.name}
</Text>
</Group>
@@ -131,7 +131,6 @@ export const CertificateErrorDetails = ({ error, url }: CertificateErrorDetailsP
{(error.data.reason === "untrusted" && rootCertificate.isSelfSigned) ||
error.data.reason === "hostnameMismatch" ? (
<Button
type="button"
variant="default"
fullWidth
onClick={error.data.reason === "hostnameMismatch" ? handleTrustHostname : handleTrustSelfSigned}
@@ -141,7 +140,6 @@ export const CertificateErrorDetails = ({ error, url }: CertificateErrorDetailsP
) : null}
{error.data.reason === "untrusted" && !rootCertificate.isSelfSigned ? (
<Button
type="button"
variant="default"
fullWidth
onClick={() =>
@@ -17,10 +17,9 @@ interface AnalyticsSettingsProps {
export const AnalyticsSettings = ({ initialData }: AnalyticsSettingsProps) => {
const t = useScopedI18n("management.page.settings.section.analytics");
const { instanceId: _, ...formDefaults } = initialData;
const form = useForm({
initialValues: formDefaults,
onValuesChange: (updatedValues, _prev) => {
initialValues: initialData,
onValuesChange: (updatedValues, _) => {
if (!form.isValid()) {
return;
}
@@ -4,7 +4,6 @@ import { useCallback } from "react";
import { clientApi } from "@homarr/api/client";
import { revalidatePathActionAsync } from "@homarr/common/client";
import type { SupportedAuthProvider } from "@homarr/definitions";
import { useModalAction } from "@homarr/modals";
import { useScopedI18n } from "@homarr/translation/client";
@@ -14,10 +13,9 @@ import { MobileAffixButton } from "~/components/manage/mobile-affix-button";
interface AddGroupMemberProps {
groupId: string;
presentUserIds: string[];
allowedProviders: SupportedAuthProvider[];
}
export const AddGroupMember = ({ groupId, presentUserIds, allowedProviders }: AddGroupMemberProps) => {
export const AddGroupMember = ({ groupId, presentUserIds }: AddGroupMemberProps) => {
const tMembersAdd = useScopedI18n("group.action.addMember");
const { mutateAsync } = clientApi.group.addMember.useMutation();
const { openModal } = useModalAction(UserSelectModal);
@@ -34,13 +32,13 @@ export const AddGroupMember = ({ groupId, presentUserIds, allowedProviders }: Ad
await revalidatePathActionAsync(`/manage/users/groups/${groupId}}/members`);
},
presentUserIds,
allowedProviders,
excludeExternalProviders: true,
},
{
title: tMembersAdd("label"),
},
);
}, [openModal, presentUserIds, groupId, mutateAsync, tMembersAdd, allowedProviders]);
}, [openModal, presentUserIds, groupId, mutateAsync, tMembersAdd]);
return <MobileAffixButton onClick={handleAddMember}>{tMembersAdd("label")}</MobileAffixButton>;
};
@@ -4,12 +4,9 @@ import { IconExclamationCircle } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { api } from "@homarr/api/server";
import { env } from "@homarr/auth/env";
import { auth } from "@homarr/auth/next";
import {
getGroupMemberManagementType,
getLocallyManageableProviders,
isGroupMembershipManagedLocally,
} from "@homarr/auth/server";
import { isProviderEnabled } from "@homarr/auth/server";
import { everyoneGroup } from "@homarr/definitions";
import { getI18n, getScopedI18n } from "@homarr/translation/server";
import { Link, SearchInput, UserAvatar } from "@homarr/ui";
@@ -41,15 +38,16 @@ export default async function GroupsDetailPage(props: GroupsDetailPageProps) {
const group = await api.group.getById({ id: params.id });
const isReserved = group.name === everyoneGroup;
const searchTerm = searchParams.search?.trim().toLowerCase();
const filteredMembers = group.members.filter(
(member) => !searchTerm || member.name?.toLowerCase().includes(searchTerm),
);
const filteredMembers = searchParams.search
? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
group.members.filter((member) => member.name?.toLowerCase().includes(searchParams.search!.trim().toLowerCase()))
: group.members;
// "local" = every enabled provider managed locally, "external" = none, "mixed" = some.
const managementType = getGroupMemberManagementType();
const canManageMembers = managementType !== "external";
const allowedProviders = getLocallyManageableProviders();
const providerTypes = isProviderEnabled("credentials")
? env.AUTH_PROVIDERS.length > 1
? "mixed"
: "credentials"
: "external";
return (
<Stack>
@@ -58,21 +56,17 @@ export default async function GroupsDetailPage(props: GroupsDetailPageProps) {
{isReserved ? (
<ReservedGroupAlert />
) : (
managementType !== "local" && (
providerTypes !== "credentials" && (
<Alert variant="light" color="yellow" icon={<IconExclamationCircle size="1rem" stroke={1.5} />}>
{t(`group.memberNotice.${managementType}`)}
{t(`group.memberNotice.${providerTypes}`)}
</Alert>
)
)}
<Group justify="space-between">
<SearchInput placeholder={`${tMembers("search")}...`} defaultValue={searchParams.search} />
{canManageMembers && !isReserved && (
<AddGroupMember
groupId={group.id}
presentUserIds={group.members.map((member) => member.id)}
allowedProviders={allowedProviders}
/>
{isProviderEnabled("credentials") && !isReserved && (
<AddGroupMember groupId={group.id} presentUserIds={group.members.map((member) => member.id)} />
)}
</Group>
{filteredMembers.length === 0 && (
@@ -100,8 +94,6 @@ interface RowProps {
}
const Row = ({ member, groupId, disabled }: RowProps) => {
const canBeRemoved = isGroupMembershipManagedLocally(member.provider);
return (
<TableTr>
<TableTd>
@@ -112,7 +104,9 @@ const Row = ({ member, groupId, disabled }: RowProps) => {
</Anchor>
</Group>
</TableTd>
<TableTd w={100}>{canBeRemoved && !disabled && <RemoveGroupMember user={member} groupId={groupId} />}</TableTd>
<TableTd w={100}>
{member.provider === "credentials" && !disabled && <RemoveGroupMember user={member} groupId={groupId} />}
</TableTd>
</TableTr>
);
};
@@ -211,17 +211,7 @@ describe("SQLite backup", () => {
const decryptedAfter = decryptWithKey(updatedRow.value as `${string}.${string}`, newKey);
expect(decryptedAfter).toBe(plaintext);
// The old key must no longer recover the plaintext. With AES-256-CBC this
// usually fails PKCS7 padding validation (throws), but ~1/256 of the time the
// wrong key yields valid padding and returns garbage instead of throwing, so
// assert on the actual property (plaintext is unrecoverable) rather than throwing.
let decryptedWithOldKey: string | null = null;
try {
decryptedWithOldKey = decryptWithKey(updatedRow.value as `${string}.${string}`, oldKey);
} catch {
// Expected for most wrong keys: padding validation fails.
}
expect(decryptedWithOldKey).not.toBe(plaintext);
expect(() => decryptWithKey(updatedRow.value as `${string}.${string}`, oldKey)).toThrow();
sqlite.close();
});
@@ -148,8 +148,6 @@ If \`hasUseAccess\` is false, the API key owner lacks permission for that integr
**"Check server health"** → Use \`healthMonitoring_getSystemHealthStatus\` for NAS/server metrics or \`healthMonitoring_getClusterHealthStatus\` for Proxmox clusters.
**"Check Beszel systems"** → Call \`integration_all\` to get Beszel integrationIds, then use \`beszel_getSystems\` to list all monitored systems with CPU/memory/disk/network status. Use \`beszel_getAlerts\` for active alerts and history. Use \`beszel_getSystemStats\` for historical metrics of a specific system (requires systemId from \`beszel_getSystems\`).
**"Manage Docker containers"** → Use \`docker_getContainers\` to list containers with status/CPU/memory, then \`docker_startAll\`/\`docker_stopAll\`/\`docker_restartAll\` with container IDs.
**"Control smart home"** → Use \`smartHome_entityState\` to check a Home Assistant entity, \`smartHome_switchEntity\` to toggle it, or \`smartHome_executeAutomation\` to trigger an automation.
@@ -5,7 +5,6 @@ import { IconCheck } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import type { SupportedAuthProvider } from "@homarr/definitions";
import { useForm } from "@homarr/form";
import { createModal } from "@homarr/modals";
import { useI18n } from "@homarr/translation/client";
@@ -13,7 +12,7 @@ import { UserAvatar } from "@homarr/ui";
interface InnerProps {
presentUserIds: string[];
allowedProviders?: SupportedAuthProvider[];
excludeExternalProviders?: boolean;
onSelect: (props: { id: string; name: string; image: string; email: string | null }) => void | Promise<void>;
confirmLabel?: string;
}
@@ -25,7 +24,7 @@ interface UserSelectFormType {
export const UserSelectModal = createModal<InnerProps>(({ actions, innerProps }) => {
const t = useI18n();
const { data: users, isPending } = clientApi.user.selectable.useQuery({
providers: innerProps.allowedProviders,
excludeExternalProviders: innerProps.excludeExternalProviders,
});
const [loading, setLoading] = useState(false);
const form = useForm<UserSelectFormType>();
@@ -142,8 +142,7 @@ export const useBackupAnalysis = () => {
phase: "error",
});
throw new Error(
`Migration ${migration.tag} failed: ${migrationErr instanceof Error ? migrationErr.message : "Unknown error"}`,
{ cause: migrationErr },
`Migration ${migration.tag} failed: ${migrationErr instanceof Error ? migrationErr.message : "Unknown error"}`, { cause: migrationErr },
);
}
@@ -41,12 +41,7 @@ export const ItemSelectModal = createModal<void>(({ actions }) => {
name: t(`widget.${kind}.name`),
description: t(`widget.${kind}.description`),
}))
.sort((itemA, itemB) => {
if (itemA.kind === "app") return -1;
if (itemB.kind === "app") return 1;
return itemA.name.localeCompare(itemB.name);
}),
.sort((itemA, itemB) => itemA.name.localeCompare(itemB.name)),
[t],
);
@@ -46,12 +46,7 @@ export const WidgetHoverOverlay = ({ item, integrations }: WidgetHoverOverlayPro
<Avatar.Group spacing="xs" className={classes.integrations}>
{connectedIntegrations.map((integration) => (
<Tooltip key={integration.id} label={integration.name} withArrow position="top">
<Avatar
src={getIconUrl(integration.kind)}
size={18}
radius="sm"
className={classes.integrationAvatar}
/>
<Avatar src={getIconUrl(integration.kind)} size={18} radius="sm" className={classes.integrationAvatar} />
</Tooltip>
))}
</Avatar.Group>
@@ -57,7 +57,6 @@ export const categoryTranslationKeys: Record<string, string> = {
mediaMonitoring: "integration.category.mediaMonitoring",
speedtest: "integration.category.speedtest",
analytics: "integration.category.analytics",
vpn: "integration.category.vpn",
documents: "integration.category.documents",
mediaLibrary: "integration.category.mediaLibrary",
uptimeMonitoring: "integration.category.uptimeMonitoring",
+11 -19
View File
@@ -1,24 +1,16 @@
"use client";
import Script from "next/script";
import { useEffect } from "react";
import { UMAMI_WEBSITE_ID } from "@homarr/analytics";
import { db } from "@homarr/db";
import { getServerSettingByKeyAsync } from "@homarr/db/queries";
const POSTHOG_KEY = "phc_vYBmGWNbRshvfeC7EHfeSmUm2pD2Neg5nGqzJuGvS8Hs";
const POSTHOG_HOST = "https://hog.homarr.dev";
export const Analytics = async () => {
// For static pages it will not find any analytics data so we do not include the script on them
const analytics = await getServerSettingByKeyAsync(db, "analytics").catch(() => null);
export const Analytics = ({ enabled }: { enabled: boolean }) => {
useEffect(() => {
if (!enabled) return;
if (analytics?.enableGeneral) {
return <Script src="https://umami.homarr.dev/script.js" data-website-id={UMAMI_WEBSITE_ID} defer />;
}
void import("posthog-js").then(({ default: posthog }) => {
posthog.init(POSTHOG_KEY, {
api_host: POSTHOG_HOST,
capture_pageview: false,
capture_pageleave: false,
autocapture: false,
persistence: "memory",
});
});
}, [enabled]);
return null;
return <></>;
};
+1 -1
View File
@@ -1,4 +1,4 @@
FROM node:24.17.0-trixie AS base
FROM node:24.16.0-trixie AS base
WORKDIR /app
COPY package.json .
COPY pnpm-lock.yaml .
+3 -3
View File
@@ -5,8 +5,8 @@
"better-sqlite3": "^12.10.0"
},
"engines": {
"node": ">=24.17.0",
"pnpm": ">=11.8.0"
"node": ">=24.16.0",
"pnpm": ">=11.0.0"
},
"packageManager": "pnpm@11.8.0"
"packageManager": "pnpm@11.5.3"
}
+30 -44
View File
@@ -74,13 +74,6 @@
</a>
</td>
<td align="center">
<a href="null" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/selfhst/icons/png/archiveteam-warrior.png" alt="ArchiveTeam Warrior" width="90" height="90" />
<br/>
<p align="center">ArchiveTeam<br/>Warrior</p>
</a>
</td>
<td align="center">
<a href="https://homarr.dev/docs/integrations/aria2" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/PapirusDevelopmentTeam/papirus_icons@latest/src/system_downloads_3.svg" alt="Aria2" width="90" height="90" />
<br/>
@@ -107,15 +100,15 @@
<br/>
<p align="center">Codeberg</p>
</a>
</td></tr>
<tr><td align="center">
</td>
<td align="center">
<a href="https://homarr.dev/docs/integrations/coolify" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/coolify.svg" alt="Coolify" width="90" height="90" />
<br/>
<p align="center">Coolify</p>
</a>
</td>
<td align="center">
</td></tr>
<tr><td align="center">
<a href="https://homarr.dev/docs/integrations/dash-dot" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/png/dashdot.png" alt="Dash." width="90" height="90" />
<br/>
@@ -156,15 +149,15 @@
<br/>
<p align="center">GitHub<br/>Container<br/>Registry</p>
</a>
</td></tr>
<tr><td align="center">
</td>
<td align="center">
<a href="https://homarr.dev/docs/integrations/gitlab" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/gitlab.svg" alt="Gitlab" width="90" height="90" />
<br/>
<p align="center">Gitlab</p>
</a>
</td>
<td align="center">
</td></tr>
<tr><td align="center">
<a href="null" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/glances.svg" alt="Glances" width="90" height="90" />
<br/>
@@ -172,13 +165,6 @@
</a>
</td>
<td align="center">
<a href="https://homarr.dev/docs/integrations/gotify" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/gotify.svg" alt="Gotify" width="90" height="90" />
<br/>
<p align="center">Gotify</p>
</a>
</td>
<td align="center">
<a href="https://homarr.dev/docs/integrations/home-assistant" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/home-assistant.svg" alt="Home Assistant" width="90" height="90" />
<br/>
@@ -205,8 +191,8 @@
<br/>
<p align="center">Jellyfin</p>
</a>
</td></tr>
<tr><td align="center">
</td>
<td align="center">
<a href="https://homarr.dev/docs/integrations/jellyseerr" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/jellyseerr.svg" alt="Jellyseerr" width="90" height="90" />
<br/>
@@ -219,8 +205,8 @@
<br/>
<p align="center">Lidarr</p>
</a>
</td>
<td align="center">
</td></tr>
<tr><td align="center">
<a href="https://homarr.dev/docs/integrations/linux-server-io" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/linuxserver-io.svg" alt="LinuxServer.io" width="90" height="90" />
<br/>
@@ -254,8 +240,8 @@
<br/>
<p align="center">ntfy</p>
</a>
</td></tr>
<tr><td align="center">
</td>
<td align="center">
<a href="https://homarr.dev/docs/integrations/nzbget" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/nzbget.svg" alt="NZBGet" width="90" height="90" />
<br/>
@@ -268,8 +254,8 @@
<br/>
<p align="center">OpenMediaVault</p>
</a>
</td>
<td align="center">
</td></tr>
<tr><td align="center">
<a href="https://homarr.dev/docs/integrations/opnsense" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/opnsense.svg" alt="OPNsense" width="90" height="90" />
<br/>
@@ -303,8 +289,8 @@
<br/>
<p align="center">Pi-hole</p>
</a>
</td></tr>
<tr><td align="center">
</td>
<td align="center">
<a href="https://homarr.dev/docs/integrations/plex" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/plex.svg" alt="Plex" width="90" height="90" />
<br/>
@@ -317,8 +303,8 @@
<br/>
<p align="center">Prowlarr</p>
</a>
</td>
<td align="center">
</td></tr>
<tr><td align="center">
<a href="https://homarr.dev/docs/integrations/proxmox" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/proxmox.svg" alt="Proxmox" width="90" height="90" />
<br/>
@@ -352,8 +338,8 @@
<br/>
<p align="center">Readarr</p>
</a>
</td></tr>
<tr><td align="center">
</td>
<td align="center">
<a href="https://homarr.dev/docs/integrations/sabnzbd" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/sabnzbd.svg" alt="SABnzbd" width="90" height="90" />
<br/>
@@ -366,8 +352,8 @@
<br/>
<p align="center">Search.ch</p>
</a>
</td>
<td align="center">
</td></tr>
<tr><td align="center">
<a href="https://homarr.dev/docs/integrations/seerr" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/seerr.svg" alt="Seerr" width="90" height="90" />
<br/>
@@ -401,8 +387,8 @@
<br/>
<p align="center">Tdarr</p>
</a>
</td></tr>
<tr><td align="center">
</td>
<td align="center">
<a href="https://homarr.dev/docs/integrations/technitium-dns" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/selfhst/icons/svg/technitium.svg" alt="Technitium DNS" width="90" height="90" />
<br/>
@@ -415,8 +401,8 @@
<br/>
<p align="center">Tracearr</p>
</a>
</td>
<td align="center">
</td></tr>
<tr><td align="center">
<a href="https://homarr.dev/docs/integrations/transmission" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/transmission.svg" alt="Transmission" width="90" height="90" />
<br/>
@@ -450,8 +436,8 @@
<br/>
<p align="center">Unraid</p>
</a>
</td></tr>
<tr><td align="center">
</td>
<td align="center">
<a href="null" target="_blank" rel="noreferrer noopener">
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/uptime-kuma.svg" alt="Uptime Kuma" width="90" height="90" />
<br/>
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "homarr",
"version": "1.67.0",
"version": "1.65.0",
"private": true,
"scripts": {
"build": "cross-env CI=true turbo build",
@@ -61,10 +61,10 @@
"vitest": "catalog:"
},
"engines": {
"node": ">=24.17.0",
"pnpm": ">=11.8.0"
"node": ">=24.16.0",
"pnpm": ">=11.0.0"
},
"packageManager": "pnpm@11.8.0",
"packageManager": "pnpm@11.5.3",
"dependencies": {
"jsonpath-plus": "catalog:"
}
+3 -1
View File
@@ -26,7 +26,9 @@
"@homarr/core": "workspace:^0.1.0",
"@homarr/db": "workspace:^0.1.0",
"@homarr/docker": "workspace:^0.1.0",
"posthog-node": "catalog:"
"@homarr/server-settings": "workspace:^0.1.0",
"@umami/node": "catalog:",
"superjson": "catalog:"
},
"devDependencies": {
"@homarr/tsconfig": "workspace:^0.1.0",
-23
View File
@@ -1,23 +0,0 @@
import { PostHog } from "posthog-node";
export const POSTHOG_API_KEY = "phc_vYBmGWNbRshvfeC7EHfeSmUm2pD2Neg5nGqzJuGvS8Hs";
export const POSTHOG_HOST = "https://hog.homarr.dev";
let instance: PostHog | undefined;
export const getPostHogClient = (): PostHog => {
instance ??= new PostHog(POSTHOG_API_KEY, {
host: POSTHOG_HOST,
flushAt: 10,
flushInterval: 30_000,
});
return instance;
};
export const trackEvent = (instanceId: string, event: string, properties?: Record<string, unknown>) => {
getPostHogClient().capture({
distinctId: instanceId,
event,
properties,
});
};
+2
View File
@@ -0,0 +1,2 @@
export const UMAMI_HOST_URL = "https://umami.homarr.dev";
export const UMAMI_WEBSITE_ID = "ff7dc470-a84f-4779-b1ab-66a5bb16a94b";
+2 -2
View File
@@ -1,2 +1,2 @@
export { trackEvent } from "./client";
export { sendServerAnalyticsAsync } from "./send-server-analytics";
export * from "./constants";
export * from "./send-server-analytics";
+63 -136
View File
@@ -1,16 +1,17 @@
import type { UmamiEventData } from "@umami/node";
import { Umami } from "@umami/node";
import { isProviderEnabled } from "@homarr/auth/server";
import { createId, Stopwatch } from "@homarr/common";
import { Stopwatch } from "@homarr/common";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { count, db } from "@homarr/db";
import { isMysql, isPostgresql } from "@homarr/db/collection";
import { getServerSettingByKeyAsync, updateServerSettingByKeyAsync } from "@homarr/db/queries";
import { getServerSettingByKeyAsync } from "@homarr/db/queries";
import {
accounts,
apiKeys,
apps,
boards,
cronJobConfigurations,
customWidgetDefinitions,
groups,
iconRepositories,
icons,
@@ -23,160 +24,86 @@ import {
searchEngines,
sectionLayouts,
sections,
sessions,
trustedCertificateHostnames,
users,
} from "@homarr/db/schema";
import { env as dockerEnv } from "@homarr/docker/env";
import packageJson from "../../../package.json";
import { getPostHogClient } from "./client";
import { UMAMI_HOST_URL, UMAMI_WEBSITE_ID } from "./constants";
const logger = createLogger({ module: "analytics" });
type AnalyticsResult = "sent" | "disabled" | "failed";
// ponytail: no DB-level lock; concurrent calls may both generate an ID, but the last write wins
// and the ID stabilizes after the first successful run. Upgrade path: use DB upsert with WHERE instanceId IS NULL.
const getOrCreateInstanceId = async (
analyticsSettings: Awaited<ReturnType<typeof getServerSettingByKeyAsync<"analytics">>>,
): Promise<string> => {
if (analyticsSettings.instanceId) return analyticsSettings.instanceId;
const instanceId = createId();
await updateServerSettingByKeyAsync(db, "analytics", { ...analyticsSettings, instanceId });
const verified = await getServerSettingByKeyAsync(db, "analytics");
return verified.instanceId ?? instanceId;
const getDatabaseType = (): "mysql" | "postgresql" | "sqlite" => {
if (isMysql()) return "mysql";
if (isPostgresql()) return "postgresql";
return "sqlite";
};
const sumGroupedCounts = (rows: { count: number }[]): number => rows.reduce((sum, row) => sum + row.count, 0);
const getEnabledAuthProviders = (): string[] => {
const providers: string[] = [];
if (isProviderEnabled("credentials")) providers.push("credentials");
if (isProviderEnabled("oidc")) providers.push("oidc");
if (isProviderEnabled("ldap")) providers.push("ldap");
return providers;
};
export const sendServerAnalyticsAsync = async (): Promise<AnalyticsResult> => {
export const sendServerAnalyticsAsync = async () => {
const stopWatch = new Stopwatch();
const analyticsSettings = await getServerSettingByKeyAsync(db, "analytics");
if (!analyticsSettings.enableGeneral) {
logger.info("Analytics are disabled. No data will be sent. Enable analytics in the settings");
return "disabled";
return;
}
const client = getPostHogClient();
const umamiInstance = new Umami();
umamiInstance.init({
hostUrl: UMAMI_HOST_URL,
websiteId: UMAMI_WEBSITE_ID,
});
try {
const instanceId = await getOrCreateInstanceId(analyticsSettings);
const enabledAuthProviders = getEnabledAuthProviders();
const [
cultureSettings,
countBoards,
countGroups,
countApps,
countSections,
countSearchEngines,
countIconRepositories,
countIcons,
countLayouts,
countItemLayouts,
countSectionLayouts,
countCronJobConfigs,
countCustomWidgets,
countTrustedCertificates,
countUsers,
countApiKeys,
countInvites,
countMedias,
countSessions,
countAccounts,
integrationKinds,
widgetKinds,
] = await Promise.all([
getServerSettingByKeyAsync(db, "culture"),
db.$count(boards),
db.$count(groups),
db.$count(apps),
db.$count(sections),
db.$count(searchEngines),
db.$count(iconRepositories),
db.$count(icons),
db.$count(layouts),
db.$count(itemLayouts),
db.$count(sectionLayouts),
db.$count(cronJobConfigurations),
db.$count(customWidgetDefinitions),
db.$count(trustedCertificateHostnames),
db.$count(users),
db.$count(apiKeys),
db.$count(invites),
db.$count(medias),
db.$count(sessions),
db.$count(accounts),
db
.select({ kind: integrations.kind, count: count(integrations.id) })
.from(integrations)
.groupBy(integrations.kind),
db
.select({ kind: items.kind, count: count(items.id) })
.from(items)
.groupBy(items.kind),
]);
const analyticsData: UmamiEventData = {
homarrVersion: packageJson.version,
databaseType: getDatabaseType(),
dockerEnabled: dockerEnv.ENABLE_DOCKER ? 1 : 0,
kubernetesEnabled: dockerEnv.ENABLE_KUBERNETES ? 1 : 0,
authCredentials: enabledAuthProviders.includes("credentials") ? 1 : 0,
authOidc: enabledAuthProviders.includes("oidc") ? 1 : 0,
authLdap: enabledAuthProviders.includes("ldap") ? 1 : 0,
countUsers: await db.$count(users),
countBoards: await db.$count(boards),
countGroups: await db.$count(groups),
countApps: await db.$count(apps),
countWidgets: await db.$count(items),
countSections: await db.$count(sections),
countIntegrations: await db.$count(integrations),
countSearchEngines: await db.$count(searchEngines),
countIconRepositories: await db.$count(iconRepositories),
countIcons: await db.$count(icons),
countApiKeys: await db.$count(apiKeys),
countInvites: await db.$count(invites),
countMedias: await db.$count(medias),
countLayouts: await db.$count(layouts),
countItemLayouts: await db.$count(itemLayouts),
countSectionLayouts: await db.$count(sectionLayouts),
countCronJobConfigs: await db.$count(cronJobConfigurations),
};
const enabledAuthProviders = (["credentials", "oidc", "ldap"] as const).filter(isProviderEnabled);
const integrationKinds = await db
.select({ kind: integrations.kind, count: count(integrations.id) })
.from(integrations)
.groupBy(integrations.kind);
const properties: Record<string, unknown> = {
homarrVersion: packageJson.version,
databaseType: isMysql() ? "mysql" : isPostgresql() ? "postgresql" : "sqlite",
dockerEnabled: Boolean(dockerEnv.ENABLE_DOCKER),
kubernetesEnabled: Boolean(dockerEnv.ENABLE_KUBERNETES),
authProviders: enabledAuthProviders,
integrationKinds.forEach((integrationKind) => {
analyticsData[`integration_${integrationKind.kind}`] = integrationKind.count;
});
osPlatform: process.platform,
osArch: process.arch,
uptimeSeconds: Math.floor(process.uptime()),
defaultLocale: cultureSettings.defaultLocale,
countBoards,
countGroups,
countApps,
countSections,
countSearchEngines,
countIconRepositories,
countIcons,
countLayouts,
countItemLayouts,
countSectionLayouts,
countCronJobConfigs,
countCustomWidgets,
countTrustedCertificates,
countUsers,
countApiKeys,
countInvites,
countMedias,
countSessions,
countAccounts,
countIntegrations: sumGroupedCounts(integrationKinds),
countWidgets: sumGroupedCounts(widgetKinds),
};
for (const row of integrationKinds) {
properties[`integration_${row.kind}`] = row.count;
}
for (const row of widgetKinds) {
properties[`widget_${row.kind}`] = row.count;
}
client.capture({
distinctId: instanceId,
event: "server-analytics",
properties,
});
await client.flush();
logger.info(`Sent analytics to PostHog in ${stopWatch.getElapsedInHumanWords()}`);
return "sent";
} catch (error) {
logger.warn("Failed to send analytics to PostHog", { error });
return "failed";
const response = await umamiInstance.track("server-analytics-v2", analyticsData);
if (!response.ok) {
logger.warn("Unable to send analytics to Umami instance");
}
logger.info(`Sent analytics in ${stopWatch.getElapsedInHumanWords()}`);
};
-1
View File
@@ -24,7 +24,6 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@homarr/analytics": "workspace:^0.1.0",
"@homarr/auth": "workspace:^0.1.0",
"@homarr/common": "workspace:^0.1.0",
"@homarr/core": "workspace:^0.1.0",
-2
View File
@@ -9,7 +9,6 @@ import { iconsRouter } from "./router/icons";
import { infoRouter } from "./router/info";
import { integrationRouter } from "./router/integration/integration-router";
import { inviteRouter } from "./router/invite";
import { beszelRouter } from "./router/widgets/beszel";
import { calendarRouter } from "./router/widgets/calendar";
import { dnsHoleRouter } from "./router/widgets/dns-hole";
import { downloadsRouter } from "./router/widgets/downloads";
@@ -27,7 +26,6 @@ export const mcpRouter = createTRPCRouter({
info: infoRouter,
integration: integrationRouter,
invite: inviteRouter,
beszel: beszelRouter,
calendar: calendarRouter,
dnsHole: dnsHoleRouter,
downloads: downloadsRouter,
-1
View File
@@ -28,7 +28,6 @@ export const appRouter = createTRPCRouter({
updateChecker: lazy(() => import("./router/update-checker").then((mod) => mod.updateCheckerRouter)),
certificates: lazy(() => import("./router/certificates/certificate-router").then((mod) => mod.certificateRouter)),
bangs: lazy(() => import("./router/bangs/bangs-router").then((mod) => mod.bangsRouter)),
analytics: lazy(() => import("./router/analytics").then((mod) => mod.analyticsRouter)),
info: lazy(() => import("./router/info").then((mod) => mod.infoRouter)),
customWidget: lazy(() => import("./router/custom-widget/custom-widget-router").then((mod) => mod.customWidgetRouter)),
});
-51
View File
@@ -1,51 +0,0 @@
import { TRPCError } from "@trpc/server";
import z from "zod/v4";
import { sendServerAnalyticsAsync, trackEvent } from "@homarr/analytics";
import { env } from "@homarr/common/env";
import { db } from "@homarr/db";
import { getServerSettingByKeyAsync } from "@homarr/db/queries";
import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure } from "../trpc";
const getInstanceId = async (): Promise<string | null> => {
if (env.NO_EXTERNAL_CONNECTION) return null;
const settings = await getServerSettingByKeyAsync(db, "analytics");
if (!settings.enableGeneral) return null;
return settings.instanceId;
};
export const analyticsRouter = createTRPCRouter({
sendAnalytics: permissionRequiredProcedure.requiresPermission("admin").mutation(async () => {
if (env.NO_EXTERNAL_CONNECTION) {
throw new TRPCError({ code: "PRECONDITION_FAILED", message: "External connections are disabled" });
}
return { status: await sendServerAnalyticsAsync() };
}),
trackFeature: protectedProcedure
.input(
z.object({
feature: z.string().max(128),
properties: z.record(z.string(), z.unknown()).optional(),
}),
)
.mutation(async ({ input, ctx }) => {
const instanceId = await getInstanceId();
if (!instanceId) return;
trackEvent(instanceId, `feature:${input.feature}`, {
...input.properties,
userId: ctx.session.user.id,
});
}),
heartbeat: protectedProcedure.mutation(async ({ ctx }) => {
const instanceId = await getInstanceId();
if (!instanceId) return;
trackEvent(instanceId, "user-active", {
userId: ctx.session.user.id,
});
}),
});
+5 -21
View File
@@ -1,12 +1,11 @@
import { TRPCError } from "@trpc/server";
import { z } from "zod/v4";
import { canManageGroupMembersLocally, isGroupMembershipManagedLocally } from "@homarr/auth/server";
import { createId } from "@homarr/common";
import type { Database } from "@homarr/db";
import { and, eq, handleTransactionsAsync, like, not } from "@homarr/db";
import { getMaxGroupPositionAsync } from "@homarr/db/queries";
import { groupMembers, groupPermissions, groups, users } from "@homarr/db/schema";
import { groupMembers, groupPermissions, groups } from "@homarr/db/schema";
import { everyoneGroup } from "@homarr/definitions";
import { byIdSchema, paginatedSchema } from "@homarr/validation/common";
import {
@@ -19,6 +18,7 @@ import {
} from "@homarr/validation/group";
import { createTRPCRouter, onboardingProcedure, permissionRequiredProcedure, protectedProcedure } from "../trpc";
import { throwIfCredentialsDisabled } from "./invite/checks";
import { nextOnboardingStepAsync } from "./onboard/onboard-queries";
export const groupRouter = createTRPCRouter({
@@ -315,10 +315,10 @@ export const groupRouter = createTRPCRouter({
.mutation(async ({ input, ctx }) => {
await throwIfGroupNotFoundAsync(ctx.db, input.groupId);
await throwIfGroupNameIsReservedAsync(ctx.db, input.groupId);
throwIfGroupMembersCannotBeManagedLocally();
throwIfCredentialsDisabled();
const user = await ctx.db.query.users.findFirst({
where: eq(users.id, input.userId),
where: eq(groups.id, input.userId),
});
if (!user) {
@@ -328,13 +328,6 @@ export const groupRouter = createTRPCRouter({
});
}
if (!isGroupMembershipManagedLocally(user.provider)) {
throw new TRPCError({
code: "FORBIDDEN",
message: "User's provider is not managed locally",
});
}
await ctx.db.insert(groupMembers).values({
groupId: input.groupId,
userId: input.userId,
@@ -346,7 +339,7 @@ export const groupRouter = createTRPCRouter({
.mutation(async ({ input, ctx }) => {
await throwIfGroupNotFoundAsync(ctx.db, input.groupId);
await throwIfGroupNameIsReservedAsync(ctx.db, input.groupId);
throwIfGroupMembersCannotBeManagedLocally();
throwIfCredentialsDisabled();
await ctx.db
.delete(groupMembers)
@@ -378,15 +371,6 @@ const throwIfGroupNameIsReservedAsync = async (db: Database, id: string) => {
}
};
const throwIfGroupMembersCannotBeManagedLocally = () => {
if (!canManageGroupMembersLocally()) {
throw new TRPCError({
code: "FORBIDDEN",
message: "Group members cannot be managed locally",
});
}
};
const throwIfGroupNotFoundAsync = async (db: Database, id: string) => {
const group = await db.query.groups.findFirst({
where: eq(groups.id, id),
+9 -25
View File
@@ -15,36 +15,20 @@ export const iconsRouter = createTRPCRouter({
})
.input(iconsFindSchema)
.query(async ({ ctx, input }) => {
const term = input.searchText?.toLowerCase().trim() ?? "";
const keywords = (input.searchText ?? "").split(" ").filter((keyword) => keyword.length > 0);
let whereCondition = undefined;
if (term.length > 0) {
whereCondition = and(...keywords.map((keyword) => like(icons.name, `%${keyword}%`)));
}
return {
icons: await ctx.db.query.iconRepositories.findMany({
with: {
icons: {
columns: { id: true, name: true, url: true },
where: whereCondition,
orderBy: (table, { asc, sql }) => {
// ponytail: SVG first, then alphabetical; with a search term,
// prepend a relevance tier (exact > prefix > substring).
const svgFirst = sql`CASE WHEN ${table.name} LIKE '%.svg' THEN 0 ELSE 1 END`;
const nameAsc = asc(table.name);
if (term.length === 0) {
return [svgFirst, nameAsc];
}
const tier = sql`CASE
WHEN LOWER(${table.name}) = ${term} THEN 0
WHEN LOWER(${table.name}) LIKE ${term + "%"} THEN 1
WHEN LOWER(${table.name}) LIKE ${`%${term}%`} THEN 2
ELSE 3
END`;
return [tier, svgFirst, nameAsc];
columns: {
id: true,
name: true,
url: true,
},
where:
(input.searchText?.length ?? 0) > 0
? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
and(...input.searchText!.split(" ").map((keyword) => like(icons.name, `%${keyword}%`)))
: undefined,
limit: input.limitPerGroup,
},
},
@@ -27,7 +27,6 @@ import {
integrationSecretKindObject,
} from "@homarr/definitions";
import { createIntegrationAsync } from "@homarr/integrations";
import { invalidateIntegrationCacheAsync } from "@homarr/redis";
import { byIdSchema } from "@homarr/validation/common";
import {
integrationCreateSchema,
@@ -470,10 +469,6 @@ export const integrationRouter = createTRPCRouter({
kind: integration.kind,
url: input.url,
});
// Invalidate all cached data for this integration so that widgets pick up the
// new configuration immediately instead of serving stale (or errored) data.
await invalidateIntegrationCacheAsync(input.id);
}),
delete: protectedProcedure
.meta({
@@ -495,9 +490,6 @@ export const integrationRouter = createTRPCRouter({
}
await ctx.db.delete(integrations).where(eq(integrations.id, input.id));
// Clean up any cached data left behind by the deleted integration.
await invalidateIntegrationCacheAsync(input.id);
}),
getIntegrationPermissions: protectedProcedure.input(byIdSchema).query(async ({ input, ctx }) => {
await throwIfActionForbiddenAsync(ctx, eq(integrations.id, input.id), "full");
+6 -7
View File
@@ -24,18 +24,17 @@ export const serverSettingsRouter = createTRPCRouter({
}),
)
.mutation(async ({ ctx, input }) => {
const current = await getServerSettingByKeyAsync(ctx.db, input.settingsKey);
await updateServerSettingByKeyAsync(ctx.db, input.settingsKey, {
...current,
...input.value,
} as ServerSettings[keyof ServerSettings]);
await updateServerSettingByKeyAsync(
ctx.db,
input.settingsKey,
input.value as ServerSettings[keyof ServerSettings],
);
}),
initSettings: onboardingProcedure
.requiresStep("settings")
.input(settingsInitSchema)
.mutation(async ({ ctx, input }) => {
const currentAnalytics = await getServerSettingByKeyAsync(ctx.db, "analytics");
await updateServerSettingByKeyAsync(ctx.db, "analytics", { ...currentAnalytics, ...input.analytics });
await updateServerSettingByKeyAsync(ctx.db, "analytics", input.analytics);
await updateServerSettingByKeyAsync(ctx.db, "crawlingAndIndexing", input.crawlingAndIndexing);
await nextOnboardingStepAsync(ctx.db, undefined);
}),
+2 -40
View File
@@ -748,45 +748,7 @@ describe("addMember should add member to group", () => {
});
// Assert
await expect(actAsync()).rejects.toThrow("Group members cannot be managed locally");
});
test("with a user from an externally managed provider it should throw FORBIDDEN error", async () => {
// Arrange
const db = createDb();
const spy = vi.spyOn(env, "env", "get");
spy.mockReturnValue({ AUTH_PROVIDERS: ["credentials", "ldap"] } as never);
const caller = groupRouter.createCaller({ db, deviceType: undefined, session: adminSession });
const groupId = createId();
const userId = createId();
await db.insert(users).values([
{
id: userId,
name: "User",
provider: "ldap",
},
{
id: defaultOwnerId,
name: "Creator",
},
]);
await db.insert(groups).values({
id: groupId,
name: "Group",
ownerId: defaultOwnerId,
position: 1,
});
// Act
const actAsync = async () =>
await caller.addMember({
groupId,
userId,
});
// Assert
await expect(actAsync()).rejects.toThrow("User's provider is not managed locally");
await expect(actAsync()).rejects.toThrow("Credentials provider is disabled");
});
});
@@ -910,7 +872,7 @@ describe("removeMember should remove member from group", () => {
});
// Assert
await expect(actAsync()).rejects.toThrow("Group members cannot be managed locally");
await expect(actAsync()).rejects.toThrow("Credentials provider is disabled");
});
});
@@ -75,6 +75,9 @@ describe("saveSettings", () => {
settingsKey: "analytics",
value: {
enableGeneral: true,
enableWidgetData: true,
enableIntegrationData: true,
enableUserData: true,
},
});
@@ -84,7 +87,9 @@ describe("saveSettings", () => {
settingKey: "analytics",
value: SuperJSON.stringify({
enableGeneral: true,
instanceId: null,
enableWidgetData: true,
enableIntegrationData: true,
enableUserData: true,
}),
},
]);
+4 -4
View File
@@ -7,12 +7,12 @@ import { comparePasswordsAsync, hashPasswordAsync } from "@homarr/auth";
import { createId } from "@homarr/common";
import { createLogger } from "@homarr/core/infrastructure/logs";
import type { Database } from "@homarr/db";
import { and, eq, handleTransactionsAsync, inArray, like } from "@homarr/db";
import { and, eq, handleTransactionsAsync, like } from "@homarr/db";
import { getMaxGroupPositionAsync } from "@homarr/db/queries";
import { boards, groupMembers, groupPermissions, groups, invites, users } from "@homarr/db/schema";
import { selectUserSchema } from "@homarr/db/validationSchemas";
import type { SupportedAuthProvider } from "@homarr/definitions";
import { credentialsAdminGroup, supportedAuthProviders } from "@homarr/definitions";
import { credentialsAdminGroup } from "@homarr/definitions";
import { byIdSchema } from "@homarr/validation/common";
import type { userBaseCreateSchema } from "@homarr/validation/user";
import {
@@ -257,7 +257,7 @@ export const userRouter = createTRPCRouter({
}),
// Is protected because also used in board access / integration access forms
selectable: protectedProcedure
.input(z.object({ providers: z.array(z.enum(supportedAuthProviders)).optional() }).optional())
.input(z.object({ excludeExternalProviders: z.boolean().default(false) }).optional())
.output(
z.array(
selectUserSchema.pick({
@@ -284,7 +284,7 @@ export const userRouter = createTRPCRouter({
image: true,
email: true,
},
where: input?.providers ? inArray(users.provider, input.providers) : undefined,
where: input?.excludeExternalProviders ? eq(users.provider, "credentials") : undefined,
});
}),
search: permissionRequiredProcedure
@@ -1,39 +0,0 @@
import { observable } from "@trpc/server/observable";
import type { ArchiveTeamWarriorStatus } from "@homarr/integrations";
import { archiveTeamWarriorRequestHandler } from "@homarr/request-handler/archive-team-warrior";
import { createOneIntegrationMiddleware } from "../../middlewares/integration";
import { createTRPCRouter, publicProcedure } from "../../trpc";
export const archiveTeamWarriorRouter = createTRPCRouter({
getStatus: publicProcedure
.concat(createOneIntegrationMiddleware("query", "archiveTeamWarrior"))
.query(async ({ ctx }) => {
const handler = archiveTeamWarriorRequestHandler.handler(ctx.integration, {});
const { data, timestamp } = await handler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
return {
status: data,
updatedAt: timestamp,
};
}),
subscribeStatus: publicProcedure
.concat(createOneIntegrationMiddleware("query", "archiveTeamWarrior"))
.subscription(({ ctx }) => {
return observable<{ status: ArchiveTeamWarriorStatus; updatedAt: Date }>((emit) => {
const handler = archiveTeamWarriorRequestHandler.handler(ctx.integration, {});
const unsubscribe = handler.subscribe((status) => {
emit.next({
status,
updatedAt: new Date(),
});
});
return () => {
unsubscribe();
};
});
}),
});
+11 -196
View File
@@ -1,10 +1,6 @@
import { TRPCError } from "@trpc/server";
import { observable } from "@trpc/server/observable";
import { z } from "zod/v4";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { createIntegrationAsync } from "@homarr/integrations";
import type { BeszelContainerStatsRecord, BeszelSystemStatsRecord } from "@homarr/integrations/types";
import {
beszelAlertsRequestHandler,
beszelStatsRequestHandler,
@@ -15,27 +11,14 @@ import type { BeszelAlertsData, BeszelSystemRow } from "@homarr/request-handler/
import { createManyIntegrationMiddleware } from "../../middlewares/integration";
import { createTRPCRouter, publicProcedure } from "../../trpc";
const logger = createLogger({ module: "beszelRouter" });
export const beszelRouter = createTRPCRouter({
getSystems: publicProcedure
.meta({
mcp: {
enabled: true,
description:
"Get all Beszel-monitored systems with CPU, memory, disk, GPU, network, temperature, and status. REQUIRED: integrationIds (array of Beszel integration IDs from integration_all)",
},
})
.concat(createManyIntegrationMiddleware("query", "beszel", "mock"))
.query(async ({ ctx }) => {
const integrationIds = ctx.integrations.map((i) => i.id);
logger.debug("getSystems called", { userId: ctx.session?.user?.id, integrationIds });
const settled = await Promise.allSettled(
const results = await Promise.all(
ctx.integrations.map(async (integration) => {
const innerHandler = beszelSystemsRequestHandler.handler(integration, {});
const { data, timestamp } = await innerHandler.getCachedOrUpdatedDataAsync({
forceUpdate: false,
});
const { data, timestamp } = await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
return {
integrationId: integration.id,
integrationName: integration.name,
@@ -45,40 +28,13 @@ export const beszelRouter = createTRPCRouter({
};
}),
);
const results = settled.map((result, index) => {
if (result.status === "fulfilled") return result.value;
const integration = ctx.integrations[index];
logger.warn("getSystems integration failed", {
userId: ctx.session?.user?.id,
integrationId: integration?.id,
error: result.reason,
});
return {
integrationId: integration?.id ?? "unknown",
integrationName: integration?.name ?? "unknown",
integrationUrl: integration?.url ?? "",
systems: [],
updatedAt: new Date(0),
error: result.reason instanceof Error ? result.reason.message : String(result.reason),
};
});
logger.debug("getSystems completed", {
userId: ctx.session?.user?.id,
integrationIds,
resultCount: results.length,
errorCount: results.filter((r) => "error" in r).length,
});
return results;
}),
subscribeSystems: publicProcedure
.concat(createManyIntegrationMiddleware("query", "beszel", "mock"))
.subscription(({ ctx }) => {
return observable<{
integrationId: string;
systems: BeszelSystemRow[];
timestamp: Date;
}>((emit) => {
return observable<{ integrationId: string; systems: BeszelSystemRow[]; timestamp: Date }>((emit) => {
const unsubscribes = ctx.integrations.map((integration) => {
const innerHandler = beszelSystemsRequestHandler.handler(integration, {});
return innerHandler.subscribe((systems) => {
@@ -96,13 +52,6 @@ export const beszelRouter = createTRPCRouter({
}),
getAlerts: publicProcedure
.meta({
mcp: {
enabled: true,
description:
"Get Beszel alerts and optional alert history for all monitored systems. REQUIRED: integrationIds (array of Beszel integration IDs from integration_all). OPTIONAL: includeHistory (default true), maxHistoryItems (default 10)",
},
})
.concat(createManyIntegrationMiddleware("query", "beszel", "mock"))
.input(
z.object({
@@ -111,14 +60,7 @@ export const beszelRouter = createTRPCRouter({
}),
)
.query(async ({ ctx, input }) => {
const integrationIds = ctx.integrations.map((i) => i.id);
logger.debug("getAlerts called", {
userId: ctx.session?.user?.id,
integrationIds,
includeHistory: input.includeHistory,
maxHistoryItems: input.maxHistoryItems,
});
const settled = await Promise.allSettled(
const results = await Promise.all(
ctx.integrations.map(async (integration) => {
const alertsHandler = beszelAlertsRequestHandler.handler(integration, {
includeHistory: input.includeHistory,
@@ -135,7 +77,6 @@ export const beszelRouter = createTRPCRouter({
}
return {
integrationId: integration.id,
integrationName: integration.name,
alerts: alertsResult.data.alerts,
history: alertsResult.data.history,
systemNameMap,
@@ -143,30 +84,6 @@ export const beszelRouter = createTRPCRouter({
};
}),
);
const results = settled.map((result, index) => {
if (result.status === "fulfilled") return result.value;
const integration = ctx.integrations[index];
logger.warn("getAlerts integration failed", {
userId: ctx.session?.user?.id,
integrationId: integration?.id,
error: result.reason,
});
return {
integrationId: integration?.id ?? "unknown",
integrationName: integration?.name ?? "unknown",
alerts: [],
history: [],
systemNameMap: {},
updatedAt: new Date(0),
error: result.reason instanceof Error ? result.reason.message : String(result.reason),
};
});
logger.debug("getAlerts completed", {
userId: ctx.session?.user?.id,
integrationIds,
resultCount: results.length,
errorCount: results.filter((r) => "error" in r).length,
});
return results;
}),
@@ -179,22 +96,14 @@ export const beszelRouter = createTRPCRouter({
}),
)
.subscription(({ ctx, input }) => {
return observable<{
integrationId: string;
alerts: BeszelAlertsData;
timestamp: Date;
}>((emit) => {
return observable<{ integrationId: string; alerts: BeszelAlertsData; timestamp: Date }>((emit) => {
const unsubscribes = ctx.integrations.map((integration) => {
const innerHandler = beszelAlertsRequestHandler.handler(integration, {
includeHistory: input.includeHistory,
maxHistoryItems: input.maxHistoryItems,
});
return innerHandler.subscribe((data) => {
emit.next({
integrationId: integration.id,
alerts: data,
timestamp: new Date(),
});
emit.next({ integrationId: integration.id, alerts: data, timestamp: new Date() });
});
});
return () => {
@@ -204,117 +113,23 @@ export const beszelRouter = createTRPCRouter({
}),
getSystemStats: publicProcedure
.meta({
mcp: {
enabled: true,
description:
"Get historical Beszel system metrics (CPU, memory, disk, network, temperature) and optional Docker container stats. REQUIRED: integrationIds (pass the single integrationId from the beszel_getSystems entry containing the target system — only the first ID is used), systemId (from beszel_getSystems). OPTIONAL: timePeriod (1m/1h/12h/24h/1w/30d, default 1h), includeDocker (default true)",
},
})
.concat(createManyIntegrationMiddleware("query", "beszel", "mock"))
.input(
z.object({
systemId: z.string(),
timePeriod: z.enum(["1m", "1h", "12h", "24h", "1w", "30d"]).default("1h"),
timePeriod: z.enum(["1h", "12h", "24h", "1w", "30d"]),
includeDocker: z.boolean().default(true),
}),
)
.query(async ({ ctx, input }) => {
const integration = ctx.integrations[0];
if (!integration) {
throw new TRPCError({ code: "BAD_REQUEST", message: "At least one Beszel integrationId is required" });
}
logger.debug("getSystemStats called", {
userId: ctx.session?.user?.id,
integrationId: integration.id,
if (!integration) return null;
const innerHandler = beszelStatsRequestHandler.handler(integration, {
systemId: input.systemId,
timePeriod: input.timePeriod,
includeDocker: input.includeDocker,
});
try {
const innerHandler = beszelStatsRequestHandler.handler(integration, {
systemId: input.systemId,
timePeriod: input.timePeriod,
includeDocker: input.includeDocker,
});
const { data, timestamp } = await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
logger.debug("getSystemStats completed", {
userId: ctx.session?.user?.id,
integrationId: integration.id,
systemId: input.systemId,
});
return { integrationId: integration.id, ...data, updatedAt: timestamp };
} catch (error) {
logger.warn("getSystemStats failed", {
userId: ctx.session?.user?.id,
integrationId: integration.id,
systemId: input.systemId,
error,
});
return {
integrationId: integration.id,
systemStats: [],
containerStats: [],
updatedAt: new Date(0),
error: error instanceof Error ? error.message : String(error),
};
}
}),
subscribeSystemStats: publicProcedure
.concat(createManyIntegrationMiddleware("query", "beszel", "mock"))
.input(
z.object({
systemId: z.string(),
}),
)
.subscription(({ ctx, input }) => {
return observable<{
stats: BeszelSystemStatsRecord;
containerStats: BeszelContainerStatsRecord | null;
}>((emit) => {
const integration = ctx.integrations[0];
if (!integration) {
emit.error(new Error("No Beszel integration configured"));
return () => {};
}
logger.debug("subscribeSystemStats opened", {
userId: ctx.session?.user?.id,
integrationId: integration.id,
systemId: input.systemId,
});
const abortController = new AbortController();
void (async () => {
try {
const instance = await createIntegrationAsync(integration);
await instance.subscribeRealtimeMetrics(input.systemId, (data) => emit.next(data), abortController.signal);
} catch (error) {
if (!abortController.signal.aborted) {
logger.warn("subscribeSystemStats error", {
userId: ctx.session?.user?.id,
integrationId: integration.id,
systemId: input.systemId,
error,
});
if (error instanceof Error) {
emit.error(error);
} else {
emit.error(new Error(String(error)));
}
}
}
})();
return () => {
abortController.abort();
logger.debug("subscribeSystemStats closed", {
userId: ctx.session?.user?.id,
integrationId: integration.id,
systemId: input.systemId,
});
};
});
const { data, timestamp } = await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
return { integrationId: integration.id, ...data, updatedAt: timestamp };
}),
});
-2
View File
@@ -3,7 +3,6 @@ import { lazy } from "@trpc/server";
import { createTRPCRouter } from "../../trpc";
export const widgetRouter = createTRPCRouter({
archiveTeamWarrior: lazy(() => import("./archive-team-warrior").then((mod) => mod.archiveTeamWarriorRouter)),
beszel: lazy(() => import("./beszel").then((mod) => mod.beszelRouter)),
anchorNotes: lazy(() => import("./anchor-notes").then((mod) => mod.anchorNotesRouter)),
coolify: lazy(() => import("./coolify").then((mod) => mod.coolifyRouter)),
@@ -36,7 +35,6 @@ export const widgetRouter = createTRPCRouter({
uptimeKuma: lazy(() => import("./uptime-kuma").then((mod) => mod.uptimeKumaRouter)),
audioStats: lazy(() => import("./audio-stats").then((mod) => mod.audioStatsRouter)),
umami: lazy(() => import("./umami").then((mod) => mod.umamiRouter)),
vpn: lazy(() => import("./vpn").then((mod) => mod.vpnRouter)),
ups: lazy(() => import("./ups").then((mod) => mod.upsRouter)),
customApi: lazy(() => import("./custom-api").then((mod) => mod.customApiRouter)),
});
+1 -37
View File
@@ -1,14 +1,7 @@
import { TRPCError } from "@trpc/server";
import SuperJSON from "superjson";
import { z } from "zod/v4";
import { eq } from "@homarr/db";
import { getServerSettingsAsync } from "@homarr/db/queries";
import { boards, items } from "@homarr/db/schema";
import type { WidgetOptionsSettings } from "../../../../widgets/src";
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../../trpc";
import { throwIfActionForbiddenAsync } from "../board/board-access";
import { createTRPCRouter, publicProcedure } from "../../trpc";
export const optionsRouter = createTRPCRouter({
getWidgetOptionSettings: publicProcedure.query(async ({ ctx }): Promise<WidgetOptionsSettings> => {
@@ -23,33 +16,4 @@ export const optionsRouter = createTRPCRouter({
},
};
}),
saveItemOptions: protectedProcedure
.input(
z.object({
itemId: z.string(),
boardId: z.string(),
newOptions: z.record(z.string(), z.unknown()),
}),
)
.mutation(async ({ ctx, input }) => {
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.boardId), "modify");
const item = await ctx.db.query.items.findFirst({
where: eq(items.id, input.itemId),
});
if (item?.boardId !== input.boardId) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Specified item was not found",
});
}
const options = SuperJSON.parse<Record<string, unknown>>(item.options);
Object.assign(options, input.newOptions);
await ctx.db
.update(items)
.set({ options: SuperJSON.stringify(options) })
.where(eq(items.id, input.itemId));
}),
});
-59
View File
@@ -1,59 +0,0 @@
import { observable } from "@trpc/server/observable";
import type { Modify } from "@homarr/common/types";
import type { Integration } from "@homarr/db/schema";
import type { IntegrationKindByCategory } from "@homarr/definitions";
import { getIntegrationKindsByCategory } from "@homarr/definitions";
import type { VpnSummary } from "@homarr/integrations/types";
import { vpnSummaryHandler } from "@homarr/request-handler/vpn";
import { createManyIntegrationMiddleware } from "../../middlewares/integration";
import { createTRPCRouter, publicProcedure } from "../../trpc";
const createVpnIntegrationMiddleware = () =>
createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("vpn"));
export const vpnRouter = createTRPCRouter({
getSummaries: publicProcedure.unstable_concat(createVpnIntegrationMiddleware()).query(async ({ ctx }) => {
return await Promise.all(
ctx.integrations.map(async (integration) => {
const innerHandler = vpnSummaryHandler.handler(integration, {});
const { data, timestamp } = await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
return {
integration: {
id: integration.id,
name: integration.name,
kind: integration.kind,
updatedAt: timestamp,
},
summary: data,
};
}),
);
}),
subscribeSummaries: publicProcedure.unstable_concat(createVpnIntegrationMiddleware()).subscription(({ ctx }) => {
return observable<{
integration: Modify<Integration, { kind: IntegrationKindByCategory<"vpn"> }>;
summary: VpnSummary | null;
}>((emit) => {
const unsubscribes: (() => void)[] = [];
for (const integrationWithSecrets of ctx.integrations) {
const { decryptedSecrets: _, ...integration } = integrationWithSecrets;
const innerHandler = vpnSummaryHandler.handler(integrationWithSecrets, {});
const unsubscribe = innerHandler.subscribe((summary) => {
emit.next({
integration,
summary,
});
});
unsubscribes.push(unsubscribe);
}
return () => {
unsubscribes.forEach((unsubscribe) => {
unsubscribe();
});
};
});
}),
});
+5 -19
View File
@@ -20,24 +20,6 @@ import { expireDateAfter, generateSessionToken, sessionTokenCookieName } from ".
const logger = createLogger({ module: "authConfiguration" });
// All Auth.js cookies are prefixed with AUTH_COOKIE_PREFIX (default "homarr") so
// Homarr's cookie jar is isolated from any other Auth.js/NextAuth app on the
// same hostname (browsers scope cookies by host, not by port).
// See https://github.com/homarr-labs/homarr/issues/5773
const createCookies = (useSecureCookies: boolean) => {
const prefix = env.AUTH_COOKIE_PREFIX;
const securePrefix = useSecureCookies ? "__Secure-" : "";
const hostPrefix = useSecureCookies ? "__Host-" : "";
return {
sessionToken: { name: sessionTokenCookieName },
csrfToken: { name: `${hostPrefix}${prefix}.csrf-token` },
callbackUrl: { name: `${securePrefix}${prefix}.callback-url` },
pkceCodeVerifier: { name: `${securePrefix}${prefix}.pkce.cooldown` },
state: { name: `${securePrefix}${prefix}.state` },
nonce: { name: `${securePrefix}${prefix}.nonce` },
};
};
// See why it's unknown in the [...nextauth]/route.ts file
export const createConfiguration = (
provider: SupportedAuthProvider | "unknown",
@@ -59,7 +41,11 @@ export const createConfiguration = (
},
},
trustHost: true,
cookies: createCookies(useSecureCookies),
cookies: {
sessionToken: {
name: sessionTokenCookieName,
},
},
adapter,
providers: filterProviders([
Credentials(createCredentialsConfiguration(db)),
-6
View File
@@ -28,11 +28,6 @@ export const env = createEnv({
AUTH_LOGOUT_REDIRECT_URL: z.string().url().optional(),
AUTH_SESSION_EXPIRY_TIME: createDurationSchema("30d"),
AUTH_PROVIDERS: authProvidersSchema,
AUTH_COOKIE_PREFIX: z
.string()
.min(1)
.regex(/^[a-zA-Z0-9-_]+$/, "AUTH_COOKIE_PREFIX must only contain letters, numbers, hyphens and underscores")
.default("homarr"),
...(authProviders.includes("oidc")
? {
AUTH_OIDC_ISSUER: z.string().url(),
@@ -42,7 +37,6 @@ export const env = createEnv({
AUTH_OIDC_AUTO_LOGIN: createBooleanSchema(false),
AUTH_OIDC_SCOPE_OVERWRITE: z.string().min(1).default("openid email profile groups"),
AUTH_OIDC_GROUPS_ATTRIBUTE: z.string().default("groups"), // Is used in the signIn event to assign the correct groups, key is from object of decoded id_token
AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT: createBooleanSchema(false), // When enabled, group memberships of oidc users are managed locally instead of synced from the groups claim
AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE: z.string().optional(),
AUTH_OIDC_FORCE_USERINFO: createBooleanSchema(false),
AUTH_OIDC_ENABLE_DANGEROUS_ACCOUNT_LINKING: createBooleanSchema(false),
+1 -6
View File
@@ -31,12 +31,7 @@ export const createSignInEventHandler = (db: Database): Exclude<NextAuthConfig["
const groupsKey = env.AUTH_OIDC_GROUPS_ATTRIBUTE;
// Groups from oidc provider are provided from the profile, it's not typed.
if (
!env.AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT &&
profile &&
groupsKey in profile &&
Array.isArray(profile[groupsKey])
) {
if (profile && groupsKey in profile && Array.isArray(profile[groupsKey])) {
logger.debug(`Using profile groups (${groupsKey}): ${JSON.stringify(profile[groupsKey])}`);
await synchronizeGroupsWithExternalForUserAsync(db, user.id, profile[groupsKey] as string[]);
}
-48
View File
@@ -1,57 +1,9 @@
import type { SupportedAuthProvider } from "@homarr/definitions";
import { supportedAuthProviders } from "@homarr/definitions";
import { env } from "../env";
export type GroupMemberManagementType = "local" | "mixed" | "external";
export const isProviderEnabled = (provider: SupportedAuthProvider) => {
// The question mark is placed there because isProviderEnabled is called during static build of about page
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
return env.AUTH_PROVIDERS?.includes(provider);
};
/**
* Whether a single provider's group memberships are managed locally (manually via UI/API).
* True for credentials users, and for oidc users when AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT is enabled.
*/
export const isGroupMembershipManagedLocally = (provider: SupportedAuthProvider): boolean => {
switch (provider) {
case "credentials":
return true;
case "oidc":
return env.AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT;
default:
// ldap + any provider added later: externally managed (synced, not editable
// here) until explicitly given a case above. New providers safe-by-default.
return false;
}
};
export const getEnabledProviders = (): SupportedAuthProvider[] => supportedAuthProviders.filter(isProviderEnabled);
/**
* The enabled providers whose group memberships can be managed locally.
*/
export const getLocallyManageableProviders = (): SupportedAuthProvider[] =>
getEnabledProviders().filter(isGroupMembershipManagedLocally);
/**
* Classifies group-member management across all enabled providers:
* - "local": every enabled provider is managed locally (no member is synced externally)
* - "external": no enabled provider is managed locally (every member is synced externally)
* - "mixed": some are managed locally, some externally (only a subset of members is editable here)
*/
export const getGroupMemberManagementType = (): GroupMemberManagementType => {
const enabled = getEnabledProviders();
const manageable = enabled.filter(isGroupMembershipManagedLocally);
if (manageable.length === enabled.length) return "local";
if (manageable.length === 0) return "external";
return "mixed";
};
/**
* Whether group memberships can be managed locally for at least one enabled provider.
*/
export const canManageGroupMembersLocally = (): boolean => getLocallyManageableProviders().length > 0;
@@ -1,105 +0,0 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import type { SupportedAuthProvider } from "@homarr/definitions";
import * as env from "../../env";
import {
canManageGroupMembersLocally,
getGroupMemberManagementType,
getLocallyManageableProviders,
isGroupMembershipManagedLocally,
} from "../check-provider";
const mockEnv = (providers: SupportedAuthProvider[], oidcLocalManagement = false) => {
vi.spyOn(env, "env", "get").mockReturnValue({
AUTH_PROVIDERS: providers,
AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT: oidcLocalManagement,
} as never);
};
beforeEach(() => {
vi.restoreAllMocks();
});
describe("isGroupMembershipManagedLocally", () => {
test("credentials is always managed locally", () => {
mockEnv(["credentials"]);
expect(isGroupMembershipManagedLocally("credentials")).toBe(true);
});
test("oidc follows AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT", () => {
mockEnv(["oidc"], true);
expect(isGroupMembershipManagedLocally("oidc")).toBe(true);
mockEnv(["oidc"], false);
expect(isGroupMembershipManagedLocally("oidc")).toBe(false);
});
test("ldap is never managed locally", () => {
mockEnv(["ldap"]);
expect(isGroupMembershipManagedLocally("ldap")).toBe(false);
});
});
describe("getGroupMemberManagementType", () => {
test("credentials only is local", () => {
mockEnv(["credentials"]);
expect(getGroupMemberManagementType()).toBe("local");
});
test("credentials + oidc with local management is local", () => {
mockEnv(["credentials", "oidc"], true);
expect(getGroupMemberManagementType()).toBe("local");
});
test("credentials + oidc without local management is mixed", () => {
mockEnv(["credentials", "oidc"], false);
expect(getGroupMemberManagementType()).toBe("mixed");
});
test("credentials + ldap is mixed", () => {
mockEnv(["credentials", "ldap"]);
expect(getGroupMemberManagementType()).toBe("mixed");
});
test("ldap only is external", () => {
mockEnv(["ldap"]);
expect(getGroupMemberManagementType()).toBe("external");
});
test("oidc only without local management is external", () => {
mockEnv(["oidc"], false);
expect(getGroupMemberManagementType()).toBe("external");
});
});
describe("getLocallyManageableProviders", () => {
test("returns only the enabled, locally managed providers", () => {
mockEnv(["credentials", "oidc", "ldap"], true);
expect(getLocallyManageableProviders()).toEqual(["credentials", "oidc"]);
mockEnv(["credentials", "oidc", "ldap"], false);
expect(getLocallyManageableProviders()).toEqual(["credentials"]);
mockEnv(["ldap"]);
expect(getLocallyManageableProviders()).toEqual([]);
});
});
describe("canManageGroupMembersLocally", () => {
test("is true when at least one enabled provider is managed locally", () => {
mockEnv(["credentials", "ldap"]);
expect(canManageGroupMembersLocally()).toBe(true);
mockEnv(["oidc"], true);
expect(canManageGroupMembersLocally()).toBe(true);
});
test("is false when every enabled provider is external", () => {
mockEnv(["ldap"]);
expect(canManageGroupMembersLocally()).toBe(false);
mockEnv(["oidc"], false);
expect(canManageGroupMembersLocally()).toBe(false);
});
});
+1 -8
View File
@@ -1,11 +1,4 @@
export { hasQueryAccessToIntegrationsAsync } from "./permissions/integration-query-permissions";
export { getIntegrationsWithPermissionsAsync } from "./permissions/integrations-with-permissions";
export {
isProviderEnabled,
isGroupMembershipManagedLocally,
getLocallyManageableProviders,
getGroupMemberManagementType,
canManageGroupMembersLocally,
} from "./providers/check-provider";
export type { GroupMemberManagementType } from "./providers/check-provider";
export { isProviderEnabled } from "./providers/check-provider";
export { createSessionCallback, createSessionAsync } from "./callbacks";
+2 -4
View File
@@ -4,11 +4,9 @@ import { generateSecureRandomToken } from "@homarr/common/server";
import type { Database } from "@homarr/db";
import { getCurrentUserPermissionsAsync } from "./callbacks";
import { env } from "./env";
// Prefixed (AUTH_COOKIE_PREFIX, default "homarr") to avoid cookie collisions
// with other Auth.js apps on the same host. See https://github.com/homarr-labs/homarr/issues/5773
export const sessionTokenCookieName = `${env.AUTH_COOKIE_PREFIX}.session-token`;
// Default of authjs
export const sessionTokenCookieName = "authjs.session-token";
export const expireDateAfter = (seconds: number) => {
return new Date(Date.now() + seconds * 1000);
+3 -29
View File
@@ -12,13 +12,11 @@ import { colorSchemeCookieKey, everyoneGroup } from "@homarr/definitions";
import { createSignInEventHandler } from "../events";
vi.mock("next-auth", () => ({}));
const mockEnv = vi.hoisted(() => ({
AUTH_OIDC_GROUPS_ATTRIBUTE: "someRandomGroupsKey",
AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT: false,
}));
vi.mock("../env", () => {
return {
env: mockEnv,
env: {
AUTH_OIDC_GROUPS_ATTRIBUTE: "someRandomGroupsKey",
},
};
});
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
@@ -200,30 +198,6 @@ describe("createSignInEventHandler should create signInEventHandler", () => {
});
expect(dbGroupMembers?.groupId).toBe("1");
});
test("should not synchronize groups when AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT is enabled", async () => {
// Arrange
mockEnv.AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT = true;
const db = createDb();
await createUserAsync(db);
await createGroupAsync(db);
const eventHandler = createSignInEventHandler(db);
// Act
await eventHandler?.({
user: { id: "1", name: "test" },
profile: { preferred_username: "test", someRandomGroupsKey: ["test"] },
account: null,
});
// Assert
const dbGroupMembers = await db.query.groupMembers.findFirst({
where: eq(groupMembers.userId, "1"),
});
expect(dbGroupMembers).toBeUndefined();
// Cleanup
mockEnv.AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT = false;
});
});
test.each([
["ldap" as const, { name: "test-new" }, undefined],
-2
View File
@@ -20,7 +20,6 @@ interface CreateCronJobOptions {
runOnStart?: boolean;
preventManualExecution?: boolean;
preventCustomInterval?: boolean;
hidden?: boolean;
expectedMaximumDurationInMillis?: number;
beforeStart?: () => MaybePromise<void>;
}
@@ -122,7 +121,6 @@ const createCallback = <TAllowedNames extends string, TName extends TAllowedName
},
preventManualExecution: options.preventManualExecution ?? false,
preventCustomInterval: options.preventCustomInterval ?? false,
hidden: options.hidden ?? false,
timezone: creatorOptions.timezone,
};
};
-2
View File
@@ -21,7 +21,6 @@ import { refreshNotificationsJob } from "./jobs/integrations/notifications";
import { timetableJob } from "./jobs/integrations/timetable";
import { tracearrJob } from "./jobs/integrations/tracearr";
import { umamiActiveVisitorsJob } from "./jobs/integrations/umami";
import { vpnJob } from "./jobs/integrations/vpn";
import { minecraftServerStatusJob } from "./jobs/minecraft-server-status";
import { pingJob } from "./jobs/ping";
import { rssFeedsJob } from "./jobs/rss-feeds";
@@ -58,7 +57,6 @@ const getJobGroup = () => {
timetable: timetableJob,
tracearr: tracearrJob,
umamiActiveVisitors: umamiActiveVisitorsJob,
vpn: vpnJob,
});
};
+10 -12
View File
@@ -122,17 +122,15 @@ export class JobManager {
> {
const configurations = await this.db.query.cronJobConfigurations.findMany();
return [...this.jobGroup.getJobRegistry().entries()]
.filter(([_, job]) => !job.hidden)
.map(([name, job]) => {
const config = configurations.find((config) => config.name === name);
return {
name,
cron: config?.cronExpression ?? job.cronExpression,
preventManualExecution: job.preventManualExecution,
preventCustomInterval: job.preventCustomInterval,
isEnabled: config?.isEnabled ?? true,
};
});
return [...this.jobGroup.getJobRegistry().entries()].map(([name, job]) => {
const config = configurations.find((config) => config.name === name);
return {
name,
cron: config?.cronExpression ?? job.cronExpression,
preventManualExecution: job.preventManualExecution,
preventCustomInterval: job.preventCustomInterval,
isEnabled: config?.isEnabled ?? true,
};
});
}
}
+8 -1
View File
@@ -1,6 +1,8 @@
import { sendServerAnalyticsAsync } from "@homarr/analytics";
import { env } from "@homarr/common/env";
import { EVERY_WEEK } from "@homarr/cron-jobs-core/expressions";
import { db } from "@homarr/db";
import { getServerSettingByKeyAsync } from "@homarr/db/queries";
import { createCronJob } from "../lib";
@@ -8,8 +10,13 @@ export const analyticsJob = createCronJob("analytics", EVERY_WEEK, {
runOnStart: true,
preventManualExecution: true,
preventCustomInterval: true,
hidden: true,
}).withCallback(async () => {
if (env.NO_EXTERNAL_CONNECTION) return;
const analyticSetting = await getServerSettingByKeyAsync(db, "analytics");
if (!analyticSetting.enableGeneral) {
return;
}
await sendServerAnalyticsAsync();
});
@@ -1,14 +0,0 @@
import { EVERY_30_SECONDS } from "@homarr/cron-jobs-core/expressions";
import { vpnSummaryHandler } from "@homarr/request-handler/vpn";
import { createRequestIntegrationJobHandler } from "@homarr/request-handler/lib/cached-request-integration-job-handler";
import { createCronJob } from "../../lib";
export const vpnJob = createCronJob("vpn", EVERY_30_SECONDS).withCallback(
createRequestIntegrationJobHandler(vpnSummaryHandler.handler, {
widgetKinds: ["vpn"],
getInput: {
vpn: () => ({}),
},
}),
);
+14 -10
View File
@@ -647,13 +647,9 @@ const seedDemoUserAsync = async (db: Database) => {
const seedDefaultCustomWidgetsAsync = async (db: Database) => {
const seedIds = CUSTOM_WIDGET_SEEDS.map((s) => s.id);
const existing = await db.query.customWidgetDefinitions.findMany({
columns: { id: true },
where: inArray(customWidgetDefinitions.id, seedIds),
});
const existingIds = new Set(existing.map((row) => row.id));
const beforeCount = await db.$count(customWidgetDefinitions, inArray(customWidgetDefinitions.id, seedIds));
const seedValues = CUSTOM_WIDGET_SEEDS.filter((seed) => !existingIds.has(seed.id)).map((seed) => {
const seedValues = CUSTOM_WIDGET_SEEDS.map((seed) => {
const parsed = customWidgetImportSchema.parse(seed.data);
return {
id: seed.id,
@@ -672,14 +668,22 @@ const seedDefaultCustomWidgetsAsync = async (db: Database) => {
};
});
if (seedValues.length === 0) {
if (seedValues.length === 0) return;
await db
.insert(customWidgetDefinitions)
.values(seedValues)
.onConflictDoNothing({ target: customWidgetDefinitions.id });
const afterCount = await db.$count(customWidgetDefinitions, inArray(customWidgetDefinitions.id, seedIds));
const createdCount = afterCount - beforeCount;
if (createdCount === 0) {
console.log("Skipping seeding of default custom widgets as they already exist");
return;
}
await db.insert(customWidgetDefinitions).values(seedValues);
console.log(`Created ${seedValues.length} default custom widgets through seeding process`);
console.log(`Created ${createdCount} default custom widgets through seeding process`);
};
const seedBoardWidgetsAsync = async (db: Database) => {
@@ -98,6 +98,7 @@ export type HomarrDocumentationPath =
| "/docs/tags/puid"
| "/docs/tags/redis"
| "/docs/tags/responsive"
| "/docs/tags/restore"
| "/docs/tags/roles"
| "/docs/tags/search-engines"
| "/docs/tags/search"
@@ -179,8 +180,6 @@ export type HomarrDocumentationPath =
| "/docs/integrations/github"
| "/docs/integrations/gitlab"
| "/docs/integrations/glances"
| "/docs/integrations/gluetun"
| "/docs/integrations/gotify"
| "/docs/integrations/home-assistant"
| "/docs/integrations/ical"
| "/docs/integrations/immich"
@@ -234,6 +233,7 @@ export type HomarrDocumentationPath =
| "/docs/management/search-engines"
| "/docs/management/settings"
| "/docs/management/tasks"
| "/docs/management/tools/backup"
| "/docs/management/users"
| "/docs/widgets/anchor-note"
| "/docs/widgets/app"
@@ -281,7 +281,6 @@ export type HomarrDocumentationPath =
| "/docs/widgets/ups"
| "/docs/widgets/uptime-kuma"
| "/docs/widgets/video"
| "/docs/widgets/vpn"
| "/docs/widgets/weather"
| ""
| "/sitemap.xml"
@@ -324,7 +323,6 @@ export type HomarrDocumentationPath =
| "/docs/integrations/github-containerregistry"
| "/docs/integrations/quay"
| "/docs/integrations/ntfy"
| "/docs/integrations/gotify"
| "/docs/integrations/ical"
| "/docs/integrations/anchor"
| "/docs/integrations/truenas"
@@ -339,7 +337,6 @@ export type HomarrDocumentationPath =
| "/docs/integrations/audiobookshelf"
| "/docs/integrations/navidrome"
| "/docs/integrations/umami"
| "/docs/integrations/gluetun"
| "/docs/integrations/peanut"
| "/docs/integrations/beszel"
| "/docs/widgets/clock"
@@ -383,7 +380,6 @@ export type HomarrDocumentationPath =
| "/docs/widgets/uptime-kuma"
| "/docs/widgets/audio-stats"
| "/docs/widgets/umami"
| "/docs/widgets/vpn"
| "/docs/widgets/ups"
| "/docs/widgets/beszel-system-table"
| "/docs/widgets/beszel-system-grid"
@@ -40,7 +40,6 @@ export const integrationDocSlugs: Record<IntegrationKind, string | null> = {
gitHubContainerRegistry: "github-containerregistry",
quay: "quay",
ntfy: "ntfy",
gotify: "gotify",
ical: "ical",
anchor: "anchor",
truenas: "truenas",
@@ -55,9 +54,7 @@ export const integrationDocSlugs: Record<IntegrationKind, string | null> = {
audiobookshelf: "audiobookshelf",
navidrome: "navidrome",
umami: "umami",
gluetun: "gluetun",
peaNut: "peanut",
beszel: "beszel",
archiveTeamWarrior: null,
mock: null,
};
@@ -43,9 +43,7 @@ export const widgetDocSlugs: Record<WidgetKind, string | null> = {
uptimeKuma: "uptime-kuma",
audioStats: "audio-stats",
umami: "umami",
vpn: "vpn",
ups: "ups",
archiveTeamWarrior: null,
beszelSystemTable: "beszel-system-table",
beszelSystemGrid: "beszel-system-grid",
beszelAlerts: "beszel-alerts",
-24
View File
@@ -355,13 +355,6 @@ export const integrationDefs = {
documentationUrl: createDocumentationLink("/docs/integrations/ntfy"),
defaultPort: 80,
},
gotify: {
name: "Gotify",
secretKinds: [["username", "password"]],
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/gotify.svg",
category: ["notifications"],
documentationUrl: createDocumentationLink("/docs/integrations/gotify"),
},
ical: {
name: "iCal",
secretKinds: [["url"]],
@@ -489,21 +482,6 @@ export const integrationDefs = {
documentationUrl: createDocumentationLink("/docs/integrations/beszel"),
defaultPort: 8090,
},
gluetun: {
name: "Gluetun",
secretKinds: [["username", "password"], ["apiKey"], []],
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/gluetun.svg",
category: ["vpn"],
documentationUrl: createDocumentationLink("/docs/integrations/gluetun"),
},
archiveTeamWarrior: {
name: "ArchiveTeam Warrior",
secretKinds: [[], ["username", "password"]],
iconUrl: "https://cdn.jsdelivr.net/gh/selfhst/icons/png/archiveteam-warrior.png",
category: ["archiving"],
defaultUrl: "http://localhost:8001",
documentationUrl: null,
},
// This integration only returns mock data, it is used during development (but can also be used in production by directly going to the create page)
mock: {
name: "Mock",
@@ -611,8 +589,6 @@ export const integrationCategories = [
"mediaMonitoring",
"speedtest",
"analytics",
"vpn",
"archiving",
"ups",
"documents",
"mediaLibrary",
@@ -38,7 +38,6 @@ export const widgetIntegrationSupport: Partial<Record<WidgetKind, readonly Integ
speedtestTracker: ["speedtestTracker"],
uptimeKuma: ["uptimeKuma"],
audioStats: ["navidrome", "audiobookshelf"],
vpn: getIntegrationKindsByCategory("vpn"),
anchorNote: ["anchor"],
};
-2
View File
@@ -41,8 +41,6 @@ export const widgetKinds = [
"uptimeKuma",
"audioStats",
"umami",
"vpn",
"archiveTeamWarrior",
"ups",
"beszelSystemTable",
"beszelSystemGrid",
@@ -1,11 +1,8 @@
"use client";
import type { FocusEventHandler } from "react";
import { startTransition, useEffect, useState } from "react";
import { startTransition } from "react";
import {
ActionIcon,
Box,
Button,
Card,
Combobox,
Flex,
@@ -21,7 +18,7 @@ import {
useCombobox,
} from "@mantine/core";
import { useDebouncedValue, useUncontrolled } from "@mantine/hooks";
import { IconMoodEmpty, IconSearchOff, IconUpload } from "@tabler/icons-react";
import { IconUpload } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client";
@@ -37,6 +34,7 @@ interface IconPickerProps {
error?: string | null;
onFocus?: FocusEventHandler;
onBlur?: FocusEventHandler;
label?: string;
placeholder?: string;
withAsterisk?: boolean;
@@ -52,30 +50,29 @@ export const IconPicker = ({
label,
placeholder,
}: IconPickerProps) => {
const [value, setValue] = useUncontrolled({ value: propsValue, onChange });
const [query, setQuery] = useState("");
// ponytail: reset the typed query when the committed value changes
// externally (form reset, parent re-render) so the input reverts to the URL.
useEffect(() => {
setQuery("");
}, [value]);
const [value, setValue] = useUncontrolled({
value: propsValue,
onChange,
});
const [search, setSearch] = useUncontrolled({
value,
onChange: (value) => {
setValue(value);
},
});
const [previewUrl, setPreviewUrl] = useUncontrolled({
value: propsValue ?? null,
});
const { data: session } = useSession();
const tCommon = useScopedI18n("common");
const [debouncedQuery] = useDebouncedValue(query, 100);
// ponytail: only search when the typed query differs from the committed
// value. On mount the input shows the existing URL (edit mode), which
// would never match the bare filenames in the icon table.
const searchText = (debouncedQuery !== (value ?? "") && debouncedQuery) || "";
const [debouncedSearch] = useDebouncedValue(search, 100);
// ponytail: not useSuspenseQuery — an above Suspense boundary would
// trigger on every keystroke and the dropdown flash is bad UX.
const { data, isLoading, isError, refetch } = clientApi.icon.findIcons.useQuery(
{ searchText },
{ placeholderData: (prev) => prev },
);
// We use not useSuspenseQuery as it would cause an above Suspense boundary to trigger and so searching for something is bad UX.
const { data } = clientApi.icon.findIcons.useQuery({
searchText: debouncedSearch,
});
const combobox = useCombobox({
onDropdownClose: () => combobox.resetSelectedOption(),
@@ -93,15 +90,25 @@ export const IconPicker = ({
>
<UnstyledButton
onClick={() => {
const value = item.url;
startTransition(() => {
setValue(item.url);
setQuery("");
setPreviewUrl(value);
setSearch(value);
setValue(value);
combobox.closeDropdown();
});
}}
>
<Indicator label="SVG" disabled={!item.url.endsWith(".svg")} size={16}>
<Card p="sm" pos="relative" style={{ overflow: "visible", cursor: "pointer" }} className={classes.iconCard}>
<Card
p="sm"
pos="relative"
style={{
overflow: "visible",
cursor: "pointer",
}}
className={classes.iconCard}
>
<Box w={25} h={25}>
<Image src={item.url} w={25} h={25} />
</Box>
@@ -123,48 +130,6 @@ export const IconPicker = ({
);
});
// ponytail: show the typed query if non-empty, else fall back to the URL.
const inputValue = query || value || "";
// ponytail: show the existing icon as a left-section preview.
const leftSection = shouldShowPreview(value) && <img src={value} alt="" style={{ width: 20, height: 20 }} />;
// ponytail: prop override -> real count -> loading text.
const placeholderText =
placeholder ||
(data && tCommon("iconPicker.header", { countIcons: String(data.countIcons) })) ||
tCommon("iconPicker.headerLoading");
const renderDropdown = () => {
if (isError) {
return (
<Stack align="center" gap="xs" p="md">
<IconSearchOff size={32} stroke={1.5} />
<Text size="sm">{tCommon("iconPicker.error")}</Text>
<Button size="xs" variant="default" onClick={() => refetch()}>
{tCommon("action.tryAgain")}
</Button>
</Stack>
);
}
if (isLoading) {
return Array(15)
.fill(0)
.map((_, index) => (
<Combobox.Option value={`skeleton-${index}`} key={index} disabled>
<Skeleton height={25} visible />
</Combobox.Option>
));
}
if (totalOptions > 0) {
return <Stack gap={4}>{groups}</Stack>;
}
return (
<Stack align="center" gap="xs" p="md">
<IconMoodEmpty size={32} stroke={1.5} />
<Text size="sm">{tCommon("iconPicker.noResults", { search: debouncedQuery })}</Text>
</Stack>
);
};
return (
<Combobox store={combobox} withinPortal>
<Combobox.Target>
@@ -172,11 +137,16 @@ export const IconPicker = ({
<InputBase
flex={1}
rightSection={<Combobox.Chevron />}
leftSection={leftSection}
value={inputValue}
leftSection={
shouldShowPreview(previewUrl) ? <img src={previewUrl} alt="" style={{ width: 20, height: 20 }} /> : null
}
value={search}
onChange={(event) => {
combobox.openDropdown();
setQuery(event.currentTarget.value);
combobox.updateSelectedOptionIndex();
setSearch(event.currentTarget.value);
setValue(event.currentTarget.value);
setPreviewUrl(null);
}}
onClick={() => combobox.openDropdown()}
onFocus={(event) => {
@@ -186,21 +156,25 @@ export const IconPicker = ({
onBlur={(event) => {
onBlur?.(event);
combobox.closeDropdown();
setQuery("");
setPreviewUrl(value);
setSearch(value || "");
}}
rightSectionPointerEvents="none"
withAsterisk={withAsterisk}
error={error}
label={label ?? tCommon("iconPicker.label")}
placeholder={placeholderText}
placeholder={placeholder ?? tCommon("iconPicker.header", { countIcons: String(data?.countIcons ?? 0) })}
/>
{session?.user.permissions.includes("media-upload") && (
<UploadMedia
onSuccess={(medias) => {
const first = medias.at(0);
if (!first) return;
startTransition(() => {
setValue(first.url);
setPreviewUrl(first.url);
setSearch(first.url);
});
}}
>
@@ -216,7 +190,17 @@ export const IconPicker = ({
<Combobox.Dropdown>
<Combobox.Options mah={350} style={{ overflowY: "auto" }}>
{renderDropdown()}
{totalOptions > 0 ? (
<Stack gap={4}>{groups}</Stack>
) : (
Array(15)
.fill(0)
.map((_, index: number) => (
<Combobox.Option value={`skeleton-${index}`} key={index} disabled>
<Skeleton height={25} visible />
</Combobox.Option>
))
)}
</Combobox.Options>
</Combobox.Dropdown>
</Combobox>
@@ -225,8 +209,8 @@ export const IconPicker = ({
// This regex is used to prevent loading a preview like en or /en which would trigger a language change
// See https://github.com/homarr-labs/homarr/issues/3070
const localizationPathRegex = new RegExp(`^/?(${supportedLanguages.join("|")})(/.*)?$`, "i");
const shouldShowPreview = (value: string | null | undefined): value is string => {
const localizationPathRegex = new RegExp(`^/?(${supportedLanguages.join("|")})(/.*)?$`, "i" /* ignore casing */);
const shouldShowPreview = (value: string | null): value is string => {
if (!value) return false;
return !localizationPathRegex.test(value);
};
@@ -1,386 +0,0 @@
import { Buffer } from "node:buffer";
import { randomUUID } from "node:crypto";
import WebSocket from "ws";
import type { RawData } from "ws";
import { z } from "zod/v4";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
import type { IntegrationTestingInput } from "../base/integration";
import { Integration } from "../base/integration";
import { TestConnectionError } from "../base/test-connection/test-connection-error";
import type { TestingResult } from "../base/test-connection/test-connection-service";
import {
bandwidthMessageSchema,
itemStatusMessageSchema,
pipelineStartItemMessageSchema,
projectRefreshMessageSchema,
seesawFrameSchema,
warriorBroadcastMessageSchema,
warriorProjectSelectedMessageSchema,
warriorStatusMessageSchema,
} from "./archive-team-warrior-schemas";
import type { SeesawFrame, WarriorItem, WarriorProject } from "./archive-team-warrior-schemas";
import type { ArchiveTeamWarriorItem, ArchiveTeamWarriorStatus } from "./archive-team-warrior-types";
const SOCKJS_SNAPSHOT_TIMEOUT_MS = 2500;
interface WarriorSnapshotState {
status: string;
runnerStatus?: string;
selectedProject: string | null;
broadcastMessage: string | null;
project: ArchiveTeamWarriorStatus["project"];
bandwidth: ArchiveTeamWarriorStatus["bandwidth"];
items: Map<string, ArchiveTeamWarriorItem>;
}
export class ArchiveTeamWarriorIntegration extends Integration {
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
const response = await input.fetchAsync(this.url("/index.html"), {
headers: this.createAuthHeaders(),
});
if (!response.ok) return TestConnectionError.StatusResult(response);
return { success: true };
}
public async getStatusAsync(): Promise<ArchiveTeamWarriorStatus> {
const baseUrl = this.url("/").toString().replace(/\/$/, "");
await fetchWithTrustedCertificatesAsync(`${baseUrl}/index.html`, {
headers: this.createAuthHeaders(),
});
return await this.readSockJsSnapshotAsync(baseUrl);
}
private async readSockJsSnapshotAsync(baseUrl: string): Promise<ArchiveTeamWarriorStatus> {
const snapshot: WarriorSnapshotState = {
status: "Unknown",
selectedProject: null,
broadcastMessage: null,
project: null,
bandwidth: null,
items: new Map<string, ArchiveTeamWarriorItem>(),
};
await new Promise<void>((resolve, reject) => {
let isSettled = false;
const socket = new WebSocket(this.createSockJsWebSocketUrl(baseUrl), {
headers: this.createAuthHeaders(),
});
const finish = () => {
if (isSettled) return;
isSettled = true;
clearTimeout(timeout);
if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) {
socket.close();
}
resolve();
};
const fail = () => {
if (isSettled) return;
isSettled = true;
clearTimeout(timeout);
reject(new Error("Failed to connect to ArchiveTeam Warrior websocket"));
};
const timeout = setTimeout(finish, SOCKJS_SNAPSHOT_TIMEOUT_MS);
socket.on("message", (data: RawData) => {
const frames = this.parseSockJsMessage(this.decodeWebSocketData(data));
for (const frame of frames) {
this.applyFrameToSnapshot(frame, snapshot);
}
});
socket.on("error", fail);
socket.on("close", finish);
});
return this.createStatusFromSnapshot(snapshot);
}
private applyFrameToSnapshot(frame: SeesawFrame, snapshot: WarriorSnapshotState) {
switch (frame.event_name) {
case "warrior.status":
this.applyWarriorStatusFrame(frame, snapshot);
break;
case "warrior.project_selected":
this.applyProjectSelectedFrame(frame, snapshot);
break;
case "warrior.broadcast_message":
this.applyBroadcastMessageFrame(frame, snapshot);
break;
case "runner.status":
this.applyRunnerStatusFrame(frame, snapshot);
break;
case "project.refresh":
this.applyProjectRefreshFrame(frame, snapshot);
break;
case "pipeline.start_item":
this.applyPipelineStartItemFrame(frame, snapshot);
break;
case "item.complete":
this.applyItemStatusFrame(frame, snapshot, "completed");
break;
case "item.fail":
this.applyItemStatusFrame(frame, snapshot, "failed");
break;
case "item.cancel":
this.applyItemStatusFrame(frame, snapshot, "canceled");
break;
case "bandwidth":
this.applyBandwidthFrame(frame, snapshot);
break;
}
}
private applyWarriorStatusFrame(frame: SeesawFrame, snapshot: WarriorSnapshotState) {
const message = warriorStatusMessageSchema.safeParse(frame.message);
if (!message.success) return;
snapshot.status = this.normalizeDisplayStatus(message.data.status);
}
private applyProjectSelectedFrame(frame: SeesawFrame, snapshot: WarriorSnapshotState) {
const message = warriorProjectSelectedMessageSchema.safeParse(frame.message);
if (!message.success) return;
snapshot.selectedProject = message.data.project;
}
private applyBroadcastMessageFrame(frame: SeesawFrame, snapshot: WarriorSnapshotState) {
const message = warriorBroadcastMessageSchema.safeParse(frame.message);
if (!message.success) return;
snapshot.broadcastMessage = message.data.message;
}
private applyRunnerStatusFrame(frame: SeesawFrame, snapshot: WarriorSnapshotState) {
const message = warriorStatusMessageSchema.safeParse(frame.message);
if (!message.success) return;
snapshot.runnerStatus = this.normalizeDisplayStatus(message.data.status);
}
private applyProjectRefreshFrame(frame: SeesawFrame, snapshot: WarriorSnapshotState) {
const message = projectRefreshMessageSchema.safeParse(frame.message);
if (!message.success) return;
snapshot.project = this.mapProject(message.data?.project);
snapshot.runnerStatus = message.data?.status
? this.normalizeDisplayStatus(message.data.status)
: snapshot.runnerStatus;
for (const item of message.data?.items ?? []) {
snapshot.items.set(item.id, this.mapItem(item));
}
}
private applyPipelineStartItemFrame(frame: SeesawFrame, snapshot: WarriorSnapshotState) {
const message = pipelineStartItemMessageSchema.safeParse(frame.message);
if (!message.success) return;
snapshot.items.set(message.data.item.id, this.mapItem(message.data.item));
}
private applyItemStatusFrame(
frame: SeesawFrame,
snapshot: WarriorSnapshotState,
status: ArchiveTeamWarriorItem["status"],
) {
const message = itemStatusMessageSchema.safeParse(frame.message);
if (!message.success) return;
this.updateItemStatus(snapshot.items, message.data.item_id, status);
}
private applyBandwidthFrame(frame: SeesawFrame, snapshot: WarriorSnapshotState) {
const message = bandwidthMessageSchema.safeParse(frame.message);
if (!message.success) return;
snapshot.bandwidth = message.data;
}
private createStatusFromSnapshot(snapshot: WarriorSnapshotState): ArchiveTeamWarriorStatus {
const itemList = Array.from(snapshot.items.values());
return {
status: snapshot.status,
runnerStatus: snapshot.runnerStatus,
project: snapshot.project,
selectedProject: snapshot.selectedProject,
broadcastMessage: snapshot.broadcastMessage,
bandwidth: snapshot.bandwidth,
items: itemList,
counts: {
running: itemList.filter((item) => item.status === "running").length,
completed: itemList.filter((item) => item.status === "completed").length,
failed: itemList.filter((item) => item.status === "failed").length,
canceled: itemList.filter((item) => item.status === "canceled").length,
},
updatedAt: new Date().toISOString(),
};
}
private createAuthHeaders() {
const authorization = this.createBasicAuthHeader();
return authorization ? { Authorization: authorization } : undefined;
}
private createBasicAuthHeader() {
if (!this.hasSecretValue("username") || !this.hasSecretValue("password")) return undefined;
const username = this.getSecretValue("username");
const password = this.getSecretValue("password");
const credentials = Buffer.from(`${username}:${password}`, "utf8").toString("base64");
return `Basic ${credentials}`;
}
private decodeWebSocketData(data: RawData) {
if (typeof data === "string") return data;
if (Buffer.isBuffer(data)) return data.toString("utf8");
if (Array.isArray(data)) return Buffer.concat(data).toString("utf8");
return Buffer.from(data).toString("utf8");
}
private parseSockJsMessage(raw: string): SeesawFrame[] {
if (raw === "o" || raw === "h" || raw.length === 0) return [];
if (!raw.startsWith("a")) return [];
const rawPayload = this.parseJsonSafely(raw.slice(1));
const payload = z.array(z.string()).safeParse(rawPayload);
if (!payload.success) return [];
return payload.data.flatMap((frame) => {
const rawFrame = this.parseJsonSafely(frame);
const result = seesawFrameSchema.safeParse(rawFrame);
return result.success ? [result.data] : [];
});
}
private parseJsonSafely(value: string) {
try {
return JSON.parse(value) as unknown;
} catch {
return null;
}
}
private createSockJsWebSocketUrl(baseUrl: string) {
const url = new URL(baseUrl);
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
url.pathname = `/${Date.now()}/${randomUUID()}/websocket`;
return url.toString();
}
private mapProject(project?: WarriorProject): ArchiveTeamWarriorStatus["project"] {
if (!project) return null;
return {
id: project.project_id?.toString(),
title: project.title ?? "Unknown Project",
};
}
private mapItem(item: WarriorItem): ArchiveTeamWarriorItem {
return {
id: item.id,
name: this.formatItemName(item.name),
status: this.normalizeItemStatus(item.status),
project: item.project,
startTime: item.start_time,
};
}
private normalizeDisplayStatus(status?: string | null) {
if (!status) return "Unknown";
switch (status) {
case "RUNNING_PROJECT":
return "Running";
case "STOPPED":
return "Stopped";
case "IDLE":
return "Idle";
default:
return status
.replaceAll("_", " ")
.toLowerCase()
.replace(/\b\w/g, (character) => character.toUpperCase());
}
}
private formatItemName(name: string) {
const cleaned = name.replace(/^Item\s+/i, "");
const parts = cleaned.split("\u0000").filter(Boolean);
if (parts.length === 0) return "Item";
const first = parts[0];
if (!first) return "Item";
const label = parts.length === 1 ? first : `${first} + ${parts.length - 1} more`;
return label.length <= 80 ? label : `${label.slice(0, 77)}...`;
}
private normalizeItemStatus(status?: string | null): ArchiveTeamWarriorItem["status"] {
if (!status) return "running";
switch (status.toLowerCase()) {
case "running":
case "running_project":
return "running";
case "completed":
return "completed";
case "failed":
case "fail":
return "failed";
case "canceled":
case "cancel":
return "canceled";
default:
return "unknown";
}
}
private updateItemStatus(
items: Map<string, ArchiveTeamWarriorItem>,
itemId: string,
status: ArchiveTeamWarriorItem["status"],
) {
const item = items.get(itemId);
if (!item) return;
items.set(itemId, {
...item,
status,
});
}
}
@@ -1,61 +0,0 @@
import { z } from "zod/v4";
export const seesawFrameSchema = z.object({
event_name: z.string(),
message: z.unknown(),
});
export const warriorStatusMessageSchema = z.object({
status: z.string(),
});
export const warriorBroadcastMessageSchema = z.object({
message: z.string().nullable(),
});
export const warriorProjectSelectedMessageSchema = z.object({
project: z.string().nullable(),
});
export const warriorProjectSchema = z.object({
project_id: z.number().optional(),
title: z.string().optional(),
project_html: z.string().optional(),
utc_deadline: z.string().nullable().optional(),
});
export const warriorItemSchema = z.object({
id: z.string(),
name: z.string(),
status: z.string().nullable().optional(),
project: z.string().nullable().optional(),
start_time: z.number().optional(),
});
export const projectRefreshMessageSchema = z
.object({
project: warriorProjectSchema.optional(),
status: z.string().optional(),
items: z.array(warriorItemSchema).optional(),
})
.nullable();
export const itemStatusMessageSchema = z.object({
item_id: z.string(),
});
export const pipelineStartItemMessageSchema = z.object({
item: warriorItemSchema,
});
export const bandwidthMessageSchema = z.object({
received: z.number().optional(),
sent: z.number().optional(),
receiving: z.number().optional(),
sending: z.number().optional(),
session_id: z.string().optional(),
});
export type WarriorProject = z.infer<typeof warriorProjectSchema>;
export type WarriorItem = z.infer<typeof warriorItemSchema>;
export type SeesawFrame = z.infer<typeof seesawFrameSchema>;
@@ -1,37 +0,0 @@
export interface ArchiveTeamWarriorItem {
id: string;
name: string;
status: "running" | "completed" | "failed" | "canceled" | "unknown";
project?: string | null;
startTime?: number;
}
export interface ArchiveTeamWarriorBandwidth {
received?: number;
sent?: number;
receiving?: number;
sending?: number;
session_id?: string;
}
export interface ArchiveTeamWarriorProject {
id?: string;
title: string;
}
export interface ArchiveTeamWarriorStatus {
status: string;
runnerStatus?: string;
project?: ArchiveTeamWarriorProject | null;
selectedProject?: string | null;
broadcastMessage?: string | null;
bandwidth?: ArchiveTeamWarriorBandwidth | null;
items: ArchiveTeamWarriorItem[];
counts: {
running: number;
completed: number;
failed: number;
canceled: number;
};
updatedAt: string;
}
@@ -3,7 +3,6 @@ import type { IntegrationKind } from "@homarr/definitions";
import { AdGuardHomeIntegration } from "../adguard-home/adguard-home-integration";
import { BeszelIntegration } from "../beszel/beszel-integration";
import { AnchorIntegration } from "../anchor/anchor-integration";
import { ArchiveTeamWarriorIntegration } from "../archive-team-warrior/archive-team-warrior-integration";
import { AudiobookshelfIntegration } from "../audiobookshelf/audiobookshelf-integration";
import { CodebergIntegration } from "../codeberg/codeberg-integration";
import { CoolifyIntegration } from "../coolify/coolify-integration";
@@ -21,7 +20,6 @@ import { GitHubContainerRegistryIntegration } from "../github-container-registry
import { GithubIntegration } from "../github/github-integration";
import { GitlabIntegration } from "../gitlab/gitlab-integration";
import { GlancesIntegration } from "../glances/glances-integration";
import { GluetunIntegration } from "../gluetun/gluetun-integration";
import { HomeAssistantIntegration } from "../homeassistant/homeassistant-integration";
import { ICalIntegration } from "../ical/ical-integration";
import { ImmichIntegration } from "../immich/immich-integration";
@@ -37,7 +35,6 @@ import { MockIntegration } from "../mock/mock-integration";
import { NavidromeIntegration } from "../navidrome/navidrome-integration";
import { NextcloudIntegration } from "../nextcloud/nextcloud.integration";
import { NPMIntegration } from "../npm/npm-integration";
import { GotifyIntegration } from "../gotify/gotify-integration";
import { NTFYIntegration } from "../ntfy/ntfy-integration";
import { OpenMediaVaultIntegration } from "../openmediavault/openmediavault-integration";
import { OPNsenseIntegration } from "../opnsense/opnsense-integration";
@@ -124,7 +121,6 @@ export const integrationCreators = {
ical: ICalIntegration,
quay: QuayIntegration,
ntfy: NTFYIntegration,
gotify: GotifyIntegration,
mock: MockIntegration,
truenas: TrueNasIntegration,
unraid: UnraidIntegration,
@@ -138,8 +134,6 @@ export const integrationCreators = {
audiobookshelf: AudiobookshelfIntegration,
navidrome: NavidromeIntegration,
umami: UmamiIntegration,
gluetun: GluetunIntegration,
archiveTeamWarrior: ArchiveTeamWarriorIntegration,
uptimeKuma: UptimeKumaIntegration,
peaNut: PeaNutIntegration,
beszel: BeszelIntegration,
@@ -1,5 +1,4 @@
import { ResponseError } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
import type { IntegrationInput, IntegrationTestingInput } from "../base/integration";
@@ -13,21 +12,17 @@ import type {
BeszelAlertHistory,
BeszelAuthResponse,
BeszelContainer,
BeszelContainerStats,
BeszelContainerStatsRecord,
BeszelSmartDevice,
BeszelSystem,
BeszelSystemDetails,
BeszelSystemdService,
BeszelSystemStats,
BeszelSystemStatsRecord,
CreateAlertInput,
PocketBaseListResponse,
UpdateAlertInput,
} from "./beszel-types";
const logger = createLogger({ module: "beszel-integration" });
const escapeFilterValue = (value: string) => value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
interface BeszelSession {
@@ -46,13 +41,10 @@ export class BeszelIntegration extends Integration {
private async authenticateAsync(): Promise<BeszelSession> {
const existingSession = await this.sessionStore.getAsync();
if (existingSession) {
logger.debug("Using stored Beszel session", { integrationId: this.integration.id });
return existingSession;
}
const authUrl = this.url("/api/collections/users/auth-with-password");
logger.debug("Authenticating with Beszel", { integrationId: this.integration.id, url: authUrl.pathname });
const response = await fetchWithTrustedCertificatesAsync(authUrl, {
const response = await fetchWithTrustedCertificatesAsync(this.url("/api/collections/users/auth-with-password"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
@@ -60,28 +52,23 @@ export class BeszelIntegration extends Integration {
password: this.getSecretValue("password"),
}),
});
logger.debug("Beszel auth response received", { integrationId: this.integration.id, status: response.status });
if (!response.ok) {
logger.warn("Beszel auth failed", { integrationId: this.integration.id, status: response.status });
throw new ResponseError(response);
}
const data = (await response.json()) as BeszelAuthResponse;
const session: BeszelSession = { token: data.token, userId: data.record.id };
await this.sessionStore.setAsync(session);
logger.debug("Saved Beszel session", { integrationId: this.integration.id, userId: session.userId });
return session;
}
private async fetchWithAuthAsync(url: URL, options: { method?: string; body?: string } = {}) {
const method = options.method ?? "GET";
const start = performance.now();
let session = await this.authenticateAsync();
const doFetch = (token: string) =>
fetchWithTrustedCertificatesAsync(url, {
method,
method: options.method ?? "GET",
headers: {
Authorization: token,
...(options.body ? { "Content-Type": "application/json" } : {}),
@@ -90,42 +77,14 @@ export class BeszelIntegration extends Integration {
});
let response = await doFetch(session.token);
logger.debug("Beszel response", {
integrationId: this.integration.id,
method,
path: url.pathname,
status: response.status,
durationMs: Math.round(performance.now() - start),
attempt: 1,
});
if (response.status === 401) {
logger.warn("Beszel 401, clearing session and retrying", {
integrationId: this.integration.id,
method,
path: url.pathname,
});
await this.sessionStore.clearAsync();
session = await this.authenticateAsync();
response = await doFetch(session.token);
logger.debug("Beszel response (after re-auth)", {
integrationId: this.integration.id,
method,
path: url.pathname,
status: response.status,
durationMs: Math.round(performance.now() - start),
attempt: 2,
});
}
if (!response.ok) {
logger.warn("Beszel request failed", {
integrationId: this.integration.id,
method,
path: url.pathname,
status: response.status,
durationMs: Math.round(performance.now() - start),
});
throw new ResponseError(response);
}
@@ -286,111 +245,6 @@ export class BeszelIntegration extends Integration {
});
}
public async subscribeRealtimeMetrics(
systemId: string,
onMessage: (data: { stats: BeszelSystemStatsRecord; containerStats: BeszelContainerStatsRecord | null }) => void,
signal: AbortSignal,
): Promise<void> {
const session = await this.authenticateAsync();
const sseUrl = this.url("/api/realtime");
logger.debug("Opening Beszel SSE connection", { integrationId: this.integration.id, systemId });
const sseResponse = await fetchWithTrustedCertificatesAsync(sseUrl, {
headers: { Authorization: session.token },
signal,
});
if (!sseResponse.ok || !sseResponse.body) {
logger.warn("Beszel SSE connection failed", {
integrationId: this.integration.id,
systemId,
status: sseResponse.status,
});
throw new ResponseError(sseResponse);
}
logger.debug("Beszel SSE connection opened", { integrationId: this.integration.id, systemId });
const reader = sseResponse.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let clientId: string | null = null;
const processLine = (line: string) => {
if (!line.startsWith("data:")) return;
const jsonStr = line.slice(5).trim();
if (!jsonStr) return;
try {
const parsed = JSON.parse(jsonStr) as Record<string, unknown>;
if (!clientId && typeof parsed.clientId === "string") {
clientId = parsed.clientId;
this.subscribeTopic(clientId, systemId, session.token).catch((err) => {
logger.warn("Failed to subscribe to rt_metrics topic, aborting SSE", { error: err });
reader.cancel().catch(() => {});
});
return;
}
if ("stats" in parsed) {
const now = new Date().toISOString();
const envelope = { id: "", system: systemId, type: "1m" as const, created: now, updated: now };
const stats: BeszelSystemStatsRecord = { ...envelope, stats: parsed.stats as BeszelSystemStats };
let containerStats: BeszelContainerStatsRecord | null = null;
const hasContainers =
parsed.container &&
Array.isArray(parsed.container) &&
(parsed.container as BeszelContainerStats[]).length > 0;
if (hasContainers) {
containerStats = { ...envelope, stats: parsed.container as BeszelContainerStats[] };
}
onMessage({ stats, containerStats });
}
} catch {
logger.debug("Failed to parse SSE message", { line });
}
};
try {
while (!signal.aborted) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
processLine(line);
}
}
if (!signal.aborted) {
logger.warn("Beszel SSE stream ended unexpectedly", {
integrationId: this.integration.id,
systemId,
});
throw new Error("Beszel SSE stream ended unexpectedly");
}
} finally {
reader.cancel().catch(() => {});
}
}
private async subscribeTopic(clientId: string, systemId: string, token: string): Promise<void> {
const topic = `rt_metrics?options=${JSON.stringify({ query: { system: systemId } })}`;
const response = await fetchWithTrustedCertificatesAsync(this.url("/api/realtime"), {
method: "POST",
headers: {
Authorization: token,
"Content-Type": "application/json",
},
body: JSON.stringify({ clientId, subscriptions: [topic] }),
});
if (!response.ok) {
throw new ResponseError(response);
}
}
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
const response = await input.fetchAsync(this.url("/api/collections/users/auth-with-password"), {
method: "POST",
@@ -38,7 +38,7 @@ const itemSchema = z.object({
ServerId: z.string(),
Name: z.string(),
Taglines: z.array(z.string()),
Studios: z.array(z.object({ Name: z.string() })).optional(),
Studios: z.array(z.object({ Name: z.string() })),
Overview: z.string().optional(),
PremiereDate: z
.string()
@@ -172,7 +172,7 @@ export class EmbyIntegration extends Integration implements IMediaServerIntegrat
poster: super.externalUrl(`/Items/${item.Id}/Images/Primary?maxHeight=492&maxWidth=328&quality=90`).toString(),
backdrop: super.externalUrl(`/Items/${item.Id}/Images/Backdrop/0?maxWidth=960&quality=70`).toString(),
},
producer: item.Studios?.at(0)?.Name,
producer: item.Studios.at(0)?.Name,
rating: item.CommunityRating?.toFixed(1),
tags: item.Genres,
href: super.externalUrl(`/web/index.html#!/item?id=${item.Id}&serverId=${item.ServerId}`).toString(),
@@ -55,7 +55,7 @@ export class GlancesIntegration extends Integration implements ISystemHealthMoni
})),
uptime: stats.uptime.as("seconds"),
rebootRequired: false,
cpuModelName: stats.quicklook?.cpu_name ?? "Unknown",
cpuModelName: stats.quicklook.cpu_name,
loadAverage: null,
smart: [],
cpuTemp: undefined,
@@ -155,11 +155,9 @@ const allSchema = z.object({
return dayjs.duration({ days, hours, minutes, seconds });
}),
quicklook: z
.object({
cpu_name: z.string(),
})
.optional(),
quicklook: z.object({
cpu_name: z.string(),
}),
gpu: z
.array(
z.object({
@@ -1,115 +0,0 @@
import { ResponseError } from "@homarr/common/server";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
import type { IntegrationTestingInput } from "../base/integration";
import { Integration } from "../base/integration";
import { TestConnectionError } from "../base/test-connection/test-connection-error";
import type { TestingResult } from "../base/test-connection/test-connection-service";
import type { VpnSummaryIntegration } from "../interfaces/vpn-summary/vpn-summary-integration";
import type { VpnSummary } from "../interfaces/vpn-summary/vpn-summary-types";
import {
gluetunDnsStatusSchema,
gluetunPublicIpSchema,
gluetunVpnSettingsSchema,
gluetunVpnStatusSchema,
} from "./gluetun-types";
import type { GluetunDnsStatus, GluetunPublicIp, GluetunVpnSettings, GluetunVpnStatus } from "./gluetun-types";
export class GluetunIntegration extends Integration implements VpnSummaryIntegration {
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
const authHeaders = this.getAuthHeaders();
const url = this.url("/v1/vpn/status");
const response = await input.fetchAsync(url, {
headers: authHeaders,
});
if (!response.ok) {
return TestConnectionError.StatusResult(response);
}
return { success: true };
}
public async getSummaryAsync(): Promise<VpnSummary> {
const authHeaders = this.getAuthHeaders();
const [vpnStatus, dnsStatus, publicIp, vpnSettings] = await Promise.all([
this.getVpnStatusAsync(authHeaders),
this.getDnsStatusAsync(authHeaders),
this.getPublicIpAsync(authHeaders),
this.getVpnSettingAsync(authHeaders),
]);
return {
vpnStatus: vpnStatus.status,
dnsStatus: dnsStatus.status,
publicIp: publicIp.public_ip,
country: publicIp.country,
city: publicIp.city,
vpnProvider: {
protocol: vpnSettings.type,
provider: vpnSettings.provider.name,
},
};
}
private async getVpnStatusAsync(authHeaders: Record<string, string>): Promise<GluetunVpnStatus> {
const url = this.url("/v1/vpn/status");
const response = await fetchWithTrustedCertificatesAsync(url, {
headers: authHeaders,
});
if (!response.ok) throw new ResponseError(response);
return gluetunVpnStatusSchema.parse(await response.json());
}
private async getDnsStatusAsync(authHeaders: Record<string, string>): Promise<GluetunDnsStatus> {
const url = this.url("/v1/dns/status");
const response = await fetchWithTrustedCertificatesAsync(url, {
headers: authHeaders,
});
if (!response.ok) throw new ResponseError(response);
return gluetunDnsStatusSchema.parse(await response.json());
}
private async getPublicIpAsync(authHeaders: Record<string, string>): Promise<GluetunPublicIp> {
const url = this.url("/v1/publicip/ip");
const response = await fetchWithTrustedCertificatesAsync(url, {
headers: authHeaders,
});
if (!response.ok) throw new ResponseError(response);
return gluetunPublicIpSchema.parse(await response.json());
}
private async getVpnSettingAsync(authHeaders: Record<string, string>): Promise<GluetunVpnSettings> {
const url = this.url("/v1/vpn/settings");
const response = await fetchWithTrustedCertificatesAsync(url, {
headers: authHeaders,
});
if (!response.ok) throw new ResponseError(response);
return gluetunVpnSettingsSchema.parse(await response.json());
}
private getAuthHeaders(): Record<string, string> {
if (this.hasSecretValue("apiKey")) {
return { "X-API-Key": this.getSecretValue("apiKey") };
}
if (this.hasSecretValue("username") && this.hasSecretValue("password")) {
const username = this.getSecretValue("username");
const password = this.getSecretValue("password");
const encodedCredentials = btoa(`${username}:${password}`);
return { Authorization: `Basic ${encodedCredentials}` };
}
return {};
}
}
@@ -1,116 +0,0 @@
import { z } from "zod/v4";
export const gluetunVpnStatusSchema = z.object({
status: z.string(),
});
export type GluetunVpnStatus = z.infer<typeof gluetunVpnStatusSchema>;
export const gluetunDnsStatusSchema = gluetunVpnStatusSchema;
export type GluetunDnsStatus = z.infer<typeof gluetunDnsStatusSchema>;
export const gluetunPublicIpSchema = z.object({
public_ip: z.string(),
region: z.string(),
country: z.string(),
city: z.string(),
location: z.string(),
organization: z.string(),
postal_code: z.string(),
timezone: z.string(),
});
export type GluetunPublicIp = z.infer<typeof gluetunPublicIpSchema>;
const gluetunServerSelectionOpenvpnSchema = z.object({
config_file_path: z.string(),
protocol: z.string(),
endpoint_ip: z.string(),
custom_port: z.number(),
pia_encryption_preset: z.string(),
});
const gluetunServerSelectionWireguardSchema = z.object({
endpoint_ip: z.string(),
endpoint_port: z.number(),
public_key: z.string(),
});
const gluetunServerSelectionSchema = z.object({
vpn: z.string(),
countries: z.array(z.string()).nullable(),
categories: z.array(z.string()).nullable(),
regions: z.array(z.string()).nullable(),
cities: z.array(z.string()).nullable(),
isps: z.array(z.string()).nullable(),
names: z.array(z.string()).nullable(),
numbers: z.array(z.number()).nullable(),
hostnames: z.array(z.string()),
owned_only: z.boolean(),
free_only: z.boolean(),
premium_only: z.boolean(),
stream_only: z.boolean(),
multi_hop_only: z.boolean(),
port_forward_only: z.boolean(),
secure_core_only: z.boolean(),
tor_only: z.boolean(),
openvpn: gluetunServerSelectionOpenvpnSchema,
wireguard: gluetunServerSelectionWireguardSchema,
});
const gluetunPortForwardingSchema = z.object({
enabled: z.boolean(),
provider: z.string(),
status_file_path: z.string(),
up_command: z.string(),
down_command: z.string(),
listening_port: z.number(),
username: z.string(),
password: z.string(),
});
const gluetunProviderSchema = z.object({
name: z.string(),
server_selection: gluetunServerSelectionSchema,
port_forwarding: gluetunPortForwardingSchema,
});
const gluetunOpenvpnSettingsSchema = z.object({
version: z.string(),
user: z.string(),
password: z.string(),
config_file_path: z.string(),
ciphers: z.array(z.string()).nullable(),
auth: z.string(),
cert: z.string(),
key: z.string(),
encrypted_key: z.string(),
key_passphrase: z.string(),
pia_encryption_preset: z.string(),
mssfix: z.number(),
interface: z.string(),
process_user: z.string(),
verbosity: z.number(),
flags: z.array(z.string()).nullable(),
});
const gluetunWireguardSettingsSchema = z.object({
private_key: z.string(),
pre_shared_key: z.string(),
addresses: z.array(z.string()),
allowed_ips: z.array(z.string()),
interface: z.string(),
persistent_keep_alive_interval: z.number(),
mtu: z.number(),
implementation: z.string(),
});
export const gluetunVpnSettingsSchema = z.object({
type: z.string(),
provider: gluetunProviderSchema,
openvpn: gluetunOpenvpnSettingsSchema,
wireguard: gluetunWireguardSettingsSchema,
});
export type GluetunVpnSettings = z.infer<typeof gluetunVpnSettingsSchema>;
@@ -1,371 +0,0 @@
import { Response } from "undici";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { createDb } from "@homarr/db/test";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
import type { IntegrationTestingInput } from "../../base/integration";
import { GluetunIntegration } from "../gluetun-integration";
import {
gluetunDnsStatusSchema,
gluetunPublicIpSchema,
gluetunVpnSettingsSchema,
gluetunVpnStatusSchema,
} from "../gluetun-types";
vi.mock("@homarr/db", async (importActual) => {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const actual = await importActual<typeof import("@homarr/db")>();
return {
...actual,
db: createDb(),
};
});
vi.mock("@homarr/core/infrastructure/http", () => ({
fetchWithTrustedCertificatesAsync: vi.fn(),
}));
const TEST_URL = "https://gluetun.example.com";
const TEST_API_KEY = "test-api-key";
const TEST_USERNAME = "user";
const TEST_PASSWORD = "p@ss";
const mockFetch = vi.mocked(fetchWithTrustedCertificatesAsync);
type FetchResponse = Awaited<ReturnType<typeof fetchWithTrustedCertificatesAsync>>;
const VPN_STATUS_PAYLOAD = { status: "running" };
const DNS_STATUS_PAYLOAD = { status: "running" };
const PUBLIC_IP_PAYLOAD = {
public_ip: "203.0.113.42",
region: "Europe",
country: "Germany",
city: "Berlin",
location: "52.5200,13.4050",
organization: "Example Org",
postal_code: "10115",
timezone: "Europe/Berlin",
};
const VPN_SETTINGS_PAYLOAD = {
type: "wireguard",
provider: {
name: "mullvad",
server_selection: {
vpn: "wireguard",
countries: ["Germany"],
categories: null,
regions: null,
cities: ["Berlin"],
isps: null,
names: null,
numbers: null,
hostnames: ["de-ber-wg-001"],
owned_only: false,
free_only: false,
premium_only: false,
stream_only: false,
multi_hop_only: false,
port_forward_only: false,
secure_core_only: false,
tor_only: false,
openvpn: {
config_file_path: "",
protocol: "udp",
endpoint_ip: "",
custom_port: 0,
pia_encryption_preset: "",
},
wireguard: {
endpoint_ip: "203.0.113.1",
endpoint_port: 51820,
public_key: "pubkey",
},
},
port_forwarding: {
enabled: false,
provider: "mullvad",
status_file_path: "",
up_command: "",
down_command: "",
listening_port: 0,
username: "",
password: "",
},
},
openvpn: {
version: "",
user: "",
password: "",
config_file_path: "",
ciphers: null,
auth: "",
cert: "",
key: "",
encrypted_key: "",
key_passphrase: "",
pia_encryption_preset: "",
mssfix: 0,
interface: "tun0",
process_user: "",
verbosity: 0,
flags: null,
},
wireguard: {
private_key: "",
pre_shared_key: "",
addresses: ["10.0.0.2/32"],
allowed_ips: ["0.0.0.0/0"],
interface: "wg0",
persistent_keep_alive_interval: 25,
mtu: 1420,
implementation: "auto",
},
};
const jsonResponse = (body: unknown, init: ResponseInit = { status: 200 }): FetchResponse =>
new Response(JSON.stringify(body), {
...init,
headers: { "content-type": "application/json" },
}) as unknown as FetchResponse;
const setupHappyPath = () => {
mockFetch.mockImplementation((url) => {
const urlString = typeof url === "string" ? url : url.toString();
const { pathname } = new URL(urlString);
switch (pathname) {
case "/v1/vpn/status":
return Promise.resolve(jsonResponse(VPN_STATUS_PAYLOAD));
case "/v1/dns/status":
return Promise.resolve(jsonResponse(DNS_STATUS_PAYLOAD));
case "/v1/publicip/ip":
return Promise.resolve(jsonResponse(PUBLIC_IP_PAYLOAD));
case "/v1/vpn/settings":
return Promise.resolve(jsonResponse(VPN_SETTINGS_PAYLOAD));
default:
return Promise.resolve(jsonResponse({ error: "not found" }, { status: 404 }));
}
});
};
const createIntegrationWithApiKey = () =>
new GluetunIntegration({
id: "gluetun-1",
name: "Gluetun",
url: TEST_URL,
externalUrl: null,
decryptedSecrets: [{ kind: "apiKey", value: TEST_API_KEY }],
});
const createIntegrationWithBasicAuth = () =>
new GluetunIntegration({
id: "gluetun-2",
name: "Gluetun",
url: TEST_URL,
externalUrl: null,
decryptedSecrets: [
{ kind: "username", value: TEST_USERNAME },
{ kind: "password", value: TEST_PASSWORD },
],
});
describe("GluetunIntegration.getSummaryAsync", () => {
beforeEach(() => {
vi.clearAllMocks();
});
test("maps the four upstream responses into a flat VPN summary", async () => {
setupHappyPath();
const result = await createIntegrationWithApiKey().getSummaryAsync();
expect(result).toEqual({
vpnStatus: "running",
dnsStatus: "running",
publicIp: "203.0.113.42",
country: "Germany",
city: "Berlin",
vpnProvider: {
protocol: "wireguard",
provider: "mullvad",
},
});
});
test("hits each of the four control endpoints exactly once", async () => {
setupHappyPath();
await createIntegrationWithApiKey().getSummaryAsync();
const calledPaths = mockFetch.mock.calls.map(([url]) => {
const urlString = typeof url === "string" ? url : url.toString();
return new URL(urlString).pathname;
});
expect(calledPaths).toHaveLength(4);
expect(new Set(calledPaths)).toEqual(
new Set(["/v1/vpn/status", "/v1/dns/status", "/v1/publicip/ip", "/v1/vpn/settings"]),
);
});
test("sends X-API-Key header when an apiKey secret is configured", async () => {
setupHappyPath();
await createIntegrationWithApiKey().getSummaryAsync();
for (const [, init] of mockFetch.mock.calls) {
const headers = (init?.headers ?? {}) as Record<string, string>;
expect(headers["X-API-Key"]).toBe(TEST_API_KEY);
expect(headers.Authorization).toBeUndefined();
}
});
test("sends Basic auth header when username/password are configured", async () => {
setupHappyPath();
await createIntegrationWithBasicAuth().getSummaryAsync();
const expected = `Basic ${btoa(`${TEST_USERNAME}:${TEST_PASSWORD}`)}`;
for (const [, init] of mockFetch.mock.calls) {
const headers = (init?.headers ?? {}) as Record<string, string>;
expect(headers.Authorization).toBe(expected);
expect(headers["X-API-Key"]).toBeUndefined();
}
});
test("throws when any upstream endpoint returns a non-OK status", async () => {
mockFetch.mockImplementation((url) => {
const urlString = typeof url === "string" ? url : url.toString();
const { pathname } = new URL(urlString);
if (pathname === "/v1/publicip/ip") {
return Promise.resolve(jsonResponse({ error: "unauthorized" }, { status: 401 }));
}
return Promise.resolve(jsonResponse(VPN_STATUS_PAYLOAD));
});
await expect(createIntegrationWithApiKey().getSummaryAsync()).rejects.toThrow();
});
test("throws when an upstream payload fails schema validation", async () => {
mockFetch.mockImplementation((url) => {
const urlString = typeof url === "string" ? url : url.toString();
const { pathname } = new URL(urlString);
if (pathname === "/v1/publicip/ip") {
return Promise.resolve(jsonResponse({ public_ip: 123 }));
}
return Promise.resolve(jsonResponse(VPN_STATUS_PAYLOAD));
});
await expect(createIntegrationWithApiKey().getSummaryAsync()).rejects.toThrow();
});
});
describe("GluetunIntegration testing endpoint", () => {
type TestingFn = (input: IntegrationTestingInput) => Promise<{ success: boolean }>;
const invokeTesting = (integration: GluetunIntegration, input: IntegrationTestingInput) => {
const testing = (integration as unknown as { testingAsync: TestingFn }).testingAsync.bind(integration);
return testing(input);
};
const makeInput = (response: Response): IntegrationTestingInput =>
({
fetchAsync: vi.fn().mockResolvedValue(response),
}) as unknown as IntegrationTestingInput;
test("returns success when /v1/vpn/status responds 200", async () => {
const input = makeInput(new Response(JSON.stringify(VPN_STATUS_PAYLOAD), { status: 200 }));
const result = await invokeTesting(createIntegrationWithApiKey(), input);
expect(result.success).toBe(true);
});
test("returns a status-code failure when /v1/vpn/status responds non-OK", async () => {
const input = makeInput(new Response("unauthorized", { status: 401 }));
const result = await invokeTesting(createIntegrationWithApiKey(), input);
expect(result.success).toBe(false);
});
test("passes the api-key header through to fetchAsync", async () => {
const response = new Response(JSON.stringify(VPN_STATUS_PAYLOAD), { status: 200 });
const input = makeInput(response);
await invokeTesting(createIntegrationWithApiKey(), input);
const fetchAsyncMock = vi.mocked(input.fetchAsync);
const init = fetchAsyncMock.mock.calls[0]?.[1];
const headers = (init?.headers ?? {}) as Record<string, string>;
expect(headers["X-API-Key"]).toBe(TEST_API_KEY);
});
test("passes the Basic auth header through to fetchAsync when username/password are configured", async () => {
const response = new Response(JSON.stringify(VPN_STATUS_PAYLOAD), { status: 200 });
const input = makeInput(response);
await invokeTesting(createIntegrationWithBasicAuth(), input);
const fetchAsyncMock = vi.mocked(input.fetchAsync);
const init = fetchAsyncMock.mock.calls[0]?.[1];
const headers = (init?.headers ?? {}) as Record<string, string>;
const expected = `Basic ${btoa(`${TEST_USERNAME}:${TEST_PASSWORD}`)}`;
expect(headers.Authorization).toBe(expected);
expect(headers["X-API-Key"]).toBeUndefined();
});
});
describe("gluetun schemas", () => {
test("vpn status schema accepts a string status", () => {
expect(gluetunVpnStatusSchema.parse({ status: "running" })).toEqual({ status: "running" });
});
test("vpn status schema rejects a missing status", () => {
expect(() => gluetunVpnStatusSchema.parse({})).toThrow();
});
test("dns status schema mirrors vpn status schema", () => {
expect(gluetunDnsStatusSchema.parse({ status: "stopped" })).toEqual({ status: "stopped" });
expect(() => gluetunDnsStatusSchema.parse({ status: 42 })).toThrow();
});
test("public ip schema parses the full payload", () => {
expect(gluetunPublicIpSchema.parse(PUBLIC_IP_PAYLOAD)).toEqual(PUBLIC_IP_PAYLOAD);
});
test("public ip schema rejects a missing required field", () => {
const { city: _city, ...partial } = PUBLIC_IP_PAYLOAD;
expect(() => gluetunPublicIpSchema.parse(partial)).toThrow();
});
test("vpn settings schema parses a wireguard payload", () => {
const parsed = gluetunVpnSettingsSchema.parse(VPN_SETTINGS_PAYLOAD);
expect(parsed.type).toBe("wireguard");
expect(parsed.provider.name).toBe("mullvad");
});
test("vpn settings schema accepts nullable server-selection arrays", () => {
const payloadWithNulls = {
...VPN_SETTINGS_PAYLOAD,
provider: {
...VPN_SETTINGS_PAYLOAD.provider,
server_selection: {
...VPN_SETTINGS_PAYLOAD.provider.server_selection,
countries: null,
cities: null,
},
},
};
expect(() => gluetunVpnSettingsSchema.parse(payloadWithNulls)).not.toThrow();
});
test("vpn settings schema rejects a non-string type", () => {
expect(() => gluetunVpnSettingsSchema.parse({ ...VPN_SETTINGS_PAYLOAD, type: 1 })).toThrow();
});
});
@@ -1,43 +0,0 @@
import { ResponseError } from "@homarr/common/server";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
import { Integration } from "../base/integration";
import type { IntegrationTestingInput } from "../base/integration";
import type { TestingResult } from "../base/test-connection/test-connection-service";
import type { Notification } from "../interfaces/notifications/notification-types";
import type { INotificationsIntegration } from "../interfaces/notifications/notifications-integration";
import { gotifyMessagesResponseSchema } from "./gotify-schema";
export class GotifyIntegration extends Integration implements INotificationsIntegration {
public async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
await input.fetchAsync(this.url("/health"), { headers: this.getHeaders() });
return { success: true };
}
private getHeaders() {
const credentials = Buffer.from(`${super.getSecretValue("username")}:${super.getSecretValue("password")}`).toString(
"base64",
);
return { Authorization: `Basic ${credentials}` };
}
public async getNotificationsAsync(): Promise<Notification[]> {
const url = this.url("/message", { limit: 100 });
const response = await fetchWithTrustedCertificatesAsync(url, { headers: this.getHeaders() });
if (!response.ok) throw new ResponseError(response);
const result = await gotifyMessagesResponseSchema.safeParseAsync(await response.json());
if (!result.success) throw new Error(`Failed to parse Gotify response: ${result.error.message}`);
const parsed = result.data;
return parsed.messages.map(
(message): Notification => ({
id: String(message.id),
time: new Date(message.date),
title: message.title,
body: message.message,
}),
);
}
}
@@ -1,14 +0,0 @@
import { z } from "zod/v4";
// See: https://gotify.net/api-docs#/message/getMessages
export const gotifyMessageSchema = z.object({
id: z.number(),
date: z.string(),
title: z.string(),
message: z.string(),
priority: z.number().optional(),
});
export const gotifyMessagesResponseSchema = z.object({
messages: z.array(gotifyMessageSchema),
});
Loaded 100 of 197 files, more files were not shown because too many files have changed in this diff. Show more