From e0769e8e20de1e008bd3424b06fc408383b89657 Mon Sep 17 00:00:00 2001 From: kongbai01203 <76691945+kongbai01203@users.noreply.github.com> Date: Sat, 7 Nov 2026 01:13:55 +0800 Subject: [PATCH] zcode 0.1.52: hold a rate-limited account in the plugin until ZCode's wait is over (#503) When ZCode rate limits a check-in (HTTP 429 on the touch feed, or code 3002 on a claim), the plugin now holds that account itself. Until the wait is over, a check-in answers the same failed (message and until) and sends no request. The wait follows Retry-After (seconds or a date) up to six hours. Without one, it doubles from 30 minutes. A read that comes through with nothing rate limited forgets it. magpie before v0.1.3165 asks a failed again after 30 minutes whatever its until says, which is how #503 saw 180 reads in four days. The hold is keyed by the account (s.key || s.jwt), so keyless Start-Plan sign-ins each have their own. It lives in memory, so a restart forgets it. Run at 017e5dfc (merge base 654d3bea), on mote with HOME in a temp folder: bun test packages/zcode 208 pass, 0 fail; check.mjs zcode ok. Merged with origin/main 8163be36: zcode 209 pass; the whole repo check.mjs exit 0 and bun test 6498 pass, 20 skip, 0 fail. Broken by hand, each red: holdKey back to s.key (the two-keyless-accounts test), the delete moved before the claims (the claim doubling test), no forget after a read with nothing to claim (the doubling test). CI on-npm and test green at 017e5dfc. Not tried: a live ZCode 429 or 3002. --- packages/zcode/README.md | 11 ++++ packages/zcode/checkin.test.mjs | 96 +++++++++++++++++++++++++++- packages/zcode/index.mjs | 109 +++++++++++++++++++++++++++++--- packages/zcode/package.json | 2 +- 4 files changed, 207 insertions(+), 11 deletions(-) diff --git a/packages/zcode/README.md b/packages/zcode/README.md index 920f148..68f76ca 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -323,6 +323,17 @@ the body's code, not the HTTP status: first: six accounts all answered 1004 under 3.16.3's header, and four of them claimed with code 0 under 3.17.2's, one night, with nothing else changed; +- HTTP 429 "Too Many Requests", or a body code 3002 "请求过于频繁": *failed*, + and the account is then **held in the plugin**: until the wait is over, a + check-in answers that same failed (`until` and all) and asks ZCode nothing. + magpie asks a failed again after 30 minutes of its own whatever `until` + says, so the hold has to live here (magpie from v0.1.3165 honors a failed's + `until` itself; older versions lean on this hold). A `Retry-After` ZCode + sent is honored up to six hours; without one the account's own wait doubles + from half an hour, and a read that comes through forgets it. The hold + belongs to one account and lives in memory — a magpie restart forgets it. + (11-04, #503: one owner read 180 of them over four days at magpie's + 30-minute retry, across several accounts.); - anything else, an HTTP error without a code, or a reply that isn't JSON: *failed*, which magpie asks again later that day. It is never taken as claimed, and a failed claim leaves the account's sign-in diff --git a/packages/zcode/checkin.test.mjs b/packages/zcode/checkin.test.mjs index 492f0bc..77884e6 100644 --- a/packages/zcode/checkin.test.mjs +++ b/packages/zcode/checkin.test.mjs @@ -11,10 +11,10 @@ import { test, expect, afterAll, beforeAll, beforeEach } from "bun:test" import { homedir, tmpdir } from "node:os" import { readFileSync, realpathSync } from "node:fs" -let ZCodeAuthPlugin, _internal +let ZCodeAuthPlugin, _internal, resetRateWait beforeAll(async () => { if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test") - ;({ ZCodeAuthPlugin, _internal } = await import("./index.mjs")) + ;({ ZCodeAuthPlugin, _internal, resetRateWait } = await import("./index.mjs")) }) const offline = async () => { throw new Error("no network in tests") } const real = globalThis.fetch @@ -22,6 +22,7 @@ afterAll(() => (globalThis.fetch = real)) beforeEach(() => { globalThis.fetch = offline _internal.routes.clear() + resetRateWait() // each test starts with no hold of its own (they share an account key) }) // serve is the fake zcode.z.ai: route answers each request, and a request @@ -37,6 +38,8 @@ function serve(route) { return calls } const json = (v, status = 200) => new Response(typeof v === "string" ? v : JSON.stringify(v), { status }) +// jsonWith is json with headers: a Retry-After comes as one +const jsonWith = (v, status, headers) => new Response(typeof v === "string" ? v : JSON.stringify(v), { status, headers }) const jwt = (exp) => ["{}", JSON.stringify({ exp })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig" const now = Math.trunc(Date.now() / 1000) const DEVICE = "11111111-2222-4333-8444-555555555555" @@ -76,6 +79,10 @@ const CAPTCHA = '{"code":3007,"msg":"captcha verify failed"}' // The same six accounts answered it under an older APP_VERSION's header // and four of them claimed with code 0 under 3.17.2's. const NOT_ELIGIBLE = '{"code":1004,"msg":"your account is not eligible for this plan yet"}' +// 11-04 (#503, MiniFullC): what ZCode says to a client that asked too +// often, with HTTP 429 — read 180 times over four days at magpie's +// 30-minute retry +const RATE_LIMITED = '{"code":3002,"msg":"请求过于频繁"}' const PREVIEW = "/api/v1/zcode-plan/billing/preview" const CLAIM = "/api/v1/zcode-plan/billing/claim" @@ -206,6 +213,91 @@ test("a 1004 beside a claimed plan is claimed, naming the one not offered", asyn expect(r.message).toContain("ZCODE GLOBAL BUILD: your account is not eligible for this plan yet") }) +test("a rate-limited feed is failed with an until half an hour out", async () => { + claimWith(() => json(CLAIMED_NOW), () => json("", 429)) + const r = await checkin() + expect(r.outcome).toBe("failed") + expect(r.message).toContain("Too Many Requests") + const t = Date.parse(r.until) + expect(t).toBeGreaterThan(Date.now() + 25 * 60_000) + expect(t).toBeLessThan(Date.now() + 35 * 60_000) +}) + +// the hold itself: magpie asks a failed again after 30 minutes of its own +// whatever `until` says, so the plugin must be the one that waits +test("a check-in inside the wait asks ZCode nothing, and answers the failed it gave", async () => { + const calls = claimWith(() => json(CLAIMED_NOW), () => json("", 429)) + const first = await checkin() + expect(first.outcome).toBe("failed") + const asked = calls.length // what the first read spent + const again = await checkin() + expect(again.outcome).toBe("failed") + expect(again.message).toBe(first.message) // the same failed, replayed + expect(again.until).toBe(first.until) + expect(calls.length).toBe(asked) // not one request more +}) + +test("a check-in after the wait reaches ZCode again", async () => { + const calls = claimWith(() => json(CLAIMED_NOW), () => json("", 429)) + await checkin() + const asked = calls.length + resetRateWait(true) // stand where the wait has passed + await checkin() + expect(calls.length).toBeGreaterThan(asked) +}) + +test("a Retry-After ZCode sent is honored", async () => { + claimWith(() => json(CLAIMED_NOW), () => jsonWith("", 429, { "retry-after": "7200" })) + const r = await checkin() + expect(r.outcome).toBe("failed") + const t = Date.parse(r.until) + expect(t).toBeGreaterThan(Date.now() + 110 * 60_000) + expect(t).toBeLessThan(Date.now() + 130 * 60_000) +}) + +test("a claim ZCode rate limited (3002) is failed and held too", async () => { + claimWith(() => json(RATE_LIMITED, 400), touchOf([TRUST, "ZCode Trust Build"])) + const r = await checkin() + expect(r.outcome).toBe("failed") + expect(r.message).toContain("ZCode Trust Build: 请求过于频繁") + expect(Date.parse(r.until)).toBeGreaterThan(Date.now() + 25 * 60_000) +}) + +// stateOf gives a sign-in that has a jwt and no API key (the +// Start-Plan-only accounts that claim gift plans) key: "", so a hold keyed +// by the key alone would answer for every one of them +test("another keyless sign-in still reaches ZCode while one is held", async () => { + claimWith(() => json(CLAIMED_NOW), () => json("", 429)) + expect((await checkin()).outcome).toBe("failed") // the first account is held + const other = claimWith(() => json(CLAIMED_NOW), touchOf([TRUST, "ZCode Trust Build"])) + const r = await checkin(oauth({ site: "zai", jwt: jwt(now + 86401), device: DEVICE })) + expect(other.length).toBeGreaterThan(0) // asked ZCode all the same + expect(r.outcome).toBe("claimed") +}) + +test("a claim ZCode keeps limiting waits longer each time", async () => { + claimWith(() => json(RATE_LIMITED, 400), touchOf([TRUST, "ZCode Trust Build"])) + const first = Date.parse((await checkin()).until) + resetRateWait(true) // the wait passed, so the next claim reaches ZCode + claimWith(() => json(RATE_LIMITED, 400), touchOf([TRUST, "ZCode Trust Build"])) + const second = Date.parse((await checkin()).until) + expect(second - first).toBeGreaterThan(20 * 60_000) // ~30 min -> ~60 min +}) + +test("the wait doubles while ZCode keeps turning the ask away, and a read that comes through forgets it", async () => { + claimWith(() => json(CLAIMED_NOW), () => json("", 429)) + const first = Date.parse((await checkin()).until) + resetRateWait(true) // the wait passed, so the next ask reaches ZCode + const second = Date.parse((await checkin()).until) + expect(second - first).toBeGreaterThan(20 * 60_000) // ~30 min -> ~60 min + // a read that comes through (nothing to claim) forgets the wait + resetRateWait(true) + claimWith(() => json(CLAIMED_NOW), TOUCH_NONE) + expect((await checkin()).outcome).toBe("inactive") + claimWith(() => json(CLAIMED_NOW), () => json("", 429)) + expect(Date.parse((await checkin()).until)).toBeLessThan(Date.now() + 35 * 60_000) +}) + test("a claim that doesn't read is failed (unknown), never claimed", async () => { for (const answer of [ () => json("", 500), diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index 13cbbe3..37d0edb 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -96,8 +96,11 @@ async function call(method, url, { auth, body, headers, device, signal } = {}) { } catch {} const code = env?.code == null ? "" : String(env.code) if (!res.ok) { - if (env?.msg) throw new ZError(code && code !== "0" ? `${env.msg} (${res.status}, code ${code})` : `${env.msg} (${res.status})`, res.status) - throw new ZError(STATUS_TEXT[res.status] ?? `${res.status} ${res.statusText}`.trim(), res.status) + const said = env?.msg ? (code && code !== "0" ? `${env.msg} (${res.status}, code ${code})` : `${env.msg} (${res.status})`) : (STATUS_TEXT[res.status] ?? `${res.status} ${res.statusText}`.trim()) + const err = new ZError(said, res.status) + err.code = Number(code) || 0 // 3002 and the like: so a caller can tell a rate limit from a failure + err.retryAfterMs = retryAfterMs(res) // 0 unless the reply carried a Retry-After + throw err } if (!env || typeof env !== "object") throw new ZError("not JSON", res.status) if (code && code !== "0" && code !== "200") throw new ZError(env.msg || `error ${code}`, res.status) @@ -715,6 +718,62 @@ const CAPTCHA = 3007 // 1004 under 3.16.3's header, and four of them claimed with code 0 under // 3.17.2's, one night, with nothing else changed). const NOT_ELIGIBLE = 1004 +// RATE_LIMITED is Z.ai's "请求过于频繁" body code, its answer (with HTTP +// 429) to a client that asked too often. #503 (MiniFullC, 11-04) read 180 +// "gift plans to claim: Too Many Requests" over four days at magpie's +// 30-minute retry, so asking again the same half hour keeps the limit on. +// magpie asks a failed again once retryAfter() has passed, whatever the +// answer's `until` says (the contract reads `until` as when an answer +// stops standing, not as the earliest time to ask again), so the account +// is held here instead: while the wait lasts, claimDaily answers the same +// failed again, `until` and all, and asks ZCode nothing. A Retry-After +// ZCode sent is honored up to RATE_LIMIT_MAX_MS; without one the +// account's own wait doubles from RECHECK_MS, and a read that comes +// through forgets it. +const RATE_LIMITED = 3002 +const RATE_LIMIT_MAX_MS = 6 * 60 * 60_000 +const rateWait = new Map() // s.key -> { ms, until, message }: the hold this account is under +// resetRateWait is for tests: it forgets the holds, and with `expire` it +// back-dates them, standing where the wait has passed. The plugin itself +// forgets a hold by reading through or by waiting it out, never by calling +// this. +export function resetRateWait(expire = false) { + if (!expire) { + rateWait.clear() + return + } + for (const [k, h] of rateWait) rateWait.set(k, { ...h, until: new Date(Date.now() - 1).toISOString() }) +} +// holdKey names the account a wait belongs to. stateOf gives key: "" to a +// sign-in that has a jwt and no API key — the Start-Plan-only sign-ins +// that claim gift plans, #503's case — so the key alone would put every +// one of them under a single hold, and one account's 429 would answer for +// all of them. The jwt tells them apart; a renewed token starting its own +// wait is fine. +const holdKey = (s) => s.key || s.jwt +// retryAfterMs is a Retry-After header, in seconds or as an HTTP date, in +// ms; 0 when there is none or it doesn't read. +function retryAfterMs(res) { + const v = first(res?.headers?.get?.("retry-after")) + if (!v) return 0 + const secs = Number(v) + if (Number.isFinite(secs) && secs > 0) return secs * 1000 + const at = Date.parse(v) + return Number.isFinite(at) ? Math.max(0, at - Date.now()) : 0 +} +// noteRateLimit remembers the wait this account is under, with the failed +// that wait answers with, and says when it ends: a Retry-After ZCode sent +// is taken as it is, up to the cap; without one the wait doubles from +// RECHECK_MS (and never falls below it), so a client ZCode keeps turning +// away asks less and less. +function noteRateLimit(key, saidMs, message) { + const last = rateWait.get(key)?.ms ?? 0 + const want = saidMs > 0 ? saidMs : Math.max(RECHECK_MS, last * 2) + const ms = Math.min(RATE_LIMIT_MAX_MS, want) + const until = new Date(Date.now() + ms).toISOString() + rateWait.set(key, { ms, until, message }) + return until +} const CAPTCHA_WORDS = /captcha/i // The marketing feed and the claim are gated on the client's version: @@ -747,6 +806,8 @@ async function claimOne(s, planID) { } catch {} const code = env && typeof env === "object" && env.code != null && String(env.code).trim() !== "" ? Number(env.code) : NaN const msg = typeof env?.msg === "string" ? env.msg : "" + // a rate limit is no claim: it is said as one, and carries how long to wait + if (res.status === 429 || code === RATE_LIMITED) return { outcome: "failed", why: `${msg || STATUS_TEXT[429]} (HTTP ${res.status}${Number.isFinite(code) ? `, code ${code}` : ""})`, rate: retryAfterMs(res) } if (code === CAPTCHA || CAPTCHA_WORDS.test(msg)) return { outcome: "captcha", why: msg || `code ${code}` } if (code === CLAIMED_ALREADY) return { outcome: "done" } if (code === NOT_ELIGIBLE) return { outcome: "ineligible", why: msg || `code ${code}` } @@ -829,12 +890,14 @@ async function toClaim(s) { d = await call("GET", `${ZCODE}${TOUCH}?seq=${touchSeq++}`, { auth: "Bearer " + s.jwt, device: s.device, headers: marketingHeaders() }) } catch (e) { unread.push(`gift plans to claim: ${e?.message ?? String(e)}`) - return { plans, unread } + // rate is the ms ZCode asked to wait (0 when it sent no Retry-After), + // null when this was not a rate limit at all + return { plans, unread, rate: e?.status === 429 || e?.code === RATE_LIMITED ? (e.retryAfterMs || 0) : null } } const got = touchPlans(d) if (!got) unread.push("gift plans to claim: the plan list doesn't read") else got.forEach(add) - return { plans, unread } + return { plans, unread, rate: null } } // RECHECK is how long an "nothing to claim" stands before magpie's loop @@ -863,7 +926,16 @@ const recheck = () => new Date(Date.now() + RECHECK_MS).toISOString() // captcha for one (it is claimed in the ZCode app), ineligible when // ZCode is not offering one at that moment (code 1004, read again later // in the day), failed when a list -// or a claim can't be read. A failed one is asked again later in the +// or a claim can't be read. A rate-limited read (HTTP 429, or code 3002) +// is not asked again either: the account is held here until the wait ends +// (a Retry-After ZCode sent, else the account's own wait doubling from +// RECHECK_MS, out to RATE_LIMIT_MAX_MS — see RATE_LIMITED), and every ask +// inside the wait answers the failed it already gave, without a request. +// The hold belongs to one account (`s.key || s.jwt`) and lives in this +// process's memory alone: a magpie restart forgets it. magpie from +// v0.1.3165 honors a failed's `until` itself; older versions wait for +// this hold, which is why it stays. +// A failed one is asked again later in the // day, when a plan claimed now answers 1003. An inactive stands only // until RECHECK_MS from now, so a plan dropped into the feed later in // the day is still claimed; the other settled answers stand for the day @@ -872,9 +944,26 @@ const recheck = () => new Date(Date.now() + RECHECK_MS).toISOString() async function claimDaily(s) { if (!s?.jwt) return { outcome: "ineligible", message: "ZCode's gift plans are claimed with a ZCode sign-in; this account has none" } if (jwtExpired(s.jwt)) return { outcome: "failed", message: EXPIRED } - const { plans, unread } = await toClaim(s) - if (!plans.length && unread.length) return { outcome: "failed", message: unread.join("; ") } - if (!plans.length) return { outcome: "inactive", message: "no ZCode gift plan to claim", until: recheck() } + // a rate limit this account is still under: the same failed again, and + // not one request (magpie asks a failed again after 30 minutes of its + // own, so holding it is the plugin's job — see RATE_LIMITED) + const held = rateWait.get(holdKey(s)) + if (held && Date.now() < Date.parse(held.until)) return { outcome: "failed", message: held.message, until: held.until } + const { plans, unread, rate = null } = await toClaim(s) + // a rate-limited read: held here until the wait is over + if (rate !== null) { + const message = unread.join("; ") || "ZCode rate limited this account" + return { outcome: "failed", message, until: noteRateLimit(holdKey(s), rate, message) } + } + // the feed answered and no claim is read: the wait is over. It is not + // forgotten before the claims below, so a claim ZCode keeps limiting + // waits longer each time (see noteRateLimit) + if (!plans.length) { + rateWait.delete(holdKey(s)) + return unread.length + ? { outcome: "failed", message: unread.join("; ") } + : { outcome: "inactive", message: "no ZCode gift plan to claim", until: recheck() } + } const got = [] for (const p of plans) got.push({ name: p.name, ...(await claimOne(s, p.plan_id)) }) const named = (o) => got.filter((g) => g.outcome === o).map((g) => g.name) @@ -888,6 +977,10 @@ async function claimDaily(s) { ].filter(Boolean).join("; ") // a plan claimed now is used by the next request, not ten minutes on if (claimed.length) routes.delete(s.key + "\0" + s.jwt) + // a claim ZCode rate limited: the plan may still be there, later + const limitedClaim = got.find((g) => g.rate !== undefined) + if (limitedClaim) return { outcome: "failed", message: said, until: noteRateLimit(holdKey(s), limitedClaim.rate, said) } + rateWait.delete(holdKey(s)) // nothing in this check-in was rate limited: the wait is over // a list that didn't read may hold a plan not claimed: asked again if (unread.length || got.some((g) => g.outcome === "failed")) return { outcome: "failed", message: said } if (got.some((g) => g.outcome === "captcha")) return { outcome: "captcha", message: said } diff --git a/packages/zcode/package.json b/packages/zcode/package.json index c3cc4c0..868ae26 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.51", + "version": "0.1.52", "description": "OpenCode provider plugin: signs in to Z.ai's or BigModel's (智谱) GLM Coding Plan as ZCode does, including team seats and ZCode's Start Plan, and claims its gift plans daily", "type": "module", "main": "./opencode.mjs",