fix(pdf): security hardening — hex-encoded link URIs, strict branding URL schema, branding and labels re-validated at export, PNG dimension budget, CSS escape and parenthesis rules in the sanitiser, finite raster size, file size checked before read

This commit is contained in:
bchanot committed 2026-10-11 13:54:18 +02:00
1 parent 4930704d8a
commit 1f417b21fd
12 files changed
+437 -25

No files matched your search

+3 -1
View File
@@ -8,7 +8,7 @@ import {
import AppHeader from '@/components/brand/AppHeader'
import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { importReportFromPdf, ImportError, MAX_PDF_BYTES } from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import { useSheet } from '@/sheets/useSheet'
import type { SheetIndex } from '@/services/sheetIndex'
@@ -77,6 +77,8 @@ export default function HomeRoute() {
/** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */
async function importFile(file: File, index: SheetIndex) {
// The engine refuses the same size; checking first keeps a huge file out of memory.
if (file.size > MAX_PDF_BYTES) throw new ImportError('invalid_pdf')
const bytes = new Uint8Array(await file.arrayBuffer())
const outcome = await importReportFromPdf(bytes, index.sheet.migrationMap)
const rebase = rebaseReportOnSheet(
@@ -23,7 +23,7 @@ import {
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type { ArchiveReadOutcome } from '@faunosteo/domain'
import HomeRoute from '@/app/routes/HomeRoute'
import { ImportError, importReportFromPdf } from '@/pdf/import'
import { ImportError, importReportFromPdf, MAX_PDF_BYTES } from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
@@ -72,7 +72,14 @@ function outcome(patch: {
}
}
async function mountAndPickPdf(): Promise<void> {
/** A 4-byte "%PDF" file; the import is mocked, the bytes only travel. */
function pdfFile(): File {
return new File([new Uint8Array([37, 80, 68, 70])], 'bilan.pdf', {
type: 'application/pdf',
})
}
async function mountAndPickPdf(file: File = pdfFile()): Promise<void> {
render(
<MemoryRouter initialEntries={['/']}>
<Routes>
@@ -84,9 +91,6 @@ async function mountAndPickPdf(): Promise<void> {
const button = screen.getByRole('button', { name: fr['home.import.cta'] })
await waitFor(() => expect(button).toBeEnabled())
const input = document.querySelector('input[type="file"]')!
const file = new File([new Uint8Array([37, 80, 68, 70])], 'bilan.pdf', {
type: 'application/pdf',
})
fireEvent.change(input, { target: { files: [file] } })
}
@@ -160,3 +164,18 @@ describe('HomeRoute import: error paths', () => {
expect(alertMock()).not.toHaveBeenCalled()
})
})
describe('HomeRoute import: size gate', () => {
it('refuses a file over MAX_PDF_BYTES before reading it: unreadable PDF message', async () => {
const file = pdfFile()
Object.defineProperty(file, 'size', { value: MAX_PDF_BYTES + 1 })
const read = vi.spyOn(file, 'arrayBuffer')
await mountAndPickPdf(file)
await waitFor(() => expect(errorText()).not.toBeNull())
expect(errorText()!.textContent).toBe(fr['home.import.error_invalid_pdf'])
expect(read).not.toHaveBeenCalled()
expect(importMock).not.toHaveBeenCalled()
expect(screen.queryByTestId('editor-route')).toBeNull()
expect(useReportStore.getState().report).toBeNull()
})
})
+29 -1
View File
@@ -161,6 +161,8 @@ Two operations are distinct:
| snapshot assets | ≤ 4, ≤ 2 MiB each, ≤ 6 MiB total |
| snapshot document | ≤ 64 views, ≤ 1,024 annotations, ≤ 8,192 finding nodes, depth ≤ 8, names ≤ 512 chars |
| branding | PNG base64 ≤ 512 KiB, SVG ≤ 256 KiB, http(s) URLs ≤ 2,048 chars |
| branding URL | `http(s)://` then printable ASCII only, without `"` `'` `(` `)` `<` `>` `\`, no space or control character |
| branding PNG | valid signature and IHDR, each side ≤ 8,192 px, ≤ 16,777,216 px (4096²) |
| report at export | ≤ 500 observations, ≤ 8 views per observation |
| SVG sanitiser | ≤ 20,000 elements, nesting ≤ 64, ≤ 256 `<use>`, blur `stdDeviation` ≤ 100 |
@@ -170,10 +172,36 @@ sanitised by allowlist (shapes, groups, gradients, the filter primitives the
drawings use, `clipPath`, `mask`, `switch`, `use`, `title`, `desc`; geometry,
presentation, gradient and filter attributes; `href` and `url()` only to a
`#fragment`; no `style` element, no `script`, `image`, `a`, `foreignObject`,
`text`, no event handler). The reference drawings pass unchanged (tested).
`text`, no event handler). An attribute value with a backslash is removed (a
CSS escape such as `u\72l(` would hide a reference), and a `style` or
presentation attribute may call no function other than `url(#…)`: `rgb(`,
`image-set(`, `expression(` and the like are removed with the attribute. The
reference drawings pass unchanged (tested).
The same caps are checked at export, so an export can never write a file its
own reader refuses.
The branding URL rule exists because a URL is written into every page's
link action: pdf-lib does not escape a literal string, so the engine writes
the URI as a hex string and the schema refuses the characters that could
close a literal. The export re-validates the branding and the labels it
receives (`ArchiveExportError('branding_invalid')` before any page is
drawn), even from an archive that passed the reader. A PNG logo whose header
is missing, wrong or over the pixel budget is never decoded: that slot alone
prints its fallback text and the export reports `logo_failed`.
### Known limits
- pdf-lib inflates PDF object streams without a cap when loading: a crafted
PDF of a few hundred KB can expand to hundreds of MB in the tab before the
attachment is even looked at. The 50 MiB file cap bounds the input, not
the expansion. Mitigation planned: parse in a Worker, or locate the
attachment without a full load.
- `<use>` expansion is bounded by the rasterizer (resvg refuses an
oversized tree), not by the sanitiser, which only counts the `<use>`
elements (≤ 256).
- Report v3 collections are not capped on read; the export refuses above
500 observations and 8 views per observation.
## Checking an archive against its migration
`pnpm report:compare <file.pdf | folder>...` reads the attachment of one or
+9 -1
View File
@@ -10,11 +10,19 @@ import { z } from 'zod'
const KIB = 1024
const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/
/**
* `http(s)://` then printable ASCII without `"`, `'`, `(`, `)`, `<`, `>`
* or `\`: the URL is written into PDF link actions and must never be able
* to close a string literal or carry a control character. Expressed as the
* allowed ranges of printable ASCII (0x21-0x7e) minus those seven.
*/
const HTTP_URL_PATTERN = /^https?:\/\/[!#-&*-;=?-[\]-~]+$/
const HttpUrlSchema = z
.string()
.max(2048)
.url()
.refine((url) => /^https?:\/\//i.test(url), 'http(s) URL expected')
.regex(HTTP_URL_PATTERN, 'http(s) URL expected')
export const ImageAssetSchema = z.discriminatedUnion('kind', [
z
@@ -97,6 +97,47 @@ describe('BrandingSchema', () => {
})
})
/** Closes a PDF `(` string literal and chains an action: must never reach the engine. */
const INJECTION_URL =
'https://a.example/) /Next << /S /JavaScript /JS (app.alert\\(1\\)) >> /Z ('
describe('BrandingSchema URLs', () => {
it.each([
'https://faunosteo.com',
'https://zenquality.fr',
'https://www.instagram.com/paws.iin.harmony',
'http://localhost:5173',
'https://x.test/a-b_c~d?e=1&f=2#frag',
`https://x.test/${'a'.repeat(2048 - 'https://x.test/'.length)}`,
])('accepts %s', (url) => {
const branding = { ...sampleBranding(), siteUrl: url }
expect(BrandingSchema.safeParse(branding).success).toBe(true)
})
it.each([
['a closing parenthesis', 'https://a.example/)'],
['an opening parenthesis', 'https://a.example/('],
['a PDF action injection', INJECTION_URL],
['a backslash', 'https://a.example/a\\b'],
['a space', 'https://a.example/a b'],
['a tab', 'https://a.example/a\tb'],
['a control character', 'https://a.example/a\u0001b'],
['DEL', 'https://a.example/a\u007fb'],
['an angle bracket', 'https://a.example/<x>'],
['a double quote', 'https://a.example/"x'],
['a single quote', "https://a.example/'x"],
['a non-ASCII character', 'https://a.example/é'],
['no host', 'https://'],
['a scheme in upper case', 'HTTPS://a.example/'],
])('rejects %s in the site URL and in a credit URL', (_name, url) => {
const site = { ...sampleBranding(), siteUrl: url }
expect(BrandingSchema.safeParse(site).success).toBe(false)
const base = sampleBranding()
const credit = { ...base, partner: { ...base.partner!, url } }
expect(BrandingSchema.safeParse(credit).success).toBe(false)
})
})
describe('PdfLabelSetSchema', () => {
it('lists 25 distinct keys and accepts a complete set in both locales', () => {
expect(PDF_LABEL_KEYS).toHaveLength(25)
+37 -4
View File
@@ -5,11 +5,21 @@ import { renderBrandingSvg } from './svg/view'
/**
* The branding images embedded once per document. A PNG is decoded from
* its base64; 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 fits 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]
const IHDR_TYPE = 0x49484452
const IHDR_END = 24
export type PngHeaderIssue = 'signature' | 'dimensions'
export type LogoSlot = Extract<ExportWarning, { kind: 'logo_failed' }>['slot']
export interface CreditAsset {
@@ -26,6 +36,24 @@ export interface BrandingImages {
partner: CreditAsset | null
}
/**
* Why a PNG is refused before any decoding, or null when its header fits
* the budget: the signature and the IHDR chunk must be there, and the
* announced width × height must stay under `PNG_CAPS`. The decoder would
* otherwise allocate the full bitmap of whatever size the header 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(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 null
}
function base64ToBytes(base64: string): Uint8Array {
const binary = atob(base64)
const bytes = new Uint8Array(binary.length)
@@ -38,7 +66,12 @@ async function embedImage(
asset: ImageAsset,
rasterizer: Rasterizer,
): Promise<PDFImage> {
if (asset.kind === 'png') return pdfDoc.embedPng(base64ToBytes(asset.base64))
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))
}
+2
View File
@@ -25,6 +25,8 @@ export type ArchiveExportErrorKind =
| 'snapshot_too_large'
| 'sheet_mismatch'
| 'too_many_pages'
/** The branding or the label set fails its schema (URLs included). */
| 'branding_invalid'
export class ArchiveExportError extends Error {
constructor(
+17
View File
@@ -1,9 +1,11 @@
import { PDFDocument } from 'pdf-lib'
import {
assertSnapshot,
BrandingSchema,
buildSheetIndex,
ENVELOPE_FORMAT,
ENVELOPE_VERSION,
PdfLabelSetSchema,
snapshotIndexSource,
SnapshotError,
type Report,
@@ -43,6 +45,20 @@ export const PAGE_CAPS = {
viewsPerObservation: 8,
} as const
/**
* Step 0: the branding and the labels pass their schemas again. They reach
* the engine from an archive or from the application and end up in link
* URIs and drawn text, so a caller cannot be trusted to have validated them.
*/
function assertBrandingAndLabels(input: ExportInput): void {
if (!BrandingSchema.safeParse(input.branding).success) {
throw new ArchiveExportError('branding_invalid', 'branding')
}
if (!PdfLabelSetSchema.safeParse(input.labels).success) {
throw new ArchiveExportError('branding_invalid', 'labels')
}
}
/** Step 1: the snapshot gate, with every asset accepted by the sanitiser. */
function checkedSnapshot(sheet: SheetSnapshot): SheetSnapshot {
let parsed: SheetSnapshot
@@ -161,6 +177,7 @@ async function drawPages(pages: Pages): Promise<void> {
export async function exportReportArchive(
input: ExportInput,
): Promise<ExportResult> {
assertBrandingAndLabels(input)
const sheet = checkedSnapshot(input.sheet)
assertExportable(input.report, sheet)
const envelope = buildEnvelope(input, sheet)
+9 -4
View File
@@ -1,4 +1,4 @@
import { PDFName, PDFArray, PDFString, type PDFPage } from 'pdf-lib'
import { PDFName, PDFHexString, type PDFPage } from 'pdf-lib'
export interface LinkRect {
x: number
@@ -8,14 +8,19 @@ export interface LinkRect {
url: string
}
/** A clickable `/Link` annotation opening `url`, appended to the page's Annots. */
/**
* A clickable `/Link` annotation opening `url`, appended to the page's
* Annots. The URI is written as a hex string: pdf-lib does not escape `(`,
* `)` or `\` in a literal string, so a hostile URL could otherwise close
* the literal and inject objects (a `/Next` JavaScript action, for one).
*/
export function addLinkAnnotation(page: PDFPage, rect: LinkRect): void {
const context = page.doc.context
const actionDict = context.obj({
Type: 'Action',
S: 'URI',
URI: PDFString.of(rect.url),
URI: PDFHexString.fromText(rect.url),
})
const annotDict = context.obj({
@@ -26,7 +31,7 @@ export function addLinkAnnotation(page: PDFPage, rect: LinkRect): void {
A: actionDict,
})
const annots = page.node.lookup(PDFName.of('Annots'), PDFArray)
const annots = page.node.Annots()
if (annots) {
annots.push(context.register(annotDict))
} else {
+50 -6
View File
@@ -5,10 +5,12 @@ import { SvgRejectedError } from '../errors'
* Allowlist sanitiser for the sheet drawings and the branding SVGs
* (STEP6 §15), on DOM Level 2 only. Elements and attributes outside the
* inventory of the real assets plus structural needs are removed with
* their subtree; `href` and `url(…)` must stay inside the document; a
* `style` attribute may carry no external reference; the halo filters are
* clamped. Element, nesting and `<use>` counters refuse an oversized tree.
* The caller learns what was removed (names only, never values).
* their subtree; `href` and `url(…)` must stay inside the document; no
* value carries a backslash (a CSS escape such as `u\72l(` would hide a
* reference from the rules below); a `style` or presentation attribute may
* call no function but `url(#…)`; the halo filters are clamped. Element,
* nesting and `<use>` counters refuse an oversized tree. The caller learns
* what was removed (names only, never values).
*/
export const SANITIZER_CAPS = {
@@ -126,9 +128,42 @@ const ALLOWED_ATTRIBUTES = new Set([
'style',
])
/** Attributes whose value is CSS-like: a function call there is a reference or an exploit. */
const PRESENTATION_ATTRIBUTES = new Set([
'fill',
'fill-opacity',
'fill-rule',
'stroke',
'stroke-width',
'stroke-linecap',
'stroke-linejoin',
'stroke-opacity',
'stroke-dasharray',
'stroke-dashoffset',
'stroke-miterlimit',
'opacity',
'filter',
'clip-path',
'clip-rule',
'mask',
'display',
'visibility',
'color',
'stop-color',
'stop-opacity',
'flood-color',
'flood-opacity',
'color-interpolation-filters',
'font-family',
'font-size',
'font-weight',
])
const LOCAL_REFERENCE = /^#[A-Za-z_][\w.:-]*$/
const URL_FUNCTION = /url\(\s*['"]?\s*(.?)/gi
const STYLE_FORBIDDEN = /expression\(|@import|javascript:|behavior:/i
const LOCAL_URL_OPEN = /url\(\s*['"]?\s*#/gi
const STYLE_FORBIDDEN =
/expression\(|image-set\(|@import|javascript:|behavior:/i
export interface SanitizeOutcome {
/** Removed element names and `element@attribute` pairs, in document order. */
@@ -157,11 +192,20 @@ function hrefIsLocal(value: string): boolean {
return LOCAL_REFERENCE.test(value.trim())
}
/** Any `(` left once the `url(#` openings are gone is a function we never allow. */
function callsOnlyLocalUrl(value: string): boolean {
return !value.replace(LOCAL_URL_OPEN, '').includes('(')
}
/** Whether an allowed attribute keeps its value, by name-specific rule. */
function attributeAcceptable(name: string, value: string): boolean {
if (value.includes('\\')) return false
if (!urlsAreLocal(value)) return false
if (name === 'href' || name === 'xlink:href') return hrefIsLocal(value)
if (name === 'style') return !STYLE_FORBIDDEN.test(value)
if (name === 'style') {
return !STYLE_FORBIDDEN.test(value) && callsOnlyLocalUrl(value)
}
if (PRESENTATION_ATTRIBUTES.has(name)) return callsOnlyLocalUrl(value)
return true
}
+11 -2
View File
@@ -27,6 +27,11 @@ export interface RenderedSvg {
size: RasterSize
}
/** A usable dimension: finite and strictly positive (`1e999` parses to Infinity). */
function isPositiveFinite(value: number | undefined): value is number {
return value !== undefined && Number.isFinite(value) && value > 0
}
/** Height over width of a `viewBox` value, or the fallback when unusable. */
function aspectOf(viewBox: string | null): number {
const parts = (viewBox ?? '')
@@ -34,10 +39,14 @@ function aspectOf(viewBox: string | null): number {
.split(/[\s,]+/)
.map(Number)
const [, , width, height] = parts
if (parts.length !== 4 || !(width! > 0) || !(height! > 0)) {
if (
parts.length !== 4 ||
!isPositiveFinite(width) ||
!isPositiveFinite(height)
) {
return ASPECT_FALLBACK
}
return height! / width!
return height / width
}
export function rasterSizeOf(viewBox: string | null): RasterSize {
+205 -1
View File
@@ -6,10 +6,12 @@
*/
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { beforeAll, describe, expect, it } from 'vitest'
import { beforeAll, describe, expect, it, vi } from 'vitest'
import { PDFDict, PDFDocument, PDFName } from 'pdf-lib'
import {
assertSnapshot,
SnapshotError,
type Branding,
type Report,
type ReportArchiveEnvelope,
type SheetSnapshot,
@@ -17,23 +19,29 @@ import {
import {
ArchiveExportError,
defaultPdfLabels,
exportFromEnvelope,
exportReportArchive,
readReportArchive,
type ExportInput,
type Rasterizer,
} from '../src'
import { inflateFlate } from '../src/attachment/inflate'
import { pngHeaderIssue } from '../src/branding'
import { SvgRejectedError } from '../src/errors'
import { addLinkAnnotation } from '../src/render/linkAnnotation'
import { parseSvg, serializeSvg } from '../src/svg/parse'
import { sanitizeSvgRoot } from '../src/svg/sanitize'
import { rasterSizeOf } from '../src/svg/view'
import { DRAFT_DIR, PUBLIC_DIR } from './helpers/draft'
import {
FIXED_EXPORTED_AT,
logosBranding,
nologosBranding,
ONE_PX_PNG,
rasterizerOf,
readLinks,
recordDrawing,
TWO_BY_ONE_PNG,
} from './helpers/goldens'
import { pdfWithAttachment } from './helpers/pdf'
import { loadGoldenReports, type GoldenReports } from './helpers/reports'
@@ -297,6 +305,46 @@ describe('hostile SVG assets', () => {
expect(serializeSvg(root)).toContain('stdDeviation="100 3"')
})
it('CSS escapes, image-set and function calls in style or presentation attributes are removed', () => {
const root = parseSvg(
wrap(
'<path d="M0 0" style="fill:u\\72l(http://evil/x)"/>' +
`<path d="M0 0" style='fill:image-set("http://evil/y")'/>` +
'<path d="M0 0" fill="u\\72l(http://evil/x)"/>' +
'<path d="M0 0" fill="rgb(1,2,3)"/>' +
'<path d="M0 0" id="a&#92;b"/>' +
'<path d="M0 0" fill="url(#ok)" transform="translate(1 2)"/>',
),
)
const { removed } = sanitizeSvgRoot(root)
expect(removed).toEqual([
'path@style',
'path@style',
'path@fill',
'path@fill',
'path@id',
])
const out = serializeSvg(root)
expect(out).not.toContain('evil')
expect(out).not.toContain('rgb(')
expect(out).toContain('fill="url(#ok)" transform="translate(1 2)"')
})
it('a non-finite or empty viewBox falls back to the 0.6 ratio, never NaN', () => {
for (const viewBox of [
'0 0 1e999 1e999',
'0 0 Infinity 10',
'0 0 NaN 10',
'0 0 0 10',
'0 0 -5 10',
'',
]) {
const size = rasterSizeOf(viewBox)
expect(size, viewBox).toEqual({ widthPx: 1200, heightPx: 720 })
expect(Number.isFinite(size.heightPx)).toBe(true)
}
})
it('<!ENTITY> and 257 <use> are refused: the export fails as snapshot_invalid', async () => {
const entity =
'<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY x "y">]>' + wrap('&x;')
@@ -409,3 +457,159 @@ describe('__proto__ ids and the inflate bomb', () => {
expect(await inflateFlate(bomb)).toBeNull()
})
})
// ---------------------------------------------------------------------------
// Branding: URL injection at the link sink, PNG budget
/** Closes the `/URI (` literal and chains a JavaScript action when written unescaped. */
const INJECTION_URL =
'https://a.example/) /Next << /S /JavaScript /JS (app.alert\\(1\\)) >> /Z ('
/** Every dictionary of the loaded file whose `/S` is `JavaScript`. */
function javaScriptActions(doc: PDFDocument): PDFDict[] {
return doc.context
.enumerateIndirectObjects()
.map(([, object]) => object)
.filter((object): object is PDFDict => object instanceof PDFDict)
.filter((dict) => dict.get(PDFName.of('S')) === PDFName.of('JavaScript'))
}
function reexportOptions() {
return {
locale: 'fr' as const,
rasterizer: rasterizerOf('nologos'),
exportedAt: FIXED_EXPORTED_AT,
}
}
describe('branding URL injection (HIGH)', () => {
it('the link sink alone keeps the whole URL inside the /URI string', async () => {
const doc = await PDFDocument.create()
const rect = { x: 0, y: 0, width: 10, height: 10, url: INJECTION_URL }
addLinkAnnotation(doc.addPage(), rect)
const bytes = await doc.save()
const raw = Buffer.from(bytes).toString('latin1')
expect(raw).not.toContain('/JavaScript')
expect(raw).not.toContain('/Next')
const reloaded = await PDFDocument.load(bytes)
expect(javaScriptActions(reloaded)).toEqual([])
const action = reloaded
.getPage(0)
.node.Annots()!
.lookup(0, PDFDict)
.lookup(PDFName.of('A'), PDFDict)
expect(action.has(PDFName.of('Next'))).toBe(false)
expect(action.get(PDFName.of('S'))).toBe(PDFName.of('URI'))
const [link] = await readLinks(bytes)
expect(link?.uri).toBe(INJECTION_URL)
})
it('exportFromEnvelope refuses the URL before drawing anything: branding_invalid', async () => {
const hostile = clone(envelope)
hostile.branding = {
...hostile.branding,
siteUrl: INJECTION_URL,
} as unknown as Branding
const recording = recordDrawing()
try {
const promise = exportFromEnvelope(hostile, reexportOptions())
await expect(promise).rejects.toBeInstanceOf(ArchiveExportError)
await expect(promise).rejects.toMatchObject({ kind: 'branding_invalid' })
expect(recording.texts).toEqual([])
expect(recording.images).toEqual([])
} finally {
recording.stop()
}
})
it('a credit URL with a parenthesis and a broken label set are refused the same way', async () => {
const credit = clone(envelope)
credit.branding.partner!.url = 'https://a.example/)'
await expect(
exportFromEnvelope(credit, reexportOptions()),
).rejects.toMatchObject({ kind: 'branding_invalid' })
const labels = clone(envelope)
delete (labels.labels.fr as Record<string, string>)['pdf.subject']
await expect(
exportFromEnvelope(labels, reexportOptions()),
).rejects.toMatchObject({ kind: 'branding_invalid' })
await expect(
exportFromEnvelope(clone(envelope), reexportOptions()),
).resolves.toMatchObject({ warnings: [] })
})
})
/** A PNG signature and an IHDR chunk announcing `width` × `height`, nothing after. */
function pngHeader(
width: number,
height: number,
signature = true,
): Uint8Array {
const bytes = new Uint8Array(33)
bytes.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
if (!signature) bytes[3] = 0x48
const view = new DataView(bytes.buffer)
view.setUint32(8, 13)
bytes.set([0x49, 0x48, 0x44, 0x52], 12)
view.setUint32(16, width)
view.setUint32(20, height)
return bytes
}
describe('PNG budget (MEDIUM)', () => {
it.each([
['8193 × 1 → dimensions', 8193, 1, 'dimensions'],
['1 × 8193 → dimensions', 1, 8193, 'dimensions'],
['4097 × 4096 (over 4096²) → dimensions', 4097, 4096, 'dimensions'],
['12000 × 12000 (144 Mpx) → dimensions', 12_000, 12_000, 'dimensions'],
['4096 × 4096 → accepted', 4096, 4096, null],
['8192 × 2048 → accepted', 8192, 2048, null],
])('%s', (_name, width, height, issue) => {
expect(pngHeaderIssue(pngHeader(width, height))).toBe(issue)
})
it('a wrong signature or a truncated header is refused; the real logos pass', () => {
expect(pngHeaderIssue(pngHeader(1, 1, false))).toBe('signature')
expect(pngHeaderIssue(pngHeader(1, 1).subarray(0, 20))).toBe('signature')
expect(pngHeaderIssue(new TextEncoder().encode('<svg/>'))).toBe('signature')
expect(pngHeaderIssue(ONE_PX_PNG)).toBeNull()
expect(pngHeaderIssue(TWO_BY_ONE_PNG)).toBeNull()
const logos = logosBranding()
for (const asset of [
logos.headerLogo,
logos.footerLogo,
logos.poweredBy!.logo,
]) {
if (asset?.kind !== 'png') throw new Error('png expected')
expect(pngHeaderIssue(Buffer.from(asset.base64, 'base64'))).toBeNull()
}
})
it('an oversized header logo fails alone with logo_failed and never reaches embedPng', async () => {
const branding = nologosBranding()
const huge = pngHeader(16_384, 16_384)
branding.headerLogo = {
kind: 'png',
base64: Buffer.from(huge).toString('base64'),
}
branding.footerLogo = {
kind: 'png',
base64: Buffer.from(ONE_PX_PNG).toString('base64'),
}
const embedPng = vi.spyOn(PDFDocument.prototype, 'embedPng')
try {
const { warnings } = await exportReportArchive({
...baseInput(golden.reports.demo, golden.snapshots.demo),
branding,
})
expect(warnings).toEqual([{ kind: 'logo_failed', slot: 'headerLogo' }])
const sizes = embedPng.mock.calls.map(
([png]) => (png as Uint8Array).byteLength,
)
expect(sizes).not.toContain(huge.byteLength)
expect(sizes).toContain(ONE_PX_PNG.byteLength)
} finally {
embedPng.mockRestore()
}
})
})