Skip to content

The agent that grows with you

fix(desktop,gateway): proxy client-unreachable remote images through the gateway

Brooklyn Nicholson82bbc694b5b8
diff --git a/apps/desktop/src/hooks/use-media-image.test.tsx b/apps/desktop/src/hooks/use-media-image.test.tsx
new file mode 100644
index 00000000000..7cf0bbce627
--- /dev/null
+++ b/apps/desktop/src/hooks/use-media-image.test.tsx
@@ -0,0 +1,89 @@
+import { act, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { useMediaImage } from './use-media-image'
+
+// useMediaImage's gateway-proxy retry (#74564): a direct inline https image
+// that fails to load (client blocked from the CDN) is fetched once through
+// the gateway's authenticated /api/media/proxy and swapped in as a data URL.
+
+const CDN_URL = 'https://v3.fal.media/media/abc123'
+
+describe('useMediaImage gateway proxy fallback (#74564)', () => {
+ const api = vi.fn(async ({ path }: { path: string }) => {
+ if (path.startsWith('/api/media/proxy?')) {
+ return { dataUrl: 'data:image/png;base64,cHJveGllZA==' }
+ }
+
+ throw new Error(`unexpected path ${path}`)
+ })
+
+ beforeEach(() => {
+ api.mockClear()
+ vi.stubGlobal('window', { hermesDesktop: { api } })
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
+ it('retries a failed inline https load once through the gateway proxy', async () => {
+ const { result } = renderHook(() => useMediaImage(CDN_URL, 4 / 3))
+
+ // Inline https src paints directly; no resolution effect runs.
+ expect(result.current.src).toBe(CDN_URL)
+ expect(api).not.toHaveBeenCalled()
+
+ act(() => {
+ result.current.onError()
+ })
+
+ expect(result.current.failed).toBe(true)
+ expect(api).toHaveBeenCalledTimes(1)
+ expect(api).toHaveBeenCalledWith({ path: `/api/media/proxy?url=${encodeURIComponent(CDN_URL)}` })
+
+ await vi.waitFor(() => expect(result.current.failed).toBe(false))
+ expect(result.current.src).toBe('data:image/png;base64,cHJveGllZA==')
+ })
+
+ it('does not retry a failed proxied data URL or a non-https source', async () => {
+ const { result } = renderHook(() => useMediaImage(CDN_URL, 4 / 3))
+
+ act(() => {
+ result.current.onError()
+ })
+
+ await vi.waitFor(() => expect(result.current.src).toBe('data:image/png;base64,cHJveGllZA=='))
+
+ // The proxied data URL failing must not trigger another proxy request.
+ act(() => {
+ result.current.onError()
+ })
+
+ expect(api).toHaveBeenCalledTimes(1)
+
+ // A data: source never reaches the proxy at all.
+ const dataUrl = renderHook(() => useMediaImage('data:image/png;base64,aGk=', 4 / 3))
+
+ act(() => {
+ dataUrl.result.current.onError()
+ })
+
+ expect(api).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps the failed state when the gateway proxy cannot fetch the image', async () => {
+ api.mockRejectedValueOnce(new Error('403 Image host not allowed'))
+
+ const { result } = renderHook(() => useMediaImage(CDN_URL, 4 / 3))
+
+ act(() => {
+ result.current.onError()
+ })
+
+ // One attempt, then it stays failed — no retry loop.
+ await vi.waitFor(() => expect(api).toHaveBeenCalledTimes(1))
+ expect(result.current.failed).toBe(true)
+ expect(result.current.src).toBe(CDN_URL)
+ })
+})
diff --git a/apps/desktop/src/hooks/use-media-image.ts b/apps/desktop/src/hooks/use-media-image.ts
index 818d7efc6ba..c6bec1f05a0 100644
--- a/apps/desktop/src/hooks/use-media-image.ts
+++ b/apps/desktop/src/hooks/use-media-image.ts
@@ -1,8 +1,9 @@
import { useStore } from '@nanostores/react'
-import { type CSSProperties, useEffect, useMemo, useState } from 'react'
+import { type CSSProperties, useEffect, useMemo, useRef, useState } from 'react'
import { useComposerScope } from '@/app/chat/composer/scope'
import {
+ gatewayImageProxyDataUrl,
getMediaImageDimensions,
isInlineMediaSrc,
isKnownBrokenMediaImage,
@@ -79,6 +80,33 @@ export function useMediaImage(
setState(inheritsPendingFrame ? { ...next, frameStyle: state.frameStyle } : next)
}
+ // One proxy retry per inline https source (#74564): when the direct load
+ // fails (client blocked from the image CDN), ask the gateway — which
+ // generated the image and can reach the CDN — to fetch the bytes through
+ // its authenticated /api/media/proxy. Latched so a failing proxy data URL
+ // (itself a data: src, which cannot fail with onError again) and a remount
+ // never loop: the failed direct load is remembered via the broken-key
+ // mechanism instead.
+ const proxyRetriedRef = useRef(false)
+
+ const retryThroughGatewayProxy = () => {
+ if (proxyRetriedRef.current || !path || !isInlineMediaSrc(path) || !/^https?:/i.test(path)) {
+ return
+ }
+
+ proxyRetriedRef.current = true
+
+ void gatewayImageProxyDataUrl(path, owner).then(dataUrl => {
+ if (dataUrl) {
+ setState(current =>
+ current.key === key && current.failed && !current.loaded
+ ? { ...current, src: dataUrl, failed: false }
+ : current
+ )
+ }
+ })
+ }
+
useEffect(() => {
let cancelled = false
@@ -107,15 +135,20 @@ export function useMediaImage(
}
}, [key, path, owner])
+ const onLoad = (image: HTMLImageElement) => {
+ rememberMediaImageDimensions(key, image.naturalWidth, image.naturalHeight)
+ setState(current => ({ ...current, loaded: true }))
+ }
+
+ const onError = () => {
+ rememberMediaImageFailure(key)
+ setState(current => ({ ...current, failed: true, loaded: false }))
+ retryThroughGatewayProxy()
+ }
+
return {
...state,
- onLoad: (image: HTMLImageElement) => {
- rememberMediaImageDimensions(key, image.naturalWidth, image.naturalHeight)
- setState(current => ({ ...current, loaded: true }))
- },
- onError: () => {
- rememberMediaImageFailure(key)
- setState(current => ({ ...current, failed: true, loaded: false }))
- }
+ onLoad,
+ onError
}
}
diff --git a/apps/desktop/src/lib/media.remote.test.ts b/apps/desktop/src/lib/media.remote.test.ts
index e9d3f02c9e7..f4d158f6242 100644
--- a/apps/desktop/src/lib/media.remote.test.ts
+++ b/apps/desktop/src/lib/media.remote.test.ts
@@ -5,6 +5,7 @@ import { $connection } from '@/store/session'
import {
downloadGatewayMediaFile,
filePathFromMediaPath,
+ gatewayImageProxyDataUrl,
gatewayMediaDataUrl,
isInlineMediaSrc,
mediaExternalUrl,
@@ -231,6 +232,56 @@ describe('gatewayMediaDataUrl', () => {
})
})
+describe('gatewayImageProxyDataUrl (#74564)', () => {
+ const api = vi.fn(async ({ path }: { path: string }) => {
+ if (path.startsWith('/api/media/proxy?')) {
+ return { dataUrl: 'data:image/png;base64,cGRveGllZA==' }
+ }
+
+ throw new Error(`unexpected path ${path}`)
+ })
+
+ beforeEach(() => {
+ api.mockClear()
+ vi.stubGlobal('window', { hermesDesktop: { api } })
+ $connection.set({ mode: 'remote' } as never)
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ $connection.set(null)
+ })
+
+ it('fetches a client-unreachable CDN image through the gateway proxy', async () => {
+ const url = 'https://v3.fal.media/media/abc123?x=1'
+
+ await expect(gatewayImageProxyDataUrl(url)).resolves.toBe('data:image/png;base64,cGRveGllZA==')
+ expect(api).toHaveBeenCalledWith({ path: `/api/media/proxy?url=${encodeURIComponent(url)}` })
+ })
+
+ it('pins the request to the owner connection and profile when given', async () => {
+ await gatewayImageProxyDataUrl('https://fal.run/img.png', {
+ connectionId: 'studio-ssh',
+ profile: 'voice reviewer'
+ })
+
+ expect(api).toHaveBeenCalledWith({
+ connectionId: 'studio-ssh',
+ path: '/api/media/proxy?url=https%3A%2F%2Ffal.run%2Fimg.png',
+ profile: 'voice reviewer'
+ })
+ })
+
+ it('returns an empty string for non-http sources and proxy failures', async () => {
+ await expect(gatewayImageProxyDataUrl('data:image/png;base64,aGk=')).resolves.toBe('')
+ await expect(gatewayImageProxyDataUrl('/local/file.png')).resolves.toBe('')
+ expect(api).not.toHaveBeenCalled()
+
+ api.mockRejectedValueOnce(new Error('403 Image host not allowed'))
+ await expect(gatewayImageProxyDataUrl('https://fal.media/x.png')).resolves.toBe('')
+ })
+})
+
describe('downloadGatewayMediaFile', () => {
const saveGatewayFile = vi.fn(async () => ({ path: '/Users/me/Downloads/report.md', saved: true }))
diff --git a/apps/desktop/src/lib/media.ts b/apps/desktop/src/lib/media.ts
index 3fe026a7e26..f54f0708b21 100644
--- a/apps/desktop/src/lib/media.ts
+++ b/apps/desktop/src/lib/media.ts
@@ -322,6 +322,30 @@ export async function gatewayMediaDataUrl(path: string): Promise<string> {
return readDesktopFileDataUrl(filePathFromMediaPath(path))
}
+/** Retry an inline remote image through the gateway's authenticated proxy
+ * (#74564). A client on a restricted network cannot reach the image CDN
+ * directly, but the gateway that GENERATED the image can; ask it to fetch the
+ * bytes and hand them back as a data URL. Returns '' when the gateway rejects
+ * or cannot fetch the URL (unknown host, not an image, too large) — the caller
+ * keeps the failed direct src so the row still renders its fallback. */
+export async function gatewayImageProxyDataUrl(url: string, owner?: OwnerScope): Promise<string> {
+ if (!/^https?:/i.test(url)) {
+ return ''
+ }
+
+ try {
+ const result = await hermesApi<string | { dataUrl?: string }>({
+ path: `/api/media/proxy?url=${encodeURIComponent(url)}`,
+ ...(owner?.connectionId ? { connectionId: owner.connectionId } : {}),
+ ...(owner?.profile ? { profile: owner.profile } : {})
+ })
+
+ return typeof result === 'string' ? result : result.dataUrl || ''
+ } catch {
+ return ''
+ }
+}
+
export interface GatewayFileSaveResult {
canceled?: boolean
path?: string
diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.py
index b6fc5f7ccfa..6d498410519 100644
--- a/hermes_cli/web_routers/files.py
+++ b/hermes_cli/web_routers/files.py
@@ -42,6 +42,7 @@ _profile_scope = late("_profile_scope", "hermes_cli.web_server_profiles")
get_hermes_home = late("get_hermes_home", "hermes_cli.config")
load_config = late("load_config", "hermes_cli.config")
load_env = late("load_env", "hermes_cli.config")
+_require_token = late("_require_token")
# Image types GET /api/media serves — extension-allowlisted so an authenticated
# caller can't pull non-image files through it.
_MEDIA_CONTENT_TYPES = {
@@ -349,6 +350,65 @@ async def get_media(path: str):
return {"data_url": f"data:{_MEDIA_CONTENT_TYPES[target.suffix.lower()]};base64,{encoded}"}
+# Remote image URLs an authenticated proxy may fetch for a client that cannot
+# reach the CDN itself (#74564: a Desktop on a restricted network renders an
+# agent-generated FAL image inline; the direct link is blocked, but the GATEWAY
+# hosts a working route to the CDN and already holds the generation credentials).
+# Host-allowlisted + size-capped like the rest of the media surface.
+_MEDIA_PROXY_ALLOWED_HOSTS = (
+ "fal.media", "fal.run", "v3.fal.media", "storage.googleapis.com",
+ "*.fal.media", "*.fal.run",
+)
+_MEDIA_PROXY_TIMEOUT_S = 20.0
+
+
+def _media_proxy_host_allowed(host: str) -> bool:
+ host = host.lower().rstrip(".")
+ return any(
+ host == allowed.lstrip("*.") or (allowed.startswith("*.") and host.endswith(allowed[1:]))
+ for allowed in _MEDIA_PROXY_ALLOWED_HOSTS
+ )
+
+
[email protected]("/api/media/proxy")
+async def proxy_remote_media(url: str, request: Request):
+ """Fetch a remote image URL the gateway can reach but the client cannot
+ (#74564), returning the same ``data_url`` shape as ``/api/media``. Only
+ allowlisted image CDNs; the bytes stay behind the size cap."""
+ _require_token(request)
+ parsed = urllib.parse.urlparse((url or "").strip())
+ if parsed.scheme not in ("http", "https") or not parsed.hostname:
+ raise HTTPException(status_code=400, detail="A remote image URL is required")
+ if not _media_proxy_host_allowed(parsed.hostname):
+ raise HTTPException(status_code=403, detail="Image host not allowed")
+ if not parsed.path or Path(parsed.path).suffix.lower() not in _MEDIA_CONTENT_TYPES:
+ # Generated-image CDN URLs are content-hash paths with no extension;
+ # a missing extension is expected, so only reject explicit non-image
+ # extensions and let content type be sniffed from the response.
+ if Path(parsed.path).suffix and Path(parsed.path).suffix.lower() not in _MEDIA_CONTENT_TYPES:
+ raise HTTPException(status_code=415, detail="Unsupported media type")
+
+ import httpx
+
+ try:
+ async with httpx.AsyncClient(timeout=_MEDIA_PROXY_TIMEOUT_S, follow_redirects=True) as client:
+ response = await client.get(url)
+ except Exception as exc:
+ raise HTTPException(status_code=502, detail=f"Image fetch failed: {exc}")
+
+ if response.status_code != 200:
+ raise HTTPException(status_code=502, detail=f"Image fetch returned HTTP {response.status_code}")
+ content_type = (response.headers.get("content-type") or "").split(";")[0].strip().lower()
+ if content_type not in _MEDIA_CONTENT_TYPES.values():
+ raise HTTPException(status_code=415, detail="Unsupported media type")
+ data = response.content
+ if len(data) > _MEDIA_MAX_BYTES:
+ raise HTTPException(status_code=413, detail="File too large")
+
+ encoded = base64.b64encode(data).decode("ascii")
+ return {"data_url": f"data:{content_type};base64,{encoded}"}
+
+
def _decode_data_url(data_url: str) -> tuple[bytes, str]:
from hermes_cli.web_server import _MANAGED_FILE_MAX_BYTES
text = (data_url or "").strip()
diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.py
index 913455c2e9c..442227d2722 100644
--- a/tests/hermes_cli/test_web_server.py
+++ b/tests/hermes_cli/test_web_server.py
@@ -1098,6 +1098,98 @@ CONFIG_SCHEMA = ProviderConfigSchema(
)
assert resp.status_code == 401
+ # ── GET /api/media/proxy (client-blocked CDN fallback, #74564) ──────
+
+
+ def test_media_proxy_requires_auth(self):
+ from hermes_cli.web_server import _SESSION_HEADER_NAME
+
+ resp = self.client.get(
+ "/api/media/proxy",
+ params={"url": "https://v3.fal.media/x.png"},
+ headers={_SESSION_HEADER_NAME: "wrong-token"},
+ )
+ assert resp.status_code == 401
+
+ def test_media_proxy_rejects_disallowed_hosts_and_schemes(self):
+ for bad in (
+ "https://evil.example.com/img.png",
+ "https://sub.fal.media.evil.com/img.png",
+ "file:///etc/passwd",
+ "not a url",
+ "",
+ ):
+ resp = self.client.get("/api/media/proxy", params={"url": bad})
+ assert resp.status_code in (400, 403), (bad, resp.status_code)
+
+ def test_media_proxy_fetches_allowlisted_image_and_returns_data_url(self, monkeypatch):
+ png_bytes = b"\x89PNG\r\n\x1a\n" + b"0" * 8
+
+ class _Resp:
+ status_code = 200
+ headers = {"content-type": "image/png"}
+ content = png_bytes
+
+ class _Client:
+ def __init__(self, *a, **k):
+ pass
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *a):
+ return False
+
+ async def get(self, url):
+ assert url == "https://v3.fal.media/media/abc123"
+ return _Resp()
+
+ import hermes_cli.web_routers.files as files_router
+
+ monkeypatch.setattr(files_router, "_require_token", lambda request: None, raising=False)
+ # The route imports httpx locally; patch the module it resolves from.
+ import httpx
+
+ monkeypatch.setattr(httpx, "AsyncClient", _Client, raising=False)
+
+ resp = self.client.get(
+ "/api/media/proxy", params={"url": "https://v3.fal.media/media/abc123"}
+ )
+ assert resp.status_code == 200
+ import base64
+
+ assert resp.json()["data_url"] == (
+ "data:image/png;base64," + base64.b64encode(png_bytes).decode("ascii")
+ )
+
+ def test_media_proxy_rejects_non_image_content_type(self, monkeypatch):
+ class _Resp:
+ status_code = 200
+ headers = {"content-type": "text/html"}
+ content = b"<html>nope</html>"
+
+ class _Client:
+ def __init__(self, *a, **k):
+ pass
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *a):
+ return False
+
+ async def get(self, url):
+ return _Resp()
+
+ import httpx
+
+ monkeypatch.setattr(httpx, "AsyncClient", _Client, raising=False)
+
+ resp = self.client.get(
+ "/api/media/proxy", params={"url": "https://fal.media/media/abc123"}
+ )
+ assert resp.status_code == 415
+
# ── POST /api/chat/image-upload (browser clipboard/drop images) ─────