Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

**修:平台取消基础用户日额度之后,额度卡片整张变错误态**
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
51 changes: 47 additions & 4 deletions src/baizhi/credits.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 布尔值(上游形态可能已变)" }
}
Expand Down
224 changes: 216 additions & 8 deletions src/browser-login.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 端口能不能连上」为准。
//
Expand Down Expand Up @@ -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 ""
Expand All @@ -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<string,string>, lookup?:(exe:string)=>string}} [o]
* @param {{platform?:string, env?:Record<string,string>, 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 || ""
Expand All @@ -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"))
Expand All @@ -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") {
Expand Down Expand Up @@ -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 字符串与命中的键。 */
Expand Down Expand Up @@ -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) => {
Expand Down
Loading
Loading