# Untrusted workbooks

> What Birch UI Spreadsheet does with workbooks, pasted content and files that come from people you do not trust, and what stays your responsibility.

A spreadsheet component opens files that other people made. This page states what the component does with hostile input, how that is tested, and what it leaves to you.

## What is checked

| Input | What the component does |
| --- | --- |
| Colours in cell styles, borders, fills, gradients, rich text, conditional formats, tab colours, charts, shapes and sparklines | A colour reaches CSS or SVG only if it is a hex colour, an `rgb()`, `rgba()`, `hsl()` or `hsla()` value made of numbers, or a CSS colour name. Anything else is dropped and the default is used. |
| Font names | Each family is stripped to letters, digits, spaces and `_ . - + &`, quoted, and written as a `font-family` list. A name cannot end the declaration. |
| Numbers such as font size, indent, rotation and drawing sizes | A value that is not a finite number is dropped when the workbook loads. |
| Enumerated style values such as `align` and `readingOrder` | A value outside the documented set is dropped. |
| Hyperlinks | Only `http:`, `https:`, `mailto:`, `tel:` and `ftp:` addresses are kept and followed. A `javascript:` or `data:` address is removed when the workbook loads and refused by `setHyperlink()`. Links open with `noopener,noreferrer`. |
| Pictures | Only `data:image/…` and `blob:` sources are shown. An `http:` address is never fetched. `IMAGE()` formulas resolve through your `resolveImage` function only. |
| SVG pictures | A `data:image/svg+xml` source is only ever used as an image: the `src` of an `<img>` element, or the CSS `background-image` of a cell for a picture placed in a cell. In both, the browser runs no script from the SVG and loads nothing it references. The markup is never inlined into the page and never opened as a document. |
| Cell text, sheet names, defined names, notes, comments, validation messages, table and pivot names | Written to the page as text, never as markup. |
| Pasted HTML | Parsed in an inert document that runs no script and loads nothing. Only cell text, a few style properties and the component's own formula attribute are read; no pasted node is attached to the page. |
| Chart and shape drawings | Built from validated values, then passed through an allow-list that removes scripts, event handlers, external references and embedded content before they are attached. |
| Compressed files | `.xlsx` and `.ods` files are refused when they exceed the [zip limits](#zip-limits). |
| Legacy `.xls` files | Every record length and offset is checked against the file, and reading stops at the [limits](https://docs.birchui.com/spreadsheet/file-formats.md#limits) on records (5,000,000), cells (5,000,000), shared strings (2,000,000), text length (32,767 characters) and shared string size (256 MiB). A damaged file gives an `XlsError`, never a partial read of memory. Styles from the file go through the same checks as any workbook. |
| Macros, form controls, external links, embedded files | Kept as bytes and written back. Nothing in them runs. An embedded file is only handed to your `embeddedObjectOpen` handler or downloaded when the user asks. |

The checks run in two places. `sanitizeWorkbook()` is applied to every workbook as it is loaded, by `createSpreadsheet({ data })`, `fromJSON()`, the importers and the headless engine's `fromJSON()`. The places that write styles to the page validate again, so values set later through `setStyle()`, `addChart()` or `addShape()` are covered too. `sanitizeWorkbook()` does not change the object you pass in.

```ts
import { sanitizeWorkbook, safeColor, safeLinkUrl } from '@birchui/spreadsheet';

const clean = sanitizeWorkbook(untrustedJson); // the same object when nothing had to be removed
safeColor('red;background:url(//example.test)'); // undefined
safeLinkUrl('javascript:alert(1)'); // undefined
```

The colour check is an allow-list and is stricter than `safeCssValue()` from `@birchui/core`: values such as `var(--x)` or a gradient are not accepted as a workbook colour. Where the component writes its own computed values into inline styles, they are numbers and keywords it produced itself.

The component makes no network request of its own, whatever the workbook contains.

## Zip limits

An `.xlsx` or `.ods` file is a zip archive, and a small archive can expand to gigabytes. Reading stops with a `ZipLimitError` before anything is expanded when a file is over one of these limits:

| Limit | Default | Error `code` |
| --- | --- | --- |
| `maxEntries` | 10,000 files in the archive | `too-many-entries` |
| `maxEntryBytes` | 512 MiB for one file, expanded | `entry-too-large` |
| `maxTotalBytes` | 1 GiB for all files, expanded | `archive-too-large` |
| `maxRatio` | 200:1 expansion, checked for files that expand to more than 1 MiB | `ratio-too-high` |

The error also has `limit`, `actual` and `entryName`. Ordinary workbooks are far inside the limits: a 52.6 MB file with 1,760,000 cells has a largest part of 73 MiB and expands 6.5:1, and a sheet of 3,000,000 cells has a largest part of 118 MiB and expands 9.9:1. A sheet with millions of identical cells compresses better than that and can pass 200:1; raise the limit for files you trust.

```ts
import { xlsxToJSON, odsToJSON, validateXlsxPackage, ZipLimitError, DEFAULT_ZIP_LIMITS } from '@birchui/spreadsheet';

try {
  const workbook = await xlsxToJSON(bytes, { limits: { maxRatio: 500 } });
} catch (error) {
  if (error instanceof ZipLimitError) console.warn(error.code, error.entryName, error.message);
}
```

`limits` is accepted by `xlsxToJSON()`, `xlsxToJSONWithReport()`, `inspectXlsx()`, `odsToJSON()`, `validateXlsxPackage()` and by the component's `importXlsx()` and `importOds()`. In the component a refused file leaves the open workbook as it was, fires the `error` event with the reason, and puts a **File not opened** entry in the [import report](https://docs.birchui.com/spreadsheet/xlsx.md#import-report). `validateXlsxPackage()` reports the limit as an issue with the rule `zip-limit` instead of throwing.

## CSV export

A CSV file opened in a spreadsheet program is interpreted again, so text that starts with `=`, `+`, `-`, `@`, a tab or a carriage return can run as a formula there. `exportCsv()` and `jsonToCsv()` write such text with a leading apostrophe by default. See [CSV injection](https://docs.birchui.com/spreadsheet/file-formats.md#csv-injection).

## How this is tested

- `test/hostile-workbook.test.ts` loads a workbook in which every string is an injection attempt and every style number is a string that tries to end the declaration, as JSON and again after a trip through an xlsx file. It walks every sheet, opens the dialogs, renders the print layout and fails on any script element, event-handler attribute, unsafe address or external reference in the page.
- `test/hostile-files.test.ts` builds an xlsx file with a hostile font name in `styles.xml`, `javascript:` and `data:` hyperlink targets in the sheet relationships, hostile comment text and authors and a hostile chart title, and an ods file with a hostile font name, colour, sheet name and cell text, then imports and renders both. It also renders nine payload groups written independently of this package.
- `e2e/tests/spreadsheet-security.spec.ts` runs in Chrome and Firefox with every request intercepted and two tripwire globals. It pastes a table with `onclick`, `<img onerror>`, a `javascript:` link, `<iframe>`, `<meta http-equiv=refresh>` and a `<style>` block (through the real clipboard in Chrome, through a paste event in Firefox), renders the hostile workbook, the payload groups and the two hostile files, and loads an SVG picture that carries a script. Each test asserts that the content arrived as plain cells, that no script ran and that no request left the test server.
- `e2e/tests/spreadsheet-network.spec.ts` records every request, WebSocket and beacon in Chrome and Firefox while each part that is loaded on demand is used for the first time: exporting and importing xlsx, opening an xls file and a LibreOffice xlsx file, exporting PDF, exporting and importing ods, writing and opening a password-protected workbook, the password dialog of a picked file, the four downloads of the File tab and printing, and a workbook whose picture and `IMAGE()` formula point at another host. Each test asserts that the expected part was requested once, from the page's own origin, and that nothing left that origin. Plain editing, CSV export and the print HTML load none of those parts.
- `test/zip-limits.test.ts` builds archives that expand past the limits and checks that both importers refuse them.
- `test/xls-fuzz.test.ts` feeds the `.xls` reader 900 truncated, randomly corrupted and forged copies of six workbooks from a seeded generator, and requires a workbook or an `XlsError` each time within a time limit. `test/xls-records.test.ts` covers the limits, a stream that claims to be larger than its file, and thousands of sheets pointing at one substream.

## What stays with you

- **Content Security Policy.** The component needs `style-src 'unsafe-inline'` for cell styles, or `injectStyles: false` with the stylesheet imported and a policy that allows inline `style` attributes. It needs no `script-src` exception and no `connect-src`. Pictures need `img-src data: blob:`.
- **What you do with workbook text.** Values you read with `getValue()` or `toJSON()` are the file's text. Escape them when you put them in your own HTML, SQL or shell commands.
- **Callbacks.** `resolveImage`, `embeddedObjectOpen` and `hyperlinkClick` hand you addresses and bytes from the file. Validate them before fetching or opening anything.
- **Formulas are data.** The formula language has no function that reads files, the network or the page. Custom functions you [register](https://docs.birchui.com/spreadsheet/formulas.md#custom-functions) run with whatever arguments the workbook passes them.
- **Size.** The zip limits bound expansion, not calculation time. A workbook can still hold formulas that take long to calculate; use [worker calculation](https://docs.birchui.com/spreadsheet/worker-calculation.md) to keep the page responsive.
