OX ONEX PDF Engine
Code Analysis Report & Architecture Handbook

ONEX PDF Engine

Complete engineering walkthrough of ONEX: Chromium rendering paired with a zero-dependency TypeScript PDF byte engine, hardened for Indian SaaS, ERP, and Government compliance workflows.

Repository: github.com/BAHUBALISID/onex
Package: onex-pdf (Apache-2.0, Node >= 18)
Codebase: 15,639 lines TypeScript across 37 modules
Subpath Exports: 11 ESM + CJS bundles · 147 passing tests
Zero Native Addons Unicode 16 + Legacy Indic Fail-Closed SSRF Matrix Shipped: signPdf() Shipped: redactPdf() Shipped: diffPdfs() Shipped: renderVerified() Shipped: PDF/A-3b E-Invoice

1. Executive Summary

Most Node PDF tools pick one lane and ignore the other side of the problem. Wrappers around Puppeteer print HTML reasonably well, then leave you stranded the moment you need to strip tracking bytes, merge 20 files without duplicating embedded fonts, validate a PKCS#7 signature, or pull tabular line items back out of a vendor bill. Conversely, pure JavaScript PDF writers let you assemble pages by coordinate, yet break completely on Hindi conjuncts, Bengali matras, Tamil vowel ordering, Arabic right-to-left shaping, or modern CSS Grid invoices.

ONEX bridges both worlds in one package. The top half drives Chromium through playwright-core with automatic font discovery, multi-pass byte budgets, and table pagination fixes. The bottom half is a pure TypeScript PDF engine written without C++ bindings or WebAssembly binaries: it parses streams, packs object streams, deduplicates resources by semantic SHA-256 hash, validates PDF/A compliance, extracts invoice geometry, verifies and creates digital signatures, redacts sensitive fields from content streams, and compares PDF versions semantically.

What sets this codebase apart in the open-source JavaScript ecosystem is its focus on real Indian commercial and e-governance pain points alongside strict security defaults. Official GSTIN Mod-36 checksum validation, Kruti Dev and Chanakya legacy font decoders, 80mm thermal POS receipts, 200 KB portal size ceilings, fail-closed SSRF translation checks across NAT64 and 6to4 IPv6 gateways, and an explicit error code on every security boundary come together in a single self-contained codebase.

Metric Original Baseline (v1.3.1 Report) Current Repository Snapshot
Language & Build TypeScript, ESM + CJS dual build (esbuild), Node >= 18 TypeScript, 37 ESM files + 11 CJS bundles (esbuild), Node >= 18
Source Size 11,178 lines TypeScript across 30 files 15,639 lines TypeScript across 37 files in src/
Core Engine File src/index.ts (1,846 lines) src/index.ts (2,097 lines) + dedicated compliance & redact modules
Runtime Dependencies 1 package: playwright-core (never downloads browsers on install) 1 package: playwright-core (0 npm audit vulnerabilities)
Bundled Fonts 7 Noto TTF files (~2.2 MB): Devanagari (R/B), Bengali, Tamil, Arabic, Latin (R/B) 7 Noto TTF files bundled and resolved identically across ESM and CJS
Subpath Exports 10 subpath entry points 11 subpath entry points (added onex-pdf/redact alongside /compliance)
HTTP & MCP Surfaces 13 HTTP endpoints · 13 MCP tools 17 HTTP endpoints (1 health + 16 POST) · 18 stdio MCP tools
CLI & Tests ~20 commands · 12 vitest files (3,422 lines) 25 commands · 14 vitest files (4,135 lines, 147 passing tests)

2. Architecture & System Map

The project is organized into three deliberate layers so expensive parts stay out of your critical path until you actually need them:

Zone 1: Rendering Zone

Drives Chromium through Playwright, manages browser crashes via epoch counters, injects missing Noto script fallbacks, re-encodes oversized images within a rendered pixel budget, and produces raw PDF bytes from HTML or live URLs.

Zone 2: Pure-JS PDF Core

Operates strictly on PDF Buffers with zero native libraries. Handles parsing, classical and incremental xref chains, dual-layout serialization, resource deduplication, PKCS#7 signing and verification, true redaction, semantic diffs, and PDF/A enforcement.

Zone 3: Delivery Surfaces

Exposes identical core guarantees over four interfaces: an authenticated HTTP microservice, a path-confined stdio MCP server for AI agents, a multi-command CLI, and a 1-line drop-in Puppeteer facade.

