Skip to content

A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.

feat(board): add apps by dropping a URL onto the board in edit mode

Michael A Williamsonf2dc86b37add
diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_client.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/_client.tsx
index 958bdec92..717516ffe 100644
--- a/apps/nextjs/src/app/[locale]/boards/(content)/_client.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/(content)/_client.tsx
@@ -11,6 +11,7 @@ import { useI18n } from "@homarr/translation/client";
import { FloatingTip } from "@homarr/ui";
import { BoardAdvancedFocusProvider } from "~/components/board/advanced-focus/context";
+import { BoardAppUrlDrop } from "~/components/board/board-app-url-drop";
import { BoardAppsSpotlightRegistrar } from "~/components/board/board-apps-spotlight-registrar";
import { BoardEmptyState } from "~/components/board/board-empty-state";
import { BoardSetupChecklist } from "~/components/board/board-setup-checklist";
@@ -96,6 +97,7 @@ export const ClientBoard = () => {
<BoardBackgroundVideo />
<BoardEmptyState />
<BoardSetupChecklist />
+ <BoardAppUrlDrop />
<BoardSectionCollapseProvider>
<BoardGridPortalHost>
<ScaledBoardCanvas
diff --git a/apps/nextjs/src/app/[locale]/boards/_providers.tsx b/apps/nextjs/src/app/[locale]/boards/_providers.tsx
index 4b58fa533..89e83326c 100644
--- a/apps/nextjs/src/app/[locale]/boards/_providers.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/_providers.tsx
@@ -29,13 +29,15 @@ export const BoardProviders = ({
const layoutOverrideId = isLayoutEditRequest ? requestedLayoutId : null;
return (
- <BoardProvider
- initialBoard={initialBoard}
- initialLayoutId={initialLayoutId}
- initialViewportWidth={initialViewportWidth}
- layoutOverrideId={layoutOverrideId}
- >
- <EditModeProvider initialOpen={isLayoutEditRequest}>{children}</EditModeProvider>
- </BoardProvider>
+ <EditModeProvider initialOpen={isLayoutEditRequest}>
+ <BoardProvider
+ initialBoard={initialBoard}
+ initialLayoutId={initialLayoutId}
+ initialViewportWidth={initialViewportWidth}
+ layoutOverrideId={layoutOverrideId}
+ >
+ {children}
+ </BoardProvider>
+ </EditModeProvider>
);
};
diff --git a/apps/nextjs/src/app/api/image-proxy/[id]/route.ts b/apps/nextjs/src/app/api/image-proxy/[id]/route.ts
index 94b273fd7..13c900921 100644
--- a/apps/nextjs/src/app/api/image-proxy/[id]/route.ts
+++ b/apps/nextjs/src/app/api/image-proxy/[id]/route.ts
@@ -20,6 +20,10 @@ export const GET = async (request: Request, props: { params: Promise<{ id: strin
return new Response(result.image, {
headers: {
"Cache-Control": "public, max-age=3600, immutable", // Cache for 1 hour
+ // Icons may contain HTML or SVG supplied by an untrusted website. They may
+ // render as images, but must never execute as a document on Homarr's origin.
+ "Content-Security-Policy": "sandbox; default-src 'none'; style-src 'unsafe-inline'",
+ "X-Content-Type-Options": "nosniff",
...(result.contentType ? { "Content-Type": result.contentType } : {}),
},
});
diff --git a/apps/nextjs/src/components/board/board-app-url-drop.spec.tsx b/apps/nextjs/src/components/board/board-app-url-drop.spec.tsx
new file mode 100644
index 000000000..0bc32cb2c
--- /dev/null
+++ b/apps/nextjs/src/components/board/board-app-url-drop.spec.tsx
@@ -0,0 +1,163 @@
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import type { Root } from "react-dom/client";
+import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";
+import { MantineProvider } from "@mantine/core";
+
+const mocks = vi.hoisted(() => ({
+ isEditMode: true,
+ permissions: ["app-create"] as string[],
+ createItem: vi.fn(),
+ invalidateApp: vi.fn(),
+ detectMetadataAsync: vi.fn(),
+ hasRoomForItem: vi.fn(),
+ showErrorNotification: vi.fn(),
+ showSuccessNotification: vi.fn(),
+}));
+
+vi.mock("@homarr/boards/edit-mode", () => ({
+ useEditMode: () => [mocks.isEditMode, { open: vi.fn(), close: vi.fn() }],
+}));
+
+vi.mock("@homarr/boards/context", () => ({
+ useRequiredBoard: () => ({ name: "board" }),
+}));
+
+vi.mock("./items/actions/create-item", () => ({
+ hasRoomForItem: mocks.hasRoomForItem,
+}));
+
+vi.mock("@homarr/auth/client", () => ({
+ useSession: () => ({ data: { user: { permissions: mocks.permissions } } }),
+}));
+
+vi.mock("@homarr/notifications", () => ({
+ showSuccessNotification: mocks.showSuccessNotification,
+ showErrorNotification: mocks.showErrorNotification,
+}));
+
+vi.mock("@homarr/translation/client", () => ({
+ useI18n: () => (key: string) => key,
+}));
+
+vi.mock("./items/item-actions", () => ({
+ useItemActions: () => ({ createItem: mocks.createItem }),
+}));
+
+// Deferred resolvers for app.create, one per drop, so the test controls exactly when
+// each drop's work finishes, independently of the others.
+let createResolvers: ((app: { id: string; name: string }) => void)[] = [];
+
+vi.mock("@homarr/api/client", () => ({
+ clientApi: {
+ useUtils: () => ({
+ app: { invalidate: mocks.invalidateApp },
+ board: { getBoardByName: { getData: () => ({ name: "board" }) } },
+ }),
+ app: {
+ detectMetadata: { useMutation: () => ({ mutateAsync: mocks.detectMetadataAsync }) },
+ create: {
+ useMutation: () => ({
+ mutateAsync: () =>
+ new Promise<{ id: string; name: string }>((resolve) => {
+ createResolvers.push(resolve);
+ }),
+ }),
+ },
+ },
+ },
+}));
+
+import { BoardAppUrlDrop } from "./board-app-url-drop";
+
+const createDataTransfer = (url: string) => ({
+ types: ["text/uri-list"],
+ getData: (type: string) => (type === "text/uri-list" ? url : ""),
+});
+
+const dispatchWindowEvent = (name: string, dataTransfer: unknown) => {
+ const event = new Event(name, { bubbles: true, cancelable: true });
+ Object.defineProperty(event, "dataTransfer", { value: dataTransfer });
+ window.dispatchEvent(event);
+};
+
+const dropUrl = async (url: string) => {
+ await act(async () => dispatchWindowEvent("drop", createDataTransfer(url)));
+};
+
+describe("BoardAppUrlDrop", () => {
+ let container: HTMLDivElement;
+ let root: Root;
+
+ beforeAll(() => {
+ Object.defineProperty(window, "matchMedia", {
+ writable: true,
+ value: (media: string) => ({
+ matches: false,
+ media,
+ onchange: null,
+ addListener: () => undefined,
+ removeListener: () => undefined,
+ addEventListener: () => undefined,
+ removeEventListener: () => undefined,
+ dispatchEvent: () => false,
+ }),
+ });
+ });
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ mocks.isEditMode = true;
+ mocks.permissions = ["app-create"];
+ mocks.createItem.mockClear();
+ mocks.invalidateApp.mockClear();
+ mocks.detectMetadataAsync.mockReset().mockResolvedValue({ name: "App", iconUrl: null });
+ mocks.hasRoomForItem.mockReset().mockReturnValue(true);
+ mocks.showErrorNotification.mockClear();
+ mocks.showSuccessNotification.mockClear();
+ createResolvers = [];
+
+ act(() => {
+ root.render(createElement(MantineProvider, null, createElement(BoardAppUrlDrop)));
+ });
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ });
+
+ test("keeps the progress overlay visible until every concurrent drop finishes", async () => {
+ await dropUrl("https://first.example.com");
+ expect(container.textContent).toContain("board.urlDrop.resolving");
+
+ await dropUrl("https://second.example.com");
+ expect(container.textContent).toContain("board.urlDrop.resolving");
+ expect(createResolvers).toHaveLength(1);
+
+ // The first drop finishes while the second is still in flight: the overlay must stay.
+ await act(async () => createResolvers[0]?.({ id: "1", name: "First" }));
+ expect(container.textContent).toContain("board.urlDrop.resolving");
+ expect(createResolvers).toHaveLength(2);
+
+ // Only once the second (last remaining) drop finishes should the overlay disappear.
+ await act(async () => createResolvers[1]?.({ id: "2", name: "Second" }));
+ expect(container.textContent).not.toContain("board.urlDrop.resolving");
+ expect(mocks.createItem).toHaveBeenCalledTimes(2);
+ });
+
+ test("does not create an app when the board has no room for it", async () => {
+ mocks.hasRoomForItem.mockReturnValue(false);
+
+ await dropUrl("https://first.example.com");
+
+ expect(mocks.detectMetadataAsync).not.toHaveBeenCalled();
+ expect(createResolvers).toHaveLength(0);
+ expect(mocks.createItem).not.toHaveBeenCalled();
+ expect(mocks.showErrorNotification).toHaveBeenCalledWith(
+ expect.objectContaining({ message: "board.urlDrop.notification.full.message" }),
+ );
+ });
+});
diff --git a/apps/nextjs/src/components/board/board-app-url-drop.tsx b/apps/nextjs/src/components/board/board-app-url-drop.tsx
new file mode 100644
index 000000000..432eea997
--- /dev/null
+++ b/apps/nextjs/src/components/board/board-app-url-drop.tsx
@@ -0,0 +1,189 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { Loader, Overlay, Paper, Stack, Text, ThemeIcon } from "@mantine/core";
+import { IconLink } from "@tabler/icons-react";
+
+import { clientApi } from "@homarr/api/client";
+import { useSession } from "@homarr/auth/client";
+import { useRequiredBoard } from "@homarr/boards/context";
+import { useEditMode } from "@homarr/boards/edit-mode";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
+import { useI18n } from "@homarr/translation/client";
+
+import { hasRoomForItem } from "./items/actions/create-item";
+import { useItemActions } from "./items/item-actions";
+
+// Firefox sends text/x-moz-url (the url, then the page title on the next line) instead of text/uri-list.
+const urlTypes = ["text/uri-list", "text/x-moz-url"];
+
+// Files are not excluded: Edge adds an internet shortcut file to address bar drags.
+// Dropped files without a http(s) url are ignored by getDroppedUrl.
+const isUrlDrag = (dataTransfer: DataTransfer | null) =>
+ Boolean(dataTransfer?.types.some((type) => urlTypes.includes(type)));
+
+const getDroppedUrl = (dataTransfer: DataTransfer) => {
+ const candidate = urlTypes
+ .flatMap((type) => dataTransfer.getData(type).split(/\r?\n/))
+ .find((line) => line.trim() !== "" && !line.startsWith("#"))
+ ?.trim();
+ if (!candidate) return null;
+ try {
+ const url = new URL(candidate);
+ return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;
+ } catch {
+ return null;
+ }
+};
+
+/**
+ * Lets users drop a URL (e.g. from the browser address bar) onto a board in edit mode
+ * to create an app from the page title and favicon and add it to the board.
+ */
+export const BoardAppUrlDrop = () => {
+ const [isEditMode] = useEditMode();
+ const { data: session } = useSession();
+ const canCreateApp = session?.user.permissions.includes("app-create") ?? false;
+ const board = useRequiredBoard();
+ const [isDragging, setIsDragging] = useState(false);
+ const [isResolving, setIsResolving] = useState(false);
+ // Counts drops still in flight, so the overlay only hides once all of them are done
+ // instead of whichever drop happens to resolve first.
+ const pendingDropCountRef = useRef(0);
+ const dropQueueRef = useRef(Promise.resolve());
+ const editSessionRef = useRef<symbol | null>(null);
+ const { createItem } = useItemActions();
+ const utils = clientApi.useUtils();
+ const { mutateAsync: detectMetadataAsync } = clientApi.app.detectMetadata.useMutation();
+ const { mutateAsync: createAppAsync } = clientApi.app.create.useMutation();
+ const t = useI18n();
+ const isEnabled = isEditMode && canCreateApp;
+
+ useEffect(() => {
+ editSessionRef.current = isEnabled ? Symbol() : null;
+ return () => {
+ editSessionRef.current = null;
+ };
+ }, [board.name, isEnabled]);
+
+ const addAppFromUrlAsync = useCallback(
+ async (url: string) => {
+ const editSession = editSessionRef.current;
+ if (editSession === null) return;
+ pendingDropCountRef.current++;
+ setIsResolving(true);
+
+ // Serialize placement so two drops cannot both pass a capacity check for the
+ // same last position. Always inspect the current cache, not the render snapshot.
+ const pendingDrop = dropQueueRef.current.then(async () => {
+ if (editSessionRef.current !== editSession) return;
+ const checkCapacity = () => {
+ const currentBoard = utils.board.getBoardByName.getData({ name: board.name });
+ if (currentBoard && hasRoomForItem(currentBoard, "app")) return true;
+ showErrorNotification({
+ title: t("common.notification.create.error"),
+ message: t("board.urlDrop.notification.full.message"),
+ });
+ return false;
+ };
+
+ if (!checkCapacity()) return;
+ const metadata = await detectMetadataAsync({ href: url });
+ if (editSessionRef.current !== editSession || !checkCapacity()) return;
+ const app = await createAppAsync({ ...metadata, href: url, description: null, pingUrl: "" });
+ void utils.app.invalidate();
+ // Saving, cancelling or navigating must not place a late result on another
+ // board or in a newer edit session.
+ if (editSessionRef.current !== editSession) return;
+ createItem({ kind: "app", options: { appId: app.id } });
+ showSuccessNotification({
+ title: t("common.notification.create.success"),
+ message: t("board.urlDrop.notification.success.message", { name: app.name }),
+ });
+ });
+ dropQueueRef.current = pendingDrop.catch(() => undefined);
+
+ try {
+ await pendingDrop;
+ } catch {
+ showErrorNotification({
+ title: t("common.notification.create.error"),
+ message: t("app.page.create.notification.error.message"),
+ });
+ } finally {
+ pendingDropCountRef.current--;
+ if (pendingDropCountRef.current === 0) setIsResolving(false);
+ }
+ },
+ [board.name, createAppAsync, createItem, detectMetadataAsync, t, utils],
+ );
+
+ useEffect(() => {
+ if (!isEnabled) return;
+
+ // Drags that start inside Homarr (links, images) are not URLs to add.
+ let isInternalDrag = false;
+ let enterCount = 0;
+ const handleDragStart = () => (isInternalDrag = true);
+ const handleDragEnd = () => (isInternalDrag = false);
+ const handleDragEnter = (event: DragEvent) => {
+ if (isInternalDrag || !isUrlDrag(event.dataTransfer)) return;
+ enterCount++;
+ setIsDragging(true);
+ };
+ const handleDragLeave = (event: DragEvent) => {
+ if (isInternalDrag || !isUrlDrag(event.dataTransfer)) return;
+ enterCount = Math.max(0, enterCount - 1);
+ if (enterCount === 0) setIsDragging(false);
+ };
+ const handleDragOver = (event: DragEvent) => {
+ if (isInternalDrag || !isUrlDrag(event.dataTransfer) || !event.dataTransfer) return;
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "copy";
+ };
+ const handleDrop = (event: DragEvent) => {
+ if (isInternalDrag || !isUrlDrag(event.dataTransfer) || !event.dataTransfer) return;
+ // Prevent the browser from navigating away and discarding unsaved board changes.
+ event.preventDefault();
+ enterCount = 0;
+ setIsDragging(false);
+ const url = getDroppedUrl(event.dataTransfer);
+ if (url) void addAppFromUrlAsync(url);
+ };
+
+ window.addEventListener("dragstart", handleDragStart);
+ window.addEventListener("dragend", handleDragEnd);
+ window.addEventListener("dragenter", handleDragEnter);
+ window.addEventListener("dragleave", handleDragLeave);
+ window.addEventListener("dragover", handleDragOver);
+ window.addEventListener("drop", handleDrop);
+ return () => {
+ setIsDragging(false);
+ window.removeEventListener("dragstart", handleDragStart);
+ window.removeEventListener("dragend", handleDragEnd);
+ window.removeEventListener("dragenter", handleDragEnter);
+ window.removeEventListener("dragleave", handleDragLeave);
+ window.removeEventListener("dragover", handleDragOver);
+ window.removeEventListener("drop", handleDrop);
+ };
+ }, [addAppFromUrlAsync, isEnabled]);
+
+ if (!isDragging && !isResolving) return null;
+
+ return (
+ <Overlay fixed center blur={2} backgroundOpacity={0.35} zIndex={300}>
+ <Paper withBorder shadow="md" radius="md" p="lg">
+ <Stack align="center" gap="xs">
+ {isResolving ? (
+ <Loader size="md" />
+ ) : (
+ <ThemeIcon variant="light" size="xl" radius="xl">
+ <IconLink size={24} />
+ </ThemeIcon>
+ )}
+ <Text fw={500}>{t(isResolving ? "board.urlDrop.resolving" : "board.urlDrop.hint")}</Text>
+ </Stack>
+ </Paper>
+ </Overlay>
+ );
+};
diff --git a/apps/nextjs/src/components/board/items/actions/create-item.ts b/apps/nextjs/src/components/board/items/actions/create-item.ts
index 9b0f08d23..cb0985422 100644
--- a/apps/nextjs/src/components/board/items/actions/create-item.ts
+++ b/apps/nextjs/src/components/board/items/actions/create-item.ts
@@ -67,6 +67,19 @@ export const createItemCallback =
};
};
+/**
+ * Whether createItemCallback would actually place an item of this kind,
+ * so a caller that needs the result of a step before placement (for example persisting a
+ * record server side, which it cannot easily undo) can check first instead of after.
+ */
+export const hasRoomForItem = (board: Board, kind: WidgetKind, size?: { width: number; height: number }): boolean => {
+ try {
+ return createItemCallback({ kind, size })(board) !== board;
+ } catch {
+ return false;
+ }
+};
+
const defaultItemSize = { width: 1, height: 1 };
const getWidgetItemSize = (kind: WidgetKind) => widgetDefaultSizes[kind] ?? defaultItemSize;
diff --git a/apps/nextjs/src/components/board/items/actions/test/create-item.spec.ts b/apps/nextjs/src/components/board/items/actions/test/create-item.spec.ts
index ad753f8d1..991f46a62 100644
--- a/apps/nextjs/src/components/board/items/actions/test/create-item.spec.ts
+++ b/apps/nextjs/src/components/board/items/actions/test/create-item.spec.ts
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test, vi } from "vitest";
import * as boardContext from "@homarr/boards/context";
-import { createItemCallback } from "../create-item";
+import { createItemCallback, hasRoomForItem } from "../create-item";
import * as emptyPositionModule from "../empty-position";
import { BoardMockBuilder } from "./mocks/board-mock";
import { ContainerSectionMockBuilder } from "./mocks/container-section-mock";
@@ -268,4 +268,20 @@ describe("item actions create-item", () => {
}),
]);
});
+
+ test("hasRoomForItem reports true when a position is found", () => {
+ const board = new BoardMockBuilder().addEmptySection({ id: "canvas" }).build();
+ vi.spyOn(emptyPositionModule, "getFirstEmptyPosition").mockReturnValue({ xOffset: 0, yOffset: 0 });
+
+ expect(hasRoomForItem(board, "app")).toBe(true);
+ expect(hasRoomForItem({ ...board, sections: [] }, "app")).toBe(false);
+ expect(hasRoomForItem({ ...board, layouts: [] }, "app")).toBe(false);
+ });
+
+ test("hasRoomForItem reports false instead of throwing when the board is full", () => {
+ const board = new BoardMockBuilder().addEmptySection({ id: "canvas" }).build();
+ vi.spyOn(emptyPositionModule, "getFirstEmptyPosition").mockReturnValue(undefined);
+
+ expect(hasRoomForItem(board, "app")).toBe(false);
+ });
});
diff --git a/bun.lock b/bun.lock
index ec4a97ed3..0cf3cc88e 100644
--- a/bun.lock
+++ b/bun.lock
@@ -302,6 +302,7 @@
"@homarr/definitions": "workspace:^0.1.0",
"@homarr/docker": "workspace:^0.1.0",
"@homarr/icons": "workspace:^0.1.0",
+ "@homarr/image-proxy": "workspace:^0.1.0",
"@homarr/integrations": "workspace:^0.1.0",
"@homarr/ping": "workspace:^0.1.0",
"@homarr/redis": "workspace:^0.1.0",
diff --git a/packages/api/package.json b/packages/api/package.json
index 2ab8ff571..5c43983bc 100644
--- a/packages/api/package.json
+++ b/packages/api/package.json
@@ -43,6 +43,7 @@
"@homarr/definitions": "workspace:^0.1.0",
"@homarr/docker": "workspace:^0.1.0",
"@homarr/icons": "workspace:^0.1.0",
+ "@homarr/image-proxy": "workspace:^0.1.0",
"@homarr/integrations": "workspace:^0.1.0",
"@homarr/ping": "workspace:^0.1.0",
"@homarr/redis": "workspace:^0.1.0",
diff --git a/packages/api/src/router/app.ts b/packages/api/src/router/app.ts
index b31216b8c..aa546cdfa 100644
--- a/packages/api/src/router/app.ts
+++ b/packages/api/src/router/app.ts
@@ -3,14 +3,17 @@ import { z } from "zod/v4";
import type { Session } from "@homarr/auth";
import { createId } from "@homarr/common";
+import { env } from "@homarr/common/env";
import type { Database, InferSelectModel } from "@homarr/db";
import { asc, eq, inArray, like } from "@homarr/db";
import { apps, integrations } from "@homarr/db/schema";
import { selectAppSchema } from "@homarr/db/validationSchemas";
-import { getIconForName } from "@homarr/icons";
+import { fetchWebsiteMetadataAsync, getIconForName } from "@homarr/icons";
+import { ImageProxy } from "@homarr/image-proxy";
import { invalidateIntegrationResponseCacheAsync } from "@homarr/redis";
import { appCreateManySchema, appEditSchema, appManageSchema } from "@homarr/validation/app";
import { byIdSchema, paginatedSchema } from "@homarr/validation/common";
+import { iconsDetectFaviconSchema } from "@homarr/validation/icons";
import { convertIntersectionToZodObject } from "../schema-merger";
import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure, publicProcedure } from "../trpc";
@@ -221,6 +224,30 @@ export const appRouter = createTRPCRouter({
// TODO: breaking change necessary for removing appId property
return { appId: id, ...insertValues };
}),
+ // A mutation, so the website url travels in the request body and stays out of access logs.
+ detectMetadata: permissionRequiredProcedure
+ .requiresPermission("app-create")
+ .input(iconsDetectFaviconSchema)
+ .output(z.object({ name: z.string(), iconUrl: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const metadata = env.NO_EXTERNAL_CONNECTION
+ ? { title: null, iconUrl: null }
+ : await fetchWebsiteMetadataAsync(input.href);
+ const name = (metadata.title ?? new URL(input.href).hostname).slice(0, 64);
+ // Proxied so the browser always loads it from Homarr's own origin: the detected
+ // icon's own site can still block the direct link (mixed content, or a
+ // Cross-Origin-Resource-Policy header) even though the server fetched it fine.
+ const iconUrl = metadata.iconUrl
+ ? await new ImageProxy()
+ .createImageAsync(metadata.iconUrl, undefined, { persistent: true })
+ .catch(() => metadata.iconUrl)
+ : null;
+
+ return {
+ name,
+ iconUrl: iconUrl ?? getIconForName(ctx.db, name).sync()?.url ?? defaultIcon,
+ };
+ }),
createMany: permissionRequiredProcedure
.requiresPermission("app-create")
.input(appCreateManySchema)
diff --git a/packages/api/src/router/test/app.spec.ts b/packages/api/src/router/test/app.spec.ts
index b2368ef6d..367bc17c7 100644
--- a/packages/api/src/router/test/app.spec.ts
+++ b/packages/api/src/router/test/app.spec.ts
@@ -6,6 +6,7 @@ import { createId } from "@homarr/common";
import { apps } from "@homarr/db/schema";
import { createDb } from "@homarr/db/test";
import type { GroupPermissionKey } from "@homarr/definitions";
+import type * as IconsModule from "@homarr/icons";
import { appRouter } from "../app";
import * as appAccessControl from "../app/app-access-control";
@@ -13,6 +14,22 @@ import * as appAccessControl from "../app/app-access-control";
// Mock the auth module to return an empty session
vi.mock("@homarr/auth", () => ({ auth: () => ({}) as Session }));
+const { fetchWebsiteMetadataAsyncMock, createImageAsyncMock } = vi.hoisted(() => ({
+ fetchWebsiteMetadataAsyncMock: vi.fn(),
+ createImageAsyncMock: vi.fn(),
+}));
+
+// getIconForName keeps its real implementation, so only the network-dependent part is mocked
+vi.mock("@homarr/icons", async (importOriginal) => ({
+ ...(await importOriginal<typeof IconsModule>()),
+ fetchWebsiteMetadataAsync: fetchWebsiteMetadataAsyncMock,
+}));
+vi.mock("@homarr/image-proxy", () => ({
+ ImageProxy: class {
+ createImageAsync = createImageAsyncMock;
+ },
+}));
+
const createFakeAccessControl = (canAccess: boolean) =>
vi.fn(
class {
@@ -381,3 +398,74 @@ describe("delete should delete an app", () => {
expect(dbApp).toBeUndefined();
});
});
+
+describe("detectMetadata", () => {
+ test("refuses a user who may not create apps without detecting anything", async () => {
+ // Arrange
+ const caller = appRouter.createCaller({ db: createDb(), deviceType: undefined, session: createDefaultSession([]) });
+
+ // Act & Assert
+ await expect(caller.detectMetadata({ href: "https://app.example.com" })).rejects.toThrow("Permission denied");
+ expect(fetchWebsiteMetadataAsyncMock).not.toHaveBeenCalled();
+ });
+
+ test("proxies the detected icon so the tile never links the site directly", async () => {
+ // Arrange
+ fetchWebsiteMetadataAsyncMock.mockResolvedValueOnce({
+ title: "Example App",
+ iconUrl: "https://app.example.com/favicon.ico",
+ });
+ createImageAsyncMock.mockResolvedValueOnce("/api/image-proxy/abc123");
+ const caller = appRouter.createCaller({
+ db: createDb(),
+ deviceType: undefined,
+ session: createDefaultSession(["app-create"]),
+ });
+
+ // Act
+ const result = await caller.detectMetadata({ href: "https://app.example.com" });
+
+ // Assert
+ expect(result).toEqual({ name: "Example App", iconUrl: "/api/image-proxy/abc123" });
+ expect(createImageAsyncMock).toHaveBeenCalledWith("https://app.example.com/favicon.ico", undefined, {
+ persistent: true,
+ });
+ });
+
+ test("falls back to the site's own icon url when registering it with the proxy fails", async () => {
+ // Arrange
+ fetchWebsiteMetadataAsyncMock.mockResolvedValueOnce({
+ title: "Example App",
+ iconUrl: "https://app.example.com/favicon.ico",
+ });
+ createImageAsyncMock.mockRejectedValueOnce(new Error("proxy unavailable"));
+ const caller = appRouter.createCaller({
+ db: createDb(),
+ deviceType: undefined,
+ session: createDefaultSession(["app-create"]),
+ });
+
+ // Act
+ const result = await caller.detectMetadata({ href: "https://app.example.com" });
+
+ // Assert
+ expect(result).toEqual({ name: "Example App", iconUrl: "https://app.example.com/favicon.ico" });
+ });
+
+ test("does not register anything with the proxy when no icon was detected", async () => {
+ // Arrange
+ fetchWebsiteMetadataAsyncMock.mockResolvedValueOnce({ title: null, iconUrl: null });
+ const caller = appRouter.createCaller({
+ db: createDb(),
+ deviceType: undefined,
+ session: createDefaultSession(["app-create"]),
+ });
+
+ // Act
+ const result = await caller.detectMetadata({ href: "https://app.example.com" });
+
+ // Assert
+ expect(result.name).toBe("app.example.com");
+ expect(createImageAsyncMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/boards/src/context.spec.tsx b/packages/boards/src/context.spec.tsx
new file mode 100644
index 000000000..3b0abcee2
--- /dev/null
+++ b/packages/boards/src/context.spec.tsx
@@ -0,0 +1,89 @@
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import type { Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ isEditMode: false,
+ cancel: vi.fn(),
+ invalidate: vi.fn(),
+}));
+
+vi.mock("next/navigation", () => ({
+ usePathname: () => "/boards/home",
+}));
+
+vi.mock("./edit-mode", () => ({
+ useEditMode: () => [mocks.isEditMode, { open: vi.fn(), close: vi.fn() }],
+}));
+
+vi.mock("@homarr/api/client", () => ({
+ clientApi: {
+ useUtils: () => ({
+ board: {
+ getBoardByName: {
+ cancel: mocks.cancel,
+ invalidate: mocks.invalidate,
+ },
+ },
+ }),
+ board: {
+ getBoardByName: {
+ useQuery: (input: { name: string }) => ({ data: { name: input.name, layouts: [{ id: "base" }] } }),
+ },
+ },
+ },
+}));
+
+import { BoardProvider } from "./context";
+
+describe("BoardProvider", () => {
+ let container: HTMLDivElement;
+ let root: Root;
+
+ const renderBoard = () =>
+ act(() => {
+ root.render(
+ createElement(
+ BoardProvider,
+ {
+ initialBoard: { name: "home", layouts: [{ id: "base" }] } as never,
+ initialLayoutId: "base",
+ initialViewportWidth: 1280,
+ },
+ createElement("span", null, "board"),
+ ),
+ );
+ });
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ mocks.isEditMode = false;
+ mocks.cancel.mockClear();
+ mocks.invalidate.mockClear();
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ });
+
+ test("cancels an in-flight board refetch when edit mode turns on", async () => {
+ renderBoard();
+ expect(mocks.cancel).not.toHaveBeenCalled();
+
+ mocks.isEditMode = true;
+ renderBoard();
+
+ expect(mocks.cancel).toHaveBeenCalledWith({ name: "home" });
+ });
+
+ test("does not cancel while edit mode stays off", async () => {
+ renderBoard();
+ renderBoard();
+
+ expect(mocks.cancel).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/boards/src/context.tsx b/packages/boards/src/context.tsx
index e777217e6..2c521cbe1 100644
--- a/packages/boards/src/context.tsx
+++ b/packages/boards/src/context.tsx
@@ -7,6 +7,7 @@ import { usePathname } from "next/navigation";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
+import { useEditMode } from "./edit-mode";
import { boardViewportWidthCookieName, getLayoutIdForViewportWidth } from "./layout-selection";
import { updateBoardName } from "./updater";
@@ -70,6 +71,7 @@ export const BoardProvider = ({
initialViewportWidth: number;
layoutOverrideId?: string | null;
}>) => {
+ const [isEditMode] = useEditMode();
const { data } = clientApi.board.getBoardByName.useQuery(
{ name: initialBoard.name },
{
@@ -78,6 +80,9 @@ export const BoardProvider = ({
// avoid an immediate duplicate request while still surfacing remote edits
// when a user later returns to the board.
staleTime: 30_000,
+ // A refetch would replace the unsaved changes of edit mode with the saved board.
+ refetchOnWindowFocus: !isEditMode,
+ refetchOnReconnect: !isEditMode,
},
);
const currentLayout = useSyncExternalStore(
@@ -92,6 +97,14 @@ export const BoardProvider = ({
const pathname = usePathname();
const utils = clientApi.useUtils();
+ // A refetch started just before edit mode turned on (e.g. from window focus) is not
+ // covered by the refetchOnWindowFocus/refetchOnReconnect guard below, since that guard
+ // only stops new refetches. Cancelling here stops that in-flight one from resolving
+ // later and overwriting unsaved edit mode changes.
+ useEffect(() => {
+ if (isEditMode) void utils.board.getBoardByName.cancel({ name: initialBoard.name });
+ }, [isEditMode, utils, initialBoard.name]);
+
// Invalidate the board when the pathname changes
// This allows to refetch the board when it might have changed - e.g. if someone else added an item
useEffect(() => {
diff --git a/packages/core/package.json b/packages/core/package.json
index a94954bff..3a3a5a650 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -26,7 +26,8 @@
"./infrastructure/certificates/hostnames/db/postgresql": "./src/infrastructure/certificates/hostnames/db/postgresql.ts",
"./infrastructure/dns/init": "./src/infrastructure/dns/init.ts",
"./infrastructure/http": "./src/infrastructure/http/index.ts",
- "./infrastructure/http/timeout": "./src/infrastructure/http/timeout.ts"
+ "./infrastructure/http/timeout": "./src/infrastructure/http/timeout.ts",
+ "./infrastructure/http/request": "./src/infrastructure/http/request.ts"
},
"scripts": {
"clean": "rm -rf .turbo node_modules",
diff --git a/packages/icons/src/guarded-fetch.ts b/packages/core/src/infrastructure/http/guarded-fetch.ts
similarity index 90%
rename from packages/icons/src/guarded-fetch.ts
rename to packages/core/src/infrastructure/http/guarded-fetch.ts
index dceb8c3ca..ad0a479fa 100644
--- a/packages/icons/src/guarded-fetch.ts
+++ b/packages/core/src/infrastructure/http/guarded-fetch.ts
@@ -2,7 +2,7 @@ import { lookup } from "node:dns/promises";
import type { LookupFunction } from "node:net";
import { BlockList, isIP } from "node:net";
-import { createCertificateAgentAsync, fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
+import { createCertificateAgentAsync, fetchWithTrustedCertificatesAsync } from "./request";
type FetchResponse = Awaited<ReturnType<typeof fetchWithTrustedCertificatesAsync>>;
type Dispatcher = Awaited<ReturnType<typeof createCertificateAgentAsync>>;
@@ -14,6 +14,9 @@ interface ResolvedAddress {
interface GuardedFetchOptions {
headers?: Record<string, string>;
+ // Only server-registered integrations may trust their configured origin. Website
+ // metadata and page-declared icons must never set this exception.
+ trustedOrigin?: string;
// Bounds the lookup, the connect and the response headers of every hop, and how long
// the body may stay idle.
timeout: number;
@@ -161,8 +164,10 @@ const requestHopAsync = async (
const signal = options.signal ? AbortSignal.any([options.signal, timeout.signal]) : timeout.signal;
try {
- const addresses = await resolveAllowedAddressesAsync(url, signal);
- const dispatcher = await createPinnedDispatcherAsync(addresses, options.timeout);
+ const dispatcher =
+ options.trustedOrigin === url.origin && (url.protocol === "http:" || url.protocol === "https:")
+ ? await createCertificateAgentAsync(undefined, { bodyTimeout: options.timeout, logOriginOnly: true })
+ : await createPinnedDispatcherAsync(await resolveAllowedAddressesAsync(url, signal), options.timeout);
try {
const response = await fetchWithTrustedCertificatesAsync(url, {
headers: options.headers,
@@ -194,10 +199,11 @@ export const fetchGuardedAsync = async <TResult>(
handleResponse: (response: FetchResponse, url: URL) => Promise<TResult>,
): Promise<TResult> => {
let currentUrl = url;
+ let currentOptions = options;
for (let redirects = 0; ; redirects++) {
options.signal?.throwIfAborted();
- const { response, dispatcher } = await requestHopAsync(currentUrl, options);
+ const { response, dispatcher } = await requestHopAsync(currentUrl, currentOptions);
try {
const location = redirectStatuses.has(response.status) ? response.headers.get("location") : null;
@@ -211,6 +217,11 @@ export const fetchGuardedAsync = async <TResult>(
// undici refuses a url with credentials and puts all of it, query included, into its error.
target.username = "";
target.password = "";
+ // Custom integration headers can contain credentials too. Once a redirect
+ // leaves the origin, neither credentials nor its trust exception may follow.
+ if (target.origin !== currentUrl.origin) {
+ currentOptions = { ...currentOptions, headers: undefined, trustedOrigin: undefined };
+ }
currentUrl = target;
} finally {
await dispatcher.destroy();
diff --git a/packages/core/src/infrastructure/http/index.ts b/packages/core/src/infrastructure/http/index.ts
index 6bdbdb951..d0b2c3aa1 100644
--- a/packages/core/src/infrastructure/http/index.ts
+++ b/packages/core/src/infrastructure/http/index.ts
@@ -6,5 +6,6 @@ export {
createHttpsAgentAsync,
fetchWithTrustedCertificatesAsync,
} from "./request";
+export { cancelBodyAsync, fetchGuardedAsync } from "./guarded-fetch";
export { withHttpRequestSignalAsync, getHttpRequestSignal } from "./request-signal";
diff --git a/packages/icons/src/test/guarded-fetch.spec.ts b/packages/core/src/test/infrastructure/http/guarded-fetch.spec.ts
similarity index 95%
rename from packages/icons/src/test/guarded-fetch.spec.ts
rename to packages/core/src/test/infrastructure/http/guarded-fetch.spec.ts
index a9c707b56..10a850c36 100644
--- a/packages/icons/src/test/guarded-fetch.spec.ts
+++ b/packages/core/src/test/infrastructure/http/guarded-fetch.spec.ts
@@ -4,12 +4,14 @@ import type { LookupAddress } from "node:dns";
import type { LookupFunction } from "node:net";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
-import { createCertificateAgentAsync, fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
-
-import { fetchGuardedAsync } from "../guarded-fetch";
+import { fetchGuardedAsync } from "@homarr/core/infrastructure/http";
+import {
+ createCertificateAgentAsync,
+ fetchWithTrustedCertificatesAsync,
+} from "@homarr/core/infrastructure/http/request";
vi.mock("node:dns/promises", () => ({ lookup: vi.fn() }));
-vi.mock("@homarr/core/infrastructure/http", () => ({
+vi.mock("@homarr/core/infrastructure/http/request", () => ({
createCertificateAgentAsync: vi.fn(),
fetchWithTrustedCertificatesAsync: vi.fn(),
}));
@@ -246,10 +248,21 @@ describe("fetchGuardedAsync", () => {
"http://login.example.com/sign-in": createResponse(200),
});
- await expect(fetchStatusAsync("http://app.example.com/")).resolves.toEqual({
+ await expect(
+ fetchGuardedAsync(
+ new URL("http://app.example.com/"),
+ { timeout: 1_000, headers: { Authorization: "Bearer example", "X-Plex-Token": "example" } },
+ (response, finalUrl) => Promise.resolve({ status: response.status, url: finalUrl.href }),
+ ),
+ ).resolves.toEqual({
status: 200,
url: "http://login.example.com/sign-in",
});
+ expect(mockedFetch.mock.calls[0]?.[1]?.headers).toEqual({
+ Authorization: "Bearer example",
+ "X-Plex-Token": "example",
+ });
+ expect(mockedFetch.mock.calls[1]?.[1]?.headers).toBeUndefined();
expect(mockedLookup).toHaveBeenCalledWith("login.example.com", expect.anything());
await expect(lookupThroughPinnedAsync(pinnedLookupOfRequest(1), "login.example.com")).resolves.toBe("192.168.1.40");
});
diff --git a/packages/forms-collection/src/icon-picker/icon-picker.spec.ts b/packages/forms-collection/src/icon-picker/icon-picker.spec.ts
index 278ae2e1b..9024831a0 100644
--- a/packages/forms-collection/src/icon-picker/icon-picker.spec.ts
+++ b/packages/forms-collection/src/icon-picker/icon-picker.spec.ts
@@ -323,6 +323,21 @@ describe("IconPicker", () => {
expect(onChange).toHaveBeenCalledWith("https://app.example.com/favicon.ico");
});
+ test("offers the website icon suggestion alongside an app's existing remote icon", async () => {
+ faviconResult = { data: { url: "https://app.example.com/favicon.ico" } };
+ const input = await renderPicker(vi.fn(), {
+ value: directImageUrl,
+ faviconSourceUrl: "https://app.example.com",
+ });
+
+ await focusInput(input);
+
+ expect(detectFaviconQuery.mock.calls.at(-1)?.[1]).toMatchObject({ enabled: true });
+ expect(document.body.textContent).toContain("iconPicker.websiteIcon");
+ // The current icon is still previewed alongside the suggestion, not replaced by it.
+ expect(document.body.querySelector('[data-testid="direct-url-preview"]')).not.toBeNull();
+ });
+
test("keeps the keyboard selection on the same image when the website icon arrives later", async () => {
queryResult = { data: { icons: iconGroups, countIcons: 3 }, isLoading: false, isFetching: false, isError: false };
const onChange = vi.fn();
diff --git a/packages/icons/src/favicon-fetcher.ts b/packages/icons/src/favicon-fetcher.ts
index 916ccd6cd..1036ac7cf 100644
--- a/packages/icons/src/favicon-fetcher.ts
+++ b/packages/icons/src/favicon-fetcher.ts
@@ -1,8 +1,7 @@
import type { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
+import { cancelBodyAsync, fetchGuardedAsync } from "@homarr/core/infrastructure/http";
import { createLogger } from "@homarr/core/infrastructure/logs";
-import { cancelBodyAsync, fetchGuardedAsync } from "./guarded-fetch";
-
const logger = createLogger({ module: "faviconFetcher" });
type FetchResponse = Awaited<ReturnType<typeof fetchWithTrustedCertificatesAsync>>;
@@ -44,28 +43,41 @@ interface IconCandidate {
* them away from loopback and metadata addresses but lets them reach the local
* network, where self hosted apps usually run next to Homarr.
*/
-export const fetchFaviconUrlAsync = async (href: string): Promise<string | null> => {
+export const fetchFaviconUrlAsync = async (href: string): Promise<string | null> =>
+ (await fetchWebsiteMetadataAsync(href)).iconUrl;
+
+export interface WebsiteMetadata {
+ title: string | null;
+ iconUrl: string | null;
+}
+
+/**
+ * Resolves the title and icon of a website with the same requests and safeguards as
+ * fetchFaviconUrlAsync. Either value is `null` when it cannot be determined.
+ */
+export const fetchWebsiteMetadataAsync = async (href: string): Promise<WebsiteMetadata> => {
const websiteUrl = parseHttpUrl(href);
- if (websiteUrl === null) return null;
+ if (websiteUrl === null) return { title: null, iconUrl: null };
const deadline = new AbortController();
const timer = setTimeout(() => deadline.abort(new Error("Favicon detection timed out")), detectionTimeoutInMs);
try {
- return await detectFaviconUrlAsync(websiteUrl, deadline.signal);
+ return await detectWebsiteMetadataAsync(websiteUrl, deadline.signal);
} finally {
clearTimeout(timer);
}
};
-const detectFaviconUrlAsync = async (websiteUrl: URL, signal: AbortSignal): Promise<string | null> => {
+const detectWebsiteMetadataAsync = async (websiteUrl: URL, signal: AbortSignal): Promise<WebsiteMetadata> => {
const page = await fetchPageAsync(websiteUrl, signal);
+ const title = page?.html == null ? null : findTitle(page.html);
const declaredIconUrl = page?.html == null ? null : findDeclaredIconUrl(page.html, page.url);
- if (declaredIconUrl !== null) return declaredIconUrl;
+ if (declaredIconUrl !== null) return { title, iconUrl: declaredIconUrl };
// The well known icon belongs to the origin that served the page, which differs from the
// requested one when the app redirects across origins.
const wellKnownUrl = new URL("/favicon.ico", page?.url.origin ?? websiteUrl.origin);
- return (await isImageAsync(wellKnownUrl, signal)) ? wellKnownUrl.href : null;
+ return { title, iconUrl: (await isImageAsync(wellKnownUrl, signal)) ? wellKnownUrl.href : null };
};
// Credentials in the app url are never sent to the site, and leaving them out here keeps
@@ -159,6 +171,29 @@ const linkTagRegex = /<link\b[^<>]*>/gi;
const attributeRegex = /(?<![a-z-])([a-z-]+)\s*=\s*("([^"]*)"|'([^']*)'|([^\s"'>]+))/gi;
const sizeRegex = /(?<!\d)(\d+)x(\d+)/gi;
+// Like the link tag, the title tag and its text end at the next "<", so unclosed titles are
+// scanned once. Entities have a bounded length for the same reason.
+const titleRegex = /<title\b[^<>]*>([^<]*)/i;
+const entityRegex = /&(#x[\da-f]{1,6}|#\d{1,7}|[a-z]{2,8});/gi;
+const namedEntities: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
+const maximumTitleLength = 512;
+
+const findTitle = (html: string): string | null => {
+ const rawTitle = titleRegex.exec(html)?.[1]?.slice(0, maximumTitleLength);
+ if (rawTitle === undefined) return null;
+
+ const title = decodeEntities(rawTitle).replaceAll(/\s+/g, " ").trim();
+ return title.length > 0 ? title : null;
+};
+
+const decodeEntities = (text: string): string =>
+ text.replaceAll(entityRegex, (entity, name: string) => {
+ if (!name.startsWith("#")) return namedEntities[name.toLowerCase()] ?? entity;
+
+ const codePoint = name[1]?.toLowerCase() === "x" ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
+ return codePoint > 0 && codePoint <= 0x10ffff ? String.fromCodePoint(codePoint) : entity;
+ });
+
const findDeclaredIconUrl = (html: string, pageUrl: URL): string | null => {
const candidates: IconCandidate[] = [];
diff --git a/packages/icons/src/test/favicon-fetcher.spec.ts b/packages/icons/src/test/favicon-fetcher.spec.ts
index 59bb9d04f..8d18f6b5e 100644
--- a/packages/icons/src/test/favicon-fetcher.spec.ts
+++ b/packages/icons/src/test/favicon-fetcher.spec.ts
@@ -3,12 +3,15 @@ import { lookup } from "node:dns/promises";
import type { LookupAddress } from "node:dns";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
-import { createCertificateAgentAsync, fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
+import {
+ createCertificateAgentAsync,
+ fetchWithTrustedCertificatesAsync,
+} from "@homarr/core/infrastructure/http/request";
-import { fetchFaviconUrlAsync } from "../favicon-fetcher";
+import { fetchFaviconUrlAsync, fetchWebsiteMetadataAsync } from "../favicon-fetcher";
vi.mock("node:dns/promises", () => ({ lookup: vi.fn() }));
-vi.mock("@homarr/core/infrastructure/http", () => ({
+vi.mock("@homarr/core/infrastructure/http/request", () => ({
createCertificateAgentAsync: vi.fn(),
fetchWithTrustedCertificatesAsync: vi.fn(),
}));
@@ -127,16 +130,17 @@ describe("fetchFaviconUrlAsync", () => {
vi.useRealTimers();
});
- test("prefers the apple touch icon and resolves it to an absolute url", async () => {
+ test("normalizes the title and prefers the absolute apple touch icon in the same request", async () => {
mockResponses({
[websiteUrl]: createPage(
- '<link rel="icon" href="/favicon-16.png" sizes="16x16"><link rel="apple-touch-icon" href="touch.png">',
+ '<title> My\n App &amp; &#x1f680; &#33; </title><link rel="icon" href="/favicon-16.png" sizes="16x16"><link rel="apple-touch-icon" href="touch.png">',
),
});
- const result = await fetchFaviconUrlAsync("https://app.example.com");
+ const result = await fetchWebsiteMetadataAsync("https://app.example.com");
- expect(result).toBe("https://app.example.com/touch.png");
+ expect(result).toEqual({ title: "My App & 🚀 !", iconUrl: "https://app.example.com/touch.png" });
+ expect(mockedFetch).toHaveBeenCalledTimes(1);
});
test("prefers the icon with the largest declared size", async () => {
@@ -164,13 +168,13 @@ describe("fetchFaviconUrlAsync", () => {
test("falls back to the well known favicon when the page declares no icon", async () => {
mockResponses({
- "https://app.example.com/dashboard": createPage(""),
+ "https://app.example.com/dashboard": createPage("<title> \n </title>"),
[faviconUrl]: createResponse({ contentType: "image/x-icon", body: "binary" }),
});
- const result = await fetchFaviconUrlAsync("https://app.example.com/dashboard");
+ const result = await fetchWebsiteMetadataAsync("https://app.example.com/dashboard");
- expect(result).toBe(faviconUrl);
+ expect(result).toEqual({ title: null, iconUrl: faviconUrl });
});
test("falls back to the well known favicon of the origin that answered the request", async () => {
diff --git a/packages/image-proxy/src/index.ts b/packages/image-proxy/src/index.ts
index f2366654f..7553ea349 100644
--- a/packages/image-proxy/src/index.ts
+++ b/packages/image-proxy/src/index.ts
@@ -3,8 +3,14 @@ import { setImmediate } from "node:timers/promises";
import { createId, formatBytes } from "@homarr/common";
import { env } from "@homarr/common/env";
-import { decryptSecret, encryptSecret, readBoundedResponseAsync } from "@homarr/common/server";
-import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
+import {
+ createKeyedFingerprint,
+ decryptSecret,
+ encryptSecret,
+ readBoundedResponseAsync,
+ verifyKeyedFingerprint,
+} from "@homarr/common/server";
+import { cancelBodyAsync, fetchGuardedAsync } from "@homarr/core/infrastructure/http";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import { createGetSetChannel } from "@homarr/redis";
@@ -39,7 +45,20 @@ export class ImageProxy {
return this.hmacKey;
}
- public async createImageAsync(url: string, headers?: Record<string, string>): Promise<string> {
+ public async createImageAsync(
+ url: string,
+ headers?: Record<string, string>,
+ options?: { persistent?: boolean },
+ ): Promise<string> {
+ if (options?.persistent) {
+ if (headers) throw new Error("Persistent image URLs cannot contain integration headers");
+ // App icons are saved in the database, unlike periodically refreshed integration
+ // images. A signed, encrypted source survives Redis expiry and server restarts.
+ const encryptedUrl = encryptSecret(url);
+ const signature = createKeyedFingerprint(`image-proxy:persistent:${encryptedUrl}`);
+ return this.createImageUrl(`persistent.${signature}.${encryptedUrl}`);
+ }
+
const existingId = await this.getExistingIdAsync(url, headers);
if (existingId) {
logger.debug("Image already exists in the proxy", {
@@ -100,36 +119,45 @@ export class ImageProxy {
);
try {
signal.throwIfAborted();
- const response = await fetchWithTrustedCertificatesAsync(urlAndHeaders.url, {
- headers: urlAndHeaders.headers ?? {},
- signal,
- });
+ // Page-declared icons are untrusted on every fetch, including redirects and DNS
+ // changes. Existing integration images retain loopback and HTTP proxy support
+ // only on their registered origin; redirects elsewhere lose credentials and trust.
+ return await fetchGuardedAsync(
+ new URL(urlAndHeaders.url),
+ {
+ headers: urlAndHeaders.headers ?? undefined,
+ trustedOrigin: urlAndHeaders.trustedOrigin,
+ timeout: IMAGE_PROXY_TIMEOUT_MS,
+ signal,
+ },
+ async (response) => {
+ if (!response.ok) {
+ await cancelBodyAsync(response);
+ logger.error(
+ new ErrorWithMetadata("Failed to fetch image", {
+ id,
+ url: this.redactUrl(urlAndHeaders.url),
+ headers: this.redactHeaders(urlAndHeaders.headers),
+ proxyUrl,
+ statusCode: response.status,
+ }),
+ );
+ return { error: "upstream-error", statusCode: response.status };
+ }
- if (!response.ok) {
- void response.body?.cancel().catch(() => undefined);
- logger.error(
- new ErrorWithMetadata("Failed to fetch image", {
+ const body = await readBoundedResponseAsync(response, IMAGE_PROXY_MAX_BYTES, "Image", signal);
+ const image = body?.buffer ?? new ArrayBuffer(0);
+ logger.debug("Forwarding image succeeded", {
id,
url: this.redactUrl(urlAndHeaders.url),
headers: this.redactHeaders(urlAndHeaders.headers),
proxyUrl,
- statusCode: response.status,
- }),
- );
- return { error: "upstream-error", statusCode: response.status };
- }
-
- const body = await readBoundedResponseAsync(response, IMAGE_PROXY_MAX_BYTES, "Image", signal);
- const image = body?.buffer ?? new ArrayBuffer(0);
- logger.debug("Forwarding image succeeded", {
- id,
- url: this.redactUrl(urlAndHeaders.url),
- headers: this.redactHeaders(urlAndHeaders.headers),
- proxyUrl,
- size: formatBytes(image.byteLength),
- });
+ size: formatBytes(image.byteLength),
+ });
- return { image, contentType: response.headers.get("content-type") };
+ return { image, contentType: response.headers.get("content-type") };
+ },
+ );
} catch (error) {
logger.error(
new ErrorWithMetadata(
@@ -155,6 +183,19 @@ export class ImageProxy {
}
private async getImageUrlAndHeadersAsync(id: string) {
+ if (id.startsWith("persistent.")) {
+ const parts = /^persistent\.([a-f0-9]{64})\.([a-f0-9]+)\.([a-f0-9]{32})$/.exec(id);
+ if (!parts) return null;
+ const [, signature = "", ciphertext = "", initializationVector = ""] = parts;
+ const encryptedUrl = `${ciphertext}.${initializationVector}` as const;
+ if (!verifyKeyedFingerprint(`image-proxy:persistent:${encryptedUrl}`, signature)) return null;
+ try {
+ return { url: decryptSecret(encryptedUrl), headers: null, trustedOrigin: undefined };
+ } catch {
+ return null;
+ }
+ }
+
const urlHeaderChannel = createUrlByIdChannel(id);
const urlHeader = await urlHeaderChannel.getAsync();
if (!urlHeader) {
@@ -162,9 +203,11 @@ export class ImageProxy {
return null;
}
+ const url = decryptSecret(urlHeader.url);
return {
- url: decryptSecret(urlHeader.url),
+ url,
headers: JSON.parse(decryptSecret(urlHeader.headers)) as Record<string, string> | null,
+ trustedOrigin: new URL(url).origin,
};
}
diff --git a/packages/image-proxy/src/test/index.spec.ts b/packages/image-proxy/src/test/index.spec.ts
new file mode 100644
index 000000000..39051c09a
--- /dev/null
+++ b/packages/image-proxy/src/test/index.spec.ts
@@ -0,0 +1,178 @@
+// @vitest-environment node
+import { lookup } from "node:dns/promises";
+import type { LookupAddress } from "node:dns";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+process.env.SECRET_ENCRYPTION_KEY ??= "0".repeat(64);
+
+const mocks = vi.hoisted(() => ({ store: new Map<string, { value: unknown; expiresAt: number | null }>() }));
+
+vi.mock("node:dns/promises", () => ({ lookup: vi.fn() }));
+vi.mock("@homarr/core/infrastructure/http/request", () => ({
+ createCertificateAgentAsync: vi.fn(() => Promise.resolve({ destroy: () => Promise.resolve() })),
+ fetchWithTrustedCertificatesAsync: vi.fn(),
+}));
+vi.mock("@homarr/core/infrastructure/logs", () => ({
+ createLogger: () => ({ debug: vi.fn(), error: vi.fn(), warn: vi.fn(), info: vi.fn() }),
+}));
+vi.mock("@homarr/redis", () => ({
+ createGetSetChannel: (name: string) => ({
+ getAsync: async () => {
+ const stored = mocks.store.get(name);
+ if (!stored) return null;
+ if (stored.expiresAt !== null && Date.now() >= stored.expiresAt) {
+ mocks.store.delete(name);
+ return null;
+ }
+ return stored.value;
+ },
+ setAsync: async (value: unknown, options?: { ttlSeconds?: number }) => {
+ mocks.store.set(name, { value, expiresAt: options?.ttlSeconds ? Date.now() + options.ttlSeconds * 1_000 : null });
+ },
+ }),
+}));
+
+const { createCertificateAgentAsync, fetchWithTrustedCertificatesAsync } =
+ await import("@homarr/core/infrastructure/http/request");
+const { ImageProxy } = await import("../index");
+
+const mockedLookup = vi.mocked(lookup as unknown as (hostname: string) => Promise<LookupAddress[]>);
+const mockedFetch = vi.mocked(fetchWithTrustedCertificatesAsync);
+const mockedCreateAgent = vi.mocked(createCertificateAgentAsync);
+
+const encoder = new TextEncoder();
+
+const createResponse = (status: number, options: { location?: string; contentType?: string; body?: string } = {}) => {
+ const bytes = options.body !== undefined ? encoder.encode(options.body) : undefined;
+ let delivered = false;
+ return {
+ status,
+ ok: status >= 200 && status < 300,
+ headers: {
+ get: (name: string) => {
+ const key = name.toLowerCase();
+ if (key === "location") return options.location ?? null;
+ if (key === "content-type") return options.contentType ?? null;
+ return null;
+ },
+ },
+ body: {
+ cancel: () => Promise.resolve(),
+ getReader: () => ({
+ read: () => {
+ if (!bytes || delivered) return Promise.resolve({ done: true });
+ delivered = true;
+ return Promise.resolve({ done: false, value: bytes });
+ },
+ cancel: () => Promise.resolve(),
+ }),
+ },
+ };
+};
+
+const mockDns = (addressesByHostname: Record<string, string[]>) => {
+ mockedLookup.mockImplementation((hostname) => {
+ const addresses = addressesByHostname[hostname];
+ if (addresses === undefined) return Promise.reject(new Error(`getaddrinfo ENOTFOUND ${hostname}`));
+ return Promise.resolve(addresses.map((address) => ({ address, family: address.includes(":") ? 6 : 4 })));
+ });
+};
+
+const mockResponses = (responsesByUrl: Record<string, ReturnType<typeof createResponse>>) => {
+ mockedFetch.mockImplementation((input) => {
+ const url = input instanceof URL ? input.href : String(input);
+ const response = responsesByUrl[url];
+ return response === undefined
+ ? Promise.reject(new Error(`Unexpected request to ${url}`))
+ : // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ Promise.resolve(response as any);
+ });
+};
+
+describe("ImageProxy.forwardImageAsync", () => {
+ beforeEach(() => {
+ mocks.store.clear();
+ mockedLookup.mockReset();
+ mockedFetch.mockReset();
+ mockedCreateAgent.mockClear();
+ });
+
+ test("forwards a persistent image after its Redis registration is lost", async () => {
+ const imageProxy = new ImageProxy();
+ mockResponses({ "http://192.168.1.10/icon.png": createResponse(200, { contentType: "image/png", body: "img" }) });
+ const proxyUrl = await imageProxy.createImageAsync("http://192.168.1.10/icon.png", undefined, { persistent: true });
+ const id = proxyUrl.split("/").pop() as string;
+ mocks.store.clear();
+
+ const result = await new ImageProxy().forwardImageAsync(id);
+
+ expect(result).toMatchObject({ contentType: "image/png" });
+ expect("image" in result && new TextDecoder().decode(result.image)).toBe("img");
+ expect(proxyUrl).not.toContain("192.168.1.10");
+ const tamperedId = `${id.slice(0, -1)}${id.endsWith("0") ? "1" : "0"}`;
+ await expect(imageProxy.forwardImageAsync(tamperedId)).resolves.toEqual({ error: "not-found" });
+ expect(mockedFetch).toHaveBeenCalledTimes(1);
+ });
+
+ test("refuses to forward an image whose registered url resolves to a blocked address", async () => {
+ const imageProxy = new ImageProxy();
+ mockDns({ "metadata.internal": ["169.254.169.254"] });
+ const proxyUrl = await imageProxy.createImageAsync("http://metadata.internal/latest/meta-data/", undefined, {
+ persistent: true,
+ });
+ const id = proxyUrl.split("/").pop() as string;
+
+ const result = await imageProxy.forwardImageAsync(id);
+
+ expect(result).toEqual({ error: "fetch-error" });
+ expect(mockedFetch).not.toHaveBeenCalled();
+ });
+
+ test("refuses to forward when a redirect points at a blocked address", async () => {
+ const imageProxy = new ImageProxy();
+ mockResponses({
+ "http://192.168.1.10/icon.png": createResponse(302, { location: "http://169.254.169.254/latest/meta-data/" }),
+ });
+ const proxyUrl = await imageProxy.createImageAsync("http://192.168.1.10/icon.png", undefined, { persistent: true });
+ const id = proxyUrl.split("/").pop() as string;
+
+ const result = await imageProxy.forwardImageAsync(id);
+
+ expect(result).toEqual({ error: "fetch-error" });
+ expect(mockedFetch).toHaveBeenCalledTimes(1);
+ });
+
+ test("still allows a private network address, for self hosted integrations", async () => {
+ const imageProxy = new ImageProxy();
+ mockResponses({
+ "http://192.168.1.50:32400/photo": createResponse(200, { contentType: "image/jpeg", body: "poster" }),
+ });
+ const proxyUrl = await imageProxy.createImageAsync("http://192.168.1.50:32400/photo", {
+ "X-Plex-Token": "secret",
+ });
+ const id = proxyUrl.split("/").pop() as string;
+
+ const result = await imageProxy.forwardImageAsync(id);
+
+ expect(result).toMatchObject({ contentType: "image/jpeg" });
+ expect(mockedFetch).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ headers: { "X-Plex-Token": "secret" } }),
+ );
+
+ mockResponses({
+ "http://127.0.0.1:32400/photo": createResponse(200, { contentType: "image/jpeg", body: "poster" }),
+ });
+ const loopbackUrl = await imageProxy.createImageAsync("http://127.0.0.1:32400/photo", { "X-Plex-Token": "secret" });
+ await expect(imageProxy.forwardImageAsync(loopbackUrl.split("/").pop() as string)).resolves.toMatchObject({
+ contentType: "image/jpeg",
+ });
+ });
+
+ test("reports not-found for an unregistered id", async () => {
+ const imageProxy = new ImageProxy();
+
+ await expect(imageProxy.forwardImageAsync("unknown-id")).resolves.toEqual({ error: "not-found" });
+ expect(mockedFetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/translation/src/lang/en.json b/packages/translation/src/lang/en.json
index 60c4f76c0..b0e489e6c 100644
--- a/packages/translation/src/lang/en.json
+++ b/packages/translation/src/lang/en.json
@@ -6075,6 +6075,18 @@
"addApp": "Add app",
"connectService": "Connect service"
},
+ "urlDrop": {
+ "hint": "Drop to add as an app",
+ "resolving": "Adding app…",
+ "notification": {
+ "success": {
+ "message": "{name} was added to the board"
+ },
+ "full": {
+ "message": "Your board is full"
+ }
+ }
+ },
"setupChecklist": {
"title": "Make this board useful",
"description": "Pick up where you left off. Progress follows the content already on this board.",