diff --git a/bin/lib/handlers.js b/bin/lib/handlers.js index 7f05b18..cfd6bf0 100644 --- a/bin/lib/handlers.js +++ b/bin/lib/handlers.js @@ -520,14 +520,10 @@ class PageHandler extends BaseHandler { async waitForFunction(page, command) { try { - let func; - try { - func = eval(`(${command.pageFunction})`); - } catch (e) { - func = command.pageFunction; - } - - await page.waitForFunction(func, command.arg, command.options); + await page.waitForFunction(({ expression, arg }) => { + const value = eval(`(${expression})`); + return typeof value === 'function' ? value(arg) : value; + }, { expression: command.pageFunction, arg: command.arg }, command.options); } catch (error) { logger.error('PAGE WAITFORFUNCTION ERROR', { message: error.message }); throw error; diff --git a/bin/playwright-server.js b/bin/playwright-server.js index c7563ed..4b616bd 100644 --- a/bin/playwright-server.js +++ b/bin/playwright-server.js @@ -305,7 +305,7 @@ class PlaywrightServer extends BaseHandler { if (command?.options?.env?.PWDEBUG) process.env.PWDEBUG = String(command.options.env.PWDEBUG); if (command.browser === 'chromium' || !command.browser) { options.args = [ - '--no-sandbox', '--disable-dev-shm-usage', '--disable-web-security', + '--disable-dev-shm-usage', '--disable-background-timer-throttling', '--disable-backgrounding-occluded-windows', '--disable-renderer-backgrounding', '--disable-field-trial-config', '--disable-ipc-flooding-protection', '--disable-popup-blocking', ...(options.args || []) ]; @@ -470,62 +470,66 @@ class PlaywrightServer extends BaseHandler { } } -const server = new PlaywrightServer(); -let inputBuffer = Buffer.alloc(0); - -sendFramedResponse({ type: 'ready', message: 'READY' }); - -process.stdin.on('data', ErrorHandler.wrapHandler(async (chunk) => { - inputBuffer = Buffer.concat([inputBuffer, chunk]); - try { - const decoded = LspFraming.decode(inputBuffer); - inputBuffer = decoded.remainingBuffer; - for (const messageContent of decoded.messages) { - if (!messageContent.trim()) continue; - let command; - const fail = (error) => { - logger.error('SERVER ERROR', { error: error.message, stack: error.stack, command: messageContent }); - const errorResponse = { error: error.message, parseError: true }; - if (command?.requestId) errorResponse.requestId = command.requestId; - sendFramedResponse(errorResponse); - }; - try { - command = JSON.parse(messageContent); - // Not awaited, so a slow command cannot hold back the rest of the chunk. - server.handleCommand(command).then((result) => { if (result) sendFramedResponse(result); }, fail); - } catch (error) { - fail(error); +module.exports = { PlaywrightServer }; + +if (require.main === module) { + const server = new PlaywrightServer(); + let inputBuffer = Buffer.alloc(0); + + sendFramedResponse({ type: 'ready', message: 'READY' }); + + process.stdin.on('data', ErrorHandler.wrapHandler(async (chunk) => { + inputBuffer = Buffer.concat([inputBuffer, chunk]); + try { + const decoded = LspFraming.decode(inputBuffer); + inputBuffer = decoded.remainingBuffer; + for (const messageContent of decoded.messages) { + if (!messageContent.trim()) continue; + let command; + const fail = (error) => { + logger.error('SERVER ERROR', { error: error.message, stack: error.stack, command: messageContent }); + const errorResponse = { error: error.message, parseError: true }; + if (command?.requestId) errorResponse.requestId = command.requestId; + sendFramedResponse(errorResponse); + }; + try { + command = JSON.parse(messageContent); + // Not awaited, so a slow command cannot hold back the rest of the chunk. + server.handleCommand(command).then((result) => { if (result) sendFramedResponse(result); }, fail); + } catch (error) { + fail(error); + } } + } catch (error) { + logger.error('LSP FRAMING ERROR', { error: error.message, stack: error.stack }); + sendFramedResponse({ error: 'LSP framing error: ' + error.message }); } - } catch (error) { - logger.error('LSP FRAMING ERROR', { error: error.message, stack: error.stack }); - sendFramedResponse({ error: 'LSP framing error: ' + error.message }); - } -})); + })); + + // The PHP process owns this server. Once it is gone, nothing will ever arrive on + // stdin again and every browser we hold becomes an orphan reparented to init. + // stdin closing covers the cases no PHP-side shutdown hook can reach: SIGKILL, + // a fatal error, or SIGTERM, none of which run register_shutdown_function. + let shuttingDown = false; -// The PHP process owns this server. Once it is gone, nothing will ever arrive on -// stdin again and every browser we hold becomes an orphan reparented to init. -// stdin closing covers the cases no PHP-side shutdown hook can reach: SIGKILL, -// a fatal error, or SIGTERM, none of which run register_shutdown_function. -let shuttingDown = false; + async function shutdown(reason) { + if (shuttingDown) return; + shuttingDown = true; -async function shutdown(reason) { - if (shuttingDown) return; - shuttingDown = true; + // A browser that refuses to close must not wedge the process: exiting without + // cleanup still lets Chromium notice the broken pipe, hanging here does not. + const watchdog = setTimeout(() => process.exit(1), 5000); + watchdog.unref(); - // A browser that refuses to close must not wedge the process: exiting without - // cleanup still lets Chromium notice the broken pipe, hanging here does not. - const watchdog = setTimeout(() => process.exit(1), 5000); - watchdog.unref(); + try { + logger.info('Parent gone, shutting down', { reason }); + } catch {} - try { - logger.info('Parent gone, shutting down', { reason }); - } catch {} + await server.exit(); + } - await server.exit(); + process.stdin.on('end', () => shutdown('stdin end')); + process.stdin.on('close', () => shutdown('stdin close')); + process.on('SIGTERM', () => shutdown('SIGTERM')); + process.on('SIGHUP', () => shutdown('SIGHUP')); } - -process.stdin.on('end', () => shutdown('stdin end')); -process.stdin.on('close', () => shutdown('stdin close')); -process.on('SIGTERM', () => shutdown('SIGTERM')); -process.on('SIGHUP', () => shutdown('SIGHUP')); diff --git a/docs/guide/core-concepts.md b/docs/guide/core-concepts.md index afa1ac0..a908c6a 100644 --- a/docs/guide/core-concepts.md +++ b/docs/guide/core-concepts.md @@ -94,3 +94,7 @@ $signInButton->click(); By understanding and using these four core concepts, you can build powerful, reliable, and maintainable browser automation scripts and tests. + +## Browser execution + +Chromium launches keep the browser's normal same-origin checks. Tests that deliberately need different behavior can supply their own Chromium arguments through `args`. diff --git a/tests/Integration/Bridge/BrowserBridgeTest.php b/tests/Integration/Bridge/BrowserBridgeTest.php new file mode 100644 index 0000000..b8ff313 --- /dev/null +++ b/tests/Integration/Bridge/BrowserBridgeTest.php @@ -0,0 +1,32 @@ +setTimeout(30); + $process->run(); + + $this->assertSame(0, $process->getExitCode(), $process->getOutput().$process->getErrorOutput()); + } +} diff --git a/tests/Integration/Bridge/browser.test.cjs b/tests/Integration/Bridge/browser.test.cjs new file mode 100644 index 0000000..6cdd563 --- /dev/null +++ b/tests/Integration/Bridge/browser.test.cjs @@ -0,0 +1,31 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const vm = require('node:vm'); +const { PageHandler } = require('../../../bin/lib/handlers'); +const { PlaywrightServer } = require('../../../bin/playwright-server'); + +test('Chromium arguments keep origin checks and caller sandbox choices', () => { + const server = new PlaywrightServer(); + const options = server.buildLaunchOptions({ browser: 'chromium', options: { chromiumSandbox: true } }); + assert.equal(options.args.includes('--disable-web-security'), false); + assert.equal(options.args.includes('--no-sandbox'), false); + assert.equal(options.chromiumSandbox, true); + assert.equal(server.buildLaunchOptions({ options: { args: ['--disable-web-security'] } }).args.includes('--disable-web-security'), true); +}); + +test('browser predicates stay in their browser realm and keep arguments', async () => { + delete globalThis.hostPredicateMarker; + const page = { + waitForFunction: async (callback, payload, options) => { + assert.deepEqual(options, { polling: 20, timeout: 1000 }); + const result = vm.runInNewContext(`(${callback.toString()})(payload)`, { payload, document: { title: 'Ready' } }); + assert.equal(result, true); + }, + }; + const handler = new PageHandler(); + await handler.waitForFunction(page, { + pageFunction: '(globalThis.hostPredicateMarker = true, arg => document.title === arg)', + arg: 'Ready', options: { polling: 20, timeout: 1000 }, + }); + assert.equal(globalThis.hostPredicateMarker, undefined); +}); diff --git a/tests/Integration/Browser/BrowserBoundaryTest.php b/tests/Integration/Browser/BrowserBoundaryTest.php new file mode 100644 index 0000000..68cdddc --- /dev/null +++ b/tests/Integration/Browser/BrowserBoundaryTest.php @@ -0,0 +1,73 @@ +setUpPlaywright(); + $this->page->route('https://private.example/**', static function (RouteInterface $route): void { + $route->fulfill(['contentType' => 'text/html', 'headers' => ['access-control-allow-origin' => 'https://private.example'], 'body' => '
private-content
']); + }); + } + + protected function tearDown(): void + { + $this->tearDownPlaywright(); + } + + public function testDefaultLaunchKeepsCrossOriginReadsBlocked(): void + { + $result = $this->page->evaluate('async () => { try { return await (await fetch("https://private.example/data")).text(); } catch { return "blocked"; } }'); + $this->assertSame('blocked', $result); + $this->page->goto('https://private.example/data'); + $this->assertSame('private-content', $this->page->locator('p')->textContent()); + } + + public function testWaitPredicatesKeepExpressionsFunctionsAndArguments(): void + { + $this->page->setContent('