Skip to content
Merged
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
10 changes: 9 additions & 1 deletion docs/src/api/class-browsertype.md
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,11 @@ const { chromium } = require('playwright'); // Or 'webkit' or 'firefox'.
* since: v1.45
- `host` <[string]>

Host to use for the web socket. It is optional and defaults to `localhost`, accepting connections only from the loopback interface. Pass an explicit address (e.g. `0.0.0.0`) to accept connections from the network — be aware this exposes the browser RPC to anything that can reach the listening port.
Host to use for the web socket. It is optional and defaults to `localhost`, accepting connections only from the loopback interface. Pass an explicit address (e.g. `0.0.0.0`) to accept connections from the network.

:::warning
The Browser Server has no authentication. A client that can reach the listening port and knows the [`option: BrowserType.launchServer.wsPath`] gets full control of the browser and can act as the OS user that started the server. When you pass an explicit host, restrict access to the port with your network configuration, for example a firewall, a private network or an authenticating proxy. Do not rely on the `wsPath` alone.
:::

### option: BrowserType.launchServer.port
* since: v1.8
Expand All @@ -440,6 +444,10 @@ unguessable string.
Any process or web page (including those running in Playwright) with knowledge
of the `wsPath` can take control of the OS user. For this reason, you should
use an unguessable token when using this option.

The unguessable path protects a server on the loopback interface from web pages and
from other local processes. It is not a replacement for network access control: the path
is a part of the URL and is sent in plain text over `ws://`. See [`option: BrowserType.launchServer.host`].
:::

## method: BrowserType.name
Expand Down
6 changes: 6 additions & 0 deletions docs/src/docker.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,12 @@ Start the Playwright Server in Docker:
docker run -p 3000:3000 --rm --init -it --workdir /home/pwuser --user pwuser mcr.microsoft.com/playwright:v%%VERSION%%-noble /bin/sh -c "npx -y playwright@%%VERSION%% run-server --port 3000 --host 0.0.0.0"
```

:::warning
The Playwright Server has no authentication. Any client that can reach the port gets full control of the browsers and can act as the user that runs the server. The server is intended to run in an environment where the network configuration restricts access to the port. Publish the port only to trusted clients, for example with `-p 127.0.0.1:3000:3000` when the tests run on the same machine, or with a firewall, a private network or an authenticating proxy otherwise.

If other local users or processes must not connect, for example on a shared development machine, serve the endpoint at an unguessable path with `--path /<secret>` and connect to `ws://127.0.0.1:3000/<secret>`.
:::

#### Connecting to the Server
* langs: js

