Original flaw
Earlier flawThe exposed Vitest browser RPC surface permitted remote filesystem writes and code execution.
Sink: Vitest packages/browser/src/node/rpc.ts write, exec, and CDP RPC handlers
Originally written by Vladimir
How AI contributed: Incomplete remediationPublished Jun 15, 2026 in
vitest-dev/vitest
Summary Vitest Browser Mode exposes a cdp() API that forwards raw Chrome DevTools Protocol (CDP) methods over the Vitest browser WebSocket RPC. CDP is not gated by browser.api.allowWrite, browser.api.allowExec, api.allowWrite, or api.allowExec. As a result, disabling Browser Mode write and exec operations does not prevent a browser API client from using CDP to perform equivalent actions. In a verified reproduction with allowWrite: false and allowExec: false, CDP Page.setDownloadBehavior set the browser download directory to the project root, and CDP Runtime.evaluate downloaded a controlled vite.config.ts. Vitest reloaded the changed config and executed attacker-controlled Node.js code. When the Browser Mode API is also exposed to the network, this becomes remotely exploitable because the generated browser runner page exposes the API token, active session id, project name, and project root path needed to connect to the browser WebSocket API and select the target download directory. Impact This affects Browser Mode projects using a CDP-capable provider, such as Playwright Chromium, when the browser API server is exposed to the network, for example with --browser.api.host=0.0.0.0. In this mode Vitest warns that write and exec operations are disabled by default, but the generated browser runner page exposes enough metadata for a remote client to authenticate to the browser WebSocket API while an active session exists. This includes the browser API token, active session id, project name, and serialized test config including the project root path. The attacker can then call Vitest's CDP RPC and use Chrome's download controls to overwrite vite.config.ts in the project root. When Vitest reloads the changed config, attacker-controlled Node.js code executes on the host running Vitest. The same exposed CDP bridge also allows direct browser-session JavaScript execution through Runtime.evaluate. A separate local probe showed that CDP can navigate the browser to a file:// URL and read rendered file contents, but the primary verified impact is config-file overwrite leading to RCE. Reproduction For a concrete reproduction, start Browser Mode in watch mode using the official Lit example: Configure the Browser Mode API to listen on all interfaces while explicitly disabling write and exec operations: Then start the test server: Vitest serves the browser runner HTML and WebSocket API at http://localhost:63315. While the browser session is active: 1. Fetch the generated browser runner page: 2. Extract the embedded browser API token, active session id, project name, and project root: · window.VITEST_API_TOKEN · __vitest_browser_runner__.sessionId · __vitest_browser_runner__.config.name · __vitest_browser_runner__.config.root 3. Connect to the browser API WebSocket as a tester client: 4. Call the sendCdpEvent RPC method with: 5. Call sendCdpEvent again with Runtime.evaluate. The evaluated JavaScript creates a Blob containing a malicious Vite config and clicks an anchor element <a download="vite.config.ts">. 6. Observed result: · vite.config.ts is overwritten with attacker-controlled content. · Vitest reloads the changed config. · The injected Node.js payload runs on the host.
The debugger RPC path in packages/browser/src/node/rpc.ts was not gated by the allowWrite and allowExec flags that restrict the file commands, so a client could call Chrome DevTools Protocol methods like Page.setDownloadBehavior and Runtime.evaluate with both disabled. When the browser API is exposed to the network, the runner page leaks the API token and session id, and CDP can overwrite vite.config.ts so the reload executes attacker code.
Case facts
Only the highlighted steps are this advisory. The first step is the earlier flaw the AI tried, and failed, to close.
Original flaw
Earlier flawSink: Vitest packages/browser/src/node/rpc.ts write, exec, and CDP RPC handlers
Originally written by Vladimir
This advisoryCVE-2026-53633 (GHSA-G8MR-85JM-7XHM)
AI tried to fix this
The AI-assisted change was a real security patch, but it left the same advisory reachable.
Missed: Left raw sendCdpEvent and trackCdpEvent handlers outside those gates.
Incomplete AI-assisted fix · ChatGPT/Codex
Fixed again
This is the patch that actually stops the same attack path.
AI-assisted fix: ChatGPT/Codex · Hiroshi Ogawa
@@ -4,7 +4,7 @@ import type CodeMirror from 'codemirror' import type { ErrorWithDiff, File, TestAnnotation, TestError } from 'vitest' import { createTooltip, destroyTooltip } from 'floating-vue' import { getAttachmentUrl, sanitizeFilePath } from '~/composables/attachments'-import { client, isReport } from '~/composables/client'+import { client, config, isReport } from '~/composables/client' import { finished } from '~/composables/client/state' import { codemirrorRef } from '~/composables/codemirror' import { openInEditor } from '~/composables/error'@@ -382,7 +382,7 @@ onBeforeUnmount(clearListeners) ref="editor" v-model="code" h-full- v-bind="{ lineNumbers: true, readOnly: isReport, saving }"+ v-bind="{ lineNumbers: true, readOnly: isReport || !config.api?.allowWrite, saving }" :mode="ext" data-testid="code-mirror" @save="onSave"@@ -1,5 +1,6 @@ import type { ResolvedConfig as ResolvedViteConfig } from 'vite' import type { Vitest } from '../core'+import type { Logger } from '../logger' import type { BenchmarkBuiltinReporters } from '../reporters' import type { ResolvedBrowserOptions } from '../types/browser' import type {@@ -59,6 +60,8 @@ function parseInspector(inspect: string | undefined | boolean | number) { export function resolveApiServerConfig<Options extends ApiConfig & UserConfig>( options: Options, defaultPort: number,+ parentApi?: ApiConfig,+ logger?: Logger, ): ApiConfig | undefined { let api: ApiConfig | undefined @@ -98,6 +101,22 @@ export function resolveApiServerConfig<Options extends ApiConfig & UserConfig>( api = { middlewareMode: true } } + if (!api.middlewareMode && api.host && api.host !== 'localhost' && api.host !== '127.0.0.1') {+ if (parentApi && api.allowWrite == null && api.allowExec == null) {+ logger?.error(+ c.yellow(+ `${c.yellowBright(' WARNING ')} API server is exposed to network, disabling write and exec operations by default for security reasons. This can cause some APIs to not work as expected. Set \`browser.api.allowExec\` manually to hide this warning. See https://vitest.dev/config/browser/api for more details.`,+ ),+ )+ }+ api.allowWrite ??= parentApi?.allowWrite ?? false+ api.allowExec ??= parentApi?.allowExec ?? false+ }+ else {+ api.allowWrite ??= parentApi?.allowWrite ?? true+ api.allowExec ??= parentApi?.allowExec ?? true+ }+ return api } @@ -838,6 +857,8 @@ export function resolveConfig( resolved.browser.api = resolveApiServerConfig( resolved.browser, defaultBrowserPort,+ resolved.api,+ logger, ) || { port: defaultBrowserPort, }@@ -5,6 +5,12 @@ import { basename, dirname, resolve } from 'node:path' import mime from 'mime/lite' import { isFileServingAllowed } from 'vitest/node' +function assertWrite(path: string, project: TestProject) {+ if (!project.config.browser.api.allowWrite || !project.vitest.config.api.allowWrite) {+ throw new Error(`Cannot modify file "${path}". File writing is disabled because server is exposed to the internet, see https://vitest.dev/config/browser/api.`)+ }+}+ function assertFileAccess(path: string, project: TestProject) { if ( !isFileServingAllowed(path, project.vite)@@ -34,6 +40,7 @@ export const writeFile: BrowserCommand< const filepath = resolve(project.config.root, path) assertFileAccess(filepath, project) const dir = dirname(filepath)+ assertWrite(path, project) if (!fs.existsSync(dir)) { await fsp.mkdir(dir, { recursive: true }) }@@ -45,6 +52,7 @@ export const removeFile: BrowserCommand< > = async ({ project }, path) => { const filepath = resolve(project.config.root, path) assertFileAccess(filepath, project)+ assertWrite(path, project) await fsp.rm(filepath) } @@ -128,6 +128,27 @@ export function setupBrowserRpc(globalServer: ParentBrowserProject, defaultMocke ) } + function isCdpAllowed(project: TestProject) {+ return (+ project.config.api.allowExec+ && project.config.browser.api.allowExec+ && project.vitest.config.api.allowExec+ && project.vitest.config.browser.api.allowExec+ && project.config.api.allowWrite+ && project.config.browser.api.allowWrite+ && project.vitest.config.api.allowWrite+ && project.vitest.config.browser.api.allowWrite+ )+ }++ function assertCdpAllowed(project: TestProject) {+ if (!isCdpAllowed(project)) {+ throw new Error(+ `Cannot use CDP because browser API write or exec operations are disabled. See https://vitest.dev/config/browser/api.`,+ )+ }+ }+ function setupClient(project: TestProject, rpcId: string, ws: WebSocket) { const mockResolver = new ServerMockResolver(globalServer.vite, { moduleDirectories: project.config.server?.deps?.moduleDirectories,@@ -271,6 +292,7 @@ export function setupBrowserRpc(globalServer: ParentBrowserProject, defaultMocke provider, contextId: sessionId, sessionId,+ __ensureCDPHandler: () => globalServer.ensureCDPHandler(sessionId, rpcId), }, provider.getCommandsContext(sessionId), ) as any as BrowserCommandContext@@ -344,10 +366,12 @@ export function setupBrowserRpc(globalServer: ParentBrowserProject, defaultMocke // CDP async sendCdpEvent(sessionId: string, event: string, payload?: Record<string, unknown>) {+ assertCdpAllowed(project) const cdp = await globalServer.ensureCDPHandler(sessionId, rpcId) return cdp.send(event, payload) }, async trackCdpEvent(sessionId: string, type: 'on' | 'once' | 'off', event: string, listenerId: string) {+ assertCdpAllowed(project) const cdp = await globalServer.ensureCDPHandler(sessionId, rpcId) cdp[type](event, listenerId) },@@ -245,6 +245,12 @@ export interface BrowserCommandContext { /** @deprecated use `sessionId` instead */ contextId: string sessionId: string+ /**+ * Returns Vitest's cached CDP handler for the current tester RPC connection.+ *+ * @internal+ */+ __ensureCDPHandler: () => Promise<any> } export interface BrowserServerStateSession {@@ -1,12 +1,15 @@+import type { Profiler } from 'node:inspector' import type { CoverageProviderModule } from 'vitest/node' import type { V8CoverageProvider } from './provider'-import { cdp } from '@vitest/browser/context' import { loadProvider } from './load-provider' -const session = cdp() let enabled = false -type ScriptCoverage = Awaited<ReturnType<typeof session.send<'Profiler.takePreciseCoverage'>>>+type ScriptCoverage = Profiler.TakePreciseCoverageReturnType++function triggerCommand(command: string, args: any[] = []): Promise<any> {+ return (globalThis as any).__vitest_browser_runner__.commands.triggerCommand(command, args)+} const mod: CoverageProviderModule = { async startCoverage() {@@ -16,15 +19,11 @@ const mod: CoverageProviderModule = { enabled = true - await session.send('Profiler.enable')- await session.send('Profiler.startPreciseCoverage', {- callCount: true,- detailed: true,- })+ await triggerCommand('__vitest_startV8Coverage') }, async takeCoverage(): Promise<{ result: any[] }> {- const coverage = await session.send('Profiler.takePreciseCoverage')+ const coverage: ScriptCoverage = await triggerCommand('__vitest_takeV8Coverage') const result: typeof coverage.result = [] // Reduce amount of data sent over rpc by doing some early result filteringAI-assisted change 31c3dfceba2499b82e89dccba89309378db4e208efb901919c7230262545b3e5 · Fix 814ac09862ebbdc9b3853b0a3d17cfa07f8710e5b05bf6bed7369544e0dc7674