feat(import): harden untrusted spreadsheet boundaries

This commit is contained in:
2026-03-30 08:02:52 +02:00
parent fac8c1c3a5
commit f6daf21983
13 changed files with 561 additions and 76 deletions
+212 -28
View File
@@ -1,41 +1,225 @@
let _xlsx: typeof import("xlsx") | null = null;
const XLSX_EXTENSION = ".xlsx";
const CSV_EXTENSION = ".csv";
const XLS_EXTENSION = ".xls";
async function getXLSX() {
if (!_xlsx) {
_xlsx = await import("xlsx");
export const MAX_BROWSER_SPREADSHEET_BYTES = 10 * 1024 * 1024;
type ExcelJsModule = typeof import("exceljs");
let _excelJs: ExcelJsModule | null = null;
function getFileExtension(fileName: string): string {
const dotIndex = fileName.lastIndexOf(".");
if (dotIndex < 0) {
return "";
}
return _xlsx;
return fileName.slice(dotIndex).toLowerCase();
}
function isSupportedSpreadsheetExtension(extension: string): boolean {
return extension === XLSX_EXTENSION || extension === CSV_EXTENSION;
}
function normalizeCellString(value: unknown): string {
if (value === undefined || value === null) {
return "";
}
if (value instanceof Date) {
return value.toISOString();
}
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return String(value);
}
if (typeof value === "object") {
const record = value as Record<string, unknown>;
if ("result" in record) {
return normalizeCellString(record.result);
}
if ("text" in record && typeof record.text === "string") {
return record.text;
}
if ("hyperlink" in record && typeof record.hyperlink === "string") {
return record.hyperlink;
}
if ("richText" in record && Array.isArray(record.richText)) {
return record.richText
.map((part) => {
if (part && typeof part === "object" && "text" in part) {
const text = (part as { text?: unknown }).text;
return typeof text === "string" ? text : "";
}
return "";
})
.join("");
}
if ("error" in record && typeof record.error === "string") {
return record.error;
}
}
return String(value);
}
function parseCsvMatrix(input: string): string[][] {
const text = input.replace(/^\uFEFF/u, "");
const rows: string[][] = [];
let currentRow: string[] = [];
let currentCell = "";
let inQuotes = false;
for (let index = 0; index < text.length; index += 1) {
const character = text[index];
const nextCharacter = text[index + 1];
if (character === "\"") {
if (inQuotes && nextCharacter === "\"") {
currentCell += "\"";
index += 1;
} else {
inQuotes = !inQuotes;
}
continue;
}
if (!inQuotes && character === ",") {
currentRow.push(currentCell);
currentCell = "";
continue;
}
if (!inQuotes && (character === "\n" || character === "\r")) {
if (character === "\r" && nextCharacter === "\n") {
index += 1;
}
currentRow.push(currentCell);
rows.push(currentRow);
currentRow = [];
currentCell = "";
continue;
}
currentCell += character;
}
if (currentCell.length > 0 || currentRow.length > 0) {
currentRow.push(currentCell);
rows.push(currentRow);
}
return rows;
}
function matrixToObjects(rows: string[][]): Record<string, string>[] {
const headers = (rows[0] ?? []).map((header) => header.trim());
if (headers.length === 0) {
return [];
}
return rows
.slice(1)
.filter((row) => row.some((value) => value.trim() !== ""))
.map((row) =>
headers.reduce<Record<string, string>>((record, header, index) => {
record[header] = row[index] ?? "";
return record;
}, {}),
);
}
async function getExcelJS() {
if (!_excelJs) {
_excelJs = await import("exceljs");
}
return _excelJs;
}
export function assertSpreadsheetFile(
file: File,
options?: { allowCsv?: boolean; contextLabel?: string },
): void {
const extension = getFileExtension(file.name);
const allowCsv = options?.allowCsv ?? true;
const contextLabel = options?.contextLabel ?? "spreadsheet import";
if (file.size <= 0) {
throw new Error(`The selected file is empty and cannot be used for ${contextLabel}.`);
}
if (file.size > MAX_BROWSER_SPREADSHEET_BYTES) {
throw new Error(
`The selected file exceeds the ${MAX_BROWSER_SPREADSHEET_BYTES} byte limit for ${contextLabel}.`,
);
}
if (extension === XLS_EXTENSION) {
throw new Error(
"Legacy .xls files are not supported. Please resave the workbook as .xlsx or export it as .csv.",
);
}
if (extension === XLSX_EXTENSION) {
return;
}
if (allowCsv && extension === CSV_EXTENSION) {
return;
}
if (allowCsv) {
throw new Error("Unsupported file type. Please upload a .xlsx or .csv file.");
}
throw new Error("Unsupported file type. Please upload a .xlsx file.");
}
async function parseXlsxSpreadsheet(file: File): Promise<Record<string, string>[]> {
const ExcelJS = await getExcelJS();
const workbook = new ExcelJS.Workbook();
const buffer = await file.arrayBuffer();
await workbook.xlsx.load(buffer);
const worksheet = workbook.worksheets[0];
if (!worksheet) {
return [];
}
const rows: string[][] = [];
for (let rowNumber = 1; rowNumber <= worksheet.rowCount; rowNumber += 1) {
const row = worksheet.getRow(rowNumber);
const cells: string[] = [];
for (let columnNumber = 1; columnNumber <= row.cellCount; columnNumber += 1) {
cells.push(normalizeCellString(row.getCell(columnNumber).value));
}
rows.push(cells);
}
return matrixToObjects(rows);
}
/**
* Parse an Excel (.xlsx, .xls) or CSV file to an array of row objects.
* Parse a spreadsheet import file to an array of row objects.
* Keys come from the first row (headers).
*/
export async function parseSpreadsheet(file: File): Promise<Record<string, string>[]> {
const XLSX = await getXLSX();
const buffer = await file.arrayBuffer();
const data = new Uint8Array(buffer);
const workbook = XLSX.read(data, { type: "array" });
const sheetName = workbook.SheetNames[0];
if (!sheetName) {
return [];
assertSpreadsheetFile(file);
if (getFileExtension(file.name) === CSV_EXTENSION) {
return matrixToObjects(parseCsvMatrix(await file.text()));
}
const sheet = workbook.Sheets[sheetName];
if (!sheet) {
return [];
}
return XLSX.utils.sheet_to_json<Record<string, string>>(sheet, {
raw: false,
defval: "",
});
return parseXlsxSpreadsheet(file);
}
export function isSpreadsheetFile(file: File): boolean {
return (
file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
file.type === "application/vnd.ms-excel" ||
file.name.endsWith(".xlsx") ||
file.name.endsWith(".xls") ||
file.name.endsWith(".csv")
);
return isSupportedSpreadsheetExtension(getFileExtension(file.name));
}