autoclaw 0.1.0: AutoClaw (Zhipu OpenClaw) provider plugin (#53, hubo1989)

Adds packages/autoclaw, @magpie-community/opencode-autoclaw-auth, for AutoClaw (Zhipu OpenClaw).
- Providers autoclaw (oversea, web sign-in through Google or z.ai) and autoclaw-cn (CN, phone SMS).
- Reads the credit balance and runs the daily check-in through auth.checkin.

Since the 10-08 review, this fixes:
- The OAuth callback takes a code only with the state the authorize page handed out (login CSRF). The legacy /callback is gone.
- The local server closes after 10 minutes even if magpie never calls callback, so port 18432 isn't held.
- The registry entry no longer uses ZCode's icon.
- The User-Agent names the real arch.
- The check-in row's used is 0.
- A 401 or 403 the upstream answers without an envelope marks the sign-in expired.
- New tests with a fake fetch cover loader().fetch, refreshTokens and the callback's state check.

What was run, at 356fb53 (8a0fd3a plus a merge of origin/main 118cf2e; the merge resolved registry.json, raccoon's entry beside autoclaw's):
- HOME=$(mktemp -d) bun test packages/autoclaw: 9 pass, 0 fail.
- Whole repo, HOME=$(mktemp -d) bun test: 1584 pass, 0 fail.
- bun scripts/check.mjs: all ✓.
- Broken by hand, each turning a test red:
  - Dropping the callback's state comparison: 1 fail.
  - Dropping the expired mark on a non-envelope 401: 1 fail.
- The package isn't on npm yet. magpie serves it from the dist branch until an owner publishes its first version.

Not verified: a real AutoClaw account, and the 10-minute server close (read, not tested).
This commit is contained in:
hubo
2026-10-16 15:04:41 +08:00
committed by GitHub
parent 118cf2edcc
commit 423e78e49c
5 changed files with 1387 additions and 0 deletions
+84
View File
@@ -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 无任何关联。实现基于对官方客户端行为的逆向分析与实测,仅供个人学习研究;使用产生的账号风险由使用者自行承担。上游协议变更可能导致插件随时失效。
File diff suppressed because it is too large Load Diff
+239
View File
@@ -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
}
})
+34
View File
@@ -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
}
}
}
+2
View File
@@ -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,