fix: 加固批量出库导入流程

This commit is contained in:
Nixevol
2026-07-14 07:02:41 +08:00
parent 3c74f03e7e
commit 9644f5c128
54 changed files with 5292 additions and 516 deletions
@@ -0,0 +1,143 @@
export const OUTBOUND_IMPORT_MAX_ROWS = 10_000;
export const OUTBOUND_IMPORT_MAX_COLUMNS = 64;
export const OUTBOUND_IMPORT_MAX_ZIP_ENTRIES = 20_002;
export const OUTBOUND_IMPORT_MAX_UNCOMPRESSED_SIZE = 120 * 1024 * 1024;
export const OUTBOUND_IMPORT_MAX_XLSX_SIZE = 10 * 1024 * 1024;
export const OUTBOUND_IMPORT_MAX_XLSX_ENTRIES = 256;
export const OUTBOUND_IMPORT_MAX_XLSX_UNCOMPRESSED_SIZE = 50 * 1024 * 1024;
export const OUTBOUND_IMPORT_MAX_IMAGE_SIZE = 10 * 1024 * 1024;
export const OUTBOUND_IMPORT_MAX_IMAGES_PER_ROW = 20;
export const OUTBOUND_IMPORT_MAX_IMAGE_PIXELS = 40_000_000;
export const OUTBOUND_IMPORT_MAX_IMAGE_REFERENCES = 20_000;
export const OUTBOUND_IMPORT_MAX_STORED_IMAGE_SIZE = 200 * 1024 * 1024;
interface ArchiveEntryLike {
isDirectory: boolean;
header: { size: number };
}
export function assertZipEntryCount(buffer: Buffer, maxEntries: number, label: string): void {
const minEndOffset = Math.max(0, buffer.length - 65_557);
for (let offset = buffer.length - 22; offset >= minEndOffset; offset--) {
if (buffer.readUInt32LE(offset) !== 0x06054b50) continue;
const commentLength = buffer.readUInt16LE(offset + 20);
if (offset + 22 + commentLength !== buffer.length) continue;
const entries = buffer.readUInt16LE(offset + 10);
if (entries === 0xffff || entries > maxEntries) {
throw new Error(`${label}文件数量超过限制(最多 ${maxEntries} 个)`);
}
return;
}
throw new Error(`${label}文件结构无效`);
}
export function assertArchiveLimits(
entries: ArchiveEntryLike[],
maxEntries: number,
maxUncompressedSize: number,
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 (total > maxUncompressedSize) {
throw new Error(`${label}解压后总大小超过限制`);
}
}
}
export function assertStoredImageBudget(referenceCount: number, totalBytes: number): void {
if (referenceCount > OUTBOUND_IMPORT_MAX_IMAGE_REFERENCES) {
throw new Error(`出库图片引用总数超过限制(最多 ${OUTBOUND_IMPORT_MAX_IMAGE_REFERENCES} 张)`);
}
if (totalBytes > OUTBOUND_IMPORT_MAX_STORED_IMAGE_SIZE) {
throw new Error(`出库图片按引用累计大小超过限制(最多 ${OUTBOUND_IMPORT_MAX_STORED_IMAGE_SIZE / 1024 / 1024}MB)`);
}
}
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().replace(/^image\//i, 'images/');
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';
}