From 94aa8562f95e0144016abd61d556abf20e4c3817 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 11:22:36 +0100 Subject: [PATCH 01/22] JSE-71: tests for inspect() Behaviour tests (result shape, part kinds, every refusal read makes, the signal, peak heap against read on a 1,000,000-cell sheet), a differential test against read over the fixtures, the conformance corpus and generated hostile files, and a seeded fuzz of mutated workbooks. --- .../javascript-excel/test/entries.test.ts | 2 +- .../test/read/inspect-check.ts | 74 +++ .../test/read/inspect-differential.test.ts | 90 ++++ .../test/read/inspect-files.ts | 420 ++++++++++++++++++ .../test/read/inspect-fuzz.test.ts | 227 ++++++++++ .../test/read/inspect.test.ts | 316 +++++++++++++ 6 files changed, 1128 insertions(+), 1 deletion(-) create mode 100644 packages/javascript-excel/test/read/inspect-check.ts create mode 100644 packages/javascript-excel/test/read/inspect-differential.test.ts create mode 100644 packages/javascript-excel/test/read/inspect-files.ts create mode 100644 packages/javascript-excel/test/read/inspect-fuzz.test.ts create mode 100644 packages/javascript-excel/test/read/inspect.test.ts diff --git a/packages/javascript-excel/test/entries.test.ts b/packages/javascript-excel/test/entries.test.ts index 9c1ce8a..1e67929 100644 --- a/packages/javascript-excel/test/entries.test.ts +++ b/packages/javascript-excel/test/entries.test.ts @@ -19,7 +19,7 @@ describe("entries", () => { }); it("/read exports the documented API", () => { - expect(Object.keys(read).sort()).toEqual(["DEFAULT_READ_LIMITS", "detectFormat", "isDataLossWarning", "read", "readSheetNames"]); + expect(Object.keys(read).sort()).toEqual(["DEFAULT_READ_LIMITS", "detectFormat", "inspect", "isDataLossWarning", "read", "readSheetNames"]); }); it("/dom exports the documented API", () => { diff --git a/packages/javascript-excel/test/read/inspect-check.ts b/packages/javascript-excel/test/read/inspect-check.ts new file mode 100644 index 0000000..5644d8c --- /dev/null +++ b/packages/javascript-excel/test/read/inspect-check.ts @@ -0,0 +1,74 @@ +// The check behind the inspect differential and fuzz tests (JSE-71). +import { expect } from "vitest"; +import { isExcelError } from "../../src/index"; +import type { InspectResult, ReadLimits, ReadOptions, ReadResult } from "../../src/read"; + +export interface Outcome { + ok?: T; + err?: unknown; +} + +export async function outcome(p: Promise): Promise> { + try { + return { ok: await p }; + } catch (err) { + return { err }; + } +} + +export function describeError(err: unknown): string { + const e = err as { name?: string; code?: string; message?: string }; + return `${e.name}/${e.code ?? "-"}: ${e.message}`; +} + +/** + * The guarantee for one file and one set of limits, against read with its + * default options: read throws => inspect throws the same class, code and + * details; read succeeds => inspect reports exactly read's UNSUPPORTED_PART + * warnings and the same sheets, or refuses the file (a check read does not make). + */ +export function checkPair(label: string, r: Outcome, i: Outcome): "both-refuse" | "inspect-only" | "both-accept" { + if (r.err !== undefined) { + expect(i.err, `${label}: read threw ${describeError(r.err)}; inspect accepted`).toBeDefined(); + const re = r.err as { constructor: unknown; code?: string; details?: unknown }; + const ie = i.err as { constructor: unknown; code?: string; details?: unknown }; + if (!isExcelError(r.err)) { + // TypeError for invalid limits, or a non-ExcelError from the platform: the same kind. + expect(ie.constructor, label).toBe(re.constructor); + return "both-refuse"; + } + expect(ie.constructor, `${label}: ${describeError(i.err)} vs ${describeError(r.err)}`).toBe(re.constructor); + expect(ie.code, `${label}: ${describeError(i.err)} vs ${describeError(r.err)}`).toBe(re.code); + expect(ie.details, label).toEqual(re.details); + return "both-refuse"; + } + if (i.err !== undefined) { + expect(isExcelError(i.err), `${label}: inspect threw ${describeError(i.err)}`).toBe(true); + return "inspect-only"; + } + const read = r.ok!; + const got = i.ok!; + const unsupported = read.warnings.filter((w) => w.code === "UNSUPPORTED_PART"); + expect(got.warnings, label).toEqual(unsupported); + for (const w of unsupported) expect(got.partKinds, label).toContain(w.partKind); + expect(got.sheets.map((s) => [s.name, s.state, s.dimension]), label).toEqual(read.workbook.sheets.map((s) => [s.name, s.state ?? "visible", s.dimension])); + return "both-accept"; +} + +/** Read options that read less than the defaults: what read refuses with them, inspect refuses too. */ +export const LESS: ReadOptions[] = [{ styles: false }, { formulas: false }, { sheets: [0] }, { richText: "plain", dates: "serial", rawText: true, dateZone: "utc" }]; + +export const TIGHT: Partial = { + maxEntryBytes: 64 * 1024, + maxTotalBytes: 512 * 1024, + maxRatio: 40, + maxXmlDepth: 12, + maxXmlTokenLength: 600, + maxSheets: 6, + maxCells: 400, + maxItems: 200, + maxSharedStrings: 100, + maxCellTextLength: 64, + maxColumns: 8, + maxWarnings: 5, +}; diff --git a/packages/javascript-excel/test/read/inspect-differential.test.ts b/packages/javascript-excel/test/read/inspect-differential.test.ts new file mode 100644 index 0000000..437736a --- /dev/null +++ b/packages/javascript-excel/test/read/inspect-differential.test.ts @@ -0,0 +1,90 @@ +// JSE-71: inspect refuses everything read refuses, under the same limits, and +// reports every part kind read reports. Checked over the repository's +// fixtures, the conformance corpus and generated hostile files, under the +// default limits, a tight set and each hostile file's own limits. +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { isExcelError, toUint8Array } from "../../src/index"; +import { inspect, read, type ReadLimits } from "../../src/read"; +import { ALL } from "../conformance/corpus"; +import { checkPair, describeError, LESS, outcome, TIGHT } from "./inspect-check"; +import { hostileFiles } from "./inspect-files"; + +interface Case { + name: string; + bytes: Uint8Array; + limits: Array | undefined>; +} + +async function corpus(): Promise { + const cases: Case[] = []; + const fixtures = join(__dirname, "../fixtures"); + for (const dir of ["read", "import/xlsx"]) { + for (const f of readdirSync(join(fixtures, dir)).filter((n) => n.endsWith(".xlsx"))) { + cases.push({ name: `fixture ${dir}/${f}`, bytes: new Uint8Array(readFileSync(join(fixtures, dir, f))), limits: [undefined, TIGHT] }); + } + } + for (const entry of ALL) { + if (entry.heavy) continue; + cases.push({ name: `conformance ${entry.id}`, bytes: await toUint8Array(entry.workbook(), entry.options), limits: [undefined, TIGHT] }); + } + for (const h of hostileFiles()) { + cases.push({ name: `hostile: ${h.name}`, bytes: await h.bytes(), limits: h.limits ? [undefined, h.limits, TIGHT] : [undefined, TIGHT] }); + } + return cases; +} + +describe("inspect vs read: the differential test", () => { + it("over the fixtures, the conformance corpus and the hostile files: read refuses => inspect refuses the same way; read reports a part kind => inspect reports it", async () => { + const cases = await corpus(); + const tally = { files: cases.length, runs: 0, "both-refuse": 0, "inspect-only": 0, "both-accept": 0, lessOptionRuns: 0 }; + const inspectOnly: string[] = []; + for (const c of cases) { + for (const limits of c.limits) { + const label = `${c.name} [${limits === undefined ? "default limits" : JSON.stringify(limits)}]`; + const options = limits === undefined ? {} : { limits }; + const i = await outcome(inspect(c.bytes, options)); + const verdict = checkPair(label, await outcome(read(c.bytes, options)), i); + tally.runs++; + tally[verdict]++; + if (verdict === "inspect-only") inspectOnly.push(`${label}: ${describeError(i.err)}`); + for (const more of LESS) { + const r = await outcome(read(c.bytes, { ...more, ...options })); + tally.lessOptionRuns++; + if (r.err !== undefined) expect(i.err, `${label} with ${JSON.stringify(more)}: read threw ${describeError(r.err)}`).toBeDefined(); + } + } + } + console.log(`inspect differential: ${JSON.stringify(tally)}\ninspect refused, read accepted:\n ${inspectOnly.join("\n ")}`); + expect(tally.files).toBeGreaterThan(80); + expect(tally["both-refuse"]).toBeGreaterThan(40); + expect(tally["both-accept"]).toBeGreaterThan(40); + }, 120_000); + + it("the hostile files are refused by inspect under their limits", async () => { + for (const h of hostileFiles()) { + if (/^(xlsm|xltm|xltx|macro sheet|external link|connections|OLE object|query table|everything at once|malformed \(optional\))/.test(h.name)) continue; + const i = await outcome(inspect(await h.bytes(), h.limits ? { limits: h.limits } : {})); + expect(i.err, h.name).toBeDefined(); + expect(isExcelError(i.err), `${h.name}: ${describeError(i.err)}`).toBe(true); + } + }); + + it("every DOCTYPE file is refused with XML_DTD_FORBIDDEN or, where it breaks the markup read checks, XML_MALFORMED", async () => { + for (const h of hostileFiles().filter((f) => f.name.startsWith("DTD"))) { + const i = await outcome(inspect(await h.bytes())); + expect((i.err as { code?: string }).code, h.name).toMatch(/^XML_(DTD_FORBIDDEN|MALFORMED)$/); + } + }); + + it("the part kinds files report what read reports", async () => { + for (const h of hostileFiles().filter((f) => /^(xlsm|xltm|macro sheet|external link|connections|OLE object|query table|everything)/.test(f.name))) { + const bytes = await h.bytes(); + const [r, i] = [await read(bytes), await inspect(bytes)]; + const kinds = r.warnings.filter((w) => w.code === "UNSUPPORTED_PART").map((w) => w.partKind); + expect(i.partKinds, h.name).toEqual(kinds); + expect(kinds.length, h.name).toBeGreaterThan(4); + } + }); +}); diff --git a/packages/javascript-excel/test/read/inspect-files.ts b/packages/javascript-excel/test/read/inspect-files.ts new file mode 100644 index 0000000..3f51671 --- /dev/null +++ b/packages/javascript-excel/test/read/inspect-files.ts @@ -0,0 +1,420 @@ +// Workbooks for the inspect() tests (JSE-71): a package with one part of every +// kind the reader reads or reports, and hostile variants of it. Everything is +// generated here; no third-party files. +import { writeZip, type ZipWriteEntry } from "../../src/internal/zip/write"; +import { NS } from "./build"; + +const REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; +const PKG_REL = "http://schemas.openxmlformats.org/package/2006/relationships"; +const CT = "application/vnd.openxmlformats-officedocument"; +const MAIN: Readonly> = { + xlsx: `${CT}.spreadsheetml.sheet.main+xml`, + xlsm: "application/vnd.ms-excel.sheet.macroEnabled.main+xml", + xltx: `${CT}.spreadsheetml.template.main+xml`, + xltm: "application/vnd.ms-excel.template.macroEnabled.main+xml", + xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.main", +}; + +export type Parts = Map; + +const rel = (id: string, type: string, target: string, external = false): string => + ``; +const rels = (items: string[]): string => `${items.join("")}`; + +export interface RichOptions { + format?: keyof typeof MAIN; + /** Extra workbook relationships, e.g. externalLink, connections. */ + externalLink?: boolean; + connections?: boolean; + /** A macro sheet in the sheet list. */ + macrosheet?: boolean; + /** An OLE object and a query table on the first sheet. */ + oleObject?: boolean; + queryTable?: boolean; + /** Rows of numbers on the second sheet. */ + rows?: number; +} + +/** + * A workbook with a part of every kind the reader parses (content types, + * relationships, workbook, styles, theme, shared strings, three document + * property parts, two worksheets) and of several it only reports (drawing, + * image, comments, VML, chart sheet, VBA, external link, connections, ...). + */ +export function richParts(o: RichOptions = {}): Parts { + const format = o.format ?? "xlsx"; + const p: Parts = new Map(); + const overrides: string[] = [ + ``, + ``, + ``, + ``, + ``, + ``, + ``, + ``, + ``, + ``, + ``, + ``, + ]; + const wbRels = [ + rel("rId1", "worksheet", "worksheets/sheet1.xml"), + rel("rId2", "worksheet", "worksheets/sheet2.xml"), + rel("rId3", "chartsheet", "chartsheets/sheet1.xml"), + rel("rId4", "styles", "styles.xml"), + rel("rId5", "sharedStrings", "sharedStrings.xml"), + rel("rId6", "theme", "theme/theme1.xml"), + ]; + const sheets = [ + ``, + ``, + ``, + ]; + if (format === "xlsm" || format === "xltm") { + wbRels.push(rel("rId7", "http://schemas.microsoft.com/office/2006/relationships/vbaProject", "vbaProject.bin")); + p.set("xl/vbaProject.bin", new Uint8Array([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1, 1, 2, 3, 4])); + } + if (o.externalLink) { + wbRels.push(rel("rId8", "externalLink", "externalLinks/externalLink1.xml")); + overrides.push(``); + p.set("xl/externalLinks/externalLink1.xml", ``); + p.set("xl/externalLinks/_rels/externalLink1.xml.rels", rels([rel("rId1", "externalLinkPath", "file:///C:/other.xlsx", true)])); + } + if (o.connections) { + wbRels.push(rel("rId9", "connections", "connections.xml")); + p.set("xl/connections.xml", ``); + } + if (o.macrosheet) { + // The relationship type read maps to 'macrosheet'. (Excel's own xlMacrosheet type is not mapped by read: a separate gap.) + wbRels.push(rel("rId10", "macrosheet", "macrosheets/sheet1.xml")); + sheets.push(``); + p.set("xl/macrosheets/sheet1.xml", ``); + } + p.set( + "[Content_Types].xml", + `` + + `` + + `` + + `${overrides.join("")}`, + ); + p.set( + "_rels/.rels", + rels([ + rel("rId1", "officeDocument", "xl/workbook.xml"), + rel("rId2", "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties", "docProps/core.xml"), + rel("rId3", "extended-properties", "docProps/app.xml"), + rel("rId4", "custom-properties", "docProps/custom.xml"), + ]), + ); + p.set( + "docProps/core.xml", + `Richtests`, + ); + p.set("docProps/app.xml", `tests`); + p.set( + "docProps/custom.xml", + `QA`, + ); + p.set( + "xl/workbook.xml", + `${sheets.join("")}Data!$A$1:$B$2Data!$A$1:$C$3`, + ); + p.set("xl/_rels/workbook.xml.rels", rels(wbRels)); + p.set( + "xl/styles.xml", + `` + + `` + + ``, + ); + p.set("xl/sharedStrings.xml", `NameBold plainThird`); + p.set( + "xl/theme/theme1.xml", + ``, + ); + const sheet1Rels = [ + rel("rId1", "drawing", "../drawings/drawing1.xml"), + rel("rId2", "comments", "../comments1.xml"), + rel("rId3", "vmlDrawing", "../drawings/vmlDrawing1.vml"), + rel("rId4", "hyperlink", "https://example.com/", true), + ]; + if (o.oleObject) { + sheet1Rels.push(rel("rId5", "oleObject", "../embeddings/oleObject1.bin")); + p.set("xl/embeddings/oleObject1.bin", new Uint8Array([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1, 9, 9])); + } + if (o.queryTable) { + sheet1Rels.push(rel("rId6", "queryTable", "../queryTables/queryTable1.xml")); + p.set("xl/queryTables/queryTable1.xml", ``); + } + p.set( + "xl/worksheets/sheet1.xml", + `` + + `` + + `01inline` + + `145306A2*22` + + `214` + + `` + + `&CTitle`, + ); + p.set("xl/worksheets/_rels/sheet1.xml.rels", rels(sheet1Rels)); + const rows: string[] = []; + for (let r = 1; r <= (o.rows ?? 4); r++) rows.push(`${r}2`); + p.set("xl/worksheets/sheet2.xml", `${rows.join("")}`); + p.set("xl/chartsheets/sheet1.xml", ``); + p.set( + "xl/drawings/drawing1.xml", + `4010`, + ); + p.set("xl/drawings/_rels/drawing1.xml.rels", rels([rel("rId1", "image", "../media/image1.png")])); + p.set("xl/media/image1.png", new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0])); + p.set("xl/comments1.xml", `anote`); + // Excel's legacy VML is not well-formed XML (an unclosed
): read never parses it, and inspect must not refuse it. + p.set("xl/drawings/vmlDrawing1.vml", `
note
`); + return p; +} + +/** The parts zipped (deflate unless said otherwise), with a fixed timestamp. */ +export function zipParts(parts: Parts, compression: "deflate" | "store" = "deflate"): Promise { + const entries: ZipWriteEntry[] = [...parts].map(([name, data]) => ({ name, data })); + return writeZip(entries, { compression, modified: new Date(Date.UTC(2024, 0, 1)) }); +} + +export const DTD: string = ']>'; + +/** The XML text with a document type declaration after its XML declaration (or at the start). */ +export function withDtd(xml: string, dtd: string = DTD): string { + const decl = xml.startsWith("") + 2 : 0; + return xml.slice(0, decl) + dtd + xml.slice(decl); +} + +/** Sets the encryption flag (bit 0) on every local and central header. */ +export function markEncrypted(zip: Uint8Array): Uint8Array { + const out = zip.slice(); + const view = new DataView(out.buffer); + for (let i = 0; i + 4 <= out.length; i++) { + const sig = view.getUint32(i, true); + if (sig === 0x04034b50) view.setUint16(i + 6, view.getUint16(i + 6, true) | 1, true); + else if (sig === 0x02014b50) view.setUint16(i + 8, view.getUint16(i + 8, true) | 1, true); + } + return out; +} + +/** The names of every XML part of `richParts` (the parts DTD injection applies to). */ +export function xmlPartNames(parts: Parts): string[] { + return [...parts].filter(([, v]) => typeof v === "string").map(([k]) => k); +} + +export interface Hostile { + name: string; + bytes: () => Promise; + limits?: Record; +} + +/** A sheet body of `n` rows of `cols` number cells. */ +export function numberRows(n: number, cols: number): string { + const out: string[] = []; + for (let r = 1; r <= n; r++) { + let row = ``; + for (let c = 0; c < cols; c++) row += `${r * cols + c}`; + out.push(`${row}`); + } + return `${out.join("")}`; +} + +/** + * Hostile and broken files: one DTD per XML part, zip bombs and ratio bombs, + * every zip limit, encryption, CFB, ODS, xlsb, a zip that is not a workbook, + * truncated and corrupted archives, and the files read reports part kinds for. + */ +export function hostileFiles(): Hostile[] { + const files: Hostile[] = []; + const base = richParts(); + for (const name of xmlPartNames(base)) { + files.push({ + name: `DTD in ${name}`, + bytes: () => { + const p = richParts(); + p.set(name, withDtd(p.get(name) as string)); + return zipParts(p); + }, + }); + } + files.push({ + name: "DTD late in a large sheet (past any row limit)", + bytes: () => { + const p = richParts(); + const body = numberRows(3000, 3); + // A DOCTYPE inside the sheet, after thousands of rows: XML_DTD_FORBIDDEN or XML_MALFORMED, never accepted. + p.set("xl/worksheets/sheet2.xml", `${body.replace("", "")}`); + return zipParts(p); + }, + }); + files.push({ + name: "DTD after the break in a malformed theme (read warns BROKEN_OPTIONAL_PART)", + bytes: () => { + const p = richParts(); + p.set("xl/theme/theme1.xml", `
${DTD}`); + return zipParts(p); + }, + }); + files.push({ + name: "DTD in an unreferenced XML part", + bytes: () => { + const p = richParts(); + p.set("customXml/item1.xml", withDtd(``)); + return zipParts(p); + }, + }); + files.push({ + name: "DTD in a UTF-16 drawing", + bytes: () => { + const p = richParts(); + const xml = withDtd(p.get("xl/drawings/drawing1.xml") as string); + const u16 = new Uint8Array(2 + xml.length * 2); + u16[0] = 0xff; + u16[1] = 0xfe; + for (let i = 0; i < xml.length; i++) { + u16[2 + 2 * i] = xml.charCodeAt(i) & 0xff; + u16[3 + 2 * i] = xml.charCodeAt(i) >> 8; + } + p.set("xl/drawings/drawing1.xml", u16); + return zipParts(p); + }, + }); + // Zip limits. + files.push({ name: "maxInputBytes", bytes: () => zipParts(richParts()), limits: { maxInputBytes: 1000 } }); + files.push({ name: "maxEntries", bytes: () => zipParts(richParts()), limits: { maxEntries: 5 } }); + files.push({ name: "maxEntryBytes", bytes: () => zipParts(richParts({ rows: 2000 })), limits: { maxEntryBytes: 20_000 } }); + files.push({ name: "maxTotalBytes", bytes: () => zipParts(richParts({ rows: 2000 })), limits: { maxTotalBytes: 50_000 } }); + files.push({ + name: "ratio bomb in a sheet", + bytes: () => { + const p = richParts(); + p.set("xl/worksheets/sheet2.xml", `${"".repeat(400_000)}`); + return zipParts(p); + }, + limits: { maxRatio: 100 }, + }); + files.push({ + name: "zip bomb in an unread part", + bytes: () => { + const p = richParts(); + p.set("xl/media/image2.png", new Uint8Array(3 * 1024 * 1024)); + return zipParts(p); + }, + limits: { maxRatio: 100 }, + }); + files.push({ + name: "zip bomb in the shared strings", + bytes: () => { + const p = richParts(); + p.set("xl/sharedStrings.xml", `${"a".repeat(200_000)}`); + return zipParts(p); + }, + limits: { maxRatio: 50 }, + }); + // Reader limits. + files.push({ name: "maxCells", bytes: () => zipParts(richParts({ rows: 50 })), limits: { maxCells: 20 } }); + files.push({ name: "maxColumns", bytes: () => zipParts(richParts()), limits: { maxColumns: 2 } }); + files.push({ name: "maxSharedStrings", bytes: () => zipParts(richParts()), limits: { maxSharedStrings: 2 } }); + files.push({ name: "maxCellTextLength", bytes: () => zipParts(richParts()), limits: { maxCellTextLength: 4 } }); + files.push({ name: "maxItems", bytes: () => zipParts(richParts()), limits: { maxItems: 3 } }); + files.push({ name: "maxSheets", bytes: () => zipParts(richParts()), limits: { maxSheets: 2 } }); + files.push({ name: "maxXmlDepth", bytes: () => zipParts(richParts()), limits: { maxXmlDepth: 3 } }); + files.push({ name: "maxXmlTokenLength", bytes: () => zipParts(richParts()), limits: { maxXmlTokenLength: 40 } }); + // Containers and formats. + files.push({ name: "encrypted zip", bytes: async () => markEncrypted(await zipParts(richParts())) }); + files.push({ name: "CFB (legacy .xls or encrypted OOXML)", bytes: async () => new Uint8Array([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1, ...new Uint8Array(504)]) }); + files.push({ name: "not a zip", bytes: async () => new TextEncoder().encode("name,value\nA,1\n") }); + files.push({ name: "empty input", bytes: async () => new Uint8Array(0) }); + files.push({ name: "zip that is not a workbook", bytes: () => zipParts(new Map([["readme.txt", "hello"]])) }); + files.push({ + name: "ODS", + bytes: () => zipParts(new Map([["mimetype", "application/vnd.oasis.opendocument.spreadsheet"], ["content.xml", ""]]), "store"), + }); + files.push({ name: "xlsb", bytes: () => zipParts(richParts({ format: "xlsb" })) }); + files.push({ name: "truncated zip", bytes: async () => (await zipParts(richParts())).subarray(0, 900) }); + files.push({ name: "zip without its last byte", bytes: async () => { const z = await zipParts(richParts()); return z.subarray(0, z.length - 1); } }); + files.push({ + name: "corrupted sheet data (CRC)", + bytes: async () => { + const z = (await zipParts(richParts(), "store")).slice(); + const at = findText(z, ""); + z[at + 3]! ^= 0x20; + return z; + }, + }); + files.push({ + name: "corrupted unread part (CRC)", + bytes: async () => { + const z = (await zipParts(richParts(), "store")).slice(); + const at = findText(z, "commentList"); + z[at]! ^= 0x20; + return z; + }, + }); + files.push({ + name: "malformed worksheet", + bytes: () => { + const p = richParts(); + p.set("xl/worksheets/sheet2.xml", `1`); + return zipParts(p); + }, + }); + files.push({ + name: "malformed styles", + bytes: () => { + const p = richParts(); + p.set("xl/styles.xml", ``); + return zipParts(p); + }, + }); + files.push({ + name: "unknown entity in shared strings", + bytes: () => { + const p = richParts(); + p.set("xl/sharedStrings.xml", `&e;`); + return zipParts(p); + }, + }); + files.push({ + name: "malformed (optional) theme and core properties", + bytes: () => { + const p = richParts(); + p.set("xl/theme/theme1.xml", ""); + p.set("docProps/core.xml", ""); + return zipParts(p); + }, + }); + files.push({ + name: "duplicate part names differing in case", + bytes: () => { + const p = richParts(); + p.set("XL/STYLES.XML", p.get("xl/styles.xml")!); + return zipParts(p); + }, + }); + // Part kinds read reports. + files.push({ name: "xlsm (VBA)", bytes: () => zipParts(richParts({ format: "xlsm" })) }); + files.push({ name: "xltm (VBA)", bytes: () => zipParts(richParts({ format: "xltm" })) }); + files.push({ name: "xltx", bytes: () => zipParts(richParts({ format: "xltx" })) }); + files.push({ name: "macro sheet", bytes: () => zipParts(richParts({ macrosheet: true })) }); + files.push({ name: "external link", bytes: () => zipParts(richParts({ externalLink: true })) }); + files.push({ name: "connections", bytes: () => zipParts(richParts({ connections: true })) }); + files.push({ name: "OLE object", bytes: () => zipParts(richParts({ oleObject: true })) }); + files.push({ name: "query table", bytes: () => zipParts(richParts({ queryTable: true })) }); + files.push({ + name: "everything at once", + bytes: () => zipParts(richParts({ format: "xlsm", macrosheet: true, externalLink: true, connections: true, oleObject: true, queryTable: true })), + }); + return files; +} + +function findText(bytes: Uint8Array, text: string): number { + const t = new TextEncoder().encode(text); + outer: for (let i = 0; i + t.length <= bytes.length; i++) { + for (let j = 0; j < t.length; j++) if (bytes[i + j] !== t[j]) continue outer; + return i; + } + throw new Error(`${text} not found`); +} diff --git a/packages/javascript-excel/test/read/inspect-fuzz.test.ts b/packages/javascript-excel/test/read/inspect-fuzz.test.ts new file mode 100644 index 0000000..3ae2b62 --- /dev/null +++ b/packages/javascript-excel/test/read/inspect-fuzz.test.ts @@ -0,0 +1,227 @@ +// JSE-71: a seeded fuzz of the inspect guarantee. Valid workbooks are mutated +// (their parts' text, their part list and relationships, the zipped bytes) +// and read and inspected under default or random tight limits; for every case +// read refuses => inspect refuses the same way, and read reports a part kind +// => inspect reports it (inspect-check.ts). Deterministic: the same seed gives +// the same files. +import { describe, expect, it } from "vitest"; +import { toUint8Array } from "../../src/index"; +import { openZip } from "../../src/internal/zip/read"; +import { inspect, read, type ReadLimits } from "../../src/read"; +import { ALL } from "../conformance/corpus"; +import { checkPair, describeError, LESS, outcome } from "./inspect-check"; +import { DTD, richParts, zipParts, type Parts } from "./inspect-files"; + +const SEED = 20_261_202; +const CASES = 3_000; + +/** mulberry32: a small, fast, seeded PRNG. */ +function prng(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +/** Text the mutations insert: markup the reader treats specially, limits' edges, and damage. */ +const TOKENS = [ + DTD, + "", + "", + '1', + '2', + '999', + '45306', + 'ab', + '1', + 'SUM(A1:A9)', + '1', + '", + "", + "<", + ">", + '"', + "_x0041_", + `${"".repeat(20)}${"".repeat(20)}`, + ``, + `${"9".repeat(100)}`, +]; + +const KINDS = ["worksheet", "chartsheet", "macrosheet", "dialogsheet", "drawing", "vmlDrawing", "comments", "table", "pivotTable", "oleObject", "vbaProject", "externalLink", "connections", "queryTable", "slicer", "image", "sharedStrings", "styles", "theme"]; + +function pick(rnd: () => number, items: readonly T[]): T { + return items[Math.floor(rnd() * items.length)]!; +} + +function mutateText(rnd: () => number, text: string): string { + let s = text; + const ops = 1 + Math.floor(rnd() * 3); + for (let k = 0; k < ops; k++) { + const at = Math.floor(rnd() * (s.length + 1)); + switch (Math.floor(rnd() * 6)) { + case 0: + case 1: + s = s.slice(0, at) + pick(rnd, TOKENS) + s.slice(at); + break; + case 2: + s = s.slice(0, at) + s.slice(at + 1 + Math.floor(rnd() * 40)); + break; + case 3: { + const len = 1 + Math.floor(rnd() * 200); + s = s.slice(0, at) + s.slice(at, at + len).repeat(1 + Math.floor(rnd() * 4)) + s.slice(at); + break; + } + case 4: + s = s.replace(/\d+/g, (d) => (rnd() < 0.15 ? String(pick(rnd, [0, 1, 2, 63, 64, 999, 16384, 16385, 1048576, 1048577, 2 ** 31])) : d)); + break; + default: + s = s.replace(/relationships\/([A-Za-z]+)"/g, (whole) => (rnd() < 0.3 ? `relationships/${pick(rnd, KINDS)}"` : whole)); + } + } + return s; +} + +function mutateParts(rnd: () => number, base: Parts): Parts { + const p: Parts = new Map(base); + const names = [...p.keys()]; + const textNames = names.filter((n) => typeof p.get(n) === "string"); + const r = rnd(); + if (r < 0.7) { + const n = 1 + Math.floor(rnd() * 2); + for (let k = 0; k < n; k++) { + const name = pick(rnd, textNames); + p.set(name, mutateText(rnd, p.get(name) as string)); + } + } else if (r < 0.8) { + p.delete(pick(rnd, names)); + } else if (r < 0.87) { + const name = pick(rnd, names); + p.set(name.toUpperCase(), p.get(name)!); + } else if (r < 0.94) { + p.set(pick(rnd, ["customXml/item1.xml", "xl/media/image7.svg", "xl/embeddings/x.bin", "xl/worksheets/sheet9.xml"]), mutateText(rnd, '')); + } else { + const name = pick(rnd, names); + p.set(name, new Uint8Array(Math.floor(rnd() * 3) * 600_000)); // zeros: ratio bombs and empty parts + } + return p; +} + +function mutateBytes(rnd: () => number, bytes: Uint8Array): Uint8Array { + const b = bytes.slice(); + switch (Math.floor(rnd() * 3)) { + case 0: { + const n = 1 + Math.floor(rnd() * 4); + for (let k = 0; k < n; k++) b[Math.floor(rnd() * b.length)]! ^= 1 << Math.floor(rnd() * 8); + return b; + } + case 1: + return b.subarray(0, Math.floor(rnd() * b.length)); + default: { + const at = Math.floor(rnd() * b.length); + const out = new Uint8Array(b.length + 4); + out.set(b.subarray(0, at)); + out.set([0x50, 0x4b, 0x03, 0x04].map(() => Math.floor(rnd() * 256)), at); + out.set(b.subarray(at), at + 4); + return out; + } + } +} + +const LIMIT_CHOICES: Record = { + maxEntries: [3, 8, 20], + maxEntryBytes: [500, 4_000, 100_000], + maxTotalBytes: [5_000, 40_000, 1_000_000], + maxRatio: [2, 10, 100], + maxXmlDepth: [2, 4, 8], + maxXmlTokenLength: [20, 120, 1_000], + maxSheets: [1, 2, 3], + maxCells: [1, 5, 15, 40], + maxItems: [1, 4, 12], + maxSharedStrings: [1, 2, 3], + maxCellTextLength: [1, 4, 20], + maxColumns: [1, 2, 3, 8], + maxWarnings: [1, 3, 50], +}; + +function randomLimits(rnd: () => number): Partial | undefined { + if (rnd() < 0.5) return undefined; + const out: Record = {}; + for (const [k, values] of Object.entries(LIMIT_CHOICES)) if (rnd() < 0.2) out[k] = pick(rnd, values); + return out as Partial; +} + +async function unzip(bytes: Uint8Array): Promise { + const zip = openZip(bytes); + const p: Parts = new Map(); + for (const e of zip.entries) { + const data = await zip.read(e); + p.set(e.name, /\.(xml|rels)$/.test(e.name) ? new TextDecoder().decode(data) : data); + } + return p; +} + +describe("inspect vs read: seeded fuzz", () => { + it(`${CASES} mutated workbooks (seed ${SEED}): read refuses => inspect refuses the same way; read's part kinds => inspect's`, async () => { + const rnd = prng(SEED); + const bases: Parts[] = [ + richParts(), + richParts({ format: "xlsm", macrosheet: true, externalLink: true, connections: true, oleObject: true, queryTable: true, rows: 12 }), + richParts({ format: "xltx", rows: 30 }), + ]; + for (const entry of ALL.filter((e) => !e.heavy).slice(0, 3)) bases.push(await unzip(await toUint8Array(entry.workbook(), entry.options))); + const tally: Record = { cases: 0, "both-refuse": 0, "inspect-only": 0, "both-accept": 0 }; + const codes: Record = {}; + for (let n = 0; n < CASES; n++) { + const base = pick(rnd, bases); + const mode = rnd(); + let bytes: Uint8Array; + if (mode < 0.75) bytes = await zipParts(mutateParts(rnd, base), rnd() < 0.8 ? "deflate" : "store"); + else bytes = mutateBytes(rnd, await zipParts(base, rnd() < 0.5 ? "deflate" : "store")); + const limits = randomLimits(rnd); + const options = limits ? { limits } : {}; + const label = `case ${n} (seed ${SEED}) ${JSON.stringify(limits ?? {})}`; + const i = await outcome(inspect(bytes, options)); + const verdict = checkPair(label, await outcome(read(bytes, options)), i); + tally.cases!++; + tally[verdict]!++; + if (i.err !== undefined) { + const e = i.err as { code?: string; details?: { limit?: string } }; + const key = e.details?.limit ? `${e.code}:${e.details.limit}` : (e.code ?? "other"); + codes[key] = (codes[key] ?? 0) + 1; + } + // Read with options that read less refuses no more than inspect does. + const more = pick(rnd, LESS); + const r2 = await outcome(read(bytes, { ...more, ...options })); + if (r2.err !== undefined) expect(i.err, `${label} with ${JSON.stringify(more)}: read threw ${describeError(r2.err)}`).toBeDefined(); + } + console.log(`inspect fuzz (seed ${SEED}): ${JSON.stringify(tally)}\ninspect refusals by code: ${JSON.stringify(codes)}`); + expect(tally.cases).toBe(CASES); + // The fuzz reaches both sides of the guarantee. + expect(tally["both-refuse"]).toBeGreaterThan(CASES / 5); + expect(tally["both-accept"]).toBeGreaterThan(CASES / 10); + }, 300_000); +}); diff --git a/packages/javascript-excel/test/read/inspect.test.ts b/packages/javascript-excel/test/read/inspect.test.ts new file mode 100644 index 0000000..654bc33 --- /dev/null +++ b/packages/javascript-excel/test/read/inspect.test.ts @@ -0,0 +1,316 @@ +// JSE-71: inspect() checks a workbook part by part, with read()'s zip and XML +// safety, without building cells. +import { describe, expect, it } from "vitest"; +import { FormatError, LimitError } from "../../src/errors"; +import { inspect, read, type InspectResult } from "../../src/read"; +import { build, NS } from "./build"; +import { DTD, markEncrypted, numberRows, richParts, withDtd, xmlPartNames, zipParts } from "./inspect-files"; + +async function codeOf(p: Promise): Promise { + try { + await p; + } catch (err) { + return (err as { code?: string }).code ?? String(err); + } + return "no error"; +} + +describe("inspect: the result", () => { + it("names the format, the worksheets with their cell counts and extents, and the counts of the package", async () => { + const bytes = await zipParts(richParts()); + const r: InspectResult = await inspect(bytes); + const { workbook } = await read(bytes); + expect(r.format).toBe("xlsx"); + expect(r.sheets).toEqual([ + { name: "Data", index: 0, state: "visible", part: "xl/worksheets/sheet1.xml", cells: 9, dimension: "A1:C3" }, + { name: "Second", index: 1, state: "hidden", part: "xl/worksheets/sheet2.xml", cells: 8, dimension: "A1:B4" }, + ]); + expect(r.sheets.map((s) => s.dimension)).toEqual(workbook.sheets.map((s) => s.dimension)); + expect(r.cells).toBe(17); + expect(r.sharedStrings).toBe(3); + expect(r.parts).toBe(richParts().size); + // Every part was inflated once at least; rels and content types are read more than once. + const total = [...richParts().values()].reduce((n, v) => n + (typeof v === "string" ? new TextEncoder().encode(v).length : v.length), 0); + expect(r.inflatedBytes).toBeGreaterThanOrEqual(total); + }); + + it("reports the same UNSUPPORTED_PART warnings as read, and their part kinds", async () => { + const bytes = await zipParts(richParts({ format: "xlsm", macrosheet: true, externalLink: true, connections: true, oleObject: true, queryTable: true })); + const r = await inspect(bytes); + const { warnings } = await read(bytes); + const unsupported = warnings.filter((w) => w.code === "UNSUPPORTED_PART"); + expect(r.warnings).toEqual(unsupported); + expect(r.partKinds).toEqual(unsupported.map((w) => w.partKind)); + expect(r.format).toBe("xlsm"); + for (const k of ["vbaProject", "externalLink", "connections", "chartsheet", "macrosheet", "drawing", "comments", "vmlDrawing", "oleObject", "queryTable"]) { + expect(r.partKinds).toContain(k); + } + expect(r.warnings.every((w) => w.code === "UNSUPPORTED_PART")).toBe(true); + }); + + it("a plain workbook from the writer has no part kinds to report", async () => { + const bytes = await build({ sheets: ['1'] }); + const r = await inspect(bytes); + expect(r).toMatchObject({ format: "xlsx", partKinds: [], warnings: [], cells: 1, sharedStrings: 0 }); + }); + + it("a sheet whose part is missing is listed without a part and with no cells", async () => { + const p = richParts(); + p.delete("xl/worksheets/sheet2.xml"); + const r = await inspect(await zipParts(p)); + expect(r.sheets[1]).toEqual({ name: "Second", index: 1, state: "hidden", cells: 0 }); + }); + + it("reports part kinds found after maxWarnings other warnings, as read does (UNSUPPORTED_PART is a data-loss warning)", async () => { + // 1,500 cells with an invalid shared string index each fill the warning list before the second sheet's table. + const cells = Array.from({ length: 1500 }, (_, i) => `99`).join(""); + const p = richParts({ rows: 1 }); + p.set("xl/worksheets/sheet1.xml", `${cells}`); + p.set("xl/worksheets/_rels/sheet2.xml.rels", ``); + p.set("xl/tables/table1.xml", ``); + const bytes = await zipParts(p); + const limits = { maxWarnings: 10 }; + const r = await inspect(bytes, { limits }); + const { warnings } = await read(bytes, { limits }); + expect(warnings.some((w) => w.code === "WARNINGS_TRUNCATED")).toBe(true); + expect(r.partKinds).toContain("table"); + expect(r.warnings).toEqual(warnings.filter((w) => w.code === "UNSUPPORTED_PART")); + }); +}); + +describe("inspect: refuses what read refuses", () => { + it.each(xmlPartNames(richParts()))("a DOCTYPE in %s: XML_DTD_FORBIDDEN with details.part", async (name) => { + const p = richParts(); + p.set(name, withDtd(p.get(name) as string)); + const bytes = await zipParts(p); + const err = await inspect(bytes).then(() => undefined, (e: unknown) => e); + expect(err).toBeInstanceOf(FormatError); + expect((err as FormatError).code).toBe("XML_DTD_FORBIDDEN"); + expect((err as FormatError).details?.["part"]).toBe(name); + }); + + it("a DOCTYPE after 50,000 rows of a sheet is refused (every row is checked)", async () => { + const p = richParts(); + p.set("xl/worksheets/sheet2.xml", `${numberRows(50_000, 2).replace("", `${DTD}`)}`); + expect(await codeOf(inspect(await zipParts(p)))).toBe("XML_DTD_FORBIDDEN"); + }); + + it("a DOCTYPE in an unreferenced XML part, in a UTF-16 part and in an SVG image is refused", async () => { + const a = richParts(); + a.set("customXml/item1.xml", withDtd('')); + expect(await codeOf(inspect(await zipParts(a)))).toBe("XML_DTD_FORBIDDEN"); + + const b = richParts(); + const xml = withDtd(b.get("xl/comments1.xml") as string); + const u16 = new Uint8Array(2 + 2 * xml.length); + u16.set([0xfe, 0xff]); + for (let i = 0; i < xml.length; i++) u16[3 + 2 * i] = xml.charCodeAt(i); + b.set("xl/comments1.xml", u16); + expect(await codeOf(inspect(await zipParts(b)))).toBe("XML_DTD_FORBIDDEN"); + + const c = richParts(); + c.set("xl/media/image2.svg", ''); + expect(await codeOf(inspect(await zipParts(c)))).toBe("XML_DTD_FORBIDDEN"); + }); + + it("a DOCTYPE after the break in a broken optional part (theme, document properties) is refused, though read only warns there", async () => { + for (const name of ["xl/theme/theme1.xml", "docProps/core.xml", "docProps/app.xml", "docProps/custom.xml"]) { + const p = richParts(); + p.set(name, `${DTD}`); + const bytes = await zipParts(p); + const { warnings } = await read(bytes); + expect(warnings.map((w) => w.code), name).toContain("BROKEN_OPTIONAL_PART"); + const err = await inspect(bytes).then(() => undefined, (e: unknown) => e as FormatError); + expect(err?.code, name).toBe("XML_DTD_FORBIDDEN"); + expect(err?.details?.["part"], name).toBe(name); + } + // Broken but without a DOCTYPE: accepted, as by read. + const p = richParts(); + p.set("xl/theme/theme1.xml", ""); + await expect(inspect(await zipParts(p))).resolves.toMatchObject({ format: "xlsx" }); + }); + + it("parts read does not parse are not checked for well-formedness (Excel's VML is not XML), only for a DOCTYPE", async () => { + const r = await inspect(await zipParts(richParts())); + expect(r.partKinds).toContain("vmlDrawing"); + }); + + it("zip limits, encryption and formats: the same codes as read", async () => { + const bytes = await zipParts(richParts()); + const cases: Array<[Uint8Array, Record]> = [ + [bytes, { maxInputBytes: 100 }], + [bytes, { maxEntries: 3 }], + [bytes, { maxEntryBytes: 500 }], + [bytes, { maxTotalBytes: 2000 }], + [markEncrypted(bytes), {}], + [new Uint8Array([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1, 0, 0]), {}], + [new TextEncoder().encode("a,b\n1,2\n"), {}], + [await zipParts(new Map([["a.txt", "x"]])), {}], + [await zipParts(richParts({ format: "xlsb" })), {}], + [bytes.subarray(0, bytes.length - 30), {}], + ]; + for (const [b, limits] of cases) { + const fromRead = await codeOf(read(b, { limits })); + expect(fromRead).not.toBe("no error"); + expect(await codeOf(inspect(b, { limits }))).toBe(fromRead); + } + }); + + it("a ratio bomb in a part read never inflates is refused", async () => { + const p = richParts(); + p.set("xl/media/image9.png", new Uint8Array(4 * 1024 * 1024)); + const bytes = await zipParts(p); + await expect(read(bytes, { limits: { maxRatio: 100 } })).resolves.toBeDefined(); + const err = await inspect(bytes, { limits: { maxRatio: 100 } }).then(() => undefined, (e: unknown) => e); + expect(err).toBeInstanceOf(LimitError); + expect((err as LimitError).details?.["limit"]).toBe("maxRatio"); + }); + + it("reader limits apply as in read: maxCells, maxColumns, maxSharedStrings, maxCellTextLength, maxItems, maxSheets", async () => { + const bytes = await zipParts(richParts({ rows: 40 })); + for (const limits of [{ maxCells: 30 }, { maxColumns: 2 }, { maxSharedStrings: 2 }, { maxCellTextLength: 4 }, { maxItems: 3 }, { maxSheets: 2 }, { maxXmlDepth: 3 }]) { + const fromRead = await read(bytes, { limits }).then(() => undefined, (e: unknown) => e as LimitError); + expect(fromRead, JSON.stringify(limits)).toBeInstanceOf(LimitError); + const fromInspect = await inspect(bytes, { limits }).then(() => undefined, (e: unknown) => e as LimitError); + expect(fromInspect).toBeInstanceOf(LimitError); + expect(fromInspect!.details).toEqual(fromRead!.details); + } + }); + + it("an invalid shared string index does not count as a cell, as in read", async () => { + const p = richParts({ rows: 1 }); + p.set("xl/worksheets/sheet2.xml", `23`); + const bytes = await zipParts(p); + const r = await inspect(bytes); + expect(r.sheets[1]!.cells).toBe(1); + expect(r.sheets[1]!.dimension).toBe("A1"); + }); + + it("maxRows is outside the guarantee: a capped read counts cells whose shared string is missing toward maxCells (docs/api.md §5.2.1)", async () => { + const p = richParts({ rows: 1 }); + p.set("xl/worksheets/sheet2.xml", `505152`); + const bytes = await zipParts(p); + const limits = { maxCells: 10 }; + // Sheet 1 has 9 cells; the three cells of sheet 2 point past the 3-item table. + expect(await codeOf(read(bytes, { limits }))).toBe("no error"); + expect(await codeOf(inspect(bytes, { limits }))).toBe("no error"); + expect(await codeOf(read(bytes, { limits, maxRows: 100 }))).toBe("LIMIT_EXCEEDED"); + }); + + it("validates limits like read", async () => { + const bytes = await zipParts(richParts()); + await expect(inspect(bytes, { limits: { maxCells: -1 } })).rejects.toThrow(TypeError); + await expect(inspect("nope" as unknown as Uint8Array)).rejects.toThrow(TypeError); + }); + + it("takes an ArrayBuffer and a Blob", async () => { + const bytes = await zipParts(richParts()); + expect((await inspect(bytes.slice().buffer)).cells).toBe(17); + expect((await inspect(new Blob([bytes.slice()]))).cells).toBe(17); + }); +}); + +describe("inspect: the signal", () => { + it("rejects with the reason when already aborted", async () => { + const bytes = await zipParts(richParts()); + const reason = new Error("stop"); + await expect(inspect(bytes, { signal: { aborted: true, reason } })).rejects.toBe(reason); + }); + + it("is consulted within a long sheet", async () => { + const p = richParts(); + p.set("xl/worksheets/sheet2.xml", `${numberRows(60_000, 3)}`); + const bytes = await zipParts(p, "store"); + const reason = new Error("stop"); + let checks = 0; + const signal = { + get aborted(): boolean { + return ++checks > 40; + }, + reason, + }; + await expect(inspect(bytes, { signal })).rejects.toBe(reason); + }); + + it("is consulted while an unread part is scanned", async () => { + const p = richParts(); + // A 6 MB stored drawing: scanned in slices, with the signal consulted between them. + p.set("xl/drawings/drawing1.xml", `${"".repeat(1_500_000)}`); + const bytes = await zipParts(p, "store"); + const clean = await inspect(bytes); + let checks = 0; + const counter = { + get aborted(): boolean { + checks++; + return false; + }, + }; + await inspect(bytes, { signal: counter }); + const base = checks; + expect(clean.partKinds).toContain("drawing"); + // Abort after every check that inspect made before the scan, so it fires inside it. + let n = 0; + const reason = new Error("stop in the scan"); + const late = { + get aborted(): boolean { + return ++n >= base - 3; + }, + reason, + }; + await expect(inspect(bytes, { signal: late })).rejects.toBe(reason); + }); +}); + +describe("inspect: memory does not grow with the cells", () => { + async function file(rows: number): Promise { + const p = richParts({ rows: 1 }); + p.set("xl/worksheets/sheet2.xml", `${numberRows(rows, 10)}`); + return zipParts(p); + } + + /** Peak heap above the start while `fn` runs, sampled every millisecond (inspect and read yield every ~16 ms). */ + async function peak(fn: () => Promise): Promise<{ peak: number; result: unknown }> { + const gc = await exposeGc(); + gc(); + const before = process.memoryUsage().heapUsed; + let max = before; + const timer = setInterval(() => { + const h = process.memoryUsage().heapUsed; + if (h > max) max = h; + }, 1); + let result: unknown; + try { + result = await fn(); + } finally { + clearInterval(timer); + } + max = Math.max(max, process.memoryUsage().heapUsed); + return { peak: max - before, result }; + } + + it("a 1,000,000-cell sheet: inspect's peak heap is a fraction of read's, and the same as for 100,000 cells", async () => { + const small = await file(10_000); + const big = await file(100_000); + const s = await peak(() => inspect(small)); + const i = await peak(() => inspect(big)); + expect((i.result as InspectResult).cells).toBe(1_000_000 + 9); + const r = await peak(() => read(big)); + // Measured on Node 26 (Apple M2): read about 120 MB; inspect about 30 MB for either file (the young generation's garbage). + console.log(`inspect 100k cells ${(s.peak / 1e6).toFixed(0)} MB, inspect 1M cells ${(i.peak / 1e6).toFixed(0)} MB, read 1M cells ${(r.peak / 1e6).toFixed(0)} MB (peak heap)`); + expect(r.peak).toBeGreaterThan(80e6); + expect(i.peak).toBeLessThan(r.peak / 3); + expect(i.peak).toBeLessThan(48e6); + // Ten times the cells, about the same memory. + expect(i.peak).toBeLessThan(s.peak + 16e6); + }, 60_000); +}); + +/** `global.gc`, made available at run time if node was not started with --expose-gc. */ +async function exposeGc(): Promise<() => void> { + const g = globalThis as { gc?: () => void }; + if (typeof g.gc === "function") return g.gc; + const v8 = await import("node:v8"); + const vm = await import("node:vm"); + v8.setFlagsFromString("--expose-gc"); + return vm.runInNewContext("gc") as () => void; +} From 1363a2f16955adce9c554a8d63d4687fb1cd3687 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 11:22:36 +0100 Subject: [PATCH 02/22] JSE-71: inspect() checks a workbook without building cells inspect runs read's own pipeline with the sheet and shared-string parsers in a mode that converts, checks and counts each cell and string and then drops it, so it refuses what read refuses with the same error and reports read's UNSUPPORTED_PART warnings. It then inflates every part read leaves unopened (or stopped at malformed XML) and searches XML parts for a DOCTYPE. read's output is unchanged. --- .../javascript-excel/scripts/consumer.mjs | 6 +- .../src/internal/read/context.ts | 7 +- .../src/internal/read/inspect.ts | 110 ++++++++++++++++++ .../src/internal/read/reader.ts | 50 +++++++- .../src/internal/read/sheet.ts | 58 +++++++-- .../src/internal/read/strings.ts | 24 ++-- packages/javascript-excel/src/read.ts | 57 ++++++++- 7 files changed, 284 insertions(+), 28 deletions(-) create mode 100644 packages/javascript-excel/src/internal/read/inspect.ts diff --git a/packages/javascript-excel/scripts/consumer.mjs b/packages/javascript-excel/scripts/consumer.mjs index 19fefec..9d84ba6 100644 --- a/packages/javascript-excel/scripts/consumer.mjs +++ b/packages/javascript-excel/scripts/consumer.mjs @@ -19,7 +19,7 @@ const specifier = (sub) => (sub === "." ? pkg.name : `${pkg.name}/${sub.slice(2) export const FUNCTION = Symbol("function"); const expected = { ".": { VERSION: pkg.version }, - "./read": { read: FUNCTION, readSheetNames: FUNCTION, detectFormat: FUNCTION }, + "./read": { read: FUNCTION, readSheetNames: FUNCTION, detectFormat: FUNCTION, inspect: FUNCTION }, "./csv": { CSV_MIME: "text/csv;charset=utf-8", parseCsv: FUNCTION, readCsv: FUNCTION, toCsv: FUNCTION, toCsvBlob: FUNCTION }, "./dom": { fromTable: FUNCTION, download: FUNCTION, DOWNLOAD_REVOKE_DELAY_MS: 40000 }, "./worker": { exposeWorker: FUNCTION, createWorkerClient: FUNCTION }, @@ -199,6 +199,10 @@ const full23: ReadLimits = { maxInputBytes: 1, maxEntries: 1, maxEntryBytes: 1, const columnsMax: number = DEFAULT_READ_LIMITS.maxColumns; const columnsLimited: ReadOptions = { limits: { maxColumns: 256 } }; void full23; void columnsMax; void columnsLimited; +import { inspect, type InspectOptions, type InspectResult, type InspectedSheet, type InspectFormat } from ${JSON.stringify(`${pkg.name}/read`)}; +const iopts: InspectOptions = { limits: { maxColumns: 256, maxCells: 1_000_000 }, signal: undefined }; +const checked: Promise = inspect(new Uint8Array(0), iopts); +checked.then((r) => { const f: InspectFormat = r.format; const s: InspectedSheet | undefined = r.sheets[0]; const kinds: string[] = r.partKinds; const n: number = r.cells + r.parts + r.inflatedBytes + r.sharedStrings + (s?.cells ?? 0); const code: string | undefined = r.warnings[0]?.code; void f; void kinds; void n; void code; }, () => {}); import { importDataset, type DroppedIssues, type ImportDatasetResult } from ${JSON.stringify(`${pkg.name}/import`)}; const imp: Promise = importDataset("a", { maxIssues: 10, limits: { maxCellTextLength: 100 } }); imp.then((r) => { const d: DroppedIssues | undefined = r.meta.droppedIssues; void d; }, () => {}); diff --git a/packages/javascript-excel/src/internal/read/context.ts b/packages/javascript-excel/src/internal/read/context.ts index 3264dbe..689024d 100644 --- a/packages/javascript-excel/src/internal/read/context.ts +++ b/packages/javascript-excel/src/internal/read/context.ts @@ -31,7 +31,7 @@ export interface ProgressInfo { ratio: number; } -interface TextDecoderLike { +export interface TextDecoderLike { decode(input?: Uint8Array, options?: { stream?: boolean }): string; } type TextDecoderCtor = new (label?: string, options?: { fatal?: boolean }) => TextDecoderLike; @@ -61,6 +61,8 @@ export class ReadContext { } private readonly onProgress: ((p: ProgressInfo) => void) | undefined; + /** Sees every warning before the cap applies (inspect collects UNSUPPORTED_PART with it, JSE-71). */ + tap: ((w: ExcelWarning) => void) | undefined; /** Returns to the event loop about every 16 ms between chunks, so a big read does not freeze the page (JSE-24). */ private readonly pause = createYielder(); @@ -75,6 +77,7 @@ export class ReadContext { if (where?.sheet !== undefined) w.sheet = where.sheet; if (where?.ref !== undefined) w.ref = where.ref; if (where?.partKind !== undefined) w.partKind = where.partKind; + this.tap?.(w); const kept = this.cap.add(w, (dropped) => { const t: ExcelWarning = { code: "WARNINGS_TRUNCATED", message: `More than maxWarnings (${this.limits.maxWarnings}) warnings; later ones were dropped.`, dropped }; this.cap.warnings.push(t); @@ -197,7 +200,7 @@ export function withPart(err: unknown, part: string): unknown { return err; } -function newDecoder(first: Uint8Array): TextDecoderLike { +export function newDecoder(first: Uint8Array): TextDecoderLike { const Ctor = (globalThis as unknown as { TextDecoder: TextDecoderCtor }).TextDecoder; // OOXML parts are UTF-8 or UTF-16 (with a BOM). if (first[0] === 0xff && first[1] === 0xfe) return new Ctor("utf-16le"); diff --git a/packages/javascript-excel/src/internal/read/inspect.ts b/packages/javascript-excel/src/internal/read/inspect.ts new file mode 100644 index 0000000..a922140 --- /dev/null +++ b/packages/javascript-excel/src/internal/read/inspect.ts @@ -0,0 +1,110 @@ +/** + * inspect (docs/api.md §5.2.1, JSE-71): checks a workbook part by part with + * read's zip and XML safety, without building cells. Internal. + * + * The workbook is read by readImpl itself, with every check read makes, in + * the same order, but with no cells and no shared strings kept (the sheet + * and shared-strings parsers count instead). So inspect refuses what read + * refuses, with the same error, and reports the part kinds read reports; + * whatever readImpl learns to check or report, inspect does too. Then every + * zip entry the read did not parse, or parsed only up to an error it forgave + * (a broken optional part), is inflated (zip limits, CRC) and, when it is + * XML, searched for a document type declaration. + */ + +import { FormatError } from "../../errors"; +import type { InspectedSheet, InspectFormat, InspectOptions, InspectResult } from "../../read"; +import type { ExcelPartKind } from "../../warnings"; +import { newDecoder, PARSE_SLICE, withPart, type ReadContext, type TextDecoderLike } from "./context"; +import type { Package } from "./opc"; +import { readImpl, type InspectSink } from "./reader"; +import type { ZipEntryInfo } from "../zip/read"; + +/** + * A document type declaration, also in UTF-16 text decoded as UTF-8 (a NUL + * between the characters). The tokenizer refuses ` { + const sink: InspectSink = { unsupported: [], broken: new Set(), sharedStrings: 0, sheets: [] }; + const { workbook } = await readImpl(bytes, { limits: options?.limits, signal: options?.signal }, { inspect: sink }); + const ctx = sink.ctx!; + const pkg = sink.pkg!; + for (const entry of ctx.zip.entries) { + if (ctx.consumed.has(entry.name) && !sink.broken.has(entry.name)) continue; + const pause = ctx.step(); + if (pause) await pause; + await scanPart(ctx, entry, isXmlPart(pkg, entry.name)); + } + const kinds = new Set(); + for (const w of sink.unsupported) if (w.partKind !== undefined) kinds.add(w.partKind); + const sheets = workbook.sheets.map((s, index): InspectedSheet => { + const out: InspectedSheet = { name: s.name, index, state: s.state ?? "visible", cells: sink.sheets[index]!.cells }; + const part = sink.sheets[index]!.part; + if (part !== undefined) out.part = part; + if (s.dimension !== undefined) out.dimension = s.dimension; + return out; + }); + return { + format: sink.format!.format as InspectFormat, + sheets, + partKinds: [...kinds], + warnings: sink.unsupported, + parts: pkg.partNames.length, + inflatedBytes: ctx.zip.totalBytesRead, + cells: ctx.cells, + sharedStrings: sink.sharedStrings, + }; +} + +/** + * Inflates one entry to its end, so the zip limits and its CRC are checked, + * and searches XML text for ` { + let decoder: TextDecoderLike | undefined; + let tail = ""; + const search = (text: string): void => { + const s = tail + text; + if (DOCTYPE.test(s)) throw doctype(); + tail = s.slice(-DOCTYPE_TAIL); + }; + try { + for await (const chunk of ctx.zip.stream(entry, ctx.signal)) { + if (xml) { + // A byte order mark selects UTF-16 and is dropped by the decoder, as in ctx.parse. + decoder ??= newDecoder(chunk); + for (let at = 0; at < chunk.length; ) { + const piece = chunk.subarray(at, at + PARSE_SLICE); + at += piece.length; + search(decoder.decode(piece, { stream: true })); + if (at < chunk.length) { + const pause = ctx.step(); + if (pause) await pause; + } + } + } + const pause = ctx.step(); + if (pause) await pause; + } + if (decoder) search(decoder.decode()); + } catch (err) { + throw withPart(err, entry.name); + } +} diff --git a/packages/javascript-excel/src/internal/read/reader.ts b/packages/javascript-excel/src/internal/read/reader.ts index dc6eb7c..fa943f0 100644 --- a/packages/javascript-excel/src/internal/read/reader.ts +++ b/packages/javascript-excel/src/internal/read/reader.ts @@ -8,9 +8,9 @@ import { FormatError } from "../../errors"; import type { Cell, DefinedName, DocProperties, RichText, Sheet, Workbook } from "../../model"; import type { ReadLimits, ReadOptions, ReadResult, SheetInfo } from "../../read"; import type { AbortSignalLike } from "../../signal"; -import type { ExcelPartKind } from "../../warnings"; +import type { ExcelPartKind, ExcelWarning } from "../../warnings"; import { toBytes } from "../input"; -import { openZip } from "../zip/read"; +import { openZip, type ZipEntryInfo } from "../zip/read"; import { ReadContext } from "./context"; import { ODS_MIME, OTHER_FORMATS, sniffContainer, WORKBOOK_FORMATS, workbookFormat, type FormatName, type WorkbookFormat } from "./formats"; import { DEFAULT_LIMITS } from "./limits"; @@ -223,6 +223,27 @@ export interface InternalReadOptions { * are unchanged. For importDataset, which uses only the values. */ sharedFormulaText?: "shifted" | "master"; + /** + * inspect (JSE-71): the read runs as always, with every check, but keeps no + * cells and no shared strings; what inspect reports is collected here. + */ + inspect?: InspectSink; +} + +/** What a read for inspect collects (internal/read/inspect.ts). */ +export interface InspectSink { + /** Set once the package is open. */ + ctx?: ReadContext; + pkg?: Package; + format?: WorkbookFormat; + /** Every UNSUPPORTED_PART warning, before the warning cap. */ + unsupported: ExcelWarning[]; + /** Parts whose XML was malformed and skipped (BROKEN_OPTIONAL_PART): not read to their end. */ + broken: Set; + /** Items in the shared strings table. */ + sharedStrings: number; + /** Per listed worksheet, in order: its part and the cells it has. */ + sheets: Array<{ part: string | undefined; cells: number }>; } export interface InternalReadResult extends ReadResult { @@ -248,6 +269,16 @@ export async function readImpl(input: BinaryInput, options?: ReadOptions, intern return ctx; }); ctx.progress({ phase: "unzip", ratio: 0.02 }); + const inspect = internal?.inspect; + if (inspect) { + inspect.ctx = ctx; + inspect.pkg = pkg; + inspect.format = format; + ctx.tap = (w) => { + if (w.code === "UNSUPPORTED_PART") inspect.unsupported.push(w); + else if (w.code === "BROKEN_OPTIONAL_PART" && w.part !== undefined) inspect.broken.add(w.part); + }; + } const wbp = await parseWorkbook(pkg, workbookPart); const wbRels = await pkg.rels(workbookPart); @@ -296,9 +327,10 @@ export async function readImpl(input: BinaryInput, options?: ReadOptions, intern if (!entry) ctx.warn("MISSING_PART", `The shared strings part ${excerpt(sstRel.target)} is missing; cells that use it are empty.`, { part: sstRel.target, partKind: "sharedStrings" }); else if (deferred) sstEntry = entry; else { - const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, Infinity, (n) => ctx.charge(n), limits.maxCellTextLength); + const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, Infinity, (n) => ctx.charge(n), limits.maxCellTextLength, !inspect); await ctx.parse(entry, sp); sst = sp.strings; + if (inspect) inspect.sharedStrings = sp.count; } } @@ -315,6 +347,10 @@ export async function readImpl(input: BinaryInput, options?: ReadOptions, intern totalBytes ||= 1; let doneBytes = 0; const sheets: Array> = []; + const done = (parser: SheetParser, part: ZipEntryInfo | undefined, sheet: Sheet): void => { + sheets.push(sheet); + inspect?.sheets.push({ part: part?.name, cells: parser.cellCount }); + }; for (let i = 0; i < listed.length; i++) { const pause = ctx.step(); if (pause) await pause; @@ -328,17 +364,19 @@ export async function readImpl(input: BinaryInput, options?: ReadOptions, intern rawText: o.rawText === true, date1904: wbp.date1904, maxRows: o.maxRows ?? MAX_ROWS, + keepCells: !inspect, }, rel?.target ?? workbookPart); parser.sharedStrings = sst; + if (inspect) parser.sharedStringCount = inspect.sharedStrings; parser.deferred = deferred; const part = rel ? pkg.part(rel.target) : undefined; if (!part) { ctx.warn("MISSING_PART", `The part for sheet "${excerpt(entry.name)}" is missing; the sheet is empty.`, { sheet: entry.name, partKind: "worksheet" }); - sheets.push(parser.finish([])); + done(parser, part, parser.finish([])); continue; } if (!wanted(entry.name, i)) { - sheets.push(parser.finish([])); + done(parser, part, parser.finish([])); continue; } const sheetRels = await pkg.rels(part.name); @@ -351,7 +389,7 @@ export async function readImpl(input: BinaryInput, options?: ReadOptions, intern ctx.progress({ phase: "parse", sheet: entry.name, ratio: 0.1 + 0.9 * (Math.min(base + read, totalBytes) / totalBytes) }); }); doneBytes += part.size; - sheets.push(parser.finish(sheetRels)); + done(parser, part, parser.finish(sheetRels)); } // The table counts as read either way, so it's never listed as an unparsed part. if (sstEntry && deferred && deferred.cells.length === 0) ctx.consumed.add(sstEntry.name); diff --git a/packages/javascript-excel/src/internal/read/sheet.ts b/packages/javascript-excel/src/internal/read/sheet.ts index 52323b6..a8d0364 100644 --- a/packages/javascript-excel/src/internal/read/sheet.ts +++ b/packages/javascript-excel/src/internal/read/sheet.ts @@ -82,6 +82,12 @@ export interface SheetOptions { date1904: boolean; /** Rows at or beyond this zero-based index are skipped (ReadOptions.maxRows). */ maxRows: number; + /** + * false (inspect, JSE-71): every cell is converted, checked and counted as + * a read keeps it, then dropped; merges and selections are counted, not + * kept; a hyperlink is kept only when it could pass maxColumns. Default true. + */ + keepCells?: boolean; } interface PendingCell { @@ -212,6 +218,12 @@ export class SheetParser implements XmlHandler { private maxCol = -1; private truncated = false; private control: XmlControl | undefined; + /** opts.keepCells (default true). */ + private readonly keep: boolean; + /** Cells kept (or, without keepCells, that would have been), as maxCells counts them. */ + cellCount = 0; + /** Without keepCells: the rows that had properties, one bit per row (for counting each once, as `rowProps` does). */ + private rowPropSeen: Uint8Array | undefined; constructor( name: string, @@ -223,6 +235,7 @@ export class SheetParser implements XmlHandler { ) { this.sheet = { name, rows: this.rows }; if (state && state !== "visible") this.sheet.state = state; + this.keep = opts.keepCells !== false; } // ------------------------------------------------------------------ events @@ -272,7 +285,7 @@ export class SheetParser implements XmlHandler { const ref = a.get("ref"); if (ref) { this.ctx.charge(1); - this.merges.push(cleanRange(ref)); + if (this.keep) this.merges.push(cleanRange(ref)); } return; } @@ -280,7 +293,7 @@ export class SheetParser implements XmlHandler { if (parent === "hyperlinks") { const ref = a.get("ref"); if (ref) this.ctx.charge(1); // the hyperlink, and the empty cell it may create - if (ref) this.hyperlinks.push({ ref: cleanRange(ref), relId: a.getPrefixed("id"), location: a.get("location"), tooltip: a.get("tooltip") }); + if (ref && (this.keep || this.mayBeTooWide(ref))) this.hyperlinks.push({ ref: cleanRange(ref), relId: a.getPrefixed("id"), location: a.get("location"), tooltip: a.get("tooltip") }); } return; case "sheetView": @@ -292,7 +305,7 @@ export class SheetParser implements XmlHandler { case "selection": if (parent === "sheetView" && this.viewCount === 1) { this.ctx.charge(1); - this.selections.push({ pane: a.get("pane"), activeCell: a.get("activeCell"), sqref: a.get("sqref") }); + if (this.keep) this.selections.push({ pane: a.get("pane"), activeCell: a.get("activeCell"), sqref: a.get("sqref") }); } return; case "sheetFormatPr": { @@ -461,6 +474,13 @@ export class SheetParser implements XmlHandler { if (Object.keys(p).length) { // JSE-52: one row-property object per row that has properties (with or without cells), // counted once even when the row appears again; maxItems, not maxCells. + if (!this.keep) { + const seen = (this.rowPropSeen ??= new Uint8Array(MAX_ROWS >> 3)); + const bit = 1 << (this.curRow & 7); + if (!(seen[this.curRow >> 3]! & bit)) this.ctx.charge(1); + seen[this.curRow >> 3]! |= bit; + return; + } if (this.rowProps[this.curRow] === undefined) this.ctx.charge(1); this.rowProps[this.curRow] = p; } @@ -618,6 +638,12 @@ export class SheetParser implements XmlHandler { if (!cell) return; if (p.col >= this.ctx.limits.maxColumns) this.tooWide(p.col, p.ref); this.ctx.countCell(); + this.cellCount++; + if (!this.keep) { + this.pendingIndex = -1; + this.extend(p.row, p.col); + return; + } let row = this.rows[p.row]; if (!row) row = this.rows[p.row] = []; if (row[p.col] !== undefined) { @@ -636,10 +662,21 @@ export class SheetParser implements XmlHandler { if (this.pendingIndex > d.maxIndex) d.maxIndex = this.pendingIndex; this.pendingIndex = -1; } - if (p.row < this.minRow) this.minRow = p.row; - if (p.row > this.maxRow) this.maxRow = p.row; - if (p.col < this.minCol) this.minCol = p.col; - if (p.col > this.maxCol) this.maxCol = p.col; + this.extend(p.row, p.col); + } + + /** Widens the sheet's dimension to a kept cell. */ + private extend(row: number, col: number): void { + if (row < this.minRow) this.minRow = row; + if (row > this.maxRow) this.maxRow = row; + if (col < this.minCol) this.minCol = col; + if (col > this.maxCol) this.maxCol = col; + } + + /** Without keepCells: whether a hyperlink on `ref` could fail maxColumns when the sheet is finished (attachHyperlink). */ + private mayBeTooWide(ref: string): boolean { + const pos = parseRef(cleanRange(ref).split(":")[0]!); + return pos !== undefined && pos[1] >= this.ctx.limits.maxColumns; } /** @@ -673,7 +710,9 @@ export class SheetParser implements XmlHandler { break; } const sst = this.sharedStrings; - const str = Number.isInteger(idx) && idx >= 0 ? sst[idx] : undefined; + const count = this.sharedStringCount; + // Without keepCells only the table's size is known: any string stands for the one at idx. + const str = Number.isInteger(idx) && idx >= 0 ? (count === undefined ? sst[idx] : idx < count ? "" : undefined) : undefined; if (str === undefined) { // The file places a cell here: counted toward maxColumns as on the deferred path // (ReadOptions.maxRows), where it is kept before its string resolves (JSE-68 review). @@ -832,6 +871,8 @@ export class SheetParser implements XmlHandler { /** Set before parsing; the shared strings table. */ sharedStrings: ReadonlyArray = []; + /** Set instead of `sharedStrings` when they were counted, not kept (inspect, JSE-71). */ + sharedStringCount: number | undefined; /** When set, shared-string cells are collected here and filled in later (ReadOptions.maxRows). */ deferred: DeferredStrings | undefined; @@ -987,6 +1028,7 @@ export class SheetParser implements XmlHandler { const [r, c] = pos; if (r >= MAX_ROWS || c >= MAX_COLS) return; if (c >= this.ctx.limits.maxColumns) this.tooWide(c, `${colLetters(c + 1)}${r + 1}`); + if (!this.keep) return; let row = this.rows[r]; if (!row) row = this.rows[r] = []; const cell = row[c] ?? (row[c] = { type: "empty" }); diff --git a/packages/javascript-excel/src/internal/read/strings.ts b/packages/javascript-excel/src/internal/read/strings.ts index a4d3216..0fbaebe 100644 --- a/packages/javascript-excel/src/internal/read/strings.ts +++ b/packages/javascript-excel/src/internal/read/strings.ts @@ -216,6 +216,8 @@ export class StringItem { /** Handler for sharedStrings.xml. */ export class SharedStringsParser implements XmlHandler { readonly strings: Array = []; + /** Items decoded so far; with `keep` false, the only record of them (inspect, JSE-71). */ + count = 0; private item: StringItem | undefined; private depth = 0; private control: XmlControl | undefined; @@ -231,6 +233,8 @@ export class SharedStringsParser implements XmlHandler { private readonly charge: (n: number) => void = () => {}, /** maxCellTextLength (JSE-58). */ private readonly maxText: number = Infinity, + /** false: decode and check every item, but keep none of them, only `count` (inspect, JSE-71). */ + private readonly keep: boolean = true, ) {} attach(control: XmlControl): void { @@ -241,8 +245,10 @@ export class SharedStringsParser implements XmlHandler { /** True once stopAfter items were decoded and the rest of the part is skipped. */ stopped = false; - private pushed(): void { - if (this.strings.length >= this.stopAfter && !this.stopped && this.control) { + private push(item: string | RichText): void { + if (this.keep) this.strings.push(item); + this.count++; + if (this.count >= this.stopAfter && !this.stopped && this.control) { this.stopped = true; this.control.skipToEndOf(1); } @@ -261,15 +267,13 @@ export class SharedStringsParser implements XmlHandler { return; } if (name === "si") { - if (this.strings.length >= this.max) { + if (this.count >= this.max) { throw new LimitError("LIMIT_EXCEEDED", `More than maxSharedStrings (${this.max}) shared strings.`, { - details: { limit: "maxSharedStrings", value: this.strings.length + 1, max: this.max }, + details: { limit: "maxSharedStrings", value: this.count + 1, max: this.max }, }); } - if (empty) { - this.strings.push(""); - this.pushed(); - } else { + if (empty) this.push(""); + else { this.item = new StringItem(this.charge, this.maxText); this.depth = 0; } @@ -279,9 +283,9 @@ export class SharedStringsParser implements XmlHandler { close(name: string): void { if (!this.item) return; if (this.depth === 0 && name === "si") { - this.strings.push(this.item.value(this.mode)); + const value = this.item.value(this.mode); this.item = undefined; - this.pushed(); + this.push(value); return; } this.depth--; diff --git a/packages/javascript-excel/src/read.ts b/packages/javascript-excel/src/read.ts index 8d58ce9..d31a209 100644 --- a/packages/javascript-excel/src/read.ts +++ b/packages/javascript-excel/src/read.ts @@ -14,11 +14,12 @@ import type { BinaryInput } from "./binary"; import { toBytes } from "./internal/input"; import { DEFAULT_LIMITS } from "./internal/read/limits"; +import { inspectImpl } from "./internal/read/inspect"; import { detectFormatImpl, readImpl, readSheetNamesImpl } from "./internal/read/reader"; import type { Cell, Workbook } from "./model"; import type { AbortSignalLike } from "./signal"; import type { Progress } from "./write"; -import type { ExcelWarning } from "./warnings"; +import type { ExcelPartKind, ExcelWarning } from "./warnings"; export type { BinaryInput, BlobLike, BlobType } from "./binary"; export type { AbortSignalLike } from "./signal"; @@ -249,3 +250,57 @@ export async function read(input: BinaryInput, options?: ReadOptions): Promise | undefined; + /** Rejects with `signal.reason` when aborted. */ + signal?: AbortSignalLike | undefined; +} + +/** The formats `inspect` (like `read`) accepts. */ +export type InspectFormat = "xlsx" | "xlsm" | "xltx" | "xltm"; + +/** A worksheet as `inspect` found it. */ +export interface InspectedSheet { + name: string; + /** Position among the worksheets, as in `readSheetNames` and `read`'s `workbook.sheets`. */ + index: number; + state: "visible" | "hidden" | "veryHidden"; + /** The sheet's part; left out when the part is missing (`read` gives an empty sheet). */ + part?: string; + /** Cells `read` would return with values, formulas or styles, as `maxCells` counts them (hyperlink-only cells are not counted). */ + cells: number; + /** The used range of those cells, as `read` sets `sheet.dimension`; left out for a sheet without cells. */ + dimension?: string; +} + +/** Result of `inspect`. */ +export interface InspectResult { + format: InspectFormat; + /** The worksheets in book order (chart, dialog and macro sheets are part kinds, not worksheets). */ + sheets: InspectedSheet[]; + /** The kinds of the `warnings`, each once, in the order found. */ + partKinds: ExcelPartKind[]; + /** The `UNSUPPORTED_PART` warnings `read` gives for this file, the same objects (no other warnings, and not capped by `maxWarnings`). */ + warnings: ExcelWarning[]; + /** Parts in the package (zip entries that are not folders). */ + parts: number; + /** Bytes inflated, counted as `maxTotalBytes` counts them (a part read twice counts twice). */ + inflatedBytes: number; + /** Cells of all worksheets together (the sum of `sheets[].cells`). */ + cells: number; + /** Items in the shared strings table. */ + sharedStrings: number; +} + +/** + * Checks an .xlsx, .xlsm, .xltx or .xltm file part by part without building + * its cells: every part `read` parses is parsed with the same checks and + * limits (every sheet to its end), every other part is inflated and, when it + * is XML, searched for a DOCTYPE. Throws what `read` throws for any file + * `read` refuses under the same limits (docs/api.md §5.2.1). + */ +export async function inspect(input: BinaryInput, options?: InspectOptions): Promise { + return inspectImpl(await toBytes(input, "inspect"), options); +} From 39e324ab91469d91fca05152519bc7eccf41fc32 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 11:22:36 +0100 Subject: [PATCH 03/22] JSE-71: document inspect() and add a changeset --- .changeset/inspect.md | 5 +++ docs/api.md | 70 ++++++++++++++++++++++++++++- packages/javascript-excel/README.md | 2 + 3 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 .changeset/inspect.md diff --git a/.changeset/inspect.md b/.changeset/inspect.md new file mode 100644 index 0000000..47e8dea --- /dev/null +++ b/.changeset/inspect.md @@ -0,0 +1,5 @@ +--- +"javascript-excel": minor +--- + +New `inspect(input, { limits, signal })` in `javascript-excel/read` checks an `.xlsx`, `.xlsm`, `.xltx` or `.xltm` file part by part without building its cells, for servers and browsers that must accept or refuse an upload without reading it into the model. Under the same limits it refuses every file `read` refuses, with the same error class, code and details (zip and reader limits, encryption, CFB and other formats, `NOT_XLSX`, `XML_DTD_FORBIDDEN`, malformed XML in the parts `read` parses, every sheet to its last row), and it returns `read`'s `UNSUPPORTED_PART` warnings with their `partKinds` (VBA, macro sheets, external links, connections, OLE objects, query tables, …), the format, the worksheets with their cell counts and used ranges, and the counts of parts, inflated bytes, cells and shared strings. It also inflates every part `read` never opens (zip limits and CRC-32 apply) and refuses a `DOCTYPE` in any XML part, so it can refuse files `read` accepts. It keeps no cells or shared strings: on a 1,000,000-cell sheet its peak heap was about 30 MB, against about 120 MB for `read`. `read` is unchanged. diff --git a/docs/api.md b/docs/api.md index c7055d3..76892f4 100644 --- a/docs/api.md +++ b/docs/api.md @@ -75,7 +75,7 @@ One npm package, `javascript-excel`, with subpath exports. `package.json` declar | Entry | Exports | Pulls in | Tree-shaking intent | |---|---|---|---| | `javascript-excel` | Model types; address, date, colour and style helpers; `fromDataset`, `fromDatasets`, `toDataset`; xlsx writer: `toUint8Array`, `toBlob`; error classes and `isExcelError` | Zip writer, XML writer | The default "build a file" path. No reader, no CSV, no DOM. | -| `javascript-excel/read` | `read`, `readSheetNames`, `detectFormat`, `ReadOptions`, `ReadLimits`, `DEFAULT_READ_LIMITS` | Zip reader, XML pull tokenizer | Only apps that open files pay for the reader. | +| `javascript-excel/read` | `read`, `readSheetNames`, `detectFormat`, `inspect`, `ReadOptions`, `ReadLimits`, `DEFAULT_READ_LIMITS`, `InspectOptions`, `InspectResult` | Zip reader, XML pull tokenizer | Only apps that open files pay for the reader. | | `javascript-excel/csv` | `parseCsv`, `readCsv`, `toCsv`, `toCsvBlob`, option types | Nothing from the xlsx code | CSV-only apps ship a few kB of CSV code and the model types. | | `javascript-excel/dom` | `fromTable`, `download` | DOM APIs, called only inside functions | The only module that touches `document`. Safe to import during SSR; calling it without a DOM throws `ENVIRONMENT_UNSUPPORTED`. | | `javascript-excel/worker` | `exposeWorker` (worker side), `createWorkerClient` (main-thread side) | Writer and reader, inside the worker only | Moves big jobs off the main thread. Main-thread code that imports only `createWorkerClient` does not ship the engine. | @@ -781,6 +781,7 @@ export type BinaryInput = Uint8Array | ArrayBuffer | BlobType; // Node Buffer export function read(input: BinaryInput, options?: ReadOptions): Promise; export function readSheetNames(input: BinaryInput, options?: Pick): Promise; export function detectFormat(input: BinaryInput): Promise; // never throws for unreadable input +export function inspect(input: BinaryInput, options?: InspectOptions): Promise; // §5.2.1 (2.5) export interface SheetInfo { name: string; index: number; state: 'visible' | 'hidden' | 'veryHidden' } export type DetectedFormat = 'xlsx' | 'xlsm' | 'xltx' | 'xltm' | 'xlsb' | 'ods' | 'cfb' | 'zip' | 'unknown'; // 'cfb' = .xls or an encrypted OOXML file @@ -909,6 +910,71 @@ How the reader works, as far as the API is concerned: - Print setup: the `_xlnm.Print_Area` and `_xlnm.Print_Titles` defined names become `sheet.print.printArea` and `printTitles` and are not repeated in `definedNames`; `_xlnm._FilterDatabase` is implied by `sheet.autoFilter` and dropped. - **Yielding** (JSE-24). As with the writer (§5.1), a read on the main thread used to be one long task in Chromium: for 100k and 300k rows of 7 columns in Chromium 150 that was about 535 and 1,580 ms with no frame rendered, and no timer, input or abort ran until the read finished. There were two causes. Awaiting the decompressor and the part parsers only runs microtasks. And each zip entry was written to `DecompressionStream` in one piece, which Chromium inflates in batches of up to about 50 ms. Now `read` (and `client.read` inside a worker) returns to the event loop between XML chunks of every streamed part (sheets, shared strings, styles, theme) once about 16 ms have passed, using the writer's mechanism (`setImmediate`, else `MessageChannel`, else `setTimeout(0)`). It also feeds compressed data to the decompressor in 256 KB slices. In `bench/browser/read-yield.bench.test.ts`, no task is over 50 ms, the longest gap between frames is 18 ms, and total time is within noise (+0.4 % to +2.3 %). The model is deep-equal to before on the conformance corpus and the read fixtures under five option sets, and on a 300k-row file. A read inside a worker takes the same time as before. The budget is internal, not an option. `readCsv` already yields between 1M-character chunks and is unchanged (17 ms frame gaps at 300k rows). Since 2.2 (JSE-52) the signal is also consulted while the workbook part is parsed (at least every 256 sheet entries), for every entry of the sheet list and every defined name (these steps also yield on the same budget), and between 256 KB slices of a stored (uncompressed) part, which the zip reader hands over in one piece. `readSheetNames` gets the same checks. Some steps are synchronous and consult the signal without yielding: building the relationship map and the unsupported-part warnings (every 4,096 relationships), attaching a sheet's hyperlinks when it is finished (every 4,096 hyperlinks, bounded by `maxItems`), filling in deferred shared strings with `maxRows` (every 4,096 cells, bounded by `maxCells`) and the CRC-32 of a stored entry before its first byte is used (every 1 MiB, bounded by `maxEntryBytes`). The zip central directory is read in one synchronous step bounded by `maxEntries`, and building a sheet's column objects in one step of at most 16,384 per sheet. So a long-running phase cannot outrun an abort, but at the default limits a single step can still take a few hundred milliseconds on a hostile file (about 0.5 s for 1M hyperlinks or relationships on an Apple-silicon laptop). +### 5.2.1 Inspect (`inspect`, added in 2.5) + +`inspect` checks a file the way `read` does, part by part, without building its cells. It is for a server or browser that must decide whether an upload is a real, safe workbook before (or instead of) reading it into the model: `read` of a 20 MiB `.xlsx` can hold well over a gigabyte of heap, and `maxRows` skips the rest of a sheet without checking it. + +```ts +export function inspect(input: BinaryInput, options?: InspectOptions): Promise; + +export interface InspectOptions { + limits?: Partial; // the same limits as read, the same defaults + signal?: AbortSignalLike; +} + +export type InspectFormat = 'xlsx' | 'xlsm' | 'xltx' | 'xltm'; + +export interface InspectResult { + format: InspectFormat; + sheets: InspectedSheet[]; // the worksheets, in book order (as read's workbook.sheets) + partKinds: ExcelPartKind[]; // the kinds of `warnings`, each once, in the order found + warnings: ExcelWarning[]; // read's UNSUPPORTED_PART warnings for the file; no other warnings; not capped + parts: number; // parts in the package (zip entries that are not folders) + inflatedBytes: number; // bytes inflated, as maxTotalBytes counts them + cells: number; // all worksheets, as maxCells counts them + sharedStrings: number; // items in the shared strings table +} + +export interface InspectedSheet { + name: string; + index: number; + state: 'visible' | 'hidden' | 'veryHidden'; + part?: string; // left out when the sheet's part is missing + cells: number; // cells read would return with a value, formula or style + dimension?: string; // read's sheet.dimension; left out for a sheet without cells +} +``` + +**The guarantee.** Under the same `limits`, every file `read` (with its default options) refuses, `inspect` refuses with the same error: the same class, `code` and `details`. Every `UNSUPPORTED_PART` warning `read` gives for a file, `inspect` returns (the same warning, with the same `partKind`), so a part kind `read` reports is in `partKinds`. Read options that read less (`sheets`, `styles: false`, `formulas: false`, `richText`, `dates`, `dateZone`, `rawText`) refuse no file that `inspect` accepts. `maxRows` is not covered: a capped read counts a cell whose shared string index is past the table toward `maxCells` before the strings are decoded, so with a tight `maxCells` it can refuse a file that the full read and `inspect` accept. + +How it is kept: `inspect` is `read`'s own code path with every check in the same order. The sheet and shared-string parsers run in a mode that converts, checks and counts each cell and string as `read` does and then drops it. So whatever `read` checks or reports in a later version, `inspect` checks and reports too. Tests hold it: a differential test over the repository's fixtures, the conformance corpus and generated hostile files (a `DOCTYPE` in each kind of part, zip and ratio bombs in read and unread parts, every zip and reader limit, encrypted, CFB, ODS, `.xlsb`, a zip that is not a workbook, truncated and corrupted archives, VBA, macro sheets, external links, connections, OLE objects, query tables), under the default limits, a tight set and each file's own limits; and a seeded fuzz of 3,000 mutated workbooks (their parts' text, their part list and relationships, their zipped bytes, random tight limits). + +**What it checks beyond read.** So `inspect` can refuse files `read` accepts: + +- Every zip entry is inflated to its end, including parts `read` never opens (images, VBA projects, OLE objects, drawings, comments, unreferenced parts): `maxEntryBytes`, `maxRatio` and the CRC-32 apply to each, and `maxTotalBytes` to all of them together. +- Every XML part `read` does not parse, and every optional part `read` stops parsing at malformed XML (the theme and the document properties, `BROKEN_OPTIONAL_PART`), is searched for a document type declaration and refused with `XML_DTD_FORBIDDEN` (`details.part` names it): parts whose content type ends in `xml` or `+xml`, or whose name ends in `.xml`, `.rels`, `.vml` or `.svg`, in UTF-8 or UTF-16. So an SVG image that carries a `` (as some editors export them) is refused. Such parts are not checked for well-formedness, because `read` does not parse them and Excel's own VML is not well-formed XML; binary parts are checked at the zip level only, and nested archives are never opened. + +**What it holds.** No cells, no shared strings, no merges, selections or row properties, and a hyperlink only when its cell could be past `maxColumns`. It still holds the input, the styles table, the relationship lists, the defined names, the warnings `read` would keep (bounded by `maxWarnings`), and for the sheet being checked its column definitions and shared-formula masters. Measured with a 1,000,000-cell sheet (Node 26, Apple M2, peak heap while it runs): `read` about 120 MB, `inspect` about 30 MB, the same as for 100,000 cells (most of it is garbage the young generation collects). The time is about `read`'s: every part is parsed and every cell converted. + +**The signal** is consulted as in `read` (§5.2, Yielding), between the parts `read` does not parse, and between 256 KB pieces of each XML part searched; the event loop gets a turn on the same budget. + +`inspect` reports no warnings other than `UNSUPPORTED_PART`: missing parts, broken optional parts and damaged cells are found by `read`, which keeps the cells they concern. + +```ts +import { isExcelError } from 'javascript-excel'; +import { inspect } from 'javascript-excel/read'; + +const limits = { maxColumns: 256, maxCells: 1_000_000, maxEntryBytes: 64 * 1024 * 1024, maxTotalBytes: 128 * 1024 * 1024 }; +try { + const report = await inspect(upload, { limits, signal: AbortSignal.timeout(10_000) }); + if (report.partKinds.includes('vbaProject') || report.partKinds.includes('externalLink')) refuse('active content'); + else accept(report.sheets.map((s) => `${s.name}: ${s.cells} cells`)); +} catch (err) { + if (isExcelError(err)) refuse(err.code); // LIMIT_EXCEEDED, XML_DTD_FORBIDDEN, ZIP_ENCRYPTED, UNSUPPORTED_FORMAT, NOT_XLSX, ... + else throw err; // the signal's reason +} +``` + ### 5.3 CSV (`javascript-excel/csv`) ```ts @@ -1800,6 +1866,7 @@ if (lost.length) throw new Error(`Refused: ${[...new Set(lost.map((w) => w.code) | **External references** | External links, OLE objects, DDE and data connections are not read or followed. The reader resolves relationships only within the package. | | **ReDoS** | Hot paths (A1 parsing, number detection, CSV) use hand-written scanners or linear regexes with no nested quantifiers. Format codes are bounded by part size. | | **Encrypted, legacy and macro content** | CFB containers (`.xls`, encrypted OOXML) throw `UNSUPPORTED_FORMAT`; VBA parts are dropped, never executed. | +| **Checking an upload without reading it** | `inspect` (§5.2.1) refuses every file `read` refuses under the same limits, with the same error, and returns the part kinds `read` reports (VBA, macro sheets, external links, connections, OLE objects, …), without building cells. It also inflates every part `read` leaves unopened and refuses a `DOCTYPE` in any XML part. | **Server guidance for untrusted uploads.** The defaults are sized for real workbooks in a browser tab. A server that reads files from strangers should tighten them and isolate the work: @@ -1810,6 +1877,7 @@ if (lost.length) throw new Error(`Refused: ${[...new Set(lost.map((w) => w.code) - `maxIssues` around 1,000 for `importDataset`; - `formulas: false` on `read` when the formula text is not needed: cells that share a formula then cost no more than other cells (`importDataset` already reads them so); - `maxEntryBytes` 64 MiB and `maxTotalBytes` 128 MiB; +- to accept or refuse an upload without reading it into the model, `inspect` with the same limits (§5.2.1); - run imports of untrusted files in a worker thread with a memory limit (`resourceLimits` in Node) and a wall-clock timeout that terminates it. An `AbortSignal` is consulted between steps, but it cannot interrupt a synchronous step such as the conversion of a read sheet into a dataset. Writer-side hygiene: all text and attributes are XML-escaped, and invalid XML characters are encoded (§3.4). A string that starts with `=` is text, never a formula. Sheet names and defined names are validated, and sheet names are quoted correctly in generated references (`'It''s'!A1`). diff --git a/packages/javascript-excel/README.md b/packages/javascript-excel/README.md index caeb4c5..80fbcd0 100644 --- a/packages/javascript-excel/README.md +++ b/packages/javascript-excel/README.md @@ -93,6 +93,8 @@ console.log(cell?.type, cell?.value, cell?.rawText); // "number" 50.3 "50.30" Damage the reader can recover from comes back as `warnings`. `isDataLossWarning(w)` tells the ones where data was lost (a cell skipped, rows cut, a part missing, comments or charts not read; `partKind` names the part) from informational ones; the warning cap (`limits.maxWarnings`, default 1,000) drops only informational warnings, so filtering `warnings` with it is enough to refuse a damaged file. +To accept or refuse an upload without reading it into the model, `inspect(file, { limits, signal })` checks it part by part without building cells: it refuses every file `read` refuses under the same limits, with the same error, and returns the format, the worksheets with their cell counts, and the part kinds `read` reports (`partKinds`: VBA, external links, OLE objects, …). It also inflates the parts `read` never opens and refuses a `DOCTYPE` in any XML part. See [docs/api.md §5.2.1](https://github.com/securedeveloper/javascript-excel/blob/main/docs/api.md#521-inspect-inspect-added-in-25). + ## CSV From 2d0cceaa8ae42e5286c797a56c548f093f01889b Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 11:36:48 +0100 Subject: [PATCH 04/22] JSE-71: measured memory of inspect on a 20 MiB file --- .changeset/inspect.md | 2 +- docs/api.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/inspect.md b/.changeset/inspect.md index 47e8dea..858f409 100644 --- a/.changeset/inspect.md +++ b/.changeset/inspect.md @@ -2,4 +2,4 @@ "javascript-excel": minor --- -New `inspect(input, { limits, signal })` in `javascript-excel/read` checks an `.xlsx`, `.xlsm`, `.xltx` or `.xltm` file part by part without building its cells, for servers and browsers that must accept or refuse an upload without reading it into the model. Under the same limits it refuses every file `read` refuses, with the same error class, code and details (zip and reader limits, encryption, CFB and other formats, `NOT_XLSX`, `XML_DTD_FORBIDDEN`, malformed XML in the parts `read` parses, every sheet to its last row), and it returns `read`'s `UNSUPPORTED_PART` warnings with their `partKinds` (VBA, macro sheets, external links, connections, OLE objects, query tables, …), the format, the worksheets with their cell counts and used ranges, and the counts of parts, inflated bytes, cells and shared strings. It also inflates every part `read` never opens (zip limits and CRC-32 apply) and refuses a `DOCTYPE` in any XML part, so it can refuse files `read` accepts. It keeps no cells or shared strings: on a 1,000,000-cell sheet its peak heap was about 30 MB, against about 120 MB for `read`. `read` is unchanged. +New `inspect(input, { limits, signal })` in `javascript-excel/read` checks an `.xlsx`, `.xlsm`, `.xltx` or `.xltm` file part by part without building its cells, for servers and browsers that must accept or refuse an upload without reading it into the model. Under the same limits it refuses every file `read` refuses, with the same error class, code and details (zip and reader limits, encryption, CFB and other formats, `NOT_XLSX`, `XML_DTD_FORBIDDEN`, malformed XML in the parts `read` parses, every sheet to its last row), and it returns `read`'s `UNSUPPORTED_PART` warnings with their `partKinds` (VBA, macro sheets, external links, connections, OLE objects, query tables, …), the format, the worksheets with their cell counts and used ranges, and the counts of parts, inflated bytes, cells and shared strings. It also inflates every part `read` never opens (zip limits and CRC-32 apply) and refuses a `DOCTYPE` in any XML part, so it can refuse files `read` accepts. It keeps no cells or shared strings: on a 19.8 MiB file of 3,420,000 cells its peak heap was about 30 MB, against about 410 MB for `read`, and it checks that file with the old generation limited to 32 MB. `read` is unchanged. diff --git a/docs/api.md b/docs/api.md index 76892f4..8b84c7f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -954,7 +954,7 @@ How it is kept: `inspect` is `read`'s own code path with every check in the same - Every zip entry is inflated to its end, including parts `read` never opens (images, VBA projects, OLE objects, drawings, comments, unreferenced parts): `maxEntryBytes`, `maxRatio` and the CRC-32 apply to each, and `maxTotalBytes` to all of them together. - Every XML part `read` does not parse, and every optional part `read` stops parsing at malformed XML (the theme and the document properties, `BROKEN_OPTIONAL_PART`), is searched for a document type declaration and refused with `XML_DTD_FORBIDDEN` (`details.part` names it): parts whose content type ends in `xml` or `+xml`, or whose name ends in `.xml`, `.rels`, `.vml` or `.svg`, in UTF-8 or UTF-16. So an SVG image that carries a `` (as some editors export them) is refused. Such parts are not checked for well-formedness, because `read` does not parse them and Excel's own VML is not well-formed XML; binary parts are checked at the zip level only, and nested archives are never opened. -**What it holds.** No cells, no shared strings, no merges, selections or row properties, and a hyperlink only when its cell could be past `maxColumns`. It still holds the input, the styles table, the relationship lists, the defined names, the warnings `read` would keep (bounded by `maxWarnings`), and for the sheet being checked its column definitions and shared-formula masters. Measured with a 1,000,000-cell sheet (Node 26, Apple M2, peak heap while it runs): `read` about 120 MB, `inspect` about 30 MB, the same as for 100,000 cells (most of it is garbage the young generation collects). The time is about `read`'s: every part is parsed and every cell converted. +**What it holds.** No cells, no shared strings, no merges, selections or row properties, and a hyperlink only when its cell could be past `maxColumns`. It still holds the input, the styles table, the relationship lists, the defined names, the warnings `read` would keep (bounded by `maxWarnings`), and for the sheet being checked its column definitions and shared-formula masters. Measured on Node 26 (Apple M2), peak heap while it runs: a 1,000,000-cell sheet, `read` about 120 MB and `inspect` about 30 MB, the same as for 100,000 cells (most of it is garbage the young generation collects); a 19.8 MiB file of 3,420,000 cells over two sheets, `read` about 410 MB in 2.2–2.5 s, `inspect` about 30 MB in 2.0–2.3 s. With the old generation limited to 32 MB (`--max-old-space-size=32`) `inspect` still checks that file; `read` runs out of memory at 256 MB. The time is about `read`'s: every part is parsed and every cell converted. **The signal** is consulted as in `read` (§5.2, Yielding), between the parts `read` does not parse, and between 256 KB pieces of each XML part searched; the event loop gets a turn on the same budget. From 974fb6a6e038e79844c2a2035a8acb0324c097a0 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 11:42:35 +0100 Subject: [PATCH 05/22] JSE-71: heap test bounds relative to the young generation's size --- packages/javascript-excel/test/read/inspect.test.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/javascript-excel/test/read/inspect.test.ts b/packages/javascript-excel/test/read/inspect.test.ts index 654bc33..fa7d133 100644 --- a/packages/javascript-excel/test/read/inspect.test.ts +++ b/packages/javascript-excel/test/read/inspect.test.ts @@ -297,10 +297,11 @@ describe("inspect: memory does not grow with the cells", () => { const r = await peak(() => read(big)); // Measured on Node 26 (Apple M2): read about 120 MB; inspect about 30 MB for either file (the young generation's garbage). console.log(`inspect 100k cells ${(s.peak / 1e6).toFixed(0)} MB, inspect 1M cells ${(i.peak / 1e6).toFixed(0)} MB, read 1M cells ${(r.peak / 1e6).toFixed(0)} MB (peak heap)`); + // The young generation's size differs by Node version and machine (CI's Node 24: inspect about 55 MB for + // either file, read 137 MB), so the bounds are relative: ten times the cells cost inspect about nothing more, + // and read, which keeps the cells, far more. expect(r.peak).toBeGreaterThan(80e6); - expect(i.peak).toBeLessThan(r.peak / 3); - expect(i.peak).toBeLessThan(48e6); - // Ten times the cells, about the same memory. + expect(i.peak).toBeLessThan(r.peak / 2); expect(i.peak).toBeLessThan(s.peak + 16e6); }, 60_000); }); From 0e9f5d2ef3ab985102932a9776f09ed17d2219ee Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 12:10:10 +0100 Subject: [PATCH 06/22] JSE-71 review: tests for shared-formula memory, encodings and the DOCTYPE search A sheet of 120,000 long shared-formula masters against short ones under a relative heap bound; copies' resolution decided as read decides it for any maxCellTextLength. XML parts in UTF-32, UTF-7, EBCDIC or declaring another encoding; DOCTYPE in parts named or typed as images or binaries, in UTF-7 and UTF-32 forms and across a slice boundary. The differential test now asserts no inspect-only refusal outside the hostile files. --- .../test/read/inspect-differential.test.ts | 2 + .../test/read/inspect-encoding.test.ts | 139 ++++++++++++++++++ .../test/read/inspect-files.ts | 44 ++++++ .../test/read/inspect-fuzz.test.ts | 3 + .../test/read/inspect.test.ts | 59 ++++++++ 5 files changed, 247 insertions(+) create mode 100644 packages/javascript-excel/test/read/inspect-encoding.test.ts diff --git a/packages/javascript-excel/test/read/inspect-differential.test.ts b/packages/javascript-excel/test/read/inspect-differential.test.ts index 437736a..15bbc34 100644 --- a/packages/javascript-excel/test/read/inspect-differential.test.ts +++ b/packages/javascript-excel/test/read/inspect-differential.test.ts @@ -57,6 +57,8 @@ describe("inspect vs read: the differential test", () => { } } console.log(`inspect differential: ${JSON.stringify(tally)}\ninspect refused, read accepted:\n ${inspectOnly.join("\n ")}`); + // No false positives: every fixture and corpus file read accepts, inspect accepts. + expect(inspectOnly.filter((l) => !l.startsWith("hostile:"))).toEqual([]); expect(tally.files).toBeGreaterThan(80); expect(tally["both-refuse"]).toBeGreaterThan(40); expect(tally["both-accept"]).toBeGreaterThan(40); diff --git a/packages/javascript-excel/test/read/inspect-encoding.test.ts b/packages/javascript-excel/test/read/inspect-encoding.test.ts new file mode 100644 index 0000000..094e97d --- /dev/null +++ b/packages/javascript-excel/test/read/inspect-encoding.test.ts @@ -0,0 +1,139 @@ +// JSE-71 review F2: the DOCTYPE search and the encodings of XML parts. +// Every part inspect inflates is searched for `'; +const WITH_DTD = `${DTD}`; + +function utf32(text: string, order: "le" | "be", bom: boolean): Uint8Array { + const cps = [...(bom ? "" : ""), ...text].map((c) => c.codePointAt(0)!); + const out = new Uint8Array(cps.length * 4); + const view = new DataView(out.buffer); + cps.forEach((cp, i) => view.setUint32(i * 4, cp, order === "le")); + return out; +} + +/** UTF-7 with every markup character base64-encoded, as a UTF-7 writer does. */ +function utf7(text: string): Uint8Array { + const map: Record = { "<": "+ADw-", ">": "+AD4-", '"': "+ACI-", "!": "+ACE-" }; + return new TextEncoder().encode([...text].map((c) => map[c] ?? c).join("")); +} + +/** IBM037 (EBCDIC) for the characters used here. */ +function ebcdic(text: string): Uint8Array { + const table: Record = { " ": 0x40, "<": 0x4c, "?": 0x6f, ">": 0x6e, "!": 0x5a, "=": 0x7e, '"': 0x7f, ".": 0x4b, "/": 0x61 }; + return Uint8Array.from([...text], (c) => { + if (table[c] !== undefined) return table[c]!; + const k = c.charCodeAt(0); + if (k >= 48 && k <= 57) return 0xf0 + k - 48; + const base = (lo: number, from: string) => lo + (k - from.charCodeAt(0)); + if (c >= "a" && c <= "i") return base(0x81, "a"); + if (c >= "j" && c <= "r") return base(0x91, "j"); + if (c >= "s" && c <= "z") return base(0xa2, "s"); + if (c >= "A" && c <= "I") return base(0xc1, "A"); + if (c >= "J" && c <= "R") return base(0xd1, "J"); + return base(0xe2, "S"); + }); +} + +async function refusal(p: Parts): Promise<{ code?: string; details?: Record } | undefined> { + return inspect(await zipParts(p)).then( + () => undefined, + (e: { code?: string; details?: Record }) => e, + ); +} + +function withPart(name: string, data: string | Uint8Array, edit?: (p: Parts) => void): Parts { + const p = richParts(); + p.set(name, data); + edit?.(p); + return p; +} + +describe("inspect: XML parts in encodings OPC does not allow (XML_MALFORMED, details.encoding)", () => { + it.each([ + ["UTF-32LE without a BOM", utf32(WITH_DTD, "le", false), "UTF-32LE"], + ["UTF-32LE with a BOM", utf32(WITH_DTD, "le", true), "UTF-32LE"], + ["UTF-32BE without a BOM", utf32(WITH_DTD, "be", false), "UTF-32BE"], + ["UTF-32BE with a BOM", utf32(WITH_DTD, "be", true), "UTF-32BE"], + ["UTF-32LE, no DOCTYPE", utf32(PLAIN, "le", false), "UTF-32LE"], + ["UTF-7", utf7(``), "UTF-7"], + ["EBCDIC", ebcdic(``), "EBCDIC"], + ["a declaration naming ISO-8859-1", ``, "ISO-8859-1"], + ])("a drawing in %s", async (_, data, encoding) => { + const err = await refusal(withPart(DRAWING, data)); + expect(err?.code).toBe("XML_MALFORMED"); + expect(err?.details).toMatchObject({ part: DRAWING, encoding }); + }); + + it("a part read parses (a worksheet) whose declaration names UTF-7: read accepts it, inspect refuses it", async () => { + const p = richParts(); + p.set("xl/worksheets/sheet2.xml", (p.get("xl/worksheets/sheet2.xml") as string).replace('', '')); + const bytes = await zipParts(p); + await expect(read(bytes)).resolves.toBeDefined(); + const err = await inspect(bytes).then(() => undefined, (e: { code?: string; details?: unknown }) => e); + expect(err?.code).toBe("XML_MALFORMED"); + expect(err?.details).toMatchObject({ part: "xl/worksheets/sheet2.xml", encoding: "UTF-7" }); + }); + + it("a part named .png that a drawing relationship points at is XML: in UTF-32 it is refused", async () => { + const p = withPart("xl/drawings/d.png", utf32(PLAIN, "le", false), (q) => { + q.set("xl/drawings/_rels/drawing1.xml.rels", (q.get("xl/drawings/_rels/drawing1.xml.rels") as string).replace("", '')); + }); + const err = await refusal(p); + expect(err?.code).toBe("XML_MALFORMED"); + expect(err?.details).toMatchObject({ part: "xl/drawings/d.png", encoding: "UTF-32LE" }); + }); + + it("UTF-8, UTF-16 with a BOM, and declarations naming UTF-8 or UTF-16 are accepted", async () => { + const u16 = (t: string) => Uint8Array.from([0xff, 0xfe, ...[...t].flatMap((c) => [c.charCodeAt(0), 0])]); + for (const data of [PLAIN, `${PLAIN}`, '', '', u16(PLAIN)]) { + expect(await refusal(withPart(DRAWING, data))).toBeUndefined(); + } + }); + + it("a binary part that is not XML may start with any bytes", async () => { + expect(await refusal(withPart("xl/vbaProject.bin", new Uint8Array([0x3c, 0, 0, 0, 0x4c, 0x6f, 0xa7, 0x94])))).toBeUndefined(); + expect(await refusal(withPart("xl/media/image1.png", utf32(PLAIN, "be", true)))).toBeUndefined(); + }); +}); + +describe("inspect: the DOCTYPE search covers every part, whatever its name or content type", () => { + it("a drawing relationship to xl/drawings/d.png (image/png) holding a DOCTYPE", async () => { + const p = withPart("xl/drawings/d.png", WITH_DTD, (q) => { + q.set("xl/drawings/_rels/drawing1.xml.rels", (q.get("xl/drawings/_rels/drawing1.xml.rels") as string).replace("", '')); + }); + expect((await refusal(p))?.code).toBe("XML_DTD_FORBIDDEN"); + }); + + it("VML held in a .bin part with a vmlDrawing content type", async () => { + const p = withPart("xl/drawings/vmlDrawing2.bin", `${DTD}`, (q) => { + q.set("[Content_Types].xml", (q.get("[Content_Types].xml") as string).replace("", '')); + }); + const err = await refusal(p); + expect(err?.code).toBe("XML_DTD_FORBIDDEN"); + expect(err?.details?.["part"]).toBe("xl/drawings/vmlDrawing2.bin"); + }); + + it.each([ + ["UTF-7", utf7("")], + ["UTF-32LE", utf32("", "le", false)], + ["UTF-32BE", utf32("", "be", false)], + ["UTF-16BE", Uint8Array.from([...""].flatMap((c) => [0, c.charCodeAt(0)]))], + ])("a %s DOCTYPE in an image", async (_, data) => { + const bytes = new Uint8Array(70_000 + data.length); + bytes.set(data, 65_530); // across a 64 KiB boundary + expect((await refusal(withPart("xl/media/image1.png", bytes)))?.code).toBe("XML_DTD_FORBIDDEN"); + }); + + it("documented false positive: a DOCTYPE inside a comment of a part read does not parse is refused", async () => { + expect((await refusal(withPart("xl/comments1.xml", ``)))?.code).toBe("XML_DTD_FORBIDDEN"); + }); +}); diff --git a/packages/javascript-excel/test/read/inspect-files.ts b/packages/javascript-excel/test/read/inspect-files.ts index 3f51671..4585e48 100644 --- a/packages/javascript-excel/test/read/inspect-files.ts +++ b/packages/javascript-excel/test/read/inspect-files.ts @@ -281,6 +281,50 @@ export function hostileFiles(): Hostile[] { return zipParts(p); }, }); + files.push({ + name: "UTF-32LE drawing without a BOM, with a DOCTYPE", + bytes: () => { + const p = richParts(); + const xml = withDtd(p.get("xl/drawings/drawing1.xml") as string); + const out = new Uint8Array(xml.length * 4); + for (let i = 0; i < xml.length; i++) out[4 * i] = xml.charCodeAt(i); + p.set("xl/drawings/drawing1.xml", out); + return zipParts(p); + }, + }); + files.push({ + name: "UTF-7 DOCTYPE in the comments part", + bytes: () => { + const p = richParts(); + p.set("xl/comments1.xml", '+ADw-?xml version=+ACI-1.0+ACI- encoding=+ACI-UTF-7+ACI-?+AD4-+ADw-+ACE-DOCTYPE r+AD4-+ADw-comments/+AD4-'); + return zipParts(p); + }, + }); + files.push({ + name: "worksheet declaring encoding UTF-7 (read accepts)", + bytes: () => { + const p = richParts(); + p.set("xl/worksheets/sheet2.xml", (p.get("xl/worksheets/sheet2.xml") as string).replace('', '')); + return zipParts(p); + }, + }); + files.push({ + name: "DOCTYPE in a .png a drawing relationship points at", + bytes: () => { + const p = richParts(); + p.set("xl/drawings/d.png", withDtd('')); + p.set("xl/drawings/_rels/drawing1.xml.rels", (p.get("xl/drawings/_rels/drawing1.xml.rels") as string).replace("", ``)); + return zipParts(p); + }, + }); + files.push({ + name: "DOCTYPE in VML held in a .bin part", + bytes: () => { + const p = richParts(); + p.set("xl/drawings/vmlDrawing2.bin", `${DTD}`); + return zipParts(p); + }, + }); // Zip limits. files.push({ name: "maxInputBytes", bytes: () => zipParts(richParts()), limits: { maxInputBytes: 1000 } }); files.push({ name: "maxEntries", bytes: () => zipParts(richParts()), limits: { maxEntries: 5 } }); diff --git a/packages/javascript-excel/test/read/inspect-fuzz.test.ts b/packages/javascript-excel/test/read/inspect-fuzz.test.ts index 3ae2b62..a085bea 100644 --- a/packages/javascript-excel/test/read/inspect-fuzz.test.ts +++ b/packages/javascript-excel/test/read/inspect-fuzz.test.ts @@ -32,6 +32,9 @@ const TOKENS = [ DTD, "", "", + "+ADw-!DOCTYPE x+AD4-", + '', + '', '1', '2', '999', diff --git a/packages/javascript-excel/test/read/inspect.test.ts b/packages/javascript-excel/test/read/inspect.test.ts index fa7d133..66430d1 100644 --- a/packages/javascript-excel/test/read/inspect.test.ts +++ b/packages/javascript-excel/test/read/inspect.test.ts @@ -306,6 +306,65 @@ describe("inspect: memory does not grow with the cells", () => { }, 60_000); }); +describe("inspect: shared-formula masters (review F1)", () => { + /** One sheet of `n` distinct shared-formula masters of about `len` characters, none of them shared by another cell. */ + function masters(n: number, len: number): Promise { + const unit = "SUM(A1:B2)*C3+"; + const body = unit.repeat(Math.ceil(len / unit.length)).slice(0, len); + const rows: string[] = []; + for (let r = 1; r <= n; r++) rows.push(`${body}${r}1`); + const p = richParts({ rows: 1 }); + p.set("xl/worksheets/sheet2.xml", `${rows.join("")}`); + return zipParts(p); + } + + /** Peak heap above the start while `fn` runs (as in the memory test above). */ + async function peakOf(fn: () => Promise): Promise { + const gc = await exposeGc(); + gc(); + const before = process.memoryUsage().heapUsed; + let max = before; + const timer = setInterval(() => { + const h = process.memoryUsage().heapUsed; + if (h > max) max = h; + }, 1); + try { + await fn(); + } finally { + clearInterval(timer); + } + return Math.max(max, process.memoryUsage().heapUsed) - before; + } + + it("120,000 masters of 600 characters (72 MB of formula text) cost inspect about what 120,000 short masters cost", async () => { + const long = await masters(120_000, 600); + const short = await masters(120_000, 4); + const s = await peakOf(() => inspect(short)); + const l = await peakOf(() => inspect(long)); + console.log(`inspect, 120,000 shared-formula masters: 4 characters ${(s / 1e6).toFixed(0)} MB, 600 characters ${(l / 1e6).toFixed(0)} MB (peak heap)`); + // Holding the masters' text would add at least 72 MB. + expect(l).toBeLessThan(s + 36e6); + }, 120_000); + + it("whether a shared copy resolves (and so whether a value-less cell counts) is decided as read decides it, for every maxCellTextLength", async () => { + // A master in C3 shared down and across; copies near the sheet's edges grow longer (XFD1048576 vs A1). + const master = Array.from({ length: 40 }, (_, k) => `A${k + 1}`).join("+"); + const cells = [`${master}`]; + for (const ref of ["D3", "C4", "AA30", "ZZ999", "AAA9999", "XFA1048000", "B2"]) cells.push(``); + const p = richParts({ rows: 1 }); + p.set("xl/worksheets/sheet2.xml", `${cells.join("")}`); + const bytes = await zipParts(p); + for (const maxCellTextLength of [master.length - 1, master.length, 150, 170, 200, 260, 300, 400, 1_000_000]) { + for (const maxCells of [12, 14, 100]) { + const limits = { maxCellTextLength, maxCells }; + const r = await read(bytes, { limits }).then((x) => ({ sheet: x.workbook.sheets[1]!.dimension, n: x.workbook.sheets[1]!.rows.flat().filter((c) => c && (c.formula !== undefined || c.value !== undefined)).length }), (e: { code: string; details: unknown }) => ({ code: e.code, details: e.details })); + const i = await inspect(bytes, { limits }).then((x) => ({ sheet: x.sheets[1]!.dimension, n: x.sheets[1]!.cells }), (e: { code: string; details: unknown }) => ({ code: e.code, details: e.details })); + expect(i, JSON.stringify(limits)).toEqual(r); + } + } + }); +}); + /** `global.gc`, made available at run time if node was not started with --expose-gc. */ async function exposeGc(): Promise<() => void> { const g = globalThis as { gc?: () => void }; From 4db9eccfb4400a30a39e6f198ea7ce201a900c75 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 12:10:10 +0100 Subject: [PATCH 07/22] JSE-71 review: lean shared-formula masters; DOCTYPE search over every part; XML encodings Without keepCells a shared-formula master keeps its position, length, relative bounds and whether its copies fit maxCellTextLength (from the range of lengths a copy can have), not its text, unless the limit falls inside that range. inspect searches the bytes of every part read does not parse for void) | undefined; /** Sees every warning before the cap applies (inspect collects UNSUPPORTED_PART with it, JSE-71). */ tap: ((w: ExcelWarning) => void) | undefined; + /** Sees the first inflated bytes of every part parsed as XML (inspect checks their encoding, JSE-71). */ + sniff: ((part: string, first: Uint8Array) => void) | undefined; /** Returns to the event loop about every 16 ms between chunks, so a big read does not freeze the page (JSE-24). */ private readonly pause = createYielder(); @@ -154,6 +156,7 @@ export class ReadContext { for await (const chunk of this.zip.stream(entry, this.signal)) { let bytes = chunk; if (!decoder) { + this.sniff?.(entry.name, chunk); decoder = newDecoder(chunk); bytes = stripBom(chunk); } diff --git a/packages/javascript-excel/src/internal/read/formula.ts b/packages/javascript-excel/src/internal/read/formula.ts index 0eab8b7..8daf6ba 100644 --- a/packages/javascript-excel/src/internal/read/formula.ts +++ b/packages/javascript-excel/src/internal/read/formula.ts @@ -250,6 +250,55 @@ export function shiftCompiled(c: CompiledFormula, dRow: number, dCol: number, ma return out; } +/** + * The shortest and longest text `c` can have when shifted by any offset that + * `canShift` allows: a relative column takes 1 to 3 letters, a relative row 1 + * to 7 digits. So a copy's length is known to fit maxCellTextLength (or not) + * without the formula's text whenever the limit is outside this range (JSE-71). + */ +export function shiftedLengthRange(c: CompiledFormula): [number, number] { + let min = c.literalLength; + let max = c.literalLength; + const col = (anchor: string, v: number): void => { + if (anchor === "$") { + const n = letters(v).length + 1; + min += n; + max += n; + } else { + min += 1; + max += 3; + } + }; + const row = (anchor: string, v: number): void => { + if (anchor === "$") { + const n = String(v).length + 1; + min += n; + max += n; + } else { + min += 1; + max += 7; + } + }; + for (const u of c.slots) { + const r = c.uniq[u]!; + if (r.kind === COLS_REF) { + col(r.aAnchor, r.a); + col(r.bAnchor, r.b); + min += 1; + max += 1; + } else if (r.kind === ROWS_REF) { + row(r.aAnchor, r.a); + row(r.bAnchor, r.b); + min += 1; + max += 1; + } else { + col(r.aAnchor, r.a); + row(r.bAnchor, r.b); + } + } + return [min, max]; +} + /** `formula` shifted by (dRow, dCol), or undefined when a reference would leave the sheet. */ export function shiftFormula(formula: string, dRow: number, dCol: number): string | undefined { if (dRow === 0 && dCol === 0) return formula; diff --git a/packages/javascript-excel/src/internal/read/inspect.ts b/packages/javascript-excel/src/internal/read/inspect.ts index a922140..ae7125b 100644 --- a/packages/javascript-excel/src/internal/read/inspect.ts +++ b/packages/javascript-excel/src/internal/read/inspect.ts @@ -6,33 +6,94 @@ * the same order, but with no cells and no shared strings kept (the sheet * and shared-strings parsers count instead). So inspect refuses what read * refuses, with the same error, and reports the part kinds read reports; - * whatever readImpl learns to check or report, inspect does too. Then every - * zip entry the read did not parse, or parsed only up to an error it forgave - * (a broken optional part), is inflated (zip limits, CRC) and, when it is - * XML, searched for a document type declaration. + * whatever readImpl learns to check or report, inspect does too. Only once + * that read has succeeded come the checks read does not make: + * - every XML part (by content type, by name, or as the target of a + * relationship of a kind that is not binary), including the parts read + * parses, must be in UTF-8 or UTF-16, as OPC requires; + * - every zip entry the read did not parse, or parsed only up to an error it + * forgave (a broken optional part), is inflated (zip limits, CRC) and its + * bytes searched for ` = new Set([ + "image", + "oleObject", + "package", + "vbaProject", + "vbaProjectSignature", + "vbaProjectSignatureAgile", + "vbaProjectSignatureV3", + "printerSettings", + "activeXControlBinary", + "thumbnail", + "font", + "media", + "audio", + "video", + "hyperlink", + "attachedTemplate", + "externalLinkPath", + "xlBinaryIndex", +]); + +/** Parts whose content type or name says XML. */ +function isXmlByName(pkg: Package, name: string): boolean { const type = (pkg.contentType(name) ?? "").toLowerCase(); - return /[+/]xml\s*(;|$)/.test(type) || /\.(xml|rels|vml|svg)$/i.test(name); + return /[+/]xml\s*(;|$)/.test(type) || type.endsWith("vmldrawing") || /\.(xml|rels|vml|svg)$/i.test(name); +} + +/** Bytes looked at for the encoding: the byte order mark and the XML declaration. */ +const HEAD = 1024; + +/** + * The encoding of an XML part's first bytes when OPC does not allow it + * (ECMA-376 Part 2: UTF-8 or UTF-16), else undefined: UTF-32 (with or + * without a byte order mark), UTF-7, EBCDIC, or a declaration naming any + * other encoding. + */ +export function forbiddenEncoding(b: Uint8Array): string | undefined { + const [b0, b1, b2, b3] = [b[0], b[1], b[2], b[3]]; + if (b0 === 0x00 && b1 === 0x00 && b2 === 0xfe && b3 === 0xff) return "UTF-32BE"; + if (b0 === 0xff && b1 === 0xfe && b2 === 0x00 && b3 === 0x00) return "UTF-32LE"; + if (b0 === 0x00 && b1 === 0x00 && b2 === 0x00 && b3 === 0x3c) return "UTF-32BE"; + if (b0 === 0x3c && b1 === 0x00 && b2 === 0x00 && b3 === 0x00) return "UTF-32LE"; + if ((b0 === 0x00 && b1 === 0x00 && b2 === 0x3c && b3 === 0x00) || (b0 === 0x00 && b1 === 0x3c && b2 === 0x00 && b3 === 0x00)) return "UCS-4"; + if (b0 === 0x4c && b1 === 0x6f && b2 === 0xa7 && b3 === 0x94) return "EBCDIC"; + if (b0 === 0x2b && b1 === 0x2f && b2 === 0x76) return "UTF-7"; + const text = newDecoder(b).decode(b.subarray(0, HEAD)); + if (/^?\s*\+AD[wx]/.test(text)) return "UTF-7"; + const decl = /^?\s*<\?xml\s[^>]*?\bencoding\s*=\s*(["'])([^"']*)\1/.exec(text); + if (decl && !/^utf-?(8|16(le|be)?)$/i.test(decl[2]!.trim())) return decl[2]!.trim(); + return undefined; +} + +function encodingError(part: string, encoding: string): FormatError { + return new FormatError("XML_MALFORMED", `${excerpt(part)}: the part is encoded in ${excerpt(encoding)}; XML parts must be UTF-8 or UTF-16.`, { + details: { part, encoding }, + }); } function doctype(): FormatError { @@ -40,15 +101,29 @@ function doctype(): FormatError { } export async function inspectImpl(bytes: Uint8Array, options?: InspectOptions): Promise { - const sink: InspectSink = { unsupported: [], broken: new Set(), sharedStrings: 0, sheets: [] }; + let badEncoding: { part: string; encoding: string } | undefined; + const sink: InspectSink = { + unsupported: [], + broken: new Set(), + sharedStrings: 0, + sheets: [], + // Parts read parses: their encoding is refused only once the read has succeeded, so read's own errors come first. + sniff: (part, first) => { + if (badEncoding) return; + const encoding = forbiddenEncoding(first); + if (encoding !== undefined) badEncoding = { part, encoding }; + }, + }; const { workbook } = await readImpl(bytes, { limits: options?.limits, signal: options?.signal }, { inspect: sink }); const ctx = sink.ctx!; const pkg = sink.pkg!; + const xmlTargets = await relationshipTargets(ctx, pkg, sink); + if (badEncoding) throw encodingError(badEncoding.part, badEncoding.encoding); for (const entry of ctx.zip.entries) { if (ctx.consumed.has(entry.name) && !sink.broken.has(entry.name)) continue; const pause = ctx.step(); if (pause) await pause; - await scanPart(ctx, entry, isXmlPart(pkg, entry.name)); + await scanPart(ctx, entry, isXmlByName(pkg, entry.name) || xmlTargets.has(entry.name.toLowerCase())); } const kinds = new Set(); for (const w of sink.unsupported) if (w.partKind !== undefined) kinds.add(w.partKind); @@ -72,38 +147,70 @@ export async function inspectImpl(bytes: Uint8Array, options?: InspectOptions): } /** - * Inflates one entry to its end, so the zip limits and its CRC are checked, - * and searches XML text for `> { + const out = new Set(); + for (const name of pkg.partNames) { + const m = /^(.*?)_rels\/([^/]+)\.rels$/i.exec(name); + if (!m) continue; + const pause = ctx.step(); + if (pause) await pause; + let rels; + try { + rels = await pkg.rels(`${m[1]}${m[2]}`); + } catch (err) { + if (err instanceof FormatError && err.code === "XML_MALFORMED") { + sink.broken.add(name); + continue; + } + throw err; + } + for (const r of rels) if (!r.external && !BINARY_KINDS.has(r.kind)) out.add(r.target.toLowerCase()); + } + return out; +} + +/** + * Inflates one entry to its end, so the zip limits and its CRC are checked; + * searches its bytes for ` { - let decoder: TextDecoderLike | undefined; let tail = ""; - const search = (text: string): void => { - const s = tail + text; - if (DOCTYPE.test(s)) throw doctype(); - tail = s.slice(-DOCTYPE_TAIL); - }; + let head: Uint8Array | undefined = xml ? new Uint8Array(0) : undefined; try { for await (const chunk of ctx.zip.stream(entry, ctx.signal)) { - if (xml) { - // A byte order mark selects UTF-16 and is dropped by the decoder, as in ctx.parse. - decoder ??= newDecoder(chunk); - for (let at = 0; at < chunk.length; ) { - const piece = chunk.subarray(at, at + PARSE_SLICE); - at += piece.length; - search(decoder.decode(piece, { stream: true })); - if (at < chunk.length) { - const pause = ctx.step(); - if (pause) await pause; - } + if (head) { + // The encoding is decided on the first bytes, before they are searched. + const more = new Uint8Array(Math.min(HEAD, head.length + chunk.length)); + more.set(head); + more.set(chunk.subarray(0, more.length - head.length), head.length); + head = more; + const encoding = forbiddenEncoding(head); + if (encoding !== undefined) throw encodingError(entry.name, encoding); + if (head.length >= HEAD) head = undefined; + } + for (let at = 0; at < chunk.length; ) { + const piece = chunk.subarray(at, at + PARSE_SLICE); + at += piece.length; + const s = tail + BYTES.decode(piece); + if (DOCTYPE.test(s)) throw doctype(); + tail = s.slice(-DOCTYPE_TAIL); + if (at < chunk.length) { + const pause = ctx.step(); + if (pause) await pause; } } const pause = ctx.step(); if (pause) await pause; } - if (decoder) search(decoder.decode()); } catch (err) { throw withPart(err, entry.name); } diff --git a/packages/javascript-excel/src/internal/read/reader.ts b/packages/javascript-excel/src/internal/read/reader.ts index fa943f0..3dfb4df 100644 --- a/packages/javascript-excel/src/internal/read/reader.ts +++ b/packages/javascript-excel/src/internal/read/reader.ts @@ -240,6 +240,8 @@ export interface InspectSink { unsupported: ExcelWarning[]; /** Parts whose XML was malformed and skipped (BROKEN_OPTIONAL_PART): not read to their end. */ broken: Set; + /** Given the first inflated bytes of every part the read parses as XML, from the first part on. */ + sniff: (part: string, first: Uint8Array) => void; /** Items in the shared strings table. */ sharedStrings: number; /** Per listed worksheet, in order: its part and the cells it has. */ @@ -266,6 +268,7 @@ export async function readImpl(input: BinaryInput, options?: ReadOptions, intern let ctx!: ReadContext; const { pkg, workbookPart, format } = await openPackage(bytes, limits, (zip) => { ctx = new ReadContext(zip, limits, o.signal, o.onWarning, o.onProgress); + if (internal?.inspect) ctx.sniff = internal.inspect.sniff; return ctx; }); ctx.progress({ phase: "unzip", ratio: 0.02 }); diff --git a/packages/javascript-excel/src/internal/read/sheet.ts b/packages/javascript-excel/src/internal/read/sheet.ts index a8d0364..6bbfd56 100644 --- a/packages/javascript-excel/src/internal/read/sheet.ts +++ b/packages/javascript-excel/src/internal/read/sheet.ts @@ -8,7 +8,7 @@ import type { Cell, CellValue, ColumnProps, Hyperlink, PrintSetup, RichText, RowProps, Sheet, SheetView } from "../../model"; import { LimitError } from "../../errors"; import type { ReadContext } from "./context"; -import { canShift, colLetters, colNumber, compileFormula, MAX_SHARED_FORMULA_LENGTH, shiftCompiled, type CompiledFormula } from "./formula"; +import { canShift, colLetters, colNumber, compileFormula, MAX_SHARED_FORMULA_LENGTH, shiftCompiled, shiftedLengthRange, type CompiledFormula } from "./formula"; import { isDateFormat } from "../../numfmt"; import type { Relationship } from "./opc"; import { serialToDate } from "../../dates"; @@ -104,6 +104,28 @@ interface PendingCell { inline: string | RichText | undefined; } +/** Shared by every lean master's bounds (they hold no segments or references). */ +const NONE: string[] = []; +const NO_SLOTS: number[] = []; +const NO_REFS: CompiledFormula["uniq"] = []; + +/** A shared formula's master, as a sheet keeps it until the sheet ends. */ +interface SharedMaster { + /** The text; "" for a lean master, whose copies' text is never built. */ + formula: string; + length: number; + row: number; + col: number; + ref: string; + compiled: CompiledFormula | undefined; + /** + * Lean masters only (keepCells false, JSE-71): whether every shifted copy + * fits maxCellTextLength. Undefined for a kept master, and for a lean one + * whose copies may or may not fit (it keeps its text, as read does). + */ + fits: boolean | undefined; +} + interface RawHyperlink { ref: string; relId: string | undefined; @@ -194,7 +216,7 @@ export class SheetParser implements XmlHandler { private readonly merges: string[] = []; private readonly hyperlinks: RawHyperlink[] = []; /** Shared formula masters by `si`; compiled when the first cell that shares one needs it. */ - private readonly shared = new Map(); + private readonly shared = new Map(); private view: SheetView | undefined; private print: PrintSetup | undefined; private fitToPage = false; @@ -824,16 +846,16 @@ export class SheetParser implements XmlHandler { if (p.f === undefined || !this.opts.formulas) return undefined; if (p.fType === "shared" && p.fSi !== undefined) { if (p.f !== "") { - this.shared.set(p.fSi, { formula: p.f, row: p.row, col: p.col, ref: p.ref, compiled: undefined }); + this.shared.set(p.fSi, this.keep ? { formula: p.f, length: p.f.length, row: p.row, col: p.col, ref: p.ref, compiled: undefined, fits: undefined } : this.leanMaster(p)); return { text: p.f }; } const master = this.shared.get(p.fSi); // importDataset ("master"): the cell carries the master's text, so no copy is built and the // result is the same as 2.3.0's for every master; only whether it resolves is decided. const masterText = this.opts.sharedFormulaText === "master"; - if (master && !masterText && master.formula.length > MAX_SHARED_FORMULA_LENGTH) { + if (master && !masterText && master.length > MAX_SHARED_FORMULA_LENGTH) { // Longer than Excel allows: not expanded into every cell that shares it (JSE-62). - this.unresolved(p, `: its master formula in cell ${master.ref} has ${master.formula.length} characters, more than Excel's limit of ${MAX_SHARED_FORMULA_LENGTH}`); + this.unresolved(p, `: its master formula in cell ${master.ref || `${colLetters(master.col + 1)}${master.row + 1}`} has ${master.length} characters, more than Excel's limit of ${MAX_SHARED_FORMULA_LENGTH}`); return undefined; } const dRow = master ? p.row - master.row : 0; @@ -848,6 +870,12 @@ export class SheetParser implements XmlHandler { // Each shifted copy is cell text: one longer than maxCellTextLength is not built, and the // cell keeps its cached value, as for an over-long master (the read goes on, as in 2.3.0). const max = this.ctx.limits.maxCellTextLength; + if (master.fits !== undefined) { + // A lean master (keepCells false): the length range already decided it for every offset. + if (master.fits) return { text: "" }; + this.unresolved(p, `: shifted, it would have more than maxCellTextLength (${max}) characters`); + return undefined; + } const text = shiftCompiled(compiled, dRow, dCol, max); if (typeof text === "number") { this.unresolved(p, `: shifted, it would have ${text} characters, more than maxCellTextLength (${max})`); @@ -861,6 +889,27 @@ export class SheetParser implements XmlHandler { return { text: p.f }; } + /** + * keepCells false (JSE-71): a master without its text, so that a sheet of + * many long masters does not hold them all. Kept: the length, the position + * and the relative bounds (canShift); and whether a copy fits + * maxCellTextLength, from the range of lengths a copy can have. Only when + * the limit falls inside that range is the text kept, to decide per copy. + */ + private leanMaster(p: PendingCell): SharedMaster { + const f = p.f!; + // The ref is only for a warning message; a lean master rebuilds it from row and col (masterRef). + const base = { length: f.length, row: p.row, col: p.col, ref: "" }; + // Longer than Excel allows: never expanded, whatever is kept (formula()). + if (f.length > MAX_SHARED_FORMULA_LENGTH) return { ...base, formula: "", compiled: undefined, fits: false }; + const full = compileFormula(f); + const [min, max] = shiftedLengthRange(full); + const limit = this.ctx.limits.maxCellTextLength; + if (min <= limit && max > limit) return { ...base, formula: f, compiled: full, fits: undefined }; + const bounds: CompiledFormula = { source: "", segs: NONE, slots: NO_SLOTS, uniq: NO_REFS, literalLength: 0, rowMin: full.rowMin, rowMax: full.rowMax, colMin: full.colMin, colMax: full.colMax }; + return { ...base, formula: "", compiled: bounds, fits: max <= limit }; + } + private unresolved(p: PendingCell, why: string): void { this.ctx.warn("SHARED_FORMULA_UNRESOLVED", `The shared formula of cell ${p.ref} could not be resolved${why}; only its cached value was read.`, { part: this.part, diff --git a/packages/javascript-excel/src/read.ts b/packages/javascript-excel/src/read.ts index d31a209..ea69929 100644 --- a/packages/javascript-excel/src/read.ts +++ b/packages/javascript-excel/src/read.ts @@ -269,7 +269,7 @@ export interface InspectedSheet { state: "visible" | "hidden" | "veryHidden"; /** The sheet's part; left out when the part is missing (`read` gives an empty sheet). */ part?: string; - /** Cells `read` would return with values, formulas or styles, as `maxCells` counts them (hyperlink-only cells are not counted). */ + /** Cells as `maxCells` counts them: each `` kept with a value, formula or style (a cell written twice counts twice; hyperlink-only cells are not counted). */ cells: number; /** The used range of those cells, as `read` sets `sheet.dimension`; left out for a sheet without cells. */ dimension?: string; @@ -288,7 +288,7 @@ export interface InspectResult { parts: number; /** Bytes inflated, counted as `maxTotalBytes` counts them (a part read twice counts twice). */ inflatedBytes: number; - /** Cells of all worksheets together (the sum of `sheets[].cells`). */ + /** Cells of all worksheets together, as `maxCells` counts them (the sum of `sheets[].cells`). */ cells: number; /** Items in the shared strings table. */ sharedStrings: number; @@ -297,8 +297,8 @@ export interface InspectResult { /** * Checks an .xlsx, .xlsm, .xltx or .xltm file part by part without building * its cells: every part `read` parses is parsed with the same checks and - * limits (every sheet to its end), every other part is inflated and, when it - * is XML, searched for a DOCTYPE. Throws what `read` throws for any file + * limits (every sheet to its end), every other part is inflated and its + * bytes searched for a DOCTYPE, and XML parts must be UTF-8 or UTF-16. Throws what `read` throws for any file * `read` refuses under the same limits (docs/api.md §5.2.1). */ export async function inspect(input: BinaryInput, options?: InspectOptions): Promise { From 8b24cdbbfa58eb93ef93f97f281bb1c5262686cc Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 12:10:10 +0100 Subject: [PATCH 08/22] JSE-71 review: document the DOCTYPE search, the encoding check, false positives and maxItems --- .changeset/inspect.md | 2 +- docs/api.md | 27 ++++++++++++++++----------- packages/javascript-excel/README.md | 2 +- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/.changeset/inspect.md b/.changeset/inspect.md index 858f409..799473b 100644 --- a/.changeset/inspect.md +++ b/.changeset/inspect.md @@ -2,4 +2,4 @@ "javascript-excel": minor --- -New `inspect(input, { limits, signal })` in `javascript-excel/read` checks an `.xlsx`, `.xlsm`, `.xltx` or `.xltm` file part by part without building its cells, for servers and browsers that must accept or refuse an upload without reading it into the model. Under the same limits it refuses every file `read` refuses, with the same error class, code and details (zip and reader limits, encryption, CFB and other formats, `NOT_XLSX`, `XML_DTD_FORBIDDEN`, malformed XML in the parts `read` parses, every sheet to its last row), and it returns `read`'s `UNSUPPORTED_PART` warnings with their `partKinds` (VBA, macro sheets, external links, connections, OLE objects, query tables, …), the format, the worksheets with their cell counts and used ranges, and the counts of parts, inflated bytes, cells and shared strings. It also inflates every part `read` never opens (zip limits and CRC-32 apply) and refuses a `DOCTYPE` in any XML part, so it can refuse files `read` accepts. It keeps no cells or shared strings: on a 19.8 MiB file of 3,420,000 cells its peak heap was about 30 MB, against about 410 MB for `read`, and it checks that file with the old generation limited to 32 MB. `read` is unchanged. +New `inspect(input, { limits, signal })` in `javascript-excel/read` checks an `.xlsx`, `.xlsm`, `.xltx` or `.xltm` file part by part without building its cells, for servers and browsers that must accept or refuse an upload without reading it into the model. Under the same limits it refuses every file `read` refuses, with the same error class, code and details (zip and reader limits, encryption, CFB and other formats, `NOT_XLSX`, `XML_DTD_FORBIDDEN`, malformed XML in the parts `read` parses, every sheet to its last row), and it returns `read`'s `UNSUPPORTED_PART` warnings with their `partKinds` (VBA, macro sheets, external links, connections, OLE objects, query tables, …), the format, the worksheets with their cell counts (as `maxCells` counts them) and used ranges, and the counts of parts, inflated bytes, cells and shared strings. It also inflates every part `read` never opens (zip limits and CRC-32 apply) and searches its bytes for ` kept with a value, formula or style, a cell written twice counted twice dimension?: string; // read's sheet.dimension; left out for a sheet without cells } ``` **The guarantee.** Under the same `limits`, every file `read` (with its default options) refuses, `inspect` refuses with the same error: the same class, `code` and `details`. Every `UNSUPPORTED_PART` warning `read` gives for a file, `inspect` returns (the same warning, with the same `partKind`), so a part kind `read` reports is in `partKinds`. Read options that read less (`sheets`, `styles: false`, `formulas: false`, `richText`, `dates`, `dateZone`, `rawText`) refuse no file that `inspect` accepts. `maxRows` is not covered: a capped read counts a cell whose shared string index is past the table toward `maxCells` before the strings are decoded, so with a tight `maxCells` it can refuse a file that the full read and `inspect` accept. -How it is kept: `inspect` is `read`'s own code path with every check in the same order. The sheet and shared-string parsers run in a mode that converts, checks and counts each cell and string as `read` does and then drops it. So whatever `read` checks or reports in a later version, `inspect` checks and reports too. Tests hold it: a differential test over the repository's fixtures, the conformance corpus and generated hostile files (a `DOCTYPE` in each kind of part, zip and ratio bombs in read and unread parts, every zip and reader limit, encrypted, CFB, ODS, `.xlsb`, a zip that is not a workbook, truncated and corrupted archives, VBA, macro sheets, external links, connections, OLE objects, query tables), under the default limits, a tight set and each file's own limits; and a seeded fuzz of 3,000 mutated workbooks (their parts' text, their part list and relationships, their zipped bytes, random tight limits). +How it is kept: `inspect` is `read`'s own code path with every check in the same order. The sheet and shared-string parsers run in a mode that converts, checks and counts each cell and string as `read` does and then drops it. So whatever `read` checks or reports in a later version, `inspect` checks and reports too. Tests hold it: a differential test over the repository's fixtures, the conformance corpus and generated hostile files (a `DOCTYPE` in each kind of part and in parts named or typed as images or binaries, XML parts in UTF-32, UTF-7 or EBCDIC or declaring another encoding, zip and ratio bombs in read and unread parts, every zip and reader limit, encrypted, CFB, ODS, `.xlsb`, a zip that is not a workbook, truncated and corrupted archives, VBA, macro sheets, external links, connections, OLE objects, query tables), under the default limits, a tight set and each file's own limits; and a seeded fuzz of 3,000 mutated workbooks (their parts' text, their part list and relationships, their zipped bytes, random tight limits). **What it checks beyond read.** So `inspect` can refuse files `read` accepts: - Every zip entry is inflated to its end, including parts `read` never opens (images, VBA projects, OLE objects, drawings, comments, unreferenced parts): `maxEntryBytes`, `maxRatio` and the CRC-32 apply to each, and `maxTotalBytes` to all of them together. -- Every XML part `read` does not parse, and every optional part `read` stops parsing at malformed XML (the theme and the document properties, `BROKEN_OPTIONAL_PART`), is searched for a document type declaration and refused with `XML_DTD_FORBIDDEN` (`details.part` names it): parts whose content type ends in `xml` or `+xml`, or whose name ends in `.xml`, `.rels`, `.vml` or `.svg`, in UTF-8 or UTF-16. So an SVG image that carries a `` (as some editors export them) is refused. Such parts are not checked for well-formedness, because `read` does not parse them and Excel's own VML is not well-formed XML; binary parts are checked at the zip level only, and nested archives are never opened. +- **Every part `read` does not parse, whatever its name or content type**, and every optional part `read` stops parsing at malformed XML (the theme and the document properties, `BROKEN_OPTIONAL_PART`), has its bytes searched for `` (as some editors export them); and any binary part (image, VBA project, OLE object or embedded file stored without compression, printer settings) whose bytes happen to contain the letters ` `${s.name}: ${s.cells} cells`)); } catch (err) { - if (isExcelError(err)) refuse(err.code); // LIMIT_EXCEEDED, XML_DTD_FORBIDDEN, ZIP_ENCRYPTED, UNSUPPORTED_FORMAT, NOT_XLSX, ... + if (isExcelError(err)) refuse(err.code); // LIMIT_EXCEEDED, XML_DTD_FORBIDDEN, XML_MALFORMED, ZIP_ENCRYPTED, UNSUPPORTED_FORMAT, NOT_XLSX, ... else throw err; // the signal's reason } ``` @@ -1751,7 +1756,7 @@ Aborts are not `ExcelError`s: they reject with `signal.reason`, as `fetch` does. | `UNSUPPORTED_FORMAT` | Format | `.xls`/encrypted (CFB), `.xlsb`, `.ods`, and Strict OOXML if not mapped (§5.2); `details.format` says which | | `NOT_XLSX` | Format | A zip without a workbook part | | `ZIP_INVALID` / `ZIP_UNSUPPORTED_METHOD` / `ZIP_ENCRYPTED` / `ZIP_CRC_MISMATCH` | Format | §6 | -| `XML_MALFORMED` | Format | Not well-formed XML in a required part | +| `XML_MALFORMED` | Format | Not well-formed XML in a required part; from `inspect`, also an XML part in an encoding other than UTF-8 or UTF-16 (`details.encoding`) | | `XML_DTD_FORBIDDEN` | Format | Any ` w.code) | **External references** | External links, OLE objects, DDE and data connections are not read or followed. The reader resolves relationships only within the package. | | **ReDoS** | Hot paths (A1 parsing, number detection, CSV) use hand-written scanners or linear regexes with no nested quantifiers. Format codes are bounded by part size. | | **Encrypted, legacy and macro content** | CFB containers (`.xls`, encrypted OOXML) throw `UNSUPPORTED_FORMAT`; VBA parts are dropped, never executed. | -| **Checking an upload without reading it** | `inspect` (§5.2.1) refuses every file `read` refuses under the same limits, with the same error, and returns the part kinds `read` reports (VBA, macro sheets, external links, connections, OLE objects, …), without building cells. It also inflates every part `read` leaves unopened and refuses a `DOCTYPE` in any XML part. | +| **Checking an upload without reading it** | `inspect` (§5.2.1) refuses every file `read` refuses under the same limits, with the same error, and returns the part kinds `read` reports (VBA, macro sheets, external links, connections, OLE objects, …), without building cells. It also inflates every part `read` leaves unopened, searches the bytes of each for ` w.code) - `maxIssues` around 1,000 for `importDataset`; - `formulas: false` on `read` when the formula text is not needed: cells that share a formula then cost no more than other cells (`importDataset` already reads them so); - `maxEntryBytes` 64 MiB and `maxTotalBytes` 128 MiB; -- to accept or refuse an upload without reading it into the model, `inspect` with the same limits (§5.2.1); +- to accept or refuse an upload without reading it into the model, `inspect` with the same limits (§5.2.1), including `maxItems`, which bounds the styles and defined names it holds; - run imports of untrusted files in a worker thread with a memory limit (`resourceLimits` in Node) and a wall-clock timeout that terminates it. An `AbortSignal` is consulted between steps, but it cannot interrupt a synchronous step such as the conversion of a read sheet into a dataset. Writer-side hygiene: all text and attributes are XML-escaped, and invalid XML characters are encoded (§3.4). A string that starts with `=` is text, never a formula. Sheet names and defined names are validated, and sheet names are quoted correctly in generated references (`'It''s'!A1`). diff --git a/packages/javascript-excel/README.md b/packages/javascript-excel/README.md index 80fbcd0..b0429cc 100644 --- a/packages/javascript-excel/README.md +++ b/packages/javascript-excel/README.md @@ -93,7 +93,7 @@ console.log(cell?.type, cell?.value, cell?.rawText); // "number" 50.3 "50.30" Damage the reader can recover from comes back as `warnings`. `isDataLossWarning(w)` tells the ones where data was lost (a cell skipped, rows cut, a part missing, comments or charts not read; `partKind` names the part) from informational ones; the warning cap (`limits.maxWarnings`, default 1,000) drops only informational warnings, so filtering `warnings` with it is enough to refuse a damaged file. -To accept or refuse an upload without reading it into the model, `inspect(file, { limits, signal })` checks it part by part without building cells: it refuses every file `read` refuses under the same limits, with the same error, and returns the format, the worksheets with their cell counts, and the part kinds `read` reports (`partKinds`: VBA, external links, OLE objects, …). It also inflates the parts `read` never opens and refuses a `DOCTYPE` in any XML part. See [docs/api.md §5.2.1](https://github.com/securedeveloper/javascript-excel/blob/main/docs/api.md#521-inspect-inspect-added-in-25). +To accept or refuse an upload without reading it into the model, `inspect(file, { limits, signal })` checks it part by part without building cells: it refuses every file `read` refuses under the same limits, with the same error, and returns the format, the worksheets with their cell counts, and the part kinds `read` reports (`partKinds`: VBA, external links, OLE objects, …). It also inflates the parts `read` never opens, searches the bytes of every one of them for ` Date: Wed, 2 Dec 2026 13:17:11 +0100 Subject: [PATCH 09/22] JSE-71 review 2: tests for chunked and long declarations, straddling masters, rels counted once A sheet declaring UTF-7 after 1,100 spaces; the same sheet inflated as a 10-byte first chunk; unparsed parts with a long declaration and UTF-7 DOCTYPE spellings; an upper-case , i: Outcome): "both-refuse" | "inspect-only" | "both-accept" { if (r.err !== undefined) { expect(i.err, `${label}: read threw ${describeError(r.err)}; inspect accepted`).toBeDefined(); + // The one documented exception (docs/api.md §5.2.1): inspect's own budget for shared-formula reference + // records may refuse with maxItems before an error read gives later in the file. + if ((i.err as { details?: Record }).details?.["sharedFormulaReferences"] !== undefined) return "inspect-only"; const re = r.err as { constructor: unknown; code?: string; details?: unknown }; const ie = i.err as { constructor: unknown; code?: string; details?: unknown }; if (!isExcelError(r.err)) { diff --git a/packages/javascript-excel/test/read/inspect-encoding.test.ts b/packages/javascript-excel/test/read/inspect-encoding.test.ts index 094e97d..87c96f7 100644 --- a/packages/javascript-excel/test/read/inspect-encoding.test.ts +++ b/packages/javascript-excel/test/read/inspect-encoding.test.ts @@ -6,7 +6,8 @@ // `details.encoding`. import { describe, expect, it } from "vitest"; import { inspect, read } from "../../src/read"; -import { DTD, richParts, zipParts, type Parts } from "./inspect-files"; +import { build } from "./build"; +import { DTD, rawZip, richParts, storedBlocks, zipParts, type Parts } from "./inspect-files"; const DRAWING = "xl/drawings/drawing1.xml"; const PLAIN = ''; @@ -137,3 +138,96 @@ describe("inspect: the DOCTYPE search covers every part, whatever its name or co expect((await refusal(withPart("xl/comments1.xml", ``)))?.code).toBe("XML_DTD_FORBIDDEN"); }); }); + +describe("inspect: the encoding is decided on the whole declaration, however the part is chunked (review 2)", () => { + const UTF7_DTD = ""; + const sheet = (decl: string) => `${decl}${UTF7_DTD}1`; + + it("A: a parsed sheet whose declaration puts encoding=\"UTF-7\" after 1,100 spaces", async () => { + const p = richParts(); + p.set("xl/worksheets/sheet2.xml", sheet(``)); + const bytes = await zipParts(p); + await expect(read(bytes)).resolves.toBeDefined(); + const err = await refusal(p); + expect(err?.code).toBe("XML_MALFORMED"); + expect(err?.details).toMatchObject({ part: "xl/worksheets/sheet2.xml", encoding: "UTF-7" }); + }); + + it("B: a parsed sheet whose first inflated chunk is 10 bytes (stored blocks), then 60,000 empty blocks", async () => { + const p = richParts(); + const xml = sheet(''); + p.set("xl/worksheets/sheet2.xml", xml); + const bytes = rawZip(p, { "xl/worksheets/sheet2.xml": storedBlocks(new TextEncoder().encode(xml), 10, 60_000) }); + await expect(read(bytes)).resolves.toBeDefined(); + const err = await inspect(bytes).then(() => undefined, (e: { code?: string; details?: Record }) => e); + expect(err?.code).toBe("XML_MALFORMED"); + expect(err?.details).toMatchObject({ part: "xl/worksheets/sheet2.xml", encoding: "UTF-7" }); + }); + + it("B': a byte order mark split over 1-byte chunks is still seen (UTF-32LE)", async () => { + const p = richParts(); + const data = utf32(PLAIN, "le", true); + p.set(DRAWING, data); + p.set("xl/worksheets/sheet2.xml", data); + const bytes = rawZip(p, { [DRAWING]: storedBlocks(data, 1, 3), "xl/worksheets/sheet2.xml": storedBlocks(data, 1, 3) }); + const err = await inspect(bytes).then(() => undefined, (e: { code?: string; details?: Record }) => e); + expect(err?.code).toMatch(/^XML_MALFORMED$/); + }); + + it.each([ + ["+ADw!DOCTYPE (a base64 run ended by '!')", "+ADw!DOCTYPE r+AD4-"], + ["+ADwAIQBE-OCTYPE", "+ADwAIQBE-OCTYPE r+AD4-"], + ["+AHgAPAAh-DOCTYPE", "+AHgAPAAh-DOCTYPE r+AD4-"], + ])("an unparsed drawing with a 1,100-space declaration naming UTF-7 and %s", async (_, body) => { + const err = await refusal(withPart(DRAWING, `${body}`)); + expect(err?.code).toBe("XML_MALFORMED"); + expect(err?.details).toMatchObject({ part: DRAWING, encoding: "UTF-7" }); + }); + + it("an unparsed drawing whose declaration arrives in 10-byte chunks", async () => { + const p = richParts(); + const xml = ``; + p.set(DRAWING, xml); + const bytes = rawZip(p, { [DRAWING]: storedBlocks(new TextEncoder().encode(xml), 10, 5_000) }); + const err = await inspect(bytes).then(() => undefined, (e: { code?: string; details?: Record }) => e); + expect(err?.details).toMatchObject({ part: DRAWING, encoding: "UTF-7" }); + }); + + it("an upper-case is checked like a declaration (XML parsers reject it as a reserved target)", async () => { + const err = await refusal(withPart(DRAWING, ``)); + expect(err?.details).toMatchObject({ part: DRAWING, encoding: "UTF-7" }); + }); + + it("an unparsed declaration longer than maxXmlTokenLength is refused as a token would be", async () => { + const p = withPart(DRAWING, ``); + const err = await inspect(await zipParts(p), { limits: { maxXmlTokenLength: 200 } }).then(() => undefined, (e: { code?: string; details?: Record }) => e); + expect(err?.code).toBe("LIMIT_EXCEEDED"); + expect(err?.details).toMatchObject({ limit: "maxXmlTokenLength", part: DRAWING }); + }); + + it("details.encoding is a short, printable excerpt of what the file declares", async () => { + const err = await refusal(withPart(DRAWING, ``)); + expect(err?.code).toBe("XML_MALFORMED"); + const encoding = err?.details?.["encoding"] as string; + expect(encoding.length).toBeLessThanOrEqual(40); + expect(encoding).toMatch(/^[\x20-\x7e]*$/); + }); +}); + +describe("inspect: relationship parts read already parsed are not counted twice (review 2)", () => { + it("a file read reads at exactly maxTotalBytes is inspected at that limit", async () => { + // Every part of this file is parsed by read, so inspect inflates nothing more. + const bytes = await build({ sheets: ['1'] }); + let lo = 1; + let hi = 1_000_000; + while (lo < hi) { + const mid = (lo + hi) >> 1; + const ok = await read(bytes, { limits: { maxTotalBytes: mid } }).then(() => true, () => false); + if (ok) hi = mid; + else lo = mid + 1; + } + await expect(read(bytes, { limits: { maxTotalBytes: lo - 1 } })).rejects.toThrow(); + const r = await inspect(bytes, { limits: { maxTotalBytes: lo } }); + expect(r.inflatedBytes).toBe(lo); + }); +}); diff --git a/packages/javascript-excel/test/read/inspect-files.ts b/packages/javascript-excel/test/read/inspect-files.ts index 4585e48..a5c7012 100644 --- a/packages/javascript-excel/test/read/inspect-files.ts +++ b/packages/javascript-excel/test/read/inspect-files.ts @@ -1,6 +1,7 @@ // Workbooks for the inspect() tests (JSE-71): a package with one part of every // kind the reader reads or reports, and hostile variants of it. Everything is // generated here; no third-party files. +import { crc32 } from "../../src/internal/zip/crc32"; import { writeZip, type ZipWriteEntry } from "../../src/internal/zip/write"; import { NS } from "./build"; @@ -462,3 +463,92 @@ function findText(bytes: Uint8Array, text: string): number { } throw new Error(`${text} not found`); } + +/** + * A zip written by hand: every part stored, except those given in `deflated` + * as raw DEFLATE data of their own making (so a test controls how the + * inflater splits them into chunks). + */ +export function rawZip(parts: Parts, deflated: Record = {}): Uint8Array { + const enc = new TextEncoder(); + const chunks: Uint8Array[] = []; + const central: Uint8Array[] = []; + let offset = 0; + for (const [name, value] of parts) { + const data = typeof value === "string" ? enc.encode(value) : value; + const body = deflated[name] ?? data; + const method = deflated[name] ? 8 : 0; + const nameBytes = enc.encode(name); + const crc = crc32(data); + const local = new Uint8Array(30 + nameBytes.length); + const lv = new DataView(local.buffer); + lv.setUint32(0, 0x04034b50, true); + lv.setUint16(4, 20, true); + lv.setUint16(8, method, true); + lv.setUint16(12, 0x21, true); + lv.setUint32(14, crc, true); + lv.setUint32(18, body.length, true); + lv.setUint32(22, data.length, true); + lv.setUint16(26, nameBytes.length, true); + local.set(nameBytes, 30); + const cd = new Uint8Array(46 + nameBytes.length); + const cv = new DataView(cd.buffer); + cv.setUint32(0, 0x02014b50, true); + cv.setUint16(4, 20, true); + cv.setUint16(6, 20, true); + cv.setUint16(10, method, true); + cv.setUint16(14, 0x21, true); + cv.setUint32(16, crc, true); + cv.setUint32(20, body.length, true); + cv.setUint32(24, data.length, true); + cv.setUint16(28, nameBytes.length, true); + cv.setUint32(42, offset, true); + cd.set(nameBytes, 46); + chunks.push(local, body); + central.push(cd); + offset += local.length + body.length; + } + const cdSize = central.reduce((n, c) => n + c.length, 0); + const eocd = new Uint8Array(22); + const ev = new DataView(eocd.buffer); + ev.setUint32(0, 0x06054b50, true); + ev.setUint16(8, parts.size, true); + ev.setUint16(10, parts.size, true); + ev.setUint32(12, cdSize, true); + ev.setUint32(16, offset, true); + const all = [...chunks, ...central, eocd]; + const out = new Uint8Array(all.reduce((n, c) => n + c.length, 0)); + let at = 0; + for (const c of all) { + out.set(c, at); + at += c.length; + } + return out; +} + +/** + * Raw DEFLATE of `data` as stored blocks: the first `first` bytes, then + * `empty` empty blocks, then the rest. An inflater hands the first bytes over + * as a chunk of their own. + */ +export function storedBlocks(data: Uint8Array, first: number, empty: number): Uint8Array { + const block = (bytes: Uint8Array, final: boolean): Uint8Array => { + const b = new Uint8Array(5 + bytes.length); + b[0] = final ? 1 : 0; + new DataView(b.buffer).setUint16(1, bytes.length, true); + new DataView(b.buffer).setUint16(3, ~bytes.length & 0xffff, true); + b.set(bytes, 5); + return b; + }; + const blocks: Uint8Array[] = [block(data.subarray(0, first), false)]; + for (let i = 0; i < empty; i++) blocks.push(block(new Uint8Array(0), false)); + for (let at = first; at < data.length; at += 65_535) blocks.push(block(data.subarray(at, Math.min(data.length, at + 65_535)), at + 65_535 >= data.length)); + if (first >= data.length) blocks.push(block(new Uint8Array(0), true)); + const out = new Uint8Array(blocks.reduce((n, b) => n + b.length, 0)); + let at = 0; + for (const b of blocks) { + out.set(b, at); + at += b.length; + } + return out; +} diff --git a/packages/javascript-excel/test/read/inspect.test.ts b/packages/javascript-excel/test/read/inspect.test.ts index 66430d1..a49aaca 100644 --- a/packages/javascript-excel/test/read/inspect.test.ts +++ b/packages/javascript-excel/test/read/inspect.test.ts @@ -307,12 +307,15 @@ describe("inspect: memory does not grow with the cells", () => { }); describe("inspect: shared-formula masters (review F1)", () => { - /** One sheet of `n` distinct shared-formula masters of about `len` characters, none of them shared by another cell. */ + /** One sheet of `n` distinct shared-formula masters of `len` characters (at least 6), none of them shared by another cell. */ function masters(n: number, len: number): Promise { const unit = "SUM(A1:B2)*C3+"; const body = unit.repeat(Math.ceil(len / unit.length)).slice(0, len); const rows: string[] = []; - for (let r = 1; r <= n; r++) rows.push(`${body}${r}1`); + for (let r = 1; r <= n; r++) { + const tail = `+${String(r).padStart(5, "0")}`; + rows.push(`${body.slice(0, Math.max(0, len - tail.length))}${tail}1`); + } const p = richParts({ rows: 1 }); p.set("xl/worksheets/sheet2.xml", `${rows.join("")}`); return zipParts(p); @@ -338,14 +341,47 @@ describe("inspect: shared-formula masters (review F1)", () => { it("120,000 masters of 600 characters (72 MB of formula text) cost inspect about what 120,000 short masters cost", async () => { const long = await masters(120_000, 600); - const short = await masters(120_000, 4); + const short = await masters(120_000, 6); const s = await peakOf(() => inspect(short)); const l = await peakOf(() => inspect(long)); - console.log(`inspect, 120,000 shared-formula masters: 4 characters ${(s / 1e6).toFixed(0)} MB, 600 characters ${(l / 1e6).toFixed(0)} MB (peak heap)`); + console.log(`inspect, 120,000 shared-formula masters: 6 characters ${(s / 1e6).toFixed(0)} MB, 600 characters ${(l / 1e6).toFixed(0)} MB (peak heap)`); // Holding the masters' text would add at least 72 MB. expect(l).toBeLessThan(s + 36e6); }, 120_000); + it("a small maxCellTextLength (the range of a copy's length straddles it) keeps no text: 60,000 masters of 998 characters at 1,000, and of 600 at 605", async () => { + for (const [len, limit] of [ + [998, 1000], + [600, 605], + ] as const) { + const file = await masters(60_000, len); + const base = await peakOf(() => inspect(file)); + const tight = await peakOf(() => inspect(file, { limits: { maxCellTextLength: limit } })); + console.log(`inspect, 60,000 masters of ${len} characters: default limits ${(base / 1e6).toFixed(0)} MB, maxCellTextLength ${limit}: ${(tight / 1e6).toFixed(0)} MB (peak heap)`); + // Holding the text would add about 60,000 x len bytes (36 to 60 MB). + expect(tight).toBeLessThan(base + 24e6); + } + }, 180_000); + + it("the reference records a straddling master keeps count against maxItems: past it, LIMIT_EXCEEDED with details.sharedFormulaReferences", async () => { + // 1,500 distinct relative references in a master (7,892 characters, under Excel's 8,192), 20 masters, each shared by a copy. + const master = Array.from({ length: 1500 }, (_, k) => `A${k + 1}`).join("+"); + const rows: string[] = []; + for (let m = 0; m < 20; m++) rows.push(`${master}`); + const p = richParts({ rows: 1 }); + p.set("xl/worksheets/sheet2.xml", `${rows.join("")}`); + const bytes = await zipParts(p); + // The range of a copy's length straddles this limit, so the records are kept. + const limits = { maxCellTextLength: master.length + 2000, maxItems: 10_000 }; + await expect(read(bytes, { limits })).resolves.toBeDefined(); + const err = await inspect(bytes, { limits }).then(() => undefined, (e: LimitError) => e); + expect(err).toBeInstanceOf(LimitError); + expect(err!.details).toMatchObject({ limit: "maxItems", max: 10_000, part: "xl/worksheets/sheet2.xml" }); + expect(err!.details?.["sharedFormulaReferences"]).toBeGreaterThan(0); + // Under the default maxItems the same file is accepted, as by read. + await expect(inspect(bytes, { limits: { maxCellTextLength: master.length + 2000 } })).resolves.toBeDefined(); + }); + it("whether a shared copy resolves (and so whether a value-less cell counts) is decided as read decides it, for every maxCellTextLength", async () => { // A master in C3 shared down and across; copies near the sheet's edges grow longer (XFD1048576 vs A1). const master = Array.from({ length: 40 }, (_, k) => `A${k + 1}`).join("+"); diff --git a/packages/javascript-excel/test/read/shift-formula.test.ts b/packages/javascript-excel/test/read/shift-formula.test.ts index c2f6f63..dabfb17 100644 --- a/packages/javascript-excel/test/read/shift-formula.test.ts +++ b/packages/javascript-excel/test/read/shift-formula.test.ts @@ -1,7 +1,7 @@ // JSE-62: the compiled shifter gives exactly what the 2.3.0 shifter gave, for // every formula and offset, while each copy costs its own length once. import { describe, expect, it } from "vitest"; -import { canShift, colLetters, colNumber, compileFormula, shiftCompiled, shiftFormula, shiftWork } from "../../src/internal/read/formula"; +import { canShift, colLetters, colNumber, compileFormula, lengthParts, shiftCompiled, shiftedLength, shiftedLengthRange, shiftFormula, shiftWork } from "../../src/internal/read/formula"; const MAX_ROW = 1_048_576; const MAX_COL = 16_384; @@ -212,3 +212,42 @@ describe("the compiled shifter equals the 2.3.0 shifter", () => { expect(MAX_ROW).toBe(1_048_576); }); }); + +describe("lengthParts / shiftedLength (JSE-71): a copy's exact length without its text", () => { + it("equals the length of the copy shiftCompiled builds, and lies in shiftedLengthRange, for 5,000 seeded formulas and offsets", () => { + let seed = 71; + const rnd = (n: number) => { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + return seed % n; + }; + const col = () => colLetters(1 + rnd(rnd(2) ? 30 : 16_384)); + const row = () => String(1 + rnd(rnd(2) ? 12 : 1_048_576)); + const anchor = () => (rnd(3) === 0 ? "$" : ""); + const ref = () => { + switch (rnd(4)) { + case 0: + return `${anchor()}${col()}:${anchor()}${col()}`; + case 1: + return `${anchor()}${row()}:${anchor()}${row()}`; + default: + return `${anchor()}${col()}${anchor()}${row()}`; + } + }; + let checked = 0; + for (let k = 0; k < 5_000; k++) { + const formula = Array.from({ length: 1 + rnd(6) }, () => (rnd(4) ? ref() : `"t${rnd(9)}"`)).join(rnd(2) ? "+" : ","); + const c = compileFormula(formula); + const dRow = rnd(2) ? rnd(40) - 20 : rnd(2_000_000) - 1_000_000; + const dCol = rnd(2) ? rnd(40) - 20 : rnd(30_000) - 15_000; + if (!canShift(c, dRow, dCol)) continue; + const text = shiftCompiled(c, dRow, dCol) as string; + const { fixed, parts } = lengthParts(c); + expect(shiftedLength(fixed, parts, dRow, dCol), `${formula} by ${dRow},${dCol}`).toBe(text.length); + const [min, max] = shiftedLengthRange(c); + expect(text.length).toBeGreaterThanOrEqual(min); + expect(text.length).toBeLessThanOrEqual(max); + checked++; + } + expect(checked).toBeGreaterThan(1_000); + }); +}); From 9d11dc72afb71c9f3e238d229d7f77a318c672c0 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 13:17:11 +0100 Subject: [PATCH 10/22] JSE-71 review 2: encoding from the whole declaration; reference records instead of formula text The encoding of a part read parses comes from the tokenizer's declaration token and its first four bytes gathered across chunks; an unparsed XML part has its declaration gathered across chunks up to ?>, bounded by maxXmlTokenLength. details.encoding is at most 40 printable characters. Relationship parts read parsed are reused, not inflated again. A lean master whose copies' length range straddles maxCellTextLength keeps one record per distinct relative row or column (exact copy length without the text), counted against maxItems with the read's other items; past it, LIMIT_EXCEEDED with details.sharedFormulaReferences. read is unchanged. --- .../src/internal/read/context.ts | 31 +++- .../src/internal/read/formula.ts | 62 +++++++ .../src/internal/read/inspect.ts | 172 ++++++++++++++---- .../javascript-excel/src/internal/read/opc.ts | 1 + .../src/internal/read/reader.ts | 12 +- .../src/internal/read/sheet.ts | 34 +++- .../src/internal/read/xml-reader.ts | 7 + 7 files changed, 267 insertions(+), 52 deletions(-) diff --git a/packages/javascript-excel/src/internal/read/context.ts b/packages/javascript-excel/src/internal/read/context.ts index ceedfc9..ab3efe3 100644 --- a/packages/javascript-excel/src/internal/read/context.ts +++ b/packages/javascript-excel/src/internal/read/context.ts @@ -63,8 +63,15 @@ export class ReadContext { private readonly onProgress: ((p: ProgressInfo) => void) | undefined; /** Sees every warning before the cap applies (inspect collects UNSUPPORTED_PART with it, JSE-71). */ tap: ((w: ExcelWarning) => void) | undefined; - /** Sees the first inflated bytes of every part parsed as XML (inspect checks their encoding, JSE-71). */ + /** + * inspect (JSE-71): sees the first four inflated bytes of every part parsed + * as XML (fewer only when the part is shorter), however the inflater splits + * them, and its XML declaration, whole, from the tokenizer. + */ sniff: ((part: string, first: Uint8Array) => void) | undefined; + declared: ((part: string, declaration: string) => void) | undefined; + /** inspect (JSE-71): sees every relationship part the package parses, with its relationships. */ + relsParsed: ((part: string, rels: ReadonlyArray<{ kind: string; target: string; external: boolean }>) => void) | undefined; /** Returns to the event loop about every 16 ms between chunks, so a big read does not freeze the page (JSE-24). */ private readonly pause = createYielder(); @@ -150,13 +157,21 @@ export class ReadContext { */ async parse(entry: ZipEntryInfo, handler: XmlHandler, onChunk?: (bytes: number) => void): Promise { this.consumed.add(entry.name); - const tok = new XmlTokenizer(handler, this.limits.maxXmlDepth, this.limits.maxXmlTokenLength); + const declared = this.declared; + const tok = new XmlTokenizer(handler, this.limits.maxXmlDepth, this.limits.maxXmlTokenLength, declared && ((pi) => declared(entry.name, pi))); let decoder: TextDecoderLike | undefined; + let head: Uint8Array | undefined = this.sniff ? new Uint8Array(0) : undefined; try { for await (const chunk of this.zip.stream(entry, this.signal)) { + if (head) { + head = joinHead(head, chunk, 4); + if (head.length >= 4) { + this.sniff!(entry.name, head); + head = undefined; + } + } let bytes = chunk; if (!decoder) { - this.sniff?.(entry.name, chunk); decoder = newDecoder(chunk); bytes = stripBom(chunk); } @@ -184,6 +199,7 @@ export class ReadContext { this.checkAbort(); } } + if (head) this.sniff!(entry.name, head); if (decoder) tok.feed(decoder.decode()); tok.end(); } catch (err) { @@ -192,6 +208,15 @@ export class ReadContext { } } +/** `head` with the start of `chunk` appended, up to `n` bytes in all. */ +export function joinHead(head: Uint8Array, chunk: Uint8Array, n: number): Uint8Array { + if (head.length >= n) return head; + const out = new Uint8Array(Math.min(n, head.length + chunk.length)); + out.set(head); + out.set(chunk.subarray(0, out.length - head.length), head.length); + return out; +} + export function withPart(err: unknown, part: string): unknown { if (err instanceof FormatError && (err.code === "XML_MALFORMED" || err.code === "XML_DTD_FORBIDDEN") && !err.details?.["part"]) { return new FormatError(err.code, `${excerpt(part)}: ${err.message}`, { details: { ...err.details, part }, cause: err }); diff --git a/packages/javascript-excel/src/internal/read/formula.ts b/packages/javascript-excel/src/internal/read/formula.ts index 8daf6ba..ccfbc9b 100644 --- a/packages/javascript-excel/src/internal/read/formula.ts +++ b/packages/javascript-excel/src/internal/read/formula.ts @@ -299,6 +299,68 @@ export function shiftedLengthRange(c: CompiledFormula): [number, number] { return [min, max]; } +/** + * What the exact length of every shifted copy of `c` depends on, without its + * text (JSE-71): the characters that never change (`fixed`: the literal text, + * `$` anchors, `:` and anchored parts) and, for each distinct relative part, + * whether it is a row, its value and how many times the copy holds it, as + * triples in `parts`. `shiftedLength` gives the same length as + * `shiftCompiled`, for any offset `canShift` allows. + */ +export function lengthParts(c: CompiledFormula): { fixed: number; parts: Int32Array } { + let fixed = c.literalLength; + const counts = new Map(); // (value << 1 | isRow) -> count + const part = (anchor: string, v: number, isRow: boolean): void => { + if (anchor === "$") fixed += 1 + (isRow ? String(v).length : letters(v).length); + else { + const key = v * 2 + (isRow ? 1 : 0); + counts.set(key, (counts.get(key) ?? 0) + 1); + } + }; + for (const u of c.slots) { + const r = c.uniq[u]!; + if (r.kind === COLS_REF) { + part(r.aAnchor, r.a, false); + part(r.bAnchor, r.b, false); + fixed += 1; + } else if (r.kind === ROWS_REF) { + part(r.aAnchor, r.a, true); + part(r.bAnchor, r.b, true); + fixed += 1; + } else { + part(r.aAnchor, r.a, false); + part(r.bAnchor, r.b, true); + } + } + const parts = new Int32Array(counts.size * 3); + let i = 0; + for (const [key, n] of counts) { + parts[i++] = key & 1; + parts[i++] = Math.floor(key / 2); + parts[i++] = n; + } + return { fixed, parts }; +} + +/** The length of a copy shifted by (dRow, dCol), from `lengthParts`; the offset must pass `canShift`. */ +export function shiftedLength(fixed: number, parts: Int32Array, dRow: number, dCol: number): number { + let n = fixed; + for (let i = 0; i < parts.length; i += 3) { + const v = parts[i + 1]! + (parts[i] ? dRow : dCol); + n += parts[i + 2]! * (parts[i] ? digitCount(v) : v <= 26 ? 1 : v <= 702 ? 2 : 3); + } + return n; +} + +function digitCount(v: number): number { + let d = 1; + while (v >= 10) { + v = Math.floor(v / 10); + d++; + } + return d; +} + /** `formula` shifted by (dRow, dCol), or undefined when a reference would leave the sheet. */ export function shiftFormula(formula: string, dRow: number, dCol: number): string | undefined { if (dRow === 0 && dCol === 0) return formula; diff --git a/packages/javascript-excel/src/internal/read/inspect.ts b/packages/javascript-excel/src/internal/read/inspect.ts index ae7125b..9c07ee9 100644 --- a/packages/javascript-excel/src/internal/read/inspect.ts +++ b/packages/javascript-excel/src/internal/read/inspect.ts @@ -16,7 +16,7 @@ * bytes searched for `]*?\bencoding\s*=\s*(["'])([^"']*)\1/.exec(text); - if (decl && !/^utf-?(8|16(le|be)?)$/i.test(decl[2]!.trim())) return decl[2]!.trim(); + if (b0 === 0x2b && b1 === 0x41 && b2 === 0x44 && (b3 === 0x77 || b3 === 0x78)) return "UTF-7"; return undefined; } +/** The encoding a whole XML declaration names when it is not UTF-8 or UTF-16, cleaned for `details`; else undefined. */ +export function declaredEncoding(declaration: string): string | undefined { + const m = /\bencoding\s*=\s*(["'])([^"']*)\1/.exec(declaration); + if (!m) return undefined; + const name = m[2]!.trim(); + return /^utf-?(8|16(le|be)?)$/i.test(name) ? undefined : printable(name); +} + +/** File text for `details`: printable ASCII only, at most 40 characters. */ +function printable(s: string): string { + const clean = s.replace(/[^\x20-\x7e]/g, "?"); + return clean.length > 40 ? `${clean.slice(0, 37)}...` : clean; +} + function encodingError(part: string, encoding: string): FormatError { - return new FormatError("XML_MALFORMED", `${excerpt(part)}: the part is encoded in ${excerpt(encoding)}; XML parts must be UTF-8 or UTF-16.`, { + return new FormatError("XML_MALFORMED", `${excerpt(part)}: the part is encoded in ${encoding}; XML parts must be UTF-8 or UTF-16.`, { details: { part, encoding }, }); } @@ -101,23 +109,30 @@ function doctype(): FormatError { } export async function inspectImpl(bytes: Uint8Array, options?: InspectOptions): Promise { + // Parts read parses: their encoding is refused only once the read has succeeded, so read's own errors come first. let badEncoding: { part: string; encoding: string } | undefined; + const note = (part: string, encoding: string | undefined): void => { + if (encoding !== undefined && !badEncoding) badEncoding = { part, encoding }; + }; + const xmlTargets = new Set(); + const relsDone = new Set(); const sink: InspectSink = { unsupported: [], broken: new Set(), sharedStrings: 0, sheets: [], - // Parts read parses: their encoding is refused only once the read has succeeded, so read's own errors come first. - sniff: (part, first) => { - if (badEncoding) return; - const encoding = forbiddenEncoding(first); - if (encoding !== undefined) badEncoding = { part, encoding }; + sniff: (part, first) => note(part, signatureEncoding(first)), + declared: (part, declaration) => note(part, declaredEncoding(declaration)), + // Relationship parts read parses are used as they are, not parsed (and counted toward maxTotalBytes) again. + relsParsed: (part, rels) => { + relsDone.add(part); + for (const r of rels) if (!r.external && !BINARY_KINDS.has(r.kind)) xmlTargets.add(r.target.toLowerCase()); }, }; const { workbook } = await readImpl(bytes, { limits: options?.limits, signal: options?.signal }, { inspect: sink }); const ctx = sink.ctx!; const pkg = sink.pkg!; - const xmlTargets = await relationshipTargets(ctx, pkg, sink); + await relationshipTargets(ctx, pkg, sink, relsDone); if (badEncoding) throw encodingError(badEncoding.part, badEncoding.encoding); for (const entry of ctx.zip.entries) { if (ctx.consumed.has(entry.name) && !sink.broken.has(entry.name)) continue; @@ -153,16 +168,15 @@ export async function inspectImpl(bytes: Uint8Array, options?: InspectOptions): * does not need and that is not well-formed is left to the byte search (as a * broken part), not refused, as read would not refuse it. */ -async function relationshipTargets(ctx: ReadContext, pkg: Package, sink: InspectSink): Promise> { - const out = new Set(); +async function relationshipTargets(ctx: ReadContext, pkg: Package, sink: InspectSink, done: ReadonlySet): Promise { for (const name of pkg.partNames) { const m = /^(.*?)_rels\/([^/]+)\.rels$/i.exec(name); - if (!m) continue; + if (!m || done.has(name)) continue; const pause = ctx.step(); if (pause) await pause; - let rels; try { - rels = await pkg.rels(`${m[1]}${m[2]}`); + // Its relationships reach the targets through sink.relsParsed. + await pkg.rels(`${m[1]}${m[2]}`); } catch (err) { if (err instanceof FormatError && err.code === "XML_MALFORMED") { sink.broken.add(name); @@ -170,9 +184,7 @@ async function relationshipTargets(ctx: ReadContext, pkg: Package, sink: Inspect } throw err; } - for (const r of rels) if (!r.external && !BINARY_KINDS.has(r.kind)) out.add(r.target.toLowerCase()); } - return out; } /** @@ -184,19 +196,12 @@ async function relationshipTargets(ctx: ReadContext, pkg: Package, sink: Inspect */ async function scanPart(ctx: ReadContext, entry: ZipEntryInfo, xml: boolean): Promise { let tail = ""; - let head: Uint8Array | undefined = xml ? new Uint8Array(0) : undefined; + const decl = xml ? new DeclarationReader(ctx.limits.maxXmlTokenLength) : undefined; try { for await (const chunk of ctx.zip.stream(entry, ctx.signal)) { - if (head) { - // The encoding is decided on the first bytes, before they are searched. - const more = new Uint8Array(Math.min(HEAD, head.length + chunk.length)); - more.set(head); - more.set(chunk.subarray(0, more.length - head.length), head.length); - head = more; - const encoding = forbiddenEncoding(head); - if (encoding !== undefined) throw encodingError(entry.name, encoding); - if (head.length >= HEAD) head = undefined; - } + // The encoding is decided on the first bytes and the whole declaration, before they are searched. + const encoding = decl?.feed(chunk); + if (encoding !== undefined) throw encodingError(entry.name, encoding); for (let at = 0; at < chunk.length; ) { const piece = chunk.subarray(at, at + PARSE_SLICE); at += piece.length; @@ -211,7 +216,98 @@ async function scanPart(ctx: ReadContext, entry: ZipEntryInfo, xml: boolean): Pr const pause = ctx.step(); if (pause) await pause; } + const encoding = decl?.end(); + if (encoding !== undefined) throw encodingError(entry.name, encoding); } catch (err) { throw withPart(err, entry.name); } } + +/** + * Reads the start of a part that read does not parse, however it is chunked: + * its first four bytes (signatureEncoding), then, decoded as UTF-8 or UTF-16 + * by its byte order mark as read decodes, its XML declaration up to `?>`, + * bounded like any token by maxXmlTokenLength. `feed` and `end` return a + * forbidden encoding once one is known. Linear: each chunk is decoded and + * searched once. + */ +class DeclarationReader { + private pending: Uint8Array[] = []; + private pendingLength = 0; + private decoder: ReturnType | undefined; + private text = ""; + private searched = 0; + private done = false; + + constructor(private readonly maxToken: number) {} + + feed(chunk: Uint8Array): string | undefined { + if (this.done) return undefined; + if (!this.decoder) { + this.pending.push(chunk); + this.pendingLength += chunk.length; + if (this.pendingLength < 4) return undefined; + return this.start(); + } + return this.more(this.decoder.decode(chunk, { stream: true })); + } + + end(): string | undefined { + if (this.done) return undefined; + if (!this.decoder) { + const found = this.start(); + if (found !== undefined || this.done) return found; + } + return this.more(this.decoder!.decode(), true); + } + + private start(): string | undefined { + const head = new Uint8Array(this.pendingLength); + let at = 0; + for (const p of this.pending) { + head.set(p, at); + at += p.length; + } + this.pending = []; + const sig = signatureEncoding(head); + if (sig !== undefined) { + this.done = true; + return sig; + } + this.decoder = newDecoder(head); + return this.more(this.decoder.decode(head, { stream: true })); + } + + private more(text: string, final = false): string | undefined { + this.text += text; + const t = this.text; + // Before the declaration: a byte order mark (dropped by the decoder) and nothing else; leading space is let through. + const lead = t.length - t.trimStart().length; + const rest = t.slice(lead, lead + 6); + // Too short to tell yet: what has come is the start of "", Math.max(lead, this.searched - 1)); + if (close === -1) { + this.searched = t.length; + if (final) this.done = true; + return final ? undefined : this.bound(); + } + this.done = true; + if (close + 2 - lead > this.maxToken) this.bound(true); + return declaredEncoding(t.slice(lead, close + 2)); + } + + /** A declaration (with the space before it) longer than maxXmlTokenLength is refused, as the tokenizer refuses a token. */ + private bound(over = false): undefined { + if (over || this.text.length > this.maxToken) { + throw new LimitError("LIMIT_EXCEEDED", `An XML tag, comment, CDATA section or processing instruction is longer than maxXmlTokenLength (${this.maxToken}).`, { + details: { limit: "maxXmlTokenLength", value: this.maxToken + 1, max: this.maxToken }, + }); + } + return undefined; + } +} diff --git a/packages/javascript-excel/src/internal/read/opc.ts b/packages/javascript-excel/src/internal/read/opc.ts index 50c5853..c7a90c2 100644 --- a/packages/javascript-excel/src/internal/read/opc.ts +++ b/packages/javascript-excel/src/internal/read/opc.ts @@ -109,6 +109,7 @@ export class Package { close: () => {}, text: () => {}, }); + this.ctx.relsParsed?.(entry.name, out); return out; } } diff --git a/packages/javascript-excel/src/internal/read/reader.ts b/packages/javascript-excel/src/internal/read/reader.ts index 3dfb4df..36a90a5 100644 --- a/packages/javascript-excel/src/internal/read/reader.ts +++ b/packages/javascript-excel/src/internal/read/reader.ts @@ -240,8 +240,10 @@ export interface InspectSink { unsupported: ExcelWarning[]; /** Parts whose XML was malformed and skipped (BROKEN_OPTIONAL_PART): not read to their end. */ broken: Set; - /** Given the first inflated bytes of every part the read parses as XML, from the first part on. */ - sniff: (part: string, first: Uint8Array) => void; + /** From the first part on (ReadContext): the first bytes and the declaration of every part parsed as XML, and every relationship part parsed. */ + sniff: NonNullable; + declared: NonNullable; + relsParsed: NonNullable; /** Items in the shared strings table. */ sharedStrings: number; /** Per listed worksheet, in order: its part and the cells it has. */ @@ -268,7 +270,11 @@ export async function readImpl(input: BinaryInput, options?: ReadOptions, intern let ctx!: ReadContext; const { pkg, workbookPart, format } = await openPackage(bytes, limits, (zip) => { ctx = new ReadContext(zip, limits, o.signal, o.onWarning, o.onProgress); - if (internal?.inspect) ctx.sniff = internal.inspect.sniff; + if (internal?.inspect) { + ctx.sniff = internal.inspect.sniff; + ctx.declared = internal.inspect.declared; + ctx.relsParsed = internal.inspect.relsParsed; + } return ctx; }); ctx.progress({ phase: "unzip", ratio: 0.02 }); diff --git a/packages/javascript-excel/src/internal/read/sheet.ts b/packages/javascript-excel/src/internal/read/sheet.ts index 6bbfd56..232214f 100644 --- a/packages/javascript-excel/src/internal/read/sheet.ts +++ b/packages/javascript-excel/src/internal/read/sheet.ts @@ -8,7 +8,7 @@ import type { Cell, CellValue, ColumnProps, Hyperlink, PrintSetup, RichText, RowProps, Sheet, SheetView } from "../../model"; import { LimitError } from "../../errors"; import type { ReadContext } from "./context"; -import { canShift, colLetters, colNumber, compileFormula, MAX_SHARED_FORMULA_LENGTH, shiftCompiled, shiftedLengthRange, type CompiledFormula } from "./formula"; +import { canShift, colLetters, colNumber, compileFormula, lengthParts, MAX_SHARED_FORMULA_LENGTH, shiftCompiled, shiftedLength, shiftedLengthRange, type CompiledFormula } from "./formula"; import { isDateFormat } from "../../numfmt"; import type { Relationship } from "./opc"; import { serialToDate } from "../../dates"; @@ -121,9 +121,11 @@ interface SharedMaster { /** * Lean masters only (keepCells false, JSE-71): whether every shifted copy * fits maxCellTextLength. Undefined for a kept master, and for a lean one - * whose copies may or may not fit (it keeps its text, as read does). + * whose copies may or may not fit: that one has `lengths` instead. */ fits: boolean | undefined; + /** A lean master whose copies may or may not fit: what each copy's exact length depends on (formula.ts lengthParts). */ + lengths?: { fixed: number; parts: Int32Array } | undefined; } interface RawHyperlink { @@ -244,6 +246,8 @@ export class SheetParser implements XmlHandler { private readonly keep: boolean; /** Cells kept (or, without keepCells, that would have been), as maxCells counts them. */ cellCount = 0; + /** Without keepCells: reference records kept for shared formulas on this sheet (leanMaster). */ + private lengthRecords = 0; /** Without keepCells: the rows that had properties, one bit per row (for counting each once, as `rowProps` does). */ private rowPropSeen: Uint8Array | undefined; @@ -870,9 +874,10 @@ export class SheetParser implements XmlHandler { // Each shifted copy is cell text: one longer than maxCellTextLength is not built, and the // cell keeps its cached value, as for an over-long master (the read goes on, as in 2.3.0). const max = this.ctx.limits.maxCellTextLength; - if (master.fits !== undefined) { - // A lean master (keepCells false): the length range already decided it for every offset. - if (master.fits) return { text: "" }; + if (master.fits !== undefined || master.lengths) { + // A lean master (keepCells false): decided by the length range, or per copy from its reference records. + const fits = master.lengths ? shiftedLength(master.lengths.fixed, master.lengths.parts, dRow, dCol) <= max : master.fits; + if (fits) return { text: "" }; this.unresolved(p, `: shifted, it would have more than maxCellTextLength (${max}) characters`); return undefined; } @@ -893,8 +898,11 @@ export class SheetParser implements XmlHandler { * keepCells false (JSE-71): a master without its text, so that a sheet of * many long masters does not hold them all. Kept: the length, the position * and the relative bounds (canShift); and whether a copy fits - * maxCellTextLength, from the range of lengths a copy can have. Only when - * the limit falls inside that range is the text kept, to decide per copy. + * maxCellTextLength, from the range of lengths a copy can have. When the + * limit falls inside that range, the records each copy's exact length + * depends on (one per distinct relative row or column) are kept instead, + * counted against maxItems together with what the read built besides cells + * (sharedFormulaReferences): so no formula text is held under any limit. */ private leanMaster(p: PendingCell): SharedMaster { const f = p.f!; @@ -905,8 +913,18 @@ export class SheetParser implements XmlHandler { const full = compileFormula(f); const [min, max] = shiftedLengthRange(full); const limit = this.ctx.limits.maxCellTextLength; - if (min <= limit && max > limit) return { ...base, formula: f, compiled: full, fits: undefined }; const bounds: CompiledFormula = { source: "", segs: NONE, slots: NO_SLOTS, uniq: NO_REFS, literalLength: 0, rowMin: full.rowMin, rowMax: full.rowMax, colMin: full.colMin, colMax: full.colMax }; + if (min <= limit && max > limit) { + const lengths = lengthParts(full); + this.lengthRecords += lengths.parts.length / 3; + const most = this.ctx.limits.maxItems; + if (this.ctx.items + this.lengthRecords > most) { + throw new LimitError("LIMIT_EXCEEDED", `Sheet "${excerpt(this.sheet.name)}": the shared formulas need more than maxItems (${most}) reference records, with the items the read built besides cells, to check their copies' length against maxCellTextLength.`, { + details: { limit: "maxItems", value: most + 1, max: most, part: this.part, ref: p.ref, sharedFormulaReferences: this.lengthRecords }, + }); + } + return { ...base, formula: "", compiled: bounds, fits: undefined, lengths }; + } return { ...base, formula: "", compiled: bounds, fits: max <= limit }; } diff --git a/packages/javascript-excel/src/internal/read/xml-reader.ts b/packages/javascript-excel/src/internal/read/xml-reader.ts index 983102f..a06f894 100644 --- a/packages/javascript-excel/src/internal/read/xml-reader.ts +++ b/packages/javascript-excel/src/internal/read/xml-reader.ts @@ -149,6 +149,12 @@ export class XmlTokenizer implements XmlControl { private readonly handler: XmlHandler, private readonly maxDepth: number, private readonly maxToken: number = DEFAULT_LIMITS.maxXmlTokenLength, + /** + * Given each processing instruction before the root element whose target + * is `xml` in any case (the XML declaration, and ` void, ) { handler.attach?.(this); } @@ -306,6 +312,7 @@ export class XmlTokenizer implements XmlControl { const e = buf.indexOf("?>", i + 2); if (e === -1) return this.unfinished(buf, i, final, "Unterminated processing instruction.", Wait.Delim, "?>", i + 2); this.checkToken(e + 2 - i); + if (this.onDeclaration && !this.rootSeen && /^<\?xml(?![^\s?])/i.test(buf.slice(i, i + 6))) this.onDeclaration(buf.slice(i, e + 2)); i = e + 2; continue; } From 828b85533e5b35eb2d41a1b6313fab2e4b10d8c9 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 13:17:11 +0100 Subject: [PATCH 11/22] JSE-71 review 2: document how the encoding is decided, what the guarantee rests on, and the reference-record budget --- .changeset/inspect.md | 2 +- docs/api.md | 12 ++++++------ packages/javascript-excel/README.md | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.changeset/inspect.md b/.changeset/inspect.md index 799473b..f8c7b6e 100644 --- a/.changeset/inspect.md +++ b/.changeset/inspect.md @@ -2,4 +2,4 @@ "javascript-excel": minor --- -New `inspect(input, { limits, signal })` in `javascript-excel/read` checks an `.xlsx`, `.xlsm`, `.xltx` or `.xltm` file part by part without building its cells, for servers and browsers that must accept or refuse an upload without reading it into the model. Under the same limits it refuses every file `read` refuses, with the same error class, code and details (zip and reader limits, encryption, CFB and other formats, `NOT_XLSX`, `XML_DTD_FORBIDDEN`, malformed XML in the parts `read` parses, every sheet to its last row), and it returns `read`'s `UNSUPPORTED_PART` warnings with their `partKinds` (VBA, macro sheets, external links, connections, OLE objects, query tables, …), the format, the worksheets with their cell counts (as `maxCells` counts them) and used ranges, and the counts of parts, inflated bytes, cells and shared strings. It also inflates every part `read` never opens (zip limits and CRC-32 apply) and searches its bytes for ``, which may not be longer than `maxXmlTokenLength` (with any space before it), or it is refused with `LIMIT_EXCEEDED` (`maxXmlTokenLength`) as a token would be. A part that begins with a UTF-32 or UCS-4 byte order mark or `<` pattern, the UTF-7 signature (`+/v`) or `+ADw` (an encoded `<`), or the EBCDIC form of `` in another letter case is checked the same way; XML parsers reject it, since `xml` in any case is a reserved target. This is what the guarantee against other encodings rests on: an XML parser decodes a part as UTF-7, UTF-32, EBCDIC or a code page only because of its byte order mark, its first bytes or its declaration, and those are what is refused. No new error code: such a part is not well-formed package XML, and `read` decodes every part as UTF-8 or UTF-16. These refusals come only after the read has succeeded, so `read`'s own errors come first. - Parts `read` does not parse are not checked for well-formedness, because Excel's own VML is not well-formed XML. Nested archives and compressed streams inside binary parts are never opened, so a declaration inside them is not seen; nor is one in an EBCDIC (or other non-ASCII-compatible, non-UTF) encoding in a part that is not an XML part. **False positives.** The search does not parse, so it also refuses, though no XML parser would read a DTD from them: a `` (as some editors export them); and any binary part (image, VBA project, OLE object or embedded file stored without compression, printer settings) whose bytes happen to contain the letters ` w.code) | **External references** | External links, OLE objects, DDE and data connections are not read or followed. The reader resolves relationships only within the package. | | **ReDoS** | Hot paths (A1 parsing, number detection, CSV) use hand-written scanners or linear regexes with no nested quantifiers. Format codes are bounded by part size. | | **Encrypted, legacy and macro content** | CFB containers (`.xls`, encrypted OOXML) throw `UNSUPPORTED_FORMAT`; VBA parts are dropped, never executed. | -| **Checking an upload without reading it** | `inspect` (§5.2.1) refuses every file `read` refuses under the same limits, with the same error, and returns the part kinds `read` reports (VBA, macro sheets, external links, connections, OLE objects, …), without building cells. It also inflates every part `read` leaves unopened, searches the bytes of each for ` w.code) - `maxIssues` around 1,000 for `importDataset`; - `formulas: false` on `read` when the formula text is not needed: cells that share a formula then cost no more than other cells (`importDataset` already reads them so); - `maxEntryBytes` 64 MiB and `maxTotalBytes` 128 MiB; -- to accept or refuse an upload without reading it into the model, `inspect` with the same limits (§5.2.1), including `maxItems`, which bounds the styles and defined names it holds; +- to accept or refuse an upload without reading it into the model, `inspect` with the same limits (§5.2.1), including `maxItems`, which bounds the styles and defined names it holds and the shared-formula reference records it keeps when `maxCellTextLength` is small; - run imports of untrusted files in a worker thread with a memory limit (`resourceLimits` in Node) and a wall-clock timeout that terminates it. An `AbortSignal` is consulted between steps, but it cannot interrupt a synchronous step such as the conversion of a read sheet into a dataset. Writer-side hygiene: all text and attributes are XML-escaped, and invalid XML characters are encoded (§3.4). A string that starts with `=` is text, never a formula. Sheet names and defined names are validated, and sheet names are quoted correctly in generated references (`'It''s'!A1`). diff --git a/packages/javascript-excel/README.md b/packages/javascript-excel/README.md index b0429cc..b8fa12e 100644 --- a/packages/javascript-excel/README.md +++ b/packages/javascript-excel/README.md @@ -93,7 +93,7 @@ console.log(cell?.type, cell?.value, cell?.rawText); // "number" 50.3 "50.30" Damage the reader can recover from comes back as `warnings`. `isDataLossWarning(w)` tells the ones where data was lost (a cell skipped, rows cut, a part missing, comments or charts not read; `partKind` names the part) from informational ones; the warning cap (`limits.maxWarnings`, default 1,000) drops only informational warnings, so filtering `warnings` with it is enough to refuse a damaged file. -To accept or refuse an upload without reading it into the model, `inspect(file, { limits, signal })` checks it part by part without building cells: it refuses every file `read` refuses under the same limits, with the same error, and returns the format, the worksheets with their cell counts, and the part kinds `read` reports (`partKinds`: VBA, external links, OLE objects, …). It also inflates the parts `read` never opens, searches the bytes of every one of them for ` Date: Wed, 2 Dec 2026 13:22:57 +0100 Subject: [PATCH 12/22] JSE-71: inspect uses the package scan's relationships; differential covers JSE-72's kinds read now parses every relationships part once (scanPackageParts): inspect takes the XML targets from those relationships (canonical part keys, alternative readings included) instead of parsing .rels parts itself, and does not inflate them again. The differential test asserts that read and inspect report the same warnings for activeX, embeddedPackage, customUI, webExtension, unreferencedPart (with parts), invalidPartName, Excel's xlMacrosheet and a VBA signature, and that equivalent part names fail with the same ZIP_INVALID. --- .../src/internal/read/inspect.ts | 70 ++++++----------- .../test/read/inspect-differential.test.ts | 28 ++++++- .../test/read/inspect-files.ts | 76 +++++++++++++++++++ 3 files changed, 128 insertions(+), 46 deletions(-) diff --git a/packages/javascript-excel/src/internal/read/inspect.ts b/packages/javascript-excel/src/internal/read/inspect.ts index 9c07ee9..3bc9cf3 100644 --- a/packages/javascript-excel/src/internal/read/inspect.ts +++ b/packages/javascript-excel/src/internal/read/inspect.ts @@ -9,8 +9,9 @@ * whatever readImpl learns to check or report, inspect does too. Only once * that read has succeeded come the checks read does not make: * - every XML part (by content type, by name, or as the target of a - * relationship of a kind that is not binary), including the parts read - * parses, must be in UTF-8 or UTF-16, as OPC requires; + * relationship of a kind that is not binary, from the relationships read's + * package scan parsed), including the parts read parses, must be in UTF-8 + * or UTF-16, as OPC requires; * - every zip entry the read did not parse, or parsed only up to an error it * forgave (a broken optional part), is inflated (zip limits, CRC) and its * bytes searched for ` = new Set([ "image", - "oleObject", + "oleobject", "package", - "vbaProject", - "vbaProjectSignature", - "vbaProjectSignatureAgile", - "vbaProjectSignatureV3", - "printerSettings", - "activeXControlBinary", + "vbaproject", + "vbaprojectsignature", + "vbaprojectsignatureagile", + "vbaprojectsignaturev3", + "attachedtoolbars", + "printersettings", + "activexcontrolbinary", "thumbnail", "font", "media", "audio", "video", "hyperlink", - "attachedTemplate", - "externalLinkPath", - "xlBinaryIndex", + "attachedtemplate", + "externallinkpath", + "xlbinaryindex", ]); /** Parts whose content type or name says XML. */ @@ -123,22 +125,26 @@ export async function inspectImpl(bytes: Uint8Array, options?: InspectOptions): sheets: [], sniff: (part, first) => note(part, signatureEncoding(first)), declared: (part, declaration) => note(part, declaredEncoding(declaration)), - // Relationship parts read parses are used as they are, not parsed (and counted toward maxTotalBytes) again. + // read parses every relationships part once (the package scan, scan.ts): their relationships are used as they are, + // and the parts are not inflated (and counted toward maxTotalBytes) again. relsParsed: (part, rels) => { relsDone.add(part); - for (const r of rels) if (!r.external && !BINARY_KINDS.has(r.kind)) xmlTargets.add(r.target.toLowerCase()); + for (const r of rels) { + if (r.external || r.tooLong || r.target === "" || BINARY_KINDS.has(r.kind.toLowerCase())) continue; + xmlTargets.add(partKey(r.target)); + if (r.altTarget !== undefined) xmlTargets.add(partKey(r.altTarget)); + } }, }; const { workbook } = await readImpl(bytes, { limits: options?.limits, signal: options?.signal }, { inspect: sink }); const ctx = sink.ctx!; const pkg = sink.pkg!; - await relationshipTargets(ctx, pkg, sink, relsDone); if (badEncoding) throw encodingError(badEncoding.part, badEncoding.encoding); for (const entry of ctx.zip.entries) { - if (ctx.consumed.has(entry.name) && !sink.broken.has(entry.name)) continue; + if ((ctx.consumed.has(entry.name) || relsDone.has(entry.name)) && !sink.broken.has(entry.name)) continue; const pause = ctx.step(); if (pause) await pause; - await scanPart(ctx, entry, isXmlByName(pkg, entry.name) || xmlTargets.has(entry.name.toLowerCase())); + await scanPart(ctx, entry, isXmlByName(pkg, entry.name) || xmlTargets.has(pkg.keyOf(entry))); } const kinds = new Set(); for (const w of sink.unsupported) if (w.partKind !== undefined) kinds.add(w.partKind); @@ -161,32 +167,6 @@ export async function inspectImpl(bytes: Uint8Array, options?: InspectOptions): }; } -/** - * The parts (lower case) that some relationship of the package targets with - * a kind that is not binary: XML parts, whatever their names. Every - * relationship part is parsed, as read parses the ones it needs; one read - * does not need and that is not well-formed is left to the byte search (as a - * broken part), not refused, as read would not refuse it. - */ -async function relationshipTargets(ctx: ReadContext, pkg: Package, sink: InspectSink, done: ReadonlySet): Promise { - for (const name of pkg.partNames) { - const m = /^(.*?)_rels\/([^/]+)\.rels$/i.exec(name); - if (!m || done.has(name)) continue; - const pause = ctx.step(); - if (pause) await pause; - try { - // Its relationships reach the targets through sink.relsParsed. - await pkg.rels(`${m[1]}${m[2]}`); - } catch (err) { - if (err instanceof FormatError && err.code === "XML_MALFORMED") { - sink.broken.add(name); - continue; - } - throw err; - } - } -} - /** * Inflates one entry to its end, so the zip limits and its CRC are checked; * searches its bytes for ` { it("the hostile files are refused by inspect under their limits", async () => { for (const h of hostileFiles()) { - if (/^(xlsm|xltm|xltx|macro sheet|external link|connections|OLE object|query table|everything at once|malformed \(optional\))/.test(h.name)) continue; + if (/^(kind:|xlsm|xltm|xltx|macro sheet|external link|connections|OLE object|query table|everything at once|malformed \(optional\))/.test(h.name)) continue; const i = await outcome(inspect(await h.bytes(), h.limits ? { limits: h.limits } : {})); expect(i.err, h.name).toBeDefined(); expect(isExcelError(i.err), `${h.name}: ${describeError(i.err)}`).toBe(true); @@ -80,6 +80,32 @@ describe("inspect vs read: the differential test", () => { } }); + it("every kind the package scan reports (JSE-72) is reported by read and, the same, by inspect", async () => { + const want = ["activeX", "embeddedPackage", "customUI", "webExtension", "unreferencedPart", "invalidPartName", "macrosheet", "vbaProject"]; + const seen = new Set(); + for (const h of hostileFiles().filter((f) => f.name.startsWith("kind:"))) { + const bytes = await h.bytes(); + const [r, i] = [await read(bytes), await inspect(bytes)]; + const unsupported = r.warnings.filter((w) => w.code === "UNSUPPORTED_PART"); + expect(i.warnings, h.name).toEqual(unsupported); + expect(i.partKinds, h.name).toEqual([...new Set(unsupported.map((w) => w.partKind))]); + for (const k of i.partKinds) seen.add(k); + const orphan = unsupported.find((w) => w.partKind === "unreferencedPart"); + if (orphan) expect(i.warnings.find((w) => w.partKind === "unreferencedPart")!.parts).toEqual(orphan.parts); + } + for (const k of want) expect([...seen], k).toContain(k); + }); + + it("equivalent part names: inspect throws ZIP_INVALID as read does", async () => { + const h = hostileFiles().find((f) => f.name.startsWith("equivalent part names"))!; + const bytes = await h.bytes(); + const r = await outcome(read(bytes)); + expect((r.err as { code?: string }).code).toBe("ZIP_INVALID"); + const i = await outcome(inspect(bytes)); + expect((i.err as { code?: string; details?: unknown }).code).toBe("ZIP_INVALID"); + expect((i.err as { details?: unknown }).details).toEqual((r.err as { details?: unknown }).details); + }); + it("the part kinds files report what read reports", async () => { for (const h of hostileFiles().filter((f) => /^(xlsm|xltm|macro sheet|external link|connections|OLE object|query table|everything)/.test(f.name))) { const bytes = await h.bytes(); diff --git a/packages/javascript-excel/test/read/inspect-files.ts b/packages/javascript-excel/test/read/inspect-files.ts index a5c7012..f4b9e91 100644 --- a/packages/javascript-excel/test/read/inspect-files.ts +++ b/packages/javascript-excel/test/read/inspect-files.ts @@ -326,6 +326,34 @@ export function hostileFiles(): Hostile[] { return zipParts(p); }, }); + // The kinds the package scan reports (JSE-72): each in a file of its own, and all at once. + for (const [name, edit] of JSE72_KINDS) { + files.push({ + name: `kind: ${name}`, + bytes: () => { + const p = richParts(); + edit(p); + return zipParts(p); + }, + }); + } + files.push({ + name: "kind: every package-scan kind at once", + bytes: () => { + const p = richParts({ format: "xlsm" }); + for (const [, edit] of JSE72_KINDS) edit(p); + return zipParts(p); + }, + }); + files.push({ + name: "equivalent part names (read refuses with ZIP_INVALID)", + bytes: () => { + const p = richParts(); + p.set("xl/media/image%31.png", new Uint8Array([1, 2, 3])); + p.set("xl/media/image1.png", new Uint8Array([1, 2, 3])); + return zipParts(p); + }, + }); // Zip limits. files.push({ name: "maxInputBytes", bytes: () => zipParts(richParts()), limits: { maxInputBytes: 1000 } }); files.push({ name: "maxEntries", bytes: () => zipParts(richParts()), limits: { maxEntries: 5 } }); @@ -552,3 +580,51 @@ export function storedBlocks(data: Uint8Array, first: number, empty: number): Ui } return out; } + +const appendRel = (p: Parts, relsPart: string, rel: string): void => { + const current = p.get(relsPart); + p.set(relsPart, typeof current === "string" ? current.replace("", `${rel}`) : rels([rel])); +}; +const override = (p: Parts, part: string, type: string): void => { + p.set("[Content_Types].xml", (p.get("[Content_Types].xml") as string).replace("", ``)); +}; + +/** Edits of `richParts` that add one kind the package scan (JSE-72) reports. */ +export const JSE72_KINDS: ReadonlyArray<[string, (p: Parts) => void]> = [ + ["activeX (control relationship, ActiveX binary)", (p) => { + appendRel(p, "xl/worksheets/_rels/sheet1.xml.rels", rel("rIdAx", "control", "../activeX/activeX1.xml")); + p.set("xl/activeX/activeX1.xml", ``); + override(p, "xl/activeX/activeX1.xml", "application/vnd.ms-office.activeX+xml"); + appendRel(p, "xl/activeX/_rels/activeX1.xml.rels", rel("rId1", "http://schemas.microsoft.com/office/2006/relationships/activeXControlBinary", "activeX1.bin")); + p.set("xl/activeX/activeX1.bin", new Uint8Array([1, 2, 3, 4])); + }], + ["embeddedPackage (package relationship to a .docx)", (p) => { + appendRel(p, "xl/worksheets/_rels/sheet1.xml.rels", rel("rIdPk", "package", "../embeddings/Document1.docx")); + p.set("xl/embeddings/Document1.docx", new Uint8Array([0x50, 0x4b, 0x05, 0x06, ...new Uint8Array(18)])); + }], + ["customUI (ribbon extensibility)", (p) => { + appendRel(p, "_rels/.rels", rel("rIdUi", "http://schemas.microsoft.com/office/2007/relationships/ui/extensibility", "customUI/customUI14.xml")); + p.set("customUI/customUI14.xml", ``); + }], + ["webExtension (task pane add-in)", (p) => { + appendRel(p, "_rels/.rels", rel("rIdWe", "http://schemas.microsoft.com/office/2011/relationships/webextensiontaskpanes", "xl/webextensions/taskpanes.xml")); + p.set("xl/webextensions/taskpanes.xml", ``); + }], + ["unreferencedPart (an orphan part)", (p) => { + p.set("xl/orphan/payload.bin", new Uint8Array([9, 9, 9])); + }], + ["invalidPartName (a name OPC forbids)", (p) => { + p.set("xl/media/x.", new Uint8Array([7])); + }], + ["macrosheet (Excel's xlMacrosheet relationship)", (p) => { + appendRel(p, "xl/_rels/workbook.xml.rels", rel("rIdM", "http://schemas.microsoft.com/office/2006/relationships/xlMacrosheet", "macrosheets/sheet7.xml")); + p.set("xl/workbook.xml", (p.get("xl/workbook.xml") as string).replace("", '')); + p.set("xl/macrosheets/sheet7.xml", ``); + }], + ["vbaProject family (a VBA signature)", (p) => { + appendRel(p, "xl/_rels/workbook.xml.rels", rel("rIdV", "http://schemas.microsoft.com/office/2006/relationships/vbaProject", "vbaProject.bin")); + p.set("xl/vbaProject.bin", new Uint8Array([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1])); + appendRel(p, "xl/_rels/vbaProject.bin.rels", rel("rId1", "http://schemas.microsoft.com/office/2006/relationships/vbaProjectSignature", "vbaProjectSignature.bin")); + p.set("xl/vbaProjectSignature.bin", new Uint8Array([1])); + }], +]; From bab128536477fc4922c1880bb9e708c9d05b30f1 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 13:55:56 +0100 Subject: [PATCH 13/22] JSE-71 review 3: tests for the master budget, lazy shaping, strict declarations 400,000 cells each a master of its own si under a relative heap bound and the maxItems budget; a 50,000 x 10 shared-formula sheet under maxItems 100,000; inspect's time against read's on masters without copies; a redefined si releasing its records; XMLDecl grammar, declarations not at the very start and BOM-less UTF-16 declarations on parsed and unparsed parts; formulaShape against the compiler on 20,000 seeded formulas. --- .../test/read/inspect-encoding.test.ts | 70 ++++++++++++++-- .../test/read/inspect-files.ts | 26 ++++++ .../test/read/inspect.test.ts | 84 +++++++++++++++++++ .../test/read/shift-formula.test.ts | 25 ++++-- 4 files changed, 192 insertions(+), 13 deletions(-) diff --git a/packages/javascript-excel/test/read/inspect-encoding.test.ts b/packages/javascript-excel/test/read/inspect-encoding.test.ts index 87c96f7..bcb8942 100644 --- a/packages/javascript-excel/test/read/inspect-encoding.test.ts +++ b/packages/javascript-excel/test/read/inspect-encoding.test.ts @@ -193,9 +193,10 @@ describe("inspect: the encoding is decided on the whole declaration, however the expect(err?.details).toMatchObject({ part: DRAWING, encoding: "UTF-7" }); }); - it("an upper-case is checked like a declaration (XML parsers reject it as a reserved target)", async () => { + it("an upper-case is not a declaration: refused as malformed (XML parsers reject it as a reserved target)", async () => { const err = await refusal(withPart(DRAWING, ``)); - expect(err?.details).toMatchObject({ part: DRAWING, encoding: "UTF-7" }); + expect(err?.code).toBe("XML_MALFORMED"); + expect(err?.details).toMatchObject({ part: DRAWING }); }); it("an unparsed declaration longer than maxXmlTokenLength is refused as a token would be", async () => { @@ -205,12 +206,15 @@ describe("inspect: the encoding is decided on the whole declaration, however the expect(err?.details).toMatchObject({ limit: "maxXmlTokenLength", part: DRAWING }); }); - it("details.encoding is a short, printable excerpt of what the file declares", async () => { - const err = await refusal(withPart(DRAWING, ``)); - expect(err?.code).toBe("XML_MALFORMED"); - const encoding = err?.details?.["encoding"] as string; - expect(encoding.length).toBeLessThanOrEqual(40); - expect(encoding).toMatch(/^[\x20-\x7e]*$/); + it("details.encoding and details.declaration are short, printable excerpts of what the file declares", async () => { + const long = await refusal(withPart(DRAWING, ``)); + expect(long?.code).toBe("XML_MALFORMED"); + expect((long?.details?.["encoding"] as string).length).toBeLessThanOrEqual(40); + const odd = await refusal(withPart(DRAWING, ``)); + expect(odd?.code).toBe("XML_MALFORMED"); + const declaration = odd?.details?.["declaration"] as string; + expect(declaration.length).toBeLessThanOrEqual(40); + expect(declaration).toMatch(/^[\x20-\x7e]*$/); }); }); @@ -231,3 +235,53 @@ describe("inspect: relationship parts read already parsed are not counted twice expect(r.inflatedBytes).toBe(lo); }); }); + +describe("inspect: the XML declaration follows the XMLDecl grammar and stands at the very start (review 3)", () => { + const SHEET = "xl/worksheets/sheet2.xml"; + const body = (p: Parts) => (p.get(SHEET) as string).replace('', ""); + const bad = [ + ["two encodings", ''], + ["encoding inside the version's value", ``], + ["another attribute before it", ''], + ["attributes out of order", ''], + ["no version", ''], + ["an unquoted value", ""], + ]; + it.each(bad)("a parsed sheet whose declaration has %s", async (_, decl) => { + const p = richParts(); + p.set(SHEET, decl + body(p)); + const err = await refusal(p); + expect(err?.code).toBe("XML_MALFORMED"); + expect(err?.details?.["part"]).toBe(SHEET); + }); + it.each(bad)("an unparsed drawing whose declaration has %s", async (_, decl) => { + const err = await refusal(withPart(DRAWING, `${decl}`)); + expect(err?.code).toBe("XML_MALFORMED"); + expect(err?.details?.["part"]).toBe(DRAWING); + }); + + it.each([ + ["a comment", ""], + ["a processing instruction", ""], + ["a space", " "], + ])("a declaration naming UTF-7 after %s is refused, parsed or not", async (_, before) => { + const decl = ''; + const p = richParts(); + p.set(SHEET, before + decl + body(p)); + expect((await refusal(p))?.code).toBe("XML_MALFORMED"); + expect((await refusal(withPart(DRAWING, `${before}${decl}`)))?.code).toBe("XML_MALFORMED"); + }); + + it("a BOM-less UTF-16 drawing whose declaration names UTF-7 (either byte order)", async () => { + const text = ''; + const le = Uint8Array.from([...text].flatMap((c) => [c.charCodeAt(0), 0])); + const be = Uint8Array.from([...text].flatMap((c) => [0, c.charCodeAt(0)])); + for (const data of [le, be]) expect((await refusal(withPart(DRAWING, data)))?.details).toMatchObject({ part: DRAWING, encoding: "UTF-7" }); + }); + + it("well-formed declarations are accepted: version only, with encoding and standalone, single quotes, spaces and line breaks", async () => { + for (const decl of ['', ``, '', '']) { + expect(await refusal(withPart(DRAWING, `${decl}`)), decl).toBeUndefined(); + } + }); +}); diff --git a/packages/javascript-excel/test/read/inspect-files.ts b/packages/javascript-excel/test/read/inspect-files.ts index f4b9e91..262ab35 100644 --- a/packages/javascript-excel/test/read/inspect-files.ts +++ b/packages/javascript-excel/test/read/inspect-files.ts @@ -354,6 +354,32 @@ export function hostileFiles(): Hostile[] { return zipParts(p); }, }); + files.push({ + name: "declaration with two encodings in the worksheet (read accepts)", + bytes: () => { + const p = richParts(); + p.set("xl/worksheets/sheet2.xml", (p.get("xl/worksheets/sheet2.xml") as string).replace('', '')); + return zipParts(p); + }, + }); + files.push({ + name: "declaration after a comment in a drawing", + bytes: () => { + const p = richParts(); + p.set("xl/drawings/drawing1.xml", ``); + return zipParts(p); + }, + }); + files.push({ + name: "20,000 shared-formula masters of their own si", + bytes: () => { + const p = richParts(); + const rows = Array.from({ length: 20_000 }, (_, k) => `1`).join(""); + p.set("xl/worksheets/sheet2.xml", `${rows}`); + return zipParts(p); + }, + limits: { maxItems: 5_000 }, + }); // Zip limits. files.push({ name: "maxInputBytes", bytes: () => zipParts(richParts()), limits: { maxInputBytes: 1000 } }); files.push({ name: "maxEntries", bytes: () => zipParts(richParts()), limits: { maxEntries: 5 } }); diff --git a/packages/javascript-excel/test/read/inspect.test.ts b/packages/javascript-excel/test/read/inspect.test.ts index a49aaca..61f9c45 100644 --- a/packages/javascript-excel/test/read/inspect.test.ts +++ b/packages/javascript-excel/test/read/inspect.test.ts @@ -382,6 +382,90 @@ describe("inspect: shared-formula masters (review F1)", () => { await expect(inspect(bytes, { limits: { maxCellTextLength: master.length + 2000 } })).resolves.toBeDefined(); }); + /** One sheet of `n` cells, each a shared-formula master of its own `si` (the review's reproducer) or, with `plain`, an ordinary formula. */ + function distinctMasters(n: number, plain = false): Promise { + const rows: string[] = []; + for (let r = 1; r <= n; r++) rows.push(`1`); + const p = richParts({ rows: 1 }); + p.set("xl/worksheets/sheet2.xml", `${rows.join("")}`); + return zipParts(p); + } + + it("review 3: every live master counts against maxItems; 400,000 masters of their own si cost what 400,000 ordinary formulas cost", async () => { + const limits = { maxCells: 1_000_000, maxItems: 100_000, maxCellTextLength: 1000 }; + const shared = await distinctMasters(400_000); + const plain = await distinctMasters(400_000, true); + const base = await peakOf(() => inspect(plain, { limits })); + let err: LimitError | undefined; + const tight = await peakOf(() => inspect(shared, { limits }).catch((e: LimitError) => (err = e))); + console.log(`inspect, 400,000 formula cells: ordinary ${(base / 1e6).toFixed(0)} MB, each a master of its own si ${(tight / 1e6).toFixed(0)} MB (peak heap)`); + expect(err).toBeInstanceOf(LimitError); + expect(err!.details).toMatchObject({ limit: "maxItems", max: 100_000, part: "xl/worksheets/sheet2.xml" }); + expect(err!.details?.["sharedFormulaMasters"]).toBeGreaterThan(90_000); + // Until the limit trips, 100,000 live masters cost a few hundred bytes each (their numbers, the si map). + expect(tight).toBeLessThan(base + 32e6); + // read accepts the file: the masters are its cells. + await expect(read(shared, { limits })).resolves.toBeDefined(); + }, 180_000); + + it("review 3: a realistic sheet (50,000 rows x 10 shared-formula columns) passes under the default limits and maxItems 100,000, as read", async () => { + const rows: string[] = []; + for (let r = 1; r <= 50_000; r++) { + let row = ``; + for (let c = 0; c < 10; c++) { + const col = String.fromCharCode(66 + c); + row += r === 1 ? `A1*${c + 2}1` : `${r}`; + } + rows.push(`${row}`); + } + const p = richParts({ rows: 1 }); + p.set("xl/worksheets/sheet2.xml", `${rows.join("")}`); + const bytes = await zipParts(p); + for (const limits of [undefined, { maxItems: 100_000 }]) { + const r = await read(bytes, limits ? { limits } : {}); + const i = await inspect(bytes, limits ? { limits } : {}); + expect(i.sheets[1]!.cells).toBe(500_000); + expect(i.sheets[1]!.dimension).toBe(r.workbook.sheets[1]!.dimension); + } + }, 120_000); + + it("review 3: masters without copies cost inspect about what they cost read (time ratio); past 8 Mi characters pending, about three times", async () => { + const time = async (fn: () => Promise): Promise => { + const t0 = performance.now(); + await fn(); + return performance.now() - t0; + }; + // 6,000 x 998 characters stay under the pending-text budget; 30,000 x 998 go past it. + for (const [n, bound] of [ + [6_000, 1.6], + [30_000, 6], + ] as const) { + const file = await masters(n, 998); + await read(file); // warm up + for (const limits of [undefined, { maxCellTextLength: 1000 }]) { + const o = limits ? { limits } : {}; + const r = Math.min(await time(() => read(file, o)), await time(() => read(file, o)), await time(() => read(file, o))); + const i = Math.min(await time(() => inspect(file, o)), await time(() => inspect(file, o)), await time(() => inspect(file, o))); + console.log(`${n} masters of 998 characters ${JSON.stringify(limits ?? {})}: read ${r.toFixed(0)} ms, inspect ${i.toFixed(0)} ms`); + expect(i).toBeLessThan(bound * r); + } + } + }, 300_000); + + it("review 3: redefining one si many times releases the replaced master's reference records", async () => { + const master = Array.from({ length: 1500 }, (_, k) => `A${k + 1}`).join("+"); + const rows: string[] = []; + for (let m = 1; m <= 80; m++) rows.push(`${master}`); + rows.push(``); + const p = richParts({ rows: 1 }); + p.set("xl/worksheets/sheet2.xml", `${rows.join("")}`); + const bytes = await zipParts(p); + // 1,501 records each: one live master fits 100,000; eighty counted together would not. + const limits = { maxCellTextLength: master.length + 2000, maxItems: 100_000 }; + await expect(read(bytes, { limits })).resolves.toBeDefined(); + await expect(inspect(bytes, { limits })).resolves.toMatchObject({ format: "xlsx" }); + }); + it("whether a shared copy resolves (and so whether a value-less cell counts) is decided as read decides it, for every maxCellTextLength", async () => { // A master in C3 shared down and across; copies near the sheet's edges grow longer (XFD1048576 vs A1). const master = Array.from({ length: 40 }, (_, k) => `A${k + 1}`).join("+"); diff --git a/packages/javascript-excel/test/read/shift-formula.test.ts b/packages/javascript-excel/test/read/shift-formula.test.ts index dabfb17..709579c 100644 --- a/packages/javascript-excel/test/read/shift-formula.test.ts +++ b/packages/javascript-excel/test/read/shift-formula.test.ts @@ -1,7 +1,7 @@ // JSE-62: the compiled shifter gives exactly what the 2.3.0 shifter gave, for // every formula and offset, while each copy costs its own length once. import { describe, expect, it } from "vitest"; -import { canShift, colLetters, colNumber, compileFormula, lengthParts, shiftCompiled, shiftedLength, shiftedLengthRange, shiftFormula, shiftWork } from "../../src/internal/read/formula"; +import { canShift, colLetters, colNumber, compileFormula, formulaShape, lengthParts, partsOf, shiftCompiled, shiftedLength, shiftedLengthRange, shiftFormula, shiftWork } from "../../src/internal/read/formula"; const MAX_ROW = 1_048_576; const MAX_COL = 16_384; @@ -213,8 +213,8 @@ describe("the compiled shifter equals the 2.3.0 shifter", () => { }); }); -describe("lengthParts / shiftedLength (JSE-71): a copy's exact length without its text", () => { - it("equals the length of the copy shiftCompiled builds, and lies in shiftedLengthRange, for 5,000 seeded formulas and offsets", () => { +describe("lengthParts, formulaShape / shiftedLength (JSE-71): a copy's exact length without its text", () => { + it("equals the length of the copy shiftCompiled builds, and lies in shiftedLengthRange, for 20,000 seeded formulas and offsets", () => { let seed = 71; const rnd = (n: number) => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; @@ -234,20 +234,35 @@ describe("lengthParts / shiftedLength (JSE-71): a copy's exact length without it } }; let checked = 0; - for (let k = 0; k < 5_000; k++) { - const formula = Array.from({ length: 1 + rnd(6) }, () => (rnd(4) ? ref() : `"t${rnd(9)}"`)).join(rnd(2) ? "+" : ","); + for (let k = 0; k < 20_000; k++) { + const noise = ["SUM(", ")", "'It''s'!", "[1]Sheet1!", "Table1[[#This Row],[Col]]", "a1", "$b$2", "ABCD12", "1E5", "$", "_x", "A1B2", "R1C1", "XFE1", "A0", "A01", "Sheet1!", "\"q\"\"q\"", ".5", "IF(", ":", "!", "aa:zz", "1:$3", "$A$1:$B$2", "XFD1048576"]; + const formula = Array.from({ length: 1 + rnd(8) }, () => (rnd(3) ? ref() : rnd(2) ? `"t${rnd(9)}"` : noise[rnd(noise.length)]!)).join(["+", ",", "", " ", "*"][rnd(5)]!); const c = compileFormula(formula); const dRow = rnd(2) ? rnd(40) - 20 : rnd(2_000_000) - 1_000_000; const dCol = rnd(2) ? rnd(40) - 20 : rnd(30_000) - 15_000; + const shapeAny = formulaShape(formula, true); + expect([shapeAny.min, shapeAny.max], formula).toEqual(shiftedLengthRange(c)); + expect([shapeAny.rowMin, shapeAny.rowMax, shapeAny.colMin, shapeAny.colMax], formula).toEqual([c.rowMin, c.rowMax, c.colMin, c.colMax]); + expect([shapeAny.fixed, [...partsOf(shapeAny.keys)].join()], formula).toEqual([lengthParts(c).fixed, sortedTriples(lengthParts(c).parts)]); if (!canShift(c, dRow, dCol)) continue; const text = shiftCompiled(c, dRow, dCol) as string; const { fixed, parts } = lengthParts(c); expect(shiftedLength(fixed, parts, dRow, dCol), `${formula} by ${dRow},${dCol}`).toBe(text.length); + const shape = formulaShape(formula, true); + expect([shape.min, shape.max], formula).toEqual(shiftedLengthRange(c)); + expect(shiftedLength(shape.fixed, partsOf(shape.keys), dRow, dCol), formula).toBe(text.length); + expect([shape.rowMin, shape.rowMax, shape.colMin, shape.colMax]).toEqual([c.rowMin, c.rowMax, c.colMin, c.colMax]); const [min, max] = shiftedLengthRange(c); expect(text.length).toBeGreaterThanOrEqual(min); expect(text.length).toBeLessThanOrEqual(max); checked++; } expect(checked).toBeGreaterThan(1_000); + function sortedTriples(parts: Int32Array): string { + const t: number[][] = []; + for (let k = 0; k < parts.length; k += 3) t.push([parts[k]!, parts[k + 1]!, parts[k + 2]!]); + t.sort((x, y) => x[1]! * 2 + x[0]! - (y[1]! * 2 + y[0]!)); + return t.flat().join(); + } }); }); From 64d4f73977e376e45f23ebd9f6ee0b952366e3b6 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 13:55:56 +0100 Subject: [PATCH 14/22] JSE-71 review 3: lean masters counted and shaped lazily; strict XML declarations A master keeps its text (UTF-8, at most 8 MiB per sheet) until a copy needs it, then numbers only from one allocation-free pass (formulaShape); every live master and reference record counts against maxItems, and a redefined si releases its records. read's shared-formula path is main's again. Every XML part's start is read by one per-part check, fed by ctx.parse or by the byte scan: first bytes, BOM-less UTF-16, the declaration held to the XMLDecl grammar, and no void) | undefined; /** - * inspect (JSE-71): sees the first four inflated bytes of every part parsed - * as XML (fewer only when the part is shorter), however the inflater splits - * them, and its XML declaration, whole, from the tokenizer. + * inspect (JSE-71): for every part parsed as XML, a sniffer that sees its + * inflated bytes (however the inflater splits them) and, from the tokenizer, + * every processing instruction whose target is `xml` in any case. */ - sniff: ((part: string, first: Uint8Array) => void) | undefined; - declared: ((part: string, declaration: string) => void) | undefined; + sniff: ((part: string) => PartSniffer | undefined) | undefined; /** inspect (JSE-71): sees every relationship part the package parses, with its relationships. */ relsParsed: ((part: string, rels: ReadonlyArray<{ kind: string; target: string; external: boolean; altTarget?: string | undefined; tooLong?: boolean | undefined }>) => void) | undefined; /** Returns to the event loop about every 16 ms between chunks, so a big read does not freeze the page (JSE-24). */ @@ -158,19 +157,12 @@ export class ReadContext { */ async parse(entry: ZipEntryInfo, handler: XmlHandler, onChunk?: (bytes: number) => void): Promise { this.consumed.add(entry.name); - const declared = this.declared; - const tok = new XmlTokenizer(handler, this.limits.maxXmlDepth, this.limits.maxXmlTokenLength, declared && ((pi) => declared(entry.name, pi))); + const sniffer = this.sniff?.(entry.name); + const tok = new XmlTokenizer(handler, this.limits.maxXmlDepth, this.limits.maxXmlTokenLength, sniffer && ((pi) => sniffer.pi(pi))); let decoder: TextDecoderLike | undefined; - let head: Uint8Array | undefined = this.sniff ? new Uint8Array(0) : undefined; try { for await (const chunk of this.zip.stream(entry, this.signal)) { - if (head) { - head = joinHead(head, chunk, 4); - if (head.length >= 4) { - this.sniff!(entry.name, head); - head = undefined; - } - } + sniffer?.feed(chunk); let bytes = chunk; if (!decoder) { decoder = newDecoder(chunk); @@ -200,22 +192,20 @@ export class ReadContext { this.checkAbort(); } } - if (head) this.sniff!(entry.name, head); if (decoder) tok.feed(decoder.decode()); tok.end(); + sniffer?.end(); } catch (err) { throw withPart(err, entry.name); } } } -/** `head` with the start of `chunk` appended, up to `n` bytes in all. */ -export function joinHead(head: Uint8Array, chunk: Uint8Array, n: number): Uint8Array { - if (head.length >= n) return head; - const out = new Uint8Array(Math.min(n, head.length + chunk.length)); - out.set(head); - out.set(chunk.subarray(0, out.length - head.length), head.length); - return out; +/** What inspect (JSE-71) sees of a part read parses: every inflated chunk in order, every `, dRow: number, dCol: number): boolean { if (dRow === 0 && dCol === 0) return true; if (c.rowMin !== Infinity && (c.rowMin + dRow < 1 || c.rowMax + dRow > MAX_ROW)) return false; if (c.colMin !== Infinity && (c.colMin + dCol < 1 || c.colMax + dCol > MAX_COL)) return false; @@ -361,6 +361,187 @@ function digitCount(v: number): number { return d; } +/** What a lean shared-formula master keeps (JSE-71): see formulaShape. */ +export interface FormulaShape { + rowMin: number; + rowMax: number; + colMin: number; + colMax: number; + /** The shortest and longest text a shifted copy can have (shiftedLengthRange). */ + min: number; + max: number; + /** The copy's characters that never change; with `parts` (lengthParts), its exact length per offset. */ + fixed: number; + /** Relative parts as keys (value * 2 + isRow), with collectParts; else empty. */ + keys: number[]; +} + +/** + * One pass over a master's text (JSE-71), allocating nothing per reference: + * the relative bounds, the range of a copy's length and the characters that + * never change, as compileFormula, shiftedLengthRange and lengthParts give + * them; with `collectParts`, the relative parts too. It walks the text as + * compileFormula does and recognises references as parseRef does (the tests + * compare the two on seeded formulas), so a copy's text is the original's + * with each reference re-printed as refText prints it. + */ +export function formulaShape(formula: string, collectParts: boolean): FormulaShape { + let rowMin = Infinity; + let rowMax = -Infinity; + let colMin = Infinity; + let colMax = -Infinity; + let fixed = formula.length; + let relCols = 0; + let relRows = 0; + const keys: number[] = []; + const col = (anchored: boolean, v: number): void => { + if (anchored) fixed += 1 + (v <= 26 ? 1 : v <= 702 ? 2 : 3); + else { + relCols++; + if (v < colMin) colMin = v; + if (v > colMax) colMax = v; + if (collectParts) keys.push(v * 2); + } + }; + const row = (anchored: boolean, v: number): void => { + if (anchored) fixed += 1 + digitCount(v); + else { + relRows++; + if (v < rowMin) rowMin = v; + if (v > rowMax) rowMax = v; + if (collectParts) keys.push(v * 2 + 1); + } + }; + const n = formula.length; + let i = 0; + while (i < n) { + const code = formula.charCodeAt(i); + if (code === 34 || code === 39) { + let j = i + 1; + for (; j < n; j++) { + if (formula.charCodeAt(j) === code) { + if (formula.charCodeAt(j + 1) === code) j++; + else break; + } + } + i = j + 1; + continue; + } + if (code === 91) { + let depth = 0; + let j = i; + for (; j < n; j++) { + const c = formula.charCodeAt(j); + if (c === 91) depth++; + else if (c === 93 && --depth === 0) break; + } + i = j + 1; + continue; + } + const prev = i > 0 ? formula.charCodeAt(i - 1) : -1; + if ((code === 36 || isAlnumCode(code)) && !isWordCode(prev) && prev !== 36) { + const end = refAt(formula, i); + if (end >= 0) { + fixed -= end - i; + const r = REF; + if (r.kind === COLS_REF) { + col(r.aAnchored, r.a); + col(r.bAnchored, r.b); + fixed += 1; + } else if (r.kind === ROWS_REF) { + row(r.aAnchored, r.a); + row(r.bAnchored, r.b); + fixed += 1; + } else { + col(r.aAnchored, r.a); + row(r.bAnchored, r.b); + } + i = end; + continue; + } + let j = i + 1; + while (j < n && isWordCode(formula.charCodeAt(j))) j++; + i = j; + continue; + } + i++; + } + return { rowMin, rowMax, colMin, colMax, min: fixed + relCols + relRows, max: fixed + 3 * relCols + 7 * relRows, fixed, keys }; +} + +/** refAt's result, reused (formulaShape reads it before the next call). */ +const REF = { kind: CELL_REF as number, aAnchored: false, a: 0, bAnchored: false, b: 0 }; + +/** parseRef without allocating: the reference at `i` into REF and the index after it, or -1. */ +function refAt(f: string, i: number): number { + const n = f.length; + const aAnchored = f.charCodeAt(i) === 36; + const p = i + (aAnchored ? 1 : 0); + let la = 0; + while (la < 3 && p + la < n && isLetterCode(f.charCodeAt(p + la))) la++; + let da = 0; + if (la === 0) while (da < 7 && p + da < n && isDigitCode(f.charCodeAt(p + da))) da++; + const first = la || da; + if (first > 0 && f.charCodeAt(p + first) === 58) { + const q = p + first + 1; + const bAnchored = q < n && f.charCodeAt(q) === 36; + const r = q + (bAnchored ? 1 : 0); + let second = 0; + if (la) while (second < 3 && r + second < n && isLetterCode(f.charCodeAt(r + second))) second++; + else while (second < 7 && r + second < n && isDigitCode(f.charCodeAt(r + second))) second++; + if (second > 0 && isEnd(f, r + second)) { + if (la) { + const a = colAt(f, p, la); + const b = colAt(f, r, second); + if (a > MAX_COL || b > MAX_COL) return -1; + return setRef(COLS_REF, aAnchored, a, bAnchored, b, r + second); + } + return setRef(ROWS_REF, aAnchored, digitsAt(f, p, da), bAnchored, digitsAt(f, r, second), r + second); + } + } + if (la > 0) { + const q = p + la; + const bAnchored = f.charCodeAt(q) === 36; + const r = q + (bAnchored ? 1 : 0); + let digits = 0; + while (digits < 7 && r + digits < n && isDigitCode(f.charCodeAt(r + digits))) digits++; + if (digits > 0 && isEnd(f, r + digits)) { + const c = colAt(f, p, la); + if (c > MAX_COL) return -1; + return setRef(CELL_REF, aAnchored, c, bAnchored, digitsAt(f, r, digits), r + digits); + } + } + return -1; +} + +function setRef(kind: number, aAnchored: boolean, a: number, bAnchored: boolean, b: number, end: number): number { + REF.kind = kind; + REF.aAnchored = aAnchored; + REF.a = a; + REF.bAnchored = bAnchored; + REF.b = b; + return end; +} + +/** formulaShape's keys as lengthParts' triples (isRow, value, count). */ +export function partsOf(list: number[]): Int32Array { + const keys = Int32Array.from(list).sort(); + let distinct = 0; + for (let i = 0; i < keys.length; i++) if (i === 0 || keys[i] !== keys[i - 1]) distinct++; + const out = new Int32Array(distinct * 3); + let o = -3; + for (let i = 0; i < keys.length; i++) { + const k = keys[i]!; + if (i === 0 || k !== keys[i - 1]) { + o += 3; + out[o] = k & 1; + out[o + 1] = Math.floor(k / 2); + } + out[o + 2]!++; + } + return out; +} + /** `formula` shifted by (dRow, dCol), or undefined when a reference would leave the sheet. */ export function shiftFormula(formula: string, dRow: number, dCol: number): string | undefined { if (dRow === 0 && dCol === 0) return formula; @@ -369,6 +550,20 @@ export function shiftFormula(formula: string, dRow: number, dCol: number): strin } /** Whether a reference may end before `end`: no word character, `(`, `!` or `$` follows. */ +/** colNumber(f.slice(at, at + n)) without the slice; `n` ASCII letters. */ +function colAt(f: string, at: number, n: number): number { + let v = 0; + for (let k = 0; k < n; k++) v = v * 26 + ((f.charCodeAt(at + k) & ~32) - 64); + return v; +} + +/** Number(f.slice(at, at + n)) without the slice; `n` (at most 7) ASCII digits. */ +function digitsAt(f: string, at: number, n: number): number { + let v = 0; + for (let k = 0; k < n; k++) v = v * 10 + (f.charCodeAt(at + k) - 48); + return v; +} + function isEnd(f: string, end: number): boolean { if (end >= f.length) return true; const c = f.charCodeAt(end); diff --git a/packages/javascript-excel/src/internal/read/inspect.ts b/packages/javascript-excel/src/internal/read/inspect.ts index 3bc9cf3..da9c58b 100644 --- a/packages/javascript-excel/src/internal/read/inspect.ts +++ b/packages/javascript-excel/src/internal/read/inspect.ts @@ -21,7 +21,8 @@ import { FormatError, LimitError } from "../../errors"; import type { InspectedSheet, InspectFormat, InspectOptions, InspectResult } from "../../read"; import type { ExcelPartKind } from "../../warnings"; import { excerpt } from "../excerpt"; -import { newDecoder, PARSE_SLICE, withPart, type ReadContext } from "./context"; +import { newDecoder, PARSE_SLICE, withPart, type PartSniffer, type ReadContext } from "./context"; +import { DEFAULT_LIMITS } from "./limits"; import { partKey, type Package } from "./opc"; import { readImpl, type InspectSink } from "./reader"; import type { ZipEntryInfo } from "../zip/read"; @@ -33,6 +34,8 @@ import type { ZipEntryInfo } from "../zip/read"; * case, as the tokenizer refuses it. */ const DOCTYPE = /<(\u0000{0,3})!\1d\1o\1c\1t\1y\1p\1e|\+ADw(?:-!|AIQ-|-\+ACE-)doctype/i; +/** A processing instruction whose target is `xml` in any case, in the same byte forms as DOCTYPE. */ +const XML_PI = /<(\u0000{0,3})\?\1x\1m\1l\1[ \t\r\n?]/gi; /** Characters kept between two pieces, so a declaration split across them is found: the longest match less one. */ const DOCTYPE_TAIL = 32; /** Reads bytes as characters one to one (windows-1252: ASCII and NUL map to themselves). */ @@ -86,12 +89,25 @@ export function signatureEncoding(b: Uint8Array): string | undefined { return undefined; } -/** The encoding a whole XML declaration names when it is not UTF-8 or UTF-16, cleaned for `details`; else undefined. */ -export function declaredEncoding(declaration: string): string | undefined { - const m = /\bencoding\s*=\s*(["'])([^"']*)\1/.exec(declaration); - if (!m) return undefined; - const name = m[2]!.trim(); - return /^utf-?(8|16(le|be)?)$/i.test(name) ? undefined : printable(name); +/** + * The XMLDecl production (XML 1.0 §2.8), strictly: `$/; + +/** A whole declaration at the start of a part: undefined when it is well-formed and names UTF-8, UTF-16 or nothing. */ +export function checkDeclaration(part: string, declaration: string): FormatError | undefined { + const m = XML_DECLARATION.exec(declaration); + if (!m) { + return new FormatError("XML_MALFORMED", `${excerpt(part)}: the XML declaration is not well-formed (XML 1.0 XMLDecl).`, { details: { part, declaration: printable(declaration) } }); + } + const name = m[1] ?? m[2]; + return name === undefined || /^utf-?(8|16(le|be)?)$/i.test(name) ? undefined : encodingError(part, printable(name)); +} + +function misplacedDeclaration(part: string): FormatError { + return new FormatError("XML_MALFORMED", `${excerpt(part)}: an XML declaration () appears other than at the very start of the part.`, { details: { part } }); } /** File text for `details`: printable ASCII only, at most 40 characters. */ @@ -111,11 +127,9 @@ function doctype(): FormatError { } export async function inspectImpl(bytes: Uint8Array, options?: InspectOptions): Promise { - // Parts read parses: their encoding is refused only once the read has succeeded, so read's own errors come first. - let badEncoding: { part: string; encoding: string } | undefined; - const note = (part: string, encoding: string | undefined): void => { - if (encoding !== undefined && !badEncoding) badEncoding = { part, encoding }; - }; + // Parts read parses: what their checks find is refused only once the read has succeeded, so read's own errors come first. + let deferred: unknown; + const maxToken = (options?.limits?.maxXmlTokenLength as number | undefined) ?? DEFAULT_LIMITS.maxXmlTokenLength; const xmlTargets = new Set(); const relsDone = new Set(); const sink: InspectSink = { @@ -123,8 +137,7 @@ export async function inspectImpl(bytes: Uint8Array, options?: InspectOptions): broken: new Set(), sharedStrings: 0, sheets: [], - sniff: (part, first) => note(part, signatureEncoding(first)), - declared: (part, declaration) => note(part, declaredEncoding(declaration)), + sniff: (part) => new PartCheck(part, maxToken, (err) => (deferred ??= err)), // read parses every relationships part once (the package scan, scan.ts): their relationships are used as they are, // and the parts are not inflated (and counted toward maxTotalBytes) again. relsParsed: (part, rels) => { @@ -139,7 +152,7 @@ export async function inspectImpl(bytes: Uint8Array, options?: InspectOptions): const { workbook } = await readImpl(bytes, { limits: options?.limits, signal: options?.signal }, { inspect: sink }); const ctx = sink.ctx!; const pkg = sink.pkg!; - if (badEncoding) throw encodingError(badEncoding.part, badEncoding.encoding); + if (deferred !== undefined) throw deferred; for (const entry of ctx.zip.entries) { if ((ctx.consumed.has(entry.name) || relsDone.has(entry.name)) && !sink.broken.has(entry.name)) continue; const pause = ctx.step(); @@ -176,52 +189,116 @@ export async function inspectImpl(bytes: Uint8Array, options?: InspectOptions): */ async function scanPart(ctx: ReadContext, entry: ZipEntryInfo, xml: boolean): Promise { let tail = ""; - const decl = xml ? new DeclarationReader(ctx.limits.maxXmlTokenLength) : undefined; + let offset = 0; + let lastPi = -1; + let failure: unknown; + const check = xml ? new PartCheck(entry.name, ctx.limits.maxXmlTokenLength, (err) => (failure ??= err)) : undefined; try { for await (const chunk of ctx.zip.stream(entry, ctx.signal)) { - // The encoding is decided on the first bytes and the whole declaration, before they are searched. - const encoding = decl?.feed(chunk); - if (encoding !== undefined) throw encodingError(entry.name, encoding); + // The encoding and the declaration are decided on the first bytes, before they are searched. + check?.feed(chunk); + if (failure !== undefined) throw failure; for (let at = 0; at < chunk.length; ) { const piece = chunk.subarray(at, at + PARSE_SLICE); - at += piece.length; const s = tail + BYTES.decode(piece); if (DOCTYPE.test(s)) throw doctype(); + if (check) { + // Every ` lastPi) { + lastPi = base + m.index; + check.pi(); + } + } + } + at += piece.length; tail = s.slice(-DOCTYPE_TAIL); if (at < chunk.length) { const pause = ctx.step(); if (pause) await pause; } } + offset += chunk.length; const pause = ctx.step(); if (pause) await pause; } - const encoding = decl?.end(); - if (encoding !== undefined) throw encodingError(entry.name, encoding); + check?.end(); + if (failure !== undefined) throw failure; } catch (err) { throw withPart(err, entry.name); } } /** - * Reads the start of a part that read does not parse, however it is chunked: - * its first four bytes (signatureEncoding), then, decoded as UTF-8 or UTF-16 - * by its byte order mark as read decodes, its XML declaration up to `?>`, - * bounded like any token by maxXmlTokenLength. `feed` and `end` return a - * forbidden encoding once one is known. Linear: each chunk is decoded and - * searched once. + * The checks of one XML part, parsed by read (through ctx.sniff) or not + * (scanPart): its first bytes and its declaration (DeclarationReader), and + * that no ` void, + ) { + this.reader = new DeclarationReader(part, maxToken); + } + + feed(chunk: Uint8Array): void { + if (!this.failed) this.report(() => this.reader.feed(chunk)); + } + + pi(): void { + this.instructions++; + } + + end(): void { + if (!this.failed) this.report(() => this.reader.end()); + if (!this.failed && this.instructions > (this.reader.hasDeclaration ? 1 : 0)) this.report(() => misplacedDeclaration(this.part)); + } + + private report(step: () => FormatError | undefined): void { + let err: unknown; + try { + err = step(); + } catch (thrown) { + err = withPart(thrown, this.part); + } + if (err !== undefined) { + this.failed = true; + this.fail(err); + } + } +} + +/** + * Reads the start of an XML part, however it is chunked: its first four bytes + * (signatureEncoding), then, decoded as UTF-8 or UTF-16 by its byte order mark + * or, without one, by ``, bounded + * like any token by maxXmlTokenLength, which must stand at the very start + * (checkDeclaration). Linear: each chunk is decoded and searched once. */ class DeclarationReader { + hasDeclaration = false; private pending: Uint8Array[] = []; private pendingLength = 0; - private decoder: ReturnType | undefined; + private decoder: { decode(input?: Uint8Array, options?: { stream?: boolean }): string } | undefined; private text = ""; private searched = 0; private done = false; - constructor(private readonly maxToken: number) {} + constructor( + private readonly part: string, + private readonly maxToken: number, + ) {} - feed(chunk: Uint8Array): string | undefined { + feed(chunk: Uint8Array): FormatError | undefined { if (this.done) return undefined; if (!this.decoder) { this.pending.push(chunk); @@ -232,7 +309,7 @@ class DeclarationReader { return this.more(this.decoder.decode(chunk, { stream: true })); } - end(): string | undefined { + end(): FormatError | undefined { if (this.done) return undefined; if (!this.decoder) { const found = this.start(); @@ -241,7 +318,7 @@ class DeclarationReader { return this.more(this.decoder!.decode(), true); } - private start(): string | undefined { + private start(): FormatError | undefined { const head = new Uint8Array(this.pendingLength); let at = 0; for (const p of this.pending) { @@ -252,36 +329,38 @@ class DeclarationReader { const sig = signatureEncoding(head); if (sig !== undefined) { this.done = true; - return sig; + return encodingError(this.part, sig); } - this.decoder = newDecoder(head); + const Ctor = (globalThis as unknown as { TextDecoder: new (label: string) => NonNullable }).TextDecoder; + if (head[0] === 0x3c && head[1] === 0x00 && head[2] === 0x3f && head[3] === 0x00) this.decoder = new Ctor("utf-16le"); + else if (head[0] === 0x00 && head[1] === 0x3c && head[2] === 0x00 && head[3] === 0x3f) this.decoder = new Ctor("utf-16be"); + else this.decoder = newDecoder(head); return this.more(this.decoder.decode(head, { stream: true })); } - private more(text: string, final = false): string | undefined { + private more(text: string, final = false): FormatError | undefined { this.text += text; const t = this.text; - // Before the declaration: a byte order mark (dropped by the decoder) and nothing else; leading space is let through. - const lead = t.length - t.trimStart().length; - const rest = t.slice(lead, lead + 6); // Too short to tell yet: what has come is the start of "", Math.max(lead, this.searched - 1)); + this.hasDeclaration = true; + const close = t.indexOf("?>", Math.max(0, this.searched - 1)); if (close === -1) { this.searched = t.length; - if (final) this.done = true; - return final ? undefined : this.bound(); + if (!final) return this.bound(); + this.done = true; + return checkDeclaration(this.part, t); } this.done = true; - if (close + 2 - lead > this.maxToken) this.bound(true); - return declaredEncoding(t.slice(lead, close + 2)); + if (close + 2 > this.maxToken) this.bound(true); + return checkDeclaration(this.part, t.slice(0, close + 2)); } - /** A declaration (with the space before it) longer than maxXmlTokenLength is refused, as the tokenizer refuses a token. */ + /** A declaration longer than maxXmlTokenLength is refused, as the tokenizer refuses a token. */ private bound(over = false): undefined { if (over || this.text.length > this.maxToken) { throw new LimitError("LIMIT_EXCEEDED", `An XML tag, comment, CDATA section or processing instruction is longer than maxXmlTokenLength (${this.maxToken}).`, { diff --git a/packages/javascript-excel/src/internal/read/reader.ts b/packages/javascript-excel/src/internal/read/reader.ts index 7e1bba7..385570c 100644 --- a/packages/javascript-excel/src/internal/read/reader.ts +++ b/packages/javascript-excel/src/internal/read/reader.ts @@ -254,9 +254,8 @@ export interface InspectSink { unsupported: ExcelWarning[]; /** Parts whose XML was malformed and skipped (BROKEN_OPTIONAL_PART): not read to their end. */ broken: Set; - /** From the first part on (ReadContext): the first bytes and the declaration of every part parsed as XML, and every relationship part parsed. */ + /** From the first part on (ReadContext): a sniffer for every part parsed as XML, and every relationship part parsed. */ sniff: NonNullable; - declared: NonNullable; relsParsed: NonNullable; /** Items in the shared strings table. */ sharedStrings: number; @@ -286,7 +285,6 @@ export async function readImpl(input: BinaryInput, options?: ReadOptions, intern ctx = new ReadContext(zip, limits, o.signal, o.onWarning, o.onProgress); if (internal?.inspect) { ctx.sniff = internal.inspect.sniff; - ctx.declared = internal.inspect.declared; ctx.relsParsed = internal.inspect.relsParsed; } return ctx; diff --git a/packages/javascript-excel/src/internal/read/sheet.ts b/packages/javascript-excel/src/internal/read/sheet.ts index 232214f..0a4be92 100644 --- a/packages/javascript-excel/src/internal/read/sheet.ts +++ b/packages/javascript-excel/src/internal/read/sheet.ts @@ -8,7 +8,7 @@ import type { Cell, CellValue, ColumnProps, Hyperlink, PrintSetup, RichText, RowProps, Sheet, SheetView } from "../../model"; import { LimitError } from "../../errors"; import type { ReadContext } from "./context"; -import { canShift, colLetters, colNumber, compileFormula, lengthParts, MAX_SHARED_FORMULA_LENGTH, shiftCompiled, shiftedLength, shiftedLengthRange, type CompiledFormula } from "./formula"; +import { canShift, colLetters, colNumber, compileFormula, formulaShape, MAX_SHARED_FORMULA_LENGTH, partsOf, shiftCompiled, shiftedLength, type CompiledFormula } from "./formula"; import { isDateFormat } from "../../numfmt"; import type { Relationship } from "./opc"; import { serialToDate } from "../../dates"; @@ -104,28 +104,32 @@ interface PendingCell { inline: string | RichText | undefined; } -/** Shared by every lean master's bounds (they hold no segments or references). */ -const NONE: string[] = []; -const NO_SLOTS: number[] = []; -const NO_REFS: CompiledFormula["uniq"] = []; +/** Bytes (UTF-8) of shared-formula masters a sheet keeps, at most, until a copy needs them (inspect, JSE-71). */ +export const PENDING_TEXT: number = 8 * 1024 * 1024; -/** A shared formula's master, as a sheet keeps it until the sheet ends. */ -interface SharedMaster { - /** The text; "" for a lean master, whose copies' text is never built. */ - formula: string; - length: number; - row: number; - col: number; - ref: string; - compiled: CompiledFormula | undefined; - /** - * Lean masters only (keepCells false, JSE-71): whether every shifted copy - * fits maxCellTextLength. Undefined for a kept master, and for a lean one - * whose copies may or may not fit: that one has `lengths` instead. - */ - fits: boolean | undefined; - /** A lean master whose copies may or may not fit: what each copy's exact length depends on (formula.ts lengthParts). */ - lengths?: { fixed: number; parts: Int32Array } | undefined; +/** + * A shared formula's master as inspect keeps it (keepCells false, JSE-71): + * numbers only, in one small object; the bounds are canShift's. + */ +const UTF8 = new (globalThis as unknown as { TextEncoder: new () => { encode(s: string): Uint8Array } }).TextEncoder(); +const UTF8_TEXT = new (globalThis as unknown as { TextDecoder: new () => { decode(b: Uint8Array): string } }).TextDecoder(); + +class LeanMaster { + rowMin = Infinity; + rowMax = -Infinity; + colMin = Infinity; + colMax = -Infinity; + /** Whether every copy fits maxCellTextLength; `parts`, when set, decides per copy instead. */ + fits = false; + fixed = 0; + parts: Int32Array | undefined = undefined; + /** The master's text, as UTF-8, until it is shaped (setLean); then undefined. */ + text: Uint8Array | string | undefined = undefined; + constructor( + readonly row: number, + readonly col: number, + readonly length: number, + ) {} } interface RawHyperlink { @@ -218,7 +222,7 @@ export class SheetParser implements XmlHandler { private readonly merges: string[] = []; private readonly hyperlinks: RawHyperlink[] = []; /** Shared formula masters by `si`; compiled when the first cell that shares one needs it. */ - private readonly shared = new Map(); + private readonly shared = new Map(); private view: SheetView | undefined; private print: PrintSetup | undefined; private fitToPage = false; @@ -246,8 +250,12 @@ export class SheetParser implements XmlHandler { private readonly keep: boolean; /** Cells kept (or, without keepCells, that would have been), as maxCells counts them. */ cellCount = 0; - /** Without keepCells: reference records kept for shared formulas on this sheet (leanMaster). */ - private lengthRecords = 0; + /** Without keepCells: the shared-formula masters by si, their reference records, and the masters whose text is pending (setLean). */ + private readonly lean = new Map(); + private leanRecords = 0; + private readonly pending: LeanMaster[] = []; + private pendingHead = 0; + private pendingText = 0; /** Without keepCells: the rows that had properties, one bit per row (for counting each once, as `rowProps` does). */ private rowPropSeen: Uint8Array | undefined; @@ -849,17 +857,18 @@ export class SheetParser implements XmlHandler { private formula(p: PendingCell): { text: string; arrayRef?: string } | undefined { if (p.f === undefined || !this.opts.formulas) return undefined; if (p.fType === "shared" && p.fSi !== undefined) { + if (!this.keep) return this.leanFormula(p); if (p.f !== "") { - this.shared.set(p.fSi, this.keep ? { formula: p.f, length: p.f.length, row: p.row, col: p.col, ref: p.ref, compiled: undefined, fits: undefined } : this.leanMaster(p)); + this.shared.set(p.fSi, { formula: p.f, row: p.row, col: p.col, ref: p.ref, compiled: undefined }); return { text: p.f }; } const master = this.shared.get(p.fSi); // importDataset ("master"): the cell carries the master's text, so no copy is built and the // result is the same as 2.3.0's for every master; only whether it resolves is decided. const masterText = this.opts.sharedFormulaText === "master"; - if (master && !masterText && master.length > MAX_SHARED_FORMULA_LENGTH) { + if (master && !masterText && master.formula.length > MAX_SHARED_FORMULA_LENGTH) { // Longer than Excel allows: not expanded into every cell that shares it (JSE-62). - this.unresolved(p, `: its master formula in cell ${master.ref || `${colLetters(master.col + 1)}${master.row + 1}`} has ${master.length} characters, more than Excel's limit of ${MAX_SHARED_FORMULA_LENGTH}`); + this.unresolved(p, `: its master formula in cell ${master.ref} has ${master.formula.length} characters, more than Excel's limit of ${MAX_SHARED_FORMULA_LENGTH}`); return undefined; } const dRow = master ? p.row - master.row : 0; @@ -874,13 +883,6 @@ export class SheetParser implements XmlHandler { // Each shifted copy is cell text: one longer than maxCellTextLength is not built, and the // cell keeps its cached value, as for an over-long master (the read goes on, as in 2.3.0). const max = this.ctx.limits.maxCellTextLength; - if (master.fits !== undefined || master.lengths) { - // A lean master (keepCells false): decided by the length range, or per copy from its reference records. - const fits = master.lengths ? shiftedLength(master.lengths.fixed, master.lengths.parts, dRow, dCol) <= max : master.fits; - if (fits) return { text: "" }; - this.unresolved(p, `: shifted, it would have more than maxCellTextLength (${max}) characters`); - return undefined; - } const text = shiftCompiled(compiled, dRow, dCol, max); if (typeof text === "number") { this.unresolved(p, `: shifted, it would have ${text} characters, more than maxCellTextLength (${max})`); @@ -895,37 +897,117 @@ export class SheetParser implements XmlHandler { } /** - * keepCells false (JSE-71): a master without its text, so that a sheet of - * many long masters does not hold them all. Kept: the length, the position - * and the relative bounds (canShift); and whether a copy fits - * maxCellTextLength, from the range of lengths a copy can have. When the - * limit falls inside that range, the records each copy's exact length - * depends on (one per distinct relative row or column) are kept instead, - * counted against maxItems together with what the read built besides cells - * (sharedFormulaReferences): so no formula text is held under any limit. + * keepCells false (JSE-71): a shared formula decided as formula() decides + * it, in the same order, from a LeanMaster instead of the master's text. + * Only whether the cell has a formula matters here, so a resolved one + * returns an empty text. + */ + private leanFormula(p: PendingCell): { text: string } | undefined { + const si = p.fSi!; + if (p.f !== "") { + this.setLean(si, p); + return { text: "" }; + } + const m = this.lean.get(si); + if (m && m.length > MAX_SHARED_FORMULA_LENGTH) { + this.unresolved(p, `: its master formula in cell ${colLetters(m.col + 1)}${m.row + 1} has ${m.length} characters, more than Excel's limit of ${MAX_SHARED_FORMULA_LENGTH}`); + return undefined; + } + if (!m) { + this.unresolved(p, ""); + return undefined; + } + const dRow = p.row - m.row; + const dCol = p.col - m.col; + if (dRow === 0 && dCol === 0) return { text: "" }; + if (m.text !== undefined) this.shape(m, p); + if (!canShift(m, dRow, dCol)) { + this.unresolved(p, ""); + return undefined; + } + const max = this.ctx.limits.maxCellTextLength; + if (m.parts ? shiftedLength(m.fixed, m.parts, dRow, dCol) <= max : m.fits) return { text: "" }; + this.unresolved(p, `: shifted, it would have more than maxCellTextLength (${max}) characters`); + return undefined; + } + + /** + * Keeps a master as a LeanMaster. Its text is kept only until a copy needs + * it (as read compiles a master only then), and only while the text pending + * on this sheet is at most PENDING_TEXT characters; past that, the oldest + * pending masters are shaped and their text dropped. Shaping (formula.ts + * formulaShape) keeps numbers only: the bounds, and whether copies fit + * maxCellTextLength from the range of lengths a copy can have, or, when the + * limit falls inside that range, records of the relative parts (partsOf). + * Every live master (one per si: a redefinition replaces it, its pending + * text and its records) and every record counts against maxItems (budget()). */ - private leanMaster(p: PendingCell): SharedMaster { + private setLean(si: string, p: PendingCell): void { const f = p.f!; - // The ref is only for a warning message; a lean master rebuilds it from row and col (masterRef). - const base = { length: f.length, row: p.row, col: p.col, ref: "" }; - // Longer than Excel allows: never expanded, whatever is kept (formula()). - if (f.length > MAX_SHARED_FORMULA_LENGTH) return { ...base, formula: "", compiled: undefined, fits: false }; - const full = compileFormula(f); - const [min, max] = shiftedLengthRange(full); - const limit = this.ctx.limits.maxCellTextLength; - const bounds: CompiledFormula = { source: "", segs: NONE, slots: NO_SLOTS, uniq: NO_REFS, literalLength: 0, rowMin: full.rowMin, rowMax: full.rowMax, colMin: full.colMin, colMax: full.colMax }; - if (min <= limit && max > limit) { - const lengths = lengthParts(full); - this.lengthRecords += lengths.parts.length / 3; - const most = this.ctx.limits.maxItems; - if (this.ctx.items + this.lengthRecords > most) { - throw new LimitError("LIMIT_EXCEEDED", `Sheet "${excerpt(this.sheet.name)}": the shared formulas need more than maxItems (${most}) reference records, with the items the read built besides cells, to check their copies' length against maxCellTextLength.`, { - details: { limit: "maxItems", value: most + 1, max: most, part: this.part, ref: p.ref, sharedFormulaReferences: this.lengthRecords }, - }); + const old = this.lean.get(si); + if (old) this.release(old); + const m = new LeanMaster(p.row, p.col, f.length); + this.lean.set(si, m); + if (f.length <= MAX_SHARED_FORMULA_LENGTH) { + // Long text as UTF-8 bytes (a byte per ASCII character; a parsed string may keep a whole decoded chunk alive); + // a short one as a string, which V8 copies and which costs less than an array. + m.text = f.length > 12 ? UTF8.encode(f) : (" " + f).slice(1); + this.pendingText += m.text.length; + this.pending.push(m); + while (this.pendingText > PENDING_TEXT) { + const next = this.pending[this.pendingHead++]!; + if (next.text !== undefined) this.shape(next, p); + } + if (this.pendingHead === this.pending.length) { + this.pending.length = 0; + this.pendingHead = 0; } - return { ...base, formula: "", compiled: bounds, fits: undefined, lengths }; } - return { ...base, formula: "", compiled: bounds, fits: max <= limit }; + this.budget(p); + } + + /** A master's numbers from its text, which is then dropped (setLean). */ + private shape(m: LeanMaster, p: PendingCell): void { + const bytes = m.text!; + m.text = undefined; + this.pendingText -= bytes.length; + const f = typeof bytes === "string" ? bytes : UTF8_TEXT.decode(bytes); + const limit = this.ctx.limits.maxCellTextLength; + // A copy is at most 7 times as long as its master (a 1-digit relative row becomes 7 digits): below that, no parts are needed. + const shape = formulaShape(f, 7 * f.length > limit); + if (shape.min <= limit && shape.max > limit) { + m.parts = partsOf(shape.keys); + this.leanRecords += m.parts.length / 3; + } + m.rowMin = shape.rowMin; + m.rowMax = shape.rowMax; + m.colMin = shape.colMin; + m.colMax = shape.colMax; + m.fixed = shape.fixed; + m.fits = shape.max <= limit; + if (m.parts) this.budget(p); + } + + /** A replaced master: its pending text and its records no longer count. */ + private release(m: LeanMaster): void { + if (m.text !== undefined) { + this.pendingText -= m.text.length; + m.text = undefined; + } + if (m.parts) this.leanRecords -= m.parts.length / 3; + } + + /** + * inspect's own budget, the one documented exception to "the same error as + * read" (docs/api.md §5.2.1): live masters and reference records, with the + * items the read built besides cells, may not pass maxItems. + */ + private budget(p: PendingCell): void { + const most = this.ctx.limits.maxItems; + if (this.ctx.items + this.lean.size + this.leanRecords <= most) return; + throw new LimitError("LIMIT_EXCEEDED", `Sheet "${excerpt(this.sheet.name)}": its shared formulas need more than maxItems (${most}) masters and reference records, with the items the read built besides cells, to be checked without their text.`, { + details: { limit: "maxItems", value: most + 1, max: most, part: this.part, ref: p.ref, sharedFormulaMasters: this.lean.size, sharedFormulaReferences: this.leanRecords }, + }); } private unresolved(p: PendingCell, why: string): void { diff --git a/packages/javascript-excel/src/internal/read/xml-reader.ts b/packages/javascript-excel/src/internal/read/xml-reader.ts index a06f894..667b2ad 100644 --- a/packages/javascript-excel/src/internal/read/xml-reader.ts +++ b/packages/javascript-excel/src/internal/read/xml-reader.ts @@ -150,9 +150,9 @@ export class XmlTokenizer implements XmlControl { private readonly maxDepth: number, private readonly maxToken: number = DEFAULT_LIMITS.maxXmlTokenLength, /** - * Given each processing instruction before the root element whose target - * is `xml` in any case (the XML declaration, and ` void, ) { @@ -312,7 +312,7 @@ export class XmlTokenizer implements XmlControl { const e = buf.indexOf("?>", i + 2); if (e === -1) return this.unfinished(buf, i, final, "Unterminated processing instruction.", Wait.Delim, "?>", i + 2); this.checkToken(e + 2 - i); - if (this.onDeclaration && !this.rootSeen && /^<\?xml(?![^\s?])/i.test(buf.slice(i, i + 6))) this.onDeclaration(buf.slice(i, e + 2)); + if (this.onDeclaration && /^<\?xml(?:[ \t\r\n?]|$)/i.test(buf.slice(i, i + 6))) this.onDeclaration(buf.slice(i, e + 2)); i = e + 2; continue; } From f0ccbc83b1c840613fe2773628e0f6a230f83b6e Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 13:55:56 +0100 Subject: [PATCH 15/22] JSE-71 review 3: document the master budget, off-heap records, waiting text, strict declarations and binary kinds --- .changeset/inspect.md | 2 +- docs/api.md | 8 ++++---- packages/javascript-excel/README.md | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.changeset/inspect.md b/.changeset/inspect.md index f8c7b6e..20bd597 100644 --- a/.changeset/inspect.md +++ b/.changeset/inspect.md @@ -2,4 +2,4 @@ "javascript-excel": minor --- -New `inspect(input, { limits, signal })` in `javascript-excel/read` checks an `.xlsx`, `.xlsm`, `.xltx` or `.xltm` file part by part without building its cells, for servers and browsers that must accept or refuse an upload without reading it into the model. Under the same limits it refuses every file `read` refuses, with the same error class, code and details (zip and reader limits, encryption, CFB and other formats, `NOT_XLSX`, `XML_DTD_FORBIDDEN`, malformed XML in the parts `read` parses, every sheet to its last row), and it returns `read`'s `UNSUPPORTED_PART` warnings with their `partKinds` (VBA, macro sheets, external links, connections, OLE objects, query tables, …), the format, the worksheets with their cell counts (as `maxCells` counts them) and used ranges, and the counts of parts, inflated bytes, cells and shared strings. It also inflates every part `read` never opens (zip limits and CRC-32 apply) and searches its bytes for ``, which may not be longer than `maxXmlTokenLength` (with any space before it), or it is refused with `LIMIT_EXCEEDED` (`maxXmlTokenLength`) as a token would be. A part that begins with a UTF-32 or UCS-4 byte order mark or `<` pattern, the UTF-7 signature (`+/v`) or `+ADw` (an encoded `<`), or the EBCDIC form of `` in another letter case is checked the same way; XML parsers reject it, since `xml` in any case is a reserved target. This is what the guarantee against other encodings rests on: an XML parser decodes a part as UTF-7, UTF-32, EBCDIC or a code page only because of its byte order mark, its first bytes or its declaration, and those are what is refused. No new error code: such a part is not well-formed package XML, and `read` decodes every part as UTF-8 or UTF-16. These refusals come only after the read has succeeded, so `read`'s own errors come first. +- **Every XML part must be UTF-8 or UTF-16, with a well-formed declaration at the very start or none**, as the package format (ECMA-376 Part 2) and XML 1.0 require, including the parts `read` parses: a part whose content type ends in `xml` or `+xml` or names a VML drawing, whose name ends in `.xml`, `.rels`, `.vml` or `.svg`, or that a relationship of a non-binary kind targets. The binary kinds are `image`, `oleObject`, `package`, `vbaProject`, `vbaProjectSignature`, `vbaProjectSignatureAgile`, `vbaProjectSignatureV3`, `attachedToolbars`, `printerSettings`, `activeXControlBinary`, `thumbnail`, `font`, `media`, `audio`, `video`, `hyperlink`, `attachedTemplate`, `externalLinkPath` and `xlBinaryIndex` (compared without regard to case); every other internal target is an XML part, so a drawing relationship to `d.png` makes `d.png` one. A relationship without an `Id` (or `Type`) does not class its target as XML; the package scan reports its relationships part as `invalidPartName` (§5.2). The start of each XML part is read however the inflater splits it (the same code for parts `read` parses and parts it does not): its first four bytes, then, decoded as UTF-8 or UTF-16 by its byte order mark or, without one, by ``, which may not be longer than `maxXmlTokenLength` (`LIMIT_EXCEEDED`, `maxXmlTokenLength`, as for any token). Refused with `XML_MALFORMED`: a part that begins with a UTF-32 or UCS-4 byte order mark or `<` pattern, the UTF-7 signature (`+/v`) or `+ADw` (an encoded `<`), or the EBCDIC form of `` in another letter case (XML parsers reject it, since `xml` in any case is a reserved target); and a `` (as some editors export them); and any binary part (image, VBA project, OLE object or embedded file stored without compression, printer settings) whose bytes happen to contain the letters ` w.code) - for CSV uploads, `encoding: 'auto'`, `rejectBinary: true` and `maxInputBytes` on `readCsv` (`limits.maxInputBytes` for `importDataset`, which applies it to CSV only when given); `keepRows: false` to check a file without keeping its rows. With `importDataset`, also pass `format: 'csv'` when only CSV is accepted: with format detection a zip or xlsx input is read as a workbook and does not go through `rejectBinary`. `rejectBinary` means "decodes to text"; it does not judge HTML, script or polyglot content; - `formulas: false` on `read` when the formula text is not needed: cells that share a formula then cost no more than other cells (`importDataset` already reads them so); - `maxEntryBytes` 64 MiB and `maxTotalBytes` 128 MiB; -- to accept or refuse an upload without reading it into the model, `inspect` with the same limits (§5.2.1), including `maxItems`, which bounds the styles and defined names it holds and the shared-formula reference records it keeps when `maxCellTextLength` is small; +- to accept or refuse an upload without reading it into the model, `inspect` with the same limits (§5.2.1), including `maxItems` (for example 100,000), which bounds the styles and defined names it holds and the shared-formula masters and reference records it keeps; the records live outside the JavaScript heap, so a worker's heap cap does not count them and `maxItems` is what bounds them; - run imports of untrusted files in a worker thread with a memory limit (`resourceLimits` in Node) and a wall-clock timeout that terminates it. An `AbortSignal` is consulted between steps, but it cannot interrupt a synchronous step such as the conversion of a read sheet into a dataset. Writer-side hygiene: all text and attributes are XML-escaped, and invalid XML characters are encoded (§3.4). A string that starts with `=` is text, never a formula. Sheet names and defined names are validated, and sheet names are quoted correctly in generated references (`'It''s'!A1`). diff --git a/packages/javascript-excel/README.md b/packages/javascript-excel/README.md index f04d79f..9a999f8 100644 --- a/packages/javascript-excel/README.md +++ b/packages/javascript-excel/README.md @@ -93,7 +93,7 @@ console.log(cell?.type, cell?.value, cell?.rawText); // "number" 50.3 "50.30" Damage the reader can recover from comes back as `warnings`. `isDataLossWarning(w)` tells the ones where data was lost (a cell skipped, rows cut, a part missing, comments or charts not read; `partKind` names the part, including ActiveX controls, embedded files, customUI, web add-ins and parts no relationship reaches, wherever they sit in the package) from informational ones; the warning cap (`limits.maxWarnings`, default 1,000) drops only informational warnings, so filtering `warnings` with it is enough to refuse a damaged file. -To accept or refuse an upload without reading it into the model, `inspect(file, { limits, signal })` checks it part by part without building cells: it refuses every file `read` refuses under the same limits, with the same error, and returns the format, the worksheets with their cell counts, and the part kinds `read` reports (`partKinds`: VBA, external links, OLE objects, …). It also inflates the parts `read` never opens, searches the bytes of every one of them for ` Date: Wed, 2 Dec 2026 14:35:33 +0100 Subject: [PATCH 16/22] JSE-71 review 4: tests that a redefined si keeps nothing A master redefined before every copy (records each time) under relative bounds on heap and external memory, and 300,000 redefinitions of one si with a short master against as many ordinary formulas. --- .../test/read/inspect.test.ts | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/packages/javascript-excel/test/read/inspect.test.ts b/packages/javascript-excel/test/read/inspect.test.ts index 61f9c45..0d24663 100644 --- a/packages/javascript-excel/test/read/inspect.test.ts +++ b/packages/javascript-excel/test/read/inspect.test.ts @@ -466,6 +466,75 @@ describe("inspect: shared-formula masters (review F1)", () => { await expect(inspect(bytes, { limits })).resolves.toMatchObject({ format: "xlsx" }); }); + /** Peak heap and peak memory outside it (external, array buffers) above the start while `fn` runs. */ + async function peaksOf(fn: () => Promise): Promise<{ heap: number; external: number }> { + const gc = await exposeGc(); + gc(); + const before = process.memoryUsage(); + let heap = before.heapUsed; + let external = before.external + before.arrayBuffers; + const sample = (): void => { + const m = process.memoryUsage(); + if (m.heapUsed > heap) heap = m.heapUsed; + if (m.external + m.arrayBuffers > external) external = m.external + m.arrayBuffers; + }; + const timer = setInterval(sample, 1); + try { + await fn(); + } finally { + clearInterval(timer); + } + sample(); + return { heap: heap - before.heapUsed, external: external - before.external - before.arrayBuffers }; + } + + /** `rows` rows of a master in B (si 0, redefined on every row unless `once`) and a copy of it in C. */ + function redefined(rows: number, formula: string, once = false): Promise { + const out: string[] = []; + for (let r = 1; r <= rows; r++) { + const master = !once || r === 1 ? `${formula}` : ""; + out.push(`${master}`); + } + const p = richParts({ rows: 1 }); + p.set("xl/worksheets/sheet2.xml", `${out.join("")}`); + return zipParts(p); + } + + it("review 4: a master redefined on every row, each followed by a copy, keeps nothing per redefinition (heap and external memory)", async () => { + const formula = Array.from({ length: 200 }, (_, k) => `A${k + 1}`).join("+"); + const limits = { maxCellTextLength: 1000, maxItems: 100_000 }; + const many = await redefined(50_000, formula); + const one = await redefined(50_000, formula, true); + await expect(read(many, { limits })).resolves.toBeDefined(); + const base = await peaksOf(() => inspect(one, { limits })); + const storm = await peaksOf(() => inspect(many, { limits })); + console.log(`inspect, 50,000 copies: one master heap ${(base.heap / 1e6).toFixed(0)} MB external ${(base.external / 1e6).toFixed(0)} MB; redefined before each copy heap ${(storm.heap / 1e6).toFixed(0)} MB external ${(storm.external / 1e6).toFixed(0)} MB`); + // Nothing is kept per redefinition; what remains is records of replaced masters awaiting collection, + // 15 to 17 MB at 25,000 or 100,000 rows alike (Node 26). Before the fix: 256 MB external at 50,000 rows. + expect(storm.heap).toBeLessThan(base.heap + 24e6); + expect(storm.external).toBeLessThan(base.external + 24e6); + }, 180_000); + + it("review 4: 300,000 redefinitions of one si with a short master cost what 300,000 ordinary formulas cost", async () => { + const rows: string[] = []; + const plain: string[] = []; + for (let r = 1; r <= 300_000; r++) { + rows.push(`A1`); + plain.push(`A1`); + } + const file = (body: string[]) => { + const p = richParts({ rows: 1 }); + p.set("xl/worksheets/sheet2.xml", `${body.join("")}`); + return zipParts(p); + }; + const storm = await file(rows); + const ordinary = await file(plain); + const base = await peaksOf(() => inspect(ordinary)); + const many = await peaksOf(() => inspect(storm)); + console.log(`inspect, 300,000 formulas: ordinary heap ${(base.heap / 1e6).toFixed(0)} MB; one si redefined heap ${(many.heap / 1e6).toFixed(0)} MB`); + expect(many.heap).toBeLessThan(base.heap + 16e6); + }, 180_000); + it("whether a shared copy resolves (and so whether a value-less cell counts) is decided as read decides it, for every maxCellTextLength", async () => { // A master in C3 shared down and across; copies near the sheet's edges grow longer (XFD1048576 vs A1). const master = Array.from({ length: 40 }, (_, k) => `A${k + 1}`).join("+"); From b9e4bfd8b53e192209f529a6ef0e8080209c603c Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 14:35:33 +0100 Subject: [PATCH 17/22] JSE-71 review 4: drop a replaced master; move test-only length helpers into the tests release() drops the master's records, and the waiting queue is compacted once masters that no longer wait outnumber those that do, so a replaced master is unreachable. partsOf sorts in a reused buffer. lengthParts and shiftedLengthRange, used only as oracles, move to shift-formula.test.ts. --- .../src/internal/read/formula.ts | 114 +++--------------- .../src/internal/read/sheet.ts | 28 ++++- .../test/read/shift-formula.test.ts | 67 +++++++++- 3 files changed, 103 insertions(+), 106 deletions(-) diff --git a/packages/javascript-excel/src/internal/read/formula.ts b/packages/javascript-excel/src/internal/read/formula.ts index 9cfe05b..e871394 100644 --- a/packages/javascript-excel/src/internal/read/formula.ts +++ b/packages/javascript-excel/src/internal/read/formula.ts @@ -250,99 +250,7 @@ export function shiftCompiled(c: CompiledFormula, dRow: number, dCol: number, ma return out; } -/** - * The shortest and longest text `c` can have when shifted by any offset that - * `canShift` allows: a relative column takes 1 to 3 letters, a relative row 1 - * to 7 digits. So a copy's length is known to fit maxCellTextLength (or not) - * without the formula's text whenever the limit is outside this range (JSE-71). - */ -export function shiftedLengthRange(c: CompiledFormula): [number, number] { - let min = c.literalLength; - let max = c.literalLength; - const col = (anchor: string, v: number): void => { - if (anchor === "$") { - const n = letters(v).length + 1; - min += n; - max += n; - } else { - min += 1; - max += 3; - } - }; - const row = (anchor: string, v: number): void => { - if (anchor === "$") { - const n = String(v).length + 1; - min += n; - max += n; - } else { - min += 1; - max += 7; - } - }; - for (const u of c.slots) { - const r = c.uniq[u]!; - if (r.kind === COLS_REF) { - col(r.aAnchor, r.a); - col(r.bAnchor, r.b); - min += 1; - max += 1; - } else if (r.kind === ROWS_REF) { - row(r.aAnchor, r.a); - row(r.bAnchor, r.b); - min += 1; - max += 1; - } else { - col(r.aAnchor, r.a); - row(r.bAnchor, r.b); - } - } - return [min, max]; -} - -/** - * What the exact length of every shifted copy of `c` depends on, without its - * text (JSE-71): the characters that never change (`fixed`: the literal text, - * `$` anchors, `:` and anchored parts) and, for each distinct relative part, - * whether it is a row, its value and how many times the copy holds it, as - * triples in `parts`. `shiftedLength` gives the same length as - * `shiftCompiled`, for any offset `canShift` allows. - */ -export function lengthParts(c: CompiledFormula): { fixed: number; parts: Int32Array } { - let fixed = c.literalLength; - const counts = new Map(); // (value << 1 | isRow) -> count - const part = (anchor: string, v: number, isRow: boolean): void => { - if (anchor === "$") fixed += 1 + (isRow ? String(v).length : letters(v).length); - else { - const key = v * 2 + (isRow ? 1 : 0); - counts.set(key, (counts.get(key) ?? 0) + 1); - } - }; - for (const u of c.slots) { - const r = c.uniq[u]!; - if (r.kind === COLS_REF) { - part(r.aAnchor, r.a, false); - part(r.bAnchor, r.b, false); - fixed += 1; - } else if (r.kind === ROWS_REF) { - part(r.aAnchor, r.a, true); - part(r.bAnchor, r.b, true); - fixed += 1; - } else { - part(r.aAnchor, r.a, false); - part(r.bAnchor, r.b, true); - } - } - const parts = new Int32Array(counts.size * 3); - let i = 0; - for (const [key, n] of counts) { - parts[i++] = key & 1; - parts[i++] = Math.floor(key / 2); - parts[i++] = n; - } - return { fixed, parts }; -} - -/** The length of a copy shifted by (dRow, dCol), from `lengthParts`; the offset must pass `canShift`. */ +/** The length of a copy shifted by (dRow, dCol), from formulaShape's `fixed` and partsOf's records; the offset must pass `canShift`. */ export function shiftedLength(fixed: number, parts: Int32Array, dRow: number, dCol: number): number { let n = fixed; for (let i = 0; i < parts.length; i += 3) { @@ -367,10 +275,10 @@ export interface FormulaShape { rowMax: number; colMin: number; colMax: number; - /** The shortest and longest text a shifted copy can have (shiftedLengthRange). */ + /** The shortest and longest text a shifted copy can have: a relative column takes 1 to 3 letters, a relative row 1 to 7 digits. */ min: number; max: number; - /** The copy's characters that never change; with `parts` (lengthParts), its exact length per offset. */ + /** The copy's characters that never change; with partsOf(keys), its exact length per offset (shiftedLength). */ fixed: number; /** Relative parts as keys (value * 2 + isRow), with collectParts; else empty. */ keys: number[]; @@ -378,9 +286,9 @@ export interface FormulaShape { /** * One pass over a master's text (JSE-71), allocating nothing per reference: - * the relative bounds, the range of a copy's length and the characters that - * never change, as compileFormula, shiftedLengthRange and lengthParts give - * them; with `collectParts`, the relative parts too. It walks the text as + * the relative bounds as compileFormula gives them, the range of a copy's + * length and the characters that never change (the tests compute both from + * the compiled formula too); with `collectParts`, the relative parts. It walks the text as * compileFormula does and recognises references as parseRef does (the tests * compare the two on seeded formulas), so a copy's text is the original's * with each reference re-printed as refText prints it. @@ -523,9 +431,15 @@ function setRef(kind: number, aAnchored: boolean, a: number, bAnchored: boolean, return end; } -/** formulaShape's keys as lengthParts' triples (isRow, value, count). */ +/** formulaShape's keys as records: triples (isRow, value, count), one per distinct relative part. */ +/** partsOf's sort buffer, reused so that sorting allocates nothing. */ +let sortScratch = new Int32Array(256); + export function partsOf(list: number[]): Int32Array { - const keys = Int32Array.from(list).sort(); + if (sortScratch.length < list.length) sortScratch = new Int32Array(Math.max(list.length, 2 * sortScratch.length)); + const keys = sortScratch.subarray(0, list.length); + keys.set(list); + keys.sort(); let distinct = 0; for (let i = 0; i < keys.length; i++) if (i === 0 || keys[i] !== keys[i - 1]) distinct++; const out = new Int32Array(distinct * 3); diff --git a/packages/javascript-excel/src/internal/read/sheet.ts b/packages/javascript-excel/src/internal/read/sheet.ts index 0a4be92..63d6e88 100644 --- a/packages/javascript-excel/src/internal/read/sheet.ts +++ b/packages/javascript-excel/src/internal/read/sheet.ts @@ -253,8 +253,10 @@ export class SheetParser implements XmlHandler { /** Without keepCells: the shared-formula masters by si, their reference records, and the masters whose text is pending (setLean). */ private readonly lean = new Map(); private leanRecords = 0; - private readonly pending: LeanMaster[] = []; + private pending: LeanMaster[] = []; private pendingHead = 0; + /** Masters in `pending` that still wait (have text); the others are dropped by compactPending. */ + private pendingLive = 0; private pendingText = 0; /** Without keepCells: the rows that had properties, one bit per row (for counting each once, as `rowProps` does). */ private rowPropSeen: Uint8Array | undefined; @@ -954,14 +956,12 @@ export class SheetParser implements XmlHandler { m.text = f.length > 12 ? UTF8.encode(f) : (" " + f).slice(1); this.pendingText += m.text.length; this.pending.push(m); + this.pendingLive++; while (this.pendingText > PENDING_TEXT) { const next = this.pending[this.pendingHead++]!; if (next.text !== undefined) this.shape(next, p); } - if (this.pendingHead === this.pending.length) { - this.pending.length = 0; - this.pendingHead = 0; - } + this.compactPending(); } this.budget(p); } @@ -971,6 +971,7 @@ export class SheetParser implements XmlHandler { const bytes = m.text!; m.text = undefined; this.pendingText -= bytes.length; + this.pendingLive--; const f = typeof bytes === "string" ? bytes : UTF8_TEXT.decode(bytes); const limit = this.ctx.limits.maxCellTextLength; // A copy is at most 7 times as long as its master (a 1-digit relative row becomes 7 digits): below that, no parts are needed. @@ -992,9 +993,26 @@ export class SheetParser implements XmlHandler { private release(m: LeanMaster): void { if (m.text !== undefined) { this.pendingText -= m.text.length; + this.pendingLive--; m.text = undefined; } if (m.parts) this.leanRecords -= m.parts.length / 3; + m.parts = undefined; + } + + /** + * Drops the masters that no longer wait (shaped, or replaced by a + * redefinition) from `pending` once they outnumber the waiting ones, so a + * replaced master is unreachable and nothing is kept per redefinition. + * Amortised constant time per master. + */ + private compactPending(): void { + const queued = this.pending.length - this.pendingHead; + if (queued <= 2 * this.pendingLive + 64) return; + const live: LeanMaster[] = []; + for (let i = this.pendingHead; i < this.pending.length; i++) if (this.pending[i]!.text !== undefined) live.push(this.pending[i]!); + this.pending = live; + this.pendingHead = 0; } /** diff --git a/packages/javascript-excel/test/read/shift-formula.test.ts b/packages/javascript-excel/test/read/shift-formula.test.ts index 709579c..49b8b7c 100644 --- a/packages/javascript-excel/test/read/shift-formula.test.ts +++ b/packages/javascript-excel/test/read/shift-formula.test.ts @@ -1,7 +1,7 @@ // JSE-62: the compiled shifter gives exactly what the 2.3.0 shifter gave, for // every formula and offset, while each copy costs its own length once. import { describe, expect, it } from "vitest"; -import { canShift, colLetters, colNumber, compileFormula, formulaShape, lengthParts, partsOf, shiftCompiled, shiftedLength, shiftedLengthRange, shiftFormula, shiftWork } from "../../src/internal/read/formula"; +import { canShift, colLetters, colNumber, compileFormula, formulaShape, partsOf, shiftCompiled, shiftedLength, shiftFormula, shiftWork, type CompiledFormula } from "../../src/internal/read/formula"; const MAX_ROW = 1_048_576; const MAX_COL = 16_384; @@ -266,3 +266,68 @@ describe("lengthParts, formulaShape / shiftedLength (JSE-71): a copy's exact len } }); }); + +// Oracles for formulaShape, from the compiled formula (the references shiftCompiled re-prints). +// A relative column takes 1 to 3 letters, a relative row 1 to 7 digits; anchored parts and ':' never change. +type Part = (anchor: string, v: number, isRow: boolean) => void; +function walkRefs(c: CompiledFormula, part: Part, colon: () => void): void { + for (const u of c.slots) { + const r = c.uniq[u]!; + if (r.kind === 0) { + part(r.aAnchor, r.a, false); + part(r.bAnchor, r.b, false); + colon(); + } else if (r.kind === 1) { + part(r.aAnchor, r.a, true); + part(r.bAnchor, r.b, true); + colon(); + } else { + part(r.aAnchor, r.a, false); + part(r.bAnchor, r.b, true); + } + } +} + +function shiftedLengthRange(c: CompiledFormula): [number, number] { + let min = c.literalLength; + let max = c.literalLength; + walkRefs( + c, + (anchor, v, isRow) => { + if (anchor === "$") { + const n = (isRow ? String(v) : colLetters(v)).length + 1; + min += n; + max += n; + } else { + min += 1; + max += isRow ? 7 : 3; + } + }, + () => { + min += 1; + max += 1; + }, + ); + return [min, max]; +} + +function lengthParts(c: CompiledFormula): { fixed: number; parts: Int32Array } { + let fixed = c.literalLength; + const counts = new Map(); + walkRefs( + c, + (anchor, v, isRow) => { + if (anchor === "$") fixed += 1 + (isRow ? String(v) : colLetters(v)).length; + else counts.set(v * 2 + (isRow ? 1 : 0), (counts.get(v * 2 + (isRow ? 1 : 0)) ?? 0) + 1); + }, + () => fixed++, + ); + const parts = new Int32Array(counts.size * 3); + let i = 0; + for (const [key, n] of counts) { + parts[i++] = key & 1; + parts[i++] = Math.floor(key / 2); + parts[i++] = n; + } + return { fixed, parts }; +} From a5f4e14e9920886656c48a1bd22b287788c52008 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 14:35:33 +0100 Subject: [PATCH 18/22] JSE-71 review 4: docs for `, which may not be longer than `maxXmlTokenLength` (`LIMIT_EXCEEDED`, `maxXmlTokenLength`, as for any token). Refused with `XML_MALFORMED`: a part that begins with a UTF-32 or UCS-4 byte order mark or `<` pattern, the UTF-7 signature (`+/v`) or `+ADw` (an encoded `<`), or the EBCDIC form of `` in another letter case (XML parsers reject it, since `xml` in any case is a reserved target); and a `` (as some editors export them); and any binary part (image, VBA project, OLE object or embedded file stored without compression, printer settings) whose bytes happen to contain the letters `…]]>` in `customXml/item1.xml`, is refused with `XML_MALFORMED` as a declaration not at the start (the same text in a part `read` parses is accepted, since its tokenizer sees it as character data); an SVG image that carries `` (as some editors export them); and any binary part (image, VBA project, OLE object or embedded file stored without compression, printer settings) whose bytes happen to contain the letters ` Date: Wed, 2 Dec 2026 14:49:45 +0100 Subject: [PATCH 19/22] JSE-71 review 4: measure reachable memory in the redefinition test Garbage awaiting collection differs by Node version (CI's Node 24 kept 26 MB of freed records external); the test now samples after a full collection, so it measures what inspect still reaches: 241 MB external without the fix, 2 to 4 MB with it. --- .../test/read/inspect.test.ts | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/packages/javascript-excel/test/read/inspect.test.ts b/packages/javascript-excel/test/read/inspect.test.ts index 0d24663..f881c17 100644 --- a/packages/javascript-excel/test/read/inspect.test.ts +++ b/packages/javascript-excel/test/read/inspect.test.ts @@ -466,19 +466,24 @@ describe("inspect: shared-formula masters (review F1)", () => { await expect(inspect(bytes, { limits })).resolves.toMatchObject({ format: "xlsx" }); }); - /** Peak heap and peak memory outside it (external, array buffers) above the start while `fn` runs. */ - async function peaksOf(fn: () => Promise): Promise<{ heap: number; external: number }> { + /** + * Peak heap and peak memory outside it (external, array buffers) above the start while `fn` runs. With + * `retained`, a full collection runs before every sample (every 20 ms), so only what is still reachable + * counts, not garbage the collector has yet to free (how much of that waits differs by Node version). + */ + async function peaksOf(fn: () => Promise, retained = false): Promise<{ heap: number; external: number }> { const gc = await exposeGc(); gc(); const before = process.memoryUsage(); let heap = before.heapUsed; let external = before.external + before.arrayBuffers; const sample = (): void => { + if (retained) gc(); const m = process.memoryUsage(); if (m.heapUsed > heap) heap = m.heapUsed; if (m.external + m.arrayBuffers > external) external = m.external + m.arrayBuffers; }; - const timer = setInterval(sample, 1); + const timer = setInterval(sample, retained ? 20 : 1); try { await fn(); } finally { @@ -506,13 +511,12 @@ describe("inspect: shared-formula masters (review F1)", () => { const many = await redefined(50_000, formula); const one = await redefined(50_000, formula, true); await expect(read(many, { limits })).resolves.toBeDefined(); - const base = await peaksOf(() => inspect(one, { limits })); - const storm = await peaksOf(() => inspect(many, { limits })); - console.log(`inspect, 50,000 copies: one master heap ${(base.heap / 1e6).toFixed(0)} MB external ${(base.external / 1e6).toFixed(0)} MB; redefined before each copy heap ${(storm.heap / 1e6).toFixed(0)} MB external ${(storm.external / 1e6).toFixed(0)} MB`); - // Nothing is kept per redefinition; what remains is records of replaced masters awaiting collection, - // 15 to 17 MB at 25,000 or 100,000 rows alike (Node 26). Before the fix: 256 MB external at 50,000 rows. - expect(storm.heap).toBeLessThan(base.heap + 24e6); - expect(storm.external).toBeLessThan(base.external + 24e6); + const base = await peaksOf(() => inspect(one, { limits }), true); + const storm = await peaksOf(() => inspect(many, { limits }), true); + console.log(`inspect, 50,000 copies (reachable after a collection): one master heap ${(base.heap / 1e6).toFixed(0)} MB external ${(base.external / 1e6).toFixed(0)} MB; redefined before each copy heap ${(storm.heap / 1e6).toFixed(0)} MB external ${(storm.external / 1e6).toFixed(0)} MB`); + // Reachable memory, sampled after a full collection. Before the fix: about 250 MB external at 50,000 rows. + expect(storm.heap).toBeLessThan(base.heap + 16e6); + expect(storm.external).toBeLessThan(base.external + 16e6); }, 180_000); it("review 4: 300,000 redefinitions of one si with a short master cost what 300,000 ordinary formulas cost", async () => { From dcc888acb5bea852351db1c321e74dafca383f1e Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 14:53:39 +0100 Subject: [PATCH 20/22] JSE-71: time ratio test takes the best of five runs A shared CI runner measured inspect at 109 ms against read's 62 for work that is the same under the pending-text budget; best of five, and a 2x bound under the budget. --- packages/javascript-excel/test/read/inspect.test.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/packages/javascript-excel/test/read/inspect.test.ts b/packages/javascript-excel/test/read/inspect.test.ts index f881c17..e218d75 100644 --- a/packages/javascript-excel/test/read/inspect.test.ts +++ b/packages/javascript-excel/test/read/inspect.test.ts @@ -437,15 +437,20 @@ describe("inspect: shared-formula masters (review F1)", () => { }; // 6,000 x 998 characters stay under the pending-text budget; 30,000 x 998 go past it. for (const [n, bound] of [ - [6_000, 1.6], + [6_000, 2], [30_000, 6], ] as const) { const file = await masters(n, 998); await read(file); // warm up for (const limits of [undefined, { maxCellTextLength: 1000 }]) { const o = limits ? { limits } : {}; - const r = Math.min(await time(() => read(file, o)), await time(() => read(file, o)), await time(() => read(file, o))); - const i = Math.min(await time(() => inspect(file, o)), await time(() => inspect(file, o)), await time(() => inspect(file, o))); + // Best of five: shared CI runners are noisy (Node 24 once took 109 ms against read's 62 for the same work). + let r = Infinity; + let i = Infinity; + for (let k = 0; k < 5; k++) { + r = Math.min(r, await time(() => read(file, o))); + i = Math.min(i, await time(() => inspect(file, o))); + } console.log(`${n} masters of 998 characters ${JSON.stringify(limits ?? {})}: read ${r.toFixed(0)} ms, inspect ${i.toFixed(0)} ms`); expect(i).toBeLessThan(bound * r); } From 89c96c6e329526500226aafb85ddd005d1874c72 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 15:10:11 +0100 Subject: [PATCH 21/22] JSE-71: reference records as plain arrays on the heap; retention tests measure reachable memory A record set is three numbers per distinct relative part; a typed array per master cost more than its records and sat outside the heap a worker's cap counts. The test that masters keep no text now compares long masters with short ones of the same structure, by reachable memory after a full collection, so garbage the collector has not freed yet (more on Node 24) does not count. --- docs/api.md | 4 ++-- packages/javascript-excel/README.md | 2 +- .../src/internal/read/formula.ts | 9 +++++---- .../javascript-excel/src/internal/read/sheet.ts | 2 +- .../javascript-excel/test/read/inspect.test.ts | 17 +++++++++++------ .../test/read/shift-formula.test.ts | 2 +- 6 files changed, 21 insertions(+), 15 deletions(-) diff --git a/docs/api.md b/docs/api.md index 56d0123..c0609d6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -962,7 +962,7 @@ How it is kept: `inspect` is `read`'s own code path with every check in the same **False positives.** The search does not parse, so it also refuses, though no XML parser would read a DTD from them: a `…]]>` in `customXml/item1.xml`, is refused with `XML_MALFORMED` as a declaration not at the start (the same text in a part `read` parses is accepted, since its tokenizer sees it as character data); an SVG image that carries `` (as some editors export them); and any binary part (image, VBA project, OLE object or embedded file stored without compression, printer settings) whose bytes happen to contain the letters ` w.code) - for CSV uploads, `encoding: 'auto'`, `rejectBinary: true` and `maxInputBytes` on `readCsv` (`limits.maxInputBytes` for `importDataset`, which applies it to CSV only when given); `keepRows: false` to check a file without keeping its rows. With `importDataset`, also pass `format: 'csv'` when only CSV is accepted: with format detection a zip or xlsx input is read as a workbook and does not go through `rejectBinary`. `rejectBinary` means "decodes to text"; it does not judge HTML, script or polyglot content; - `formulas: false` on `read` when the formula text is not needed: cells that share a formula then cost no more than other cells (`importDataset` already reads them so); - `maxEntryBytes` 64 MiB and `maxTotalBytes` 128 MiB; -- to accept or refuse an upload without reading it into the model, `inspect` with the same limits (§5.2.1), including `maxItems` (for example 100,000), which bounds the styles and defined names it holds and the shared-formula masters and reference records it keeps; the records live outside the JavaScript heap, so a worker's heap cap does not count them and `maxItems` is what bounds them; +- to accept or refuse an upload without reading it into the model, `inspect` with the same limits (§5.2.1), including `maxItems` (for example 100,000), which bounds the styles and defined names it holds and the shared-formula masters and reference records it keeps; - run imports of untrusted files in a worker thread with a memory limit (`resourceLimits` in Node) and a wall-clock timeout that terminates it. An `AbortSignal` is consulted between steps, but it cannot interrupt a synchronous step such as the conversion of a read sheet into a dataset. Writer-side hygiene: all text and attributes are XML-escaped, and invalid XML characters are encoded (§3.4). A string that starts with `=` is text, never a formula. Sheet names and defined names are validated, and sheet names are quoted correctly in generated references (`'It''s'!A1`). diff --git a/packages/javascript-excel/README.md b/packages/javascript-excel/README.md index 9a999f8..9fe8ebe 100644 --- a/packages/javascript-excel/README.md +++ b/packages/javascript-excel/README.md @@ -93,7 +93,7 @@ console.log(cell?.type, cell?.value, cell?.rawText); // "number" 50.3 "50.30" Damage the reader can recover from comes back as `warnings`. `isDataLossWarning(w)` tells the ones where data was lost (a cell skipped, rows cut, a part missing, comments or charts not read; `partKind` names the part, including ActiveX controls, embedded files, customUI, web add-ins and parts no relationship reaches, wherever they sit in the package) from informational ones; the warning cap (`limits.maxWarnings`, default 1,000) drops only informational warnings, so filtering `warnings` with it is enough to refuse a damaged file. -To accept or refuse an upload without reading it into the model, `inspect(file, { limits, signal })` checks it part by part without building cells: it refuses every file `read` refuses under the same limits, with the same error, and returns the format, the worksheets with their cell counts, and the part kinds `read` reports (`partKinds`: VBA, external links, OLE objects, …). It also inflates the parts `read` never opens, searches the bytes of every one of them for `, dRow: number, dCol: number): number { let n = fixed; for (let i = 0; i < parts.length; i += 3) { const v = parts[i + 1]! + (parts[i] ? dRow : dCol); @@ -435,14 +435,15 @@ function setRef(kind: number, aAnchored: boolean, a: number, bAnchored: boolean, /** partsOf's sort buffer, reused so that sorting allocates nothing. */ let sortScratch = new Int32Array(256); -export function partsOf(list: number[]): Int32Array { +export function partsOf(list: number[]): number[] { if (sortScratch.length < list.length) sortScratch = new Int32Array(Math.max(list.length, 2 * sortScratch.length)); const keys = sortScratch.subarray(0, list.length); keys.set(list); keys.sort(); let distinct = 0; for (let i = 0; i < keys.length; i++) if (i === 0 || keys[i] !== keys[i - 1]) distinct++; - const out = new Int32Array(distinct * 3); + // A plain array: on the JavaScript heap (a worker's heap cap counts it), and smaller than a typed array for a few records. + const out: number[] = new Array(distinct * 3).fill(0); let o = -3; for (let i = 0; i < keys.length; i++) { const k = keys[i]!; @@ -451,7 +452,7 @@ export function partsOf(list: number[]): Int32Array { out[o] = k & 1; out[o + 1] = Math.floor(k / 2); } - out[o + 2]!++; + out[o + 2] = out[o + 2]! + 1; } return out; } diff --git a/packages/javascript-excel/src/internal/read/sheet.ts b/packages/javascript-excel/src/internal/read/sheet.ts index 63d6e88..84c49c1 100644 --- a/packages/javascript-excel/src/internal/read/sheet.ts +++ b/packages/javascript-excel/src/internal/read/sheet.ts @@ -122,7 +122,7 @@ class LeanMaster { /** Whether every copy fits maxCellTextLength; `parts`, when set, decides per copy instead. */ fits = false; fixed = 0; - parts: Int32Array | undefined = undefined; + parts: number[] | undefined = undefined; /** The master's text, as UTF-8, until it is shaped (setLean); then undefined. */ text: Uint8Array | string | undefined = undefined; constructor( diff --git a/packages/javascript-excel/test/read/inspect.test.ts b/packages/javascript-excel/test/read/inspect.test.ts index e218d75..afea078 100644 --- a/packages/javascript-excel/test/read/inspect.test.ts +++ b/packages/javascript-excel/test/read/inspect.test.ts @@ -354,12 +354,17 @@ describe("inspect: shared-formula masters (review F1)", () => { [998, 1000], [600, 605], ] as const) { - const file = await masters(60_000, len); - const base = await peakOf(() => inspect(file)); - const tight = await peakOf(() => inspect(file, { limits: { maxCellTextLength: limit } })); - console.log(`inspect, 60,000 masters of ${len} characters: default limits ${(base / 1e6).toFixed(0)} MB, maxCellTextLength ${limit}: ${(tight / 1e6).toFixed(0)} MB (peak heap)`); - // Holding the text would add about 60,000 x len bytes (36 to 60 MB). - expect(tight).toBeLessThan(base + 24e6); + // Against masters of the same structure but 100 characters, whose copies also straddle their limit (102): + // the same records, so holding the text would show as the difference (60,000 x (len - 100) bytes, 30 to 54 MB). + // Reachable heap and external memory, sampled after a full collection (peaksOf below): what is kept, not garbage. + const longFile = await masters(60_000, len); + const shortFile = await masters(60_000, 100); + const long = await peaksOf(() => inspect(longFile, { limits: { maxCellTextLength: limit } }), true); + const short = await peaksOf(() => inspect(shortFile, { limits: { maxCellTextLength: 102 } }), true); + const kept = long.heap + long.external; + const base = short.heap + short.external; + console.log(`inspect, 60,000 straddling masters (reachable after a collection): 100 characters at 102 ${(base / 1e6).toFixed(0)} MB, ${len} at ${limit} ${(kept / 1e6).toFixed(0)} MB`); + expect(kept).toBeLessThan(base + 12e6); } }, 180_000); diff --git a/packages/javascript-excel/test/read/shift-formula.test.ts b/packages/javascript-excel/test/read/shift-formula.test.ts index 49b8b7c..fbd778b 100644 --- a/packages/javascript-excel/test/read/shift-formula.test.ts +++ b/packages/javascript-excel/test/read/shift-formula.test.ts @@ -258,7 +258,7 @@ describe("lengthParts, formulaShape / shiftedLength (JSE-71): a copy's exact len checked++; } expect(checked).toBeGreaterThan(1_000); - function sortedTriples(parts: Int32Array): string { + function sortedTriples(parts: ArrayLike): string { const t: number[][] = []; for (let k = 0; k < parts.length; k += 3) t.push([parts[k]!, parts[k + 1]!, parts[k + 2]!]); t.sort((x, y) => x[1]! * 2 + x[0]! - (y[1]! * 2 + y[0]!)); From b756805b4c61c4017449c48c7d96ad6f1fd1b9ff Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 15:17:33 +0100 Subject: [PATCH 22/22] name-cost test: best of three aborted reads, like its baselines A single aborted read against best-of-three baselines failed on Node 24 when heavier test files ran beside it (174 ms against 157). --- .../test/read/name-cost.test.ts | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/packages/javascript-excel/test/read/name-cost.test.ts b/packages/javascript-excel/test/read/name-cost.test.ts index 1e7e56b..f8b367c 100644 --- a/packages/javascript-excel/test/read/name-cost.test.ts +++ b/packages/javascript-excel/test/read/name-cost.test.ts @@ -89,15 +89,19 @@ describe("cost of decoding part names", () => { } const whole = await best(bytes); // A signal that reads as aborted from 1 ms after the start: checked inside synchronous steps too. - let start = 0; - const signal = { - get aborted() { - return performance.now() - start > 1; - }, - reason: new Error("stop"), - } as unknown as AbortSignal; - start = performance.now(); - const t = await timed(bytes, signal); + // Best of three, like the times it is compared with (a single run is at the mercy of other test files). + let t = Infinity; + for (let k = 0; k < 3; k++) { + let start = 0; + const signal = { + get aborted() { + return performance.now() - start > 1; + }, + reason: new Error("stop"), + } as unknown as AbortSignal; + start = performance.now(); + t = Math.min(t, await timed(bytes, signal)); + } expect(t).toBeLessThan(zipTime + Math.max(30, (whole - zipTime) / 2)); }, 60_000); });