whs-authz-authn/browser-use-oauth
Watch
1
0
Fork
You've already forked browser-use-oauth
0
mirror of https://github.com/j93es/browser-use-oauth.git synced 2026-10-12 07:21:21 +09:00

Refactor authentication and session management

- Removed old llm_login and session scripts, replacing them with a new structure for handling SSO login and session management.
- Introduced a new prompt system for collecting SSO redirect URLs, ensuring compliance with security protocols.
- Implemented a robust backend notification system for tracking scan initiation.
- Enhanced browser profile configuration and resource management for improved session handling.
- Added utility functions for environment variable checks and logging.
- Updated the overall architecture to improve maintainability and readability.
This commit is contained in:
imnyang 2025-06-15 12:24:01 +09:00
commit b68425f523
16 changed files with 251 additions and 232 deletions

View file

@ -1,35 +0,0 @@
from browser_use.browser.context import BrowserContextConfig
from pathlib import Path
import os
from typing import Any
def browser_config_kwargs(lang: str = "en_US") -> dict[str, Any]:
browser_config_kwargs: dict[str, Any] = {
"keep_alive": True,
"browser_type": "chromium",
"headless": False,
"disable_security": True,
"extra_browser_args": [
"--disable-web-security",
"--disable-features=VizDisplayCompositor",
"--disable-site-isolation-trials",
"--disable-features=IsolateOrigins,site-per-process",
"--disable-popup-blocking",
"--disable-dev-shm-usage",
f"--lang={lang}",
"--ignore-certificate-errors",
"--ignore-ssl-errors",
"--allow-running-insecure-content"
],
}
proxy_host = os.getenv("PROXY_HOST")
proxy_port = os.getenv("PROXY_PORT")
if proxy_host and proxy_port:
browser_config_kwargs["extra_browser_args"].append(
f"--proxy-server=http={proxy_host}:{proxy_port};https={proxy_host}:{proxy_port}"
)
return browser_config_kwargs

25
lib/llm/__init__.py Normal file
View file

@ -0,0 +1,25 @@
from langchain.callbacks.base import BaseCallbackHandler
from langchain_google_genai import ChatGoogleGenerativeAI
class QuotaExhaustedHandler(BaseCallbackHandler):
def on_llm_error(self, error, **kwargs):
if "ResourceExhausted" in str(error) or "429" in str(error):
print("⚠️ API 쿼터가 소진되었습니다. 재시도 로직에 위임합니다...")
# backoff handled in scan_one_url
def CreateChatGoogleGenerativeAI(model: str):
"""재시도 로직이 포함된 LLM 생성"""
if model == "fallback":
print("⚠️ Fallback 모델을 사용합니다. Envorinment 변수를 확인하세요.")
print("⚠️ Model Gemini-2.0-flash-lite를 사용합니다.")
model = "gemini-2.0-flash-lite"
return ChatGoogleGenerativeAI(
model=model,
max_retries=10, # 최대 재시도 횟수 증가
model_kwargs={
"request_timeout": 120, # 타임아웃 시간 증가 (2분)
},
callbacks=[QuotaExhaustedHandler()],
# API 호출 간격 조정
temperature=0.1,
)

View file

@ -0,0 +1,12 @@
from dotenv import load_dotenv
import os
from lib.llm.prompt import llm_login, session
load_dotenv(override=True)
def extend_planner_system_message():
if os.getenv("PROVIDOR_CREDENTIALS_IN_LLM", "False").lower() == "true":
return llm_login.extend_planner_system_message
else:
return session.extend_planner_system_message

View file

