diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index 201471b..fb076f7 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -56,6 +56,22 @@ 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. +A chat or usage read WorkBuddy answers 401 (since 0.1.31) is renewed once, +whatever the token's time, and sent once more. A token another process +saved since is taken first instead of spending the refresh token again. A +desktop sign-in is never renewed for it: the app's file is read again, and +its token is used if the app signed in again. A 401 again, or no new +token, ends in a 401 that says to sign in again (Providers → WorkBuddy → +this account's Sign in again in magpie; WorkBuddy desktop for a desktop +sign-in). The plugin marks the account expired in magpie +(`X-Magpie-Sign-In: expired`, usage's `signIn`) only on WorkBuddy's word +that the sign-in is gone: the refresh token refused (401, `invalid_grant`), +or the access token refused (`WWW-Authenticate: … error="invalid_token"`) +with no refresh token left to renew it with or just after renewing. A +failed renewal for another reason, or a bare 401 without `invalid_token`, +leaves the account as it is; a desktop sign-in is never marked. A 401 +after a renewal takes a mark off (`renewed`). + ## Requests Chats are chat completions (`@ai-sdk/openai-compatible`) at `/chat/completions`. diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index a48aa4e..956552f 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -1123,6 +1123,8 @@ function readDesktop(site) { uid: acct.uid, ...(typeof acct.enterpriseId === "string" && acct.enterpriseId.trim() ? { enterpriseId: acct.enterpriseId.trim() } : {}), name: acct.nickname || acct.phoneNumber || acct.uid, + // what the errors below say to do goes by it: sign in to the app again + source: "desktop", } } catch { return null @@ -1237,23 +1239,143 @@ async function unanswered(site, a, body, err, signal) { const size = byteLength(body) if (size <= EDGE_READS) throw err let status = 0 + let challenge = "" try { const res = await meterAsked(site, a, "/billing/meter/get-user-resource-summary", {}, AbortSignal.timeout(20000)) status = res.status + challenge = res.headers.get("www-authenticate") ?? "" await res.body?.cancel() } catch { throw err } if (status !== 401) throw err const mb = (size / (1024 * 1024)).toFixed(1) + const note = `It closes the connection on a refused request over 2 MiB (this one was ${mb} MiB) instead of answering, which is why it read as ECONNRESET.` const message = - `${site.name} refused this account's sign-in (401). It closes the connection on a refused request over 2 MiB ` + - `(this one was ${mb} MiB) instead of answering, which is why it read as ECONNRESET. ` + + `${site.name} refused this account's sign-in (401). ${note} ` + (a.source === "desktop" ? `Sign in to ${site.name} desktop again.` : `Sign in to ${site.name} again in magpie.`) + // the billing API's challenge goes with it: it says whether the token + // itself was refused (invalidToken), as the chat's own 401 would have + const headers = { "content-type": "application/json", ...(challenge ? { "www-authenticate": challenge } : {}) } + const res = new Response(JSON.stringify({ error: { message, type: "authentication_error", code: 401 } }), { + status: 401, + statusText: "Unauthorized", + headers, + }) + edgeNotes.set(res, note) + return res +} + +// edgeNotes is what unanswered's 401s say of the reset, for signedOut to +// say again when the sign-in can't be renewed. +const edgeNotes = new WeakMap() + +// ---- a refused sign-in ---------------------------------------------------------- + +// invalidToken says res is WorkBuddy refusing the access token itself. Its +// front door (APISIX, on both sites) answers a token it doesn't take with +// 401 and WWW-Authenticate: Bearer realm="copilot", error="invalid_token", +// on a chat (streamed or not) and on the billing API alike; measured on +// www.workbuddy.ai on 2026-10-23 with a real account's token cut short, +// and with "garbage". (Its /v3/config answers 200 to any token, so the +// models list never meets a 401.) A 401 without it is not taken as the +// sign-in's: WorkBuddy answers some paths with a bare 401 to an accepted +// sign-in (magpie's check-in, モモコ on Discord). +const invalidToken = (res) => res?.status === 401 && /invalid_token/i.test(res.headers.get("www-authenticate") ?? "") + +// refreshRefused says e is WorkBuddy turning the refresh token itself +// away: HTTP 401 with code 12153, "refresh token failed:400 Bad Request: +// invalid_grant: Invalid refresh token" for a spent or unknown one, or +// "10000:token format error" (measured 2026-10-23). Anything else (a 5xx, +// a timeout) says nothing of the sign-in. +const refreshRefused = (e) => e instanceof WBError && (e.status === 401 || /invalid_grant/i.test(e.message)) + +// reissued is the sign-in to send a request WorkBuddy refused a's access +// token for (401) once more with, before that token's time: WorkBuddy can +// refuse one long before it ends (a browser sign-in's lasts as long as +// its refresh token, about 340 days), and renewing only by time left such +// an account refused on every request for months. It is +// { a }: a sign-in with another access token, to send the request with +// once more; +// { why, kind }: none to be had, why, and of what kind: "refresh +// refused" (WorkBuddy turned the refresh token away too), "nothing to +// renew with" (no refresh token, or one past its end), or "unknown" +// (the refresh failed for another reason, the desktop's token is the +// one refused). +// began is the access token the request read at its start: a stored one +// that isn't it was saved since by someone else (magpie's renewal, +// another of its processes), and is taken rather than renewing again. +// +// A desktop sign-in is the app's: its file is read again, and what was +// renewed here (desktopHeld) is let go, but its refresh token is never +// spent for a refusal, which would sign the app itself out (see +// desktopSignIn). +async function reissued(site, client, getAuth, a, began) { + if (a.source === "desktop") { + desktopHeld.delete(site.id + "|" + a.uid) + const d = readDesktop(site) + if (!d) return { why: notDesktop(site), kind: "unknown" } + if (d.access !== a.access) { + desktopHeld.set(site.id + "|" + d.uid, d) + return { a: d } + } + return { why: `${site.name} desktop's own sign-in is the one refused`, kind: "unknown" } + } + const newer = async () => { + const now = await getAuth().catch(() => null) + return now?.type === "oauth" && now.source !== "desktop" && now.access && now.access !== began && now.access !== a.access ? now : null + } + const saved = await newer() + if (saved) return { a: saved } + if (!refreshable(a)) return { why: a.refresh ? "its refresh token has ended" : "there is no refresh token to renew it with", kind: "nothing to renew with" } + try { + const next = await renew(site, a, async (n) => { + try { + await client?.auth?.set?.({ path: { id: site.id }, body: n }) + } catch {} + }) + return next.access !== a.access ? { a: next } : { why: "renewing it gave the same token", kind: "unknown" } + } catch (e) { + if (refreshRefused(e)) { + // spent by someone else, who saved what it gave + const saved = await newer() + if (saved) return { a: saved } + return { why: `it refused the refresh token too (${e.said ?? e.message})`, kind: "refresh refused" } + } + return { why: `renewing it failed: ${e?.said ?? e?.message ?? e}`, kind: "unknown" } + } +} + +// gone says whether a sign-in reissued (r) couldn't renew is gone, on +// WorkBuddy's word: it turned the refresh token away, or refused the access +// token itself (tokenRefused, invalidToken) with none to renew it with. A +// desktop sign-in never is: the app's file is read on each request, and +// signing in to the app again is all it takes. +const gone = (a, r, tokenRefused) => + a.source !== "desktop" && (r.kind === "refresh refused" || (r.kind === "nothing to renew with" && !!tokenRefused)) + +// refusedText says WorkBuddy refused a's sign-in, why it wasn't renewed, +// and what to do. +function refusedText(site, a, why, note) { + return ( + `${site.name} refused this account's sign-in (401)${why ? "; " + why : ""}. ${note ? note + " " : ""}` + + (a.source === "desktop" + ? `Sign in to ${site.name} desktop again; magpie reads its sign-in on the next request.` + : `Sign in to it again in magpie: Providers → ${site.name} → this account's Sign in again.`) + ) +} + +// signedOut is the answer to a request WorkBuddy refused this account's +// sign-in for, renewed or not: a 401 that says so and what to do, which +// WorkBuddy's own (an HTML page, its {code, msg}) doesn't. expired marks +// the account in magpie (X-Magpie-Sign-In), out of routing and "sign in +// again" on its row, till it is signed in again; else it is kept. +function signedOut(site, a, why, expired, note) { + const message = refusedText(site, a, why, note) return new Response(JSON.stringify({ error: { message, type: "authentication_error", code: 401 } }), { status: 401, statusText: "Unauthorized", - headers: { "content-type": "application/json" }, + headers: { "content-type": "application/json", "X-Magpie-Sign-In": expired ? "expired" : "kept" }, }) } @@ -1267,9 +1389,12 @@ async function meter(site, a, path, body = {}) { } catch {} const code = Number.parseInt(env.code, 10) || 0 if (!res.ok) { - if (code) throw new Error(env.msg || `error ${code}`) - if (env.msg) throw new Error(env.msg) - throw new Error(statusText(res.status)) + // the status and whether the token itself was refused go with it, for + // usage's one renewal on a 401 (reissued) + const said = { status: res.status, invalidToken: invalidToken(res) } + if (code) throw Object.assign(new Error(env.msg || `error ${code}`), said) + if (env.msg) throw Object.assign(new Error(env.msg), said) + throw Object.assign(new Error(statusText(res.status)), said) } if (code) throw new Error(env.msg || `error ${code}`) return env.data ?? null @@ -1671,9 +1796,9 @@ function makePlugin(site) { baseURL: api(site), apiKey: "", async fetch(input, init) { - let a = await getAuth() - if (a?.type !== "oauth") throw new Error(`${site.name} isn't signed in`) - a = await current(site, client, a) + const stored = await getAuth() + if (stored?.type !== "oauth") throw new Error(`${site.name} isn't signed in`) + let a = await current(site, client, stored) const req = input instanceof Request ? input : null const headers = new Headers(init?.headers ?? req?.headers) headers.delete("authorization") @@ -1687,8 +1812,44 @@ function makePlugin(site) { const fit = fitted(body) body = normalizeToolChoice(fit.body) attend(headers, body, session) - const send = (b) => + const post = (b) => fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body: b }).catch((e) => unanswered(site, a, b, e, init?.signal)) + // a 401 is answered once, on whichever try meets it: by a + // sign-in with another access token (reissued), the request + // sent once more with it, never again after that; else, or + // when that is refused too, by signedOut. The body is a + // string here (or bytes), which goes again as it is; one that + // can't be read twice isn't sent again. + // + // The account is marked (expired) only on WorkBuddy's word + // that the sign-in is gone: it turned the refresh token away, + // or refused the access token itself (invalidToken) with none + // to renew it with, or refused even the token just renewed. A + // desktop sign-in is never marked: the app's file is read on + // each request, so signing in to the app again is enough. + let renewed = false + const ours = new WeakSet() // the answers signedOut gave, passed on as they are + const out = (why, expired, res) => { + const r = signedOut(site, a, why, expired && a.source !== "desktop", edgeNotes.get(res)) + ours.add(r) + return r + } + const resendable = (b) => b == null || typeof b === "string" || b instanceof ArrayBuffer || ArrayBuffer.isView(b) + const send = async (b) => { + const res = await post(b) + if (res.status !== 401) return res + if (renewed) return out("it refused the token renewed for it too", invalidToken(res), res) + if (!resendable(b)) return res + await res.body?.cancel().catch(() => {}) + const r = await reissued(site, client, getAuth, a, stored.access) + if (!r.a) return out(r.why, gone(a, r, invalidToken(res)), res) + renewed = true + a = r.a + sign(site, a, headers) + const again = await post(b) + if (again.status !== 401) return again + return out("it refused the token renewed for it too", invalidToken(again), again) + } // a model known to turn tool results then the user's message away // gets the empty reply between them up front (see endsAfterTools) const model = chatOf(body)?.model @@ -1716,20 +1877,43 @@ function makePlugin(site) { res = new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers }) } } - return res.status >= 400 ? explained(res) : kept(await renamed(res, fit.names)) + if (ours.has(res)) return res + // renewed here: a mark the account had comes off + return res.status >= 400 ? explained(res) : kept(await renamed(res, fit.names), renewed ? "renewed" : "kept") }, } }, // the account's credits, as magpie's built-in showed them; each // read keeps the sign-in (signIn), as the built-in's neither marked - // an account lapsed nor cleared it + // an account lapsed nor cleared it, but for a 401 (gone, below) async usage(getAuth) { const auth = await getAuth() if (auth?.type !== "oauth" || !(auth.access || auth.source)) return { error: "not signed in", signIn: "kept" } try { - const a = await current(site, client, auth) + let a = await current(site, client, auth) // the meter has no /v2 prefix, on either site - const sum = await meter(site, a, "/billing/meter/get-user-resource-summary") + const SUMMARY = "/billing/meter/get-user-resource-summary" + // a 401 is answered as a chat's is: once, by a sign-in with + // another access token, else the card says WorkBuddy refused + // the sign-in and what to do; renewed, a mark comes off + let said = "kept" + let sum + try { + sum = await meter(site, a, SUMMARY) + } catch (e) { + if (e?.status !== 401) throw e + const r = await reissued(site, client, getAuth, a, auth.access) + if (!r.a) return { error: refusedText(site, a, r.why), signIn: gone(a, r, e.invalidToken) ? "expired" : "kept" } + a = r.a + try { + sum = await meter(site, a, SUMMARY) + } catch (e) { + if (e?.status !== 401) throw e + const why = "it refused the token renewed for it too" + return { error: refusedText(site, a, why), signIn: a.source !== "desktop" && e.invalidToken ? "expired" : "kept" } + } + said = "renewed" + } const out = usageOf(sum, auth.plan) // an enterprise account's summary has no packages: its credits // are the enterprise meter's (#1904). A personal account's @@ -1740,7 +1924,7 @@ function makePlugin(site) { try { ent = enterpriseUsageOf(await meter(site, a, "/billing/meter/get-enterprise-user-usage")) } catch {} - if (ent) return { plan: auth.plan || "Enterprise", windows: await spareFree(site, a, [ent]), signIn: "kept" } + if (ent) return { plan: auth.plan || "Enterprise", windows: await spareFree(site, a, [ent]), signIn: said } } // when the credits left run out, for routing to spend them first; // a list that can't be read leaves it unknown, the card stands @@ -1751,7 +1935,7 @@ function makePlugin(site) { } catch {} } await spareFree(site, a, out.windows) - return { ...out, signIn: "kept" } + return { ...out, signIn: said } } catch (e) { return { error: e?.message ?? String(e), signIn: "kept" } } @@ -1806,17 +1990,19 @@ const EXHAUSTED_HINT = // another error, and insufficient_quota would rest the account as out of credit. const EXHAUSTED_TEXT = /credits exhausted|额度已用尽|["']code["']\s*:\s*["']?14018(?![\d.])/i -// kept is an answer that went through, saying the sign-in is kept: the -// built-in never cleared a WorkBuddy account's mark, as it never set one. -function kept(res) { +// kept is an answer that went through, saying the sign-in is kept (the +// built-in never cleared a WorkBuddy account's mark, as it never set one), +// or "renewed" when it went through on a sign-in renewed for a 401, which +// takes a mark off (see signedOut). +function kept(res, said = "kept") { const headers = new Headers(res.headers) - headers.set("X-Magpie-Sign-In", "kept") + headers.set("X-Magpie-Sign-In", said) return new Response(res.body, { status: res.status, statusText: res.statusText, headers }) } // explained is res with REFUSED_HINT, RESTRICTED_HINT or EXHAUSTED_HINT added to that refusal's message. -// Each refusal says the sign-in is kept: the built-in passed WorkBuddy's -// 401 on and never marked a WorkBuddy account lapsed. +// Each refusal says the sign-in is kept: a 401 never comes here, it is +// signedOut's. async function explained(res) { const text = await res.text() const again = (b) => { diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 7752de5..f2670d6 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.30", + "version": "0.1.31", "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/reset.test.mjs b/packages/workbuddy/reset.test.mjs index 09fc34c..7f330b7 100644 --- a/packages/workbuddy/reset.test.mjs +++ b/packages/workbuddy/reset.test.mjs @@ -85,7 +85,8 @@ test("a refused sign-in on a chat past 2 MiB says the 401, not ECONNRESET", asyn expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") const { error } = await res.json() expect(error.message).toContain("refused this account's sign-in (401)") - expect(error.message).toContain("Sign in to WorkBuddy AI again") + expect(error.message).toContain("which is why it read as ECONNRESET") + expect(error.message).toContain("Sign in to it again in magpie") expect(meterAsked).toBe(1) }) @@ -93,7 +94,7 @@ test("the China build's front door is read the same way", async () => { meterAsked = 0 const res = await chat("refused", EDGE_READS + 100_000, WorkBuddyAuthPlugin, "https://copilot.tencent.com") expect(res.status).toBe(401) - expect((await res.json()).error.message).toContain("Sign in to WorkBuddy again") + expect((await res.json()).error.message).toContain("Providers → WorkBuddy →") expect(meterAsked).toBe(1) }) @@ -101,7 +102,8 @@ test("a refused sign-in on a short chat is the front door's own 401, nothing els meterAsked = 0 const res = await chat("refused", 1000) expect(res.status).toBe(401) - expect(await res.text()).toContain("401 Authorization Required") + // with no refresh token to renew it with, said so (unauthorized.test.mjs) + expect((await res.json()).error.message).toContain("there is no refresh token to renew it with") expect(meterAsked).toBe(0) }) diff --git a/packages/workbuddy/signin.test.mjs b/packages/workbuddy/signin.test.mjs index 9707459..1e71f8b 100644 --- a/packages/workbuddy/signin.test.mjs +++ b/packages/workbuddy/signin.test.mjs @@ -1,7 +1,8 @@ // What a failure means for the sign-in, as magpie's built-in WorkBuddy -// account had it: WorkBuddy's own 401 was passed on and no WorkBuddy -// account was ever marked lapsed, so every refusal says X-Magpie-Sign-In: -// kept; a token that couldn't be renewed fails in wbFresh's words. +// account had it: every refusal but a 401 says X-Magpie-Sign-In: kept; a +// token that couldn't be renewed fails in wbFresh's words. A 401 is +// unauthorized.test.mjs's: renewed once, and marked only on WorkBuddy's +// word that the sign-in is gone. import { afterEach, expect, test } from "bun:test" import { WorkBuddyAIAuthPlugin, _internal } from "./index.mjs" @@ -17,11 +18,15 @@ const ask = async (reply) => { return opts.fetch("https://www.workbuddy.ai/v2/chat/completions", { method: "POST", body: '{"messages":[]}' }) } -test("WorkBuddy's 401 goes on as it came, the account kept", async () => { +// this fake answers the refresh with the same 401: the refresh token is +// turned away too, which is WorkBuddy's word that the sign-in is gone +test("WorkBuddy's 401 with its refresh refused too says to sign in again, the account marked", async () => { const res = await ask(() => new Response('{"code":401,"msg":"token invalid"}', { status: 401 })) expect(res.status).toBe(401) - expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") - expect(await res.text()).toBe('{"code":401,"msg":"token invalid"}') + expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") + const { error } = await res.json() + expect(error.message).toContain("WorkBuddy AI refused this account's sign-in (401); it refused the refresh token too (token invalid)") + expect(error.message).toContain("Sign in to it again in magpie") }) test("the channel refusal keeps the account too", async () => { diff --git a/packages/workbuddy/unauthorized.test.mjs b/packages/workbuddy/unauthorized.test.mjs new file mode 100644 index 0000000..7a3ef8c --- /dev/null +++ b/packages/workbuddy/unauthorized.test.mjs @@ -0,0 +1,251 @@ +// A chat WorkBuddy answers 401 is renewed once and sent once more, before +// the token's time: a browser sign-in's token lasts as long as its refresh +// token (about 340 days), and one WorkBuddy refused before then was +// refused on every request for months, renewed by nothing, its 401 passed +// on as WorkBuddy's HTML page (wenchen855443 on X: "with WorkBuddy as the +// provider, requests return a 401"). What WorkBuddy answers is as measured +// on www.workbuddy.ai on 2026-10-23: a token it doesn't take gets 401 with +// WWW-Authenticate error="invalid_token"; a refresh token it doesn't take +// gets HTTP 401 {"code":12153, "msg":"...invalid_grant..."}. +import { test, expect, afterAll, beforeAll, afterEach } from "bun:test" +import { mkdirSync, writeFileSync, rmSync, realpathSync } from "node:fs" +import { homedir, tmpdir } from "node:os" +import { join } from "node:path" + +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() + _internal.desktopHeld.clear() +}) + +const CHAT = "https://www.workbuddy.ai/v2/chat/completions" +const REFRESH = "/v2/plugin/auth/token/refresh" +const SUMMARY = "/billing/meter/get-user-resource-summary" +const later = () => Date.now() + 340 * 86400_000 +const ok = (data) => new Response(JSON.stringify({ code: 0, msg: "OK", data })) +const PAGE = "401 Authorization Required

