From 02c4a7e1e28fd882d0a9bcf76d835a695e9a1266 Mon Sep 17 00:00:00 2001 From: MYCF711 Date: Thu, 19 Nov 2026 15:28:55 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E7=99=BE=E6=99=BA=E4=BA=91=E6=AF=8F?= =?UTF-8?q?=E6=97=A5=E7=A7=AF=E5=88=86=E8=AF=AF=E5=88=A4=20+=20=E6=B5=8F?= =?UTF-8?q?=E8=A7=88=E5=99=A8=E7=99=BB=E5=BD=95=E5=80=99=E9=80=89=E9=A1=BA?= =?UTF-8?q?=E5=BA=8F=EF=BC=880.2.46=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 百智云每日积分(#13):`claimed:false` 不再一律当「今日已领取」,按 `captcha_required` / `captcha` 对象 → 回读钱包(dailyClaimed 或 temporary 正差额)→ failed 三档判定;三档各报真话。误报成「已领取」会让宿主当天 不再重试,额度卡片也永远不出「每日积分」那一行。 - 浏览器登录(#7):优先系统默认浏览器(`UrlAssociations\http\UserChoice` 的 ProgId),夸克 / UC 这类会自己回收 CDP 目标的浏览器排最后;目标丢失时 报可行动文案(换用 Edge 或 Chrome),不再误导成「窗口被关掉了」。 - 测试:`node --test` 427/427 通过;`node scripts/check.mjs` 49/49 通过; `node scripts/check-maintenance.mjs` 仅「0.2.46 没有 tag」一条失败(发布前预期)。 Co-authored-by: NaturePorter --- CHANGELOG.md | 13 ++ package.json | 2 +- src/baizhi/credits.mjs | 51 ++++++- src/browser-login.mjs | 224 ++++++++++++++++++++++++++++-- src/session-login.mjs | 19 ++- tests/baizhi.test.mjs | 150 +++++++++++++++++++- tests/browser-candidates.test.mjs | 182 ++++++++++++++++++++++++ 7 files changed, 622 insertions(+), 19 deletions(-) create mode 100644 tests/browser-candidates.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index e97e316..21e49ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,19 @@ > 每个版本一节,**一条一行**,说用户能感知的变化。 > 格式与规矩见 [UPDATING.md](./UPDATING.md)。 +## 0.2.46 — 2026-11-19 + +**修:百智云每日积分把「要验证码」误报成「今日已领取」;浏览器登录不再优先选夸克** + +- `claimed:false` 不再一律当「今日已领取」(#13):先看 `captcha_required` / `captcha` 对象,再回读钱包 + (`daily_claimed` 为真、或 temporary 余额有正差额 ⇒ 并发幂等已领取),两样都不成立才判 `failed`; + 三档各报真话 —— 误报成「已领取」会让宿主当天不再重试,额度卡片也永远不出「每日积分」那一行 +- 受控浏览器优先系统默认浏览器(读 `UrlAssociations\http\UserChoice` 的 ProgId)(#7): + 夸克 / UC 这类能开调试端口、却会自己回收 CDP 目标(把已连上的 page 目标弄丢)的浏览器一律排最后; + 目标丢失时报可行动的文案(「换用 Edge 或 Chrome」),不再把用户误导向「你关了窗口」 +- 两处都补了离线单测:`claimed:false` 的三条判据、候选排序 / ProgId / 目标丢失文案; + 全部注入假实现,不读真注册表、不启动浏览器 + ## 0.2.45 — 2026-11-13 **修:平台取消基础用户日额度之后,额度卡片整张变错误态** diff --git a/package.json b/package.json index be961c2..c6418eb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "magpie-monkeycode", - "version": "0.2.45", + "version": "0.2.46", "description": "MonkeyCode 国内站 / 国际站 + 百智云 magpie 插件:百智云「本机导入」「浏览器登录」成功后自动开通并写入国内 MonkeyCode(后台执行、失败不影响百智云登录、按 uid 去重);百智云只保留这两条登录路,国内站只认百智云身份,国际站独立(API Key / 账号密码 / 本机导入 / 浏览器);支持双方邀请码、网关签名与「每日额度 / 积分」计费标识。", "type": "module", "main": "./index.mjs", diff --git a/src/baizhi/credits.mjs b/src/baizhi/credits.mjs index 4ff9500..ec4840d 100644 --- a/src/baizhi/credits.mjs +++ b/src/baizhi/credits.mjs @@ -76,12 +76,46 @@ function readCaptchaToken(data) { return token.length === 0 ? undefined : token } +/** + * 报文是不是在要求人机验证:`captcha_required === true`,或直接下发了 `captcha` 对象 + * (上游回落的点选图片验证码,`{ id, master_image, thumb_image, width, height }`)。 + */ +function needsCaptcha(value) { + if (readBoolField(value, "captcha_required") === true) return true + const captcha = value.captcha + return captcha !== null && typeof captcha === "object" +} + +/** + * `claimed:false` 的三种含义必须分开判,不能一律当「今日已领取」(#13): + * + * ① 上游要求人机验证(`captcha_required` / `captcha`)—— 这次**没领到**,要人去控制台手动领; + * ② 并发幂等 —— 回读钱包确认:今天确实已领取,或 temporary 余额比领取前多了; + * ③ 上游只是没发积分 —— 这是失败。报成「已领取」会让宿主当天不再重试, + * 额度卡片也永远不出「每日积分」行(`readUsage` 只在 temporary > 0 时建这个窗口)。 + */ +async function classifyUnclaimedClaim({ value, walletBefore, cookie, site, fetchImpl, timeoutMs }) { + if (needsCaptcha(value)) { + return { kind: "captcha", message: "上游要求图片验证码,请到 https://baizhi.cloud/console 手动领取每日积分" } + } + const walletAfter = await fetchWallet(cookie, site, { fetchImpl, timeoutMs }) + if (walletAfter.ok + && (walletAfter.wallet.dailyClaimed || walletAfter.wallet.temporary > walletBefore.temporary)) { + return { kind: "already-claimed", message: "今日已领取" } + } + return { + kind: "failed", + message: "领取每日积分没有生效(上游返回 claimed:false),请稍后重试或到控制台手动领取", + } +} + /** * 领取每日积分:钱包幂等状态 → challenge → 本地 PoW → redeem → daily-temporary-credit。 * - * 已领取 / 领取前钱包失败时绝不发 POST。`claimed:false` 是并发下另一会话已领取的 - * 幂等结果,不是失败。实际到账只认领取前后 `temporary_credit_cents` 的正差额; - * 上游报文没有金额、复读钱包失败或没有正差额时,只报告通用成功,不硬编码 100。 + * 已领取 / 领取前钱包失败时绝不发 POST。只有 `claimed:true` 是本次真的领取成功; + * `claimed:false` 按 {@link classifyUnclaimedClaim} 分 captcha / already-claimed / failed。 + * 实际到账只认领取前后 `temporary_credit_cents` 的正差额;上游报文没有金额、 + * 复读钱包失败或没有正差额时,只报告通用成功,不硬编码 100。 */ export async function claimDailyCredit(credential, site, { fetchImpl = fetch, timeoutMs = 10_000 } = {}) { const cookie = cookieOf(credential, site.sessionCookies, site.sessionCookie) @@ -139,7 +173,16 @@ export async function claimDailyCredit(credential, site, { fetchImpl = fetch, ti const claimEnvelope = unwrapEnvelope(claimResult.data) if (!claimEnvelope.ok) return { kind: "failed", message: `领取每日积分失败:${claimEnvelope.error}` } const claimed = readBoolField(claimEnvelope.value, "claimed") - if (claimed === false) return { kind: "already-claimed", message: "今日已领取" } + if (claimed === false) { + return await classifyUnclaimedClaim({ + value: claimEnvelope.value, + walletBefore: walletBefore.wallet, + cookie, + site, + fetchImpl, + timeoutMs, + }) + } if (claimed !== true) { return { kind: "failed", message: "领取每日积分的响应里没有明确的 claimed 布尔值(上游形态可能已变)" } } diff --git a/src/browser-login.mjs b/src/browser-login.mjs index 03ac038..1a6c56f 100644 --- a/src/browser-login.mjs +++ b/src/browser-login.mjs @@ -6,7 +6,10 @@ // 设计取舍(来自 WPS 灵犀 0.4.11 的实测实现,MIT;见 NOTICE.md): // · 任意 Chromium 内核浏览器都行(Chrome / Edge / 360 / QQ / Brave / Vivaldi…), // 不止 Chrome;国产浏览器在 Windows 上很常见,漏了它们这条登录路对用户就不存在。 -// · Windows 的候选顺序:Chrome → 国产 Chromium → Edge 最后(Edge 策略最多、最容易被组织禁用)。 +// · Windows 先看系统默认浏览器(UserChoice 的 ProgId),默认不可用再退回 +// Chrome → 国产 Chromium → Edge 的顺序(Edge 策略最多、最容易被组织禁用)。 +// · 夸克 / UC 这类「能开调试端口、但会自己回收 CDP 目标」的浏览器一律殿后, +// 只有没有别的可用候选时才用(issue #7)。 // · 用一次性 user-data-dir,不碰用户日常浏览器配置;登录态只在本次窗口里。 // · 退出码不可靠:浏览器可能把调试参数吞掉,所以以「CDP 端口能不能连上」为准。 // @@ -39,6 +42,62 @@ const WIN_EXES = [ "msedge.exe", ] +/** + * 已知 CDP 不可靠的浏览器:能开调试端口,但会把自己的内部页塞进 `/json/list`, + * 并把插件已经连上的 page 目标回收掉(issue #7 实测:夸克约 10 秒)。 + * 排序时一律殿后 —— 只有没有别的可用候选时才用它们。 + */ +export const UNRELIABLE_CDP_EXES = ["quark.exe", "ucbrowser.exe"] + +/** 候选 exe 的规范显示名(注册表命中原先直接显示小写 exe 名)。 */ +const WIN_EXE_NAMES = new Map([ + ["chrome.exe", "Chrome"], + ["msedge.exe", "Edge"], + ["chromium.exe", "Chromium"], + ["brave.exe", "Brave"], + ["vivaldi.exe", "Vivaldi"], + ["opera.exe", "Opera"], + ["360chromex.exe", "360极速浏览器X"], + ["360chrome.exe", "360浏览器"], + ["360se.exe", "360安全浏览器"], + ["qqbrowser.exe", "QQ浏览器"], + ["sogouexplorer.exe", "搜狗浏览器"], + ["2345explorer.exe", "2345浏览器"], + ["liebao.exe", "猎豹浏览器"], + ["maxthon.exe", "Maxthon"], + ["ucbrowser.exe", "UC浏览器"], + ["quark.exe", "夸克浏览器"], +]) + +/** + * ProgId 前缀 → exe。覆盖 issue #7 点名的最小集合(Edge / Chrome / Brave / + * Firefox / 360 / QQ),另加 Opera / Vivaldi / Chromium / 搜狗等常见值。 + * 未知 ProgId 返回空串。 + */ +const PROGID_RULES = [ + [/^(microsoftedge|msedge)/, "msedge.exe"], + [/^(chrome|chromium)/, "chrome.exe"], + [/^brave/, "brave.exe"], + [/^firefox/, "firefox.exe"], + [/^opera/, "opera.exe"], + [/^vivaldi/, "vivaldi.exe"], + [/^sogou/, "SogouExplorer.exe"], + [/^maxthon/, "Maxthon.exe"], + [/^liebao/, "liebao.exe"], + [/^(qqbrowser|tencentqq)/, "QQBrowser.exe"], + [/^uc/, "UCBrowser.exe"], + [/^quark/, "Quark.exe"], + [/^360.*chromex/, "360ChromeX.exe"], + [/^360.*chrom/, "360chrome.exe"], + [/^360/, "360se.exe"], +] + +/** Firefox 不支持 CDP:默认浏览器是它时按「没有默认」处理。 */ +const CDP_UNSUPPORTED_EXES = new Set(["firefox.exe"]) + +/** 系统默认浏览器(http)的 UserChoice 键。 */ +const USER_CHOICE_KEY = "HKCU\\SOFTWARE\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice" + /** Windows 注册表 App Paths 查浏览器;查不到返回空串。 */ export function registryAppPath(exe) { if (process.platform !== "win32") return "" @@ -58,12 +117,103 @@ export function registryAppPath(exe) { return "" } +/** 读一条 REG_SZ 注册表值;查不到返回空串(不抛)。测试可注入替代实现。 */ +function registryValue(key, name) { + if (process.platform !== "win32") return "" + try { + const out = execFileSync("reg", ["query", key, "/v", name], { encoding: "utf8", timeout: 5000 }) + const line = out.split(/\r?\n/).find((l) => /REG_SZ/i.test(l) && l.toLowerCase().includes(name.toLowerCase())) + return line?.split(/REG_SZ/i)[1]?.trim() ?? "" + } catch { + return "" + } +} + +/** + * ProgId → exe 名(纯函数)。例如 `MSEdgeHTM` → `msedge.exe`。 + * @param {string} progId `UrlAssociations\http\UserChoice` 的 ProgId + * @returns {string} 未知 / 空值返回空串 + */ +export function exeForProgId(progId) { + const id = String(progId ?? "").trim().toLowerCase() + if (id.length === 0) return "" + for (const [pattern, exe] of PROGID_RULES) { + if (pattern.test(id)) return exe + } + return "" +} + +/** + * Windows 系统默认浏览器的 exe(UserChoice 的 ProgId → exe)。 + * + * 只返回能走 CDP 的浏览器:默认是 Firefox 时按「没有默认」处理,交回候选表, + * 免得把一条注定读不到 cookie 的路排到最前。 + * + * @param {{platform?:string, query?:(key:string,name:string)=>string}} [o] + * @returns {string} 如 `msedge.exe`;没有 / 解析不出 / 不支持 CDP 时为空串 + */ +export function systemDefaultBrowserExe({ platform = process.platform, query = registryValue } = {}) { + if (platform !== "win32") return "" + const exe = exeForProgId(query(USER_CHOICE_KEY, "ProgId")) + if (!exe) return "" + return CDP_UNSUPPORTED_EXES.has(exe.toLowerCase()) ? "" : exe +} + +/** 路径 → 小写 exe 名(排序按 exe 而不是完整路径,注册表命中与标准路径才对得上)。 */ +export function exeNameOf(path) { + const clean = String(path ?? "").trim().replace(/^"(.*)"$/, "$1") + const base = clean.split(/[\\/]/).pop() ?? "" + return base.toLowerCase() +} + +function displayNameForExe(exe) { + const key = String(exe ?? "").trim().toLowerCase() + return WIN_EXE_NAMES.get(key) ?? key.replace(/\.exe$/, "") +} + +/** + * 候选排序(纯函数,不做任何 IO)。 + * + * 优先级:默认浏览器(存在)→ 其他可靠浏览器(存在)→ 可靠但不存在 → + * 默认但不存在 → 已知 CDP 不可靠(存在)→ 不可靠且不存在。 + * 同档保持传入顺序;返回新数组,不改入参。 + * + * @param {object} [o] + * @param {{name:string, path:string}[]} [o.candidates] + * @param {string} [o.defaultExe] 系统默认浏览器的 exe 名(如 `msedge.exe`) + * @param {(path:string)=>boolean} [o.exists] 存在性探测(单测注入假实现) + * @param {string[]} [o.unreliableExes] 已知 CDP 不可靠的 exe 名单 + * @returns {{name:string, path:string}[]} + */ +export function rankBrowserCandidates({ + candidates = [], + defaultExe = "", + exists = () => true, + unreliableExes = UNRELIABLE_CDP_EXES, +} = {}) { + const preferred = String(defaultExe ?? "").trim().toLowerCase() + const unreliable = new Set((unreliableExes ?? []).map((exe) => String(exe ?? "").trim().toLowerCase())) + const scoreOf = (candidate) => { + const missing = exists(candidate?.path) ? 0 : 1 + const exe = exeNameOf(candidate?.path) + // 不可靠浏览器永远殿后:就算系统默认是夸克,也不能让它进第一梯队。 + if (unreliable.has(exe)) return missing === 0 ? 4 : 5 + if (preferred && exe === preferred) return missing === 0 ? 0 : 3 + return missing === 0 ? 1 : 2 + } + return candidates + .map((candidate, index) => ({ candidate, index, score: scoreOf(candidate) })) + .sort((a, b) => a.score - b.score || a.index - b.index) + .map((entry) => entry.candidate) +} + /** * 候选浏览器(按优先级)。不做存在性检查,方便测试与排序。 - * @param {{platform?:string, env?:Record, lookup?:(exe:string)=>string}} [o] + * @param {{platform?:string, env?:Record, lookup?:(exe:string)=>string, defaultExe?:string}} [o] + * @param {string} [o.defaultExe] 系统默认浏览器 exe;命中的排最前(夸克 / UC 除外) * @returns {{name:string, path:string}[]} */ -export function browserCandidates({ platform = process.platform, env = process.env, lookup = registryAppPath } = {}) { +export function browserCandidates({ platform = process.platform, env = process.env, lookup = registryAppPath, defaultExe = "" } = {}) { const h = env.HOME || env.USERPROFILE || "" const local = env.LOCALAPPDATA || "" const roaming = env.APPDATA || "" @@ -77,7 +227,7 @@ export function browserCandidates({ platform = process.platform, env = process.e const list = [] for (const exe of WIN_EXES) { const fromRegistry = lookup(exe) - if (fromRegistry) add(list, exe.replace(/\.exe$/i, ""), fromRegistry) + if (fromRegistry) add(list, displayNameForExe(exe), fromRegistry) } add(list, "Chrome", join(pf, "Google", "Chrome", "Application", "chrome.exe")) add(list, "Chrome", join(pf86, "Google", "Chrome", "Application", "chrome.exe")) @@ -101,7 +251,14 @@ export function browserCandidates({ platform = process.platform, env = process.e add(list, "夸克浏览器", join(local, "Quark", "Quark.exe")) add(list, "Edge", join(pf86, "Microsoft", "Edge", "Application", "msedge.exe")) add(list, "Edge", join(pf, "Microsoft", "Edge", "Application", "msedge.exe")) - return dedupe(list) + // 默认浏览器不在候选表里时(只写了 App Paths、又不在上面的标准位置)补一条。 + // 仍然交给 rank 排序:夸克就算被设为默认,也不该进第一梯队。 + const preferred = String(defaultExe ?? "").trim().toLowerCase() + if (preferred && !list.some((b) => exeNameOf(b.path) === preferred)) { + const fromRegistry = lookup(defaultExe) + if (fromRegistry) add(list, displayNameForExe(defaultExe), fromRegistry) + } + return dedupe(rankBrowserCandidates({ candidates: list, defaultExe: preferred, exists: () => true })) } if (platform === "darwin") { @@ -133,9 +290,24 @@ function dedupe(list) { }) } -/** 第一个真实存在的候选;没有返回 null。 */ -export function findBrowser({ platform = process.platform, env = process.env, exists = existsSync, lookup = registryAppPath } = {}) { - return browserCandidates({ platform, env, lookup }).find((b) => exists(b.path)) ?? null +/** + * 第一个真实存在的候选;没有返回 null。 + * + * @param {object} [o] + * @param {(key:string,name:string)=>string} [o.query] 注册表探测(单测注入,默认真读) + * @param {string} [o.defaultExe] 强制指定默认浏览器 exe(传 "" 表示不探测默认浏览器) + */ +export function findBrowser({ + platform = process.platform, + env = process.env, + exists = existsSync, + lookup = registryAppPath, + query, + defaultExe, +} = {}) { + const preferred = defaultExe ?? (platform === "win32" ? systemDefaultBrowserExe({ platform, query }) : "") + const candidates = browserCandidates({ platform, env, lookup, defaultExe: preferred }) + return rankBrowserCandidates({ candidates, defaultExe: preferred, exists }).find((b) => exists(b.path)) ?? null } /** 从 CDP 的 cookie 列表里挑需要的名字;返回 header 字符串与命中的键。 */ @@ -178,6 +350,42 @@ async function getJson(url, timeoutMs = 5000) { return res.json() } +/** + * CDP 调试端口是否还活着(窗口是否真的是被用户关掉的判据之一)。 + * + * 目标被浏览器自己回收时,WS 会断,但浏览器进程和调试端口都还在 —— + * 「窗口被关掉了」的文案在这个场景下会把用户引向错误方向。 + * + * @param {number} port `--remote-debugging-port` 的端口 + * @param {{running?:()=>boolean, fetchJson?:Function, timeoutMs?:number}} [o] + */ +export async function cdpEndpointAlive(port, { running = () => true, fetchJson = getJson, timeoutMs = 1200 } = {}) { + if (!port || !running()) return false + try { + await fetchJson(`http://127.0.0.1:${port}/json/list`, timeoutMs) + return true + } catch { + return false + } +} + +/** + * 「调试目标丢了」的可读原因(纯函数)。 + * + * - 端口还响应 ⇒ 窗口还开着,是浏览器自己回收了 CDP 目标(夸克 / UC 这类): + * 给能行动的文案,别再让用户以为自己关掉了窗口; + * - 端口也不响应 ⇒ 保持原来的「窗口被关掉了」文案。 + * + * @param {{endpointAlive?:boolean, browser?:{name?:string}}} [o] + */ +export function browserLossMessage({ endpointAlive = false, browser } = {}) { + if (endpointAlive) { + const who = browser?.name ? `「${browser.name}」` : "这个浏览器" + return `${who}会自己关闭自动化窗口(调试目标被浏览器回收),请换用 Edge 或 Chrome 再试` + } + return "受控浏览器窗口被关掉了(或被系统拦下没能启动)" +} + function cdpSend(ws, id, method, params = {}) { return new Promise((resolve, reject) => { const onMessage = (event) => { diff --git a/src/session-login.mjs b/src/session-login.mjs index ed489c4..7316b02 100644 --- a/src/session-login.mjs +++ b/src/session-login.mjs @@ -22,7 +22,7 @@ import { createServer } from "node:net" import { homedir, tmpdir } from "node:os" import { join } from "node:path" -import { findBrowser } from "./browser-login.mjs" +import { browserLossMessage, cdpEndpointAlive, findBrowser } from "./browser-login.mjs" /** 默认等用户登录的上限(毫秒)。 */ export const BROWSER_LOGIN_TIMEOUT_MS = 240_000 @@ -186,7 +186,15 @@ export async function openControlledBrowser({ url = "about:blank", profileDir, h await cdpSend(ws, 0, "Page.enable").catch(() => {}) await cdpSend(ws, -1, "Page.navigate", { url }).catch(() => {}) } - return { ws, close, profileDir: profile, persistent } + return { + ws, + close, + profileDir: profile, + persistent, + // 「窗口被关」和「浏览器自己回收了 CDP 目标」要分开报:后者窗口还开着。 + debugPort: port, + running: () => child.exitCode === null && child.signalCode === null, + } } /** @@ -312,7 +320,12 @@ export async function startBrowserLogin({ try { while (Date.now() < deadline) { if (signal?.aborted) throw new Error("登录已取消") - if (closed()) throw new Error("受控浏览器窗口被关掉了(或被系统拦下没能启动)") + if (closed()) { + // 先分清是用户关了窗口,还是浏览器自己把 CDP 目标回收了(夸克 / UC)。 + // 后者的窗口还开着,沿用「窗口被关掉了」会把用户引向错误的方向。 + const endpointAlive = await cdpEndpointAlive(handle.debugPort, { running: handle.running }) + throw new Error(browserLossMessage({ endpointAlive, browser })) + } if (typeof onPoll === "string" && onPoll.length > 0) { await cdpSend(handle.ws, pollId++, "Runtime.evaluate", { expression: onPoll, returnByValue: true }).catch(() => {}) } diff --git a/tests/baizhi.test.mjs b/tests/baizhi.test.mjs index e5ee4d3..5eb69ef 100644 --- a/tests/baizhi.test.mjs +++ b/tests/baizhi.test.mjs @@ -78,6 +78,33 @@ function claimChainHandler({ claimed = true, onClaim } = {}) { } } +/** + * 「只有领取环节可变」的假链:钱包按顺序回 `wallets` 里的读数,challenge / redeem 恒成功, + * 领取 POST 回 `claimValue`。全部离线,`fetchImpl` 直接注入。 + */ +function scriptedClaimFetch({ wallets, claimValue }) { + const calls = [] + let walletIndex = 0 + const fetchImpl = async (url, init = {}) => { + const path = new URL(url).pathname + calls.push(`${init.method ?? "GET"} ${path}`) + if (path === BAIZHI.walletBalancePath) { + const wallet = wallets[Math.min(walletIndex, wallets.length - 1)] + walletIndex += 1 + return walletResponse(wallet) + } + if (path === "/api/v1/public/captcha/challenge") { + return Response.json({ code: 0, data: { token: "challenge-token", challenge: { c: 1, s: 1, d: 1 } } }) + } + if (path === "/api/v1/public/captcha/redeem") { + return Response.json({ code: 0, data: { success: true, token: "captcha-token" } }) + } + if (path === DAILY_CREDIT_PATH) return Response.json({ code: 0, data: claimValue }) + throw new Error(`unexpected ${url}`) + } + return { fetchImpl, calls } +} + test("凭据:裸 sk- key 就能用,也接受带 session_cookie 的 JSON", () => { assert.deepEqual(parseCredential(KEY), { access_token: KEY }) const withCookie = JSON.stringify({ access_token: KEY, session_cookie: "sess" }) @@ -255,13 +282,130 @@ test("每日积分:完整成功链的 endpoint / body / 顺序正确,到账 }) }) -test("每日积分:领取响应 claimed=false 是并发幂等已领取,checkin 回 claimed", async () => { +test("每日积分:claimed=false 而余额已增加 ⇒ 并发幂等已领取,checkin 回 claimed", async () => { const plugin = await makeBaizhiPlugin()({ client: {} }) await withFetch(claimChainHandler({ claimed: false }), async (calls) => { const outcome = await plugin.auth.checkin(async () => sessionAuth()) assert.deepEqual(outcome, { outcome: "claimed", message: "今日已领取" }) - assert.equal(calls.length, 4, "claimed=false 不再复读钱包,也不能当成失败重发") - assert.equal(calls.filter((call) => new URL(call.url).pathname === DAILY_CREDIT_PATH).length, 1) + assert.equal(calls.length, 5, "claimed=false 必须回读钱包确认,不能凭报文就当已领取") + assert.equal( + calls.filter((call) => new URL(call.url).pathname === BAIZHI.walletBalancePath).length, + 2, + "领取前后各读一次钱包", + ) + assert.equal( + calls.filter((call) => new URL(call.url).pathname === DAILY_CREDIT_PATH).length, + 1, + "确认已到账就不重发领取", + ) + }) +}) + +test("每日积分 #13:claimed=false + captcha_required ⇒ captcha,绝不误报「今日已领取」", async () => { + const { fetchImpl, calls } = scriptedClaimFetch({ + wallets: [{ dailyClaimed: false, temporaryCents: 0 }], + claimValue: { + claimed: false, + amount_credit_cents: 0, + expires_at: "0001-01-01T00:00:00Z", + captcha_required: true, + captcha: { + id: "captcha-1", + master_image: "data:image/jpeg;base64,AAAA", + thumb_image: "data:image/jpeg;base64,BBBB", + width: 300, + height: 150, + }, + }, + }) + const result = await claimDailyCredit(sessionCredential(), BAIZHI, { fetchImpl }) + assert.deepEqual(result, { + kind: "captcha", + message: "上游要求图片验证码,请到 https://baizhi.cloud/console 手动领取每日积分", + }) + assert.deepEqual(calls, [ + `GET ${BAIZHI.walletBalancePath}`, + "POST /api/v1/public/captcha/challenge", + "POST /api/v1/public/captcha/redeem", + `POST ${DAILY_CREDIT_PATH}`, + ], "要求验证码时既不复读钱包,也不重发领取") +}) + +test("每日积分 #13:只带 captcha 对象、没有 captcha_required 也算要验证码", async () => { + const { fetchImpl } = scriptedClaimFetch({ + wallets: [{ dailyClaimed: false, temporaryCents: 0 }], + claimValue: { claimed: false, captcha: { id: "captcha-2", width: 300, height: 150 } }, + }) + const result = await claimDailyCredit(sessionCredential(), BAIZHI, { fetchImpl }) + assert.equal(result.kind, "captcha") + assert.match(result.message, /图片验证码.*baizhi\.cloud\/console/) +}) + +test("每日积分 #13:claimed=false 但钱包 dailyClaimed=true ⇒ already-claimed", async () => { + const { fetchImpl, calls } = scriptedClaimFetch({ + wallets: [ + { dailyClaimed: false, temporaryCents: 0 }, + { dailyClaimed: true, temporaryCents: 0 }, + ], + claimValue: { claimed: false }, + }) + const result = await claimDailyCredit(sessionCredential(), BAIZHI, { fetchImpl }) + assert.deepEqual(result, { kind: "already-claimed", message: "今日已领取" }) + assert.equal(calls.filter((call) => call === `GET ${BAIZHI.walletBalancePath}`).length, 2) +}) + +test("每日积分 #13:claimed=false 但 temporary 余额增加 ⇒ already-claimed", async () => { + const { fetchImpl } = scriptedClaimFetch({ + wallets: [ + { dailyClaimed: false, temporaryCents: 0 }, + { dailyClaimed: false, temporaryCents: 10_000 }, + ], + claimValue: { claimed: false }, + }) + const result = await claimDailyCredit(sessionCredential(), BAIZHI, { fetchImpl }) + assert.deepEqual(result, { kind: "already-claimed", message: "今日已领取" }) +}) + +test("每日积分 #13:claimed=false 且钱包也没到账 ⇒ failed,宿主当天还能重试", async () => { + const plugin = await makeBaizhiPlugin()({ client: {} }) + const chain = () => scriptedClaimFetch({ + wallets: [ + { dailyClaimed: false, temporaryCents: 0 }, + { dailyClaimed: false, temporaryCents: 0 }, + ], + claimValue: { claimed: false, amount_credit_cents: 0, captcha_required: false }, + }) + + const direct = chain() + const result = await claimDailyCredit(sessionCredential(), BAIZHI, { fetchImpl: direct.fetchImpl }) + assert.deepEqual(result, { + kind: "failed", + message: "领取每日积分没有生效(上游返回 claimed:false),请稍后重试或到控制台手动领取", + }) + assert.equal( + direct.calls.filter((call) => call === `GET ${BAIZHI.walletBalancePath}`).length, + 2, + "判失败前必须回读钱包确认真的没到账", + ) + + const hooked = chain() + await withFetch(hooked.fetchImpl, async () => { + const outcome = await plugin.auth.checkin(async () => sessionAuth()) + assert.equal(outcome.outcome, "failed", "只有 claimed / already-claimed 才允许记成当天已完成") + assert.match(outcome.message, /没有生效|手动领取/) + }) +}) + +test("每日积分 #13:checkin 把要图片验证码的领取如实报成 captcha", async () => { + const plugin = await makeBaizhiPlugin()({ client: {} }) + const { fetchImpl } = scriptedClaimFetch({ + wallets: [{ dailyClaimed: false, temporaryCents: 0 }], + claimValue: { claimed: false, captcha_required: true, captcha: { id: "captcha-3" } }, + }) + await withFetch(fetchImpl, async () => { + const outcome = await plugin.auth.checkin(async () => sessionAuth()) + assert.equal(outcome.outcome, "captcha") + assert.match(outcome.message, /图片验证码/) }) }) diff --git a/tests/browser-candidates.test.mjs b/tests/browser-candidates.test.mjs new file mode 100644 index 0000000..8c83ac8 --- /dev/null +++ b/tests/browser-candidates.test.mjs @@ -0,0 +1,182 @@ +// 浏览器候选排序的离线单测(issue #7): +// 全部靠注入的注册表 / 存在性探测结果,不读真注册表、不启动浏览器。 +import test from "node:test" +import assert from "node:assert/strict" + +const { + browserCandidates, + findBrowser, + rankBrowserCandidates, + exeForProgId, + systemDefaultBrowserExe, + exeNameOf, + browserLossMessage, + cdpEndpointAlive, +} = await import("../src/browser-login.mjs") + +const ENV = { + LOCALAPPDATA: "C:\\Users\\x\\AppData\\Local", + APPDATA: "C:\\Users\\x\\AppData\\Roaming", + PROGRAMFILES: "C:\\Program Files", + "PROGRAMFILES(X86)": "C:\\Program Files (x86)", +} +const EDGE = "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" +const CHROME = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" +const QUARK = "C:\\Users\\x\\AppData\\Local\\Quark\\Quark.exe" +const UC = "C:\\Users\\x\\AppData\\Local\\UCBrowser\\Application\\UCBrowser.exe" + +/** 假注册表:exe → App Paths 命中;未列出的 exe 一律查不到。 */ +const winLookup = (paths) => (exe) => paths[String(exe).toLowerCase()] ?? "" + +test("ProgId → exe:覆盖 issue #7 点名的默认浏览器", () => { + assert.equal(exeForProgId("MSEdgeHTM"), "msedge.exe") + assert.equal(exeForProgId("ChromeHTML"), "chrome.exe") + assert.equal(exeForProgId("BraveHTML"), "brave.exe") + assert.equal(exeForProgId("FirefoxURL-308046B0AF4A39CB"), "firefox.exe") + assert.equal(exeForProgId("360se6URL"), "360se.exe") + assert.equal(exeForProgId("360ChromeHTML"), "360chrome.exe") + assert.equal(exeForProgId("QQBrowserHTML"), "QQBrowser.exe") + assert.equal(exeForProgId(""), "") + assert.equal(exeForProgId("SomeUnknownBrowserHTML"), "") +}) + +test("systemDefaultBrowserExe:读 http 的 UserChoice;Firefox 不支持 CDP 就跳过", () => { + const calls = [] + const query = (key, name) => { + calls.push([key, name]) + return key.includes("UrlAssociations\\http\\UserChoice") && name === "ProgId" ? "MSEdgeHTM" : "" + } + assert.equal(systemDefaultBrowserExe({ platform: "win32", query }), "msedge.exe") + assert.equal(calls.length, 1, "只该查一次 UserChoice") + assert.match(calls[0][0], /UrlAssociations\\http\\UserChoice$/, "必须读 http 协议的 UserChoice") + assert.equal(calls[0][1], "ProgId") + + assert.equal(systemDefaultBrowserExe({ platform: "win32", query: () => "ChromeHTML" }), "chrome.exe") + assert.equal(systemDefaultBrowserExe({ platform: "win32", query: () => "FirefoxURL" }), "", "Firefox 没有 CDP") + assert.equal(systemDefaultBrowserExe({ platform: "win32", query: () => "" }), "") + assert.equal(systemDefaultBrowserExe({ platform: "darwin", query: () => "ChromeHTML" }), "") +}) + +test("rankBrowserCandidates:默认浏览器排最前,且不能压过「真实存在」这一条", () => { + const candidates = [ + { name: "Chrome", path: CHROME }, + { name: "Edge", path: EDGE }, + { name: "Quark", path: QUARK }, + ] + const ranked = rankBrowserCandidates({ candidates, defaultExe: "msedge.exe", exists: () => true }) + assert.deepEqual(ranked.map((b) => b.name), ["Edge", "Chrome", "Quark"]) + assert.deepEqual(candidates.map((b) => b.name), ["Chrome", "Edge", "Quark"], "不能改入参顺序") + + // 默认浏览器没装:存在的 Chrome 必须排在它前面。 + const noEdge = rankBrowserCandidates({ candidates, defaultExe: "msedge.exe", exists: (p) => p === CHROME }) + assert.deepEqual(noEdge.map((b) => b.name), ["Chrome", "Edge", "Quark"]) +}) + +test("rankBrowserCandidates:夸克 / UC 永远殿后,哪怕系统默认就是夸克", () => { + const candidates = [ + { name: "Quark", path: QUARK }, + { name: "Chrome", path: CHROME }, + { name: "UC", path: UC }, + ] + const ranked = rankBrowserCandidates({ candidates, defaultExe: "quark.exe", exists: () => true }) + assert.deepEqual(ranked.map((b) => b.name), ["Chrome", "Quark", "UC"]) + + // 没有别的可用候选时,它们仍在队尾 —— 但 findBrowser 会兜底选到(下一条用例)。 + const onlyUnreliable = rankBrowserCandidates({ candidates, exists: (p) => p === QUARK || p === UC }) + assert.deepEqual(onlyUnreliable.map((b) => b.name), ["Chrome", "Quark", "UC"], "不可靠的排在所有可靠候选之后") +}) + +test("browserCandidates:默认浏览器排最前,夸克靠注册表命中也不进第一梯队", () => { + const lookup = winLookup({ "chrome.exe": CHROME, "msedge.exe": EDGE, "quark.exe": QUARK }) + const list = browserCandidates({ platform: "win32", env: ENV, lookup, defaultExe: "msedge.exe" }) + + assert.equal(exeNameOf(list[0].path), "msedge.exe", "系统默认浏览器应排最前") + assert.ok( + list.some((b) => exeNameOf(b.path) === "chrome.exe"), + "其他可靠浏览器仍在候选里", + ) + const tail = list.slice(-2).map((b) => exeNameOf(b.path)).sort() + assert.deepEqual(tail, ["quark.exe", "ucbrowser.exe"], "夸克 / UC 只能殿后") + assert.equal(list.filter((b) => b.path === QUARK).length, 1, "同一路径不能重复") + assert.ok(list.every((b) => b.path.length > 0), "候选不应有空路径") + + // 没有默认浏览器信息(探测失败 / 非 Windows)时保持原来的顺序。 + const legacy = browserCandidates({ platform: "win32", env: ENV, lookup }) + assert.equal(exeNameOf(legacy[0].path), "chrome.exe") + assert.deepEqual( + legacy.slice(-2).map((b) => exeNameOf(b.path)).sort(), + ["quark.exe", "ucbrowser.exe"], + ) +}) + +test("browserCandidates:默认 exe 不在候选表里时用 App Paths 补一条", () => { + const firefox = "C:\\Program Files\\Mozilla Firefox\\firefox.exe" + const list = browserCandidates({ + platform: "win32", + env: ENV, + lookup: winLookup({ "firefox.exe": firefox }), + defaultExe: "firefox.exe", + }) + assert.equal(list[0].path, firefox) + assert.equal(exeNameOf(list[0].path), "firefox.exe") +}) + +test("findBrowser:默认是 Edge 时不再被夸克的注册表命中抢走(issue #7 的机器)", () => { + const lookup = winLookup({ "quark.exe": QUARK, "msedge.exe": EDGE }) + const exists = (p) => p === QUARK || p === EDGE + const found = findBrowser({ + platform: "win32", + env: {}, + lookup, + exists, + query: () => "MSEdgeHTM", + }) + assert.equal(found?.path, EDGE) + assert.equal(found?.name, "Edge") +}) + +test("findBrowser:没有别的可用候选时才退回夸克;Firefox 默认不参与", () => { + const lookup = winLookup({ "quark.exe": QUARK }) + const exists = (p) => p === QUARK + + const edgeDefault = findBrowser({ platform: "win32", env: {}, lookup, exists, query: () => "MSEdgeHTM" }) + assert.equal(edgeDefault?.path, QUARK, "只剩夸克时仍要能用(最后兜底)") + + const firefoxDefault = findBrowser({ platform: "win32", env: {}, lookup, exists, query: () => "FirefoxURL" }) + assert.equal(firefoxDefault?.path, QUARK, "Firefox 不算可用默认,应回落到普通候选") +}) + +test("browserLossMessage:区分「浏览器回收目标」与「窗口被关」", () => { + const lost = browserLossMessage({ endpointAlive: true, browser: { name: "夸克浏览器" } }) + assert.match(lost, /夸克浏览器/) + assert.match(lost, /Edge/) + assert.match(lost, /Chrome/) + assert.ok(!lost.includes("窗口被关掉了"), "目标被回收时不能再说窗口被关") + + const closed = "受控浏览器窗口被关掉了(或被系统拦下没能启动)" + assert.equal(browserLossMessage({ endpointAlive: false, browser: { name: "Edge" } }), closed) + assert.equal(browserLossMessage(), closed) +}) + +test("cdpEndpointAlive:进程没了直接 false;端口还响应才算目标丢失", async () => { + let calls = 0 + const fetchJson = async () => { + calls += 1 + return [] + } + assert.equal(await cdpEndpointAlive(9222, { running: () => false, fetchJson }), false) + assert.equal(calls, 0, "进程已退出就不该再探端口") + assert.equal(await cdpEndpointAlive(0, { running: () => true, fetchJson }), false) + assert.equal(calls, 0, "没有端口也不探") + assert.equal(await cdpEndpointAlive(9222, { running: () => true, fetchJson }), true) + assert.equal(calls, 1) + assert.equal( + await cdpEndpointAlive(9222, { + running: () => true, + fetchJson: async () => { + throw new Error("ECONNREFUSED") + }, + }), + false, + ) +})