pdf-codec 1.4.2 → 1.5.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 +20 -12
- package/dist/content-write.cjs +2 -3
- package/dist/content-write.js +1 -2
- package/dist/crypto/aes.cjs +166 -0
- package/dist/crypto/aes.d.cts +6 -0
- package/dist/crypto/aes.d.ts +6 -0
- package/dist/crypto/aes.js +163 -0
- package/dist/crypto/md5.cjs +215 -0
- package/dist/crypto/md5.d.cts +4 -0
- package/dist/crypto/md5.d.ts +4 -0
- package/dist/crypto/md5.js +214 -0
- package/dist/crypto/rc4.cjs +29 -0
- package/dist/crypto/rc4.d.cts +4 -0
- package/dist/crypto/rc4.d.ts +4 -0
- package/dist/crypto/rc4.js +28 -0
- package/dist/crypto/sha2.cjs +261 -0
- package/dist/crypto/sha2.d.cts +6 -0
- package/dist/crypto/sha2.d.ts +6 -0
- package/dist/crypto/sha2.js +258 -0
- package/dist/diagnostics.cjs +7 -0
- package/dist/diagnostics.d.cts +4 -1
- package/dist/diagnostics.d.ts +4 -1
- package/dist/diagnostics.js +7 -1
- package/dist/document.cjs +38 -2
- package/dist/document.js +38 -2
- package/dist/encrypt.cjs +264 -0
- package/dist/encrypt.d.cts +11 -0
- package/dist/encrypt.d.ts +11 -0
- package/dist/encrypt.js +263 -0
- package/dist/filters.cjs +19 -1
- package/dist/filters.js +19 -1
- package/dist/image/ccitt.cjs +488 -0
- package/dist/image/ccitt.d.cts +17 -0
- package/dist/image/ccitt.d.ts +17 -0
- package/dist/image/ccitt.js +487 -0
- package/dist/images-read.cjs +1 -4
- package/dist/images-read.js +2 -5
- package/dist/index.cjs +3 -0
- package/dist/index.d.cts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +3 -2
- package/dist/interpret.cjs +173 -38
- package/dist/interpret.d.cts +27 -10
- package/dist/interpret.d.ts +27 -10
- package/dist/interpret.js +174 -39
- package/dist/math-font-write.cjs +1 -1
- package/dist/math-font-write.js +1 -1
- package/dist/{matrix-B3c2_a2f.d.cts → matrix-BHzJESll.d.cts} +2 -1
- package/dist/{matrix-B3c2_a2f.d.ts → matrix-BHzJESll.d.ts} +2 -1
- package/dist/matrix.cjs +2 -0
- package/dist/matrix.d.cts +2 -2
- package/dist/matrix.d.ts +2 -2
- package/dist/matrix.js +2 -1
- package/dist/objects.cjs +4 -0
- package/dist/objects.d.cts +2 -1
- package/dist/objects.d.ts +2 -1
- package/dist/objects.js +4 -1
- package/dist/read.cjs +43 -4
- package/dist/read.d.cts +1 -1
- package/dist/read.d.ts +1 -1
- package/dist/read.js +43 -4
- package/dist/write.cjs +1 -1
- package/dist/write.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
> A hand-written, dependency-minimal PDF codec: parses arbitrary real-world PDFs into a structured, positioned-content document and generates new PDFs from one, built on [`document-schema.js`](https://github.com/ExaDev/document-schema.js)'s `LayoutDocument` pivot and [Zod 4](https://zod.dev) codecs.
|
|
6
6
|
|
|
7
|
-
`pdf-codec` is the PDF-reading-and-writing half of [`documents.js`](https://github.com/ExaDev/documents.js), extracted into its own package: every layer of the PDF format — the object model, the cross-reference table, the content-stream operators, standard-font metrics, the parser's cross-reference/object-stream resolution and content-stream interpreter — is hand-written against the ISO 32000-1 specification, with no external PDF library (`pdf-lib`, `pdfjs-dist`, `mupdf`, or any other) as a dependency. The one exception is [`fflate`](https://github.com/101arrowz/fflate) for raw DEFLATE/zlib compression underneath PDF's `FlateDecode` filter and PNG's `IDAT` chunks. The OpenType/CFF font parsing this package's own writer uses to embed a real math font (`sfnt.ts`/`math-*.ts`) is hand-written too, for the same "no supply-chain surface beyond what's already declared" reason — the one bundled binary asset is the vendored STIX Two Math font itself (OFL-1.1, see [Fidelity](#fidelity) and `assets/fonts/NOTICE.md`), not a library.
|
|
7
|
+
`pdf-codec` is the PDF-reading-and-writing half of [`documents.js`](https://github.com/ExaDev/documents.js), extracted into its own package: every layer of the PDF format — the object model, the cross-reference table, the content-stream operators, standard-font metrics, the parser's cross-reference/object-stream resolution and content-stream interpreter — is hand-written against the ISO 32000-1 specification, with no external PDF library (`pdf-lib`, `pdfjs-dist`, `mupdf`, or any other) as a dependency. The one exception is [`fflate`](https://github.com/101arrowz/fflate) for raw DEFLATE/zlib compression underneath PDF's `FlateDecode` filter and PNG's `IDAT` chunks. The OpenType/CFF font parsing this package's own writer uses to embed a real math font (`sfnt.ts`/`math-*.ts`) is hand-written too, as are the cryptographic primitives its reader needs to open an encrypted PDF (`crypto/` — MD5, SHA-2, RC4, AES), for the same "no supply-chain surface beyond what's already declared" reason — and, for the crypto specifically, because `node:crypto` would end this package's platform neutrality and WebCrypto offers neither MD5 nor RC4 nor a synchronous API — the one bundled binary asset is the vendored STIX Two Math font itself (OFL-1.1, see [Fidelity](#fidelity) and `assets/fonts/NOTICE.md`), not a library.
|
|
8
8
|
|
|
9
9
|
That is a genuinely large undertaking — this codec is comparable in size to a small application in its own right — and it comes with an honest trade-off spelled out in [Fidelity](#fidelity) below: this is not, and does not attempt to be, as robust against adversarial or badly malformed real-world PDFs as a library with 15+ years of hardening. What it buys instead is a dependency-free, fully auditable PDF implementation with no supply-chain surface beyond `document-schema.js`, `fflate`, and `zod`.
|
|
10
10
|
|
|
@@ -70,6 +70,8 @@ const layout = readPdf(pdfBytes); // -> LayoutDocument: pages of positioned text
|
|
|
70
70
|
const bytes = writePdf(layout);
|
|
71
71
|
```
|
|
72
72
|
|
|
73
|
+
An encrypted PDF that opens without a password decrypts transparently on the way through — there is no extra option, no password parameter, and no separate call; one that genuinely needs a user password throws `PdfPasswordRequiredError` instead. See [Gotchas](#gotchas-and-quirks) for exactly which encryption is supported and why no password can be supplied.
|
|
74
|
+
|
|
73
75
|
Both accept an optional `signal` (`AbortSignal`); `readPdf` additionally takes a `sink` (a `PdfDiagnosticSink`, called once per recoverable parse diagnostic — see the three-tier failure policy under [Conventions](#conventions)), and `writePdf` an `onSubstitution` callback, called once per character not representable in a standard-14 font (see [Fidelity](#fidelity)).
|
|
74
76
|
|
|
75
77
|
The same round trip is also available as a schema-validated [`z.codec()`](https://zod.dev) pair:
|
|
@@ -100,7 +102,7 @@ Because `MathBox` and its own constituent types (`MathGlyphRun`/`MathRule`/`Math
|
|
|
100
102
|
|
|
101
103
|
Building a layout engine on top of this codec (this is what `documents.js`'s own `src/layout/` does for docx/pptx/odt/odp/ods/odg): `TextMeasurer`/`createStandardFontMeasurer` and `wrapRunsToWidth` answer "how wide does this text render, and where does this line break" against the standard-14 metrics; `resolveStandardFont`/`STANDARD_METRICS` map an arbitrary requested family/weight/style onto one of the 14 standard PDF faces and that face's own AFM-derived metrics; `rotatePointAboutCenter` handles shape-rotation placement math. None of these do any PDF I/O themselves — they're the same primitives `writePdf`/`readPdf` use internally, exported so a caller assembling its own `LayoutDocument` (from any source format) can measure and wrap text identically to how this package will actually render it.
|
|
102
104
|
|
|
103
|
-
The full `src/bytes/`/`src/image/` surface is exported too — `crc32`, `deflate`/`inflate`/`inflateTolerant`, `ByteReader`/`ByteWriter`/`concatBytes`, `readJpegInfo`, `decodePng`/`encodePng`, `unfilterScanlines`/`filterScanlines` — generic byte- and image-container primitives with zero PDF-specific knowledge of their own, useful independently of anything PDF-related.
|
|
105
|
+
The full `src/bytes/`/`src/image/` surface is exported too — `crc32`, `deflate`/`inflate`/`inflateTolerant`, `ByteReader`/`ByteWriter`/`concatBytes`, `readJpegInfo`, `decodePng`/`encodePng`, `unfilterScanlines`/`filterScanlines`, `decodeCcittFax` — generic byte- and image-container primitives with zero PDF-specific knowledge of their own, useful independently of anything PDF-related.
|
|
104
106
|
|
|
105
107
|
Every module under `src/` is also deep-importable directly by its own subpath, for a caller that wants one internal module (not part of the curated barrel above) without pulling in the rest:
|
|
106
108
|
|
|
@@ -116,16 +118,18 @@ This works via package.json's `"./*"` wildcard export, resolving any `pdf-codec/
|
|
|
116
118
|
The package is layered from generic primitives outward to the codec itself:
|
|
117
119
|
|
|
118
120
|
- **`src/math-types.ts`** and **`src/formula.ts`** — a local, structurally-compatible mirror of `documents.js`'s own `src/mathml/layout-types.ts` + `src/mathml/metrics.ts` (`MathColor`/`MathGlyphRun`/`MathRule`/`MathStroke`/`MathLayoutItem`/`MathBox`/`MathGlyphMetrics`/`MathFontMetrics`, including the latter's own `glyph()` method signature) and `src/model/formula.ts`'s `PositionedFormula`. Deliberately not imported from `documents.js` — that would be a circular dependency once `documents.js` depends on this package for `readPdf`/`writePdf` — the same "mirror the shape, don't import the package" trick this whole family already uses elsewhere (`odf.js`'s own `MathMlNode` mirrors `ooxml.js`'s `XmlNode` rather than importing it). Because every one of these types is plain data (only `MathFontMetrics` carries a method), a real `MathBox` value `documents.js`'s own MathML layout engine produces passes into `writePdf({ formulas })` with zero cast, zero wrapper, and zero transformation.
|
|
119
|
-
- **`src/bytes/`** and **`src/image/`** — generic byte and image-container primitives with zero PDF-specific knowledge: a chunked byte writer, a backtracking byte reader, CRC32, and a hand-written PNG decoder/encoder (palette/gray/RGB/alpha, multi-`IDAT` files, all five scanline filters) plus JPEG marker scanning for dimensions only — JPEG's compressed bytes pass through completely unchanged in both directions. `src/bytes/flate.ts` is the only file that imports `fflate`.
|
|
121
|
+
- **`src/bytes/`** and **`src/image/`** — generic byte and image-container primitives with zero PDF-specific knowledge: a chunked byte writer, a backtracking byte reader, CRC32, and a hand-written PNG decoder/encoder (palette/gray/RGB/alpha, multi-`IDAT` files, all five scanline filters) plus JPEG marker scanning for dimensions only — JPEG's compressed bytes pass through completely unchanged in both directions — and a hand-written CCITT Group 3/Group 4 fax decoder (ITU-T T.4/T.6), which knows nothing of PDF: `src/filters.ts` reads the `/CCITTFaxDecode` parameter dictionary and hands it plain options, and the identical bitstreams are what TIFF's own Group3Options/Group4Options describe. `src/bytes/flate.ts` is the only file that imports `fflate`.
|
|
120
122
|
- **`src/util/`** — two small, independently-duplicated copies of logic that lives elsewhere in the family for a reason narrow enough not to warrant a shared dependency: `base64.ts` (isomorphic base64 ⇄ `Uint8Array`, a verbatim copy of `odf.js`'s own `src/util/base64.ts`, replacing a dependency this codec used to have on `ooxml.js` purely for this one helper pair) and `abort.ts` (`throwIfAborted`, a four-line signal-check helper called at every page loop boundary in `write.ts`/`read.ts` — there is no `await` point in this package's synchronous reader/writer pipeline for cancellation to hook into implicitly, so every long-running loop checks explicitly instead; a duplicate of `documents.js`'s own `src/ports/abort.ts`, which stays there since other, non-PDF consumers still depend on it in that repository).
|
|
121
|
-
-
|
|
123
|
+
- **`src/crypto/`** — MD5, SHA-256/384/512, RC4, and AES-CBC, hand-written with zero local imports, exactly like `src/bytes/`. Not a preference: ISO 32000-1's own key-derivation algorithms name MD5 and RC4 directly, neither of which any platform crypto API this package could portably reach still offers, and `crypto.subtle` is asynchronous where this codec's read path is synchronous end to end. Reaching for `node:crypto` would put a Node builtin inside a `src/` tree that deliberately has none and is built with `platform: 'neutral'`, breaking the browser bundle its downstream consumer depends on. Each module cites the specification it implements (RFC 1321, FIPS 180-4, FIPS 197) and is tested against that specification's own published conformance vectors. MD5 and RC4 are cryptographically broken and are here solely to *read* files that already exist and whose format mandates them.
|
|
124
|
+
- **The codec itself, importing only `math-types`/`formula`/`bytes`/`image`/`crypto` (no OOXML or ODF knowledge at all):**
|
|
122
125
|
- **Write**: `objects.ts` (the `PdfObject` discriminated union), `afm-widths.ts`/`encoding.ts`/`winansi.ts`/`fonts.ts` (standard-14 metrics, WinAnsi encoding, family resolution), `measure.ts`/`text-layout.ts` (greedy line-wrapping), `matrix.ts`, `content-write.ts` (`LayoutItem[]` → content-stream operators), `write.ts` (the full object graph, classic cross-reference table, trailer, and — when `WritePdfOptions.formulas` is non-empty — one embedded math composite font group, allocated once and shared across pages).
|
|
123
126
|
- **Embedded math font**: `sfnt.ts` (a generic sfnt table-directory reader), `math-cmap.ts`/`math-hmtx.ts`/`math-table.ts` (Unicode → glyph ID, per-glyph advance widths, and the OpenType `MATH` table's constants/glyph-info subtables), `math-font.ts` (parses and caches the vendored STIX Two Math font once per process, exposing a size-specific `MathFontMetrics` implementation), `math-font-write.ts` (builds the `/Type0`/`/CIDFontType0`/`/FontDescriptor`/`/FontFile3`/ToUnicode object group), `math-content-write.ts` (a `PositionedFormula[]` → PDF content-stream bytes, Identity-H 2-byte CIDs for text-showing, `re`/`m`/`l` operators for rules and the radical hook). See [Fidelity](#fidelity) for the CFF-full-embed (not glyph-subsetted) simplification this makes.
|
|
124
|
-
- **Read**: `lexer.ts`/`parse.ts` (byte tokenizer and tokens → `PdfObject`), `filters.ts`/`predictors.ts` (Flate/LZW/ASCII85/ASCIIHex/RunLength, TIFF/PNG predictors), `xref.ts`/`document.ts` (classic and cross-reference-stream resolution, object streams, `/Prev` chains, linear-scan recovery, the page tree with attribute inheritance), `content-read.ts`/`interpret.ts` (the content-stream tokenizer and graphics/text state machine, including form-XObject recursion and general vector-path tracking — see [Gotchas](#gotchas-and-quirks)), `cmap.ts`/`font-style.ts`/`font-read.ts` (`/ToUnicode` CMaps, font-dictionary resolution), `images-read.ts` (Image XObjects → PNG/JPEG bytes), `read.ts` (`readPdf`, assembling all of the above into a `LayoutDocument`).
|
|
127
|
+
- **Read**: `lexer.ts`/`parse.ts` (byte tokenizer and tokens → `PdfObject`), `filters.ts`/`predictors.ts` (Flate/LZW/ASCII85/ASCIIHex/RunLength/CCITTFax, TIFF/PNG predictors), `xref.ts`/`document.ts` (classic and cross-reference-stream resolution, object streams, `/Prev` chains, linear-scan recovery, the page tree with attribute inheritance), `encrypt.ts` (the standard security handler: `/Encrypt` parsing, empty-user-password key derivation and `/U` verification, per-object keys, and the string/stream decryption `document.ts` applies transparently as each indirect object is fetched — see [Gotchas](#gotchas-and-quirks)), `content-read.ts`/`interpret.ts` (the content-stream tokenizer and graphics/text state machine, including form-XObject recursion and general vector-path tracking — see [Gotchas](#gotchas-and-quirks)), `cmap.ts`/`font-style.ts`/`font-read.ts` (`/ToUnicode` CMaps, font-dictionary resolution), `images-read.ts` (Image XObjects → PNG/JPEG bytes), `read.ts` (`readPdf`, assembling all of the above into a `LayoutDocument`).
|
|
125
128
|
- `codec.ts` — `pdfCodec`, a `z.codec()` pair over `readPdf`/`writePdf`, plus a standalone, ~20-line local copy of just the `%PDF-` header check `PdfBytesSchema` needs (`documents.js`'s own equivalent schema lives in a file that also carries unrelated docx/pptx/odt schemas that have no place here).
|
|
126
|
-
- **`src/test-support/pdf.ts`** — hand-built PDF fixtures for the parser's own tests (a classic-xref file, an xref-stream-with-object-streams file, a broken-`startxref` file needing linear-scan recovery, an incremental update,
|
|
129
|
+
- **`src/test-support/pdf.ts`** — hand-built PDF fixtures for the parser's own tests (a classic-xref file, an xref-stream-with-object-streams file, a broken-`startxref` file needing linear-scan recovery, an incremental update, a trailer naming a security handler no password could open, and more), built by literal byte/string concatenation and deliberately importing NOTHING from this package's own writer — a fixture built by calling `writePdf` would let a writer bug hide from the corresponding reader test and vice versa. Not part of the public surface; test-only.
|
|
130
|
+
- **`src/test-support/encrypted-pdfs.ts`** — the same independence principle applied to encryption: real PDFs encrypted by [qpdf](https://qpdf.sourceforge.io/), embedded as base64 and regenerated by `node scripts/generate-encrypted-pdf-fixtures.mjs`. One fixture per supported cipher, plus password-protected counterparts and an `/EncryptMetadata false` variant. Encrypted by a mature outside implementation on purpose — a fixture this package encrypted itself would let a bug in key derivation or in a cipher cancel out between the write and read halves and pass anyway.
|
|
127
131
|
|
|
128
|
-
Dependency direction is strictly downward and checkable: `math-types`/`formula`/`bytes`/`util` import nothing local (`bytes/flate.ts` imports `fflate`); `image` imports `bytes` only; the codec itself imports `math-types`+`formula`+`bytes`+`image`+`util` only. No `PdfObject`/`PdfDict`/`PdfStream` type appears outside the codec's own read/write modules — it never crosses a public boundary and is constructed exclusively by this package's own parser.
|
|
132
|
+
Dependency direction is strictly downward and checkable: `math-types`/`formula`/`bytes`/`crypto`/`util` import nothing local (`bytes/flate.ts` imports `fflate`); `image` imports `bytes` only; the codec itself imports `math-types`+`formula`+`bytes`+`image`+`crypto`+`util` only. Nothing anywhere under `src/` imports a `node:` builtin, which is what lets `tsdown`'s `platform: 'neutral'` build run unchanged in a browser bundle. No `PdfObject`/`PdfDict`/`PdfStream` type appears outside the codec's own read/write modules — it never crosses a public boundary and is constructed exclusively by this package's own parser.
|
|
129
133
|
|
|
130
134
|
## Conventions
|
|
131
135
|
|
|
@@ -134,15 +138,17 @@ Dependency direction is strictly downward and checkable: `math-types`/`formula`/
|
|
|
134
138
|
- **`PdfObject` has no Zod schema at all**, deliberately: it never crosses a public boundary or round-trips through JSON, and is constructed exclusively by this package's own parser — validating it would just be validating our own output. It narrows natively on its own `kind` discriminant instead.
|
|
135
139
|
- **The `MathBox`/`MathFontMetrics` family is structurally typed on purpose, not validated by Zod either.** This is the mechanism that lets a caller (`documents.js`) hand this package a real value produced by a completely independent module, with zero cast, zero wrapper, and no shared class or branded type — see [Architecture](#architecture).
|
|
136
140
|
- **No type assertions anywhere.** Every third-party or loosely-typed value is narrowed through a type guard or a Zod parse at the boundary.
|
|
137
|
-
- **A three-tier PDF-read failure policy**, applied consistently across every read module: throw a typed `PdfParseError`/`PdfEncryptedError` for a file that cannot be meaningfully processed at all; recover with a `PdfDiagnostic` (`severity: 'warning'`) for something malformed but salvageable (a bad `startxref`, a wrong stream `/Length`); degrade with a diagnostic for an individual unsupported feature (an unimplemented filter, an unrecognised colour space) while the rest of the document still reads.
|
|
141
|
+
- **A three-tier PDF-read failure policy**, applied consistently across every read module: throw a typed `PdfParseError`/`PdfEncryptedError`/`PdfPasswordRequiredError` for a file that cannot be meaningfully processed at all; recover with a `PdfDiagnostic` (`severity: 'warning'`) for something malformed but salvageable (a bad `startxref`, a wrong stream `/Length`); degrade with a diagnostic for an individual unsupported feature (an unimplemented filter, an unrecognised colour space) while the rest of the document still reads.
|
|
138
142
|
- **Conventional commits**, enforced via commitlint + husky.
|
|
139
143
|
|
|
140
144
|
## Gotchas and quirks
|
|
141
145
|
|
|
142
146
|
- **Reading arbitrary real-world PDFs is the single largest risk surface in this package**, and the parser is honest about its design target: cleanly-generated output from mainstream producers (Word, PowerPoint, Chrome, LibreOffice, Acrobat), recovering from the malformations those producers and their downstream tooling actually create, and failing loudly and specifically on anything else — not matching a mature library's robustness against adversarial input.
|
|
143
|
-
- **
|
|
144
|
-
-
|
|
145
|
-
- **`
|
|
147
|
+
- **An encrypted PDF is readable when, and only when, it opens without a password.** That is the overwhelmingly common real-world case — a permissions-only file, exported with "no printing" or "no copying" set, whose owner password may well be set but whose *user* password is empty. `readPdf` derives the file key from the empty user password, verifies it against the `/Encrypt` dictionary's own `/U` entry, and decrypts every string and stream transparently; nothing downstream of the object store knows the file was encrypted at all. Supported: `/Filter /Standard` at `/V` 1, 2, 4, and 5 — RC4-40, RC4-128, AES-128 (`/CFM /AESV2`) and AES-256 (`/CFM /AESV3`) — including `/EncryptMetadata false` and `/Identity` crypt filters. A file that genuinely needs a user password throws `PdfPasswordRequiredError`, its own distinct error, because "supply the password" and "this codec cannot read this at all" are different things to tell a user and only one of them can be acted on. Anything else — a non-standard (public-key) security handler, the unpublished `/V 3` algorithm, an unrecognised `/CFM` — still throws `PdfEncryptedError`.
|
|
148
|
+
- **Nothing in this codec accepts, prompts for, or guesses a password.** There is no password parameter on `readPdf`, and no owner-password path: authenticating as owner is a permissions escalation, not a way to read a file you were already allowed to read. Decryption is here to open files that are already open, not to get into ones that are not.
|
|
149
|
+
- **`CCITTFaxDecode` images decode for real; `JBIG2Decode`/`JPXDecode` images do not.** `src/image/ccitt.ts` is a hand-written ITU-T T.4/T.6 fax decoder — Group 4 (`/K < 0`, the modern default and the overwhelming majority of scanned-PDF usage), Group 3 one-dimensional (`/K = 0`), and Group 3 mixed (`/K > 0`) — producing a real packed 1-bit-per-pixel bitmap that the rest of `images-read.ts` then treats exactly like any other 1-bit `/DeviceGray` raster, `/Decode` inversion and all. `/Columns`, `/Rows` (falling back to the image's own `/Height`), `/BlackIs1`, and `/EncodedByteAlign` are honoured; the uncompressed-mode extension code is not, and a stream that stops making sense degrades to the rows already recovered plus a `pdf/ccitt-fax-degraded` diagnostic rather than throwing. JBIG2 and JPEG2000 images are still skipped with a diagnostic, the rest of the page still reading. JPEG images (`DCTDecode`) pass through completely losslessly in both directions; PNG-sourced images go through a real, narrowly-scoped hand-written codec.
|
|
150
|
+
- **`interpret.ts` tracks general vector paths, not just axis-aligned `re` rectangles.** `m`/`l`/`c`/`v`/`y`/`h` (and `re` itself, per its own ISO 32000-1 definition as a 4-point rectangle subpath) accumulate real subpaths — CTM-transformed line/cubic segments, open or closed — and any paint operator (`f`/`F`/`f*`/`S`/`s`/`B`/`B*`/`b`/`b*`) emits an item built from them. Verified both by dedicated tests and by a genuine `writePath` → `writePdf` → `readPdf` round trip recovering the original `LayoutPath` value exactly. This is the shared infrastructure a caller reconstructing structure from a `LayoutDocument` (a spreadsheet grid, a vector drawing) builds on.
|
|
151
|
+
- **A recovered path that matches one of three characteristic shape patterns comes back as that shape's own kind, not as a generic `LayoutPath`.** PDF has exactly one shape operator, `re`, and no ellipse or line operator at all, so a writer has no way to record what a path *was* — `interpret.ts` recovers it from the geometry instead. A single closed four-corner subpath whose every edge runs along one axis is a `LayoutRect` (so `re` under a non-rotated *or* 90°-rotated CTM, a hand-built `m`/`l`/`l`/`l`/`h` rectangle, and any combination of fill and stroke all reach it — not just the fill-only single-`re` case an earlier fast path covered); a closed subpath of exactly four cubic segments meeting at its bounding box's four cardinal points, with all eight control points at the standard kappa offset (`BEZIER_KAPPA`, 4/3·(√2−1)) those extremes imply, is a `LayoutEllipse` — precisely what `writeEllipse` emits; an open single-straight-segment stroke-only subpath is a `LayoutLine`. Tolerance is `max(1e-3pt, 1e-4 × the shape's own extent)`: the absolute floor is twenty times the 5e-5pt quantisation `formatNumber`'s 4-decimal-place rounding imposes, and the relative term is what lets a large ellipse from a producer that rounded its kappa constant more coarsely (`0.5523`) still match. **These are deliberate, bounded heuristics, not certainties** — a hand-authored freeform path that happens to consist of four kappa-ratio cubics between its bounding box's cardinal points is indistinguishable from a "real" ellipse in the PDF bytes, because at that point it geometrically *is* one, whatever the author called it. What a false positive can never do is misreport geometry: every detected shape reproduces its source path's own points exactly, so it changes an item's kind, never where or how big it is. Anything the patterns don't cover — a non-90° rotation, a curve that isn't the four-quadrant construction, a polygon that isn't a rectangle, multiple subpaths — stays a `LayoutPath`, and a rotated ellipse deliberately does too, since `LayoutEllipse` carries no rotation to report one with.
|
|
146
152
|
- **`writePdf`/`readPdf` round-trip a page's own `notes` field via a hidden annotation, not any real PDF feature.** PDF has no native concept of hidden presenter notes, so a page's `LayoutPage.notes` (when present) is written as a `/Subtype /Text` annotation (the same construct Acrobat's own sticky-note tool uses) with the `Hidden` annotation flag set so it never renders or prints, and `readPdf` reads it back via an internal author marker that distinguishes this package's own notes annotation from a genuine third-party sticky note. This is a round-trip mechanism specific to this package's own writer/reader pair — a PDF produced by anything else will never carry it, and a PDF consumer other than this package's own `readPdf` will never see it as anything but an invisible, empty sticky note. `documents.js` uses this to carry pptx/odp speaker notes through `pptxToPdf`/`pdfToPptx` and `odpToPdf`/`pdfToOdp`.
|
|
147
153
|
- **STIX Two Math (the embedded formula font) is a CFF-flavoured OpenType font (an `OTTO` sfnt wrapping a `CFF ` table), not TrueType/glyf** — confirmed by inspecting the vendored font's own sfnt table directory while `math-font.ts` was built. Genuine Type2-charstring glyph subsetting (re-encoding charstrings, rebuilding the CFF `INDEX` structures with a renumbered, minimal glyph set) is a substantially larger undertaking than TrueType glyf/loca subsetting, and is out of scope: the **entire** `CFF ` table is embedded verbatim, unmodified, as a single `/FontFile3` `/Subtype /CIDFontType0C` stream — a real, correct, working embedded font, just not glyph-subsetted. Everything else genuinely IS built from a targeted parse of only what's used: `cmap` resolves exactly the Unicode code points a document's formulas actually reference to glyph IDs, and the emitted `/W` widths array and ToUnicode CMap only ever cover those same glyph IDs, not the font's full ~5,500-glyph repertoire. A CID-keyed composite font built this way needs no `/CIDToGIDMap` at all (that key exists only for `/CIDFontType2`): per ISO 32000-1 9.7.4.2, a `/CIDFontType0` whose `/FontFile3` is a "bare" (non-CID-keyed) CFF program is read with CID treated as directly indexing the CFF's own `CharStrings` INDEX by glyph order — i.e. CID == GID, exactly the numbering `cmap`-derived glyph IDs already use, so Identity-H text-showing needs no further remapping anywhere in the write path.
|
|
148
154
|
- **The OpenType `MATH` table's `MathVariants` subtable (stretchy glyph assembly — building a tall parenthesis or brace from reusable top/middle/bottom/extender pieces) is deliberately not parsed by `math-table.ts`.** A caller asking for a stretchy fence or a stretchy operator wrapping a tall construct gets back the base glyph at its own fixed size, not a dynamically assembled one — a documented, honest omission, not a bug. `MathConstants` (every fraction/radical/script-positioning constant `MathFontMetrics` exposes) and `MathGlyphInfo` (italics correction, top-accent attachment) ARE both genuinely parsed in full.
|
|
@@ -154,7 +160,7 @@ Dependency direction is strictly downward and checkable: `math-types`/`formula`/
|
|
|
154
160
|
|
|
155
161
|
**The one exception is math-formula rendering (`WritePdfOptions.formulas`): this genuinely embeds a real, hand-parsed font.** Real box-model glyph runs are shown through the embedded STIX Two Math font with genuine per-glyph metrics (advance width, italic correction, top-accent attachment) and font-wide layout constants (axis height, fraction/radical rule thickness and gaps, script shift amounts) parsed directly from that font's own `MATH` table — not approximated or hand-tuned. See [Gotchas](#gotchas-and-quirks) for the exact boundary of what this package's own font parsing does and doesn't cover (the CFF-full-embed simplification, the unparsed `MathVariants` subtable, and the nominal-rather-than-ink vertical metrics).
|
|
156
162
|
|
|
157
|
-
**`readPdf(writePdf(doc))` is not guaranteed to reproduce `doc` exactly, and `writePdf(readPdf(bytes))` is not guaranteed to reproduce `bytes` exactly — this package makes no round-trip-losslessness claim in either direction.** A PDF page is fundamentally a stream of positioned drawing operators, not a structured document: a
|
|
163
|
+
**`readPdf(writePdf(doc))` is not guaranteed to reproduce `doc` exactly, and `writePdf(readPdf(bytes))` is not guaranteed to reproduce `bytes` exactly — this package makes no round-trip-losslessness claim in either direction.** A PDF page is fundamentally a stream of positioned drawing operators, not a structured document: a rectangle, an ellipse, and a line are recovered as their own kinds only because each is *always* written as one characteristic operator pattern this package recognises (see the shape-detection gotcha above) — a shape drawn any other way, or rotated off-axis, still collapses to a generic `LayoutPath`, and text is recovered as positioned glyph runs with no guarantee the original run boundaries (which characters were grouped into one `Tj` versus several) survive identically. This is a deliberate, permanent contrast with format-preserving codecs like `ooxml.js`'s own `packageCodec`. `pdfCodec` shares `z.codec()`'s *mechanism* (schema-validated both ways) but not that *guarantee* — wrapping this round trip in `z.codec()` validates the shape of what comes out, not its fidelity to what went in.
|
|
158
164
|
|
|
159
165
|
**Optional real-world corpus.** `test/corpus/` (gitignored, never committed) holds a `pnpm test:corpus` vitest project for manual conformance checking against real PDFs a hand-built fixture can't fully stand in for — a Word "Save as PDF", a PowerPoint "Save as PDF", a Chrome "Print to PDF", a LibreOffice export. It is not part of `pnpm test` and does not gate CI; drop files in locally before a significant parser change.
|
|
160
166
|
|
|
@@ -172,6 +178,8 @@ Commits follow Conventional Commits (`feat:`, `fix:`, `test:`, `chore:`, …), e
|
|
|
172
178
|
|
|
173
179
|
- [documents.js](https://github.com/ExaDev/documents.js) — the package this codec was extracted from, and its principal downstream consumer: docx/pptx/odt/odp/ods/odg ⇄ PDF conversion, and MathML formula rendering (its own `src/mathml/` typesetting engine feeds a real `MathBox` into this package's `writePdf({ formulas })` with zero cast — see [Architecture](#architecture)).
|
|
174
180
|
- [document-schema.js](https://github.com/ExaDev/document-schema.js) — the sibling package that owns `LayoutDocument` itself (the PDF-side pivot this codec reads into and writes from), and the canonical `ContentDocument` pivot the wider `documents.js`/`odf.js`/`ooxml.js` family shares.
|
|
181
|
+
- [qpdf](https://qpdf.sourceforge.io/) — the independent implementation that produces this package's encrypted-PDF test fixtures (`src/test-support/encrypted-pdfs.ts`, regenerated by `scripts/generate-encrypted-pdf-fixtures.mjs`). A build-time and test-time tool only, never a dependency of the package itself.
|
|
182
|
+
- The specifications `src/crypto/` implements, each cited in the module that implements it and checked against that specification's own published conformance vectors: [RFC 1321](https://www.rfc-editor.org/rfc/rfc1321) (MD5), [FIPS 180-4](https://csrc.nist.gov/pubs/fips/180-4/upd1/final) (SHA-256/384/512), [FIPS 197](https://csrc.nist.gov/pubs/fips/197/final) (AES), and [NIST SP 800-38A](https://csrc.nist.gov/pubs/sp/800/38/a/final) (CBC mode). The standard security handler that consumes them is ISO 32000-1 7.6, extended for revisions 5 and 6 by ISO 32000-2 7.6.4.3.
|
|
175
183
|
- [STIX Two Math](https://github.com/stipub/stixfonts) — the embedded math font `math-font.ts` parses and `writePdf({ formulas })` renders through, vendored at `assets/fonts/STIXTwoMath-Regular.otf` and embedded into `dist/` as a base64 string (`src/assets/stix-two-math-font.ts`, generated by `scripts/generate-math-font-asset.mjs`) rather than read from disk at runtime. Copyright 2001-2021 The STIX Fonts Project Authors, licensed [OFL-1.1](assets/fonts/OFL.txt) — see `assets/fonts/NOTICE.md` for the exact source commit and version this was vendored from.
|
|
176
184
|
|
|
177
185
|
## npm aliases
|
package/dist/content-write.cjs
CHANGED
|
@@ -5,7 +5,6 @@ const require_objects = require("./objects.cjs");
|
|
|
5
5
|
const require_matrix = require("./matrix.cjs");
|
|
6
6
|
const require_serialize = require("./serialize.cjs");
|
|
7
7
|
//#region src/content-write.ts
|
|
8
|
-
const BEZIER_KAPPA = .5522847498;
|
|
9
8
|
function writeRgbOperator(writer, color, operator) {
|
|
10
9
|
writer.writeAscii(`${require_serialize.formatNumber(color.r)} ${require_serialize.formatNumber(color.g)} ${require_serialize.formatNumber(color.b)} ${operator}\n`);
|
|
11
10
|
}
|
|
@@ -87,8 +86,8 @@ function writeEllipse(writer, item) {
|
|
|
87
86
|
const cy = item.yPt + item.heightPt / 2;
|
|
88
87
|
const rx = item.widthPt / 2;
|
|
89
88
|
const ry = item.heightPt / 2;
|
|
90
|
-
const kx = rx * BEZIER_KAPPA;
|
|
91
|
-
const ky = ry * BEZIER_KAPPA;
|
|
89
|
+
const kx = rx * require_matrix.BEZIER_KAPPA;
|
|
90
|
+
const ky = ry * require_matrix.BEZIER_KAPPA;
|
|
92
91
|
writer.writeAscii(`${formatPoint(cx + rx, cy)} m\n`);
|
|
93
92
|
writer.writeAscii(`${formatPoint(cx + rx, cy + ky)} ${formatPoint(cx + kx, cy + ry)} ${formatPoint(cx, cy + ry)} c\n`);
|
|
94
93
|
writer.writeAscii(`${formatPoint(cx - kx, cy + ry)} ${formatPoint(cx - rx, cy + ky)} ${formatPoint(cx - rx, cy)} c\n`);
|
package/dist/content-write.js
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import { o as encodeForShow } from "./afm-widths-Dxucrg7D.js";
|
|
2
2
|
import { ByteWriter } from "./bytes/writer.js";
|
|
3
3
|
import { pdfHexString } from "./objects.js";
|
|
4
|
-
import { multiplyMatrices, rotationMatrix, scaleMatrix, translationMatrix } from "./matrix.js";
|
|
4
|
+
import { BEZIER_KAPPA, multiplyMatrices, rotationMatrix, scaleMatrix, translationMatrix } from "./matrix.js";
|
|
5
5
|
import { formatNumber, writeObject } from "./serialize.js";
|
|
6
6
|
//#region src/content-write.ts
|
|
7
|
-
const BEZIER_KAPPA = .5522847498;
|
|
8
7
|
function writeRgbOperator(writer, color, operator) {
|
|
9
8
|
writer.writeAscii(`${formatNumber(color.r)} ${formatNumber(color.g)} ${formatNumber(color.b)} ${operator}\n`);
|
|
10
9
|
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region src/crypto/aes.ts
|
|
3
|
+
const AES_BLOCK_BYTES = 16;
|
|
4
|
+
const WORDS_PER_BLOCK = 4;
|
|
5
|
+
const GF_MODULUS = 283;
|
|
6
|
+
const AFFINE_CONSTANT = 99;
|
|
7
|
+
function xtime(a) {
|
|
8
|
+
const doubled = a << 1;
|
|
9
|
+
return (doubled & 256) !== 0 ? (doubled ^ GF_MODULUS) & 255 : doubled;
|
|
10
|
+
}
|
|
11
|
+
function gmul(a, b) {
|
|
12
|
+
let product = 0;
|
|
13
|
+
let left = a;
|
|
14
|
+
let right = b;
|
|
15
|
+
while (right !== 0) {
|
|
16
|
+
if ((right & 1) !== 0) product ^= left;
|
|
17
|
+
left = xtime(left);
|
|
18
|
+
right >>= 1;
|
|
19
|
+
}
|
|
20
|
+
return product & 255;
|
|
21
|
+
}
|
|
22
|
+
function rotl8(value, bits) {
|
|
23
|
+
return (value << bits | value >>> 8 - bits) & 255;
|
|
24
|
+
}
|
|
25
|
+
const { SBOX, INV_SBOX } = (() => {
|
|
26
|
+
const inverse = /* @__PURE__ */ new Uint8Array(256);
|
|
27
|
+
for (let a = 1; a < 256; a++) for (let b = 1; b < 256; b++) if (gmul(a, b) === 1) {
|
|
28
|
+
inverse[a] = b;
|
|
29
|
+
break;
|
|
30
|
+
}
|
|
31
|
+
const sbox = /* @__PURE__ */ new Uint8Array(256);
|
|
32
|
+
const invSbox = /* @__PURE__ */ new Uint8Array(256);
|
|
33
|
+
for (let i = 0; i < 256; i++) {
|
|
34
|
+
const b = inverse[i];
|
|
35
|
+
const s = (b ^ rotl8(b, 1) ^ rotl8(b, 2) ^ rotl8(b, 3) ^ rotl8(b, 4) ^ AFFINE_CONSTANT) & 255;
|
|
36
|
+
sbox[i] = s;
|
|
37
|
+
invSbox[s] = i;
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
SBOX: sbox,
|
|
41
|
+
INV_SBOX: invSbox
|
|
42
|
+
};
|
|
43
|
+
})();
|
|
44
|
+
function subWord(word) {
|
|
45
|
+
return (SBOX[word >>> 24 & 255] << 24 | SBOX[word >>> 16 & 255] << 16 | SBOX[word >>> 8 & 255] << 8 | SBOX[word & 255]) >>> 0;
|
|
46
|
+
}
|
|
47
|
+
function rotWord(word) {
|
|
48
|
+
return (word << 8 | word >>> 24) >>> 0;
|
|
49
|
+
}
|
|
50
|
+
function expandKey(key) {
|
|
51
|
+
if (key.length !== 16 && key.length !== 24 && key.length !== 32) throw new Error(`AES key must be 16, 24, or 32 bytes; got ${String(key.length)}`);
|
|
52
|
+
const nk = key.length / 4;
|
|
53
|
+
const rounds = nk + 6;
|
|
54
|
+
const words = new Uint32Array(WORDS_PER_BLOCK * (rounds + 1));
|
|
55
|
+
for (let i = 0; i < nk; i++) words[i] = (key[4 * i] << 24 | key[4 * i + 1] << 16 | key[4 * i + 2] << 8 | key[4 * i + 3]) >>> 0;
|
|
56
|
+
let rcon = 1;
|
|
57
|
+
for (let i = nk; i < words.length; i++) {
|
|
58
|
+
let temp = words[i - 1];
|
|
59
|
+
if (i % nk === 0) {
|
|
60
|
+
temp = (subWord(rotWord(temp)) ^ rcon << 24) >>> 0;
|
|
61
|
+
rcon = xtime(rcon);
|
|
62
|
+
} else if (nk > 6 && i % nk === 4) temp = subWord(temp);
|
|
63
|
+
words[i] = (words[i - nk] ^ temp) >>> 0;
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
words,
|
|
67
|
+
rounds
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function addRoundKey(state, words, round) {
|
|
71
|
+
for (let c = 0; c < WORDS_PER_BLOCK; c++) {
|
|
72
|
+
const word = words[round * WORDS_PER_BLOCK + c];
|
|
73
|
+
for (let r = 0; r < WORDS_PER_BLOCK; r++) state[4 * c + r] = state[4 * c + r] ^ word >>> 24 - r * 8 & 255;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function substituteBytes(state, table) {
|
|
77
|
+
for (let i = 0; i < 16; i++) state[i] = table[state[i]];
|
|
78
|
+
}
|
|
79
|
+
function shiftRows(state, direction) {
|
|
80
|
+
const source = Uint8Array.from(state);
|
|
81
|
+
for (let r = 1; r < WORDS_PER_BLOCK; r++) for (let c = 0; c < WORDS_PER_BLOCK; c++) state[r + 4 * c] = source[r + 4 * (((c + direction * r) % WORDS_PER_BLOCK + WORDS_PER_BLOCK) % WORDS_PER_BLOCK)];
|
|
82
|
+
}
|
|
83
|
+
function mixColumns(state, coefficients) {
|
|
84
|
+
const [k0, k1, k2, k3] = coefficients;
|
|
85
|
+
for (let c = 0; c < WORDS_PER_BLOCK; c++) {
|
|
86
|
+
const a0 = state[4 * c];
|
|
87
|
+
const a1 = state[4 * c + 1];
|
|
88
|
+
const a2 = state[4 * c + 2];
|
|
89
|
+
const a3 = state[4 * c + 3];
|
|
90
|
+
state[4 * c] = gmul(a0, k0) ^ gmul(a1, k1) ^ gmul(a2, k2) ^ gmul(a3, k3);
|
|
91
|
+
state[4 * c + 1] = gmul(a0, k3) ^ gmul(a1, k0) ^ gmul(a2, k1) ^ gmul(a3, k2);
|
|
92
|
+
state[4 * c + 2] = gmul(a0, k2) ^ gmul(a1, k3) ^ gmul(a2, k0) ^ gmul(a3, k1);
|
|
93
|
+
state[4 * c + 3] = gmul(a0, k1) ^ gmul(a1, k2) ^ gmul(a2, k3) ^ gmul(a3, k0);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const FORWARD_MIX = [
|
|
97
|
+
2,
|
|
98
|
+
3,
|
|
99
|
+
1,
|
|
100
|
+
1
|
|
101
|
+
];
|
|
102
|
+
const INVERSE_MIX = [
|
|
103
|
+
14,
|
|
104
|
+
11,
|
|
105
|
+
13,
|
|
106
|
+
9
|
|
107
|
+
];
|
|
108
|
+
function encryptBlock(state, key) {
|
|
109
|
+
addRoundKey(state, key.words, 0);
|
|
110
|
+
for (let round = 1; round < key.rounds; round++) {
|
|
111
|
+
substituteBytes(state, SBOX);
|
|
112
|
+
shiftRows(state, 1);
|
|
113
|
+
mixColumns(state, FORWARD_MIX);
|
|
114
|
+
addRoundKey(state, key.words, round);
|
|
115
|
+
}
|
|
116
|
+
substituteBytes(state, SBOX);
|
|
117
|
+
shiftRows(state, 1);
|
|
118
|
+
addRoundKey(state, key.words, key.rounds);
|
|
119
|
+
}
|
|
120
|
+
function decryptBlock(state, key) {
|
|
121
|
+
addRoundKey(state, key.words, key.rounds);
|
|
122
|
+
for (let round = key.rounds - 1; round >= 1; round--) {
|
|
123
|
+
shiftRows(state, -1);
|
|
124
|
+
substituteBytes(state, INV_SBOX);
|
|
125
|
+
addRoundKey(state, key.words, round);
|
|
126
|
+
mixColumns(state, INVERSE_MIX);
|
|
127
|
+
}
|
|
128
|
+
shiftRows(state, -1);
|
|
129
|
+
substituteBytes(state, INV_SBOX);
|
|
130
|
+
addRoundKey(state, key.words, 0);
|
|
131
|
+
}
|
|
132
|
+
function wholeBlockCount(byteLength) {
|
|
133
|
+
return Math.floor(byteLength / 16);
|
|
134
|
+
}
|
|
135
|
+
function aesCbcDecrypt(key, iv, data) {
|
|
136
|
+
const expanded = expandKey(key);
|
|
137
|
+
const blocks = wholeBlockCount(data.length);
|
|
138
|
+
const out = new Uint8Array(blocks * 16);
|
|
139
|
+
const chain = Uint8Array.from(iv.subarray(0, 16));
|
|
140
|
+
for (let b = 0; b < blocks; b++) {
|
|
141
|
+
const cipherBlock = data.subarray(b * 16, (b + 1) * 16);
|
|
142
|
+
const state = Uint8Array.from(cipherBlock);
|
|
143
|
+
decryptBlock(state, expanded);
|
|
144
|
+
for (let i = 0; i < 16; i++) out[b * 16 + i] = state[i] ^ chain[i];
|
|
145
|
+
chain.set(cipherBlock);
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
function aesCbcEncrypt(key, iv, data) {
|
|
150
|
+
const expanded = expandKey(key);
|
|
151
|
+
const blocks = wholeBlockCount(data.length);
|
|
152
|
+
const out = new Uint8Array(blocks * 16);
|
|
153
|
+
const chain = Uint8Array.from(iv.subarray(0, 16));
|
|
154
|
+
for (let b = 0; b < blocks; b++) {
|
|
155
|
+
const state = /* @__PURE__ */ new Uint8Array(16);
|
|
156
|
+
for (let i = 0; i < 16; i++) state[i] = data[b * 16 + i] ^ chain[i];
|
|
157
|
+
encryptBlock(state, expanded);
|
|
158
|
+
out.set(state, b * 16);
|
|
159
|
+
chain.set(state);
|
|
160
|
+
}
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
//#endregion
|
|
164
|
+
exports.AES_BLOCK_BYTES = AES_BLOCK_BYTES;
|
|
165
|
+
exports.aesCbcDecrypt = aesCbcDecrypt;
|
|
166
|
+
exports.aesCbcEncrypt = aesCbcEncrypt;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
//#region src/crypto/aes.d.ts
|
|
2
|
+
declare const AES_BLOCK_BYTES = 16;
|
|
3
|
+
declare function aesCbcDecrypt(key: Uint8Array<ArrayBuffer>, iv: Uint8Array<ArrayBuffer>, data: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer>;
|
|
4
|
+
declare function aesCbcEncrypt(key: Uint8Array<ArrayBuffer>, iv: Uint8Array<ArrayBuffer>, data: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer>;
|
|
5
|
+
//#endregion
|
|
6
|
+
export { AES_BLOCK_BYTES, aesCbcDecrypt, aesCbcEncrypt };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
//#region src/crypto/aes.d.ts
|
|
2
|
+
declare const AES_BLOCK_BYTES = 16;
|
|
3
|
+
declare function aesCbcDecrypt(key: Uint8Array<ArrayBuffer>, iv: Uint8Array<ArrayBuffer>, data: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer>;
|
|
4
|
+
declare function aesCbcEncrypt(key: Uint8Array<ArrayBuffer>, iv: Uint8Array<ArrayBuffer>, data: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer>;
|
|
5
|
+
//#endregion
|
|
6
|
+
export { AES_BLOCK_BYTES, aesCbcDecrypt, aesCbcEncrypt };
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
//#region src/crypto/aes.ts
|
|
2
|
+
const AES_BLOCK_BYTES = 16;
|
|
3
|
+
const WORDS_PER_BLOCK = 4;
|
|
4
|
+
const GF_MODULUS = 283;
|
|
5
|
+
const AFFINE_CONSTANT = 99;
|
|
6
|
+
function xtime(a) {
|
|
7
|
+
const doubled = a << 1;
|
|
8
|
+
return (doubled & 256) !== 0 ? (doubled ^ GF_MODULUS) & 255 : doubled;
|
|
9
|
+
}
|
|
10
|
+
function gmul(a, b) {
|
|
11
|
+
let product = 0;
|
|
12
|
+
let left = a;
|
|
13
|
+
let right = b;
|
|
14
|
+
while (right !== 0) {
|
|
15
|
+
if ((right & 1) !== 0) product ^= left;
|
|
16
|
+
left = xtime(left);
|
|
17
|
+
right >>= 1;
|
|
18
|
+
}
|
|
19
|
+
return product & 255;
|
|
20
|
+
}
|
|
21
|
+
function rotl8(value, bits) {
|
|
22
|
+
return (value << bits | value >>> 8 - bits) & 255;
|
|
23
|
+
}
|
|
24
|
+
const { SBOX, INV_SBOX } = (() => {
|
|
25
|
+
const inverse = /* @__PURE__ */ new Uint8Array(256);
|
|
26
|
+
for (let a = 1; a < 256; a++) for (let b = 1; b < 256; b++) if (gmul(a, b) === 1) {
|
|
27
|
+
inverse[a] = b;
|
|
28
|
+
break;
|
|
29
|
+
}
|
|
30
|
+
const sbox = /* @__PURE__ */ new Uint8Array(256);
|
|
31
|
+
const invSbox = /* @__PURE__ */ new Uint8Array(256);
|
|
32
|
+
for (let i = 0; i < 256; i++) {
|
|
33
|
+
const b = inverse[i];
|
|
34
|
+
const s = (b ^ rotl8(b, 1) ^ rotl8(b, 2) ^ rotl8(b, 3) ^ rotl8(b, 4) ^ AFFINE_CONSTANT) & 255;
|
|
35
|
+
sbox[i] = s;
|
|
36
|
+
invSbox[s] = i;
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
SBOX: sbox,
|
|
40
|
+
INV_SBOX: invSbox
|
|
41
|
+
};
|
|
42
|
+
})();
|
|
43
|
+
function subWord(word) {
|
|
44
|
+
return (SBOX[word >>> 24 & 255] << 24 | SBOX[word >>> 16 & 255] << 16 | SBOX[word >>> 8 & 255] << 8 | SBOX[word & 255]) >>> 0;
|
|
45
|
+
}
|
|
46
|
+
function rotWord(word) {
|
|
47
|
+
return (word << 8 | word >>> 24) >>> 0;
|
|
48
|
+
}
|
|
49
|
+
function expandKey(key) {
|
|
50
|
+
if (key.length !== 16 && key.length !== 24 && key.length !== 32) throw new Error(`AES key must be 16, 24, or 32 bytes; got ${String(key.length)}`);
|
|
51
|
+
const nk = key.length / 4;
|
|
52
|
+
const rounds = nk + 6;
|
|
53
|
+
const words = new Uint32Array(WORDS_PER_BLOCK * (rounds + 1));
|
|
54
|
+
for (let i = 0; i < nk; i++) words[i] = (key[4 * i] << 24 | key[4 * i + 1] << 16 | key[4 * i + 2] << 8 | key[4 * i + 3]) >>> 0;
|
|
55
|
+
let rcon = 1;
|
|
56
|
+
for (let i = nk; i < words.length; i++) {
|
|
57
|
+
let temp = words[i - 1];
|
|
58
|
+
if (i % nk === 0) {
|
|
59
|
+
temp = (subWord(rotWord(temp)) ^ rcon << 24) >>> 0;
|
|
60
|
+
rcon = xtime(rcon);
|
|
61
|
+
} else if (nk > 6 && i % nk === 4) temp = subWord(temp);
|
|
62
|
+
words[i] = (words[i - nk] ^ temp) >>> 0;
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
words,
|
|
66
|
+
rounds
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function addRoundKey(state, words, round) {
|
|
70
|
+
for (let c = 0; c < WORDS_PER_BLOCK; c++) {
|
|
71
|
+
const word = words[round * WORDS_PER_BLOCK + c];
|
|
72
|
+
for (let r = 0; r < WORDS_PER_BLOCK; r++) state[4 * c + r] = state[4 * c + r] ^ word >>> 24 - r * 8 & 255;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function substituteBytes(state, table) {
|
|
76
|
+
for (let i = 0; i < 16; i++) state[i] = table[state[i]];
|
|
77
|
+
}
|
|
78
|
+
function shiftRows(state, direction) {
|
|
79
|
+
const source = Uint8Array.from(state);
|
|
80
|
+
for (let r = 1; r < WORDS_PER_BLOCK; r++) for (let c = 0; c < WORDS_PER_BLOCK; c++) state[r + 4 * c] = source[r + 4 * (((c + direction * r) % WORDS_PER_BLOCK + WORDS_PER_BLOCK) % WORDS_PER_BLOCK)];
|
|
81
|
+
}
|
|
82
|
+
function mixColumns(state, coefficients) {
|
|
83
|
+
const [k0, k1, k2, k3] = coefficients;
|
|
84
|
+
for (let c = 0; c < WORDS_PER_BLOCK; c++) {
|
|
85
|
+
const a0 = state[4 * c];
|
|
86
|
+
const a1 = state[4 * c + 1];
|
|
87
|
+
const a2 = state[4 * c + 2];
|
|
88
|
+
const a3 = state[4 * c + 3];
|
|
89
|
+
state[4 * c] = gmul(a0, k0) ^ gmul(a1, k1) ^ gmul(a2, k2) ^ gmul(a3, k3);
|
|
90
|
+
state[4 * c + 1] = gmul(a0, k3) ^ gmul(a1, k0) ^ gmul(a2, k1) ^ gmul(a3, k2);
|
|
91
|
+
state[4 * c + 2] = gmul(a0, k2) ^ gmul(a1, k3) ^ gmul(a2, k0) ^ gmul(a3, k1);
|
|
92
|
+
state[4 * c + 3] = gmul(a0, k1) ^ gmul(a1, k2) ^ gmul(a2, k3) ^ gmul(a3, k0);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const FORWARD_MIX = [
|
|
96
|
+
2,
|
|
97
|
+
3,
|
|
98
|
+
1,
|
|
99
|
+
1
|
|
100
|
+
];
|
|
101
|
+
const INVERSE_MIX = [
|
|
102
|
+
14,
|
|
103
|
+
11,
|
|
104
|
+
13,
|
|
105
|
+
9
|
|
106
|
+
];
|
|
107
|
+
function encryptBlock(state, key) {
|
|
108
|
+
addRoundKey(state, key.words, 0);
|
|
109
|
+
for (let round = 1; round < key.rounds; round++) {
|
|
110
|
+
substituteBytes(state, SBOX);
|
|
111
|
+
shiftRows(state, 1);
|
|
112
|
+
mixColumns(state, FORWARD_MIX);
|
|
113
|
+
addRoundKey(state, key.words, round);
|
|
114
|
+
}
|
|
115
|
+
substituteBytes(state, SBOX);
|
|
116
|
+
shiftRows(state, 1);
|
|
117
|
+
addRoundKey(state, key.words, key.rounds);
|
|
118
|
+
}
|
|
119
|
+
function decryptBlock(state, key) {
|
|
120
|
+
addRoundKey(state, key.words, key.rounds);
|
|
121
|
+
for (let round = key.rounds - 1; round >= 1; round--) {
|
|
122
|
+
shiftRows(state, -1);
|
|
123
|
+
substituteBytes(state, INV_SBOX);
|
|
124
|
+
addRoundKey(state, key.words, round);
|
|
125
|
+
mixColumns(state, INVERSE_MIX);
|
|
126
|
+
}
|
|
127
|
+
shiftRows(state, -1);
|
|
128
|
+
substituteBytes(state, INV_SBOX);
|
|
129
|
+
addRoundKey(state, key.words, 0);
|
|
130
|
+
}
|
|
131
|
+
function wholeBlockCount(byteLength) {
|
|
132
|
+
return Math.floor(byteLength / 16);
|
|
133
|
+
}
|
|
134
|
+
function aesCbcDecrypt(key, iv, data) {
|
|
135
|
+
const expanded = expandKey(key);
|
|
136
|
+
const blocks = wholeBlockCount(data.length);
|
|
137
|
+
const out = new Uint8Array(blocks * 16);
|
|
138
|
+
const chain = Uint8Array.from(iv.subarray(0, 16));
|
|
139
|
+
for (let b = 0; b < blocks; b++) {
|
|
140
|
+
const cipherBlock = data.subarray(b * 16, (b + 1) * 16);
|
|
141
|
+
const state = Uint8Array.from(cipherBlock);
|
|
142
|
+
decryptBlock(state, expanded);
|
|
143
|
+
for (let i = 0; i < 16; i++) out[b * 16 + i] = state[i] ^ chain[i];
|
|
144
|
+
chain.set(cipherBlock);
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
function aesCbcEncrypt(key, iv, data) {
|
|
149
|
+
const expanded = expandKey(key);
|
|
150
|
+
const blocks = wholeBlockCount(data.length);
|
|
151
|
+
const out = new Uint8Array(blocks * 16);
|
|
152
|
+
const chain = Uint8Array.from(iv.subarray(0, 16));
|
|
153
|
+
for (let b = 0; b < blocks; b++) {
|
|
154
|
+
const state = /* @__PURE__ */ new Uint8Array(16);
|
|
155
|
+
for (let i = 0; i < 16; i++) state[i] = data[b * 16 + i] ^ chain[i];
|
|
156
|
+
encryptBlock(state, expanded);
|
|
157
|
+
out.set(state, b * 16);
|
|
158
|
+
chain.set(state);
|
|
159
|
+
}
|
|
160
|
+
return out;
|
|
161
|
+
}
|
|
162
|
+
//#endregion
|
|
163
|
+
export { AES_BLOCK_BYTES, aesCbcDecrypt, aesCbcEncrypt };
|