Sub topic 9
Building an Escaping Tag and Avoiding Injection
This chapter assumes you already know how tag functions receive the strings array and the values rest parameter, and how nested template literals work. You should also know the basics of reduce and instanceof.
Why Plain Interpolation Is Unsafe
A plain template literal inserts each value exactly as it is. It doesn't know the value is headed for HTML, SQL, or a shell command, so it never escapes anything. If a value comes from a user, that user controls part of your markup:
const userName = '<img src=x onerror="alert(1)">';
const markup = `<p>Hello, ${userName}</p>`;
console.log(markup);
// <p>Hello, <img src=x onerror="alert(1)"></p>If the browser receives that string as HTML, the onerror handler runs. This attack is called cross-site scripting (XSS). The backticks didn't cause it, and they don't prevent it either.
A Basic Escaping Tag
A tag function sees every interpolated value before it joins the pieces. That makes it a good place to escape each value. The literal parts come from your source code, so the tag trusts them. Only the values get escaped.
const escape = (s) => String(s)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
function html(strings, ...values) {
return strings.reduce((out, str, i) => out + escape(values[i - 1]) + str);
}
const userName = '<img src=x onerror="alert(1)">';
console.log(html`<p>Hello, ${userName}</p>`);
// <p>Hello, <img src=x onerror="alert(1)"></p>reduce is called with no initial value, so out starts as strings[0] and i starts at 1. Each step adds the value that came before strings[i], then strings[i] itself. The & replacement has to run first. If it ran later, it would double-escape the & characters that the other replacements just added.
The Nesting Problem
Nesting breaks this simple tag. If you build a list with inner html calls, the outer call escapes the markup that the inner calls produced:
const items = ["<b>", "ok"];
console.log(html`<ul>${items.map(item => html`<li>${item}</li>`).join("")}</ul>`);
// <ul><li><b></li><li>ok</li></ul>The outer tag can't tell a string that is already safe from untrusted text. To fix this, the tag returns a marker object instead of a plain string, and it skips escaping for any value that carries the marker.
class SafeHtml {
constructor(value) { this.value = value; }
toString() { return this.value; }
}
const escape = (s) => String(s)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
function render(value) {
if (value instanceof SafeHtml) return value.value;
if (Array.isArray(value)) return value.map(render).join("");
return escape(value);
}
function html(strings, ...values) {
return new SafeHtml(
strings.reduce((out, str, i) => out + render(values[i - 1]) + str)
);
}
const items = ["<b>", "ok"];
const list = html`<ul>${items.map(item => html`<li>${item}</li>`)}</ul>`;
console.log(String(list));
// <ul><li><b></li><li>ok</li></ul>Arrays are now joined inside the tag, so you no longer call .join("") yourself. If you did, join would turn the SafeHtml objects into plain strings, and the outer tag would escape them again.
Escaping Depends on Context
HTML entity escaping is only correct for text content and quoted attribute values. In these places it doesn't protect you:
| Context | Example | Why entity escaping fails |
|---|---|---|
| URL attribute | `href="${url}"` | `javascript:alert(1)` contains no characters to escape |
| Unquoted attribute | `<div class=${c}>` | A space starts a new attribute |
| Script block | `<script>let x = "${v}"</script>` | JavaScript string rules apply instead of HTML rules |
| Event handler | `onclick="${code}"` | The value runs as code |
In these contexts, validate the value (for example, allow only http: and https: URLs) or avoid putting data there at all.
Tags for Parameterized Queries
For SQL, don't escape at all. Use placeholders, and let the database driver send the values separately from the query text. A tag can build that pair for you:
function sql(strings, ...values) {
const text = strings.reduce((out, str, i) => out + "$" + i + str);
return { text, values };
}
const name = "x'; DROP TABLE users; --";
const age = 30;
console.log(sql`SELECT * FROM users WHERE name = ${name} AND age > ${age}`);
// {
// text: 'SELECT * FROM users WHERE name = $1 AND age > $2',
// values: [ "x'; DROP TABLE users; --", 30 ]
// }Drivers such as pg accept this { text, values } shape. The value never becomes part of the SQL text, so it can't change the query.
Exercise
Using the first, basic html tag, a developer writes html<a href="${link}">profile</a> with link set to "javascript:alert(1)". Is the output safe? Explain why or why not.
Show answer
No. The value has no &, <, >, ", or ' characters, so escaping leaves it unchanged. The browser runs the javascript: URL when someone clicks the link. URL contexts need validation, such as allowing only http: and https: schemes, not entity escaping.
Exercise
Why does the improved html tag return a SafeHtml object instead of a plain string?
Show answer
The outer tag needs a way to tell output that is already escaped from untrusted strings. Without the marker, nested html results would be escaped a second time and show up as visible <li> text.