Dev.to Security 🔐 Cybersecurity 👁 2 📖 5 min read

How to Verify PDF Redactions Cannot Be Reversed (Canvas RGBA + %%EOF Audit in TypeScript)

Every few months, a high-profile court filing, FOIA release, or vendor contract leaks confidential data because someone "redacted" a PDF by drawing opaque black rectangles over sensitive text. To the human eye, the page

Every few months, a high-profile court filing, FOIA release, or vendor contract leaks confidential data because someone "redacted" a PDF by drawing opaque black rectangles over sensitive text. To the human eye, the page looks blacked out. Inside the PDF byte stream, the original characters are still sitting intact underneath the rectangle and can be extracted with Ctrl+A, Ctrl+C, or two lines of Python.

When we built the local redaction auditor for PDFFields (and our zero-permission Firefox Add-on on Mozilla Add-ons), we wanted a deterministic check that runs 100% inside the user's browser without ever uploading confidential PDFs to a server.

Here are the four concrete failure modes that make PDF redactions reversible, and the exact browser-local TypeScript techniques that detect and eliminate all four.

Failure Mode 1: Hidden Text Under Black Boxes (Canvas RGBA Luminance Audit)

Most broken redactions happen in Apple Preview, Word-to-PDF exports, or generic PDF annotators where a user draws a filled black rectangle or black highlighter over text instead of removing the underlying text operators (Tj / TJ).

Checking only vector annotation boxes misses painted path operators (re f) baked directly into the page content stream. A reliable way to catch both is combining pdfjs-dist text item bounding boxes with actual rendered pixel luminance on an offscreen HTML5 <canvas>:

export interface RedactionLeak {
  page: number;
  text: string;
  avgLuminance: number;
  bbox: { x: number; y: number; w: number; h: number };
}

export async function scanPageForDarkCoveredText(
  page: PDFPageProxy,
  pageNumber: number,
  scale = 1.5
): Promise<RedactionLeak[]> {
  const viewport = page.getViewport({ scale });
  const canvas = document.createElement('canvas');
  canvas.width = Math.ceil(viewport.width);
  canvas.height = Math.ceil(viewport.height);

  const ctx = canvas.getContext('2d', { willReadFrequently: true });
  if (!ctx) return [];

  await page.render({ canvasContext: ctx, viewport }).promise;
  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
  const textContent = await page.getTextContent();
  const leaks: RedactionLeak[] = [];

  for (const rawItem of textContent.items) {
    if (!('str' in rawItem) || !rawItem.str.trim()) continue;
    const tx = pdfjsLib.Util.transform(viewport.transform, rawItem.transform);
    const x = Math.max(0, Math.floor(tx[4]));
    const h = Math.max(6, Math.ceil(Math.hypot(tx[2], tx[3])));
    const y = Math.max(0, Math.floor(tx[5] - h));
    const w = Math.max(4, Math.ceil(rawItem.width * scale));

    // Sample pixel luminance across the rendered text bounding box
    let lumSum = 0;
    let samples = 0;
    const stepX = Math.max(1, Math.floor(w / 8));
    const stepY = Math.max(1, Math.floor(h / 4));

    for (let py = y; py < Math.min(canvas.height, y + h); py += stepY) {
      for (let px = x; px < Math.min(canvas.width, x + w); px += stepX) {
        const idx = (py * canvas.width + px) * 4;
        const lum = 0.2126 * imageData[idx] + 0.7152 * imageData[idx + 1] + 0.0722 * imageData[idx + 2];
        lumSum += lum;
        samples++;
      }
    }

    const avgLuminance = samples > 0 ? lumSum / samples : 255;
    // Standard dark ink on white paper averages > 180 luminance;
    // text buried under a solid dark redaction box averages < 45.
    if (samples > 0 && avgLuminance < 45) {
      leaks.push({
        page: pageNumber,
        text: rawItem.str.trim(),
        avgLuminance: Math.round(avgLuminance),
        bbox: { x, y, w, h }
      });
    }
  }
  return leaks;
}

Why this threshold works so cleanly in practice: normal black text printed on a white background leaves roughly 75% to 88% white background pixels inside its bounding box, producing an average luminance well above 170. When a solid black rectangle covers that text, almost every pixel inside the bounding box drops near 0, pushing average luminance below 45 (and white-on-black intentional headers can be filtered cleanly by comparing against page-wide dark banner bands).

Failure Mode 2: Unapplied /Subtype /Redact Annotations

In Adobe Acrobat and several enterprise editors, marking text for redaction creates a /Redact annotation dictionary on the page. Until the user explicitly clicks Apply Redactions, that annotation is only a visual overlay instruction. Anyone opening the file in a different viewer, or parsing page.getAnnotations(), can hide or strip the annotation and read the full text underneath:

const annotations = await page.getAnnotations();
const unappliedRedacts = annotations.filter(
  (annot) => annot.subtype === 'Redact' || annot.subtype === 'Square'
);

Flagging every /Subtype /Redact annotation immediately catches drafts that were saved and emailed before redactions were burned in.

Failure Mode 3: Incremental Save Revisions (%%EOF History)

ISO 32000 supports incremental updates so PDF editors can append modified objects to the end of a file instead of rewriting the entire file from scratch. Each incremental save appends a new cross-reference table and a new %%EOF marker.

If a tool saves a redacted page as an incremental update without rewriting and garbage-collecting the file, the prior unredacted stream can still exist in the earlier byte range of the .pdf file. Scanning the raw Uint8Array directly in the browser reveals multi-revision history in milliseconds:

export function countIncrementalRevisions(pdfBytes: Uint8Array): number {
  const text = new TextDecoder('latin1').decode(pdfBytes);
  const matches = text.match(/%%EOF/g);
  return matches ? matches.length : 0;
}

A freshly rewritten clean PDF contains exactly one %%EOF marker. Two or more %%EOF markers mean the file carries appended revision history that must be scrubbed before distribution.

Failure Mode 4: Hidden /Info and XMP Metadata Streams

Even when every redacted page is clean visually, PDF files routinely carry author names, original draft titles, internal client matter numbers, software toolchains, and edit timestamps inside the classic /Info dictionary and the XML /Metadata (XMP) packet. Inspecting pdfDoc.getMetadata() surfaces both dictionaries immediately.

The Only 100% Permanent Fix: 200 DPI Page Rasterization + Fresh Container Rebuild

Trying to surgically delete individual character glyphs from a complex PDF content stream is notoriously brittle (shared font subsets, clipped Form XObjects, overlapping kerning arrays, or Form /AcroForm widget appearance streams can survive partial deletion).

The deterministic way to guarantee a redacted page cannot be reversed is to:

  1. Render the finalized page with solid opaque black redaction masks onto a 200 DPI offscreen canvas.
  2. Encode the flattened pixels into a fresh image stream.
  3. Build a brand-new single-revision (1 %%EOF) PDF container with empty /Info metadata and zero /Metadata XMP packets.

Because the output page contains only flattened raster pixels, there is literally no hidden text layer, no unapplied /Redact annotation, and no incremental revision history left to recover.

Try It Locally (Zero Server Upload)

If you want to inspect a sensitive PDF right now without uploading it to a third-party server:

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.