-
Notifications
You must be signed in to change notification settings - Fork 3.5k
fix(pdf): PDF previews by adding the missing preview endpoint and allowing same-origin blob URLs in iframe CSP #4225
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
83 changes: 83 additions & 0 deletions
83
apps/sim/app/api/workspaces/[id]/pdf/preview/route.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
| import { NextRequest } from 'next/server' | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| const { mockGetSession, mockVerifyWorkspaceMembership, mockRunSandboxTask } = vi.hoisted(() => ({ | ||
| mockGetSession: vi.fn(), | ||
| mockVerifyWorkspaceMembership: vi.fn(), | ||
| mockRunSandboxTask: vi.fn(), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/auth', () => ({ | ||
| getSession: mockGetSession, | ||
| })) | ||
|
|
||
| vi.mock('@/app/api/workflows/utils', () => ({ | ||
| verifyWorkspaceMembership: mockVerifyWorkspaceMembership, | ||
| })) | ||
|
|
||
| vi.mock('@/lib/execution/sandbox/run-task', () => ({ | ||
| runSandboxTask: mockRunSandboxTask, | ||
| })) | ||
|
|
||
| import { POST } from '@/app/api/workspaces/[id]/pdf/preview/route' | ||
|
|
||
| describe('PDF preview API route', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| mockGetSession.mockResolvedValue({ user: { id: 'user-1' } }) | ||
| mockVerifyWorkspaceMembership.mockResolvedValue(true) | ||
| mockRunSandboxTask.mockResolvedValue(Buffer.from('%PDF-test')) | ||
| }) | ||
|
|
||
| it('returns a generated PDF for authorized workspace members', async () => { | ||
| const request = new NextRequest( | ||
| 'http://localhost:3000/api/workspaces/workspace-1/pdf/preview', | ||
| { | ||
| method: 'POST', | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| body: JSON.stringify({ code: 'return 1' }), | ||
| } | ||
| ) | ||
|
|
||
| const response = await POST(request, { | ||
| params: Promise.resolve({ id: 'workspace-1' }), | ||
| }) | ||
|
|
||
| expect(response.status).toBe(200) | ||
| expect(response.headers.get('Content-Type')).toBe('application/pdf') | ||
| expect(response.headers.get('Cache-Control')).toBe('private, no-store') | ||
| expect(mockVerifyWorkspaceMembership).toHaveBeenCalledWith('user-1', 'workspace-1') | ||
| expect(mockRunSandboxTask).toHaveBeenCalledWith( | ||
| 'pdf-generate', | ||
| { code: 'return 1', workspaceId: 'workspace-1' }, | ||
| { ownerKey: 'user:user-1', signal: request.signal } | ||
| ) | ||
| expect(Buffer.from(await response.arrayBuffer()).toString()).toBe('%PDF-test') | ||
| }) | ||
|
|
||
| it('rejects requests without code', async () => { | ||
| const request = new NextRequest( | ||
| 'http://localhost:3000/api/workspaces/workspace-1/pdf/preview', | ||
| { | ||
| method: 'POST', | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| body: JSON.stringify({}), | ||
| } | ||
| ) | ||
|
|
||
| const response = await POST(request, { | ||
| params: Promise.resolve({ id: 'workspace-1' }), | ||
| }) | ||
|
|
||
| expect(response.status).toBe(400) | ||
| await expect(response.json()).resolves.toEqual({ error: 'code is required' }) | ||
| expect(mockRunSandboxTask).not.toHaveBeenCalled() | ||
| }) | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| import { createLogger } from '@sim/logger' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { getSession } from '@/lib/auth' | ||
| import { runSandboxTask } from '@/lib/execution/sandbox/run-task' | ||
| import { verifyWorkspaceMembership } from '@/app/api/workflows/utils' | ||
|
|
||
| export const dynamic = 'force-dynamic' | ||
| export const runtime = 'nodejs' | ||
|
|
||
| const logger = createLogger('PdfPreviewAPI') | ||
|
|
||
| /** | ||
| * POST /api/workspaces/[id]/pdf/preview | ||
| * Compile PDF-Lib source code and return the binary PDF for streaming preview. | ||
| */ | ||
| export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) { | ||
| const { id: workspaceId } = await params | ||
|
|
||
| try { | ||
| const session = await getSession() | ||
| if (!session?.user?.id) { | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) | ||
| } | ||
|
|
||
| const membership = await verifyWorkspaceMembership(session.user.id, workspaceId) | ||
| if (!membership) { | ||
| return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 }) | ||
| } | ||
|
|
||
| let body: unknown | ||
| try { | ||
| body = await req.json() | ||
| } catch { | ||
| return NextResponse.json({ error: 'Invalid or missing JSON body' }, { status: 400 }) | ||
| } | ||
| const { code } = body as { code?: string } | ||
|
|
||
| if (typeof code !== 'string' || code.trim().length === 0) { | ||
| return NextResponse.json({ error: 'code is required' }, { status: 400 }) | ||
| } | ||
|
|
||
| const MAX_CODE_BYTES = 512 * 1024 | ||
| if (Buffer.byteLength(code, 'utf-8') > MAX_CODE_BYTES) { | ||
| return NextResponse.json({ error: 'code exceeds maximum size' }, { status: 413 }) | ||
| } | ||
|
|
||
| const buffer = await runSandboxTask( | ||
| 'pdf-generate', | ||
| { code, workspaceId }, | ||
| { ownerKey: `user:${session.user.id}`, signal: req.signal } | ||
| ) | ||
|
|
||
| return new NextResponse(new Uint8Array(buffer), { | ||
| status: 200, | ||
| headers: { | ||
| 'Content-Type': 'application/pdf', | ||
| 'Content-Length': String(buffer.length), | ||
| 'Cache-Control': 'private, no-store', | ||
| }, | ||
| }) | ||
| } catch (err) { | ||
| const message = err instanceof Error ? err.message : 'PDF generation failed' | ||
|
icecrasher321 marked this conversation as resolved.
Outdated
|
||
| logger.error('PDF preview generation failed', { error: message, workspaceId }) | ||
| return NextResponse.json({ error: message }, { status: 500 }) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.