Because delivery surfaces rely on a shared lazy-engine controller (src/engine/lazy-engine.ts), pure-JS operations such as onex merge, onex verify-signatures, onex redact, or onex diff never even launch Chromium. Browser startup only happens when HTML rendering enters the picture.

Figure 1: Live source lines of TypeScript across module groups (15,639 lines total). More than 60% of the repository is pure-JS PDF parsing, compliance, redaction, extraction, and verification logic rather than browser glue.

2.2 Render Pipeline: The 18-Stage Gauntlet

Every render executes through a deterministic sequence inside renderInternal() in src/index.ts followed by post-processing in toBuffer(). Order matters here because earlier mutations reshape inputs for downstream stages:

  1. Concurrency Gate: Enters through a semaphore limiter (default 4 parallel renders, queue capacity 100). Saturated queues fail immediately with ONEX_QUEUE_FULL; long waits expire with ONEX_QUEUE_TIMEOUT.
  2. Page Acquisition: Live interactive documents check their pooled page against the engine epoch; one-shot renders spin up a clean isolated browser context so storage and cookies never cross tenants.
  3. SSRF Re-check: URL documents re-run checkUrlAsync() right before navigation to narrow DNS rebinding windows.
  4. Legacy Normalization & Content Load: Raw HTML auto-converts Kruti Dev and Chanakya spans when requested (convertLegacyFonts defaulting to 'auto'), normalizes Puppeteer wait options (networkidle0/networkidle2), and sets document markup.
  5. Report Pagination CSS: When reportMode or avoidRowSplits is active, injects print stylesheet rules locking repeating headers (thead), footers (tfoot), and unbroken rows (tr).
  6. Selectors & Images Wait: Honors optional waitForSelector under security timeouts, then resolves pending images (waitForImages).
  7. Three-Stage Font Fallback: Checks static HTML, live computed document.body.innerText, and post-image DOM text. Pure Latin pages skip base64 injection altogether, saving ~1.9 MB of overhead while Devanagari, Bengali, Tamil, Arabic, and ₹ text pick up guaranteed font faces.
  8. Pixel-Budget Image Downsampling: Measures each image's rendered CSS box multiplied by DPI ratio and 1.25 headroom, converts opaque high-res photos to JPEG, keeps alpha transparency intact as PNG with SMask, applies BT.601 grayscale luma if enabled, and gracefully ignores CORS-tainted canvases.
  9. Single-Page & Thermal Geometry: Thermal presets (80mm and 58mm) turn on singlePage. ONEX injects temporary CSS to neutralize @page size constraints, sets viewport width to print width, waits one animation frame to measure exact scroll height, clamps to PDF spec's 14,400 pt ceiling, and restores viewport state.
  10. Print & Drift Retry: Calls Chromium print, quickly counts pages on latin1 bytes using regex instead of re-parsing the full DOM, and adjusts height up to 2 correction retries if Chromium page-rounded past 1 page.
  11. Security Ceiling & Teardown: Enforces maxPages (1000 default), closes temporary contexts inside finally, and frees the limiter slot.
  12. Post-Render Loop (toBuffer): Checks optional SHA-256 LRU cache (disabled for live/URL documents), runs optimization (default balanced), loops across up to 3 progressive quality passes if maxBytes is still exceeded (including re-trying after PDF/A wrapping), enforces PDF/A-1b, PDF/A-2b, or PDF/A-3b if requested, and caches deterministic outputs.

2.3 Two Lifecycles: One-Shot vs Live Session

One-shot calls (setContent or setURL) build an isolated context per render and burn it down right after printing. Nothing lingers in memory across API requests. Live sessions (goto, setContentLive, interactive typing or clicking) bind a keyed page object inside PagePool so double renders see your DOM state immediately—and ONEX deliberately disables LRU caching in live mode because mutated DOM state cannot be safely keyed from static input strings.

2.4 Four Delivery Surfaces, One Core Engine

Whether teams invoke ONEX directly in Node/TypeScript, run it inside Docker behind an API gateway over HTTP, wire it to coding agents via stdio MCP, or drop it into existing scripts through onex-pdf/puppeteer and the CLI, every surface funnels through the exact same validation, SSRF rules, optimizer, and compliance routines.

3. Feature-by-Feature Deep Analysis

3.1 Core Engine, Crash Recovery & Backpressure

Engine Lifecycle & Epoch Invalidation

