Skip to content

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

refc: removed 2fa_codes_function

Saurav Panda09795c0531a5
diff --git a/browser_use/integrations/gmail/__init__.py b/browser_use/integrations/gmail/__init__.py
index 0fbfac3d5..e963b4227 100644
--- a/browser_use/integrations/gmail/__init__.py
+++ b/browser_use/integrations/gmail/__init__.py
@@ -1,7 +1,7 @@
"""
Gmail Integration for Browser Use
-Provides Gmail API integration for handling 2FA codes and email reading.
-This integration enables agents to authenticate via email when 2FA is required.
+Provides Gmail API integration for email reading and verification code extraction.
+This integration enables agents to read email content and extract verification codes themselves.
Usage:
from browser_use.integrations.gmail import GmailService, register_gmail_actions
# Option 1: Register Gmail actions with file-based authentication
@@ -13,7 +13,7 @@ Usage:
# Option 3: Use the service directly
gmail = GmailService(access_token="your_access_token_here")
await gmail.authenticate()
- codes = await gmail.find_2fa_codes()
+ emails = await gmail.get_recent_emails()
"""
# @file purpose: Gmail integration for 2FA email authentication and email reading
diff --git a/browser_use/integrations/gmail/actions.py b/browser_use/integrations/gmail/actions.py
index 7225d86e3..af902c3ad 100644
--- a/browser_use/integrations/gmail/actions.py
+++ b/browser_use/integrations/gmail/actions.py
@@ -4,7 +4,6 @@ Defines agent actions for Gmail integration including 2FA code retrieval,
email reading, and authentication management.
"""
-import asyncio
import logging
from pydantic import BaseModel, Field
@@ -20,20 +19,12 @@ logger = logging.getLogger(__name__)
_gmail_service: GmailService | None = None
-class Find2FACodesParams(BaseModel):
- """Parameters for finding 2FA codes in emails"""
-
- time_filter: str = Field(default='2m', description='Time filter for emails (e.g., "2m", "5m", "1h", "1d")')
- sender_email: str | None = Field(default=None, description='Filter by specific sender email address')
- custom_patterns: list[str] | None = Field(default=None, description='Additional regex patterns to search for codes')
-
-
class GetRecentEmailsParams(BaseModel):
"""Parameters for getting recent emails"""
- max_results: int = Field(default=10, description='Maximum number of emails to fetch')
- query: str = Field(default='', description='Gmail search query (e.g., "from:[email protected]")')
- time_filter: str = Field(default='1h', description='Time filter for emails (e.g., "5m", "1h", "1d")')
+ query: str = Field(
+ default='', description='Gmail search query (e.g., "from:[email protected]") - optional additional filter'
+ )
def register_gmail_actions(
@@ -57,16 +48,13 @@ def register_gmail_actions(
_gmail_service = GmailService()
@controller.action(
- description='πŸ” **USE THIS FOR VERIFICATION CODES - NOT get_recent_emails** πŸ” '
- 'When you need verification codes/OTP/2FA: USE THIS ACTION IMMEDIATELY! '
- 'This searches Gmail, finds codes, extracts them automatically. '
- 'DO NOT use get_recent_emails for verification - it cannot extract codes! '
- 'This action is specifically built for code extraction from emails. '
- 'One call gets you the actual numeric code ready to input.',
- param_model=Find2FACodesParams,
+ description='πŸ“§ **Get recent verification emails** - Fetches the last 20 emails from the past 5 minutes with full content. '
+ 'Perfect for finding verification codes, OTP, 2FA, or any recent email content. '
+ 'Returns complete email content so you can extract verification codes or analyze email details yourself.',
+ param_model=GetRecentEmailsParams,
)
- async def find_2fa_codes(params: Find2FACodesParams) -> ActionResult:
- """Find 2FA verification codes in recent emails"""
+ async def get_recent_emails(params: GetRecentEmailsParams) -> ActionResult:
+ """Get recent emails from the last 5 minutes with full content"""
try:
if _gmail_service is None:
raise RuntimeError('Gmail service not initialized')
@@ -81,117 +69,37 @@ def register_gmail_actions(
include_in_memory=True,
)
- # Find 2FA codes with retry logic (4 attempts with longer waits for email delivery)
- max_retries = 4
- codes_found = None
- wait_times = [10, 20, 30] # 10s, 20s, 30s (total 60s wait time)
-
- for attempt in range(max_retries):
- # Ensure authentication before each attempt
- if not _gmail_service.is_authenticated():
- logger.info(f'πŸ“§ Gmail not authenticated (attempt {attempt + 1}), attempting authentication...')
- authenticated = await _gmail_service.authenticate()
- if not authenticated:
- logger.warning(f'❌ Gmail authentication failed on attempt {attempt + 1}')
- # Continue to next attempt rather than failing immediately
- if attempt < max_retries - 1:
- wait_time = wait_times[attempt]
- logger.info(f'πŸ”„ Retrying authentication in {wait_time}s...')
- await asyncio.sleep(wait_time)
- continue
-
- codes_found = await _gmail_service.find_2fa_codes(
- time_filter=params.time_filter, sender_email=params.sender_email, custom_patterns=params.custom_patterns
- )
-
- if codes_found:
- break
-
- # If not the last attempt, wait for email delivery
- if attempt < max_retries - 1:
- wait_time = wait_times[attempt]
- logger.info(f'πŸ”„ No 2FA codes found (attempt {attempt + 1}/{max_retries}), retrying in {wait_time}s...')
- await asyncio.sleep(wait_time)
-
- if not codes_found:
- return ActionResult(
- extracted_content=f'πŸ” No 2FA codes found in emails from the last {params.time_filter} after {max_retries} attempts. '
- f'{"Filter: " + params.sender_email if params.sender_email else ""}',
- include_in_memory=True,
- )
-
- # Format results
- results = []
- for email_with_codes in codes_found:
- results.append(
- {
- 'codes': email_with_codes['codes'],
- 'from': email_with_codes['from'],
- 'subject': email_with_codes['subject'],
- 'snippet': email_with_codes['body_snippet'],
- }
- )
+ # Fixed parameters: 10 emails max, last 5 minutes
+ max_results = 10
+ time_filter = '5m'
- # Return the most recent code as the primary result
- primary_code = codes_found[0]['codes'][0]
+ # Build query with time filter and optional user query
+ query_parts = [f'newer_than:{time_filter}']
+ if params.query.strip():
+ query_parts.append(params.query.strip())
- content = f'βœ… Found 2FA code: {primary_code}\n'
- content += f'πŸ“§ From: {codes_found[0]["from"]}\n'
- content += f'πŸ“ Subject: {codes_found[0]["subject"]}\n'
-
- if len(codes_found) > 1:
- content += f'\nπŸ” Additional {len(codes_found) - 1} emails with codes found.'
-
- return ActionResult(extracted_content=content, include_in_memory=True)
-
- except Exception as e:
- logger.error(f'Error finding 2FA codes: {e}')
- return ActionResult(extracted_content=f'❌ Error finding 2FA codes: {str(e)}', include_in_memory=True)
-
- @controller.action(
- description='πŸ“§ **General Email Reading** - For newsletters, notifications, and email content analysis. '
- '⚠️ DO NOT use when you need verification codes, OTP, 2FA, or login codes! '
- "For any verification scenario, use find_2fa_codes instead - it's specifically designed for that. "
- 'This action has limited search capabilities that miss verification emails.',
- param_model=GetRecentEmailsParams,
- )
- async def get_recent_emails(params: GetRecentEmailsParams) -> ActionResult:
- """Get recent emails from Gmail"""
- try:
- if _gmail_service is None:
- raise RuntimeError('Gmail service not initialized')
-
- # Ensure authentication
- if not _gmail_service.is_authenticated():
- logger.info('πŸ“§ Gmail not authenticated, attempting authentication...')
- authenticated = await _gmail_service.authenticate()
- if not authenticated:
- return ActionResult(
- extracted_content='❌ Failed to authenticate with Gmail. Please ensure Gmail credentials are set up properly.',
- include_in_memory=True,
- )
+ query = ' '.join(query_parts)
+ logger.info(f'πŸ” Gmail search query: {query}')
# Get emails
- emails = await _gmail_service.get_recent_emails(
- max_results=params.max_results, query=params.query, time_filter=params.time_filter
- )
+ emails = await _gmail_service.get_recent_emails(max_results=max_results, query=query, time_filter=time_filter)
if not emails:
- query_info = f" matching '{params.query}'" if params.query else ''
+ query_info = f" matching '{params.query}'" if params.query.strip() else ''
return ActionResult(
- extracted_content=f'πŸ“­ No emails found from the last {params.time_filter}{query_info}', include_in_memory=True
+ extracted_content=f'πŸ“­ No emails found from the last {time_filter}{query_info}', include_in_memory=True
)
- # Format email summary
- content = f'πŸ“§ Found {len(emails)} recent emails:\n\n'
-
- for i, email in enumerate(emails[:5], 1): # Show first 5 emails
- content += f'{i}. From: {email["from"]}\n'
- content += f' Subject: {email["subject"]}\n'
- content += f' Preview: {email["body"][:100]}...\n\n'
+ # Format with full email content
+ content = f'πŸ“§ Found {len(emails)} recent email{"s" if len(emails) > 1 else ""} from the last {time_filter}:\n\n'
- if len(emails) > 5:
- content += f'... and {len(emails) - 5} more emails'
+ for i, email in enumerate(emails, 1):
+ content += f'πŸ“§ Email {i}:\n'
+ content += f'From: {email["from"]}\n'
+ content += f'Subject: {email["subject"]}\n'
+ content += f'Date: {email["date"]}\n'
+ content += f'Content:\n{email["body"]}\n'
+ content += '-' * 50 + '\n\n'
return ActionResult(extracted_content=content, include_in_memory=True)
diff --git a/browser_use/integrations/gmail/service.py b/browser_use/integrations/gmail/service.py
index 69e07f504..3658a3036 100644
--- a/browser_use/integrations/gmail/service.py
+++ b/browser_use/integrations/gmail/service.py
@@ -7,7 +7,6 @@ This service provides a clean interface for agents to interact with Gmail.
import base64
import logging
import os
-import re
from pathlib import Path
from typing import Any
@@ -25,12 +24,11 @@ logger = logging.getLogger(__name__)
class GmailService:
"""
- Gmail API service for email reading and 2FA code extraction.
+ Gmail API service for email reading.
Provides functionality to:
- Authenticate with Gmail API using OAuth2
- Read recent emails with filtering
- - Extract 2FA codes from email content
- - Poll for new 2FA codes
+ - Return full email content for agent analysis
"""
# Gmail API scopes
@@ -226,142 +224,3 @@ class GmailService:
body = base64.urlsafe_b64decode(part['body']['data']).decode('utf-8')
return body
-
- async def find_2fa_codes(
- self, time_filter: str = '5m', sender_email: str | None = None, custom_patterns: list[str] | None = None
- ) -> list[dict[str, Any]]:
- """
- Find 2FA verification codes in recent emails
- Args:
- time_filter: Time filter for emails (e.g., '5m', '1h', '1d')
- sender_email: Filter by specific sender email
- custom_patterns: Additional regex patterns to look for codes
- Returns:
- List of emails containing potential 2FA codes
- """
- logger.info(f'πŸ” Looking for 2FA codes in emails from last {time_filter}...')
-
- # Build search query for 2FA-related emails - very inclusive with simple terms
- query_parts = [
- f'newer_than:{time_filter}',
- '(code OR otp OR "one time password" OR "verification code" OR 2FA OR "two-factor" OR "authentication code" OR verify OR "login code" OR "access your account" OR "sign in" OR "enter the code")',
- ]
-
- if sender_email:
- query_parts.append(f'from:{sender_email}')
-
- query = ' '.join(query_parts)
- logger.info(f'πŸ” Gmail search query: {query}')
-
- emails = await self.get_recent_emails(max_results=10, query=query)
-
- codes_found = []
-
- for email in emails:
- codes = self._extract_codes_from_text(email['body'], custom_patterns)
- if codes:
- codes_found.append(
- {
- 'subject': email['subject'],
- 'from': email['from'],
- 'timestamp': email['timestamp'],
- 'codes': codes,
- 'body_snippet': email['body'][:200] + '...' if len(email['body']) > 200 else email['body'],
- 'email_id': email['id'],
- }
- )
-
- # Sort by timestamp (most recent first) and keep only the most recent per sender
- codes_found.sort(key=lambda x: x['timestamp'], reverse=True)
-
- # Group by sender and keep only the most recent from each
- seen_senders = set()
- filtered_codes = []
- for email_with_codes in codes_found:
- sender = email_with_codes['from']
- if sender not in seen_senders:
- seen_senders.add(sender)
- filtered_codes.append(email_with_codes)
-
- logger.info(f'🎯 Found {len(filtered_codes)} recent emails with 2FA codes (most recent per sender)')
- return filtered_codes
-
- def _extract_codes_from_text(self, text: str, custom_patterns: list[str] | None = None) -> list[str]:
- """Extract potential verification codes from text"""
- if not text:
- return []
-
- # Common 2FA code patterns - prioritize context-specific patterns to avoid URL noise
- patterns = [
- # High priority: Context-specific patterns
- r'(?:code|verification|OTP)[:\s]+(\d{4,8})', # "code: 123456"
- r'(?:your|the)\s+(?:code|verification)\s+(?:is|code)[:\s]+(\d{4,8})', # "your code is 123456"
- r'(?:enter|use)\s+(?:code|verification)[:\s]+(\d{4,8})', # "enter code: 123456"
- r'(?:below|code)\.\s*(\d{4,8})', # "code below. 12345"
- r'(?:emailCode=)(\d{4,8})', # URL parameter like emailCode=77599
- # Lower priority: Standalone numbers (but exclude those in long URLs)
- r'(?<![\w\-])\d{5}(?![\w\-])', # 5-digit codes (like 80565) not in URLs
- r'(?<![\w\-])\d{6}(?![\w\-])', # 6-digit codes (most common) not in URLs
- ]
-
- # Add custom patterns if provided
- if custom_patterns:
- patterns.extend(custom_patterns)
-
- found_codes_with_priority = []
-
- for i, pattern in enumerate(patterns):
- matches = re.findall(pattern, text, re.IGNORECASE)
- for match in matches:
- code = match if isinstance(match, str) else str(match)
- # Assign priority based on pattern order (earlier patterns = higher priority)
- priority = len(patterns) - i
- found_codes_with_priority.append((code, priority))
-
- # Filter out codes from long URLs (except emailCode parameter)
- filtered_codes_with_priority = []
- for code, priority in found_codes_with_priority:
- # Skip codes that are part of long URL UUIDs or tokens
- code_index = text.find(code)
- if code_index != -1:
- # Check surrounding context for URL patterns
- context_start = max(0, code_index - 30)
- context_end = min(len(text), code_index + len(code) + 30)
- context = text[context_start:context_end]
-
- # Skip if it's part of a UUID in a URL (like af6e5ca8-f2ae-4932-97d9)
- if re.search(r'[a-f0-9]{8}-[a-f0-9]{4}-' + re.escape(code) + r'-[a-f0-9]{4}', context):
- continue
-
- # Special case: emailCode parameter gets highest priority
- if 'emailCode=' in context:
- priority = 1000
-
- filtered_codes_with_priority.append((code, priority))
-
- # Sort by priority (highest first) and remove duplicates
- filtered_codes_with_priority.sort(key=lambda x: x[1], reverse=True)
-
- # Remove duplicates while preserving priority order
- seen = set()
- unique_codes = []
- for code, priority in filtered_codes_with_priority:
- if code not in seen and 4 <= len(code) <= 8 and re.match(r'^\d+$', code):
- seen.add(code)
- unique_codes.append(code)
-
- # If no numeric codes found, allow alphanumeric but with stricter filtering
- if not unique_codes:
- for code, priority in filtered_codes_with_priority:
- if (
- code not in seen
- and 4 <= len(code) <= 8
- and re.match(r'^[A-Z0-9]+$', code, re.IGNORECASE)
- and not re.match(r'^[A-F0-9]{6}$', code) # Exclude likely hex color codes
- and code
- not in ['header', 'padding', 'button', 'margin', 'border', 'center', 'hidden', 'normal', 'mobile', 'device']
- ):
- seen.add(code)
- unique_codes.append(code)
-
- return unique_codes