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.

10.7 KB
Raw Blame
import type { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
import { cancelBodyAsync, fetchGuardedAsync } from "@homarr/core/infrastructure/http";
import { createLogger } from "@homarr/core/infrastructure/logs";

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> =>
  (await fetchWebsiteMetadataAsync(href)).iconUrl;

export interface WebsiteMetadata {
  title: string | null;
  iconUrl: string | null;
}

/**
 * Resolves the title and icon of a website with the same requests and safeguards as
 * fetchFaviconUrlAsync. Either value is `null` when it cannot be determined.
 */
export const fetchWebsiteMetadataAsync = async (href: string): Promise<WebsiteMetadata> => {
  const websiteUrl = parseHttpUrl(href);
  if (websiteUrl === null) return { title: null, iconUrl: null };

  const deadline = new AbortController();
  const timer = setTimeout(() => deadline.abort(new Error("Favicon detection timed out")), detectionTimeoutInMs);
  try {
    return await detectWebsiteMetadataAsync(websiteUrl, deadline.signal);
  } finally {
    clearTimeout(timer);
  }
};

const detectWebsiteMetadataAsync = async (websiteUrl: URL, signal: AbortSignal): Promise<WebsiteMetadata> => {
  const page = await fetchPageAsync(websiteUrl, signal);
  const title = page?.html == null ? null : findTitle(page.html);
  const declaredIconUrl = page?.html == null ? null : findDeclaredIconUrl(page.html, page.url);
  if (declaredIconUrl !== null) return { title, iconUrl: declaredIconUrl };

  // The well known icon belongs to the origin that served the page, which differs from the
  // requested one when the app redirects across origins.
  const wellKnownUrl = new URL("/favicon.ico", page?.url.origin ?? websiteUrl.origin);
  return { title, iconUrl: (await isImageAsync(wellKnownUrl, signal)) ? wellKnownUrl.href : null };
};

// Credentials in the app url are never sent to the site, and leaving them out here keeps
// 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;

// Like the link tag, the title tag and its text end at the next "<", so unclosed titles are
// scanned once. Entities have a bounded length for the same reason.
const titleRegex = /<title\b[^<>]*>([^<]*)/i;
const entityRegex = /&(#x[\da-f]{1,6}|#\d{1,7}|[a-z]{2,8});/gi;
const namedEntities: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
const maximumTitleLength = 512;

const findTitle = (html: string): string | null => {
  const rawTitle = titleRegex.exec(html)?.[1]?.slice(0, maximumTitleLength);
  if (rawTitle === undefined) return null;

  const title = decodeEntities(rawTitle).replaceAll(/\s+/g, " ").trim();
  return title.length > 0 ? title : null;
};

const decodeEntities = (text: string): string =>
  text.replaceAll(entityRegex, (entity, name: string) => {
    if (!name.startsWith("#")) return namedEntities[name.toLowerCase()] ?? entity;

    const codePoint = name[1]?.toLowerCase() === "x" ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
    return codePoint > 0 && codePoint <= 0x10ffff ? String.fromCodePoint(codePoint) : entity;
  });

const findDeclaredIconUrl = (html: string, pageUrl: URL): string | null => {
  const candidates: IconCandidate[] = [];

  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;
  }
};