diff --git a/packages/astudio/README.md b/packages/astudio/README.md index 9c11eeb..848fe31 100644 --- a/packages/astudio/README.md +++ b/packages/astudio/README.md @@ -1,6 +1,6 @@ # @magpie-community/opencode-astudio-auth -把 **AStudio(科大讯飞 Astron Studio 桌面端)** 的账号额度接入 [magpie](https://usemagpie.ai/) 与 [OpenCode](https://opencode.ai/):复用桌面端登录态,直连云端模型网关(OpenAI Responses 协议),agent 以 `astudio/` 使用它的模型;支持每日登录积分自动签到与积分余额显示。 +把 **AStudio(科大讯飞 Astron Studio)** 的账号额度接入 [magpie](https://usemagpie.ai/) 与 [OpenCode](https://opencode.ai/):浏览器登录或复用桌面端登录态,直连云端模型网关(OpenAI Responses 协议),agent 以 `astudio/` 使用它的模型;支持每日登录积分自动签到、积分余额与到期时间显示,每个账号各占账号池一格。 ## 与 Providers Hub 的 `hub-astudio` 的区别 @@ -8,31 +8,33 @@ AStudio 在 registry 里有两个入口,都保留([#614](https://github.com/ | | 本包(`astudio`) | [magpie-providers-hub](https://www.npmjs.com/package/magpie-providers-hub)(`hub-astudio`) | | --- | --- | --- | -| 登录 | 读取本机 AStudio 桌面端的登录态,或粘贴 `modelBearerToken`;不需要再输手机号或密码 | 本机打开一个登录页:手机验证码、账号密码或微信扫码(含极验验证),不依赖桌面端 | -| 适合 | 装了 AStudio 桌面端的用户(数据目录按 `ASTUDIO_HOME`、Windows 注册表、`~/.acode` 查找;其他情况粘贴凭据) | 任何平台,没装桌面端也行 | +| 登录 | 浏览器登录(推荐,可多账号)、读取本机 AStudio 桌面端的登录态,或粘贴 `modelBearerToken` | 本机打开一个登录页:手机验证码、账号密码或微信扫码(含极验验证),不依赖桌面端 | +| 适合 | 装了桌面端就复用登录态;没装也可以用浏览器登录(可多账号);两者都不方便时粘贴凭据 | 任何平台,没装桌面端也行 | | 模型端点 | `…/model-gateway/v1/responses`(OpenAI Responses,与桌面端一致) | `…/model-gateway/v1/chat/completions` | -| 每日积分 | 做一次会话活跃,按前后余额差与 `client-popups/pending` 待通知弹窗记录,不调用领取接口 | 调用 `client-popups` 领取每日奖励和新人礼包弹窗 | +| 每日积分 | 先读当日获得流水(与网页后台「获得明细」同源):有当日 GRANT 行即已发放,此时一个写请求都不发;流水为空才做一次会话活跃再读流水,流水不可用才退回余额差 + `client-popups/pending` 弹窗观测;不调用领取接口 | 调用 `client-popups` 领取每日奖励和新人礼包弹窗 | 两者用同一个 AStudio 账号时,读的是同一个 `points/balance`,模型调用也扣同一份积分:**每日登录积分是一个池子,装两个不会多一份。** 同一账号两边都登录只会重复显示同一笔余额。 -English: two entries serve AStudio. This one reuses the AStudio desktop's -sign-in (or a pasted `modelBearerToken`) and calls the Responses endpoint; +English: two entries serve AStudio. This one signs in through a browser +(each account gets its own pool slot), reuses the AStudio desktop's sign-in, +or takes a pasted `modelBearerToken`, and calls the Responses endpoint; Providers Hub's `hub-astudio` signs in on a local page (SMS code, password or WeChat QR) and calls chat/completions. On one account both draw on the same daily points balance. ## 登录什么 -两种方式(登录时二选一): +三种方式(登录时选一种): -1. **读取 AStudio 桌面端登录态(推荐)**——本机装有 AStudio 桌面版并登录过即可,插件自动从它的数据目录读出模型凭据与网页会话(积分/签到用),不用填任何东西。没装/没登录时这一步会给出 [AStudio 官网](https://agent.xfyun.cn/) 链接并自动等待:装好登录后自动完成,不用回来点按钮。本机已有数据但读不出来(会话不是有效 JSON、没有凭据、账号被封禁)会直接说明原因,登录/修好后同样自动完成。数据目录按以下顺序查找: +1. **浏览器登录(推荐,可多账号)**——弹出的浏览器里登录讯飞账号(手机验证码或扫码),插件收割网页会话 Cookie(`ssoSessionId` + `account_id` 必需,`token` 有则一并带上),再调桌面端启动时的同款 `POST auth/bearer-token` 换发模型凭据(JWT,实测 3 年有效;换发后旧 token 仍可用)。不装桌面端也能用。每次登录用全新浏览器 profile,绝不带旧票;登录收尾后连 profile 一起删掉(会话已进账号 metadata,浏览器目录不留第二份凭据)。网页会话 Cookie 过期后积分/签到会提示重新登录(重新走一次浏览器登录即可;模型凭据是 3 年 JWT,聊天不受影响)。需要本机有 Chrome 或 Edge(或用 `ASTUDIO_CHROME_PATH` 指到可执行文件);profile 根目录是 `<配置目录>/magpie/astudio-browser-profiles`——Windows 为 `%APPDATA%`、macOS/Linux 为 `~/.config`(`XDG_CONFIG_HOME` 可改),`ASTUDIO_BROWSER_PROFILE` 可整体覆盖;登录收尾即删。 +2. **读取 AStudio 桌面端登录态**——本机装有 AStudio 桌面版并登录过即可,插件自动从它的数据目录读出模型凭据与网页会话(积分/签到用),不用填任何东西。没装/没登录时这一步会给出 [AStudio 官网](https://agent.xfyun.cn/) 链接并自动等待:装好登录后自动完成,不用回来点按钮。本机已有数据但读不出来(会话不是有效 JSON、没有凭据、账号被封禁)会直接说明原因,登录/修好后同样自动完成。数据目录按以下顺序查找: - `ASTUDIO_HOME`(或 `SYNARA_HOME`)环境变量指定的目录; - Windows 注册表 `HKCU\Software\AStudioStorage` 的 `Production/Canary/DevelopmentDataRoot`; - 兜底 `~/.acode/acode/`。 - 目标文件:`<数据根>/userdata/astron-session.json`(其次 `<数据根>/runtime/acode-home/config.toml`,该方式无网页会话,积分/签到不可用)。 -2. **粘贴 modelBearerToken**——从 `astron-session.json` 的 `modelBearerToken`(或 `config.toml` 的 `experimental_bearer_token`)复制粘贴;可选填账号面 `accountId` 与网页会话 `token`(两者齐才能用积分/签到,另有 `ssoSessionId`/uid 可选)。 +3. **粘贴 modelBearerToken**——从 `astron-session.json` 的 `modelBearerToken`(或 `config.toml` 的 `experimental_bearer_token`)复制粘贴;可选填账号面 `accountId` 与网页会话 `token`(两者齐才能用积分/签到,另有 `ssoSessionId`/uid 可选)。 -每个 AStudio 账号登录一次即得一个 magpie 账号,可多账号故障切换。凭据保存在 magpie 的 `plugin-auth.json`(权限 600),不上传。 +每个 AStudio 账号登录一次即得 magpie 账号池里的一格:签到、用量、模型调用都按账号各算各的,网关在账号间故障切换。同一账号用浏览器登录和桌面端登录会归到同一格(`accountId` 都是 uid)。凭据保存在 magpie 的 `plugin-auth.json`(权限 600),不上传。 ## 模型 @@ -52,11 +54,15 @@ same daily points balance. ## 每日签到(每日登录积分) -AStudio 有「每日登录积分」:服务端在当天账号会话首次活跃时发放(体验版 100 分/天,标准版 200,高级/畅享 400;活动期 31 天有效),客户端弹窗只做通知、没有领取接口。插件为此提供 magpie 的 `auth.checkin`:每天替账号做一次会话活跃(只读请求,带桌面端 `clientType` / `studioVersion` 身份头;缺 `clientType` 会被服务端以 `11001001` 拒绝),再观测前后余额差与 `client-popups/pending` 的 `DAILY_REWARD_DIALOG` 待通知弹窗——涨了记为已领取,见到弹窗记为今日已发放,两者都没有则如实报「未观测到新发放」,**不谎称已签**。发放由服务端按账号会话判定,插件不能代替桌面端登录,也不保证某天一定有积分到账。签到需要账号带网页会话(桌面端登录态方式默认有)。 +AStudio 有「每日登录积分」:服务端在当天账号会话首次活跃时发放(体验版 100 分/天,标准版 200,高级/畅享 400;活动期 31 天有效),客户端弹窗只做通知、没有领取接口。 + +插件为此提供 magpie 的 `auth.checkin`,**先读当日获得流水**(`points/details?direction=CREDIT`,与网页后台「获得明细」同源,时间窗口按北京时间算):有 `GRANT` 且 reason 为「每日登录赠送」的入账即已发放——此时**一个写请求都不发**,连会话活跃也不做。流水为空才替账号做一次会话活跃(`POST tenant-app/v2/init-app`,带桌面端 `clientType` / `studioVersion` 身份头;缺 `clientType` 会被服务端以 `11001001` 拒绝),再读一次流水:新出现的 GRANT 行记为本次领取;流水接口不可用时退回余额差 + `client-popups/pending` 的 `DAILY_REWARD_DIALOG` 弹窗观测。余额涨了但流水还没入账也记领取(流水滞后);流水通畅、余额没涨、也没有当日弹窗则如实报「未观测到新发放」,**不谎称已签**。 + +签到**不调用** `client-popups/complete`:桌面端的「知道了」是桌面端的交互,插件只读弹窗、不替用户点掉。除 init-app 外,签到发出的都是只读请求。发放由服务端按账号会话判定,插件不能代替桌面端登录,也不保证某天一定有积分到账。签到需要账号带网页会话(浏览器登录与桌面端登录态方式默认有)。 ## 用量 -有网页会话时显示真实数据:会员档(体验版/标准版/高级版/畅享版)、通用积分余额(含最近到期批次与时间)、星火积分余额。所有读取均不计费;模型调用本身才消耗账号额度。401/403/登录异常会把账号标记为需要重新登录。 +有网页会话时显示真实数据:会员档(体验版/标准版/高级版/畅享版)、通用积分余额(含最近到期批次与时间)、星火积分余额与最早到期时间(`runsOutAt` / `runsOut`:60 天流水里未过期批次按到期日聚合,翻页读取,金额按余额封顶)。星火积分 7 天内到期时,签到消息会追加提醒。所有读取均不计费;模型调用本身才消耗账号额度。401/403/登录异常会把账号标记为需要重新登录。 ## 协议与上游 @@ -72,7 +78,7 @@ AStudio 有「每日登录积分」:服务端在当天账号会话首次活跃 ``` magpie plugin add @magpie-community/opencode-astudio-auth -magpie plugin login astudio # 选「读取 AStudio 桌面端登录态」或「粘贴 modelBearerToken」 +magpie plugin login astudio # 选「浏览器登录」「读取 AStudio 桌面端登录态」或「粘贴 modelBearerToken」 magpie provider test astudio spark-x2.6-4b # 限免模型,验收一发 ``` diff --git a/packages/astudio/browser.mjs b/packages/astudio/browser.mjs new file mode 100644 index 0000000..a90e877 --- /dev/null +++ b/packages/astudio/browser.mjs @@ -0,0 +1,375 @@ +// AStudio 网页登录的浏览器收割(CDP 管道客户端,移植自 mclaw/browser.mjs, +// 后者整体移植自 gcp-ai 插件,MIT)。 +// +// Chrome/Edge 以 --remote-debugging-pipe 启动:CDP 走本进程的 fd 3/4(NUL 分隔 +// JSON),不监听任何 TCP 端口,机器上其他进程碰不到这个浏览器会话。每次登录用 +// 全新 profile(随机子目录),绝不复用旧登录态——换账号登录、会话被吊销后重登 +// 都不会捡到上一次的 Cookie;登录收尾后目录即删(会话已进账号 metadata.session, +// 浏览器目录只是第二份凭据副本)。 +import { spawn } from "node:child_process" +import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises" +import { createHash, randomBytes } from "node:crypto" +import { homedir, tmpdir } from "node:os" +import { join, dirname, resolve } from "node:path" + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) + +const configRoot = () => process.env.XDG_CONFIG_HOME + || (process.platform === "win32" && process.env.APPDATA ? process.env.APPDATA : join(homedir(), ".config")) +const cacheRoot = () => process.env.XDG_CACHE_HOME + || (process.platform === "win32" && process.env.LOCALAPPDATA ? process.env.LOCALAPPDATA : join(homedir(), ".cache")) + +// 登录态 profile 的根(ASTUDIO_BROWSER_PROFILE 可覆盖)。 +export const profilesRoot = () => process.env.ASTUDIO_BROWSER_PROFILE + ? resolve(process.env.ASTUDIO_BROWSER_PROFILE.startsWith("~") ? join(homedir(), process.env.ASTUDIO_BROWSER_PROFILE.slice(2)) : process.env.ASTUDIO_BROWSER_PROFILE) + : join(configRoot(), "magpie", "astudio-browser-profiles") + +// 一次新登录的专属 profile:随机子目录,绝不带旧票。 +export const freshSigninProfile = () => join(profilesRoot(), `signin-${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`) + +// 删掉一个登录用过的 profile:成功、失败、取消、超时都不留——会话已进账号 +// metadata.session,浏览器目录只是第二份凭据副本。 +export async function removeProfile(profilePath) { + if (profilePath) await rm(profilePath, { recursive: true, force: true }).catch(() => {}) +} + +// ---------------------------------------------------------------- profile 锁 +// 同一 profile 的多个操作串行化:mkdir 原子抢锁,抢不到就排队。锁从抢到那一刻 +// 一直持到 release() 被调(浏览器关掉之后)。 +const LOCK_TIMEOUT = 180_000 + +async function claimProfileLock(profilePath) { + const lockDir = join(cacheRoot(), "magpie", "astudio", "profiles", + createHash("sha256").update(profilePath).digest("hex").slice(0, 16)) + await mkdir(dirname(lockDir), { recursive: true }).catch(() => {}) + const deadline = Date.now() + LOCK_TIMEOUT + for (;;) { + try { + await mkdir(lockDir) + await writeFile(join(lockDir, "pid"), String(process.pid)).catch(() => {}) + break + } catch (error) { + if (error.code !== "EEXIST") throw error + // 持锁进程已经死了(上次没来得及清理)就偷走这把锁。 + const holder = await readFile(join(lockDir, "pid"), "utf8").then((t) => Number(t.trim())).catch(() => NaN) + if (Number.isFinite(holder) && holder !== process.pid) { + let alive = true + try { process.kill(holder, 0) } catch (e) { alive = e.code === "EPERM" } + if (!alive) { + await rm(lockDir, { recursive: true, force: true }).catch(() => {}) + continue + } + } + if (Date.now() >= deadline) throw new Error("AStudio 浏览器 profile 被其他操作占用,请稍后重试") + await sleep(500) + } + } + let released = false + return async () => { + if (released) return + released = true + await rm(lockDir, { recursive: true, force: true }).catch(() => {}) + } +} + +// ---------------------------------------------------------------- CDP 管道客户端 + +const timeoutError = (message) => Object.assign(new Error(message), { name: "TimeoutError" }) +// 超时提示按量级选单位:不足 1 分钟说「45 秒」,别渲染成「0 分钟」。 +const durationLabel = (ms) => (ms >= 60_000 + ? `${Math.round(ms / 60_000)} 分钟` + : `${Math.max(1, Math.round(ms / 1000))} 秒`) + +// Chrome 每写完一个 JSON 消息跟一个 NUL。 +class Pipe { + constructor(child) { + this.child = child + this.toChrome = child.stdio[3] + this.fromChrome = child.stdio[4] + this.buffer = "" + this.nextId = 1 + this.pending = new Map() + this.events = new Map() + this.closed = false + this.closedReason = "Chrome was closed" + this.fromChrome.setEncoding("utf8") + this.fromChrome.on("data", (chunk) => this.read(chunk)) + this.fromChrome.on("end", () => this.shut("Chrome closed the debugging connection")) + this.fromChrome.on("error", () => this.shut("Chrome closed the debugging connection")) + this.toChrome.on("error", () => this.shut("Chrome closed the debugging connection")) + child.once("exit", (code) => this.shut(`Chrome exited (${code ?? "signal"})`)) + } + + read(chunk) { + this.buffer += chunk + for (let end = this.buffer.indexOf("\0"); end >= 0; end = this.buffer.indexOf("\0")) { + const raw = this.buffer.slice(0, end) + this.buffer = this.buffer.slice(end + 1) + let message + try { message = JSON.parse(raw) } catch { continue } + if (message.id === undefined) { + for (const listener of this.events.get(`${message.sessionId ?? ""}:${message.method}`) ?? []) listener(message.params ?? {}) + continue + } + const pending = this.pending.get(message.id) + if (!pending) continue + this.pending.delete(message.id) + if (message.error) pending.reject(new Error(message.error.message ?? "Chrome refused the command")) + else pending.resolve(message.result ?? {}) + } + } + + shut(reason) { + if (this.closed) return + this.closed = true + this.closedReason = reason + for (const { reject } of this.pending.values()) reject(new Error(reason)) + this.pending.clear() + } + + send(method, params = {}, sessionId) { + if (this.closed) return Promise.reject(new Error(this.closedReason)) + const id = this.nextId++ + const message = { id, method, params, ...(sessionId ? { sessionId } : {}) } + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve, reject }) + this.toChrome.write(JSON.stringify(message) + "\0") + }) + } +} + +class Page { + constructor(connection, sessionId, targetId) { + this.connection = connection + this.sessionId = sessionId + this.targetId = targetId + this.closed = false + } + + send(method, params) { + return this.connection.send(method, params, this.sessionId) + } + + isClosed() { + return this.closed || this.connection.closed + } + + async close() { + if (this.closed) return + this.closed = true + if (this.connection.closed) return + await this.connection.send("Target.closeTarget", { targetId: this.targetId }).catch(() => {}) + } +} + +export class Browser { + constructor(child, connection) { + this.child = child + this.connection = connection + this.pages = new Set() + } + + async firstPage(timeout = 15000) { + const deadline = Date.now() + timeout + while (Date.now() < deadline) { + const { targetInfos = [] } = await this.connection.send("Target.getTargets").catch(() => ({})) + const found = targetInfos.find((target) => target.type === "page") + if (found) { + const { sessionId } = await this.connection.send("Target.attachToTarget", { targetId: found.targetId, flatten: true }) + const page = new Page(this.connection, sessionId, found.targetId) + this.pages.add(page) + page.send("Page.enable").catch(() => {}) + return page + } + if (this.connection.closed) throw new Error(this.connection.closedReason) + await sleep(100) + } + throw new Error("浏览器没有打开页面") + } + + // 关进程 = 收掉 profile 会话:Cookie 留在磁盘上,也不会留下无主浏览器。 + async close() { + for (const page of this.pages) page.closed = true + const exited = new Promise((resolve) => { + if (this.child.exitCode !== null || this.child.signalCode !== null) resolve() + else this.child.once("exit", resolve) + }) + await this.connection.send("Browser.close").catch(() => {}) + this.connection.shut("Browser was closed") + const gone = await Promise.race([ + exited.then(() => true), + sleep(5000).then(() => false), + ]) + if (!gone) { + this.child.kill("SIGTERM") + const stopped = await Promise.race([exited.then(() => true), sleep(3000).then(() => false)]) + if (!stopped) { + this.child.kill("SIGKILL") + await Promise.race([exited, sleep(2000)]) + } + } + } +} + +function launch(executable, args, { timeout = 30000 } = {}) { + const child = spawn(executable, [...args, "--remote-debugging-pipe"], { + stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"], + detached: false, + }) + const connection = new Pipe(child) + const failed = new Promise((_, reject) => { + child.once("error", (error) => { + connection.shut("Browser could not be started") + reject(error.code === "ENOENT" + ? new Error("找不到浏览器;请安装 Chrome/Edge,或用 ASTUDIO_CHROME_PATH 指到可执行文件") + : new Error(`浏览器无法启动:${error.message}`)) + }) + child.once("exit", (code) => { + connection.shut(`Browser exited (${code ?? "signal"})`) + }) + }) + failed.catch(() => {}) + const browser = new Browser(child, connection) + return Promise.race([browser.firstPage(timeout).then((page) => ({ browser, page })), failed]) +} + +// ---------------------------------------------------------------- 浏览器定位 + +export async function browserExecutable() { + const override = process.env.ASTUDIO_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["PROGRAMFILES(X86)"] && join(process.env["PROGRAMFILES(X86)"], "Microsoft", "Edge", "Application", "msedge.exe"), + process.env.PROGRAMFILES && join(process.env.PROGRAMFILES, "Microsoft", "Edge", "Application", "msedge.exe"), + process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, "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"), + "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", + ] + : ["/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/Edge;请安装其中一个,或用 ASTUDIO_CHROME_PATH 指到可执行文件") +} + +// ---------------------------------------------------------------- 打开/收割 + +/** 用专属 profile 开浏览器(登录用 headless: false,用户手动操作窗口)。 + * 返回 { browser, page, profilePath, release }:release() 在 close() 之后调用才放锁。 */ +export async function openBrowser({ headless = false, startUrl = "about:blank", profilePath = freshSigninProfile() } = {}) { + const release = await claimProfileLock(profilePath) + try { + await mkdir(profilePath, { recursive: true, mode: 0o700 }) + const args = [ + `--user-data-dir=${profilePath}`, + "--no-first-run", "--no-default-browser-check", + "--disable-background-networking", "--disable-sync", "--disable-default-apps", + "--disable-component-update", "--disable-client-side-phishing-detection", + "--disable-domain-reliability", + "--disable-features=Translate,OptimizationHints,MediaRouter,DialMediaRouteProvider", + "--metrics-recording-only", "--no-service-autorun", + // Cookie 存储用 mock keychain,不碰 macOS 钥匙串 / Linux keyring。 + ...(process.platform === "darwin" ? ["--use-mock-keychain"] : process.platform === "linux" ? ["--password-store=basic"] : []), + "--window-size=1280,900", + ...(headless ? ["--headless=new", "--disable-gpu"] : []), + "--crash-dumps-dir=" + tmpdir(), + startUrl, + ] + const started = await launch(await browserExecutable(), args) + return { ...started, profilePath, release } + } catch (error) { + await release() + await removeProfile(profilePath) + throw error + } +} + +// 网页登录成功后写进 Cookie 的三件套(web bundle 从 URL 参数落到 document.cookie)。 +const COOKIE_DOMAIN = /(^|\.)xfyun\.cn$/i +// 同名 Cookie 可能在 .xfyun.cn 和 agent.xfyun.cn 各有一份:登录页写的是 +// host-only 的 agent.xfyun.cn,优先它,其次根域,最后其他子域(如 passport)。 +const domainRank = (cookie) => { + const domain = String(cookie?.domain ?? "").replace(/^\./, "").toLowerCase() + if (domain === "agent.xfyun.cn") return 3 + if (domain === "xfyun.cn") return 2 + return 1 +} +const pickCookie = (cookies, names) => + cookies + .filter((c) => names.includes(c?.name) && COOKIE_DOMAIN.test(String(c?.domain ?? "")) && c?.value) + .sort((a, b) => domainRank(b) - domainRank(a))[0] + +/** 读 AStudio 网页会话 Cookie(含 httpOnly;CDP 直读浏览器 Cookie 库)。 + * 返回 { session: {token, accountId, ssoSessionId?} } 或 undefined。 */ +export async function harvestAstronSession(browser) { + const { cookies = [] } = await browser.connection.send("Storage.getCookies").catch(() => ({})) + const token = pickCookie(cookies, ["token"]) + const account = pickCookie(cookies, ["account_id", "accountId"]) + const sso = pickCookie(cookies, ["ssoSessionId", "sso_sessionid"]) + // 网页登录写的是 ssoSessionId + account_id(token 只是 SSO 顺带给的,可能没有; + // 2026-11-06 实测账号面与换发接口只用前两个也能通过)。 + if (!account?.value || !sso?.value) return undefined + return { + session: { + ...(token?.value ? { token: token.value } : {}), + accountId: account.value, + ssoSessionId: sso.value, + }, + } +} + +/** 浏览器登录全流程:有头浏览器(全新 profile)→ 用户在窗口里完成讯飞登录 → + * 收割 Cookie。返回 { promise, abort }:promise resolve { session, profilePath, + * release, close }。abort() 随时可调(宿主取消);成功/失败/取消/超时都删掉 + * profile 目录——会话已进账号 metadata,浏览器目录不留第二份凭据。 + * removeProfileImpl 只为测试能观测清理动作,生产不传。 */ +export function startBrowserHarvest({ deadlineMs = 600_000, startUrl, profilePath = freshSigninProfile(), open = openBrowser, removeProfileImpl = removeProfile } = {}) { + const harvest = { promise: undefined, abort: async () => {} } + harvest.promise = (async () => { + let aborted = false + let opened // { browser, release }:浏览器开出后持有,成功时移交 callback + let usedPath = profilePath + harvest.abort = async () => { + if (aborted) return + aborted = true + if (opened) { + await opened.browser.close().catch(() => {}) + await opened.release() + } + // 宿主取消时 callback 不会再被调,profile 没人认领;成功路径下 callback + // 自己也会删(rm 幂等),所以这里一律删。 + await removeProfileImpl(usedPath) + } + try { + const { browser, profilePath: used, release } = await open({ headless: false, startUrl, profilePath }) + opened = { browser, release } + usedPath = used + if (aborted) throw new Error("登录已取消") + const deadline = Date.now() + deadlineMs + for (;;) { + if (aborted) throw new Error("登录已取消") + if (browser.connection.closed) throw new Error("浏览器被关闭,登录中断") + const found = await harvestAstronSession(browser).catch(() => undefined) + if (found) return { ...found, profilePath: used, release, close: () => browser.close() } + if (Date.now() >= deadline) throw timeoutError(`登录超时(${durationLabel(deadlineMs)}内没有检测到 AStudio 登录)`) + await sleep(1500) + } + } catch (error) { + if (opened) { + await opened.browser.close().catch(() => {}) + await opened.release() + } + await removeProfileImpl(usedPath) + throw error + } + })() + return harvest +} diff --git a/packages/astudio/index.mjs b/packages/astudio/index.mjs index 8753325..8dc684b 100644 --- a/packages/astudio/index.mjs +++ b/packages/astudio/index.mjs @@ -13,17 +13,26 @@ // 账号面 https://agent.xfyun.cn/xingchen-studio/…(Cookie 会话鉴权): // points/balance、membership/me、membership/plan-config、points/summary // -// 本插件复用这份登录态:第一种登录方式直接从磁盘读取桌面端会话(Raccoon -// 「复用桌面端登录态」同款;magpie 的 oauth 方式,读不到时给出官网链接并轮询, -// 等用户装好桌面端登录),第二种让用户手动粘贴 modelBearerToken。目录与 -// 思考档位按账号实时拉取(目录读取不计费)。AStudio 有「每日登录积分」 -// (服务端在当天账号会话首次活跃时发放,客户端弹窗只做通知,无领取接口), -// auth.checkin 用「发放前后余额差」观测:涨了记 claimed,没涨不谎称已签—— -// 记 inactive 并说明未观测到(宿主把 done 渲染成「今日已签到」,是没发生的断言)。 +// 三种登录方式:①浏览器登录(推荐,可多账号)——弹出全新 profile 的专用浏览器, +// 用户在里面登录后收割网页会话 Cookie(ssoSessionId + account_id 必需,token 有 +// 则带上),再用桌面端启动时的同款 POST auth/bearer-token 换发模型凭据(JWT, +// 实测 3 年有效;换发后旧 token 仍可用),accountId 用账号 uid,同一账号的桌面端 +// 与网页登录因此归到同一格;②读取桌面端登录态——直接从磁盘读桌面端会话 +// (magpie 的 oauth 方式,读不到时给出官网链接并轮询,等用户装好登录); +// ③粘贴 modelBearerToken。目录与思考档位按账号实时拉取(目录读取不计费)。 +// +// AStudio 有「每日登录积分」:服务端在当天账号会话首次活跃时发放,客户端弹窗 +// 只做通知、没有领取接口。auth.checkin 先读当日获得流水(points/details +// direction=CREDIT,与网页后台「获得明细」同源):已有「每日登录赠送」GRANT 行 +// 即 done,此时一个写请求都不发;流水为空才补一次会话活跃(POST +// tenant-app/v2/init-app,复刻桌面端启动),再读一次流水。流水读失败退回余额差 + +// 弹窗观测。流水通畅、余额没涨、也无当日弹窗则记 inactive——宿主把 done 渲染成 +// 「今日已签到」,没发生的不能断言。 import { spawnSync } from "node:child_process" import { readFileSync } from "node:fs" import { homedir as osHomedir } from "node:os" +import * as browserDefault from "./browser.mjs" const ID = "astudio" @@ -38,6 +47,10 @@ const STUDIO_VERSION = "3.5.5" // 读取桌面端登录态失败时展示的跳转页:AStudio 官网(含桌面端下载)。 const OFFICIAL_SITE = "https://agent.xfyun.cn/" +// 网页登录的落地页:登录后 web bundle 把 ssoSessionId/account_id/token 写进 Cookie。 +const STUDIO_WEB_URL = "https://agent.xfyun.cn/studio-credits" +// 浏览器登录窗口的等待上限(宿主取消时也会提前 abort)。 +const WEB_SIGNIN_WAIT_MS = 10 * 60 * 1000 // 等待「用户去装桌面端并登录」的窗口与轮询间隔。 const DESKTOP_POLL_MS = 2000 const DESKTOP_WAIT_MS = 5 * 60 * 1000 @@ -272,7 +285,7 @@ async function studioJson(path, { session, fetchImpl, method = "GET", body, oper redirect: "error", }) } catch (error) { - throw new Error(`${operation} 网络失败:${error?.cause?.code || error?.message || "未知错误"}`) + throw Object.assign(new Error(`${operation} 网络失败:${error?.cause?.code || error?.message || "未知错误"}`), { transient: true }) } if (res.status === 401 || res.status === 403) { throw Object.assign(new Error(`AStudio 会话已失效(HTTP ${res.status}),请重新登录 AStudio`), { signIn: "expired" }) @@ -288,11 +301,41 @@ async function studioJson(path, { session, fetchImpl, method = "GET", body, oper if (envelope.code === 80000 || /重新登录/.test(String(envelope.desc ?? ""))) { throw Object.assign(new Error(`AStudio 会话已失效,请重新登录 AStudio`), { signIn: "expired" }) } - throw new Error(`${operation} 失败(HTTP ${res.status}${envelope.desc ? `:${envelope.desc}` : ""})`) + throw Object.assign(new Error(`${operation} 失败(HTTP ${res.status}${envelope.desc ? `:${envelope.desc}` : ""})`), { + transient: res.status >= 500, + }) } return envelope.data } +// 网页登录换发模型凭据:桌面端启动时的同款 POST(Cookie 鉴权),返回 +// modelBearerToken(JWT,实测 3 年有效期;换发后旧 token 仍可用)。 +// 请求装配与错误分类都走 studioJson,别再抄一份(抄本必然与正本漂移)。 +async function exchangeModelToken(session, fetchImpl) { + const data = await studioJson("auth/bearer-token", { + session, + fetchImpl, + method: "POST", + operation: "换发模型凭据", + }) + const token = data?.modelBearerToken + if (typeof token !== "string" || !token) throw new Error("换发模型凭据失败:返回里没有 modelBearerToken") + return token +} + +// 登录回调里的两次网络读:只有网络/5xx 这类瞬时失败重试,会话失效与确定性 +// 4xx 不重试——用户刚在浏览器里登完,一次抖动不该把整次登录作废。 +async function retryTransient(fn, sleep, attempts = 3, delayMs = 2000) { + for (let i = 0; ; i++) { + try { + return await fn() + } catch (error) { + if (!error?.transient || i + 1 >= attempts) throw error + await sleep(delayMs) + } + } +} + async function fetchCatalog(key, fetchImpl) { return await fetchImpl(MODEL_MANAGER_URL, { headers: { authorization: `Bearer ${key}`, accept: "application/json" }, @@ -307,7 +350,9 @@ function authResult(cred) { return { type: "success", key: cred.key, - accountId: cred.uid, + // 实测 uid === account_id;session 里缺 uid 的旧登录态退回 account_id, + // 否则 accountId 为空会让宿主把多个账号塌进同一格。 + accountId: cred.uid || cred.session?.accountId, metadata: { uid: cred.uid, source: cred.source, @@ -347,13 +392,106 @@ function reasonOf(error) { : "本机没有 AStudio 桌面端登录态" } -function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir = osHomedir(), registryQuery, readFileImpl, sleepImpl, nowMsImpl = () => Date.now() } = {}) { +function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir = osHomedir(), registryQuery, readFileImpl, sleepImpl, nowMsImpl = () => Date.now(), browserModule = browserDefault } = {}) { const sleep = sleepImpl ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))) async function readBalance(session) { return await studioJson("points/balance", { session, fetchImpl, operation: "积分余额" }) } + // points/details 的时间参数格式(网页端同款):`YYYY-MM-DD HH:mm:ss`,服务端 + // 按北京时间解释。窗口必须用 +08:00 的墙上时间算:本地时区(TZ=America/ + // Los_Angeles)或 UTC 机器会把当天的 GRANT 行算到窗口外,签到误报 inactive。 + // 时间只从 nowMsImpl 取,测试才能把时钟钉住。 + const CST_OFFSET_MS = 8 * 3600 * 1000 + function cstStamp(ms) { + const d = new Date(ms + CST_OFFSET_MS) + const p2 = (n) => String(n).padStart(2, "0") + return `${d.getUTCFullYear()}-${p2(d.getUTCMonth() + 1)}-${p2(d.getUTCDate())} ${p2(d.getUTCHours())}:${p2(d.getUTCMinutes())}:${p2(d.getUTCSeconds())}` + } + const cstDayStart = (ms) => Math.floor((ms + CST_OFFSET_MS) / 86400000) * 86400000 - CST_OFFSET_MS + const cstDayOf = (ms) => Math.floor((ms + CST_OFFSET_MS) / 86400000) + + // 当日「每日登录赠送」入账流水。网页后台的获得明细(points/details + // direction=CREDIT)是权威数据源:发放一旦发生就有 GRANT 行,不管由哪个 + // 端触发(桌面端 init-app、服务端午夜批量),都比「余额差+弹窗」可靠。 + async function readDailyGrantLedger(session) { + const now = nowMsImpl() + const query = `pageNum=1&pageSize=50&direction=CREDIT&startTime=${encodeURIComponent(cstStamp(cstDayStart(now)))}&endTime=${encodeURIComponent(cstStamp(now))}` + const data = await studioJson(`points/details?${query}`, { session, fetchImpl, operation: "获得明细" }) + const items = Array.isArray(data?.items) ? data.items : [] + return items.find((item) => item?.direction === "CREDIT" && item?.operation === "GRANT" && item?.reason === "每日登录赠送") ?? null + } + + // 星火积分最近到期批次(raccoon 同款算法):流水按 expireTime 聚合, + // 取最近的未过期批次金额,供 usage 窗口挂 runsOutAt/runsOut。 + // 服务端时间戳是北京时间的裸串(无时区标记),显式钉 +08:00: + // 不同运行时对无时区 ISO 串的解释不同(node=本地时区、bun=UTC)。 + const parseCST = (s) => Date.parse(/(?:[zZ]|[+-]\d{2}:?\d{2})$/.test(s) ? s : `${s}+08:00`) + async function readSparkExpiry(session, cap) { + const now = nowMsImpl() + const startTime = encodeURIComponent(cstStamp(now - 60 * 86400000)) + const endTime = encodeURIComponent(cstStamp(now)) + // 60 天窗口里每天一笔 GRANT,一页 50 行装不下——逐页读,最多 10 页, + // 用整行去重防服务端忽略 pageNum 时重复累加。 + const seen = new Set() + const rows = [] + for (let page = 1; page <= 10; page++) { + const data = await studioJson( + `points/details?pageNum=${page}&pageSize=50&direction=CREDIT&startTime=${startTime}&endTime=${endTime}`, + { session, fetchImpl, operation: "获得明细" }, + ) + const batch = Array.isArray(data?.items) ? data.items : [] + for (const item of batch) { + const key = JSON.stringify(item) + if (seen.has(key)) continue + seen.add(key) + rows.push(item) + } + if (batch.length < 50) break + } + let soonestMs = 0 + let expiring = 0 + for (const item of rows) { + if (item?.assetCode !== "SPARK_POINTS") continue + const amount = Number(item?.amount) + const expMs = item?.expireTime ? parseCST(item.expireTime) : NaN + if (!Number.isFinite(amount) || amount <= 0) continue + if (!Number.isFinite(expMs) || expMs <= now) continue + if (!soonestMs || expMs < soonestMs) { + soonestMs = expMs + expiring = amount + } else if (expMs === soonestMs) { + expiring += amount + } + } + if (!soonestMs) return null + // 流水记的是发放额,余额才是还没花掉的量:到期提示不能超过余额。 + const limit = Number(cap) + const runsOut = Number.isFinite(limit) && limit >= 0 ? Math.min(expiring, limit) : expiring + return { runsOutAt: new Date(soonestMs).toISOString(), runsOut } + } + + async function readPopups(session) { + return await studioJson("client-popups/pending", { session, fetchImpl, operation: "每日奖励弹窗" }) + } + + // 桌面端启动时的两个 POST 里,签到只复刻 init-app(租户初始化)。另一个 + // auth/bearer-token 会换发 modelBearerToken;2026-11-06 实测新旧 token 并存 + // (换发后旧 token 仍可用),但签到没有换发需求,多换一次只是白白轮换, + // 故仍不调用——浏览器登录自己需要 key 时才换。失败不塌方,但原因要收集 + // 起来交给上层,否则用户分不清「POST 失败」和「今天确实没发」。 + async function desktopLogin(session) { + const warnings = [] + try { + await studioJson("tenant-app/v2/init-app", { session, fetchImpl, method: "POST", operation: "租户初始化" }) + } catch (error) { + if (error?.signIn === "expired") throw error + warnings.push(`init-app ${error?.message ?? "失败"}`) + } + return { warnings } + } + return { config: async (cfg) => { cfg.provider ??= {} @@ -369,6 +507,72 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir auth: { provider: ID, methods: [ + { + // 网页登录:浏览器里登一次,插件收割 Cookie(ssoSessionId/account_id/ + // token)后换发模型凭据。每次登录用全新 profile,不串票;登录收尾后 + // 连 profile 一起删掉——会话已存进 metadata.session,浏览器目录只是 + // 第二份凭据副本,留着只会随每次重登无限堆积。accountId 用 uid—— + // 同一账号用桌面端登录时也是 uid,宿主因此把两路登录归到同一格。 + type: "oauth", + label: "浏览器登录(推荐,可多账号)", + async authorize(_inputs, { signal } = {}) { + // 先确认本机有 Chrome/Edge:没有就当场报错,别先说「已弹出」再失败。 + await browserModule.browserExecutable?.() + const harvesting = browserModule.startBrowserHarvest({ deadlineMs: WEB_SIGNIN_WAIT_MS, startUrl: STUDIO_WEB_URL }) + harvesting.promise.catch(() => {}) + const cleanup = setTimeout(() => { harvesting.abort().catch(() => {}) }, WEB_SIGNIN_WAIT_MS) + // 别让这个兜底定时器拖住宿主的事件循环(测试里变成 5 分钟不退出)。 + cleanup.unref?.() + const onAbort = () => { harvesting.abort().catch(() => {}) } + if (signal?.aborted) onAbort() + else if (typeof signal?.addEventListener === "function") signal.addEventListener("abort", onAbort, { once: true }) + return { + url: "", + opened: true, // 浏览器已由本插件弹出,宿主不要再开 url + instructions: "已弹出专用浏览器窗口:请在里面登录讯飞账号(手机验证码或扫码均可),登录成功后本流程自动继续。", + method: "auto", + async callback(_code, { signal: callbackSignal } = {}) { + if (callbackSignal?.aborted) onAbort() + else if (typeof callbackSignal?.addEventListener === "function") callbackSignal.addEventListener("abort", onAbort, { once: true }) + let harvested + try { + harvested = await harvesting.promise + const membership = await retryTransient( + () => studioJson("membership/me", { session: harvested.session, fetchImpl, operation: "会员信息" }), + sleep, + ) + const uid = String(membership?.uid ?? "").trim() + if (!uid) throw new Error("AStudio 账号信息里没有 uid,无法确定账号") + const key = await retryTransient(() => exchangeModelToken(harvested.session, fetchImpl), sleep) + return { + type: "success", + key, + accountId: uid, + metadata: { + uid, + method: "web", + source: STUDIO_WEB_URL, + session: harvested.session, + }, + } + } catch (error) { + return { type: "failed", error: error?.message ?? String(error) } + } finally { + clearTimeout(cleanup) + signal?.removeEventListener?.("abort", onAbort) + callbackSignal?.removeEventListener?.("abort", onAbort) + if (harvested) { + await harvested.close().catch(() => {}) + await harvested.release() + // 会话已收进 metadata.session;浏览器目录是第二份凭据副本, + // 成功失败都不留(否则每次重登都在盘上堆一份)。 + await browserModule.removeProfile(harvested.profilePath) + } + } + }, + } + }, + }, { // oauth 方式:magpie 不显示 key 输入框,authorize 必须立刻返回 // { url, instructions, method, callback },结果由 callback 交回。 @@ -479,7 +683,9 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir const auth = await getAuth() if (auth?.type !== "api" || !auth.key) return {} const session = auth.metadata?.session - if (!session?.token) { + // 账号面鉴权只需 ssoSessionId + account_id(2026-11-06 实测,token 可缺); + // account_id 是三种登录方式都有的最小标识。 + if (!session?.accountId) { let res try { res = await fetchCatalog(auth.key, fetchImpl) @@ -523,7 +729,15 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir }) } if (balance && typeof balance.sparkTotalBalance === "number") { - windows.push({ name: "星火积分", balance: balance.sparkTotalBalance, aside: false }) + // 星火积分的到期时间 balance 接口不给,从入账流水推(失败不塌方); + // 流水是发放额,到期提示按余额封顶。 + const sparkExpiry = await readSparkExpiry(session, balance.sparkTotalBalance).catch(() => null) + windows.push({ + name: "星火积分", + balance: balance.sparkTotalBalance, + aside: false, + ...(sparkExpiry && balance.sparkTotalBalance > 0 ? sparkExpiry : {}), + }) } return { ...(membership?.planName ? { plan: membership.planName } : { plan: "AStudio" }), @@ -533,13 +747,14 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir } }, // 「每日登录积分」:服务端在当天账号会话首次活跃时发放,客户端没有领取 - // 接口(DAILY_REWARD_DIALOG 弹窗只做通知)。这里以一组账号面请求代表 - // 当天的会话活跃,再用余额差与待通知弹窗观测结果,不谎称已领取。 + // 接口(DAILY_REWARD_DIALOG 弹窗只做通知)。先读当日获得流水:已有当日 + // GRANT 行就 done、一个写请求都不发;流水为空才复刻桌面端启动的 init-app, + // 再读一次流水(流水读不到才退回余额差 + 弹窗观测)。 async checkin(getAuth) { const auth = await getAuth() if (auth?.type !== "api" || !auth.key) return {} const session = auth.metadata?.session - if (!session?.token) { + if (!session?.accountId) { return { outcome: "ineligible", message: "该账号只有模型凭据(无网页会话),无法执行每日登录签到" } } let config @@ -552,46 +767,148 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir if (config?.dailyLoginEnabled === false) { return { outcome: "inactive", message: "当前没有每日登录积分活动" } } - let before + const warnings = [] + // 星火 7 天内到期时给签到消息加一句提醒(按北京时间算日历天,不是 + // 「剩不到 24 小时」)。余额是还没花掉的量,提示金额不能超过它。 + const expiryNote = async (cap) => { + let limit = cap + if (limit === undefined) { + const balance = await readBalance(session).catch(() => null) + limit = balance?.sparkTotalBalance + } + const sparkExpiry = await readSparkExpiry(session, limit).catch(() => null) + if (!sparkExpiry) return "" + const daysLeft = cstDayOf(Date.parse(sparkExpiry.runsOutAt)) - cstDayOf(nowMsImpl()) + if (daysLeft > 7) return "" + return `;注意 ${sparkExpiry.runsOut} 星火积分${daysLeft <= 0 ? "今天" : ` ${daysLeft} 天内`}到期` + } + + // 1) 流水优先:当日已有「每日登录赠送」GRANT 行 = 已发放。只读, + // 不写 init-app、不碰弹窗(11-06 实测服务端午夜批量先于签到)。 + let grant = null + let ledgerError = null + try { + grant = await readDailyGrantLedger(session) + } catch (error) { + if (error?.signIn === "expired") throw error + ledgerError = error + } + if (grant) { + const rawPoints = Number(grant.amount) + const credit = Number.isFinite(rawPoints) && rawPoints > 0 ? rawPoints : 0 + return { + outcome: "done", + ...(credit > 0 ? { credit } : {}), + message: `每日登录积分 +${credit || 0} 已发放(流水实证,先于签到发生)${await expiryNote()}`, + } + } + + // 2) 未发放:复刻桌面端启动的 init-app(签到唯一的写请求),再读一次 + // 流水。余额只用于「流水滞后」归因与旧判据兜底。 + let before = null try { before = await readBalance(session) } catch (error) { if (error?.signIn === "expired") throw error - return { outcome: "failed", message: error?.message ?? "积分余额读取失败" } } + // 旧判据(流水不可用)才需要基线弹窗:签到前就挂着的旧弹窗不能算今天。 + let hadDailyBefore = null + let baselineError = null + if (ledgerError) { + try { + const baseline = await readPopups(session) + hadDailyBefore = Array.isArray(baseline) && baseline.some((item) => item?.componentType === "DAILY_REWARD_DIALOG") + } catch (error) { + if (error?.signIn === "expired") throw error + baselineError = error + } + } + const login = await desktopLogin(session) + warnings.push(...login.warnings) // 会话活跃 touch:与桌面端启动时同类只读请求。 await studioJson("membership/me", { session, fetchImpl, operation: "会员信息" }).catch(() => null) await studioJson("points/summary", { session, fetchImpl, operation: "积分汇总" }).catch(() => null) await sleep(2500) - let after + let after = null try { after = await readBalance(session) } catch (error) { if (error?.signIn === "expired") throw error - return { outcome: "failed", message: error?.message ?? "积分余额读取失败" } } - if (typeof before?.totalBalance !== "number" || typeof after?.totalBalance !== "number") { - return { outcome: "failed", message: "积分余额读数不完整" } - } - const delta = after.totalBalance - before.totalBalance - if (delta > 0) return { outcome: "claimed", credit: delta, message: `每日登录积分 +${delta}` } - // 服务端把已发放但还没通知的每日奖励挂成待通知弹窗;见到它才算「今日已签到」。 - let popups + let grantAfter = null try { - popups = await studioJson("client-popups/pending", { session, fetchImpl, operation: "每日奖励弹窗" }) + grantAfter = await readDailyGrantLedger(session) } catch (error) { if (error?.signIn === "expired") throw error - return { outcome: "failed", message: error?.message ?? "每日奖励弹窗读取失败" } + if (!ledgerError) ledgerError = error + } + if (grantAfter) { + const rawPoints = Number(grantAfter.amount) + const credit = Number.isFinite(rawPoints) && rawPoints > 0 ? rawPoints : 0 + return { + outcome: "claimed", + ...(credit > 0 ? { credit } : {}), + message: `每日登录积分 +${credit || "?"}(流水实证,本次签到触发)${await expiryNote(after?.sparkTotalBalance)}`, + } + } + const delta = + typeof before?.totalBalance === "number" && typeof after?.totalBalance === "number" + ? after.totalBalance - before.totalBalance + : null + const warnSuffix = warnings.length ? `(${warnings.join(" / ")})` : "" + if (!ledgerError) { + // 流水通畅但无 GRANT 行:余额涨了说明发放已到账、流水只是滞后; + // 余额没涨才是真的没发。不谎称已签。 + if (delta > 0) { + return { + outcome: "claimed", + credit: delta, + message: `每日登录积分 +${delta}(余额上涨,流水尚未入账)${await expiryNote(after?.sparkTotalBalance)}`, + } + } + return { outcome: "inactive", message: `未观测到新发放:当日获得流水无「每日登录赠送」记录${warnSuffix}` } + } + // ---- 流水读失败:退回旧判据(余额差+弹窗,只读)---- + if (typeof before?.totalBalance !== "number" || typeof after?.totalBalance !== "number") { + return { outcome: "failed", message: `积分余额读数不完整${warnSuffix}` } + } + let popups = null + let popupError = null + try { + popups = await readPopups(session) + } catch (error) { + if (error?.signIn === "expired") throw error + popupError = error + } + if (delta > 0) { + return { + outcome: "claimed", + credit: delta, + message: `每日登录积分 +${delta}${await expiryNote(after?.sparkTotalBalance)}`, + } + } + // 基线读失败 ⇒ 不知道签到前是否已有弹窗,任何 done 结论都是猜的。 + if (hadDailyBefore === null) { + return { + outcome: "failed", + message: `签到前无法读取每日奖励弹窗,不能判定今日是否发放${baselineError?.message ? `:${baselineError.message}` : ""}${warnSuffix}`, + } + } + if (popupError) { + return { outcome: "failed", message: `${popupError?.message ?? "每日奖励弹窗读取失败"}${warnSuffix}` } } const daily = Array.isArray(popups) && popups.find((item) => item?.componentType === "DAILY_REWARD_DIALOG") if (daily) { const rawPoints = Number(daily.payload?.points) const credit = Number.isFinite(rawPoints) && rawPoints >= 0 ? rawPoints : 0 + // payload 没有日期字段,签到前就挂着的那份无法断定是今天的。 + if (hadDailyBefore === true) { + return { outcome: "inactive", message: "余额无变化,且签到前已有未确认的每日奖励弹窗,无法判定今日是否发放" } + } return { outcome: "done", ...(credit > 0 ? { credit } : {}), message: "每日登录积分已发放(服务端待通知弹窗)" } } - // 余额没涨、也没有待通知弹窗:发放可能挂靠桌面端登录,本次未观测到。 - // done 会渲染成「今日已签到」,是没发生的断言,故记 inactive。 - return { outcome: "inactive", message: "未观测到新发放:余额无变化(发放可能挂靠桌面端登录)" } + // 余额没涨、也没有待通知弹窗:这套请求序列没触发发放,不谎称已签。 + return { outcome: "inactive", message: `未观测到新发放:余额无变化,也没有今日的每日奖励弹窗${warnSuffix}` } }, }, @@ -650,12 +967,15 @@ export const _internal = { registryDataRoots, buildCookieHeader, studioJson, + exchangeModelToken, MODEL_GATEWAY_BASE, MODEL_MANAGER_URL, STUDIO_API_BASE, STUDIO_VERSION, + STUDIO_WEB_URL, OFFICIAL_SITE, DESKTOP_WAIT_MS, + WEB_SIGNIN_WAIT_MS, BOOTSTRAP, ID, } diff --git a/packages/astudio/index.test.mjs b/packages/astudio/index.test.mjs index f03e020..91a8d50 100644 --- a/packages/astudio/index.test.mjs +++ b/packages/astudio/index.test.mjs @@ -1,6 +1,7 @@ import test from "node:test" import assert from "node:assert/strict" import { AStudioPlugin, _internal } from "./index.mjs" +import * as astroBrowser from "./browser.mjs" const { createPlugin, @@ -12,15 +13,26 @@ const { registryDataRoots, buildCookieHeader, studioJson, + exchangeModelToken, MODEL_GATEWAY_BASE, MODEL_MANAGER_URL, STUDIO_API_BASE, STUDIO_VERSION, + STUDIO_WEB_URL, OFFICIAL_SITE, DESKTOP_WAIT_MS, ID, } = _internal +const methodByLabel = (plugin, pattern) => { + const method = plugin.auth.methods.find((m) => pattern.test(m.label)) + assert.ok(method, `没有找到匹配 ${pattern} 的登录方式`) + return method +} +const desktopMethod = (plugin) => methodByLabel(plugin, /桌面端/) +const pasteMethod = (plugin) => methodByLabel(plugin, /粘贴/) +const webMethod = (plugin) => methodByLabel(plugin, /浏览器登录/) + const CATALOG_ENTRY = { slug: "spark-x2.6-4b", badge: { text: { en: "Free", "zh-CN": "限免" } }, @@ -231,6 +243,19 @@ test("models hook maps the live catalog and keeps the old list on network failur await assert.rejects(malformed.provider.models({ models: {} }, { auth: { type: "api", key: "k" } })) }) +test("catalog reads refuse redirects and carry a timeout", async () => { + let init + const plugin = createPlugin({ + fetchImpl: async (_url, options) => { + init = options + return okRes({ code: 0, data: { models: [CATALOG_ENTRY] } }) + }, + }) + await plugin.provider.models({ models: {} }, { auth: { type: "api", key: "k" } }) + assert.equal(init.redirect, "error") + assert.ok(init.signal, "目录请求要带 AbortSignal 超时") +}) + test("usage hook checks the credential without burning quota", async () => { const ok = createPlugin({ fetchImpl: async () => okRes({ code: 0, data: { models: [] } }) }) assert.deepEqual(await ok.auth.usage(async () => ({ type: "api", key: "k" })), { plan: "AStudio", windows: [] }) @@ -248,7 +273,7 @@ test("usage hook checks the credential without burning quota", async () => { test("desktop login method is oauth, so magpie shows no key input box", () => { const plugin = createPlugin({ env: {}, registryQuery: () => null, readFileImpl: fakeFs({}) }) - const method = plugin.auth.methods[0] + const method = desktopMethod(plugin) // type:"api" 在 magpie 里就是一个 key 输入框 —— 本方法自己读磁盘,不该要用户输入。 assert.equal(method.type, "oauth") assert.match(method.label, /桌面端/) @@ -263,7 +288,7 @@ test("desktop login method reads real files through authorize", async () => { "D:\\astudio/userdata/astron-session.json": JSON.stringify({ uid: "u9", modelBearerToken: "tok-9" }), }), }) - const out = await plugin.auth.methods[0].authorize({}) + const out = await desktopMethod(plugin).authorize({}) assert.equal(out.url, "") assert.match(out.instructions, /已读取本机 AStudio 登录态(u9)/) assert.equal(out.method, "auto") @@ -290,7 +315,7 @@ test("desktop login method points at the official site and waits when nothing is }, nowMsImpl: () => clock, }) - const out = await plugin.auth.methods[0].authorize({}) + const out = await desktopMethod(plugin).authorize({}) assert.equal(out.url, OFFICIAL_SITE) assert.equal(out.method, "auto") assert.match(out.instructions, /没有找到 AStudio 桌面端登录态/) @@ -316,7 +341,7 @@ test("desktop login method completes on its own once the desktop signs in", asyn return session }, }) - const out = await plugin.auth.methods[0].authorize({}) + const out = await desktopMethod(plugin).authorize({}) assert.equal(out.url, OFFICIAL_SITE) assert.equal(reads, 1) // authorize 读一次 assert.equal((await out.callback()).key, "tok-7") @@ -351,7 +376,7 @@ test("desktop login method refuses banned accounts instead of offering the site" }) // 宿主 host.js 不看 oauth authorize 结果里的 type,只看它抛出的 message 或 callback; // 抛错在任何宿主版本上都把原因原样交给用户。 - await assert.rejects(() => plugin.auth.methods[0].authorize({}, {}), /封禁/) + await assert.rejects(() => desktopMethod(plugin).authorize({}, {}), /封禁/) }) test("desktop login method explains an unreadable session instead of pointing at install", async () => { @@ -360,7 +385,7 @@ test("desktop login method explains an unreadable session instead of pointing at registryQuery: () => null, readFileImpl: fakeFs({ "D:\\astudio/userdata/astron-session.json": "{ 不是 JSON" }), }) - const out = await plugin.auth.methods[0].authorize({}, {}) + const out = await desktopMethod(plugin).authorize({}, {}) assert.equal(out.url, OFFICIAL_SITE) assert.match(out.instructions, /不是有效 JSON/) assert.doesNotMatch(out.instructions, /本机没有找到/) @@ -374,7 +399,7 @@ test("desktop login method keeps a read error instead of calling the machine emp throw Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" }) }, }) - const out = await plugin.auth.methods[0].authorize({}, {}) + const out = await desktopMethod(plugin).authorize({}, {}) assert.match(out.instructions, /读取失败.*EACCES/s) // 读不了 ≠ 没装 }) @@ -392,7 +417,7 @@ test("desktop login method reports the last reason when it times out", async () }, nowMsImpl: () => clock, }) - const out = await plugin.auth.methods[0].authorize({}, {}) + const out = await desktopMethod(plugin).authorize({}, {}) const failed = await out.callback(undefined, {}) assert.equal(failed.type, "failed") assert.match(failed.error, /没有 modelBearerToken.token/) @@ -413,7 +438,7 @@ test("desktop login method stops polling when the sign-in is cancelled", async ( }, nowMsImpl: () => clock, }) - const out = await plugin.auth.methods[0].authorize({}, { signal: controller.signal }) + const out = await desktopMethod(plugin).authorize({}, { signal: controller.signal }) const failed = await out.callback(undefined, { signal: controller.signal }) assert.equal(failed.type, "failed") assert.match(failed.error, /取消/) @@ -473,6 +498,8 @@ test("studioJson unwraps the envelope and flags dead sessions", async () => { test("studioJson via usage: balance and membership map to quota windows", async () => { const session = { token: "T", ssoSessionId: "S", accountId: "A" } const plugin = createPlugin({ + // 时钟钉在 2026-11-06:否则 11-22 之后这条断言会随真实时间过期。 + nowMsImpl: () => Date.parse("2026-11-06T00:00:00+08:00"), fetchImpl: async (input) => { const url = String(input) if (url.includes("points/balance")) { @@ -481,6 +508,9 @@ test("studioJson via usage: balance and membership map to quota windows", async if (url.includes("membership/me")) { return jsonRes({ flag: true, code: 0, data: { uid: 18800000000, active: true, planCode: "TRIAL", planName: "体验版" } }) } + if (url.includes("points/details")) { + return jsonRes({ flag: true, code: 0, data: { total: 1, items: [sparkGrantRow(35000, "2026-11-22T21:34:30")] } }) + } throw new Error(`unexpected ${url}`) }, }) @@ -488,14 +518,39 @@ test("studioJson via usage: balance and membership map to quota windows", async assert.equal(out.plan, "体验版") assert.equal(out.user, "18800000000") assert.deepEqual(out.windows[0], { name: "通用积分", balance: 7900, aside: false, runsOutAt: "2026-11-03T06:11:12", runsOut: 7900 }) + // 星火到期从入账流水推(balance 接口不给星火到期时间)。 + assert.deepEqual(out.windows[1], { name: "星火积分", balance: 35000, aside: false, runsOutAt: "2026-11-22T13:34:30.000Z", runsOut: 35000 }) +}) + +test("usage spark window omits expiry when the ledger query fails", async () => { + const session = { token: "T", ssoSessionId: "S", accountId: "A" } + const plugin = createPlugin({ + fetchImpl: async (input) => { + const url = String(input) + if (url.includes("points/balance")) { + return jsonRes({ flag: true, code: 0, data: { totalBalance: 7900, activityBalance: 7900, sparkTotalBalance: 35000, sparkActivityBalance: 35000 } }) + } + if (url.includes("membership/me")) { + return jsonRes({ flag: true, code: 0, data: { uid: 18800000000, active: true, planCode: "TRIAL", planName: "体验版" } }) + } + if (url.includes("points/details")) { + return jsonRes({ flag: false, code: 11001001, desc: "参数无效" }) + } + throw new Error(`unexpected ${url}`) + }, + }) + const out = await plugin.auth.usage(async () => ({ type: "api", key: "k", metadata: { session } })) + // 到期推算失败不塌方:星火窗口退回无 runsOut 形态。 assert.deepEqual(out.windows[1], { name: "星火积分", balance: 35000, aside: false }) }) -const checkinFetch = (balanceSequence, { popups = [], identityAssert, popupFails = false } = {}) => { +const checkinFetch = (balanceSequence, { popups = [], popupsSequence, identityAssert, popupFails = false, onComplete, onInitApp, ledger, ledgerSequence, ledgerFails = false, sparkLedger, sparkPages } = {}) => { let balanceCalls = 0 + let popupCalls = 0 + let ledgerCalls = 0 return async (input, init) => { const url = String(input) - if (identityAssert) identityAssert(init.headers) + if (identityAssert) identityAssert(init.headers, init) if (url.includes("membership/plan-config")) { return jsonRes({ flag: true, code: 0, data: { dailyLoginEnabled: true, dailyLoginValidDays: 31, plans: [{ planCode: "TRIAL", dailyLoginPoints: 100 }] } }) } @@ -504,9 +559,44 @@ const checkinFetch = (balanceSequence, { popups = [], identityAssert, popupFails const total = balanceSequence[Math.min(balanceCalls - 1, balanceSequence.length - 1)] return jsonRes({ flag: true, code: 0, data: { totalBalance: total, activityBalance: total } }) } + if (url.includes("points/details")) { + if (ledgerFails) return jsonRes({ flag: false, code: 11001001, desc: "参数无效" }) + // 当日窗口(起止同日)=「每日登录赠送」查询;跨 60 天窗口 = 星火到期查询。 + const params = new URL(url).searchParams + const isDailyQuery = params.get("startTime")?.slice(0, 10) === params.get("endTime")?.slice(0, 10) + if (!isDailyQuery && sparkPages) { + const page = Number(params.get("pageNum") ?? 1) + const items = sparkPages[page - 1] ?? [] + return jsonRes({ flag: true, code: 0, data: { total: 0, pageNum: page, pageSize: 50, items } }) + } + // ledgerSequence 区分「签到前读」与「签到后读」:前者没有行,后者有。 + let items + if (isDailyQuery) { + ledgerCalls += 1 + items = ledgerSequence + ? ledgerSequence[Math.min(ledgerCalls - 1, ledgerSequence.length - 1)] + : ledger + } else { + items = sparkLedger + } + return jsonRes({ flag: true, code: 0, data: { total: items?.length ?? 0, pageNum: 1, pageSize: 50, items: items ?? [] } }) + } if (url.includes("client-popups/pending")) { if (popupFails) return jsonRes({ flag: false, code: 11001001, desc: "客户端平台、版本或构建号无效", data: null }) - return jsonRes({ flag: true, code: 0, data: popups }) + popupCalls += 1 + // popupsSequence 区分「基线读」与「签到后读」:前者看旧弹窗,后者看新发放。 + const data = popupsSequence + ? popupsSequence[Math.min(popupCalls - 1, popupsSequence.length - 1)] + : popups + return jsonRes({ flag: true, code: 0, data }) + } + if (url.includes("client-popups/complete")) { + if (onComplete) onComplete(JSON.parse(init.body)) + return jsonRes({ flag: true, code: 0, data: {} }) + } + if (url.includes("tenant-app/v2/init-app")) { + if (onInitApp) onInitApp() + return jsonRes({ flag: true, code: 0, data: {} }) } if (url.includes("membership/me") || url.includes("points/summary")) { return jsonRes({ flag: true, code: 0, data: {} }) @@ -515,6 +605,18 @@ const checkinFetch = (balanceSequence, { popups = [], identityAssert, popupFails } } +const dailyGrantRow = (createTime = "2026-11-06T00:00:30", amount = 100) => ({ + assetCode: "GENERAL_POINTS", deductions: [], direction: "CREDIT", operation: "GRANT", + amount, balanceAfter: 8000, sourceType: "ACTIVITY", reason: "每日登录赠送", createTime, + expireTime: "2026-12-07T00:00:30", +}) + +const sparkGrantRow = (amount, expireTime) => ({ + assetCode: "SPARK_POINTS", deductions: [], direction: "CREDIT", operation: "GRANT", + amount, balanceAfter: 35000, sourceType: "ACTIVITY", reason: "1024讯飞开发者节狂欢", createTime: "2026-10-22T21:34:30", + expireTime, +}) + const dailyRewardPopup = [{ popupId: 1, popupCode: "DAILY_LOGIN", popupType: "BANNER", componentType: "DAILY_REWARD_DIALOG", priority: 100, instanceKey: "2026-11-04", payload: { points: "100" }, @@ -523,17 +625,102 @@ const dailyRewardPopup = [{ const checkinAuth = { type: "api", key: "k", metadata: { session: { token: "T", ssoSessionId: "S", accountId: "A" } } } test("check-in observes the balance delta around the session touch", async () => { - const claimed = createPlugin({ fetchImpl: checkinFetch([7900, 8000]), sleepImpl: async () => {} }) + // 流水通畅但还没入账、余额涨了:发放已到账,记 claimed(不谎称 inactive)。 + const claimed = createPlugin({ fetchImpl: checkinFetch([7900, 8000], { ledger: [] }), sleepImpl: async () => {} }) const out = await claimed.auth.checkin(async () => checkinAuth) - assert.deepEqual(out, { outcome: "claimed", credit: 100, message: "每日登录积分 +100" }) + assert.equal(out.outcome, "claimed") + assert.equal(out.credit, 100) + assert.match(out.message, /余额上涨,流水尚未入账/) - const unobserved = createPlugin({ fetchImpl: checkinFetch([7900, 7900]), sleepImpl: async () => {} }) + const unobserved = createPlugin({ fetchImpl: checkinFetch([7900, 7900], { ledger: [] }), sleepImpl: async () => {} }) const out2 = await unobserved.auth.checkin(async () => checkinAuth) - // 余额没涨不谎称 done(宿主渲染成「今日已签到」):inactive + 实情 message。 + // 流水通畅但无当日 GRANT 行:没发放就是没发放,不谎称 done。 assert.equal(out2.outcome, "inactive") assert.match(out2.message, /未观测到新发放/) }) +test("check-in trusts the daily grant ledger as the authoritative signal", async () => { + // 11-06 实测:服务端午夜批量先于签到发放,纯余额差会误报 inactive; + // 流水里有当日 GRANT 行就是发了,谁触发的不影响结论。 + const plugin = createPlugin({ fetchImpl: checkinFetch([8000, 8000], { ledger: [dailyGrantRow()] }), sleepImpl: async () => {} }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.equal(out.outcome, "done") + assert.equal(out.credit, 100) + assert.match(out.message, /流水实证,先于签到发生/) +}) + +test("check-in claims when the grant lands after the check-in started", async () => { + // 签到前读流水为空(还没发),init-app 之后才有 GRANT 行 ⇒ 本次触发。 + const plugin = createPlugin({ + fetchImpl: checkinFetch([7900, 8000], { ledgerSequence: [[], [dailyGrantRow()]] }), + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.equal(out.outcome, "claimed") + assert.equal(out.credit, 100) + assert.match(out.message, /本次签到触发/) +}) + +test("check-in skips init-app when today's grant is already on the ledger", async () => { + // 流水已有当日 GRANT 行 ⇒ 只读,不再发 init-app(不给账号制造无谓写入)。 + let initCalls = 0 + let popupReads = 0 + const plugin = createPlugin({ + fetchImpl: async (input, init) => { + const url = String(input) + if (url.includes("client-popups")) popupReads += 1 + if (url.includes("points/details")) { + return jsonRes({ flag: true, code: 0, data: { items: [dailyGrantRow()] } }) + } + return checkinFetch([8000], { onInitApp: () => { initCalls += 1 } })(input, init) + }, + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.equal(out.outcome, "done") + assert.equal(initCalls, 0) + assert.equal(popupReads, 0) +}) + +test("check-in message warns about spark points expiring within 7 days", async () => { + // 星火大额批次 5 天后到期:签到消息要带上提醒。 + const soon = new Date(Date.now() + 5 * 86400000) + const p2 = (n) => String(n).padStart(2, "0") + const stamp = `${soon.getFullYear()}-${p2(soon.getMonth() + 1)}-${p2(soon.getDate())}T21:34:30` + const plugin = createPlugin({ + fetchImpl: checkinFetch([8000, 8000], { + ledger: [dailyGrantRow()], + sparkLedger: [sparkGrantRow(35000, stamp)], + }), + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.equal(out.outcome, "done") + assert.match(out.message, /35000 星火积分 \d 天内到期|35000 星火积分 今天到期/) +}) + +test("check-in message stays quiet when spark expiry is far away", async () => { + const far = new Date(Date.now() + 40 * 86400000) + const p2 = (n) => String(n).padStart(2, "0") + const stamp = `${far.getFullYear()}-${p2(far.getMonth() + 1)}-${p2(far.getDate())}T21:34:30` + const plugin = createPlugin({ + fetchImpl: checkinFetch([8000, 8000], { + ledger: [dailyGrantRow()], + sparkLedger: [sparkGrantRow(35000, stamp)], + }), + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.doesNotMatch(out.message, /到期/) +}) + +test("check-in falls back to balance and popups when the ledger query fails", async () => { + // 流水读失败退回旧判据:余额差为正仍能 claimed。 + const plugin = createPlugin({ fetchImpl: checkinFetch([7900, 8000], { ledgerFails: true }), sleepImpl: async () => {} }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.deepEqual(out, { outcome: "claimed", credit: 100, message: "每日登录积分 +100" }) +}) + test("check-in reports ineligible without a session and inactive without the campaign", async () => { const noSession = createPlugin() const out = await noSession.auth.checkin(async () => ({ type: "api", key: "k", metadata: {} })) @@ -551,20 +738,28 @@ test("check-in sends the desktop client identity on account requests", async () const seen = [] const plugin = createPlugin({ fetchImpl: checkinFetch([7900, 7900], { - identityAssert: (headers) => seen.push(headers), + identityAssert: (headers, init) => seen.push({ headers, method: init.method ?? "GET" }), }), sleepImpl: async () => {}, }) await plugin.auth.checkin(async () => checkinAuth) - assert.equal(seen.length, 6) - for (const headers of seen) { + // 只数账号面 GET:POST(init-app)不参与这条断言。签到主路径(inactive 场景)= + // plan-config、签到前流水、签到前余额、touch(me+summary)、签到后余额、签到后流水。 + const gets = seen.filter((item) => item.method !== "POST") + assert.equal(gets.length, 7) + for (const { headers } of seen) { assert.equal(headers.clientType, process.platform === "darwin" ? "22" : "21") assert.equal(headers.studioVersion, STUDIO_VERSION) } }) -test("check-in reports done when the server has a pending daily reward popup", async () => { - const plugin = createPlugin({ fetchImpl: checkinFetch([7900, 7900], { popups: dailyRewardPopup }), sleepImpl: async () => {} }) +test("check-in reports done from popups when the ledger query fails", async () => { + // 弹窗 done 路径只属于退路:流水读失败 + 余额无变化 + 签到前无旧弹窗 + + // 签到后出现 DAILY_REWARD_DIALOG ⇒ 服务端发了但流水接口没读到。 + const plugin = createPlugin({ + fetchImpl: checkinFetch([7900, 7900], { popupsSequence: [[], dailyRewardPopup], ledgerFails: true }), + sleepImpl: async () => {}, + }) const out = await plugin.auth.checkin(async () => checkinAuth) assert.deepEqual(out, { outcome: "done", credit: 100, message: "每日登录积分已发放(服务端待通知弹窗)" }) }) @@ -572,7 +767,7 @@ test("check-in reports done when the server has a pending daily reward popup", a test("check-in omits credit when the daily reward popup has no usable points", async () => { for (const payload of [{}, { points: "0" }, { points: "n/a" }]) { const plugin = createPlugin({ - fetchImpl: checkinFetch([7900, 7900], { popups: [{ ...dailyRewardPopup[0], payload }] }), + fetchImpl: checkinFetch([7900, 7900], { popupsSequence: [[], [{ ...dailyRewardPopup[0], payload }]], ledgerFails: true }), sleepImpl: async () => {}, }) const out = await plugin.auth.checkin(async () => checkinAuth) @@ -584,6 +779,7 @@ test("check-in ignores other popup types", async () => { const plugin = createPlugin({ fetchImpl: checkinFetch([7900, 7900], { popups: [{ ...dailyRewardPopup[0], componentType: "NEW_USER_DIALOG" }], + ledger: [], }), sleepImpl: async () => {}, }) @@ -591,13 +787,135 @@ test("check-in ignores other popup types", async () => { assert.equal(out.outcome, "inactive") }) -test("check-in reports failed when the popup query is rejected", async () => { - const plugin = createPlugin({ fetchImpl: checkinFetch([7900, 7900], { popupFails: true }), sleepImpl: async () => {} }) +test("check-in still falls back to popups when both ledger and popup query fail", async () => { + // 流水+弹窗都挂:退路里的退路,基线(第一次弹窗读)失败 ⇒ failed 不硬判。 + const plugin = createPlugin({ fetchImpl: checkinFetch([7900, 7900], { popupFails: true, ledgerFails: true }), sleepImpl: async () => {} }) const out = await plugin.auth.checkin(async () => checkinAuth) assert.equal(out.outcome, "failed") assert.match(out.message, /11001001|平台|版本/) }) +test("check-in never claims done when the baseline popup read fails", async () => { + // 退路里的场景:流水读失败 + 基线读失败 = 不知道签到前有没有旧弹窗, + // 签到后读到弹窗也不能判 done,更不能替用户把弹窗 complete 掉。 + let popupCalls = 0 + const completed = [] + const plugin = createPlugin({ + fetchImpl: async (input, init) => { + const url = String(input) + if (url.includes("membership/plan-config")) { + return jsonRes({ flag: true, code: 0, data: { dailyLoginEnabled: true } }) + } + if (url.includes("points/balance")) { + return jsonRes({ flag: true, code: 0, data: { totalBalance: 7900, activityBalance: 7900 } }) + } + if (url.includes("points/details")) { + return jsonRes({ flag: false, code: 11001001, desc: "参数无效" }) + } + if (url.includes("client-popups/pending")) { + popupCalls += 1 + if (popupCalls === 1) return jsonRes({ flag: false, code: 500, desc: "基线读失败" }) + return jsonRes({ flag: true, code: 0, data: dailyRewardPopup }) + } + if (url.includes("client-popups/complete")) { + completed.push(JSON.parse(init.body)) + return jsonRes({ flag: true, code: 0, data: {} }) + } + return jsonRes({ flag: true, code: 0, data: {} }) + }, + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.equal(out.outcome, "failed") + assert.match(out.message, /基线读失败/) + assert.equal(completed.length, 0) +}) + +test("check-in leaves the daily popup alone on the ledger path", async () => { + // 流水能判定时不再碰弹窗:不读、更不替用户点「知道了」(那是桌面端的交互)。 + let popupReads = 0 + const completed = [] + const mock = checkinFetch([7900, 8000], { ledgerSequence: [[], [dailyGrantRow()]] }) + const plugin = createPlugin({ + fetchImpl: async (input, init) => { + const url = String(input) + if (url.includes("client-popups/pending")) popupReads += 1 + if (url.includes("client-popups/complete")) completed.push(JSON.parse(init.body)) + return mock(input, init) + }, + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.match(out.message, /本次签到触发/) + assert.equal(popupReads, 0) + assert.equal(completed.length, 0) +}) + +test("check-in treats a pre-existing daily popup as unprovable on the fallback path", async () => { + const completed = [] + const plugin = createPlugin({ + fetchImpl: checkinFetch([7900, 7900], { + popupsSequence: [dailyRewardPopup, dailyRewardPopup], + ledgerFails: true, + onComplete: (body) => completed.push(body), + }), + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.equal(out.outcome, "inactive") + assert.match(out.message, /签到前已有/) + // 旧弹窗不属于今天,但也不替用户点掉:签到不再发 client-popups/complete。 + assert.equal(completed.length, 0) +}) + +test("check-in surfaces init-app failures instead of hiding them", async () => { + const plugin = createPlugin({ + fetchImpl: async (input) => { + const url = String(input) + if (url.includes("tenant-app/v2/init-app")) { + return jsonRes({ flag: false, code: 400, desc: "bad request" }, 400) + } + if (url.includes("membership/plan-config")) { + return jsonRes({ flag: true, code: 0, data: { dailyLoginEnabled: true } }) + } + if (url.includes("points/balance")) { + return jsonRes({ flag: true, code: 0, data: { totalBalance: 7900, activityBalance: 7900 } }) + } + if (url.includes("client-popups/pending")) return jsonRes({ flag: true, code: 0, data: [] }) + if (url.includes("points/details")) return jsonRes({ flag: true, code: 0, data: { total: 0, items: [] } }) + return jsonRes({ flag: true, code: 0, data: {} }) + }, + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.equal(out.outcome, "inactive") + assert.match(out.message, /init-app/) + assert.match(out.message, /400/) +}) + +test("check-in never calls auth/bearer-token", async () => { + const paths = [] + const plugin = createPlugin({ + fetchImpl: async (input) => { + const url = String(input) + paths.push(url) + if (url.includes("membership/plan-config")) { + return jsonRes({ flag: true, code: 0, data: { dailyLoginEnabled: true } }) + } + if (url.includes("points/balance")) { + return jsonRes({ flag: true, code: 0, data: { totalBalance: 7900, activityBalance: 7900 } }) + } + if (url.includes("client-popups/pending")) return jsonRes({ flag: true, code: 0, data: [] }) + if (url.includes("points/details")) return jsonRes({ flag: true, code: 0, data: { total: 0, items: [] } }) + return jsonRes({ flag: true, code: 0, data: {} }) + }, + sleepImpl: async () => {}, + }) + await plugin.auth.checkin(async () => checkinAuth) + assert.ok(paths.some((p) => p.includes("tenant-app/v2/init-app"))) + assert.ok(!paths.some((p) => p.includes("auth/bearer-token"))) +}) + test("check-in propagates dead sessions as signIn expired", async () => { const dead = createPlugin({ fetchImpl: async () => jsonRes({ flag: false, code: 80000, desc: "登录异常,请重新登录" }, 200), @@ -611,7 +929,7 @@ test("check-in propagates dead sessions as signIn expired", async () => { test("paste login method stores key plus cookie session inputs", async () => { const plugin = createPlugin() - const method = plugin.auth.methods[1] + const method = pasteMethod(plugin) assert.match(method.label, /粘贴/) const out = await method.authorize({ modelBearerToken: "tok-p", uid: "u7", sessionToken: "tok-36", accountId: "A7", ssoSessionId: "sso-7" }) assert.deepEqual(out, { @@ -659,5 +977,522 @@ test("module export is a plugin factory", async () => { const plugin = await AStudioPlugin() assert.equal(typeof plugin.config, "function") assert.equal(typeof plugin.auth.loader, "function") - assert.equal(plugin.auth.methods.length, 2) + assert.equal(plugin.auth.methods.length, 3) +}) + +// ---------------------------------------------------------------- 网页登录(多账号) + +// 假浏览器模块:startBrowserHarvest 立刻给出一个收割结果,removeProfile 记账。 +function fakeBrowser({ session = { token: "tok-web", accountId: "A-web", ssoSessionId: "sso-web" }, profilePath = "C:/tmp/astudio-profile" } = {}) { + const calls = { started: 0, closed: 0, released: 0, removed: [] } + return { + calls, + startBrowserHarvest() { + calls.started++ + return { + promise: Promise.resolve({ + session, + profilePath, + release: async () => { calls.released++ }, + close: async () => { calls.closed++ }, + }), + abort: async () => {}, + } + }, + async removeProfile(path) { calls.removed.push(path) }, + } +} + +const webFetch = ({ uid = "u-web", token = "tok-model-web", exchangeStatus = 200 } = {}) => async (input) => { + const url = String(input) + if (url.includes("membership/me")) return jsonRes({ flag: true, code: 0, data: uid ? { uid } : {} }) + if (url.includes("auth/bearer-token")) { + if (exchangeStatus !== 200) return jsonRes({}, exchangeStatus) + return jsonRes({ flag: true, code: 0, data: { modelBearerToken: token } }) + } + throw new Error(`unexpected ${url}`) +} + +test("web login is the recommended oauth method, listed first", () => { + const plugin = createPlugin() + const method = webMethod(plugin) + assert.equal(method.type, "oauth") + assert.match(method.label, /推荐/) + assert.match(method.label, /多账号/) + assert.equal(method.prompts, undefined) + assert.equal(plugin.auth.methods[0], method) +}) + +test("web login harvests cookies, exchanges the model token, and drops the browser profile", async () => { + const browser = fakeBrowser() + const plugin = createPlugin({ fetchImpl: webFetch(), browserModule: browser }) + const out = await webMethod(plugin).authorize({}, {}) + // 浏览器由插件自己弹出,宿主不要再开 url(mclaw 同款 opened:true)。 + assert.equal(out.url, "") + assert.equal(out.opened, true) + assert.match(out.instructions, /登录/) + assert.equal(out.method, "auto") + const result = await out.callback() + assert.deepEqual(result, { + type: "success", + key: "tok-model-web", + accountId: "u-web", + metadata: { + uid: "u-web", + method: "web", + source: STUDIO_WEB_URL, + session: { token: "tok-web", accountId: "A-web", ssoSessionId: "sso-web" }, + }, + }) + assert.equal(browser.calls.started, 1) + assert.equal(browser.calls.closed, 1) + assert.equal(browser.calls.released, 1) + // 会话已进 metadata.session,浏览器目录不留第二份凭据。 + assert.deepEqual(browser.calls.removed, ["C:/tmp/astudio-profile"]) +}) + +test("web login retries a transient membership read before failing", async () => { + let reads = 0 + const sleeps = [] + const flaky = async (input) => { + if (String(input).includes("membership/me") && reads++ === 0) throw new Error("network down") + return webFetch()(input) + } + const plugin = createPlugin({ fetchImpl: flaky, sleepImpl: async (ms) => { sleeps.push(ms) }, browserModule: fakeBrowser() }) + const out = await webMethod(plugin).authorize({}, {}) + const result = await out.callback() + assert.equal(result.type, "success") + assert.equal(result.accountId, "u-web") + assert.equal(reads, 2) + // 真实等 2s 会让这条测试变成最慢的一条;注入 sleep 只验「等过」。 + assert.deepEqual(sleeps, [2000]) +}) + +test("web login retries a membership read that answered 5xx", async () => { + let reads = 0 + const flaky = async (input) => { + if (String(input).includes("membership/me") && reads++ === 0) return jsonRes({}, 502) + return webFetch()(input) + } + const plugin = createPlugin({ fetchImpl: flaky, sleepImpl: async () => {}, browserModule: fakeBrowser() }) + const result = await (await webMethod(plugin).authorize({}, {})).callback() + assert.equal(result.type, "success") + assert.equal(reads, 2) +}) + +test("web login refuses to promise a window when no browser is installed", async () => { + const browser = { + ...fakeBrowser(), + browserExecutable: async () => { throw new Error("找不到 Chrome/Edge;请安装其中一个") }, + } + const plugin = createPlugin({ fetchImpl: webFetch(), browserModule: browser }) + await assert.rejects(() => webMethod(plugin).authorize({}, {}), /找不到 Chrome/) + assert.equal(browser.calls.started, 0) +}) + +test("check-in reads the ledger for a web session without a token cookie", async () => { + const urls = [] + const plugin = createPlugin({ + nowMsImpl: () => Date.parse("2026-11-06T02:00:00Z"), + fetchImpl: async (input) => { + const url = String(input) + urls.push(url) + if (url.includes("membership/plan-config")) { + return jsonRes({ flag: true, code: 0, data: { dailyLoginEnabled: true } }) + } + if (url.includes("points/details")) { + return jsonRes({ + flag: true, + code: 0, + data: { items: [{ direction: "CREDIT", operation: "GRANT", reason: "每日登录赠送", amount: 100, createTime: "2026-11-06 00:00:30" }] }, + }) + } + throw new Error(`unexpected ${url}`) + }, + }) + // 网页登录收割的会话可以没有 token Cookie(只需 ssoSessionId + account_id)。 + const out = await plugin.auth.checkin(async () => ({ + type: "api", + key: "k", + metadata: { session: { accountId: "A-web", ssoSessionId: "S-web" } }, + })) + assert.equal(out.outcome, "done") + assert.ok(urls.some((url) => url.includes("points/details"))) +}) + +test("web login drops the profile when the session cannot become an account", async () => { + const browser = fakeBrowser() + const plugin = createPlugin({ fetchImpl: webFetch({ uid: "" }), browserModule: browser }) + const out = await webMethod(plugin).authorize({}, {}) + const result = await out.callback() + assert.equal(result.type, "failed") + assert.match(result.error, /没有 uid/) + assert.deepEqual(browser.calls.removed, ["C:/tmp/astudio-profile"]) + assert.equal(browser.calls.closed, 1) +}) + +test("web login drops the profile when the exchange is refused", async () => { + const browser = fakeBrowser() + const plugin = createPlugin({ fetchImpl: webFetch({ exchangeStatus: 401 }), browserModule: browser }) + const out = await webMethod(plugin).authorize({}, {}) + const result = await out.callback() + assert.equal(result.type, "failed") + assert.match(result.error, /会话已失效/) + assert.deepEqual(browser.calls.removed, ["C:/tmp/astudio-profile"]) +}) + +test("two web logins with different accounts return different accountIds", async () => { + const signIn = async (uid) => { + const plugin = createPlugin({ fetchImpl: webFetch({ uid }), browserModule: fakeBrowser() }) + const out = await webMethod(plugin).authorize({}, {}) + return (await out.callback()).accountId + } + // 宿主按 accountId 给账号池分格:uid 不同 = 两个账号,uid 相同 = 同一账号。 + assert.equal(await signIn("u-a"), "u-a") + assert.equal(await signIn("u-b"), "u-b") +}) + +test("exchangeModelToken reads modelBearerToken and reports the envelope error", async () => { + const session = { token: "T", accountId: "A" } + assert.equal(await exchangeModelToken(session, webFetch({ token: "tok-x" })), "tok-x") + await assert.rejects(() => exchangeModelToken(session, async () => jsonRes({ flag: false, code: 7, desc: "拒绝" })), /拒绝/) + await assert.rejects(() => exchangeModelToken(session, async () => ({ ok: true, status: 200, json: async () => { throw new Error("x") } })), /不是 JSON/) +}) + +test("desktop sign-in falls back to account_id when the session has no uid", async () => { + const plugin = createPlugin({ + env: { ASTUDIO_HOME: "D:\astudio" }, + readFileImpl: fakeFs({ + "D:\astudio/userdata/astron-session.json": JSON.stringify({ + accountId: "A-only", token: "tok-36", ssoSessionId: "sso-36", modelBearerToken: "tok-65", + }), + }), + }) + const out = await desktopMethod(plugin).authorize({}, {}) + const result = await out.callback() + assert.equal(result.accountId, "A-only") +}) + +test("the same account signed in both ways lands on one accountId", async () => { + const plugin = createPlugin({ + env: { ASTUDIO_HOME: "D:\astudio" }, + readFileImpl: fakeFs({ + "D:\astudio/userdata/astron-session.json": JSON.stringify({ + uid: "u-same", accountId: "u-same", token: "tok-36", ssoSessionId: "sso-36", modelBearerToken: "tok-65", + }), + }), + fetchImpl: webFetch({ uid: "u-same" }), + browserModule: fakeBrowser(), + }) + const desktop = await (await desktopMethod(plugin).authorize({}, {})).callback() + const web = await (await webMethod(plugin).authorize({}, {})).callback() + assert.equal(desktop.accountId, "u-same") + assert.equal(web.accountId, desktop.accountId) +}) + +// ---------------------------------------------------------------- browser.mjs + +const fakeChrome = (cookies = []) => ({ + connection: { send: async () => ({ cookies }), closed: false }, + close: async () => {}, +}) + +test("harvestAstronSession prefers the most specific domain and needs ssoSessionId plus account_id", async () => { + const cookies = [ + { name: "token", value: "t-other", domain: ".example.com" }, + { name: "token", value: "t-generic", domain: ".xfyun.cn" }, + { name: "token", value: "t-passport", domain: "passport.xfyun.cn" }, + { name: "token", value: "t-host", domain: "agent.xfyun.cn" }, + { name: "account_id", value: "A1", domain: ".xfyun.cn" }, + { name: "ssoSessionId", value: "S1", domain: ".xfyun.cn" }, + ] + assert.deepEqual((await astroBrowser.harvestAstronSession(fakeChrome(cookies))).session, { + token: "t-host", accountId: "A1", ssoSessionId: "S1", + }) + // 网页登录可能没有 token Cookie:账号面与换发只需 ssoSessionId + account_id。 + const noToken = cookies.filter((c) => c.name !== "token") + assert.deepEqual((await astroBrowser.harvestAstronSession(fakeChrome(noToken))).session, { + accountId: "A1", ssoSessionId: "S1", + }) + assert.equal(await astroBrowser.harvestAstronSession(fakeChrome([{ name: "token", value: "t", domain: ".xfyun.cn" }])), undefined) + assert.equal(await astroBrowser.harvestAstronSession(fakeChrome([ + { name: "account_id", value: "A1", domain: ".xfyun.cn" }, + ])), undefined) +}) + +test("startBrowserHarvest rejects, closes the window, and removes the profile on abort", async () => { + let closed = 0 + const removed = [] + const open = async ({ profilePath }) => ({ + browser: { ...fakeChrome(), close: async () => { closed++ } }, + profilePath, + release: async () => {}, + }) + const harvest = astroBrowser.startBrowserHarvest({ + startUrl: "https://example.com", + profilePath: "C:/tmp/astudio-abort-profile", + open, + removeProfileImpl: async (path) => { removed.push(path) }, + }) + // 先挂 rejection 断言再 abort:abort 会立刻让 promise 拒绝。 + const rejected = assert.rejects(() => harvest.promise, /登录已取消/) + await harvest.abort() + await rejected + assert.equal(closed, 1) + // 宿主取消后 callback 不会再被调,profile 没人认领,必须删掉(abort 与 catch + // 都会删,rm 幂等,所以只断言「删过这个路径」)。 + assert.ok(removed.includes("C:/tmp/astudio-abort-profile")) +}) + +test("startBrowserHarvest times out when no sign-in appears", async () => { + const removed = [] + const open = async ({ profilePath }) => ({ browser: fakeChrome(), profilePath, release: async () => {} }) + const harvest = astroBrowser.startBrowserHarvest({ + startUrl: "https://example.com", + deadlineMs: 0, + open, + removeProfileImpl: async (path) => { removed.push(path) }, + }) + await assert.rejects(() => harvest.promise, (error) => { + assert.match(error.message, /登录超时/) + // 不足 1 分钟要说秒,不能渲染成「0 分钟」。 + assert.doesNotMatch(error.message, /0 分钟/) + return true + }) + assert.equal(removed.length, 1) +}) + +test("startBrowserHarvest removes the profile when the browser cannot start", async () => { + const removed = [] + const harvest = astroBrowser.startBrowserHarvest({ + startUrl: "https://example.com", + profilePath: "C:/tmp/never-opened", + open: async () => { throw new Error("找不到浏览器") }, + removeProfileImpl: async (path) => { removed.push(path) }, + }) + await assert.rejects(() => harvest.promise, /找不到浏览器/) + assert.deepEqual(removed, ["C:/tmp/never-opened"]) +}) + +test("web login does not retry a deterministic 4xx", async () => { + let calls = 0 + const plugin = createPlugin({ + fetchImpl: async (input) => { + if (String(input).includes("membership/me")) { + calls++ + return jsonRes({ flag: false, code: 7, desc: "参数无效" }, 400) + } + return webFetch()(input) + }, + browserModule: fakeBrowser(), + }) + const out = await webMethod(plugin).authorize({}, {}) + const result = await out.callback() + assert.equal(result.type, "failed") + assert.match(result.error, /参数无效/) + assert.equal(calls, 1) +}) + +test("usage reads the account API from a token-less web session", async () => { + const seen = [] + const plugin = createPlugin({ + fetchImpl: async (input) => { + seen.push(String(input)) + if (String(input).includes("points/balance")) { + return jsonRes({ flag: true, code: 0, data: { totalBalance: 42 } }) + } + if (String(input).includes("membership/me")) return jsonRes({ flag: true, code: 0, data: { uid: "u" } }) + return jsonRes({ flag: true, code: 0, data: {} }) + }, + }) + const out = await plugin.auth.usage(async () => ({ + type: "api", + key: "k", + metadata: { session: { accountId: "A", ssoSessionId: "S" } }, + })) + assert.ok(seen.some((u) => u.includes("points/balance"))) + assert.equal(out.windows[0].balance, 42) +}) + +// ---------------------------------------------------------------- 北京时间窗口 + +test("check-in builds the daily ledger window in Beijing time", async () => { + // 北京 2026-11-06 00:00:30(UTC 还是 11-05):窗口必须是北京的当日, + // 否则午夜批量发放会被算到窗口外,签到误报 inactive。 + const seen = [] + const plugin = createPlugin({ + nowMsImpl: () => Date.parse("2026-11-05T16:00:30Z"), + fetchImpl: async (input) => { + const url = String(input) + seen.push(url) + if (url.includes("points/details")) return jsonRes({ flag: true, code: 0, data: { items: [] } }) + if (url.includes("membership/plan-config")) return jsonRes({ flag: true, code: 0, data: { dailyLoginEnabled: true } }) + if (url.includes("points/balance")) return jsonRes({ flag: true, code: 0, data: { totalBalance: 8000, activityBalance: 8000 } }) + return jsonRes({ flag: true, code: 0, data: {} }) + }, + sleepImpl: async () => {}, + }) + await plugin.auth.checkin(async () => checkinAuth) + const daily = seen.find((url) => url.includes("points/details")) + const params = new URL(daily).searchParams + assert.equal(params.get("startTime"), "2026-11-06 00:00:00") + assert.equal(params.get("endTime"), "2026-11-06 00:00:30") +}) + +test("spark expiry window also uses Beijing bounds", async () => { + const seen = [] + const plugin = createPlugin({ + nowMsImpl: () => Date.parse("2026-11-06T00:00:00+08:00"), + fetchImpl: async (input) => { + const url = String(input) + seen.push(url) + if (url.includes("points/balance")) { + return jsonRes({ flag: true, code: 0, data: { totalBalance: 0, activityBalance: 0, sparkTotalBalance: 35000 } }) + } + if (url.includes("membership/me")) return jsonRes({ flag: true, code: 0, data: {} }) + if (url.includes("points/details")) return jsonRes({ flag: true, code: 0, data: { items: [] } }) + throw new Error(`unexpected ${url}`) + }, + }) + await plugin.auth.usage(async () => ({ type: "api", key: "k", metadata: { session: { token: "T", accountId: "A" } } })) + const spark = seen.find((url) => url.includes("points/details")) + const params = new URL(spark).searchParams + assert.equal(params.get("startTime"), "2026-09-07 00:00:00") + assert.equal(params.get("endTime"), "2026-11-06 00:00:00") +}) + +test("check-in ignores a GRANT row that is not the daily login grant", async () => { + // reason 过滤:别的活动赠送不能冒充每日登录积分。 + const plugin = createPlugin({ + fetchImpl: checkinFetch([8000, 8000], { ledger: [{ ...dailyGrantRow(), reason: "活动奖励" }] }), + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.equal(out.outcome, "inactive") +}) + +test("spark expiry sums one batch, skips expired rows, and caps at the balance", async () => { + const plugin = createPlugin({ + nowMsImpl: () => Date.parse("2026-11-06T00:00:00+08:00"), + fetchImpl: async (input) => { + const url = String(input) + if (url.includes("points/balance")) { + return jsonRes({ flag: true, code: 0, data: { totalBalance: 0, activityBalance: 0, sparkTotalBalance: 20000 } }) + } + if (url.includes("membership/me")) return jsonRes({ flag: true, code: 0, data: {} }) + if (url.includes("points/details")) { + return jsonRes({ flag: true, code: 0, data: { items: [ + sparkGrantRow(10000, "2026-11-22T21:34:30"), + sparkGrantRow(25000, "2026-11-22T21:34:30"), + sparkGrantRow(9999, "2026-10-01T00:00:00"), // 已过期,跳过 + ] } }) + } + throw new Error(`unexpected ${url}`) + }, + }) + const out = await plugin.auth.usage(async () => ({ type: "api", key: "k", metadata: { session: { token: "T", accountId: "A" } } })) + // 同批 10000+25000=35000,但余额只剩 20000 ⇒ 提示按余额封顶。 + const spark = out.windows.find((w) => w.name === "星火积分") + assert.equal(spark.runsOut, 20000) + assert.equal(spark.runsOutAt, "2026-11-22T13:34:30.000Z") +}) + +test("spark expiry reads past the first page of ledger rows", async () => { + const filler = Array.from({ length: 50 }, (_, i) => ({ ...dailyGrantRow(), createTime: `2026-10-${String((i % 28) + 1).padStart(2, "0")}T00:00:00` })) + const plugin = createPlugin({ + nowMsImpl: () => Date.parse("2026-11-06T00:00:00+08:00"), + fetchImpl: async (input) => { + const url = String(input) + if (url.includes("points/balance")) { + return jsonRes({ flag: true, code: 0, data: { totalBalance: 0, activityBalance: 0, sparkTotalBalance: 35000 } }) + } + if (url.includes("membership/me")) return jsonRes({ flag: true, code: 0, data: {} }) + if (url.includes("points/details")) { + const page = Number(new URL(url).searchParams.get("pageNum") ?? 1) + const items = page === 1 ? filler : [sparkGrantRow(35000, "2026-11-22T21:34:30")] + return jsonRes({ flag: true, code: 0, data: { items } }) + } + throw new Error(`unexpected ${url}`) + }, + }) + const out = await plugin.auth.usage(async () => ({ + type: "api", + key: "k", + metadata: { session: { token: "T", accountId: "A" } }, + })) + const spark = out.windows.find((w) => w.name === "星火积分") + assert.equal(spark.runsOut, 35000) + assert.equal(spark.runsOutAt, "2026-11-22T13:34:30.000Z") +}) + +test("check-in counts days to expiry by Beijing calendar days", async () => { + // 北京 11-06 23:00,到期 11-07 00:30:不到 24 小时,但日历上是「1 天内」。 + const plugin = createPlugin({ + nowMsImpl: () => Date.parse("2026-11-06T23:00:00+08:00"), + fetchImpl: checkinFetch([8000, 8000], { + ledger: [dailyGrantRow()], + sparkLedger: [sparkGrantRow(35000, "2026-11-07T00:30:00")], + }), + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.match(out.message, /35000 星火积分 1 天内到期/) +}) + +test("web login does not retry a session the server turns away", async () => { + // code 80000 = 登录异常:studioJson 映射成 signIn expired,retryTransient 不重试。 + let calls = 0 + const plugin = createPlugin({ + fetchImpl: async (input) => { + if (String(input).includes("membership/me")) { + calls++ + return jsonRes({ flag: false, code: 80000, desc: "登录异常,请重新登录" }) + } + return webFetch()(input) + }, + browserModule: fakeBrowser(), + }) + const out = await webMethod(plugin).authorize({}, {}) + const result = await out.callback() + assert.equal(result.type, "failed") + assert.match(result.error, /会话已失效/) + assert.equal(calls, 1) +}) + +test("web login's account requests refuse redirects and carry a timeout", async () => { + let exchangeInit + const plugin = createPlugin({ + fetchImpl: async (input, init) => { + if (String(input).includes("auth/bearer-token")) { + exchangeInit = init + return jsonRes({ flag: true, code: 0, data: { modelBearerToken: "tok" } }) + } + return webFetch()(input) + }, + browserModule: fakeBrowser(), + }) + const out = await webMethod(plugin).authorize({}, {}) + const result = await out.callback() + assert.equal(result.type, "success") + assert.equal(exchangeInit.redirect, "error") + assert.ok(exchangeInit.signal, "请求要带超时 signal") +}) + +test("web login maps a code 80000 from the exchange to sign-in expired", async () => { + let exchangeCalls = 0 + const plugin = createPlugin({ + fetchImpl: async (input) => { + if (String(input).includes("auth/bearer-token")) { + exchangeCalls++ + return jsonRes({ flag: false, code: 80000, desc: "登录异常,请重新登录" }) + } + return webFetch()(input) + }, + browserModule: fakeBrowser(), + }) + const out = await webMethod(plugin).authorize({}, {}) + const result = await out.callback() + assert.equal(result.type, "failed") + assert.match(result.error, /会话已失效/) + assert.equal(exchangeCalls, 1) }) diff --git a/packages/astudio/package.json b/packages/astudio/package.json index dbc0219..ee3b1b2 100644 --- a/packages/astudio/package.json +++ b/packages/astudio/package.json @@ -1,12 +1,13 @@ { "name": "@magpie-community/opencode-astudio-auth", - "version": "0.1.4", - "description": "AStudio (iFLYTEK Astron Studio) desktop sign-in as an OpenCode/magpie provider: Responses model gateway with live model catalog", + "version": "0.2.0", + "description": "AStudio (iFLYTEK Astron Studio) sign-in as an OpenCode/magpie provider: browser sign-in with one account-pool slot per account, or the desktop sign-in, over the Responses model gateway with live model catalog", "type": "module", "main": "./opencode.mjs", "exports": { ".": "./opencode2.mjs" }, "files": [ "index.mjs", + "browser.mjs", "opencode.mjs", "opencode2.mjs", "README.md", diff --git a/registry.json b/registry.json index 64217de..183e2d0 100644 --- a/registry.json +++ b/registry.json @@ -189,8 +189,8 @@ ], "community": true, "summary": { - "en": "Third-party Magpie adapter for dsh-providers-hub (by JetLi): ten providers, each a separate channel you can sign in to, meter and switch off on its own — AStudio (iFlytek), Accio (Alibaba), LobsterAI (Youdao), MagiCrew (letsmagic.cn / magicrew.ai), AutoClaw (international autoglm.ai / China zhipuai.cn), and Loomy (iFlytek), plus MonkeyCode (monkeycode-ai.com China / monkeycode-ai.net international). Channels already in the registry are shipped only with a named difference (#614; see the notes below). Runs without DSH. Its AStudio signs in on a local page (SMS, password or WeChat QR, no desktop app needed) and calls chat/completions; the standalone AStudio plugin (astudio) reuses the desktop sign-in and calls Responses. On one account both share the same daily points pool. Its AutoClaw providers sign in by pasting an accessToken + refreshToken, or by reading an already signed-in AutoClaw desktop client (current Windows user only, off unless clicked) — web OAuth and phone SMS are NOT supported here, use opencode-autoclaw-auth for those. Note: importing rotates the one-time refresh token, which signs the desktop client out; it will ask for sign-in again afterwards. Both plugins read one account's credit balance, so spend in one and the other sees it. Its Loomy adds WeChat QR sign-in (the official iFlytek WeChat OAuth, long-poll for the code) — the standalone Loomy plugin (opencode-loomy-auth) has SMS code + pasted session but no WeChat QR; SMS code sign-in works the same in both (the plugin's local sign-in page offers only WeChat QR and SMS — no pasted-session entry; use opencode-loomy-auth for that), and both read one account's credit balance. Its MonkeyCode providers (new channels, no standalone-package overlap) reach the OhMyAgent gateway over the Anthropic Messages protocol with a per-prompt HMAC signature; sign in through a browser window (the plugin reads the HttpOnly session cookie and exchanges it for gateway credentials) or paste an API key + signing secret; the daily-tier models (monkeycode-basic/pro/ultra/…) draw on the subscription quota and unprefixed models draw on credits, with a Cap proof-of-work daily check-in when a web session is present.", - "zh": "dsh-providers-hub(作者 JetLi)的第三方适配:十条供应商(每渠道一条,可各自登录/看额度/单独关闭)——AStudio(讯飞)、Accio(阿里)、LobsterAI(有道)、超级麦吉/MagiCrew(letsmagic.cn / magicrew.ai)、AutoClaw(autoglm.ai 国际 / zhipuai.cn 国内)、Loomy(讯飞)、MonkeyCode(monkeycode-ai.com 国内 / monkeycode-ai.net 国际)。与 registry 已有渠道重复的,只有写明差别(#614,见下方各渠道说明)才提供。不依赖 DSH 运行。其中 AStudio 在本地登录页用短信、密码或微信扫码登录(不需要桌面端),走 chat/completions;独立的 AStudio 插件(astudio)复用桌面端登录态,走 Responses。同一账号两边共用一个每日积分池。其 AutoClaw 两条渠道的登录方式只有两种:粘贴 accessToken + refreshToken,或读取已登录的 AutoClaw 桌面端(仅当前 Windows 用户、默认关闭、需主动点击);不支持网页 OAuth 与手机验证码,需要请用 opencode-autoclaw-auth。注意:导入会轮换一次性的 refresh_token,桌面客户端会被登出、之后需要重新登录。两个插件读同一账号的积分余额,一边用掉的另一边会同步减少。其 Loomy 新增微信扫码登录(讯飞官方微信 OAuth,长轮询拿 code)——独立的 Loomy 插件(opencode-loomy-auth)只有短信验证码与粘贴 session,没有微信扫码;短信验证码两边同款(本插件登录页只有微信扫码与短信两条路,没有粘贴 session 入口,要粘贴请用独立包),读的也是同一账号的积分余额。 其 MonkeyCode 两条渠道为新渠道(registry 无同渠道独立包),走 OhMyAgent 网关的 Anthropic Messages 协议(按 prompt 文本做 HMAC 签名);登录为浏览器窗口(插件读 HttpOnly 会话 cookie 换网关凭据)或粘贴 API Key + 签名密钥;monkeycode-basic/pro/ultra/ 前缀模型走订阅每日额度、不带前缀走积分,有网页会话时支持 Cap 工作量证明的每日签到。" + "en": "Third-party Magpie adapter for dsh-providers-hub (by JetLi): ten providers, each a separate channel you can sign in to, meter and switch off on its own — AStudio (iFlytek), Accio (Alibaba), LobsterAI (Youdao), MagiCrew (letsmagic.cn / magicrew.ai), AutoClaw (international autoglm.ai / China zhipuai.cn), and Loomy (iFlytek), plus MonkeyCode (monkeycode-ai.com China / monkeycode-ai.net international). Channels already in the registry are shipped only with a named difference (#614; see the notes below). Runs without DSH. Its AStudio signs in on a local page (SMS, password or WeChat QR, no desktop app needed) and calls chat/completions; the standalone AStudio plugin (astudio) signs in through a browser or reuses the desktop sign-in, and calls Responses. On one account both share the same daily points pool. Its AutoClaw providers sign in by pasting an accessToken + refreshToken, or by reading an already signed-in AutoClaw desktop client (current Windows user only, off unless clicked) — web OAuth and phone SMS are NOT supported here, use opencode-autoclaw-auth for those. Note: importing rotates the one-time refresh token, which signs the desktop client out; it will ask for sign-in again afterwards. Both plugins read one account's credit balance, so spend in one and the other sees it. Its Loomy adds WeChat QR sign-in (the official iFlytek WeChat OAuth, long-poll for the code) — the standalone Loomy plugin (opencode-loomy-auth) has SMS code + pasted session but no WeChat QR; SMS code sign-in works the same in both (the plugin's local sign-in page offers only WeChat QR and SMS — no pasted-session entry; use opencode-loomy-auth for that), and both read one account's credit balance. Its MonkeyCode providers (new channels, no standalone-package overlap) reach the OhMyAgent gateway over the Anthropic Messages protocol with a per-prompt HMAC signature; sign in through a browser window (the plugin reads the HttpOnly session cookie and exchanges it for gateway credentials) or paste an API key + signing secret; the daily-tier models (monkeycode-basic/pro/ultra/…) draw on the subscription quota and unprefixed models draw on credits, with a Cap proof-of-work daily check-in when a web session is present.", + "zh": "dsh-providers-hub(作者 JetLi)的第三方适配:十条供应商(每渠道一条,可各自登录/看额度/单独关闭)——AStudio(讯飞)、Accio(阿里)、LobsterAI(有道)、超级麦吉/MagiCrew(letsmagic.cn / magicrew.ai)、AutoClaw(autoglm.ai 国际 / zhipuai.cn 国内)、Loomy(讯飞)、MonkeyCode(monkeycode-ai.com 国内 / monkeycode-ai.net 国际)。与 registry 已有渠道重复的,只有写明差别(#614,见下方各渠道说明)才提供。不依赖 DSH 运行。其中 AStudio 在本地登录页用短信、密码或微信扫码登录(不需要桌面端),走 chat/completions;独立的 AStudio 插件(astudio)可在浏览器里登录(可多账号)或复用桌面端登录态,也可以粘贴模型凭据,走 Responses。同一账号两边共用一个每日积分池。其 AutoClaw 两条渠道的登录方式只有两种:粘贴 accessToken + refreshToken,或读取已登录的 AutoClaw 桌面端(仅当前 Windows 用户、默认关闭、需主动点击);不支持网页 OAuth 与手机验证码,需要请用 opencode-autoclaw-auth。注意:导入会轮换一次性的 refresh_token,桌面客户端会被登出、之后需要重新登录。两个插件读同一账号的积分余额,一边用掉的另一边会同步减少。其 Loomy 新增微信扫码登录(讯飞官方微信 OAuth,长轮询拿 code)——独立的 Loomy 插件(opencode-loomy-auth)只有短信验证码与粘贴 session,没有微信扫码;短信验证码两边同款(本插件登录页只有微信扫码与短信两条路,没有粘贴 session 入口,要粘贴请用独立包),读的也是同一账号的积分余额。 其 MonkeyCode 两条渠道为新渠道(registry 无同渠道独立包),走 OhMyAgent 网关的 Anthropic Messages 协议(按 prompt 文本做 HMAC 签名);登录为浏览器窗口(插件读 HttpOnly 会话 cookie 换网关凭据)或粘贴 API Key + 签名密钥;monkeycode-basic/pro/ultra/ 前缀模型走订阅每日额度、不带前缀走积分,有网页会话时支持 Cap 工作量证明的每日签到。" } }, { @@ -215,7 +215,7 @@ } }, { "package": "@magpie-community/opencode-astudio-auth", "name": "AStudio", "providers": ["astudio"], "community": true, - "summary": { "en": "Unofficial AStudio (iFLYTEK Astron Studio desktop): reuse the desktop sign-in to serve its Responses model gateway, with the live model catalog, daily login-points check-in and points balance. Desktop discovery runs on Windows (registry lookup), with a paste-token fallback. Differs from Providers Hub's hub-astudio, which signs in on a local page (SMS, password or WeChat QR) and calls chat/completions; on one account both share the same daily points pool.", "zh": "非官方 AStudio(科大讯飞 Astron Studio 桌面端):复用桌面端登录态接入其模型网关,含实时模型目录、每日登录积分签到与积分余额。桌面端发现仅 Windows(注册表定位),另有粘贴凭据方式。与 Providers Hub 的 hub-astudio 不同:那边在本地登录页用短信、密码或微信扫码登录,走 chat/completions;同一账号两边共用一个每日积分池。" } }, + "summary": { "en": "Unofficial AStudio (iFLYTEK Astron Studio): sign in through a browser (each account gets its own pool slot), reuse the desktop sign-in, or paste a token, to serve its Responses model gateway with the live model catalog, daily login-points check-in (read from the credit ledger) and points balance with spark-point expiry. Differs from Providers Hub's hub-astudio, which signs in on a local page (SMS, password or WeChat QR) and calls chat/completions; on one account both share the same daily points pool.", "zh": "非官方 AStudio(科大讯飞 Astron Studio):支持浏览器登录(每个账号占账号池一格)、复用桌面端登录态或粘贴凭据,接入其模型网关,含实时模型目录、每日登录积分签到(按积分流水判定)与积分余额/星火到期时间。与 Providers Hub 的 hub-astudio 不同:那边在本地登录页用短信、密码或微信扫码登录,走 chat/completions;同一账号两边共用一个每日积分池。" } }, { "package": "@magpie-community/opencode-agnes-code-auth", "name": "Agnes Code", "providers": ["agnes-code"], "community": true, "summary": { "en": "Unofficial Agnes Code desktop: reuse the desktop sign-in for its OpenAI-compatible gateway, with the live model catalog, daily credit check-in and points balance. Desktop decryption is Windows-only; a paste-token method covers the rest. Differs from opencode-agnes-auth (`agnes`), which signs in to Agnes AI international in Chrome and meters that product's plans and USD balance: this one serves the Agnes Code desktop product and its daily credits.", "zh": "非官方 Agnes Code 桌面端:复用桌面端登录态接入其 OpenAI 兼容网关,含实时模型目录、每日积分签到与余额显示。桌面端解密仅限 Windows,其余平台用粘贴 accessToken。与 opencode-agnes-auth(`agnes`)不同:那边在 Chrome 里登录 Agnes AI 国际版、显示该产品的套餐与美元余额;本包服务 Agnes Code 桌面端产品与它的每日积分。" } }, { "package": "@magpie-community/opencode-tabbit-auth", "name": "Tabbit", "icon": "https://web.tabbit.com/favicon.ico", "providers": ["tabbit"], "community": true,