Chromium crashes happen under heavy production PDF traffic. Rather than crashing your worker process or leaking orphaned promises, ONEX tracks two integer counters on ONEXEngine: epochValue bumps every time the browser launches or relaunches after disconnect, while relaunchCount records transparent recoveries. When a live session invokes any method after a crash, PagePool.acquire() detects the stale epoch immediately in O(1) time without walking active locks, allocates a clean page on the fresh browser, replays the document's recorded origin recipe (either last URL or HTML snapshot), and flips doc.wasRecovered = true so your application knows state was rebuilt.

Startup arguments pass through a strict denylist (FORBIDDEN_SWITCHES) splitting flags on = so disguised attempts like --no-sandbox=1 are rejected with ONEX_UNSAFE_BROWSER_ARG. Only root processes inside Ubuntu AppArmor user-namespace constraints can opt into allowInsecureSandboxForRoot: true—and non-root callers passing that flag fail closed with ONEX_INSECURE_SANDBOX_MISUSE because sandbox relaxation without necessity is a bug.

Live Automation & CSP-Safe Multi-Arg Handling

Playwright imposes strict element handle limits across multi-argument browser evaluations, and older wrappers fell back to in-page new Function() which crashes immediately on sites enforcing strict Content Security Policy or Trusted Types. ONEX bypasses both hazards by routing multi-argument calls directly through CDP Runtime.callFunctionOn and resolving mixed primitive/ElementHandle lists via a clean page-global registry keyed by Symbol.for('onex.handleBox') inside src/puppeteer/index.ts.

Bounded Worker Batching & Limiter

Calling engine.renderBatch() pulls work through a shared worker cursor clamped at Math.min(security.maxConcurrency, requested, jobs.length). Even if an application passes concurrency: 100, the engine security ceiling keeps concurrency bounded cleanly without pre-allocating a queue of pending closures for every single job.

3.2 Media Pipeline, Thermal Presets & Byte Budgets

Real Indian POS billing needs continuous long receipts without arbitrary A4 page cuts, whereas government tender uploads reject anything over 200 KB.

  • 80mm & 58mm Thermal Support: Widths (227 pt and 164 pt) automatically activate continuous height calculation with zero margins unless overridden.
  • Progressive maxBytes Passes: When an optimized document still sits over your target byte limit, ONEX drops back to source HTML and retries through three progressively leaner compression profiles: 125 DPI at 0.70 JPEG quality, 96 DPI at 0.54 quality, then 72 DPI grayscale with aggressive metadata/info stripping—stopping the moment the budget holds. Crucially, even if pdfA compliance runs afterward, a final tight pass respects the budget after wrapping ICC and XMP archival streams.
  • Alpha-Aware Re-Encoding: Scanning pixels after canvas readback solves an ugly real-world bug where transparent PNG signatures (from API endpoints that omit .png extensions) previously turned into solid black JPEG squares. Any image holding even one pixel with alpha below 255 stays PNG. Grayscale conversion uses standard BT.601 luminance weights (0.299R + 0.587G + 0.114B).
  • XSS-Safe Page Number Templates: Supplying custom footers via pageNumbers: { format } HTML-escapes every character first before swapping safe {page} and {total} placeholders into Chromium footer spans, whitelists color values, and clamps font sizes between 7 and 20 px.

3.3 Unicode 16 Pipeline & Legacy Hindi Conversion

Text diagnostics in src/unicode/ do not rely on V8's built-in Intl.Segmenter quirks; they ship tables built directly from Unicode 16.0 UCD data.

  • Script Detection: Frozen binary-searchable [lo, hi, scriptIndex] triples cover 168 scripts—including the seven newest Unicode 16 additions (Garay, Gurung Khema, Kirat Rai, Ol Onal, Sunuwar, Todhri, Tulu Tigalari)—plus UAX #24 run splitting and 22 right-to-left scripts.
  • Complete UAX #29 Graphemes: Handles GB3 through GB13 rules natively (Hangul composition chains, ZWJ emoji sequences with Extend lookbehind, odd/even regional indicator flags) using flat frozen typed tables for zero per-codepoint Map churn.
  • Kruti Dev & Chanakya Visual-to-Unicode Converter: Decades of older Hindi land records, gazettes, and court orders are stored in non-Unicode font byte mappings where vowel signs (short i matra) and half-ra rephs are ordered visually on screen rather than phonetically in memory. ONEX maps 104 Kruti Dev pairs and 56 Chanakya pairs greedy-longest-match-first, marks visual modifiers with temporary Private Use sentinel codes (U+E001, U+E002), walks halant consonant conjuncts to shift short-i and reph into phonetic order, applies cleanup ligature normalizations, and finishes in strict Unicode NFC—automatically rewriting CSS font-family attributes in HTML streams to Noto Sans Devanagari without corrupting inline script or style blocks.

