Skip to content

Instantly share code, notes, and snippets.

@d2m
Created October 5, 2012 08:20
Show Gist options
  • Save d2m/3838726 to your computer and use it in GitHub Desktop.
Save d2m/3838726 to your computer and use it in GitHub Desktop.
You are probably misusing DOM text methods
/*
* dart version of http://benv.ca/2012/10/4/you-are-probably-misusing-DOM-text-methods/
*/
import 'dart:html';
import 'package:unittest/unittest.dart';
import 'package:unittest/html_enhanced_config.dart';
String escapeHtml(String str) {
var div = new Element.tag('div');
div.addText(str);
return div.innerHTML;
}
String betterEscapeHtml(String str) {
var s = str.replaceAll("&", "&");
s = s.replaceAll("<", "&lt;");
s = s.replaceAll(">", "&gt;");
s = s.replaceAll('"', "&quot;");
s = s.replaceAll("'", "&#039;");
s = s.replaceAll("\/", "&#x2F;");
return s;
}
void main() {
useHtmlEnhancedConfiguration();
group('Stripping tags with element.text >>', () {
test('text', () {
var div = new Element.tag('div');
div.innerHTML = 'Hello <a href="http://bob.com">Bob</a>!';
expect(div.text, 'Hello Bob!');
});
test('script', () {
var div = new Element.tag('div');
div.innerHTML =
'Hello <a>&lt;script&gt;alert(&quot;!&quot;)&lt;/script&gt;</a>!';
expect(div.text, 'Hello <script>alert("!")</script>!');
});
});
group('Escaping HTML with text nodes >>', () {
test('text', () {
var div = new Element.tag('div');
div.text = '<span>Foo & bar</span>';
expect(div.innerHTML, '&lt;span&gt;Foo &amp; bar&lt;/span&gt;');
});
test('addText', () {
var div = new Element.tag('div');
div.addText('<span>Foo & bar</span>');
expect(div.innerHTML, '&lt;span&gt;Foo &amp; bar&lt;/span&gt;');
});
test('escapeHTML', () {
var username = '<img src="herp:/" onerror=alert("derp")>';
var profileLink = '<a href="/profile">${escapeHtml(username)}</a>';
var div = new Element.tag('div');
div.innerHTML = profileLink;
expect(div.innerHTML, '<a href="/profile">&lt;img src="herp:/" onerror=alert("derp")&gt;</a>');
});
test('xss', () {
var userWebsite = '" onmouseover="alert(\'derp\')" "';
var profileLink = '<a href="${escapeHtml(userWebsite)}">Bob</a>';
var div = new Element.tag('div');
div.innerHTML = profileLink;
expect(div.innerHTML, '<a href="" onmouseover="alert(\'derp\')" ""="">Bob</a>');
});
test('betterEscapeHtml', () {
var userWebsite = '" onmouseover="alert(\'derp\')" "';
var profileLink = '<a href="${betterEscapeHtml(userWebsite)}">Bob</a>';
var div = new Element.tag('div');
div.innerHTML = profileLink;
expect(div.innerHTML, '<a href="&quot; onmouseover=&quot;alert(\'derp\')&quot; &quot;">Bob</a>');
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment