From dd8caac45b4e60a132513f3da919907e0caaa467 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 23 Oct 2026 02:04:23 +0800 Subject: [PATCH] =?UTF-8?q?autoclaw=200.2.5:=20a=20banned=20account=20keep?= =?UTF-8?q?s=20its=20sign-in=20and=20says=20the=20ban,=20not=20=E7=99=BB?= =?UTF-8?q?=E5=BD=95=E5=B7=B2=E5=A4=B1=E6=95=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 小八 (Discord, 2026-10-23): a banned AutoClaw account answers HTTP 403 {"code":410004,"message":"The account has been banned"}. The plugin read every 401/403 as an expired sign-in, so magpie dropped the token from plugin-auth.json and the user never saw why. Signing in again gets the same account and the same refusal. A body whose code field is 410004, or whose code/message field (message, msg, error.message) names a ban or account restriction (banned, 封禁, 封号, 账号异常, account suspended/frozen/disabled/blocked/restricted, 账号被冻结/停用/禁用), is now the account's refusal, not the sign-in. Only those fields are read, never the whole body. A true token expiry (401/403 with any other code or message) is still expired. Every route that mapped 401/403 to expired: - overseas loader: 403 permission_error with the vendor's words and X-Magpie-Sign-In: kept; the second host isn't asked (a ban is the account's on every host, as a spent quota already was). - CN managed loader: the same. - refresh: an envelope ban throws "AutoClaw: " with signIn "kept"; a non-envelope 401/403 naming a ban does too, every other one stays expired. - usage: the wallets read said "积分接口无数据" for a ban; it now returns the vendor's words with signIn "kept". - check-in: taskList threw 登录已失效 for any 403; a ban now says the ban and stops the host rotation. - models: provider.models makes no request, nothing to change. Siblings with "every 401/403 is expired" and no vendor-shaped ban evidence, listed and left alone: qoder (refreshJob, patSignIn), codearts (withSignInMark, 403 on chat), cline (clineApi default lapsed), minimax (accountCall), kiro (refresh 400/401/403), opendesign (usage preflight, models), trae (refresh 400/401/403). Run at this head (worktree from origin/main 929a8b3): - packages/autoclaw: bun test (sandbox TMPDIR/HOME) 34 pass, 0 fail. - repo root: bun test 2157 pass, 0 fail across 188 files. - bun scripts/check.mjs: exit 0. - Broken by hand, each red: overseas loader back to quotaRefusal only, CN loader back to quotaRefusal only, refresh envelope ban check off, refresh non-envelope back to "expired", usage wallets ban throw off, check-in break-on-ban off, 410004 dropped from the codes. The new tests against origin/main's index.mjs: 6 of 6 red. Not tried: a real banned account (none at hand); the bytes are the reporter's. --- packages/autoclaw/index.mjs | 99 ++++++++++++++++++++---- packages/autoclaw/index.test.mjs | 128 +++++++++++++++++++++++++++++++ packages/autoclaw/package.json | 2 +- 3 files changed, 214 insertions(+), 15 deletions(-) diff --git a/packages/autoclaw/index.mjs b/packages/autoclaw/index.mjs index 2f8718b..098e7ed 100644 --- a/packages/autoclaw/index.mjs +++ b/packages/autoclaw/index.mjs @@ -119,6 +119,15 @@ async function explained(res) { const QUOTA_CODES = new Set(["810000"]); const QUOTA_WORDS = /额度|余额不足|用完|用尽|quota|insufficient[_ ]?(balance|credit)|exhausted/i; +/** said is the code and message of a parsed refusal body, read from its code/message fields only. */ +function said(d) { + if (!d || typeof d !== "object") return { code: null, message: "" }; + return { + code: d.code ?? d.error?.code ?? null, + message: String(d.message ?? d.msg ?? d.error?.message ?? "").trim(), + }; +} + /** quotaRefusal is a 403 chat answer read as a spent quota, or null when it isn't one (a 401 or any other 403 is still the sign-in). */ async function quotaRefusal(res) { if (res.status !== 403) return null; @@ -126,8 +135,7 @@ async function quotaRefusal(res) { let d; try { d = JSON.parse(text); } catch { return null; } if (!d || typeof d !== "object") return null; - const code = d.code ?? d.error?.code ?? null; - const message = String(d.message ?? d.msg ?? d.error?.message ?? "").trim(); + const { code, message } = said(d); if (!QUOTA_CODES.has(String(code)) && !(message && QUOTA_WORDS.test(message))) return null; try { res.body?.cancel?.(); } catch {} return new Response(JSON.stringify({ error: { message: `AutoClaw: ${message || "quota exhausted"}`, type: "rate_limit_error", code } }), { @@ -136,6 +144,50 @@ async function quotaRefusal(res) { }); } +// A 403 can be the account itself: a banned AutoClaw account answers +// HTTP 403 {"code":410004,"message":"The account has been banned"} on every +// route (小八, Discord 2026-10-23). That is no expired sign-in: signing in +// again gets the same account and the same refusal, and reading it as +// expired made magpie drop the token while the user never saw why. It goes +// on as a 403 with the vendor's words, and the sign-in is kept. Only the +// body's code or message field is read, never the whole body. +const BANNED_CODES = new Set(["410004"]); +const BANNED_WORDS = /\bbanned\b|封禁|封号|账号异常|账户异常|account (has been |is |was )?(suspended|frozen|disabled|blocked|restricted)|账[号户](已|已被|被)?(冻结|停用|禁用)/i; + +/** bannedSaid is the vendor's words when a parsed body is an account-level refusal (a ban), or "" when it isn't one. */ +function bannedSaid(d) { + const { code, message } = said(d); + if (BANNED_CODES.has(String(code))) return message || `account refused (code ${code})`; + return message && BANNED_WORDS.test(message) ? message : ""; +} + +/** bannedText is bannedSaid over a raw body text. */ +function bannedText(text) { + let d; + try { d = JSON.parse(text); } catch { return ""; } + return bannedSaid(d); +} + +/** accountRefusal is a 401/403 chat answer read as the account refused (banned), or null when it isn't one. */ +async function accountRefusal(res) { + if (res.status !== 401 && res.status !== 403) return null; + const text = await res.clone().text().catch(() => ""); + const message = bannedText(text); + if (!message) return null; + let code = null; + try { code = said(JSON.parse(text)).code; } catch {} + try { res.body?.cancel?.(); } catch {} + return new Response(JSON.stringify({ error: { message: `AutoClaw: ${message}`, type: "permission_error", code } }), { + status: 403, + headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "kept" }, + }); +} + +/** refusedNotSignIn is a 401/403 that is the account's (quota or ban), not its sign-in, or null. */ +async function refusedNotSignIn(res) { + return (await quotaRefusal(res)) ?? (await accountRefusal(res)); +} + function autoclawRewriteBody(rawBody) { let payload; try { @@ -293,12 +345,15 @@ async function callEnvelope(path, { method = "GET", body, base }) { 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"; + const banned = bannedSaid(parsed); + const err = new Error(banned + ? `AutoClaw: ${banned}` + : `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 = banned ? "kept" : "expired"; throw err; } - return { status: response.status, code: parsed.code, msg: parsed.msg, data: parsed.data }; + return { status: response.status, code: parsed.code, msg: parsed.msg ?? parsed.message, data: parsed.data, banned: bannedSaid(parsed) }; } /** 验证码必须按数字发送(服务端按类型校验,字符串 → 400001)。 */ @@ -336,9 +391,17 @@ async function fetchWallets(accessToken, hosts) { redirect: "error", signal: AbortSignal.timeout(20_000), }); - if (!res.ok) continue; + if (!res.ok) { + // a banned account is so on every host: say it instead of "no data" + const banned = (res.status === 401 || res.status === 403) ? bannedText(await res.text().catch(() => "")) : ""; + if (banned) throw Object.assign(new Error(`AutoClaw: ${banned}`), { banned: true }); + continue; + } payload = await res.json(); - } catch { continue; } + } catch (e) { + if (e?.banned) throw e; + continue; + } if (!payload || payload.code !== 0 || !payload.data) continue; return payload.data; } @@ -369,6 +432,8 @@ async function taskList(accessToken, host) { signal: AbortSignal.timeout(15_000), }); if (res.status === 401 || res.status === 403) { + const banned = bannedText(await res.text().catch(() => "")); + if (banned) throw Object.assign(new Error(`AutoClaw: ${banned}`), { banned: true, signIn: "kept" }); throw new Error(`登录已失效(HTTP ${res.status})`); } if (!res.ok) return null; @@ -519,6 +584,8 @@ async function refreshTokens(refreshToken, preferredHosts) { } if (!result) throw new Error("AutoClaw refresh: no host attempted"); if (result.code !== 0 || !result.data) { + // a banned account is refused, not signed out: the sign-in is kept + if (result.banned) throw Object.assign(new Error(`AutoClaw: ${result.banned}`), { signIn: "kept" }); 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}`}`); @@ -650,12 +717,12 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod }) const res1 = await tryFetch(hosts[0]); if (res1.status !== 401 && res1.status !== 403) return explained(res1); - // a spent quota is the account's on every host: not asked again - const spent1 = await quotaRefusal(res1); + // a spent quota or a ban is the account's on every host: not asked again + const spent1 = await refusedNotSignIn(res1); if (spent1) return spent1; try { res1.body?.cancel?.(); } catch {} const res2 = await tryFetch(hosts[1]); - const spent2 = await quotaRefusal(res2); + const spent2 = await refusedNotSignIn(res2); if (spent2) return spent2; if (res2.status === 401 || res2.status === 403) { try { res2.body?.cancel?.(); } catch {} @@ -678,7 +745,7 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod }) body: JSON.stringify(payload), }); if (res.status !== 401 && res.status !== 403) return explained(res); - const spent = await quotaRefusal(res); + const spent = await refusedNotSignIn(res); if (spent) return spent; try { res.body?.cancel?.(); } catch {} return new Response(JSON.stringify({ error: { message: "AutoClaw 登录已失效", type: "invalid_request_error" } }), { @@ -741,6 +808,7 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod }) ], }; } catch (e) { + if (e?.banned) return { error: e.message, signIn: "kept", windows: [] }; return { error: `积分查询失败: ${e?.message ?? e}`, windows: [] }; } }, @@ -766,7 +834,10 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod }) task = tasks.find((x) => x?.task_id === "daily_signin") ?? null; break; } - } catch (e) { lastErr = e; } + } catch (e) { + lastErr = e; + if (e?.banned) break; + } } if (!task && lastErr) throw lastErr; if (!task) return { outcome: "inactive", message: "当前没有签到活动" }; @@ -1252,7 +1323,7 @@ export const AutoclawCnAuthPlugin = makeAutoclawPlugin({ /** 测试辅助(magpie/OpenCode 不会把它当插件调用)。 */ export const _internal = { - quotaRefusal, + quotaRefusal, accountRefusal, bannedSaid, makePluginForTest: makeAutoclawPlugin, md5Hex, jwtClaim, tokenFields, codeValue, bizHeaders, bareToken, newDeviceId, dailySignin, signinStatus, maybeSignin, signinAccountKey, signinConfig, checkinOutcome, refreshTokens, diff --git a/packages/autoclaw/index.test.mjs b/packages/autoclaw/index.test.mjs index 323750c..ae93cb3 100644 --- a/packages/autoclaw/index.test.mjs +++ b/packages/autoclaw/index.test.mjs @@ -672,3 +672,131 @@ test("overseas chat: a spent quota on the first host isn't asked of the second, globalThis.fetch = realFetch } }) + +// 小八 (Discord, 2026-10-23): a banned AutoClaw account answers every route +// with exactly these bytes. It is the account, not an expired sign-in: +// magpie must keep the token and show the vendor's words. +const BANNED = '{"code":410004,"message":"The account has been banned"}' + +test("bannedSaid reads the code or message field, never the whole body", () => { + const { bannedSaid } = _internal + expect(bannedSaid(JSON.parse(BANNED))).toBe("The account has been banned") + expect(bannedSaid({ code: 410004 })).toBe("account refused (code 410004)") + expect(bannedSaid({ code: 1, msg: "账号已被封禁" })).toBe("账号已被封禁") + expect(bannedSaid({ error: { message: "账号异常,请联系客服" } })).toBe("账号异常,请联系客服") + // a true expiry, and "banned" outside the code/message fields, are not a ban + expect(bannedSaid({ code: 401, message: "token invalid" })).toBe("") + expect(bannedSaid({ code: 401001, msg: "invalid_grant", detail: "The account has been banned" })).toBe("") + expect(bannedSaid({ code: 401, message: "token expired" })).toBe("") +}) + +test("overseas chat: a banned account is a 403 with the vendor's words, the sign-in kept, the second host not asked", async () => { + const realFetch = globalThis.fetch + const urls = [] + let answer = () => new Response(BANNED, { status: 403, headers: { "content-type": "application/json" } }) + globalThis.fetch = async (input) => { + urls.push(String(input)) + return answer() + } + try { + const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } }) + const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "a1" })) + const body = JSON.stringify({ model: "zai_glm-5.3-flash", messages: [{ role: "user", content: "hi" }] }) + const banned = await loader.fetch("x", { method: "POST", body }) + expect(banned.status).toBe(403) + expect(banned.headers.get("X-Magpie-Sign-In")).toBe("kept") + const e = (await banned.json()).error + expect(e.message).toBe("AutoClaw: The account has been banned") + expect(e.type).toBe("permission_error") + expect(e.code).toBe(410004) + expect(urls.length).toBe(1) + + // a token both hosts refuse as expired is still the sign-in + urls.length = 0 + answer = () => new Response('{"code":401,"message":"token expired"}', { status: 401 }) + const dead = await loader.fetch("x", { method: "POST", body }) + expect(dead.status).toBe(401) + expect(dead.headers.get("X-Magpie-Sign-In")).toBe("expired") + expect(urls.length).toBe(2) + } finally { + globalThis.fetch = realFetch + } +}) + +test("CN chat: a banned account is a 403 with the vendor's words, and the sign-in is kept", async () => { + const realFetch = globalThis.fetch + let answer = () => new Response(BANNED, { status: 403 }) + globalThis.fetch = async () => answer() + try { + const hooks = await AutoclawCnAuthPlugin({ client: { auth: { set: async () => {} } } }) + const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "a1" })) + const body = JSON.stringify({ model: "zaicoding_glm-5.3", messages: [{ role: "user", content: "hi" }] }) + const banned = await loader.fetch("x", { method: "POST", body }) + expect(banned.status).toBe(403) + expect(banned.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect((await banned.json()).error.message).toBe("AutoClaw: The account has been banned") + + answer = () => new Response('{"code":401,"message":"token invalid"}', { status: 403 }) + const dead = await loader.fetch("x", { method: "POST", body }) + expect(dead.status).toBe(401) + expect(dead.headers.get("X-Magpie-Sign-In")).toBe("expired") + } finally { + globalThis.fetch = realFetch + } +}) + +test("refreshTokens keeps a banned account's sign-in and says why", async () => { + const realFetch = globalThis.fetch + const requests = [] + globalThis.fetch = async (input) => { + requests.push(String(input)) + return new Response(BANNED, { status: 403 }) + } + try { + let threw + try { await refreshTokens(jwt({ source_id: "google" }), []) } catch (e) { threw = e } + expect(threw).toBeInstanceOf(Error) + expect(threw.message).toBe("AutoClaw: The account has been banned") + expect(threw.signIn).toBe("kept") + expect(requests.length).toBe(1) + } finally { + globalThis.fetch = realFetch + } +}) + +test("refreshTokens keeps the sign-in for a ban without an envelope code", async () => { + const realFetch = globalThis.fetch + globalThis.fetch = async () => new Response('{"message":"The account has been banned"}', { status: 403 }) + try { + let threw + try { await refreshTokens(jwt({ source_id: "google" }), []) } catch (e) { threw = e } + expect(threw.message).toBe("AutoClaw: The account has been banned") + expect(threw.signIn).toBe("kept") + } finally { + globalThis.fetch = realFetch + } +}) + +test("usage and check-in of a banned account say the ban and keep the sign-in", async () => { + const realFetch = globalThis.fetch + const urls = [] + globalThis.fetch = async (input) => { + urls.push(String(input)) + return new Response(BANNED, { status: 403 }) + } + try { + for (const plugin of [AutoclawAuthPlugin, AutoclawCnAuthPlugin]) { + const hooks = await plugin({ client: { auth: { set: async () => {} } } }, {}) + const u = await hooks.auth.usage(async () => ({ type: "oauth", access: "a1", refresh: "r1" })) + expect(u.error).toBe("AutoClaw: The account has been banned") + expect(u.signIn).toBe("kept") + urls.length = 0 + let threw + try { await hooks.auth.checkin(async () => ({ type: "oauth", access: "a1", refresh: "r1" })) } catch (e) { threw = e } + expect(threw.message).toBe("AutoClaw: The account has been banned") + expect(urls.length).toBe(1) + } + } finally { + globalThis.fetch = realFetch + } +}) diff --git a/packages/autoclaw/package.json b/packages/autoclaw/package.json index 47a813c..9a45d4a 100644 --- a/packages/autoclaw/package.json +++ b/packages/autoclaw/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-autoclaw-auth", - "version": "0.2.4", + "version": "0.2.5", "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",