Files
faunosteo/packages/pdf/src/branding.ts
T

162 lines
5.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { PDFDocument, PDFImage } from 'pdf-lib'
import type { Branding, Credit, ImageAsset } from '@faunosteo/domain'
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.
*/
/** 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
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
/** A chunk is length (4), type (4), data (length), CRC (4). */
const CHUNK_HEAD = 8
const CHUNK_OVERHEAD = 12
const IHDR_LENGTH = 13
const IHDR_END = PNG_SIGNATURE.length + CHUNK_OVERHEAD + IHDR_LENGTH
/** The big-endian uint32 a four-letter chunk type reads as. */
const chunkType = (name: string): number =>
[...name].reduce((acc, char) => acc * 256 + char.charCodeAt(0), 0)
const IHDR_TYPE = chunkType('IHDR')
const IEND_TYPE = chunkType('IEND')
/** A second IHDR resizes the decoder's buffer; APNG frames are not a logo. */
const FORBIDDEN_CHUNKS = new Set(
['IHDR', 'acTL', 'fcTL', 'fdAT'].map(chunkType),
)
export type PngHeaderIssue = 'signature' | 'dimensions' | 'chunks'
export type LogoSlot = Extract<ExportWarning, { kind: 'logo_failed' }>['slot']
export interface CreditAsset {
image: PDFImage | null
url: string
fallbackText: string
}
export interface BrandingImages {
siteUrl: string
header: PDFImage | null
footer: PDFImage | null
poweredBy: CreditAsset | null
partner: CreditAsset | null
}
/**
* 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 no second IHDR, no APNG chunk and no length past the end
* of the buffer. The decoder would otherwise allocate the full bitmap of
* whatever size the last IHDR claims.
*/
export function pngHeaderIssue(bytes: Uint8Array): PngHeaderIssue | 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)
if (width > PNG_CAPS.side || height > PNG_CAPS.side) return 'dimensions'
if (width * height > PNG_CAPS.pixels) return 'dimensions'
return chunkListIssue(view)
}
/**
* Walks the chunks after the first IHDR until `IEND` or the end of the
* buffer. UPNG applies every IHDR it meets and sizes its buffer from the
* last one, so the first header alone proves nothing; a declared length
* that overruns the buffer, or a truncated chunk head, is refused as well.
*/
function chunkListIssue(view: DataView): PngHeaderIssue | null {
let offset = IHDR_END
while (offset < view.byteLength) {
if (offset + CHUNK_HEAD > view.byteLength) return 'chunks'
const length = view.getUint32(offset)
const type = view.getUint32(offset + 4)
if (offset + CHUNK_OVERHEAD + length > view.byteLength) return 'chunks'
if (type === IEND_TYPE) return null
if (FORBIDDEN_CHUNKS.has(type)) return 'chunks'
offset += CHUNK_OVERHEAD + length
}
return null
}
function base64ToBytes(base64: string): Uint8Array {
const binary = atob(base64)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)
return bytes
}
async function embedImage(
pdfDoc: PDFDocument,
asset: ImageAsset,
rasterizer: Rasterizer,
): Promise<PDFImage> {
if (asset.kind === 'png') {
const bytes = base64ToBytes(asset.base64)
const issue = pngHeaderIssue(bytes)
if (issue) throw new Error(`png refused: ${issue}`)
return pdfDoc.embedPng(bytes)
}
const { svg, size } = renderBrandingSvg(asset.svg)
return pdfDoc.embedPng(await rasterizer(svg, size))
}
interface Embedder {
pdfDoc: PDFDocument
rasterizer: Rasterizer
warnings: ExportWarning[]
}
async function embedSlot(
embedder: Embedder,
slot: LogoSlot,
asset: ImageAsset | null,
): Promise<PDFImage | null> {
if (!asset) return null
try {
return await embedImage(embedder.pdfDoc, asset, embedder.rasterizer)
} catch {
embedder.warnings.push({ kind: 'logo_failed', slot })
return null
}
}
async function embedCredit(
embedder: Embedder,
slot: LogoSlot,
credit: Credit | null,
): Promise<CreditAsset | null> {
if (!credit) return null
return {
image: await embedSlot(embedder, slot, credit.logo),
url: credit.url,
fallbackText: credit.fallbackText,
}
}
/** Embeds the four slots in a fixed order: header, footer, powered-by, partner. */
export async function embedBranding(
embedder: Embedder,
branding: Branding,
): Promise<BrandingImages> {
return {
siteUrl: branding.siteUrl,
header: await embedSlot(embedder, 'headerLogo', branding.headerLogo),
footer: await embedSlot(embedder, 'footerLogo', branding.footerLogo),
poweredBy: await embedCredit(embedder, 'poweredBy', branding.poweredBy),
partner: await embedCredit(embedder, 'partner', branding.partner),
}
}