diff --git a/package.json b/package.json index 218f347..fbc2ac0 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "base64-js": "1.2.1", "base64-loader": "1.0.0", "dompurify": "2.2.7", + "fastestsmallesttextencoderdecoder": "^1.0.22", "minilog": "3.1.0", "transformation-matrix": "1.15.0" }, diff --git a/src/index.js b/src/index.js index 060a323..5a6c636 100644 --- a/src/index.js +++ b/src/index.js @@ -2,6 +2,7 @@ const SVGRenderer = require('./svg-renderer'); const BitmapAdapter = require('./bitmap-adapter'); const inlineSvgFonts = require('./font-inliner'); const loadSvgString = require('./load-svg-string'); +const sanitizeSvg = require('./sanitize-svg'); const serializeSvgToString = require('./serialize-svg-to-string'); const SvgElement = require('./svg-element'); const convertFonts = require('./font-converter'); @@ -14,6 +15,7 @@ module.exports = { convertFonts: convertFonts, inlineSvgFonts: inlineSvgFonts, loadSvgString: loadSvgString, + sanitizeSvg: sanitizeSvg, serializeSvgToString: serializeSvgToString, SvgElement: SvgElement, SVGRenderer: SVGRenderer diff --git a/src/sanitize-svg.js b/src/sanitize-svg.js new file mode 100644 index 0000000..5bc2132 --- /dev/null +++ b/src/sanitize-svg.js @@ -0,0 +1,45 @@ +const DOMPurify = require('dompurify'); + +const sanitizeSvg = {}; + +DOMPurify.addHook( + 'beforeSanitizeAttributes', + currentNode => { + console.log('in the hook!'); + if (currentNode && currentNode.href && currentNode.href.baseVal && + currentNode.href.baseVal.replace(/\s/g, '').slice(0, 5) !== 'data:'){ + currentNode.attributes.removeNamedItem('href'); + delete currentNode.href; + } + return currentNode; + } +); + +let _TextDecoder; +let _TextEncoder; +if (typeof TextDecoder === 'undefined' || typeof TextEncoder === 'undefined') { + // Wait to require the text encoding polyfill until we know it's needed. + // eslint-disable-next-line global-require + const encoding = require('fastestsmallesttextencoderdecoder'); + _TextDecoder = encoding.TextDecoder; + _TextEncoder = encoding.TextEncoder; +} else { + _TextDecoder = TextDecoder; + _TextEncoder = TextEncoder; +} + +sanitizeSvg.sanitizeByteStream = function (data){ + console.log('calling me!'); + const decoder = new _TextDecoder(); + const encoder = new _TextEncoder(); + + const sanitizedValue = DOMPurify.sanitize(decoder.decode(data), { + USE_PROFILES: {svg: true} + }); + + console.log('before >', decoder.decode(data)); + console.log('after >', sanitizedValue); + return encoder.encode(sanitizedValue); +}; + +module.exports = sanitizeSvg;