Fixed handling SVG files with missing tag

fix https://linear.app/tryghost/issue/SLO-151/[ghost]-cannot-read-properties-of-null-reading-attributes-an

- in the event the file doesn't contain a tag, the code currently crashes
  because it tries to read `attributes from `undefined`
- we can fix that by checking the first element exists before reading
  from it
- also includes a breaking test
This commit is contained in:
Daniel Lockyer 2024-06-18 14:27:29 +02:00 committed by Daniel Lockyer
parent cd8a54d7cc
commit 9a40440e82
3 changed files with 15 additions and 5 deletions

View File

@ -152,19 +152,23 @@ const checkFileIsValid = (fileData, types, extensions) => {
};
/**
*
* @param {String} filepath
*
* @param {String} filepath
* @returns {Boolean}
*
*
* Checks for the presence of <script> tags or 'on' attributes in an SVG file
*
*
*/
const isSvgSafe = (filepath) => {
const fileContent = fs.readFileSync(filepath, 'utf8');
const document = new JSDOM(fileContent).window.document;
document.body.innerHTML = fileContent;
const svgEl = document.body.firstElementChild;
if (!svgEl) {
return false;
}
const attributes = Array.from(svgEl.attributes).map(({name}) => name);
const hasScriptAttr = !!attributes.find(attr => attr.startsWith('on'));
const scripts = svgEl.getElementsByTagName('script');

View File

@ -63,5 +63,10 @@ describe('web utils', function () {
dirtySvgContent.should.not.containEql('<script');
validation.isSvgSafe(filepath).should.be.true;
});
it('returns false for malformed svg', async function () {
const filepath = path.join(__dirname, imageFixturePath, 'svg-malformed.svg');
validation.isSvgSafe(filepath).should.be.false;
});
});
});

View File

@ -0,0 +1 @@
<