qoder 0.2.21: Qoder CN PAT sign-in, and a PAT account checks in on its job token (#262, sphuang1030-prog)

Qoder CN offers the PAT sign-in too (its /api/v1/jobToken/exchange takes a
personal_token as qoder.com's does; the prompt names qoder.cn's console),
and a PAT account, which has no device token, signs the campaigns pages and
the daily check-in with its job token instead of rotating a device token it
doesn't have. The account keeps the name its browser sign-in takes
(email || uid), so a renewed PAT sign-in replaces its lapsed row.

Run at d7db9f2b987c46cbf100cda9d89a8a546e374fb6:
- bun test packages/qoder: 155 pass, 0 fail; bun scripts/check.mjs passes.
- The PR's check-in tests go through the loader's campaigns fetch, not
  auth.checkin. Two local tests calling auth.checkin with a PAT account
  (qoder and qoder-cn: claimed on the job token, no deviceToken refresh;
  a 403 is "failed", not rotated) pass on this head and both fail with the
  checkin hook's change reverted by hand. They follow on main.
- Probe: POST openapi.qoder.com.cn/api/v1/jobToken/exchange with an
  invalid pt- token answers 400 BadRequest, as openapi.qoder.sh does (an
  unknown path answers 401), so the endpoint exists on CN and a bad PAT
  maps to "refused the PAT". qoder.cn/account/integrations redirects to
  sign-in, as qoder.com's does.
- Not tried: a live qoder.cn PAT exchange, chat or claim; that rests on
  the author's live run.
This commit is contained in:
hspnick
2026-10-20 16:15:12 +08:00
committed by GitHub
parent c7186858da
commit 0a8e5abd00
5 changed files with 198 additions and 41 deletions
+25
View File
@@ -22,6 +22,31 @@ hosts; [its section](#qoder-cn) says what differs.
3. The device token is traded for a job token, and the account's email and
name are read.
**Sign in with Qoder PAT** (and **Sign in with Qoder CN PAT**) skips the
device flow: a Personal Access Token from `<site>/account/integrations` is
posted to `/api/v1/jobToken/exchange` (`personal_token`), which answers a
job token, its refresh token and its expiry. The PAT is kept on the
credential, so a lapsed job refresh is exchanged again instead of asking
for the sign-in; PATs last up to a year. The job token signs the model list
and chat calls with the same COSY envelope either sign-in's does.
On Qoder CN this is the plugin's own reading of the protocol rather than
the CLI's path: qoder.cn's CLI signs requests with its device token and
never asks for a job token. Verified against a live qoder.cn account — the
exchange answers 200 with a `jt-` token, the signed model list answers 200
with that account's own models, and a chat completion returns its text.
A PAT account keeps the name its browser sign-in takes (`email || uid`): magpie
replaces an account on a new sign-in when both the accountId and the uid
match, so a renewed PAT sign-in names the same account rather than adding a
row beside the lapsed one.
A PAT account has no device token, so its usage read, campaigns pages and
daily check-in go out on the job token instead. The check-in works on it: a
live PAT account answered 200 to the campaigns list and `CLAIMED` to a claim,
so it earns the daily credits the browser sign-in does. That path has no
second token to rotate, so a refused call is the answer rather than a retry.
What is kept: the job token, its refresh token and expiry, the uid, the
device token and a machine id made for this sign-in. OpenCode keeps them in
`auth.json`; magpie keeps them in `plugin-auth.json`.
+43 -2
View File
@@ -58,8 +58,8 @@ const account = () => ({
const json = (v, status = 200) => new Response(JSON.stringify(v), { status })
async function loader(make, serve) {
let auth = account()
async function loader(make, serve, over = {}) {
let auth = { ...account(), ...over }
const seen = []
globalThis.fetch = async (url, init = {}) => {
const u = new URL(String(url))
@@ -233,6 +233,47 @@ test("CN still queries and claims without a native identity runtime", async () =
expect(reads).toHaveLength(0)
})
test("a PAT account checks in on its job token, having no device token", async () => {
// a PAT sign-in keeps no device token; the campaigns pages take the job
// token the exchange gave, as the usage endpoint does. A live Qoder CN PAT
// account answered 200 to the list and CLAIMED to a claim.
const p = await loader(
QoderCNAuthPlugin,
(u, init) => {
if (u.pathname === "/sash/api/v1/me/campaigns") return json(LIST)
if (u.pathname === "/sash/api/v1/me/campaigns/c1/claim") return json({ status: "CLAIMED" })
return new Response("", { status: 404 })
},
{ patAuth: true, pat: "pt-cn", deviceToken: "", deviceRefresh: "" },
)
const origin = "https://openapi.qoder.com.cn"
const list = await p.fetch(origin + "/sash/api/v1/me/campaigns", { method: "GET" })
expect(list.status).toBe(200)
expect(await list.json()).toEqual(LIST)
const claim = await p.fetch(origin + "/sash/api/v1/me/campaigns/c1/claim", { method: "POST", body: "{}" })
expect(claim.status).toBe(200)
expect((await claim.json()).status).toBe("CLAIMED")
// the job token signs both calls, and no device-token refresh is asked for
expect(p.seen).toEqual([
{ origin, path: "/sash/api/v1/me/campaigns", method: "GET", auth: "Bearer jt-one", body: undefined },
{ origin, path: "/sash/api/v1/me/campaigns/c1/claim", method: "POST", auth: "Bearer jt-one", body: "{}" },
])
expect(p.seen.some((s) => s.path.includes("deviceToken"))).toBe(false)
})
test("a PAT account's refused check-in is the answer, with no second token to rotate", async () => {
const p = await loader(
QoderCNAuthPlugin,
() => new Response("", { status: 401 }),
{ patAuth: true, pat: "pt-cn", deviceToken: "", deviceRefresh: "" },
)
const res = await p.fetch("https://openapi.qoder.com.cn/sash/api/v1/me/campaigns", { method: "GET" })
expect(res.status).toBe(401)
// nothing is rotated: the refresh call would fail with no device refresh
expect(p.seen.map((s) => s.path)).toEqual(["/sash/api/v1/me/campaigns"])
expect(p.auth().deviceToken).toBe("")
})
for (const [make, origin] of [
[QoderAuthPlugin, "https://openapi.qoder.sh"],
[QoderCNAuthPlugin, "https://openapi.qoder.com.cn"],
+48 -34
View File
@@ -357,6 +357,10 @@ async function patSignIn(site, pat) {
return {
type: "success",
...chat,
// The same name its browser sign-in takes: magpie's plugin host replaces
// an account on a new sign-in when both the accountId and the uid match,
// so a renewed PAT sign-in must keep naming the same account. A suffix
// here would add a second row beside the lapsed one instead.
accountId: email || uid,
uid,
email,
@@ -1636,8 +1640,14 @@ const makePlugin = (site) => async ({ client }) => {
const method = String(init.method ?? input?.method ?? "GET").toUpperCase()
try {
const machine = site.id === "qoder" ? await machineForCampaign(cred.uid) : {}
let res = await campaignCall(url, method, body, cred.deviceToken, machine, init.signal)
if (res.status === 401 || res.status === 403) res = await campaignCall(url, method, body, await deviceToken(getAuth, cred.deviceToken), machine, init.signal)
// A PAT account has no device token: its job token signs the campaigns
// pages too, as it does the usage read. Nothing is rotated on that
// path — the refusal is the answer.
const patToken = cred.patAuth && !cred.deviceToken
const token = patToken ? cred.access : cred.deviceToken
let res = await campaignCall(url, method, body, token, machine, init.signal)
if (!patToken && (res.status === 401 || res.status === 403))
res = await campaignCall(url, method, body, await deviceToken(getAuth, cred.deviceToken), machine, init.signal)
return signed(res, renewed(cred))
} catch (e) {
if (e?.expired) return signedInError(e)
@@ -1659,8 +1669,15 @@ const makePlugin = (site) => async ({ client }) => {
if (!base) return { outcome: "inactive", message: "no campaigns page for this account" }
try {
const machine = site.id === "qoder" ? await machineForCampaign(cred.uid) : {}
// A PAT account has no device token: the campaigns pages take the job
// token the exchange gave, as the usage endpoint does. A live Qoder CN
// PAT account answered 200 to the list and CLAIMED to a claim, so the
// check-in works there as it does on a device-token account. That path
// has no second token to rotate, so a refusal is the answer.
const patToken = cred.patAuth && !cred.deviceToken ? cred.access : ""
const call = async (url, method, body) => {
let res = await campaignCall(url, method, body, cred.deviceToken, machine)
let res = await campaignCall(url, method, body, patToken || cred.deviceToken, machine)
if (patToken) return res
if (res.status === 401 || res.status === 403) {
const token = await deviceToken(getAuth, cred.deviceToken)
const current = latest(await getAuth())
@@ -1809,38 +1826,35 @@ const makePlugin = (site) => async ({ client }) => {
{ 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)
},
}
},
// Offered on both sites: Qoder CN's /api/v1/jobToken/exchange takes
// a PAT too (verified: HTTP 200 and a jt- token), and that job token
// signs the model list and chat calls with the COSY envelope as on
// qoder.com, so the exchange gives a token the chat endpoint accepts.
{
type: "oauth",
label: `Sign in with ${site.name} PAT`,
prompts: [
{
type: "password",
key: "pat",
message: `Your ${site.name} Personal Access Token (from ${site.web}/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.20",
"version": "0.2.21",
"description": "Qoder subscriptions in OpenCode and magpie: Qoder (qoder.com) and Qoder CN (qoder.cn)",
"type": "module",
"main": "./index.mjs",
+81 -4
View File
@@ -1,6 +1,7 @@
// 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).
// the OAuth device flow. Offered on both sites: Qoder CN's exchange takes a
// PAT too, and the job token it returns signs the model list and chat calls
// with the COSY envelope as it does on qoder.com.
import { afterEach, expect, test } from "bun:test"
import { QoderAuthPlugin, QoderCNAuthPlugin } from "./index.mjs"
@@ -26,11 +27,87 @@ test("qoder: PAT auth method is listed", async () => {
expect(patMethod.prompts[0].type).toBe("password")
})
test("qoder-cn: PAT auth method is NOT listed", async () => {
test("qoder-cn: PAT auth method is 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()
expect(patMethod).toBeDefined()
expect(patMethod.type).toBe("oauth")
expect(patMethod.label).toBe("Sign in with Qoder CN PAT")
expect(patMethod.prompts).toHaveLength(1)
expect(patMethod.prompts[0].key).toBe("pat")
expect(patMethod.prompts[0].type).toBe("password")
// the prompt names the CN console, not qoder.com's
expect(patMethod.prompts[0].message).toContain("https://qoder.cn/account/integrations")
})
test("qoder-cn: PAT sign-in exchanges at the CN openapi host", 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.com.cn" && u.pathname === "/api/v1/jobToken/exchange") {
const body = JSON.parse(init.body)
expect(body.personal_token).toBe("pt-cn123")
return json({ token: "jt-cn", refresh_token: "jrt-cn", expires_in: 86400000 })
}
if (u.host === "openapi.qoder.com.cn" && u.pathname === "/api/v1/userinfo") {
return json({ id: "cn-user-1", name: "CN User" })
}
return new Response("", { status: 500 })
}
const client = { auth: { set: async () => {} } }
const hooks = await QoderCNAuthPlugin({ client })
const patMethod = hooks.auth.methods.find((m) => m.label?.includes("PAT"))
const flow = patMethod.authorize({ pat: "pt-cn123" })
expect(flow.url).toBe("https://qoder.cn/account/integrations")
const res = await flow.callback()
expect(res.type).toBe("success")
expect(res.access).toBe("jt-cn")
expect(res.uid).toBe("cn-user-1")
expect(res.patAuth).toBe(true)
expect(res.pat).toBe("pt-cn123")
// a PAT account keeps no device token: it is not a device-chat account
expect(res.deviceToken).toBe("")
expect(res.deviceChat).toBeUndefined()
expect(calls).toContain("openapi.qoder.com.cn/api/v1/jobToken/exchange")
expect(calls).toContain("openapi.qoder.com.cn/api/v1/userinfo")
// nothing is asked of the global host
expect(calls.some((c) => c.startsWith("openapi.qoder.sh"))).toBe(false)
})
test("qoder-cn: a PAT account keeps the name its browser sign-in takes", async () => {
globalThis.fetch = async (url) => {
const u = new URL(String(url))
if (u.pathname === "/api/v1/jobToken/exchange") return json({ token: "jt-1", refresh_token: "jrt-1", expires_in: 86400000 })
if (u.pathname === "/api/v1/userinfo") return json({ id: "same-user", name: "Someone" })
return new Response("", { status: 500 })
}
const client = { auth: { set: async () => {} } }
const hooks = await QoderCNAuthPlugin({ client })
const patMethod = hooks.auth.methods.find((m) => m.label?.includes("PAT"))
const res = await patMethod.authorize({ pat: "pt-x" }).callback()
// no suffix: magpie's host replaces an account on a new sign-in when both
// the accountId and the uid match, so a re-signed PAT must name the same
// account the browser sign-in does, not a row of its own beside it
expect(res.accountId).toBe("same-user")
expect(res.uid).toBe("same-user")
expect(res.email).toBe("")
})
test("qoder: a PAT account is named by its email, as the browser sign-in is", async () => {
globalThis.fetch = async (url) => {
const u = new URL(String(url))
if (u.pathname === "/api/v1/jobToken/exchange") return json({ token: "jt-g", refresh_token: "jrt-g", expires_in: 86400000 })
if (u.pathname === "/api/v1/userinfo") return json({ id: "g-1", email: "g@example.com", name: "G" })
return new Response("", { status: 500 })
}
const { hooks } = await plugin(null)
const patMethod = hooks.auth.methods.find((m) => m.label?.includes("PAT"))
const res = await patMethod.authorize({ pat: "pt-g" }).callback()
expect(res.accountId).toBe("g@example.com")
})
test("qoder: PAT auth method validates PAT format", async () => {