diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index e2136fd..035ad90 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -311,6 +311,64 @@ async function deviceSignIn(site) { } } +// exchangeExpiry is when a job token from /api/v1/jobToken/exchange runs +// out, as Qoder's own client reads it: expire_time or expires_at (a date) +// first, then expires_in (milliseconds), then a day. +function exchangeExpiry(jt) { + for (const k of ["expire_time", "expires_at"]) { + const at = Date.parse(String(jt?.[k] ?? "").trim()) + if (!isNaN(at)) return at + } + if (jt?.expires_in > 0) return Date.now() + jt.expires_in + return Date.now() + DAY +} + +// exchangeToken is the job token from an exchange response, as Qoder's +// client reads it: token, device_token or access_token. +function exchangeToken(jt) { + return String(jt?.token ?? jt?.device_token ?? jt?.access_token ?? "").trim() +} + +// patSignIn exchanges a Personal Access Token for a job token, bypassing +// the OAuth device flow. PATs are long-lived (up to 1 year): the PAT is +// kept on the credential, and when the job token's refresh lapses the PAT +// is exchanged again rather than asking the user to sign in once more. +async function patSignIn(site, pat) { + const machineId = randomUUID() + const r = await openapi(site, "/api/v1/jobToken/exchange", { method: "POST", body: { personal_token: pat } }) + if (r.status === 400 || r.status === 401 || r.status === 403) + throw Object.assign(new Error(`${site.name} refused the PAT — check it is still valid`), { status: r.status }) + if (r.status !== 200) throw new Error(`${site.name} PAT exchange: status ${r.status}`) + const token = exchangeToken(r.json) + if (!token) throw new Error(`${site.name} PAT exchange: empty token in response`) + const refresh = String(r.json?.refresh_token ?? r.json?.refreshToken ?? "").trim() + const chat = { access: token, refresh, expires: exchangeExpiry(r.json) } + let email = "" + let name = "" + let uid = "" + try { + const ui = await openapi(site, "/api/v1/userinfo", { token }) + if (ui.status >= 200 && ui.status < 300) { + ;[email, name] = [ui.json?.email ?? "", ui.json?.name ?? ""] + uid = String(ui.json?.id ?? ui.json?.user_id ?? ui.json?.uid ?? "") + } + } catch {} + if (!uid) throw new Error(`${site.name} PAT sign-in: could not determine user id`) + return { + type: "success", + ...chat, + accountId: email || uid, + uid, + email, + name: name || "", + machineId, + deviceToken: "", + deviceRefresh: "", + patAuth: true, + pat, + } +} + // 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, @@ -1372,7 +1430,8 @@ const makePlugin = (site) => async ({ client }) => { return got } // renew spends a's chat refresh token, under the lock: the fields it - // changes, recorded in spent. + // changes, recorded in spent. A PAT account whose job refresh has lapsed + // exchanges the PAT again: the PAT lasts a year, the refresh two days. const renew = async (a) => { const s = siteOf(site, a) if (a.deviceChat) { @@ -1381,7 +1440,22 @@ const makePlugin = (site) => async ({ client }) => { const dt = await refreshDevice(s, a.refresh, true) return spend(a.refresh, { access: dt.token, refresh: dt.refresh, expires: dt.expires, deviceToken: dt.token, deviceRefresh: dt.refresh }) } - const jt = await refreshJob(s, a.refresh, a.accountId || a.email || a.uid) + let jt + try { + jt = await refreshJob(s, a.refresh, a.accountId || a.email || a.uid) + } catch (e) { + if (!(e instanceof SignInGone) || !a.patAuth || !a.pat) throw e + let ex + try { + ex = await patSignIn(s, a.pat) + } catch (p) { + // a PAT lapses too — out of date, or revoked: Qoder's refusal ends + // the sign-in as a lapsed device one does, not as a server fault + if (!p?.status) throw p + throw new SignInGone(`${site.name} refused the PAT — sign in again with a new one`, true) + } + return spend(a.refresh, { access: ex.access, refresh: ex.refresh, expires: ex.expires }) + } return spend(a.refresh, { access: jt.token, refresh: jt.refresh_token, expires: expiresAt(jt) }) } // each account's listing, the model configs a request carries @@ -1450,6 +1524,14 @@ const makePlugin = (site) => async ({ client }) => { try { const cred = await fresh(getAuth) if (renewed(cred)) signIn = "renewed" + // A PAT account has no device token: the usage endpoint takes the job + // token the exchange gave — a live PAT account answered 200 with a + // qoder envelope. Its errors surface as the device path's do; there is + // no second token here to rotate and retry with. + if (cred.patAuth && !cred.deviceToken) { + const env = await fetchUsage(siteOf(site, cred), cred.access) + return { ...parseUsage(env), signIn } + } let env try { env = await fetchUsage(siteOf(site, cred), cred.deviceToken) @@ -1583,6 +1665,40 @@ const makePlugin = (site) => async ({ client }) => { }, methods: [ { type: "oauth", label: `Sign in with ${site.name}`, authorize: () => deviceSignIn(site) }, + // PAT sign-in: exchange a Personal Access Token for a job token, + // bypassing the OAuth device flow. PATs last up to 1 year. + // Not offered on Qoder CN: its CLI uses device chat directly and + // never makes a job token, so a PAT exchange may not produce one + // the chat endpoint accepts. + ...(site.id !== "qoder-cn" + ? [ + { + type: "oauth", + label: `Sign in with ${site.name} PAT`, + prompts: [ + { + type: "password", + key: "pat", + message: "Your Qoder Personal Access Token (from qoder.com/account/integrations)", + placeholder: "pt-...", + validate: (v) => (String(v ?? "").trim().startsWith("pt-") ? undefined : "PAT must start with pt-"), + }, + ], + authorize: (inputs) => { + const pat = String(inputs?.pat ?? "").trim() + if (!pat) throw new Error("enter your Personal Access Token") + return { + url: `${site.web}/account/integrations`, + instructions: `Create a PAT at ${site.web}/account/integrations if you don't have one`, + method: "auto", + async callback() { + return patSignIn(site, pat) + }, + } + }, + }, + ] + : []), // an enterprise VPC instance (Qoder CN), a method of its own so // that the sign-in above asks nothing new ...(site.vpcDomain diff --git a/packages/qoder/package.json b/packages/qoder/package.json index 41b0905..c8ee333 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.2.14", + "version": "0.2.15", "description": "Qoder subscriptions in OpenCode and magpie: Qoder (qoder.com) and Qoder CN (qoder.cn)", "type": "module", "main": "./index.mjs", diff --git a/packages/qoder/pat.test.mjs b/packages/qoder/pat.test.mjs new file mode 100644 index 0000000..5ec576d --- /dev/null +++ b/packages/qoder/pat.test.mjs @@ -0,0 +1,249 @@ +// PAT sign-in: exchange a Personal Access Token for a job token, bypassing +// the OAuth device flow. PAT is only offered on the global site (qoder.com), +// not on Qoder CN (which uses device chat directly). +import { afterEach, expect, test } from "bun:test" +import { QoderAuthPlugin, QoderCNAuthPlugin } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json" } }) + +async function plugin(auth) { + let stored = auth + const client = { auth: { set: async ({ body }) => (stored = body) } } + const hooks = await QoderAuthPlugin({ client }) + return { hooks, get: async () => stored } +} + +test("qoder: PAT auth method is listed", async () => { + const { hooks } = await plugin(null) + const patMethod = hooks.auth.methods.find((m) => m.label?.includes("PAT")) + expect(patMethod).toBeDefined() + expect(patMethod.type).toBe("oauth") + expect(patMethod.prompts).toHaveLength(1) + expect(patMethod.prompts[0].key).toBe("pat") + expect(patMethod.prompts[0].type).toBe("password") +}) + +test("qoder-cn: PAT auth method is NOT listed", async () => { + const client = { auth: { set: async () => {} } } + const hooks = await QoderCNAuthPlugin({ client }) + const patMethod = hooks.auth.methods.find((m) => m.label?.includes("PAT")) + expect(patMethod).toBeUndefined() +}) + +test("qoder: PAT auth method validates PAT format", async () => { + const { hooks } = await plugin(null) + const patMethod = hooks.auth.methods.find((m) => m.label?.includes("PAT")) + const validate = patMethod.prompts[0].validate + expect(validate("pt-abc123")).toBeUndefined() + expect(validate("invalid")).toContain("pt-") + expect(validate("")).toContain("pt-") +}) + +test("qoder: PAT sign-in exchanges token and returns credentials", async () => { + const calls = [] + globalThis.fetch = async (url, init = {}) => { + const u = new URL(String(url)) + calls.push(u.host + u.pathname) + if (u.host === "openapi.qoder.sh" && u.pathname === "/api/v1/jobToken/exchange") { + const body = JSON.parse(init.body) + expect(body.personal_token).toBe("pt-test123") + return json({ token: "jt-pat", refresh_token: "jrt-pat", expires_in: 86400000, expires_at: new Date(Date.now() + 86400000).toISOString(), refresh_token_expires_at: new Date(Date.now() + 172800000).toISOString(), refresh_token_expires_in: 172800000 }) + } + if (u.host === "openapi.qoder.sh" && u.pathname === "/api/v1/userinfo") { + return json({ id: "user-123", email: "test@example.com", name: "Test User" }) + } + return new Response("", { status: 500 }) + } + const { hooks } = await plugin(null) + const patMethod = hooks.auth.methods.find((m) => m.label?.includes("PAT")) + const flow = patMethod.authorize({ pat: "pt-test123" }) + expect(flow.url).toContain("account/integrations") + expect(flow.method).toBe("auto") + const result = await flow.callback() + expect(result.type).toBe("success") + expect(result.access).toBe("jt-pat") + expect(result.refresh).toBe("jrt-pat") + expect(result.uid).toBe("user-123") + expect(result.email).toBe("test@example.com") + expect(result.patAuth).toBe(true) + expect(result.pat).toBe("pt-test123") + expect(result.deviceToken).toBe("") + expect(result.machineId).toBeTruthy() + expect(calls).toContain("openapi.qoder.sh/api/v1/jobToken/exchange") + expect(calls).toContain("openapi.qoder.sh/api/v1/userinfo") +}) + +test("qoder: PAT sign-in reads alternate response fields", async () => { + globalThis.fetch = async (url) => { + const u = new URL(String(url)) + if (u.pathname === "/api/v1/jobToken/exchange") { + return json({ access_token: "jt-alt", refreshToken: "jrt-alt", expire_time: new Date(Date.now() + 7200_000).toISOString() }) + } + if (u.pathname === "/api/v1/userinfo") { + return json({ id: "user-alt", email: "alt@example.com" }) + } + return new Response("", { status: 500 }) + } + const { hooks } = await plugin(null) + const patMethod = hooks.auth.methods.find((m) => m.label?.includes("PAT")) + const result = await patMethod.authorize({ pat: "pt-alt" }).callback() + expect(result.access).toBe("jt-alt") + expect(result.refresh).toBe("jrt-alt") + expect(result.expires).toBeGreaterThan(Date.now()) + expect(result.expires).toBeLessThanOrEqual(Date.now() + 7200_000) +}) + +test("qoder: PAT sign-in fails when Qoder refuses the PAT", async () => { + globalThis.fetch = async () => new Response("Bad request", { status: 400 }) + const { hooks } = await plugin(null) + const patMethod = hooks.auth.methods.find((m) => m.label?.includes("PAT")) + const flow = patMethod.authorize({ pat: "pt-bad" }) + const err = await flow.callback().catch((e) => e) + expect(err).toBeInstanceOf(Error) + expect(err.message).toContain("refused the PAT") +}) + +test("qoder: PAT sign-in fails when no user id", async () => { + globalThis.fetch = async (url) => { + const u = new URL(String(url)) + if (u.pathname === "/api/v1/jobToken/exchange") return json({ token: "jt-x", refresh_token: "jrt-x", expires_in: 86400000 }) + if (u.pathname === "/api/v1/userinfo") return json({ email: "no-id@example.com" }) + return new Response("", { status: 500 }) + } + const { hooks } = await plugin(null) + const patMethod = hooks.auth.methods.find((m) => m.label?.includes("PAT")) + const flow = patMethod.authorize({ pat: "pt-no-id" }) + const err = await flow.callback().catch((e) => e) + expect(err).toBeInstanceOf(Error) + expect(err.message).toContain("user id") +}) + +const patCredential = (over = {}) => ({ + type: "oauth", + access: "jt-old", + refresh: "jrt-old", + expires: Date.now() - 1000, + uid: "user-re", + email: "re@example.com", + accountId: "re@example.com", + name: "", + machineId: "machine-1", + deviceToken: "", + deviceRefresh: "", + patAuth: true, + pat: "pt-reexchange", + ...over, +}) + +// the exchange and refresh endpoints a renew through the real path meets, +// shared by the tests below +function mockRenew() { + const calls = [] + let exchangeCount = 0 + globalThis.fetch = async (url, init = {}) => { + const u = new URL(String(url)) + calls.push(u.host + u.pathname + (init.body ? " " + init.body : "")) + if (u.host === "openapi.qoder.sh" && u.pathname === "/api/v1/jobToken/refresh") { + return json({ message: "refresh token expired" }, 401) + } + if (u.pathname === "/api/v1/jobToken/exchange") { + exchangeCount++ + return json({ token: `jt-exchange-${exchangeCount}`, refresh_token: `jrt-exchange-${exchangeCount}`, expires_in: 86400000 }) + } + if (u.pathname === "/api/v1/userinfo") { + return json({ id: "user-re", email: "re@example.com" }) + } + if (u.pathname === "/sash/api/v2/me/usage") { + return json({ displayMode: "qoder", qoderUsage: { userType: "pro", userQuota: { name: "Credits", total: 100, used: 10, unit: "credits" } } }) + } + return new Response("", { status: 500 }) + } + return { calls, exchanged: () => exchangeCount } +} + +test("qoder: lapsed job refresh re-exchanges the stored PAT on the real path", async () => { + const mock = mockRenew() + const { hooks, get } = await plugin(patCredential()) + const out = await hooks.auth.usage(get) + // the exchange was asked with the stored PAT, not a prompt's + expect(mock.calls.some((c) => c.startsWith("openapi.qoder.sh/api/v1/jobToken/exchange ") && c.endsWith('"personal_token":"pt-reexchange"}'))).toBe(true) + expect(mock.exchanged()).toBe(1) + // the usage request went on with the new job token + const usage = mock.calls.find((c) => c.startsWith("openapi.qoder.sh/sash/api/v2/me/usage")) + expect(usage).toBe("openapi.qoder.sh/sash/api/v2/me/usage") + expect(out).toEqual({ + plan: "pro", + windows: [{ name: "Credits", used: 10, display: "10 / 100 credits" }], + signIn: "renewed", + }) + // the saved credential is the renewed one, still carrying the PAT + const saved = await get() + expect(saved.access).toBe("jt-exchange-1") + expect(saved.refresh).toBe("jrt-exchange-1") + expect(saved.patAuth).toBe(true) + expect(saved.pat).toBe("pt-reexchange") +}) + +test("qoder: lapsed job refresh without a stored PAT surfaces sign-in gone", async () => { + const mock = mockRenew() + const { pat, ...noPat } = patCredential() + const { hooks, get } = await plugin(noPat) + const out = await hooks.auth.usage(get) + // no re-exchange without a PAT to re-exchange + expect(mock.exchanged()).toBe(0) + expect(out.error).toContain("sign-in has expired") + expect(out.signIn).toBe("expired") + // the store was left as it was + expect((await get()).access).toBe("jt-old") +}) + +test("qoder: PAT account usage reads the usage endpoint with the job token", async () => { + let auth = "" + globalThis.fetch = async (url, init = {}) => { + const u = new URL(String(url)) + if (u.pathname === "/sash/api/v2/me/usage") { + auth = init.headers.Authorization + return json({ displayMode: "qoder", qoderUsage: { userType: "pro", userQuota: { name: "Credits", total: 200, used: 50, unit: "credits" } } }) + } + return new Response("", { status: 500 }) + } + const live = patCredential({ access: "jt-live", expires: Date.now() + 86400000 }) + const { hooks } = await plugin(live) + const out = await hooks.auth.usage(async () => live) + expect(auth).toBe("Bearer jt-live") + expect(out).toEqual({ + plan: "pro", + windows: [{ name: "Credits", used: 25, display: "50 / 200 credits" }], + signIn: "kept", + }) +}) + +test("qoder: PAT account usage surfaces a refused job token", async () => { + globalThis.fetch = async () => json({ message: "unauthorized" }, 401) + const live = patCredential({ access: "jt-live", expires: Date.now() + 86400000 }) + const { hooks } = await plugin(live) + const out = await hooks.auth.usage(async () => live) + expect(out.error).toBe("qoder usage: upstream HTTP 401") + expect(out.signIn).toBe("kept") + expect(out.plan).toBeUndefined() +}) + +test("qoder: a refused PAT re-exchange ends the sign-in", async () => { + globalThis.fetch = async (url) => { + const u = new URL(String(url)) + if (u.pathname === "/api/v1/jobToken/refresh") return json({ message: "refresh token expired" }, 401) + if (u.pathname === "/api/v1/jobToken/exchange") return json({ message: "PAT expired" }, 401) + return new Response("", { status: 500 }) + } + const { hooks, get } = await plugin(patCredential()) + const out = await hooks.auth.usage(get) + expect(out.signIn).toBe("expired") + expect(out.error).toContain("sign in again") + const l = await hooks.auth.loader(get) + const res = await l.fetch(l.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ model: "efficient" }) }) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") +}) diff --git a/packages/qoder/vpc.test.mjs b/packages/qoder/vpc.test.mjs index 1d0ed1c..9e50175 100644 --- a/packages/qoder/vpc.test.mjs +++ b/packages/qoder/vpc.test.mjs @@ -89,8 +89,8 @@ test("the public sign-in is unchanged: it is still the first method and asks not expect(hooks.auth.methods[0].prompts).toBeUndefined() const u = new URL((await hooks.auth.methods[0].authorize()).url) expect(u.origin + u.pathname).toBe("https://qoder.cn/device/selectAccounts") - // qoder.com gains no VPC method - expect((await QoderAuthPlugin({ client: store().client })).auth.methods.length).toBe(1) + // qoder.com gains no VPC method, but has the PAT method + expect((await QoderAuthPlugin({ client: store().client })).auth.methods.length).toBe(2) }) test("the VPC method asks for the instance and checks it", async () => {