[Update] new logic

This commit is contained in:
tv0924@icloud.com 2025-06-22 20:35:56 +09:00
commit 92967ed353
38 changed files with 1516 additions and 5209 deletions

View file

@ -0,0 +1,51 @@
import json
from pydantic import BaseModel
from browser_use import (
Agent,
Controller,
)
from lib.agents.run_agent import run_agent
from lib.utils.logger import logger
from lib.browser_use_utils.clean_resources import clean_agent_resources
from lib.browser_use_utils.create_google_ai import create_google_ai
from lib.config import GOOGLE_MODEL, GOOGLE_PLANNER_MODEL
NOT_FOUND_LOGIN_PAGE = 0
FOUND_LOGIN_PAGE = 1
class IsFound(BaseModel):
status: int
async def find_login_page(target_url, session):
initial_actions = [{"open_tab": {"url": target_url}}]
task = "Navigate to the login page, and stop"
extend_planner_system_message = "You are an expert in finding login pages. Your task is to navigate to the login page of the given URL and stop there."
controller = Controller(output_model=IsFound, exclude_actions=['search_google'])
agent = Agent(
browser_session=session,
initial_actions=initial_actions,
task=task,
llm=create_google_ai(GOOGLE_MODEL),
planner_llm=create_google_ai(GOOGLE_PLANNER_MODEL),
controller=controller,
extend_planner_system_message=extend_planner_system_message,
)
status, final_result = await run_agent(agent)
if status:
logger(f"⚠️ 스캔 실패: {target_url} | {final_result}")
print(f"⚠️ 스캔 실패: {target_url} | {final_result}")
return False, None;
data = json.loads(final_result)
try:
is_found = IsFound(**data)
if is_found.status == NOT_FOUND_LOGIN_PAGE:
return False, "로그인 페이지를 찾을 수 없습니다."
else:
return True, "로그인 페이지를 찾았습니다."
except Exception as e:
logger(f"⚠️ 결과 파싱 실패: {target_url} | {e}\n원본 결과: {final_result}")
print(f"⚠️ 결과 파싱 실패: {target_url} | {e}\n원본 결과: {final_result}")
return False, "결과 파싱 실패"

20
lib/agents/run_agent.py Normal file
View file

@ -0,0 +1,20 @@
from lib.browser_use_utils.clean_resources import clean_agent_resources
async def run_agent(agent):
try:
response = await agent.run()
final_result = response.final_result()
if final_result is None:
return -1, "최종 결과가 없습니다. 에이전트 실행 실패"
return 0, final_result
except Exception as e:
# API 쿼터 문제인지 확인
if "ResourceExhausted" in str(e) or "429" in str(e):
return 1, "API 쿼터 에러로 인한 실패"
# 일반 에러 처리
else:
return 2, "일반 에러로 인한 실패"
finally:
await clean_agent_resources(agent)
print("리소스 정리 완료")

View file

@ -0,0 +1,21 @@
async def clean_agent_resources(agent=None):
"""에이전트 리소스를 정리하는 함수"""
if agent:
try:
await agent.close()
except Exception as e:
print(f"⚠️ 에이전트 리소스 정리 실패: {e}")
async def clean_session_resources(session=None):
"""브라우저 리소스를 정리하는 함수"""
if session:
try:
await session.close()
except Exception as e:
print(f"⚠️ 브라우저 리소스 정리 실패: {e}")
async def clean_resources(agent=None, session=None):
"""리소스를 정리하는 함수"""
await clean_agent_resources(agent)
await clean_session_resources(session)

View file

@ -7,7 +7,7 @@ class QuotaExhaustedHandler(BaseCallbackHandler):
print("⚠️ API 쿼터가 소진되었습니다. 재시도 로직에 위임합니다...")
# backoff handled in scan_one_url
def CreateChatGoogleGenerativeAI(model: str):
def create_google_ai(model: str):
"""재시도 로직이 포함된 LLM 생성"""
if model == "fallback":
print("⚠️ Fallback 모델을 사용합니다. Envorinment 변수를 확인하세요.")

View file

