Skip to content

Commit

Permalink
Merge pull request #1 from CommercialTribe/feature/unescape-ampersands
Browse files Browse the repository at this point in the history
Add unescape ampersand characters to sanitizer and unit tests
  • Loading branch information
Federico Bohn authored Dec 20, 2017
2 parents 7b2cfe2 + b63ea50 commit be8efd5
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/express-sanitized.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,20 @@ 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;
}

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);
Expand Down
55 changes: 55 additions & 0 deletions test/test-express-sanitized.js
Original file line number Diff line number Diff line change
@@ -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('&amp&&&amp', '&amp&&&amp', next);
});

it('should remove unknown tags', function() {
testSanitizer('<u:y><b>hello <bogus><i>world</i></bogus></b>', '<b>hello <i>world</i></b>', next);
});

it('should remove unsafe tags', function() {
testSanitizer('<b>hello <i>world</i><script src=foo.js></script></b>', '<b>hello <i>world</i></b>', next);
});

it('should remove unsafe attributes', function() {
testSanitizer('<b>hello <i onclick="takeOverWorld(this)">world</i></b>', '<b>hello <i>world</i></b>', next);
});

it('should escape cruft', function() {
testSanitizer('<b>hello <i>world<</i></b> & tomorrow the universe', '<b>hello <i>world&lt;</i></b> & 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);
}

0 comments on commit be8efd5

Please sign in to comment.