diff --git a/packages/cline/README.md b/packages/cline/README.md index c6de725..8df5cac 100644 --- a/packages/cline/README.md +++ b/packages/cline/README.md @@ -15,15 +15,25 @@ Provider id: `cline`. The sign-in is kept where OpenCode keeps auth (`auth.json` under the data directory); magpie keeps plugin sign-ins in its own store -(`~/.config/magpie/plugin-auth.json`). Access tokens are renewed through -`/api/v1/auth/refresh` when they near expiry — Cline rotates the refresh -token, and the rotated pair is saved back the moment it arrives (and kept in -memory beside the store, so a save that fails can't leave the next request -spending the token that was already spent). Refreshes are serialized, so two -requests renewing at once can't spend one token and lose the other. A refresh -that fails for a while keeps the token that is still good, as Cline's own -client does; only a token that has actually expired is treated as the sign-in -gone. +(`~/.config/magpie/plugin-auth.json`). + +Refreshing: +- Access tokens are renewed through `/api/v1/auth/refresh`. Cline rotates + the refresh token and refuses one already spent, so the rotated pair is + kept in memory beside the store the moment it arrives: a save that fails + can't leave the next request spending the token that was already spent. +- magpie renews the token ten minutes before it ends, 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 token is refreshed five minutes before it ends, before a + request, and the new pair is saved. +- Refreshes are serialized, magpie's renewal included, so two at once can't + spend one token and lose the other; one that finds the token already + renewed uses that pair. +- A refresh that fails for a while keeps the token that is still good, as + Cline's own client does (magpie tries its renewal again shortly); only a + refresh Cline refuses, or a token that has actually expired, is treated as + the sign-in gone. ## Requests diff --git a/packages/cline/index.mjs b/packages/cline/index.mjs index 8cfacb3..191993e 100644 --- a/packages/cline/index.mjs +++ b/packages/cline/index.mjs @@ -21,7 +21,8 @@ const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code" // signed-in one rides as "workos:" (Cline's own clients send it so) const WORKOS_PREFIX = "workos:" -const REFRESH_LEAD = 5 * 60 * 1000 +const REFRESH_LEAD = 5 * 60 * 1000 // a 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) // a refresh that failed transiently keeps a token with this much left, as // Cline's getValidClineCredentials does (DEFAULT_RETRYABLE_TOKEN_GRACE_MS); // only once it has actually expired is the sign-in the one to blame @@ -692,6 +693,20 @@ export const ClinePlugin = async ({ client } = {}) => { return run } + // spend trades r's refresh token for a new pair and holds it, whatever a + // save then does, against the token it spent and the one getAuth handed + // back (a's): the next request offering either of them finds this chain's + // newest. Called under the lock only. + const spend = async (a, r) => { + const p = await refresh(r) + const next = { ...r, access: p.access, refresh: p.refresh, expires: p.expires, uid: p.uid || r.uid, email: p.email || r.email, name: p.name || r.name, accountId: r.accountId || p.accountId } + const chain = held.get(a.refresh) ?? {} + Object.assign(chain, { access: next.access, refresh: next.refresh, expires: next.expires }) + held.set(a.refresh, chain) + held.set(r.refresh, chain) + return next + } + // fresh is the account with a token still good: one near its end is // renewed, and the rotated pair saved back. A transient refresh failure // keeps the token that is still good, as Cline's own client does; only a @@ -711,23 +726,15 @@ export const ClinePlugin = async ({ client } = {}) => { const r = h ? { ...a, access: h.access, refresh: h.refresh, expires: h.expires } : a if (r.access && r.expires - Date.now() > REFRESH_LEAD) return { ...r, bearer: bearerOf(r), renewed: false } if (!r.refresh) throw new Lapsed("Cline's access token has expired and there is no refresh token; sign in to Cline again") - let p + let next try { - p = await refresh(r) + next = await spend(a, r) } catch (e) { // a token that is still good rides on through a refresh that // failed for a while; an expired one is the sign-in gone if (!e?.expired && r.access && r.expires - Date.now() > RETRYABLE_GRACE) return { ...r, bearer: bearerOf(r), renewed: false } throw e } - const next = { ...r, access: p.access, refresh: p.refresh, expires: p.expires, uid: p.uid || r.uid, email: p.email || r.email, name: p.name || r.name, accountId: r.accountId || p.accountId } - // the pair just rotated, held whatever the save through magpie does, - // against the token it spent and the one getAuth handed back: the - // next request offering either of them finds this chain's newest - const chain = held.get(a.refresh) ?? {} - Object.assign(chain, { access: next.access, refresh: next.refresh, expires: next.expires }) - held.set(a.refresh, chain) - held.set(r.refresh, chain) await remember(next) const cred = { ...next, bearer: bearerOf(next), renewed: true } renewals.add(cred) @@ -782,6 +789,38 @@ export const ClinePlugin = async ({ client } = {}) => { auth: { provider: PROVIDER, + // magpie renews the sign-in RENEW_LEAD before its end, once for the + // account, before its requests, models and usage ask for it; the + // check in fresh before each request stays for OpenCode, which + // doesn't call this. It takes the same lock and the same held pairs + // as fresh, so the two never spend one refresh token twice. magpie + // saves what this gives (it is merged over the sign-in): only what + // changed comes back, and remember isn't called here. + refreshLead: RENEW_LEAD, + refresh: (auth) => + locked(async () => { + const a = authOf(auth) + // an API key, or a sign-in with nothing to renew with + if (auth?.type !== "oauth" || !a.refresh) return undefined + // renewed here already (a request's refresh), the store not + // yet saying so: that pair, not another spend + const h = held.get(a.refresh) + const r = h ? { ...a, access: h.access, refresh: h.refresh, expires: h.expires } : a + if (h && r.access && r.expires - Date.now() > RENEW_LEAD) return { access: r.access, refresh: r.refresh, expires: r.expires } + let next + try { + next = await spend(a, r) + } catch (e) { + // a refused refresh is the sign-in gone; anything else is + // retried by magpie, the token in hand riding on meanwhile + if (e?.expired) throw Object.assign(new Error(String(e.message ?? e).replace(/^Cline: /, "")), { signIn: "expired" }) + throw e + } + const out = { access: next.access, refresh: next.refresh, expires: next.expires } + for (const k of ["uid", "email", "name", "accountId"]) if (next[k] && next[k] !== a[k]) out[k] = next[k] + return out + }), + async loader(getAuth) { const a = await getAuth() if (a?.type !== "oauth" && a?.type !== "api") return {} diff --git a/packages/cline/package.json b/packages/cline/package.json index c061c13..69fe5f3 100644 --- a/packages/cline/package.json +++ b/packages/cline/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cline-auth", - "version": "0.1.0", + "version": "0.1.1", "description": "Cline (cline.bot) on your own account — usage billing, ClinePass and the free models — in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/cline/refresh.test.mjs b/packages/cline/refresh.test.mjs new file mode 100644 index 0000000..78064a6 --- /dev/null +++ b/packages/cline/refresh.test.mjs @@ -0,0 +1,137 @@ +// Tests for auth.refresh, the hook magpie renews a sign-in through ahead of +// its end. Every request is answered by a mock fetch; nothing reaches the +// network. +import { test, expect, afterEach } from "bun:test" +import { ClinePlugin } from "./index.mjs" + +const API = "https://api.cline.bot/api/v1" +const chatUrl = `${API}/chat/completions` +const chatInit = () => ({ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model: "anthropic/claude-sonnet-5" }) }) + +let calls = [] +const realFetch = globalThis.fetch +afterEach(() => { + globalThis.fetch = realFetch +}) + +// serve answers each URL from routes ([urlPart, (init) => Response]), in +// order; an unmatched URL fails loudly +function serve(routes) { + routes = [...routes] + calls = [] + globalThis.fetch = async (input, init = {}) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url + calls.push({ url, init }) + const idx = routes.findIndex(([part]) => url.includes(part)) + if (idx < 0) throw new Error(`no route for ${url}`) + const r = routes[idx][1] + routes.splice(idx, 1) + return r(init) + } +} + +const refreshes = () => calls.filter((c) => c.url.includes("/auth/refresh")) + +const rotated = (n, extra = {}) => () => + Response.json({ success: true, data: { accessToken: `jwt${n}`, refreshToken: `r${n}`, expiresAt: new Date(Date.now() + 3600_000).toISOString(), userInfo: { clineUserId: "cu1", ...extra } } }) + +// plugin is the plugin over a store that saves what client.auth.set is given +async function plugin(seed) { + const saved = [] + let stored = seed + const client = { + app: { log: async () => {} }, + auth: { + set: async (input) => { + saved.push(input.body) + stored = input.body + }, + }, + } + return { hooks: await ClinePlugin({ client }), saved, getAuth: async () => stored } +} + +const due = () => ({ type: "oauth", access: "jwt1", refresh: "r1", expires: Date.now() + 60_000, uid: "cu1", email: "a@b.c", accountId: "a@b.c" }) + +test("the lead is no shorter than the check before each request", async () => { + const { hooks } = await plugin(due()) + expect(hooks.auth.refreshLead).toBeGreaterThanOrEqual(5 * 60 * 1000) + expect(typeof hooks.auth.refresh).toBe("function") +}) + +test("auth.refresh renews and gives the new pair, leaving the save to magpie", async () => { + const { hooks, saved } = await plugin(due()) + serve([["/auth/refresh", rotated(2)]]) + const got = await hooks.auth.refresh(due()) + expect(got.access).toBe("jwt2") + expect(got.refresh).toBe("r2") + expect(got.expires).toBeGreaterThan(Date.now() + 50 * 60_000) + // only what changed: no type, nothing the sign-in had already + expect(got.type).toBeUndefined() + expect(got.uid).toBeUndefined() + expect(got.email).toBeUndefined() + expect(JSON.parse(refreshes()[0].init.body).refreshToken).toBe("r1") + expect(saved.length).toBe(0) +}) + +test("auth.refresh and a request's refresh at once spend the refresh token once", async () => { + for (const hookFirst of [true, false]) { + const { hooks, getAuth } = await plugin(due()) + // the refresh is held open until both are under way + let open + const gate = new Promise((r) => (open = r)) + serve([["/auth/refresh", async () => (await gate, rotated(2)())], [chatUrl, () => Response.json({ ok: true })]]) + const l = await hooks.auth.loader(getAuth) + const started = async () => { + while (!refreshes().length) await new Promise((r) => setTimeout(r, 1)) + } + let got, res + if (hookFirst) { + const h = hooks.auth.refresh(due()) + await started() + const q = l.fetch(chatUrl, chatInit()) + open() + ;[got, res] = await Promise.all([h, q]) + } else { + const q = l.fetch(chatUrl, chatInit()) + await started() + const h = hooks.auth.refresh(due()) + open() + ;[got, res] = await Promise.all([h, q]) + } + expect(res.status).toBe(200) + expect(got.access).toBe("jwt2") + expect(got.refresh).toBe("r2") + expect(refreshes().length).toBe(1) + expect(calls.find((c) => c.url === chatUrl).init.headers.get("Authorization")).toBe("Bearer workos:jwt2") + } +}) + +test("a refresh Cline refuses is the sign-in expired", async () => { + const { hooks, saved } = await plugin(due()) + serve([["/auth/refresh", () => Response.json({ error: "invalid_grant", error_description: "refresh token revoked" }, { status: 400 })]]) + const e = await hooks.auth.refresh(due()).then(() => null, (e) => e) + expect(e).toBeInstanceOf(Error) + expect(e.signIn).toBe("expired") + expect(saved.length).toBe(0) +}) + +test("a refresh that failed for a while throws plainly, for magpie to retry", async () => { + const { hooks } = await plugin(due()) + serve([["/auth/refresh", () => new Response("upstream down", { status: 503 })]]) + const e = await hooks.auth.refresh(due()).then(() => null, (e) => e) + expect(e).toBeInstanceOf(Error) + expect(e.signIn).toBeUndefined() + // and the refresh token wasn't spent: the next try sends it again + serve([["/auth/refresh", rotated(2)]]) + expect((await hooks.auth.refresh(due())).access).toBe("jwt2") + expect(JSON.parse(refreshes()[0].init.body).refreshToken).toBe("r1") +}) + +test("an account with nothing to renew with gives nothing", async () => { + const { hooks } = await plugin(due()) + serve([]) + expect(await hooks.auth.refresh({ type: "api", key: "ck" })).toBeUndefined() + expect(await hooks.auth.refresh({ type: "oauth", access: "jwt1", refresh: "", expires: Date.now() + 60_000 })).toBeUndefined() + expect(calls.length).toBe(0) +})