From 540209288c782ad2c1c99740fbe6359cc18c7902 Mon Sep 17 00:00:00 2001 From: ellan-bm <296672810@qq.com> Date: Tue, 24 Nov 2026 15:00:05 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20=E6=8C=87=E7=BA=B9=E6=B5=8F?= =?UTF-8?q?=E8=A7=88=E5=99=A8=E6=94=AF=E6=8C=81=20Firefox=20WebDriver=20Bi?= =?UTF-8?q?Di=20=E5=AF=BC=E5=85=A5=E5=B9=B6=E6=96=B0=E5=A2=9E=20Camoufox?= =?UTF-8?q?=20=E8=BF=9C=E7=A8=8B=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 从指纹浏览器导入与 setup --cdp 在 Chromium CDP 之外支持 Firefox 内核的 WebDriver BiDi:/json/version 无 CDP 信息或产品名为 Firefox 时经 session.new 与 storage.getCookies 读取未分区 Cookie,BiDi Cookie 转换为 storage state 形状并完成 base64 值解码 - 账户行新增远程操作,全屏窗口接入常驻 Camoufox 画面,支持地址栏导航、历史进退、刷新、标签页开关、指针键盘输入、粘贴与页面对话框 - 远程操作连接期间账户暂停参与请求调度,断开后恢复调度并把浏览器当前 Cookie 全量写回 storage-state.json;打开前经状态接口返回可用性与原因,控制命令失败在窗口内提示 - 登录窗口与远程操作共用画面转发,画面帧率为每秒 20 帧 - 中英文 README、开发文档与协议文档同步 --- README.md | 8 +- README_en.md | 8 +- docs/development.md | 6 +- docs/protocol.md | 8 +- internal/aistudio/accounts.go | 34 ++ internal/aistudio/manual_hold_test.go | 114 ++++ internal/aistudio/runtime_native.go | 41 ++ internal/api/account_live_view.go | 41 ++ internal/api/account_tasks.go | 2 +- internal/api/admin.go | 6 + internal/app/admin.go | 16 +- internal/app/lifecycle.go | 12 + internal/app/liveview.go | 92 +++ internal/camoufoxnative/bidi.go | 43 +- internal/camoufoxnative/liveview.go | 202 ++++++- internal/camoufoxnative/worker.go | 2 + internal/camoufoxnative/worker_liveview.go | 54 ++ internal/chromeauth/bidi.go | 231 ++++++++ internal/chromeauth/bidi_test.go | 438 ++++++++++++++ internal/chromeauth/cdp.go | 85 +-- internal/chromeauth/debugging.go | 11 +- internal/i18n/messages/de.json | 7 + internal/i18n/messages/en.json | 7 + internal/i18n/messages/fr.json | 7 + internal/i18n/messages/ja.json | 7 + internal/i18n/messages/ko.json | 7 + internal/i18n/messages/zh-TW.json | 7 + internal/setup/setup.go | 2 +- web/src/App.vue | 1 + web/src/api.ts | 6 + web/src/components/AccountLiveViewer.vue | 651 +++++++++++++++++++++ web/src/components/AccountsPanel.vue | 34 ++ web/src/icons.ts | 2 + web/src/locales/de.ts | 14 +- web/src/locales/en.ts | 14 +- web/src/locales/fr.ts | 14 +- web/src/locales/ja.ts | 14 +- web/src/locales/ko.ts | 14 +- web/src/locales/zh-CN.ts | 14 +- web/src/locales/zh-TW.ts | 14 +- 40 files changed, 2198 insertions(+), 92 deletions(-) create mode 100644 internal/aistudio/manual_hold_test.go create mode 100644 internal/api/account_live_view.go create mode 100644 internal/app/liveview.go create mode 100644 internal/camoufoxnative/worker_liveview.go create mode 100644 internal/chromeauth/bidi.go create mode 100644 internal/chromeauth/bidi_test.go create mode 100644 web/src/components/AccountLiveViewer.vue diff --git a/README.md b/README.md index a7ce015b..6a49e1bb 100644 --- a/README.md +++ b/README.md @@ -781,7 +781,7 @@ API 试用页的 HTML 预览运行在 `PREVIEW_LISTEN_ADDR` 提供的独立来 | --- | --- | --- | | 从 Chrome 导入 | 本机 Chrome 中已登录的账户 | 可多选,Windows 可用 | | 粘贴 Cookie | Cookie 扩展导出的 JSON、请求头中的 Cookie 一行或 Netscape cookies.txt | 自动识别其中登录的账户邮箱 | -| 从指纹浏览器导入 | 本机指纹浏览器与 Chromium 中已登录 AI Studio 的窗口 | 浏览器需开启远程调试 | +| 从指纹浏览器导入 | 本机指纹浏览器与 Chromium 中已登录 AI Studio 的窗口 | 浏览器需开启远程调试,Chromium 走 CDP,Firefox 内核走 WebDriver BiDi | | 浏览器登录 | 独立的 Camoufox 窗口 | 登录后自动识别邮箱并授权 Google Drive | | 远程添加 | 另一台能登录 Google 的电脑 | 见 [命令](#命令) 的 `setup --remote` | @@ -799,6 +799,12 @@ API 试用页的 HTML 预览运行在 `PREVIEW_LISTEN_ADDR` 提供的独立来 - 服务器没有图形界面,或从其他电脑、经反向代理打开管理页面时,“浏览器登录”与“重新登录”的 Camoufox 在服务器上无头运行,画面显示在管理页面的全屏登录窗口中,在其中点击、输入与粘贴,点“取消”结束登录 - 页内登录窗口可以隐藏,之后从任务行再次打开;经反向代理访问时需要转发 `/api/login-view/` 的 WebSocket +远程操作常驻浏览器: + +- 生成服务运行时,账户行的“远程操作”把该账户的常驻 Camoufox 画面接入管理页全屏窗口,可在地址栏输入网址、前进后退、刷新、开关标签页,并直接点击、输入与处理对话框,用于完成验证、授权邮件等操作 +- 窗口连接期间账户不参与请求调度,断开后自动恢复;操作产生的 Cookie 在断开时全量回写账户状态,浏览器连接中断时窗口显示原因并结束远程操作 +- 需要 Camoufox 后端与已就绪的常驻 Worker;经反向代理访问时需要转发 `/api/accounts/` 下的 WebSocket + 账户操作随状态显示,点击账户行的状态可把账户改为“就绪”或“已停用”: | 账户状态 | 可用操作 | diff --git a/README_en.md b/README_en.md index 80a26495..d80c7294 100644 --- a/README_en.md +++ b/README_en.md @@ -780,7 +780,7 @@ HTTP, HTTPS, and SOCKS5 proxies are supported. For proxies that require authenti | --- | --- | --- | | Import from Chrome | Accounts signed in to Chrome on this computer | Several can be selected; available on Windows | | Paste cookies | JSON exported by a cookie extension, a Cookie request header line, or a Netscape cookies.txt file | The account email is detected automatically | -| Import from an antidetect browser | Windows signed in to AI Studio in local antidetect browsers and Chromium | The browser needs remote debugging enabled | +| Import from an antidetect browser | Windows signed in to AI Studio in local antidetect browsers and Chromium | The browser needs remote debugging enabled; Chromium uses CDP while Firefox-based browsers use WebDriver BiDi | | Sign in with browser | An isolated Camoufox window | Detects the email and authorizes Google Drive after login | | Add remotely | Another computer that can sign in to Google | See `setup --remote` under [Commands](#commands) | @@ -798,6 +798,12 @@ Sign in with browser: - When the server has no graphical display, or the console is opened from another computer or through a reverse proxy, Camoufox for "Sign in with browser" and "Sign in again" runs headless on the server and its screen appears in a full-screen sign-in window in the console, where you click, type, and paste; Cancel ends the sign-in - The in-page sign-in window can be hidden and reopened from its task row; a reverse proxy must forward the WebSocket at `/api/login-view/` +Remote control of the resident browser: + +- While the generation service runs, "Remote control" in an account row streams that account's resident Camoufox screen into a full-screen console window, with an address bar for entering URLs, back/forward, reload, and tab open/close controls, plus direct clicks, typing, and dialog handling for verification and authorization steps +- The account stays out of request scheduling while the window is connected and resumes when it closes; cookies produced during the session are written back to the account state on disconnect, and a dropped browser connection shows the reason and ends the session +- Requires the Camoufox backend and a ready resident worker; a reverse proxy must forward WebSockets under `/api/accounts/` + Account actions depend on state. Click the state in an account row to set the account to Ready or Disabled: | Account state | Available actions | diff --git a/docs/development.md b/docs/development.md index ce2c3e5f..d0d4efa0 100644 --- a/docs/development.md +++ b/docs/development.md @@ -36,7 +36,7 @@ cd .. go run ./cmd/aistudio2api ``` -管理页面“账户”页的“添加账户”菜单提供从 Chrome 导入、粘贴 Cookie、从指纹浏览器导入、浏览器登录和远程添加,也可以重新登录、立即刷新、编辑、启停和删除账户。浏览器登录会在隔离 Camoufox 中完成并自动读取邮箱。启停账户保存后立即返回,停用后等待在途请求结束并关闭 Worker、启用后载入页面同步模型目录,都在后台完成。 +管理页面“账户”页的“添加账户”菜单提供从 Chrome 导入、粘贴 Cookie、从指纹浏览器导入、浏览器登录和远程添加,也可以重新登录、立即刷新、编辑、启停和删除账户。浏览器登录会在隔离 Camoufox 中完成并自动读取邮箱。启停账户保存后立即返回,停用后等待在途请求结束并关闭 Worker、启用后载入页面同步模型目录,都在后台完成。生成服务运行时,账户行的“远程操作”把常驻 Camoufox Worker 的画面接入全屏窗口,支持地址栏导航、历史进退、刷新、标签页开关与指针键盘输入,窗口连接期间账户暂停参与请求调度,断开时把浏览器当前 Cookie 写回账户状态。 浏览器登录与重新登录的显示方式由服务端按请求决定: @@ -46,7 +46,7 @@ go run ./cmd/aistudio2api 管理页面为每次登录生成随机 ID,在 `POST /api/accounts` 或 `POST /api/accounts/{id}/login` 的 body 中以 `view` 带上该 ID,同时连接 `GET /api/login-view/{ID}` 的 WebSocket,两者在服务端取得同一个登录窗口。使用登录窗口时: - 隔离 Camoufox 以无头方式启动,Linux 没有 `DISPLAY` 时使用服务启动的 Xvfb,页面保持 Firefox 默认刷新帧率;导航 AI Studio 后立即返回,登录窗口显示载入过程 -- 登录窗口连接期间,服务端经 WebDriver BiDi `browsingContext.captureScreenshot` 以 JPEG(质量 0.8)截取最后打开且仍存在的顶层页面,间隔不短于 100 ms,只推送与上一帧不同的画面;每帧先发 JSON 元数据(页面 context、URL、标题、CSS 视口宽高与 devicePixelRatio),再发 JPEG 二进制。弹窗关闭后画面回到原页面 +- 登录窗口连接期间,服务端经 WebDriver BiDi `browsingContext.captureScreenshot` 以 JPEG(质量 0.8)截取最后打开且仍存在的顶层页面,间隔不短于 50 ms,只推送与上一帧不同的画面;每帧先发 JSON 元数据(页面 context、URL、标题、CSS 视口宽高与 devicePixelRatio),再发 JPEG 二进制。弹窗关闭后画面回到原页面 - 管理页面把鼠标移动、按下与抬起、滚轮、按键按下与抬起和粘贴文本经同一连接发回,附带画面所属页面;服务端按到达顺序合并成 `input.performActions`:指针为 mouse,滚轮为 wheel,`KeyboardEvent.key` 的命名键映射为 WebDriver 键码点,粘贴文本逐字符按下与抬起;页面已关闭的输入丢弃,输入内容不写日志 - 会话以 `unhandledPromptBehavior` 让 alert、confirm 与 prompt 保持打开,`browsingContext.userPromptOpened` 时登录窗口显示对话框,用户的选择以 `browsingContext.handleUserPrompt` 不经命令锁发送,打开对话框的输入命令随之返回 - 关闭登录窗口时管理页面中止登录请求,请求取消后服务端结束 Camoufox 并删除 profile 与隔离登录目录 @@ -82,7 +82,7 @@ go run ./cmd/aistudio2api - 文件导入:`--storage-state` - Cookie 导入:`--cookie`、`--cookie-file` 或 `--cdp`,账户邮箱按 Cookie 识别,也可用一个 `--email` 指定;`--authuser N` 选择 Cookie 中第 N 个 Google 会话(官网 `/u/N/`)的账户并验证其邮箱;只保留 google.com 及其子域的 Cookie,缺少 `__Secure-1PSID`、`SAPISID`、`__Secure-1PAPISID` 或 `__Secure-3PAPISID` 时报告缺少的 Cookie -- `--cdp` 接受 `host:port`、HTTP 调试地址或浏览器级 `ws://` 地址,经 CDP `Storage.getCookies` 读取该浏览器的全部未分区 Cookie +- `--cdp` 接受 `host:port`、HTTP 调试地址或浏览器级 `ws://` 地址:Chromium 经 CDP `Storage.getCookies` 读取全部未分区 Cookie;`/json/version` 没有 CDP 信息时(Firefox 内核仅开放 WebDriver BiDi,返回 404)改用 BiDi,经 `session.new` 与 `storage.getCookies` 读取未分区 Cookie - 管理页面导入 Cookie 只需粘贴 Cookie 或选择 Cookie 文件:页面在粘贴或输入停顿后自动识别,服务以 Cookie 打开 AI Studio 对话页,从页面全局数据 `oPEP7c` 读取登录账户邮箱,再读取 `ListModels` 确认可用;页面转到登录页时返回 `signed_out`;账户池中已有的账户标为 `imported`,其中需要重新登录的另标 `sign_in_required` 并默认勾选,导入时原地更新该账户,冷却与运行状态保留 - 管理页面的添加、导入与重新登录在服务端的账户任务中运行(`internal/api/account_tasks.go`):请求返回 202 与任务后对话框即关闭,任务在请求结束后继续运行,逐个处理账户并把每个账户的状态、当前步骤、错误码与原因推送到管理事件流的 `account_tasks`,账户页据此显示任务行;浏览器登录任务带登录窗口 ID,页内登录窗口隐藏或页面刷新后以同一 ID 重新连接 - “从指纹浏览器导入”从本机进程命令行找出带 `--remote-debugging-port` 的浏览器(端口为 0 时读取用户数据目录的 `DevToolsActivePort`),逐个读取 Cookie 并识别账户,列出可导入、已导入与未登录的浏览器 diff --git a/docs/protocol.md b/docs/protocol.md index 17c99ce4..6b15c8ab 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -1698,7 +1698,7 @@ GET/DELETE /v1beta/files/{file} | 生成服务 | `POST /api/control/start`、`POST /api/control/stop` | | 账户 | `GET /api/accounts`、`GET /api/accounts/exits`、`POST /api/accounts`、`GET/POST /api/accounts/import/chrome`、`GET /api/accounts/import/browsers`、`POST /api/accounts/import/cookies/discover`、`POST /api/accounts/import/cookies`、`PUT /api/accounts/{id}`、`PUT /api/accounts/{id}/state`、`DELETE /api/accounts/{id}` | | 账户任务 | `GET /api/accounts/tasks`、`DELETE /api/accounts/tasks/{id}` | -| 账户认证与刷新 | `POST /api/accounts/{id}/login`、`POST /api/accounts/{id}/refresh`、`POST /api/accounts/refresh`、`GET /api/login-view/{view}`(WebSocket) | +| 账户认证与刷新 | `POST /api/accounts/{id}/login`、`POST /api/accounts/{id}/refresh`、`POST /api/accounts/refresh`、`GET /api/login-view/{view}`(WebSocket)、`GET /api/accounts/{id}/live-view`(WebSocket)、`GET /api/accounts/{id}/live-view/status` | | 远程配对 | `GET /api/pairing`、`POST /api/pairing`、`POST /api/pairing/accounts`、`PUT /api/pairing/accounts/{account}/cookies` | | 配置 | `GET /api/config`、`PUT /api/config`、`GET /api/first-event-latency` | | 冷却与请求 | `GET /api/cooldowns`、`DELETE /api/accounts/{id}/cooldowns/{scope}`、`GET /api/requests`、`POST /api/requests/{id}/cancel` | @@ -1799,7 +1799,10 @@ GET/DELETE /v1beta/files/{file} - 服务端推送 `{"type":"status","status":"starting|waiting|saving"}` - 服务端推送 `{"type":"dialog","dialog":{"kind","message","value"}|null}` - 服务端推送 `{"type":"frame","context","url","title","width","height","scale"}`,后面紧跟一条 JPEG 二进制消息 + - 服务端推送 `{"type":"control-error","message"}` 报告导航或标签页控制命令的失败 - 客户端发送 `{"type":"pointer","action":"move|down|up","x","y","button","context"}`、`{"type":"wheel","x","y","dx","dy","context"}`、`{"type":"key","action":"down|up","key","context"}`、`{"type":"text","text","context"}` 与 `{"type":"dialog","accept","text"}` +- `GET /api/accounts/{id}/live-view` 把管理页远程操作窗口接到账户的常驻 Camoufox Worker(Camoufox 后端且 Worker 就绪时可用,冲突时返回 409 `live_view_unavailable`):挂载期间账户被手动占用,不参与请求调度;窗口断开后解除占用并把浏览器当前 Cookie 全量写回 `storage-state.json`。推送消息与 `GET /api/login-view/{view}` 相同,另推送 `{"type":"closed","error"}` 表示浏览器连接断开并结束远程操作;客户端除指针、键盘、文本与对话框消息外,还可发送 `{"type":"navigate","url","context"}`、`{"type":"reload","context"}`、`{"type":"history","delta","context"}`、`{"type":"newTab","url?","context"}` 与 `{"type":"closeTab","context"}` +- `GET /api/accounts/{id}/live-view/status` 在建立 WebSocket 前返回 `{"available":bool,"reason"?:string}`:SpiderMonkey 后端、无就绪常驻 Worker 或窗口已被占用时 `available` 为假并给出具体原因,管理页据此在打开远程操作窗口前展示提示 管理 DTO 字段: @@ -1825,6 +1828,7 @@ GET/DELETE /v1beta/files/{file} | `AccountTask` | `id`、`kind`(`login`、`relogin`、`chrome`、`cookies`、`browser`)、可选 `view`、`state`(`running`、`done`、`failed`)、`items`、`started_at` | | `AccountTaskItem` | `label`(账户邮箱,浏览器登录完成前为空)、`state`(`pending`、`running`、`done`、`failed`)、可选 `step`(处理中的账户当前的步骤:`login` 等待登录、`reading` 读取浏览器里的登录状态、`checking` 检查 AI Studio 访问、`saving` 保存账户)、可选 `code`、`error` | | `CookieBrowser` | `address`、`browser`、`email`、`auth_user`、`imported`、`signed_out`、`error`、`restricted`、`device_bound`、`sign_in_required` | +| `LiveViewAvailability` | `available`、可选 `reason` | | `PairingToken` | `token`、`expires_at` | | `AccountStateInput` | `label`、`locale`、`timezone`、`storage_state`、可选 `auth_user`(默认 0)、可选 `fingerprint` | | `AdminCooldown` | `account_id`、`account_label`、`model_id`、`until`、可选 `reason` | @@ -1917,7 +1921,7 @@ Chrome 导入列表按 `Preferences.account_info` 中的 Gaia ID 与邮箱逐个 - `AccountCreateInput` 启动隔离 Camoufox 登录,邮箱由 AI Studio 页面读取 - `ChromeImportInput.accounts` 可一次选择多个账号,每个账号作为账户任务中的一项单独导入 - `CookieImportInput.cookies` 与 `CookieAccountsInput` 每项的 `cookies` 接受 Cookie 扩展导出的 storage state 或 Cookie 数组 JSON、Netscape cookies.txt 和一行 Cookie 请求头,只保留 google.com 及其子域的 Cookie,导入账户的 `label` 为账户邮箱 -- `CookieAccountsInput` 每项的 `cdp` 非空时,改从该远程调试地址读取浏览器的全部未分区 Cookie +- `CookieAccountsInput` 每项的 `cdp` 非空时,改从该远程调试地址读取浏览器的全部未分区 Cookie:Chromium 走 CDP `Storage.getCookies`,Firefox 内核(`/json/version` 返回 404)走 WebDriver BiDi 的 `session.new` 与 `storage.getCookies`,分区 Cookie 一律过滤 - `AccountCreateInput`、`ChromeImportInput`、`CookieAccountsInput` 与 `AccountStateInput` 的 `locale`、`timezone` 为空时按账户出口的地理位置填写;`GET /api/accounts/exits` 对各账户出口代理各查询一次公网 IP 与地理位置 - `AccountInput.label` 必须与不可变的 Google 邮箱 ID 一致,`locale` 与 `timezone` 必须非空;`proxy` 使用 HTTP、HTTPS 或 SOCKS5 origin,可带 `user:password@`,不含 path、query 或 fragment diff --git a/internal/aistudio/accounts.go b/internal/aistudio/accounts.go index 074c276f..c578ccc3 100644 --- a/internal/aistudio/accounts.go +++ b/internal/aistudio/accounts.go @@ -83,6 +83,8 @@ var ( ErrAccountCoolingDown = errors.New("账户已进入冷却") // ErrResourceNotFound 表示资源没有创建账户映射 ErrResourceNotFound = errors.New("资源账户映射不存在") + // ErrAccountManualHold 表示账户正在被远程操作,生成请求选号返回该错误 + ErrAccountManualHold = errors.New("账户正在远程操作中") ) // AllCoolingError 表示请求的全部候选账户都在冷却且不会很快恢复 @@ -598,6 +600,8 @@ type AccountPool struct { sessions singleflight.Group // fileBindMu 串行化文件绑定,使公开文件名的重名检查与绑定成为一步 fileBindMu sync.Mutex + // manualHolds 是远程操作期间禁止调度的账户及占用次数,由 mu 保护 + manualHolds map[string]int } // AccountLease 表示一个账户请求槽位 @@ -1078,6 +1082,7 @@ func NewAccountPool(accounts []*Account, perAccountConcurrency int) *AccountPool accounts: append([]*Account(nil), accounts...), byID: make(map[string]*Account, len(accounts)), resources: make(map[string]string), perAccountConcurrency: perAccountConcurrency, changed: make(chan struct{}), routingStrategy: "round-robin", lastPicked: make(map[string]string), lastPickedChannel: make(map[string]Channel), + manualHolds: make(map[string]int), } for _, account := range p.accounts { if account.runtime.Cooldowns == nil { @@ -3349,6 +3354,9 @@ func (p *AccountPool) selectionIndicesLocked(selection AccountSelection) ([]int, if accountID != "" { for index, account := range p.accounts { if account.ID == accountID { + if p.manualHolds[accountID] > 0 { + return nil, ErrAccountManualHold + } if allowed != nil { if _, exists := allowed[accountID]; !exists { return nil, fmt.Errorf("%w:账户 %s 不在本次请求可用的账户中", ErrNoEligibleAccount, accountID) @@ -3361,6 +3369,9 @@ func (p *AccountPool) selectionIndicesLocked(selection AccountSelection) ([]int, } indices := make([]int, 0, len(p.accounts)) for index, account := range p.accounts { + if p.manualHolds[account.ID] > 0 { + continue + } if allowed != nil { if _, exists := allowed[account.ID]; !exists { continue @@ -3486,6 +3497,29 @@ func (p *AccountPool) Changed() <-chan struct{} { return p.changed } +// SetManualHold 增加或释放账户的手动占用,占用期间该账户不参与请求调度,释放时唤醒等待者 +func (p *AccountPool) SetManualHold(accountID string, delta int) { + p.mu.Lock() + defer p.mu.Unlock() + if p.manualHolds == nil { + p.manualHolds = make(map[string]int) + } + count := p.manualHolds[accountID] + delta + if count <= 0 { + delete(p.manualHolds, accountID) + } else { + p.manualHolds[accountID] = count + } + p.notifyLocked() +} + +// ManualHold 报告账户当前是否被手动占用 +func (p *AccountPool) ManualHold(accountID string) bool { + p.mu.Lock() + defer p.mu.Unlock() + return p.manualHolds[accountID] > 0 +} + func (p *AccountPool) notifyLocked() { close(p.changed) p.changed = make(chan struct{}) diff --git a/internal/aistudio/manual_hold_test.go b/internal/aistudio/manual_hold_test.go new file mode 100644 index 00000000..84f6d0df --- /dev/null +++ b/internal/aistudio/manual_hold_test.go @@ -0,0 +1,114 @@ +package aistudio + +import ( + "context" + "errors" + "testing" +) + +// newManualHoldPool 构造两个可调度账户的测试池 +func newManualHoldPool() *AccountPool { + model := Model{ID: "gemini", Methods: []string{"generateContent"}, Capabilities: map[string]bool{"chat_model": true}} + accounts := []*Account{ + {ID: "a@example.com", Config: AccountConfig{Enabled: true}, State: AccountReady, Models: []Model{model}, modelAccessGeneration: 1}, + {ID: "b@example.com", Config: AccountConfig{Enabled: true}, State: AccountReady, Models: []Model{model}, modelAccessGeneration: 1}, + } + pool := NewAccountPool(accounts, 1) + pool.SetUpstreamChannels([]Channel{ChannelPlayground}) + for _, account := range accounts { + if err := pool.SetBuildCatalog(account.ID, []Model{model}); err != nil { + panic(err) + } + } + return pool +} + +// TestManualHoldSkipsAccount 验证手动占用的账户不参与通用调度,释放后恢复 +func TestManualHoldSkipsAccount(t *testing.T) { + pool := newManualHoldPool() + selection := AccountSelection{ModelID: "gemini", Method: "generateContent", PreferredChannel: ChannelBuild} + + pool.SetManualHold("a@example.com", 1) + if !pool.ManualHold("a@example.com") { + t.Fatal("占用标记未生效") + } + for range 5 { + lease, ok, err := pool.TryAcquireFor(context.Background(), selection) + if err != nil || !ok || lease == nil { + t.Fatalf("占用 a 后应始终选到 b,lease=%v ok=%v err=%v", lease, ok, err) + } + if lease.Account().ID != "b@example.com" { + t.Fatalf("选中了被占用的账户 %s", lease.Account().ID) + } + if err := lease.Release(); err != nil { + t.Fatal(err) + } + } + + pool.SetManualHold("a@example.com", -1) + if pool.ManualHold("a@example.com") { + t.Fatal("释放占用后标记仍存在") + } + seen := map[string]bool{} + for range 4 { + lease, ok, err := pool.TryAcquireFor(context.Background(), selection) + if err != nil || !ok || lease == nil { + t.Fatalf("释放占用后应能正常选号,lease=%v ok=%v err=%v", lease, ok, err) + } + seen[lease.Account().ID] = true + if err := lease.Release(); err != nil { + t.Fatal(err) + } + } + if !seen["a@example.com"] || !seen["b@example.com"] { + t.Fatalf("释放占用后两个账户都应可被选中,实际 %v", seen) + } +} + +// TestManualHoldDirectSelection 验证手动占用下生成请求选号返回错误、管理租约保持可用,嵌套占用可逐层释放 +func TestManualHoldDirectSelection(t *testing.T) { + pool := newManualHoldPool() + selection := AccountSelection{AccountID: "a@example.com"} + pool.SetManualHold("a@example.com", 1) + + // 生成请求路径指定被占用账户时返回明确错误 + _, ok, err := pool.TryAcquireFor(context.Background(), selection) + if !errors.Is(err, ErrAccountManualHold) { + t.Fatalf("指定被占用账户的选号错误 = %v,期望 ErrAccountManualHold", err) + } + if ok { + t.Fatal("被占用账户不应返回可用租约") + } + + // 管理操作租约保持可用,远程操作结束后的 Cookie 回写使用该租约 + lease, err := pool.AcquireAccount(context.Background(), "a@example.com") + if err != nil { + t.Fatalf("管理租约获取失败: %v", err) + } + if err := lease.Release(); err != nil { + t.Fatal(err) + } + + // 计数语义:两层占用时释放一层仍保持占用,生成请求继续返回错误 + pool.SetManualHold("a@example.com", 1) + pool.SetManualHold("a@example.com", -1) + if !pool.ManualHold("a@example.com") { + t.Fatal("计数占用释放一层后仍应保持占用") + } + if _, _, err := pool.TryAcquireFor(context.Background(), selection); !errors.Is(err, ErrAccountManualHold) { + t.Fatalf("占用保持时选号错误 = %v,期望 ErrAccountManualHold", err) + } + + pool.SetManualHold("a@example.com", -1) + if pool.ManualHold("a@example.com") { + t.Fatal("全部释放后占用应解除") + } + // 释放后生成请求路径恢复选号 + lease, ok, err = pool.TryAcquireFor(context.Background(), selection) + if err != nil || !ok || lease == nil { + t.Fatalf("占用解除后应能选号,lease=%v ok=%v err=%v", lease, ok, err) + } + if err := lease.Release(); err != nil { + t.Fatal(err) + } +} diff --git a/internal/aistudio/runtime_native.go b/internal/aistudio/runtime_native.go index 4ae9374f..481ea6fb 100644 --- a/internal/aistudio/runtime_native.go +++ b/internal/aistudio/runtime_native.go @@ -47,6 +47,47 @@ var ErrProtectedTransport = errors.New("受保护请求网络错误") var _ ProtectedPreparer = (*NativeWorker)(nil) var _ ProtocolHeaderProvider = (*NativeWorker)(nil) +// liveViewAttacher 是能挂载远程操作窗口的浏览器 runtime,SpiderMonkey 后端不满足 +type liveViewAttacher interface { + AttachLiveView(context.Context, *camoufoxnative.LiveView) (func(), error) + LiveViewAvailable() (bool, string) +} + +// liveViewUnsupportedReason 是 SpiderMonkey 后端不支持远程操作时的原因 +const liveViewUnsupportedReason = "SpiderMonkey 后端没有可操作的浏览器,请在服务配置切换为 Camoufox 后端并重启" + +// LiveViewAvailability 返回该 runtime 挂载远程操作窗口的可用性与原因 +func (worker *NativeWorker) LiveViewAvailability() (bool, string) { + worker.runtimeMu.RLock() + runtime := worker.runtime + worker.runtimeMu.RUnlock() + attacher, ok := runtime.(liveViewAttacher) + if !ok { + return false, liveViewUnsupportedReason + } + return attacher.LiveViewAvailable() +} + +// AttachLiveView 把远程操作窗口接到账户的 Camoufox runtime,SpiderMonkey 后端没有可操作的浏览器 +func (worker *NativeWorker) AttachLiveView(ctx context.Context, view *camoufoxnative.LiveView) (func(), error) { + worker.runtimeMu.RLock() + runtime := worker.runtime + worker.runtimeMu.RUnlock() + attacher, ok := runtime.(liveViewAttacher) + if !ok { + return nil, errors.New(liveViewUnsupportedReason) + } + return attacher.AttachLiveView(ctx, view) +} + +// StorageCookies 导出当前浏览器 Cookie 的 storage state JSON +func (worker *NativeWorker) StorageCookies(ctx context.Context) ([]byte, error) { + worker.runtimeMu.RLock() + runtime := worker.runtime + worker.runtimeMu.RUnlock() + return runtime.StorageCookies(ctx) +} + // camoufoxRuntime 是 Camoufox 后端的 workerRuntime,重新载入在同一浏览器中进行 type camoufoxRuntime struct { *camoufoxnative.Worker diff --git a/internal/api/account_live_view.go b/internal/api/account_live_view.go new file mode 100644 index 00000000..5905711f --- /dev/null +++ b/internal/api/account_live_view.go @@ -0,0 +1,41 @@ +package api + +import ( + "net/http" + + "github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative" +) + +// LiveViewAvailability 是远程操作窗口的可用性检查结果 +type LiveViewAvailability struct { + Available bool `json:"available"` + Reason string `json:"reason,omitempty"` +} + +// handleAccountLiveView 把管理页远程操作窗口接到账户的常驻 Camoufox Worker, +// 连接期间转发画面与输入,断开后由服务清理挂载与账户调度占用并写回 Cookie +func (s *server) handleAccountLiveView(w http.ResponseWriter, r *http.Request) { + accountID := r.PathValue("id") + view := camoufoxnative.NewLiveView() + cleanup, err := s.config.Admin.AttachAccountLiveView(r.Context(), accountID, view) + if err != nil { + writeAdminError(w, http.StatusConflict, "live_view_unavailable", err.Error()) + return + } + defer cleanup() + connection, err := loginViewUpgrader.Upgrade(w, r, nil) + if err != nil { + return + } + _ = view.Serve(r.Context(), connection) +} + +// handleAccountLiveViewStatus 返回账户常驻浏览器当前能否挂载远程操作窗口 +func (s *server) handleAccountLiveViewStatus(w http.ResponseWriter, r *http.Request) { + availability, err := s.config.Admin.LiveViewAvailability(r.Context(), r.PathValue("id")) + if err != nil { + writeAdminError(w, http.StatusNotFound, "account_not_found", err.Error()) + return + } + writeJSON(w, http.StatusOK, availability) +} diff --git a/internal/api/account_tasks.go b/internal/api/account_tasks.go index a8fff73d..ac2689e0 100644 --- a/internal/api/account_tasks.go +++ b/internal/api/account_tasks.go @@ -437,7 +437,7 @@ func (s *server) importCookieAccount(ctx context.Context, item cookieImportItem, cookies := item.Cookies if address := strings.TrimSpace(item.CDP); address != "" { ReportTaskStep(ctx, TaskStepReading) - browser, err := chromeauth.ReadCDPBrowser(ctx, address) + browser, err := chromeauth.ReadBrowserCookies(ctx, address) if err != nil { return AdminAccount{}, err } diff --git a/internal/api/admin.go b/internal/api/admin.go index 12506b29..47959e61 100644 --- a/internal/api/admin.go +++ b/internal/api/admin.go @@ -30,6 +30,10 @@ type AdminService interface { DeleteAccount(context.Context, string) error LoginAccount(context.Context, string, *camoufoxnative.LiveView) (AdminAccount, error) VerifyAccount(context.Context, string, *camoufoxnative.LiveView) (AdminAccount, error) + // AttachAccountLiveView 把远程操作窗口接到账户的常驻浏览器,返回的函数在窗口断开时清理 + AttachAccountLiveView(ctx context.Context, accountID string, view *camoufoxnative.LiveView) (func(), error) + // LiveViewAvailability 返回账户远程操作窗口的可用性与原因 + LiveViewAvailability(ctx context.Context, accountID string) (LiveViewAvailability, error) RefreshAccount(context.Context, string) (AdminAccountRefresh, error) StartService(context.Context) (AdminStatus, error) StopService(context.Context) (AdminStatus, error) @@ -451,6 +455,8 @@ func (s *server) registerAdmin(mux *http.ServeMux) { mux.HandleFunc("POST /api/accounts/{id}/login", s.handleLoginAccount) mux.HandleFunc("POST /api/accounts/{id}/verify", s.handleVerifyAccount) mux.HandleFunc("GET /api/login-view/{view}", s.handleLoginView) + mux.HandleFunc("GET /api/accounts/{id}/live-view", s.handleAccountLiveView) + mux.HandleFunc("GET /api/accounts/{id}/live-view/status", s.handleAccountLiveViewStatus) mux.HandleFunc("POST /api/accounts/{id}/refresh", s.handleRefreshAccount) mux.HandleFunc("POST /api/accounts/refresh", s.handleRefreshAccounts) mux.HandleFunc("POST /api/control/start", s.handleStartService) diff --git a/internal/app/admin.go b/internal/app/admin.go index 60805b49..8834c3af 100644 --- a/internal/app/admin.go +++ b/internal/app/admin.go @@ -405,14 +405,14 @@ func (admin *runtimeAdmin) CookieBrowsers(ctx context.Context, proxy string) ([] for index, address := range addresses { group.Go(func() { browser := api.CookieBrowser{Address: address} - name, err := chromeauth.DebugBrowserName(ctx, address) + source, err := chromeauth.ReadBrowserCookies(ctx, address) if err != nil { browser.Error = err.Error() browsers[index] = []api.CookieBrowser{browser} return } - browser.Browser = name - accounts, err := admin.readCookieBrowser(ctx, &browser, proxy) + browser.Browser = source.Product + accounts, err := admin.readCookieBrowser(ctx, &browser, proxy, source.Cookies) browser.SignedOut = errors.Is(err, chromeauth.ErrSignedOut) || errors.Is(err, aistudio.ErrLoginCookieMissing) if err != nil && !browser.SignedOut { browser.Error = err.Error() @@ -424,13 +424,9 @@ func (admin *runtimeAdmin) CookieBrowsers(ctx context.Context, proxy string) ([] return append([]api.CookieBrowser{}, slices.Concat(browsers...)...), nil } -// readCookieBrowser 读取调试浏览器的 Cookie,经 proxy 识别其中各会话登录 AI Studio 的账户 -func (admin *runtimeAdmin) readCookieBrowser(ctx context.Context, browser *api.CookieBrowser, proxy string) ([]chromeauth.CookieAccount, error) { - source, err := chromeauth.ReadCDPBrowser(ctx, browser.Address) - if err != nil { - return nil, err - } - state, err := aistudio.ParseCookieText(source.Cookies) +// readCookieBrowser 解析调试浏览器的 Cookie 文本,经 proxy 识别其中各会话登录 AI Studio 的账户 +func (admin *runtimeAdmin) readCookieBrowser(ctx context.Context, browser *api.CookieBrowser, proxy, cookies string) ([]chromeauth.CookieAccount, error) { + state, err := aistudio.ParseCookieText(cookies) if err != nil { return nil, err } diff --git a/internal/app/lifecycle.go b/internal/app/lifecycle.go index 887ccdfd..b6103250 100644 --- a/internal/app/lifecycle.go +++ b/internal/app/lifecycle.go @@ -47,6 +47,8 @@ type generationAdmin interface { DeleteAccount(context.Context, string) error LoginAccount(context.Context, string, *camoufoxnative.LiveView) (api.AdminAccount, error) VerifyAccount(context.Context, string, *camoufoxnative.LiveView) (api.AdminAccount, error) + AttachAccountLiveView(ctx context.Context, accountID string, view *camoufoxnative.LiveView) (func(), error) + LiveViewAvailability(ctx context.Context, accountID string) (api.LiveViewAvailability, error) RefreshAccount(context.Context, string) (api.AdminAccountRefresh, error) StartService(context.Context) (api.AdminStatus, error) StopService(context.Context) (api.AdminStatus, error) @@ -724,6 +726,16 @@ func (manager *runtimeManager) VerifyAccount(ctx context.Context, id string, vie return manager.currentAdmin().VerifyAccount(ctx, id, view) } +// AttachAccountLiveView 把远程操作窗口接到当前生成服务中账户的常驻浏览器 +func (manager *runtimeManager) AttachAccountLiveView(ctx context.Context, id string, view *camoufoxnative.LiveView) (func(), error) { + return manager.currentAdmin().AttachAccountLiveView(ctx, id, view) +} + +// LiveViewAvailability 返回当前生成服务中账户远程操作的可用性 +func (manager *runtimeManager) LiveViewAvailability(ctx context.Context, id string) (api.LiveViewAvailability, error) { + return manager.currentAdmin().LiveViewAvailability(ctx, id) +} + // prepareLoginCamoufox 在浏览器登录前等 Camoufox 就绪,需要下载时记录等待,失败时记录原因 func (manager *runtimeManager) prepareLoginCamoufox(ctx context.Context, source string) error { if !camoufoxnative.PreparationState().Ready { diff --git a/internal/app/liveview.go b/internal/app/liveview.go new file mode 100644 index 00000000..d9a8b115 --- /dev/null +++ b/internal/app/liveview.go @@ -0,0 +1,92 @@ +package app + +import ( + "context" + "encoding/json" + "errors" + "sync" + "time" + + "github.com/Mag1cFall/AIStudio2API/internal/aistudio" + "github.com/Mag1cFall/AIStudio2API/internal/api" + "github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative" +) + +// liveViewWritebackTimeout 是远程操作结束后把浏览器 Cookie 写回 storage state 的最长时间 +const liveViewWritebackTimeout = 20 * time.Second + +// liveViewNoWorkerReason 是账户没有就绪的常驻浏览器时的提示 +const liveViewNoWorkerReason = "账户的常驻浏览器未运行,请先启动生成服务并等待该账户预热完成" + +// LiveViewAvailability 返回账户常驻浏览器挂载远程操作窗口的可用性与原因 +func (manager *accountWorkerManager) LiveViewAvailability(accountID string) api.LiveViewAvailability { + worker := manager.residentWorker(accountID) + if worker == nil { + return api.LiveViewAvailability{Available: false, Reason: liveViewNoWorkerReason} + } + available, reason := worker.LiveViewAvailability() + return api.LiveViewAvailability{Available: available, Reason: reason} +} + +// AttachAccountLiveView 实现 api.AdminService,委托给 Worker 管理器 +func (admin *runtimeAdmin) AttachAccountLiveView(ctx context.Context, accountID string, view *camoufoxnative.LiveView) (func(), error) { + return admin.workers.AttachAccountLiveView(ctx, accountID, view) +} + +// LiveViewAvailability 实现 api.AdminService,返回账户远程操作的可用性 +func (admin *runtimeAdmin) LiveViewAvailability(_ context.Context, accountID string) (api.LiveViewAvailability, error) { + return admin.workers.LiveViewAvailability(accountID), nil +} + +// AttachAccountLiveView 把远程操作窗口接到账户的常驻 Camoufox Worker: +// 挂载期间账户不参与请求调度,窗口断开后解除占用并把浏览器当前 Cookie 写回到 storage state,返回的清理函数幂等 +func (manager *accountWorkerManager) AttachAccountLiveView(ctx context.Context, accountID string, view *camoufoxnative.LiveView) (func(), error) { + worker := manager.residentWorker(accountID) + if worker == nil { + return nil, errors.New(liveViewNoWorkerReason) + } + manager.pool.SetManualHold(accountID, 1) + detach, err := worker.AttachLiveView(ctx, view) + if err != nil { + manager.pool.SetManualHold(accountID, -1) + return nil, err + } + manager.requests.log(accountID, "INFO", "远程操作窗口已连接") + var cleanupOnce sync.Once + return func() { + cleanupOnce.Do(func() { + detach() + manager.pool.SetManualHold(accountID, -1) + manager.writebackLiveViewCookies(accountID, worker) + manager.requests.log(accountID, "INFO", "远程操作窗口已断开") + }) + }, nil +} + +// writebackLiveViewCookies 把浏览器当前 Cookie 全量写回 storage state,保留 localStorage 与认证扩展,失败只记录日志 +func (manager *accountWorkerManager) writebackLiveViewCookies(accountID string, worker *aistudio.NativeWorker) { + writebackCtx, cancel := context.WithTimeout(context.WithoutCancel(context.Background()), liveViewWritebackTimeout) + defer cancel() + encoded, err := worker.StorageCookies(writebackCtx) + if err != nil { + manager.requests.log(accountID, "WARN", "远程操作 Cookie 写回跳过:读取浏览器 Cookie 失败", "error", err) + return + } + var cookies []aistudio.StateCookie + if err := json.Unmarshal(encoded, &cookies); err != nil { + manager.requests.log(accountID, "WARN", "远程操作 Cookie 写回跳过:Cookie 格式无效", "error", err) + return + } + lease, err := manager.pool.AcquireAccount(writebackCtx, accountID) + if err != nil { + manager.requests.log(accountID, "WARN", "远程操作 Cookie 写回跳过:获取账户租约失败", "error", err) + return + } + defer func() { _ = lease.Release() }() + // ReplaceCookies 从磁盘载入最新状态后只替换 Cookie,保留 localStorage 与认证扩展 + if err := lease.ReplaceCookies(cookies); err != nil { + manager.requests.log(accountID, "WARN", "远程操作 Cookie 写回失败", "error", err) + return + } + manager.requests.log(accountID, "INFO", "远程操作后的浏览器 Cookie 已写回", "cookies", len(cookies)) +} diff --git a/internal/camoufoxnative/bidi.go b/internal/camoufoxnative/bidi.go index 24772946..76e48cdc 100644 --- a/internal/camoufoxnative/bidi.go +++ b/internal/camoufoxnative/bidi.go @@ -41,8 +41,8 @@ type bidiClient struct { accessTokenStatus atomic.Int64 // denial 是页面导航到官网拒绝页时的原因,之后的命令立即以它返回 denial *AccessDenial - // listener 接收 BiDi 事件,在读取连接的协程中调用 - listener func(map[string]any) + // listeners 接收 BiDi 事件,在读取连接的协程中调用,由 mu 保护 + listeners []*eventListener // rhythm 是账户点击与粘贴的事件节奏,决定可信指针与键盘动作中的停顿 rhythm rhythm.Rhythm // loads 是正在载入官网页面的标签页记下的网络状态,键为标签页的 context @@ -230,20 +230,45 @@ func (client *bidiClient) fail(err error) { } } -// setListener 设置接收 BiDi 事件的函数 -func (client *bidiClient) setListener(listener func(map[string]any)) { +// eventListener 是一个 BiDi 事件订阅 +type eventListener struct { + fn func(map[string]any) +} + +// addListener 注册一个 BiDi 事件回调,返回取消注册的函数;回调在读取连接的协程中执行,需立即返回 +func (client *bidiClient) addListener(fn func(map[string]any)) func() { + listener := &eventListener{fn: fn} client.mu.Lock() - client.listener = listener + client.listeners = append(client.listeners, listener) client.mu.Unlock() + return func() { + client.mu.Lock() + client.listeners = slices.DeleteFunc(client.listeners, func(item *eventListener) bool { return item == listener }) + client.mu.Unlock() + } +} + +// Done 在 BiDi 连接读取失败时关闭 +func (client *bidiClient) Done() <-chan struct{} { + return client.done +} + +// Failure 返回连接读取失败的原因,连接仍正常时为 nil +func (client *bidiClient) Failure() error { + client.mu.Lock() + defer client.mu.Unlock() + return client.failure } -// observe 把事件交给 listener 与 script.message 通道,记下载入中标签页的目录 RPC、公共请求头与 WAA 图片请求,以及 GenerateAccessToken 的响应状态和跳转到地区不可用页的导航 +// observe 把事件交给各订阅者与 script.message 通道,记下载入中标签页的目录 RPC、公共请求头与 WAA 图片请求,以及 GenerateAccessToken 的响应状态和跳转到地区不可用页的导航 func (client *bidiClient) observe(message map[string]any) { client.mu.Lock() - listener := client.listener + listeners := slices.Clone(client.listeners) client.mu.Unlock() - if listener != nil && message["type"] == "event" { - listener(message) + if message["type"] == "event" { + for _, listener := range listeners { + listener.fn(message) + } } method, _ := message["method"].(string) params, _ := message["params"].(map[string]any) diff --git a/internal/camoufoxnative/liveview.go b/internal/camoufoxnative/liveview.go index 886b7b00..9e701150 100644 --- a/internal/camoufoxnative/liveview.go +++ b/internal/camoufoxnative/liveview.go @@ -6,8 +6,10 @@ import ( "encoding/base64" "encoding/json" "errors" + "fmt" "math" "slices" + "strings" "sync" "time" "unicode/utf8" @@ -15,8 +17,8 @@ import ( "github.com/gorilla/websocket" ) -// liveViewFrameInterval 为登录窗口截取画面的最短间隔,约每秒 10 帧 -const liveViewFrameInterval = 100 * time.Millisecond +// liveViewFrameInterval 为登录窗口截取画面的最短间隔,约每秒 20 帧 +const liveViewFrameInterval = 50 * time.Millisecond // liveViewWriteTimeout 为向登录窗口写出一条消息的最长等待 const liveViewWriteTimeout = 10 * time.Second @@ -70,6 +72,12 @@ type LiveView struct { viewer *liveViewer inputs []liveInput client *bidiClient + // closed 表示浏览器连接已断开,closedReason 是断开原因,由 mu 保护 + closed bool + closedReason string + // controlError 是最近一次导航或标签页控制命令的失败原因,controlErrorSeq 随其递增,由 mu 保护 + controlError string + controlErrorSeq int // inputReady 在有待转发的输入时唤醒输入协程 inputReady chan struct{} // capture 在登录窗口连接或页面对话框关闭时唤醒截图协程 @@ -112,11 +120,16 @@ type liveInput struct { Button int `json:"button"` DeltaX float64 `json:"dx"` DeltaY float64 `json:"dy"` + Delta int64 `json:"delta"` Key string `json:"key"` Text string `json:"text"` + URL string `json:"url"` Accept bool `json:"accept"` } +// liveControlTimeout 是地址栏导航、开关标签页等控制命令的最长时间 +const liveControlTimeout = 30 * time.Second + // liveBatch 是对同一页面执行的一次 input.performActions type liveBatch struct { context string @@ -184,7 +197,7 @@ func (view *LiveView) Serve(ctx context.Context, connection *websocket.Conn) err return errors.Join(err, <-received) } -// receive 读取登录窗口的输入与对话框选择,直到连接出错 +// receive 读取登录窗口的输入、导航控制与对话框选择,直到连接出错 func (view *LiveView) receive(connection *websocket.Conn) error { connection.SetReadLimit(liveViewReadLimit) for { @@ -192,14 +205,95 @@ func (view *LiveView) receive(connection *websocket.Conn) error { if err := connection.ReadJSON(&input); err != nil { return err } - if input.Type == "dialog" { + switch input.Type { + case "dialog": view.answerDialog(input.Accept, input.Text) continue + case "navigate", "reload", "history", "newTab", "closeTab": + if err := view.control(input); err != nil { + view.reportControlError(err) + } + continue } view.enqueue(input) } } +// reportControlError 记下控制命令错误并唤醒窗口连接推送 +func (view *LiveView) reportControlError(err error) { + if err == nil { + return + } + view.mu.Lock() + view.controlError = err.Error() + view.controlErrorSeq++ + view.mu.Unlock() + view.notify() +} + +// control 执行地址栏导航、历史进退、刷新与标签页开关命令,失败时返回错误 +func (view *LiveView) control(input liveInput) error { + view.mu.Lock() + client := view.client + contextID := input.Context + if contextID == "" { + contextID = view.activeContextLocked() + } + view.mu.Unlock() + if client == nil { + return errors.New("浏览器连接不可用") + } + if contextID == "" && input.Type != "newTab" { + return errors.New("没有可操作的标签页") + } + ctx, cancel := context.WithTimeout(context.Background(), liveControlTimeout) + defer cancel() + switch input.Type { + case "navigate": + if strings.TrimSpace(input.URL) == "" { + return nil + } + if _, err := client.command(ctx, "browsingContext.navigate", map[string]any{ + "context": contextID, "url": input.URL, "wait": "none", + }); err != nil { + return fmt.Errorf("打开网址失败: %w", err) + } + case "reload": + if _, err := client.command(ctx, "browsingContext.reload", map[string]any{ + "context": contextID, "ignoreCache": false, + }); err != nil { + return fmt.Errorf("刷新失败: %w", err) + } + case "history": + if _, err := client.command(ctx, "browsingContext.traverseHistory", map[string]any{ + "context": contextID, "delta": input.Delta, + }); err != nil { + return fmt.Errorf("历史导航失败: %w", err) + } + case "newTab": + result, err := client.command(ctx, "browsingContext.create", map[string]any{"type": "tab"}) + if err != nil { + return fmt.Errorf("新建标签页失败: %w", err) + } + newContext, _ := result["context"].(string) + if newContext == "" { + return errors.New("新建标签页失败:浏览器未返回标签页") + } + if url := strings.TrimSpace(input.URL); url != "" { + if _, err := client.command(ctx, "browsingContext.navigate", map[string]any{ + "context": newContext, "url": url, "wait": "none", + }); err != nil { + return fmt.Errorf("新标签页打开网址失败: %w", err) + } + } + case "closeTab": + if _, err := client.command(ctx, "browsingContext.close", map[string]any{"context": contextID}); err != nil { + return fmt.Errorf("关闭标签页失败: %w", err) + } + } + return nil +} + // enqueue 把输入排入转发队列,连续的指针移动只保留最后一次,同一位置连续的滚动合并 func (view *LiveView) enqueue(input liveInput) { view.mu.Lock() @@ -224,7 +318,7 @@ func (view *LiveView) enqueue(input liveInput) { // push 在状态变化时向登录窗口写出登录阶段、页面对话框与最新一帧画面 func (view *LiveView) push(ctx context.Context, connection *websocket.Conn, viewer *liveViewer) error { - status, frameSeq, dialogSeq := "", 0, 0 + status, frameSeq, dialogSeq, controlErrorSeq := "", 0, 0, 0 write := func(messageType int, data []byte) error { if err := connection.SetWriteDeadline(time.Now().Add(liveViewWriteTimeout)); err != nil { return err @@ -238,6 +332,7 @@ func (view *LiveView) push(ctx context.Context, connection *websocket.Conn, view } return write(websocket.TextMessage, encoded) } + closedSent := false for { select { case <-ctx.Done(): @@ -248,7 +343,15 @@ func (view *LiveView) push(ctx context.Context, connection *websocket.Conn, view } view.mu.Lock() currentStatus, frame, currentFrame, dialog, currentDialog := view.status, view.frame, view.frameSeq, view.dialog, view.dialogSeq + closed, closedReason := view.closed, view.closedReason + controlError, currentControlErrorSeq := view.controlError, view.controlErrorSeq view.mu.Unlock() + if closed && !closedSent { + if err := writeJSON(map[string]any{"type": "closed", "error": closedReason}); err != nil { + return err + } + closedSent = true + } if currentStatus != status { if err := writeJSON(map[string]any{"type": "status", "status": currentStatus}); err != nil { return err @@ -261,6 +364,12 @@ func (view *LiveView) push(ctx context.Context, connection *websocket.Conn, view } dialogSeq = currentDialog } + if currentControlErrorSeq != controlErrorSeq { + if err := writeJSON(map[string]any{"type": "control-error", "message": controlError}); err != nil { + return err + } + controlErrorSeq = currentControlErrorSeq + } if currentFrame != frameSeq && frame != nil { if err := writeJSON(frame); err != nil { return err @@ -332,14 +441,44 @@ func (view *LiveView) closeDialog() { signal(view.capture) } -// attach 把登录浏览器接到 LiveView:订阅顶层页面与对话框事件,开始截图与输入转发;返回的函数停止并等待这些协程 +// attach 把新启动的登录浏览器接到 LiveView,root 为它的初始顶层页面 func (view *LiveView) attach(ctx context.Context, client *bidiClient, root string) (func(), error) { + return view.attachWith(ctx, client, []string{root}) +} + +// attachTo 把运行中的浏览器接到 LiveView:读取现有顶层页面后开始截图与输入转发,返回的函数停止转发 +func (view *LiveView) attachTo(ctx context.Context, client *bidiClient) (func(), error) { + tree, err := client.command(ctx, "browsingContext.getTree", map[string]any{"maxDepth": 0}) + if err != nil { + return nil, fmt.Errorf("读取浏览器标签页: %w", err) + } + rawContexts, _ := tree["contexts"].([]any) + roots := make([]string, 0, len(rawContexts)) + for _, raw := range rawContexts { + if item, ok := raw.(map[string]any); ok { + if id, _ := item["context"].(string); id != "" { + roots = append(roots, id) + } + } + } + if len(roots) == 0 { + return nil, errors.New("浏览器没有打开的标签页") + } + return view.attachWith(ctx, client, roots) +} + +// attachWith 订阅顶层页面与对话框事件,开始截图与输入转发;返回的函数停止并等待这些协程 +func (view *LiveView) attachWith(ctx context.Context, client *bidiClient, roots []string) (func(), error) { view.mu.Lock() - view.contexts = []string{root} + view.contexts = append([]string(nil), roots...) view.client = client + view.closed = false + view.closedReason = "" view.mu.Unlock() - client.setListener(view.observe) - if _, err := client.command(ctx, "session.subscribe", map[string]any{"events": liveViewEvents}); err != nil { + unsubscribe := client.addListener(view.observe) + subscription := map[string]any{"events": liveViewEvents} + if _, err := client.command(ctx, "session.subscribe", subscription); err != nil { + unsubscribe() return nil, err } loopCtx, cancel := context.WithCancel(ctx) @@ -349,6 +488,13 @@ func (view *LiveView) attach(ctx context.Context, client *bidiClient, root strin return func() { cancel() group.Wait() + unsubscribe() + // 连接仍正常时取消订阅,连接已断开则命令失败可忽略 + if client.Failure() == nil { + unsubCtx, unsubCancel := context.WithTimeout(context.Background(), liveControlTimeout) + _, _ = client.command(unsubCtx, "session.unsubscribe", subscription) + unsubCancel() + } view.mu.Lock() view.client = nil view.inputs = nil @@ -367,12 +513,34 @@ func (view *LiveView) watched() bool { func (view *LiveView) activeContext() string { view.mu.Lock() defer view.mu.Unlock() + return view.activeContextLocked() +} + +// activeContextLocked 返回当前顶层页面,调用方需持有 view.mu +func (view *LiveView) activeContextLocked() string { if len(view.contexts) == 0 { return "" } return view.contexts[len(view.contexts)-1] } +// markClosed 记下浏览器连接断开的原因并唤醒窗口连接 +func (view *LiveView) markClosed(reason error) { + view.mu.Lock() + if view.closed { + view.mu.Unlock() + return + } + view.closed = true + if reason != nil { + view.closedReason = reason.Error() + } else { + view.closedReason = "浏览器连接已断开" + } + view.mu.Unlock() + view.notify() +} + // runFrames 在登录窗口连接期间按间隔截取当前顶层页面,画面变化时推给登录窗口 func (view *LiveView) runFrames(ctx context.Context, client *bidiClient) { for { @@ -380,14 +548,26 @@ func (view *LiveView) runFrames(ctx context.Context, client *bidiClient) { select { case <-ctx.Done(): return + case <-client.Done(): + view.markClosed(client.Failure()) + return case <-view.capture: } continue } started := time.Now() view.captureFrame(ctx, client) - if err := waitContext(ctx, liveViewFrameInterval-time.Since(started)); err != nil { + wait := liveViewFrameInterval - time.Since(started) + timer := time.NewTimer(max(wait, 0)) + select { + case <-ctx.Done(): + timer.Stop() return + case <-client.Done(): + timer.Stop() + view.markClosed(client.Failure()) + return + case <-timer.C: } } } @@ -451,6 +631,8 @@ func (view *LiveView) runInputs(ctx context.Context, client *bidiClient) { select { case <-ctx.Done(): return + case <-client.Done(): + return case <-view.inputReady: } view.mu.Lock() diff --git a/internal/camoufoxnative/worker.go b/internal/camoufoxnative/worker.go index 8c2c2ffe..4c2026ae 100644 --- a/internal/camoufoxnative/worker.go +++ b/internal/camoufoxnative/worker.go @@ -86,6 +86,8 @@ type Worker struct { idle *time.Timer // settle 在 Worker 就绪 readyMinimizeDelay 后发出一次 memory-pressure settle *time.Timer + // liveView 是当前挂载的远程操作窗口,同一 Worker 同时只允许一个 + liveView *LiveView } // tabUse 是一个标签页中进行中的受保护请求数,retired 表示该标签页已被重新载入的页面替换 diff --git a/internal/camoufoxnative/worker_liveview.go b/internal/camoufoxnative/worker_liveview.go new file mode 100644 index 00000000..1067eb5e --- /dev/null +++ b/internal/camoufoxnative/worker_liveview.go @@ -0,0 +1,54 @@ +package camoufoxnative + +import ( + "context" + "errors" +) + +// ErrLiveViewAttached 表示账户浏览器已挂载远程操作窗口 +var ErrLiveViewAttached = errors.New("账户浏览器已在远程操作中") + +// LiveViewAvailable 返回当前 Worker 挂载远程操作窗口的可用性与原因 +func (worker *Worker) LiveViewAvailable() (bool, string) { + worker.mu.Lock() + defer worker.mu.Unlock() + if worker.closed { + return false, "Camoufox runtime 已关闭" + } + if worker.liveView != nil { + return false, ErrLiveViewAttached.Error() + } + return true, "" +} + +// AttachLiveView 把远程操作窗口接到运行中的 Worker,返回停止画面与输入转发的函数;同一 Worker 同时只允许一个窗口 +func (worker *Worker) AttachLiveView(ctx context.Context, view *LiveView) (func(), error) { + worker.mu.Lock() + if worker.closed { + worker.mu.Unlock() + return nil, errors.New("Camoufox runtime 已关闭") + } + if worker.liveView != nil { + worker.mu.Unlock() + return nil, ErrLiveViewAttached + } + client := worker.client + worker.liveView = view + worker.mu.Unlock() + + stop, err := view.attachTo(ctx, client) + if err != nil { + worker.mu.Lock() + worker.liveView = nil + worker.mu.Unlock() + return nil, err + } + return func() { + stop() + worker.mu.Lock() + if worker.liveView == view { + worker.liveView = nil + } + worker.mu.Unlock() + }, nil +} diff --git a/internal/chromeauth/bidi.go b/internal/chromeauth/bidi.go new file mode 100644 index 00000000..b8352e98 --- /dev/null +++ b/internal/chromeauth/bidi.go @@ -0,0 +1,231 @@ +package chromeauth + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/url" + "strings" + "time" + + "github.com/gorilla/websocket" +) + +const ( + // bidiHandshakeTimeout 是 BiDi WebSocket 握手的最长时间 + bidiHandshakeTimeout = 15 * time.Second + // bidiSessionEndTimeout 是关闭 BiDi 会话的最长时间 + bidiSessionEndTimeout = 3 * time.Second +) + +// bidiProductFallback 是 BiDi 会话没有回报产品名时显示的浏览器名 +const bidiProductFallback = "Firefox (WebDriver BiDi)" + +// bidiCookie 是 WebDriver BiDi storage.getCookies 返回的 Cookie +type bidiCookie struct { + Name string `json:"name"` + // Value 是 BytesRemoteValue,type 为 string 时 Value 为明文,为 base64 时是标准 base64 + Value struct { + Type string `json:"type"` + Value string `json:"value"` + } `json:"value"` + Domain string `json:"domain"` + Path string `json:"path"` + HTTPOnly bool `json:"httpOnly"` + Secure bool `json:"secure"` + SameSite string `json:"sameSite"` + Expiry *float64 `json:"expiry"` + PartitionKey json.RawMessage `json:"partitionKey"` +} + +// browserCookieExport 是 aistudio.ParseCookieText 接受的浏览器扩展导出 Cookie 形状 +type browserCookieExport struct { + Name string `json:"name"` + Value string `json:"value"` + Domain string `json:"domain"` + Path string `json:"path"` + Expires float64 `json:"expires,omitempty"` + Session bool `json:"session,omitempty"` + HTTPOnly bool `json:"httpOnly"` + Secure bool `json:"secure"` + SameSite string `json:"sameSite,omitempty"` +} + +// readBiDiBrowser 经 Firefox WebDriver BiDi 读取浏览器全部未分区 Cookie,返回产品名与扩展导出形状的 Cookie JSON +func readBiDiBrowser(ctx context.Context, address string) (BrowserCookies, error) { + endpoint, err := bidiSessionEndpoint(address) + if err != nil { + return BrowserCookies{}, err + } + dialer := websocket.Dialer{HandshakeTimeout: bidiHandshakeTimeout} + conn, _, err := dialer.DialContext(ctx, endpoint, nil) + if err != nil { + return BrowserCookies{}, fmt.Errorf("连接 Firefox WebDriver BiDi 调试地址: %w", err) + } + defer conn.Close() + stop := context.AfterFunc(ctx, func() { conn.Close() }) + defer stop() + client := &bidiSession{conn: conn} + + session, err := client.call(ctx, "session.new", map[string]any{"capabilities": map[string]any{}}) + if err != nil { + return BrowserCookies{}, fmt.Errorf("创建 WebDriver BiDi 会话: %w", err) + } + var info struct { + SessionID string `json:"sessionId"` + Capabilities struct { + BrowserName string `json:"browserName"` + BrowserVersion string `json:"browserVersion"` + } `json:"capabilities"` + } + if err := json.Unmarshal(session, &info); err != nil || info.SessionID == "" { + return BrowserCookies{}, errors.New("WebDriver BiDi 会话没有返回 sessionId") + } + defer func() { + // 用脱离调用方取消的上下文结束会话,避免浏览器侧残留会话;失败时连接关闭也会让浏览器自行回收 + endCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), bidiSessionEndTimeout) + defer cancel() + _, _ = client.call(endCtx, "session.end", map[string]any{"sessionId": info.SessionID}) + }() + + result, err := client.call(ctx, "storage.getCookies", map[string]any{}) + if err != nil { + return BrowserCookies{}, fmt.Errorf("经 WebDriver BiDi 读取浏览器 Cookie: %w", err) + } + var stored struct { + Cookies []bidiCookie `json:"cookies"` + } + if err := json.Unmarshal(result, &stored); err != nil { + return BrowserCookies{}, fmt.Errorf("解析 WebDriver BiDi Cookie: %w", err) + } + cookies, err := biDiCookiesToExport(stored.Cookies) + if err != nil { + return BrowserCookies{}, err + } + data, err := json.Marshal(cookies) + if err != nil { + return BrowserCookies{}, fmt.Errorf("编码浏览器 Cookie: %w", err) + } + return BrowserCookies{ + Product: bidiProductName(info.Capabilities.BrowserName, info.Capabilities.BrowserVersion), + Cookies: string(data), + }, nil +} + +// bidiSession 在一条 WebDriver BiDi WebSocket 上依次发送命令 +type bidiSession struct { + conn *websocket.Conn + id int +} + +// call 发送一条 BiDi 命令并等待同一 id 的响应,事件消息没有 id,读取后跳过 +func (session *bidiSession) call(ctx context.Context, method string, params map[string]any) (json.RawMessage, error) { + session.id++ + if err := session.conn.WriteJSON(map[string]any{"id": session.id, "method": method, "params": params}); err != nil { + return nil, err + } + for { + var response struct { + ID int `json:"id"` + Result json.RawMessage `json:"result"` + Error string `json:"error"` + Message string `json:"message"` + } + if err := session.conn.ReadJSON(&response); err != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + return nil, err + } + if response.ID != session.id { + continue + } + if response.Error != "" { + return nil, fmt.Errorf("%s: %s", response.Error, response.Message) + } + return response.Result, nil + } +} + +// bidiSessionEndpoint 把 host:port、HTTP 调试地址或 BiDi WebSocket 地址解析为 /session 的 WebSocket 地址 +func bidiSessionEndpoint(address string) (string, error) { + address = strings.TrimSpace(address) + if strings.HasPrefix(address, "ws://") || strings.HasPrefix(address, "wss://") { + parsed, err := url.Parse(address) + if err != nil || parsed.Host == "" { + return "", fmt.Errorf("浏览器调试地址无效,例如 127.0.0.1:9222") + } + if parsed.Path == "" || parsed.Path == "/" { + parsed.Path = "/session" + } + return parsed.String(), nil + } + if !strings.Contains(address, "://") { + address = "http://" + address + } + parsed, err := url.Parse(address) + if err != nil || parsed.Host == "" || parsed.Scheme != "http" && parsed.Scheme != "https" { + return "", fmt.Errorf("浏览器调试地址无效,例如 127.0.0.1:9222") + } + scheme := "ws" + if parsed.Scheme == "https" { + scheme = "wss" + } + return scheme + "://" + parsed.Host + "/session", nil +} + +// biDiCookiesToExport 把 BiDi Cookie 转为扩展导出形状,跳过分区 Cookie 与缺少名称或域的条目 +func biDiCookiesToExport(items []bidiCookie) ([]browserCookieExport, error) { + cookies := make([]browserCookieExport, 0, len(items)) + for _, item := range items { + if len(item.PartitionKey) > 0 && string(item.PartitionKey) != "null" { + continue + } + if item.Name == "" || item.Domain == "" { + continue + } + value := item.Value.Value + if item.Value.Type == "base64" { + decoded, err := base64.StdEncoding.DecodeString(value) + if err != nil { + return nil, fmt.Errorf("解码 WebDriver BiDi Cookie %s 的 base64 值: %w", item.Name, err) + } + value = string(decoded) + } + export := browserCookieExport{ + Name: item.Name, Value: value, Domain: item.Domain, Path: item.Path, + HTTPOnly: item.HTTPOnly, Secure: item.Secure, SameSite: item.SameSite, + } + if export.Path == "" { + export.Path = "/" + } + if item.Expiry == nil { + export.Session = true + } else { + export.Expires = *item.Expiry + } + cookies = append(cookies, export) + } + return cookies, nil +} + +// bidiProductName 把会话回报的浏览器名与版本拼成产品名,缺省时返回固定的 Firefox BiDi 名称 +func bidiProductName(name, version string) string { + name = strings.TrimSpace(name) + version = strings.TrimSpace(version) + if name != "" { + if first := name[0]; first >= 'a' && first <= 'z' { + name = string(first-32) + name[1:] + } + if version != "" { + return name + "/" + version + } + return name + } + if version != "" { + return bidiProductFallback + "/" + version + } + return bidiProductFallback +} diff --git a/internal/chromeauth/bidi_test.go b/internal/chromeauth/bidi_test.go new file mode 100644 index 00000000..9aa30c5d --- /dev/null +++ b/internal/chromeauth/bidi_test.go @@ -0,0 +1,438 @@ +package chromeauth + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Mag1cFall/AIStudio2API/internal/aistudio" + "github.com/gorilla/websocket" +) + +// biDiGoogleCookies 是满足 aistudio.ParseCookieText 登录 Cookie 校验的 BiDi Cookie 集合 +func biDiGoogleCookies() []map[string]any { + return []map[string]any{ + { + "name": "__Secure-1PSID", "value": map[string]string{"type": "string", "value": "sid-value"}, + "domain": ".google.com", "path": "/", "secure": true, "httpOnly": true, "sameSite": "none", "expiry": 1900000000.0, + }, + { + "name": "SAPISID", "value": map[string]string{"type": "string", "value": "sapisid-value"}, + "domain": ".google.com", "path": "/", "secure": true, "httpOnly": true, "sameSite": "lax", + }, + { + "name": "__Secure-1PAPISID", "value": map[string]string{"type": "string", "value": "papisid1"}, + "domain": ".google.com", "path": "/", "secure": true, "httpOnly": true, "sameSite": "none", "expiry": 1900000000.0, + }, + { + "name": "__Secure-3PAPISID", "value": map[string]string{"type": "string", "value": "papisid3"}, + "domain": ".google.com", "path": "/", "secure": true, "httpOnly": true, "sameSite": "none", "expiry": 1900000000.0, + }, + { + // base64 编码的 Cookie 值应被解码 + "name": "BiDiBase64", "value": map[string]string{"type": "base64", "value": "aGVsbG8="}, + "domain": ".google.com", "path": "/", "secure": true, + }, + { + // 分区 Cookie 应被过滤 + "name": "PartitionedCookie", "value": map[string]string{"type": "string", "value": "partitioned"}, + "domain": ".google.com", "path": "/", "secure": true, + "partitionKey": map[string]any{"userContext": "default", "sourceOrigin": "https://aistudio.google.com"}, + }, + { + // 非 google.com 域的 Cookie 在 ParseCookieText 中被过滤,但 chromeauth 层仍原样返回 + "name": "OtherSite", "value": map[string]string{"type": "string", "value": "other"}, + "domain": "example.com", "path": "/", + }, + } +} + +// newBiDiRemoteServer 启动模拟远程调试浏览器:mode 为 bidi-only 时 /json/version 返回 404, +// 为 firefox-both 时返回带 Firefox 产品名的 CDP 信息,为 chrome 时返回 Chrome 的 CDP 信息 +func newBiDiRemoteServer(t *testing.T, mode string) (*httptest.Server, <-chan string) { + t.Helper() + upgrader := websocket.Upgrader{} + ended := make(chan string, 1) + mux := http.NewServeMux() + mux.HandleFunc("/json/version", func(w http.ResponseWriter, _ *http.Request) { + switch mode { + case "bidi-only": + http.NotFound(w, nil) + case "firefox-both": + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{ + "Browser": "Firefox/128.0.2", + "webSocketDebuggerUrl": "ws://invalid-cdp.example.invalid/devtools/browser/firefox", + }) + default: + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{ + "Browser": "Chrome/131.0.0.0", + "webSocketDebuggerUrl": "", + }) + } + }) + mux.HandleFunc("/session", func(w http.ResponseWriter, r *http.Request) { + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + t.Errorf("升级 BiDi WebSocket 失败: %v", err) + return + } + defer conn.Close() + for { + var message struct { + ID int `json:"id"` + Method string `json:"method"` + Params map[string]any `json:"params"` + } + if err := conn.ReadJSON(&message); err != nil { + return + } + switch message.Method { + case "session.new": + _ = conn.WriteJSON(map[string]any{ + "id": message.ID, + "result": map[string]any{ + "sessionId": "test-session", + "capabilities": map[string]any{ + "browserName": "firefox", "browserVersion": "128.0.2", + }, + }, + }) + case "storage.getCookies": + _ = conn.WriteJSON(map[string]any{ + "id": message.ID, + "result": map[string]any{"cookies": biDiGoogleCookies()}, + }) + case "session.end": + ended <- message.Params["sessionId"].(string) + _ = conn.WriteJSON(map[string]any{"id": message.ID, "result": map[string]any{}}) + return + default: + _ = conn.WriteJSON(map[string]any{ + "id": message.ID, "error": "unknown command", "message": message.Method, + }) + return + } + } + }) + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + return server, ended +} + +// newCDPRemoteServer 启动只说 CDP 的模拟 Chromium 调试端口 +func newCDPRemoteServer(t *testing.T) *httptest.Server { + t.Helper() + upgrader := websocket.Upgrader{} + mux := http.NewServeMux() + mux.HandleFunc("/devtools/browser/test", func(w http.ResponseWriter, r *http.Request) { + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + t.Errorf("升级 CDP WebSocket 失败: %v", err) + return + } + defer conn.Close() + for { + var message struct { + ID int `json:"id"` + Method string `json:"method"` + } + if err := conn.ReadJSON(&message); err != nil { + return + } + if message.Method != "Storage.getCookies" { + _ = conn.WriteJSON(map[string]any{"id": message.ID, "error": map[string]string{"message": "unknown method"}}) + return + } + _ = conn.WriteJSON(map[string]any{ + "id": message.ID, + "result": map[string]any{"cookies": []map[string]any{ + { + "name": "__Secure-1PSID", "value": "sid-value", "domain": ".google.com", + "path": "/", "expires": 1900000000.0, "httpOnly": true, "secure": true, "sameSite": "None", + }, + { + "name": "SAPISID", "value": "sapisid-value", "domain": ".google.com", + "path": "/", "session": true, "httpOnly": true, "secure": true, "sameSite": "Lax", + }, + { + "name": "__Secure-1PAPISID", "value": "papisid1", "domain": ".google.com", + "path": "/", "expires": 1900000000.0, "httpOnly": true, "secure": true, + }, + { + "name": "__Secure-3PAPISID", "value": "papisid3", "domain": ".google.com", + "path": "/", "expires": 1900000000.0, "httpOnly": true, "secure": true, + }, + { + "name": "PartitionedCookie", "value": "partitioned", "domain": ".google.com", + "path": "/", "secure": true, "partitionKey": "https://aistudio.google.com", + }, + }}, + }) + } + }) + // /json/version 回报指向当前测试服务器的浏览器级 WebSocket + var server *httptest.Server + mux.HandleFunc("/json/version", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{ + "Browser": "Chrome/131.0.0.0", + "webSocketDebuggerUrl": "ws://" + strings.TrimPrefix(server.URL, "http://") + "/devtools/browser/test", + }) + }) + server = httptest.NewServer(mux) + t.Cleanup(server.Close) + return server +} + +func TestReadBrowserCookiesBiDiFallback(t *testing.T) { + server, ended := newBiDiRemoteServer(t, "bidi-only") + address := strings.TrimPrefix(server.URL, "http://") + + browser, err := ReadBrowserCookies(context.Background(), address) + if err != nil { + t.Fatalf("BiDi 读取失败: %v", err) + } + if browser.Product != "Firefox/128.0.2" { + t.Fatalf("产品名 = %q,期望 Firefox/128.0.2", browser.Product) + } + if sessionID := <-ended; sessionID != "test-session" { + t.Fatalf("会话结束参数 = %q,期望 test-session", sessionID) + } + state := assertExportedCookieState(t, browser.Cookies) + // base64 解码只发生在 BiDi 路径,CDP 的 Storage.getCookies 返回明文值 + for _, cookie := range state.Cookies { + if cookie.Name == "BiDiBase64" { + if cookie.Value != "hello" { + t.Fatalf("base64 Cookie 值 = %q,期望 hello", cookie.Value) + } + return + } + } + t.Fatal("缺少解码后的 BiDiBase64 Cookie") +} + +func TestReadBrowserCookiesFirefoxWithBothProtocols(t *testing.T) { + server, _ := newBiDiRemoteServer(t, "firefox-both") + address := strings.TrimPrefix(server.URL, "http://") + + browser, err := ReadBrowserCookies(context.Background(), address) + if err != nil { + t.Fatalf("双协议 Firefox 读取失败: %v", err) + } + if browser.Product != "Firefox/128.0.2" { + t.Fatalf("产品名 = %q,期望 Firefox/128.0.2", browser.Product) + } +} + +func TestReadBrowserCookiesDirectBiDiURL(t *testing.T) { + server, ended := newBiDiRemoteServer(t, "bidi-only") + address := "ws://" + strings.TrimPrefix(server.URL, "http://") + "/session" + + browser, err := ReadBrowserCookies(context.Background(), address) + if err != nil { + t.Fatalf("直连 BiDi WebSocket 失败: %v", err) + } + if browser.Product != "Firefox/128.0.2" { + t.Fatalf("产品名 = %q,期望 Firefox/128.0.2", browser.Product) + } + if sessionID := <-ended; sessionID != "test-session" { + t.Fatalf("会话结束参数 = %q,期望 test-session", sessionID) + } +} + +func TestReadBrowserCookiesCDP(t *testing.T) { + server := newCDPRemoteServer(t) + address := strings.TrimPrefix(server.URL, "http://") + + browser, err := ReadBrowserCookies(context.Background(), address) + if err != nil { + t.Fatalf("CDP 读取失败: %v", err) + } + if browser.Product != "Chrome/131.0.0.0" { + t.Fatalf("产品名 = %q,期望 Chrome/131.0.0.0", browser.Product) + } + var cookies []map[string]any + if err := json.Unmarshal([]byte(browser.Cookies), &cookies); err != nil { + t.Fatalf("Cookie JSON 无效: %v", err) + } + for _, cookie := range cookies { + if cookie["name"] == "PartitionedCookie" { + t.Fatal("分区 Cookie 没有被过滤") + } + } + assertExportedCookieState(t, browser.Cookies) +} + +func TestReadBrowserCookiesUnreachable(t *testing.T) { + listener := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + address := strings.TrimPrefix(listener.URL, "http://") + listener.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := ReadBrowserCookies(ctx, address); err == nil { + t.Fatal("不可达的调试地址应当返回错误") + } else if !strings.Contains(err.Error(), "连接浏览器调试地址") { + t.Fatalf("错误 = %q,期望包含连接失败说明", err.Error()) + } +} + +// assertExportedCookieState 验证 Cookie 文本可被存储状态解析、登录 Cookie 齐全且分区 Cookie 被过滤,返回解析后的状态 +func assertExportedCookieState(t *testing.T, text string) aistudio.StorageState { + t.Helper() + state, err := aistudio.ParseCookieText(text) + if err != nil { + t.Fatalf("Cookie 解析为存储状态失败: %v", err) + } + names := make(map[string]string, len(state.Cookies)) + for _, cookie := range state.Cookies { + names[cookie.Name] = cookie.Value + } + for _, required := range []string{"__Secure-1PSID", "SAPISID", "__Secure-1PAPISID", "__Secure-3PAPISID"} { + if _, ok := names[required]; !ok { + t.Fatalf("缺少必需 Cookie %s,实际有 %v", required, names) + } + } + if _, ok := names["PartitionedCookie"]; ok { + t.Fatal("分区 Cookie 不应进入存储状态") + } + return state +} + +func TestBiDiCookiesToExport(t *testing.T) { + expiry := 1900000000.0 + items := []bidiCookie{ + { + Name: "Persistent", Domain: ".google.com", Path: "/", Secure: true, SameSite: "lax", Expiry: &expiry, + Value: struct { + Type string `json:"type"` + Value string `json:"value"` + }{Type: "string", Value: "persisted"}, + }, + { + Name: "Session", Domain: ".google.com", + Value: struct { + Type string `json:"type"` + Value string `json:"value"` + }{Type: "string", Value: "session"}, + }, + { + Name: "Encoded", Domain: ".google.com", + Value: struct { + Type string `json:"type"` + Value string `json:"value"` + }{Type: "base64", Value: "aGVsbG8="}, + }, + { + Name: "Partitioned", Domain: ".google.com", + Value: struct { + Type string `json:"type"` + Value string `json:"value"` + }{Type: "string", Value: "x"}, + PartitionKey: json.RawMessage(`{"userContext":"default"}`), + }, + { + Name: "NullPartition", Domain: ".google.com", + Value: struct { + Type string `json:"type"` + Value string `json:"value"` + }{Type: "string", Value: "y"}, + PartitionKey: json.RawMessage("null"), + }, + {Name: "", Domain: ".google.com"}, + } + cookies, err := biDiCookiesToExport(items) + if err != nil { + t.Fatalf("转换 BiDi Cookie 失败: %v", err) + } + names := make(map[string]browserCookieExport, len(cookies)) + for _, cookie := range cookies { + names[cookie.Name] = cookie + } + if len(cookies) != 4 { + t.Fatalf("保留 Cookie 数 = %d,期望 4", len(cookies)) + } + if names["Persistent"].Expires != expiry || names["Persistent"].Session { + t.Fatal("持久 Cookie 的过期时间转换错误") + } + if names["Session"].Expires != 0 || !names["Session"].Session { + t.Fatal("会话 Cookie 应标记 session 且没有过期时间") + } + if names["Session"].Path != "/" { + t.Fatal("空路径应补为 /") + } + if names["Encoded"].Value != "hello" { + t.Fatalf("base64 值 = %q,期望 hello", names["Encoded"].Value) + } + if names["NullPartition"].SameSite != "" { + t.Fatal("SameSite 缺省应为空字符串") + } + + invalid := []bidiCookie{{ + Name: "BadBase64", Domain: ".google.com", + Value: struct { + Type string `json:"type"` + Value string `json:"value"` + }{Type: "base64", Value: "not-base64!"}, + }} + if _, err := biDiCookiesToExport(invalid); err == nil { + t.Fatal("非法 base64 应当返回错误") + } +} + +func TestBidiSessionEndpoint(t *testing.T) { + cases := []struct { + name string + input string + expect string + wantErr bool + }{ + {name: "主机端口", input: "127.0.0.1:9222", expect: "ws://127.0.0.1:9222/session"}, + {name: "HTTP 地址", input: "http://127.0.0.1:9222", expect: "ws://127.0.0.1:9222/session"}, + {name: "HTTPS 地址", input: "https://127.0.0.1:9222", expect: "wss://127.0.0.1:9222/session"}, + {name: "WS 根路径补 session", input: "ws://127.0.0.1:9222", expect: "ws://127.0.0.1:9222/session"}, + {name: "WS session 保持不变", input: "ws://127.0.0.1:9222/session", expect: "ws://127.0.0.1:9222/session"}, + {name: "无效地址", input: "bad url", wantErr: true}, + {name: "空地址", input: "", wantErr: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + endpoint, err := bidiSessionEndpoint(tc.input) + if tc.wantErr { + if err == nil { + t.Fatalf("输入 %q 应当返回错误", tc.input) + } + return + } + if err != nil { + t.Fatalf("输入 %q 返回错误: %v", tc.input, err) + } + if endpoint != tc.expect { + t.Fatalf("端点 = %q,期望 %q", endpoint, tc.expect) + } + }) + } +} + +func TestBidiProductName(t *testing.T) { + cases := []struct { + name, version, expect string + }{ + {name: "firefox", version: "128.0.2", expect: "Firefox/128.0.2"}, + {name: "camoufox", version: "", expect: "Camoufox"}, + {name: "", version: "128", expect: bidiProductFallback + "/128"}, + {name: "", version: "", expect: bidiProductFallback}, + {name: "Firefox", version: "1", expect: "Firefox/1"}, + } + for _, tc := range cases { + if got := bidiProductName(tc.name, tc.version); got != tc.expect { + t.Fatalf("bidiProductName(%q, %q) = %q,期望 %q", tc.name, tc.version, got, tc.expect) + } + } +} diff --git a/internal/chromeauth/cdp.go b/internal/chromeauth/cdp.go index 546d4b29..36c413be 100644 --- a/internal/chromeauth/cdp.go +++ b/internal/chromeauth/cdp.go @@ -13,20 +13,46 @@ import ( "github.com/gorilla/websocket" ) -// CDPBrowser 是经远程调试地址读取的浏览器 Cookie -type CDPBrowser struct { +// BrowserCookies 是经远程调试地址读取的浏览器产品名与全部未分区 Cookie,Cookie 为 JSON 数组文本 +type BrowserCookies struct { + Product string Cookies string } -// ReadCDPBrowser 经 Chromium 远程调试地址读取浏览器全部未分区 Cookie -func ReadCDPBrowser(ctx context.Context, address string) (CDPBrowser, error) { - endpoint, err := cdpBrowserEndpoint(ctx, address) - if err != nil { - return CDPBrowser{}, err +// ReadBrowserCookies 经远程调试地址读取浏览器 Cookie:Chromium 走 CDP,Firefox 内核浏览器走 WebDriver BiDi +func ReadBrowserCookies(ctx context.Context, address string) (BrowserCookies, error) { + address = strings.TrimSpace(address) + if strings.HasPrefix(address, "ws://") || strings.HasPrefix(address, "wss://") { + // /session 是 WebDriver BiDi 的 WebSocket 路径,其余按浏览器级 CDP WebSocket 处理 + if parsed, err := url.Parse(address); err == nil && strings.TrimSuffix(parsed.Path, "/") == "/session" { + return readBiDiBrowser(ctx, address) + } + return readCDPBrowser(ctx, address, "") } + version, status, err := probeCDPVersion(ctx, address) + if err == nil { + // Firefox 的 CDP 不提供 Storage 域,统一使用 WebDriver BiDi + if strings.Contains(strings.ToLower(version.Browser), "firefox") { + return readBiDiBrowser(ctx, address) + } + return readCDPBrowser(ctx, version.WebSocketDebuggerURL, version.Browser) + } + if status == 0 { + return BrowserCookies{}, err + } + // HTTP 有响应但没有 CDP 调试信息时,Firefox 内核浏览器改用 WebDriver BiDi + bidi, bidiErr := readBiDiBrowser(ctx, address) + if bidiErr != nil { + return BrowserCookies{}, fmt.Errorf("浏览器调试地址没有返回调试信息: HTTP %d;WebDriver BiDi 读取失败: %w", status, bidiErr) + } + return bidi, nil +} + +// readCDPBrowser 经浏览器级 CDP WebSocket 读取浏览器全部未分区 Cookie +func readCDPBrowser(ctx context.Context, endpoint, product string) (BrowserCookies, error) { conn, _, err := websocket.DefaultDialer.DialContext(ctx, endpoint, nil) if err != nil { - return CDPBrowser{}, fmt.Errorf("连接浏览器调试地址: %w", err) + return BrowserCookies{}, fmt.Errorf("连接浏览器调试地址: %w", err) } defer conn.Close() stop := context.AfterFunc(ctx, func() { conn.Close() }) @@ -35,8 +61,8 @@ func ReadCDPBrowser(ctx context.Context, address string) (CDPBrowser, error) { var stored struct { Cookies []map[string]any `json:"cookies"` } - if err := session.call(ctx, "Storage.getCookies", nil, "", &stored); err != nil { - return CDPBrowser{}, fmt.Errorf("读取浏览器 Cookie: %w", err) + if err := session.call(ctx, "Storage.getCookies", nil, &stored); err != nil { + return BrowserCookies{}, fmt.Errorf("读取浏览器 Cookie: %w", err) } cookies := make([]map[string]any, 0, len(stored.Cookies)) for _, cookie := range stored.Cookies { @@ -46,9 +72,9 @@ func ReadCDPBrowser(ctx context.Context, address string) (CDPBrowser, error) { } data, err := json.Marshal(cookies) if err != nil { - return CDPBrowser{}, fmt.Errorf("编码浏览器 Cookie: %w", err) + return BrowserCookies{}, fmt.Errorf("编码浏览器 Cookie: %w", err) } - return CDPBrowser{Cookies: string(data)}, nil + return BrowserCookies{Product: product, Cookies: string(data)}, nil } // cdpSession 在一条浏览器级 CDP 连接上依次发送命令 @@ -57,16 +83,13 @@ type cdpSession struct { id int } -// call 发送一条命令并把同一 id 的结果解码到 result,sessionID 非空时发往已附加的页面 -func (session *cdpSession) call(ctx context.Context, method string, params any, sessionID string, result any) error { +// call 发送一条命令并把同一 id 的结果解码到 result +func (session *cdpSession) call(ctx context.Context, method string, params any, result any) error { session.id++ message := map[string]any{"id": session.id, "method": method} if params != nil { message["params"] = params } - if sessionID != "" { - message["sessionId"] = sessionID - } if err := session.conn.WriteJSON(message); err != nil { return err } @@ -100,42 +123,30 @@ type cdpVersion struct { WebSocketDebuggerURL string `json:"webSocketDebuggerUrl"` } -// cdpBrowserEndpoint 把 host:port、HTTP 调试地址或浏览器 WebSocket 地址解析为浏览器级 WebSocket 地址 -func cdpBrowserEndpoint(ctx context.Context, address string) (string, error) { - address = strings.TrimSpace(address) - if strings.HasPrefix(address, "ws://") || strings.HasPrefix(address, "wss://") { - return address, nil - } - version, err := debugVersion(ctx, address) - if err != nil { - return "", err - } - return version.WebSocketDebuggerURL, nil -} - -// debugVersion 读取 host:port 或 HTTP 调试地址的 /json/version -func debugVersion(ctx context.Context, address string) (cdpVersion, error) { +// probeCDPVersion 读取 host:port 或 HTTP 调试地址的 /json/version。 +// 传输层失败时返回的 status 为 0;收到 HTTP 响应但不是 CDP 调试信息时 status 为响应状态码 +func probeCDPVersion(ctx context.Context, address string) (cdpVersion, int, error) { address = strings.TrimSpace(address) if !strings.Contains(address, "://") { address = "http://" + address } parsed, err := url.Parse(address) if err != nil || parsed.Host == "" || parsed.Scheme != "http" && parsed.Scheme != "https" { - return cdpVersion{}, fmt.Errorf("浏览器调试地址无效,例如 127.0.0.1:9222") + return cdpVersion{}, 0, fmt.Errorf("浏览器调试地址无效,例如 127.0.0.1:9222") } request, _ := http.NewRequestWithContext(ctx, http.MethodGet, parsed.Scheme+"://"+parsed.Host+"/json/version", nil) response, err := http.DefaultClient.Do(request) if err != nil { - return cdpVersion{}, fmt.Errorf("连接浏览器调试地址: %w", err) + return cdpVersion{}, 0, fmt.Errorf("连接浏览器调试地址: %w", err) } defer response.Body.Close() body, err := io.ReadAll(io.LimitReader(response.Body, 1<<20)) if err != nil { - return cdpVersion{}, fmt.Errorf("读取浏览器调试信息: %w", err) + return cdpVersion{}, response.StatusCode, fmt.Errorf("读取浏览器调试信息: %w", err) } var version cdpVersion if response.StatusCode != http.StatusOK || json.Unmarshal(body, &version) != nil || version.WebSocketDebuggerURL == "" { - return cdpVersion{}, fmt.Errorf("浏览器调试地址没有返回调试信息: HTTP %d", response.StatusCode) + return cdpVersion{}, response.StatusCode, fmt.Errorf("浏览器调试地址没有返回调试信息: HTTP %d", response.StatusCode) } - return version, nil + return version, response.StatusCode, nil } diff --git a/internal/chromeauth/debugging.go b/internal/chromeauth/debugging.go index a4b14998..89d3ec65 100644 --- a/internal/chromeauth/debugging.go +++ b/internal/chromeauth/debugging.go @@ -12,7 +12,7 @@ import ( "github.com/shirou/gopsutil/v4/process" ) -// DebugAddresses 从本机进程命令行找出开启远程调试端口的 Chromium 浏览器,返回去重排序后的 127.0.0.1:端口 +// DebugAddresses 从本机进程命令行找出开启远程调试端口的浏览器(Chromium 与 Firefox 内核),返回去重排序后的 127.0.0.1:端口 func DebugAddresses(ctx context.Context) ([]string, error) { processes, err := process.ProcessesWithContext(ctx) if err != nil { @@ -56,12 +56,3 @@ func debugAddress(args []string) string { } return "127.0.0.1:" + port } - -// DebugBrowserName 返回远程调试地址对应浏览器的产品名与版本 -func DebugBrowserName(ctx context.Context, address string) (string, error) { - version, err := debugVersion(ctx, address) - if err != nil { - return "", err - } - return version.Browser, nil -} diff --git a/internal/i18n/messages/de.json b/internal/i18n/messages/de.json index 6388b408..2ccb2824 100644 --- a/internal/i18n/messages/de.json +++ b/internal/i18n/messages/de.json @@ -1219,6 +1219,13 @@ "远程实例账户页生成的配对令牌,省略时从标准输入读取": "Auf der Kontoseite der Remote-Instanz generiertes Kopplungstoken; wenn weggelassen, wird von stdin gelesen", "连接 Camoufox BiDi: %w": "Verbindung zu Camoufox BiDi: {0}", "连接 WebDriver BiDi": "Verbindung zu WebDriver BiDi", + "连接 Firefox WebDriver BiDi 调试地址": "Verbindung zur Firefox-WebDriver-BiDi-Debug-Adresse", + "创建 WebDriver BiDi 会话": "WebDriver-BiDi-Sitzung erstellen", + "WebDriver BiDi 会话没有返回 sessionId": "Die WebDriver-BiDi-Sitzung hat keine sessionId zurückgegeben", + "经 WebDriver BiDi 读取浏览器 Cookie": "Browser-Cookies über WebDriver BiDi lesen", + "解析 WebDriver BiDi Cookie": "WebDriver-BiDi-Cookies parsen", + "解码 WebDriver BiDi Cookie %s 的 base64 值": "Base64-Wert des WebDriver-BiDi-Cookies {0} dekodieren", + "WebDriver BiDi 读取失败": "WebDriver-BiDi-Lesen fehlgeschlagen", "连接浏览器调试地址: %w": "Verbindung zur Browser-Debugging-Adresse: {0}", "连接远程实例: %w": "Verbindung zur Remote-Instanz: {0}", "选中新标签页: %w": "Neuen Tab auswählen: {0}", diff --git a/internal/i18n/messages/en.json b/internal/i18n/messages/en.json index 4b1ece83..7d76e21a 100644 --- a/internal/i18n/messages/en.json +++ b/internal/i18n/messages/en.json @@ -1219,6 +1219,13 @@ "远程实例账户页生成的配对令牌,省略时从标准输入读取": "Pairing token generated on remote instance account page, read from standard input if omitted", "连接 Camoufox BiDi: %w": "Connecting to Camoufox BiDi: {0}", "连接 WebDriver BiDi": "Connecting to WebDriver BiDi", + "连接 Firefox WebDriver BiDi 调试地址": "Connecting to the Firefox WebDriver BiDi debugging address", + "创建 WebDriver BiDi 会话": "Creating a WebDriver BiDi session", + "WebDriver BiDi 会话没有返回 sessionId": "The WebDriver BiDi session did not return a sessionId", + "经 WebDriver BiDi 读取浏览器 Cookie": "Reading browser cookies via WebDriver BiDi", + "解析 WebDriver BiDi Cookie": "Parsing WebDriver BiDi cookies", + "解码 WebDriver BiDi Cookie %s 的 base64 值": "Decoding the base64 value of WebDriver BiDi cookie {0}", + "WebDriver BiDi 读取失败": "WebDriver BiDi read failed", "连接浏览器调试地址: %w": "Connecting to browser debugging address: {0}", "连接远程实例: %w": "Connecting to remote instance: {0}", "选中新标签页: %w": "Select new tab: {0}", diff --git a/internal/i18n/messages/fr.json b/internal/i18n/messages/fr.json index 8fc5fb05..cf0307af 100644 --- a/internal/i18n/messages/fr.json +++ b/internal/i18n/messages/fr.json @@ -1219,6 +1219,13 @@ "远程实例账户页生成的配对令牌,省略时从标准输入读取": "Jeton d’association généré sur la page des comptes de l’instance distante, lu depuis stdin si omis", "连接 Camoufox BiDi: %w": "Connexion à Camoufox BiDi : {0}", "连接 WebDriver BiDi": "Connexion à WebDriver BiDi", + "连接 Firefox WebDriver BiDi 调试地址": "Connexion à l'adresse de débogage Firefox WebDriver BiDi", + "创建 WebDriver BiDi 会话": "Création d'une session WebDriver BiDi", + "WebDriver BiDi 会话没有返回 sessionId": "La session WebDriver BiDi n'a pas renvoyé de sessionId", + "经 WebDriver BiDi 读取浏览器 Cookie": "Lecture des cookies du navigateur via WebDriver BiDi", + "解析 WebDriver BiDi Cookie": "Analyse des cookies WebDriver BiDi", + "解码 WebDriver BiDi Cookie %s 的 base64 值": "Décodage de la valeur base64 du cookie WebDriver BiDi {0}", + "WebDriver BiDi 读取失败": "Échec de la lecture WebDriver BiDi", "连接浏览器调试地址: %w": "Connexion à l’adresse de débogage du navigateur : {0}", "连接远程实例: %w": "Connexion à l’instance distante : {0}", "选中新标签页: %w": "Sélection du nouvel onglet : {0}", diff --git a/internal/i18n/messages/ja.json b/internal/i18n/messages/ja.json index 83ab5ced..533df8e6 100644 --- a/internal/i18n/messages/ja.json +++ b/internal/i18n/messages/ja.json @@ -1219,6 +1219,13 @@ "远程实例账户页生成的配对令牌,省略时从标准输入读取": "リモート インスタンスのアカウント画面で生成されたペアリング トークン。省略時は標準入力から読み取ります", "连接 Camoufox BiDi: %w": "Camoufox BiDi への接続: {0}", "连接 WebDriver BiDi": "WebDriver BiDi に接続中", + "连接 Firefox WebDriver BiDi 调试地址": "Firefox WebDriver BiDi デバッグアドレスへの接続", + "创建 WebDriver BiDi 会话": "WebDriver BiDi セッションの作成", + "WebDriver BiDi 会话没有返回 sessionId": "WebDriver BiDi セッションが sessionId を返しませんでした", + "经 WebDriver BiDi 读取浏览器 Cookie": "WebDriver BiDi 経由でブラウザ Cookie を読み込み", + "解析 WebDriver BiDi Cookie": "WebDriver BiDi Cookie の解析", + "解码 WebDriver BiDi Cookie %s 的 base64 值": "WebDriver BiDi Cookie {0} の base64 値をデコード", + "WebDriver BiDi 读取失败": "WebDriver BiDi の読み取りに失敗しました", "连接浏览器调试地址: %w": "ブラウザ デバッグ アドレスへの接続: {0}", "连接远程实例: %w": "リモート インスタンスへの接続: {0}", "选中新标签页: %w": "新しいタブを選択: {0}", diff --git a/internal/i18n/messages/ko.json b/internal/i18n/messages/ko.json index b3a46220..4fc8fd8e 100644 --- a/internal/i18n/messages/ko.json +++ b/internal/i18n/messages/ko.json @@ -1219,6 +1219,13 @@ "远程实例账户页生成的配对令牌,省略时从标准输入读取": "원격 인스턴스 계정 페이지에서 생성된 페어링 토큰, 생략 시 표준 입력에서 읽음", "连接 Camoufox BiDi: %w": "Camoufox BiDi 연결: {0}", "连接 WebDriver BiDi": "WebDriver BiDi 연결 중", + "连接 Firefox WebDriver BiDi 调试地址": "Firefox WebDriver BiDi 디버그 주소 연결", + "创建 WebDriver BiDi 会话": "WebDriver BiDi 세션 생성", + "WebDriver BiDi 会话没有返回 sessionId": "WebDriver BiDi 세션이 sessionId를 반환하지 않았습니다", + "经 WebDriver BiDi 读取浏览器 Cookie": "WebDriver BiDi로 브라우저 쿠키 읽기", + "解析 WebDriver BiDi Cookie": "WebDriver BiDi 쿠키 구문 분석", + "解码 WebDriver BiDi Cookie %s 的 base64 值": "WebDriver BiDi 쿠키 {0}의 base64 값 디코딩", + "WebDriver BiDi 读取失败": "WebDriver BiDi 읽기 실패", "连接浏览器调试地址: %w": "브라우저 디버그 주소 연결: {0}", "连接远程实例: %w": "원격 인스턴스 연결: {0}", "选中新标签页: %w": "새 탭 선택: {0}", diff --git a/internal/i18n/messages/zh-TW.json b/internal/i18n/messages/zh-TW.json index 11e38140..9cae7b20 100644 --- a/internal/i18n/messages/zh-TW.json +++ b/internal/i18n/messages/zh-TW.json @@ -1219,6 +1219,13 @@ "远程实例账户页生成的配对令牌,省略时从标准输入读取": "遠端執行個體帳號頁產生的配對權杖,省略時從標準輸入讀取", "连接 Camoufox BiDi: %w": "連線 Camoufox BiDi: {0}", "连接 WebDriver BiDi": "連線 WebDriver BiDi", + "连接 Firefox WebDriver BiDi 调试地址": "連線 Firefox WebDriver BiDi 偵錯位址", + "创建 WebDriver BiDi 会话": "建立 WebDriver BiDi 工作階段", + "WebDriver BiDi 会话没有返回 sessionId": "WebDriver BiDi 工作階段沒有傳回 sessionId", + "经 WebDriver BiDi 读取浏览器 Cookie": "經 WebDriver BiDi 讀取瀏覽器 Cookie", + "解析 WebDriver BiDi Cookie": "剖析 WebDriver BiDi Cookie", + "解码 WebDriver BiDi Cookie %s 的 base64 值": "解碼 WebDriver BiDi Cookie {0} 的 base64 值", + "WebDriver BiDi 读取失败": "WebDriver BiDi 讀取失敗", "连接浏览器调试地址: %w": "連線瀏覽器偵錯位址: {0}", "连接远程实例: %w": "連線遠端執行個體: {0}", "选中新标签页: %w": "選取新分頁: {0}", diff --git a/internal/setup/setup.go b/internal/setup/setup.go index aa8921c8..d58e87f9 100644 --- a/internal/setup/setup.go +++ b/internal/setup/setup.go @@ -293,7 +293,7 @@ func importStorageState(ctx context.Context, target accountTarget, options setup // importCookies 把 --cookie、--cookie-file 或 --cdp 浏览器中的 Cookie 导入为账户,未给 --email 时以 Cookie 登录的账户邮箱为账户 func importCookies(ctx context.Context, target accountTarget, options setupOptions) error { if options.cdp != "" { - browser, err := chromeauth.ReadCDPBrowser(ctx, options.cdp) + browser, err := chromeauth.ReadBrowserCookies(ctx, options.cdp) if err != nil { return err } diff --git a/web/src/App.vue b/web/src/App.vue index 30c36d7d..a534120c 100644 --- a/web/src/App.vue +++ b/web/src/App.vue @@ -509,6 +509,7 @@ onMounted(revealCurrentTab) :camoufox="status?.camoufox" :models="models" :cooldowns="cooldowns" + :service-running="serviceState === 'running'" @refresh="loadAccountData" @updated="updateAccount" @notice="showNotice" diff --git a/web/src/api.ts b/web/src/api.ts index ad99cecd..3f58ab35 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -250,6 +250,12 @@ export const api = { ).task, loginViewURL: (view: string) => `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.host}/api/login-view/${encodeURIComponent(view)}`, + accountLiveViewURL: (id: string) => + `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.host}/api/accounts/${encodeURIComponent(id)}/live-view`, + liveViewStatus: (id: string) => + requestJSON<{ available: boolean; reason?: string }>( + `/api/accounts/${encodeURIComponent(id)}/live-view/status`, + ), paths: (path: string) => requestJSON(`/api/paths?path=${encodeURIComponent(path)}`), pickPath: (path: string) => requestJSON<{ path: string }>(`/api/paths/pick?path=${encodeURIComponent(path)}`, { diff --git a/web/src/components/AccountLiveViewer.vue b/web/src/components/AccountLiveViewer.vue new file mode 100644 index 00000000..66c8ab24 --- /dev/null +++ b/web/src/components/AccountLiveViewer.vue @@ -0,0 +1,651 @@ + + + diff --git a/web/src/components/AccountsPanel.vue b/web/src/components/AccountsPanel.vue index 4e6f0a86..481cf271 100644 --- a/web/src/components/AccountsPanel.vue +++ b/web/src/components/AccountsPanel.vue @@ -44,6 +44,7 @@ import ImportFilterBar, { } from './ImportFilterBar.vue' import LinkedText from './LinkedText.vue' import LoginViewer from './LoginViewer.vue' +import AccountLiveViewer from './AccountLiveViewer.vue' import StagedRefreshIcon from './StagedRefreshIcon.vue' import UiCollapse from './UiCollapse.vue' import UiIcon from './UiIcon.vue' @@ -65,6 +66,8 @@ const props = defineProps<{ // models 与 cooldowns 是实时模型目录与模型冷却,供账户的模型对话框显示 models: Model[] cooldowns: Cooldown[] + // serviceRunning 表示生成服务正在运行,常驻浏览器远程操作在该状态下可用 + serviceRunning: boolean }>() const emit = defineEmits<{ @@ -765,6 +768,13 @@ watch( // viewerTaskID 是页内登录窗口显示的登录任务,为空时登录窗口关闭 const viewerTaskID = ref('') const viewerTask = computed(() => props.tasks.find((task) => task.id === viewerTaskID.value)) +// liveViewAccount 是打开远程操作窗口的账户,为空时窗口关闭 +const liveViewAccount = ref(null) + +// openLiveView 打开账户常驻浏览器的远程操作窗口 +function openLiveView(account: Account): void { + liveViewAccount.value = account +} // 登录窗口显示的任务被关闭或登录完成时关闭登录窗口,登录失败时窗口显示原因 watch(viewerTask, (task) => { @@ -2030,6 +2040,22 @@ watch(
+