29 lines
1.2 KiB
TypeScript
29 lines
1.2 KiB
TypeScript
import { zipNames } from "./xlsx.ts";
|
|
|
|
export const MAX_FILE_BYTES = 1024 * 1024;
|
|
|
|
export const CONTENT_TYPES = {
|
|
pdf: "application/pdf",
|
|
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
} as const;
|
|
|
|
const NAME_RE = /^[\p{L}\p{N}_ .()-]{1,100}\.(pdf|xlsx)$/u;
|
|
|
|
/** Расширение из безопасного имени файла или null. */
|
|
export function fileKind(name: string): "pdf" | "xlsx" | null {
|
|
if (name.includes("..") || name.startsWith(".")) return null;
|
|
const m = NAME_RE.exec(name);
|
|
return m ? (m[1] as "pdf" | "xlsx") : null;
|
|
}
|
|
|
|
/** Содержимое должно соответствовать расширению (по сигнатурам, не по заявленному типу). */
|
|
export function validateFile(name: string, data: Buffer): boolean {
|
|
const kind = fileKind(name);
|
|
if (!kind || data.length === 0 || data.length > MAX_FILE_BYTES) return false;
|
|
if (kind === "pdf") {
|
|
return data.subarray(0, 5).toString("latin1") === "%PDF-" && data.subarray(-1024).toString("latin1").includes("%%EOF");
|
|
}
|
|
const names = zipNames(data);
|
|
return !!names && names.includes("[Content_Types].xml") && names.includes("xl/workbook.xml");
|
|
}
|