fix(pdf): PNG gate inflates IDAT natively against the exact raw size, validates IHDR fields, refuses zero dimensions and interlace (UPNG inflateRaw spin)

This commit is contained in:
bchanot committed 2026-10-11 14:52:03 +02:00
1 parent 0ceb357b18
commit cb95627a11
4 files changed
+412 -76

No files matched your search

+7 -2
View File
@@ -14,9 +14,14 @@ function concat(chunks: Uint8Array[], total: number): Uint8Array {
return out
}
/** FlateDecode under the cap. Null on failure or when the cap is exceeded. */
/**
* FlateDecode (zlib framing) under `limit`, the attachment cap by default.
* Null on any failure (truncated or corrupt stream, trailing junk, bad
* checksum) or as soon as the output exceeds the limit.
*/
export async function inflateFlate(
bytes: Uint8Array,
limit: number = MAX_ATTACHMENT_BYTES,
): Promise<Uint8Array | null> {
if (typeof DecompressionStream === 'undefined') return null
try {
@@ -31,7 +36,7 @@ export async function inflateFlate(
const { done, value } = await reader.read()
if (done) break
total += value.byteLength
if (total > MAX_ATTACHMENT_BYTES) {
if (total > limit) {
await reader.cancel()
return null
}
+129 -20
View File
@@ -1,18 +1,27 @@
import type { PDFDocument, PDFImage } from 'pdf-lib'
import type { Branding, Credit, ImageAsset } from '@faunosteo/domain'
import { inflateFlate, MAX_ATTACHMENT_BYTES } from './attachment/inflate'
import type { ExportWarning, Rasterizer } from './types'
import { renderBrandingSvg } from './svg/view'
/**
* The branding images embedded once per document. A PNG is decoded from
* its base64 once its header and chunk list fit the pixel budget; an SVG is
* sanitised and rasterised at the view width. Each slot fails alone: the
* page prints the credit's fallback text instead and the export reports a
* `logo_failed` warning.
* its base64 once its header, chunk list and IDAT stream pass `pngIssue`;
* an SVG is sanitised and rasterised at the view width. Each slot fails
* alone: the page prints the credit's fallback text instead and the export
* reports a `logo_failed` warning.
*/
/** A logo PNG is at most 4096² pixels and 8192 px a side (STEP6 §15). */
export const PNG_CAPS = { side: 8192, pixels: 4096 * 4096 } as const
/**
* A logo PNG is at most 4096² pixels and 8192 px a side (STEP6 §15), and
* its raw (filtered, uncompressed) scanlines fit the attachment cap, the
* most the native inflater is allowed to produce.
*/
export const PNG_CAPS = {
side: 8192,
pixels: 4096 * 4096,
rawBytes: MAX_ATTACHMENT_BYTES,
} as const
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
/** A chunk is length (4), type (4), data (length), CRC (4). */
@@ -26,6 +35,7 @@ const chunkType = (name: string): number =>
[...name].reduce((acc, char) => acc * 256 + char.charCodeAt(0), 0)
const IHDR_TYPE = chunkType('IHDR')
const IDAT_TYPE = chunkType('IDAT')
const IEND_TYPE = chunkType('IEND')
/**
* The chunk types UPNG reads by fixed offsets or by declared length. A
@@ -49,7 +59,28 @@ const ALLOWED_CHUNKS = new Set(
].map(chunkType),
)
export type PngHeaderIssue = 'signature' | 'dimensions' | 'chunks'
/** Samples per pixel and the bit depths the PNG spec allows, by colour type. */
const CHANNELS: Record<number, number> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }
const DEPTHS: Record<number, readonly number[]> = {
0: [1, 2, 4, 8, 16],
2: [8, 16],
3: [1, 2, 4, 8],
4: [8, 16],
6: [8, 16],
}
export type PngIssue = 'signature' | 'dimensions' | 'ihdr' | 'chunks' | 'idat'
/** The 13 IHDR fields, read as announced. */
interface PngHeader {
width: number
height: number
depth: number
colourType: number
compression: number
filter: number
interlace: number
}
export type LogoSlot = Extract<ExportWarning, { kind: 'logo_failed' }>['slot']
@@ -68,25 +99,66 @@ export interface BrandingImages {
}
/**
* Why a PNG is refused before any decoding, or null when it fits the
* budget: the signature and a first IHDR chunk of 13 bytes must be there,
* the announced width × height must stay under `PNG_CAPS`, and the chunk
* list must hold only allowlisted types, none past the end of the buffer,
* closed by an `IEND` that ends the file. The decoder would otherwise
* allocate the bitmap of whatever size the last IHDR claims, or scan past
* the buffer for a NUL byte that is not there.
* Why a PNG is refused before UPNG sees it, or null when it may be decoded.
* In order: the signature and a first 13-byte IHDR (`signature`); the
* announced size under `PNG_CAPS` (`dimensions`); IHDR fields the spec
* allows, non-interlaced (`ihdr`); an allowlisted chunk list closed by an
* empty `IEND` (`chunks`); an IDAT stream the native inflater accepts and
* that yields exactly the raw scanline size (`idat`). UPNG's `inflateRaw`
* never checks its input bound, so a truncated or crafted stream makes it
* read past the buffer and never return; its bitmap is sized from whatever
* IHDR claims; and `nextZero` scans text chunks for a NUL that may be
* missing. Each check closes one of those paths.
*/
export function pngHeaderIssue(bytes: Uint8Array): PngHeaderIssue | null {
export async function pngIssue(bytes: Uint8Array): Promise<PngIssue | null> {
if (bytes.byteLength < IHDR_END) return 'signature'
if (PNG_SIGNATURE.some((byte, i) => bytes[i] !== byte)) return 'signature'
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
if (view.getUint32(8) !== IHDR_LENGTH) return 'signature'
if (view.getUint32(12) !== IHDR_TYPE) return 'signature'
const width = view.getUint32(16)
const height = view.getUint32(20)
const header = readHeader(view)
const headerProblem = headerIssue(header)
if (headerProblem) return headerProblem
const rawSize = expectedRawSize(header)
if (rawSize > PNG_CAPS.rawBytes) return 'dimensions'
return chunkListIssue(view) ?? idatIssue(view, rawSize)
}
function readHeader(view: DataView): PngHeader {
return {
width: view.getUint32(16),
height: view.getUint32(20),
depth: view.getUint8(24),
colourType: view.getUint8(25),
compression: view.getUint8(26),
filter: view.getUint8(27),
interlace: view.getUint8(28),
}
}
/**
* The size budget, then the IHDR fields: a side of 0 would give the page
* stream an Infinity scale, an unknown colour type or depth (255 at 4096²
* costs seconds of CPU in UPNG) has no raw size to check against, and an
* interlaced image is refused outright: no archived logo is interlaced and
* the Adam7 pass sizes are not worth computing here.
*/
function headerIssue(header: PngHeader): PngIssue | null {
const { width, height, depth, colourType } = header
if (width < 1 || height < 1) return 'dimensions'
if (width > PNG_CAPS.side || height > PNG_CAPS.side) return 'dimensions'
if (width * height > PNG_CAPS.pixels) return 'dimensions'
return chunkListIssue(view)
if (!DEPTHS[colourType]?.includes(depth)) return 'ihdr'
if (header.compression !== 0 || header.filter !== 0) return 'ihdr'
if (header.interlace !== 0) return 'ihdr'
return null
}
/** Non-interlaced raw size: each scanline is a filter byte plus its packed samples. */
function expectedRawSize(header: PngHeader): number {
const bitsPerPixel = CHANNELS[header.colourType]! * header.depth
const rowBytes = Math.ceil((header.width * bitsPerPixel) / 8) + 1
return rowBytes * header.height
}
/**
@@ -96,7 +168,7 @@ export function pngHeaderIssue(bytes: Uint8Array): PngHeaderIssue | null {
* `nextZero` forever, an unknown type), a declared length past the buffer,
* a truncated chunk head, a missing IEND or bytes after it are refused.
*/
function chunkListIssue(view: DataView): PngHeaderIssue | null {
function chunkListIssue(view: DataView): PngIssue | null {
let offset = IHDR_END
while (offset + CHUNK_HEAD <= view.byteLength) {
const length = view.getUint32(offset)
@@ -112,6 +184,43 @@ function chunkListIssue(view: DataView): PngHeaderIssue | null {
return 'chunks'
}
/** The IDAT payloads in file order, one zlib stream; the chunk list is already known sound. */
function idatPayload(view: DataView): Uint8Array {
const parts: Uint8Array[] = []
let total = 0
let offset = IHDR_END
while (offset + CHUNK_HEAD <= view.byteLength) {
const length = view.getUint32(offset)
if (view.getUint32(offset + 4) === IDAT_TYPE) {
const start = view.byteOffset + offset + CHUNK_HEAD
parts.push(new Uint8Array(view.buffer, start, length))
total += length
}
offset += CHUNK_OVERHEAD + length
}
const payload = new Uint8Array(total)
let at = 0
for (const part of parts) {
payload.set(part, at)
at += part.byteLength
}
return payload
}
/**
* Inflates the IDAT stream with the native, bounded inflater before UPNG's
* unbounded `inflateRaw` does: a truncated, corrupt or oversized stream, or
* one that does not yield exactly the raw scanline size, is refused.
*/
async function idatIssue(
view: DataView,
rawSize: number,
): Promise<PngIssue | null> {
const raw = await inflateFlate(idatPayload(view), rawSize)
if (!raw || raw.byteLength !== rawSize) return 'idat'
return null
}
function base64ToBytes(base64: string): Uint8Array {
const binary = atob(base64)
const bytes = new Uint8Array(binary.length)
@@ -126,7 +235,7 @@ async function embedImage(
): Promise<PDFImage> {
if (asset.kind === 'png') {
const bytes = base64ToBytes(asset.base64)
const issue = pngHeaderIssue(bytes)
const issue = await pngIssue(bytes)
if (issue) throw new Error(`png refused: ${issue}`)
return pdfDoc.embedPng(bytes)
}