Skip to content

Commit 7b949da

Browse files
authored
Merge pull request #1 from zakyyudha/contrib-master
Update isSvg validator
2 parents 0aef182 + 6c43abc commit 7b949da

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

lib/signature.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,8 @@ module.exports = {
3535
ZIP_2 : Buffer.from([0x50, 0x4B, 0x07, 0x08]),
3636
WEBP : Buffer.from([0x52, 0x49, 0x46, 0x46]),
3737
SVG : Buffer.from([0x3C, 0x3F, 0x78, 0x6D, 0x6C]),
38+
39+
HtmlCommentRegex : /<!--([\s\S]*?)-->/gi,
40+
SvgRegex : /^\s*(?:<\?xml[^>]*>\s*)?(?:<!doctype svg[^>]*>\s*)?<svg[^>]*>[^*]*<\/svg>\s*$/gi,
41+
ScriptRegex : /<\s*script/gi,
3842
};

lib/validator.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

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

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

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

118-
const isSvg = (buffer) => genericCompareBuffer(buffer, s.SVG);
119+
const isSvg = (buffer) => {
120+
if (!Buffer.isBuffer(buffer)) {
121+
throw new Error('Input should be a buffer');
122+
}
123+
124+
const buffStr = buffer.toString();
125+
const withoutComments = buffStr.replace(HtmlCommentRegex, '');
126+
return SvgRegex.test(withoutComments) && !ScriptRegex.test(withoutComments);
127+
}
119128

120129
module.exports = {
121130
oneOf,

0 commit comments

Comments
 (0)