diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index 4540fce..44448c2 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -33,6 +33,16 @@ marker, `{"type": "oauth", "source": "desktop", "accountId", "uid"}`. OpenCode k refreshed a minute before it ends, and the new one is saved. If the refresh fails, the old token is used while it lasts. +In magpie (0.1.684 or later) the plugin also gives `auth.refresh` with +`refreshLead` of 5 minutes: magpie renews a browser sign-in (an hour's +token) 5 minutes before it ends, once for the account, before its +requests, models and usage ask, and saves what it gives. It goes through +the same one-refresh-at-a-time as a request's refresh, so a refresh token +is never spent twice. A failed renewal, a refresh token past its end +included, doesn't mark the account, as the built-in never did; magpie +tries again later, and the old token is used meanwhile. +OpenCode doesn't call `auth.refresh`; the check before each request stays. + Desktop's sign-in is refreshed only when the app hasn't refreshed it itself, and the new token is kept in memory, never written back, as magpie's built-in WorkBuddy does. diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index 69532f8..f04f113 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -17,7 +17,9 @@ const APP_VERSION = "2.0.0" // the version WorkBuddy's sign-in page is opened wi const UA_VERSION = "5.5.6" // WorkBuddy/ is the User-Agent the API takes const POLL_MS = 1000 const SIGN_IN_MS = 5 * 60 * 1000 -const EARLY_MS = 60 * 1000 // a token this close to its end is refreshed +const EARLY_MS = 60 * 1000 // a token this close to its end is refreshed before a request +const LEAD_MS = 5 * 60 * 1000 // and this close, magpie renews it ahead of time (auth.refresh) +const KEEP_RENEWED_MS = 60 * 1000 // how long a refresh's result answers for the old refresh token // [id, name, context, efforts] const CN_MODELS = [ @@ -146,27 +148,66 @@ function stale(a) { return !!a.expires && Date.now() >= a.expires - EARLY_MS } +// renewing is each refresh under way, by site and the refresh token it +// spends; renewed is what each gave, kept a minute so one that read the +// old refresh token after it was spent (magpie's auth.refresh, a request) +// takes that rather than spending it again. +const renewing = new Map() +const renewed = new Map() + +function refreshable(a) { + return !!a.refresh && !(a.refreshExpiresAt && Date.now() >= a.refreshExpiresAt) +} + +// renew spends a's refresh token, once: those who come while it runs, or +// within KEEP_RENEWED_MS of it, get what it gave. save keeps the result. +function renew(site, a, save) { + const key = site.id + "\n" + a.refresh + const done = renewed.get(key) + if (done && Date.now() - done.at < KEEP_RENEWED_MS) return Promise.resolve(merged(a, done.next)) + let r = renewing.get(key) + if (!r) { + r = (async () => { + const got = await call(site, "POST", "/v2/plugin/auth/token/refresh", { + "X-Refresh-Token": a.refresh, + "X-Auth-Refresh-Source": "plugin", + "X-Domain": domainOf(site, a), + }, {}) + if (!got?.accessToken) throw Object.assign(new Error("WorkBuddy gave no refreshed token"), { bare: true }) + const next = merge(a, got) + renewed.set(key, { next, at: Date.now() }) + await save?.(next) + return next + })().finally(() => renewing.delete(key)) + renewing.set(key, r) + } + return r.then((next) => merged(a, next)) +} + +// merged is a with the tokens another's refresh gave over it. +function merged(a, next) { + const out = { ...a } + for (const k of TOKEN_FIELDS) if (k in next) out[k] = next[k] + return out +} +const TOKEN_FIELDS = ["access", "refresh", "expires", "refreshExpiresAt", "domain", "tokenType"] + // fresh is the sign-in with an access token that isn't about to end: // refreshed (and saved) when it is. A refresh that fails, or a refresh // token that has ended, leaves the access token there is. Its failures // are worded as the built-in's (wbFresh), "WorkBuddy" on both sites. async function fresh(site, client, a) { if (!stale(a)) return a - const refreshable = a.refresh && !(a.refreshExpiresAt && Date.now() >= a.refreshExpiresAt) - if (!refreshable) { + if (!refreshable(a)) { if (a.access) return a throw new Error("this WorkBuddy account is signed out; sign in again") } try { - const got = await call(site, "POST", "/v2/plugin/auth/token/refresh", { - "X-Refresh-Token": a.refresh, - "X-Auth-Refresh-Source": "plugin", - "X-Domain": domainOf(site, a), - }, {}) - if (!got?.accessToken) throw Object.assign(new Error("WorkBuddy gave no refreshed token"), { bare: true }) - const next = merge(a, got) - await client?.auth?.set?.({ path: { id: site.id }, body: next }) - return next + return await renew(site, a, async (next) => { + try { + await client?.auth?.set?.({ path: { id: site.id }, body: next }) + } catch {} + }) } catch (e) { if (a.access) return a if (e?.bare) throw e @@ -174,6 +215,26 @@ async function fresh(site, client, a) { } } +// refreshed is what magpie's auth.refresh gives for a browser sign-in: +// the fields a refresh changed, nothing when there's nothing to renew. +// magpie saves them itself. +async function refreshed(site, auth) { + if (auth?.type !== "oauth" || auth.source === "desktop" || !auth.access || !auth.refresh) return undefined + // a refresh token that has ended is said plainly, never as signIn + // "expired": the built-in never marked a WorkBuddy account + if (!refreshable(auth)) throw new Error("this WorkBuddy account is signed out; sign in again") + let next + try { + next = await renew(site, auth) + } catch (e) { + if (e?.bare) throw e + throw new Error(`WorkBuddy token refresh: ${e?.said ?? e?.message ?? e}`) + } + const out = {} + for (const k of TOKEN_FIELDS) if (k in next && next[k] !== auth[k]) out[k] = next[k] + return Object.keys(out).length ? out : undefined +} + // sign sets on headers what WorkBuddy's desktop app sends with a chat. function sign(site, a, headers) { headers.set("Authorization", "Bearer " + a.access) @@ -571,6 +632,13 @@ function makePlugin(site) { }, auth: { provider: site.id, + // magpie renews a browser sign-in LEAD_MS before its end (an hour's + // token), once for the account, before its requests, models and + // usage ask; the check before each request stays for OpenCode, + // which doesn't call this. Desktop's sign-in has no expiry stored + // and is renewed as before. + refreshLead: LEAD_MS, + refresh: (auth) => refreshed(site, auth), async loader(getAuth) { const auth = await getAuth() if (auth?.type !== "oauth") return {} @@ -676,4 +744,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -export const _internal = { withSystem, usageOf, desktopHeld, explained, REFUSED_HINT, freeCredits, creditsOf, fresh, SITES } +export const _internal = { withSystem, usageOf, desktopHeld, explained, REFUSED_HINT, freeCredits, creditsOf, fresh, SITES, renewing, renewed } diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 29899d4..6d0c4ac 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.6", + "version": "0.1.7", "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)", "type": "module", "main": "./index.mjs", diff --git a/packages/workbuddy/refresh.test.mjs b/packages/workbuddy/refresh.test.mjs new file mode 100644 index 0000000..0624460 --- /dev/null +++ b/packages/workbuddy/refresh.test.mjs @@ -0,0 +1,124 @@ +// auth.refresh: magpie renews a browser sign-in ahead of time, through the +// same one-refresh-at-a-time as a request's, and saves what it gives. +import { test, expect, afterAll, beforeAll, afterEach } from "bun:test" +import { homedir, tmpdir } from "node:os" +import { realpathSync } from "node:fs" + +let WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal +beforeAll(async () => { + if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test") + ;({ WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal } = await import("./index.mjs")) +}) +const offline = async () => { throw new Error("no network in tests") } +const real = globalThis.fetch +globalThis.fetch = offline +afterAll(() => (globalThis.fetch = real)) +afterEach(() => { + globalThis.fetch = offline + _internal.renewing.clear() + _internal.renewed.clear() +}) + +const ok = (data) => new Response(JSON.stringify({ code: 0, msg: "ok", data })) + +// serve answers WorkBuddy's refresh (after gate, when given) and chats. +function serve(answer, gate) { + const calls = [] + globalThis.fetch = async (url, init) => { + const u = new URL(String(url)) + calls.push({ url: u, headers: new Headers(init?.headers) }) + if (u.pathname === "/v2/plugin/auth/token/refresh") { + if (gate) await gate + return answer(init) + } + return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } }) + } + return calls +} +const refreshes = (calls) => calls.filter((c) => c.url.pathname === "/v2/plugin/auth/token/refresh") +const soon = () => Date.now() + 3 * 60 * 1000 // within the lead, past EARLY_MS +const auth = (over = {}) => ({ type: "oauth", access: "old", refresh: "r1", expires: soon(), uid: "u1", domain: "", ...over }) +const NEW = { accessToken: "new", refreshToken: "r2", expiresIn: 3600, refreshExpiresIn: 7200 } + +test("auth.refresh renews and gives the new fields, saving nothing itself", async () => { + const calls = serve(() => ok(NEW)) + const sets = [] + const hooks = await WorkBuddyAIAuthPlugin({ client: { auth: { set: async (x) => sets.push(x) } } }) + expect(hooks.auth.refreshLead).toBeGreaterThanOrEqual(60 * 1000) + const got = await hooks.auth.refresh(auth(), "workbuddy-ai") + expect(got.access).toBe("new") + expect(got.refresh).toBe("r2") + expect(got.expires).toBeGreaterThan(Date.now() + 3500 * 1000) + expect(got.refreshExpiresAt).toBeGreaterThan(Date.now() + 7100 * 1000) + expect("type" in got).toBe(false) + expect("uid" in got).toBe(false) + expect(sets).toEqual([]) + const r = refreshes(calls) + expect(r.length).toBe(1) + expect(r[0].url.origin).toBe("https://www.workbuddy.ai") + expect(r[0].headers.get("x-refresh-token")).toBe("r1") +}) + +test("auth.refresh and a request's refresh at once spend the refresh token once", async () => { + let open + const gate = new Promise((ok) => (open = ok)) + const calls = serve(() => ok(NEW), gate) + const sets = [] + const hooks = await WorkBuddyAuthPlugin({ client: { auth: { set: async (x) => sets.push(x) } } }) + const stored = auth({ expires: Date.now() + 30 * 1000 }) // stale for a request too + const opts = await hooks.auth.loader(async () => stored) + const req = opts.fetch("https://copilot.tencent.com/v2/chat/completions", { method: "POST", body: "{}" }) + const hook = hooks.auth.refresh(stored, "workbuddy") + await new Promise((ok) => setTimeout(ok, 10)) + open() + const [res, got] = await Promise.all([req, hook]) + expect(res.status).toBe(200) + expect(got.access).toBe("new") + expect(refreshes(calls).length).toBe(1) + // saved at most once: by the request when it spent the token, else by + // magpie, from what the hook gave + expect(sets.length).toBeLessThanOrEqual(1) + const chat = calls.find((c) => c.url.pathname === "/v2/chat/completions") + expect(chat.headers.get("authorization")).toBe("Bearer new") +}) + +test("auth.refresh after a request renewed the token gives that one", async () => { + const calls = serve(() => ok(NEW)) + const hooks = await WorkBuddyAuthPlugin({ client: { auth: { set: async () => {} } } }) + const stored = auth({ expires: Date.now() + 30 * 1000 }) + await _internal.fresh(_internal.SITES.workbuddy, null, stored) + const got = await hooks.auth.refresh(stored, "workbuddy") + expect(got.access).toBe("new") + expect(refreshes(calls).length).toBe(1) +}) + +test("a refresh token past its end is said plainly, the account not marked", async () => { + const calls = serve(() => ok(NEW)) + const hooks = await WorkBuddyAuthPlugin({ client: {} }) + const e = await hooks.auth.refresh(auth({ refreshExpiresAt: Date.now() - 1000 }), "workbuddy").catch((e) => e) + expect(e).toBeInstanceOf(Error) + expect(e.signIn).toBeUndefined() + expect(e.message).toContain("signed out") + expect(refreshes(calls).length).toBe(0) +}) + +test("a refresh that fails throws plainly, and the next one tries again", async () => { + let fail = true + serve(() => (fail ? new Response("busy", { status: 502 }) : ok(NEW))) + const hooks = await WorkBuddyAuthPlugin({ client: {} }) + const e = await hooks.auth.refresh(auth(), "workbuddy").catch((e) => e) + expect(e).toBeInstanceOf(Error) + expect(e.signIn).toBeUndefined() + expect(e.message).toContain("WorkBuddy token refresh") + fail = false + expect((await hooks.auth.refresh(auth(), "workbuddy")).access).toBe("new") +}) + +test("nothing to renew with gives nothing", async () => { + const calls = serve(() => ok(NEW)) + const hooks = await WorkBuddyAuthPlugin({ client: {} }) + expect(await hooks.auth.refresh(auth({ refresh: "" }), "workbuddy")).toBeUndefined() + expect(await hooks.auth.refresh({ type: "oauth", source: "desktop", refresh: "", access: "", expires: 0, uid: "u" }, "workbuddy")).toBeUndefined() + expect(await hooks.auth.refresh({ type: "api", key: "k" }, "workbuddy")).toBeUndefined() + expect(refreshes(calls).length).toBe(0) +})