Created
October 5, 2012 08:20
-
-
Save d2m/3838726 to your computer and use it in GitHub Desktop.
You are probably misusing DOM text methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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("<", "<"); | |
s = s.replaceAll(">", ">"); | |
s = s.replaceAll('"', """); | |
s = s.replaceAll("'", "'"); | |
s = s.replaceAll("\/", "/"); | |
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><script>alert("!")</script></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, '<span>Foo & bar</span>'); | |
}); | |
test('addText', () { | |
var div = new Element.tag('div'); | |
div.addText('<span>Foo & bar</span>'); | |
expect(div.innerHTML, '<span>Foo & bar</span>'); | |
}); | |
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"><img src="herp:/" onerror=alert("derp")></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="" onmouseover="alert(\'derp\')" "">Bob</a>'); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment