# Running the engine on untrusted files

> The limits Birch UI PDF applies while it reads a file, how to change them, how to isolate the engine in a worker, and what is and is not validated when a PDF comes from someone you do not trust.

A PDF that a user uploads is attacker-controlled input. This page describes what the engine does to stay within bounds while it reads such a file, what you should add around it, and where its checks stop.

## Limits

Every document is read under a set of limits. Passing one produces a `PdfLimitError` with the name of the limit in `limit` and the value in `allowed`; nothing past the limit is decoded or allocated.

| Limit | Default | Applies to |
| --- | --- | --- |
| `maxStreamBytes` | 128 MiB | The decoded size of one stream. It is enforced while Flate, LZW, ASCII85 and RunLength data is expanded, not afterwards. |
| `maxExpansionRatio` | 250 | Decoded bytes divided by stored bytes, across the whole filter chain. The first mebibyte of output is exempt. |
| `maxTotalDecodedBytes` | 1 GiB | Everything the document's streams are decoded to, counted every time a stream is decoded. Page content that was decoded recently is kept (up to 32 MiB) and not decoded or counted again. |
| `maxPageContentBytes` | 64 MiB | The content streams of one page put together, so a small stream listed many times in `/Contents` cannot multiply. |
| `maxGraphicsStateDepth` | 256 | Nested `q` operators in a content stream. The format's own implementation limit is 28. |
| `maxContentOperations` | 2,000,000 | Operators in one content stream. |
| `maxFilterChain` | 8 | The number of filters one stream may name. |
| `maxImagePixels` | 100,000,000 | Width times height of an image before its pixels are decoded. An image stream may decode to what its dimensions call for, even above `maxStreamBytes`. |
| `maxNestingDepth` | 256 | Arrays and dictionaries inside one another. Deeper input is a `PdfSyntaxError`. |
| `maxTreeDepth` | 64 | Levels of the page tree. Deeper input is a `PdfSyntaxError`. |

A stream that passed a limit is remembered and refused immediately the next time something asks for it. Saving the graphics state costs a constant amount per level, not a copy of the state. Because `maxTotalDecodedBytes` counts work, not distinct data, a long session that decodes many large images again and again (redacting hundreds of scanned pages, for example) can reach it; raise it for such jobs.

```ts
import { PdfLimitError, loadPdfDocument, setDefaultPdfLimits, verifyPdfSignatures } from '@birchui/pdf/engine';

declare const upload: Uint8Array;

setDefaultPdfLimits({ maxStreamBytes: 32 * 1024 * 1024, maxImagePixels: 40_000_000 });

try {
  const pdf = await loadPdfDocument(upload, { limits: { maxTotalDecodedBytes: 512 * 1024 * 1024 } });
  console.info(pdf.pageCount, pdf.extractText(0).length);
  await verifyPdfSignatures(upload, { limits: { maxStreamBytes: 16 * 1024 * 1024 } });
} catch (error) {
  if (error instanceof PdfLimitError) console.warn(`refused: ${error.limit} (${error.allowed})`);
  else throw error;
}
```

`limits` on `openPdfDocument`, `loadPdfDocument` and `verifyPdfSignatures` applies to that document. `setDefaultPdfLimits(limits)` changes the defaults for everything opened afterwards, including the calls that take no `limits` option (`optimizePdf`, `comparePdf`, `signPdf`, merging a second document); call it with no argument to restore the built-in values. `getDefaultPdfLimits()` returns the current ones. Invalid values are a `TypeError`.

## Errors you can rely on

Malformed input produces one of these and nothing else: `PdfSyntaxError`, `PdfLimitError`, `PdfPasswordError`, `PdfPermissionError`, `PdfWriteError`, `UnsupportedFilterError`, `InflateError`, and a `RangeError` whose message starts with `Page index` when you ask for a page that does not exist. Reading is lenient where it can be: a page whose content cannot be decoded has no text, a broken cross-reference table is rebuilt by scanning the file, and an object that cannot be parsed reads as missing.

