perf: implement Phase 1 homepage diet via Next.js Cache Components

P1-0: V8 heap cap (HOMARR_MAX_OLD_SPACE_SIZE, default 512MB)
P1-1: Module graph cuts
  - Dynamic integration imports (55 static → lazy loaders)
  - Conditional DB driver loading (only configured driver loaded)
  - Replace jsdom with linkedom for SVG sanitization
  - Delete eager widget barrel (55 import * as → 0)
  - Extract createRetryableLoader to @homarr/common
P1-2: Enable cacheComponents + restructure root layout
  - Suspense boundaries around session-dependent providers
  - ColorSchemeScript replaces server-side cookie reads
  - Board/manage/auth layouts wrapped in Suspense
P1-3: Cache read paths
  - Cache tag registry + invalidation helpers
  - Cache invalidation wired into all mutation routers
  - Translation deep-merge memoized per locale
P1-4: Prerendered shells + loading.tsx files
P1-5: Shared integration data cache (60s TTL, stale-while-revalidate)
P1-6: Redis-backed Next.js cache handler (@homarr/next-cache-handler)
P1-7: Redis optional (memory channel fallback), TTL on pubSub:last:*,
      Redis clients consolidated from 6 to 2
This commit is contained in:
Thomas Camlong committed 2026-08-07 18:59:47 +02:00
1 parent 366ec6bdbc
commit 018f98e318
86 files changed
+2219 -1232

No files matched your search

