sanitize-html 1.19.3 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,7 @@
1
1
  ## Changelog
2
2
 
3
+ 1.20.0: reduced size of npm package via the `files` key; we only need to publish what's in `dist`. Thanks to Steven. There should be zero impact on behavior, minor version bump is precautionary.
4
+
3
5
  1.19.3: reverted to `postcss` due to a [reported issue with `css-tree` that might or might not have XSS implications](https://github.com/punkave/sanitize-html/issues/269).
4
6
 
5
7
  1.19.2:
package/package.json CHANGED
@@ -1,8 +1,11 @@
1
1
  {
2
2
  "name": "sanitize-html",
3
- "version": "1.19.3",
3
+ "version": "1.20.0",
4
4
  "description": "Clean up user-submitted HTML, preserving whitelisted elements and whitelisted attributes on a per-element basis",
5
5
  "main": "dist/index.js",
6
+ "files": [
7
+ "dist/"
8
+ ],
6
9
  "scripts": {
7
10
  "prepare": "true",
8
11
  "build": "make clean && make all && npm run prepare && browserify dist/index.js > dist/sanitize-html.js --standalone 'sanitizeHtml'",
package/.babelrc DELETED
@@ -1,5 +0,0 @@
1
- {
2
- "presets": [
3
- "env"
4
- ]
5
- }
package/.travis.yml DELETED
@@ -1,5 +0,0 @@
1
- language: node_js
2
- node_js:
3
- - "stable"
4
- - "lts/*"
5
-
package/Makefile DELETED
@@ -1,10 +0,0 @@
1
- all: dist/index.js
2
-
3
- dist:
4
- mkdir -p dist
5
-
6
- dist/index.js: dist src/index.js package.json
7
- ./node_modules/.bin/babel src -d dist
8
-
9
- clean:
10
- rm -rf dist
Binary file
Binary file
package/src/index.js DELETED
@@ -1,610 +0,0 @@
1
- var htmlparser = require('htmlparser2');
2
- var extend = require('xtend');
3
- var quoteRegexp = require('lodash.escaperegexp');
4
- var cloneDeep = require('lodash.clonedeep');
5
- var mergeWith = require('lodash.mergewith');
6
- var isString = require('lodash.isstring');
7
- var isPlainObject = require('lodash.isplainobject');
8
- var srcset = require('srcset');
9
- var postcss = require('postcss');
10
- var url = require('url');
11
-
12
- function each(obj, cb) {
13
- if (obj) Object.keys(obj).forEach(function (key) {
14
- cb(obj[key], key);
15
- });
16
- }
17
-
18
- // Avoid false positives with .__proto__, .hasOwnProperty, etc.
19
- function has(obj, key) {
20
- return ({}).hasOwnProperty.call(obj, key);
21
- }
22
-
23
- // Returns those elements of `a` for which `cb(a)` returns truthy
24
- function filter(a, cb) {
25
- var n = [];
26
- each(a, function(v) {
27
- if (cb(v)) {
28
- n.push(v);
29
- }
30
- });
31
- return n;
32
- }
33
-
34
- module.exports = sanitizeHtml;
35
-
36
- // A valid attribute name.
37
- // We use a tolerant definition based on the set of strings defined by
38
- // html.spec.whatwg.org/multipage/parsing.html#before-attribute-name-state
39
- // and html.spec.whatwg.org/multipage/parsing.html#attribute-name-state .
40
- // The characters accepted are ones which can be appended to the attribute
41
- // name buffer without triggering a parse error:
42
- // * unexpected-equals-sign-before-attribute-name
43
- // * unexpected-null-character
44
- // * unexpected-character-in-attribute-name
45
- // We exclude the empty string because it's impossible to get to the after
46
- // attribute name state with an empty attribute name buffer.
47
- const VALID_HTML_ATTRIBUTE_NAME = /^[^\0\t\n\f\r /<=>]+$/;
48
-
49
- // Ignore the _recursing flag; it's there for recursive
50
- // invocation as a guard against this exploit:
51
- // https://github.com/fb55/htmlparser2/issues/105
52
-
53
- function sanitizeHtml(html, options, _recursing) {
54
- var result = '';
55
-
56
- function Frame(tag, attribs) {
57
- var that = this;
58
- this.tag = tag;
59
- this.attribs = attribs || {};
60
- this.tagPosition = result.length;
61
- this.text = ''; // Node inner text
62
-
63
- this.updateParentNodeText = function() {
64
- if (stack.length) {
65
- var parentFrame = stack[stack.length - 1];
66
- parentFrame.text += that.text;
67
- }
68
- };
69
- }
70
-
71
- if (!options) {
72
- options = sanitizeHtml.defaults;
73
- options.parser = htmlParserDefaults;
74
- } else {
75
- options = extend(sanitizeHtml.defaults, options);
76
- if (options.parser) {
77
- options.parser = extend(htmlParserDefaults, options.parser);
78
- } else {
79
- options.parser = htmlParserDefaults;
80
- }
81
- }
82
-
83
- // Tags that contain something other than HTML, or where discarding
84
- // the text when the tag is disallowed makes sense for other reasons.
85
- // If we are not allowing these tags, we should drop their content too.
86
- // For other tags you would drop the tag but keep its content.
87
- var nonTextTagsArray = options.nonTextTags || [ 'script', 'style', 'textarea' ];
88
- var allowedAttributesMap;
89
- var allowedAttributesGlobMap;
90
- if(options.allowedAttributes) {
91
- allowedAttributesMap = {};
92
- allowedAttributesGlobMap = {};
93
- each(options.allowedAttributes, function(attributes, tag) {
94
- allowedAttributesMap[tag] = [];
95
- var globRegex = [];
96
- attributes.forEach(function(obj) {
97
- if(isString(obj) && obj.indexOf('*') >= 0) {
98
- globRegex.push(quoteRegexp(obj).replace(/\\\*/g, '.*'));
99
- } else {
100
- allowedAttributesMap[tag].push(obj);
101
- }
102
- });
103
- allowedAttributesGlobMap[tag] = new RegExp('^(' + globRegex.join('|') + ')$');
104
- });
105
- }
106
- var allowedClassesMap = {};
107
- each(options.allowedClasses, function(classes, tag) {
108
- // Implicitly allows the class attribute
109
- if(allowedAttributesMap) {
110
- if (!has(allowedAttributesMap, tag)) {
111
- allowedAttributesMap[tag] = [];
112
- }
113
- allowedAttributesMap[tag].push('class');
114
- }
115
-
116
- allowedClassesMap[tag] = classes;
117
- });
118
-
119
- var transformTagsMap = {};
120
- var transformTagsAll;
121
- each(options.transformTags, function(transform, tag) {
122
- var transFun;
123
- if (typeof transform === 'function') {
124
- transFun = transform;
125
- } else if (typeof transform === "string") {
126
- transFun = sanitizeHtml.simpleTransform(transform);
127
- }
128
- if (tag === '*') {
129
- transformTagsAll = transFun;
130
- } else {
131
- transformTagsMap[tag] = transFun;
132
- }
133
- });
134
-
135
- var depth = 0;
136
- var stack = [];
137
- var skipMap = {};
138
- var transformMap = {};
139
- var skipText = false;
140
- var skipTextDepth = 0;
141
-
142
- var parser = new htmlparser.Parser({
143
- onopentag: function(name, attribs) {
144
- if (skipText) {
145
- skipTextDepth++;
146
- return;
147
- }
148
- var frame = new Frame(name, attribs);
149
- stack.push(frame);
150
-
151
- var skip = false;
152
- var hasText = frame.text ? true : false;
153
- var transformedTag;
154
- if (has(transformTagsMap, name)) {
155
- transformedTag = transformTagsMap[name](name, attribs);
156
-
157
- frame.attribs = attribs = transformedTag.attribs;
158
-
159
- if (transformedTag.text !== undefined) {
160
- frame.innerText = transformedTag.text;
161
- }
162
-
163
- if (name !== transformedTag.tagName) {
164
- frame.name = name = transformedTag.tagName;
165
- transformMap[depth] = transformedTag.tagName;
166
- }
167
- }
168
- if (transformTagsAll) {
169
- transformedTag = transformTagsAll(name, attribs);
170
-
171
- frame.attribs = attribs = transformedTag.attribs;
172
- if (name !== transformedTag.tagName) {
173
- frame.name = name = transformedTag.tagName;
174
- transformMap[depth] = transformedTag.tagName;
175
- }
176
- }
177
-
178
- if (options.allowedTags && options.allowedTags.indexOf(name) === -1) {
179
- skip = true;
180
- if (nonTextTagsArray.indexOf(name) !== -1) {
181
- skipText = true;
182
- skipTextDepth = 1;
183
- }
184
- skipMap[depth] = true;
185
- }
186
- depth++;
187
- if (skip) {
188
- // We want the contents but not this tag
189
- return;
190
- }
191
- result += '<' + name;
192
- if (!allowedAttributesMap || has(allowedAttributesMap, name) || allowedAttributesMap['*']) {
193
- each(attribs, function(value, a) {
194
- if (!VALID_HTML_ATTRIBUTE_NAME.test(a)) {
195
- // This prevents part of an attribute name in the output from being
196
- // interpreted as the end of an attribute, or end of a tag.
197
- delete frame.attribs[a];
198
- return;
199
- }
200
- var parsed;
201
- // check allowedAttributesMap for the element and attribute and modify the value
202
- // as necessary if there are specific values defined.
203
- var passedAllowedAttributesMapCheck = false;
204
- if (!allowedAttributesMap ||
205
- (has(allowedAttributesMap, name) && allowedAttributesMap[name].indexOf(a) !== -1 ) ||
206
- (allowedAttributesMap['*'] && allowedAttributesMap['*'].indexOf(a) !== -1 ) ||
207
- (has(allowedAttributesGlobMap, name) && allowedAttributesGlobMap[name].test(a)) ||
208
- (allowedAttributesGlobMap['*'] && allowedAttributesGlobMap['*'].test(a))) {
209
- passedAllowedAttributesMapCheck = true;
210
- } else if (allowedAttributesMap && allowedAttributesMap[name]) {
211
- for (const o of allowedAttributesMap[name]) {
212
- if (isPlainObject(o) && o.name && (o.name === a)) {
213
- passedAllowedAttributesMapCheck = true;
214
- var newValue = '';
215
- if (o.multiple === true) {
216
- // verify the values that are allowed
217
- const splitStrArray = value.split(' ');
218
- for (const s of splitStrArray) {
219
- if (o.values.indexOf(s) !== -1) {
220
- if (newValue === '') {
221
- newValue = s;
222
- } else {
223
- newValue += ' ' + s;
224
- }
225
- }
226
- }
227
- } else if (o.values.indexOf(value) >= 0) {
228
- // verified an allowed value matches the entire attribute value
229
- newValue = value;
230
- }
231
- value = newValue;
232
- }
233
- }
234
- }
235
- if (passedAllowedAttributesMapCheck) {
236
- if (options.allowedSchemesAppliedToAttributes.indexOf(a) !== -1) {
237
- if (naughtyHref(name, value)) {
238
- delete frame.attribs[a];
239
- return;
240
- }
241
- }
242
- if (name === 'iframe' && a === 'src') {
243
- var allowed = true;
244
- try {
245
- // naughtyHref is in charge of whether protocol relative URLs
246
- // are cool. We should just accept them
247
- parsed = url.parse(value, false, true);
248
- var isRelativeUrl = parsed && parsed.host === null && parsed.protocol === null;
249
- if (isRelativeUrl) {
250
- // default value of allowIframeRelativeUrls is true unless allowIframeHostnames specified
251
- allowed = has(options, "allowIframeRelativeUrls") ?
252
- options.allowIframeRelativeUrls : !options.allowedIframeHostnames;
253
- } else if (options.allowedIframeHostnames) {
254
- allowed = options.allowedIframeHostnames.find(function (hostname) {
255
- return hostname === parsed.hostname;
256
- });
257
- }
258
- } catch (e) {
259
- // Unparseable iframe src
260
- allowed = false;
261
- }
262
- if (!allowed) {
263
- delete frame.attribs[a];
264
- return;
265
- }
266
- }
267
- if (a === 'srcset') {
268
- try {
269
- parsed = srcset.parse(value);
270
- each(parsed, function(value) {
271
- if (naughtyHref('srcset', value.url)) {
272
- value.evil = true;
273
- }
274
- });
275
- parsed = filter(parsed, function(v) {
276
- return !v.evil;
277
- });
278
- if (!parsed.length) {
279
- delete frame.attribs[a];
280
- return;
281
- } else {
282
- value = srcset.stringify(filter(parsed, function(v) {
283
- return !v.evil;
284
- }));
285
- frame.attribs[a] = value;
286
- }
287
- } catch (e) {
288
- // Unparseable srcset
289
- delete frame.attribs[a];
290
- return;
291
- }
292
- }
293
- if (a === 'class') {
294
- value = filterClasses(value, allowedClassesMap[name]);
295
- if (!value.length) {
296
- delete frame.attribs[a];
297
- return;
298
- }
299
- }
300
- if (a === 'style') {
301
- try {
302
- var abstractSyntaxTree = postcss.parse(name + " {" + value + "}");
303
- var filteredAST = filterCss(abstractSyntaxTree, options.allowedStyles);
304
-
305
- value = stringifyStyleAttributes(filteredAST);
306
-
307
- if(value.length === 0) {
308
- delete frame.attribs[a];
309
- return;
310
- }
311
- } catch (e) {
312
- delete frame.attribs[a];
313
- return;
314
- }
315
- }
316
- result += ' ' + a;
317
- if (value.length) {
318
- result += '="' + escapeHtml(value, true) + '"';
319
- }
320
- } else {
321
- delete frame.attribs[a];
322
- }
323
- });
324
- }
325
- if (options.selfClosing.indexOf(name) !== -1) {
326
- result += " />";
327
- } else {
328
- result += ">";
329
- if (frame.innerText && !hasText && !options.textFilter) {
330
- result += frame.innerText;
331
- }
332
- }
333
- },
334
- ontext: function(text) {
335
- if (skipText) {
336
- return;
337
- }
338
- var lastFrame = stack[stack.length-1];
339
- var tag;
340
-
341
- if (lastFrame) {
342
- tag = lastFrame.tag;
343
- // If inner text was set by transform function then let's use it
344
- text = lastFrame.innerText !== undefined ? lastFrame.innerText : text;
345
- }
346
-
347
- if ((tag === 'script') || (tag === 'style')) {
348
- // htmlparser2 gives us these as-is. Escaping them ruins the content. Allowing
349
- // script tags is, by definition, game over for XSS protection, so if that's
350
- // your concern, don't allow them. The same is essentially true for style tags
351
- // which have their own collection of XSS vectors.
352
- result += text;
353
- } else {
354
- var escaped = escapeHtml(text, false);
355
- if (options.textFilter) {
356
- result += options.textFilter(escaped);
357
- } else {
358
- result += escaped;
359
- }
360
- }
361
- if (stack.length) {
362
- var frame = stack[stack.length - 1];
363
- frame.text += text;
364
- }
365
- },
366
- onclosetag: function(name) {
367
-
368
- if (skipText) {
369
- skipTextDepth--;
370
- if (!skipTextDepth) {
371
- skipText = false;
372
- } else {
373
- return;
374
- }
375
- }
376
-
377
- var frame = stack.pop();
378
- if (!frame) {
379
- // Do not crash on bad markup
380
- return;
381
- }
382
- skipText = false;
383
- depth--;
384
- if (skipMap[depth]) {
385
- delete skipMap[depth];
386
- frame.updateParentNodeText();
387
- return;
388
- }
389
-
390
- if (transformMap[depth]) {
391
- name = transformMap[depth];
392
- delete transformMap[depth];
393
- }
394
-
395
- if (options.exclusiveFilter && options.exclusiveFilter(frame)) {
396
- result = result.substr(0, frame.tagPosition);
397
- return;
398
- }
399
-
400
- frame.updateParentNodeText();
401
-
402
- if (options.selfClosing.indexOf(name) !== -1) {
403
- // Already output />
404
- return;
405
- }
406
-
407
- result += "</" + name + ">";
408
- }
409
- }, options.parser);
410
- parser.write(html);
411
- parser.end();
412
-
413
- return result;
414
-
415
- function escapeHtml(s, quote) {
416
- if (typeof(s) !== 'string') {
417
- s = s + '';
418
- }
419
- if (options.parser.decodeEntities) {
420
- s = s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\>/g, '&gt;');
421
- if (quote) {
422
- s = s.replace(/\"/g, '&quot;');
423
- }
424
- }
425
- // TODO: this is inadequate because it will pass `&0;`. This approach
426
- // will not work, each & must be considered with regard to whether it
427
- // is followed by a 100% syntactically valid entity or not, and escaped
428
- // if it is not. If this bothers you, don't set parser.decodeEntities
429
- // to false. (The default is true.)
430
- s = s.replace(/&(?![a-zA-Z0-9#]{1,20};)/g, '&amp;') // Match ampersands not part of existing HTML entity
431
- .replace(/</g, '&lt;')
432
- .replace(/\>/g, '&gt;');
433
- if (quote) {
434
- s = s.replace(/\"/g, '&quot;');
435
- }
436
- return s;
437
- }
438
-
439
- function naughtyHref(name, href) {
440
- // Browsers ignore character codes of 32 (space) and below in a surprising
441
- // number of situations. Start reading here:
442
- // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Embedded_tab
443
- href = href.replace(/[\x00-\x20]+/g, '');
444
- // Clobber any comments in URLs, which the browser might
445
- // interpret inside an XML data island, allowing
446
- // a javascript: URL to be snuck through
447
- href = href.replace(/<\!\-\-.*?\-\-\>/g, '');
448
- // Case insensitive so we don't get faked out by JAVASCRIPT #1
449
- var matches = href.match(/^([a-zA-Z]+)\:/);
450
- if (!matches) {
451
- // Protocol-relative URL starting with any combination of '/' and '\'
452
- if (href.match(/^[\/\\]{2}/)) {
453
- return !options.allowProtocolRelative;
454
- }
455
-
456
- // No scheme
457
- return false;
458
- }
459
- var scheme = matches[1].toLowerCase();
460
-
461
- if (has(options.allowedSchemesByTag, name)) {
462
- return options.allowedSchemesByTag[name].indexOf(scheme) === -1;
463
- }
464
-
465
- return !options.allowedSchemes || options.allowedSchemes.indexOf(scheme) === -1;
466
- }
467
-
468
- /**
469
- * Filters user input css properties by whitelisted regex attributes.
470
- *
471
- * @param {object} abstractSyntaxTree - Object representation of CSS attributes.
472
- * @property {array[Declaration]} abstractSyntaxTree.nodes[0] - Each object cointains prop and value key, i.e { prop: 'color', value: 'red' }.
473
- * @param {object} allowedStyles - Keys are properties (i.e color), value is list of permitted regex rules (i.e /green/i).
474
- * @return {object} - Abstract Syntax Tree with filtered style attributes.
475
- */
476
- function filterCss(abstractSyntaxTree, allowedStyles) {
477
- if (!allowedStyles) {
478
- return abstractSyntaxTree;
479
- }
480
-
481
- var filteredAST = cloneDeep(abstractSyntaxTree);
482
- var astRules = abstractSyntaxTree.nodes[0];
483
- var selectedRule;
484
-
485
- // Merge global and tag-specific styles into new AST.
486
- if (allowedStyles[astRules.selector] && allowedStyles['*']) {
487
- selectedRule = mergeWith(
488
- cloneDeep(allowedStyles[astRules.selector]),
489
- allowedStyles['*'],
490
- function(objValue, srcValue) {
491
- if (Array.isArray(objValue)) {
492
- return objValue.concat(srcValue);
493
- }
494
- }
495
- );
496
- } else {
497
- selectedRule = allowedStyles[astRules.selector] || allowedStyles['*'];
498
- }
499
-
500
- if (selectedRule) {
501
- filteredAST.nodes[0].nodes = astRules.nodes.reduce(filterDeclarations(selectedRule), []);
502
- }
503
-
504
- return filteredAST;
505
- }
506
-
507
- /**
508
- * Extracts the style attribues from an AbstractSyntaxTree and formats those
509
- * values in the inline style attribute format.
510
- *
511
- * @param {AbstractSyntaxTree} filteredAST
512
- * @return {string} - Example: "color:yellow;text-align:center;font-family:helvetica;"
513
- */
514
- function stringifyStyleAttributes(filteredAST) {
515
- return filteredAST.nodes[0].nodes
516
- .reduce(function(extractedAttributes, attributeObject) {
517
- extractedAttributes.push(
518
- attributeObject.prop + ':' + attributeObject.value + ';'
519
- );
520
- return extractedAttributes;
521
- }, [])
522
- .join('');
523
- }
524
-
525
- /**
526
- * Filters the existing attributes for the given property. Discards any attributes
527
- * which don't match the whitelist.
528
- *
529
- * @param {object} selectedRule - Example: { color: red, font-family: helvetica }
530
- * @param {array} allowedDeclarationsList - List of declarations which pass whitelisting.
531
- * @param {object} attributeObject - Object representing the current css property.
532
- * @property {string} attributeObject.type - Typically 'declaration'.
533
- * @property {string} attributeObject.prop - The CSS property, i.e 'color'.
534
- * @property {string} attributeObject.value - The corresponding value to the css property, i.e 'red'.
535
- * @return {function} - When used in Array.reduce, will return an array of Declaration objects
536
- */
537
- function filterDeclarations(selectedRule) {
538
- return function (allowedDeclarationsList, attributeObject) {
539
- // If this property is whitelisted...
540
- if (selectedRule.hasOwnProperty(attributeObject.prop)) {
541
- var matchesRegex = selectedRule[attributeObject.prop].some(function(regularExpression) {
542
- return regularExpression.test(attributeObject.value);
543
- });
544
-
545
- if (matchesRegex) {
546
- allowedDeclarationsList.push(attributeObject);
547
- }
548
- }
549
- return allowedDeclarationsList;
550
- };
551
- }
552
-
553
- function filterClasses(classes, allowed) {
554
- if (!allowed) {
555
- // The class attribute is allowed without filtering on this tag
556
- return classes;
557
- }
558
- classes = classes.split(/\s+/);
559
- return classes.filter(function(clss) {
560
- return allowed.indexOf(clss) !== -1;
561
- }).join(' ');
562
- }
563
- }
564
-
565
- // Defaults are accessible to you so that you can use them as a starting point
566
- // programmatically if you wish
567
-
568
- var htmlParserDefaults = {
569
- decodeEntities: true
570
- };
571
- sanitizeHtml.defaults = {
572
- allowedTags: [ 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol',
573
- 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div',
574
- 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre', 'iframe' ],
575
- allowedAttributes: {
576
- a: [ 'href', 'name', 'target' ],
577
- // We don't currently allow img itself by default, but this
578
- // would make sense if we did. You could add srcset here,
579
- // and if you do the URL is checked for safety
580
- img: [ 'src' ]
581
- },
582
- // Lots of these won't come up by default because we don't allow them
583
- selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ],
584
- // URL schemes we permit
585
- allowedSchemes: [ 'http', 'https', 'ftp', 'mailto' ],
586
- allowedSchemesByTag: {},
587
- allowedSchemesAppliedToAttributes: [ 'href', 'src', 'cite' ],
588
- allowProtocolRelative: true
589
- };
590
-
591
- sanitizeHtml.simpleTransform = function(newTagName, newAttribs, merge) {
592
- merge = (merge === undefined) ? true : merge;
593
- newAttribs = newAttribs || {};
594
-
595
- return function(tagName, attribs) {
596
- var attrib;
597
- if (merge) {
598
- for (attrib in newAttribs) {
599
- attribs[attrib] = newAttribs[attrib];
600
- }
601
- } else {
602
- attribs = newAttribs;
603
- }
604
-
605
- return {
606
- tagName: newTagName,
607
- attribs: attribs
608
- };
609
- };
610
- };