3.4 Font Parser, Intelligence & Runtime Fallback

Reading raw font files purely in Node (`src/fonts/parser.ts`) extracts OpenType sfnt directory tables, UTF-16BE naming records, weight/italic OS/2 flags, cmap formats 4 and 12 (preferring full UCS-4 `(3, 10)` subtables and handling non-zero `idRangeOffset` tables correctly), and detects embedded Chromium color emoji tables (`CBDT`, `CBLC`, `COLR`, `CPAL`, `SVG`). `FontManager` deduplicates identical font binaries by SHA-256 hash and builds a sorted `Uint32Array` glyph census so `hasCodePoint()` runs in O(log n) with minimal garbage collection.

Inside browser pages, `runtime-fonts.ts` pairs bundled regional fonts with an inventive alias trick: registering Noto Sans a second time under the name `'ONEX Rupee'` restricted strictly via `unicode-range: U+20B9`. That ensures the Indian Rupee symbol renders cleanly on stripped Alpine Linux or minimal Docker containers while leaving existing invoice fonts (`Georgia`, `Inter`, `Roboto`) completely untouched on Latin text. Client-side DOM scanning applies `dir="auto"` and `unicode-bidi: plaintext` automatically whenever RTL runs appear, backed by a live `MutationObserver` for dynamically hydrated templates.

3.5 PDF Parser, Writer & Signature Guard

PDF files in the wild routinely violate textbook formatting rules, so ONEX's parser (`src/pdf/parser.ts`) trusts-but-verifies. Stream `/Length` integers are sanity-checked against the expected `endstream` offset—falling back to literal byte scanning when producers miscalculate lengths, retrying `FlateDecode` with off-by-one byte trimming, implementing Sub/Up/Average/Paeth PNG predictors, chasing classic xref and PDF 1.5+ xref `/Prev` chains with cycle guards, scanning the trailing 4,096 bytes for the latest `startxref` (critical for incrementally updated signed PDFs), and offering forensic `recoverByScan()` recovery when xref tables are corrupted.

For mutations that recreate documents cleanly, the standard writer uses dual-layout writing (object streams + `/W [1 4 2]` compressed xref streams vs classic tables, picking whichever yields fewer bytes) while preserving `/Type /Metadata` uncompressed to satisfy archival specs and copying `DCTDecode`/`JPXDecode` photo streams untouched. For signatures, `writePdfIncremental()` keeps every byte of the source file immutable, appending only delta objects and a chained `/Prev` xref table. Before full rewrites run, `assertNotSignedForMutation()` blocks optimization, merging, page extraction, watermarking, and PDF/A rewriting on signed files (including widget-only `/FT /Sig` annotations) unless you explicitly opt into `allowModifySigned: true`.

3.6 Four-Level Optimizer Matrix

Pipeline Stage none fast balanced (default) maximum
Reachability GC (DFS depth 100 from Root/Info) Yes Yes Yes Yes
Semantic Stream Deduplication (decoded SHA-256 + stripped dict) — — Yes Yes
Object Deduplication (3 fixed-point passes, protects page tree) — — Yes Yes
Strip Metadata / Info — Yes Yes Yes
Strip Page Thumbnails & Private PieceInfo — — — Yes
Object Stream Packing (ObjStm, 100 objects/container) — Yes Yes Yes
Zlib Deflate Level 6 6 6 9
Empirical Dual-Layout Selection (smallest bytes kept) — Yes Yes Yes

What makes stream deduplication unusually effective is hashing decompressed bytes plus dictionary keys minus /Length and /Filter. Identical font programs or ICC profiles encoded differently by separate producers collapse into a single shared object while preserving every character's searchability.

3.7 Pure-JS Merge, Split & Watermark

mergePdfs() guarantees zero cross-file object ID collisions by remapping every document cleanly into fresh slots starting after shared `/Catalog` and `/Pages` containers, materializing inherited MediaBox, CropBox, Resources, and Rotate properties directly onto leaf pages, then deduplicating shared font/image streams across merged inputs. watermarkPdf() wraps original page content inside isolated q ... Q graphics state boundaries, respects page rotation (0°, 90°, 180°, 270°), escapes literal delimiters safely to prevent content-stream injection, maps ₹ to Rs. cleanly for WinAnsi Helvetica compatibility, and rejects silent signature invalidation.

