Compare commits

..
Author SHA1 Message Date
ajnart 84f7ed97fc style: auto-fix lint and format 2026-06-17 14:11:52 +00:00
Thomas Camlong dc1e1891fb fix: persist Beszel server selection and improve picker visibility
The server picker was invisible (opacity: 0, hover-only) and selections
were lost on refresh because setOptions only updated the React Query cache.
Add a generic saveItemOptions mutation that persists widget option changes
directly to the database, and replace the hidden icon with a visible button.
2026-06-17 16:09:32 +02:00
Thomas 52c624addb Merge pull request #5966 from homarr-labs/feat/beszel-fixes
fix(beszel): chart color mismatch, system selector UX, SSE infrastructure, and widget fixes
2026-06-17 11:39:23 +02:00
homarr-renovate[bot] 91f9329773 chore(deps): update pnpm to v11.6.0 (#5980)
Co-authored-by: homarr-renovate[bot] <158783068+homarr-renovate[bot]@users.noreply.github.com>
2026-06-17 11:38:47 +02:00
homarr-renovate[bot] 4f1fc4d616 chore(deps): update pnpm to v11.6.0 (#5980)
Co-authored-by: homarr-renovate[bot] <158783068+homarr-renovate[bot]@users.noreply.github.com>
2026-06-17 00:29:01 +00:00
ajnart 8bee0174e9 style: auto-fix lint and format 2026-06-16 16:30:39 +00:00
Thomas Camlong 45dfe3b9ab fix: address PR review findings
- Remove ternary operators from new code (widget-integration-select,
  TabsContainer, mock data, members page)
- Remove stale /docs/management/tools/backup from sitemap type
- Add value prop to error-state Select in beszel-system-stats
2026-06-16 18:29:28 +02:00
Thomas Camlong 5078c300f8 fix(widgets): race conditions in useLiveStats and stale value in integration select
- Add generation guard to prevent late SSE events from writing stale
  data after systemId/integration changes
- Sort integrationIds for stable key (avoids unnecessary resubscribes)
- Include integrationKey and systemId in flush interval deps
- Preserve current form value in WidgetIntegrationSelectInput when it's
  missing from loaded options (matches WidgetDynamicSelectInput pattern)
2026-06-16 17:59:41 +02:00
Thomas Camlong 065b78fa3e fix(widgets): prevent TabsContainer state reset on data refetch
react-jsx-parser auto-generates random keys on every render, causing
full remounts that reset uncontrolled Tabs to defaultValue. Fix by:
- Adding disableKeyGeneration to preserve React reconciliation
- Memoizing bindings to avoid unnecessary re-parses
- Converting TabsContainer to controlled Tabs with useState
- Validating defaultTab against actual panel values
- Clearing stale parseErrors when template/data changes
2026-06-16 17:55:37 +02:00
Thomas Camlong 39900090b3 fix(ui): prevent icon/name wrapping in custom widgets table
The Group in the Name cell lacked wrap="nowrap", causing the icon to
detach onto its own line when the widget name was too long.
2026-06-16 17:24:21 +02:00
Thomas Camlong 2af2d59b8f docs: align Gotify integration page with documentation PR #558
Match the official Gotify description wording and list Gotify as a
supported integration on the Notifications widget page.
2026-06-16 16:41:30 +02:00
Thomas Camlong d0450b5153 docs(integrations): add missing Gotify integration page
The Gotify integration (merged from dev) declares a documentationUrl but
had no docs page, failing the docs-coverage validation plugin once gotify
was added to the integration doc-slug map.
2026-06-16 16:30:07 +02:00
Thomas Camlong 5f588ae287 fix(definitions): add doc slugs for gotify and archiveTeamWarrior
Merging dev introduced the Gotify integration and ArchiveTeam Warrior
widget/integration, which require entries in the doc-slug maps and the
generated documentation sitemap. Also remove a misplaced non-null
assertion in the group members page flagged by oxlint.
2026-06-16 16:23:02 +02:00
Thomas Camlong 066fb038b5 Merge remote-tracking branch 'origin/dev' into feat/beszel-fixes 2026-06-16 16:08:32 +02:00
Thomas Camlong ece436a1cc fix(docs): use valid string type for beszel system stats config
The "text" type is not a valid WidgetConfigurationItem value type;
the searchable system selector maps to "string".
2026-06-16 15:59:20 +02:00
Thomas Camlong 4da2feda35 refactor(beszel): tighten background color lookup type 2026-06-16 15:49:06 +02:00
Thomas Camlong 0a05bbed8d fix(beszel): review fixes for MCP and widget styling
- Throw TRPCError instead of returning null when no integration
- Sort beszelRouter import alphabetically in mcp.ts
- Replace ternary with lookup table for background color
- Mention integration_all in MCP server instructions
2026-06-16 15:18:13 +02:00
Thomas Camlong 420c0c30e4 fix(beszel): MCP description accuracy and type strictness
- Add .default("1h") to timePeriod so MCP clients can omit it
- Include "1m" in the description's valid timePeriod values
- Clarify that getSystemStats uses only the first integrationId
- Use MantineSize type instead of plain string for itemRadius
2026-06-16 15:13:35 +02:00
Thomas Camlong 8600c63bab feat(beszel): expose Beszel systems, alerts, and stats via MCP
Register beszelRouter in the MCP server with .meta({ mcp: enabled })
on getSystems, getAlerts, and getSystemStats procedures. AI assistants
can now query Beszel-monitored systems, view alerts, and fetch
historical metrics through the MCP protocol.

Ref #5968
2026-06-16 15:09:36 +02:00
Thomas Camlong 2a5398bec0 fix(beszel): system grid widget respects board opacity and radius
The inner Card components used Mantine's default opaque background and
hard-coded radius, clashing with board styling. Now uses board.opacity
and board.itemRadius with the same pattern as system-resources widgets.

Closes #5968
2026-06-16 15:02:58 +02:00
ajnart c751feedf7 style: auto-fix lint and format 2026-06-16 12:39:26 +00:00
Thomas Camlong cbb5e301dc refactor(widgets): replace beszelSystem option with generic integrationSelect 2026-06-16 14:38:25 +02:00
Thomas Camlong ea8f07e2bd docs(management): move SQLite Backup & Restore out of Tools category 2026-06-16 14:20:57 +02:00
Louis Bailleau fb18b975b2 feat: add local group support for OIDC users (#5952) 2026-06-16 13:45:44 +02:00
homarr-update-contributors[bot] 4692e7ce3a chore: update integrations list readme (#5973)
Co-authored-by: Homarr Update Contributors <210161987+homarr-update-contributors[bot]@users.noreply.github.com>
2026-06-16 10:45:49 +02:00
GlareandManuel dd57ee2102 feat(integrations): add ArchiveTeam Warrior widget (#5784)
* feat(integrations): add ArchiveTeam Warrior widget

* feat(integrations): add support for basic auth for archive warrior

* refactor(integrations): address ArchiveTeam Warrior review feedback

* Increase cache duration from 1 to 5 minutes

---------

Co-authored-by: Manuel <30572287+manuel-rw@users.noreply.github.com>
2026-06-16 10:43:55 +02:00
homarr-update-contributors[bot] 2ae83458e6 chore: update integrations list readme (#5972)
Co-authored-by: Homarr Update Contributors <210161987+homarr-update-contributors[bot]@users.noreply.github.com>
2026-06-16 10:40:19 +02:00
Nerdy Technician 5a1967bdd4 feat(integrations): add Gotify notifications integration (#5847)
* feat(integrations): add Gotify notifications integration

Closes #4186

> "It would be really useful if Homarr could integrate with Gotify —
> view notifications from Gotify right inside the Homarr dashboard,
> maybe as a widget or a small panel. A widget that displays the latest
> messages from Gotify (with title, message, time)."
> — #4186: feat: Gotify Integration - display notifications in Homarr

- `gotify/gotify-schema.ts` — Zod schema validating the `GET /message`
  API response from the Gotify server, including id, date, title,
  message body, and optional priority fields.
- `gotify/gotify-integration.ts` — `GotifyIntegration` class extending
  the base `Integration` and implementing `INotificationsIntegration`.
  Authenticates via HTTP Basic Auth (username + password) and fetches
  the latest 100 messages from the `/message` endpoint. Connection
  testing hits `/health`.
- `index.ts` — exports `GotifyIntegration` from the package public API.
- `base/creator.ts` — registers `GotifyIntegration` in the integration
  creator map so it can be instantiated at runtime.

- `integration.ts` — registers the `gotify` integration definition with:
  - `secretKinds: [["username", "password"]]` (Basic Auth credentials)
  - `category: ["notifications"]` (picked up automatically by the
    Notifications widget via `getIntegrationKindsByCategory`)
  - Icon sourced from `homarr-labs/dashboard-icons`
  - Documentation URL pointing to `/docs/integrations/gotify`
- `docs/homarr-docs-sitemap.ts` — adds `/docs/integrations/gotify` to
  the `HomarrDocumentationPath` union type so the documentation link
  passes the TypeScript path validation check.

Because `gotify` is registered under the `notifications` category, the
existing Notifications widget automatically supports it with no widget
code changes required. Users add the integration via Settings →
Integrations, supply their Gotify server URL, username, and password,
then attach it to a Notifications widget on any board.

* refactor(integrations): inline json parse and add error handling in Gotify integration

Address PR review feedback: remove intermediate `as unknown` cast by inlining
response.json() directly, and use safeParseAsync to handle deserialization
failures gracefully instead of throwing unhandled.
2026-06-16 10:29:48 +02:00
homarr-crowdin[bot] a4f0eda4a0 chore(lang): updated translations from crowdin (#5965)
Co-authored-by: Crowdin Homarr <190541745+homarr-crowdin[bot]@users.noreply.github.com>
2026-06-16 10:27:23 +02:00
homarr-renovate[bot] 1e07ce5c96 chore(deps): update mantine monorepo to ^9.3.1 (#5956)
Co-authored-by: homarr-renovate[bot] <158783068+homarr-renovate[bot]@users.noreply.github.com>
2026-06-16 10:26:10 +02:00
homarr-renovate[bot] 176222f56b chore(deps): update dependency form-data@>=4.0.0 <4.0.4 to >=4.0.6 [security] (#5969)
Co-authored-by: homarr-renovate[bot] <158783068+homarr-renovate[bot]@users.noreply.github.com>
2026-06-16 10:25:28 +02:00
homarr-renovate[bot] d6ce320eb2 chore(deps): update turbo monorepo to ^2.9.18 (#5971)
Co-authored-by: homarr-renovate[bot] <158783068+homarr-renovate[bot]@users.noreply.github.com>
2026-06-16 10:24:22 +02:00
homarr-renovate[bot] 094f23778c chore(deps): update dependency @types/node to ^24.13.2 (#5970)
Co-authored-by: homarr-renovate[bot] <158783068+homarr-renovate[bot]@users.noreply.github.com>
2026-06-16 10:23:50 +02:00
homarr-update-contributors[bot] ec9f3cc5ad chore: update contributors (#5945)
* chore: update contributors

* style: auto-fix lint and format

---------

Co-authored-by: Homarr Update Contributors <210161987+homarr-update-contributors[bot]@users.noreply.github.com>
2026-06-16 10:21:33 +02:00
homarr-releases[bot] 7ff115465a chore: update bug report template (#5944)
* chore: update bug report template

* style: auto-fix lint and format

---------

Co-authored-by: Releases Homarr <175486441+homarr-releases[bot]@users.noreply.github.com>
2026-06-16 10:21:19 +02:00
Matt Van HornandMatt Van Horn 58058f2ea6 fix: make quicklook optional in Glances integration schema (#5949)
On macOS (and some Glances configurations) the /api/4/all endpoint
omits the quicklook key, causing a Zod invalid_type error and crashing
the system health widget. Mark quicklook as .optional() in allSchema
and add a null-safe fallback (`?? "Unknown"`) for cpuModelName.

Fixes #5728

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
2026-06-16 10:17:56 +02:00
Daniel Lopes 6881b8355c fix: fixes and unifies descriptions in dns-hole-controls and dns-hole-summary docs (#5938) 2026-06-16 10:15:56 +02:00
homarr-renovate[bot] 7837b6fa6b chore(deps): update pnpm to >=11.5.2 (#5941)
Co-authored-by: homarr-renovate[bot] <158783068+homarr-renovate[bot]@users.noreply.github.com>
2026-06-15 21:55:49 +00:00
homarr-renovate[bot] f263388f71 chore(deps): update turbo monorepo to ^2.9.17 (#5959)
Co-authored-by: homarr-renovate[bot] <158783068+homarr-renovate[bot]@users.noreply.github.com>
2026-06-15 18:40:14 +00:00
Thomas Camlong 9aecb2ae13 refactor(beszel): replace last ternary in subscribeSystemStats 2026-06-15 17:33:58 +02:00
ajnart 1d691c0994 style: auto-fix lint and format 2026-06-15 15:33:22 +00:00
Thomas Camlong baf2b09327 refactor(beszel): consolidate hooks, extract helpers, deduplicate SSE envelope
Consolidate 5 stat mapper useCallbacks and 6 series useMemos into
single mappers/series objects. Extract statsWhenShown helper for
repeated visibility guard pattern. Deduplicate SSE record envelope
construction. Simplify prepareRecords with if/else. Remove unused
gridColumns ternary with Number() indexing.
2026-06-15 17:30:50 +02:00
ajnart 3d93ae1246 style: auto-fix lint and format 2026-06-15 15:25:49 +00:00
Thomas Camlong df66cf25c7 refactor(beszel): remove ternary operators and fix dead code
Replace all ternary operators with if/else, &&/||, or early returns.
Remove unused noAnimation constant that caused lint error.
Fix variable shadowing in tooltip deduplication loop.
2026-06-15 17:24:18 +02:00
ajnart 15ed1e51fd style: auto-fix lint and format 2026-06-15 15:15:38 +00:00
Thomas Camlong 9abce89a14 perf(beszel): throttle live renders, reduce buffer, skip hidden charts
- Decouple 1Hz SSE ingestion from render rate: accumulate data in a
  ref and flush to React state every 3s instead of every tick
- First data point flushes immediately to avoid blank screen
- Reduce MAX_BUFFER from 60 to 30 (halves SVG reconciliation work)
- Gate chart data hooks behind visibility flags so disabled charts
  skip all array processing
2026-06-15 17:14:18 +02:00
ajnart 7ffb90abd2 style: auto-fix lint and format 2026-06-15 14:58:56 +00:00
Thomas Camlong 4a65d2ae87 fix(beszel): don't clear live data on transient connection errors
Keep showing existing charts during brief WebSocket reconnections
instead of flashing the error UI. The error state only shows when
no data was ever received (genuine initial connection failure).
2026-06-15 16:57:35 +02:00
ajnart 4857b72804 style: auto-fix lint and format 2026-06-15 14:14:28 +00:00
Thomas Camlong 8134b168e1 perf(beszel): deep memoization pass for live chart rendering
- Set withDots={false} to eliminate thousands of hidden SVG Dot nodes
- Disable Recharts animation (isAnimationActive: false) during data updates
- Merge ChartPanel + BeszelAreaChart into BeszelChartPanel to fix
  React.memo being defeated by children prop creating new refs
- Memoize yAxisProps inside BeszelAreaChart instead of rebuilding inline
- Hoist chartStyle, panelStyle, CPU_Y_AXIS_DOMAIN to module constants
- Memoize subscription input/enabled in useLiveStats
- Replace O(n) find() with Map lookup in useDockerChartData hot path
2026-06-15 16:12:47 +02:00
ajnart 583b1d2935 style: auto-fix lint and format 2026-06-15 14:09:55 +00:00
Thomas Camlong 6189daf6a4 perf(beszel): fix live mode re-render cascade for Docker charts
- Stabilize useContainerNames with ref comparison so it returns the
  same array reference when container names haven't changed
- Memoize containerSeries (was computed inline every render)
- Hoist all system chart series arrays into useMemo
- Hoist activeDotProps/dotProps to module-level constants
- Wrap BeszelAreaChart and ChartPanel in React.memo
2026-06-15 16:07:37 +02:00
ajnart 569293275d style: auto-fix lint and format 2026-06-15 14:06:34 +00:00
Thomas Camlong d6ced037df refactor(beszel): deduplicate alerts query input and document systemId option
- Memoize alerts query input to avoid triple repetition
- Add system selector to docs configuration items
2026-06-15 16:04:59 +02:00
ajnart 8d2b2ee74a style: auto-fix lint and format 2026-06-15 14:03:03 +00:00
Thomas Camlong c5b4cf9a0e fix(beszel): add recovery button when live mode fails
When SSE connection fails, the error UI now shows a specific message
and a button to switch back to historical view, so users don't need
to reload the page to recover.
2026-06-15 16:01:14 +02:00
ajnart 2316f6e79d style: auto-fix lint and format 2026-06-15 13:57:09 +00:00
Thomas Camlong 16094876fa fix(beszel): restore timePeriod cast and improve error visibility
- Restore timePeriod union cast to fix typecheck (TS2769)
- Clear live data on subscription error so error UI always shows
- Emit error when no integration is configured for live subscription
- Add error state to system select input when query fails
2026-06-15 15:55:41 +02:00
ajnart 6cb9024781 style: auto-fix lint and format 2026-06-15 13:50:38 +00:00
Thomas Camlong a68eee24eb fix(beszel): improve live subscription error handling and cleanup
- Surface subscription errors in useLiveStats via onError + error state
- Show error UI in live mode when SSE connection fails
- Abort SSE reader on subscribeTopic failure instead of silent log
- Guard mock realtime against pre-aborted signal to prevent interval leak
- Remove dead includeDocker from subscription input schema
2026-06-15 15:49:14 +02:00
ajnart 2d4832dc96 style: auto-fix lint and format 2026-06-15 13:40:03 +00:00
Thomas Camlong e29c46cc5a fix(beszel): address final review findings
- Gate stats/live queries on systems loading state to prevent stale ID
  requests during initial load
- Simplify useLiveStats: functional setState, stable integrationKey dep,
  remove unused includeDocker param
- Extract prepareRecords helper to deduplicate chart ordering logic
- Remove stale timePeriod type cast
2026-06-15 15:39:01 +02:00
homarr-renovate[bot] 85e74691f2 fix(deps): update dependency postcss to ^8.5.15 (#5940)
Co-authored-by: homarr-renovate[bot] <158783068+homarr-renovate[bot]@users.noreply.github.com>
2026-06-15 13:27:40 +00:00
Thomas Camlong ed333e1cbb feat(beszel): add searchable system select input for widget options
Replace plain text systemId option with a dedicated beszelSystem factory
type backed by a searchable Select that fetches available systems from
the integration. Shows proper states for no integration, loading, and
no systems found.
2026-06-15 15:16:59 +02:00
ajnart e0e493e2f9 style: auto-fix lint and format 2026-06-15 13:16:43 +00:00
Thomas Camlong d13effdda0 fix(beszel): address review findings for live streaming
- Skip toReversed() for live data (already chronological from buffer)
- Reset live buffer on systemId/integration change to avoid stale data
- Throw on unexpected SSE stream end so subscription emits error
- Delete unused time-period.ts config (duplicate of server-side config)
2026-06-15 15:15:06 +02:00
Thomas Camlong 7e46c71187 fix(beszel): remove unused {name} placeholder from systemNotFound translation 2026-06-15 15:11:48 +02:00
ajnart 4e32e81c54 style: auto-fix lint and format 2026-06-15 13:11:01 +00:00
Thomas Camlong c5266a7a42 feat(beszel): wire live SSE streaming for 1-minute time period
Add "Live" option to time period selector that uses the existing
subscribeSystemStats tRPC subscription (PocketBase SSE) instead of
REST polling. A useLiveStats hook accumulates incoming data points
in a 60-entry rolling buffer. Charts use HH:mm:ss timestamps in
live mode.
2026-06-15 15:09:44 +02:00
ajnart 680cbc69d8 style: auto-fix lint and format 2026-06-15 13:00:46 +00:00
Thomas Camlong e22eee271c docs(beszel): update system stats widget documentation and add time-period config
Update docs with new widget options and add client-side time-period
configuration for future live streaming support.
2026-06-15 14:59:01 +02:00
Thomas Camlong 441cc692f9 feat(beszel): add error definitions and retry config to beszel widgets
Add INTERNAL_SERVER_ERROR error definitions to alerts, grid, and table
widgets. Set retry: false and appropriate staleTime/refetchInterval.
2026-06-15 14:58:53 +02:00
Thomas Camlong c9769bf530 feat(beszel): add SSE subscription endpoint and per-period cache TTL
- Add subscribeSystemStats tRPC subscription bridging PocketBase SSE
- Add subscribeRealtimeMetrics to BeszelIntegration with SSE parsing
- Add error handling: try/catch in subscription, response check in topic POST
- Add cacheDurationForInput to request handler for per-period cache TTL
- Add mock subscribeRealtimeMetrics with 1s interval for dev testing
2026-06-15 14:58:47 +02:00
Thomas Camlong 5035c26dbd feat(beszel): add translation keys for system stats widget
Add systemId option label, systemNotFound error message, and
internalServerError translations for all beszel widgets.
2026-06-15 14:58:38 +02:00
Thomas Camlong 4d8beac7d3 style(beszel): reorder container colors to rainbow spectrum
Rearrange containerColors from random order to rainbow sequence
(red -> orange -> yellow -> ... -> violet -> grape -> pink).
2026-06-15 14:58:32 +02:00
Thomas Camlong 824f31d6aa fix(beszel): deduplicate tooltip entries and round indicator pill
Non-stacked charts produce duplicate Recharts payload entries (stroke +
fill). Deduplicate by dataKey keeping the first entry (correct color).
Also increase indicator borderRadius for a fully rounded pill.
2026-06-15 14:58:27 +02:00
Thomas Camlong 90ceaf5fe8 feat(beszel): add hover-reveal CSS for system toggle button
System selector icon fades in on widget hover via CSS module.
2026-06-15 14:58:20 +02:00
Thomas Camlong 82eac2dcc1 fix(beszel): make chart stacking configurable and fix color mismatch
BeszelAreaChart hardcoded type="stacked" for all charts, causing Docker
Network I/O to render blended colors that didn't match the tooltip.

- Make `type` prop configurable (default "default")
- Only stack Memory, Docker CPU, and Docker Memory charts
- Add systemId as a persisted widget option with Menu-based selector
- Replace Popover with Menu trigger="click-hover" for proper hover UX
- Show error state with Select when selected system is not found
- Remove 1-minute time period (live SSE not wired yet)
2026-06-15 14:58:14 +02:00
homarr-renovate[bot] ab41b76a66 chore(deps): update semantic-release monorepo to ^25.0.4 (#5960)
Co-authored-by: homarr-renovate[bot] <158783068+homarr-renovate[bot]@users.noreply.github.com>
2026-06-15 06:36:32 +00:00
homarr-renovate[bot] 1f474c9ee7 chore(deps): update nextjs monorepo to v16.2.8 (#5961)
Co-authored-by: homarr-renovate[bot] <158783068+homarr-renovate[bot]@users.noreply.github.com>
2026-06-15 00:21:13 +00:00
homarr-renovate[bot] 0c15dc13fa chore(deps): update oxlint monorepo to ^1.69.0 (#5953)
Co-authored-by: homarr-renovate[bot] <158783068+homarr-renovate[bot]@users.noreply.github.com>
2026-06-14 22:22:45 +00:00
homarr-renovate[bot] 992c48fdde chore(deps): update dependency undici to v7.27.2 (#5424)
Co-authored-by: homarr-renovate[bot] <158783068+homarr-renovate[bot]@users.noreply.github.com>
2026-06-14 20:28:50 +00:00
homarr-renovate[bot] 7ccaabbd97 chore(deps): update scalar monorepo to ^0.9.43 (#5954)
Co-authored-by: homarr-renovate[bot] <158783068+homarr-renovate[bot]@users.noreply.github.com>
2026-06-14 18:27:39 +00:00
homarr-renovate[bot] 030b84674f chore(deps): update dependency hono@<4.6.5 to >=4.12.24 (#5950)
Co-authored-by: homarr-renovate[bot] <158783068+homarr-renovate[bot]@users.noreply.github.com>
2026-06-14 16:32:22 +00:00
Thomas 5fe43eb363 fix(beszel): correct unit scaling for system stats and container charts (#5958) 2026-06-14 18:21:29 +02:00
homarr-crowdin[bot] db8440bddf chore(lang): updated translations from crowdin (#5875) 2026-06-14 16:59:34 +02:00
121 changed files with 50283 additions and 1811 deletions

No files matched your search

+1
View File
@@ -33,6 +33,7 @@ body:
options:
# The below comment is used to insert a new version with on-release.yml
#NEXT_VERSION#
- 1.65.0
- 1.64.0
- 1.62.0
- 1.61.0
+1 -1
View File
@@ -1,5 +1,5 @@
{
"typescript.tsdk": "node_modules\\typescript\\lib",
"js/ts.tsdk.path": "node_modules\\typescript\\lib",
"js/ts.implicitProjectConfig.experimentalDecorators": true,
"cSpell.words": [
"ajnart",
@@ -124,6 +124,8 @@ 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
@@ -197,6 +199,7 @@ 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 |
@@ -0,0 +1,33 @@
---
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: []
}]} />
@@ -0,0 +1,8 @@
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,6 +130,7 @@ 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 |
@@ -162,3 +163,4 @@ 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
@@ -1,5 +0,0 @@
{
"label": "Tools",
"collapsed": true,
"position": 10
}
@@ -1,66 +0,0 @@
---
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,12 +8,19 @@ 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",
description:
"The time range for chart data. '1 Minute' enables live streaming via PocketBase SSE (requires Beszel agent >= 0.13.0)",
values: {
type: "select",
options: ["1 Hour", "12 Hours", "24 Hours", "1 Week", "30 Days"],
options: ["1 Minute", "1 Hour", "12 Hours", "24 Hours", "1 Week", "30 Days"],
},
defaultValue: "1 Hour",
},
@@ -1,16 +1,17 @@
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 PiHole or AdGuard from your dashboard",
description: `Control the blocking feature of your ${integrations} 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,10 +1,12 @@
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 DNS Hole",
description: `Displays the summary of your ${integrations} blocks and queries statistics`,
path: "../../widgets/dns-hole-summary",
configuration: {
items: [
@@ -19,7 +21,7 @@ export const dnsHoleSummaryWidget: WidgetDefinition = {
},
{
name: "Use Pi-Hole colors",
description: "Color the tiles using the background color, that is used by default in PiHole.",
description: `Color the tiles using the background color, that is used by default in ${integrations}.`,
values: { type: "boolean" },
defaultValue: "yes",
},
@@ -13,7 +13,8 @@ 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 { nextcloudIntegration } from '@site/docs/integrations/nextcloud';
import { gotifyIntegration } from '@site/docs/integrations/gotify';
<WidgetHeader
widget={notificationsWidget}
@@ -33,7 +34,8 @@ import notificationsScreenshot from './img/notifications.png';
<WidgetIntegrations
items={[
{ integration: ntfyIntegration },
{ integration: nextcloudIntegration }
{ integration: nextcloudIntegration },
{ integration: gotifyIntegration }
]}
/>
+1 -1
View File
@@ -37,7 +37,7 @@
"dayjs": "catalog:",
"docusaurus-plugin-image-zoom": "^3.0.1",
"leader-line-new": "^1.1.9",
"postcss": "^8.5.10",
"postcss": "^8.5.15",
"posthog-docusaurus": "^2.0.5",
"prism-react-renderer": "^2.4.1",
"random-word-slugs": "^0.1.7",
@@ -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">
<Group gap="xs" wrap="nowrap">
{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"}>
<Text size="sm" fw={500} lineClamp={1} c={def.enabled ? undefined : "dimmed"} style={{ minWidth: 0 }}>
{def.name}
</Text>
</Group>
@@ -4,6 +4,7 @@ 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";
@@ -13,9 +14,10 @@ import { MobileAffixButton } from "~/components/manage/mobile-affix-button";
interface AddGroupMemberProps {
groupId: string;
presentUserIds: string[];
allowedProviders: SupportedAuthProvider[];
}
export const AddGroupMember = ({ groupId, presentUserIds }: AddGroupMemberProps) => {
export const AddGroupMember = ({ groupId, presentUserIds, allowedProviders }: AddGroupMemberProps) => {
const tMembersAdd = useScopedI18n("group.action.addMember");
const { mutateAsync } = clientApi.group.addMember.useMutation();
const { openModal } = useModalAction(UserSelectModal);
@@ -32,13 +34,13 @@ export const AddGroupMember = ({ groupId, presentUserIds }: AddGroupMemberProps)
await revalidatePathActionAsync(`/manage/users/groups/${groupId}}/members`);
},
presentUserIds,
excludeExternalProviders: true,
allowedProviders,
},
{
title: tMembersAdd("label"),
},
);
}, [openModal, presentUserIds, groupId, mutateAsync, tMembersAdd]);
}, [openModal, presentUserIds, groupId, mutateAsync, tMembersAdd, allowedProviders]);
return <MobileAffixButton onClick={handleAddMember}>{tMembersAdd("label")}</MobileAffixButton>;
};
@@ -4,9 +4,12 @@ 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 { isProviderEnabled } from "@homarr/auth/server";
import {
getGroupMemberManagementType,
getLocallyManageableProviders,
isGroupMembershipManagedLocally,
} from "@homarr/auth/server";
import { everyoneGroup } from "@homarr/definitions";
import { getI18n, getScopedI18n } from "@homarr/translation/server";
import { Link, SearchInput, UserAvatar } from "@homarr/ui";
@@ -38,16 +41,15 @@ export default async function GroupsDetailPage(props: GroupsDetailPageProps) {
const group = await api.group.getById({ id: params.id });
const isReserved = group.name === everyoneGroup;
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;
const searchTerm = searchParams.search?.trim().toLowerCase();
const filteredMembers = group.members.filter(
(member) => !searchTerm || member.name?.toLowerCase().includes(searchTerm),
);
const providerTypes = isProviderEnabled("credentials")
? env.AUTH_PROVIDERS.length > 1
? "mixed"
: "credentials"
: "external";
// "local" = every enabled provider managed locally, "external" = none, "mixed" = some.
const managementType = getGroupMemberManagementType();
const canManageMembers = managementType !== "external";
const allowedProviders = getLocallyManageableProviders();
return (
<Stack>
@@ -56,17 +58,21 @@ export default async function GroupsDetailPage(props: GroupsDetailPageProps) {
{isReserved ? (
<ReservedGroupAlert />
) : (
providerTypes !== "credentials" && (
managementType !== "local" && (
<Alert variant="light" color="yellow" icon={<IconExclamationCircle size="1rem" stroke={1.5} />}>
{t(`group.memberNotice.${providerTypes}`)}
{t(`group.memberNotice.${managementType}`)}
</Alert>
)
)}
<Group justify="space-between">
<SearchInput placeholder={`${tMembers("search")}...`} defaultValue={searchParams.search} />
{isProviderEnabled("credentials") && !isReserved && (
<AddGroupMember groupId={group.id} presentUserIds={group.members.map((member) => member.id)} />
{canManageMembers && !isReserved && (
<AddGroupMember
groupId={group.id}
presentUserIds={group.members.map((member) => member.id)}
allowedProviders={allowedProviders}
/>
)}
</Group>
{filteredMembers.length === 0 && (
@@ -94,6 +100,8 @@ interface RowProps {
}
const Row = ({ member, groupId, disabled }: RowProps) => {
const canBeRemoved = isGroupMembershipManagedLocally(member.provider);
return (
<TableTr>
<TableTd>
@@ -104,9 +112,7 @@ const Row = ({ member, groupId, disabled }: RowProps) => {
</Anchor>
</Group>
</TableTd>
<TableTd w={100}>
{member.provider === "credentials" && !disabled && <RemoveGroupMember user={member} groupId={groupId} />}
</TableTd>
<TableTd w={100}>{canBeRemoved && !disabled && <RemoveGroupMember user={member} groupId={groupId} />}</TableTd>
</TableTr>
);
};
@@ -148,6 +148,8 @@ 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,6 +5,7 @@ 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";
@@ -12,7 +13,7 @@ import { UserAvatar } from "@homarr/ui";
interface InnerProps {
presentUserIds: string[];
excludeExternalProviders?: boolean;
allowedProviders?: SupportedAuthProvider[];
onSelect: (props: { id: string; name: string; image: string; email: string | null }) => void | Promise<void>;
confirmLabel?: string;
}
@@ -24,7 +25,7 @@ interface UserSelectFormType {
export const UserSelectModal = createModal<InnerProps>(({ actions, innerProps }) => {
const t = useI18n();
const { data: users, isPending } = clientApi.user.selectable.useQuery({
excludeExternalProviders: innerProps.excludeExternalProviders,
providers: innerProps.allowedProviders,
});
const [loading, setLoading] = useState(false);
const form = useForm<UserSelectFormType>();
@@ -5,7 +5,7 @@
bottom: calc(100% - 10px);
margin-bottom: 1px;
z-index: 200;
pointer-events: auto;
pointer-events: none;
opacity: 0;
transform: translateY(6px);
transition:
@@ -13,8 +13,10 @@
transform 150ms ease;
}
:global(.grid-stack-item[data-type="item"]:not([data-kind="app"]):hover) .wrapper,
:global(.grid-stack-item[data-type="item"]:not([data-kind="app"]):focus-within) .wrapper {
:global(.grid-stack-item[data-type="item"]:not([data-kind="app"]):hover)
.wrapper,
:global(.grid-stack-item[data-type="item"]:not([data-kind="app"]):focus-within)
.wrapper {
opacity: 1;
transform: translateY(0);
}
@@ -77,6 +79,8 @@
gap: 4px;
min-width: 0;
margin-left: auto;
flex-wrap: nowrap;
overflow: hidden;
}
.metadataItem {
@@ -1,17 +1,14 @@
"use client";
import { Avatar, Group, Text, Tooltip } from "@mantine/core";
import { Avatar, Text, Tooltip } from "@mantine/core";
import type { RouterOutputs } from "@homarr/api";
import { useEditMode } from "@homarr/boards/edit-mode";
import { getIconUrl } from "@homarr/definitions";
import { useSettings } from "@homarr/settings";
import { useI18n } from "@homarr/translation/client";
import { widgetImports } from "@homarr/widgets";
import type { SectionItem } from "~/app/[locale]/boards/_types";
import type { Translator } from "./widget-hover-metadata";
import { collectWidgetHoverMetadata, resolveWidgetDisplayName } from "./widget-hover-metadata";
import classes from "./widget-hover-overlay.module.css";
interface WidgetHoverOverlayProps {
@@ -21,27 +18,17 @@ interface WidgetHoverOverlayProps {
export const WidgetHoverOverlay = ({ item, integrations }: WidgetHoverOverlayProps) => {
const [isEditMode] = useEditMode();
const settings = useSettings();
const t = useI18n();
const { definition } = widgetImports[item.kind];
const WidgetIcon = definition.icon;
const translate = ((key: string) => t(key as never)) as Translator;
const displayName = resolveWidgetDisplayName(item, settings, translate);
const displayName = item.advancedOptions.title?.trim() || t(`widget.${item.kind}.name`);
const connectedIntegrations = (integrations ?? []).filter((integration) =>
item.integrationIds.includes(integration.id),
);
const metadataItems = collectWidgetHoverMetadata(
item,
settings,
connectedIntegrations.map((integration) => integration.kind),
translate,
);
const hasIntegrations = connectedIntegrations.length > 0;
const hasMetadata = metadataItems.length > 0;
if (isEditMode) {
if (!isEditMode) {
return null;
}
@@ -55,13 +42,13 @@ export const WidgetHoverOverlay = ({ item, integrations }: WidgetHoverOverlayPro
</Text>
</div>
{hasIntegrations && (
{connectedIntegrations.length > 0 && (
<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={20}
size={18}
radius="sm"
className={classes.integrationAvatar}
/>
@@ -69,17 +56,6 @@ export const WidgetHoverOverlay = ({ item, integrations }: WidgetHoverOverlayPro
))}
</Avatar.Group>
)}
{hasMetadata && (
<Group className={classes.metadata} gap={4}>
{metadataItems.map((metadataItem) => (
<div key={`${metadataItem.label}-${metadataItem.value}`} className={classes.metadataItem}>
<span className={classes.metadataLabel}>{metadataItem.label}</span>
<span className={classes.metadataValue}>{metadataItem.value}</span>
</div>
))}
</Group>
)}
</div>
</div>
);
+2 -2
View File
@@ -6,7 +6,7 @@
},
"engines": {
"node": ">=24.16.0",
"pnpm": ">=11.0.0"
"pnpm": ">=11.6.0"
},
"packageManager": "pnpm@11.5.3"
"packageManager": "pnpm@11.6.0"
}
+44 -30
View File
@@ -74,6 +74,13 @@
</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/>
@@ -100,15 +107,15 @@
<br/>
<p align="center">Codeberg</p>
</a>
</td>
<td align="center">
</td></tr>
<tr><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></tr>
<tr><td align="center">
</td>
<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/>
@@ -149,15 +156,15 @@
<br/>
<p align="center">GitHub<br/>Container<br/>Registry</p>
</a>
</td>
<td align="center">
</td></tr>
<tr><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></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/glances.svg" alt="Glances" width="90" height="90" />
<br/>
@@ -165,6 +172,13 @@
</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/>
@@ -191,8 +205,8 @@
<br/>
<p align="center">Jellyfin</p>
</a>
</td>
<td align="center">
</td></tr>
<tr><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/>
@@ -205,8 +219,8 @@
<br/>
<p align="center">Lidarr</p>
</a>
</td></tr>
<tr><td align="center">
</td>
<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/>
@@ -240,8 +254,8 @@
<br/>
<p align="center">ntfy</p>
</a>
</td>
<td align="center">
</td></tr>
<tr><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/>
@@ -254,8 +268,8 @@
<br/>
<p align="center">OpenMediaVault</p>
</a>
</td></tr>
<tr><td align="center">
</td>
<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/>
@@ -289,8 +303,8 @@
<br/>
<p align="center">Pi-hole</p>
</a>
</td>
<td align="center">
</td></tr>
<tr><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/>
@@ -303,8 +317,8 @@
<br/>
<p align="center">Prowlarr</p>
</a>
</td></tr>
<tr><td align="center">
</td>
<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/>
@@ -338,8 +352,8 @@
<br/>
<p align="center">Readarr</p>
</a>
</td>
<td align="center">
</td></tr>
<tr><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/>
@@ -352,8 +366,8 @@
<br/>
<p align="center">Search.ch</p>
</a>
</td></tr>
<tr><td align="center">
</td>
<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/>
@@ -387,8 +401,8 @@
<br/>
<p align="center">Tdarr</p>
</a>
</td>
<td align="center">
</td></tr>
<tr><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/>
@@ -401,8 +415,8 @@
<br/>
<p align="center">Tracearr</p>
</a>
</td></tr>
<tr><td align="center">
</td>
<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/>
@@ -436,8 +450,8 @@
<br/>
<p align="center">Unraid</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/uptime-kuma.svg" alt="Uptime Kuma" width="90" height="90" />
<br/>
+2 -2
View File
@@ -62,9 +62,9 @@
},
"engines": {
"node": ">=24.16.0",
"pnpm": ">=11.0.0"
"pnpm": ">=11.6.0"
},
"packageManager": "pnpm@11.5.3",
"packageManager": "pnpm@11.6.0",
"dependencies": {
"jsonpath-plus": "catalog:"
}
+2
View File
@@ -9,6 +9,7 @@ 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";
@@ -26,6 +27,7 @@ export const mcpRouter = createTRPCRouter({
info: infoRouter,
integration: integrationRouter,
invite: inviteRouter,
beszel: beszelRouter,
calendar: calendarRouter,
dnsHole: dnsHoleRouter,
downloads: downloadsRouter,
+21 -5
View File
@@ -1,11 +1,12 @@
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 } from "@homarr/db/schema";
import { groupMembers, groupPermissions, groups, users } from "@homarr/db/schema";
import { everyoneGroup } from "@homarr/definitions";
import { byIdSchema, paginatedSchema } from "@homarr/validation/common";
import {
@@ -18,7 +19,6 @@ 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);
throwIfCredentialsDisabled();
throwIfGroupMembersCannotBeManagedLocally();
const user = await ctx.db.query.users.findFirst({
where: eq(groups.id, input.userId),
where: eq(users.id, input.userId),
});
if (!user) {
@@ -328,6 +328,13 @@ 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,
@@ -339,7 +346,7 @@ export const groupRouter = createTRPCRouter({
.mutation(async ({ input, ctx }) => {
await throwIfGroupNotFoundAsync(ctx.db, input.groupId);
await throwIfGroupNameIsReservedAsync(ctx.db, input.groupId);
throwIfCredentialsDisabled();
throwIfGroupMembersCannotBeManagedLocally();
await ctx.db
.delete(groupMembers)
@@ -371,6 +378,15 @@ 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),
+40 -2
View File
@@ -748,7 +748,45 @@ describe("addMember should add member to group", () => {
});
// Assert
await expect(actAsync()).rejects.toThrow("Credentials provider is disabled");
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");
});
});
@@ -872,7 +910,7 @@ describe("removeMember should remove member from group", () => {
});
// Assert
await expect(actAsync()).rejects.toThrow("Credentials provider is disabled");
await expect(actAsync()).rejects.toThrow("Group members cannot be managed locally");
});
});
+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, like } from "@homarr/db";
import { and, eq, handleTransactionsAsync, inArray, 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 } from "@homarr/definitions";
import { credentialsAdminGroup, supportedAuthProviders } 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({ excludeExternalProviders: z.boolean().default(false) }).optional())
.input(z.object({ providers: z.array(z.enum(supportedAuthProviders)).optional() }).optional())
.output(
z.array(
selectUserSchema.pick({
@@ -284,7 +284,7 @@ export const userRouter = createTRPCRouter({
image: true,
email: true,
},
where: input?.excludeExternalProviders ? eq(users.provider, "credentials") : undefined,
where: input?.providers ? inArray(users.provider, input.providers) : undefined,
});
}),
search: permissionRequiredProcedure
@@ -0,0 +1,39 @@
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();
};
});
}),
});
+87 -6
View File
@@ -1,6 +1,9 @@
import { TRPCError } from "@trpc/server";
import { observable } from "@trpc/server/observable";
import { z } from "zod/v4";
import { createIntegrationAsync } from "@homarr/integrations";
import type { BeszelContainerStatsRecord, BeszelSystemStatsRecord } from "@homarr/integrations/types";
import {
beszelAlertsRequestHandler,
beszelStatsRequestHandler,
@@ -13,12 +16,21 @@ import { createTRPCRouter, publicProcedure } from "../../trpc";
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 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,
@@ -34,7 +46,11 @@ export const beszelRouter = createTRPCRouter({
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) => {
@@ -52,6 +68,13 @@ 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({
@@ -96,14 +119,22 @@ 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 () => {
@@ -113,17 +144,26 @@ 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(["1h", "12h", "24h", "1w", "30d"]),
timePeriod: z.enum(["1m", "1h", "12h", "24h", "1w", "30d"]).default("1h"),
includeDocker: z.boolean().default(true),
}),
)
.query(async ({ ctx, input }) => {
const integration = ctx.integrations[0];
if (!integration) return null;
if (!integration) {
throw new TRPCError({ code: "BAD_REQUEST", message: "At least one Beszel integrationId is required" });
}
const innerHandler = beszelStatsRequestHandler.handler(integration, {
systemId: input.systemId,
timePeriod: input.timePeriod,
@@ -132,4 +172,45 @@ export const beszelRouter = createTRPCRouter({
const { data, timestamp } = await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
return { integrationId: integration.id, ...data, updatedAt: timestamp };
}),
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 () => {};
}
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) {
if (error instanceof Error) {
emit.error(error);
} else {
emit.error(new Error(String(error)));
}
}
}
})();
return () => {
abortController.abort();
};
});
}),
});
+1
View File
@@ -3,6 +3,7 @@ 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)),
+37 -1
View File
@@ -1,7 +1,14 @@
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, publicProcedure } from "../../trpc";
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../../trpc";
import { throwIfActionForbiddenAsync } from "../board/board-access";
export const optionsRouter = createTRPCRouter({
getWidgetOptionSettings: publicProcedure.query(async ({ ctx }): Promise<WidgetOptionsSettings> => {
@@ -16,4 +23,33 @@ 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));
}),
});
+1
View File
@@ -37,6 +37,7 @@ 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),
+6 -1
View File
@@ -31,7 +31,12 @@ 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 (profile && groupsKey in profile && Array.isArray(profile[groupsKey])) {
if (
!env.AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT &&
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,9 +1,57 @@
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;
@@ -0,0 +1,105 @@
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);
});
});
+8 -1
View File
@@ -1,4 +1,11 @@
export { hasQueryAccessToIntegrationsAsync } from "./permissions/integration-query-permissions";
export { getIntegrationsWithPermissionsAsync } from "./permissions/integrations-with-permissions";
export { isProviderEnabled } from "./providers/check-provider";
export {
isProviderEnabled,
isGroupMembershipManagedLocally,
getLocallyManageableProviders,
getGroupMemberManagementType,
canManageGroupMembersLocally,
} from "./providers/check-provider";
export type { GroupMemberManagementType } from "./providers/check-provider";
export { createSessionCallback, createSessionAsync } from "./callbacks";
+29 -3
View File
@@ -12,11 +12,13 @@ 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: {
AUTH_OIDC_GROUPS_ATTRIBUTE: "someRandomGroupsKey",
},
env: mockEnv,
};
});
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
@@ -198,6 +200,30 @@ 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,6 +2,7 @@
// it uses the sitemap.xml to generate the HomarrDocumentationPath type
export type HomarrDocumentationPath =
| "/about-us"
| "/api-reference"
| "/blog"
| "/blog/2023/01/11/version0.11"
| "/blog/2023/04/16/version0.12-more-widgets"
@@ -42,9 +43,11 @@ export type HomarrDocumentationPath =
| "/docs/tags/active-directory"
| "/docs/tags/administration"
| "/docs/tags/advanced"
| "/docs/tags/ai"
| "/docs/tags/analytics"
| "/docs/tags/api"
| "/docs/tags/apps"
| "/docs/tags/automation"
| "/docs/tags/background"
| "/docs/tags/backup"
| "/docs/tags/boards"
@@ -55,9 +58,10 @@ export type HomarrDocumentationPath =
| "/docs/tags/community"
| "/docs/tags/configuration"
| "/docs/tags/connections"
| "/docs/tags/custom"
| "/docs/tags/custom-widgets"
| "/docs/tags/customization"
| "/docs/tags/data-sources"
| "/docs/tags/data"
| "/docs/tags/database"
| "/docs/tags/developer"
| "/docs/tags/development"
@@ -78,9 +82,11 @@ export type HomarrDocumentationPath =
| "/docs/tags/integrations"
| "/docs/tags/interface"
| "/docs/tags/jobs"
| "/docs/tags/jsx"
| "/docs/tags/layout"
| "/docs/tags/ldap"
| "/docs/tags/management"
| "/docs/tags/mcp"
| "/docs/tags/media"
| "/docs/tags/oidc"
| "/docs/tags/open-collective"
@@ -92,7 +98,6 @@ 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"
@@ -174,6 +179,7 @@ export type HomarrDocumentationPath =
| "/docs/integrations/github"
| "/docs/integrations/gitlab"
| "/docs/integrations/glances"
| "/docs/integrations/gotify"
| "/docs/integrations/home-assistant"
| "/docs/integrations/ical"
| "/docs/integrations/immich"
@@ -217,15 +223,16 @@ export type HomarrDocumentationPath =
| "/docs/integrations/uptime-kuma"
| "/docs/management/api"
| "/docs/management/apps"
| "/docs/management/backup"
| "/docs/management/boards"
| "/docs/management/certificates"
| "/docs/management/custom-widgets"
| "/docs/management/integrations"
| "/docs/management/mcp"
| "/docs/management/media"
| "/docs/management/search-engines"
| "/docs/management/settings"
| "/docs/management/tasks"
| "/docs/management/tools/backup"
| "/docs/management/users"
| "/docs/widgets/anchor-note"
| "/docs/widgets/app"
@@ -315,6 +322,7 @@ 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"
@@ -40,6 +40,7 @@ export const integrationDocSlugs: Record<IntegrationKind, string | null> = {
gitHubContainerRegistry: "github-containerregistry",
quay: "quay",
ntfy: "ntfy",
gotify: "gotify",
ical: "ical",
anchor: "anchor",
truenas: "truenas",
@@ -56,5 +57,6 @@ export const integrationDocSlugs: Record<IntegrationKind, string | null> = {
umami: "umami",
peaNut: "peanut",
beszel: "beszel",
archiveTeamWarrior: null,
mock: null,
};
@@ -44,6 +44,7 @@ export const widgetDocSlugs: Record<WidgetKind, string | null> = {
audioStats: "audio-stats",
umami: "umami",
ups: "ups",
archiveTeamWarrior: null,
beszelSystemTable: "beszel-system-table",
beszelSystemGrid: "beszel-system-grid",
beszelAlerts: "beszel-alerts",
+16
View File
@@ -355,6 +355,13 @@ 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"]],
@@ -482,6 +489,14 @@ export const integrationDefs = {
documentationUrl: createDocumentationLink("/docs/integrations/beszel"),
defaultPort: 8090,
},
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",
@@ -589,6 +604,7 @@ export const integrationCategories = [
"mediaMonitoring",
"speedtest",
"analytics",
"archiving",
"ups",
"documents",
"mediaLibrary",
+1
View File
@@ -41,6 +41,7 @@ export const widgetKinds = [
"uptimeKuma",
"audioStats",
"umami",
"archiveTeamWarrior",
"ups",
"beszelSystemTable",
"beszelSystemGrid",
@@ -0,0 +1,386 @@
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,
});
}
}
@@ -0,0 +1,61 @@
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>;
@@ -0,0 +1,37 @@
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,6 +3,7 @@ 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";
@@ -35,6 +36,7 @@ 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";
@@ -121,6 +123,7 @@ export const integrationCreators = {
ical: ICalIntegration,
quay: QuayIntegration,
ntfy: NTFYIntegration,
gotify: GotifyIntegration,
mock: MockIntegration,
truenas: TrueNasIntegration,
unraid: UnraidIntegration,
@@ -134,6 +137,7 @@ export const integrationCreators = {
audiobookshelf: AudiobookshelfIntegration,
navidrome: NavidromeIntegration,
umami: UmamiIntegration,
archiveTeamWarrior: ArchiveTeamWarriorIntegration,
uptimeKuma: UptimeKumaIntegration,
peaNut: PeaNutIntegration,
beszel: BeszelIntegration,
@@ -1,4 +1,5 @@
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";
@@ -12,17 +13,21 @@ 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 {
@@ -245,6 +250,100 @@ 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");
const sseResponse = await fetchWithTrustedCertificatesAsync(sseUrl, {
headers: { Authorization: session.token },
signal,
});
if (!sseResponse.ok || !sseResponse.body) {
throw new ResponseError(sseResponse);
}
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) {
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",
@@ -94,8 +94,8 @@ export interface BeszelSystemDetails {
*
* Units:
* - CPU/GPU/memory/disk percentages: 0–100
* - Memory/disk absolute values (mu, du, etc.): bytes
* - Disk I/O (dr, dw): bytes/s
* - Memory/disk absolute values (mu, du, m, d, etc.): GB
* - Disk I/O (dr, dw): MB/s
* - Network (ns, nr): bytes/s — all interfaces (including loopback, docker bridges)
* - Bandwidth (b): bytes/s [sent, recv] — public interfaces only. Prefer b over ns/nr for user-facing charts
*/
@@ -110,35 +110,35 @@ export interface BeszelSystemStats {
cpus?: number[];
/** load average [1m, 5m, 15m] */
la?: [number, number, number];
/** total memory (bytes) */
/** total memory (GB) */
m: number;
/** memory used (bytes) */
/** memory used (GB) */
mu: number;
/** memory usage (%) */
mp: number;
/** memory buffer/cache (bytes) */
/** memory buffer/cache (GB) */
mb: number;
/** memory max used (bytes) */
/** memory max used (GB) */
mm?: number;
/** memory zfs arc (bytes) */
/** memory zfs arc (GB) */
mz?: number;
/** total swap (bytes) */
/** total swap (GB) */
s: number;
/** swap used (bytes) */
/** swap used (GB) */
su: number;
/** total disk (bytes) */
/** total disk (GB) */
d: number;
/** disk used (bytes) */
/** disk used (GB) */
du: number;
/** disk usage (%) */
dp: number;
/** disk read (bytes/s) */
/** disk read (MB/s) */
dr: number;
/** disk write (bytes/s) */
/** disk write (MB/s) */
dw: number;
/** disk read max (bytes/s) */
/** disk read max (MB/s) */
drm?: number;
/** disk write max (bytes/s) */
/** disk write max (MB/s) */
dwm?: number;
/** disk IOPS [read, write] */
dio?: [number, number];
@@ -236,13 +236,14 @@ export interface BeszelContainer {
* One entry per container in a BeszelContainerStatsRecord.
*
* Network fields: b (bandwidth) is preferred when available; fall back to ns/nr.
* Units: m = MB, c = %, b/ns/nr = bytes/s
*/
export interface BeszelContainerStats {
/** container name */
n: string;
/** CPU usage (%) */
c: number;
/** memory usage (bytes) */
/** memory usage (MB) */
m: number;
/** network sent (bytes/s) — legacy, use b when available */
ns?: number;
@@ -55,7 +55,7 @@ export class GlancesIntegration extends Integration implements ISystemHealthMoni
})),
uptime: stats.uptime.as("seconds"),
rebootRequired: false,
cpuModelName: stats.quicklook.cpu_name,
cpuModelName: stats.quicklook?.cpu_name ?? "Unknown",
loadAverage: null,
smart: [],
cpuTemp: undefined,
@@ -155,9 +155,11 @@ const allSchema = z.object({
return dayjs.duration({ days, hours, minutes, seconds });
}),
quicklook: z.object({
cpu_name: z.string(),
}),
quicklook: z
.object({
cpu_name: z.string(),
})
.optional(),
gpu: z
.array(
z.object({
@@ -0,0 +1,41 @@
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,
}));
}
}
@@ -0,0 +1,14 @@
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),
});
+7
View File
@@ -1,5 +1,6 @@
// General integrations
export { AdGuardHomeIntegration } from "./adguard-home/adguard-home-integration";
export { ArchiveTeamWarriorIntegration } from "./archive-team-warrior/archive-team-warrior-integration";
export { TechnitiumDnsIntegration } from "./technitium/technitium-integration";
export { AnchorIntegration } from "./anchor/anchor-integration";
export { Aria2Integration } from "./download-client/aria2/aria2-integration";
@@ -17,6 +18,7 @@ export { RadarrIntegration } from "./media-organizer/radarr/radarr-integration";
export { ReadarrIntegration } from "./media-organizer/readarr/readarr-integration";
export { SonarrIntegration } from "./media-organizer/sonarr/sonarr-integration";
export { NextcloudIntegration } from "./nextcloud/nextcloud.integration";
export { GotifyIntegration } from "./gotify/gotify-integration";
export { NTFYIntegration } from "./ntfy/ntfy-integration";
export { OpenMediaVaultIntegration } from "./openmediavault/openmediavault-integration";
export { GlancesIntegration } from "./glances/glances-integration";
@@ -73,6 +75,11 @@ export type {
AnchorNotesListInput,
AnchorNoteSummary,
} from "./anchor/anchor-types";
export type {
ArchiveTeamWarriorBandwidth,
ArchiveTeamWarriorItem,
ArchiveTeamWarriorStatus,
} from "./archive-team-warrior/archive-team-warrior-types";
export type { TracearrDashboardData } from "./tracearr/tracearr-types";
export type { SpeedtestTrackerDashboardData } from "./speedtest-tracker/speedtest-tracker-types";
export type { AudiobookshelfDashboardData } from "./audiobookshelf/audiobookshelf-types";
+53 -15
View File
@@ -10,7 +10,6 @@ import type {
} from "../../beszel/beszel-types";
const GB = 1024 * 1024 * 1024;
const MB = 1024 * 1024;
const KB = 1024;
interface MockSystemDef {
@@ -144,26 +143,27 @@ function generateSystemStatsSeries(count: number, sys: MockSystemDef): BeszelSys
const netSendWalk = smoothWalk(500, 200, count, 10, 8000);
const netRecvWalk = smoothWalk(800, 300, count, 10, 12000);
const memTotal = sys.mem;
const diskTotal = rand(200, 2000) * GB;
return cpuWalk.map((cpu, i) => {
const memPct = memPctWalk[i] ?? sys.baseMem;
const diskPct = diskPctWalk[i] ?? sys.baseDisk;
const memTotalGB = sys.mem / GB;
const diskTotalGB = diskTotal / GB;
return {
cpu,
la: [cpu / 20 + rand(0, 0.5), cpu / 25 + rand(0, 0.3), cpu / 30 + rand(0, 0.2)] as [number, number, number],
m: memTotal,
mu: (memTotal * memPct) / 100,
m: memTotalGB,
mu: (memTotalGB * memPct) / 100,
mp: memPct,
mb: rand(0.5, 4) * GB,
s: 4 * GB,
su: rand(0, 2) * GB,
d: diskTotal,
du: (diskTotal * diskPct) / 100,
mb: rand(0.5, 4),
s: 4,
su: rand(0, 2),
d: diskTotalGB,
du: (diskTotalGB * diskPct) / 100,
dp: diskPct,
dr: (diskReadWalk[i] ?? 5) * MB,
dw: (diskWriteWalk[i] ?? 3) * MB,
dr: diskReadWalk[i] ?? 5,
dw: diskWriteWalk[i] ?? 3,
ns: (netSendWalk[i] ?? 500) * KB,
nr: (netRecvWalk[i] ?? 800) * KB,
b: [(netSendWalk[i] ?? 500) * KB * 0.7, (netRecvWalk[i] ?? 800) * KB * 0.7] as [number, number],
@@ -183,7 +183,7 @@ function generateContainerStatsSeries(count: number, profiles: typeof containerP
walks.map(({ profile, cpuWalk, memWalk, netWalk }) => ({
n: profile.name,
c: cpuWalk[i] ?? profile.cpuBase,
m: (memWalk[i] ?? profile.memMB) * MB,
m: memWalk[i] ?? profile.memMB,
b: [(netWalk[i] ?? profile.netKB) * KB * 0.4, (netWalk[i] ?? profile.netKB) * KB * 0.6] as [number, number],
})),
);
@@ -264,13 +264,15 @@ export class BeszelMockService {
const sys = resolveSystem(systemId);
const intervalMinutes = typeToMinutes[type] ?? 1;
const statsSeries = generateSystemStatsSeries(perPage, sys);
return buildTimeSeries(
const result = buildTimeSeries(
systemId,
perPage,
intervalMinutes,
type,
statsSeries.map((stats) => ({ stats })),
);
return result;
}
public async getContainerStatsAsync(
@@ -284,13 +286,15 @@ export class BeszelMockService {
.map((i) => containerProfiles[i])
.filter(Boolean) as typeof containerProfiles;
const series = generateContainerStatsSeries(perPage, selectedProfiles);
return buildTimeSeries(
const result = buildTimeSeries(
systemId,
perPage,
intervalMinutes,
type,
series.map((stats) => ({ stats })),
);
return result;
}
public async getAlertsAsync(): Promise<BeszelAlert[]> {
@@ -326,6 +330,40 @@ export class BeszelMockService {
];
}
public async subscribeRealtimeMetrics(
systemId: string,
onMessage: (data: { stats: BeszelSystemStatsRecord; containerStats: BeszelContainerStatsRecord | null }) => void,
signal: AbortSignal,
): Promise<void> {
const sys = resolveSystem(systemId);
const emit = () => {
if (signal.aborted) return;
const [stats] = generateSystemStatsSeries(1, sys);
if (!stats) return;
const record: BeszelSystemStatsRecord = {
id: `mock-rt-${Date.now()}`,
system: systemId,
stats,
type: "1m",
created: new Date().toISOString(),
updated: new Date().toISOString(),
};
onMessage({ stats: record, containerStats: null });
};
if (signal.aborted) return;
await new Promise<void>((resolve) => {
const interval = setInterval(emit, 1000);
signal.addEventListener(
"abort",
() => {
clearInterval(interval);
resolve();
},
{ once: true },
);
});
}
public async getAlertHistoryAsync(_systemId?: string, perPage = 10): Promise<BeszelAlertHistory[]> {
const now = Date.now();
const names = ["CPU", "Memory", "Disk", "Temperature", "Bandwidth"];
@@ -337,7 +375,7 @@ export class BeszelMockService {
name: names[i % names.length] ?? "CPU",
val: rand(60, 95),
created: new Date(now - (i + 1) * 3_600_000).toISOString(),
resolved: i % 2 === 0 ? new Date(now - i * 1_800_000).toISOString() : null,
resolved: (i % 2 === 0 && new Date(now - i * 1_800_000).toISOString()) || null,
}));
}
}
@@ -140,4 +140,5 @@ export class MockIntegration
getContainerStatsAsync = MockIntegration.beszel.getContainerStatsAsync.bind(MockIntegration.beszel);
getAlertsAsync = MockIntegration.beszel.getAlertsAsync.bind(MockIntegration.beszel);
getAlertHistoryAsync = MockIntegration.beszel.getAlertHistoryAsync.bind(MockIntegration.beszel);
subscribeRealtimeMetrics = MockIntegration.beszel.subscribeRealtimeMetrics.bind(MockIntegration.beszel);
}
@@ -0,0 +1,103 @@
// @vitest-environment node
import { describe, expect, test, vi } from "vitest";
import { createDb } from "@homarr/db/test";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
import { GlancesIntegration } from "../src/glances/glances-integration";
// ─── module mocks ────────────────────────────────────────────────────────────
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/certificates", async (importActual) => {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const actual = await importActual<typeof import("@homarr/core/infrastructure/certificates")>();
return {
...actual,
getTrustedCertificateHostnamesAsync: vi.fn().mockResolvedValue([]),
};
});
vi.mock("@homarr/core/infrastructure/http", () => ({
fetchWithTrustedCertificatesAsync: vi.fn(),
}));
vi.mock("../src/base/session-store", () => ({
createSessionStore: () => ({
async getAsync() {
return { version: "4.0.0" };
},
async setAsync() {
return;
},
async clearAsync() {
return;
},
}),
}));
// ─── helpers ─────────────────────────────────────────────────────────────────
const baseStats = {
cpu: { total: 10 },
mem: { total: 8_000_000_000, used: 4_000_000_000, free: 4_000_000_000 },
network: [{ bytes_sent_rate_per_sec: 1000, bytes_recv_rate_per_sec: 2000 }],
fs: [{ device_name: "/dev/sda1", used: 10_000, free: 90_000, percent: 10 }],
uptime: "1 day, 2:03:04",
gpu: [],
};
const mockFetch = vi.mocked(fetchWithTrustedCertificatesAsync);
// Cast lives here so call sites don't need `as never`.
function makeResponse(body: unknown) {
return {
ok: true,
status: 200,
json: () => Promise.resolve(body),
} as never;
}
const integrationInput = {
id: "test-glances",
name: "Glances",
url: "http://localhost:61208",
decryptedSecrets: [],
externalUrl: null,
};
// ─── tests ───────────────────────────────────────────────────────────────────
describe("GlancesIntegration schema", () => {
test("parses stats when quicklook is present", async () => {
mockFetch.mockResolvedValueOnce(makeResponse({ ...baseStats, quicklook: { cpu_name: "Apple M1" } }));
const integration = new GlancesIntegration(integrationInput);
const result = await integration.getSystemInfoAsync();
expect(result.cpuModelName).toBe("Apple M1");
expect(result.cpuUtilization).toBe(10);
});
test("returns Unknown cpuModelName when quicklook is absent (macOS scenario)", async () => {
mockFetch.mockResolvedValueOnce(makeResponse(baseStats));
const integration = new GlancesIntegration(integrationInput);
const result = await integration.getSystemInfoAsync();
expect(result.cpuModelName).toBe("Unknown");
});
test("does not throw a Zod parse error when quicklook is missing", async () => {
mockFetch.mockResolvedValueOnce(makeResponse(baseStats));
const integration = new GlancesIntegration(integrationInput);
await expect(integration.getSystemInfoAsync()).resolves.not.toThrow();
});
});
+211 -152
View File
@@ -2,7 +2,15 @@
import type { StartedTestContainer } from "testcontainers";
import { GenericContainer, Wait } from "testcontainers";
import { beforeAll, beforeEach, afterAll, describe, expect, test, vi } from "vitest";
import {
beforeAll,
beforeEach,
afterAll,
describe,
expect,
test,
vi,
} from "vitest";
import { createDb } from "@homarr/db/test";
@@ -23,10 +31,15 @@ vi.mock("@homarr/db", async (importActual) => {
vi.mock("@homarr/core/infrastructure/certificates", async (importActual) => {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const actual = await importActual<typeof import("@homarr/core/infrastructure/certificates")>();
const actual =
await importActual<
typeof import("@homarr/core/infrastructure/certificates")
>();
return {
...actual,
getTrustedCertificateHostnamesAsync: vi.fn().mockImplementation(() => Promise.resolve([])),
getTrustedCertificateHostnamesAsync: vi
.fn()
.mockImplementation(() => Promise.resolve([])),
};
});
@@ -77,7 +90,9 @@ const INTEGRATION_ID = "test-technitium";
const makeInput = (
baseUrl: string,
auth: { kind: "credentials"; password?: string } | { kind: "apiKey"; value: string },
auth:
| { kind: "credentials"; password?: string }
| { kind: "apiKey"; value: string },
): IntegrationInput => ({
id: INTEGRATION_ID,
name: "Technitium DNS",
@@ -94,7 +109,10 @@ const makeInput = (
// Fetch an API token appropriate for the server version.
// v15 has a dedicated createToken endpoint; legacy reuses the session token from login.
async function fetchApiToken(baseUrl: string, apiVersion: TechnitiumVersion): Promise<string> {
async function fetchApiToken(
baseUrl: string,
apiVersion: TechnitiumVersion,
): Promise<string> {
if (apiVersion === "v15") {
// v15 exposes a dedicated endpoint for non-expiring API tokens.
const res = await fetch(
@@ -104,7 +122,9 @@ async function fetchApiToken(baseUrl: string, apiVersion: TechnitiumVersion): Pr
}
// Legacy: /api/user/login exists on all tested versions (v11–v14) and returns a session
// token that can be used as a long-lived API key via the ?token= query parameter.
const res = await fetch(`${baseUrl}/api/user/login?user=${DEFAULT_USERNAME}&pass=${DEFAULT_PASSWORD}`);
const res = await fetch(
`${baseUrl}/api/user/login?user=${DEFAULT_USERNAME}&pass=${DEFAULT_PASSWORD}`,
);
return ((await res.json()) as { token: string }).token;
}
@@ -124,12 +144,16 @@ const pool: Record<string, ContainerEntry> = {};
beforeAll(async () => {
await Promise.all(
VERSIONS.map(async ({ tag, apiVersion }) => {
const container = await new GenericContainer(`technitium/dns-server:${tag}`)
const container = await new GenericContainer(
`technitium/dns-server:${tag}`,
)
.withExposedPorts(5380)
// Explicitly set the admin password so all versions use the same credentials.
// Without this, older versions may generate a random password on first run.
.withEnvironment({ DNS_SERVER_ADMIN_PASSWORD: DEFAULT_PASSWORD })
.withWaitStrategy(Wait.forLogMessage("Technitium DNS Server was started successfully."))
.withWaitStrategy(
Wait.forLogMessage("Technitium DNS Server was started successfully."),
)
.start();
const baseUrl = `http://${container.getHost()}:${container.getMappedPort(5380)}`;
const apiToken = await fetchApiToken(baseUrl, apiVersion);
@@ -139,203 +163,238 @@ beforeAll(async () => {
}, 120_000);
afterAll(async () => {
await Promise.all(Object.values(pool).map(({ container }) => container.stop()));
await Promise.all(
Object.values(pool).map(({ container }) => container.stop()),
);
});
// ─── version-parameterised suites ────────────────────────────────────────────
describe.each(VERSIONS)("Technitium DNS $tag ($apiVersion)", ({ tag, apiVersion }) => {
let baseUrl: string;
let apiToken: string;
describe.each(VERSIONS)(
"Technitium DNS $tag ($apiVersion)",
({ tag, apiVersion }) => {
let baseUrl: string;
let apiToken: string;
beforeAll(() => {
const entry = pool[tag];
if (!entry) throw new Error(`Container pool entry for ${tag} was not initialized`);
({ baseUrl, apiToken } = entry);
});
beforeAll(() => {
const entry = pool[tag];
if (!entry)
throw new Error(`Container pool entry for ${tag} was not initialized`);
({ baseUrl, apiToken } = entry);
});
beforeEach(() => {
sessionState[INTEGRATION_ID] = null;
});
beforeEach(() => {
sessionState[INTEGRATION_ID] = null;
});
// ── factory ────────────────────────────────────────────────────────────────
// ── factory ────────────────────────────────────────────────────────────────
describe("createTechnitiumDnsIntegrationAsync (factory)", () => {
test("factory creates a working integration (auto-detects version)", async () => {
const integration = await createTechnitiumDnsIntegrationAsync(makeInput(baseUrl, { kind: "credentials" }));
describe("createTechnitiumDnsIntegrationAsync (factory)", () => {
test("factory creates a working integration (auto-detects version)", async () => {
const integration = await createTechnitiumDnsIntegrationAsync(
makeInput(baseUrl, { kind: "credentials" }),
);
const result = await integration.getSummaryAsync();
const result = await integration.getSummaryAsync();
expect(result.status).toBe("enabled");
expect(result.dnsQueriesToday).toBeGreaterThanOrEqual(0);
}, 20_000);
});
expect(result.status).toBe("enabled");
expect(result.dnsQueriesToday).toBeGreaterThanOrEqual(0);
}, 20_000);
});
// ── getSummaryAsync ────────────────────────────────────────────────────────
// ── getSummaryAsync ────────────────────────────────────────────────────────
describe("getSummaryAsync", () => {
test("returns valid summary with credentials", async () => {
const integration = new TechnitiumDnsIntegration(makeInput(baseUrl, { kind: "credentials" }));
describe("getSummaryAsync", () => {
test("returns valid summary with credentials", async () => {
const integration = new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "credentials" }),
);
const result = await integration.getSummaryAsync();
const result = await integration.getSummaryAsync();
expect(result.dnsQueriesToday).toBeGreaterThanOrEqual(0);
expect(result.adsBlockedToday).toBeGreaterThanOrEqual(0);
expect(result.adsBlockedTodayPercentage).toBeGreaterThanOrEqual(0);
expect(result.domainsBeingBlocked).toBeGreaterThanOrEqual(0);
expect(result.status).toBe("enabled");
}, 20_000);
expect(result.dnsQueriesToday).toBeGreaterThanOrEqual(0);
expect(result.adsBlockedToday).toBeGreaterThanOrEqual(0);
expect(result.adsBlockedTodayPercentage).toBeGreaterThanOrEqual(0);
expect(result.domainsBeingBlocked).toBeGreaterThanOrEqual(0);
expect(result.status).toBe("enabled");
}, 20_000);
test("returns valid summary with API key", async () => {
const integration = new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "apiKey", value: apiToken }),
apiVersion,
);
test("returns valid summary with API key", async () => {
const integration = new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "apiKey", value: apiToken }),
apiVersion,
);
const result = await integration.getSummaryAsync();
const result = await integration.getSummaryAsync();
expect(result.status).toBe("enabled");
expect(result.dnsQueriesToday).toBeGreaterThanOrEqual(0);
}, 20_000);
expect(result.status).toBe("enabled");
expect(result.dnsQueriesToday).toBeGreaterThanOrEqual(0);
}, 20_000);
test("domainsBeingBlocked is a non-negative number (blockedZones + blockListZones)", async () => {
const integration = new TechnitiumDnsIntegration(makeInput(baseUrl, { kind: "credentials" }));
test("domainsBeingBlocked is a non-negative number (blockedZones + blockListZones)", async () => {
const integration = new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "credentials" }),
);
const result = await integration.getSummaryAsync();
const result = await integration.getSummaryAsync();
expect(typeof result.domainsBeingBlocked).toBe("number");
expect(result.domainsBeingBlocked).toBeGreaterThanOrEqual(0);
}, 20_000);
});
expect(typeof result.domainsBeingBlocked).toBe("number");
expect(result.domainsBeingBlocked).toBeGreaterThanOrEqual(0);
}, 20_000);
});
// ── session caching ────────────────────────────────────────────────────────
// ── session caching ────────────────────────────────────────────────────────
describe("session caching", () => {
test("login is performed once and token is cached for subsequent calls", async () => {
const integration = new TechnitiumDnsIntegration(makeInput(baseUrl, { kind: "credentials" }));
describe("session caching", () => {
test("login is performed once and token is cached for subsequent calls", async () => {
const integration = new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "credentials" }),
);
await integration.getSummaryAsync();
const tokenAfterFirst = sessionState[INTEGRATION_ID]?.token;
expect(tokenAfterFirst).toBeDefined();
await integration.getSummaryAsync();
const tokenAfterFirst = sessionState[INTEGRATION_ID]?.token;
expect(tokenAfterFirst).toBeDefined();
await integration.getSummaryAsync();
const tokenAfterSecond = sessionState[INTEGRATION_ID]?.token;
await integration.getSummaryAsync();
const tokenAfterSecond = sessionState[INTEGRATION_ID]?.token;
expect(tokenAfterSecond).toBe(tokenAfterFirst);
}, 20_000);
expect(tokenAfterSecond).toBe(tokenAfterFirst);
}, 20_000);
test("recovers from an expired/invalid stored token by re-logging in", async () => {
// Plant a bad token with the correct version so it hits the right API path before failing
sessionState[INTEGRATION_ID] = { token: "deliberately-invalid-token", version: apiVersion };
test("recovers from an expired/invalid stored token by re-logging in", async () => {
// Plant a bad token with the correct version so it hits the right API path before failing
sessionState[INTEGRATION_ID] = {
token: "deliberately-invalid-token",
version: apiVersion,
};
const integration = new TechnitiumDnsIntegration(makeInput(baseUrl, { kind: "credentials" }), apiVersion);
const integration = new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "credentials" }),
apiVersion,
);
const result = await integration.getSummaryAsync();
const result = await integration.getSummaryAsync();
expect(result.status).toBe("enabled");
expect(sessionState[INTEGRATION_ID]).not.toBeNull();
expect(sessionState[INTEGRATION_ID]?.token).not.toBe("deliberately-invalid-token");
}, 20_000);
});
expect(result.status).toBe("enabled");
expect(sessionState[INTEGRATION_ID]).not.toBeNull();
expect(sessionState[INTEGRATION_ID]?.token).not.toBe(
"deliberately-invalid-token",
);
}, 20_000);
});
// ── blocking state changes ─────────────────────────────────────────────────
// ── blocking state changes ─────────────────────────────────────────────────
describe("blocking state changes", () => {
test("disableAsync permanently disables blocking", async () => {
const integration = new TechnitiumDnsIntegration(makeInput(baseUrl, { kind: "credentials" }));
describe("blocking state changes", () => {
test("disableAsync permanently disables blocking", async () => {
const integration = new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "credentials" }),
);
await integration.disableAsync();
const result = await integration.getSummaryAsync();
await integration.disableAsync();
const result = await integration.getSummaryAsync();
expect(result.status).toBe("disabled");
expect(result.status).toBe("disabled");
await integration.enableAsync(); // restore
}, 20_000);
await integration.enableAsync(); // restore
}, 20_000);
test("enableAsync re-enables blocking after permanent disable", async () => {
const integration = new TechnitiumDnsIntegration(makeInput(baseUrl, { kind: "credentials" }));
test("enableAsync re-enables blocking after permanent disable", async () => {
const integration = new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "credentials" }),
);
await integration.disableAsync();
await integration.enableAsync();
const result = await integration.getSummaryAsync();
await integration.disableAsync();
await integration.enableAsync();
const result = await integration.getSummaryAsync();
expect(result.status).toBe("enabled");
}, 20_000);
expect(result.status).toBe("enabled");
}, 20_000);
test("disableAsync with duration temporarily disables blocking", async () => {
const integration = new TechnitiumDnsIntegration(makeInput(baseUrl, { kind: "credentials" }));
test("disableAsync with duration temporarily disables blocking", async () => {
const integration = new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "credentials" }),
);
await integration.disableAsync(120); // 120s → 2 min
const result = await integration.getSummaryAsync();
await integration.disableAsync(120); // 120s → 2 min
const result = await integration.getSummaryAsync();
expect(result.status).toBe("disabled");
expect(result.status).toBe("disabled");
await integration.enableAsync(); // restore
}, 20_000);
await integration.enableAsync(); // restore
}, 20_000);
test("disableAsync with small duration (1s) rounds up to 1 minute and disables", async () => {
const integration = new TechnitiumDnsIntegration(makeInput(baseUrl, { kind: "credentials" }));
test("disableAsync with small duration (1s) rounds up to 1 minute and disables", async () => {
const integration = new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "credentials" }),
);
await integration.disableAsync(1);
const result = await integration.getSummaryAsync();
await integration.disableAsync(1);
const result = await integration.getSummaryAsync();
expect(result.status).toBe("disabled");
expect(result.status).toBe("disabled");
await integration.enableAsync(); // restore
}, 20_000);
await integration.enableAsync(); // restore
}, 20_000);
test("enableAsync cancels an active timed disable immediately", async () => {
const integration = new TechnitiumDnsIntegration(makeInput(baseUrl, { kind: "credentials" }));
test("enableAsync cancels an active timed disable immediately", async () => {
const integration = new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "credentials" }),
);
await integration.disableAsync(600); // 10 minutes
await integration.enableAsync();
const result = await integration.getSummaryAsync();
await integration.disableAsync(600); // 10 minutes
await integration.enableAsync();
const result = await integration.getSummaryAsync();
expect(result.status).toBe("enabled");
}, 20_000);
});
expect(result.status).toBe("enabled");
}, 20_000);
});
// ── testConnectionAsync ────────────────────────────────────────────────────
// ── testConnectionAsync ────────────────────────────────────────────────────
describe("testConnectionAsync", () => {
test("succeeds with valid credentials", async () => {
const result = await new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "credentials" }),
).testConnectionAsync();
expect(result.success).toBe(true);
}, 20_000);
describe("testConnectionAsync", () => {
test("succeeds with valid credentials", async () => {
const result = await new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "credentials" }),
).testConnectionAsync();
expect(result.success).toBe(true);
}, 20_000);
test("succeeds with valid API key", async () => {
const result = await new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "apiKey", value: apiToken }),
apiVersion,
).testConnectionAsync();
expect(result.success).toBe(true);
}, 20_000);
test("succeeds with valid API key", async () => {
const result = await new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "apiKey", value: apiToken }),
apiVersion,
).testConnectionAsync();
expect(result.success).toBe(true);
}, 20_000);
test("fails with wrong password — returns authorization error", async () => {
const integration = new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "credentials", password: "wrong-password" }),
);
test("fails with wrong password — returns authorization error", async () => {
const integration = new TechnitiumDnsIntegration(
makeInput(baseUrl, {
kind: "credentials",
password: "wrong-password",
}),
);
const result = await integration.testConnectionAsync();
const result = await integration.testConnectionAsync();
expect(result.success).toBe(false);
if (result.success) return;
expect(result.error).toBeInstanceOf(TestConnectionError);
expect(result.error.type).toBe("authorization");
}, 20_000);
expect(result.success).toBe(false);
if (result.success) return;
expect(result.error).toBeInstanceOf(TestConnectionError);
expect(result.error.type).toBe("authorization");
}, 20_000);
test("fails with invalid API key — returns authorization error", async () => {
const result = await new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "apiKey", value: "invalid-api-key-xyz" }),
apiVersion,
).testConnectionAsync();
test("fails with invalid API key — returns authorization error", async () => {
const result = await new TechnitiumDnsIntegration(
makeInput(baseUrl, { kind: "apiKey", value: "invalid-api-key-xyz" }),
apiVersion,
).testConnectionAsync();
expect(result.success).toBe(false);
if (result.success) return;
expect(result.error).toBeInstanceOf(TestConnectionError);
expect(result.error.type).toBe("authorization");
}, 20_000);
});
});
expect(result.success).toBe(false);
if (result.success) return;
expect(result.error).toBeInstanceOf(TestConnectionError);
expect(result.error.type).toBe("authorization");
}, 20_000);
});
},
);
@@ -0,0 +1,20 @@
import dayjs from "dayjs";
import type { IntegrationKindByCategory } from "@homarr/definitions";
import type { ArchiveTeamWarriorStatus } from "@homarr/integrations";
import { createIntegrationAsync } from "@homarr/integrations";
import { createCachedIntegrationRequestHandler } from "./lib/cached-integration-request-handler";
export const archiveTeamWarriorRequestHandler = createCachedIntegrationRequestHandler<
ArchiveTeamWarriorStatus,
IntegrationKindByCategory<"archiving">,
Record<string, never>
>({
async requestAsync(integration) {
const integrationInstance = await createIntegrationAsync(integration);
return await integrationInstance.getStatusAsync();
},
cacheDuration: dayjs.duration(5, "minute"),
queryKey: "archiveTeamWarriorStatus",
});
+14 -8
View File
@@ -90,12 +90,13 @@ export const beszelAlertsRequestHandler = createCachedIntegrationRequestHandler<
queryKey: "beszelAlerts",
});
const timePeriodConfig: Record<string, { type: string; perPage: number }> = {
"1h": { type: "1m", perPage: 60 },
"12h": { type: "10m", perPage: 72 },
"24h": { type: "20m", perPage: 72 },
"1w": { type: "120m", perPage: 84 },
"30d": { type: "480m", perPage: 90 },
const timePeriodConfig: Record<string, { type: string; perPage: number; cacheSeconds: number }> = {
"1m": { type: "1m", perPage: 60, cacheSeconds: 5 },
"1h": { type: "1m", perPage: 60, cacheSeconds: 60 },
"12h": { type: "10m", perPage: 72, cacheSeconds: 300 },
"24h": { type: "20m", perPage: 72, cacheSeconds: 600 },
"1w": { type: "120m", perPage: 84, cacheSeconds: 1800 },
"30d": { type: "480m", perPage: 90, cacheSeconds: 3600 },
};
export interface BeszelStatsData {
@@ -109,7 +110,7 @@ export const beszelStatsRequestHandler = createCachedIntegrationRequestHandler<
{ systemId: string; timePeriod: string; includeDocker: boolean }
>({
async requestAsync(integration, input) {
const config = timePeriodConfig[input.timePeriod] ?? { type: "1m", perPage: 60 };
const config = timePeriodConfig[input.timePeriod] ?? { type: "1m", perPage: 60, cacheSeconds: 60 };
const instance = await createIntegrationAsync(integration);
const systemStats = await instance.getSystemStatsAsync(input.systemId, config.type, config.perPage);
const containerStats = input.includeDocker
@@ -117,6 +118,11 @@ export const beszelStatsRequestHandler = createCachedIntegrationRequestHandler<
: [];
return { systemStats, containerStats };
},
cacheDuration: dayjs.duration(30, "seconds"),
cacheDuration: dayjs.duration(60, "seconds"),
queryKey: "beszelStats",
cacheDurationForInput(input) {
const config = timePeriodConfig[input.timePeriod];
if (!config) return undefined;
return dayjs.duration(config.cacheSeconds, "seconds");
},
});
@@ -14,10 +14,10 @@ type IntegrationOfKind<TKind extends IntegrationKind> = Omit<Integration, "kind"
};
interface Options<TData, TKind extends IntegrationKind, TInput extends Record<string, unknown>> {
// Unique key for this request handler
queryKey: string;
requestAsync: (integration: IntegrationOfKind<TKind>, input: TInput) => Promise<TData>;
cacheDuration: Duration;
cacheDurationForInput?: (input: TInput) => Duration | undefined;
}
export const createCachedIntegrationRequestHandler = <
@@ -34,9 +34,9 @@ export const createCachedIntegrationRequestHandler = <
requestAsync: async (input: { options: TInput; integration: IntegrationOfKind<TKind> }) => {
return await options.requestAsync(input.integration, input.options);
},
cacheDuration: options.cacheDuration,
createRedisChannel(input, options) {
return createIntegrationOptionsChannel<TData>(input.integration.id, options.queryKey, input.options);
cacheDuration: options.cacheDurationForInput?.(itemOptions) ?? options.cacheDuration,
createRedisChannel(input, handlerOptions) {
return createIntegrationOptionsChannel<TData>(input.integration.id, handlerOptions.queryKey, input.options);
},
}).handler({ options: itemOptions, integration }),
};
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+35
View File
@@ -1652,6 +1652,13 @@
}
},
"widget": {
"integrationSelect": {
"configureIntegrationFirst": "Connect an integration first",
"loading": "Loading...",
"placeholder": "Select an option",
"noResults": "No results found",
"loadError": "Failed to load options"
},
"app": {
"name": "App",
"description": "Embeds an app into the board.",
@@ -1739,6 +1746,15 @@
}
}
},
"archiveTeamWarrior": {
"name": "ArchiveTeam Warrior",
"description": "Monitor ArchiveTeam Warrior status, projects, and active archival jobs.",
"option": {
"showBroadcastMessage": {
"label": "Show broadcast messages"
}
}
},
"dnsHoleSummary": {
"name": "DNS Hole Summary",
"description": "Displays the summary of your DNS Hole",
@@ -3561,6 +3577,9 @@
}
},
"noRecords": "No systems found",
"error": {
"internalServerError": "Unable to connect to Beszel. Check your integration settings."
},
"column": {
"system": "System",
"cpu": "CPU",
@@ -3617,6 +3636,9 @@
"label": "Show agent version"
}
},
"error": {
"internalServerError": "Unable to connect to Beszel. Check your integration settings."
},
"metric": {
"cpu": "CPU",
"memory": "Memory",
@@ -3643,6 +3665,9 @@
}
},
"empty": "No alerts configured",
"error": {
"internalServerError": "Unable to connect to Beszel. Check your integration settings."
},
"history": "History",
"resolved": "Resolved",
"status": {
@@ -3654,6 +3679,10 @@
"name": "Beszel System Stats",
"description": "Time-series charts for CPU, memory, disk, network, and Docker container metrics",
"option": {
"systemId": {
"label": "System",
"description": "Select a Beszel system to display stats for"
},
"timePeriod": {
"label": "Time period"
},
@@ -3683,6 +3712,12 @@
}
},
"selectSystem": "Select system",
"error": {
"internalServerError": "Unable to connect to Beszel. Check your integration settings.",
"liveConnectionFailed": "Live connection failed. Your Beszel instance may not support real-time streaming.",
"switchToHistorical": "Switch to historical view",
"systemNotFound": "Selected system was not found. Choose a different system."
},
"chart": {
"cpu": {
"title": "CPU Usage",
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+2
View File
@@ -16,6 +16,7 @@ import { WidgetTextInput } from "./widget-text-input";
import { WidgetUmamiEventInput } from "./widget-umami-event-input";
import { WidgetUmamiEventNamesInput } from "./widget-umami-event-names-input";
import { WidgetUmamiWebsiteInput } from "./widget-umami-website-input";
import { WidgetIntegrationSelectInput } from "./widget-integration-select-input";
const mapping = {
anchorNote: WidgetAnchorNoteInput,
@@ -35,6 +36,7 @@ const mapping = {
umamiEventNames: WidgetUmamiEventNamesInput,
umamiWebsite: WidgetUmamiWebsiteInput,
customWidgetSelect: WidgetCustomWidgetSelectInput,
integrationSelect: WidgetIntegrationSelectInput,
} satisfies Record<WidgetOptionType, unknown>;
export const getInputForType = <TType extends WidgetOptionType>(type: TType) => {
@@ -0,0 +1,55 @@
"use client";
import { Select, Text } from "@mantine/core";
import { useScopedI18n } from "@homarr/translation/client";
import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
import { useFormContext } from "./form";
const useIntegrationSelectTranslation = () => useScopedI18n("widget.integrationSelect");
export const WidgetIntegrationSelectInput = ({
property,
kind,
options,
}: CommonWidgetInputProps<"integrationSelect">) => {
const t = useIntegrationSelectTranslation();
const tInput = useWidgetInputTranslation(kind, property);
const form = useFormContext();
const integrationIds = form.values.integrationIds as string[];
const { data: selectData = [], isPending, isError } = options.useOptions(integrationIds);
const currentValue = form.getInputProps(`options.${property}`).value as string;
const hasCurrentInData = !currentValue || selectData.some((opt) => opt.value === currentValue);
const data = hasCurrentInData ? selectData : [...selectData, { value: currentValue, label: currentValue }];
if (integrationIds.length === 0) {
return (
<Text size="sm" c="dimmed">
{t("configureIntegrationFirst")}
</Text>
);
}
const description = options.withDescription ? tInput("description") : undefined;
const placeholder = isPending ? t("loading") : t("placeholder");
const error = isError ? t("loadError") : undefined;
return (
<Select
label={tInput("label")}
description={description}
placeholder={placeholder}
clearable={options.clearable}
searchable={options.searchable}
nothingFoundMessage={t("noResults")}
data={data}
disabled={isError}
error={error}
{...form.getInputProps(`options.${property}`)}
/>
);
};
+2
View File
@@ -6,6 +6,8 @@
object-fit: contain;
scale: 0.8;
transition: scale 0.2s ease-in-out;
user-select: none;
-webkit-touch-callout: none;
}
.appWithUrl:hover > .appIcon {
@@ -0,0 +1,100 @@
"use client";
import { Avatar, Badge, Card, Group, SimpleGrid, Stack, Text } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { humanFileSize } from "@homarr/common";
import { getIconUrl } from "@homarr/definitions";
import type { WidgetComponentProps } from "../definition";
export default function ArchiveTeamWarriorWidget({
integrationIds,
options,
}: WidgetComponentProps<"archiveTeamWarrior">) {
const integrationId = integrationIds[0];
if (!integrationId) {
return null;
}
return <ArchiveTeamWarriorWidgetContent integrationId={integrationId} options={options} />;
}
const ArchiveTeamWarriorWidgetContent = ({
integrationId,
options,
}: {
integrationId: string;
options: WidgetComponentProps<"archiveTeamWarrior">["options"];
}) => {
const [data] = clientApi.widget.archiveTeamWarrior.getStatus.useSuspenseQuery({
integrationId,
});
const utils = clientApi.useUtils();
clientApi.widget.archiveTeamWarrior.subscribeStatus.useSubscription(
{ integrationId },
{
onData: (next) => {
utils.widget.archiveTeamWarrior.getStatus.setData({ integrationId }, next);
},
},
);
const status = data.status;
const projectName = status.project?.title ?? status.selectedProject ?? "No project selected";
return (
<Stack p="xs" gap="xs" h="100%">
<Group justify="space-between" align="center" wrap="nowrap">
<Group gap="xs" wrap="nowrap" miw={0}>
<Avatar size="sm" radius="md" src={getIconUrl("archiveTeamWarrior")} />
<Text size="sm" c="dimmed" lineClamp={1}>
{projectName}
</Text>
</Group>
<Badge size="sm" color={status.status === "Running" ? "green" : "gray"}>
{status.status}
</Badge>
</Group>
{options.showBroadcastMessage && status.broadcastMessage && (
<Card withBorder p="xs">
<Text size="xs" lineClamp={3}>
{status.broadcastMessage}
</Text>
</Card>
)}
<SimpleGrid cols={2} spacing="xs">
<Metric label="Running" value={status.counts.running} />
<Metric label="Done" value={status.counts.completed} />
<Metric label="Failed" value={status.counts.failed} />
<Metric label="Canceled" value={status.counts.canceled} />
</SimpleGrid>
{status.bandwidth && (
<SimpleGrid cols={2} spacing="xs">
<Metric label="Download" value={formatBandwidth(status.bandwidth.receiving)} />
<Metric label="Upload" value={formatBandwidth(status.bandwidth.sending)} />
</SimpleGrid>
)}
</Stack>
);
};
const Metric = ({ label, value }: { label: string; value: number | string }) => (
<Stack gap={0} miw={0}>
<Text size="md" fw={700} lineClamp={1}>
{value}
</Text>
<Text size="xs" c="dimmed" lineClamp={1}>
{label}
</Text>
</Stack>
);
const formatBandwidth = (value?: number) => humanFileSize(Math.round(value ?? 0), "/s");
@@ -0,0 +1,16 @@
import { IconArchive } from "@tabler/icons-react";
import { createWidgetDefinition } from "../definition";
import { optionsBuilder } from "../options";
export const { definition, componentLoader } = createWidgetDefinition("archiveTeamWarrior", {
icon: IconArchive,
createOptions() {
return optionsBuilder.from((factory) => ({
showBroadcastMessage: factory.switch({
defaultValue: true,
}),
}));
},
supportedIntegrations: ["archiveTeamWarrior"],
}).withDynamicImport(() => import("./component"));
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more