Compare commits

..
298 changed files with 4911 additions and 20488 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
+1 -5
View File
@@ -31,10 +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.2.0
- 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
@@ -79,4 +75,4 @@ body:
- Other (describe in "additional information") - Other (describe in "additional information")
default: 0 default: 0
validations: validations:
required: false required: false
-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
@@ -64,4 +64,4 @@ packages/cli/cli.cjs
e2e/shared/tmp e2e/shared/tmp
#personal backgrounds #personal backgrounds
apps/nextjs/public/images/background.png apps/nextjs/public/images/background.png
+1 -1
View File
@@ -1 +1 @@
22.13.1 22.13.0
+1 -1250
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";
+20 -25
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",
@@ -36,24 +33,23 @@
"@homarr/old-schema": "workspace:^0.1.0", "@homarr/old-schema": "workspace:^0.1.0",
"@homarr/redis": "workspace:^0.1.0", "@homarr/redis": "workspace:^0.1.0",
"@homarr/server-settings": "workspace:^0.1.0", "@homarr/server-settings": "workspace:^0.1.0",
"@homarr/settings": "workspace:^0.1.0",
"@homarr/spotlight": "workspace:^0.1.0", "@homarr/spotlight": "workspace:^0.1.0",
"@homarr/translation": "workspace:^0.1.0", "@homarr/translation": "workspace:^0.1.0",
"@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.2", "@mantine/colors-generator": "^7.16.0",
"@mantine/core": "^7.16.2", "@mantine/core": "^7.16.0",
"@mantine/dropzone": "^7.16.2", "@mantine/dropzone": "^7.16.0",
"@mantine/hooks": "^7.16.2", "@mantine/hooks": "^7.16.0",
"@mantine/modals": "^7.16.2", "@mantine/modals": "^7.16.0",
"@mantine/tiptap": "^7.16.2", "@mantine/tiptap": "^7.16.0",
"@million/lint": "1.0.14", "@million/lint": "1.0.14",
"@t3-oss/env-nextjs": "^0.12.0", "@t3-oss/env-nextjs": "^0.11.1",
"@tabler/icons-react": "^3.29.0", "@tabler/icons-react": "^3.28.1",
"@tanstack/react-query": "^5.65.0", "@tanstack/react-query": "^5.64.1",
"@tanstack/react-query-devtools": "^5.65.0", "@tanstack/react-query-devtools": "^5.64.1",
"@tanstack/react-query-next-experimental": "^5.65.0", "@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",
@@ -65,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",
@@ -79,21 +75,20 @@
"sass": "^1.83.4", "sass": "^1.83.4",
"superjson": "2.2.2", "superjson": "2.2.2",
"swagger-ui-react": "^5.18.2", "swagger-ui-react": "^5.18.2",
"use-deep-compare-effect": "^1.8.1", "use-deep-compare-effect": "^1.8.1"
"zod": "^3.24.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/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.19.0", "@types/swagger-ui-react": "^4.18.3",
"concurrently": "^9.1.2", "concurrently": "^9.1.2",
"eslint": "^9.19.0", "eslint": "^9.18.0",
"node-loader": "^2.1.0", "node-loader": "^2.1.0",
"prettier": "^3.4.2", "prettier": "^3.4.2",
"typescript": "^5.7.3" "typescript": "^5.7.3"
@@ -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,13 +2,13 @@
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Button, PasswordInput, Stack, TextInput } from "@mantine/core"; import { Button, PasswordInput, Stack, TextInput } from "@mantine/core";
import type { z } from "zod";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { useZodForm } from "@homarr/form"; import { useZodForm } from "@homarr/form";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
import { CustomPasswordInput } from "@homarr/ui"; import { CustomPasswordInput } from "@homarr/ui";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation"; import { validation } from "@homarr/validation";
interface RegistrationFormProps { interface RegistrationFormProps {
@@ -5,7 +5,6 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Anchor, Button, Card, Code, Collapse, Divider, PasswordInput, Stack, Text, TextInput } from "@mantine/core"; import { Anchor, Button, Card, Code, Collapse, Divider, PasswordInput, Stack, Text, TextInput } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks"; import { useDisclosure } from "@mantine/hooks";
import { z } from "zod";
import { signIn } from "@homarr/auth/client"; import { signIn } from "@homarr/auth/client";
import { revalidatePathActionAsync } from "@homarr/common/client"; import { revalidatePathActionAsync } from "@homarr/common/client";
@@ -13,7 +12,7 @@ import type { useForm } from "@homarr/form";
import { useZodForm } from "@homarr/form"; import { useZodForm } from "@homarr/form";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
import { validation } from "@homarr/validation"; import { validation, z } from "@homarr/validation";
interface LoginFormProps { interface LoginFormProps {
providers: string[]; providers: string[];
@@ -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();
@@ -2,12 +2,12 @@
import { Button, Card, Stack, TextInput } from "@mantine/core"; import { Button, Card, Stack, TextInput } from "@mantine/core";
import { IconArrowRight } from "@tabler/icons-react"; import { IconArrowRight } from "@tabler/icons-react";
import type { z } from "zod";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { revalidatePathActionAsync } from "@homarr/common/client"; import { revalidatePathActionAsync } from "@homarr/common/client";
import { useZodForm } from "@homarr/form"; import { useZodForm } from "@homarr/form";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation"; import { validation } from "@homarr/validation";
export const InitGroup = () => { export const InitGroup = () => {
@@ -3,7 +3,6 @@
import { startTransition } from "react"; import { startTransition } from "react";
import { Button, Card, Group, Stack, Switch, Text } from "@mantine/core"; import { Button, Card, Group, Stack, Switch, Text } from "@mantine/core";
import { IconArrowRight } from "@tabler/icons-react"; import { IconArrowRight } from "@tabler/icons-react";
import type { z } from "zod";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { revalidatePathActionAsync } from "@homarr/common/client"; import { revalidatePathActionAsync } from "@homarr/common/client";
@@ -12,6 +11,7 @@ import type { CheckboxProps } from "@homarr/form/types";
import { defaultServerSettings } from "@homarr/server-settings"; import { defaultServerSettings } from "@homarr/server-settings";
import type { TranslationObject } from "@homarr/translation"; import type { TranslationObject } from "@homarr/translation";
import { useI18n, useScopedI18n } from "@homarr/translation/client"; import { useI18n, useScopedI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation"; import { validation } from "@homarr/validation";
export const InitSettings = () => { export const InitSettings = () => {
@@ -1,7 +1,6 @@
"use client"; "use client";
import { Button, PasswordInput, Stack, TextInput } from "@mantine/core"; import { Button, PasswordInput, Stack, TextInput } from "@mantine/core";
import type { z } from "zod";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { revalidatePathActionAsync } from "@homarr/common/client"; import { revalidatePathActionAsync } from "@homarr/common/client";
@@ -9,6 +8,7 @@ import { useZodForm } from "@homarr/form";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
import { CustomPasswordInput } from "@homarr/ui"; import { CustomPasswordInput } from "@homarr/ui";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation"; import { validation } from "@homarr/validation";
export const InitUserForm = () => { export const InitUserForm = () => {
-19
View File
@@ -9,14 +9,10 @@ import "~/styles/scroll-area.scss";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { NextIntlClientProvider } from "next-intl"; import { NextIntlClientProvider } from "next-intl";
import { api } from "@homarr/api/server";
import { env } from "@homarr/auth/env"; import { env } from "@homarr/auth/env";
import { auth } from "@homarr/auth/next"; import { auth } from "@homarr/auth/next";
import { db } from "@homarr/db";
import { getServerSettingsAsync } from "@homarr/db/queries";
import { ModalProvider } from "@homarr/modals"; import { ModalProvider } from "@homarr/modals";
import { Notifications } from "@homarr/notifications"; import { Notifications } from "@homarr/notifications";
import { SettingsProvider } from "@homarr/settings";
import { SpotlightProvider } from "@homarr/spotlight"; import { SpotlightProvider } from "@homarr/spotlight";
import type { SupportedLanguage } from "@homarr/translation"; import type { SupportedLanguage } from "@homarr/translation";
import { isLocaleRTL, isLocaleSupported } from "@homarr/translation"; import { isLocaleRTL, isLocaleSupported } from "@homarr/translation";
@@ -77,8 +73,6 @@ export default async function Layout(props: {
} }
const session = await auth(); const session = await auth();
const user = session ? await api.user.getById({ userId: session.user.id }).catch(() => null) : null;
const serverSettings = await getServerSettingsAsync(db);
const colorScheme = await getCurrentColorSchemeAsync(); const colorScheme = await getCurrentColorSchemeAsync();
const direction = isLocaleRTL((await props.params).locale) ? "rtl" : "ltr"; const direction = isLocaleRTL((await props.params).locale) ? "rtl" : "ltr";
const i18nMessages = await getI18nMessages(); const i18nMessages = await getI18nMessages();
@@ -87,19 +81,6 @@ export default async function Layout(props: {
(innerProps) => { (innerProps) => {
return <AuthProvider session={session} logoutUrl={env.AUTH_LOGOUT_REDIRECT_URL} {...innerProps} />; return <AuthProvider session={session} logoutUrl={env.AUTH_LOGOUT_REDIRECT_URL} {...innerProps} />;
}, },
(innerProps) => (
<SettingsProvider
user={user}
serverSettings={{
board: {
homeBoardId: serverSettings.board.homeBoardId,
mobileHomeBoardId: serverSettings.board.mobileHomeBoardId,
},
search: { defaultSearchEngineId: serverSettings.search.defaultSearchEngineId },
}}
{...innerProps}
/>
),
(innerProps) => <JotaiProvider {...innerProps} />, (innerProps) => <JotaiProvider {...innerProps} />,
(innerProps) => <TRPCReactProvider {...innerProps} />, (innerProps) => <TRPCReactProvider {...innerProps} />,
(innerProps) => <DayJsLoader {...innerProps} />, (innerProps) => <DayJsLoader {...innerProps} />,
@@ -2,11 +2,11 @@
import Link from "next/link"; import Link from "next/link";
import { Button, Group, Stack, Textarea, TextInput } from "@mantine/core"; import { Button, Group, Stack, Textarea, TextInput } from "@mantine/core";
import type { z } from "zod";
import { useZodForm } from "@homarr/form"; import { useZodForm } from "@homarr/form";
import type { TranslationFunction } from "@homarr/translation"; import type { TranslationFunction } from "@homarr/translation";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation"; import { validation } from "@homarr/validation";
import { IconPicker } from "~/components/icons/picker/icon-picker"; import { IconPicker } from "~/components/icons/picker/icon-picker";
@@ -25,11 +25,11 @@ export const AppForm = (props: AppFormProps) => {
const t = useI18n(); const t = useI18n();
const form = useZodForm(validation.app.manage, { const form = useZodForm(validation.app.manage, {
initialValues: { initialValues: initialValues ?? {
name: initialValues?.name ?? "", name: "",
description: initialValues?.description ?? "", description: "",
iconUrl: initialValues?.iconUrl ?? "", iconUrl: "",
href: initialValues?.href ?? "", href: "",
}, },
}); });
@@ -2,7 +2,6 @@
import { useCallback } from "react"; import { useCallback } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import type { z } from "zod";
import type { RouterOutputs } from "@homarr/api"; import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
@@ -10,7 +9,7 @@ import { revalidatePathActionAsync } from "@homarr/common/client";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import type { TranslationFunction } from "@homarr/translation"; import type { TranslationFunction } from "@homarr/translation";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
import type { validation } from "@homarr/validation"; import type { validation, z } from "@homarr/validation";
import { AppForm } from "../../_form"; import { AppForm } from "../../_form";
@@ -2,14 +2,13 @@
import { useCallback } from "react"; import { useCallback } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import type { z } from "zod";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { revalidatePathActionAsync } from "@homarr/common/client"; import { revalidatePathActionAsync } from "@homarr/common/client";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import type { TranslationFunction } from "@homarr/translation"; import type { TranslationFunction } from "@homarr/translation";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
import type { validation } from "@homarr/validation"; import type { validation, z } from "@homarr/validation";
import { AppForm } from "../_form"; import { AppForm } from "../_form";
@@ -2,7 +2,6 @@ import Link from "next/link";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { ActionIcon, ActionIconGroup, Anchor, Avatar, Card, Group, Stack, Text, Title } from "@mantine/core"; import { ActionIcon, ActionIconGroup, Anchor, Avatar, Card, Group, Stack, Text, Title } from "@mantine/core";
import { IconBox, IconPencil } from "@tabler/icons-react"; import { IconBox, IconPencil } from "@tabler/icons-react";
import { z } from "zod";
import type { RouterOutputs } from "@homarr/api"; import type { RouterOutputs } from "@homarr/api";
import { api } from "@homarr/api/server"; import { api } from "@homarr/api/server";
@@ -10,6 +9,7 @@ import { auth } from "@homarr/auth/next";
import type { inferSearchParamsFromSchema } from "@homarr/common/types"; import type { inferSearchParamsFromSchema } from "@homarr/common/types";
import { getI18n, getScopedI18n } from "@homarr/translation/server"; import { getI18n, getScopedI18n } from "@homarr/translation/server";
import { SearchInput, TablePagination } from "@homarr/ui"; import { SearchInput, TablePagination } from "@homarr/ui";
import { z } from "@homarr/validation";
import { ManageContainer } from "~/components/manage/manage-container"; import { ManageContainer } from "~/components/manage/manage-container";
import { MobileAffixButton } from "~/components/manage/mobile-affix-button"; import { MobileAffixButton } from "~/components/manage/mobile-affix-button";
@@ -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>;
@@ -3,7 +3,6 @@
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Button, Fieldset, Group, Stack, TextInput } from "@mantine/core"; import { Button, Fieldset, Group, Stack, TextInput } from "@mantine/core";
import type { z } from "zod";
import type { RouterOutputs } from "@homarr/api"; import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
@@ -14,6 +13,7 @@ import { convertIntegrationTestConnectionError } from "@homarr/integrations/clie
import { useConfirmModal } from "@homarr/modals"; import { useConfirmModal } from "@homarr/modals";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation"; import { validation } from "@homarr/validation";
import { SecretCard } from "../../_components/secrets/integration-secret-card"; import { SecretCard } from "../../_components/secrets/integration-secret-card";
@@ -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}
/> />
@@ -5,7 +5,6 @@ import Link from "next/link";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Alert, Button, Checkbox, Fieldset, Group, SegmentedControl, Stack, Text, TextInput } from "@mantine/core"; import { Alert, Button, Checkbox, Fieldset, Group, SegmentedControl, Stack, Text, TextInput } from "@mantine/core";
import { IconInfoCircle } from "@tabler/icons-react"; import { IconInfoCircle } from "@tabler/icons-react";
import type { z } from "zod";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { revalidatePathActionAsync } from "@homarr/common/client"; import { revalidatePathActionAsync } from "@homarr/common/client";
@@ -16,6 +15,7 @@ import { useZodForm } from "@homarr/form";
import { convertIntegrationTestConnectionError } from "@homarr/integrations/client"; import { convertIntegrationTestConnectionError } from "@homarr/integrations/client";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n, useScopedI18n } from "@homarr/translation/client"; import { useI18n, useScopedI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation"; import { validation } from "@homarr/validation";
import { IntegrationSecretInput } from "../_components/secrets/integration-secret-inputs"; import { IntegrationSecretInput } from "../_components/secrets/integration-secret-inputs";
@@ -1,6 +1,5 @@
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { Container, Group, Stack, Title } from "@mantine/core"; import { Container, Group, Stack, Title } from "@mantine/core";
import { z } from "zod";
import { auth } from "@homarr/auth/next"; import { auth } from "@homarr/auth/next";
import type { IntegrationKind } from "@homarr/definitions"; import type { IntegrationKind } from "@homarr/definitions";
@@ -8,6 +7,7 @@ import { getIntegrationName, integrationKinds } from "@homarr/definitions";
import { getScopedI18n } from "@homarr/translation/server"; import { getScopedI18n } from "@homarr/translation/server";
import { IntegrationAvatar } from "@homarr/ui"; import { IntegrationAvatar } from "@homarr/ui";
import type { validation } from "@homarr/validation"; import type { validation } from "@homarr/validation";
import { z } from "@homarr/validation";
import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb"; import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
import { NewIntegrationForm } from "./_integration-new-form"; import { NewIntegrationForm } from "./_integration-new-form";
@@ -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,31 +1,16 @@
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 { z } from "zod";
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 { ManageContainer } from "~/components/manage/manage-container"; import { ManageContainer } from "~/components/manage/manage-container";
import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb"; import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
@@ -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>
@@ -4,13 +4,13 @@ import Link from "next/link";
import type { SegmentedControlItem } from "@mantine/core"; import type { SegmentedControlItem } from "@mantine/core";
import { Button, Fieldset, Grid, Group, SegmentedControl, Stack, Textarea, TextInput } from "@mantine/core"; import { Button, Fieldset, Grid, Group, SegmentedControl, Stack, Textarea, TextInput } from "@mantine/core";
import { WidgetIntegrationSelect } from "node_modules/@homarr/widgets/src/widget-integration-select"; import { WidgetIntegrationSelect } from "node_modules/@homarr/widgets/src/widget-integration-select";
import type { z } from "zod";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { searchEngineTypes } from "@homarr/definitions"; import { searchEngineTypes } from "@homarr/definitions";
import { useZodForm } from "@homarr/form"; import { useZodForm } from "@homarr/form";
import type { TranslationFunction } from "@homarr/translation"; import type { TranslationFunction } from "@homarr/translation";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation"; import { validation } from "@homarr/validation";
import { IconPicker } from "~/components/icons/picker/icon-picker"; import { IconPicker } from "~/components/icons/picker/icon-picker";
@@ -2,7 +2,6 @@
import { useCallback } from "react"; import { useCallback } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import type { z } from "zod";
import type { RouterOutputs } from "@homarr/api"; import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
@@ -10,7 +9,7 @@ import { revalidatePathActionAsync } from "@homarr/common/client";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import type { TranslationFunction } from "@homarr/translation"; import type { TranslationFunction } from "@homarr/translation";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
import type { validation } from "@homarr/validation"; import type { validation, z } from "@homarr/validation";
import { SearchEngineForm } from "../../_form"; import { SearchEngineForm } from "../../_form";
@@ -2,14 +2,13 @@
import { useCallback } from "react"; import { useCallback } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import type { z } from "zod";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { revalidatePathActionAsync } from "@homarr/common/client"; import { revalidatePathActionAsync } from "@homarr/common/client";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import type { TranslationFunction } from "@homarr/translation"; import type { TranslationFunction } from "@homarr/translation";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
import type { validation } from "@homarr/validation"; import type { validation, z } from "@homarr/validation";
import { SearchEngineForm } from "../_form"; import { SearchEngineForm } from "../_form";
@@ -2,7 +2,6 @@ import Link from "next/link";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { ActionIcon, ActionIconGroup, Anchor, Avatar, Card, Group, Stack, Text, Title } from "@mantine/core"; import { ActionIcon, ActionIconGroup, Anchor, Avatar, Card, Group, Stack, Text, Title } from "@mantine/core";
import { IconPencil, IconSearch } from "@tabler/icons-react"; import { IconPencil, IconSearch } from "@tabler/icons-react";
import { z } from "zod";
import type { RouterOutputs } from "@homarr/api"; import type { RouterOutputs } from "@homarr/api";
import { api } from "@homarr/api/server"; import { api } from "@homarr/api/server";
@@ -10,6 +9,7 @@ import { auth } from "@homarr/auth/next";
import type { inferSearchParamsFromSchema } from "@homarr/common/types"; import type { inferSearchParamsFromSchema } from "@homarr/common/types";
import { getI18n, getScopedI18n } from "@homarr/translation/server"; import { getI18n, getScopedI18n } from "@homarr/translation/server";
import { SearchInput, TablePagination } from "@homarr/ui"; import { SearchInput, TablePagination } from "@homarr/ui";
import { z } from "@homarr/validation";
import { ManageContainer } from "~/components/manage/manage-container"; import { ManageContainer } from "~/components/manage/manage-container";
import { MobileAffixButton } from "~/components/manage/mobile-affix-button"; import { MobileAffixButton } from "~/components/manage/mobile-affix-button";
@@ -1,82 +0,0 @@
"use client";
import { Button, FileInput, Group, Stack } from "@mantine/core";
import { IconCertificate } from "@tabler/icons-react";
import { z } from "zod";
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 } 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 (
@@ -1,7 +1,6 @@
"use client"; "use client";
import { Button, Group, Select, Stack, Switch } from "@mantine/core"; import { Button, Group, Select, Stack } from "@mantine/core";
import type { z } from "zod";
import type { RouterOutputs } from "@homarr/api"; import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
@@ -9,38 +8,37 @@ import { revalidatePathActionAsync } from "@homarr/common/client";
import { useZodForm } from "@homarr/form"; import { useZodForm } from "@homarr/form";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation"; import { validation } from "@homarr/validation";
interface ChangeSearchPreferencesFormProps { interface ChangeDefaultSearchEngineFormProps {
user: RouterOutputs["user"]["getById"]; user: RouterOutputs["user"]["getById"];
searchEnginesData: { value: string; label: string }[]; searchEnginesData: { value: string; label: string }[];
} }
export const ChangeSearchPreferencesForm = ({ user, searchEnginesData }: ChangeSearchPreferencesFormProps) => { export const ChangeDefaultSearchEngineForm = ({ user, searchEnginesData }: ChangeDefaultSearchEngineFormProps) => {
const t = useI18n(); const t = useI18n();
const { mutate, isPending } = clientApi.user.changeSearchPreferences.useMutation({ const { mutate, isPending } = clientApi.user.changeDefaultSearchEngine.useMutation({
async onSettled() { async onSettled() {
await revalidatePathActionAsync(`/manage/users/${user.id}`); await revalidatePathActionAsync(`/manage/users/${user.id}`);
}, },
onSuccess(_, variables) { onSuccess(_, variables) {
form.setInitialValues({ form.setInitialValues({
defaultSearchEngineId: variables.defaultSearchEngineId, defaultSearchEngineId: variables.defaultSearchEngineId,
openInNewTab: variables.openInNewTab,
}); });
showSuccessNotification({ showSuccessNotification({
message: t("user.action.changeSearchPreferences.notification.success.message"), message: t("user.action.changeDefaultSearchEngine.notification.success.message"),
}); });
}, },
onError() { onError() {
showErrorNotification({ showErrorNotification({
message: t("user.action.changeSearchPreferences.notification.error.message"), message: t("user.action.changeDefaultSearchEngine.notification.error.message"),
}); });
}, },
}); });
const form = useZodForm(validation.user.changeSearchPreferences, { const form = useZodForm(validation.user.changeDefaultSearchEngine, {
initialValues: { initialValues: {
defaultSearchEngineId: user.defaultSearchEngineId, defaultSearchEngineId: user.defaultSearchEngineId ?? "",
openInNewTab: user.openSearchInNewTab,
}, },
}); });
@@ -54,16 +52,7 @@ export const ChangeSearchPreferencesForm = ({ user, searchEnginesData }: ChangeS
return ( return (
<form onSubmit={form.onSubmit(handleSubmit)}> <form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md"> <Stack gap="md">
<Select <Select w="100%" data={searchEnginesData} {...form.getInputProps("defaultSearchEngineId")} />
label={t("user.field.defaultSearchEngine.label")}
w="100%"
data={searchEnginesData}
{...form.getInputProps("defaultSearchEngineId")}
/>
<Switch
label={t("user.field.openSearchInNewTab.label")}
{...form.getInputProps("openInNewTab", { type: "checkbox" })}
/>
<Group justify="end"> <Group justify="end">
<Button type="submit" color="teal" loading={isPending}> <Button type="submit" color="teal" loading={isPending}>
@@ -75,4 +64,4 @@ export const ChangeSearchPreferencesForm = ({ user, searchEnginesData }: ChangeS
); );
}; };
type FormType = z.infer<typeof validation.user.changeSearchPreferences>; type FormType = z.infer<typeof validation.user.changeDefaultSearchEngine>;
@@ -1,7 +1,6 @@
"use client"; "use client";
import { Button, Group, Select, Stack } from "@mantine/core"; import { Button, Group, Select, Stack } from "@mantine/core";
import type { z } from "zod";
import type { RouterOutputs } from "@homarr/api"; import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
@@ -9,6 +8,7 @@ import { revalidatePathActionAsync } from "@homarr/common/client";
import { useZodForm } from "@homarr/form"; import { useZodForm } from "@homarr/form";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation"; import { validation } from "@homarr/validation";
interface ChangeHomeBoardFormProps { interface ChangeHomeBoardFormProps {
@@ -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 ?? "",
}, },
}); });
@@ -4,7 +4,6 @@ import { Button, Group, Radio, Stack } from "@mantine/core";
import type { DayOfWeek } from "@mantine/dates"; import type { DayOfWeek } from "@mantine/dates";
import dayjs from "dayjs"; import dayjs from "dayjs";
import localeData from "dayjs/plugin/localeData"; import localeData from "dayjs/plugin/localeData";
import type { z } from "zod";
import type { RouterOutputs } from "@homarr/api"; import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
@@ -12,6 +11,7 @@ import { revalidatePathActionAsync } from "@homarr/common/client";
import { useZodForm } from "@homarr/form"; import { useZodForm } from "@homarr/form";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation"; import { validation } from "@homarr/validation";
dayjs.extend(localeData); dayjs.extend(localeData);
@@ -1,7 +1,6 @@
"use client"; "use client";
import { Button, Group, Stack, Switch } from "@mantine/core"; import { Button, Group, Stack, Switch } from "@mantine/core";
import type { z } from "zod";
import type { RouterOutputs } from "@homarr/api"; import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
@@ -9,6 +8,7 @@ import { revalidatePathActionAsync } from "@homarr/common/client";
import { useZodForm } from "@homarr/form"; import { useZodForm } from "@homarr/form";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation"; import { validation } from "@homarr/validation";
interface PingIconsEnabledProps { interface PingIconsEnabledProps {
@@ -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}>
@@ -11,8 +11,8 @@ import { DangerZoneItem, DangerZoneRoot } from "~/components/manage/danger-zone"
import { catchTrpcNotFound } from "~/errors/trpc-catch-error"; import { catchTrpcNotFound } from "~/errors/trpc-catch-error";
import { createMetaTitle } from "~/metadata"; import { createMetaTitle } from "~/metadata";
import { canAccessUserEditPage } from "../access"; import { canAccessUserEditPage } from "../access";
import { ChangeDefaultSearchEngineForm } from "./_components/_change-default-search-engine";
import { ChangeHomeBoardForm } from "./_components/_change-home-board"; import { ChangeHomeBoardForm } from "./_components/_change-home-board";
import { ChangeSearchPreferencesForm } from "./_components/_change-search-preferences";
import { DeleteUserButton } from "./_components/_delete-user-button"; import { DeleteUserButton } from "./_components/_delete-user-button";
import { FirstDayOfWeek } from "./_components/_first-day-of-week"; import { FirstDayOfWeek } from "./_components/_first-day-of-week";
import { PingIconsEnabled } from "./_components/_ping-icons-enabled"; import { PingIconsEnabled } from "./_components/_ping-icons-enabled";
@@ -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>
@@ -102,8 +100,8 @@ export default async function EditUserPage(props: Props) {
</Stack> </Stack>
<Stack mb="lg"> <Stack mb="lg">
<Title order={2}>{tGeneral("item.search")}</Title> <Title order={2}>{tGeneral("item.defaultSearchEngine")}</Title>
<ChangeSearchPreferencesForm user={user} searchEnginesData={searchEngines} /> <ChangeDefaultSearchEngineForm user={user} searchEnginesData={searchEngines} />
</Stack> </Stack>
<Stack mb="lg"> <Stack mb="lg">
@@ -17,7 +17,6 @@ import {
} from "@mantine/core"; } from "@mantine/core";
import { useListState } from "@mantine/hooks"; import { useListState } from "@mantine/hooks";
import { IconPlus, IconUserCheck } from "@tabler/icons-react"; import { IconPlus, IconUserCheck } from "@tabler/icons-react";
import { z } from "zod";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { everyoneGroup, groupPermissions } from "@homarr/definitions"; import { everyoneGroup, groupPermissions } from "@homarr/definitions";
@@ -27,7 +26,7 @@ import { useModalAction } from "@homarr/modals";
import { showErrorNotification } from "@homarr/notifications"; import { showErrorNotification } from "@homarr/notifications";
import { useI18n, useScopedI18n } from "@homarr/translation/client"; import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { CustomPasswordInput, UserAvatar } from "@homarr/ui"; import { CustomPasswordInput, UserAvatar } from "@homarr/ui";
import { validation } from "@homarr/validation"; import { validation, z } from "@homarr/validation";
import { createCustomErrorParams } from "@homarr/validation/form"; import { createCustomErrorParams } from "@homarr/validation/form";
import { GroupSelectModal } from "~/components/access/group-select-modal"; import { GroupSelectModal } from "~/components/access/group-select-modal";
@@ -1,7 +1,6 @@
import Link from "next/link"; import Link from "next/link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { Anchor, Group, Stack, Table, TableTbody, TableTd, TableTh, TableThead, TableTr, Title } from "@mantine/core"; import { Anchor, Group, Stack, Table, TableTbody, TableTd, TableTh, TableThead, TableTr, Title } from "@mantine/core";
import { z } from "zod";
import type { RouterOutputs } from "@homarr/api"; import type { RouterOutputs } from "@homarr/api";
import { api } from "@homarr/api/server"; import { api } from "@homarr/api/server";
@@ -9,6 +8,7 @@ import { auth } from "@homarr/auth/next";
import type { inferSearchParamsFromSchema } from "@homarr/common/types"; import type { inferSearchParamsFromSchema } from "@homarr/common/types";
import { getI18n } from "@homarr/translation/server"; import { getI18n } from "@homarr/translation/server";
import { SearchInput, TablePagination, UserAvatarGroup } from "@homarr/ui"; import { SearchInput, TablePagination, UserAvatarGroup } from "@homarr/ui";
import { z } from "@homarr/validation";
import { ManageContainer } from "~/components/manage/manage-container"; import { ManageContainer } from "~/components/manage/manage-container";
import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb"; import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
+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
@@ -1,11 +1,11 @@
import { useCallback, useRef } from "react"; import { useCallback, useRef } from "react";
import { Button, Grid, Group, NumberInput, Stack } from "@mantine/core"; import { Button, Grid, Group, NumberInput, Stack } from "@mantine/core";
import { z } from "zod";
import { useZodForm } from "@homarr/form"; import { useZodForm } from "@homarr/form";
import type { GridStack } from "@homarr/gridstack"; import type { GridStack } from "@homarr/gridstack";
import { createModal } from "@homarr/modals"; import { createModal } from "@homarr/modals";
import { useI18n, useScopedI18n } from "@homarr/translation/client"; import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { z } from "@homarr/validation";
import type { Item } from "~/app/[locale]/boards/_types"; import type { Item } from "~/app/[locale]/boards/_types";
@@ -1,12 +1,12 @@
"use client"; "use client";
import { Button, Group, Stack, TextInput } from "@mantine/core"; import { Button, Group, Stack, TextInput } from "@mantine/core";
import type { z } from "zod";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { useZodForm } from "@homarr/form"; import { useZodForm } from "@homarr/form";
import { createModal } from "@homarr/modals"; import { createModal } from "@homarr/modals";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation"; import { validation } from "@homarr/validation";
interface InnerProps { interface InnerProps {
@@ -2,32 +2,19 @@ import { Card, Collapse, Group, Stack, Title, UnstyledButton } from "@mantine/co
import { useDisclosure } from "@mantine/hooks"; import { useDisclosure } from "@mantine/hooks";
import { IconChevronDown, IconChevronUp } from "@tabler/icons-react"; import { IconChevronDown, IconChevronUp } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import type { CategorySection } from "~/app/[locale]/boards/_types"; import type { CategorySection } from "~/app/[locale]/boards/_types";
import { useRequiredBoard } from "~/app/[locale]/boards/(content)/_context";
import { CategoryMenu } from "./category/category-menu"; import { CategoryMenu } from "./category/category-menu";
import { GridStack } from "./gridstack/gridstack"; import { GridStack } from "./gridstack/gridstack";
import classes from "./item.module.css";
interface Props { interface Props {
section: CategorySection; section: CategorySection;
} }
export const BoardCategorySection = ({ section }: Props) => { export const BoardCategorySection = ({ section }: Props) => {
const { mutate } = clientApi.section.changeCollapsed.useMutation(); const [opened, { toggle }] = useDisclosure(false);
const board = useRequiredBoard();
const [opened, { toggle }] = useDisclosure(section.collapsed, {
onOpen() {
mutate({ sectionId: section.id, collapsed: true });
},
onClose() {
mutate({ sectionId: section.id, collapsed: false });
},
});
return ( return (
<Card style={{ "--opacity": board.opacity / 100 }} withBorder p={0} className={classes.itemCard}> <Card withBorder p={0}>
<Stack> <Stack>
<Group wrap="nowrap" gap="sm"> <Group wrap="nowrap" gap="sm">
<UnstyledButton w="100%" p="sm" onClick={toggle}> <UnstyledButton w="100%" p="sm" onClick={toggle}>
@@ -67,7 +67,6 @@ const createSections = (categoryCount: number) => {
name: `Category ${index}`, name: `Category ${index}`,
yOffset: index, yOffset: index,
xOffset: 0, xOffset: 0,
collapsed: false,
items: [], items: [],
})) satisfies Section[]; })) satisfies Section[];
}; };
@@ -118,7 +118,6 @@ const createSections = (initialYOffsets: number[]) => {
id: yOffset.toString(), id: yOffset.toString(),
kind: index % 2 === 0 ? "empty" : "category", kind: index % 2 === 0 ? "empty" : "category",
name: "Category", name: "Category",
collapsed: false,
yOffset, yOffset,
xOffset: 0, xOffset: 0,
items: [createItem({ id: yOffset.toString() })], items: [createItem({ id: yOffset.toString() })],
@@ -40,7 +40,6 @@ export const useCategoryActions = () => {
kind: "category", kind: "category",
yOffset, yOffset,
xOffset: 0, xOffset: 0,
collapsed: false,
items: [], items: [],
}, },
{ {
@@ -90,7 +89,6 @@ export const useCategoryActions = () => {
kind: "category", kind: "category",
yOffset: lastYOffset + 1, yOffset: lastYOffset + 1,
xOffset: 0, xOffset: 0,
collapsed: false,
items: [], items: [],
}, },
{ {
@@ -1,9 +1,9 @@
import { Button, Group, Stack, TextInput } from "@mantine/core"; import { Button, Group, Stack, TextInput } from "@mantine/core";
import { z } from "zod";
import { useZodForm } from "@homarr/form"; import { useZodForm } from "@homarr/form";
import { createModal } from "@homarr/modals"; import { createModal } from "@homarr/modals";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import { z } from "@homarr/validation";
interface Category { interface Category {
id: string; id: string;
+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,
}); });
+3 -3
View File
@@ -38,15 +38,15 @@
"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.19.0", "eslint": "^9.18.0",
"prettier": "^3.4.2", "prettier": "^3.4.2",
"tsx": "4.19.2", "tsx": "4.19.2",
"typescript": "^5.7.3" "typescript": "^5.7.3"
@@ -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);
+2 -2
View File
@@ -33,8 +33,8 @@
"@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.19.0", "eslint": "^9.18.0",
"prettier": "^3.4.2", "prettier": "^3.4.2",
"typescript": "^5.7.3" "typescript": "^5.7.3"
} }
-8
View File
@@ -39,14 +39,6 @@ const handler = applyWSSHandler({
}); });
} }
}, },
// Enable heartbeat messages to keep connection open (disabled by default)
keepAlive: {
enabled: true,
// server ping message interval in milliseconds
pingMs: 30000,
// connection is terminated if pong message is not received in this many milliseconds
pongWaitMs: 5000,
},
}); });
wss.on("connection", (websocket, incomingMessage) => { wss.on("connection", (websocket, incomingMessage) => {
+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.3.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.2", "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"
} }
+1 -1
View File
@@ -32,7 +32,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",
"eslint": "^9.19.0", "eslint": "^9.18.0",
"typescript": "^5.7.3" "typescript": "^5.7.3"
} }
} }
+5 -7
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,20 +41,20 @@
"@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",
"pretty-print-error": "^1.1.2",
"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",
"trpc-to-openapi": "^2.1.2", "trpc-to-openapi": "^2.1.2"
"zod": "^3.24.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",
"eslint": "^9.19.0", "@types/dockerode": "^3.3.34",
"eslint": "^9.18.0",
"prettier": "^3.4.2", "prettier": "^3.4.2",
"typescript": "^5.7.3" "typescript": "^5.7.3"
} }
+39 -42
View File
@@ -1,5 +1,4 @@
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { z } from "zod";
import type { Session } from "@homarr/auth"; import type { Session } from "@homarr/auth";
import { hasQueryAccessToIntegrationsAsync } from "@homarr/auth/server"; import { hasQueryAccessToIntegrationsAsync } from "@homarr/auth/server";
@@ -10,6 +9,7 @@ import type { Database } from "@homarr/db";
import { and, eq, inArray } from "@homarr/db"; import { and, eq, inArray } from "@homarr/db";
import { integrations } from "@homarr/db/schema"; import { integrations } from "@homarr/db/schema";
import type { IntegrationKind } from "@homarr/definitions"; import type { IntegrationKind } from "@homarr/definitions";
import { z } from "@homarr/validation";
import { publicProcedure } from "../trpc"; import { publicProcedure } from "../trpc";
@@ -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),
})), })),
}), }),
), ),
}, },
});
}); });
});
}; };
/** /**
+1 -1
View File
@@ -1,9 +1,9 @@
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { and, eq } from "@homarr/db"; import { and, eq } from "@homarr/db";
import { items } from "@homarr/db/schema"; import { items } from "@homarr/db/schema";
import type { WidgetKind } from "@homarr/definitions"; import type { WidgetKind } from "@homarr/definitions";
import { z } from "@homarr/validation";
import { publicProcedure } from "../trpc"; import { publicProcedure } from "../trpc";
-4
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";
@@ -15,7 +14,6 @@ import { logRouter } from "./router/log";
import { mediaRouter } from "./router/medias/media-router"; import { mediaRouter } from "./router/medias/media-router";
import { onboardRouter } from "./router/onboard/onboard-router"; import { onboardRouter } from "./router/onboard/onboard-router";
import { searchEngineRouter } from "./router/search-engine/search-engine-router"; import { searchEngineRouter } from "./router/search-engine/search-engine-router";
import { sectionRouter } from "./router/section/section-router";
import { serverSettingsRouter } from "./router/serverSettings"; import { serverSettingsRouter } from "./router/serverSettings";
import { updateCheckerRouter } from "./router/update-checker"; import { updateCheckerRouter } from "./router/update-checker";
import { userRouter } from "./router/user"; import { userRouter } from "./router/user";
@@ -28,7 +26,6 @@ export const appRouter = createTRPCRouter({
invite: inviteRouter, invite: inviteRouter,
integration: integrationRouter, integration: integrationRouter,
board: boardRouter, board: boardRouter,
section: sectionRouter,
app: innerAppRouter, app: innerAppRouter,
searchEngine: searchEngineRouter, searchEngine: searchEngineRouter,
widget: widgetRouter, widget: widgetRouter,
@@ -44,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
+2 -3
View File
@@ -1,11 +1,10 @@
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { asc, createId, eq, inArray, like } from "@homarr/db"; import { asc, createId, eq, inArray, like } from "@homarr/db";
import { apps } from "@homarr/db/schema"; import { apps } from "@homarr/db/schema";
import { selectAppSchema } from "@homarr/db/validationSchemas"; import { selectAppSchema } from "@homarr/db/validationSchemas";
import { getIconForName } from "@homarr/icons"; import { getIconForName } from "@homarr/icons";
import { validation } from "@homarr/validation"; import { validation, z } from "@homarr/validation";
import { convertIntersectionToZodObject } from "../schema-merger"; import { convertIntersectionToZodObject } from "../schema-merger";
import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure, publicProcedure } from "../trpc"; import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure, publicProcedure } from "../trpc";
@@ -103,7 +102,7 @@ export const appRouter = createTRPCRouter({
return app; return app;
}), }),
byIds: publicProcedure.input(z.array(z.string())).query(async ({ ctx, input }) => { byIds: protectedProcedure.input(z.array(z.string())).query(async ({ ctx, input }) => {
return await ctx.db.query.apps.findMany({ return await ctx.db.query.apps.findMany({
where: inArray(apps.id, input), where: inArray(apps.id, input),
}); });
+184 -457
View File
@@ -1,11 +1,10 @@
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import superjson from "superjson"; import superjson from "superjson";
import { z } from "zod";
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,
@@ -17,7 +16,6 @@ import {
integrationItems, integrationItems,
integrationUserPermissions, integrationUserPermissions,
items, items,
sectionCollapseStates,
sections, sections,
users, users,
} from "@homarr/db/schema"; } from "@homarr/db/schema";
@@ -27,7 +25,7 @@ import { importOldmarrAsync } from "@homarr/old-import";
import { importJsonFileSchema } from "@homarr/old-import/shared"; import { importJsonFileSchema } from "@homarr/old-import/shared";
import { oldmarrConfigSchema } from "@homarr/old-schema"; import { oldmarrConfigSchema } from "@homarr/old-schema";
import type { BoardItemAdvancedOptions } from "@homarr/validation"; import type { BoardItemAdvancedOptions } from "@homarr/validation";
import { createSectionSchema, sharedItemSchema, validation, zodUnionFromArray } from "@homarr/validation"; import { createSectionSchema, sharedItemSchema, validation, z, zodUnionFromArray } from "@homarr/validation";
import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure, publicProcedure } from "../trpc"; import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure, publicProcedure } from "../trpc";
import { throwIfActionForbiddenAsync } from "./board/board-access"; import { throwIfActionForbiddenAsync } from "./board/board-access";
@@ -206,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
@@ -332,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 }) => {
@@ -490,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();
}
});
},
}); });
}), }),
@@ -876,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
@@ -919,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
@@ -1026,9 +757,6 @@ const getFullBoardWithWhereAsync = async (db: Database, where: SQL<unknown>, use
}, },
sections: { sections: {
with: { with: {
collapseStates: {
where: eq(sectionCollapseStates.userId, userId ?? ""),
},
items: { items: {
with: { with: {
integrations: { integrations: {
@@ -1063,10 +791,9 @@ const getFullBoardWithWhereAsync = async (db: Database, where: SQL<unknown>, use
return { return {
...otherBoardProperties, ...otherBoardProperties,
sections: sections.map(({ collapseStates, ...section }) => sections: sections.map((section) =>
parseSection({ parseSection({
...section, ...section,
collapsed: collapseStates.at(0)?.collapsed ?? false,
items: section.items.map(({ integrations: itemIntegrations, ...item }) => ({ items: section.items.map(({ integrations: itemIntegrations, ...item }) => ({
...item, ...item,
integrationIds: itemIntegrations.map((item) => item.integration.id), integrationIds: itemIntegrations.map((item) => item.integration.id),
@@ -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);
}),
});
+14 -11
View File
@@ -1,24 +1,26 @@
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { z } from "zod"; 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 { 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;
}
}
+1 -2
View File
@@ -1,11 +1,10 @@
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { z } from "zod";
import type { Database } from "@homarr/db"; import type { Database } from "@homarr/db";
import { and, createId, eq, like, not, sql } from "@homarr/db"; import { and, createId, eq, like, not, sql } from "@homarr/db";
import { groupMembers, groupPermissions, groups } from "@homarr/db/schema"; import { groupMembers, groupPermissions, groups } from "@homarr/db/schema";
import { everyoneGroup } from "@homarr/definitions"; import { everyoneGroup } from "@homarr/definitions";
import { validation } from "@homarr/validation"; import { validation, z } from "@homarr/validation";
import { createTRPCRouter, onboardingProcedure, permissionRequiredProcedure, protectedProcedure } from "../trpc"; import { createTRPCRouter, onboardingProcedure, permissionRequiredProcedure, protectedProcedure } from "../trpc";
import { throwIfCredentialsDisabled } from "./invite/checks"; import { throwIfCredentialsDisabled } from "./invite/checks";
@@ -1,11 +1,10 @@
import { z } from "zod";
import { analyseOldmarrImportForRouterAsync, analyseOldmarrImportInputSchema } from "@homarr/old-import/analyse"; import { analyseOldmarrImportForRouterAsync, analyseOldmarrImportInputSchema } from "@homarr/old-import/analyse";
import { import {
ensureValidTokenOrThrow, ensureValidTokenOrThrow,
importInitialOldmarrAsync, importInitialOldmarrAsync,
importInitialOldmarrInputSchema, importInitialOldmarrInputSchema,
} from "@homarr/old-import/import"; } from "@homarr/old-import/import";
import { z } from "@homarr/validation";
import { createTRPCRouter, onboardingProcedure } from "../../trpc"; import { createTRPCRouter, onboardingProcedure } from "../../trpc";
import { nextOnboardingStepAsync } from "../onboard/onboard-queries"; import { nextOnboardingStepAsync } from "../onboard/onboard-queries";
@@ -1,10 +1,9 @@
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { z } from "zod";
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,
@@ -24,7 +23,7 @@ import {
integrationSecretKindObject, integrationSecretKindObject,
} from "@homarr/definitions"; } from "@homarr/definitions";
import { integrationCreator } from "@homarr/integrations"; import { integrationCreator } from "@homarr/integrations";
import { validation } from "@homarr/validation"; import { validation, z } from "@homarr/validation";
import { createOneIntegrationMiddleware } from "../../middlewares/integration"; import { createOneIntegrationMiddleware } from "../../middlewares/integration";
import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure, publicProcedure } from "../../trpc"; import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure, publicProcedure } from "../../trpc";
@@ -131,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({
@@ -371,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
@@ -417,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,11 +1,8 @@
import { formatError } from "pretty-print-error";
import { decryptSecret } from "@homarr/common/server"; import { decryptSecret } from "@homarr/common/server";
import type { Integration } from "@homarr/db/schema"; import type { Integration } from "@homarr/db/schema";
import type { IntegrationKind, IntegrationSecretKind } from "@homarr/definitions"; import type { IntegrationKind, IntegrationSecretKind } from "@homarr/definitions";
import { getAllSecretKindOptions } from "@homarr/definitions"; import { getAllSecretKindOptions } from "@homarr/definitions";
import { integrationCreator, IntegrationTestConnectionError } from "@homarr/integrations"; import { integrationCreator, IntegrationTestConnectionError } from "@homarr/integrations";
import { logger } from "@homarr/log";
type FormIntegration = Integration & { type FormIntegration = Integration & {
secrets: { secrets: {
@@ -31,22 +28,11 @@ export const testConnectionAsync = async (
source: "form" as const, source: "form" as const,
})); }));
const decryptedDbSecrets = dbSecrets const decryptedDbSecrets = dbSecrets.map((secret) => ({
.map((secret) => { ...secret,
try { value: decryptSecret(secret.value),
return { source: "db" as const,
...secret, }));
value: decryptSecret(secret.value),
source: "db" as const,
};
} catch (error) {
logger.warn(
`Failed to decrypt secret from database integration="${integration.name}" secretKind="${secret.kind}"\n${formatError(error)}`,
);
return null;
}
})
.filter((secret) => secret !== null);
const sourcedSecrets = [...formSecrets, ...decryptedDbSecrets]; const sourcedSecrets = [...formSecrets, ...decryptedDbSecrets];
const secretKinds = getSecretKindOption(integration.kind, sourcedSecrets); const secretKinds = getSecretKindOption(integration.kind, sourcedSecrets);
+1 -1
View File
@@ -1,10 +1,10 @@
import { randomBytes } from "crypto"; import { randomBytes } from "crypto";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { asc, createId, eq } from "@homarr/db"; import { asc, createId, eq } from "@homarr/db";
import { invites } from "@homarr/db/schema"; import { invites } from "@homarr/db/schema";
import { selectInviteSchema } from "@homarr/db/validationSchemas"; import { selectInviteSchema } from "@homarr/db/validationSchemas";
import { z } from "@homarr/validation";
import { createTRPCRouter, permissionRequiredProcedure } from "../trpc"; import { createTRPCRouter, permissionRequiredProcedure } from "../trpc";
import { throwIfCredentialsDisabled } from "./invite/checks"; import { throwIfCredentialsDisabled } from "./invite/checks";
+1 -2
View File
@@ -1,6 +1,5 @@
import type { z } from "zod";
import { fetchWithTimeout } from "@homarr/common"; import { fetchWithTimeout } from "@homarr/common";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation"; import { validation } from "@homarr/validation";
import { createTRPCRouter, publicProcedure } from "../trpc"; import { createTRPCRouter, publicProcedure } from "../trpc";
@@ -1,11 +1,10 @@
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { z } from "zod";
import type { InferInsertModel } from "@homarr/db"; import type { InferInsertModel } from "@homarr/db";
import { and, createId, desc, eq, like } from "@homarr/db"; import { and, createId, desc, eq, like } from "@homarr/db";
import { iconRepositories, icons, medias } from "@homarr/db/schema"; import { iconRepositories, icons, medias } from "@homarr/db/schema";
import { createLocalImageUrl, LOCAL_ICON_REPOSITORY_SLUG, mapMediaToIcon } from "@homarr/icons/local"; import { createLocalImageUrl, LOCAL_ICON_REPOSITORY_SLUG, mapMediaToIcon } from "@homarr/icons/local";
import { validation } from "@homarr/validation"; import { validation, z } from "@homarr/validation";
import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure } from "../../trpc"; import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure } from "../../trpc";
@@ -1,8 +1,6 @@
import { z } from "zod";
import { onboarding } from "@homarr/db/schema"; import { onboarding } from "@homarr/db/schema";
import { onboardingSteps } from "@homarr/definitions"; import { onboardingSteps } from "@homarr/definitions";
import { zodEnumFromArray } from "@homarr/validation"; import { z, zodEnumFromArray } from "@homarr/validation";
import { createTRPCRouter, publicProcedure } from "../../trpc"; import { createTRPCRouter, publicProcedure } from "../../trpc";
import { getOnboardingOrFallbackAsync, nextOnboardingStepAsync } from "./onboard-queries"; import { getOnboardingOrFallbackAsync, nextOnboardingStepAsync } from "./onboard-queries";
@@ -1,11 +1,10 @@
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { asc, createId, eq, like, sql } from "@homarr/db"; import { asc, createId, eq, like, sql } from "@homarr/db";
import { getServerSettingByKeyAsync } from "@homarr/db/queries"; import { getServerSettingByKeyAsync } from "@homarr/db/queries";
import { searchEngines, users } from "@homarr/db/schema"; import { searchEngines, users } from "@homarr/db/schema";
import { integrationCreator } from "@homarr/integrations"; import { integrationCreator } from "@homarr/integrations";
import { validation } from "@homarr/validation"; import { validation, z } from "@homarr/validation";
import { createOneIntegrationMiddleware } from "../../middlewares/integration"; import { createOneIntegrationMiddleware } from "../../middlewares/integration";
import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure, publicProcedure } from "../../trpc"; import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure, publicProcedure } from "../../trpc";
@@ -1,52 +0,0 @@
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { and, eq } from "@homarr/db";
import { sectionCollapseStates, sections } from "@homarr/db/schema";
import { createTRPCRouter, protectedProcedure } from "../../trpc";
export const sectionRouter = createTRPCRouter({
changeCollapsed: protectedProcedure
.input(
z.object({
sectionId: z.string(),
collapsed: z.boolean(),
}),
)
.mutation(async ({ ctx, input }) => {
const section = await ctx.db.query.sections.findFirst({
where: and(eq(sections.id, input.sectionId), eq(sections.kind, "category")),
with: {
collapseStates: {
where: eq(sectionCollapseStates.userId, ctx.session.user.id),
},
},
});
if (!section) {
throw new TRPCError({
code: "NOT_FOUND",
message: `Section not found id=${input.sectionId}`,
});
}
if (section.collapseStates.length === 0) {
await ctx.db.insert(sectionCollapseStates).values({
sectionId: section.id,
userId: ctx.session.user.id,
collapsed: input.collapsed,
});
return;
}
await ctx.db
.update(sectionCollapseStates)
.set({
collapsed: input.collapsed,
})
.where(
and(eq(sectionCollapseStates.sectionId, section.id), eq(sectionCollapseStates.userId, ctx.session.user.id)),
);
}),
});
+1 -3
View File
@@ -1,9 +1,7 @@
import { z } from "zod";
import { getServerSettingByKeyAsync, getServerSettingsAsync, updateServerSettingByKeyAsync } from "@homarr/db/queries"; import { getServerSettingByKeyAsync, getServerSettingsAsync, updateServerSettingByKeyAsync } from "@homarr/db/queries";
import type { ServerSettings } from "@homarr/server-settings"; import type { ServerSettings } from "@homarr/server-settings";
import { defaultServerSettingsKeys } from "@homarr/server-settings"; import { defaultServerSettingsKeys } from "@homarr/server-settings";
import { validation } from "@homarr/validation"; import { validation, z } from "@homarr/validation";
import { createTRPCRouter, onboardingProcedure, permissionRequiredProcedure, publicProcedure } from "../trpc"; import { createTRPCRouter, onboardingProcedure, permissionRequiredProcedure, publicProcedure } from "../trpc";
import { nextOnboardingStepAsync } from "./onboard/onboard-queries"; import { nextOnboardingStepAsync } from "./onboard/onboard-queries";
+1 -3
View File
@@ -812,7 +812,7 @@ describe("saveBoard should save full board", () => {
expect(integration).toBeUndefined(); expect(integration).toBeUndefined();
expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "modify"); expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "modify");
}); });
it.each([[{ kind: "empty" as const }], [{ kind: "category" as const, collapsed: false, name: "My first category" }]])( it.each([[{ kind: "empty" as const }], [{ kind: "category" as const, name: "My first category" }]])(
"should add section when present in input", "should add section when present in input",
async (partialSection) => { async (partialSection) => {
const spy = vi.spyOn(boardAccess, "throwIfActionForbiddenAsync"); const spy = vi.spyOn(boardAccess, "throwIfActionForbiddenAsync");
@@ -1023,7 +1023,6 @@ describe("saveBoard should save full board", () => {
yOffset: 1, yOffset: 1,
xOffset: 0, xOffset: 0,
name: "Test", name: "Test",
collapsed: true,
items: [], items: [],
}, },
{ {
@@ -1032,7 +1031,6 @@ describe("saveBoard should save full board", () => {
name: "After", name: "After",
yOffset: 0, yOffset: 0,
xOffset: 0, xOffset: 0,
collapsed: false,
items: [], items: [],
}, },
], ],
+62 -34
View File
@@ -1,5 +1,4 @@
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { createSaltAsync, hashPasswordAsync } from "@homarr/auth"; import { createSaltAsync, hashPasswordAsync } from "@homarr/auth";
import type { Database } from "@homarr/db"; import type { Database } from "@homarr/db";
@@ -9,7 +8,7 @@ import { selectUserSchema } from "@homarr/db/validationSchemas";
import { credentialsAdminGroup } from "@homarr/definitions"; import { credentialsAdminGroup } from "@homarr/definitions";
import type { SupportedAuthProvider } from "@homarr/definitions"; import type { SupportedAuthProvider } from "@homarr/definitions";
import { logger } from "@homarr/log"; import { logger } from "@homarr/log";
import { validation } from "@homarr/validation"; import { validation, z } from "@homarr/validation";
import { convertIntersectionToZodObject } from "../schema-merger"; import { convertIntersectionToZodObject } from "../schema-merger";
import { import {
@@ -22,7 +21,6 @@ import {
import { throwIfActionForbiddenAsync } from "./board/board-access"; import { throwIfActionForbiddenAsync } from "./board/board-access";
import { throwIfCredentialsDisabled } from "./invite/checks"; import { throwIfCredentialsDisabled } from "./invite/checks";
import { nextOnboardingStepAsync } from "./onboard/onboard-queries"; import { nextOnboardingStepAsync } from "./onboard/onboard-queries";
import { changeSearchPreferencesAsync, changeSearchPreferencesInputSchema } from "./user/change-search-preferences";
export const userRouter = createTRPCRouter({ export const userRouter = createTRPCRouter({
initUser: onboardingProcedure initUser: onboardingProcedure
@@ -216,7 +214,6 @@ export const userRouter = createTRPCRouter({
firstDayOfWeek: true, firstDayOfWeek: true,
pingIconsEnabled: true, pingIconsEnabled: true,
defaultSearchEngineId: true, defaultSearchEngineId: true,
openSearchInNewTab: true,
}), }),
) )
.meta({ openapi: { method: "GET", path: "/api/users/{userId}", tags: ["users"], protect: true } }) .meta({ openapi: { method: "GET", path: "/api/users/{userId}", tags: ["users"], protect: true } })
@@ -241,7 +238,6 @@ export const userRouter = createTRPCRouter({
firstDayOfWeek: true, firstDayOfWeek: true,
pingIconsEnabled: true, pingIconsEnabled: true,
defaultSearchEngineId: true, defaultSearchEngineId: true,
openSearchInNewTab: true,
}, },
where: eq(users.id, input.userId), where: eq(users.id, input.userId),
}); });
@@ -408,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)
@@ -426,32 +416,40 @@ export const userRouter = createTRPCRouter({
}), }),
changeDefaultSearchEngine: protectedProcedure changeDefaultSearchEngine: protectedProcedure
.input( .input(
convertIntersectionToZodObject( convertIntersectionToZodObject(validation.user.changeDefaultSearchEngine.and(z.object({ userId: z.string() }))),
validation.user.changeSearchPreferences.omit({ openInNewTab: true }).and(z.object({ userId: z.string() })),
),
) )
.output(z.void()) .output(z.void())
.meta({ .meta({ openapi: { method: "PATCH", path: "/api/users/changeSearchEngine", tags: ["users"], protect: true } })
openapi: {
method: "PATCH",
path: "/api/users/changeSearchEngine",
tags: ["users"],
protect: true,
deprecated: true,
},
})
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
await changeSearchPreferencesAsync(ctx.db, ctx.session, { const user = ctx.session.user;
...input, // Only admins can change other users passwords
openInNewTab: undefined, if (!user.permissions.includes("admin") && user.id !== input.userId) {
throw new TRPCError({
code: "NOT_FOUND",
message: "User not found",
});
}
const dbUser = await ctx.db.query.users.findFirst({
columns: {
id: true,
},
where: eq(users.id, input.userId),
}); });
}),
changeSearchPreferences: protectedProcedure if (!dbUser) {
.input(convertIntersectionToZodObject(changeSearchPreferencesInputSchema)) throw new TRPCError({
.output(z.void()) code: "NOT_FOUND",
.meta({ openapi: { method: "PATCH", path: "/api/users/search-preferences", tags: ["users"], protect: true } }) message: "User not found",
.mutation(async ({ input, ctx }) => { });
await changeSearchPreferencesAsync(ctx.db, ctx.session, input); }
await ctx.db
.update(users)
.set({
defaultSearchEngineId: input.defaultSearchEngineId,
})
.where(eq(users.id, input.userId));
}), }),
changeColorScheme: protectedProcedure changeColorScheme: protectedProcedure
.input(validation.user.changeColorScheme) .input(validation.user.changeColorScheme)
@@ -465,6 +463,21 @@ export const userRouter = createTRPCRouter({
}) })
.where(eq(users.id, ctx.session.user.id)); .where(eq(users.id, ctx.session.user.id));
}), }),
getPingIconsEnabledOrDefault: publicProcedure.query(async ({ ctx }) => {
if (!ctx.session?.user) {
return false;
}
const user = await ctx.db.query.users.findFirst({
columns: {
id: true,
pingIconsEnabled: true,
},
where: eq(users.id, ctx.session.user.id),
});
return user?.pingIconsEnabled ?? false;
}),
changePingIconsEnabled: protectedProcedure changePingIconsEnabled: protectedProcedure
.input(validation.user.pingIconsEnabled.and(validation.common.byId)) .input(validation.user.pingIconsEnabled.and(validation.common.byId))
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
@@ -483,6 +496,21 @@ export const userRouter = createTRPCRouter({
}) })
.where(eq(users.id, ctx.session.user.id)); .where(eq(users.id, ctx.session.user.id));
}), }),
getFirstDayOfWeekForUserOrDefault: publicProcedure.input(z.undefined()).query(async ({ ctx }) => {
if (!ctx.session?.user) {
return 1 as const;
}
const user = await ctx.db.query.users.findFirst({
columns: {
id: true,
firstDayOfWeek: true,
},
where: eq(users.id, ctx.session.user.id),
});
return user?.firstDayOfWeek ?? (1 as const);
}),
changeFirstDayOfWeek: protectedProcedure changeFirstDayOfWeek: protectedProcedure
.input(convertIntersectionToZodObject(validation.user.firstDayOfWeek.and(validation.common.byId))) .input(convertIntersectionToZodObject(validation.user.firstDayOfWeek.and(validation.common.byId)))
.output(z.void()) .output(z.void())
@@ -1,50 +0,0 @@
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import type { Session } from "@homarr/auth";
import type { Modify } from "@homarr/common/types";
import { eq } from "@homarr/db";
import type { Database } from "@homarr/db";
import { users } from "@homarr/db/schema";
import { validation } from "@homarr/validation";
export const changeSearchPreferencesInputSchema = validation.user.changeSearchPreferences.and(
z.object({ userId: z.string() }),
);
export const changeSearchPreferencesAsync = async (
db: Database,
session: Session,
input: Modify<z.infer<typeof changeSearchPreferencesInputSchema>, { openInNewTab: boolean | undefined }>,
) => {
const user = session.user;
// Only admins can change other users passwords
if (!user.permissions.includes("admin") && user.id !== input.userId) {
throw new TRPCError({
code: "NOT_FOUND",
message: "User not found",
});
}
const dbUser = await db.query.users.findFirst({
columns: {
id: true,
},
where: eq(users.id, input.userId),
});
if (!dbUser) {
throw new TRPCError({
code: "NOT_FOUND",
message: "User not found",
});
}
await db
.update(users)
.set({
defaultSearchEngineId: input.defaultSearchEngineId,
openSearchInNewTab: input.openInNewTab,
})
.where(eq(users.id, input.userId));
};
+1 -1
View File
@@ -1,8 +1,8 @@
import { observable } from "@trpc/server/observable"; import { observable } from "@trpc/server/observable";
import { z } from "zod";
import { sendPingRequestAsync } from "@homarr/ping"; import { sendPingRequestAsync } from "@homarr/ping";
import { pingChannel, pingUrlChannel } from "@homarr/redis"; import { pingChannel, pingUrlChannel } from "@homarr/redis";
import { z } from "@homarr/validation";
import { createTRPCRouter, publicProcedure } from "../../trpc"; import { createTRPCRouter, publicProcedure } from "../../trpc";
+1 -2
View File
@@ -1,8 +1,7 @@
import { z } from "zod";
import { getIntegrationKindsByCategory } from "@homarr/definitions"; import { getIntegrationKindsByCategory } from "@homarr/definitions";
import { radarrReleaseTypes } from "@homarr/integrations/types"; import { radarrReleaseTypes } from "@homarr/integrations/types";
import { calendarMonthRequestHandler } from "@homarr/request-handler/calendar"; import { calendarMonthRequestHandler } from "@homarr/request-handler/calendar";
import { z } from "@homarr/validation";
import { createManyIntegrationMiddleware } from "../../middlewares/integration"; import { createManyIntegrationMiddleware } from "../../middlewares/integration";
import { createTRPCRouter, publicProcedure } from "../../trpc"; import { createTRPCRouter, publicProcedure } from "../../trpc";
+1 -1
View File
@@ -1,5 +1,4 @@
import { observable } from "@trpc/server/observable"; import { observable } from "@trpc/server/observable";
import { z } from "zod";
import type { Modify } from "@homarr/common/types"; import type { Modify } from "@homarr/common/types";
import type { Integration } from "@homarr/db/schema"; import type { Integration } from "@homarr/db/schema";
@@ -8,6 +7,7 @@ import { getIntegrationKindsByCategory } from "@homarr/definitions";
import type { DownloadClientJobsAndStatus } from "@homarr/integrations"; import type { DownloadClientJobsAndStatus } from "@homarr/integrations";
import { downloadClientItemSchema, integrationCreator } from "@homarr/integrations"; import { downloadClientItemSchema, integrationCreator } from "@homarr/integrations";
import { downloadClientRequestHandler } from "@homarr/request-handler/downloads"; import { downloadClientRequestHandler } from "@homarr/request-handler/downloads";
import { z } from "@homarr/validation";
import type { IntegrationAction } from "../../middlewares/integration"; import type { IntegrationAction } from "../../middlewares/integration";
import { createManyIntegrationMiddleware } from "../../middlewares/integration"; import { createManyIntegrationMiddleware } from "../../middlewares/integration";
@@ -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();
};
});
}),
}); });
Loaded 100 of 298 files, more files were not shown because too many files have changed in this diff. Show more