Files
faunosteo/packages/pdf/src/svg/sanitize.ts
T

282 lines
6.6 KiB
TypeScript

import type { Attr, Element, Node } from '@xmldom/xmldom'
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; 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 = {
elements: 20_000,
depth: 64,
uses: 256,
stdDeviation: 100,
} as const
const ALLOWED_ELEMENTS = new Set([
'svg',
'g',
'path',
'circle',
'ellipse',
'rect',
'line',
'polyline',
'polygon',
'defs',
'linearGradient',
'radialGradient',
'stop',
'filter',
'feGaussianBlur',
'feMerge',
'feMergeNode',
'feOffset',
'feFlood',
'feComposite',
'feBlend',
'feColorMatrix',
'clipPath',
'mask',
'title',
'desc',
'switch',
'use',
])
const ALLOWED_ATTRIBUTES = new Set([
'id',
'class',
'd',
'cx',
'cy',
'r',
'rx',
'ry',
'x',
'y',
'x1',
'y1',
'x2',
'y2',
'dx',
'dy',
'width',
'height',
'points',
'transform',
'viewBox',
'version',
'preserveAspectRatio',
'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',
'gradientUnits',
'gradientTransform',
'spreadMethod',
'offset',
'stop-color',
'stop-opacity',
'stdDeviation',
'in',
'in2',
'result',
'mode',
'operator',
'k1',
'k2',
'k3',
'k4',
'flood-color',
'flood-opacity',
'type',
'values',
'color-interpolation-filters',
'filterUnits',
'primitiveUnits',
'systemLanguage',
'font-family',
'font-size',
'font-weight',
'xmlns',
'xmlns:xlink',
'xlink:href',
'href',
'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 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. */
removed: string[]
}
const ELEMENT_NODE = 1
function isElement(node: Node): node is Element {
return node.nodeType === ELEMENT_NODE
}
function elementChildren(node: Node): Element[] {
return Array.from(node.childNodes).filter(isElement)
}
/** Every `url(` in the value must point inside the document (`url(#…)`). */
function urlsAreLocal(value: string): boolean {
for (const match of value.matchAll(URL_FUNCTION)) {
if (match[1] !== '#') return false
}
return true
}
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) && callsOnlyLocalUrl(value)
}
if (PRESENTATION_ATTRIBUTES.has(name)) return callsOnlyLocalUrl(value)
return true
}
/** Clamps every number of a `stdDeviation` list; rewrites only when needed. */
function clampStdDeviation(element: Element): void {
const raw = element.getAttribute('stdDeviation')
if (raw === null) return
const numbers = raw
.trim()
.split(/[\s,]+/)
.map(Number)
if (numbers.some(Number.isNaN)) {
element.removeAttribute('stdDeviation')
return
}
if (numbers.every((n) => n <= SANITIZER_CAPS.stdDeviation)) return
const clamped = numbers.map((n) => Math.min(n, SANITIZER_CAPS.stdDeviation))
element.setAttribute('stdDeviation', clamped.join(' '))
}
function sanitizeAttributes(element: Element, removed: string[]): void {
const attributes: Attr[] = Array.from(element.attributes)
for (const attribute of attributes) {
const { name, value } = attribute
const keep =
ALLOWED_ATTRIBUTES.has(name) && attributeAcceptable(name, value)
if (keep) continue
element.removeAttribute(name)
removed.push(`${element.tagName}@${name}`)
}
clampStdDeviation(element)
}
interface Walk {
removed: string[]
elements: number
uses: number
}
function visit(element: Element, depth: number, walk: Walk): void {
walk.elements += 1
if (walk.elements > SANITIZER_CAPS.elements) {
throw new SvgRejectedError('too_many_elements')
}
if (depth > SANITIZER_CAPS.depth) throw new SvgRejectedError('too_deep')
if (element.tagName === 'use') {
walk.uses += 1
if (walk.uses > SANITIZER_CAPS.uses) {
throw new SvgRejectedError('too_many_uses')
}
}
sanitizeAttributes(element, walk.removed)
for (const child of elementChildren(element)) {
if (ALLOWED_ELEMENTS.has(child.tagName)) {
visit(child, depth + 1, walk)
} else {
element.removeChild(child)
walk.removed.push(child.tagName)
}
}
}
/**
* Sanitises the tree under `root` in place. Throws SvgRejectedError when a
* counter cap is exceeded; the tree is then unusable and the caller drops
* it. Returns the names of what was removed (empty on the real assets).
*/
export function sanitizeSvgRoot(root: Element): SanitizeOutcome {
if (root.tagName !== 'svg') throw new SvgRejectedError('not_svg')
const walk: Walk = { removed: [], elements: 0, uses: 0 }
visit(root, 1, walk)
return { removed: walk.removed }
}