From d51e9e3cadbcd665d9bc1703809c88ec06d6cbe3 Mon Sep 17 00:00:00 2001 From: Joey Shao Date: Mon, 9 Nov 2026 17:58:05 +0800 Subject: [PATCH] mclaw 0.5.3: fail at authorize when there is no browser or display (#898) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mclaw's authorize now runs a preflight before it returns opened:true. When no Chromium browser can be found, or Linux has neither DISPLAY nor WAYLAND_DISPLAY, it returns {type:'failed'} at once instead of claiming a window opened and failing later in callback (source issue joey-41/opencode-mclaw-auth#1, the same shape as inkstone #825). requireBrowser() is now the only place that looks up the browser, and holds its one error message. It now looks for Edge, Chromium and Brave on macOS, Edge on Windows, and microsoft-edge and /opt/google/chrome on Linux. MCLAW_CHROME_PATH is checked first (X_OK, or F_OK on Windows) and a bad path gets its own error. Headless renewal still goes through requireBrowser only, with no display check. The cancel test now uses two independent AbortControllers (#746 follow-up). README and CHANGELOG updated, 0.5.3. Reviewed head 40784afa76c89285cb039460f55cc0f9fb059e21, on main 89fcfb2e. Read every line of the diff: it adds no network endpoint, credential read, install script or obfuscated code. Run at that head, on mote (macOS), HOME a scratch dir: - packages/mclaw `bun test`: 41 pass, 0 fail. - repo `bun test` (HOME=$(mktemp -d), as CI): 7604 pass, 0 fail. `bun scripts/check.mjs`: exit 0. (The package has no node:test files; every test is bun:test.) - Broken by hand, each red and restored: - no preflight call in authorize: both login preflight tests red; - no DISPLAY check: the browser-path and login no-display tests red; - MCLAW_CHROME_PATH not validated: the bad-override test red; - candidates not access()-checked: the real-executable test red. - Real env, no seams, in WSL (magpie-desktop): DISPLAY/WAYLAND_DISPLAY unset → authorize returns failed with the no-display message, no opened. DISPLAY set + MCLAW_CHROME_PATH=/no/such → failed with the override message. DISPLAY set, no browser installed → requireBrowser throws the no-browser message. - Candidate tables against real machines: mote finds ~/Applications/Google Chrome.app; xiaomi-gpu (Windows 11) finds C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe. - PR CI (ubuntu, headless) test job green. Not blocking, left for a later version: on Windows, Edge (installed on every machine) now comes before a LOCALAPPDATA Chromium, so a renewal of a profile Chromium made would open in Edge. Linux's table has no Brave, though the README names it. Not tried: a real MClaw sign-in (no account), or a headed sign-in through Edge or Brave. --- packages/mclaw/CHANGELOG.md | 13 ++++ packages/mclaw/README.md | 19 ++++- packages/mclaw/browser-path.test.mjs | 107 +++++++++++++++++++++++++++ packages/mclaw/browser.mjs | 88 ++++++++++++++++++---- packages/mclaw/index.mjs | 26 ++++++- packages/mclaw/login.test.mjs | 62 +++++++++++++++- packages/mclaw/package.json | 2 +- 7 files changed, 293 insertions(+), 24 deletions(-) create mode 100644 packages/mclaw/browser-path.test.mjs diff --git a/packages/mclaw/CHANGELOG.md b/packages/mclaw/CHANGELOG.md index 34556fc..5d404ee 100644 --- a/packages/mclaw/CHANGELOG.md +++ b/packages/mclaw/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 0.5.3 — 2026-11-09 + +浏览器登录的「开始前」预检与提示语(对应源仓库 issue #1「弹不出登陆界面,找不到chrome」,做法对齐 magpie-community/plugins#825 对 inkstone 的修法): + +- **authorize 阶段就失败,不再先说「窗口已弹出」**:登录前的图形界面/浏览器预检放在 `authorize` 里、`opened: true` 之前;没有可用浏览器或 Linux 无 `DISPLAY`/`WAYLAND_DISPLAY` 时直接返回 `type: 'failed'`,错误在选登录方式时就可见,而不是拖到 callback。此前无预检、无条件返回 `opened: true` +「已弹出专用 Chrome 窗口」,正是社区 #825 批评的形状。 +- **单一 `requireBrowser()` helper**:浏览器定位与「找不到」文案只此一份,`authorize` 预检、登录、续期共用;`launch()` 的 ENOENT 分支复用同一文案,避免多处漂移。 +- **浏览器候选表扩充**:macOS 增加 Edge / Chromium / Brave 与 `~/Applications`,Windows 增加 Edge×3,Linux 增加 `microsoft-edge` 与 `/opt/google/chrome/chrome`;仍是自维护表 + 自己 spawn(不查 PATH、不用系统默认浏览器,与社区其他登录插件一致)。 +- **`MCLAW_CHROME_PATH` 校验存在/可执行**:写错路径给专属报错「指向的浏览器不存在或不可执行」,不再混成误导性的「找不到 Chrome」;Windows 用 `F_OK`、其余用 `X_OK`。 +- **README 写明登录前提**:需本机 Chromium 内核浏览器(Safari 不行并给原因)+ 有图形界面的本地会话;远程/SSH/容器/无头环境不支持弹窗,附 `MCLAW_CHROME_PATH` 示例。 +- **instructions 按实际行为写**:「专用浏览器窗口…登录成功后自动检测并继续,窗口由插件自己关闭,不需要手动关窗」(CDP 轮询 Cookie,不依赖用户关窗)。 +- **测试加固**:合并评论里的非阻塞 follow-up——magpie 式取消用例改用两个独立 `AbortController`,只 abort callback 的那个,并断言 authorize 的 signal 未被碰;临时摘掉 callback 的 signal 接线该用例会报红。新增 `browser-path.test.mjs` 覆盖三平台候选表、空候选、override 写错/正确、有/无 DISPLAY、预检通过的 authorize 行为。测试 30 → 41。 +- **测试不依赖测试机平台**(市场 PR #898 首轮 CI 在无头 Ubuntu 上报红):「找不到浏览器」用例原本只注入空候选,在无 `DISPLAY` 的 Linux runner 上会先命中无 GUI 预检,拿不到预期的浏览器报错。新增 `signinEnv` / `signinPlatform` 测试缝,两条预检各自可确定性触发;本机 macOS 与清空 DISPLAY 的无头模拟下均 41 pass。 + ## 0.5.2 — 2026-11-05 - **magpie 式取消立即收尾**:magpie 在 authorize 之后**立刻**调 `callback(undefined, { signal })`,用户取消/登录超时时 abort signal——之前 callback 不读 signal、`clearTimeout` 又把 5 分钟兜底定时器拆了,Chrome 会一直开满 10 分钟 deadline(甚至给已被宿主放弃的登录继续取 key)。现在 `authorize` 和 `callback` 都接 signal:`signal.aborted` 先查、`addEventListener('abort', …, { once: true })` 后挂,abort 一到立即收尾。 diff --git a/packages/mclaw/README.md b/packages/mclaw/README.md index 91cc86f..e0ae607 100644 --- a/packages/mclaw/README.md +++ b/packages/mclaw/README.md @@ -15,7 +15,22 @@ magpie plugin login mclaw ## 登录 -浏览器登录,一次登录凭证全自动,**没有任何要填的输入**:选「浏览器登录」→ 插件弹出一个**专用 Chrome 窗口**(每次登录一个全新 profile,不影响日常浏览器)→ 在窗口里登录移动云 `yun.139.com`(网页支持验证码、密码、扫码等多种方式,任选)→ 插件自动收走 `authorization` Cookie(= `pc:` 票,30 天期),其余全自动:llm chat key(`na-…`)与模型倍率表自动取回,openclawId 与账号实际模型清单自动发现,vip 会话由换票链自动维持(`toSourceId 001005`,与 App vip 会员中心同渠道;进程内复用,24h 期,失败 30 分钟冷却),用量窗口(含「重置于」与逐条明细)自动接上;账号显示名 = 掩码手机号(票里解出)。**票到期前 3 天自动续期**:headless 复开该账号自己的 profile(目录存在账号 metadata 里,多账号互不串票,续期时会校验收割到的票属于本账号),网页会话自己刷新后重新收割,票换了顺手刷新 key。取消登录、登录失败或超时都会立即关掉 Chrome 并清掉当次的 profile 目录。已知限制:**重新登录同一账号会生成一个新 profile,旧目录会留在** `mclaw-browser-profiles/` 下(内含不再被任何账号引用的历史登录态,可手动删除)。 +**登录前提**:浏览器登录由插件自己启动一个**有界面的 Chromium 内核浏览器窗口**(CDP `--remote-debugging-pipe` 驱动,收登录态),所以要求: + +- 本机安装了 **Google Chrome / Microsoft Edge / Chromium / Brave** 之一(macOS 上 Safari 不行:它不支持插件用的独立 `--user-data-dir` profile,也没有 CDP); +- magpie 运行在**有图形界面的本地会话**里。远程服务器、SSH、容器、纯 headless 环境弹不出窗口——Linux 上未设置 `DISPLAY` / `WAYLAND_DISPLAY` 时插件会在选登录方式时直接报明原因。 + +浏览器装在非标准位置(或上述自动探测没找到)时,用 `MCLAW_CHROME_PATH` 指到可执行文件,例如 macOS: + +```bash +MCLAW_CHROME_PATH="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" magpie plugin login mclaw +``` + +`MCLAW_CHROME_PATH` 会先校验存在/可执行,路径写错会明确报「指向的浏览器不存在或不可执行」,不会混成「找不到 Chrome」。**没有可用的浏览器或没有图形界面时,无法完成浏览器登录**,本插件目前只有这一种登录方式。 + +--- + +浏览器登录,一次登录凭证全自动,**没有任何要填的输入**:选「浏览器登录」→ 插件弹出一个**专用浏览器窗口**(每次登录一个全新 profile,不影响日常浏览器)→ 在窗口里登录移动云 `yun.139.com`(网页支持验证码、密码、扫码等多种方式,任选)→ 插件自动收走 `authorization` Cookie(= `pc:` 票,30 天期),其余全自动:llm chat key(`na-…`)与模型倍率表自动取回,openclawId 与账号实际模型清单自动发现,vip 会话由换票链自动维持(`toSourceId 001005`,与 App vip 会员中心同渠道;进程内复用,24h 期,失败 30 分钟冷却),用量窗口(含「重置于」与逐条明细)自动接上;账号显示名 = 掩码手机号(票里解出)。**票到期前 3 天自动续期**:headless 复开该账号自己的 profile(目录存在账号 metadata 里,多账号互不串票,续期时会校验收割到的票属于本账号),网页会话自己刷新后重新收割,票换了顺手刷新 key。取消登录、登录失败或超时都会立即关掉 Chrome 并清掉当次的 profile 目录。已知限制:**重新登录同一账号会生成一个新 profile,旧目录会留在** `mclaw-browser-profiles/` 下(内含不再被任何账号引用的历史登录态,可手动删除)。 ## 模型 @@ -46,7 +61,7 @@ aitokens 池窗口:总量、已用、剩余与「重置于」。重置于来 magpie plugin options mclaw '{"base": "https://ai.yun.139.com/api/llm/102001"}' ``` -环境变量(浏览器登录相关):`MCLAW_CHROME_PATH`(Chrome 可执行文件路径,默认按平台探测)、`MCLAW_BROWSER_PROFILE`(登录 profile 目录的根,每个账号用其下的独立子目录,默认 `~/.config/magpie/mclaw-browser-profiles/`)。 +环境变量(浏览器登录相关):`MCLAW_CHROME_PATH`(Chrome / Edge / Chromium / Brave 可执行文件路径,默认按平台探测;设置后会校验存在/可执行)、`MCLAW_BROWSER_PROFILE`(登录 profile 目录的根,每个账号用其下的独立子目录,默认 `~/.config/magpie/mclaw-browser-profiles/`)。登录前提见上文「登录」。 ## 许可证 diff --git a/packages/mclaw/browser-path.test.mjs b/packages/mclaw/browser-path.test.mjs new file mode 100644 index 0000000..4d83cf6 --- /dev/null +++ b/packages/mclaw/browser-path.test.mjs @@ -0,0 +1,107 @@ +// 浏览器定位与登录前提:候选表、MCLAW_CHROME_PATH 校验、无图形界面拒绝。 +// 全部注入 platform/env/candidates,不依赖测试机是否装了 Chrome。 +import './nonet.mjs' +import { mkdtempSync, writeFileSync, chmodSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, test } from 'bun:test' +import { browserCandidates, requireBrowser, assertBrowserSigninPrerequisites } from './browser.mjs' + +const clean = (env = {}) => ({ + MCLAW_CHROME_PATH: undefined, + DISPLAY: undefined, + WAYLAND_DISPLAY: undefined, + ...env, +}) + +let tmp +afterEach(() => { + if (tmp) rmSync(tmp, { recursive: true, force: true }) + tmp = undefined +}) + +function fakeExecutable(name = 'chrome') { + tmp = mkdtempSync(join(tmpdir(), 'mclaw-browser-test-')) + const path = join(tmp, name) + writeFileSync(path, '#!/bin/sh\n') + chmodSync(path, 0o755) + return path +} + +test('候选表覆盖三平台,且认 Edge / Chromium / Brave', () => { + const win = browserCandidates({ platform: 'win32', env: { PROGRAMFILES: 'C:/PF', LOCALAPPDATA: 'C:/LA' } }) + expect(win.some((p) => p.endsWith('msedge.exe'))).toBe(true) + expect(win.some((p) => p.endsWith('chrome.exe'))).toBe(true) + + const mac = browserCandidates({ platform: 'darwin', env: {} }) + expect(mac.some((p) => p.includes('Google Chrome.app'))).toBe(true) + expect(mac.some((p) => p.includes('Microsoft Edge.app'))).toBe(true) + expect(mac.some((p) => p.includes('Chromium.app'))).toBe(true) + expect(mac.some((p) => p.includes('Brave Browser.app'))).toBe(true) + + const linux = browserCandidates({ platform: 'linux', env: {} }) + expect(linux).toContain('/usr/bin/microsoft-edge') + expect(linux).toContain('/usr/bin/chromium') +}) + +test('候选为空 → 报错且只此一份文案,不宣称窗口已弹出', async () => { + let caught + try { + await requireBrowser({ platform: 'linux', env: clean(), candidates: [] }) + } catch (error) { + caught = error + } + expect(caught?.message).toContain('找不到可用的 Chrome / Edge / Chromium') + expect(caught?.message).toContain('图形界面') + expect(caught?.message).toContain('MCLAW_CHROME_PATH') +}) + +test('候选里有一个真实可执行文件 → 返回它', async () => { + const exe = fakeExecutable() + const found = await requireBrowser({ platform: 'linux', env: clean(), candidates: ['/definitely/not/here', exe] }) + expect(found).toBe(exe) +}) + +test('MCLAW_CHROME_PATH 写错 → 专属报错,不混成「找不到 Chrome」', async () => { + let caught + try { + await requireBrowser({ platform: 'linux', env: clean({ MCLAW_CHROME_PATH: '/no/such/chrome' }), candidates: [] }) + } catch (error) { + caught = error + } + expect(caught?.message).toContain('MCLAW_CHROME_PATH 指向的浏览器不存在或不可执行') + expect(caught?.message).toContain('/no/such/chrome') + expect(caught?.message).not.toContain('找不到可用的 Chrome') +}) + +test('MCLAW_CHROME_PATH 指向可执行文件 → 优先于候选表', async () => { + const exe = fakeExecutable() + const found = await requireBrowser({ platform: 'linux', env: clean({ MCLAW_CHROME_PATH: exe }), candidates: [] }) + expect(found).toBe(exe) +}) + +test('Linux 无 DISPLAY / WAYLAND_DISPLAY → 明确拒绝,即使浏览器存在', async () => { + const exe = fakeExecutable() + let caught + try { + await assertBrowserSigninPrerequisites({ platform: 'linux', env: clean(), candidates: [exe] }) + } catch (error) { + caught = error + } + expect(caught?.message).toContain('没有图形界面') + expect(caught?.message).toContain('DISPLAY') +}) + +test('Linux 有 DISPLAY 且浏览器存在 → 预检通过', async () => { + const exe = fakeExecutable() + await expect(assertBrowserSigninPrerequisites({ + platform: 'linux', env: clean({ DISPLAY: ':0' }), candidates: [exe], + })).resolves.toBe(exe) +}) + +test('macOS 无 DISPLAY 也放行(不走 Linux 的 GUI 判定)', async () => { + const exe = fakeExecutable() + await expect(assertBrowserSigninPrerequisites({ + platform: 'darwin', env: clean(), candidates: [exe], + })).resolves.toBe(exe) +}) diff --git a/packages/mclaw/browser.mjs b/packages/mclaw/browser.mjs index 7960a1d..781f9bd 100644 --- a/packages/mclaw/browser.mjs +++ b/packages/mclaw/browser.mjs @@ -11,6 +11,7 @@ * 用 --headless=new 复开该账号自己的 profile,网页应用自己会刷新会话。 */ import { spawn } from 'node:child_process' +import { constants } from 'node:fs' import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises' import { createHash, randomBytes } from 'node:crypto' import { homedir, tmpdir } from 'node:os' @@ -263,8 +264,10 @@ function launch(executable, args, { timeout = 30000 } = {}) { const failed = new Promise((_, reject) => { child.once('error', (error) => { connection.shut('Chrome could not be started') + // 常规「没装浏览器」已被 requireBrowser 的预检挡在前面;这里的 ENOENT + // 只剩竞态 / 坏软链等罕见情形,文案仍复用同一份,避免多处漂移。 reject(error.code === 'ENOENT' - ? new Error('找不到 Chrome;请安装 Google Chrome 或用 MCLAW_CHROME_PATH 指到可执行文件') + ? new Error(noBrowserMessage) : new Error(`Chrome 无法启动:${error.message}`)) }) child.once('exit', (code) => { @@ -279,23 +282,76 @@ function launch(executable, args, { timeout = 30000 } = {}) { // ---------------------------------------------------------------- Chrome 定位 -export async function chromeExecutable() { - const override = process.env.MCLAW_CHROME_PATH - if (override) return resolve(override.startsWith('~') ? join(homedir(), override.slice(2)) : override) - const candidates = process.platform === 'win32' - ? [ - process.env.PROGRAMFILES && join(process.env.PROGRAMFILES, 'Google', 'Chrome', 'Application', 'chrome.exe'), - process.env['PROGRAMFILES(X86)'] && join(process.env['PROGRAMFILES(X86)'], 'Google', 'Chrome', 'Application', 'chrome.exe'), - process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, 'Google', 'Chrome', 'Application', 'chrome.exe'), - process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, 'Chromium', 'Application', 'chrome.exe'), +/** 各平台的 Chromium 内核浏览器候选(按优先级)。只驱动自己 spawn 的浏览器, + * 所以不查 PATH、不用系统默认浏览器:Edge / Brave / Chromium 与 Chrome 同一套 + * --remote-debugging-pipe flags 即可工作,都列进来。platform/env 可注入,测试 + * 不必依赖测试机装了什么浏览器。 */ +export function browserCandidates({ platform = process.platform, env = process.env } = {}) { + const pf = env.PROGRAMFILES + const pf86 = env['PROGRAMFILES(X86)'] + const local = env.LOCALAPPDATA + if (platform === 'win32') { + return [ + pf && join(pf, 'Google', 'Chrome', 'Application', 'chrome.exe'), + pf86 && join(pf86, 'Google', 'Chrome', 'Application', 'chrome.exe'), + local && join(local, 'Google', 'Chrome', 'Application', 'chrome.exe'), + pf && join(pf, 'Microsoft', 'Edge', 'Application', 'msedge.exe'), + pf86 && join(pf86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'), + local && join(local, 'Microsoft', 'Edge', 'Application', 'msedge.exe'), + local && join(local, 'Chromium', 'Application', 'chrome.exe'), ].filter(Boolean) - : process.platform === 'darwin' - ? ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', join(homedir(), 'Applications', 'Google Chrome.app', 'Contents', 'MacOS', 'Google Chrome')] - : ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/snap/bin/chromium'] - for (const path of candidates) { - try { await access(path); return path } catch {} } - throw new Error('找不到 Chrome;请安装 Google Chrome 或用 MCLAW_CHROME_PATH 指到可执行文件') + if (platform === 'darwin') { + const home = join(homedir(), 'Applications') + return [ + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + join(home, 'Google Chrome.app', 'Contents', 'MacOS', 'Google Chrome'), + '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge', + '/Applications/Chromium.app/Contents/MacOS/Chromium', + join(home, 'Chromium.app', 'Contents', 'MacOS', 'Chromium'), + '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser', + ] + } + return [ + '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', + '/usr/bin/chromium', '/usr/bin/chromium-browser', + '/usr/bin/microsoft-edge', '/snap/bin/chromium', + '/opt/google/chrome/chrome', + ] +} + +const noBrowserMessage = '找不到可用的 Chrome / Edge / Chromium。MClaw 的浏览器登录需要本机安装 Chromium 内核浏览器,且 magpie 运行在有图形界面的本地会话里(远程 / SSH / 容器 / 无头环境不支持弹窗)。请安装 Google Chrome,或设置 MCLAW_CHROME_PATH=/path/to/chrome 指向可执行文件。' + +/** 唯一的浏览器定位入口:authorize 预检、登录、续期都走它,文案只此一份, + * 不会在多处漂移。override 会先校验存在/可执行,写错路径给专属报错而不是 + * 误导性的「找不到 Chrome」。返回可执行文件路径,找不到就抛。 + * candidates 是测试缝:注入后不依赖测试机装了什么浏览器。 */ +export async function requireBrowser({ platform = process.platform, env = process.env, candidates } = {}) { + const override = env.MCLAW_CHROME_PATH + // Windows 上 X_OK 等同 F_OK(可执行位无意义),别用它误判。 + const mode = platform === 'win32' ? constants.F_OK : constants.X_OK + if (override) { + const path = resolve(override.startsWith('~') ? join(homedir(), override.slice(2)) : override) + try { await access(path, mode); return path } catch {} + throw new Error(`MCLAW_CHROME_PATH 指向的浏览器不存在或不可执行:${path}。请改成 Chrome / Edge / Chromium 的可执行文件,或 unset 该变量让插件自动探测。`) + } + for (const path of candidates ?? browserCandidates({ platform, env })) { + try { await access(path, mode); return path } catch {} + } + throw new Error(noBrowserMessage) +} + +/** 兼容入口:openMclawBrowser(登录与 headless 续期)用它拿真实环境的浏览器。 */ +export const chromeExecutable = () => requireBrowser() + +/** 登录(有头窗口)的前提检查:Linux 无图形界面先明确拒绝,再查浏览器。 + * 只在 authorize 里调用——续期是 headless,没有界面也能跑,不该被这条挡住。 + * candidates 透传给 requireBrowser,方便测试注入。 */ +export async function assertBrowserSigninPrerequisites({ platform = process.platform, env = process.env, candidates } = {}) { + if (platform === 'linux' && !env.DISPLAY && !env.WAYLAND_DISPLAY) { + throw new Error('当前 Linux 会话没有图形界面(未设置 DISPLAY / WAYLAND_DISPLAY),MClaw 的浏览器登录无法弹出窗口;请在有图形界面的本地会话里运行 magpie。') + } + return requireBrowser({ platform, env, candidates }) } // ---------------------------------------------------------------- 打开/收割 diff --git a/packages/mclaw/index.mjs b/packages/mclaw/index.mjs index 702afa8..9fd5f5e 100644 --- a/packages/mclaw/index.mjs +++ b/packages/mclaw/index.mjs @@ -66,6 +66,7 @@ * { "base": "https://ai.yun.139.com/api/llm/102001" } * 环境变量:MCLAW_CHROME_PATH(Chrome 路径)、MCLAW_BROWSER_PROFILE(登录 * profile 目录的根,每个账号是它下面的一个子目录) + * 测试缝:options.signinPrerequisites(预检函数)、options.browserCandidates */ import { randomUUID } from 'node:crypto' import * as browserDefault from './browser.mjs' @@ -634,6 +635,20 @@ export const MclawAuthPlugin = async (_input, options) => { activeBase = base // 测试缝:fake browser 从 options.browserModule 进(宿主不会传)。 const browser = options?.browserModule ?? browserDefault + // 登录前的浏览器/图形界面预检(宿主不会传,测试可注入)。失败要发生在 + // authorize 里、返回 opened:true 之前——不能先宣称窗口已弹出再在 callback 里 + // 报错。fake browser 不带预检时整个跳过,不碰本机真实环境。 + // signinEnv / signinPlatform 是测试缝:让「找不到浏览器」与「无 DISPLAY」两条 + // 预检各自可确定性触发,不受测试机(如无头 Linux CI)环境影响。 + const signinPrerequisites = options?.signinPrerequisites + ?? (options?.browserCandidates !== undefined || options?.signinEnv !== undefined || options?.signinPlatform !== undefined + ? () => browserDefault.assertBrowserSigninPrerequisites({ + ...(options?.signinPlatform !== undefined ? { platform: options.signinPlatform } : {}), + ...(options?.signinEnv !== undefined ? { env: options.signinEnv } : {}), + ...(options?.browserCandidates !== undefined ? { candidates: options.browserCandidates } : {}), + }) + : undefined) + ?? (options?.browserModule ? undefined : (pre) => browserDefault.assertBrowserSigninPrerequisites(pre)) // 宿主取消登录(callback 没被调)后的收尾时限:到点关浏览器、放 profile 锁, // 不然锁被宿主 pid 占着,后续登录/续期全要等 LOCK_TIMEOUT。 const signinAbortMs = Number(options?.signinAbortMs) > 0 ? Number(options.signinAbortMs) : 300_000 @@ -674,6 +689,15 @@ export const MclawAuthPlugin = async (_input, options) => { // metadata },到期前宿主调 refresh 钩子 headless 续期(复开该账号 // 自己的 profile)。 async authorize(inputs = {}, { signal } = {}) { + // 预检先于任何副作用:没有图形界面(Linux 无 DISPLAY/WAYLAND)或找不到 + // Chromium 内核浏览器时,直接在这里失败。参照 inkstone 0.1.1 的 + // 修法——「窗口已弹出」这类话绝不能先说出去再在 callback 里报错 + // (magpie-community/plugins#825)。 + try { + if (typeof signinPrerequisites === 'function') await signinPrerequisites() + } catch (error) { + return { type: 'failed', error: error?.message ?? String(error) } + } // 不 await:Chrome 立即弹出;若宿主取消(callback 没被调),定时器 // 到点 abort——关浏览器、放 profile 锁;挂个空 catch 免得 abort 后 // 的拒绝刷 unhandled rejection。 @@ -689,7 +713,7 @@ export const MclawAuthPlugin = async (_input, options) => { return { url: '', opened: true, // Chrome 已由本插件弹出,宿主不要再开 url - instructions: '已弹出专用 Chrome 窗口:请在里面登录移动云(yun.139.com,网页支持多种登录方式),登录成功后本流程自动继续并收走全部凭证', + instructions: '已弹出专用浏览器窗口:请在里面登录移动云(yun.139.com,网页支持验证码、密码、扫码等多种方式)。登录成功后本流程自动检测并继续,窗口由插件自己关闭,你不需要手动关窗。', method: 'auto', async callback(_code, { signal: callbackSignal } = {}) { clearTimeout(cleanup) diff --git a/packages/mclaw/login.test.mjs b/packages/mclaw/login.test.mjs index 3ad852c..3d7ddb3 100644 --- a/packages/mclaw/login.test.mjs +++ b/packages/mclaw/login.test.mjs @@ -121,15 +121,20 @@ test('magpie 式取消:callback 立即被调 + signal abort → 立即收尾', f = fakeUpstream() fb = fakeBrowserModule({ ticket: TICKET_A }) const plugin = await MclawAuthPlugin({}, { browserModule: fb.module, signinAbortMs: 60_000 }) - const controller = new AbortController() + // magpie 给 authorize 和 callback 的是两个各自独立的 signal,取消时只 abort + // callback 的那个。两个入口必须用不同 controller,否则 authorize 的 listener + // 会替它兜住收尾,callback 就算没接 signal 测试也照样绿,测不出漏接。 + const authorizeController = new AbortController() + const callbackController = new AbortController() // magpie 的时序:authorize 一返回就调 callback(undefined, { signal }), // 用户取消/登录超时时 abort signal——收尾必须立刻发生,不等 5 分钟定时器 - const flow = await oauthMethod(plugin).authorize({}, { signal: controller.signal }) - const done = flow.callback(undefined, { signal: controller.signal }) + const flow = await oauthMethod(plugin).authorize({}, { signal: authorizeController.signal }) + const done = flow.callback(undefined, { signal: callbackController.signal }) await sleep(10) expect(fb.state.aborted).toBe(false) - controller.abort() + callbackController.abort() // 只取消 callback;authorize 的 signal 保持 alive const result = await done + expect(authorizeController.signal.aborted).toBe(false) // 确实没碰另一个入口 expect(result.type).toBe('failed') expect(fb.state.aborted).toBe(true) expect(fb.state.closed).toBeGreaterThanOrEqual(1) @@ -148,3 +153,52 @@ test('authorize 时 signal 已是 aborted → 直接收尾不开流程', async ( expect(fb.state.closed).toBeGreaterThanOrEqual(1) expect(fb.state.released).toBeGreaterThanOrEqual(1) }) + +// 浏览器/图形界面预检发生在 authorize、返回 opened:true 之前(#825 的修法): +// 失败时宿主拿到 type:'failed',绝不能先说「窗口已弹出」再在 callback 里报错。 +test('预检失败(找不到浏览器)→ authorize 直接 failed,不开 harvest', async () => { + f = fakeUpstream() + fb = fakeBrowserModule({ ticket: TICKET_A }) + // 注入「有图形界面的 Linux + 空候选」:否则无头 CI 上会先撞上无 DISPLAY + // 预检,测不到浏览器那条分支。两条预检各自可确定性触发。 + const plugin = await MclawAuthPlugin({}, { + browserModule: fb.module, browserCandidates: [], signinAbortMs: 60_000, + signinPlatform: 'linux', signinEnv: { DISPLAY: ':0' }, + }) + const out = await oauthMethod(plugin).authorize({}) + expect(out.type).toBe('failed') + expect(out.error).toContain('找不到可用的 Chrome') + expect(out.opened).toBeUndefined() + expect(fb.state.harvests).toBe(0) +}) + +test('预检失败(Linux 无 DISPLAY)→ authorize 直接 failed,不开 harvest', async () => { + f = fakeUpstream() + fb = fakeBrowserModule({ ticket: TICKET_A }) + // 走真实预检(不是抛错桩):即使给一个存在的浏览器,无 DISPLAY 也要先拒绝。 + const plugin = await MclawAuthPlugin({}, { + browserModule: fb.module, browserCandidates: ['/bin/true'], + signinPlatform: 'linux', signinEnv: {}, + }) + const out = await oauthMethod(plugin).authorize({}) + expect(out.type).toBe('failed') + expect(out.error).toContain('没有图形界面') + expect(fb.state.harvests).toBe(0) +}) + +test('预检通过(注入可执行候选)→ 正常开 harvest,instructions 不再谎报已弹出', async () => { + f = fakeUpstream() + fb = fakeBrowserModule({ ticket: TICKET_A }) + const plugin = await MclawAuthPlugin({}, { + browserModule: fb.module, + signinPrerequisites: async () => {}, + signinAbortMs: 60_000, + }) + const flow = await oauthMethod(plugin).authorize({}) + expect(flow.opened).toBe(true) + expect(flow.instructions).toContain('专用浏览器窗口') + expect(flow.instructions).toContain('不需要手动关窗') + fb.module.deliverHarvest() + const result = await flow.callback() + expect(result.type).toBe('success') +}) diff --git a/packages/mclaw/package.json b/packages/mclaw/package.json index f0755a7..2f5dbcc 100644 --- a/packages/mclaw/package.json +++ b/packages/mclaw/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-mclaw-auth", - "version": "0.5.2", + "version": "0.5.3", "description": "OpenCode provider plugin: MClaw (中国移动云 MClaw, ai.yun.139.com)", "type": "module", "main": "./opencode.mjs",