@ -0,0 +1,87 @@
from dotenv import load_dotenv
import os
load_dotenv(override=True)
google_id = os.getenv("GOOGLE_ID", "")
google_password = os.getenv("GOOGLE_PASSWORD", "")
naver_id = os.getenv("NAVER_ID", "")
naver_password = os.getenv("NAVER_PASSWORD", "")
facebook_id = os.getenv("FACEBOOK_ID", "")
facebook_password = os.getenv("FACEBOOK_PASSWORD", "")
github_id = os.getenv("GITHUB_ID", "")
github_password = os.getenv("GITHUB_PASSWORD", "")
# Extended planner prompt
extend_planner_system_message = f"""
🎯 Mission: Collect Initial SSO Redirect URLs (For Browser Automation)
※ **모든 STEP에서 구글 검색, Bing 검색 등 어떤 외부 검색 기능도 절대 사용하지 않고, 초기에 주어진 URL에서 탐색하세요.**
※ **초기에 주어진 URL 내에서 실제로 확인되지 않은 URL로 직접 이동하는것은 허용되지 않습니다.**
0. **초기 블록(Block) 체크**
- 브라우저가 로그인 페이지에 접근하려 할 때, **페이지가 차단(blocked)** 되거나 **방화벽, CAPTCHA, 접근 제한** 등으로 인해 정상적으로 로드되지 않으면 즉시 프로세스를 종료하고 아래 JSON만 반환해야 합니다.
```json
[
{{
"provider": "Blocked",
"oauth_uri": "-"
}}
]
```
- 이후 단계로 절대 넘어가지 않도록 합니다.
1. **로그인 페이지 탐색**
- **클라이언트(비엔터프라이즈) 로그인 페이지**로 직접 이동합니다. **검색 엔진을 사용하여 찾아서는 안 됩니다.**
- 접근 후 **개인정보/쿠키/동의 팝업**이 뜨면, 이를 반드시 **닫거나(Dismiss)** 처리하고 계속 진행합니다.
- (이미 0단계에서 블록 여부를 확인했으므로, 이 단계에서는 페이지가 정상 로드되었다고 가정합니다.)
2. **SSO 버튼 식별**
- 로그인 페이지에서 다음과 같은 소셜 로그인 버튼을 찾습니다:
- Google, GitHub, Facebook, Linkedin, Microsoft, Naver”
- ✅ **실제 SSO 버튼**임이 명확히 확인되는 경우에만 진행합니다.
- ❌ 제외 대상:
- “Passkey” 관련 버튼
- 아이디/비밀번호 입력란
- 이메일 기반 로그인
- 인증서, 휴대폰 인증 등 비-OAuth 로그인 옵션
3. **SSO 버튼 클릭 및 로그인 시도**
- 유효한 SSO 버튼이 발견되면, 버튼을 클릭합니다.
- 클릭 후 **첫 번째로 리디렉션된 URL(쿼리 스트링 포함)**을 `oauth_uri`로 기록합니다.
- 공급자 페이지가 열리면, 아래 자격증명을 이용해 로그인을 시도합니다, 아래 자격증명에 포함되지 않는 SSO 버튼도 클릭까지는 시도합니다.:
- Google → `{google_id}` / `{google_password}`
- Naver → `{naver_id}` / `{naver_password}`
- GitHub → `{github_id}` / `{github_password}`
- 자격증명이 주어진 SSO 버튼인 경우 로그인 과정을 꼭 진행합니다.
- 로그인 과정이 모두 끝나거나 로그인이 되지 않는 경우 세션 및 쿠키를 모두 삭제하고 페이지를 새로고침합니다.
- 아직 로그인을 시도하지 않은 SSO 버튼이 있다면 이전 단계인 1. **로그인 페이지 탐색**, 2. **SSO 버튼 식별**, 3. **SSO 버튼 클릭 및 로그인 시도** 로 돌아가 절차를 반복합니다.
- 최종 결과는 다음과 같이 기록합니다:
```json
[
{{
"provider": "Google",
"oauth_uri": "(optional) https://example.com/auth/google?client_id=...",
}},
{{
"provider": "Naver",
"oauth_uri": "(optional) https://example.com/auth/naver?client_id=...",
}}
]
```
4. **SSO 버튼 미발견 또는 오류 발생 시**
- 페이지 내부에 유효한 SSO 버튼이 전혀 없거나, 탐색 중 예기치 않은 오류가 발생하면 즉시 프로세스를 종료하고 **빈 배열**을 반환합니다:
```json
[]
```
5. **중요 사항**
- **반드시** 위의 단계들을 순서대로 수행해야 하며, 각 단계에서 발생하는 예외 상황을 정확히 처리해야 합니다.
- **반복 행동**이 감지되면 즉시 빈 배열을 반환하고, **블록된 페이지**는 초기 단계에서 처리하여 프로세스를 종료해야 합니다.
- **SSO 버튼이 발견되지 않거나, 오류가 발생한 경우에도 빈 배열을 반환해야 합니다.**
- **반드시** JSON 형식으로 결과를 반환해야 하며, 다른 형식은 허용되지 않습니다.
- 최대한 효율적인 단계로 진행하며, 불필요한 반복이나 검색 엔진 사용을 피해야 합니다.
"""

136
lib/llm/prompt/session.py Normal file
View file