Recursive structures are followed with a visited set or a depth limit: the page tree, the outline, name trees, the field hierarchy, the `/Prev` chain of cross-reference sections, indirect `/Length` values and form XObjects that draw themselves. The test suite runs 22 hand-made malformed files, generated files with 100,000 levels of nesting and a 20,000-level page tree, decompression bombs for every filter, and 2,000 seeded mutations of valid files; each must open or fail with a typed error within a time limit.

Arguments you pass are checked when you pass them. `addAnnotation`, `updateAnnotation`, `addReply`, `addFormField`, `updateFormField`, `addAttachment` and `encrypt` throw a `PdfInputError` (a `TypeError` with the offending `path`, for example `field.format.kind`) instead of storing something that fails later in `save()`.

## Isolate the engine

Limits bound memory and time per stream, not per request. For files from the public, run the engine away from your main thread and be ready to stop it.

```ts
// pdf-worker.ts
import { PdfLimitError, loadPdfDocument, setDefaultPdfLimits } from '@birchui/pdf/engine';

setDefaultPdfLimits({ maxStreamBytes: 32 * 1024 * 1024, maxTotalDecodedBytes: 512 * 1024 * 1024 });

addEventListener('message', async (event: MessageEvent<Uint8Array>) => {
  try {
    const pdf = await loadPdfDocument(event.data);
    postMessage({ pages: pdf.pageCount, text: pdf.extractText(0) });
  } catch (error) {
    postMessage({ refused: error instanceof PdfLimitError ? error.limit : String(error) });
  }
});
```

```ts
function readInWorker(bytes: Uint8Array, timeoutMs = 10_000): Promise<unknown> {
  const worker = new Worker(new URL('./pdf-worker.ts', import.meta.url), { type: 'module' });
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      worker.terminate();
      reject(new Error('The document took too long to read'));
    }, timeoutMs);
    worker.onmessage = (event) => {
      clearTimeout(timer);
      worker.terminate();
      resolve(event.data);
    };
    worker.postMessage(bytes, [bytes.buffer]);
  });
}
```

- **Browser:** a dedicated worker per document, terminated on a timer, as above. The engine has no DOM dependency and never calls the network.
- **Node:** a `worker_threads` worker with `resourceLimits: { maxOldGenerationSizeMb }`, or a child process, and a timeout that terminates it. Reject files above a size you choose before you read them; the whole file is held in memory.
- **The viewer** parses and paints with its renderer and edits with the engine. The limits on this page cover the engine; the renderer has its own handling of malformed files.

## What is validated

- **Syntax** of every object the engine touches, with the limits above.
- **Signatures:** the digest over the signed byte ranges, the signature value, the certificate chain to the roots you supply, revocation data you supply, timestamps, and every change made after signing. The byte range has to start at zero, has to leave out exactly the `/Contents` string of the signature dictionary it belongs to, and that dictionary has to lie inside the signed bytes. See [Changes after signing](https://docs.birchui.com/pdf/signatures.md#changes-after-signing).
- **Form scripts** are parsed against a fixed grammar and never executed as JavaScript.
- **Passwords and permissions** of the standard security handler.

## What is not validated

- **Conformance.** A file that opens is not thereby a valid PDF. The engine does not check fonts, colour spaces, content stream operators it does not need, or PDF/A and PDF/UA rules beyond the [archive check](https://docs.birchui.com/pdf/document-tools.md).
- **Embedded files.** Attachments are returned as bytes. Scan them before you hand them to anything else.
- **Links and actions.** URLs in link annotations and submit actions come from the document and are not checked; the viewer asks before following a link it treats as an annotation.
- **Image codecs you plug in.** `decodeImage` callbacks and WASM decoders run with whatever limits they have.
- **Trust.** `isValid` on a signature says the signature is cryptographically sound and nothing disallowed was changed. It does not say the signer is someone you trust; use `isTrusted` or `summary` for that.
- **Time.** There is no global time budget. A file can stay inside every limit and still be slow, which is why the worker has a timeout.