3.8 Verification & PDF/A Compliance Suite

Signature verification (`verifyPdfSignatures()`) walks both annotation widgets and top-level `/Type /Sig` dictionaries sorted cleanly in file offset order, checks `/ByteRange` structural bounds (confirming the gap matches the exact hex string of `/Contents`), reports trailing bytes appended outside the signature range, parses ASN.1 CMS `SignedData` across every `SignerInfo`, retags implicit `[0]` `signedAttrs` bytes to `0x31` `SET OF` per RFC 5652 before verifying RSA/ECDSA digests with timing-safe comparison, detects DocMDP `/P` permissions and RFC 3161 TSA timestamps, and supports verifying certificate chains against supplied `trustedCaPem` anchors plus certificate validity periods.

Archival tooling (`validatePdfA()` and `enforcePdfA()`) enforces strict `PDF/A-1b`, `PDF/A-2b`, and `PDF/A-3b` requirements: recursive dictionary scanning strips nested inline /OpenAction, /AA, JavaScript, Launch actions, external `/URI` links, and non-compliant transparency masks; writes compliant uncompressed UTF-8 XMP metadata packets; synthesizes a clean 5-tag sRGB IEC61966-2.1 ICC profile dynamically in 68 lines (avoiding third-party ICC copyright baggage); enforces classic PDF 1.4 xref syntax on `PDF/A-1b`; permits `/AFRelationship` XML attachments on `PDF/A-3b`; and validates embedded fonts strictly.

3.9 Inspection, Tables & GSTIN Checksum

Reading raw PDF text reliably is subtle because multi-byte fonts embed mixed 1-byte and 2-byte glyph codes inside content operators. `extractText()` pairs a `ToUnicode` CMap parser with a 1-byte vs 2-byte CID auto-detector that scores hits against actual code maps, handles PDF/UA `/ActualText` marked spans (crucial for emoji extraction), and formats Indic punctuation naturally.

Building structured tables on top (`extractTables()`) tracks full cm, Tm, and Td matrices, recurses into Form XObjects up to depth 8, treats large negative kerning gaps (>= 350/1000em) in TJ arrays as column split hints, clusters rows into aligned vertical columns from anchor headers without erasing blank cells, and merges multi-page ledger continuations by deduplicating repeated page headers. extractInvoiceData() matches priorities carefully so Sub Total lines never hijack Grand Total, parses CGST/SGST/IGST rates, and runs India's official Base-36 Luhn Mod-36 checksum via isValidGstin(). Alongside it, inspectScanQuality() separates searchable, scanned, hybrid, and blank pages, estimates per-page DPI, warns under 150 DPI, and reports 200 KB GovTech upload readiness.

3.10 Fail-Closed Security Architecture

Untrusted templates and external URLs go through multi-layer SSRF and filesystem defenses rarely seen inside PDF engines:

  • Full IPv4 & IPv6 Transition SSRF Blocking: Blocks RFC1918, loopback, link-local cloud metadata (`169.254.0.0/16`), CGNAT (`100.64.0.0/10`), ULA (`fc00::/7`), and recursively extracts embedded IPv4 addresses inside IPv4-compatible (`::/96`), IPv4-mapped (`::ffff:0:0/96`), NAT64 (`64:ff9b::/96`), and 6to4 (`2002::/16`) tunnels while stripping trailing dots and zone IDs.
  • DNS-Rebinding Defense: Resolves host A and AAAA records with a bounded cache before requests proceed.
  • Redirect-Hop Re-validation: Fetches sub-resources manually using maxRedirects: 0, checking up to 10 redirect hops against SSRF policy so an allowed public domain returning HTTP 302 to 169.254.169.254 gets cut off before Chromium connects.
  • Symlink-Safe Path Confinement: Resolves canonical ancestor paths with realpathSync and validates containment via path.relative, stopping sibling-prefix bypasses and symlink traversal even when output files do not exist on disk yet.
  • Cryptographic HTTP Auth & Slowloris Protections: Hashes API keys with SHA-256 before timingSafeEqual checks, destroys sockets instantly when payloads pass 20 MiB without draining attacker streams, enforces header/request timeouts, and preserves Retry-After: 5 on 503 backpressure.
