v1.10.88 품질·보안 개선과 미디어 카탈로그 database 전환을 반영한다.
세션·로그인 제한, ZIP/업로드 스트리밍, CSP 최소 강제와 Report-Only, Playwright 격리 검증을 추가하고 미디어 목록을 reconcile 후 database 모드로 고정한다. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,10 +1,9 @@
|
||||
import { mkdir, stat, writeFile } from 'node:fs/promises'
|
||||
import { link, mkdir, mkdtemp, rm, unlink } from 'node:fs/promises'
|
||||
import { extname, join } from 'node:path'
|
||||
import { createError, readMultipartFormData } from 'h3'
|
||||
import { createError } from 'h3'
|
||||
import {
|
||||
buildDefaultUploadSizeLimits,
|
||||
formatUploadSizeLimit,
|
||||
getUploadFilesTotalSize,
|
||||
getMaxUploadBytesForKind,
|
||||
getUploadKind,
|
||||
getUploadKindLabel,
|
||||
@@ -14,6 +13,9 @@ import {
|
||||
import { requireAdminSession } from '../../../utils/admin-auth'
|
||||
import { getRuntimeEnvNumber } from '../../../utils/runtime-env.js'
|
||||
import { upsertMediaMetadataCategory } from '../../../utils/media-library'
|
||||
import { deleteMediaCatalogEntries } from '../../../repositories/media-catalog-repository'
|
||||
import { saveMultipartFilesToDisk } from '../../../utils/multipart-file-upload'
|
||||
import { getConfiguredUploadRoot } from '../../../utils/upload-root'
|
||||
import { getSiteSettings } from '../../../repositories/content-repository'
|
||||
|
||||
const allowedUploadTypes = new Map([
|
||||
@@ -72,7 +74,7 @@ const sanitizePathPart = (value) => String(value || '')
|
||||
|
||||
/**
|
||||
* 파일 확장자 조회
|
||||
* @param {Object} file - multipart 파일 파트
|
||||
* @param {{ filename: string, type: string }} file - multipart 파일 정보
|
||||
* @returns {string} 확장자
|
||||
*/
|
||||
const getUploadExtension = (file) => {
|
||||
@@ -87,20 +89,21 @@ const getUploadExtension = (file) => {
|
||||
|
||||
/**
|
||||
* 업로드 허용 파일인지 확인한다.
|
||||
* @param {Object} file - multipart 파일 파트
|
||||
* @param {{ filename: string, type: string }} file - multipart 파일 정보
|
||||
* @returns {boolean} 허용 여부
|
||||
*/
|
||||
const isAllowedUploadFile = (file) => allowedUploadTypes.has(file.type)
|
||||
|| allowedUploadExtensions.has(extname(file.filename || '').toLowerCase())
|
||||
|
||||
/**
|
||||
* 디렉터리 안에서 비어 있는 저장 파일명을 고른다. 동일 이름이 있으면 `이름-2`, `이름-3` 식으로 넘버링한다.
|
||||
* 임시 파일을 충돌하지 않는 최종 파일명으로 원자적으로 이동한다.
|
||||
* @param {string} directoryPath - 저장 디렉터리 절대 경로
|
||||
* @param {string} stem - 확장자 제외 파일명
|
||||
* @param {string} extension - 확장자(점 포함, 예: `.png`)
|
||||
* @param {string} sourcePath - 임시 파일 절대 경로
|
||||
* @returns {Promise<{ fileName: string, filePath: string }>} 선택된 파일명과 절대 경로
|
||||
*/
|
||||
const pickUniqueDiskFileName = async (directoryPath, stem, extension) => {
|
||||
const moveToUniqueDiskFileName = async (directoryPath, stem, extension, sourcePath) => {
|
||||
let suffix = 1
|
||||
|
||||
while (suffix < 10000) {
|
||||
@@ -108,13 +111,17 @@ const pickUniqueDiskFileName = async (directoryPath, stem, extension) => {
|
||||
const filePath = join(directoryPath, fileName)
|
||||
|
||||
try {
|
||||
await stat(filePath)
|
||||
suffix += 1
|
||||
} catch {
|
||||
await link(sourcePath, filePath)
|
||||
await unlink(sourcePath)
|
||||
return {
|
||||
fileName,
|
||||
filePath
|
||||
}
|
||||
} catch (error) {
|
||||
if (error?.code !== 'EEXIST') {
|
||||
throw error
|
||||
}
|
||||
suffix += 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,79 +149,120 @@ export default defineEventHandler(async (event) => {
|
||||
const settings = await getSiteSettings()
|
||||
const uploadMaxFileCount = normalizeUploadMaxFileCount(settings.uploadMaxFileCount)
|
||||
const uploadMaxTotalSize = normalizeUploadMaxTotalSize(settings.uploadMaxTotalSize)
|
||||
const formData = await readMultipartFormData(event)
|
||||
const files = (formData || []).filter((part) => part.name === 'files' && part.filename)
|
||||
|
||||
if (!files.length) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '업로드할 파일이 없습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
if (files.length > uploadMaxFileCount) {
|
||||
throw createError({
|
||||
statusCode: 413,
|
||||
message: `한 번에 업로드할 수 있는 파일은 최대 ${uploadMaxFileCount}개입니다.`
|
||||
})
|
||||
}
|
||||
|
||||
const uploadTotalSize = getUploadFilesTotalSize(files)
|
||||
|
||||
if (uploadTotalSize > uploadMaxTotalSize) {
|
||||
throw createError({
|
||||
statusCode: 413,
|
||||
message: `한 번에 업로드 가능한 전체 용량을 초과했습니다. (최대 ${formatUploadSizeLimit(uploadMaxTotalSize)})`
|
||||
})
|
||||
}
|
||||
|
||||
const now = new Date()
|
||||
const year = String(now.getFullYear())
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0')
|
||||
const uploadBaseUrl = String(config.uploadDir || '/uploads').replace(/\/+$/g, '') || '/uploads'
|
||||
const publicBasePath = uploadBaseUrl.replace(/^\/+/, '')
|
||||
const directoryPath = join(process.cwd(), 'public', publicBasePath, 'posts', year, month)
|
||||
const directoryPath = join(getConfiguredUploadRoot(publicBasePath), 'posts', year, month)
|
||||
|
||||
await mkdir(directoryPath, { recursive: true })
|
||||
const tempDirectoryPath = await mkdtemp(join(directoryPath, '.upload-'))
|
||||
const movedFilePaths = []
|
||||
const catalogRecordedUrls = []
|
||||
|
||||
const uploadedFiles = []
|
||||
try {
|
||||
const streamedFiles = await saveMultipartFilesToDisk(event, {
|
||||
fieldName: 'files',
|
||||
maxFiles: uploadMaxFileCount,
|
||||
maxTotalBytes: uploadMaxTotalSize,
|
||||
createFileTarget: async (file, index) => {
|
||||
const uploadFile = {
|
||||
filename: file.filename,
|
||||
type: file.mimeType
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
if (!isAllowedUploadFile(file)) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '지원하지 않는 파일 형식입니다.'
|
||||
if (!isAllowedUploadFile(uploadFile)) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '지원하지 않는 파일 형식입니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const uploadKind = getUploadKind(uploadFile.type, uploadFile.filename)
|
||||
const maxFileSize = getMaxUploadBytesForKind(uploadKind, uploadSizeLimits)
|
||||
const originalStem = sanitizePathPart(uploadFile.filename.replace(/\.[^.]+$/g, '')) || 'file'
|
||||
const extension = getUploadExtension(uploadFile)
|
||||
|
||||
return {
|
||||
filePath: join(tempDirectoryPath, `${index}${extension}`),
|
||||
maxBytes: maxFileSize,
|
||||
metadata: {
|
||||
originalStem,
|
||||
extension,
|
||||
uploadKind
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const uploadedFiles = []
|
||||
|
||||
for (const file of streamedFiles) {
|
||||
const { fileName, filePath } = await moveToUniqueDiskFileName(
|
||||
directoryPath,
|
||||
file.metadata.originalStem,
|
||||
file.metadata.extension,
|
||||
file.filePath
|
||||
)
|
||||
movedFilePaths.push(filePath)
|
||||
|
||||
const publicUrl = `${uploadBaseUrl}/posts/${year}/${month}/${fileName}`
|
||||
await upsertMediaMetadataCategory(publicUrl, '미분류')
|
||||
catalogRecordedUrls.push(publicUrl)
|
||||
|
||||
uploadedFiles.push({
|
||||
url: publicUrl,
|
||||
name: fileName,
|
||||
size: file.size
|
||||
})
|
||||
}
|
||||
|
||||
const uploadKind = getUploadKind(file.type, file.filename)
|
||||
const maxFileSize = getMaxUploadBytesForKind(uploadKind, uploadSizeLimits)
|
||||
return {
|
||||
files: uploadedFiles
|
||||
}
|
||||
} catch (error) {
|
||||
await Promise.all(movedFilePaths.map((filePath) => unlink(filePath).catch(() => {})))
|
||||
await deleteMediaCatalogEntries(catalogRecordedUrls).catch(() => {
|
||||
console.warn('[media-catalog] 업로드 실패 정리 중 카탈로그 갱신 실패')
|
||||
})
|
||||
|
||||
if (file.data.length > maxFileSize) {
|
||||
if (error?.statusCode) {
|
||||
throw error
|
||||
}
|
||||
if (error?.code === 'MULTIPART_TOO_MANY_FILES') {
|
||||
throw createError({
|
||||
statusCode: 413,
|
||||
message: `${getUploadKindLabel(uploadKind)} 업로드 가능 크기를 초과했습니다. (최대 ${formatUploadSizeLimit(maxFileSize)})`
|
||||
message: `한 번에 업로드할 수 있는 파일은 최대 ${uploadMaxFileCount}개입니다.`
|
||||
})
|
||||
}
|
||||
if (error?.code === 'MULTIPART_TOTAL_SIZE_TOO_LARGE') {
|
||||
throw createError({
|
||||
statusCode: 413,
|
||||
message: `한 번에 업로드 가능한 전체 용량을 초과했습니다. (최대 ${formatUploadSizeLimit(uploadMaxTotalSize)})`
|
||||
})
|
||||
}
|
||||
if (error?.code === 'MULTIPART_FILE_TOO_LARGE') {
|
||||
throw createError({
|
||||
statusCode: 413,
|
||||
message: `${getUploadKindLabel(error.metadata?.uploadKind)} 업로드 가능 크기를 초과했습니다. (최대 ${formatUploadSizeLimit(error.maxBytes)})`
|
||||
})
|
||||
}
|
||||
if (['MULTIPART_FILE_NOT_FOUND', 'INVALID_MULTIPART_REQUEST', 'MULTIPART_TOO_MANY_PARTS'].includes(error?.code)) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '업로드할 파일이 없거나 요청 형식이 올바르지 않습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const originalStem = sanitizePathPart(file.filename.replace(/\.[^.]+$/g, '')) || 'image'
|
||||
const extension = getUploadExtension(file)
|
||||
const { fileName, filePath } = await pickUniqueDiskFileName(directoryPath, originalStem, extension)
|
||||
|
||||
await writeFile(filePath, file.data)
|
||||
|
||||
const publicUrl = `${uploadBaseUrl}/posts/${year}/${month}/${fileName}`
|
||||
|
||||
await upsertMediaMetadataCategory(publicUrl, '미분류')
|
||||
|
||||
uploadedFiles.push({
|
||||
url: publicUrl,
|
||||
name: fileName,
|
||||
size: file.data.length
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: '파일을 업로드하지 못했습니다.'
|
||||
})
|
||||
} finally {
|
||||
await rm(tempDirectoryPath, {
|
||||
recursive: true,
|
||||
force: true
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
files: uploadedFiles
|
||||
}
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user