diff --git a/packages/autoclaw/README.md b/packages/autoclaw/README.md new file mode 100644 index 0000000..e6e7bf0 --- /dev/null +++ b/packages/autoclaw/README.md @@ -0,0 +1,84 @@ +# @magpie-community/opencode-autoclaw-auth + +[OpenCode](https://opencode.ai) / [magpie](https://usemagpie.ai) provider 插件:**AutoClaw(智谱澳龙 / OpenClaw 云端账号体系)**。 + +一个包注册两个供应商,按账号所在地分开登录、分开记额度: + +| 供应商 id | 登录方式 | 上游 host | 模型引用 | +|---|---|---|---| +| `autoclaw` | Google / z.ai 网页 OAuth | `autoglm-api.autoglm.ai` | `autoclaw/zai_auto` 等 | +| `autoclaw-cn` | 手机验证码(+86) | `autoglm-api.zhipuai.cn` | `autoclaw-cn/zai_auto` 等 | + +两个供应商都支持 magpie 的多账号、故障切换、token 自动轮换与积分余额显示。模型为带前缀的 routeModelId(`zai_` 智谱 / `zaicoding_` coding plan / `tdpsk_` 豆包 DeepSeek): + +- `zai_auto` / `zai_auto-fast`(自动路由,推荐默认) +- `zai_glm-5.3-flash` / `zai_glm-5-turbo` +- `zaicoding_glm-5.3` +- `tdpsk_deepseek-v4-flash-202605` / `tdpsk_deepseek-v4-pro-202606` + +## 安装 + +```sh +magpie plugin add @magpie-community/opencode-autoclaw-auth +magpie plugin login autoclaw # Google / z.ai 网页登录 +magpie plugin login autoclaw-cn # 手机验证码 +magpie provider test autoclaw zai_auto +magpie quota # 积分余额 +``` + +OpenCode 同样可加载(`opencode auth login`)。登录信息保存在 magpie 的 `plugin-auth.json`(600 权限)/ OpenCode 的 `auth.json`。 + +## 直连说明(不经本地网关) + +插件**直连上游云 API**,登录/对话/刷新/积分全部自行完成: + +- 对话走 `POST {host}/autoclaw-proxy/proxy/autoclaw/v1/chat/completions`(`X-Authorization` 鉴权); +- token 过期前自动轮换(refresh token 一次一换,`auth.refresh` 钩子交给 magpie 串行化,不会双花); +- 积分余额通过 `auth.usage` 显示(纯积分制,无总量上限,`aside` 窗口展示余额); +- **国际版登录是完整本地实现**:插件在 127.0.0.1 上取官方 TokenServer 端口池中的一个端口 + (18432/19654/19723/53699,OAuth client 回调白名单;被占自动顺延)起临时服务器,内嵌引导页完成 + 阿里滑块验证(`AliyunCaptcha` SDK,`ali_captcha_verify_param` 回执)→ 获取授权页 → + 自动跳转 Google/z.ai → 回调自动捕获 code,全程浏览器完成、无需粘贴;登录结束服务器即关 + (未完成时 10 分钟后自动关闭释放端口)。回调 code 必须匹配授权页下发的 `state`,其余一律拒收 + (防伪造回调劫持登录);本地服务器的写接口仅接受 127.0.0.1/localhost 来源。 + +## 每日签到 + +两种方式,推荐用**原生签到**: + +**① magpie 原生签到(magpie ≥ v0.1.1083,推荐)**:插件实现 `auth.checkin` 钩子,走 magpie 统一调度——Settings → Usage → Plugins 里每个供应商有 **Daily check-in** 开关(默认关),打开后每天每账号自动签一次(北京时间;启动 2 分钟后首查、每 30 分钟轮询,失败 30 分钟后重试),账户 Usage 卡片显示签到结果,也可 **Check in now** 手动签。 + +**② 旧链路自动补签(默认关)**:查额度(`magpie quota`、GUI 刷新)与 token 刷新时发现未签就补签(服务端幂等,本地按天去重、失败按小时重试)。旧版 magpie / OpenCode 宿主或偏好该行为的用户开启 `signinOnUsage`。 + +`magpie quota` 的额度窗口里始终显示**每日签到**状态行(今日已签 ✓ / 今日未签 +N)。 + +旧链路的开关有**两个通道**(插件 options 优先,配置文件兜底;原生签到开关只在 GUI 的 Settings 里): + +```sh +# 通道 1:插件 options(magpie CLI) +magpie plugin options @magpie-community/opencode-autoclaw-auth '{"signin": false}' # 关闭自动补签总开关 +magpie plugin options @magpie-community/opencode-autoclaw-auth '{"signinHour": 8}' # 只在 8:00–8:59 补签 +magpie plugin options @magpie-community/opencode-autoclaw-auth '{"signinOnUsage": true}' # 开启查额度/刷新自动补签 + +# 通道 2:配置文件 ~/.config/magpie/autoclaw.json(保存即生效,热读取) +cat > ~/.config/magpie/autoclaw.json <<'EOF' +{ "signin": true, "signinHour": null, "signinOnUsage": true } +EOF +``` + +| 选项 | 默认 | 说明 | +|---|---|---| +| `signin` | `true` | 旧链路自动补签总开关(不影响原生 checkin) | +| `signinOnUsage` | `false` | 查额度/刷新时自动补签(默认关,交给原生开关) | +| `signinHour` | `null` | 限定补签小时:`8` = 仅当本地时间处于 8:00–8:59 时补签;`null` 不限 | + +## 已知行为 + +- 手机号账号只认国内 host、z.ai/Google 账号只认国际 host;对话 fetch 已内置 401/403 自动换侧重试。 +- 上游模型白名单随版本变化,模型下线时上游返回 `400 非法模型`(原样透传错误消息)。 +- refresh token 与 AutoClaw 桌面端**共用会互踢**(双方都轮换),插件账号请勿同时在桌面端登录。 +- 上游偶发改协议时,`CLIENT_VERSION` / 端点路径可能需要随官方客户端更新。 + +## 免责声明 + +本包为**非官方**社区插件,与智谱 AI / OpenClaw / AutoClaw 无任何关联。实现基于对官方客户端行为的逆向分析与实测,仅供个人学习研究;使用产生的账号风险由使用者自行承担。上游协议变更可能导致插件随时失效。 diff --git a/packages/autoclaw/index.mjs b/packages/autoclaw/index.mjs new file mode 100644 index 0000000..eeae53b --- /dev/null +++ b/packages/autoclaw/index.mjs @@ -0,0 +1,1028 @@ +/** + * 国际版网页 OAuth —— 完整本地实现,不依赖 workbuddy2api / opencodex 面板。 + * + * 宿主协议形态:authorize(inputs) 启动本地临时 HTTP 服务器(127.0.0.1 上 + * 官方 TokenServer 端口池之一),立即返回 { url: 本地引导页, method: "auto", callback }; + * 浏览器全流程在本地页完成: + * + * 引导页(内嵌) ──拉 /captcha-config──▶ 未启用滑块 ──▶ 直接「继续授权」 + * │启用 + * ▼ + * 加载 AliyunCaptcha SDK(CDN) → 用户拖滑块 → 回执 POST /captcha + * ▼ + * 「继续授权」──POST /open-auth──▶ 插件带回执调上游 {vendor}-oauth-url + * ▼ + * 页面自动跳授权页(Google/z.ai)→ 302 回 /callback?code=…&state=… + * ▼ + * callback() 里用 code 调 {vendor}-oauth-login 换 token → {type:"success"} + */ + +import { createHash, randomBytes } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { Buffer } from "node:buffer"; +import * as http from "node:http"; +import { spawn } from "node:child_process"; + +const APP_ID = "100003"; +const APP_KEY = "38d2391985e2369a5fb8227d8e6cd5e5"; +const PRODUCT = "autoclaw"; +const CHANNEL = "AutoClaw4"; +const CLIENT_VERSION = "1.18.1"; +const PLATFORM_TM = process.platform === "darwin" ? "mac" : process.platform === "win32" ? "win" : "linux"; +const USER_AGENT = `AutoClaw/${CLIENT_VERSION} (${PLATFORM_TM}-${process.arch})`; + +const GLOBAL_HOST = "https://autoglm-api.autoglm.ai"; +const CN_HOST = "https://autoglm-api.zhipuai.cn"; + +const CHAT_PATH = "/autoclaw-proxy/proxy/autoclaw/v1/chat/completions"; +const WALLETS_PATH = `/agent-assetmgr/api/v2/wallets?biz_app_id=${PRODUCT}`; + +const OAUTH_EXPIRY_SKEW_MS = 10 * 60 * 1000; +const FALLBACK_EXPIRES_IN_S = 5 * 3600; +/** 本地 OAuth 会话上限:callback 的等待是 5 分钟;宿主不调 callback 时兜底释放端口。 */ +const OAUTH_SESSION_TIMEOUT_MS = 10 * 60 * 1000; + +/** 模型清单:键 = magpie 里显示的 id;值里的 id = 上游接受的 routeModelId。 */ +function autoclawModels() { + return { + "zai_auto": { name: "GLM Auto (路由)", id: "zai_auto", limit: { context: 200000, output: 32000 }, reasoning: true, tool_call: true }, + "zai_auto-fast": { name: "GLM Auto Fast", id: "zai_auto-fast", limit: { context: 200000, output: 32000 }, reasoning: true, tool_call: true }, + "zai_glm-5.3-flash": { name: "GLM-5.3 Flash", id: "zai_glm-5.3-flash", limit: { context: 1000000, output: 32000 }, reasoning: true, tool_call: true }, + "zai_glm-5-turbo": { name: "GLM-5 Turbo", id: "zai_glm-5-turbo", limit: { context: 200000, output: 32000 }, reasoning: true, tool_call: true }, + "zaicoding_glm-5.3": { name: "GLM-5.3 Coding", id: "zaicoding_glm-5.3", limit: { context: 1000000, output: 131072 }, reasoning: true, tool_call: true }, + "tdpsk_deepseek-v4-flash-202605": { name: "DeepSeek V4 Flash", id: "tdpsk_deepseek-v4-flash-202605", limit: { context: 1000000, output: 384000 }, reasoning: true, tool_call: true }, + "tdpsk_deepseek-v4-pro-202606": { name: "DeepSeek V4 Pro", id: "tdpsk_deepseek-v4-pro-202606", limit: { context: 1000000, output: 384000 }, reasoning: true, tool_call: true }, + }; +} + +// --------------------------------------------------------------------------- +// 基础工具 +// --------------------------------------------------------------------------- + +function md5Hex(input) { + return createHash("md5").update(input).digest("hex"); +} + +function randomHex(n) { + return randomBytes(n).toString("hex"); +} + +/** 64 位十六进制 device_id(官方客户端形态)。 */ +function newDeviceId() { + return randomHex(32); +} + +/** 业务签名头(task/wallet/登录/refresh),WAF 要求带客户端 UA。 */ +function bizHeaders(accessToken) { + const ts = String(Math.floor(Date.now() / 1000)); + const h = { + "Content-Type": "application/json", + "Accept": "*/*", + "User-Agent": USER_AGENT, + "X-Version": CLIENT_VERSION, + "X-Tm": PLATFORM_TM, + "X-Product": PRODUCT, + "X-Auth-Appid": APP_ID, + "X-Auth-TimeStamp": ts, + "X-Auth-Sign": md5Hex(`${APP_ID}&${ts}&${APP_KEY}`), + "X-Trace-Id": randomHex(16), + "X-Lang": "zh-CN", + "X-Channel": CHANNEL, + "Origin": "http://localhost:18432", + "Referer": "http://localhost:18432/", + }; + if (accessToken) h["Authorization"] = `Bearer ${accessToken}`; + return h; +} + +function nonEmptyString(v) { + return typeof v === "string" && v.length > 0 ? v : undefined; +} + +/** 剥掉 token 上误带的 "Bearer " 前缀(老凭据/代理回包可能带;7863 侧同样的容错)。 */ +function bareToken(v) { + let t = String(v ?? "").trim(); + while (t.toLowerCase().startsWith("bearer ")) t = t.slice(7).trim(); + return t; +} + +function dedupe(values) { + return [...new Set(values.filter(Boolean))]; +} + +/** 读 JWT payload 字段(不校验签名——只取自己账号的 device_id / exp)。 */ +function jwtClaim(token, key) { + const raw = bareToken(token); + const part = raw.split(".")[1]; + if (!part) return undefined; + try { + const json = Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"); + return JSON.parse(json)[key]; + } catch { + return undefined; + } +} + +/** access token 真实过期时间(epoch ms)。 */ +function jwtExpiresAtMs(token) { + const exp = jwtClaim(token, "exp"); + return typeof exp === "number" && Number.isFinite(exp) && exp > 0 ? exp * 1000 : undefined; +} + +async function callEnvelope(path, { method = "GET", body, base }) { + let response, text; + try { + response = await fetch(`${base}${path}`, { + method, + headers: bizHeaders(), + ...(body !== undefined ? { body } : {}), + }); + text = await response.text(); + } catch (cause) { + throw Object.assign(new Error(`AutoClaw request failed: ${cause?.message ?? cause}`), { cause }); + } + let parsed; + try { parsed = text ? JSON.parse(text) : undefined; } catch { parsed = undefined; } + if (!parsed || (parsed.code === undefined && response.status >= 400)) { + const err = new Error(`AutoClaw ${path.split("?")[0]} non-envelope response (HTTP ${response.status}): ${text.slice(0, 200)}`); + // 401/403 不论响应体形态都是登录失效:挂上标记,宿主才会提示重新登录 + if (response.status === 401 || response.status === 403) err.signIn = "expired"; + throw err; + } + return { status: response.status, code: parsed.code, msg: parsed.msg, data: parsed.data }; +} + +/** 验证码必须按数字发送(服务端按类型校验,字符串 → 400001)。 */ +function codeValue(code) { + const s = (code ?? "").trim(); + return /^\d+$/.test(s) ? Number(s) : s; +} + +/** token 响应 → magpie 凭据字段(不含 type——由 magpie 按 oauth 方式包装)。 */ +function tokenFields(data, fallbackRefresh) { + const access = bareToken(nonEmptyString(data.access_token)); + if (!access) throw new Error("AutoClaw token response contained no access_token"); + const refresh = bareToken(nonEmptyString(data.refresh_token) ?? fallbackRefresh); + if (!refresh) throw new Error("AutoClaw token response contained no refresh_token"); + // expires_in 常缺省;JWT exp 才是事实来源(约 24h)。按 5h 记会白跑 refresh(轮换有吊销风险)。 + const jwtExpires = jwtExpiresAtMs(access); + const expiresInS = typeof data.expires_in === "number" && data.expires_in > 0 ? data.expires_in : undefined; + const expires = jwtExpires !== undefined + ? jwtExpires - OAUTH_EXPIRY_SKEW_MS + : Date.now() + (expiresInS ?? FALLBACK_EXPIRES_IN_S) * 1000 - OAUTH_EXPIRY_SKEW_MS; + return { access, refresh, expires }; +} + +// --------------------------------------------------------------------------- +// 签到与积分 +// --------------------------------------------------------------------------- + +async function fetchWallets(accessToken, hosts) { + for (const host of dedupe(hosts)) { + let payload; + try { + const res = await fetch(host + WALLETS_PATH, { + method: "GET", + headers: bizHeaders(accessToken), + redirect: "error", + signal: AbortSignal.timeout(20_000), + }); + if (!res.ok) continue; + payload = await res.json(); + } catch { continue; } + if (!payload || payload.code !== 0 || !payload.data) continue; + return payload.data; + } + return null; +} + +/** 每日签到(幂等)。返回解析后的结果(可能为 null)。 */ +async function dailySignin(accessToken, host) { + try { + const res = await fetch(`${host}/autoclaw-proxy/proxy/autoclaw-task-complete`, { + method: "POST", + headers: bizHeaders(accessToken), + body: JSON.stringify({ task_id: "daily_signin", source_id: PRODUCT }), + signal: AbortSignal.timeout(15_000), + }); + const env = await res.json().catch(() => null); + return env?.data ?? null; // { success, already_completed, reward_points, continuous_days } + } catch { + return null; + } +} + +/** 查任务列表;401/403 throw(登录失效),HTTP 其他失败/非 envelope 返回 null,网络错误 throw。 */ +async function taskList(accessToken, host) { + const res = await fetch(`${host}/autoclaw-proxy/proxy/autoclaw-task-list`, { + method: "GET", + headers: bizHeaders(accessToken), + signal: AbortSignal.timeout(15_000), + }); + if (res.status === 401 || res.status === 403) { + throw new Error(`登录已失效(HTTP ${res.status})`); + } + if (!res.ok) return null; + const env = await res.json().catch(() => null); + return Array.isArray(env?.data) ? env.data : null; +} + +/** 查询 daily_signin 任务状态(容错版:任何失败返回 null)。 */ +async function signinStatus(accessToken, host) { + try { + const tasks = await taskList(accessToken, host); + if (!tasks) return null; + const t = tasks.find((x) => x?.task_id === "daily_signin"); + return t ? { status: String(t.status ?? ""), desc: String(t.status_description ?? ""), reward: Number(t.reward_points ?? 0) } : null; + } catch { + return null; + } +} + +/** 可选数字:>0 才返回,否则 undefined(checkin 的 credit/streak 允许缺省)。 */ +function optNumber(v) { + const n = Number(v); + return Number.isFinite(n) && n > 0 ? n : undefined; +} + +/** dailySignin 结果 → magpie 原生 checkin outcome({outcome, credit?, streak?, message?})。 */ +function checkinOutcome(r) { + if (!r) return { outcome: "failed", message: "签到接口无响应" }; + if (r.success) { + return { + outcome: "claimed", + credit: optNumber(r.reward_points), + streak: optNumber(r.continuous_days), + message: `已签到${r.reward_points ? ` +${r.reward_points}` : ""}${r.continuous_days ? ` · 连续 ${r.continuous_days} 天` : ""}`, + }; + } + if (r.already_completed) return { outcome: "done", credit: optNumber(r.reward_points) }; + return { outcome: "failed", message: String(r.message ?? r.msg ?? "签到失败") }; +} + +/** 本地去重键(成功才记;按小时允许重试)。 */ +const signinTriedLocal = new Map(); // key → hour-stamp of last SUCCESSFUL signin + +/** + * 签到配置合并:插件 options(plugins.json 的 options 字段)优先, + * 其次配置文件 ~/.config/magpie/autoclaw.json(热读取,GUI 没有选项入口时的保底通道): + * { "signin": true, "signinHour": null, "signinOnUsage": false } + * 两处都没有 → signin=true、signinOnUsage=false(自动补签默认关: + * 签到交给 magpie 原生 checkin 开关;旧版宿主/需要旧行为时显式开 signinOnUsage)。 + */ +function signinConfig(options) { + let fileCfg = {}; + try { + // magpie 配置目录固定(文档:~/.config/magpie 或 $XDG_CONFIG_HOME/magpie) + const cfgDir = process.env.XDG_CONFIG_HOME + ? `${process.env.XDG_CONFIG_HOME}/magpie` + : `${process.env.HOME ?? ""}/.config/magpie`; + fileCfg = JSON.parse(readFileSync(`${cfgDir}/autoclaw.json`, "utf8")); + } catch { /* 无文件/解析失败 → 用默认 */ } + const merged = { ...fileCfg, ...(options ?? {}) }; + return { + signin: merged.signin !== false, // 自动补签总开关(默认开) + signinOnUsage: merged.signinOnUsage === true, // usage/refresh 链路自动补签(默认关,见上) + signinHour: typeof merged.signinHour === "number" ? merged.signinHour : null, + }; +} + +/** 依据合并配置决定是否补签(usage/refresh 旧链路;原生 checkin 不经过这里)。 */ +async function maybeSignin(accessToken, host, options, reason, accountKey) { + void reason; + const cfg = signinConfig(options); + if (!cfg.signin || !cfg.signinOnUsage) return; + if (cfg.signinHour !== null && new Date().getHours() !== cfg.signinHour) return; + const hourStamp = `${new Date().toISOString().slice(0, 13)}`; // YYYY-MM-DDTHH(每小时可重试一次) + const dayKey = `${accountKey ?? "x"}`; + const lastOk = signinTriedLocal.get(dayKey); + if (typeof lastOk === "string" && lastOk.slice(0, 10) === hourStamp.slice(0, 10)) return; // 今天已成功 + const r = await dailySignin(accessToken, host); + if (r && (r.success || r.already_completed)) { + signinTriedLocal.set(dayKey, hourStamp); + } +} + +// --------------------------------------------------------------------------- +// 用户资料(GUI 账户命名:昵称/手机号,替代无意义的 uid 哈希 → 「已登录」) +// --------------------------------------------------------------------------- + +/** POST /userapi/v1/user-profile → { user_name, user_phone, user_id, … };失败返回 null。 */ +async function fetchUserProfile(accessToken, base) { + try { + const res = await fetch(`${base}/userapi/v1/user-profile`, { + method: "POST", + headers: bizHeaders(accessToken), + body: JSON.stringify({ source_id: PRODUCT, device_id: "magpie-plugin" }), + signal: AbortSignal.timeout(15_000), + }); + if (!res.ok) return null; + const env = await res.json().catch(() => null); + const d = env?.data; + if (!d || typeof d !== "object") return null; + return { + userId: nonEmptyString(d.user_id), + name: nonEmptyString(d.user_name), + phone: nonEmptyString(d.user_phone), + }; + } catch { + return null; + } +} + +/** GUI 显示名:昵称 > 手机号 > uid(workbuddy 社区插件同款优先级 nickname/phone/uid)。 */ +function accountDisplayName(profile, fallback) { + if (!profile) return fallback; + return profile.name ?? profile.phone ?? profile.userId ?? fallback; +} + +// --------------------------------------------------------------------------- +// 刷新(refresh token 轮换;host 必须与账号来源匹配) +// --------------------------------------------------------------------------- + +async function refreshTokens(refreshToken, preferredHosts) { + const deviceId = nonEmptyString(jwtClaim(refreshToken, "device_id")) ?? ""; + const body = JSON.stringify({ source_id: PRODUCT, device_id: deviceId, refresh_token: refreshToken }); + const isSmsAccount = /^agent/i.test(String(jwtClaim(refreshToken, "source_id") ?? "")); + const ordered = isSmsAccount + ? [CN_HOST, GLOBAL_HOST, ...preferredHosts] + : [GLOBAL_HOST, CN_HOST, ...preferredHosts]; + + let result = null; + for (const base of dedupe(ordered)) { + result = await callEnvelope("/userapi/v1/refresh", { method: "POST", body, base }); + if (result.code !== 0 && result.code === 400002) { + result = await callEnvelope("/userapi/v1/agent-refresh", { method: "POST", body, base }); + } + if (result.code !== 400000) break; + } + if (!result) throw new Error("AutoClaw refresh: no host attempted"); + if (result.code !== 0 || !result.data) { + const dead = result.status === 401 || result.status === 403 + || /invalid[_ ]?grant|revoked|expired|登录已失效|token 失效/i.test(String(result.msg ?? "")); + const err = new Error(`AutoClaw token refresh failed (HTTP ${result.status}): ${result.msg ?? `code ${result.code}`}`); + if (dead) err.signIn = "expired"; + throw err; + } + return tokenFields(result.data, refreshToken); +} + +// --------------------------------------------------------------------------- +// 插件工厂 +// --------------------------------------------------------------------------- + +function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod }) { + return async ({ client }, options) => ({ + config: async (cfg) => { + cfg.provider ??= {}; + cfg.provider[providerId] ??= { + name: providerName, + npm: "@ai-sdk/openai-compatible", + api: homeHost, + models: autoclawModels(), + }; + }, + + auth: { + provider: providerId, + methods: [loginMethod], + + async refresh(auth) { + const t = await refreshTokens(bareToken(auth.refresh), [homeHost]); + await maybeSignin(t.access, homeHost, options, "refresh", providerId); + // 存量账号就地正名:登录响应缺昵称的旧账号(GUI 显示「已登录」), + // 刷新时补拉 user-profile。magpie 的 refresh 返回字段会合并进账号。 + const old = String(auth.accountId ?? auth.email ?? ""); + if (!old || /^(已登录|[0-9a-f]{24,})$/.test(old)) { + const profile = await fetchUserProfile(t.access, homeHost); + const name = accountDisplayName(profile, ""); + if (name) { + t.accountId = name; + t.email = name; + } + } + return t; + }, + + async loader(getAuth) { + const auth = await getAuth(); + if (auth?.type !== "oauth" || !auth.access) return {}; + const accessToken = bareToken(auth.access); + const hosts = providerId === "autoclaw-cn" ? [CN_HOST, GLOBAL_HOST] : [GLOBAL_HOST, CN_HOST]; + + return { + baseURL: homeHost, + async fetch(input, init) { + const headers = new Headers(init?.headers); + headers.set("X-Authorization", `Bearer ${accessToken}`); + headers.set("X-Client-Type", "pc"); + headers.set("X-Product", PRODUCT); + headers.set("X-Harness-Type", "zcode"); + headers.set("X-Tm", PLATFORM_TM); + headers.set("X-Version", CLIENT_VERSION); + headers.set("X-Lang", "zh-CN"); + headers.set("X-Channel", CHANNEL); + headers.set("x_trace_id", "autoclaw-desktop"); + headers.delete("Authorization"); + + let routeModel = ""; + try { + const body = JSON.parse(String(init?.body ?? "{}")); + routeModel = String(body.model ?? ""); + } catch { /* 保持空 */ } + if (routeModel) headers.set("X-Request-Model", routeModel); + headers.set("X-Request-Id", randomHex(16)); + + const tryFetch = (host) => + fetch(`${host}${CHAT_PATH}`, { ...init, headers, signal: init?.signal }); + + const res1 = await tryFetch(hosts[0]); + if (res1.status !== 401 && res1.status !== 403) return res1; + const res2 = await tryFetch(hosts[1]); + if (res2.status === 401 || res2.status === 403) { + try { res2.body?.cancel?.(); } catch {} + return new Response(JSON.stringify({ error: { message: "AutoClaw 登录已失效(两个 host 均拒绝该 token)", type: "invalid_request_error" } }), { + status: 401, + headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "expired" }, + }); + } + return res2; + }, + }; + }, + + async usage(getAuth) { + const auth = await getAuth(); + if (auth?.type !== "oauth" || !auth.access) return { error: "未登录", windows: [] }; + const hosts = providerId === "autoclaw-cn" ? [CN_HOST, GLOBAL_HOST] : [GLOBAL_HOST, CN_HOST]; + const token = bareToken(auth.access); + const cfg = signinConfig(options); + try { + const [data, signin] = await Promise.all([ + fetchWallets(token, hosts), + signinStatus(token, hosts[0]).then((s) => s ?? signinStatus(token, hosts[1] ?? hosts[0])), + ]); + // 旧链路自动补签(默认关,需 signinOnUsage=true):查额度即触发。 + // 放在状态查询之后:未签才补,补完重查一次状态展示。 + if (signin && signin.status !== "completed" && (cfg.signin && cfg.signinOnUsage)) { + await maybeSignin(token, hosts[0], options, "usage", providerId); + } + const signinFinal = signin?.status === "completed" + ? signin + : (await signinStatus(token, hosts[0]).then((s) => s ?? signinStatus(token, hosts[1] ?? hosts[0])) ?? signin); + if (!data) return { error: "积分接口无数据(token 可能不属于该 host)", windows: [] }; + const total = Number(data.total_balance); + if (!Number.isFinite(total)) return { error: "积分响应异常", windows: [] }; + + const rows = Array.isArray(data.wallets) ? data.wallets : []; + const named = rows + .filter((r) => r.display !== false && Number(r.balance) > 0) + .map((r) => ({ name: String(r.display_name ?? r.public_wallet_type ?? "积分"), balance: Number(r.balance) })) + .filter((w) => Math.round(w.balance) !== Math.round(total)) + .slice(0, 3); + + // 签到窗口行 = 状态展示(开关指示交给 magpie 原生 checkin 的 Settings 开关) + const signinWindow = signinFinal + ? [{ + name: "每日签到", + // used 是 0–100 的百分比;签到行只表达状态,状态在 display 里 + used: 0, + display: signinFinal.status === "completed" + ? `今日已签 ✓${signinFinal.reward ? ` +${signinFinal.reward}` : ""}` + : `今日未签(+${signinFinal.reward || 400})`, + aside: true, + }] + : []; + + return { + balance: `${Math.round(total)} 积分`, + windows: [ + { name: "积分余额", used: 0, display: `${Math.round(total)} 积分`, aside: true }, + ...signinWindow, + ...named.map((w) => ({ name: w.name, used: 0, display: `${Math.round(w.balance)}`, aside: true })), + ], + }; + } catch (e) { + return { error: `积分查询失败: ${e?.message ?? e}`, windows: [] }; + } + }, + + /** + * 原生每日签到钩子(magpie ≥ v0.1.1083)。由宿主调度:Settings → Usage → Plugins + * 的 Daily check-in 开关(默认关)控制;每天每账号一次,结果上 Usage 卡片。 + * 契约:返回 {outcome, credit?, streak?, message?};throw → failed(30 分钟后重试)。 + */ + async checkin(getAuth) { + const auth = await getAuth(); + if (auth?.type !== "oauth" || !auth.access) throw new Error("未登录"); + const token = bareToken(auth.access); + const hosts = providerId === "autoclaw-cn" ? [CN_HOST, GLOBAL_HOST] : [GLOBAL_HOST, CN_HOST]; + + // 先查任务状态:区分「无签到活动」(inactive)与「查询失败」(throw → failed 重试) + let task = null; + let lastErr = null; + for (const h of hosts) { + try { + const tasks = await taskList(token, h); + if (tasks) { + task = tasks.find((x) => x?.task_id === "daily_signin") ?? null; + break; + } + } catch (e) { lastErr = e; } + } + if (!task && lastErr) throw lastErr; + if (!task) return { outcome: "inactive", message: "当前没有签到活动" }; + if (String(task.status ?? "") === "completed") { + return { outcome: "done", credit: optNumber(task.reward_points) }; + } + + // 补签:主 host 优先,无响应再试备用 host(服务端幂等) + const r = await dailySignin(token, hosts[0]).catch(() => null) + ?? await dailySignin(token, hosts[1] ?? hosts[0]).catch(() => null); + return checkinOutcome(r); + }, + }, + + provider: { + id: providerId, + async models(provider) { + return provider.models; + }, + }, + }); +} + +// --------------------------------------------------------------------------- +// 登录方式:国内手机验证码 +// --------------------------------------------------------------------------- + +const phoneSmsMethod = { + type: "oauth", + label: "AutoClaw 手机验证码登录(国内)", + async authorize(inputs) { + const phone = String(inputs?.phone ?? "").trim(); + // authorize 失败必须 throw(返回 {type:"failed"} 会被宿主当 "auto" 分支无参调 callback())。 + if (!/^1\d{10}$/.test(phone)) { + throw new Error("请输入 11 位手机号(不带 +86)"); + } + const deviceId = newDeviceId(); + const send = await callEnvelope("/userapi/v1/agent-send-code", { + method: "POST", + body: JSON.stringify({ source_id: PRODUCT, device_id: deviceId, phone }), + base: CN_HOST, + }); + if (send.code !== 0) { + throw new Error(`发送验证码失败: ${send.msg ?? `code ${send.code}`}`); + } + return { + url: "", + instructions: `验证码已发送到 ${phone.slice(0, 3)}****${phone.slice(-4)} 的短信,请输入收到的验证码。`, + method: "code", + async callback(code) { + const res = await callEnvelope("/userapi/v1/agent-login/", { + method: "POST", + body: JSON.stringify({ source_id: PRODUCT, device_id: deviceId, phone, code: codeValue(code) }), + base: CN_HOST, + }); + if (res.code !== 0 || !res.data?.access_token) { + return { type: "failed", error: `登录失败: ${res.msg ?? `code ${res.code}`}` }; + } + const t = tokenFields(res.data); + // GUI 显示名:拉 user-profile 取昵称/手机号(登录响应的 user_name 常为空 → 显示「已登录」) + const profile = await fetchUserProfile(t.access, CN_HOST); + const displayName = accountDisplayName(profile, phone); + return { + type: "success", + ...t, + accountId: displayName, + email: displayName, + uid: nonEmptyString(res.data.user_id) ?? undefined, + }; + }, + }; + }, + prompts: [ + { type: "text", key: "phone", message: "手机号(11 位,不带 +86)", placeholder: "13800138000", + validate: (v) => (/^1\d{10}$/.test(String(v ?? "").trim()) ? undefined : "11 位手机号") }, + ], +}; + +// --------------------------------------------------------------------------- +// 登录方式:国际网页 OAuth(本地完整实现:滑块 + 授权 + 回调捕获) +// --------------------------------------------------------------------------- + +const overseaOAuthMethod = { + type: "oauth", + label: "AutoClaw 网页登录(Google / z.ai)", + async authorize(inputs) { + const vendor = inputs?.vendor === "zai" ? "zai" : "google"; + return await startLocalOAuth(vendor); + }, + prompts: [ + { type: "select", key: "vendor", message: "登录方式", + options: [ + { label: "Google 账号", value: "google" }, + { label: "z.ai 账号", value: "zai" }, + ] }, + ], +}; + +/** + * 启动本地 OAuth:立即返回 {url, method:"auto", callback}。 + * url = 本地引导页(滑块在内完成,之后自动跳授权页);callback 挂起等 code, + * 拿到后直连上游换 token。 + */ +async function startLocalOAuth(vendor, openFn = openBrowser) { + const deviceId = newDeviceId(); + const state = { + captchaReceipt: null, + oauthCode: null, + oauthState: "", + // /open-auth 从上游授权页地址里读出的 state;回调必须原样带回(防 login CSRF) + expectedOauthState: null, + error: null, + }; + const waiters = []; + const notify = () => { while (waiters.length) waiters.shift()(); }; + const waitFor = (timeoutMs, what) => new Promise((resolve, reject) => { + const check = () => { + if (state.error) { cleanup(); reject(new Error(state.error)); return true; } + if (state.oauthCode) { cleanup(); resolve(state.oauthCode); return true; } + return false; + }; + const timer = setTimeout(() => { cleanup(); reject(new Error(`${what} 等待超时(${Math.round(timeoutMs / 60000)} 分钟)— 请重试登录`)); }, timeoutMs); + const w = () => { check(); }; + const cleanup = () => { clearTimeout(timer); const i = waiters.indexOf(w); if (i >= 0) waiters.splice(i, 1); }; + waiters.push(w); + check(); + }); + + // 官方 TokenServer 端口池(OAuth client 注册的回调白名单端口)。 + // 18432 被占(如官方客户端在跑)时依次尝试其余。 + const FIXED_PORTS = [18432, 19654, 19723, 53699]; + + // 探测可用端口(listen → 记下 → 关闭),随后本函数末尾立即 listen 占住, + // 直到 callback 完成或 OAUTH_SESSION_TIMEOUT_MS 超时(宿主可能不调 callback)。 + let fixedPort = 0; + const probe = http.createServer(); + for (const p of FIXED_PORTS) { + const ok = await new Promise((resolve) => { + probe.once("error", () => resolve(false)); + probe.listen(p, "127.0.0.1", () => { probe.close(() => resolve(true)); }); + }); + if (ok) { fixedPort = p; break; } + } + if (!fixedPort) { + throw new Error(`本地端口 ${FIXED_PORTS.join("/")} 均被占用——OAuth 回调需要其中之一(官方 client 白名单端口)。请关闭占用进程(可能是 AutoClaw 桌面端或其 TokenServer)后重试。`); + } + + const server = http.createServer((req, res) => { + const base = `http://127.0.0.1:${server.address()?.port ?? 0}`; + let url; + try { url = new URL(req.url, base); } catch { res.writeHead(400); res.end(); return; } + const send = (status, type, body, extra = {}) => { + res.writeHead(status, { "Content-Type": type, "Cache-Control": "no-store", ...extra }); + res.end(body); + }; + // 写接口仅接受本机来源:浏览器同源 fetch 一定带 Origin(127.0.0.1/localhost); + // curl 等非浏览器客户端无 Origin,放行。防其他网页跨源 POST /abort 干扰登录。 + const localOrigin = (req) => { + const o = req.headers.origin; + return !o || /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(String(o)); + }; + if (["/captcha", "/open-auth", "/abort"].includes(url.pathname) && !localOrigin(req)) { + send(403, "application/json", JSON.stringify({ error: "forbidden origin" })); + return; + } + + if (req.method === "OPTIONS") { + send(204, "text/plain", "", { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "content-type", "Access-Control-Allow-Methods": "GET,POST,OPTIONS" }); + return; + } + + if (url.pathname === "/" || url.pathname === "/index.html") { + send(200, "text/html; charset=utf-8", guidePageHtml(vendor)); + return; + } + + if (url.pathname === "/captcha-config") { + callEnvelope("/userapi/overseasv1/oauth-captcha-config", { method: "POST", body: "{}", base: GLOBAL_HOST }) + .then((r) => send(200, "application/json", JSON.stringify(r.data ?? { enabled: false }))) + .catch(() => send(502, "application/json", JSON.stringify({ enabled: false, error: "config fetch failed" }))); + return; + } + + const readBody = () => new Promise((resolve) => { + let b = ""; + req.on("data", (c) => { b += c; }); + req.on("end", () => { try { resolve(JSON.parse(b || "{}")); } catch { resolve({}); } }); + }); + + if (url.pathname === "/captcha" && req.method === "POST") { + readBody().then((j) => { + // 阿里 SDK 把回执作为 captchaVerifyCallback 首参本身(JSON 字符串), + // 兜底 captchaVerifyParam 字段两种形态。 + const receipt = typeof j.receipt === "string" ? j.receipt + : typeof j.captchaVerifyParam === "string" ? j.captchaVerifyParam : ""; + state.captchaReceipt = receipt.trim(); + send(200, "application/json", JSON.stringify({ ok: !!state.captchaReceipt }), { "Access-Control-Allow-Origin": "*" }); + }); + return; + } + + if (url.pathname === "/open-auth" && req.method === "POST") { + (async () => { + // ⚠️ redirect_uri 必须是官方 client 注册过的白名单形态: + // http://localhost:/auth/callback-(host=localhost、固定路径、 + // 端口为官方 TokenServer 端口池之一),随机端口/自定路径会被 + // {"detail":"Redirect URI not registered for this client"} 拒绝。 + const redirectUri = `http://localhost:${fixedPort}/auth/callback-${vendor}`; + const bodyObj = { source_id: PRODUCT, device_id: deviceId, navigate_uri: redirectUri }; + if (state.captchaReceipt) bodyObj.ali_captcha_verify_param = state.captchaReceipt; + const r = await callEnvelope(`/userapi/overseasv1/${vendor}-oauth-url`, { + method: "POST", body: JSON.stringify(bodyObj), base: GLOBAL_HOST, + }); + if (r.code !== 0 || !r.data) { + send(200, "application/json", JSON.stringify({ error: `获取授权页失败: ${r.msg ?? `code ${r.code}`}` })); + return; + } + const authorizeUrl = String(r.data.oauth_url ?? r.data.url ?? r.data.login_url ?? r.data.auth_url ?? r.data.verify_url ?? ""); + if (!authorizeUrl) { + send(200, "application/json", JSON.stringify({ error: "上游未返回授权页地址" })); + return; + } + // 记下上游放进授权页的 state:回调必须原样带回,否则拒收(防伪造回调劫持登录) + let handedOutState = ""; + try { handedOutState = new URL(authorizeUrl).searchParams.get("state") ?? ""; } catch { /* 非法地址按缺 state 处理 */ } + if (!handedOutState) { + send(200, "application/json", JSON.stringify({ error: "上游授权页地址缺少 state 参数,已取消登录(回调校验必需)" })); + return; + } + state.expectedOauthState = handedOutState; + send(200, "application/json", JSON.stringify({ url: authorizeUrl })); + })().catch((e) => send(200, "application/json", JSON.stringify({ error: `获取授权页失败: ${e?.message ?? e}` }))); + return; + } + + // 官方注册的回调路径:/auth/callback-(redirect_uri 传的就是它)。 + // 等待窗口内任何网页都能导航到本端口——code 必须配上 /open-auth 记下的 + // state 才收,否则只回失败页:把别人的 code 塞进来会登录成别人的账号。 + if (url.pathname === `/auth/callback-${vendor}`) { + const code = url.searchParams.get("code"); + const cbState = url.searchParams.get("state") ?? ""; + const accepted = !!code && state.expectedOauthState !== null && cbState === state.expectedOauthState; + if (accepted) { + state.oauthCode = code; + state.oauthState = cbState; + notify(); + send(200, "text/html; charset=utf-8", callbackPageHtml(true)); + } else { + // 拒收但不动会话状态:之后到达的合法回调仍能完成登录 + const note = !code ? undefined + : state.expectedOauthState === null ? "授权尚未发起或已结束,请回引导页重试。" + : "回调校验失败(state 不匹配),已拒绝——请回 magpie 重新登录。"; + send(200, "text/html; charset=utf-8", callbackPageHtml(false, note)); + } + return; + } + + if (url.pathname === "/abort" && req.method === "POST") { + readBody().then((j) => { + state.error = String(j.reason ?? "用户取消"); + notify(); + send(200, "application/json", JSON.stringify({ ok: true })); + }); + return; + } + + send(404, "text/plain", "not found"); + }); + + const serverReady = new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(fixedPort, "127.0.0.1", () => resolve(fixedPort)); + }); + + // 会话最长 OAUTH_SESSION_TIMEOUT_MS:宿主可能永远不调 callback(用户在 magpie + // 里取消),定时器负责关服务器、释放官方 TokenServer 端口。 + let sessionDone = false; + let sessionClosed = false; + const closeServer = () => { + if (sessionClosed) return; + sessionClosed = true; + clearTimeout(sessionTimer); + if (!sessionDone) { + state.error ??= "本地登录已超时,服务器已关闭——请重新发起登录"; + notify(); + } + try { server.close(); } catch { /* 未 listening/已关闭 */ } + server.closeAllConnections?.(); + }; + const sessionTimer = setTimeout(closeServer, OAUTH_SESSION_TIMEOUT_MS); + sessionTimer.unref?.(); + + return { + url: "", // 由 callback 里自行开浏览器(本地引导页),宿主不重复打开 + instructions: `已打开本地引导页(未自动打开时手动访问 http://127.0.0.1:${fixedPort}/ ):请完成滑块验证并登录授权,完成后自动返回 magpie。`, + method: "auto", + async callback() { + const port = await serverReady; + const guide = `http://127.0.0.1:${port}/`; + const redirectUri = `http://localhost:${port}/auth/callback-${vendor}`; + try { + openFn(guide); + const code = await waitFor(5 * 60 * 1000, "浏览器登录"); + const res = await callEnvelope(`/userapi/overseasv1/${vendor}-oauth-login`, { + method: "POST", + body: JSON.stringify({ source_id: PRODUCT, device_id: deviceId, code, state: state.oauthState, navigate_uri: redirectUri }), + base: GLOBAL_HOST, + }); + if (res.code !== 0 || !res.data?.access_token) { + return { type: "failed", error: `登录失败: ${res.msg ?? `code ${res.code}`}` }; + } + const t = tokenFields(res.data); + // GUI 显示名:拉 user-profile 取昵称(Google/z.ai 账号通常有昵称或邮箱) + const profile = await fetchUserProfile(t.access, GLOBAL_HOST); + const displayName = accountDisplayName(profile, `${vendor} 账号`); + return { + type: "success", + ...t, + accountId: displayName, + email: displayName, + uid: nonEmptyString(res.data.user_id) ?? undefined, + }; + } finally { + sessionDone = true; + closeServer(); + } + }, + }; +} + +/** 跨平台打开浏览器(node:child_process,Bun / Node 宿主均可;失败时用户可手动打开 instructions 里的地址)。 */ +function openBrowser(urlStr) { + const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open"; + try { + // Windows 的 start 是 cmd 内建命令,必须走 shell。 + const child = process.platform === "win32" + ? spawn(cmd, [urlStr], { shell: true, stdio: "ignore", detached: true }) + : spawn(cmd, [urlStr], { stdio: "ignore", detached: true }); + child.on("error", () => { /* 打开失败静默:instructions 已给出可手动访问的地址 */ }); + child.unref(); + } catch { /* 同上 */ } +} + +/** 引导页:滑块(如启用)→ 继续授权 → 自动跳授权页。 */ +function guidePageHtml(vendor) { + const vendorName = vendor === "zai" ? "z.ai" : "Google"; + return ` + +AutoClaw ${vendorName} 登录 + + +
+

