all: each plugin fails with its built-in's status and marks the sign-in as it did, through X-Magpie-Sign-In (要保证插件跟内置的所有逻辑都要一模一样) — Factory's and MiMo's refused renewals are the built-ins' 502 marked expired, not 401s; Qoder's vendor 403 is the built-in's 401 kept, its model list's failure a 400, its job refresh refused marked expired; Zed's retried 401 is a 401 kept, not a 403; Kiro's unreachable refresh a 401 kept; Cursor's expired trial a 401 kept; a vendor 401 WorkBuddy, Grok, Devin, Command Code and ZCode passed on no longer marks the account, as their built-ins never did, and Grok and MiMo no longer retry what their built-ins sent once. Messages take the built-ins' words. New tests fail against the previous index.mjs.
This commit is contained in:
+37
-13
@@ -16,6 +16,7 @@
|
||||
// from magpie's internal/qoder, which ported it from CLIProxyAPI's qoder
|
||||
// support (https://github.com/ufec/CLIProxyAPI, MIT).
|
||||
import { createCipheriv, createHash, publicEncrypt, randomBytes, randomUUID, constants } from "node:crypto"
|
||||
import { STATUS_CODES } from "node:http"
|
||||
|
||||
const ID = "qoder"
|
||||
const CLIENT_ID = "732aef47-9cf2-46a2-95fe-4cebb5d0d1fa"
|
||||
@@ -213,14 +214,24 @@ async function deviceSignIn() {
|
||||
}
|
||||
}
|
||||
|
||||
class SignInGone extends Error {}
|
||||
// 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,
|
||||
// answered 401 there without marking one.
|
||||
class SignInGone extends Error {
|
||||
constructor(message, expired = false) {
|
||||
super(message)
|
||||
this.expired = expired
|
||||
}
|
||||
}
|
||||
|
||||
// refreshJob trades the job token's refresh token for a new pair; the old
|
||||
// one is spent.
|
||||
async function refreshJob(refresh) {
|
||||
async function refreshJob(refresh, user) {
|
||||
if (!String(refresh ?? "").trim()) throw new SignInGone("Qoder: the sign-in lapsed; sign in again")
|
||||
const r = await openapi("/api/v1/jobToken/refresh", { method: "POST", body: { refresh_token: refresh } })
|
||||
if (r.status === 401 || r.status === 403) throw new SignInGone("Qoder: the sign-in has expired — sign in again")
|
||||
if (r.status === 401 || r.status === 403)
|
||||
throw new SignInGone(`${user}'s Qoder sign-in has expired — sign in again (qoder job token refresh: status ${r.status})`, true)
|
||||
if (r.status !== 200) throw new Error(`Qoder job token refresh: status ${r.status}`)
|
||||
if (!String(r.json?.token ?? "").trim() || !String(r.json?.refresh_token ?? "").trim())
|
||||
throw new Error("Qoder job token refresh: incomplete token pair")
|
||||
@@ -486,19 +497,26 @@ function failure(status, text) {
|
||||
try {
|
||||
const j = JSON.parse(text)
|
||||
if (j?.message) msg = j.message
|
||||
const d = typeof j?.details === "string" ? JSON.parse(j.details) : null
|
||||
// details is a JSON string, or the object itself (gjson reads either)
|
||||
const d = typeof j?.details === "string" ? JSON.parse(j.details) : j?.details
|
||||
if (d?.error?.message) msg += ": " + d.error.message
|
||||
} catch {}
|
||||
msg ||= `HTTP ${status}`
|
||||
// only Qoder's 401 says the job token itself is refused; a 403 is kept as
|
||||
// what it is, as magpie marks the account lapsed on a 401
|
||||
if (status === 401 || status === 403) return { status, message: "the sign-in lapsed — sign in again" }
|
||||
msg ||= STATUS_CODES[status] ?? `HTTP ${status}`
|
||||
// a refused chat is the built-in's 401, which never marked the account
|
||||
// lapsed: only a refused refresh did (errorResponse says kept)
|
||||
if (status === 401 || status === 403) return { status: 401, message: "the sign-in lapsed — sign in again" }
|
||||
if (status === 429 || msg.toLowerCase().includes("quota")) return { status: 429, message: "usage limit reached: " + msg }
|
||||
return { status, message: msg }
|
||||
}
|
||||
|
||||
const errorResponse = ({ status, message }) =>
|
||||
new Response(JSON.stringify({ error: { message, type: "qoder_error", code: status } }), { status, headers: { "Content-Type": "application/json" } })
|
||||
// errorResponse is a failure as OpenAI's API gives it. signIn is what it
|
||||
// means for the account (magpie's X-Magpie-Sign-In): a 401 keeps it unless
|
||||
// told expired, since the built-in marked only a refused refresh.
|
||||
const errorResponse = ({ status, message, signIn = status === 401 ? "kept" : undefined }) =>
|
||||
new Response(JSON.stringify({ error: { message, type: "qoder_error", code: status } }), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json", ...(signIn ? { "X-Magpie-Sign-In": signIn } : {}) },
|
||||
})
|
||||
|
||||
// ---- the reply ----------------------------------------------------------------
|
||||
|
||||
@@ -870,7 +888,7 @@ export async function QoderAuthPlugin({ client }) {
|
||||
const a = await getAuth()
|
||||
if (a?.type !== "oauth" || !a.access || !a.uid) throw new SignInGone("Qoder: not signed in")
|
||||
if (a.expires - Date.now() > REFRESH_LEAD) return a
|
||||
const jt = await refreshJob(a.refresh)
|
||||
const jt = await refreshJob(a.refresh, a.accountId || a.email || a.uid)
|
||||
const next = { ...a, access: jt.token, refresh: jt.refresh_token, expires: expiresAt(jt) }
|
||||
await client.auth.set({ path: { id: ID }, body: next })
|
||||
return next
|
||||
@@ -914,7 +932,11 @@ export async function QoderAuthPlugin({ client }) {
|
||||
}
|
||||
|
||||
const signedInError = (e) =>
|
||||
errorResponse({ status: e instanceof SignInGone ? 401 : 502, message: String(e?.message ?? e).replace(/^Qoder: /, "") })
|
||||
errorResponse({
|
||||
status: e instanceof SignInGone ? 401 : 502,
|
||||
message: String(e?.message ?? e).replace(/^Qoder: /, ""),
|
||||
signIn: e?.expired ? "expired" : undefined,
|
||||
})
|
||||
|
||||
return {
|
||||
auth: {
|
||||
@@ -946,7 +968,9 @@ export async function QoderAuthPlugin({ client }) {
|
||||
try {
|
||||
m = (await models(cred)).find((x) => x.key === chat.model) ?? (await models(cred, true)).find((x) => x.key === chat.model)
|
||||
} catch (e) {
|
||||
return errorResponse({ status: 502, message: e.message })
|
||||
// the built-in answered any failure to read the list 400
|
||||
// (QoderModelOf), a refused one included, marking nothing
|
||||
return errorResponse({ status: 400, message: e.message })
|
||||
}
|
||||
if (!m) return errorResponse({ status: 400, message: `unknown or disabled model "${chat.model}"` })
|
||||
const wire = encodeBody(JSON.stringify(qoderBody(chat, m)))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-qoder-auth",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.3",
|
||||
"description": "Qoder subscription in OpenCode and magpie",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
@@ -145,13 +145,69 @@ const LISTING = {
|
||||
],
|
||||
}
|
||||
|
||||
test("a refused chat is a 401 only when Qoder says 401; a 403 stays a 403", async () => {
|
||||
const ASK = { method: "POST", body: JSON.stringify({ model: "qmodel", messages: [{ role: "user", content: "hi" }] }) }
|
||||
|
||||
test("a refused chat, 401 or 403, is the built-in's 401 and leaves the account unmarked", async () => {
|
||||
for (const status of [401, 403]) {
|
||||
const { fetch } = await chat(LISTING, () => new Response("nope", { status }))
|
||||
const res = await fetch(API_CHAT, { method: "POST", body: JSON.stringify({ model: "qmodel", messages: [{ role: "user", content: "hi" }] }) })
|
||||
expect(res.status).toBe(status)
|
||||
const res = await fetch(API_CHAT, ASK)
|
||||
expect(res.status).toBe(401)
|
||||
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
|
||||
expect((await res.json()).error.message).toBe("the sign-in lapsed — sign in again")
|
||||
}
|
||||
// refused in the stream, before any answer: the same
|
||||
const sse = (v) => new Response(`data: ${JSON.stringify(v)}\n\n`, { headers: { "Content-Type": "text/event-stream" } })
|
||||
const { fetch } = await chat(LISTING, () => sse({ statusCodeValue: 403, body: "" }))
|
||||
const res = await fetch(API_CHAT, ASK)
|
||||
expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([401, "kept"])
|
||||
})
|
||||
|
||||
test("other refusals keep their status and say nothing of the sign-in", async () => {
|
||||
for (const [status, want] of [[500, 500], [429, 429], [402, 402]]) {
|
||||
const { fetch } = await chat(LISTING, () => new Response("", { status }))
|
||||
const res = await fetch(API_CHAT, ASK)
|
||||
expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([want, null])
|
||||
}
|
||||
// an empty body is named as Go's http.StatusText names it; details may be an object
|
||||
expect(_internal.failure(502, "")).toEqual({ status: 502, message: "Bad Gateway" })
|
||||
expect(_internal.failure(400, JSON.stringify({ message: "bad", details: { error: { message: "effort" } } }))).toEqual({ status: 400, message: "bad: effort" })
|
||||
})
|
||||
|
||||
test("a model list Qoder won't give is a 400, as the built-in's QoderModelOf answered, the account unmarked", async () => {
|
||||
for (const status of [401, 403, 500]) {
|
||||
const auth = { ...account(), machineId: "m1" }
|
||||
globalThis.fetch = async () => new Response("no", { status })
|
||||
const hooks = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } })
|
||||
const l = await hooks.auth.loader(async () => auth)
|
||||
const res = await l.fetch(API_CHAT, ASK)
|
||||
expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([400, null])
|
||||
expect((await res.json()).error.message).toBe(`Qoder models: HTTP ${status}: no`)
|
||||
}
|
||||
})
|
||||
|
||||
// the loader's fetch for an account whose job token is due, the refresh answered by refresh()
|
||||
async function due(refresh, fields = {}) {
|
||||
const auth = { ...account(), machineId: "m1", expires: 0, ...fields }
|
||||
globalThis.fetch = async (url) => (new URL(String(url)).pathname === "/api/v1/jobToken/refresh" ? refresh() : new Response("", { status: 500 }))
|
||||
const hooks = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } })
|
||||
const l = await hooks.auth.loader(async () => auth)
|
||||
return l.fetch(API_CHAT, ASK)
|
||||
}
|
||||
|
||||
test("a refresh Qoder refuses (401 or 403) marks the account lapsed, as qoderRefreshFailed did", async () => {
|
||||
for (const status of [401, 403]) {
|
||||
const res = await due(() => new Response("", { status }))
|
||||
expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([401, "expired"])
|
||||
expect((await res.json()).error.message).toBe(`one@x's Qoder sign-in has expired — sign in again (qoder job token refresh: status ${status})`)
|
||||
}
|
||||
})
|
||||
|
||||
test("no refresh token is a 401 the built-in didn't mark; a refresh that failed otherwise is a 502", async () => {
|
||||
let res = await due(() => new Response("", { status: 401 }), { refresh: "" })
|
||||
expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([401, "kept"])
|
||||
res = await due(() => new Response("", { status: 500 }))
|
||||
expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([502, null])
|
||||
expect((await res.json()).error.message).toBe("Qoder job token refresh: status 500")
|
||||
})
|
||||
|
||||
test("errors don't name Qoder, which magpie adds", async () => {
|
||||
@@ -164,7 +220,7 @@ test("errors don't name Qoder, which magpie adds", async () => {
|
||||
const gone = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } })
|
||||
const l = await gone.auth.loader(async () => ({ type: "oauth" }))
|
||||
res = await l.fetch(API_CHAT, { method: "POST", body: JSON.stringify({ model: "qmodel", messages: [] }) })
|
||||
expect(res.status).toBe(401)
|
||||
expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([401, "kept"])
|
||||
expect((await res.json()).error.message).toBe("not signed in")
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user