refactor: trim v2 hardening scaffolding

This commit is contained in:
ajnart committed 2026-07-30 15:19:17 +02:00
1 parent ecfb9d59e0
commit 2eb0baf17e
75 files changed
+334 -2067

No files matched your search

+10 -4
View File
@@ -26,7 +26,14 @@ pnpm dev
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.
To test Custom Widgets against a local Community Workshop, run `pnpm dev:workshop` in another terminal and set:
To test Custom Widgets against a local Community Workshop, start PocketBase and the docs in separate terminals:
```sh
pnpm docker:workshop
WORKSHOP_API_URL=http://127.0.0.1:8090 pnpm dev:docs
```
Then set:
```dotenv
HOMARR_WEBSITE_URL=http://127.0.0.1:3003
@@ -37,6 +44,5 @@ WORKSHOP_WEB_URL=http://127.0.0.1:3003/workshop
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.
See [`apps/docs/docs/advanced/development/getting-started.mdx`](../docs/docs/advanced/development/getting-started.mdx)
for the full contributor setup.
@@ -3,8 +3,6 @@ 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 = {
@@ -15,7 +13,6 @@ 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} />;
}
-2
View File
@@ -149,8 +149,6 @@ export default async function Layout(props: {
<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>
@@ -24,7 +24,6 @@ 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 };
@@ -38,7 +37,6 @@ 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 duplicateMutation = clientApi.customWidget.duplicate.useMutation();
@@ -189,11 +187,9 @@ export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
<Menu.Item onClick={() => void handleExport()} leftSection={<IconDownload {...iconProps} />}>
{t("action.export")}
</Menu.Item>
{workshopEnabled && (
<Menu.Item onClick={publishControls.open} leftSection={<IconBuildingStore {...iconProps} />}>
{t("action.publishWorkshop")}
</Menu.Item>
)}
<Menu.Item onClick={publishControls.open} leftSection={<IconBuildingStore {...iconProps} />}>
{t("action.publishWorkshop")}
</Menu.Item>
<Menu.Divider />
</>
)}
@@ -226,9 +222,7 @@ export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
)}
</Menu.Dropdown>
</Menu>
{widget.valid && workshopEnabled && (
<WorkshopPublishModal opened={publishOpened} onClose={publishControls.close} widget={widget} />
)}
{widget.valid && <WorkshopPublishModal opened={publishOpened} onClose={publishControls.close} widget={widget} />}
{widget.migrationRequired && (
<>
<input
@@ -5,9 +5,7 @@ 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";
@@ -21,8 +19,6 @@ export default async function EditCustomWidgetPage(props: EditCustomWidgetPagePr
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,8 +5,6 @@ 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";
@@ -16,8 +14,6 @@ export default async function NewCustomWidgetPage() {
if (!session || !session.user.permissions.includes("admin")) {
redirect("/manage/custom-widgets");
}
if (env.CUSTOM_WIDGETS_ENABLED === false) return <CustomWidgetsUnavailable />;
const t = await getScopedI18n("customWidget");
return (
@@ -9,8 +9,6 @@ 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";
@@ -22,8 +20,6 @@ export default async function CustomWidgetsPage() {
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,13 +5,9 @@ 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("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,7 +41,6 @@ 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");
@@ -80,16 +79,13 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
icon: IconApi,
href: "/manage/custom-widgets",
label: t("items.customWidgets"),
hidden: nextEnv.CUSTOM_WIDGETS_ENABLED === false || !session?.user.permissions.includes("admin"),
hidden: !session?.user.permissions.includes("admin"),
},
{
icon: IconBuildingStore,
href: "/manage/workshop",
label: t("items.workshop"),
hidden:
nextEnv.CUSTOM_WIDGETS_ENABLED === false ||
nextEnv.WORKSHOP_ENABLED === false ||
!session?.user.permissions.includes("admin"),
hidden: !session?.user.permissions.includes("admin"),
},
{
icon: IconSearch,
@@ -13,7 +13,6 @@ import { env } from "~/env";
export default async function WorkshopPage() {
const session = await auth();
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,
@@ -4,16 +4,13 @@ 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"] } });
});
@@ -30,11 +27,4 @@ describe("Custom Widget HTTP resource access", () => {
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") });
});
});
@@ -2,18 +2,10 @@ 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;
};
@@ -7,7 +7,6 @@ const mocks = vi.hoisted(() => ({
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"),
),
@@ -39,7 +38,6 @@ 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: () => [
@@ -75,8 +73,6 @@ interface JsonRpcResponse {
beforeEach(() => {
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();
@@ -242,27 +238,6 @@ describe("non-admin MCP discovery", () => {
});
});
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" }],
@@ -27,7 +27,6 @@ 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";
@@ -124,17 +123,14 @@ function getVisibleTools() {
if (!isCustomWidgetMcpEnabled()) {
return tools.filter((tool) => !tool.name.startsWith("customWidget_"));
}
return env.WORKSHOP_ENABLED === false
? tools.filter((tool) => !tool.name.startsWith("customWidget_workshop"))
: tools;
return tools;
}
function requireCustomWidgetMcpAdmin() {
if (!isCustomWidgetMcpEnabled()) throw new Error("Resource not found");
}
const isCustomWidgetMcpEnabled = () =>
Boolean(callerStorage.getStore()?.isAdmin) && env.CUSTOM_WIDGETS_ENABLED !== false;
const isCustomWidgetMcpEnabled = () => Boolean(callerStorage.getStore()?.isAdmin);
const SAFE_ERROR_MESSAGES: Record<string, string> = {
UNAUTHORIZED: "You do not have permission to perform this action",
@@ -16,14 +16,11 @@ 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();
@@ -31,7 +28,7 @@ export const ItemSelectModal = createModal<{ boardId: string }>(({ actions, inne
const { data: integrationData } = clientApi.integration.all.useQuery();
const { data: customWidgetDefs } = clientApi.customWidget.available.useQuery(
{ boardId: innerProps.boardId },
{ enabled: isAdmin && customWidgetsEnabled },
{ enabled: isAdmin },
);
const settings = useSettings();
@@ -169,7 +166,7 @@ export const ItemSelectModal = createModal<{ boardId: string }>(({ actions, inne
/>
))}
{isAdmin && customWidgetsEnabled && (
{isAdmin && (
<>
<Divider
label={t("customWidget.page.list.title")}
@@ -221,15 +218,13 @@ export const ItemSelectModal = createModal<{ boardId: string }>(({ actions, inne
</Card>
))}
{workshopEnabled && (
<Box style={{ gridColumn: "1 / -1" }}>
<WorkshopInstallButton fullWidth>{t("workshop.installDialog")}</WorkshopInstallButton>
</Box>
)}
<Box style={{ gridColumn: "1 / -1" }}>
<WorkshopInstallButton fullWidth>{t("workshop.installDialog")}</WorkshopInstallButton>
</Box>
</>
)}
{filteredItems.length === 0 && (!isAdmin || !customWidgetsEnabled || filteredCustomWidgets.length === 0) && (
{filteredItems.length === 0 && (!isAdmin || filteredCustomWidgets.length === 0) && (
<Center p="xl">
<Text c="dimmed">{t("common.noResults")}</Text>
</Center>
@@ -1,16 +0,0 @@
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,14 +5,10 @@ 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,7 +9,6 @@ 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 {
@@ -18,7 +17,6 @@ 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);
@@ -29,8 +27,6 @@ export function WorkshopInstallButton({ children, fullWidth }: WorkshopInstallBu
setPendingWidget(null);
};
if (!workshopEnabled) return null;
return (
<>
<Button
@@ -10,7 +10,6 @@ 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,
@@ -26,7 +25,6 @@ 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);
@@ -37,16 +35,15 @@ 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 && workshopEnabled });
const definition = clientApi.customWidget.export.useQuery({ id: widget.id }, { enabled: opened });
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, workshopEnabled]);
}, [client]);
useEffect(() => {
if (!opened) return;
setTitle(widget.name);
@@ -89,8 +86,6 @@ export function WorkshopPublishModal({
}
};
if (!workshopEnabled) return null;
return (
<Modal opened={opened} onClose={onClose} title={t("publish.title")} size="lg">
<Stack>
-2
View File
@@ -21,8 +21,6 @@ export const env = createEnv({
UNSAFE_ENABLE_MOCK_INTEGRATION: createBooleanSchema(false),
DEMO_MODE: createBooleanSchema(false),
DEMO_READ_ONLY: createBooleanSchema(true),
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(),
@@ -1,12 +0,0 @@
"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,
);