|
| 1 | +import path from 'node:path' |
| 2 | +import { createLogger } from '@sim/logger' |
| 3 | +import { toError } from '@sim/utils/errors' |
| 4 | +import JSZip from 'jszip' |
| 5 | +import type { NextRequest } from 'next/server' |
| 6 | +import { NextResponse } from 'next/server' |
| 7 | +import { fileExportContract } from '@/lib/api/contracts/storage-transfer' |
| 8 | +import { parseRequest } from '@/lib/api/server' |
| 9 | +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' |
| 10 | +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
| 11 | +import type { StorageContext } from '@/lib/uploads/config' |
| 12 | +import { USE_BLOB_STORAGE } from '@/lib/uploads/config' |
| 13 | +import { downloadFile } from '@/lib/uploads/core/storage-service' |
| 14 | +import { getFileMetadataById } from '@/lib/uploads/server/metadata' |
| 15 | +import { verifyFileAccess } from '@/app/api/files/authorization' |
| 16 | + |
| 17 | +const logger = createLogger('FilesExportAPI') |
| 18 | + |
| 19 | +const MARKDOWN_MIME_TYPES = new Set(['text/markdown', 'text/x-markdown']) |
| 20 | +const MARKDOWN_EXTENSIONS = new Set(['md', 'markdown']) |
| 21 | +const VIEW_URL_RE = |
| 22 | + /\/api\/files\/view\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/gi |
| 23 | +const MAX_EMBEDDED_IMAGES = 50 |
| 24 | + |
| 25 | +function isMarkdown(originalName: string, contentType: string): boolean { |
| 26 | + if (MARKDOWN_MIME_TYPES.has(contentType)) return true |
| 27 | + const ext = originalName.split('.').pop()?.toLowerCase() ?? '' |
| 28 | + return MARKDOWN_EXTENSIONS.has(ext) |
| 29 | +} |
| 30 | + |
| 31 | +function safeFilename(name: string): string { |
| 32 | + return path |
| 33 | + .basename(name) |
| 34 | + .replace(/["\\]/g, '_') |
| 35 | + .replace(/[\r\n\t]/g, '') |
| 36 | +} |
| 37 | + |
| 38 | +function deduplicatedFilename(preferred: string, existing: Set<string>, imageId: string): string { |
| 39 | + if (!existing.has(preferred)) return preferred |
| 40 | + const ext = path.extname(preferred) |
| 41 | + const base = path.basename(preferred, ext) |
| 42 | + const short = `${base}_${imageId.slice(0, 8)}${ext}` |
| 43 | + if (!existing.has(short)) return short |
| 44 | + return `${base}_${imageId}${ext}` |
| 45 | +} |
| 46 | + |
| 47 | +export const GET = withRouteHandler( |
| 48 | + async (request: NextRequest, context: { params: Promise<{ id: string }> }) => { |
| 49 | + const parsed = await parseRequest(fileExportContract, request, context) |
| 50 | + if (!parsed.success) return parsed.response |
| 51 | + |
| 52 | + const { id } = parsed.data.params |
| 53 | + |
| 54 | + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) |
| 55 | + if (!authResult.success || !authResult.userId) { |
| 56 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 57 | + } |
| 58 | + const userId = authResult.userId |
| 59 | + |
| 60 | + const record = await getFileMetadataById(id) |
| 61 | + if (!record) { |
| 62 | + logger.warn('File not found by ID', { id }) |
| 63 | + return NextResponse.json({ error: 'Not found' }, { status: 404 }) |
| 64 | + } |
| 65 | + |
| 66 | + const hasAccess = await verifyFileAccess(record.key, userId) |
| 67 | + if (!hasAccess) { |
| 68 | + logger.warn('Unauthorized file export attempt', { id, userId }) |
| 69 | + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) |
| 70 | + } |
| 71 | + |
| 72 | + if (!isMarkdown(record.originalName, record.contentType)) { |
| 73 | + const storagePrefix = USE_BLOB_STORAGE ? 'blob' : 's3' |
| 74 | + const servePath = `/api/files/serve/${storagePrefix}/${encodeURIComponent(record.key)}` |
| 75 | + return NextResponse.redirect(new URL(servePath, request.url), { status: 302 }) |
| 76 | + } |
| 77 | + |
| 78 | + const mdBuffer = await downloadFile({ |
| 79 | + key: record.key, |
| 80 | + context: record.context as StorageContext, |
| 81 | + }) |
| 82 | + let mdContent = mdBuffer.toString('utf-8') |
| 83 | + |
| 84 | + const imageIds = [...new Set([...mdContent.matchAll(VIEW_URL_RE)].map((m) => m[1]))].slice( |
| 85 | + 0, |
| 86 | + MAX_EMBEDDED_IMAGES |
| 87 | + ) |
| 88 | + |
| 89 | + logger.info('Exporting markdown with embedded images', { id, imageCount: imageIds.length }) |
| 90 | + |
| 91 | + const fetchResults = await Promise.allSettled( |
| 92 | + imageIds.map(async (imageId) => { |
| 93 | + const imgRecord = await getFileMetadataById(imageId) |
| 94 | + if (!imgRecord) return null |
| 95 | + const imgHasAccess = await verifyFileAccess(imgRecord.key, userId) |
| 96 | + if (!imgHasAccess) return null |
| 97 | + const imgBuffer = await downloadFile({ |
| 98 | + key: imgRecord.key, |
| 99 | + context: imgRecord.context as StorageContext, |
| 100 | + }) |
| 101 | + return { imageId, originalName: imgRecord.originalName, buffer: imgBuffer } |
| 102 | + }) |
| 103 | + ) |
| 104 | + |
| 105 | + const assetMap = new Map<string, { filename: string; buffer: Buffer }>() |
| 106 | + const usedFilenames = new Set<string>() |
| 107 | + |
| 108 | + for (let i = 0; i < fetchResults.length; i++) { |
| 109 | + const result = fetchResults[i] |
| 110 | + if (result.status === 'rejected') { |
| 111 | + logger.warn('Failed to fetch asset for export', { |
| 112 | + imageId: imageIds[i], |
| 113 | + error: toError(result.reason).message, |
| 114 | + }) |
| 115 | + continue |
| 116 | + } |
| 117 | + if (!result.value) continue |
| 118 | + const { imageId, originalName, buffer } = result.value |
| 119 | + const preferred = safeFilename(originalName) |
| 120 | + const filename = deduplicatedFilename(preferred, usedFilenames, imageId) |
| 121 | + usedFilenames.add(filename) |
| 122 | + assetMap.set(imageId, { filename, buffer }) |
| 123 | + } |
| 124 | + |
| 125 | + for (const [imageId, asset] of assetMap) { |
| 126 | + const escapedId = imageId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') |
| 127 | + const replacement = `./assets/${asset.filename}` |
| 128 | + mdContent = mdContent.replace( |
| 129 | + new RegExp(`/api/files/view/${escapedId}`, 'g'), |
| 130 | + () => replacement |
| 131 | + ) |
| 132 | + } |
| 133 | + |
| 134 | + const zip = new JSZip() |
| 135 | + zip.file(safeFilename(record.originalName), mdContent) |
| 136 | + const assetsFolder = zip.folder('assets')! |
| 137 | + for (const { filename, buffer } of assetMap.values()) { |
| 138 | + assetsFolder.file(filename, buffer) |
| 139 | + } |
| 140 | + |
| 141 | + const zipBuffer = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' }) |
| 142 | + const zipName = safeFilename(`${record.originalName.replace(/\.[^.]+$/, '')}.zip`) |
| 143 | + |
| 144 | + return new NextResponse(new Uint8Array(zipBuffer), { |
| 145 | + status: 200, |
| 146 | + headers: { |
| 147 | + 'Content-Type': 'application/zip', |
| 148 | + 'Content-Disposition': `attachment; filename="${zipName}"`, |
| 149 | + 'Content-Length': String(zipBuffer.length), |
| 150 | + }, |
| 151 | + }) |
| 152 | + } |
| 153 | +) |
0 commit comments