From b63ea5026c03bc3d7f3545547e23acd388050824 Mon Sep 17 00:00:00 2001 From: Federico Bohn Date: Wed, 20 Dec 2017 16:57:43 -0300 Subject: [PATCH] Add unescape ampersand characters to sanitizer and unit tests --- lib/express-sanitized.js | 8 +++-- test/test-express-sanitized.js | 55 ++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 test/test-express-sanitized.js diff --git a/lib/express-sanitized.js b/lib/express-sanitized.js index 4b1745f..05500e3 100644 --- a/lib/express-sanitized.js +++ b/lib/express-sanitized.js @@ -49,8 +49,12 @@ module.exports = function expressSanitized() { }; +function unescapeAmpersand(val) { + return val.replace(/&/gi, '&'); +} + function sanitizeString(val) { - var sanitized = sanitizer.sanitize(val); + var sanitized = unescapeAmpersand(sanitizer.sanitize(val)); return sanitized; } @@ -58,7 +62,7 @@ function sanitizeObject(val) { var restore; try { var teardown = JSON.stringify(val); - var clean = sanitizer.sanitize(teardown); + var clean = unescapeAmpersand(sanitizer.sanitize(teardown)); restore = JSON.parse(clean); } catch (e) { console.log(e); diff --git a/test/test-express-sanitized.js b/test/test-express-sanitized.js new file mode 100644 index 0000000..2873989 --- /dev/null +++ b/test/test-express-sanitized.js @@ -0,0 +1,55 @@ +const assert = require("assert"); +const expressSanitized = require('../lib/express-sanitized'); + +function next(){} + +describe('expressSanitized', function() { + + it('should sanitize empty', function() { + testSanitizer('', '', next); + }); + + it('should sanitize simple text', function() { + testSanitizer('hello world', 'hello world', next); + }); + + it('should sanitize entities', function() { + testSanitizer('<hello world>&', '<hello world>&', next); + }); + + it('should sanitize more entities', function() { + testSanitizer('&&&&', '&&&&', next); + }); + + it('should remove unknown tags', function() { + testSanitizer('hello world', 'hello world', next); + }); + + it('should remove unsafe tags', function() { + testSanitizer('hello world', 'hello world', next); + }); + + it('should remove unsafe attributes', function() { + testSanitizer('hello world', 'hello world', next); + }); + + it('should escape cruft', function() { + testSanitizer('hello world< & tomorrow the universe', 'hello world< & tomorrow the universe', next); + }); +}); + +function testSanitizer(value, expectedValue, next) { + const req = { + body: { + data: value + }, + query: { + variables: { + field: value + } + } + }; + expressSanitized()(req, '', next); + assert.equal(req.query.variables.field, expectedValue); + assert.equal(req.body.data, expectedValue); +}