Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 67 additions & 15 deletions src/backends/adb-backend.test.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 () => {
Expand Down Expand Up @@ -813,6 +822,7 @@ describe('AdbBackend.tapElement', () => {
[
'adb',
['-s', 'emulator-5554', 'shell', 'dumpsys', 'window', 'InputMethod'],
{ secret: undefined },
],
]);
expect(tapCalls()).toHaveLength(0);
Expand Down Expand Up @@ -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<typeof execModule>('../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<typeof execFile>;
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 () => {
Expand Down Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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 () => {
Expand Down
13 changes: 9 additions & 4 deletions src/backends/adb-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { loadHelperArtifact } from './android-instrumentation/artifact.js';
import {
assertClipboardWriteSucceeded,
buildClipboardInstrumentArgs,
encodeClipboardText,
} from './android-instrumentation/clipboard.js';
import {
isHelperIncompleteCaptureError,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -274,8 +276,8 @@ export class AdbBackend implements DeviceBackend {
this.#snapshotModeOption = options.snapshotMode;
}

async #adb(args: string[]): Promise<string> {
return execStrict('adb', ['-s', this.#serial, ...args]);
async #adb(args: string[], secret?: ExecSecret): Promise<string> {
return execStrict('adb', ['-s', this.#serial, ...args], { secret });
}

async ensureConnected(): Promise<void> {
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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.
Expand Down
6 changes: 5 additions & 1 deletion src/backends/android-instrumentation/clipboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand All @@ -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',
Expand Down
66 changes: 53 additions & 13 deletions src/backends/idb-backend.test.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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 },
);
});
});

Expand All @@ -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 },
);
});
});

Expand Down Expand Up @@ -2941,13 +2946,48 @@ 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(),
expect.anything(),
);
});

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<typeof execModule>('../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<typeof execFile>;
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('');

Expand Down
21 changes: 12 additions & 9 deletions src/backends/idb-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -252,12 +253,16 @@ export class IdbBackend implements DeviceBackend {
await this.#disposing;
}

async #execStrict(command: string, args: string[]): Promise<string> {
async #execStrict(
command: string,
args: string[],
secret?: ExecSecret,
): Promise<string> {
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 }),
);
}

Expand Down Expand Up @@ -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(
Expand Down
Loading
Loading