401 Authorization Required

" +// WorkBuddy's front door refusing a token, as it does +const refusedToken = () => + new Response(PAGE, { status: 401, headers: { "content-type": "text/html; charset=utf-8", "www-authenticate": 'Bearer realm="copilot", error="invalid_token", error_description="invalid token"' } }) +// a 401 that says nothing of the token (as some of WorkBuddy's paths answer an accepted one) +const bare401 = () => new Response(PAGE, { status: 401, headers: { "content-type": "text/html" } }) +const refreshRefused = () => + new Response(JSON.stringify({ code: 12153, msg: "12153:refresh token failed:400 Bad Request: invalid_grant: Invalid refresh token" }), { status: 401 }) +const RENEWED = { accessToken: "new", refreshToken: "r2", expiresIn: 340 * 86400, refreshExpiresIn: 340 * 86400 } +const STREAM = 'data: {"choices":[{"delta":{"content":"ok"}}]}\n\ndata: [DONE]\n\n' + +// serve answers each path with routes[path](headers, body); a chat is +// served while its token is in good, else refused. +function serve({ good = ["new"], refresh = () => ok(RENEWED), chat, meter } = {}) { + const calls = [] + globalThis.fetch = async (url, init) => { + const u = new URL(String(url instanceof Request ? url.url : url)) + const headers = new Headers(init?.headers) + calls.push({ path: u.pathname, headers, body: init?.body }) + const token = (headers.get("authorization") ?? "").replace(/^Bearer /, "") + if (u.pathname === REFRESH) return refresh(headers) + if (u.pathname === SUMMARY) return meter ? meter(token) : good.includes(token) ? ok({ IsPaidUser: false, Packages: [] }) : refusedToken() + if (chat) return chat(token) + return good.includes(token) ? new Response(STREAM, { headers: { "content-type": "text/event-stream" } }) : refusedToken() + } + return calls +} +const of = (calls, path) => calls.filter((c) => c.path === path) + +// ask is one chat through the loader of a browser sign-in stored as auth; +// stored() is what getAuth reads each time (another process may save) +async function ask(auth, { plugin = WorkBuddyAIAuthPlugin, sets = [], stored } = {}) { + const hooks = await plugin({ client: { auth: { set: async (x) => sets.push(x) } } }) + const read = stored ?? (async () => auth) + const opts = await hooks.auth.loader(read) + const body = JSON.stringify({ model: "deepseek-v4.1-flash", stream: true, messages: [{ role: "user", content: "Say ok." }] }) + return opts.fetch(CHAT, { method: "POST", body }) +} +const signedIn = (over = {}) => ({ type: "oauth", access: "old", refresh: "r1", expires: later(), refreshExpiresAt: later(), uid: "u1", domain: "www.workbuddy.ai", ...over }) + +test("a 401 before the token's time is renewed, saved and sent once more, which takes a mark off", async () => { + const calls = serve() + const sets = [] + const res = await ask(signedIn(), { sets }) + expect(res.status).toBe(200) + expect(await res.text()).toBe(STREAM) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed") + const chats = of(calls, "/v2/chat/completions") + expect(chats.map((c) => c.headers.get("authorization"))).toEqual(["Bearer old", "Bearer new"]) + expect(chats[1].body).toBe(chats[0].body) // the same request, again + const r = of(calls, REFRESH) + expect(r.length).toBe(1) + expect(r[0].headers.get("x-refresh-token")).toBe("r1") + expect(sets.length).toBe(1) + expect(sets[0]).toMatchObject({ path: { id: "workbuddy-ai" }, body: { access: "new", refresh: "r2", uid: "u1" } }) +}) + +test("a refresh WorkBuddy turns away too ends in signing in again, the account marked", async () => { + const calls = serve({ refresh: refreshRefused }) + const res = await ask(signedIn()) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") + const { error } = await res.json() + expect(error.type).toBe("authentication_error") + expect(error.message).toBe( + "WorkBuddy AI refused this account's sign-in (401); it refused the refresh token too " + + "(12153:refresh token failed:400 Bad Request: invalid_grant: Invalid refresh token). " + + "Sign in to it again in magpie: Providers → WorkBuddy AI → this account's Sign in again.", + ) + expect(of(calls, "/v2/chat/completions").length).toBe(1) + expect(of(calls, REFRESH).length).toBe(1) +}) + +test("a refresh that fails for another reason says so, the account kept", async () => { + serve({ refresh: () => new Response("busy", { status: 502 }) }) + const res = await ask(signedIn()) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect((await res.json()).error.message).toContain("renewing it failed: Bad Gateway") +}) + +test("a renewed token refused too is not renewed or sent again", async () => { + const calls = serve({ good: [] }) + const res = await ask(signedIn()) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") + expect((await res.json()).error.message).toContain("it refused the token renewed for it too") + expect(of(calls, "/v2/chat/completions").map((c) => c.headers.get("authorization"))).toEqual(["Bearer old", "Bearer new"]) + expect(of(calls, REFRESH).length).toBe(1) +}) + +test("a 401 with no refresh token is said, and marked only when the token itself was refused", async () => { + let calls = serve() + let res = await ask(signedIn({ refresh: "", refreshExpiresAt: 0 })) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") + expect((await res.json()).error.message).toContain("there is no refresh token to renew it with. Sign in to it again in magpie") + expect(of(calls, REFRESH).length).toBe(0) + expect(of(calls, "/v2/chat/completions").length).toBe(1) + + // a refresh token past its end is as none + calls = serve() + res = await ask(signedIn({ refreshExpiresAt: Date.now() - 1000 })) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") + expect((await res.json()).error.message).toContain("its refresh token has ended") + expect(of(calls, REFRESH).length).toBe(0) + + // a 401 that doesn't say the token was refused leaves the account as it is + serve({ chat: bare401 }) + res = await ask(signedIn({ refresh: "" })) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") +}) + +test("a token another process saved since is taken, not renewed again", async () => { + // another process renews and saves while this request is out + let saved = false + const calls = serve({ good: ["theirs"], chat: (t) => (t === "theirs" ? new Response(STREAM) : ((saved = true), refusedToken())) }) + const stored = async () => (saved ? signedIn({ access: "theirs", refresh: "r9" }) : signedIn()) + const res = await ask(null, { stored }) + expect(res.status).toBe(200) + expect(of(calls, REFRESH).length).toBe(0) + expect(of(calls, "/v2/chat/completions").map((c) => c.headers.get("authorization"))).toEqual(["Bearer old", "Bearer theirs"]) +}) + +test("a refresh token another process spent while this one renewed: the one it saved is taken", async () => { + let spent = false + const calls = serve({ good: ["theirs"], refresh: () => ((spent = true), refreshRefused()) }) + const stored = async () => (spent ? signedIn({ access: "theirs", refresh: "r9" }) : signedIn()) + const res = await ask(null, { stored }) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed") + expect(of(calls, "/v2/chat/completions").map((c) => c.headers.get("authorization"))).toEqual(["Bearer old", "Bearer theirs"]) +}) + +test("a 401 on a later try of the same request (after a 400 the request is sent again for) isn't renewed twice", async () => { + // the system prompt refused as an unapproved channel, then the renewed token refused + let chats = 0 + const calls = serve({ + chat: (token) => { + chats++ + if (chats === 1) return refusedToken() + if (chats === 2) return new Response(JSON.stringify({ code: 11004, msg: "Illegal API invocation from an unapproved channel" }), { status: 400 }) + return refusedToken() + }, + }) + const hooks = await WorkBuddyAIAuthPlugin({ client: {} }) + const opts = await hooks.auth.loader(async () => signedIn()) + const body = JSON.stringify({ model: "m", messages: [{ role: "system", content: "You are X." }, { role: "user", content: "hi" }] }) + const res = await opts.fetch(CHAT, { method: "POST", body }) + expect(res.status).toBe(401) + expect((await res.json()).error.message).toContain("it refused the token renewed for it too") + expect(of(calls, REFRESH).length).toBe(1) + expect(chats).toBe(3) +}) + +function desktopFile(name, info) { + const dir = process.platform === "darwin" ? join(homedir(), "Library", "Application Support", "CodeBuddyExtension") + : process.platform === "win32" ? join(homedir(), "AppData", "Local", "CodeBuddyExtension") : join(homedir(), ".local", "share", "CodeBuddyExtension") + mkdirSync(join(dir, "Data", "Public", "auth"), { recursive: true }) + const file = join(dir, "Data", "Public", "auth", name) + writeFileSync(file, JSON.stringify(info)) + return file +} +const desk = (access) => ({ auth: { accessToken: access, refreshToken: "desk-refresh", expiresAt: Date.now() + 3600_000, domain: "www.workbuddy.ai" }, account: { uid: "d1", nickname: "D" } }) +const DESKTOP = { type: "oauth", access: "", refresh: "", expires: 0, source: "desktop", uid: "d1" } + +test("a desktop sign-in refused reads the app's file again: its new token is taken, its refresh token never spent", async () => { + const file = desktopFile("workbuddy-desktop-ai.info", desk("desk-old")) + try { + // what was renewed here before is the one refused + _internal.desktopHeld.set("workbuddy-ai|d1", { access: "held", refresh: "x", expires: Date.now() + 7200_000, uid: "d1", source: "desktop" }) + // the app signed in again meanwhile + writeFileSync(file, JSON.stringify(desk("desk-new"))) + const calls = serve({ good: ["desk-new"] }) + const res = await ask(DESKTOP) + expect(res.status).toBe(200) + expect(of(calls, "/v2/chat/completions").map((c) => c.headers.get("authorization"))).toEqual(["Bearer held", "Bearer desk-new"]) + expect(of(calls, REFRESH).length).toBe(0) + expect(_internal.desktopHeld.get("workbuddy-ai|d1").access).toBe("desk-new") + } finally { + rmSync(file, { force: true }) + } +}) + +test("a desktop sign-in whose own token is refused says to sign in to the app again, never marked", async () => { + const file = desktopFile("workbuddy-desktop-ai.info", desk("desk-old")) + try { + const calls = serve({ good: [] }) + const res = await ask(DESKTOP) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect((await res.json()).error.message).toContain("Sign in to WorkBuddy AI desktop again") + expect(of(calls, REFRESH).length).toBe(0) + expect(of(calls, "/v2/chat/completions").length).toBe(1) + } finally { + rmSync(file, { force: true }) + } +}) + +test("usage meets a 401 the same way: renewed once and read again", async () => { + const calls = serve({ meter: (t) => (t === "new" ? ok({ IsPaidUser: true, Packages: [{ CycleTotalCapacity: "100", CycleUsedCapacity: "10" }] }) : refusedToken()) }) + const hooks = await WorkBuddyAuthPlugin({ client: {} }) + const out = await hooks.auth.usage(async () => signedIn()) + expect(out).toMatchObject({ plan: "Pro", signIn: "renewed" }) + expect(out.windows[0].used).toBe(10) + expect(of(calls, REFRESH).length).toBe(1) +}) + +test("usage whose refresh is turned away says to sign in again, the account marked", async () => { + serve({ refresh: refreshRefused }) + const hooks = await WorkBuddyAuthPlugin({ client: {} }) + const out = await hooks.auth.usage(async () => signedIn()) + expect(out.signIn).toBe("expired") + expect(out.error).toContain("WorkBuddy refused this account's sign-in (401); it refused the refresh token too") +}) diff --git a/packages/workbuddy/usage.test.mjs b/packages/workbuddy/usage.test.mjs index 8ada4ee..285076d 100644 --- a/packages/workbuddy/usage.test.mjs +++ b/packages/workbuddy/usage.test.mjs @@ -80,8 +80,10 @@ test("counts and plans as Go says them", () => { test("WorkBuddy's refusals are the card's error", async () => { const auth = { type: "oauth", access: "a", expires: later(), uid: "u" } + // a bare 401 (no invalid_token) with nothing to renew with: said, not marked serve({ "/billing/meter/get-user-resource-summary": () => new Response("", { status: 401 }) }) - expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ signIn: "kept", error: "Unauthorized" }) + expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ signIn: "kept", + error: "WorkBuddy refused this account's sign-in (401); there is no refresh token to renew it with. Sign in to it again in magpie: Providers → WorkBuddy → this account's Sign in again." }) serve({ "/billing/meter/get-user-resource-summary": () => new Response(JSON.stringify({ code: 10085, msg: "" }), { status: 403 }) }) expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ signIn: "kept", error: "error 10085" }) serve({ "/billing/meter/get-user-resource-summary": () => new Response(JSON.stringify({ code: 11001, msg: "token expired" })) })