From 8c7e31911e1f12da2c64be08a52ac592d242f074 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 2 Oct 2026 18:30:00 +0800 Subject: [PATCH] qoder: Qoder CN (qoder.cn) as a second provider, qoder-cn (#1) (#4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hosts, client id and paths read from Qoder CN's own CLI (@qodercn-ai/qoderclicn 1.1.65): sign-in on qoder.cn, accounts on openapi.qoder.com.cn, models and chat on gateway.qoder.com.cn, client id e883ade2-…; signing unchanged. The same as magpie's built-in Qoder CN. When qoder.cn refuses a job token the account chats on its device token, renewed through /api/v1/deviceToken/refresh, as the CN CLI does. cn.test.mjs (12 tests, a local server standing in for every host) covers sign-in, polling, both tokens' refresh, a chat, models, usage and qoder.com unchanged; 6 fail with the CN chat host pointed back at api3.qoder.sh or the fallback off. Version 0.2.0. --- README.md | 3 +- packages/qoder/README.md | 51 +++++- packages/qoder/cn.test.mjs | 299 ++++++++++++++++++++++++++++++++++++ packages/qoder/index.mjs | 201 ++++++++++++++++-------- packages/qoder/package.json | 6 +- registry.json | 4 +- 6 files changed, 495 insertions(+), 69 deletions(-) create mode 100644 packages/qoder/cn.test.mjs diff --git a/README.md b/README.md index 68786dd..205c54a 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,8 @@ subscription and makes its requests. The packages work in OpenCode and in | [grok](packages/grok) | Grok (SuperGrok / X Premium+), through the Grok Build CLI's sign-in | `grok` | | [kiro](packages/kiro) | Kiro (Free, Pro, Pro+, Power), with Kiro's sign-in, kiro-cli's or the IDE's, or an API key | `kiro` | | [mimo](packages/mimo) | Xiaomi MiMo, with a Xiaomi account | `mimo-app` | -| [qoder](packages/qoder) | Qoder subscription, with Qoder's device sign-in | `qoder` | +| [qoder](packages/qoder) | Qoder subscription (qoder.com), with Qoder's device sign-in | `qoder` | +| [qoder](packages/qoder) | Qoder CN subscription (qoder.cn), with Qoder CN's device sign-in | `qoder-cn` | | [workbuddy](packages/workbuddy) | WorkBuddy (China build, CodeBuddy plan) | `workbuddy` | | [workbuddy](packages/workbuddy) | WorkBuddy (international build) | `workbuddy-ai` | | [zcode](packages/zcode) | ZCode: Z.ai / BigModel (智谱) GLM Coding Plan, team seats | `zcode` | diff --git a/packages/qoder/README.md b/packages/qoder/README.md index 1dfb43e..380833f 100644 --- a/packages/qoder/README.md +++ b/packages/qoder/README.md @@ -1,7 +1,16 @@ # @magpie-community/opencode-qoder-auth Your [Qoder](https://qoder.com) subscription in OpenCode and -[magpie](https://usemagpie.ai), with provider id `qoder`. +[magpie](https://usemagpie.ai). The package serves Qoder's two sites, whose +accounts exist only on their own: + +| Provider id | Site | Accounts | Plugin export | +|---|---|---|---| +| `qoder` | qoder.com (international) | Google, GitHub or email | `QoderAuthPlugin` | +| `qoder-cn` | qoder.cn ([Qoder CN](#qoder-cn)) | Alibaba Cloud or phone number | `QoderCNAuthPlugin` | + +What follows is about `qoder`. Qoder CN works the same way on its own +hosts; [its section](#qoder-cn) says what differs. ## Sign-in @@ -83,6 +92,46 @@ The `config` hook declares the list as it was on 2026-09-30: Every model speaks chat completions (`@ai-sdk/openai-compatible`). +## Qoder CN + +`qoder-cn` is for accounts on [qoder.cn](https://qoder.cn), the China site. +Those accounts sign in with Alibaba Cloud or a phone number and can't sign +in through `qoder`. Qoder CN speaks the same protocol as qoder.com: + +- the same device flow, poll, job token and refresh paths; +- the same COSY envelope and body codec; +- the same model list, chat and usage paths. + +Only the hosts and the sign-in's client id differ. The plugin uses the ones +Qoder CN's own CLI builds in for its `cn` build (`@qodercn-ai/qoderclicn` +1.1.65): + +| | `qoder` | `qoder-cn` | +|---|---|---| +| Sign-in page | qoder.com | qoder.cn | +| Accounts: poll, tokens, user info, usage | openapi.qoder.sh | openapi.qoder.com.cn | +| Models and chat | api3.qoder.sh | gateway.qoder.com.cn | +| Device-flow client id | Qoder's desktop client's | Qoder CN's CLI's (production) | +| `redirect_uri` on the sign-in page | `qoder-app://` | none, as the CLI sends | + +Qoder CN's CLI chats with the device token itself and never makes a job +token. The plugin asks qoder.cn for a job token first, as it does on +qoder.com. If qoder.cn refuses it (a 4xx), the account works the way the +CLI does: + +- the device token signs the model calls; +- it is renewed with `/api/v1/deviceToken/refresh`, the chat and account + tokens being one pair; +- a refused renewal (401 or 403) means signing in again. + +Until you sign in, the `config` hook declares the tiers Qoder CN's CLI names +(Ultimate, Performance, Efficient, Lite). Once you are signed in, the +account's own list from gateway.qoder.com.cn replaces them. + +Neither magpie's built-in Qoder CN nor this plugin has been checked against +every kind of qoder.cn account. If a sign-in or a chat fails, please open +an issue with the error. + ## Not here - Qoder's usage and quota display. diff --git a/packages/qoder/cn.test.mjs b/packages/qoder/cn.test.mjs new file mode 100644 index 0000000..51a433a --- /dev/null +++ b/packages/qoder/cn.test.mjs @@ -0,0 +1,299 @@ +// Qoder CN (qoder-cn) against a local stand-in for its hosts: every request +// the plugin makes is sent to a Bun.serve server instead, which sees the +// host it was meant for, so each test says which of Qoder CN's hosts a call +// went to — the sign-in page on qoder.cn, accounts on openapi.qoder.com.cn, +// models on gateway.qoder.com.cn — and that none went to qoder.com's. +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test" +import { createHash } from "node:crypto" +import { QoderAuthPlugin, QoderCNAuthPlugin, _internal } from "./index.mjs" + +const CN_CLIENT = "e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb" +const OPENAPI = "openapi.qoder.com.cn" +const GATEWAY = "gateway.qoder.com.cn" + +let server +let route = () => new Response("", { status: 404 }) +let seen = [] +const real = globalThis.fetch + +beforeAll(() => { + server = Bun.serve({ + port: 0, + async fetch(req) { + const u = new URL(req.url) + const host = req.headers.get("x-qoder-host") + const body = req.method === "GET" ? "" : await req.text() + seen.push({ host, path: u.pathname, query: u.searchParams, method: req.method, headers: req.headers, body }) + return route(host + u.pathname, { req, url: u, body }) + }, + }) +}) +afterAll(() => server.stop(true)) + +// every fetch goes to the stand-in, carrying the host it was meant for +const toServer = () => { + globalThis.fetch = async (input, init = {}) => { + const u = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url) + const headers = new Headers(init.headers) + headers.set("x-qoder-host", u.host) + return real(`http://127.0.0.1:${server.port}${u.pathname}${u.search}`, { ...init, headers }) + } +} +afterEach(() => { + globalThis.fetch = real + route = () => new Response("", { status: 404 }) + seen = [] +}) + +const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json" } }) + +function store(initial) { + let auth = initial + const saved = [] + return { + client: { auth: { set: async ({ path, body }) => (saved.push(path.id), (auth = body)) } }, + get: async () => auth, + auth: () => auth, + saved, + } +} + +const hostsOf = () => [...new Set(seen.map((s) => s.host))] + +test("the sign-in page is qoder.cn's, with Qoder CN's CLI client id and no redirect", async () => { + const hooks = await QoderCNAuthPlugin({ client: store().client }) + expect(hooks.auth.provider).toBe("qoder-cn") + expect(hooks.auth.methods[0].label).toBe("Sign in with Qoder CN") + const flow = await hooks.auth.methods[0].authorize() + const u = new URL(flow.url) + expect(u.origin + u.pathname).toBe("https://qoder.cn/device/selectAccounts") + expect(u.searchParams.get("client_id")).toBe(CN_CLIENT) + expect(u.searchParams.get("challenge_method")).toBe("S256") + expect(u.searchParams.has("redirect_uri")).toBe(false) + for (const k of ["challenge", "nonce", "machine_id"]) expect(u.searchParams.get(k)).toBeTruthy() +}) + +test("qoder.com's sign-in is as it was", async () => { + const flow = await (await QoderAuthPlugin({ client: store().client })).auth.methods[0].authorize() + const u = new URL(flow.url) + expect(u.origin + u.pathname).toBe("https://qoder.com/device/selectAccounts") + expect(u.searchParams.get("client_id")).toBe("732aef47-9cf2-46a2-95fe-4cebb5d0d1fa") + expect(u.searchParams.get("redirect_uri")).toBe("qoder-app://") +}) + +test("the sign-in polls openapi.qoder.com.cn until authorized, then makes a job token there", async () => { + toServer() + let polls = 0 + route = (at, { url, body, req }) => { + if (at === OPENAPI + "/api/v1/deviceToken/poll") { + expect(url.searchParams.get("challenge_method")).toBe("S256") + expect(url.searchParams.get("verifier")).toBeTruthy() + return ++polls < 2 ? new Response("", { status: 404 }) : json({ token: "dt-cn", refresh_token: "drt-cn", user_id: "u-cn", user_name: "阿里云用户" }) + } + if (at === OPENAPI + "/api/v1/me/jobToken") { + expect(req.headers.get("authorization")).toBe("Bearer dt-cn") + expect(JSON.parse(body)).toEqual({ clientId: CN_CLIENT }) + return json({ token: "jt-cn", refresh_token: "jrt-cn", expires_in: 3_600_000 }) + } + if (at === OPENAPI + "/api/v1/userinfo") return json({ email: "", name: "" }) + return new Response("", { status: 404 }) + } + const hooks = await QoderCNAuthPlugin({ client: store().client }) + const flow = await hooks.auth.methods[0].authorize() + const nonce = new URL(flow.url).searchParams.get("nonce") + const cred = await flow.callback() + expect(polls).toBe(2) + expect(seen[0].query.get("nonce")).toBe(nonce) + expect(cred).toMatchObject({ type: "success", access: "jt-cn", refresh: "jrt-cn", uid: "u-cn", accountId: "u-cn", name: "阿里云用户", deviceToken: "dt-cn", deviceRefresh: "drt-cn" }) + expect(cred.deviceChat).toBeUndefined() + expect(cred.machineId).toBe(new URL(flow.url).searchParams.get("machine_id")) + expect(hostsOf()).toEqual([OPENAPI]) +}, 10_000) + +test("a job token qoder.cn refuses leaves the account chatting on its device token, as Qoder CN's CLI does", async () => { + toServer() + route = (at) => { + if (at === OPENAPI + "/api/v1/deviceToken/poll") return json({ token: "dt-cn", refresh_token: "drt-cn", user_id: "u-cn", expires_in: 7200 }) + if (at === OPENAPI + "/api/v1/me/jobToken") return json({ message: "client not allowed" }, 403) + if (at === OPENAPI + "/api/v1/userinfo") return json({ email: "cn@x", name: "CN" }) + return new Response("", { status: 404 }) + } + const flow = await (await QoderCNAuthPlugin({ client: store().client })).auth.methods[0].authorize() + const cred = await flow.callback() + expect(cred).toMatchObject({ access: "dt-cn", refresh: "drt-cn", deviceChat: true, accountId: "cn@x", deviceToken: "dt-cn", deviceRefresh: "drt-cn" }) + expect(Math.abs(cred.expires - (Date.now() + 7_200_000))).toBeLessThan(5_000) +}) + +test("qoder.com's sign-in still fails on a refused job token", async () => { + toServer() + route = (at) => { + if (at === "openapi.qoder.sh/api/v1/deviceToken/poll") return json({ token: "dt", refresh_token: "drt", user_id: "u" }) + if (at === "openapi.qoder.sh/api/v1/me/jobToken") return json({ message: "no" }, 403) + return new Response("", { status: 404 }) + } + const flow = await (await QoderAuthPlugin({ client: store().client })).auth.methods[0].authorize() + await expect(flow.callback()).rejects.toThrow("Qoder job token: status 403") +}) + +const MODEL = { + key: "performance", + display_name: "Performance", + enable: true, + source: "system", + max_input_tokens: 1_000_000, + is_vl: true, + thinking_config: { enabled: { efforts: { low: {}, medium: { is_default: true }, high: {} } }, disabled: {} }, +} + +const sse = (...chunks) => + new Response(chunks.map((c) => `data: ${JSON.stringify({ statusCodeValue: 200, body: JSON.stringify(c) })}\n\n`).join(""), { + headers: { "Content-Type": "text/event-stream" }, + }) + +// chatServer answers the model list and a chat on gateway.qoder.com.cn, +// checking the COSY signature over the body as it arrived +const chatServer = (machines, refresh) => (at, { req, body, url }) => { + if (refresh) { + const r = refresh(at, body) + if (r) return r + } + if (at === GATEWAY + "/algo/api/v2/model/list") return json({ chat: [MODEL, { key: "auto", enable: true }] }) + if (at === GATEWAY + "/algo/api/v2/service/pro/sse/agent_chat_generation") { + expect(url.searchParams.get("Encode")).toBe("1") + const auth = req.headers.get("authorization") + const [, payload, sig] = auth.match(/^Bearer COSY\.([^.]+)\.([0-9a-f]{32})$/) + const path = url.pathname.slice("/algo".length) + const want = createHash("md5").update(`${payload}\n${req.headers.get("cosy-key")}\n${req.headers.get("cosy-date")}\n${body}\n${path}`).digest("hex") + expect(sig).toBe(want) + expect(req.headers.get("cosy-user")).toBe("u-cn") + expect(req.headers.get("x-model-key")).toBe("performance") + const q = JSON.parse(_internal.decodeBody(body)) + expect(q.model_config.key).toBe("performance") + expect(q.parameters.reasoning_effort).toBe("high") + expect(q.messages.at(-1)).toEqual({ role: "user", content: [{ type: "text", text: "你好" }] }) + machines.push(req.headers.get("cosy-machineid")) + return sse( + { choices: [{ delta: { reasoning_content: "想想" } }] }, + { choices: [{ delta: { content: "你好!" } }] }, + { choices: [{ delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 3, completion_tokens: 2 } }, + ) + } + return new Response("", { status: 404 }) +} + +const signedIn = (over = {}) => ({ + type: "oauth", + access: "jt-cn", + refresh: "jrt-cn", + expires: Date.now() + 3_600_000, + accountId: "cn@x", + uid: "u-cn", + machineId: "m-cn", + deviceToken: "dt-cn", + deviceRefresh: "drt-cn", + ...over, +}) + +const chat = { model: "performance", reasoning_effort: "high", messages: [{ role: "user", content: "你好" }] } + +test("a chat goes to gateway.qoder.com.cn, signed and encoded as Qoder's client does", async () => { + toServer() + const machines = [] + route = chatServer(machines) + const s = store(signedIn()) + const hooks = await QoderCNAuthPlugin({ client: s.client }) + const opts = await hooks.auth.loader(s.get) + expect(opts.baseURL).toBe("https://gateway.qoder.com.cn") + const res = await opts.fetch("https://gateway.qoder.com.cn/chat/completions", { method: "POST", body: JSON.stringify(chat) }) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + const out = await res.json() + expect(out.choices[0]).toEqual({ index: 0, message: { role: "assistant", content: "你好!", reasoning_content: "想想" }, finish_reason: "stop" }) + expect(out.usage).toEqual({ prompt_tokens: 3, completion_tokens: 2, total_tokens: 5 }) + expect(machines).toEqual(["m-cn"]) + expect(hostsOf()).toEqual([GATEWAY]) + expect(seen.map((x) => x.path)).toEqual(["/algo/api/v2/model/list", "/algo/api/v2/service/pro/sse/agent_chat_generation"]) + expect(s.saved).toEqual([]) +}) + +test("a job token near its end is refreshed on openapi.qoder.com.cn and saved under qoder-cn before the chat", async () => { + toServer() + const refresh = (at, body) => { + if (at !== OPENAPI + "/api/v1/jobToken/refresh") return null + expect(JSON.parse(body)).toEqual({ refresh_token: "jrt-cn" }) + return json({ token: "jt-cn-2", refresh_token: "jrt-cn-2", expires_in: 3_600_000 }) + } + route = chatServer([], refresh) + const s = store(signedIn({ expires: Date.now() + 60_000 })) + const opts = await (await QoderCNAuthPlugin({ client: s.client })).auth.loader(s.get) + const res = await opts.fetch("https://gateway.qoder.com.cn/chat/completions", { method: "POST", body: JSON.stringify({ ...chat, stream: true }) }) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed") + const text = await res.text() + expect(text).toContain('"content":"你好!"') + expect(text.trim().endsWith("data: [DONE]")).toBe(true) + expect(s.saved).toEqual(["qoder-cn"]) + expect(s.auth()).toMatchObject({ access: "jt-cn-2", refresh: "jrt-cn-2", deviceToken: "dt-cn" }) + expect(hostsOf()).toEqual([OPENAPI, GATEWAY]) +}) + +test("a device-token account is renewed as a device token on openapi.qoder.com.cn, both pairs as one", async () => { + toServer() + const refresh = (at, body) => { + if (at === OPENAPI + "/api/v1/jobToken/refresh") throw new Error("a device-token account made a job refresh") + if (at !== OPENAPI + "/api/v1/deviceToken/refresh") return null + expect(JSON.parse(body)).toEqual({ refresh_token: "drt-cn" }) + return json({ device_token: "dt-cn-2", refresh_token: "drt-cn-2", expires_at: new Date(Date.now() + 7_200_000).toISOString() }) + } + route = chatServer([], refresh) + const s = store(signedIn({ access: "dt-cn", refresh: "drt-cn", deviceChat: true, expires: Date.now() + 60_000 })) + const opts = await (await QoderCNAuthPlugin({ client: s.client })).auth.loader(s.get) + const res = await opts.fetch("https://gateway.qoder.com.cn/chat/completions", { method: "POST", body: JSON.stringify(chat) }) + expect(res.status).toBe(200) + expect(s.auth()).toMatchObject({ access: "dt-cn-2", refresh: "drt-cn-2", deviceToken: "dt-cn-2", deviceRefresh: "drt-cn-2", deviceChat: true }) + expect(s.auth().expires).toBeGreaterThan(Date.now() + 7_000_000) + expect(seen.map((x) => x.host + x.path)).toEqual([OPENAPI + "/api/v1/deviceToken/refresh", GATEWAY + "/algo/api/v2/model/list", GATEWAY + "/algo/api/v2/service/pro/sse/agent_chat_generation"]) +}) + +test("a device-token account whose refresh qoder.cn refuses is signed out, marked expired", async () => { + toServer() + route = (at) => (at === OPENAPI + "/api/v1/deviceToken/refresh" ? new Response("", { status: 401 }) : new Response("", { status: 404 })) + const s = store(signedIn({ access: "dt-cn", refresh: "drt-cn", deviceChat: true, expires: Date.now() + 60_000 })) + const opts = await (await QoderCNAuthPlugin({ client: s.client })).auth.loader(s.get) + const res = await opts.fetch("https://gateway.qoder.com.cn/chat/completions", { method: "POST", body: JSON.stringify(chat) }) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") + expect((await res.json()).error.message).toContain("Qoder CN sign-in has expired") +}) + +test("the account's list is read from gateway.qoder.com.cn as qoder-cn's models", async () => { + toServer() + route = chatServer([]) + const hooks = await QoderCNAuthPlugin({ client: store().client }) + const ms = await hooks.provider.models({ models: {} }, { auth: signedIn() }) + expect(Object.keys(ms)).toEqual(["performance"]) + expect(ms.performance).toMatchObject({ providerID: "qoder-cn", api: { url: "https://gateway.qoder.com.cn" }, variants: { low: {}, medium: {}, high: {} } }) + expect(hostsOf()).toEqual([GATEWAY]) +}) + +test("usage is read from openapi.qoder.com.cn with the device token", async () => { + toServer() + route = (at, { req }) => { + if (at !== OPENAPI + "/sash/api/v2/me/usage") return new Response("", { status: 404 }) + expect(req.headers.get("authorization")).toBe("Bearer dt-cn") + return json({ displayMode: "qoder", qoderUsage: { userType: "pro", userQuota: { total: 100, used: 40 } } }) + } + const s = store(signedIn()) + const hooks = await QoderCNAuthPlugin({ client: s.client }) + expect(await hooks.auth.usage(s.get)).toEqual({ plan: "pro", windows: [{ name: "Credits", used: 40, display: "40 / 100 credits" }], signIn: "kept" }) +}) + +test("the config declares qoder-cn on its gateway, with the tiers Qoder CN's CLI names", async () => { + const cfg = { provider: {} } + await (await QoderCNAuthPlugin({ client: store().client })).config(cfg) + await (await QoderAuthPlugin({ client: store().client })).config(cfg) + expect(cfg.provider["qoder-cn"]).toMatchObject({ name: "Qoder CN", npm: "@ai-sdk/openai-compatible", api: "https://gateway.qoder.com.cn" }) + expect(Object.keys(cfg.provider["qoder-cn"].models)).toEqual(["ultimate", "performance", "efficient", "lite"]) + expect(cfg.provider.qoder.api).toBe("https://api3.qoder.sh") + expect(Object.keys(cfg.provider.qoder.models)).toContain("qmodel") +}) diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index 503a645..bc8f461 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -1,4 +1,7 @@ -// Qoder's subscription (qoder.com) as an OpenCode provider plugin. +// Qoder's subscriptions as OpenCode provider plugins, one for each of its +// sites, whose accounts exist only on their own: +// - qoder: the international site, qoder.com +// - qoder-cn: Qoder CN, qoder.cn (Alibaba Cloud or phone sign-in) // // Qoder is signed in to the way its desktop client is: a PKCE device flow // (qoder.com's page, then a poll of openapi.qoder.sh for the device token), @@ -15,17 +18,18 @@ // The protocol (endpoints, COSY envelope, body codec, device flow) is ported // from magpie's internal/qoder, which ported it from CLIProxyAPI's qoder // support (https://github.com/ufec/CLIProxyAPI, MIT). +// +// Qoder CN speaks the same protocol on its own hosts, as Qoder CN's CLI +// (@qodercn-ai/qoderclicn 1.1.65) builds them in for its "cn" build: the +// sign-in page on qoder.cn, accounts on openapi.qoder.com.cn and models on +// gateway.qoder.com.cn, with the device-flow client id that CLI sends in +// production and no redirect_uri. That CLI chats on the device token itself; +// if qoder.cn won't trade it for a job token, the account does the same. import { createCipheriv, createHash, publicEncrypt, randomBytes, randomUUID, constants } from "node:crypto" import { STATUS_CODES } from "node:http" -const ID = "qoder" -const CLIENT_ID = "732aef47-9cf2-46a2-95fe-4cebb5d0d1fa" -const DEVICE_HOST = "https://qoder.com" -const OPENAPI = "https://openapi.qoder.sh" -const API = "https://api3.qoder.sh" -const REDIRECT = "qoder-app://" -const CHAT_URL = API + "/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1" -const MODELS_URL = API + "/algo/api/v2/model/list?Encode=1" +const CHAT_PATH = "/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1" +const MODELS_PATH = "/algo/api/v2/model/list?Encode=1" const COSY_VERSION = "1.1.49" const SIGN_IN_TIMEOUT = 15 * 60 * 1000 const REFRESH_LEAD = 5 * 60 * 1000 @@ -145,8 +149,8 @@ function decodeBody(wire) { const b64url = (buf) => buf.toString("base64url") -async function openapi(path, { method = "GET", token, body, query } = {}) { - const url = new URL(OPENAPI + path) +async function openapi(site, path, { method = "GET", token, body, query } = {}) { + const url = new URL(site.openapi + path) for (const [k, v] of Object.entries(query ?? {})) url.searchParams.set(k, v) const headers = { Accept: "application/json" } if (body) headers["Content-Type"] = "application/json" @@ -164,23 +168,34 @@ async function openapi(path, { method = "GET", token, body, query } = {}) { // runs out; a day when it said none. const expiresAt = (jt) => Date.now() + (jt.expires_in > 0 ? jt.expires_in : DAY) -async function deviceSignIn() { +// deviceExpiry is when a device token used for chat runs out: its +// expires_at (a date) or expires_in (seconds), as Qoder's CLI reads it; a +// day when it said neither. +function deviceExpiry(dt) { + const at = Date.parse(String(dt?.expires_at ?? "").trim()) + if (!isNaN(at)) return at + if (dt?.expires_in > 0) return Date.now() + dt.expires_in * 1000 + return Date.now() + DAY +} + +async function deviceSignIn(site) { const verifier = b64url(randomBytes(64)) const challenge = b64url(createHash("sha256").update(verifier).digest()) const nonce = randomUUID() const machineId = randomUUID() - const q = new URLSearchParams({ challenge, challenge_method: "S256", nonce, machine_id: machineId, client_id: CLIENT_ID, redirect_uri: REDIRECT }) + const q = new URLSearchParams({ challenge, challenge_method: "S256", nonce, machine_id: machineId, client_id: site.clientId }) + if (site.redirect) q.set("redirect_uri", site.redirect) const until = Date.now() + SIGN_IN_TIMEOUT return { - url: `${DEVICE_HOST}/device/selectAccounts?${q}`, - instructions: "Sign in to Qoder in the browser and authorize this device", + url: `${site.web}/device/selectAccounts?${q}`, + instructions: `Sign in to ${site.name} in the browser and authorize this device`, method: "auto", async callback() { let dt for (;;) { - if (Date.now() > until) throw new Error("Qoder: the sign-in timed out; start again") + if (Date.now() > until) throw new Error(`${site.name}: the sign-in timed out; start again`) try { - const r = await openapi("/api/v1/deviceToken/poll", { query: { nonce, verifier, challenge_method: "S256" } }) + const r = await openapi(site, "/api/v1/deviceToken/poll", { query: { nonce, verifier, challenge_method: "S256" } }) if (r.status === 200 && String(r.json?.token ?? "").trim()) { dt = r.json break @@ -188,24 +203,29 @@ async function deviceSignIn() { } catch {} // a hiccup: ask again await new Promise((r) => setTimeout(r, 2000)) } - const jr = await openapi("/api/v1/me/jobToken", { method: "POST", token: dt.token, body: { clientId: CLIENT_ID } }) - if (jr.status !== 200) throw new Error(`Qoder job token: status ${jr.status}: ${jr.text.trim().slice(0, 300)}`) - if (!String(jr.json?.token ?? "").trim()) throw new Error("Qoder job token: empty token in response") + const jr = await openapi(site, "/api/v1/me/jobToken", { method: "POST", token: dt.token, body: { clientId: site.clientId } }) + let chat + if (jr.status === 200) { + if (!String(jr.json?.token ?? "").trim()) throw new Error(`${site.name} job token: empty token in response`) + chat = { access: jr.json.token, refresh: jr.json.refresh_token ?? "", expires: expiresAt(jr.json) } + } else if (site.deviceChat && jr.status >= 400 && jr.status < 500) { + // Qoder CN's CLI never makes a job token: its device token is what + // signs the model calls, renewed as a device token + chat = { access: dt.token, refresh: dt.refresh_token ?? "", expires: deviceExpiry(dt), deviceChat: true } + } else throw new Error(`${site.name} job token: status ${jr.status}: ${jr.text.trim().slice(0, 300)}`) let email = "" let name = "" try { - const ui = await openapi("/api/v1/userinfo", { token: dt.token }) + const ui = await openapi(site, "/api/v1/userinfo", { token: dt.token }) if (ui.status >= 200 && ui.status < 300) [email, name] = [ui.json?.email ?? "", ui.json?.name ?? ""] } catch {} return { type: "success", - access: jr.json.token, - refresh: jr.json.refresh_token ?? "", - expires: expiresAt(jr.json), + ...chat, accountId: email || dt.user_id, uid: dt.user_id, email, - name, + name: name || dt.user_name || "", machineId, deviceToken: dt.token, deviceRefresh: dt.refresh_token ?? "", @@ -227,11 +247,11 @@ class SignInGone extends Error { // refreshJob trades the job token's refresh token for a new pair; the old // one is spent. -async function refreshJob(refresh, user) { - if (!String(refresh ?? "").trim()) throw new SignInGone("Qoder: the sign-in lapsed; sign in again") - const r = await openapi("/api/v1/jobToken/refresh", { method: "POST", body: { refresh_token: refresh } }) +async function refreshJob(site, refresh, user) { + if (!String(refresh ?? "").trim()) throw new SignInGone(`${site.name}: the sign-in lapsed; sign in again`) + const r = await openapi(site, "/api/v1/jobToken/refresh", { method: "POST", body: { refresh_token: refresh } }) if (r.status === 401 || r.status === 403) - throw new SignInGone(`${user}'s Qoder sign-in has expired — sign in again (qoder job token refresh: status ${r.status})`, true) + throw new SignInGone(`${user}'s ${site.name} sign-in has expired — sign in again (qoder job token refresh: status ${r.status})`, true) if (r.status !== 200) throw new Error(`qoder job token refresh: status ${r.status}`) if (!String(r.json?.token ?? "").trim() || !String(r.json?.refresh_token ?? "").trim()) throw new Error("qoder job token refresh: incomplete token pair") @@ -263,6 +283,14 @@ const MODELS = [ { id: "mmodel", name: "MiniMax-M3", context: 180_000 }, ].map((m) => ({ images: true, ...m })) +// Qoder CN's list when the account's can't be asked: the tiers Qoder CN's +// CLI names (auto routes inside Qoder and isn't one model). The account's +// own list, read once signed in, takes over from it. +const CN_MODELS = [ + ...MODELS.filter((m) => ["ultimate", "performance", "efficient"].includes(m.id)), + { id: "lite", name: "Lite" }, +] + // freeOf reads whether the listing marks a model free, as Qoder's client // reads it (internal/qoder/models.go): is_free true, or a price_factor (the // credits a request costs, as a multiple) of 0, either in snake or camel case. @@ -313,10 +341,11 @@ function modelInfos(listing) { .map(modelInfo) } -async function fetchListing(cred) { - const res = await fetch(MODELS_URL, { headers: cosyHeaders(MODELS_URL, cred, ""), signal: AbortSignal.timeout(15_000) }) +async function fetchListing(site, cred) { + const url = site.api + MODELS_PATH + const res = await fetch(url, { headers: cosyHeaders(url, cred, ""), signal: AbortSignal.timeout(15_000) }) const text = await res.text() - if (!res.ok) throw new Error(`Qoder models: HTTP ${res.status}: ${text.trim().slice(0, 512)}`) + if (!res.ok) throw new Error(`${site.name} models: HTTP ${res.status}: ${text.trim().slice(0, 512)}`) return JSON.parse(text) } @@ -330,12 +359,12 @@ function configModel(m) { } } -function runtimeModel(m) { +function runtimeModel(site, m) { return { id: m.id, - providerID: ID, + providerID: site.id, name: m.name ?? m.id, - api: { id: m.id, url: API, npm: CHAT }, + api: { id: m.id, url: site.api, npm: CHAT }, status: "active", headers: {}, options: {}, @@ -785,11 +814,11 @@ class UsageStatus extends Error { } // fetchUsage is the usage envelope, {displayMode, qoderUsage}. -async function fetchUsage(deviceToken) { +async function fetchUsage(site, deviceToken) { if (!String(deviceToken ?? "").trim()) throw new Error("qoder usage: missing device token") let res try { - res = await fetch(OPENAPI + "/sash/api/v2/me/usage", { + res = await fetch(site.openapi + "/sash/api/v2/me/usage", { headers: { Accept: "application/json", Authorization: `Bearer ${deviceToken}`, "Cosy-ClientType": "10", "User-Agent": "Qoder" }, signal: AbortSignal.timeout(20_000), }) @@ -810,25 +839,31 @@ async function fetchUsage(deviceToken) { // refreshDevice trades the device refresh token for a new pair; it rotates // too, so the caller saves it. -async function refreshDevice(refresh) { - if (!String(refresh ?? "").trim()) throw new Error("qoder device token refresh: missing refresh token; sign in again") +async function refreshDevice(site, refresh, chat = false) { + if (!String(refresh ?? "").trim()) { + if (chat) throw new SignInGone(`${site.name}: the sign-in lapsed; sign in again`) + throw new Error("qoder device token refresh: missing refresh token; sign in again") + } let r try { - r = await openapi("/api/v1/deviceToken/refresh", { method: "POST", body: { refresh_token: refresh } }) + r = await openapi(site, "/api/v1/deviceToken/refresh", { method: "POST", body: { refresh_token: refresh } }) } catch (e) { throw new Error(`qoder device token refresh: request failed: ${e?.message ?? e}`) } if (r.status !== 200) { const err = `qoder device token refresh: upstream HTTP ${r.status}` - // the device token serves only the account pages (usage); chat runs on - // the job token, so a refused one doesn't lapse the account - if (r.status === 401 || r.status === 403) - throw new Error(`Qoder usage is unavailable: Qoder refused the account-page sign-in (chat still works) — sign in again to see usage (${err})`) + if (r.status === 401 || r.status === 403) { + // a device token that is the chat token too: refused, the sign-in is gone + if (chat) throw new SignInGone(`${site.name} sign-in has expired — sign in again (${err})`, true) + // otherwise it serves only the account pages (usage); chat runs on + // the job token, so a refused one doesn't lapse the account + throw new Error(`${site.name} usage is unavailable: ${site.name} refused the account-page sign-in (chat still works) — sign in again to see usage (${err})`) + } throw new Error(err) } const token = r.json?.token || r.json?.device_token || "" if (!String(token).trim() || !String(r.json?.refresh_token ?? "").trim()) throw new Error("qoder device token refresh: incomplete token pair") - return { token, refresh: r.json.refresh_token } + return { token, refresh: r.json.refresh_token, expires: deviceExpiry(r.json) } } // gfmt is a number as Go's %g writes it. @@ -880,7 +915,35 @@ function parseUsage(env) { return out } -export async function QoderAuthPlugin({ client }) { +// SITES are Qoder's two sites, each a subscription of its own. +const SITES = { + qoder: { + id: "qoder", + name: "Qoder", + clientId: "732aef47-9cf2-46a2-95fe-4cebb5d0d1fa", + web: "https://qoder.com", + openapi: "https://openapi.qoder.sh", + api: "https://api3.qoder.sh", + redirect: "qoder-app://", + models: MODELS, + }, + "qoder-cn": { + id: "qoder-cn", + name: "Qoder CN", + // the production client id of Qoder CN's CLI (@qodercn-ai/qoderclicn) + clientId: "e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb", + web: "https://qoder.cn", + openapi: "https://openapi.qoder.com.cn", + api: "https://gateway.qoder.com.cn", + redirect: "", // Qoder CN's CLI sends none + deviceChat: true, // a refused job token falls back to the CLI's device-token chat + models: CN_MODELS, + }, +} + +const makePlugin = (site) => async ({ client }) => { + const ID = site.id + const CHAT_URL = site.api + CHAT_PATH // serializes checking, rotating and saving tokens: a refresh token is // spent once, so two refreshes would spend it twice let lock = Promise.resolve() @@ -908,10 +971,18 @@ export async function QoderAuthPlugin({ client }) { const fresh = (getAuth) => locked(async () => { const a = await getAuth() - if (a?.type !== "oauth" || !a.access || !a.uid) throw new SignInGone("Qoder: not signed in") + if (a?.type !== "oauth" || !a.access || !a.uid) throw new SignInGone(`${site.name}: not signed in`) if (a.expires - Date.now() > REFRESH_LEAD) return a - const jt = await refreshJob(a.refresh, a.accountId || a.email || a.uid) - const next = { ...a, access: jt.token, refresh: jt.refresh_token, expires: expiresAt(jt) } + let next + if (a.deviceChat) { + // the device token is the chat token: renewed as a device token, + // both pairs being the one pair + const dt = await refreshDevice(site, a.refresh, true) + next = { ...a, access: dt.token, refresh: dt.refresh, expires: dt.expires, deviceToken: dt.token, deviceRefresh: dt.refresh } + } else { + const jt = await refreshJob(site, a.refresh, a.accountId || a.email || a.uid) + next = { ...a, access: jt.token, refresh: jt.refresh_token, expires: expiresAt(jt) } + } await client.auth.set({ path: { id: ID }, body: next }) renewals.add(next) return next @@ -920,7 +991,7 @@ export async function QoderAuthPlugin({ client }) { const models = async (cred, again = false) => { let l = listings.get(cred.uid) if (!l || again) { - l = modelInfos(await fetchListing(cred)) + l = modelInfos(await fetchListing(site, cred)) listings.set(cred.uid, l) } return l @@ -932,8 +1003,11 @@ export async function QoderAuthPlugin({ client }) { locked(async () => { const a = await getAuth() if (a?.deviceToken !== attempted) return a?.deviceToken - const dt = await refreshDevice(a.deviceRefresh) - await client.auth.set({ path: { id: ID }, body: { ...a, deviceToken: dt.token, deviceRefresh: dt.refresh } }) + const dt = await refreshDevice(site, a.deviceRefresh, !!a.deviceChat) + const next = { ...a, deviceToken: dt.token, deviceRefresh: dt.refresh } + // the pair it spent was the chat pair too + if (a.deviceChat) Object.assign(next, { access: dt.token, refresh: dt.refresh, expires: dt.expires }) + await client.auth.set({ path: { id: ID }, body: next }) return dt.token }) @@ -948,10 +1022,10 @@ export async function QoderAuthPlugin({ client }) { if (renewed(cred)) signIn = "renewed" let env try { - env = await fetchUsage(cred.deviceToken) + env = await fetchUsage(site, cred.deviceToken) } catch (e) { if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e - env = await fetchUsage(await deviceToken(getAuth, cred.deviceToken)) + env = await fetchUsage(site, await deviceToken(getAuth, cred.deviceToken)) } return { ...parseUsage(env), signIn } } catch (e) { @@ -962,7 +1036,7 @@ export async function QoderAuthPlugin({ client }) { const signedInError = (e) => errorResponse({ status: e instanceof SignInGone ? 401 : 502, - message: String(e?.message ?? e).replace(/^Qoder: /, ""), + message: String(e?.message ?? e).replace(new RegExp(`^${site.name}: `), ""), signIn: e?.expired ? "expired" : undefined, }) @@ -1002,7 +1076,7 @@ export async function QoderAuthPlugin({ client }) { const a = await getAuth() if (a?.type !== "oauth") return {} return { - baseURL: API, + baseURL: site.api, apiKey: "qoder", // every chat completion written as Qoder's own request async fetch(input, init = {}) { @@ -1025,18 +1099,18 @@ export async function QoderAuthPlugin({ client }) { }, } }, - methods: [{ type: "oauth", label: "Sign in with Qoder", authorize: deviceSignIn }], + methods: [{ type: "oauth", label: `Sign in with ${site.name}`, authorize: () => deviceSignIn(site) }], usage, }, async config(config) { config.provider ??= {} const was = config.provider[ID] ?? {} config.provider[ID] = { - name: "Qoder", + name: site.name, npm: CHAT, - api: API, + api: site.api, ...was, - models: { ...Object.fromEntries(MODELS.map((m) => [m.id, configModel(m)])), ...(was.models ?? {}) }, + models: { ...Object.fromEntries(site.models.map((m) => [m.id, configModel(m)])), ...(was.models ?? {}) }, } }, // the account's own list, as Qoder's client asks it @@ -1058,7 +1132,7 @@ export async function QoderAuthPlugin({ client }) { const ms = await models(cred, true) if (!ms.length) return provider.models return Object.fromEntries( - ms.map((m) => [m.key, runtimeModel({ id: m.key, name: m.name, context: m.context, images: m.images, efforts: m.thinks ? m.efforts : [], free: m.free })]), + ms.map((m) => [m.key, runtimeModel(site, { id: m.key, name: m.name, context: m.context, images: m.images, efforts: m.thinks ? m.efforts : [], free: m.free })]), ) } catch { return provider.models @@ -1068,5 +1142,8 @@ export async function QoderAuthPlugin({ client }) { } } +export const QoderAuthPlugin = makePlugin(SITES.qoder) +export const QoderCNAuthPlugin = makePlugin(SITES["qoder-cn"]) + // for tests -export const _internal = { parseUsage, gfmt, when, failure, modelInfo } +export const _internal = { parseUsage, gfmt, when, failure, modelInfo, SITES, decodeBody } diff --git a/packages/qoder/package.json b/packages/qoder/package.json index b614a59..c8f43e7 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,11 +1,11 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.1.4", - "description": "Qoder subscription in OpenCode and magpie", + "version": "0.2.0", + "description": "Qoder subscriptions in OpenCode and magpie: Qoder (qoder.com) and Qoder CN (qoder.cn)", "type": "module", "main": "./index.mjs", "exports": "./index.mjs", "files": ["index.mjs", "README.md", "LICENSE-CLIProxyAPI"], - "keywords": ["opencode", "opencode-plugin", "magpie", "qoder"], + "keywords": ["opencode", "opencode-plugin", "magpie", "qoder", "qoder-cn"], "license": "MIT" } diff --git a/registry.json b/registry.json index d3d6fa1..8837ba6 100644 --- a/registry.json +++ b/registry.json @@ -3,8 +3,8 @@ "plugins": [ { "package": "@magpie-community/opencode-zcode-auth", "name": "ZCode", "icon": "zcode", "providers": ["zcode"], "community": true, "replaces": "zcode", "summary": { "en": "Z.ai and BigModel GLM Coding Plan, with team seats.", "zh": "Z.ai 与智谱 GLM Coding Plan,支持团队席位。" } }, - { "package": "@magpie-community/opencode-qoder-auth", "name": "Qoder", "icon": "qoder", "providers": ["qoder"], "community": true, "replaces": "qoder", - "summary": { "en": "Your Qoder subscription, with Qoder's own device sign-in.", "zh": "用 Qoder 自己的设备登录使用 Qoder 订阅。" } }, + { "package": "@magpie-community/opencode-qoder-auth", "name": "Qoder", "icon": "qoder", "providers": ["qoder", "qoder-cn"], "community": true, "replaces": "qoder", + "summary": { "en": "Your Qoder subscription, international (qoder.com) or Qoder CN (qoder.cn), with Qoder's own device sign-in.", "zh": "用 Qoder 自己的设备登录使用 Qoder 订阅:国际版(qoder.com)或 Qoder CN(qoder.cn)。" } }, { "package": "@magpie-community/opencode-devin-auth", "name": "Devin", "icon": "devin", "providers": ["devin"], "community": true, "replaces": "devin", "summary": { "en": "Devin's models with your Devin account — a browser sign-in or the devin CLI's.", "zh": "用 Devin 账号使用 Devin 的模型:浏览器登录,或沿用 devin CLI 的登录。" } }, { "package": "@magpie-community/opencode-zed-auth", "name": "Zed", "icon": "zed", "providers": ["zed"], "community": true, "replaces": "zed",