119 lines
5.3 KiB
TypeScript
119 lines
5.3 KiB
TypeScript
import yauzl from "yauzl";
|
||
import iconv from "iconv-lite";
|
||
import { MaterialPackValidationError } from "./types.js";
|
||
import {
|
||
normalizeMaterialPackFilePolicy,
|
||
type MaterialPackFilePolicy,
|
||
type MaterialPackFilePolicyPatch
|
||
} from "./policy.js";
|
||
|
||
export const MATERIAL_PACK_LIMITS = { maxEntries: 1000, maxTotalSize: 500 * 1024 * 1024, maxCompressionRatio: 150 };
|
||
|
||
export type ZipEntry = { fileName: string; uncompressedSize: number; compressedSize: number; raw: unknown };
|
||
|
||
export async function readZipEntries(buffer: Uint8Array): Promise<ZipEntry[]> {
|
||
return new Promise((resolve, reject) => {
|
||
yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, autoClose: true, decodeStrings: false }, (openError: Error | null, zipFile: any) => {
|
||
if (openError || !zipFile) return reject(openError ?? new Error("无法打开 ZIP"));
|
||
const entries: ZipEntry[] = [];
|
||
zipFile.readEntry();
|
||
zipFile.on("entry", (entry: any) => {
|
||
const fileName = decodeZipEntryName(entry);
|
||
if (!fileName.endsWith("/") && !isJunk(fileName)) {
|
||
entries.push({ fileName, uncompressedSize: entry.uncompressedSize, compressedSize: entry.compressedSize, raw: entry });
|
||
}
|
||
zipFile.readEntry();
|
||
});
|
||
zipFile.on("end", () => resolve(entries));
|
||
zipFile.on("error", reject);
|
||
});
|
||
});
|
||
}
|
||
|
||
function decodeZipEntryName(entry: any): string {
|
||
const raw: Buffer = Buffer.isBuffer(entry.fileName)
|
||
? entry.fileName
|
||
: Buffer.from(String(entry.fileName), "binary");
|
||
const utf8 = raw.toString("utf8");
|
||
if (!utf8.includes("\uFFFD")) return utf8;
|
||
const gbk = iconv.decode(raw, "gbk");
|
||
if (!gbk.includes("\uFFFD")) return gbk;
|
||
return utf8;
|
||
}
|
||
|
||
function isJunk(name: string): boolean {
|
||
const base = name.split("/").pop() ?? "";
|
||
return name.split("/").includes("__MACOSX") || base === ".DS_Store" || base.startsWith("._") || base.startsWith(".~") || base.startsWith("~$");
|
||
}
|
||
|
||
export function validatePackEntries(entries: ZipEntry[], policy?: MaterialPackFilePolicyPatch): void {
|
||
const errors: string[] = [];
|
||
const filePolicy = normalizeMaterialPackFilePolicy(policy);
|
||
if (entries.length > MATERIAL_PACK_LIMITS.maxEntries) errors.push(`文件数超过 ${MATERIAL_PACK_LIMITS.maxEntries}`);
|
||
const total = entries.reduce((sum, entry) => sum + entry.uncompressedSize, 0);
|
||
if (total > MATERIAL_PACK_LIMITS.maxTotalSize) errors.push("解压后总大小超过 500MB");
|
||
for (const entry of entries) {
|
||
if (entry.fileName.startsWith("/") || entry.fileName.split("/").includes("..")) errors.push(`存在不安全路径: ${entry.fileName}`);
|
||
if (entry.compressedSize > 0 && entry.uncompressedSize / entry.compressedSize > MATERIAL_PACK_LIMITS.maxCompressionRatio) errors.push(`压缩比超过 150: ${entry.fileName}`);
|
||
if (entry.fileName === "信息表.xlsx") continue;
|
||
validateAttachmentFile(entry, filePolicy, errors);
|
||
}
|
||
const info = entries.find((entry) => entry.fileName === "信息表.xlsx");
|
||
if (!info) errors.push("ZIP 根目录缺少精确名为「信息表.xlsx」的文件");
|
||
if (entries.some((entry) => entry.fileName.toLowerCase().endsWith(".zip"))) errors.push("不允许嵌套 ZIP");
|
||
if (errors.length) throw new MaterialPackValidationError(errors);
|
||
}
|
||
|
||
function validateAttachmentFile(
|
||
entry: ZipEntry,
|
||
policy: MaterialPackFilePolicy,
|
||
errors: string[]
|
||
): void {
|
||
const extension = getFileExtension(entry.fileName);
|
||
if (!extension || !policy.allowedExtensions.includes(extension)) {
|
||
errors.push(
|
||
`附件后缀不在白名单中: ${entry.fileName}(允许: ${policy.allowedExtensions.join(", ")})`
|
||
);
|
||
}
|
||
if (entry.uncompressedSize < policy.minFileSizeBytes) {
|
||
errors.push(
|
||
`附件文件过小: ${entry.fileName}(${entry.uncompressedSize} B,小于最小值 ${policy.minFileSizeBytes} B)`
|
||
);
|
||
}
|
||
if (
|
||
policy.maxFileSizeBytes !== undefined &&
|
||
policy.maxFileSizeBytes !== null &&
|
||
entry.uncompressedSize > policy.maxFileSizeBytes
|
||
) {
|
||
errors.push(
|
||
`附件文件过大: ${entry.fileName}(${entry.uncompressedSize} B,大于最大值 ${policy.maxFileSizeBytes} B)`
|
||
);
|
||
}
|
||
}
|
||
|
||
function getFileExtension(fileName: string): string {
|
||
const baseName = fileName.split("/").pop() ?? fileName;
|
||
const dotIndex = baseName.lastIndexOf(".");
|
||
return dotIndex > 0 ? baseName.slice(dotIndex).toLowerCase() : "";
|
||
}
|
||
|
||
export function extractZipEntry(buffer: Uint8Array, target: ZipEntry): Promise<Buffer> {
|
||
return new Promise((resolve, reject) => {
|
||
yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, autoClose: true, decodeStrings: false }, (openError: Error | null, zipFile: any) => {
|
||
if (openError || !zipFile) return reject(openError ?? new Error("无法打开 ZIP"));
|
||
zipFile.readEntry();
|
||
zipFile.on("entry", (entry: any) => {
|
||
if (decodeZipEntryName(entry) !== target.fileName) return zipFile.readEntry();
|
||
zipFile.openReadStream(entry, (error: Error | null, stream: any) => {
|
||
if (error || !stream) return reject(error ?? new Error(`无法读取 ${target.fileName}`));
|
||
const chunks: Buffer[] = [];
|
||
stream.on("data", (chunk: Buffer) => chunks.push(chunk));
|
||
stream.on("end", () => resolve(Buffer.concat(chunks)));
|
||
stream.on("error", reject);
|
||
});
|
||
});
|
||
zipFile.on("error", reject);
|
||
});
|
||
});
|
||
}
|