diff --git a/.changeset/package-scan-active-content.md b/.changeset/package-scan-active-content.md new file mode 100644 index 0000000..69b3ebd --- /dev/null +++ b/.changeset/package-scan-active-content.md @@ -0,0 +1,7 @@ +--- +"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 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 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 c7055d3..1d65aa4 100644 --- a/docs/api.md +++ b/docs/api.md @@ -877,6 +877,10 @@ 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), `'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). 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. - **`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 +911,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`) @@ -1709,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 } @@ -1719,7 +1724,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' | 'webExtension' | 'invalidPartName' | 'unreferencedPart'; export interface DroppedWarnings { total: number; // warnings not recorded @@ -1738,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. 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 | @@ -1770,7 +1777,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 +1806,10 @@ 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 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. | +| **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..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) 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/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 50c5853..35e6ae0 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,33 +15,99 @@ 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 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). 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; + export class Package { + /** partKey(name) -> entry. */ private readonly parts = new Map(); - /** Part name (lower case, no leading '/') -> content type. */ - private readonly overrides = new Map(); - /** Extension (lower case) -> content type. */ - private readonly defaults = new Map(); + /** entry -> partKey(entry.name), computed once. */ + private readonly keys = new Map(); + /** + * 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. */ + private readonly defaults = new Map(); + /** + * 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). + */ 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 = 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) { + 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 { - return this.parts.get(stripSlash(name).toLowerCase()); + if (name.length > TOO_LONG) return undefined; // cannot name a part (TOO_LONG) + return this.parts.get(partKey(name)); } get partNames(): string[] { @@ -50,89 +117,395 @@ 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") { 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(stripSlash(part).toLowerCase(), 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 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 { + // 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); + } + + /** + * 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[] { + if (name.length > TOO_LONG) return []; + 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). */ + /** 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()]; + return [...this.legacyOverrides.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[] = []; + 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"; - out.push({ - id, - type, - kind: type.slice(type.lastIndexOf("/") + 1), - target: external ? target : resolveTarget(dir, target), - external, - }); + 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; + } 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; + } + } + } + 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; } -/** Resolves a relationship target against the source part's folder (RFC 3986 dot segments, '%xx' decoded). */ +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 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 { + let i = name.indexOf("%"); + if (i === -1) return name; + const n = name.length; + let out = ""; + /** 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 >= 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 { + // 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; + } + continue; + } + emit(i, String.fromCharCode(b), i + 3); + i += 3; + } + return from === 0 ? name : out + name.slice(from); +} + +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; + const h = hexDigit(s.charCodeAt(i + 1)); + const l = hexDigit(s.charCodeAt(i + 2)); + return h < 0 || l < 0 ? -1 : (h << 4) | l; +} + +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). */ +export function partKey(name: string): string { + return canonicalPartName(stripSlash(name)).toLowerCase(); +} + +/** + * 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); - try { - t = decodeURIComponent(t); - } catch { - // keep as is - } - t = t.replace(/\\/g, "/"); + 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("/")) { + 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; 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 dc6eb7c..5513583 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 { 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"; @@ -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 } }); } @@ -200,15 +177,52 @@ 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 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]!; + 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", parts: scan.unreferenced }); + } +} + /** Internal options, not part of the public API yet. */ export interface InternalReadOptions { /** @@ -353,6 +367,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..d5a2f10 --- /dev/null +++ b/packages/javascript-excel/src/internal/read/scan.ts @@ -0,0 +1,292 @@ +/** + * 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. `read` uses it; it is kept in one + * function so that other entry points can reuse it. Internal. + */ + +import { FormatError } from "../../errors"; +import type { ExcelPartKind } from "../../warnings"; +import { partKey, relsOwner, type Package, type 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)"], + ["webExtension", "Office web add-ins"], +]); + +/** + * Relationship kinds, lower case (relationship types compare + * case-insensitively), that name a kind other than their own last segment. + */ +const RELATIONSHIP_ALIASES: ReadonlyMap = 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.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"], + // Templates, add-ins and slides, macro-enabled or not. + ["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"], + ["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"], +]); + +/** + * 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", + "macrosheet", + "webExtension", +]); + +/** 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 (at most maxEntries). Not + * listed: `[Content_Types].xml` and the relationships part of a reached + * part. Office 2007 and 2010 could leave discarded parts under `[trash]/`; + * they are listed like any other. Part names are matched in canonical form + * (opc.ts `partKey`; equivalent zip names already failed with ZIP_INVALID). + * A relationships part that is not well-formed XML is listed, and the parts + * only it would reach are listed too. + */ + unreferenced: string[]; + /** + * Names OPC forbids (opc.ts `forbiddenName`): zip entries with such a name, + * in zip order, then each relationships part that holds a target with such + * a name, in walk order. Each is a zip entry name, listed once. + */ + forbidden: string[]; +} + +/** + * The kind a relationship names, by its type alone: the last segment of the + * type URI, compared without regard to case, or an alias (RELATIONSHIP_ALIASES). + * customUI is matched on the whole type (`.../ui/extensibility`). + */ +export function relationshipKindOf(rel: Relationship): ExcelPartKind | undefined { + const kind = rel.kind.toLowerCase(); + if (kind === "extensibility" && /\/ui\/extensibility$/i.test(rel.type)) return "customUI"; + return RELATIONSHIP_ALIASES.get(kind) ?? RELATIONSHIP_KINDS.get(kind); +} + +/** + * What a relationship and its target's content type make of a part; undefined + * for parts the model reads or that need no report. A kind in REPORTED_ANYWHERE + * wins: an active content type behind a passive or unknown relationship (an + * `image` relationship to an OLE object) is reported by its content type. + */ +export function partKindOf(rel: Relationship, contentTypes: readonly string[]): ExcelPartKind | undefined { + const byRel = relationshipKindOf(rel); + if (byRel !== undefined && REPORTED_ANYWHERE.has(byRel)) return byRel; + for (const t of contentTypes) { + const byType = CONTENT_TYPES.get(t.toLowerCase().split(";")[0]!.trim()); + if (byType) return byType; + } + return byRel; +} + +/** + * 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. + * A target OPC forbids is followed both as a decoder reads it and literally, + * so content behind it is found either way. Consults the signal per part and + * every 4,096 relationships or zip entries. 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(); + const forbidden = new Set(pkg.forbiddenNames); + /** partKey of the parts accounted for (reached from the package root). */ + const reached = new Set([partKey("[Content_Types].xml")]); + /** 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 (counts) reached.add(key); + if (queued.has(key)) return; + queued.add(key); + queue.push({ source: entry.name, counts }); + }; + 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 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); + } + } + 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(pkg.keyOf(e)); // canonical, so %5Frels and .r%65ls count + if (owner === undefined) continue; + queue.push({ source: owner, counts: false }); + await drain(); + } + const unreferenced: string[] = []; + 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 + if (!reached.has(pkg.keyOf(e))) unreferenced.push(e.name); + } + return { found, unreferenced, forbidden: [...forbidden] }; +} diff --git a/packages/javascript-excel/src/warnings.ts b/packages/javascript-excel/src/warnings.ts index 7cd7b13..22bbce4 100644 --- a/packages/javascript-excel/src/warnings.ts +++ b/packages/javascript-excel/src/warnings.ts @@ -38,7 +38,11 @@ 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), + * `'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 = @@ -70,7 +74,14 @@ export type ExcelPartKind = | "timeline" | "chartsheet" | "dialogsheet" - | "macrosheet"; + | "macrosheet" + // found by the package scan, wherever they sit (UNSUPPORTED_PART, since 2.5) + | "activeX" + | "embeddedPackage" + | "customUI" + | "webExtension" + | "invalidPartName" + | "unreferencedPart"; /** What the warning cap left out; on `WARNINGS_TRUNCATED` only. */ export interface DroppedWarnings { @@ -97,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 1a8c6d4..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 { 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,4 +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("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/ä%FF.png"); + expect(resolveTarget("xl/worksheets/", "%%34%31s.xml")).toBe("xl/worksheets/%2541s.xml"); + }); + 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", "ä"], + ["%41%2f%5c%25", "A%2F%5C%25"], + ["%2541", "%2541"], + ["%%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!), 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..1e7e56b --- /dev/null +++ b/packages/javascript-excel/test/read/name-cost.test.ts @@ -0,0 +1,103 @@ +// 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) => + ``; + +/** 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: BIG }); + } 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); + + // 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 }); + // 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 new file mode 100644 index 0000000..05fd3a5 --- /dev/null +++ b/packages/javascript-excel/test/read/package-scan.test.ts @@ -0,0 +1,687 @@ +/// +// 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 { 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"; + +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", + parts: ["xl/vbaProject.bin"], + }, + ]); + }); + + 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.'); + expect(r.warnings[0]!.parts).toEqual(["payload.exe", "xl/media/x.dat"]); + }); + + 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.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("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([]); + }); + + 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("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("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([ + ["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("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.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: `` }, + { 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({ + 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"]]); + }); +}); + +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({ + 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([]); + }); +});