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(editor): rehost pasted document images (#19527)

Rdmclin2021bd4b4b3e0
diff --git a/apps/server/src/routers/lambda/__tests__/file.test.ts b/apps/server/src/routers/lambda/__tests__/file.test.ts
index 547232225ff..e07e32835e4 100644
--- a/apps/server/src/routers/lambda/__tests__/file.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/file.test.ts
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { KnowledgeRepo } from '@/database/repositories/knowledge';
import { fileRouter } from '@/server/routers/lambda/file';
+import { downloadRemoteImage } from '@/server/services/file/downloadRemoteImage';
import { AsyncTaskStatus } from '@/types/asyncTask';
import { FileSource } from '@/types/files';
import { TransferErrorCode } from '@/types/transferError';
@@ -229,11 +230,15 @@ const mockFileServiceGetFileContent = vi.fn();
const mockFileServiceGetFileAccessUrl = vi.fn();
const mockFileServiceGetFileMetadata = vi.fn();
const mockFileServiceDeleteFile = vi.fn();
+const mockUploadFromBuffer = vi.fn();
+
+vi.mock('@/server/services/file/downloadRemoteImage', () => ({ downloadRemoteImage: vi.fn() }));
vi.mock('@/server/services/file', () => ({
FileService: vi.fn(function () {
return {
deleteFile: mockFileServiceDeleteFile,
+ uploadFromBuffer: mockUploadFromBuffer,
deleteFiles: vi.fn(),
getFileAccessUrl: mockFileServiceGetFileAccessUrl,
getFileContent: mockFileServiceGetFileContent,
@@ -309,6 +314,58 @@ vi.mock('@/server/services/resourcePermission', () => ({
assertCanPerformResourceAction: mockAssertCanPerformResourceAction,
}));
+describe('fileRouter rehostImage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ routerMocks.businessFileUploadCheck.mockResolvedValue(undefined);
+ vi.mocked(downloadRemoteImage).mockResolvedValue({
+ buffer: Buffer.from('image'),
+ extension: 'png',
+ mimeType: 'image/png',
+ });
+ mockUploadFromBuffer.mockImplementation(async (_buffer, _mime, _path, beforeRecord) => {
+ await beforeRecord(routerMocks.transactionClient);
+ return { fileId: 'image-id', key: 'stored-key', url: 'https://lobehub.com/f/image-id' };
+ });
+ });
+
+ it('returns an attachment after checking actual bytes within the upload transaction', async () => {
+ const { caller } = createCallerWithCtx();
+ await expect(
+ caller.rehostImage({ url: 'https://cdn.discordapp.com/image.png' }),
+ ).resolves.toEqual({ fileId: 'image-id', url: 'https://lobehub.com/f/image-id' });
+ expect(mockUploadFromBuffer.mock.calls[0][4]).toEqual({
+ source: FileSource.PageEditor,
+ visibility: 'private',
+ });
+ expect(routerMocks.businessFileUploadCheck).toHaveBeenCalledWith(
+ expect.objectContaining({
+ actualSize: 5,
+ inputSize: 5,
+ userId: 'test-user',
+ transaction: routerMocks.transactionClient,
+ }),
+ );
+ });
+
+ it('propagates quota rejection instead of returning an attachment', async () => {
+ routerMocks.businessFileUploadCheck.mockRejectedValueOnce(new TRPCError({ code: 'FORBIDDEN' }));
+ const { caller } = createCallerWithCtx();
+ await expect(
+ caller.rehostImage({ url: 'https://cdn.discordapp.com/image.png' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('does not upload failed downloads', async () => {
+ vi.mocked(downloadRemoteImage).mockRejectedValueOnce(new Error('Download failed'));
+ const { caller } = createCallerWithCtx();
+ await expect(
+ caller.rehostImage({ url: 'https://cdn.discordapp.com/image.png' }),
+ ).rejects.toThrow('Download failed');
+ expect(mockUploadFromBuffer).not.toHaveBeenCalled();
+ });
+});
+
describe('fileRouter', () => {
let ctx: any;
let caller: any;
diff --git a/apps/server/src/routers/lambda/file.ts b/apps/server/src/routers/lambda/file.ts
index 762abaff972..633ec787862 100644
--- a/apps/server/src/routers/lambda/file.ts
+++ b/apps/server/src/routers/lambda/file.ts
@@ -1,3 +1,5 @@
+import { randomUUID } from 'node:crypto';
+
import {
CUSTOM_FOLDER_FILE_TYPE,
DERIVED_DOCUMENT_SOURCE_TYPE,
@@ -29,13 +31,14 @@ import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { DocumentService } from '@/server/services/document';
import { FileService } from '@/server/services/file';
+import { downloadRemoteImage } from '@/server/services/file/downloadRemoteImage';
import { FileUploadService } from '@/server/services/fileUpload';
import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';
import { createResourceContentPreview } from '@/server/utils/resourceContentPreview';
import { AsyncTaskStatus, AsyncTaskType, type IAsyncTaskError } from '@/types/asyncTask';
import type { FileListItem, KnowledgeItemStatus } from '@/types/files';
-import { QueryFileListSchema, toFileSource, UploadFileSchema } from '@/types/files';
+import { FileSource, QueryFileListSchema, toFileSource, UploadFileSchema } from '@/types/files';
import { TransferErrorCode } from '@/types/transferError';
import {
@@ -858,6 +861,32 @@ export const fileRouter = router({
return ctx.knowledgeRepo.queryRecent(limit, 'page', input?.visibility);
}),
+ rehostImage: fileProcedure
+ .use(withScopedPermission('file:upload'))
+ .use(checkFileStorageUsage)
+ .input(z.object({ url: z.url() }))
+ .mutation(async ({ ctx, input }) => {
+ const { buffer, extension, mimeType } = await downloadRemoteImage(input.url);
+ const pathname = `images/${ctx.userId}/${randomUUID()}.${extension}`;
+ const result = await ctx.fileService.uploadFromBuffer(
+ buffer,
+ mimeType,
+ pathname,
+ (transaction) =>
+ businessFileUploadCheck({
+ actualSize: buffer.length,
+ clientIp: ctx.clientIp ?? undefined,
+ inputSize: buffer.length,
+ transaction,
+ url: pathname,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ }),
+ { source: FileSource.PageEditor, visibility: 'private' },
+ );
+ return { fileId: result.fileId, url: result.url };
+ }),
+
removeFile: fileProcedure
.use(withScopedPermission('file:delete'))
.input(z.object({ id: z.string() }))
diff --git a/apps/server/src/services/file/__tests__/index.test.ts b/apps/server/src/services/file/__tests__/index.test.ts
index b0babb6fe37..5192caf84cd 100644
--- a/apps/server/src/services/file/__tests__/index.test.ts
+++ b/apps/server/src/services/file/__tests__/index.test.ts
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { FileModel } from '@/database/models/file';
import { TempFileManager } from '@/server/utils/tempFileManager';
+import { FileSource } from '@/types/files';
import { FileService } from '../index';
@@ -416,6 +417,26 @@ describe('FileService', () => {
);
});
+ it('preserves private visibility and page-editor source for rehosted images', async () => {
+ const beforeRecord = vi.fn();
+ await service.uploadFromBuffer(
+ Buffer.from('image'),
+ 'image/png',
+ 'images/test.png',
+ beforeRecord,
+ {
+ source: FileSource.PageEditor,
+ visibility: 'private',
+ },
+ );
+ expect(beforeRecord).toHaveBeenCalled();
+ expect(mockFileModel.create).toHaveBeenCalledWith(
+ expect.objectContaining({ source: 'page-editor', visibility: 'private' }),
+ expect.any(Boolean),
+ expect.anything(),
+ );
+ });
+
it('should compute hash for deduplication', async () => {
const content = Buffer.from('test content');
diff --git a/apps/server/src/services/file/downloadRemoteImage.test.ts b/apps/server/src/services/file/downloadRemoteImage.test.ts
new file mode 100644
index 00000000000..218321c7a4e
--- /dev/null
+++ b/apps/server/src/services/file/downloadRemoteImage.test.ts
@@ -0,0 +1,92 @@
+// @vitest-environment node
+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { downloadRemoteImage, MAX_REMOTE_IMAGE_BYTES } from './downloadRemoteImage';
+
+vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: vi.fn() }));
+
+const png = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=',
+ 'base64',
+);
+
+describe('downloadRemoteImage', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('downloads through the SSRF guard and uses detected image content', async () => {
+ vi.mocked(ssrfSafeFetch).mockResolvedValue(
+ new Response(png, { headers: { 'content-type': 'application/octet-stream' } }),
+ );
+ await expect(downloadRemoteImage('https://cdn.discordapp.com/image')).resolves.toEqual({
+ buffer: png,
+ extension: 'png',
+ mimeType: 'image/png',
+ });
+ expect(ssrfSafeFetch).toHaveBeenCalledWith(
+ 'https://cdn.discordapp.com/image',
+ {
+ signal: expect.any(AbortSignal),
+ },
+ {
+ maxContentLength: MAX_REMOTE_IMAGE_BYTES + 1,
+ },
+ );
+ });
+
+ it.each([
+ 'file:///etc/passwd',
+ 'data:image/png;base64,AA==',
+ 'https://user:[email protected]/image',
+ ])('rejects unsupported URLs: %s', async (url) => {
+ await expect(downloadRemoteImage(url)).rejects.toThrow('Invalid image URL');
+ expect(ssrfSafeFetch).not.toHaveBeenCalled();
+ });
+
+ it('propagates SSRF rejection without uploading', async () => {
+ vi.mocked(ssrfSafeFetch).mockRejectedValue(new Error('Blocked private IP'));
+ await expect(downloadRemoteImage('http://127.0.0.1/image')).rejects.toThrow(
+ 'Blocked private IP',
+ );
+ });
+
+ it('rejects failed HTTP responses even with image bytes', async () => {
+ vi.mocked(ssrfSafeFetch).mockResolvedValue(new Response(png, { status: 404 }));
+ await expect(downloadRemoteImage('https://example.com/image')).rejects.toThrow(
+ 'Failed to download image',
+ );
+ });
+
+ it('rejects HTML masquerading as an image', async () => {
+ vi.mocked(ssrfSafeFetch).mockResolvedValue(
+ new Response('<html>not an image</html>', { headers: { 'content-type': 'image/png' } }),
+ );
+ await expect(downloadRemoteImage('https://example.com/image')).rejects.toThrow(
+ 'Unsupported image content',
+ );
+ });
+
+ it('rejects oversized declared bodies', async () => {
+ vi.mocked(ssrfSafeFetch).mockResolvedValue(
+ new Response(png, { headers: { 'content-length': String(MAX_REMOTE_IMAGE_BYTES + 1) } }),
+ );
+ await expect(downloadRemoteImage('https://example.com/image')).rejects.toThrow(
+ 'download limit',
+ );
+ });
+
+ it('caps streamed bodies even without a content length', async () => {
+ const cancel = vi.fn();
+ const stream = new ReadableStream({
+ start(controller) {
+ controller.enqueue(new Uint8Array(MAX_REMOTE_IMAGE_BYTES + 1));
+ },
+ cancel,
+ });
+ vi.mocked(ssrfSafeFetch).mockResolvedValue(new Response(stream));
+ await expect(downloadRemoteImage('https://example.com/image')).rejects.toThrow(
+ 'download limit',
+ );
+ expect(cancel).toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/file/downloadRemoteImage.ts b/apps/server/src/services/file/downloadRemoteImage.ts
new file mode 100644
index 00000000000..229586af739
--- /dev/null
+++ b/apps/server/src/services/file/downloadRemoteImage.ts
@@ -0,0 +1,42 @@
+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';
+import { inferImageMimeTypeFromBytes } from '@lobechat/utils/imageMimeType';
+import { readBlobWithLimit } from '@lobechat/utils/imageToBase64';
+import { TRPCError } from '@trpc/server';
+
+export const MAX_REMOTE_IMAGE_BYTES = 20 * 1024 * 1024;
+
+const imageExtensions: Record<string, string> = {
+ 'image/avif': 'avif',
+ 'image/bmp': 'bmp',
+ 'image/gif': 'gif',
+ 'image/jpeg': 'jpg',
+ 'image/png': 'png',
+ 'image/webp': 'webp',
+};
+
+export const downloadRemoteImage = async (url: string) => {
+ const parsed = new URL(url);
+ if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Invalid image URL' });
+ }
+
+ const response = await ssrfSafeFetch(
+ url,
+ { signal: AbortSignal.timeout(30_000) },
+ { maxContentLength: MAX_REMOTE_IMAGE_BYTES + 1 },
+ );
+ if (!response.ok) {
+ await response.body?.cancel();
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Failed to download image' });
+ }
+
+ const blob = await readBlobWithLimit(response, MAX_REMOTE_IMAGE_BYTES);
+ const buffer = Buffer.from(await blob.arrayBuffer());
+ const mimeType = await inferImageMimeTypeFromBytes(buffer);
+ const extension = mimeType && imageExtensions[mimeType];
+ if (!mimeType || !extension) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Unsupported image content' });
+ }
+
+ return { buffer, extension, mimeType };
+};
diff --git a/apps/server/src/services/file/extractFileIdsFromEditorData.test.ts b/apps/server/src/services/file/extractFileIdsFromEditorData.test.ts
index 2e1aeadc464..62539d2913c 100644
--- a/apps/server/src/services/file/extractFileIdsFromEditorData.test.ts
+++ b/apps/server/src/services/file/extractFileIdsFromEditorData.test.ts
@@ -77,18 +77,20 @@ describe('extractFileIdsFromEditorData', () => {
expect(db.select).not.toHaveBeenCalled();
});
- it('extracts fileIds from proxy URLs without DB query', async () => {
+ it('extracts prefixed and UUID fileIds from proxy URLs without DB query', async () => {
const db = mockDb([]);
+ const uuid = '1c4521fe-3921-4f74-8de4-0f8085416ca2';
const json = {
root: {
children: [
image('http://localhost:3010/f/file_a'),
file('http://localhost:3010/f/file_b', 'b.pdf'),
+ image(`https://app.lobehub.com/f/${uuid}`),
],
},
};
const result = await extractFileIdsFromEditorData(json, { db, userId: 'u' });
- expect(result.sort()).toEqual(['file_a', 'file_b']);
+ expect(result.sort()).toEqual([uuid, 'file_a', 'file_b'].sort());
expect(db.select).not.toHaveBeenCalled();
});
diff --git a/apps/server/src/services/file/extractFileIdsFromEditorData.ts b/apps/server/src/services/file/extractFileIdsFromEditorData.ts
index 433ab2e3602..7a8bb1b2897 100644
--- a/apps/server/src/services/file/extractFileIdsFromEditorData.ts
+++ b/apps/server/src/services/file/extractFileIdsFromEditorData.ts
@@ -20,7 +20,7 @@ import { buildWorkspaceWhere } from '@/database/utils/workspace';
* frequently omit the field, so we treat a missing `status` as uploaded.
*/
-const FILE_PROXY_RE = /\/f\/(file_[\w-]+)/;
+const FILE_PROXY_RE = /\/f\/([\w-]+)(?:[/?#]|$)/;
const IMAGE_NODE_TYPES = new Set(['image', 'block-image']);
const FILE_NODE_TYPE = 'file';
diff --git a/apps/server/src/services/file/index.ts b/apps/server/src/services/file/index.ts
index 2ac67e86170..0348cb78427 100644
--- a/apps/server/src/services/file/index.ts
+++ b/apps/server/src/services/file/index.ts
@@ -202,7 +202,9 @@ export class FileService {
metadata?: Record<string, unknown>;
name: string;
size: number;
+ source?: FileItem['source'];
url: string;
+ visibility?: FileItem['visibility'];
},
trx?: Transaction,
): Promise<{ fileId: string; url: string }> {
@@ -234,7 +236,9 @@ export class FileService {
metadata: params.metadata,
name: params.name,
size: params.size,
+ source: params.source,
url: params.url,
+ visibility: params.visibility,
},
!isExist, // insertToGlobalFiles
trx,
@@ -401,6 +405,7 @@ export class FileService {
* is removed again when it rejects.
*/
beforeRecord?: (trx: Transaction) => Promise<void>,
+ recordOptions?: Pick<FileItem, 'source' | 'visibility'>,
): Promise<{ fileId: string; key: string; url: string }> {
// Use uploadBuffer with explicit contentType so S3 Content-Type matches
// the actual bytes (e.g. PNG buffer won't get image/jpeg from .jpg pathname)
@@ -436,6 +441,7 @@ export class FileService {
name,
size,
url: key,
+ ...recordOptions,
},
trx,
);
diff --git a/packages/utils/src/imageToBase64.ts b/packages/utils/src/imageToBase64.ts
index 5b442c7c298..083b603001e 100644
--- a/packages/utils/src/imageToBase64.ts
+++ b/packages/utils/src/imageToBase64.ts
@@ -48,7 +48,7 @@ export interface ImageUrlToBase64Options {
const sizeLimitError = (maxBytes: number) =>
new RangeError(`Remote binary exceeds the ${maxBytes}-byte download limit`);
-const readBlobWithLimit = async (response: Response, maxBytes: number): Promise<Blob> => {
+export const readBlobWithLimit = async (response: Response, maxBytes: number): Promise<Blob> => {
const declaredLength = Number(response.headers.get('content-length'));
if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
await response.body?.cancel().catch(() => {});
diff --git a/src/features/EditorCanvas/InternalEditor.readonly.test.tsx b/src/features/EditorCanvas/InternalEditor.readonly.test.tsx
index f3f9bd429fc..49421924bfd 100644
--- a/src/features/EditorCanvas/InternalEditor.readonly.test.tsx
+++ b/src/features/EditorCanvas/InternalEditor.readonly.test.tsx
@@ -18,6 +18,7 @@ vi.mock('@lobehub/ui/base-ui', () => ({
const editorProps = vi.hoisted(() => ({
last: undefined as any,
+ image: undefined as any,
}));
vi.mock('@lobehub/editor/react', () => ({
@@ -26,7 +27,12 @@ vi.mock('@lobehub/editor/react', () => ({
editorProps.last = props;
return <div data-testid="editor" />;
}),
- { withProps: (plugin: unknown) => plugin },
+ {
+ withProps: (plugin: unknown, props: any) => {
+ if (props?.defaultBlockImage) editorProps.image = props;
+ return plugin;
+ },
+ },
),
useEditorState: () => ({}),
}));
@@ -44,6 +50,8 @@ vi.mock('@/features/ChatInput/InputEditor/plugins', () => ({
createChatInputRichPlugins: () => [],
}));
+vi.mock('./rehostImage', () => ({ needsImageRehost: () => true, rehostImage: vi.fn() }));
+
vi.mock('./InlineToolbar', () => ({
default: () => <div />,
}));
@@ -79,6 +87,26 @@ describe('InternalEditor readonly state', () => {
editorProps.last = undefined;
});
+ it('only rehosts images while the live editor is editable', () => {
+ let editable = false;
+ const liveEditor = {
+ ...editor,
+ getLexicalEditor: () => ({
+ isEditable: () => editable,
+ registerCommand: vi.fn(() => vi.fn()),
+ registerRootListener: vi.fn(() => vi.fn()),
+ registerUpdateListener: vi.fn(() => vi.fn()),
+ }),
+ } as unknown as IEditor;
+ render(<InternalEditor editor={liveEditor} />);
+ expect(editorProps.image.handleRehost).toBeTypeOf('function');
+ expect(editorProps.image.needRehost('https://example.com/image.png')).toBe(false);
+ editable = true;
+ expect(editorProps.image.needRehost('https://example.com/image.png')).toBe(true);
+ editable = false;
+ expect(editorProps.image.needRehost('https://example.com/image.png')).toBe(false);
+ });
+
it('passes editable=false to the editor when disabled', () => {
render(<InternalEditor disabled editor={editor} />);
diff --git a/src/features/EditorCanvas/InternalEditor.tsx b/src/features/EditorCanvas/InternalEditor.tsx
index 1bdf91fed2d..7af7d65cad2 100644
--- a/src/features/EditorCanvas/InternalEditor.tsx
+++ b/src/features/EditorCanvas/InternalEditor.tsx
@@ -25,6 +25,7 @@ import InlineToolbar from './InlineToolbar';
import LinearFilePlugin from './LinearFilePlugin';
import { registerAttachmentClickOpen } from './registerAttachmentClickOpen';
import { registerBlockDecoratorCaretGuard } from './registerBlockDecoratorCaretGuard';
+import { needsImageRehost, rehostImage } from './rehostImage';
import { useFileUpload, useImageUpload } from './useImageUpload';
const IMAGE_FILTERS = [
@@ -165,7 +166,10 @@ const InternalEditor = memo<InternalEditorProps>(
const imagePlugin = Editor.withProps(ReactImagePlugin, {
defaultBlockImage: true,
+ handleRehost: rehostImage,
handleUpload: handleImageUpload,
+ needRehost: (url: string) =>
+ !!editor.getLexicalEditor?.()?.isEditable() && needsImageRehost(url),
onPickFile: isDesktop ? handlePickFile : undefined,
});
diff --git a/src/features/EditorCanvas/rehostImage.test.ts b/src/features/EditorCanvas/rehostImage.test.ts
new file mode 100644
index 00000000000..8782b06b83f
--- /dev/null
+++ b/src/features/EditorCanvas/rehostImage.test.ts
@@ -0,0 +1,80 @@
+// @vitest-environment happy-dom
+import { toast } from '@lobehub/ui/base-ui';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { fileService } from '@/services/file';
+
+import { getFileIdForUrl, registerAttachment } from './attachmentRegistry';
+import { needsImageRehost, rehostImage } from './rehostImage';
+
+vi.mock('@/services/file', () => ({ fileService: { rehostImage: vi.fn() } }));
+vi.mock('@lobehub/ui/base-ui', () => ({ toast: { error: vi.fn() } }));
+vi.mock('i18next', () => ({ t: (key: string) => key }));
+
+const setWindowUrl = (url: string) => {
+ (window as typeof window & { happyDOM: { setURL: (url: string) => void } }).happyDOM.setURL(url);
+};
+
+describe('editor image rehosting', () => {
+ const defaultUrl = window.location.href;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ setWindowUrl(defaultUrl);
+ });
+
+ it('transfers Discord and external image URLs', () => {
+ expect(needsImageRehost('https://cdn.discordapp.com/attachments/image.png?ex=123')).toBe(true);
+ expect(needsImageRehost('https://external.example/f/image.png')).toBe(true);
+ });
+
+ it('normalizes protocol-relative images to HTTPS on the desktop origin', async () => {
+ setWindowUrl('app://renderer/');
+ vi.mocked(fileService.rehostImage).mockResolvedValue({
+ fileId: 'rehosted-file',
+ url: 'https://storage.example/rehosted.png',
+ });
+
+ expect(needsImageRehost('//media.discordapp.net/image.png')).toBe(true);
+ await rehostImage('//media.discordapp.net/image.png');
+
+ expect(fileService.rehostImage).toHaveBeenCalledWith('https://media.discordapp.net/image.png');
+ });
+
+ it('does not transfer internal attachments or local image upload sources', () => {
+ for (const url of [
+ '/f/image-id',
+ `${window.location.origin}/f/image-id`,
+ 'data:image/png;base64,abc',
+ 'blob:https://example.com/id',
+ 'desktop://image.png',
+ ]) {
+ expect(needsImageRehost(url)).toBe(false);
+ }
+ registerAttachment('https://storage.example/uploaded.png', 'stored-file');
+ expect(needsImageRehost('https://storage.example/uploaded.png')).toBe(false);
+ });
+
+ it('registers the returned file for document persistence and prevents repeat rehosting', async () => {
+ vi.mocked(fileService.rehostImage).mockResolvedValue({
+ fileId: 'rehosted-file',
+ url: 'https://storage.example/rehosted.png',
+ });
+ await expect(rehostImage('https://cdn.discordapp.com/example.png')).resolves.toEqual({
+ url: 'https://storage.example/rehosted.png',
+ });
+ expect(fileService.rehostImage).toHaveBeenCalledWith('https://cdn.discordapp.com/example.png');
+ expect(getFileIdForUrl('https://storage.example/rehosted.png')).toBe('rehosted-file');
+ expect(needsImageRehost('https://storage.example/rehosted.png')).toBe(false);
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it('propagates download failures to the editor', async () => {
+ vi.mocked(fileService.rehostImage).mockRejectedValue(new Error('Download failed'));
+ await expect(rehostImage('https://cdn.discordapp.com/missing.png')).rejects.toThrow(
+ 'Download failed',
+ );
+ expect(getFileIdForUrl('https://cdn.discordapp.com/missing.png')).toBeUndefined();
+ expect(toast.error).toHaveBeenCalledWith('uploadDock.body.item.error');
+ });
+});
diff --git a/src/features/EditorCanvas/rehostImage.ts b/src/features/EditorCanvas/rehostImage.ts
new file mode 100644
index 00000000000..cda5419bf9a
--- /dev/null
+++ b/src/features/EditorCanvas/rehostImage.ts
@@ -0,0 +1,32 @@
+import { toast } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+
+import { fileService } from '@/services/file';
+
+import { getRegisteredAttachment, registerAttachment } from './attachmentRegistry';
+
+const resolveImageUrl = (src: string) =>
+ new URL(src.startsWith('//') ? `https:${src}` : src, window.location.href);
+
+export const needsImageRehost = (src: string): boolean => {
+ if (getRegisteredAttachment(src)) return false;
+
+ try {
+ const url = resolveImageUrl(src);
+ if (!['http:', 'https:'].includes(url.protocol)) return false;
+ return url.origin !== window.location.origin || !url.pathname.startsWith('/f/');
+ } catch {
+ return false;
+ }
+};
+
+export const rehostImage = async (src: string): Promise<{ url: string }> => {
+ try {
+ const result = await fileService.rehostImage(resolveImageUrl(src).href);
+ registerAttachment(result.url, result.fileId);
+ return { url: result.url };
+ } catch (error) {
+ toast.error(t('uploadDock.body.item.error', { ns: 'file' }));
+ throw error;
+ }
+};
diff --git a/src/services/file/index.ts b/src/services/file/index.ts
index e20431321a4..bac28fd0fb2 100644
--- a/src/services/file/index.ts
+++ b/src/services/file/index.ts
@@ -19,6 +19,8 @@ interface CreateFileParams extends Omit<UploadFileParams, 'url'> {
}
export class FileService {
+ rehostImage = async (url: string) => lambdaClient.file.rehostImage.mutate({ url });
+
createFile = async (
params: UploadFileParams & {
parentId?: string;