Skip to content

Commit

Permalink
Merge pull request #7 from zakyyudha/master
Browse files Browse the repository at this point in the history
Update isSvg validator by reading a regex
  • Loading branch information
wuriyanto48 authored Apr 16, 2024
2 parents 0aef182 + 7b949da commit 8739d7b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
4 changes: 4 additions & 0 deletions lib/signature.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,8 @@ module.exports = {
ZIP_2 : Buffer.from([0x50, 0x4B, 0x07, 0x08]),
WEBP : Buffer.from([0x52, 0x49, 0x46, 0x46]),
SVG : Buffer.from([0x3C, 0x3F, 0x78, 0x6D, 0x6C]),

HtmlCommentRegex : /<!--([\s\S]*?)-->/gi,
SvgRegex : /^\s*(?:<\?xml[^>]*>\s*)?(?:<!doctype svg[^>]*>\s*)?<svg[^>]*>[^*]*<\/svg>\s*$/gi,
ScriptRegex : /<\s*script/gi,
};
11 changes: 10 additions & 1 deletion lib/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const { Buffer } = require('buffer');
const s = require('./signature');
const { ScriptRegex, SvgRegex, HtmlCommentRegex } = require("./signature");

/**
* Check if buffer is one of the predefined file types function
Expand Down Expand Up @@ -115,7 +116,15 @@ const isZip = (buffer) => genericMultipleCompareBuffer(buffer, [s.ZIP_0, s.ZIP_1

const isWebp = (buffer) => genericCompareBuffer(buffer, s.WEBP);

const isSvg = (buffer) => genericCompareBuffer(buffer, s.SVG);
const isSvg = (buffer) => {
if (!Buffer.isBuffer(buffer)) {
throw new Error('Input should be a buffer');
}

const buffStr = buffer.toString();
const withoutComments = buffStr.replace(HtmlCommentRegex, '');
return SvgRegex.test(withoutComments) && !ScriptRegex.test(withoutComments);
}

module.exports = {
oneOf,
Expand Down

0 comments on commit 8739d7b

Please sign in to comment.