diff --git a/.changeset/inspect.md b/.changeset/inspect.md new file mode 100644 index 0000000..20bd597 --- /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 (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 `; 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 @@ -913,6 +914,76 @@ 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, and (since 2.5) for every part the package scan visits (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, and the package scan's pass over a relationships part and over the zip's part names (every 4,096 relationships or names), 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 (a cell written twice counts twice) + 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; // as maxCells counts them: each 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. One exception, `inspect`'s own: the shared-formula masters and the reference records it keeps instead of formula text (see What it holds) count against `maxItems`, and past it `inspect` refuses at that point with `LIMIT_EXCEEDED` (`details.limit: 'maxItems'`, `details.part`, `details.ref`, `details.sharedFormulaMasters`, `details.sharedFormulaReferences`), which can come before an error `read` would give later in the file. `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 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 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 ``, 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 `…]]>` 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 ` `${s.name}: ${s.cells} cells`)); +} catch (err) { + 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 +} +``` + ### 5.3 CSV (`javascript-excel/csv`) ```ts @@ -1698,7 +1769,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) | **Hostile relationships parts** | Since 2.5 the scan parses every relationships part in the zip: those of reached parts, also of sheets left out by `sheets` and of nested parts (drawings, tables, …), and those whose owner nothing reaches (orphans, in any percent-encoded spelling of `_rels` or `.rels`). A DTD in any of them throws `XML_DTD_FORBIDDEN`, and one past an XML or zip limit (for example deeper than `maxXmlDepth`) throws `LIMIT_EXCEEDED`, as for any part the reader parses; 2.4.0 never opened those parts and read such a file. Since 2.5, two zip entries with equivalent part names (equal after percent-decoding and case folding) throw `ZIP_INVALID`; 2.4.0 threw only for names that differ in case. A relationships part that is only malformed XML does not throw: it and the parts only it reaches are reported as unreferenced. | | **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, and reported as `'vbaProject'` (or `'unreferencedPart'` when no relationship reaches them). | +| **Checking an upload without reading it** | `inspect` (§5.2.1) refuses every file `read` refuses under the same limits, with the same error (one documented exception there), and returns the part kinds `read` reports (VBA, macro sheets, external links, connections, OLE objects, ActiveX controls, embedded packages, customUI, web extensions, unreferenced parts, invalid part names, …), without building cells. It also inflates every part `read` leaves unopened, searches the bytes of each for ` 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; - 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 07796a2..9fe8ebe 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, 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 ` 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 d175b7f..e72d342 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,16 @@ 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; + /** + * 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) => 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). */ private readonly pause = createYielder(); @@ -76,6 +86,7 @@ export class ReadContext { if (where?.ref !== undefined) w.ref = where.ref; if (where?.partKind !== undefined) w.partKind = where.partKind; if (where?.parts !== undefined) w.parts = where.parts; + 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); @@ -146,10 +157,12 @@ 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 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; try { for await (const chunk of this.zip.stream(entry, this.signal)) { + sniffer?.feed(chunk); let bytes = chunk; if (!decoder) { decoder = newDecoder(chunk); @@ -181,12 +194,20 @@ export class ReadContext { } if (decoder) tok.feed(decoder.decode()); tok.end(); + sniffer?.end(); } catch (err) { throw withPart(err, entry.name); } } } +/** 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; @@ -250,6 +250,213 @@ export function shiftCompiled(c: CompiledFormula, dRow: number, dCol: number, ma return out; } +/** 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: ArrayLike, 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; +} + +/** 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: 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 partsOf(keys), its exact length per offset (shiftedLength). */ + 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 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. + */ +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 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[]): 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++; + // 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]!; + if (i === 0 || k !== keys[i - 1]) { + o += 3; + out[o] = k & 1; + out[o + 1] = Math.floor(k / 2); + } + out[o + 2] = out[o + 2]! + 1; + } + 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; @@ -258,6 +465,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 new file mode 100644 index 0000000..da9c58b --- /dev/null +++ b/packages/javascript-excel/src/internal/read/inspect.ts @@ -0,0 +1,372 @@ +/** + * 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. 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, 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", + "package", + "vbaproject", + "vbaprojectsignature", + "vbaprojectsignatureagile", + "vbaprojectsignaturev3", + "attachedtoolbars", + "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) || type.endsWith("vmldrawing") || /\.(xml|rels|vml|svg)$/i.test(name); +} + +/** + * The encoding a part's first four bytes show when OPC does not allow it + * (ECMA-376 Part 2: UTF-8 or UTF-16), else undefined: a UTF-32 or UCS-4 byte + * order mark or `<`, the EBCDIC bytes of `$/; + +/** 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. */ +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 ${encoding}; XML parts must be UTF-8 or UTF-16.`, { + details: { part, encoding }, + }); +} + +function doctype(): FormatError { + return new FormatError("XML_DTD_FORBIDDEN", "XML parts must not contain a document type declaration ( { + // 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 = { + unsupported: [], + broken: new Set(), + sharedStrings: 0, + sheets: [], + 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) => { + relsDone.add(part); + 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!; + 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(); + if (pause) await pause; + 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); + 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; + * searches its bytes for ` { + let tail = ""; + 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 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); + 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; + } + check?.end(); + if (failure !== undefined) throw failure; + } catch (err) { + throw withPart(err, entry.name); + } +} + +/** + * 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: { decode(input?: Uint8Array, options?: { stream?: boolean }): string } | undefined; + private text = ""; + private searched = 0; + private done = false; + + constructor( + private readonly part: string, + private readonly maxToken: number, + ) {} + + feed(chunk: Uint8Array): FormatError | 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(): FormatError | 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(): FormatError | 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 encodingError(this.part, sig); + } + 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): FormatError | undefined { + this.text += text; + const t = this.text; + // Too short to tell yet: what has come is the start of "", Math.max(0, this.searched - 1)); + if (close === -1) { + this.searched = t.length; + if (!final) return this.bound(); + this.done = true; + return checkDeclaration(this.part, t); + } + this.done = true; + if (close + 2 > this.maxToken) this.bound(true); + return checkDeclaration(this.part, t.slice(0, close + 2)); + } + + /** 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}).`, { + 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 35e6ae0..fb686ba 100644 --- a/packages/javascript-excel/src/internal/read/opc.ts +++ b/packages/javascript-excel/src/internal/read/opc.ts @@ -255,6 +255,7 @@ export class Package { text: () => {}, }); if (malformed.length) this.malformedRels.set(entry.name, malformed); + 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 5513583..385570c 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 { relationshipKindOf, REPORTED_ANYWHERE, SCANNED_KINDS, scanPackageParts, UNSUPPORTED_RELATIONSHIPS } from "./scan"; import { ODS_MIME, OTHER_FORMATS, sniffContainer, WORKBOOK_FORMATS, workbookFormat, type FormatName, type WorkbookFormat } from "./formats"; @@ -237,6 +237,30 @@ 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; + /** From the first part on (ReadContext): a sniffer for every part parsed as XML, and every relationship part parsed. */ + sniff: NonNullable; + relsParsed: NonNullable; + /** 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 { @@ -259,9 +283,23 @@ 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; + ctx.relsParsed = internal.inspect.relsParsed; + } 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); @@ -310,9 +348,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; } } @@ -329,6 +368,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; @@ -342,17 +385,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); @@ -365,7 +410,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)); } await warnScannedParts(pkg, seen); diff --git a/packages/javascript-excel/src/internal/read/sheet.ts b/packages/javascript-excel/src/internal/read/sheet.ts index 52323b6..84c49c1 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, 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"; @@ -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 { @@ -98,6 +104,34 @@ interface PendingCell { inline: string | RichText | undefined; } +/** 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 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: number[] | 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 { ref: string; relId: string | undefined; @@ -212,6 +246,20 @@ 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 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 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; constructor( name: string, @@ -223,6 +271,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 +321,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 +329,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 +341,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 +510,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 +674,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 +698,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 +746,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). @@ -784,6 +859,7 @@ 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, { formula: p.f, row: p.row, col: p.col, ref: p.ref, compiled: undefined }); return { text: p.f }; @@ -822,6 +898,136 @@ export class SheetParser implements XmlHandler { return { text: p.f }; } + /** + * 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 setLean(si: string, p: PendingCell): void { + const f = p.f!; + 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); + this.pendingLive++; + while (this.pendingText > PENDING_TEXT) { + const next = this.pending[this.pendingHead++]!; + if (next.text !== undefined) this.shape(next, p); + } + this.compactPending(); + } + 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; + 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. + 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; + 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; + } + + /** + * 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 { 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, @@ -832,6 +1038,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 +1195,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/internal/read/xml-reader.ts b/packages/javascript-excel/src/internal/read/xml-reader.ts index 983102f..667b2ad 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 whose target is `xml` in any case, + * whole, wherever it is: inspect (JSE-71) allows only the declaration at + * the very start. + */ + private readonly onDeclaration?: (pi: string) => 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 && /^<\?xml(?:[ \t\r\n?]|$)/i.test(buf.slice(i, i + 6))) this.onDeclaration(buf.slice(i, e + 2)); i = e + 2; continue; } diff --git a/packages/javascript-excel/src/read.ts b/packages/javascript-excel/src/read.ts index 8d58ce9..ea69929 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 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; +} + +/** 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, as `maxCells` counts them (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 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 { + return inspectImpl(await toBytes(input, "inspect"), options); +} 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..85e926d --- /dev/null +++ b/packages/javascript-excel/test/read/inspect-check.ts @@ -0,0 +1,77 @@ +// 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(); + // 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)) { + // 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..1792bbd --- /dev/null +++ b/packages/javascript-excel/test/read/inspect-differential.test.ts @@ -0,0 +1,118 @@ +// 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 ")}`); + // 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); + }, 120_000); + + it("the hostile files are refused by inspect under their limits", async () => { + for (const h of hostileFiles()) { + 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); + } + }); + + 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("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(); + 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-encoding.test.ts b/packages/javascript-excel/test/read/inspect-encoding.test.ts new file mode 100644 index 0000000..bcb8942 --- /dev/null +++ b/packages/javascript-excel/test/read/inspect-encoding.test.ts @@ -0,0 +1,287 @@ +// 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"); + }); +}); + +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 not a declaration: refused as malformed (XML parsers reject it as a reserved target)", async () => { + const err = await refusal(withPart(DRAWING, ``)); + 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 () => { + 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 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]*$/); + }); +}); + +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); + }); +}); + +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 new file mode 100644 index 0000000..262ab35 --- /dev/null +++ b/packages/javascript-excel/test/read/inspect-files.ts @@ -0,0 +1,656 @@ +// 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"; + +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); + }, + }); + 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); + }, + }); + // 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); + }, + }); + 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 } }); + 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`); +} + +/** + * 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; +} + +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])); + }], +]; 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..a085bea --- /dev/null +++ b/packages/javascript-excel/test/read/inspect-fuzz.test.ts @@ -0,0 +1,230 @@ +// 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, + "", + "", + "+ADw-!DOCTYPE x+AD4-", + '', + '', + '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..afea078 --- /dev/null +++ b/packages/javascript-excel/test/read/inspect.test.ts @@ -0,0 +1,579 @@ +// 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)`); + // 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 / 2); + expect(i.peak).toBeLessThan(s.peak + 16e6); + }, 60_000); +}); + +describe("inspect: shared-formula masters (review F1)", () => { + /** 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++) { + 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); + } + + /** 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, 6); + const s = await peakOf(() => inspect(short)); + const l = await peakOf(() => inspect(long)); + 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) { + // 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); + + 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(); + }); + + /** 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, 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 } : {}; + // 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); + } + } + }, 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" }); + }); + + /** + * 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, retained ? 20 : 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 }), 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 () => { + 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("+"); + 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 }; + 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; +} 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); }); diff --git a/packages/javascript-excel/test/read/shift-formula.test.ts b/packages/javascript-excel/test/read/shift-formula.test.ts index c2f6f63..fbd778b 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, formulaShape, partsOf, shiftCompiled, shiftedLength, shiftFormula, shiftWork, type CompiledFormula } from "../../src/internal/read/formula"; const MAX_ROW = 1_048_576; const MAX_COL = 16_384; @@ -212,3 +212,122 @@ describe("the compiled shifter equals the 2.3.0 shifter", () => { expect(MAX_ROW).toBe(1_048_576); }); }); + +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; + 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 < 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: 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]!)); + return t.flat().join(); + } + }); +}); + +// 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 }; +}