AutoClaw · ${vendorName} 登录

+

本页面由 magpie 插件本地生成,关闭本页即取消登录。

+
+
1检查安全验证…
+
+
2跳转 ${vendorName} 授权页完成登录
+
+ +
+
已完成授权,正在返回 magpie…
+
+`; +} + +/** 授权回调落地页;note 覆盖默认文案(如 state 校验被拒的原因)。 */ +function callbackPageHtml(ok, note) { + return `AutoClaw 登录 + +

${ok ? "✓ 授权成功" : "✗ 授权失败"}

+

${note ?? (ok ? "正在返回 magpie 完成登录,本页可以关闭。" : "回调缺少 code,请回 magpie 重试。")}

`; +} + +// --------------------------------------------------------------------------- +// 导出 +// --------------------------------------------------------------------------- + +/** provider "autoclaw":国际版(z.ai / Google 网页 OAuth,本地完整实现)。 */ +export const AutoclawAuthPlugin = makeAutoclawPlugin({ + providerId: "autoclaw", + providerName: "AutoClaw (Zhipu)", + homeHost: GLOBAL_HOST, + loginMethod: overseaOAuthMethod, +}); + +/** provider "autoclaw-cn":国内版(手机验证码)。 */ +export const AutoclawCnAuthPlugin = makeAutoclawPlugin({ + providerId: "autoclaw-cn", + providerName: "AutoClaw 国内 (Zhipu)", + homeHost: CN_HOST, + loginMethod: phoneSmsMethod, +}); + +/** 测试辅助(magpie/OpenCode 不会把它当插件调用)。 */ +export const _internal = { + md5Hex, jwtClaim, tokenFields, codeValue, bizHeaders, bareToken, newDeviceId, + dailySignin, signinStatus, maybeSignin, signinConfig, checkinOutcome, refreshTokens, + fetchUserProfile, accountDisplayName, startLocalOAuth, + guidePageHtml, callbackPageHtml, +}; diff --git a/packages/autoclaw/index.test.mjs b/packages/autoclaw/index.test.mjs new file mode 100644 index 0000000..d98aa65 --- /dev/null +++ b/packages/autoclaw/index.test.mjs @@ -0,0 +1,239 @@ +// The check-in mapping is magpie's contract (provider-plugins.md): every +// answer the upstream gives lands on one of its outcomes, and the plugin +// factory registers both providers with every hook check.mjs looks for. +import { expect, test } from "bun:test" +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { AutoclawAuthPlugin, AutoclawCnAuthPlugin, _internal } from "./index.mjs" + +const { checkinOutcome, signinConfig, bareToken, codeValue, tokenFields, refreshTokens, startLocalOAuth } = _internal + +const b64url = (o) => Buffer.from(JSON.stringify(o)).toString("base64url") +const jwt = (claims) => `${b64url({ alg: "none" })}.${b64url(claims)}.sig` + +test("both providers register with models and every hook", async () => { + for (const [Plugin, id, api] of [ + [AutoclawAuthPlugin, "autoclaw", "https://autoglm-api.autoglm.ai"], + [AutoclawCnAuthPlugin, "autoclaw-cn", "https://autoglm-api.zhipuai.cn"], + ]) { + const hooks = await Plugin({ client: { auth: { set: async () => {} } } }) + expect(hooks.auth.provider).toBe(id) + expect(hooks.auth.loader).toBeFunction() + expect(hooks.auth.usage).toBeFunction() + expect(hooks.auth.checkin).toBeFunction() + expect(hooks.auth.methods[0].prompts.length).toBeGreaterThan(0) + const cfg = {} + await hooks.config(cfg) + expect(cfg.provider[id].api).toBe(api) + expect(Object.keys(cfg.provider[id].models).length).toBeGreaterThan(0) + } +}) + +test("checkinOutcome maps every upstream answer onto the contract", () => { + expect(checkinOutcome({ success: true, reward_points: 400, continuous_days: 7 })).toEqual({ + outcome: "claimed", credit: 400, streak: 7, message: "已签到 +400 · 连续 7 天", + }) + expect(checkinOutcome({ already_completed: true, reward_points: 200 })).toEqual({ + outcome: "done", credit: 200, + }) + expect(checkinOutcome(null)).toEqual({ outcome: "failed", message: "签到接口无响应" }) + expect(checkinOutcome({ success: false, message: "风控拦截" })).toEqual({ + outcome: "failed", message: "风控拦截", + }) +}) + +test("signinConfig: plugin options over the file, the file over the default", () => { + const home = mkdtempSync(join(tmpdir(), "autoclaw-cfg-")) + const prev = process.env.XDG_CONFIG_HOME + try { + process.env.XDG_CONFIG_HOME = home + // no file, no options: auto-signing stays off, left to the native switch + expect(signinConfig(undefined)).toEqual({ signin: true, signinOnUsage: false, signinHour: null }) + + mkdirSync(join(home, "magpie"), { recursive: true }) + const file = join(home, "magpie", "autoclaw.json") + writeFileSync(file, JSON.stringify({ signin: false, signinHour: 8 })) + expect(signinConfig(undefined)).toEqual({ signin: false, signinOnUsage: false, signinHour: 8 }) + expect(signinConfig({ signin: true, signinOnUsage: true })).toEqual({ + signin: true, signinOnUsage: true, signinHour: 8, + }) + // a broken file reads as no file + writeFileSync(file, "{ not json") + expect(signinConfig(undefined)).toEqual({ signin: true, signinOnUsage: false, signinHour: null }) + } finally { + if (prev === undefined) delete process.env.XDG_CONFIG_HOME + else process.env.XDG_CONFIG_HOME = prev + rmSync(home, { recursive: true, force: true }) + } +}) + +test("the JWT's exp is the token's truth, with the 10-minute skew", () => { + const access = jwt({ exp: 2_000_000_000 }) + expect(bareToken(`Bearer ${access}`)).toBe(access) + expect(tokenFields({ access_token: `Bearer ${access}`, refresh_token: "Bearer r1" })).toEqual({ + access, refresh: "r1", expires: 2_000_000_000_000 - 10 * 60 * 1000, + }) + expect(codeValue("123456")).toBe(123456) + expect(codeValue("12a45")).toBe("12a45") +}) + +// The request path, against a fake upstream: which headers the chat request +// carries, how a wrong host's 401 rotates to the other one, and when the host +// is told the sign-in is dead. +test("loader().fetch signs with X-Authorization and rotates hosts on 401", async () => { + const realFetch = globalThis.fetch + const calls = [] + let mode = "ok" // ok | first-401 | all-401 + globalThis.fetch = async (input, init) => { + calls.push({ url: String(input), headers: new Headers(init?.headers) }) + if (mode === "first-401") { mode = "ok"; return new Response("{}", { status: 401 }) } + if (mode === "all-401") return new Response("{}", { status: 401 }) + return new Response("ok") + } + try { + const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } }) + const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "Bearer a1" })) + + // The chat path goes to the upstream, signed by X-Authorization, not Authorization + await loader.fetch("x", { headers: { Authorization: "Bearer old" } }) + expect(calls.at(-1).url).toBe("https://autoglm-api.autoglm.ai/autoclaw-proxy/proxy/autoclaw/v1/chat/completions") + expect(calls.at(-1).headers.get("X-Authorization")).toBe("Bearer a1") + expect(calls.at(-1).headers.get("Authorization")).toBe(null) + + // A 401 from the home host retries the other one, which answers + mode = "first-401" + calls.length = 0 + expect((await loader.fetch("x")).status).toBe(200) + expect(calls.map((c) => new URL(c.url).host)).toEqual(["autoglm-api.autoglm.ai", "autoglm-api.zhipuai.cn"]) + + // Both hosts refusing the token answers 401 with the sign-in marker + mode = "all-401" + const refused = await loader.fetch("x") + expect(refused.status).toBe(401) + expect(refused.headers.get("X-Magpie-Sign-In")).toBe("expired") + } finally { + globalThis.fetch = realFetch + } +}) + +test("refreshTokens orders hosts by the token's source_id and falls back on 400002", async () => { + const realFetch = globalThis.fetch + const requests = [] + globalThis.fetch = async (input, init) => { + const url = new URL(String(input)) + requests.push({ url, body: JSON.parse(String(init?.body ?? "{}")) }) + const { pathname } = url + if (pathname === "/userapi/v1/refresh") return Response.json({ code: 400002, msg: "need agent refresh" }) + if (pathname === "/userapi/v1/agent-refresh") { + return Response.json({ code: 0, msg: "ok", data: { access_token: "a2", refresh_token: "r2", expires_in: 3600 } }) + } + throw new Error(`unexpected request ${pathname}`) + } + try { + // An agent (SMS) token tries the CN host first, and its /refresh answers 400002 + const out = await refreshTokens(jwt({ source_id: "agent", device_id: "dev-1" }), []) + expect(requests.map((r) => `${new URL(r.url).origin}${r.url.pathname}`)).toEqual([ + "https://autoglm-api.zhipuai.cn/userapi/v1/refresh", + "https://autoglm-api.zhipuai.cn/userapi/v1/agent-refresh", + ]) + expect(requests[0].body.device_id).toBe("dev-1") + expect(out).toEqual({ access: "a2", refresh: "r2", expires: Date.now() + 3600_000 - 600_000 }) + } finally { + globalThis.fetch = realFetch + } +}) + +test("refreshTokens tries the oversea host first and marks a dead token expired", async () => { + const realFetch = globalThis.fetch + const requests = [] + globalThis.fetch = async (input) => { + const url = new URL(String(input)) + requests.push(url) + return new Response(JSON.stringify({ code: 401001, msg: "invalid_grant" }), { status: 401 }) + } + try { + let threw + try { await refreshTokens(jwt({ source_id: "google" }), []) } catch (e) { threw = e } + expect(threw).toBeInstanceOf(Error) + expect(threw.signIn).toBe("expired") + // A web token belongs to the oversea host; its 401 stops the rotation there + expect(requests.map((u) => u.origin)).toEqual(["https://autoglm-api.autoglm.ai"]) + } finally { + globalThis.fetch = realFetch + } +}) + +// A 401 whose body isn't an envelope (a gateway's plain text) must still tell +// the host the sign-in is dead, or the user isn't offered to sign in again. +test("refreshTokens marks a non-envelope 401 as expired too", async () => { + const realFetch = globalThis.fetch + globalThis.fetch = async () => new Response("Unauthorized", { status: 401 }) + try { + let threw + try { await refreshTokens(jwt({ source_id: "google" }), []) } catch (e) { threw = e } + expect(threw).toBeInstanceOf(Error) + expect(threw.message).toContain("non-envelope response (HTTP 401)") + expect(threw.signIn).toBe("expired") + } finally { + globalThis.fetch = realFetch + } +}) + +// The local OAuth server against a fake upstream and a real listener: the +// callback only accepts the state the authorize page handed out, and the +// legacy /callback catch-all is gone. +test("the OAuth callback takes only the state the authorize page handed out", async () => { + const realFetch = globalThis.fetch + const upstream = [] + globalThis.fetch = async (input, init) => { + const url = new URL(String(input)) + // The plugin's own local server stays real; only the upstream is faked + if (url.hostname === "127.0.0.1" || url.hostname === "localhost") return realFetch(input, init) + upstream.push({ url, body: JSON.parse(String(init?.body ?? "{}")) }) + if (url.pathname === "/userapi/overseasv1/google-oauth-url") { + return Response.json({ code: 0, msg: "ok", data: { oauth_url: "https://accounts.google.test/o/auth2/auth?state=st-123&client_id=c" } }) + } + if (url.pathname === "/userapi/overseasv1/google-oauth-login") { + return Response.json({ code: 0, msg: "ok", data: { access_token: jwt({ exp: 2_000_000_000 }), refresh_token: "r1", user_id: "u1" } }) + } + if (url.pathname === "/userapi/v1/user-profile") { + return Response.json({ code: 0, msg: "ok", data: { user_name: "Tester" } }) + } + throw new Error(`unexpected request ${url.pathname}`) + } + try { + const session = await startLocalOAuth("google", () => {}) + const port = Number(/127\.0\.0\.1:(\d+)\//.exec(session.instructions)[1]) + const local = (path, init) => fetch(`http://127.0.0.1:${port}${path}`, init) + + // The guide page's Continue hands out the authorize URL, and the state in it + const openAuth = await (await local("/open-auth", { method: "POST" })).json() + expect(openAuth.url).toContain("state=st-123") + + // A forged state is turned away without ending the session… + const evil = await local("/auth/callback-google?code=evil&state=attacker") + expect(evil.status).toBe(200) + expect(await evil.text()).toContain("state 不匹配") + + // …and the old /callback catch-all no longer answers + expect((await local("/callback?code=evil&state=st-123")).status).toBe(404) + + // …while the real one still signs in with exactly the code it was given + const good = await local("/auth/callback-google?code=good-code&state=st-123") + expect(await good.text()).toContain("授权成功") + const result = await session.callback() + expect(result.type).toBe("success") + expect(result.accountId).toBe("Tester") + const login = upstream.find((u) => u.url.pathname === "/userapi/overseasv1/google-oauth-login") + expect(login.body.code).toBe("good-code") + expect(login.body.state).toBe("st-123") + + // The session's port is released once the callback returns + let refused = false + try { await local("/") } catch { refused = true } + expect(refused).toBe(true) + } finally { + globalThis.fetch = realFetch + } +}) diff --git a/packages/autoclaw/package.json b/packages/autoclaw/package.json new file mode 100644 index 0000000..0b635a1 --- /dev/null +++ b/packages/autoclaw/package.json @@ -0,0 +1,34 @@ +{ + "name": "@magpie-community/opencode-autoclaw-auth", + "version": "0.2.0", + "description": "OpenCode provider plugin for AutoClaw (Zhipu OpenClaw): oversea web sign-in (Google/z.ai) and CN phone SMS, multi-account pool, credit balance and daily check-in", + "type": "module", + "main": "./index.mjs", + "exports": "./index.mjs", + "files": [ + "index.mjs", + "README.md" + ], + "keywords": [ + "opencode", + "opencode-plugin", + "magpie", + "autoclaw", + "zhipu", + "glm" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/autoclaw" + }, + "magpie": { + "icon": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Ccircle cx='32' cy='32' r='30' fill='%234f6ef7'/%3E%3Ctext x='32' y='42' font-size='28' text-anchor='middle' fill='white' font-family='sans-serif'%3E%E8%9F%B9%3C/text%3E%3C/svg%3E", + "options": { + "signin": true, + "signinHour": null, + "signinOnUsage": false + } + } +} diff --git a/registry.json b/registry.json index 50e54e3..31135c1 100644 --- a/registry.json +++ b/registry.json @@ -35,6 +35,8 @@ "summary": { "en": "Open Design Cloud's Design Plan (open-design.ai): the account's device sign-in, the models the plan entitles it to, and the plan's 5-hour and 7-day allowance and wallet balance.", "zh": "Open Design Cloud 的 Design Plan(open-design.ai):账号设备登录、套餐可用的模型,以及 5 小时与 7 天额度、钱包余额。" } }, { "package": "@magpie-community/opencode-raccoon-auth", "name": "商汤小浣熊", "icon": "sensenova-color", "providers": ["raccoon"], "community": true, "summary": { "en": "SenseTime Raccoon (xiaohuanxiong.com) models, account credits and daily check-in, with browser sign-in or Raccoon desktop's live sign-in.", "zh": "商汤小浣熊(xiaohuanxiong.com)模型、积分余额与每日签到,支持浏览器登录或直接复用小浣熊桌面端登录态。" } }, + { "package": "@magpie-community/opencode-autoclaw-auth", "name": "AutoClaw", "providers": ["autoclaw", "autoclaw-cn"], "community": true, + "summary": { "en": "AutoClaw (Zhipu OpenClaw) cloud accounts: oversea web sign-in (Google/z.ai) or CN phone SMS, credit balance and daily check-in.", "zh": "AutoClaw(智谱澳龙/OpenClaw)云端账号:国际版网页登录(Google/z.ai)或国内手机验证码,积分余额与每日签到。" } }, { "package": "@magpie-community/middleware-param-override", "name": "Param Override", "kind": "middleware", "community": true, "summary": { "en": "New API's parameter override: set, delete, move or rewrite fields of every request, by model or by condition.", "zh": "New API 的参数覆盖:按模型或条件设置、删除、移动或改写每个请求的字段。" } }, { "package": "@magpie-community/middleware-model-map", "name": "Model Map", "kind": "middleware", "community": true,