@ -0,0 +1,136 @@
import os
from dotenv import load_dotenv
load_dotenv(override=True)
# Extended planner prompt
extend_planner_system_message = f"""
🎯 목적: 웹 자동화를 위한 **SSO 로그인 리디렉션 URL 수집**
📌 주의사항 (전제 조건)
- ❌ **검색 엔진(Google, Bing 등) 사용 금지**
- ✅ **초기 제공된 URL 내에서만 탐색**
- ❌ 직접 이동하거나 추측한 링크 클릭 금지
- ⛔ 추측한 URL은 대답하거나 클릭하지 마세요
---
## 🧩 Step 0: 페이지 차단(Block) 여부 확인
초기 URL의 로그인 페이지에 접근하여 다음 사항을 점검합니다:
- 🚫 페이지 차단됨 (Firewall, Access Denied 등) → 즉시 중단
- 🔒 CAPTCHA는 통과 가능 (해결하고 계속 진행)
- ❗ 로그인 UI가 정상적으로 로드되지 않으면 중단
📤 차단 시 즉시 반환:
```json
[
{{
"provider": "Blocked",
"oauth_uri": "-"
}}
]
````
---
## 🔍 Step 1: 로그인 페이지 탐색
* 초기 URL에 접속하여 **클라이언트용 로그인 페이지**로 진입합니다.
* 쿠키 동의, 개인정보 안내 등 팝업은 무시하거나 닫고 계속 진행하세요.
* 페이지가 정상 로드되었다고 가정합니다.
---
## 👀 Step 2: SSO 로그인 버튼 식별
아래 **OAuth SSO 버튼들만** 유효합니다:
* ✅ Google, GitHub, Facebook, LinkedIn, Microsoft, Naver
**유효한 버튼 기준**:
* OAuth 인증 흐름을 실제로 트리거
* `window.location` 또는 `<a href=...>` 또는 JS로 redirect가 발생
**제외 버튼들 (클릭 금지)**:
* ❌ 일반 로그인, 패스키, 이메일/전화번호, 인증서 기반, 비밀번호 입력
---
## ✅ Step 3: 모든 SSO 버튼 클릭 및 로그인 시도
> 각 SSO 로그인 버튼을 클릭한 뒤 반드시 아래 절차를 **완전히 수행**해야 합니다.
각 SSO 버튼에 대해 다음을 수행:
1. 버튼 클릭
2. 🌐 페이지가 이동되면, **현재 주소창(URL)을 확인하여 리디렉션된 OAuth URL**을 `oauth_uri`로 저장
→ 예: `https://accounts.google.com/o/oauth2/auth?...`
3. ✅ 로그인 진행:
- 세션 및 쿠키에 따라 이미 로그인된 상태로 간주하고 진행
- Google OAuth인 경우 URL에 `&login_hint={str(os.getenv('GOOGLE_ID'))}` 추가
- 버튼같은게 안눌리면 새로고침을 해봐
- **로그인 완료 후 authorize 등 버튼이 있으면 클릭**
- GitHub같은 경우 Authorize 버튼이 뜨는데 오래걸릴 수 있음, 기다려야 할 수도 있음
- 만약 버튼을 눌러도 반응이 없을 경우 새로고침을 한번 해주세요.
4. 로그인 성공 시 원래 페이지로 돌아오고, 해당 OAuth URL은 결과에 저장
5. 다음 SSO 버튼으로 반복 진행
🛑 절대 아래와 같이 해석하지 말 것:
- ❌ 버튼 클릭 후 페이지 로딩만 기다리고 돌아가기
- ❌ URL 저장 없이 go_back() 호출
📤 각 로그인 후 다음 형식으로 결과 저장:
```json
[
{{
"provider": "Google",
"oauth_uri": "https://example.com/auth/google?client_id=..."
}}
]
````
````
---
### ✨ 추가 안전 장치: "뒤로가기(go_back) 호출 조건" 제한
```text
🛑 뒤로가기(go_back)은 다음 조건이 모두 충족될 때만 사용:
- ✅ 로그인 흐름이 완료됨 (예: redirect back to app, or callback URL)
- ✅ 현재 리디렉션 URL이 수집됨
- ✅ 결과에 저장 후 다음 버튼 탐색을 위해 복귀 필요할 때
```
---
## 🚫 Step 4: 버튼 없음 또는 예외 발생 시
* 유효한 SSO 버튼이 **전혀 없을 경우**
* 예외, 오류 등 발생 시
📤 즉시 중단 후 다음 형식으로 반환:
```json
[]
```
---
## 📎 중요 규칙 요약
* ✅ **모든 SSO 로그인은 반드시 실행** (가능한 버튼은 모두 클릭)
* 🔁 단계는 반드시 순서대로 진행
* 🔐 로그인은 쿠키/세션으로 유지된 상태에서 수행
* 🚫 직접 ID/PW 입력하지 않음
* ⛔ 추측 URL 클릭 금지
* ❗ 예외 발생 시 반드시 규정된 JSON 포맷만 반환
---
"""

