Skip to content

Commit f44f792

Browse files
committed
feat: server-side favicon proxy
1 parent 0caaccf commit f44f792

3 files changed

Lines changed: 286 additions & 3 deletions

File tree

backend/open_webui/routers/utils.py

Lines changed: 280 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
import black
2+
import hashlib
3+
import ipaddress
24
import logging
35
import markdown
6+
import socket
7+
import time
8+
from collections import OrderedDict
9+
from urllib.parse import urljoin, urlparse
10+
11+
import aiohttp
12+
from bs4 import BeautifulSoup
413

514
from open_webui.models.chats import ChatTitleMessagesForm
615
from open_webui.config import DATA_DIR, ENABLE_ADMIN_EXPORT
@@ -121,3 +130,274 @@ async def download_db(user=Depends(get_admin_user)):
121130
media_type='application/octet-stream',
122131
filename='webui.db',
123132
)
133+
134+
135+
_FAVICON_CACHE: OrderedDict = OrderedDict()
136+
_FAVICON_CACHE_MAX = 1000
137+
_FAVICON_CACHE_TTL = 7 * 24 * 3600
138+
_FAVICON_TIMEOUT = aiohttp.ClientTimeout(total=5)
139+
_MAX_ICON_BYTES = 256 * 1024 # 256 KiB
140+
_MAX_HTML_BYTES = 250 * 1024 # 250 KiB
141+
_MAX_REDIRECTS = 3
142+
_ALLOWED_ICON_TYPES = {
143+
'image/x-icon',
144+
'image/vnd.microsoft.icon',
145+
'image/png',
146+
'image/jpeg',
147+
'image/gif',
148+
'image/webp',
149+
}
150+
_BADGE_PALETTE = [
151+
'#e74c3c', '#e67e22', '#2ecc71', '#3498db',
152+
'#9b59b6', '#1abc9c', '#e91e63', '#f39c12',
153+
]
154+
155+
156+
def _svg_badge(hostname: str) -> bytes:
157+
if hostname:
158+
letter = hostname[0].upper()
159+
idx = hashlib.sha256(hostname.encode()).digest()[0] % len(_BADGE_PALETTE)
160+
color = _BADGE_PALETTE[idx]
161+
else:
162+
letter = '?'
163+
color = '#95a5a6'
164+
svg = (
165+
f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">'
166+
f'<circle cx="16" cy="16" r="16" fill="{color}"/>'
167+
f'<text x="16" y="21" font-size="16" font-family="sans-serif" '
168+
f'fill="white" text-anchor="middle">{letter}</text>'
169+
f'</svg>'
170+
)
171+
return svg.encode()
172+
173+
174+
def _normalize_hostname(url: str) -> str | None:
175+
try:
176+
if '://' not in url:
177+
url = 'https://' + url
178+
parsed = urlparse(url)
179+
hostname = (parsed.hostname or '').lower().rstrip('.')
180+
if not hostname:
181+
return None
182+
try:
183+
hostname = hostname.encode('idna').decode('ascii')
184+
except (UnicodeError, UnicodeDecodeError):
185+
pass
186+
return hostname or None
187+
except Exception:
188+
return None
189+
190+
191+
def _is_safe_url(url: str) -> bool:
192+
"""Return True if url has an http/https scheme and a globally routable target."""
193+
try:
194+
parsed = urlparse(url)
195+
if parsed.scheme not in ('http', 'https'):
196+
return False
197+
hostname = parsed.hostname
198+
if not hostname:
199+
return False
200+
try:
201+
if not ipaddress.ip_address(hostname).is_global: # raw IP
202+
return False
203+
except ValueError:
204+
pass # hostname; _SafeResolver handles it
205+
return True
206+
except Exception:
207+
return False
208+
209+
210+
class _SafeResolver(aiohttp.ThreadedResolver):
211+
async def resolve(self, hostname, port=0, family=socket.AF_UNSPEC):
212+
results = await super().resolve(hostname, port, family)
213+
for r in results:
214+
if not ipaddress.ip_address(r['host']).is_global:
215+
raise OSError(f'non-global IP: {r["host"]}')
216+
return results
217+
218+
219+
async def _fetch_bounded(
220+
session: aiohttp.ClientSession,
221+
url: str,
222+
max_bytes: int,
223+
allowed_types: set[str] | None,
224+
) -> tuple[bytes, str] | None:
225+
"""GET with capped size and per-hop SSRF validation."""
226+
current = url
227+
for _ in range(_MAX_REDIRECTS + 1):
228+
try:
229+
async with session.get(
230+
current, allow_redirects=False, timeout=_FAVICON_TIMEOUT
231+
) as resp:
232+
if resp.status in (301, 302, 303, 307, 308):
233+
location = resp.headers.get('Location', '')
234+
if not location:
235+
return None
236+
next_url = urljoin(current, location)
237+
if not _is_safe_url(next_url):
238+
return None
239+
current = next_url
240+
continue
241+
242+
if resp.status != 200:
243+
return None
244+
245+
ct = resp.headers.get('Content-Type', '').split(';')[0].strip().lower()
246+
if allowed_types is not None and ct not in allowed_types:
247+
return None
248+
249+
data = b''
250+
async for chunk in resp.content.iter_chunked(8192):
251+
data += chunk
252+
if len(data) > max_bytes:
253+
return None
254+
return data, ct
255+
except Exception:
256+
return None
257+
return None
258+
259+
260+
async def _discover_favicon(hostname: str) -> tuple[bytes, str] | None:
261+
# aiohttp bypasses the resolver for raw numeric IPs (is_ip_address() short-circuits
262+
# _resolve_host). This is the sole guard for that path.
263+
try:
264+
if not ipaddress.ip_address(hostname).is_global:
265+
return None
266+
except ValueError:
267+
pass # hostname; _SafeResolver handles it
268+
269+
connector = aiohttp.TCPConnector(resolver=_SafeResolver(), use_dns_cache=False)
270+
async with aiohttp.ClientSession(connector=connector) as session:
271+
# try /favicon.ico
272+
result = await _fetch_bounded(
273+
session,
274+
f'https://{hostname}/favicon.ico',
275+
_MAX_ICON_BYTES,
276+
_ALLOWED_ICON_TYPES,
277+
)
278+
if result:
279+
return result
280+
281+
# fall back to HTML <link> discovery
282+
html_result = await _fetch_bounded(
283+
session,
284+
f'https://{hostname}/',
285+
_MAX_HTML_BYTES,
286+
{'text/html'},
287+
)
288+
if not html_result:
289+
return None
290+
291+
html_bytes, _ = html_result
292+
try:
293+
soup = BeautifulSoup(html_bytes, 'html.parser')
294+
except Exception:
295+
return None
296+
297+
candidates: list[tuple[int, int, str]] = []
298+
for tag in soup.find_all('link'):
299+
rel = tag.get('rel') or []
300+
if isinstance(rel, str):
301+
rel = [rel]
302+
rel_lower = [r.lower() for r in rel]
303+
304+
href = tag.get('href') or ''
305+
if not href or href.startswith('data:'):
306+
continue
307+
tag_type = (tag.get('type') or '').lower()
308+
if 'svg' in tag_type:
309+
continue
310+
311+
if 'apple-touch-icon' in rel_lower and 'precomposed' not in rel_lower:
312+
priority, size = 0, 180
313+
elif 'icon' in rel_lower:
314+
priority = 1
315+
size = 0
316+
sizes_str = (tag.get('sizes') or '').strip()
317+
if sizes_str and sizes_str.lower() != 'any':
318+
try:
319+
size = max(
320+
int(p.lower().split('x')[0])
321+
for p in sizes_str.split()
322+
if 'x' in p.lower()
323+
)
324+
except Exception:
325+
size = 0
326+
elif 'shortcut' in rel_lower:
327+
priority, size = 2, 0
328+
elif 'apple-touch-icon' in rel_lower: # precomposed
329+
priority, size = 3, 0
330+
else:
331+
continue
332+
333+
full_href = urljoin(f'https://{hostname}/', href)
334+
candidates.append((priority, -size, full_href))
335+
336+
candidates.sort(key=lambda x: (x[0], x[1]))
337+
338+
for _, _, href in candidates:
339+
if not _is_safe_url(href):
340+
continue
341+
icon_result = await _fetch_bounded(
342+
session, href, _MAX_ICON_BYTES, _ALLOWED_ICON_TYPES
343+
)
344+
if icon_result:
345+
return icon_result
346+
347+
return None
348+
349+
350+
def _cache_get(hostname: str) -> tuple[bytes, str] | None:
351+
entry = _FAVICON_CACHE.get(hostname)
352+
if entry is None:
353+
return None
354+
content, ct, expires_at = entry
355+
if time.monotonic() > expires_at:
356+
del _FAVICON_CACHE[hostname]
357+
return None
358+
_FAVICON_CACHE.move_to_end(hostname)
359+
return content, ct
360+
361+
362+
def _cache_set(hostname: str, content: bytes, ct: str) -> None:
363+
if hostname in _FAVICON_CACHE:
364+
_FAVICON_CACHE.move_to_end(hostname)
365+
_FAVICON_CACHE[hostname] = (content, ct, time.monotonic() + _FAVICON_CACHE_TTL)
366+
while len(_FAVICON_CACHE) > _FAVICON_CACHE_MAX:
367+
_FAVICON_CACHE.popitem(last=False)
368+
369+
370+
_FAVICON_RESPONSE_HEADERS = {
371+
'Cache-Control': 'public, max-age=604800',
372+
'X-Content-Type-Options': 'nosniff',
373+
}
374+
375+
376+
@router.get('/favicon')
377+
async def get_favicon(url: str = '', user=Depends(get_verified_user)):
378+
"""Favicon proxy; always returns a response."""
379+
hostname = _normalize_hostname(url)
380+
381+
if hostname:
382+
cached = _cache_get(hostname)
383+
if cached:
384+
content, ct = cached
385+
return Response(content=content, media_type=ct, headers=_FAVICON_RESPONSE_HEADERS)
386+
387+
icon: tuple[bytes, str] | None = None
388+
if hostname:
389+
try:
390+
icon = await _discover_favicon(hostname)
391+
except Exception:
392+
pass
393+
394+
if icon:
395+
content, ct = icon
396+
_cache_set(hostname, content, ct)
397+
return Response(content=content, media_type=ct, headers=_FAVICON_RESPONSE_HEADERS)
398+
399+
content = _svg_badge(hostname or '')
400+
ct = 'image/svg+xml'
401+
if hostname:
402+
_cache_set(hostname, content, ct)
403+
return Response(content=content, media_type=ct, headers=_FAVICON_RESPONSE_HEADERS)

