Skip to content
Closed
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
5 changes: 5 additions & 0 deletions .changeset/electron-owned-switches.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@e2e-dev/electron': patch
---

`app.launchArguments` and `electron.launch({ launchArguments })` refuse the switches the engine owns however Chromium would read them: after one dash as well as two (`-remote-debugging-port=9222`), with whitespace around them, after a slash and in any letter case on Windows, and Node's other inspector switches (`--inspect-port`, `--inspect-wait`, `--inspect-brk-node`, `--debug-port`). Each one used to reach the app and could open a second debugging port or break the launch. A packaged app named by its `.asar` archive is bound to that archive when Electron does not report the app's path, so a window that shows a file next to the archive is not observed.
7 changes: 5 additions & 2 deletions docs/reference/electron.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,11 @@ them.
| `--user-data-dir=<directory>` | The test's own [user-data directory](#userdatadir). |

`app.launchArguments` and `launch({ launchArguments })` must not set `--user-data-dir`,
`--inspect`, `--inspect-brk`, `--remote-debugging-port`, or
`--remote-debugging-pipe`: the engine owns them.
`--inspect`, `--inspect-brk`, `--inspect-brk-node`, `--inspect-port`,
`--inspect-wait`, `--debug-port`, `--remote-debugging-port`, or
`--remote-debugging-pipe`, with two dashes or one (or, on Windows, a slash, in
any letter case), with or without whitespace around them, as Chromium reads
them: the engine owns them.
Comment thread
kdy1 marked this conversation as resolved.
Resolved

#### Environment

