qoder: add PAT (Personal Access Token) sign-in method (#103)

* qoder: add PAT (Personal Access Token) sign-in method

Add a new auth method that exchanges a PAT for a job token via
/api/v1/jobToken/exchange, bypassing the OAuth device flow. PATs are
long-lived (up to 1 year), avoiding the ~3-day re-authentication cycle
of OAuth refresh tokens.

Changes:
- Add patSignIn function for PAT → job token exchange
- Add "Sign in with Qoder PAT" method with password prompt
- Handle PAT accounts in usage (no device token available)
- Add pat.test.mjs with 10 tests covering both sites
- Update vpc.test.mjs for new method count

* qoder: use text prompt type for PAT (magpie has no password type)

magpie's prompt system only supports "text" and "select" types.
Change the PAT prompt from "password" to "text" to match.

* qoder: use password prompt type for PAT input

Now that magpie supports "password" prompt type, use it for PAT input
so the token is masked when typed in both GUI and TUI.

* qoder: address PR review — PAT kept, fields read as Qoder's client does

1. Store the PAT on the credential; when the job refresh lapses
   (SignInGone from refreshJob), re-exchange the PAT instead of
   marking the account signed out. The PAT lasts a year, the refresh
   two days.

2. Read the exchange response as Qoder's client does:
   - token from token, device_token or access_token
   - refresh from refresh_token or refreshToken
   - expiry from expire_time or expires_at (date) first, then
     expires_in in seconds (not milliseconds)

3. Use the openapi() helper for the exchange (no custom User-Agent);
   400/401/403 say "refused the PAT" rather than passing through the
   raw body.

4. Try the usage endpoint with the job token for PAT accounts; fall
   back to the "PAT" plan label if it won't accept it.

5. Exclude the PAT method from 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.

* qoder: fix expires_in unit — milliseconds, not seconds

The real exchange response shows expires_in: 86400000 (24h in ms),
not 86400 (seconds). The expires_at date field takes precedence in
exchangeExpiry, so the fallback was not hit in practice, but correct
it for completeness.

* qoder: drive the renew test through the real refresh path, usage through fetchUsage

The renew test called the PAT sign-in directly, so it never met the
fallback it was named for. It now loads a stored expired credential
whose job refresh is refused, and checks the exchange is asked with the
stored PAT, the request goes on with the new token, and the saved
credential still carries the PAT — and fails when the fallback is
taken out. A second case keeps no PAT on the credential and expects
the sign-in gone to come out.

The PAT branch of usage built fetchUsage's request by hand and turned
every error into a plan of its own; it calls fetchUsage now, its
errors surfacing as the device path's do. A live PAT account answered
the usage endpoint 200 with a qoder envelope on the job token from the
exchange, said so in the comment there.

* qoder: a refused PAT re-exchange ends the sign-in

The renew fallback let a refused PAT through as a plain error, which
magpie read as a server fault and kept the account on. A PAT lapses
like a device sign-in does — expired, or revoked — so renew turns the
exchange's refusal into a lapsed sign-in: usage says "expired" and the
request answers 401, asking for a new PAT. Interactive sign-in keeps
the plain error.
This commit is contained in:
unship
2026-10-14 18:34:37 +08:00
committed by GitHub
parent e87ea310c3
commit a6f09a0e9a
4 changed files with 370 additions and 5 deletions
+118 -2
View File
@@ -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
+1 -1
View File
@@ -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",
+249
View File
@@ -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")
})
+2 -2
View File
@@ -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 () => {