Honest Security Residual Notes

No client-side control eliminates OS-level DNS TOCTOU races completely because Chromium maintains its own resolver cache beneath Playwright routing; for high-threat multi-tenant SaaS clusters, pair ONEX's SSRF guards with an egress firewall / metadata iptables block on the container network. Also note ONEX refuses decrypting `/Encrypt` PDFs intentionally rather than guessing passwords or silently dropping protection without user consent.

3.11 HTTP Microservice, MCP Server, CLI & Puppeteer Facade

All four interfaces now carry parity across both existing features and the newly shipped suite: 17 HTTP endpoints (`GET /health` + `POST /render`, `/optimize`, `/inspect`, `/tables`, `/scan-quality`, `/verify-signatures`, `/pdfa`, `/convert-legacy`, `/merge`, `/split`, `/watermark`, `/sign`, `/redact`, `/diff`, `/render-verified`, `/einvoice`), 18 path-confined stdio MCP tools for AI agents, 25 CLI commands with dedicated security exit code `3`, and `onex-pdf/puppeteer` forwarding thermal presets and ONEX optimizations transparently while isolating remote HTTP servers from local filesystem signing keys (`p12Path` is blocked on HTTP `/sign`, requiring inline P12/PEM credentials instead).

4. Overall Assessment: Strengths & Gaps

Stepping back, ONEX outperforms heavyweight browser wrappers on security and output size while outperforming pure-JS PDF assemblers on multilingual fidelity, analytics, and government compliance. Below is an honest accounting of where gaps stood at baseline and which high-severity priorities are now closed vs still queued for future polish:

Area / Gap Details & Tradeoff Severity Current Status
Digital Signing Sign, co-sign via incremental append, DocMDP, P12/PEM/callback, RFC 3161 TSA High Shipped (v1.5)
True Redaction Remove PII text/image operators + fail-closed post-redaction audit High Shipped (v1.5)
Semantic PDF Diff Word/layout/resource diffs + visual strikethrough/green highlight redlines Medium Shipped (v1.5)
Render Verification Round-trip audit + tamper-evident HMAC XMP manifest Medium Shipped (v1.5)
PDF/A-3 E-Invoice EN 16931 CII XML + ISO-18004 QR + India IRP JWT verification High Shipped (v1.5)
Signature Guard & Chains Widget-only `/FT /Sig` guard, all SignerInfos, chain/expiry/TSA checks Medium Closed in v1.5
maxBytes + pdfA Order Post-PDF/A budget re-check if combined with size caps Low Closed in v1.5
PDF Password Decrypt /Encrypt detected cleanly; RC4/AES object decryption not included High Explicit refusal (by design)
Font Subsetting on Fallback Fallback runtime injects whole TTF base64 (~330 KB on Devanagari); Chromium subsets printed PDFs automatically Medium Planned enhancement
AcroForm Field Merge Interactive non-signature form fields across merged files need /AcroForm stitching Low Planned enhancement

5. Five Next-Level Capabilities (Now Built Into ONEX)

All Five Report Proposals Are Now Implemented & Verified

Everything scoped in Chapter 5 of the deep-dive analysis is live in TypeScript across Node API, CLI, HTTP server, and MCP tools, covered by automated tests using real cryptographic keys, live Chromium renders, and mock TSA endpoints.

5.1 signPdf() — PAdES-Ready Digital Signing Suite

Why it matters: Verifying signatures only solves half of a government or ERP document workflow. Indian e-tenders, GST filings, court submissions, and EU eIDAS PAdES documents need authentic CMS detached signatures applied cleanly—including hardware USB eTokens, co-signing without breaking earlier signatures, DocMDP lock levels, and RFC 3161 trusted timestamps. Mainstream npm tools like pdf-lib left digital signing open as a stale issue for years, while smaller helpers fail on multiple co-signatures and timestamps.

How ONEX solves it: Uses a new writePdfIncremental() writer mode that preserves every byte of prior revisions untouched and chains a clean classic xref subsection with /Prev. Supports encrypted PKCS#12/PFX bundles (`parsePkcs12()` with OpenSSL PKCS8 + PBES2 decryption), PEM keys/certificates, and async external callback signers for USB PKCS#11 HSM tokens. Optionally fetches SSRF-checked RFC 3161 TSA tokens and attaches them inside `unsignedAttrs`, stamps visual signature badges via isolated Form XObjects, and closes a self-verifying loop with `verifyPdfSignatures()`.

