Daryll Doyle WordPress Development and Consultancy in Cornwall

SVG Sanitization

S

A couple of days ago I was browsing through the WordPress core Trac looking for something to get involved in and stumbled upon the following issue: https://core.trac.wordpress.org/ticket/24251

The lack of ability to upload SVGs into WordPress has always been a slight annoyance to me so I decided to see what I could do about it. After reading through the thread, I realised that what PHP was really missing, was a decent SVG sanitizer.

I read around a few articles and read through the source at: https://github.com/cure53/DOMPurify to get some ideas of how it’s done by the professionals. I started off by mapping out what was needed:

  • An element whitelist
  • An attribute whitelist
  • A way to remove those not in the whitelist

The two whitelists I borrowed from DOMPurify, after all it’s built by people with more knowledge than me. I then put a basic PHP library together that allowed me to pass in a dirty SVG string and receive out an SVG string with all the non-whitelisted elements and attributes removed.

The strangest thing I came across whilst building this was the fact that DOMNodeList doesn’t work like an array. If you iterate from 0 to 10 and delete node 5, everything drops down 1 place, so when you move to node 6, that’s actually node 7, odd. This can be easily fixed of course by iterating backwards from 10 to 0.

Anyway, I have a basic POC up on Github (https://github.com/darylldoyle/svg-sanitizer) that I’m hopefully going to push a bit further in the next week or so. Lets hope all goes well!

 

About the author

Daryll Doyle

Daryll is a Staff Engineer at 10up.

With a deep passion for web development and open-source technology, Daryll is the original author of the SVG sanitization plugin Safe SVG, which boasts over 900,000 installs from the WordPress.org plugin directory and is now proudly maintained by 10up.

Throughout his career, Daryll has demonstrated expertise in SVGs and WordPress, sharing his knowledge through public speaking engagements, including a notable talk at WordCamp London 2018.

Beyond his professional life, Daryll enjoys spending quality time with his family and diving into research on Developer Experience, constantly seeking ways to improve the workflow and productivity of fellow developers.

Add comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Daryll Doyle WordPress Development and Consultancy in Cornwall