diff --git a/packages/commandcode/errors.test.mjs b/packages/commandcode/errors.test.mjs index 9a771d1..fbb955e 100644 --- a/packages/commandcode/errors.test.mjs +++ b/packages/commandcode/errors.test.mjs @@ -28,6 +28,19 @@ async function ask(reply, stream = false) { return { status: res.status, message: (await res.json()).error?.message } } +// asks as ask does, with every answer's X-Magpie-Sign-In +async function signIn(reply, plan = "Go", path = "/alpha/generate") { + globalThis.fetch = async (url) => (new URL(String(url)).pathname === path ? reply() : new Response("", { status: 404 })) + const auth = { type: "api", key: "key", metadata: { plan } } + const hooks = await CommandCodePlugin() + const opts = await hooks.auth.loader(async () => auth) + const res = await opts.fetch("https://api.commandcode.ai/provider/v1/chat/completions", { + method: "POST", + body: JSON.stringify({ model: "deepseek/deepseek-v4-pro", messages: [{ role: "user", content: "hi" }] }), + }) + return { status: res.status, signIn: res.headers.get("X-Magpie-Sign-In") } +} + test("an empty 429 reads as Go's http.StatusText says it, which quotaWords knows", async () => { expect(await ask(() => new Response("", { status: 429 }))).toEqual({ status: 429, message: "Too Many Requests" }) }) @@ -46,3 +59,20 @@ test("an error line before any content keeps its status", async () => { const line = JSON.stringify({ type: "error", error: { message: '429 {"error":{"message":"RATE_LIMITED: slow down"}}' } }) expect(await ask(() => new Response(line + "\n"), true)).toEqual({ status: 429, message: "RATE_LIMITED: slow down" }) }) + +// the built-in never marked a Command Code account lapsed: a 401 of +// /alpha/generate's (cmdFailure) or of the Provider API's goes on with it kept +test("a Go key Command Code turns away is a 401, the account kept", async () => { + expect(await signIn(() => Response.json({ error: { message: "Invalid API key" } }, { status: 401 }))).toEqual({ status: 401, signIn: "kept" }) +}) + +test("an error line saying 401 keeps the account too", async () => { + const line = JSON.stringify({ type: "error", error: { message: "Unauthorized", statusCode: 401 } }) + expect(await signIn(() => new Response(line + "\n"))).toEqual({ status: 401, signIn: "kept" }) +}) + +test("the Provider API's 401 goes on as it came, the account kept", async () => { + expect(await signIn(() => Response.json({ error: { message: "Invalid API key" } }, { status: 401 }), "Pro", "/provider/v1/chat/completions")) + .toEqual({ status: 401, signIn: "kept" }) + expect(await signIn(() => Response.json({}), "Pro", "/provider/v1/chat/completions")).toEqual({ status: 200, signIn: null }) +}) diff --git a/packages/commandcode/index.mjs b/packages/commandcode/index.mjs index bbb617c..6662964 100644 --- a/packages/commandcode/index.mjs +++ b/packages/commandcode/index.mjs @@ -719,12 +719,24 @@ function streamError(e) { return failure(status || 500, msg) } +// errorResponse is a failure as the built-in answered it, the account +// kept: the built-in never marked a Command Code account lapsed, a 401 of +// Command Code's among them. const errorResponse = ({ status, message }) => new Response(JSON.stringify({ error: { message, type: "commandcode_error", code: status } }), { status, - headers: { "Content-Type": "application/json" }, + headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "kept" }, }) +// kept is a Provider API answer, as it came, saying the account is kept. +function kept(res) { + const headers = new Headers(res.headers) + headers.delete("content-length") + headers.delete("content-encoding") + headers.set("X-Magpie-Sign-In", "kept") + return new Response(res.body, { status: res.status, statusText: res.statusText, headers }) +} + // lines reads the reply a JSON object a line. async function* lines(body) { const dec = new TextDecoder() @@ -907,7 +919,9 @@ export async function CommandCodePlugin({ client } = {}) { } return generate(key, chat, init.signal) } - return fetch(input, { ...init, headers }) + // the Provider API's 401 went on as it came, the account kept + const res = await fetch(input, { ...init, headers }) + return res.status === 401 ? kept(res) : res }, } }, diff --git a/packages/commandcode/package.json b/packages/commandcode/package.json index 919eaa3..df157ea 100644 --- a/packages/commandcode/package.json +++ b/packages/commandcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-commandcode-auth", - "version": "0.1.4", + "version": "0.1.5", "description": "Command Code plans (Pro, GOAT, Max, Ultra, Go, Teams) in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/cursor/errors.test.mjs b/packages/cursor/errors.test.mjs index beb084b..7de05c7 100644 --- a/packages/cursor/errors.test.mjs +++ b/packages/cursor/errors.test.mjs @@ -4,7 +4,7 @@ import { expect, test } from "bun:test" import { _internal } from "./index.mjs" -const { failure } = _internal +const { failure, errorResponse } = _internal test("an HTTP error that says nothing is worded as Go's status text", () => { expect(failure(402, "")).toEqual({ status: 402, message: "Payment Required" }) @@ -21,6 +21,25 @@ test("the codes and words map as the built-in's cursorStatus", () => { expect(failure(200, end("unavailable", "busy"))).toEqual({ status: 503, message: "busy" }) expect(failure(200, end("permission_denied", "no"))).toEqual({ status: 403, message: "no" }) expect(failure(200, end("internal", "boom"))).toEqual({ status: 502, message: "boom" }) - expect(failure(401, "")).toEqual({ status: 401, message: "Unauthorized — sign in to Cursor again" }) - expect(failure(200, end("unauthenticated", "Error"))).toEqual({ status: 401, message: "unauthenticated — sign in to Cursor again" }) + expect(failure(401, "")).toEqual({ status: 401, message: "Unauthorized — sign in to Cursor again in magpie" }) + expect(failure(200, end("unauthenticated", "Error"))).toEqual({ status: 401, message: "unauthenticated — sign in to Cursor again in magpie" }) +}) + +// The built-in answered any "expired" with a 401 and marked nothing; here a +// token or session run out marks the account (a plain 401), anything else +// run out — a trial, a plan — is the same 401 with X-Magpie-Sign-In: kept. +test("any expired is the built-in's 401; only a sign-in run out marks the account", () => { + const end = (code, message) => JSON.stringify({ error: { code, message } }) + expect(failure(200, end("failed_precondition", "Your free trial has expired"))).toEqual({ + status: 401, message: "Your free trial has expired — sign in to Cursor again in magpie", signIn: "kept" }) + expect(failure(400, end("", "Your session has expired"))).toEqual({ + status: 401, message: "Your session has expired — sign in to Cursor again in magpie" }) + expect(failure(401, "")).not.toHaveProperty("signIn") +}) + +test("the answer carries what it means for the sign-in", async () => { + const res = errorResponse({ status: 401, message: "Your plan has expired", signIn: "kept" }) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect(errorResponse({ status: 401, message: "x" }).headers.get("X-Magpie-Sign-In")).toBeNull() }) diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index 5382dae..73c368a 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -158,9 +158,10 @@ async function cliTokenNow() { await cliRefresh tok = await cliToken() } - if (!tok) throw new AuthError("Cursor isn't signed in: run `cursor-agent login`, or sign in again") + // the built-in's words (provider.CursorToken) + if (!tok) throw new AuthError("Cursor isn't signed in; sign in from magpie's Providers page or run `cursor-agent login`") const e = expiry(tok) - if (e && e <= Date.now()) throw new AuthError("Cursor's sign-in has run out: run `cursor-agent login`, or sign in again") + if (e && e <= Date.now()) throw new AuthError("Cursor's sign-in has run out; sign in again from magpie's Providers page or run `cursor-agent login`") return tok } @@ -847,21 +848,22 @@ function failure(status, text) { return statusOf(status, f.code ?? "", msg) } -// signInExpired is a message of a token or session run out; a trial, a -// plan or a link run out is no lapsed sign-in, and magpie marks the -// account lapsed on a 401. +// signInExpired is a message of a token or session run out. The built-in +// answered any "expired" with a 401, but a trial, a plan or a link run out +// is no lapsed sign-in: that 401 says "kept" (X-Magpie-Sign-In). const signInExpired = (low) => low.includes("expired") && /token|session|sign[- ]?in|log[- ]?in|auth|credential/.test(low) // statusOf is the status and words for Cursor's error of this code and // message. A region the team isn't served in says so, not to sign in. function statusOf(status, code, msg) { - msg ||= statusText(status) || `HTTP ${status}` + msg ||= statusText(status) const low = msg.toLowerCase() // magpie names the provider before the message itself - const out = (status, message) => ({ status, message }) + const out = (status, message, signIn) => ({ status, message, ...(signIn ? { signIn } : {}) }) if (regional(msg)) return out(403, msg + " — Cursor serves your team only in some regions and turned this request away; signing in again won't change that") if (code === "permission_denied") return out(403, msg) - if (code === "unauthenticated" || status === 401 || signInExpired(low)) return out(401, msg + " — sign in to Cursor again") + if (code === "unauthenticated" || status === 401 || low.includes("expired")) + return out(401, msg + " — sign in to Cursor again in magpie", code === "unauthenticated" || status === 401 || signInExpired(low) ? undefined : "kept") if (code === "resource_exhausted" || low.includes("quota") || low.includes("rate limit") || low.includes("usage limit")) return out(429, "usage limit reached: " + msg) if (low.includes("too long") || low.includes("context length") || low.includes("too many tokens")) @@ -1357,10 +1359,12 @@ function exec(msg, tools, send, closeExec) { // ---- chat completions ------------------------------------------------------------------ -const errorResponse = ({ status, message }) => +// signIn, the X-Magpie-Sign-In header, says what the answer means for the +// account whatever its status: "kept" leaves it unmarked. +const errorResponse = ({ status, message, signIn }) => new Response(JSON.stringify({ error: { message, type: "cursor_error", code: status } }), { status, - headers: { "Content-Type": "application/json" }, + headers: { "Content-Type": "application/json", ...(signIn ? { "X-Magpie-Sign-In": signIn } : {}) }, }) // answer runs a chat completion on Cursor and answers it as one, streamed @@ -1522,4 +1526,4 @@ export async function CursorAuthPlugin() { } // for tests -export const _internal = { poolBase, splitID, families, byEffort, offered, modelID, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry } +export const _internal = { errorResponse, poolBase, splitID, families, byEffort, offered, modelID, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry } diff --git a/packages/cursor/package.json b/packages/cursor/package.json index b1b2047..aeb7f0f 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.1.4", + "version": "0.1.5", "description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to", "type": "module", "main": "./index.mjs", diff --git a/packages/cursor/usage.test.mjs b/packages/cursor/usage.test.mjs index b44653e..31e91b9 100644 --- a/packages/cursor/usage.test.mjs +++ b/packages/cursor/usage.test.mjs @@ -115,13 +115,16 @@ test("a run-out sign-in says so, and asks nothing", async () => { // magpie marks a plugin's account lapsed on any 401, so only a sign-in // that is gone says 401 +// the built-in's 401 for any "expired"; X-Magpie-Sign-In keeps the account +// when what ran out was no sign-in test("an expired token is a lapsed sign-in; an expired trial is not", () => { const { failure } = _internal const says = (msg) => failure(400, JSON.stringify({ code: "failed_precondition", message: msg })) - expect(says("Your access token has expired").status).toBe(401) - expect(says("Session expired, please log in again").status).toBe(401) - expect(says("Your free trial has expired").status).toBe(502) - expect(says("This link has expired").status).toBe(502) + expect(says("Your access token has expired")).toMatchObject({ status: 401 }) + expect(says("Your access token has expired")).not.toHaveProperty("signIn") + expect(says("Session expired, please log in again")).not.toHaveProperty("signIn") + expect(says("Your free trial has expired")).toMatchObject({ status: 401, signIn: "kept" }) + expect(says("This link has expired")).toMatchObject({ status: 401, signIn: "kept" }) }) // the gateway names the provider before a plugin's error diff --git a/packages/devin/errors.test.mjs b/packages/devin/errors.test.mjs index 2fc947d..0904b30 100644 --- a/packages/devin/errors.test.mjs +++ b/packages/devin/errors.test.mjs @@ -30,7 +30,7 @@ const ask = async (reply, stream = false) => { { key: "k", server: "https://devin.test", families: _internal.familiesOf(_internal.SNAPSHOT) }, { model: "swe-2", stream, messages: [{ role: "user", content: "hi" }] }, ) - return { status: res.status, body: await res.text() } + return { status: res.status, body: await res.text(), signIn: res.headers.get("X-Magpie-Sign-In") } } const errOf = (r) => JSON.parse(r.body).error.message @@ -52,10 +52,30 @@ test("a too-long conversation is the built-in's 400", async () => { expect(errOf(r)).toBe("input is too long for the model's context: prompt is too long") }) -test("a refused key is the 401 magpie marks the account lapsed on", async () => { +// the built-in answered it 401 and left the account as it was +test("a refused key is the built-in's 401, the account kept", async () => { const r = await ask(() => new Response(JSON.stringify({ code: "unauthenticated", message: "bad key" }), { status: 401 })) expect(r.status).toBe(401) expect(errOf(r)).toBe("bad key — sign in to Devin again") + expect(r.signIn).toBe("kept") +}) + +test("unauthenticated at the stream's end is a 401 that keeps the account too", async () => { + const r = await ask(() => new Response(end({ error: { code: "unauthenticated", message: "key revoked" } }))) + expect(r.status).toBe(401) + expect(errOf(r)).toBe("key revoked — sign in to Devin again") + expect(r.signIn).toBe("kept") +}) + +test("no key to send is a 401 that keeps the account", async () => { + const { DevinAuthPlugin } = await import("./index.mjs") + const hooks = await DevinAuthPlugin() + let auth = { type: "api", key: "k", metadata: {} } + const opts = await hooks.auth.loader(async () => auth) + auth = null + const res = await opts.fetch("https://devin.test/v1/chat/completions", { method: "POST", body: "{}" }) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") }) test("an empty reply is the built-in's 502 of a broken-off one", async () => { diff --git a/packages/devin/index.mjs b/packages/devin/index.mjs index a8d817d..1416a95 100644 --- a/packages/devin/index.mjs +++ b/packages/devin/index.mjs @@ -1005,10 +1005,14 @@ async function* events(it) { } } +// errorResponse is a failure as the built-in answered it. None marks the +// account lapsed: the built-in's 401s (a key Devin turned away, none to +// send) were answered without touching the account, so each says +// X-Magpie-Sign-In: kept. const errorResponse = ({ status, message }) => new Response(JSON.stringify({ error: { message, type: "devin_error", code: status } }), { status, - headers: { "Content-Type": "application/json" }, + headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "kept" }, }) // complete answers a chat completion through GetChatMessage. diff --git a/packages/devin/package.json b/packages/devin/package.json index 943f2f8..0c13a92 100644 --- a/packages/devin/package.json +++ b/packages/devin/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-devin-auth", - "version": "0.1.4", + "version": "0.1.5", "description": "Devin subscriptions (the devin CLI's account) in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/factory/index.mjs b/packages/factory/index.mjs index be1a406..725a612 100644 --- a/packages/factory/index.mjs +++ b/packages/factory/index.mjs @@ -123,15 +123,6 @@ function expiry(access) { return typeof exp === "number" && exp > 0 ? Math.floor(exp) * 1000 : 0 } -function apiError(text, fallback) { - try { - const j = JSON.parse(text) - const m = j?.error?.message ?? j?.error_description ?? j?.message ?? j?.detail ?? (typeof j?.error === "string" ? j.error : "") - if (m) return String(m) - } catch {} - return text.trim().slice(0, 300) || fallback -} - // workos posts a form to WorkOS: the answer and its status. async function workos(path, form, signal) { const res = await fetch(WORKOS + path, { @@ -152,7 +143,7 @@ async function authenticate(form, signal) { t = JSON.parse(text) ?? {} } catch {} t.status = status - if (status !== 200 && !t.error) throw new FactoryStatus(status, "Factory sign-in: " + apiError(text, String(status))) + if (status !== 200 && !t.error) throw new FactoryStatus(status, "Factory sign-in: " + vendorError(text, STATUS_CODES[status] ?? "")) return t } @@ -198,7 +189,7 @@ async function factoryGet(c, path) { factoryHeaders(h, c) const res = await fetch(base(c) + path, { headers: h, signal: AbortSignal.timeout(30_000) }) const text = await res.text() - if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " + apiError(text, String(res.status))) + if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " + vendorError(text, statusLine(res.status))) return JSON.parse(text) } @@ -217,7 +208,7 @@ async function whoami(c, signal) { if (c.activeOrganizationId) h["X-Factory-Org-Id"] = c.activeOrganizationId const res = await fetch(base(c) + "/api/cli/whoami", { headers: h, signal: signal ?? AbortSignal.timeout(10_000) }) const text = await res.text() - if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " + apiError(text, String(res.status))) + if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " + vendorError(text, statusLine(res.status))) return JSON.parse(text) ?? {} } @@ -268,6 +259,15 @@ function errorReply(url, status, type, message, headers = new Headers()) { return new Response(JSON.stringify(body), { status, headers }) } +// said is an answer with magpie's X-Magpie-Sign-In, which tells what it +// means for the account's sign-in whatever its status: "expired" marks it +// lapsed, "kept" leaves it be. magpie takes it off before the agent sees it. +function said(res, v) { + const h = new Headers(res.headers) + h.set("X-Magpie-Sign-In", v) + return new Response(res.body, { status: res.status, statusText: res.statusText, headers: h }) +} + // ---- sign-in ---------------------------------------------------------------- // signedInWith is the account WorkOS just signed in, as droid keeps it: a @@ -319,7 +319,7 @@ async function signedInWith(t) { async function deviceSignIn() { const { text, status } = await workos("/authorize/device", { client_id: CLIENT_ID }) - if (status !== 200) throw new FactoryStatus(status, "Factory sign-in: " + apiError(text, String(status))) + if (status !== 200) throw new FactoryStatus(status, "Factory sign-in: " + vendorError(text, STATUS_CODES[status] ?? "")) const dc = JSON.parse(text) if (!dc.device_code || !dc.user_code) throw new Error("Factory's sign-in gave no device code") let interval = Math.max(dc.interval ?? 0, 1) * 1000 @@ -502,8 +502,9 @@ export const FactoryAuthPlugin = async ({ client }) => { return c } - // fresh is a live token, renewed near its end. - const fresh = () => + // fresh is a live token, renewed near its end; renewed is told when + // it was, the built-in's clearing of the account's lapse. + const fresh = (renewed) => locked(async () => { const c = await current() if ((c.expires > 0 && Date.now() < c.expires - REFRESH_LEAD) || !c.refresh) return orgOf(c) @@ -523,6 +524,7 @@ export const FactoryAuthPlugin = async ({ client }) => { await reconcile(c) ask(c) await save(c) + renewed?.() return c }) @@ -530,8 +532,9 @@ export const FactoryAuthPlugin = async ({ client }) => { // can't reach is left off and whoami asked again without it; with // no header sent, the token is put in the first org /api/cli/org // lists. Any other 403 to an account that sent no org asks whoami - // for one. True when the request is worth sending again. - const mendOrg = (status, text) => + // for one. True when the request is worth sending again; renewed is + // told when the token was. + const mendOrg = (status, text, renewed) => locked(async () => { if (status !== 403) return false const isOrg = orgRefused(status, text) @@ -570,6 +573,7 @@ export const FactoryAuthPlugin = async ({ client }) => { c.orgId = org if (t.refresh_token) c.refresh = t.refresh_token await save(c) + renewed?.() return true }) @@ -634,8 +638,8 @@ export const FactoryAuthPlugin = async ({ client }) => { const { fresh, mendOrg } = account(getAuth) - const send = async (input, init, body) => { - const c = await fresh() + const send = async (input, init, body, renewed) => { + const c = await fresh(renewed) let url = input instanceof Request ? input.url : String(input) // an EU org is served from Factory's EU region, an on-prem one // from its own host: the request goes there @@ -665,25 +669,32 @@ export const FactoryAuthPlugin = async ({ client }) => { if (body == null && input instanceof Request && input.body) body = new Uint8Array(await input.arrayBuffer()) if (body instanceof ReadableStream) body = new Uint8Array(await new Response(body).arrayBuffer()) const url = input instanceof Request ? input.url : String(input) + // the built-in takes an account's lapse off when it renews the + // token, and never for an answer: a 401 of Factory's leaves it + // be, and so does a success with no renewal on the way + let renewed = false + const onRenew = () => (renewed = true) + const answer = (res) => (renewed && res.status >= 200 && res.status < 300 ? res : said(res, "kept")) let res try { - res = await send(input, init, body) + res = await send(input, init, body, onRenew) + if (res.status !== 403) return answer(res) + let text = await res.text() + if (await mendOrg(res.status, text, onRenew).catch(() => false)) { + res = await send(input, init, body, onRenew) + if (res.status !== 403) return answer(res) + text = await res.text() + } + const why = explain(res.status, text) + // the refusal, then what to do about it, as provider.Explain joins them + const msg = `${vendorError(text, statusLine(res.status))} — ${why}` + return answer(errorReply(url, res.status, "permission_error", msg, new Headers(res.headers))) } catch (e) { - // Factory refused to renew the sign-in: the account's own 401 - if (e?.lapsed) return errorReply(url, 401, "authentication_error", e.message) + // Factory refused to renew the sign-in: the built-in failed the + // request (magpie's 502) and marked the account lapsed + if (e?.lapsed) return said(errorReply(url, 502, "api_error", e.message), "expired") throw e } - if (res.status !== 403) return res - let text = await res.text() - if (await mendOrg(res.status, text).catch(() => false)) { - res = await send(input, init, body) - if (res.status !== 403) return res - text = await res.text() - } - const why = explain(res.status, text) - // the refusal, then what to do about it, as provider.Explain joins them - const msg = `${apiError(text, "403 Forbidden")} — ${why}` - return errorReply(url, res.status, "permission_error", msg, new Headers(res.headers)) }, } }, diff --git a/packages/factory/lapsed.test.mjs b/packages/factory/lapsed.test.mjs index 1ced49b..751c212 100644 --- a/packages/factory/lapsed.test.mjs +++ b/packages/factory/lapsed.test.mjs @@ -1,5 +1,8 @@ // An account whose sign-in Factory won't renew answers as the built-in's -// does: a 401 in the shape of the API the request was for, not a throw. +// does: magpie's 502 in the shape of the API the request was for, not a +// throw, with X-Magpie-Sign-In: expired so magpie marks the account lapsed +// as factoryLapse did. Factory's own answers leave the mark as the built-in +// did: only a renewal takes it off. import { afterEach, expect, test } from "bun:test" import { FactoryAuthPlugin } from "./index.mjs" @@ -32,23 +35,25 @@ async function loaded() { return { l, seen } } -test("a refused renewal is Anthropic's 401 on /llm/a/", async () => { +test("a refused renewal is Anthropic's 502 on /llm/a/, marking the account", async () => { const { l, seen } = await loaded() const res = await l.fetch("https://api.factory.ai/api/llm/a/v1/messages", { method: "POST", body: JSON.stringify({ model: "claude-x" }) }) - expect(res.status).toBe(401) + expect(res.status).toBe(502) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") const b = await res.json() expect(b.type).toBe("error") - expect(b.error.type).toBe("authentication_error") - expect(b.error.message).toContain("sign in") + expect(b.error.type).toBe("api_error") + expect(b.error.message).toBe("ada's Factory sign-in has expired — sign in again (Factory: invalid_grant)") expect(seen.some((p) => p.includes("/llm/"))).toBe(false) }) test("and OpenAI's on /llm/o/", async () => { const { l } = await loaded() const res = await l.fetch("https://api.factory.ai/api/llm/o/v1/responses", { method: "POST", body: JSON.stringify({ model: "gpt-x" }) }) - expect(res.status).toBe(401) + expect(res.status).toBe(502) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") const b = await res.json() - expect(b.error.type).toBe("authentication_error") + expect(b.error.type).toBe("api_error") expect(b.error.code).toBe(null) expect(b.type).toBeUndefined() }) @@ -60,8 +65,51 @@ test("a refusal says what to do after an em dash, as the built-in's Explain join const l = await hooks.auth.loader(async () => auth) let res = await l.fetch("https://api.factory.ai/api/llm/o/v1/responses", { method: "POST", body: JSON.stringify({ model: "gpt-x" }) }) expect(res.status).toBe(403) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") expect((await res.json()).error.message).toMatch(/^model not allowed — Factory refused this account the request; check that `droid`/) globalThis.fetch = async () => new Response("", { status: 403 }) res = await l.fetch("https://api.factory.ai/api/llm/o/v1/responses", { method: "POST", body: JSON.stringify({ model: "gpt-x" }) }) expect((await res.json()).error.message).toMatch(/^403 Forbidden — Factory refused/) }) + +// a live account whose requests fetch answers with serve +async function live(serve, auth = { ...expired, access: "tok", expires: Date.now() + 3_600_000 }) { + globalThis.fetch = async (url) => serve(new URL(String(url)).pathname) + const hooks = await FactoryAuthPlugin({ client: { auth: { set: async ({ body }) => (auth = body) } } }) + return hooks.auth.loader(async () => auth) +} +const ask = (l) => l.fetch("https://api.factory.ai/api/llm/o/v1/responses", { method: "POST", body: JSON.stringify({ model: "gpt-x" }) }) + +test("Factory's own 401 goes through as it is, leaving the account unmarked", async () => { + const l = await live(() => new Response(JSON.stringify({ error: { message: "bad token" } }), { status: 401 })) + const res = await ask(l) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect((await res.json()).error.message).toBe("bad token") +}) + +test("a success takes the mark off only after a renewal", async () => { + let l = await live(() => new Response("{}", { status: 200 })) + let res = await ask(l) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + l = await live((path) => (path.endsWith("/authenticate") ? new Response(JSON.stringify({ access_token: "tok-new" })) : new Response("{}", { status: 200 })), { ...expired }) + res = await ask(l) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe(null) +}) + +test("a renewal WorkOS fails without refusing it is magpie's 502 for the throw, in Go's words, the account unmarked", async () => { + const l = await live((path) => (path.endsWith("/authenticate") ? new Response("", { status: 500 }) : new Response("{}")), { ...expired }) + await expect(ask(l)).rejects.toThrow(/^Factory sign-in: Internal Server Error$/) +}) + +test("while the token still runs, a renewal that fails goes on with it", async () => { + const l = await live( + (path) => (path.endsWith("/authenticate") ? new Response("", { status: 503 }) : new Response("{}")), + { ...expired, access: "tok", expires: Date.now() + 60_000 }, + ) + const res = await ask(l) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") +}) diff --git a/packages/factory/package.json b/packages/factory/package.json index 3711076..d16738b 100644 --- a/packages/factory/package.json +++ b/packages/factory/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-factory-auth", - "version": "0.1.3", + "version": "0.1.4", "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/grok/index.mjs b/packages/grok/index.mjs index d33c29e..8145efc 100644 --- a/packages/grok/index.mjs +++ b/packages/grok/index.mjs @@ -420,6 +420,15 @@ async function usage(key) { return { windows: out } } +// kept is res saying magpie is to leave the account's sign-in be. +function kept(res) { + const headers = new Headers(res.headers) + headers.delete("content-length") + headers.delete("content-encoding") + headers.set("X-Magpie-Sign-In", "kept") + return new Response(res.body, { status: res.status, statusText: res.statusText, headers }) +} + // ---- the plugin --------------------------------------------------------------- export const GrokAuthPlugin = async ({ client }) => { @@ -461,19 +470,17 @@ export const GrokAuthPlugin = async ({ client }) => { parsed = JSON.parse(body) ?? {} } catch {} } - const send = async (expired) => { - const c = await token(home, expired) - await remember(auth, c) - const headers = new Headers(req.headers) - await sign(headers, c.key) - if (typeof parsed.model === "string" && parsed.model) headers.set("x-grok-model-override", parsed.model) - if (typeof parsed.prompt_cache_key === "string" && parsed.prompt_cache_key) headers.set("x-grok-conv-id", parsed.prompt_cache_key) - headers.delete("content-length") - return fetch(req.url, { ...init, method: req.method, headers, body }) - } - const res = await send(false) - if (res.status !== 401) return res - return send(true) + const c = await token(home, false) + await remember(auth, c) + const headers = new Headers(req.headers) + await sign(headers, c.key) + if (typeof parsed.model === "string" && parsed.model) headers.set("x-grok-model-override", parsed.model) + if (typeof parsed.prompt_cache_key === "string" && parsed.prompt_cache_key) headers.set("x-grok-conv-id", parsed.prompt_cache_key) + headers.delete("content-length") + // sent once, as the built-in sent it: Grok's 401 goes on as it + // came, and the built-in never marked a Grok account lapsed + const res = await fetch(req.url, { ...init, method: req.method, headers, body }) + return res.status === 401 ? kept(res) : res }, } }, diff --git a/packages/grok/package.json b/packages/grok/package.json index cb9cbb0..21a5740 100644 --- a/packages/grok/package.json +++ b/packages/grok/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-grok-auth", - "version": "0.1.2", + "version": "0.1.3", "description": "OpenCode provider plugin: Grok (SuperGrok / X Premium+) through the Grok Build CLI's sign-in", "type": "module", "main": "./index.mjs", diff --git a/packages/grok/signin.test.mjs b/packages/grok/signin.test.mjs new file mode 100644 index 0000000..57770bb --- /dev/null +++ b/packages/grok/signin.test.mjs @@ -0,0 +1,47 @@ +// A chat is sent once, as magpie's built-in Grok account sent it +// (internal/provider/grok.go, grokSigned): Grok's 401 goes on as it came, +// and says X-Magpie-Sign-In: kept, as the built-in never marked a Grok +// account lapsed. +import { afterAll, afterEach, expect, test } from "bun:test" +import { mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { GrokAuthPlugin } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +// a CLI home whose token is good for a day, so nothing renews it +const home = mkdtempSync(join(tmpdir(), "grok-signin-")) +afterAll(() => rmSync(home, { recursive: true, force: true })) +writeFileSync(join(home, "auth.json"), JSON.stringify({ a: { key: "tok", email: "g@x.ai", expires_at: new Date(Date.now() + 24 * 3600_000).toISOString() } })) +const auth = { type: "oauth", refresh: home, access: "tok", expires: 0, accountId: "g@x.ai" } + +async function chat(reply) { + let sent = 0 + globalThis.fetch = async () => { + sent++ + return reply() + } + const hooks = await GrokAuthPlugin({ client: { auth: { set: async () => {} } } }) + const opts = await hooks.auth.loader(async () => auth) + const res = await opts.fetch("https://cli-chat-proxy.grok.com/v1/responses", { method: "POST", body: '{"model":"grok-4.7","input":"hi"}' }) + return { res, sent } +} + +test("Grok's 401 is passed on once, the account kept", async () => { + const { res, sent } = await chat(() => Response.json({ error: "token revoked" }, { status: 401 })) + expect(sent).toBe(1) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect(await res.json()).toEqual({ error: "token revoked" }) +}) + +test("other answers go as they came", async () => { + for (const status of [200, 403, 429]) { + const { res, sent } = await chat(() => new Response("x", { status })) + expect(sent).toBe(1) + expect(res.status).toBe(status) + expect(res.headers.get("X-Magpie-Sign-In")).toBeNull() + } +}) diff --git a/packages/kiro/errors.test.mjs b/packages/kiro/errors.test.mjs index 0584c3f..df57b29 100644 --- a/packages/kiro/errors.test.mjs +++ b/packages/kiro/errors.test.mjs @@ -84,3 +84,73 @@ test("unstreamed, what was said before an exception is the answer", async () => expect(res.status).toBe(200) expect((await res.json()).content).toEqual([{ type: "text", text: "Hello" }]) }) + +// Failing before any of the answer, a request is answered with the built-in's +// status (internal/gateway/kiro.go askKiro), and X-Magpie-Sign-In says when +// that is no lapsed sign-in: only one Kiro refused marks the account. +const { generate, refresh, failure } = _internal +const msgReq = { model: "claude-sonnet-4.5", messages: [{ role: "user", content: "hi" }] } +const gone = (msg) => Object.assign(new Error(msg), { gone: true }) + +test("credentials that can't be had are a 401; the account is kept unless the sign-in is gone", async () => { + let res = await generate(async () => { throw new Error("refreshing Kiro's sign-in: fetch failed") }, {}, msgReq) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect((await res.json()).error.message).toBe("refreshing Kiro's sign-in: fetch failed") + res = await generate(async () => { throw gone("Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE") }, {}, msgReq) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBeNull() +}) + +const withFetch = async (answer, fn) => { + const was = globalThis.fetch + globalThis.fetch = async (...a) => answer(...a) + try { + return await fn() + } finally { + globalThis.fetch = was + } +} +const creds = (fail) => { + let n = 0 + return async () => { + if (n++ && fail) throw fail + return { token: "t", tokenType: "", profile: "arn:aws:codewhisperer:us-east-1:1:profile/x", region: "us-east-1" } + } +} + +test("a refresh failing after Kiro's 403 is a 502, marked only when Kiro refused it", async () => { + await withFetch(() => new Response("{}", { status: 403 }), async () => { + let res = await generate(creds(new Error("refreshing Kiro's sign-in: 503 Service Unavailable")), {}, msgReq) + expect(res.status).toBe(502) + expect(res.headers.get("X-Magpie-Sign-In")).toBeNull() + res = await generate(creds(gone("Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE")), {}, msgReq) + expect(res.status).toBe(502) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") + }) +}) + +test("Kiro's own 401 is passed on without marking the account", async () => { + await withFetch(() => new Response(JSON.stringify({ message: "bad token" }), { status: 401 }), async () => { + const res = await generate(creds(), {}, msgReq) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect((await res.json()).error.message).toBe("bad token") + }) +}) + +test("an error Kiro gives no words for is Go's status text", () => { + expect(failure(500, "")).toEqual({ status: 500, message: "Internal Server Error" }) +}) + +test("a refresh is worded as the built-in's", async () => { + const c = { method: "social", refresh: "r", region: "us-east-1", access: "a" } + await withFetch(() => new Response("", { status: 500 }), async () => { + await expect(refresh(c)).rejects.toThrow(/^refreshing Kiro's sign-in: 500 Internal Server Error$/) + }) + await withFetch(() => new Response("", { status: 400 }), async () => { + await expect(refresh(c)).rejects.toMatchObject({ gone: true, message: "Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE" }) + }) + await expect(refresh({ ...c, refresh: "" })).rejects.toMatchObject({ message: "Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE" }) + await expect(refresh({ ...c, method: "odd" })).rejects.toMatchObject({ message: "Kiro's sign-in has expired" }) +}) diff --git a/packages/kiro/index.mjs b/packages/kiro/index.mjs index 2467e5f..097355e 100644 --- a/packages/kiro/index.mjs +++ b/packages/kiro/index.mjs @@ -188,11 +188,14 @@ async function saveBack(c) { // ---- tokens -------------------------------------------------------------------- +// EXPIRED is the built-in's words for a sign-in Kiro refused, or one with +// nothing to refresh it. const EXPIRED = "Kiro's sign-in has expired; sign in again" +const EXPIRED_CLI = EXPIRED + " with `kiro-cli login` or the Kiro IDE" // gone is an error saying the sign-in itself is gone — refused, or never -// there — which alone answers a request with the 401 magpie marks the -// account lapsed on; a refresh that timed out or met a 5xx may pass. +// there — which alone marks the account lapsed; a refresh that timed out +// or met a 5xx fails the request as the built-in did, the account kept. const gone = (msg) => Object.assign(new Error(msg), { gone: true }) const fresh = (c) => c.method === "apikey" || !c.expires || c.expires - Date.now() > 2 * 60 * 1000 @@ -206,8 +209,8 @@ async function post(url, contentType, body, headers = {}) { } const text = await res.text() if (!res.ok) { - if ([400, 401, 403].includes(res.status)) throw gone(EXPIRED) - throw new Error(`refreshing Kiro's sign-in: ${res.status}`) + if ([400, 401, 403].includes(res.status)) throw gone(EXPIRED_CLI) + throw new Error(`refreshing Kiro's sign-in: ${res.status} ${STATUS_TEXT[res.status] ?? ""}`.trimEnd()) // Go's res.Status } return JSON.parse(text) } @@ -223,7 +226,7 @@ async function refresh(c) { if (n && n.dbKey === c.dbKey && n.access !== c.access && fresh(n)) return n } } - if (!c.refresh) throw gone(EXPIRED) + if (!c.refresh) throw gone(EXPIRED_CLI) let out switch (c.method) { case "social": { @@ -246,9 +249,9 @@ async function refresh(c) { break } default: - throw gone(EXPIRED) + throw gone("Kiro's sign-in has expired") } - if (!out.access) throw gone(EXPIRED) + if (!out.access) throw gone(EXPIRED_CLI) const n = { ...c, access: out.access, expires: Date.now() + (out.expiresIn > 0 ? out.expiresIn : 3600) * 1000 } if (out.refresh) n.refresh = out.refresh await saveBack(n) @@ -315,7 +318,7 @@ async function profileOf(c) { signal: AbortSignal.timeout(20_000), }) if (!res.ok) { - const msg = `Kiro didn't take the API key: ${res.status}` + const msg = `Kiro didn't take the API key: ${res.status} ${STATUS_TEXT[res.status] ?? ""}`.trimEnd() throw res.status === 401 || res.status === 403 ? gone(msg) : new Error(msg) } const arn = (await res.json().catch(() => null))?.profile?.arn @@ -431,7 +434,7 @@ function account(client) { if (stale && c && read.access !== c.access && fresh(read)) stale = false // the owner refreshed it already c = read if (!fresh(c) || stale) { - if (c.method === "apikey") throw gone("Kiro turned down the API key") + if (c.method === "apikey") throw gone("Kiro turned down the API key saved on the provider") c = await refresh(c) await save(auth, c) } @@ -712,7 +715,7 @@ function failure(status, body) { const e = JSON.parse(body) if (e?.message) msg = e.message + (e.reason ? ` (${e.reason})` : "") } catch {} - msg ||= `HTTP ${status}` + msg ||= STATUS_TEXT[status] ?? "" if (msg.includes("CONTENT_LENGTH_EXCEEDS_THRESHOLD") || msg.toLowerCase().includes("input is too long")) return { status: 400, message: "input is too long for the model's context: " + msg } if (msg.includes("INSUFFICIENT_MODEL_CAPACITY")) return { status: 503, message: msg } @@ -723,10 +726,12 @@ function failure(status, body) { const ERROR_TYPES = { 400: "invalid_request_error", 401: "authentication_error", 402: "billing_error", 403: "permission_error", 404: "not_found_error", 413: "request_too_large", 429: "rate_limit_error", 503: "overloaded_error", 529: "overloaded_error" } const errorType = (status) => ERROR_TYPES[status] ?? "api_error" -const errorResponse = (status, message) => +// signIn, the X-Magpie-Sign-In header, says what the answer means for the +// account whatever its status: "expired" marks it lapsed, "kept" leaves it. +const errorResponse = (status, message, signIn) => new Response(JSON.stringify({ type: "error", error: { type: errorType(status), message } }), { status, - headers: { "Content-Type": "application/json" }, + headers: { "Content-Type": "application/json", ...(signIn ? { "X-Magpie-Sign-In": signIn } : {}) }, }) // ---- the reply: an AWS event stream → Messages --------------------------------------- @@ -1087,7 +1092,9 @@ async function reply(it, model, stream) { } // generate answers a Messages request through Kiro's API: once more, -// refreshed, when Kiro turns the token down (403). +// refreshed, when Kiro turns the token down (403). As the built-in: no +// credentials is a 401, a failed refresh after the 403 a 502; only a +// sign-in that is gone marks the account. async function generate(creds, auth, req, signal) { const model = String(req.model ?? "auto") const budget = thinking(req, model) @@ -1095,7 +1102,7 @@ async function generate(creds, auth, req, signal) { try { a = await creds(auth) } catch (e) { - return errorResponse(e?.gone ? 401 : 502, e.message) + return errorResponse(401, e.message, e?.gone ? undefined : "kept") } let res try { @@ -1109,7 +1116,7 @@ async function generate(creds, auth, req, signal) { try { a = await creds(auth, true) } catch (e) { - return errorResponse(e?.gone ? 401 : 502, e.message) + return errorResponse(502, e.message, e?.gone ? "expired" : undefined) } try { res = await sendKiro(a, buildKiro(req, model, a.profile, budget), signal) @@ -1119,8 +1126,9 @@ async function generate(creds, auth, req, signal) { } } if (!res.ok) { + // Kiro's own 401 is passed on, as the built-in did, the sign-in kept const f = failure(res.status, (await res.text()).slice(0, 1 << 20)) - return errorResponse(f.status, f.message) + return errorResponse(f.status, f.message, f.status === 401 ? "kept" : undefined) } return reply(events(res.body, model, budget), model, req.stream === true) } @@ -1373,4 +1381,4 @@ export async function KiroAuthPlugin({ client } = {}) { } // for tests -export const _internal = { usageOf, buildKiro, events, reply, failure, toolID, thinking, readCLI, readIDE, regionOf, planName, frames } +export const _internal = { generate, refresh, usageOf, buildKiro, events, reply, failure, toolID, thinking, readCLI, readIDE, regionOf, planName, frames } diff --git a/packages/kiro/package.json b/packages/kiro/package.json index 02398da..863bb73 100644 --- a/packages/kiro/package.json +++ b/packages/kiro/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-kiro-auth", - "version": "0.1.4", + "version": "0.1.5", "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/kiro/usage.test.mjs b/packages/kiro/usage.test.mjs index c83fdee..4b44cf7 100644 --- a/packages/kiro/usage.test.mjs +++ b/packages/kiro/usage.test.mjs @@ -79,23 +79,29 @@ test("no account, no usage", async () => { expect(calls).toEqual([]) }) -// the loader's fetch answering a Messages request +// the loader's fetch answering a Messages request, and what it says of the +// sign-in (X-Magpie-Sign-In) async function ask(a) { const hooks = await plugin({ client: { auth: { set: async () => {} } } }) const l = await hooks.auth.loader(async () => a) const res = await l.fetch("https://kiro.invalid/v1/messages", { method: "POST", body: JSON.stringify({ model: "auto", max_tokens: 10, messages: [{ role: "user", content: "hi" }] }) }) - return { status: res.status, message: (await res.json()).error.message } + const out = { status: res.status, message: (await res.json()).error.message } + const said = res.headers.get("X-Magpie-Sign-In") + return said ? { ...out, signIn: said } : out } const stale = { ...auth, expires: Date.now() - 60_000 } -test("a refresh that failed for a while is no lapsed sign-in (no 401); one Kiro refused is", async () => { +// the built-in answered any credentials it couldn't get with a 401 and +// marked nothing; only a refresh Kiro refused marks the account here +test("a refresh that failed for a while is the built-in's 401, the account kept; one Kiro refused marks it", async () => { answer(500, "") - expect(await ask(stale)).toEqual({ status: 502, message: "refreshing Kiro's sign-in: 500" }) + expect(await ask(stale)).toEqual({ status: 401, message: "refreshing Kiro's sign-in: 500 Internal Server Error", signIn: "kept" }) globalThis.fetch = async () => { throw new Error("getaddrinfo ENOTFOUND") } - expect(await ask(stale)).toEqual({ status: 502, message: "refreshing Kiro's sign-in: getaddrinfo ENOTFOUND" }) + expect(await ask(stale)).toEqual({ status: 401, message: "refreshing Kiro's sign-in: getaddrinfo ENOTFOUND", signIn: "kept" }) answer(401, { error: "invalid_grant" }) - expect(await ask(stale)).toEqual({ status: 401, message: "Kiro's sign-in has expired; sign in again" }) - expect(await ask({ ...stale, refresh: "" })).toEqual({ status: 401, message: "Kiro's sign-in has expired; sign in again" }) + const refused = "Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE" + expect(await ask(stale)).toEqual({ status: 401, message: refused }) + expect(await ask({ ...stale, refresh: "" })).toEqual({ status: 401, message: refused }) }) test("errors don't name Kiro, which magpie adds", async () => { diff --git a/packages/mimo/README.md b/packages/mimo/README.md index 0e8b533..e0f2d08 100644 --- a/packages/mimo/README.md +++ b/packages/mimo/README.md @@ -29,10 +29,11 @@ Chat completions go to `https://mimo-server-.xiaomimimo.com/api/route/ch `mimo-auto`, the app's default model, is requested as `mimo-pro`. -The session is renewed with the passToken a day after it was issued. It is -also renewed once when the server turns a request away: a 401, or a Xiaomi -sign-in page where an answer was expected. If the passToken no longer works, -sign in again. +The session is renewed with the passToken a day after it was issued. A model +request the server turns away (a 401) is answered as the server answered it, +as magpie's built-in MiMo account did; reading usage renews the session once +when the server turns it away. If the passToken no longer works, sign in +again. ## Where the sign-in is kept diff --git a/packages/mimo/index.mjs b/packages/mimo/index.mjs index 379b3e3..5586b2c 100644 --- a/packages/mimo/index.mjs +++ b/packages/mimo/index.mjs @@ -117,7 +117,11 @@ async function session(creds, base) { const headers = appHeaders() const cookie = jar.header(url) if (cookie) headers.Cookie = cookie - res = await fetch(url, { headers, redirect: "manual", signal }) + try { + res = await fetch(url, { headers, redirect: "manual", signal }) + } catch (e) { + throw new Error("Xiaomi MiMo sign-in: " + (e?.message ?? e)) + } jar.take(res, url) const loc = res.headers.get("location") if (res.status < 300 || res.status >= 400 || !loc) break @@ -184,6 +188,15 @@ function fromAuth(auth) { } } +// said is an answer with magpie's X-Magpie-Sign-In, which tells what it +// means for the account's sign-in whatever its status: "expired" marks it +// lapsed, "kept" leaves it be. magpie takes it off before the agent sees it. +function said(res, v) { + const h = new Headers(res.headers) + h.set("X-Magpie-Sign-In", v) + return new Response(res.body, { status: res.status, statusText: res.statusText, headers: h }) +} + // ---- the sign-in ------------------------------------------------------------ // serviceOf is the sid and callback the MiMo server sends a browser with @@ -336,7 +349,8 @@ export const MimoAuthPlugin = async ({ client }) => { // fresh is the account with a live session, signed on again when it is // older than the app lets one get, or when force is set (the server - // turned the last one away) + // turned the last one away); renewed when it was signed on again, which + // took the built-in's lapse mark off const fresh = async (getAuth, force) => { const a = fromAuth(await getAuth()) if (!a) throw new Error("Xiaomi MiMo: not signed in") @@ -349,7 +363,7 @@ export const MimoAuthPlugin = async ({ client }) => { const s = await session(a.creds, a.creds.base) const issued = Date.now() await save(toAuth(a.creds, s.cookies, issued)) - return { creds: a.creds, cookies: s.cookies, expires: issued + RENEW_AFTER } + return { creds: a.creds, cookies: s.cookies, expires: issued + RENEW_AFTER, renewed: true } } catch (e) { // a hiccup: the session in hand may still do if (!(e instanceof Lapsed) && !force && Object.keys(a.cookies).length) return a @@ -467,31 +481,28 @@ export const MimoAuthPlugin = async ({ client }) => { if (j?.model === "mimo-auto") body = JSON.stringify({ ...j, model: "mimo-pro" }) } catch {} } - const send = async (force) => { - const s = await fresh(getAuth, force) - const headers = new Headers(init.headers ?? req?.headers) - headers.delete("authorization") - headers.set("Cookie", cookieHeader(s.cookies)) - headers.set("X-Mimo-Source", SOURCE) - headers.set("User-Agent", UA) - headers.set("X-Client-Version", APP_VERSION) - return fetch(url, { ...init, method: init.method ?? req?.method ?? "POST", headers, body }) - } + let s try { - const res = await send(false) - // a session gone stale, or a redirect to Xiaomi's sign-in page - const stale = res.status === 401 || (res.status === 200 && /text\/html/i.test(res.headers.get("content-type") ?? "")) - if (!stale || (body != null && typeof body !== "string")) return res - await res.arrayBuffer().catch(() => {}) - return await send(true) + s = await fresh(getAuth, false) } catch (e) { - // the passToken no longer signs the account on: the account's - // own 401, in the built-in's words (mimoLapse) + // the passToken no longer signs the account on: the built-in + // failed the request (magpie's 502) in mimoLapse's words and + // marked the account lapsed if (!(e instanceof Lapsed)) throw e const who = fromAuth(await getAuth())?.creds.userId ?? a.creds.userId const message = `${who}: the Xiaomi MiMo sign-in has expired — sign in again` - return new Response(JSON.stringify({ error: { message, type: "authentication_error", code: null } }), { status: 401, headers: { "content-type": "application/json" } }) + return said(new Response(JSON.stringify({ error: { message, type: "api_error", code: null } }), { status: 502, headers: { "content-type": "application/json" } }), "expired") } + const headers = new Headers(init.headers ?? req?.headers) + headers.delete("authorization") + headers.set("Cookie", cookieHeader(s.cookies)) + headers.set("X-Mimo-Source", SOURCE) + headers.set("User-Agent", UA) + headers.set("X-Client-Version", APP_VERSION) + // the server's answer goes through as it is, a 401 too, as the + // built-in's did: it took the lapse off only when it signed on again + const res = await fetch(url, { ...init, method: init.method ?? req?.method ?? "POST", headers, body }) + return s.renewed && res.status >= 200 && res.status < 300 ? res : said(res, "kept") }, } }, diff --git a/packages/mimo/package.json b/packages/mimo/package.json index 47db2a3..141c873 100644 --- a/packages/mimo/package.json +++ b/packages/mimo/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-mimo-auth", - "version": "0.1.4", + "version": "0.1.5", "description": "OpenCode provider plugin for Xiaomi MiMo: the MiMo app's Xiaomi-account sign-in, MiMo Pro and MiMo Flash", "type": "module", "main": "./index.mjs", diff --git a/packages/mimo/usage.test.mjs b/packages/mimo/usage.test.mjs index b45a401..bc2b6ab 100644 --- a/packages/mimo/usage.test.mjs +++ b/packages/mimo/usage.test.mjs @@ -139,12 +139,49 @@ test("a chat body in bytes has mimo-auto asked as mimo-pro, as a string one does expect(sent.map((b) => JSON.parse(b).model)).toEqual(["mimo-pro", "mimo-pro"]) }) -test("a sign-in Xiaomi no longer takes is a 401 in the built-in's words, not a thrown fetch", async () => { +test("a sign-in Xiaomi no longer takes is magpie's 502 in the built-in's words, marking the account, not a thrown fetch", async () => { const { fetch } = await loaderFetch(account(0), (path) => { if (path === "/api/user/xiaomi/me") return new Response("sign in", { status: 200 }) return new Response("", { status: 401 }) }) const res = await fetch(BASE + "/route/chat/completions", { method: "POST", body: JSON.stringify({ model: "mimo-pro", messages: [] }) }) + expect(res.status).toBe(502) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") + const b = await res.json() + expect(b.error.message).toBe("42: the Xiaomi MiMo sign-in has expired — sign in again") + expect(b.error.type).toBe("api_error") +}) + +test("the server's 401 goes through as the built-in's did: not signed on again, the account unmarked", async () => { + const asked = [] + const { fetch } = await loaderFetch(account(), (path) => { + asked.push(path) + return path === "/api/user/xiaomi/me" ? json({ code: 0, data: { userId: "42" } }) : json({ error: { message: "stale" } }, 401) + }) + const res = await fetch(BASE + "/route/chat/completions", { method: "POST", body: JSON.stringify({ model: "mimo-pro", messages: [] }) }) expect(res.status).toBe(401) - expect((await res.json()).error.message).toBe("42: the Xiaomi MiMo sign-in has expired — sign in again") + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect((await res.json()).error.message).toBe("stale") + expect(asked).toEqual(["/api/route/chat/completions"]) +}) + +test("a success takes the mark off only when the account was signed on again", async () => { + let p = await loaderFetch(account(), () => json({ ok: true })) + let res = await p.fetch(BASE + "/route/chat/completions", { method: "POST", body: "{}" }) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + p = await loaderFetch(account(0), (path) => + path === "/api/user/xiaomi/me" ? new Response(JSON.stringify({ code: 0, data: { userId: "42" } }), { headers: { "set-cookie": "serviceToken=st-2; Path=/" } }) : json({ ok: true }), + ) + res = await p.fetch(BASE + "/route/chat/completions", { method: "POST", body: "{}" }) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe(null) +}) + +test("a sign-on that can't reach the server is a thrown fetch (magpie's 502) in the built-in's words, the account unmarked", async () => { + const noSession = { ...account(0), access: "{}" } + const { fetch } = await loaderFetch(noSession, () => { + throw new Error("connection refused") + }) + await expect(fetch(BASE + "/route/chat/completions", { method: "POST", body: "{}" })).rejects.toThrow(/^Xiaomi MiMo sign-in: connection refused$/) }) diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index 9eeca9e..7321c67 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -16,6 +16,7 @@ // from magpie's internal/qoder, which ported it from CLIProxyAPI's qoder // support (https://github.com/ufec/CLIProxyAPI, MIT). import { createCipheriv, createHash, publicEncrypt, randomBytes, randomUUID, constants } from "node:crypto" +import { STATUS_CODES } from "node:http" const ID = "qoder" const CLIENT_ID = "732aef47-9cf2-46a2-95fe-4cebb5d0d1fa" @@ -213,14 +214,24 @@ async function deviceSignIn() { } } -class SignInGone extends Error {} +// SignInGone is a sign-in that can't sign a request: a 401. Only Qoder +// refusing the refresh token marks the account lapsed (expired), as the +// built-in's qoderRefreshFailed did; no refresh token, or no account, +// answered 401 there without marking one. +class SignInGone extends Error { + constructor(message, expired = false) { + super(message) + this.expired = expired + } +} // refreshJob trades the job token's refresh token for a new pair; the old // one is spent. -async function refreshJob(refresh) { +async function refreshJob(refresh, user) { if (!String(refresh ?? "").trim()) throw new SignInGone("Qoder: the sign-in lapsed; sign in again") const r = await openapi("/api/v1/jobToken/refresh", { method: "POST", body: { refresh_token: refresh } }) - if (r.status === 401 || r.status === 403) throw new SignInGone("Qoder: the sign-in has expired — sign in again") + if (r.status === 401 || r.status === 403) + throw new SignInGone(`${user}'s Qoder sign-in has expired — sign in again (qoder job token refresh: status ${r.status})`, true) if (r.status !== 200) throw new Error(`Qoder job token refresh: status ${r.status}`) if (!String(r.json?.token ?? "").trim() || !String(r.json?.refresh_token ?? "").trim()) throw new Error("Qoder job token refresh: incomplete token pair") @@ -486,19 +497,26 @@ function failure(status, text) { try { const j = JSON.parse(text) if (j?.message) msg = j.message - const d = typeof j?.details === "string" ? JSON.parse(j.details) : null + // details is a JSON string, or the object itself (gjson reads either) + const d = typeof j?.details === "string" ? JSON.parse(j.details) : j?.details if (d?.error?.message) msg += ": " + d.error.message } catch {} - msg ||= `HTTP ${status}` - // only Qoder's 401 says the job token itself is refused; a 403 is kept as - // what it is, as magpie marks the account lapsed on a 401 - if (status === 401 || status === 403) return { status, message: "the sign-in lapsed — sign in again" } + msg ||= STATUS_CODES[status] ?? `HTTP ${status}` + // a refused chat is the built-in's 401, which never marked the account + // lapsed: only a refused refresh did (errorResponse says kept) + if (status === 401 || status === 403) return { status: 401, message: "the sign-in lapsed — sign in again" } if (status === 429 || msg.toLowerCase().includes("quota")) return { status: 429, message: "usage limit reached: " + msg } return { status, message: msg } } -const errorResponse = ({ status, message }) => - new Response(JSON.stringify({ error: { message, type: "qoder_error", code: status } }), { status, headers: { "Content-Type": "application/json" } }) +// errorResponse is a failure as OpenAI's API gives it. signIn is what it +// means for the account (magpie's X-Magpie-Sign-In): a 401 keeps it unless +// told expired, since the built-in marked only a refused refresh. +const errorResponse = ({ status, message, signIn = status === 401 ? "kept" : undefined }) => + new Response(JSON.stringify({ error: { message, type: "qoder_error", code: status } }), { + status, + headers: { "Content-Type": "application/json", ...(signIn ? { "X-Magpie-Sign-In": signIn } : {}) }, + }) // ---- the reply ---------------------------------------------------------------- @@ -870,7 +888,7 @@ export async function QoderAuthPlugin({ client }) { const a = await getAuth() if (a?.type !== "oauth" || !a.access || !a.uid) throw new SignInGone("Qoder: not signed in") if (a.expires - Date.now() > REFRESH_LEAD) return a - const jt = await refreshJob(a.refresh) + const jt = await refreshJob(a.refresh, a.accountId || a.email || a.uid) const next = { ...a, access: jt.token, refresh: jt.refresh_token, expires: expiresAt(jt) } await client.auth.set({ path: { id: ID }, body: next }) return next @@ -914,7 +932,11 @@ export async function QoderAuthPlugin({ client }) { } const signedInError = (e) => - errorResponse({ status: e instanceof SignInGone ? 401 : 502, message: String(e?.message ?? e).replace(/^Qoder: /, "") }) + errorResponse({ + status: e instanceof SignInGone ? 401 : 502, + message: String(e?.message ?? e).replace(/^Qoder: /, ""), + signIn: e?.expired ? "expired" : undefined, + }) return { auth: { @@ -946,7 +968,9 @@ export async function QoderAuthPlugin({ client }) { try { m = (await models(cred)).find((x) => x.key === chat.model) ?? (await models(cred, true)).find((x) => x.key === chat.model) } catch (e) { - return errorResponse({ status: 502, message: e.message }) + // the built-in answered any failure to read the list 400 + // (QoderModelOf), a refused one included, marking nothing + return errorResponse({ status: 400, message: e.message }) } if (!m) return errorResponse({ status: 400, message: `unknown or disabled model "${chat.model}"` }) const wire = encodeBody(JSON.stringify(qoderBody(chat, m))) diff --git a/packages/qoder/package.json b/packages/qoder/package.json index 6b698fa..f5edd0b 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.1.2", + "version": "0.1.3", "description": "Qoder subscription in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/qoder/usage.test.mjs b/packages/qoder/usage.test.mjs index c232937..261c62b 100644 --- a/packages/qoder/usage.test.mjs +++ b/packages/qoder/usage.test.mjs @@ -145,13 +145,69 @@ const LISTING = { ], } -test("a refused chat is a 401 only when Qoder says 401; a 403 stays a 403", async () => { +const ASK = { method: "POST", body: JSON.stringify({ model: "qmodel", messages: [{ role: "user", content: "hi" }] }) } + +test("a refused chat, 401 or 403, is the built-in's 401 and leaves the account unmarked", async () => { for (const status of [401, 403]) { const { fetch } = await chat(LISTING, () => new Response("nope", { status })) - const res = await fetch(API_CHAT, { method: "POST", body: JSON.stringify({ model: "qmodel", messages: [{ role: "user", content: "hi" }] }) }) - expect(res.status).toBe(status) + const res = await fetch(API_CHAT, ASK) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") expect((await res.json()).error.message).toBe("the sign-in lapsed — sign in again") } + // refused in the stream, before any answer: the same + const sse = (v) => new Response(`data: ${JSON.stringify(v)}\n\n`, { headers: { "Content-Type": "text/event-stream" } }) + const { fetch } = await chat(LISTING, () => sse({ statusCodeValue: 403, body: "" })) + const res = await fetch(API_CHAT, ASK) + expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([401, "kept"]) +}) + +test("other refusals keep their status and say nothing of the sign-in", async () => { + for (const [status, want] of [[500, 500], [429, 429], [402, 402]]) { + const { fetch } = await chat(LISTING, () => new Response("", { status })) + const res = await fetch(API_CHAT, ASK) + expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([want, null]) + } + // an empty body is named as Go's http.StatusText names it; details may be an object + expect(_internal.failure(502, "")).toEqual({ status: 502, message: "Bad Gateway" }) + expect(_internal.failure(400, JSON.stringify({ message: "bad", details: { error: { message: "effort" } } }))).toEqual({ status: 400, message: "bad: effort" }) +}) + +test("a model list Qoder won't give is a 400, as the built-in's QoderModelOf answered, the account unmarked", async () => { + for (const status of [401, 403, 500]) { + const auth = { ...account(), machineId: "m1" } + globalThis.fetch = async () => new Response("no", { status }) + const hooks = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } }) + const l = await hooks.auth.loader(async () => auth) + const res = await l.fetch(API_CHAT, ASK) + expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([400, null]) + expect((await res.json()).error.message).toBe(`Qoder models: HTTP ${status}: no`) + } +}) + +// the loader's fetch for an account whose job token is due, the refresh answered by refresh() +async function due(refresh, fields = {}) { + const auth = { ...account(), machineId: "m1", expires: 0, ...fields } + globalThis.fetch = async (url) => (new URL(String(url)).pathname === "/api/v1/jobToken/refresh" ? refresh() : new Response("", { status: 500 })) + const hooks = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } }) + const l = await hooks.auth.loader(async () => auth) + return l.fetch(API_CHAT, ASK) +} + +test("a refresh Qoder refuses (401 or 403) marks the account lapsed, as qoderRefreshFailed did", async () => { + for (const status of [401, 403]) { + const res = await due(() => new Response("", { status })) + expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([401, "expired"]) + expect((await res.json()).error.message).toBe(`one@x's Qoder sign-in has expired — sign in again (qoder job token refresh: status ${status})`) + } +}) + +test("no refresh token is a 401 the built-in didn't mark; a refresh that failed otherwise is a 502", async () => { + let res = await due(() => new Response("", { status: 401 }), { refresh: "" }) + expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([401, "kept"]) + res = await due(() => new Response("", { status: 500 })) + expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([502, null]) + expect((await res.json()).error.message).toBe("Qoder job token refresh: status 500") }) test("errors don't name Qoder, which magpie adds", async () => { @@ -164,7 +220,7 @@ test("errors don't name Qoder, which magpie adds", async () => { const gone = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } }) const l = await gone.auth.loader(async () => ({ type: "oauth" })) res = await l.fetch(API_CHAT, { method: "POST", body: JSON.stringify({ model: "qmodel", messages: [] }) }) - expect(res.status).toBe(401) + expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([401, "kept"]) expect((await res.json()).error.message).toBe("not signed in") }) diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index f959881..6f35b3f 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -86,10 +86,11 @@ const api = (site) => site.endpoint + "/v2" // ---- WorkBuddy's API ------------------------------------------------------ class WBError extends Error { - constructor(message, code, status) { + constructor(message, code, status, said) { super(message) this.code = code this.status = status + this.said = said // as magpie's built-in (wbCall) worded it } } @@ -112,11 +113,13 @@ async function call(site, method, path, headers = {}, body) { try { env = JSON.parse(text) } catch {} + const code = Number.parseInt(env.code, 10) || 0 if (!res.ok) { const why = env.msg || env.message || env.error?.message || text.slice(0, 200) || res.statusText - throw new WBError(`${site.name}: ${why} (HTTP ${res.status}${env.code ? ", code " + env.code : ""})`, env.code, res.status) + const said = code ? env.msg || `error ${code}` : env.msg || statusText(res.status) + throw new WBError(`${site.name}: ${why} (HTTP ${res.status}${env.code ? ", code " + env.code : ""})`, env.code, res.status, said) } - if (env.code) throw new WBError(`${site.name}: ${env.msg || "error"} (${env.code})`, env.code, res.status) + if (env.code) throw new WBError(`${site.name}: ${env.msg || "error"} (${env.code})`, env.code, res.status, env.msg || `error ${code}`) return env.data } @@ -145,13 +148,14 @@ function stale(a) { // 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. +// 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 (a.access) return a - throw new Error(`this ${site.name} account is signed out; sign in again`) + throw new Error("this WorkBuddy account is signed out; sign in again") } try { const got = await call(site, "POST", "/v2/plugin/auth/token/refresh", { @@ -159,13 +163,14 @@ async function fresh(site, client, a) { "X-Auth-Refresh-Source": "plugin", "X-Domain": domainOf(site, a), }, {}) - if (!got?.accessToken) throw new Error(`${site.name} gave no refreshed token`) + 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 } catch (e) { if (a.access) return a - throw new Error(`${site.name} token refresh: ${e?.message ?? e}`) + if (e?.bare) throw e + throw new Error(`WorkBuddy token refresh: ${e?.said ?? e?.message ?? e}`) } } @@ -612,12 +617,15 @@ const REFUSED_HINT = const REFUSED = /unapproved channel|illegal api invocation/i // explained is res with REFUSED_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. async function explained(res) { const text = await res.text() const again = (b) => { const headers = new Headers(res.headers) headers.delete("content-length") headers.delete("content-encoding") + headers.set("X-Magpie-Sign-In", "kept") return new Response(b, { status: res.status, statusText: res.statusText, headers }) } if (!REFUSED.test(text)) return again(text) @@ -635,6 +643,7 @@ async function explained(res) { headers.set("content-type", "application/json") headers.delete("content-length") headers.delete("content-encoding") + headers.set("X-Magpie-Sign-In", "kept") return new Response(JSON.stringify({ error: { message: msg, type: "permission_error", code: null } }), { status: res.status, statusText: res.statusText, headers }) } @@ -642,4 +651,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 } +export const _internal = { withSystem, usageOf, desktopHeld, explained, REFUSED_HINT, freeCredits, fresh, SITES } diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 49e1950..321fb2f 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.4", + "version": "0.1.5", "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/signin.test.mjs b/packages/workbuddy/signin.test.mjs new file mode 100644 index 0000000..6b083e9 --- /dev/null +++ b/packages/workbuddy/signin.test.mjs @@ -0,0 +1,61 @@ +// 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. +import { afterEach, expect, test } from "bun:test" +import { WorkBuddyAIAuthPlugin, _internal } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const later = () => Date.now() + 3600_000 +const ask = async (reply) => { + globalThis.fetch = async () => reply() + const auth = { type: "oauth", access: "a", refresh: "r", expires: later(), uid: "u" } + const hooks = await WorkBuddyAIAuthPlugin({ client: {} }) + const opts = await hooks.auth.loader(async () => auth) + 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 () => { + 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"}') +}) + +test("the channel refusal keeps the account too", async () => { + const res = await ask(() => new Response('{"code":11004,"msg":"Illegal API invocation from an unapproved channel"}', { status: 403 })) + expect(res.status).toBe(403) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") +}) + +test("a reply that went through says nothing of the sign-in", async () => { + const res = await ask(() => new Response("data: [DONE]\n\n", { status: 200 })) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBeNull() +}) + +// wbFresh with no access token left: its words, on either site +const refresh = async (reply, a = {}) => { + globalThis.fetch = async () => reply() + const site = _internal.SITES["workbuddy-ai"] + try { + await _internal.fresh(site, null, { access: "", refresh: "r", expires: 1, ...a }) + } catch (e) { + return e.message + } + return "no error" +} + +test("a refresh WorkBuddy refused is worded as wbCall's error", async () => { + expect(await refresh(() => new Response('{"code":11001,"msg":"refresh token expired"}', { status: 401 }))).toBe("WorkBuddy token refresh: refresh token expired") + expect(await refresh(() => new Response('{"code":11001}', { status: 401 }))).toBe("WorkBuddy token refresh: error 11001") + expect(await refresh(() => new Response("", { status: 401 }))).toBe("WorkBuddy token refresh: Unauthorized") + expect(await refresh(() => new Response('{"code":11002,"msg":"bad refresh"}'))).toBe("WorkBuddy token refresh: bad refresh") + expect(await refresh(() => new Response('{"code":0,"data":{}}'))).toBe("WorkBuddy gave no refreshed token") +}) + +test("nothing to refresh with is signed out, in the built-in's words", async () => { + expect(await refresh(() => new Response(""), { refresh: "" })).toBe("this WorkBuddy account is signed out; sign in again") +}) diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index 948d57a..40b282c 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -120,7 +120,9 @@ const jwtExpired = (jwt) => { const t = jwtExpiry(jwt) return t > 0 && Date.now() > t } -const EXPIRED = "ZCode's sign-in has expired; sign in again" +// EXPIRED is the built-in's words (errZCodeExpired) for a Start Plan +// sign-in past its end. +const EXPIRED = "ZCode's sign-in has expired; sign in to ZCode again (or add the account again in magpie)" const num = (v) => { const n = typeof v === "string" ? parseFloat(v) : v @@ -236,7 +238,7 @@ async function teamKey(s) { teamKeys.set(id, { key, at: Date.now() }) return key } catch (e) { - const err = new Error(`ZCode's team plan: ${e.message} — sign in again`) + const err = new Error(`ZCode's team plan: ${e.message} — sign in to ZCode again`) teamKeys.set(id, { err, at: Date.now() }) throw err } @@ -1093,7 +1095,15 @@ export async function ZCodeAuthPlugin({ client }) { h.delete("authorization") h.set("x-api-key", key) h.set("Authorization", "Bearer " + key) - return fetch(url, { ...opts, headers: h }) + const res = await fetch(url, { ...opts, headers: h }) + // the plan's 401 goes on as it came: the built-in never + // marked a ZCode account lapsed + if (res.status !== 401) return res + const kept = new Headers(res.headers) + kept.delete("content-length") + kept.delete("content-encoding") + kept.set("X-Magpie-Sign-In", "kept") + return new Response(res.body, { status: res.status, statusText: res.statusText, headers: kept }) }, } }, diff --git a/packages/zcode/package.json b/packages/zcode/package.json index fa6f452..4b72977 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.3", + "version": "0.1.4", "description": "OpenCode provider plugin: signs in to Z.ai's or BigModel's (智谱) GLM Coding Plan as ZCode does, including team seats and ZCode's Start Plan", "type": "module", "main": "./index.mjs", diff --git a/packages/zcode/signin.test.mjs b/packages/zcode/signin.test.mjs new file mode 100644 index 0000000..65760ab --- /dev/null +++ b/packages/zcode/signin.test.mjs @@ -0,0 +1,48 @@ +// A request's failures, as magpie's built-in ZCode account answered them +// (internal/provider/zcode.go zcodeProvider): the plan's 401 goes on as it +// came, saying X-Magpie-Sign-In: kept, as the built-in never marked a +// ZCode account lapsed; a Start Plan sign-in past its end fails in +// errZCodeExpired's words. +import { afterEach, beforeAll, expect, test } from "bun:test" +import { homedir, tmpdir } from "node:os" +import { realpathSync } from "node:fs" + +let ZCodeAuthPlugin +beforeAll(async () => { + if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test") + ;({ ZCodeAuthPlugin } = await import("./index.mjs")) +}) +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const jwt = (exp) => ["{}", JSON.stringify({ exp })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig" + +async function send(auth, reply) { + globalThis.fetch = async () => reply() + const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) + const opts = await hooks.auth.loader(async () => auth, { id: "zcode" }) + return opts.fetch("https://api.z.ai/api/anthropic/v1/messages", { method: "POST", body: "{}" }) +} + +const key = { type: "api", key: "one.secret", metadata: { site: "zai" } } + +test("the plan's 401 goes on as it came, the account kept", async () => { + const res = await send(key, () => Response.json({ error: { message: "token expired or incorrect" } }, { status: 401 })) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect(await res.json()).toEqual({ error: { message: "token expired or incorrect" } }) +}) + +test("other answers go as they came", async () => { + for (const status of [200, 429]) { + const res = await send(key, () => new Response("x", { status })) + expect(res.status).toBe(status) + expect(res.headers.get("X-Magpie-Sign-In")).toBeNull() + } +}) + +test("a Start Plan sign-in past its end fails as errZCodeExpired", async () => { + const s = { site: "zai", jwt: jwt(Math.floor(Date.now() / 1000) - 60) } + const auth = { type: "oauth", access: s.jwt, refresh: JSON.stringify(s), expires: 0 } + await expect(send(auth, () => new Response(""))).rejects.toThrow("ZCode's sign-in has expired; sign in to ZCode again (or add the account again in magpie)") +}) diff --git a/packages/zcode/usage.test.mjs b/packages/zcode/usage.test.mjs index 23208f1..27bac02 100644 --- a/packages/zcode/usage.test.mjs +++ b/packages/zcode/usage.test.mjs @@ -130,7 +130,7 @@ test("ZCode's Start Plan: its buckets, each for its models", async () => { expect((await usage(auth)).windows).toEqual([{ name: "GLM-5-Turbo", used: 25, display: "50 / 200", span: 7 * 86400, models: ["GLM-5-Turbo"] }]) // its token run out - expect(await usage(oauth({ site: "zai", jwt: jwt(now - 60) }))).toEqual({ error: "ZCode's sign-in has expired; sign in again" }) + expect(await usage(oauth({ site: "zai", jwt: jwt(now - 60) }))).toEqual({ error: "ZCode's sign-in has expired; sign in to ZCode again (or add the account again in magpie)" }) }) test("a team seat: the team plan's windows, name, end and resets, its key found and saved", async () => { diff --git a/packages/zed/errors.test.mjs b/packages/zed/errors.test.mjs index 49c4319..3c9f195 100644 --- a/packages/zed/errors.test.mjs +++ b/packages/zed/errors.test.mjs @@ -35,7 +35,7 @@ async function ask(wire, lines, stream = true) { body: JSON.stringify({ model: MODEL[wire], stream, messages: [{ role: "user", content: "hi" }], max_tokens: 100 }), }) const text = await res.text() - return { status: res.status, text } + return { status: res.status, text, signIn: res.headers.get("x-magpie-sign-in") } } const msgOf = (text) => { @@ -55,6 +55,9 @@ test("a rate limit Zed reports after the reply's start is the 429 it stands for" test("a failure keeps the status its code names on every API: 401 on chat, 403 on Responses, 402 for billing", async () => { const chat = await ask("chat", [{ status: "started" }, { status: { failed: { code: "upstream_http_401", message: "bad key upstream" } } }]) expect([chat.status, msgOf(chat.text)]).toEqual([401, "bad key upstream"]) + // a vendor's 401 in the stream never lapsed the built-in's account + expect(chat.signIn).toBe("kept") + expect((await ask("anthropic", [start, { status: { failed: { code: "upstream_http_401", message: "x" } } }], false)).signIn).toBe("kept") const resp = await ask("responses", [{ event: { type: "response.created", response: { id: "r1" } } }, { status: { failed: { code: "http_403", message: "no" } } }]) expect([resp.status, msgOf(resp.text)]).toEqual([403, "no"]) const bill = await ask("anthropic", [start, { status: { failed: { code: "billing_limit", message: "" } } }]) diff --git a/packages/zed/index.mjs b/packages/zed/index.mjs index 2a83a60..71ebe94 100644 --- a/packages/zed/index.mjs +++ b/packages/zed/index.mjs @@ -80,6 +80,11 @@ class ZedStatus extends Error { } } +// SignInExpired is Zed refusing the account's own sign-in (a 401 for its +// model token): the one failure the built-in marked the account lapsed for +// (zedLapse). +class SignInExpired extends Error {} + const parse = (s) => { try { return JSON.parse(s) @@ -125,9 +130,9 @@ function failedStatus(code) { function refusal(status, body) { if (status === 402) return [402, "payment required — this account's plan doesn't include Zed's hosted models, or its allowance is used up (see zed.dev/account)"] // a model token refused right after it was minted: the account's own - // sign-in just worked, so this isn't the sign-in lapsing (a 401 would - // have magpie mark it so, which the built-in never did here) - if (status === 401) return [403, "the sign-in was refused — sign in again"] + // sign-in just worked, so the built-in answered 401 without marking it + // (errorResponse says kept) + if (status === 401) return [401, "the sign-in was refused — sign in again"] const j = parse(body) ?? {} let code = status const up = Number(j.upstream_status) @@ -228,7 +233,7 @@ async function modelToken(s, renew) { return tok } catch (e) { tokens.delete(key) - if (e instanceof ZedStatus && e.status === 401) throw new Error(`${s.who || "the account"}'s Zed sign-in has expired — sign in again`) + if (e instanceof ZedStatus && e.status === 401) throw new SignInExpired(`${s.who || "the account"}: the Zed sign-in has expired — sign in again`) throw e } })() @@ -557,8 +562,15 @@ function errorBody(wire, status, message) { } } -const errorResponse = (wire, status, message) => - new Response(JSON.stringify(errorBody(wire, status, message)), { status, headers: { "content-type": "application/json" } }) +// errorResponse is a failure as the caller's API gives it. signIn is what it +// means for the account (magpie's X-Magpie-Sign-In): the built-in marked +// the account lapsed only when Zed refused its sign-in, so any other 401 +// (a model token refused twice, a vendor's upstream_http_401) is kept. +const errorResponse = (wire, status, message, signIn = status === 401 ? "kept" : undefined) => + new Response(JSON.stringify(errorBody(wire, status, message)), { + status, + headers: { "content-type": "application/json", ...(signIn ? { "x-magpie-sign-in": signIn } : {}) }, + }) // said tells whether one of the provider's own events says anything — // text, reasoning, a call, a finish — rather than only framing the reply, @@ -845,7 +857,8 @@ async function complete(s, url, init) { try { tok = await modelToken(s, t > 0) } catch (e) { - return errorResponse(w.wire, /sign in again/.test(e?.message ?? "") ? 401 : 502, String(e?.message ?? e).replace(/^Zed: /, "")) + if (e instanceof SignInExpired) return errorResponse(w.wire, 401, e.message, "expired") + return errorResponse(w.wire, 502, String(e?.message ?? e).replace(/^Zed: /, "")) } res = await fetch(CLOUD + "/completions", { method: "POST", diff --git a/packages/zed/package.json b/packages/zed/package.json index c5eb659..1c2c68e 100644 --- a/packages/zed/package.json +++ b/packages/zed/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zed-auth", - "version": "0.1.4", + "version": "0.1.5", "description": "Sign in to a Zed subscription (Zed Pro, trial, student, business) from OpenCode or magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/zed/usage.test.mjs b/packages/zed/usage.test.mjs index 1a88fa9..3b3ab3d 100644 --- a/packages/zed/usage.test.mjs +++ b/packages/zed/usage.test.mjs @@ -91,19 +91,42 @@ async function ask(replies) { return { res, body: await res.json(), seen } } -test("a model token refused right after it was minted isn't a lapsed sign-in (no 401)", async () => { +test("a model token refused right after it was minted is the built-in's 401, the account kept (not lapsed)", async () => { const tok = () => new Response(JSON.stringify({ token: "llm" })) const no = () => new Response("", { status: 401 }) const { res, body, seen } = await ask([tok, no, tok, no]) expect(seen).toEqual(["/client/llm_tokens", "/completions", "/client/llm_tokens", "/completions"]) - expect(res.status).toBe(403) + expect(res.status).toBe(401) + expect(res.headers.get("x-magpie-sign-in")).toBe("kept") expect(body.error.message).toBe("the sign-in was refused — sign in again") }) -test("the account's own sign-in refused is a 401, worded as the built-in's", async () => { - const { res, body } = await ask([() => new Response("", { status: 401 })]) - expect(res.status).toBe(401) - expect(body.error.message).toBe("octo's Zed sign-in has expired — sign in again") +test("the account's own sign-in refused is a 401 that marks it lapsed, worded as the built-in's", async () => { + let r = await ask([() => new Response("", { status: 401 })]) + expect(r.res.status).toBe(401) + expect(r.res.headers.get("x-magpie-sign-in")).toBe("expired") + expect(r.body.error.message).toBe("octo: the Zed sign-in has expired — sign in again") + // refused on the second mint, after a stale token: marked all the same + const tok = () => new Response(JSON.stringify({ token: "llm" })) + r = await ask([tok, () => new Response("", { status: 401 }), () => new Response("", { status: 401 })]) + expect([r.res.status, r.res.headers.get("x-magpie-sign-in")]).toEqual([401, "expired"]) +}) + +test("a mint that fails otherwise is a 502 that leaves the account be, whatever its body says", async () => { + const { res, body } = await ask([() => new Response(JSON.stringify({ message: "sign in again later" }), { status: 403 })]) + expect(res.status).toBe(502) + expect(res.headers.get("x-magpie-sign-in")).toBeNull() + expect(body.error.message).toBe("sign in again later (403)") +}) + +test("a vendor's 401 Zed passes on (upstream_status) is a 401 the account keeps; other refusals say nothing of it", async () => { + const tok = () => new Response(JSON.stringify({ token: "llm" })) + let r = await ask([tok, () => new Response(JSON.stringify({ code: "upstream", message: "bad key", upstream_status: 401 }), { status: 500 })]) + expect([r.res.status, r.res.headers.get("x-magpie-sign-in")]).toEqual([401, "kept"]) + r = await ask([tok, () => new Response("", { status: 403 })]) + expect([r.res.status, r.res.headers.get("x-magpie-sign-in")]).toEqual([403, null]) + r = await ask([tok, () => new Response("", { status: 402 })]) + expect([r.res.status, r.res.headers.get("x-magpie-sign-in")]).toEqual([402, null]) }) test("errors don't name Zed, which magpie adds", async () => {