Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
704d06f
v0
Sg312 Mar 22, 2026
8abb884
Fix ppt load
Sg312 Mar 22, 2026
b28556f
Fixes
Sg312 Mar 22, 2026
dde64aa
Fixes
Sg312 Mar 22, 2026
4a537ff
Fix lint
Sg312 Mar 22, 2026
aa9fc10
Fix wid
Sg312 Mar 22, 2026
5954abd
Download image
Sg312 Mar 22, 2026
77a4f2f
Update tools
Sg312 Mar 23, 2026
d071248
Fix lint
Sg312 Mar 23, 2026
844c9a2
Fix error msg
Sg312 Mar 23, 2026
46e8964
Tool fixes
Sg312 Mar 23, 2026
6549a50
Reenable subagent stream
Sg312 Mar 23, 2026
98f4dfd
Subagent stream
Sg312 Mar 23, 2026
1e7a987
Fix edit workflow hydration
Sg312 Mar 23, 2026
0b3000a
Throw func execute error on error
Sg312 Mar 23, 2026
e21a987
Sandbox PPTX generation in subprocess with vm.createContext
waleedlatif1 Mar 23, 2026
cc50d1e
upgrade deps, file viewer
waleedlatif1 Mar 23, 2026
119d5a5
Fix auth bypass, SSRF, and wrong size limit comment
waleedlatif1 Mar 23, 2026
cc214cd
Fix Buffer not assignable to BodyInit in preview route
waleedlatif1 Mar 23, 2026
c5f73a7
Fix SSRF bypass, IPv6 coverage, download size cap, and missing deps
waleedlatif1 Mar 23, 2026
ad2dab1
Replace hand-rolled SSRF guard with secureFetchWithValidation
waleedlatif1 Mar 23, 2026
51b47f1
Fix streaming preview cache ordering and patch ambiguity
waleedlatif1 Mar 23, 2026
7ab98e2
Fix subprocess env leak, unbounded preview spawning, and dead code
waleedlatif1 Mar 23, 2026
6ffb4b9
Wire abort signal through to subprocess and correct security comment
waleedlatif1 Mar 23, 2026
5de3616
Remove implementation-specific comments from pptx worker files
waleedlatif1 Mar 23, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 51 additions & 10 deletions apps/sim/app/api/files/serve/[...path]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ import { createLogger } from '@sim/logger'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
import { generatePptxFromCode } from '@/lib/execution/pptx-vm'
import { CopilotFiles, isUsingCloudStorage } from '@/lib/uploads'
import type { StorageContext } from '@/lib/uploads/config'
import { parseWorkspaceFileKey } from '@/lib/uploads/contexts/workspace/workspace-file-manager'
import { downloadFile } from '@/lib/uploads/core/storage-service'
import { inferContextFromKey } from '@/lib/uploads/utils/file-utils'
import { verifyFileAccess } from '@/app/api/files/authorization'
Expand All @@ -18,6 +20,27 @@ import {

const logger = createLogger('FilesServeAPI')

const ZIP_MAGIC = Buffer.from([0x50, 0x4b, 0x03, 0x04])

async function compilePptxIfNeeded(
buffer: Buffer,
filename: string,
workspaceId?: string,
raw?: boolean
): Promise<{ buffer: Buffer; contentType: string }> {
const isPptx = filename.toLowerCase().endsWith('.pptx')
if (raw || !isPptx || buffer.subarray(0, 4).equals(ZIP_MAGIC)) {
return { buffer, contentType: getContentType(filename) }
}

const code = buffer.toString('utf-8')
const compiled = await generatePptxFromCode(code, workspaceId || '')
return {
buffer: compiled,
contentType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
}
}

const STORAGE_KEY_PREFIX_RE = /^\d{13}-[a-z0-9]{7}-/

function stripStorageKeyPrefix(segment: string): string {
Expand All @@ -44,6 +67,7 @@ export async function GET(
const cloudKey = isCloudPath ? path.slice(1).join('/') : fullPath

const contextParam = request.nextUrl.searchParams.get('context')
const raw = request.nextUrl.searchParams.get('raw') === '1'

const context = contextParam || (isCloudPath ? inferContextFromKey(cloudKey) : undefined)

Expand All @@ -68,10 +92,10 @@ export async function GET(
const userId = authResult.userId

if (isUsingCloudStorage()) {
return await handleCloudProxy(cloudKey, userId, contextParam)
return await handleCloudProxy(cloudKey, userId, contextParam, raw)
}

return await handleLocalFile(cloudKey, userId)
return await handleLocalFile(cloudKey, userId, raw)
} catch (error) {
logger.error('Error serving file:', error)

Expand All @@ -83,7 +107,11 @@ export async function GET(
}
}

async function handleLocalFile(filename: string, userId: string): Promise<NextResponse> {
async function handleLocalFile(
filename: string,
userId: string,
raw: boolean
): Promise<NextResponse> {
try {
const contextParam: StorageContext | undefined = inferContextFromKey(filename) as
| StorageContext
Expand All @@ -108,10 +136,16 @@ async function handleLocalFile(filename: string, userId: string): Promise<NextRe
throw new FileNotFoundError(`File not found: ${filename}`)
}

const fileBuffer = await readFile(filePath)
const rawBuffer = await readFile(filePath)
const segment = filename.split('/').pop() || filename
const displayName = stripStorageKeyPrefix(segment)
const contentType = getContentType(displayName)
const workspaceId = parseWorkspaceFileKey(filename) ?? undefined
const { buffer: fileBuffer, contentType } = await compilePptxIfNeeded(
rawBuffer,
displayName,
workspaceId,
raw
)

logger.info('Local file served', { userId, filename, size: fileBuffer.length })

Expand All @@ -130,7 +164,8 @@ async function handleLocalFile(filename: string, userId: string): Promise<NextRe
async function handleCloudProxy(
cloudKey: string,
userId: string,
contextParam?: string | null
contextParam?: string | null,
raw = false
): Promise<NextResponse> {
try {
let context: StorageContext
Expand All @@ -156,20 +191,26 @@ async function handleCloudProxy(
throw new FileNotFoundError(`File not found: ${cloudKey}`)
}

let fileBuffer: Buffer
let rawBuffer: Buffer

if (context === 'copilot') {
fileBuffer = await CopilotFiles.downloadCopilotFile(cloudKey)
rawBuffer = await CopilotFiles.downloadCopilotFile(cloudKey)
} else {
fileBuffer = await downloadFile({
rawBuffer = await downloadFile({
key: cloudKey,
context,
})
}

const segment = cloudKey.split('/').pop() || 'download'
const displayName = stripStorageKeyPrefix(segment)
const contentType = getContentType(displayName)
const workspaceId = parseWorkspaceFileKey(cloudKey) ?? undefined
const { buffer: fileBuffer, contentType } = await compilePptxIfNeeded(
rawBuffer,
displayName,
workspaceId,
raw
)

logger.info('Cloud file served', {
userId,
Expand Down
52 changes: 52 additions & 0 deletions apps/sim/app/api/workspaces/[id]/pptx/preview/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { generatePptxFromCode } from '@/lib/execution/pptx-vm'
import { verifyWorkspaceMembership } from '@/app/api/workflows/utils'

export const dynamic = 'force-dynamic'
export const runtime = 'nodejs'

const logger = createLogger('PptxPreviewAPI')

/**
* POST /api/workspaces/[id]/pptx/preview
* Compile PptxGenJS source code and return the binary PPTX 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 })
}

const body = await req.json()
const { code } = body as { code?: string }

if (typeof code !== 'string' || code.trim().length === 0) {
return NextResponse.json({ error: 'code is required' }, { status: 400 })
}

const buffer = await generatePptxFromCode(code, workspaceId, req.signal)

return new NextResponse(new Uint8Array(buffer), {
status: 200,
headers: {
'Content-Type': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'Content-Length': String(buffer.length),
'Cache-Control': 'private, no-store',
},
})
} catch (err) {
const message = err instanceof Error ? err.message : 'PPTX generation failed'
logger.error('PPTX preview generation failed', { error: message, workspaceId })
return NextResponse.json({ error: message }, { status: 500 })
}
}
Loading
Loading