Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(file-viewer): fetch file proxy URLs from the page origin (#21914)

Arvin Xuacc6317955e1
diff --git a/src/features/FileViewer/Renderer/PDF/index.tsx b/src/features/FileViewer/Renderer/PDF/index.tsx
index 49b62f605e7..ead733343de 100644
--- a/src/features/FileViewer/Renderer/PDF/index.tsx
+++ b/src/features/FileViewer/Renderer/PDF/index.tsx
@@ -8,6 +8,7 @@ import { Fragment, memo, useCallback, useState } from 'react';
import { Document, Page, pdfjs } from '@/libs/pdfjs';
+import { toSameOriginFileProxyUrl } from '../../fileProxyUrl';
import HighlightLayer from './HighlightLayer';
import { styles } from './style';
import { useChunkHighlights } from './useChunkHighlights';
@@ -65,7 +66,7 @@ const PDFViewer = memo<PDFViewerProps>(({ url, fileId, showChunkHighlights = tru
>
<Document
className={styles.document}
- file={url}
+ file={url && toSameOriginFileProxyUrl(url)}
loading={<Spin size="large" />}
options={options}
onLoadSuccess={onDocumentLoadSuccess}
diff --git a/src/features/FileViewer/fileProxyUrl.test.ts b/src/features/FileViewer/fileProxyUrl.test.ts
new file mode 100644
index 00000000000..e5a4cea902c
--- /dev/null
+++ b/src/features/FileViewer/fileProxyUrl.test.ts
@@ -0,0 +1,50 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { toSameOriginFileProxyUrl } from './fileProxyUrl';
+
+describe('toSameOriginFileProxyUrl', () => {
+ const origin = window.location.origin;
+
+ it('rewrites a cross-origin file proxy URL to the current origin', () => {
+ expect(toSameOriginFileProxyUrl('https://app.lobehub.com/f/file_k9D0pniGzVIW')).toBe(
+ `${origin}/f/file_k9D0pniGzVIW`,
+ );
+ });
+
+ it('keeps same-origin and relative proxy URLs untouched', () => {
+ expect(toSameOriginFileProxyUrl(`${origin}/f/file_abc`)).toBe(`${origin}/f/file_abc`);
+ expect(toSameOriginFileProxyUrl('/f/file_abc')).toBe('/f/file_abc');
+ });
+
+ it('keeps signed storage and other non-proxy URLs untouched', () => {
+ const signed = 'https://bucket.r2.cloudflarestorage.com/files/a.md?X-Amz-Signature=x';
+ expect(toSameOriginFileProxyUrl(signed)).toBe(signed);
+ expect(toSameOriginFileProxyUrl('https://example.com/f/file_abc/raw')).toBe(
+ 'https://example.com/f/file_abc/raw',
+ );
+ expect(toSameOriginFileProxyUrl('https://example.com/f/file_abc?x=1')).toBe(
+ 'https://example.com/f/file_abc?x=1',
+ );
+ expect(toSameOriginFileProxyUrl('blob:https://example.com/123')).toBe(
+ 'blob:https://example.com/123',
+ );
+ });
+
+ it('keeps a remote proxy URL untouched when the page itself is not http(s)', () => {
+ // The desktop renderer runs at `app://renderer`, where `/f` is not proxied to the backend.
+ vi.stubGlobal('window', {
+ location: { href: 'app://renderer/', origin: 'app://renderer', protocol: 'app:' },
+ });
+
+ try {
+ const remote = 'https://app.lobehub.com/f/file_k9D0pniGzVIW';
+ expect(toSameOriginFileProxyUrl(remote)).toBe(remote);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
diff --git a/src/features/FileViewer/fileProxyUrl.ts b/src/features/FileViewer/fileProxyUrl.ts
new file mode 100644
index 00000000000..0833ec6dd11
--- /dev/null
+++ b/src/features/FileViewer/fileProxyUrl.ts
@@ -0,0 +1,30 @@
+const FILE_PROXY_PATH = /^\/f\/[\w-]+$/;
+
+/**
+ * Point a `/f/:id` file-proxy URL at the current origin before fetching it.
+ *
+ * The server builds proxy URLs from `APP_URL`, which can differ from the host the
+ * SPA runs on (e.g. `app.lobehub.com` vs `lobehub.com`). The proxy answers with a
+ * 302 to signed storage and sends no CORS headers, so a cross-origin `fetch` of it
+ * fails. Same-origin, the redirect keeps the page Origin, which bucket CORS allows.
+ */
+export const toSameOriginFileProxyUrl = (url: string): string => {
+ if (typeof window === 'undefined') return url;
+
+ // Only an http(s) page can inherit the proxy. The desktop renderer runs at
+ // `app://renderer`, where `/f` is not one of the backend-proxied prefixes
+ // (`apps/desktop/src/main/const/protocol.ts`), so rewriting into that origin
+ // would fall through to the static renderer and serve the app HTML instead.
+ if (!['http:', 'https:'].includes(window.location.protocol)) return url;
+
+ try {
+ const parsed = new URL(url, window.location.href);
+ if (parsed.origin === window.location.origin) return url;
+ if (!['http:', 'https:'].includes(parsed.protocol)) return url;
+ if (parsed.search || !FILE_PROXY_PATH.test(parsed.pathname)) return url;
+
+ return `${window.location.origin}${parsed.pathname}`;
+ } catch {
+ return url;
+ }
+};
diff --git a/src/features/FileViewer/hooks/useBlobFileLoader.ts b/src/features/FileViewer/hooks/useBlobFileLoader.ts
index bab3cec3f55..85bf9828873 100644
--- a/src/features/FileViewer/hooks/useBlobFileLoader.ts
+++ b/src/features/FileViewer/hooks/useBlobFileLoader.ts
@@ -1,6 +1,8 @@
import { readBlobWithLimit } from '@lobechat/utils/readBlobWithLimit';
import { useEffect, useState } from 'react';
+import { toSameOriginFileProxyUrl } from '../fileProxyUrl';
+
/** Mirrors the device-side document preview ceiling in `@lobechat/device-control`. */
const MAX_BINARY_PREVIEW_BYTES = 20 * 1024 * 1024;
@@ -39,7 +41,9 @@ export const useBlobFileLoader = (url: string | null): BlobFileState => {
const loadFile = async () => {
try {
- const response = await fetch(url, { signal: controller.signal });
+ const response = await fetch(toSameOriginFileProxyUrl(url), {
+ signal: controller.signal,
+ });
if (!response.ok) throw new Error(`Failed to load file: ${response.status}`);
const blob = await readBlobWithLimit(response, MAX_BINARY_PREVIEW_BYTES);
if (!controller.signal.aborted) setState({ blob, error: null, loading: false, url });
diff --git a/src/features/FileViewer/hooks/useTextFileLoader.test.ts b/src/features/FileViewer/hooks/useTextFileLoader.test.ts
index 11164229a3a..22c5773a2ae 100644
--- a/src/features/FileViewer/hooks/useTextFileLoader.test.ts
+++ b/src/features/FileViewer/hooks/useTextFileLoader.test.ts
@@ -22,6 +22,21 @@ describe('useTextFileLoader', () => {
});
});
+ /** @example A proxy URL built from another app host is fetched through the page origin. */
+ it('fetches a cross-origin file proxy URL from the current origin', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response('# title'));
+ vi.stubGlobal('fetch', fetchMock);
+ const { result } = renderHook(() => useTextFileLoader('https://app.lobehub.com/f/file_abc'));
+ await waitFor(() => {
+ expect(result.current.fileData).toBe('# title');
+ });
+ /** @example The proxy 302 carries no CORS headers, so it must be requested same-origin. */
+ expect(fetchMock).toHaveBeenCalledWith(
+ `${window.location.origin}/f/file_abc`,
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ );
+ });
+
/** @example Empty uploads are successful previews, not perpetual loading. */
it('finishes loading an empty file', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('')));
diff --git a/src/features/FileViewer/hooks/useTextFileLoader.ts b/src/features/FileViewer/hooks/useTextFileLoader.ts
index 74fdcad5d34..d56cc87dd3a 100644
--- a/src/features/FileViewer/hooks/useTextFileLoader.ts
+++ b/src/features/FileViewer/hooks/useTextFileLoader.ts
@@ -2,6 +2,8 @@ import { decodeTextBuffer } from '@lobechat/utils/isBinaryContent';
import { readBlobWithLimit } from '@lobechat/utils/readBlobWithLimit';
import { useEffect, useState } from 'react';
+import { toSameOriginFileProxyUrl } from '../fileProxyUrl';
+
/** Bound text downloads and decoding to 2 MiB to keep preview rendering responsive. */
const MAX_TEXT_PREVIEW_BYTES = 2 * 1024 * 1024;
@@ -41,7 +43,9 @@ export const useTextFileLoader = (url: string | null): TextFileState => {
const loadFile = async () => {
try {
// Abort on navigation; enforce the limit even when Content-Length is missing or wrong.
- const response = await fetch(url, { signal: controller.signal });
+ const response = await fetch(toSameOriginFileProxyUrl(url), {
+ signal: controller.signal,
+ });
if (!response.ok) throw new Error(`Failed to load file: ${response.status}`);
const blob = await readBlobWithLimit(response, MAX_TEXT_PREVIEW_BYTES);
const fileData = decodeTextBuffer(new Uint8Array(await blob.arrayBuffer()));