https://github.com/mikesamuel/html-contextual-autoescaper-java
Prevents XSS by figuring out how to escape untrusted values in templates
https://github.com/mikesamuel/html-contextual-autoescaper-java
java security-hardening template-engine xss
Last synced: over 1 year ago
JSON representation
Prevents XSS by figuring out how to escape untrusted values in templates
- Host: GitHub
- URL: https://github.com/mikesamuel/html-contextual-autoescaper-java
- Owner: mikesamuel
- License: other
- Created: 2011-10-14T20:36:28.000Z (over 14 years ago)
- Default Branch: master
- Last Pushed: 2020-10-13T10:15:13.000Z (over 5 years ago)
- Last Synced: 2025-03-18T15:43:18.944Z (over 1 year ago)
- Topics: java, security-hardening, template-engine, xss
- Language: Python
- Homepage:
- Size: 10.2 MB
- Stars: 15
- Watchers: 3
- Forks: 3
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
A runtime contextual autoescaper written in Java.
This provides a writer-like object that provides two methods:
```java
writeSafe(String)
write(Object)
```
so that the sequence of calls
```java
w.writeSafe("");
w.write("I <3 Ponies!");
w.writeSafe("\nof(
"foo", "bar", "\"baz\"", 42));
w.writeSafe(")>");
```
results in the output
```html
I <3 Ponies!
```
The safe parts are treated as literal chunks of HTML/CSS/JS, and the unsafe
parts are escaped to preserve security and least-surprise.
For a more comprehensive example, a template like
```html
<% helper($self) %>
(function () { // Sleepy developers put sensitive info in comments.
var o = <%=$self>,
w = "<%=$self.world%>";
})();
<% def helper($self) {
%>Hello, <%=$self.world%>
<%}%>
```
might correspond to the sequence of calls
```java
// Dummy input values.
Map $self = ImmutableMap.of(
"world", "", "color", "blue");
Object color = self.get("color"), world = self.get("world");
// Alternating safe and unsafe writes that implement the template.
w.writeSafe("
\n\n ");
helper (w, $self);
w.writeSafe("\n \n (function () {\n var o = ");
w.write ($self);
w.writeSafe(",\n w = \"");
w.write (world);
w.writeSafe("\";\n })();\n");
```
which result in the output
```html
Hello, !
(function () {
var o = {"Color":"blue","World":"\u003cCincinatti\u003e"},
w = "\x26lt;Cincinatti\x26gt;";
})();
```