feat!: release v2 (#6545)

Co-authored-by: Artur <145776561+arturict@users.noreply.github.com>
Co-authored-by: arturict <arturict@users.noreply.github.com>
Co-authored-by: Thomas <thomas@ajnart.fr>
Co-authored-by: Afonso Jorge Ramos <afonsojorgeramos@gmail.com>
Co-authored-by: Danura30082 <danura30082+github@gmail.com>
Co-authored-by: Kushie <122986913+kushiemoon-dev@users.noreply.github.com>
Co-authored-by: ajnart <thomas@ajnart.fr>
Co-authored-by: ajnart <thomas@ajnart.dev>
Co-authored-by: chenjun <chenjun@foxmail.com>
Co-authored-by: Wikibear <wikibear@users.noreply.github.com>
Co-authored-by: Bergasha <bergasha@gmail.com>
Co-authored-by: leafyelin <43306196+leafyelin@users.noreply.github.com>
Co-authored-by: Lucas Araujo <lucas.lra@gmail.com>
Co-authored-by: GreenMonito <86085570+GreenMonito@users.noreply.github.com>
Co-authored-by: Nerdy-Technician <roffo@nerdy-technician.social>
Co-authored-by: Jun <34545896+jcstrong@users.noreply.github.com>
Co-authored-by: Edmond Abraham <54119952+gitedmond@users.noreply.github.com>
Co-authored-by: thrawnx <tight.bulb9384@fastmail.com>
Co-authored-by: Chris <58918656+nordada@users.noreply.github.com>
Co-authored-by: yi111 <153097222+Yi-111-a@users.noreply.github.com>
Co-authored-by: Yanis <naamaneyanis@gmail.com>
Co-authored-by: Wikibear <me@sej.de>
Co-authored-by: alessiottavo <93441886+alessiottavo@users.noreply.github.com>
This commit is contained in:
3286 files changed
+284386 -139176

No files matched your search

+188
View File
@@ -0,0 +1,188 @@
export const assistantProviderIds = [
"homarr",
"openrouter",
"openai",
"anthropic",
"google-gemini",
"xai",
"groq",
"mistral",
"deepseek",
"together",
"ollama",
"lm-studio",
"llama-cpp",
"custom",
] as const;
export type AssistantProvider = (typeof assistantProviderIds)[number];
export type AssistantProviderCategory = "free" | "hosted" | "local" | "custom";
export const assistantHomarrProviderTokenHeader = "X-Homarr-Provider-Token";
export const assistantReasoningModes = ["auto", "none", "minimal", "low", "medium", "high"] as const;
export type AssistantReasoningMode = (typeof assistantReasoningModes)[number];
export interface AssistantModelOption {
id: string;
name: string;
}
export const getAssistantModelOptionLabel = (model: AssistantModelOption) =>
model.name === model.id ? model.id : `${model.name} (${model.id})`;
export const resolveAssistantModelId = (models: AssistantModelOption[], value: string) =>
models.find((model) => model.id === value || getAssistantModelOptionLabel(model) === value)?.id ?? null;
const providerIconBaseUrl = "https://cdn.jsdelivr.net/npm/@lobehub/icons-static-svg@latest/icons";
interface AssistantProviderPreset {
label?: string;
baseUrl: string;
modelDiscoveryPath: string | null;
requiresApiKey: boolean;
category: AssistantProviderCategory;
discoveryAuthentication: "bearer" | "anthropic";
iconUrl: string | null;
darkIconUrl?: string;
}
export const assistantProviderPresets = {
homarr: {
label: "Homarr",
// Browser and server code replace this public fallback with WORKSHOP_API_URL at runtime.
baseUrl: "https://homarr.dev/api/ai/v1",
modelDiscoveryPath: "/models",
requiresApiKey: false,
category: "free",
discoveryAuthentication: "bearer",
iconUrl: "https://homarr.dev/img/logo.png",
},
openrouter: {
label: "OpenRouter",
baseUrl: "https://openrouter.ai/api/v1",
modelDiscoveryPath: "/models",
requiresApiKey: true,
category: "hosted",
discoveryAuthentication: "bearer",
iconUrl: `${providerIconBaseUrl}/openrouter-color.svg`,
},
openai: {
label: "OpenAI",
baseUrl: "https://api.openai.com/v1",
modelDiscoveryPath: "/models",
requiresApiKey: true,
category: "hosted",
discoveryAuthentication: "bearer",
iconUrl: `${providerIconBaseUrl}/openai.svg`,
},
anthropic: {
label: "Anthropic Claude",
baseUrl: "https://api.anthropic.com/v1",
modelDiscoveryPath: "/models",
requiresApiKey: true,
category: "hosted",
discoveryAuthentication: "anthropic",
iconUrl: `${providerIconBaseUrl}/anthropic.svg`,
},
"google-gemini": {
label: "Google Gemini",
baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai",
modelDiscoveryPath: "/models",
requiresApiKey: true,
category: "hosted",
discoveryAuthentication: "bearer",
iconUrl: `${providerIconBaseUrl}/gemini-color.svg`,
},
xai: {
label: "xAI",
baseUrl: "https://api.x.ai/v1",
modelDiscoveryPath: "/models",
requiresApiKey: true,
category: "hosted",
discoveryAuthentication: "bearer",
iconUrl: `${providerIconBaseUrl}/xai.svg`,
},
groq: {
label: "Groq",
baseUrl: "https://api.groq.com/openai/v1",
modelDiscoveryPath: "/models",
requiresApiKey: true,
category: "hosted",
discoveryAuthentication: "bearer",
iconUrl: `${providerIconBaseUrl}/groq.svg`,
darkIconUrl: "https://cdn.jsdelivr.net/npm/@lobehub/icons-static-png@latest/dark/groq.png",
},
mistral: {
label: "Mistral AI",
baseUrl: "https://api.mistral.ai/v1",
modelDiscoveryPath: "/models",
requiresApiKey: true,
category: "hosted",
discoveryAuthentication: "bearer",
iconUrl: `${providerIconBaseUrl}/mistral-color.svg`,
},
deepseek: {
label: "DeepSeek",
baseUrl: "https://api.deepseek.com",
modelDiscoveryPath: "/models",
requiresApiKey: true,
category: "hosted",
discoveryAuthentication: "bearer",
iconUrl: `${providerIconBaseUrl}/deepseek-color.svg`,
},
together: {
label: "Together AI",
baseUrl: "https://api.together.xyz/v1",
modelDiscoveryPath: "/models",
requiresApiKey: true,
category: "hosted",
discoveryAuthentication: "bearer",
iconUrl: `${providerIconBaseUrl}/together-color.svg`,
},
ollama: {
label: "Ollama",
baseUrl: "http://localhost:11434/v1",
modelDiscoveryPath: "/models",
requiresApiKey: false,
category: "local",
discoveryAuthentication: "bearer",
iconUrl: `${providerIconBaseUrl}/ollama.svg`,
},
"lm-studio": {
label: "LM Studio",
baseUrl: "http://localhost:1234/v1",
modelDiscoveryPath: "/models",
requiresApiKey: false,
category: "local",
discoveryAuthentication: "bearer",
iconUrl: `${providerIconBaseUrl}/lmstudio.svg`,
},
"llama-cpp": {
label: "llama.cpp",
baseUrl: "http://localhost:8080/v1",
modelDiscoveryPath: "/models",
requiresApiKey: false,
category: "local",
discoveryAuthentication: "bearer",
iconUrl: "https://cdn.jsdelivr.net/gh/selfhst/icons/svg/llama-cpp.svg",
},
custom: {
label: undefined,
baseUrl: "",
modelDiscoveryPath: "/models",
requiresApiKey: false,
category: "custom",
discoveryAuthentication: "bearer",
iconUrl: null,
},
} as const satisfies Record<AssistantProvider, AssistantProviderPreset>;
export const assistantProviderRequiresApiKey = (provider: AssistantProvider) =>
assistantProviderPresets[provider].requiresApiKey;
/**
* OpenRouter and Homarr Router implement OpenRouter server tools directly.
* Custom endpoints may opt in when they proxy the OpenRouter request format.
*/
export const assistantProviderCanUseOpenRouterServerTools = (provider: AssistantProvider) =>
provider === "openrouter" || provider === "homarr" || provider === "custom";
+47
View File
@@ -8,7 +8,54 @@ export const backgroundImageRepeats = createDefinition(["repeat", "repeat-x", "r
export const backgroundImageSizes = createDefinition(["cover", "contain"], {
defaultValue: "cover",
});
export const layoutRoles = createDefinition(["mobile", "base", "custom"], { defaultValue: "custom" });
export type BackgroundImageAttachment = inferDefinitionType<typeof backgroundImageAttachments>;
export type BackgroundImageRepeat = inferDefinitionType<typeof backgroundImageRepeats>;
export type BackgroundImageSize = inferDefinitionType<typeof backgroundImageSizes>;
export type LayoutRole = inferDefinitionType<typeof layoutRoles>;
const MAX_LAYOUT_BREAKPOINT = 32767;
const compareBoardLayouts = (
layoutA: { id: string; breakpoint: number; columnCount: number },
layoutB: { id: string; breakpoint: number; columnCount: number },
) =>
layoutA.breakpoint - layoutB.breakpoint ||
layoutA.columnCount - layoutB.columnCount ||
layoutA.id.localeCompare(layoutB.id);
export const normalizeBoardLayoutRoles = <
TLayout extends { id: string; breakpoint: number; columnCount: number; role?: LayoutRole },
>(
sourceLayouts: TLayout[],
): Array<TLayout & { role: LayoutRole }> => {
const mobileLayouts = sourceLayouts.filter((layout) => layout.role === "mobile");
const baseLayouts = sourceLayouts.filter((layout) => layout.role === "base");
const mobileLayout = mobileLayouts.length === 1 ? mobileLayouts[0] : undefined;
const baseLayout = baseLayouts.length === 1 ? baseLayouts[0] : undefined;
const hasProtectedLayouts = mobileLayout !== undefined && baseLayout !== undefined;
let orderedLayouts = sourceLayouts.toSorted(compareBoardLayouts);
if (hasProtectedLayouts) {
orderedLayouts = [
mobileLayout,
...sourceLayouts.filter((layout) => layout.id !== mobileLayout.id).toSorted(compareBoardLayouts),
];
}
let previousBreakpoint = -1;
return orderedLayouts.map((layout, index) => {
const remainingLayouts = orderedLayouts.length - index - 1;
const breakpoint =
index === 0
? 0
: Math.min(MAX_LAYOUT_BREAKPOINT - remainingLayouts, Math.max(previousBreakpoint + 1, layout.breakpoint));
let role: LayoutRole = layout.role ?? "custom";
if (!hasProtectedLayouts) {
if (index === 0) role = "mobile";
else if (index === orderedLayouts.length - 1) role = "base";
else role = "custom";
}
previousBreakpoint = breakpoint;
return { ...layout, breakpoint, role };
});
};
@@ -1,6 +1,6 @@
import { objectKeys } from "@homarr/common";
import { integrationDefs } from "./integration";
import { getIntegrationDockerMetadata, integrationDefs } from "./integration";
import type { IntegrationKind } from "./integration";
export const extractContainerImageName = (image: string): string => image.split("/").at(-1)?.split(":").at(0) ?? "";
@@ -14,30 +14,6 @@ export const integrationIconSlugs: Record<IntegrationKind, string> = Object.from
objectKeys(integrationDefs).map((kind) => [kind, extractIconSlug(integrationDefs[kind].iconUrl)]),
) as Record<IntegrationKind, string>;
const integrationAliases: Partial<Record<IntegrationKind, readonly string[]>> = {
piHole: ["pihole", "pi-hole"],
adGuardHome: ["adguardhome", "adguard-home", "adguard"],
homeAssistant: ["homeassistant", "home-assistant", "hass"],
openmediavault: ["omv"],
qBittorrent: ["qbittorrent"],
sabNzbd: ["sabnzbd"],
nzbGet: ["nzbget"],
unifiController: ["unifi", "unifi-controller"],
jellyseerr: ["jellyseerr"],
overseerr: ["overseerr"],
dashDot: ["dashdot", "dash-dot", "dash."],
speedtestTracker: ["speedtest-tracker"],
uptimeKuma: ["uptime-kuma"],
audiobookshelf: ["audiobookshelf"],
navidrome: ["navidrome"],
paperlessNgx: ["paperless-ngx", "paperless"],
patchmon: ["patchmon", "patch-mon"],
coolify: ["coolify"],
truenas: ["truenas"],
bazarr: ["bazarr"],
synology: ["synology", "diskstation"],
};
export const matchIntegrationKind = (search: string): IntegrationKind | null => {
const normalized = search.toLowerCase().trim();
if (!normalized) return null;
@@ -51,8 +27,8 @@ export const matchIntegrationKind = (search: string): IntegrationKind | null =>
if (integrationIconSlugs[kind] === normalized) return kind;
}
for (const [kind, aliases] of Object.entries(integrationAliases) as [IntegrationKind, readonly string[]][]) {
if (aliases.some((alias) => alias === normalized)) return kind;
for (const kind of objectKeys(integrationDefs)) {
if (getIntegrationDockerMetadata(kind).aliases.some((alias) => alias === normalized)) return kind;
}
for (const kind of objectKeys(integrationDefs)) {
@@ -63,8 +39,6 @@ export const matchIntegrationKind = (search: string): IntegrationKind | null =>
return null;
};
const notDockerDiscoverable = new Set<IntegrationKind>(["ical", "mock"]);
interface ContainerMatchInput {
image: string;
name: string;
@@ -73,10 +47,10 @@ interface ContainerMatchInput {
export const matchIntegrationKindFromContainer = (container: ContainerMatchInput): IntegrationKind | null => {
const imageName = extractContainerImageName(container.image);
const fromImage = matchIntegrationKind(imageName);
if (fromImage && !notDockerDiscoverable.has(fromImage)) return fromImage;
if (fromImage && getIntegrationDockerMetadata(fromImage).discoverable) return fromImage;
const fromName = matchIntegrationKind(container.name);
if (fromName && !notDockerDiscoverable.has(fromName)) return fromName;
if (fromName && getIntegrationDockerMetadata(fromName).discoverable) return fromName;
return null;
};
@@ -0,0 +1,147 @@
import {
extractContainerImageName,
matchIntegrationKind,
matchIntegrationKindFromContainer,
} from "./docker-integration-match";
import type { IntegrationKind } from "./integration";
export type DockerServiceMatchConfidence = "high" | "medium";
export type DockerServiceMatchSource = "image" | "name";
export type DockerUrlCandidateSource = "publishedAddress" | "endpointHost" | "containerDns" | "manual";
export type DockerUrlCandidateScope = "browser" | "server";
export type DockerUrlCandidateReason =
| "publishedAddress"
| "dockerEndpointHost"
| "sharedContainerNetwork"
| "manualHostRequired";
export interface DockerServiceMatch {
kind: IntegrationKind;
confidence: DockerServiceMatchConfidence;
source: DockerServiceMatchSource;
}
export interface DockerServicePort {
IP?: string;
PrivatePort: number;
PublicPort?: number;
Type: string;
}
export interface DockerServiceUrlCandidate {
id: string;
url: string;
rank: number;
source: DockerUrlCandidateSource;
scopes: DockerUrlCandidateScope[];
reason: DockerUrlCandidateReason;
}
export const matchDockerService = (container: { image: string; name: string }): DockerServiceMatch | null => {
const kind = matchIntegrationKindFromContainer(container);
if (!kind) return null;
const imageMatch = matchIntegrationKind(extractContainerImageName(container.image));
return imageMatch === kind
? { kind, confidence: "high", source: "image" }
: { kind, confidence: "medium", source: "name" };
};
export const buildDockerServiceUrlCandidates = ({
containerName,
endpointHost,
ports,
preferredPort,
}: {
containerName: string;
endpointHost: string;
ports: DockerServicePort[] | undefined;
preferredPort?: number;
}): DockerServiceUrlCandidate[] => {
const candidates: DockerServiceUrlCandidate[] = [];
const endpointHostname = getEndpointHostname(endpointHost);
const tcpPorts = (ports ?? [])
.filter((port) => port.Type.toLowerCase() === "tcp")
.toSorted(
(left, right) => Number(right.PrivatePort === preferredPort) - Number(left.PrivatePort === preferredPort),
);
const addCandidate = (candidate: Omit<DockerServiceUrlCandidate, "id">) => {
if (candidates.some(({ url, scopes }) => url === candidate.url && scopes.join() === candidate.scopes.join()))
return;
candidates.push({
...candidate,
id: `${candidate.source}:${candidate.scopes.join("-")}:${candidate.url || "manual"}`,
});
};
for (const port of tcpPorts) {
if (port.PublicPort) {
const publishedHost = isUsablePublishedAddress(port.IP)
? port.IP
: isUsablePublishedAddress(endpointHostname ?? undefined)
? endpointHostname
: null;
if (publishedHost) {
addCandidate({
url: `http://${formatUrlHost(publishedHost)}:${port.PublicPort}`,
rank: port.PrivatePort === preferredPort ? 1 : 2,
source: isUsablePublishedAddress(port.IP) ? "publishedAddress" : "endpointHost",
scopes: ["browser", "server"],
reason: isUsablePublishedAddress(port.IP) ? "publishedAddress" : "dockerEndpointHost",
});
}
}
addCandidate({
url: `http://${containerName}:${port.PrivatePort}`,
rank: port.PrivatePort === preferredPort ? 3 : 4,
source: "containerDns",
scopes: ["server"],
reason: "sharedContainerNetwork",
});
}
addCandidate({
url: "",
rank: 99,
source: "manual",
scopes: ["browser"],
reason: "manualHostRequired",
});
return candidates.toSorted((left, right) => left.rank - right.rank);
};
export const normalizeDockerServiceUrl = (value: string | null | undefined) => {
if (!value) return null;
try {
const url = new URL(value);
url.hash = "";
return url.toString().replace(/\/$/, "").toLowerCase();
} catch {
return value.trim().replace(/\/$/, "").toLowerCase() || null;
}
};
const isUsablePublishedAddress = (value: string | undefined): value is string => {
if (!value) return false;
const host = value.toLowerCase().replace(/^\[|\]$/gu, "");
return (
!["0.0.0.0", "::", "::0", "::1", "localhost"].includes(host) &&
!host.endsWith(".localhost") &&
!/^127(?:\.\d{1,3}){3}$/.test(host) &&
!host.startsWith("::ffff:127.")
);
};
const getEndpointHostname = (host: string) => {
if (host === "socket" || host.startsWith("/") || /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(host)) return null;
try {
return new URL(`http://${host}`).hostname || null;
} catch {
return null;
}
};
const formatUrlHost = (host: string) => (host.includes(":") && !host.startsWith("[") ? `[${host}]` : host);
+4 -3
View File
@@ -5,8 +5,8 @@ import { XMLParser } from "fast-xml-parser";
import { z } from "zod/v4";
import { createDocumentationLink } from "./index";
import { integrationDocSlugs } from "./integration-doc-slugs";
import { widgetDocSlugs } from "./widget-doc-slugs";
import { getIntegrationDocumentationSlug, integrationKinds } from "../integration";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -60,7 +60,8 @@ const updateSitemapTypeFileAsync = async (sitemapPathType: string) => {
};
const slugMapPaths = [
...Object.values(integrationDocSlugs)
...integrationKinds
.map(getIntegrationDocumentationSlug)
.filter(Boolean)
.map((slug) => `/docs/integrations/${slug}`),
...Object.values(widgetDocSlugs)
@@ -89,7 +90,7 @@ const main = async () => {
paths = [];
}
paths.push("/sitemap.xml");
paths.push("/sitemap.xml", "/blog", "/search");
for (const p of slugMapPaths) {
if (!paths.includes(p)) {
paths.push(p);
@@ -280,6 +280,37 @@ export type HomarrDocumentationPath =
| "/docs/widgets/whats-up-docker"
| ""
| "/sitemap.xml"
| "/docs/integrations/autobrr"
| "/docs/integrations/jellystat"
| "/docs/integrations/scrutiny"
| "/docs/integrations/tubearchivist"
| "/docs/integrations/frigate"
| "/docs/integrations/komga"
| "/docs/integrations/netalertx"
| "/docs/integrations/jackett"
| "/docs/integrations/your-spotify"
| "/docs/integrations/romm"
| "/docs/integrations/homebox"
| "/docs/integrations/mealie"
| "/docs/integrations/xteve"
| "/docs/integrations/unmanic"
| "/docs/integrations/syncthing-relay"
| "/docs/integrations/stash"
| "/docs/integrations/prometheus"
| "/docs/integrations/plantit"
| "/docs/integrations/netdata"
| "/docs/integrations/fileflows"
| "/docs/integrations/trilium"
| "/docs/integrations/tandoor"
| "/docs/integrations/spoolman"
| "/docs/integrations/miniflux"
| "/docs/integrations/maintainerr"
| "/docs/integrations/linkwarden"
| "/docs/integrations/karakeep"
| "/docs/integrations/healthchecks"
| "/docs/integrations/gatus"
| "/docs/integrations/changedetection"
| "/docs/integrations/caddy"
| "/docs/integrations/sabnzbd"
| "/docs/integrations/nzbget"
| "/docs/integrations/deluge"
@@ -291,6 +322,7 @@ export type HomarrDocumentationPath =
| "/docs/integrations/radarr"
| "/docs/integrations/lidarr"
| "/docs/integrations/readarr"
| "/docs/integrations/bindery"
| "/docs/integrations/prowlarr"
| "/docs/integrations/bazarr"
| "/docs/integrations/jellyfin"
@@ -328,13 +360,20 @@ export type HomarrDocumentationPath =
| "/docs/integrations/audiobookshelf"
| "/docs/integrations/navidrome"
| "/docs/integrations/umami"
| "/docs/integrations/gluetun"
| "/docs/integrations/peanut"
| "/docs/integrations/beszel"
| "/docs/integrations/gluetun"
| "/docs/integrations/traefik"
| "/docs/integrations/archiveteam-warrior"
| "/docs/integrations/wazuh"
| "/docs/integrations/whats-up-docker"
| "/docs/integrations/llama-cpp"
| "/docs/widgets/stats"
| "/docs/widgets/clock"
| "/docs/widgets/weather"
| "/docs/widgets/air-quality"
| "/docs/widgets/countdown"
| "/docs/widgets/timer"
| "/docs/widgets/app"
| "/docs/widgets/iframe"
| "/docs/widgets/video"
@@ -386,4 +425,6 @@ export type HomarrDocumentationPath =
| "/docs/widgets/beszel-system-stats"
| "/docs/widgets/traefik"
| "/docs/widgets/custom-api"
| "/docs/widgets/whats-up-docker";
| "/docs/widgets/assistant"
| "/docs/widgets/whats-up-docker"
| "/docs/widgets/llama-cpp";
+11 -2
View File
@@ -1,6 +1,15 @@
import type { HomarrDocumentationPath } from "./homarr-docs-sitemap";
const documentationBaseUrl = "https://homarr.dev";
const defaultDocumentationBaseUrl = "https://homarr.dev";
const getDocumentationBaseUrl = () => {
const browserValue =
typeof document === "undefined"
? undefined
: document.querySelector<HTMLMetaElement>('meta[name="homarr-website-url"]')?.content;
const serverValue = typeof process === "undefined" ? undefined : process.env.HOMARR_WEBSITE_URL;
return (browserValue || serverValue || defaultDocumentationBaseUrl).replace(/\/+$/u, "");
};
// Please use the method so the path can be checked!
export const createDocumentationLink = (
@@ -8,7 +17,7 @@ export const createDocumentationLink = (
hashTag?: `#${string}`,
queryParams?: Record<string, string>,
) => {
const url = `${documentationBaseUrl}${path}`;
const url = `${getDocumentationBaseUrl()}${path}`;
const params = queryParams ? `?${new URLSearchParams(queryParams)}` : "";
return `${url}${params}${hashTag ?? ""}`;
};
@@ -1,59 +0,0 @@
import type { IntegrationKind } from "../integration";
export const integrationDocSlugs: Record<IntegrationKind, string | null> = {
sabNzbd: "sabnzbd",
nzbGet: "nzbget",
deluge: "deluge",
transmission: "transmission",
qBittorrent: "q-bittorent",
aria2: "aria2",
slskd: "slskd",
sonarr: "sonarr",
radarr: "radarr",
lidarr: "lidarr",
readarr: "readarr",
prowlarr: "prowlarr",
bazarr: "bazarr",
jellyfin: "jellyfin",
emby: "emby",
plex: "plex",
jellyseerr: "jellyseerr",
seerr: "seerr",
overseerr: "overseerr",
piHole: "pi-hole",
adGuardHome: "adguard-home",
technitiumDns: "technitium-dns",
homeAssistant: "home-assistant",
openmediavault: "open-media-vault",
dashDot: "dash-dot",
glances: "glances",
tdarr: "tdarr",
proxmox: "proxmox",
nextcloud: "nextcloud",
unifiController: "unifi-controller",
opnsense: "opnsense",
ntfy: "ntfy",
gotify: "gotify",
ical: "ical",
anchor: "anchor",
truenas: "truenas",
synology: "synology",
unraid: "unraid",
coolify: "coolify",
immich: "immich",
paperlessNgx: "paperless-ngx",
patchmon: "patchmon",
tracearr: "tracearr",
speedtestTracker: "speedtest-tracker",
uptimeKuma: "uptime-kuma",
audiobookshelf: "audiobookshelf",
navidrome: "navidrome",
umami: "umami",
gluetun: "gluetun",
peaNut: "peanut",
beszel: "beszel",
traefik: "traefik",
archiveTeamWarrior: null,
wud: "whats-up-docker",
mock: null,
};
@@ -1,8 +1,12 @@
import type { WidgetKind } from "../widget";
export const widgetDocSlugs: Record<WidgetKind, string | null> = {
export const widgetDocSlugs = {
stats: "stats",
clock: "clock",
weather: "weather",
airQuality: "air-quality",
countdown: "countdown",
timer: "timer",
app: "app",
iframe: "iframe",
video: "video",
@@ -55,5 +59,15 @@ export const widgetDocSlugs: Record<WidgetKind, string | null> = {
beszelSystemStats: "beszel-system-stats",
traefik: "traefik",
customApi: "custom-api",
assistant: "assistant",
wud: "whats-up-docker",
};
llamacpp: "llama-cpp",
wazuhAgents: null,
wazuhAlerts: null,
wazuhSummary: null,
wazuhTimeline: null,
wazuhTopList: null,
wazuhVulnerabilities: null,
wazuhFim: null,
wazuhAuthFailures: null,
} satisfies Record<WidgetKind, string | null>;
+4
View File
@@ -3,4 +3,8 @@ export const hotkeys = {
toggleColorScheme: "mod+j",
saveNotebook: "mod+s",
openSpotlight: "mod+k",
openSpotlightApps: "mod+p",
openSpotlightAssistant: "mod+/",
openSpotlightPreferences: "mod+shift+?",
openAssistant: "shift+a",
};
+4
View File
@@ -2,6 +2,7 @@ export * from "./board";
export * from "./integration";
export * from "./section";
export * from "./widget";
export * from "./widget-name";
export * from "./permissions";
export * from "./docker";
export * from "./kubernetes";
@@ -16,5 +17,8 @@ export * from "./widget-integration-map";
export * from "./emptysuperjson";
export * from "./hotkeys";
export * from "./docker-integration-match";
export * from "./docker-service-discovery";
export * from "./integration-url-template";
export * from "./release-provider";
export * from "./assistant";
export * from "./invariant-technical-labels";
@@ -4,14 +4,41 @@ import { integrationIconSlugs } from "./docker-integration-match";
import type { IntegrationKind } from "./integration";
import { getIntegrationDefaultPort } from "./integration";
export type UrlTemplateMode = "hostPort" | "subdomain";
export type UrlTemplateMode = "hostPort" | "subdomain" | "path";
const getSlugForKind = (kind: IntegrationKind): string => integrationIconSlugs[kind];
const buildUrl = (slug: string, host: string, mode: UrlTemplateMode, port?: number): string => {
const normalizeBaseHost = (value: string) => {
const trimmed = value.trim();
if (!trimmed) return null;
try {
const url = trimmed.includes("://") ? trimmed : `http://${trimmed}`;
const authority = url
.match(/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/iu)?.[1]
?.split("@")
.at(-1);
const explicitPort = authority?.match(/^(?:\[[^\]]+\]|[^:]+):(\d+)$/u)?.[1];
const parsed = new URL(url);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
return {
protocol: parsed.protocol,
hostname: parsed.hostname,
port: parsed.port ? Number(parsed.port) : explicitPort ? Number(explicitPort) : undefined,
pathname: parsed.pathname.replace(/\/+$/, ""),
};
} catch {
return null;
}
};
const buildUrl = (slug: string, rawHost: string, mode: UrlTemplateMode, port?: number): string => {
const base = normalizeBaseHost(rawHost);
if (!base) return "";
const effectivePort = port ?? base.port;
const modeBuilders: Record<UrlTemplateMode, () => string> = {
subdomain: () => `https://${slug}.${host}`,
hostPort: () => (port ? `http://${host}:${port}` : `http://${host}`),
subdomain: () => (base.hostname.startsWith("[") ? "" : `https://${slug}.${base.hostname}`),
hostPort: () => (effectivePort ? `http://${base.hostname}:${effectivePort}` : `http://${base.hostname}`),
path: () => `${base.protocol}//${base.hostname}${base.port ? `:${base.port}` : ""}${base.pathname}/${slug}`,
};
return modeBuilders[mode]();
};
@@ -23,7 +50,6 @@ export const buildIntegrationUrl = (
dockerPort?: number,
): string => {
const host = removeTrailingSlash(baseHost.trim());
if (!host) return "";
const port = dockerPort ?? getIntegrationDefaultPort(kind);
return buildUrl(getSlugForKind(kind), host, mode, port ?? undefined);
};
@@ -35,7 +61,6 @@ export const buildAppUrl = (
dockerPort?: number,
): string => {
const host = removeTrailingSlash(baseHost.trim());
if (!host) return "";
const slug = containerName.toLowerCase().replace(/[^a-z0-9-]/g, "-");
return buildUrl(slug, host, mode, dockerPort);
};
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,14 @@
export const invariantTechnicalLabels = {
cpu: "CPU",
docker: "Docker",
gpu: "GPU",
ram: "RAM",
os: "OS",
id: "ID",
json: "JSON",
jsonSchema: "JSON Schema",
jsx: "JSX",
url: "URL",
} as const;
export type InvariantTechnicalLabel = (typeof invariantTechnicalLabels)[keyof typeof invariantTechnicalLabels];
+6 -4
View File
@@ -1,7 +1,9 @@
import { invariantTechnicalLabels } from "./invariant-technical-labels";
export const kubernetesNodeStates = ["Ready", "NotReady"] as const;
export const kubernetesNamespaceStates = ["Active", "Terminating"] as const;
export const kubernetesResourceTypes = ["Reserved", "Used"] as const;
export const kubernetesCapacityTypes = ["Pods", "CPU", "Memory"] as const;
export const kubernetesCapacityTypes = ["Pods", invariantTechnicalLabels.cpu, "Memory"] as const;
export const kubernetesLabelResourceTypes = [
"configmaps",
"pods",
@@ -12,7 +14,6 @@ export const kubernetesLabelResourceTypes = [
"services",
"volumes",
] as const;
export type KubernetesNodeState = (typeof kubernetesNodeStates)[number];
export type KubernetesNamespaceState = (typeof kubernetesNamespaceStates)[number];
export type KubernetesResourceType = (typeof kubernetesResourceTypes)[number];
@@ -73,8 +74,8 @@ export interface KubernetesNamespace extends KubernetesBaseResource {
export interface KubernetesNode {
name: string;
status: KubernetesNodeState;
allocatableCpuPercentage: number;
allocatableRamPercentage: number;
allocatableCpuPercentage: number | null;
allocatableRamPercentage: number | null;
podsCount: number;
operatingSystem?: string;
architecture?: string;
@@ -88,6 +89,7 @@ export interface KubernetesCluster {
kubernetesVersion: string;
architecture: string;
nodeCount: number;
metricsAvailable: boolean;
capacity: KubernetesCapacity[];
}
+4 -1
View File
@@ -1,2 +1,5 @@
export const onboardingSteps = ["start", "import", "user", "group", "settings", "integrations", "finish"] as const;
export const onboardingSteps = ["start", "user", "group", "setup", "finish"] as const;
export type OnboardingStep = (typeof onboardingSteps)[number];
export const onboardingLayoutPresets = ["balanced", "wide", "focused"] as const;
export type OnboardingLayoutPreset = (typeof onboardingLayoutPresets)[number];
+136
View File
@@ -117,3 +117,139 @@ export const groupPermissionKeys = objectKeys(groupPermissions).reduce((acc, key
}
return acc;
}, [] as GroupPermissionKey[]);
/**
* Describes how each permission category is presented in the group permission matrix UI.
*
* `levels` is an ordered escalation of access: every level implies the one below it through
* {@link groupPermissionParents}, so picking level N grants everything up to N.
*
* `capabilities` are the keys that are NOT part of that ladder - "may add new resources", "may
* upload", "may put any app on a board". They can be granted on their own (e.g. "members may create
* their own boards but not see anyone else's") and some levels already imply them; use
* {@link isCapabilityImpliedByLevel} to detect that instead of hard-coding it.
*
* Only keys that genuinely imply each other may share a ladder. `app-modify-all` implies
* `app-create` but NOT `app-use-all` (only `app-full-all` does), so `app-use-all` is a capability -
* putting it in the ladder would make picking "Modify" silently grant use of every app.
*
* Together, `levels` and `capabilities` cover every key in {@link groupPermissionKeys}, so the
* matrix is a lossless representation of a group's permissions.
*/
export const permissionMatrix = {
board: { levels: ["board-view-all", "board-modify-all", "board-full-all"], capabilities: ["board-create"] },
app: { levels: ["app-modify-all", "app-full-all"], capabilities: ["app-use-all", "app-create"] },
integration: {
levels: ["integration-use-all", "integration-interact-all", "integration-full-all"],
capabilities: ["integration-create"],
},
"search-engine": {
levels: ["search-engine-modify-all", "search-engine-full-all"],
capabilities: ["search-engine-create"],
},
media: { levels: ["media-view-all", "media-full-all"], capabilities: ["media-upload"] },
other: { levels: ["other-view-logs"], capabilities: [] },
admin: { levels: ["admin"], capabilities: [] },
} as const satisfies Record<
string,
{ levels: readonly GroupPermissionKey[]; capabilities: readonly GroupPermissionKey[] }
>;
export type PermissionMatrixCategory = keyof typeof permissionMatrix;
export interface PermissionMatrixCategoryState {
/** 0 = no access, N = every key up to `permissionMatrix[category].levels[N - 1]` */
level: number;
/** The category's granted capability keys, including the ones the level already implies */
capabilities: readonly GroupPermissionKey[];
}
export type PermissionMatrixState = Record<PermissionMatrixCategory, PermissionMatrixCategoryState>;
/**
* Whether the given level already grants a capability through permission inheritance.
* For example board level 3 (`board-full-all`) implies `board-create`.
*/
export const isCapabilityImpliedByLevel = (
category: PermissionMatrixCategory,
capability: GroupPermissionKey,
level: number,
) => {
if (level <= 0) {
return false;
}
return getPermissionsWithChildren([...permissionMatrix[category].levels.slice(0, level)]).includes(capability);
};
export const permissionsToMatrixState = (permissions: GroupPermissionKey[]): PermissionMatrixState => {
const permissionSet = new Set(permissions);
return objectKeys(permissionMatrix).reduce((acc, category) => {
let level = 0;
permissionMatrix[category].levels.forEach((key, index) => {
if (permissionSet.has(key)) {
level = index + 1;
}
});
acc[category] = {
level,
capabilities: permissionMatrix[category].capabilities.filter(
(capability) => permissionSet.has(capability) || isCapabilityImpliedByLevel(category, capability, level),
),
};
return acc;
}, {} as PermissionMatrixState);
};
export const matrixStateToPermissions = (state: PermissionMatrixState): GroupPermissionKey[] => {
return objectKeys(permissionMatrix).reduce((acc, category) => {
const { level, capabilities } = state[category];
acc.push(...permissionMatrix[category].levels.slice(0, level));
// Skip capabilities the chosen level already implies, so the stored permissions stay minimal
// and a state -> permissions -> state round-trip is exact.
acc.push(...capabilities.filter((capability) => !isCapabilityImpliedByLevel(category, capability, level)));
return acc;
}, [] as GroupPermissionKey[]);
};
export interface ManagementSectionAccess {
/** May see and manage every resource of the section */
canManageAll: boolean;
/** May add new resources to the section */
canCreate: boolean;
/** May open the section at all */
canAccess: boolean;
}
/**
* A management section is reachable when the user can do at least one thing in it. Both rules live
* here so the navigation, the pages themselves and the management home statistics cannot drift
* apart - each of them consumes the same function.
*/
export const getAppManagementAccess = (permissions: readonly GroupPermissionKey[]): ManagementSectionAccess => {
const canManageAll = permissions.includes("app-modify-all");
const canCreate = permissions.includes("app-create");
return { canManageAll, canCreate, canAccess: canManageAll || canCreate };
};
/**
* `hasDelegatedFullAccess` is whether the user was granted full access to at least one specific
* integration; it has to be looked up per request, so the caller resolves it.
*/
export const getIntegrationManagementAccess = (
permissions: readonly GroupPermissionKey[],
hasDelegatedFullAccess: boolean,
): ManagementSectionAccess & { hasDelegatedFullAccess: boolean } => {
const canManageAll = permissions.includes("integration-full-all");
const canCreate = permissions.includes("integration-create");
return {
canManageAll,
canCreate,
hasDelegatedFullAccess,
canAccess: canManageAll || canCreate || hasDelegatedFullAccess,
};
};
+39 -1
View File
@@ -1,2 +1,40 @@
export const sectionKinds = ["category", "empty", "dynamic"] as const;
import type { LayoutRole } from "./board";
export const sectionKinds = ["empty", "container"] as const;
export type SectionKind = (typeof sectionKinds)[number];
export const boardLanes = ["left", "main", "right"] as const;
export type BoardLane = (typeof boardLanes)[number];
export const rootSectionOffsets = {
left: -1,
main: 0,
right: 1,
} as const satisfies Record<BoardLane, number>;
export const getRootSectionLane = (xOffset: number | null | undefined): BoardLane => {
if (xOffset === rootSectionOffsets.left) return "left";
if (xOffset === rootSectionOffsets.right) return "right";
return "main";
};
export const getBoardLaneColumnCount = (
layout: {
columnCount: number;
leftGutterColumnCount?: number | null;
rightGutterColumnCount?: number | null;
role?: LayoutRole;
},
lane: BoardLane,
) => {
const total = Math.max(1, Math.floor(layout.columnCount));
const left =
layout.role === "mobile" ? 0 : Math.min(Math.max(0, Math.floor(layout.leftGutterColumnCount ?? 0)), total - 1);
const right =
layout.role === "mobile"
? 0
: Math.min(Math.max(0, Math.floor(layout.rightGutterColumnCount ?? 0)), total - left - 1);
if (lane === "left") return left;
if (lane === "right") return right;
return total - left - right;
};
@@ -1,8 +1,18 @@
import { describe, expect, it } from "vitest";
import { getIntegrationApiKeyUrl } from "../integration";
import { objectEntries } from "@homarr/common";
import { getIntegrationApiKeyUrl, getIntegrationDocumentationUrl, integrationDefs } from "../integration";
describe("getIntegrationApiKeyUrl", () => {
it("links every user-facing integration to its Homarr setup guide", () => {
expect(
objectEntries(integrationDefs)
.filter(([kind]) => kind !== "mock" && !getIntegrationDocumentationUrl(kind))
.map(([kind]) => kind),
).toEqual([]);
});
it("builds URL for sonarr", () => {
expect(getIntegrationApiKeyUrl("http://192.168.1.10:8989", "sonarr")).toBe(
"http://192.168.1.10:8989/settings/general",
@@ -21,12 +31,52 @@ describe("getIntegrationApiKeyUrl", () => {
);
});
it("returns null for integrations without apiKeySettingsPath", () => {
expect(getIntegrationApiKeyUrl("http://localhost", "plex")).toBeNull();
it.each([
["homeAssistant", "http://homeassistant.local:8123", "http://homeassistant.local:8123/profile/security"],
["opnsense", "https://firewall.local", "https://firewall.local/system_usermanager.php"],
["ntfy", "https://ntfy.local", "https://ntfy.local/account"],
["anchor", "http://anchor.local:8080", "http://anchor.local:8080/settings"],
["unraid", "http://tower.local", "http://tower.local/Settings/ManagementAccess"],
["coolify", "https://coolify.local", "https://coolify.local/security/api-tokens"],
["immich", "http://immich.local:2283", "http://immich.local:2283/user-settings"],
["tracearr", "http://tracearr.local:7040", "http://tracearr.local:7040/settings"],
["speedtestTracker", "http://speedtest.local", "http://speedtest.local/admin/api-tokens"],
["uptimeKuma", "http://uptime.local:3001", "http://uptime.local:3001/settings/api-keys"],
] as const)("builds a verified credential URL for %s", (kind, baseUrl, expected) => {
expect(getIntegrationApiKeyUrl(baseUrl, kind)).toBe(expected);
});
it("returns null for empty URL", () => {
expect(getIntegrationApiKeyUrl("", "sonarr")).toBeNull();
it.each(["plex", "piHole", "truenas"] as const)(
"returns null when %s has no version-safe credential path",
(kind) => {
expect(getIntegrationApiKeyUrl("http://localhost", kind)).toBeNull();
},
);
it.each(["", "javascript:alert(1)", "data:text/html,test", "file:///etc/passwd"])(
"returns null for an empty or unsafe URL: %s",
(url) => {
expect(getIntegrationApiKeyUrl(url, "sonarr")).toBeNull();
},
);
it.each([
["sonarr.local:8989", "http://sonarr.local:8989/settings/general"],
["0.0.0.0:8989", "http://0.0.0.0:8989/settings/general"],
])("normalizes a self-hosted address without a scheme: %s", (url, expected) => {
expect(getIntegrationApiKeyUrl(url, "sonarr")).toBe(expected);
});
it("joins onto a reverse-proxy pathname without retaining stale query or fragment state", () => {
expect(getIntegrationApiKeyUrl("https://home.example.com/services/sonarr/?from=old#section", "sonarr")).toBe(
"https://home.example.com/services/sonarr/settings/general",
);
});
it("preserves configured credential fragments while joining pathnames", () => {
expect(getIntegrationApiKeyUrl("https://home.example.com/services/jellyfin/", "jellyfin")).toBe(
"https://home.example.com/services/jellyfin/web/index.html#!/dashboard/keys",
);
});
it("strips trailing slash from base URL", () => {
@@ -0,0 +1,93 @@
import { describe, expect, test } from "vitest";
import { buildDockerServiceUrlCandidates, matchDockerService } from "../docker-service-discovery";
describe("matchDockerService", () => {
test("reports image matches with high confidence and name fallbacks with medium confidence", () => {
expect(matchDockerService({ image: "linuxserver/sonarr:latest", name: "media" })).toEqual({
kind: "sonarr",
confidence: "high",
source: "image",
});
expect(matchDockerService({ image: "custom/media:latest", name: "sonarr" })).toEqual({
kind: "sonarr",
confidence: "medium",
source: "name",
});
});
});
describe("buildDockerServiceUrlCandidates", () => {
test("never emits wildcard or socket-path browser URLs", () => {
const candidates = buildDockerServiceUrlCandidates({
containerName: "sonarr",
endpointHost: "/var/run/docker.sock",
preferredPort: 8989,
ports: [{ IP: "0.0.0.0", PrivatePort: 8989, PublicPort: 8989, Type: "tcp" }],
});
expect(candidates.map(({ url }) => url)).not.toContain("http://0.0.0.0:8989");
expect(candidates.map(({ url }) => url)).not.toContain("http:///var/run/docker.sock:8989");
expect(candidates[0]).toMatchObject({
url: "http://sonarr:8989",
scopes: ["server"],
reason: "sharedContainerNetwork",
});
expect(candidates.at(-1)).toMatchObject({ url: "", reason: "manualHostRequired" });
});
test("uses a remote Docker endpoint hostname for wildcard published ports", () => {
const candidates = buildDockerServiceUrlCandidates({
containerName: "sonarr",
endpointHost: "docker.example.test:2375",
preferredPort: 8989,
ports: [{ IP: "0.0.0.0", PrivatePort: 8989, PublicPort: 8989, Type: "tcp" }],
});
expect(candidates[0]).toMatchObject({
url: "http://docker.example.test:8989",
scopes: ["browser", "server"],
reason: "dockerEndpointHost",
});
});
test.each(["127.0.0.1", "127.12.0.9", "::1", "::ffff:127.0.0.1", "localhost"])(
"does not advertise loopback address %s to browsers",
(address) => {
const candidates = buildDockerServiceUrlCandidates({
containerName: "sonarr",
endpointHost: "socket",
preferredPort: 8989,
ports: [{ IP: address, PrivatePort: 8989, PublicPort: 8989, Type: "tcp" }],
});
expect(candidates.some(({ source }) => source === "publishedAddress")).toBe(false);
expect(candidates.some(({ url, scopes }) => url.includes(address) && scopes.includes("browser"))).toBe(false);
},
);
test("does not use a loopback Docker endpoint as a browser URL", () => {
const candidates = buildDockerServiceUrlCandidates({
containerName: "sonarr",
endpointHost: "[::1]:2375",
preferredPort: 8989,
ports: [{ IP: "0.0.0.0", PrivatePort: 8989, PublicPort: 8989, Type: "tcp" }],
});
expect(candidates.some(({ source }) => source === "endpointHost")).toBe(false);
});
test.each(["tcp://10.0.0.5:2375", "unix:///var/run/docker.sock", "https://10.0.0.5"])(
"rejects a scheme-bearing endpoint host %s as a browser URL",
(endpointHost) => {
const candidates = buildDockerServiceUrlCandidates({
containerName: "sonarr",
endpointHost,
preferredPort: 8989,
ports: [{ IP: "0.0.0.0", PrivatePort: 8989, PublicPort: 8989, Type: "tcp" }],
});
expect(candidates.some(({ source }) => source === "endpointHost")).toBe(false);
},
);
});
@@ -30,6 +30,21 @@ describe("createDocumentationLink should generate correct URLs", () => {
});
describe("createDocumentationLink parameter validation", () => {
test("uses the server-rendered website URL at runtime", () => {
const meta = document.createElement("meta");
meta.name = "homarr-website-url";
meta.content = "https://docs.example.com/base/";
document.head.append(meta);
try {
expect(createDocumentationLink("/docs/getting-started")).toBe(
"https://docs.example.com/base/docs/getting-started",
);
} finally {
meta.remove();
}
});
test("should work with only path parameter", () => {
const result = createDocumentationLink("/docs/getting-started");
expect(result).toBe("https://homarr.dev/docs/getting-started");
@@ -0,0 +1,9 @@
import { describe, expect, it } from "vitest";
import { hotkeys } from "../hotkeys";
describe("hotkeys", () => {
it("uses the discoverable assistant shortcut", () => {
expect(hotkeys.openAssistant).toBe("shift+a");
});
});
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { getIntegrationDefaultPort } from "../integration";
import { buildIntegrationUrl } from "../integration-url-template";
import { buildAppUrl, buildIntegrationUrl } from "../integration-url-template";
describe("buildIntegrationUrl", () => {
it("builds subdomain URL", () => {
@@ -25,6 +25,44 @@ describe("buildIntegrationUrl", () => {
expect(buildIntegrationUrl("sonarr", "homelab.local///", "subdomain")).toBe("https://sonarr.homelab.local");
});
it("accepts full URLs but ignores their path when suggesting service URLs", () => {
expect(buildIntegrationUrl("sonarr", "https://home.example.com/homarr", "hostPort")).toBe(
"http://home.example.com:8989",
);
expect(buildAppUrl("My Service", "http://home.example.com/path", "subdomain")).toBe(
"https://my-service.home.example.com",
);
});
it("builds reverse-proxy path URLs and preserves the configured base path", () => {
expect(buildIntegrationUrl("sonarr", "https://home.example.com/services", "path")).toBe(
"https://home.example.com/services/sonarr",
);
expect(buildAppUrl("My Service", "home.lan/apps/", "path", 9999)).toBe("http://home.lan/apps/my-service");
});
it("replaces a supplied base port instead of producing a double port", () => {
expect(buildIntegrationUrl("sonarr", "https://home.example.com:8443/homarr", "hostPort")).toBe(
"http://home.example.com:8989",
);
expect(buildAppUrl("My Service", "https://home.example.com:8443/homarr", "hostPort")).toBe(
"http://home.example.com:8443",
);
});
it("preserves an explicitly supplied default port for an app", () => {
expect(buildAppUrl("My Service", "https://home.example.com:443/homarr", "hostPort")).toBe(
"http://home.example.com:443",
);
});
it("formats IPv6 hosts safely in host-port mode", () => {
expect(buildIntegrationUrl("sonarr", "https://[2001:db8::1]:8443/homarr", "hostPort")).toBe(
"http://[2001:db8::1]:8989",
);
expect(buildIntegrationUrl("sonarr", "[2001:db8::1]", "subdomain")).toBe("");
});
it("returns empty string for empty host", () => {
expect(buildIntegrationUrl("sonarr", "", "subdomain")).toBe("");
});
@@ -37,5 +75,11 @@ describe("buildIntegrationUrl", () => {
expect(getIntegrationDefaultPort("radarr")).toBe(7878);
expect(getIntegrationDefaultPort("prowlarr")).toBe(9696);
expect(getIntegrationDefaultPort("jellyfin")).toBe(8096);
expect(getIntegrationDefaultPort("technitiumDns")).toBe(5380);
expect(getIntegrationDefaultPort("dashDot")).toBe(3001);
expect(getIntegrationDefaultPort("gotify")).toBe(80);
expect(getIntegrationDefaultPort("peaNut")).toBe(8080);
expect(getIntegrationDefaultPort("gluetun")).toBe(8000);
expect(getIntegrationDefaultPort("archiveTeamWarrior")).toBe(8001);
});
});
@@ -1,14 +0,0 @@
import { describe, expect, it } from "vitest";
import { objectEntries } from "@homarr/common";
import { integrationDefs } from "../integration";
describe("Icon url's of integrations should be valid and return 200", () => {
objectEntries(integrationDefs).forEach(([integration, { iconUrl }]) => {
it.concurrent(`should return 200 for ${integration}`, async () => {
const res = await fetch(iconUrl);
expect(res.status).toBe(200);
});
});
});
@@ -1,7 +1,28 @@
import { describe, expect, test } from "vitest";
import type { GroupPermissionKey } from "../permissions";
import { getPermissionsWithChildren, getPermissionsWithParents } from "../permissions";
import type { GroupPermissionKey, PermissionMatrixState } from "../permissions";
import {
getAppManagementAccess,
getIntegrationManagementAccess,
getPermissionsWithChildren,
getPermissionsWithParents,
groupPermissionKeys,
isCapabilityImpliedByLevel,
matrixStateToPermissions,
permissionMatrix,
permissionsToMatrixState,
} from "../permissions";
const emptyState = (overrides: Partial<PermissionMatrixState> = {}): PermissionMatrixState => ({
board: { level: 0, capabilities: [] },
app: { level: 0, capabilities: [] },
integration: { level: 0, capabilities: [] },
"search-engine": { level: 0, capabilities: [] },
media: { level: 0, capabilities: [] },
other: { level: 0, capabilities: [] },
admin: { level: 0, capabilities: [] },
...overrides,
});
describe("getPermissionsWithParents should return the correct permissions", () => {
test.each([
@@ -45,3 +66,204 @@ describe("getPermissionsWithChildren should return the correct permissions", ()
expect(getPermissionsWithChildren(input)).toEqual(expect.arrayContaining(expectedOutput));
});
});
describe("the matrix must be able to represent every permission", () => {
test("every group permission key is covered by exactly one category", () => {
const covered = Object.values(permissionMatrix).flatMap(({ levels, capabilities }) => [...levels, ...capabilities]);
expect(covered.toSorted()).toEqual(groupPermissionKeys.toSorted());
});
test.each(groupPermissionKeys.map((key) => [key]))("expect %s to survive a round-trip on its own", (key) => {
expect(matrixStateToPermissions(permissionsToMatrixState([key]))).toContain(key);
});
test("every ladder is a real chain, so no level can fabricate a sibling permission", () => {
Object.values(permissionMatrix).forEach(({ levels }) => {
levels.forEach((key, index) => {
// Selecting a level must never grant more than that level's key already implies.
const implied = getPermissionsWithChildren([key]);
expect(levels.slice(0, index + 1).every((lower) => implied.includes(lower))).toBe(true);
});
});
});
});
describe("permissionsToMatrixState should resolve the highest present level per category", () => {
test("resolves the highest present level key", () => {
expect(permissionsToMatrixState(["board-view-all", "board-modify-all"]).board.level).toBe(2);
});
test("resolves the admin category", () => {
expect(permissionsToMatrixState(["admin"]).admin.level).toBe(1);
});
test("resolves an empty selection to all zero", () => {
const state = permissionsToMatrixState([]);
expect(Object.values(state).every(({ level, capabilities }) => level === 0 && capabilities.length === 0)).toBe(
true,
);
});
test("resolves a standalone create key without granting any level", () => {
expect(permissionsToMatrixState(["board-create"]).board).toEqual({ level: 0, capabilities: ["board-create"] });
});
test("marks a capability as granted when the level implies it", () => {
expect(permissionsToMatrixState(["board-full-all"]).board.capabilities).toEqual(["board-create"]);
expect(permissionsToMatrixState(["app-modify-all"]).app.capabilities).toEqual(["app-create"]);
expect(permissionsToMatrixState(["media-full-all"]).media.capabilities).toEqual(["media-upload"]);
});
test("does not mark a capability as granted for a level that does not imply it", () => {
expect(permissionsToMatrixState(["board-modify-all"]).board.capabilities).toEqual([]);
expect(permissionsToMatrixState(["integration-interact-all"]).integration.capabilities).toEqual([]);
});
test("app-use-all is a capability, not a level, because app-modify-all does not imply it", () => {
// Regression: modelling use as the level below modify made picking Modify silently grant the
// use of every app, which the permission graph does not do.
const state = permissionsToMatrixState(["app-modify-all"]);
expect(state.app).toEqual({ level: 1, capabilities: ["app-create"] });
expect(matrixStateToPermissions(state)).toEqual(["app-modify-all"]);
});
test("app-full-all implies both app capabilities", () => {
expect(permissionsToMatrixState(["app-full-all"]).app).toEqual({
level: 2,
capabilities: ["app-use-all", "app-create"],
});
});
});
describe("isCapabilityImpliedByLevel", () => {
test.each([
["board", "board-create", 0, false],
["board", "board-create", 1, false],
["board", "board-create", 2, false],
["board", "board-create", 3, true],
["app", "app-create", 1, true],
["app", "app-use-all", 1, false],
["app", "app-use-all", 2, true],
["integration", "integration-create", 2, false],
["integration", "integration-create", 3, true],
["search-engine", "search-engine-create", 1, true],
["media", "media-upload", 1, false],
["media", "media-upload", 2, true],
] satisfies [keyof typeof permissionMatrix, GroupPermissionKey, number, boolean][])(
"expect %s at level %i to imply %s: %s",
(category, capability, level, expected) => {
expect(isCapabilityImpliedByLevel(category, capability, level)).toBe(expected);
},
);
});
describe("matrixStateToPermissions should expand levels into permission keys", () => {
test("expands a level into the ordered level keys", () => {
expect(matrixStateToPermissions(emptyState({ board: { level: 2, capabilities: [] } }))).toEqual([
"board-view-all",
"board-modify-all",
]);
});
test("expands the admin category into the admin key", () => {
expect(matrixStateToPermissions(emptyState({ admin: { level: 1, capabilities: [] } }))).toEqual(["admin"]);
});
test("emits a standalone capability without any level", () => {
expect(matrixStateToPermissions(emptyState({ board: { level: 0, capabilities: ["board-create"] } }))).toEqual([
"board-create",
]);
});
test("emits media-upload as the capability of the media category", () => {
expect(matrixStateToPermissions(emptyState({ media: { level: 0, capabilities: ["media-upload"] } }))).toEqual([
"media-upload",
]);
});
test("emits app-use-all without granting any app level", () => {
expect(matrixStateToPermissions(emptyState({ app: { level: 0, capabilities: ["app-use-all"] } }))).toEqual([
"app-use-all",
]);
});
test("omits a capability that the chosen level already implies", () => {
expect(matrixStateToPermissions(emptyState({ board: { level: 3, capabilities: ["board-create"] } }))).toEqual([
"board-view-all",
"board-modify-all",
"board-full-all",
]);
});
});
describe("matrix helpers should round-trip stably", () => {
test.each([
[["board-view-all", "board-modify-all"]],
[["integration-use-all", "integration-interact-all", "integration-full-all"]],
[["admin"]],
[[]],
[["search-engine-modify-all", "search-engine-full-all", "media-view-all", "other-view-logs"]],
[["board-create"]],
[["media-upload"]],
[["board-create", "app-create", "integration-create", "search-engine-create", "media-upload"]],
[["board-create", "board-view-all"]],
[["app-modify-all"]],
[["app-use-all"]],
[["app-use-all", "app-modify-all"]],
] satisfies [GroupPermissionKey[]][])("expect %s to round-trip", (permissions) => {
const roundTripped = matrixStateToPermissions(permissionsToMatrixState(permissions));
expect(roundTripped).toEqual(expect.arrayContaining(permissions));
expect(roundTripped).toHaveLength(permissions.length);
});
test("expect a redundant capability key to be normalised away by the level that implies it", () => {
// app-modify-all already grants app-create, so the matrix stores the minimal set. The permission
// is not lost: getPermissionsWithChildren re-derives it whenever permissions are read.
const roundTripped = matrixStateToPermissions(permissionsToMatrixState(["app-create", "app-modify-all"]));
expect(roundTripped).toEqual(["app-modify-all"]);
expect(getPermissionsWithChildren(roundTripped)).toContain("app-create");
});
test("expect a single higher-level key to expand to its full set on round-trip", () => {
expect(matrixStateToPermissions(permissionsToMatrixState(["board-full-all"]))).toEqual([
"board-view-all",
"board-modify-all",
"board-full-all",
]);
});
});
describe("management section access", () => {
test.each([
[[], false, false],
[["app-create"], true, false],
[["app-modify-all"], true, true],
[["app-full-all", "app-modify-all"], true, true],
[["app-use-all"], false, false],
[["board-modify-all"], false, false],
] satisfies [GroupPermissionKey[], boolean, boolean][])(
"expect apps with %s to be reachable: %s, manage-all: %s",
(permissions, canAccess, canManageAll) => {
const access = getAppManagementAccess(permissions);
expect(access.canAccess).toBe(canAccess);
expect(access.canManageAll).toBe(canManageAll);
},
);
test.each([
[[], false, false, false],
[[], true, true, false],
[["integration-create"], false, true, false],
[["integration-full-all"], false, true, true],
[["integration-use-all"], false, false, false],
[["integration-interact-all"], false, false, false],
[["integration-interact-all"], true, true, false],
] satisfies [GroupPermissionKey[], boolean, boolean, boolean][])(
"expect integrations with %s and delegated access %s to be reachable: %s, manage-all: %s",
(permissions, hasDelegatedFullAccess, canAccess, canManageAll) => {
const access = getIntegrationManagementAccess(permissions, hasDelegatedFullAccess);
expect(access.canAccess).toBe(canAccess);
expect(access.canManageAll).toBe(canManageAll);
},
);
});
@@ -0,0 +1,62 @@
import { describe, expect, test } from "vitest";
import { integrationKinds } from "../integration";
import {
getWidgetKindsForIntegration,
integrationWidgetSupport,
widgetIntegrationConfigs,
widgetIntegrationLimits,
widgetIntegrationSupport,
widgetKindsWithOptionalIntegrations,
} from "../widget-integration-map";
describe("widget integration config", () => {
test("derives forward and reverse support without losing relationships", () => {
for (const [widgetKind, capability] of Object.entries(widgetIntegrationConfigs)) {
expect(widgetIntegrationSupport[widgetKind as keyof typeof widgetIntegrationSupport]).toEqual(
capability.supportedIntegrations,
);
for (const integrationKind of capability.supportedIntegrations) {
expect(integrationWidgetSupport[integrationKind]).toContain(widgetKind);
}
}
for (const integrationKind of integrationKinds) {
expect(getWidgetKindsForIntegration(integrationKind)).toEqual(integrationWidgetSupport[integrationKind]);
}
});
test("supports the mock integration for every integration-backed widget", () => {
for (const config of Object.values(widgetIntegrationConfigs)) {
expect(config.supportedIntegrations).toContain("mock");
}
});
test("derives optional connections and server selection limits", () => {
expect(widgetKindsWithOptionalIntegrations).toEqual(new Set(["calendar"]));
expect(widgetIntegrationLimits).toEqual({
"smartHome-entityState": 1,
"smartHome-executeAutomation": 1,
mediaTranscoding: 1,
"immich-serverStats": 1,
"immich-albumCarousel": 1,
paperlessNgx: 1,
patchmon: 1,
bazarr: 1,
audioStats: 1,
umami: 1,
archiveTeamWarrior: 1,
anchorNote: 1,
wud: 1,
llamacpp: 1,
wazuhAgents: 1,
wazuhAlerts: 1,
wazuhSummary: 1,
wazuhTimeline: 1,
wazuhTopList: 1,
wazuhVulnerabilities: 1,
wazuhFim: 1,
wazuhAuthFailures: 1,
});
});
});
@@ -1,70 +1,198 @@
import { objectEntries } from "@homarr/common";
import { createDocumentationLink } from "./docs";
import type { IntegrationKind } from "./integration";
import { getIntegrationKindsByCategory } from "./integration";
import { getIntegrationKindsByCategory, integrationKinds } from "./integration";
import type { WidgetKind } from "./widget";
import { widgetDefaultSizes } from "./widget";
/**
* Static mapping of widget kinds to the integration kinds they support.
* Mirrors the supportedIntegrations declared in each widget definition
* but lives in @homarr/definitions so server-side code (API layer)
* can use it without importing @homarr/widgets.
*/
export const widgetIntegrationSupport: Partial<Record<WidgetKind, readonly IntegrationKind[]>> = {
dnsHoleSummary: getIntegrationKindsByCategory("dnsHole"),
dnsHoleControls: getIntegrationKindsByCategory("dnsHole"),
"smartHome-entityState": getIntegrationKindsByCategory("smartHomeServer"),
"smartHome-executeAutomation": getIntegrationKindsByCategory("smartHomeServer"),
mediaServer: getIntegrationKindsByCategory("mediaService"),
calendar: getIntegrationKindsByCategory("calendar"),
downloads: getIntegrationKindsByCategory("downloadClient"),
"mediaRequests-requestList": getIntegrationKindsByCategory("mediaRequest"),
"mediaRequests-requestStats": getIntegrationKindsByCategory("mediaRequest"),
mediaTranscoding: getIntegrationKindsByCategory("mediaTranscoding"),
mediaMissing: getIntegrationKindsByCategory("mediaOrganizer"),
networkControllerSummary: getIntegrationKindsByCategory("networkController"),
networkControllerStatus: getIntegrationKindsByCategory("networkController"),
indexerManager: getIntegrationKindsByCategory("indexerManager"),
healthMonitoring: getIntegrationKindsByCategory("healthMonitoring").filter(
(kind) => kind !== "patchmon" && kind !== "wud",
),
firewall: getIntegrationKindsByCategory("firewall"),
notifications: getIntegrationKindsByCategory("notifications"),
mediaReleases: ["mock", "emby", "jellyfin", "plex"],
systemResources: ["dashDot", "openmediavault", "truenas", "unraid", "glances", "synology"],
systemDisks: ["dashDot", "openmediavault", "truenas", "unraid", "synology"],
coolify: ["coolify"],
"immich-serverStats": ["immich"],
"immich-albumCarousel": ["immich"],
paperlessNgx: ["paperlessNgx"],
patchmon: ["patchmon"],
bazarr: ["bazarr"],
tracearr: ["tracearr"],
speedtestTracker: ["speedtestTracker"],
uptimeKuma: ["uptimeKuma"],
audioStats: ["navidrome", "audiobookshelf"],
umami: ["umami"],
vpn: getIntegrationKindsByCategory("vpn"),
ups: getIntegrationKindsByCategory("ups"),
beszelSystemTable: ["beszel", "mock"],
beszelSystemGrid: ["beszel", "mock"],
beszelAlerts: ["beszel", "mock"],
beszelSystemStats: ["beszel", "mock"],
archiveTeamWarrior: ["archiveTeamWarrior"],
anchorNote: ["anchor"],
traefik: ["traefik"],
wud: ["wud"],
/** Integration selection shared by the widget UI and API trust boundary. */
export interface WidgetIntegrationConfig {
supportedIntegrations: IntegrationKind[];
integrationsRequired?: false;
maxIntegrations?: number;
}
const healthMonitoringGeneralIntegrationKinds = [
"openmediavault",
"dashDot",
"truenas",
"unraid",
"glances",
"synology",
] as const satisfies readonly IntegrationKind[];
export const healthMonitoringSystemIntegrationKinds = [
...healthMonitoringGeneralIntegrationKinds,
"mock",
] as const satisfies readonly IntegrationKind[];
export const healthMonitoringClusterIntegrationKinds = [
"proxmox",
"mock",
] as const satisfies readonly IntegrationKind[];
export const widgetIntegrationConfigs = {
stats: { supportedIntegrations: integrationKinds.filter((kind) => kind !== "ical") },
dnsHoleSummary: { supportedIntegrations: getIntegrationKindsByCategory("dnsHole") },
dnsHoleControls: { supportedIntegrations: getIntegrationKindsByCategory("dnsHole") },
"smartHome-entityState": {
supportedIntegrations: getIntegrationKindsByCategory("smartHomeServer"),
maxIntegrations: 1,
},
"smartHome-executeAutomation": {
supportedIntegrations: getIntegrationKindsByCategory("smartHomeServer"),
maxIntegrations: 1,
},
mediaServer: { supportedIntegrations: getIntegrationKindsByCategory("mediaService") },
calendar: { supportedIntegrations: getIntegrationKindsByCategory("calendar"), integrationsRequired: false },
downloads: { supportedIntegrations: getIntegrationKindsByCategory("downloadClient") },
"mediaRequests-requestList": { supportedIntegrations: getIntegrationKindsByCategory("mediaRequest") },
"mediaRequests-requestStats": { supportedIntegrations: getIntegrationKindsByCategory("mediaRequest") },
mediaTranscoding: {
supportedIntegrations: getIntegrationKindsByCategory("mediaTranscoding"),
maxIntegrations: 1,
},
mediaMissing: { supportedIntegrations: getIntegrationKindsByCategory("mediaOrganizer") },
networkControllerSummary: { supportedIntegrations: getIntegrationKindsByCategory("networkController") },
networkControllerStatus: { supportedIntegrations: getIntegrationKindsByCategory("networkController") },
indexerManager: { supportedIntegrations: getIntegrationKindsByCategory("indexerManager") },
healthMonitoring: {
supportedIntegrations: [...healthMonitoringGeneralIntegrationKinds, ...healthMonitoringClusterIntegrationKinds],
},
firewall: { supportedIntegrations: [...getIntegrationKindsByCategory("firewall"), "mock"] },
notifications: { supportedIntegrations: getIntegrationKindsByCategory("notifications") },
mediaReleases: { supportedIntegrations: ["mock", "emby", "jellyfin", "plex"] },
systemResources: {
supportedIntegrations: [...healthMonitoringSystemIntegrationKinds],
},
systemDisks: { supportedIntegrations: ["dashDot", "openmediavault", "truenas", "unraid", "synology", "mock"] },
beszelAlerts: { supportedIntegrations: ["beszel", "mock"] },
beszelSystemGrid: { supportedIntegrations: ["beszel", "mock"] },
beszelSystemStats: { supportedIntegrations: ["beszel", "mock"] },
beszelSystemTable: { supportedIntegrations: ["beszel", "mock"] },
coolify: { supportedIntegrations: ["coolify", "mock"] },
"immich-serverStats": { supportedIntegrations: ["immich", "mock"], maxIntegrations: 1 },
"immich-albumCarousel": { supportedIntegrations: ["immich", "mock"], maxIntegrations: 1 },
paperlessNgx: { supportedIntegrations: ["paperlessNgx", "mock"], maxIntegrations: 1 },
patchmon: { supportedIntegrations: ["patchmon", "mock"], maxIntegrations: 1 },
bazarr: { supportedIntegrations: ["bazarr", "mock"], maxIntegrations: 1 },
tracearr: { supportedIntegrations: ["tracearr", "mock"] },
speedtestTracker: { supportedIntegrations: ["speedtestTracker", "mock"] },
uptimeKuma: { supportedIntegrations: ["uptimeKuma", "mock"] },
audioStats: { supportedIntegrations: ["navidrome", "audiobookshelf", "mock"], maxIntegrations: 1 },
umami: { supportedIntegrations: ["umami", "mock"], maxIntegrations: 1 },
vpn: { supportedIntegrations: [...getIntegrationKindsByCategory("vpn"), "mock"] },
ups: { supportedIntegrations: getIntegrationKindsByCategory("ups") },
archiveTeamWarrior: { supportedIntegrations: ["archiveTeamWarrior", "mock"], maxIntegrations: 1 },
anchorNote: { supportedIntegrations: ["anchor", "mock"], maxIntegrations: 1 },
traefik: { supportedIntegrations: ["traefik", "mock"] },
wud: { supportedIntegrations: ["wud", "mock"], maxIntegrations: 1 },
llamacpp: { supportedIntegrations: ["llamacpp", "mock"], maxIntegrations: 1 },
wazuhAgents: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },
wazuhAlerts: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },
wazuhSummary: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },
wazuhTimeline: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },
wazuhTopList: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },
wazuhVulnerabilities: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },
wazuhFim: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },
wazuhAuthFailures: { supportedIntegrations: ["wazuh", "mock"], maxIntegrations: 1 },
} satisfies Partial<Record<WidgetKind, WidgetIntegrationConfig>>;
export type WidgetKindWithIntegration = keyof typeof widgetIntegrationConfigs;
export type WidgetIntegrationKind<TKind extends WidgetKindWithIntegration> =
(typeof widgetIntegrationConfigs)[TKind]["supportedIntegrations"][number];
export const getWidgetIntegrationConfig = <TKind extends WidgetKindWithIntegration>(
kind: TKind,
): (typeof widgetIntegrationConfigs)[TKind] => widgetIntegrationConfigs[kind];
const widgetIntegrationConfigEntries = objectEntries(widgetIntegrationConfigs);
const createWidgetIntegrationSupport = () => {
const result: Partial<Record<WidgetKind, readonly IntegrationKind[]>> = {};
for (const [kind, config] of widgetIntegrationConfigEntries) result[kind] = config.supportedIntegrations;
return result;
};
export const getWidgetKindsForIntegration = (integrationKind: IntegrationKind): WidgetKind[] => {
const result: WidgetKind[] = [];
for (const [widgetKind, supportedIntegrations] of Object.entries(widgetIntegrationSupport)) {
if (supportedIntegrations.includes(integrationKind)) {
result.push(widgetKind as WidgetKind);
}
export const widgetIntegrationSupport = createWidgetIntegrationSupport();
/** Widgets that remain useful without a configured integration. */
export const widgetKindsWithOptionalIntegrations = new Set<WidgetKind>(
widgetIntegrationConfigEntries
.filter(([, config]) => "integrationsRequired" in config && config.integrationsRequired === false)
.map(([kind]) => kind),
);
const createWidgetIntegrationLimits = () => {
const result: Partial<Record<WidgetKind, number>> = {};
for (const [kind, config] of widgetIntegrationConfigEntries) {
if ("maxIntegrations" in config) result[kind] = config.maxIntegrations;
}
return result;
};
export const widgetIntegrationLimits = createWidgetIntegrationLimits();
export type WidgetIntegrationIssue =
| { code: "integration-not-supported" }
| { code: "integration-required" }
| { code: "incompatible-integration"; incompatibleKinds: IntegrationKind[] }
| { code: "integration-limit"; limit: number };
export const getWidgetIntegrationIssue = (
widgetKind: WidgetKind,
selectedIntegrationKinds: readonly IntegrationKind[],
): WidgetIntegrationIssue | null => {
const supportedIntegrations = widgetIntegrationSupport[widgetKind];
const integrationLimit = widgetIntegrationLimits[widgetKind] ?? Number.POSITIVE_INFINITY;
if (selectedIntegrationKinds.length > integrationLimit) {
return { code: "integration-limit", limit: integrationLimit };
}
if (supportedIntegrations === undefined && selectedIntegrationKinds.length > 0) {
return { code: "integration-not-supported" };
}
if (
supportedIntegrations !== undefined &&
selectedIntegrationKinds.length === 0 &&
!widgetKindsWithOptionalIntegrations.has(widgetKind)
) {
return { code: "integration-required" };
}
const incompatibleKinds = selectedIntegrationKinds.filter((kind) => !supportedIntegrations?.includes(kind));
if (incompatibleKinds.length === 0) return null;
return { code: "incompatible-integration", incompatibleKinds };
};
export const getWidgetIntegrationIssueMessage = (widgetKind: WidgetKind, issue: WidgetIntegrationIssue) => {
if (issue.code === "integration-limit") {
return `${widgetKind} supports at most ${issue.limit} integration${issue.limit === 1 ? "" : "s"}`;
}
if (issue.code === "integration-not-supported") return `${widgetKind} does not support integrations`;
if (issue.code === "integration-required") return `${widgetKind} requires an integration`;
return `${widgetKind} does not support integration kind${issue.incompatibleKinds.length === 1 ? "" : "s"}: ${issue.incompatibleKinds.join(", ")}`;
};
const createIntegrationWidgetSupport = () => {
const result = {} as Record<IntegrationKind, readonly WidgetKind[]>;
for (const integrationKind of integrationKinds) {
result[integrationKind] = widgetIntegrationConfigEntries
.filter(([, config]) => supportsIntegration(config, integrationKind))
.map(([widgetKind]) => widgetKind);
}
return result;
};
const supportsIntegration = (config: WidgetIntegrationConfig, integrationKind: IntegrationKind) =>
config.supportedIntegrations.includes(integrationKind);
export const integrationWidgetSupport = createIntegrationWidgetSupport();
export const getWidgetKindsForIntegration = (integrationKind: IntegrationKind): WidgetKind[] => {
return [...integrationWidgetSupport[integrationKind]];
};
export interface DefaultWidgetConfig {
kind: WidgetKind;
width: number;
@@ -75,10 +203,15 @@ export interface DefaultWidgetConfig {
export const defaultWidgetConfigs: DefaultWidgetConfig[] = [
{ kind: "clock", width: 2, height: 1 },
{ kind: "weather", width: 2, height: 1, options: { showCity: true, hasForecast: true, forecastDayCount: 3 } },
{ kind: "weather", width: 2, height: 1, options: { showHumidity: false, showCity: false, hasForecast: false } },
{ kind: "bookmarks", width: 2, height: 2, options: { title: "Useful Links", layout: "grid", openNewTab: true } },
];
const defaultWidgetConfigByKind = new Map(defaultWidgetConfigs.map((config) => [config.kind, config]));
export const getDefaultWidgetConfig = (kind: WidgetKind): DefaultWidgetConfig =>
defaultWidgetConfigByKind.get(kind) ?? { kind, ...(widgetDefaultSizes[kind] ?? { width: 1, height: 1 }) };
export const generalWidgets: WidgetKind[] = defaultWidgetConfigs
.filter((config) => !config.skip)
.map((config) => config.kind);
+24
View File
@@ -0,0 +1,24 @@
import type { IntegrationKind } from "./integration";
import { getIntegrationName } from "./integration";
import type { WidgetKind } from "./widget";
const widgetIntegrationKinds: Partial<Record<WidgetKind, IntegrationKind>> = {
coolify: "coolify",
tracearr: "tracearr",
paperlessNgx: "paperlessNgx",
patchmon: "patchmon",
bazarr: "bazarr",
uptimeKuma: "uptimeKuma",
traefik: "traefik",
};
export const getWidgetIntegrationName = (kind: WidgetKind): string | undefined => {
const integrationKind = widgetIntegrationKinds[kind];
if (!integrationKind) return undefined;
return getIntegrationName(integrationKind);
};
type WidgetNameTranslator = (key: never) => string;
export const getWidgetName = (kind: WidgetKind, translate: WidgetNameTranslator): string =>
getWidgetIntegrationName(kind) ?? translate(`widget.${kind}.name` as never);
+38 -1
View File
@@ -1,6 +1,10 @@
export const widgetKinds = [
"stats",
"clock",
"weather",
"airQuality",
"countdown",
"timer",
"app",
"iframe",
"video",
@@ -53,15 +57,48 @@ export const widgetKinds = [
"beszelSystemStats",
"traefik",
"customApi",
"assistant",
"wud",
"llamacpp",
"wazuhAgents",
"wazuhAlerts",
"wazuhSummary",
"wazuhTimeline",
"wazuhTopList",
"wazuhVulnerabilities",
"wazuhFim",
"wazuhAuthFailures",
] as const;
export type WidgetKind = (typeof widgetKinds)[number];
export const widgetDefaultSizes: Partial<Record<WidgetKind, { width: number; height: number }>> = {
clock: { width: 2, height: 1 },
weather: { width: 2, height: 1 },
airQuality: { width: 2, height: 1 },
calendar: { width: 2, height: 2 },
countdown: { width: 2, height: 1 },
customApi: { width: 3, height: 2 },
downloads: { width: 4, height: 2 },
indexerManager: { width: 2, height: 3 },
timer: { width: 2, height: 1 },
bookmarks: { width: 2, height: 2 },
uptimeKuma: { width: 2, height: 3 },
audioStats: { width: 2, height: 2 },
paperlessNgx: { width: 2, height: 2 },
patchmon: { width: 2, height: 2 },
mediaMissing: { width: 4, height: 3 },
mediaServer: { width: 3, height: 2 },
"mediaRequests-requestList": { width: 3, height: 2 },
"mediaRequests-requestStats": { width: 2, height: 2 },
mediaMissing: { width: 2, height: 2 },
bazarr: { width: 2, height: 2 },
assistant: { width: 10, height: 4 },
wazuhAgents: { width: 6, height: 4 },
wazuhAlerts: { width: 4, height: 4 },
wazuhSummary: { width: 3, height: 3 },
wazuhTimeline: { width: 6, height: 3 },
wazuhTopList: { width: 3, height: 3 },
wazuhVulnerabilities: { width: 4, height: 4 },
wazuhFim: { width: 4, height: 3 },
wazuhAuthFailures: { width: 4, height: 3 },
};