src/lib/components/chat/Messages/Citations.svelte

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<script lang="ts">
22
import { getContext } from 'svelte';
3+
import { WEBUI_API_BASE_URL } from '$lib/constants';
34
import { embed, showControls, showEmbeds } from '$lib/stores';
45
56
import CitationModal from './Citations/CitationModal.svelte';
@@ -175,7 +176,7 @@
175176
<div class="flex -space-x-1 items-center">
176177
{#each urlCitations.slice(0, 3) as citation, idx}
177178
<img
178-
src="https://www.google.com/s2/favicons?sz=32&domain={citation.source.name}"
179+
src={`${WEBUI_API_BASE_URL}/utils/favicon?url=${encodeURIComponent(citation.source.name)}`}
179180
alt="favicon"
180181
class="size-4 rounded-full shrink-0 border border-white dark:border-gray-850 bg-white dark:bg-gray-900"
181182
on:error={(e) => {

src/lib/components/chat/Messages/ResponseMessage/WebSearchResults.svelte

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
<script lang="ts">
2+
import { WEBUI_API_BASE_URL } from '$lib/constants';
3+
24
import ChevronDown from '$lib/components/icons/ChevronDown.svelte';
35
import ChevronUp from '$lib/components/icons/ChevronUp.svelte';
46
import Search from '$lib/components/icons/Search.svelte';
@@ -66,7 +68,7 @@
6668
<div class=" flex justify-center items-center gap-3">
6769
<div class="w-fit">
6870
<img
69-
src="https://www.google.com/s2/favicons?sz=32&domain={item.link}"
71+
src={`${WEBUI_API_BASE_URL}/utils/favicon?url=${encodeURIComponent(item.link)}`}
7072
alt="{item?.title ?? item.link} favicon"
7173
class="size-3.5"
7274
/>
@@ -106,7 +108,7 @@
106108
<div class=" flex justify-center items-center gap-3">
107109
<div class="w-fit">
108110
<img
109-
src="https://www.google.com/s2/favicons?sz=32&domain={url}"
111+
src={`${WEBUI_API_BASE_URL}/utils/favicon?url=${encodeURIComponent(url)}`}
110112
alt="{url} favicon"
111113
class="size-3.5"
112114
/>

0 commit comments

Comments
 (0)