Expand Down
2 changes: 1 addition & 1 deletion packages/electron/src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ function validateApp(app: EngineAppDeclaration, { targetName }: EngineAppCheckIn
}
if (app.bundleId !== undefined) throw new ConfigurationError('INVALID_CONFIG', `${where} declares app.bundleId, which an electron() target cannot launch; name the app with app.appPath`);
if (app.permissions !== undefined) throw new ConfigurationError('INVALID_CONFIG', `${where} declares app.permissions, which an electron() target cannot set`);
const owned = app.launchArguments?.map(ownedArgument).find((reason) => reason !== undefined);
const owned = app.launchArguments?.map((argument) => ownedArgument(argument)).find((reason) => reason !== undefined);
if (owned !== undefined) throw new ConfigurationError('INVALID_CONFIG', `${where} app.launchArguments ${owned}`);
if (app.appPath === undefined && executablePath === undefined) {
throw new ConfigurationError(
Expand Down
2 changes: 1 addition & 1 deletion packages/electron/src/file-bound.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export function appDirectory({ reported, declared, firstDocument, projectRoot }:
// An `.asar` archive is a file too, and the app itself, as Electron reports it: its bound is the archive.
if (declared !== undefined && !/\.asar$/i.test(declared) && statSync(declared, { throwIfNoEntry: false })?.isFile() === true) return canonical(packageOf(declared, projectRoot) ?? path.dirname(declared));
if (reported !== undefined && reported !== '') return canonical(reported);
if (declared !== undefined) return canonical(statSync(declared, { throwIfNoEntry: false })?.isDirectory() === true ? declared : path.dirname(declared));
if (declared !== undefined) return canonical(/\.asar$/i.test(declared) || statSync(declared, { throwIfNoEntry: false })?.isDirectory() === true ? declared : path.dirname(declared));
const file = localFile(firstDocument);
if (file === undefined) return undefined;
const archive = /^(.*?\.asar)(?:[\\/]|$)/.exec(file)?.[1];
Expand Down
19 changes: 13 additions & 6 deletions packages/electron/src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,23 @@ export interface ResolvedElectronOptions {
* the DevTools transport the engine drives the app through (a fixed port
* would also collide between workers).
*/
export function ownedArgument(argument: string): string | undefined {
if (/^--user-data-dir(=|$)/.test(argument)) return 'must not set --user-data-dir: the engine gives every attempt an empty one of its own';
const port = /^(--inspect(-brk)?|--remote-debugging-port|--remote-debugging-pipe)(=|$)/.exec(argument);
if (port !== null) return `must not set ${port[1]}: the engine opens the inspector and the DevTools pipe it drives the app through itself`;
export function ownedArgument(argument: string, platform: NodeJS.Platform = process.platform): string | undefined {
// Chromium trims the whitespace around an argument, then reads a switch after one dash as after two,
// and on Windows after a slash too, with its name lowercased.
const name =
platform === 'win32'
? /^(?:--?|\/)([a-z][a-z-]*)(?:=|$)/i.exec(argument.trim())?.[1]?.toLowerCase()
: /^--?([a-z][a-z-]*)(?:=|$)/.exec(argument.trim())?.[1];
Comment thread
kdy1 marked this conversation as resolved.
Resolved
if (name === 'user-data-dir') return 'must not set --user-data-dir: the engine gives every attempt an empty one of its own';
if (name !== undefined && /^(inspect(-brk|-brk-node|-port|-wait)?|debug-port|remote-debugging-port|remote-debugging-pipe)$/.test(name)) {
return `must not set --${name}: the engine opens the inspector and the DevTools pipe it drives the app through itself`;
}
return undefined;
}

/** Checks the target's `app.launchArguments`: the app's own switches and Chromium's, none of the engine's. */
export function checkLaunchArguments(launchArguments: readonly string[] | undefined): void {
const owned = launchArguments?.map(ownedArgument).find((reason) => reason !== undefined);
const owned = launchArguments?.map((argument) => ownedArgument(argument)).find((reason) => reason !== undefined);
if (owned !== undefined) throw new ConfigurationError('INVALID_CONFIG', `app.launchArguments ${owned}`);
}

Expand Down Expand Up @@ -154,7 +161,7 @@ export function checkLaunchOptions(options: unknown, projectRoot: string): { rea
rejectUnknownKeys(`${label} options`, options, LAUNCH_KEYS, 'INVALID_ARGUMENT');
const { launchArguments: args = [], env, cwd } = options as { readonly launchArguments?: unknown; readonly env?: unknown; readonly cwd?: unknown };
if (!Array.isArray(args) || args.some((argument) => typeof argument !== 'string')) throw refusal('INVALID_ARGUMENT', 'electron.launch({ launchArguments }) must be a list of strings');
const owned = (args as string[]).map(ownedArgument).find((reason) => reason !== undefined);
const owned = (args as string[]).map((argument) => ownedArgument(argument)).find((reason) => reason !== undefined);
if (owned !== undefined) throw refusal('INVALID_ARGUMENT', `electron.launch({ launchArguments }) ${owned}`);
checkEnv('electron.launch({ env })', env, 'INVALID_ARGUMENT');
checkCwdShape('electron.launch({ cwd })', cwd, 'INVALID_ARGUMENT');
Expand Down
42 changes: 42 additions & 0 deletions packages/electron/tests/integration/launch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { DevTools } from '../../src/devtools.ts';
import { ensureFfmpeg } from '../../src/ffmpeg.ts';
import { readWindow } from '../../src/locate.ts';
import { resolveOptions } from '../../src/options.ts';
import { ElectronSurface } from '../../src/surface.ts';
import { Recorder } from '../../src/video.ts';
import { DialogRouter } from '../../src/dialogs.ts';
import { Windows, type AppWindow } from '../../src/windows.ts';
Expand Down Expand Up @@ -327,6 +328,47 @@ describe('dialogs', () => {
});
});

describe('the local file bound', () => {
it('sends an observation, keeps a trace screen, and records frames of the app\'s own pages only', async () => {
const { app, windows, dialogs, directory, launch } = appWith(`app.whenReady().then(() => new BrowserWindow({ show: false }).loadFile(require('node:path').join(__dirname, 'index.html')));`);
writeFileSync(path.join(directory, 'index.html'), '<title>Own</title><h1>Own page</h1>');
await launch();
const elsewhere = mkdtempSync(path.join(tmpdir(), 'e2e-electron-elsewhere-'));
directories.push(elsewhere);
const outside = path.join(elsewhere, 'outside.html');
writeFileSync(outside, '<title>Outside</title><h1>Outside page</h1>');
// The surface over this test's app, as the engine holds it mid-attempt, its trace collecting each screen it is handed.
const surface = new ElectronSurface(resolveOptions({}));
const screens: unknown[] = [];
const ffmpeg = await ensureFfmpeg(process.env, new AbortController().signal);
Object.assign(surface, { app, windowList: windows, dialogs, runEnv: { E2E_FFMPEG_PATH: ffmpeg }, attempt: { artifactsDir: path.join(directory, 'artifacts'), screen: (screen: unknown) => void screens.push(screen) } });
const operation = { signal: new AbortController().signal, timeoutMs: 5000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext;
const heading = (name: string) => ({ kind: 'query', query: { kind: 'role', value: { kind: 'string', value: 'heading', exact: true }, name: { kind: 'string', value: name, exact: true } } }) as const;
const traceScreen = (): Promise<void> => (Reflect.get(surface, 'traceScreen') as () => Promise<void>).call(surface);
await surface.startVideo(operation);
try {
const recorded = Reflect.get(Reflect.get(surface, 'recorder') as object, 'allowed') as (page: unknown) => boolean;

expect((await surface.observe(operation)).location).toMatch(/index\.html$/);
expect(await surface.locate(heading('Own page'), operation)).toHaveLength(1);
await traceScreen();
expect(screens).toHaveLength(2);
expect(recorded(windows.require().page)).toBe(true);

await app.evaluate(({ BrowserWindow }, file) => BrowserWindow.getAllWindows()[0]?.loadFile(file), outside);
await expect.poll(() => windows.require().page.url()).toMatch(/outside\.html$/);
await expect(surface.observe(operation)).rejects.toMatchObject({ code: 'POLICY_DENIED', message: expect.stringMatching(/left the app's directory/) as string });
// The test's own locator still finds what the window shows; the trace gets no screen of it.
expect(await surface.locate(heading('Outside page'), operation)).toHaveLength(1);
await traceScreen();
expect(screens).toHaveLength(2);
expect(recorded(windows.require().page)).toBe(false);
} finally {
await surface.stopVideo();
}
});
});

describe('electron.evaluate', () => {
it('returns a number JSON has no word for, and refuses an argument that is not JSON as the test\'s own mistake', async () => {
const { app, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`);
Expand Down
16 changes: 15 additions & 1 deletion packages/electron/tests/unit/engine.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { electron } from '../../src/engine.ts';
import { checkCwd, checkLaunchArguments, checkLaunchOptions, resolveOptions } from '../../src/options.ts';
import { checkCwd, checkLaunchArguments, checkLaunchOptions, ownedArgument, resolveOptions } from '../../src/options.ts';

describe('electron()', () => {
it('declares the capabilities of a Chromium window driven over the DevTools protocol', () => {
Expand Down Expand Up @@ -49,7 +49,21 @@ describe('resolveOptions', () => {
expect(() => checkLaunchArguments(['--user-data-dir=/tmp/x'])).toThrow(/app\.launchArguments must not set --user-data-dir/);
// The engine opens the inspector and the DevTools pipe itself; a fixed port also collides between workers.
expect(() => checkLaunchArguments(['--inspect=9229'])).toThrow(/--inspect/);
// Node's other inspector switches move its port too, or open it before the engine's.
for (const argument of ['--inspect-port=9229', '--debug-port=9229', '--inspect-brk-node', '--inspect-wait=9229']) expect(() => checkLaunchArguments([argument]), argument).toThrow(new RegExp(`must not set ${argument.split('=')[0]!}`));
expect(() => checkLaunchArguments(['--remote-debugging-port=9222'])).toThrow(/--remote-debugging-port/);
// Chromium takes a switch after one dash too, and on Windows after a slash.
expect(() => checkLaunchArguments(['-remote-debugging-port=9341'])).toThrow(/must not set --remote-debugging-port/);
expect(() => checkLaunchArguments(['-user-data-dir=/tmp/x'])).toThrow(/must not set --user-data-dir/);
expect(ownedArgument('/user-data-dir=C:\\x', 'win32')).toMatch(/must not set --user-data-dir/);
expect(ownedArgument('/user-data-dir', 'linux')).toBeUndefined();
// Chromium on Windows lowercases a switch's name; elsewhere --USER-DATA-DIR is another switch.
expect(ownedArgument('/USER-DATA-DIR=C:\\shared', 'win32')).toMatch(/must not set --user-data-dir/);
expect(ownedArgument('--Inspect=9229', 'win32')).toMatch(/must not set --inspect:/);
expect(ownedArgument('--USER-DATA-DIR=/tmp/x', 'linux')).toBeUndefined();
// Chromium trims the whitespace around an argument before it reads a switch.
expect(() => checkLaunchArguments([' -user-data-dir=/tmp/shared'])).toThrow(/must not set --user-data-dir/);
expect(() => checkLaunchArguments(['\t--inspect=9229\n'])).toThrow(/must not set --inspect/);
expect(() => checkLaunchArguments(['--lang=de', '--no-update-check'])).not.toThrow();
expect(() => resolveOptions({ env: { ELECTRON_RUN_AS_NODE: '1' } })).toThrow(/ELECTRON_RUN_AS_NODE/);
// Windows reads a variable's name in any case.
Expand Down
2 changes: 2 additions & 0 deletions packages/electron/tests/unit/file-bound.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ describe('appDirectory', () => {
mkdirSync(path.dirname(archive), { recursive: true });
writeFileSync(archive, '');
expect(appDirectory({ reported: archive, declared: archive, firstDocument: page, projectRoot: app })).toBe(archive);
// The main process did not answer in time: the archive is still the bound, never the directory beside it.
expect(appDirectory({ reported: undefined, declared: archive, firstDocument: page, projectRoot: app })).toBe(archive);
expect(outsideApp(page, archive)).toMatch(/outside it/);
});

Expand Down
Loading