How to Sanitize SVG: An Allowlist Tested on 12 Payloads
A regex that strips <script> and on…= blocked 5 of the 12 payloads below and left 6 still live. An allowlist that parses the file as XML, walks the tree and keeps only known elements and attributes blocked all 11 that could be parsed — and on a real 890-byte Figma icon it cost 27 bytes and 0 of 14,400 pixels. That is the whole argument for doing it structurally, measured.
The other half of the argument is what you cannot see from the outside: after sanitising, ten of the eleven cleaned files rendered pixel-identical to the originals, and the one that changed changed because its artwork was a remote image the sanitiser removed. Nothing about the drawing was harmed; only the parts that reached outside the file.

Why stripping script tags is not sanitizing
The naive version is four lines, and it is worth writing out so the failure mode is concrete:
// The anti-pattern: a regex pass. Shorter output, not a safer file.
function naiveSanitize(src) {
return src
.replace(/<script[\s\S]*?<\/script>/gi, '')
.replace(/\son\w+\s*=\s*("[^"]*"|'[^']*')/gi, '');
}
Run it over the twelve payloads and two of them still execute afterwards: the two whose attack is an <a href="javascript:">, one written plainly and one with the scheme encoded as javascript:. Four more still call out to the second origin, because the regex never looks at <image href>, at CSS @import, or at a <script href> that has no closing tag — the pattern requires </script>, and a self-closing element does not have one.
That is 6 of 12 still hostile after a pass that looks like it did something, because the output is shorter and the word script is gone. The failures are not exotic; they are the four ways an SVG reaches outside itself, none of which involves a script element.
Parse it as XML, not as HTML
The first line of a sanitiser decides most of its behaviour. DOMParser with image/svg+xml gives you a case-sensitive tree that matches the bytes in the file, and a parse error you can act on: if the file is not well-formed XML, refuse it rather than guessing. Parsing with innerHTML would give you the browser’s normalisation instead — which is exactly what an attacker wants, since that is where OnLoad becomes onload.
Everything downstream then works on one representation. Namespaced attributes arrive with their prefix stripped by localName, so xlink:href and href are the same key, and one rule covers both.
The allowlist
Three sets and one walk. Elements not in the set are removed with their subtree; attributes not in the set are removed individually; href gets a second check because a valid attribute name is not a valid value.
const SVG_NS = 'http://www.w3.org/2000/svg';
const OK_TAG = new Set([
'svg', 'g', 'defs', 'symbol', 'use', 'a', 'title', 'desc', 'style',
'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon',
'text', 'tspan', 'textPath',
'linearGradient', 'radialGradient', 'stop', 'pattern',
'clipPath', 'mask', 'image',
'filter', 'feGaussianBlur', 'feOffset', 'feBlend', 'feColorMatrix', 'feFlood',
'feComposite', 'feMerge', 'feMergeNode',
]);
const OK_ATTR = new Set([
'id', 'class', 'style', 'transform', 'viewBox', 'preserveAspectRatio', 'version',
'x', 'y', 'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', 'width', 'height', 'd', 'points',
'fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
'stroke-opacity', 'stroke-dasharray', 'opacity', 'clip-path', 'clip-rule', 'mask', 'filter',
'gradientUnits', 'gradientTransform', 'spreadMethod', 'offset', 'stop-color', 'stop-opacity',
'patternUnits', 'patternContentUnits', 'stdDeviation', 'in', 'in2', 'result', 'mode', 'type',
'values', 'font-size', 'font-family', 'font-weight', 'letter-spacing', 'text-anchor',
'dominant-baseline', 'role', 'aria-label', 'aria-hidden', 'focusable', 'href',
]);
// href: keep only local anchors, http(s) on <a>, and data: bitmaps on <image>
function hrefAllowed(el, raw) {
const v = raw.replace(/[\u0000-\u0020]/g, '').toLowerCase();
if (v.startsWith('#')) return true;
if (el.localName === 'a') return /^https?:\/\//.test(v);
if (el.localName === 'image') return /^data:image\/(png|jpe?g|gif|webp);base64,/.test(v);
return false;
}
// Keep <style> (Figma puts every fill in .cls-1), but cut what can fetch: @import and remote url()
function sanitizeCSS(css) {
let dropped = 0;
const out = css
.replace(/@import[^;{}]*;?/gi, () => { dropped++; return ''; })
.replace(/url\(\s*(['"]?)([^)'"]*)\1\s*\)/gi, (m, q, u) => {
const v = u.replace(/[\u0000-\u0020]/g, '').toLowerCase();
if (v === '' || v.startsWith('#')) return m;
dropped++;
return 'none';
})
.replace(/(expression|javascript)\s*[:(]/gi, () => { dropped++; return 'none('; });
return { css: out, dropped };
}
function sanitizeSVG(src) {
const doc = new DOMParser().parseFromString(src, 'image/svg+xml');
if (doc.querySelector('parsererror')) return { error: 'not XML' };
const root = doc.documentElement;
if (root.localName !== 'svg' || root.namespaceURI !== SVG_NS) return { error: 'not SVG' };
const rejected = [];
const removedAttrs = [];
let cssDrops = 0;
const all = [root, ...Array.from(root.querySelectorAll('*'))];
for (const el of all) {
if (el !== root && !OK_TAG.has(el.localName)) {
rejected.push(el.localName);
el.remove();
continue;
}
for (const at of Array.from(el.attributes)) {
const name = at.localName; // xlink:href -> href
if (at.prefix === 'xmlns' || at.name.startsWith('xmlns')) continue;
if (!OK_ATTR.has(name)) {
removedAttrs.push(el.localName + '@' + at.name);
el.removeAttributeNode(at);
continue;
}
if (name === 'href' && !hrefAllowed(el, at.value)) {
removedAttrs.push(el.localName + '@' + at.name);
el.removeAttributeNode(at);
}
}
if (el.localName === 'style') {
const r = sanitizeCSS(el.textContent || '');
cssDrops += r.dropped;
el.textContent = r.css;
} else if (el.hasAttribute('style')) {
const r = sanitizeCSS(el.getAttribute('style'));
cssDrops += r.dropped;
el.setAttribute('style', r.css);
}
}
return {
svg: new XMLSerializer().serializeToString(root),
removedNodes: rejected.length,
removedAttrs: removedAttrs.length,
cssDrops,
rejected,
};
}
Three details are load-bearing.
Remove against a snapshot, not a live list. querySelectorAll is collected once, before any deletion. Deleting a parent while iterating a live collection is the classic way to skip the next sibling — and the skipped node is the one that matters.
Compare localName, keep the namespace. An attacker can register their own prefix pointing at a different namespace; matching on the qualified name lets ev:onload through as a different attribute. localName collapses every prefix to one key, and the element check still looks at localName plus the SVG namespace on the root.
Refuse, do not repair, when the parse fails. One of the twelve payloads is a 376-byte file with a DTD declaring four nested entities. DOMParser returns a parser error, the function returns { error: 'not XML' }, and the caller shows nothing. Recovering from a parse error means guessing what the author meant, and the author is the problem.
Filtering href: the three cases that look safe
The href attribute is where an allowlist quietly becomes useless if you only check that the name is allowed. Three values that pass a naive check and should not:
href="java script:alert(1)"— a literal tab inside the scheme. Browsers strip control characters before parsing a URL, so this isjavascript:with extra steps. The check strips