zcode 0.1.31: ZCode 3.16's key location gives the coding plan its key (#410)
ZCode 3.16.3 on a Mac keeps no coding plan key in credentials.json or
config.json, only a project-key-location:v1 record
({organizationId, projectId, apiKeyId}, encrypted like the rest). With no
key, plansOf sent the account to the gift and the BigModel GLM Coding Plan
never showed (meraki7304).
ownSignIn now reads that record (the account's own: team null, coding
plan, the profile's user id, the family ZCode is on first), and located()
reads the named key's secret from api_keys/copy/{apiKeyId} with the OAuth
token, as ZCode lists keys (BigModel bare, Z.ai as a Bearer). Only GET:
nothing is created. The record's origin is used only when it is an https
z.ai / bigmodel.cn host, else the site's own API. A 404 leaves the sign-in
as before; another failure says sign in again. Request fetch and usage
resolve it before plansOf.
Record format and auth forms read from ZCode 3.16.3's own app.asar
(ProjectAccessTokenClient / project-key-location:v1).
Run: HOME=$(mktemp -d) bun test in packages/zcode, 119 pass;
bun scripts/check.mjs ok.
Red on old code: the new own.test.mjs case fails with the old index.mjs
(key "" and start true).
Not tried: a real ZCode 3.16 account (no vendor credentials used); the
reporter's read-only check of the same endpoints is the evidence.
This commit is contained in:
@@ -1200,6 +1200,86 @@ function configKey(key) {
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ownLocation is where ZCode 3.16 finds the account's own coding plan key
|
||||||
|
// when it keeps none: credentials.json's
|
||||||
|
// project-key-location:v1:<[origin, family, accountId, team, 1, selection]>,
|
||||||
|
// URI-encoded JSON, holds { organizationId, projectId, apiKeyId } (its
|
||||||
|
// ProjectAccessTokenClient). ZCode trades that key for a short-lived
|
||||||
|
// project token each time; here its secret is read (located), as a sign-in
|
||||||
|
// here reads its own key's. The account's own (team null), of the family
|
||||||
|
// ZCode is on first, else Z.ai's, as ZCode lists them; one of another
|
||||||
|
// account the profile names is left alone (meraki7304, #410).
|
||||||
|
const LOCATION = "project-key-location:v1:"
|
||||||
|
function ownLocation(store, key) {
|
||||||
|
const set = readJSON(join(settingDir(), "setting.json"))
|
||||||
|
const fams = set?.providerFamilyDomain === "bigmodel" ? ["bigmodel", "zai"] : ["zai", "bigmodel"]
|
||||||
|
const found = []
|
||||||
|
for (const [name, v] of Object.entries(store)) {
|
||||||
|
if (!name.startsWith(LOCATION)) continue
|
||||||
|
let at
|
||||||
|
try {
|
||||||
|
at = JSON.parse(decodeURIComponent(name.slice(LOCATION.length)))
|
||||||
|
} catch {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (!Array.isArray(at) || at[3] !== null || String(at[4]) !== "1" || !fams.includes(at[1])) continue
|
||||||
|
let loc
|
||||||
|
try {
|
||||||
|
loc = JSON.parse(decrypt(key, v) ?? "")
|
||||||
|
} catch {}
|
||||||
|
const org = first(loc?.organizationId), project = first(loc?.projectId), apiKeyId = first(loc?.apiKeyId)
|
||||||
|
if (!org || !project || !apiKeyId) continue
|
||||||
|
found.push({ site: at[1], origin: typeof at[0] === "string" ? at[0] : "", account: String(at[2] ?? ""), org, project, apiKeyId })
|
||||||
|
}
|
||||||
|
for (const site of fams) {
|
||||||
|
const token = first(decrypt(key, store[`oauth:${site}:access_token`]))
|
||||||
|
if (!token) continue
|
||||||
|
let me = ""
|
||||||
|
try {
|
||||||
|
me = String(JSON.parse(decrypt(key, store[`oauth:${site}:user_info`]) ?? "{}")?.id ?? "")
|
||||||
|
} catch {}
|
||||||
|
const mine = found.filter((l) => l.site === site && (!me || l.account === me))
|
||||||
|
if (!mine.length) continue
|
||||||
|
const l = mine[0]
|
||||||
|
// the origin ZCode asked, when it is the site's own; else the site's API
|
||||||
|
let origin = SITES[site].api
|
||||||
|
try {
|
||||||
|
const u = new URL(l.origin)
|
||||||
|
const h = u.host.toLowerCase()
|
||||||
|
if (u.protocol === "https:" && (site === "zai" ? h === "z.ai" || h.endsWith(".z.ai") : h === "bigmodel.cn" || h.endsWith(".bigmodel.cn"))) origin = u.origin
|
||||||
|
} catch {}
|
||||||
|
return { site, base: SITES[site].base, token, loc: { origin, org: l.org, project: l.project, apiKeyId: l.apiKeyId } }
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
// located gives a sign-in that has only ZCode's key location (ownLocation)
|
||||||
|
// its key: the secret of the key it names, read as ZCode lists the
|
||||||
|
// project's keys (BigModel's token bare, Z.ai's as a Bearer). Nothing is
|
||||||
|
// made: a location whose key is gone (404) leaves the sign-in keyless, as
|
||||||
|
// before; any other failure is said. A key read is kept for the token.
|
||||||
|
const locatedKeys = new Map()
|
||||||
|
async function located(s) {
|
||||||
|
if (!s || s.key || !s.loc || !s.token) return s
|
||||||
|
const l = s.loc
|
||||||
|
const id = [s.token, l.origin, l.org, l.project, l.apiKeyId].join("\0")
|
||||||
|
let got = locatedKeys.get(id)
|
||||||
|
if (!got || (got.err && Date.now() - got.at >= 60_000)) {
|
||||||
|
const auth = s.site === "zai" ? "Bearer " + s.token : s.token
|
||||||
|
try {
|
||||||
|
const secret = first((await call("GET", `${keysURL(l.origin, l.org, l.project)}/copy/${encodeURIComponent(l.apiKeyId)}`, { auth }))?.secretKey)
|
||||||
|
got = secret ? { key: `${l.apiKeyId}.${secret}` } : { err: new Error("no secret for the key") }
|
||||||
|
} catch (e) {
|
||||||
|
got = e?.status === 404 ? { key: "" } : { err: e }
|
||||||
|
}
|
||||||
|
got.at = Date.now()
|
||||||
|
locatedKeys.set(id, got)
|
||||||
|
}
|
||||||
|
if (got.err) throw new Error(`ZCode's ${SITES[s.site].name} coding plan key: ${got.err.message} — sign in to ZCode again`)
|
||||||
|
if (got.key) s.key = got.key
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
// ownSignIn is what ZCode is signed in to now: the account, its coding
|
// ownSignIn is what ZCode is signed in to now: the account, its coding
|
||||||
// plan key, ZCode's session token (the Start Plan's key) and the team plan
|
// plan key, ZCode's session token (the Start Plan's key) and the team plan
|
||||||
// it is switched to; null when it has none of them.
|
// it is switched to; null when it has none of them.
|
||||||
@@ -1220,6 +1300,8 @@ function ownSignIn() {
|
|||||||
// ZCode 3.15 keeps no plan key in its credentials; the one it uses sits
|
// ZCode 3.15 keeps no plan key in its credentials; the one it uses sits
|
||||||
// in config.json, the provider's options.apiKey (yetone/magpie#2130)
|
// in config.json, the provider's options.apiKey (yetone/magpie#2130)
|
||||||
if (!s.key) s = configKey(key) || s
|
if (!s.key) s = configKey(key) || s
|
||||||
|
// ZCode 3.16 keeps neither: only where the key is (#410)
|
||||||
|
if (!s.key) s = ownLocation(store, key) || s
|
||||||
const jwt = first(first(decrypt(key, store.zcodejwttoken)).replace(/^Bearer /, ""))
|
const jwt = first(first(decrypt(key, store.zcodejwttoken)).replace(/^Bearer /, ""))
|
||||||
const team = ownTeam(store, key)
|
const team = ownTeam(store, key)
|
||||||
if (team) s = { ...team, jwt }
|
if (team) s = { ...team, jwt }
|
||||||
@@ -1906,7 +1988,7 @@ export async function ZCodeAuthPlugin({ client }) {
|
|||||||
apiKey: s0.key || "zcode", // the fetch below puts the real one on
|
apiKey: s0.key || "zcode", // the fetch below puts the real one on
|
||||||
async fetch(input, init) {
|
async fetch(input, init) {
|
||||||
const auth = await getAuth()
|
const auth = await getAuth()
|
||||||
const s = stateOf(auth)
|
const s = await located(stateOf(auth))
|
||||||
if (!s) throw new Error("not signed in to ZCode")
|
if (!s) throw new Error("not signed in to ZCode")
|
||||||
let url = input instanceof Request ? input.url : String(input)
|
let url = input instanceof Request ? input.url : String(input)
|
||||||
const opts = input instanceof Request ? { method: input.method, headers: input.headers, body: input.body, signal: input.signal, duplex: "half", ...init } : { ...init }
|
const opts = input instanceof Request ? { method: input.method, headers: input.headers, body: input.body, signal: input.signal, duplex: "half", ...init } : { ...init }
|
||||||
@@ -2048,6 +2130,11 @@ export async function ZCodeAuthPlugin({ client }) {
|
|||||||
const auth = await getAuth()
|
const auth = await getAuth()
|
||||||
const s = stateOf(auth)
|
const s = stateOf(auth)
|
||||||
if (!s) return { error: "not signed in", signIn: "kept" }
|
if (!s) return { error: "not signed in", signIn: "kept" }
|
||||||
|
try {
|
||||||
|
await located(s)
|
||||||
|
} catch (e) {
|
||||||
|
return { error: e.message, signIn: "kept" }
|
||||||
|
}
|
||||||
// every card starts from the plan the sign-in saved, as magpie's
|
// every card starts from the plan the sign-in saved, as magpie's
|
||||||
// built-in did: a reply without a level, a team detail that
|
// built-in did: a reply without a level, a team detail that
|
||||||
// failed or an error keeps it
|
// failed or an error keeps it
|
||||||
@@ -2142,4 +2229,4 @@ export async function ZCodeAuthPlugin({ client }) {
|
|||||||
// config sets what zcodeConfig has read, for tests: null is ZCode's config
|
// config sets what zcodeConfig has read, for tests: null is ZCode's config
|
||||||
// out of reach, undefined forgets it
|
// out of reach, undefined forgets it
|
||||||
const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
|
const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
|
||||||
export const _internal = { config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, dress, PROMPT, marked, keyDevice, sessionOf }
|
export const _internal = { config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, PROMPT, marked, keyDevice, sessionOf }
|
||||||
|
|||||||
@@ -193,3 +193,61 @@ test("the app's sign-in keeps the user id, and follows ZCode by it", async () =>
|
|||||||
zcodeHas({ [KEY]: "id3.secret3", zcodejwttoken: "j3", "oauth:zai:user_info": as("u2") })
|
zcodeHas({ [KEY]: "id3.secret3", zcodejwttoken: "j3", "oauth:zai:user_info": as("u2") })
|
||||||
expect(_internal.stateOf(auth)).toMatchObject({ key: "id1.secret1" })
|
expect(_internal.stateOf(auth)).toMatchObject({ key: "id1.secret1" })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// meraki7304 (#410): ZCode 3.16.3 on a Mac keeps no plan key at all, in
|
||||||
|
// credentials.json or config.json, only where the key is: a
|
||||||
|
// project-key-location:v1 record. The sign-in reads that key, as ZCode lists
|
||||||
|
// it, and the BigModel GLM Coding Plan is found, not only the gift.
|
||||||
|
test("ZCode 3.16's key location gives the coding plan its key", async () => {
|
||||||
|
const loc = (fam, account) =>
|
||||||
|
"project-key-location:v1:" + encodeURIComponent(JSON.stringify(["https://bigmodel.cn", fam, account, null, 1, "non-team"]))
|
||||||
|
zcodeHas(
|
||||||
|
{
|
||||||
|
zcodejwttoken: "Bearer j1",
|
||||||
|
"oauth:bigmodel:access_token": "tok-bm",
|
||||||
|
"oauth:bigmodel:user_info": JSON.stringify({ id: "u7", email: "q@example.com" }),
|
||||||
|
[loc("bigmodel", "u7")]: JSON.stringify({ organizationId: "org7", projectId: "proj7", apiKeyId: "k7" }),
|
||||||
|
// another account's location is left alone
|
||||||
|
[loc("bigmodel", "u8")]: JSON.stringify({ organizationId: "org8", projectId: "proj8", apiKeyId: "k8" }),
|
||||||
|
},
|
||||||
|
{ providerFamilyDomain: "bigmodel" },
|
||||||
|
)
|
||||||
|
const sent = []
|
||||||
|
globalThis.fetch = async (input, init = {}) => {
|
||||||
|
const url = String(input)
|
||||||
|
sent.push([init.method ?? "GET", url, new Headers(init.headers ?? {}).get("authorization")])
|
||||||
|
if (url.includes("/api_keys/copy/k7")) return Response.json({ code: 200, data: { secretKey: "sec7" } })
|
||||||
|
if (url.includes("/api/biz/subscription/list")) return Response.json({ code: 200, data: [{ productName: "GLM Coding Pro", status: "VALID" }] })
|
||||||
|
if (url.includes("/zcode-plan/billing/balance")) return Response.json({ code: 0, data: { plans: [] } })
|
||||||
|
return new Response("{}", { status: 404 })
|
||||||
|
}
|
||||||
|
const hooks = await ZCodeAuthPlugin({ client: {} })
|
||||||
|
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")
|
||||||
|
const auth = { ...got, type: "oauth" }
|
||||||
|
const s = await _internal.located(_internal.stateOf(auth))
|
||||||
|
expect(s).toMatchObject({ key: "k7.sec7", site: "bigmodel", base: "https://open.bigmodel.cn/api/anthropic" })
|
||||||
|
expect(sent[0]).toEqual(["GET", "https://bigmodel.cn/api/biz/v1/organization/org7/projects/proj7/api_keys/copy/k7", "tok-bm"])
|
||||||
|
// nothing is made
|
||||||
|
expect(sent.every(([method]) => method === "GET")).toBe(true)
|
||||||
|
_internal.routes.clear()
|
||||||
|
expect((await _internal.plansOf(s)).start).toBe(false)
|
||||||
|
expect(sent.map(([, u]) => u).join(" ")).not.toContain("k8")
|
||||||
|
|
||||||
|
// a location whose key is gone leaves the sign-in as it was
|
||||||
|
zcodeHas(
|
||||||
|
{
|
||||||
|
zcodejwttoken: "Bearer j1",
|
||||||
|
"oauth:zai:access_token": "tok-z",
|
||||||
|
"oauth:zai:user_info": JSON.stringify({ id: "u9", email: "z@example.com" }),
|
||||||
|
["project-key-location:v1:" + encodeURIComponent(JSON.stringify(["https://evil.example", "zai", "u9", null, 1, "non-team"]))]: JSON.stringify({ organizationId: "o", projectId: "p", apiKeyId: "gone" }),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
sent.length = 0
|
||||||
|
const z = await (await m.authorize()).callback()
|
||||||
|
const zs = await _internal.located(_internal.stateOf({ ...z, type: "oauth" }))
|
||||||
|
expect(zs.key).toBe("")
|
||||||
|
// asked at the site's own API, never the record's foreign origin, as a Bearer
|
||||||
|
expect(sent[0]).toEqual(["GET", "https://api.z.ai/api/biz/v1/organization/o/projects/p/api_keys/copy/gone", "Bearer tok-z"])
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@magpie-community/opencode-zcode-auth",
|
"name": "@magpie-community/opencode-zcode-auth",
|
||||||
"version": "0.1.30",
|
"version": "0.1.31",
|
||||||
"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",
|
"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",
|
"type": "module",
|
||||||
"main": "./index.mjs",
|
"main": "./index.mjs",
|
||||||
|
|||||||
Reference in New Issue
Block a user