SPB Git

Repository Public

sanitize-svg.ts 8.2 KB 143 lines typescript

1/**2 * SVG sanitiser. Uploaded or generated SVG markup never reaches a page: it is parsed here (htmlparser2, XML mode)3 * into a tree of whitelisted elements and attributes, and the renderer draws that tree with React elements.4 * Everything that can run code or fetch something is dropped: <script>, <foreignObject>, <style>, <use>, <image>,5 * <a>, event handlers, external references, data: URLs, javascript:, CSS url() other than a local #fragment.6 */7import { parseDocument } from "htmlparser2";8import { SVG_TAGS, type SvgNode } from "@/schema";910export const SVG_MAX_BYTES = 400 * 1024;11const MAX_CHILDREN = 400, MAX_TEXT = 2000, MAX_ATTR = 20000, MAX_DEPTH = 24, MAX_NODES = 6000;1213const TAGS: ReadonlySet<string> = new Set(SVG_TAGS);14const TEXT_PARENTS: ReadonlySet<string> = new Set(["text", "tspan", "title", "desc"]);1516/** Geometry and presentation attributes. Anything else is removed. */17export const SVG_ATTRS: ReadonlySet<string> = new Set([18  "id", "x", "y", "x1", "y1", "x2", "y2", "cx", "cy", "r", "rx", "ry", "fx", "fy", "d", "points", "width", "height", "viewBox",19  "preserveAspectRatio", "transform", "fill", "fill-opacity", "fill-rule", "stroke", "stroke-width", "stroke-opacity",20  "stroke-linecap", "stroke-linejoin", "stroke-dasharray", "stroke-dashoffset", "stroke-miterlimit", "opacity", "color",21  "font-family", "font-size", "font-weight", "font-style", "text-anchor", "dominant-baseline", "letter-spacing",22  "dx", "dy", "rotate", "textLength", "lengthAdjust", "offset", "stop-color", "stop-opacity", "gradientUnits",23  "gradientTransform", "spreadMethod", "clip-path", "clip-rule", "clipPathUnits", "href", "xlink:href", "style",24  "vector-effect", "paint-order", "pathLength", "role", "aria-label", "aria-hidden",25]);26/** Dropped without a note: they carry no behaviour and every exported SVG has them. */27const SILENT: ReadonlySet<string> = new Set(["xmlns", "xmlns:xlink", "version", "xml:space"]);2829/** CSS properties accepted inside a style attribute (presentation only). */30export const SVG_STYLE_PROPS: ReadonlySet<string> = new Set([31  "fill", "fill-opacity", "fill-rule", "stroke", "stroke-width", "stroke-opacity", "stroke-linecap", "stroke-linejoin",32  "stroke-dasharray", "stroke-dashoffset", "stroke-miterlimit", "opacity", "color", "font-family", "font-size", "font-weight",33  "font-style", "text-anchor", "dominant-baseline", "letter-spacing", "stop-color", "stop-opacity", "paint-order", "vector-effect",34]);3536const DANGEROUS = /javascript:|vbscript:|data:|expression\s*\(|@import|&#|\\[0-9a-f]/i;3738/**39 * Is this attribute value acceptable? Shared by the sanitiser (when markup comes in) and by the renderer40 * (re-checked when the tree is drawn, because a stored document could have been written by other means).41 */42export function safeSvgAttr(name: string, value: string): boolean {43  if (/^on/i.test(name) || !SVG_ATTRS.has(name) || value.length > MAX_ATTR) return false;44  const v = value.replace(/[\u0000- \u007f]+/g, "");45  if (DANGEROUS.test(v)) return false;46  if (name === "href" || name === "xlink:href") return /^#[A-Za-z_][\w.-]*$/.test(value.trim());47  // url() may only point to a fragment of the same drawing (gradients, clip paths).48  const urls = v.match(/url\(/gi)?.length ?? 0;49  if (urls > 0 && (name === "style" || (v.match(/url\(#[A-Za-z_][\w.-]*\)/g)?.length ?? 0) !== urls)) return false;50  return true;51}5253/** Declarations of a style attribute that are safe presentation properties; the rest is dropped. */54export function safeStyle(value: string): [string, string][] {55  const out: [string, string][] = [];56  for (const decl of value.split(";")) {57    const i = decl.indexOf(":");58    if (i < 1) continue;59    const prop = decl.slice(0, i).trim().toLowerCase(), val = decl.slice(i + 1).trim();60    if (!SVG_STYLE_PROPS.has(prop) || !val || /url\(|expression|@import|javascript:|[<>{}\\]/i.test(val)) continue;61    out.push([prop, val]);62  }63  return out;64}6566interface DomLike { type: string; name?: string; attribs?: Record<string, string>; children?: DomLike[]; data?: string }6768export type SanitizeResult = { ok: true; tree: SvgNode; removed: string[] } | { ok: false; error: string };6970export function sanitizeSvg(markup: string): SanitizeResult {71  if (typeof markup !== "string" || markup.trim() === "") return { ok: false, error: "empty SVG" };72  if (new TextEncoder().encode(markup).length > SVG_MAX_BYTES) return { ok: false, error: "SVG larger than 400 KB" };73  if (/<!ENTITY/i.test(markup)) return { ok: false, error: "SVG declares entities" };74  let doc: DomLike;75  try { doc = parseDocument(markup, { xmlMode: true, decodeEntities: true }) as unknown as DomLike; }76  catch (e) { return { ok: false, error: "SVG cannot be parsed: " + (e instanceof Error ? e.message : String(e)) }; }77  const roots = (doc.children ?? []).filter((c) => c.type === "tag");78  if (roots.length !== 1 || roots[0].name !== "svg") return { ok: false, error: "the document must have a single <svg> root" };7980  const removed: string[] = [];81  const note = (what: string) => { if (removed.length < 200 && !removed.includes(what)) removed.push(what); };82  let count = 0;8384  const convert = (el: DomLike, depth: number): SvgNode | null => {85    const tag = el.name ?? "";86    if (!TAGS.has(tag)) { note(`<${tag.slice(0, 40)}>`); return null; }87    if (depth > MAX_DEPTH || ++count > MAX_NODES) { note("too many nested elements"); return null; }88    const attrs: Record<string, string> = {};89    for (const [name, value] of Object.entries(el.attribs ?? {})) {90      if (SILENT.has(name)) continue;91      if (!/^[a-zA-Z][a-zA-Z0-9:-]{0,40}$/.test(name) || !safeSvgAttr(name, value)) { note(`${name.slice(0, 40)} attribute`); continue; }92      if (name === "style") {93        const kept = safeStyle(value);94        if (kept.length !== value.split(";").filter((d) => d.trim()).length) note("style declaration");95        if (kept.length) attrs.style = kept.map(([p, v]) => `${p}: ${v}`).join("; ");96        continue;97      }98      attrs[name === "xlink:href" ? "href" : name] = value;99    }100    const children: (SvgNode | string)[] = [];101    for (const child of el.children ?? []) {102      if (children.length >= MAX_CHILDREN) { note("too many children"); break; }103      if (child.type === "text") {104        const text = child.data ?? "";105        if (!TEXT_PARENTS.has(tag)) { if (text.trim()) note("stray text"); continue; }106        if (text.trim() === "" && !/^[  ]+$/.test(text)) continue;107        children.push(text.slice(0, MAX_TEXT));108      } else if (child.type === "tag" || child.type === "script" || child.type === "style") {109        const node = convert(child, depth + 1);110        if (node) children.push(node);111      } else if (child.type === "cdata") {112        if (TEXT_PARENTS.has(tag)) for (const c of child.children ?? []) if (c.type === "text" && c.data) children.push(c.data.slice(0, MAX_TEXT));113      } else if (child.type !== "comment") note(child.type);114    }115    return { tag: tag as SvgNode["tag"], attrs, children };116  };117118  const tree = convert(roots[0], 0);119  if (!tree) return { ok: false, error: "the <svg> root was rejected" };120  if (!tree.attrs.viewBox) {121    const w = parseFloat(tree.attrs.width ?? ""), h = parseFloat(tree.attrs.height ?? "");122    if (w > 0 && h > 0) tree.attrs.viewBox = `0 0 ${w} ${h}`;123  }124  return { ok: true, tree, removed };125}126127const escText = (s: string): string => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");128const escAttr = (s: string): string => escText(s).replace(/"/g, "&quot;");129130/** Tree → SVG markup (for download and round-trips). Applies the same checks as the renderer. */131export function svgTreeToMarkup(tree: SvgNode): string {132  const write = (node: SvgNode, root: boolean): string => {133    if (!TAGS.has(node.tag)) return "";134    const attrs = Object.entries(node.attrs).filter(([k, v]) => safeSvgAttr(k, v)).map(([k, v]) => {135      if (k === "style") { const kept = safeStyle(v); return kept.length ? ` style="${escAttr(kept.map(([p, val]) => `${p}: ${val}`).join("; "))}"` : ""; }136      return ` ${k}="${escAttr(v)}"`;137    }).join("");138    const inner = node.children.map((c) => (typeof c === "string" ? escText(c) : write(c, false))).join("");139    return `<${node.tag}${root ? ' xmlns="http://www.w3.org/2000/svg"' : ""}${attrs}${inner ? `>${inner}</${node.tag}>` : "/>"}`;140  };141  return write(tree, true);142}143
Files main
Menu

Theme