Skip to content

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

Enhance authentication flow in CLI and sync service

Magnus Müller37e43449db6d
diff --git a/browser_use/cli.py b/browser_use/cli.py
index 2756ae459..fc30ff1fb 100644
--- a/browser_use/cli.py
+++ b/browser_use/cli.py
@@ -1600,9 +1600,31 @@ async def run_auth_command():
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)
+ # Create a minimal sync service to establish session context like main branch does
+ from uuid_extensions import uuid7str
+
+ from browser_use.agent.cloud_events import CreateAgentSessionEvent
+ from browser_use.sync.service import CloudSync
+
+ # Create session ID and sync service with auth context flag
+ session_id = uuid7str()
+ sync_service = CloudSync(allow_session_events_for_auth=True)
+
+ # Create a minimal session event to establish context (like main branch)
+ session_event = CreateAgentSessionEvent(
+ user_id=auth_client.temp_user_id,
+ browser_session_id=uuid7str(),
+ browser_session_live_url='',
+ browser_session_cdp_url='',
+ device_id=auth_client.device_id,
+ )
+ session_event.id = session_id # Set the session ID
+
+ # Handle the session event to set up the sync context
+ await sync_service.handle_event(session_event)
+
+ # Now authenticate using the established session context
+ success = await sync_service.authenticate(show_instructions=True)
if success:
print('🎉 Authentication successful!')
print(' Future browser-use runs will now sync to the cloud.')
diff --git a/browser_use/sync/service.py b/browser_use/sync/service.py
index 6ab3bf5ae..475b8a328 100644
--- a/browser_use/sync/service.py
+++ b/browser_use/sync/service.py
@@ -18,12 +18,13 @@ logger = logging.getLogger(__name__)
class CloudSync:
"""Service for syncing events to the Browser Use cloud"""
- def __init__(self, base_url: str | None = None):
+ def __init__(self, base_url: str | None = None, allow_session_events_for_auth: bool = False):
# 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.auth_client = DeviceAuthClient(base_url=self.base_url)
self.auth_task = None
self.session_id: str | None = None
+ self.allow_session_events_for_auth = allow_session_events_for_auth
async def handle_event(self, event: BaseEvent) -> None:
"""Handle an event by sending it to the cloud"""
@@ -40,8 +41,12 @@ class CloudSync:
else:
logger.warning('Cannot start auth - session_id not set yet')
- # Only send event if user is authenticated
+ # Send events based on authentication status and context
if self.auth_client.is_authenticated:
+ # User is authenticated - send all events
+ await self._send_event(event)
+ elif event.event_type == 'CreateAgentSessionEvent' and self.allow_session_events_for_auth:
+ # Special case: allow session events for auth flow only
await self._send_event(event)
else:
# User is not authenticated - don't send anything
diff --git a/tests/ci/test_sync_client_auth.py b/tests/ci/test_sync_client_auth.py
index a64498cb5..a1a1128bf 100644
--- a/tests/ci/test_sync_client_auth.py
+++ b/tests/ci/test_sync_client_auth.py
@@ -381,7 +381,7 @@ class TestCloudSync:
assert event['task'] == 'Test task'
async def test_send_event_pre_auth(self, httpserver: HTTPServer, temp_config_dir):
- """Test that events are not sent before authentication."""
+ """Test that non-session events are not sent before authentication."""
requests = []
def capture_request(request):
@@ -395,8 +395,7 @@ class TestCloudSync:
return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
- # Don't expect any requests since events should not be sent
- # httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_request)
+ httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_request)
# Create unauthenticated service
auth = DeviceAuthClient(base_url=httpserver.url_for(''))
@@ -406,7 +405,18 @@ class TestCloudSync:
service.auth_client = auth
service.session_id = 'test-session-id'
- # Send event
+ # Send session event first (should be sent)
+ await service.handle_event(
+ CreateAgentSessionEvent(
+ user_id=TEMP_USER_ID,
+ browser_session_id='test-browser-session',
+ browser_session_live_url='http://example.com',
+ browser_session_cdp_url='ws://example.com',
+ device_id='test-device-id',
+ )
+ )
+
+ # Send task event (should be skipped - not authenticated)
await service.handle_event(
CreateAgentTaskEvent(
agent_session_id='test-session',
@@ -421,8 +431,9 @@ class TestCloudSync:
)
)
- # Check that NO request was made (event should be skipped)
- assert len(requests) == 0
+ # Check that only the session event was sent (1 request)
+ assert len(requests) == 1
+ assert requests[0]['json']['events'][0]['event_type'] == 'CreateAgentSessionEvent'
async def test_authenticate_then_send(self, httpserver: HTTPServer, temp_config_dir):
"""Test that events are only sent after authentication."""