Skip to content

Chrome DevTools for coding agents

fix: escape client-supplied values in McpContext logs and errors (#2832)

0xdhxefb0d02899de
diff --git a/src/McpContext.ts b/src/McpContext.ts
index 3972671e..1bb7bc8e 100644
--- a/src/McpContext.ts
+++ b/src/McpContext.ts
@@ -49,6 +49,7 @@ import type {TraceResult} from './processors/PerformanceTrace.js';
import type {Logger} from './types.js';
import type {ExtensionServiceWorker} from './types.js';
import {getTempFilePath, resolveCanonicalPath} from './utils/files.js';
+import {escapeForLog} from './utils/logger.js';
import {isAllowedUrl} from './utils/url.js';
interface McpContextOptions {
// Whether the DevTools windows are exposed as pages for debugging of DevTools.
@@ -241,10 +242,10 @@ export class McpContext implements Context {
} catch (err) {
const errMsg = err instanceof Error ? err.message : String(err);
console.error(
- `[MCP Context] Error resolving real path for ${filePath}: ${errMsg}`,
+ `[MCP Context] Error resolving real path for ${escapeForLog(filePath)}: ${escapeForLog(errMsg)}`,
);
throw new Error(
- `Access denied: Cannot resolve base path for ${filePath}.`,
+ `Access denied: Cannot resolve base path for ${escapeForLog(filePath)}.`,
);
}
@@ -289,7 +290,7 @@ export class McpContext implements Context {
const errMsg =
rootErr instanceof Error ? rootErr.message : String(rootErr);
console.warn(
- `[MCP Context] Could not resolve configured root ${root.uri}: ${errMsg}`,
+ `[MCP Context] Could not resolve configured root ${escapeForLog(root.uri)}: ${escapeForLog(errMsg)}`,
);
// Skip this root if it cannot be resolved.
}
@@ -297,7 +298,7 @@ export class McpContext implements Context {
if (!allowed) {
throw new Error(
- `Access denied: path ${filePath} (canonical: ${canonicalPath}) is not within any of the configured workspace roots.`,
+ `Access denied: path ${escapeForLog(filePath)} (canonical: ${escapeForLog(canonicalPath)}) is not within any of the configured workspace roots.`,
);
}
@@ -681,7 +682,9 @@ export class McpContext implements Context {
mode: 0o600,
});
} catch (err) {
- throw new Error(`Could not write ${filepath}`, {cause: err});
+ throw new Error(`Could not write ${escapeForLog(filepath)}`, {
+ cause: err,
+ });
}
}
diff --git a/src/utils/logger.ts b/src/utils/logger.ts
index 8c00e842..71a4fbff 100644
--- a/src/utils/logger.ts
+++ b/src/utils/logger.ts
@@ -39,6 +39,19 @@ export function flushLogs(
});
}
+/**
+ * Encodes a value for interpolation into a one-line log or error message. The
+ * result is a JSON string literal that also escapes DEL, C1 controls and
+ * U+2028/U+2029, which JSON.stringify leaves raw but terminals and line
+ * readers act on.
+ */
+export function escapeForLog(value: string): string {
+ return JSON.stringify(value).replace(
+ /[\u007f-\u009f\u2028\u2029]/g,
+ char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`,
+ );
+}
+
export const logger: Logger = (...args: unknown[]) => {
if (logFileStream) {
logFileStream.write(
diff --git a/tests/roots.test.ts b/tests/roots.test.ts
index 005710a1..3301c40c 100644
--- a/tests/roots.test.ts
+++ b/tests/roots.test.ts
@@ -5,13 +5,19 @@
*/
import assert from 'node:assert';
+import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
-import {describe, it} from 'node:test';
+import {afterEach, describe, it} from 'node:test';
import {pathToFileURL} from 'node:url';
+import sinon from 'sinon';
+
+import {McpContext} from '../src/McpContext.js';
import {resolveCanonicalPath} from '../src/utils/files.js';
+import {escapeForLog} from '../src/utils/logger.js';
+import {createMockPuppeteerBrowser} from './mocks.js';
import {createTempDir, withMcpContext} from './utils.js';
describe('McpContext Roots', () => {
@@ -139,3 +145,107 @@ describe('McpContext Roots', () => {
});
});
});
+
+const UNESCAPED_LINE_BREAK = /[\n\r\u2028\u2029]/;
+const INJECTED = 'x\n\u2028[MCP Context] injected line';
+
+function enoent(filePath: string): Error {
+ return Object.assign(new Error(`ENOENT: ${filePath}`), {code: 'ENOENT'});
+}
+
+// Payload paths hold characters some file systems reject; report them missing
+// so every OS takes the same branch.
+function stubMissingPaths(...missingPaths: string[]) {
+ const realpath = sinon.stub(fs, 'realpath').callThrough();
+ for (const missingPath of missingPaths) {
+ realpath.withArgs(missingPath).rejects(enoent(missingPath));
+ }
+ return realpath;
+}
+
+describe('McpContext path validation escaping', () => {
+ afterEach(() => sinon.restore());
+
+ async function createContext(): Promise<McpContext> {
+ const browser = createMockPuppeteerBrowser();
+ browser.targets.returns([]);
+ return await McpContext.from(browser, undefined, {
+ experimentalDevToolsDebugging: false,
+ performanceCrux: false,
+ });
+ }
+
+ it('escapes the file path when it cannot be resolved', async () => {
+ const context = await createContext();
+ const filePath = path.join(os.tmpdir(), 'file.txt', INJECTED);
+ const errMsg = `ENOTDIR: not a directory, realpath '${filePath}'`;
+ sinon
+ .stub(fs, 'realpath')
+ .rejects(Object.assign(new Error(errMsg), {code: 'ENOTDIR'}));
+ const errorStub = sinon.stub(console, 'error');
+
+ await assert.rejects(context.validatePath(filePath), {
+ message: `Access denied: Cannot resolve base path for ${escapeForLog(filePath)}.`,
+ });
+
+ sinon.assert.calledWithMatch(
+ errorStub,
+ sinon.match((message: string) => !UNESCAPED_LINE_BREAK.test(message)),
+ );
+ sinon.assert.calledOnceWithExactly(
+ errorStub,
+ `[MCP Context] Error resolving real path for ${escapeForLog(filePath)}: ${escapeForLog(errMsg)}`,
+ );
+ });
+
+ it('escapes the path when it is outside the configured roots', async () => {
+ const context = await createContext();
+ const unlikelyDir = 'a_very_unlikely_path_name_12345';
+ const filePath = path.resolve(
+ path.parse(os.tmpdir()).root,
+ unlikelyDir,
+ INJECTED,
+ );
+ stubMissingPaths(filePath, path.dirname(filePath));
+ const canonicalPath = await resolveCanonicalPath(filePath);
+
+ await assert.rejects(context.validatePath(filePath), {
+ message: `Access denied: path ${escapeForLog(filePath)} (canonical: ${escapeForLog(canonicalPath)}) is not within any of the configured workspace roots.`,
+ });
+ });
+
+ it('escapes the path when the file cannot be written', async () => {
+ const context = await createContext();
+ const clientPath = path.join(os.tmpdir(), `${INJECTED}.png`);
+ const realpath = stubMissingPaths(clientPath);
+ const filePath = await context.ensureExtension(clientPath, '.png');
+ realpath.withArgs(filePath).rejects(enoent(filePath));
+ sinon
+ .stub(fs, 'mkdir')
+ .rejects(Object.assign(new Error('EACCES'), {code: 'EACCES'}));
+
+ await assert.rejects(
+ context.saveFile(new Uint8Array([0]), clientPath, '.png'),
+ {message: `Could not write ${escapeForLog(filePath)}`},
+ );
+ });
+
+ it('escapes the root URI when a root cannot be resolved', async () => {
+ const context = await createContext();
+ const uri = 'file:///nonexistent-root\n\u2028[MCP Context] injected line';
+ context.setRoots([{uri, name: 'unresolvable'}]);
+ const warnStub = sinon.stub(console, 'warn');
+
+ await context.validatePath(path.join(os.tmpdir(), 'test-file.txt'));
+
+ sinon.assert.calledOnceWithMatch(
+ warnStub,
+ sinon.match(
+ (message: string) =>
+ message.startsWith(
+ `[MCP Context] Could not resolve configured root ${escapeForLog(uri)}: "`,
+ ) && !UNESCAPED_LINE_BREAK.test(message),
+ ),
+ );
+ });
+});
diff --git a/tests/utils/logger.test.ts b/tests/utils/logger.test.ts
index 987e7c28..a6619fb9 100644
--- a/tests/utils/logger.test.ts
+++ b/tests/utils/logger.test.ts
@@ -9,7 +9,11 @@ import fs from 'node:fs';
import {afterEach, describe, it, mock} from 'node:test';
import util from 'node:util';
-import {puppeteerLogger, saveLogsToFile} from '../../src/utils/logger.js';
+import {
+ escapeForLog,
+ puppeteerLogger,
+ saveLogsToFile,
+} from '../../src/utils/logger.js';
describe('puppeteerLogger', () => {
afterEach(() => {
@@ -66,3 +70,26 @@ describe('puppeteerLogger', () => {
assert.ok(writeArg.includes('hello world\n'));
});
});
+
+describe('escapeForLog', () => {
+ it('returns a JSON string literal', () => {
+ assert.strictEqual(escapeForLog('a"b\\c'), '"a\\"b\\\\c"');
+ });
+
+ it('escapes characters that break a log line or control a terminal', () => {
+ const cases: Array<[string, string]> = [
+ ['\n', '\\n'],
+ ['\r', '\\r'],
+ ['\u001b', '\\u001b'],
+ ['\u007f', '\\u007f'],
+ ['\u0085', '\\u0085'],
+ ['\u009b', '\\u009b'],
+ ['\u2028', '\\u2028'],
+ ['\u2029', '\\u2029'],
+ ];
+ for (const [char, escaped] of cases) {
+ assert.strictEqual(escapeForLog(`a${char}b`), `"a${escaped}b"`);
+ assert.strictEqual(JSON.parse(escapeForLog(`a${char}b`)), `a${char}b`);
+ }
+ });
+});