JavaScriptFundamental (ES6), part 1
Escape HTML with a tagged template in JavaScript
123 a tagged template that escapes what it interpolates
hardWrite an html tag function that escapes every interpolated value, so a name containing <script> renders as text. Let a nested html result and an array of them pass through unescaped by returning a small wrapper type rather than a string. Render null and undefined as nothing, and show what strings.raw holds.
Stuck? Three hints, smallest first
- 1. A tag function is called with the literal chunks first and the values after:
(strings, ...values), wherestrings.lengthis always one more thanvalues.length. - 2. Escape all five characters in one
replacewith a callback. Chaining five replaces re-escapes the ampersands you just wrote. - 3. To know that a value is already safe, it has to be a different type from a string — hence the wrapper class, and hence the need for
String(...)at the end.
const ENTITIES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (ch) => ENTITIES[ch]);
class Safe {
constructor(markup) { this.markup = markup; }
toString() { return this.markup; }
}
const render = (value) =>
value instanceof Safe ? value.markup
: Array.isArray(value) ? value.map(render).join('')
: value === null || value === undefined ? ''
: escapeHtml(value);
const html = (strings, ...values) =>
new Safe(strings.reduce((out, chunk, i) => out + render(values[i - 1]) + chunk));
const shapes = (strings, ...values) => ({ chunks: strings.length, values: values.length, cooked: strings[1], raw: strings.raw[1] });
const vendor = { name: 'Ade & Sons', review: '<script>steal()</script>', stall: null, crates: 12 };
const card = html`<p>${vendor.name} sold ${vendor.crates} crates</p>`;
const nasty = html`<blockquote>${vendor.review}</blockquote>`;
const nested = html`<ul>${['Yaba', 'Surulere'].map((z) => html`<li>${z}</li>`)}</ul>`;
const missing = html`<span>${vendor.stall}${undefined}</span>`;
const parts = shapes`a${1}b\nc${2}d`;
console.log('card :', String(card));
console.log('nasty :', String(nasty));
console.log('nested:', String(nested));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('an interpolated ampersand becomes an entity', String(card), '<p>Ade & Sons sold 12 crates</p>');
test('a script tag arrives as text, so the browser will not run it', String(nasty), '<blockquote><script>steal()</script></blockquote>');
test('the markup you typed yourself is untouched, only the holes are escaped', String(card).startsWith('<p>'), true);
test('a nested html result is trusted, and an array of them joins', String(nested), '<ul><li>Yaba</li><li>Surulere</li></ul>');
test('null and undefined render as nothing at all', String(missing), '<span></span>');
test('the tag gets one more chunk than it gets values', [parts.chunks, parts.values], [3, 2]);
test('the cooked chunk has a real newline, the raw one has a backslash and an n', [parts.cooked.length, parts.raw.length], [3, 4]);
test('the result is an object, not a string, which is the price of knowing it is safe', typeof card, 'object');
test('and escaping in one pass is what stops &lt; becoming &amp;lt;', escapeHtml('a<b&c'), 'a<b&c');
The reason to reach for a tag function is that it can tell the difference between the parts you wrote and the parts that came from data. The literal chunks arrive as strings and are trusted; everything in values came from somewhere else and is escaped. That is the whole security model, and it is why concatenating markup with + can never be made safe by the same means.
Two details make it hold up. Escaping in a single replace with a callback avoids the classic double-escape, where you turn < into < and then turn that ampersand into &. And trust has to be carried by a type: if html returned a plain string there would be no way to tell an already-escaped fragment from an attacker's string, so nesting would either double-escape or open a hole. The cost is real, and the eighth assertion is it — the result is an object, and forgetting String(...) somewhere will show a reader [object Object].
strings.raw is the same chunks before escape processing. String.raw is the tag built on it, and it is what you want for a Windows path or a regular expression written inside a template.