@inkvero/pdf-tools 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -61,8 +61,9 @@ The inspection holds **counts and flags only**. It never contains a script, a UR
61
61
  any other text from the file, and neither do error messages. The text of the metadata is available separately, and
62
62
  only on request, from `open(...)` then `doc.readMetadata()`.
63
63
 
64
- `open(bytes, options?)` resolves to a `PdfDoc` with `pageCount`, `inspect()` and `readMetadata()`. All the reading
65
- happens in `open`, under the limits; the methods only return copies of what was read.
64
+ `open(bytes, options?)` resolves to a `PdfDoc` with `pageCount`, `inspect()`, `readMetadata()` and
65
+ `readEmbeddedFiles()` (see [Embedded files](#embedded-files)). All the reading happens in `open`, under the limits;
66
+ the methods only return copies of what was read.
66
67
 
67
68
  The full API is in [docs/api.md](docs/api.md).
68
69
 
@@ -156,6 +157,110 @@ active content.
156
157
  A count says that something is there, not that it is harmful: `uri` counts ordinary links too. A strict upload
157
158
  check refuses a file when any count is above zero; a looser one can allow `uri`.
158
159
 
160
+ ## Embedded files
161
+
162
+ `inspect()` counts embedded files. To decide about them one by one, `open(...)` then `doc.readEmbeddedFiles()`
163
+ describes each embedded file of the document:
164
+
165
+ - `name`: the file name its file specification gives;
166
+ - `mediaType` and `relationship`: what the file declares (`/Subtype`, `/AFRelationship`);
167
+ - `size`: its size after decoding (it is decoded to be measured, never kept);
168
+ - `inNameTree` and `inAssociatedFiles`: whether the document's list of attachments (the `/EmbeddedFiles` name
169
+ tree) and its associated files (the catalog's `/AF`) list it;
170
+ - `xml`: for a file declared as XML (`text/xml`, `application/xml` or `+xml`), whether it is a well-formed XML 1.0
171
+ document without a DOCTYPE, and the name and namespace of its root element.
172
+
173
+ Names and media types are text from the file: treat them as untrusted input.
174
+
175
+ ```ts
176
+ const pdf = await open(bytes);
177
+ const { files, complete } = pdf.readEmbeddedFiles();
178
+
179
+ // Accept attachments of a few known kinds only, and nothing this report cannot vouch for.
180
+ const allowed = new Set(['text/xml', 'application/xml', 'application/pdf', 'image/png']);
181
+ const ok =
182
+ complete &&
183
+ files.length === pdf.inspect().active.embeddedFile &&
184
+ files.every((f) => f.size !== null && allowed.has(f.mediaType ?? '') && (f.xml === null || f.xml.wellFormed));
185
+ ```
186
+
187
+ **What `complete` promises.** Detection counts what *any* reading of the file holds; a description can follow only
188
+ one reading, the document in force. `complete` is `true` only for a plain file written in one form, which every
189
+ reader following its structure reads the same way. First the profile: the file is not encrypted, starts with
190
+ `%PDF-` at byte 0, ends exactly with `startxref`, its offset, `%%EOF` and at most one end of line, and stores each
191
+ embedded file uncompressed or as one whole `/FlateDecode` stream without parameters. Then one form for the whole
192
+ file, read or not: no hidden object, no repair, nothing `unresolved`, and every object header, string, name,
193
+ number, stream, cross-reference section and trailer written in the one form every reader reads alike. Then one
194
+ reading of everything used: the files described are exactly the files counted, the trailers agree on the catalog,
195
+ and every object, key, name and stream read on the way has one reading only.
196
+ [docs/api.md](docs/api.md#embeddedfiles) lists every rule. The promise is one-directional: no reader shows an
197
+ embedded file, a file name or file bytes that the report lacks or reports differently. It does not promise that
198
+ every reader lists every file or opens the file without a warning: on an unusual file a reader may show fewer files or none, fail to open the file, or warn: pdf.js on a cross-reference subsection that starts with a free entry other than object 0, readers that do not read an object stream given a generation other than 0, and pypdf on keys that Python's GBK and the browsers' GBK decode differently are known cases. It does not say that pages, the page tree, the outline, forms, page labels, destinations or
199
+ other name trees, annotations other than file attachments, actions, fonts, page content, unrelated stream data or
200
+ linearization data are valid or load without a warning in any reader. Every file attachment annotation in the file
201
+ must give a file the name tree lists, so a reader that shows one shows no file the list lacks. When it is `false`,
202
+ another reader may see other files or other values: do not rely on `files`. `complete` was compared with pdf.js,
203
+ qpdf, MuPDF and pypdf on generated, mutated and real files: no reader showed a file, name or bytes the report lacked
204
+ or reported differently (the test suite runs pdf.js and qpdf; the comparison with all four was run outside it); it
205
+ is not a proof about every reader.
206
+
207
+ **What it does not promise.** It says nothing about what the files contain, beyond the XML check. It is
208
+ conservative. These fine files report `complete: false`: **encrypted files** (their files are still listed,
209
+ decrypted; PDF/A forbids encryption), files with bytes before `%PDF-` or after the final `%%EOF` and its end of
210
+ line, files with syntax outside the one form anywhere (also in objects the description does not read), attachments
211
+ stored with a filter other than Flate, **signed or incrementally updated files whose update rewrites the catalog, the `/Names` dictionary, a file
212
+ specification or anything else the description reads**, files that needed repair, and files that embed an
213
+ uncompressed PDF (its own objects are found in the stream data, as a rebuilding reader would find them).
214
+
215
+ Each stream is decoded and checked once, however many file specifications give it, under `maxStreamBytes` and
216
+ `maxInflateBytes`. A file that cannot be decoded within them, or is damaged, has `size: null` (and the report is not
217
+ complete); it never makes `open` fail. After one such file, no further file is decoded. The work this adds to
218
+ `open` is bounded by `maxInflateBytes` of decompressed data plus the uncompressed data in the file, each read once
219
+ and, for XML, checked once: up to about 95 MB of XML from a file of a few hundred kB (five XML files in 369 kB took
220
+ about 2 s on the machine of the measurements, and 2.8 to 3.5 s with other heavy work running). A caller with a time limit tighter than that may see `TIMEOUT` on such a file where 0.1 did not.
221
+
222
+ The XML check is strict and reads no DTD: a document with a DOCTYPE is never well-formed (`doctype: true`), so no
223
+ entity is expanded and nothing is fetched. It is this library's own reading of a stated subset of XML 1.0: UTF-8 only, names
224
+ in ASCII, namespaces checked on every element, and limits on sizes and nesting ([docs/api.md](docs/api.md) states
225
+ it in full). A document outside the subset (UTF-16, a name with a character outside ASCII, a document past a limit)
226
+ is reported as not well-formed, though parsers may read it; a parser with limits of its own or a stricter grammar
227
+ may refuse a document the check accepts. No schema is applied. A malformed document is reported as such, never as an error. `complete` does not depend on it.
228
+
229
+ ### E-invoices
230
+
231
+ `readMetadata().eInvoice` is what the XMP metadata declares about an embedded e-invoice in the Factur-X or ZUGFeRD
232
+ extension schema (XRechnung included, in the Factur-X schema); like `pdfa`, it is declared, not validated.
233
+
234
+ ### Example: accepting an e-invoice
235
+
236
+ One way to accept a PDF/A-3 e-invoice that carries its invoice XML and nothing else:
237
+
238
+ ```ts
239
+ const pdf = await open(bytes);
240
+ const report = pdf.inspect();
241
+ const { files, complete } = pdf.readEmbeddedFiles();
242
+ const invoice = pdf.readMetadata().eInvoice;
243
+
244
+ const [file] = files;
245
+ const ok =
246
+ report.active.embeddedFile === 1 &&
247
+ complete &&
248
+ files.length === 1 &&
249
+ invoice !== null &&
250
+ file.name === invoice.documentFileName &&
251
+ // Both text/xml and application/xml occur in real invoices.
252
+ ['text/xml', 'application/xml'].includes(file.mediaType ?? '') &&
253
+ ['Data', 'Source', 'Alternative'].includes(file.relationship ?? '') &&
254
+ file.inNameTree &&
255
+ file.inAssociatedFiles &&
256
+ file.xml?.wellFormed === true &&
257
+ // A Factur-X or ZUGFeRD 2.x invoice is a UN/CEFACT Cross Industry Invoice. An XRechnung in UBL syntax has
258
+ // another root (Invoice or CreditNote in the UBL namespaces).
259
+ file.xml.root?.name === 'CrossIndustryInvoice' &&
260
+ file.xml.root.namespace === 'urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100' &&
261
+ report.pdfa?.part === 3;
262
+ ```
263
+
159
264
  ## Limits
160
265
 
161
266
  Every call is bounded. Past a limit it rejects with `PdfToolsError('LIMIT_EXCEEDED')` (`TIMEOUT` for the time),
@@ -178,15 +283,21 @@ Every call is bounded. Past a limit it rejects with `PdfToolsError('LIMIT_EXCEED
178
283
  await inspect(bytes, { limits: { maxPages: 50, timeoutMs: 2_000 }, signal: AbortSignal.timeout(5_000) });
179
284
  ```
180
285
 
181
- Only the streams the library must read are decompressed: object streams, cross-reference streams and the XMP
182
- metadata stream. Page contents, images and fonts are never decoded. Nothing is allocated from a count the file
286
+ Data after the last `%%EOF` is ignored, as pdf.js ignores it; qpdf rebuilds a file with more than about 1 KB of
287
+ trailing data, so the two may then read such a file differently (nothing in the inspection depends on it; such a
288
+ file is never `complete` in `readEmbeddedFiles()`).
289
+
290
+ Only the streams the library must read are decompressed: object streams, cross-reference streams, the XMP
291
+ metadata stream, and embedded files (to measure them and check XML). Page contents, images and fonts are never decoded. Nothing is allocated from a count the file
183
292
  declares (`/Size`, `/Index`, `/N`, `/Count`); what the data holds is counted instead.
184
293
 
185
294
  The work runs in short steps and gives the event loop a turn every few milliseconds; the time limit is checked
186
295
  inside steps too. An `AbortSignal` takes effect at the next turn. With the default limits the longest step measured
187
- on the hostile test files was 130 ms (scanning a 19 MB string), the slowest file took 0.9 s, and an abort took effect at
188
- most 40 ms late (the numbers are in
189
- [SECURITY.md](SECURITY.md#measured-worst-cases)). On a server, run `inspect` in a child process with its own heap
296
+ on the hostile test files was 131 ms (scanning a 19 MB string), the slowest file took 1.27 s (1.54 s with about 95 MB
297
+ of embedded XML to measure and check), and an abort took effect at most 4 ms late (the numbers are in
298
+ [SECURITY.md](SECURITY.md#measured-worst-cases)). On ordinary files, opening takes about 11 to 19 % longer than in
299
+ 0.1.0 without embedded files (median and total over the published files without any; files of 10 000 to 40 000
300
+ generated objects take 20 to 28 % longer) and about 30 to 40 % longer for a published e-invoice (median and total; a tenth of them take 50 to 70 % longer or more), for the checks behind `complete` and the measuring and checking of the files. On a server, run `inspect` in a child process with its own heap
190
301
  limit, as shown in [docs/server.md](docs/server.md); a worker thread keeps the main thread free but does not
191
302
  reliably contain memory exhaustion.
192
303
 
@@ -238,7 +349,9 @@ sequence of objects find, which is every object a reader could reach.
238
349
  fonts made to attack a viewer's decoders.
239
350
  - **It does not validate PDF/A.** `pdfa` is what the file claims in its XMP metadata. Use veraPDF to validate.
240
351
  - **It does not check signatures** (planned).
241
- - **It does not look inside embedded files.** An embedded file is counted, not opened.
352
+ - **It looks inside embedded files only to measure them and check XML.** An embedded file is counted, described and
353
+ decoded to measure its size; an XML file is checked for well-formedness. Nothing else inside an embedded file is
354
+ inspected.
242
355
  - **It does not run or analyse scripts.** A script is counted, whatever it does.
243
356
  - **It does not change the file.** Removing active content comes in a later version.
244
357
 
package/dist/index.d.mts CHANGED
@@ -110,11 +110,85 @@ interface Inspection {
110
110
  /** Active content, counted in every object of every revision, including replaced ones and those in object streams. */
111
111
  active: ActiveCounts;
112
112
  }
113
+ /**
114
+ * The e-invoice (Factur-X, ZUGFeRD, XRechnung) the XMP metadata declares in the properties of an invoice
115
+ * extension schema. Declared, not validated. Text from the file: treat it as untrusted input.
116
+ */
117
+ interface EInvoiceClaim {
118
+ /**
119
+ * The namespace the properties are in: `'factur-x'` (`urn:factur-x:pdfa:CrossIndustryDocument:invoice:1p0#`,
120
+ * Factur-X 1.0 and ZUGFeRD 2.1 and later, XRechnung included), `'zugferd-2.0'`
121
+ * (`urn:zugferd:pdfa:CrossIndustryDocument:invoice:2p0#`) or `'zugferd-1.0'`
122
+ * (`urn:ferd:pdfa:CrossIndustryDocument:invoice:1p0#`).
123
+ */
124
+ schema: "factur-x" | "zugferd-2.0" | "zugferd-1.0";
125
+ /** `DocumentType`, for example `'INVOICE'`, or `null` when not given. */
126
+ documentType: string | null;
127
+ /** `DocumentFileName`: the name of the embedded invoice XML, for example `'factur-x.xml'`. */
128
+ documentFileName: string | null;
129
+ /** `Version`, for example `'1.0'`. */
130
+ version: string | null;
131
+ /** `ConformanceLevel`: the profile, for example `'EN 16931'`, `'BASIC'` or `'XRECHNUNG'`. */
132
+ conformanceLevel: string | null;
133
+ }
113
134
  /** Text taken from the file. Treat it as untrusted input. */
114
135
  interface Metadata {
115
136
  info: Partial<Record<InfoField, string>>;
116
137
  /** The XMP packet as text, or `null` when there is none. */
117
138
  xmp: string | null;
139
+ /**
140
+ * The e-invoice the XMP packet declares, or `null`: when there is none, and when the packet does not say
141
+ * one thing for sure (properties in two of the namespaces, a property given twice with different values).
142
+ */
143
+ eInvoice: EInvoiceClaim | null;
144
+ }
145
+ /** One embedded file: text and numbers taken from the file. Treat the text as untrusted input. */
146
+ interface EmbeddedFile {
147
+ /** The file name the file specification gives: `/UF`, else `/F`. `null` when it gives none (or not as a string). */
148
+ name: string | null;
149
+ /** The media type the embedded file stream declares (its `/Subtype`, for example `'text/xml'`), or `null`. */
150
+ mediaType: string | null;
151
+ /** The file specification's `/AFRelationship` (for example `'Data'`, `'Source'`, `'Alternative'`), or `null`. */
152
+ relationship: string | null;
153
+ /** Bytes of the file after decoding. `null` when the data cannot be decoded within the limits, or is damaged. */
154
+ size: number | null;
155
+ /** Whether the document's `/EmbeddedFiles` name tree lists the file specification. */
156
+ inNameTree: boolean;
157
+ /** Whether the catalog's `/AF` array lists the file specification (a file associated with the whole document). */
158
+ inAssociatedFiles: boolean;
159
+ /**
160
+ * For a file whose declared media type is XML (`text/xml`, `application/xml` or one ending in `+xml`) and
161
+ * whose data was decoded: the result of a strict check. `null` otherwise.
162
+ */
163
+ xml: XmlCheck | null;
164
+ }
165
+ /** The well-formedness of an embedded XML file. */
166
+ interface XmlCheck {
167
+ /** Whether the data is a well-formed XML 1.0 document with no DOCTYPE. */
168
+ wellFormed: boolean;
169
+ /**
170
+ * Whether the data has a DOCTYPE declaration (a document with one is never reported as well-formed: entities
171
+ * and external subsets are not followed).
172
+ */
173
+ doctype: boolean;
174
+ /**
175
+ * The root element, when the document is well-formed: its local name and namespace URI (`null` for no
176
+ * namespace). Text from the file.
177
+ */
178
+ root: {
179
+ name: string;
180
+ namespace: string | null;
181
+ } | null;
182
+ }
183
+ interface EmbeddedFiles {
184
+ /** The embedded files of the document in force, ordered by the object number of their streams. */
185
+ files: EmbeddedFile[];
186
+ /**
187
+ * Whether `files` is the whole story: it accounts for every embedded file `inspect().active.embeddedFile`
188
+ * counts, nothing is `unresolved`, and every object and entry read on the way has one reading only. When
189
+ * `false`, another reader may see other files or other values: do not rely on `files`.
190
+ */
191
+ complete: boolean;
118
192
  }
119
193
  /** An opened PDF. */
120
194
  interface PdfDoc {
@@ -123,6 +197,8 @@ interface PdfDoc {
123
197
  inspect(): Inspection;
124
198
  /** The document's metadata: text from the file. */
125
199
  readMetadata(): Metadata;
200
+ /** The embedded files of the document: text from the file. */
201
+ readEmbeddedFiles(): EmbeddedFiles;
126
202
  }
127
203
  type PdfToolsErrorCode = "NOT_PDF" | "DAMAGED" | "ENCRYPTED" | "WRONG_PASSWORD" | "UNSUPPORTED_SECURITY" | "LIMIT_EXCEEDED" | "TIMEOUT" | "ABORTED" | "INVALID_ARGUMENT" | "INTERNAL";
128
204
  /**
@@ -151,11 +227,11 @@ export declare class PdfToolsError extends Error {
151
227
  /** The default limits, for untrusted uploads of up to 20 MB. */
152
228
  export declare const defaultLimits: Readonly<Limits>;
153
229
  /**
154
- * Opens a PDF under the limits and reads everything `inspect` and `readMetadata` report. Rejects with
230
+ * Opens a PDF under the limits and reads everything `inspect`, `readMetadata` and `readEmbeddedFiles` report. Rejects with
155
231
  * `PdfToolsError` for every problem; anything that cannot be read within the limits is an error, never an
156
232
  * empty report.
157
233
  */
158
234
  export declare function open(bytes: Uint8Array, options?: OpenOptions): Promise<PdfDoc>;
159
235
  /** `open(bytes, options)`, then `inspect()`. */
160
236
  export declare function inspect(bytes: Uint8Array, options?: OpenOptions): Promise<Inspection>;
161
- export type { ActiveCounts, ActiveKind, InfoField, Inspection, Limits, Metadata, OpenOptions, PageSize, PdfDoc, PdfToolsErrorCode, PdfToolsErrorDetails };
237
+ export type { ActiveCounts, ActiveKind, EInvoiceClaim, EmbeddedFile, EmbeddedFiles, InfoField, Inspection, Limits, Metadata, OpenOptions, PageSize, PdfDoc, PdfToolsErrorCode, PdfToolsErrorDetails, XmlCheck };