Compare commits

..
185 changed files with 3822 additions and 11662 deletions

No files matched your search

-4
View File
@@ -28,10 +28,6 @@ DB_URL='FULL_PATH_TO_YOUR_SQLITE_DB_FILE'
# DB_PASSWORD='password' # DB_PASSWORD='password'
# DB_NAME='name-of-database' # DB_NAME='name-of-database'
# The below path can be used to store trusted certificates during development, it is not required and can be left empty.
# If it is used, please use the full path to the directory where the certificates are stored.
# LOCAL_CERTIFICATE_PATH='FULL_PATH_TO_CERTIFICATES'
TURBO_TELEMETRY_DISABLED=1 TURBO_TELEMETRY_DISABLED=1
# Configure logging to use winston logger # Configure logging to use winston logger
-3
View File
@@ -31,9 +31,6 @@ body:
label: Version label: Version
description: What version of Homarr are you running? description: What version of Homarr are you running?
options: options:
- 1.1.0
- 1.0.1
- 1.0.0
- 1.0.0-beta - 1.0.0-beta
- Other (describe in "additional information") - Other (describe in "additional information")
default: 0 default: 0
-5
View File
@@ -6,11 +6,6 @@
matchPackagePatterns: ["^@homarr/"], matchPackagePatterns: ["^@homarr/"],
enabled: false, enabled: false,
}, },
// Disable Dockerode updates see https://github.com/apocas/dockerode/issues/787
{
matchPackagePatterns: ["^dockerode$"],
enabled: false,
},
{ {
matchUpdateTypes: ["minor", "patch", "pin", "digest"], matchUpdateTypes: ["minor", "patch", "pin", "digest"],
automerge: true, automerge: true,
@@ -37,7 +37,7 @@ jobs:
token: ${{ github.token }} token: ${{ github.token }}
branch: dev branch: dev
- name: Create pull request - name: Create pull request
run: 'gh pr create --title "chore(release): automatic release ${{ steps.semver.outputs.next }}" --body "**This is an automatic release**.<br/>Manual action may be required for major bumps.<br/>Detected change to be ``${{ steps.semver.outputs.bump }}``<br/>Bump version from ``${{ steps.semver.outputs.current }}`` to ``${{ steps.semver.outputs.next }}``" --base main --head dev --label automerge' run: 'gh pr create --title "chore(release): automatic release ${{ steps.semver.outputs.next }}" --body "**This is an automatic release**.<br/>Manual action may be required for major bumps.<br/>Detected change to be ``${{ steps.semver.outputs.bump }}``<br/>Bump version from ``${{ steps.semver.outputs.current }}`` to ``${{ steps.semver.outputs.next }}``" --base beta --head dev --label automerge'
env: env:
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
- name: Discord notification - name: Discord notification
+1 -1
View File
@@ -1 +1 @@
22.13.1 22.13.0
+1 -1225
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,4 +1,4 @@
FROM node:22.13.1-alpine AS base FROM node:22.13.0-alpine AS base
FROM base AS builder FROM base AS builder
RUN apk add --no-cache libc6-compat RUN apk add --no-cache libc6-compat
-1
View File
@@ -2,7 +2,6 @@
import "@homarr/auth/env"; import "@homarr/auth/env";
import "@homarr/db/env"; import "@homarr/db/env";
import "@homarr/common/env"; import "@homarr/common/env";
import "@homarr/docker/env";
import type { NextConfig } from "next"; import type { NextConfig } from "next";
import MillionLint from "@million/lint"; import MillionLint from "@million/lint";
+16 -19
View File
@@ -18,15 +18,12 @@
"@homarr/analytics": "workspace:^0.1.0", "@homarr/analytics": "workspace:^0.1.0",
"@homarr/api": "workspace:^0.1.0", "@homarr/api": "workspace:^0.1.0",
"@homarr/auth": "workspace:^0.1.0", "@homarr/auth": "workspace:^0.1.0",
"@homarr/certificates": "workspace:^0.1.0",
"@homarr/common": "workspace:^0.1.0", "@homarr/common": "workspace:^0.1.0",
"@homarr/cron-job-status": "workspace:^0.1.0", "@homarr/cron-job-status": "workspace:^0.1.0",
"@homarr/db": "workspace:^0.1.0", "@homarr/db": "workspace:^0.1.0",
"@homarr/definitions": "workspace:^0.1.0", "@homarr/definitions": "workspace:^0.1.0",
"@homarr/docker": "workspace:^0.1.0",
"@homarr/form": "workspace:^0.1.0", "@homarr/form": "workspace:^0.1.0",
"@homarr/gridstack": "^1.12.0", "@homarr/gridstack": "^1.11.3",
"@homarr/icons": "workspace:^0.1.0",
"@homarr/integrations": "workspace:^0.1.0", "@homarr/integrations": "workspace:^0.1.0",
"@homarr/log": "workspace:^", "@homarr/log": "workspace:^",
"@homarr/modals": "workspace:^0.1.0", "@homarr/modals": "workspace:^0.1.0",
@@ -41,18 +38,18 @@
"@homarr/ui": "workspace:^0.1.0", "@homarr/ui": "workspace:^0.1.0",
"@homarr/validation": "workspace:^0.1.0", "@homarr/validation": "workspace:^0.1.0",
"@homarr/widgets": "workspace:^0.1.0", "@homarr/widgets": "workspace:^0.1.0",
"@mantine/colors-generator": "^7.16.1", "@mantine/colors-generator": "^7.16.0",
"@mantine/core": "^7.16.1", "@mantine/core": "^7.16.0",
"@mantine/dropzone": "^7.16.1", "@mantine/dropzone": "^7.16.0",
"@mantine/hooks": "^7.16.1", "@mantine/hooks": "^7.16.0",
"@mantine/modals": "^7.16.1", "@mantine/modals": "^7.16.0",
"@mantine/tiptap": "^7.16.1", "@mantine/tiptap": "^7.16.0",
"@million/lint": "1.0.14", "@million/lint": "1.0.14",
"@t3-oss/env-nextjs": "^0.11.1", "@t3-oss/env-nextjs": "^0.11.1",
"@tabler/icons-react": "^3.29.0", "@tabler/icons-react": "^3.28.1",
"@tanstack/react-query": "^5.64.2", "@tanstack/react-query": "^5.64.1",
"@tanstack/react-query-devtools": "^5.64.2", "@tanstack/react-query-devtools": "^5.64.1",
"@tanstack/react-query-next-experimental": "5.64.2", "@tanstack/react-query-next-experimental": "5.64.1",
"@trpc/client": "next", "@trpc/client": "next",
"@trpc/next": "next", "@trpc/next": "next",
"@trpc/react-query": "next", "@trpc/react-query": "next",
@@ -64,11 +61,11 @@
"clsx": "^2.1.1", "clsx": "^2.1.1",
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"dotenv": "^16.4.7", "dotenv": "^16.4.7",
"flag-icons": "^7.3.2", "flag-icons": "^7.2.3",
"glob": "^11.0.1", "glob": "^11.0.1",
"jotai": "^2.11.1", "jotai": "^2.11.0",
"mantine-react-table": "2.0.0-beta.8", "mantine-react-table": "2.0.0-beta.8",
"next": "15.1.6", "next": "15.1.4",
"postcss-preset-mantine": "^1.17.0", "postcss-preset-mantine": "^1.17.0",
"prismjs": "^1.29.0", "prismjs": "^1.29.0",
"react": "19.0.0", "react": "19.0.0",
@@ -85,9 +82,9 @@
"@homarr/prettier-config": "workspace:^0.1.0", "@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0", "@homarr/tsconfig": "workspace:^0.1.0",
"@types/chroma-js": "3.1.0", "@types/chroma-js": "3.1.0",
"@types/node": "^22.10.10", "@types/node": "^22.10.6",
"@types/prismjs": "^1.26.5", "@types/prismjs": "^1.26.5",
"@types/react": "19.0.8", "@types/react": "19.0.7",
"@types/react-dom": "19.0.3", "@types/react-dom": "19.0.3",
"@types/swagger-ui-react": "^4.18.3", "@types/swagger-ui-react": "^4.18.3",
"concurrently": "^9.1.2", "concurrently": "^9.1.2",
@@ -94,7 +94,6 @@ export function TRPCReactProvider(props: PropsWithChildren) {
false: unstable_httpBatchStreamLink({ false: unstable_httpBatchStreamLink({
transformer: superjson, transformer: superjson,
url: getTrpcUrl(), url: getTrpcUrl(),
maxURLLength: 2083, // Suggested by tRPC: https://trpc.io/docs/client/links/httpBatchLink#setting-a-maximum-url-length
headers: createHeadersCallbackForSource("nextjs-react (json)"), headers: createHeadersCallbackForSource("nextjs-react (json)"),
}), }),
}), }),
@@ -2,7 +2,6 @@
import type { MouseEvent } from "react"; import type { MouseEvent } from "react";
import { useCallback, useEffect } from "react"; import { useCallback, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Group, Menu } from "@mantine/core"; import { Group, Menu } from "@mantine/core";
import { useHotkeys } from "@mantine/hooks"; import { useHotkeys } from "@mantine/hooks";
@@ -10,11 +9,9 @@ import {
IconBox, IconBox,
IconBoxAlignTop, IconBoxAlignTop,
IconChevronDown, IconChevronDown,
IconLayoutBoard,
IconPencil, IconPencil,
IconPencilOff, IconPencilOff,
IconPlus, IconPlus,
IconReplace,
IconResize, IconResize,
IconSettings, IconSettings,
} from "@tabler/icons-react"; } from "@tabler/icons-react";
@@ -52,8 +49,6 @@ export const BoardContentHeaderActions = () => {
<HeaderButton href={`/boards/${board.name}/settings`}> <HeaderButton href={`/boards/${board.name}/settings`}>
<IconSettings stroke={1.5} /> <IconSettings stroke={1.5} />
</HeaderButton> </HeaderButton>
<SelectBoardsMenu />
</> </>
); );
}; };
@@ -156,32 +151,6 @@ const EditModeMenu = () => {
); );
}; };
const SelectBoardsMenu = () => {
const { data: boards = [] } = clientApi.board.getAllBoards.useQuery();
return (
<Menu position="bottom-end" withArrow>
<Menu.Target>
<HeaderButton w="auto" px={4}>
<IconReplace stroke={1.5} />
</HeaderButton>
</Menu.Target>
<Menu.Dropdown style={{ transform: "translate(-7px, 0)" }}>
{boards.map((board) => (
<Menu.Item
key={board.id}
component={Link}
href={`/boards/${board.name}`}
leftSection={<IconLayoutBoard size={20} />}
>
{board.name}
</Menu.Item>
))}
</Menu.Dropdown>
</Menu>
);
};
const usePreventLeaveWithDirty = (isDirty: boolean) => { const usePreventLeaveWithDirty = (isDirty: boolean) => {
const t = useI18n(); const t = useI18n();
const { openConfirmModal } = useConfirmModal(); const { openConfirmModal } = useConfirmModal();
@@ -1,4 +1,4 @@
import { IconGrid3x3, IconKey, IconPassword, IconServer, IconUser } from "@tabler/icons-react"; import { IconKey, IconPassword, IconUser } from "@tabler/icons-react";
import type { IntegrationSecretKind } from "@homarr/definitions"; import type { IntegrationSecretKind } from "@homarr/definitions";
import type { TablerIcon } from "@homarr/ui"; import type { TablerIcon } from "@homarr/ui";
@@ -7,6 +7,4 @@ export const integrationSecretIcons = {
username: IconUser, username: IconUser,
apiKey: IconKey, apiKey: IconKey,
password: IconPassword, password: IconPassword,
realm: IconServer,
tokenId: IconGrid3x3,
} satisfies Record<IntegrationSecretKind, TablerIcon>; } satisfies Record<IntegrationSecretKind, TablerIcon>;
@@ -15,9 +15,7 @@ export const IntegrationCreateDropdownContent = () => {
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const filteredKinds = useMemo(() => { const filteredKinds = useMemo(() => {
return integrationKinds.filter((kind) => return integrationKinds.filter((kind) => kind.includes(search.toLowerCase()));
getIntegrationName(kind).toLowerCase().includes(search.toLowerCase().trim()),
);
}, [search]); }, [search]);
const handleSearch = React.useCallback( const handleSearch = React.useCallback(
@@ -31,7 +29,6 @@ export const IntegrationCreateDropdownContent = () => {
leftSection={<IconSearch stroke={1.5} size={20} />} leftSection={<IconSearch stroke={1.5} size={20} />}
placeholder={t("integration.page.list.search")} placeholder={t("integration.page.list.search")}
value={search} value={search}
data-autofocus
onChange={handleSearch} onChange={handleSearch}
/> />
@@ -102,15 +102,7 @@ export default async function IntegrationsPage(props: IntegrationsPageProps) {
const IntegrationSelectMenu = ({ children }: PropsWithChildren) => { const IntegrationSelectMenu = ({ children }: PropsWithChildren) => {
return ( return (
<Menu <Menu width={256} trapFocus position="bottom-end" withinPortal shadow="md" keepMounted={false}>
width={256}
trapFocus
position="bottom-end"
withinPortal
shadow="md"
keepMounted={false}
withInitialFocusPlaceholder={false}
>
{children} {children}
<MenuDropdown> <MenuDropdown>
<IntegrationCreateDropdownContent /> <IntegrationCreateDropdownContent />
@@ -6,7 +6,6 @@ import {
IconBrandDiscord, IconBrandDiscord,
IconBrandDocker, IconBrandDocker,
IconBrandGithub, IconBrandGithub,
IconCertificate,
IconGitFork, IconGitFork,
IconHome, IconHome,
IconInfoSmall, IconInfoSmall,
@@ -120,12 +119,6 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
href: "/manage/tools/logs", href: "/manage/tools/logs",
hidden: !session?.user.permissions.includes("other-view-logs"), hidden: !session?.user.permissions.includes("other-view-logs"),
}, },
{
label: t("items.tools.items.certificates"),
icon: IconCertificate,
href: "/manage/tools/certificates",
hidden: !session?.user.permissions.includes("admin"),
},
{ {
label: t("items.tools.items.tasks"), label: t("items.tools.items.tasks"),
icon: IconReport, icon: IconReport,
@@ -153,7 +146,7 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
{ {
label: t("items.help.items.submitIssue"), label: t("items.help.items.submitIssue"),
icon: IconBrandGithub, icon: IconBrandGithub,
href: "https://github.com/homarr-labs/homarr/issues/new/choose", href: "https://github.com/ajnart/homarr/issues/new/choose",
external: true, external: true,
}, },
{ {
@@ -165,7 +158,7 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
{ {
label: t("items.help.items.sourceCode"), label: t("items.help.items.sourceCode"),
icon: IconGitFork, icon: IconGitFork,
href: "https://github.com/homarr-labs/homarr", href: "https://github.com/ajnart/homarr",
external: true, external: true,
}, },
], ],
@@ -15,11 +15,6 @@ export const CopyMedia = ({ media }: CopyMediaProps) => {
const url = typeof window !== "undefined" ? `${window.location.origin}/api/user-medias/${media.id}` : ""; const url = typeof window !== "undefined" ? `${window.location.origin}/api/user-medias/${media.id}` : "";
// Clipboard only works on localhost or secure connections (https)
if (url.startsWith("http://") && !url.startsWith("http://localhost")) {
return null;
}
return ( return (
<CopyButton value={url}> <CopyButton value={url}>
{({ copy, copied }) => ( {({ copy, copied }) => (
@@ -1,28 +1,13 @@
import Image from "next/image"; import Image from "next/image";
import Link from "next/link"; import Link from "next/link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { import { Anchor, Group, Stack, Table, TableTbody, TableTd, TableTh, TableThead, TableTr, Title } from "@mantine/core";
ActionIcon,
Anchor,
Group,
Stack,
Table,
TableTbody,
TableTd,
TableTh,
TableThead,
TableTr,
Title,
Tooltip,
} from "@mantine/core";
import { IconExternalLink } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api"; import type { RouterOutputs } from "@homarr/api";
import { api } from "@homarr/api/server"; import { api } from "@homarr/api/server";
import { auth } from "@homarr/auth/next"; import { auth } from "@homarr/auth/next";
import { humanFileSize } from "@homarr/common"; import { humanFileSize } from "@homarr/common";
import type { inferSearchParamsFromSchema } from "@homarr/common/types"; import type { inferSearchParamsFromSchema } from "@homarr/common/types";
import { createLocalImageUrl } from "@homarr/icons/local";
import { getI18n } from "@homarr/translation/server"; import { getI18n } from "@homarr/translation/server";
import { SearchInput, TablePagination, UserAvatar } from "@homarr/ui"; import { SearchInput, TablePagination, UserAvatar } from "@homarr/ui";
import { z } from "@homarr/validation"; import { z } from "@homarr/validation";
@@ -106,14 +91,13 @@ interface RowProps {
const Row = async ({ media }: RowProps) => { const Row = async ({ media }: RowProps) => {
const session = await auth(); const session = await auth();
const t = await getI18n();
const canDelete = media.creatorId === session?.user.id || session?.user.permissions.includes("media-full-all"); const canDelete = media.creatorId === session?.user.id || session?.user.permissions.includes("media-full-all");
return ( return (
<TableTr> <TableTr>
<TableTd w={64}> <TableTd w={64}>
<Image <Image
src={createLocalImageUrl(media.id)} src={`/api/user-medias/${media.id}`}
alt={media.name} alt={media.name}
width={64} width={64}
height={64} height={64}
@@ -137,17 +121,6 @@ const Row = async ({ media }: RowProps) => {
<TableTd w={64}> <TableTd w={64}>
<Group wrap="nowrap" gap="xs"> <Group wrap="nowrap" gap="xs">
<CopyMedia media={media} /> <CopyMedia media={media} />
<Tooltip label={t("media.action.open.label")} openDelay={500}>
<ActionIcon
component="a"
href={createLocalImageUrl(media.id)}
target="_blank"
color="gray"
variant="subtle"
>
<IconExternalLink size={16} stroke={1.5} />
</ActionIcon>
</Tooltip>
{canDelete && <DeleteMedia media={media} />} {canDelete && <DeleteMedia media={media} />}
</Group> </Group>
</TableTd> </TableTd>
@@ -1,81 +0,0 @@
"use client";
import { Button, FileInput, Group, Stack } from "@mantine/core";
import { IconCertificate } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { revalidatePathActionAsync } from "@homarr/common/client";
import { useZodForm } from "@homarr/form";
import { createModal, useModalAction } from "@homarr/modals";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client";
import { superRefineCertificateFile, z } from "@homarr/validation";
export const AddCertificateButton = () => {
const { openModal } = useModalAction(AddCertificateModal);
const t = useI18n();
const handleClick = () => {
openModal({});
};
return <Button onClick={handleClick}>{t("certificate.action.create.label")}</Button>;
};
const AddCertificateModal = createModal(({ actions }) => {
const t = useI18n();
const form = useZodForm(
z.object({
file: z.instanceof(File).nullable().superRefine(superRefineCertificateFile),
}),
{
initialValues: {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
file: null!,
},
},
);
const { mutateAsync } = clientApi.certificates.addCertificate.useMutation();
return (
<form
onSubmit={form.onSubmit(async (values) => {
const formData = new FormData();
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
formData.set("file", values.file!);
await mutateAsync(formData, {
async onSuccess() {
showSuccessNotification({
title: t("certificate.action.create.notification.success.title"),
message: t("certificate.action.create.notification.success.message"),
});
await revalidatePathActionAsync("/manage/tools/certificates");
actions.closeModal();
},
onError() {
showErrorNotification({
title: t("certificate.action.create.notification.error.title"),
message: t("certificate.action.create.notification.error.message"),
});
},
});
})}
>
<Stack>
<FileInput leftSection={<IconCertificate size={16} />} {...form.getInputProps("file")} />
<Group justify="end">
<Button onClick={actions.closeModal} variant="subtle" color="gray">
{t("common.action.cancel")}
</Button>
<Button type="submit" loading={form.submitting}>
{t("common.action.add")}
</Button>
</Group>
</Stack>
</form>
);
}).withOptions({
defaultTitle(t) {
return t("certificate.action.create.label");
},
});
@@ -1,54 +0,0 @@
"use client";
import { ActionIcon } from "@mantine/core";
import { IconTrash } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { revalidatePathActionAsync } from "@homarr/common/client";
import { useConfirmModal } from "@homarr/modals";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client";
interface RemoveCertificateProps {
fileName: string;
}
export const RemoveCertificate = ({ fileName }: RemoveCertificateProps) => {
const { openConfirmModal } = useConfirmModal();
const { mutateAsync } = clientApi.certificates.removeCertificate.useMutation();
const t = useI18n();
const handleClick = () => {
openConfirmModal({
title: t("certificate.action.remove.label"),
children: t("certificate.action.remove.confirm"),
// eslint-disable-next-line no-restricted-syntax
async onConfirm() {
await mutateAsync(
{ fileName },
{
async onSuccess() {
showSuccessNotification({
title: t("certificate.action.remove.notification.success.title"),
message: t("certificate.action.remove.notification.success.message"),
});
await revalidatePathActionAsync("/manage/tools/certificates");
},
onError() {
showErrorNotification({
title: t("certificate.action.remove.notification.error.title"),
message: t("certificate.action.remove.notification.error.message"),
});
},
},
);
},
});
};
return (
<ActionIcon onClick={handleClick} color="red" variant="subtle">
<IconTrash color="red" size={16} />
</ActionIcon>
);
};
@@ -1,104 +0,0 @@
import { X509Certificate } from "node:crypto";
import { notFound } from "next/navigation";
import { Card, Group, SimpleGrid, Stack, Text, Title } from "@mantine/core";
import { IconCertificate, IconCertificateOff } from "@tabler/icons-react";
import dayjs from "dayjs";
import { auth } from "@homarr/auth/next";
import { loadCustomRootCertificatesAsync } from "@homarr/certificates/server";
import { getMantineColor } from "@homarr/common";
import type { SupportedLanguage } from "@homarr/translation";
import { getI18n } from "@homarr/translation/server";
import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
import { NoResults } from "~/components/no-results";
import { AddCertificateButton } from "./_components/add-certificate";
import { RemoveCertificate } from "./_components/remove-certificate";
interface CertificatesPageProps {
params: Promise<{
locale: SupportedLanguage;
}>;
}
export default async function CertificatesPage({ params }: CertificatesPageProps) {
const session = await auth();
if (!session?.user.permissions.includes("admin")) {
notFound();
}
const { locale } = await params;
const t = await getI18n();
const certificates = await loadCustomRootCertificatesAsync();
const x509Certificates = certificates
.map((cert) => ({
...cert,
x509: new X509Certificate(cert.content),
}))
.sort((certA, certB) => certA.x509.validToDate.getTime() - certB.x509.validToDate.getTime());
return (
<>
<DynamicBreadcrumb />
<Stack>
<Group justify="space-between">
<Stack gap={4}>
<Title>{t("certificate.page.list.title")}</Title>
<Text>{t("certificate.page.list.description")}</Text>
</Stack>
<AddCertificateButton />
</Group>
{x509Certificates.length === 0 && (
<NoResults icon={IconCertificateOff} title={t("certificate.page.list.noResults.title")} />
)}
<SimpleGrid cols={{ sm: 1, lg: 2, xl: 3 }} spacing="lg">
{x509Certificates.map((cert) => (
<Card key={cert.x509.fingerprint} withBorder>
<Group wrap="nowrap">
<IconCertificate
color={getMantineColor(iconColor(cert.x509.validToDate), 6)}
style={{ minWidth: 32 }}
size={32}
stroke={1.5}
/>
<Stack flex={1} gap="xs" maw="calc(100% - 48px)">
<Group justify="space-between" wrap="nowrap">
<Text fw={500} lineClamp={1} style={{ wordBreak: "break-all" }}>
{cert.x509.subject}
</Text>
<Text c="gray.6" ta="end" size="sm">
{cert.fileName}
</Text>
</Group>
<Group justify="space-between">
<Text size="sm" c="gray.6" title={cert.x509.validToDate.toISOString()}>
{t("certificate.page.list.expires", {
when: new Intl.RelativeTimeFormat(locale).format(
dayjs(cert.x509.validToDate).diff(dayjs(), "days"),
"days",
),
})}
</Text>
<RemoveCertificate fileName={cert.fileName} />
</Group>
</Stack>
</Group>
</Card>
))}
</SimpleGrid>
</Stack>
</>
);
}
const iconColor = (validTo: Date) => {
const daysUntilInvalid = dayjs(validTo).diff(new Date(), "days");
if (daysUntilInvalid < 1) return "red";
if (daysUntilInvalid < 7) return "orange";
if (daysUntilInvalid < 30) return "yellow";
return "green";
};
@@ -16,7 +16,7 @@ import { MantineReactTable } from "mantine-react-table";
import type { RouterOutputs } from "@homarr/api"; import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { useTimeAgo } from "@homarr/common"; import { useTimeAgo } from "@homarr/common";
import type { ContainerState } from "@homarr/docker"; import type { DockerContainerState } from "@homarr/definitions";
import { useModalAction } from "@homarr/modals"; import { useModalAction } from "@homarr/modals";
import { AddDockerAppToHomarr } from "@homarr/modals-collection"; import { AddDockerAppToHomarr } from "@homarr/modals-collection";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
@@ -246,9 +246,9 @@ const containerStates = {
exited: "red", exited: "red",
removing: "pink", removing: "pink",
dead: "dark", dead: "dark",
} satisfies Record<ContainerState, MantineColor>; } satisfies Record<DockerContainerState, MantineColor>;
const ContainerStateBadge = ({ state }: { state: ContainerState }) => { const ContainerStateBadge = ({ state }: { state: DockerContainerState }) => {
const t = useScopedI18n("docker.field.state.option"); const t = useScopedI18n("docker.field.state.option");
return ( return (
@@ -39,8 +39,8 @@ export const ChangeHomeBoardForm = ({ user, boardsData }: ChangeHomeBoardFormPro
}); });
const form = useZodForm(validation.user.changeHomeBoards, { const form = useZodForm(validation.user.changeHomeBoards, {
initialValues: { initialValues: {
homeBoardId: user.homeBoardId, homeBoardId: user.homeBoardId ?? "",
mobileHomeBoardId: user.mobileHomeBoardId, mobileHomeBoardId: user.mobileHomeBoardId ?? "",
}, },
}); });
@@ -51,10 +51,7 @@ export const PingIconsEnabled = ({ user }: PingIconsEnabledProps) => {
return ( return (
<form onSubmit={form.onSubmit(handleSubmit)}> <form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md"> <Stack gap="md">
<Switch <Switch {...form.getInputProps("pingIconsEnabled")} label={t("user.field.pingIconsEnabled.label")} />
{...form.getInputProps("pingIconsEnabled", { type: "checkbox" })}
label={t("user.field.pingIconsEnabled.label")}
/>
<Group justify="end"> <Group justify="end">
<Button type="submit" color="teal" loading={isPending}> <Button type="submit" color="teal" loading={isPending}>
@@ -83,12 +83,10 @@ export default async function EditUserPage(props: Props) {
</Box> </Box>
</Group> </Group>
{session?.user.id === user.id && ( <Stack mb="lg">
<Stack mb="lg"> <Title order={2}>{tGeneral("item.language")}</Title>
<Title order={2}>{tGeneral("item.language")}</Title> <CurrentLanguageCombobox />
<CurrentLanguageCombobox /> </Stack>
</Stack>
)}
<Stack mb="lg"> <Stack mb="lg">
<Title order={2}>{tGeneral("item.board.title")}</Title> <Title order={2}>{tGeneral("item.board.title")}</Title>
+1 -3
View File
@@ -30,9 +30,7 @@ const handler = auth(async (req) => {
req, req,
createContext: () => createTRPCContext({ session: req.auth, headers: req.headers }), createContext: () => createTRPCContext({ session: req.auth, headers: req.headers }),
onError({ error, path, type }) { onError({ error, path, type }) {
logger.error( logger.error(`tRPC Error with ${type} on '${path}': (${error.code}) - ${error.message}`);
`tRPC Error with ${type} on '${path}': (${error.code}) - ${error.message}\n${error.stack}\n${error.cause}`,
);
}, },
}); });
@@ -1,62 +0,0 @@
import type { Modify } from "@homarr/common/types";
import { createId } from "@homarr/db/client";
import type { WidgetKind } from "@homarr/definitions";
import type { Board, DynamicSection, EmptySection, Item } from "~/app/[locale]/boards/_types";
import { getFirstEmptyPosition } from "./empty-position";
export interface CreateItemInput {
kind: WidgetKind;
}
export const createItemCallback =
({ kind }: CreateItemInput) =>
(previous: Board): Board => {
const firstSection = previous.sections
.filter((section): section is EmptySection => section.kind === "empty")
.sort((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset)
.at(0);
if (!firstSection) return previous;
const dynamicSectionsOfFirstSection = previous.sections.filter(
(section): section is DynamicSection => section.kind === "dynamic" && section.parentSectionId === firstSection.id,
);
const elements = [...firstSection.items, ...dynamicSectionsOfFirstSection];
const emptyPosition = getFirstEmptyPosition(elements, previous.columnCount);
if (!emptyPosition) {
console.error("Your board is full");
return previous;
}
const widget = {
id: createId(),
kind,
options: {},
width: 1,
height: 1,
...emptyPosition,
integrationIds: [],
advancedOptions: {
customCssClasses: [],
},
} satisfies Modify<
Item,
{
kind: WidgetKind;
}
>;
return {
...previous,
sections: previous.sections.map((section) => {
// Return same section if item is not in it
if (section.id !== firstSection.id) return section;
return {
...section,
items: section.items.concat(widget),
};
}),
};
};
@@ -1,81 +0,0 @@
import { createId } from "@homarr/db/client";
import type { Board, DynamicSection, EmptySection } from "~/app/[locale]/boards/_types";
import { getFirstEmptyPosition } from "./empty-position";
export interface DuplicateItemInput {
itemId: string;
}
export const duplicateItemCallback =
({ itemId }: DuplicateItemInput) =>
(previous: Board): Board => {
const itemToDuplicate = previous.sections
.flatMap((section) => section.items.map((item) => ({ ...item, sectionId: section.id })))
.find((item) => item.id === itemId);
if (!itemToDuplicate) return previous;
const currentSection = previous.sections.find((section) => section.id === itemToDuplicate.sectionId);
if (!currentSection) return previous;
const dynamicSectionsOfCurrentSection = previous.sections.filter(
(section): section is DynamicSection =>
section.kind === "dynamic" && section.parentSectionId === currentSection.id,
);
const elements = [...currentSection.items, ...dynamicSectionsOfCurrentSection];
let sectionId = currentSection.id;
let emptyPosition = getFirstEmptyPosition(
elements,
currentSection.kind === "dynamic" ? currentSection.width : previous.columnCount,
currentSection.kind === "dynamic" ? currentSection.height : undefined,
{
width: itemToDuplicate.width,
height: itemToDuplicate.height,
},
);
if (!emptyPosition) {
const firstSection = previous.sections
.filter((section): section is EmptySection => section.kind === "empty")
.sort((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset)
.at(0);
if (!firstSection) return previous;
const dynamicSectionsOfFirstSection = previous.sections.filter(
(section): section is DynamicSection =>
section.kind === "dynamic" && section.parentSectionId === firstSection.id,
);
const elements = [...firstSection.items, ...dynamicSectionsOfFirstSection];
emptyPosition = getFirstEmptyPosition(elements, previous.columnCount, undefined, {
width: itemToDuplicate.width,
height: itemToDuplicate.height,
});
if (!emptyPosition) {
console.error("Your board is full");
return previous;
}
sectionId = firstSection.id;
}
const widget = structuredClone(itemToDuplicate);
widget.id = createId();
widget.xOffset = emptyPosition.xOffset;
widget.yOffset = emptyPosition.yOffset;
widget.sectionId = sectionId;
const result = {
...previous,
sections: previous.sections.map((section) => {
// Return same section if item is not in it
if (section.id !== sectionId) return section;
return {
...section,
items: section.items.concat(widget),
};
}),
};
return result;
};
@@ -1,25 +0,0 @@
import type { Item } from "~/app/[locale]/boards/_types";
export const getFirstEmptyPosition = (
elements: Pick<Item, "yOffset" | "xOffset" | "width" | "height">[],
columnCount: number,
rowCount = 9999,
size: { width: number; height: number } = { width: 1, height: 1 },
) => {
for (let yOffset = 0; yOffset < rowCount + 1 - size.height; yOffset++) {
for (let xOffset = 0; xOffset < columnCount; xOffset++) {
const isOccupied = elements.some(
(element) =>
element.yOffset < yOffset + size.height &&
element.yOffset + element.height > yOffset &&
element.xOffset < xOffset + size.width &&
element.xOffset + element.width > xOffset,
);
if (!isOccupied) {
return { xOffset, yOffset };
}
}
}
return undefined;
};
@@ -1,61 +0,0 @@
import { describe, expect, test, vi } from "vitest";
import type { Board } from "~/app/[locale]/boards/_types";
import { createItemCallback } from "../create-item";
import * as emptyPosition from "../empty-position";
import { createDynamicSection, createEmptySection, createItem } from "./shared";
describe("item actions create-item", () => {
test("should add it to first section", () => {
const spy = vi.spyOn(emptyPosition, "getFirstEmptyPosition");
spy.mockReturnValue({ xOffset: 5, yOffset: 5 });
const input = {
sections: [createEmptySection("1", 2), createEmptySection("2", 0), createEmptySection("3", 1)],
columnCount: 4,
} satisfies Pick<Board, "sections" | "columnCount">;
const result = createItemCallback({
kind: "clock",
})(input as unknown as Board);
const firstSection = result.sections.find((section) => section.id === "2");
const item = firstSection?.items.at(0);
expect(item).toEqual(expect.objectContaining({ kind: "clock", xOffset: 5, yOffset: 5 }));
expect(spy).toHaveBeenCalledWith([], input.columnCount);
});
test("should correctly pass dynamic section and items to getFirstEmptyPosition", () => {
const spy = vi.spyOn(emptyPosition, "getFirstEmptyPosition");
spy.mockReturnValue({ xOffset: 5, yOffset: 5 });
const firstSection = createEmptySection("2", 0);
const expectedItem = createItem({ id: "12", xOffset: 1, yOffset: 2, width: 3, height: 2 });
firstSection.items.push(expectedItem);
const dynamicSectionInFirst = createDynamicSection({
id: "4",
parentSectionId: "2",
yOffset: 0,
xOffset: 0,
width: 2,
height: 2,
});
const input = {
sections: [
createEmptySection("1", 2),
firstSection,
createEmptySection("3", 1),
dynamicSectionInFirst,
createDynamicSection({ id: "5", parentSectionId: "3", yOffset: 1 }),
],
columnCount: 4,
} satisfies Pick<Board, "sections" | "columnCount">;
const result = createItemCallback({
kind: "clock",
})(input as unknown as Board);
const firstSectionResult = result.sections.find((section) => section.id === "2");
const item = firstSectionResult?.items.find((item) => item.id !== "12");
expect(item).toEqual(expect.objectContaining({ kind: "clock", xOffset: 5, yOffset: 5 }));
expect(spy).toHaveBeenCalledWith([expectedItem, dynamicSectionInFirst], input.columnCount);
});
});
@@ -1,52 +0,0 @@
import { describe, expect, test, vi } from "vitest";
import type { Board } from "~/app/[locale]/boards/_types";
import { duplicateItemCallback } from "../duplicate-item";
import * as emptyPosition from "../empty-position";
import { createEmptySection, createItem } from "./shared";
describe("item actions duplicate-item", () => {
test("should copy it in the same section", () => {
const spy = vi.spyOn(emptyPosition, "getFirstEmptyPosition");
spy.mockReturnValue({ xOffset: 5, yOffset: 5 });
const currentSection = createEmptySection("2", 1);
const currentItem = createItem({
id: "1",
xOffset: 1,
yOffset: 3,
width: 3,
height: 2,
kind: "minecraftServerStatus",
integrationIds: ["1"],
options: { address: "localhost" },
advancedOptions: { customCssClasses: ["test"] },
});
const otherItem = createItem({
id: "2",
});
currentSection.items.push(currentItem, otherItem);
const input = {
columnCount: 10,
sections: [createEmptySection("1", 0), currentSection, createEmptySection("3", 2)],
} satisfies Pick<Board, "sections" | "columnCount">;
const result = duplicateItemCallback({ itemId: currentItem.id })(input as unknown as Board);
const section = result.sections.find((section) => section.id === "2");
expect(section?.items.length).toBe(3);
const duplicatedItem = section?.items.find((item) => item.id !== currentItem.id && item.id !== otherItem.id);
expect(duplicatedItem).toEqual(
expect.objectContaining({
kind: "minecraftServerStatus",
xOffset: 5,
yOffset: 5,
width: 3,
height: 2,
integrationIds: ["1"],
options: { address: "localhost" },
advancedOptions: { customCssClasses: ["test"] },
}),
);
});
});
@@ -1,138 +0,0 @@
import { describe, expect, test } from "vitest";
import type { Item } from "~/app/[locale]/boards/_types";
import { getFirstEmptyPosition } from "../empty-position";
describe("get first empty position", () => {
test.each([
[[[" ", " ", " ", " "]], [1, 1], 0, 0],
[[["a", " ", " ", " "]], [1, 1], 1, 0],
[[[" ", "a", " ", " "]], [1, 1], 0, 0],
[
[
["a", "a", " ", " "],
["a", "a", " ", " "],
],
[1, 1],
2,
0,
],
[[["a", "a", "a", "a"]], [1, 1], 0, 1],
[
[
["a", "a", "a", "a"],
["a", "a", "a", "a"],
],
[1, 1],
0,
2,
],
[
[
["a", "a", " ", "b", "b"],
["a", "a", " ", "b", "b"],
],
[1, 2],
2,
0,
],
[
[
["a", "a", " ", " ", "b", "b"],
["a", "a", " ", " ", "b", "b"],
],
[2, 2],
2,
0,
],
[
[
["a", "a", " ", "d", "b", "b"],
["a", "a", "c", "e", "b", "b"],
],
[1, 1],
2,
0,
],
[
[
["a", "a", " ", " ", "b", "b"],
["a", "a", " ", "e", "b", "b"],
],
[2, 2],
0,
2,
],
])("should return the first empty position", (layout, size, expectedX, expectedY) => {
const elements = createElementsFromLayout(layout);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const result = getFirstEmptyPosition(elements, layout[0]!.length, undefined, { width: size[0]!, height: size[1]! });
expect(result).toEqual({ xOffset: expectedX, yOffset: expectedY });
});
test.each([
[[[" ", " "]], [1, 1], 0, 0, 1],
[[["a", " "]], [1, 1], 1, 0, 1],
[[["a", "a"]], [1, 1], undefined, undefined, 1],
[[["a", "a"]], [1, 1], 0, 1, 2],
[
[
["a", "b", " ", " "],
["a", "c", " ", "d"],
],
[2, 2],
undefined,
undefined,
3,
],
[
[
["a", "b", " ", " "],
["a", "c", " ", "d"],
],
[2, 2],
0,
2,
4,
],
[[["a", "b"]], [2, 1], 0, 1, 2],
])("should return the first empty position with limited rows", (layout, size, expectedX, expectedY, rowCount) => {
const elements = createElementsFromLayout(layout);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const result = getFirstEmptyPosition(elements, layout[0]!.length, rowCount, { width: size[0]!, height: size[1]! });
expect(result).toEqual(expectedX !== undefined ? { xOffset: expectedX, yOffset: expectedY } : undefined);
});
});
const createElementsFromLayout = (layout: string[][]) => {
const elements: (Pick<Item, "xOffset" | "yOffset" | "width" | "height"> & { char: string })[] = [];
for (let yOffset = 0; yOffset < layout.length; yOffset++) {
const row = layout[yOffset];
if (!row) continue;
for (let xOffset = 0; xOffset < row.length; xOffset++) {
const item = row[xOffset];
if (item === " " || !item) continue;
const existing = elements.find((element) => element.char === item);
if (existing) {
existing.height = yOffset - existing.yOffset + 1;
existing.width = xOffset - existing.xOffset + 1;
continue;
}
elements.push({
yOffset,
xOffset,
width: 1,
height: 1,
char: item,
});
}
}
return elements;
};
@@ -1,32 +0,0 @@
import type { DynamicSection, EmptySection, Item } from "~/app/[locale]/boards/_types";
export const createEmptySection = (id: string, yOffset: number): EmptySection => ({
id,
kind: "empty",
yOffset,
xOffset: 0,
items: [],
});
export const createDynamicSection = (section: Omit<Partial<DynamicSection>, "kind">): DynamicSection => ({
id: section.id ?? "0",
kind: "dynamic",
parentSectionId: section.parentSectionId ?? "0",
height: section.height ?? 1,
width: section.width ?? 1,
yOffset: section.yOffset ?? 0,
xOffset: section.xOffset ?? 0,
items: section.items ?? [],
});
export const createItem = (item: Partial<Item>): Item => ({
id: item.id ?? "0",
width: item.width ?? 1,
height: item.height ?? 1,
yOffset: item.yOffset ?? 0,
xOffset: item.xOffset ?? 0,
kind: item.kind ?? "clock",
integrationIds: item.integrationIds ?? [],
options: item.options ?? {},
advancedOptions: item.advancedOptions ?? { customCssClasses: [] },
});
@@ -1,13 +1,12 @@
import { useCallback } from "react"; import { useCallback } from "react";
import type { Modify } from "@homarr/common/types";
import { createId } from "@homarr/db/client";
import type { WidgetKind } from "@homarr/definitions";
import type { BoardItemAdvancedOptions } from "@homarr/validation"; import type { BoardItemAdvancedOptions } from "@homarr/validation";
import type { Item } from "~/app/[locale]/boards/_types"; import type { EmptySection, Item } from "~/app/[locale]/boards/_types";
import { useUpdateBoard } from "~/app/[locale]/boards/(content)/_client"; import { useUpdateBoard } from "~/app/[locale]/boards/(content)/_client";
import type { CreateItemInput } from "./actions/create-item";
import { createItemCallback } from "./actions/create-item";
import type { DuplicateItemInput } from "./actions/duplicate-item";
import { duplicateItemCallback } from "./actions/duplicate-item";
interface MoveAndResizeItem { interface MoveAndResizeItem {
itemId: string; itemId: string;
@@ -43,19 +42,87 @@ interface UpdateItemIntegrations {
newIntegrations: string[]; newIntegrations: string[];
} }
interface CreateItem {
kind: WidgetKind;
}
interface DuplicateItem {
itemId: string;
}
export const useItemActions = () => { export const useItemActions = () => {
const { updateBoard } = useUpdateBoard(); const { updateBoard } = useUpdateBoard();
const createItem = useCallback( const createItem = useCallback(
(input: CreateItemInput) => { ({ kind }: CreateItem) => {
updateBoard(createItemCallback(input)); updateBoard((previous) => {
const lastSection = previous.sections
.filter((section): section is EmptySection => section.kind === "empty")
.sort((sectionA, sectionB) => sectionB.yOffset - sectionA.yOffset)[0];
if (!lastSection) return previous;
const widget = {
id: createId(),
kind,
options: {},
width: 1,
height: 1,
integrationIds: [],
advancedOptions: {
customCssClasses: [],
},
} satisfies Modify<
Omit<Item, "yOffset" | "xOffset">,
{
kind: WidgetKind;
}
>;
return {
...previous,
sections: previous.sections.map((section) => {
// Return same section if item is not in it
if (section.id !== lastSection.id) return section;
return {
...section,
items: section.items.concat(widget as unknown as Item),
};
}),
};
});
}, },
[updateBoard], [updateBoard],
); );
const duplicateItem = useCallback( const duplicateItem = useCallback(
({ itemId }: DuplicateItemInput) => { ({ itemId }: DuplicateItem) => {
updateBoard(duplicateItemCallback({ itemId })); updateBoard((previous) => {
const itemToDuplicate = previous.sections
.flatMap((section) => section.items)
.find((item) => item.id === itemId);
if (!itemToDuplicate) return previous;
const newItem = {
...itemToDuplicate,
id: createId(),
yOffset: undefined,
xOffset: undefined,
} satisfies Modify<Item, { yOffset?: number; xOffset?: number }>;
return {
...previous,
sections: previous.sections.map((section) => {
// Return same section if item is not in it
if (!section.items.some((item) => item.id === itemId)) return section;
return {
...section,
items: section.items.concat(newItem as unknown as Item),
};
}),
};
});
}, },
[updateBoard], [updateBoard],
); );
@@ -79,12 +79,7 @@ const InnerContent = ({ item, ...dimensions }: InnerContentProps) => {
> >
<Throw <Throw
error={new NoIntegrationSelectedError()} error={new NoIntegrationSelectedError()}
when={ when={widgetSupportsIntegrations && item.integrationIds.length === 0}
widgetSupportsIntegrations &&
item.integrationIds.length === 0 &&
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
(!("integrationsRequired" in definition) || definition.integrationsRequired !== false)
}
/> />
<BoardItemMenu offset={4} item={newItem} /> <BoardItemMenu offset={4} item={newItem} />
<Comp <Comp
+7 -2
View File
@@ -12,7 +12,11 @@ export const env = createEnv({
* Specify your server-side environment variables schema here. This way you can ensure the app isn't * Specify your server-side environment variables schema here. This way you can ensure the app isn't
* built with invalid env vars. * built with invalid env vars.
*/ */
server: {}, server: {
// Comma separated list of docker hostnames that can be used to connect to query the docker endpoints (localhost:2375,host.docker.internal:2375, ...)
DOCKER_HOSTNAMES: z.string().optional(),
DOCKER_PORTS: z.string().optional(),
},
/** /**
* Specify your client-side environment variables schema here. * Specify your client-side environment variables schema here.
* For them to be exposed to the client, prefix them with `NEXT_PUBLIC_`. * For them to be exposed to the client, prefix them with `NEXT_PUBLIC_`.
@@ -26,8 +30,9 @@ export const env = createEnv({
runtimeEnv: { runtimeEnv: {
PORT: process.env.PORT, PORT: process.env.PORT,
NODE_ENV: process.env.NODE_ENV, NODE_ENV: process.env.NODE_ENV,
DOCKER_HOSTNAMES: process.env.DOCKER_HOSTNAMES,
DOCKER_PORTS: process.env.DOCKER_PORTS,
// NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR, // NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR,
}, },
skipValidation: shouldSkipEnvValidation(), skipValidation: shouldSkipEnvValidation(),
emptyStringAsUndefined: true,
}); });
+2 -2
View File
@@ -38,13 +38,13 @@
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"dotenv": "^16.4.7", "dotenv": "^16.4.7",
"superjson": "2.2.2", "superjson": "2.2.2",
"undici": "7.3.0" "undici": "7.2.1"
}, },
"devDependencies": { "devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0", "@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0", "@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0", "@homarr/tsconfig": "workspace:^0.1.0",
"@types/node": "^22.10.10", "@types/node": "^22.10.6",
"dotenv-cli": "^8.0.0", "dotenv-cli": "^8.0.0",
"eslint": "^9.18.0", "eslint": "^9.18.0",
"prettier": "^3.4.2", "prettier": "^3.4.2",
@@ -3,7 +3,7 @@ import { describe, expect, test, vi } from "vitest";
import { logger } from "@homarr/log"; import { logger } from "@homarr/log";
import { LoggingAgent } from "../fetch-agent"; import { LoggingAgent } from "~/undici-log-agent-override";
vi.mock("undici", () => { vi.mock("undici", () => {
return { return {
+31 -2
View File
@@ -1,6 +1,35 @@
import { setGlobalDispatcher } from "undici"; import type { Dispatcher } from "undici";
import { Agent, setGlobalDispatcher } from "undici";
import { LoggingAgent } from "@homarr/common/server"; import { logger } from "@homarr/log";
export class LoggingAgent extends Agent {
constructor(...props: ConstructorParameters<typeof Agent>) {
super(...props);
}
dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean {
const url = new URL(`${options.origin as string}${options.path}`);
// The below code should prevent sensitive data from being logged as
// some integrations use query parameters for auth
url.searchParams.forEach((value, key) => {
if (value === "") return; // Skip empty values
if (/^-?\d{1,12}$/.test(value)) return; // Skip small numbers
if (value === "true" || value === "false") return; // Skip boolean values
if (/^[a-zA-Z]{1,12}$/.test(value)) return; // Skip short strings
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return; // Skip dates
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) return; // Skip date times
url.searchParams.set(key, "REDACTED");
});
logger.info(
`Dispatching request ${url.toString().replaceAll("=&", "&")} (${Object.keys(options.headers ?? {}).length} headers)`,
);
return super.dispatch(options, handler);
}
}
const agent = new LoggingAgent(); const agent = new LoggingAgent();
setGlobalDispatcher(agent); setGlobalDispatcher(agent);
+1 -1
View File
@@ -33,7 +33,7 @@
"@homarr/eslint-config": "workspace:^0.2.0", "@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0", "@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0", "@homarr/tsconfig": "workspace:^0.1.0",
"@types/ws": "^8.5.14", "@types/ws": "^8.5.13",
"eslint": "^9.18.0", "eslint": "^9.18.0",
"prettier": "^3.4.2", "prettier": "^3.4.2",
"typescript": "^5.7.3" "typescript": "^5.7.3"
+10 -3
View File
@@ -24,10 +24,10 @@
<strong>Demo ✨</strong> <strong>Demo ✨</strong>
</a> </a>
• •
<a href="https://homarr.dev/docs/category/installation-1/"> <a href="https://homarr.dev/docs/getting-started/installation/">
<strong>Install 💻</strong> <strong>Install 💻</strong>
</a> • </a> •
<a href="https://crowdin.com/project/homarr_labs"> <a href="https://translate.homarr.dev/">
<strong>Translations 🈺</strong> <strong>Translations 🈺</strong>
</a> • </a> •
<a href="https://discord.com/invite/aCsmEV5RgA"> <a href="https://discord.com/invite/aCsmEV5RgA">
@@ -35,6 +35,13 @@
</a> </a>
</p> </p>
> [!WARNING]
> This is a beta version of Homarr. You can download the old but stable version at https://github.com/ajnart/homarr/. Running this version is at your own risk.
Simplify the management of your server with Homarr - a sleek, modern dashboard that puts all of your apps and services at your fingertips. With Homarr, you can access and control everything in one location. Homarr seamlessly integrates with the apps you've added, providing you with valuable information and giving you complete control. Installation is a breeze, and Homarr supports a wide range of deployment methods.
<br/>
<br/>
![Features Section](./section-features.png) ![Features Section](./section-features.png)
@@ -93,7 +100,7 @@ Homarr has a [built-in collection of widgets and integrations](https://homarr.de
Since we are updating Homarr very frequently, we recommend reading our official installation guides: Since we are updating Homarr very frequently, we recommend reading our official installation guides:
<h2> <h2>
<a href="https://homarr.dev/docs/category/installation-1/"> <a href="https://homarr.dev/docs/getting-started/installation/">
Please click here for official installation instructions Please click here for official installation instructions
</a> </a>
</h2> </h2>
+3 -3
View File
@@ -49,9 +49,9 @@ describe("Onboarding", () => {
environment: { environment: {
AUTH_PROVIDERS: "ldap", AUTH_PROVIDERS: "ldap",
AUTH_LDAP_URI: "ldap://host.docker.internal:3890", AUTH_LDAP_URI: "ldap://host.docker.internal:3890",
AUTH_LDAP_BASE: "not-used", AUTH_LDAP_BASE: "",
AUTH_LDAP_BIND_DN: "not-used", AUTH_LDAP_BIND_DN: "",
AUTH_LDAP_BIND_PASSWORD: "not-used", AUTH_LDAP_BIND_PASSWORD: "",
}, },
mounts: { mounts: {
"/appdata": localMountPath, "/appdata": localMountPath,
+8 -11
View File
@@ -1,6 +1,6 @@
{ {
"name": "homarr", "name": "homarr",
"version": "1.2.0", "version": "1.0.0-beta.13",
"private": true, "private": true,
"scripts": { "scripts": {
"build": "cross-env CI=true turbo build", "build": "cross-env CI=true turbo build",
@@ -38,30 +38,27 @@
"@semantic-release/github": "^11.0.1", "@semantic-release/github": "^11.0.1",
"@semantic-release/npm": "^12.0.1", "@semantic-release/npm": "^12.0.1",
"@semantic-release/release-notes-generator": "^14.0.3", "@semantic-release/release-notes-generator": "^14.0.3",
"@turbo/gen": "^2.3.4", "@turbo/gen": "^2.3.3",
"@vitejs/plugin-react": "^4.3.4", "@vitejs/plugin-react": "^4.3.4",
"@vitest/coverage-v8": "^3.0.4", "@vitest/coverage-v8": "^2.1.8",
"@vitest/ui": "^3.0.4", "@vitest/ui": "^2.1.8",
"conventional-changelog-conventionalcommits": "^8.0.0", "conventional-changelog-conventionalcommits": "^8.0.0",
"cross-env": "^7.0.3", "cross-env": "^7.0.3",
"jsdom": "^26.0.0", "jsdom": "^26.0.0",
"prettier": "^3.4.2", "prettier": "^3.4.2",
"semantic-release": "^24.2.1", "semantic-release": "^24.2.1",
"testcontainers": "^10.17.1", "testcontainers": "^10.16.0",
"turbo": "^2.3.4", "turbo": "^2.3.3",
"typescript": "^5.7.3", "typescript": "^5.7.3",
"vite-tsconfig-paths": "^5.1.4", "vite-tsconfig-paths": "^5.1.4",
"vitest": "^3.0.4" "vitest": "^2.1.8"
}, },
"packageManager": "pnpm@9.15.4", "packageManager": "pnpm@9.15.4",
"engines": { "engines": {
"node": ">=22.13.1" "node": ">=22.13.0"
}, },
"pnpm": { "pnpm": {
"allowNonAppliedPatches": true, "allowNonAppliedPatches": true,
"overrides": {
"proxmox-api>undici": "7.3.0"
},
"patchedDependencies": { "patchedDependencies": {
"pretty-print-error": "patches/pretty-print-error.patch" "pretty-print-error": "patches/pretty-print-error.patch"
} }
+3 -3
View File
@@ -22,14 +22,12 @@
"prettier": "@homarr/prettier-config", "prettier": "@homarr/prettier-config",
"dependencies": { "dependencies": {
"@homarr/auth": "workspace:^0.1.0", "@homarr/auth": "workspace:^0.1.0",
"@homarr/certificates": "workspace:^0.1.0",
"@homarr/common": "workspace:^0.1.0", "@homarr/common": "workspace:^0.1.0",
"@homarr/cron-job-runner": "workspace:^0.1.0", "@homarr/cron-job-runner": "workspace:^0.1.0",
"@homarr/cron-job-status": "workspace:^0.1.0", "@homarr/cron-job-status": "workspace:^0.1.0",
"@homarr/cron-jobs": "workspace:^0.1.0", "@homarr/cron-jobs": "workspace:^0.1.0",
"@homarr/db": "workspace:^0.1.0", "@homarr/db": "workspace:^0.1.0",
"@homarr/definitions": "workspace:^0.1.0", "@homarr/definitions": "workspace:^0.1.0",
"@homarr/docker": "workspace:^0.1.0",
"@homarr/icons": "workspace:^0.1.0", "@homarr/icons": "workspace:^0.1.0",
"@homarr/integrations": "workspace:^0.1.0", "@homarr/integrations": "workspace:^0.1.0",
"@homarr/log": "workspace:^", "@homarr/log": "workspace:^",
@@ -43,8 +41,9 @@
"@trpc/client": "next", "@trpc/client": "next",
"@trpc/react-query": "next", "@trpc/react-query": "next",
"@trpc/server": "next", "@trpc/server": "next",
"dockerode": "^4.0.3",
"lodash.clonedeep": "^4.5.0", "lodash.clonedeep": "^4.5.0",
"next": "15.1.6", "next": "15.1.4",
"react": "19.0.0", "react": "19.0.0",
"react-dom": "19.0.0", "react-dom": "19.0.0",
"superjson": "2.2.2", "superjson": "2.2.2",
@@ -54,6 +53,7 @@
"@homarr/eslint-config": "workspace:^0.2.0", "@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0", "@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0", "@homarr/tsconfig": "workspace:^0.1.0",
"@types/dockerode": "^3.3.34",
"eslint": "^9.18.0", "eslint": "^9.18.0",
"prettier": "^3.4.2", "prettier": "^3.4.2",
"typescript": "^5.7.3" "typescript": "^5.7.3"
+38 -41
View File
@@ -98,59 +98,56 @@ export const createManyIntegrationMiddleware = <TKind extends IntegrationKind>(
action: IntegrationAction, action: IntegrationAction,
...kinds: AtLeastOneOf<TKind> // Ensure at least one kind is provided ...kinds: AtLeastOneOf<TKind> // Ensure at least one kind is provided
) => { ) => {
return publicProcedure.input(z.object({ integrationIds: z.array(z.string()) })).use(async ({ ctx, input, next }) => { return publicProcedure
const dbIntegrations = .input(z.object({ integrationIds: z.array(z.string()).min(1) }))
input.integrationIds.length >= 1 .use(async ({ ctx, input, next }) => {
? await ctx.db.query.integrations.findMany({ const dbIntegrations = await ctx.db.query.integrations.findMany({
where: and(inArray(integrations.id, input.integrationIds), inArray(integrations.kind, kinds)), where: and(inArray(integrations.id, input.integrationIds), inArray(integrations.kind, kinds)),
with: {
secrets: true,
items: {
with: { with: {
secrets: true, item: {
items: {
with: { with: {
item: { section: {
with: { columns: {
section: { boardId: true,
columns: {
boardId: true,
},
},
}, },
}, },
}, },
}, },
userPermissions: true,
groupPermissions: true,
}, },
}) },
: []; userPermissions: true,
groupPermissions: true,
const offset = input.integrationIds.length - dbIntegrations.length; },
if (offset !== 0) {
throw new TRPCError({
code: "NOT_FOUND",
message: `${offset} of the specified integrations not found or not of kinds ${kinds.join(",")}: ([${input.integrationIds.join(",")}] compared to [${dbIntegrations.map(({ id, kind }) => `${kind}:${id}`).join(",")}])`,
}); });
}
if (dbIntegrations.length >= 1) { const offset = input.integrationIds.length - dbIntegrations.length;
if (offset !== 0) {
throw new TRPCError({
code: "NOT_FOUND",
message: `${offset} of the specified integrations not found or not of kinds ${kinds.join(",")}: ([${input.integrationIds.join(",")}] compared to [${dbIntegrations.map(({ id, kind }) => `${kind}:${id}`).join(",")}])`,
});
}
await throwIfActionIsNotAllowedAsync(action, ctx.db, dbIntegrations, ctx.session); await throwIfActionIsNotAllowedAsync(action, ctx.db, dbIntegrations, ctx.session);
}
return next({ return next({
ctx: { ctx: {
integrations: dbIntegrations.map( integrations: dbIntegrations.map(
({ secrets, kind, items: _ignore1, groupPermissions: _ignore2, userPermissions: _ignore3, ...rest }) => ({ ({ secrets, kind, items: _ignore1, groupPermissions: _ignore2, userPermissions: _ignore3, ...rest }) => ({
...rest, ...rest,
kind: kind as TKind, kind: kind as TKind,
decryptedSecrets: secrets.map((secret) => ({ decryptedSecrets: secrets.map((secret) => ({
...secret, ...secret,
value: decryptSecret(secret.value), value: decryptSecret(secret.value),
})), })),
}), }),
), ),
}, },
});
}); });
});
}; };
/** /**
-2
View File
@@ -1,7 +1,6 @@
import { apiKeysRouter } from "./router/apiKeys"; import { apiKeysRouter } from "./router/apiKeys";
import { appRouter as innerAppRouter } from "./router/app"; import { appRouter as innerAppRouter } from "./router/app";
import { boardRouter } from "./router/board"; import { boardRouter } from "./router/board";
import { certificateRouter } from "./router/certificates/certificate-router";
import { cronJobsRouter } from "./router/cron-jobs"; import { cronJobsRouter } from "./router/cron-jobs";
import { dockerRouter } from "./router/docker/docker-router"; import { dockerRouter } from "./router/docker/docker-router";
import { groupRouter } from "./router/group"; import { groupRouter } from "./router/group";
@@ -42,7 +41,6 @@ export const appRouter = createTRPCRouter({
apiKeys: apiKeysRouter, apiKeys: apiKeysRouter,
media: mediaRouter, media: mediaRouter,
updateChecker: updateCheckerRouter, updateChecker: updateCheckerRouter,
certificates: certificateRouter,
}); });
// export type definition of API // export type definition of API
+182 -449
View File
@@ -4,7 +4,7 @@ import superjson from "superjson";
import { constructBoardPermissions } from "@homarr/auth/shared"; import { constructBoardPermissions } from "@homarr/auth/shared";
import type { DeviceType } from "@homarr/common/server"; import type { DeviceType } from "@homarr/common/server";
import type { Database, InferInsertModel, InferSelectModel, SQL } from "@homarr/db"; import type { Database, InferInsertModel, InferSelectModel, SQL } from "@homarr/db";
import { and, createId, eq, handleTransactionsAsync, inArray, like, or } from "@homarr/db"; import { and, createId, eq, inArray, like, or } from "@homarr/db";
import { getServerSettingByKeyAsync } from "@homarr/db/queries"; import { getServerSettingByKeyAsync } from "@homarr/db/queries";
import { import {
boardGroupPermissions, boardGroupPermissions,
@@ -204,49 +204,21 @@ export const boardRouter = createTRPCRouter({
.input(validation.board.create) .input(validation.board.create)
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {
const boardId = createId(); const boardId = createId();
await handleTransactionsAsync(ctx.db, { await ctx.db.transaction(async (transaction) => {
async handleAsync(db, schema) { await transaction.insert(boards).values({
await db.transaction(async (transaction) => { id: boardId,
await transaction.insert(schema.boards).values({ name: input.name,
id: boardId, isPublic: input.isPublic,
name: input.name, columnCount: input.columnCount,
isPublic: input.isPublic, creatorId: ctx.session.user.id,
columnCount: input.columnCount, });
creatorId: ctx.session.user.id, await transaction.insert(sections).values({
}); id: createId(),
await transaction.insert(schema.sections).values({ kind: "empty",
id: createId(), xOffset: 0,
kind: "empty", yOffset: 0,
xOffset: 0, boardId,
yOffset: 0, });
boardId,
});
});
},
handleSync(db) {
db.transaction((transaction) => {
transaction
.insert(boards)
.values({
id: boardId,
name: input.name,
isPublic: input.isPublic,
columnCount: input.columnCount,
creatorId: ctx.session.user.id,
})
.run();
transaction
.insert(sections)
.values({
id: createId(),
kind: "empty",
xOffset: 0,
yOffset: 0,
boardId,
})
.run();
});
},
}); });
}), }),
duplicateBoard: permissionRequiredProcedure duplicateBoard: permissionRequiredProcedure
@@ -330,54 +302,28 @@ export const boardRouter = createTRPCRouter({
})), })),
); );
await handleTransactionsAsync(ctx.db, { ctx.db.transaction((transaction) => {
async handleAsync(db, schema) { transaction
await db.transaction(async (transaction) => { .insert(boards)
transaction.insert(schema.boards).values({ .values({
...boardProps, ...boardProps,
id: newBoardId, id: newBoardId,
name: input.name, name: input.name,
creatorId: ctx.session.user.id, creatorId: ctx.session.user.id,
}); })
.run();
if (sectionsToInsert.length > 0) { if (sectionsToInsert.length > 0) {
await transaction.insert(schema.sections).values(sectionsToInsert); transaction.insert(sections).values(sectionsToInsert).run();
} }
if (itemsToInsert.length > 0) { if (itemsToInsert.length > 0) {
await transaction.insert(schema.items).values(itemsToInsert); transaction.insert(items).values(itemsToInsert).run();
} }
if (itemIntegrationsToInsert.length > 0) { if (itemIntegrationsToInsert.length > 0) {
await transaction.insert(schema.integrationItems).values(itemIntegrationsToInsert); transaction.insert(integrationItems).values(itemIntegrationsToInsert).run();
} }
});
},
handleSync(db) {
db.transaction((transaction) => {
transaction
.insert(boards)
.values({
...boardProps,
id: newBoardId,
name: input.name,
creatorId: ctx.session.user.id,
})
.run();
if (sectionsToInsert.length > 0) {
transaction.insert(sections).values(sectionsToInsert).run();
}
if (itemsToInsert.length > 0) {
transaction.insert(items).values(itemsToInsert).run();
}
if (itemIntegrationsToInsert.length > 0) {
transaction.insert(integrationItems).values(itemIntegrationsToInsert).run();
}
});
},
}); });
}), }),
renameBoard: protectedProcedure.input(validation.board.rename).mutation(async ({ ctx, input }) => { renameBoard: protectedProcedure.input(validation.board.rename).mutation(async ({ ctx, input }) => {
@@ -488,313 +434,148 @@ export const boardRouter = createTRPCRouter({
saveBoard: protectedProcedure.input(validation.board.save).mutation(async ({ input, ctx }) => { saveBoard: protectedProcedure.input(validation.board.save).mutation(async ({ input, ctx }) => {
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "modify"); await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "modify");
const dbBoard = await getFullBoardWithWhereAsync(ctx.db, eq(boards.id, input.id), ctx.session.user.id); await ctx.db.transaction(async (transaction) => {
const dbBoard = await getFullBoardWithWhereAsync(transaction, eq(boards.id, input.id), ctx.session.user.id);
await handleTransactionsAsync(ctx.db, { const addedSections = filterAddedItems(input.sections, dbBoard.sections);
async handleAsync(db, schema) {
await db.transaction(async (transaction) => {
const addedSections = filterAddedItems(input.sections, dbBoard.sections);
if (addedSections.length > 0) { if (addedSections.length > 0) {
await transaction.insert(schema.sections).values( await transaction.insert(sections).values(
addedSections.map((section) => ({ addedSections.map((section) => ({
id: section.id, id: section.id,
kind: section.kind, kind: section.kind,
yOffset: section.yOffset, yOffset: section.yOffset,
xOffset: section.kind === "dynamic" ? section.xOffset : 0, xOffset: section.kind === "dynamic" ? section.xOffset : 0,
height: "height" in section ? section.height : null, height: "height" in section ? section.height : null,
width: "width" in section ? section.width : null, width: "width" in section ? section.width : null,
parentSectionId: "parentSectionId" in section ? section.parentSectionId : null, parentSectionId: "parentSectionId" in section ? section.parentSectionId : null,
name: "name" in section ? section.name : null, name: "name" in section ? section.name : null,
boardId: dbBoard.id, boardId: dbBoard.id,
})), })),
); );
} }
const inputItems = input.sections.flatMap((section) => const inputItems = input.sections.flatMap((section) =>
section.items.map((item) => ({ ...item, sectionId: section.id })), section.items.map((item) => ({ ...item, sectionId: section.id })),
); );
const dbItems = dbBoard.sections.flatMap((section) => const dbItems = dbBoard.sections.flatMap((section) =>
section.items.map((item) => ({ ...item, sectionId: section.id })), section.items.map((item) => ({ ...item, sectionId: section.id })),
); );
const addedItems = filterAddedItems(inputItems, dbItems); const addedItems = filterAddedItems(inputItems, dbItems);
if (addedItems.length > 0) { if (addedItems.length > 0) {
await transaction.insert(schema.items).values( await transaction.insert(items).values(
addedItems.map((item) => ({ addedItems.map((item) => ({
id: item.id, id: item.id,
kind: item.kind, kind: item.kind,
height: item.height, height: item.height,
width: item.width, width: item.width,
xOffset: item.xOffset, xOffset: item.xOffset,
yOffset: item.yOffset, yOffset: item.yOffset,
options: superjson.stringify(item.options), options: superjson.stringify(item.options),
advancedOptions: superjson.stringify(item.advancedOptions), advancedOptions: superjson.stringify(item.advancedOptions),
sectionId: item.sectionId, sectionId: item.sectionId,
})), })),
); );
} }
const inputIntegrationRelations = inputItems.flatMap(({ integrationIds, id: itemId }) => const inputIntegrationRelations = inputItems.flatMap(({ integrationIds, id: itemId }) =>
integrationIds.map((integrationId) => ({ integrationIds.map((integrationId) => ({
integrationId, integrationId,
itemId, itemId,
})), })),
); );
const dbIntegrationRelations = dbItems.flatMap(({ integrationIds, id: itemId }) => const dbIntegrationRelations = dbItems.flatMap(({ integrationIds, id: itemId }) =>
integrationIds.map((integrationId) => ({ integrationIds.map((integrationId) => ({
integrationId, integrationId,
itemId, itemId,
})), })),
); );
const addedIntegrationRelations = inputIntegrationRelations.filter( const addedIntegrationRelations = inputIntegrationRelations.filter(
(inputRelation) => (inputRelation) =>
!dbIntegrationRelations.some( !dbIntegrationRelations.some(
(dbRelation) =>
dbRelation.itemId === inputRelation.itemId &&
dbRelation.integrationId === inputRelation.integrationId,
),
);
if (addedIntegrationRelations.length > 0) {
await transaction.insert(schema.integrationItems).values(
addedIntegrationRelations.map((relation) => ({
itemId: relation.itemId,
integrationId: relation.integrationId,
})),
);
}
const updatedItems = filterUpdatedItems(inputItems, dbItems);
for (const item of updatedItems) {
await transaction
.update(schema.items)
.set({
kind: item.kind,
height: item.height,
width: item.width,
xOffset: item.xOffset,
yOffset: item.yOffset,
options: superjson.stringify(item.options),
advancedOptions: superjson.stringify(item.advancedOptions),
sectionId: item.sectionId,
})
.where(eq(items.id, item.id));
}
const updatedSections = filterUpdatedItems(input.sections, dbBoard.sections);
for (const section of updatedSections) {
const prev = dbBoard.sections.find((dbSection) => dbSection.id === section.id);
await transaction
.update(schema.sections)
.set({
yOffset: section.yOffset,
xOffset: section.xOffset,
height: prev?.kind === "dynamic" && "height" in section ? section.height : null,
width: prev?.kind === "dynamic" && "width" in section ? section.width : null,
parentSectionId:
prev?.kind === "dynamic" && "parentSectionId" in section ? section.parentSectionId : null,
name: prev?.kind === "category" && "name" in section ? section.name : null,
})
.where(eq(sections.id, section.id));
}
const removedIntegrationRelations = dbIntegrationRelations.filter(
(dbRelation) => (dbRelation) =>
!inputIntegrationRelations.some( dbRelation.itemId === inputRelation.itemId && dbRelation.integrationId === inputRelation.integrationId,
(inputRelation) => ),
dbRelation.itemId === inputRelation.itemId && );
dbRelation.integrationId === inputRelation.integrationId,
),
);
for (const relation of removedIntegrationRelations) { if (addedIntegrationRelations.length > 0) {
await transaction await transaction.insert(integrationItems).values(
.delete(schema.integrationItems) addedIntegrationRelations.map((relation) => ({
.where( itemId: relation.itemId,
and( integrationId: relation.integrationId,
eq(integrationItems.itemId, relation.itemId), })),
eq(integrationItems.integrationId, relation.integrationId), );
), }
);
}
const removedItems = filterRemovedItems(inputItems, dbItems); const updatedItems = filterUpdatedItems(inputItems, dbItems);
const itemIds = removedItems.map((item) => item.id); for (const item of updatedItems) {
if (itemIds.length > 0) { await transaction
await transaction.delete(schema.items).where(inArray(items.id, itemIds)); .update(items)
} .set({
kind: item.kind,
height: item.height,
width: item.width,
xOffset: item.xOffset,
yOffset: item.yOffset,
options: superjson.stringify(item.options),
advancedOptions: superjson.stringify(item.advancedOptions),
sectionId: item.sectionId,
})
.where(eq(items.id, item.id));
}
const removedSections = filterRemovedItems(input.sections, dbBoard.sections); const updatedSections = filterUpdatedItems(input.sections, dbBoard.sections);
const sectionIds = removedSections.map((section) => section.id);
if (sectionIds.length > 0) { for (const section of updatedSections) {
await transaction.delete(schema.sections).where(inArray(sections.id, sectionIds)); const prev = dbBoard.sections.find((dbSection) => dbSection.id === section.id);
} await transaction
}); .update(sections)
}, .set({
handleSync(db) { yOffset: section.yOffset,
db.transaction((transaction) => { xOffset: section.xOffset,
const addedSections = filterAddedItems(input.sections, dbBoard.sections); height: prev?.kind === "dynamic" && "height" in section ? section.height : null,
width: prev?.kind === "dynamic" && "width" in section ? section.width : null,
parentSectionId: prev?.kind === "dynamic" && "parentSectionId" in section ? section.parentSectionId : null,
name: prev?.kind === "category" && "name" in section ? section.name : null,
})
.where(eq(sections.id, section.id));
}
if (addedSections.length > 0) { const removedIntegrationRelations = dbIntegrationRelations.filter(
transaction (dbRelation) =>
.insert(sections) !inputIntegrationRelations.some(
.values(
addedSections.map((section) => ({
id: section.id,
kind: section.kind,
yOffset: section.yOffset,
xOffset: section.kind === "dynamic" ? section.xOffset : 0,
height: "height" in section ? section.height : null,
width: "width" in section ? section.width : null,
parentSectionId: "parentSectionId" in section ? section.parentSectionId : null,
name: "name" in section ? section.name : null,
boardId: dbBoard.id,
})),
)
.run();
}
const inputItems = input.sections.flatMap((section) =>
section.items.map((item) => ({ ...item, sectionId: section.id })),
);
const dbItems = dbBoard.sections.flatMap((section) =>
section.items.map((item) => ({ ...item, sectionId: section.id })),
);
const addedItems = filterAddedItems(inputItems, dbItems);
if (addedItems.length > 0) {
transaction
.insert(items)
.values(
addedItems.map((item) => ({
id: item.id,
kind: item.kind,
height: item.height,
width: item.width,
xOffset: item.xOffset,
yOffset: item.yOffset,
options: superjson.stringify(item.options),
advancedOptions: superjson.stringify(item.advancedOptions),
sectionId: item.sectionId,
})),
)
.run();
}
const inputIntegrationRelations = inputItems.flatMap(({ integrationIds, id: itemId }) =>
integrationIds.map((integrationId) => ({
integrationId,
itemId,
})),
);
const dbIntegrationRelations = dbItems.flatMap(({ integrationIds, id: itemId }) =>
integrationIds.map((integrationId) => ({
integrationId,
itemId,
})),
);
const addedIntegrationRelations = inputIntegrationRelations.filter(
(inputRelation) => (inputRelation) =>
!dbIntegrationRelations.some( dbRelation.itemId === inputRelation.itemId && dbRelation.integrationId === inputRelation.integrationId,
(dbRelation) => ),
dbRelation.itemId === inputRelation.itemId && );
dbRelation.integrationId === inputRelation.integrationId,
), for (const relation of removedIntegrationRelations) {
await transaction
.delete(integrationItems)
.where(
and(
eq(integrationItems.itemId, relation.itemId),
eq(integrationItems.integrationId, relation.integrationId),
),
); );
}
if (addedIntegrationRelations.length > 0) { const removedItems = filterRemovedItems(inputItems, dbItems);
transaction
.insert(integrationItems)
.values(
addedIntegrationRelations.map((relation) => ({
itemId: relation.itemId,
integrationId: relation.integrationId,
})),
)
.run();
}
const updatedItems = filterUpdatedItems(inputItems, dbItems); const itemIds = removedItems.map((item) => item.id);
if (itemIds.length > 0) {
await transaction.delete(items).where(inArray(items.id, itemIds));
}
for (const item of updatedItems) { const removedSections = filterRemovedItems(input.sections, dbBoard.sections);
transaction const sectionIds = removedSections.map((section) => section.id);
.update(items)
.set({
kind: item.kind,
height: item.height,
width: item.width,
xOffset: item.xOffset,
yOffset: item.yOffset,
options: superjson.stringify(item.options),
advancedOptions: superjson.stringify(item.advancedOptions),
sectionId: item.sectionId,
})
.where(eq(items.id, item.id))
.run();
}
const updatedSections = filterUpdatedItems(input.sections, dbBoard.sections); if (sectionIds.length > 0) {
await transaction.delete(sections).where(inArray(sections.id, sectionIds));
for (const section of updatedSections) { }
const prev = dbBoard.sections.find((dbSection) => dbSection.id === section.id);
transaction
.update(sections)
.set({
yOffset: section.yOffset,
xOffset: section.xOffset,
height: prev?.kind === "dynamic" && "height" in section ? section.height : null,
width: prev?.kind === "dynamic" && "width" in section ? section.width : null,
parentSectionId:
prev?.kind === "dynamic" && "parentSectionId" in section ? section.parentSectionId : null,
name: prev?.kind === "category" && "name" in section ? section.name : null,
})
.where(eq(sections.id, section.id))
.run();
}
const removedIntegrationRelations = dbIntegrationRelations.filter(
(dbRelation) =>
!inputIntegrationRelations.some(
(inputRelation) =>
dbRelation.itemId === inputRelation.itemId &&
dbRelation.integrationId === inputRelation.integrationId,
),
);
for (const relation of removedIntegrationRelations) {
transaction
.delete(integrationItems)
.where(
and(
eq(integrationItems.itemId, relation.itemId),
eq(integrationItems.integrationId, relation.integrationId),
),
)
.run();
}
const removedItems = filterRemovedItems(inputItems, dbItems);
const itemIds = removedItems.map((item) => item.id);
if (itemIds.length > 0) {
transaction.delete(items).where(inArray(items.id, itemIds)).run();
}
const removedSections = filterRemovedItems(input.sections, dbBoard.sections);
const sectionIds = removedSections.map((section) => section.id);
if (sectionIds.length > 0) {
transaction.delete(sections).where(inArray(sections.id, sectionIds)).run();
}
});
},
}); });
}), }),
@@ -874,42 +655,18 @@ export const boardRouter = createTRPCRouter({
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.entityId), "full"); await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.entityId), "full");
await handleTransactionsAsync(ctx.db, { await ctx.db.transaction(async (transaction) => {
async handleAsync(db, schema) { await transaction.delete(boardUserPermissions).where(eq(boardUserPermissions.boardId, input.entityId));
await db.transaction(async (transaction) => { if (input.permissions.length === 0) {
await transaction return;
.delete(schema.boardUserPermissions) }
.where(eq(boardUserPermissions.boardId, input.entityId)); await transaction.insert(boardUserPermissions).values(
if (input.permissions.length === 0) { input.permissions.map((permission) => ({
return; userId: permission.principalId,
} permission: permission.permission,
await transaction.insert(schema.boardUserPermissions).values( boardId: input.entityId,
input.permissions.map((permission) => ({ })),
userId: permission.principalId, );
permission: permission.permission,
boardId: input.entityId,
})),
);
});
},
handleSync(db) {
db.transaction((transaction) => {
transaction.delete(boardUserPermissions).where(eq(boardUserPermissions.boardId, input.entityId)).run();
if (input.permissions.length === 0) {
return;
}
transaction
.insert(boardUserPermissions)
.values(
input.permissions.map((permission) => ({
userId: permission.principalId,
permission: permission.permission,
boardId: input.entityId,
})),
)
.run();
});
},
}); });
}), }),
saveGroupBoardPermissions: protectedProcedure saveGroupBoardPermissions: protectedProcedure
@@ -917,42 +674,18 @@ export const boardRouter = createTRPCRouter({
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.entityId), "full"); await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.entityId), "full");
await handleTransactionsAsync(ctx.db, { await ctx.db.transaction(async (transaction) => {
async handleAsync(db, schema) { await transaction.delete(boardGroupPermissions).where(eq(boardGroupPermissions.boardId, input.entityId));
await db.transaction(async (transaction) => { if (input.permissions.length === 0) {
await transaction return;
.delete(schema.boardGroupPermissions) }
.where(eq(boardGroupPermissions.boardId, input.entityId)); await transaction.insert(boardGroupPermissions).values(
if (input.permissions.length === 0) { input.permissions.map((permission) => ({
return; groupId: permission.principalId,
} permission: permission.permission,
await transaction.insert(schema.boardGroupPermissions).values( boardId: input.entityId,
input.permissions.map((permission) => ({ })),
groupId: permission.principalId, );
permission: permission.permission,
boardId: input.entityId,
})),
);
});
},
handleSync(db) {
db.transaction((transaction) => {
transaction.delete(boardGroupPermissions).where(eq(boardGroupPermissions.boardId, input.entityId)).run();
if (input.permissions.length === 0) {
return;
}
transaction
.insert(boardGroupPermissions)
.values(
input.permissions.map((permission) => ({
groupId: permission.principalId,
permission: permission.permission,
boardId: input.entityId,
})),
)
.run();
});
},
}); });
}), }),
importOldmarrConfig: permissionRequiredProcedure importOldmarrConfig: permissionRequiredProcedure
@@ -1,27 +0,0 @@
import { z } from "zod";
import { zfd } from "zod-form-data";
import { addCustomRootCertificateAsync, removeCustomRootCertificateAsync } from "@homarr/certificates/server";
import { superRefineCertificateFile, validation } from "@homarr/validation";
import { createTRPCRouter, permissionRequiredProcedure } from "../../trpc";
export const certificateRouter = createTRPCRouter({
addCertificate: permissionRequiredProcedure
.requiresPermission("admin")
.input(
zfd.formData({
file: zfd.file().superRefine(superRefineCertificateFile),
}),
)
.mutation(async ({ input }) => {
const content = await input.file.text();
await addCustomRootCertificateAsync(input.file.name, content);
}),
removeCertificate: permissionRequiredProcedure
.requiresPermission("admin")
.input(z.object({ fileName: validation.certificates.validFileNameSchema }))
.mutation(async ({ input }) => {
await removeCustomRootCertificateAsync(input.fileName);
}),
});
+13 -10
View File
@@ -1,24 +1,26 @@
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import type Docker from "dockerode";
import type { Container } from "dockerode";
import { db, like, or } from "@homarr/db"; import { db, like, or } from "@homarr/db";
import { icons } from "@homarr/db/schema"; import { icons } from "@homarr/db/schema";
import { DockerSingleton } from "@homarr/docker"; import type { DockerContainerState } from "@homarr/definitions";
import type { Container, ContainerInfo, ContainerState, Docker, Port } from "@homarr/docker";
import { logger } from "@homarr/log"; import { logger } from "@homarr/log";
import { createCacheChannel } from "@homarr/redis"; import { createCacheChannel } from "@homarr/redis";
import { z } from "@homarr/validation"; import { z } from "@homarr/validation";
import { createTRPCRouter, permissionRequiredProcedure } from "../../trpc"; import { createTRPCRouter, permissionRequiredProcedure } from "../../trpc";
import { DockerSingleton } from "./docker-singleton";
const dockerCache = createCacheChannel<{ const dockerCache = createCacheChannel<{
containers: (ContainerInfo & { instance: string; iconUrl: string | null })[]; containers: (Docker.ContainerInfo & { instance: string; iconUrl: string | null })[];
}>("docker-containers", 5 * 60 * 1000); }>("docker-containers", 5 * 60 * 1000);
export const dockerRouter = createTRPCRouter({ export const dockerRouter = createTRPCRouter({
getContainers: permissionRequiredProcedure.requiresPermission("admin").query(async () => { getContainers: permissionRequiredProcedure.requiresPermission("admin").query(async () => {
const result = await dockerCache const result = await dockerCache
.consumeAsync(async () => { .consumeAsync(async () => {
const dockerInstances = DockerSingleton.getInstances(); const dockerInstances = DockerSingleton.getInstance();
const containers = await Promise.all( const containers = await Promise.all(
// Return all the containers of all the instances into only one item // Return all the containers of all the instances into only one item
dockerInstances.map(({ instance, host: key }) => dockerInstances.map(({ instance, host: key }) =>
@@ -31,7 +33,8 @@ export const dockerRouter = createTRPCRouter({
), ),
).then((containers) => containers.flat()); ).then((containers) => containers.flat());
const extractImage = (container: ContainerInfo) => container.Image.split("/").at(-1)?.split(":").at(0) ?? ""; const extractImage = (container: Docker.ContainerInfo) =>
container.Image.split("/").at(-1)?.split(":").at(0) ?? "";
const likeQueries = containers.map((container) => like(icons.name, `%${extractImage(container)}%`)); const likeQueries = containers.map((container) => like(icons.name, `%${extractImage(container)}%`));
const dbIcons = const dbIcons =
likeQueries.length >= 1 likeQueries.length >= 1
@@ -148,7 +151,7 @@ const getContainerOrDefaultAsync = async (instance: Docker, id: string) => {
}; };
const getContainerOrThrowAsync = async (id: string) => { const getContainerOrThrowAsync = async (id: string) => {
const dockerInstances = DockerSingleton.getInstances(); const dockerInstances = DockerSingleton.getInstance();
const containers = await Promise.all(dockerInstances.map(({ instance }) => getContainerOrDefaultAsync(instance, id))); const containers = await Promise.all(dockerInstances.map(({ instance }) => getContainerOrDefaultAsync(instance, id)));
const foundContainer = containers.find((container) => container) ?? null; const foundContainer = containers.find((container) => container) ?? null;
@@ -165,21 +168,21 @@ const getContainerOrThrowAsync = async (id: string) => {
interface DockerContainer { interface DockerContainer {
name: string; name: string;
id: string; id: string;
state: ContainerState; state: DockerContainerState;
image: string; image: string;
ports: Port[]; ports: Docker.Port[];
iconUrl: string | null; iconUrl: string | null;
} }
function sanitizeContainers( function sanitizeContainers(
containers: (ContainerInfo & { instance: string; iconUrl: string | null })[], containers: (Docker.ContainerInfo & { instance: string; iconUrl: string | null })[],
): DockerContainer[] { ): DockerContainer[] {
return containers.map((container) => { return containers.map((container) => {
return { return {
name: container.Names[0]?.split("/")[1] ?? "Unknown", name: container.Names[0]?.split("/")[1] ?? "Unknown",
id: container.Id, id: container.Id,
instance: container.instance, instance: container.instance,
state: container.State as ContainerState, state: container.State as DockerContainerState,
image: container.Image, image: container.Image,
ports: container.Ports, ports: container.Ports,
iconUrl: container.iconUrl, iconUrl: container.iconUrl,
@@ -0,0 +1,51 @@
import Docker from "dockerode";
interface DockerInstance {
host: string;
instance: Docker;
}
export class DockerSingleton {
private static instances: DockerInstance[];
private createInstances() {
const instances: DockerInstance[] = [];
const hostVariable = process.env.DOCKER_HOST;
const portVariable = process.env.DOCKER_PORT;
if (hostVariable === undefined || portVariable === undefined) {
instances.push({ host: "socket", instance: new Docker() });
return instances;
}
const hosts = hostVariable.split(",");
const ports = portVariable.split(",");
if (hosts.length !== ports.length) {
throw new Error("The number of hosts and ports must match");
}
hosts.forEach((host, i) => {
instances.push({
host: `${host}:${ports[i]}`,
instance: new Docker({
host,
port: parseInt(ports[i] ?? "", 10),
}),
});
return instances;
});
return instances;
}
public static findInstance(key: string): DockerInstance | undefined {
return this.instances.find((instance) => instance.host === key);
}
public static getInstance(): DockerInstance[] {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!DockerSingleton.instances) {
DockerSingleton.instances = new DockerSingleton().createInstances();
}
return this.instances;
}
}
@@ -3,7 +3,7 @@ import { TRPCError } from "@trpc/server";
import { objectEntries } from "@homarr/common"; import { objectEntries } from "@homarr/common";
import { decryptSecret, encryptSecret } from "@homarr/common/server"; import { decryptSecret, encryptSecret } from "@homarr/common/server";
import type { Database } from "@homarr/db"; import type { Database } from "@homarr/db";
import { and, asc, createId, eq, handleTransactionsAsync, inArray, like } from "@homarr/db"; import { and, asc, createId, eq, inArray, like } from "@homarr/db";
import { import {
groupMembers, groupMembers,
groupPermissions, groupPermissions,
@@ -130,16 +130,6 @@ export const integrationRouter = createTRPCRouter({
limit: input.limit, limit: input.limit,
}); });
}), }),
// This is used to get the integrations by their ids it's public because it's needed to get integrations data in the boards
byIds: publicProcedure.input(z.array(z.string())).query(async ({ ctx, input }) => {
return await ctx.db.query.integrations.findMany({
where: inArray(integrations.id, input),
columns: {
id: true,
kind: true,
},
});
}),
byId: protectedProcedure.input(validation.integration.byId).query(async ({ ctx, input }) => { byId: protectedProcedure.input(validation.integration.byId).query(async ({ ctx, input }) => {
await throwIfActionForbiddenAsync(ctx, eq(integrations.id, input.id), "full"); await throwIfActionForbiddenAsync(ctx, eq(integrations.id, input.id), "full");
const integration = await ctx.db.query.integrations.findFirst({ const integration = await ctx.db.query.integrations.findFirst({
@@ -370,45 +360,20 @@ export const integrationRouter = createTRPCRouter({
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
await throwIfActionForbiddenAsync(ctx, eq(integrations.id, input.entityId), "full"); await throwIfActionForbiddenAsync(ctx, eq(integrations.id, input.entityId), "full");
await handleTransactionsAsync(ctx.db, { await ctx.db.transaction(async (transaction) => {
async handleAsync(db, schema) { await transaction
await ctx.db.transaction(async (transaction) => { .delete(integrationUserPermissions)
await transaction .where(eq(integrationUserPermissions.integrationId, input.entityId));
.delete(schema.integrationUserPermissions) if (input.permissions.length === 0) {
.where(eq(schema.integrationUserPermissions.integrationId, input.entityId)); return;
if (input.permissions.length === 0) { }
return; await transaction.insert(integrationUserPermissions).values(
} input.permissions.map((permission) => ({
await transaction.insert(schema.integrationUserPermissions).values( userId: permission.principalId,
input.permissions.map((permission) => ({ permission: permission.permission,
userId: permission.principalId, integrationId: input.entityId,
permission: permission.permission, })),
integrationId: input.entityId, );
})),
);
});
},
handleSync(db) {
db.transaction((transaction) => {
transaction
.delete(integrationUserPermissions)
.where(eq(integrationUserPermissions.integrationId, input.entityId))
.run();
if (input.permissions.length === 0) {
return;
}
transaction
.insert(integrationUserPermissions)
.values(
input.permissions.map((permission) => ({
userId: permission.principalId,
permission: permission.permission,
integrationId: input.entityId,
})),
)
.run();
});
},
}); });
}), }),
saveGroupIntegrationPermissions: protectedProcedure saveGroupIntegrationPermissions: protectedProcedure
@@ -416,45 +381,20 @@ export const integrationRouter = createTRPCRouter({
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
await throwIfActionForbiddenAsync(ctx, eq(integrations.id, input.entityId), "full"); await throwIfActionForbiddenAsync(ctx, eq(integrations.id, input.entityId), "full");
await handleTransactionsAsync(ctx.db, { await ctx.db.transaction(async (transaction) => {
async handleAsync(db, schema) { await transaction
await db.transaction(async (transaction) => { .delete(integrationGroupPermissions)
await transaction .where(eq(integrationGroupPermissions.integrationId, input.entityId));
.delete(schema.integrationGroupPermissions) if (input.permissions.length === 0) {
.where(eq(schema.integrationGroupPermissions.integrationId, input.entityId)); return;
if (input.permissions.length === 0) { }
return; await transaction.insert(integrationGroupPermissions).values(
} input.permissions.map((permission) => ({
await transaction.insert(schema.integrationGroupPermissions).values( groupId: permission.principalId,
input.permissions.map((permission) => ({ permission: permission.permission,
groupId: permission.principalId, integrationId: input.entityId,
permission: permission.permission, })),
integrationId: input.entityId, );
})),
);
});
},
handleSync(db) {
db.transaction((transaction) => {
transaction
.delete(integrationGroupPermissions)
.where(eq(integrationGroupPermissions.integrationId, input.entityId))
.run();
if (input.permissions.length === 0) {
return;
}
transaction
.insert(integrationGroupPermissions)
.values(
input.permissions.map((permission) => ({
groupId: permission.principalId,
permission: permission.permission,
integrationId: input.entityId,
})),
)
.run();
});
},
}); });
}), }),
searchInIntegration: protectedProcedure searchInIntegration: protectedProcedure
+1 -7
View File
@@ -404,13 +404,7 @@ export const userRouter = createTRPCRouter({
}); });
} }
// Only allow user to select boards they have access to await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.userId), "view");
if (input.homeBoardId) {
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.homeBoardId), "view");
}
if (input.mobileHomeBoardId) {
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.mobileHomeBoardId), "view");
}
await ctx.db await ctx.db
.update(users) .update(users)
@@ -1,15 +1,15 @@
import { observable } from "@trpc/server/observable"; import { observable } from "@trpc/server/observable";
import { getIntegrationKindsByCategory } from "@homarr/definitions";
import type { HealthMonitoring } from "@homarr/integrations"; import type { HealthMonitoring } from "@homarr/integrations";
import type { ProxmoxClusterInfo } from "@homarr/integrations/types"; import { systemInfoRequestHandler } from "@homarr/request-handler/health-monitoring";
import { clusterInfoRequestHandler, systemInfoRequestHandler } from "@homarr/request-handler/health-monitoring";
import { createManyIntegrationMiddleware, createOneIntegrationMiddleware } from "../../middlewares/integration"; import { createManyIntegrationMiddleware } from "../../middlewares/integration";
import { createTRPCRouter, publicProcedure } from "../../trpc"; import { createTRPCRouter, publicProcedure } from "../../trpc";
export const healthMonitoringRouter = createTRPCRouter({ export const healthMonitoringRouter = createTRPCRouter({
getSystemHealthStatus: publicProcedure getHealthStatus: publicProcedure
.unstable_concat(createManyIntegrationMiddleware("query", "openmediavault", "dashDot")) .unstable_concat(createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("healthMonitoring")))
.query(async ({ ctx }) => { .query(async ({ ctx }) => {
return await Promise.all( return await Promise.all(
ctx.integrations.map(async (integration) => { ctx.integrations.map(async (integration) => {
@@ -25,8 +25,9 @@ export const healthMonitoringRouter = createTRPCRouter({
}), }),
); );
}), }),
subscribeSystemHealthStatus: publicProcedure
.unstable_concat(createManyIntegrationMiddleware("query", "openmediavault", "dashDot")) subscribeHealthStatus: publicProcedure
.unstable_concat(createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("healthMonitoring")))
.subscription(({ ctx }) => { .subscription(({ ctx }) => {
return observable<{ integrationId: string; healthInfo: HealthMonitoring; timestamp: Date }>((emit) => { return observable<{ integrationId: string; healthInfo: HealthMonitoring; timestamp: Date }>((emit) => {
const unsubscribes: (() => void)[] = []; const unsubscribes: (() => void)[] = [];
@@ -48,26 +49,4 @@ export const healthMonitoringRouter = createTRPCRouter({
}; };
}); });
}), }),
getClusterHealthStatus: publicProcedure
.unstable_concat(createOneIntegrationMiddleware("query", "proxmox"))
.query(async ({ ctx }) => {
const innerHandler = clusterInfoRequestHandler.handler(ctx.integration, {});
const { data } = await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
return data;
}),
subscribeClusterHealthStatus: publicProcedure
.unstable_concat(createOneIntegrationMiddleware("query", "proxmox"))
.subscription(({ ctx }) => {
return observable<ProxmoxClusterInfo>((emit) => {
const unsubscribes: (() => void)[] = [];
const innerHandler = clusterInfoRequestHandler.handler(ctx.integration, {});
const unsubscribe = innerHandler.subscribe((healthInfo) => {
emit.next(healthInfo);
});
unsubscribes.push(unsubscribe);
return () => {
unsubscribe();
};
});
}),
}); });
+7 -31
View File
@@ -1,36 +1,12 @@
import { rssFeedsRequestHandler } from "@homarr/request-handler/rss-feeds"; import type { RssFeed } from "@homarr/cron-jobs";
import { z } from "@homarr/validation"; import { createItemChannel } from "@homarr/redis";
import { createOneItemMiddleware } from "../../middlewares/item";
import { createTRPCRouter, publicProcedure } from "../../trpc"; import { createTRPCRouter, publicProcedure } from "../../trpc";
export const rssFeedRouter = createTRPCRouter({ export const rssFeedRouter = createTRPCRouter({
getFeeds: publicProcedure getFeeds: publicProcedure.unstable_concat(createOneItemMiddleware("rssFeed")).query(async ({ input }) => {
.input( const channel = createItemChannel<RssFeed[]>(input.itemId);
z.object({ return await channel.getAsync();
urls: z.array(z.string()), }),
maximumAmountPosts: z.number(),
}),
)
.query(async ({ input }) => {
const rssFeeds = await Promise.all(
input.urls.map(async (url) => {
const innerHandler = rssFeedsRequestHandler.handler({
url,
count: input.maximumAmountPosts,
});
return await innerHandler.getCachedOrUpdatedDataAsync({
forceUpdate: false,
});
}),
);
return rssFeeds
.flatMap((rssFeed) => rssFeed.data.entries)
.slice(0, input.maximumAmountPosts)
.sort((entryA, entryB) => {
return entryA.published && entryB.published
? new Date(entryB.published).getTime() - new Date(entryA.published).getTime()
: 0;
});
}),
}); });
+4 -7
View File
@@ -2,11 +2,9 @@ import type { ReadonlyHeaders } from "next/dist/server/web/spec-extension/adapte
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import NextAuth from "next-auth"; import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials"; import Credentials from "next-auth/providers/credentials";
import { formatError } from "pretty-print-error";
import { db } from "@homarr/db"; import { db } from "@homarr/db";
import type { SupportedAuthProvider } from "@homarr/definitions"; import type { SupportedAuthProvider } from "@homarr/definitions";
import { logger } from "@homarr/log";
import { createAdapter } from "./adapter"; import { createAdapter } from "./adapter";
import { createSessionCallback } from "./callbacks"; import { createSessionCallback } from "./callbacks";
@@ -28,16 +26,15 @@ export const createConfiguration = (
const adapter = createAdapter(db, provider); const adapter = createAdapter(db, provider);
return NextAuth({ return NextAuth({
logger: { logger: {
error: (error) => { error: (code, ...message) => {
// Remove the big error message for failed login attempts // Remove the big error message for failed login attempts
// as it is not useful for the user. // as it is not useful for the user.
if (error.name === "CredentialsSignin") { if (code.name === "CredentialsSignin") {
logger.warn("The login attempt of a user was not successful."); console.warn("The login attempt of a user was not successful.");
return; return;
} }
logger.error(formatError(error)); console.error(code, ...message);
logger.error(formatError(error.cause));
}, },
}, },
trustHost: true, trustHost: true,
-1
View File
@@ -86,5 +86,4 @@ export const env = createEnv({
AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE: process.env.AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE, AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE: process.env.AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE,
}, },
skipValidation, skipValidation,
emptyStringAsUndefined: true,
}); });
+1 -2
View File
@@ -34,9 +34,8 @@
"bcrypt": "^5.1.1", "bcrypt": "^5.1.1",
"cookies": "^0.9.1", "cookies": "^0.9.1",
"ldapts": "7.3.1", "ldapts": "7.3.1",
"next": "15.1.6", "next": "15.1.4",
"next-auth": "5.0.0-beta.25", "next-auth": "5.0.0-beta.25",
"pretty-print-error": "^1.1.2",
"react": "19.0.0", "react": "19.0.0",
"react-dom": "19.0.0" "react-dom": "19.0.0"
}, },
@@ -1,6 +1,5 @@
import { CredentialsSignin } from "@auth/core/errors"; import { CredentialsSignin } from "@auth/core/errors";
import { extractErrorMessage } from "@homarr/common";
import type { Database, InferInsertModel } from "@homarr/db"; import type { Database, InferInsertModel } from "@homarr/db";
import { and, createId, eq } from "@homarr/db"; import { and, createId, eq } from "@homarr/db";
import { users } from "@homarr/db/schema"; import { users } from "@homarr/db/schema";
@@ -22,8 +21,8 @@ export const authorizeWithLdapCredentialsAsync = async (
distinguishedName: env.AUTH_LDAP_BIND_DN, distinguishedName: env.AUTH_LDAP_BIND_DN,
password: env.AUTH_LDAP_BIND_PASSWORD, password: env.AUTH_LDAP_BIND_PASSWORD,
}) })
.catch((error) => { .catch(() => {
logger.error(`Failed to connect to LDAP server ${extractErrorMessage(error)}`); logger.error("Failed to connect to LDAP server");
throw new CredentialsSignin(); throw new CredentialsSignin();
}); });
-9
View File
@@ -1,9 +0,0 @@
import baseConfig from "@homarr/eslint-config/base";
/** @type {import('typescript-eslint').Config} */
export default [
{
ignores: [],
},
...baseConfig,
];
-35
View File
@@ -1,35 +0,0 @@
{
"name": "@homarr/certificates",
"version": "0.1.0",
"private": true,
"license": "MIT",
"type": "module",
"exports": {
"./server": "./src/server.ts"
},
"typesVersions": {
"*": {
"*": [
"src/*"
]
}
},
"scripts": {
"clean": "rm -rf .turbo node_modules",
"format": "prettier --check . --ignore-path ../../.gitignore",
"lint": "eslint",
"typecheck": "tsc --noEmit"
},
"prettier": "@homarr/prettier-config",
"dependencies": {
"@homarr/common": "workspace:^0.1.0",
"undici": "7.3.0"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"eslint": "^9.18.0",
"typescript": "^5.7.3"
}
}
-87
View File
@@ -1,87 +0,0 @@
import fsSync from "node:fs";
import fs from "node:fs/promises";
import { Agent } from "node:https";
import path from "node:path";
import { rootCertificates } from "node:tls";
import axios from "axios";
import { fetch } from "undici";
import { LoggingAgent } from "@homarr/common/server";
const getCertificateFolder = () => {
return process.env.NODE_ENV === "production"
? path.join("/appdata", "trusted-certificates")
: process.env.LOCAL_CERTIFICATE_PATH;
};
export const loadCustomRootCertificatesAsync = async () => {
const folder = getCertificateFolder();
if (!folder) {
return [];
}
if (!fsSync.existsSync(folder)) {
await fs.mkdir(folder, { recursive: true });
}
const dirContent = await fs.readdir(folder);
return await Promise.all(
dirContent
.filter((file) => file.endsWith(".crt"))
.map(async (file) => ({
content: await fs.readFile(path.join(folder, file), "utf8"),
fileName: file,
})),
);
};
export const removeCustomRootCertificateAsync = async (fileName: string) => {
const folder = getCertificateFolder();
if (!folder) {
return;
}
await fs.rm(path.join(folder, fileName));
};
export const addCustomRootCertificateAsync = async (fileName: string, content: string) => {
const folder = getCertificateFolder();
if (!folder) {
throw new Error(
"When you want to use custom certificates locally you need to set LOCAL_CERTIFICATE_PATH to an absolute path",
);
}
if (fileName.includes("/")) {
throw new Error("Invalid file name");
}
await fs.writeFile(path.join(folder, fileName), content);
};
export const createCertificateAgentAsync = async () => {
const customCertificates = await loadCustomRootCertificatesAsync();
return new LoggingAgent({
connect: {
ca: rootCertificates.concat(customCertificates.map((cert) => cert.content)),
},
});
};
export const createAxiosCertificateInstanceAsync = async () => {
const customCertificates = await loadCustomRootCertificatesAsync();
return axios.create({
httpsAgent: new Agent({
ca: rootCertificates.concat(customCertificates.map((cert) => cert.content)),
}),
});
};
export const fetchWithTrustedCertificatesAsync: typeof fetch = async (url, options) => {
const agent = await createCertificateAgentAsync();
return fetch(url, {
...options,
dispatcher: agent,
});
};
-8
View File
@@ -1,8 +0,0 @@
{
"extends": "@homarr/tsconfig/base.json",
"compilerOptions": {
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
},
"include": ["*.ts", "src"],
"exclude": ["node_modules"]
}
-1
View File
@@ -26,5 +26,4 @@ export const env = createEnv({
SECRET_ENCRYPTION_KEY: process.env.SECRET_ENCRYPTION_KEY, SECRET_ENCRYPTION_KEY: process.env.SECRET_ENCRYPTION_KEY,
}, },
skipValidation: shouldSkipEnvValidation(), skipValidation: shouldSkipEnvValidation(),
emptyStringAsUndefined: true,
}); });
+1 -2
View File
@@ -29,10 +29,9 @@
"dependencies": { "dependencies": {
"@homarr/log": "workspace:^0.1.0", "@homarr/log": "workspace:^0.1.0",
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"next": "15.1.6", "next": "15.1.4",
"react": "19.0.0", "react": "19.0.0",
"react-dom": "19.0.0", "react-dom": "19.0.0",
"undici": "7.3.0",
"zod": "^3.24.1" "zod": "^3.24.1"
}, },
"devDependencies": { "devDependencies": {
-32
View File
@@ -1,32 +0,0 @@
import type { Dispatcher } from "undici";
import { Agent } from "undici";
import { logger } from "@homarr/log";
export class LoggingAgent extends Agent {
constructor(...props: ConstructorParameters<typeof Agent>) {
super(...props);
}
dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean {
const url = new URL(`${options.origin as string}${options.path}`);
// The below code should prevent sensitive data from being logged as
// some integrations use query parameters for auth
url.searchParams.forEach((value, key) => {
if (value === "") return; // Skip empty values
if (/^-?\d{1,12}$/.test(value)) return; // Skip small numbers
if (value === "true" || value === "false") return; // Skip boolean values
if (/^[a-zA-Z]{1,12}$/.test(value)) return; // Skip short strings
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return; // Skip dates
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) return; // Skip date times
url.searchParams.set(key, "REDACTED");
});
logger.info(
`Dispatching request ${url.toString().replaceAll("=&", "&")} (${Object.keys(options.headers ?? {}).length} headers)`,
);
return super.dispatch(options, handler);
}
}
-1
View File
@@ -1,4 +1,3 @@
export * from "./security"; export * from "./security";
export * from "./encryption"; export * from "./encryption";
export * from "./user-agent"; export * from "./user-agent";
export * from "./fetch-agent";
+1
View File
@@ -22,6 +22,7 @@
}, },
"prettier": "@homarr/prettier-config", "prettier": "@homarr/prettier-config",
"dependencies": { "dependencies": {
"@extractus/feed-extractor": "^7.1.3",
"@homarr/analytics": "workspace:^0.1.0", "@homarr/analytics": "workspace:^0.1.0",
"@homarr/auth": "workspace:^0.1.0", "@homarr/auth": "workspace:^0.1.0",
"@homarr/common": "workspace:^0.1.0", "@homarr/common": "workspace:^0.1.0",
+2
View File
@@ -11,6 +11,7 @@ import { mediaServerJob } from "./jobs/integrations/media-server";
import { mediaTranscodingJob } from "./jobs/integrations/media-transcoding"; import { mediaTranscodingJob } from "./jobs/integrations/media-transcoding";
import { minecraftServerStatusJob } from "./jobs/minecraft-server-status"; import { minecraftServerStatusJob } from "./jobs/minecraft-server-status";
import { pingJob } from "./jobs/ping"; import { pingJob } from "./jobs/ping";
import type { RssFeed } from "./jobs/rss-feeds";
import { rssFeedsJob } from "./jobs/rss-feeds"; import { rssFeedsJob } from "./jobs/rss-feeds";
import { sessionCleanupJob } from "./jobs/session-cleanup"; import { sessionCleanupJob } from "./jobs/session-cleanup";
import { updateCheckerJob } from "./jobs/update-checker"; import { updateCheckerJob } from "./jobs/update-checker";
@@ -37,3 +38,4 @@ export const jobGroup = createCronJobGroup({
}); });
export type JobGroupKeys = ReturnType<(typeof jobGroup)["getKeys"]>[number]; export type JobGroupKeys = ReturnType<(typeof jobGroup)["getKeys"]>[number];
export type { RssFeed };
+35 -73
View File
@@ -1,7 +1,7 @@
import { splitToNChunks, Stopwatch } from "@homarr/common"; import { splitToNChunks, Stopwatch } from "@homarr/common";
import { EVERY_WEEK } from "@homarr/cron-jobs-core/expressions"; import { EVERY_WEEK } from "@homarr/cron-jobs-core/expressions";
import type { InferInsertModel } from "@homarr/db"; import type { InferInsertModel } from "@homarr/db";
import { db, handleTransactionsAsync, inArray, sql } from "@homarr/db"; import { db, inArray, sql } from "@homarr/db";
import { createId } from "@homarr/db/client"; import { createId } from "@homarr/db/client";
import { iconRepositories, icons } from "@homarr/db/schema"; import { iconRepositories, icons } from "@homarr/db/schema";
import { fetchIconsAsync } from "@homarr/icons"; import { fetchIconsAsync } from "@homarr/icons";
@@ -83,81 +83,43 @@ export const iconsUpdaterJob = createCronJob("iconsUpdater", EVERY_WEEK, {
(iconRepository) => !repositoryIconGroups.some((group) => group.slug === iconRepository.slug), (iconRepository) => !repositoryIconGroups.some((group) => group.slug === iconRepository.slug),
); );
await handleTransactionsAsync(db, { db.transaction((transaction) => {
async handleAsync(db, schema) { if (newIconRepositories.length >= 1) {
await db.transaction(async (transaction) => { transaction.insert(iconRepositories).values(newIconRepositories).run();
if (newIconRepositories.length >= 1) { }
await transaction.insert(schema.iconRepositories).values(newIconRepositories);
}
if (newIcons.length >= 1) { if (newIcons.length >= 1) {
// We only insert 5000 icons at a time to avoid SQLite limitations // We only insert 5000 icons at a time to avoid SQLite limitations
for (const chunck of splitToNChunks(newIcons, Math.ceil(newIcons.length / 5000))) { for (const chunck of splitToNChunks(newIcons, Math.ceil(newIcons.length / 5000))) {
await transaction.insert(schema.icons).values(chunck); transaction.insert(icons).values(chunck).run();
} }
} }
if (deadIcons.length >= 1) { if (deadIcons.length >= 1) {
await transaction.delete(schema.icons).where( transaction
inArray( .delete(icons)
// Combine iconRepositoryId and checksum to allow same icons on different repositories .where(
sql`concat(${icons.iconRepositoryId}, '.', ${icons.checksum})`, inArray(
deadIcons.map((icon) => `${icon.iconRepositoryId}.${icon.checksum}`), // Combine iconRepositoryId and checksum to allow same icons on different repositories
), sql`concat(${icons.iconRepositoryId}, '.', ${icons.checksum})`,
); deadIcons.map((icon) => `${icon.iconRepositoryId}.${icon.checksum}`),
} ),
)
.run();
}
if (deadIconRepositories.length >= 1) { if (deadIconRepositories.length >= 1) {
await transaction.delete(schema.iconRepositories).where( transaction
inArray( .delete(iconRepositories)
iconRepositories.id, .where(
deadIconRepositories.map((iconRepository) => iconRepository.id), inArray(
), iconRepositories.id,
); deadIconRepositories.map((iconRepository) => iconRepository.id),
} ),
)
.run();
}
countDeleted += deadIcons.length; countDeleted += deadIcons.length;
});
},
handleSync() {
db.transaction((transaction) => {
if (newIconRepositories.length >= 1) {
transaction.insert(iconRepositories).values(newIconRepositories).run();
}
if (newIcons.length >= 1) {
// We only insert 5000 icons at a time to avoid SQLite limitations
for (const chunck of splitToNChunks(newIcons, Math.ceil(newIcons.length / 5000))) {
transaction.insert(icons).values(chunck).run();
}
}
if (deadIcons.length >= 1) {
transaction
.delete(icons)
.where(
inArray(
// Combine iconRepositoryId and checksum to allow same icons on different repositories
sql`concat(${icons.iconRepositoryId}, '.', ${icons.checksum})`,
deadIcons.map((icon) => `${icon.iconRepositoryId}.${icon.checksum}`),
),
)
.run();
}
if (deadIconRepositories.length >= 1) {
transaction
.delete(iconRepositories)
.where(
inArray(
iconRepositories.id,
deadIconRepositories.map((iconRepository) => iconRepository.id),
),
)
.run();
}
countDeleted += deadIcons.length;
});
},
}); });
logger.info(`Updated database within ${stopWatch.getElapsedInHumanWords()} (-${countDeleted}, +${countInserted})`); logger.info(`Updated database within ${stopWatch.getElapsedInHumanWords()} (-${countDeleted}, +${countInserted})`);
@@ -1,23 +1,14 @@
import { EVERY_5_SECONDS } from "@homarr/cron-jobs-core/expressions"; import { EVERY_5_SECONDS } from "@homarr/cron-jobs-core/expressions";
import { clusterInfoRequestHandler, systemInfoRequestHandler } from "@homarr/request-handler/health-monitoring"; import { systemInfoRequestHandler } from "@homarr/request-handler/health-monitoring";
import { createRequestIntegrationJobHandler } from "@homarr/request-handler/lib/cached-request-integration-job-handler"; import { createRequestIntegrationJobHandler } from "@homarr/request-handler/lib/cached-request-integration-job-handler";
import { createCronJob } from "../../lib"; import { createCronJob } from "../../lib";
export const healthMonitoringJob = createCronJob("healthMonitoring", EVERY_5_SECONDS).withCallback( export const healthMonitoringJob = createCronJob("healthMonitoring", EVERY_5_SECONDS).withCallback(
createRequestIntegrationJobHandler( createRequestIntegrationJobHandler(systemInfoRequestHandler.handler, {
(integration, itemOptions: Record<string, never>) => { widgetKinds: ["healthMonitoring"],
const { kind } = integration; getInput: {
if (kind !== "proxmox") { healthMonitoring: () => ({}),
return systemInfoRequestHandler.handler({ ...integration, kind }, itemOptions);
}
return clusterInfoRequestHandler.handler({ ...integration, kind }, itemOptions);
}, },
{ }),
widgetKinds: ["healthMonitoring"],
getInput: {
healthMonitoring: () => ({}),
},
},
),
); );
+122 -19
View File
@@ -1,36 +1,139 @@
import type { FeedData, FeedEntry } from "@extractus/feed-extractor";
import { extract } from "@extractus/feed-extractor";
import SuperJSON from "superjson"; import SuperJSON from "superjson";
import type { Modify } from "@homarr/common/types";
import { EVERY_5_MINUTES } from "@homarr/cron-jobs-core/expressions"; import { EVERY_5_MINUTES } from "@homarr/cron-jobs-core/expressions";
import { db, eq } from "@homarr/db"; import { db, eq } from "@homarr/db";
import { items } from "@homarr/db/schema"; import { items } from "@homarr/db/schema";
import { logger } from "@homarr/log"; import { logger } from "@homarr/log";
// This import is done that way to avoid circular dependencies. import { createItemChannel } from "@homarr/redis";
import { rssFeedsRequestHandler } from "@homarr/request-handler/rss-feeds"; import { z } from "@homarr/validation";
// This import is done that way to avoid circular dependencies.
import type { WidgetComponentProps } from "../../../widgets"; import type { WidgetComponentProps } from "../../../widgets";
import { createCronJob } from "../lib"; import { createCronJob } from "../lib";
export const rssFeedsJob = createCronJob("rssFeeds", EVERY_5_MINUTES).withCallback(async () => { export const rssFeedsJob = createCronJob("rssFeeds", EVERY_5_MINUTES).withCallback(async () => {
const rssItems = await db.query.items.findMany({ const itemsForIntegration = await db.query.items.findMany({
where: eq(items.kind, "rssFeed"), where: eq(items.kind, "rssFeed"),
}); });
const itemOptions = rssItems.map((item) => SuperJSON.parse<WidgetComponentProps<"rssFeed">["options"]>(item.options)); for (const item of itemsForIntegration) {
const options = SuperJSON.parse<WidgetComponentProps<"rssFeed">["options"]>(item.options);
for (const option of itemOptions) { const feeds = await Promise.all(
const maxAmountPosts = typeof option.maximumAmountPosts === "number" ? option.maximumAmountPosts : 100; options.feedUrls.map(async (feedUrl) => ({
for (const url of option.feedUrls) { feedUrl,
try { feed: (await extract(feedUrl, {
const innerHandler = rssFeedsRequestHandler.handler({ getExtraEntryFields: (feedEntry) => {
url, const media = attemptGetImageFromEntry(feedUrl, feedEntry);
count: maxAmountPosts, if (!media) {
}); return {};
await innerHandler.getCachedOrUpdatedDataAsync({ }
forceUpdate: true, return {
}); enclosure: media,
} catch (error) { };
logger.error("Failed to update RSS feed", { url, error }); },
} })) as ExtendedFeedData,
} })),
);
const channel = createItemChannel<RssFeed[]>(item.id);
await channel.publishAndUpdateLastStateAsync(feeds);
} }
}); });
const attemptGetImageFromEntry = (feedUrl: string, entry: object) => {
const media = getFirstMediaProperty(entry);
if (media !== null) {
return media;
}
return getImageFromStringAsFallback(feedUrl, JSON.stringify(entry));
};
const getImageFromStringAsFallback = (feedUrl: string, content: string) => {
const regex = /https?:\/\/\S+?\.(jpg|jpeg|png|gif|bmp|svg|webp|tiff)/i;
const result = regex.exec(content);
if (result == null) {
return null;
}
console.debug(
`Falling back to regex image search for '${feedUrl}'. Found ${result.length} matches in content: ${content}`,
);
return result[0];
};
const mediaProperties = [
{
path: ["enclosure", "@_url"],
},
{
path: ["media:content", "@_url"],
},
];
/**
* The RSS and Atom standards are poorly adhered to in most of the web.
* We want to show pretty background images on the posts and therefore need to extract
* the enclosure (aka. media images). This function uses the dynamic properties defined above
* to search through the possible paths and detect valid image URLs.
* @param feedObject The object to scan for.
* @returns the value of the first path that is found within the object
*/
const getFirstMediaProperty = (feedObject: object) => {
for (const mediaProperty of mediaProperties) {
let propertyIndex = 0;
let objectAtPath: object = feedObject;
while (propertyIndex < mediaProperty.path.length) {
const key = mediaProperty.path[propertyIndex];
if (key === undefined) {
break;
}
const propertyEntries = Object.entries(objectAtPath);
const propertyEntry = propertyEntries.find(([entryKey]) => entryKey === key);
if (!propertyEntry) {
break;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const [_, propertyEntryValue] = propertyEntry;
objectAtPath = propertyEntryValue as object;
propertyIndex++;
}
const validationResult = z.string().url().safeParse(objectAtPath);
if (!validationResult.success) {
continue;
}
logger.debug(`Found an image in the feed entry: ${validationResult.data}`);
return validationResult.data;
}
return null;
};
/**
* We extend the feed with custom properties.
* This interface adds properties on top of the default ones.
*/
interface ExtendedFeedEntry extends FeedEntry {
enclosure?: string;
}
/**
* We extend the feed with custom properties.
* This interface omits the default entries with our custom definition.
*/
type ExtendedFeedData = Modify<
FeedData,
{
entries?: ExtendedFeedEntry;
}
>;
export interface RssFeed {
feedUrl: string;
feed: ExtendedFeedData;
}
+1 -3
View File
@@ -2,7 +2,6 @@ import Database from "better-sqlite3";
import type { Logger } from "drizzle-orm"; import type { Logger } from "drizzle-orm";
import type { BetterSQLite3Database } from "drizzle-orm/better-sqlite3"; import type { BetterSQLite3Database } from "drizzle-orm/better-sqlite3";
import { drizzle as drizzleSqlite } from "drizzle-orm/better-sqlite3"; import { drizzle as drizzleSqlite } from "drizzle-orm/better-sqlite3";
import type { MySql2Database } from "drizzle-orm/mysql2";
import { drizzle as drizzleMysql } from "drizzle-orm/mysql2"; import { drizzle as drizzleMysql } from "drizzle-orm/mysql2";
import mysql from "mysql2"; import mysql from "mysql2";
@@ -12,8 +11,7 @@ import { env } from "./env";
import * as mysqlSchema from "./schema/mysql"; import * as mysqlSchema from "./schema/mysql";
import * as sqliteSchema from "./schema/sqlite"; import * as sqliteSchema from "./schema/sqlite";
export type HomarrDatabase = BetterSQLite3Database<typeof sqliteSchema>; type HomarrDatabase = BetterSQLite3Database<typeof sqliteSchema>;
export type HomarrDatabaseMysql = MySql2Database<typeof mysqlSchema>;
const init = () => { const init = () => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
+1 -6
View File
@@ -27,11 +27,7 @@ export const env = createEnv({
.default(drivers.betterSqlite3), .default(drivers.betterSqlite3),
...(urlRequired ...(urlRequired
? { ? {
DB_URL: DB_URL: z.string(),
// Fallback to the default sqlite file path in production
process.env.NODE_ENV === "production" && isDriver("better-sqlite3")
? z.string().default("/appdata/db/db.sqlite")
: z.string().nonempty(),
} }
: {}), : {}),
...(hostRequired ...(hostRequired
@@ -62,5 +58,4 @@ export const env = createEnv({
DB_PORT: process.env.DB_PORT, DB_PORT: process.env.DB_PORT,
}, },
skipValidation: shouldSkipEnvValidation(), skipValidation: shouldSkipEnvValidation(),
emptyStringAsUndefined: true,
}); });
-2
View File
@@ -7,7 +7,5 @@ export * from "drizzle-orm";
export const db = database; export const db = database;
export type Database = typeof db; export type Database = typeof db;
export type { HomarrDatabaseMysql } from "./driver";
export { createId } from "@paralleldrive/cuid2"; export { createId } from "@paralleldrive/cuid2";
export { handleDiffrentDbDriverOperationsAsync as handleTransactionsAsync } from "./transactions";
+4 -4
View File
@@ -44,11 +44,11 @@
"@homarr/server-settings": "workspace:^0.1.0", "@homarr/server-settings": "workspace:^0.1.0",
"@paralleldrive/cuid2": "^2.2.2", "@paralleldrive/cuid2": "^2.2.2",
"@t3-oss/env-nextjs": "^0.11.1", "@t3-oss/env-nextjs": "^0.11.1",
"@testcontainers/mysql": "^10.17.1", "@testcontainers/mysql": "^10.16.0",
"better-sqlite3": "^11.8.1", "better-sqlite3": "^11.7.2",
"dotenv": "^16.4.7", "dotenv": "^16.4.7",
"drizzle-kit": "^0.30.2", "drizzle-kit": "^0.30.1",
"drizzle-orm": "^0.38.4", "drizzle-orm": "^0.38.3",
"drizzle-zod": "^0.6.1", "drizzle-zod": "^0.6.1",
"mysql2": "3.12.0" "mysql2": "3.12.0"
}, },
-24
View File
@@ -1,24 +0,0 @@
import type { HomarrDatabase, HomarrDatabaseMysql } from "./driver";
import { env } from "./env";
import * as mysqlSchema from "./schema/mysql";
type MysqlSchema = typeof mysqlSchema;
interface HandleTransactionInput {
handleAsync: (db: HomarrDatabaseMysql, schema: MysqlSchema) => Promise<void>;
handleSync: (db: HomarrDatabase) => void;
}
/**
* The below method is mostly used to handle transactions in different database drivers.
* As better-sqlite3 transactions have to be synchronous, we have to implement them in a different way.
* But it can also generally be used when dealing with different database drivers.
*/
export const handleDiffrentDbDriverOperationsAsync = async (db: HomarrDatabase, input: HandleTransactionInput) => {
if (env.DB_DRIVER !== "mysql2") {
input.handleSync(db);
return;
}
await input.handleAsync(db as unknown as HomarrDatabaseMysql, mysqlSchema);
};
@@ -10,7 +10,6 @@ export type HomarrDocumentationPath =
| "/blog/2024/09/23/version-1.0" | "/blog/2024/09/23/version-1.0"
| "/blog/2024/12/17/open-beta-1.0" | "/blog/2024/12/17/open-beta-1.0"
| "/blog/2024/12/31/migrate-secret-enryption-key" | "/blog/2024/12/31/migrate-secret-enryption-key"
| "/blog/2025/01/19/migration-guide-1.0"
| "/blog/archive" | "/blog/archive"
| "/blog/authors" | "/blog/authors"
| "/blog/authors/ajnart" | "/blog/authors/ajnart"
@@ -52,7 +51,6 @@ export type HomarrDocumentationPath =
| "/docs/tags/bookmark" | "/docs/tags/bookmark"
| "/docs/tags/bookmarks" | "/docs/tags/bookmarks"
| "/docs/tags/caddy" | "/docs/tags/caddy"
| "/docs/tags/certificates"
| "/docs/tags/checklist" | "/docs/tags/checklist"
| "/docs/tags/code" | "/docs/tags/code"
| "/docs/tags/community" | "/docs/tags/community"
@@ -115,7 +113,6 @@ export type HomarrDocumentationPath =
| "/docs/tags/search" | "/docs/tags/search"
| "/docs/tags/search-engines" | "/docs/tags/search-engines"
| "/docs/tags/security" | "/docs/tags/security"
| "/docs/tags/self-signed"
| "/docs/tags/seo" | "/docs/tags/seo"
| "/docs/tags/server" | "/docs/tags/server"
| "/docs/tags/settings" | "/docs/tags/settings"
@@ -166,10 +163,10 @@ export type HomarrDocumentationPath =
| "/docs/getting-started/installation/home-assistant" | "/docs/getting-started/installation/home-assistant"
| "/docs/getting-started/installation/portainer" | "/docs/getting-started/installation/portainer"
| "/docs/getting-started/installation/qnap" | "/docs/getting-started/installation/qnap"
| "/docs/getting-started/installation/railway"
| "/docs/getting-started/installation/saltbox" | "/docs/getting-started/installation/saltbox"
| "/docs/getting-started/installation/source" | "/docs/getting-started/installation/source"
| "/docs/getting-started/installation/synology" | "/docs/getting-started/installation/synology"
| "/docs/getting-started/installation/truenas"
| "/docs/getting-started/installation/unraid" | "/docs/getting-started/installation/unraid"
| "/docs/integrations/containers" | "/docs/integrations/containers"
| "/docs/integrations/dns" | "/docs/integrations/dns"
@@ -182,7 +179,6 @@ export type HomarrDocumentationPath =
| "/docs/management/api" | "/docs/management/api"
| "/docs/management/apps" | "/docs/management/apps"
| "/docs/management/boards" | "/docs/management/boards"
| "/docs/management/certificates"
| "/docs/management/integrations" | "/docs/management/integrations"
| "/docs/management/media" | "/docs/management/media"
| "/docs/management/search-engines" | "/docs/management/search-engines"
+1 -1
View File
@@ -1,6 +1,6 @@
import type { HomarrDocumentationPath } from "./homarr-docs-sitemap"; import type { HomarrDocumentationPath } from "./homarr-docs-sitemap";
const documentationBaseUrl = "https://homarr.dev"; const documentationBaseUrl = "https://deploy-preview-113--homarr-docs.netlify.app";
// Please use the method so the path can be checked! // Please use the method so the path can be checked!
export const createDocumentationLink = (path: HomarrDocumentationPath, hashTag?: `#${string}`) => export const createDocumentationLink = (path: HomarrDocumentationPath, hashTag?: `#${string}`) =>
-8
View File
@@ -5,8 +5,6 @@ export const integrationSecretKindObject = {
apiKey: { isPublic: false }, apiKey: { isPublic: false },
username: { isPublic: true }, username: { isPublic: true },
password: { isPublic: false }, password: { isPublic: false },
tokenId: { isPublic: true },
realm: { isPublic: true },
} satisfies Record<string, { isPublic: boolean }>; } satisfies Record<string, { isPublic: boolean }>;
export const integrationSecretKinds = objectKeys(integrationSecretKindObject); export const integrationSecretKinds = objectKeys(integrationSecretKindObject);
@@ -139,12 +137,6 @@ export const integrationDefs = {
category: ["mediaTranscoding"], category: ["mediaTranscoding"],
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/png/tdarr.png", iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/png/tdarr.png",
}, },
proxmox: {
name: "Proxmox",
secretKinds: [["username", "tokenId", "apiKey", "realm"]],
category: ["healthMonitoring"],
iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/proxmox.png",
},
} as const satisfies Record<string, integrationDefinition>; } as const satisfies Record<string, integrationDefinition>;
export const integrationKinds = objectKeys(integrationDefs) as AtLeastOneOf<IntegrationKind>; export const integrationKinds = objectKeys(integrationDefs) as AtLeastOneOf<IntegrationKind>;
-9
View File
@@ -1,9 +0,0 @@
import baseConfig from "@homarr/eslint-config/base";
/** @type {import('typescript-eslint').Config} */
export default [
{
ignores: [],
},
...baseConfig,
];
-1
View File
@@ -1 +0,0 @@
export * from "./src";
-38
View File
@@ -1,38 +0,0 @@
{
"name": "@homarr/docker",
"version": "0.1.0",
"private": true,
"license": "MIT",
"type": "module",
"exports": {
".": "./index.ts",
"./env": "./src/env.ts"
},
"typesVersions": {
"*": {
"*": [
"src/*"
]
}
},
"scripts": {
"clean": "rm -rf .turbo node_modules",
"format": "prettier --check . --ignore-path ../../.gitignore",
"lint": "eslint",
"typecheck": "tsc --noEmit"
},
"prettier": "@homarr/prettier-config",
"dependencies": {
"@homarr/common": "workspace:^0.1.0",
"@t3-oss/env-nextjs": "^0.11.1",
"dockerode": "^4.0.4"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"@types/dockerode": "^3.3.34",
"eslint": "^9.18.0",
"typescript": "^5.7.3"
}
}
-18
View File
@@ -1,18 +0,0 @@
import { createEnv } from "@t3-oss/env-nextjs";
import { z } from "zod";
import { shouldSkipEnvValidation } from "@homarr/common/env-validation";
export const env = createEnv({
server: {
// Comma separated list of docker hostnames that can be used to connect to query the docker endpoints (localhost:2375,host.docker.internal:2375, ...)
DOCKER_HOSTNAMES: z.string().optional(),
DOCKER_PORTS: z.string().optional(),
},
runtimeEnv: {
DOCKER_HOSTNAMES: process.env.DOCKER_HOSTNAMES,
DOCKER_PORTS: process.env.DOCKER_PORTS,
},
skipValidation: shouldSkipEnvValidation(),
emptyStringAsUndefined: true,
});
-10
View File
@@ -1,10 +0,0 @@
import type Docker from "dockerode";
export type { DockerInstance } from "./singleton";
export { DockerSingleton } from "./singleton";
export type { ContainerInfo, Container, Port } from "dockerode";
export type { Docker };
export const containerStates = ["created", "running", "paused", "restarting", "exited", "removing", "dead"] as const;
export type ContainerState = (typeof containerStates)[number];
-53
View File
@@ -1,53 +0,0 @@
import Docker from "dockerode";
import { env } from "./env";
export interface DockerInstance {
host: string;
instance: Docker;
}
export class DockerSingleton {
private static instances: DockerInstance[] | null = null;
private createInstances() {
const hostVariable = env.DOCKER_HOSTNAMES;
const portVariable = env.DOCKER_PORTS;
if (hostVariable === undefined || portVariable === undefined) {
return [{ host: "socket", instance: new Docker() }];
}
const hostnames = hostVariable.split(",");
const ports = portVariable.split(",");
if (hostnames.length !== ports.length) {
throw new Error("The number of hosts and ports must match");
}
return hostnames.map((host, i) => {
// Check above ensures that ports[i] is not undefined
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const port = ports[i]!;
return {
host: `${host}:${port}`,
instance: new Docker({
host,
port: parseInt(port, 10),
}),
};
});
}
public static findInstance(host: string): DockerInstance | undefined {
return this.instances?.find((instance) => instance.host === host);
}
public static getInstances(): DockerInstance[] {
if (this.instances) {
return this.instances;
}
this.instances = new DockerSingleton().createInstances();
return this.instances;
}
}
-8
View File
@@ -1,8 +0,0 @@
{
"extends": "@homarr/tsconfig/base.json",
"compilerOptions": {
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
},
"include": ["*.ts", "src"],
"exclude": ["node_modules"]
}
+1 -1
View File
@@ -26,7 +26,7 @@
"@homarr/common": "workspace:^0.1.0", "@homarr/common": "workspace:^0.1.0",
"@homarr/translation": "workspace:^0.1.0", "@homarr/translation": "workspace:^0.1.0",
"@homarr/validation": "workspace:^0.1.0", "@homarr/validation": "workspace:^0.1.0",
"@mantine/form": "^7.16.1" "@mantine/form": "^7.16.0"
}, },
"devDependencies": { "devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0", "@homarr/eslint-config": "workspace:^0.2.0",
-3
View File
@@ -27,7 +27,6 @@
"@ctrl/deluge": "^7.1.0", "@ctrl/deluge": "^7.1.0",
"@ctrl/qbittorrent": "^9.2.0", "@ctrl/qbittorrent": "^9.2.0",
"@ctrl/transmission": "^7.2.0", "@ctrl/transmission": "^7.2.0",
"@homarr/certificates": "workspace:^0.1.0",
"@homarr/common": "workspace:^0.1.0", "@homarr/common": "workspace:^0.1.0",
"@homarr/db": "workspace:^0.1.0", "@homarr/db": "workspace:^0.1.0",
"@homarr/definitions": "workspace:^0.1.0", "@homarr/definitions": "workspace:^0.1.0",
@@ -36,8 +35,6 @@
"@homarr/translation": "workspace:^0.1.0", "@homarr/translation": "workspace:^0.1.0",
"@homarr/validation": "workspace:^0.1.0", "@homarr/validation": "workspace:^0.1.0",
"@jellyfin/sdk": "^0.11.0", "@jellyfin/sdk": "^0.11.0",
"proxmox-api": "1.1.1",
"undici": "7.3.0",
"xml2js": "^0.6.2" "xml2js": "^0.6.2"
}, },
"devDependencies": { "devDependencies": {
@@ -1,5 +1,3 @@
import { fetchWithTrustedCertificatesAsync } from "@homarr/certificates/server";
import { Integration } from "../base/integration"; import { Integration } from "../base/integration";
import { IntegrationTestConnectionError } from "../base/test-connection-error"; import { IntegrationTestConnectionError } from "../base/test-connection-error";
import type { DnsHoleSummaryIntegration } from "../interfaces/dns-hole-summary/dns-hole-summary-integration"; import type { DnsHoleSummaryIntegration } from "../interfaces/dns-hole-summary/dns-hole-summary-integration";
@@ -8,7 +6,7 @@ import { filteringStatusSchema, statsResponseSchema, statusResponseSchema } from
export class AdGuardHomeIntegration extends Integration implements DnsHoleSummaryIntegration { export class AdGuardHomeIntegration extends Integration implements DnsHoleSummaryIntegration {
public async getSummaryAsync(): Promise<DnsHoleSummary> { public async getSummaryAsync(): Promise<DnsHoleSummary> {
const statsResponse = await fetchWithTrustedCertificatesAsync(this.url("/control/stats"), { const statsResponse = await fetch(this.url("/control/stats"), {
headers: { headers: {
Authorization: `Basic ${this.getAuthorizationHeaderValue()}`, Authorization: `Basic ${this.getAuthorizationHeaderValue()}`,
}, },
@@ -20,7 +18,7 @@ export class AdGuardHomeIntegration extends Integration implements DnsHoleSummar
); );
} }
const statusResponse = await fetchWithTrustedCertificatesAsync(this.url("/control/status"), { const statusResponse = await fetch(this.url("/control/status"), {
headers: { headers: {
Authorization: `Basic ${this.getAuthorizationHeaderValue()}`, Authorization: `Basic ${this.getAuthorizationHeaderValue()}`,
}, },
@@ -32,7 +30,7 @@ export class AdGuardHomeIntegration extends Integration implements DnsHoleSummar
); );
} }
const filteringStatusResponse = await fetchWithTrustedCertificatesAsync(this.url("/control/filtering/status"), { const filteringStatusResponse = await fetch(this.url("/control/filtering/status"), {
headers: { headers: {
Authorization: `Basic ${this.getAuthorizationHeaderValue()}`, Authorization: `Basic ${this.getAuthorizationHeaderValue()}`,
}, },
@@ -88,7 +86,7 @@ export class AdGuardHomeIntegration extends Integration implements DnsHoleSummar
public async testConnectionAsync(): Promise<void> { public async testConnectionAsync(): Promise<void> {
await super.handleTestConnectionResponseAsync({ await super.handleTestConnectionResponseAsync({
queryFunctionAsync: async () => { queryFunctionAsync: async () => {
return await fetchWithTrustedCertificatesAsync(this.url("/control/status"), { return await fetch(this.url("/control/status"), {
headers: { headers: {
Authorization: `Basic ${this.getAuthorizationHeaderValue()}`, Authorization: `Basic ${this.getAuthorizationHeaderValue()}`,
}, },
@@ -96,7 +94,7 @@ export class AdGuardHomeIntegration extends Integration implements DnsHoleSummar
}, },
handleResponseAsync: async (response) => { handleResponseAsync: async (response) => {
try { try {
const result = await response.json(); const result = (await response.json()) as unknown;
if (typeof result === "object" && result !== null) return; if (typeof result === "object" && result !== null) return;
} catch { } catch {
throw new IntegrationTestConnectionError("invalidJson"); throw new IntegrationTestConnectionError("invalidJson");
@@ -108,7 +106,7 @@ export class AdGuardHomeIntegration extends Integration implements DnsHoleSummar
} }
public async enableAsync(): Promise<void> { public async enableAsync(): Promise<void> {
const response = await fetchWithTrustedCertificatesAsync(this.url("/control/protection"), { const response = await fetch(this.url("/control/protection"), {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -126,7 +124,7 @@ export class AdGuardHomeIntegration extends Integration implements DnsHoleSummar
} }
public async disableAsync(duration = 0): Promise<void> { public async disableAsync(duration = 0): Promise<void> {
const response = await fetchWithTrustedCertificatesAsync(this.url("/control/protection"), { const response = await fetch(this.url("/control/protection"), {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -23,7 +23,6 @@ import { OverseerrIntegration } from "../overseerr/overseerr-integration";
import { PiHoleIntegration } from "../pi-hole/pi-hole-integration"; import { PiHoleIntegration } from "../pi-hole/pi-hole-integration";
import { PlexIntegration } from "../plex/plex-integration"; import { PlexIntegration } from "../plex/plex-integration";
import { ProwlarrIntegration } from "../prowlarr/prowlarr-integration"; import { ProwlarrIntegration } from "../prowlarr/prowlarr-integration";
import { ProxmoxIntegration } from "../proxmox/proxmox-integration";
import type { Integration, IntegrationInput } from "./integration"; import type { Integration, IntegrationInput } from "./integration";
export const integrationCreator = <TKind extends keyof typeof integrationCreators>( export const integrationCreator = <TKind extends keyof typeof integrationCreators>(
@@ -73,5 +72,4 @@ export const integrationCreators = {
readarr: ReadarrIntegration, readarr: ReadarrIntegration,
dashDot: DashDotIntegration, dashDot: DashDotIntegration,
tdarr: TdarrIntegration, tdarr: TdarrIntegration,
proxmox: ProxmoxIntegration,
} satisfies Record<IntegrationKind, new (integration: IntegrationInput) => Integration>; } satisfies Record<IntegrationKind, new (integration: IntegrationInput) => Integration>;
@@ -1,5 +1,3 @@
import type { Response } from "undici";
import { extractErrorMessage, removeTrailingSlash } from "@homarr/common"; import { extractErrorMessage, removeTrailingSlash } from "@homarr/common";
import type { IntegrationSecretKind } from "@homarr/definitions"; import type { IntegrationSecretKind } from "@homarr/definitions";
import { logger } from "@homarr/log"; import { logger } from "@homarr/log";
@@ -4,7 +4,6 @@ import "@homarr/redis";
import dayjs from "dayjs"; import dayjs from "dayjs";
import { fetchWithTrustedCertificatesAsync } from "@homarr/certificates/server";
import { z } from "@homarr/validation"; import { z } from "@homarr/validation";
import { createChannelEventHistory } from "../../../redis/src/lib/channel"; import { createChannelEventHistory } from "../../../redis/src/lib/channel";
@@ -13,7 +12,7 @@ import type { HealthMonitoring } from "../types";
export class DashDotIntegration extends Integration { export class DashDotIntegration extends Integration {
public async testConnectionAsync(): Promise<void> { public async testConnectionAsync(): Promise<void> {
const response = await fetchWithTrustedCertificatesAsync(this.url("/info")); const response = await fetch(this.url("/info"));
await response.json(); await response.json();
} }
@@ -53,7 +52,7 @@ export class DashDotIntegration extends Integration {
} }
private async getInfoAsync() { private async getInfoAsync() {
const infoResponse = await fetchWithTrustedCertificatesAsync(this.url("/info")); const infoResponse = await fetch(this.url("/info"));
const serverInfo = await internalServerInfoApi.parseAsync(await infoResponse.json()); const serverInfo = await internalServerInfoApi.parseAsync(await infoResponse.json());
return { return {
maxAvailableMemoryBytes: serverInfo.ram.size, maxAvailableMemoryBytes: serverInfo.ram.size,
@@ -67,7 +66,7 @@ export class DashDotIntegration extends Integration {
private async getCurrentCpuLoadAsync() { private async getCurrentCpuLoadAsync() {
const channel = this.getChannel(); const channel = this.getChannel();
const cpu = await fetchWithTrustedCertificatesAsync(this.url("/load/cpu")); const cpu = await fetch(this.url("/load/cpu"));
const data = await cpuLoadPerCoreApiList.parseAsync(await cpu.json()); const data = await cpuLoadPerCoreApiList.parseAsync(await cpu.json());
await channel.pushAsync(data); await channel.pushAsync(data);
return { return {
@@ -89,12 +88,12 @@ export class DashDotIntegration extends Integration {
} }
private async getCurrentStorageLoadAsync() { private async getCurrentStorageLoadAsync() {
const storageLoad = await fetchWithTrustedCertificatesAsync(this.url("/load/storage")); const storageLoad = await fetch(this.url("/load/storage"));
return (await storageLoad.json()) as number[]; return (await storageLoad.json()) as number[];
} }
private async getCurrentMemoryLoadAsync() { private async getCurrentMemoryLoadAsync() {
const memoryLoad = await fetchWithTrustedCertificatesAsync(this.url("/load/ram")); const memoryLoad = await fetch(this.url("/load/ram"));
const data = await memoryLoadApi.parseAsync(await memoryLoad.json()); const data = await memoryLoadApi.parseAsync(await memoryLoad.json());
return { return {
loadInBytes: data.load, loadInBytes: data.load,
@@ -1,8 +1,6 @@
import { Deluge } from "@ctrl/deluge"; import { Deluge } from "@ctrl/deluge";
import dayjs from "dayjs"; import dayjs from "dayjs";
import { createCertificateAgentAsync } from "@homarr/certificates/server";
import type { DownloadClientJobsAndStatus } from "../../interfaces/downloads/download-client-data"; import type { DownloadClientJobsAndStatus } from "../../interfaces/downloads/download-client-data";
import { DownloadClientIntegration } from "../../interfaces/downloads/download-client-integration"; import { DownloadClientIntegration } from "../../interfaces/downloads/download-client-integration";
import type { DownloadClientItem } from "../../interfaces/downloads/download-client-items"; import type { DownloadClientItem } from "../../interfaces/downloads/download-client-items";
@@ -10,13 +8,13 @@ import type { DownloadClientStatus } from "../../interfaces/downloads/download-c
export class DelugeIntegration extends DownloadClientIntegration { export class DelugeIntegration extends DownloadClientIntegration {
public async testConnectionAsync(): Promise<void> { public async testConnectionAsync(): Promise<void> {
const client = await this.getClientAsync(); const client = this.getClient();
await client.login(); await client.login();
} }
public async getClientJobsAndStatusAsync(): Promise<DownloadClientJobsAndStatus> { public async getClientJobsAndStatusAsync(): Promise<DownloadClientJobsAndStatus> {
const type = "torrent"; const type = "torrent";
const client = await this.getClientAsync(); const client = this.getClient();
const { const {
stats: { download_rate, upload_rate }, stats: { download_rate, upload_rate },
torrents: rawTorrents, torrents: rawTorrents,
@@ -59,7 +57,7 @@ export class DelugeIntegration extends DownloadClientIntegration {
} }
public async pauseQueueAsync() { public async pauseQueueAsync() {
const client = await this.getClientAsync(); const client = this.getClient();
const store = (await client.listTorrents()).result.torrents; const store = (await client.listTorrents()).result.torrents;
await Promise.all( await Promise.all(
Object.entries(store).map(async ([id]) => { Object.entries(store).map(async ([id]) => {
@@ -69,12 +67,11 @@ export class DelugeIntegration extends DownloadClientIntegration {
} }
public async pauseItemAsync({ id }: DownloadClientItem): Promise<void> { public async pauseItemAsync({ id }: DownloadClientItem): Promise<void> {
const client = await this.getClientAsync(); await this.getClient().pauseTorrent(id);
await client.pauseTorrent(id);
} }
public async resumeQueueAsync() { public async resumeQueueAsync() {
const client = await this.getClientAsync(); const client = this.getClient();
const store = (await client.listTorrents()).result.torrents; const store = (await client.listTorrents()).result.torrents;
await Promise.all( await Promise.all(
Object.entries(store).map(async ([id]) => { Object.entries(store).map(async ([id]) => {
@@ -84,20 +81,17 @@ export class DelugeIntegration extends DownloadClientIntegration {
} }
public async resumeItemAsync({ id }: DownloadClientItem): Promise<void> { public async resumeItemAsync({ id }: DownloadClientItem): Promise<void> {
const client = await this.getClientAsync(); await this.getClient().resumeTorrent(id);
await client.resumeTorrent(id);
} }
public async deleteItemAsync({ id }: DownloadClientItem, fromDisk: boolean): Promise<void> { public async deleteItemAsync({ id }: DownloadClientItem, fromDisk: boolean): Promise<void> {
const client = await this.getClientAsync(); await this.getClient().removeTorrent(id, fromDisk);
await client.removeTorrent(id, fromDisk);
} }
private async getClientAsync() { private getClient() {
return new Deluge({ return new Deluge({
baseUrl: this.url("/").toString(), baseUrl: this.url("/").toString(),
password: this.getSecretValue("password"), password: this.getSecretValue("password"),
dispatcher: await createCertificateAgentAsync(),
}); });
} }
@@ -1,7 +1,5 @@
import dayjs from "dayjs"; import dayjs from "dayjs";
import { fetchWithTrustedCertificatesAsync } from "@homarr/certificates/server";
import type { DownloadClientJobsAndStatus } from "../../interfaces/downloads/download-client-data"; import type { DownloadClientJobsAndStatus } from "../../interfaces/downloads/download-client-data";
import { DownloadClientIntegration } from "../../interfaces/downloads/download-client-integration"; import { DownloadClientIntegration } from "../../interfaces/downloads/download-client-integration";
import type { DownloadClientItem } from "../../interfaces/downloads/download-client-items"; import type { DownloadClientItem } from "../../interfaces/downloads/download-client-items";
@@ -96,9 +94,9 @@ export class NzbGetIntegration extends DownloadClientIntegration {
): Promise<ReturnType<NzbGetClient[CallType]>> { ): Promise<ReturnType<NzbGetClient[CallType]>> {
const username = this.getSecretValue("username"); const username = this.getSecretValue("username");
const password = this.getSecretValue("password"); const password = this.getSecretValue("password");
const url = this.url(`/${encodeURIComponent(username)}:${encodeURIComponent(password)}/jsonrpc`); const url = this.url(`/${username}:${password}/jsonrpc`);
const body = JSON.stringify({ method, params }); const body = JSON.stringify({ method, params });
return await fetchWithTrustedCertificatesAsync(url, { method: "POST", body }) return await fetch(url, { method: "POST", body })
.then(async (response) => { .then(async (response) => {
if (!response.ok) { if (!response.ok) {
throw new Error(response.statusText); throw new Error(response.statusText);
@@ -1,8 +1,6 @@
import { QBittorrent } from "@ctrl/qbittorrent"; import { QBittorrent } from "@ctrl/qbittorrent";
import dayjs from "dayjs"; import dayjs from "dayjs";
import { createCertificateAgentAsync } from "@homarr/certificates/server";
import type { DownloadClientJobsAndStatus } from "../../interfaces/downloads/download-client-data"; import type { DownloadClientJobsAndStatus } from "../../interfaces/downloads/download-client-data";
import { DownloadClientIntegration } from "../../interfaces/downloads/download-client-integration"; import { DownloadClientIntegration } from "../../interfaces/downloads/download-client-integration";
import type { DownloadClientItem } from "../../interfaces/downloads/download-client-items"; import type { DownloadClientItem } from "../../interfaces/downloads/download-client-items";
@@ -10,13 +8,13 @@ import type { DownloadClientStatus } from "../../interfaces/downloads/download-c
export class QBitTorrentIntegration extends DownloadClientIntegration { export class QBitTorrentIntegration extends DownloadClientIntegration {
public async testConnectionAsync(): Promise<void> { public async testConnectionAsync(): Promise<void> {
const client = await this.getClientAsync(); const client = this.getClient();
await client.login(); await client.login();
} }
public async getClientJobsAndStatusAsync(): Promise<DownloadClientJobsAndStatus> { public async getClientJobsAndStatusAsync(): Promise<DownloadClientJobsAndStatus> {
const type = "torrent"; const type = "torrent";
const client = await this.getClientAsync(); const client = this.getClient();
const torrents = await client.listTorrents(); const torrents = await client.listTorrents();
const rates = torrents.reduce( const rates = torrents.reduce(
({ down, up }, { dlspeed, upspeed }) => ({ down: down + dlspeed, up: up + upspeed }), ({ down, up }, { dlspeed, upspeed }) => ({ down: down + dlspeed, up: up + upspeed }),
@@ -52,36 +50,30 @@ export class QBitTorrentIntegration extends DownloadClientIntegration {
} }
public async pauseQueueAsync() { public async pauseQueueAsync() {
const client = await this.getClientAsync(); await this.getClient().pauseTorrent("all");
await client.pauseTorrent("all");
} }
public async pauseItemAsync({ id }: DownloadClientItem): Promise<void> { public async pauseItemAsync({ id }: DownloadClientItem): Promise<void> {
const client = await this.getClientAsync(); await this.getClient().pauseTorrent(id);
await client.pauseTorrent(id);
} }
public async resumeQueueAsync() { public async resumeQueueAsync() {
const client = await this.getClientAsync(); await this.getClient().resumeTorrent("all");
await client.resumeTorrent("all");
} }
public async resumeItemAsync({ id }: DownloadClientItem): Promise<void> { public async resumeItemAsync({ id }: DownloadClientItem): Promise<void> {
const client = await this.getClientAsync(); await this.getClient().resumeTorrent(id);
await client.resumeTorrent(id);
} }
public async deleteItemAsync({ id }: DownloadClientItem, fromDisk: boolean): Promise<void> { public async deleteItemAsync({ id }: DownloadClientItem, fromDisk: boolean): Promise<void> {
const client = await this.getClientAsync(); await this.getClient().removeTorrent(id, fromDisk);
await client.removeTorrent(id, fromDisk);
} }
private async getClientAsync() { private getClient() {
return new QBittorrent({ return new QBittorrent({
baseUrl: this.url("/").toString(), baseUrl: this.url("/").toString(),
username: this.getSecretValue("username"), username: this.getSecretValue("username"),
password: this.getSecretValue("password"), password: this.getSecretValue("password"),
dispatcher: await createCertificateAgentAsync(),
}); });
} }
@@ -1,8 +1,6 @@
import dayjs from "dayjs"; import dayjs from "dayjs";
import duration from "dayjs/plugin/duration"; import duration from "dayjs/plugin/duration";
import { fetchWithTrustedCertificatesAsync } from "@homarr/certificates/server";
import type { DownloadClientJobsAndStatus } from "../../interfaces/downloads/download-client-data"; import type { DownloadClientJobsAndStatus } from "../../interfaces/downloads/download-client-data";
import { DownloadClientIntegration } from "../../interfaces/downloads/download-client-integration"; import { DownloadClientIntegration } from "../../interfaces/downloads/download-client-integration";
import type { DownloadClientItem } from "../../interfaces/downloads/download-client-items"; import type { DownloadClientItem } from "../../interfaces/downloads/download-client-items";
@@ -108,12 +106,12 @@ export class SabnzbdIntegration extends DownloadClientIntegration {
apikey: this.getSecretValue("apiKey"), apikey: this.getSecretValue("apiKey"),
}); });
return await fetchWithTrustedCertificatesAsync(url) return await fetch(url)
.then((response) => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error(response.statusText); throw new Error(response.statusText);
} }
return response.json(); return response.json() as Promise<unknown>;
}) })
.catch((error) => { .catch((error) => {
if (error instanceof Error) { if (error instanceof Error) {
@@ -1,8 +1,6 @@
import { Transmission } from "@ctrl/transmission"; import { Transmission } from "@ctrl/transmission";
import dayjs from "dayjs"; import dayjs from "dayjs";
import { createCertificateAgentAsync } from "@homarr/certificates/server";
import type { DownloadClientJobsAndStatus } from "../../interfaces/downloads/download-client-data"; import type { DownloadClientJobsAndStatus } from "../../interfaces/downloads/download-client-data";
import { DownloadClientIntegration } from "../../interfaces/downloads/download-client-integration"; import { DownloadClientIntegration } from "../../interfaces/downloads/download-client-integration";
import type { DownloadClientItem } from "../../interfaces/downloads/download-client-items"; import type { DownloadClientItem } from "../../interfaces/downloads/download-client-items";
@@ -10,13 +8,12 @@ import type { DownloadClientStatus } from "../../interfaces/downloads/download-c
export class TransmissionIntegration extends DownloadClientIntegration { export class TransmissionIntegration extends DownloadClientIntegration {
public async testConnectionAsync(): Promise<void> { public async testConnectionAsync(): Promise<void> {
const client = await this.getClientAsync(); await this.getClient().getSession();
await client.getSession();
} }
public async getClientJobsAndStatusAsync(): Promise<DownloadClientJobsAndStatus> { public async getClientJobsAndStatusAsync(): Promise<DownloadClientJobsAndStatus> {
const type = "torrent"; const type = "torrent";
const client = await this.getClientAsync(); const client = this.getClient();
const { torrents } = (await client.listTorrents()).arguments; const { torrents } = (await client.listTorrents()).arguments;
const rates = torrents.reduce( const rates = torrents.reduce(
({ down, up }, { rateDownload, rateUpload }) => ({ down: down + rateDownload, up: up + rateUpload }), ({ down, up }, { rateDownload, rateUpload }) => ({ down: down + rateDownload, up: up + rateUpload }),
@@ -50,38 +47,34 @@ export class TransmissionIntegration extends DownloadClientIntegration {
} }
public async pauseQueueAsync() { public async pauseQueueAsync() {
const client = await this.getClientAsync(); const client = this.getClient();
const ids = (await client.listTorrents()).arguments.torrents.map(({ hashString }) => hashString); const ids = (await client.listTorrents()).arguments.torrents.map(({ hashString }) => hashString);
await client.pauseTorrent(ids); await this.getClient().pauseTorrent(ids);
} }
public async pauseItemAsync({ id }: DownloadClientItem): Promise<void> { public async pauseItemAsync({ id }: DownloadClientItem): Promise<void> {
const client = await this.getClientAsync(); await this.getClient().pauseTorrent(id);
await client.pauseTorrent(id);
} }
public async resumeQueueAsync() { public async resumeQueueAsync() {
const client = await this.getClientAsync(); const client = this.getClient();
const ids = (await client.listTorrents()).arguments.torrents.map(({ hashString }) => hashString); const ids = (await client.listTorrents()).arguments.torrents.map(({ hashString }) => hashString);
await client.resumeTorrent(ids); await this.getClient().resumeTorrent(ids);
} }
public async resumeItemAsync({ id }: DownloadClientItem): Promise<void> { public async resumeItemAsync({ id }: DownloadClientItem): Promise<void> {
const client = await this.getClientAsync(); await this.getClient().resumeTorrent(id);
await client.resumeTorrent(id);
} }
public async deleteItemAsync({ id }: DownloadClientItem, fromDisk: boolean): Promise<void> { public async deleteItemAsync({ id }: DownloadClientItem, fromDisk: boolean): Promise<void> {
const client = await this.getClientAsync(); await this.getClient().removeTorrent(id, fromDisk);
await client.removeTorrent(id, fromDisk);
} }
private async getClientAsync() { private getClient() {
return new Transmission({ return new Transmission({
baseUrl: this.url("/").toString(), baseUrl: this.url("/").toString(),
username: this.getSecretValue("username"), username: this.getSecretValue("username"),
password: this.getSecretValue("password"), password: this.getSecretValue("password"),
dispatcher: await createCertificateAgentAsync(),
}); });
} }
@@ -1,4 +1,3 @@
import { fetchWithTrustedCertificatesAsync } from "@homarr/certificates/server";
import { logger } from "@homarr/log"; import { logger } from "@homarr/log";
import { Integration } from "../base/integration"; import { Integration } from "../base/integration";
@@ -8,7 +7,7 @@ export class HomeAssistantIntegration extends Integration {
public async getEntityStateAsync(entityId: string) { public async getEntityStateAsync(entityId: string) {
try { try {
const response = await this.getAsync(`/api/states/${entityId}`); const response = await this.getAsync(`/api/states/${entityId}`);
const body = await response.json(); const body = (await response.json()) as unknown;
if (!response.ok) { if (!response.ok) {
logger.warn(`Response did not indicate success`); logger.warn(`Response did not indicate success`);
return { return {
@@ -72,7 +71,7 @@ export class HomeAssistantIntegration extends Integration {
* @returns the response from the API * @returns the response from the API
*/ */
private async getAsync(path: `/api/${string}`) { private async getAsync(path: `/api/${string}`) {
return await fetchWithTrustedCertificatesAsync(this.url(path), { return await fetch(this.url(path), {
headers: this.getAuthHeaders(), headers: this.getAuthHeaders(),
}); });
} }
@@ -85,7 +84,7 @@ export class HomeAssistantIntegration extends Integration {
* @returns the response from the API * @returns the response from the API
*/ */
private async postAsync(path: `/api/${string}`, body: Record<string, string>) { private async postAsync(path: `/api/${string}`, body: Record<string, string>) {
return await fetchWithTrustedCertificatesAsync(this.url(path), { return await fetch(this.url(path), {
headers: this.getAuthHeaders(), headers: this.getAuthHeaders(),
body: JSON.stringify(body), body: JSON.stringify(body),
method: "POST", method: "POST",
@@ -2,8 +2,6 @@ import { Jellyfin } from "@jellyfin/sdk";
import { getSessionApi } from "@jellyfin/sdk/lib/utils/api/session-api"; import { getSessionApi } from "@jellyfin/sdk/lib/utils/api/session-api";
import { getSystemApi } from "@jellyfin/sdk/lib/utils/api/system-api"; import { getSystemApi } from "@jellyfin/sdk/lib/utils/api/system-api";
import { createAxiosCertificateInstanceAsync } from "@homarr/certificates/server";
import { Integration } from "../base/integration"; import { Integration } from "../base/integration";
import type { StreamSession } from "../interfaces/media-server/session"; import type { StreamSession } from "../interfaces/media-server/session";
@@ -67,13 +65,12 @@ export class JellyfinIntegration extends Integration {
* @returns An instance of Api that has been authenticated * @returns An instance of Api that has been authenticated
*/ */
private async getApiAsync() { private async getApiAsync() {
const httpsAgent = await createAxiosCertificateInstanceAsync();
if (this.hasSecretValue("apiKey")) { if (this.hasSecretValue("apiKey")) {
const apiKey = this.getSecretValue("apiKey"); const apiKey = this.getSecretValue("apiKey");
return this.jellyfin.createApi(this.url("/").toString(), apiKey, httpsAgent); return this.jellyfin.createApi(this.url("/").toString(), apiKey);
} }
const apiClient = this.jellyfin.createApi(this.url("/").toString(), undefined, httpsAgent); const apiClient = this.jellyfin.createApi(this.url("/").toString());
// Authentication state is stored internally in the Api class, so now // Authentication state is stored internally in the Api class, so now
// requests that require authentication can be made normally. // requests that require authentication can be made normally.
// see https://typescript-sdk.jellyfin.org/#usage // see https://typescript-sdk.jellyfin.org/#usage
@@ -1,4 +1,3 @@
import { fetchWithTrustedCertificatesAsync } from "@homarr/certificates/server";
import { logger } from "@homarr/log"; import { logger } from "@homarr/log";
import { z } from "@homarr/validation"; import { z } from "@homarr/validation";
@@ -9,7 +8,7 @@ export class LidarrIntegration extends MediaOrganizerIntegration {
public async testConnectionAsync(): Promise<void> { public async testConnectionAsync(): Promise<void> {
await super.handleTestConnectionResponseAsync({ await super.handleTestConnectionResponseAsync({
queryFunctionAsync: async () => { queryFunctionAsync: async () => {
return await fetchWithTrustedCertificatesAsync(this.url("/api"), { return await fetch(this.url("/api"), {
headers: { "X-Api-Key": super.getSecretValue("apiKey") }, headers: { "X-Api-Key": super.getSecretValue("apiKey") },
}); });
}, },
@@ -29,7 +28,7 @@ export class LidarrIntegration extends MediaOrganizerIntegration {
unmonitored: includeUnmonitored, unmonitored: includeUnmonitored,
}); });
const response = await fetchWithTrustedCertificatesAsync(url, { const response = await fetch(url, {
headers: { headers: {
"X-Api-Key": super.getSecretValue("apiKey"), "X-Api-Key": super.getSecretValue("apiKey"),
}, },
@@ -1,4 +1,3 @@
import { fetchWithTrustedCertificatesAsync } from "@homarr/certificates/server";
import type { AtLeastOneOf } from "@homarr/common/types"; import type { AtLeastOneOf } from "@homarr/common/types";
import { logger } from "@homarr/log"; import { logger } from "@homarr/log";
import { z } from "@homarr/validation"; import { z } from "@homarr/validation";
@@ -21,7 +20,7 @@ export class RadarrIntegration extends MediaOrganizerIntegration {
unmonitored: includeUnmonitored, unmonitored: includeUnmonitored,
}); });
const response = await fetchWithTrustedCertificatesAsync(url, { const response = await fetch(url, {
headers: { headers: {
"X-Api-Key": super.getSecretValue("apiKey"), "X-Api-Key": super.getSecretValue("apiKey"),
}, },
@@ -95,7 +94,7 @@ export class RadarrIntegration extends MediaOrganizerIntegration {
public async testConnectionAsync(): Promise<void> { public async testConnectionAsync(): Promise<void> {
await super.handleTestConnectionResponseAsync({ await super.handleTestConnectionResponseAsync({
queryFunctionAsync: async () => { queryFunctionAsync: async () => {
return await fetchWithTrustedCertificatesAsync(this.url("/api"), { return await fetch(this.url("/api"), {
headers: { "X-Api-Key": super.getSecretValue("apiKey") }, headers: { "X-Api-Key": super.getSecretValue("apiKey") },
}); });
}, },
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff. Show more