feat(pdf): @faunosteo/pdf engine — explicit inputs, envelope v1 attachment, layered reader, xmldom composition, allowlist SVG sanitiser, WinAnsi guard, rasterizer adapter; goldens reproduced
This commit is contained in:
1 parent
e7419cb4cb
commit
c17956031d
46 files changed
+4396
-1
No files matched your search
@@ -0,0 +1,37 @@
|
||||
import { DOMParser, XMLSerializer, type Element } from '@xmldom/xmldom'
|
||||
import { SvgRejectedError } from '../errors'
|
||||
|
||||
/**
|
||||
* SVG text in, DOM root out, with xmldom (one code path in Node and in the
|
||||
* browser). Entity declarations are refused before parsing; a parse error
|
||||
* is reported as a typed rejection and its message, which may echo the
|
||||
* input, is never logged.
|
||||
*/
|
||||
|
||||
const ENTITY_MARKUP = /<!(DOCTYPE|ENTITY)/i
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg'
|
||||
|
||||
function rejectOnError(level: 'warning' | 'error' | 'fatalError'): void {
|
||||
if (level !== 'warning') throw new SvgRejectedError('malformed')
|
||||
}
|
||||
|
||||
export function parseSvg(text: string): Element {
|
||||
if (ENTITY_MARKUP.test(text)) throw new SvgRejectedError('doctype')
|
||||
let root: Element | null
|
||||
try {
|
||||
const parser = new DOMParser({ onError: rejectOnError })
|
||||
root = parser.parseFromString(text, 'image/svg+xml').documentElement
|
||||
} catch (error) {
|
||||
if (error instanceof SvgRejectedError) throw error
|
||||
throw new SvgRejectedError('malformed')
|
||||
}
|
||||
if (!root || root.localName !== 'svg' || root.namespaceURI !== SVG_NS) {
|
||||
throw new SvgRejectedError('not_svg')
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
/** The root element alone: no XML declaration, as the app serialised it. */
|
||||
export function serializeSvg(root: Element): string {
|
||||
return new XMLSerializer().serializeToString(root)
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
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; 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).
|
||||
*/
|
||||
|
||||
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',
|
||||
])
|
||||
|
||||
const LOCAL_REFERENCE = /^#[A-Za-z_][\w.:-]*$/
|
||||
const URL_FUNCTION = /url\(\s*['"]?\s*(.?)/gi
|
||||
const STYLE_FORBIDDEN = /expression\(|@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())
|
||||
}
|
||||
|
||||
/** Whether an allowed attribute keeps its value, by name-specific rule. */
|
||||
function attributeAcceptable(name: string, value: string): boolean {
|
||||
if (!urlsAreLocal(value)) return false
|
||||
if (name === 'href' || name === 'xlink:href') return hrefIsLocal(value)
|
||||
if (name === 'style') return !STYLE_FORBIDDEN.test(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 }
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { Element } from '@xmldom/xmldom'
|
||||
import { composeViewSvg } from '@faunosteo/anatomy/render'
|
||||
import type { Observation, SheetSnapshot, SheetView } from '@faunosteo/domain'
|
||||
import { parseSvg, serializeSvg } from './parse'
|
||||
import { sanitizeSvgRoot } from './sanitize'
|
||||
|
||||
/**
|
||||
* The picture of one view of an observation: the snapshot's drawing,
|
||||
* sanitised, framed on the view and overlaid with the observation's zones
|
||||
* highlighted (accent fill, halo on the main view). The raster size follows
|
||||
* today's rule, width 1200 px and the view box aspect, with the aspect
|
||||
* clamped so an untrusted `viewBox` cannot request a huge canvas.
|
||||
*/
|
||||
|
||||
export const RASTER_WIDTH_PX = 1200
|
||||
const ASPECT_MIN = 0.2
|
||||
const ASPECT_MAX = 2.0
|
||||
const ASPECT_FALLBACK = 0.6
|
||||
|
||||
export interface RasterSize {
|
||||
widthPx: number
|
||||
heightPx: number
|
||||
}
|
||||
|
||||
export interface RenderedSvg {
|
||||
svg: string
|
||||
size: RasterSize
|
||||
}
|
||||
|
||||
/** Height over width of a `viewBox` value, or the fallback when unusable. */
|
||||
function aspectOf(viewBox: string | null): number {
|
||||
const parts = (viewBox ?? '')
|
||||
.trim()
|
||||
.split(/[\s,]+/)
|
||||
.map(Number)
|
||||
const [, , width, height] = parts
|
||||
if (parts.length !== 4 || !(width! > 0) || !(height! > 0)) {
|
||||
return ASPECT_FALLBACK
|
||||
}
|
||||
return height! / width!
|
||||
}
|
||||
|
||||
export function rasterSizeOf(viewBox: string | null): RasterSize {
|
||||
const aspect = Math.min(ASPECT_MAX, Math.max(ASPECT_MIN, aspectOf(viewBox)))
|
||||
return {
|
||||
widthPx: RASTER_WIDTH_PX,
|
||||
heightPx: Math.max(1, Math.round(RASTER_WIDTH_PX * aspect)),
|
||||
}
|
||||
}
|
||||
|
||||
/** The asset a view draws: its own, else the first up its parent chain. */
|
||||
export function assetIdOfView(
|
||||
view: SheetView,
|
||||
views: ReadonlyMap<string, SheetView>,
|
||||
): string | null {
|
||||
const visited = new Set<string>()
|
||||
let current: SheetView | undefined = view
|
||||
while (current && !visited.has(current.id)) {
|
||||
if (current.svg_asset_id !== null) return current.svg_asset_id
|
||||
visited.add(current.id)
|
||||
current =
|
||||
current.kind === 'detail' ? views.get(current.parent_view_id) : undefined
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function assetText(sheet: SheetSnapshot, view: SheetView): string {
|
||||
const views = new Map(sheet.document.views.map((v) => [v.id, v]))
|
||||
const assetId = assetIdOfView(view, views)
|
||||
const asset = sheet.assets.find((a) => a.svgAssetId === assetId)
|
||||
if (!asset) throw new Error(`view "${view.id}" reaches no asset`)
|
||||
return asset.svg
|
||||
}
|
||||
|
||||
/** Parse, sanitise: the only way an asset text becomes a tree here. */
|
||||
export function cleanSvgRoot(text: string): Element {
|
||||
const root = parseSvg(text)
|
||||
sanitizeSvgRoot(root)
|
||||
return root
|
||||
}
|
||||
|
||||
/** The view's drawing with the observation's zones of that view highlighted. */
|
||||
export function renderHighlightedView(
|
||||
sheet: SheetSnapshot,
|
||||
viewId: string,
|
||||
observation: Observation,
|
||||
): RenderedSvg {
|
||||
const view = sheet.document.views.find((v) => v.id === viewId)
|
||||
if (!view) throw new Error(`unknown view "${viewId}"`)
|
||||
const annotationIds = new Set(
|
||||
observation.zones
|
||||
.filter((zone) => zone.viewId === viewId)
|
||||
.map((zone) => zone.annotationId),
|
||||
)
|
||||
const root = cleanSvgRoot(assetText(sheet, view))
|
||||
composeViewSvg({
|
||||
root,
|
||||
document: sheet.document,
|
||||
viewId,
|
||||
highlight: { annotationIds, halo: view.kind === 'main' },
|
||||
})
|
||||
return {
|
||||
svg: serializeSvg(root),
|
||||
size: rasterSizeOf(root.getAttribute('viewBox')),
|
||||
}
|
||||
}
|
||||
|
||||
export function composeHighlightedViewSvg(
|
||||
sheet: SheetSnapshot,
|
||||
viewId: string,
|
||||
observation: Observation,
|
||||
): string {
|
||||
return renderHighlightedView(sheet, viewId, observation).svg
|
||||
}
|
||||
|
||||
/** A branding SVG made safe, with the raster size its own viewBox gives. */
|
||||
export function renderBrandingSvg(text: string): RenderedSvg {
|
||||
const root = cleanSvgRoot(text)
|
||||
return {
|
||||
svg: serializeSvg(root),
|
||||
size: rasterSizeOf(root.getAttribute('viewBox')),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user