312 lines
13 KiB
TypeScript
312 lines
13 KiB
TypeScript
import { createHash } from 'crypto';
|
|
import { mkdir, open, statfs } from 'fs/promises';
|
|
import { tmpdir } from 'os';
|
|
import { resolve } from 'path';
|
|
import { Readable } from 'stream';
|
|
|
|
export const OUTBOUND_IMPORT_MAX_ROWS = 10_000;
|
|
export const OUTBOUND_IMPORT_MAX_COLUMNS = 64;
|
|
// 仅用于防止恶意中央目录耗尽内存,不作为业务图片数量限制。
|
|
export const OUTBOUND_IMPORT_MAX_ZIP_ENTRIES = 100_002;
|
|
export const OUTBOUND_IMPORT_MAX_XLSX_SIZE = 100 * 1024 * 1024;
|
|
export const OUTBOUND_IMPORT_MAX_XLSX_ENTRIES = 256;
|
|
export const OUTBOUND_IMPORT_MAX_XLSX_UNCOMPRESSED_SIZE = 500 * 1024 * 1024;
|
|
export const OUTBOUND_IMPORT_MAX_IMAGE_SIZE = 100 * 1024 * 1024;
|
|
export const OUTBOUND_IMPORT_MAX_IMAGE_PIXELS = 40_000_000;
|
|
export const OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS = 60 * 60 * 1000;
|
|
export const OUTBOUND_IMPORT_TEMP_DIR = resolve(process.env.ARTVERIS_OUTBOUND_TEMP_DIR || tmpdir());
|
|
export const OUTBOUND_IMPORT_UPLOAD_TEMP_PREFIX = 'artveris-outbound-upload-';
|
|
export const OUTBOUND_IMPORT_PREVIEW_TEMP_PREFIX = 'artveris-outbound-preview-';
|
|
export const OUTBOUND_IMPORT_PREVIEW_STORAGE_ROOT = 'outbound-preview';
|
|
const OUTBOUND_IMPORT_MIN_FREE_BYTES = 1024 * 1024 * 1024;
|
|
|
|
const ARCHIVE_PROGRESS_INTERVAL_BYTES = 8 * 1024 * 1024;
|
|
const ZIP_END_RECORD_MAX_SIZE = 65_557;
|
|
const ZIP_END_RECORD_MIN_SIZE = 22;
|
|
const ZIP64_LOCATOR_SIZE = 20;
|
|
const ZIP64_END_RECORD_MIN_SIZE = 56;
|
|
const ZIP_END_SIGNATURE = 0x06054b50;
|
|
const ZIP64_LOCATOR_SIGNATURE = 0x07064b50;
|
|
const ZIP64_END_SIGNATURE = 0x06064b50;
|
|
|
|
export function outboundImportPreviewStoragePrefix(sessionId: string): string {
|
|
if (!/^[A-Za-z0-9_-]+$/.test(sessionId)) throw new Error('Invalid outbound import session id');
|
|
return `${OUTBOUND_IMPORT_PREVIEW_STORAGE_ROOT}/${sessionId}/`;
|
|
}
|
|
|
|
export function outboundImportPreviewImageKey(sessionId: string, imagePath: string): string {
|
|
const canonicalPath = canonicalImagePath(imagePath);
|
|
const pathHash = createHash('sha256').update(canonicalPath, 'utf8').digest('hex');
|
|
const extension = mimeOfImagePath(canonicalPath) === 'image/jpeg'
|
|
? '.jpg'
|
|
: canonicalPath.slice(canonicalPath.lastIndexOf('.')).toLowerCase();
|
|
return `${outboundImportPreviewStoragePrefix(sessionId)}${pathHash}${extension}`;
|
|
}
|
|
|
|
export async function ensureOutboundImportTempDir(): Promise<void> {
|
|
await mkdir(OUTBOUND_IMPORT_TEMP_DIR, { recursive: true });
|
|
}
|
|
|
|
export async function assertOutboundImportDiskCapacity(requiredBytes: number, copies = 1): Promise<void> {
|
|
await ensureOutboundImportTempDir();
|
|
const fs = await statfs(OUTBOUND_IMPORT_TEMP_DIR);
|
|
const available = Number(fs.bavail) * Number(fs.bsize);
|
|
const required = Math.max(
|
|
OUTBOUND_IMPORT_MIN_FREE_BYTES,
|
|
Math.max(0, Math.ceil(requiredBytes)) * Math.max(1, copies),
|
|
);
|
|
if (!Number.isFinite(available) || available < required) {
|
|
throw new Error(
|
|
`出库导入临时磁盘空间不足:至少需要 ${Math.ceil(required / 1024 / 1024)}MB 可用空间`,
|
|
);
|
|
}
|
|
}
|
|
|
|
interface ArchiveEntryLike {
|
|
isDirectory: boolean;
|
|
header: { size: number };
|
|
}
|
|
|
|
interface ArchiveStreamEntryLike extends ArchiveEntryLike {
|
|
stream: () => Readable;
|
|
}
|
|
|
|
function findZipEndRecordOffset(buffer: Buffer, label: string): number {
|
|
const minEndOffset = Math.max(0, buffer.length - ZIP_END_RECORD_MAX_SIZE);
|
|
for (let offset = buffer.length - ZIP_END_RECORD_MIN_SIZE; offset >= minEndOffset; offset--) {
|
|
if (buffer.readUInt32LE(offset) !== ZIP_END_SIGNATURE) continue;
|
|
const commentLength = buffer.readUInt16LE(offset + 20);
|
|
if (offset + ZIP_END_RECORD_MIN_SIZE + commentLength !== buffer.length) continue;
|
|
return offset;
|
|
}
|
|
throw new Error(`${label}文件结构无效`);
|
|
}
|
|
|
|
function assertZipEntryCountValue(entries: bigint, maxEntries: number, label: string): void {
|
|
if (entries > BigInt(maxEntries)) {
|
|
throw new Error(`${label}文件数量超过限制(最多 ${maxEntries} 个)`);
|
|
}
|
|
}
|
|
|
|
function usesZip64(buffer: Buffer, endOffset: number): boolean {
|
|
return buffer.readUInt16LE(endOffset + 10) === 0xffff
|
|
|| buffer.readUInt32LE(endOffset + 12) === 0xffffffff
|
|
|| buffer.readUInt32LE(endOffset + 16) === 0xffffffff;
|
|
}
|
|
|
|
function readZip64EntryCount(buffer: Buffer, endOffset: number, label: string): bigint {
|
|
const locatorOffset = endOffset - ZIP64_LOCATOR_SIZE;
|
|
if (locatorOffset < 0 || buffer.readUInt32LE(locatorOffset) !== ZIP64_LOCATOR_SIGNATURE) {
|
|
throw new Error(`${label}文件结构无效`);
|
|
}
|
|
const recordOffset = buffer.readBigUInt64LE(locatorOffset + 8);
|
|
if (recordOffset > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error(`${label}文件结构无效`);
|
|
const offset = Number(recordOffset);
|
|
if (offset < 0 || offset + ZIP64_END_RECORD_MIN_SIZE > buffer.length) throw new Error(`${label}文件结构无效`);
|
|
if (buffer.readUInt32LE(offset) !== ZIP64_END_SIGNATURE) throw new Error(`${label}文件结构无效`);
|
|
return buffer.readBigUInt64LE(offset + 32);
|
|
}
|
|
|
|
export function assertZipEntryCount(buffer: Buffer, maxEntries: number, label: string): number {
|
|
const endOffset = findZipEndRecordOffset(buffer, label);
|
|
const entries = usesZip64(buffer, endOffset)
|
|
? readZip64EntryCount(buffer, endOffset, label)
|
|
: BigInt(buffer.readUInt16LE(endOffset + 10));
|
|
assertZipEntryCountValue(entries, maxEntries, label);
|
|
return buffer.length - endOffset;
|
|
}
|
|
|
|
export async function inspectZipFile(filePath: string, maxEntries: number, label: string): Promise<number> {
|
|
const file = await open(filePath, 'r');
|
|
try {
|
|
const { size } = await file.stat();
|
|
if (size < ZIP_END_RECORD_MIN_SIZE) throw new Error(`${label}文件结构无效`);
|
|
const tailLength = Math.min(size, ZIP_END_RECORD_MAX_SIZE);
|
|
const tail = Buffer.allocUnsafe(tailLength);
|
|
const tailRead = await file.read(tail, 0, tailLength, size - tailLength);
|
|
if (tailRead.bytesRead !== tailLength) throw new Error(`${label}文件结构无效`);
|
|
const relativeEndOffset = findZipEndRecordOffset(tail, label);
|
|
const absoluteEndOffset = size - tailLength + relativeEndOffset;
|
|
let entries: bigint;
|
|
if (usesZip64(tail, relativeEndOffset)) {
|
|
const locator = Buffer.allocUnsafe(ZIP64_LOCATOR_SIZE);
|
|
if (absoluteEndOffset < ZIP64_LOCATOR_SIZE) throw new Error(`${label}文件结构无效`);
|
|
const locatorRead = await file.read(locator, 0, locator.length, absoluteEndOffset - ZIP64_LOCATOR_SIZE);
|
|
if (locatorRead.bytesRead !== locator.length) throw new Error(`${label}文件结构无效`);
|
|
if (locator.readUInt32LE(0) !== ZIP64_LOCATOR_SIGNATURE) throw new Error(`${label}文件结构无效`);
|
|
const recordOffset = locator.readBigUInt64LE(8);
|
|
if (recordOffset > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error(`${label}文件结构无效`);
|
|
const record = Buffer.allocUnsafe(ZIP64_END_RECORD_MIN_SIZE);
|
|
const recordRead = await file.read(record, 0, record.length, Number(recordOffset));
|
|
if (recordRead.bytesRead !== record.length) throw new Error(`${label}文件结构无效`);
|
|
if (record.readUInt32LE(0) !== ZIP64_END_SIGNATURE) throw new Error(`${label}文件结构无效`);
|
|
entries = record.readBigUInt64LE(32);
|
|
} else {
|
|
entries = BigInt(tail.readUInt16LE(relativeEndOffset + 10));
|
|
}
|
|
assertZipEntryCountValue(entries, maxEntries, label);
|
|
return size - absoluteEndOffset;
|
|
} finally {
|
|
await file.close();
|
|
}
|
|
}
|
|
|
|
export function assertArchiveLimits(
|
|
entries: ArchiveEntryLike[],
|
|
maxEntries: number,
|
|
maxUncompressedSize: number | undefined,
|
|
label: string,
|
|
): void {
|
|
if (entries.length > maxEntries) {
|
|
throw new Error(`${label}文件数量超过限制(最多 ${maxEntries} 个)`);
|
|
}
|
|
let total = 0;
|
|
for (const entry of entries) {
|
|
if (entry.isDirectory) continue;
|
|
const size = Number(entry.header?.size ?? 0);
|
|
if (!Number.isSafeInteger(size) || size < 0) throw new Error(`${label}包含无效文件大小`);
|
|
total += size;
|
|
if (maxUncompressedSize !== undefined && total > maxUncompressedSize) {
|
|
throw new Error(`${label}解压后总大小超过限制`);
|
|
}
|
|
}
|
|
}
|
|
|
|
export async function readArchiveEntryBuffer(
|
|
entry: Pick<ArchiveStreamEntryLike, 'stream'>,
|
|
maxBytes: number,
|
|
overflowMessage: string,
|
|
onProgress?: () => Promise<void>,
|
|
): Promise<Buffer> {
|
|
const stream = entry.stream();
|
|
const chunks: Buffer[] = [];
|
|
let total = 0;
|
|
let progressBytes = 0;
|
|
try {
|
|
for await (const chunk of stream) {
|
|
const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
total += data.length;
|
|
if (total > maxBytes) throw new Error(overflowMessage);
|
|
chunks.push(data);
|
|
progressBytes += data.length;
|
|
if (onProgress && progressBytes >= ARCHIVE_PROGRESS_INTERVAL_BYTES) {
|
|
progressBytes = 0;
|
|
await onProgress();
|
|
}
|
|
}
|
|
} catch (error) {
|
|
stream.destroy();
|
|
throw error;
|
|
}
|
|
return Buffer.concat(chunks, total);
|
|
}
|
|
|
|
export async function assertArchiveActualSize(
|
|
entries: ArchiveStreamEntryLike[],
|
|
maxUncompressedSize: number,
|
|
label: string,
|
|
onProgress?: () => Promise<void>,
|
|
): Promise<void> {
|
|
let total = 0;
|
|
let progressBytes = 0;
|
|
for (const entry of entries) {
|
|
const stream = entry.stream();
|
|
try {
|
|
for await (const chunk of stream) {
|
|
const size = Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(chunk);
|
|
total += size;
|
|
if (total > maxUncompressedSize) throw new Error(`${label}解压后总大小超过限制`);
|
|
progressBytes += size;
|
|
if (onProgress && progressBytes >= ARCHIVE_PROGRESS_INTERVAL_BYTES) {
|
|
progressBytes = 0;
|
|
await onProgress();
|
|
}
|
|
}
|
|
} catch (error) {
|
|
stream.destroy();
|
|
throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
export function cellToString(value: unknown): string {
|
|
if (value === null || value === undefined) return '';
|
|
if (value instanceof Date) {
|
|
const pad = (part: number) => String(part).padStart(2, '0');
|
|
return `${value.getUTCFullYear()}-${pad(value.getUTCMonth() + 1)}-${pad(value.getUTCDate())} ${pad(value.getUTCHours())}:${pad(value.getUTCMinutes())}:${pad(value.getUTCSeconds())}`;
|
|
}
|
|
if (typeof value === 'object') {
|
|
const item = value as Record<string, unknown>;
|
|
if (typeof item.text === 'string') return item.text.trim();
|
|
if (item.result !== undefined && item.result !== null) return String(item.result).trim();
|
|
if (Array.isArray(item.richText)) {
|
|
return item.richText.map((part: any) => String(part?.text ?? '')).join('').trim();
|
|
}
|
|
if (item.hyperlink) return String(item.hyperlink).trim();
|
|
}
|
|
return String(value).trim();
|
|
}
|
|
|
|
function isValidCalendarTime(year: number, month: number, day: number, hour: number, minute: number, second: number): boolean {
|
|
const calendar = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
|
|
return (
|
|
calendar.getUTCFullYear() === year &&
|
|
calendar.getUTCMonth() === month - 1 &&
|
|
calendar.getUTCDate() === day &&
|
|
calendar.getUTCHours() === hour &&
|
|
calendar.getUTCMinutes() === minute &&
|
|
calendar.getUTCSeconds() === second
|
|
);
|
|
}
|
|
|
|
export function parseOutboundDate(value?: string): Date | undefined | null {
|
|
const text = (value || '').trim();
|
|
if (!text) return undefined;
|
|
|
|
const local = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?$/.exec(text);
|
|
if (local) {
|
|
const [, y, m, d, hh, mm, ss = '0'] = local;
|
|
const parts = [y, m, d, hh, mm, ss].map(Number);
|
|
const [year, month, day, hour, minute, second] = parts;
|
|
if (!isValidCalendarTime(year, month, day, hour, minute, second)) return null;
|
|
// 模板中的无时区时间按中国业务时区(UTC+8)解释,避免部署服务器时区影响结果。
|
|
return new Date(Date.UTC(year, month - 1, day, hour - 8, minute, second));
|
|
}
|
|
|
|
const iso = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,3})?)?(?:Z|[+-]\d{2}:\d{2})$/.exec(text);
|
|
if (iso) {
|
|
const [, y, m, d, hh, mm, ss = '0'] = iso;
|
|
if (!isValidCalendarTime(Number(y), Number(m), Number(d), Number(hh), Number(mm), Number(ss))) return null;
|
|
const parsed = new Date(text);
|
|
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export function normalizeImagePath(raw: string): string {
|
|
const path = raw.trim();
|
|
if (!path) return '';
|
|
if (path.includes('\\') || path.includes('..') || path.startsWith('/') || /^[a-z]:/i.test(path)) {
|
|
throw new Error(`图片路径不安全:${raw}`);
|
|
}
|
|
if (!/^images\/[^/][\w.\- /()\u4e00-\u9fa5]+$/i.test(path)) {
|
|
throw new Error(`图片必须位于 images 目录:${raw}`);
|
|
}
|
|
const ext = path.slice(path.lastIndexOf('.')).toLowerCase();
|
|
if (!['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) {
|
|
throw new Error(`不支持的图片格式:${raw}`);
|
|
}
|
|
return path;
|
|
}
|
|
|
|
export function canonicalImagePath(path: string): string {
|
|
return path.toLocaleLowerCase('en-US');
|
|
}
|
|
|
|
export function mimeOfImagePath(path: string): string {
|
|
const ext = path.slice(path.lastIndexOf('.')).toLowerCase();
|
|
if (ext === '.png') return 'image/png';
|
|
if (ext === '.webp') return 'image/webp';
|
|
return 'image/jpeg';
|
|
}
|