An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
fix(privacy): serve source favicons from our own origin (#1029)
Yoshiki Miura8afbebe5c7b1
diff --git a/.env.local.example b/.env.local.exampleindex ac57e7c5..3048f491 100644--- a/.env.local.example+++ b/.env.local.example@@ -193,5 +193,11 @@ ANONYMOUS_USER_ID=anonymous-user# not reachable from the internet.# FETCH_ALLOW_PRIVATE_NETWORK=true+# Where source favicons come from. The server fetches them and serves them from+# your own origin, so visitors never contact the provider themselves. Use+# {domain} and {size} as placeholders, or set it to "off" to show letter+# initials instead of fetching anything.+# FAVICON_PROVIDER_URL=https://www.google.com/s2/favicons?domain={domain}&sz={size}+# Feedback Notifications (Slack)# SLACK_WEBHOOK_URL=[YOUR_SLACK_WEBHOOK_URL]diff --git a/app/api/favicon/__tests__/route.test.ts b/app/api/favicon/__tests__/route.test.tsnew file mode 100644index 00000000..beffb8f6--- /dev/null+++ b/app/api/favicon/__tests__/route.test.ts@@ -0,0 +1,189 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const safeFetch = vi.fn()++vi.mock('@/lib/utils/safe-fetch', () => ({+ safeFetch: (...args: unknown[]) => safeFetch(...args)+}))++const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])++function imageResponse(+ body: Uint8Array<ArrayBuffer> = PNG,+ contentType = 'image/png',+ status = 200+): Response {+ return new Response(body, {+ status,+ headers: { 'content-type': contentType }+ })+}++function request(query: string): Request {+ return new Request(`https://morphic.test/api/favicon?${query}`)+}++async function get(query: string): Promise<Response> {+ const { GET } = await import('../route')+ return GET(request(query))+}++let counter = 0++// Each case needs a domain the module-level cache has not seen.+function freshDomain(): string {+ counter += 1+ return `case-${counter}.example.com`+}++describe('GET /api/favicon', () => {+ beforeEach(() => {+ vi.resetModules()+ safeFetch.mockReset()+ delete process.env.FAVICON_PROVIDER_URL+ })++ afterEach(() => {+ delete process.env.FAVICON_PROVIDER_URL+ })++ it('serves the icon from our own origin, cached and non-sniffable', async () => {+ safeFetch.mockResolvedValue(imageResponse())++ const response = await get(`domain=${freshDomain()}&sz=32`)++ expect(response.status).toBe(200)+ expect(response.headers.get('content-type')).toBe('image/png')+ expect(response.headers.get('cache-control')).toContain('max-age=86400')+ expect(response.headers.get('x-content-type-options')).toBe('nosniff')+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(PNG)+ })++ it('asks the provider for the requested domain and size', async () => {+ safeFetch.mockResolvedValue(imageResponse())+ const domain = freshDomain()++ await get(`domain=${domain}&sz=128`)++ expect(safeFetch).toHaveBeenCalledWith(+ `https://www.google.com/s2/favicons?domain=${domain}&sz=128`,+ expect.anything()+ )+ })++ it('falls back to the default size for one it does not serve', async () => {+ safeFetch.mockResolvedValue(imageResponse())+ const domain = freshDomain()++ await get(`domain=${domain}&sz=4096`)++ expect(safeFetch).toHaveBeenCalledWith(+ expect.stringContaining('&sz=16'),+ expect.anything()+ )+ })++ it('fetches a domain once and answers the rest from cache', async () => {+ safeFetch.mockResolvedValue(imageResponse())+ const domain = freshDomain()++ const [first, second] = await Promise.all([+ get(`domain=${domain}&sz=16`),+ get(`domain=${domain}&sz=16`)+ ])+ const third = await get(`domain=${domain}&sz=16`)++ expect(first.status).toBe(200)+ expect(second.status).toBe(200)+ expect(third.status).toBe(200)+ expect(safeFetch).toHaveBeenCalledTimes(1)+ })++ it('sheds a burst instead of opening unbounded upstream requests', async () => {+ let release: (() => void) | undefined+ const held = new Promise<void>(resolve => {+ release = resolve+ })+ safeFetch.mockImplementation(async () => {+ await held+ return imageResponse()+ })++ const inFlightRequests = Array.from({ length: 8 }, () =>+ get(`domain=${freshDomain()}&sz=16`)+ )+ const shed = await get(`domain=${freshDomain()}&sz=16`)++ expect(shed.status).toBe(503)+ expect(shed.headers.get('cache-control')).toBe('no-store')+ expect(safeFetch).toHaveBeenCalledTimes(8)++ release?.()+ for (const response of await Promise.all(inFlightRequests)) {+ expect(response.status).toBe(200)+ }++ // The slot frees up once those finish.+ expect((await get(`domain=${freshDomain()}&sz=16`)).status).toBe(200)+ })++ it('refuses a domain that is not a public hostname', async () => {+ const response = await get('domain=127.0.0.1&sz=16')++ expect(response.status).toBe(404)+ expect(safeFetch).not.toHaveBeenCalled()+ })++ it('refuses SVG, which would run as our own origin', async () => {+ safeFetch.mockResolvedValue(+ imageResponse(+ new TextEncoder().encode('<svg onload="alert(1)"></svg>'),+ 'image/svg+xml'+ )+ )++ const response = await get(`domain=${freshDomain()}&sz=16`)++ expect(response.status).toBe(404)+ })++ it('refuses a body past the size cap', async () => {+ safeFetch.mockResolvedValue(imageResponse(new Uint8Array(200 * 1024)))++ const response = await get(`domain=${freshDomain()}&sz=16`)++ expect(response.status).toBe(404)+ })++ it('answers 404 when the provider fails or refuses', async () => {+ safeFetch.mockResolvedValueOnce(imageResponse(PNG, 'image/png', 500))+ expect((await get(`domain=${freshDomain()}&sz=16`)).status).toBe(404)++ safeFetch.mockRejectedValueOnce(new Error('blocked'))+ expect((await get(`domain=${freshDomain()}&sz=16`)).status).toBe(404)+ })++ it('uses a configured provider template', async () => {+ process.env.FAVICON_PROVIDER_URL =+ 'https://icons.example.net/{size}/{domain}'+ safeFetch.mockResolvedValue(imageResponse())+ const domain = freshDomain()++ await get(`domain=${domain}&sz=32`)++ expect(safeFetch).toHaveBeenCalledWith(+ `https://icons.example.net/32/${domain}`,+ expect.anything()+ )+ })++ it('contacts nobody when the provider is turned off', async () => {+ process.env.FAVICON_PROVIDER_URL = 'off'++ const response = await get(`domain=${freshDomain()}&sz=16`)++ expect(response.status).toBe(404)+ expect(safeFetch).not.toHaveBeenCalled()+ })+})diff --git a/app/api/favicon/route.ts b/app/api/favicon/route.tsnew file mode 100644index 00000000..d63e3998--- /dev/null+++ b/app/api/favicon/route.ts@@ -0,0 +1,209 @@+import {+ DEFAULT_FAVICON_SIZE,+ isFaviconSize,+ normalizeFaviconDomain+} from '@/lib/utils/favicon'+import { safeFetch } from '@/lib/utils/safe-fetch'++export const runtime = 'nodejs'++const DEFAULT_PROVIDER_URL =+ 'https://www.google.com/s2/favicons?domain={domain}&sz={size}'++const MAX_BYTES = 100 * 1024+const UPSTREAM_TIMEOUT_MS = 5000+const HIT_TTL_MS = 24 * 60 * 60 * 1000+const MISS_TTL_MS = 10 * 60 * 1000+const MAX_CACHE_ENTRIES = 512+// The cache only bounds finished entries, so a burst of never-seen domains+// would otherwise open as many upstream requests as it likes.+const MAX_CONCURRENT_LOADS = 8++// SVG is left out on purpose: it is served from our own origin here, where an+// icon carrying script would run as us.+const ALLOWED_CONTENT_TYPES = new Set([+ 'image/png',+ 'image/jpeg',+ 'image/jpg',+ 'image/gif',+ 'image/webp',+ 'image/avif',+ 'image/bmp',+ 'image/x-icon',+ 'image/vnd.microsoft.icon'+])++type CacheEntry = {+ expiresAt: number+ body: ArrayBuffer | null+ contentType: string+}++const cache = new Map<string, CacheEntry>()+const inFlight = new Map<string, Promise<CacheEntry>>()++function providerTemplate(): string | null {+ const configured = process.env.FAVICON_PROVIDER_URL?.trim()+ if (configured === undefined || configured === '') return DEFAULT_PROVIDER_URL+ if (configured.toLowerCase() === 'off') return null+ return configured+}++function providerUrl(template: string, domain: string, size: number): string {+ return template+ .replaceAll('{domain}', encodeURIComponent(domain))+ .replaceAll('{size}', String(size))+}++function readCache(key: string): CacheEntry | null {+ const entry = cache.get(key)+ if (!entry) return null+ if (entry.expiresAt <= Date.now()) {+ cache.delete(key)+ return null+ }+ // Refresh insertion order so the eviction below drops the coldest key.+ cache.delete(key)+ cache.set(key, entry)+ return entry+}++function writeCache(key: string, entry: CacheEntry): void {+ cache.set(key, entry)+ while (cache.size > MAX_CACHE_ENTRIES) {+ const oldest = cache.keys().next()+ if (oldest.done) break+ cache.delete(oldest.value)+ }+}++async function readCapped(response: Response): Promise<ArrayBuffer | null> {+ const declared = Number(response.headers.get('content-length'))+ if (Number.isFinite(declared) && declared > MAX_BYTES) {+ await response.body?.cancel().catch(() => {})+ return null+ }++ const reader = response.body?.getReader()+ if (!reader) return null++ const chunks: Uint8Array[] = []+ let total = 0+ while (true) {+ const { done, value } = await reader.read()+ if (done) break+ total += value.byteLength+ if (total > MAX_BYTES) {+ await reader.cancel().catch(() => {})+ return null+ }+ chunks.push(value)+ }++ const merged = new Uint8Array(total)+ let offset = 0+ for (const chunk of chunks) {+ merged.set(chunk, offset)+ offset += chunk.byteLength+ }+ return merged.buffer+}++async function loadFavicon(+ template: string,+ domain: string,+ size: number+): Promise<CacheEntry> {+ const miss: CacheEntry = {+ expiresAt: Date.now() + MISS_TTL_MS,+ body: null,+ contentType: ''+ }++ let response: Response+ try {+ response = await safeFetch(providerUrl(template, domain, size), {+ headers: { accept: 'image/*' },+ signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)+ })+ } catch {+ return miss+ }++ if (!response.ok) {+ await response.body?.cancel().catch(() => {})+ return miss+ }++ const contentType = (response.headers.get('content-type') ?? '')+ .split(';')[0]+ .trim()+ .toLowerCase()+ if (!ALLOWED_CONTENT_TYPES.has(contentType)) {+ await response.body?.cancel().catch(() => {})+ return miss+ }++ const body = await readCapped(response).catch(() => null)+ if (!body || body.byteLength === 0) return miss++ return { expiresAt: Date.now() + HIT_TTL_MS, body, contentType }+}++function notFound(): Response {+ return new Response(null, {+ status: 404,+ headers: { 'cache-control': 'public, max-age=600' }+ })+}++// Kept out of any cache: the icon is fine, this instance is just busy.+function unavailable(): Response {+ return new Response(null, {+ status: 503,+ headers: { 'cache-control': 'no-store' }+ })+}++export async function GET(req: Request): Promise<Response> {+ const params = new URL(req.url).searchParams++ const domain = normalizeFaviconDomain(params.get('domain') ?? '')+ if (!domain) return notFound()++ const requested = Number(params.get('sz'))+ const size = isFaviconSize(requested) ? requested : DEFAULT_FAVICON_SIZE++ const template = providerTemplate()+ if (!template) return notFound()++ const key = `${size}:${domain}`+ let entry = readCache(key)++ if (!entry) {+ let pending = inFlight.get(key)+ if (!pending) {+ if (inFlight.size >= MAX_CONCURRENT_LOADS) return unavailable()+ pending = loadFavicon(template, domain, size).finally(() => {+ inFlight.delete(key)+ })+ inFlight.set(key, pending)+ }+ entry = await pending+ writeCache(key, entry)+ }++ if (!entry.body) return notFound()++ return new Response(entry.body, {+ status: 200,+ headers: {+ 'content-type': entry.contentType,+ 'content-length': String(entry.body.byteLength),+ 'cache-control': 'public, max-age=86400, stale-while-revalidate=604800',+ 'x-content-type-options': 'nosniff',+ 'content-security-policy': "default-src 'none'; sandbox",+ 'cross-origin-resource-policy': 'same-origin'+ }+ })+}diff --git a/components/chat-panel.tsx b/components/chat-panel.tsxindex efc8b7df..54111e4a 100644--- a/components/chat-panel.tsx+++ b/components/chat-panel.tsx@@ -41,6 +41,7 @@ import {setCookie,subscribeToCookieChange} from '@/lib/utils/cookies'+import { faviconUrl } from '@/lib/utils/favicon'import { stripMarkdownText } from '@/lib/utils/markdown'import { useArtifact } from './artifact/artifact-context'@@ -718,19 +719,22 @@ export function ChatPanel({try {host = new URL(url).host.replace(/^www\./, '')} catch {}+ const favicon = faviconUrl(host, 32)return (<spankey={i}className="inline-flex items-center gap-1.5 rounded-full border border-input bg-background py-1 pl-2 pr-1 text-xs text-muted-foreground">- {/* eslint-disable-next-line @next/next/no-img-element */}- <img- src={`https://www.google.com/s2/favicons?domain=${host}&sz=32`}- alt=""- width={14}- height={14}- className="size-3.5 shrink-0 rounded-sm"- />+ {favicon && (+ /* eslint-disable-next-line @next/next/no-img-element */+ <img+ src={favicon}+ alt=""+ width={14}+ height={14}+ className="size-3.5 shrink-0 rounded-sm"+ />+ )}<span className="max-w-[180px] truncate">{host}</span><buttontype="button"diff --git a/components/citation-link.tsx b/components/citation-link.tsxindex 8a419ada..04678e4b 100644--- a/components/citation-link.tsx+++ b/components/citation-link.tsx@@ -6,6 +6,7 @@ import Link from 'next/link'import type { SearchResultItem } from '@/lib/types'import { cn } from '@/lib/utils'import { isCitationLabel } from '@/lib/utils/citation'+import { faviconUrl } from '@/lib/utils/favicon'import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'import {@@ -95,9 +96,7 @@ export const CitationLink = memo(function CitationLink({<div className="flex items-center gap-2"><Avatar className="h-4 w-4 shrink-0"><AvatarImage- src={`https://www.google.com/s2/favicons?domain=${getHostname(- citationData.url- )}`}+ src={faviconUrl(citationData.url)}alt={getHostname(citationData.url)}/><AvatarFallback className="text-xs">diff --git a/components/image-credit-overlay.tsx b/components/image-credit-overlay.tsxindex 72f45658..7896d15a 100644--- a/components/image-credit-overlay.tsx+++ b/components/image-credit-overlay.tsx@@ -2,6 +2,7 @@'use client'import { displayUrlName } from '@/lib/utils/domain'+import { faviconUrl } from '@/lib/utils/favicon'/*** Normalize a user- or model-supplied URL to a safe http(s) URL, or return@@ -21,15 +22,6 @@ const sanitizeHttpUrl = (raw: string | undefined): string | null => {}}-export const getFaviconUrl = (imageUrl: string): string => {- try {- const hostname = new URL(imageUrl).hostname- return `https://www.google.com/s2/favicons?domain=${hostname}&sz=128`- } catch {- return ''- }-}-type ImageCreditOverlayProps = {/** Fallback link URL (e.g. the image URL itself). Used when sourceUrl is not set. */url: string@@ -46,16 +38,13 @@ export function ImageCreditOverlay({description}: ImageCreditOverlayProps) {const safeLink = sanitizeHttpUrl(sourceUrl) ?? sanitizeHttpUrl(url)+ const favicon = safeLink ? faviconUrl(safeLink, 128) : ''const label = title || descriptionconst content = (<>- {safeLink && (- <img- src={getFaviconUrl(safeLink)}- alt=""- className="size-7 rounded-lg shrink-0"- />+ {favicon && (+ <img src={favicon} alt="" className="size-7 rounded-lg shrink-0" />)}<div className="min-w-0 flex-1">{safeLink && (diff --git a/components/pasted-parts.tsx b/components/pasted-parts.tsxindex 2d874ff5..2a2f0a15 100644--- a/components/pasted-parts.tsx+++ b/components/pasted-parts.tsx@@ -8,6 +8,8 @@ import {IconFileText as FileText} from '@tabler/icons-react'+import { faviconUrl } from '@/lib/utils/favicon'+// Collapsed card for a pasted text blob (a `data-pastedContent` part, or a// legacy `<user-content>` block in old messages).export function PastedContentCard({@@ -48,6 +50,7 @@ export function UrlChip({ url }: { url: string }) {try {host = new URL(url).host.replace(/^www\./, '')} catch {}+ const favicon = faviconUrl(host, 32)return (<ahref={url}@@ -55,14 +58,16 @@ export function UrlChip({ url }: { url: string }) {rel="noopener noreferrer"className="inline-flex w-fit items-center gap-1.5 rounded-full border border-input bg-background py-1 pl-2 pr-2.5 text-xs text-muted-foreground hover:text-foreground">- {/* eslint-disable-next-line @next/next/no-img-element */}- <img- src={`https://www.google.com/s2/favicons?domain=${host}&sz=32`}- alt=""- width={14}- height={14}- className="size-3.5 shrink-0 rounded-sm"- />+ {favicon && (+ /* eslint-disable-next-line @next/next/no-img-element */+ <img+ src={favicon}+ alt=""+ width={14}+ height={14}+ className="size-3.5 shrink-0 rounded-sm"+ />+ )}<span className="max-w-[220px] truncate">{host}</span></a>)diff --git a/components/search-results.tsx b/components/search-results.tsxindex 0b10564e..189fb5f1 100644--- a/components/search-results.tsx+++ b/components/search-results.tsx@@ -5,6 +5,7 @@ import Link from 'next/link'import { SearchResultItem } from '@/lib/types'import { displayUrlName } from '@/lib/utils/domain'+import { faviconUrl } from '@/lib/utils/favicon'import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'import { Button } from '@/components/ui/button'@@ -46,9 +47,7 @@ export function SearchResults({<CardContent className="p-2 flex items-start space-x-2"><Avatar className="h-4 w-4 mt-1 shrink-0"><AvatarImage- src={`https://www.google.com/s2/favicons?domain=${- new URL(result.url).hostname- }`}+ src={faviconUrl(result.url)}alt={new URL(result.url).hostname}/><AvatarFallback className="text-xs">@@ -90,9 +89,7 @@ export function SearchResults({<div className="flex max-w-[42%] shrink-0 items-center space-x-1 min-w-0 md:mt-2 md:max-w-full md:shrink"><Avatar className="h-4 w-4 shrink-0"><AvatarImage- src={`https://www.google.com/s2/favicons?domain=${- new URL(result.url).hostname- }`}+ src={faviconUrl(result.url)}alt={new URL(result.url).hostname}/><AvatarFallback>diff --git a/components/source-favicons.tsx b/components/source-favicons.tsxindex 5cca19bb..a9b4f074 100644--- a/components/source-favicons.tsx+++ b/components/source-favicons.tsx@@ -2,6 +2,7 @@ import Image from 'next/image'import type { SearchResultItem } from '@/lib/types'import { cn } from '@/lib/utils'+import { faviconUrl } from '@/lib/utils/favicon'interface SourceFaviconsProps {results: SearchResultItem[]@@ -17,8 +18,8 @@ export function SourceFavicons({maxDisplay = 3,className}: SourceFaviconsProps) {- // Extract unique domains from results- const uniqueDomains = Array.from(+ // One favicon per unique result domain+ const favicons = Array.from(new Set(results.map(result => {try {@@ -30,25 +31,27 @@ export function SourceFavicons({)).filter((domain): domain is string => domain !== null)+ .map(domain => ({ domain, src: faviconUrl(domain, 16) }))+ .filter(entry => entry.src !== '').slice(0, maxDisplay)- if (uniqueDomains.length === 0) {+ if (favicons.length === 0) {return null}return (<div className={cn('flex items-center', className)}>- {uniqueDomains.map((domain, index) => (+ {favicons.map(({ domain, src }, index) => (<divkey={domain}className="relative rounded-full border border-background overflow-hidden"style={{marginLeft: index > 0 ? '-6px' : '0',- zIndex: uniqueDomains.length - index+ zIndex: favicons.length - index}}><Image- src={`https://www.google.com/s2/favicons?domain=${domain}&sz=16`}+ src={src}alt={domain}width={16}height={16}diff --git a/components/video-result-grid.tsx b/components/video-result-grid.tsxindex d2f6288e..a7dfd2b8 100644--- a/components/video-result-grid.tsx+++ b/components/video-result-grid.tsx@@ -5,6 +5,7 @@ import Image from 'next/image'import { IconCirclePlus as PlusCircle } from '@tabler/icons-react'import { SerperSearchResultItem } from '@/lib/types'+import { faviconUrl } from '@/lib/utils/favicon'import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'import { Card, CardContent } from '@/components/ui/card'@@ -78,9 +79,7 @@ export function VideoResultGrid({<div className="flex items-center space-x-2"><Avatar className="h-4 w-4"><AvatarImage- src={`https://www.google.com/s2/favicons?domain=${- new URL(video.link).hostname- }`}+ src={faviconUrl(video.link)}alt={video.channel || video.source}/><AvatarFallback>diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex d33ec53d..f26c6ac7 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -280,6 +280,22 @@ FETCH_ALLOW_PRIVATE_NETWORK=trueLeave this off on any instance others can reach. With it on, whoever can send a prompt can read whatever the host can reach.+### Source Favicons++Favicons for cited sources are fetched by the server and served from your own origin at `/api/favicon`, so a visitor's browser never tells the icon provider which sources a result cites. Responses are cached in memory and at the edge.++The provider defaults to Google's favicon service. To point it somewhere else, use `{domain}` and `{size}` as placeholders:++```bash+FAVICON_PROVIDER_URL=https://icons.example.com/{domain}?size={size}+```++To fetch no favicons at all, which falls back to the letter or hostname already shown when an icon fails to load:++```bash+FAVICON_PROVIDER_URL=off+```+### File UploadEnable file upload with Cloudflare R2 or S3-compatible storage:diff --git a/lib/utils/__tests__/favicon.test.ts b/lib/utils/__tests__/favicon.test.tsnew file mode 100644index 00000000..2d9c8b85--- /dev/null+++ b/lib/utils/__tests__/favicon.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest'++import { faviconUrl, normalizeFaviconDomain } from '../favicon'++describe('normalizeFaviconDomain', () => {+ it('accepts a full URL and a bare host alike', () => {+ expect(normalizeFaviconDomain('https://www.example.com/a?b=c')).toBe(+ 'www.example.com'+ )+ expect(normalizeFaviconDomain('example.com')).toBe('example.com')+ expect(normalizeFaviconDomain(' Example.COM ')).toBe('example.com')+ })++ it('refuses IP literals so a render cannot probe an address', () => {+ expect(normalizeFaviconDomain('127.0.0.1')).toBeNull()+ expect(normalizeFaviconDomain('http://169.254.169.254/latest')).toBeNull()+ expect(normalizeFaviconDomain('[::1]')).toBeNull()+ expect(normalizeFaviconDomain('http://[::1]')).toBeNull()+ })++ it('refuses names that are not public hostnames', () => {+ expect(normalizeFaviconDomain('')).toBeNull()+ expect(normalizeFaviconDomain('localhost')).toBeNull()+ expect(normalizeFaviconDomain('javascript:alert(1)')).toBeNull()+ expect(normalizeFaviconDomain('file:///etc/passwd')).toBeNull()+ expect(normalizeFaviconDomain('exa mple.com')).toBeNull()+ expect(normalizeFaviconDomain(`${'a'.repeat(300)}.com`)).toBeNull()+ })++ it('drops credentials and ports that the lookup does not use', () => {+ expect(normalizeFaviconDomain('https://user:[email protected]:8443')).toBe(+ 'example.com'+ )+ })+})++describe('faviconUrl', () => {+ it('points at our own origin', () => {+ expect(faviconUrl('https://example.com/page')).toBe(+ '/api/favicon?domain=example.com&sz=16'+ )+ expect(faviconUrl('example.com', 128)).toBe(+ '/api/favicon?domain=example.com&sz=128'+ )+ })++ it('returns an empty string the caller can skip rendering on', () => {+ expect(faviconUrl('not a host')).toBe('')+ })++ it('escapes the domain it puts in the query', () => {+ expect(faviconUrl('https://example.com/?x=1#y')).toBe(+ '/api/favicon?domain=example.com&sz=16'+ )+ })+})diff --git a/lib/utils/favicon.ts b/lib/utils/favicon.tsnew file mode 100644index 00000000..b2224e6e--- /dev/null+++ b/lib/utils/favicon.ts@@ -0,0 +1,54 @@+export const FAVICON_SIZES = [16, 32, 128] as const++export type FaviconSize = (typeof FAVICON_SIZES)[number]++// Matches what the upstream provider serves when no size is requested.+export const DEFAULT_FAVICON_SIZE: FaviconSize = 16++const MAX_HOSTNAME_LENGTH = 253+const HOSTNAME_PATTERN = /^(?!-)[a-z0-9-]{1,63}(?:\.(?!-)[a-z0-9-]{1,63})+$/++/**+ * Reduces a URL or a bare host to the hostname the favicon lookup uses, or+ * null when the input is not a public-looking name. IP literals are refused+ * here so the route never turns a rendered result into an address probe.+ */+export function normalizeFaviconDomain(source: string): string | null {+ const trimmed = source.trim()+ if (!trimmed || trimmed.length > 2048) return null++ let hostname: string+ try {+ const parsed = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)+ ? new URL(trimmed)+ : new URL(`https://${trimmed}`)+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null+ hostname = parsed.hostname.toLowerCase()+ } catch {+ return null+ }++ if (hostname.startsWith('[')) return null+ if (hostname.length > MAX_HOSTNAME_LENGTH) return null+ if (/^[\d.]+$/.test(hostname)) return null+ if (!HOSTNAME_PATTERN.test(hostname)) return null++ return hostname+}++export function isFaviconSize(value: number): value is FaviconSize {+ return (FAVICON_SIZES as readonly number[]).includes(value)+}++/**+ * Same-origin favicon URL. The icon is fetched by the server, so the visitor's+ * browser never tells a third party which sources a result cites.+ */+export function faviconUrl(+ source: string,+ size: FaviconSize = DEFAULT_FAVICON_SIZE+): string {+ const domain = normalizeFaviconDomain(source)+ if (!domain) return ''+ return `/api/favicon?domain=${encodeURIComponent(domain)}&sz=${size}`+}diff --git a/next.config.mjs b/next.config.mjsindex e9e12f04..88d8229e 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -37,12 +37,6 @@ const nextConfig = {hostname: 'imgs.search.brave.com',port: '',pathname: '/**' // Brave search cached images- },- {- protocol: 'https',- hostname: 'www.google.com',- port: '',- pathname: '/s2/favicons/**' // Google Favicon API}]}diff --git a/proxy.ts b/proxy.tsindex 4f16c508..8048b5fe 100644--- a/proxy.ts+++ b/proxy.ts@@ -43,8 +43,9 @@ export const config = {* - _next/static (static files)* - _next/image (image optimization files)* - favicon.ico (favicon file)+ * - api/favicon (source favicon images, which need no session)* Feel free to modify this pattern to include more paths.*/- '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'+ '/((?!_next/static|_next/image|favicon.ico|api/favicon|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)']}