Skip to content

Commit a7ece7e

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

3 files changed

Lines changed: 288 additions & 3 deletions

File tree

backend/open_webui/routers/utils.py

Lines changed: 282 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,276 @@ 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+
url = url.strip()
177+
if '://' not in url:
178+
url = 'https://' + url
179+
parsed = urlparse(url)
180+
hostname = (parsed.hostname or '').lower().rstrip('.')
181+
if not hostname:
182+
return None
183+
try:
184+
hostname = hostname.encode('idna').decode('ascii')
185+
except (UnicodeError, UnicodeDecodeError):
186+
pass
187+
return hostname or None
188+
except Exception:
189+
return None
190+
191+
192+
def _is_safe_url(url: str) -> bool:
193+
"""Return True if url has an http/https scheme and a globally routable target."""
194+
try:
195+
parsed = urlparse(url)
196+
if parsed.scheme not in ('http', 'https'):
197+
return False
198+
hostname = parsed.hostname
199+
if not hostname:
200+
return False
201+
try:
202+
if not ipaddress.ip_address(hostname).is_global: # raw IP
203+
return False
204+
except ValueError:
205+
pass # hostname; _SafeResolver handles it
206+
return True
207+
except Exception:
208+
return False
209+
210+
211+
class _SafeResolver(aiohttp.ThreadedResolver):
212+
async def resolve(self, hostname, port=0, family=socket.AF_UNSPEC):
213+
results = await super().resolve(hostname, port, family)
214+
for r in results:
215+
if not ipaddress.ip_address(r['host']).is_global:
216+
raise OSError(f'non-global IP: {r["host"]}')
217+
return results
218+
219+
220+
async def _fetch_bounded(
221+
session: aiohttp.ClientSession,
222+
url: str,
223+
max_bytes: int,
224+
allowed_types: set[str] | None,
225+
) -> tuple[bytes, str] | None:
226+
"""GET with capped size and per-hop SSRF validation."""
227+
current = url
228+
for _ in range(_MAX_REDIRECTS + 1):
229+
try:
230+
async with session.get(
231+
current, allow_redirects=False, timeout=_FAVICON_TIMEOUT
232+
) as resp:
233+
if resp.status in (301, 302, 303, 307, 308):
234+
location = resp.headers.get('Location', '')
235+
if not location:
236+
return None
237+
next_url = urljoin(current, location)
238+
if not _is_safe_url(next_url):
239+
return None
240+
current = next_url
241+
continue
242+
243+
if resp.status != 200:
244+
return None
245+
246+
ct = resp.headers.get('Content-Type', '').split(';')[0].strip().lower()
247+
if allowed_types is not None and ct not in allowed_types:
248+
return None
249+
250+
data = b''
251+
async for chunk in resp.content.iter_chunked(8192):
252+
data += chunk
253+
if len(data) > max_bytes:
254+
return None
255+
return data, ct
256+
except Exception:
257+
return None
258+
return None
259+
260+
261+
async def _discover_favicon(hostname: str) -> tuple[bytes, str] | None:
262+
# aiohttp bypasses the resolver for raw numeric IPs (is_ip_address() short-circuits
263+
# _resolve_host). This is the sole guard for that path.
264+
try:
265+
if not ipaddress.ip_address(hostname).is_global:
266+
return None
267+
except ValueError:
268+
pass # hostname; _SafeResolver handles it
269+
270+
connector = aiohttp.TCPConnector(resolver=_SafeResolver(), use_dns_cache=False)
271+
headers = {'User-Agent': 'Mozilla/5.0 (compatible; open-webui/favicon-proxy)'}
272+
async with aiohttp.ClientSession(connector=connector, headers=headers) as session:
273+
# try /favicon.ico
274+
result = await _fetch_bounded(
275+
session,
276+
f'https://{hostname}/favicon.ico',
277+
_MAX_ICON_BYTES,
278+
_ALLOWED_ICON_TYPES,
279+
)
280+
if result:
281+
return result
282+
283+
# fall back to HTML <link> discovery
284+
html_result = await _fetch_bounded(
285+
session,
286+
f'https://{hostname}/',
287+
_MAX_HTML_BYTES,
288+
{'text/html'},
289+
)
290+
if not html_result:
291+
return None
292+
293+
html_bytes, _ = html_result
294+
try:
295+
soup = BeautifulSoup(html_bytes, 'html.parser')
296+
except Exception:
297+
return None
298+
299+
candidates: list[tuple[int, int, str]] = []
300+
for tag in soup.find_all('link'):
301+
rel = tag.get('rel') or []
302+
if isinstance(rel, str):
303+
rel = [rel]
304+
rel_lower = [r.lower() for r in rel]
305+
306+
href = tag.get('href') or ''
307+
if not href or href.startswith('data:'):
308+
continue
309+
tag_type = (tag.get('type') or '').lower()
310+
if 'svg' in tag_type:
311+
continue
312+
313+
if 'apple-touch-icon' in rel_lower and 'precomposed' not in rel_lower:
314+
priority, size = 0, 180
315+
elif 'icon' in rel_lower:
316+
priority = 1
317+
size = 0
318+
sizes_str = (tag.get('sizes') or '').strip()
319+
if sizes_str and sizes_str.lower() != 'any':
320+
try:
321+
size = max(
322+
int(p.lower().split('x')[0])
323+
for p in sizes_str.split()
324+
if 'x' in p.lower()
325+
)
326+
except Exception:
327+
size = 0
328+
elif 'shortcut' in rel_lower:
329+
priority, size = 2, 0
330+
elif 'apple-touch-icon' in rel_lower: # precomposed
331+
priority, size = 3, 0
332+
else:
333+
continue
334+
335+
full_href = urljoin(f'https://{hostname}/', href)
336+
candidates.append((priority, -size, full_href))
337+
338+
candidates.sort(key=lambda x: (x[0], x[1]))
339+
340+
for _, _, href in candidates:
341+
if not _is_safe_url(href):
342+
continue
343+
icon_result = await _fetch_bounded(
344+
session, href, _MAX_ICON_BYTES, _ALLOWED_ICON_TYPES
345+
)
346+
if icon_result:
347+
return icon_result
348+
349+
return None
350+
351+
352+
def _cache_get(hostname: str) -> tuple[bytes, str] | None:
353+
entry = _FAVICON_CACHE.get(hostname)
354+
if entry is None:
355+
return None
356+
content, ct, expires_at = entry
357+
if time.monotonic() > expires_at:
358+
del _FAVICON_CACHE[hostname]
359+
return None
360+
_FAVICON_CACHE.move_to_end(hostname)
361+
return content, ct
362+
363+
364+
def _cache_set(hostname: str, content: bytes, ct: str) -> None:
365+
if hostname in _FAVICON_CACHE:
366+
_FAVICON_CACHE.move_to_end(hostname)
367+
_FAVICON_CACHE[hostname] = (content, ct, time.monotonic() + _FAVICON_CACHE_TTL)
368+
while len(_FAVICON_CACHE) > _FAVICON_CACHE_MAX:
369+
_FAVICON_CACHE.popitem(last=False)
370+
371+
372+
_FAVICON_RESPONSE_HEADERS = {
373+
'Cache-Control': 'public, max-age=604800',
374+
'X-Content-Type-Options': 'nosniff',
375+
}
376+
377+
378+
@router.get('/favicon')
379+
async def get_favicon(url: str = '', user=Depends(get_verified_user)):
380+
"""Favicon proxy; always returns a response."""
381+
hostname = _normalize_hostname(url)
382+
383+
if hostname:
384+
cached = _cache_get(hostname)
385+
if cached:
386+
content, ct = cached
387+
return Response(content=content, media_type=ct, headers=_FAVICON_RESPONSE_HEADERS)
388+
389+
icon: tuple[bytes, str] | None = None
390+
if hostname:
391+
try:
392+
icon = await _discover_favicon(hostname)
393+
except Exception:
394+
pass
395+
396+
if icon:
397+
content, ct = icon
398+
_cache_set(hostname, content, ct)
399+
return Response(content=content, media_type=ct, headers=_FAVICON_RESPONSE_HEADERS)
400+
401+
content = _svg_badge(hostname or '')
402+
ct = 'image/svg+xml'
403+
if hostname:
404+
_cache_set(hostname, content, ct)
405+
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)