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.

βͺ revert(file-proxy): restore anonymous public access to /f/:id (#16754)

Arvin Xud8ea34c8d8f0
diff --git a/src/app/(backend)/f/[id]/route.test.ts b/src/app/(backend)/f/[id]/route.test.ts
index 37a8ea4eff3..5fa8886535a 100644
--- a/src/app/(backend)/f/[id]/route.test.ts
+++ b/src/app/(backend)/f/[id]/route.test.ts
@@ -2,7 +2,6 @@
import type { LobeChatDatabase } from '@lobechat/database';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { auth } from '@/auth';
import { FileModel } from '@/database/models/file';
import type { FileItem } from '@/database/schemas';
import { getServerDB } from '@/database/server';
@@ -10,50 +9,28 @@ import { FileService } from '@/server/services/file';
import { GET } from './route';
-vi.mock('@/auth', () => ({
- auth: {
- api: {
- getSession: vi.fn(),
- },
- },
-}));
-
const fileServiceMocks = vi.hoisted(() => {
const instance = {
createCachedPreSignedUrlForPreview: vi.fn(),
getFullFileUrl: vi.fn(),
};
- return {
- FileService: vi.fn(() => instance),
- instance,
- };
-});
-const fileModelMocks = vi.hoisted(() => {
- const instance = {
- findById: vi.fn(),
- };
- const constructor = vi.fn(() => instance);
- const getFileById = vi.fn();
return {
- FileModel: Object.assign(constructor, { getFileById }),
- getFileById,
+ FileService: vi.fn(() => instance),
instance,
};
});
vi.mock('@/database/models/file', () => ({
- FileModel: fileModelMocks.FileModel,
+ FileModel: {
+ getFileById: vi.fn(),
+ },
}));
vi.mock('@/database/server', () => ({
getServerDB: vi.fn(),
}));
-vi.mock('@/database/core/db-adaptor', () => ({
- getServerDB: vi.fn(),
-}));
-
vi.mock('@/server/services/file', () => ({
FileService: fileServiceMocks.FileService,
}));
@@ -61,103 +38,32 @@ vi.mock('@/server/services/file', () => ({
describe('file proxy route', () => {
const db = {} as LobeChatDatabase;
- beforeEach(async () => {
+ beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getServerDB).mockResolvedValue(db);
- const { getServerDB: adaptorGetServerDB } = await import('@/database/core/db-adaptor');
- vi.mocked(adaptorGetServerDB).mockResolvedValue(db);
-
- vi.mocked(auth.api.getSession).mockResolvedValue({
- session: {} as any,
- user: { id: 'viewer-user-id' } as any,
- });
-
+ vi.mocked(FileModel.getFileById).mockResolvedValue({
+ id: 'file-id',
+ url: 'files/user-id/image.png',
+ userId: 'owner-user-id',
+ } as FileItem);
fileServiceMocks.instance.createCachedPreSignedUrlForPreview.mockResolvedValue(
'https://s3.example.com/presigned-preview-url',
);
});
- it('redirects to a cached presigned preview URL for a personal file the viewer owns', async () => {
- const file = {
- id: 'file-id',
- url: 'files/viewer-user-id/image.png',
- userId: 'viewer-user-id',
- workspaceId: null,
- } as FileItem;
- fileModelMocks.getFileById.mockResolvedValue(file);
- fileModelMocks.instance.findById.mockResolvedValue(file);
-
+ it('should redirect to a cached presigned preview URL instead of a public full file URL', async () => {
const response = await GET(new Request('https://lobehub.com/f/file-id'), {
params: Promise.resolve({ id: 'file-id' }),
});
expect(response.status).toBe(302);
expect(response.headers.get('location')).toBe('https://s3.example.com/presigned-preview-url');
- expect(fileModelMocks.getFileById).toHaveBeenCalledWith(db, 'file-id');
- // Personal file β†’ workspaceId argument is undefined so buildWorkspaceWhere
- // falls into the "userId = viewer AND workspaceId IS NULL" branch.
- expect(FileModel).toHaveBeenCalledWith(db, 'viewer-user-id', undefined);
- expect(fileModelMocks.instance.findById).toHaveBeenCalledWith('file-id');
- expect(FileService).toHaveBeenCalledWith(db, 'viewer-user-id');
+ expect(FileModel.getFileById).toHaveBeenCalledWith(db, 'file-id');
+ expect(FileService).toHaveBeenCalledWith(db, 'owner-user-id');
expect(fileServiceMocks.instance.createCachedPreSignedUrlForPreview).toHaveBeenCalledWith(
- 'files/viewer-user-id/image.png',
+ 'files/user-id/image.png',
);
- });
-
- it('returns 404 when the file id does not exist at all', async () => {
- fileModelMocks.getFileById.mockResolvedValue(undefined);
-
- const response = await GET(new Request('https://lobehub.com/f/missing'), {
- params: Promise.resolve({ id: 'missing' }),
- });
-
- expect(response.status).toBe(404);
- expect(fileModelMocks.instance.findById).not.toHaveBeenCalled();
- expect(fileServiceMocks.instance.createCachedPreSignedUrlForPreview).not.toHaveBeenCalled();
- });
-
- it('returns 404 when the ownership-scoped lookup rejects the viewer (workspace private / cross-user / cross-workspace)', async () => {
- fileModelMocks.getFileById.mockResolvedValue({
- id: 'file-id',
- url: 'files/other-user/image.png',
- userId: 'other-user-id',
- workspaceId: 'ws-42',
- } as FileItem);
- fileModelMocks.instance.findById.mockResolvedValue(undefined);
-
- const response = await GET(new Request('https://lobehub.com/f/file-id'), {
- params: Promise.resolve({ id: 'file-id' }),
- });
-
- expect(response.status).toBe(404);
- // Second pass carried the file's workspaceId so buildWorkspaceWhere ran the
- // workspace-visibility check rather than the personal-mode fallback.
- expect(FileModel).toHaveBeenCalledWith(db, 'viewer-user-id', 'ws-42');
- expect(fileServiceMocks.instance.createCachedPreSignedUrlForPreview).not.toHaveBeenCalled();
- });
-
- it('redirects for a workspace-public file owned by another member (no X-Workspace-Id needed)', async () => {
- fileModelMocks.getFileById.mockResolvedValue({
- id: 'file-id',
- url: 'files/other-user/image.png',
- userId: 'other-user-id',
- workspaceId: 'ws-42',
- } as FileItem);
- fileModelMocks.instance.findById.mockResolvedValue({
- id: 'file-id',
- url: 'files/other-user/image.png',
- userId: 'other-user-id',
- workspaceId: 'ws-42',
- } as FileItem);
-
- const response = await GET(new Request('https://lobehub.com/f/file-id'), {
- params: Promise.resolve({ id: 'file-id' }),
- });
-
- expect(response.status).toBe(302);
- // workspaceId was derived from the file row, not the request headers.
- expect(FileModel).toHaveBeenCalledWith(db, 'viewer-user-id', 'ws-42');
- expect(FileService).toHaveBeenCalledWith(db, 'other-user-id');
+ expect(fileServiceMocks.instance.getFullFileUrl).not.toHaveBeenCalled();
});
});
diff --git a/src/app/(backend)/f/[id]/route.ts b/src/app/(backend)/f/[id]/route.ts
index f456f301736..e6ccecbc8b5 100644
--- a/src/app/(backend)/f/[id]/route.ts
+++ b/src/app/(backend)/f/[id]/route.ts
@@ -1,68 +1,49 @@
import debug from 'debug';
-import { checkAuth } from '@/app/(backend)/middleware/auth';
import { FileModel } from '@/database/models/file';
+import { getServerDB } from '@/database/server';
import { FileService } from '@/server/services/file';
const log = debug('lobe-file:proxy');
-type Params = { id: string };
+type Params = Promise<{ id: string }>;
/**
* File proxy service
* GET /f/:id
*
- * Resolves a file's storage URL to a short-lived S3 presigned URL and issues a
- * 302 redirect. Because the proxy URL is embedded in `<img>` tags and download
- * links (bare `/f/:id` β€” no way to attach `X-Workspace-Id`), workspace context
- * has to be derived from the row itself: we first locate the file by id
- * (unscoped), read its `workspaceId`, then re-run the lookup through
- * `FileModel(..., file.workspaceId)` so `buildWorkspaceWhere` enforces the
- * standard visibility rules. Same result as the ownership check TRPC would run
- * for a member: workspace-public files owned by another member resolve;
- * workspace-private / cross-workspace / cross-user rows surface as 404, which
- * LOBE-11270 relies on when a creator flips a file back from `public` to
- * `private`.
+ * Features:
+ * - Query database to get file record (without userId filter for public access)
+ * - Generate a temporary S3 presigned preview URL
+ * - Return 302 redirect
+ *
+ * NOTE: This endpoint is intentionally unauthenticated. The proxy URL is
+ * embedded in bare `<img>` tags, download links, and links shared to AI β€” none
+ * of which can attach auth headers/cookies. Adding `checkAuth` here would break
+ * every previously-shared `/f/:id` link, so access stays public by id.
*/
-// `checkAuth`'s public shape narrows `params` to the shared `{ provider? }`
-// route family. The `/f/[id]` segment lives outside that family, so cast the
-// exported handler back to the `{ id }` shape Next.js's dynamic-route type
-// checker expects. Type-only cast β€” the runtime shape is unchanged.
-const handler = checkAuth(async (_req: Request, { params, userId, serverDB }) => {
+export const GET = async (_req: Request, segmentData: { params: Params }) => {
try {
- const resolvedParams = (await (params as unknown as Promise<Params>)) as Params;
- const { id } = resolvedParams;
+ const params = await segmentData.params;
+ const { id } = params;
- log('File proxy request: %s (viewer=%s)', id, userId);
+ log('File proxy request: %s', id);
- // Locate the file first (no ownership filter) so we can read its
- // `workspaceId` from the row β€” the request itself carries no workspace
- // context on plain `<img>`/download hits.
- const locatedFile = await FileModel.getFileById(serverDB, id);
- if (!locatedFile) {
- log('File not found: %s', id);
- return new Response('File not found', {
- status: 404,
- });
- }
+ // Get database connection
+ const db = await getServerDB();
- // Re-run through the ownership-scoped model so `buildWorkspaceWhere`
- // applies the same visibility rules TRPC uses (workspace-public visible to
- // any member, private visible only to the creator, personal visible only
- // to the owner).
- const fileModel = new FileModel(serverDB, userId, locatedFile.workspaceId ?? undefined);
- const file = await fileModel.findById(id);
+ // Query file record without userId filter (public access)
+ const file = await FileModel.getFileById(db, id);
if (!file) {
- log('File found but forbidden for viewer: %s', id);
+ log('File not found: %s', id);
return new Response('File not found', {
status: 404,
});
}
- // File service is scoped to the file's owner so it can build the storage
- // key correctly; access permission has already been enforced above.
- const fileService = new FileService(serverDB, file.userId);
+ // Create file service with file owner's userId
+ const fileService = new FileService(db, file.userId);
// Web: Generate a cached S3 presigned URL, normalizing legacy full S3 URLs.
const redirectUrl = await fileService.createCachedPreSignedUrlForPreview(file.url);
@@ -76,9 +57,4 @@ const handler = checkAuth(async (_req: Request, { params, userId, serverDB }) =>
status: 500,
});
}
-});
-
-export const GET = handler as unknown as (
- req: Request,
- ctx: { params: Promise<Params> },
-) => Promise<Response>;
+};