mirror of
https://github.com/j93es/browser-use-oauth.git
synced 2026-06-04 06:01:51 +09:00
[Update] new logic
This commit is contained in:
parent
95d56259e7
commit
92967ed353
38 changed files with 1516 additions and 5209 deletions
|
|
@ -1,40 +0,0 @@
|
|||
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 환경변수가 설정되지 않았습니다.")
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
from lib.utils.browser_use.func import *
|
||||
|
||||
# Initialize configuration
|
||||
proxy_url = setup_proxy()
|
||||
|
||||
# Create browser profile
|
||||
async def GetProfile():
|
||||
storage_state_path = await setup_storage_state()
|
||||
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(),
|
||||
)
|
||||
|
||||
return profile
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
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}")
|
||||
|
|
@ -1,75 +0,0 @@
|
|||
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
|
||||
|
||||
|
||||
async def setup_storage_state():
|
||||
"""Setup browser storage state for session persistence."""
|
||||
# Get the script directory to ensure correct path resolution
|
||||
script_dir = Path(__file__).parent.parent.parent.parent
|
||||
storage_state_path = script_dir / "data" / "storage_state.json"
|
||||
storage_state_temp_path = script_dir / "data" / "storage_state_temp.json"
|
||||
|
||||
print(f"📂 Storage state path: {storage_state_path}")
|
||||
print(f"📂 Temp storage state path: {storage_state_temp_path}")
|
||||
|
||||
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)
|
||||
|
||||
print("⚠️ No existing storage state found")
|
||||
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')}",
|
||||
]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
from typing import List
|
||||
from pydantic import BaseModel
|
||||
|
||||
# 출력 모델
|
||||
class OAuth(BaseModel):
|
||||
provider: str
|
||||
oauth_uri: str
|
||||
|
||||
|
||||
class OAuthList(BaseModel):
|
||||
oauth_providers: List[OAuth]
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
# read json file .sensitive.json
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
def GetSensitiveData():
|
||||
"""
|
||||
Reads sensitive data from a .sensitive.json file in the current directory.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary containing the sensitive data.
|
||||
"""
|
||||
file_path = os.path.join(os.getcwd(), '.sensitive.json')
|
||||
|
||||
if not os.path.exists(file_path):
|
||||
return None
|
||||
|
||||
with open(file_path, 'r') as file:
|
||||
sensitive_data = json.load(file)
|
||||
|
||||
return sensitive_data
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
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")
|
||||
16
lib/utils/env_checker.py
Normal file
16
lib/utils/env_checker.py
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
def check_env_variables():
|
||||
"""환경변수 체크 함수"""
|
||||
required_vars = [
|
||||
"BACKEND_URL",
|
||||
"GOOGLE_API_KEY",
|
||||
"GOOGLE_MODEL",
|
||||
"GOOGLE_PLANNER_MODEL"
|
||||
]
|
||||
|
||||
for var in required_vars:
|
||||
if os.getenv(var) is None:
|
||||
raise ValueError(f"{var} 환경변수가 설정되지 않았습니다.")
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import requests
|
||||
|
||||
from lib.utils.config import BACKEND_URL
|
||||
from lib.config import BACKEND_URL
|
||||
|
||||
def notify_backend(target_url):
|
||||
# Backend에 스캔 시작을 알림
|
||||
22
lib/utils/progress_checker.py
Normal file
22
lib/utils/progress_checker.py
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
progress_file = Path("data/scan_progress.json")
|
||||
|
||||
|
||||
def save_progress(current_progress):
|
||||
"""현재 진행 상황을 파일에 저장"""
|
||||
with open(progress_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(current_progress, f, ensure_ascii=False, indent=2)
|
||||
|
||||
|
||||
def load_progress():
|
||||
"""이전 진행 상황을 파일에서 불러오기"""
|
||||
if os.path.exists(progress_file):
|
||||
try:
|
||||
with open(progress_file, 'r', encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
except:
|
||||
return None
|
||||
return None
|
||||
90
lib/utils/prompt.py
Normal file
90
lib/utils/prompt.py
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
from dotenv import load_dotenv
|
||||
import os
|
||||
|
||||
load_dotenv()
|
||||
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}`
|
||||
- facebook → `{facebook_id}` / `{facebook_password}`
|
||||
- **자격증명이 주어진 SSO 버튼인 경우 로그인 과정을 꼭 진행합니다.**
|
||||
- 로그인 과정이 모두 끝나거나 로그인이 되지 않는 경우 세션 및 쿠키를 모두 삭제하고 페이지를 새로고침합니다.
|
||||
- 한번이라도 SSO 버튼을 클릭한 경우, 해당 버튼은 더 이상 탐색하지 않습니다.
|
||||
- id/pw 입력 성공 시, 아직 로그인되지 않았다면, 최대 5초간 대기합니다.
|
||||
- 아직 로그인을 시도하지 않은 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 형식으로 결과를 반환해야 하며, 다른 형식은 허용되지 않습니다.
|
||||
- 최대한 효율적인 단계로 진행하며, 불필요한 반복이나 검색 엔진 사용을 피해야 합니다.
|
||||
"""
|
||||
Loading…
Add table
Add a link
Reference in a new issue