40
lib/utils/__init__.py Normal file
View file

@ -0,0 +1,40 @@
from lib.utils.config import (
BACKEND_URL,
GOOGLE_API_KEY,
GOOGLE_MODEL,
GOOGLE_PLANNER_MODEL,
)
def show_info():
print("🔧 환경 설정:")
print(browser_use_version())
print(f"🔗 Backend URL: {BACKEND_URL}")
print(
f"🔑 Google API Key: {'*' * (len(GOOGLE_API_KEY) - 4) + GOOGLE_API_KEY[-4:] if GOOGLE_API_KEY else None}"
)
print(f"🌐 Google Model: {GOOGLE_MODEL}")
print(f"🌐 Google Planner Model: {GOOGLE_PLANNER_MODEL}")
def browser_use_version():
try:
# run uv pip show browser-use
import subprocess
result = subprocess.run(
["uv", "pip", "show", "browser-use"],
capture_output=True,
text=True,
check=True,
)
print("📦 Browser Use 패키지 정보:")
return result.stdout.strip()
except ImportError:
return None
def env_cheker():
if GOOGLE_API_KEY is None:
raise ValueError("GOOGLE_API_KEY 환경변수가 설정되지 않았습니다.")

View file

@ -0,0 +1,21 @@
import requests
from config import BACKEND_URL
def notify_backend(target_url):
# Backend에 스캔 시작을 알림
try:
response = requests.post(
f"{BACKEND_URL}/start", params={"url": target_url}, timeout=5
)
if response.status_code == 200:
print(f"✅ Backend notified: {response.text}")
else:
print(f"⚠️ Backend notification failed: {response.status_code}")
except requests.exceptions.ConnectionError:
print(
f"⚠️ Backend server not available at {BACKEND_URL}. Continuing without notification."
)
except requests.exceptions.Timeout:
print(f"⚠️ Backend notification timed out. Continuing without notification.")
except Exception as e:
print(f"⚠️ Failed to notify backend: {e}")

View file

@ -0,0 +1,29 @@
from func import *
import clean_resources as clean_resources_func
# Initialize configuration
proxy_url = setup_proxy()
storage_state_path = setup_storage_state()
# Create browser profile
profile = BrowserProfile(
# Security settings
disable_security=True,
stealth=True,
# Display settings
headless=False,
device_scale_factor=1,
window_size={"width": 1600, "height": 900},
viewport={"width": 1600, "height": 900},
# Data persistence
user_data_dir=None,
storage_state=storage_state_path,
# Network settings
proxy={"server": proxy_url} if proxy_url else None,
# Additional arguments
args=get_browser_args(),
)

View file

@ -0,0 +1,25 @@
from pathlib import Path
async def clean_resources(agent=None, session=None):
"""리소스를 정리하는 함수"""
storage_state_temp_path = Path("./data/storage_state_temp.json").resolve()
if storage_state_temp_path.exists():
try:
# remove file
print(f"🗑️ 임시 스토리지 상태 파일 삭제 중: {storage_state_temp_path}")
# unlink removes the file
storage_state_temp_path.unlink()
print("🗑️ 임시 스토리지 상태 파일 삭제 완료.")
except Exception as e:
print(f"⚠️ 임시 스토리지 상태 파일 삭제 실패: {e}")
if agent:
try:
await agent.close()
except Exception as e:
print(f"⚠️ 에이전트 리소스 정리 실패: {e}")
if session:
try:
await session.close()
except Exception as e:
print(f"⚠️ 세션 리소스 정리 실패: {e}")

View file

