Skip to content

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

Implement cloud authentication feature in CLI and sync services

Magnus Müller9828d18871dd
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 5bd078295..f315d14e7 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -1952,6 +1952,25 @@ class Agent(Generic[Context, AgentStructuredOutput]):
},
}
+ async def authenticate_cloud_sync(self, show_instructions: bool = True) -> bool:
+ """
+ Authenticate with cloud service for future runs.
+
+ This is useful when users want to authenticate after a task has completed
+ so that future runs will sync to the cloud.
+
+ Args:
+ show_instructions: Whether to show authentication instructions to user
+
+ Returns:
+ bool: True if authentication was successful
+ """
+ if not hasattr(self, 'cloud_sync') or self.cloud_sync is None:
+ self.logger.warning('Cloud sync is not available for this agent')
+ return False
+
+ return await self.cloud_sync.authenticate(show_instructions=show_instructions)
+
def run_sync(
self,
max_steps: int = 100,
diff --git a/browser_use/cli.py b/browser_use/cli.py
index a1a95d937..2756ae459 100644
--- a/browser_use/cli.py
+++ b/browser_use/cli.py
@@ -1574,6 +1574,46 @@ async def textual_interface(config: dict[str, Any]):
raise
+async def run_auth_command():
+ """Run the authentication command."""
+
+ from browser_use.sync.auth import DeviceAuthClient
+
+ print('🔐 Browser Use Cloud Authentication')
+ print('=' * 40)
+
+ auth_client = DeviceAuthClient()
+
+ # Check if already authenticated
+ if auth_client.is_authenticated:
+ print('✅ Already authenticated!')
+ print(f' User ID: {auth_client.user_id}')
+ print(f' Authenticated at: {auth_client.auth_config.authorized_at}')
+
+ # Show cloud URL if possible
+ frontend_url = CONFIG.BROWSER_USE_CLOUD_UI_URL or auth_client.base_url.replace('//api.', '//cloud.')
+ print(f'\n🌐 View your runs at: {frontend_url}')
+ return
+
+ print('🚀 Starting authentication flow...')
+ print(' This will open a browser window for you to sign in.')
+ print()
+
+ try:
+ # For standalone auth, use a special session ID that indicates it's for auth only
+ standalone_auth_session_id = '00000000-0000-0000-0000-000000000001' # Special ID for standalone auth
+ success = await auth_client.authenticate(agent_session_id=standalone_auth_session_id, show_instructions=True)
+ if success:
+ print('🎉 Authentication successful!')
+ print(' Future browser-use runs will now sync to the cloud.')
+ else:
+ print('❌ Authentication failed.')
+ print(' Please try again or check your internet connection.')
+ except Exception as e:
+ print(f'❌ Authentication error: {e}')
+ sys.exit(1)
+
+
@click.command()
@click.option('--version', is_flag=True, help='Print version and exit')
@click.option('--model', type=str, help='Model to use (e.g., gpt-5-mini, claude-4-sonnet, gemini-2.5-flash)')
@@ -1592,9 +1632,10 @@ async def textual_interface(config: dict[str, Any]):
@click.option('--proxy-password', type=str, help='Proxy auth password')
@click.option('-p', '--prompt', type=str, help='Run a single task without the TUI (headless mode)')
@click.option('--mcp', is_flag=True, help='Run as MCP server (exposes JSON RPC via stdin/stdout)')
[email protected]('--auth', is_flag=True, help='Authenticate with Browser Use Cloud')
@click.pass_context
def main(ctx: click.Context, debug: bool = False, **kwargs):
- """Browser-Use Interactive TUI or Command Line Executor
+ """Run Browser-Use Interactive TUI or Command Line Executor
Use --user-data-dir to specify a local Chrome profile directory.
Common Chrome profile locations:
@@ -1612,6 +1653,11 @@ def main(ctx: click.Context, debug: bool = False, **kwargs):
print(version('browser-use'))
sys.exit(0)
+ # Check if auth mode is activated
+ if kwargs.get('auth'):
+ asyncio.run(run_auth_command())
+ return
+
# Check if MCP server mode is activated
if kwargs.get('mcp'):
# Capture telemetry for MCP server mode via CLI
diff --git a/browser_use/sync/auth.py b/browser_use/sync/auth.py
index e8b6ec508..6d08a46ec 100644
--- a/browser_use/sync/auth.py
+++ b/browser_use/sync/auth.py
@@ -134,7 +134,7 @@ class DeviceAuthClient:
data={
'client_id': self.client_id,
'scope': self.scope,
- 'agent_session_id': agent_session_id,
+ 'agent_session_id': agent_session_id or '',
'device_id': self.device_id,
},
)
@@ -147,7 +147,7 @@ class DeviceAuthClient:
data={
'client_id': self.client_id,
'scope': self.scope,
- 'agent_session_id': agent_session_id,
+ 'agent_session_id': agent_session_id or '',
'device_id': self.device_id,
},
)
diff --git a/browser_use/sync/service.py b/browser_use/sync/service.py
index d6de419cf..6ab3bf5ae 100644
--- a/browser_use/sync/service.py
+++ b/browser_use/sync/service.py
@@ -18,12 +18,10 @@ logger = logging.getLogger(__name__)
class CloudSync:
"""Service for syncing events to the Browser Use cloud"""
- def __init__(self, base_url: str | None = None, enable_auth: bool = True):
+ def __init__(self, base_url: str | None = None):
# Backend API URL for all API requests - can be passed directly or defaults to env var
self.base_url = base_url or CONFIG.BROWSER_USE_CLOUD_API_URL
- self.enable_auth = enable_auth
- self.auth_client = DeviceAuthClient(base_url=self.base_url) if enable_auth else None
- self.pending_events: list[BaseEvent] = []
+ self.auth_client = DeviceAuthClient(base_url=self.base_url)
self.auth_task = None
self.session_id: str | None = None
@@ -34,23 +32,20 @@ class CloudSync:
if event.event_type == 'CreateAgentSessionEvent' and hasattr(event, 'id'):
self.session_id = str(event.id) # type: ignore
- # Start authentication flow on first step (after first LLM response)
- if event.event_type == 'CreateAgentStepEvent' and 'step' in dict(event):
- step = dict(event)['step']
- # logger.debug(f'Got CreateAgentStepEvent with step={step}')
- # Trigger on the first step (step=2 because n_steps is incremented before actions)
- if step == 2 and self.enable_auth and self.auth_client:
- if not hasattr(self, 'auth_task') or self.auth_task is None:
- # Start auth in background
- if self.session_id:
- # logger.info('Triggering auth on first step event')
- # Always run auth to show the cloud URL, even if already authenticated
- self.auth_task = asyncio.create_task(self._background_auth(agent_session_id=self.session_id))
- else:
- logger.warning('Cannot start auth - session_id not set yet')
-
- # Send event to cloud
- await self._send_event(event)
+ # Start authentication immediately when session is created
+ if not hasattr(self, 'auth_task') or self.auth_task is None:
+ if self.session_id:
+ # Start auth in background immediately
+ self.auth_task = asyncio.create_task(self._background_auth(agent_session_id=self.session_id))
+ else:
+ logger.warning('Cannot start auth - session_id not set yet')
+
+ # Only send event if user is authenticated
+ if self.auth_client.is_authenticated:
+ await self._send_event(event)
+ else:
+ # User is not authenticated - don't send anything
+ logger.debug(f'Skipping event {event.event_type} - user not authenticated')
except Exception as e:
logger.error(f'Failed to handle {event.event_type} event: {type(e).__name__}: {e}', exc_info=True)
@@ -84,10 +79,7 @@ class CloudSync:
timeout=10.0,
)
- if response.status_code == 401 and self.auth_client and not self.auth_client.is_authenticated:
- # Store event for retry after auth
- self.pending_events.append(event)
- elif response.status_code >= 400:
+ if response.status_code >= 400:
# Log error but don't raise - we want to fail silently
logger.debug(
f'Failed to send sync event: POST {response.request.url} {response.status_code} - {response.text}'
@@ -104,7 +96,7 @@ class CloudSync:
async def _background_auth(self, agent_session_id: str) -> None:
"""Run authentication in background or show cloud URL if already authenticated"""
- assert self.auth_client, 'enable_auth=True must be set before calling CloudSync_background_auth()'
+ assert self.auth_client, 'auth_client must exist before calling CloudSync._background_auth()'
assert self.session_id, 'session_id must be set before calling CloudSync._background_auth() can fire'
try:
# If already authenticated, just show the cloud URL
@@ -119,36 +111,16 @@ class CloudSync:
logger.info('─' * max(terminal_width - 40, 20) + '\n\n')
return
- # Otherwise run full authentication
- success = await self.auth_client.authenticate(
- agent_session_id=agent_session_id,
- show_instructions=True,
- )
-
- if success:
- # Resend any pending events
- await self._resend_pending_events()
-
- # Update WAL events with real user_id
- # await self._update_wal_user_ids(agent_session_id)
+ # Otherwise show simple auth prompt
+ terminal_width, _terminal_height = shutil.get_terminal_size((80, 20))
+ logger.info('─' * max(terminal_width - 40, 20))
+ logger.info('🔐 To view this run in Browser Use Cloud, authenticate with:')
+ logger.info(' 👉 browser-use auth')
+ logger.info('─' * max(terminal_width - 40, 20) + '\n')
except Exception as e:
logger.debug(f'Cloud sync authentication failed: {e}')
- async def _resend_pending_events(self) -> None:
- """Resend events that were queued during auth"""
- if not self.pending_events:
- return
-
- # Send all pending events
- for event in self.pending_events:
- try:
- await self._send_event(event)
- except Exception as e:
- logger.warning(f'Failed to resend pending event: {e}')
-
- self.pending_events.clear()
-
# async def _update_wal_user_ids(self, session_id: str) -> None:
# """Update user IDs in WAL file after authentication"""
# try:
@@ -190,7 +162,4 @@ class CloudSync:
async def authenticate(self, show_instructions: bool = True) -> bool:
"""Authenticate with the cloud service"""
- if not self.auth_client:
- return False
-
return await self.auth_client.authenticate(agent_session_id=self.session_id, show_instructions=show_instructions)
diff --git a/docs/development/monitoring/observability.mdx b/docs/development/monitoring/observability.mdx
index 8c962ae3b..1c275b378 100644
--- a/docs/development/monitoring/observability.mdx
+++ b/docs/development/monitoring/observability.mdx
@@ -56,3 +56,37 @@ In the trace view, you can also see the agent's current step, the tool it's usin
## Laminar
To learn more about tracing and evaluating your browser agents, check out the [Laminar docs](https://docs.lmnr.ai).
+
+## Browser Use Cloud Authentication
+
+Browser Use can sync your agent runs to the cloud for easy viewing and sharing. Authentication is required to protect your data.
+
+### Quick Setup
+
+```bash
+# Authenticate once to enable cloud sync for all future runs
+browser-use auth
+```
+
+### Manual Authentication
+
+```python
+# Authenticate from code after task completion
+from browser_use import Agent
+
+agent = Agent(task="your task")
+await agent.run()
+
+# Later, authenticate for future runs
+await agent.authenticate_cloud_sync()
+```
+
+### Reset Authentication
+
+```bash
+# Force re-authentication with a different account
+rm ~/.config/browseruse/cloud_auth.json
+browser-use auth
+```
+
+**Note**: Authentication uses OAuth Device Flow - you must complete the auth process while the command is running. Links expire when the polling stops.
diff --git a/tests/ci/test_sync_client_auth.py b/tests/ci/test_sync_client_auth.py
index 487aef335..a64498cb5 100644
--- a/tests/ci/test_sync_client_auth.py
+++ b/tests/ci/test_sync_client_auth.py
@@ -318,16 +318,11 @@ class TestCloudSync:
async def test_init(self, temp_config_dir, httpserver):
"""Test CloudSync initialization."""
- service = CloudSync(
- base_url=httpserver.url_for(''),
- enable_auth=True,
- )
+ service = CloudSync(base_url=httpserver.url_for(''))
assert service.base_url == httpserver.url_for('')
- assert service.enable_auth is True
assert service.auth_client is not None
assert isinstance(service.auth_client, DeviceAuthClient)
- assert service.pending_events == []
async def test_send_event_authenticated(self, httpserver: HTTPServer, temp_config_dir):
"""Test sending event when authenticated."""
@@ -351,7 +346,7 @@ class TestCloudSync:
auth.auth_config.api_token = 'test-api-key'
auth.auth_config.user_id = 'test-user-123'
- service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service = CloudSync(base_url=httpserver.url_for(''))
service.auth_client = auth
service.session_id = 'test-session-id'
@@ -386,7 +381,7 @@ class TestCloudSync:
assert event['task'] == 'Test task'
async def test_send_event_pre_auth(self, httpserver: HTTPServer, temp_config_dir):
- """Test sending event before authentication."""
+ """Test that events are not sent before authentication."""
requests = []
def capture_request(request):
@@ -400,13 +395,14 @@ class TestCloudSync:
return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
- httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_request)
+ # Don't expect any requests since events should not be sent
+ # httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_request)
# Create unauthenticated service
auth = DeviceAuthClient(base_url=httpserver.url_for(''))
# Don't set api_token - leave it unauthenticated
- service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service = CloudSync(base_url=httpserver.url_for(''))
service.auth_client = auth
service.session_id = 'test-session-id'
@@ -425,54 +421,35 @@ class TestCloudSync:
)
)
- # Check request was made without auth header
- assert len(requests) == 1
- request_data = requests[0]
- assert 'Authorization' not in request_data['headers']
+ # Check that NO request was made (event should be skipped)
+ assert len(requests) == 0
- # Check event was sent with temp user ID
- json_data = request_data['json']
- assert len(json_data['events']) == 1
- event = json_data['events'][0]
- assert event['event_type'] == 'CreateAgentTaskEvent'
- assert event['user_id'] == TEMP_USER_ID
- assert event['task'] == 'Test task'
-
- async def test_authenticate_and_resend(self, httpserver: HTTPServer, temp_config_dir):
- """Test authentication flow with pre-auth event resending."""
+ async def test_authenticate_then_send(self, httpserver: HTTPServer, temp_config_dir):
+ """Test that events are only sent after authentication."""
requests = []
- request_count = 0
- def handle_events_request(request):
- nonlocal request_count
- request_count += 1
+ def capture_request(request):
requests.append(
{
'headers': dict(request.headers),
'json': request.get_json(),
}
)
-
from werkzeug.wrappers import Response
- if request_count == 1:
- # First request: unauthenticated, return 401
- return Response('{"error": "unauthorized"}', status=401, mimetype='application/json')
- else:
- # Subsequent requests: success
- return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
+ return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
- httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(handle_events_request)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_request)
# Create service with unauthenticated auth client
auth = DeviceAuthClient(base_url=httpserver.url_for(''))
# Start unauthenticated
- service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service = CloudSync(base_url=httpserver.url_for(''))
service.auth_client = auth
service.session_id = 'test-session-id'
- # Send pre-auth event (should get 401 and be queued)
+ # Send pre-auth event (should be skipped)
await service.handle_event(
CreateAgentTaskEvent(
agent_session_id='test-session',
@@ -487,31 +464,33 @@ class TestCloudSync:
)
)
- # Event should be in pending_events since we got 401
- assert len(service.pending_events) == 1
- assert hasattr(service.pending_events[0], 'task') and service.pending_events[0].task == 'Pre-auth task' # type: ignore
- assert hasattr(service.pending_events[0], 'user_id') and service.pending_events[0].user_id == TEMP_USER_ID # type: ignore
+ # No requests should have been made yet
+ assert len(requests) == 0
# Now authenticate the auth client
auth.auth_config.api_token = 'test-api-key'
auth.auth_config.user_id = 'test-user-123'
- # Manually trigger resend of pending events
- await service._resend_pending_events()
-
- # Pre-auth events should be cleared after successful resend
- assert len(service.pending_events) == 0
-
- # Check that events were sent (1 original attempt + 1 resend)
- assert len(requests) == 2
-
- # Check first request was unauthenticated
- assert 'Authorization' not in requests[0]['headers']
- assert requests[0]['json']['events'][0]['user_id'] == TEMP_USER_ID
+ # Send post-auth event (should be sent)
+ await service.handle_event(
+ CreateAgentTaskEvent(
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Post-auth task',
+ user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
+ device_id='test-device-id',
+ )
+ )
- # Check second request was authenticated with updated user_id
- assert requests[1]['headers']['Authorization'] == 'Bearer test-api-key'
- assert requests[1]['json']['events'][0]['user_id'] == 'test-user-123'
+ # Now exactly one request should have been made (the post-auth event)
+ assert len(requests) == 1
+ assert requests[0]['headers']['Authorization'] == 'Bearer test-api-key'
+ assert requests[0]['json']['events'][0]['user_id'] == 'test-user-123'
+ assert requests[0]['json']['events'][0]['task'] == 'Post-auth task'
async def test_error_handling(self, httpserver: HTTPServer, temp_config_dir):
"""Test error handling during event sending."""
@@ -523,7 +502,7 @@ class TestCloudSync:
auth.auth_config.api_token = 'test-api-key'
auth.auth_config.user_id = 'test-user-123'
- service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service = CloudSync(base_url=httpserver.url_for(''))
service.auth_client = auth
service.session_id = 'test-session-id'
@@ -552,8 +531,7 @@ class TestCloudSync:
# auth.auth_config.user_id = 'test-user-123'
# service = CloudSync(
- # base_url='http://localhost:8000',
- # enable_auth=True,
+ # base_url='http://localhost:8000'
# )
# service.auth_client = auth
# service.session_id = 'test-session-id'
@@ -673,7 +651,7 @@ class TestIntegration:
).respond_with_json({'processed': 1, 'failed': 0})
# Create service
- service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service = CloudSync(base_url=httpserver.url_for(''))
service.session_id = 'test-session-id'
# Send pre-auth event
@@ -766,7 +744,7 @@ class TestAuthResilience:
# Create cloud sync service
from browser_use.sync.service import CloudSync
- service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service = CloudSync(base_url=httpserver.url_for(''))
service.auth_client = auth
# Send event - should not raise exception even though token is expired
@@ -804,7 +782,7 @@ class TestAuthResilience:
# Should still be able to create sync service
from browser_use.sync.service import CloudSync
- service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service = CloudSync(base_url=httpserver.url_for(''))
service.auth_client = auth
# Set up events endpoint to handle unauthenticated requests
@@ -840,7 +818,7 @@ class TestAuthResilience:
from browser_use.sync.service import CloudSync
- service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service = CloudSync(base_url=httpserver.url_for(''))
service.auth_client = auth
# Should be able to send events even when server is down
@@ -865,7 +843,7 @@ class TestAuthResilience:
from browser_use.sync.service import CloudSync
- service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service = CloudSync(base_url=httpserver.url_for(''))
service.auth_client = auth
# Send many events while server is down (no responses configured)
@@ -911,7 +889,7 @@ class TestAuthResilience:
from browser_use.sync.service import CloudSync
- service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service = CloudSync(base_url=httpserver.url_for(''))
service.auth_client = auth
# Should handle malformed event response gracefully