@ -1,32 +1,13 @@
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():
async def get_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"
storage_state_path = Path("data/storage_state.json")
storage_state_temp_path = Path("data/storage_state_temp.json")
print(f"📂 Storage state path: {storage_state_path}")
print(f"📂 Temp storage state path: {storage_state_temp_path}")
@ -44,6 +25,20 @@ async def setup_storage_state():
return None
def get_proxy_url():
"""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 get_browser_args():
"""Get browser arguments for enhanced compatibility and security."""
return [
@ -73,3 +68,30 @@ def get_browser_args():
# Language
f"--lang={os.getenv('LANG', 'en_US')}",
]
async def get_profile():
proxy_url = get_proxy_url()
storage_state_path = await get_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

53
lib/find_sso_list.py Normal file
View file

@ -0,0 +1,53 @@
import asyncio
from browser_use import Agent, BrowserSession
from patchright.async_api import async_playwright as async_patchright
from lib.agents.find_login_page import find_login_page
from lib.browser_use_utils.clean_resources import clean_session_resources
from lib.browser_use_utils.get_profile import get_profile
async def find_sso_list(target_url):
session = BrowserSession(
playwright=(await async_patchright().start()),
browser_profile=await get_profile(),
)
FIND_LOGIN_PAGE = 1
FIND_SSO_LIST = 2
SAVE_DATA = 3
WHEN_ERROR = -1
FINISH = 0
final_result = None
task_queue = []
# find SSO
state = FIND_LOGIN_PAGE
while True:
if state == FIND_LOGIN_PAGE:
status, response = await find_login_page(
target_url=target_url,
session=session,
)
if not status:
print(f"⚠️ 로그인 페이지 탐지 실패: {target_url} | {response}")
state = WHEN_ERROR
state = FIND_SSO_LIST
if state == FIND_SSO_LIST:
print(f"🔎 SSO 목록 찾는 중: {target_url}")
await asyncio.sleep(10) # 잠시 대기 후 다음 단계로 넘어감
break
if state == SAVE_DATA:
print(f"💾 데이터 저장 중: {target_url}")
break
if state == WHEN_ERROR:
print(f"⚠️ 에러 발생: {target_url} | 스캔을 중단합니다.")
return
if state == FINISH:
print(f"✅ 스캔 완료: {target_url}")
break
await clean_session_resources(session)

View file

@ -1,142 +0,0 @@
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은 대답하거나 클릭하지 마세요
- OAuth가 아닌 일반 로그인은 무시
- OAuth가 없다면 **즉시 중단**하고 배열 반환
---
## 🧩 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. 로그인 진행:
- 로그인 페이지에서 OAuth 인증을 완료합니다.
- sign in with your username(email) x_username and password is x_password
- 버튼같은게 안눌리면 새로고침을 해봐
- **로그인 완료 authorize 버튼이 있으면 클릭**
- GitHub같은 경우 Authorize 버튼이 뜨는데 오래걸릴 있음, 기다려야 수도 있음
- 만약 버튼을 눌러도 반응이 없을 경우 새로고침을 한번 해주세요.
- 로그인 실패 시에는 다음 SSO 버튼을 클릭합니다.
4. 로그인이 성공하면 모두 쿠키를 삭제하고 다음 SSO 버튼을 클릭합니다.
5. 다음 SSO 버튼으로 반복 진행
쿠키 삭제 방법:
chrome://settings/clearBrowserData에 들어가서 삭제해주세요.
🛑 절대 아래와 같이 해석하지 :
- 버튼 클릭 페이지 로딩만 기다리고 돌아가기
- 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 포맷만 반환
---
"""

View file

@ -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 환경변수가 설정되지 않았습니다.")

View file

@ -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

View file

@ -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}")

View file

@ -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]

View file

@ -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

16
lib/utils/env_checker.py Normal file
View 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} 환경변수가 설정되지 않았습니다.")

View file

@ -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에 스캔 시작을 알림

View 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
View 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 형식으로 결과를 반환해야 하며, 다른 형식은 허용되지 않습니다.
- 최대한 효율적인 단계로 진행하며, 불필요한 반복이나 검색 엔진 사용을 피해야 합니다.
"""