@ -0,0 +1,69 @@
import os
from pathlib import Path
from dotenv import load_dotenv
from browser_use import BrowserProfile
# Load environment variables
load_dotenv(override=True)
def setup_proxy():
"""Configure proxy settings from environment variables."""
proxy_host = os.getenv("PROXY_HOST")
proxy_port = os.getenv("PROXY_PORT")
if proxy_host and proxy_port:
proxy_url = f"http://{proxy_host}:{proxy_port}"
print(f"🔗 Using proxy: {proxy_host}:{proxy_port}")
return proxy_url
else:
print("🔗 No proxy configured, using direct connection.")
return None
def setup_storage_state():
"""Setup browser storage state for session persistence."""
storage_state_path = Path("./data/storage_state.json").resolve()
storage_state_temp_path = Path("./data/storage_state_temp.json").resolve()
if storage_state_path.exists():
if storage_state_temp_path.exists():
storage_state_temp_path.unlink()
storage_state_temp_path.write_text(
storage_state_path.read_text(encoding="utf-8"), encoding="utf-8"
)
print(f"🔄 Using existing storage state: {storage_state_temp_path}")
return str(storage_state_temp_path)
return None
def get_browser_args():
"""Get browser arguments for enhanced compatibility and security."""
return [
# Security and isolation
"--disable-web-security",
"--disable-site-isolation-trials",
"--disable-features=IsolateOrigins,site-per-process",
"--ignore-certificate-errors",
"--ignore-ssl-errors",
"--allow-running-insecure-content",
# Performance and rendering
"--disable-features=VizDisplayCompositor",
"--disable-dev-shm-usage",
# Popup and automation
"--disable-popup-blocking",
"--disable-blink-features=AutomationControlled",
# Browser behavior
"--no-first-run",
"--no-service-autorun",
"--no-default-browser-check",
"--password-store=basic",
"--use-mock-keychain",
# Extensions
"--disable-extensions-file-access-check",
"--disable-extensions-http-throttling",
"--disable-component-extensions-with-background-pages",
# Language
f"--lang={os.getenv('LANG', 'en_US')}",
]

View file

@ -0,0 +1,11 @@
from typing import List
from pydantic import BaseModel
# 출력 모델
class OAuth(BaseModel):
provider: str
oauth_uri: str
class OAuthList(BaseModel):
oauth_providers: List[OAuth]

8
lib/utils/config.py Normal file
View file

@ -0,0 +1,8 @@
import os
from dotenv import load_dotenv
load_dotenv(verbose=True, override=True)
BACKEND_URL = os.getenv("BACKEND_URL", "http://localhost:11081")
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
GOOGLE_MODEL = os.getenv("GOOGLE_MODEL", "gemini-2.5-flash-preview-05-20")
GOOGLE_PLANNER_MODEL = os.getenv("GOOGLE_PLANNER_MODEL", "gemini-2.5-pro-preview-06-05")

36
lib/utils/is_html.py Normal file
View file

@ -0,0 +1,36 @@
import requests
def is_html_url(url: str, timeout: float = 10.0) -> bool:
"""
주어진 URL에 HEAD 요청을 보내고, 응답 헤더의 Content-Type이 HTML인지 확인합니다.
- url: 검사할 URL 문자열
- timeout: 요청 타임아웃(초 단위)
반환값:
- Content-Type이 'text/html' 로 시작하면 True, 그렇지 않으면 False
"""
try:
with requests.get(url, timeout=timeout, stream=True) as response:
# 응답 코드가 200번대가 아니면 False로 간주
if not response.ok:
return False
content_type = response.headers.get('Content-Type', '')
# Content-Type에 'text/html'이 포함되어 있으면 HTML로 간주
return content_type.lower().startswith('text/html')
except requests.RequestException:
return False
if __name__ == '__main__':
test_urls = [
'https://www.example.com',
'https://api.github.com', # JSON API라서 HTML이 아닐 확률이 높음
'https://raw.githubusercontent.com' # 텍스트 파일 등 다양한 타입
]
for url in test_urls:
if is_html_url(url):
print(f"[HTML] {url}")
else:
print(f"[Not HTML] {url}")

29
lib/utils/logger.py Normal file
View file

@ -0,0 +1,29 @@
from pathlib import Path
from datetime import datetime
# 미리 정해진 파일 경로
FILE_PATH = Path("data/log.txt")
def logger(msg: str) -> None:
try:
"""
msg 문자열을 파일 끝에 추가합니다.
- 파일이 없으면 새로 생성
- 디렉터리가 없으면 생성
"""
# 상위 디렉터리 생성 (이미 있으면 무시)
FILE_PATH.parent.mkdir(parents=True, exist_ok=True)
# 현재 시각 구해서 포맷팅
now = datetime.now()
timestamp = now.strftime("%Y-%m-%d %H:%M:%S")
# 메시지에 개행이 없으면 자동으로 붙이기
newline = "" if msg.endswith("\n") else "\n"
line = f"[{timestamp}] {msg}{newline}"
# 'a' 모드: 파일이 없으면 생성, 있으면 이어쓰기
with FILE_PATH.open(mode="a", encoding="utf-8") as f:
f.write(line)
except:
print(msg)

