zcode 0.1.16: the ZCode app's sign-in follows ZCode only while it is signed in to the same account (LingYi_Stu on X)

The app's sign-in stores the account ZCode is signed in to, and stateOf
read ~/.zcode/v2 again for every request. After ZCode switched to account
B and the app's sign-in was added again, both entries read B's
credentials: A's sent B's requests and its usage card showed B.

stateOf now follows ZCode's own credentials only when ZCode's user is the
entry's accountId. Otherwise (ZCode signed out, or on another account) it
uses the snapshot saved at sign-in, which holds the coding plan key, the
Start Plan JWT, the team project and the device. A snapshot whose JWT has
run out says EXPIRED (sign in again), as a lapsed sign-in already did,
instead of borrowing B's session.

own.test.mjs: two app sign-ins (A, then B) with ZCode on B; A's request
carries A's key and no request (messages, plan, usage) carries B's key or
JWT; and A with only an expired JWT says sign in again without sending
B's. Both fail on 0.1.15 (A sent idB.secretB; the expired case was served
with B's JWT). The first test now keeps the account's user_info as ZCode
signs in again. HOME=$(mktemp -d) bun test packages/zcode: 79 pass.
bun scripts/check.mjs zcode passes.
This commit is contained in:
yetone
2026-10-12 14:41:07 +08:00
parent 7e67b980aa
commit d2be892d70
4 changed files with 88 additions and 9 deletions
+5 -1
View File
@@ -31,7 +31,11 @@ over Anthropic's Messages API. Provider id: `zcode`.
- Uses the account the ZCode app on this computer is signed in to. For
every request it reads ZCode's own credentials (`~/.zcode/v2`), so it
follows ZCode as it signs in again, renews its session or switches to a
team's plan.
team's plan, but only while ZCode is signed in to that same account.
Once ZCode signs out, or signs in to another account, the sign-in uses
what it saved when it was added; when that session has run out, it
asks to be signed in again. It never sends one account's requests with
another's credentials: to use both, add the app's sign-in once for each.
- **GLM Coding Plan API key**
- Paste a key (`<id>.<secret>`) and say which site it is from.
+7 -4
View File
@@ -1044,7 +1044,7 @@ function ownSignIn() {
function asZCode() {
return {
url: "",
instructions: "Uses the account the ZCode app is signed in to, and follows it.",
instructions: "Uses the account the ZCode app is signed in to, and follows it while ZCode stays signed in to that account.",
method: "auto",
async callback() {
const own = ownSignIn()
@@ -1064,10 +1064,13 @@ function stateOf(auth) {
s = JSON.parse(auth.refresh)
} catch {}
if (s.source === "zcode") {
// ZCode's own, read now: what it was when this was signed in, if
// ZCode has since signed out
// ZCode's own, read now, while ZCode is signed in to this same
// account. Signed out, or signed in to another account since, it is
// what it was when this was signed in: another account's key would
// send this account's requests as that one, and an expired session
// says sign in again (EXPIRED) rather than borrowing another's.
const own = ownSignIn()
if (own) {
if (own && own.user === String(auth.accountId ?? "")) {
const { user, ...now } = own
s = { source: "zcode", device: s.device, plan: s.plan, ...now }
}
+75 -3
View File
@@ -2,7 +2,7 @@
// (internal/provider/zcode.go zcodeOwn, zcode_team.go zcodeOwnTeam), and
// follows it: a request made after ZCode switched to a team's plan, or
// signed in anew, uses what ZCode has now.
import { test, expect, beforeAll } from "bun:test"
import { test, expect, beforeAll, afterEach } from "bun:test"
import { homedir, tmpdir } from "node:os"
import { mkdirSync, realpathSync, writeFileSync } from "node:fs"
import { createCipheriv, createHash, randomBytes } from "node:crypto"
@@ -43,12 +43,13 @@ test("the sign-in takes ZCode's account and key, and follows ZCode after", async
expect(_internal.stateOf(auth)).toMatchObject({ key: "id1.secret1", jwt: "j1", base: "https://api.z.ai/api/anthropic" })
// ZCode signs in again with a new key
zcodeHas({ [KEY]: "id2.secret2", zcodejwttoken: "j2" })
const ada = JSON.stringify({ email: "ada@phone.local" })
zcodeHas({ [KEY]: "id2.secret2", zcodejwttoken: "j2", "oauth:zai:user_info": ada })
expect(_internal.stateOf(auth)).toMatchObject({ key: "id2.secret2", jwt: "j2" })
// and switches to a team's plan
zcodeHas(
{ [KEY]: "id2.secret2", zcodejwttoken: "j2", "oauth:zai:access_token": "tok-team" },
{ [KEY]: "id2.secret2", zcodejwttoken: "j2", "oauth:zai:access_token": "tok-team", "oauth:zai:user_info": ada },
{ providerFamilyConnectionSelections: { zai: { kind: "team-coding-plan", organizationId: "org1", projectId: "p1" } } },
)
expect(_internal.stateOf(auth)).toMatchObject({ key: "", token: "tok-team", org: "org1", project: "p1", jwt: "j2" })
@@ -68,3 +69,74 @@ test("a sign-in not ZCode's keeps its own key", () => {
const s = _internal.stateOf({ type: "oauth", access: "mine.k", refresh: JSON.stringify({ site: "zai", key: "mine.k" }) })
expect(s.key).toBe("mine.k")
})
// LingYi_Stu on X: the app's sign-in added for A, then again after ZCode
// switched to B, is two accounts. A's entry follows ZCode only while ZCode
// is signed in to A; with ZCode on B it is what A's sign-in saved, never B's.
const real = globalThis.fetch
afterEach(() => (globalThis.fetch = real))
const expiredJWT = ["{}", JSON.stringify({ exp: Math.floor(Date.now() / 1000) - 60 })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig"
async function appSignIn() {
const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } })
const m = hooks.auth.methods.find((x) => x.label === "ZCode app's sign-in")
const got = await (await m.authorize()).callback()
expect(got.type).toBe("success")
return { ...got, type: "oauth" }
}
test("an app sign-in for A doesn't send with B's key once ZCode is signed in to B", async () => {
zcodeHas({ [KEY]: "idA.secretA", zcodejwttoken: "Bearer jA", "oauth:zai:user_info": JSON.stringify({ email: "alice@x.local" }) })
const a = await appSignIn()
zcodeHas({ [KEY]: "idB.secretB", zcodejwttoken: "Bearer jB", "oauth:zai:user_info": JSON.stringify({ email: "bob@x.local" }) })
const b = await appSignIn()
expect([a.accountId, b.accountId]).toEqual(["alice@x.local", "bob@x.local"])
expect(_internal.stateOf(a)).toMatchObject({ key: "idA.secretA", jwt: "jA" })
expect(_internal.stateOf(b)).toMatchObject({ key: "idB.secretB", jwt: "jB" })
_internal.routes?.clear?.()
const sent = []
globalThis.fetch = async (input, init = {}) => {
const url = new URL(input instanceof Request ? input.url : String(input))
sent.push({ path: url.pathname, headers: Object.fromEntries(new Headers(init.headers ?? {})) })
if (url.pathname === "/api/biz/subscription/list") return new Response(JSON.stringify({ code: 0, data: [{ productName: "GLM Coding Pro", status: "VALID" }] }))
if (url.pathname === "/api/monitor/usage/quota/limit") return new Response(JSON.stringify({ code: 0, data: { limits: [] } }))
return new Response(JSON.stringify({ type: "message", content: [] }), { headers: { "content-type": "application/json" } })
}
const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } })
const opts = await hooks.auth.loader(async () => a, { id: "zcode" })
const res = await opts.fetch("https://api.z.ai/api/anthropic/v1/messages", {
method: "POST",
headers: { "content-type": "application/json", "x-api-key": "zcode" },
body: JSON.stringify({ model: "glm-5.1", max_tokens: 10, messages: [{ role: "user", content: "hi" }] }),
})
expect(res.status).toBe(200)
await hooks.auth.usage?.(async () => a, { id: "zcode" }).catch(() => {})
const msg = sent.find((c) => c.path === "/api/anthropic/v1/messages")
expect(msg.headers["x-api-key"]).toBe("idA.secretA")
const all = JSON.stringify(sent)
expect(all).not.toContain("secretB")
expect(all).not.toContain("jB")
})
test("an app sign-in for A whose saved session has lapsed, with ZCode on B, says sign in again", async () => {
zcodeHas({ zcodejwttoken: "Bearer " + expiredJWT, "oauth:zai:user_info": JSON.stringify({ email: "alice@x.local" }) })
const a = await appSignIn()
zcodeHas({ zcodejwttoken: "Bearer jB-live", "oauth:zai:user_info": JSON.stringify({ email: "bob@x.local" }) })
expect(_internal.stateOf(a).jwt).toBe(expiredJWT)
_internal.routes?.clear?.()
const sent = []
globalThis.fetch = async (input, init = {}) => {
sent.push(JSON.stringify(Object.fromEntries(new Headers(init.headers ?? {}))))
return new Response("{}", { status: 500 })
}
const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } })
const opts = await hooks.auth.loader(async () => a, { id: "zcode" })
const err = await opts
.fetch("https://api.z.ai/api/anthropic/v1/messages", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model: "glm-5.1", messages: [] }) })
.then(() => null, (e) => e)
expect(err?.message).toContain("sign in")
expect(sent.join("")).not.toContain("jB-live")
})
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-zcode-auth",
"version": "0.1.15",
"version": "0.1.16",
"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",
"type": "module",
"main": "./index.mjs",