Files
plugins/packages/qoder/pat.test.mjs
T
unship a6f09a0e9a 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.
2026-10-14 18:34:37 +08:00

250 lines
10 KiB
JavaScript

// 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")
})