A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.
fix(board): isolate dropped icons and preserve editable drops (#7300)
Thomas907311b25cb8
diff --git a/apps/nextjs/src/app/api/image-proxy/[id]/route.ts b/apps/nextjs/src/app/api/image-proxy/[id]/route.tsindex 13c900921..29c73065d 100644--- a/apps/nextjs/src/app/api/image-proxy/[id]/route.ts+++ b/apps/nextjs/src/app/api/image-proxy/[id]/route.ts@@ -17,6 +17,8 @@ export const GET = async (request: Request, props: { params: Promise<{ id: strin});}+ if ("redirectUrl" in result) return Response.redirect(result.redirectUrl);+return new Response(result.image, {headers: {"Cache-Control": "public, max-age=3600, immutable", // Cache for 1 hourdiff --git a/apps/nextjs/src/components/board/board-app-url-drop.tsx b/apps/nextjs/src/components/board/board-app-url-drop.tsxindex 432eea997..3c52105ef 100644--- a/apps/nextjs/src/components/board/board-app-url-drop.tsx+++ b/apps/nextjs/src/components/board/board-app-url-drop.tsx@@ -22,6 +22,11 @@ const urlTypes = ["text/uri-list", "text/x-moz-url"];const isUrlDrag = (dataTransfer: DataTransfer | null) =>Boolean(dataTransfer?.types.some((type) => urlTypes.includes(type)));+const isEditableTarget = (target: EventTarget | null) =>+ target instanceof Element &&+ target.closest("input, textarea, select, [contenteditable]:not([contenteditable='false']), [role='textbox']") !==+ null;+const getDroppedUrl = (dataTransfer: DataTransfer) => {const candidate = urlTypes.flatMap((type) => dataTransfer.getData(type).split(/\r?\n/))@@ -129,7 +134,7 @@ export const BoardAppUrlDrop = () => {const handleDragEnter = (event: DragEvent) => {if (isInternalDrag || !isUrlDrag(event.dataTransfer)) return;enterCount++;- setIsDragging(true);+ setIsDragging(!event.defaultPrevented && !isEditableTarget(event.target));};const handleDragLeave = (event: DragEvent) => {if (isInternalDrag || !isUrlDrag(event.dataTransfer)) return;@@ -138,15 +143,16 @@ export const BoardAppUrlDrop = () => {};const handleDragOver = (event: DragEvent) => {if (isInternalDrag || !isUrlDrag(event.dataTransfer) || !event.dataTransfer) return;+ if (event.defaultPrevented || isEditableTarget(event.target)) 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);+ if (event.defaultPrevented || isEditableTarget(event.target)) return;+ event.preventDefault();const url = getDroppedUrl(event.dataTransfer);if (url) void addAppFromUrlAsync(url);};@@ -171,7 +177,14 @@ export const BoardAppUrlDrop = () => {if (!isDragging && !isResolving) return null;return (- <Overlay fixed center blur={2} backgroundOpacity={0.35} zIndex={300}>+ <Overlay+ fixed+ center+ blur={2}+ backgroundOpacity={0.35}+ zIndex={300}+ style={{ pointerEvents: isResolving ? "auto" : "none" }}+ ><Paper withBorder shadow="md" radius="md" p="lg"><Stack align="center" gap="xs">{isResolving ? (diff --git a/bun.lock b/bun.lockindex 12382bdb2..bf1390b82 100644--- a/bun.lock+++ b/bun.lock@@ -302,7 +302,6 @@"@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.jsonindex 5c43983bc..2ab8ff571 100644--- a/packages/api/package.json+++ b/packages/api/package.json@@ -43,7 +43,6 @@"@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.tsindex aa546cdfa..f0f3e8a7f 100644--- a/packages/api/src/router/app.ts+++ b/packages/api/src/router/app.ts@@ -9,7 +9,6 @@ import { asc, eq, inArray, like } from "@homarr/db";import { apps, integrations } from "@homarr/db/schema";import { selectAppSchema } from "@homarr/db/validationSchemas";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";@@ -234,18 +233,9 @@ export const appRouter = createTRPCRouter({? { 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,+ iconUrl: metadata.iconUrl ?? getIconForName(ctx.db, name).sync()?.url ?? defaultIcon,};}),createMany: permissionRequiredProcedurediff --git a/packages/api/src/router/test/app.spec.ts b/packages/api/src/router/test/app.spec.tsindex 367bc17c7..9ba26c1e3 100644--- a/packages/api/src/router/test/app.spec.ts+++ b/packages/api/src/router/test/app.spec.ts@@ -14,9 +14,8 @@ import * as appAccessControl from "../app/app-access-control";// Mock the auth module to return an empty sessionvi.mock("@homarr/auth", () => ({ auth: () => ({}) as Session }));-const { fetchWebsiteMetadataAsyncMock, createImageAsyncMock } = vi.hoisted(() => ({+const { fetchWebsiteMetadataAsyncMock } = vi.hoisted(() => ({fetchWebsiteMetadataAsyncMock: vi.fn(),- createImageAsyncMock: vi.fn(),}));// getIconForName keeps its real implementation, so only the network-dependent part is mocked@@ -24,11 +23,6 @@ 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(@@ -409,13 +403,12 @@ describe("detectMetadata", () => {expect(fetchWebsiteMetadataAsyncMock).not.toHaveBeenCalled();});- test("proxies the detected icon so the tile never links the site directly", async () => {+ test("returns the detected icon URL without registering a server-side fetch", async () => {// ArrangefetchWebsiteMetadataAsyncMock.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,@@ -426,19 +419,15 @@ describe("detectMetadata", () => {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,- });+ expect(result).toEqual({ name: "Example App", iconUrl: "https://app.example.com/favicon.ico" });});- test("falls back to the site's own icon url when registering it with the proxy fails", async () => {+ test("leaves page-declared LAN icon requests to the browser", async () => {// ArrangefetchWebsiteMetadataAsyncMock.mockResolvedValueOnce({title: "Example App",- iconUrl: "https://app.example.com/favicon.ico",+ iconUrl: "http://192.168.1.10/private",});- createImageAsyncMock.mockRejectedValueOnce(new Error("proxy unavailable"));const caller = appRouter.createCaller({db: createDb(),deviceType: undefined,@@ -449,10 +438,10 @@ describe("detectMetadata", () => {const result = await caller.detectMetadata({ href: "https://app.example.com" });// Assert- expect(result).toEqual({ name: "Example App", iconUrl: "https://app.example.com/favicon.ico" });+ expect(result).toEqual({ name: "Example App", iconUrl: "http://192.168.1.10/private" });});- test("does not register anything with the proxy when no icon was detected", async () => {+ test("uses the hostname when no title was detected", async () => {// ArrangefetchWebsiteMetadataAsyncMock.mockResolvedValueOnce({ title: null, iconUrl: null });const caller = appRouter.createCaller({@@ -466,6 +455,5 @@ describe("detectMetadata", () => {// Assertexpect(result.name).toBe("app.example.com");- expect(createImageAsyncMock).not.toHaveBeenCalled();});});diff --git a/packages/image-proxy/src/index.ts b/packages/image-proxy/src/index.tsindex 7553ea349..6b27b8772 100644--- a/packages/image-proxy/src/index.ts+++ b/packages/image-proxy/src/index.ts@@ -3,13 +3,7 @@ import { setImmediate } from "node:timers/promises";import { createId, formatBytes } from "@homarr/common";import { env } from "@homarr/common/env";-import {- createKeyedFingerprint,- decryptSecret,- encryptSecret,- readBoundedResponseAsync,- verifyKeyedFingerprint,-} from "@homarr/common/server";+import { 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";@@ -30,6 +24,7 @@ const createUrlByIdChannel = (id: string) =>export type ForwardImageResult =| { image: ArrayBuffer; contentType: string | null }+ | { redirectUrl: string }| { error: "not-found" }| { error: "upstream-error"; statusCode: number }| { error: "fetch-error" };@@ -45,20 +40,7 @@ export class ImageProxy {return this.hmacKey;}- 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}`);- }-+ public async createImageAsync(url: string, headers?: Record<string, string>): Promise<string> {const existingId = await this.getExistingIdAsync(url, headers);if (existingId) {logger.debug("Image already exists in the proxy", {@@ -105,6 +87,7 @@ export class ImageProxy {}public async forwardImageAsync(id: string, requestSignal?: AbortSignal): Promise<ForwardImageResult> {+ if (id.startsWith("persistent.")) return this.getPersistentImageRedirect(id);const urlAndHeaders = await this.getImageUrlAndHeadersAsync(id);if (!urlAndHeaders) {return { error: "not-found" };@@ -119,9 +102,6 @@ export class ImageProxy {);try {signal.throwIfAborted();- // 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),{@@ -182,20 +162,22 @@ export class ImageProxy {return `/api/image-proxy/${id}`;}- 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;- }+ private getPersistentImageRedirect(id: string): ForwardImageResult {+ const parts = /^persistent\.([a-f0-9]{64})\.([a-f0-9]+)\.([a-f0-9]{32})$/.exec(id);+ if (!parts) return { error: "not-found" };+ const [, signature = "", ciphertext = "", initializationVector = ""] = parts;+ const encryptedUrl = `${ciphertext}.${initializationVector}` as const;+ if (!verifyKeyedFingerprint(`image-proxy:persistent:${encryptedUrl}`, signature)) return { error: "not-found" };+ try {+ const url = URL.parse(decryptSecret(encryptedUrl));+ if (!url || (url.protocol !== "http:" && url.protocol !== "https:")) return { error: "not-found" };+ return { redirectUrl: url.href };+ } catch {+ return { error: "not-found" };}+ }+ private async getImageUrlAndHeadersAsync(id: string) {const urlHeaderChannel = createUrlByIdChannel(id);const urlHeader = await urlHeaderChannel.getAsync();if (!urlHeader) {diff --git a/packages/image-proxy/src/test/index.spec.ts b/packages/image-proxy/src/test/index.spec.tsindex 39051c09a..b816e3245 100644--- a/packages/image-proxy/src/test/index.spec.ts+++ b/packages/image-proxy/src/test/index.spec.ts@@ -34,6 +34,7 @@ vi.mock("@homarr/redis", () => ({const { createCertificateAgentAsync, fetchWithTrustedCertificatesAsync } =await import("@homarr/core/infrastructure/http/request");+const { createKeyedFingerprint, encryptSecret } = await import("@homarr/common/server");const { ImageProxy } = await import("../index");const mockedLookup = vi.mocked(lookup as unknown as (hostname: string) => Promise<LookupAddress[]>);@@ -42,6 +43,12 @@ const mockedCreateAgent = vi.mocked(createCertificateAgentAsync);const encoder = new TextEncoder();+const createPersistentImageId = (url: string) => {+ const encryptedUrl = encryptSecret(url);+ const signature = createKeyedFingerprint(`image-proxy:persistent:${encryptedUrl}`);+ return `persistent.${signature}.${encryptedUrl}`;+};+const createResponse = (status: number, options: { location?: string; contentType?: string; body?: string } = {}) => {const bytes = options.body !== undefined ? encoder.encode(options.body) : undefined;let delivered = false;@@ -97,49 +104,44 @@ describe("ImageProxy.forwardImageAsync", () => {mockedCreateAgent.mockClear();});- test("forwards a persistent image after its Redis registration is lost", async () => {+ test("redirects an existing persistent image to its source without fetching it", 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;+ const id = createPersistentImageId("http://192.168.1.10/icon.png");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");+ expect(result).toEqual({ redirectUrl: "http://192.168.1.10/icon.png" });+ expect(id).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);+ expect(mockedFetch).not.toHaveBeenCalled();});- test("refuses to forward an image whose registered url resolves to a blocked address", async () => {+ test("does not request a persistent image whose source 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 id = createPersistentImageId("http://metadata.internal/latest/meta-data/");const result = await imageProxy.forwardImageAsync(id);- expect(result).toEqual({ error: "fetch-error" });+ expect(result).toEqual({ redirectUrl: "http://metadata.internal/latest/meta-data/" });+ expect(mockedLookup).not.toHaveBeenCalled();expect(mockedFetch).not.toHaveBeenCalled();});- test("refuses to forward when a redirect points at a blocked address", async () => {+ test("does not follow upstream redirects for a persistent image", 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 id = createPersistentImageId("http://192.168.1.10/icon.png");const result = await imageProxy.forwardImageAsync(id);- expect(result).toEqual({ error: "fetch-error" });- expect(mockedFetch).toHaveBeenCalledTimes(1);+ expect(result).toEqual({ redirectUrl: "http://192.168.1.10/icon.png" });+ expect(mockedFetch).not.toHaveBeenCalled();});test("still allows a private network address, for self hosted integrations", async () => {