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(app-form): suggest website icons (#6562)

Junker der Provinz6871a35b1531
diff --git a/apps/docs/docs/advanced/icons/index.mdx b/apps/docs/docs/advanced/icons/index.mdx
index 294c39f65..ed8258050 100644
--- a/apps/docs/docs/advanced/icons/index.mdx
+++ b/apps/docs/docs/advanced/icons/index.mdx
@@ -35,6 +35,10 @@ Icons that are high quality and printable ([SVG](https://wikipedia.org/wiki/Scal
You can clear the selected image with the clear button or the usual keyboard shortcut for deleting a line (Command+Backspace on macOS or Control+Backspace on other platforms). Clearing the field does not restore the previous image.
+### Icon of the app website
+
+When an app has a URL, the picker offers the icon of that website as its first suggestion. Homarr requests the page the URL points to without its credentials, query string or fragment. It reads the `<link rel="icon">` and `<link rel="apple-touch-icon">` declarations in the head of that page and falls back to `/favicon.ico` of the same origin. The suggestion is only requested while the picker is open and it is never selected for you, so an image you picked yourself is never replaced. Nothing is suggested when neither a declared icon nor the `/favicon.ico` fallback is available.
+
### Using external icons
If you don't find the icon you're looking for on Dashboard Icons or wish to use a different source, you can simply enter a URL that points to an icon.
diff --git a/packages/api/src/router/icons.ts b/packages/api/src/router/icons.ts
index 202d044a0..3cc86c987 100644
--- a/packages/api/src/router/icons.ts
+++ b/packages/api/src/router/icons.ts
@@ -1,8 +1,10 @@
import { getImageMatchRank, normalizeImageName } from "@homarr/common";
+import { env } from "@homarr/common/env";
import { icons } from "@homarr/db/schema";
-import { iconsFindSchema } from "@homarr/validation/icons";
+import { fetchFaviconUrlAsync } from "@homarr/icons";
+import { iconsDetectFaviconSchema, iconsFindSchema } from "@homarr/validation/icons";
-import { createTRPCRouter, publicProcedure } from "../trpc";
+import { createTRPCRouter, permissionRequiredProcedure, publicProcedure } from "../trpc";
export const iconsRouter = createTRPCRouter({
findIcons: publicProcedure
@@ -56,4 +58,19 @@ export const iconsRouter = createTRPCRouter({
countIcons,
};
}),
+ detectFavicon: permissionRequiredProcedure
+ .requiresPermission("app-create")
+ .meta({
+ mcp: {
+ enabled: true,
+ description:
+ 'Detect the icon of a website by reading the <link rel="icon"> declarations of its page, falling back to /favicon.ico. REQUIRED: href (http or https URL of the website). Returns { url: string | null }, null when no icon was found',
+ },
+ })
+ .input(iconsDetectFaviconSchema)
+ .query(async ({ input }) => {
+ if (env.NO_EXTERNAL_CONNECTION) return { url: null };
+
+ return { url: await fetchFaviconUrlAsync(input.href) };
+ }),
});
diff --git a/packages/api/src/router/test/icons.spec.ts b/packages/api/src/router/test/icons.spec.ts
index d58f96425..8ce325315 100644
--- a/packages/api/src/router/test/icons.spec.ts
+++ b/packages/api/src/router/test/icons.spec.ts
@@ -1,12 +1,46 @@
// @vitest-environment node
-import { describe, expect, test } from "vitest";
+import { describe, expect, test, vi } from "vitest";
+import type { Session } from "@homarr/auth";
+import { createId } from "@homarr/common";
import { iconRepositories, icons } from "@homarr/db/schema";
import { createDb } from "@homarr/db/test";
+import type { GroupPermissionKey } from "@homarr/definitions";
+import { fetchFaviconUrlAsync } from "@homarr/icons";
import { iconsRouter } from "../icons";
+vi.mock("@homarr/icons", () => ({ fetchFaviconUrlAsync: vi.fn() }));
+
+const createSession = (permissions: GroupPermissionKey[]): Session => ({
+ user: { id: createId(), permissions, colorScheme: "light" },
+ expires: new Date().toISOString(),
+});
+
+describe("detectFavicon", () => {
+ test("refuses a user who may not create apps without requesting the website", async () => {
+ const caller = iconsRouter.createCaller({ db: createDb(), deviceType: undefined, session: createSession([]) });
+
+ await expect(caller.detectFavicon({ href: "https://app.example.com" })).rejects.toThrow("Permission denied");
+ expect(fetchFaviconUrlAsync).not.toHaveBeenCalled();
+ });
+
+ test("detects the icon for a user who may create apps", async () => {
+ vi.mocked(fetchFaviconUrlAsync).mockResolvedValueOnce("https://app.example.com/favicon.ico");
+ const caller = iconsRouter.createCaller({
+ db: createDb(),
+ deviceType: undefined,
+ session: createSession(["app-create"]),
+ });
+
+ await expect(caller.detectFavicon({ href: "https://app.example.com" })).resolves.toEqual({
+ url: "https://app.example.com/favicon.ico",
+ });
+ expect(fetchFaviconUrlAsync).toHaveBeenCalledWith("https://app.example.com");
+ });
+});
+
describe("findIcons", () => {
test("returns only repositories containing matches for a search", async () => {
const db = createDb();
diff --git a/packages/api/src/test/mcp.spec.ts b/packages/api/src/test/mcp.spec.ts
index 27be6b291..36935618b 100644
--- a/packages/api/src/test/mcp.spec.ts
+++ b/packages/api/src/test/mcp.spec.ts
@@ -57,6 +57,7 @@ const MCP_TOOL_ALLOWLIST = {
"healthMonitoring_getClusterHealthStatus",
"healthMonitoring_getSystemHealthStatus",
"healthMonitoring_listStorageVolumes",
+ "icon_detectFavicon",
"icon_findIcons",
"info_getInfo",
"integration_all",
diff --git a/packages/core/src/infrastructure/http/http-agent.ts b/packages/core/src/infrastructure/http/http-agent.ts
index b15ada890..976986057 100644
--- a/packages/core/src/infrastructure/http/http-agent.ts
+++ b/packages/core/src/infrastructure/http/http-agent.ts
@@ -7,16 +7,19 @@ import { createLogger } from "@homarr/core/infrastructure/logs";
// The below import statement initializes dns-caching
import "@homarr/core/infrastructure/dns/init";
-interface HttpAgentOptions extends EnvHttpProxyAgent.Options {
+export interface HttpAgentOptions extends EnvHttpProxyAgent.Options {
logger?: ILogger;
+ logOriginOnly?: boolean;
}
export class UndiciHttpAgent extends EnvHttpProxyAgent {
private logger: ILogger;
+ private logOriginOnly: boolean;
constructor(props?: HttpAgentOptions) {
super(props);
this.logger = props?.logger ?? createLogger({ module: "httpAgent" });
+ this.logOriginOnly = props?.logOriginOnly ?? false;
}
dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean {
@@ -25,13 +28,14 @@ export class UndiciHttpAgent extends EnvHttpProxyAgent {
}
private logRequestDispatch(options: Dispatcher.DispatchOptions) {
- const path = this.redactPathParams(options.path);
- let url = new URL(`${options.origin as string}${path}`);
- url = this.redactSearchParams(url);
+ let loggedUrl = new URL(String(options.origin)).origin;
+ if (!this.logOriginOnly) {
+ const path = this.redactPathParams(options.path);
+ const url = this.redactSearchParams(new URL(`${loggedUrl}${path}`));
+ loggedUrl = url.toString().replaceAll("=&", "&");
+ }
- this.logger.debug(
- `Dispatching request ${url.toString().replaceAll("=&", "&")} (${Object.keys(options.headers ?? {}).length} headers)`,
- );
+ this.logger.debug(`Dispatching request ${loggedUrl} (${Object.keys(options.headers ?? {}).length} headers)`);
}
/**
diff --git a/packages/core/src/infrastructure/http/request.ts b/packages/core/src/infrastructure/http/request.ts
index a96525f29..135ade9a9 100644
--- a/packages/core/src/infrastructure/http/request.ts
+++ b/packages/core/src/infrastructure/http/request.ts
@@ -5,7 +5,7 @@ import type { LookupFunction } from "node:net";
import { checkServerIdentity, createSecureContext } from "node:tls";
import type { SecureContext } from "node:tls";
import axios from "axios";
-import type { EnvHttpProxyAgent as UndiciEnvHttpProxyAgent, RequestInfo, RequestInit, Response } from "undici";
+import type { RequestInfo, RequestInit, Response } from "undici";
import { fetch } from "undici";
import {
@@ -15,6 +15,7 @@ import {
import { UndiciHttpAgent } from "@homarr/core/infrastructure/http";
import type { TrustedCertificateHostname } from "../certificates/hostnames";
+import type { HttpAgentOptions } from "./http-agent";
import { getHttpRequestSignal } from "./request-signal";
import { withTimeoutAsync } from "./timeout";
@@ -63,8 +64,8 @@ export const createCertificateAgentAsync = async (
lookup: LookupFunction;
}>,
agentOptions?: Pick<
- UndiciEnvHttpProxyAgent.Options,
- "autoSelectFamily" | "bodyTimeout" | "httpProxy" | "httpsProxy" | "noProxy"
+ HttpAgentOptions,
+ "autoSelectFamily" | "bodyTimeout" | "httpProxy" | "httpsProxy" | "noProxy" | "logOriginOnly"
>,
) => {
const ca = override?.ca ?? (await getAllTrustedCertificatesAsync());
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 54ccd728a..278ae2e1b 100644
--- a/packages/forms-collection/src/icon-picker/icon-picker.spec.ts
+++ b/packages/forms-collection/src/icon-picker/icon-picker.spec.ts
@@ -6,8 +6,9 @@ import { MantineProvider } from "@mantine/core";
import type { Root } from "react-dom/client";
import type { IconGroup } from "./icon-picker.utils";
-const { findIconsQuery, refetch, uploadSelection, sessionPermissions } = vi.hoisted(() => ({
+const { findIconsQuery, detectFaviconQuery, refetch, uploadSelection, sessionPermissions } = vi.hoisted(() => ({
findIconsQuery: vi.fn(),
+ detectFaviconQuery: vi.fn(),
refetch: vi.fn(),
uploadSelection: vi.fn(),
sessionPermissions: { current: [] as string[] },
@@ -25,6 +26,7 @@ let queryResult: {
isFetching: boolean;
isError: boolean;
};
+let faviconResult: { data?: { url: string | null } };
vi.mock("@homarr/api/client", () => ({
clientApi: {
@@ -35,6 +37,12 @@ vi.mock("@homarr/api/client", () => ({
return { ...queryResult, refetch };
},
},
+ detectFavicon: {
+ useQuery: (input: { href: string }, options: { enabled: boolean }) => {
+ detectFaviconQuery(input, options);
+ return options.enabled ? faviconResult : {};
+ },
+ },
},
},
}));
@@ -105,6 +113,7 @@ const advanceDebounce = async () => {
describe("IconPicker", () => {
let container: HTMLDivElement;
let root: Root;
+ let rerenderPicker: () => Promise<void>;
beforeAll(() => {
Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { value: true, writable: true });
@@ -127,10 +136,12 @@ describe("IconPicker", () => {
beforeEach(() => {
vi.useFakeTimers();
findIconsQuery.mockClear();
+ detectFaviconQuery.mockClear();
refetch.mockClear();
uploadSelection.mockClear();
- sessionPermissions.current = [];
+ sessionPermissions.current = ["app-create"];
queryResult = { data: emptyResult, isLoading: false, isFetching: false, isError: false };
+ faviconResult = { data: undefined };
});
afterEach(() => {
@@ -147,9 +158,12 @@ describe("IconPicker", () => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
- await act(async () => {
- root.render(createElement(MantineProvider, null, createElement(IconPicker, { value: "", onChange, ...props })));
- });
+ rerenderPicker = async () => {
+ await act(async () => {
+ root.render(createElement(MantineProvider, null, createElement(IconPicker, { value: "", onChange, ...props })));
+ });
+ };
+ await rerenderPicker();
const input = container.querySelector("input");
if (!input) throw new Error("Icon picker input was not rendered");
return input;
@@ -291,6 +305,76 @@ describe("IconPicker", () => {
expect(refetch).toHaveBeenCalledOnce();
});
+ test("offers the icon detected for the website of the app", async () => {
+ faviconResult = { data: { url: "https://app.example.com/favicon.ico" } };
+ const onChange = vi.fn();
+ const input = await renderPicker(onChange, { faviconSourceUrl: "https://app.example.com" });
+ await focusInput(input);
+
+ expect(detectFaviconQuery.mock.calls.at(-1)?.[0]).toEqual({ href: "https://app.example.com/" });
+ expect(document.body.textContent).toContain("iconPicker.websiteIcon");
+
+ const option = document.body.querySelector<HTMLElement>(
+ '[data-combobox-option][value="https://app.example.com/favicon.ico"]',
+ );
+ if (!option) throw new Error("Website icon option was not rendered");
+ await act(async () => option.click());
+
+ expect(onChange).toHaveBeenCalledWith("https://app.example.com/favicon.ico");
+ });
+
+ 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();
+ const input = await renderPicker(onChange, { faviconSourceUrl: "https://app.example.com" });
+ await focusInput(input);
+
+ await act(async () => pressKey(input, "ArrowDown"));
+ expect(document.body.querySelector("[data-combobox-selected]")?.getAttribute("value")).toBe(
+ "/api/user-medias/local-icon",
+ );
+
+ // The detection answers only after the user already navigated, which puts the website
+ // icon in front of the library images and moves every one of them one position down.
+ faviconResult = { data: { url: "https://app.example.com/favicon.ico" } };
+ await rerenderPicker();
+
+ expect(document.body.textContent).toContain("iconPicker.websiteIcon");
+ expect(document.body.querySelector("[data-combobox-selected]")?.getAttribute("value")).toBe(
+ "/api/user-medias/local-icon",
+ );
+
+ await act(async () => pressKey(input, "Enter"));
+
+ expect(onChange).toHaveBeenCalledWith("/api/user-medias/local-icon");
+ expect(onChange).not.toHaveBeenCalledWith("https://app.example.com/favicon.ico");
+ });
+
+ test("sends neither credentials nor the query of the app url to the server", async () => {
+ const input = await renderPicker(vi.fn(), {
+ faviconSourceUrl: "https://admin:[email protected]/home?token=abc#section",
+ });
+ await focusInput(input);
+
+ expect(detectFaviconQuery.mock.calls.at(-1)?.[0]).toEqual({ href: "https://app.example.com/home" });
+ });
+
+ test("detects the website icon only while the dropdown is open", async () => {
+ const input = await renderPicker(vi.fn(), { faviconSourceUrl: "https://app.example.com" });
+
+ expect(detectFaviconQuery.mock.calls.at(-1)?.[1]).toMatchObject({ enabled: false });
+
+ await focusInput(input);
+ expect(detectFaviconQuery.mock.calls.at(-1)?.[1]).toMatchObject({ enabled: true });
+ });
+
+ test("does not detect a website icon without a website", async () => {
+ const input = await renderPicker(vi.fn());
+ await focusInput(input);
+
+ expect(detectFaviconQuery.mock.calls.at(-1)?.[1]).toMatchObject({ enabled: false });
+ });
+
test("selects an uploaded local image when the user has permission", async () => {
sessionPermissions.current = ["media-upload"];
const onChange = vi.fn();
diff --git a/packages/forms-collection/src/icon-picker/icon-picker.tsx b/packages/forms-collection/src/icon-picker/icon-picker.tsx
index 7e42ccade..29ec8696a 100644
--- a/packages/forms-collection/src/icon-picker/icon-picker.tsx
+++ b/packages/forms-collection/src/icon-picker/icon-picker.tsx
@@ -30,6 +30,7 @@ import {
IconPhotoOff,
IconSearchOff,
IconUpload,
+ IconWorldWww,
} from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
@@ -38,7 +39,7 @@ import { supportedLanguages } from "@homarr/translation";
import { useI18n } from "@homarr/translation/client";
import { UploadMedia } from "../upload-media/upload-media";
-import { arrangeIconPickerSections, isDirectImageUrl, isImageSource, isSvgImage } from "./icon-picker.utils";
+import { arrangeIconPickerSections, isDirectImageUrl, isHttpUrl, isImageSource, isSvgImage } from "./icon-picker.utils";
import classes from "./icon-picker.module.css";
interface IconPickerProps {
@@ -51,6 +52,8 @@ interface IconPickerProps {
description?: ReactNode;
placeholder?: string;
suggestedSearch?: string | null;
+ /** Website whose own icon is offered as a suggestion, usually the URL of the app being created */
+ faviconSourceUrl?: string | null;
withAsterisk?: boolean;
}
@@ -67,11 +70,16 @@ export const IconPicker = ({
description,
placeholder,
suggestedSearch,
+ faviconSourceUrl,
}: IconPickerProps) => {
const [value, setValue] = useUncontrolled({ value: propsValue, onChange, defaultValue: "" });
const [draft, setDraft] = useState(propsValue ?? "");
const [hasEdited, setHasEdited] = useState(false);
- const [keyboardIndex, setKeyboardIndex] = useState(-1);
+ // The option the user navigated to is remembered by its URL and not by its position,
+ // because the list grows while the dropdown is open, for example when the detected
+ // website icon arrives. A position would then point at a different option than the
+ // one the user actually highlighted.
+ const [keyboardSelectedUrl, setKeyboardSelectedUrl] = useState<string | null>(null);
const [previewState, setPreviewState] = useState<PreviewState>("idle");
const { data: session } = useSession();
const tCommon = useI18n("common");
@@ -81,6 +89,7 @@ export const IconPicker = ({
const isCommittedValueDraft = debouncedDraft === (value ?? "");
const searchText = directUrl !== null || isCommittedValueDraft ? "" : debouncedDraft.trim();
const canUpload = session?.user.permissions.includes("media-upload") ?? false;
+ const canDetectFavicon = session?.user.permissions.includes("app-create") ?? false;
const query = clientApi.icon.findIcons.useQuery(
{ searchText, limitPerGroup: 24 },
@@ -92,6 +101,19 @@ export const IconPicker = ({
onDropdownOpen: () => combobox.updateSelectedOptionIndex("active"),
});
+ const faviconSource = faviconSourceUrl?.trim() ?? "";
+ const faviconPage = isHttpUrl(faviconSource) ? new URL(faviconSource) : null;
+ const faviconHostname = faviconPage?.hostname ?? null;
+ // Detecting the icon reaches out to the website, so it only happens while the user
+ // actually browses for an image and not on every keystroke in the URL field. The input
+ // of a query travels in the request url, which proxies write to their access logs, so
+ // credentials, query and fragment of the app url stay in the browser.
+ const faviconQuery = clientApi.icon.detectFavicon.useQuery(
+ { href: faviconPage === null ? "" : `${faviconPage.origin}${faviconPage.pathname}` },
+ { enabled: canDetectFavicon && faviconPage !== null && combobox.dropdownOpened, retry: false },
+ );
+ const detectedFaviconUrl = faviconQuery.data?.url ?? null;
+
useEffect(() => {
setDraft(value ?? "");
setHasEdited(false);
@@ -105,18 +127,38 @@ export const IconPicker = ({
() => arrangeIconPickerSections(query.data?.icons ?? [], searchText),
[query.data?.icons, searchText],
);
- const orderedOptions = useMemo(
- () => [...sections.local, ...sections.svg, ...sections.other],
- [sections.local, sections.svg, sections.other],
- );
+ const detectedFavicon = useMemo(() => {
+ if (!canDetectFavicon || detectedFaviconUrl === null || faviconHostname === null) return null;
+ return { url: detectedFaviconUrl, hostname: faviconHostname };
+ }, [canDetectFavicon, detectedFaviconUrl, faviconHostname]);
+ const orderedOptions = useMemo(() => {
+ const options: { url: string }[] = [];
+ if (detectedFavicon) options.push(detectedFavicon);
+ if (directUrl === null) options.push(...sections.local, ...sections.svg, ...sections.other);
+ return options;
+ }, [detectedFavicon, directUrl, sections.local, sections.svg, sections.other]);
const totalOptions = sections.local.length + sections.svg.length + sections.other.length;
+ const keyboardIndex = useMemo(
+ () =>
+ keyboardSelectedUrl === null ? -1 : orderedOptions.findIndex((option) => option.url === keyboardSelectedUrl),
+ [keyboardSelectedUrl, orderedOptions],
+ );
+
+ // Mantine marks the highlighted option by its position, so the mark is moved along
+ // whenever options are inserted before the one the user navigated to.
+ const { selectOption: selectComboboxOption } = combobox;
+ useEffect(() => {
+ if (keyboardIndex >= 0) {
+ selectComboboxOption(keyboardIndex);
+ }
+ }, [keyboardIndex, selectComboboxOption]);
const commitValue = (nextValue: string) => {
startTransition(() => {
setValue(nextValue);
setDraft(nextValue);
setHasEdited(false);
- setKeyboardIndex(-1);
+ setKeyboardSelectedUrl(null);
});
};
@@ -146,21 +188,18 @@ export const IconPicker = ({
return;
}
- if (!directUrl && orderedOptions.length > 0 && (event.key === "ArrowDown" || event.key === "ArrowUp")) {
+ if (orderedOptions.length > 0 && (event.key === "ArrowDown" || event.key === "ArrowUp")) {
event.preventDefault();
combobox.openDropdown("keyboard");
- setKeyboardIndex((current) => {
- const next =
- event.key === "ArrowDown"
- ? current >= orderedOptions.length - 1
- ? 0
- : current + 1
- : current <= 0
- ? orderedOptions.length - 1
- : current - 1;
- combobox.selectOption(next);
- return next;
- });
+ const nextIndex =
+ event.key === "ArrowDown"
+ ? keyboardIndex >= orderedOptions.length - 1
+ ? 0
+ : keyboardIndex + 1
+ : keyboardIndex <= 0
+ ? orderedOptions.length - 1
+ : keyboardIndex - 1;
+ setKeyboardSelectedUrl(orderedOptions[nextIndex]?.url ?? null);
return;
}
@@ -177,14 +216,14 @@ export const IconPicker = ({
}
};
- const renderIconOptions = (icons: typeof sections.local, offset: number) => (
+ const renderIconOptions = (icons: typeof sections.local) => (
<SimpleGrid className={classes.iconGrid} spacing={6} verticalSpacing={6}>
- {icons.map((icon, index) => (
+ {icons.map((icon) => (
<Tooltip key={icon.id} label={`${icon.name} · ${icon.repositorySlug}`} openDelay={500}>
<Combobox.Option
value={icon.url}
aria-label={icon.name}
- active={icon.url === value || keyboardIndex === offset + index}
+ active={icon.url === value || icon.url === keyboardSelectedUrl}
className={classes.iconOption}
>
<Image src={icon.url} alt="" w={30} h={30} fit="contain" fallbackSrc="/logo/logo.png" />
@@ -195,6 +234,31 @@ export const IconPicker = ({
</SimpleGrid>
);
+ const renderDetectedFavicon = () => {
+ if (!detectedFavicon) {
+ return null;
+ }
+
+ return (
+ <Box p="xs" pb={0}>
+ <PickerSection icon={<IconWorldWww size={15} />} label={tCommon("iconPicker.websiteIcon")}>
+ <SimpleGrid className={classes.iconGrid} spacing={6} verticalSpacing={6}>
+ <Tooltip label={detectedFavicon.hostname} openDelay={500}>
+ <Combobox.Option
+ value={detectedFavicon.url}
+ aria-label={detectedFavicon.hostname}
+ active={detectedFavicon.url === value || detectedFavicon.url === keyboardSelectedUrl}
+ className={classes.iconOption}
+ >
+ <Image src={detectedFavicon.url} alt="" w={30} h={30} fit="contain" fallbackSrc="/logo/logo.png" />
+ </Combobox.Option>
+ </Tooltip>
+ </SimpleGrid>
+ </PickerSection>
+ </Box>
+ );
+ };
+
const renderSearchResults = () => {
if (query.isError) {
return (
@@ -233,17 +297,17 @@ export const IconPicker = ({
<Stack gap="sm" p="xs">
{sections.local.length > 0 && (
<PickerSection icon={<IconPhoto size={15} />} label={tCommon("iconPicker.localImages")}>
- {renderIconOptions(sections.local, 0)}
+ {renderIconOptions(sections.local)}
</PickerSection>
)}
{sections.svg.length > 0 && (
<PickerSection label={tCommon("iconPicker.svgIcons")} badge="SVG">
- {renderIconOptions(sections.svg, sections.local.length)}
+ {renderIconOptions(sections.svg)}
</PickerSection>
)}
{sections.other.length > 0 && (
<PickerSection icon={<IconCloud size={15} />} label={tCommon("iconPicker.otherImages")}>
- {renderIconOptions(sections.other, sections.local.length + sections.svg.length)}
+ {renderIconOptions(sections.other)}
</PickerSection>
)}
</Stack>
@@ -337,7 +401,7 @@ export const IconPicker = ({
const nextValue = event.currentTarget.value;
setDraft(nextValue);
setHasEdited(true);
- setKeyboardIndex(-1);
+ setKeyboardSelectedUrl(null);
combobox.openDropdown("keyboard");
combobox.updateSelectedOptionIndex();
@@ -376,6 +440,7 @@ export const IconPicker = ({
<Combobox.Dropdown className={classes.dropdown}>
<Combobox.Options className={classes.options} aria-label={tCommon("iconPicker.results")}>
+ {renderDetectedFavicon()}
{directUrl ? (
<Paper p="sm" m="xs" className={classes.urlPreview}>
<Group wrap="nowrap" align="center">
diff --git a/packages/forms-collection/src/icon-picker/icon-picker.utils.ts b/packages/forms-collection/src/icon-picker/icon-picker.utils.ts
index e71558f8e..c577a92ce 100644
--- a/packages/forms-collection/src/icon-picker/icon-picker.utils.ts
+++ b/packages/forms-collection/src/icon-picker/icon-picker.utils.ts
@@ -46,7 +46,7 @@ export const arrangeIconPickerSections = (iconGroups: IconGroup[], searchTerm =
return sections;
};
-export const isDirectImageUrl = (value: string) => {
+export const isHttpUrl = (value: string) => {
try {
const url = new URL(value.trim());
return (url.protocol === "http:" || url.protocol === "https:") && Boolean(url.hostname);
@@ -55,6 +55,8 @@ export const isDirectImageUrl = (value: string) => {
}
};
+export const isDirectImageUrl = (value: string) => isHttpUrl(value);
+
export const isImageSource = (value: string) => isDirectImageUrl(value) || value.trim().startsWith("/");
export const isSvgImage = (value: string) => {
diff --git a/packages/forms-collection/src/new-app/_form.tsx b/packages/forms-collection/src/new-app/_form.tsx
index c0e30c139..452679396 100644
--- a/packages/forms-collection/src/new-app/_form.tsx
+++ b/packages/forms-collection/src/new-app/_form.tsx
@@ -138,6 +138,7 @@ export const AppForm = ({
<IconPicker
{...form.getInputProps("iconUrl")}
suggestedSearch={initialValues === undefined ? form.values.name : undefined}
+ faviconSourceUrl={form.values.href}
/>
<Textarea
{...form.getInputProps("description")}
diff --git a/packages/icons/index.ts b/packages/icons/index.ts
index 59a0b28ba..95f0ca3b7 100644
--- a/packages/icons/index.ts
+++ b/packages/icons/index.ts
@@ -1,3 +1,4 @@
export * from "./src/icons-fetcher";
export * from "./src/types";
export * from "./src/auto-icon-searcher";
+export * from "./src/favicon-fetcher";
diff --git a/packages/icons/src/favicon-fetcher.ts b/packages/icons/src/favicon-fetcher.ts
new file mode 100644
index 000000000..916ccd6cd
--- /dev/null
+++ b/packages/icons/src/favicon-fetcher.ts
@@ -0,0 +1,235 @@
+import type { fetchWithTrustedCertificatesAsync } 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>>;
+
+const requestTimeoutInMs = 5_000;
+// Lets the page, one redirect and the favicon.ico probe each use their full request timeout,
+// while a server that drips its page byte by byte cannot hold the detection open until the
+// size limit.
+const detectionTimeoutInMs = 3 * requestTimeoutInMs;
+// Icon declarations live in the document head, so only the beginning of the page is read.
+const maximumHtmlBytes = 256 * 1024;
+
+// Link relations that declare a page icon, ordered from most to least preferred.
+// The relation is the primary ranking signal because the sizes attribute is omitted
+// far too often to compare candidates of different relations by their size.
+const iconRelationScores: Record<string, number> = {
+ "apple-touch-icon-precomposed": 4,
+ "apple-touch-icon": 3,
+ icon: 2,
+ "shortcut icon": 1,
+};
+
+interface IconCandidate {
+ url: string;
+ relationScore: number;
+ sizeArea: number;
+}
+
+/**
+ * Resolves the icon of a website by reading the `<link rel="icon">` and
+ * `<link rel="apple-touch-icon">` declarations of the page it serves and by
+ * falling back to the well known `/favicon.ico` of its origin.
+ *
+ * Returns `null` when the site is unreachable, declares no usable icon or does not
+ * answer within the detection timeout.
+ *
+ * The requests go to an address the user provided, so this may only be called
+ * from an authorized context. They pass through fetchGuardedAsync, which keeps
+ * 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> => {
+ const websiteUrl = parseHttpUrl(href);
+ if (websiteUrl === null) return null;
+
+ const deadline = new AbortController();
+ const timer = setTimeout(() => deadline.abort(new Error("Favicon detection timed out")), detectionTimeoutInMs);
+ try {
+ return await detectFaviconUrlAsync(websiteUrl, deadline.signal);
+ } finally {
+ clearTimeout(timer);
+ }
+};
+
+const detectFaviconUrlAsync = async (websiteUrl: URL, signal: AbortSignal): Promise<string | null> => {
+ const page = await fetchPageAsync(websiteUrl, signal);
+ const declaredIconUrl = page?.html == null ? null : findDeclaredIconUrl(page.html, page.url);
+ if (declaredIconUrl !== null) return 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;
+};
+
+// Credentials in the app url are never sent to the site, and leaving them out here keeps
+// them out of every error raised further down.
+const parseHttpUrl = (value: string): URL | null => {
+ const url = URL.parse(value.trim());
+ if (url === null || (url.protocol !== "http:" && url.protocol !== "https:")) return null;
+
+ url.username = "";
+ url.password = "";
+ url.hash = "";
+ return url;
+};
+
+// Returns null only when no response was obtained at all. Once a response exists, its
+// url is always returned, even when the response carries no usable html, so a caller
+// falling back to the well known favicon still targets the origin that actually
+// answered, which can differ from the requested address when the app redirects.
+const fetchPageAsync = async (
+ websiteUrl: URL,
+ signal: AbortSignal,
+): Promise<{ html: string | null; url: URL } | null> => {
+ try {
+ return await fetchGuardedAsync(
+ websiteUrl,
+ { headers: { Accept: "text/html" }, timeout: requestTimeoutInMs, signal },
+ async (response, finalUrl) => {
+ const body = response.body;
+ const contentType = response.headers.get("content-type")?.toLowerCase() ?? "";
+ if (!response.ok || !contentType.includes("text/html") || body === null) {
+ await cancelBodyAsync(response);
+ return { html: null, url: finalUrl };
+ }
+
+ try {
+ return { html: await readDocumentHeadAsync(body), url: finalUrl };
+ } catch (error) {
+ logger.debug("Unable to read website for favicon detection", { origin: finalUrl.origin, error });
+ return { html: null, url: finalUrl };
+ }
+ },
+ );
+ } catch (error) {
+ logger.debug("Unable to load website for favicon detection", { origin: websiteUrl.origin, error });
+ return null;
+ }
+};
+
+// The head also ends at <body> because </head> is optional in HTML and minifiers drop it.
+// The character class keeps longer names such as </header> from matching.
+const headEndRegex = /<\/head[\s/>]|<body[\s/>]/i;
+
+// Only the new text and the few characters before it are searched for the head end, so a page
+// sent in tiny chunks costs no more than one sent at once.
+const readDocumentHeadAsync = async (body: NonNullable<FetchResponse["body"]>): Promise<string> => {
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ const texts: string[] = [];
+ let textLength = 0;
+ let tail = "";
+ let remainingBytes = maximumHtmlBytes;
+
+ try {
+ while (remainingBytes > 0) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ const chunk = value.subarray(0, remainingBytes);
+ remainingBytes -= chunk.byteLength;
+ const text = decoder.decode(chunk, { stream: true });
+ texts.push(text);
+
+ const searched = tail + text;
+ const headEnd = searched.search(headEndRegex);
+ if (headEnd !== -1) return texts.join("").slice(0, textLength - tail.length + headEnd);
+
+ textLength += text.length;
+ tail = searched.slice(-"</head".length);
+ }
+ } finally {
+ await reader.cancel().catch(() => undefined);
+ }
+
+ return texts.join("");
+};
+
+// A tag ends at the next "<" and no name or size starts inside another one, so a long run of
+// letters, digits or unclosed tags is scanned once and not again from every position inside
+// it, which would block the process for over a minute at 256 KiB.
+const linkTagRegex = /<link\b[^<>]*>/gi;
+const attributeRegex = /(?<![a-z-])([a-z-]+)\s*=\s*("([^"]*)"|'([^']*)'|([^\s"'>]+))/gi;
+const sizeRegex = /(?<!\d)(\d+)x(\d+)/gi;
+
+const findDeclaredIconUrl = (html: string, pageUrl: URL): string | null => {
+ const candidates: IconCandidate[] = [];
+
+ for (const linkTag of html.match(linkTagRegex) ?? []) {
+ const attributes = parseAttributes(linkTag);
+ const relation = attributes.rel?.toLowerCase().replaceAll(/\s+/g, " ").trim();
+ const relationScore = relation === undefined ? undefined : iconRelationScores[relation];
+ if (relationScore === undefined || attributes.href === undefined) continue;
+
+ const url = resolveHttpUrl(attributes.href, pageUrl);
+ if (url === null) continue;
+
+ candidates.push({ url, relationScore, sizeArea: parseLargestSizeArea(attributes.sizes) });
+ }
+
+ const bestCandidate = candidates.toSorted(
+ (first, second) => second.relationScore - first.relationScore || second.sizeArea - first.sizeArea,
+ )[0];
+
+ return bestCandidate?.url ?? null;
+};
+
+const parseAttributes = (linkTag: string): Record<string, string> => {
+ const attributes: Record<string, string> = {};
+
+ for (const match of linkTag.matchAll(attributeRegex)) {
+ const name = match[1]?.toLowerCase();
+ const value = match[3] ?? match[4] ?? match[5];
+ if (name !== undefined && value !== undefined) {
+ attributes[name] = value;
+ }
+ }
+
+ return attributes;
+};
+
+// Parses a sizes attribute like "32x32" or "180x180 128x128" into the largest area it
+// declares so that the icon with the highest resolution wins.
+const parseLargestSizeArea = (sizes: string | undefined): number => {
+ if (sizes === undefined) return 0;
+
+ let largestArea = 0;
+ for (const match of sizes.matchAll(sizeRegex)) {
+ largestArea = Math.max(largestArea, Number(match[1] ?? 0) * Number(match[2] ?? 0));
+ }
+
+ return largestArea;
+};
+
+const resolveHttpUrl = (href: string, pageUrl: URL): string | null => {
+ try {
+ const url = new URL(href, pageUrl);
+ return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;
+ } catch {
+ return null;
+ }
+};
+
+const isImageAsync = async (url: URL, signal: AbortSignal): Promise<boolean> => {
+ try {
+ return await fetchGuardedAsync(url, { timeout: requestTimeoutInMs, signal }, async (response) => {
+ await cancelBodyAsync(response);
+ if (!response.ok) return false;
+
+ // Many self hosted apps answer unknown paths with their HTML entry point, so only the
+ // content type tells apart a real icon from such a fallback page.
+ const contentType = response.headers.get("content-type")?.toLowerCase() ?? "";
+ return contentType.startsWith("image/") || contentType.includes("icon");
+ });
+ } catch (error) {
+ logger.debug("Unable to load the well known favicon", { origin: url.origin, error });
+ return false;
+ }
+};
diff --git a/packages/icons/src/guarded-fetch.ts b/packages/icons/src/guarded-fetch.ts
new file mode 100644
index 000000000..dceb8c3ca
--- /dev/null
+++ b/packages/icons/src/guarded-fetch.ts
@@ -0,0 +1,227 @@
+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";
+
+type FetchResponse = Awaited<ReturnType<typeof fetchWithTrustedCertificatesAsync>>;
+type Dispatcher = Awaited<ReturnType<typeof createCertificateAgentAsync>>;
+
+interface ResolvedAddress {
+ address: string;
+ family: 4 | 6;
+}
+
+interface GuardedFetchOptions {
+ headers?: Record<string, string>;
+ // Bounds the lookup, the connect and the response headers of every hop, and how long
+ // the body may stay idle.
+ timeout: number;
+ // Aborts the whole exchange, redirects and body included.
+ signal?: AbortSignal;
+}
+
+const maximumRedirects = 5;
+const redirectStatuses = new Set([301, 302, 303, 307, 308]);
+
+// Loopback, link-local, unspecified, multicast and reserved addresses, plus the cloud
+// metadata services that live outside link-local. Private networks stay reachable,
+// Homarr's own container address and its Docker gateway included, because self hosted
+// apps run there. Node matches the IPv4 rules against IPv4-mapped IPv6 addresses as well.
+const blockedAddresses = new BlockList();
+for (const [network, prefix] of [
+ ["0.0.0.0", 8],
+ ["127.0.0.0", 8],
+ ["169.254.0.0", 16],
+ ["100.100.100.200", 32],
+ ["168.63.129.16", 32],
+ ["224.0.0.0", 4],
+ ["240.0.0.0", 4],
+] as const) {
+ blockedAddresses.addSubnet(network, prefix, "ipv4");
+}
+for (const [network, prefix] of [
+ ["::", 96],
+ ["fe80::", 10],
+ ["fd00:ec2::254", 128],
+ ["ff00::", 8],
+] as const) {
+ blockedAddresses.addSubnet(network, prefix, "ipv6");
+}
+
+const parseIpv6Groups = (part: string) =>
+ part === ""
+ ? []
+ : part.split(":").flatMap((group) => {
+ if (!group.includes(".")) return [parseInt(group, 16)];
+ const [a = 0, b = 0, c = 0, d = 0] = group.split(".").map(Number);
+ return [(a << 8) | b, (c << 8) | d];
+ });
+
+const expandIpv6 = (address: string) => {
+ const [head = "", tail] = address.split("::");
+ const start = parseIpv6Groups(head);
+ if (tail === undefined) return start;
+ const end = parseIpv6Groups(tail);
+ return [...start, ...Array<number>(8 - start.length - end.length).fill(0), ...end];
+};
+
+const toIpv4 = (high: number, low: number) => `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`;
+
+// A NAT64 or 6to4 gateway connects to the IPv4 address carried inside these addresses.
+const embeddedIpv4 = (address: string) => {
+ const groups = expandIpv6(address);
+ const [first, second, third, , , , seventh = 0, eighth = 0] = groups;
+ if (first === 0x64 && second === 0xff9b && groups.slice(2, 6).every((group) => group === 0)) {
+ return toIpv4(seventh, eighth);
+ }
+ if (first === 0x2002 && second !== undefined && third !== undefined) return toIpv4(second, third);
+ return null;
+};
+
+const isBlockedAddress = ({ address, family }: ResolvedAddress) => {
+ if (family === 4) return blockedAddresses.check(address, "ipv4");
+ if (blockedAddresses.check(address, "ipv6")) return true;
+ const embedded = embeddedIpv4(address);
+ return embedded !== null && blockedAddresses.check(embedded, "ipv4");
+};
+
+// A lookup cannot be cancelled, so one that never answers is abandoned instead.
+const untilAbortedAsync = <T>(promise: Promise<T>, signal: AbortSignal) =>
+ new Promise<T>((resolve, reject) => {
+ signal.throwIfAborted();
+ const abort = () => reject(signal.reason);
+ signal.addEventListener("abort", abort, { once: true });
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
+ });
+
+const resolveAllowedAddressesAsync = async (url: URL, signal: AbortSignal): Promise<ResolvedAddress[]> => {
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
+ throw new Error(`Refusing to request a ${url.protocol} url`);
+ }
+
+ const hostname = url.hostname.replace(/^\[(.*)\]$/, "$1");
+ const literalFamily = isIP(hostname);
+ const resolved =
+ literalFamily === 0
+ ? await untilAbortedAsync(lookup(hostname, { all: true, verbatim: true }), signal)
+ : [{ address: hostname, family: literalFamily }];
+ const addresses = resolved.filter((entry): entry is ResolvedAddress => entry.family === 4 || entry.family === 6);
+
+ if (addresses.length === 0) throw new Error(`${url.hostname} did not resolve to an address`);
+ const blocked = addresses.find(isBlockedAddress);
+ if (blocked !== undefined) {
+ throw new Error(`Refusing to request ${url.origin} because it resolves to ${blocked.address}`);
+ }
+
+ return addresses;
+};
+
+// Answers every lookup of the connection with the addresses that were checked, so a DNS
+// record that changes between the check and the connect cannot redirect the request.
+const createPinnedLookup =
+ (addresses: ResolvedAddress[]): LookupFunction =>
+ (_hostname, options, callback) => {
+ const candidates =
+ options.family === 4 || options.family === 6
+ ? addresses.filter(({ family }) => family === options.family)
+ : addresses;
+ const selected = candidates[0];
+ if (selected === undefined) {
+ const error: NodeJS.ErrnoException = new Error("No checked address for the requested family");
+ error.code = "ENOTFOUND";
+ callback(error, []);
+ return;
+ }
+
+ if (options.all) callback(null, candidates);
+ else callback(null, selected.address, selected.family);
+ };
+
+// A proxy resolves the target on its own, which would bypass the pinned lookup.
+const createPinnedDispatcherAsync = async (addresses: ResolvedAddress[], timeout: number) =>
+ await createCertificateAgentAsync(
+ { lookup: createPinnedLookup(addresses) },
+ {
+ autoSelectFamily: addresses.length > 1,
+ bodyTimeout: timeout,
+ httpProxy: "",
+ httpsProxy: "",
+ noProxy: "*",
+ logOriginOnly: true,
+ },
+ );
+
+const requestHopAsync = async (
+ url: URL,
+ options: GuardedFetchOptions,
+): Promise<{ response: FetchResponse; dispatcher: Dispatcher }> => {
+ const timeout = new AbortController();
+ const timer = setTimeout(() => timeout.abort(new Error(`Request to ${url.origin} timed out`)), options.timeout);
+ 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);
+ try {
+ const response = await fetchWithTrustedCertificatesAsync(url, {
+ headers: options.headers,
+ redirect: "manual",
+ dispatcher,
+ signal,
+ });
+ return { response, dispatcher };
+ } catch (error) {
+ await dispatcher.destroy();
+ throw error;
+ }
+ } finally {
+ clearTimeout(timer);
+ }
+};
+
+/**
+ * fetchGuardedAsync requests a user provided url without letting it reach loopback,
+ * link-local, multicast or cloud metadata addresses, following up to five redirects
+ * and checking every hop again.
+ *
+ * The final response is handed to handleResponse together with its url, and the
+ * connection is closed once that callback settles.
+ */
+export const fetchGuardedAsync = async <TResult>(
+ url: URL,
+ options: GuardedFetchOptions,
+ handleResponse: (response: FetchResponse, url: URL) => Promise<TResult>,
+): Promise<TResult> => {
+ let currentUrl = url;
+
+ for (let redirects = 0; ; redirects++) {
+ options.signal?.throwIfAborted();
+ const { response, dispatcher } = await requestHopAsync(currentUrl, options);
+
+ try {
+ const location = redirectStatuses.has(response.status) ? response.headers.get("location") : null;
+ if (location === null) return await handleResponse(response, currentUrl);
+
+ await cancelBodyAsync(response);
+ if (redirects === maximumRedirects) throw new Error(`Too many redirects starting at ${url.origin}`);
+ // The TypeError of new URL carries the full location and base, query strings included.
+ const target = URL.parse(location, currentUrl);
+ if (target === null) throw new Error(`Invalid redirect location from ${currentUrl.origin}`);
+ // undici refuses a url with credentials and puts all of it, query included, into its error.
+ target.username = "";
+ target.password = "";
+ currentUrl = target;
+ } finally {
+ await dispatcher.destroy();
+ }
+ }
+};
+
+export const cancelBodyAsync = async (response: FetchResponse): Promise<void> => {
+ try {
+ await response.body?.cancel();
+ } catch {
+ // The connection is already gone, so there is nothing left to release
+ }
+};
diff --git a/packages/icons/src/test/favicon-fetcher.spec.ts b/packages/icons/src/test/favicon-fetcher.spec.ts
new file mode 100644
index 000000000..59bb9d04f
--- /dev/null
+++ b/packages/icons/src/test/favicon-fetcher.spec.ts
@@ -0,0 +1,406 @@
+// @vitest-environment node
+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 { fetchFaviconUrlAsync } from "../favicon-fetcher";
+
+vi.mock("node:dns/promises", () => ({ lookup: vi.fn() }));
+vi.mock("@homarr/core/infrastructure/http", () => ({
+ createCertificateAgentAsync: vi.fn(),
+ fetchWithTrustedCertificatesAsync: vi.fn(),
+}));
+const debugLog = vi.hoisted(() => vi.fn());
+vi.mock("@homarr/core/infrastructure/logs", () => ({
+ createLogger: () => ({ debug: debugLog }),
+}));
+
+type FetchResponse = Awaited<ReturnType<typeof fetchWithTrustedCertificatesAsync>>;
+type Dispatcher = Awaited<ReturnType<typeof createCertificateAgentAsync>>;
+
+const mockedLookup = vi.mocked(lookup as unknown as (hostname: string) => Promise<LookupAddress[]>);
+const mockedCreateAgent = vi.mocked(createCertificateAgentAsync);
+const mockedFetch = vi.mocked(fetchWithTrustedCertificatesAsync);
+
+const websiteUrl = "https://app.example.com/";
+const faviconUrl = "https://app.example.com/favicon.ico";
+
+const addressesByHostname: Record<string, string> = {
+ "app.example.com": "93.184.216.34",
+ "auth.example.net": "93.184.216.35",
+ localhost: "127.0.0.1",
+};
+
+const createBody = (content: string | string[]) => {
+ const chunks = (typeof content === "string" ? [content] : content).map((chunk) => new TextEncoder().encode(chunk));
+ return {
+ getReader: () => ({
+ read: () => {
+ const value = chunks.shift();
+ return Promise.resolve(value === undefined ? { done: true, value: undefined } : { done: false, value });
+ },
+ cancel: () => Promise.resolve(),
+ }),
+ cancel: () => Promise.resolve(),
+ };
+};
+
+const createResponse = (options: {
+ status?: number;
+ location?: string;
+ contentType?: string;
+ body?: string | string[];
+}): FetchResponse => {
+ const status = options.status ?? 200;
+ const headers: Record<string, string | undefined> = {
+ "content-type": options.contentType,
+ location: options.location,
+ };
+ return {
+ status,
+ ok: status >= 200 && status < 300,
+ headers: { get: (name: string) => headers[name.toLowerCase()] ?? null },
+ body: options.body === undefined ? null : createBody(options.body),
+ } as unknown as FetchResponse;
+};
+
+// Sends one byte every few seconds, each within the idle timeout, and fails the read once
+// the request is aborted the way the body of a real fetch does.
+const createDrippingPage = (signal: AbortSignal | null | undefined): FetchResponse =>
+ ({
+ status: 200,
+ ok: true,
+ headers: { get: (name: string) => (name.toLowerCase() === "content-type" ? "text/html" : null) },
+ body: {
+ getReader: () => ({
+ read: () =>
+ new Promise((resolve, reject) => {
+ const timer = setTimeout(() => resolve({ done: false, value: new Uint8Array([32]) }), 3_000);
+ signal?.addEventListener("abort", () => {
+ clearTimeout(timer);
+ reject(signal.reason);
+ });
+ }),
+ cancel: () => Promise.resolve(),
+ }),
+ cancel: () => Promise.resolve(),
+ },
+ }) as unknown as FetchResponse;
+
+const createPage = (head: string) =>
+ createResponse({ contentType: "text/html; charset=utf-8", body: `<html><head>${head}</head></html>` });
+
+const createRedirect = (location: string) => createResponse({ status: 302, location });
+
+const mockResponses = (responsesByUrl: Record<string, FetchResponse>) => {
+ 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}`))
+ : Promise.resolve(response);
+ });
+};
+
+const requestedUrls = () => mockedFetch.mock.calls.map(([input]) => String(input));
+
+describe("fetchFaviconUrlAsync", () => {
+ beforeEach(() => {
+ debugLog.mockReset();
+ mockedFetch.mockReset();
+ mockedCreateAgent.mockReset();
+ mockedCreateAgent.mockImplementation(() =>
+ Promise.resolve({ destroy: () => Promise.resolve() } as unknown as Dispatcher),
+ );
+ mockedLookup.mockReset();
+ mockedLookup.mockImplementation((hostname) => {
+ const address = addressesByHostname[hostname];
+ return address === undefined
+ ? Promise.reject(new Error(`getaddrinfo ENOTFOUND ${hostname}`))
+ : Promise.resolve([{ address, family: 4 }]);
+ });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ test("prefers the apple touch icon and resolves it to an absolute url", async () => {
+ mockResponses({
+ [websiteUrl]: createPage(
+ '<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");
+
+ expect(result).toBe("https://app.example.com/touch.png");
+ });
+
+ test("prefers the icon with the largest declared size", async () => {
+ mockResponses({
+ [websiteUrl]: createPage(
+ '<link rel="icon" href="/small.png" sizes="16x16"><link rel="icon" href="/large.png" sizes="128x128">',
+ ),
+ });
+
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBe("https://app.example.com/large.png");
+ });
+
+ test("resolves relative icons against the page that answered the request", async () => {
+ mockResponses({
+ [websiteUrl]: createRedirect("/login/"),
+ "https://app.example.com/login/": createPage('<link rel="icon" href="icon.png">'),
+ });
+
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBe("https://app.example.com/login/icon.png");
+ });
+
+ test("falls back to the well known favicon when the page declares no icon", async () => {
+ mockResponses({
+ "https://app.example.com/dashboard": createPage(""),
+ [faviconUrl]: createResponse({ contentType: "image/x-icon", body: "binary" }),
+ });
+
+ const result = await fetchFaviconUrlAsync("https://app.example.com/dashboard");
+
+ expect(result).toBe(faviconUrl);
+ });
+
+ test("falls back to the well known favicon of the origin that answered the request", async () => {
+ mockResponses({
+ [websiteUrl]: createRedirect("https://auth.example.net/login"),
+ "https://auth.example.net/login": createPage(""),
+ "https://auth.example.net/favicon.ico": createResponse({ contentType: "image/x-icon", body: "binary" }),
+ });
+
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBe("https://auth.example.net/favicon.ico");
+ });
+
+ test("falls back to the well known favicon of the origin that answered, even when that response carried no usable html", async () => {
+ mockResponses({
+ [websiteUrl]: createRedirect("https://auth.example.net/error"),
+ "https://auth.example.net/error": createResponse({ contentType: "application/json" }),
+ "https://auth.example.net/favicon.ico": createResponse({ contentType: "image/x-icon", body: "binary" }),
+ });
+
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBe("https://auth.example.net/favicon.ico");
+ });
+
+ test("ignores a well known favicon that answers with a page instead of an image", async () => {
+ mockResponses({
+ [websiteUrl]: createPage(""),
+ [faviconUrl]: createResponse({ contentType: "text/html", body: "<html></html>" }),
+ });
+
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBeNull();
+ });
+
+ test("reads a page that declares its media type in a different case", async () => {
+ mockResponses({
+ [websiteUrl]: createResponse({
+ contentType: "Text/HTML; charset=UTF-8",
+ body: '<html><head><link rel="icon" href="/icon.png"></head></html>',
+ }),
+ });
+
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBe("https://app.example.com/icon.png");
+ });
+
+ test("reads no more than 256 KiB of a page that arrives in a single chunk", async () => {
+ const padding = " ".repeat(256 * 1024);
+ mockResponses({
+ [websiteUrl]: createResponse({
+ contentType: "text/html",
+ body: `<html><head>${padding}<link rel="icon" href="/late.png"></head></html>`,
+ }),
+ [faviconUrl]: createResponse({ contentType: "image/x-icon", body: "binary" }),
+ });
+
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBe(faviconUrl);
+ });
+
+ test("ignores icons declared after the end of the head", async () => {
+ mockResponses({
+ [websiteUrl]: createResponse({
+ contentType: "text/html",
+ body: [
+ '<html><head><link rel="icon" href="/head.png"></he',
+ 'ad><body><header></header><link rel="apple-touch-icon" href="/body.png"></body></html>',
+ ],
+ }),
+ });
+
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBe("https://app.example.com/head.png");
+ });
+
+ test("ends the head at the body when the page leaves out </head>", async () => {
+ mockResponses({
+ [websiteUrl]: createResponse({
+ contentType: "text/html",
+ body: [
+ '<html><head><link rel="icon" href="/head.png"><bo',
+ 'dy><link rel="apple-touch-icon" href="/body.png"></body></html>',
+ ],
+ }),
+ });
+
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBe("https://app.example.com/head.png");
+ });
+
+ test("ignores a header element that is not the end of the head", async () => {
+ mockResponses({
+ [websiteUrl]: createResponse({
+ contentType: "text/html",
+ body: '<html><head><header></header><link rel="icon" href="/icon.png"></head></html>',
+ }),
+ });
+
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBe("https://app.example.com/icon.png");
+ });
+
+ test("parses a link tag with a very long attribute without stalling", async () => {
+ mockResponses({
+ [websiteUrl]: createPage(`<link ${"a".repeat(64 * 1024)}><link rel="icon" href="/icon.png">`),
+ });
+
+ const start = performance.now();
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBe("https://app.example.com/icon.png");
+ expect(performance.now() - start).toBeLessThan(500);
+ });
+
+ test("parses a head full of unclosed link tags without stalling", async () => {
+ mockResponses({
+ [websiteUrl]: createPage(`<link rel="icon" href="/icon.png">${"<link".repeat(50_000)}`),
+ });
+
+ const start = performance.now();
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBe("https://app.example.com/icon.png");
+ expect(performance.now() - start).toBeLessThan(500);
+ });
+
+ test("parses a very long sizes attribute without stalling", async () => {
+ mockResponses({
+ [websiteUrl]: createPage(`<link rel="icon" sizes="${"1".repeat(64 * 1024)}" href="/icon.png">`),
+ });
+
+ const start = performance.now();
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBe("https://app.example.com/icon.png");
+ expect(performance.now() - start).toBeLessThan(500);
+ });
+
+ test("sends no credentials and logs only the origin when the website fails", async () => {
+ mockedFetch.mockRejectedValue(new Error("connection refused"));
+
+ const result = await fetchFaviconUrlAsync("https://admin:[email protected]/home?token=abc#section");
+
+ expect(result).toBeNull();
+ expect(requestedUrls()).toEqual(["https://app.example.com/home?token=abc", faviconUrl]);
+ expect(debugLog.mock.calls.map(([, metadata]) => (metadata as { origin: string }).origin)).toEqual([
+ "https://app.example.com",
+ "https://app.example.com",
+ ]);
+ expect(JSON.stringify(debugLog.mock.calls)).not.toMatch(/admin|secret|token|section/);
+ });
+
+ test("bounds the page body and not only the response headers", async () => {
+ mockResponses({ [websiteUrl]: createPage('<link rel="icon" href="/icon.png">') });
+
+ await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(mockedCreateAgent.mock.calls[0]?.[1]?.bodyTimeout).toBeGreaterThan(0);
+ expect(mockedFetch.mock.calls[0]?.[1]?.signal).toBeInstanceOf(AbortSignal);
+ });
+
+ test("gives up on a page that keeps dripping its head after fifteen seconds", async () => {
+ vi.useFakeTimers();
+ mockedFetch.mockImplementation((input, init) =>
+ String(input) === websiteUrl
+ ? Promise.resolve(createDrippingPage(init?.signal))
+ : Promise.reject(new Error(`Unexpected request to ${String(input)}`)),
+ );
+
+ let settled = false;
+ const detection = fetchFaviconUrlAsync(websiteUrl).finally(() => (settled = true));
+ await vi.advanceTimersByTimeAsync(14_999);
+ expect(settled).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(1);
+ await expect(detection).resolves.toBeNull();
+ expect(requestedUrls()).toEqual([websiteUrl]);
+ });
+
+ test("returns null when the website cannot be reached", async () => {
+ mockedFetch.mockRejectedValue(new Error("connection refused"));
+
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBeNull();
+ });
+
+ test("rejects other protocols without sending a request", async () => {
+ const result = await fetchFaviconUrlAsync("ftp://app.example.com");
+
+ expect(result).toBeNull();
+ expect(mockedFetch).not.toHaveBeenCalled();
+ });
+
+ test("sends no request to a loopback address, not even for the well known favicon", async () => {
+ const result = await fetchFaviconUrlAsync("http://localhost:3000/");
+
+ expect(result).toBeNull();
+ expect(mockedFetch).not.toHaveBeenCalled();
+ });
+
+ test("does not follow the page to the cloud metadata service", async () => {
+ mockResponses({
+ [websiteUrl]: createRedirect("http://169.254.169.254/latest/meta-data/"),
+ [faviconUrl]: createResponse({ contentType: "image/x-icon", body: "binary" }),
+ });
+
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBe(faviconUrl);
+ expect(requestedUrls()).toEqual([websiteUrl, faviconUrl]);
+ });
+
+ test("does not follow the well known favicon to a loopback address", async () => {
+ mockResponses({
+ [websiteUrl]: createPage(""),
+ [faviconUrl]: createRedirect("http://127.0.0.1:7575/favicon.ico"),
+ });
+
+ const result = await fetchFaviconUrlAsync(websiteUrl);
+
+ expect(result).toBeNull();
+ expect(requestedUrls()).toEqual([websiteUrl, faviconUrl]);
+ });
+});
diff --git a/packages/icons/src/test/guarded-fetch.spec.ts b/packages/icons/src/test/guarded-fetch.spec.ts
new file mode 100644
index 000000000..a9c707b56
--- /dev/null
+++ b/packages/icons/src/test/guarded-fetch.spec.ts
@@ -0,0 +1,356 @@
+// @vitest-environment node
+import { lookup } from "node:dns/promises";
+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";
+
+vi.mock("node:dns/promises", () => ({ lookup: vi.fn() }));
+vi.mock("@homarr/core/infrastructure/http", () => ({
+ createCertificateAgentAsync: vi.fn(),
+ fetchWithTrustedCertificatesAsync: vi.fn(),
+}));
+
+type FetchResponse = Awaited<ReturnType<typeof fetchWithTrustedCertificatesAsync>>;
+type Dispatcher = Awaited<ReturnType<typeof createCertificateAgentAsync>>;
+
+const mockedLookup = vi.mocked(lookup as unknown as (hostname: string) => Promise<LookupAddress[]>);
+const mockedCreateAgent = vi.mocked(createCertificateAgentAsync);
+const mockedFetch = vi.mocked(fetchWithTrustedCertificatesAsync);
+
+const createResponse = (status: number, location?: string): FetchResponse =>
+ ({
+ status,
+ ok: status >= 200 && status < 300,
+ headers: { get: (name: string) => (name.toLowerCase() === "location" ? (location ?? null) : null) },
+ body: { cancel: () => Promise.resolve() },
+ }) as unknown as FetchResponse;
+
+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, FetchResponse>) => {
+ 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}`))
+ : Promise.resolve(response);
+ });
+};
+
+const requestedUrls = () => mockedFetch.mock.calls.map(([input]) => String(input));
+
+const pinnedLookupOfRequest = (index: number): LookupFunction => {
+ const lookupFunction = mockedCreateAgent.mock.calls[index]?.[0]?.lookup;
+ if (lookupFunction === undefined) throw new Error(`Request ${index} was not given a pinned lookup`);
+ return lookupFunction;
+};
+
+const lookupThroughPinnedAsync = (pinnedLookup: LookupFunction, hostname: string) =>
+ new Promise<string>((resolve, reject) => {
+ pinnedLookup(hostname, {}, (error, address) => (error ? reject(error) : resolve(address as string)));
+ });
+
+const fetchStatusAsync = (url: string, signal?: AbortSignal) =>
+ fetchGuardedAsync(new URL(url), { timeout: 1_000, signal }, (response, finalUrl) =>
+ Promise.resolve({ status: response.status, url: finalUrl.href }),
+ );
+
+const never = <T>() => new Promise<T>(() => undefined);
+
+describe("fetchGuardedAsync", () => {
+ beforeEach(() => {
+ mockedLookup.mockReset();
+ mockedFetch.mockReset();
+ mockedCreateAgent.mockReset();
+ mockedCreateAgent.mockImplementation(() =>
+ Promise.resolve({ destroy: () => Promise.resolve() } as unknown as Dispatcher),
+ );
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ test.each([
+ ["ipv4 loopback", "http://127.0.0.1/"],
+ ["the far end of the ipv4 loopback range", "http://127.255.0.9/"],
+ ["ipv4 loopback written as a single number", "http://2130706433/"],
+ ["ipv6 loopback", "http://[::1]/"],
+ ["the unspecified ipv4 address", "http://0.0.0.0/"],
+ ["the this-network range", "http://0.1.2.3/"],
+ ["the unspecified ipv6 address", "http://[::]/"],
+ ["the cloud metadata service", "http://169.254.169.254/latest/meta-data/"],
+ ["ipv4 link-local", "http://169.254.10.20/"],
+ ["ipv6 link-local", "http://[fe80::1]/"],
+ ["the ipv6 metadata service of aws", "http://[fd00:ec2::254]/"],
+ ["the metadata service of alibaba cloud", "http://100.100.100.200/"],
+ ["the wireserver of azure", "http://168.63.129.16/"],
+ ["ipv4 multicast", "http://224.0.0.251/"],
+ ["ipv6 multicast", "http://[ff02::1]/"],
+ ["the ipv4 broadcast address", "http://255.255.255.255/"],
+ ["ipv4-mapped loopback", "http://[::ffff:127.0.0.1]/"],
+ ["ipv4-mapped metadata service", "http://[::ffff:169.254.169.254]/"],
+ ["ipv4-mapped wireserver of azure", "http://[::ffff:168.63.129.16]/"],
+ ["ipv4-mapped unspecified address", "http://[::ffff:0.0.0.0]/"],
+ ["ipv4-mapped multicast", "http://[::ffff:224.0.0.1]/"],
+ ["ipv4-mapped loopback in full notation", "http://[0:0:0:0:0:ffff:7f00:1]/"],
+ ["loopback behind nat64", "http://[64:ff9b::7f00:1]/"],
+ ["the metadata service behind nat64", "http://[64:ff9b::a9fe:a9fe]/"],
+ ["loopback behind 6to4", "http://[2002:7f00:1::]/"],
+ ["the metadata service behind 6to4", "http://[2002:a9fe:a9fe::1]/"],
+ ])("refuses %s without sending a request", async (_name, url) => {
+ await expect(fetchStatusAsync(url)).rejects.toThrow(/Refusing/);
+
+ expect(mockedFetch).not.toHaveBeenCalled();
+ });
+
+ test.each([
+ ["a class c private address", "http://192.168.1.10/", "192.168.1.10"],
+ ["a class a private address", "http://10.0.0.5/", "10.0.0.5"],
+ ["a class b private address", "http://172.16.3.4/", "172.16.3.4"],
+ ["a carrier grade nat address", "http://100.64.1.2/", "100.64.1.2"],
+ ["an ipv6 unique local address", "http://[fd12:3456::1]/", "fd12:3456::1"],
+ ["an ipv4-mapped private address", "http://[::ffff:c0a8:10a]/", "::ffff:c0a8:10a"],
+ ["a public address", "https://93.184.216.34/", "93.184.216.34"],
+ ["a public address behind nat64", "http://[64:ff9b::5db8:d822]/", "64:ff9b::5db8:d822"],
+ ["a public address behind 6to4", "http://[2002:5db8:d822::1]/", "2002:5db8:d822::1"],
+ ])("allows %s", async (_name, url, address) => {
+ mockResponses({ [url]: createResponse(200) });
+
+ await expect(fetchStatusAsync(url)).resolves.toEqual({ status: 200, url });
+ await expect(lookupThroughPinnedAsync(pinnedLookupOfRequest(0), "ignored")).resolves.toBe(address);
+ });
+
+ test("allows a hostname in the local network and connects to the address it resolved to", async () => {
+ mockDns({ "nas.lan": ["192.168.1.20"] });
+ mockResponses({ "http://nas.lan:5000/": createResponse(200) });
+
+ await expect(fetchStatusAsync("http://nas.lan:5000/")).resolves.toEqual({
+ status: 200,
+ url: "http://nas.lan:5000/",
+ });
+ await expect(lookupThroughPinnedAsync(pinnedLookupOfRequest(0), "nas.lan")).resolves.toBe("192.168.1.20");
+ });
+
+ test("refuses a hostname that resolves to a blocked address", async () => {
+ mockDns({ "evil.example.com": ["127.0.0.1"] });
+
+ await expect(fetchStatusAsync("http://evil.example.com/")).rejects.toThrow(/Refusing/);
+ expect(mockedFetch).not.toHaveBeenCalled();
+ });
+
+ test("refuses a hostname when any of its addresses is blocked", async () => {
+ mockDns({ "mixed.example.com": ["93.184.216.34", "169.254.169.254"] });
+
+ await expect(fetchStatusAsync("http://mixed.example.com/")).rejects.toThrow(/169\.254\.169\.254/);
+ expect(mockedFetch).not.toHaveBeenCalled();
+ });
+
+ test("keeps connecting to the checked address when the hostname starts resolving to a blocked one", async () => {
+ mockDns({ "rebind.example.com": ["192.168.1.30"] });
+ mockResponses({ "http://rebind.example.com/": createResponse(200) });
+
+ await fetchStatusAsync("http://rebind.example.com/");
+ mockDns({ "rebind.example.com": ["127.0.0.1"] });
+
+ const pinnedLookup = pinnedLookupOfRequest(0);
+ await expect(lookupThroughPinnedAsync(pinnedLookup, "rebind.example.com")).resolves.toBe("192.168.1.30");
+ await expect(lookupThroughPinnedAsync(pinnedLookup, "rebind.example.com")).resolves.toBe("192.168.1.30");
+ expect(mockedLookup).toHaveBeenCalledTimes(1);
+ });
+
+ test("answers only with checked addresses of the requested family", async () => {
+ mockDns({ "dual.example.com": ["93.184.216.34", "2606:2800:220:1::1"] });
+ mockResponses({ "http://dual.example.com/": createResponse(200) });
+
+ await fetchStatusAsync("http://dual.example.com/");
+
+ const pinnedLookup = pinnedLookupOfRequest(0);
+ const addressesOf = (family: number) =>
+ new Promise<unknown>((resolve) => {
+ pinnedLookup("dual.example.com", { family, all: true }, (_error, addresses) => resolve(addresses));
+ });
+ await expect(addressesOf(6)).resolves.toEqual([{ address: "2606:2800:220:1::1", family: 6 }]);
+ await expect(addressesOf(4)).resolves.toEqual([{ address: "93.184.216.34", family: 4 }]);
+ });
+
+ test("connects directly, follows redirects by hand and bounds the body", async () => {
+ mockResponses({ "http://192.168.1.10/": createResponse(200) });
+
+ await fetchStatusAsync("http://192.168.1.10/");
+
+ expect(mockedCreateAgent.mock.calls[0]?.[1]).toMatchObject({
+ bodyTimeout: 1_000,
+ httpProxy: "",
+ httpsProxy: "",
+ noProxy: "*",
+ });
+ expect(mockedFetch.mock.calls[0]?.[1]).toMatchObject({ redirect: "manual", signal: expect.any(AbortSignal) });
+ expect(mockedFetch.mock.calls[0]?.[1]?.dispatcher).toBe(await mockedCreateAgent.mock.results[0]?.value);
+ });
+
+ test("gives up on a hostname whose lookup never answers", async () => {
+ vi.useFakeTimers();
+ mockedLookup.mockImplementation(never);
+
+ let settled = false;
+ const request = fetchStatusAsync("http://slow-dns.example.com/").finally(() => (settled = true));
+ await vi.advanceTimersByTimeAsync(999);
+ expect(settled).toBe(false);
+
+ const assertion = expect(request).rejects.toThrow(/timed out/);
+ await vi.advanceTimersByTimeAsync(1);
+ await assertion;
+ expect(mockedFetch).not.toHaveBeenCalled();
+ });
+
+ test("gives up on a server that never sends its response headers", async () => {
+ vi.useFakeTimers();
+ mockedFetch.mockImplementation(
+ (_input, init) =>
+ new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => reject(init.signal?.reason));
+ }),
+ );
+
+ const assertion = expect(fetchStatusAsync("http://192.168.1.10/")).rejects.toThrow(/timed out/);
+ await vi.advanceTimersByTimeAsync(1_000);
+ await assertion;
+ });
+
+ test("sends no further request once the caller aborted", async () => {
+ const controller = new AbortController();
+ mockedFetch.mockImplementation(() => {
+ controller.abort(new Error("caller gave up"));
+ return Promise.resolve(createResponse(302, "/next"));
+ });
+
+ await expect(fetchStatusAsync("http://192.168.1.10/", controller.signal)).rejects.toThrow(/caller gave up/);
+ expect(requestedUrls()).toEqual(["http://192.168.1.10/"]);
+ });
+
+ test("follows a redirect and checks the new target again", async () => {
+ mockDns({ "app.example.com": ["93.184.216.34"], "login.example.com": ["192.168.1.40"] });
+ mockResponses({
+ "http://app.example.com/": createResponse(302, "http://login.example.com/sign-in"),
+ "http://login.example.com/sign-in": createResponse(200),
+ });
+
+ await expect(fetchStatusAsync("http://app.example.com/")).resolves.toEqual({
+ status: 200,
+ url: "http://login.example.com/sign-in",
+ });
+ expect(mockedLookup).toHaveBeenCalledWith("login.example.com", expect.anything());
+ await expect(lookupThroughPinnedAsync(pinnedLookupOfRequest(1), "login.example.com")).resolves.toBe("192.168.1.40");
+ });
+
+ test("refuses a redirect to a blocked address", async () => {
+ mockResponses({ "http://192.168.1.10/": createResponse(301, "http://169.254.169.254/latest/meta-data/") });
+
+ await expect(fetchStatusAsync("http://192.168.1.10/")).rejects.toThrow(/Refusing/);
+ expect(requestedUrls()).toEqual(["http://192.168.1.10/"]);
+ });
+
+ test("refuses a redirect to a hostname that resolves to a blocked address", async () => {
+ mockDns({ localhost: ["127.0.0.1", "::1"] });
+ mockResponses({ "http://192.168.1.10/": createResponse(307, "http://localhost:8080/admin") });
+
+ await expect(fetchStatusAsync("http://192.168.1.10/")).rejects.toThrow(/Refusing/);
+ expect(requestedUrls()).toEqual(["http://192.168.1.10/"]);
+ });
+
+ test("refuses a redirect to another protocol", async () => {
+ mockResponses({ "http://192.168.1.10/": createResponse(302, "file:///etc/passwd") });
+
+ await expect(fetchStatusAsync("http://192.168.1.10/")).rejects.toThrow(/Refusing/);
+ expect(requestedUrls()).toEqual(["http://192.168.1.10/"]);
+ });
+
+ test("follows five redirects", async () => {
+ const hops = Array.from({ length: 6 }, (_, index) => `http://192.168.1.10/${index}`);
+ mockResponses({
+ ...Object.fromEntries(hops.slice(0, 5).map((hop, index) => [hop, createResponse(302, `/${index + 1}`)])),
+ [hops[5] as string]: createResponse(200),
+ });
+
+ await expect(fetchStatusAsync(hops[0] as string)).resolves.toEqual({ status: 200, url: hops[5] });
+ expect(requestedUrls()).toEqual(hops);
+ });
+
+ test("gives up after more than five redirects", async () => {
+ const hops = Array.from({ length: 7 }, (_, index) => `http://192.168.1.10/${index}`);
+ mockResponses(Object.fromEntries(hops.map((hop, index) => [hop, createResponse(302, `/${index + 1}`)])));
+
+ await expect(fetchStatusAsync(hops[0] as string)).rejects.toThrow(/Too many redirects/);
+ expect(requestedUrls()).toEqual(hops.slice(0, 6));
+ });
+
+ test("gives up on a redirect loop", async () => {
+ mockResponses({
+ "http://192.168.1.10/a": createResponse(302, "/b"),
+ "http://192.168.1.10/b": createResponse(302, "/a"),
+ });
+
+ await expect(fetchStatusAsync("http://192.168.1.10/a")).rejects.toThrow(/Too many redirects/);
+ expect(mockedFetch).toHaveBeenCalledTimes(6);
+ });
+
+ test("drops credentials from a redirect target", async () => {
+ mockResponses({
+ "http://192.168.1.10/": createResponse(302, "http://admin:[email protected]/next?page=2"),
+ "http://192.168.1.20/next?page=2": createResponse(200),
+ });
+
+ await expect(fetchStatusAsync("http://192.168.1.10/")).resolves.toEqual({
+ status: 200,
+ url: "http://192.168.1.20/next?page=2",
+ });
+ });
+
+ test.each([
+ ["a refused address", {}, "http://127.0.0.1/home?token=abc", "Refusing to request http://127.0.0.1 because"],
+ [
+ "an invalid redirect location",
+ { "http://192.168.1.10/home?token=abc": createResponse(302, "http://[broken") },
+ "http://192.168.1.10/home?token=abc",
+ "Invalid redirect location from http://192.168.1.10",
+ ],
+ [
+ "a redirect loop",
+ { "http://192.168.1.10/home?token=abc": createResponse(302, "/home?token=abc") },
+ "http://192.168.1.10/home?token=abc",
+ "Too many redirects starting at http://192.168.1.10",
+ ],
+ ])("names only the origin in the error for %s", async (_name, responses, url, message) => {
+ mockResponses(responses);
+
+ const error = await fetchStatusAsync(url).catch((caught: unknown) => caught);
+
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toContain(message);
+ expect((error as Error).message).not.toMatch(/home|token/);
+ });
+
+ test("closes the connection of every hop", async () => {
+ const destroy = vi.fn(() => Promise.resolve());
+ mockedCreateAgent.mockImplementation(() => Promise.resolve({ destroy } as unknown as Dispatcher));
+ mockResponses({
+ "http://192.168.1.10/": createResponse(302, "/next"),
+ "http://192.168.1.10/next": createResponse(200),
+ });
+
+ await fetchStatusAsync("http://192.168.1.10/");
+
+ expect(destroy).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/translation/src/lang/en.json b/packages/translation/src/lang/en.json
index fe555b85c..b8848b029 100644
--- a/packages/translation/src/lang/en.json
+++ b/packages/translation/src/lang/en.json
@@ -1935,6 +1935,7 @@
"clear": "Clear image",
"uploadImage": "Upload image",
"results": "Image search results",
+ "websiteIcon": "Icon of the website",
"localImages": "Your images",
"svgIcons": "SVG icons",
"otherImages": "Other images",
diff --git a/packages/validation/src/icons.ts b/packages/validation/src/icons.ts
index a577c39b6..9d17392d7 100644
--- a/packages/validation/src/icons.ts
+++ b/packages/validation/src/icons.ts
@@ -4,3 +4,11 @@ export const iconsFindSchema = z.object({
searchText: z.string().optional(),
limitPerGroup: z.number().min(1).max(500).default(12),
});
+
+export const iconsDetectFaviconSchema = z.object({
+ href: z
+ .string()
+ .trim()
+ .url()
+ .regex(/^https?:\/\//i), // Only allow http and https for security reasons (javascript: is not allowed)
+});