Spaces:
Paused
Paused
fix: harden auth sync and direct signup flow
Browse filesFiles changed (5)
394 unmodified lines3953963973983994004 unmodified lines405406407408409410146 unmodified lines557558559560561562148 unmodified lines711712713714715716767 unmodified lines148414851486148714881489394 unmodified linesdef _finish_admin_login(completed: dict):global _admin_login_api, _admin_login_stepapi = _admin_login_apitry:info = _pw_executor.run(api.complete_admin_login)finally:4 unmodified linespass_admin_login_api = None_admin_login_step = Noneif _playwright_lock.locked():_playwright_lock.release()return {"status": "completed", "admin": _admin_status(), "info": info}146 unmodified linesapi.stop()info = _pw_executor.run(_do_import, params.email.strip(), params.session_token.strip())_admin_login_api = None_admin_login_step = Nonereturn {"status": "completed", "admin": _admin_status(), "info": info}148 unmodified linesif _playwright_lock.locked():_playwright_lock.release()if not _playwright_lock.acquire(blocking=False):raise HTTPException(status_code=409, detail=_current_busy_detail("有任务正在执行,请等待完成后再同步主号 Codex")767 unmodified lines@app.on_event("startup")def _start_auto_check():thread = threading.Thread(target=_auto_check_loop, daemon=True)thread.start()394 unmodified lines3953963973983994004014 unmodified lines406407408409410411412413414415416417418419420421422146 unmodified lines569570571572573574575576577578579580581582583584585148 unmodified lines734735736737738739740741742743744745746747748749750751752767 unmodified lines152015211522152315241525152615271528152915301531153215331534394 unmodified linesdef _finish_admin_login(completed: dict):global _admin_login_api, _admin_login_stepapi = _admin_login_apiinfo = Nonetry:info = _pw_executor.run(api.complete_admin_login)finally:4 unmodified linespass_admin_login_api = None_admin_login_step = Noneif info and info.get("session_token") and info.get("account_id"):try:from autoteam.codex_auth import refresh_main_auth_filemain_auth = _pw_executor.run(refresh_main_auth_file)if main_auth:info["main_auth"] = main_authlogger.info("[API] 管理员登录后已刷新主号认证文件: %s", main_auth.get("auth_file"))except Exception as exc:info["main_auth_error"] = str(exc)logger.warning("[API] 管理员登录完成,但刷新主号认证文件失败: %s", exc)if _playwright_lock.locked():_playwright_lock.release()return {"status": "completed", "admin": _admin_status(), "info": info}146 unmodified linesapi.stop()info = _pw_executor.run(_do_import, params.email.strip(), params.session_token.strip())if info.get("session_token") and info.get("account_id"):try:from autoteam.codex_auth import refresh_main_auth_filemain_auth = _pw_executor.run(refresh_main_auth_file)if main_auth:info["main_auth"] = main_authlogger.info("[API] session_token 导入后已刷新主号认证文件: %s", main_auth.get("auth_file"))except Exception as exc:info["main_auth_error"] = str(exc)logger.warning("[API] session_token 导入完成,但刷新主号认证文件失败: %s", exc)_admin_login_api = None_admin_login_step = Nonereturn {"status": "completed", "admin": _admin_status(), "info": info}148 unmodified linesif _playwright_lock.locked():_playwright_lock.release()from autoteam.codex_auth import get_saved_main_auth_filefrom autoteam.cpa_sync import sync_main_codex_to_cpasaved_auth_file = get_saved_main_auth_file()if saved_auth_file:sync_main_codex_to_cpa(saved_auth_file)return {"status": "completed","message": "主号 Codex 已同步到 CPA","codex": _main_codex_status(),"info": {"auth_file": saved_auth_file},}if not _playwright_lock.acquire(blocking=False):raise HTTPException(status_code=409, detail=_current_busy_detail("有任务正在执行,请等待完成后再同步主号 Codex")767 unmodified lines@app.on_event("startup")def _start_auto_check():try:from autoteam.auth_storage import ensure_auth_file_permissionsfixed = ensure_auth_file_permissions()if fixed:logger.info("[启动] 已修复 %d 个 auths 认证文件权限", fixed)except Exception as exc:logger.warning("[启动] 修复 auths 认证文件权限失败: %s", exc)thread = threading.Thread(target=_auto_check_loop, daemon=True)thread.start()
1234567891011121314151617181920212223242526272829303132333435"""认证文件目录与权限辅助。"""
from pathlib import Path
PROJECT_ROOT = Path(__file__).parent.parent.parentAUTH_DIR = PROJECT_ROOT / "auths"
# Docker bind mount 下文件常由容器用户写入;给宿主机用户保留可读写权限。AUTH_FILE_MODE = 0o666
def ensure_auth_dir() -> Path: AUTH_DIR.mkdir(exist_ok=True) return AUTH_DIR
def ensure_auth_file_permissions(filepath: str | Path | None = None) -> int: """统一修复 auths 目录下认证文件权限。""" ensure_auth_dir()
if filepath is None: candidates = list(AUTH_DIR.glob("codex-*.json")) else: candidates = [Path(filepath)]
updated = 0 for path in candidates: if not path.exists() or not path.is_file(): continue try: path.chmod(AUTH_FILE_MODE) updated += 1 except Exception: continue return updated3 unmodified lines4567891011 unmodified lines22232425262728293031323386 unmodified lines1201211221231241258 unmodified lines1341351361371381391401261 unmodified lines140214031404140514061407140822 unmodified lines1431143214331434143514363 unmodified linesimport hashlibimport jsonimport loggingimport osimport reimport secretsimport time11 unmodified linesget_chatgpt_workspace_name,update_admin_state,)from autoteam.textio import write_textlogger = logging.getLogger(__name__)PROJECT_ROOT = Path(__file__).parent.parent.parentAUTH_DIR = PROJECT_ROOT / "auths"SCREENSHOT_DIR = PROJECT_ROOT / "screenshots"# Codex OAuth 配置86 unmodified linesdef _write_auth_file(filepath, bundle):filepath = Path(filepath)filepath.parent.mkdir(exist_ok=True)auth_data = {8 unmodified lines}write_text(filepath, json.dumps(auth_data, indent=2))os.chmod(filepath, 0o600)logger.info("[Codex] 认证文件已保存: %s", filepath)return str(filepath)1261 unmodified linesdef save_auth_file(bundle):"""保存 CPA 兼容的认证文件。同一邮箱只保留一个文件,优先 team。"""AUTH_DIR.mkdir(exist_ok=True)email = bundle["email"]plan_type = bundle.get("plan_type", "unknown")22 unmodified linesreturn _write_auth_file(filepath, bundle)def check_codex_quota(access_token, account_id=None):"""通过 /backend-api/wham/usage 查询 Codex 额度状态,不消耗额度。3 unmodified lines45678911 unmodified lines21222324252627282930313286 unmodified lines1191201211221231241258 unmodified lines1341351361371381391401261 unmodified lines140214031404140514061407140822 unmodified lines1431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814693 unmodified linesimport hashlibimport jsonimport loggingimport reimport secretsimport time11 unmodified linesget_chatgpt_workspace_name,update_admin_state,)from autoteam.auth_storage import AUTH_DIR, ensure_auth_dir, ensure_auth_file_permissionsfrom autoteam.textio import write_textlogger = logging.getLogger(__name__)PROJECT_ROOT = Path(__file__).parent.parent.parentSCREENSHOT_DIR = PROJECT_ROOT / "screenshots"# Codex OAuth 配置86 unmodified linesdef _write_auth_file(filepath, bundle):filepath = Path(filepath)ensure_auth_dir()filepath.parent.mkdir(exist_ok=True)auth_data = {8 unmodified lines}write_text(filepath, json.dumps(auth_data, indent=2))ensure_auth_file_permissions(filepath)logger.info("[Codex] 认证文件已保存: %s", filepath)return str(filepath)1261 unmodified linesdef save_auth_file(bundle):"""保存 CPA 兼容的认证文件。同一邮箱只保留一个文件,优先 team。"""ensure_auth_dir()email = bundle["email"]plan_type = bundle.get("plan_type", "unknown")22 unmodified linesreturn _write_auth_file(filepath, bundle)def get_saved_main_auth_file():"""获取本地已保存的主号 Codex 认证文件路径。"""candidates = []for path in AUTH_DIR.glob("codex-main-*.json"):if not path.is_file():continuetry:stat = path.stat()except Exception:continuecandidates.append((stat.st_mtime, path.name, path))if not candidates:return ""candidates.sort(reverse=True)return str(candidates[0][2].resolve())def refresh_main_auth_file():"""基于已保存的管理员登录态,刷新并保存主号 Codex 认证文件。"""bundle = login_codex_via_session()if not bundle:raise RuntimeError("无法基于管理员登录态生成主号 Codex 认证文件")auth_file = save_main_auth_file(bundle)return {"email": bundle.get("email"),"auth_file": auth_file,"plan_type": bundle.get("plan_type"),}def check_codex_quota(access_token, account_id=None):"""通过 /backend-api/wham/usage 查询 Codex 额度状态,不消耗额度。
9 unmodified lines1011121314151617181920212223157 unmodified lines1811821831841851865 unmodified lines1921931941951961971981992002019 unmodified linesimport requestsfrom autoteam.config import CPA_KEY, CPA_URLfrom autoteam.textio import write_textlogger = logging.getLogger(__name__)PROJECT_ROOT = Path(__file__).parent.parent.parentAUTH_DIR = PROJECT_ROOT / "auths"def _headers():return {"Authorization": f"Bearer {CPA_KEY}"}157 unmodified linesdef _write_auth_file(filepath, bundle):auth_data = {"type": "codex","id_token": bundle.get("id_token", ""),5 unmodified lines"last_refresh": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(bundle.get("last_refresh_ts", time.time()))),}write_text(filepath, json.dumps(auth_data, indent=2))try:filepath.chmod(0o600)except Exception:passreturn filepath9 unmodified lines101112131415161718192021157 unmodified lines1791801811821831841855 unmodified lines1911921931941951961979 unmodified linesimport requestsfrom autoteam.auth_storage import AUTH_DIR, ensure_auth_dir, ensure_auth_file_permissionsfrom autoteam.config import CPA_KEY, CPA_URLfrom autoteam.textio import write_textlogger = logging.getLogger(__name__)def _headers():return {"Authorization": f"Bearer {CPA_KEY}"}157 unmodified linesdef _write_auth_file(filepath, bundle):ensure_auth_dir()auth_data = {"type": "codex","id_token": bundle.get("id_token", ""),5 unmodified lines"last_refresh": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(bundle.get("last_refresh_ts", time.time()))),}write_text(filepath, json.dumps(auth_data, indent=2))ensure_auth_file_permissions(filepath)return filepath
47 unmodified lines4849505152535455565758682 unmodified lines7417427437447457467477487497507517527537547557567577587594 unmodified lines76476576676776876977077177277377415 unmodified lines79079179279379479589 unmodified lines8858868878888898908918928938948958968978988999009019029036 unmodified lines91091191291391491529 unmodified lines9459469479489499509519529539549559569579589599609614 unmodified lines96696796896997097150 unmodified lines10221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059545 unmodified lines16051606160716081609161014 unmodified lines16251626162716281629163073 unmodified lines17041705170617071708170911 unmodified lines172117221723172417251726157 unmodified lines1884188518861887188818891890116 unmodified lines20072008200920102011201247 unmodified lines_click_primary_auth_button,_is_google_redirect,check_codex_quota,login_codex_via_browser,refresh_access_token,save_auth_file,)from autoteam.cpa_sync import sync_from_cpa, sync_to_cpafrom autoteam.textio import read_text, write_textlogger = logging.getLogger(__name__)682 unmodified linesreturn ""def _detect_direct_register_step(page):url = (page.url or "").lower()if _is_google_redirect(page):return "google"try:if page.locator(_DIRECT_PASSWORD_SELECTORS).first.is_visible(timeout=300):return "password"except Exception:passtry:if page.locator(_DIRECT_CODE_SELECTORS).first.is_visible(timeout=300):return "code"except Exception:pass4 unmodified linesexcept Exception:passif "chatgpt.com" in url and "auth" not in url:return "completed"try:if page.locator(_DIRECT_EMAIL_SELECTORS).first.is_visible(timeout=300):return "email"except Exception:pass15 unmodified linesreturn _detect_direct_register_step(page)def _register_direct_once(mail_client, email, password):"""执行一次直接注册,返回是否完成注册并进入 Team。"""from playwright.sync_api import sync_playwright89 unmodified linesif step != "email":breakemail_input = page.locator(_DIRECT_EMAIL_SELECTORS).firstemail_input.wait_for(state="visible", timeout=5000)email_input.fill(email)time.sleep(0.5)logger.info("[直接注册] 邮箱已填入,点击 Continue... (attempt %d)", attempt + 1)_safe_invite_screenshot(page, f"direct_02b_email_filled_{attempt}.png")_click_primary_auth_button(page, email_input, ["Continue", "继续"])next_step = _wait_for_direct_register_step(page,{"email", "password", "code", "profile", "completed", "google"},timeout=15,)logger.info("[直接注册] 点击 Continue 后状态: %s | URL: %s", next_step, page.url)_safe_invite_screenshot(page, f"direct_02c_after_continue_{attempt}.png")6 unmodified linesif next_step != "email":breaklogger.warning("[直接注册] 点击 Continue 后仍停留在邮箱步骤,准备重试... | URL: %s | body=%s",page.url,29 unmodified lineslogger.info("[直接注册] 未检测到密码输入框,跳过")breakpwd_input = page.locator(_DIRECT_PASSWORD_SELECTORS).firstpwd_input.wait_for(state="visible", timeout=10000)logger.info("[直接注册] 设置密码")pwd_input.fill(password)time.sleep(0.5)_click_primary_auth_button(page, pwd_input, ["Continue", "继续", "Log in"])next_step = _wait_for_direct_register_step(page,{"password", "code", "profile", "completed", "google", "email"},timeout=15,)logger.info("[直接注册] 提交密码后状态: %s | URL: %s", next_step, page.url)if next_step == "google":4 unmodified linescontinueif next_step != "password":breakexcept Exception as exc:logger.warning("[直接注册] 密码步骤异常: %s | URL: %s", exc, page.url)50 unmodified lines_safe_invite_screenshot(page, "direct_05_after_code.png")logger.info("[直接注册] 当前 URL: %s", page.url)name_input = page.locator('input[name="name"]').firsttry:if name_input.is_visible(timeout=5000):name_input.fill("User")time.sleep(0.5)spinbuttons = page.locator('[role="spinbutton"]').all()if len(spinbuttons) >= 3:try:page.locator("text=生日日期").click()time.sleep(0.5)except Exception:passfor sb, val in zip(spinbuttons[:3], ["1995", "06", "15"]):sb.click(force=True)time.sleep(0.2)page.keyboard.type(val, delay=80)time.sleep(0.3)logger.info("[直接注册] 填入生日: 1995/06/15")else:age_input = page.locator('input[name="age"]').firsttry:if age_input.is_visible(timeout=3000):age_input.fill("25")logger.info("[直接注册] 填入年龄: 25")except Exception:pass_click_primary_auth_button(page, name_input, ["完成帐户创建", "Continue", "继续"])time.sleep(8)except Exception:pass_safe_invite_screenshot(page, "direct_06_after_profile.png")logger.info("[直接注册] 当前 URL: %s", page.url)545 unmodified linesflow.stop()def cmd_admin_login(email=None):"""交互式完成管理员登录并保存到 state.json。"""email = (email or "").strip()14 unmodified lineswhile True:if step == "completed":info = chatgpt.complete_admin_login()logger.info("[管理员登录] 登录完成: %s", info.get("email") or email)if info.get("account_id"):logger.info("[管理员登录] Workspace ID: %s", info["account_id"])73 unmodified linestry:logger.info("[管理员登录] 开始导入 session_token: %s", email)info = chatgpt.import_admin_session(email, session_token)logger.info("[管理员登录] session_token 导入完成: %s", info.get("email") or email)if info.get("account_id"):logger.info("[管理员登录] Workspace ID: %s", info["account_id"])11 unmodified lineslogger.error("[主号 Codex] 缺少管理员登录态,请先执行 admin-login")return Noneflow = MainCodexSyncFlow()try:logger.info("[主号 Codex] 开始同步: %s", state.get("email"))157 unmodified lines# 确定要移除的数量if max_seats is None:max_seats = len(external_members) + 2 # 保留外部成员 + 2 个本地席位to_remove_count = total - max_seatsif to_remove_count <= 0:logger.info("[清理] 成员数 %d 未超过上限 %d,无需清理", total, max_seats)116 unmodified linescheck_and_setup(interactive=True)if args.command == "status":cmd_status()elif args.command == "check":47 unmodified lines48495051525354555657585960682 unmodified lines7437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978984 unmodified lines90390490590690790890991015 unmodified lines9269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104689 unmodified lines11361137113811391140114111421143114411451146114711481149115011511152115311541155115611576 unmodified lines1164116511661167116811691170117111721173117411751176117729 unmodified lines120712081209121012111212121312141215121612171218121912201221122212231224122512264 unmodified lines1231123212331234123512361237123812391240124112421243124450 unmodified lines1295129612971298129913001301130213031304545 unmodified lines185018511852185318541855185618571858185918601861186218631864186514 unmodified lines1880188118821883188418851886188773 unmodified lines1961196219631964196519661967196811 unmodified lines198019811982198319841985198619871988198919901991157 unmodified lines21492150215121522153215421552156116 unmodified lines227322742275227622772278227922802281228222832284228547 unmodified lines_click_primary_auth_button,_is_google_redirect,check_codex_quota,get_saved_main_auth_file,login_codex_via_browser,refresh_access_token,refresh_main_auth_file,save_auth_file,)from autoteam.cpa_sync import sync_from_cpa, sync_main_codex_to_cpa, sync_to_cpafrom autoteam.textio import read_text, write_textlogger = logging.getLogger(__name__)682 unmodified linesreturn ""def _first_visible_editable_locator(page, selectors, timeout=800):try:locator = page.locator(selectors).firstif not locator.is_visible(timeout=timeout):return Noneif locator.is_editable(timeout=timeout):return locatorexcept Exception:return Nonereturn Nonedef _collect_date_spinbutton_meta(page):try:return page.evaluate("""() => {const byIdsText = (rawIds) => {return (rawIds || '').split(/\\s+/).filter(Boolean).map(id => {const el = document.getElementById(id);return el ? (el.textContent || '').trim() : '';}).filter(Boolean).join(' ');};return Array.from(document.querySelectorAll('[role="spinbutton"]')).map((el, index) => ({index,text: (el.textContent || '').trim(),ariaLabel: el.getAttribute('aria-label') || '',ariaValueText: el.getAttribute('aria-valuetext') || '',ariaValueMin: el.getAttribute('aria-valuemin') || '',ariaValueMax: el.getAttribute('aria-valuemax') || '',placeholder: el.getAttribute('placeholder') || '',dataType: el.getAttribute('data-type') || el.dataset?.type || '',labelledText: byIdsText(el.getAttribute('aria-labelledby')),describedText: byIdsText(el.getAttribute('aria-describedby')),}));}""")except Exception:return []def _infer_date_spinbutton_kind(meta):text_parts = [meta.get("text", ""),meta.get("ariaLabel", ""),meta.get("ariaValueText", ""),meta.get("placeholder", ""),meta.get("dataType", ""),meta.get("labelledText", ""),meta.get("describedText", ""),]lowered = " ".join(part for part in text_parts if part).lower()def _to_int(value):try:return int(str(value).strip())except Exception:return Nonemax_val = _to_int(meta.get("ariaValueMax"))if any(token in lowered for token in ("year", "yyyy", "yy", "年")):return "year"if any(token in lowered for token in ("month", "mm", "月")):return "month"if any(token in lowered for token in ("day", "dd", "日")):return "day"if max_val is not None:if max_val > 31:return "year"if max_val == 12:return "month"if max_val <= 31:return "day"return Nonedef _fill_about_you_birthday_by_meta(page):metas = _collect_date_spinbutton_meta(page)if len(metas) < 3:return Falsedesired = {"year": "1995", "month": "06", "day": "15"}kind_to_meta = {}for meta in metas:kind = _infer_date_spinbutton_kind(meta)if kind and kind not in kind_to_meta:kind_to_meta[kind] = metaif not all(kind in kind_to_meta for kind in desired):logger.info("[直接注册] 无法可靠识别生日字段顺序,降级为位置猜测")return Falsetry:for kind in ("year", "month", "day"):meta = kind_to_meta[kind]sb = page.locator('[role="spinbutton"]').nth(meta["index"])sb.click(force=True)time.sleep(0.2)try:page.keyboard.press("ControlOrMeta+A")time.sleep(0.1)except Exception:passpage.keyboard.type(desired[kind], delay=80)time.sleep(0.3)logger.info("[直接注册] 已按字段识别填入生日: year=%s month=%s day=%s | order=%s",desired["year"],desired["month"],desired["day"],{kind: kind_to_meta[kind]["index"] for kind in ("year", "month", "day")},)return Trueexcept Exception as exc:logger.warning("[直接注册] 按字段填写生日失败,降级为位置猜测: %s", exc)return Falsedef _detect_direct_register_step(page):url = (page.url or "").lower()if _is_google_redirect(page):return "google"if "email-verification" in url:return "code"if "about-you" in url:return "profile"if "create-account/password" in url or url.endswith("/password"):return "password"if "chatgpt.com" in url and "auth" not in url:return "completed"try:if _first_visible_editable_locator(page, _DIRECT_PASSWORD_SELECTORS, timeout=300):return "password"except Exception:passtry:if _first_visible_editable_locator(page, _DIRECT_CODE_SELECTORS, timeout=300):return "code"except Exception:pass4 unmodified linesexcept Exception:passtry:if _first_visible_editable_locator(page, _DIRECT_EMAIL_SELECTORS, timeout=300):return "email"except Exception:pass15 unmodified linesreturn _detect_direct_register_step(page)def _wait_for_direct_step_change(page, current_step, timeout=15):deadline = time.time() + timeoutwhile time.time() < deadline:step = _detect_direct_register_step(page)if step != current_step:return steptime.sleep(0.5)return _detect_direct_register_step(page)def _complete_direct_about_you(page):"""尽量完成 about-you 页面,兼容不同生日字段顺序。"""if "about-you" not in (page.url or "").lower():return Truebirthday_orders = [("1995", "06", "15"),("06", "15", "1995"),("15", "06", "1995"),]for attempt, values in enumerate(birthday_orders, 1):if "about-you" not in (page.url or "").lower():return Truetry:name_input = page.locator('input[name="name"]').firstif name_input.is_visible(timeout=2000):try:if name_input.is_editable(timeout=500):name_input.fill("User")time.sleep(0.3)except Exception:passexcept Exception:name_input = Nonespinbuttons = []try:spinbuttons = page.locator('[role="spinbutton"]').all()except Exception:spinbuttons = []if len(spinbuttons) >= 3:filled = _fill_about_you_birthday_by_meta(page)if not filled:for label_sel in ("text=生日日期", "text=Date of birth"):try:page.locator(label_sel).first.click(timeout=1000)time.sleep(0.3)breakexcept Exception:continuetry:for sb, val in zip(spinbuttons[:3], values):sb.click(force=True)time.sleep(0.2)try:page.keyboard.press("ControlOrMeta+A")time.sleep(0.1)except Exception:passpage.keyboard.type(val, delay=80)time.sleep(0.3)logger.info("[直接注册] 尝试按位置填入生日(第 %d 次): %s/%s/%s", attempt, *values)except Exception as exc:logger.warning("[直接注册] 生日字段填写失败(第 %d 次): %s", attempt, exc)else:try:age_input = page.locator('input[name="age"], input[placeholder*="年龄"], input[placeholder*="Age"]').firstif age_input.is_visible(timeout=2000) and age_input.is_editable(timeout=500):age_input.fill("25")logger.info("[直接注册] 填入年龄: 25")except Exception:passsubmitted = Falsefor btn_selector in ('button:has-text("完成帐户创建")','button:has-text("Create account")','button:has-text("Continue")','button:has-text("继续")','button[type="submit"]',):try:btn = page.locator(btn_selector).firstif btn.is_visible(timeout=1000):btn.click()submitted = Truebreakexcept Exception:continueif not submitted:try:page.keyboard.press("Enter")except Exception:passnext_step = _wait_for_direct_register_step(page,{"profile", "completed", "code", "password", "email", "google"},timeout=12,)logger.info("[直接注册] 提交资料后状态: %s | URL: %s", next_step, page.url)if next_step != "profile":return Truelogger.warning("[直接注册] about-you 页面仍未完成 | URL: %s | body=%s", page.url, _page_excerpt(page))return Falsedef _register_direct_once(mail_client, email, password):"""执行一次直接注册,返回是否完成注册并进入 Team。"""from playwright.sync_api import sync_playwright89 unmodified linesif step != "email":breakemail_input = _first_visible_editable_locator(page, _DIRECT_EMAIL_SELECTORS, timeout=1500)if not email_input:logger.info("[直接注册] 邮箱输入框不可编辑,等待页面继续跳转...")next_step = _wait_for_direct_step_change(page, "email", timeout=10)if next_step != "email":breaklogger.warning("[直接注册] 邮箱输入框仍不可编辑,继续重试 | URL: %s", page.url)continueemail_input.fill(email)time.sleep(0.5)logger.info("[直接注册] 邮箱已填入,点击 Continue... (attempt %d)", attempt + 1)_safe_invite_screenshot(page, f"direct_02b_email_filled_{attempt}.png")_click_primary_auth_button(page, email_input, ["Continue", "继续"])next_step = _wait_for_direct_step_change(page, "email", timeout=15)logger.info("[直接注册] 点击 Continue 后状态: %s | URL: %s", next_step, page.url)_safe_invite_screenshot(page, f"direct_02c_after_continue_{attempt}.png")6 unmodified linesif next_step != "email":breakemail_input = _first_visible_editable_locator(page, _DIRECT_EMAIL_SELECTORS, timeout=600)if not email_input:logger.info("[直接注册] 邮箱框已只读/跳转中,额外等待页面推进...")next_step = _wait_for_direct_step_change(page, "email", timeout=10)logger.info("[直接注册] 额外等待后状态: %s | URL: %s", next_step, page.url)if next_step != "email":breaklogger.warning("[直接注册] 点击 Continue 后仍停留在邮箱步骤,准备重试... | URL: %s | body=%s",page.url,29 unmodified lineslogger.info("[直接注册] 未检测到密码输入框,跳过")breakpwd_input = _first_visible_editable_locator(page, _DIRECT_PASSWORD_SELECTORS, timeout=1500)if not pwd_input:logger.info("[直接注册] 密码输入框不可编辑,等待页面继续跳转...")next_step = _wait_for_direct_step_change(page, "password", timeout=10)if next_step != "password":breaklogger.warning("[直接注册] 密码输入框仍不可编辑,继续重试 | URL: %s", page.url)continuelogger.info("[直接注册] 设置密码")pwd_input.fill(password)time.sleep(0.5)_click_primary_auth_button(page, pwd_input, ["Continue", "继续", "Log in"])next_step = _wait_for_direct_step_change(page, "password", timeout=15)logger.info("[直接注册] 提交密码后状态: %s | URL: %s", next_step, page.url)if next_step == "google":4 unmodified linescontinueif next_step != "password":breakpwd_input = _first_visible_editable_locator(page, _DIRECT_PASSWORD_SELECTORS, timeout=600)if not pwd_input:logger.info("[直接注册] 密码框已只读/跳转中,额外等待页面推进...")next_step = _wait_for_direct_step_change(page, "password", timeout=10)logger.info("[直接注册] 额外等待后状态: %s | URL: %s", next_step, page.url)if next_step != "password":breakexcept Exception as exc:logger.warning("[直接注册] 密码步骤异常: %s | URL: %s", exc, page.url)50 unmodified lines_safe_invite_screenshot(page, "direct_05_after_code.png")logger.info("[直接注册] 当前 URL: %s", page.url)try:_complete_direct_about_you(page)except Exception as exc:logger.warning("[直接注册] about-you 步骤异常: %s | URL: %s", exc, page.url)_safe_invite_screenshot(page, "direct_06_after_profile.png")logger.info("[直接注册] 当前 URL: %s", page.url)545 unmodified linesflow.stop()def _refresh_main_auth_after_admin_login():try:info = refresh_main_auth_file()logger.info("[管理员登录] 已保存主号认证文件: %s", info.get("auth_file"))return infoexcept Exception as exc:logger.warning("[管理员登录] 主号认证文件生成失败: %s", exc)return Nonedef cmd_admin_login(email=None):"""交互式完成管理员登录并保存到 state.json。"""email = (email or "").strip()14 unmodified lineswhile True:if step == "completed":info = chatgpt.complete_admin_login()chatgpt.stop()_refresh_main_auth_after_admin_login()logger.info("[管理员登录] 登录完成: %s", info.get("email") or email)if info.get("account_id"):logger.info("[管理员登录] Workspace ID: %s", info["account_id"])73 unmodified linestry:logger.info("[管理员登录] 开始导入 session_token: %s", email)info = chatgpt.import_admin_session(email, session_token)chatgpt.stop()_refresh_main_auth_after_admin_login()logger.info("[管理员登录] session_token 导入完成: %s", info.get("email") or email)if info.get("account_id"):logger.info("[管理员登录] Workspace ID: %s", info["account_id"])11 unmodified lineslogger.error("[主号 Codex] 缺少管理员登录态,请先执行 admin-login")return Nonesaved_auth_file = get_saved_main_auth_file()if saved_auth_file:sync_main_codex_to_cpa(saved_auth_file)logger.info("[主号 Codex] 已直接同步现有认证文件: %s", saved_auth_file)return {"auth_file": saved_auth_file}flow = MainCodexSyncFlow()try:logger.info("[主号 Codex] 开始同步: %s", state.get("email"))157 unmodified lines# 确定要移除的数量if max_seats is None:max_seats = 5logger.info("[清理] 未指定上限,使用默认总人数: %d", max_seats)to_remove_count = total - max_seatsif to_remove_count <= 0:logger.info("[清理] 成员数 %d 未超过上限 %d,无需清理", total, max_seats)116 unmodified linescheck_and_setup(interactive=True)try:from autoteam.auth_storage import ensure_auth_file_permissionsensure_auth_file_permissions()except Exception:passif args.command == "status":cmd_status()elif args.command == "check":
src/autoteam/api.py+45
src/autoteam/auth_storage.pyAdded+35
src/autoteam/codex_auth.py+37-4
src/autoteam/cpa_sync.py+3-7
src/autoteam/manager.py+326-53