gongxiangp2/lib/performance-survey-attachment-storage.ts

80 lines
3.8 KiB
TypeScript

import path from 'path'
import { createHash } from 'crypto'
import { createReadStream } from 'fs'
import { chmod, copyFile, lstat, mkdir, open, readFile, rm } from 'fs/promises'
import AdmZip from 'adm-zip'
import { isPathFreeOfSymbolicLinks } from './path-security'
import { getPerformanceCaseFileType } from './performance-survey-attachment-contract'
export const PERFORMANCE_CASE_PRIVATE_DIRECTORY = '.performance-survey-private'
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
export async function performanceAttachmentPath(id: string, relative = '', create = false) {
if (!UUID.test(id) || relative.split('/').some((part) => part === '..' || part === '.') || relative.includes('\\') || path.isAbsolute(relative)) {
throw new Error('附件路径无效')
}
const root = path.resolve(process.env.UPLOAD_DIR || './uploads', PERFORMANCE_CASE_PRIVATE_DIRECTORY)
const file = path.join(root, id, relative)
if (!(await isPathFreeOfSymbolicLinks(path.parse(root).root, file, { allowMissingDescendants: true }))) throw new Error('附件存储路径不可用')
if (create) {
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 })
await chmod(root, 0o700)
}
return file
}
export async function storePerformanceAttachment(id: string, source: string, extension: string) {
const destination = await performanceAttachmentPath(id, `original.${extension}`, true)
await copyFile(source, destination, 1)
await chmod(destination, 0o600)
const hash = createHash('sha256')
for await (const chunk of createReadStream(destination)) hash.update(chunk)
return hash.digest('hex')
}
export async function removePerformanceAttachment(id: string) {
await rm(await performanceAttachmentPath(id), { recursive: true, force: true })
}
export async function assertPerformanceAttachmentFormat(file: string, name: string) {
const type = getPerformanceCaseFileType(name)
if (!type) throw new Error('文件格式不支持')
const handle = await open(file, 'r')
const header = Buffer.alloc(64)
try { await handle.read(header, 0, header.length, 0) } finally { await handle.close() }
let valid = false
switch (type.extension) {
case 'mp4':
case 'mov':
valid = header.subarray(4, 8).toString() === 'ftyp' || (type.extension === 'mov' && ['moov', 'mdat', 'wide'].includes(header.subarray(4, 8).toString()))
break
case 'webm': valid = header.subarray(0, 4).equals(Buffer.from([0x1a, 0x45, 0xdf, 0xa3])); break
case 'pdf': valid = header.subarray(0, 5).toString() === '%PDF-'; break
case 'doc':
case 'ppt': {
const content = await readFile(file)
valid = header.subarray(0, 8).equals(Buffer.from('d0cf11e0a1b11ae1', 'hex'))
&& content.includes(Buffer.from(type.extension === 'doc' ? 'WordDocument' : 'PowerPoint Document', 'utf16le'))
&& !content.includes(Buffer.from('EncryptedPackage', 'utf16le'))
&& !content.includes(Buffer.from('VBA', 'utf16le'))
break
}
case 'docx':
case 'pptx': {
const zip = new AdmZip(file)
const entries = zip.getEntries()
let expanded = 0
for (const entry of entries) {
expanded += entry.header.size
if (expanded > 256 * 1024 * 1024 || entries.length > 20000 || /vbaproject|encryptioninfo/i.test(entry.entryName) || entry.entryName.includes('..')) throw new Error('文档包含宏、加密内容或解压后过大')
}
valid = Boolean(zip.getEntry('[Content_Types].xml') && zip.getEntry(type.extension === 'docx' ? 'word/document.xml' : 'ppt/presentation.xml'))
break
}
}
if (!valid) throw new Error(`文件「${name}」内容与格式不符,或包含宏、加密内容`)
const stats = await lstat(file)
if (!stats.isFile() || stats.isSymbolicLink()) throw new Error('附件原件不可用')
return type
}