From 7c8cb213d949aec4cd83f7bb03efe2894760b5a1 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Thu, 26 Nov 2026 16:46:55 +0800 Subject: [PATCH] fix(upload): separate display names from storage paths --- .../brand-knowledge/[id]/file/route.test.ts | 3 +- .../[id]/preview/route.test.ts | 5 +- .../brand-knowledge/engagement-routes.test.ts | 4 +- .../brand-knowledge/route.test.ts | 27 ++++- .../brand-knowledge/route.ts | 5 +- .../materials/upload/complete/route.test.ts | 17 ++- app/api/materials/upload/complete/route.ts | 44 ++------ .../upload/file-name.integration.test.ts | 102 ++++++++++++++++++ app/api/materials/upload/init/route.test.ts | 15 ++- app/api/materials/upload/init/route.ts | 25 ++--- .../upload/route.idempotency.test.ts | 1 + app/api/materials/upload/route.ts | 5 +- .../upload/ProductPackageUploader.test.tsx | 21 ++++ components/upload/ProductPackageUploader.tsx | 21 +++- .../materials-upload-task-other-route.test.ts | 1 + lib/__tests__/path-security.test.ts | 18 ++++ .../product-package-completion.test.ts | 12 ++- .../task-detail-preview-storage.test.ts | 11 ++ .../upload-sessions-security.test.ts | 8 +- lib/path-security.ts | 52 +-------- lib/product-package-completion.ts | 18 ++-- lib/task-detail-change-staging.ts | 11 +- lib/task-detail-preview-storage.ts | 4 +- lib/temp-cleanup.ts | 48 ++++----- lib/upload-file-name.ts | 62 +++++++++++ lib/upload-paths.ts | 31 ++++++ lib/upload-sessions.ts | 59 ++++------ 27 files changed, 423 insertions(+), 207 deletions(-) create mode 100644 app/api/materials/upload/file-name.integration.test.ts create mode 100644 lib/upload-file-name.ts diff --git a/app/api/department-dashboard/brand-knowledge/[id]/file/route.test.ts b/app/api/department-dashboard/brand-knowledge/[id]/file/route.test.ts index b0793808..a53eab62 100644 --- a/app/api/department-dashboard/brand-knowledge/[id]/file/route.test.ts +++ b/app/api/department-dashboard/brand-knowledge/[id]/file/route.test.ts @@ -2,6 +2,7 @@ import { getServerSession } from 'next-auth' import { createReadStream } from 'fs' import { stat } from 'fs/promises' import { Readable } from 'stream' +import path from 'path' import { prisma } from '@/lib/prisma' jest.mock('next-auth', () => ({ getServerSession: jest.fn() })) @@ -80,7 +81,7 @@ describe('brand knowledge file route', () => { const response = await GET(new Request('http://localhost/file'), { params: { id: 'knowledge-1' } }) expect(response.status).toBe(200) - expect(createReadStream).toHaveBeenCalledWith('/uploads/brand-knowledge/guide.pdf') + expect(createReadStream).toHaveBeenCalledWith(path.resolve('/uploads/brand-knowledge/guide.pdf')) expect(prisma.brandKnowledge.updateMany).not.toHaveBeenCalled() expect(await response.text()).toBe('test') expect(prisma.brandKnowledge.updateMany).toHaveBeenCalledWith({ diff --git a/app/api/department-dashboard/brand-knowledge/[id]/preview/route.test.ts b/app/api/department-dashboard/brand-knowledge/[id]/preview/route.test.ts index 37918420..4be24c2d 100644 --- a/app/api/department-dashboard/brand-knowledge/[id]/preview/route.test.ts +++ b/app/api/department-dashboard/brand-knowledge/[id]/preview/route.test.ts @@ -1,5 +1,6 @@ import { getServerSession } from 'next-auth' import { readFile, stat } from 'fs/promises' +import path from 'path' import { prisma } from '@/lib/prisma' jest.mock('next-auth', () => ({ getServerSession: jest.fn() })) @@ -64,7 +65,7 @@ describe('brand knowledge preview route', () => { ) expect(response.status).toBe(200) - expect(readFile).toHaveBeenCalledWith('/uploads/brand-knowledge/part-002.webp') + expect(readFile).toHaveBeenCalledWith(path.resolve('/uploads/brand-knowledge/part-002.webp')) expect(response.headers.get('content-type')).toBe('image/webp') await expect(response.text()).resolves.toBe('slice-02') }) @@ -103,7 +104,7 @@ describe('brand knowledge preview route', () => { const response = await GET(new Request('http://localhost/preview'), { params: { id: 'knowledge-1' } }) expect(response.status).toBe(200) - expect(readFile).toHaveBeenCalledWith('/uploads/brand-knowledge/legacy.png') + expect(readFile).toHaveBeenCalledWith(path.resolve('/uploads/brand-knowledge/legacy.png')) expect(response.headers.get('content-type')).toBe('image/png') }) }) diff --git a/app/api/department-dashboard/brand-knowledge/engagement-routes.test.ts b/app/api/department-dashboard/brand-knowledge/engagement-routes.test.ts index ad25f1e8..7255ab1d 100644 --- a/app/api/department-dashboard/brand-knowledge/engagement-routes.test.ts +++ b/app/api/department-dashboard/brand-knowledge/engagement-routes.test.ts @@ -1,3 +1,5 @@ +/** @jest-environment node */ + import { getServerSession } from 'next-auth' import { prisma } from '@/lib/prisma' import { assertBrandCenterDashboardAccess } from '@/lib/brand-center-dashboard-access' @@ -14,7 +16,7 @@ jest.mock('@/lib/brand-center-dashboard-access', () => ({ jest.mock('@/lib/department-permission', () => ({ isSuperAdmin: jest.fn(async () => false) })) jest.mock('@/lib/prisma', () => ({ prisma: { - brandKnowledge: { findMany: jest.fn(), findFirst: jest.fn(), updateMany: jest.fn() }, + brandKnowledge: { count: jest.fn().mockResolvedValue(1), findMany: jest.fn(), findFirst: jest.fn(), updateMany: jest.fn() }, brandKnowledgeLike: { upsert: jest.fn(), deleteMany: jest.fn(), count: jest.fn() }, brandKnowledgeFavorite: { upsert: jest.fn(), deleteMany: jest.fn() }, }, diff --git a/app/api/department-dashboard/brand-knowledge/route.test.ts b/app/api/department-dashboard/brand-knowledge/route.test.ts index fa5ffb46..20c98a6b 100644 --- a/app/api/department-dashboard/brand-knowledge/route.test.ts +++ b/app/api/department-dashboard/brand-knowledge/route.test.ts @@ -1,5 +1,6 @@ import { getServerSession } from 'next-auth' import { link, rename, unlink, writeFile } from 'fs/promises' +import path from 'path' import { prisma } from '@/lib/prisma' import { prepareBrandKnowledgePreview } from '@/lib/brand-knowledge-preview' import { validateBrandKnowledgeUploadedPreviewSlices } from '@/lib/brand-knowledge-preview' @@ -78,7 +79,7 @@ const previewFile = { arrayBuffer: async () => Uint8Array.from([1, 2, 3, 4, 5, 6, 7, 8]).buffer, } -function uploadRequest() { +function uploadRequest(originalFileName = 'knowledge.pdf') { const values = new Map([ ['title', '长图规范'], ['knowledgeType', '主图模板'], @@ -86,7 +87,7 @@ function uploadRequest() { ['productCategoryName', '衣柜'], ['uploadId', 'upload-1'], ['existingFilePath', '/uploads/temp/upload-1/merged-knowledge.pdf'], - ['originalFileName', 'knowledge.pdf'], + ['originalFileName', originalFileName], ['fileSize', '4'], ['previewImage', previewFile], ]) @@ -234,6 +235,24 @@ describe('brand knowledge upload route', () => { })) }) + test('stores the full display name for a source with a short storage path', async () => { + const fileName = `${'组合款知识'.repeat(22)}...pdf` + jest.mocked(resolveOwnedMergedUpload).mockResolvedValueOnce({ + uploadId: 'upload-1', + filePath: '/uploads/temp/upload-1/merged-file.pdf', + session: { + fileName, fileSize: 4, totalChunks: 1, chunks: new Map(), + createdAt: Date.now(), userId: 'user-1', uploadPurpose: 'brand-knowledge', + }, + }) + const response = await POST(uploadRequest(fileName)) + + expect(response.status).toBe(201) + expect(prisma.brandKnowledge.create).toHaveBeenCalledWith(expect.objectContaining({ + data: expect.objectContaining({ fileName, filePath: 'uploads/brand-knowledge/source-upload-1.pdf' }), + })) + }) + test('stores ordered WebP slices and keeps the first slice as the card preview', async () => { const response = await POST(uploadRequest()) const call = (prisma.brandKnowledge.create as jest.Mock).mock.calls[0][0] @@ -266,8 +285,8 @@ describe('brand knowledge upload route', () => { expect(response.status).toBe(500) expect(unlink).toHaveBeenCalledWith('/uploads/brand-knowledge/source-upload-1.pdf') - expect(unlink).toHaveBeenCalledWith('/uploads/brand-knowledge/upload-1-preview-part-001.webp') - expect(unlink).toHaveBeenCalledWith('/uploads/brand-knowledge/upload-1-preview-part-002.webp') + expect(unlink).toHaveBeenCalledWith(path.join('/uploads', 'brand-knowledge', 'upload-1-preview-part-001.webp')) + expect(unlink).toHaveBeenCalledWith(path.join('/uploads', 'brand-knowledge', 'upload-1-preview-part-002.webp')) expect(cleanupConsumedUploadSession).not.toHaveBeenCalled() expect(errorSpy).toHaveBeenCalled() expect(releaseRequestSlot).toHaveBeenCalledTimes(1) diff --git a/app/api/department-dashboard/brand-knowledge/route.ts b/app/api/department-dashboard/brand-knowledge/route.ts index a3212eda..35d4291a 100644 --- a/app/api/department-dashboard/brand-knowledge/route.ts +++ b/app/api/department-dashboard/brand-knowledge/route.ts @@ -10,6 +10,7 @@ import { prisma } from '@/lib/prisma' import { isSuperAdmin } from '@/lib/department-permission' import { getUploadRootDir } from '@/lib/upload-paths' import { ensureSafeDirectoryWithinRoot, isPathFreeOfSymbolicLinks, normalizeSafeFileName, resolveStrictChildPath } from '@/lib/path-security' +import { normalizeUploadFileName } from '@/lib/upload-file-name' import { assertBoundedMultipartHeaders, assertMultipartFiles } from '@/lib/multipart-request-guard' import { boundedMultipartRequestLimiter, getBoundedMultipartFailure } from '@/lib/multipart-route-limits' import { prepareBrandKnowledgePreview, validateBrandKnowledgeUploadedPreviewSlices } from '@/lib/brand-knowledge-preview' @@ -286,7 +287,7 @@ export async function POST(request: Request) { const productCategoryName = normalizeText(formData.get('productCategoryName'), 80) uploadId = normalizeText(formData.get('uploadId'), 128) const existingFilePath = normalizeText(formData.get('existingFilePath'), 4096) - const safeOriginalName = normalizeSafeFileName(normalizeText(formData.get('originalFileName'), 255)) + const safeOriginalName = normalizeUploadFileName(formData.get('originalFileName')) const declaredFileSize = Number(normalizeText(formData.get('fileSize'), 20)) if (!title) return NextResponse.json({ success: false, error: '请填写知识标题' }, { status: 400, headers: PRIVATE_HEADERS }) if (!KNOWLEDGE_TYPES.has(knowledgeType)) return NextResponse.json({ success: false, error: '知识类型不合法' }, { status: 400, headers: PRIVATE_HEADERS }) @@ -355,7 +356,7 @@ export async function POST(request: Request) { ) } if ( - normalizeSafeFileName(ownedMergedUpload.session.fileName) !== safeOriginalName + normalizeUploadFileName(ownedMergedUpload.session.fileName) !== safeOriginalName || ownedMergedUpload.session.fileSize !== declaredFileSize || ownedMergedUpload.session.uploadPurpose !== 'brand-knowledge' ) { diff --git a/app/api/materials/upload/complete/route.test.ts b/app/api/materials/upload/complete/route.test.ts index 2bc61d35..10796fb5 100644 --- a/app/api/materials/upload/complete/route.test.ts +++ b/app/api/materials/upload/complete/route.test.ts @@ -11,7 +11,7 @@ import { mergeUploadChunksAtomically, } from '@/lib/material-upload-merge' import { MaterialUploadStorageReservationManager } from '@/lib/material-upload-storage-reservation' -import { cancelUploadSessionSeal } from '@/lib/material-upload-session-seal' +import { beginUploadCompletionSeal, cancelUploadSessionSeal, completeUploadCompletionSeal } from '@/lib/material-upload-session-seal' import { deleteUploadSession, getOwnedUploadSession, @@ -87,6 +87,21 @@ describe('material upload complete safety', () => { expect(await readFile(secondBody.existingFilePath)).toEqual(fileBytes) }) + test('发布前已经完成的会话继续返回原合并路径', async () => { + const tempDir = path.join(uploadRoot, 'temp', uploadId) + const legacyPath = path.join(tempDir, `merged-${fileName}`) + await writeFile(legacyPath, fileBytes) + const seal = await beginUploadCompletionSeal(uploadId) + if (seal.state !== 'sealing') throw new Error('预期会话可封存') + await completeUploadCompletionSeal(seal.handle) + await rm(path.join(tempDir, 'chunk-0')) + await rm(path.join(tempDir, 'chunk-1')) + + const response = await POST(completeRequest()) + expect(response.status).toBe(200) + await expect(response.json()).resolves.toMatchObject({ existingFilePath: legacyPath, fileName }) + }) + test('cancelled 终态让 complete 结构化 fail-closed', async () => { await cancelUploadSessionSeal(uploadId) diff --git a/app/api/materials/upload/complete/route.ts b/app/api/materials/upload/complete/route.ts index 7881edec..4fe7ed20 100644 --- a/app/api/materials/upload/complete/route.ts +++ b/app/api/materials/upload/complete/route.ts @@ -24,8 +24,9 @@ import { getOwnedUploadSession, isSafeUploadId, } from '@/lib/upload-sessions' -import { getUploadRootDir } from '@/lib/upload-paths' -import { normalizeSafeFileName, resolveStrictChildPath } from '@/lib/path-security' +import { getUploadRootDir, inspectUploadOutput } from '@/lib/upload-paths' +import { resolveStrictChildPath } from '@/lib/path-security' +import { normalizeUploadFileName } from '@/lib/upload-file-name' import { acquireMaterialUploadStorageLock, type MaterialUploadStorageLockRelease, @@ -68,13 +69,10 @@ export async function POST(req: NextRequest) { return NextResponse.json({ error: '上传会话不存在、已过期或无权访问' }, { status: 404 }) } - const mergedFileName = normalizeSafeFileName(uploadSession.fileName) + const mergedFileName = normalizeUploadFileName(uploadSession.fileName) const uploadRoot = getUploadRootDir() const tempDir = resolveStrictChildPath(uploadRoot, 'temp', uploadId) - const mergedPath = mergedFileName - ? resolveStrictChildPath(tempDir || '', `merged-${mergedFileName}`) - : null - if (!tempDir || !mergedFileName || !mergedPath) { + if (!tempDir || !mergedFileName) { return NextResponse.json({ error: '上传会话路径无效' }, { status: 400 }) } @@ -117,11 +115,10 @@ export async function POST(req: NextRequest) { // 第一次请求可能已经成功,只是响应在公网链路中丢失。完整且大小一致的 // merged 文件是同一会话的确定结果,重复调用直接返回同一路径。 - const existingMerged = await inspectExistingMergedFile( - mergedPath, - uploadSession.fileSize, + const { outputPath: mergedPath, existing } = await inspectUploadOutput( + tempDir, 'merged-file', 'merged-', mergedFileName, ) - if (existingMerged === 'valid') { + if (existing?.stats.isFile() && existing.stats.size === uploadSession.fileSize) { if (completionSealHandle) { await completeUploadCompletionSeal(completionSealHandle) completionSealFinalized = true @@ -129,7 +126,7 @@ export async function POST(req: NextRequest) { await cleanupCompletedUpload(uploadId, chunks.map((chunk) => chunk.path)) return createCompletedResponse({ uploadId, - mergedPath, + mergedPath: existing.filePath, mergedFileName, fileSize: uploadSession.fileSize, }) @@ -141,8 +138,8 @@ export async function POST(req: NextRequest) { 'UPLOAD_COMPLETED_FILE_INVALID', ) } - if (existingMerged === 'invalid') { - await rm(mergedPath, { force: true }) + if (existing) { + await rm(existing.filePath, { force: true }) } for (let index = 0; index < chunks.length; index += 1) { @@ -222,25 +219,6 @@ export async function POST(req: NextRequest) { } } -async function inspectExistingMergedFile( - mergedPath: string, - expectedBytes: number, -): Promise<'missing' | 'valid' | 'invalid'> { - try { - const stats = await lstat(mergedPath) - return !stats.isSymbolicLink() - && stats.isFile() - && stats.size === expectedBytes - ? 'valid' - : 'invalid' - } catch (error: any) { - if (error?.code === 'ENOENT') { - return 'missing' - } - throw error - } -} - async function cleanupCompletedUpload(uploadId: string, chunkFiles: string[]): Promise { for (const chunkFile of chunkFiles) { try { diff --git a/app/api/materials/upload/file-name.integration.test.ts b/app/api/materials/upload/file-name.integration.test.ts new file mode 100644 index 00000000..61af7eeb --- /dev/null +++ b/app/api/materials/upload/file-name.integration.test.ts @@ -0,0 +1,102 @@ +/** @jest-environment node */ + +import { mkdtemp, readFile, rm } from 'fs/promises' +import os from 'os' +import path from 'path' +import { getServerSession } from 'next-auth' +import { NextRequest } from 'next/server' + +import { POST as init } from './init/route' +import { POST as chunk } from './chunk/route' +import { POST as complete } from './complete/route' +import { cleanupConsumedUploadSession } from '@/lib/temp-cleanup' +import { getOwnedUploadSession, getUploadedFile, resolveOwnedMergedUpload } from '@/lib/upload-sessions' + +jest.mock('next-auth', () => ({ getServerSession: jest.fn() })) +jest.mock('@/lib/auth', () => ({ authOptions: {} })) + +function jsonRequest(endpoint: string, body: object) { + return new NextRequest(`http://localhost/api/materials/upload/${endpoint}`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(body), + }) +} + +describe('分片上传展示名与实际文件路径', () => { + const content = Buffer.from('source-content') + const owner = 'user-1' + let uploadRoot: string + const previousUploadDir = process.env.UPLOAD_DIR + + beforeEach(async () => { + uploadRoot = await mkdtemp(path.join(os.tmpdir(), 'upload-file-name-')) + process.env.UPLOAD_DIR = uploadRoot + jest.mocked(getServerSession).mockResolvedValue({ user: { id: owner } }) + }) + + afterEach(async () => { + if (previousUploadDir === undefined) delete process.env.UPLOAD_DIR + else process.env.UPLOAD_DIR = previousUploadDir + await rm(uploadRoot, { recursive: true, force: true }) + }) + + async function upload(fileName: string) { + const response = await init(jsonRequest('init', { + fileName, fileSize: content.length, totalChunks: 1, + })) + const body = await response.json() + expect(body).toEqual({ uploadId: expect.any(String) }) + expect(response.status).toBe(200) + + const chunkResponse = await chunk(new NextRequest('http://localhost/api/materials/upload/chunk', { + method: 'POST', + headers: { + 'content-type': 'application/octet-stream', + 'content-length': String(content.length), + 'x-upload-id': body.uploadId, + 'x-chunk-index': '0', + 'x-chunk-size': String(content.length), + 'x-file-name': encodeURIComponent(fileName), + }, + body: content, + })) + expect(chunkResponse.status).toBe(200) + return body.uploadId as string + } + + test.each([ + `ZH-GBSFY-${'SJ045004N1410V01-1-'.repeat(18)}组合款...psd`, + `${'文'.repeat(254)}ab.psb`, + 'a..b.jpg', + ])('init、分片、合并与重试完整保留名称 %s', async (fileName) => { + const uploadId = await upload(fileName) + const first = await complete(jsonRequest('complete', { uploadId })) + const firstBody = await first.json() + expect(firstBody).toMatchObject({ fileName, fileSize: content.length, uploadId }) + expect(first.status).toBe(200) + const mergedPath = firstBody.existingFilePath + expect(Buffer.byteLength(path.basename(mergedPath))).toBeLessThanOrEqual(200) + expect(path.extname(mergedPath)).toBe(path.extname(fileName)) + await expect(readFile(mergedPath)).resolves.toEqual(content) + + const retry = await complete(jsonRequest('complete', { uploadId })) + expect(retry.status).toBe(200) + await expect(retry.json()).resolves.toEqual(firstBody) + await expect(resolveOwnedMergedUpload({ existingFilePath: mergedPath, userId: owner, uploadId })) + .resolves.toMatchObject({ session: { fileName } }) + }) + + test('产品包组装后按会话名清理长中文文件', async () => { + const fileName = `${'组合源文件'.repeat(30)}...psd` + const uploadId = await upload(fileName) + + await expect(getOwnedUploadSession(uploadId, owner)).resolves.toMatchObject({ fileName }) + const assembledPath = await getUploadedFile(uploadId) + expect(assembledPath).toBe(path.join(uploadRoot, 'assembled', `${uploadId}.psd`)) + await expect(readFile(assembledPath!)).resolves.toEqual(content) + await expect(getUploadedFile(uploadId)).resolves.toBe(assembledPath) + await cleanupConsumedUploadSession(uploadId) + await expect(readFile(assembledPath!)).rejects.toMatchObject({ code: 'ENOENT' }) + }) +}) diff --git a/app/api/materials/upload/init/route.test.ts b/app/api/materials/upload/init/route.test.ts index ccbdf0d3..2a5ad060 100644 --- a/app/api/materials/upload/init/route.test.ts +++ b/app/api/materials/upload/init/route.test.ts @@ -4,6 +4,7 @@ import { POST } from '@/app/api/materials/upload/init/route' import { getServerSession } from 'next-auth' import { saveUploadSession } from '@/lib/upload-sessions' import { ensureSafeDirectoryWithinRoot } from '@/lib/path-security' +import { MAX_UPLOAD_FILE_NAME_BYTES } from '@/lib/upload-file-name' import { rm, statfs, writeFile } from 'fs/promises' jest.mock('next-auth', () => ({ @@ -228,21 +229,27 @@ describe('/api/materials/upload/init', () => { })) expect(response.status).toBe(400) - await expect(response.json()).resolves.toEqual({ - error: '文件名包含不安全的路径或字符', + await expect(response.json()).resolves.toMatchObject({ + code: 'FILE_NAME_INVALID', + error: `文件名包含不支持的路径或字符。请修改「${JSON.stringify(fileName).slice(1, -1)}」后重新选择`, }) expect(ensureSafeDirectoryWithinRoot).not.toHaveBeenCalled() expect(saveUploadSession).not.toHaveBeenCalled() }) - test('拒绝超过文件系统叶子名称上限的文件名', async () => { + test('文件名超出展示名上限时提示具体文件及长度限制', async () => { + const fileName = `组合款-${'文'.repeat(MAX_UPLOAD_FILE_NAME_BYTES / 3)}-源文件.psd` const response = await POST(createRequest({ - fileName: `${'文'.repeat(90)}.psd`, + fileName, fileSize: 1024, totalChunks: 1, })) expect(response.status).toBe(400) + await expect(response.json()).resolves.toMatchObject({ + code: 'FILE_NAME_TOO_LONG', + error: expect.stringMatching(/^文件名过长.*请缩短「组合款-.*….*-源文件\.psd」/), + }) expect(saveUploadSession).not.toHaveBeenCalled() }) }) diff --git a/app/api/materials/upload/init/route.ts b/app/api/materials/upload/init/route.ts index 4e45f967..d5dd2d12 100644 --- a/app/api/materials/upload/init/route.ts +++ b/app/api/materials/upload/init/route.ts @@ -2,10 +2,8 @@ import { NextRequest, NextResponse } from 'next/server' import { getAuthenticatedUploadUserId } from '@/lib/upload-auth' import { saveUploadSession } from '@/lib/upload-sessions' import { getUploadRootDir } from '@/lib/upload-paths' -import { - ensureSafeDirectoryWithinRoot, - normalizeSafeFileName, -} from '@/lib/path-security' +import { ensureSafeDirectoryWithinRoot } from '@/lib/path-security' +import { validateUploadFileName } from '@/lib/upload-file-name' import { randomBytes } from 'crypto' import { rm, statfs, writeFile } from 'fs/promises' import path from 'path' @@ -38,20 +36,19 @@ export async function POST(req: NextRequest) { ) } - const rawFileName = typeof body?.fileName === 'string' ? body.fileName : '' - const normalizedFileName = normalizeSafeFileName(rawFileName) + const name = validateUploadFileName(body?.fileName) + if (name.fileName === null) { + return NextResponse.json( + { error: name.error, ...(name.code !== 'FILE_NAME_EMPTY' ? { code: name.code } : {}) }, + { status: 400 }, + ) + } const normalizedFileSize = Number(body?.fileSize) const normalizedTotalChunks = Number(body?.totalChunks) const uploadPurpose = typeof body?.uploadPurpose === 'string' ? body.uploadPurpose.trim() : '' - if (!rawFileName.trim()) { - return NextResponse.json({ error: '文件名不能为空' }, { status: 400 }) - } - if (!normalizedFileName) { - return NextResponse.json({ error: '文件名包含不安全的路径或字符' }, { status: 400 }) - } if (uploadPurpose && !ALLOWED_UPLOAD_PURPOSES.has(uploadPurpose)) { return NextResponse.json({ error: '上传用途无效' }, { status: 400 }) } @@ -120,7 +117,7 @@ export async function POST(req: NextRequest) { // 写入元数据,方便在Redis丢失时回溯 const metaPath = path.join(tempDir, 'meta.json') const metaPayload = { - fileName: normalizedFileName, + fileName: name.fileName, fileSize: normalizedFileSize, totalChunks: normalizedTotalChunks, chunkSize: normalizedChunkSize, @@ -133,7 +130,7 @@ export async function POST(req: NextRequest) { // 保存会话(使用统一的接口,自动选择Redis或内存Map) const now = Date.now() await saveUploadSession(uploadId, { - fileName: normalizedFileName, + fileName: name.fileName, fileSize: normalizedFileSize, totalChunks: normalizedTotalChunks, chunkSize: normalizedChunkSize, diff --git a/app/api/materials/upload/route.idempotency.test.ts b/app/api/materials/upload/route.idempotency.test.ts index 35c09a1e..0c314a8d 100644 --- a/app/api/materials/upload/route.idempotency.test.ts +++ b/app/api/materials/upload/route.idempotency.test.ts @@ -32,6 +32,7 @@ jest.mock('next-auth', () => ({ jest.mock('@/lib/auth', () => ({ authOptions: {} })) jest.mock('fs', () => ({ + ...jest.requireActual('fs'), promises: { mkdir: jest.fn().mockResolvedValue(undefined), rename: jest.fn().mockResolvedValue(undefined), diff --git a/app/api/materials/upload/route.ts b/app/api/materials/upload/route.ts index 9cdc8010..65b0c7be 100644 --- a/app/api/materials/upload/route.ts +++ b/app/api/materials/upload/route.ts @@ -9,6 +9,7 @@ import { uploadToS3 } from '@/lib/s3'; import { promises as fs } from 'fs'; import path from 'path'; import { randomBytes, randomUUID } from 'crypto'; +import { getUploadStorageExtension } from '@/lib/upload-paths'; import { parseAudioMetadata, isAudioFile } from '@/lib/audio-processor'; import { enqueueVideoTranscodeTask, USER_TRANSCODE_FAILURE_MESSAGE } from '@/lib/video-transcode-task'; import { AUTO_GENERAL_TYPES, requiresCategoryAndScene, requiresRenderer, getDefaultRenderer } from '@/lib/material-validation'; @@ -941,7 +942,7 @@ export async function POST(request: NextRequest) { let sourcePath = ''; if (zipFile) { - ext = path.extname(zipFile.name); + ext = getUploadStorageExtension(zipFile.name); buffer = Buffer.from(await zipFile.arrayBuffer()); zipFileSize = BigInt(buffer.length); console.log('[Upload] Using uploaded file buffer'); @@ -974,7 +975,7 @@ export async function POST(request: NextRequest) { '已合并的 canonical 源文件大小与上传会话不一致', ); } - ext = path.extname(originalFileName || sourcePath); + ext = getUploadStorageExtension(originalFileName || ownedMergedUpload!.session.fileName || sourcePath); console.log('[Upload] Using existing merged file:', sourcePath, 'size:', stat.size); } diff --git a/components/upload/ProductPackageUploader.test.tsx b/components/upload/ProductPackageUploader.test.tsx index 5735ae3c..22625ca4 100644 --- a/components/upload/ProductPackageUploader.test.tsx +++ b/components/upload/ProductPackageUploader.test.tsx @@ -1,6 +1,7 @@ import { changeField, selectOption, openSelect } from '@/test-utils/select' import { act, createEvent, fireEvent, render, screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' +import { TextEncoder } from 'util' import ProductPackageUploader, { selectTaskDetailFilesWithinLimits, @@ -13,6 +14,8 @@ const mockPrepareTaskDetailImagePreview = jest.fn() const mockPrepareTaskDetailSelectionThumbnail = jest.fn() const mockPollTaskDetailUploadJob = jest.fn() +Object.defineProperty(globalThis, 'TextEncoder', { value: TextEncoder, configurable: true }) + jest.mock('@/lib/chunk-upload', () => ({ chunkUpload: (...args: unknown[]) => mockChunkUpload(...args), })) @@ -217,6 +220,24 @@ describe('ProductPackageUploader', () => { expect(screen.queryByText('empty.psd')).not.toBeInTheDocument() }) + test('保留合法组合款文件名,并分别提示过长与含非法字符的文件', async () => { + const user = userEvent.setup() + render() + await screen.findByPlaceholderText('搜索发起本次出图需求的运营人员') + + const input = screen.getByLabelText(/PSD源文件/) + const longName = `ZH-GBSFY-${'SJ045004N1410V01-1-'.repeat(18)}组合款...psd` + const tooLongName = `${'组合源文件'.repeat(55)}.psd` + const invalidName = '组合款?.psd' + await user.upload(input, [longName, tooLongName, invalidName].map((name) => new File(['file'], name))) + + expect(screen.getByText(longName)).toBeInTheDocument() + const feedback = screen.getByRole('alert') + expect(feedback).toHaveTextContent(/文件名过长.*请缩短「组合源文件.*….*\.psd」/) + expect(feedback).toHaveTextContent(`文件名包含不支持的路径或字符。请修改「${invalidName}」`) + expect(mockChunkUpload).not.toHaveBeenCalled() + }) + test('应提供任务详情需求类型、可见性和出图方式字段', async () => { render() await screen.findByPlaceholderText('搜索发起本次出图需求的运营人员') diff --git a/components/upload/ProductPackageUploader.tsx b/components/upload/ProductPackageUploader.tsx index ea160bd5..630fa869 100644 --- a/components/upload/ProductPackageUploader.tsx +++ b/components/upload/ProductPackageUploader.tsx @@ -32,6 +32,7 @@ import { } from './drag-drop-utils'; import TaskReferenceFields from './TaskReferenceFields'; import { getDingtalkApprovalNoError } from '@/lib/dingtalk-approval-no'; +import { validateUploadFileName } from '@/lib/upload-file-name'; import { TASK_DETAIL_UPLOAD_LIMITS, validateTaskDetailUploadFiles, @@ -174,6 +175,7 @@ export function selectTaskDetailFilesWithinLimits( psdBytes: [], }; const acceptedFiles: File[] = []; + const errors: string[] = []; const isImageGroup = group !== 'psd'; let groupCount = existing[group].length; let totalImageCount = existing.main.length + existing.sku.length + existing.detail.length; @@ -184,6 +186,12 @@ export function selectTaskDetailFilesWithinLimits( .reduce((sum, file) => sum + Math.max(0, Number(file.size) || 0), 0); candidates.forEach((file) => { + const name = validateUploadFileName(file.name); + if (name.fileName === null) { + errors.push(name.error); + return; + } + const groupLimit = isImageGroup ? limits.maxImagesPerGroup : limits.maxPsdFileCount; let reason: SelectionLimitReason | null = null; if (groupCount >= groupLimit) { @@ -216,7 +224,6 @@ export function selectTaskDetailFilesWithinLimits( totalSourceCount += 1; }); - const errors: string[] = []; const groupLimit = isImageGroup ? limits.maxImagesPerGroup : limits.maxPsdFileCount; if (rejected.group.length > 0) { errors.push( @@ -724,7 +731,7 @@ export default function ProductPackageUploader({ if (messages.length > 0 && acceptedCount > 0) { messages.push(`其余 ${acceptedCount} ${unit}符合限制的文件已保留,可继续补充或直接提交`); } - setError(messages.join(';')); + setError(messages.join('\n')); }; const handleDrop = ( @@ -1204,10 +1211,14 @@ export default function ProductPackageUploader({ // 由外层回滚本次上传,避免把网络错误伪装成浏览器兼容问题。 for (let previewIndex = 0; previewIndex < browserPreviews.length; previewIndex += 1) { const preview: TaskDetailBrowserPreview = browserPreviews[previewIndex]; + const previewName = validateUploadFileName(preview.file.name); + const previewFile = previewName.fileName === null + ? new File([preview.file], `preview-${requestPrefix}-${previewIndex + 1}.webp`, { type: preview.file.type }) + : preview.file; totalWorkBytes += preview.file.size; const previewKey = `${requestPrefix}-preview-${previewIndex}`; const previewUploadId = await uploadFileWithChunks( - preview.file, + previewFile, (progress) => reportFileProgress(previewKey, preview.file.size, progress), () => cancelledRef.current || uploadStopRef.current, previewKey, @@ -1215,7 +1226,7 @@ export default function ProductPackageUploader({ uploadedFileIds.push(previewUploadId); previewAssets.push({ uploadId: previewUploadId, - fileName: preview.file.name, + fileName: previewFile.name, fileSize: preview.file.size, width: preview.width, height: preview.height, @@ -1821,7 +1832,7 @@ export default function ProductPackageUploader({ {/* 错误提示 */} {error && ( -
+
{error}
)} diff --git a/lib/__tests__/materials-upload-task-other-route.test.ts b/lib/__tests__/materials-upload-task-other-route.test.ts index 85a7ed83..e0f53383 100644 --- a/lib/__tests__/materials-upload-task-other-route.test.ts +++ b/lib/__tests__/materials-upload-task-other-route.test.ts @@ -20,6 +20,7 @@ jest.mock('@/lib/auth', () => ({ })) jest.mock('fs', () => ({ + ...jest.requireActual('fs'), promises: { mkdir: jest.fn().mockResolvedValue(undefined), writeFile: jest.fn().mockResolvedValue(undefined), diff --git a/lib/__tests__/path-security.test.ts b/lib/__tests__/path-security.test.ts index f1d02f55..7fdb53d3 100644 --- a/lib/__tests__/path-security.test.ts +++ b/lib/__tests__/path-security.test.ts @@ -1,3 +1,5 @@ +/** @jest-environment node */ + /** * R29 测试:路径安全工具 * @@ -158,6 +160,17 @@ describe('R29: 路径安全工具', () => { '%25252e%25252e%25252foutside.psd', 'folder/name.psd', 'bad\u0000name.psd', + 'name.psd\n', + '\tname.psd', + 'bad\x7fname.psd', + '.', + '..', + '%2e.', + 'C:source.psd', + '100% complete%2Fname.psd', + '%0aname.psd', + '组合%25%35%63款.psd', + ...Array.from('<>:"|?*', (character) => `bad${character}name.psd`), ])('应该拒绝路径形式的文件名:%s', (fileName) => { expect(normalizeSafeFileName(fileName)).toBeNull() }) @@ -166,6 +179,11 @@ describe('R29: 路径安全工具', () => { expect(normalizeSafeFileName(' 中文源文件.psb ')).toBe('中文源文件.psb') }) + it.each(['组合款...psd', 'a..b.jpg', '套装(左)+右 100%😃.psd', 'a%2e%2eb.jpg'])( + '保留合法单层文件名 %s', + (fileName) => expect(normalizeSafeFileName(fileName)).toBe(fileName), + ) + it('应该按 UTF-8 字节数拒绝超长文件名', () => { expect(normalizeSafeFileName(`${'文'.repeat(90)}.psd`)).toBeNull() }) diff --git a/lib/__tests__/product-package-completion.test.ts b/lib/__tests__/product-package-completion.test.ts index 5b5791f3..7cf2360c 100644 --- a/lib/__tests__/product-package-completion.test.ts +++ b/lib/__tests__/product-package-completion.test.ts @@ -742,13 +742,14 @@ describe('product-package-completion', () => { })).rejects.toThrow('上传已过期') }) - test('同批同名 PSD 不会覆盖,成功后会清理全部上传会话', async () => { + test('同批同名长 PSD 保留原名并各自写入短路径,成功后清理上传会话', async () => { const uploadRoot = await mkdtemp(path.join(tmpdir(), 'gongxiang-psd-success-')) const previousUploadDir = process.env.UPLOAD_DIR process.env.UPLOAD_DIR = uploadRoot try { const firstSource = path.join(uploadRoot, 'first-upload.tmp') const secondSource = path.join(uploadRoot, 'second-upload.tmp') + const fileName = `ZH-GBSFY-${'SJ045004N1410V01-1-'.repeat(18)}组合款...psd` await writeFile(firstSource, 'first') await writeFile(secondSource, 'second') ;(getOwnedUploadSession as jest.Mock).mockImplementation(async (uploadId: string) => ({ @@ -771,8 +772,8 @@ describe('product-package-completion', () => { assets: { main: [{ fileUrl: 'https://img.example/main.png', fileName: 'main.png', fileSize: 10 }], psd: [ - { uploadId: 'psd-1', fileName: 'same.psd', fileSize: 5 }, - { uploadId: 'psd-2', fileName: 'same.psd', fileSize: 6 }, + { uploadId: 'psd-1', fileName, fileSize: 5 }, + { uploadId: 'psd-2', fileName, fileSize: 6 }, ], }, })).resolves.toEqual(expect.objectContaining({ materialId: 'material-1' })) @@ -780,6 +781,11 @@ describe('product-package-completion', () => { const psdInfos = (saveProductPackageAssetsAndComplete as jest.Mock).mock.calls.at(-1)?.[0]?.psdInfos expect(psdInfos).toHaveLength(2) expect(psdInfos[0].filePath).not.toBe(psdInfos[1].filePath) + for (const info of psdInfos) { + expect(info.fileName).toBe(fileName) + expect(path.extname(info.filePath)).toBe('.psd') + expect(Buffer.byteLength(path.basename(info.filePath))).toBeLessThanOrEqual(200) + } await expect(readFile(path.join(uploadRoot, 'materials', path.basename(psdInfos[0].filePath)), 'utf8')) .resolves.toBe('first') await expect(readFile(path.join(uploadRoot, 'materials', path.basename(psdInfos[1].filePath)), 'utf8')) diff --git a/lib/__tests__/task-detail-preview-storage.test.ts b/lib/__tests__/task-detail-preview-storage.test.ts index d0d7e03d..467be5ec 100644 --- a/lib/__tests__/task-detail-preview-storage.test.ts +++ b/lib/__tests__/task-detail-preview-storage.test.ts @@ -69,6 +69,17 @@ describe('task-detail-preview-storage', () => { const secondAbsolutePath = path.join(uploadRoot, second.replace(/^uploads\//, '').replace(/\//g, path.sep)) await expect(readFile(firstAbsolutePath)).resolves.toEqual(Buffer.from('private-preview-1')) await expect(readFile(secondAbsolutePath)).resolves.toEqual(Buffer.from('private-preview-2')) + + const longPreview = await saveTaskDetailPreview( + Buffer.from('long-preview'), + 'material-1', + 'detail', + `${'组合详细图'.repeat(55)}.webp`, + true, + ) + expect(Buffer.byteLength(path.basename(longPreview))).toBeLessThanOrEqual(200) + await expect(readFile(path.join(uploadRoot, longPreview.replace(/^uploads\//, '')))) + .resolves.toEqual(Buffer.from('long-preview')) } finally { if (previousUploadDir === undefined) { delete process.env.UPLOAD_DIR diff --git a/lib/__tests__/upload-sessions-security.test.ts b/lib/__tests__/upload-sessions-security.test.ts index c4a72eca..162f9374 100644 --- a/lib/__tests__/upload-sessions-security.test.ts +++ b/lib/__tests__/upload-sessions-security.test.ts @@ -67,7 +67,7 @@ describe('upload-sessions 最终落盘安全', () => { const outputPath = await getUploadedFile(uploadId) expect(outputPath).toBe( - path.join(uploadRoot, 'assembled', `${uploadId}-中文源文件.psd`), + path.join(uploadRoot, 'assembled', `${uploadId}.psd`), ) await expect(readFile(outputPath!)).resolves.toEqual(content) }) @@ -81,7 +81,7 @@ describe('upload-sessions 最终落盘安全', () => { await expect(getUploadedFile(uploadId)).resolves.toBeNull() await expect( - readFile(path.join(uploadRoot, 'assembled', `${uploadId}-source.jpg`)), + readFile(path.join(uploadRoot, 'assembled', `${uploadId}.jpg`)), ).rejects.toMatchObject({ code: 'ENOENT' }) }) @@ -123,7 +123,7 @@ describe('upload-sessions 最终落盘安全', () => { // 受控清理只能消费已完成的上传:先原子合并并写入 completed // tombstone,再删除 assembled/temp 和内存 + Redis 会话。 await expect(getUploadedFile(uploadId)).resolves.toEqual( - path.join(uploadRoot, 'assembled', `${uploadId}-source.jpg`), + path.join(uploadRoot, 'assembled', `${uploadId}.jpg`), ) await cleanupTempFiles([], [uploadId]) @@ -145,7 +145,7 @@ describe('upload-sessions 最终落盘安全', () => { await writeFile(sentinelPath, 'sentinel') await symlink( sentinelDir, - path.join(assembledDir, `${uploadId}-source.psd`), + path.join(assembledDir, `${uploadId}.psd`), 'junction', ) diff --git a/lib/path-security.ts b/lib/path-security.ts index 81bab9b7..dbeb86f1 100644 --- a/lib/path-security.ts +++ b/lib/path-security.ts @@ -11,25 +11,10 @@ import path from 'path' import { lstat, mkdir } from 'fs/promises' +import { validateUploadFileName } from './upload-file-name' export const MAX_SAFE_FILE_NAME_BYTES = 255 -function decodePathForValidation(value: string): string { - let decoded = value - for (let index = 0; index < 5; index += 1) { - try { - const next = decodeURIComponent(decoded) - if (next === decoded) { - break - } - decoded = next - } catch { - break - } - } - return decoded -} - /** * 验证客户端文件名是单一叶子文件名,而不是路径。 * 返回 trim + NFC 后的文件名;不安全时返回 null。 @@ -38,40 +23,7 @@ export function normalizeSafeFileName( fileName: string, maxBytes: number = MAX_SAFE_FILE_NAME_BYTES, ): string | null { - if (typeof fileName !== 'string') { - return null - } - - const normalized = fileName.trim().normalize('NFC') - if ( - !normalized || - normalized === '.' || - normalized === '..' || - Buffer.byteLength(normalized, 'utf8') > maxBytes - ) { - return null - } - - const decoded = decodePathForValidation(normalized) - const candidates = decoded === normalized ? [normalized] : [normalized, decoded] - - for (const candidate of candidates) { - if ( - path.posix.isAbsolute(candidate) || - path.win32.isAbsolute(candidate) || - /^[A-Za-z]:/.test(candidate) || - candidate.startsWith('\\\\') || - candidate.includes('/') || - candidate.includes('\\') || - candidate.includes('..') || - /[\x00-\x1f\x7f]/.test(candidate) || - /[<>:"|?*]/.test(candidate) - ) { - return null - } - } - - return normalized + return validateUploadFileName(fileName, maxBytes).fileName } /** diff --git a/lib/product-package-completion.ts b/lib/product-package-completion.ts index 6f1cb13d..638b17ec 100644 --- a/lib/product-package-completion.ts +++ b/lib/product-package-completion.ts @@ -14,7 +14,8 @@ import { type ProductPackageZipInfos, type SavedProductPackageSkuPreviewAsset, } from '@/lib/task-material-processor' -import { buildStoredUploadPath, getUploadRootDir } from '@/lib/upload-paths' +import { buildStoredUploadPath, getUploadRootDir, getUploadStorageExtension } from '@/lib/upload-paths' +import { validateUploadFileName } from '@/lib/upload-file-name' import { isRemoteUploadSyncEnabled, syncStoredUploadFileToRemote } from '@/lib/remote-upload-sync' import { getOwnedUploadSession, @@ -327,10 +328,12 @@ function parsePublicAssetGroup( } const uploadId = typeof asset.uploadId === 'string' ? asset.uploadId.trim() : '' - const fileName = typeof asset.fileName === 'string' ? asset.fileName.trim() : '' + const name = validateUploadFileName(asset.fileName) + if (name.fileName === null) throw new Error(name.error) + const fileName = name.fileName const fileSize = Number(asset.fileSize) - if (!uploadId || !fileName || !Number.isFinite(fileSize) || fileSize < 0) { + if (!uploadId || !Number.isFinite(fileSize) || fileSize < 0) { throw new Error(`${group} 第 ${index + 1} 个资产参数无效`) } @@ -627,10 +630,9 @@ async function writeAssetToTempFile( buffer: Buffer, ) { const tempPath = path.join( - process.cwd(), - 'uploads', + getUploadRootDir(), 'temp', - `${prefix}-${Date.now()}-${Math.random().toString(36).substring(2, 9)}-${asset.fileName}`, + `${prefix}-${Date.now()}-${randomBytes(6).toString('hex')}${getUploadStorageExtension(asset.fileName)}`, ) await mkdir(path.dirname(tempPath), { recursive: true }) @@ -952,8 +954,8 @@ export function buildPsdPermanentFileName( timestamp = Date.now(), entropy = randomBytes(6).toString('hex'), ) { - const sanitizedFileName = originalFileName.replace(/[\/\\:*?"<>|]/g, '_') - return `psd-${materialId}-${timestamp}-${assetIndex}-${entropy}-${sanitizedFileName}` + const extension = getUploadStorageExtension(originalFileName) + return `psd-${materialId}-${timestamp}-${assetIndex}-${entropy}${extension}` } async function movePsdFilesToPermanentDir( diff --git a/lib/task-detail-change-staging.ts b/lib/task-detail-change-staging.ts index 176efe20..95399897 100644 --- a/lib/task-detail-change-staging.ts +++ b/lib/task-detail-change-staging.ts @@ -3,11 +3,12 @@ import { copyFile, lstat, mkdir, rm } from 'fs/promises' import path from 'path' import { acquireTaskMaterialUploadSessionLocks } from '@/lib/material-upload-cross-process-lock' -import { normalizeSafeFileName, resolveStrictChildPath } from '@/lib/path-security' +import { resolveStrictChildPath } from '@/lib/path-security' +import { normalizeUploadFileName } from '@/lib/upload-file-name' import { TaskDetailAssetEditError } from '@/lib/task-detail-asset-edit' import { TASK_DETAIL_UPLOAD_LIMITS } from '@/lib/task-detail-upload-policy' import { cleanupConsumedUploadSession } from '@/lib/temp-cleanup' -import { getUploadRootDir } from '@/lib/upload-paths' +import { getUploadRootDir, getUploadStorageExtension } from '@/lib/upload-paths' import { getOwnedUploadSession, getUploadedFile, @@ -83,9 +84,9 @@ export async function withTaskDetailStagedUploads(input: { } } - const safeName = normalizeSafeFileName(session.fileName) + const safeName = normalizeUploadFileName(session.fileName) if (!safeName) throw new Error('图片文件名无效') - const storedName = `${String(index).padStart(3, '0')}-${safeName}` + const storedName = `${String(index).padStart(3, '0')}${getUploadStorageExtension(safeName)}` const targetPath = resolveStrictChildPath(requestDirectory, storedName) if (!targetPath) throw new Error('图片暂存路径无效') await copyFile(sourcePath, targetPath, fsConstants.COPYFILE_EXCL) @@ -129,7 +130,7 @@ export function resolveTaskDetailStagedFile( const baseName = normalized.slice(expectedPrefix.length) const filePath = resolveStrictChildPath(requestDirectory, baseName) if (!filePath) throw new Error('图片审批暂存引用无效') - const fileName = normalizeSafeFileName(file.fileName) + const fileName = normalizeUploadFileName(file.fileName) if (!fileName) throw new Error('图片审批暂存文件名无效') return { trusted: true, diff --git a/lib/task-detail-preview-storage.ts b/lib/task-detail-preview-storage.ts index 2a570601..ae582e89 100644 --- a/lib/task-detail-preview-storage.ts +++ b/lib/task-detail-preview-storage.ts @@ -22,8 +22,8 @@ function buildPrivatePreviewFileName( .replace(/[\x00-\x1f]/g, '') .replace(/[<>:"|?*]/g, '_') .trim() - .slice(0, 80) - const uniqueBaseName = safeBaseName || `${group}-preview` + const shortBaseName = Array.from(safeBaseName).slice(0, 35).join('') + const uniqueBaseName = shortBaseName || `${group}-preview` return `${Date.now()}-${randomUUID()}-${uniqueBaseName}.webp` } diff --git a/lib/temp-cleanup.ts b/lib/temp-cleanup.ts index 8abd472c..fe442006 100644 --- a/lib/temp-cleanup.ts +++ b/lib/temp-cleanup.ts @@ -21,8 +21,9 @@ import { type UploadSessionSealState, } from './material-upload-session-seal' import { MaterialUploadRequestError } from './material-upload-request-guard' -import { normalizeSafeFileName, resolveStrictChildPath } from './path-security' -import { getUploadRootDir } from './upload-paths' +import { resolveStrictChildPath } from './path-security' +import { normalizeUploadFileName } from './upload-file-name' +import { getUploadRootDir, inspectUploadOutput } from './upload-paths' import { uploadSessions, type UploadSession } from './upload-sessions' const MAX_AGE_MS = 8 * 60 * 60 * 1000 @@ -690,7 +691,7 @@ async function readMetadataFailClosed(metadataPath: string): Promise<{ try { const parsed = JSON.parse(await readFile(metadataPath, 'utf8')) as Record const userId = typeof parsed.userId === 'string' ? parsed.userId.trim() : '' - const fileName = normalizeSafeFileName( + const fileName = normalizeUploadFileName( typeof parsed.fileName === 'string' ? parsed.fileName : '', ) const fileSize = Number(parsed.fileSize) @@ -752,7 +753,7 @@ function normalizeSessionEvidence( source: StoredSessionEvidence['source'], ): StoredSessionEvidence { const userId = typeof session.userId === 'string' ? session.userId.trim() : '' - const fileName = normalizeSafeFileName( + const fileName = normalizeUploadFileName( typeof session.fileName === 'string' ? session.fileName : '', ) const fileSize = Number(session.fileSize) @@ -816,37 +817,28 @@ async function inspectAssembledFile( expectedFileSize?: number, ): Promise { const assembledDir = resolveStrictChildPath(getUploadRootDir(), 'assembled') - const assembledPath = assembledDir - ? resolveStrictChildPath(assembledDir, `${uploadId}-${fileName}`) - : null - if (!assembledPath) { + if (!assembledDir) { throw new MaterialUploadRequestError( '上传合并文件路径异常,已保留数据', 503, 'UPLOAD_CLEANUP_PATH_INVALID', ) } - try { - const stats = await lstat(assembledPath) - if ( - stats.isSymbolicLink() - || !stats.isFile() - || stats.size <= 0 - || (expectedFileSize !== undefined && stats.size !== expectedFileSize) - ) { - throw new MaterialUploadRequestError( - '上传合并文件状态异常,已保留数据', - 503, - 'UPLOAD_CLEANUP_MERGED_INVALID', - ) - } - return assembledPath - } catch (error: any) { - if (error?.code === 'ENOENT') { - return null - } - throw error + const { existing } = await inspectUploadOutput(assembledDir, uploadId, `${uploadId}-`, fileName) + if (!existing) return null + const { stats, filePath } = existing + if ( + !stats.isFile() + || stats.size <= 0 + || (expectedFileSize !== undefined && stats.size !== expectedFileSize) + ) { + throw new MaterialUploadRequestError( + '上传合并文件状态异常,已保留数据', + 503, + 'UPLOAD_CLEANUP_MERGED_INVALID', + ) } + return filePath } async function deleteSessionStateFailClosed(uploadId: string): Promise { diff --git a/lib/upload-file-name.ts b/lib/upload-file-name.ts new file mode 100644 index 00000000..747037b5 --- /dev/null +++ b/lib/upload-file-name.ts @@ -0,0 +1,62 @@ +// 展示名写入 TEXT 字段。768 个 UTF-8 字节进行百分号编码后至多占 2304 字节。 +export const MAX_UPLOAD_FILE_NAME_BYTES = 768 + +const controlCharacters = /[\x00-\x1f\x7f]/ +const invalidFileNameCharacters = /[/\\<>:"|?*]|[\x00-\x1f\x7f]/ +const unpairedSurrogate = new RegExp('[\\uD800-\\uDFFF]', 'u') + +function containsUnsupportedPathOrCharacters(fileName: string): boolean { + let candidate = fileName + for (let pass = 0; pass <= 5; pass += 1) { + const segment = candidate.trim() + if (invalidFileNameCharacters.test(candidate) || segment === '.' || segment === '..') { + return true + } + if (!candidate.includes('%')) break + // ASCII 转义独立解码,避免合法的字面百分号掩盖编码分隔符。 + const decoded = candidate.replace(/%(?:25)*([0-7][0-9a-f])/gi, (_, hex: string) => + String.fromCharCode(Number.parseInt(hex, 16)), + ) + if (decoded === candidate) break + candidate = decoded + } + return false +} + +export function validateUploadFileName( + value: unknown, + maxBytes = MAX_UPLOAD_FILE_NAME_BYTES, +) { + const raw = typeof value === 'string' ? value : '' + const fileName = raw.trim().normalize('NFC') + const label = raw.length > 96 + ? `${raw.slice(0, 64)}…${raw.slice(-24)}` + : raw + + if ( + controlCharacters.test(raw) + || unpairedSurrogate.test(fileName) + || containsUnsupportedPathOrCharacters(fileName) + ) { + return { + fileName: null, + code: 'FILE_NAME_INVALID', + error: `文件名包含不支持的路径或字符。请修改「${JSON.stringify(label).slice(1, -1)}」后重新选择`, + } as const + } + if (!fileName) { + return { fileName: null, code: 'FILE_NAME_EMPTY', error: '文件名不能为空' } as const + } + if (fileName.length > maxBytes || new TextEncoder().encode(fileName).length > maxBytes) { + return { + fileName: null, + code: 'FILE_NAME_TOO_LONG', + error: `文件名过长(最多支持 ${maxBytes} 个 UTF-8 字节)。请缩短「${label}」后重新选择`, + } as const + } + return { fileName } as const +} + +export function normalizeUploadFileName(value: unknown): string | null { + return validateUploadFileName(value).fileName +} diff --git a/lib/upload-paths.ts b/lib/upload-paths.ts index 37da7f0a..a99e38f6 100644 --- a/lib/upload-paths.ts +++ b/lib/upload-paths.ts @@ -1,4 +1,35 @@ import path from 'path' +import { lstat } from 'fs/promises' +import { normalizeSafeFileName } from './path-security' + +export function getUploadStorageExtension(fileName: string): string { + const extension = path.extname(fileName) + return /^\.[A-Za-z0-9]{1,16}$/.test(extension) ? extension : '' +} + +export async function inspectUploadOutput( + directory: string, + storageStem: string, + legacyPrefix: string, + fileName: string, +) { + const outputPath = path.join(directory, `${storageStem}${getUploadStorageExtension(fileName) || '.bin'}`) + const paths = [outputPath] + const legacyName = `${legacyPrefix}${fileName}` + if (normalizeSafeFileName(legacyName) === legacyName) { + const legacyPath = path.join(directory, legacyName) + if (legacyPath !== outputPath) paths.push(legacyPath) + } + // 保留重试时对升级前已合并产物的引用。 + for (const filePath of paths) { + const stats = await lstat(filePath).catch((error: NodeJS.ErrnoException) => { + if (error.code === 'ENOENT') return null + throw error + }) + if (stats) return { outputPath, existing: { filePath, stats } } + } + return { outputPath, existing: null } +} export function buildStoredUploadPath(...segments: string[]) { return path.posix.join('uploads', ...segments.map((segment) => String(segment || '').replace(/\\/g, '/'))) diff --git a/lib/upload-sessions.ts b/lib/upload-sessions.ts index 4028b7fc..a8b2f97f 100644 --- a/lib/upload-sessions.ts +++ b/lib/upload-sessions.ts @@ -25,10 +25,10 @@ import { lstat, readFile, readdir, rm } from 'fs/promises' import { ensureSafeDirectoryWithinRoot, isPathFreeOfSymbolicLinks, - normalizeSafeFileName, resolveStrictChildPath, } from './path-security' -import { getUploadRootDir } from './upload-paths' +import { getUploadRootDir, inspectUploadOutput } from './upload-paths' +import { normalizeUploadFileName } from './upload-file-name' import { getExpectedUploadChunkBytes, resolveUploadChunkSize, @@ -212,7 +212,7 @@ async function getUploadSessionFromMetadata(uploadId: string): Promise { const normalizedUploadId = String(uploadId || '').trim() - const normalizedFileName = normalizeSafeFileName(session.fileName) + const normalizedFileName = normalizeUploadFileName(session.fileName) if (!isSafeUploadId(normalizedUploadId) || !normalizedFileName) { throw new Error('上传会话包含不安全的标识或文件名') } @@ -374,7 +374,7 @@ export async function getOwnedUploadSession( return ( session?.userId === normalizedUserId && - normalizeSafeFileName(session.fileName) !== null + normalizeUploadFileName(session.fileName) !== null ) ? session : null @@ -472,7 +472,7 @@ export async function getUploadedFile( return null } - const safeFileName = normalizeSafeFileName(session.fileName) + const safeFileName = normalizeUploadFileName(session.fileName) if (!safeFileName) { console.warn(`[Upload Session] Unsafe file name rejected: ${normalizedUploadId}`) return null @@ -486,15 +486,7 @@ export async function getUploadedFile( return null } - const outputPath = resolveStrictChildPath( - outputDir, - `${normalizedUploadId}-${safeFileName}`, - ) - if ( - !outputPath || - !(await isPathFreeOfSymbolicLinks(uploadRoot, tempDir)) || - !(await isPathFreeOfSymbolicLinks(uploadRoot, outputPath, { allowMissingLeaf: true })) - ) { + if (!(await isPathFreeOfSymbolicLinks(uploadRoot, tempDir))) { console.warn(`[Upload Session] Unsafe upload path rejected: ${normalizedUploadId}`) return null } @@ -514,36 +506,27 @@ export async function getUploadedFile( } // 只在跨容器独占锁内检查/替换结果,避免两个完成请求互删半成品。 - try { - const existingStats = await lstat(outputPath) - if (existingStats.isSymbolicLink() || !existingStats.isFile()) { - console.warn(`[Upload Session] Existing output is not a regular file: ${outputPath}`) - } else if (existingStats.size === session.fileSize) { - if (completionSealHandle) { - await completeUploadCompletionSeal(completionSealHandle) - completionSealFinalized = true - } - console.log(`[Upload Session] File already exists, skip assembly: ${outputPath}`) - return outputPath - } - if (completionSeal.state === 'completed') { - console.error( - `[Upload Session] Completed seal exists but assembled output is invalid: ${normalizedUploadId}`, - ) - return null - } - await rm(outputPath, { force: true }) - } catch (error: any) { - if (error?.code !== 'ENOENT') { - throw error + const { outputPath, existing } = await inspectUploadOutput( + outputDir, normalizedUploadId, `${normalizedUploadId}-`, safeFileName, + ) + if (existing?.stats.isSymbolicLink()) { + console.warn(`[Upload Session] Unsafe upload path rejected: ${normalizedUploadId}`) + return null + } + if (existing?.stats.isFile() && existing.stats.size === session.fileSize) { + if (completionSealHandle) { + await completeUploadCompletionSeal(completionSealHandle) + completionSealFinalized = true } + return existing.filePath } if (completionSeal.state === 'completed') { console.error( - `[Upload Session] Completed seal exists but assembled output is missing: ${normalizedUploadId}`, + `[Upload Session] Completed seal exists but assembled output is invalid: ${normalizedUploadId}`, ) return null } + if (existing) await rm(existing.filePath, { force: true }) // 读取所有chunk文件 const files = await readdir(tempDir)