@@ -13,8 +13,8 @@ import { theme } from "@homarr/ui";
export const CustomMantineProvider = ({
children,
defaultColorScheme,
}: PropsWithChildren<{ defaultColorScheme: MantineColorScheme }>) => {
defaultColorScheme = "auto",
}: PropsWithChildren<{ defaultColorScheme?: MantineColorScheme }>) => {
const manager = useColorSchemeManager();
return (
<DirectionProvider>
@@ -0,0 +1,84 @@
import type { PropsWithChildren } from "react";
import type { DayOfWeek } from "@mantine/dates";
import { NextIntlClientProvider } from "next-intl";
import { getRscServerSettingsAsync } from "@homarr/api/server-settings-server";
import { getRscUserSettingsAsync } from "@homarr/api/user-server";
import { env } from "@homarr/auth/env";
import { auth } from "@homarr/auth/next";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { ModalProvider } from "@homarr/modals";
import { Notifications } from "@homarr/notifications";
import { SettingsProvider } from "@homarr/settings";
import { SpotlightProvider } from "@homarr/spotlight";
import { Analytics } from "~/components/layout/analytics";
import { ServiceWorkerRegistration } from "~/components/layout/service-worker-registration";
import { DayJsLoader } from "./_client-providers/dayjs-loader";
import { JotaiProvider } from "./_client-providers/jotai";
import { CustomMantineProvider } from "./_client-providers/mantine";
import { AuthProvider } from "./_client-providers/session";
import { TRPCReactProvider } from "./_client-providers/trpc";
import { composeWrappers } from "./compose";
const logger = createLogger({ module: "sessionScopedProviders" });
export async function SessionScopedProviders({ children }: PropsWithChildren) {
const sessionPromise = auth();
const userPromise = sessionPromise.then((session) =>
session
? getRscUserSettingsAsync(session.user.id).catch((error: unknown) => {
logger.error(new Error("Failed to load the authenticated user in the root layout", { cause: error }));
return null;
})
: null,
);
const [session, user, serverSettings] = await Promise.all([
sessionPromise,
userPromise,
getRscServerSettingsAsync(),
]);
const StackedProvider = composeWrappers([
(innerProps) => <AuthProvider session={session} logoutUrl={env.AUTH_LOGOUT_REDIRECT_URL} {...innerProps} />,
(innerProps) => (
<SettingsProvider
user={
user
? {
...user,
firstDayOfWeek: user.firstDayOfWeek as DayOfWeek,
}
: null
}
serverSettings={{
board: {
homeBoardId: serverSettings.board.homeBoardId,
mobileHomeBoardId: serverSettings.board.mobileHomeBoardId,
enableStatusByDefault: serverSettings.board.enableStatusByDefault,
forceDisableStatus: serverSettings.board.forceDisableStatus,
},
search: { defaultSearchEngineId: serverSettings.search.defaultSearchEngineId },
user: { enableGravatar: serverSettings.user.enableGravatar },
}}
{...innerProps}
/>
),
(innerProps) => <JotaiProvider {...innerProps} />,
(innerProps) => <TRPCReactProvider {...innerProps} />,
(innerProps) => <DayJsLoader {...innerProps} />,
(innerProps) => <NextIntlClientProvider {...innerProps} />,
(innerProps) => <CustomMantineProvider {...innerProps} />,
(innerProps) => <ModalProvider {...innerProps} />,
(innerProps) => <SpotlightProvider {...innerProps} />,
]);
return (
<StackedProvider>
<Analytics enabled={serverSettings.analytics.enableGeneral} />
<Notifications pauseResetOnHover="notification" />
<ServiceWorkerRegistration />
{children}
</StackedProvider>
);
}
@@ -1,5 +1,6 @@
import { Suspense } from "react";
import { redirect } from "next/navigation";
import { Alert, Card, Center, Code, Stack, Text, Title } from "@mantine/core";
import { Alert, Card, Center, Code, Loader, Stack, Text, Title } from "@mantine/core";
import { IconLogin } from "@tabler/icons-react";
import { env } from "@homarr/auth/env";
@@ -18,8 +19,7 @@ interface LoginProps {
}>;
}
export default async function Login(props: LoginProps) {
const searchParams = await props.searchParams;
async function LoginContent({ searchParams }: { searchParams: { callbackUrl?: string } }) {
const session = await auth();
if (session) {
@@ -59,3 +59,19 @@ export default async function Login(props: LoginProps) {
</Center>
);
}
export default async function Login(props: LoginProps) {
const searchParams = await props.searchParams;
return (
<Suspense
fallback={
<Center h="100vh">
<Loader size="lg" />
</Center>
}
>
<LoginContent searchParams={searchParams} />
</Suspense>
);
}
@@ -1,5 +1,7 @@
import type { Metadata } from "next";
import { Suspense } from "react";
import { cache } from "react";
import { Center, Loader } from "@mantine/core";
import { TRPCError } from "@trpc/server";
// Placed here because gridstack styles are used for board content
@@ -33,6 +35,52 @@ interface Props<TParams extends Params> {
getInitialBoardAsync: (params: TParams) => Promise<Board>;
}
interface BoardContentPageProps<TParams extends Params> {
params: TParams;
getInitialBoard: (params: TParams) => Promise<Board>;
}
async function BoardContentPageDynamic<TParams extends Params>({
params,
getInitialBoard,
}: BoardContentPageProps<TParams>) {
const queryClient = getQueryClient();
const [board, session] = await Promise.all([getInitialBoard(params), auth()]);
const itemsMap = board.items.reduce((acc, item) => {
const existing = acc.get(item.kind);
if (existing) {
existing.push(item);
} else {
acc.set(item.kind, [item]);
}
return acc;
}, new Map<WidgetKind, Item[]>());
const [integrations] = await Promise.all([
getIntegrationsWithPermissionsAsync(session),
...Array.from(itemsMap).map(([kind, items]) =>
prefetchForKindAsync(kind, queryClient, items).catch((error) => {
logger.error(
new ErrorWithMetadata(
"Failed to prefetch widget",
{ widgetKind: kind, itemCount: items.length },
{ cause: error },
),
);
}),
),
]);
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<IntegrationProvider integrations={integrations}>
<DynamicClientBoard />
</IntegrationProvider>
</HydrationBoundary>
);
}
export const createBoardContentPage = <TParams extends Record<string, unknown>>({
getInitialBoardAsync: getInitialBoard,
}: Props<TParams>) => {
@@ -45,40 +93,17 @@ export const createBoardContentPage = <TParams extends Record<string, unknown>>(
// eslint-disable-next-line no-restricted-syntax
page: async ({ params }: { params: Promise<TParams> }) => {
const resolvedParams = await params;
const queryClient = getQueryClient();
const [board, session] = await Promise.all([getInitialBoard(resolvedParams), auth()]);
const itemsMap = board.items.reduce((acc, item) => {
const existing = acc.get(item.kind);
if (existing) {
existing.push(item);
} else {
acc.set(item.kind, [item]);
}
return acc;
}, new Map<WidgetKind, Item[]>());
const [integrations] = await Promise.all([
getIntegrationsWithPermissionsAsync(session),
...Array.from(itemsMap).map(([kind, items]) =>
prefetchForKindAsync(kind, queryClient, items).catch((error) => {
logger.error(
new ErrorWithMetadata(
"Failed to prefetch widget",
{ widgetKind: kind, itemCount: items.length },
{ cause: error },
),
);
}),
),
]);
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<IntegrationProvider integrations={integrations}>
<DynamicClientBoard />
</IntegrationProvider>
</HydrationBoundary>
<Suspense
fallback={
<Center w="100%" h="100%">
<Loader size="xl" />
</Center>
}
>
<BoardContentPageDynamic params={resolvedParams} getInitialBoard={getInitialBoard} />
</Suspense>
);
},
generateMetadataAsync: async ({ params }: { params: Promise<TParams> }): Promise<Metadata> => {
@@ -11,8 +11,8 @@ import { useColorSchemeManager } from "../../_client-providers/mantine";
export const BoardMantineProvider = ({
children,
defaultColorScheme,
}: PropsWithChildren<{ defaultColorScheme: ColorScheme }>) => {
defaultColorScheme = "auto",
}: PropsWithChildren<{ defaultColorScheme?: ColorScheme }>) => {
const board = useRequiredBoard();
const colorSchemeManager = useColorSchemeManager();
@@ -0,0 +1,9 @@
import { Center, Loader } from "@mantine/core";
export default function BoardLoading() {
return (
<Center w="100%" h="100vh">
<Loader size="xl" />
</Center>
);
}
@@ -1,6 +1,7 @@
import type { JSX, PropsWithChildren } from "react";
import { Suspense } from "react";
import { notFound, redirect } from "next/navigation";
import { AppShellMain } from "@mantine/core";
import { AppShellMain, Skeleton } from "@mantine/core";
import { TRPCError } from "@trpc/server";
import { getRscUserSettingsAsync } from "@homarr/api/user-server";
@@ -14,7 +15,6 @@ import { BoardLogoWithTitle } from "~/components/layout/logo/board-logo";
import { ClientShell } from "~/components/layout/shell";
import { BoardTourGate } from "~/components/onboarding/board-tour-gate";
import { env } from "~/env";
import { getCurrentColorSchemeAsync } from "~/theme/color-scheme";
import type { Board } from "./_types";
import type { Params } from "./(content)/_creator";
import { CustomCss } from "./(content)/_custom-css";
@@ -29,6 +29,94 @@ interface CreateBoardLayoutProps<TParams extends Params> {
withTour?: boolean;
}
const BoardLayoutFallback = ({ headerActions }: { headerActions: JSX.Element }) => (
<ClientShell hasNavigation={false}>
<MainHeader logo={<BoardLogoWithTitle size="md" hideTitleOnMobile />} actions={headerActions} hasNavigation={false} />
<AppShellMain>
<Skeleton height="100%" radius="sm" />
</AppShellMain>
</ClientShell>
);
interface BoardLayoutDynamicProps<TParams extends Params> {
params: TParams;
headerActions: JSX.Element;
getInitialBoardAsync: (params: TParams) => Promise<Board>;
withTour: boolean;
children: React.ReactNode;
}
async function BoardLayoutDynamic<TParams extends Params>({
params,
headerActions,
getInitialBoardAsync: getInitialBoard,
withTour,
children,
}: BoardLayoutDynamicProps<TParams>) {
const sessionPromise = auth();
const initialBoardPromise = getInitialBoard(params).then(
(board) => ({ status: "fulfilled", board }) as const,
(error: unknown) => ({ status: "rejected", error }) as const,
);
const shouldRunBoardTourPromise = sessionPromise.then(async (session) => {
if (!withTour || !session || env.DEMO_MODE) return false;
try {
const user = await getRscUserSettingsAsync(session.user.id);
return user !== undefined && !user.completedBoardTour;
} catch (error) {
logger.error(new Error("Failed to load the board tour status", { cause: error }));
return false;
}
});
const [session, initialBoardResult, shouldRunBoardTour] = await Promise.all([
sessionPromise,
initialBoardPromise,
shouldRunBoardTourPromise,
]);
if (initialBoardResult.status === "rejected") {
const { error } = initialBoardResult;
if (error instanceof TRPCError && error.code === "NOT_FOUND") {
if (!session) {
logger.debug("No home board found for anonymous user, redirecting to login");
redirect("/auth/login");
}
logger.warn(error);
notFound();
}
if (error instanceof TRPCError && error.code === "BAD_REQUEST") {
notFound();
}
throw error;
}
const initialBoard = initialBoardResult.board;
return (
<BoardProvider initialBoard={initialBoard}>
<BoardReadyProvider>
<EditModeProvider>
<BoardMantineProvider>
<CustomCss />
<BoardTourGate enabled={shouldRunBoardTour}>
<ClientShell hasNavigation={false}>
<MainHeader
logo={<BoardLogoWithTitle size="md" hideTitleOnMobile />}
actions={headerActions}
hasNavigation={false}
/>
<AppShellMain>{children}</AppShellMain>
</ClientShell>
</BoardTourGate>
</BoardMantineProvider>
</EditModeProvider>
</BoardReadyProvider>
</BoardProvider>
);
}
export const createBoardLayout = <TParams extends Params>({
headerActions,
getInitialBoardAsync: getInitialBoard,
@@ -41,69 +129,18 @@ export const createBoardLayout = <TParams extends Params>({
params: Promise<TParams>;
}>) => {
const resolvedParams = await params;
const sessionPromise = auth();
const initialBoardPromise = getInitialBoard(resolvedParams).then(
(board) => ({ status: "fulfilled", board }) as const,
(error: unknown) => ({ status: "rejected", error }) as const,
);
const colorSchemePromise = getCurrentColorSchemeAsync();
const shouldRunBoardTourPromise = sessionPromise.then(async (session) => {
if (!withTour || !session || env.DEMO_MODE) return false;
try {
const user = await getRscUserSettingsAsync(session.user.id);
return user !== undefined && !user.completedBoardTour;
} catch (error) {
logger.error(new Error("Failed to load the board tour status", { cause: error }));
return false;
}
});
const [session, initialBoardResult, colorScheme, shouldRunBoardTour] = await Promise.all([
sessionPromise,
initialBoardPromise,
colorSchemePromise,
shouldRunBoardTourPromise,
]);
if (initialBoardResult.status === "rejected") {
const { error } = initialBoardResult;
if (error instanceof TRPCError && error.code === "NOT_FOUND") {
if (!session) {
logger.debug("No home board found for anonymous user, redirecting to login");
redirect("/auth/login");
}
logger.warn(error);
notFound();
}
if (error instanceof TRPCError && error.code === "BAD_REQUEST") {
notFound();
}
throw error;
}
const initialBoard = initialBoardResult.board;
return (
<BoardProvider initialBoard={initialBoard}>
<BoardReadyProvider>
<EditModeProvider>
<BoardMantineProvider defaultColorScheme={colorScheme}>
<CustomCss />
<BoardTourGate enabled={shouldRunBoardTour}>
<ClientShell hasNavigation={false}>
<MainHeader
logo={<BoardLogoWithTitle size="md" hideTitleOnMobile />}
actions={headerActions}
hasNavigation={false}
/>
<AppShellMain>{children}</AppShellMain>
</ClientShell>
</BoardTourGate>
</BoardMantineProvider>
</EditModeProvider>
</BoardReadyProvider>
</BoardProvider>
<Suspense fallback={<BoardLayoutFallback headerActions={headerActions} />}>
<BoardLayoutDynamic
params={resolvedParams}
headerActions={headerActions}
getInitialBoardAsync={getInitialBoard}
withTour={withTour}
>
{children}
</BoardLayoutDynamic>
</Suspense>
);
};
+10 -94
View File
@@ -1,5 +1,7 @@
import type { Metadata, Viewport } from "next";
import { Suspense } from "react";
import { Inter } from "next/font/google";
import { ColorSchemeScript } from "@mantine/core";
import "@gfazioli/mantine-onboarding-tour/styles.css";
import "@homarr/notifications/styles.css";
@@ -10,42 +12,19 @@ import "~/styles/color-scheme.scss";
import "~/styles/scroll-area.scss";
import { notFound } from "next/navigation";
import type { DayOfWeek } from "@mantine/dates";
import { NextIntlClientProvider } from "next-intl";
import { getRscServerSettingsAsync } from "@homarr/api/server-settings-server";
import { getRscUserSettingsAsync } from "@homarr/api/user-server";
import { env } from "@homarr/auth/env";
import { auth } from "@homarr/auth/next";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { ModalProvider } from "@homarr/modals";
import { Notifications } from "@homarr/notifications";
import { SettingsProvider } from "@homarr/settings";
import { SpotlightProvider } from "@homarr/spotlight";
import type { SupportedLanguage } from "@homarr/translation";
import { isLocaleRTL, isLocaleSupported } from "@homarr/translation";
import { Analytics } from "~/components/layout/analytics";
import { CrowdinLiveTranslation } from "~/components/layout/crowdin-live-translation";
import { SearchEngineOptimization } from "~/components/layout/search-engine-optimization";
import { ServiceWorkerRegistration } from "~/components/layout/service-worker-registration";
import { getCurrentColorSchemeAsync } from "~/theme/color-scheme";
import { DayJsLoader } from "./_client-providers/dayjs-loader";
import { JotaiProvider } from "./_client-providers/jotai";
import { CustomMantineProvider } from "./_client-providers/mantine";
import { AuthProvider } from "./_client-providers/session";
import { TRPCReactProvider } from "./_client-providers/trpc";
import { composeWrappers } from "./compose";
import { CrowdinLiveTranslation } from "~/components/layout/crowdin-live-translation";
import { SessionScopedProviders } from "./_session-scoped-providers";
const fontSans = Inter({
subsets: ["latin"],
variable: "--font-sans",
});
const logger = createLogger({ module: "rootLayout" });
// eslint-disable-next-line no-restricted-syntax
export const generateMetadata = async (): Promise<Metadata> => ({
title: "Homarr",
description:
@@ -65,7 +44,7 @@ export const generateMetadata = async (): Promise<Metadata> => ({
title: "Homarr",
capable: true,
startupImage: { url: "/logo/logo.png" },
statusBarStyle: (await getCurrentColorSchemeAsync()) === "dark" ? "black-translucent" : "default",
statusBarStyle: "default",
},
});
@@ -85,82 +64,19 @@ export default async function Layout(props: {
notFound();
}
const sessionPromise = auth();
const userPromise = sessionPromise.then((session) =>
session
? getRscUserSettingsAsync(session.user.id).catch((error: unknown) => {
logger.error(new Error("Failed to load the authenticated user in the root layout", { cause: error }));
return null;
})
: null,
);
const [session, user, serverSettings, colorScheme] = await Promise.all([
sessionPromise,
userPromise,
getRscServerSettingsAsync(),
getCurrentColorSchemeAsync(),
]);
const direction = isLocaleRTL(locale) ? "rtl" : "ltr";
const StackedProvider = composeWrappers([
(innerProps) => {
return <AuthProvider session={session} logoutUrl={env.AUTH_LOGOUT_REDIRECT_URL} {...innerProps} />;
},
(innerProps) => (
<SettingsProvider
user={
user
? {
...user,
// Convert type, because output schema is not smart enough to infer $type from drizzle
firstDayOfWeek: user.firstDayOfWeek as DayOfWeek,
}
: null
}
serverSettings={{
board: {
homeBoardId: serverSettings.board.homeBoardId,
mobileHomeBoardId: serverSettings.board.mobileHomeBoardId,
enableStatusByDefault: serverSettings.board.enableStatusByDefault,
forceDisableStatus: serverSettings.board.forceDisableStatus,
},
search: { defaultSearchEngineId: serverSettings.search.defaultSearchEngineId },
user: { enableGravatar: serverSettings.user.enableGravatar },
}}
{...innerProps}
/>
),
(innerProps) => <JotaiProvider {...innerProps} />,
(innerProps) => <TRPCReactProvider {...innerProps} />,
(innerProps) => <DayJsLoader {...innerProps} />,
(innerProps) => <NextIntlClientProvider {...innerProps} />,
(innerProps) => <CustomMantineProvider {...innerProps} defaultColorScheme={colorScheme} />,
(innerProps) => <ModalProvider {...innerProps} />,
(innerProps) => <SpotlightProvider {...innerProps} />,
]);
return (
// Instead of ColorSchemScript we use data-mantine-color-scheme to prevent flickering
<html
lang={locale}
dir={direction}
data-mantine-color-scheme={colorScheme}
style={{
backgroundColor: colorScheme === "dark" ? "#242424" : colorScheme === "auto" ? undefined : "#fff",
}}
suppressHydrationWarning
>
<html lang={locale} dir={direction} suppressHydrationWarning>
<head>
<ColorSchemeScript />
<SearchEngineOptimization />
<CrowdinLiveTranslation locale={locale} />
</head>
<body className={[fontSans.className, fontSans.variable].join(" ")} suppressHydrationWarning>
<Analytics enabled={serverSettings.analytics.enableGeneral} />
<StackedProvider>
<Notifications pauseResetOnHover="notification" />
<ServiceWorkerRegistration />
{props.children}
</StackedProvider>
<Suspense>
<SessionScopedProviders>{props.children}</SessionScopedProviders>
</Suspense>
</body>
</html>
);
+26 -11
View File
@@ -1,5 +1,6 @@
import type { PropsWithChildren } from "react";
import { AppShellMain } from "@mantine/core";
import { Suspense } from "react";
import { AppShellMain, Skeleton } from "@mantine/core";
import {
IconAffiliateFilled,
IconApi,
@@ -46,7 +47,17 @@ import { env as nextEnv } from "~/env";
const logger = createLogger({ module: "manageLayout" });
export default async function ManageLayout({ children }: PropsWithChildren) {
const ManageLayoutFallback = () => (
<ClientShell hasNavigation>
<MainHeader />
<MainNavigation links={[]} />
<AppShellMain>
<Skeleton height="100%" radius="sm" />
</AppShellMain>
</ClientShell>
);
async function ManageLayoutContent({ children }: PropsWithChildren) {
const sessionPromise = auth();
const shouldRunManageTourPromise = sessionPromise.then(async (session) => {
if (!session || nextEnv.DEMO_MODE) return false;
@@ -237,17 +248,21 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
const isAdmin = session?.user.permissions.includes("admin") ?? false;
const shell = (
<ClientShell hasNavigation>
<MainHeader></MainHeader>
<MainNavigation links={navigationLinks}></MainNavigation>
<AppShellMain>{children}</AppShellMain>
</ClientShell>
);
return (
<ManageTourGate enabled={shouldRunManageTour} isAdmin={isAdmin}>
{shell}
<ClientShell hasNavigation>
<MainHeader />
<MainNavigation links={navigationLinks} />
<AppShellMain>{children}</AppShellMain>
</ClientShell>
</ManageTourGate>
);
}
export default function ManageLayout({ children }: PropsWithChildren) {
return (
<Suspense fallback={<ManageLayoutFallback />}>
<ManageLayoutContent>{children}</ManageLayoutContent>
</Suspense>
);
}
@@ -0,0 +1,9 @@
import { Center, Loader } from "@mantine/core";
export default function ManageLoading() {
return (
<Center w="100%" h="100vh">
<Loader size="lg" />
</Center>
);
}
@@ -11,6 +11,10 @@ interface Props {
params: Promise<{ kind: string }>;
}
export function generateStaticParams() {
return widgetKinds.map((kind) => ({ kind }));
}
export default async function WidgetPreview(props: Props) {
const { kind } = await props.params;
if (!widgetKinds.includes(kind as WidgetKind)) {
@@ -1,11 +1,12 @@
import { notFound } from "next/navigation";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import DOMPurify from "isomorphic-dompurify";
import { db, eq } from "@homarr/db";
import { medias } from "@homarr/db/schema";
import { sanitizeSvg } from "../svg-purify";
export async function GET(_req: NextRequest, props: { params: Promise<{ id: string }> }) {
const params = await props.params;
const image = await db.query.medias.findFirst({
@@ -25,9 +26,7 @@ export async function GET(_req: NextRequest, props: { params: Promise<{ id: stri
// Sanitize SVG content to prevent XSS attacks
if (image.contentType === "image/svg+xml" || image.contentType === "image/svg") {
const svgText = new TextDecoder().decode(content);
const sanitized = DOMPurify.sanitize(svgText, {
USE_PROFILES: { svg: true, svgFilters: true },
});
const sanitized = sanitizeSvg(svgText);
content = new TextEncoder().encode(sanitized);
}
@@ -0,0 +1,44 @@
import { describe, expect, it } from "vitest";
import { purify, sanitizeSvg, svgSanitizeOptions } from "./svg-purify";
describe("SVG sanitization", () => {
it("strips script tags from SVG", () => {
const dirty = '<svg><script>alert("xss")</script><circle r="10"/></svg>';
const clean = sanitizeSvg(dirty);
expect(clean).not.toContain("<script");
expect(clean).toContain("circle");
});
it("strips onload event handler", () => {
const dirty = '<svg onload="alert(1)"><rect width="100" height="100"/></svg>';
const clean = sanitizeSvg(dirty);
expect(clean).not.toContain("onload");
});
it("strips data URI in use href", () => {
const dirty = '<svg><use href="data:text/html,<script>alert(1)</script>"/></svg>';
const clean = sanitizeSvg(dirty);
expect(clean).not.toContain("data:");
});
it("strips foreignObject", () => {
const dirty =
'<svg><foreignObject><body xmlns="http://www.w3.org/1999/xhtml"><script>alert(1)</script></body></foreignObject></svg>';
const clean = sanitizeSvg(dirty);
expect(clean).not.toContain("foreignObject");
});
it("preserves safe SVG content", () => {
const safe = '<svg viewBox="0 0 100 100"><circle cx="50" cy="50" r="40" fill="red"/></svg>';
const clean = sanitizeSvg(safe);
expect(clean).toContain("circle");
expect(clean).toContain('fill="red"');
});
it("uses the same DOMPurify options as production", () => {
const dirty = '<svg><script>alert("xss")</script></svg>';
const wrapped = `<html><body>${dirty}</body></html>`;
expect(sanitizeSvg(dirty)).toBe(purify.sanitize(wrapped, svgSanitizeOptions));
});
});
@@ -0,0 +1,90 @@
import createDOMPurify from "dompurify";
import { parseHTML } from "linkedom";
const svgSanitizeOptions = {
USE_PROFILES: { svg: true, svgFilters: true },
} as const;
// ponytail: linkedom stores DOM tree pointers as own value properties; DOMPurify
// resolves them via prototype getters (lookupGetter). Without this shim, sanitize
// is a no-op and XSS payloads pass through unchanged.
const patchLinkedomNodePrototype = (Node: typeof window.Node) => {
for (const prop of [
"ownerDocument",
"parentNode",
"nextSibling",
"previousSibling",
"nodeName",
"nodeType",
"childNodes",
] as const) {
if (Object.getOwnPropertyDescriptor(Node.prototype, prop)?.get) {
continue;
}
if (Object.getOwnPropertyDescriptor(Node.prototype, prop)?.value !== undefined) {
delete Node.prototype[prop as keyof Node];
}
Object.defineProperty(Node.prototype, prop, {
configurable: true,
enumerable: true,
get() {
return Object.getOwnPropertyDescriptor(this, prop)?.value ?? null;
},
set(value: unknown) {
Object.defineProperty(this, prop, {
value,
writable: true,
configurable: true,
enumerable: true,
});
},
});
}
};
const createDocument = () => parseHTML("<!doctype html><html><head></head><body></body></html>");
const { window, document, Node } = createDocument();
patchLinkedomNodePrototype(Node);
if (!document.implementation?.createHTMLDocument) {
Object.defineProperty(document, "implementation", {
value: {
createHTMLDocument() {
return createDocument().document;
},
createDocument() {
return createDocument().document;
},
},
});
}
window.NodeFilter ??= {
FILTER_ACCEPT: 1,
FILTER_REJECT: 2,
FILTER_SKIP: 3,
SHOW_ALL: 0xffffffff,
SHOW_ELEMENT: 1,
SHOW_ATTRIBUTE: 2,
SHOW_TEXT: 4,
SHOW_CDATA_SECTION: 8,
SHOW_PROCESSING_INSTRUCTION: 64,
SHOW_COMMENT: 128,
SHOW_DOCUMENT: 0x100,
SHOW_DOCUMENT_TYPE: 0x200,
SHOW_DOCUMENT_FRAGMENT: 0x400,
SHOW_NOTATION: 0x800,
} as typeof window.NodeFilter;
const purify = createDOMPurify(window as unknown as Parameters<typeof createDOMPurify>[0]);
export const sanitizeSvg = (svgText: string) => {
// linkedom's DOMParser omits html/body for fragment-only SVG; DOMPurify needs a body root.
const wrapped = `<html><body>${svgText}</body></html>`;
return purify.sanitize(wrapped, svgSanitizeOptions);
};
export { svgSanitizeOptions, purify };