diff --git a/packages/commandcode/cli-key.test.mjs b/packages/commandcode/cli-key.test.mjs new file mode 100644 index 0000000..59c90e4 --- /dev/null +++ b/packages/commandcode/cli-key.test.mjs @@ -0,0 +1,20 @@ +// An account taken from the CLI's sign-in uses the key the CLI has now, as +// magpie's built-in re-reads ~/.commandcode/auth.json: a `commandcode +// login` since changes it. Others keep the key they were saved with. +// Run with HOME a scratch folder (as `HOME=$(mktemp -d) bun test`). +import { expect, test } from "bun:test" +import { existsSync, mkdirSync, writeFileSync } from "node:fs" +import { homedir } from "node:os" +import { join } from "node:path" +import { _internal } from "./index.mjs" + +const home = homedir() + +test.skipIf(existsSync(join(home, ".commandcode")))("the CLI's account follows the CLI's key; a pasted key stays", async () => { + const cli = { type: "api", key: "saved", metadata: { cli: true } } + expect(await _internal.liveKey(cli)).toBe("saved") // the CLI signed out: the saved one + mkdirSync(join(home, ".commandcode")) + writeFileSync(join(home, ".commandcode", "auth.json"), JSON.stringify({ apiKey: "rotated" })) + expect(await _internal.liveKey(cli)).toBe("rotated") + expect(await _internal.liveKey({ type: "api", key: "pasted", metadata: {} })).toBe("pasted") +}) diff --git a/packages/commandcode/index.mjs b/packages/commandcode/index.mjs index f07f1f2..bc0cc01 100644 --- a/packages/commandcode/index.mjs +++ b/packages/commandcode/index.mjs @@ -414,7 +414,7 @@ async function browserSignIn() { : html(200, page(false, "Sign-in didn't finish", status.error || "Start it again.")) } if (path === "/cancel") { - finish({ state: "canceled" }, { type: "failed" }) + finish({ state: "canceled" }, { type: "failed", error: "the sign-in was canceled" }) return res.writeHead(204).end() } if (path !== "/callback") return res.writeHead(404).end() @@ -444,7 +444,7 @@ async function browserSignIn() { if (status.state !== "waiting") return answer(false, "this sign-in is over") if (got.error) { const msg = got.error === "access_denied" ? "the sign-in was denied" : got.error_description || got.error - finish({ state: "failed", error: msg }, { type: "failed" }) + finish({ state: "failed", error: msg }, { type: "failed", error: msg }) return answer(false, msg) } if (!got.apiKey) return answer(false, "Command Code sent back no key") @@ -453,7 +453,7 @@ async function browserSignIn() { finish({ state: "done", who: r.metadata.email }, r) answer(true, "") } catch (e) { - finish({ state: "failed", error: e.message }, { type: "failed" }) + finish({ state: "failed", error: e.message }, { type: "failed", error: e.message }) answer(false, e.message) } }) @@ -462,7 +462,7 @@ async function browserSignIn() { server.listen(0, "127.0.0.1", resolve) }) const port = server.address().port - const timer = setTimeout(() => finish({ state: "failed", error: "the sign-in timed out" }, { type: "failed" }), SIGN_IN_TIMEOUT) + const timer = setTimeout(() => finish({ state: "failed", error: "the sign-in timed out" }, { type: "failed", error: "the sign-in timed out" }), SIGN_IN_TIMEOUT) // the browser comes back for its page after the key: the server stays // up a while for it done.then(() => { @@ -489,15 +489,30 @@ async function cliSignIn() { callback: async () => { try { const a = JSON.parse(await readFile(path, "utf8")) - if (!String(a?.apiKey ?? "").trim()) return { type: "failed" } - return await success(a) - } catch { - return { type: "failed" } + if (!String(a?.apiKey ?? "").trim()) return { type: "failed", error: `Command Code's CLI isn't signed in: ${path} has no key` } + const r = await success(a) + r.metadata.cli = true + return r + } catch (e) { + return { type: "failed", error: e?.code === "ENOENT" ? "Command Code's CLI isn't signed in: run `commandcode login`" : e instanceof SyntaxError ? `${path} can't be read` : e.message } } }, } } +// liveKey is the key an account has now: one taken from the CLI's sign-in +// reads the CLI's again, as a `commandcode login` since may have changed +// it, and keeps the one it was saved with while the CLI has none. +async function liveKey(auth) { + if (!auth?.metadata?.cli) return auth?.key + try { + const a = JSON.parse(await readFile(join(homedir(), ".commandcode", "auth.json"), "utf8")) + const k = String(a?.apiKey ?? "").trim() + if (k) return k + } catch {} + return auth.key +} + // ---- the Go plan: /alpha/generate ---------------------------------------------- const session = randomUUID() // one x-session-id for as long as this runs, as one CLI session has @@ -849,7 +864,7 @@ async function generate(key, chat, signal) { // ---- the plugin --------------------------------------------------------------- -export const _internal = { subsSeen, waits } +export const _internal = { subsSeen, waits, liveKey } export async function CommandCodePlugin({ client } = {}) { return { @@ -858,7 +873,7 @@ export async function CommandCodePlugin({ client } = {}) { async loader(getAuth) { const auth = await getAuth() if (auth?.type !== "api" || !auth.key) return {} - const key = auth.key + const key = await liveKey(auth) const saved = auth.metadata?.plan return { baseURL: BASE, @@ -869,6 +884,7 @@ export async function CommandCodePlugin({ client } = {}) { async fetch(input, init = {}) { const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url const headers = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined)) + const key = await liveKey((await getAuth()) ?? auth) headers.set("Authorization", `Bearer ${key}`) headers.set("x-api-key", key) if (/\/chat\/completions$/.test(new URL(url).pathname) && (await planNow(key, saved)) === "Go") { @@ -895,7 +911,7 @@ export async function CommandCodePlugin({ client } = {}) { const auth = await getAuth() if (auth?.type !== "api" || !auth.key) return { error: "not signed in" } const md = auth.metadata ?? {} - const { out, read } = await usage(auth.key, md.plan ? { id: md.planId ?? "", plan: md.plan } : undefined) + const { out, read } = await usage(await liveKey(auth), md.plan ? { id: md.planId ?? "", plan: md.plan } : undefined) // the plan read is saved with the key, so a start doesn't wait on // billing/subscriptions again, for the models, Go's endpoint or this if (read && (read.plan !== md.plan || read.id !== (md.planId ?? "")) && client?.auth?.set) { @@ -923,10 +939,11 @@ export async function CommandCodePlugin({ client } = {}) { id: ID, async models(provider, { auth } = {}) { if (auth?.type !== "api" || !auth.key) return provider.models - if ((await planNow(auth.key, auth.metadata?.plan)) === "Go") + const key = await liveKey(auth) + if ((await planNow(key, auth.metadata?.plan)) === "Go") return Object.fromEntries(GO_MODELS.map((m) => [m.id, runtimeModel(m)])) try { - return Object.fromEntries((await liveModels(auth.key)).map((m) => [m.id, runtimeModel(m)])) + return Object.fromEntries((await liveModels(key)).map((m) => [m.id, runtimeModel(m)])) } catch { return provider.models } diff --git a/packages/commandcode/package.json b/packages/commandcode/package.json index 2c251be..a13651b 100644 --- a/packages/commandcode/package.json +++ b/packages/commandcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-commandcode-auth", - "version": "0.1.1", + "version": "0.1.2", "description": "Command Code plans (Pro, GOAT, Max, Ultra, Go, Teams) in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index 0e8bcad..2c577d7 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -268,7 +268,7 @@ async function browserSignIn() { try { res = await fetch(`${API}/auth/poll?uuid=${uuid}&verifier=${verifier}`, { headers, signal: AbortSignal.timeout(15_000) }) } catch { - if (++errors >= 3) return { type: "failed" } + if (++errors >= 3) return { type: "failed", error: "couldn't reach Cursor" } await sleep(wait) continue } @@ -278,12 +278,12 @@ async function browserSignIn() { continue } if (!res.ok) { - if (res.status === 403 || ++errors >= 3) return { type: "failed" } + if (res.status === 403 || ++errors >= 3) return { type: "failed", error: res.status === 403 ? "Cursor refused the sign-in (403)" : `Cursor's sign-in answered HTTP ${res.status}` } await sleep(wait) continue } const j = await res.json().catch(() => null) - if (!j?.accessToken || !("refreshToken" in j)) return { type: "failed" } + if (!j?.accessToken || !("refreshToken" in j)) return { type: "failed", error: "Cursor sent back no token" } const who = await whoIs(j.accessToken) return { type: "success", @@ -294,7 +294,7 @@ async function browserSignIn() { ...(who.plan ? { plan: who.plan } : {}), } } - return { type: "failed" } + return { type: "failed", error: "the sign-in timed out" } }, } } @@ -309,9 +309,10 @@ async function cliSignIn() { async callback() { const tok = await cliToken() const exp = expiry(tok) - if (!tok || (exp && exp <= Date.now())) return { type: "failed" } + if (!tok) return { type: "failed", error: "cursor-agent isn't signed in: run `cursor-agent login`" } + if (exp && exp <= Date.now()) return { type: "failed", error: "cursor-agent's sign-in has run out: run `cursor-agent login` again" } const who = await whoIs(tok) - if (!who.email) return { type: "failed" } + if (!who.email) return { type: "failed", error: "Cursor couldn't say which account is signed in" } return { type: "success", access: "", refresh: CLI_MARK, expires: 0, accountId: who.email, ...(who.plan ? { plan: who.plan } : {}) } }, } diff --git a/packages/cursor/package.json b/packages/cursor/package.json index d6a3531..a139d11 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.1.1", + "version": "0.1.2", "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/devin/cli-key.test.mjs b/packages/devin/cli-key.test.mjs new file mode 100644 index 0000000..06a72c4 --- /dev/null +++ b/packages/devin/cli-key.test.mjs @@ -0,0 +1,22 @@ +// An account taken from the CLI's sign-in uses the key credentials.toml +// has now, as magpie's built-in re-reads it: a `devin auth login` since +// changes it. Others keep the key they were saved with. +import { afterAll, expect, test } from "bun:test" +import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { _internal } from "./index.mjs" + +const was = process.env.XDG_DATA_HOME +const data = mkdtempSync(join(tmpdir(), "devin-data-")) +process.env.XDG_DATA_HOME = data +afterAll(() => (was === undefined ? delete process.env.XDG_DATA_HOME : (process.env.XDG_DATA_HOME = was))) + +test("the CLI's account follows credentials.toml; a browser sign-in stays", async () => { + const cli = { type: "api", key: "saved", metadata: { cli: true, server: "https://s.example" } } + expect(await _internal.live(cli)).toEqual({ key: "saved", server: "https://s.example" }) + mkdirSync(join(data, "devin")) + writeFileSync(join(data, "devin", "credentials.toml"), 'windsurf_api_key = "rotated"\napi_server_url = "https://t.example/"\n') + expect(await _internal.live(cli)).toEqual({ key: "rotated", server: "https://t.example" }) + expect(await _internal.live({ type: "api", key: "own", metadata: {} })).toMatchObject({ key: "own" }) +}) diff --git a/packages/devin/index.mjs b/packages/devin/index.mjs index 403e691..f7c4ff9 100644 --- a/packages/devin/index.mjs +++ b/packages/devin/index.mjs @@ -508,7 +508,7 @@ async function browserSignIn() { if (over) return html(200, page(false, "This sign-in is over", "Start it again.")) if (q.get("error")) { const msg = q.get("error_description") || q.get("error") - finish({ type: "failed" }) + finish({ type: "failed", error: msg }) return html(200, page(false, "Sign-in didn't finish", msg)) } if (q.get("state") !== state || !q.get("code")) return html(200, page(false, "This link isn't from this sign-in", "Start it again.")) @@ -518,7 +518,7 @@ async function browserSignIn() { finish(r) html(200, page(true, "You're signed in", `${r.metadata.email} is signed in. You can close this tab.`)) } catch (e) { - finish({ type: "failed" }) + finish({ type: "failed", error: e.message }) html(200, page(false, "Sign-in didn't finish", e.message)) } }) @@ -527,7 +527,7 @@ async function browserSignIn() { server.listen(0, "127.0.0.1", resolve) }) redirect = `http://127.0.0.1:${server.address().port}/callback` - const timer = setTimeout(() => finish({ type: "failed" }), SIGN_IN_TIMEOUT) + const timer = setTimeout(() => finish({ type: "failed", error: "the sign-in timed out" }), SIGN_IN_TIMEOUT) done.then(() => { clearTimeout(timer) setTimeout(() => server.close(), 5_000).unref?.() @@ -559,10 +559,12 @@ async function cliSignIn() { callback: async () => { try { const c = readCredentials(await readFile(path, "utf8")) - if (!c.windsurf_api_key) return { type: "failed" } - return await success(c.windsurf_api_key, (c.api_server_url || SERVER).replace(/\/+$/, "")) - } catch { - return { type: "failed" } + if (!c.windsurf_api_key) return { type: "failed", error: `Devin isn't signed in: ${path} has no key` } + const r = await success(c.windsurf_api_key, (c.api_server_url || SERVER).replace(/\/+$/, "")) + r.metadata.cli = true + return r + } catch (e) { + return { type: "failed", error: e?.code === "ENOENT" ? "Devin isn't signed in: run `devin auth login`" : e.message } } }, } @@ -1105,6 +1107,21 @@ async function usage(key, server) { const serverOf = (auth) => (process.env.WINDSURF_API_SERVER_URL || auth?.metadata?.server || SERVER).replace(/\/+$/, "") +// live is the key and server an account has now: one taken from the CLI's +// sign-in reads credentials.toml again, as a `devin auth login` since may +// have changed it, and keeps the ones it was saved with while the CLI has +// none. +async function live(auth) { + if (auth?.metadata?.cli) { + try { + const c = readCredentials(await readFile(cliCredentialsPath(), "utf8")) + if (c.windsurf_api_key) + return { key: c.windsurf_api_key, server: (process.env.WINDSURF_API_SERVER_URL || c.api_server_url || SERVER).replace(/\/+$/, "") } + } catch {} + } + return { key: auth?.key, server: serverOf(auth) } +} + export async function DevinAuthPlugin() { return { auth: { @@ -1127,9 +1144,9 @@ export async function DevinAuthPlugin() { } catch { return errorResponse({ status: 400, message: "Devin: a request that isn't JSON" }) } - const server = serverOf(now) - const families = await familiesFor(now.key, server) - return complete({ key: now.key, server, families }, chat, init.signal) + const { key, server } = await live(now) + const families = await familiesFor(key, server) + return complete({ key, server, families }, chat, init.signal) }, } }, @@ -1141,7 +1158,8 @@ export async function DevinAuthPlugin() { async usage(getAuth) { const auth = await getAuth() if (auth?.type !== "api" || !auth.key) return { error: "Devin isn't signed in" } - return usage(auth.key, serverOf(auth)) + const { key, server } = await live(auth) + return usage(key, server) }, }, async config(config) { @@ -1160,7 +1178,8 @@ export async function DevinAuthPlugin() { id: ID, async models(provider, { auth } = {}) { if (auth?.type !== "api" || !auth.key || !cliPath()) return provider.models - const families = await familiesFor(auth.key, serverOf(auth)) + const { key, server } = await live(auth) + const families = await familiesFor(key, server) return Object.fromEntries(listed(families).map((m) => [m.id, runtimeModel(m)])) }, }, @@ -1168,4 +1187,4 @@ export async function DevinAuthPlugin() { } // for tests -export const _internal = { build, failure, complete, parseFamilies, listed, variantFor, familiesOf, SNAPSHOT, parseStatus, readCredentials, credentials, fields, frame, PB, events, frames } +export const _internal = { live, build, failure, complete, parseFamilies, listed, variantFor, familiesOf, SNAPSHOT, parseStatus, readCredentials, credentials, fields, frame, PB, events, frames } diff --git a/packages/devin/package.json b/packages/devin/package.json index 0c5d162..c019f4a 100644 --- a/packages/devin/package.json +++ b/packages/devin/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-devin-auth", - "version": "0.1.1", + "version": "0.1.2", "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 cc0e888..8364664 100644 --- a/packages/factory/index.mjs +++ b/packages/factory/index.mjs @@ -253,8 +253,19 @@ const orgRefused = (status, text) => status === 403 && text.toLowerCase().includ // the request carries what droid sends. function explain(status, text) { if (status !== 403) return "" - if (orgRefused(status, text)) return "the Factory account's organization changed; sign in to it again" - return "Factory refused this account the request; check that `droid`, signed in to the same account and organization, can use this model (an organization's model policy or the plan may not allow it), and if it can, sign in to the Factory account again" + if (orgRefused(status, text)) return "the Factory account's organization changed; remove the account in magpie and sign in to it again" + return "Factory refused this account the request; check that `droid`, signed in to the same account and organization, can use this model (an organization's model policy or the plan may not allow it), and if it can, remove the Factory account in magpie and sign in to it again" +} + +// errorReply is an error as the API the request was for words one: +// Anthropic's on /llm/a/, OpenAI's on the others. +function errorReply(url, status, type, message, headers = new Headers()) { + headers.set("content-type", "application/json") + headers.delete("content-length") + headers.delete("content-encoding") + const anthropic = new URL(url).pathname.includes("/llm/a/") + const body = anthropic ? { type: "error", error: { type, message } } : { error: { message, type, code: null } } + return new Response(JSON.stringify(body), { status, headers }) } // ---- sign-in ---------------------------------------------------------------- @@ -462,9 +473,11 @@ export const FactoryAuthPlugin = async ({ client }) => { lock = run.catch(() => {}) return run } - // when the account last asked whoami for its org, so one whoami can't - // answer doesn't ask before every request - let asked = 0 + // when each account last asked whoami for its org, so one whoami can't + // answer doesn't ask before every request, nor hold back the others + const asked = new Map() + const askedOf = (c) => asked.get(c.accountId || c.refresh || "") ?? 0 + const ask = (c) => asked.set(c.accountId || c.refresh || "", Date.now()) // account is the account getAuth reads, with what keeps its token live // and its org right. @@ -483,8 +496,8 @@ export const FactoryAuthPlugin = async ({ client }) => { // whoami as soon as it holds a token and sends the orgId it answers // as X-Factory-Org-Id on every request after. const orgOf = async (c) => { - if (c.activeOrganizationId || Date.now() - asked < ASK_AGAIN) return c - asked = Date.now() + if (c.activeOrganizationId || Date.now() - askedOf(c) < ASK_AGAIN) return c + ask(c) if (await reconcile(c)) await save(c) return c } @@ -500,7 +513,7 @@ export const FactoryAuthPlugin = async ({ client }) => { } catch (e) { // a hiccup while the token still runs: go on with it if (!refused(e) && c.expires > 0 && Date.now() < c.expires) return orgOf(c) - if (refused(e)) throw new Error(`${c.accountId || "the account"}'s Factory sign-in has expired — sign in again (${e.message})`) + if (refused(e)) throw Object.assign(new Error(`${c.accountId || "the account"}'s Factory sign-in has expired — sign in again (${e.message})`), { lapsed: true }) throw e } c.access = t.access_token @@ -508,7 +521,7 @@ export const FactoryAuthPlugin = async ({ client }) => { if (t.refresh_token) c.refresh = t.refresh_token // droid asks whoami again for each new token, keeping the org it names await reconcile(c) - asked = Date.now() + ask(c) await save(c) return c }) @@ -528,12 +541,12 @@ export const FactoryAuthPlugin = async ({ client }) => { const was = c.activeOrganizationId c.activeOrganizationId = "" if ((await reconcile(c)) && c.activeOrganizationId === was) c.activeOrganizationId = "" // whoami names the org refused: send none - asked = Date.now() + ask(c) await save(c) return true } if (!isOrg) { - asked = Date.now() + ask(c) if ((await reconcile(c)) && c.activeOrganizationId) { await save(c) return true @@ -651,7 +664,15 @@ export const FactoryAuthPlugin = async ({ client }) => { let body = init?.body 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()) - let res = await send(input, init, body) + const url = input instanceof Request ? input.url : String(input) + let res + try { + res = await send(input, init, body) + } 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) + throw e + } if (res.status !== 403) return res let text = await res.text() if (await mendOrg(res.status, text).catch(() => false)) { @@ -661,15 +682,7 @@ export const FactoryAuthPlugin = async ({ client }) => { } const why = explain(res.status, text) const msg = `${apiError(text, "Forbidden")}: ${why}` - const headers = new Headers(res.headers) - headers.set("content-type", "application/json") - headers.delete("content-length") - headers.delete("content-encoding") - return new Response(JSON.stringify({ type: "error", error: { type: "permission_error", message: msg } }), { - status: res.status, - statusText: res.statusText, - headers, - }) + 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 new file mode 100644 index 0000000..5e2f884 --- /dev/null +++ b/packages/factory/lapsed.test.mjs @@ -0,0 +1,54 @@ +// 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. +import { afterEach, expect, test } from "bun:test" +import { FactoryAuthPlugin } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const expired = { + type: "oauth", + access: "tok-old", + refresh: "r-old", + expires: Date.now() - 1000, + accountId: "ada", + activeOrganizationId: "fac_A", + region: "", + premBaseHost: "", +} + +async function loaded() { + const seen = [] + globalThis.fetch = async (url) => { + const u = new URL(String(url)) + seen.push(u.pathname) + if (u.pathname.endsWith("/authenticate")) return new Response(JSON.stringify({ error: "invalid_grant" }), { status: 400 }) + return new Response("upstream reached", { status: 500 }) + } + let auth = { ...expired } + const client = { auth: { set: async ({ body }) => (auth = body) } } + const hooks = await FactoryAuthPlugin({ client }) + const l = await hooks.auth.loader(async () => auth) + return { l, seen } +} + +test("a refused renewal is Anthropic's 401 on /llm/a/", 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) + 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(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) + const b = await res.json() + expect(b.error.type).toBe("authentication_error") + expect(b.error.code).toBe(null) + expect(b.type).toBeUndefined() +}) diff --git a/packages/factory/package.json b/packages/factory/package.json index 9c86532..6f48de5 100644 --- a/packages/factory/package.json +++ b/packages/factory/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-factory-auth", - "version": "0.1.1", + "version": "0.1.2", "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/kiro/index.mjs b/packages/kiro/index.mjs index addfe97..684fe14 100644 --- a/packages/kiro/index.mjs +++ b/packages/kiro/index.mjs @@ -1171,7 +1171,7 @@ async function browserSignIn() { const q = url.searchParams if (!waiting) return html(200, page(false, "This sign-in is over", "Start it again.")) const fail = (msg) => { - finish({ type: "failed" }) + finish({ type: "failed", error: msg }) html(200, page(false, "Sign-in didn't finish", msg)) } if (q.get("error")) return fail(q.get("error_description") || q.get("error")) @@ -1226,7 +1226,7 @@ async function browserSignIn() { html(200, page(true, "You're signed in", `${user} is signed in. You can close this tab.`)) }) - const timer = setTimeout(() => finish({ type: "failed" }), SIGN_IN_TIMEOUT) + const timer = setTimeout(() => finish({ type: "failed", error: "the sign-in timed out" }), SIGN_IN_TIMEOUT) done.then(() => { clearTimeout(timer) setTimeout(() => server.close(), 10_000).unref?.() @@ -1251,7 +1251,7 @@ async function ownSignIn() { callback: async () => { const cli = await readCLI() const c = cli ?? (await readIDE()) - if (!c) return { type: "failed" } + if (!c) return { type: "failed", error: "neither kiro-cli nor the Kiro IDE is signed in" } const who = fresh(c) ? await whoIs(c) : { email: "", plan: "" } return { type: "success", provider: ID, refresh: "", access: "", expires: 0, source: cli ? "kiro-cli" : "kiro-ide", accountId: who.email || (cli ? "kiro-cli's account" : "Kiro IDE's account"), ...(who.plan ? { plan: who.plan } : {}) } diff --git a/packages/kiro/package.json b/packages/kiro/package.json index 8ba3cd6..d52b73f 100644 --- a/packages/kiro/package.json +++ b/packages/kiro/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-kiro-auth", - "version": "0.1.1", + "version": "0.1.2", "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/mimo/index.mjs b/packages/mimo/index.mjs index d4d4d39..bf3b7e4 100644 --- a/packages/mimo/index.mjs +++ b/packages/mimo/index.mjs @@ -493,8 +493,8 @@ export const MimoAuthPlugin = async ({ client }) => { const p = await waitPoll(t) const { creds, cookies } = await signedInWith(p, t.device) return { ...toAuth(creds, cookies, Date.now()), type: "success" } - } catch { - return { type: "failed" } + } catch (e) { + return { type: "failed", error: e.message } } }, } diff --git a/packages/mimo/package.json b/packages/mimo/package.json index 6946d61..421ca10 100644 --- a/packages/mimo/package.json +++ b/packages/mimo/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-mimo-auth", - "version": "0.1.1", + "version": "0.1.2", "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/workbuddy/index.mjs b/packages/workbuddy/index.mjs index b6c79b1..b73d14a 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -243,7 +243,7 @@ async function browserSignIn(site) { const deadline = Date.now() + SIGN_IN_MS const q = encodeURIComponent(state.state) const token = await poll(site, `/v2/plugin/auth/token?state=${q}`, {}, [11217], deadline) - if (!token.accessToken) return { type: "failed" } + if (!token.accessToken) return { type: "failed", error: `${site.name} sent back no token` } let a = merge({}, token) const who = await poll(site, `/v2/plugin/login/account?state=${q}`, { Authorization: "Bearer " + a.access, @@ -253,8 +253,8 @@ async function browserSignIn(site) { }, [12151], deadline) a.uid = who.uid ?? "" return success(site, a, who.nickname || who.phoneNumber || who.uid) - } catch { - return { type: "failed" } + } catch (e) { + return { type: "failed", error: e.message } } }, } @@ -319,7 +319,7 @@ function desktopSignIn(site) { method: "auto", async callback() { const d = readDesktop(site) - if (!d) return { type: "failed" } + if (!d) return { type: "failed", error: `${site.name} desktop isn't signed in` } return { type: "success", refresh: "", access: "", expires: 0, source: "desktop", accountId: d.name || site.name, uid: d.uid } }, } diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 224011b..564c3e3 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.2", + "version": "0.1.3", "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/usage.test.mjs b/packages/workbuddy/usage.test.mjs index 19d4613..d6034bc 100644 --- a/packages/workbuddy/usage.test.mjs +++ b/packages/workbuddy/usage.test.mjs @@ -124,3 +124,10 @@ test("the desktop's sign-in is renewed in memory only", async () => { await usageOf(WorkBuddyAuthPlugin, auth, client) expect(calls.filter((c) => c.url.pathname.endsWith("/refresh")).length).toBe(1) }) + +test("a desktop sign-in with the app signed out says why it failed", async () => { + const p = await WorkBuddyAIAuthPlugin({ client: {} }) + const m = p.auth.methods.find((x) => x.label.endsWith("desktop's sign-in")) + const r = await (await m.authorize()).callback() + expect(r).toEqual({ type: "failed", error: "WorkBuddy AI desktop isn't signed in" }) +}) diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index c0c9490..cde5226 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -661,7 +661,7 @@ async function authorize(site, log) { instructions: `Sign in to ${SITES[site].name} in the browser; this finishes on its own.`, method: "auto", async callback() { - const fail = (msg) => (log(msg), { type: "failed" }) + const fail = (msg) => (log(msg), { type: "failed", error: msg }) for (;;) { await sleep(interval) if (Date.now() > deadline) return fail("the sign-in expired; start again") diff --git a/packages/zcode/package.json b/packages/zcode/package.json index c8db9f2..141e9b6 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.1", + "version": "0.1.2", "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/zed/index.mjs b/packages/zed/index.mjs index 3d70201..0f244d8 100644 --- a/packages/zed/index.mjs +++ b/packages/zed/index.mjs @@ -424,10 +424,10 @@ async function signIn() { let timer try { const cb = await Promise.race([back, new Promise((r) => (timer = setTimeout(() => r(null), SIGN_IN_TIMEOUT)))]) - if (!cb) return { type: "failed" } + if (!cb) return { type: "failed", error: "the sign-in timed out" } return await signedInWith(privateKey, cb.uid, cb.tok, systemId) - } catch { - return { type: "failed" } + } catch (e) { + return { type: "failed", error: e.message } } finally { clearTimeout(timer) close() diff --git a/packages/zed/package.json b/packages/zed/package.json index fecc9f7..f0b5b04 100644 --- a/packages/zed/package.json +++ b/packages/zed/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zed-auth", - "version": "0.1.1", + "version": "0.1.2", "description": "Sign in to a Zed subscription (Zed Pro, trial, student, business) from OpenCode or magpie", "type": "module", "main": "./index.mjs",