harden v2 custom widgets and workshop

This commit is contained in:
ajnart committed 2026-07-28 14:12:14 +02:00
1 parent e8a2c87c2d
commit 723b46926a
194 files changed
+44862 -1265

No files matched your search

+31 -17
View File
@@ -1,28 +1,42 @@
# Create T3 App
# Homarr web application
This is a [T3 Stack](https://create.t3.gg/) project bootstrapped with `create-t3-app`.
This workspace contains Homarr's Next.js application. It consumes the shared API, authentication, database, board,
widget, translation, and UI packages from this monorepo.
## What's next? How do I make an app with this?
Run commands from the repository root:
We try to keep this project as simple as possible, so you can start with just the scaffolding we set up for you, and add additional things later when they become necessary.
```sh
pnpm install --frozen-lockfile
cp .env.example .env
```
If you are not familiar with the different technologies used in this project, please refer to the respective docs. If you still are in the wind, please join our [Discord](https://t3.gg/discord) and ask for help.
Keep infrastructure running in the first terminal:
- [Next.js](https://nextjs.org)
- [NextAuth.js](https://next-auth.js.org)
- [Drizzle](https://orm.drizzle.team)
- [Tailwind CSS](https://tailwindcss.com)
- [tRPC](https://trpc.io)
```sh
pnpm docker:dev
```
## Learn More
Apply migrations and start the application in a second terminal:
To learn more about the [T3 Stack](https://create.t3.gg/), take a look at the following resources:
```sh
pnpm db:migration:sqlite:run
pnpm dev
```
- [Documentation](https://create.t3.gg/)
- [Learn the T3 Stack](https://create.t3.gg/en/faq#what-learning-resources-are-currently-available) — Check out these awesome tutorials
The app listens on `http://127.0.0.1:3000`. Configure an absolute writable `DB_URL`, `AUTH_SECRET`, and
`SECRET_ENCRYPTION_KEY` in `.env` before first startup.
You can check out the [create-t3-app GitHub repository](https://github.com/t3-oss/create-t3-app) — your feedback and contributions are welcome!
To test Custom Widgets against a local Community Workshop, run `pnpm dev:workshop` in another terminal and set:
## How do I deploy this?
```dotenv
HOMARR_WEBSITE_URL=http://127.0.0.1:3003
WORKSHOP_API_URL=http://127.0.0.1:8090
WORKSHOP_WEB_URL=http://127.0.0.1:3003/workshop
```
Follow our deployment guides for [Vercel](https://create.t3.gg/en/deployment/vercel) and [Docker](https://create.t3.gg/en/deployment/docker) for more information.
Server-rendered runtime configuration exposes those URLs to the browser, so changing a production container's
environment does not require rebuilding the Next.js bundle.
See the repository [`README.md`](../../README.md) for validation commands and
[`apps/docs/docs/advanced/development/getting-started.mdx`](../docs/docs/advanced/development/getting-started.mdx) for
the full contributor setup.
@@ -9,6 +9,7 @@ import "~/styles/prismjs.scss";
import { IconInfoCircle } from "@tabler/icons-react";
import { useForm } from "@homarr/form";
import { useSession } from "@homarr/auth/client";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { WorkshopCssImportButton } from "~/components/workshop/workshop-css-import-button";
@@ -22,6 +23,8 @@ interface Props {
}
export const CustomCssSettingsContent = ({ board }: Props) => {
const { data: session } = useSession();
const isAdmin = session?.user.permissions.includes("admin") ?? false;
const t = useI18n();
const customCssT = useScopedI18n("board.field.customCss");
const { mutate: savePartialSettings, isPending } = useSavePartialSettingsMutation(board);
@@ -48,7 +51,7 @@ export const CustomCssSettingsContent = ({ board }: Props) => {
</Alert>
<Group justify="space-between">
<WorkshopCssImportButton onImport={(css) => form.setFieldValue("customCss", css)} />
{isAdmin ? <WorkshopCssImportButton onImport={(css) => form.setFieldValue("customCss", css)} /> : <span />}
<Button type="submit" loading={isPending}>
{t("common.action.saveChanges")}
</Button>
@@ -1,5 +1,10 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { auth } from "@homarr/auth/next";
import { CustomWidgetsUnavailable } from "~/components/custom-widgets/custom-widgets-unavailable";
import { env } from "~/env";
import { CustomWidgetConfigurationEntry } from "./configuration-entry";
export const metadata: Metadata = {
@@ -8,6 +13,9 @@ export const metadata: Metadata = {
};
export default async function CustomWidgetConfigurationPage({ params }: { params: Promise<{ token: string }> }) {
const session = await auth();
if (!session?.user.permissions.includes("admin")) redirect(session ? "/" : "/auth/login");
if (env.CUSTOM_WIDGETS_ENABLED === false) return <CustomWidgetsUnavailable />;
const { token } = await params;
return <CustomWidgetConfigurationEntry token={token} />;
}
+12 -3
View File
@@ -24,7 +24,7 @@ import { SettingsProvider } from "@homarr/settings";
import { SpotlightProvider } from "@homarr/spotlight";
import type { SupportedLanguage } from "@homarr/translation";
import { isLocaleRTL, isLocaleSupported } from "@homarr/translation";
import { WORKSHOP_API_URL } from "@homarr/workshop/schema";
import { resolveHomarrUrlConfig } from "@homarr/workshop/schema";
import { Analytics } from "~/components/layout/analytics";
import { CrowdinLiveTranslation } from "~/components/layout/crowdin-live-translation";
@@ -54,7 +54,7 @@ export const generateMetadata = async (): Promise<Metadata> => ({
title: "Homarr Dashboard",
description:
"A self-hosted dashboard for the *arr stack and your entire homelab. Integrates with 50+ services, real-time widgets, no config files.",
url: "https://homarr.dev",
url: env.HOMARR_WEBSITE_URL,
siteName: "Homarr",
},
icons: {
@@ -89,6 +89,11 @@ export default async function Layout(props: {
const serverSettings = await getServerSettingsAsync(db);
const colorScheme = await getCurrentColorSchemeAsync();
const direction = isLocaleRTL((await props.params).locale) ? "rtl" : "ltr";
const publicUrls = resolveHomarrUrlConfig({
homarrWebsiteUrl: env.HOMARR_WEBSITE_URL,
workshopApiUrl: env.WORKSHOP_API_URL,
workshopWebUrl: env.WORKSHOP_WEB_URL,
});
const StackedProvider = composeWrappers([
(innerProps) => {
@@ -141,7 +146,11 @@ export default async function Layout(props: {
suppressHydrationWarning
>
<head>
<meta name="homarr-workshop-api-url" content={env.WORKSHOP_API_URL ?? WORKSHOP_API_URL} />
<meta name="homarr-website-url" content={publicUrls.homarrWebsiteUrl} />
<meta name="homarr-workshop-api-url" content={publicUrls.workshopApiUrl} />
<meta name="homarr-workshop-web-url" content={publicUrls.workshopWebUrl} />
<meta name="homarr-custom-widgets-enabled" content={String(env.CUSTOM_WIDGETS_ENABLED !== false)} />
<meta name="homarr-workshop-enabled" content={String(env.WORKSHOP_ENABLED !== false)} />
<SearchEngineOptimization />
<CrowdinLiveTranslation locale={locale} />
</head>
@@ -23,6 +23,7 @@ import { useScopedI18n } from "@homarr/translation/client";
import { CustomWidgetImportDialog } from "~/components/custom-widgets/custom-widget-import-dialog";
import { WorkshopPublishModal } from "~/components/workshop/workshop-publish-modal";
import { useRuntimeFeature } from "~/hooks/use-runtime-feature";
const iconProps = { size: 16, stroke: 1.5 };
@@ -36,9 +37,9 @@ interface WidgetRef {
export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
const t = useScopedI18n("customWidget");
const workshopEnabled = useRuntimeFeature("workshop");
const { openConfirmModal } = useConfirmModal();
const deleteMutation = clientApi.customWidget.delete.useMutation();
const deleteLegacyMutation = clientApi.customWidget.deleteLegacy.useMutation();
const duplicateMutation = clientApi.customWidget.duplicate.useMutation();
const utils = clientApi.useUtils();
const [publishOpened, publishControls] = useDisclosure(false);
@@ -146,10 +147,6 @@ export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
showErrorNotification({ title: t("action.delete"), message: t("notification.deleteError") });
},
};
if (widget.migrationRequired) {
deleteLegacyMutation.mutate({ id: widget.id }, callbacks);
return;
}
deleteMutation.mutate({ id: widget.id }, callbacks);
},
});
@@ -176,9 +173,11 @@ export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
<Menu.Item onClick={() => void handleExport()} leftSection={<IconDownload {...iconProps} />}>
{t("action.export")}
</Menu.Item>
<Menu.Item onClick={publishControls.open} leftSection={<IconBuildingStore {...iconProps} />}>
{t("action.publishWorkshop")}
</Menu.Item>
{workshopEnabled && (
<Menu.Item onClick={publishControls.open} leftSection={<IconBuildingStore {...iconProps} />}>
{t("action.publishWorkshop")}
</Menu.Item>
)}
<Menu.Divider />
</>
)}
@@ -196,17 +195,21 @@ export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
<Menu.Divider />
</>
)}
<Menu.Item
color="red"
leftSection={<IconTrash {...iconProps} />}
onClick={handleDelete}
disabled={deleteMutation.isPending || deleteLegacyMutation.isPending}
>
{t("action.delete")}
</Menu.Item>
{!widget.migrationRequired && (
<Menu.Item
color="red"
leftSection={<IconTrash {...iconProps} />}
onClick={handleDelete}
disabled={deleteMutation.isPending}
>
{t("action.delete")}
</Menu.Item>
)}
</Menu.Dropdown>
</Menu>
{widget.valid && <WorkshopPublishModal opened={publishOpened} onClose={publishControls.close} widget={widget} />}
{widget.valid && workshopEnabled && (
<WorkshopPublishModal opened={publishOpened} onClose={publishControls.close} widget={widget} />
)}
{widget.migrationRequired && (
<>
<input
@@ -5,7 +5,9 @@ import { api } from "@homarr/api/server";
import { auth } from "@homarr/auth/next";
import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
import { CustomWidgetsUnavailable } from "~/components/custom-widgets/custom-widgets-unavailable";
import { catchTrpcNotFound } from "~/errors/trpc-catch-error";
import { env } from "~/env";
import { CustomWidgetBetaBanner } from "../../_beta-banner";
import { CustomWidgetForm } from "../../_custom-widget-form";
import { FormErrorBoundary } from "../../_form-error-boundary";
@@ -16,9 +18,10 @@ interface EditCustomWidgetPageProps {
export default async function EditCustomWidgetPage(props: EditCustomWidgetPageProps) {
const session = await auth();
if (!session || !session.user.permissions.includes("custom-widget-manage")) {
if (!session || !session.user.permissions.includes("admin")) {
redirect("/manage/custom-widgets");
}
if (env.CUSTOM_WIDGETS_ENABLED === false) return <CustomWidgetsUnavailable />;
const params = await props.params;
const definition = await api.customWidget.get({ id: params.id }).catch(catchTrpcNotFound);
@@ -5,15 +5,18 @@ import { auth } from "@homarr/auth/next";
import { getScopedI18n } from "@homarr/translation/server";
import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
import { CustomWidgetsUnavailable } from "~/components/custom-widgets/custom-widgets-unavailable";
import { env } from "~/env";
import { CustomWidgetBetaBanner } from "../_beta-banner";
import { CustomWidgetForm } from "../_custom-widget-form";
import { FormErrorBoundary } from "../_form-error-boundary";
export default async function NewCustomWidgetPage() {
const session = await auth();
if (!session || !session.user.permissions.includes("custom-widget-manage")) {
if (!session || !session.user.permissions.includes("admin")) {
redirect("/manage/custom-widgets");
}
if (env.CUSTOM_WIDGETS_ENABLED === false) return <CustomWidgetsUnavailable />;
const t = await getScopedI18n("customWidget");
@@ -9,6 +9,8 @@ import { Link } from "@homarr/ui";
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
import { MobileAffixButton } from "~/components/manage/mobile-affix-button";
import { CustomWidgetsUnavailable } from "~/components/custom-widgets/custom-widgets-unavailable";
import { env } from "~/env";
import { CustomWidgetBetaBanner } from "./_beta-banner";
import { WorkshopInstallButton } from "~/components/workshop/workshop-install-button";
import { ImportCustomWidgetButton } from "./_import-custom-widget-button";
@@ -17,9 +19,10 @@ import { CustomWidgetList } from "./_custom-widget-list";
export default async function CustomWidgetsPage() {
const session = await auth();
if (!session || !session.user.permissions.includes("custom-widget-manage")) {
if (!session || !session.user.permissions.includes("admin")) {
redirect(session ? "/" : "/auth/login");
}
if (env.CUSTOM_WIDGETS_ENABLED === false) return <CustomWidgetsUnavailable />;
const definitions = await api.customWidget.list();
const t = await getScopedI18n("customWidget");
@@ -5,9 +5,13 @@ import { api } from "@homarr/api/server";
import { auth } from "@homarr/auth/next";
import CustomJsxDisplay from "@homarr/widgets/custom-api/custom-jsx-display";
import { CustomWidgetsUnavailable } from "~/components/custom-widgets/custom-widgets-unavailable";
import { env } from "~/env";
export default async function CustomWidgetPreviewPage({ params }: { params: Promise<{ id: string }> }) {
const session = await auth();
if (!session?.user.permissions.includes("custom-widget-manage")) redirect("/");
if (!session?.user.permissions.includes("admin")) redirect("/");
if (env.CUSTOM_WIDGETS_ENABLED === false) return <CustomWidgetsUnavailable />;
const { id } = await params;
const preview = await api.customWidget.previewGet({ sessionId: id }).catch(() => null);
if (!preview) notFound();
@@ -41,6 +41,7 @@ import type { NavigationLink } from "~/components/layout/navigation";
import { MainNavigation } from "~/components/layout/navigation";
import { ClientShell } from "~/components/layout/shell";
import { ManageTourProvider } from "~/components/onboarding/manage-tour";
import { env as nextEnv } from "~/env";
export default async function ManageLayout({ children }: PropsWithChildren) {
const t = await getScopedI18n("management.navbar");
@@ -79,13 +80,16 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
icon: IconApi,
href: "/manage/custom-widgets",
label: t("items.customWidgets"),
hidden: !session?.user.permissions.includes("custom-widget-manage"),
hidden: nextEnv.CUSTOM_WIDGETS_ENABLED === false || !session?.user.permissions.includes("admin"),
},
{
icon: IconBuildingStore,
href: "/manage/workshop",
label: t("items.workshop"),
hidden: !session?.user.permissions.includes("custom-widget-manage"),
hidden:
nextEnv.CUSTOM_WIDGETS_ENABLED === false ||
nextEnv.WORKSHOP_ENABLED === false ||
!session?.user.permissions.includes("admin"),
},
{
icon: IconSearch,
@@ -1,17 +1,42 @@
import { redirect } from "next/navigation";
import { Button } from "@mantine/core";
import { IconExternalLink } from "@tabler/icons-react";
import { auth } from "@homarr/auth/next";
import { getScopedI18n } from "@homarr/translation/server";
import { resolveHomarrUrlConfig } from "@homarr/workshop/schema";
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
import { WorkshopInstaller } from "~/components/workshop/workshop-installer";
import { env } from "~/env";
export default async function WorkshopPage() {
const session = await auth();
if (!session?.user.permissions.includes("custom-widget-manage")) redirect(session ? "/" : "/auth/login");
if (!session?.user.permissions.includes("admin")) redirect(session ? "/" : "/auth/login");
if (env.CUSTOM_WIDGETS_ENABLED === false || env.WORKSHOP_ENABLED === false) redirect("/");
const t = await getScopedI18n("workshop");
const { workshopWebUrl } = resolveHomarrUrlConfig({
homarrWebsiteUrl: env.HOMARR_WEBSITE_URL,
workshopApiUrl: env.WORKSHOP_API_URL,
workshopWebUrl: env.WORKSHOP_WEB_URL,
});
return (
<ManagePageLayout title={t("title")} size="xl">
<ManagePageLayout
title={t("title")}
size="xl"
primaryAction={
<Button
component="a"
href={workshopWebUrl}
target="_blank"
rel="noopener noreferrer"
variant="default"
leftSection={<IconExternalLink size={16} />}
>
{t("openCommunity")}
</Button>
}
>
<WorkshopInstaller />
</ManagePageLayout>
);
+2 -2
View File
@@ -5,7 +5,7 @@ import { createOpenApiFetchHandler } from "trpc-to-openapi";
import { createTRPCContext } from "@homarr/api";
import { openApiRouter } from "@homarr/api/open-api";
import { API_KEY_HEADER_NAME, getSessionFromApiKeyAsync } from "@homarr/auth/api-key";
import { ipAddressFromHeaders } from "@homarr/common/server";
import { rateLimitAddressFromHeaders } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import { db } from "@homarr/db";
@@ -14,7 +14,7 @@ const logger = createLogger({ module: "trpcOpenApiRoute" });
const handlerAsync = async (req: NextRequest) => {
const apiKeyHeaderValue = req.headers.get(API_KEY_HEADER_NAME);
const ipAddress = ipAddressFromHeaders(req.headers);
const ipAddress = rateLimitAddressFromHeaders(req.headers);
const { ua } = userAgent(req);
logger.info(
@@ -0,0 +1,40 @@
// @vitest-environment node
import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
auth: vi.fn(),
env: { CUSTOM_WIDGETS_ENABLED: true },
}));
vi.mock("@homarr/auth/next", () => ({ auth: mocks.auth }));
vi.mock("~/env", () => ({ env: mocks.env }));
import { requireCustomWidgetAdmin } from "./admin";
beforeEach(() => {
mocks.env.CUSTOM_WIDGETS_ENABLED = true;
mocks.auth.mockResolvedValue({ user: { permissions: ["admin"] } });
});
describe("Custom Widget HTTP resource access", () => {
test("allows authenticated administrators", async () => {
await expect(requireCustomWidgetAdmin()).resolves.toBeNull();
});
test.each([
["anonymous users", null],
["authenticated non-admins", { user: { permissions: ["board-modify-all"] } }],
])("denies %s", async (_label, session) => {
mocks.auth.mockResolvedValue(session);
const response = await requireCustomWidgetAdmin();
expect(response?.status).toBe(403);
});
test("returns an unavailable response when the emergency switch is off", async () => {
mocks.env.CUSTOM_WIDGETS_ENABLED = false;
const response = await requireCustomWidgetAdmin();
expect(response?.status).toBe(503);
await expect(response?.json()).resolves.toMatchObject({ error: expect.stringContaining("temporarily disabled") });
});
});
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { auth } from "@homarr/auth/next";
import { env } from "~/env";
export const requireCustomWidgetAdmin = async (): Promise<NextResponse | null> => {
const session = await auth();
if (!session?.user.permissions.includes("admin")) {
return NextResponse.json({ error: "Administrator access is required." }, { status: 403 });
}
if (env.CUSTOM_WIDGETS_ENABLED === false) {
return NextResponse.json(
{ error: "Custom Widgets are temporarily disabled by the server administrator." },
{ status: 503 },
);
}
return null;
};
@@ -2,9 +2,11 @@ import { NextResponse } from "next/server";
import { CUSTOM_WIDGET_MCP_AUTHORING_PROMPT } from "@homarr/custom-widgets/authoring-prompt";
export const dynamic = "force-static";
import { requireCustomWidgetAdmin } from "../admin";
export function GET() {
export async function GET() {
const denied = await requireCustomWidgetAdmin();
if (denied) return denied;
return NextResponse.json({
version: 2,
prompt: CUSTOM_WIDGET_MCP_AUTHORING_PROMPT,
@@ -2,8 +2,10 @@ import { NextResponse } from "next/server";
import { getCustomWidgetComponentCatalog } from "@homarr/custom-widgets/authoring-resources";
export const dynamic = "force-static";
import { requireCustomWidgetAdmin } from "../admin";
export function GET() {
export async function GET() {
const denied = await requireCustomWidgetAdmin();
if (denied) return denied;
return NextResponse.json(getCustomWidgetComponentCatalog());
}
@@ -6,16 +6,17 @@ import {
completeCustomWidgetConfigurationRequest,
configurePreviewSessionSource,
getCustomWidgetConfigurationRequest,
invalidateCustomWidgetResponseCache,
parseStoredCustomWidgetDefinition,
releaseCustomWidgetConfigurationRequest,
serializeCustomWidgetDefinition,
} from "@homarr/api/custom-widget-configuration";
import { encryptSecret } from "@homarr/common/server";
import { invalidateCustomWidgetResponseCache } from "@homarr/custom-widgets/server";
import { customWidgetSourceSchema, hasSameCustomWidgetSourceAuthentication } from "@homarr/custom-widgets/core";
import { and, db, eq, handleTransactionsAsync } from "@homarr/db";
import { customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
import { requireCustomWidgetAdmin } from "../../admin";
import { readConfigurationRequestBody } from "../body";
interface RouteContext {
@@ -23,6 +24,8 @@ interface RouteContext {
}
export async function GET(_request: NextRequest, context: RouteContext) {
const denied = await requireCustomWidgetAdmin();
if (denied) return denied;
const { token } = await context.params;
const request = await getCustomWidgetConfigurationRequest(token);
if (!request)
@@ -41,6 +44,8 @@ export async function GET(_request: NextRequest, context: RouteContext) {
}
export async function POST(request: NextRequest, context: RouteContext) {
const denied = await requireCustomWidgetAdmin();
if (denied) return denied;
const { token } = await context.params;
const pending = await getCustomWidgetConfigurationRequest(token);
if (!pending || pending.status !== "pending") {
@@ -92,7 +97,7 @@ export async function POST(request: NextRequest, context: RouteContext) {
sourceResult.data,
secrets,
);
invalidateCustomWidgetResponseCache([`custom-jsx:preview:${claimed.target.id}:`]);
await invalidateCustomWidgetResponseCache([`custom-jsx:preview:${claimed.target.id}:`]);
} else {
const definition = await db.query.customWidgetDefinitions.findFirst({
where: eq(customWidgetDefinitions.id, claimed.target.id),
@@ -2,8 +2,10 @@ import { NextResponse } from "next/server";
import { getCustomWidgetJsonSchema } from "@homarr/custom-widgets/core";
export const dynamic = "force-static";
import { requireCustomWidgetAdmin } from "../admin";
export function GET() {
export async function GET() {
const denied = await requireCustomWidgetAdmin();
if (denied) return denied;
return NextResponse.json(getCustomWidgetJsonSchema());
}
@@ -2,8 +2,10 @@ import { NextResponse } from "next/server";
import { getCustomWidgetSkill } from "@homarr/custom-widgets/authoring-resources";
export const dynamic = "force-static";
import { requireCustomWidgetAdmin } from "../admin";
export function GET() {
export async function GET() {
const denied = await requireCustomWidgetAdmin();
if (denied) return denied;
return NextResponse.json(getCustomWidgetSkill());
}
@@ -4,6 +4,10 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
authenticate: vi.fn(),
rateLimitAddress: vi.fn(() => "127.0.0.1"),
toolProcedure: vi.fn(),
loggerWarn: vi.fn(),
env: { CUSTOM_WIDGETS_ENABLED: true, WORKSHOP_ENABLED: true },
buildPrompt: vi.fn((request?: string, documentationUrl?: string) =>
[`Request: ${request ?? ""}`, `Documentation: ${documentationUrl ?? ""}`].join("\n"),
),
@@ -13,16 +17,16 @@ const mocks = vi.hoisted(() => ({
vi.mock("next/server", () => ({ userAgent: () => ({ ua: "MCP route test" }) }));
vi.mock("@homarr/api/mcp", () => ({
createTRPCContext: vi.fn(() => ({})),
mcpRouter: { createCaller: vi.fn(() => ({})) },
mcpRouter: { createCaller: vi.fn(() => ({ board: { getAllBoards: mocks.toolProcedure } })) },
}));
vi.mock("@homarr/auth/api-key", () => ({
API_KEY_HEADER_NAME: "ApiKey",
getSessionFromApiKeyAsync: mocks.authenticate,
}));
vi.mock("@homarr/common", () => ({ extractBaseUrlFromHeaders: () => "http://localhost" }));
vi.mock("@homarr/common/server", () => ({ ipAddressFromHeaders: () => "127.0.0.1" }));
vi.mock("@homarr/common/server", () => ({ rateLimitAddressFromHeaders: mocks.rateLimitAddress }));
vi.mock("@homarr/core/infrastructure/logs", () => ({
createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
createLogger: () => ({ info: vi.fn(), warn: mocks.loggerWarn, error: vi.fn() }),
}));
vi.mock("@homarr/custom-widgets/authoring-prompt", () => ({ buildCustomWidgetMcpPrompt: mocks.buildPrompt }));
vi.mock("@homarr/custom-widgets/authoring-resources", () => ({
@@ -35,8 +39,30 @@ vi.mock("@homarr/custom-widgets/core", () => ({
getCustomWidgetJsonSchema: () => ({ type: "object", title: "Custom Widget" }),
}));
vi.mock("@homarr/db", () => ({ db: {} }));
vi.mock("~/env", () => ({ env: mocks.env }));
vi.mock("~/versions/package-reader", () => ({ getPackageVersion: () => "test-version" }));
vi.mock("../_extract-tools", () => ({ extractMcpTools: () => [] }));
vi.mock("../_extract-tools", () => ({
extractMcpTools: () => [
{
name: "board_getAllBoards",
description: "List boards",
pathInRouter: ["board", "getAllBoards"],
inputSchema: { type: "object", properties: {} },
},
{
name: "customWidget_list",
description: "List Custom Widgets",
pathInRouter: ["customWidget", "list"],
inputSchema: { type: "object", properties: {} },
},
{
name: "customWidget_workshopSearch",
description: "Search Workshop",
pathInRouter: ["customWidget", "workshopSearch"],
inputSchema: { type: "object", properties: {} },
},
],
}));
import { POST } from "./route";
@@ -48,9 +74,16 @@ interface JsonRpcResponse {
}
beforeEach(() => {
mocks.authenticate.mockResolvedValue({ user: { id: "user-1" } });
mocks.authenticate.mockResolvedValue({ user: { id: "user-1", permissions: ["admin"] } });
mocks.env.CUSTOM_WIDGETS_ENABLED = true;
mocks.env.WORKSHOP_ENABLED = true;
mocks.buildPrompt.mockClear();
mocks.getComponent.mockClear();
mocks.rateLimitAddress.mockClear();
mocks.rateLimitAddress.mockReturnValue("127.0.0.1");
mocks.toolProcedure.mockReset();
mocks.toolProcedure.mockResolvedValue([]);
mocks.loggerWarn.mockClear();
});
async function callMcp(method: string, params: Record<string, unknown> = {}, id = 1) {
@@ -60,6 +93,8 @@ async function callMcp(method: string, params: Record<string, unknown> = {}, id
Accept: "application/json, text/event-stream",
ApiKey: "key.secret",
"Content-Type": "application/json",
"X-Forwarded-For": "198.51.100.10",
"X-Real-IP": "127.0.0.1",
},
body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
});
@@ -91,6 +126,7 @@ describe("authenticated MCP prompt protocol", () => {
serverInfo: { name: "homarr", version: "test-version" },
});
expect(mocks.authenticate).toHaveBeenCalledWith({}, "key.secret", "127.0.0.1", "MCP route test");
expect(mocks.rateLimitAddress).toHaveBeenCalledWith(expect.any(Headers));
});
test("lists and interpolates the custom-widget authoring prompt", async () => {
@@ -178,6 +214,55 @@ describe("authenticated MCP resource protocol", () => {
});
});
describe("non-admin MCP discovery", () => {
test("does not list or expose Custom Widget tools, prompts or resources", async () => {
mocks.authenticate.mockResolvedValue({ user: { id: "user-1", permissions: ["board-view-all"] } });
const tools = await callMcp("tools/list");
expect(((tools.body.result?.tools ?? []) as Array<{ name: string }>).map(({ name }) => name)).toEqual([
"board_getAllBoards",
]);
const prompts = await callMcp("prompts/list");
expect(prompts.body.result).toEqual({ prompts: [] });
const resources = await callMcp("resources/list");
expect(resources.body.result).toEqual({ resources: [] });
const templates = await callMcp("resources/templates/list");
expect(templates.body.result).toEqual({ resourceTemplates: [] });
const prompt = await callMcp("prompts/get", { name: "homarr-custom-widget-author" });
expect(prompt.body.result).toBeUndefined();
expect(prompt.body.error).toBeDefined();
const resource = await callMcp("resources/read", { uri: "homarr://custom-widgets/schema" });
expect(resource.body.result).toBeUndefined();
expect(resource.body.error).toBeDefined();
});
});
describe("MCP emergency switches", () => {
test("removes Custom Widget authoring discovery when Custom Widgets are disabled", async () => {
mocks.env.CUSTOM_WIDGETS_ENABLED = false;
expect((await callMcp("prompts/list")).body.result).toEqual({ prompts: [] });
expect((await callMcp("resources/list")).body.result).toEqual({ resources: [] });
const tools = await callMcp("tools/list");
expect(((tools.body.result?.tools ?? []) as Array<{ name: string }>).map(({ name }) => name)).toEqual([
"board_getAllBoards",
]);
});
test("removes only Workshop tools when Workshop is disabled", async () => {
mocks.env.WORKSHOP_ENABLED = false;
const tools = await callMcp("tools/list");
expect(((tools.body.result?.tools ?? []) as Array<{ name: string }>).map(({ name }) => name)).toEqual([
"board_getAllBoards",
"customWidget_list",
]);
});
});
describe("MCP protocol errors", () => {
test.each([
["prompts/get", { name: "unknown" }],
@@ -193,4 +278,23 @@ describe("MCP protocol errors", () => {
expect(body.result).toBeUndefined();
expect(body.error).toEqual(expect.objectContaining({ code: -32603, message: expect.any(String) }));
});
test("does not log sensitive tool error messages", async () => {
const failure = Object.assign(new Error("request to https://user:secret@example.test/private failed"), {
code: "BAD_GATEWAY",
});
mocks.toolProcedure.mockRejectedValue(failure);
const { body } = await callMcp("tools/call", { name: "board_getAllBoards", arguments: {} });
expect(JSON.stringify(body)).not.toContain("user:secret");
expect(mocks.loggerWarn).toHaveBeenCalledWith("MCP tool execution failed", {
tool: "board_getAllBoards",
errorName: "Error",
errorCode: "BAD_GATEWAY",
});
const metadata = mocks.loggerWarn.mock.calls.at(-1)?.[1] as Record<string, unknown>;
expect(metadata).not.toHaveProperty("error");
expect(metadata).not.toHaveProperty("message");
});
});
@@ -16,7 +16,7 @@ import {
import { createTRPCContext, mcpRouter } from "@homarr/api/mcp";
import { API_KEY_HEADER_NAME, getSessionFromApiKeyAsync } from "@homarr/auth/api-key";
import { extractBaseUrlFromHeaders } from "@homarr/common";
import { ipAddressFromHeaders } from "@homarr/common/server";
import { rateLimitAddressFromHeaders } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { buildCustomWidgetMcpPrompt } from "@homarr/custom-widgets/authoring-prompt";
import {
@@ -27,6 +27,7 @@ import {
import { customJsxExamples, getCustomWidgetJsonSchema } from "@homarr/custom-widgets/core";
import { db } from "@homarr/db";
import { env } from "~/env";
import { getPackageVersion } from "~/versions/package-reader";
import { extractMcpTools } from "../_extract-tools";
@@ -85,7 +86,12 @@ function clearAuthFailures(ip: string | null) {
authFailures.delete(ip ?? "unknown");
}
const callerStorage = new AsyncLocalStorage<ReturnType<typeof mcpRouter.createCaller>>();
interface McpCallerContext {
caller: ReturnType<typeof mcpRouter.createCaller>;
isAdmin: boolean;
}
const callerStorage = new AsyncLocalStorage<McpCallerContext>();
const emptyObjectSchema = {
type: "object" as const,
@@ -113,6 +119,23 @@ function getTools() {
return toolsCache;
}
function getVisibleTools() {
const tools = getTools();
if (!isCustomWidgetMcpEnabled()) {
return tools.filter((tool) => !tool.name.startsWith("customWidget_"));
}
return env.WORKSHOP_ENABLED === false
? tools.filter((tool) => !tool.name.startsWith("customWidget_workshop"))
: tools;
}
function requireCustomWidgetMcpAdmin() {
if (!isCustomWidgetMcpEnabled()) throw new Error("Resource not found");
}
const isCustomWidgetMcpEnabled = () =>
Boolean(callerStorage.getStore()?.isAdmin) && env.CUSTOM_WIDGETS_ENABLED !== false;
const SAFE_ERROR_MESSAGES: Record<string, string> = {
UNAUTHORIZED: "You do not have permission to perform this action",
FORBIDDEN: "Access denied",
@@ -184,19 +207,22 @@ If \`hasUseAccess\` is false, the API key owner lacks permission for that integr
const mcpHandler = createMcpHandler(
(server) => {
server.server.setRequestHandler(ListPromptsRequestSchema, () => ({
prompts: [
{
name: "homarr-custom-widget-author",
description: "Author and iterate on one Homarr Custom JSX v2 widget.",
arguments: [
{ name: "request", description: "The widget the user wants.", required: false },
{ name: "documentationUrl", description: "External API documentation URL.", required: false },
],
},
],
prompts: isCustomWidgetMcpEnabled()
? [
{
name: "homarr-custom-widget-author",
description: "Author and iterate on one Homarr Custom JSX v2 widget.",
arguments: [
{ name: "request", description: "The widget the user wants.", required: false },
{ name: "documentationUrl", description: "External API documentation URL.", required: false },
],
},
]
: [],
}));
server.server.setRequestHandler(GetPromptRequestSchema, (request) => {
requireCustomWidgetMcpAdmin();
if (request.params.name !== "homarr-custom-widget-author") throw new Error("Prompt not found");
return {
description: "Current Homarr Custom Widget authoring workflow.",
@@ -216,36 +242,49 @@ const mcpHandler = createMcpHandler(
});
server.server.setRequestHandler(ListResourcesRequestSchema, () => ({
resources: [
{ uri: "homarr://custom-widgets/schema", name: "Custom Widget schema", mimeType: "application/schema+json" },
{ uri: "homarr://custom-widgets/components", name: "Custom Widget components", mimeType: "application/json" },
{ uri: "homarr://custom-widgets/skill", name: "Custom Widget skill", mimeType: "text/markdown" },
...customJsxExamples.map((example) => ({
uri: `homarr://custom-widgets/examples/${example.id}`,
name: `Custom Widget example: ${example.title}`,
mimeType: "application/json",
})),
],
resources: isCustomWidgetMcpEnabled()
? [
{
uri: "homarr://custom-widgets/schema",
name: "Custom Widget schema",
mimeType: "application/schema+json",
},
{
uri: "homarr://custom-widgets/components",
name: "Custom Widget components",
mimeType: "application/json",
},
{ uri: "homarr://custom-widgets/skill", name: "Custom Widget skill", mimeType: "text/markdown" },
...customJsxExamples.map((example) => ({
uri: `homarr://custom-widgets/examples/${example.id}`,
name: `Custom Widget example: ${example.title}`,
mimeType: "application/json",
})),
]
: [],
}));
server.server.setRequestHandler(ListResourceTemplatesRequestSchema, () => ({
resourceTemplates: [
{
uriTemplate: "homarr://custom-widgets/components/{name}",
name: "Custom Widget component",
description: "Metadata for one installed Custom Widget component.",
mimeType: "application/json",
},
{
uriTemplate: "homarr://custom-widgets/examples/{name}",
name: "Custom Widget example",
description: "One canonical Custom Widget example.",
mimeType: "application/json",
},
],
resourceTemplates: isCustomWidgetMcpEnabled()
? [
{
uriTemplate: "homarr://custom-widgets/components/{name}",
name: "Custom Widget component",
description: "Metadata for one installed Custom Widget component.",
mimeType: "application/json",
},
{
uriTemplate: "homarr://custom-widgets/examples/{name}",
name: "Custom Widget example",
description: "One canonical Custom Widget example.",
mimeType: "application/json",
},
]
: [],
}));
server.server.setRequestHandler(ReadResourceRequestSchema, (request) => {
requireCustomWidgetMcpAdmin();
const { uri } = request.params;
let text: string;
let mimeType = "application/json";
@@ -271,12 +310,12 @@ const mcpHandler = createMcpHandler(
});
server.server.setRequestHandler(ListToolsRequestSchema, () => ({
tools: getTools(),
tools: getVisibleTools(),
}));
server.server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
const tools = getTools();
const tools = getVisibleTools();
const tool = tools.find((t) => t.name === name);
if (!tool) {
@@ -286,8 +325,8 @@ const mcpHandler = createMcpHandler(
};
}
const caller = callerStorage.getStore();
if (!caller) {
const callerContext = callerStorage.getStore();
if (!callerContext) {
return {
content: [{ type: "text" as const, text: "Authentication context not available" }],
isError: true,
@@ -295,7 +334,7 @@ const mcpHandler = createMcpHandler(
}
try {
const procedure = tool.pathInRouter.reduce<any>((acc, part) => acc?.[part], caller);
const procedure = tool.pathInRouter.reduce<any>((acc, part) => acc?.[part], callerContext.caller);
if (typeof procedure !== "function") {
return {
content: [{ type: "text" as const, text: `Tool "${name}" is not callable` }],
@@ -311,7 +350,9 @@ const mcpHandler = createMcpHandler(
const message = sanitizeErrorMessage(error);
logger.warn("MCP tool execution failed", {
tool: name,
error: error instanceof Error ? error.message : String(error),
errorName: error instanceof Error ? error.name : "UnknownError",
errorCode:
error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : undefined,
});
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: message }) }],
@@ -353,7 +394,7 @@ function jsonErrorResponse(status: number, body: Record<string, string>, extraHe
const handler = async (req: NextRequest) => {
const apiKeyValue = extractApiKeyValue(req);
const ipAddress = ipAddressFromHeaders(req.headers);
const ipAddress = rateLimitAddressFromHeaders(req.headers);
const { ua } = userAgent(req);
if (!checkAuthRateLimit(ipAddress)) {
@@ -398,7 +439,9 @@ const handler = async (req: NextRequest) => {
const ctx = createTRPCContext({ session, headers: req.headers });
const caller = mcpRouter.createCaller(ctx);
return callerStorage.run(caller, () => mcpHandler(req as unknown as Request));
return callerStorage.run({ caller, isAdmin: session.user.permissions.includes("admin") }, () =>
mcpHandler(req as unknown as Request),
);
};
export { handler as GET, handler as POST, handler as DELETE };
+2 -2
View File
@@ -5,7 +5,7 @@ import { appRouter, createTRPCContext } from "@homarr/api";
import { trpcPath } from "@homarr/api/shared";
import { API_KEY_HEADER_NAME, getSessionFromApiKeyAsync } from "@homarr/auth/api-key";
import { auth } from "@homarr/auth/next";
import { ipAddressFromHeaders } from "@homarr/common/server";
import { rateLimitAddressFromHeaders } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import { db } from "@homarr/db";
@@ -34,7 +34,7 @@ export function OPTIONS() {
const handler = auth(async (req) => {
// Try API key auth first, fall back to session cookie
const apiKeyHeader = req.headers.get(API_KEY_HEADER_NAME);
const ipAddress = ipAddressFromHeaders(req.headers);
const ipAddress = rateLimitAddressFromHeaders(req.headers);
const { ua } = userAgent(req);
@@ -30,6 +30,8 @@ export const BoardItemMenu = (props: BoardItemMenuProps) => {
};
const BoardItemMenuInner = ({ offset, item, resetErrorBoundary }: BoardItemMenuProps) => {
const { data: session } = useSession();
const canDuplicate = item.kind !== "customApi" || (session?.user.permissions.includes("admin") ?? false);
const refResetErrorBoundaryOnNextRender = useRef(false);
const tItem = useScopedI18n("item");
const t = useI18n();
@@ -135,9 +137,11 @@ const BoardItemMenuInner = ({ offset, item, resetErrorBoundary }: BoardItemMenuP
>
{tItem("action.moveResize")}
</Menu.Item>
<Menu.Item leftSection={<IconCopy size={16} />} onClick={() => duplicateItem({ itemId: item.id })}>
{tItem("action.duplicate")}
</Menu.Item>
{canDuplicate && (
<Menu.Item leftSection={<IconCopy size={16} />} onClick={() => duplicateItem({ itemId: item.id })}>
{tItem("action.duplicate")}
</Menu.Item>
)}
<Menu.Divider />
<Menu.Label c="red.6">{t("common.dangerZone")}</Menu.Label>
<Menu.Item c="red.6" leftSection={<IconTrash size={16} />} onClick={openRemoveModal}>
@@ -3,6 +3,7 @@ import { Avatar, Box, Button, Card, Center, Divider, Group, Image, Stack, Text,
import { IconApi } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client";
import { createId, objectEntries } from "@homarr/common";
import { getIconUrl, getIntegrationName } from "@homarr/definitions";
import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
@@ -15,15 +16,23 @@ import { reduceWidgetOptionsWithDefaultValues, widgetImports } from "@homarr/wid
import { WidgetEditModal } from "@homarr/widgets/modals";
import { WorkshopInstallButton } from "~/components/workshop/workshop-install-button";
import { useRuntimeFeature } from "~/hooks/use-runtime-feature";
import { useItemActions } from "./item-actions";
export const ItemSelectModal = createModal<{ boardId: string }>(({ actions, innerProps }) => {
const { data: session } = useSession();
const isAdmin = session?.user.permissions.includes("admin") ?? false;
const customWidgetsEnabled = useRuntimeFeature("custom-widgets");
const workshopEnabled = useRuntimeFeature("workshop");
const [search, setSearch] = useState("");
const t = useI18n();
const { createItem, updateItemOptions, updateItemAdvancedOptions, updateItemIntegrations } = useItemActions();
const { openModal: openEditModal } = useModalAction(WidgetEditModal);
const { data: integrationData } = clientApi.integration.all.useQuery();
const { data: customWidgetDefs } = clientApi.customWidget.available.useQuery({ boardId: innerProps.boardId });
const { data: customWidgetDefs } = clientApi.customWidget.available.useQuery(
{ boardId: innerProps.boardId },
{ enabled: isAdmin && customWidgetsEnabled },
);
const settings = useSettings();
const availableKinds = useMemo(() => new Set((integrationData ?? []).map((i) => i.kind)), [integrationData]);
@@ -160,61 +169,67 @@ export const ItemSelectModal = createModal<{ boardId: string }>(({ actions, inne
/>
))}
<Divider
label={t("customWidget.page.list.title")}
labelPosition="center"
my="sm"
style={{ gridColumn: "1 / -1" }}
/>
{filteredCustomWidgets.map((def) => (
<Card
key={def.id}
h={selectGridCardHeight}
withBorder
pos="relative"
style={{ overflow: "hidden", "--_hover-opacity": "0" }}
onMouseEnter={(e) => e.currentTarget.style.setProperty("--_hover-opacity", "1")}
onMouseLeave={(e) => e.currentTarget.style.setProperty("--_hover-opacity", "0")}
>
<Stack h="100%" gap="xs">
<Group gap="sm" wrap="nowrap" align="flex-start">
{def.iconUrl ? (
<Image src={def.iconUrl} w={22} h={22} fit="contain" style={{ flexShrink: 0, marginTop: 2 }} />
) : (
<IconApi size={22} style={{ flexShrink: 0, marginTop: 2 }} />
)}
<Text lh={1.2} style={{ whiteSpace: "normal" }} fw={500} size="sm" lineClamp={2}>
{def.name}
</Text>
</Group>
<Text lh={1.2} style={{ whiteSpace: "normal" }} size="xs" c="dimmed" lineClamp={1}>
{def.description ?? ""}
</Text>
</Stack>
<Box
pos="absolute"
bottom={0}
left={0}
right={0}
p="xs"
style={{
opacity: "var(--_hover-opacity)",
transition: "opacity 150ms ease",
background: "linear-gradient(transparent, var(--mantine-color-body) 30%)",
}}
>
<Button onClick={() => handleAddCustomWidget(def)} variant="light" size="xs" fullWidth>
{t("item.create.addToBoard")}
</Button>
</Box>
</Card>
))}
{isAdmin && customWidgetsEnabled && (
<>
<Divider
label={t("customWidget.page.list.title")}
labelPosition="center"
my="sm"
style={{ gridColumn: "1 / -1" }}
/>
{filteredCustomWidgets.map((def) => (
<Card
key={def.id}
h={selectGridCardHeight}
withBorder
pos="relative"
style={{ overflow: "hidden", "--_hover-opacity": "0" }}
onMouseEnter={(e) => e.currentTarget.style.setProperty("--_hover-opacity", "1")}
onMouseLeave={(e) => e.currentTarget.style.setProperty("--_hover-opacity", "0")}
>
<Stack h="100%" gap="xs">
<Group gap="sm" wrap="nowrap" align="flex-start">
{def.iconUrl ? (
<Image src={def.iconUrl} w={22} h={22} fit="contain" style={{ flexShrink: 0, marginTop: 2 }} />
) : (
<IconApi size={22} style={{ flexShrink: 0, marginTop: 2 }} />
)}
<Text lh={1.2} style={{ whiteSpace: "normal" }} fw={500} size="sm" lineClamp={2}>
{def.name}
</Text>
</Group>
<Text lh={1.2} style={{ whiteSpace: "normal" }} size="xs" c="dimmed" lineClamp={1}>
{def.description ?? ""}
</Text>
</Stack>
<Box
pos="absolute"
bottom={0}
left={0}
right={0}
p="xs"
style={{
opacity: "var(--_hover-opacity)",
transition: "opacity 150ms ease",
background: "linear-gradient(transparent, var(--mantine-color-body) 30%)",
}}
>
<Button onClick={() => handleAddCustomWidget(def)} variant="light" size="xs" fullWidth>
{t("item.create.addToBoard")}
</Button>
</Box>
</Card>
))}
<Box style={{ gridColumn: "1 / -1" }}>
<WorkshopInstallButton fullWidth>{t("workshop.installDialog")}</WorkshopInstallButton>
</Box>
{workshopEnabled && (
<Box style={{ gridColumn: "1 / -1" }}>
<WorkshopInstallButton fullWidth>{t("workshop.installDialog")}</WorkshopInstallButton>
</Box>
)}
</>
)}
{filteredItems.length === 0 && filteredCustomWidgets.length === 0 && (
{filteredItems.length === 0 && (!isAdmin || !customWidgetsEnabled || filteredCustomWidgets.length === 0) && (
<Center p="xl">
<Text c="dimmed">{t("common.noResults")}</Text>
</Center>
@@ -49,6 +49,7 @@ export const WidgetContextMenu = ({ item, widgetStateRef, children }: WidgetCont
const t = useI18n();
const settings = useSettings();
const isRightClickEnabled = settings.enableRightClickOnWidgets;
const canConfigureWidget = item.kind !== "customApi" || (session?.user.permissions.includes("admin") ?? false);
const { openModal } = useModalAction(WidgetEditModal);
const { openModal: openMoveModal } = useModalAction(ItemMoveModal);
const { openConfirmModal } = useConfirmModal();
@@ -76,9 +77,10 @@ export const WidgetContextMenu = ({ item, widgetStateRef, children }: WidgetCont
type OptionDef = { type: string; skipContextMenu?: boolean };
const toggleOptions = useMemo(() => {
if (!canConfigureWidget) return [];
const rawOptions = currentDefinition.createOptions(settings) as unknown as Record<string, OptionDef>;
return Object.entries(rawOptions).filter(([, def]) => def.type === "switch" && !def.skipContextMenu);
}, [currentDefinition, settings]);
}, [canConfigureWidget, currentDefinition, settings]);
const widgetContextActions = useMemo(() => {
const def = currentDefinition as Record<string, unknown>;
@@ -227,13 +229,15 @@ export const WidgetContextMenu = ({ item, widgetStateRef, children }: WidgetCont
>
{tItem("action.moveResize")}
</Menu.Item>
<Menu.Item
closeMenuOnClick
leftSection={<IconCopy size={16} />}
onClick={() => duplicateItem({ itemId: item.id })}
>
{tItem("action.duplicate")}
</Menu.Item>
{canConfigureWidget && (
<Menu.Item
closeMenuOnClick
leftSection={<IconCopy size={16} />}
onClick={() => duplicateItem({ itemId: item.id })}
>
{tItem("action.duplicate")}
</Menu.Item>
)}
</>
)}
@@ -0,0 +1,16 @@
import { Alert, Container } from "@mantine/core";
import { IconAlertTriangle } from "@tabler/icons-react";
import { getScopedI18n } from "@homarr/translation/server";
export async function CustomWidgetsUnavailable() {
const t = await getScopedI18n("customWidget.page.disabled");
return (
<Container size="sm" py="xl">
<Alert color="yellow" icon={<IconAlertTriangle size={18} />} title={t("title")}>
{t("message")}
</Alert>
</Container>
);
}
@@ -5,10 +5,14 @@ import { Button, Modal } from "@mantine/core";
import { IconDownload } from "@tabler/icons-react";
import { WorkshopBrowser } from "./workshop-browser";
import { useRuntimeFeature } from "~/hooks/use-runtime-feature";
export function WorkshopCssImportButton({ onImport }: { onImport(css: string): void }) {
const workshopEnabled = useRuntimeFeature("workshop");
const [opened, setOpened] = useState(false);
if (!workshopEnabled) return null;
return (
<>
<Button type="button" variant="light" leftSection={<IconDownload size={16} />} onClick={() => setOpened(true)}>
@@ -9,6 +9,7 @@ import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
import { useScopedI18n } from "@homarr/translation/client";
import { CustomWidgetImportDialog } from "~/components/custom-widgets/custom-widget-import-dialog";
import { useRuntimeFeature } from "~/hooks/use-runtime-feature";
import { WorkshopBrowser } from "./workshop-browser";
interface WorkshopInstallButtonProps {
@@ -17,6 +18,7 @@ interface WorkshopInstallButtonProps {
}
export function WorkshopInstallButton({ children, fullWidth }: WorkshopInstallButtonProps = {}) {
const workshopEnabled = useRuntimeFeature("workshop");
const t = useScopedI18n("workshop");
const stack = useModalsStack(["workshop", "review"]);
const [pendingWidget, setPendingWidget] = useState<HomarrCustomWidgetV2 | null>(null);
@@ -27,6 +29,8 @@ export function WorkshopInstallButton({ children, fullWidth }: WorkshopInstallBu
setPendingWidget(null);
};
if (!workshopEnabled) return null;
return (
<>
<Button
@@ -10,6 +10,7 @@ import type { WorkshopUser } from "@homarr/workshop/schema";
import { useScopedI18n } from "@homarr/translation/client";
import { createWorkshopClient } from "./workshop-client";
import { useRuntimeFeature } from "~/hooks/use-runtime-feature";
import {
getPrivateWorkshopSourceNames,
publishWorkshopDefinition,
@@ -25,6 +26,7 @@ export function WorkshopPublishModal({
onClose(): void;
widget: { id: string; name: string };
}) {
const workshopEnabled = useRuntimeFeature("workshop");
const t = useScopedI18n("workshop");
const client = useMemo(createWorkshopClient, []);
const [user, setUser] = useState<WorkshopUser | null>(null);
@@ -35,15 +37,16 @@ export function WorkshopPublishModal({
const [error, setError] = useState<string | null>(null);
const [published, setPublished] = useState(false);
const [sourceUrlsReviewed, setSourceUrlsReviewed] = useState(false);
const definition = clientApi.customWidget.export.useQuery({ id: widget.id }, { enabled: opened });
const definition = clientApi.customWidget.export.useQuery({ id: widget.id }, { enabled: opened && workshopEnabled });
const privateSourceNames = getPrivateWorkshopSourceNames(definition.data);
const definitionFingerprint = definition.data ? serializeWorkshopDefinition(definition.data) : null;
useEffect(() => {
if (!workshopEnabled) return;
const unsubscribe = client.subscribeToAuth(setUser);
void client.refreshAuth().then(setUser);
return unsubscribe;
}, [client]);
}, [client, workshopEnabled]);
useEffect(() => {
if (!opened) return;
setTitle(widget.name);
@@ -86,6 +89,8 @@ export function WorkshopPublishModal({
}
};
if (!workshopEnabled) return null;
return (
<Modal opened={opened} onClose={onClose} title={t("publish.title")} size="lg">
<Stack>
+19 -1
View File
@@ -1,13 +1,31 @@
import { z } from "zod/v4";
import { createBooleanSchema, createEnv } from "@homarr/core/infrastructure/env";
import { normalizeHttpUrl } from "@homarr/workshop/schema";
const publicHttpUrl = (variableName: string) =>
z.string().transform((value, context) => {
try {
return normalizeHttpUrl(value, variableName);
} catch (error) {
context.addIssue({
code: "custom",
message: error instanceof Error ? error.message : `${variableName} is invalid`,
});
return z.NEVER;
}
});
export const env = createEnv({
server: {
UNSAFE_ENABLE_MOCK_INTEGRATION: createBooleanSchema(false),
DEMO_MODE: createBooleanSchema(false),
DEMO_READ_ONLY: createBooleanSchema(true),
WORKSHOP_API_URL: z.string().url().optional(),
CUSTOM_WIDGETS_ENABLED: createBooleanSchema(true),
WORKSHOP_ENABLED: createBooleanSchema(true),
HOMARR_WEBSITE_URL: publicHttpUrl("HOMARR_WEBSITE_URL").default("https://homarr.dev"),
WORKSHOP_API_URL: publicHttpUrl("WORKSHOP_API_URL").optional(),
WORKSHOP_WEB_URL: publicHttpUrl("WORKSHOP_WEB_URL").optional(),
},
experimental__runtimeEnv: process.env,
});
@@ -0,0 +1,12 @@
"use client";
import { useSyncExternalStore } from "react";
const subscribe = () => () => undefined;
export const useRuntimeFeature = (feature: "custom-widgets" | "workshop") =>
useSyncExternalStore(
subscribe,
() => document.querySelector<HTMLMetaElement>(`meta[name="homarr-${feature}-enabled"]`)?.content !== "false",
() => true,
);