From 170129d9e6d26c5528fa08a16032008b49adbb53 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 11:15:03 +0100 Subject: [PATCH 1/6] JSE-72: report ActiveX controls, embedded packages, customUI and unreferenced parts read now walks the whole relationship graph of the package after the sheets (scanPackageParts in src/internal/read/scan.ts) and reports, as UNSUPPORTED_PART, four new part kinds: activeX, embeddedPackage, customUI and unreferencedPart. oleObject, vbaProject, externalLink, connections and queryTable are also reported where they sit deeper in the graph (under a drawing or table) or on a sheet left out by the sheets option. Passive kinds keep their previous reporting. The scan reads only relationships parts, each once per read (Package caches them), without marking them consumed, within the zip and XML limits; it never inflates the parts it reports. A malformed nested relationships part is reported as unreferenced instead of failing the read. Office's [trash]/ folder is the only name-based exemption. --- .changeset/package-scan-active-content.md | 5 + docs/api.md | 16 +- packages/javascript-excel/README.md | 2 +- .../javascript-excel/src/internal/read/opc.ts | 39 ++- .../src/internal/read/reader.ts | 55 +-- .../src/internal/read/scan.ts | 166 +++++++++ packages/javascript-excel/src/warnings.ts | 12 +- .../test/read/package-scan.test.ts | 330 ++++++++++++++++++ 8 files changed, 588 insertions(+), 37 deletions(-) create mode 100644 .changeset/package-scan-active-content.md create mode 100644 packages/javascript-excel/src/internal/read/scan.ts create mode 100644 packages/javascript-excel/test/read/package-scan.test.ts diff --git a/.changeset/package-scan-active-content.md b/.changeset/package-scan-active-content.md new file mode 100644 index 0000000..f8fc2fc --- /dev/null +++ b/.changeset/package-scan-active-content.md @@ -0,0 +1,5 @@ +--- +"javascript-excel": minor +--- + +`read` (and `importDataset`, which passes read warnings on) now walks the whole relationship graph of the package and reports more content it does not read as `UNSUPPORTED_PART`, with four new `partKind` values: `'activeX'` (ActiveX controls: a `control` or `activeXControlBinary` relationship, or a part with the ActiveX content type), `'embeddedPackage'` (a `package` relationship, such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a ribbon customisation: the root `ui/extensibility` relationship of Office 2007 or 2010) and `'unreferencedPart'` (one warning for all parts no relationship reaches, such as a `vbaProject.bin` or an executable placed in the zip; Office's `[trash]/` folder is exempt). The scan also finds `'oleObject'`, `'vbaProject'`, `'externalLink'`, `'connections'` and `'queryTable'` where they were not reported before: under a drawing, under a table, or on a sheet left out by the `sheets` option. Drawings, images, comments and the other passive kinds are reported as before. The scan reads only relationships parts, within the existing zip and XML limits, and never inflates the parts it reports; a relationships part that is not well-formed XML is reported as unreferenced instead of failing the read. Existing warnings keep their shape; a `switch` over `ExcelPartKind` needs a `default` branch, as documented. The test corpus (files from LibreOffice and openpyxl, and every file of the conformance corpus this library writes) gives no new warnings. diff --git a/docs/api.md b/docs/api.md index c7055d3..c7f9ec7 100644 --- a/docs/api.md +++ b/docs/api.md @@ -877,6 +877,8 @@ How the reader works, as far as the API is concerned: - **Formats.** Detection is a table: the container signature (CFB, zip), then the content type of the workbook part, each entry naming the decoder that reads it. `.xlsx`, `.xltx`, `.xlsm` and `.xltm` share the SpreadsheetML decoder; for the macro-enabled two, one `UNSUPPORTED_PART` warning says the VBA macros are not read or run. Formats without a decoder in 2.0 throw `UNSUPPORTED_FORMAT` with `details.format`: `'cfb'` (`.xls`, or an encrypted/password-protected `.xlsx`, which is a CFB container), `'xlsb'`, `'ods'`, `'unknown'` (no zip signature). They are a phase boundary, not a design limit: supporting `.xlsb` or `.xls` later is a new decoder plus its table row. A zip without a workbook part is `NOT_XLSX`. A workbook part with a missing or unknown content type is read as SpreadsheetML (`.bin` as `.xlsb`). - **Unread parts are not lost at the zip level.** The reader parses only the parts the model represents, but the archive stays addressable by part name until the read ends, and an internal (not yet public) option returns every unparsed part byte for byte. A later release can use it to carry drawings, comments, VBA or custom XML through a read-modify-write. - Unsupported content (drawings, charts, comments, pivot tables, tables, OLE objects, form controls, VBA, external links, chart sheets, …) gives one `UNSUPPORTED_PART` warning per kind. Chart, dialog and macro sheets are not worksheets: they are left out of `sheets` and `readSheetNames`, and defined names local to them are dropped. +- **The package scan** (since 2.5). After the sheets, the reader walks the whole relationship graph, from the package root through the workbook and every sheet (also sheets left out by `sheets`) to every part those reach (drawings, VML drawings, tables, ActiveX parts, …). It reads only relationships parts, each once, within the zip and XML limits, and never inflates the parts it finds. It reports, once per kind, the kinds that are active or embedded content or a link out of the file, wherever they sit: `'activeX'` (a `control` or `activeXControlBinary` relationship, or a part with the content type `application/vnd.ms-office.activeX…`), `'embeddedPackage'` (a `package` relationship, a file such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a root `…/relationships/ui/extensibility` relationship, 2006 and 2007 namespaces: a ribbon customisation, `customUI/customUI.xml` or `customUI14.xml`), and `'oleObject'`, `'vbaProject'`, `'externalLink'`, `'connections'` and `'queryTable'` where the workbook's and the read sheets' own relationships did not already report them (an OLE object referenced from a drawing, a query table under a table, an ActiveX control on a sheet not read). Drawings, images, comments, tables, pivots and the other passive kinds are reported as before, from the workbook's and the read sheets' own relationships only, so an image inside a drawing still gives just `'drawing'`. +- **Unreferenced parts** (since 2.5). A part no relationship reaches (a `vbaProject.bin` without a relationship, an executable dropped into the zip, with or without a content type) gives one `UNSUPPORTED_PART` warning with `partKind: 'unreferencedPart'`, `part` naming the first such part in zip order and the message their number. Parts reached only through an unreferenced part are unreferenced too, and so is a relationships part that is not well-formed XML, together with the parts only it would reach (the read goes on). Not reported: `[Content_Types].xml`, the relationships part of a reached part, and anything under Office's `[trash]/` folder, where Office 2007 and 2010 moved parts it discarded. Nothing else is exempt by name. The thumbnail (`docProps/thumbnail.*`), printer settings (`xl/printerSettings/*.bin`), `xl/calcChain.xml`, custom XML and the document properties are parts with their own relationship types (from the package root, a sheet and the workbook), so in a well-formed package they are reached and never count as unreferenced; an orphaned copy of one does, because an exemption by name would be the place to hide a payload. Evidence: none of the test corpus files (the openpyxl, LibreOffice and import fixtures and every conformance-corpus file this library writes) has an unreferenced part. Files saved by Excel and Numbers are not in the corpus; a part they leave unreferenced would be reported, and is a bug report worth filing. - Styles: each `cellXfs` entry is one frozen `Style` (§12 Q8). Pattern fills come back with `type: 'pattern'`, so `fill.type` tells pattern and gradient fills apart. A style records only what differs from the defaults: font 0 (the workbook default font), fills 0 and 1 (the required `none` and `gray125` placeholders) and border 0 are left out, and `numFmtId` 0 (General) gives no `numFmt`. `applyFont` and the other apply flags are ignored, as Excel does for cell formats. - Values: `t="s"`, `"inlineStr"` and `"str"` are strings (or rich text), with `_xHHHH_` escapes decoded; `"b"` booleans; `"e"` errors, including codes newer than the seven of ECMA-376 (`#SPILL!`, `#CALC!`, …), returned as written; `"d"` ISO dates; numbers otherwise, converted to `Date` when their number format is a date format (§3.4.1). A formula's cached value sets `value` and `type`; without one the cell is `type: 'empty'` with its `formula`. Shared formulas are expanded (§12 Q6), except from a master longer than 8,192 characters and except copies longer than `maxCellTextLength` (§3.4.2); data-table formulas (`t="dataTable"`) give their cached values only. - **`rawText`** (from 2.1.0): converting `` to a JavaScript number loses what the file says: `1234567890123456789` reads as `1234567890123456800`, `50.30` as `50.3`, `1E-7` as `1e-7`, `-0` as `0`, and a `t="d"` cell is always a `Date`. With `rawText: true`, such cells also get `cell.rawText`, the characters of `` exactly as stored: XML entities and character references decoded and line ends normalised (as for any XML text), nothing trimmed, no `_xHHHH_` decoding. `value` and `type` are what they would be without the option, so the cell still says it was a number or a date. Default false: no `rawText` key is added and the model is the same as before 2.1.0. The worker's `read` passes the option through; `importDataset` (§5.6) returns coerced column values, not cells, and does not take it. @@ -907,7 +909,7 @@ How the reader works, as far as the API is concerned: | 1M unique strings | 941 ms | 166 ms (412 ms before the shared strings were decoded lazily) | - Column widths: the file stores characters plus padding (ECMA-376 §18.3.1.13); the reader converts back to the characters Excel's UI shows, the unit `ColumnWidth` uses, so a width of 20 written by the writer reads back as 20. Files from tools that store the UI value directly (openpyxl writes `30` for 30) read as Excel shows them (29.29). - Print setup: the `_xlnm.Print_Area` and `_xlnm.Print_Titles` defined names become `sheet.print.printArea` and `printTitles` and are not repeated in `definedNames`; `_xlnm._FilterDatabase` is implied by `sheet.autoFilter` and dropped. -- **Yielding** (JSE-24). As with the writer (§5.1), a read on the main thread used to be one long task in Chromium: for 100k and 300k rows of 7 columns in Chromium 150 that was about 535 and 1,580 ms with no frame rendered, and no timer, input or abort ran until the read finished. There were two causes. Awaiting the decompressor and the part parsers only runs microtasks. And each zip entry was written to `DecompressionStream` in one piece, which Chromium inflates in batches of up to about 50 ms. Now `read` (and `client.read` inside a worker) returns to the event loop between XML chunks of every streamed part (sheets, shared strings, styles, theme) once about 16 ms have passed, using the writer's mechanism (`setImmediate`, else `MessageChannel`, else `setTimeout(0)`). It also feeds compressed data to the decompressor in 256 KB slices. In `bench/browser/read-yield.bench.test.ts`, no task is over 50 ms, the longest gap between frames is 18 ms, and total time is within noise (+0.4 % to +2.3 %). The model is deep-equal to before on the conformance corpus and the read fixtures under five option sets, and on a 300k-row file. A read inside a worker takes the same time as before. The budget is internal, not an option. `readCsv` already yields between 1M-character chunks and is unchanged (17 ms frame gaps at 300k rows). Since 2.2 (JSE-52) the signal is also consulted while the workbook part is parsed (at least every 256 sheet entries), for every entry of the sheet list and every defined name (these steps also yield on the same budget), and between 256 KB slices of a stored (uncompressed) part, which the zip reader hands over in one piece. `readSheetNames` gets the same checks. Some steps are synchronous and consult the signal without yielding: building the relationship map and the unsupported-part warnings (every 4,096 relationships), attaching a sheet's hyperlinks when it is finished (every 4,096 hyperlinks, bounded by `maxItems`), filling in deferred shared strings with `maxRows` (every 4,096 cells, bounded by `maxCells`) and the CRC-32 of a stored entry before its first byte is used (every 1 MiB, bounded by `maxEntryBytes`). The zip central directory is read in one synchronous step bounded by `maxEntries`, and building a sheet's column objects in one step of at most 16,384 per sheet. So a long-running phase cannot outrun an abort, but at the default limits a single step can still take a few hundred milliseconds on a hostile file (about 0.5 s for 1M hyperlinks or relationships on an Apple-silicon laptop). +- **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.3 CSV (`javascript-excel/csv`) @@ -1719,7 +1721,9 @@ export type ExcelPartKind = // UNSUPPORTED_PART: the relationship kind of the part the model does not represent | 'drawing' | 'vmlDrawing' | 'comments' | 'threadedComment' | 'pivotTable' | 'pivotCacheDefinition' | 'table' | 'oleObject' | 'ctrlProp' | 'image' | 'vbaProject' | 'externalLink' | 'connections' - | 'queryTable' | 'slicer' | 'slicerCache' | 'timeline' | 'chartsheet' | 'dialogsheet' | 'macrosheet'; + | 'queryTable' | 'slicer' | 'slicerCache' | 'timeline' | 'chartsheet' | 'dialogsheet' | 'macrosheet' + // UNSUPPORTED_PART, found by the package scan wherever they sit (since 2.5, §5.2) + | 'activeX' | 'embeddedPackage' | 'customUI' | 'unreferencedPart'; export interface DroppedWarnings { total: number; // warnings not recorded @@ -1738,7 +1742,7 @@ export function isDataLossWarning(warning: ExcelWarning | ExcelWarningCode): boo | Warning code | Data loss | Situation and recovery | |---|---|---| -| `UNSUPPORTED_PART` | yes | Charts, drawings, pivots, comments, VBA, … are outside the model and not in the result; one warning per kind (so it cannot flood the list), `partKind` names it. The cell values are complete; filter by `partKind` to accept the kinds you do not need | +| `UNSUPPORTED_PART` | yes | Charts, drawings, pivots, comments, VBA, … are outside the model and not in the result; one warning per kind (so it cannot flood the list), `partKind` names it. Since 2.5 also ActiveX controls (`'activeX'`), embedded packages (`'embeddedPackage'`), ribbon customisations (`'customUI'`) and parts no relationship reaches (`'unreferencedPart'`, one warning for all of them), found anywhere in the package (§5.2, package scan). The cell values are complete; filter by `partKind` to accept the kinds you do not need | | `INVALID_STYLE_INDEX` | no | Cell refers to a missing `xf`; default style used. Declared for compatibility; 2.x leaves such a cell unstyled without a warning | | `INVALID_SHARED_STRING` | yes | Index out of range; cell left empty | | `CELL_OUT_OF_BOUNDS` / `INVALID_CELL_REF` | yes | Cell skipped | @@ -1770,7 +1774,8 @@ To refuse a file that lost data: import { isDataLossWarning, read } from 'javascript-excel/read'; const { workbook, warnings } = await read(file); -// Accept parts you do not need (here VBA and drawings); refuse every other kind of data loss. +// Accept parts you do not need (here VBA and drawings); refuse every other kind of data loss, +// including ActiveX controls, embedded files, customUI and unreferenced parts (since 2.5). const ignored = new Set(['vbaProject', 'drawing', 'vmlDrawing']); const lost = warnings.filter((w) => isDataLossWarning(w) && !(w.code === 'UNSUPPORTED_PART' && w.partKind && ignored.has(w.partKind))); if (lost.length) throw new Error(`Refused: ${[...new Set(lost.map((w) => w.code))].join(', ')}`); @@ -1798,8 +1803,9 @@ if (lost.length) throw new Error(`Refused: ${[...new Set(lost.map((w) => w.code) | **Formula injection into CSV** | Guard on by default (§5.3). | | **Malicious hyperlinks** | The writer allows only `http`, `https` and `mailto` by default, and rejects `javascript:`, `data:`, `vbscript:` and anything else not listed. The reader returns targets verbatim (it cannot know the consumer's policy): apps that render them, such as the viewer, must check the scheme. | | **External references** | External links, OLE objects, DDE and data connections are not read or followed. The reader resolves relationships only within the package. | +| **Active, embedded and hidden content** (a file that is harmless to this reader but carries something for whoever opens it next in Excel) | Never run, opened or inflated, and reported so an app can refuse the file (since 2.5): the package scan (§5.2) walks the whole relationship graph and reports ActiveX controls (`'activeX'`), embedded files (`'embeddedPackage'`), ribbon customisations with callbacks (`'customUI'`), OLE objects, VBA, external links, data connections and query tables wherever they sit, including under drawings and on sheets not read, and any part no relationship reaches (`'unreferencedPart'`), such as a `vbaProject.bin` or an executable placed in the zip without a relationship. Only Office's `[trash]/` folder is exempt. The scan reads relationships parts only, within the zip and XML limits. To refuse such files, check `warnings` for `UNSUPPORTED_PART` with these `partKind`s. | | **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. | +| **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). | **Server guidance for untrusted uploads.** The defaults are sized for real workbooks in a browser tab. A server that reads files from strangers should tighten them and isolate the work: diff --git a/packages/javascript-excel/README.md b/packages/javascript-excel/README.md index caeb4c5..02b4dd1 100644 --- a/packages/javascript-excel/README.md +++ b/packages/javascript-excel/README.md @@ -91,7 +91,7 @@ const cell = exact.workbook.sheets[0]?.rows[0]?.[0]; console.log(cell?.type, cell?.value, cell?.rawText); // "number" 50.3 "50.30" ``` -Damage the reader can recover from comes back as `warnings`. `isDataLossWarning(w)` tells the ones where data was lost (a cell skipped, rows cut, a part missing, comments or charts not read; `partKind` names the part) from informational ones; the warning cap (`limits.maxWarnings`, default 1,000) drops only informational warnings, so filtering `warnings` with it is enough to refuse a damaged file. +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 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. ## CSV diff --git a/packages/javascript-excel/src/internal/read/opc.ts b/packages/javascript-excel/src/internal/read/opc.ts index 50c5853..a695b01 100644 --- a/packages/javascript-excel/src/internal/read/opc.ts +++ b/packages/javascript-excel/src/internal/read/opc.ts @@ -80,15 +80,46 @@ export class Package { return [...this.overrides.values()]; } - /** Relationships of `source` ('' for the package). Missing rels part: []. */ - async rels(source: string): Promise { + /** The relationships part of `source` ('' for the package), whether or not it exists. */ + relsPartOf(source: string): string { const src = stripSlash(source); const slash = src.lastIndexOf("/"); const dir = slash === -1 ? "" : src.slice(0, slash + 1); const file = slash === -1 ? src : src.slice(slash + 1); - const relsName = `${dir}_rels/${file}.rels`; - const entry = this.part(relsName); + return `${dir}_rels/${file}.rels`; + } + + /** + * Relationships of `source` ('' for the package). Missing rels part: []. + * Each relationships part is parsed once per read and the result shared, so + * callers must not change the array. With `peek`, a part not read before is + * not marked as consumed (InternalReadOptions.retainParts still keeps it). + */ + async rels(source: string, options?: { peek?: boolean }): Promise { + const entry = this.part(this.relsPartOf(source)); if (!entry) return []; + const consumed = this.ctx.consumed; + const cached = this.relsCache.get(entry.name); + if (cached) { + if (!options?.peek) consumed.add(entry.name); + return cached; + } + const wasConsumed = consumed.has(entry.name); + try { + const out = await this.parseRels(entry, source); + this.relsCache.set(entry.name, out); + return out; + } finally { + if (options?.peek && !wasConsumed) consumed.delete(entry.name); + } + } + + private readonly relsCache = new Map(); + + private async parseRels(entry: ZipEntryInfo, source: string): Promise { + const src = stripSlash(source); + const slash = src.lastIndexOf("/"); + const dir = slash === -1 ? "" : src.slice(0, slash + 1); const out: Relationship[] = []; await this.ctx.parse(entry, { open: (name, a: XmlAttrs) => { diff --git a/packages/javascript-excel/src/internal/read/reader.ts b/packages/javascript-excel/src/internal/read/reader.ts index dc6eb7c..25eb79c 100644 --- a/packages/javascript-excel/src/internal/read/reader.ts +++ b/packages/javascript-excel/src/internal/read/reader.ts @@ -12,6 +12,7 @@ import type { ExcelPartKind } from "../../warnings"; import { toBytes } from "../input"; import { openZip } from "../zip/read"; import { ReadContext } from "./context"; +import { REPORTED_ANYWHERE, SCANNED_KINDS, scanPackageParts, UNSUPPORTED_RELATIONSHIPS } from "./scan"; import { ODS_MIME, OTHER_FORMATS, sniffContainer, WORKBOOK_FORMATS, workbookFormat, type FormatName, type WorkbookFormat } from "./formats"; import { DEFAULT_LIMITS } from "./limits"; import { Package, type Relationship } from "./opc"; @@ -22,30 +23,6 @@ import { CustomPropsParser, PropsParser, ThemeParser, WorkbookParser, type Sheet import type { XmlHandler } from "./xml-reader"; -/** Friendly names for parts the model does not represent, keyed by relationship kind. */ -const UNSUPPORTED: ReadonlyMap = new Map([ - ["drawing", "drawings (charts, images, shapes)"], - ["vmlDrawing", "legacy drawings (VML)"], - ["comments", "comments"], - ["threadedComment", "threaded comments"], - ["pivotTable", "pivot tables"], - ["pivotCacheDefinition", "pivot caches"], - ["table", "tables (ListObjects)"], - ["oleObject", "embedded OLE objects"], - ["ctrlProp", "form controls"], - ["image", "images"], - ["vbaProject", "VBA macros"], - ["externalLink", "external links"], - ["connections", "data connections"], - ["queryTable", "query tables"], - ["slicer", "slicers"], - ["slicerCache", "slicer caches"], - ["timeline", "timelines"], - ["chartsheet", "chart sheets"], - ["dialogsheet", "dialog sheets"], - ["macrosheet", "macro sheets"], -]); - function unsupported(format: string, message: string): FormatError { return new FormatError("UNSUPPORTED_FORMAT", message, { details: { format } }); } @@ -201,7 +178,7 @@ export function warnUnsupportedParts(ctx: Pick): Promise { + const ctx = pkg.ctx; + const scan = await scanPackageParts(pkg); + for (const f of scan.found) { + if (!REPORTED_ANYWHERE.has(f.kind) || seen.has(f.kind)) continue; + seen.add(f.kind); + const what = SCANNED_KINDS.get(f.kind) ?? UNSUPPORTED_RELATIONSHIPS.get(f.kind)!; + ctx.warn("UNSUPPORTED_PART", `The workbook contains ${what}, which are not read.`, { part: f.part, partKind: f.kind }); + } + const n = scan.unreferenced.length; + if (n > 0) { + const first = scan.unreferenced[0]!; + const message = + n === 1 + ? `The package contains 1 part that no relationship refers to ("${excerpt(first)}"), which is not read.` + : `The package contains ${n} parts that no relationship refers to (first: "${excerpt(first)}"), which are not read.`; + ctx.warn("UNSUPPORTED_PART", message, { part: first, partKind: "unreferencedPart" }); + } +} + /** Internal options, not part of the public API yet. */ export interface InternalReadOptions { /** @@ -353,6 +356,8 @@ export async function readImpl(input: BinaryInput, options?: ReadOptions, intern doneBytes += part.size; sheets.push(parser.finish(sheetRels)); } + await warnScannedParts(pkg, seen); + // The table counts as read either way, so it's never listed as an unparsed part. if (sstEntry && deferred && deferred.cells.length === 0) ctx.consumed.add(sstEntry.name); if (deferred && deferred.cells.length > 0) { diff --git a/packages/javascript-excel/src/internal/read/scan.ts b/packages/javascript-excel/src/internal/read/scan.ts new file mode 100644 index 0000000..a60e57e --- /dev/null +++ b/packages/javascript-excel/src/internal/read/scan.ts @@ -0,0 +1,166 @@ +/** + * The package scan (JSE-72): walks the whole relationship graph from the + * package root and classifies every part the model does not represent, and + * lists the parts no relationship reaches. Shared by `read` and `inspect`. + * Internal. + */ + +import { FormatError } from "../../errors"; +import type { ExcelPartKind } from "../../warnings"; +import type { Package, Relationship } from "./opc"; +import { ABORT_EVERY } from "./sheet"; + +/** + * Relationship kinds (the type URI's last segment) of parts the model does not + * represent, with the words the UNSUPPORTED_PART message uses for them. + */ +export const UNSUPPORTED_RELATIONSHIPS: ReadonlyMap = new Map([ + ["drawing", "drawings (charts, images, shapes)"], + ["vmlDrawing", "legacy drawings (VML)"], + ["comments", "comments"], + ["threadedComment", "threaded comments"], + ["pivotTable", "pivot tables"], + ["pivotCacheDefinition", "pivot caches"], + ["table", "tables (ListObjects)"], + ["oleObject", "embedded OLE objects"], + ["ctrlProp", "form controls"], + ["image", "images"], + ["vbaProject", "VBA macros"], + ["externalLink", "external links"], + ["connections", "data connections"], + ["queryTable", "query tables"], + ["slicer", "slicers"], + ["slicerCache", "slicer caches"], + ["timeline", "timelines"], + ["chartsheet", "chart sheets"], + ["dialogsheet", "dialog sheets"], + ["macrosheet", "macro sheets"], +]); + +/** Words for the kinds the scan adds (since 2.5). `unreferencedPart` has its own message. */ +export const SCANNED_KINDS: ReadonlyMap = new Map([ + ["activeX", "ActiveX controls"], + ["embeddedPackage", "embedded packages (files such as documents embedded in the workbook)"], + ["customUI", "custom ribbon UI (customUI)"], +]); + +/** + * Kinds `read` reports wherever the scan finds them: on any sheet (also one + * left out by `sheets`) and under any part (a drawing, a table, ...). These are + * active or embedded content and links out of the file. The other kinds + * (drawings, images, comments, tables, pivots, ...) are reported, as before + * 2.5, from the workbook's and the read sheets' own relationships only. + */ +export const REPORTED_ANYWHERE: ReadonlySet = new Set([ + "activeX", + "embeddedPackage", + "customUI", + "oleObject", + "vbaProject", + "externalLink", + "connections", + "queryTable", +]); + +const ACTIVEX_CONTENT_TYPE = "application/vnd.ms-office.activex"; + +/** One part (or external target) of a kind the model does not represent. */ +export interface ScannedPart { + kind: ExcelPartKind; + /** The part, as the relationship names it; for an external target, the part whose relationship it is. */ + part: string; + /** The part whose relationship found it ('' for the package root). */ + source: string; + /** The relationship points outside the package (TargetMode="External"). */ + external: boolean; +} + +export interface PackageScan { + /** + * Every part of a kind the model does not represent, once per kind and part, + * in breadth-first order from the package root (root relationships, then the + * workbook's, then each sheet's in workbook order, then deeper parts). + */ + found: ScannedPart[]; + /** + * Parts no relationship reaches, in zip order. Not listed: `[Content_Types].xml`, + * the relationships part of a reached part, and Office's `[trash]/` folder. + * A relationships part that is not well-formed XML is listed, and the parts + * only it would reach are listed too. + */ + unreferenced: string[]; +} + +/** What a relationship and its target's content type make of a part; undefined for parts the model reads or that need no report. */ +export function partKindOf(rel: Relationship, contentType: string | undefined): ExcelPartKind | undefined { + if (rel.kind === "control" || rel.kind === "activeXControlBinary") return "activeX"; + if (rel.kind === "package") return "embeddedPackage"; + if (rel.kind === "extensibility" && /\/ui\/extensibility$/i.test(rel.type)) return "customUI"; + const kind = rel.kind as ExcelPartKind; + if (UNSUPPORTED_RELATIONSHIPS.has(kind)) return kind; + // A relationship of another kind (or of a kind made up for the purpose) to an ActiveX part. + if (contentType !== undefined && contentType.toLowerCase().startsWith(ACTIVEX_CONTENT_TYPE)) return "activeX"; + return undefined; +} + +/** + * Walks the relationship graph of `pkg` from the package root, breadth first. + * Reads only relationships parts (each at most once per read, through the + * zip and XML limits of `pkg.ctx`, without marking them consumed) and the + * content types already loaded; never inflates the parts it classifies. + * Consults the signal per part and every 4,096 relationships. A relationships + * part that is not well-formed XML is treated as unreferenced instead of + * failing the read; limit and DTD errors are thrown as anywhere else. + */ +export async function scanPackageParts(pkg: Package): Promise { + const ctx = pkg.ctx; + const found: ScannedPart[] = []; + const foundKeys = new Set(); + /** Lower-case names of the parts accounted for. */ + const reached = new Set(["[content_types].xml"]); + const queue: string[] = [""]; + for (let q = 0; q < queue.length; q++) { + const pause = ctx.step(); + if (pause) await pause; + const source = queue[q]!; + let rels: Relationship[]; + try { + rels = await pkg.rels(source, { peek: true }); + } catch (err) { + if (err instanceof FormatError && err.code === "XML_MALFORMED") continue; + throw err; + } + const relsPart = pkg.part(pkg.relsPartOf(source)); + if (relsPart) reached.add(relsPart.name.toLowerCase()); + for (let i = 0; i < rels.length; i++) { + if ((i & ABORT_EVERY) === ABORT_EVERY) ctx.checkAbort(); + const rel = rels[i]!; + const kind = partKindOf(rel, rel.external ? undefined : pkg.contentType(rel.target)); + if (kind) { + const part = rel.external ? source || pkg.relsPartOf(source) : rel.target; + const key = `${kind}\u0000${part.toLowerCase()}`; + if (!foundKeys.has(key)) { + foundKeys.add(key); + found.push({ kind, part, source, external: rel.external }); + } + } + if (rel.external) continue; + const entry = pkg.part(rel.target); + if (!entry) continue; + const name = entry.name.toLowerCase(); + if (reached.has(name)) continue; + reached.add(name); + queue.push(entry.name); + } + } + const unreferenced: string[] = []; + const names = pkg.partNames; + for (let i = 0; i < names.length; i++) { + if ((i & ABORT_EVERY) === ABORT_EVERY) ctx.checkAbort(); + const name = names[i]!; + const lower = name.toLowerCase(); + if (reached.has(lower) || lower.startsWith("[trash]/")) continue; + unreferenced.push(name); + } + return { found, unreferenced }; +} diff --git a/packages/javascript-excel/src/warnings.ts b/packages/javascript-excel/src/warnings.ts index 7cd7b13..7eca9bc 100644 --- a/packages/javascript-excel/src/warnings.ts +++ b/packages/javascript-excel/src/warnings.ts @@ -38,7 +38,10 @@ export type ExcelWarningCode = * The kind of package part a `MISSING_PART`, `BROKEN_OPTIONAL_PART` or * `UNSUPPORTED_PART` warning is about. The names are the last segment of the * OOXML relationship type (`.../relationships/worksheet` is `'worksheet'`), - * in camelCase for the document-property parts. Kinds may be added in a minor + * in camelCase for the document-property parts. The kinds the package scan + * adds are named for what they are: `'activeX'` (ActiveX controls), + * `'embeddedPackage'` (embedded files), `'customUI'` (ribbon customisation) + * and `'unreferencedPart'` (a part no relationship reaches). Kinds may be added in a minor * release, so a `switch` over it needs a `default` branch. */ export type ExcelPartKind = @@ -70,7 +73,12 @@ export type ExcelPartKind = | "timeline" | "chartsheet" | "dialogsheet" - | "macrosheet"; + | "macrosheet" + // found by the package scan, wherever they sit (UNSUPPORTED_PART, since 2.5) + | "activeX" + | "embeddedPackage" + | "customUI" + | "unreferencedPart"; /** What the warning cap left out; on `WARNINGS_TRUNCATED` only. */ export interface DroppedWarnings { diff --git a/packages/javascript-excel/test/read/package-scan.test.ts b/packages/javascript-excel/test/read/package-scan.test.ts new file mode 100644 index 0000000..23fe336 --- /dev/null +++ b/packages/javascript-excel/test/read/package-scan.test.ts @@ -0,0 +1,330 @@ +/// +// JSE-72: ActiveX controls, embedded packages, customUI and parts no +// relationship reaches are reported as UNSUPPORTED_PART, wherever in the +// relationship graph they sit. All packages are generated here. +import { readdirSync, readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; +import { toUint8Array } from "../../src/index"; +import { ReadContext } from "../../src/internal/read/context"; +import { DEFAULT_LIMITS } from "../../src/internal/read/limits"; +import { Package } from "../../src/internal/read/opc"; +import { readImpl } from "../../src/internal/read/reader"; +import { scanPackageParts } from "../../src/internal/read/scan"; +import { openZip } from "../../src/internal/zip/read"; +import { importDataset } from "../../src/import"; +import { read, type ReadOptions } from "../../src/read"; +import type { ExcelWarning } from "../../src/warnings"; +import { ALL } from "../conformance/corpus"; +import { build, type BuildOptions } from "./build"; + +const REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; +const PKG_REL = "http://schemas.openxmlformats.org/package/2006/relationships"; +const CT = "http://schemas.openxmlformats.org/package/2006/content-types"; +const NEW_KINDS = new Set(["activeX", "embeddedPackage", "customUI", "unreferencedPart"]); + +/** A relationships part; `type` is a full URI or a suffix of the officeDocument namespace. */ +function rels(list: Array<[id: string, type: string, target: string, external?: boolean]>): string { + const body = list + .map(([id, type, target, ext]) => ``) + .join(""); + return `${body}`; +} + +/** [Content_Types].xml as build() writes it, plus extra Default and Override entries. */ +function contentTypes(defaults: Record = {}, overrides: Record = {}): string { + const d = Object.entries({ rels: "application/vnd.openxmlformats-package.relationships+xml", xml: "application/xml", ...defaults }) + .map(([ext, t]) => ``) + .join(""); + const o = Object.entries({ "/xl/workbook.xml": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", ...overrides }) + .map(([p, t]) => ``) + .join(""); + return `${d}${o}`; +} + +const CELL = '1'; +const unsupported = (w: ExcelWarning[]) => w.filter((x) => x.code === "UNSUPPORTED_PART").map((x) => [x.partKind, x.part]); +const readOf = async (o: BuildOptions, ro?: ReadOptions) => read(await build(o), ro); + +/** An ActiveX control as Excel stores it: sheet -> control -> activeX1.xml -> activeXControlBinary -> activeX1.bin. */ +const ACTIVEX_PARTS: Record = { + "xl/activeX/activeX1.xml": '', + "xl/activeX/_rels/activeX1.xml.rels": rels([["rId1", "http://schemas.microsoft.com/office/2006/relationships/activeXControlBinary", "activeX1.bin"]]), + "xl/activeX/activeX1.bin": new Uint8Array([0xd0, 0xcf, 0x11, 0xe0, 1, 2, 3]), + "[Content_Types].xml": contentTypes({ bin: "application/vnd.ms-office.activeX" }, { "/xl/activeX/activeX1.xml": "application/vnd.ms-office.activeX+xml" }), +}; + +describe("ActiveX controls (partKind 'activeX')", () => { + it("a control relationship on a sheet", async () => { + const r = await readOf({ sheets: [CELL], sheetRels: { 0: [["rId3", "control", "../activeX/activeX1.xml"]] }, parts: ACTIVEX_PARTS }); + expect(unsupported(r.warnings)).toEqual([["activeX", "xl/activeX/activeX1.xml"]]); + expect(r.warnings[0]!.message).toBe("The workbook contains ActiveX controls, which are not read."); + expect(r.workbook.sheets[0]!.rows[0]![0]!.value).toBe(1); + }); + + it("a control referenced only from a drawing", async () => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rD", "drawing", "../drawings/drawing1.xml"]] }, + parts: { ...ACTIVEX_PARTS, "xl/drawings/drawing1.xml": "", "xl/drawings/_rels/drawing1.xml.rels": rels([["rC", "control", "../activeX/activeX1.xml"]]) }, + }); + expect(unsupported(r.warnings)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["activeX", "xl/activeX/activeX1.xml"]]); + }); + + it("a part with the ActiveX content type, whatever the relationship calls it", async () => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rX", "http://example.com/relationships/custom", "../activeX/activeX1.xml"]] }, + parts: ACTIVEX_PARTS, + }); + expect(unsupported(r.warnings)).toEqual([["activeX", "xl/activeX/activeX1.xml"]]); + }); +}); + +describe("embedded packages (partKind 'embeddedPackage')", () => { + const docx = new Uint8Array([0x50, 0x4b, 3, 4, 1, 2, 3]); + it("a package relationship on a sheet", async () => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rP", "package", "../embeddings/Microsoft_Word_Document.docx"]] }, + parts: { "xl/embeddings/Microsoft_Word_Document.docx": docx }, + }); + expect(unsupported(r.warnings)).toEqual([["embeddedPackage", "xl/embeddings/Microsoft_Word_Document.docx"]]); + expect(r.warnings[0]!.message).toMatch(/^The workbook contains embedded packages/); + }); + + it("a package referenced only from a legacy (VML) drawing", async () => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rV", "vmlDrawing", "../drawings/vmlDrawing1.vml"]] }, + parts: { + "xl/drawings/vmlDrawing1.vml": "", + "xl/drawings/_rels/vmlDrawing1.vml.rels": rels([["rP", "package", "../embeddings/Microsoft_Word_Document.docx"]]), + "xl/embeddings/Microsoft_Word_Document.docx": docx, + }, + }); + expect(unsupported(r.warnings)).toEqual([["vmlDrawing", "xl/drawings/vmlDrawing1.vml"], ["embeddedPackage", "xl/embeddings/Microsoft_Word_Document.docx"]]); + }); +}); + +describe("customUI (partKind 'customUI')", () => { + it.each([ + ["Office 2007", "http://schemas.microsoft.com/office/2006/relationships/ui/extensibility", "customUI/customUI.xml"], + ["Office 2010 and later", "http://schemas.microsoft.com/office/2007/relationships/ui/extensibility", "customUI/customUI14.xml"], + ])("a package relationship to a ribbon customisation (%s)", async (_, type, target) => { + const r = await readOf({ + sheets: [CELL], + parts: { [target]: '' }, + override: { "_rels/.rels": rels([["rId1", "officeDocument", "xl/workbook.xml"], ["rUI", type, target]]) }, + }); + expect(unsupported(r.warnings)).toEqual([["customUI", target]]); + expect(r.warnings[0]!.message).toMatch(/^The workbook contains custom ribbon UI/); + }); +}); + +describe("parts no relationship reaches (partKind 'unreferencedPart')", () => { + it("a vbaProject.bin without a relationship or a content type", async () => { + const r = await readOf({ sheets: [CELL], parts: { "xl/vbaProject.bin": new Uint8Array([0xd0, 0xcf, 0x11, 0xe0]) } }); + expect(r.warnings).toEqual([ + { + code: "UNSUPPORTED_PART", + message: 'The package contains 1 part that no relationship refers to ("xl/vbaProject.bin"), which is not read.', + part: "xl/vbaProject.bin", + partKind: "unreferencedPart", + }, + ]); + }); + + it("one warning for several, naming the first in zip order; with or without a content type", async () => { + const r = await readOf({ + sheets: [CELL], + parts: { "payload.exe": new Uint8Array([0x4d, 0x5a, 0x90, 0]), "xl/media/x.dat": "x" }, + override: { "[Content_Types].xml": contentTypes({ exe: "application/octet-stream" }) }, + }); + expect(unsupported(r.warnings)).toEqual([["unreferencedPart", "payload.exe"]]); + expect(r.warnings[0]!.message).toBe('The package contains 2 parts that no relationship refers to (first: "payload.exe"), which are not read.'); + }); + + it("parts reached only through an unreferenced part are unreferenced too", async () => { + const r = await readOf({ + sheets: [CELL], + parts: { "xl/drawings/drawing9.xml": "", "xl/drawings/_rels/drawing9.xml.rels": rels([["r", "image", "../media/image1.png"]]), "xl/media/image1.png": "png" }, + }); + expect(unsupported(r.warnings)).toEqual([["unreferencedPart", "xl/drawings/drawing9.xml"]]); + expect(r.warnings[0]!.message).toMatch(/^The package contains 3 parts/); + }); + + it("a part under a relationships part that is not well-formed counts as unreferenced; the read goes on", async () => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rD", "drawing", "../drawings/drawing1.xml"]] }, + parts: { "xl/drawings/drawing1.xml": "", "xl/drawings/_rels/drawing1.xml.rels": "", "xl/activeX/activeX1.bin": "x" }, + }); + expect(unsupported(r.warnings)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["unreferencedPart", "xl/drawings/_rels/drawing1.xml.rels"]]); + expect(r.warnings[1]!.message).toMatch(/^The package contains 2 parts/); + }); + + it("Office's [trash] folder, relationships parts of reached parts and [Content_Types].xml are not reported", async () => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rH", "hyperlink", "https://example.com", true]] }, + parts: { "[trash]/0000.dat": new Uint8Array([1, 2, 3]) }, + }); + expect(r.warnings).toEqual([]); + }); + + it("a relationship target that differs only in case or uses ../ still reaches its part", async () => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rD", "drawing", "../Drawings/./Drawing1.XML"]] }, + parts: { "xl/drawings/drawing1.xml": "" }, + }); + expect(unsupported(r.warnings)).toEqual([["drawing", "xl/Drawings/Drawing1.XML"]]); + }); +}); + +describe("existing kinds found deeper in the graph", () => { + it("an OLE object referenced only from a drawing is reported as 'oleObject'", async () => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rD", "drawing", "../drawings/drawing1.xml"]] }, + parts: { + "xl/drawings/drawing1.xml": "", + "xl/drawings/_rels/drawing1.xml.rels": rels([["rO", "oleObject", "../embeddings/oleObject1.bin"]]), + "xl/embeddings/oleObject1.bin": new Uint8Array([0xd0, 0xcf]), + }, + }); + expect(unsupported(r.warnings)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["oleObject", "xl/embeddings/oleObject1.bin"]]); + }); + + it("a query table under a table (as Excel stores it) is reported as 'queryTable'", async () => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rT", "table", "../tables/table1.xml"]] }, + parts: { + "xl/tables/table1.xml": "", + "xl/tables/_rels/table1.xml.rels": rels([["rQ", "queryTable", "../queryTables/queryTable1.xml"]]), + "xl/queryTables/queryTable1.xml": "", + }, + }); + expect(unsupported(r.warnings)).toEqual([["table", "xl/tables/table1.xml"], ["queryTable", "xl/queryTables/queryTable1.xml"]]); + }); + + it("active content on a sheet left out by `sheets` is still reported; passive content there is not, as before", async () => { + const o: BuildOptions = { + sheets: [CELL, CELL], + sheetRels: { 1: [["rD", "drawing", "../drawings/drawing1.xml"], ["rC", "control", "../activeX/activeX1.xml"], ["rO", "oleObject", "../embeddings/oleObject1.bin"]] }, + parts: { ...ACTIVEX_PARTS, "xl/drawings/drawing1.xml": "", "xl/embeddings/oleObject1.bin": "x" }, + }; + expect(unsupported((await readOf(o, { sheets: [0] })).warnings)).toEqual([["activeX", "xl/activeX/activeX1.xml"], ["oleObject", "xl/embeddings/oleObject1.bin"]]); + expect(unsupported((await readOf(o)).warnings)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["oleObject", "xl/embeddings/oleObject1.bin"], ["activeX", "xl/activeX/activeX1.xml"]]); + }); + + it("images under drawings and comments under VML are not reported on their own (unchanged)", async () => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rD", "drawing", "../drawings/drawing1.xml"]] }, + parts: { "xl/drawings/drawing1.xml": "", "xl/drawings/_rels/drawing1.xml.rels": rels([["rI", "image", "../media/image1.png"]]), "xl/media/image1.png": "png" }, + }); + expect(unsupported(r.warnings)).toEqual([["drawing", "xl/drawings/drawing1.xml"]]); + }); + + it("importDataset passes the warnings on like any read warning", async () => { + const bytes = await build({ sheets: ['a1'], parts: { "x.bin": "x" } }); + const seen: string[] = []; + await importDataset(bytes, { onWarning: (w) => seen.push(`${w.code} ${w.partKind}`) }); + expect(seen).toContain("UNSUPPORTED_PART unreferencedPart"); + }); +}); + +describe("limits", () => { + it("never inflates the parts it classifies: a payload over maxEntryBytes is reported, not read", async () => { + const big = new Uint8Array(300_000).fill(7); + const r = await readOf( + { sheets: [CELL], sheetRels: { 0: [["rP", "package", "../embeddings/big.docx"]] }, parts: { "xl/embeddings/big.docx": big, "big-orphan.bin": big } }, + { limits: { maxEntryBytes: 100_000 } }, + ); + expect(unsupported(r.warnings)).toEqual([["embeddedPackage", "xl/embeddings/big.docx"], ["unreferencedPart", "big-orphan.bin"]]); + }); + + it("relationships parts read for the scan count against the zip and XML limits", async () => { + const deep = `${"".repeat(70)}${"".repeat(70)}`; + const bytes = await build({ sheets: [CELL], sheetRels: { 0: [["rD", "drawing", "../drawings/drawing1.xml"]] }, parts: { "xl/drawings/drawing1.xml": "", "xl/drawings/_rels/drawing1.xml.rels": deep } }); + await expect(read(bytes)).rejects.toMatchObject({ code: "LIMIT_EXCEEDED" }); + }); + + it("does not mark the relationships parts it reads as consumed (retainParts keeps them)", async () => { + const drawingRels = rels([["rI", "image", "../media/image1.png"]]); + const r = await readImpl( + await build({ + sheets: [CELL], + sheetRels: { 0: [["rD", "drawing", "../drawings/drawing1.xml"]] }, + parts: { "xl/drawings/drawing1.xml": "", "xl/drawings/_rels/drawing1.xml.rels": drawingRels, "xl/media/image1.png": "png" }, + }), + {}, + { retainParts: true }, + ); + expect([...r.parts!.keys()].sort()).toEqual(["xl/drawings/_rels/drawing1.xml.rels", "xl/drawings/drawing1.xml", "xl/media/image1.png"]); + }); + + it("consults the signal while walking the graph", async () => { + const list: Array<[string, string, string]> = []; + for (let i = 0; i < 10; i++) list.push([`r${i}`, "drawing", `../drawings/drawing${i}.xml`]); + const bytes = await build({ sheets: [CELL], sheetRels: { 0: list } }); + let stop = false; + const signal = { get aborted() { return stop; }, reason: new Error("stop") }; + const ctx = new ReadContext(openZip(bytes), DEFAULT_LIMITS, signal, undefined, undefined); + const pkg = new Package(ctx); + await pkg.loadContentTypes(); + stop = true; + await expect(scanPackageParts(pkg)).rejects.toThrow("stop"); + }); +}); + +describe("scanPackageParts (shared with inspect)", () => { + it("lists every classified part in breadth-first order and the unreferenced parts", async () => { + const bytes = await build({ + sheets: [CELL], + workbookRels: [["rV", "vbaProject", "vbaProject.bin"]], + sheetRels: { 0: [["rD", "drawing", "../drawings/drawing1.xml"], ["rC", "control", "../activeX/activeX1.xml"], ["rL", "oleObject", "file:///c:/x.xls", true]] }, + parts: { ...ACTIVEX_PARTS, "xl/vbaProject.bin": "x", "xl/drawings/drawing1.xml": "", "stray.txt": "x" }, + }); + const ctx = new ReadContext(openZip(bytes), DEFAULT_LIMITS, undefined, undefined, undefined); + const pkg = new Package(ctx); + await pkg.loadContentTypes(); + const scan = await scanPackageParts(pkg); + expect(scan.found).toEqual([ + { kind: "vbaProject", part: "xl/vbaProject.bin", source: "xl/workbook.xml", external: false }, + { kind: "drawing", part: "xl/drawings/drawing1.xml", source: "xl/worksheets/sheet1.xml", external: false }, + { kind: "activeX", part: "xl/activeX/activeX1.xml", source: "xl/worksheets/sheet1.xml", external: false }, + { kind: "oleObject", part: "xl/worksheets/sheet1.xml", source: "xl/worksheets/sheet1.xml", external: true }, + { kind: "activeX", part: "xl/activeX/activeX1.bin", source: "xl/activeX/activeX1.xml", external: false }, + ]); + expect(scan.unreferenced).toEqual(["stray.txt"]); + expect(ctx.consumed.size).toBe(1); // [Content_Types].xml only: the scan reads relationships parts without consuming them + }); +}); + +describe("clean workbooks stay without these warnings", () => { + const dirs = ["../fixtures/read/", "../fixtures/import/xlsx/"]; + const files = dirs.flatMap((d) => readdirSync(new URL(d, import.meta.url)).filter((f) => f.endsWith(".xlsx")).map((f) => [`${d}${f}`, () => new Uint8Array(readFileSync(new URL(`${d}${f}`, import.meta.url)))] as const)); + const written = ALL.filter((e) => !e.heavy).map((e) => [`written: ${e.id}`, () => toUint8Array(e.workbook(), e.options)] as const); + + it("the corpus has files to check", () => { + expect(files.length).toBeGreaterThanOrEqual(10); + expect(written.length).toBeGreaterThanOrEqual(10); + }); + + it.each([...files, ...written])("%s", async (_, bytesOf) => { + const bytes = await bytesOf(); + const ctx = new ReadContext(openZip(bytes), DEFAULT_LIMITS, undefined, undefined, undefined); + const pkg = new Package(ctx); + await pkg.loadContentTypes(); + const scan = await scanPackageParts(pkg); + expect(scan.unreferenced).toEqual([]); + expect(scan.found.filter((f) => NEW_KINDS.has(f.kind))).toEqual([]); + const { warnings } = await read(bytes); + expect(warnings.filter((w) => w.partKind !== undefined && NEW_KINDS.has(w.partKind))).toEqual([]); + // Only the passive kinds these files have (LibreOffice writes a drawing for its chart). + expect(warnings.filter((w) => w.code === "UNSUPPORTED_PART" && w.partKind !== "drawing")).toEqual([]); + }); +}); From 46d55f2a903c057c531e90f2a0fadd984e70f711 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 11:50:40 +0100 Subject: [PATCH 2/6] JSE-72 review: canonical part names, macro sheet types, content-type backstop - Part names are compared in OPC canonical form on both sides (percent-escapes decoded as UTF-8 except %2F, %5C, %25; case-insensitive). resolveTarget treats only literal . and .. as dot segments, so %2E%2E, %2F, %5C and double encoding stay inside one name. Entries equivalent to an earlier entry are listed as unreferenced instead of being dropped. - xlMacrosheet and xlIntlMacrosheet relationships are macro sheets. - Relationship types compare case-insensitively. Content types of ActiveX, OLE objects, VBA, macro sheets, web add-ins and embedded Office documents classify a part whatever relationship reaches it. - New partKind 'webExtension' for Office web add-ins; attachedToolbars, VBA signatures and wordVbaData report as 'vbaProject'. - The [trash]/ exemption matches exactly; docs state it and that DTDs or over-deep XML in nested relationships parts now throw. --- .changeset/package-scan-active-content.md | 2 +- docs/api.md | 12 +- packages/javascript-excel/README.md | 2 +- .../javascript-excel/src/internal/read/opc.ts | 112 ++++++++++++++-- .../src/internal/read/reader.ts | 11 +- .../src/internal/read/scan.ts | 124 +++++++++++++---- packages/javascript-excel/src/warnings.ts | 5 +- .../test/read/helpers.test.ts | 23 +++- .../test/read/package-scan.test.ts | 126 ++++++++++++++++++ 9 files changed, 362 insertions(+), 55 deletions(-) diff --git a/.changeset/package-scan-active-content.md b/.changeset/package-scan-active-content.md index f8fc2fc..b13ad95 100644 --- a/.changeset/package-scan-active-content.md +++ b/.changeset/package-scan-active-content.md @@ -2,4 +2,4 @@ "javascript-excel": minor --- -`read` (and `importDataset`, which passes read warnings on) now walks the whole relationship graph of the package and reports more content it does not read as `UNSUPPORTED_PART`, with four new `partKind` values: `'activeX'` (ActiveX controls: a `control` or `activeXControlBinary` relationship, or a part with the ActiveX content type), `'embeddedPackage'` (a `package` relationship, such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a ribbon customisation: the root `ui/extensibility` relationship of Office 2007 or 2010) and `'unreferencedPart'` (one warning for all parts no relationship reaches, such as a `vbaProject.bin` or an executable placed in the zip; Office's `[trash]/` folder is exempt). The scan also finds `'oleObject'`, `'vbaProject'`, `'externalLink'`, `'connections'` and `'queryTable'` where they were not reported before: under a drawing, under a table, or on a sheet left out by the `sheets` option. Drawings, images, comments and the other passive kinds are reported as before. The scan reads only relationships parts, within the existing zip and XML limits, and never inflates the parts it reports; a relationships part that is not well-formed XML is reported as unreferenced instead of failing the read. Existing warnings keep their shape; a `switch` over `ExcelPartKind` needs a `default` branch, as documented. The test corpus (files from LibreOffice and openpyxl, and every file of the conformance corpus this library writes) gives no new warnings. +`read` (and `importDataset`, which passes read warnings on) now walks the whole relationship graph of the package and reports more content it does not read as `UNSUPPORTED_PART`, with four new `partKind` values: `'activeX'` (ActiveX controls: a `control` or `activeXControlBinary` relationship, or a part with the ActiveX content type), `'embeddedPackage'` (a `package` relationship, such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a ribbon customisation: the root `ui/extensibility` relationship of Office 2007 or 2010) `'webExtension'` (Office web add-ins) and `'unreferencedPart'` (one warning for all parts no relationship reaches, such as a `vbaProject.bin` or an executable placed in the zip; entries under exactly `[trash]/`, Office's folder for discarded parts, are exempt). The scan also finds `'oleObject'`, `'vbaProject'` (now also attached toolbars and VBA signatures), `'externalLink'`, `'connections'`, `'queryTable'` and `'macrosheet'` where they were not reported before: under a drawing, under a table, or on a sheet left out by the `sheets` option. Excel 4 macro sheets with Microsoft's `xlMacrosheet` and `xlIntlMacrosheet` relationship types are now reported as `'macrosheet'`. Relationship types are compared case-insensitively, and a part with the content type of an ActiveX control, OLE object, VBA project, macro sheet, web add-in or embedded Office document is reported as that kind whatever relationship reaches it. Part names are compared in OPC canonical form (percent-escapes decoded as UTF-8 on both sides, except `%2F`, `%5C` and `%25`; only literal `.` and `..` are dot segments), so a percent-encoded target such as `image%201.png` reaches its entry and `%2E%2E` no longer acts as `..`. Because the scan parses the relationships parts of every reached part, a DTD or an over-deep XML in one of them (also under a sheet that is not read) now throws `XML_DTD_FORBIDDEN` or `LIMIT_EXCEEDED`; 2.4.0 read such a file. Drawings, images, comments and the other passive kinds are reported as before. The scan reads only relationships parts, within the existing zip and XML limits, and never inflates the parts it reports; a relationships part that is not well-formed XML is reported as unreferenced instead of failing the read. Existing warnings keep their shape; a `switch` over `ExcelPartKind` needs a `default` branch, as documented. The test corpus (files from LibreOffice and openpyxl, and every file of the conformance corpus this library writes) gives no new warnings. diff --git a/docs/api.md b/docs/api.md index c7f9ec7..623076e 100644 --- a/docs/api.md +++ b/docs/api.md @@ -877,8 +877,9 @@ How the reader works, as far as the API is concerned: - **Formats.** Detection is a table: the container signature (CFB, zip), then the content type of the workbook part, each entry naming the decoder that reads it. `.xlsx`, `.xltx`, `.xlsm` and `.xltm` share the SpreadsheetML decoder; for the macro-enabled two, one `UNSUPPORTED_PART` warning says the VBA macros are not read or run. Formats without a decoder in 2.0 throw `UNSUPPORTED_FORMAT` with `details.format`: `'cfb'` (`.xls`, or an encrypted/password-protected `.xlsx`, which is a CFB container), `'xlsb'`, `'ods'`, `'unknown'` (no zip signature). They are a phase boundary, not a design limit: supporting `.xlsb` or `.xls` later is a new decoder plus its table row. A zip without a workbook part is `NOT_XLSX`. A workbook part with a missing or unknown content type is read as SpreadsheetML (`.bin` as `.xlsb`). - **Unread parts are not lost at the zip level.** The reader parses only the parts the model represents, but the archive stays addressable by part name until the read ends, and an internal (not yet public) option returns every unparsed part byte for byte. A later release can use it to carry drawings, comments, VBA or custom XML through a read-modify-write. - Unsupported content (drawings, charts, comments, pivot tables, tables, OLE objects, form controls, VBA, external links, chart sheets, …) gives one `UNSUPPORTED_PART` warning per kind. Chart, dialog and macro sheets are not worksheets: they are left out of `sheets` and `readSheetNames`, and defined names local to them are dropped. -- **The package scan** (since 2.5). After the sheets, the reader walks the whole relationship graph, from the package root through the workbook and every sheet (also sheets left out by `sheets`) to every part those reach (drawings, VML drawings, tables, ActiveX parts, …). It reads only relationships parts, each once, within the zip and XML limits, and never inflates the parts it finds. It reports, once per kind, the kinds that are active or embedded content or a link out of the file, wherever they sit: `'activeX'` (a `control` or `activeXControlBinary` relationship, or a part with the content type `application/vnd.ms-office.activeX…`), `'embeddedPackage'` (a `package` relationship, a file such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a root `…/relationships/ui/extensibility` relationship, 2006 and 2007 namespaces: a ribbon customisation, `customUI/customUI.xml` or `customUI14.xml`), and `'oleObject'`, `'vbaProject'`, `'externalLink'`, `'connections'` and `'queryTable'` where the workbook's and the read sheets' own relationships did not already report them (an OLE object referenced from a drawing, a query table under a table, an ActiveX control on a sheet not read). Drawings, images, comments, tables, pivots and the other passive kinds are reported as before, from the workbook's and the read sheets' own relationships only, so an image inside a drawing still gives just `'drawing'`. -- **Unreferenced parts** (since 2.5). A part no relationship reaches (a `vbaProject.bin` without a relationship, an executable dropped into the zip, with or without a content type) gives one `UNSUPPORTED_PART` warning with `partKind: 'unreferencedPart'`, `part` naming the first such part in zip order and the message their number. Parts reached only through an unreferenced part are unreferenced too, and so is a relationships part that is not well-formed XML, together with the parts only it would reach (the read goes on). Not reported: `[Content_Types].xml`, the relationships part of a reached part, and anything under Office's `[trash]/` folder, where Office 2007 and 2010 moved parts it discarded. Nothing else is exempt by name. The thumbnail (`docProps/thumbnail.*`), printer settings (`xl/printerSettings/*.bin`), `xl/calcChain.xml`, custom XML and the document properties are parts with their own relationship types (from the package root, a sheet and the workbook), so in a well-formed package they are reached and never count as unreferenced; an orphaned copy of one does, because an exemption by name would be the place to hide a payload. Evidence: none of the test corpus files (the openpyxl, LibreOffice and import fixtures and every conformance-corpus file this library writes) has an unreferenced part. Files saved by Excel and Numbers are not in the corpus; a part they leave unreferenced would be reported, and is a bug report worth filing. +- **The package scan** (since 2.5). After the sheets, the reader walks the whole relationship graph, from the package root through the workbook and every sheet (also sheets left out by `sheets`) to every part those reach (drawings, VML drawings, tables, ActiveX parts, …). It reads only relationships parts, each once, within the zip and XML limits, and never inflates the parts it finds. It reports, once per kind, the kinds that are active or embedded content or a link out of the file, wherever they sit: `'activeX'` (a `control` or `activeXControlBinary` relationship), `'embeddedPackage'` (a `package` relationship, a file such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a root `…/relationships/ui/extensibility` relationship, 2006 and 2007 namespaces: a ribbon customisation, `customUI/customUI.xml` or `customUI14.xml`), `'webExtension'` (an Office web add-in: the `webextensiontaskpanes` and `webextension` relationships, `xl/webextensions/`), and `'oleObject'`, `'vbaProject'`, `'externalLink'`, `'connections'`, `'queryTable'` and `'macrosheet'` where the workbook's and the read sheets' own relationships did not already report them (an OLE object referenced from a drawing, a query table under a table, an ActiveX control on a sheet not read). `'vbaProject'` covers the VBA family: the project, its signatures (`vbaProjectSignature`, `…Agile`, `…V3`), `wordVbaData` and toolbars attached to a macro workbook (`attachedToolbars`, `xl/attachedToolbars.bin`). Excel 4 macro sheets are macro sheets under all three relationship types, ECMA `…/macrosheet` and Microsoft's `…/xlMacrosheet` and `…/xlIntlMacrosheet` (before 2.5 only the first was reported; all three were left out of `sheets`). +- **Matching** (since 2.5). Relationship types are compared without regard to case (`OLEOBJECT` is `oleObject`). A part's content type is a backstop: a part with the content type of an ActiveX control (`application/vnd.ms-office.activeX+xml`, `application/vnd.ms-office.activeX`), an OLE object (`application/vnd.openxmlformats-officedocument.oleObject`), VBA (`application/vnd.ms-office.vbaProject`, `…vbaProjectSignature`, `application/vnd.ms-excel.attachedToolbars`), a macro sheet (`application/vnd.ms-excel.macrosheet+xml`, `…intlmacrosheet+xml`), a web add-in (`application/vnd.ms-office.webextension+xml`, `…webextensiontaskpanes+xml`) or an embedded Office document (Word, Excel and PowerPoint documents, macro-enabled ones included) is reported as that kind whatever relationship reaches it, so an `image` relationship to an OLE object gives both `'image'` and `'oleObject'`. Part names are matched as OPC defines equivalence: case-insensitively, after decoding percent-escapes as UTF-8, both in the relationship target and in the zip entry name, so `../media/image%201.png` reaches the entry `xl/media/image%201.png` (and `xl/media/image 1.png`), and `%C3%A4` reaches `ä`. `%2F`, `%5C` and `%25` are never decoded, and only a literal `.` or `..` segment is a dot segment, so `%2E%2E`, `%2F`, `%5C` and a double encoding such as `%2541` stay part of one name and cannot reach another part. Before 2.5 the target was decoded in full before its dot segments were resolved, so `%2E%2E/` acted as `../`. When two entries have equivalent names that differ in more than case (`a b` and `a%20b`), relationships reach the first in zip order and the other is unreferenced; entries that differ only in case still throw `ZIP_INVALID`. Drawings, images, comments, tables, pivots and the other passive kinds are reported as before, from the workbook's and the read sheets' own relationships only, so an image inside a drawing still gives just `'drawing'`. +- **Unreferenced parts** (since 2.5). A part no relationship reaches (a `vbaProject.bin` without a relationship, an executable dropped into the zip, with or without a content type) gives one `UNSUPPORTED_PART` warning with `partKind: 'unreferencedPart'`, `part` naming the first such part in zip order and the message their number. Parts reached only through an unreferenced part are unreferenced too, and so is a relationships part that is not well-formed XML, together with the parts only it would reach (the read goes on). Not reported: `[Content_Types].xml`, the relationships part of a reached part, and entries whose zip name starts with exactly `[trash]/`, the folder at the package root where Office 2007 and 2010 moved parts they discarded. The match is exact: `[TRASH]/`, `%5Btrash%5D/` or `xl/[trash]/` are reported like any other unreferenced part, since there is no evidence that Office wrote another spelling. So an entry under `[trash]/` is never reported, whatever it holds. Excel cannot load it either (parts load only through relationships), but its bytes are carried in the file: a consumer that stores or forwards files and cares about every byte they carry must look for `[trash]/` entries itself. Nothing else is exempt by name. The thumbnail (`docProps/thumbnail.*`), printer settings (`xl/printerSettings/*.bin`), `xl/calcChain.xml`, custom XML and the document properties are parts with their own relationship types (from the package root, a sheet and the workbook), so in a well-formed package they are reached and never count as unreferenced; an orphaned copy of one does, because an exemption by name would be the place to hide a payload. Evidence: none of the test corpus files (the openpyxl, LibreOffice and import fixtures and every conformance-corpus file this library writes) has an unreferenced part. Files saved by Excel and Numbers are not in the corpus; a part they leave unreferenced would be reported, and is a bug report worth filing. - Styles: each `cellXfs` entry is one frozen `Style` (§12 Q8). Pattern fills come back with `type: 'pattern'`, so `fill.type` tells pattern and gradient fills apart. A style records only what differs from the defaults: font 0 (the workbook default font), fills 0 and 1 (the required `none` and `gray125` placeholders) and border 0 are left out, and `numFmtId` 0 (General) gives no `numFmt`. `applyFont` and the other apply flags are ignored, as Excel does for cell formats. - Values: `t="s"`, `"inlineStr"` and `"str"` are strings (or rich text), with `_xHHHH_` escapes decoded; `"b"` booleans; `"e"` errors, including codes newer than the seven of ECMA-376 (`#SPILL!`, `#CALC!`, …), returned as written; `"d"` ISO dates; numbers otherwise, converted to `Date` when their number format is a date format (§3.4.1). A formula's cached value sets `value` and `type`; without one the cell is `type: 'empty'` with its `formula`. Shared formulas are expanded (§12 Q6), except from a master longer than 8,192 characters and except copies longer than `maxCellTextLength` (§3.4.2); data-table formulas (`t="dataTable"`) give their cached values only. - **`rawText`** (from 2.1.0): converting `` to a JavaScript number loses what the file says: `1234567890123456789` reads as `1234567890123456800`, `50.30` as `50.3`, `1E-7` as `1e-7`, `-0` as `0`, and a `t="d"` cell is always a `Date`. With `rawText: true`, such cells also get `cell.rawText`, the characters of `` exactly as stored: XML entities and character references decoded and line ends normalised (as for any XML text), nothing trimmed, no `_xHHHH_` decoding. `value` and `type` are what they would be without the option, so the cell still says it was a number or a date. Default false: no `rawText` key is added and the model is the same as before 2.1.0. The worker's `read` passes the option through; `importDataset` (§5.6) returns coerced column values, not cells, and does not take it. @@ -1723,7 +1724,7 @@ export type ExcelPartKind = | 'table' | 'oleObject' | 'ctrlProp' | 'image' | 'vbaProject' | 'externalLink' | 'connections' | 'queryTable' | 'slicer' | 'slicerCache' | 'timeline' | 'chartsheet' | 'dialogsheet' | 'macrosheet' // UNSUPPORTED_PART, found by the package scan wherever they sit (since 2.5, §5.2) - | 'activeX' | 'embeddedPackage' | 'customUI' | 'unreferencedPart'; + | 'activeX' | 'embeddedPackage' | 'customUI' | 'webExtension' | 'unreferencedPart'; export interface DroppedWarnings { total: number; // warnings not recorded @@ -1742,7 +1743,7 @@ export function isDataLossWarning(warning: ExcelWarning | ExcelWarningCode): boo | Warning code | Data loss | Situation and recovery | |---|---|---| -| `UNSUPPORTED_PART` | yes | Charts, drawings, pivots, comments, VBA, … are outside the model and not in the result; one warning per kind (so it cannot flood the list), `partKind` names it. Since 2.5 also ActiveX controls (`'activeX'`), embedded packages (`'embeddedPackage'`), ribbon customisations (`'customUI'`) and parts no relationship reaches (`'unreferencedPart'`, one warning for all of them), found anywhere in the package (§5.2, package scan). The cell values are complete; filter by `partKind` to accept the kinds you do not need | +| `UNSUPPORTED_PART` | yes | Charts, drawings, pivots, comments, VBA, … are outside the model and not in the result; one warning per kind (so it cannot flood the list), `partKind` names it. Since 2.5 also ActiveX controls (`'activeX'`), embedded packages (`'embeddedPackage'`), ribbon customisations (`'customUI'`), Office web add-ins (`'webExtension'`) and parts no relationship reaches (`'unreferencedPart'`, one warning for all of them), found anywhere in the package (§5.2, package scan). The cell values are complete; filter by `partKind` to accept the kinds you do not need | | `INVALID_STYLE_INDEX` | no | Cell refers to a missing `xf`; default style used. Declared for compatibility; 2.x leaves such a cell unstyled without a warning | | `INVALID_SHARED_STRING` | yes | Index out of range; cell left empty | | `CELL_OUT_OF_BOUNDS` / `INVALID_CELL_REF` | yes | Cell skipped | @@ -1803,7 +1804,8 @@ if (lost.length) throw new Error(`Refused: ${[...new Set(lost.map((w) => w.code) | **Formula injection into CSV** | Guard on by default (§5.3). | | **Malicious hyperlinks** | The writer allows only `http`, `https` and `mailto` by default, and rejects `javascript:`, `data:`, `vbscript:` and anything else not listed. The reader returns targets verbatim (it cannot know the consumer's policy): apps that render them, such as the viewer, must check the scheme. | | **External references** | External links, OLE objects, DDE and data connections are not read or followed. The reader resolves relationships only within the package. | -| **Active, embedded and hidden content** (a file that is harmless to this reader but carries something for whoever opens it next in Excel) | Never run, opened or inflated, and reported so an app can refuse the file (since 2.5): the package scan (§5.2) walks the whole relationship graph and reports ActiveX controls (`'activeX'`), embedded files (`'embeddedPackage'`), ribbon customisations with callbacks (`'customUI'`), OLE objects, VBA, external links, data connections and query tables wherever they sit, including under drawings and on sheets not read, and any part no relationship reaches (`'unreferencedPart'`), such as a `vbaProject.bin` or an executable placed in the zip without a relationship. Only Office's `[trash]/` folder is exempt. The scan reads relationships parts only, within the zip and XML limits. To refuse such files, check `warnings` for `UNSUPPORTED_PART` with these `partKind`s. | +| **Active, embedded and hidden content** (a file that is harmless to this reader but carries something for whoever opens it next in Excel) | Never run, opened or inflated, and reported so an app can refuse the file (since 2.5): the package scan (§5.2) walks the whole relationship graph and reports ActiveX controls (`'activeX'`), embedded files (`'embeddedPackage'`), ribbon customisations with callbacks (`'customUI'`), Office web add-ins (`'webExtension'`), OLE objects, VBA (with attached toolbars), Excel 4 macro sheets, external links, data connections and query tables wherever they sit, including under drawings and on sheets not read, by relationship type (case-insensitively) and by content type, and any part no relationship reaches (`'unreferencedPart'`), such as a `vbaProject.bin` or an executable placed in the zip without a relationship. Part names are compared in OPC canonical form, so percent-encoding can neither hide a reached part nor make one entry stand for another. Only entries under exactly `[trash]/` are exempt; their bytes stay in the file, so check for them yourself if that matters (§5.2). The scan reads relationships parts only, within the zip and XML limits. To refuse such files, check `warnings` for `UNSUPPORTED_PART` with these `partKind`s. | +| **Hostile relationships parts** | Since 2.5 the scan parses the relationships part of every reached part, also of sheets left out by `sheets` and of nested parts (drawings, tables, …). 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. 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). | diff --git a/packages/javascript-excel/README.md b/packages/javascript-excel/README.md index 02b4dd1..bd57bf0 100644 --- a/packages/javascript-excel/README.md +++ b/packages/javascript-excel/README.md @@ -91,7 +91,7 @@ const cell = exact.workbook.sheets[0]?.rows[0]?.[0]; 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 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. +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. ## CSV diff --git a/packages/javascript-excel/src/internal/read/opc.ts b/packages/javascript-excel/src/internal/read/opc.ts index a695b01..e61e024 100644 --- a/packages/javascript-excel/src/internal/read/opc.ts +++ b/packages/javascript-excel/src/internal/read/opc.ts @@ -20,8 +20,15 @@ export interface Relationship { } export class Package { + /** partKey(name) -> entry; the first entry of a key in zip order. */ private readonly parts = new Map(); - /** Part name (lower case, no leading '/') -> content type. */ + /** + * Entries whose name is equivalent to an earlier entry's (they differ in + * percent-encoding, e.g. `a b` and `a%20b`). No relationship can reach them, + * so the package scan lists them as unreferenced. + */ + readonly shadowed: ZipEntryInfo[] = []; + /** partKey(part name) -> content type. */ private readonly overrides = new Map(); /** Extension (lower case) -> content type. */ private readonly defaults = new Map(); @@ -29,9 +36,14 @@ export class Package { constructor(readonly ctx: ReadContext) { for (const e of ctx.zip.entries) { if (e.name.endsWith("/")) continue; // directory entries - const key = e.name.toLowerCase(); - if (this.parts.has(key)) { - throw new FormatError("ZIP_INVALID", `Part names ${excerpt(this.parts.get(key)!.name)} and ${excerpt(e.name)} differ only in case.`, { + const key = partKey(e.name); + const earlier = this.parts.get(key); + if (earlier) { + if (earlier.name.toLowerCase() !== e.name.toLowerCase()) { + this.shadowed.push(e); + continue; + } + throw new FormatError("ZIP_INVALID", `Part names ${excerpt(earlier.name)} and ${excerpt(e.name)} differ only in case.`, { details: { entry: e.name }, }); } @@ -40,7 +52,7 @@ export class Package { } part(name: string): ZipEntryInfo | undefined { - return this.parts.get(stripSlash(name).toLowerCase()); + return this.parts.get(partKey(name)); } get partNames(): string[] { @@ -59,7 +71,7 @@ export class Package { } else if (name === "Override") { const part = a.get("PartName"); const type = a.get("ContentType"); - if (part && type) this.overrides.set(stripSlash(part).toLowerCase(), type); + if (part && type) this.overrides.set(partKey(part), type); } }, close: () => {}, @@ -68,7 +80,7 @@ export class Package { } contentType(name: string): string | undefined { - const key = stripSlash(name).toLowerCase(); + const key = partKey(name); const o = this.overrides.get(key); if (o) return o; const dot = key.lastIndexOf("."); @@ -148,22 +160,94 @@ function stripSlash(name: string): string { return name.startsWith("/") ? name.slice(1) : name; } -/** Resolves a relationship target against the source part's folder (RFC 3986 dot segments, '%xx' decoded). */ +/** + * Part-name equivalence (OPC, ECMA-376 Part 2 §6.2.2.3 and the zip mapping of + * §7.3.4): `name` with percent-escapes decoded (as UTF-8), except `%2F`, `%5C` + * and `%25`, which stay encoded (upper-case hex) so that an escape can never + * become a folder separator or a new escape. Idempotent. Not lower-cased. + */ +export function canonicalPartName(name: string): string { + if (!name.includes("%")) return name; + let out = ""; + let i = 0; + const bytes: number[] = []; + const flush = (): void => { + if (!bytes.length) return; + // Each valid UTF-8 sequence is decoded; a byte that starts none stays an escape. + let j = 0; + while (j < bytes.length) { + const lead = bytes[j]!; + const len = lead < 0x80 ? 1 : lead >= 0xc2 && lead <= 0xdf ? 2 : lead >= 0xe0 && lead <= 0xef ? 3 : lead >= 0xf0 && lead <= 0xf4 ? 4 : 0; + const text = len && j + len <= bytes.length ? utf8(bytes.slice(j, j + len)) : undefined; + if (text === undefined) { + out += hex(lead); + j++; + } else { + out += text; + j += len; + } + } + bytes.length = 0; + }; + while (i < name.length) { + const m = name.charCodeAt(i) === 0x25 ? /^%([0-9A-Fa-f]{2})/.exec(name.slice(i, i + 3)) : null; + if (m) { + const byte = parseInt(m[1]!, 16); + if (byte === 0x2f || byte === 0x5c || byte === 0x25) { + flush(); + out += hex(byte); + } else bytes.push(byte); + i += 3; + continue; + } + flush(); + out += name[i]; + i++; + } + flush(); + return out; +} + +interface FatalDecoder { + decode(input: Uint8Array): string; +} +let utf8Decoder: FatalDecoder | undefined; + +function utf8(bytes: number[]): string | undefined { + // Created on first use, the same global the part parser uses (context.ts). + utf8Decoder ??= new (globalThis as unknown as { TextDecoder: new (label: string, options: { fatal: boolean }) => FatalDecoder }).TextDecoder("utf-8", { fatal: true }); + try { + return utf8Decoder.decode(new Uint8Array(bytes)); + } catch { + return undefined; + } +} + +function hex(byte: number): string { + return `%${byte.toString(16).toUpperCase().padStart(2, "0")}`; +} + +/** The lookup key of a part name: canonical, no leading '/', lower case (part names compare case-insensitively). */ +export function partKey(name: string): string { + return canonicalPartName(stripSlash(name)).toLowerCase(); +} + +/** + * Resolves a relationship target against the source part's folder. Only + * literal `.` and `..` segments are dot segments, and only a literal `/` or + * `\` separates segments; each segment is then put in canonical form + * (`canonicalPartName`), so `%2E%2E`, `%2F` and `%5C` stay part of a name. + */ export function resolveTarget(baseDir: string, target: string): string { let t = target; const hash = t.indexOf("#"); if (hash !== -1) t = t.slice(0, hash); - try { - t = decodeURIComponent(t); - } catch { - // keep as is - } t = t.replace(/\\/g, "/"); const segments = t.startsWith("/") ? [] : baseDir.split("/").filter((s) => s !== ""); for (const seg of t.split("/")) { if (seg === "" || seg === ".") continue; if (seg === "..") segments.pop(); - else segments.push(seg); + else segments.push(canonicalPartName(seg)); } return segments.join("/"); } diff --git a/packages/javascript-excel/src/internal/read/reader.ts b/packages/javascript-excel/src/internal/read/reader.ts index 25eb79c..d7c0947 100644 --- a/packages/javascript-excel/src/internal/read/reader.ts +++ b/packages/javascript-excel/src/internal/read/reader.ts @@ -12,7 +12,7 @@ import type { ExcelPartKind } from "../../warnings"; import { toBytes } from "../input"; import { openZip } from "../zip/read"; import { ReadContext } from "./context"; -import { REPORTED_ANYWHERE, SCANNED_KINDS, scanPackageParts, UNSUPPORTED_RELATIONSHIPS } from "./scan"; +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"; import { DEFAULT_LIMITS } from "./limits"; import { Package, type Relationship } from "./opc"; @@ -177,10 +177,11 @@ export function warnUnsupportedParts(ctx: Pick = new Map = new Map([ + ["control", "activeX"], + ["activexcontrolbinary", "activeX"], + ["package", "embeddedPackage"], + ["xlmacrosheet", "macrosheet"], + ["xlintlmacrosheet", "macrosheet"], + ["webextensiontaskpanes", "webExtension"], + ["webextension", "webExtension"], + // The VBA family: toolbars attached to a macro workbook and the project's signatures and data. + ["attachedtoolbars", "vbaProject"], + ["vbaprojectsignature", "vbaProject"], + ["vbaprojectsignatureagile", "vbaProject"], + ["vbaprojectsignaturev3", "vbaProject"], + ["wordvbadata", "vbaProject"], +]); + +/** UNSUPPORTED_RELATIONSHIPS keyed by lower-case kind. */ +const RELATIONSHIP_KINDS: ReadonlyMap = new Map([...UNSUPPORTED_RELATIONSHIPS.keys()].map((k) => [k.toLowerCase(), k])); + +/** + * Content types (lower case) of active or embedded content: a part with one + * of these is reported as its kind whatever relationship reaches it. + */ +const CONTENT_TYPES: ReadonlyMap = new Map([ + ["application/vnd.ms-office.activex+xml", "activeX"], + ["application/vnd.ms-office.activex", "activeX"], + ["application/vnd.openxmlformats-officedocument.oleobject", "oleObject"], + ["application/vnd.ms-office.vbaproject", "vbaProject"], + ["application/vnd.ms-office.vbaprojectsignature", "vbaProject"], + ["application/vnd.ms-excel.attachedtoolbars", "vbaProject"], + ["application/vnd.ms-excel.macrosheet+xml", "macrosheet"], + ["application/vnd.ms-excel.intlmacrosheet+xml", "macrosheet"], + ["application/vnd.ms-office.webextension+xml", "webExtension"], + ["application/vnd.ms-office.webextensiontaskpanes+xml", "webExtension"], + // Embedded Office documents (what Excel writes under xl/embeddings/ with a package relationship). + ["application/vnd.openxmlformats-officedocument.wordprocessingml.document", "embeddedPackage"], + ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "embeddedPackage"], + ["application/vnd.openxmlformats-officedocument.presentationml.presentation", "embeddedPackage"], + ["application/vnd.openxmlformats-officedocument.presentationml.slideshow", "embeddedPackage"], + ["application/vnd.ms-word.document.macroenabled.12", "embeddedPackage"], + ["application/vnd.ms-excel.sheet.macroenabled.12", "embeddedPackage"], + ["application/vnd.ms-excel.sheet.binary.macroenabled.12", "embeddedPackage"], + ["application/vnd.ms-powerpoint.presentation.macroenabled.12", "embeddedPackage"], + ["application/vnd.ms-powerpoint.slideshow.macroenabled.12", "embeddedPackage"], ]); /** @@ -60,10 +111,10 @@ export const REPORTED_ANYWHERE: ReadonlySet = new Set { const ctx = pkg.ctx; const found: ScannedPart[] = []; const foundKeys = new Set(); /** Lower-case names of the parts accounted for. */ - const reached = new Set(["[content_types].xml"]); + const reached = new Set([partKey("[Content_Types].xml")]); const queue: string[] = [""]; for (let q = 0; q < queue.length; q++) { const pause = ctx.step(); @@ -131,7 +200,7 @@ export async function scanPackageParts(pkg: Package): Promise { throw err; } const relsPart = pkg.part(pkg.relsPartOf(source)); - if (relsPart) reached.add(relsPart.name.toLowerCase()); + if (relsPart) reached.add(partKey(relsPart.name)); for (let i = 0; i < rels.length; i++) { if ((i & ABORT_EVERY) === ABORT_EVERY) ctx.checkAbort(); const rel = rels[i]!; @@ -147,20 +216,23 @@ export async function scanPackageParts(pkg: Package): Promise { if (rel.external) continue; const entry = pkg.part(rel.target); if (!entry) continue; - const name = entry.name.toLowerCase(); + const name = partKey(entry.name); if (reached.has(name)) continue; reached.add(name); queue.push(entry.name); } } const unreferenced: string[] = []; - const names = pkg.partNames; - for (let i = 0; i < names.length; i++) { + const shadowed = new Set(pkg.shadowed); + const entries = ctx.zip.entries; + for (let i = 0; i < entries.length; i++) { if ((i & ABORT_EVERY) === ABORT_EVERY) ctx.checkAbort(); - const name = names[i]!; - const lower = name.toLowerCase(); - if (reached.has(lower) || lower.startsWith("[trash]/")) continue; - unreferenced.push(name); + const e = entries[i]!; + if (e.name.endsWith("/")) continue; // directory entries + // Office 2007 and 2010 moved discarded parts to "[trash]/" (exactly so, at the root). + if (e.name.startsWith(TRASH)) continue; + if (!shadowed.has(e) && reached.has(partKey(e.name))) continue; + unreferenced.push(e.name); } return { found, unreferenced }; } diff --git a/packages/javascript-excel/src/warnings.ts b/packages/javascript-excel/src/warnings.ts index 7eca9bc..d08a89d 100644 --- a/packages/javascript-excel/src/warnings.ts +++ b/packages/javascript-excel/src/warnings.ts @@ -40,8 +40,8 @@ export type ExcelWarningCode = * OOXML relationship type (`.../relationships/worksheet` is `'worksheet'`), * in camelCase for the document-property parts. The kinds the package scan * adds are named for what they are: `'activeX'` (ActiveX controls), - * `'embeddedPackage'` (embedded files), `'customUI'` (ribbon customisation) - * and `'unreferencedPart'` (a part no relationship reaches). Kinds may be added in a minor + * `'embeddedPackage'` (embedded files), `'customUI'` (ribbon customisation), + * `'webExtension'` (Office web add-ins) and `'unreferencedPart'` (a part no relationship reaches). Kinds may be added in a minor * release, so a `switch` over it needs a `default` branch. */ export type ExcelPartKind = @@ -78,6 +78,7 @@ export type ExcelPartKind = | "activeX" | "embeddedPackage" | "customUI" + | "webExtension" | "unreferencedPart"; /** What the warning cap left out; on `WARNINGS_TRUNCATED` only. */ diff --git a/packages/javascript-excel/test/read/helpers.test.ts b/packages/javascript-excel/test/read/helpers.test.ts index 1a8c6d4..4d15f20 100644 --- a/packages/javascript-excel/test/read/helpers.test.ts +++ b/packages/javascript-excel/test/read/helpers.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { shiftFormula } from "../../src/internal/read/formula"; import { BUILTIN_NUM_FMTS, isDateFormat } from "../../src/numfmt"; -import { resolveTarget } from "../../src/internal/read/opc"; +import { canonicalPartName, partKey, resolveTarget } from "../../src/internal/read/opc"; import { fileWidthToChars } from "../../src/internal/read/sheet"; import { charsToFileWidth, pixelsToChars } from "../../src/internal/write/sheet-features"; import { decodeXstring } from "../../src/internal/read/strings"; @@ -110,4 +110,25 @@ describe("ST_Xstring and relationship targets", () => { expect(resolveTarget("xl/", "My%20Sheet.xml")).toBe("xl/My Sheet.xml"); expect(resolveTarget("", "../../../etc/passwd")).toBe("etc/passwd"); }); + it("only literal dot segments and separators structure a target; escapes stay in the name (JSE-72)", () => { + expect(resolveTarget("xl/drawings/", "%2E%2E/evil.bin")).toBe("xl/drawings/../evil.bin"); + expect(resolveTarget("xl/", "a%2Fb.bin")).toBe("xl/a%2Fb.bin"); + expect(resolveTarget("xl/", "a%5cb.bin")).toBe("xl/a%5Cb.bin"); + expect(resolveTarget("xl/", "%2541.bin")).toBe("xl/%2541.bin"); + expect(resolveTarget("xl/", "%C3%A4%FF.png")).toBe("xl/\u00e4%FF.png"); + }); + it("canonical part names: decoded except %2F, %5C and %25; idempotent; keys compare case-insensitively", () => { + for (const [raw, canon] of [ + ["xl/media/image%201.png", "xl/media/image 1.png"], + ["%C3%A4", "\u00e4"], + ["%41%2f%5c%25", "A%2F%5C%25"], + ["%2541", "%2541"], + ["%FF%zz", "%FF%zz"], + ]) { + expect(canonicalPartName(raw!)).toBe(canon); + expect(canonicalPartName(canon!)).toBe(canon); + } + expect(partKey("/XL/Media/%41.PNG")).toBe(partKey("xl/media/a.png")); + expect(partKey("xl/a%2Fb")).not.toBe(partKey("xl/a/b")); + }); }); diff --git a/packages/javascript-excel/test/read/package-scan.test.ts b/packages/javascript-excel/test/read/package-scan.test.ts index 23fe336..b47c795 100644 --- a/packages/javascript-excel/test/read/package-scan.test.ts +++ b/packages/javascript-excel/test/read/package-scan.test.ts @@ -163,6 +163,11 @@ describe("parts no relationship reaches (partKind 'unreferencedPart')", () => { expect(r.warnings[1]!.message).toMatch(/^The package contains 2 parts/); }); + it.each([["[TRASH]/0000.dat"], ["%5Btrash%5D/0000.dat"], ["xl/[trash]/0000.dat"]])("only the exact [trash]/ folder at the root is exempt: %s is reported", async (name) => { + const r = await readOf({ sheets: [CELL], parts: { [name]: "x" } }); + expect(unsupported(r.warnings)).toEqual([["unreferencedPart", name]]); + }); + it("Office's [trash] folder, relationships parts of reached parts and [Content_Types].xml are not reported", async () => { const r = await readOf({ sheets: [CELL], @@ -182,6 +187,127 @@ describe("parts no relationship reaches (partKind 'unreferencedPart')", () => { }); }); +describe("part names: percent-encoding and equivalence (OPC)", () => { + /** A sheet with a drawing whose relationships point at `targets` (relative to xl/drawings/). */ + const withDrawing = (targets: string[], parts: Record): BuildOptions => ({ + sheets: [CELL], + sheetRels: { 0: [["rD", "drawing", "../drawings/drawing1.xml"]] }, + parts: { + "xl/drawings/drawing1.xml": "", + "xl/drawings/_rels/drawing1.xml.rels": rels(targets.map((t, i) => [`r${i}`, "image", t])), + ...parts, + }, + }); + + it.each([ + ["a percent-encoded space in both", "../media/image%201.png", "xl/media/image%201.png"], + ["encoded UTF-8 in both", "../media/%C3%A4.png", "xl/media/%C3%A4.png"], + ["encoded UTF-8 in the zip, the character in the target", "../media/\u00e4.png", "xl/media/%C3%A4.png"], + ["encoded in the target, raw in the zip (as 2.4.0)", "../media/image%201.png", "xl/media/image 1.png"], + ["an encoded unreserved character", "../media/%41.png", "xl/media/a.png"], + ])("%s: the part is reached", async (_, target, entry) => { + const r = await readOf(withDrawing([JSON.parse(`"${target}"`) as string], { [entry]: "png" })); + expect(unsupported(r.warnings)).toEqual([["drawing", "xl/drawings/drawing1.xml"]]); + }); + + it.each([ + ["%2E%2E is a name, not a parent folder", "%2E%2E/evil.bin", "xl/evil.bin"], + ["%2F is not a folder separator", "../media/a%2Fb.bin", "xl/media/a/b.bin"], + ["%5C is not a folder separator", "../media/a%5Cb.bin", "xl/media/a/b.bin"], + ["double encoding is decoded once", "../media/%2541.bin", "xl/media/A.bin"], + ])("%s: an encoded target does not reach another part", async (_, target, entry) => { + const r = await readOf(withDrawing([target], { [entry]: "x" })); + expect(unsupported(r.warnings)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["unreferencedPart", entry]]); + }); + + it("two entries with equivalent names do not count as one reached part: the later one is unreferenced", async () => { + const r = await readOf(withDrawing(["../media/a%20b.bin"], { "xl/media/a b.bin": "1", "xl/media/a%20b.bin": "2" })); + expect(unsupported(r.warnings)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["unreferencedPart", "xl/media/a%20b.bin"]]); + }); +}); + +describe("Excel 4 macro sheets, case-insensitive types and content types", () => { + const MS = "http://schemas.microsoft.com/office/2006/relationships"; + it.each([ + ["xlMacrosheet", `${MS}/xlMacrosheet`], + ["xlIntlMacrosheet", `${MS}/xlIntlMacrosheet`], + ["ECMA macrosheet", `${REL}/macrosheet`], + ])("a %s relationship is a macro sheet: left out of sheets and reported", async (_, type) => { + const bytes = await build({ + sheets: [CELL], + override: { + "xl/workbook.xml": ``, + "xl/_rels/workbook.xml.rels": rels([["rS1", "worksheet", "worksheets/sheet1.xml"], ["rM", type, "macrosheets/sheet1.xml"]]), + }, + parts: { "xl/macrosheets/sheet1.xml": "" }, + }); + const r = await read(bytes); + expect(r.workbook.sheets.map((s) => s.name)).toEqual(["Sheet1"]); + expect(unsupported(r.warnings)).toEqual([["macrosheet", "xl/macrosheets/sheet1.xml"]]); + }); + + it.each([ + ["macrosheet", "application/vnd.ms-excel.macrosheet+xml", "macrosheet"], + ["international macro sheet", "application/vnd.ms-excel.intlmacrosheet+xml", "macrosheet"], + ["oleObject", "application/vnd.openxmlformats-officedocument.oleObject", "oleObject"], + ["vbaProject", "application/vnd.ms-office.vbaProject", "vbaProject"], + ["embedded .docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "embeddedPackage"], + ["embedded macro-enabled .xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12", "embeddedPackage"], + ])("a %s content type behind a harmless relationship (image) is reported by the content type", async (_, contentType, kind) => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rI", "image", "../media/payload1.bin"]] }, + parts: { "xl/media/payload1.bin": "x" }, + override: { "[Content_Types].xml": contentTypes({}, { "/xl/media/payload1.bin": contentType }) }, + }); + expect(unsupported(r.warnings)).toEqual([["image", "xl/media/payload1.bin"], [kind, "xl/media/payload1.bin"]]); + }); + + it("relationship types are compared without regard to case", async () => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rO", "OLEOBJECT", "../embeddings/oleObject1.bin"], ["rC", "Control", "../activeX/activeX1.xml"]] }, + parts: { "xl/embeddings/oleObject1.bin": "x", "xl/activeX/activeX1.xml": "" }, + }); + expect(unsupported(r.warnings)).toEqual([["oleObject", "xl/embeddings/oleObject1.bin"], ["activeX", "xl/activeX/activeX1.xml"]]); + }); + + it("Office web add-ins (task panes and web extensions): 'webExtension'", async () => { + const r = await readOf({ + sheets: [CELL], + parts: { + "xl/webextensions/taskpanes.xml": "", + "xl/webextensions/_rels/taskpanes.xml.rels": rels([["r1", "http://schemas.microsoft.com/office/2011/relationships/webextension", "webextension1.xml"]]), + "xl/webextensions/webextension1.xml": "", + }, + override: { "_rels/.rels": rels([["rId1", "officeDocument", "xl/workbook.xml"], ["rW", "http://schemas.microsoft.com/office/2011/relationships/webextensiontaskpanes", "xl/webextensions/taskpanes.xml"]]) }, + }); + expect(unsupported(r.warnings)).toEqual([["webExtension", "xl/webextensions/taskpanes.xml"]]); + expect(r.warnings[0]!.message).toMatch(/^The workbook contains Office web add-ins/); + }); + + it("attached toolbars belong to the VBA family: 'vbaProject'", async () => { + const r = await readOf({ + sheets: [CELL], + workbookRels: [["rT", "http://schemas.microsoft.com/office/2006/relationships/attachedToolbars", "attachedToolbars.bin"]], + parts: { "xl/attachedToolbars.bin": "x" }, + }); + expect(unsupported(r.warnings)).toEqual([["vbaProject", "xl/attachedToolbars.bin"]]); + }); +}); + +describe("hostile relationships parts the scan reads", () => { + const nested = (relsXml: string): BuildOptions => ({ sheets: [CELL], sheetRels: { 0: [["rD", "drawing", "../drawings/drawing1.xml"]] }, parts: { "xl/drawings/drawing1.xml": "", "xl/drawings/_rels/drawing1.xml.rels": relsXml } }); + it("a DTD in a nested relationships part throws XML_DTD_FORBIDDEN (2.4.0 read the file)", async () => { + await expect(readOf(nested(`]>`))).rejects.toMatchObject({ code: "XML_DTD_FORBIDDEN" }); + }); + it("a DTD in the relationships part of a sheet left out by `sheets` throws too", async () => { + const o: BuildOptions = { sheets: [CELL, CELL], sheetRels: { 1: [["rD", "drawing", "../drawings/drawing1.xml"]] } }; + const bytes = await build({ ...o, override: { "xl/worksheets/_rels/sheet2.xml.rels": `` } }); + await expect(read(bytes, { sheets: [0] })).rejects.toMatchObject({ code: "XML_DTD_FORBIDDEN" }); + }); +}); + describe("existing kinds found deeper in the graph", () => { it("an OLE object referenced only from a drawing is reported as 'oleObject'", async () => { const r = await readOf({ From 0e08fb80b7364a7827cd0d98a529f491b33ca70b Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 12:29:01 +0100 Subject: [PATCH 3/6] JSE-72 review 2: strict part names, no [trash] exemption, linear decoding - Equivalent zip entry names (equal after percent-decoding and case folding) are an invalid package: ZIP_INVALID. Package.shadowed is gone. - The [trash]/ exemption is removed; unreferencedPart and the new invalidPartName warnings list every name in a new `parts` field. - invalidPartName: zip entry names and relationship targets OPC forbids (%2F or %5C in a segment, percent-encoded dot segments, a trailing dot). Such a target is followed both as a decoder reads it (as 2.4.0 did) and literally, so content behind it is found either way. - canonicalPartName is one hand-written linear pass with no decoder calls, decodes once and is idempotent (a bare % becomes %25); entry keys are computed once. The Package constructor consults the signal for every entry. - Every Override/Default content type of a part is checked, so a later passive type cannot hide an active one. More content types: templates, add-ins, slides, application/vnd.ms-office.oleObject. - Docs and changeset list the behaviour changes against 2.4.0. --- .changeset/package-scan-active-content.md | 4 +- docs/api.md | 14 +- .../src/internal/read/context.ts | 3 +- .../javascript-excel/src/internal/read/opc.ts | 291 ++++++++++++------ .../src/internal/read/reader.ts | 16 +- .../src/internal/read/scan.ts | 99 +++--- packages/javascript-excel/src/warnings.ts | 11 +- .../test/read/helpers.test.ts | 50 ++- .../test/read/name-cost.test.ts | 74 +++++ .../test/read/package-scan.test.ts | 164 ++++++++-- 10 files changed, 557 insertions(+), 169 deletions(-) create mode 100644 packages/javascript-excel/test/read/name-cost.test.ts diff --git a/.changeset/package-scan-active-content.md b/.changeset/package-scan-active-content.md index b13ad95..67a3211 100644 --- a/.changeset/package-scan-active-content.md +++ b/.changeset/package-scan-active-content.md @@ -2,4 +2,6 @@ "javascript-excel": minor --- -`read` (and `importDataset`, which passes read warnings on) now walks the whole relationship graph of the package and reports more content it does not read as `UNSUPPORTED_PART`, with four new `partKind` values: `'activeX'` (ActiveX controls: a `control` or `activeXControlBinary` relationship, or a part with the ActiveX content type), `'embeddedPackage'` (a `package` relationship, such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a ribbon customisation: the root `ui/extensibility` relationship of Office 2007 or 2010) `'webExtension'` (Office web add-ins) and `'unreferencedPart'` (one warning for all parts no relationship reaches, such as a `vbaProject.bin` or an executable placed in the zip; entries under exactly `[trash]/`, Office's folder for discarded parts, are exempt). The scan also finds `'oleObject'`, `'vbaProject'` (now also attached toolbars and VBA signatures), `'externalLink'`, `'connections'`, `'queryTable'` and `'macrosheet'` where they were not reported before: under a drawing, under a table, or on a sheet left out by the `sheets` option. Excel 4 macro sheets with Microsoft's `xlMacrosheet` and `xlIntlMacrosheet` relationship types are now reported as `'macrosheet'`. Relationship types are compared case-insensitively, and a part with the content type of an ActiveX control, OLE object, VBA project, macro sheet, web add-in or embedded Office document is reported as that kind whatever relationship reaches it. Part names are compared in OPC canonical form (percent-escapes decoded as UTF-8 on both sides, except `%2F`, `%5C` and `%25`; only literal `.` and `..` are dot segments), so a percent-encoded target such as `image%201.png` reaches its entry and `%2E%2E` no longer acts as `..`. Because the scan parses the relationships parts of every reached part, a DTD or an over-deep XML in one of them (also under a sheet that is not read) now throws `XML_DTD_FORBIDDEN` or `LIMIT_EXCEEDED`; 2.4.0 read such a file. Drawings, images, comments and the other passive kinds are reported as before. The scan reads only relationships parts, within the existing zip and XML limits, and never inflates the parts it reports; a relationships part that is not well-formed XML is reported as unreferenced instead of failing the read. Existing warnings keep their shape; a `switch` over `ExcelPartKind` needs a `default` branch, as documented. The test corpus (files from LibreOffice and openpyxl, and every file of the conformance corpus this library writes) gives no new warnings. +`read` (and `importDataset`, which passes read warnings on) now walks the whole relationship graph of the package and reports more content it does not read as `UNSUPPORTED_PART`, with six new `partKind` values: `'activeX'` (ActiveX controls), `'embeddedPackage'` (a `package` relationship, such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a ribbon customisation: the root `ui/extensibility` relationship of Office 2007 or 2010), `'webExtension'` (Office web add-ins), `'invalidPartName'` (a zip entry name or relationship target OPC forbids: `%2F` or `%5C` in a segment, a percent-encoded dot segment, a segment ending in a dot) and `'unreferencedPart'` (a part no relationship reaches, such as a `vbaProject.bin` or an executable placed in the zip). The last two come as one warning each, with every name in a new `parts` field on the warning (bounded by `maxEntries`). Nothing is exempt by name: discarded parts Office 2007/2010 left under `[trash]/` are reported too; a consumer that accepts them can check that every name in `parts` starts with `[trash]/`. The scan also finds `'oleObject'`, `'vbaProject'` (now also attached toolbars and VBA signatures), `'externalLink'`, `'connections'`, `'queryTable'` and `'macrosheet'` where they were not reported before: under a drawing, under a table, or on a sheet left out by the `sheets` option. Excel 4 macro sheets with Microsoft's `xlMacrosheet` and `xlIntlMacrosheet` relationship types are now reported as `'macrosheet'`. Relationship types are compared case-insensitively, and a part with the content type of an ActiveX control, OLE object, VBA project, macro sheet, web add-in or embedded Office file (documents, templates, add-ins, slides) is reported as that kind whatever relationship reaches it; equivalent Overrides in `[Content_Types].xml` are all checked. Drawings, images, comments and the other passive kinds are reported as before. The scan reads only relationships parts, within the existing zip and XML limits, never inflates the parts it reports, and consults the signal throughout; a relationships part that is not well-formed XML is reported as unreferenced instead of failing the read. Existing warnings keep their shape; a `switch` over `ExcelPartKind` needs a `default` branch, as documented. The test corpus (files from LibreOffice and openpyxl, and every file of the conformance corpus this library writes) gives no new warnings. + +Behaviour changes against 2.4.0: part names are compared in OPC canonical form (percent-escapes decoded once, as UTF-8, on both sides; `%2F`, `%5C`, `%25` and invalid bytes kept encoded), so percent-encoded zip entry names are now found where 2.4.0 reported `MISSING_PART` or `NOT_XLSX`, while a target matched to an entry only because 2.4.0 decoded the target and not the entry name (a literal `%` spelled differently on the two sides) no longer matches. Two zip entries with equivalent names (for example `a b` and `a%20b`) now throw `ZIP_INVALID`, as names that differ only in case already did. Because the scan parses the relationships parts of every reached part, a DTD or an over-deep XML in one of them (also under a sheet that is not read) now throws `XML_DTD_FORBIDDEN` or `LIMIT_EXCEEDED`; 2.4.0 read such a file. diff --git a/docs/api.md b/docs/api.md index 623076e..e5fa2f9 100644 --- a/docs/api.md +++ b/docs/api.md @@ -878,8 +878,9 @@ How the reader works, as far as the API is concerned: - **Unread parts are not lost at the zip level.** The reader parses only the parts the model represents, but the archive stays addressable by part name until the read ends, and an internal (not yet public) option returns every unparsed part byte for byte. A later release can use it to carry drawings, comments, VBA or custom XML through a read-modify-write. - Unsupported content (drawings, charts, comments, pivot tables, tables, OLE objects, form controls, VBA, external links, chart sheets, …) gives one `UNSUPPORTED_PART` warning per kind. Chart, dialog and macro sheets are not worksheets: they are left out of `sheets` and `readSheetNames`, and defined names local to them are dropped. - **The package scan** (since 2.5). After the sheets, the reader walks the whole relationship graph, from the package root through the workbook and every sheet (also sheets left out by `sheets`) to every part those reach (drawings, VML drawings, tables, ActiveX parts, …). It reads only relationships parts, each once, within the zip and XML limits, and never inflates the parts it finds. It reports, once per kind, the kinds that are active or embedded content or a link out of the file, wherever they sit: `'activeX'` (a `control` or `activeXControlBinary` relationship), `'embeddedPackage'` (a `package` relationship, a file such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a root `…/relationships/ui/extensibility` relationship, 2006 and 2007 namespaces: a ribbon customisation, `customUI/customUI.xml` or `customUI14.xml`), `'webExtension'` (an Office web add-in: the `webextensiontaskpanes` and `webextension` relationships, `xl/webextensions/`), and `'oleObject'`, `'vbaProject'`, `'externalLink'`, `'connections'`, `'queryTable'` and `'macrosheet'` where the workbook's and the read sheets' own relationships did not already report them (an OLE object referenced from a drawing, a query table under a table, an ActiveX control on a sheet not read). `'vbaProject'` covers the VBA family: the project, its signatures (`vbaProjectSignature`, `…Agile`, `…V3`), `wordVbaData` and toolbars attached to a macro workbook (`attachedToolbars`, `xl/attachedToolbars.bin`). Excel 4 macro sheets are macro sheets under all three relationship types, ECMA `…/macrosheet` and Microsoft's `…/xlMacrosheet` and `…/xlIntlMacrosheet` (before 2.5 only the first was reported; all three were left out of `sheets`). -- **Matching** (since 2.5). Relationship types are compared without regard to case (`OLEOBJECT` is `oleObject`). A part's content type is a backstop: a part with the content type of an ActiveX control (`application/vnd.ms-office.activeX+xml`, `application/vnd.ms-office.activeX`), an OLE object (`application/vnd.openxmlformats-officedocument.oleObject`), VBA (`application/vnd.ms-office.vbaProject`, `…vbaProjectSignature`, `application/vnd.ms-excel.attachedToolbars`), a macro sheet (`application/vnd.ms-excel.macrosheet+xml`, `…intlmacrosheet+xml`), a web add-in (`application/vnd.ms-office.webextension+xml`, `…webextensiontaskpanes+xml`) or an embedded Office document (Word, Excel and PowerPoint documents, macro-enabled ones included) is reported as that kind whatever relationship reaches it, so an `image` relationship to an OLE object gives both `'image'` and `'oleObject'`. Part names are matched as OPC defines equivalence: case-insensitively, after decoding percent-escapes as UTF-8, both in the relationship target and in the zip entry name, so `../media/image%201.png` reaches the entry `xl/media/image%201.png` (and `xl/media/image 1.png`), and `%C3%A4` reaches `ä`. `%2F`, `%5C` and `%25` are never decoded, and only a literal `.` or `..` segment is a dot segment, so `%2E%2E`, `%2F`, `%5C` and a double encoding such as `%2541` stay part of one name and cannot reach another part. Before 2.5 the target was decoded in full before its dot segments were resolved, so `%2E%2E/` acted as `../`. When two entries have equivalent names that differ in more than case (`a b` and `a%20b`), relationships reach the first in zip order and the other is unreferenced; entries that differ only in case still throw `ZIP_INVALID`. Drawings, images, comments, tables, pivots and the other passive kinds are reported as before, from the workbook's and the read sheets' own relationships only, so an image inside a drawing still gives just `'drawing'`. -- **Unreferenced parts** (since 2.5). A part no relationship reaches (a `vbaProject.bin` without a relationship, an executable dropped into the zip, with or without a content type) gives one `UNSUPPORTED_PART` warning with `partKind: 'unreferencedPart'`, `part` naming the first such part in zip order and the message their number. Parts reached only through an unreferenced part are unreferenced too, and so is a relationships part that is not well-formed XML, together with the parts only it would reach (the read goes on). Not reported: `[Content_Types].xml`, the relationships part of a reached part, and entries whose zip name starts with exactly `[trash]/`, the folder at the package root where Office 2007 and 2010 moved parts they discarded. The match is exact: `[TRASH]/`, `%5Btrash%5D/` or `xl/[trash]/` are reported like any other unreferenced part, since there is no evidence that Office wrote another spelling. So an entry under `[trash]/` is never reported, whatever it holds. Excel cannot load it either (parts load only through relationships), but its bytes are carried in the file: a consumer that stores or forwards files and cares about every byte they carry must look for `[trash]/` entries itself. Nothing else is exempt by name. The thumbnail (`docProps/thumbnail.*`), printer settings (`xl/printerSettings/*.bin`), `xl/calcChain.xml`, custom XML and the document properties are parts with their own relationship types (from the package root, a sheet and the workbook), so in a well-formed package they are reached and never count as unreferenced; an orphaned copy of one does, because an exemption by name would be the place to hide a payload. Evidence: none of the test corpus files (the openpyxl, LibreOffice and import fixtures and every conformance-corpus file this library writes) has an unreferenced part. Files saved by Excel and Numbers are not in the corpus; a part they leave unreferenced would be reported, and is a bug report worth filing. +- **Matching** (since 2.5). Relationship types are compared without regard to case (`OLEOBJECT` is `oleObject`). A part's content type is a backstop: a part with the content type of an ActiveX control (`application/vnd.ms-office.activeX+xml`, `application/vnd.ms-office.activeX`), an OLE object (`application/vnd.openxmlformats-officedocument.oleObject`, `application/vnd.ms-office.oleObject`), VBA (`application/vnd.ms-office.vbaProject`, `…vbaProjectSignature`, `application/vnd.ms-excel.attachedToolbars`), a macro sheet (`application/vnd.ms-excel.macrosheet+xml`, `…intlmacrosheet+xml`), a web add-in (`application/vnd.ms-office.webextension+xml`, `…webextensiontaskpanes+xml`) or an embedded Office file (Word, Excel and PowerPoint documents, templates, add-ins, slides and slide shows, macro-enabled or not) is reported as that kind whatever relationship reaches it, so an `image` relationship to an OLE object gives both `'image'` and `'oleObject'`. When `[Content_Types].xml` lists several Overrides for equivalent part names (or several Defaults for one extension), each is checked, so a later passive type cannot hide an active one; `contentType` for format detection still takes the last, as before. Drawings, images, comments, tables, pivots and the other passive kinds are reported as before, from the workbook's and the read sheets' own relationships only, so an image inside a drawing still gives just `'drawing'`. +- **Part names** (since 2.5). Zip entry names and relationship targets are compared as OPC defines part-name equivalence: case-insensitively, after decoding percent-escapes once, as UTF-8, on both sides. So the target `../media/image%201.png` reaches the entry `xl/media/image%201.png` and `xl/media/image 1.png`, `%C3%A4` reaches `ä`, and an entry whose name is percent-encoded is found (2.4.0 compared the decoded target with the raw entry name, so it missed `x%6Cl/workbook.xml` and read such a file as `NOT_XLSX` or with `MISSING_PART`). The canonical form keeps `%2F`, `%5C`, `%25`, a `%` that starts no escape (as `%25`) and bytes that are not valid UTF-8 encoded, so a double encoding such as `%2541` stays the text `%41` and never reaches `A`; applying it again changes nothing. One consequence: 2.4.0 also matched a target such as `%2561` with an entry named `%61`, by decoding only the target; now the entry `%61` is the part `a`, and the target names the part `%61`, so they no longer match (in a 20,000-file name fuzz against 2.4.0 this affected 3 files, all with a literal `%` or `%25` spelled differently on the two sides). **Equivalent names are an invalid package**: two entries whose names are equal in this form, for example `a b` and `a%20b`, or `%5Btrash%5D/x` and `[trash]/x`, throw `ZIP_INVALID`, as entries that differ only in case always did; 2.4.0 read such a file. **Names OPC forbids** give one `UNSUPPORTED_PART` warning with `partKind: 'invalidPartName'` and every offending name in `parts`: a zip entry name, or a relationship target, with a segment that contains `%2F` or `%5C`, a percent-encoded dot segment (`%2E`, `%2E%2E`, `.%2E`), or a segment that ends in a dot (for an entry name this includes `.` and `..`; a target may use literal `.` and `..` as relative references). For a forbidden target, `parts` names the relationships part that holds it. Such a target is followed both as a decoder reads it (as 2.4.0 did: `%2F` and `%5C` separate segments, `%2E%2E` is `..`) and literally (the escapes are part of one name), so active content behind it is reported whichever way Excel resolves it; the reader reads the part the decoder's reading names, so a sheet behind `x/%2E%2E/worksheets/sheet1.xml` is read as in 2.4.0. +- **Unreferenced parts** (since 2.5). A part no relationship reaches (a `vbaProject.bin` without a relationship, an executable dropped into the zip, with or without a content type) gives one `UNSUPPORTED_PART` warning with `partKind: 'unreferencedPart'`: `part` names the first such part in zip order, `parts` lists every one in zip order, and the message gives their number. `parts` has at most one name per zip entry, so its length is bounded by `maxEntries` (each name by the zip format's 65,535 bytes); its strings are the entry names the zip already holds. Parts reached only through an unreferenced part are unreferenced too, and so is a relationships part that is not well-formed XML, together with the parts only it would reach (the read goes on). Not reported: `[Content_Types].xml` and the relationships part of a reached part. Nothing is exempt by name, `[trash]/` included: Office 2007 and 2010 could leave discarded parts in a `[trash]/` folder at the package root; Excel never loads them (parts load only through relationships), but their bytes are in the file, so they are reported like any other. A consumer that wants to accept such files can check that every name in `parts` starts with `[trash]/`. The thumbnail (`docProps/thumbnail.*`), printer settings (`xl/printerSettings/*.bin`), `xl/calcChain.xml`, custom XML and the document properties have their own relationship types, so in a well-formed package they are reached; an orphaned copy of one is reported, because an exemption by name would be the place to hide a payload. Evidence: none of the test corpus files (the openpyxl, LibreOffice and import fixtures and every conformance-corpus file this library writes) has an unreferenced part. Files saved by Excel and Numbers are not in the corpus; a part they leave unreferenced would be reported, and is a bug report worth filing. - Styles: each `cellXfs` entry is one frozen `Style` (§12 Q8). Pattern fills come back with `type: 'pattern'`, so `fill.type` tells pattern and gradient fills apart. A style records only what differs from the defaults: font 0 (the workbook default font), fills 0 and 1 (the required `none` and `gray125` placeholders) and border 0 are left out, and `numFmtId` 0 (General) gives no `numFmt`. `applyFont` and the other apply flags are ignored, as Excel does for cell formats. - Values: `t="s"`, `"inlineStr"` and `"str"` are strings (or rich text), with `_xHHHH_` escapes decoded; `"b"` booleans; `"e"` errors, including codes newer than the seven of ECMA-376 (`#SPILL!`, `#CALC!`, …), returned as written; `"d"` ISO dates; numbers otherwise, converted to `Date` when their number format is a date format (§3.4.1). A formula's cached value sets `value` and `type`; without one the cell is `type: 'empty'` with its `formula`. Shared formulas are expanded (§12 Q6), except from a master longer than 8,192 characters and except copies longer than `maxCellTextLength` (§3.4.2); data-table formulas (`t="dataTable"`) give their cached values only. - **`rawText`** (from 2.1.0): converting `` to a JavaScript number loses what the file says: `1234567890123456789` reads as `1234567890123456800`, `50.30` as `50.3`, `1E-7` as `1e-7`, `-0` as `0`, and a `t="d"` cell is always a `Date`. With `rawText: true`, such cells also get `cell.rawText`, the characters of `` exactly as stored: XML entities and character references decoded and line ends normalised (as for any XML text), nothing trimmed, no `_xHHHH_` decoding. `value` and `type` are what they would be without the option, so the cell still says it was a number or a date. Default false: no `rawText` key is added and the model is the same as before 2.1.0. The worker's `read` passes the option through; `importDataset` (§5.6) returns coerced column values, not cells, and does not take it. @@ -1712,6 +1713,7 @@ export interface ExcelWarning { sheet?: string; ref?: string; // cell or range partKind?: ExcelPartKind; // MISSING_PART, BROKEN_OPTIONAL_PART, UNSUPPORTED_PART only + parts?: string[]; // UNSUPPORTED_PART 'unreferencedPart' / 'invalidPartName' only (since 2.5): every name, `part` is the first dropped?: DroppedWarnings; // WARNINGS_TRUNCATED only } @@ -1724,7 +1726,7 @@ export type ExcelPartKind = | 'table' | 'oleObject' | 'ctrlProp' | 'image' | 'vbaProject' | 'externalLink' | 'connections' | 'queryTable' | 'slicer' | 'slicerCache' | 'timeline' | 'chartsheet' | 'dialogsheet' | 'macrosheet' // UNSUPPORTED_PART, found by the package scan wherever they sit (since 2.5, §5.2) - | 'activeX' | 'embeddedPackage' | 'customUI' | 'webExtension' | 'unreferencedPart'; + | 'activeX' | 'embeddedPackage' | 'customUI' | 'webExtension' | 'invalidPartName' | 'unreferencedPart'; export interface DroppedWarnings { total: number; // warnings not recorded @@ -1743,7 +1745,7 @@ export function isDataLossWarning(warning: ExcelWarning | ExcelWarningCode): boo | Warning code | Data loss | Situation and recovery | |---|---|---| -| `UNSUPPORTED_PART` | yes | Charts, drawings, pivots, comments, VBA, … are outside the model and not in the result; one warning per kind (so it cannot flood the list), `partKind` names it. Since 2.5 also ActiveX controls (`'activeX'`), embedded packages (`'embeddedPackage'`), ribbon customisations (`'customUI'`), Office web add-ins (`'webExtension'`) and parts no relationship reaches (`'unreferencedPart'`, one warning for all of them), found anywhere in the package (§5.2, package scan). The cell values are complete; filter by `partKind` to accept the kinds you do not need | +| `UNSUPPORTED_PART` | yes | Charts, drawings, pivots, comments, VBA, … are outside the model and not in the result; one warning per kind (so it cannot flood the list), `partKind` names it. Since 2.5 also ActiveX controls (`'activeX'`), embedded packages (`'embeddedPackage'`), ribbon customisations (`'customUI'`), Office web add-ins (`'webExtension'`), names OPC forbids (`'invalidPartName'`) and parts no relationship reaches (`'unreferencedPart'`), found anywhere in the package (§5.2, package scan); the last two are one warning each, with every name in `parts`. The cell values are complete; filter by `partKind` to accept the kinds you do not need | | `INVALID_STYLE_INDEX` | no | Cell refers to a missing `xf`; default style used. Declared for compatibility; 2.x leaves such a cell unstyled without a warning | | `INVALID_SHARED_STRING` | yes | Index out of range; cell left empty | | `CELL_OUT_OF_BOUNDS` / `INVALID_CELL_REF` | yes | Cell skipped | @@ -1804,8 +1806,8 @@ if (lost.length) throw new Error(`Refused: ${[...new Set(lost.map((w) => w.code) | **Formula injection into CSV** | Guard on by default (§5.3). | | **Malicious hyperlinks** | The writer allows only `http`, `https` and `mailto` by default, and rejects `javascript:`, `data:`, `vbscript:` and anything else not listed. The reader returns targets verbatim (it cannot know the consumer's policy): apps that render them, such as the viewer, must check the scheme. | | **External references** | External links, OLE objects, DDE and data connections are not read or followed. The reader resolves relationships only within the package. | -| **Active, embedded and hidden content** (a file that is harmless to this reader but carries something for whoever opens it next in Excel) | Never run, opened or inflated, and reported so an app can refuse the file (since 2.5): the package scan (§5.2) walks the whole relationship graph and reports ActiveX controls (`'activeX'`), embedded files (`'embeddedPackage'`), ribbon customisations with callbacks (`'customUI'`), Office web add-ins (`'webExtension'`), OLE objects, VBA (with attached toolbars), Excel 4 macro sheets, external links, data connections and query tables wherever they sit, including under drawings and on sheets not read, by relationship type (case-insensitively) and by content type, and any part no relationship reaches (`'unreferencedPart'`), such as a `vbaProject.bin` or an executable placed in the zip without a relationship. Part names are compared in OPC canonical form, so percent-encoding can neither hide a reached part nor make one entry stand for another. Only entries under exactly `[trash]/` are exempt; their bytes stay in the file, so check for them yourself if that matters (§5.2). The scan reads relationships parts only, within the zip and XML limits. To refuse such files, check `warnings` for `UNSUPPORTED_PART` with these `partKind`s. | -| **Hostile relationships parts** | Since 2.5 the scan parses the relationships part of every reached part, also of sheets left out by `sheets` and of nested parts (drawings, tables, …). 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. A relationships part that is only malformed XML does not throw: it and the parts only it reaches are reported as unreferenced. | +| **Active, embedded and hidden content** (a file that is harmless to this reader but carries something for whoever opens it next in Excel) | Never run, opened or inflated, and reported so an app can refuse the file (since 2.5): the package scan (§5.2) walks the whole relationship graph and reports ActiveX controls (`'activeX'`), embedded files (`'embeddedPackage'`), ribbon customisations with callbacks (`'customUI'`), Office web add-ins (`'webExtension'`), OLE objects, VBA (with attached toolbars), Excel 4 macro sheets, external links, data connections and query tables wherever they sit, including under drawings and on sheets not read, by relationship type (case-insensitively) and by content type, and any part no relationship reaches (`'unreferencedPart'`), such as a `vbaProject.bin` or an executable placed in the zip without a relationship. Part names are compared in OPC canonical form, decoded once on both sides; two entries with equivalent names throw `ZIP_INVALID`, and names OPC forbids (encoded separators or dot segments, a trailing dot) are reported as `'invalidPartName'`, with the target followed under both readings, so percent-encoding can neither hide a part nor make one entry stand for another. Nothing is exempt by name, Office's `[trash]/` folder included (§5.2). Decoding names is one linear pass, and the signal is consulted for every zip entry while names are indexed. The scan reads relationships parts only, within the zip and XML limits. To refuse such files, check `warnings` for `UNSUPPORTED_PART` with these `partKind`s. | +| **Hostile relationships parts** | Since 2.5 the scan parses the relationships part of every reached part, also of sheets left out by `sheets` and of nested parts (drawings, tables, …). 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). | diff --git a/packages/javascript-excel/src/internal/read/context.ts b/packages/javascript-excel/src/internal/read/context.ts index 3264dbe..d175b7f 100644 --- a/packages/javascript-excel/src/internal/read/context.ts +++ b/packages/javascript-excel/src/internal/read/context.ts @@ -69,12 +69,13 @@ export class ReadContext { * dropped warning adds WARNINGS_TRUNCATED at that point, as in 2.0.0; its * `dropped` counts grow until the read ends. */ - warn(code: ExcelWarningCode, message: string, where?: { part?: string; sheet?: string; ref?: string; partKind?: ExcelPartKind }): void { + warn(code: ExcelWarningCode, message: string, where?: { part?: string; sheet?: string; ref?: string; partKind?: ExcelPartKind; parts?: string[] }): void { const w: ExcelWarning = { code, message }; if (where?.part !== undefined) w.part = where.part; if (where?.sheet !== undefined) w.sheet = where.sheet; if (where?.ref !== undefined) w.ref = where.ref; if (where?.partKind !== undefined) w.partKind = where.partKind; + if (where?.parts !== undefined) w.parts = where.parts; 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); diff --git a/packages/javascript-excel/src/internal/read/opc.ts b/packages/javascript-excel/src/internal/read/opc.ts index e61e024..5d35827 100644 --- a/packages/javascript-excel/src/internal/read/opc.ts +++ b/packages/javascript-excel/src/internal/read/opc.ts @@ -1,6 +1,7 @@ /** - * Open Packaging Conventions for the reader: part lookup (case-insensitive, - * as OPC requires), [Content_Types].xml and relationship parts. Internal. + * Open Packaging Conventions for the reader: part lookup by part-name + * equivalence (percent-decoded once, case-insensitive, as OPC requires), + * [Content_Types].xml and relationship parts. Internal. */ import { FormatError } from "../../errors"; @@ -14,41 +15,66 @@ export interface Relationship { /** The type URI's last path segment, e.g. 'worksheet', 'officeDocument'. Transitional and Strict URIs agree on it. */ kind: string; type: string; - /** Resolved part name without a leading '/', or the raw target when external. */ + /** + * Resolved part name without a leading '/', in canonical form + * (`canonicalPartName`), or the raw target when external. For a target OPC + * forbids (see `forbidden`), this is how a decoder reads it: `%2F` and + * `%5C` separate segments and `%2E` makes dot segments, as 2.4.0 resolved it. + */ target: string; + /** + * The target uses a name OPC forbids (ECMA-376 Part 2 §6.2.2): a segment + * with `%2F` or `%5C`, a percent-encoded dot segment (`%2E`, `%2E%2E`, + * `.%2E`), or a segment other than `.` and `..` that ends in a dot. + */ + forbidden?: boolean; + /** For a forbidden target, the part it names when escapes are taken literally, if that differs from `target`. */ + literalTarget?: string; external: boolean; } export class Package { - /** partKey(name) -> entry; the first entry of a key in zip order. */ + /** partKey(name) -> entry. */ private readonly parts = new Map(); + /** entry -> partKey(entry.name), computed once. */ + private readonly keys = new Map(); + /** Zip entries whose names OPC forbids (see `forbiddenName`), in zip order. */ + readonly forbiddenNames: string[] = []; + /** partKey(part name) -> content types, in the order [Content_Types].xml lists them. */ + private readonly overrides = new Map(); + /** Extension (lower case) -> content types. */ + private readonly defaults = new Map(); + /** - * Entries whose name is equivalent to an earlier entry's (they differ in - * percent-encoding, e.g. `a b` and `a%20b`). No relationship can reach them, - * so the package scan lists them as unreferenced. + * Indexes the zip entries by part name. Two entries whose names are + * equivalent (equal in canonical form, case-insensitively) make the package + * invalid: ZIP_INVALID, as OPC requires. Consults the signal for every + * entry (each costs work linear in its name, up to 64 KB). */ - readonly shadowed: ZipEntryInfo[] = []; - /** partKey(part name) -> content type. */ - private readonly overrides = new Map(); - /** Extension (lower case) -> content type. */ - private readonly defaults = new Map(); - constructor(readonly ctx: ReadContext) { - for (const e of ctx.zip.entries) { + const entries = ctx.zip.entries; + for (let i = 0; i < entries.length; i++) { + ctx.checkAbort(); + const e = entries[i]!; if (e.name.endsWith("/")) continue; // directory entries const key = partKey(e.name); const earlier = this.parts.get(key); if (earlier) { - if (earlier.name.toLowerCase() !== e.name.toLowerCase()) { - this.shadowed.push(e); - continue; - } - throw new FormatError("ZIP_INVALID", `Part names ${excerpt(earlier.name)} and ${excerpt(e.name)} differ only in case.`, { + const how = earlier.name.toLowerCase() === e.name.toLowerCase() ? "differ only in case" : "are equivalent (they differ only in case or percent-encoding)"; + throw new FormatError("ZIP_INVALID", `Part names ${excerpt(earlier.name)} and ${excerpt(e.name)} ${how}.`, { details: { entry: e.name }, }); } this.parts.set(key, e); + this.keys.set(e, key); + if (forbiddenName(e.name, false)) this.forbiddenNames.push(e.name); } + ctx.checkAbort(); + } + + /** The lookup key of a zip entry of this package (partKey of its name, computed once). */ + keyOf(entry: ZipEntryInfo): string { + return this.keys.get(entry) ?? partKey(entry.name); } part(name: string): ZipEntryInfo | undefined { @@ -67,11 +93,11 @@ export class Package { if (name === "Default") { const ext = a.get("Extension"); const type = a.get("ContentType"); - if (ext && type) this.defaults.set(ext.toLowerCase(), type); + if (ext && type) push(this.defaults, ext.toLowerCase(), type); } else if (name === "Override") { const part = a.get("PartName"); const type = a.get("ContentType"); - if (part && type) this.overrides.set(partKey(part), type); + if (part && type) push(this.overrides, partKey(part), type); } }, close: () => {}, @@ -79,17 +105,28 @@ export class Package { }); } + /** The content type of a part: the last Override for an equivalent name, else the last Default for its extension (as 2.4.0). */ contentType(name: string): string | undefined { + return this.contentTypes(name).at(-1); + } + + /** + * Every content type [Content_Types].xml gives the part: all Overrides with + * an equivalent part name, else all Defaults for its extension. The package + * scan checks each, so a later passive entry cannot hide an active one. + */ + contentTypes(name: string): string[] { const key = partKey(name); const o = this.overrides.get(key); if (o) return o; const dot = key.lastIndexOf("."); - return dot === -1 ? undefined : this.defaults.get(key.slice(dot + 1)); + const slash = key.lastIndexOf("/"); + return (dot > slash ? this.defaults.get(key.slice(dot + 1)) : undefined) ?? []; } /** Content types of all overrides (for format detection). */ get overrideTypes(): string[] { - return [...this.overrides.values()]; + return [...this.overrides.values()].flat(); } /** The relationships part of `source` ('' for the package), whether or not it exists. */ @@ -141,13 +178,13 @@ export class Package { const target = a.get("Target"); if (!id || !type || target === undefined) return; const external = (a.get("TargetMode") ?? "").toLowerCase() === "external"; - out.push({ - id, - type, - kind: type.slice(type.lastIndexOf("/") + 1), - target: external ? target : resolveTarget(dir, target), - external, - }); + const rel: Relationship = { id, type, kind: type.slice(type.lastIndexOf("/") + 1), target: external ? target : resolveTarget(dir, target), external }; + if (!external && forbiddenName(stripFragment(target), true)) { + rel.forbidden = true; + const literal = resolveTargetLiteral(dir, target); + if (partKey(literal) !== partKey(rel.target)) rel.literalTarget = literal; + } + out.push(rel); }, close: () => {}, text: () => {}, @@ -160,71 +197,134 @@ function stripSlash(name: string): string { return name.startsWith("/") ? name.slice(1) : name; } +function push(map: Map, key: string, value: string): void { + const list = map.get(key); + if (list) list.push(value); + else map.set(key, [value]); +} + +function stripFragment(target: string): string { + const hash = target.indexOf("#"); + return hash === -1 ? target : target.slice(0, hash); +} + +/** + * True when a part name or relationship target uses a segment OPC forbids + * (ECMA-376 Part 2 §6.2.2): one containing `%2F` or `%5C`, a percent-encoded + * dot segment (`%2E`, `%2E%2E`, `.%2E`, `%2E.`), or one ending in a dot. For + * a relationship target (`isTarget`), the literal `.` and `..` segments of a + * relative reference are allowed; in a zip entry name they are forbidden too. + * Segments are split on `/` and, in a target, on `\`. Linear in the length. + */ +export function forbiddenName(name: string, isTarget: boolean): boolean { + const n = name.length; + let segStart = 0; + for (let i = 0; i <= n; i++) { + const c = i < n ? name.charCodeAt(i) : 0x2f; + if (c !== 0x2f && !(isTarget && c === 0x5c)) continue; + if (i > segStart && forbiddenSegment(name, segStart, i, isTarget)) return true; + segStart = i + 1; + } + return false; +} + +function forbiddenSegment(s: string, from: number, to: number, isTarget: boolean): boolean { + // Scan the segment once: encoded separators, and whether it ends in a (possibly encoded) dot. + let lastIsDot = false; + let literalDotSegment = true; + for (let i = from; i < to; i++) { + const c = s.charCodeAt(i); + if (c === 0x25 && i + 2 < to) { + const h = (s.charCodeAt(i + 1) << 8) | (s.charCodeAt(i + 2) | 0x20); + if (h === ((0x32 << 8) | 0x66) || h === ((0x35 << 8) | 0x63)) return true; // %2F, %5C + if (h === ((0x32 << 8) | 0x65)) { + lastIsDot = true; // %2E + literalDotSegment = false; + i += 2; + continue; + } + } + lastIsDot = c === 0x2e; + if (!lastIsDot) literalDotSegment = false; + } + if (!lastIsDot) return false; + if (isTarget && literalDotSegment && to - from <= 2) return false; // "." and ".." in a relative reference + return true; +} + /** * Part-name equivalence (OPC, ECMA-376 Part 2 §6.2.2.3 and the zip mapping of - * §7.3.4): `name` with percent-escapes decoded (as UTF-8), except `%2F`, `%5C` - * and `%25`, which stay encoded (upper-case hex) so that an escape can never - * become a folder separator or a new escape. Idempotent. Not lower-cased. + * §7.3.4): `name` with its percent-escapes decoded once, as UTF-8. Kept + * encoded (upper-case hex), so that nothing decoded can act as structure or + * as a new escape: `%2F`, `%5C`, `%25`, a `%` that does not start an escape + * (written `%25`), and each byte that is not part of a valid UTF-8 sequence. + * Not lower-cased. Idempotent: canonicalPartName(canonicalPartName(s)) === + * canonicalPartName(s). One linear pass, no decoder calls. */ export function canonicalPartName(name: string): string { - if (!name.includes("%")) return name; + let i = name.indexOf("%"); + if (i === -1) return name; + const n = name.length; let out = ""; - let i = 0; - const bytes: number[] = []; - const flush = (): void => { - if (!bytes.length) return; - // Each valid UTF-8 sequence is decoded; a byte that starts none stays an escape. - let j = 0; - while (j < bytes.length) { - const lead = bytes[j]!; - const len = lead < 0x80 ? 1 : lead >= 0xc2 && lead <= 0xdf ? 2 : lead >= 0xe0 && lead <= 0xef ? 3 : lead >= 0xf0 && lead <= 0xf4 ? 4 : 0; - const text = len && j + len <= bytes.length ? utf8(bytes.slice(j, j + len)) : undefined; - if (text === undefined) { - out += hex(lead); - j++; + /** Start of the input not yet copied: text that canonicalises to itself is copied in one slice. */ + let from = 0; + const emit = (end: number, text: string, next: number): void => { + out += name.slice(from, end) + text; + from = next; + }; + while (i < n) { + if (name.charCodeAt(i) !== 0x25) { + i = name.indexOf("%", i); + if (i === -1) break; + continue; + } + const b = hexByte(name, i); + if (b < 0) { + emit(i, "%25", i + 1); // a '%' that starts no escape + i++; + continue; + } + if (b === 0x25 || b === 0x2f || b === 0x5c || b >= 0x80) { + // Kept encoded unless it starts a valid UTF-8 sequence. + const len = b >= 0xc2 && b <= 0xdf ? 2 : b >= 0xe0 && b <= 0xef ? 3 : b >= 0xf0 && b <= 0xf4 ? 4 : 0; + let cp = len === 2 ? b & 0x1f : len === 3 ? b & 0x0f : b & 0x07; + let ok = len > 0; + for (let k = 1; ok && k < len; k++) { + const cb = hexByte(name, i + 3 * k); + if (cb < 0 || (cb & 0xc0) !== 0x80) ok = false; + else if (k === 1 && ((b === 0xe0 && cb < 0xa0) || (b === 0xed && cb > 0x9f) || (b === 0xf0 && cb < 0x90) || (b === 0xf4 && cb > 0x8f))) ok = false; + else cp = (cp << 6) | (cb & 0x3f); + } + if (ok) { + emit(i, String.fromCodePoint(cp), i + 3 * len); + i += 3 * len; } else { - out += text; - j += len; + // Already canonical when written with upper-case hex digits. + if (name.charCodeAt(i + 1) > 0x60 || name.charCodeAt(i + 2) > 0x60) emit(i, HEX[b]!, i + 3); + i += 3; } - } - bytes.length = 0; - }; - while (i < name.length) { - const m = name.charCodeAt(i) === 0x25 ? /^%([0-9A-Fa-f]{2})/.exec(name.slice(i, i + 3)) : null; - if (m) { - const byte = parseInt(m[1]!, 16); - if (byte === 0x2f || byte === 0x5c || byte === 0x25) { - flush(); - out += hex(byte); - } else bytes.push(byte); - i += 3; continue; } - flush(); - out += name[i]; - i++; + emit(i, String.fromCharCode(b), i + 3); + i += 3; } - flush(); - return out; + return from === 0 ? name : out + name.slice(from); } -interface FatalDecoder { - decode(input: Uint8Array): string; -} -let utf8Decoder: FatalDecoder | undefined; +const HEX: readonly string[] = Array.from({ length: 256 }, (_, b) => `%${b.toString(16).toUpperCase().padStart(2, "0")}`); -function utf8(bytes: number[]): string | undefined { - // Created on first use, the same global the part parser uses (context.ts). - utf8Decoder ??= new (globalThis as unknown as { TextDecoder: new (label: string, options: { fatal: boolean }) => FatalDecoder }).TextDecoder("utf-8", { fatal: true }); - try { - return utf8Decoder.decode(new Uint8Array(bytes)); - } catch { - return undefined; - } +/** The byte of the escape `%XX` at `i`, or -1. */ +function hexByte(s: string, i: number): number { + if (s.charCodeAt(i) !== 0x25 || i + 2 >= s.length) return -1; + const h = hexDigit(s.charCodeAt(i + 1)); + const l = hexDigit(s.charCodeAt(i + 2)); + return h < 0 || l < 0 ? -1 : (h << 4) | l; } -function hex(byte: number): string { - return `%${byte.toString(16).toUpperCase().padStart(2, "0")}`; +function hexDigit(c: number): number { + if (c >= 0x30 && c <= 0x39) return c - 0x30; + const l = c | 0x20; + return l >= 0x61 && l <= 0x66 ? l - 0x61 + 10 : -1; } /** The lookup key of a part name: canonical, no leading '/', lower case (part names compare case-insensitively). */ @@ -233,16 +333,31 @@ export function partKey(name: string): string { } /** - * Resolves a relationship target against the source part's folder. Only - * literal `.` and `..` segments are dot segments, and only a literal `/` or - * `\` separates segments; each segment is then put in canonical form - * (`canonicalPartName`), so `%2E%2E`, `%2F` and `%5C` stay part of a name. + * Resolves a relationship target against the source part's folder, as a + * decoder reads it (and as 2.4.0 did): `/`, `\`, `%2F` and `%5C` separate + * segments, and a segment that is `.` or `..` once `%2E` is decoded is a dot + * segment. Each other segment is put in canonical form once. For a target + * OPC allows this is the only reading; for others, see resolveTargetLiteral. */ export function resolveTarget(baseDir: string, target: string): string { - let t = target; - const hash = t.indexOf("#"); - if (hash !== -1) t = t.slice(0, hash); - t = t.replace(/\\/g, "/"); + const t = stripFragment(target).replace(/%2f|%5c|\\/gi, "/"); + const segments = t.startsWith("/") ? [] : baseDir.split("/").filter((s) => s !== ""); + for (const seg of t.split("/")) { + const dots = seg.length <= 6 ? seg.replace(/%2e/gi, ".") : seg; + if (dots === "" || dots === ".") continue; + if (dots === "..") segments.pop(); + else segments.push(canonicalPartName(seg)); + } + return segments.join("/"); +} + +/** + * Resolves a relationship target taking every escape literally: only `/` and + * `\` separate segments and only literal `.` and `..` are dot segments, so + * `%2E%2E`, `%2F` and `%5C` stay part of a name. + */ +export function resolveTargetLiteral(baseDir: string, target: string): string { + const t = stripFragment(target).replace(/\\/g, "/"); const segments = t.startsWith("/") ? [] : baseDir.split("/").filter((s) => s !== ""); for (const seg of t.split("/")) { if (seg === "" || seg === ".") continue; diff --git a/packages/javascript-excel/src/internal/read/reader.ts b/packages/javascript-excel/src/internal/read/reader.ts index d7c0947..5513583 100644 --- a/packages/javascript-excel/src/internal/read/reader.ts +++ b/packages/javascript-excel/src/internal/read/reader.ts @@ -190,8 +190,9 @@ export function warnUnsupportedParts(ctx: Pick): Promise { const ctx = pkg.ctx; @@ -202,6 +203,15 @@ async function warnScannedParts(pkg: Package, seen: Set): Promise const what = SCANNED_KINDS.get(f.kind) ?? UNSUPPORTED_RELATIONSHIPS.get(f.kind)!; ctx.warn("UNSUPPORTED_PART", `The workbook contains ${what}, which are not read.`, { part: f.part, partKind: f.kind }); } + const bad = scan.forbidden; + if (bad.length > 0) { + const first = bad[0]!; + const message = + bad.length === 1 + ? `The package uses a part name or relationship target that OPC forbids (in "${excerpt(first)}"); it is not read.` + : `The package uses ${bad.length} part names or relationship targets that OPC forbids (first in "${excerpt(first)}"); they are not read.`; + ctx.warn("UNSUPPORTED_PART", message, { part: first, partKind: "invalidPartName", parts: bad }); + } const n = scan.unreferenced.length; if (n > 0) { const first = scan.unreferenced[0]!; @@ -209,7 +219,7 @@ async function warnScannedParts(pkg: Package, seen: Set): Promise n === 1 ? `The package contains 1 part that no relationship refers to ("${excerpt(first)}"), which is not read.` : `The package contains ${n} parts that no relationship refers to (first: "${excerpt(first)}"), which are not read.`; - ctx.warn("UNSUPPORTED_PART", message, { part: first, partKind: "unreferencedPart" }); + ctx.warn("UNSUPPORTED_PART", message, { part: first, partKind: "unreferencedPart", parts: scan.unreferenced }); } } diff --git a/packages/javascript-excel/src/internal/read/scan.ts b/packages/javascript-excel/src/internal/read/scan.ts index d47a49e..0ff1b35 100644 --- a/packages/javascript-excel/src/internal/read/scan.ts +++ b/packages/javascript-excel/src/internal/read/scan.ts @@ -76,6 +76,7 @@ const CONTENT_TYPES: ReadonlyMap = new Map = new Map { const ctx = pkg.ctx; const found: ScannedPart[] = []; const foundKeys = new Set(); - /** Lower-case names of the parts accounted for. */ + const forbidden = new Set(pkg.forbiddenNames); + /** partKey of the parts accounted for. */ const reached = new Set([partKey("[Content_Types].xml")]); const queue: string[] = [""]; + const visit = (target: string): void => { + const entry = pkg.part(target); + if (!entry) return; + const key = pkg.keyOf(entry); + if (reached.has(key)) return; + reached.add(key); + queue.push(entry.name); + }; for (let q = 0; q < queue.length; q++) { const pause = ctx.step(); if (pause) await pause; @@ -200,39 +229,31 @@ export async function scanPackageParts(pkg: Package): Promise { throw err; } const relsPart = pkg.part(pkg.relsPartOf(source)); - if (relsPart) reached.add(partKey(relsPart.name)); + if (relsPart) reached.add(pkg.keyOf(relsPart)); for (let i = 0; i < rels.length; i++) { if ((i & ABORT_EVERY) === ABORT_EVERY) ctx.checkAbort(); const rel = rels[i]!; - const kind = partKindOf(rel, rel.external ? undefined : pkg.contentType(rel.target)); - if (kind) { - const part = rel.external ? source || pkg.relsPartOf(source) : rel.target; - const key = `${kind}\u0000${part.toLowerCase()}`; - if (!foundKeys.has(key)) { - foundKeys.add(key); - found.push({ kind, part, source, external: rel.external }); - } + if (rel.forbidden && relsPart) forbidden.add(relsPart.name); + const targets = rel.external ? [] : rel.literalTarget === undefined ? [rel.target] : [rel.target, rel.literalTarget]; + for (const target of rel.external ? [undefined] : targets) { + const kind = partKindOf(rel, target === undefined ? [] : pkg.contentTypes(target)); + if (!kind) continue; + const part = target ?? (source || pkg.relsPartOf(source)); + const key = `${kind}\u0000${partKey(part)}`; + if (foundKeys.has(key)) continue; + foundKeys.add(key); + found.push({ kind, part, source, external: rel.external }); } - if (rel.external) continue; - const entry = pkg.part(rel.target); - if (!entry) continue; - const name = partKey(entry.name); - if (reached.has(name)) continue; - reached.add(name); - queue.push(entry.name); + for (const t of targets) visit(t); } } const unreferenced: string[] = []; - const shadowed = new Set(pkg.shadowed); const entries = ctx.zip.entries; for (let i = 0; i < entries.length; i++) { if ((i & ABORT_EVERY) === ABORT_EVERY) ctx.checkAbort(); const e = entries[i]!; if (e.name.endsWith("/")) continue; // directory entries - // Office 2007 and 2010 moved discarded parts to "[trash]/" (exactly so, at the root). - if (e.name.startsWith(TRASH)) continue; - if (!shadowed.has(e) && reached.has(partKey(e.name))) continue; - unreferenced.push(e.name); + if (!reached.has(pkg.keyOf(e))) unreferenced.push(e.name); } - return { found, unreferenced }; + return { found, unreferenced, forbidden: [...forbidden] }; } diff --git a/packages/javascript-excel/src/warnings.ts b/packages/javascript-excel/src/warnings.ts index d08a89d..ececb1c 100644 --- a/packages/javascript-excel/src/warnings.ts +++ b/packages/javascript-excel/src/warnings.ts @@ -41,7 +41,8 @@ export type ExcelWarningCode = * in camelCase for the document-property parts. The kinds the package scan * adds are named for what they are: `'activeX'` (ActiveX controls), * `'embeddedPackage'` (embedded files), `'customUI'` (ribbon customisation), - * `'webExtension'` (Office web add-ins) and `'unreferencedPart'` (a part no relationship reaches). Kinds may be added in a minor + * `'webExtension'` (Office web add-ins), `'invalidPartName'` (a part name or + * relationship target OPC forbids) and `'unreferencedPart'` (a part no relationship reaches). Kinds may be added in a minor * release, so a `switch` over it needs a `default` branch. */ export type ExcelPartKind = @@ -79,6 +80,7 @@ export type ExcelPartKind = | "embeddedPackage" | "customUI" | "webExtension" + | "invalidPartName" | "unreferencedPart"; /** What the warning cap left out; on `WARNINGS_TRUNCATED` only. */ @@ -106,6 +108,13 @@ export interface ExcelWarning { ref?: string | undefined; /** On `MISSING_PART`, `BROKEN_OPTIONAL_PART` and `UNSUPPORTED_PART`: the kind of part. */ partKind?: ExcelPartKind | undefined; + /** + * On `UNSUPPORTED_PART` with `partKind` `'unreferencedPart'` or + * `'invalidPartName'` (since 2.5): every such name, in the order found + * (`part` is the first). Each is a zip entry name, at most once, so the + * list is bounded by `maxEntries`. + */ + parts?: string[] | undefined; /** * On `WARNINGS_TRUNCATED`: counts of the warnings that were not recorded. The * counts are final in the returned `warnings` only. `read` calls `onWarning` diff --git a/packages/javascript-excel/test/read/helpers.test.ts b/packages/javascript-excel/test/read/helpers.test.ts index 4d15f20..cd93afb 100644 --- a/packages/javascript-excel/test/read/helpers.test.ts +++ b/packages/javascript-excel/test/read/helpers.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { shiftFormula } from "../../src/internal/read/formula"; import { BUILTIN_NUM_FMTS, isDateFormat } from "../../src/numfmt"; -import { canonicalPartName, partKey, resolveTarget } from "../../src/internal/read/opc"; +import { canonicalPartName, forbiddenName, partKey, resolveTarget, resolveTargetLiteral } from "../../src/internal/read/opc"; import { fileWidthToChars } from "../../src/internal/read/sheet"; import { charsToFileWidth, pixelsToChars } from "../../src/internal/write/sheet-features"; import { decodeXstring } from "../../src/internal/read/strings"; @@ -110,25 +110,53 @@ describe("ST_Xstring and relationship targets", () => { expect(resolveTarget("xl/", "My%20Sheet.xml")).toBe("xl/My Sheet.xml"); expect(resolveTarget("", "../../../etc/passwd")).toBe("etc/passwd"); }); - it("only literal dot segments and separators structure a target; escapes stay in the name (JSE-72)", () => { - expect(resolveTarget("xl/drawings/", "%2E%2E/evil.bin")).toBe("xl/drawings/../evil.bin"); - expect(resolveTarget("xl/", "a%2Fb.bin")).toBe("xl/a%2Fb.bin"); - expect(resolveTarget("xl/", "a%5cb.bin")).toBe("xl/a%5Cb.bin"); + it("targets: a decoder's reading (resolveTarget) and the literal one (JSE-72)", () => { + expect(resolveTarget("xl/drawings/", "%2E%2E/evil.bin")).toBe("xl/evil.bin"); + expect(resolveTargetLiteral("xl/drawings/", "%2E%2E/evil.bin")).toBe("xl/drawings/../evil.bin"); + expect(resolveTarget("xl/", "a%2Fb.bin")).toBe("xl/a/b.bin"); + expect(resolveTargetLiteral("xl/", "a%2fb.bin")).toBe("xl/a%2Fb.bin"); + expect(resolveTarget("xl/", "a%5cb.bin")).toBe("xl/a/b.bin"); expect(resolveTarget("xl/", "%2541.bin")).toBe("xl/%2541.bin"); - expect(resolveTarget("xl/", "%C3%A4%FF.png")).toBe("xl/\u00e4%FF.png"); + expect(resolveTarget("xl/", "%C3%A4%FF.png")).toBe("xl/ä%FF.png"); + expect(resolveTarget("xl/worksheets/", "%%34%31s.xml")).toBe("xl/worksheets/%2541s.xml"); }); - it("canonical part names: decoded except %2F, %5C and %25; idempotent; keys compare case-insensitively", () => { + it("forbidden names: encoded separators, encoded dot segments, a trailing dot", () => { + for (const t of ["%2E%2E/x", "%2e/x", ".%2E/x", "%2E./x", "a%2Fb", "a%5cb", "a./b", "x.", "...", "a/b%2E"]) expect(forbiddenName(t, true), t).toBe(true); + for (const t of ["../x", "./x", "a.b/c", "%2541", "a%20b", "%C3%A4", "[trash]/x"]) expect(forbiddenName(t, true), t).toBe(false); + expect(forbiddenName("xl/../b", false)).toBe(true); + expect(forbiddenName("xl/./b", false)).toBe(true); + expect(forbiddenName("xl/a\\b", false)).toBe(false); + }); + it("canonical part names: decoded once, except %2F, %5C, %25, a bare % and invalid UTF-8", () => { for (const [raw, canon] of [ ["xl/media/image%201.png", "xl/media/image 1.png"], - ["%C3%A4", "\u00e4"], + ["%C3%A4", "ä"], ["%41%2f%5c%25", "A%2F%5C%25"], ["%2541", "%2541"], - ["%FF%zz", "%FF%zz"], + ["%%34%31", "%2541"], + ["%FF%zz", "%FF%25zz"], + ["100%", "100%25"], + ["%E4%E4", "%E4%E4"], + ["%ED%A0%80", "%ED%A0%80"], // a surrogate + ["%F4%90%80%80", "%F4%90%80%80"], // above U+10FFFF + ["%C0%AF", "%C0%AF"], // overlong + ["%F0%9F%98%80", "\u{1F600}"], ]) { - expect(canonicalPartName(raw!)).toBe(canon); - expect(canonicalPartName(canon!)).toBe(canon); + expect(canonicalPartName(raw!), raw).toBe(canon); + expect(canonicalPartName(canon!), canon).toBe(canon); } expect(partKey("/XL/Media/%41.PNG")).toBe(partKey("xl/media/a.png")); expect(partKey("xl/a%2Fb")).not.toBe(partKey("xl/a/b")); }); + it("canonicalPartName is idempotent (property test over random names)", () => { + const tokens = ["%", "%2", "%25", "%2F", "%2f", "%5C", "%2E", "%41", "%E4", "%B8", "%AD", "%C3", "%A4", "%F0", "%9F", "%98", "%80", "%ED", "%A0", "%ZZ", "4", "1", "a", "A", "/", ".", "ä", "\\"]; + let seed = 72; + const rand = (n: number) => ((seed = (seed * 1103515245 + 12345) >>> 0) >>> 8) % n; + for (let run = 0; run < 20_000; run++) { + let s = ""; + for (let k = rand(12); k >= 0; k--) s += tokens[rand(tokens.length)]; + const once = canonicalPartName(s); + expect(canonicalPartName(once), JSON.stringify(s)).toBe(once); + } + }); }); diff --git a/packages/javascript-excel/test/read/name-cost.test.ts b/packages/javascript-excel/test/read/name-cost.test.ts new file mode 100644 index 0000000..8400be9 --- /dev/null +++ b/packages/javascript-excel/test/read/name-cost.test.ts @@ -0,0 +1,74 @@ +// JSE-72 review: part-name canonicalisation must stay linear and abortable. +// Each hostile input is timed against a baseline of the same size whose names +// need no decoding, so the bounds hold on slow and fast machines alike. +import { describe, expect, it } from "vitest"; +import { openZip } from "../../src/internal/zip/read"; +import { read } from "../../src/read"; +import { build } from "./build"; + +const CELL = '1'; +const REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; +const rels = (target: string) => + ``; + +async function timed(bytes: Uint8Array, signal?: AbortSignal): Promise { + const t0 = performance.now(); + try { + await read(bytes, { signal, limits: { maxEntryBytes: 64 * 1024 * 1024 } }); + } catch (e) { + if ((e as Error).message !== "stop") throw e; + } + return performance.now() - t0; +} + +/** The faster of three runs, so one slow run (GC, a busy runner) does not decide. */ +async function best(bytes: Uint8Array): Promise { + const times = [await timed(bytes), await timed(bytes), await timed(bytes)]; + return Math.min(...times); +} + +// 2.4.0 read these in 33 ms and 125 ms; the PR at 46d55f2 took about 9.5 s for each. +describe("cost of decoding part names", () => { + it("a 4 MB relationship target of invalid UTF-8 escapes costs about what a plain one does", async () => { + const n = 1_400_000; // 4.2 MB of %E4 + const hostile = await build({ sheets: [CELL], override: { "xl/_rels/workbook.xml.rels": rels("%E4".repeat(n)) } }); + const plain = await build({ sheets: [CELL], override: { "xl/_rels/workbook.xml.rels": rels("abc".repeat(n)) } }); + const base = await best(plain); + const t = await best(hostile); + expect(t).toBeLessThan(5 * base + 500); + }, 60_000); + + it("100 entries with 60 KB names of invalid UTF-8 escapes cost about what plain names do", async () => { + const parts = (unit: string): Record => Object.fromEntries(Array.from({ length: 100 }, (_, i) => [`x${i}/${unit.repeat(20_000)}`, "x"])); + const hostile = await build({ sheets: [CELL], parts: parts("%E4") }); + const plain = await build({ sheets: [CELL], parts: parts("abc") }); + const base = await best(plain); + const t = await best(hostile); + expect(t).toBeLessThan(5 * base + 500); + }, 60_000); + + it("an abort is honoured promptly while the zip's part names are indexed", async () => { + const parts = Object.fromEntries(Array.from({ length: 100 }, (_, i) => [`x${i}/${"%E4".repeat(20_000)}`, "x"])); + const bytes = await build({ sheets: [CELL], parts }); + // The zip's central directory is read in one synchronous step before any part (as in 2.4.0); + // the abort must land within a few entries after it. + let zipTime = Infinity; + for (let k = 0; k < 3; k++) { + const t0 = performance.now(); + openZip(bytes, { limits: { maxEntryBytes: 64 * 1024 * 1024 } }); + zipTime = Math.min(zipTime, performance.now() - t0); + } + 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); + expect(t).toBeLessThan(zipTime + Math.max(30, (whole - zipTime) / 2)); + }, 60_000); +}); diff --git a/packages/javascript-excel/test/read/package-scan.test.ts b/packages/javascript-excel/test/read/package-scan.test.ts index b47c795..e158652 100644 --- a/packages/javascript-excel/test/read/package-scan.test.ts +++ b/packages/javascript-excel/test/read/package-scan.test.ts @@ -130,6 +130,7 @@ describe("parts no relationship reaches (partKind 'unreferencedPart')", () => { message: 'The package contains 1 part that no relationship refers to ("xl/vbaProject.bin"), which is not read.', part: "xl/vbaProject.bin", partKind: "unreferencedPart", + parts: ["xl/vbaProject.bin"], }, ]); }); @@ -142,6 +143,7 @@ describe("parts no relationship reaches (partKind 'unreferencedPart')", () => { }); expect(unsupported(r.warnings)).toEqual([["unreferencedPart", "payload.exe"]]); expect(r.warnings[0]!.message).toBe('The package contains 2 parts that no relationship refers to (first: "payload.exe"), which are not read.'); + expect(r.warnings[0]!.parts).toEqual(["payload.exe", "xl/media/x.dat"]); }); it("parts reached only through an unreferenced part are unreferenced too", async () => { @@ -163,17 +165,20 @@ describe("parts no relationship reaches (partKind 'unreferencedPart')", () => { expect(r.warnings[1]!.message).toMatch(/^The package contains 2 parts/); }); - it.each([["[TRASH]/0000.dat"], ["%5Btrash%5D/0000.dat"], ["xl/[trash]/0000.dat"]])("only the exact [trash]/ folder at the root is exempt: %s is reported", async (name) => { + it.each([["[trash]/0000.dat"], ["[TRASH]/0000.dat"], ["%5Btrash%5D/0000.dat"], ["xl/[trash]/0000.dat"]])("Office's discarded parts are not exempt: %s is reported", async (name) => { const r = await readOf({ sheets: [CELL], parts: { [name]: "x" } }); expect(unsupported(r.warnings)).toEqual([["unreferencedPart", name]]); }); - it("Office's [trash] folder, relationships parts of reached parts and [Content_Types].xml are not reported", async () => { - const r = await readOf({ - sheets: [CELL], - sheetRels: { 0: [["rH", "hyperlink", "https://example.com", true]] }, - parts: { "[trash]/0000.dat": new Uint8Array([1, 2, 3]) }, - }); + it("every unreferenced name is in `parts`, so a consumer can tolerate [trash]/ itself", async () => { + const r = await readOf({ sheets: [CELL], parts: { "[trash]/0000.dat": "x", "[trash]/0001.dat": "y" } }); + const w = r.warnings.find((x) => x.partKind === "unreferencedPart")!; + expect(w.parts).toEqual(["[trash]/0000.dat", "[trash]/0001.dat"]); + expect(w.parts!.every((n) => n.startsWith("[trash]/"))).toBe(true); + }); + + it("relationships parts of reached parts and [Content_Types].xml are not reported", async () => { + const r = await readOf({ sheets: [CELL], sheetRels: { 0: [["rH", "hyperlink", "https://example.com", true]] } }); expect(r.warnings).toEqual([]); }); @@ -210,19 +215,140 @@ describe("part names: percent-encoding and equivalence (OPC)", () => { expect(unsupported(r.warnings)).toEqual([["drawing", "xl/drawings/drawing1.xml"]]); }); + it("double encoding is decoded once: %2541 does not reach A", async () => { + const r = await readOf(withDrawing(["../media/%2541.bin"], { "xl/media/A.bin": "x" })); + expect(unsupported(r.warnings)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["unreferencedPart", "xl/media/A.bin"]]); + }); + + it("names are decoded once on both sides: a target %2561 no longer matches an entry %61 (2.4.0 matched it by decoding only the target)", async () => { + const r = await readOf(withDrawing(["../media/%2561.bin"], { "xl/media/%61.bin": "x" })); + expect(unsupported(r.warnings)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["unreferencedPart", "xl/media/%61.bin"]]); + }); + + it("a name with a literal % that is not an escape is decoded once (2.4.0 read it)", async () => { + const sheet = '7'; + const bytes = await build({ + sheets: [CELL], + override: { + "xl/_rels/workbook.xml.rels": rels([["rS1", "worksheet", "worksheets/%%34%31s.xml"]]), + "xl/worksheets/sheet1.xml": null, + "xl/worksheets/%%34%31s.xml": `${sheet}`, + }, + }); + const r = await read(bytes); + expect(r.warnings).toEqual([]); + expect(r.workbook.sheets[0]!.rows[0]![0]!.value).toBe(7); + }); + + it("a workbook part named with a literal % is found (2.4.0 read it)", async () => { + const bytes = await build({ + sheets: [CELL], + override: { + "_rels/.rels": rels([["rId1", "officeDocument", "xl/%%34%31workbook.xml"]]), + "xl/workbook.xml": null, + "xl/%%34%31workbook.xml": ``, + "xl/_rels/workbook.xml.rels": null, + "xl/_rels/%%34%31workbook.xml.rels": rels([["rS1", "worksheet", "worksheets/sheet1.xml"]]), + }, + }); + const r = await read(bytes); + expect(r.workbook.sheets.map((s) => s.name)).toEqual(["S"]); + expect(r.warnings).toEqual([]); + }); + it.each([ - ["%2E%2E is a name, not a parent folder", "%2E%2E/evil.bin", "xl/evil.bin"], - ["%2F is not a folder separator", "../media/a%2Fb.bin", "xl/media/a/b.bin"], - ["%5C is not a folder separator", "../media/a%5Cb.bin", "xl/media/a/b.bin"], - ["double encoding is decoded once", "../media/%2541.bin", "xl/media/A.bin"], - ])("%s: an encoded target does not reach another part", async (_, target, entry) => { - const r = await readOf(withDrawing([target], { [entry]: "x" })); - expect(unsupported(r.warnings)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["unreferencedPart", entry]]); - }); - - it("two entries with equivalent names do not count as one reached part: the later one is unreferenced", async () => { - const r = await readOf(withDrawing(["../media/a%20b.bin"], { "xl/media/a b.bin": "1", "xl/media/a%20b.bin": "2" })); - expect(unsupported(r.warnings)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["unreferencedPart", "xl/media/a%20b.bin"]]); + ["differ in percent-encoding", "xl/media/a b.bin", "xl/media/a%20b.bin"], + ["differ in encoded brackets (a relationships part)", "%5Btrash%5D/_rels/d.xml.rels", "[trash]/_rels/d.xml.rels"], + ])("two entries whose names %s are an invalid package: ZIP_INVALID", async (_, a, b) => { + const bytes = await build(withDrawing([], { [a]: "1", [b]: "2" })); + await expect(read(bytes)).rejects.toMatchObject({ name: "FormatError", code: "ZIP_INVALID" }); + }); +}); + +describe("names OPC forbids (partKind 'invalidPartName')", () => { + const withDrawing = (target: string, parts: Record): BuildOptions => ({ + sheets: [CELL], + sheetRels: { 0: [["rD", "drawing", "../drawings/drawing1.xml"]] }, + parts: { "xl/drawings/drawing1.xml": "", "xl/drawings/_rels/drawing1.xml.rels": rels([["r0", "image", target]]), ...parts }, + }); + const ACTIVE = rels([["rO", "oleObject", "/xl/embeddings/oleObject1.bin"], ["rP", "package", "/xl/embeddings/doc.docx"]]); + const EMB = { "xl/embeddings/oleObject1.bin": "o", "xl/embeddings/doc.docx": "d" }; + + it.each([ + ["%2E%2E", "%2E%2E/media/x.bin", "xl/media/x.bin"], + ["mixed .%2E", ".%2E/media/x.bin", "xl/media/x.bin"], + ["%2E", "%2E/x.bin", "xl/drawings/x.bin"], + ["%2F", "../media/a%2Fb.bin", "xl/media/a/b.bin"], + ["%5C", "../media/a%5cb.bin", "xl/media/a/b.bin"], + ["a segment ending in a dot", "../media/x.", "xl/media/x."], + ])("a target with %s: reported; the part a decoder resolves it to is reached", async (_, target, entry) => { + const r = await readOf(withDrawing(target, { [entry]: "x" })); + // A zip entry whose own name is forbidden ("x.") is listed first, then the relationships part with the target. + const names = [...(entry.endsWith(".") ? [entry] : []), "xl/drawings/_rels/drawing1.xml.rels"]; + expect(unsupported(r.warnings)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["invalidPartName", names[0]]]); + expect(r.warnings[1]!.parts).toEqual(names); + }); + + it("the reviewer's reproducer: ../%2E%2E/[trash]/d.xml scans the drawing it reaches either way", async () => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rD", "drawing", "../%2E%2E/[trash]/d.xml"]] }, + parts: { "[trash]/d.xml": "", "[trash]/_rels/d.xml.rels": ACTIVE, ...EMB }, + }); + expect(unsupported(r.warnings).map((w) => w[0])).toEqual(["drawing", "oleObject", "embeddedPackage", "invalidPartName"]); + }); + + it("active content behind the literal reading of a target is found too", async () => { + const r = await readOf(withDrawing("a%2Fb.xml", { "xl/drawings/a%2Fb.xml": "", "xl/drawings/_rels/a%2Fb.xml.rels": ACTIVE, ...EMB })); + const kinds = unsupported(r.warnings).map((w) => w[0]); + expect(kinds).toEqual(["drawing", "oleObject", "embeddedPackage", "invalidPartName"]); + expect(r.warnings.find((w) => w.partKind === "invalidPartName")!.parts).toEqual(["xl/drawings/a%2Fb.xml", "xl/drawings/_rels/a%2Fb.xml.rels", "xl/drawings/_rels/drawing1.xml.rels"]); + }); + + it.each([["xl/a%2Fb.bin"], ["xl/a%5Cb.bin"], ["xl/%2E%2E/b.bin"], ["xl/.%2E/b.bin"], ["xl/b./c.bin"], ["xl/../b.bin"], ["xl/media/x."]])("a zip entry named %s is reported", async (name) => { + const r = await readOf({ sheets: [CELL], parts: { [name]: "x" } }); + expect(unsupported(r.warnings)).toEqual([["invalidPartName", name], ["unreferencedPart", name]]); + }); + + it("a sheet behind a %2E%2E target is still read, as 2.4.0 did", async () => { + const bytes = await build({ sheets: [CELL], override: { "xl/_rels/workbook.xml.rels": rels([["rS1", "worksheet", "x/%2E%2E/worksheets/sheet1.xml"]]) } }); + const r = await read(bytes); + expect(r.workbook.sheets[0]!.rows[0]![0]!.value).toBe(1); + expect(unsupported(r.warnings)).toEqual([["invalidPartName", "xl/_rels/workbook.xml.rels"]]); + }); +}); + +describe("content types", () => { + it("equivalent Override part names: an active content type is never lost to a later passive one", async () => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rI", "image", "../media/a%20b.bin"]] }, + parts: { "xl/media/a b.bin": "x" }, + override: { "[Content_Types].xml": contentTypes({}, { "/xl/media/a%20b.bin": "application/vnd.ms-office.vbaProject", "/xl/media/a b.bin": "image/png" }) }, + }); + expect(unsupported(r.warnings)).toEqual([["image", "xl/media/a b.bin"], ["vbaProject", "xl/media/a b.bin"]]); + }); + + it.each([ + ["application/vnd.ms-office.oleObject", "oleObject"], + ["application/vnd.ms-excel.template.macroEnabled.12", "embeddedPackage"], + ["application/vnd.ms-excel.addin.macroEnabled.12", "embeddedPackage"], + ["application/vnd.ms-word.template.macroEnabled.12", "embeddedPackage"], + ["application/vnd.ms-powerpoint.template.macroEnabled.12", "embeddedPackage"], + ["application/vnd.ms-powerpoint.slide.macroEnabled.12", "embeddedPackage"], + ["application/vnd.ms-powerpoint.addin.macroEnabled.12", "embeddedPackage"], + ["application/vnd.openxmlformats-officedocument.spreadsheetml.template", "embeddedPackage"], + ["application/vnd.openxmlformats-officedocument.wordprocessingml.template", "embeddedPackage"], + ["application/vnd.openxmlformats-officedocument.presentationml.template", "embeddedPackage"], + ["application/vnd.openxmlformats-officedocument.presentationml.slide", "embeddedPackage"], + ])("%s behind an image relationship is %s", async (contentType, kind) => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rI", "image", "../media/p.bin"]] }, + parts: { "xl/media/p.bin": "x" }, + override: { "[Content_Types].xml": contentTypes({}, { "/xl/media/p.bin": contentType }) }, + }); + expect(unsupported(r.warnings)).toEqual([["image", "xl/media/p.bin"], [kind, "xl/media/p.bin"]]); }); }); From 37226d1b7208d2181c43fb88076f64573a591baa Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 12:29:51 +0100 Subject: [PATCH 4/6] JSE-72: docs give the 40,000-file name fuzz result --- docs/api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api.md b/docs/api.md index e5fa2f9..ca7a2b8 100644 --- a/docs/api.md +++ b/docs/api.md @@ -879,7 +879,7 @@ How the reader works, as far as the API is concerned: - Unsupported content (drawings, charts, comments, pivot tables, tables, OLE objects, form controls, VBA, external links, chart sheets, …) gives one `UNSUPPORTED_PART` warning per kind. Chart, dialog and macro sheets are not worksheets: they are left out of `sheets` and `readSheetNames`, and defined names local to them are dropped. - **The package scan** (since 2.5). After the sheets, the reader walks the whole relationship graph, from the package root through the workbook and every sheet (also sheets left out by `sheets`) to every part those reach (drawings, VML drawings, tables, ActiveX parts, …). It reads only relationships parts, each once, within the zip and XML limits, and never inflates the parts it finds. It reports, once per kind, the kinds that are active or embedded content or a link out of the file, wherever they sit: `'activeX'` (a `control` or `activeXControlBinary` relationship), `'embeddedPackage'` (a `package` relationship, a file such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a root `…/relationships/ui/extensibility` relationship, 2006 and 2007 namespaces: a ribbon customisation, `customUI/customUI.xml` or `customUI14.xml`), `'webExtension'` (an Office web add-in: the `webextensiontaskpanes` and `webextension` relationships, `xl/webextensions/`), and `'oleObject'`, `'vbaProject'`, `'externalLink'`, `'connections'`, `'queryTable'` and `'macrosheet'` where the workbook's and the read sheets' own relationships did not already report them (an OLE object referenced from a drawing, a query table under a table, an ActiveX control on a sheet not read). `'vbaProject'` covers the VBA family: the project, its signatures (`vbaProjectSignature`, `…Agile`, `…V3`), `wordVbaData` and toolbars attached to a macro workbook (`attachedToolbars`, `xl/attachedToolbars.bin`). Excel 4 macro sheets are macro sheets under all three relationship types, ECMA `…/macrosheet` and Microsoft's `…/xlMacrosheet` and `…/xlIntlMacrosheet` (before 2.5 only the first was reported; all three were left out of `sheets`). - **Matching** (since 2.5). Relationship types are compared without regard to case (`OLEOBJECT` is `oleObject`). A part's content type is a backstop: a part with the content type of an ActiveX control (`application/vnd.ms-office.activeX+xml`, `application/vnd.ms-office.activeX`), an OLE object (`application/vnd.openxmlformats-officedocument.oleObject`, `application/vnd.ms-office.oleObject`), VBA (`application/vnd.ms-office.vbaProject`, `…vbaProjectSignature`, `application/vnd.ms-excel.attachedToolbars`), a macro sheet (`application/vnd.ms-excel.macrosheet+xml`, `…intlmacrosheet+xml`), a web add-in (`application/vnd.ms-office.webextension+xml`, `…webextensiontaskpanes+xml`) or an embedded Office file (Word, Excel and PowerPoint documents, templates, add-ins, slides and slide shows, macro-enabled or not) is reported as that kind whatever relationship reaches it, so an `image` relationship to an OLE object gives both `'image'` and `'oleObject'`. When `[Content_Types].xml` lists several Overrides for equivalent part names (or several Defaults for one extension), each is checked, so a later passive type cannot hide an active one; `contentType` for format detection still takes the last, as before. Drawings, images, comments, tables, pivots and the other passive kinds are reported as before, from the workbook's and the read sheets' own relationships only, so an image inside a drawing still gives just `'drawing'`. -- **Part names** (since 2.5). Zip entry names and relationship targets are compared as OPC defines part-name equivalence: case-insensitively, after decoding percent-escapes once, as UTF-8, on both sides. So the target `../media/image%201.png` reaches the entry `xl/media/image%201.png` and `xl/media/image 1.png`, `%C3%A4` reaches `ä`, and an entry whose name is percent-encoded is found (2.4.0 compared the decoded target with the raw entry name, so it missed `x%6Cl/workbook.xml` and read such a file as `NOT_XLSX` or with `MISSING_PART`). The canonical form keeps `%2F`, `%5C`, `%25`, a `%` that starts no escape (as `%25`) and bytes that are not valid UTF-8 encoded, so a double encoding such as `%2541` stays the text `%41` and never reaches `A`; applying it again changes nothing. One consequence: 2.4.0 also matched a target such as `%2561` with an entry named `%61`, by decoding only the target; now the entry `%61` is the part `a`, and the target names the part `%61`, so they no longer match (in a 20,000-file name fuzz against 2.4.0 this affected 3 files, all with a literal `%` or `%25` spelled differently on the two sides). **Equivalent names are an invalid package**: two entries whose names are equal in this form, for example `a b` and `a%20b`, or `%5Btrash%5D/x` and `[trash]/x`, throw `ZIP_INVALID`, as entries that differ only in case always did; 2.4.0 read such a file. **Names OPC forbids** give one `UNSUPPORTED_PART` warning with `partKind: 'invalidPartName'` and every offending name in `parts`: a zip entry name, or a relationship target, with a segment that contains `%2F` or `%5C`, a percent-encoded dot segment (`%2E`, `%2E%2E`, `.%2E`), or a segment that ends in a dot (for an entry name this includes `.` and `..`; a target may use literal `.` and `..` as relative references). For a forbidden target, `parts` names the relationships part that holds it. Such a target is followed both as a decoder reads it (as 2.4.0 did: `%2F` and `%5C` separate segments, `%2E%2E` is `..`) and literally (the escapes are part of one name), so active content behind it is reported whichever way Excel resolves it; the reader reads the part the decoder's reading names, so a sheet behind `x/%2E%2E/worksheets/sheet1.xml` is read as in 2.4.0. +- **Part names** (since 2.5). Zip entry names and relationship targets are compared as OPC defines part-name equivalence: case-insensitively, after decoding percent-escapes once, as UTF-8, on both sides. So the target `../media/image%201.png` reaches the entry `xl/media/image%201.png` and `xl/media/image 1.png`, `%C3%A4` reaches `ä`, and an entry whose name is percent-encoded is found (2.4.0 compared the decoded target with the raw entry name, so it missed `x%6Cl/workbook.xml` and read such a file as `NOT_XLSX` or with `MISSING_PART`). The canonical form keeps `%2F`, `%5C`, `%25`, a `%` that starts no escape (as `%25`) and bytes that are not valid UTF-8 encoded, so a double encoding such as `%2541` stays the text `%41` and never reaches `A`; applying it again changes nothing. One consequence: 2.4.0 also matched a target such as `%2561` with an entry named `%61`, by decoding only the target; now the entry `%61` is the part `a`, and the target names the part `%61`, so they no longer match (in a 40,000-file name fuzz against 2.4.0 this affected 4 files, all with a literal `%` or `%25` spelled differently in the entry name and the target). **Equivalent names are an invalid package**: two entries whose names are equal in this form, for example `a b` and `a%20b`, or `%5Btrash%5D/x` and `[trash]/x`, throw `ZIP_INVALID`, as entries that differ only in case always did; 2.4.0 read such a file. **Names OPC forbids** give one `UNSUPPORTED_PART` warning with `partKind: 'invalidPartName'` and every offending name in `parts`: a zip entry name, or a relationship target, with a segment that contains `%2F` or `%5C`, a percent-encoded dot segment (`%2E`, `%2E%2E`, `.%2E`), or a segment that ends in a dot (for an entry name this includes `.` and `..`; a target may use literal `.` and `..` as relative references). For a forbidden target, `parts` names the relationships part that holds it. Such a target is followed both as a decoder reads it (as 2.4.0 did: `%2F` and `%5C` separate segments, `%2E%2E` is `..`) and literally (the escapes are part of one name), so active content behind it is reported whichever way Excel resolves it; the reader reads the part the decoder's reading names, so a sheet behind `x/%2E%2E/worksheets/sheet1.xml` is read as in 2.4.0. - **Unreferenced parts** (since 2.5). A part no relationship reaches (a `vbaProject.bin` without a relationship, an executable dropped into the zip, with or without a content type) gives one `UNSUPPORTED_PART` warning with `partKind: 'unreferencedPart'`: `part` names the first such part in zip order, `parts` lists every one in zip order, and the message gives their number. `parts` has at most one name per zip entry, so its length is bounded by `maxEntries` (each name by the zip format's 65,535 bytes); its strings are the entry names the zip already holds. Parts reached only through an unreferenced part are unreferenced too, and so is a relationships part that is not well-formed XML, together with the parts only it would reach (the read goes on). Not reported: `[Content_Types].xml` and the relationships part of a reached part. Nothing is exempt by name, `[trash]/` included: Office 2007 and 2010 could leave discarded parts in a `[trash]/` folder at the package root; Excel never loads them (parts load only through relationships), but their bytes are in the file, so they are reported like any other. A consumer that wants to accept such files can check that every name in `parts` starts with `[trash]/`. The thumbnail (`docProps/thumbnail.*`), printer settings (`xl/printerSettings/*.bin`), `xl/calcChain.xml`, custom XML and the document properties have their own relationship types, so in a well-formed package they are reached; an orphaned copy of one is reported, because an exemption by name would be the place to hide a payload. Evidence: none of the test corpus files (the openpyxl, LibreOffice and import fixtures and every conformance-corpus file this library writes) has an unreferenced part. Files saved by Excel and Numbers are not in the corpus; a part they leave unreferenced would be reported, and is a bug report worth filing. - Styles: each `cellXfs` entry is one frozen `Style` (§12 Q8). Pattern fills come back with `type: 'pattern'`, so `fill.type` tells pattern and gradient fills apart. A style records only what differs from the defaults: font 0 (the workbook default font), fills 0 and 1 (the required `none` and `gray125` placeholders) and border 0 are left out, and `numFmtId` 0 (General) gives no `numFmt`. `applyFont` and the other apply flags are ignored, as Excel does for cell formats. - Values: `t="s"`, `"inlineStr"` and `"str"` are strings (or rich text), with `_xHHHH_` escapes decoded; `"b"` booleans; `"e"` errors, including codes newer than the seven of ECMA-376 (`#SPILL!`, `#CALC!`, …), returned as written; `"d"` ISO dates; numbers otherwise, converted to `Date` when their number format is a date format (§3.4.1). A formula's cached value sets `value` and `type`; without one the cell is `type: 'empty'` with its `formula`. Shared formulas are expanded (§12 Q6), except from a master longer than 8,192 characters and except copies longer than `maxCellTextLength` (§3.4.2); data-table formulas (`t="dataTable"`) give their cached values only. From f70c75a04299c70484bcccc17b75ff169f37250c Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 12:54:38 +0100 Subject: [PATCH 5/6] JSE-72 review 3: classify every relationships part, malformed relationships, long names - A part reached as a relationship target is queued for its own relationships even if it was already accounted for, so a target naming a relationships part or [Content_Types].xml no longer hides what that part's relationships list. Such a target is invalidPartName. - Every .rels entry is read as its owner's relationships after the walk, also when nothing reaches the owner; what only it lists is classified but stays unreferenced. - A without Id or Target is kept out of the model as before, classified by the scan, and reported as invalidPartName. - Override PartNames: forbidden names are reported, and the content type applies under both readings. - Targets and PartNames longer than 3 x 65,535 characters are not canonicalised (they cannot name a part) and are reported. - A target with a malformed escape is read literally, as 2.4.0 did. - Format detection uses 2.4.0's override table (last wins). --- .changeset/package-scan-active-content.md | 2 +- docs/api.md | 8 +- .../javascript-excel/src/internal/read/opc.ts | 182 +++++++++++++++--- .../src/internal/read/scan.ts | 101 ++++++---- packages/javascript-excel/src/warnings.ts | 4 +- .../test/read/name-cost.test.ts | 31 ++- .../test/read/package-scan.test.ts | 88 ++++++++- 7 files changed, 350 insertions(+), 66 deletions(-) diff --git a/.changeset/package-scan-active-content.md b/.changeset/package-scan-active-content.md index 67a3211..cea3010 100644 --- a/.changeset/package-scan-active-content.md +++ b/.changeset/package-scan-active-content.md @@ -2,6 +2,6 @@ "javascript-excel": minor --- -`read` (and `importDataset`, which passes read warnings on) now walks the whole relationship graph of the package and reports more content it does not read as `UNSUPPORTED_PART`, with six new `partKind` values: `'activeX'` (ActiveX controls), `'embeddedPackage'` (a `package` relationship, such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a ribbon customisation: the root `ui/extensibility` relationship of Office 2007 or 2010), `'webExtension'` (Office web add-ins), `'invalidPartName'` (a zip entry name or relationship target OPC forbids: `%2F` or `%5C` in a segment, a percent-encoded dot segment, a segment ending in a dot) and `'unreferencedPart'` (a part no relationship reaches, such as a `vbaProject.bin` or an executable placed in the zip). The last two come as one warning each, with every name in a new `parts` field on the warning (bounded by `maxEntries`). Nothing is exempt by name: discarded parts Office 2007/2010 left under `[trash]/` are reported too; a consumer that accepts them can check that every name in `parts` starts with `[trash]/`. The scan also finds `'oleObject'`, `'vbaProject'` (now also attached toolbars and VBA signatures), `'externalLink'`, `'connections'`, `'queryTable'` and `'macrosheet'` where they were not reported before: under a drawing, under a table, or on a sheet left out by the `sheets` option. Excel 4 macro sheets with Microsoft's `xlMacrosheet` and `xlIntlMacrosheet` relationship types are now reported as `'macrosheet'`. Relationship types are compared case-insensitively, and a part with the content type of an ActiveX control, OLE object, VBA project, macro sheet, web add-in or embedded Office file (documents, templates, add-ins, slides) is reported as that kind whatever relationship reaches it; equivalent Overrides in `[Content_Types].xml` are all checked. Drawings, images, comments and the other passive kinds are reported as before. The scan reads only relationships parts, within the existing zip and XML limits, never inflates the parts it reports, and consults the signal throughout; a relationships part that is not well-formed XML is reported as unreferenced instead of failing the read. Existing warnings keep their shape; a `switch` over `ExcelPartKind` needs a `default` branch, as documented. The test corpus (files from LibreOffice and openpyxl, and every file of the conformance corpus this library writes) gives no new warnings. +`read` (and `importDataset`, which passes read warnings on) now walks the whole relationship graph of the package and reports more content it does not read as `UNSUPPORTED_PART`, with six new `partKind` values: `'activeX'` (ActiveX controls), `'embeddedPackage'` (a `package` relationship, such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a ribbon customisation: the root `ui/extensibility` relationship of Office 2007 or 2010), `'webExtension'` (Office web add-ins), `'invalidPartName'` (a zip entry name, relationship target or Override PartName OPC forbids: `%2F` or `%5C` in a segment, a percent-encoded dot segment, a segment ending in a dot, a target naming a relationships part or `[Content_Types].xml`, a name too long for any zip entry; or a `` without `Id` or `Target`, which the model still ignores) and `'unreferencedPart'` (a part no relationship reaches, such as a `vbaProject.bin` or an executable placed in the zip). The last two come as one warning each, with every name in a new `parts` field on the warning (bounded by `maxEntries`). Nothing is exempt by name: discarded parts Office 2007/2010 left under `[trash]/` are reported too; a consumer that accepts them can check that every name in `parts` starts with `[trash]/`. The scan also finds `'oleObject'`, `'vbaProject'` (now also attached toolbars and VBA signatures), `'externalLink'`, `'connections'`, `'queryTable'` and `'macrosheet'` where they were not reported before: under a drawing, under a table, or on a sheet left out by the `sheets` option. Excel 4 macro sheets with Microsoft's `xlMacrosheet` and `xlIntlMacrosheet` relationship types are now reported as `'macrosheet'`. Relationship types are compared case-insensitively, and a part with the content type of an ActiveX control, OLE object, VBA project, macro sheet, web add-in or embedded Office file (documents, templates, add-ins, slides) is reported as that kind whatever relationship reaches it; equivalent Overrides in `[Content_Types].xml` are all checked. Drawings, images, comments and the other passive kinds are reported as before. Every relationships part in the zip is classified, also one whose owner nothing reaches. The scan reads only relationships parts, within the existing zip and XML limits, never inflates the parts it reports, and consults the signal throughout; a relationships part that is not well-formed XML is reported as unreferenced instead of failing the read. Existing warnings keep their shape; a `switch` over `ExcelPartKind` needs a `default` branch, as documented. The test corpus (files from LibreOffice and openpyxl, and every file of the conformance corpus this library writes) gives no new warnings. Behaviour changes against 2.4.0: part names are compared in OPC canonical form (percent-escapes decoded once, as UTF-8, on both sides; `%2F`, `%5C`, `%25` and invalid bytes kept encoded), so percent-encoded zip entry names are now found where 2.4.0 reported `MISSING_PART` or `NOT_XLSX`, while a target matched to an entry only because 2.4.0 decoded the target and not the entry name (a literal `%` spelled differently on the two sides) no longer matches. Two zip entries with equivalent names (for example `a b` and `a%20b`) now throw `ZIP_INVALID`, as names that differ only in case already did. Because the scan parses the relationships parts of every reached part, a DTD or an over-deep XML in one of them (also under a sheet that is not read) now throws `XML_DTD_FORBIDDEN` or `LIMIT_EXCEEDED`; 2.4.0 read such a file. diff --git a/docs/api.md b/docs/api.md index ca7a2b8..1954466 100644 --- a/docs/api.md +++ b/docs/api.md @@ -879,8 +879,8 @@ How the reader works, as far as the API is concerned: - Unsupported content (drawings, charts, comments, pivot tables, tables, OLE objects, form controls, VBA, external links, chart sheets, …) gives one `UNSUPPORTED_PART` warning per kind. Chart, dialog and macro sheets are not worksheets: they are left out of `sheets` and `readSheetNames`, and defined names local to them are dropped. - **The package scan** (since 2.5). After the sheets, the reader walks the whole relationship graph, from the package root through the workbook and every sheet (also sheets left out by `sheets`) to every part those reach (drawings, VML drawings, tables, ActiveX parts, …). It reads only relationships parts, each once, within the zip and XML limits, and never inflates the parts it finds. It reports, once per kind, the kinds that are active or embedded content or a link out of the file, wherever they sit: `'activeX'` (a `control` or `activeXControlBinary` relationship), `'embeddedPackage'` (a `package` relationship, a file such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a root `…/relationships/ui/extensibility` relationship, 2006 and 2007 namespaces: a ribbon customisation, `customUI/customUI.xml` or `customUI14.xml`), `'webExtension'` (an Office web add-in: the `webextensiontaskpanes` and `webextension` relationships, `xl/webextensions/`), and `'oleObject'`, `'vbaProject'`, `'externalLink'`, `'connections'`, `'queryTable'` and `'macrosheet'` where the workbook's and the read sheets' own relationships did not already report them (an OLE object referenced from a drawing, a query table under a table, an ActiveX control on a sheet not read). `'vbaProject'` covers the VBA family: the project, its signatures (`vbaProjectSignature`, `…Agile`, `…V3`), `wordVbaData` and toolbars attached to a macro workbook (`attachedToolbars`, `xl/attachedToolbars.bin`). Excel 4 macro sheets are macro sheets under all three relationship types, ECMA `…/macrosheet` and Microsoft's `…/xlMacrosheet` and `…/xlIntlMacrosheet` (before 2.5 only the first was reported; all three were left out of `sheets`). - **Matching** (since 2.5). Relationship types are compared without regard to case (`OLEOBJECT` is `oleObject`). A part's content type is a backstop: a part with the content type of an ActiveX control (`application/vnd.ms-office.activeX+xml`, `application/vnd.ms-office.activeX`), an OLE object (`application/vnd.openxmlformats-officedocument.oleObject`, `application/vnd.ms-office.oleObject`), VBA (`application/vnd.ms-office.vbaProject`, `…vbaProjectSignature`, `application/vnd.ms-excel.attachedToolbars`), a macro sheet (`application/vnd.ms-excel.macrosheet+xml`, `…intlmacrosheet+xml`), a web add-in (`application/vnd.ms-office.webextension+xml`, `…webextensiontaskpanes+xml`) or an embedded Office file (Word, Excel and PowerPoint documents, templates, add-ins, slides and slide shows, macro-enabled or not) is reported as that kind whatever relationship reaches it, so an `image` relationship to an OLE object gives both `'image'` and `'oleObject'`. When `[Content_Types].xml` lists several Overrides for equivalent part names (or several Defaults for one extension), each is checked, so a later passive type cannot hide an active one; `contentType` for format detection still takes the last, as before. Drawings, images, comments, tables, pivots and the other passive kinds are reported as before, from the workbook's and the read sheets' own relationships only, so an image inside a drawing still gives just `'drawing'`. -- **Part names** (since 2.5). Zip entry names and relationship targets are compared as OPC defines part-name equivalence: case-insensitively, after decoding percent-escapes once, as UTF-8, on both sides. So the target `../media/image%201.png` reaches the entry `xl/media/image%201.png` and `xl/media/image 1.png`, `%C3%A4` reaches `ä`, and an entry whose name is percent-encoded is found (2.4.0 compared the decoded target with the raw entry name, so it missed `x%6Cl/workbook.xml` and read such a file as `NOT_XLSX` or with `MISSING_PART`). The canonical form keeps `%2F`, `%5C`, `%25`, a `%` that starts no escape (as `%25`) and bytes that are not valid UTF-8 encoded, so a double encoding such as `%2541` stays the text `%41` and never reaches `A`; applying it again changes nothing. One consequence: 2.4.0 also matched a target such as `%2561` with an entry named `%61`, by decoding only the target; now the entry `%61` is the part `a`, and the target names the part `%61`, so they no longer match (in a 40,000-file name fuzz against 2.4.0 this affected 4 files, all with a literal `%` or `%25` spelled differently in the entry name and the target). **Equivalent names are an invalid package**: two entries whose names are equal in this form, for example `a b` and `a%20b`, or `%5Btrash%5D/x` and `[trash]/x`, throw `ZIP_INVALID`, as entries that differ only in case always did; 2.4.0 read such a file. **Names OPC forbids** give one `UNSUPPORTED_PART` warning with `partKind: 'invalidPartName'` and every offending name in `parts`: a zip entry name, or a relationship target, with a segment that contains `%2F` or `%5C`, a percent-encoded dot segment (`%2E`, `%2E%2E`, `.%2E`), or a segment that ends in a dot (for an entry name this includes `.` and `..`; a target may use literal `.` and `..` as relative references). For a forbidden target, `parts` names the relationships part that holds it. Such a target is followed both as a decoder reads it (as 2.4.0 did: `%2F` and `%5C` separate segments, `%2E%2E` is `..`) and literally (the escapes are part of one name), so active content behind it is reported whichever way Excel resolves it; the reader reads the part the decoder's reading names, so a sheet behind `x/%2E%2E/worksheets/sheet1.xml` is read as in 2.4.0. -- **Unreferenced parts** (since 2.5). A part no relationship reaches (a `vbaProject.bin` without a relationship, an executable dropped into the zip, with or without a content type) gives one `UNSUPPORTED_PART` warning with `partKind: 'unreferencedPart'`: `part` names the first such part in zip order, `parts` lists every one in zip order, and the message gives their number. `parts` has at most one name per zip entry, so its length is bounded by `maxEntries` (each name by the zip format's 65,535 bytes); its strings are the entry names the zip already holds. Parts reached only through an unreferenced part are unreferenced too, and so is a relationships part that is not well-formed XML, together with the parts only it would reach (the read goes on). Not reported: `[Content_Types].xml` and the relationships part of a reached part. Nothing is exempt by name, `[trash]/` included: Office 2007 and 2010 could leave discarded parts in a `[trash]/` folder at the package root; Excel never loads them (parts load only through relationships), but their bytes are in the file, so they are reported like any other. A consumer that wants to accept such files can check that every name in `parts` starts with `[trash]/`. The thumbnail (`docProps/thumbnail.*`), printer settings (`xl/printerSettings/*.bin`), `xl/calcChain.xml`, custom XML and the document properties have their own relationship types, so in a well-formed package they are reached; an orphaned copy of one is reported, because an exemption by name would be the place to hide a payload. Evidence: none of the test corpus files (the openpyxl, LibreOffice and import fixtures and every conformance-corpus file this library writes) has an unreferenced part. Files saved by Excel and Numbers are not in the corpus; a part they leave unreferenced would be reported, and is a bug report worth filing. +- **Part names** (since 2.5). Zip entry names and relationship targets are compared as OPC defines part-name equivalence: case-insensitively, after decoding percent-escapes once, as UTF-8, on both sides. So the target `../media/image%201.png` reaches the entry `xl/media/image%201.png` and `xl/media/image 1.png`, `%C3%A4` reaches `ä`, and an entry whose name is percent-encoded is found (2.4.0 compared the decoded target with the raw entry name, so it missed `x%6Cl/workbook.xml` and read such a file as `NOT_XLSX` or with `MISSING_PART`). The canonical form keeps `%2F`, `%5C`, `%25`, a `%` that starts no escape (as `%25`) and bytes that are not valid UTF-8 encoded, so a double encoding such as `%2541` stays the text `%41` and never reaches `A`; applying it again changes nothing. One consequence: 2.4.0 also matched a target such as `%2561` with an entry named `%61`, by decoding only the target; now the entry `%61` is the part `a`, and the target names the part `%61`, so they no longer match (in a 40,000-file name fuzz against 2.4.0 this affected 4 files, all with a literal `%` or `%25` spelled differently in the entry name and the target). **Equivalent names are an invalid package**: two entries whose names are equal in this form, for example `a b` and `a%20b`, or `%5Btrash%5D/x` and `[trash]/x`, throw `ZIP_INVALID`, as entries that differ only in case always did; 2.4.0 read such a file. **Names OPC forbids** give one `UNSUPPORTED_PART` warning with `partKind: 'invalidPartName'` and every offending name in `parts`: a zip entry name, or a relationship target, with a segment that contains `%2F` or `%5C`, a percent-encoded dot segment (`%2E`, `%2E%2E`, `.%2E`), or a segment that ends in a dot (for an entry name this includes `.` and `..`; a target may use literal `.` and `..` as relative references). The same warning covers the other shapes OPC forbids: a relationship target that names package metadata (a relationships part `…/_rels/*.rels` or `[Content_Types].xml`; the scan still reads that part's own relationships), a `` without an `Id` (or with an empty one) or without a `Target` (the model ignores it, as 2.4.0 did, but the scan classifies it by its type and, if it has one, its target), an Override `PartName` in `[Content_Types].xml` with a forbidden segment, and a target or PartName longer than 196,605 characters (three times the 65,535 bytes a zip entry name can have, so it cannot name any part; it is not decoded at all and `read` treats it as a target that matches nothing, as 2.4.0 effectively did). For a forbidden target or relationship, `parts` names the relationships part that holds it; for a PartName, `[Content_Types].xml`. A forbidden target is followed under both readings: as a decoder reads it (`%2F` and `%5C` separate segments, `%2E%2E` is `..`) and literally (the escapes are part of one name), so active content behind it is reported whichever way Excel resolves it. `read` reads the part 2.4.0 read: the decoder's reading, except when the target has a malformed escape (a `%` that starts no escape, or escapes that are not valid UTF-8): 2.4.0's decoding then failed and the whole target was taken literally, so `read` takes the literal reading too. So a sheet behind `x/%2E%2E/worksheets/sheet1.xml`, or behind `xl/%2f/%3%%é.xml` named so in both the target and the zip, is read as in 2.4.0. An Override PartName applies its content type under both readings, and every content type given for a part is checked (any active one wins). +- **Unreferenced parts** (since 2.5). A part no relationship reaches (a `vbaProject.bin` without a relationship, an executable dropped into the zip, with or without a content type) gives one `UNSUPPORTED_PART` warning with `partKind: 'unreferencedPart'`: `part` names the first such part in zip order, `parts` lists every one in zip order, and the message gives their number. `parts` has at most one name per zip entry, so its length is bounded by `maxEntries` (each name by the zip format's 65,535 bytes); its strings are the entry names the zip already holds. Parts reached only through an unreferenced part are unreferenced too, and so is a relationships part that is not well-formed XML, together with the parts only it would reach (the read goes on). Every relationships part in the zip is read as its owner's relationships, also when nothing reaches its owner, so the kinds above are reported for whatever any relationships part lists; what only such a part lists stays unreferenced. Not reported: `[Content_Types].xml` and the relationships part of a reached part. Nothing is exempt by name, `[trash]/` included: Office 2007 and 2010 could leave discarded parts in a `[trash]/` folder at the package root; Excel never loads them (parts load only through relationships), but their bytes are in the file, so they are reported like any other. A consumer that wants to accept such files can check that every name in `parts` starts with `[trash]/`. The thumbnail (`docProps/thumbnail.*`), printer settings (`xl/printerSettings/*.bin`), `xl/calcChain.xml`, custom XML and the document properties have their own relationship types, so in a well-formed package they are reached; an orphaned copy of one is reported, because an exemption by name would be the place to hide a payload. Evidence: none of the test corpus files (the openpyxl, LibreOffice and import fixtures and every conformance-corpus file this library writes) has an unreferenced part. Files saved by Excel and Numbers are not in the corpus; a part they leave unreferenced would be reported, and is a bug report worth filing. - Styles: each `cellXfs` entry is one frozen `Style` (§12 Q8). Pattern fills come back with `type: 'pattern'`, so `fill.type` tells pattern and gradient fills apart. A style records only what differs from the defaults: font 0 (the workbook default font), fills 0 and 1 (the required `none` and `gray125` placeholders) and border 0 are left out, and `numFmtId` 0 (General) gives no `numFmt`. `applyFont` and the other apply flags are ignored, as Excel does for cell formats. - Values: `t="s"`, `"inlineStr"` and `"str"` are strings (or rich text), with `_xHHHH_` escapes decoded; `"b"` booleans; `"e"` errors, including codes newer than the seven of ECMA-376 (`#SPILL!`, `#CALC!`, …), returned as written; `"d"` ISO dates; numbers otherwise, converted to `Date` when their number format is a date format (§3.4.1). A formula's cached value sets `value` and `type`; without one the cell is `type: 'empty'` with its `formula`. Shared formulas are expanded (§12 Q6), except from a master longer than 8,192 characters and except copies longer than `maxCellTextLength` (§3.4.2); data-table formulas (`t="dataTable"`) give their cached values only. - **`rawText`** (from 2.1.0): converting `` to a JavaScript number loses what the file says: `1234567890123456789` reads as `1234567890123456800`, `50.30` as `50.3`, `1E-7` as `1e-7`, `-0` as `0`, and a `t="d"` cell is always a `Date`. With `rawText: true`, such cells also get `cell.rawText`, the characters of `` exactly as stored: XML entities and character references decoded and line ends normalised (as for any XML text), nothing trimmed, no `_xHHHH_` decoding. `value` and `type` are what they would be without the option, so the cell still says it was a number or a date. Default false: no `rawText` key is added and the model is the same as before 2.1.0. The worker's `read` passes the option through; `importDataset` (§5.6) returns coerced column values, not cells, and does not take it. @@ -1745,7 +1745,7 @@ export function isDataLossWarning(warning: ExcelWarning | ExcelWarningCode): boo | Warning code | Data loss | Situation and recovery | |---|---|---| -| `UNSUPPORTED_PART` | yes | Charts, drawings, pivots, comments, VBA, … are outside the model and not in the result; one warning per kind (so it cannot flood the list), `partKind` names it. Since 2.5 also ActiveX controls (`'activeX'`), embedded packages (`'embeddedPackage'`), ribbon customisations (`'customUI'`), Office web add-ins (`'webExtension'`), names OPC forbids (`'invalidPartName'`) and parts no relationship reaches (`'unreferencedPart'`), found anywhere in the package (§5.2, package scan); the last two are one warning each, with every name in `parts`. The cell values are complete; filter by `partKind` to accept the kinds you do not need | +| `UNSUPPORTED_PART` | yes | Charts, drawings, pivots, comments, VBA, … are outside the model and not in the result; one warning per kind (so it cannot flood the list), `partKind` names it. Since 2.5 also ActiveX controls (`'activeX'`), embedded packages (`'embeddedPackage'`), ribbon customisations (`'customUI'`), Office web add-ins (`'webExtension'`), names and relationships OPC forbids (`'invalidPartName'`) and parts no relationship reaches (`'unreferencedPart'`), found anywhere in the package (§5.2, package scan); the last two are one warning each, with every name in `parts`. The cell values are complete; filter by `partKind` to accept the kinds you do not need | | `INVALID_STYLE_INDEX` | no | Cell refers to a missing `xf`; default style used. Declared for compatibility; 2.x leaves such a cell unstyled without a warning | | `INVALID_SHARED_STRING` | yes | Index out of range; cell left empty | | `CELL_OUT_OF_BOUNDS` / `INVALID_CELL_REF` | yes | Cell skipped | @@ -1806,7 +1806,7 @@ if (lost.length) throw new Error(`Refused: ${[...new Set(lost.map((w) => w.code) | **Formula injection into CSV** | Guard on by default (§5.3). | | **Malicious hyperlinks** | The writer allows only `http`, `https` and `mailto` by default, and rejects `javascript:`, `data:`, `vbscript:` and anything else not listed. The reader returns targets verbatim (it cannot know the consumer's policy): apps that render them, such as the viewer, must check the scheme. | | **External references** | External links, OLE objects, DDE and data connections are not read or followed. The reader resolves relationships only within the package. | -| **Active, embedded and hidden content** (a file that is harmless to this reader but carries something for whoever opens it next in Excel) | Never run, opened or inflated, and reported so an app can refuse the file (since 2.5): the package scan (§5.2) walks the whole relationship graph and reports ActiveX controls (`'activeX'`), embedded files (`'embeddedPackage'`), ribbon customisations with callbacks (`'customUI'`), Office web add-ins (`'webExtension'`), OLE objects, VBA (with attached toolbars), Excel 4 macro sheets, external links, data connections and query tables wherever they sit, including under drawings and on sheets not read, by relationship type (case-insensitively) and by content type, and any part no relationship reaches (`'unreferencedPart'`), such as a `vbaProject.bin` or an executable placed in the zip without a relationship. Part names are compared in OPC canonical form, decoded once on both sides; two entries with equivalent names throw `ZIP_INVALID`, and names OPC forbids (encoded separators or dot segments, a trailing dot) are reported as `'invalidPartName'`, with the target followed under both readings, so percent-encoding can neither hide a part nor make one entry stand for another. Nothing is exempt by name, Office's `[trash]/` folder included (§5.2). Decoding names is one linear pass, and the signal is consulted for every zip entry while names are indexed. The scan reads relationships parts only, within the zip and XML limits. To refuse such files, check `warnings` for `UNSUPPORTED_PART` with these `partKind`s. | +| **Active, embedded and hidden content** (a file that is harmless to this reader but carries something for whoever opens it next in Excel) | Never run, opened or inflated, and reported so an app can refuse the file (since 2.5): the package scan (§5.2) walks the whole relationship graph and reports ActiveX controls (`'activeX'`), embedded files (`'embeddedPackage'`), ribbon customisations with callbacks (`'customUI'`), Office web add-ins (`'webExtension'`), OLE objects, VBA (with attached toolbars), Excel 4 macro sheets, external links, data connections and query tables wherever they sit, including under drawings and on sheets not read, by relationship type (case-insensitively) and by content type, and any part no relationship reaches (`'unreferencedPart'`), such as a `vbaProject.bin` or an executable placed in the zip without a relationship. Part names are compared in OPC canonical form, decoded once on both sides; two entries with equivalent names throw `ZIP_INVALID`, and names and relationships OPC forbids (encoded separators or dot segments, a trailing dot, a target naming package metadata, a relationship without `Id` or `Target`, a name too long for any zip entry) are reported as `'invalidPartName'`, with the target followed under both readings and every relationships part in the zip classified, so percent-encoding can neither hide a part nor make one entry stand for another. Nothing is exempt by name, Office's `[trash]/` folder included (§5.2). Decoding names is one linear pass, targets too long to name a part are not decoded at all, and the signal is consulted for every zip entry while names are indexed. The scan reads relationships parts only, within the zip and XML limits. To refuse such files, check `warnings` for `UNSUPPORTED_PART` with these `partKind`s. | | **Hostile relationships parts** | Since 2.5 the scan parses the relationships part of every reached part, also of sheets left out by `sheets` and of nested parts (drawings, tables, …). 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). | diff --git a/packages/javascript-excel/src/internal/read/opc.ts b/packages/javascript-excel/src/internal/read/opc.ts index 5d35827..3b2a126 100644 --- a/packages/javascript-excel/src/internal/read/opc.ts +++ b/packages/javascript-excel/src/internal/read/opc.ts @@ -28,18 +28,44 @@ export interface Relationship { * `.%2E`), or a segment other than `.` and `..` that ends in a dot. */ forbidden?: boolean; - /** For a forbidden target, the part it names when escapes are taken literally, if that differs from `target`. */ - literalTarget?: string; + /** For a forbidden target, the part it names under the other reading (see resolveTarget), if that differs from `target`. */ + altTarget?: string; + /** + * The target is longer than any part name a zip entry can carry (TOO_LONG): + * it was not resolved, `target` is '' and matches no part. + */ + tooLong?: boolean; external: boolean; } +/** + * A zip entry name has at most 65,535 bytes, and each character of a target + * stands for at least a third of a byte once decoded (`%XX` is one byte), so a + * target or PartName longer than this cannot name any part. It is never + * canonicalised (that would cost time for nothing) and counts as forbidden. + */ +export const TOO_LONG: number = 3 * 65_535; + export class Package { /** partKey(name) -> entry. */ private readonly parts = new Map(); /** entry -> partKey(entry.name), computed once. */ private readonly keys = new Map(); - /** Zip entries whose names OPC forbids (see `forbiddenName`), in zip order. */ + /** + * Names OPC forbids, in the order found: zip entries (see `forbiddenName`), + * then `[Content_Types].xml` when one of its PartNames is forbidden. + */ readonly forbiddenNames: string[] = []; + /** + * Relationships that are not well-formed, by relationships part (entry + * name): an element without `Id` (or with an empty one) or without + * `Target`. They are left out of `rels()`, so the model ignores them as + * 2.4.0 did, but the package scan classifies them. One without `Type` is + * listed with type '' (nothing to classify). + */ + readonly malformedRels: Map = new Map(); + /** 2.4.0's override table (raw lower-case PartName, last wins), for format detection only. */ + private readonly legacyOverrides = new Map(); /** partKey(part name) -> content types, in the order [Content_Types].xml lists them. */ private readonly overrides = new Map(); /** Extension (lower case) -> content types. */ @@ -78,6 +104,7 @@ export class Package { } part(name: string): ZipEntryInfo | undefined { + if (name.length > TOO_LONG) return undefined; // cannot name a part (TOO_LONG) return this.parts.get(partKey(name)); } @@ -88,6 +115,7 @@ export class Package { async loadContentTypes(): Promise { const entry = this.part("[Content_Types].xml"); if (!entry) return; + let badPartName = false; await this.ctx.parse(entry, { open: (name, a) => { if (name === "Default") { @@ -97,12 +125,24 @@ export class Package { } else if (name === "Override") { const part = a.get("PartName"); const type = a.get("ContentType"); - if (part && type) push(this.overrides, partKey(part), type); + if (!part || !type) return; + this.legacyOverrides.set(stripSlash(part).toLowerCase(), type); + if (part.length > TOO_LONG) { + badPartName = true; + return; + } + if (forbiddenName(part, false)) badPartName = true; + // Under both readings, so a type given through a forbidden spelling still applies. + const key = partKey(part); + push(this.overrides, key, type); + const decoded = partKey(resolveTarget("", part)); + if (decoded !== key) push(this.overrides, decoded, type); } }, close: () => {}, text: () => {}, }); + if (badPartName) this.forbiddenNames.push(entry.name); } /** The content type of a part: the last Override for an equivalent name, else the last Default for its extension (as 2.4.0). */ @@ -116,6 +156,7 @@ export class Package { * scan checks each, so a later passive entry cannot hide an active one. */ contentTypes(name: string): string[] { + if (name.length > TOO_LONG) return []; const key = partKey(name); const o = this.overrides.get(key); if (o) return o; @@ -124,9 +165,9 @@ export class Package { return (dot > slash ? this.defaults.get(key.slice(dot + 1)) : undefined) ?? []; } - /** Content types of all overrides (for format detection). */ + /** Content types of the overrides for format detection: one per raw PartName, the last given, exactly as 2.4.0. */ get overrideTypes(): string[] { - return [...this.overrides.values()].flat(); + return [...this.legacyOverrides.values()]; } /** The relationships part of `source` ('' for the package), whether or not it exists. */ @@ -170,29 +211,70 @@ export class Package { const slash = src.lastIndexOf("/"); const dir = slash === -1 ? "" : src.slice(0, slash + 1); const out: Relationship[] = []; + const malformed: Relationship[] = []; await this.ctx.parse(entry, { open: (name, a: XmlAttrs) => { if (name !== "Relationship") return; const id = a.get("Id"); - const type = a.get("Type"); + const type = a.get("Type") ?? ""; const target = a.get("Target"); - if (!id || !type || target === undefined) return; const external = (a.get("TargetMode") ?? "").toLowerCase() === "external"; - const rel: Relationship = { id, type, kind: type.slice(type.lastIndexOf("/") + 1), target: external ? target : resolveTarget(dir, target), external }; - if (!external && forbiddenName(stripFragment(target), true)) { + const rel: Relationship = { id: id ?? "", type, kind: type.slice(type.lastIndexOf("/") + 1), target: "", external }; + if (target === undefined) { + malformed.push(rel); // classified by its type alone + return; + } + if (external) rel.target = target; + else if (target.trim().length > TOO_LONG) { + rel.tooLong = true; rel.forbidden = true; - const literal = resolveTargetLiteral(dir, target); - if (partKey(literal) !== partKey(rel.target)) rel.literalTarget = literal; + } else { + const readings = resolveReadings(dir, target); + rel.target = readings.target; + const key = partKey(rel.target); + if (forbiddenName(stripFragment(target), true) || isPackageMetadata(key)) rel.forbidden = true; + if (readings.alt !== undefined) { + const altKey = partKey(readings.alt); + if (altKey !== key) { + rel.altTarget = readings.alt; + if (isPackageMetadata(altKey)) rel.forbidden = true; + } + } } - out.push(rel); + if (!id || !type) malformed.push(rel); + else out.push(rel); }, close: () => {}, text: () => {}, }); + if (malformed.length) this.malformedRels.set(entry.name, malformed); return out; } } +/** + * A relationships part (`…/_rels/.rels`) or `[Content_Types].xml`, by + * part key: package metadata that OPC forbids as a relationship target. + */ +export function isPackageMetadata(key: string): boolean { + if (key === "[content_types].xml") return true; + if (!key.endsWith(".rels")) return false; + const slash = key.lastIndexOf("/"); + const parent = key.slice(0, slash === -1 ? 0 : slash); + return parent === "_rels" || parent.endsWith("/_rels"); +} + +/** The owner of a relationships part (`a/_rels/b.xml.rels` -> `a/b.xml`, `_rels/.rels` -> ''), or undefined if `name` is not one. */ +export function relsOwner(name: string): string | undefined { + const slash = name.lastIndexOf("/"); + const file = name.slice(slash + 1); + if (slash === -1 || !/\.rels$/i.test(file)) return undefined; + const parent = name.slice(0, slash); + const parentSlash = parent.lastIndexOf("/"); + if (parent.slice(parentSlash + 1).toLowerCase() !== "_rels") return undefined; + return parent.slice(0, parentSlash + 1) + file.slice(0, -5); +} + function stripSlash(name: string): string { return name.startsWith("/") ? name.slice(1) : name; } @@ -286,16 +368,10 @@ export function canonicalPartName(name: string): string { } if (b === 0x25 || b === 0x2f || b === 0x5c || b >= 0x80) { // Kept encoded unless it starts a valid UTF-8 sequence. - const len = b >= 0xc2 && b <= 0xdf ? 2 : b >= 0xe0 && b <= 0xef ? 3 : b >= 0xf0 && b <= 0xf4 ? 4 : 0; - let cp = len === 2 ? b & 0x1f : len === 3 ? b & 0x0f : b & 0x07; - let ok = len > 0; - for (let k = 1; ok && k < len; k++) { - const cb = hexByte(name, i + 3 * k); - if (cb < 0 || (cb & 0xc0) !== 0x80) ok = false; - else if (k === 1 && ((b === 0xe0 && cb < 0xa0) || (b === 0xed && cb > 0x9f) || (b === 0xf0 && cb < 0x90) || (b === 0xf4 && cb > 0x8f))) ok = false; - else cp = (cp << 6) | (cb & 0x3f); - } - if (ok) { + const len = b >= 0x80 ? utf8Length(name, i, b) : 0; + if (len) { + let cp = len === 2 ? b & 0x1f : len === 3 ? b & 0x0f : b & 0x07; + for (let k = 1; k < len; k++) cp = (cp << 6) | (hexByte(name, i + 3 * k) & 0x3f); emit(i, String.fromCodePoint(cp), i + 3 * len); i += 3 * len; } else { @@ -313,6 +389,21 @@ export function canonicalPartName(name: string): string { const HEX: readonly string[] = Array.from({ length: 256 }, (_, b) => `%${b.toString(16).toUpperCase().padStart(2, "0")}`); +/** + * The length in bytes of the valid UTF-8 sequence whose lead byte `b` is the + * escape at `i` (its continuation bytes are the escapes that follow), or 0. + * Rejects overlong forms, surrogates and code points above U+10FFFF. + */ +function utf8Length(name: string, i: number, b: number): number { + const len = b >= 0xc2 && b <= 0xdf ? 2 : b >= 0xe0 && b <= 0xef ? 3 : b >= 0xf0 && b <= 0xf4 ? 4 : 0; + for (let k = 1; k < len; k++) { + const cb = hexByte(name, i + 3 * k); + if (cb < 0 || (cb & 0xc0) !== 0x80) return 0; + if (k === 1 && ((b === 0xe0 && cb < 0xa0) || (b === 0xed && cb > 0x9f) || (b === 0xf0 && cb < 0x90) || (b === 0xf4 && cb > 0x8f))) return 0; + } + return len; +} + /** The byte of the escape `%XX` at `i`, or -1. */ function hexByte(s: string, i: number): number { if (s.charCodeAt(i) !== 0x25 || i + 2 >= s.length) return -1; @@ -340,6 +431,51 @@ export function partKey(name: string): string { * OPC allows this is the only reading; for others, see resolveTargetLiteral. */ export function resolveTarget(baseDir: string, target: string): string { + return resolveReadings(baseDir, target).target; +} + +/** + * Both readings of a relationship target. `target` is the one `read` uses, + * as 2.4.0 resolved it: decoded (resolveTargetDecoded), or, when the target + * has an escape that is not valid UTF-8 or a `%` that starts no escape (2.4.0's + * decodeURIComponent threw and the target was kept raw), literal + * (resolveTargetLiteral). `alt` is the other reading, when the target has + * an escape that can change its structure (`%2F`, `%5C`, `%2E`). + */ +export function resolveReadings(baseDir: string, target: string): { target: string; alt?: string } { + const t = stripFragment(target); + const structural = /%(2f|5c|2e)/i.test(t); + if (malformedEscapes(t)) { + const literal = resolveTargetLiteral(baseDir, t); + return structural ? { target: literal, alt: resolveTargetDecoded(baseDir, t) } : { target: literal }; + } + const decoded = resolveTargetDecoded(baseDir, t); + return structural ? { target: decoded, alt: resolveTargetLiteral(baseDir, t) } : { target: decoded }; +} + +/** True when decodeURIComponent would throw: a `%` that starts no escape, or escapes that are not valid UTF-8. Linear. */ +export function malformedEscapes(name: string): boolean { + let i = name.indexOf("%"); + while (i !== -1) { + const b = hexByte(name, i); + if (b < 0) return true; + if (b < 0x80) i += 3; + else { + const len = utf8Length(name, i, b); + if (!len) return true; + i += 3 * len; + } + i = name.indexOf("%", i); + } + return false; +} + +/** + * The decoder's reading: `/`, `\`, `%2F` and `%5C` separate segments, and a + * segment that is `.` or `..` once `%2E` is decoded is a dot segment. Each + * other segment is put in canonical form once. + */ +export function resolveTargetDecoded(baseDir: string, target: string): string { const t = stripFragment(target).replace(/%2f|%5c|\\/gi, "/"); const segments = t.startsWith("/") ? [] : baseDir.split("/").filter((s) => s !== ""); for (const seg of t.split("/")) { diff --git a/packages/javascript-excel/src/internal/read/scan.ts b/packages/javascript-excel/src/internal/read/scan.ts index 0ff1b35..53c526c 100644 --- a/packages/javascript-excel/src/internal/read/scan.ts +++ b/packages/javascript-excel/src/internal/read/scan.ts @@ -7,7 +7,7 @@ import { FormatError } from "../../errors"; import type { ExcelPartKind } from "../../warnings"; -import { partKey, type Package, type Relationship } from "./opc"; +import { partKey, relsOwner, type Package, type Relationship } from "./opc"; import { ABORT_EVERY } from "./sheet"; /** @@ -206,49 +206,82 @@ export async function scanPackageParts(pkg: Package): Promise { const found: ScannedPart[] = []; const foundKeys = new Set(); const forbidden = new Set(pkg.forbiddenNames); - /** partKey of the parts accounted for. */ + /** partKey of the parts accounted for (reached from the package root). */ const reached = new Set([partKey("[Content_Types].xml")]); - const queue: string[] = [""]; - const visit = (target: string): void => { + /** partKey of the parts whose relationships are queued: a part reached as a target is queued even if it was accounted for otherwise (a relationships part, [Content_Types].xml). */ + const queued = new Set([""]); + /** Relationships parts parsed, by partKey. */ + const parsed = new Set(); + // Sources to read, with whether what they reach counts as reached. + const queue: Array<{ source: string; counts: boolean }> = [{ source: "", counts: true }]; + const visit = (target: string, counts: boolean): void => { const entry = pkg.part(target); if (!entry) return; const key = pkg.keyOf(entry); - if (reached.has(key)) return; - reached.add(key); - queue.push(entry.name); + if (counts) reached.add(key); + if (queued.has(key)) return; + queued.add(key); + queue.push({ source: entry.name, counts }); }; - for (let q = 0; q < queue.length; q++) { - const pause = ctx.step(); - if (pause) await pause; - const source = queue[q]!; - let rels: Relationship[]; - try { - rels = await pkg.rels(source, { peek: true }); - } catch (err) { - if (err instanceof FormatError && err.code === "XML_MALFORMED") continue; - throw err; + const classify = (rel: Relationship, source: string, relsPart: string): void => { + const targets = rel.external || rel.tooLong || rel.target === "" ? [] : rel.altTarget === undefined ? [rel.target] : [rel.target, rel.altTarget]; + for (const target of targets.length ? targets : [undefined]) { + const kind = partKindOf(rel, target === undefined ? [] : pkg.contentTypes(target)); + if (!kind) continue; + const part = target ?? (rel.external ? source || relsPart : relsPart); + const key = `${kind}\u0000${partKey(part)}`; + if (foundKeys.has(key)) continue; + foundKeys.add(key); + found.push({ kind, part, source, external: rel.external }); } - const relsPart = pkg.part(pkg.relsPartOf(source)); - if (relsPart) reached.add(pkg.keyOf(relsPart)); - for (let i = 0; i < rels.length; i++) { - if ((i & ABORT_EVERY) === ABORT_EVERY) ctx.checkAbort(); - const rel = rels[i]!; - if (rel.forbidden && relsPart) forbidden.add(relsPart.name); - const targets = rel.external ? [] : rel.literalTarget === undefined ? [rel.target] : [rel.target, rel.literalTarget]; - for (const target of rel.external ? [undefined] : targets) { - const kind = partKindOf(rel, target === undefined ? [] : pkg.contentTypes(target)); - if (!kind) continue; - const part = target ?? (source || pkg.relsPartOf(source)); - const key = `${kind}\u0000${partKey(part)}`; - if (foundKeys.has(key)) continue; - foundKeys.add(key); - found.push({ kind, part, source, external: rel.external }); + }; + const drain = async (): Promise => { + for (let q = 0; q < queue.length; q++) { + const pause = ctx.step(); + if (pause) await pause; + const { source, counts } = queue[q]!; + const relsEntry = pkg.part(pkg.relsPartOf(source)); + if (!relsEntry) continue; + const relsKey = pkg.keyOf(relsEntry); + if (parsed.has(relsKey)) continue; + parsed.add(relsKey); + let rels: Relationship[]; + try { + rels = await pkg.rels(source, { peek: true }); + } catch (err) { + if (err instanceof FormatError && err.code === "XML_MALFORMED") continue; + throw err; + } + if (counts) reached.add(relsKey); + const malformed = pkg.malformedRels.get(relsEntry.name) ?? []; + if (malformed.length) forbidden.add(relsEntry.name); + const all = malformed.length ? [...rels, ...malformed] : rels; + for (let i = 0; i < all.length; i++) { + if ((i & ABORT_EVERY) === ABORT_EVERY) ctx.checkAbort(); + const rel = all[i]!; + if (rel.forbidden) forbidden.add(relsEntry.name); + classify(rel, source, relsEntry.name); + if (rel.external || rel.tooLong) continue; + visit(rel.target, counts); + if (rel.altTarget !== undefined) visit(rel.altTarget, counts); } - for (const t of targets) visit(t); } + queue.length = 0; + }; + await drain(); + // Every relationships part is read as its owner's, even if nothing reaches the owner, so nothing + // listed in one escapes classification. What only these reach is not accounted for. + const entries = ctx.zip.entries; + for (let i = 0; i < entries.length; i++) { + if ((i & ABORT_EVERY) === ABORT_EVERY) ctx.checkAbort(); + const e = entries[i]!; + if (e.name.endsWith("/") || parsed.has(pkg.keyOf(e))) continue; + const owner = relsOwner(e.name); + if (owner === undefined) continue; + queue.push({ source: owner, counts: false }); + await drain(); } const unreferenced: string[] = []; - const entries = ctx.zip.entries; for (let i = 0; i < entries.length; i++) { if ((i & ABORT_EVERY) === ABORT_EVERY) ctx.checkAbort(); const e = entries[i]!; diff --git a/packages/javascript-excel/src/warnings.ts b/packages/javascript-excel/src/warnings.ts index ececb1c..22bbce4 100644 --- a/packages/javascript-excel/src/warnings.ts +++ b/packages/javascript-excel/src/warnings.ts @@ -41,8 +41,8 @@ export type ExcelWarningCode = * in camelCase for the document-property parts. The kinds the package scan * adds are named for what they are: `'activeX'` (ActiveX controls), * `'embeddedPackage'` (embedded files), `'customUI'` (ribbon customisation), - * `'webExtension'` (Office web add-ins), `'invalidPartName'` (a part name or - * relationship target OPC forbids) and `'unreferencedPart'` (a part no relationship reaches). Kinds may be added in a minor + * `'webExtension'` (Office web add-ins), `'invalidPartName'` (a part name, + * relationship target, Override PartName or relationship OPC forbids) and `'unreferencedPart'` (a part no relationship reaches). Kinds may be added in a minor * release, so a `switch` over it needs a `default` branch. */ export type ExcelPartKind = diff --git a/packages/javascript-excel/test/read/name-cost.test.ts b/packages/javascript-excel/test/read/name-cost.test.ts index 8400be9..1e7e56b 100644 --- a/packages/javascript-excel/test/read/name-cost.test.ts +++ b/packages/javascript-excel/test/read/name-cost.test.ts @@ -11,10 +11,13 @@ const REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships const rels = (target: string) => ``; +/** Limits wide enough for the big inputs here (the defaults refuse a 96 MB relationships part). */ +const BIG = { maxEntryBytes: 256 * 1024 * 1024, maxRatio: 1e7 }; + async function timed(bytes: Uint8Array, signal?: AbortSignal): Promise { const t0 = performance.now(); try { - await read(bytes, { signal, limits: { maxEntryBytes: 64 * 1024 * 1024 } }); + await read(bytes, { signal, limits: BIG }); } catch (e) { if ((e as Error).message !== "stop") throw e; } @@ -47,6 +50,32 @@ describe("cost of decoding part names", () => { expect(t).toBeLessThan(5 * base + 500); }, 60_000); + // Review 3: targets longer than any zip entry name (65,535 bytes) are never canonicalised. + const manyRels = (target: string, n: number) => + `${Array.from({ length: n }, (_, i) => ``).join("")}`; + + it("24 relationship targets of 4 MB of '%' cost about what plain ones do", async () => { + const hostile = await build({ sheets: [CELL], override: { "xl/_rels/workbook.xml.rels": manyRels("%".repeat(4_000_000), 24) } }); + const plain = await build({ sheets: [CELL], override: { "xl/_rels/workbook.xml.rels": manyRels("a".repeat(4_000_000), 24) } }); + const base = await best(plain); + const t = await best(hostile); + expect(t).toBeLessThan(3 * base + 500); + const r = await read(hostile, { limits: BIG }); + expect(r.warnings.map((w) => w.partKind)).toContain("invalidPartName"); + }, 120_000); + + it("one 16 MB target of '%': about the plain cost, and an abort lands promptly", async () => { + const hostile = await build({ sheets: [CELL], override: { "xl/_rels/workbook.xml.rels": manyRels("%".repeat(16_000_000), 1) } }); + const plain = await build({ sheets: [CELL], override: { "xl/_rels/workbook.xml.rels": manyRels("a".repeat(16_000_000), 1) } }); + const base = await best(plain); + expect(await best(hostile)).toBeLessThan(3 * base + 500); + let start = 0; + const signal = { get aborted() { return performance.now() - start > 5; }, reason: new Error("stop") } as unknown as AbortSignal; + start = performance.now(); + const t = await timed(hostile, signal); + expect(t).toBeLessThan(Math.max(100, base / 2)); + }, 120_000); + it("an abort is honoured promptly while the zip's part names are indexed", async () => { const parts = Object.fromEntries(Array.from({ length: 100 }, (_, i) => [`x${i}/${"%E4".repeat(20_000)}`, "x"])); const bytes = await build({ sheets: [CELL], parts }); diff --git a/packages/javascript-excel/test/read/package-scan.test.ts b/packages/javascript-excel/test/read/package-scan.test.ts index e158652..5101773 100644 --- a/packages/javascript-excel/test/read/package-scan.test.ts +++ b/packages/javascript-excel/test/read/package-scan.test.ts @@ -12,7 +12,8 @@ import { readImpl } from "../../src/internal/read/reader"; import { scanPackageParts } from "../../src/internal/read/scan"; import { openZip } from "../../src/internal/zip/read"; import { importDataset } from "../../src/import"; -import { read, type ReadOptions } from "../../src/read"; +import { detectFormat, read, type ReadOptions } from "../../src/read"; +import { writeZip } from "../../src/internal/zip/write"; import type { ExcelWarning } from "../../src/warnings"; import { ALL } from "../conformance/corpus"; import { build, type BuildOptions } from "./build"; @@ -318,6 +319,91 @@ describe("names OPC forbids (partKind 'invalidPartName')", () => { }); }); +describe("review 3: nothing listed in any relationships part escapes the scan", () => { + const OLE_AND_PKG = (prefix: string) => rels([["rO", "oleObject", `${prefix}embeddings/ole.bin`], ["rP", "package", `${prefix}embeddings/doc.docx`]]); + const BIN_OCTET = contentTypes({ bin: "application/octet-stream" }); + + it("a relationship to a relationships part: that part's own relationships are read, and the target is invalidPartName", async () => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rD", "drawing", "../_rels/workbook.xml.rels"], ["rX", "customXml", "../_rels/_rels/workbook.xml.rels.rels"], ["rI", "image", "../embeddings/ole.bin"]] }, + parts: { "xl/_rels/_rels/workbook.xml.rels.rels": OLE_AND_PKG("../"), "xl/embeddings/ole.bin": "o", "xl/embeddings/doc.docx": "d" }, + override: { "[Content_Types].xml": BIN_OCTET }, + }); + const kinds = unsupported(r.warnings).map((w) => w[0]); + expect(kinds).toEqual(expect.arrayContaining(["oleObject", "embeddedPackage", "invalidPartName"])); + expect(r.warnings.find((w) => w.partKind === "invalidPartName")!.parts).toEqual(["xl/worksheets/_rels/sheet1.xml.rels"]); + }); + + it("a relationship to [Content_Types].xml: its relationships part is read too", async () => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rD", "drawing", "/[Content_Types].xml"]] }, + parts: { "_rels/[Content_Types].xml.rels": OLE_AND_PKG("/xl/"), "xl/embeddings/ole.bin": "o", "xl/embeddings/doc.docx": "d" }, + }); + expect(unsupported(r.warnings).map((w) => w[0])).toEqual(expect.arrayContaining(["oleObject", "embeddedPackage", "invalidPartName"])); + }); + + it("a relationships part whose owner nothing reaches is still classified; its targets stay unreferenced", async () => { + const r = await readOf({ + sheets: [CELL], + parts: { "xl/ghost/_rels/ghost.xml.rels": OLE_AND_PKG("/xl/"), "xl/embeddings/ole.bin": "o", "xl/embeddings/doc.docx": "d" }, + }); + expect(unsupported(r.warnings).map((w) => w[0])).toEqual(["oleObject", "embeddedPackage", "unreferencedPart"]); + expect(r.warnings.at(-1)!.parts).toEqual(["xl/ghost/_rels/ghost.xml.rels", "xl/embeddings/ole.bin", "xl/embeddings/doc.docx"]); + }); + + it("a relationship without an Id is classified and reported; the model still ignores it", async () => { + const r = await readOf({ + sheets: [CELL], + parts: { "xl/vbaProject.bin": "v" }, + override: { + "xl/_rels/workbook.xml.rels": ``, + }, + }); + expect(unsupported(r.warnings)).toEqual([["vbaProject", "xl/vbaProject.bin"], ["invalidPartName", "xl/_rels/workbook.xml.rels"]]); + expect(r.workbook.sheets.map((s) => s.name)).toEqual(["Sheet1"]); + }); + + it("a relationship without a Target is classified by its type and reported", async () => { + const r = await readOf({ sheets: [CELL], sheetRels: { 0: [] }, override: { "xl/worksheets/_rels/sheet1.xml.rels": `` } }); + expect(unsupported(r.warnings)).toEqual([["oleObject", "xl/worksheets/_rels/sheet1.xml.rels"], ["invalidPartName", "xl/worksheets/_rels/sheet1.xml.rels"]]); + }); + + it.each([["/xl/x/%2E%2E/o.bin"], ["/xl/x/../o.bin"]])("an Override PartName %s: invalidPartName, and its type applies under both readings", async (partName) => { + const r = await readOf({ + sheets: [CELL], + sheetRels: { 0: [["rI", "image", "../o.bin"]] }, + parts: { "xl/o.bin": "o" }, + override: { "[Content_Types].xml": contentTypes({}, { [partName]: "application/vnd.openxmlformats-officedocument.oleObject" }) }, + }); + expect(unsupported(r.warnings)).toEqual([["image", "xl/o.bin"], ["oleObject", "xl/o.bin"], ["invalidPartName", "[Content_Types].xml"]]); + }); + + it("a target with a malformed escape is read as 2.4.0 read it (kept raw, not decoded)", async () => { + const name = "xl/%2f/%3%%\u00e9.xml"; + const bytes = await build({ + sheets: [CELL], + override: { + "xl/_rels/workbook.xml.rels": rels([["rS1", "worksheet", `/${JSON.parse(`"${name}"`)}`]]), + "xl/worksheets/sheet1.xml": null, + [JSON.parse(`"${name}"`)]: `${CELL}`, + }, + }); + const r = await read(bytes); + expect(r.workbook.sheets[0]!.rows[0]![0]!.value).toBe(1); + expect(unsupported(r.warnings).map((w) => w[0])).toEqual(["invalidPartName"]); + }); + + it("detectFormat without package relationships: duplicate Overrides, the last wins (as 2.4.0)", async () => { + const bytes = await writeZip([ + { name: "[Content_Types].xml", data: `` }, + { name: "xl/workbook.xml", data: "" }, + ]); + expect(await detectFormat(bytes)).toBe("xlsx"); + }); +}); + describe("content types", () => { it("equivalent Override part names: an active content type is never lost to a later passive one", async () => { const r = await readOf({ From d568b1fb40eb290ce442dda273878e0af483c426 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 13:14:31 +0100 Subject: [PATCH 6/6] JSE-72 review 4: 2.4.0 content types for format decisions, encoded .rels names - contentType() (format decisions) uses 2.4.0's raw PartName table, so a forbidden Override such as /xl/x/../workbook.xml cannot change the format; the scan still checks both readings through contentTypes(). - Orphan relationships parts are recognised by canonical name, so %5Frels and .r%65ls spellings are classified too. - Docs and changeset: the length limit is taken before dot segments are resolved (a padded target is not followed); every relationships part, orphans included, is parsed, so a DTD in an orphan .rels now throws. --- .changeset/package-scan-active-content.md | 4 ++-- docs/api.md | 6 +++--- .../javascript-excel/src/internal/read/opc.ts | 17 ++++++++++++----- .../src/internal/read/scan.ts | 2 +- .../test/read/package-scan.test.ts | 19 +++++++++++++++++++ 5 files changed, 37 insertions(+), 11 deletions(-) diff --git a/.changeset/package-scan-active-content.md b/.changeset/package-scan-active-content.md index cea3010..69b3ebd 100644 --- a/.changeset/package-scan-active-content.md +++ b/.changeset/package-scan-active-content.md @@ -2,6 +2,6 @@ "javascript-excel": minor --- -`read` (and `importDataset`, which passes read warnings on) now walks the whole relationship graph of the package and reports more content it does not read as `UNSUPPORTED_PART`, with six new `partKind` values: `'activeX'` (ActiveX controls), `'embeddedPackage'` (a `package` relationship, such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a ribbon customisation: the root `ui/extensibility` relationship of Office 2007 or 2010), `'webExtension'` (Office web add-ins), `'invalidPartName'` (a zip entry name, relationship target or Override PartName OPC forbids: `%2F` or `%5C` in a segment, a percent-encoded dot segment, a segment ending in a dot, a target naming a relationships part or `[Content_Types].xml`, a name too long for any zip entry; or a `` without `Id` or `Target`, which the model still ignores) and `'unreferencedPart'` (a part no relationship reaches, such as a `vbaProject.bin` or an executable placed in the zip). The last two come as one warning each, with every name in a new `parts` field on the warning (bounded by `maxEntries`). Nothing is exempt by name: discarded parts Office 2007/2010 left under `[trash]/` are reported too; a consumer that accepts them can check that every name in `parts` starts with `[trash]/`. The scan also finds `'oleObject'`, `'vbaProject'` (now also attached toolbars and VBA signatures), `'externalLink'`, `'connections'`, `'queryTable'` and `'macrosheet'` where they were not reported before: under a drawing, under a table, or on a sheet left out by the `sheets` option. Excel 4 macro sheets with Microsoft's `xlMacrosheet` and `xlIntlMacrosheet` relationship types are now reported as `'macrosheet'`. Relationship types are compared case-insensitively, and a part with the content type of an ActiveX control, OLE object, VBA project, macro sheet, web add-in or embedded Office file (documents, templates, add-ins, slides) is reported as that kind whatever relationship reaches it; equivalent Overrides in `[Content_Types].xml` are all checked. Drawings, images, comments and the other passive kinds are reported as before. Every relationships part in the zip is classified, also one whose owner nothing reaches. The scan reads only relationships parts, within the existing zip and XML limits, never inflates the parts it reports, and consults the signal throughout; a relationships part that is not well-formed XML is reported as unreferenced instead of failing the read. Existing warnings keep their shape; a `switch` over `ExcelPartKind` needs a `default` branch, as documented. The test corpus (files from LibreOffice and openpyxl, and every file of the conformance corpus this library writes) gives no new warnings. +`read` (and `importDataset`, which passes read warnings on) now walks the whole relationship graph of the package and reports more content it does not read as `UNSUPPORTED_PART`, with six new `partKind` values: `'activeX'` (ActiveX controls), `'embeddedPackage'` (a `package` relationship, such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a ribbon customisation: the root `ui/extensibility` relationship of Office 2007 or 2010), `'webExtension'` (Office web add-ins), `'invalidPartName'` (a zip entry name, relationship target or Override PartName OPC forbids: `%2F` or `%5C` in a segment, a percent-encoded dot segment, a segment ending in a dot, a target naming a relationships part or `[Content_Types].xml`, a target or PartName over 196,605 characters, which is not resolved; or a `` without `Id` or `Target`, which the model still ignores) and `'unreferencedPart'` (a part no relationship reaches, such as a `vbaProject.bin` or an executable placed in the zip). The last two come as one warning each, with every name in a new `parts` field on the warning (bounded by `maxEntries`). Nothing is exempt by name: discarded parts Office 2007/2010 left under `[trash]/` are reported too; a consumer that accepts them can check that every name in `parts` starts with `[trash]/`. The scan also finds `'oleObject'`, `'vbaProject'` (now also attached toolbars and VBA signatures), `'externalLink'`, `'connections'`, `'queryTable'` and `'macrosheet'` where they were not reported before: under a drawing, under a table, or on a sheet left out by the `sheets` option. Excel 4 macro sheets with Microsoft's `xlMacrosheet` and `xlIntlMacrosheet` relationship types are now reported as `'macrosheet'`. Relationship types are compared case-insensitively, and a part with the content type of an ActiveX control, OLE object, VBA project, macro sheet, web add-in or embedded Office file (documents, templates, add-ins, slides) is reported as that kind whatever relationship reaches it; equivalent Overrides in `[Content_Types].xml` are all checked. Drawings, images, comments and the other passive kinds are reported as before. Every relationships part in the zip is classified, also one whose owner nothing reaches. The scan reads only relationships parts, within the existing zip and XML limits, never inflates the parts it reports, and consults the signal throughout; a relationships part that is not well-formed XML is reported as unreferenced instead of failing the read. Existing warnings keep their shape; a `switch` over `ExcelPartKind` needs a `default` branch, as documented. The test corpus (files from LibreOffice and openpyxl, and every file of the conformance corpus this library writes) gives no new warnings. -Behaviour changes against 2.4.0: part names are compared in OPC canonical form (percent-escapes decoded once, as UTF-8, on both sides; `%2F`, `%5C`, `%25` and invalid bytes kept encoded), so percent-encoded zip entry names are now found where 2.4.0 reported `MISSING_PART` or `NOT_XLSX`, while a target matched to an entry only because 2.4.0 decoded the target and not the entry name (a literal `%` spelled differently on the two sides) no longer matches. Two zip entries with equivalent names (for example `a b` and `a%20b`) now throw `ZIP_INVALID`, as names that differ only in case already did. Because the scan parses the relationships parts of every reached part, a DTD or an over-deep XML in one of them (also under a sheet that is not read) now throws `XML_DTD_FORBIDDEN` or `LIMIT_EXCEEDED`; 2.4.0 read such a file. +Behaviour changes against 2.4.0: part names are compared in OPC canonical form (percent-escapes decoded once, as UTF-8, on both sides; `%2F`, `%5C`, `%25` and invalid bytes kept encoded), so percent-encoded zip entry names are now found where 2.4.0 reported `MISSING_PART` or `NOT_XLSX`, while a target matched to an entry only because 2.4.0 decoded the target and not the entry name (a literal `%` spelled differently on the two sides) no longer matches. Two zip entries with equivalent names (for example `a b` and `a%20b`) now throw `ZIP_INVALID`, as names that differ only in case already did. Because the scan parses every relationships part in the zip, a DTD or an over-deep XML in one of them (also under a sheet that is not read, or in an orphan relationships part) now throws `XML_DTD_FORBIDDEN` or `LIMIT_EXCEEDED`; 2.4.0 read such a file. A relationship target or Override PartName longer than 196,605 characters is not resolved and is reported as `'invalidPartName'`; the length is checked before dot segments are resolved, so a part reachable only through such a padded target (for example 200 KB of `./` before `worksheets/sheet1.xml`) is now missing for `read`, where 2.4.0 read it. diff --git a/docs/api.md b/docs/api.md index 1954466..1d65aa4 100644 --- a/docs/api.md +++ b/docs/api.md @@ -879,7 +879,7 @@ How the reader works, as far as the API is concerned: - Unsupported content (drawings, charts, comments, pivot tables, tables, OLE objects, form controls, VBA, external links, chart sheets, …) gives one `UNSUPPORTED_PART` warning per kind. Chart, dialog and macro sheets are not worksheets: they are left out of `sheets` and `readSheetNames`, and defined names local to them are dropped. - **The package scan** (since 2.5). After the sheets, the reader walks the whole relationship graph, from the package root through the workbook and every sheet (also sheets left out by `sheets`) to every part those reach (drawings, VML drawings, tables, ActiveX parts, …). It reads only relationships parts, each once, within the zip and XML limits, and never inflates the parts it finds. It reports, once per kind, the kinds that are active or embedded content or a link out of the file, wherever they sit: `'activeX'` (a `control` or `activeXControlBinary` relationship), `'embeddedPackage'` (a `package` relationship, a file such as a `.docx` embedded under `xl/embeddings/`), `'customUI'` (a root `…/relationships/ui/extensibility` relationship, 2006 and 2007 namespaces: a ribbon customisation, `customUI/customUI.xml` or `customUI14.xml`), `'webExtension'` (an Office web add-in: the `webextensiontaskpanes` and `webextension` relationships, `xl/webextensions/`), and `'oleObject'`, `'vbaProject'`, `'externalLink'`, `'connections'`, `'queryTable'` and `'macrosheet'` where the workbook's and the read sheets' own relationships did not already report them (an OLE object referenced from a drawing, a query table under a table, an ActiveX control on a sheet not read). `'vbaProject'` covers the VBA family: the project, its signatures (`vbaProjectSignature`, `…Agile`, `…V3`), `wordVbaData` and toolbars attached to a macro workbook (`attachedToolbars`, `xl/attachedToolbars.bin`). Excel 4 macro sheets are macro sheets under all three relationship types, ECMA `…/macrosheet` and Microsoft's `…/xlMacrosheet` and `…/xlIntlMacrosheet` (before 2.5 only the first was reported; all three were left out of `sheets`). - **Matching** (since 2.5). Relationship types are compared without regard to case (`OLEOBJECT` is `oleObject`). A part's content type is a backstop: a part with the content type of an ActiveX control (`application/vnd.ms-office.activeX+xml`, `application/vnd.ms-office.activeX`), an OLE object (`application/vnd.openxmlformats-officedocument.oleObject`, `application/vnd.ms-office.oleObject`), VBA (`application/vnd.ms-office.vbaProject`, `…vbaProjectSignature`, `application/vnd.ms-excel.attachedToolbars`), a macro sheet (`application/vnd.ms-excel.macrosheet+xml`, `…intlmacrosheet+xml`), a web add-in (`application/vnd.ms-office.webextension+xml`, `…webextensiontaskpanes+xml`) or an embedded Office file (Word, Excel and PowerPoint documents, templates, add-ins, slides and slide shows, macro-enabled or not) is reported as that kind whatever relationship reaches it, so an `image` relationship to an OLE object gives both `'image'` and `'oleObject'`. When `[Content_Types].xml` lists several Overrides for equivalent part names (or several Defaults for one extension), each is checked, so a later passive type cannot hide an active one; `contentType` for format detection still takes the last, as before. Drawings, images, comments, tables, pivots and the other passive kinds are reported as before, from the workbook's and the read sheets' own relationships only, so an image inside a drawing still gives just `'drawing'`. -- **Part names** (since 2.5). Zip entry names and relationship targets are compared as OPC defines part-name equivalence: case-insensitively, after decoding percent-escapes once, as UTF-8, on both sides. So the target `../media/image%201.png` reaches the entry `xl/media/image%201.png` and `xl/media/image 1.png`, `%C3%A4` reaches `ä`, and an entry whose name is percent-encoded is found (2.4.0 compared the decoded target with the raw entry name, so it missed `x%6Cl/workbook.xml` and read such a file as `NOT_XLSX` or with `MISSING_PART`). The canonical form keeps `%2F`, `%5C`, `%25`, a `%` that starts no escape (as `%25`) and bytes that are not valid UTF-8 encoded, so a double encoding such as `%2541` stays the text `%41` and never reaches `A`; applying it again changes nothing. One consequence: 2.4.0 also matched a target such as `%2561` with an entry named `%61`, by decoding only the target; now the entry `%61` is the part `a`, and the target names the part `%61`, so they no longer match (in a 40,000-file name fuzz against 2.4.0 this affected 4 files, all with a literal `%` or `%25` spelled differently in the entry name and the target). **Equivalent names are an invalid package**: two entries whose names are equal in this form, for example `a b` and `a%20b`, or `%5Btrash%5D/x` and `[trash]/x`, throw `ZIP_INVALID`, as entries that differ only in case always did; 2.4.0 read such a file. **Names OPC forbids** give one `UNSUPPORTED_PART` warning with `partKind: 'invalidPartName'` and every offending name in `parts`: a zip entry name, or a relationship target, with a segment that contains `%2F` or `%5C`, a percent-encoded dot segment (`%2E`, `%2E%2E`, `.%2E`), or a segment that ends in a dot (for an entry name this includes `.` and `..`; a target may use literal `.` and `..` as relative references). The same warning covers the other shapes OPC forbids: a relationship target that names package metadata (a relationships part `…/_rels/*.rels` or `[Content_Types].xml`; the scan still reads that part's own relationships), a `` without an `Id` (or with an empty one) or without a `Target` (the model ignores it, as 2.4.0 did, but the scan classifies it by its type and, if it has one, its target), an Override `PartName` in `[Content_Types].xml` with a forbidden segment, and a target or PartName longer than 196,605 characters (three times the 65,535 bytes a zip entry name can have, so it cannot name any part; it is not decoded at all and `read` treats it as a target that matches nothing, as 2.4.0 effectively did). For a forbidden target or relationship, `parts` names the relationships part that holds it; for a PartName, `[Content_Types].xml`. A forbidden target is followed under both readings: as a decoder reads it (`%2F` and `%5C` separate segments, `%2E%2E` is `..`) and literally (the escapes are part of one name), so active content behind it is reported whichever way Excel resolves it. `read` reads the part 2.4.0 read: the decoder's reading, except when the target has a malformed escape (a `%` that starts no escape, or escapes that are not valid UTF-8): 2.4.0's decoding then failed and the whole target was taken literally, so `read` takes the literal reading too. So a sheet behind `x/%2E%2E/worksheets/sheet1.xml`, or behind `xl/%2f/%3%%é.xml` named so in both the target and the zip, is read as in 2.4.0. An Override PartName applies its content type under both readings, and every content type given for a part is checked (any active one wins). +- **Part names** (since 2.5). Zip entry names and relationship targets are compared as OPC defines part-name equivalence: case-insensitively, after decoding percent-escapes once, as UTF-8, on both sides. So the target `../media/image%201.png` reaches the entry `xl/media/image%201.png` and `xl/media/image 1.png`, `%C3%A4` reaches `ä`, and an entry whose name is percent-encoded is found (2.4.0 compared the decoded target with the raw entry name, so it missed `x%6Cl/workbook.xml` and read such a file as `NOT_XLSX` or with `MISSING_PART`). The canonical form keeps `%2F`, `%5C`, `%25`, a `%` that starts no escape (as `%25`) and bytes that are not valid UTF-8 encoded, so a double encoding such as `%2541` stays the text `%41` and never reaches `A`; applying it again changes nothing. One consequence: 2.4.0 also matched a target such as `%2561` with an entry named `%61`, by decoding only the target; now the entry `%61` is the part `a`, and the target names the part `%61`, so they no longer match (in a 40,000-file name fuzz against 2.4.0 this affected 4 files, all with a literal `%` or `%25` spelled differently in the entry name and the target). **Equivalent names are an invalid package**: two entries whose names are equal in this form, for example `a b` and `a%20b`, or `%5Btrash%5D/x` and `[trash]/x`, throw `ZIP_INVALID`, as entries that differ only in case always did; 2.4.0 read such a file. **Names OPC forbids** give one `UNSUPPORTED_PART` warning with `partKind: 'invalidPartName'` and every offending name in `parts`: a zip entry name, or a relationship target, with a segment that contains `%2F` or `%5C`, a percent-encoded dot segment (`%2E`, `%2E%2E`, `.%2E`), or a segment that ends in a dot (for an entry name this includes `.` and `..`; a target may use literal `.` and `..` as relative references). The same warning covers the other shapes OPC forbids: a relationship target that names package metadata (a relationships part `…/_rels/*.rels` or `[Content_Types].xml`; the scan still reads that part's own relationships), a `` without an `Id` (or with an empty one) or without a `Target` (the model ignores it, as 2.4.0 did, but the scan classifies it by its type and, if it has one, its target), an Override `PartName` in `[Content_Types].xml` with a forbidden segment, and a target or PartName longer than 196,605 characters (three times the 65,535 bytes a zip entry name can have). The length is checked before dot segments are resolved, and such a target or PartName is not resolved or decoded at all: `read` treats it as a target that matches nothing. So a part reachable only through a padded target (200 KB of `./` or `a/../` before `worksheets/sheet1.xml`) is missing for `read`, with `MISSING_PART`, and unreferenced; 2.4.0 read it (a behaviour change that fails closed). For a forbidden target or relationship, `parts` names the relationships part that holds it; for a PartName, `[Content_Types].xml`. A forbidden target is followed under both readings: as a decoder reads it (`%2F` and `%5C` separate segments, `%2E%2E` is `..`) and literally (the escapes are part of one name), so active content behind it is reported whichever way Excel resolves it. `read` reads the part 2.4.0 read: the decoder's reading, except when the target has a malformed escape (a `%` that starts no escape, or escapes that are not valid UTF-8): 2.4.0's decoding then failed and the whole target was taken literally, so `read` takes the literal reading too. So a sheet behind `x/%2E%2E/worksheets/sheet1.xml`, or behind `xl/%2f/%3%%é.xml` named so in both the target and the zip, is read as in 2.4.0. An Override PartName applies its content type under both readings for the scan, and every content type given for a part is checked (any active one wins). Format decisions (`read`'s choice of decoder, `detectFormat`) use the content types exactly as 2.4.0 did: the last Override with the same raw PartName, so a forbidden Override such as `/xl/x/../workbook.xml` cannot change the format. - **Unreferenced parts** (since 2.5). A part no relationship reaches (a `vbaProject.bin` without a relationship, an executable dropped into the zip, with or without a content type) gives one `UNSUPPORTED_PART` warning with `partKind: 'unreferencedPart'`: `part` names the first such part in zip order, `parts` lists every one in zip order, and the message gives their number. `parts` has at most one name per zip entry, so its length is bounded by `maxEntries` (each name by the zip format's 65,535 bytes); its strings are the entry names the zip already holds. Parts reached only through an unreferenced part are unreferenced too, and so is a relationships part that is not well-formed XML, together with the parts only it would reach (the read goes on). Every relationships part in the zip is read as its owner's relationships, also when nothing reaches its owner, so the kinds above are reported for whatever any relationships part lists; what only such a part lists stays unreferenced. Not reported: `[Content_Types].xml` and the relationships part of a reached part. Nothing is exempt by name, `[trash]/` included: Office 2007 and 2010 could leave discarded parts in a `[trash]/` folder at the package root; Excel never loads them (parts load only through relationships), but their bytes are in the file, so they are reported like any other. A consumer that wants to accept such files can check that every name in `parts` starts with `[trash]/`. The thumbnail (`docProps/thumbnail.*`), printer settings (`xl/printerSettings/*.bin`), `xl/calcChain.xml`, custom XML and the document properties have their own relationship types, so in a well-formed package they are reached; an orphaned copy of one is reported, because an exemption by name would be the place to hide a payload. Evidence: none of the test corpus files (the openpyxl, LibreOffice and import fixtures and every conformance-corpus file this library writes) has an unreferenced part. Files saved by Excel and Numbers are not in the corpus; a part they leave unreferenced would be reported, and is a bug report worth filing. - Styles: each `cellXfs` entry is one frozen `Style` (§12 Q8). Pattern fills come back with `type: 'pattern'`, so `fill.type` tells pattern and gradient fills apart. A style records only what differs from the defaults: font 0 (the workbook default font), fills 0 and 1 (the required `none` and `gray125` placeholders) and border 0 are left out, and `numFmtId` 0 (General) gives no `numFmt`. `applyFont` and the other apply flags are ignored, as Excel does for cell formats. - Values: `t="s"`, `"inlineStr"` and `"str"` are strings (or rich text), with `_xHHHH_` escapes decoded; `"b"` booleans; `"e"` errors, including codes newer than the seven of ECMA-376 (`#SPILL!`, `#CALC!`, …), returned as written; `"d"` ISO dates; numbers otherwise, converted to `Date` when their number format is a date format (§3.4.1). A formula's cached value sets `value` and `type`; without one the cell is `type: 'empty'` with its `formula`. Shared formulas are expanded (§12 Q6), except from a master longer than 8,192 characters and except copies longer than `maxCellTextLength` (§3.4.2); data-table formulas (`t="dataTable"`) give their cached values only. @@ -1806,8 +1806,8 @@ if (lost.length) throw new Error(`Refused: ${[...new Set(lost.map((w) => w.code) | **Formula injection into CSV** | Guard on by default (§5.3). | | **Malicious hyperlinks** | The writer allows only `http`, `https` and `mailto` by default, and rejects `javascript:`, `data:`, `vbscript:` and anything else not listed. The reader returns targets verbatim (it cannot know the consumer's policy): apps that render them, such as the viewer, must check the scheme. | | **External references** | External links, OLE objects, DDE and data connections are not read or followed. The reader resolves relationships only within the package. | -| **Active, embedded and hidden content** (a file that is harmless to this reader but carries something for whoever opens it next in Excel) | Never run, opened or inflated, and reported so an app can refuse the file (since 2.5): the package scan (§5.2) walks the whole relationship graph and reports ActiveX controls (`'activeX'`), embedded files (`'embeddedPackage'`), ribbon customisations with callbacks (`'customUI'`), Office web add-ins (`'webExtension'`), OLE objects, VBA (with attached toolbars), Excel 4 macro sheets, external links, data connections and query tables wherever they sit, including under drawings and on sheets not read, by relationship type (case-insensitively) and by content type, and any part no relationship reaches (`'unreferencedPart'`), such as a `vbaProject.bin` or an executable placed in the zip without a relationship. Part names are compared in OPC canonical form, decoded once on both sides; two entries with equivalent names throw `ZIP_INVALID`, and names and relationships OPC forbids (encoded separators or dot segments, a trailing dot, a target naming package metadata, a relationship without `Id` or `Target`, a name too long for any zip entry) are reported as `'invalidPartName'`, with the target followed under both readings and every relationships part in the zip classified, so percent-encoding can neither hide a part nor make one entry stand for another. Nothing is exempt by name, Office's `[trash]/` folder included (§5.2). Decoding names is one linear pass, targets too long to name a part are not decoded at all, and the signal is consulted for every zip entry while names are indexed. The scan reads relationships parts only, within the zip and XML limits. To refuse such files, check `warnings` for `UNSUPPORTED_PART` with these `partKind`s. | -| **Hostile relationships parts** | Since 2.5 the scan parses the relationships part of every reached part, also of sheets left out by `sheets` and of nested parts (drawings, tables, …). 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. | +| **Active, embedded and hidden content** (a file that is harmless to this reader but carries something for whoever opens it next in Excel) | Never run, opened or inflated, and reported so an app can refuse the file (since 2.5): the package scan (§5.2) walks the whole relationship graph and reports ActiveX controls (`'activeX'`), embedded files (`'embeddedPackage'`), ribbon customisations with callbacks (`'customUI'`), Office web add-ins (`'webExtension'`), OLE objects, VBA (with attached toolbars), Excel 4 macro sheets, external links, data connections and query tables wherever they sit, including under drawings and on sheets not read, by relationship type (case-insensitively) and by content type, and any part no relationship reaches (`'unreferencedPart'`), such as a `vbaProject.bin` or an executable placed in the zip without a relationship. Part names are compared in OPC canonical form, decoded once on both sides; two entries with equivalent names throw `ZIP_INVALID`, and names and relationships OPC forbids (encoded separators or dot segments, a trailing dot, a target naming package metadata, a relationship without `Id` or `Target`, a target or PartName over 196,605 characters) are reported as `'invalidPartName'`, with the target followed under both readings and every relationships part in the zip classified, so percent-encoding can neither hide a part nor make one entry stand for another. Nothing is exempt by name, Office's `[trash]/` folder included (§5.2). Decoding names is one linear pass, targets and PartNames over 196,605 characters are not resolved or decoded at all, and the signal is consulted for every zip entry while names are indexed. The scan reads relationships parts only, within the zip and XML limits. To refuse such files, check `warnings` for `UNSUPPORTED_PART` with these `partKind`s. | +| **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). | diff --git a/packages/javascript-excel/src/internal/read/opc.ts b/packages/javascript-excel/src/internal/read/opc.ts index 3b2a126..35e6ae0 100644 --- a/packages/javascript-excel/src/internal/read/opc.ts +++ b/packages/javascript-excel/src/internal/read/opc.ts @@ -40,9 +40,11 @@ export interface Relationship { /** * A zip entry name has at most 65,535 bytes, and each character of a target - * stands for at least a third of a byte once decoded (`%XX` is one byte), so a - * target or PartName longer than this cannot name any part. It is never - * canonicalised (that would cost time for nothing) and counts as forbidden. + * stands for at least a third of a byte once decoded (`%XX` is one byte). A + * target or PartName longer than this is not resolved or canonicalised and + * counts as forbidden. The length is taken before dot segments are resolved, + * so a padded target (`./` repeated) that would resolve to a real part is + * not followed: that part is missing for `read` (2.4.0 read it). */ export const TOO_LONG: number = 3 * 65_535; @@ -145,9 +147,14 @@ export class Package { if (badPartName) this.forbiddenNames.push(entry.name); } - /** The content type of a part: the last Override for an equivalent name, else the last Default for its extension (as 2.4.0). */ + /** The content type of a part for format decisions, exactly as 2.4.0: the last Override with the same raw PartName (case-insensitive), else the last Default for its extension. */ contentType(name: string): string | undefined { - return this.contentTypes(name).at(-1); + // Format decisions use 2.4.0's table exactly: raw lower-case PartName, the last given. + const key = stripSlash(name).toLowerCase(); + const o = this.legacyOverrides.get(key); + if (o) return o; + const dot = key.lastIndexOf("."); + return dot === -1 ? undefined : this.defaults.get(key.slice(dot + 1))?.at(-1); } /** diff --git a/packages/javascript-excel/src/internal/read/scan.ts b/packages/javascript-excel/src/internal/read/scan.ts index 53c526c..d5a2f10 100644 --- a/packages/javascript-excel/src/internal/read/scan.ts +++ b/packages/javascript-excel/src/internal/read/scan.ts @@ -276,7 +276,7 @@ export async function scanPackageParts(pkg: Package): Promise { if ((i & ABORT_EVERY) === ABORT_EVERY) ctx.checkAbort(); const e = entries[i]!; if (e.name.endsWith("/") || parsed.has(pkg.keyOf(e))) continue; - const owner = relsOwner(e.name); + const owner = relsOwner(pkg.keyOf(e)); // canonical, so %5Frels and .r%65ls count if (owner === undefined) continue; queue.push({ source: owner, counts: false }); await drain(); diff --git a/packages/javascript-excel/test/read/package-scan.test.ts b/packages/javascript-excel/test/read/package-scan.test.ts index 5101773..05fd3a5 100644 --- a/packages/javascript-excel/test/read/package-scan.test.ts +++ b/packages/javascript-excel/test/read/package-scan.test.ts @@ -395,6 +395,25 @@ describe("review 3: nothing listed in any relationships part escapes the scan", expect(unsupported(r.warnings).map((w) => w[0])).toEqual(["invalidPartName"]); }); + it.each([ + ["xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.main"], + ["xlsm", "application/vnd.ms-excel.sheet.macroEnabled.main+xml"], + ])("a forbidden Override for the workbook (%s type) does not change the format (as 2.4.0); the scan reports it", async (_, type) => { + const bytes = await build({ + sheets: [CELL], + override: { "[Content_Types].xml": contentTypes({}, { "/xl/workbook.xml": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", "/xl/x/../workbook.xml": type }) }, + }); + expect(await detectFormat(bytes)).toBe("xlsx"); + const r = await read(bytes); + expect(r.workbook.sheets[0]!.rows[0]![0]!.value).toBe(1); + expect(unsupported(r.warnings)).toEqual([["invalidPartName", "[Content_Types].xml"]]); + }); + + it.each([["xl/embeddings/%5Frels/ghost.bin.rels"], ["xl/embeddings/_rels/ghost.bin.r%65ls"]])("an orphan relationships part spelled %s is classified too", async (name) => { + const r = await readOf({ sheets: [CELL], parts: { [name]: rels([["rO", "oleObject", "/xl/embeddings/ole.bin"]]), "xl/embeddings/ole.bin": "o" } }); + expect(unsupported(r.warnings).map((w) => w[0])).toEqual(["oleObject", "unreferencedPart"]); + }); + it("detectFormat without package relationships: duplicate Overrides, the last wins (as 2.4.0)", async () => { const bytes = await writeZip([ { name: "[Content_Types].xml", data: `` },