diff --git a/src/backends/adb-backend.test.ts b/src/backends/adb-backend.test.ts index 2291152..43b95ec 100644 --- a/src/backends/adb-backend.test.ts +++ b/src/backends/adb-backend.test.ts @@ -1,4 +1,5 @@ /* eslint-disable n/no-process-env -- these tests toggle DEVICE_MCP_ADB_SNAPSHOT to exercise snapshot-mode selection */ +import { execFile } from 'node:child_process'; import { readFile, readdir } from 'node:fs/promises'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; @@ -28,6 +29,11 @@ vi.mock('node:fs/promises', () => ({ readdir: vi.fn(), })); +vi.mock('node:child_process', () => ({ + execFile: vi.fn(), + spawn: vi.fn(), +})); + vi.mock('../utils/exec.js', () => ({ exec: vi.fn(), execStrict: vi.fn(), @@ -56,7 +62,14 @@ vi.mock('./webview-cdp.js', () => ({ const mockExecStrict = vi.mocked(execModule.execStrict); const mockExec = vi.mocked(execModule.exec); +const mockExecFile = vi.mocked(execFile); const mockReadFile = vi.mocked(readFile); + +type ExecFileCallback = ( + error: (Error & { code?: string }) | null, + stdout: string, + stderr: string, +) => void; const mockEnsureHelperInstalled = vi.mocked(ensureHelperInstalled); const mockAssertInstalledHelperTrusted = vi.mocked( assertInstalledHelperTrusted, @@ -652,15 +665,11 @@ describe('AdbBackend.tapElement', () => { expect( mockExecStrict.mock.calls.map(([, args]) => args?.[3]), ).toStrictEqual(['wm', 'input']); - expect(mockExecStrict).toHaveBeenCalledWith('adb', [ - '-s', - 'emulator-5554', - 'shell', - 'input', - 'tap', - '300', - '230', - ]); + expect(mockExecStrict).toHaveBeenCalledWith( + 'adb', + ['-s', 'emulator-5554', 'shell', 'input', 'tap', '300', '230'], + { secret: undefined }, + ); }); it('reads the screen size once per backend', async () => { @@ -813,6 +822,7 @@ describe('AdbBackend.tapElement', () => { [ 'adb', ['-s', 'emulator-5554', 'shell', 'dumpsys', 'window', 'InputMethod'], + { secret: undefined }, ], ]); expect(tapCalls()).toHaveLength(0); @@ -932,6 +942,41 @@ describe('AdbBackend.typeText', () => { ['input', 'keyevent', '67'], ['input', 'text', 'a%sb\\&c'], ]); + expect(mockExecStrict).toHaveBeenCalledWith( + 'adb', + ['-s', 'emulator-5554', 'shell', 'input', 'text', 'a%sb\\&c'], + { secret: ['a b&c', 'a%sb\\&c'] }, + ); + }); + + it('masks the typed text when input text fails', async () => { + // Real execStrict: the failure under test is the one built from argv and + // stderr, not a mock's error. + const { execStrict: runExecStrict } = + await vi.importActual('../utils/exec.js'); + mockExecStrict.mockImplementation(runExecStrict); + mockExecFile.mockImplementation((_command, args, _options, callback) => { + const failing = args?.includes('text') ?? false; + const child = { + exitCode: failing ? 1 : 0, + } as unknown as ReturnType; + process.nextTick(() => { + (callback as ExecFileCallback)( + failing ? Object.assign(new Error('exit 1'), { code: 'ERR' }) : null, + '', + failing ? 'Error: cannot type hunter2%sx' : '', + ); + }); + return child; + }); + + const failure = await backend.typeText('hunter2 x').then( + () => null, + (caught: unknown) => caught, + ); + + expect(String(failure)).not.toContain('hunter2'); + expect(String(failure)).toContain('•••'); }); it('only clears the field for an empty string', async () => { @@ -1033,12 +1078,16 @@ describe('AdbBackend.dismissKeyboard', () => { await backend.dismissKeyboard(); - expect(mockExecStrict).toHaveBeenCalledWith('adb', [ - '-s', - 'emulator-5554', - 'shell', - 'dumpsys input_method | grep -m1 mInputShown || true', - ]); + expect(mockExecStrict).toHaveBeenCalledWith( + 'adb', + [ + '-s', + 'emulator-5554', + 'shell', + 'dumpsys input_method | grep -m1 mInputShown || true', + ], + { secret: undefined }, + ); }); it('sends ESCAPE and checks that the keyboard hid', async () => { @@ -2068,6 +2117,9 @@ describe('AdbBackend clipboard', () => { expect(args.slice(0, 2)).toStrictEqual(['-s', 'emulator-5554']); const encoded = args[args.indexOf('textB64') + 1]; expect(Buffer.from(encoded, 'base64').toString('utf8')).toBe(SECRET); + expect(mockExec.mock.calls[0]?.[2]).toMatchObject({ + secret: [SECRET, encoded], + }); }); it('installs and trust-checks the helper before writing', async () => { diff --git a/src/backends/adb-backend.ts b/src/backends/adb-backend.ts index 68393e8..14b9e7d 100644 --- a/src/backends/adb-backend.ts +++ b/src/backends/adb-backend.ts @@ -16,6 +16,7 @@ import { loadHelperArtifact } from './android-instrumentation/artifact.js'; import { assertClipboardWriteSucceeded, buildClipboardInstrumentArgs, + encodeClipboardText, } from './android-instrumentation/clipboard.js'; import { isHelperIncompleteCaptureError, @@ -69,6 +70,7 @@ import { visibleCenter, } from '../utils/element.js'; import { exec, execStrict, isCommandAvailable } from '../utils/exec.js'; +import type { ExecSecret } from '../utils/exec.js'; import { hardenArtifactFile, resolveArtifactPath, @@ -274,8 +276,8 @@ export class AdbBackend implements DeviceBackend { this.#snapshotModeOption = options.snapshotMode; } - async #adb(args: string[]): Promise { - return execStrict('adb', ['-s', this.#serial, ...args]); + async #adb(args: string[], secret?: ExecSecret): Promise { + return execStrict('adb', ['-s', this.#serial, ...args], { secret }); } async ensureConnected(): Promise { @@ -399,7 +401,7 @@ export class AdbBackend implements DeviceBackend { } // Android input text requires escaping spaces and special chars const escaped = text.replace(/ /gu, '%s').replace(/[&|;<>]/gu, '\\$&'); - await this.#adb(['shell', 'input', 'text', escaped]); + await this.#adb(['shell', 'input', 'text', escaped], [text, escaped]); } async swipe( @@ -1246,7 +1248,10 @@ export class AdbBackend implements DeviceBackend { const { stdout, stderr } = await exec( 'adb', ['-s', this.#serial, ...buildClipboardInstrumentArgs(runner, text)], - { timeoutMs: CLIPBOARD_TIMEOUT_MS }, + { + timeoutMs: CLIPBOARD_TIMEOUT_MS, + secret: [text, encodeClipboardText(text)], + }, ); // `am` reports a missing runner as an exception on stderr. diff --git a/src/backends/android-instrumentation/clipboard.ts b/src/backends/android-instrumentation/clipboard.ts index 8f8b60f..055ebf0 100644 --- a/src/backends/android-instrumentation/clipboard.ts +++ b/src/backends/android-instrumentation/clipboard.ts @@ -21,6 +21,10 @@ export const CLIPBOARD_TEXT_ARG = 'textB64'; */ const SUCCESS_INSTRUMENTATION_CODE = '-1'; +export function encodeClipboardText(text: string): string { + return Buffer.from(text, 'utf8').toString('base64'); +} + /** * Build the `adb shell` arguments that write `text` to the device clipboard. * @@ -32,7 +36,7 @@ export function buildClipboardInstrumentArgs( runner: string, text: string, ): string[] { - const encoded = Buffer.from(text, 'utf8').toString('base64'); + const encoded = encodeClipboardText(text); return [ 'shell', 'am', diff --git a/src/backends/idb-backend.test.ts b/src/backends/idb-backend.test.ts index 94a89c8..faacc3a 100644 --- a/src/backends/idb-backend.test.ts +++ b/src/backends/idb-backend.test.ts @@ -1,4 +1,4 @@ -import { spawn } from 'node:child_process'; +import { execFile, spawn } from 'node:child_process'; import { EventEmitter } from 'node:events'; import { readFileSync } from 'node:fs'; import { readFile } from 'node:fs/promises'; @@ -63,6 +63,13 @@ vi.mock('../utils/platform.js', () => ({ const mockExec = vi.mocked(execModule.exec); const mockExecStrict = vi.mocked(execModule.execStrict); +const mockExecFile = vi.mocked(execFile); + +type ExecFileCallback = ( + error: (Error & { code?: string }) | null, + stdout: string, + stderr: string, +) => void; const mockReadFile = vi.mocked(readFile); const mockSupportsApi = vi.mocked(platformModule.idbSupportsApiSelection); const mockChooseAxApi = vi.mocked(platformModule.chooseAxApi); @@ -452,12 +459,11 @@ describe('IdbBackend simctl fallback', () => { await backend.openApp('io.metamask'); expect(mockExecStrict).toHaveBeenCalledTimes(2); - expect(mockExecStrict).toHaveBeenLastCalledWith('xcrun', [ - 'simctl', - 'launch', - udid, - 'io.metamask', - ]); + expect(mockExecStrict).toHaveBeenLastCalledWith( + 'xcrun', + ['simctl', 'launch', udid, 'io.metamask'], + { secret: undefined }, + ); }); }); @@ -481,12 +487,11 @@ describe('IdbBackend simctl fallback', () => { await backend.closeApp('io.metamask'); - expect(mockExecStrict).toHaveBeenLastCalledWith('xcrun', [ - 'simctl', - 'terminate', - udid, - 'io.metamask', - ]); + expect(mockExecStrict).toHaveBeenLastCalledWith( + 'xcrun', + ['simctl', 'terminate', udid, 'io.metamask'], + { secret: undefined }, + ); }); }); @@ -2941,6 +2946,11 @@ describe('IdbBackend keys and buttons', () => { ['ui', 'key', '42', '--udid', udid], ['ui', 'text', 'hello world', '--udid', udid], ]); + expect(mockExecStrict).toHaveBeenCalledWith( + idb, + ['ui', 'text', 'hello world', '--udid', udid], + { env: connectionOptions.env, secret: 'hello world' }, + ); expect(mockExec).not.toHaveBeenCalledWith( idb, expect.anything(), @@ -2948,6 +2958,36 @@ describe('IdbBackend keys and buttons', () => { ); }); + it('masks the typed text when ui text fails', async () => { + // Real execStrict: the failure under test is the one built from argv and + // stderr, not a mock's error. + const { execStrict: runExecStrict } = + await vi.importActual('../utils/exec.js'); + mockExecStrict.mockImplementation(runExecStrict); + mockExecFile.mockImplementation((_command, args, _options, callback) => { + const failing = args?.[1] === 'text'; + const child = { + exitCode: failing ? 1 : 0, + } as unknown as ReturnType; + process.nextTick(() => { + (callback as ExecFileCallback)( + failing ? Object.assign(new Error('exit 1'), { code: 'ERR' }) : null, + '', + failing ? 'idb: could not type "hunter2 x"' : '', + ); + }); + return child; + }); + + const failure = await backend.typeText('hunter2 x').then( + () => null, + (caught: unknown) => caught, + ); + + expect(String(failure)).not.toContain('hunter2'); + expect(String(failure)).toContain('•••'); + }); + it('only clears the field for an empty string', async () => { await backend.typeText(''); diff --git a/src/backends/idb-backend.ts b/src/backends/idb-backend.ts index c6c47bb..5fd0fb2 100644 --- a/src/backends/idb-backend.ts +++ b/src/backends/idb-backend.ts @@ -31,6 +31,7 @@ import { visibleCenter, } from '../utils/element.js'; import { execStrict, exec } from '../utils/exec.js'; +import type { ExecSecret } from '../utils/exec.js'; import { hitsTarget, TargetObscuredError } from '../utils/hit-test.js'; import { hardenArtifactFile, @@ -252,12 +253,16 @@ export class IdbBackend implements DeviceBackend { await this.#disposing; } - async #execStrict(command: string, args: string[]): Promise { + async #execStrict( + command: string, + args: string[], + secret?: ExecSecret, + ): Promise { if (command !== this.#idbPath) { - return execStrict(command, args); + return execStrict(command, args, { secret }); } return this.#idb(args, async () => - execStrict(command, args, { env: this.#connection.env }), + execStrict(command, args, { env: this.#connection.env, secret }), ); } @@ -775,13 +780,11 @@ export class IdbBackend implements DeviceBackend { if (text.length === 0) { return; } - await this.#execStrict(this.#idbPath, [ - 'ui', - 'text', + await this.#execStrict( + this.#idbPath, + ['ui', 'text', text, '--udid', this.#udid], text, - '--udid', - this.#udid, - ]); + ); } async swipe( diff --git a/src/utils/exec.test.ts b/src/utils/exec.test.ts index f850c06..b200b53 100644 --- a/src/utils/exec.test.ts +++ b/src/utils/exec.test.ts @@ -1,7 +1,7 @@ import * as childProcess from 'node:child_process'; import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { exec, execStrict, isCommandAvailable } from './exec.js'; +import { exec, execStrict, isCommandAvailable, REDACTED } from './exec.js'; vi.mock('node:child_process', () => ({ execFile: vi.fn(), @@ -139,6 +139,58 @@ describe('execStrict', () => { 'Command failed: cmd arg', ); }); + + it.each([ + { + form: 'raw', + command: 'idb', + args: ['ui', 'text', 'hunter2 x', '--udid', 'UDID'], + secret: 'hunter2 x', + stderr: 'idb: could not type "hunter2 x"', + }, + { + form: 'escaped', + command: 'adb', + args: ['-s', 'emulator-5556', 'shell', 'input', 'text', 'hunter2%sx'], + secret: ['hunter2 x', 'hunter2%sx'], + stderr: 'adb: cannot type hunter2%sx', + }, + ])( + 'masks a secret in its $form argv form and in stderr', + async (testCase) => { + const error = Object.assign(new Error('exit 1'), { code: 'ERR' }); + simulateExecFile(error, '', testCase.stderr, 1); + + const failure = await execStrict(testCase.command, testCase.args, { + secret: testCase.secret, + }).then( + () => null, + (caught: unknown) => caught, + ); + + expect(String(failure)).not.toContain('hunter2'); + expect(String(failure)).toContain(REDACTED); + }, + ); + + it('ignores an empty secret', async () => { + const error = Object.assign(new Error('exit 1'), { code: 'ERR' }); + simulateExecFile(error, '', 'boom', 1); + + await expect( + execStrict('cmd', ['hunter2 x'], { secret: '' }), + ).rejects.toThrow('Command failed: cmd hunter2 x'); + }); + + it('returns stdout unchanged when a secret-bearing call succeeds', async () => { + simulateExecFile(null, 'hunter2 x', '', 0); + + const stdout = await execStrict('cmd', ['hunter2 x'], { + secret: 'hunter2 x', + }); + + expect(stdout).toBe('hunter2 x'); + }); }); describe('isCommandAvailable', () => { diff --git a/src/utils/exec.ts b/src/utils/exec.ts index 5bda392..d145a5e 100644 --- a/src/utils/exec.ts +++ b/src/utils/exec.ts @@ -6,21 +6,38 @@ export type ExecResult = { exitCode: number; }; +export const REDACTED = '•••'; + +export type ExecSecret = string | readonly string[]; + +export type ExecOptions = ExecFileOptions & { + timeoutMs?: number; + /** Text to mask in failure messages, in each form it takes on argv. */ + secret?: ExecSecret; +}; + +function maskSecrets(text: string, secret: ExecSecret | undefined): string { + const secrets = typeof secret === 'string' ? [secret] : (secret ?? []); + return secrets + .filter((value) => value.length > 0) + .reduce((masked, value) => masked.split(value).join(REDACTED), text); +} + /** * Execute a command and return stdout/stderr/exitCode. * Rejects only on spawn failure — non-zero exit codes are returned, not thrown. * * @param command - The command to execute. * @param args - Arguments to pass to the command. - * @param options - Execution options including timeoutMs. + * @param options - Execution options including timeoutMs and secret. * @returns The stdout, stderr, and exit code. */ export async function exec( command: string, args: string[], - options?: ExecFileOptions & { timeoutMs?: number }, + options?: ExecOptions, ): Promise { - const { timeoutMs = 30_000, ...execOptions } = options ?? {}; + const { timeoutMs = 30_000, secret, ...execOptions } = options ?? {}; return new Promise((resolve, reject) => { const child = execFile( @@ -39,7 +56,7 @@ export async function exec( errno.code === 'EACCES' || errno.code === 'EPERM' ) { - reject(new Error(error.message)); + reject(new Error(maskSecrets(error.message, secret))); return; } } @@ -56,14 +73,17 @@ export async function exec( export async function execStrict( command: string, args: string[], - options?: ExecFileOptions & { timeoutMs?: number }, + options?: ExecOptions, ): Promise { const result = await exec(command, args, options); if (result.exitCode !== 0) { throw new Error( - `Command failed: ${command} ${args.join(' ')}\n` + - `Exit code: ${result.exitCode}\n` + - `stderr: ${result.stderr}`, + maskSecrets( + `Command failed: ${command} ${args.join(' ')}\n` + + `Exit code: ${result.exitCode}\n` + + `stderr: ${result.stderr}`, + options?.secret, + ), ); } return result.stdout;