import { signPdf, verifyPdfSignatures } from 'onex-pdf';

const signed = await signPdf(pdfBuffer, {
  signer: { p12Path: 'dsc-cert.p12', passphrase: 'secret' },
  reason: 'Authorised Signatory',
  location: 'New Delhi, IN',
  tsaUrl: 'https://timestamp.example.in',
  docMdp: 'formFillAndSign',
  appearance: { position: 'bottomRight', includeDate: true },
});

const audit = verifyPdfSignatures(signed, { trustedCaPem: rootCaPem, checkExpiry: true });

Expected audit result: audit.allValid === true with hasTimestamp === true, docMdpPermission === 2, and chainValid === true.

5.2 redactPdf() — True Redaction Engine (Self-Verified)

Why it matters: Drawing black rectangles over sensitive fields is one of the most common enterprise data-breach mistakes in PDF handling—anyone selecting text or running an extractor still pulls full Aadhaar numbers, PAN IDs, or bank account credentials out from underneath the rectangle.

How ONEX solves it: Reuses the CTM-aware content-stream tokenizer to inspect every text slice and image Do call across pages and Form XObjects. Built-in Indian PII recognizers detect Aadhaar (12-digit), PAN, checksum-validated GSTIN, +91 phone numbers, IFSC codes, email addresses, and Luhn-checked credit cards alongside custom search strings, regular expressions, and explicit pixel/point rectangles. Matched text operators are surgically stripped or split inside TJ arrays so surrounding non-sensitive text stays readable while offending glyph bytes disappear forever. Dropped image XObjects are pruned from page resources and swept by reachability GC, metadata is scrubbed, black burn boxes isolate cleanly inside q ... Q scopes, and—crucially—redactPdf() re-extracts text from the final file to verify zero leaks remain, throwing ONEX_REDACTION_VERIFICATION_FAILED if anything survives.

import { redactPdf } from 'onex-pdf';

const { bytes, report } = redactPdf(pdfBuffer, {
  detect: ['aadhaar', 'pan', 'gstin', 'phone', 'ifsc', 'email'],
  search: ['CONFIDENTIAL-PROJECT-X'],
  burnIn: true,
  scrubMetadata: true,
});

Returns clean scrubbed bytes plus report.verified === true and an empty report.leaks list (never leaks silent partial matches).

5.3 diffPdfs() — Semantic PDF Diff & Redline Output

Why it matters: When contracts, tender corrigendums, or revised quotes change between versions, pixel-based image comparisons require Poppler or native binaries and shout false alarms whenever pagination shifts by half a centimeter.

How ONEX solves it: Runs a three-layer pure TypeScript diff: word/char/line Myers LCS sequence diff on extracted runs, geometric coordinate comparison across extractPositionedText() bounding boxes to classify text that moved rather than vanished (blocksMoved), and structural diff across fonts, images, page counts, and metadata. Calling buildRedlinePdf() overlays non-destructive translucent green highlights and red strikethrough markers directly onto pages for instant human sign-off.

import { diffPdfs, buildRedlinePdf } from 'onex-pdf';

const diff = diffPdfs(oldContract, revisedContract, {
  granularity: 'word',
  ignore: { whitespace: true, metadata: false },
});

const reviewPdf = buildRedlinePdf(oldContract, revisedContract);

5.4 renderVerified() — Self-Auditing Render-Verify Loop

Why it matters: Generating financial PDFs relies on faith once templates leave your server—floating-point rounding glitches, hidden table truncation, or missing font glyphs fail silently unless a human QA engineer eyeballs every invoice. No mainstream package closes this loop automatically because rendering and extraction rarely share the same engine.

How ONEX solves it: engine.renderVerified() prints the HTML document, runs ONEX's own extractor right back over the output bytes, compares extracted grand totals, subtotals, tax totals, invoice numbers, GSTIN checksums, line-item sums, and required phrases against expectations, retries once conservatively if an async timing glitch occurred, throws ONEX_RENDER_VERIFICATION_FAILED on persistent mismatch, and stamps an HMAC-SHA256 tamper-evident manifest directly into the PDF's XMP metadata. Months later, verifyIntegrity() recomputes extracted content hashes and checks the HMAC signature without needing Chromium at all.

const result = await engine.renderVerified(invoiceData, html, {
  format: 'A4',
  hmacSecret: process.env.MANIFEST_SECRET,
  expectations: {
    grandTotal: invoiceData.grandTotal,
    gstin: invoiceData.sellerGstin,
    verifyLineItemSum: true,
  },
});

