noctcore-security/no-unescaped-html-response
noctcore-security/no-unescaped-html-response
- Package
- security v1.2.0
- Preset
- none opt-in
- Severity
- off
- Autofix
- No
- Suggestions
- No
- Options
- Optional
- Type info
- Not needed
HTML built from a runtime value and sent as a response (res.send, ctx.body, new Response, …), or bound to a raw template variable, must escape or sanitize the value for where it lands.
Express sends a string body as text/html, so a value concatenated into it is parsed as markup. A
name of <img src=x onerror=alert(1)> runs as script in whoever opens the page:
export function greet(req, res) { res.send('<p>Hello ' + req.query.name + '</p>');}import escapeHtml from 'escape-html';
export function greet(req, res) { res.send('<p>Hello ' + escapeHtml(req.query.name) + '</p>');}Escaping is only enough where it is enough. An escaped value still runs as script at the start of
a URL attribute (javascript:alert(1) has nothing to escape), inside an unquoted attribute (a space
starts a new one), in an event handler (the browser decodes the entities before running it) and in
a <script> or <style> element (escaping stops nothing there):
import escapeHtml from 'escape-html';
export function link(req, res) { res.send(`<a href="${escapeHtml(req.query.next)}">Continue</a>`);}export function link(req, res) { res.send(`<a href="https://example.com/continue?next=${encodeURIComponent(req.query.next)}">Continue</a>`);}Template engines escape by default, which is why a value that skips escaping is marked by hand
({{ bio | safe }} in nunjucks, <%- bio %> in EJS). That marker is where reflected and stored XSS
come back.
The rule judges the HTML being built, not where each value came from, the way
no-shell-interpolation judges a command string: a value read from the database (stored XSS)
counts the same as one read from the request.
What it flags
Section titled “What it flags”A body that, followed through the code that builds it, has author text containing a tag (<
followed by a letter, / or !) or a React server render (renderToString,
renderToStaticMarkup), and a runtime part that is not safe where it lands (see below).
The report is on that part. The bodies it reads:
res.send(x),res.end(x)andres.write(x)on a receiver inresponseObjects(res,response), also after calls that return the response (res.status(200).send(x));reply.send(x)on a receiver inreplyObjects(reply) once an HTML content type is set on it: Fastify sends a string as text otherwise. The same goes for the return value of an async handler that takes the reply as a parameter (async (request, reply) => { reply.type('text/html'); return html; });ctx.body = xandctx.response.body = xon a receiver incontextObjects(ctx), unless no content type is set and the body starts with author text that is not<on every branch of a?:,||or??: Koa sends that as text;new Response(x, init)andnew NextResponse(x, init)(fromnext/server) whoseinitsets an HTML content type, as in a Next route handler: a literal, or aconstheaders object orHeadersinstance (with its.set/.appendcalls);- the return value of a Nest route handler (
@Get,@Post, … from@nestjs/common, also@common.Get()on a namespace import): the Express platform sends a returned string astext/html. A@Header('Content-Type', ...)with a type that is not HTML,@Render,@Redirect,@Sseor a@Res()/@Next()parameter leaves it alone. The Fastify platform sends a string as text, but the rule cannot tell the platform from the handler, so it reports there too.
The body is followed through templates and +, both sides of ?: and || (the left side of &&
is only written when falsy), String.raw, in-file const bindings that build markup or hold
constant text (read as author text, so a quote in const OPEN = "JSON.parse('" opens a string in a
script), let accumulators (html += row, html = html + row, in loops and callbacks too),
array accumulators (rows.push(row) then rows.join('')), [...].join(sep) and
list.map(fn).join(sep) (every return of the mapper), .concat, a constant template filled by
.replace / .replaceAll at a string or plain regex placeholder (tpl.replace('{{name}}', q)),
and in-file helpers that return markup (every return), with their parameters bound to the call’s
arguments unless the helper writes them.
A placeholder is read with the value in place only when .replace writes the value as it is: a
replacer function of this file, a constant without $, a number or encodeURIComponent output. A
replacement string applies $ patterns ($`, $' and $& copy author text into the value’s
place), and escape-html leaves $ alone, so any other replacement may land anywhere and must be
safe in a tag; when it is safe only in text, the report says the $ patterns are why and suggests
a replacer function. A value an earlier .replace wrote may hold a later placeholder, so the later
replacement is judged there too.
Any other call or template tag given markup (layout(`<h1>${q}</h1>`), dedent, the common-tags
html tag, a decoder, or a string method that cuts, pads or rewrites it: .slice, .padStart,
.split, .trim, a .replace that is not a placeholder fill) is opaque: the rule cannot tell that
it keeps the escaped text escaped and in place. The markup it is given is still read where the call
stands, so an unsafe value in it is reported; every other value it is given may land anywhere and
must be safe in a tag; and the call itself is reported where it lands when nothing inside it is. A
string method called on markup returns markup, so it counts with no author tag around it. An
escaping module (common-tags safeHtml included) is judged as a value.
Two kinds of call count with no author tag around them too, so they are reported even as the whole
body (res.send(he.decode(page))), when an argument is markup built in this file: written in
place, held in a const, or moved from one of those through a property or element of a literal
(holder.value, items[0]), a destructuring, a spread of an array literal, a TypeScript cast,
await Promise.resolve(page), a callback run in place, a let assigned once or a function of this
file that returns its parameter.
- A decoder, which turns the escaped text in the markup back into markup: the global
decodeURIComponent,decodeURI,unescapeandatob(when nothing shadows them, also as a member ofglobalThis,window,selforglobal), and by their import orrequire(under any local name, also as aconstbound to one)hedecode/unescape, theentitiesdecoders (decode,decodeStrict,decodeHTML,decodeHTMLStrict,decodeHTMLAttribute,decodeHTML4,decodeHTML4Strict,decodeHTML5,decodeHTML5Strict,decodeXML,decodeXMLStrict), html-entitiesdecode/decodeEntity,unescapeof lodash, lodash-es, underscore, validator and html-escaper (lodash.unescape,lodash/unescape,lodash-es/unescapeandvalidator/lib/unescapeas the whole module), and escape-goathtmlUnescape. - A function read from the request, which may return anything: a member of
req,requestorctxunderquery,params,body,headers,cookies,filesorfile(req.query.render(page),req.body.fn(page)), a Nest@Body()/@Query()/@Param()/@Headers()parameter or a member of one, or aconstbound to one of these.
An unsafe value in the markup is reported as before; when there is none, the call is. Other values
given to these two kinds of call (an options object) are not judged. The result is followed on to
the body through a const, String(...), a string method (.trim(), .toString()), + and a
template: const out = he.decode(page) + ''; res.send(out.trim()). Markup with no runtime value in it
is fixed text before and after, so res.send(decodeURIComponent('<p>static</p>')) is not
reported. A decoder given no markup
(res.send(he.decode(q)), res.send(unescape(escapeHtml(q)))) is a body with no author markup,
which the rule does not flag; inside markup it is reported like any unescaped value
(`<p>${he.decode(q)}</p>`). Decode first and escape the result instead:
`<p>${escapeHtml(he.decode(q))}</p>`. Any other call from elsewhere that is the whole body
(res.send(layout(`<h1>${escapeHtml(q)}</h1>`))) is not reported itself: only the values in the
markup it is given are judged.
export function report(res, rows) { let html = '<ul>'; for (const row of rows) { html += '<li>' + row.title + '</li>'; } res.send(html + '</ul>');}export async function profile(res) { const row = await db.query('SELECT name FROM users WHERE id = $1', [1]); const page = `<h1>${row.name}</h1>`; res.send(page);}nunjucks renderString(template, context) and ejs.render(template, data) with a literal
template, inline or in a const, and a literal context object: each output ({{ user.bio }},
<%= bio %>, <%- locals.bio %>, <%- locals["bio"] %>, a nunjucks {% set b = bio | safe %}
alias) is looked up in the object, through nested literals. A raw
output (| safe, also after other filters; inside {% autoescape false %}; any output once the
file configures nunjucks with autoescape other than true; EJS <%-, and <%= too when the
options replace escape or escapeFunction) is reported when its value is not safe where it
lands. EJS options are read from a literal third argument (or a const holding one), and from the
data object when there is none, as EJS does: delimiter, openDelimiter, closeDelimiter
and localsName change how the template is read. When the options cannot be read in full (not a
literal, a spread or computed key, in the data too when it holds the options, outputFunctionName, client or another option that changes the output), or
the file writes a setting on ejs (ejs.escapeXML = ..., ejs.delimiter = ...) or hands it to a
call, every value in the data object is judged as raw element text. An escaped output is reported
only where escaping is not enough (<a href="{{ url }}">, <script>var u = <%= name %></script>).
import nunjucks from 'nunjucks';
export function bio(req) { return nunjucks.renderString('<div>{{ bio | safe }}</div>', { bio: req.body.bio });}import nunjucks from 'nunjucks';
export function bio(req) { return nunjucks.renderString('<div>{{ bio }}</div>', { bio: req.body.bio });}Where a value lands
Section titled “Where a value lands”The author text before each runtime part decides where it lands, read the way a browser tokenizes HTML (tags, attributes and their quoting, comments, and the elements whose content is not markup).
| Where | Safe there |
|---|---|
Element text, <textarea>, <title>, a comment, a script data block |
an escaper, a sanitizer (element text only), encodeURIComponent, a guard that refuses < and & |
| A double-quoted attribute | an escaper, encodeURIComponent, a guard that refuses <>&"' and backtick |
| A single-quoted attribute | an escaper that also encodes ' (escape-html, he, lodash escape, html-escaper, entities, a .replace chain covering '), a guard as above |
| An unquoted attribute | encodeURIComponent, the global escape, a guard that refuses whitespace, quotes and <>& |
The start of a URL attribute (href, src, action, formaction, …, a meta refresh content after its delay, an SVG animate / set to, from, by or values item) before the author text fixes a scheme |
encodeURIComponent (no : survives), a guard that also refuses /, \ and : |
A tag or attribute name, <script>, <style>, an event handler (on*), a style or srcdoc attribute, a URL after javascript: or after a scheme built from a runtime part, a data: URL in an iframe, frame or embed src or an object data |
only a constant, a number, or a literal allowlist; in <script> code, also serialize-javascript and htmlescape output |
Inside a ', " or backtick string, or a comment, in a <script> |
only a constant, a number, or a literal allowlist |
A number (Number(), parseInt, Math.*, .toFixed(), arithmetic, Date.now(),
new Date().toISOString()), a boolean, a literal, an in-file const literal and a value bound by
for (const x of LIST) over a literal array nothing changes are safe anywhere. .length and
.size count as numbers unless read from request input (req.query.q.length can be a string sent
as q[length]=...). A name a const destructuring binds to one of them at the top of its pattern, with no default
value (const { length } = rows, const { size: n } = seen), is a number only when this file
shows the value destructured to be an array, a string, a Map or a Set: an array, string or
template literal, Array.from(...), Array.of(...), new Array(...), the result of .map(...),
.filter(...) or .split(...), new Map(...) / new Set(...), or a const declared once and
bound to one of these. Anything else keeps the report, because an object the request fills can
hold a string under either name: a parameter, a member (req.body, ctx.request.body), any other
call or awaited value (await load(), JSON.parse(x)), || / ?? / ?:, an import, a let.
A type annotation or a cast proves nothing here (const tags: string[] = req.body.tags): only the
initializer counts.
JSON.stringify inside a <script> is reported: a value of </script><script>alert(1)// closes
the element. Use serialize-javascript or htmlescape there, as a JS expression, not inside a string:
var state = ${serialize(data)}; is safe, while JSON.parse('${serialize(data)}'),
"${serialize(data)}" and a template literal are reported, because neither library escapes ' or
backticks and their own " closes a double-quoted string. The rule reads the script text before
the value to tell: a quote escaped with \ does not open or close a string, and a quote inside a
regex literal (/'/g, /[a-z']/) opens nothing. A / starts a regex at the start, after an
operator or punctuation (( , = : [ ! & | ? { ; + - * % < > ~ ^), after a reserved word
(return, typeof, instanceof, in, new, delete, void, throw, case, do, else,
default, extends), after a spread ..., and after the ) of an if, while, for or
with head. After any other ), a ], a name, a number (1. included) or a string it is
division. Whitespace and comments end a word (q then a newline then return is two words), a
name reads every identifier character (combining marks, ZWNJ, ·), and a name right after .
or #, or written with a \u escape, is never a keyword (a.return / 2, a.if(x),
this.#in / 2). Where the rule
cannot tell, a / that does not start a comment makes it stop treating anything later in that
script as code, so it reports: after } (a block, or an object or function expression), ++,
--, ., or a word that is a keyword only in some places (of, await, yield, get, set,
async, let, static). A value inside a regex body (/${q}/i) is never code.
Author text is read as the browser reads it: a comment also ends at <!-->, <!---> and --!>,
and character references in a URL (javascript:, javascript:) are decoded before
the scheme is read, with the leading spaces and the tabs and newlines the browser drops left out.
A URL start the rule cannot shorten below 256 characters that way (a long character reference, a
meta refresh head) counts as a script URL. A meta content holds a URL when an earlier http-equiv is refresh (or not
literal).
A <script> whose first type attribute is a literal JSON or plain text type
(application/json, application/ld+json and other +json types, text/json, text/plain) is a
data block no script runs: only its </script> matters, as in a <textarea>. Any other type stays
script, since the browser or a library may run it: a JavaScript type, module, importmap,
speculationrules, text/babel, text/x-template (Vue reads {{ }} in it), a type with
parameters (text/javascript; charset=utf-8), an empty type, a type with a runtime part and a type
written with a character reference (text/javascript). The HTML escape states inside a script are followed: after
<!-- then <script>, a </script> does not end the element until a --> comes first.
What makes a value safe
Section titled “What makes a value safe”-
An escaper or sanitizer recognized by its import.
he(encode,escape),entities,escape-html,html-escaper,escape-goat,lodash/lodash-es/underscore/lodash.escape(escape),validator(escape),xss,sanitize-html,dompurify(DOMPurify.sanitize, and instances made withDOMPurify(window)),isomorphic-dompurify,react-dom/server(renderToString,renderToStaticMarkup),serialize-javascriptandhtmlescape, throughimport(default, named or namespace) orrequire(whole, destructured or.name), under any local name. A bare name alone proves nothing:mysql.escape,conn.escape,mongoSanitize.sanitizeand an unboundxss(x)are reported. The globalencodeURIComponentandescapecount when nothing shadows them. The outermost call decides:DOMPurify.sanitize(marked.parse(x))is safe,marked.parse(DOMPurify.sanitize(x))is not. -
Options that keep the protection on. sanitize-html with
allowedTags: false,allowedAttributes: false,allowVulnerableTags, ascript,style,textarea,option,svgor similar tag, anon*orsrcdocattribute (also through a glob such aso*ors*, which matchonerrorandsrcdoc), ajavascript:scheme, adata:scheme for a tag inallowedSchemesByTagother thanimg,audio,video,source,imageandtrack, adata:scheme inallowedSchemeswithiframeorframeallowed,transformTagsortextFilter; DOMPurify withRETURN_DOM,RETURN_DOM_FRAGMENT,RETURN_DOM_IMPORT,IN_PLACE,ALLOW_UNKNOWN_PROTOCOLS,SAFE_FOR_XML: false,ALLOWED_URI_REGEXP,CUSTOM_ELEMENT_HANDLING, ascript,iframeor similar tag inADD_TAGS/ALLOWED_TAGS, anon*attribute inADD_ATTR/ALLOWED_ATTR, a URL attribute (href,src, …) inADD_URI_SAFE_ATTR, a tag other than those media tags inADD_DATA_URI_TAGS, aNAMESPACEother than XHTML or aPARSER_MEDIA_TYPEother thantext/html; xss withonTag,onTagAttr,onIgnoreTag,onIgnoreTagAttr,safeAttrValue,escapeHtmlor a dangerous tag inwhiteList; he withallowUnsafeSymbols; serialize-javascript withunsafe: each of these counts as no sanitizer. Options must be an object literal, inline or in aconstthat is not exported and is only handed to sanitizer calls; anything else (a spread, a shared config from another file) counts as unknown, so as unsafe. -
No shared config that switches protection off. The default export of
dompurifyandisomorphic-dompurifyis one instance: asetConfigon it (asDOMPurify.setConfig, through aconstalias, or as the namedsetConfigexport, also through.callor.apply) whose config fails the checks above, or cannot be read, makes everysanitizeof that module untrusted in the file, the namedsanitizeexport included. So does handing the module binding to a call, assigning it, or writing one of its members (a destructuring target included). An instance made withDOMPurify(window)keeps its own config. A write tosanitizeHtml.defaultsorxss.whiteList(an assignment, apush,Object.assign, aconstalias or object that is then changed, or the module handed to a call) makes every call of that module untrusted; reading them is fine when the value is copied (.concat(),.slice(),.length) or handed straight to the sanitizer. -
React rendering without unsafe inner HTML.
renderToStringandrenderToStaticMarkupescape text, but writedangerouslySetInnerHTMLas is. The rendered element is read, with every component, element and object it names in this file, and adangerouslySetInnerHTML(JSX or acreateElementprops object) counts only when its__htmlis safe as element text (a constant, or sanitized). The{ __html }object is read inline or through the exact moves below: aconstholding it counts only while nothing can change it (the same rule as any held object). ThedangerouslySetInnerHTMLbeing judged, on a plain element such as<div>, is the one use that does not end the trust; the same object on another element, on a component, a custom element or in acreateElementprops object, a write, an alias that is written, or a helper with a default parameter does. A JSX element is a value too: a write through one (el.props.dangerouslySetInnerHTML.__html = x) on the element being judged is not seen. A component imported from another file or received as a parameter cannot be read, and counts as safe. -
A configured escaper in
sanitizers, trusted to encode&,<,>and": element text and double-quoted attributes. The name is trusted only for a helper the rule cannot read: one imported from another file, or not declared in this file. A function declared in this file is judged by its body alone, with the same proof as inline code, whether or not its name is insanitizers: afunction escapeHtml(s) { return s.replace('<', '<'); }is reported, and one whose.replacechain also covers'is safe in single-quoted attributes too. Any other local binding (a parameter, a reassigned function, a value built at run time) proves nothing. A dotted entry (utils.escapeHtml) is trusted the same way, by the name it starts from: imported,required or not declared in this file; an object, class or parameter of this file proves nothing. Either kind stops counting once the file may change it: a write to the name other than its declaration, to a member on the way to the callee (utils.escapeHtml = ...,utils[k] = ..., also as a destructuring target:[utils.escapeHtml] = ...), orObject.assign/Object.defineProperty/Object.defineProperties/Object.setPrototypeOf/Reflect.set/Reflect.defineProperty/Reflect.deleteProperty/Reflect.setPrototypeOfon one of them; the same through an alias (const u = utils; u.escapeHtml = ...) or, for a name the file does not declare, through the global object (globalThis.utils = ..., alsowindow,self,global, and an alias of one:const g = globalThis; g.utils = ...). For such a name the trust also ends when the file uses the global object for anything but a member read or write, an alias that is never reassigned,||/&&/??/?:(judged by where the result goes),typeof,!,void, a comparison,in,instanceofor aniftest: handed anywhere else (patch(globalThis)), its members may change unseen. The same goes for a file withthisoutside every function and class,eval,Functionor awithstatement, each of which can reach the global object without naming it.A dotted entry is an object the rule follows by its name, and it also stops counting when the file:
- reaches for the prototype of the object or of a member on the way:
utils.__proto__,utils.constructor,utils.prototype,Object.getPrototypeOf(utils),Reflect.getPrototypeOf(utils),Reflect.get(utils, key),Object.create(utils), a destructured__proto__orconstructor,__defineGetter__/__defineSetter__; - reads a member of it under a key computed at run time for anything but calling it or a member
of it, a
typeof, a comparison or a test (utils[k].escapeHtml = ...,patch(utils[k])); - lets the object, or a member on the way, go anywhere that is not one of the reads below.
These are reads, and leave the entry trusted:
- a call of the object or of a member of it, a test (
if (utils)), a binary operator, a unary operator other thandelete, an untagged template, a statement of its own, andawait,||,&&,??,?:and the last item of a sequence, whose result is walked as the object itself:Object.assign(utils || {}, x),(await utils).escapeHtml = fandpatch(utils ?? {})end the trust,(utils || {}).versiondoes not; - an alias (
const u = utils) and a destructuring declaration (const { escapeHtml: e } = utils), each followed on: forutils.html.escape, a destructuredhtmlis an alias ofutils.html. A rest element, a key computed at run time and__proto__/constructorin the pattern are not reads; - an argument of
console.*, or of anObject.*/Reflect.*method that only reads (the globals, not a local binding of that name, and with no spread before the object):Object.keys,values,entries,assign(as a source),getOwnPropertyNames,getOwnPropertySymbols,getOwnPropertyDescriptor,getOwnPropertyDescriptors,hasOwn,is,isFrozen,isSealed,isExtensible, andReflect.has,ownKeys,isExtensible,getOwnPropertyDescriptor,preventExtensions. This holds while the file itself leavesconsole,ObjectandReflectalone: it only calls them, reads their members under fixed keys or takes theirtypeof; reads no member of that name on any other object (this.console,globalThis.console,globalThis[k]); does not import orrequirea module of that name (console,node:console) or one whose name is computed at run time; does not hand the global object on; and has nothisoutside every function, noeval,Functionorwith. Forutils.html.escape,values,entries,assignand the descriptor reads shareutils.htmlwith their result, so givenutilsthey are not reads; Object.freeze(utils),Object.seal(utils)andObject.preventExtensions(utils), which return the object: the call is walked as the object itself, soObject.freeze(utils).escapeHtml = f,const u = Object.seal(utils); u.html.escape = fandoutside(Object.freeze(utils))end the trust;- an argument of a function of this file (a declaration never reassigned, or a
constbound to a function), whose parameter is followed like an alias (function debug(u) { console.log(u.version); }). This needs every parameter of the function to be a plain name (no rest, default or destructuring parameter anywhere in the list), no spread among the call’s arguments, a function that does not readarguments, a parameter that takes the argument (an argument past the last parameter is a read only for an arrow function, which has noarguments), and a file with noeval,Functionorwith. A method call (fn.call(null, utils)) is not followed. Inside the function the parameter may only be read by a member (u.version,u.escapeHtml(x), also from a closure). Any other use of it, or of a member on the way to the callee, ends the trust: an alias (const v = u), a destructuring, a store, areturn, a test,console.log(u), another call given it, a write; - an export:
export { utils },export default utils. Other modules reach the object without it, and what they do to it is not read. It is a read only while the file cannot import it back: noimport,export ... from,requireorimport()of a relative path that resolves to the file itself (or of a path computed at run time), noimport()at all, and no direct write to a member through an imported orrequired binding (other.utils.escapeHtml = f). A write one step further from another import (an alias of it, a destructuring of it, a function given it) is not seen, with or without the export; - a store in a property, as a statement of its own (
app.locals.utils = utils,exports.utils = utils,module.exports = { utils }), in a file that cannot read it back. The rule cannot follow every route to the slot, so it asks the whole file for these, and keeps the report when one is missing:- no enumeration or reflection on any object:
Object.keys,values,entries,getOwnPropertyNames,getOwnPropertySymbols,getOwnPropertyDescriptor(s),Reflect.ownKeys,Reflect.get,Object.assignwith a source that is not an object literal,for...in, an object spread of anything but a literal ({ ...other }), a rest element in an object pattern,ObjectorReflectused other than to call a method of them, or a member namedObject/Reflect(JSON.stringifyis fine); - no member read or destructuring under a key computed at run time, and none, on any other
object (
thisincluded), named like a key on the way to the slot (localsandutilsinapp.locals.utils, soreq.app.locals,res.localsandthis.localsall count), like a key of the stored literal, or, for the export object,exports; thisonly read by a member under a fixed key; noeval,Functionorwith;- the value stored does not start from a parameter (a caller knows it under its own name);
- the target is a chain of fixed keys, and a literal around the object has fixed keys and no getter;
- the name the target starts from is an import, a
constbound to the result of a call (const app = express()), or a name the file does not declare and does not reach through the global object (see the first paragraph); every other use of that name reads another member under a fixed key (app.get(...)), is an export, atypeofor a comparison, or stores the name the same way (module.exports = app, followed two stores deep); - for
module.exportsandexports(read together, as the one CommonJS export object): no load of a relative path that resolves to the file itself or of a path computed at run time, no member ofrequire(require.main,require.cache), norequireused other than to call it, no member ofmoduleother thanexports, and nothisoutside every function.
- no enumeration or reflection on any object:
A second import or
requireof the module the entry’s name comes from is the same object under another name, and is followed like an alias:import u2 from './utils'; u2.escapeHtml = fends the trust, as doesns.utils.escapeHtml = fthrough a namespace import beside a named one.Everything else hands the object on and ends the trust: a call from elsewhere given the object (
patch(utils),render(utils, data),res.render('page', { utils })),new Renderer(utils), the object asthis(fn.call(utils),fn.apply(utils),fn.bind(utils),Reflect.apply(fn, utils, [])), a tagged template, areturn, an array or object literal that is not stored as above, a store onthisor on a parameter, a parameter stored inside a function of this file, and any otherObject.*/Reflect.*method. A bare entry (escapeHtml) names a function, not an object, so only the writes in the first paragraph end its trust. A reassignedrequireof an escaping module no longer counts as that module either. - reaches for the prototype of the object or of a member on the way:
-
A
.replace/.replaceAllchain that encodes at least&,<,>and". A step counts for a character only when it is global (replaceAll, or a regex withgand noy), its pattern consumes every occurrence of the character (/</g,/[&<>"]/g,/&|</g, not/^</gor/[<]*/g), and it writes text with no markup character: an entity, nothing, a lookup in a literal table that covers the character (c => MAP[c], the table never changed), or'&#' + c.charCodeAt(0) + ';'.q.replace('&', '&')only replaces the first&, andq.replace(/[&<>"]/g, (c) => c)and'$&'put the match back, so neither counts. A later step that writes a markup character (.replace(/</g, '<')) undoes the chain;<br>written for a newline keeps it, in element text and quoted attributes. -
A safe value that moves. A value that is safe where it lands stays safe after a move the rule can read exactly: a
const, a TypeScript cast,await xorawait Promise.resolve(x), a function of this file that returns its parameter unchanged, a property or element read by a fixed key from an object or array literal (holder.value,items[0]), aconstdestructuring of one (const { name } = safe,const [first] = items, with no default value or rest element on the way), the one parameter of a callback that is notasyncand runs in place ([x].forEach((v) => ...),Promise.resolve(x).then((v) => ...)), and aletdeclared empty and assigned once by a statement before the read. An object or array held in a binding is read only as aconstliteral of plain data (fixed keys; no method, getter, setter, function value, spread or hole; no__proto__,constructororprototypekey) that is not exported, not declared at the top level of a classic script (another script can change it there; a file configured asscriptcounts as one even when it is plainly CommonJS, and so does every file under a legacy.eslintrcsetup withoutsourceType), and that the file only reads: by a fixed key, by aconstdestructuring declaration of fixed keys (const { name, bio } = safe; no default value, rest element or computed key, and a name bound to a nested object or array is held to this same rule), by{ ...holder }, in an untagged template, or in a test or comparison. A write anywhere in the file (safe.name = raw,Object.assign(safe, x),safeas a destructuring target), the holder given to a call or aliased by anything but aconstheld to the same rule, or anevalthat can reach it ends this: the value read from it is judged as an unknown one and reported. A moved value is still judged for the place it lands in, so an escaped value read from a holder into a<script>or an unquoted attribute is reported. -
A guard before the response, in the same function, with an
ifthat exits (or anifaround it): an allowlist (includes/hason in-file literals,===against literals) or a regex anchored at both ends, without themflag or a., that admits none of the characters the place needs refused (see the table). With theuflag, letter and number classes (\p{L},\p{N}) are read as admitting no markup. The check may be made on a value that holds the checked binding through exact moves (aconstalias, a local function that returns its parameter unchanged, an entry of aconstobject or array literal that is only read, the one element an inline callback receives), when no binding on the way is assigned after its declaration and the checked binding is not avar. The result of the check may pass through such a function inside the test (if (!forward(ok)) return;) or reach the call inside a callback run where it is passed ([ok].forEach((relay) => { if (!relay) return; ... }), one parameter, notasync), for a checked binding that is never written or changed after its declaration.
export function list(req, res) { const sort = String(req.query.sort); if (!['asc', 'desc'].includes(sort)) return res.status(400).json({ error: 'sort' }); res.send(`<p>Sorted ${sort}</p><script>window.sort = '${sort}';</script>`);}What it does not flag
Section titled “What it does not flag”res.json / res.jsonp, a body that is not built with markup in this file (res.send(data), an
object, a Buffer), and a write after a literal non-HTML content type set on every path to it: an
unconditional statement before the write in an enclosing block, or a call in the write’s own chain
(res.type('text/plain'), res.type('text').send(x), res.set('Content-Type', 'application/json'), res.writeHead(200, { 'Content-Type': 'text/plain' }), ctx.type = 'text/plain'). A type set in one branch only, inside a try, or in a callback does not count, and
any HTML, XML or SVG type (or one the rule cannot read) set before the write keeps it reported.
export function note(req, res) { res.type('text/plain'); res.send('<p>' + req.query.note + '</p>');}Not read: what a call from elsewhere returns (it stays opaque), a meta http-equiv written after content, a nunjucks {% set %}{% endset %} block,
a template string built at run time, a context object that is not a literal (or has a
spread), a template loaded from a file (res.render('page', ...)), engines other than nunjucks and
EJS, a nunjucks output that is a function call or a literal, HTML written over several
res.write calls (each is judged alone), HTML built in one function and sent from another unless
through a helper that returns it (a parameter the helper writes no longer counts as the argument),
a helper that returns no markup and has more than declarations and one return (one that returns
markup is read at every return),
DOMPurify.addHook, a sanitizer config or default changed in another file, an escaper named in
sanitizers (or the object a dotted entry starts from) that is written in another module, or in
this file through a value code from elsewhere returns (require('./utils').escapeHtml = ...
written in place, getHelpers().escapeHtml = ...): the rule reads one file and follows the object by its name, and whether a URL in <script src> or <iframe src> points at another host
(a fixed scheme is all the rule checks there). A method with a string method’s name (.replace,
.slice, …) is taken to be the string method, without type information.
Options
Section titled “Options”| Option | Type | Default | Meaning |
|---|---|---|---|
responseObjects |
string[] |
['res', 'response'] |
Receivers whose send, end and write write an HTML-capable response body. Setting this replaces the defaults. |
replyObjects |
string[] |
['reply'] |
Receivers whose send sends a string as text unless an HTML content type is set on them (Fastify). Setting this replaces the defaults. |
contextObjects |
string[] |
['ctx'] |
Receivers whose body assignment is the response (Koa). Setting this replaces the defaults. |
sanitizers |
string[] |
['escapeHtml', 'escapeHTML', 'htmlEscape', 'encodeHTML'] |
Escapers trusted to encode &, <, > and ", for helpers imported from another file or not declared in this one; a function declared in this file is judged by its body instead. An entry with a dot (utils.escapeHtml) matches that callee when the name it starts from is imported, required or not declared in this file; one without matches a call by that bare name, never a method. Neither counts once the file may change it: a write to the name, to an alias of it or to a member on the way to the callee (destructuring targets included), Object.assign / Object.defineProperty / Reflect.set and the like on one of them, or the same through the global object or an alias of it. A dotted entry also stops counting when the file reaches for the object’s prototype (__proto__, constructor, Object.getPrototypeOf), or lets the object go anywhere but a read the rule lists (a call of it, a test, console.*, a reading Object.* / Reflect.* method, a function of this file that only reads it, a destructuring declaration, an export, a store in a property the file never reads back): a call from elsewhere given the object (render(utils, data)) ends the trust. The full list is under What makes a value safe. Setting this replaces the defaults. |
Escaping modules count by their import whatever sanitizers says (see above).
'noctcore-security/no-unescaped-html-response': [ 'error', { responseObjects: ['res'], sanitizers: ['escapeHtml', 'utils.escapeHtml'] },]When not to use it
Section titled “When not to use it”A JSON API that never builds HTML gains nothing from it. A server that renders HTML through a templating engine with files on disk is better served by keeping autoescape on and reviewing raw markers in the templates themselves.
Related
Section titled “Related”require-sanitized-html: the browser sinks (dangerouslySetInnerHTML,innerHTML,insertAdjacentHTML).