diff --git a/packages/qoder/README.md b/packages/qoder/README.md index 238415a..55e605f 100644 --- a/packages/qoder/README.md +++ b/packages/qoder/README.md @@ -76,6 +76,13 @@ Refreshing: or another process renewed it meanwhile, else after one refresh, under the same lock. A token renewed less than 5 minutes ago and refused again isn't renewed again; the refusal is the answer. +- A model Qoder serves that the account's listing has off or leaves out is + asked for the same way: the job token is renewed once (or the pair saved + since is used) and the list read again, before the request is answered + `unknown or disabled model`. On a job token Qoder no longer honours in + full, the listing can have only the free models on (#484). The same + 5-minute rule holds, and an id Qoder has never served is said unknown at + once, with no renewal. - The device token, which reads usage, has no end on record: it is rotated when Qoder refuses it. On a [Qoder CN](#qoder-cn) device-token account it is the chat token too, and is renewed as above. diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index 7f86d16..3a7e5cb 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -2542,11 +2542,21 @@ const makePlugin = (site) => async ({ client }) => { return next }) + // the ids Qoder serves: the site's shipped list and every key a listing + // has named, on or off + const served = new Set(site.models.map((m) => m.id)) + const knows = (id) => served.has(id) const models = async (cred, again = false) => { const key = listingKey(cred) let l = listings.get(key) if (!l || again) { - l = modelInfos(await fetchListing(siteOf(site, cred), cred), siteOf(site, cred)) + const s = siteOf(site, cred) + const listing = await fetchListing(s, cred) + for (const m of s.modelScene ? (Array.isArray(listing?.[s.modelScene]) ? listing[s.modelScene] : []) : sceneModels(listing)) { + const k = String(m?.key ?? "").trim() + if (k) served.add(k) + } + l = modelInfos(listing, s) listings.set(key, l) } return l @@ -2783,8 +2793,26 @@ const makePlugin = (site) => async ({ client }) => { const ask = async (chat, cred, init, named = "", fallback = false, getAuth, asked = {}) => { asked.cred = cred let m + let relogged = false + const listed = (ms) => ms.find((x) => x.key === chat.model) try { - m = (await models(cred)).find((x) => x.key === chat.model) ?? (await models(cred, true)).find((x) => x.key === chat.model) + m = listed(await models(cred)) ?? listed(await models(cred, true)) + // A model Qoder serves that the account's listing leaves out, or has + // off, on a job token Qoder no longer honours in full: the token is + // renewed once (relogin, as for a refused chat) and the list asked + // again. On an enterprise qoder.com account (plugins#484) the listing + // had only the free dfmodel and qfmodel on while the job token was + // stale, and every other model was answered 400 here, before a chat + // could be refused and renew it. An id Qoder has never served is said + // unknown at once, with no renewal spent on it. + if (!m && getAuth && knows(chat.model)) { + relogged = true + const next = await relogin(getAuth, cred.access) + if (next) { + cred = asked.cred = next + m = listed(await models(cred, true)) + } + } } catch (e) { if (e instanceof SignInGone || e?.expired) return signedInError(e) return errorResponse({ status: 502, message: e?.message ?? String(e) }) @@ -2804,7 +2832,6 @@ const makePlugin = (site) => async ({ client }) => { // resend can be queued again before it is answered. const deadline = QUEUE.now() + QUEUE.budget const ask = { requestSetId: body.request_set_id, requestId: body.request_id, sessionId: body.session_id, modelKey: m.key } - let relogged = false for (let sent = 0, waited = 0; ; sent++) { if (sent) { body.request_id = body.chat_record_id = randomUUID() diff --git a/packages/qoder/listing-renew.test.mjs b/packages/qoder/listing-renew.test.mjs new file mode 100644 index 0000000..1e48bab --- /dev/null +++ b/packages/qoder/listing-renew.test.mjs @@ -0,0 +1,145 @@ +// plugins#484 (fskk54-cmyk): on an enterprise qoder.com (international) +// account under 0.2.48, 12 of the 14 app models were answered with the +// plugin's own 400 `unknown or disabled model` while dfmodel and qfmodel, +// the two free ones, were served. The 400 is said from the account's +// listing, before any chat is sent, so the renewal 0.2.48 gave a refused +// chat (plugins#474) never ran for those models. +// +// The fake Qoder lists the reporter's 14 app models. A job token it still +// honours gets all 14 on; one it has stopped honouring gets the free view, +// dfmodel and qfmodel on and the rest off, and its chats are refused as +// Login expired. A refresh token is spent once. Calls are COSY-signed, and +// the fake opens the envelope with the private half of a key the test puts +// in place of Qoder's to read which job token a call carries. +import { afterEach, beforeEach, expect, test } from "bun:test" +import { constants, createDecipheriv, generateKeyPairSync, privateDecrypt } from "node:crypto" +import { QoderAuthPlugin, _internal } from "./index.mjs" + +const real = globalThis.fetch +const site = _internal.SITES.qoder +const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 }) +beforeEach(() => (site.rsaKey = publicKey.export({ type: "spki", format: "pem" }))) +afterEach(() => { + globalThis.fetch = real + delete site.rsaKey +}) + +const HOUR = 3_600_000 +const CHAT = "https://api3.qoder.sh/v1/chat/completions" +const FREE = ["dfmodel", "qfmodel"] +// the reporter's 14 ids, in the order they tried them +const PAID = ["ultimate", "fast", "efficient", "smodel", "cmodel", "qmodel_38max", "gmodel", "gfmodel", "kmodel_latest", "kmodel", "dmodel", "mmodel"] +const ALL = [...PAID, ...FREE] + +const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json" } }) +const line = (body) => `data:${JSON.stringify({ headers: {}, body: JSON.stringify(body), statusCodeValue: 200 })}\n\n` +const answered = () => + new Response(line({ choices: [{ delta: { content: "hello" } }] }) + line({ choices: [{ delta: {}, finish_reason: "stop" }] }) + `data:${JSON.stringify({ headers: {}, body: "[DONE]", statusCodeValue: 200 })}\n\n`, { + headers: { "Content-Type": "text/event-stream" }, + }) +const chat = (model) => ({ method: "POST", body: JSON.stringify({ model, messages: [{ role: "user", content: "hi" }] }) }) + +// tokenOf is the job token a COSY-signed call carries +function tokenOf(headers) { + const block = privateDecrypt({ key: privateKey, padding: constants.RSA_NO_PADDING }, Buffer.from(headers["Cosy-Key"], "base64")) + const key = block.subarray(block.indexOf(0, 2) + 1) + const [payload] = headers.Authorization.slice("Bearer COSY.".length).split(".") + const { info } = JSON.parse(Buffer.from(payload, "base64").toString()) + const d = createDecipheriv("aes-128-cbc", key, key) + return JSON.parse(Buffer.concat([d.update(Buffer.from(info, "base64")), d.final()]).toString()).security_oauth_token +} + +// qoder is the fake. honoured is the job tokens Qoder serves in full; +// off is the models off for every account whatever its token. +function qoder({ honoured = new Set(), off = [] } = {}) { + const pairs = new Map([["jrt-1", "jt-1"]]) + const calls = { refresh: [], listings: [], chats: [] } + let n = 1 + globalThis.fetch = async (url, init = {}) => { + const u = new URL(String(url)) + if (u.pathname === "/api/v1/jobToken/refresh") { + const rt = JSON.parse(init.body).refresh_token + calls.refresh.push(rt) + if (!pairs.has(rt)) return json({ message: "invalid refresh token" }, 401) + honoured.delete(pairs.get(rt)) + pairs.delete(rt) + n++ + honoured.add(`jt-${n}`) + pairs.set(`jrt-${n}`, `jt-${n}`) + return json({ token: `jt-${n}`, refresh_token: `jrt-${n}`, expires_in: 24 * HOUR }) + } + const t = tokenOf(init.headers) + if (u.pathname.endsWith("/model/list")) { + calls.listings.push(t) + const full = honoured.has(t) + return json({ app: ALL.map((key) => ({ key, display_name: key, enable: !off.includes(key) && (full || FREE.includes(key)) })), byok_teams: [], byok_enterprise: [] }) + } + calls.chats.push(t) + if (!honoured.has(t)) return json({ message: "Login expired" }, 403) + return answered() + } + return { calls, honoured } +} + +// account is an enterprise account on qoder.com as magpie saved it, its +// job token a day from its saved end +async function account() { + const box = { stored: { type: "oauth", access: "jt-1", refresh: "jrt-1", expires: Date.now() + 24 * HOUR, accountId: "ent@corp.example", uid: "u-ent", email: "ent@corp.example", machineId: "m1" } } + const hooks = await QoderAuthPlugin({ client: { auth: { set: async ({ body }) => (box.stored = { ...body }) } } }) + const l = await hooks.auth.loader(async () => box.stored) + return { hooks, fetch: l.fetch, box } +} + +test("plugins#484: each of the reporter's 14 models is served on a job token Qoder lists only the free models for, renewed once", async () => { + const q = qoder() + const a = await account() + for (const model of ALL) { + const res = await a.fetch(CHAT, chat(model)) + expect({ model, status: res.status }).toEqual({ model, status: 200 }) + expect((await res.json()).choices[0].message.content).toBe("hello") + } + expect(q.calls.refresh).toEqual(["jrt-1"]) + expect(a.box.stored).toMatchObject({ access: "jt-2", refresh: "jrt-2" }) + expect(q.calls.chats.every((t) => t === "jt-2")).toBe(true) +}) + +test("plugins#484: the first request after the free view, on a paid model, says the renewal", async () => { + qoder() + const a = await account() + const res = await a.fetch(CHAT, chat("efficient")) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed") +}) + +test("an id Qoder never served is said unknown at once, spending no refresh token", async () => { + const q = qoder({ honoured: new Set(["jt-1"]) }) + const a = await account() + const res = await a.fetch(CHAT, chat("no-such-model")) + expect(res.status).toBe(400) + expect((await res.json()).error.message).toContain('unknown or disabled model "no-such-model"') + expect(q.calls.refresh).toEqual([]) + expect(q.calls.chats).toEqual([]) +}) + +test("a model the account has off on a renewed token too is said disabled, and the token renewed minutes ago isn't renewed again", async () => { + const q = qoder({ off: ["ultimate"] }) + const a = await account() + for (let i = 0; i < 3; i++) { + const res = await a.fetch(CHAT, chat("ultimate")) + expect(res.status).toBe(400) + expect((await res.json()).error.message).toContain('unknown or disabled model "ultimate"') + } + expect(q.calls.refresh).toEqual(["jrt-1"]) + expect(q.calls.chats).toEqual([]) + // the other models are served on the renewed token + expect((await a.fetch(CHAT, chat("gmodel"))).status).toBe(200) + expect(q.calls.refresh).toEqual(["jrt-1"]) +}) + +test("a model the live listing has on spends no refresh token", async () => { + const q = qoder({ honoured: new Set(["jt-1"]) }) + const a = await account() + for (const model of ALL) expect((await a.fetch(CHAT, chat(model))).status).toBe(200) + expect(q.calls.refresh).toEqual([]) + expect(new Set(q.calls.listings)).toEqual(new Set(["jt-1"])) +}) diff --git a/packages/qoder/package.json b/packages/qoder/package.json index edb0f1e..bb62747 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.2.48", + "version": "0.2.49", "description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship (VPC)", "type": "module", "main": "./index.mjs",