const status = verifyIntegrity(result.bytes, { hmacSecret: process.env.MANIFEST_SECRET });

5.5 PDF/A-3b & Hybrid E-Invoice Pack (CII XML + India IRP QR)

Why it matters: Global and Indian invoicing mandates demand two things inside one file: European EN 16931 ZUGFeRD / Factur-X systems require valid PDF/A-3b archives carrying embedded Cross-Industry Invoice XML attachments, while India GST e-invoicing adds cryptographically signed JWT QR payloads issued by NIC/IRP portals. Until now developers had to wire three disparate packages and hope nothing broke archival rules.

How ONEX solves it: Extends PDF/A support cleanly to PDF/A-3b with Catalog /AF and /AFRelationship streams, generates EN 16931 CII XML (`buildCiiXml()`), verifies signed RS256/ES256 IRP QR JWTs (`parseIndiaIrpQr()`), draws scannable crisp vector ISO-18004 QR SVG codes up to Version 40 without external libraries (`generateQrSvg()`), renders and bundles everything via engine.renderEInvoice(), and performs a final extraction round-trip check verifying the rendered invoice numbers, totals, and GSTINs match the embedded XML payload.

const einvoice = await engine.renderEInvoice(invoiceData, htmlTemplate, {
  cii: { profile: 'en16931' },
  indiaQr: {
    irpPayload: signedIrpJwt,
    publicKeyPem: nicPublicKeyPem,
    verifySignature: true,
  },
});

6. Delivery Strategy & Impact vs Effort Matrix

Looking back at how the original report mapped effort vs ecosystem differentiation, the quick wins reused existing extraction and validation primitives while incremental PDF writing formed the deepest structural moat—unlocking multi-signatures, DocMDP locks, and future interactive form extensions cleanly.

QUICK WINS (HIGH IMPACT, LOW EFFORT) STRATEGIC MOATS (COMPLEX + DEFENSIBLE) Implementation Effort (1 = Low, 5 = Deep Protocol Engineering) Market Differentiation 4. renderVerified() Loop (Shipped) 3. diffPdfs() Semantic Diff (Shipped) 2. redactPdf() PII Purge (Shipped) 5. PDF/A-3b E-Invoice + QR (Shipped) 1. signPdf() PAdES Suite (Shipped)
Figure 2: Impact vs effort positioning across all 5 capabilities—originally phased across 4–6 months, now delivered and tested together in the codebase.
Phase Capability Engineering Rationale Status
Phase 1 renderVerified() self-audit + HMAC manifest Fastest immediate trust loop reusing existing extractor and XMP metadata infrastructure Done
Phase 2 redactPdf() & diffPdfs() + Redline Built cleanly atop the CTM-aware tokenizer and graphics-state overlay utilities Done
Phase 3 signPdf() PAdES Suite + Incremental Writer Establishes append-only byte preservation, DER encoding, TSA timestamps, and DocMDP rules Done
Phase 4 PDF/A-3b + CII/Factur-X XML + India IRP QR Combines archival compliance, EU XML standards, and verified Indian GST QR pipelines Done

Appendix: Market Research & Competitive Evidence

Competitive positioning claims reviewed prior to building these features were verified against public package documentation and issue trackers:

Ecosystem Observation Public Source Reference
pdf-lib lacks native digital signature APIs (open request since 2019) github.com/Hopding/pdf-lib/issues/172 & pdf-lib.js.org API docs
pdf-lib lacks built-in encryption/decryption (third-party add-ons exist) github.com/Hopding/pdf-lib/issues/243 & pdf-lib-encrypt
pdf-lib omits text editing/removal APIs for surgical redaction npmjs.com/package/pdf-lib
True redaction + verification lived mainly inside paid commercial SDKs or minimal standalone wrappers docs.apryse.com/web/redaction/redaction & @liiift-studio/pdf-redact
Semantic JSON + redline PDF diffs on npm relied on native Poppler binaries or pixel diffs github.com/akotsin/pdf-pixel-diff & github.com/vslavik/diff-pdf
ZUGFeRD/Factur-X XML tools were standalone from HTML rendering and verification @lucaapp/zugferd-ts & github.com/jslno/node-zugferd
India IRP GST QR verifiers lacked unified PDF rendering and PDF/A-3b generation @financica/gst-einvoice-qr