Files
ims/app/api/admin/bulk-import/route.ts
T
adminandClaude Haiku 4.5 f1de68a305 fix: prevent RCE in bulk-import via shell injection
Use execFile instead of exec with string interpolation for unzip command.
Prevents arbitrary command execution via malicious ZIP filenames.

Changed from:
  await execAsync(`unzip -q "${uploadedFilePath}" -d "${extractDir}"`)

To:
  await execFileAsync('unzip', ['-q', uploadedFilePath, '-d', extractDir])

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-09-29 17:57:47 +08:00

99 lines
3.0 KiB
TypeScript

import { requireAdmin } from '@/lib/auth/require-admin'
import { analyzePdfsWithDeepSeek } from '@/lib/incidents/bulk-import'
import { NextRequest, NextResponse } from 'next/server'
import { mkdir, readdir, rm, writeFile } from 'fs/promises'
import path from 'path'
import { tmpdir } from 'os'
import { execFile } from 'child_process'
import { promisify } from 'util'
const execFileAsync = promisify(execFile)
export async function POST(request: NextRequest) {
const { session } = await requireAdmin()
if (!session) return new NextResponse('Unauthorized', { status: 401 })
let tempDir: string | null = null
try {
const formData = await request.formData()
const file = formData.get('file') as File
if (!file) {
return NextResponse.json(
{ error: 'No file uploaded' },
{ status: 400 }
)
}
// Save uploaded file to temp
tempDir = path.join(tmpdir(), `bulk-import-${Date.now()}`)
await mkdir(tempDir, { recursive: true })
const buffer = Buffer.from(await file.arrayBuffer())
const uploadedFilePath = path.join(tempDir, file.name)
await writeFile(uploadedFilePath, buffer)
// If .zip, extract; otherwise treat as folder
const extractDir = tempDir
if (file.name.endsWith('.zip')) {
await execFileAsync('unzip', ['-q', uploadedFilePath, '-d', extractDir])
}
// Scan extracted folders (skip __MACOSX)
const entries = await readdir(extractDir, { withFileTypes: true })
const folders = entries.filter((e) => e.isDirectory() && e.name !== '__MACOSX')
const results = []
for (const folder of folders) {
const folderPath = path.join(extractDir, folder.name)
const files = await readdir(folderPath)
// Find PDFs
const pdfFiles = files.filter((f) => f.endsWith('.pdf'))
const pdfTexts: string[] = []
// TODO: PDF text extraction requires pdf-parse dependency fix
for (const pdfFile of pdfFiles) {
pdfTexts.push(`[PDF: ${pdfFile}]`)
}
// Analyze with DeepSeek
const metadata = await analyzePdfsWithDeepSeek(pdfTexts)
results.push({
id: Buffer.from(folder.name).toString('base64'),
folder_name: folder.name,
extracted: metadata,
files: {
pdfs: pdfFiles.length,
images: files.filter((f) => /\.(jpg|jpeg|png|gif)$/i.test(f)).length,
videos: files.filter((f) => /\.(mp4|mov|webm)$/i.test(f)).length
},
metadata_confidence: 0.85
})
}
return NextResponse.json({
status: 'success',
folders: results
})
} catch (error) {
console.error('Upload failed:', error)
return NextResponse.json(
{ error: 'Upload processing failed', details: String(error) },
{ status: 500 }
)
} finally {
// Clean up temp directory
if (tempDir) {
try {
await rm(tempDir, { recursive: true, force: true })
} catch (error) {
console.error('Failed to clean up temp directory:', error)
}
}
}
}