36
lib/utils/read_txt.py Normal file
View file

@ -0,0 +1,36 @@
def read_lines_between(filepath: str, start_line: int, end_line: int) -> list[str]:
"""
파일에서 start_line번 째 줄부터 end_line번 째 줄까지 읽어와
각 줄을 요소로 갖는 리스트를 반환하는 함수.
Parameters:
----------
filepath : str
읽을 텍스트 파일의 경로
start_line : int
읽기 시작할 행 번호 (1부터 시작)
end_line : int
읽을 마지막 행 번호 (start_line <= end_line)
Returns:
-------
list[str]
각 줄을 문자열로 저장한 리스트.
파일에 해당 범위의 줄이 없으면 가능한 만큼만 반환.
"""
if start_line < 1 or end_line < start_line:
raise ValueError("start_line은 1 이상이어야 하며, end_line은 start_line 이상이어야 합니다.")
selected_lines: list[str] = []
with open(filepath, 'r', encoding='utf-8') as f:
for idx, line in enumerate(f, start=1):
if idx < start_line:
# 아직 읽기 시작 전
continue
if idx > end_line:
# 읽을 범위를 벗어났으므로 중단
break
# 줄 끝의 개행 문자를 제거하고 리스트에 추가
selected_lines.append(line.rstrip('\n'))
return selected_lines

216
main.py
View file

