From 39d9cffe7df21f76f97b461782380086217163cd Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 3 Oct 2026 12:07:23 +0800 Subject: [PATCH] qoder 0.2.3: magpie renews the sign-in ahead of time through auth.refresh auth.refresh with refreshLead 10 minutes (in-fetch: 5) for qoder and qoder-cn: the job token through refreshJob, or a qoder-cn device-token chat through refreshDevice (both pairs given). Under the request path's lock; a spent map lets a request holding the old pair use the new one. 401/403 is signIn "expired" as on the request path; anything else is retried. The check before each request stays for OpenCode, which doesn't call the hook (magpie 0.1.684+ does). refresh.test.mjs fails without the change; HOME=$(mktemp -d) bun test passes (396 across the repo). --- packages/qoder/README.md | 19 ++++- packages/qoder/index.mjs | 86 ++++++++++++++++---- packages/qoder/package.json | 2 +- packages/qoder/refresh.test.mjs | 138 ++++++++++++++++++++++++++++++++ 4 files changed, 225 insertions(+), 20 deletions(-) create mode 100644 packages/qoder/refresh.test.mjs diff --git a/packages/qoder/README.md b/packages/qoder/README.md index 380833f..ad3e084 100644 --- a/packages/qoder/README.md +++ b/packages/qoder/README.md @@ -26,10 +26,21 @@ What is kept: the job token, its refresh token and expiry, the uid, the device token and a machine id made for this sign-in. OpenCode keeps them in `auth.json`; magpie keeps them in `plugin-auth.json`. -The job token is refreshed 5 minutes before it runs out. Qoder spends a -refresh token once, so the new pair is saved straight away, and refreshes -never run at the same time. When Qoder refuses a refresh (401 or 403), the -request says to sign in again. +Refreshing: +- Qoder spends a refresh token once, so the plugin never sends one twice. +- magpie renews the job token 10 minutes before it runs out, through the + plugin's `auth.refresh`, once for the account and before its requests, + models and usage need it; magpie saves the new pair. OpenCode doesn't + call that hook: there the job token is refreshed 5 minutes before it runs + out, before a request, and the new pair is saved straight away. +- Only one refresh runs at a time. A request that reads the sign-in before + magpie saved a renewal uses the renewed pair, and a renewal handed a pair + a request already spent gives what that request got. +- 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. +- When Qoder refuses a refresh (401 or 403), the account needs signing in + again. Any other failure is tried again later. ## Requests diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index ddcde22..ca6aa66 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -32,7 +32,9 @@ const CHAT_PATH = "/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys= 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 +const REFRESH_LEAD = 5 * 60 * 1000 // a chat token this close to its end is refreshed before a request +const RENEW_LEAD = 10 * 60 * 1000 // and this close, magpie renews it ahead of time (auth.refresh) +const KEEP_SPENT_MS = 60 * 60 * 1000 // how long what a spent refresh token gave is remembered const DAY = 24 * 60 * 60 * 1000 const CHAT = "@ai-sdk/openai-compatible" @@ -842,6 +844,13 @@ function signed(res, renewed) { return new Response(res.body, { status: res.status, statusText: res.statusText, headers }) } +// changed is the fields of b that differ from a's: what auth.refresh gives. +function changed(a, b) { + const out = {} + for (const k of ["access", "refresh", "expires", "deviceToken", "deviceRefresh"]) if (b[k] !== a[k]) out[k] = b[k] + return out +} + // ---- usage -------------------------------------------------------------------- // // The account's allowance as magpie's built-in Qoder account shows it @@ -995,6 +1004,38 @@ const makePlugin = (site) => async ({ client }) => { lock = run.catch(() => {}) return run } + // spent is what each refresh token this process spent gave, by that + // token: the chat pair it renewed. magpie saves what auth.refresh gives + // only once the hook has returned, and a request may read the account in + // between, or the hook be handed the account as it was before a request + // renewed it: either follows spent rather than spending the token again. + const spent = new Map() + const latest = (a) => { + for (let i = 0; i < 16 && a?.refresh; i++) { + const s = spent.get(a.refresh) + if (!s) break + a = { ...a, ...s.got } + } + return a + } + const spend = (refresh, got) => { + const now = Date.now() + for (const [k, v] of spent) if (now - v.at > KEEP_SPENT_MS) spent.delete(k) + spent.set(refresh, { got, at: now }) + return got + } + // renew spends a's chat refresh token, under the lock: the fields it + // changes, recorded in spent. + const renew = async (a) => { + 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) + return spend(a.refresh, { access: dt.token, refresh: dt.refresh, expires: dt.expires, deviceToken: dt.token, deviceRefresh: dt.refresh }) + } + const jt = await refreshJob(site, a.refresh, a.accountId || a.email || a.uid) + return spend(a.refresh, { access: jt.token, refresh: jt.refresh_token, expires: expiresAt(jt) }) + } // each account's listing, the model configs a request carries const listings = new Map() // the accounts fresh renewed: the built-in took the lapse mark off on a @@ -1013,19 +1054,12 @@ const makePlugin = (site) => async ({ client }) => { // its end. const fresh = (getAuth) => locked(async () => { - const a = await getAuth() - if (a?.type !== "oauth" || !a.access || !a.uid) throw new SignInGone(`${site.name}: not signed in`) + const stored = await getAuth() + if (stored?.type !== "oauth" || !stored.access || !stored.uid) throw new SignInGone(`${site.name}: not signed in`) + // renewed already (by magpie's auth.refresh), the store not yet saying so + const a = latest(stored) if (a.expires - Date.now() > REFRESH_LEAD) return a - 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) } - } + const next = { ...a, ...(await renew(a)) } await client.auth.set({ path: { id: ID }, body: next }) renewals.add(next) return next @@ -1044,12 +1078,12 @@ const makePlugin = (site) => async ({ client }) => { // the one saved since, else a rotated one, saved. const deviceToken = (getAuth, attempted) => locked(async () => { - const a = await getAuth() + const a = latest(await getAuth()) if (a?.deviceToken !== attempted) return a?.deviceToken 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 }) + if (a.deviceChat) Object.assign(next, spend(a.refresh, { access: dt.token, refresh: dt.refresh, expires: dt.expires, deviceToken: dt.token, deviceRefresh: dt.refresh })) await client.auth.set({ path: { id: ID }, body: next }) return dt.token }) @@ -1115,6 +1149,28 @@ const makePlugin = (site) => async ({ client }) => { return { auth: { provider: ID, + // magpie renews the chat token RENEW_LEAD before its end, once for + // the account, before its requests, models and usage ask for it; the + // check before each request (REFRESH_LEAD) stays for OpenCode, which + // doesn't call this. The device token of a job-token account has no + // end on record: usage rotates it once Qoder refuses it, as before. + refreshLead: RENEW_LEAD, + async refresh(auth) { + if (auth?.type !== "oauth" || !auth.access || !auth.uid || !String(auth.refresh ?? "").trim()) return undefined + return locked(async () => { + // a request renewed it meanwhile (or magpie hasn't saved this + // hook's last answer): what that gave, not a second refresh + const a = latest(auth) + if (a.access !== auth.access && a.expires - Date.now() > RENEW_LEAD) return changed(auth, a) + try { + // magpie saves what this gives + return changed(auth, { ...a, ...(await renew(a)) }) + } catch (e) { + if (e?.expired) throw Object.assign(new Error(e.message), { signIn: "expired" }) + throw e + } + }) + }, async loader(getAuth) { const a = await getAuth() if (a?.type !== "oauth") return {} diff --git a/packages/qoder/package.json b/packages/qoder/package.json index 60a63ee..e6adac5 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.2.2", + "version": "0.2.3", "description": "Qoder subscriptions in OpenCode and magpie: Qoder (qoder.com) and Qoder CN (qoder.cn)", "type": "module", "main": "./index.mjs", diff --git a/packages/qoder/refresh.test.mjs b/packages/qoder/refresh.test.mjs new file mode 100644 index 0000000..03b9240 --- /dev/null +++ b/packages/qoder/refresh.test.mjs @@ -0,0 +1,138 @@ +// auth.refresh, magpie's hook for renewing a sign-in ahead of its end, on +// both sites: what it gives, that it shares a refresh token's one spending +// with a request's own refresh, and what a failure says. +import { afterEach, expect, test } from "bun:test" +import { QoderAuthPlugin, QoderCNAuthPlugin } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json" } }) + +const SITES = [ + { name: "qoder", plugin: QoderAuthPlugin, openapi: "openapi.qoder.sh" }, + { name: "qoder-cn", plugin: QoderCNAuthPlugin, openapi: "openapi.qoder.com.cn" }, +] + +const account = (over = {}) => ({ + type: "oauth", + access: "jt-1", + refresh: "jrt-1", + expires: Date.now() + 60_000, + accountId: "one@x", + uid: "u1", + machineId: "m1", + deviceToken: "dt-1", + deviceRefresh: "drt-1", + ...over, +}) + +// serve answers the refresh calls, counting them by path and token; any +// other call (the chat) is a 500, which is enough for a request's refresh +function serve(site, { job, device } = {}) { + const calls = [] + globalThis.fetch = async (url, init = {}) => { + const u = new URL(String(url)) + const token = init.body ? JSON.parse(init.body).refresh_token : undefined + calls.push(u.host + u.pathname + " " + token) + if (u.host === site.openapi && u.pathname === "/api/v1/jobToken/refresh") return job ? job(token) : json({ token: "jt-2", refresh_token: "jrt-2", expires_in: 3_600_000 }) + if (u.host === site.openapi && u.pathname === "/api/v1/deviceToken/refresh") + return device ? device(token) : json({ device_token: "dt-2", refresh_token: "drt-2", expires_at: new Date(Date.now() + 7_200_000).toISOString() }) + return new Response("", { status: 500 }) + } + return calls +} + +async function plugin(site, auth) { + let stored = auth + const sets = [] + const client = { auth: { set: async ({ body }) => (sets.push(body), (stored = body)) } } + const hooks = await site.plugin({ client }) + return { hooks, sets, get: async () => stored } +} + +for (const site of SITES) { + test(`${site.name}: auth.refresh renews the job token and gives what changed, leaving the save to magpie`, async () => { + const calls = serve(site) + const { hooks, sets } = await plugin(site, account()) + expect(hooks.auth.refreshLead).toBe(10 * 60 * 1000) + const got = await hooks.auth.refresh(account(), { id: site.name }) + expect(got).toMatchObject({ access: "jt-2", refresh: "jrt-2" }) + expect(Object.keys(got).sort()).toEqual(["access", "expires", "refresh"]) + expect(got.expires).toBeGreaterThan(Date.now() + 3_000_000) + expect(sets).toEqual([]) + expect(calls).toEqual([`${site.openapi}/api/v1/jobToken/refresh jrt-1`]) + }) + + test(`${site.name}: auth.refresh and a request's refresh spend the refresh token once`, async () => { + // the hook first: a request reading the store before magpie saved it + let calls = serve(site) + let p = await plugin(site, account()) + const opts = await p.hooks.auth.loader(p.get) + const [got] = await Promise.all([ + p.hooks.auth.refresh(account(), { id: site.name }), + opts.fetch("https://x/chat/completions", { method: "POST", body: JSON.stringify({ model: "m", messages: [] }) }), + ]) + expect(got).toMatchObject({ access: "jt-2", refresh: "jrt-2" }) + expect(calls.filter((c) => c.includes("Token/refresh"))).toEqual([`${site.openapi}/api/v1/jobToken/refresh jrt-1`]) + expect(p.sets).toEqual([]) + + // the request first: the hook, handed the sign-in as it was, gives + // what the request got + let release + const held = new Promise((r) => (release = r)) + calls = serve(site, { job: async () => (await held, json({ token: "jt-2", refresh_token: "jrt-2", expires_in: 3_600_000 })) }) + p = await plugin(site, account()) + const opts2 = await p.hooks.auth.loader(p.get) + const req = opts2.fetch("https://x/chat/completions", { method: "POST", body: JSON.stringify({ model: "m", messages: [] }) }) + while (!calls.length) await new Promise((r) => setTimeout(r, 1)) + const hook = p.hooks.auth.refresh(account(), { id: site.name }) + release() + const [, got2] = await Promise.all([req, hook]) + expect(got2).toMatchObject({ access: "jt-2", refresh: "jrt-2" }) + expect(calls.filter((c) => c.includes("Token/refresh"))).toEqual([`${site.openapi}/api/v1/jobToken/refresh jrt-1`]) + expect(p.sets.map((s) => s.refresh)).toEqual(["jrt-2"]) + }) + + test(`${site.name}: a refresh Qoder refuses (401/403) is signIn "expired"; another failure throws plainly`, async () => { + for (const status of [401, 403]) { + serve(site, { job: () => new Response("", { status }) }) + const { hooks } = await plugin(site, account()) + const err = await hooks.auth.refresh(account(), { id: site.name }).catch((e) => e) + expect(err.signIn).toBe("expired") + expect(err.message).toContain("sign-in has expired") + } + serve(site, { job: () => new Response("", { status: 500 }) }) + const { hooks } = await plugin(site, account()) + const err = await hooks.auth.refresh(account(), { id: site.name }).catch((e) => e) + expect(err).toBeInstanceOf(Error) + expect(err.signIn).toBeUndefined() + expect(err.message).toBe("qoder job token refresh: status 500") + }) + + test(`${site.name}: nothing to renew with is undefined`, async () => { + const calls = serve(site) + const { hooks } = await plugin(site, account()) + expect(await hooks.auth.refresh(account({ refresh: "" }), { id: site.name })).toBeUndefined() + expect(await hooks.auth.refresh({ type: "api", key: "k" }, { id: site.name })).toBeUndefined() + expect(calls).toEqual([]) + }) +} + +test("qoder-cn: a device-token account is renewed as a device token, both pairs given", async () => { + const site = SITES[1] + const calls = serve(site) + const a = account({ access: "dt-1", refresh: "drt-1", deviceChat: true }) + const { hooks, sets } = await plugin(site, a) + const got = await hooks.auth.refresh(a, { id: "qoder-cn" }) + expect(got).toMatchObject({ access: "dt-2", refresh: "drt-2", deviceToken: "dt-2", deviceRefresh: "drt-2" }) + expect(got.expires).toBeGreaterThan(Date.now() + 7_000_000) + expect(got.type).toBeUndefined() + expect(sets).toEqual([]) + expect(calls).toEqual([`${site.openapi}/api/v1/deviceToken/refresh drt-1`]) + + serve(site, { device: () => new Response("", { status: 401 }) }) + const p = await plugin(site, a) + const err = await p.hooks.auth.refresh(a, { id: "qoder-cn" }).catch((e) => e) + expect(err.signIn).toBe("expired") +})