|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import { type NextRequest, NextResponse } from 'next/server' |
| 3 | +import { z } from 'zod' |
| 4 | +import { checkInternalAuth } from '@/lib/auth/hybrid' |
| 5 | +import { generateRequestId } from '@/lib/core/utils/request' |
| 6 | +import { FileInputSchema } from '@/lib/uploads/utils/file-schemas' |
| 7 | +import { processFilesToUserFiles } from '@/lib/uploads/utils/file-utils' |
| 8 | +import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server' |
| 9 | + |
| 10 | +export const dynamic = 'force-dynamic' |
| 11 | + |
| 12 | +const logger = createLogger('DropboxUploadAPI') |
| 13 | + |
| 14 | +/** |
| 15 | + * Escapes non-ASCII characters in JSON string for HTTP header safety. |
| 16 | + * Dropbox API requires characters 0x7F and all non-ASCII to be escaped as \uXXXX. |
| 17 | + */ |
| 18 | +function httpHeaderSafeJson(value: object): string { |
| 19 | + return JSON.stringify(value).replace(/[\u007f-\uffff]/g, (c) => { |
| 20 | + return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4) |
| 21 | + }) |
| 22 | +} |
| 23 | + |
| 24 | +const DropboxUploadSchema = z.object({ |
| 25 | + accessToken: z.string().min(1, 'Access token is required'), |
| 26 | + path: z.string().min(1, 'Destination path is required'), |
| 27 | + file: FileInputSchema.optional().nullable(), |
| 28 | + // Legacy field for backwards compatibility |
| 29 | + fileContent: z.string().optional().nullable(), |
| 30 | + fileName: z.string().optional().nullable(), |
| 31 | + mode: z.enum(['add', 'overwrite']).optional().nullable(), |
| 32 | + autorename: z.boolean().optional().nullable(), |
| 33 | + mute: z.boolean().optional().nullable(), |
| 34 | +}) |
| 35 | + |
| 36 | +export async function POST(request: NextRequest) { |
| 37 | + const requestId = generateRequestId() |
| 38 | + |
| 39 | + try { |
| 40 | + const authResult = await checkInternalAuth(request, { requireWorkflowId: false }) |
| 41 | + |
| 42 | + if (!authResult.success) { |
| 43 | + logger.warn(`[${requestId}] Unauthorized Dropbox upload attempt: ${authResult.error}`) |
| 44 | + return NextResponse.json( |
| 45 | + { success: false, error: authResult.error || 'Authentication required' }, |
| 46 | + { status: 401 } |
| 47 | + ) |
| 48 | + } |
| 49 | + |
| 50 | + logger.info(`[${requestId}] Authenticated Dropbox upload request via ${authResult.authType}`) |
| 51 | + |
| 52 | + const body = await request.json() |
| 53 | + const validatedData = DropboxUploadSchema.parse(body) |
| 54 | + |
| 55 | + let fileBuffer: Buffer |
| 56 | + let fileName: string |
| 57 | + |
| 58 | + // Prefer UserFile input, fall back to legacy base64 string |
| 59 | + if (validatedData.file) { |
| 60 | + // Process UserFile input |
| 61 | + const userFiles = processFilesToUserFiles([validatedData.file], requestId, logger) |
| 62 | + |
| 63 | + if (userFiles.length === 0) { |
| 64 | + return NextResponse.json({ success: false, error: 'Invalid file input' }, { status: 400 }) |
| 65 | + } |
| 66 | + |
| 67 | + const userFile = userFiles[0] |
| 68 | + logger.info(`[${requestId}] Downloading file: ${userFile.name} (${userFile.size} bytes)`) |
| 69 | + |
| 70 | + fileBuffer = await downloadFileFromStorage(userFile, requestId, logger) |
| 71 | + fileName = userFile.name |
| 72 | + } else if (validatedData.fileContent) { |
| 73 | + // Legacy: base64 string input (backwards compatibility) |
| 74 | + logger.info(`[${requestId}] Using legacy base64 content input`) |
| 75 | + fileBuffer = Buffer.from(validatedData.fileContent, 'base64') |
| 76 | + fileName = validatedData.fileName || 'file' |
| 77 | + } else { |
| 78 | + return NextResponse.json( |
| 79 | + { success: false, error: 'File or file content is required' }, |
| 80 | + { status: 400 } |
| 81 | + ) |
| 82 | + } |
| 83 | + |
| 84 | + // Determine final path |
| 85 | + let finalPath = validatedData.path |
| 86 | + if (finalPath.endsWith('/')) { |
| 87 | + finalPath = `${finalPath}${fileName}` |
| 88 | + } |
| 89 | + |
| 90 | + logger.info(`[${requestId}] Uploading to Dropbox: ${finalPath} (${fileBuffer.length} bytes)`) |
| 91 | + |
| 92 | + const dropboxApiArg = { |
| 93 | + path: finalPath, |
| 94 | + mode: validatedData.mode || 'add', |
| 95 | + autorename: validatedData.autorename ?? true, |
| 96 | + mute: validatedData.mute ?? false, |
| 97 | + } |
| 98 | + |
| 99 | + const response = await fetch('https://content.dropboxapi.com/2/files/upload', { |
| 100 | + method: 'POST', |
| 101 | + headers: { |
| 102 | + Authorization: `Bearer ${validatedData.accessToken}`, |
| 103 | + 'Content-Type': 'application/octet-stream', |
| 104 | + 'Dropbox-API-Arg': httpHeaderSafeJson(dropboxApiArg), |
| 105 | + }, |
| 106 | + body: fileBuffer, |
| 107 | + }) |
| 108 | + |
| 109 | + const data = await response.json() |
| 110 | + |
| 111 | + if (!response.ok) { |
| 112 | + const errorMessage = data.error_summary || data.error?.message || 'Failed to upload file' |
| 113 | + logger.error(`[${requestId}] Dropbox API error:`, { status: response.status, data }) |
| 114 | + return NextResponse.json({ success: false, error: errorMessage }, { status: response.status }) |
| 115 | + } |
| 116 | + |
| 117 | + logger.info(`[${requestId}] File uploaded successfully to ${data.path_display}`) |
| 118 | + |
| 119 | + return NextResponse.json({ |
| 120 | + success: true, |
| 121 | + output: { |
| 122 | + file: data, |
| 123 | + }, |
| 124 | + }) |
| 125 | + } catch (error) { |
| 126 | + if (error instanceof z.ZodError) { |
| 127 | + logger.warn(`[${requestId}] Validation error:`, error.errors) |
| 128 | + return NextResponse.json( |
| 129 | + { success: false, error: error.errors[0]?.message || 'Validation failed' }, |
| 130 | + { status: 400 } |
| 131 | + ) |
| 132 | + } |
| 133 | + |
| 134 | + logger.error(`[${requestId}] Unexpected error:`, error) |
| 135 | + return NextResponse.json( |
| 136 | + { success: false, error: error instanceof Error ? error.message : 'Unknown error' }, |
| 137 | + { status: 500 } |
| 138 | + ) |
| 139 | + } |
| 140 | +} |
0 commit comments