From e6012a0435bdff482849d9fa3d6d6242d7c7816c Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 17:06:14 +0100 Subject: [PATCH 1/3] JSE-85: report relationships to external targets as UNSUPPORTED_PART 'externalTarget' A relationship with TargetMode="External" in any relationships part of the package that is not a hyperlink and that no other kind covers (a linked OLE object stays oleObject, an external link's own path stays externalLink) is now reported by the package scan, so read, inspect and importDataset all return it. Example: a linked picture under a drawing with an http(s), UNC or file: target, which Excel fetches when the file is opened. One warning for the whole package: part is the first relationships part holding one, parts lists each such relationships part once (bounded by maxEntries), and the new relationshipTypes field gives the first 16 distinct types, excerpted. Targets are never included, resolved or fetched. No new refusals. --- .changeset/external-targets.md | 5 + docs/api.md | 13 +- packages/javascript-excel/README.md | 2 +- .../src/internal/read/context.ts | 3 +- .../src/internal/read/reader.ts | 13 +- .../src/internal/read/scan.ts | 67 +++- packages/javascript-excel/src/warnings.ts | 21 +- .../test/read/external-targets.test.ts | 359 ++++++++++++++++++ .../test/read/inspect-differential.test.ts | 4 +- .../test/read/inspect-files.ts | 3 + .../test/read/package-scan.test.ts | 3 +- 11 files changed, 480 insertions(+), 13 deletions(-) create mode 100644 .changeset/external-targets.md create mode 100644 packages/javascript-excel/test/read/external-targets.test.ts diff --git a/.changeset/external-targets.md b/.changeset/external-targets.md new file mode 100644 index 0000000..82383fd --- /dev/null +++ b/.changeset/external-targets.md @@ -0,0 +1,5 @@ +--- +"javascript-excel": minor +--- + +`read`, `inspect` and `importDataset` now report relationships to targets outside the file (JSE-85). A relationship with `TargetMode="External"` anywhere in the package (root, workbook, sheets, drawings, charts, any other relationships part) that is not a hyperlink and that no other kind covers gives one `UNSUPPORTED_PART` warning with the new `partKind` `'externalTarget'`. Example: a linked picture, an `image` relationship of a drawing with an `http(s)`, UNC (`\\host\share\…`) or `file:` target, which Excel fetches when the file is opened (a tracking beacon; a UNC target can send the user's NTLM credentials to that host). Before, nothing reported it. The warning's `part` is the first relationships part that holds one, `parts` lists every such relationships part once (bounded by `maxEntries`), and the new `relationshipTypes` field gives the first 16 distinct relationship types, excerpted; targets are never included, resolved or fetched, and any number of such relationships is one warning. Not reported as `'externalTarget'`: hyperlinks (the transitional and Strict hyperlink types), relationships whose own kind is already reported wherever it sits (a linked OLE object stays `'oleObject'`), and the source path of an external link (`externalLinkPath` and Microsoft's `xlExternalLinkPath` types under a part reported as `'externalLink'`). `TargetMode` is read as before: `External` in any letter case. No new refusals: files that read in 2.5.0 still read, with at most this one more warning. `ExcelPartKind` gains `'externalTarget'` (a `switch` over it needs a `default` branch, as documented) and `ExcelWarning` gains the optional `relationshipTypes`. Files this library writes have none: their hyperlinks are not reported. diff --git a/docs/api.md b/docs/api.md index c0609d6..47721a5 100644 --- a/docs/api.md +++ b/docs/api.md @@ -882,6 +882,7 @@ How the reader works, as far as the API is concerned: - **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. +- **External targets** (since 2.6, JSE-85). A relationship with `TargetMode="External"` points outside the package, and Excel may fetch its target when the file is opened, without asking: a linked picture (an `image` relationship of a drawing whose target is `http://…`, `https://…`, a UNC path `\\host\share\…` or `file:…`) is a tracking beacon, and a UNC or `file:` target can make Windows send the user's NTLM credentials to that host. Every such relationship in any relationships part of the package (the root, the workbook, every sheet, drawings, charts, external links, an orphaned relationships part, …) gives one `UNSUPPORTED_PART` warning with `partKind: 'externalTarget'` for the whole package, unless something else already covers it: a hyperlink (the transitional and Strict `…/hyperlink` types, compared as whole URIs without regard to case, so a made-up type ending in `/hyperlink` is reported; a hyperlink opens only when it is followed), a relationship whose own kind is reported wherever it sits (a linked OLE object stays `'oleObject'`, and likewise `'externalLink'`, `'connections'`, `'queryTable'`, …: it is not reported twice), and the source path of a part reported as `'externalLink'` (its `externalLinkPath`, `xlPathMissing`, `xlStartup`, `xlAlternateStartup` or `xlLibrary` relationship; the same types under any other part are external targets). The relationship's type does not matter otherwise: a known passive kind (`image`, `attachedTemplate`, a thumbnail) and a type no one has defined are reported alike. `TargetMode` is read as the relationships parser reads it for the model: `External` in any letter case is external; with spaces around it, or any other value, the target is a part name inside the package and is not reported as an external target. The warning's `part` is the first relationships part (a zip entry name, such as `xl/drawings/_rels/drawing1.xml.rels`) that holds such a relationship, `parts` lists every one in the order the scan reads them (each once, so at most `maxEntries`), `relationshipTypes` gives the first 16 distinct relationship types (compared without regard to case; a type over 128 characters is given as its first 64, `…` and its length), and the message gives the number of relationships. The targets themselves are never included, resolved or fetched. 100,000 such relationships in one part are one warning with one part and one type. This is a warning, not a refusal: files `read` read before 2.6 still read. To refuse them, check for `partKind: 'externalTarget'`. Evidence: no file of the test corpus (the openpyxl, LibreOffice and import fixtures and the conformance corpus this library writes, whose hyperlinks are external relationships) has one. - 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. @@ -976,7 +977,7 @@ import { inspect } from 'javascript-excel/read'; const limits = { maxColumns: 256, maxCells: 1_000_000, maxItems: 100_000, maxEntryBytes: 64 * 1024 * 1024, maxTotalBytes: 128 * 1024 * 1024 }; try { const report = await inspect(upload, { limits, signal: AbortSignal.timeout(10_000) }); - if (report.partKinds.includes('vbaProject') || report.partKinds.includes('externalLink')) refuse('active content'); + if (['vbaProject', 'externalLink', 'externalTarget'].some((k) => report.partKinds.includes(k))) refuse('active content'); else accept(report.sheets.map((s) => `${s.name}: ${s.cells} cells`)); } catch (err) { if (isExcelError(err)) refuse(err.code); // LIMIT_EXCEEDED, XML_DTD_FORBIDDEN, XML_MALFORMED, ZIP_ENCRYPTED, UNSUPPORTED_FORMAT, NOT_XLSX, ... @@ -1795,7 +1796,8 @@ 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 + parts?: string[]; // UNSUPPORTED_PART 'unreferencedPart' / 'invalidPartName' (since 2.5), 'externalTarget' (since 2.6) only: every name, `part` is the first + relationshipTypes?: string[]; // UNSUPPORTED_PART 'externalTarget' only (since 2.6): the first 16 distinct relationship types, excerpted dropped?: DroppedWarnings; // WARNINGS_TRUNCATED only } @@ -1808,7 +1810,9 @@ export type ExcelPartKind = | 'table' | 'oleObject' | 'ctrlProp' | 'image' | 'vbaProject' | 'externalLink' | 'connections' | 'queryTable' | 'slicer' | 'slicerCache' | 'timeline' | 'chartsheet' | 'dialogsheet' | 'macrosheet' // UNSUPPORTED_PART, found by the package scan wherever they sit (since 2.5, §5.2) - | 'activeX' | 'embeddedPackage' | 'customUI' | 'webExtension' | 'invalidPartName' | 'unreferencedPart'; + | 'activeX' | 'embeddedPackage' | 'customUI' | 'webExtension' | 'invalidPartName' | 'unreferencedPart' + // UNSUPPORTED_PART, a relationship to a target outside the package (since 2.6, §5.2) + | 'externalTarget'; export interface DroppedWarnings { total: number; // warnings not recorded @@ -1827,7 +1831,7 @@ export function isDataLossWarning(warning: ExcelWarning | ExcelWarningCode): boo | Warning code | Data loss | Situation and recovery | |---|---|---| -| `UNSUPPORTED_PART` | yes | Charts, drawings, pivots, comments, VBA, … are outside the model and not in the result; one warning per kind (so it cannot flood the list), `partKind` names it. Since 2.5 also ActiveX controls (`'activeX'`), embedded packages (`'embeddedPackage'`), ribbon customisations (`'customUI'`), Office web add-ins (`'webExtension'`), names 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 | +| `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`. Since 2.6 also relationships to targets outside the package that nothing else covers, such as linked pictures (`'externalTarget'`, one warning, with every relationships part that holds one in `parts` and their types in `relationshipTypes`). 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 | @@ -1890,6 +1894,7 @@ if (lost.length) throw new Error(`Refused: ${[...new Set(lost.map((w) => w.code) | **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. | +| **Content fetched from outside the file** (a linked picture or another relationship with `TargetMode="External"`: a tracking beacon when the file is opened, or, through a UNC or `file:` target, the user's NTLM credentials sent to the attacker's host) | Never fetched or resolved by this library, and reported so an app can refuse the file (since 2.6): every external relationship in any relationships part of the package that is not a hyperlink and that no other kind covers (a linked OLE object stays `'oleObject'`, an external link's own path `'externalLink'`) gives one `UNSUPPORTED_PART` warning with `partKind: 'externalTarget'`, with the relationships parts in `parts` and the types in `relationshipTypes` (bounded; no target text). `inspect` reports it the same. Hyperlinks are not reported: the reader returns their targets verbatim (see **Malicious hyperlinks**). To refuse such files, check for this `partKind` (§5.2). | | **Hostile relationships parts** | Since 2.5 the scan parses every relationships part in the zip: those of reached parts, also of sheets left out by `sheets` and of nested parts (drawings, tables, …), and those whose owner nothing reaches (orphans, in any percent-encoded spelling of `_rels` or `.rels`). A DTD in any of them throws `XML_DTD_FORBIDDEN`, and one past an XML or zip limit (for example deeper than `maxXmlDepth`) throws `LIMIT_EXCEEDED`, as for any part the reader parses; 2.4.0 never opened those parts and read such a file. Since 2.5, two zip entries with equivalent part names (equal after percent-decoding and case folding) throw `ZIP_INVALID`; 2.4.0 threw only for names that differ in case. A relationships part that is only malformed XML does not throw: it and the parts only it reaches are reported as unreferenced. | | **ReDoS** | Hot paths (A1 parsing, number detection, CSV) use hand-written scanners or linear regexes with no nested quantifiers. Format codes are bounded by part size. | | **Encrypted, legacy and macro content** | CFB containers (`.xls`, encrypted OOXML) throw `UNSUPPORTED_FORMAT`; VBA parts are dropped, never executed, and reported as `'vbaProject'` (or `'unreferencedPart'` when no relationship reaches them). | diff --git a/packages/javascript-excel/README.md b/packages/javascript-excel/README.md index 9fe8ebe..ccb544e 100644 --- a/packages/javascript-excel/README.md +++ b/packages/javascript-excel/README.md @@ -91,7 +91,7 @@ const cell = exact.workbook.sheets[0]?.rows[0]?.[0]; console.log(cell?.type, cell?.value, cell?.rawText); // "number" 50.3 "50.30" ``` -Damage the reader can recover from comes back as `warnings`. `isDataLossWarning(w)` tells the ones where data was lost (a cell skipped, rows cut, a part missing, comments or charts not read; `partKind` names the part, including ActiveX controls, embedded files, customUI, 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. +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, parts no relationship reaches and relationships to targets outside the file such as linked pictures, wherever they sit in the package) from informational ones; the warning cap (`limits.maxWarnings`, default 1,000) drops only informational warnings, so filtering `warnings` with it is enough to refuse a damaged file. To accept or refuse an upload without reading it into the model, `inspect(file, { limits, signal })` checks it part by part without building cells: it refuses every file `read` refuses under the same limits, with the same error, and returns the format, the worksheets with their cell counts, and the part kinds `read` reports (`partKinds`: VBA, external links, OLE objects, …). It also inflates the parts `read` never opens, searches the bytes of every one of them for ` { const t: ExcelWarning = { code: "WARNINGS_TRUNCATED", message: `More than maxWarnings (${this.limits.maxWarnings}) warnings; later ones were dropped.`, dropped }; diff --git a/packages/javascript-excel/src/internal/read/reader.ts b/packages/javascript-excel/src/internal/read/reader.ts index 385570c..7753462 100644 --- a/packages/javascript-excel/src/internal/read/reader.ts +++ b/packages/javascript-excel/src/internal/read/reader.ts @@ -190,7 +190,9 @@ export function warnUnsupportedParts(ctx: Pick): Promise const what = SCANNED_KINDS.get(f.kind) ?? UNSUPPORTED_RELATIONSHIPS.get(f.kind)!; ctx.warn("UNSUPPORTED_PART", `The workbook contains ${what}, which are not read.`, { part: f.part, partKind: f.kind }); } + const ext = scan.external; + if (ext.count > 0) { + const first = ext.parts[0]!; + const message = + ext.count === 1 + ? `The package has 1 relationship to a target outside the file (in "${excerpt(first)}"); it is not read or fetched, but Excel may fetch it when the file is opened.` + : `The package has ${ext.count} relationships to targets outside the file (in ${ext.parts.length} relationships part${ext.parts.length === 1 ? "" : "s"}; first in "${excerpt(first)}"); they are not read or fetched, but Excel may fetch them when the file is opened.`; + ctx.warn("UNSUPPORTED_PART", message, { part: first, partKind: "externalTarget", parts: ext.parts, relationshipTypes: ext.types }); + } const bad = scan.forbidden; if (bad.length > 0) { const first = bad[0]!; diff --git a/packages/javascript-excel/src/internal/read/scan.ts b/packages/javascript-excel/src/internal/read/scan.ts index d5a2f10..915e31c 100644 --- a/packages/javascript-excel/src/internal/read/scan.ts +++ b/packages/javascript-excel/src/internal/read/scan.ts @@ -7,6 +7,7 @@ import { FormatError } from "../../errors"; import type { ExcelPartKind } from "../../warnings"; +import { excerpt } from "../excerpt"; import { partKey, relsOwner, type Package, type Relationship } from "./opc"; import { ABORT_EVERY } from "./sheet"; @@ -127,6 +128,28 @@ export const REPORTED_ANYWHERE: ReadonlySet = new Set = new Set([ + "http://schemas.openxmlformats.org/officedocument/2006/relationships/hyperlink", + "http://purl.oclc.org/ooxml/officedocument/relationships/hyperlink", +]); +const HYPERLINK_TYPE_LENGTH = Math.max(...[...HYPERLINK_TYPES].map((t) => t.length)); + +/** + * Relationship kinds (lower case) that give an external link's source file: + * under a part reported as `externalLink` they are that external link, not a + * separate external target. + */ +const EXTERNAL_LINK_PATHS: ReadonlySet = new Set(["externallinkpath", "xlpathmissing", "xlstartup", "xlalternatestartup", "xllibrary"]); + +/** At most this many distinct relationship types are listed for external targets (each excerpted). */ +export const MAX_EXTERNAL_TYPES = 16; + /** One part (or external target) of a kind the model does not represent. */ export interface ScannedPart { kind: ExcelPartKind; @@ -161,6 +184,16 @@ export interface PackageScan { * a name, in walk order. Each is a zip entry name, listed once. */ forbidden: string[]; + /** + * Relationships with TargetMode="External" that no other kind covers + * (JSE-85): not a hyperlink, not of a kind in REPORTED_ANYWHERE, and not + * the source path of a part found as an external link. `count` is how many + * there are; `parts` the relationships parts (zip entry names) that hold + * them, each once, in walk order, so at most maxEntries; `types` the first + * MAX_EXTERNAL_TYPES distinct relationship types (compared without regard + * to case), each excerpted. The targets are never kept, resolved or fetched. + */ + external: { count: number; parts: string[]; types: string[] }; } /** @@ -214,6 +247,8 @@ export async function scanPackageParts(pkg: Package): Promise { 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 external = { count: 0, parts: [] as string[], types: [] as string[] }; + const externalTypes = new Set(); const visit = (target: string, counts: boolean): void => { const entry = pkg.part(target); if (!entry) return; @@ -256,11 +291,28 @@ export async function scanPackageParts(pkg: Package): Promise { const malformed = pkg.malformedRels.get(relsEntry.name) ?? []; if (malformed.length) forbidden.add(relsEntry.name); const all = malformed.length ? [...rels, ...malformed] : rels; + // A part found as an external link (it was found before its relationships are read: breadth first). + const ofExternalLink = foundKeys.has(`externalLink\u0000${partKey(source)}`); + let externalHere = false; 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 && isExternalTarget(rel, ofExternalLink)) { + external.count++; + if (!externalHere) { + externalHere = true; + external.parts.push(relsEntry.name); + } + if (external.types.length < MAX_EXTERNAL_TYPES) { + const t = rel.type.toLowerCase(); + if (!externalTypes.has(t)) { + externalTypes.add(t); + external.types.push(excerpt(rel.type)); + } + } + } if (rel.external || rel.tooLong) continue; visit(rel.target, counts); if (rel.altTarget !== undefined) visit(rel.altTarget, counts); @@ -288,5 +340,18 @@ export async function scanPackageParts(pkg: Package): Promise { if (e.name.endsWith("/")) continue; // directory entries if (!reached.has(pkg.keyOf(e))) unreferenced.push(e.name); } - return { found, unreferenced, forbidden: [...forbidden] }; + return { found, unreferenced, forbidden: [...forbidden], external }; +} + +/** + * Whether an external relationship is reported as `externalTarget`: not when + * its own kind is reported wherever it sits (a linked OLE object is + * `oleObject`), when it is a hyperlink, or when it is the source path of a + * part found as an external link. Every other type, known or not, is. + */ +function isExternalTarget(rel: Relationship, ofExternalLink: boolean): boolean { + const kind = relationshipKindOf(rel); + if (kind !== undefined && REPORTED_ANYWHERE.has(kind)) return false; + if (rel.type.length <= HYPERLINK_TYPE_LENGTH && HYPERLINK_TYPES.has(rel.type.toLowerCase())) return false; + return !(ofExternalLink && EXTERNAL_LINK_PATHS.has(rel.kind.toLowerCase())); } diff --git a/packages/javascript-excel/src/warnings.ts b/packages/javascript-excel/src/warnings.ts index 22bbce4..13e150c 100644 --- a/packages/javascript-excel/src/warnings.ts +++ b/packages/javascript-excel/src/warnings.ts @@ -42,7 +42,10 @@ export type ExcelWarningCode = * 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 + * relationship target, Override PartName or relationship OPC forbids) and `'unreferencedPart'` (a part no relationship reaches). + * `'externalTarget'` (since 2.6) is a relationship with `TargetMode="External"` + * that no other kind covers and is not a hyperlink, such as a linked picture + * Excel fetches when the file is opened. Kinds may be added in a minor * release, so a `switch` over it needs a `default` branch. */ export type ExcelPartKind = @@ -81,7 +84,9 @@ export type ExcelPartKind = | "customUI" | "webExtension" | "invalidPartName" - | "unreferencedPart"; + | "unreferencedPart" + // a relationship to a target outside the package (UNSUPPORTED_PART, since 2.6) + | "externalTarget"; /** What the warning cap left out; on `WARNINGS_TRUNCATED` only. */ export interface DroppedWarnings { @@ -111,10 +116,20 @@ export interface ExcelWarning { /** * 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 + * (`part` is the first). With `'externalTarget'` (since 2.6): every + * relationships part that holds such a relationship, in the order the + * package scan reads them. Each is a zip entry name, at most once, so the * list is bounded by `maxEntries`. */ parts?: string[] | undefined; + /** + * On `UNSUPPORTED_PART` with `partKind` `'externalTarget'` (since 2.6): the + * relationship types of those relationships, the first 16 distinct ones + * (compared without regard to case), each as written when it is at most + * 128 characters, else its first 64, `…` and its length. Targets are never + * included. + */ + relationshipTypes?: 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/external-targets.test.ts b/packages/javascript-excel/test/read/external-targets.test.ts new file mode 100644 index 0000000..4225e48 --- /dev/null +++ b/packages/javascript-excel/test/read/external-targets.test.ts @@ -0,0 +1,359 @@ +/// +// JSE-85: a relationship with TargetMode="External" whose type is not a kind +// already reported (externalLink, oleObject, ...) and is not a hyperlink is +// reported as UNSUPPORTED_PART 'externalTarget', wherever its relationships +// part sits, by read and by inspect alike. No target is ever fetched. +import { afterEach, describe, expect, it, vi } 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 { scanPackageParts } from "../../src/internal/read/scan"; +import { openZip } from "../../src/internal/zip/read"; +import { importDataset } from "../../src/import"; +import { inspect, read, type ReadOptions } from "../../src/read"; +import type { ExcelWarning } from "../../src/warnings"; +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 IMAGE = `${REL}/image`; +const HYPERLINK = `${REL}/hyperlink`; +const CELL = '1'; +const DRAWING_RELS = "xl/drawings/_rels/drawing1.xml.rels"; + +type Rel = [id: string, type: string, target: string, mode?: string]; + +/** A relationships part; `type` is a full URI or a suffix of the officeDocument namespace; `mode` is the TargetMode attribute as written. */ +function rels(list: Rel[]): string { + const esc = (s: string) => s.replace(/&/g, "&").replace(/ ``) + .join(""); + return `${body}`; +} + +/** A sheet with a drawing whose relationships are `drawingRels`. */ +function withDrawing(drawingRels: Rel[], more: Partial = {}): BuildOptions { + return { + sheets: [CELL], + sheetRels: { 0: [["rD", "drawing", "../drawings/drawing1.xml"]] }, + ...more, + parts: { "xl/drawings/drawing1.xml": "", [DRAWING_RELS]: rels(drawingRels), ...more.parts }, + }; +} + +const unsupported = (w: ExcelWarning[]) => w.filter((x) => x.code === "UNSUPPORTED_PART"); +const kinds = (w: ExcelWarning[]) => unsupported(w).map((x) => [x.partKind, x.part]); +const externalOf = (w: ExcelWarning[]) => w.find((x) => x.partKind === "externalTarget"); + +/** read and inspect of the same file: inspect's warnings are read's UNSUPPORTED_PART warnings, the same. */ +async function both(o: BuildOptions, ro?: ReadOptions): Promise { + const bytes = await build(o); + const r = await read(bytes, ro); + const i = await inspect(bytes, ro === undefined ? undefined : { limits: ro.limits }); + expect(i.warnings).toEqual(unsupported(r.warnings)); + expect(i.partKinds).toEqual([...new Set(unsupported(r.warnings).map((w) => w.partKind))]); + expect(r.workbook.sheets[0]!.rows[0]![0]!.value).toBe(1); + return r.warnings; +} + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("linked pictures under a drawing (partKind 'externalTarget')", () => { + it.each([ + ["http", "http://tracker.example/pixel.png"], + ["https", "https://tracker.example/pixel.png?u=1&v=2"], + ["UNC", "\\\\attacker-host\\share\\pixel.png"], + ["file:", "file:///C:/Users/Public/pixel.png"], + ["file: UNC", "file://attacker-host/share/pixel.png"], + ])("%s target", async (_, target) => { + const w = await both(withDrawing([["rI", "image", target, "External"]])); + expect(kinds(w)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["externalTarget", DRAWING_RELS]]); + const ext = externalOf(w)!; + expect(ext).toEqual({ + code: "UNSUPPORTED_PART", + message: `The package has 1 relationship to a target outside the file (in "${DRAWING_RELS}"); it is not read or fetched, but Excel may fetch it when the file is opened.`, + part: DRAWING_RELS, + partKind: "externalTarget", + parts: [DRAWING_RELS], + relationshipTypes: [IMAGE], + }); + // Nothing of the target is echoed. + expect(JSON.stringify(ext)).not.toContain("pixel"); + }); + + it("a linked and embedded picture (r:link next to r:embed): the external one is reported", async () => { + const w = await both( + withDrawing( + [ + ["rE", "image", "../media/image1.png"], + ["rL", "image", "http://tracker.example/p.png", "External"], + ], + { parts: { "xl/media/image1.png": "png" } }, + ), + ); + expect(kinds(w)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["externalTarget", DRAWING_RELS]]); + }); + + it("never fetches or resolves a target", async () => { + const fetchSpy = vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("fetch must not be called")); + await both(withDrawing([["rI", "image", "https://tracker.example/pixel.png", "External"]])); + expect(fetchSpy).not.toHaveBeenCalled(); + }); +}); + +describe("external targets elsewhere in the package", () => { + it("on a chart's relationships (drawing -> chart -> image)", async () => { + const chartRels = "xl/charts/_rels/chart1.xml.rels"; + const w = await both( + withDrawing([["rC", "chart", "../charts/chart1.xml"]], { + parts: { "xl/charts/chart1.xml": "", [chartRels]: rels([["rI", "image", "https://tracker.example/c.png", "External"]]) }, + }), + ); + expect(kinds(w)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["externalTarget", chartRels]]); + }); + + it("on a sheet, with a type the library does not know", async () => { + const type = "http://example.com/relationships/beacon"; + const w = await both({ sheets: [CELL], override: { "xl/worksheets/_rels/sheet1.xml.rels": rels([["rB", type, "https://tracker.example/b", "External"]]) } }); + expect(kinds(w)).toEqual([["externalTarget", "xl/worksheets/_rels/sheet1.xml.rels"]]); + expect(externalOf(w)!.relationshipTypes).toEqual([type]); + }); + + it("on the package root", async () => { + const root = rels([ + ["rId1", "officeDocument", "xl/workbook.xml"], + ["rT", "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail", "\\\\host\\share\\t.jpeg", "External"], + ]); + const w = await both({ sheets: [CELL], override: { "_rels/.rels": root } }); + expect(kinds(w)).toEqual([["externalTarget", "_rels/.rels"]]); + }); + + it("on the workbook, and on a sheet left out by `sheets`", async () => { + const o: BuildOptions = { + sheets: [CELL, CELL], + override: { + "xl/worksheets/_rels/sheet2.xml.rels": rels([["rX", "attachedTemplate", "https://tracker.example/t.dotx", "External"]]), + }, + }; + const w = await both(o, { sheets: [0] }); + expect(kinds(w)).toEqual([["externalTarget", "xl/worksheets/_rels/sheet2.xml.rels"]]); + }); + + it("in a relationships part whose owner nothing reaches", async () => { + const w = await both({ sheets: [CELL], parts: { "xl/orphan/_rels/x.xml.rels": rels([["rI", "image", "https://tracker.example/o.png", "External"]]) } }); + expect(kinds(w)).toEqual([ + ["externalTarget", "xl/orphan/_rels/x.xml.rels"], + ["unreferencedPart", "xl/orphan/_rels/x.xml.rels"], + ]); + }); + + it("a relationship without an Id is reported too (and as invalidPartName, as before)", async () => { + const part = ``; + const w = await both(withDrawing([], { parts: { [DRAWING_RELS]: part } })); + expect(kinds(w)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["externalTarget", DRAWING_RELS], ["invalidPartName", DRAWING_RELS]]); + }); + + it("importDataset passes the warning on", async () => { + const bytes = await build(withDrawing([["rI", "image", "https://tracker.example/p.png", "External"]])); + const seen: string[] = []; + await importDataset(bytes, { onWarning: (w) => seen.push(`${w.code} ${w.partKind}`) }); + expect(seen).toContain("UNSUPPORTED_PART externalTarget"); + }); +}); + +describe("TargetMode, as the relationships parser reads it", () => { + // The parser compares TargetMode case-insensitively and does not trim it. + it.each([["External"], ["external"], ["EXTERNAL"], ["eXtErNaL"]])("%s is external: reported", async (mode) => { + const w = await both(withDrawing([["rI", "image", "https://tracker.example/p.png", mode]])); + expect(externalOf(w)?.parts).toEqual([DRAWING_RELS]); + }); + + it.each([[" External"], ["External "], ["Internal"], [""]])("%j is not external: the target is a part name, and nothing is reported as externalTarget", async (mode) => { + const bytes = await build(withDrawing([["rI", "image", "https://tracker.example/p.png", mode]])); + const ctx = new ReadContext(openZip(bytes), DEFAULT_LIMITS, undefined, undefined, undefined); + const pkg = new Package(ctx); + expect((await pkg.rels("xl/drawings/drawing1.xml"))[0]!.external).toBe(false); + const w = await both(withDrawing([["rI", "image", "https://tracker.example/p.png", mode]])); + expect(externalOf(w)).toBeUndefined(); + }); +}); + +describe("not reported as externalTarget", () => { + it("hyperlinks, on a sheet and on a drawing (transitional and strict types, any case)", async () => { + const w = await both( + withDrawing( + [ + ["rH", "hyperlink", "https://example.com/", "External"], + ["rS", "http://purl.oclc.org/ooxml/officeDocument/relationships/hyperlink", "https://example.com/s", "External"], + ], + { + sheetRels: { + 0: [ + ["rD", "drawing", "../drawings/drawing1.xml"], + ["rH", "hyperlink", "\\\\host\\share\\doc.xlsx", true], + ["rU", "HYPERLINK", "https://example.com/u", true], + ], + }, + }, + ), + ); + expect(kinds(w)).toEqual([["drawing", "xl/drawings/drawing1.xml"]]); + }); + + it("a type that only ends in /hyperlink is not a hyperlink", async () => { + const w = await both(withDrawing([["rH", "http://example.com/x/hyperlink", "https://tracker.example/h", "External"]])); + expect(externalOf(w)!.relationshipTypes).toEqual(["http://example.com/x/hyperlink"]); + }); + + it("a linked OLE object keeps its kind, 'oleObject', and is not reported twice", async () => { + const w = await both({ sheets: [CELL], sheetRels: { 0: [["rO", "oleObject", "file:///C:/data.xlsx", true]] } }); + expect(kinds(w)).toEqual([["oleObject", "xl/worksheets/sheet1.xml"]]); + }); + + it("an external OLE object on a chart (linked chart data) keeps 'oleObject'", async () => { + const w = await both( + withDrawing([["rC", "chart", "../charts/chart1.xml"]], { + parts: { "xl/charts/chart1.xml": "", "xl/charts/_rels/chart1.xml.rels": rels([["rO", "oleObject", "file:///C:/book.xlsx", "External"]]) }, + }), + ); + expect(kinds(w)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["oleObject", "xl/charts/chart1.xml"]]); + }); + + it.each([ + ["externalLinkPath", "externalLinkPath"], + ["xlPathMissing", "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlPathMissing"], + ["xlStartup", "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlStartup"], + ["xlAlternateStartup", "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlAlternateStartup"], + ["xlLibrary", "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlLibrary"], + ])("an external link's own path (%s) is the external link: 'externalLink' only", async (_, type) => { + const w = await both({ + sheets: [CELL], + workbookRels: [["rL", "externalLink", "externalLinks/externalLink1.xml"]], + parts: { "xl/externalLinks/externalLink1.xml": "", "xl/externalLinks/_rels/externalLink1.xml.rels": rels([["rId1", type, "\\\\host\\share\\other.xlsx", "External"]]) }, + }); + expect(kinds(w)).toEqual([["externalLink", "xl/externalLinks/externalLink1.xml"]]); + }); + + it("an external link path anywhere but under an external link is an external target", async () => { + const w = await both(withDrawing([["rP", "externalLinkPath", "\\\\host\\share\\other.xlsx", "External"]])); + expect(kinds(w)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["externalTarget", DRAWING_RELS]]); + }); + + it("an external link with a picture under it: both kinds", async () => { + const w = await both({ + sheets: [CELL], + workbookRels: [["rL", "externalLink", "externalLinks/externalLink1.xml"]], + parts: { + "xl/externalLinks/externalLink1.xml": "", + "xl/externalLinks/_rels/externalLink1.xml.rels": rels([ + ["rId1", "externalLinkPath", "other.xlsx", "External"], + ["rId2", "image", "https://tracker.example/p.png", "External"], + ]), + }, + }); + expect(kinds(w)).toEqual([["externalLink", "xl/externalLinks/externalLink1.xml"], ["externalTarget", "xl/externalLinks/_rels/externalLink1.xml.rels"]]); + expect(externalOf(w)!.relationshipTypes).toEqual([IMAGE]); + }); + + it("workbooks this library writes, hyperlinks included, have none", async () => { + const bytes = await toUint8Array({ + sheets: [{ name: "S", rows: [[{ value: "link", hyperlink: { target: "https://example.com/" } }, { value: "unc", hyperlink: { target: "mailto:a@example.com" } }]] }], + }); + const w = (await read(bytes)).warnings; + expect(w).toEqual([]); + expect((await inspect(bytes)).warnings).toEqual([]); + // The conformance corpus is checked in package-scan.test.ts ("clean workbooks stay without these warnings"). + }); +}); + +describe("bounded: one warning, collapsed", () => { + it("many external relationships in one part: one warning, one part, one type", async () => { + const list: Rel[] = []; + for (let i = 0; i < 100_000; i++) list.push([`r${i}`, "image", `https://tracker.example/${i}.png`, "External"]); + const w = await both(withDrawing(list)); + expect(unsupported(w)).toHaveLength(2); + const ext = externalOf(w)!; + expect(ext.parts).toEqual([DRAWING_RELS]); + expect(ext.relationshipTypes).toEqual([IMAGE]); + expect(ext.message).toBe(`The package has 100000 relationships to targets outside the file (in 1 relationships part; first in "${DRAWING_RELS}"); they are not read or fetched, but Excel may fetch them when the file is opened.`); + }, 60_000); + + it("many parts: every relationships part once, in walk order", async () => { + const sheetRels: Rel[] = []; + const parts: Record = {}; + for (let i = 1; i <= 300; i++) { + sheetRels.push([`rD${i}`, "drawing", `../drawings/drawing${i}.xml`]); + parts[`xl/drawings/drawing${i}.xml`] = ""; + parts[`xl/drawings/_rels/drawing${i}.xml.rels`] = rels([ + ["rA", "image", "https://tracker.example/a.png", "External"], + ["rB", "image", "https://tracker.example/b.png", "External"], + ]); + } + const w = await both({ sheets: [CELL], parts, override: { "xl/worksheets/_rels/sheet1.xml.rels": rels(sheetRels) } }); + const ext = externalOf(w)!; + expect(ext.parts).toEqual(Array.from({ length: 300 }, (_, i) => `xl/drawings/_rels/drawing${i + 1}.xml.rels`)); + expect(ext.part).toBe("xl/drawings/_rels/drawing1.xml.rels"); + expect(ext.message).toContain("600 relationships"); + expect(ext.message).toContain("in 300 relationships parts"); + }); + + it("relationship types: at most 16 distinct (compared without regard to case), each excerpted", async () => { + const list: Rel[] = []; + for (let i = 0; i < 1_000; i++) list.push([`r${i}`, `http://example.com/t${i}`, "https://tracker.example/x", "External"]); + list.splice(1, 0, ["rU", "HTTP://EXAMPLE.COM/T0", "https://tracker.example/x", "External"]); + const w = await both(withDrawing(list)); + const types = externalOf(w)!.relationshipTypes!; + expect(types).toHaveLength(16); + expect(types.slice(0, 2)).toEqual(["http://example.com/t0", "http://example.com/t1"]); + + const long = `http://example.com/${"x".repeat(200_000)}`; + const w2 = await both(withDrawing([["rL", long, "https://tracker.example/x", "External"]])); + const [only] = externalOf(w2)!.relationshipTypes!; + expect(only!.length).toBeLessThan(100); + expect(only).toBe(`${long.slice(0, 64)}… (${long.length} characters)`); + expect(externalOf(w2)!.message.length).toBeLessThan(400); + }); + + it("maxWarnings: kept like every UNSUPPORTED_PART (a data-loss code: the first 100 of it are kept past the cap)", async () => { + const bytes = await build(withDrawing([["rI", "image", "https://tracker.example/p.png", "External"]])); + const r = await read(bytes, { limits: { maxWarnings: 1 } }); + expect(r.warnings.map((x) => x.partKind)).toEqual(["drawing", "externalTarget"]); + expect((await inspect(bytes, { limits: { maxWarnings: 1 } })).partKinds).toEqual(["drawing", "externalTarget"]); + }); + + it("the scan consults the signal while classifying external relationships (every 4,096)", async () => { + const checksFor = async (n: number): Promise => { + const list: Rel[] = []; + for (let i = 0; i < n; i++) list.push([`r${i}`, "image", "https://tracker.example/p.png", "External"]); + const bytes = await build(withDrawing(list)); + let checks = 0; + const signal = { + get aborted() { + checks++; + return false; + }, + reason: undefined, + }; + const ctx = new ReadContext(openZip(bytes), DEFAULT_LIMITS, signal, undefined, undefined); + const pkg = new Package(ctx); + await pkg.loadContentTypes(); + checks = 0; + await scanPackageParts(pkg); + return checks; + }; + expect((await checksFor(20_000)) - (await checksFor(1))).toBeGreaterThanOrEqual(4); + }); + + it("scanPackageParts lists them apart from `found`", async () => { + const bytes = await build(withDrawing([["rI", "image", "https://tracker.example/p.png", "External"], ["rJ", "image", "https://tracker.example/q.png", "External"]])); + 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.external).toEqual({ count: 2, parts: [DRAWING_RELS], types: [IMAGE] }); + }); +}); diff --git a/packages/javascript-excel/test/read/inspect-differential.test.ts b/packages/javascript-excel/test/read/inspect-differential.test.ts index 1792bbd..17bc7fe 100644 --- a/packages/javascript-excel/test/read/inspect-differential.test.ts +++ b/packages/javascript-excel/test/read/inspect-differential.test.ts @@ -81,7 +81,7 @@ describe("inspect vs read: the differential test", () => { }); it("every kind the package scan reports (JSE-72) is reported by read and, the same, by inspect", async () => { - const want = ["activeX", "embeddedPackage", "customUI", "webExtension", "unreferencedPart", "invalidPartName", "macrosheet", "vbaProject"]; + const want = ["activeX", "embeddedPackage", "customUI", "webExtension", "unreferencedPart", "invalidPartName", "macrosheet", "vbaProject", "externalTarget"]; const seen = new Set(); for (const h of hostileFiles().filter((f) => f.name.startsWith("kind:"))) { const bytes = await h.bytes(); @@ -92,6 +92,8 @@ describe("inspect vs read: the differential test", () => { for (const k of i.partKinds) seen.add(k); const orphan = unsupported.find((w) => w.partKind === "unreferencedPart"); if (orphan) expect(i.warnings.find((w) => w.partKind === "unreferencedPart")!.parts).toEqual(orphan.parts); + const external = unsupported.find((w) => w.partKind === "externalTarget"); + if (external) expect(external).toMatchObject({ parts: ["xl/drawings/_rels/drawing1.xml.rels"], relationshipTypes: ["http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"] }); } for (const k of want) expect([...seen], k).toContain(k); }); diff --git a/packages/javascript-excel/test/read/inspect-files.ts b/packages/javascript-excel/test/read/inspect-files.ts index 262ab35..9d600f8 100644 --- a/packages/javascript-excel/test/read/inspect-files.ts +++ b/packages/javascript-excel/test/read/inspect-files.ts @@ -647,6 +647,9 @@ export const JSE72_KINDS: ReadonlyArray<[string, (p: Parts) => void]> = [ p.set("xl/workbook.xml", (p.get("xl/workbook.xml") as string).replace("", '')); p.set("xl/macrosheets/sheet7.xml", ``); }], + ["externalTarget (JSE-85: a linked picture under a drawing)", (p) => { + appendRel(p, "xl/drawings/_rels/drawing1.xml.rels", rel("rIdLk", "image", "https://tracker.example/pixel.png", true)); + }], ["vbaProject family (a VBA signature)", (p) => { appendRel(p, "xl/_rels/workbook.xml.rels", rel("rIdV", "http://schemas.microsoft.com/office/2006/relationships/vbaProject", "vbaProject.bin")); p.set("xl/vbaProject.bin", new Uint8Array([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1])); diff --git a/packages/javascript-excel/test/read/package-scan.test.ts b/packages/javascript-excel/test/read/package-scan.test.ts index 05fd3a5..87ee31a 100644 --- a/packages/javascript-excel/test/read/package-scan.test.ts +++ b/packages/javascript-excel/test/read/package-scan.test.ts @@ -21,7 +21,7 @@ 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"]); +const NEW_KINDS = new Set(["activeX", "embeddedPackage", "customUI", "unreferencedPart", "externalTarget"]); /** 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 { @@ -679,6 +679,7 @@ describe("clean workbooks stay without these warnings", () => { const scan = await scanPackageParts(pkg); expect(scan.unreferenced).toEqual([]); expect(scan.found.filter((f) => NEW_KINDS.has(f.kind))).toEqual([]); + expect(scan.external.count).toBe(0); // JSE-85: hyperlinks (the corpus has external ones) are not external targets 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). From 41835976a1eb2f5a92410ffefee7f23d286714e3 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 17:18:11 +0100 Subject: [PATCH 2/3] JSE-85 review: fail closed on external and possibly external relationships - Every non-hyperlink relationship read as external now gives externalTarget whatever its kind: a linked OLE object, an external link's path, connections, queryTable, control, package and image get it next to their own kind. The exemptions by kind and for external link paths (and their dependence on walk order) are gone. - Also reported, while the model still reads the target as a part name: a TargetMode that is neither Internal nor External; a second, prefixed or differently cased TargetMode; an internal target, or a second or prefixed Target, that starts with a URI scheme or // or contains a backslash. One pass over each Relationship's attributes as written. - Hyperlinks stay exempt everywhere. No new refusals. - docs/api.md (5.2, warning table, inspect example, security table), warnings.ts and the changeset follow. --- .changeset/external-targets.md | 7 +- docs/api.md | 7 +- .../javascript-excel/src/internal/read/opc.ts | 40 ++++++ .../src/internal/read/reader.ts | 4 +- .../src/internal/read/scan.ts | 33 ++--- packages/javascript-excel/src/warnings.ts | 8 +- .../test/read/external-targets.test.ts | 133 +++++++++++++----- 7 files changed, 163 insertions(+), 69 deletions(-) diff --git a/.changeset/external-targets.md b/.changeset/external-targets.md index 82383fd..3a053df 100644 --- a/.changeset/external-targets.md +++ b/.changeset/external-targets.md @@ -2,4 +2,9 @@ "javascript-excel": minor --- -`read`, `inspect` and `importDataset` now report relationships to targets outside the file (JSE-85). A relationship with `TargetMode="External"` anywhere in the package (root, workbook, sheets, drawings, charts, any other relationships part) that is not a hyperlink and that no other kind covers gives one `UNSUPPORTED_PART` warning with the new `partKind` `'externalTarget'`. Example: a linked picture, an `image` relationship of a drawing with an `http(s)`, UNC (`\\host\share\…`) or `file:` target, which Excel fetches when the file is opened (a tracking beacon; a UNC target can send the user's NTLM credentials to that host). Before, nothing reported it. The warning's `part` is the first relationships part that holds one, `parts` lists every such relationships part once (bounded by `maxEntries`), and the new `relationshipTypes` field gives the first 16 distinct relationship types, excerpted; targets are never included, resolved or fetched, and any number of such relationships is one warning. Not reported as `'externalTarget'`: hyperlinks (the transitional and Strict hyperlink types), relationships whose own kind is already reported wherever it sits (a linked OLE object stays `'oleObject'`), and the source path of an external link (`externalLinkPath` and Microsoft's `xlExternalLinkPath` types under a part reported as `'externalLink'`). `TargetMode` is read as before: `External` in any letter case. No new refusals: files that read in 2.5.0 still read, with at most this one more warning. `ExcelPartKind` gains `'externalTarget'` (a `switch` over it needs a `default` branch, as documented) and `ExcelWarning` gains the optional `relationshipTypes`. Files this library writes have none: their hyperlinks are not reported. +`read`, `inspect` and `importDataset` now report relationships to targets outside the file (JSE-85), failing closed. Every relationship in any relationships part of the package (root, workbook, sheets, drawings, charts, external links, any other) that is not a hyperlink and that is external (`TargetMode="External"`, any letter case), whatever its kind, gives one `UNSUPPORTED_PART` warning with the new `partKind` `'externalTarget'`. Example: a linked picture, an `image` relationship of a drawing with an `http(s)`, UNC (`\\host\share\…`) or `file:` target, which Excel fetches when the file is opened (a tracking beacon; a UNC target can send the user's NTLM credentials to that host). Before, nothing reported it. Relationships already reported as another kind are reported here too: a linked OLE object gives `'oleObject'` and `'externalTarget'`, an external link `'externalLink'` and, for its path, `'externalTarget'`. Also reported, while the model still reads the target as a part name as before: +- a `TargetMode` that is neither `Internal` nor `External` (`" External"`, `"1"`, `""`, …); +- a second, namespace-prefixed or differently cased `TargetMode`; +- an internal target, or a second or prefixed `Target`, that starts with a URI scheme or `//`, or contains a backslash. + +Hyperlinks are never reported. The warning's `part` is the first relationships part that holds one, `parts` lists every such relationships part once (bounded by `maxEntries`), and the new `relationshipTypes` field gives the first 16 distinct relationship types, excerpted. Targets are never included, resolved or fetched, and any number of such relationships is one warning. No new refusals: files that read in 2.5.0 still read, with at most this one more warning. `ExcelPartKind` gains `'externalTarget'` (a `switch` over it needs a `default` branch, as documented) and `ExcelWarning` gains the optional `relationshipTypes`. Files this library writes have none: their hyperlinks are not reported. diff --git a/docs/api.md b/docs/api.md index 47721a5..af69d5a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -882,7 +882,7 @@ How the reader works, as far as the API is concerned: - **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. -- **External targets** (since 2.6, JSE-85). A relationship with `TargetMode="External"` points outside the package, and Excel may fetch its target when the file is opened, without asking: a linked picture (an `image` relationship of a drawing whose target is `http://…`, `https://…`, a UNC path `\\host\share\…` or `file:…`) is a tracking beacon, and a UNC or `file:` target can make Windows send the user's NTLM credentials to that host. Every such relationship in any relationships part of the package (the root, the workbook, every sheet, drawings, charts, external links, an orphaned relationships part, …) gives one `UNSUPPORTED_PART` warning with `partKind: 'externalTarget'` for the whole package, unless something else already covers it: a hyperlink (the transitional and Strict `…/hyperlink` types, compared as whole URIs without regard to case, so a made-up type ending in `/hyperlink` is reported; a hyperlink opens only when it is followed), a relationship whose own kind is reported wherever it sits (a linked OLE object stays `'oleObject'`, and likewise `'externalLink'`, `'connections'`, `'queryTable'`, …: it is not reported twice), and the source path of a part reported as `'externalLink'` (its `externalLinkPath`, `xlPathMissing`, `xlStartup`, `xlAlternateStartup` or `xlLibrary` relationship; the same types under any other part are external targets). The relationship's type does not matter otherwise: a known passive kind (`image`, `attachedTemplate`, a thumbnail) and a type no one has defined are reported alike. `TargetMode` is read as the relationships parser reads it for the model: `External` in any letter case is external; with spaces around it, or any other value, the target is a part name inside the package and is not reported as an external target. The warning's `part` is the first relationships part (a zip entry name, such as `xl/drawings/_rels/drawing1.xml.rels`) that holds such a relationship, `parts` lists every one in the order the scan reads them (each once, so at most `maxEntries`), `relationshipTypes` gives the first 16 distinct relationship types (compared without regard to case; a type over 128 characters is given as its first 64, `…` and its length), and the message gives the number of relationships. The targets themselves are never included, resolved or fetched. 100,000 such relationships in one part are one warning with one part and one type. This is a warning, not a refusal: files `read` read before 2.6 still read. To refuse them, check for `partKind: 'externalTarget'`. Evidence: no file of the test corpus (the openpyxl, LibreOffice and import fixtures and the conformance corpus this library writes, whose hyperlinks are external relationships) has one. +- **External targets** (since 2.6, JSE-85). A relationship with `TargetMode="External"` points outside the package, and Excel may fetch its target when the file is opened, without asking: a linked picture (an `image` relationship of a drawing whose target is `http://…`, `https://…`, a UNC path `\\host\share\…` or `file:…`) is a tracking beacon, and a UNC or `file:` target can make Windows send the user's NTLM credentials to that host. Every relationship in any relationships part of the package (the root, the workbook, every sheet, drawings, charts, external links, an orphaned relationships part, …) that is not a hyperlink and that is external, or may be read as external by another program, gives one `UNSUPPORTED_PART` warning with `partKind: 'externalTarget'` for the whole package. It fails closed: **whatever the relationship's kind**, so a linked OLE object gives both `'oleObject'` and `'externalTarget'`, an external link gives `'externalLink'` and, for its `externalLinkPath` (or `xlPathMissing`, `xlStartup`, …) relationship, `'externalTarget'`, and the same holds for `connections`, `queryTable`, `control`, `package`, `image` and types no one has defined. Hyperlinks are exempt in every case: the transitional and Strict `…/hyperlink` types, compared as whole URIs without regard to case, so a made-up type ending in `/hyperlink` is reported; a hyperlink opens only when it is followed. Reported as well, although the model reads the target as a part name inside the package as before: a `TargetMode` that is present but, as the attribute is decoded, neither `Internal` nor `External` in any letter case (`" External"`, `"External "`, `"1"`, `""`, `"Internal, External"`); a second `TargetMode` attribute, one with a namespace prefix (`p:TargetMode`) or in another letter case (`targetMode`); and an internal target, or any other attribute whose local name is `Target` (a second or prefixed one), that starts with a URI scheme (RFC 3986: a letter, then letters, digits, `+`, `-` or `.`, then `:`, after leading spaces; so also `C:/…`), starts with `//`, or contains a backslash. Part names (`../media/image1.png`, `/xl/media/image1.png`, percent-encoded names, a colon after the first segment) are not reported. The warning's `part` is the first relationships part (a zip entry name, such as `xl/drawings/_rels/drawing1.xml.rels`) that holds such a relationship, `parts` lists every one in the order the scan reads them (each once, so at most `maxEntries`), `relationshipTypes` gives the first 16 distinct relationship types (compared without regard to case; a type over 128 characters is given as its first 64, `…` and its length), and the message gives the number of relationships. The targets themselves are never included, resolved or fetched. 100,000 such relationships in one part are one warning with one part and one type. The checks are one pass over each ``'s attributes as written. This is a warning, not a refusal: files `read` read before 2.6 still read. To refuse them, check for `partKind: 'externalTarget'`. Evidence: no file of the test corpus (the openpyxl, LibreOffice and import fixtures and the conformance corpus this library writes, whose hyperlinks are external relationships) has one; this library writes no external relationship other than hyperlinks. - 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. @@ -977,6 +977,7 @@ import { inspect } from 'javascript-excel/read'; const limits = { maxColumns: 256, maxCells: 1_000_000, maxItems: 100_000, maxEntryBytes: 64 * 1024 * 1024, maxTotalBytes: 128 * 1024 * 1024 }; try { const report = await inspect(upload, { limits, signal: AbortSignal.timeout(10_000) }); + // 'externalTarget': anything Excel may fetch from outside the file (linked pictures, linked OLE objects, external links, ...). if (['vbaProject', 'externalLink', 'externalTarget'].some((k) => report.partKinds.includes(k))) refuse('active content'); else accept(report.sheets.map((s) => `${s.name}: ${s.cells} cells`)); } catch (err) { @@ -1831,7 +1832,7 @@ export function isDataLossWarning(warning: ExcelWarning | ExcelWarningCode): boo | Warning code | Data loss | Situation and recovery | |---|---|---| -| `UNSUPPORTED_PART` | yes | Charts, drawings, pivots, comments, VBA, … are outside the model and not in the result; one warning per kind (so it cannot flood the list), `partKind` names it. Since 2.5 also ActiveX controls (`'activeX'`), embedded packages (`'embeddedPackage'`), ribbon customisations (`'customUI'`), Office web add-ins (`'webExtension'`), names 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`. Since 2.6 also relationships to targets outside the package that nothing else covers, such as linked pictures (`'externalTarget'`, one warning, with every relationships part that holds one in `parts` and their types in `relationshipTypes`). 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`. Since 2.6 also every relationship that is not a hyperlink and points, or may point, outside the package, such as a linked picture, whatever its kind (`'externalTarget'`, one warning, with every relationships part that holds one in `parts` and their types in `relationshipTypes`). 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 | @@ -1894,7 +1895,7 @@ if (lost.length) throw new Error(`Refused: ${[...new Set(lost.map((w) => w.code) | **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. | -| **Content fetched from outside the file** (a linked picture or another relationship with `TargetMode="External"`: a tracking beacon when the file is opened, or, through a UNC or `file:` target, the user's NTLM credentials sent to the attacker's host) | Never fetched or resolved by this library, and reported so an app can refuse the file (since 2.6): every external relationship in any relationships part of the package that is not a hyperlink and that no other kind covers (a linked OLE object stays `'oleObject'`, an external link's own path `'externalLink'`) gives one `UNSUPPORTED_PART` warning with `partKind: 'externalTarget'`, with the relationships parts in `parts` and the types in `relationshipTypes` (bounded; no target text). `inspect` reports it the same. Hyperlinks are not reported: the reader returns their targets verbatim (see **Malicious hyperlinks**). To refuse such files, check for this `partKind` (§5.2). | +| **Content fetched from outside the file** (a linked picture or another relationship with `TargetMode="External"`: a tracking beacon when the file is opened, or, through a UNC or `file:` target, the user's NTLM credentials sent to the attacker's host) | Never fetched or resolved by this library, and reported so an app can refuse the file (since 2.6), failing closed: every relationship in any relationships part of the package that is not a hyperlink and is external, whatever its kind (a linked OLE object or an external link's path gets `'externalTarget'` next to `'oleObject'` or `'externalLink'`), or that another program might read as external (a `TargetMode` other than `Internal` or `External`, a duplicate or prefixed `TargetMode`, an internal target with a URI scheme, `//` or a backslash), gives one `UNSUPPORTED_PART` warning with `partKind: 'externalTarget'`, with the relationships parts in `parts` and the types in `relationshipTypes` (bounded; no target text). `inspect` reports it the same. Hyperlinks are not reported: the reader returns their targets verbatim (see **Malicious hyperlinks**). To refuse such files, check for this `partKind` (§5.2). | | **Hostile relationships parts** | Since 2.5 the scan parses every relationships part in the zip: those of reached parts, also of sheets left out by `sheets` and of nested parts (drawings, tables, …), and those whose owner nothing reaches (orphans, in any percent-encoded spelling of `_rels` or `.rels`). A DTD in any of them throws `XML_DTD_FORBIDDEN`, and one past an XML or zip limit (for example deeper than `maxXmlDepth`) throws `LIMIT_EXCEEDED`, as for any part the reader parses; 2.4.0 never opened those parts and read such a file. Since 2.5, two zip entries with equivalent part names (equal after percent-decoding and case folding) throw `ZIP_INVALID`; 2.4.0 threw only for names that differ in case. A relationships part that is only malformed XML does not throw: it and the parts only it reaches are reported as unreferenced. | | **ReDoS** | Hot paths (A1 parsing, number detection, CSV) use hand-written scanners or linear regexes with no nested quantifiers. Format codes are bounded by part size. | | **Encrypted, legacy and macro content** | CFB containers (`.xls`, encrypted OOXML) throw `UNSUPPORTED_FORMAT`; VBA parts are dropped, never executed, and reported as `'vbaProject'` (or `'unreferencedPart'` when no relationship reaches them). | diff --git a/packages/javascript-excel/src/internal/read/opc.ts b/packages/javascript-excel/src/internal/read/opc.ts index fb686ba..f6a776c 100644 --- a/packages/javascript-excel/src/internal/read/opc.ts +++ b/packages/javascript-excel/src/internal/read/opc.ts @@ -36,6 +36,45 @@ export interface Relationship { */ tooLong?: boolean; external: boolean; + /** + * Read as internal, but it may point outside the package (JSE-85): its + * TargetMode is neither `Internal` nor `External` (in any case, not + * trimmed); there is a second, prefixed or differently cased TargetMode + * attribute; or the target, or any other Target-named attribute, starts + * with a URI scheme or `//` or contains a backslash. The model still reads + * the target as a part name; the package scan reports it as an external + * target. + */ + outside?: boolean; +} + +/** A URI scheme (RFC 3986) at the start, after spaces; a network-path reference (`//`); or a backslash anywhere. */ +export function pointsOutside(target: string): boolean { + if (target.includes("\\")) return true; + const t = target.trimStart(); + return t.startsWith("//") || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(t); +} + +/** + * Whether the attributes of a `` read as internal may name a + * target outside the package (Relationship.outside). One pass over the + * attributes as written (duplicates included), linear in the tag. + */ +function outsideByAttributes(a: XmlAttrs): boolean { + let modes = 0; + for (const [q, v] of a.entries()) { + const colon = q.indexOf(":"); + if (q === "xmlns" || (colon > 0 && q.slice(0, colon) === "xmlns")) continue; + const len = q.length - colon - 1; + if (len !== 10 && len !== 6) continue; + const local = (colon === -1 ? q : q.slice(colon + 1)).toLowerCase(); + if (local === "targetmode") { + if (q !== "TargetMode" || ++modes > 1) return true; + const mode = v.toLowerCase(); + if (mode !== "internal" && mode !== "external") return true; + } else if (local === "target" && pointsOutside(v)) return true; + } + return false; } /** @@ -227,6 +266,7 @@ export class Package { const target = a.get("Target"); const external = (a.get("TargetMode") ?? "").toLowerCase() === "external"; const rel: Relationship = { id: id ?? "", type, kind: type.slice(type.lastIndexOf("/") + 1), target: "", external }; + if (!external && outsideByAttributes(a)) rel.outside = true; if (target === undefined) { malformed.push(rel); // classified by its type alone return; diff --git a/packages/javascript-excel/src/internal/read/reader.ts b/packages/javascript-excel/src/internal/read/reader.ts index 7753462..c179236 100644 --- a/packages/javascript-excel/src/internal/read/reader.ts +++ b/packages/javascript-excel/src/internal/read/reader.ts @@ -191,8 +191,8 @@ export function warnUnsupportedParts(ctx: Pick = new Set([ ]); const HYPERLINK_TYPE_LENGTH = Math.max(...[...HYPERLINK_TYPES].map((t) => t.length)); -/** - * Relationship kinds (lower case) that give an external link's source file: - * under a part reported as `externalLink` they are that external link, not a - * separate external target. - */ -const EXTERNAL_LINK_PATHS: ReadonlySet = new Set(["externallinkpath", "xlpathmissing", "xlstartup", "xlalternatestartup", "xllibrary"]); - /** At most this many distinct relationship types are listed for external targets (each excerpted). */ export const MAX_EXTERNAL_TYPES = 16; @@ -185,9 +178,11 @@ export interface PackageScan { */ forbidden: string[]; /** - * Relationships with TargetMode="External" that no other kind covers - * (JSE-85): not a hyperlink, not of a kind in REPORTED_ANYWHERE, and not - * the source path of a part found as an external link. `count` is how many + * Relationships that are not hyperlinks and are external + * (TargetMode="External") or may point outside the package + * (Relationship.outside), whatever their kind, so also those reported as + * another kind (a linked OLE object, an external link's path) (JSE-85). + * `count` is how many * there are; `parts` the relationships parts (zip entry names) that hold * them, each once, in walk order, so at most maxEntries; `types` the first * MAX_EXTERNAL_TYPES distinct relationship types (compared without regard @@ -291,15 +286,13 @@ export async function scanPackageParts(pkg: Package): Promise { const malformed = pkg.malformedRels.get(relsEntry.name) ?? []; if (malformed.length) forbidden.add(relsEntry.name); const all = malformed.length ? [...rels, ...malformed] : rels; - // A part found as an external link (it was found before its relationships are read: breadth first). - const ofExternalLink = foundKeys.has(`externalLink\u0000${partKey(source)}`); let externalHere = false; 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 && isExternalTarget(rel, ofExternalLink)) { + if ((rel.external || rel.outside) && !isHyperlink(rel)) { external.count++; if (!externalHere) { externalHere = true; @@ -343,15 +336,7 @@ export async function scanPackageParts(pkg: Package): Promise { return { found, unreferenced, forbidden: [...forbidden], external }; } -/** - * Whether an external relationship is reported as `externalTarget`: not when - * its own kind is reported wherever it sits (a linked OLE object is - * `oleObject`), when it is a hyperlink, or when it is the source path of a - * part found as an external link. Every other type, known or not, is. - */ -function isExternalTarget(rel: Relationship, ofExternalLink: boolean): boolean { - const kind = relationshipKindOf(rel); - if (kind !== undefined && REPORTED_ANYWHERE.has(kind)) return false; - if (rel.type.length <= HYPERLINK_TYPE_LENGTH && HYPERLINK_TYPES.has(rel.type.toLowerCase())) return false; - return !(ofExternalLink && EXTERNAL_LINK_PATHS.has(rel.kind.toLowerCase())); +/** A hyperlink relationship (HYPERLINK_TYPES): never reported as `externalTarget`. */ +function isHyperlink(rel: Relationship): boolean { + return rel.type.length <= HYPERLINK_TYPE_LENGTH && HYPERLINK_TYPES.has(rel.type.toLowerCase()); } diff --git a/packages/javascript-excel/src/warnings.ts b/packages/javascript-excel/src/warnings.ts index 13e150c..5cb7765 100644 --- a/packages/javascript-excel/src/warnings.ts +++ b/packages/javascript-excel/src/warnings.ts @@ -43,9 +43,11 @@ export type ExcelWarningCode = * `'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). - * `'externalTarget'` (since 2.6) is a relationship with `TargetMode="External"` - * that no other kind covers and is not a hyperlink, such as a linked picture - * Excel fetches when the file is opened. Kinds may be added in a minor + * `'externalTarget'` (since 2.6) is any relationship that is not a hyperlink + * and is external, or may be read as external (an odd or duplicate + * TargetMode, an internal target with a URI scheme, `//` or a backslash), + * whatever its kind, such as a linked picture Excel fetches when the file + * is opened. Kinds may be added in a minor * release, so a `switch` over it needs a `default` branch. */ export type ExcelPartKind = diff --git a/packages/javascript-excel/test/read/external-targets.test.ts b/packages/javascript-excel/test/read/external-targets.test.ts index 4225e48..d6876ce 100644 --- a/packages/javascript-excel/test/read/external-targets.test.ts +++ b/packages/javascript-excel/test/read/external-targets.test.ts @@ -165,25 +165,101 @@ describe("external targets elsewhere in the package", () => { }); }); -describe("TargetMode, as the relationships parser reads it", () => { +describe("TargetMode", () => { // The parser compares TargetMode case-insensitively and does not trim it. it.each([["External"], ["external"], ["EXTERNAL"], ["eXtErNaL"]])("%s is external: reported", async (mode) => { const w = await both(withDrawing([["rI", "image", "https://tracker.example/p.png", mode]])); expect(externalOf(w)?.parts).toEqual([DRAWING_RELS]); }); - it.each([[" External"], ["External "], ["Internal"], [""]])("%j is not external: the target is a part name, and nothing is reported as externalTarget", async (mode) => { - const bytes = await build(withDrawing([["rI", "image", "https://tracker.example/p.png", mode]])); + it.each([["Internal"], ["internal"], ["INTERNAL"]])("%s with a part name as target: not reported", async (mode) => { + const w = await both(withDrawing([["rI", "image", "../media/image1.png", mode]], { parts: { "xl/media/image1.png": "png" } })); + expect(externalOf(w)).toBeUndefined(); + }); + + // Fail closed (JSE-85 F1a): a TargetMode that is neither Internal nor External is reported, whatever the target. + it.each([[" External"], ["External "], ["\tExternal"], ["1"], ["Internal, External"], [""], ["Externa"]])("%j is neither: reported, although the model reads the target as a part name", async (mode) => { + const bytes = await build(withDrawing([["rI", "image", "../media/image1.png", mode]], { parts: { "xl/media/image1.png": "png" } })); const ctx = new ReadContext(openZip(bytes), DEFAULT_LIMITS, undefined, undefined, undefined); const pkg = new Package(ctx); - expect((await pkg.rels("xl/drawings/drawing1.xml"))[0]!.external).toBe(false); - const w = await both(withDrawing([["rI", "image", "https://tracker.example/p.png", mode]])); + const [rel] = await pkg.rels("xl/drawings/drawing1.xml"); + expect(rel!.external).toBe(false); + expect(rel!.target).toBe("xl/media/image1.png"); + const w = await both(withDrawing([["rI", "image", "../media/image1.png", mode]], { parts: { "xl/media/image1.png": "png" } })); + expect(externalOf(w)?.parts).toEqual([DRAWING_RELS]); + }); + + const raw = (attrs: string) => ``; + const drawingWith = (attrs: string) => withDrawing([], { parts: { [DRAWING_RELS]: raw(attrs), "xl/media/image1.png": "png" } }); + + // F1c: the XML reader keeps every attribute; the parser uses the first unprefixed TargetMode and Target. + it.each([ + ["a prefixed p:TargetMode", 'Target="../media/image1.png" p:TargetMode="External"'], + ["a prefixed TargetMode next to TargetMode=Internal", 'Target="../media/image1.png" TargetMode="Internal" p:TargetMode="External"'], + ["a second TargetMode (the parser keeps the first)", 'Target="../media/image1.png" TargetMode="Internal" TargetMode="External"'], + ["a TargetMode in another letter case", 'Target="../media/image1.png" targetMode="External"'], + ["a second Target that points outside", 'Target="../media/image1.png" Target="https://tracker.example/p.png"'], + ["a prefixed Target that points outside", 'Target="../media/image1.png" p:Target="\\\\host\\s\\p.png"'], + ])("%s: reported", async (_, attrs) => { + const w = await both(drawingWith(attrs)); + expect(externalOf(w)?.parts).toEqual([DRAWING_RELS]); + }); + + it("an xmlns declaration named TargetMode is not an attribute: not reported", async () => { + const w = await both(drawingWith('Target="../media/image1.png" xmlns:TargetMode="urn:x"')); expect(externalOf(w)).toBeUndefined(); }); }); -describe("not reported as externalTarget", () => { - it("hyperlinks, on a sheet and on a drawing (transitional and strict types, any case)", async () => { +describe("internal targets that point outside (JSE-85 F1b)", () => { + it.each([ + ["http:", "http://tracker.example/p.png"], + ["https:", "https://tracker.example/p.png"], + ["file:", "file:///C:/p.png"], + ["ftp:", "ftp://host/p.png"], + ["any RFC 3986 scheme", "x-y.z+1:anything"], + ["a drive letter", "C:/Users/p.png"], + ["a scheme after leading spaces", " https://tracker.example/p.png"], + ["a network-path reference", "//host/share/p.png"], + ["a UNC path", "\\\\host\\share\\p.png"], + ["a backslash anywhere", "../media\\image1.png"], + ])("%s, without TargetMode: reported", async (_, target) => { + const w = await both(withDrawing([["rI", "image", target]])); + expect(externalOf(w)?.parts).toEqual([DRAWING_RELS]); + }); + + it("with TargetMode=Internal: reported", async () => { + const w = await both(withDrawing([["rI", "image", "https://tracker.example/p.png", "Internal"]])); + expect(externalOf(w)?.parts).toEqual([DRAWING_RELS]); + }); + + it.each([ + ["relative", "../media/image1.png"], + ["absolute", "/xl/media/image1.png"], + ["percent-encoded", "../media/image%31.png"], + ["a colon after the first segment", "../media/a:b.png"], + ["a colon after a ./ segment", "./a:b.png"], + ])("%s part names are not reported", async (_, target) => { + const w = await both(withDrawing([["rI", "image", target]], { parts: { "xl/media/image1.png": "png", "xl/media/a:b.png": "png", "xl/drawings/a:b.png": "png" } })); + expect(externalOf(w)).toBeUndefined(); + }); + + it("a hyperlink with a URL target and no TargetMode, or an odd one, is exempt as before", async () => { + const w = await both({ + sheets: [CELL], + override: { + "xl/worksheets/_rels/sheet1.xml.rels": rels([ + ["rH", "hyperlink", "https://example.com/"], + ["rJ", "hyperlink", "\\\\host\\s", " External"], + ]), + }, + }); + expect(externalOf(w)).toBeUndefined(); + }); +}); + +describe("hyperlinks are never reported", () => { + it("on a sheet and on a drawing (transitional and strict types, any case)", async () => { const w = await both( withDrawing( [ @@ -208,55 +284,40 @@ describe("not reported as externalTarget", () => { const w = await both(withDrawing([["rH", "http://example.com/x/hyperlink", "https://tracker.example/h", "External"]])); expect(externalOf(w)!.relationshipTypes).toEqual(["http://example.com/x/hyperlink"]); }); +}); - it("a linked OLE object keeps its kind, 'oleObject', and is not reported twice", async () => { - const w = await both({ sheets: [CELL], sheetRels: { 0: [["rO", "oleObject", "file:///C:/data.xlsx", true]] } }); - expect(kinds(w)).toEqual([["oleObject", "xl/worksheets/sheet1.xml"]]); +describe("external relationships of kinds already reported get 'externalTarget' too (fail closed)", () => { + it("a linked OLE object: 'oleObject' and 'externalTarget'", async () => { + const w = await both({ sheets: [CELL], sheetRels: { 0: [["rO", "oleObject", "\\\\host\\s\\x", true]] } }); + expect(kinds(w)).toEqual([["oleObject", "xl/worksheets/sheet1.xml"], ["externalTarget", "xl/worksheets/_rels/sheet1.xml.rels"]]); + expect(externalOf(w)!.relationshipTypes).toEqual([`${REL}/oleObject`]); }); - it("an external OLE object on a chart (linked chart data) keeps 'oleObject'", async () => { + it("an external OLE object on a chart (linked chart data)", async () => { const w = await both( withDrawing([["rC", "chart", "../charts/chart1.xml"]], { parts: { "xl/charts/chart1.xml": "", "xl/charts/_rels/chart1.xml.rels": rels([["rO", "oleObject", "file:///C:/book.xlsx", "External"]]) }, }), ); - expect(kinds(w)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["oleObject", "xl/charts/chart1.xml"]]); + expect(kinds(w)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["oleObject", "xl/charts/chart1.xml"], ["externalTarget", "xl/charts/_rels/chart1.xml.rels"]]); + }); + + it.each([["connections"], ["queryTable"], ["control"], ["package"], ["image"]])("an external %s relationship on a sheet", async (type) => { + const w = await both({ sheets: [CELL], sheetRels: { 0: [["rX", type, "https://tracker.example/x", true]] } }); + expect(externalOf(w)?.parts).toEqual(["xl/worksheets/_rels/sheet1.xml.rels"]); }); it.each([ ["externalLinkPath", "externalLinkPath"], ["xlPathMissing", "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlPathMissing"], ["xlStartup", "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlStartup"], - ["xlAlternateStartup", "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlAlternateStartup"], - ["xlLibrary", "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlLibrary"], - ])("an external link's own path (%s) is the external link: 'externalLink' only", async (_, type) => { + ])("an external link's own path (%s): 'externalLink' and 'externalTarget'", async (_, type) => { const w = await both({ sheets: [CELL], workbookRels: [["rL", "externalLink", "externalLinks/externalLink1.xml"]], parts: { "xl/externalLinks/externalLink1.xml": "", "xl/externalLinks/_rels/externalLink1.xml.rels": rels([["rId1", type, "\\\\host\\share\\other.xlsx", "External"]]) }, }); - expect(kinds(w)).toEqual([["externalLink", "xl/externalLinks/externalLink1.xml"]]); - }); - - it("an external link path anywhere but under an external link is an external target", async () => { - const w = await both(withDrawing([["rP", "externalLinkPath", "\\\\host\\share\\other.xlsx", "External"]])); - expect(kinds(w)).toEqual([["drawing", "xl/drawings/drawing1.xml"], ["externalTarget", DRAWING_RELS]]); - }); - - it("an external link with a picture under it: both kinds", async () => { - const w = await both({ - sheets: [CELL], - workbookRels: [["rL", "externalLink", "externalLinks/externalLink1.xml"]], - parts: { - "xl/externalLinks/externalLink1.xml": "", - "xl/externalLinks/_rels/externalLink1.xml.rels": rels([ - ["rId1", "externalLinkPath", "other.xlsx", "External"], - ["rId2", "image", "https://tracker.example/p.png", "External"], - ]), - }, - }); expect(kinds(w)).toEqual([["externalLink", "xl/externalLinks/externalLink1.xml"], ["externalTarget", "xl/externalLinks/_rels/externalLink1.xml.rels"]]); - expect(externalOf(w)!.relationshipTypes).toEqual([IMAGE]); }); it("workbooks this library writes, hyperlinks included, have none", async () => { From cf0103ac6f382fffa32ad3f61edaca867e199878 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Wed, 2 Dec 2026 17:30:23 +0100 Subject: [PATCH 3/3] docs: say exactly what externalTarget covers --- .changeset/external-targets.md | 2 +- docs/api.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.changeset/external-targets.md b/.changeset/external-targets.md index 3a053df..8191d57 100644 --- a/.changeset/external-targets.md +++ b/.changeset/external-targets.md @@ -5,6 +5,6 @@ `read`, `inspect` and `importDataset` now report relationships to targets outside the file (JSE-85), failing closed. Every relationship in any relationships part of the package (root, workbook, sheets, drawings, charts, external links, any other) that is not a hyperlink and that is external (`TargetMode="External"`, any letter case), whatever its kind, gives one `UNSUPPORTED_PART` warning with the new `partKind` `'externalTarget'`. Example: a linked picture, an `image` relationship of a drawing with an `http(s)`, UNC (`\\host\share\…`) or `file:` target, which Excel fetches when the file is opened (a tracking beacon; a UNC target can send the user's NTLM credentials to that host). Before, nothing reported it. Relationships already reported as another kind are reported here too: a linked OLE object gives `'oleObject'` and `'externalTarget'`, an external link `'externalLink'` and, for its path, `'externalTarget'`. Also reported, while the model still reads the target as a part name as before: - a `TargetMode` that is neither `Internal` nor `External` (`" External"`, `"1"`, `""`, …); - a second, namespace-prefixed or differently cased `TargetMode`; -- an internal target, or a second or prefixed `Target`, that starts with a URI scheme or `//`, or contains a backslash. +- an internal target, or a second, prefixed or differently cased `Target` attribute, that starts with a URI scheme (after leading whitespace) or `//`, or contains a backslash. Hyperlinks are never reported. The warning's `part` is the first relationships part that holds one, `parts` lists every such relationships part once (bounded by `maxEntries`), and the new `relationshipTypes` field gives the first 16 distinct relationship types, excerpted. Targets are never included, resolved or fetched, and any number of such relationships is one warning. No new refusals: files that read in 2.5.0 still read, with at most this one more warning. `ExcelPartKind` gains `'externalTarget'` (a `switch` over it needs a `default` branch, as documented) and `ExcelWarning` gains the optional `relationshipTypes`. Files this library writes have none: their hyperlinks are not reported. diff --git a/docs/api.md b/docs/api.md index af69d5a..62afa27 100644 --- a/docs/api.md +++ b/docs/api.md @@ -977,7 +977,8 @@ import { inspect } from 'javascript-excel/read'; const limits = { maxColumns: 256, maxCells: 1_000_000, maxItems: 100_000, maxEntryBytes: 64 * 1024 * 1024, maxTotalBytes: 128 * 1024 * 1024 }; try { const report = await inspect(upload, { limits, signal: AbortSignal.timeout(10_000) }); - // 'externalTarget': anything Excel may fetch from outside the file (linked pictures, linked OLE objects, external links, ...). + // 'externalTarget': any relationship to a target outside the file (linked pictures, linked OLE objects, external links, ...). + // Not covered by it: formulas such as IMAGE() or WEBSERVICE(), and the web query address inside connections.xml ('connections'). if (['vbaProject', 'externalLink', 'externalTarget'].some((k) => report.partKinds.includes(k))) refuse('active content'); else accept(report.sheets.map((s) => `${s.name}: ${s.cells} cells`)); } catch (err) {