Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/lib/svg_text_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,8 @@ var TAG_STYLES = {
em: 'font-style:italic;font-weight:bold'
};

var PROTOCOLS = ['http:', 'https:', 'mailto:'];

var STRIP_TAGS = new RegExp('</?(' + Object.keys(TAG_STYLES).join('|') + ')( [^>]*)?/?>', 'g');

util.plainText = function(_str){
Expand Down Expand Up @@ -252,7 +254,14 @@ function convertToSVG(_str){
if(tag === 'a'){
if(close) return '</a>';
else if(extra.substr(0,4).toLowerCase() !== 'href') return '<a>';
else return '<a xlink:show="new" xlink:href' + extra.substr(4) + '>';
else {
var dummyAnchor = document.createElement('a');
dummyAnchor.href = extra.substr(4).replace(/["'=]/g, '');

if(PROTOCOLS.indexOf(dummyAnchor.protocol) === -1) return '<a>';

return '<a xlink:show="new" xlink:href' + extra.substr(4) + '>';
}
}
else if(tag === 'br') return '<br>';
else if(close) {
Expand Down
69 changes: 69 additions & 0 deletions test/jasmine/tests/svg_text_utils_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
var d3 = require('d3');

var util = require('@src/lib/svg_text_utils');


describe('svg+text utils', function() {
'use strict';

describe('convertToTspans', function() {

function mockTextSVGElement(txt) {
return d3.select('body')
.append('svg')
.attr('id', 'text')
.append('text')
.text(txt)
.call(util.convertToTspans);
}

afterEach(function() {
d3.select('#text').remove();
});

it('checks for XSS attack in href', function() {
var node = mockTextSVGElement(
'<a href="javascript:alert(\'attack\')">XSS</a>'
)

expect(node.text()).toEqual('XSS');
expect(node.select('a').attr('xlink:href')).toBe(null);
});

it('checks for XSS attack in href (with plenty of white spaces)', function() {
var node = mockTextSVGElement(
'<a href = " javascript:alert(\'attack\')">XSS</a>'
)

expect(node.text()).toEqual('XSS');
expect(node.select('a').attr('xlink:href')).toBe(null);
});

it('whitelists http hrefs', function() {
var node = mockTextSVGElement(
'<a href="http://bl.ocks.org/">bl.ocks.org</a>'
)

expect(node.text()).toEqual('bl.ocks.org');
expect(node.select('a').attr('xlink:href')).toEqual('http://bl.ocks.org/');
});

it('whitelists https hrefs', function() {
var node = mockTextSVGElement(
'<a href="https://plot.ly">plot.ly</a>'
)

expect(node.text()).toEqual('plot.ly');
expect(node.select('a').attr('xlink:href')).toEqual('https://plot.ly');
});

it('whitelists mailto hrefs', function() {
var node = mockTextSVGElement(
'<a href="mailto:[email protected]">support</a>'
)

expect(node.text()).toEqual('support');
expect(node.select('a').attr('xlink:href')).toEqual('mailto:[email protected]');
});
});
});