πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Implement dynamic favicon fetching and add API route for favicon retrieval
Bill Yang948621644ba0
diff --git a/client/src/components/Favicon.test.tsx b/client/src/components/Favicon.test.tsxnew file mode 100644index 000000000..2b4b22623--- /dev/null+++ b/client/src/components/Favicon.test.tsx@@ -0,0 +1,47 @@+import React from "react";+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { Favicon } from "./Favicon";++vi.mock("@/lib/const", async importOriginal => ({+ ...(await importOriginal<typeof import("@/lib/const")>()),+ BACKEND_URL: "https://app.rybbit.com/api",+}));++afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++describe("Favicon", () => {+ it("loads the site's icon through Rybbit rather than a search engine cache", () => {+ render(<Favicon domain="example.com" />);+ const url = new URL(screen.getByRole("img").getAttribute("src")!);+ expect(url.origin + url.pathname).toBe("https://app.rybbit.com/api/favicon");+ expect(url.searchParams.get("domain")).toBe("example.com");+ });++ it("retries a failed icon when switching sites", () => {+ const view = render(<Favicon domain="old.example.com" />);+ fireEvent.error(screen.getByRole("img"));+ expect(screen.queryByRole("img")).toBeNull();+ view.rerender(<Favicon domain="new.example.com" />);+ expect(screen.getByRole("img").getAttribute("alt")).toBe("Favicon for new.example.com");+ view.rerender(<Favicon domain="old.example.com" />);+ expect(screen.getByRole("img")).toBeTruthy();+ });++ it("refreshes icons and retries failures in an open dashboard after an hour", () => {+ vi.useFakeTimers();+ const view = render(<Favicon domain="example.com" />);+ const firstSrc = screen.getByRole("img").getAttribute("src");+ act(() => vi.advanceTimersByTime(60 * 60 * 1000));+ expect(screen.getByRole("img").getAttribute("src")).not.toBe(firstSrc);+ fireEvent.error(screen.getByRole("img"));+ expect(screen.queryByRole("img")).toBeNull();+ act(() => vi.advanceTimersByTime(60 * 60 * 1000));+ expect(screen.getByRole("img")).toBeTruthy();+ view.unmount();+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/client/src/components/Favicon.tsx b/client/src/components/Favicon.tsxindex 6c65f8e7b..73b5c140a 100644--- a/client/src/components/Favicon.tsx+++ b/client/src/components/Favicon.tsx@@ -1,10 +1,23 @@-import { useState } from "react";+"use client";++import { useEffect, useState } from "react";+import { BACKEND_URL } from "@/lib/const";import { cn } from "../lib/utils";export function Favicon({ domain, className }: { domain: string; className?: string }) {- const [imageError, setImageError] = useState(false);- const firstLetter = domain.charAt(0).toUpperCase();+ const [refreshVersion, setRefreshVersion] = useState(0);+ const src = `${BACKEND_URL}/favicon?domain=${encodeURIComponent(domain)}&v=${refreshVersion}`;++ useEffect(() => {+ const timer = setInterval(() => setRefreshVersion(Date.now()), 60 * 60 * 1000);+ return () => clearInterval(timer);+ }, []);+ return <FaviconImage key={src} src={src} domain={domain} className={className} />;+}++function FaviconImage({ src, domain, className }: { src: string; domain: string; className?: string }) {+ const [imageError, setImageError] = useState(false);if (imageError) {return (<div@@ -13,14 +26,14 @@ export function Favicon({ domain, className }: { domain: string; className?: strclassName ?? "w-4 h-4")}>- {firstLetter}+ {domain.charAt(0).toUpperCase()}</div>);}return (<img- src={`https://icons.duckduckgo.com/ip3/${domain}.ico`}+ src={src}className={cn(className ?? "w-4 h-4")}alt={`Favicon for ${domain}`}onError={() => setImageError(true)}diff --git a/server/src/api/__snapshots__/routes.test.ts.snap b/server/src/api/__snapshots__/routes.test.ts.snapindex a96ad90ec..b1eda930e 100644--- a/server/src/api/__snapshots__/routes.test.ts.snap+++ b/server/src/api/__snapshots__/routes.test.ts.snap@@ -27,6 +27,7 @@ exports[`API route table > pins the access each route requires 1`] = `"GET /api/admin/sites β system-admin","GET /api/admin/subscription-plans β system-admin","GET /api/config β public",+ "GET /api/favicon β public","GET /api/gsc/callback β public","GET /api/health β public","GET /api/mcp β public",diff --git a/server/src/api/routes.ts b/server/src/api/routes.tsindex 243ab198e..21760c86f 100644--- a/server/src/api/routes.ts+++ b/server/src/api/routes.ts@@ -143,6 +143,7 @@ import {deleteSite,deleteSiteImport,getEmbedStats,+ getFavicon,getSite,getSiteExcludedCountries,getSiteExcludedHostnames,@@ -446,6 +447,11 @@ async function sessionReplayRoutes(fastify: FastifyInstance) {}async function sitesRoutes(fastify: FastifyInstance) {+ fastify.get(+ "/favicon",+ { config: { access: "public" as RouteAccess, rateLimit: { max: 120, timeWindow: "1 minute" } } },+ getFavicon+ );// Sitesfastify.get("/sites/:siteId", publicSitesRead, getSite);fastify.put("/sites/:siteId/config", site("sites:configure"), updateSiteConfig);diff --git a/server/src/api/sites/getFavicon.test.ts b/server/src/api/sites/getFavicon.test.tsnew file mode 100644index 000000000..ce0bef916--- /dev/null+++ b/server/src/api/sites/getFavicon.test.ts@@ -0,0 +1,50 @@+import Fastify from "fastify";+import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from "vitest";+import { faviconService } from "../../services/favicon/favicon.js";+import { getFavicon } from "./getFavicon.js";++const server = Fastify();+server.get("/favicon", getFavicon);+let get: MockInstance<typeof faviconService.get>;+beforeEach(() => {+ get = vi.spyOn(faviconService, "get");+});+afterEach(() => vi.restoreAllMocks());++describe("favicon endpoint", () => {+ it("returns image bytes with only the remaining cache lifetime", async () => {+ get.mockResolvedValue({+ icon: { body: Buffer.from("icon"), contentType: "image/png" },+ expiresAt: Date.now() + 60_000,+ });+ const response = await server.inject("/favicon?domain=Example.com.&v=123");+ expect(response.statusCode).toBe(200);+ expect(response.body).toBe("icon");+ expect(get).toHaveBeenCalledWith("example.com");+ expect(response.headers["content-type"]).toBe("image/png");+ expect(response.headers["cache-control"]).toMatch(/^public, max-age=(59|60), must-revalidate$/);+ expect(response.headers["content-security-policy"]).toBe("default-src 'none'; sandbox");+ expect(response.headers["x-content-type-options"]).toBe("nosniff");+ });++ it.each([+ "",+ "?domain=https://example.com",+ "[email protected]",+ "?domain=example.com/path",+ "?domain=example.com:8080",+ ])("rejects malformed domains without fetching: %s", query => {+ return server.inject(`/favicon${query}`).then(response => {+ expect(response.statusCode).toBe(400);+ expect(get).not.toHaveBeenCalled();+ expect(response.headers["cache-control"]).toBe("no-store");+ });+ });++ it("does not browser-cache missing icons", async () => {+ get.mockResolvedValue({ icon: null, expiresAt: Date.now() + 300_000 });+ const response = await server.inject("/favicon?domain=example.com");+ expect(response.statusCode).toBe(404);+ expect(response.headers["cache-control"]).toBe("no-store");+ });+});diff --git a/server/src/api/sites/getFavicon.ts b/server/src/api/sites/getFavicon.tsnew file mode 100644index 000000000..40c5c9d0f--- /dev/null+++ b/server/src/api/sites/getFavicon.ts@@ -0,0 +1,19 @@+import type { FastifyReply, FastifyRequest } from "fastify";+import { faviconService, normalizeFaviconDomain } from "../../services/favicon/favicon.js";++export async function getFavicon(request: FastifyRequest<{ Querystring: { domain?: string } }>, reply: FastifyReply) {+ const domain = normalizeFaviconDomain(request.query.domain);+ reply.header("X-Content-Type-Options", "nosniff");+ if (!domain)+ return reply.header("Cache-Control", "no-store").status(400).send({ error: "A valid domain is required" });+ const result = await faviconService.get(domain);+ if (!result.icon) return reply.header("Cache-Control", "no-store").status(404).send({ error: "Favicon not found" });+ // Use the remaining lifetime so browser/CDN caches cannot extend stale bytes+ // for another full hour just before the server's cached entry expires.+ const maxAge = Math.max(0, Math.floor((result.expiresAt - Date.now()) / 1000));+ return reply+ .header("Cache-Control", `public, max-age=${maxAge}, must-revalidate`)+ .header("Content-Security-Policy", "default-src 'none'; sandbox")+ .type(result.icon.contentType)+ .send(result.icon.body);+}diff --git a/server/src/api/sites/index.ts b/server/src/api/sites/index.tsindex 4688b43f6..5c2d13218 100644--- a/server/src/api/sites/index.ts+++ b/server/src/api/sites/index.ts@@ -9,6 +9,7 @@ export { checkInstall } from "./checkInstall.js";export { getSiteIsPublic } from "./getSiteIsPublic.js";export { getSiteUsage } from "./getSiteUsage.js";export { getEmbedStats } from "./getEmbedStats.js";+export { getFavicon } from "./getFavicon.js";export { getSitesFromOrg } from "./getSitesFromOrg.js";export { moveSite } from "./moveSite.js";export { updateSiteConfig } from "./updateSiteConfig.js";diff --git a/server/src/lib/publicHttpFetch.test.ts b/server/src/lib/publicHttpFetch.test.tsnew file mode 100644index 000000000..1ae33ac19--- /dev/null+++ b/server/src/lib/publicHttpFetch.test.ts@@ -0,0 +1,116 @@+import { EventEmitter } from "node:events";+import { Readable } from "node:stream";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { fetchPublicHttp, isPublicHttpAddress } from "./publicHttpFetch.js";++const mocks = vi.hoisted(() => ({ lookup: vi.fn(), request: vi.fn() }));+vi.mock("node:dns/promises", () => ({ lookup: mocks.lookup }));+vi.mock("node:http", () => ({ request: mocks.request }));+vi.mock("node:https", () => ({ request: mocks.request }));++beforeEach(() => {+ mocks.lookup.mockReset().mockResolvedValue([{ address: "93.184.216.34", family: 4 }]);+ mocks.request.mockReset();+});++function respond(status = 200, headers: Record<string, string> = {}, chunks = [Buffer.from("icon")]) {+ mocks.request.mockImplementationOnce((_url, _options, callback) => {+ const response = Object.assign(Readable.from(chunks), { statusCode: status, headers });+ const request = Object.assign(new EventEmitter(), { end: () => callback(response) });+ return request;+ });+}++function fetchUrl(url = "https://example.com/") {+ return fetchPublicHttp(new URL(url), { signal: AbortSignal.timeout(1000), maxBytes: 32 });+}++describe("public HTTP fetch", () => {+ it("pins the connection to validated DNS addresses and revalidates upstream caches", async () => {+ respond();+ expect((await fetchUrl()).body.toString()).toBe("icon");+ const options = mocks.request.mock.calls[0][1];+ const callback = vi.fn();+ options.lookup("example.com", {}, callback);+ expect(callback).toHaveBeenCalledWith(null, "93.184.216.34", 4);+ expect(mocks.lookup).toHaveBeenCalledTimes(1);+ expect(options.headers["Cache-Control"]).toBe("no-cache");+ expect(options.agent).toBe(false);+ });++ it.each([+ "http://127.0.0.1/",+ "http://169.254.169.254/",+ "http://[::1]/",+ "http://[::ffff:7f00:1]/",+ "file:///etc/passwd",+ "https://example.com:8080/",+ "https://user:[email protected]/",+ "https://service.local/",+ ])("blocks unsafe targets: %s", async url => {+ await expect(fetchUrl(url)).rejects.toThrow();+ expect(mocks.request).not.toHaveBeenCalled();+ });++ it("rejects a hostname with any private DNS result", async () => {+ mocks.lookup.mockResolvedValue([+ { address: "93.184.216.34", family: 4 },+ { address: "10.0.0.1", family: 4 },+ ]);+ await expect(fetchUrl()).rejects.toThrow("Non-public");+ expect(mocks.request).not.toHaveBeenCalled();+ });++ it("rejects a redirect to an internal target", async () => {+ respond(302, { location: "http://169.254.169.254/latest/meta-data/" });+ await expect(fetchUrl()).rejects.toThrow("Non-public");+ expect(mocks.request).toHaveBeenCalledTimes(1);+ });++ it("resolves relative redirects and bounds the redirect count", async () => {+ for (let i = 0; i < 4; i++) respond(302, { location: "/next" });+ await expect(fetchUrl()).rejects.toThrow("Too many redirects");+ expect(mocks.request).toHaveBeenCalledTimes(4);+ expect(mocks.request.mock.calls[1][0].href).toBe("https://example.com/next");+ });++ it("caps streamed responses without trusting Content-Length", async () => {+ respond(200, {}, [Buffer.alloc(20), Buffer.alloc(20)]);+ await expect(fetchUrl()).rejects.toThrow("Response too large");+ });++ it("bounds DNS resolution by the overall abort signal", async () => {+ mocks.lookup.mockImplementation(() => new Promise(() => {}));+ const controller = new AbortController();+ const pending = fetchPublicHttp(new URL("https://example.com/"), { signal: controller.signal, maxBytes: 32 });+ controller.abort(new Error("Deadline exceeded"));+ await expect(pending).rejects.toThrow("Deadline exceeded");+ expect(mocks.request).not.toHaveBeenCalled();+ });+});++describe("public HTTP addresses", () => {+ it.each([+ "0.0.0.0",+ "10.0.0.1",+ "100.64.0.1",+ "192.0.2.1",+ "198.51.100.1",+ "203.0.113.1",+ "224.0.0.1",+ "::",+ "::1",+ "fd00::1",+ "fe80::1",+ "::ffff:a00:1",+ "64:ff9b::a00:1",+ "2001:db8::1",+ "2002:a00:1::1",+ "3fff::1",+ ])("blocks private and reserved addresses: %s", address => {+ expect(isPublicHttpAddress(address)).toBe(false);+ });+ it.each(["93.184.216.34", "8.8.8.8", "2606:4700:4700::1111"])("allows public addresses: %s", address => {+ expect(isPublicHttpAddress(address)).toBe(true);+ });+});diff --git a/server/src/lib/publicHttpFetch.ts b/server/src/lib/publicHttpFetch.tsnew file mode 100644index 000000000..338cc2682--- /dev/null+++ b/server/src/lib/publicHttpFetch.ts@@ -0,0 +1,124 @@+import { Address4, Address6 } from "ip-address";+import { lookup } from "node:dns/promises";+import { request as httpRequest, type IncomingHttpHeaders } from "node:http";+import { request as httpsRequest } from "node:https";+import { isIP, type LookupFunction } from "node:net";++const BLOCKED_V4 = [+ "0.0.0.0/8",+ "10.0.0.0/8",+ "100.64.0.0/10",+ "127.0.0.0/8",+ "169.254.0.0/16",+ "172.16.0.0/12",+ "192.0.0.0/24",+ "192.0.2.0/24",+ "192.168.0.0/16",+ "198.18.0.0/15",+ "198.51.100.0/24",+ "203.0.113.0/24",+ "224.0.0.0/3",+].map(cidr => new Address4(cidr));+const GLOBAL_V6 = new Address6("2000::/3");+const BLOCKED_V6 = ["2001::/23", "2001:db8::/32", "2002::/16", "3fff::/20"].map(cidr => new Address6(cidr));++export function isPublicHttpAddress(address: string): boolean {+ if (isIP(address) === 4) {+ const ip = new Address4(address);+ return !BLOCKED_V4.some(range => ip.isInSubnet(range));+ }+ if (isIP(address) === 6) {+ const ip = new Address6(address);+ return ip.isInSubnet(GLOBAL_V6) && !BLOCKED_V6.some(range => ip.isInSubnet(range));+ }+ return false;+}++export interface PublicHttpResponse {+ body: Buffer;+ headers: IncomingHttpHeaders;+ status: number;+ url: URL;+}++// Resolve once and pin the connection to those addresses, including every+// redirect. A separate validation followed by fetch would allow DNS rebinding.+export async function fetchPublicHttp(+ input: URL,+ { signal, maxBytes }: { signal: AbortSignal; maxBytes: number }+): Promise<PublicHttpResponse> {+ let url = input;+ for (let hop = 0; hop <= 3; hop++) {+ signal.throwIfAborted();+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.port) {+ throw new Error("Only public HTTP(S) URLs on standard ports are allowed");+ }+ const host = url.hostname.replace(/^\[|\]$/g, "").replace(/\.$/, "");+ if ((!host.includes(".") && !isIP(host)) || /\.(localhost|local|internal|home|lan|test|invalid)$/i.test(host)) {+ throw new Error("Internal hostnames are not allowed");+ }+ const addresses = isIP(host)+ ? [{ address: host, family: isIP(host) }]+ : await new Promise<Array<{ address: string; family: number }>>((resolve, reject) => {+ const abort = () => reject(signal.reason);+ signal.addEventListener("abort", abort, { once: true });+ lookup(host, { all: true, verbatim: true })+ .then(resolve, reject)+ .finally(() => signal.removeEventListener("abort", abort));+ });+ signal.throwIfAborted();+ if (!addresses.length || addresses.some(({ address }) => !isPublicHttpAddress(address))) {+ throw new Error("Non-public addresses are not allowed");+ }+ const pinnedLookup: LookupFunction = (_host, options, callback) => {+ if (options.all) callback(null, addresses);+ else callback(null, addresses[0].address, addresses[0].family);+ };+ const response = await new Promise<PublicHttpResponse>((resolve, reject) => {+ const req = (url.protocol === "https:" ? httpsRequest : httpRequest)(+ url,+ {+ agent: false,+ lookup: pinnedLookup,+ signal,+ headers: {+ Accept: "text/html,image/*;q=0.9,*/*;q=0.1",+ "Accept-Encoding": "identity",+ "Cache-Control": "no-cache",+ "User-Agent": "RybbitFavicon/1.0 (+https://rybbit.com)",+ },+ },+ res => {+ res.on("error", reject);+ if (Number(res.headers["content-length"]) > maxBytes) {+ res.destroy(new Error("Response too large"));+ return;+ }+ if ((res.statusCode ?? 0) >= 300 && (res.statusCode ?? 0) < 400) {+ res.destroy();+ resolve({ body: Buffer.alloc(0), headers: res.headers, status: res.statusCode!, url });+ return;+ }+ let bytes = 0;+ const chunks: Buffer[] = [];+ res.on("data", (chunk: Buffer) => {+ bytes += chunk.length;+ if (bytes > maxBytes) res.destroy(new Error("Response too large"));+ else chunks.push(chunk);+ });+ res.on("end", () =>+ resolve({ body: Buffer.concat(chunks), headers: res.headers, status: res.statusCode ?? 0, url })+ );+ }+ );+ req.on("error", reject);+ req.end();+ });+ if (response.status >= 300 && response.status < 400 && response.headers.location) {+ url = new URL(response.headers.location, url);+ continue;+ }+ return response;+ }+ throw new Error("Too many redirects");+}diff --git a/server/src/services/favicon/favicon.test.ts b/server/src/services/favicon/favicon.test.tsnew file mode 100644index 000000000..4440d2d9e--- /dev/null+++ b/server/src/services/favicon/favicon.test.ts@@ -0,0 +1,109 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { fetchPublicHttp } from "../../lib/publicHttpFetch.js";+import { FaviconService } from "./favicon.js";++vi.mock("../../lib/publicHttpFetch.js", () => ({ fetchPublicHttp: vi.fn() }));+const fetchMock = vi.mocked(fetchPublicHttp);+const png = Buffer.from("89504e470d0a1a0a", "hex");++beforeEach(() => {+ vi.useFakeTimers();+ fetchMock.mockReset();+});+afterEach(() => vi.useRealTimers());++function website(icon: string, body = png) {+ fetchMock.mockImplementation(async url => ({+ url,+ status: 200,+ headers: { "content-type": url.pathname === "/" ? "text/html" : "image/png" },+ body: url.pathname === "/" ? Buffer.from(`<link rel="icon" href="${icon}">`) : body,+ }));+}++describe("FaviconService", () => {+ it("discovers the declared icon and fetches new HTML and bytes after cache expiry", async () => {+ const service = new FaviconService();+ website("/old.png");+ expect((await service.get("example.com")).icon?.body).toEqual(png);+ expect(fetchMock.mock.calls[1][0].pathname).toBe("/old.png");+ website("/new.png", Buffer.concat([png, Buffer.from("new")]));+ await service.get("example.com");+ expect(fetchMock).toHaveBeenCalledTimes(2);+ vi.advanceTimersByTime(60 * 60 * 1000);+ expect((await service.get("example.com")).icon?.body).toEqual(Buffer.concat([png, Buffer.from("new")]));+ expect(fetchMock.mock.calls[3][0].pathname).toBe("/new.png");+ });++ it("refreshes changed bytes at the same icon URL", async () => {+ const service = new FaviconService();+ website("/favicon.png");+ await service.get("example.com");+ vi.advanceTimersByTime(60 * 60 * 1000);+ website("/favicon.png", Buffer.concat([png, Buffer.from("updated")]));+ expect((await service.get("example.com")).icon?.body.length).toBeGreaterThan(png.length);+ });++ it("shares in-flight requests for the same domain", async () => {+ website("/favicon.png");+ const service = new FaviconService();+ await Promise.all([service.get("example.com"), service.get("example.com")]);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it("queues larger site lists instead of failing icons beyond the concurrency limit", async () => {+ let release!: () => void;+ const gate = new Promise<void>(resolve => {+ release = resolve;+ });+ fetchMock.mockImplementation(async url => {+ if (url.pathname === "/") await gate;+ return {+ url,+ status: 200,+ headers: {},+ body: url.pathname === "/" ? Buffer.from('<link rel="icon" href="/icon.png">') : png,+ };+ });+ const service = new FaviconService();+ const requests = Array.from({ length: 21 }, (_, i) => service.get(`site${i}.example.com`));+ expect(fetchMock).toHaveBeenCalledTimes(20);+ release();+ expect((await Promise.all(requests)).every(result => result.icon !== null)).toBe(true);+ expect(fetchMock).toHaveBeenCalledTimes(42);+ });++ it("falls back to /favicon.ico when HTML contains no usable icon", async () => {+ website("data:image/png;base64,abc");+ await new FaviconService().get("example.com");+ expect(fetchMock.mock.calls[1][0].pathname).toBe("/favicon.ico");+ });++ it("resolves relative icons against the final homepage URL and HTML base", async () => {+ fetchMock+ .mockResolvedValueOnce({+ url: new URL("https://www.example.com/app/"),+ status: 200,+ headers: {},+ body: Buffer.from('<base href="/assets/"><link href="icon.png?a=1&b=2" rel="shortcut icon">'),+ })+ .mockResolvedValueOnce({+ url: new URL("https://www.example.com/assets/icon.png"),+ status: 200,+ headers: {},+ body: png,+ });+ await new FaviconService().get("example.com");+ expect(fetchMock.mock.calls[1][0].href).toBe("https://www.example.com/assets/icon.png?a=1&b=2");+ });++ it("does not serve an HTML error page as an image and retries failures after five minutes", async () => {+ website("/favicon.png", Buffer.from("<html>Access denied</html>"));+ const service = new FaviconService();+ expect((await service.get("example.com")).icon).toBeNull();+ website("/favicon.png");+ expect((await service.get("example.com")).icon).toBeNull();+ vi.advanceTimersByTime(5 * 60 * 1000);+ expect((await service.get("example.com")).icon?.body).toEqual(png);+ });+});diff --git a/server/src/services/favicon/favicon.ts b/server/src/services/favicon/favicon.tsnew file mode 100644index 000000000..942d8111c--- /dev/null+++ b/server/src/services/favicon/favicon.ts@@ -0,0 +1,147 @@+import { fetchPublicHttp } from "../../lib/publicHttpFetch.js";+import { createServiceLogger } from "../../lib/logger/logger.js";++const logger = createServiceLogger("favicon");+const CACHE_MS = 60 * 60 * 1000;+const FAILURE_CACHE_MS = 5 * 60 * 1000;+const MAX_CACHE_ENTRIES = 128;+const MAX_ICON_BYTES = 256 * 1024;++interface Icon {+ body: Buffer;+ contentType: string;+}+interface CacheEntry {+ icon: Icon | null;+ expiresAt: number;+}++export function normalizeFaviconDomain(domain: unknown): string | null {+ if (typeof domain !== "string") return null;+ const normalized = domain.trim().toLowerCase().replace(/\.$/, "");+ if (normalized.length > 253 || !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(normalized))+ return null;+ return normalized.split(".").every(label => label.length <= 63) ? normalized : null;+}++function attributes(tag: string): Record<string, string> {+ const result: Record<string, string> = {};+ for (const match of tag.matchAll(/([^\s=<>/]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g)) {+ result[match[1].toLowerCase()] = (match[2] ?? match[3] ?? match[4]).replace(/&/gi, "&");+ }+ return result;+}++function iconUrls(html: string, pageUrl: URL): URL[] {+ const markup = html.replace(/<!--[\s\S]*?-->|<script\b[^>]*>[\s\S]*?<\/script\s*>/gi, "");+ let base = pageUrl;+ const baseTag = markup.match(/<base\b(?:[^>"']|"[^"]*"|'[^']*')*>/i)?.[0];+ if (baseTag) {+ try {+ base = new URL(attributes(baseTag).href, pageUrl);+ } catch {+ /* Ignore an invalid base. */+ }+ }+ const icons: URL[] = [];+ const touchIcons: URL[] = [];+ for (const match of markup.matchAll(/<link\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi)) {+ const attrs = attributes(match[0]);+ const rel = attrs.rel?.toLowerCase().split(/\s+/) ?? [];+ if (!attrs.href || !rel.some(value => value === "icon" || value === "apple-touch-icon")) continue;+ try {+ const url = new URL(attrs.href, base);+ if (url.protocol === "http:" || url.protocol === "https:") {+ (rel.includes("icon") ? icons : touchIcons).push(url);+ }+ } catch {+ /* Ignore malformed icon URLs. */+ }+ }+ // The last declared standard icon takes precedence; try at most three+ // declared icons before the conventional fallback to bound network work.+ return [...icons.reverse(), ...touchIcons.reverse()].slice(0, 3).concat(new URL("/favicon.ico", pageUrl));+}++function imageContentType(body: Buffer): string | null {+ if (body.subarray(0, 8).equals(Buffer.from("89504e470d0a1a0a", "hex"))) return "image/png";+ if (body.subarray(0, 4).equals(Buffer.from([0, 0, 1, 0]))) return "image/x-icon";+ if (body[0] === 0xff && body[1] === 0xd8 && body[2] === 0xff) return "image/jpeg";+ if (/^GIF8[79]a$/.test(body.subarray(0, 6).toString())) return "image/gif";+ if (body.subarray(0, 4).toString() === "RIFF" && body.subarray(8, 12).toString() === "WEBP") return "image/webp";+ const text = body+ .toString("utf8")+ .replace(/^\uFEFF/, "")+ .trimStart();+ if (/^(?:<\?xml[^>]*>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg\b/i.test(text)) return "image/svg+xml";+ return null;+}++export class FaviconService {+ private cache = new Map<string, CacheEntry>();+ private pending = new Map<string, Promise<CacheEntry>>();+ private active = 0;+ private waiting: Array<() => void> = [];++ async get(domain: string): Promise<CacheEntry> {+ const cached = this.cache.get(domain);+ if (cached && cached.expiresAt > Date.now()) return cached;+ const pending = this.pending.get(domain);+ if (pending) return pending;+ if (this.pending.size >= MAX_CACHE_ENTRIES) return { icon: null, expiresAt: Date.now() };++ const task = this.loadQueued(domain)+ .then(icon => {+ const entry = { icon, expiresAt: Date.now() + (icon ? CACHE_MS : FAILURE_CACHE_MS) };+ this.cache.delete(domain);+ if (this.cache.size >= MAX_CACHE_ENTRIES) this.cache.delete(this.cache.keys().next().value!);+ this.cache.set(domain, entry);+ return entry;+ })+ .finally(() => this.pending.delete(domain));+ this.pending.set(domain, task);+ return task;+ }++ private async loadQueued(domain: string): Promise<Icon | null> {+ if (this.active >= 20) await new Promise<void>(resolve => this.waiting.push(resolve));+ else this.active++;+ try {+ return await this.load(domain);+ } finally {+ const next = this.waiting.shift();+ if (next) next();+ else this.active--;+ }+ }++ private async load(domain: string): Promise<Icon | null> {+ const signal = AbortSignal.timeout(10_000);+ let pageUrl = new URL(`https://${domain}/`);+ let html = "";+ for (const scheme of ["https:", "http:"]) {+ pageUrl = new URL(`${scheme}//${domain}/`);+ try {+ const page = await fetchPublicHttp(pageUrl, { signal, maxBytes: 1024 * 1024 });+ pageUrl = page.url;+ if (page.status === 200) html = page.body.toString("utf8");+ break;+ } catch (err) {+ logger.debug({ domain, err }, "Favicon homepage fetch failed");+ }+ }+ for (const url of iconUrls(html, pageUrl)) {+ try {+ const response = await fetchPublicHttp(url, { signal, maxBytes: MAX_ICON_BYTES });+ if (response.status !== 200) continue;+ const contentType = imageContentType(response.body);+ if (contentType) return { body: response.body, contentType };+ } catch (err) {+ logger.debug({ domain, err }, "Favicon image fetch failed");+ }+ }+ return null;+ }+}++export const faviconService = new FaviconService();