Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

improvements to allowed_domains checking security

Nick Sweeting11eabb360125
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 9154203cb..b9f0870fa 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -8,9 +8,11 @@ import os
import re
import time
from dataclasses import dataclass
+from fnmatch import fnmatch
from functools import wraps
from pathlib import Path
from typing import Any, Self
+from urllib.parse import urlparse
import psutil
from patchright.async_api import Playwright as PatchrightPlaywright
@@ -40,7 +42,19 @@ logger = logging.getLogger('browser_use.browser.session')
_GLOB_WARNING_SHOWN = False # used inside _is_url_allowed to avoid spamming the logs with the same warning multiple times
-def truncate_url(s: str, max_len: int | None = None) -> str:
+def _show_glob_warning(domain: str, glob: str):
+ global _GLOB_WARNING_SHOWN
+ if not _GLOB_WARNING_SHOWN:
+ logger.warning(
+ # glob patterns are very easy to mess up and match too many domains by accident
+ # e.g. if you only need to access gmail, don't use *.google.com because an attacker could convince the agent to visit a malicious doc
+ # on docs.google.com/s/some/evil/doc to set up a prompt injection attack
+ f"⚠️ Allowing agent to visit {domain} based on allowed_domains=['{glob}', ...]. Set allowed_domains=['{domain}', ...] explicitly to avoid matching too many domains!"
+ )
+ _GLOB_WARNING_SHOWN = True
+
+
+def truncate_url(s: str, max_len: int | None = 22) -> str:
"""Truncate/pretty-print a URL with a maximum length, removing the protocol and www. prefix"""
s = s.replace('https://', '').replace('http://', '').replace('www.', '')
if max_len is not None and len(s) > max_len:
@@ -48,6 +62,11 @@ def truncate_url(s: str, max_len: int | None = None) -> str:
return s
+def pretty_path(path: Path) -> str:
+ """Pretty-print a path, removing the drive letter on Windows"""
+ return str(path).replace(str(Path.home()), '~').replace(str(Path.cwd().resolve()), '.')
+
+
def require_initialization(func):
"""decorator for BrowserSession methods to require the BrowserSession be already active"""
@@ -106,7 +125,9 @@ class BrowserSession(BaseModel):
browser_profile: InstanceOf[BrowserProfile] = Field(
default=DEFAULT_BROWSER_PROFILE,
description='BrowserProfile() instance containing config for the BrowserSession',
- validation_alias=AliasChoices('profile', 'config', 'new_context_config'), # old names for this field, remove eventually
+ validation_alias=AliasChoices(
+ 'profile', 'config', 'new_context_config'
+ ), # abbreviations = 'profile', old deprecated names = 'config', 'new_context_config'
)
# runtime props/state: these can be passed in as props at init, or get auto-setup by BrowserSession.start()
@@ -118,8 +139,10 @@ class BrowserSession(BaseModel):
default=None,
description='CDP URL of the browser to connect to, e.g. http://localhost:9222 or ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4',
)
- chrome_pid: int | None = Field(
- default=None, description='pid of the running chrome process to connect to on localhost (optional)'
+ browser_pid: int | None = Field(
+ default=None,
+ description='pid of a running chromium-based browser process to connect to on localhost',
+ validation_alias=AliasChoices('chrome_pid'), # old deprecated name = chrome_pid
)
playwright: Playwright | PatchrightPlaywright | Playwright | None = Field(
default=None,
@@ -138,20 +161,20 @@ class BrowserSession(BaseModel):
validation_alias=AliasChoices('playwright_browser_context', 'context'),
exclude=True,
)
+
+ # runtime state: state that changes during the lifecycle of a BrowserSession(), updated by the methods below
initialized: bool = Field(
default=False,
- description='Skip BrowserSession launch/connection setup entirely if True (not recommended)',
- validation_alias=AliasChoices('initialized', 'is_initialized'),
+ description='Mark BrowserSession launch/connection as already ready and skip setup (not recommended)',
+ validation_alias=AliasChoices('is_initialized'),
)
-
- # runtime state: internally tracked attrs updated by BrowserSession class methods
agent_current_page: InstanceOf[Page] | None = Field( # mutated by self.create_new_tab(url)
default=None,
description='Foreground Page that the agent is focused on',
- validation_alias=AliasChoices('current_page', 'page'),
+ validation_alias=AliasChoices('current_page', 'page'), # alias page= allows passing in a playwright Page object easily
exclude=True,
)
- human_current_page: InstanceOf[Page] | None = Field( # mutated by self.setup_foreground_tab_detection()
+ human_current_page: InstanceOf[Page] | None = Field( # mutated by self._setup_current_page_change_listeners()
default=None,
description='Foreground Page that the human is focused on',
exclude=True,
@@ -165,14 +188,15 @@ class BrowserSession(BaseModel):
"""Apply any extra **kwargs passed to BrowserSession(...) as config overrides on top of browser_profile"""
session_own_fields = type(self).model_fields.keys()
- # get all the extra BrowserProfile kwarg overrides passed to BrowserSession(...) that are not Fields on self
- overrides = self.model_dump(exclude=session_own_fields)
+ # get all the extra kwarg overrides passed to BrowserSession(...) that are actually
+ # config Fields tracked by BrowserProfile, instead of BrowserSession's own args
+ profile_overrides = self.model_dump(exclude=session_own_fields)
# FOR REPL DEBUGGING ONLY, NEVER ALLOW CIRCULAR REFERENCES IN REAL CODE:
# self.browser_profile._in_use_by_session = self
# replace browser_profile with patched version
- self.browser_profile = self.browser_profile.model_copy(update=overrides)
+ self.browser_profile = self.browser_profile.model_copy(update=profile_overrides)
# FOR REPL DEBUGGING ONLY, NEVER ALLOW CIRCULAR REFERENCES IN REAL CODE:
# self.browser_profile._in_use_by_session = self
@@ -188,7 +212,19 @@ class BrowserSession(BaseModel):
# return getattr(self.browser_profile, key)
async def start(self) -> Self:
- # finish initializing/validate the browser_profile:
+ """
+ Starts the browser session by either connecting to an existing browser or launching a new one.
+ Precedence order for launching/connecting:
+ 1. page=Page playwright object, will use its page.context as browser_context
+ 2. browser_context=PlaywrightBrowserContext object, will use its browser
+ 3. browser=PlaywrightBrowser object, will use its first available context
+ 4. browser_pid=int, will connect to a local chromium-based browser via pid
+ 5. wss_url=str, will connect to a remote playwright browser server via WSS
+ 6. cdp_url=str, will connect to a remote chromium-based browser via CDP
+ 7. playwright=Playwright object, will use its chromium instance to launch a new browser
+ """
+
+ # apply last-minute runtime-computed options to the the browser_profile, validate profile, set up folders on disk
assert isinstance(self.browser_profile, BrowserProfile)
self.browser_profile.prepare_user_data_dir() # create/unlock the <user_data_dir>/SingletonLock
self.browser_profile.detect_display_configuration() # adjusts config values, must come before launch/connect
@@ -196,47 +232,54 @@ class BrowserSession(BaseModel):
# launch/connect to the browser:
# setup playwright library client, Browser, and BrowserContext objects
await self.setup_playwright()
- await self.setup_browser_connection() # connects to existing browser if available
- await self.setup_browser_context() # creates a new context in existing browser or launches a new persistent context
- assert self.browser_context
+ await self.setup_browser_via_passed_objects()
+ await self.setup_browser_via_browser_pid()
+ await self.setup_browser_via_wss_url()
+ await self.setup_browser_via_cdp_url()
+ await self.setup_new_browser_context() # creates a new context in existing browser or launches a new persistent context
+ assert self.browser_context, f'Failed to connect to or create a new BrowserContext for browser={self.browser}'
# resize the existing pages and set up foreground tab detection
- await self.setup_viewport_sizing()
- await self.setup_foreground_tab_detection()
+ await self._setup_viewports()
+ await self._setup_current_page_change_listeners()
self.initialized = True
return self
async def stop(self) -> None:
- if not self.browser_profile.keep_alive:
- logger.info('🛑 Shutting down browser...')
- if self.browser_context:
- try:
- await self.browser_context.close()
- except Exception as e:
- logger.debug(f'❌ Error closing playwright BrowserContext {self.browser_context}: {type(e).__name__}: {e}')
+ """Shuts down the BrowserSession, killing the browser process if keep_alive=False"""
- if self.browser:
- try:
- await self.browser.close()
- except Exception as e:
- logger.debug(f'❌ Error closing playwright Browser {self.browser}: {type(e).__name__}: {e}')
+ if self.browser_profile.keep_alive:
+ return # nothing to do if keep_alive=True, leave the browser running
- # kill the chrome subprocess if we were the ones that started it
- if self.chrome_pid:
- try:
- psutil.Process(pid=self.chrome_pid).terminate()
- except Exception as e:
- if 'NoSuchProcess' not in type(e).__name__:
- logger.debug(f'❌ Error terminating chrome subprocess pid={self.chrome_pid}: {type(e).__name__}: {e}')
+ logger.info('🛑 Shutting down browser...')
+ if self.browser_context:
+ try:
+ await self.browser_context.close()
+ except Exception as e:
+ logger.debug(f'❌ Error closing playwright BrowserContext {self.browser_context}: {type(e).__name__}: {e}')
+
+ if self.browser:
+ try:
+ await self.browser.close()
+ except Exception as e:
+ logger.debug(f'❌ Error closing playwright Browser {self.browser}: {type(e).__name__}: {e}')
+
+ # kill the chrome subprocess if we were the ones that started it
+ if self.browser_pid:
+ try:
+ psutil.Process(pid=self.browser_pid).terminate()
+ except Exception as e:
+ if 'NoSuchProcess' not in type(e).__name__:
+ logger.debug(f'❌ Error terminating chrome subprocess pid={self.browser_pid}: {type(e).__name__}: {e}')
async def close(self) -> None:
- """Shortcut for self.stop()"""
+ """Deprecated: Provides backwards-compatibility with old class method Browser().close()"""
await self.stop()
async def new_context(self, **kwargs):
- """Create a new browser context with the given kwargs"""
+ """Deprecated: Provides backwards-compatibility with old class method Browser().new_context()"""
return self
async def __aenter__(self) -> BrowserSession:
@@ -247,8 +290,11 @@ class BrowserSession(BaseModel):
await self.stop()
async def setup_playwright(self) -> None:
- """Override to customize the set up of the playwright or patchright library object"""
- self.playwright = self.playwright or await async_playwright().start()
+ """
+ Set up playwright library client object: usually the result of (await async_playwright().start())
+ Override to customize the set up of the playwright or patchright library object
+ """
+ self.playwright = self.playwright or (await async_playwright().start())
# if isinstance(self.playwright, PatchrightPlaywright):
# # patchright handles all its own default args, dont mess with them
@@ -256,56 +302,75 @@ class BrowserSession(BaseModel):
return self.playwright
- async def setup_browser_connection(self) -> None:
+ async def setup_browser_via_passed_objects(self) -> None:
"""Override to customize the set up of the connection to an existing browser"""
- # if process is provided, calcuclate its CDP URL by looking for --remote-debugging-port=... in the launch args
- if self.chrome_pid:
- chrome_process = psutil.Process(pid=self.chrome_pid)
- assert chrome_process.is_running(), 'Chrome process is not running'
- args = chrome_process.cmdline()
- debug_port = next((arg for arg in args if arg.startswith('--remote-debugging-port=')), '').split('=')[-1].strip()
- assert debug_port, (
- f'Could not connect because could not find --remote-debugging-port=... in chrome launch args: pid={self.chrome_pid} {args}'
- )
- # we could automatically relaunch the browser process with that arg added here, but they may have tabs open they dont want to lose
- self.cdp_url = self.cdp_url or f'http://localhost:{debug_port}/'
- logger.info(f'🌎 Connecting to existing chromium process: pid={self.chrome_pid} on {self.cdp_url}')
-
- if self.wss_url:
- logger.info(f'🌎 Connecting to remote chromium playwright node.js server over WSS: {self.wss_url}')
- self.browser = self.browser or await self.playwright.chromium.connect(
- self.wss_url,
- **self.browser_profile.kwargs_for_connect().model_dump(),
- )
- # dont default to closing the browser when the BrowserSession is over if we connect by WSS
- if self.browser_profile.keep_alive is None:
- self.browser_profile.keep_alive = True
- elif self.cdp_url:
- logger.info(f'🌎 Connecting to remote chromium browser over CDP: {self.cdp_url}')
- self.browser = self.browser or await self.playwright.chromium.connect_over_cdp(
- self.cdp_url,
- **self.browser_profile.kwargs_for_connect().model_dump(),
- )
- # dont default to closing the browser when the BrowserSession is over if we connect by CDP
- if self.browser_profile.keep_alive is None:
- self.browser_profile.keep_alive = True
+ # 1. check for a passed Page object, if present, it always takes priority, set browser_context = page.context
+ self.browser_context = (self.agent_current_page and self.agent_current_page.context) or self.browser_context or None
- # self.browser may still be None at this point if we have no config implying we should connect to an existing browser
- # self.setup_browser_context() will be called next and if it finds self.browser is None, it will
- # launch a new browser+context all in one go using launch_persistent_context()
+ # 2. if we have a context now, it always takes precedence, set browser = context.browser, otherwise use the passed browser
+ self.browser = (self.browser_context and self.browser_context.browser) or self.browser or None
- return self.browser
+ if self.browser or self.browser_context:
+ logger.info(f'🌎 Connected to existing user-provided browser_context: {self.browser_context}')
+ self._set_browser_keep_alive(True) # we connected to an existing browser, dont kill it at the end
- async def setup_browser_context(self) -> None:
- # if we have a browser_context but no browser, use the browser from the context
- if self.browser_context:
- logger.info(f'🌎 Using existing user-provided browser_context and browser: {self.browser_context}')
- self.browser = self.browser or self.browser_context.browser
- # dont default to closing the browser when the BrowserSession is over if we are passed an external browser
- if self.browser_profile.keep_alive is None:
- self.browser_profile.keep_alive = True
+ async def setup_browser_via_browser_pid(self) -> None:
+ """if browser_pid is provided, calcuclate its CDP URL by looking for --remote-debugging-port=... in its CLI args, then connect to it"""
+
+ if self.browser or self.browser_context:
+ return # already connected to a browser
+ if not self.browser_pid:
+ return # no browser_pid provided, nothing to do
+
+ chrome_process = psutil.Process(pid=self.browser_pid)
+ assert chrome_process.is_running(), 'Chrome process is not running'
+ args = chrome_process.cmdline()
+ debug_port = next((arg for arg in args if arg.startswith('--remote-debugging-port=')), '').split('=')[-1].strip()
+ assert debug_port, (
+ f'Could not find --remote-debugging-port=... to connect to in browser launch args: browser_pid={self.browser_pid} {args}'
+ )
+ # we could automatically relaunch the browser process with that arg added here, but they may have tabs open they dont want to lose
+ self.cdp_url = self.cdp_url or f'http://localhost:{debug_port}/'
+ logger.info(f'🌎 Connecting to existing local browser process: browser_pid={self.browser_pid} on {self.cdp_url}')
+ self.browser = self.browser or await self.playwright.chromium.connect_over_cdp(
+ self.cdp_url,
+ **self.browser_profile.kwargs_for_connect().model_dump(),
+ )
+ self._set_browser_keep_alive(True) # we connected to an existing browser, dont kill it at the end
+
+ async def setup_browser_via_wss_url(self) -> None:
+ """check for a passed wss_url, connect to a remote playwright browser server via WSS"""
+
+ if self.browser or self.browser_context:
+ return # already connected to a browser
+ if not self.wss_url:
+ return # no wss_url provided, nothing to do
+ logger.info(f'🌎 Connecting to existing remote chromium playwright node.js server over WSS: {self.wss_url}')
+ self.browser = self.browser or await self.playwright.chromium.connect(
+ self.wss_url,
+ **self.browser_profile.kwargs_for_connect().model_dump(),
+ )
+ self._set_browser_keep_alive(True) # we connected to an existing browser, dont kill it at the end
+
+ async def setup_browser_via_cdp_url(self) -> None:
+ """check for a passed cdp_url, connect to a remote chromium-based browser via CDP"""
+
+ if self.browser or self.browser_context:
+ return # already connected to a browser
+ if not self.cdp_url:
+ return # no cdp_url provided, nothing to do
+
+ logger.info(f'🌎 Connecting to existing remote chromium-based browser over CDP: {self.cdp_url}')
+ self.browser = self.browser or await self.playwright.chromium.connect_over_cdp(
+ self.cdp_url,
+ **self.browser_profile.kwargs_for_connect().model_dump(),
+ )
+ self._set_browser_keep_alive(True) # we connected to an existing browser, dont kill it at the end
+
+ async def setup_new_browser_context(self) -> None:
+ """Launch a new browser and browser_context"""
current_process = psutil.Process(os.getpid())
child_pids_before_launch = {child.pid for child in current_process.children(recursive=True)}
@@ -313,7 +378,7 @@ class BrowserSession(BaseModel):
if self.browser and not self.browser_context:
if self.browser.contexts:
self.browser_context = self.browser.contexts[0]
- logger.info(f'🌎 Using first browser_context available in user-provided browser: {self.browser_context}')
+ logger.info(f'🌎 Using first browser_context available in existing browser: {self.browser_context}')
else:
self.browser_context = await self.browser.new_context(
**self.browser_profile.kwargs_for_new_context().model_dump()
@@ -328,7 +393,9 @@ class BrowserSession(BaseModel):
# if we still have no browser_context by now, launch a new local one using launch_persistent_context()
if not self.browser_context:
logger.info(
- f'🌎 Launching local {str(type(self.playwright).__module__).split(".")[0]} {self.browser_profile.channel.name.lower()} browser with user_data_dir={self.browser_profile.user_data_dir or "None (incognito)"}'
+ f'🌎 Launching local browser '
+ f'driver={str(type(self.playwright).__module__).split(".")[0]} channel={self.browser_profile.channel.name.lower()} '
+ f'user_data_dir={pretty_path(self.browser_profile.user_data_dir) if self.browser_profile.user_data_dir else "None (incognito)"}'
)
if not self.browser_profile.user_data_dir:
# if no user_data_dir is provided, launch an incognito context with no persistent user_data_dir
@@ -339,70 +406,77 @@ class BrowserSession(BaseModel):
**self.browser_profile.kwargs_for_new_context().model_dump()
)
else:
+ # user data dir was provided, prepare it for use
self.browser_profile.prepare_user_data_dir()
# search for potentially conflicting local processes running on the same user_data_dir
for proc in psutil.process_iter(['pid', 'cmdline']):
if f'--user-data-dir={self.browser_profile.user_data_dir}' in (proc.info['cmdline'] or []):
- # suffix_num = str(self.browser_profile.user_data_dir).rsplit('.', 1)[-1] or '1'
- # suffix_num = int(suffix_num) if suffix_num.isdigit() else 1
-
- # dir_name = self.browser_profile.user_data_dir.name
- # incremented_name = dir_name.replace(f'.{suffix_num}', f'.{suffix_num + 1}')
- # fork_path = self.browser_profile.user_data_dir.parent / incremented_name
-
- # # keep incrementing the suffix_num until we find a path that doesn't exist
- # while fork_path.exists():
- # suffix_num += 1
- # fork_path = self.browser_profile.user_data_dir.parent / (
- # dir_name.rsplit('.', 1)[0] + f'.{suffix_num}'
- # )
-
logger.warning(
- f'🚨 Found potentially conflicting Chrome process pid={proc.info["pid"]} already running with the same user_data_dir={self.browser_profile.user_data_dir}'
+ f'🚨 Found potentially conflicting browser process browser_pid={proc.info["pid"]} '
+ f'already running with the same user_data_dir={pretty_path(self.browser_profile.user_data_dir)}'
)
- # use shutil to recursively copy the user_data_dir to a new location
- # shutil.copytree(
- # str(self.browser_profile.user_data_dir),
- # str(fork_path),
- # symlinks=True,
- # ignore_dangling_symlinks=True,
- # dirs_exist_ok=False,
- # )
- # self.browser_profile.user_data_dir = fork_path
- # self.browser_profile.prepare_user_data_dir()
+ # self._fork_locked_user_data_dir()
break
# if a user_data_dir is provided, launch a persistent context with that user_data_dir
self.browser_context = await self.playwright.chromium.launch_persistent_context(
**self.browser_profile.kwargs_for_launch_persistent_context().model_dump()
)
- self.browser = self.browser_context.browser or self.browser
- # ^ this can unfortunately be None ^ playwright does not give us a browser object when we use launch_persistent_context()
+
+ self.browser = (self.browser_context and self.browser_context.browser) or self.browser
+ # ^ this can unfortunately still be None at the end ^
+ # playwright does not give us a browser object at all when we use launch_persistent_context()!
# Detect any new child chrome processes that we might have launched above
child_pids_after_launch = {child.pid for child in current_process.children(recursive=True)}
new_child_pids = child_pids_after_launch - child_pids_before_launch
new_child_procs = [psutil.Process(pid) for pid in new_child_pids]
new_chrome_procs = [proc for proc in new_child_procs if 'Helper' not in proc.name() and proc.status() == 'running']
- if new_chrome_procs and not self.chrome_pid:
- self.chrome_pid = new_chrome_procs[0].pid
- logger.debug(f' ↳ Spawned chrome subprocess: pid={self.chrome_pid} {" ".join(new_chrome_procs[0].cmdline())}')
- # default to closing the browser ourselves when the BrowserSession is over if we launched it ourselves
- if self.browser_profile.keep_alive is None:
- self.browser_profile.keep_alive = False
+ if new_chrome_procs and not self.browser_pid:
+ self.browser_pid = new_chrome_procs[0].pid
+ logger.debug(
+ f' ↳ Spawned browser subprocess: browser_pid={self.browser_pid} {" ".join(new_chrome_procs[0].cmdline())}'
+ )
+ self._set_browser_keep_alive(False) # close the browser at the end because we launched it
if self.browser:
- connection_method = 'CDP' if self.cdp_url else 'WSS' if self.wss_url else 'Local'
+ connection_method = 'WSS' if self.wss_url else 'CDP' if (self.cdp_url and not self.browser_pid) else 'Local'
assert self.browser.is_connected(), (
f'Browser is not connected, did the browser process crash or get killed? (connection method: {connection_method})'
)
logger.debug(f'🌎 {connection_method} Browser connected: v{self.browser.version}')
- assert self.browser_context, f'BrowserContext {self.browser_context} is not set up'
- return self.browser_context
+ assert self.browser_context, (
+ f'Failed to create a playwright BrowserContext {self.browser_context} for browser={self.browser}'
+ )
- async def setup_foreground_tab_detection(self) -> None:
+ # async def _fork_locked_user_data_dir(self) -> None:
+ # """Fork an in-use user_data_dir by cloning it to a new location to allow a second browser to use it"""
+ # # TODO: implement copy-on-write using overlayfs or zfs or something
+ # suffix_num = str(self.browser_profile.user_data_dir).rsplit('.', 1)[-1] or '1'
+ # suffix_num = int(suffix_num) if suffix_num.isdigit() else 1
+ # dir_name = self.browser_profile.user_data_dir.name
+ # incremented_name = dir_name.replace(f'.{suffix_num}', f'.{suffix_num + 1}')
+ # fork_path = self.browser_profile.user_data_dir.parent / incremented_name
+
+ # # keep incrementing the suffix_num until we find a path that doesn't exist
+ # while fork_path.exists():
+ # suffix_num += 1
+ # fork_path = self.browser_profile.user_data_dir.parent / (dir_name.rsplit('.', 1)[0] + f'.{suffix_num}')
+
+ # # use shutil to recursively copy the user_data_dir to a new location
+ # shutil.copytree(
+ # str(self.browser_profile.user_data_dir),
+ # str(fork_path),
+ # symlinks=True,
+ # ignore_dangling_symlinks=True,
+ # dirs_exist_ok=False,
+ # )
+ # self.browser_profile.user_data_dir = fork_path
+ # self.browser_profile.prepare_user_data_dir()
+
+ async def _setup_current_page_change_listeners(self) -> None:
# Uses a combination of:
# - visibilitychange events
# - window focus/blur events
@@ -434,7 +508,8 @@ class BrowserSession(BaseModel):
self.agent_current_page = self.agent_current_page or foreground_page
self.human_current_page = self.human_current_page or foreground_page
- def _BrowserUseonTabVisibilityChange(source):
+ def _BrowserUseonTabVisibilityChange(source: dict[str, str]):
+ """hook callback fired when init script injected into a page detects a focus event"""
new_page = source['page']
# Update human foreground tab state
@@ -444,13 +519,16 @@ class BrowserSession(BaseModel):
new_tab_idx = self.browser_context.pages.index(new_page)
# Log before and after for debugging
- if old_foreground.url != new_page.url:
+ old_url = old_foreground and old_foreground.url or 'about:blank'
+ new_url = new_page and new_page.url or 'about:blank'
+ agent_url = self.agent_current_page and self.agent_current_page.url or 'about:blank'
+ agent_tab_idx = self.browser_context.pages.index(self.agent_current_page)
+ if old_url != new_url:
logger.info(
- f'👁️ Foregound tab changed by human from [{old_tab_idx}]{truncate_url(old_foreground.url, 22) if old_foreground else "about:blank"} '
- f'➡️ [{new_tab_idx}]{truncate_url(new_page.url, 22)} '
- f'(agent will stay on [{self.browser_context.pages.index(self.agent_current_page)}]{truncate_url(self.agent_current_page.url, 22)})'
+ f'👁️ Foregound tab changed by human from [{old_tab_idx}]{truncate_url(old_url)} '
+ f'➡️ [{new_tab_idx}]{truncate_url(new_url)} '
+ f'(agent will stay on [{agent_tab_idx}]{truncate_url(agent_url)})'
)
- return new_page.url
await self.browser_context.expose_binding('_BrowserUseonTabVisibilityChange', _BrowserUseonTabVisibilityChange)
update_tab_focus_script = """
@@ -489,13 +567,10 @@ class BrowserSession(BaseModel):
await page.evaluate(update_tab_focus_script)
# logger.debug(f'👁️ Added visibility listener to existing tab: {page.url}')
- async def setup_viewport_sizing(self) -> None:
+ async def _setup_viewports(self) -> None:
"""Resize any existing page viewports to match the configured size"""
- if not self.browser_context.pages:
- return
-
- # First, set the viewport size on any existing pages
+ # log the viewport settings to terminal
viewport = self.browser_profile.viewport
logger.debug(
'📐 Setting up viewport options: '
@@ -518,10 +593,52 @@ class BrowserSession(BaseModel):
+ (f'timezone_id={self.browser_profile.timezone_id} ' if self.browser_profile.timezone_id else '')
+ (f'geolocation={self.browser_profile.geolocation} ' if self.browser_profile.geolocation else '')
)
+
+ # if we have any viewport settings in the profile, make sure to apply them to the entire browser_context as defaults
+ if self.browser_profile.permissions:
+ try:
+ await self.browser_context.grant_permissions(self.browser_profile.permissions)
+ except Exception as e:
+ logger.warning(
+ f'⚠️ Failed to grant browser permissions {self.browser_profile.permissions}: {type(e).__name__}: {e}'
+ )
+ try:
+ if self.browser_profile.default_timeout:
+ await self.browser_context.set_default_timeout(self.browser_profile.default_timeout)
+ if self.browser_profile.default_navigation_timeout:
+ await self.browser_context.set_default_navigation_timeout(self.browser_profile.default_navigation_timeout)
+ except Exception as e:
+ logger.warning(
+ f'⚠️ Failed to set playwright timeout settings '
+ f'calls={self.browser_profile.default_timeout} '
+ f'nav={self.browser_profile.default_navigation_timeout}: {type(e).__name__}: {e}'
+ )
+ try:
+ if self.browser_profile.extra_http_headers:
+ await self.browser_context.set_extra_http_headers(self.browser_profile.extra_http_headers)
+ except Exception as e:
+ logger.warning(f'⚠️ Failed to setup playwright extra_http_headers: {type(e).__name__}: {e}')
+
+ try:
+ if self.browser_profile.geolocation:
+ await self.browser_context.set_geolocation(self.browser_profile.geolocation)
+ except Exception as e:
+ logger.warning(f'⚠️ Failed to update browser geolocation {self.browser_profile.geolocation}: {type(e).__name__}: {e}')
+
+ # if self.storage_state:
+ # TODO: implement applying self.stroage_state to an existing browser_context
+ # await self.browser_context.set_storage_state(self.storage_state)
+
+ # apply viewport size settings to any existing pages
if viewport:
for page in self.browser_context.pages:
await page.set_viewport_size(viewport)
+ def _set_browser_keep_alive(self, keep_alive: bool | None) -> None:
+ """set the keep_alive flag on the browser_profile, defaulting to True if keep_alive is None"""
+ if keep_alive is None:
+ self.browser_profile.keep_alive = keep_alive
+
# --- Tab management ---
async def get_current_page(self) -> Page:
"""Get the current page + ensure it's not None / closed"""
@@ -541,8 +658,8 @@ class BrowserSession(BaseModel):
self.agent_current_page = self.agent_current_page or self.human_current_page or None
self.human_current_page = self.human_current_page or self.agent_current_page or None
+ # if both are still None, fallback to using the first open tab we can find
if self.agent_current_page is None:
- # if both are still None, fallback to using the first open tab we can find
if self.browser_context.pages:
first_available_tab = self.browser_context.pages[0]
self.agent_current_page = first_available_tab
@@ -553,8 +670,8 @@ class BrowserSession(BaseModel):
self.agent_current_page = new_tab
self.human_current_page = new_tab
- assert self.agent_current_page is not None
- assert self.human_current_page is not None
+ assert self.agent_current_page is not None, 'Failed to find or create a new page for the agent'
+ assert self.human_current_page is not None, 'Failed to find or create a new page for the human'
return self.agent_current_page
@@ -1032,70 +1149,70 @@ class BrowserSession(BaseModel):
def _is_url_allowed(self, url: str) -> bool:
"""
- Check if a URL is allowed based on the whitelist configuration.
+ Check if a URL is allowed based on the whitelist configuration. SECURITY CRITICAL.
- Supports glob patterns in allowed_domains:
+ Supports optional glob patterns and schemes in allowed_domains:
- *.example.com will match sub.example.com and example.com
- *google.com will match google.com, agoogle.com, and www.google.com
+ - http*://example.com will match http://example.com, https://example.com
+ - chrome-extension://* will match chrome-extension://aaaaaaaaaaaa and chrome-extension://bbbbbbbbbbbbb
"""
if not self.browser_profile.allowed_domains:
- return True
-
- def _show_glob_warning(domain: str, glob: str):
- global _GLOB_WARNING_SHOWN
- if not _GLOB_WARNING_SHOWN:
- logger.warning(
- # glob patterns are very easy to mess up and match too many domains by accident
- # e.g. if you only need to access gmail, don't use *.google.com because an attacker could convince the agent to visit a malicious doc
- # on docs.google.com/s/some/evil/doc to set up a prompt injection attack
- f"⚠️ Allowing agent to visit {domain} based on allowed_domains=['{glob}', ...]. Set allowed_domains=['{domain}', ...] explicitly to avoid matching too many domains!"
- )
- _GLOB_WARNING_SHOWN = True
+ return True # allowed_domains are not configured, allow everything by default
+ allowed_domain = None
try:
- import fnmatch
- from urllib.parse import urlparse
-
parsed_url = urlparse(url)
- # Special case: Allow 'about:blank' explicitly
- if url == 'about:blank' or parsed_url.scheme.lower() in ('chrome', 'brave', 'edge', 'chrome-extension'):
+ # Special case: Always allow 'about:blank' new tab page
+ if url == 'about:blank':
return True
- # Extract only the hostname component (without auth credentials or port)
- # Hostname returns only the domain portion, ignoring username:password and port
+ # Extract only the hostname and scheme components (without http basic auth user:pass@ prefix or :port suffix)
+ scheme = parsed_url.scheme.lower() if parsed_url.scheme else ''
domain = parsed_url.hostname.lower() if parsed_url.hostname else ''
-
- if not domain:
- return False
+ assert scheme and domain
for allowed_domain in self.browser_profile.allowed_domains:
allowed_domain = allowed_domain.lower()
+ if '://' in allowed_domain:
+ allowed_scheme, allowed_domain = allowed_domain.split('://', 1)
+ else:
+ allowed_scheme = 'http*'
+
+ # if scheme doesn't match, skip checking domain
+ if not fnmatch(scheme, allowed_scheme):
+ continue
+
+ # Check for exact match
+ if allowed_domain == '*' or domain == allowed_domain:
+ return True
# Handle glob patterns
if '*' in allowed_domain:
- # Special handling for *.domain.tld pattern to also match the bare domain
- if allowed_domain.startswith('*.'):
- # If pattern is *.example.com, also allow example.com (without subdomain)
- parent_domain = allowed_domain[2:] # Remove the '*.' prefix
- if domain == parent_domain or fnmatch.fnmatch(domain, allowed_domain):
- _show_glob_warning(domain, allowed_domain)
- return True
- else:
- # For other glob patterns like *google.com
- if fnmatch.fnmatch(domain, allowed_domain):
+ bare_domain = allowed_domain.replace('.*', '').replace('*.', '')
+ if '*' in bare_domain:
+ logger.error(
+ f'⛔️ allowed_domains only supports *.abc or abc.* style patterns, ignoring allowed_domains=[{allowed_domain}]'
+ )
+ continue
+
+ # Special handling so that *.google.com also matches bare google.com
+ if len(allowed_domain) > 2 and allowed_domain.startswith('*.'):
+ parent_domain = allowed_domain[2:]
+ if domain == parent_domain or fnmatch(domain, parent_domain):
_show_glob_warning(domain, allowed_domain)
return True
- else:
- # Standard matching (exact or subdomain)
- if domain == allowed_domain:
- return True
- return False
+ # Normal case: match domain abc.google.com against pattern *.google.com
+ if fnmatch(domain, allowed_domain):
+ _show_glob_warning(domain, allowed_domain)
+ return True
except Exception as e:
- logger.error(f'⛔️ Error checking URL allowlist: {type(e).__name__}: {e}')
- return False
+ failing_domain = allowed_domain or ', '.join(self.browser_profile.allowed_domains)
+ logger.error(f'⛔️ Error checking if page URL is in allowed_domains=[{failing_domain}]: {type(e).__name__}: {e}')
+ return False
async def _check_and_handle_navigation(self, page: Page) -> None:
"""Check if current page URL is allowed and handle if not."""
@@ -1391,8 +1508,19 @@ class BrowserSession(BaseModel):
# region - User Actions
- @classmethod
- def _convert_simple_xpath_to_css_selector(cls, xpath: str) -> str:
+ @staticmethod
+ async def _get_unique_filename(directory: str, filename: str) -> str:
+ """Generate a unique filename for downloads by appending (1), (2), etc., if a file already exists."""
+ base, ext = os.path.splitext(filename)
+ counter = 1
+ new_filename = filename
+ while os.path.exists(os.path.join(directory, new_filename)):
+ new_filename = f'{base} ({counter}){ext}'
+ counter += 1
+ return new_filename
+
+ @staticmethod
+ def _convert_simple_xpath_to_css_selector(xpath: str) -> str:
"""Converts simple XPath expressions to CSS selectors."""
if not xpath:
return ''
@@ -1558,6 +1686,7 @@ class BrowserSession(BaseModel):
tag_name = element.tag_name or '*'
return f"{tag_name}[highlight_index='{element.highlight_index}']"
+ @require_initialization
@time_execution_async('--is_visible')
async def _is_visible(self, element: ElementHandle) -> bool:
"""
@@ -1573,6 +1702,7 @@ class BrowserSession(BaseModel):
return not is_hidden and bbox is not None and bbox['width'] > 0 and bbox['height'] > 0
+ @require_initialization
@time_execution_async('--get_locate_element')
async def get_locate_element(self, element: DOMElementNode) -> ElementHandle | None:
page = await self.get_current_page()
@@ -1619,6 +1749,7 @@ class BrowserSession(BaseModel):
logger.error(f'❌ Failed to locate element: {str(e)}')
return None
+ @require_initialization
@time_execution_async('--get_locate_element_by_xpath')
async def get_locate_element_by_xpath(self, xpath: str) -> ElementHandle | None:
"""
@@ -1639,6 +1770,7 @@ class BrowserSession(BaseModel):
logger.error(f'❌ Failed to locate element by XPath {xpath}: {str(e)}')
return None
+ @require_initialization
@time_execution_async('--get_locate_element_by_css_selector')
async def get_locate_element_by_css_selector(self, css_selector: str) -> ElementHandle | None:
"""
@@ -1659,6 +1791,7 @@ class BrowserSession(BaseModel):
logger.error(f'❌ Failed to locate element by CSS selector {css_selector}: {str(e)}')
return None
+ @require_initialization
@time_execution_async('--get_locate_element_by_text')
async def get_locate_element_by_text(
self, text: str, nth: int | None = 0, element_type: str | None = None
@@ -1859,6 +1992,7 @@ class BrowserSession(BaseModel):
return False
+ @require_initialization
async def get_scroll_info(self, page: Page) -> tuple[int, int]:
"""Get scroll position information for the current page."""
scroll_y = await page.evaluate('window.scrollY')
@@ -1868,6 +2002,7 @@ class BrowserSession(BaseModel):
pixels_below = total_height - (scroll_y + viewport_height)
return pixels_above, pixels_below
+ @require_initialization
async def _scroll_container(self, pixels: int) -> None:
"""Scroll the element that truly owns vertical scroll.Starts at the focused node ➜ climbs to the first big, scroll-enabled ancestor otherwise picks the first scrollable element or the root, then calls `element.scrollBy` (or `window.scrollBy` for the root) by the supplied pixel value."""
@@ -1899,14 +2034,3 @@ class BrowserSession(BaseModel):
}"""
page = await self.get_current_page()
await page.evaluate(SMART_SCROLL_JS, pixels)
-
- @staticmethod
- async def _get_unique_filename(directory, filename):
- """Generate a unique filename by appending (1), (2), etc., if a file already exists."""
- base, ext = os.path.splitext(filename)
- counter = 1
- new_filename = filename
- while os.path.exists(os.path.join(directory, new_filename)):
- new_filename = f'{base} ({counter}){ext}'
- counter += 1
- return new_filename
diff --git a/tests/test_url_allowlist_security.py b/tests/test_url_allowlist_security.py
index 70e1146b9..be5497077 100644
--- a/tests/test_url_allowlist_security.py
+++ b/tests/test_url_allowlist_security.py
@@ -38,23 +38,31 @@ class TestUrlAllowlistSecurity:
assert browser_session._is_url_allowed('https://example.org') is False
# Test more complex glob patterns
- browser_profile = BrowserProfile(allowed_domains=['*google.com', 'wiki*'])
+ browser_profile = BrowserProfile(
+ allowed_domains=['*.google.com', 'https://wiki.*', '*good.com', 'chrome://version', 'brave://*']
+ )
browser_session = BrowserSession(browser_profile=browser_profile)
# Should match domains ending with google.com
assert browser_session._is_url_allowed('https://google.com') is True
assert browser_session._is_url_allowed('https://www.google.com') is True
- assert browser_session._is_url_allowed('https://anygoogle.com') is True
+ assert (
+ browser_session._is_url_allowed('https://evilgood.com') is False
+ ) # make sure we dont allow *good.com patterns, only *.good.com
# Should match domains starting with wiki
+ assert browser_session._is_url_allowed('http://wiki.org') is False
assert browser_session._is_url_allowed('https://wiki.org') is True
- assert browser_session._is_url_allowed('https://wikipedia.org') is True
- # Should not match other domains
- assert browser_session._is_url_allowed('https://example.com') is False
+ # Should not match internal domains because scheme was not provided
+ assert browser_session._is_url_allowed('chrome://google.com') is False
+ assert browser_session._is_url_allowed('chrome://abc.google.com') is False
# Test browser internal URLs
- assert browser_session._is_url_allowed('chrome://settings') is True
+ assert browser_session._is_url_allowed('chrome://settings') is False
+ assert browser_session._is_url_allowed('chrome://version') is True
+ assert browser_session._is_url_allowed('chrome-extension://version/') is False
+ assert browser_session._is_url_allowed('brave://anything/') is True
assert browser_session._is_url_allowed('about:blank') is True
# Test security for glob patterns (authentication credentials bypass attempts)
@@ -67,7 +75,7 @@ class TestUrlAllowlistSecurity:
def test_glob_pattern_edge_cases(self):
"""Test edge cases for glob pattern matching to ensure proper behavior."""
# Test with domains containing glob pattern in the middle
- browser_profile = BrowserProfile(allowed_domains=['*google.com', 'wiki*'])
+ browser_profile = BrowserProfile(allowed_domains=['*.google.com', 'wiki.*'])
browser_session = BrowserSession(browser_profile=browser_profile)
# Verify that 'wiki*' pattern doesn't match domains that merely contain 'wiki' in the middle