@ -3,26 +3,27 @@ import json
import os import os
import csv import csv
import argparse import argparse
from pathlib import Path
from turtle import width
import requests
import time
from typing import List
from dotenv import load_dotenv from dotenv import load_dotenv
from pydantic import BaseModel
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.callbacks.base import BaseCallbackHandler
from browser_use import ( from browser_use import (
Agent, Agent,
BrowserSession, BrowserSession,
BrowserProfile,
Controller, Controller,
) )
from patchright.async_api import async_playwright as async_patchright from patchright.async_api import async_playwright as async_patchright
from lib.is_html import is_html_url
from lib.read_txt import read_lines_between from lib.utils import env_cheker
from lib.prompt import extend_planner_system_message from lib.utils.backend_client import notify_backend
from lib.logger import logger from lib.utils.browser_use import model
from lib.utils.browser_use.clean_resources import clean_resources
from lib.utils.config import BACKEND_URL, GOOGLE_MODEL, GOOGLE_PLANNER_MODEL
from lib.utils.is_html import is_html_url
from lib.utils.read_txt import read_lines_between
from lib.llm.prompt import extend_planner_system_message
from lib.utils.logger import logger
import lib.utils.browser_use as browser_use
from lib.llm import CreateChatGoogleGenerativeAI
load_dotenv(verbose=True, override=True) load_dotenv(verbose=True, override=True)
@ -30,100 +31,12 @@ load_dotenv(verbose=True, override=True)
INITIAL_BACKOFF = int(os.getenv("INITIAL_BACKOFF", "60")) # seconds INITIAL_BACKOFF = int(os.getenv("INITIAL_BACKOFF", "60")) # seconds
MAX_BACKOFF = int(os.getenv("MAX_BACKOFF", "600")) # seconds MAX_BACKOFF = int(os.getenv("MAX_BACKOFF", "600")) # seconds
if os.getenv("GOOGLE_API_KEY") is None: env_cheker()
raise ValueError("GOOGLE_API_KEY 환경변수가 설정되지 않았습니다.")
if os.getenv("GOOGLE_MODEL") is None:
raise ValueError("GOOGLE_MODEL 환경변수가 설정되지 않았습니다.")
if os.getenv("GOOGLE_PLANNER_MODEL") is None:
raise ValueError("GOOGLE_PLANNER_MODEL 환경변수가 설정되지 않았습니다.")
backend_url = os.getenv("BACKEND_URL", "http://localhost:11081")
if os.getenv("LMNR_PROJECT_API_KEY"): if os.getenv("LMNR_PROJECT_API_KEY"):
from lmnr import Laminar from lmnr import Laminar
Laminar.initialize(project_api_key=os.getenv("LMNR_PROJECT_API_KEY")) Laminar.initialize(project_api_key=os.getenv("LMNR_PROJECT_API_KEY"))
print("🔧 환경 설정:")
try:
# run uv pip show browser-use
import subprocess
result = subprocess.run(
["uv", "pip", "show", "browser-use"], capture_output=True, text=True, check=True
)
print("📦 Browser Use 패키지 정보:")
print(result.stdout.strip())
except ImportError:
browser_use_version = "unknown"
print(f"🔗 Backend URL: {backend_url}")
api_key = os.getenv("GOOGLE_API_KEY")
print(f"🔑 Google API Key: {api_key[-4:] if api_key else None}")
print(f"🌐 Google Model: {os.getenv('GOOGLE_MODEL')}")
print(f"🌐 Google Planner Model: {os.getenv('GOOGLE_PLANNER_MODEL')}")
# API 쿼터 처리를 위한 콜백 핸들러
class QuotaExhaustedHandler(BaseCallbackHandler):
def on_llm_error(self, error, **kwargs):
if "ResourceExhausted" in str(error) or "429" in str(error):
print("⚠️ API 쿼터가 소진되었습니다. 재시도 로직에 위임합니다...")
# backoff handled in scan_one_url
def CreateChatGoogleGenerativeAI(model: str):
"""재시도 로직이 포함된 LLM 생성"""
if model == "fallback":
print("⚠️ Fallback 모델을 사용합니다. Envorinment 변수를 확인하세요.")
print("⚠️ Model Gemini-2.0-flash-lite를 사용합니다.")
model = "gemini-2.0-flash-lite"
return ChatGoogleGenerativeAI(
model=model,
max_retries=10, # 최대 재시도 횟수 증가
model_kwargs={
"request_timeout": 120, # 타임아웃 시간 증가 (2분)
},
callbacks=[QuotaExhaustedHandler()],
# API 호출 간격 조정
temperature=0.1,
)
# 출력 모델
class OAuth(BaseModel):
provider: str
oauth_uri: str
class OAuthList(BaseModel):
oauth_providers: List[OAuth]
async def clean_resources(agent=None, session=None):
"""리소스를 정리하는 함수"""
storage_state_temp_path = Path("./data/storage_state_temp.json").resolve()
if storage_state_temp_path.exists():
try:
# remove file
print(f"🗑️ 임시 스토리지 상태 파일 삭제 중: {storage_state_temp_path}")
# unlink removes the file
storage_state_temp_path.unlink()
print("🗑️ 임시 스토리지 상태 파일 삭제 완료.")
except Exception as e:
print(f"⚠️ 임시 스토리지 상태 파일 삭제 실패: {e}")
if agent:
try:
await agent.close()
except Exception as e:
print(f"⚠️ 에이전트 리소스 정리 실패: {e}")
if session:
try:
await session.close()
except Exception as e:
print(f"⚠️ 세션 리소스 정리 실패: {e}")
# ── URL별로 Browser를 새로 띄우는 함수 ── # ── URL별로 Browser를 새로 띄우는 함수 ──
async def scan_one_url(url: str, skip_html_check: bool = False): async def scan_one_url(url: str, skip_html_check: bool = False):
@ -136,106 +49,21 @@ async def scan_one_url(url: str, skip_html_check: bool = False):
return return
# Backend에 스캔 시작을 알림 # Backend에 스캔 시작을 알림
try: notify_backend(target_url)
response = requests.post(
f"{backend_url}/start", params={"url": target_url}, timeout=5
)
if response.status_code == 200:
print(f"✅ Backend notified: {response.text}")
else:
print(f"⚠️ Backend notification failed: {response.status_code}")
except requests.exceptions.ConnectionError:
print(
f"⚠️ Backend server not available at {backend_url}. Continuing without notification."
)
except requests.exceptions.Timeout:
print(f"⚠️ Backend notification timed out. Continuing without notification.")
except Exception as e:
print(f"⚠️ Failed to notify backend: {e}")
agent = None agent = None
session = None session = None
try_cnt = 0 try_cnt = 0
while True: while True:
proxy_host = os.getenv("PROXY_HOST")
proxy_port = os.getenv("PROXY_PORT")
proxy_url = None
if proxy_host and proxy_port:
proxy_url = f"http://{proxy_host}:{proxy_port}"
print(f"🔗 Using proxy: {proxy_host}:{proxy_port}")
else:
print("🔗 No proxy configured, using direct connection.")
# user_data_dir 설정
# user_data_path = Path("./data/user_data").resolve()
# user_data_path.mkdir(parents=True, exist_ok=True)
storage_state_path = Path("./data/storage_state.json").resolve()
storage_state_temp_path = Path("./data/storage_state_temp.json").resolve()
# copy storage_state.json to storage_state_temp.json
if storage_state_path.exists():
if storage_state_temp_path.exists():
storage_state_temp_path.unlink()
storage_state_temp_path.write_text(
storage_state_path.read_text(encoding="utf-8"), encoding="utf-8"
)
print(f"🔄 Using existing storage state: {storage_state_temp_path}")
else:
storage_state_temp_path = None
# BrowserProfile에 모든 설정 포함
profile = BrowserProfile(
disable_security=True,
#deterministic_rendering=True,
stealth=True,
headless=False,
# user_data_dir=str(user_data_path),
user_data_dir=None,
storage_state=(
str(storage_state_temp_path)
if storage_state_temp_path and storage_state_temp_path.exists()
else None
),
device_scale_factor=1,
window_size={"width": 1600, "height": 900},
viewport={"width": 1600, "height": 900},
proxy={"server": proxy_url} if proxy_url else None,
# 추가 args
args=[
"--disable-web-security",
"--disable-features=VizDisplayCompositor",
"--disable-site-isolation-trials",
"--disable-features=IsolateOrigins,site-per-process",
"--disable-popup-blocking",
"--disable-dev-shm-usage",
f"--lang={os.getenv('LANG', 'en_US')}",
"--ignore-certificate-errors",
"--ignore-ssl-errors",
"--allow-running-insecure-content",
"--disable-web-security",
"--disable-features=VizDisplayCompositor",
"--disable-blink-features=AutomationControlled",
"--no-first-run",
"--no-service-autorun",
"--password-store=basic",
"--use-mock-keychain",
"--no-default-browser-check",
"--disable-extensions-file-access-check",
"--disable-extensions-http-throttling",
"--disable-component-extensions-with-background-pages",
],
)
# BrowserSession에 profile 전달 # BrowserSession에 profile 전달
session = BrowserSession( session = BrowserSession(
playwright=(await async_patchright().start()), playwright=(await async_patchright().start()),
browser_profile=profile, browser_profile=browser_use.profile,
) )
# Agent 생성 및 실행 (단일 try-except with 백오프) # Agent 생성 및 실행 (단일 try-except with 백오프)
initial_actions = [{"open_tab": {"url": target_url}}] initial_actions = [{"open_tab": {"url": target_url}}]
controller = Controller(output_model=OAuthList) controller = Controller(output_model=model.BaseModel)
print("🤖 LLM 모델 초기화 및 스캔 시작...") print("🤖 LLM 모델 초기화 및 스캔 시작...")
try: try:
agent = Agent( agent = Agent(
@ -250,10 +78,8 @@ async def scan_one_url(url: str, skip_html_check: bool = False):
"If the OAuth buttons do not appear immediately, wait briefly to allow the page to load completely before proceeding. " "If the OAuth buttons do not appear immediately, wait briefly to allow the page to load completely before proceeding. "
"Always log out before starting the login process, and make sure to attempt the login again from a clean state." "Always log out before starting the login process, and make sure to attempt the login again from a clean state."
), ),
llm=CreateChatGoogleGenerativeAI( llm=CreateChatGoogleGenerativeAI(GOOGLE_MODEL),
os.getenv("GOOGLE_MODEL") or "fallback" planner_llm=CreateChatGoogleGenerativeAI(GOOGLE_PLANNER_MODEL),
),
planner_llm=CreateChatGoogleGenerativeAI(os.getenv("GOOGLE_PLANNER_MODEL") or "fallback"),
controller=controller, controller=controller,
extend_planner_system_message=extend_planner_system_message(), extend_planner_system_message=extend_planner_system_message(),
) )
@ -287,7 +113,7 @@ async def scan_one_url(url: str, skip_html_check: bool = False):
# 스캔 결과 처리 # 스캔 결과 처리
data = json.loads(final_result) data = json.loads(final_result)
try: try:
oauth_entries = [OAuth(**entry) for entry in data["oauth_providers"]] oauth_entries = [model.OAuth(**entry) for entry in data["oauth_providers"]]
except Exception as e: except Exception as e:
raise ValueError(f"결과 파싱 실패: {e}\n원본 결과: {final_result}") raise ValueError(f"결과 파싱 실패: {e}\n원본 결과: {final_result}")