Expand Down
14 changes: 12 additions & 2 deletions packages/playwright-client/types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18409,8 +18409,14 @@ export interface BrowserType<Unused = {}> {

/**
* Host to use for the web socket. It is optional and defaults to `localhost`, accepting connections only from the
* loopback interface. Pass an explicit address (e.g. `0.0.0.0`) to accept connections from the network — be aware
* this exposes the browser RPC to anything that can reach the listening port.
* loopback interface. Pass an explicit address (e.g. `0.0.0.0`) to accept connections from the network.
*
* **NOTE** The Browser Server has no authentication. A client that can reach the listening port and knows the
* [`wsPath`](https://playwright.dev/docs/api/class-browsertype#browser-type-launch-server-option-ws-path) gets full
* control of the browser and can act as the OS user that started the server. When you pass an explicit host, restrict
* access to the port with your network configuration, for example a firewall, a private network or an authenticating
* proxy. Do not rely on the `wsPath` alone.
*
*/
host?: string;

Expand Down Expand Up @@ -18475,6 +18481,10 @@ export interface BrowserType<Unused = {}> {
* **NOTE** Any process or web page (including those running in Playwright) with knowledge of the `wsPath` can take
* control of the OS user. For this reason, you should use an unguessable token when using this option.
*
* The unguessable path protects a server on the loopback interface from web pages and from other local processes. It
* is not a replacement for network access control: the path is a part of the URL and is sent in plain text over
* `ws://`. See [`host`](https://playwright.dev/docs/api/class-browsertype#browser-type-launch-server-option-host).
*
*/
wsPath?: string;
}): Promise<BrowserServer>;
Expand Down
7 changes: 0 additions & 7 deletions packages/playwright-core/src/remote/playwrightServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,6 @@ export class PlaywrightServer {

this._wsServer = new WSServer({
onRequest: (request, response) => {
if (request.method === 'GET' && request.url === '/json') {
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify({
wsEndpointPath: this._options.path,
}));
return;
}
response.end('Running');
},

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import net from 'net';
import { resolveGlobToRegexPattern } from '@isomorphic/urlMatch';
import { asLocatorDescription } from '@isomorphic/locatorGenerators';
import { deviceDescriptors as descriptors } from '@isomorphic/deviceDescriptors';
import { fetchData } from '../utils';
import { getUserAgent } from '../userAgent';
import { Dispatcher } from './dispatcher';
import { SdkObject } from '../instrumentation';
Expand All @@ -33,8 +32,6 @@ import type { HarBackend } from '../harBackend';
import type { Playwright } from '../playwright';
import type { RootDispatcher } from './dispatcher';
import type * as channels from '../channels';
import type * as http from 'http';
import type { HTTPRequestParams } from '@utils/network';

export class LocalUtilsDispatcher extends Dispatcher<SdkObject, channels.LocalUtilsChannel, RootDispatcher> implements channels.LocalUtilsChannel {
_type_LocalUtils: boolean;
Expand Down Expand Up @@ -96,9 +93,7 @@ export class LocalUtilsDispatcher extends Dispatcher<SdkObject, channels.LocalUt
'x-playwright-proxy': params.exposeNetwork ?? '',
...params.headers,
};
const wsEndpoint = await urlToWSEndpoint(progress, params.endpoint);

const transport = await WebSocketTransport.connect(progress, wsEndpoint, { headers: wsHeaders, followRedirects: true, debugLogHeader: 'x-playwright-debug-log' });
const transport = await WebSocketTransport.connect(progress, params.endpoint, { headers: wsHeaders, followRedirects: true, debugLogHeader: 'x-playwright-debug-log' });
const socksInterceptor = new SocksInterceptor(transport, params.exposeNetwork, params.socksProxyRedirectPortForTest);
const pipe = new JsonPipeDispatcher(this);
transport.onmessage = json => {
Expand Down Expand Up @@ -167,32 +162,3 @@ export class LocalUtilsDispatcher extends Dispatcher<SdkObject, channels.LocalUt
return { description };
}
}

async function urlToWSEndpoint(progress: Progress, endpointURL: string): Promise<string> {
if (endpointURL.startsWith('ws'))
return endpointURL;

progress.log(`<ws preparing> retrieving websocket url from ${endpointURL}`);
const fetchUrl = new URL(endpointURL);
if (!fetchUrl.pathname.endsWith('/'))
fetchUrl.pathname += '/';
fetchUrl.pathname += 'json';
const json = await fetchData(progress, {
url: fetchUrl.toString(),
method: 'GET',
headers: { 'User-Agent': getUserAgent() },
}, async (params: HTTPRequestParams, response: http.IncomingMessage) => {
return new Error(`Unexpected status ${response.statusCode} when connecting to ${fetchUrl.toString()}.\n` +
`This does not look like a Playwright server, try connecting via ws://.`);
});

const wsUrl = new URL(endpointURL);
let wsEndpointPath = JSON.parse(json).wsEndpointPath;
if (wsEndpointPath.startsWith('/'))
wsEndpointPath = wsEndpointPath.substring(1);
if (!wsUrl.pathname.endsWith('/'))
wsUrl.pathname += '/';
wsUrl.pathname += wsEndpointPath;
wsUrl.protocol = wsUrl.protocol === 'https:' ? 'wss:' : 'ws:';
return wsUrl.toString();
}
14 changes: 12 additions & 2 deletions packages/playwright-core/types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18409,8 +18409,14 @@ export interface BrowserType<Unused = {}> {

/**
* Host to use for the web socket. It is optional and defaults to `localhost`, accepting connections only from the
* loopback interface. Pass an explicit address (e.g. `0.0.0.0`) to accept connections from the network — be aware
* this exposes the browser RPC to anything that can reach the listening port.
* loopback interface. Pass an explicit address (e.g. `0.0.0.0`) to accept connections from the network.
*
* **NOTE** The Browser Server has no authentication. A client that can reach the listening port and knows the
* [`wsPath`](https://playwright.dev/docs/api/class-browsertype#browser-type-launch-server-option-ws-path) gets full
* control of the browser and can act as the OS user that started the server. When you pass an explicit host, restrict
* access to the port with your network configuration, for example a firewall, a private network or an authenticating
* proxy. Do not rely on the `wsPath` alone.
*
*/
host?: string;

Expand Down Expand Up @@ -18475,6 +18481,10 @@ export interface BrowserType<Unused = {}> {
* **NOTE** Any process or web page (including those running in Playwright) with knowledge of the `wsPath` can take
* control of the OS user. For this reason, you should use an unguessable token when using this option.
*
* The unguessable path protects a server on the loopback interface from web pages and from other local processes. It
* is not a replacement for network access control: the path is a part of the URL and is sent in plain text over
* `ws://`. See [`host`](https://playwright.dev/docs/api/class-browsertype#browser-type-launch-server-option-host).
*
*/
wsPath?: string;
}): Promise<BrowserServer>;
Expand Down
20 changes: 0 additions & 20 deletions tests/library/browsertype-connect.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -868,15 +868,6 @@ for (const kind of ['launchServer', 'run-server'] as const) {
expect(Math.abs(timestamps[i] - expectedTimestamps[i]), `expected: ${expectedTimestamps}; actual: ${timestamps}`).toBeLessThanOrEqual(1000);
});

test('BT-079 should connect over http', async ({ connect, startRemoteServer }) => {
const remoteServer = await startRemoteServer(kind);

const url = new URL(remoteServer.wsEndpoint());
const browser = await connect(`http://localhost:${url.port}`);
expect(browser.version()).toBeTruthy();
await browser.close();
});

test.describe('socks proxy', () => {
test.skip(kind === 'launchServer', 'not supported yet');

Expand Down Expand Up @@ -1201,17 +1192,6 @@ test('BT-094 should filter local paths from unsafe launch options', async ({ con
expect(actions).toContain('Set content');
});

test('BT-095 should timeout after redirect when connecting over http', async ({ connect, server }) => {
server.setRedirect('/connect/json', '/connect/slow');
let aborted = false;
server.setRoute('/connect/slow', (req, res) => {
req.socket.on('close', () => aborted = true);
});
const error = await connect(`${server.PREFIX}/connect`, { timeout: 2000, headers: { 'Connection': 'Close' } }).catch(e => e);
expect(error.message).toContain('Timeout 2000ms exceeded.');
await expect.poll(() => aborted).toBe(true);
});

test('BT-096 should not retain closed browsers in launch mode', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/43421' } }, async ({ connect }) => {
const server = new remote.PlaywrightServer({ mode: 'default', path: '/' + utils.createGuid(), maxConnections: Number.MAX_VALUE });
const wsEndpoint = await server.listen();
Expand Down
4 changes: 4 additions & 0 deletions tests/library/browsertype-launch-server.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ it.describe('launch server', () => {
it('BT-028 should default to random wsPath', async ({ browserType }) => {
const browserServer = await browserType.launchServer();
expect(browserServer.wsEndpoint()).toMatch(/:\d+\/[a-f\d]{32}$/);
// The path is the only secret of the server, plain HTTP requests must not reveal it.
const url = new URL(browserServer.wsEndpoint());
const response = await fetch(`http://${url.host}/json`);
expect(await response.text()).not.toContain(url.pathname.substring(1));
await browserServer.close();
});

Expand Down
2 changes: 0 additions & 2 deletions tests/registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,6 @@ subsystem, add a row to the Subsystems table. Then update this file:
| `BT-076` | `library/browsertype-connect.spec.ts` | {launchServer, run-server} › should upload large file *(2 copies)* |
| `BT-077` | `library/browsertype-connect.spec.ts` | {launchServer, run-server} › should upload a folder *(2 copies)* |
| `BT-078` | `library/browsertype-connect.spec.ts` | {launchServer, run-server} › setInputFiles should preserve lastModified timestamp *(2 copies)* |
| `BT-079` | `library/browsertype-connect.spec.ts` | {launchServer, run-server} › should connect over http *(2 copies)* |
| `BT-080` | `library/browsertype-connect.spec.ts` | {launchServer, run-server} › socks proxy › should forward non-forwarded requests *(2 copies)* |
| `BT-081` | `library/browsertype-connect.spec.ts` | {launchServer, run-server} › socks proxy › should proxy localhost requests @smoke *(2 copies)* |
| `BT-082` | `library/browsertype-connect.spec.ts` | {launchServer, run-server} › socks proxy › should proxy ipv6 localhost requests @smoke *(2 copies)* |
Expand All @@ -599,7 +598,6 @@ subsystem, add a row to the Subsystems table. Then update this file:
| `BT-092` | `library/browsertype-connect.spec.ts` | launchServer only › cannot launch another browser |
| `BT-093` | `library/browsertype-connect.spec.ts` | should refuse connecting when versions do not match |
| `BT-094` | `library/browsertype-connect.spec.ts` | should filter local paths from unsafe launch options |
| `BT-095` | `library/browsertype-connect.spec.ts` | should timeout after redirect when connecting over http |
| `BT-096` | `library/browsertype-connect.spec.ts` | should not retain closed browsers in launch mode |
| `BT-097` | `library/browsertype-launch-selenium.spec.ts` | selenium grid 3.141.59 standalone chromium |
| `BT-098` | `library/browsertype-launch-selenium.spec.ts` | selenium grid 3.141.59 hub + node chromium |
Expand Down
Loading