diff --git a/packages/zcode/README.md b/packages/zcode/README.md index 15d422c..9b9405d 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -31,7 +31,10 @@ over Anthropic's Messages API. Provider id: `zcode`. picks by it, so without it the cache is mostly missed (#387). An account known only by its key gets a device id made from the key, the same on every start. Every request also carries the `x-session-id` - header below. zcode.z.ai also + header below. ZCode's headers are the desktop app's (3.17.2): + `X-Title: Z Code@electron`, and an `x-query-id` per user turn, a UUID + that stays the same through the turn's tool results and is new with + the next user message, as ZCode makes one per query. zcode.z.ai also answers 405 code 3012 to every request of an account its risk control blocked, ZCode's own app's included (plugins#348). That answer comes back as ZCode's words, then "ZCode's risk control blocked this account @@ -326,6 +329,13 @@ the body's code, not the HTTP status: read is *failed*, never nothing to claim; - code 0: *claimed* (the next request uses the plan); - code 1003 "target already exists" (HTTP 200): *done*, claimed before; +- ZCode's own client config (`GET /api/v1/client/configs`, read at most + every ten minutes) says whether a claim needs its security check + (`captcha.enabled`). While it does, which is so since 11-07, nothing is + posted: every plan answers *captcha*, "claim it in the ZCode app", since + a claim without the app's proof only spends one of ZCode's refusals. A + config that doesn't read answers *failed*, and nothing is posted then + either; - code 3007 "captcha verify failed": *captcha*, the plan is claimed in the ZCode app — the claim is gated on the Aliyun captcha the app's renderer answers, and a claim from outside the app is refused it diff --git a/packages/zcode/checkin.test.mjs b/packages/zcode/checkin.test.mjs index 77884e6..ed58535 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, resetRateWait +let ZCodeAuthPlugin, _internal, resetRateWait, resetClientConfigs beforeAll(async () => { if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test") - ;({ ZCodeAuthPlugin, _internal, resetRateWait } = await import("./index.mjs")) + ;({ ZCodeAuthPlugin, _internal, resetRateWait, resetClientConfigs } = await import("./index.mjs")) }) const offline = async () => { throw new Error("no network in tests") } const real = globalThis.fetch @@ -23,17 +23,25 @@ beforeEach(() => { globalThis.fetch = offline _internal.routes.clear() resetRateWait() // each test starts with no hold of its own (they share an account key) + resetClientConfigs() // and reads client/configs from its own fake }) // serve is the fake zcode.z.ai: route answers each request, and a request -// it doesn't answer is a 404 +// it doesn't answer is a 404, but client/configs, which says whether a +// claim wants ZCode's captcha: unless route answers it, configs with no +// captcha, as they were before 11-07 +const CONFIGS = "/api/v1/client/configs" +const NO_CAPTCHA = { code: 0, msg: "", data: { configs: { builtin_provider_config_json: "https://cdn-zcode.z.ai/zcode/config/zcode-builtin-production-43.json" } } } +// 11-07's configs as zcode.z.ai answered 3.17.2 (cut to the two keys the +// plugin reads): claims want the captcha, Start Plan requests are spared +const CAPTCHA_ON = JSON.parse(readFileSync(new URL("./testdata/client-configs-1107.json", import.meta.url), "utf8")) function serve(route) { const calls = [] globalThis.fetch = async (url, init = {}) => { const u = new URL(String(url)) const c = { url: u, method: init.method ?? "GET", headers: init.headers ?? {}, body: init.body } calls.push(c) - return (await route(c)) ?? new Response("", { status: 404 }) + return (await route(c)) ?? (u.pathname === CONFIGS ? Response.json(NO_CAPTCHA) : new Response("", { status: 404 })) } return calls } @@ -476,3 +484,62 @@ test("the feed is asked in zh-CN or en-US only, as the app asks it", async () => Intl.DateTimeFormat = realDTF } }) + +// young02036 on Discord (11-07): the check-in asked for a captcha every +// day while the ZCode app showed none. zcode.z.ai's client/configs had +// switched its captcha on (testdata/client-configs-1107.json), and the +// app passes that check (Aliyun's, invisibly) before each claim, sending +// the proof as X-Aliyun-Captcha-Verify-Param (3.17.2's +// requestVerificationClaimHeaders). The plugin can't, so it posts no +// claim: the plans are named, to claim in the app. +test("a claim ZCode guards with its captcha is not posted, and the plan is named for the app", async () => { + const calls = serve(({ url, method }) => { + if (url.pathname === CONFIGS) return json(CAPTCHA_ON) + if (url.pathname === TOUCH && method === "GET") return json(TOUCH_REAL) + if (url.pathname === CLAIM) return json(CAPTCHA, 400) + }) + const r = await checkin() + expect(r.outcome).toBe("captcha") + expect(r.message).toBe("ZCODE WEEKEND BUILD: claim it in the ZCode app: ZCode asks its security check before a claim, which only the app passes, so the daily check-in leaves it to the app") + expect(r.until).toBeUndefined() // settled for the day, as a captcha was + expect(claims(calls)).toEqual([]) +}) + +test("captcha switched off in the configs: the claim is posted as before", async () => { + const off = structuredClone(CAPTCHA_ON) + off.data.configs.captcha.enabled = false + const calls = serve(({ url, method }) => { + if (url.pathname === CONFIGS) return json(off) + if (url.pathname === TOUCH && method === "GET") return json(TOUCH_REAL) + if (url.pathname === CLAIM && method === "POST") return json(CLAIMED_WEEKEND) + }) + expect((await checkin()).outcome).toBe("claimed") + expect(claims(calls)).toHaveLength(1) +}) + +// a failed read is unknown, never "no captcha": nothing is posted, and +// the failed is asked again by magpie later +test("configs that don't read: no claim posted, failed", async () => { + for (const configs of [() => json("", 500), () => json({ code: 0, data: { configs: { captcha: "on" } } })]) { + resetClientConfigs() + const calls = serve(({ url, method }) => { + if (url.pathname === CONFIGS) return configs() + if (url.pathname === TOUCH && method === "GET") return json(TOUCH_REAL) + if (url.pathname === CLAIM && method === "POST") return json(CLAIMED_WEEKEND) + }) + const r = await checkin() + expect(r.outcome).toBe("failed") + expect(r.message).toContain("ZCODE WEEKEND BUILD: not claimed, ZCode's security check for claims can't be read") + expect(claims(calls)).toEqual([]) + } +}) + +// nothing to claim asks no config at all: the feed alone, as before +test("nothing in the feed: client/configs is not asked", async () => { + const calls = serve(({ url, method }) => { + if (url.pathname === CONFIGS) return json(CAPTCHA_ON) + if (url.pathname === TOUCH && method === "GET") return json(TOUCH_NONE) + }) + expect((await checkin()).outcome).toBe("inactive") + expect(calls.filter((c) => c.url.pathname === CONFIGS)).toEqual([]) +}) diff --git a/packages/zcode/dual.test.mjs b/packages/zcode/dual.test.mjs index d942ed1..ac30880 100644 --- a/packages/zcode/dual.test.mjs +++ b/packages/zcode/dual.test.mjs @@ -705,7 +705,7 @@ test("a trial entry goes to the Start Plan, dressed", async () => { const m = sent.at(-1) expect(m.origin).toBe("https://zcode.z.ai") expect(m.path).toBe("/api/v1/zcode-plan/anthropic/v1/messages") - expect(m.headers["x-title"]).toBe("Z Code@cli") + expect(m.headers["x-title"]).toBe("Z Code@electron") expect(m.headers.authorization).toBe("Bearer " + jwt) expect(m.headers["x-api-key"]).toBeUndefined() expect(JSON.parse(m.body).system.length).toBeGreaterThan(1) // dressed diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index 64ea77e..00d848c 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -789,6 +789,23 @@ function noteRateLimit(key, saidMs, message) { } const CAPTCHA_WORDS = /captcha/i +// claimNeedsCaptcha says whether ZCode's claims want its security check +// now, from what client/configs says: its captcha (Aliyun's, which the +// ZCode app passes before every claim, invisibly as a rule, and sends as +// X-Aliyun-Captcha-Verify-Param, 3.17.2's requestVerificationClaimHeaders) +// switched on. No captcha in the configs is no check, as the app reads it +// (readRequestVerificationConfig gives null, and the claim goes without +// the header); one that isn't an object is unknown, null. +// skip_model_request is the same check for Start Plan requests, which it +// spares (true on 11-07); it is not read here. +function claimNeedsCaptcha(c) { + const k = c?.configs?.captcha + if (k == null) return false + if (typeof k !== "object" || Array.isArray(k)) return null + return k.enabled !== false +} +const CAPTCHA_CLAIM = "claim it in the ZCode app: ZCode asks its security check before a claim, which only the app passes, so the daily check-in leaves it to the app" + // The marketing feed and the claim are gated on the client's version: // under an older version's header the feed answers empty (11-03, #678: // the day's banner showed for 3.17.2 and for no older one), so they go, @@ -977,6 +994,24 @@ async function claimDaily(s) { ? { outcome: "failed", message: unread.join("; ") } : { outcome: "inactive", message: "no ZCode gift plan to claim", until: recheck() } } + // a claim ZCode guards with its security check is not posted: the app + // passes it before each claim and sends the proof in a header, which + // this plugin can't make, and a claim without it only gets 3007 again + // (young02036 on Discord, 11-07: asked every day, never claimed). The + // plans are named, to claim in the ZCode app. A config that doesn't + // read leaves it unknown: nothing is posted, and it is asked again. + let guarded + try { + guarded = claimNeedsCaptcha(await clientConfigs()) + } catch (e) { + guarded = null + unread.push(`ZCode's client config: ${e?.message ?? String(e)}`) + } + if (guarded !== false) { + rateWait.delete(holdKey(s)) + if (guarded === null) return { outcome: "failed", message: [...plans.map((p) => `${p.name}: not claimed, ZCode's security check for claims can't be read`), ...unread].join("; ") } + return { outcome: "captcha", message: plans.map((p) => `${p.name}: ${CAPTCHA_CLAIM}`).join("; ") } + } 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) @@ -1833,7 +1868,7 @@ function localConfig() { // remoteConfig is the release of ZCode's provider config zcode.z.ai names now. async function remoteConfig() { const signal = AbortSignal.timeout(8000) - const c = await call("GET", `${ZCODE}/api/v1/client/configs?app_version=${APP_VERSION}&platform=${platform()}`, { signal }) + const c = await clientConfigs() const url = c?.configs?.builtin_provider_config_json if (!String(url ?? "").startsWith("https://")) throw new Error("ZCode's configs name no provider config") const res = await fetch(url, { headers: { "User-Agent": UA }, signal }) @@ -1841,6 +1876,23 @@ async function remoteConfig() { return res.json() } +// clientConfigs is what zcode.z.ai tells this client version +// (/api/v1/client/configs): the provider config's address, and the +// captcha its claims and requests need (claimNeedsCaptcha). A read that +// came through is kept for 10 minutes; a failed one is not kept, and +// throws. +let clientCache = null +async function clientConfigs() { + if (clientCache && Date.now() - clientCache.at < 600_000) return clientCache.c + const c = await call("GET", `${ZCODE}/api/v1/client/configs?app_version=${APP_VERSION}&platform=${platform()}`, { signal: AbortSignal.timeout(8000) }) + clientCache = { c, at: Date.now() } + return c +} +// resetClientConfigs is for tests: the next read asks zcode.z.ai again. +export function resetClientConfigs() { + clientCache = null +} + // config is ZCode's provider config, the later of zcode.z.ai's and an // installed ZCode's, kept for 10 minutes. let cfgCache = null @@ -2182,7 +2234,12 @@ function startHeaders(h, jwt) { out.set("HTTP-Referer", ZCODE) out.set("User-Agent", UA + " ai-sdk/anthropic/3.0.81") out.set("X-ZCode-App-Version", APP_VERSION) - out.set("X-Title", "Z Code@cli") + // the desktop app's agent names itself electron: 3.17.2's + // zcode-protocol-entrypoint passes sourceTitle "electron", and a bare + // run under app-server says the same (Mvc in glm/zcode.cjs); "cli" is + // the zcode command line's alone, which sends no X-Device-Mid on the + // app's calls and no desktop prompt texts, as this plugin does + out.set("X-Title", "Z Code@electron") out.set("X-Release-Channel", "production") const o = intl() out.set("X-Client-Language", o.locale || "unknown") @@ -2201,6 +2258,30 @@ function startHeaders(h, jwt) { return out } +// queryOf is the request's x-query-id, as 3.17.2's +// createModelRequestAttributionHeaders (zft in glm/zcode.cjs) sends it: +// the user's query, "query_" + a UUID with the prefix cut, the same for +// every request of one turn (the tool calls the model makes on the way) +// and a new one for the next thing the user says. The agent's turns are +// counted: a user message that carries text, not tool results alone, +// starts a query. A body that doesn't read gives none, and none is sent. +function queryOf(text, session) { + let b + try { + b = JSON.parse(text) + } catch { + return "" + } + if (!Array.isArray(b?.messages)) return "" + let n = 0 + for (const m of b.messages) { + if (m?.role !== "user") continue + const c = m.content + if (typeof c === "string" ? c.trim() : Array.isArray(c) && c.some((x) => x && x.type !== "tool_result")) n++ + } + return n ? uuidOf("zcode-query\0" + session + "\0" + n) : "" +} + // Claude Code's tool search, as ZCode's plans take it. Claude Code // (2.1.310) offers a tool named ToolSearch, names its deferred tools in a // system turn, and sends a deferred tool's schema with defer_loading only @@ -2739,6 +2820,8 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { if (opts.body != null) { const text = orig ?? (typeof opts.body === "string" ? opts.body : await new Response(opts.body).text()) opts.body = dress(text, s.site, s.device, place, sid) + const q = queryOf(text, sid) + if (q) h.set("x-query-id", q) delete opts.duplex h.delete("content-length") } @@ -2975,4 +3058,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { // config sets what zcodeConfig has read, for tests: null is ZCode's config // out of reach, undefined forgets it const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() }) -export const _internal = { edge, EDGE_HOLD, busyHold, BUSY_N, BUSY_WINDOW, BUSY_HOLD, busyCap, busyHeld, config, entry, limitWindows, termOf, startUsage, routes, blocked, sidelined, plansOf, giftOf, dualUsage, claimHint, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, DEFAULT_ACCOUNTS } +export const _internal = { edge, EDGE_HOLD, busyHold, BUSY_N, BUSY_WINDOW, BUSY_HOLD, busyCap, busyHeld, config, entry, limitWindows, termOf, startUsage, routes, blocked, sidelined, plansOf, giftOf, dualUsage, claimHint, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, queryOf, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, DEFAULT_ACCOUNTS } diff --git a/packages/zcode/package.json b/packages/zcode/package.json index ad83275..18ee8fc 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.54", + "version": "0.1.55", "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", diff --git a/packages/zcode/start.test.mjs b/packages/zcode/start.test.mjs index 2140cd0..b6ae6b1 100644 --- a/packages/zcode/start.test.mjs +++ b/packages/zcode/start.test.mjs @@ -248,7 +248,7 @@ test("a Start Plan request carries ZCode's headers, and only those", async () => "http-referer": "https://zcode.z.ai", "user-agent": "ZCode/3.17.2 ai-sdk/anthropic/3.0.81", "x-zcode-app-version": "3.17.2", - "x-title": "Z Code@cli", + "x-title": "Z Code@electron", "x-release-channel": "production", "x-client-language": o.locale, "x-client-timezone": o.timeZone, @@ -260,9 +260,12 @@ test("a Start Plan request carries ZCode's headers, and only those", async () => "x-zcode-session-type": "main", "x-zcode-trace-id": h["x-zcode-trace-id"], "x-zcode-query-source": "main_turn", + // the user's query this turn answers, as 3.17.2 names it + "x-query-id": _internal.queryOf(JSON.stringify(agentBody), _internal.sessionOf("", DEVICE)), // the conversation, as ZCode names it; the agent told none (#387) "x-session-id": _internal.sessionOf("", DEVICE), }) + expect(h["x-query-id"]).toMatch(UUID) expect(h["x-api-key"]).toBeUndefined() expect(h["x-device-mid"]).toBeUndefined() }) @@ -297,7 +300,7 @@ test("a Start Plan request from Claude Code goes with ZCode's headers alone, wit const h = own(r.headers) for (const k of Object.keys(CLAUDE_CODE)) if (!TRANSPORT.has(k)) expect(h[k]).toBeUndefined() expect(Object.keys(h).sort()).toEqual( - ["authorization", "anthropic-version", "content-type", "http-referer", "user-agent", "x-zcode-app-version", "x-title", "x-release-channel", "x-client-language", "x-client-timezone", "x-zcode-agent", "x-platform", "x-os-category", "x-os-version", "x-request-id", "x-zcode-session-type", "x-zcode-trace-id", "x-zcode-query-source", "x-session-id"].sort(), + ["authorization", "anthropic-version", "content-type", "http-referer", "user-agent", "x-zcode-app-version", "x-title", "x-release-channel", "x-client-language", "x-client-timezone", "x-zcode-agent", "x-platform", "x-os-category", "x-os-version", "x-request-id", "x-zcode-session-type", "x-zcode-trace-id", "x-zcode-query-source", "x-query-id", "x-session-id"].sort(), ) expect(r.headers.accept).not.toBe(CLAUDE_CODE.accept) } @@ -375,7 +378,7 @@ test("a Start Plan body with no model has no powered-by line; a blank system add test("a Start Plan request made as a Request, its body a stream, is dressed too", async () => { const r = await send(start("zai"), JSON.stringify(agentBody), { asRequest: true }) - expect(r.headers["x-title"]).toBe("Z Code@cli") + expect(r.headers["x-title"]).toBe("Z Code@electron") expect(JSON.parse(r.body).system).toEqual(zcodeSystem("zai-api/GLM-5.3-Flash", undefined, AGENT_OWN)) expect(Number(r.headers["content-length"])).toBe(Buffer.byteLength(r.body)) }) @@ -755,3 +758,21 @@ test("a few caps do not hold the Start Plan, and coding plan caps hold nothing", _internal.busyHold.now = () => Date.now() } }) + +// 3.17.2's x-query-id (createModelRequestAttributionHeaders) names the +// user's query: every request of one turn, the tool calls on the way +// among them, carries the same, and what the user says next a new one. +test("x-query-id is the turn's: the same through tool results, new for the next user message", () => { + const q = (messages, sid = "s1") => _internal.queryOf(JSON.stringify({ messages }), sid) + const ask = { role: "user", content: [{ type: "text", text: "fix it" }] } + const call = { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "Bash", input: { command: "ls" } }] } + const result = { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "a.go" }] } + const first = q([ask]) + expect(first).toMatch(UUID) + expect(q([ask, call, result])).toBe(first) + expect(q([ask, call, result, { role: "assistant", content: "done" }, { role: "user", content: "thanks" }])).not.toBe(first) + expect(q([ask], "s2")).not.toBe(first) + // nothing the user said, or a body that doesn't read: none + expect(q([result])).toBe("") + expect(_internal.queryOf("{", "s1")).toBe("") +}) diff --git a/packages/zcode/testdata/client-configs-1107.json b/packages/zcode/testdata/client-configs-1107.json new file mode 100644 index 0000000..68c4cdf --- /dev/null +++ b/packages/zcode/testdata/client-configs-1107.json @@ -0,0 +1 @@ +{"code": 0, "msg": "", "data": {"configs": {"builtin_provider_config_json": "https://cdn-zcode.z.ai/zcode/config/zcode-builtin-production-43.json", "captcha": {"enabled": true, "prefix": "no8xfe", "region": "cn", "sceneId": "11xygtvd", "skip_model_request": true}}}, "logid": "2026110704092358084f882cce978c69bf"}