@magpie-community/opencode-qoder-auth 0.1.3 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -1
- package/index.mjs +161 -67
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
# @magpie-community/opencode-qoder-auth
|
|
2
2
|
|
|
3
3
|
Your [Qoder](https://qoder.com) subscription in OpenCode and
|
|
4
|
-
[magpie](https://usemagpie.ai)
|
|
4
|
+
[magpie](https://usemagpie.ai). The package serves Qoder's two sites, whose
|
|
5
|
+
accounts exist only on their own:
|
|
6
|
+
|
|
7
|
+
| Provider id | Site | Accounts | Plugin export |
|
|
8
|
+
|---|---|---|---|
|
|
9
|
+
| `qoder` | qoder.com (international) | Google, GitHub or email | `QoderAuthPlugin` |
|
|
10
|
+
| `qoder-cn` | qoder.cn ([Qoder CN](#qoder-cn)) | Alibaba Cloud or phone number | `QoderCNAuthPlugin` |
|
|
11
|
+
|
|
12
|
+
What follows is about `qoder`. Qoder CN works the same way on its own
|
|
13
|
+
hosts; [its section](#qoder-cn) says what differs.
|
|
5
14
|
|
|
6
15
|
## Sign-in
|
|
7
16
|
|
|
@@ -83,6 +92,46 @@ The `config` hook declares the list as it was on 2026-09-30:
|
|
|
83
92
|
|
|
84
93
|
Every model speaks chat completions (`@ai-sdk/openai-compatible`).
|
|
85
94
|
|
|
95
|
+
## Qoder CN
|
|
96
|
+
|
|
97
|
+
`qoder-cn` is for accounts on [qoder.cn](https://qoder.cn), the China site.
|
|
98
|
+
Those accounts sign in with Alibaba Cloud or a phone number and can't sign
|
|
99
|
+
in through `qoder`. Qoder CN speaks the same protocol as qoder.com:
|
|
100
|
+
|
|
101
|
+
- the same device flow, poll, job token and refresh paths;
|
|
102
|
+
- the same COSY envelope and body codec;
|
|
103
|
+
- the same model list, chat and usage paths.
|
|
104
|
+
|
|
105
|
+
Only the hosts and the sign-in's client id differ. The plugin uses the ones
|
|
106
|
+
Qoder CN's own CLI builds in for its `cn` build (`@qodercn-ai/qoderclicn`
|
|
107
|
+
1.1.65):
|
|
108
|
+
|
|
109
|
+
| | `qoder` | `qoder-cn` |
|
|
110
|
+
|---|---|---|
|
|
111
|
+
| Sign-in page | qoder.com | qoder.cn |
|
|
112
|
+
| Accounts: poll, tokens, user info, usage | openapi.qoder.sh | openapi.qoder.com.cn |
|
|
113
|
+
| Models and chat | api3.qoder.sh | gateway.qoder.com.cn |
|
|
114
|
+
| Device-flow client id | Qoder's desktop client's | Qoder CN's CLI's (production) |
|
|
115
|
+
| `redirect_uri` on the sign-in page | `qoder-app://` | none, as the CLI sends |
|
|
116
|
+
|
|
117
|
+
Qoder CN's CLI chats with the device token itself and never makes a job
|
|
118
|
+
token. The plugin asks qoder.cn for a job token first, as it does on
|
|
119
|
+
qoder.com. If qoder.cn refuses it (a 4xx), the account works the way the
|
|
120
|
+
CLI does:
|
|
121
|
+
|
|
122
|
+
- the device token signs the model calls;
|
|
123
|
+
- it is renewed with `/api/v1/deviceToken/refresh`, the chat and account
|
|
124
|
+
tokens being one pair;
|
|
125
|
+
- a refused renewal (401 or 403) means signing in again.
|
|
126
|
+
|
|
127
|
+
Until you sign in, the `config` hook declares the tiers Qoder CN's CLI names
|
|
128
|
+
(Ultimate, Performance, Efficient, Lite). Once you are signed in, the
|
|
129
|
+
account's own list from gateway.qoder.com.cn replaces them.
|
|
130
|
+
|
|
131
|
+
Neither magpie's built-in Qoder CN nor this plugin has been checked against
|
|
132
|
+
every kind of qoder.cn account. If a sign-in or a chat fails, please open
|
|
133
|
+
an issue with the error.
|
|
134
|
+
|
|
86
135
|
## Not here
|
|
87
136
|
|
|
88
137
|
- Qoder's usage and quota display.
|
package/index.mjs
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
// Qoder's
|
|
1
|
+
// Qoder's subscriptions as OpenCode provider plugins, one for each of its
|
|
2
|
+
// sites, whose accounts exist only on their own:
|
|
3
|
+
// - qoder: the international site, qoder.com
|
|
4
|
+
// - qoder-cn: Qoder CN, qoder.cn (Alibaba Cloud or phone sign-in)
|
|
2
5
|
//
|
|
3
6
|
// Qoder is signed in to the way its desktop client is: a PKCE device flow
|
|
4
7
|
// (qoder.com's page, then a poll of openapi.qoder.sh for the device token),
|
|
@@ -15,17 +18,18 @@
|
|
|
15
18
|
// The protocol (endpoints, COSY envelope, body codec, device flow) is ported
|
|
16
19
|
// from magpie's internal/qoder, which ported it from CLIProxyAPI's qoder
|
|
17
20
|
// support (https://github.com/ufec/CLIProxyAPI, MIT).
|
|
21
|
+
//
|
|
22
|
+
// Qoder CN speaks the same protocol on its own hosts, as Qoder CN's CLI
|
|
23
|
+
// (@qodercn-ai/qoderclicn 1.1.65) builds them in for its "cn" build: the
|
|
24
|
+
// sign-in page on qoder.cn, accounts on openapi.qoder.com.cn and models on
|
|
25
|
+
// gateway.qoder.com.cn, with the device-flow client id that CLI sends in
|
|
26
|
+
// production and no redirect_uri. That CLI chats on the device token itself;
|
|
27
|
+
// if qoder.cn won't trade it for a job token, the account does the same.
|
|
18
28
|
import { createCipheriv, createHash, publicEncrypt, randomBytes, randomUUID, constants } from "node:crypto"
|
|
19
29
|
import { STATUS_CODES } from "node:http"
|
|
20
30
|
|
|
21
|
-
const
|
|
22
|
-
const
|
|
23
|
-
const DEVICE_HOST = "https://qoder.com"
|
|
24
|
-
const OPENAPI = "https://openapi.qoder.sh"
|
|
25
|
-
const API = "https://api3.qoder.sh"
|
|
26
|
-
const REDIRECT = "qoder-app://"
|
|
27
|
-
const CHAT_URL = API + "/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1"
|
|
28
|
-
const MODELS_URL = API + "/algo/api/v2/model/list?Encode=1"
|
|
31
|
+
const CHAT_PATH = "/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1"
|
|
32
|
+
const MODELS_PATH = "/algo/api/v2/model/list?Encode=1"
|
|
29
33
|
const COSY_VERSION = "1.1.49"
|
|
30
34
|
const SIGN_IN_TIMEOUT = 15 * 60 * 1000
|
|
31
35
|
const REFRESH_LEAD = 5 * 60 * 1000
|
|
@@ -145,8 +149,8 @@ function decodeBody(wire) {
|
|
|
145
149
|
|
|
146
150
|
const b64url = (buf) => buf.toString("base64url")
|
|
147
151
|
|
|
148
|
-
async function openapi(path, { method = "GET", token, body, query } = {}) {
|
|
149
|
-
const url = new URL(
|
|
152
|
+
async function openapi(site, path, { method = "GET", token, body, query } = {}) {
|
|
153
|
+
const url = new URL(site.openapi + path)
|
|
150
154
|
for (const [k, v] of Object.entries(query ?? {})) url.searchParams.set(k, v)
|
|
151
155
|
const headers = { Accept: "application/json" }
|
|
152
156
|
if (body) headers["Content-Type"] = "application/json"
|
|
@@ -164,23 +168,34 @@ async function openapi(path, { method = "GET", token, body, query } = {}) {
|
|
|
164
168
|
// runs out; a day when it said none.
|
|
165
169
|
const expiresAt = (jt) => Date.now() + (jt.expires_in > 0 ? jt.expires_in : DAY)
|
|
166
170
|
|
|
167
|
-
|
|
171
|
+
// deviceExpiry is when a device token used for chat runs out: its
|
|
172
|
+
// expires_at (a date) or expires_in (seconds), as Qoder's CLI reads it; a
|
|
173
|
+
// day when it said neither.
|
|
174
|
+
function deviceExpiry(dt) {
|
|
175
|
+
const at = Date.parse(String(dt?.expires_at ?? "").trim())
|
|
176
|
+
if (!isNaN(at)) return at
|
|
177
|
+
if (dt?.expires_in > 0) return Date.now() + dt.expires_in * 1000
|
|
178
|
+
return Date.now() + DAY
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function deviceSignIn(site) {
|
|
168
182
|
const verifier = b64url(randomBytes(64))
|
|
169
183
|
const challenge = b64url(createHash("sha256").update(verifier).digest())
|
|
170
184
|
const nonce = randomUUID()
|
|
171
185
|
const machineId = randomUUID()
|
|
172
|
-
const q = new URLSearchParams({ challenge, challenge_method: "S256", nonce, machine_id: machineId, client_id:
|
|
186
|
+
const q = new URLSearchParams({ challenge, challenge_method: "S256", nonce, machine_id: machineId, client_id: site.clientId })
|
|
187
|
+
if (site.redirect) q.set("redirect_uri", site.redirect)
|
|
173
188
|
const until = Date.now() + SIGN_IN_TIMEOUT
|
|
174
189
|
return {
|
|
175
|
-
url: `${
|
|
176
|
-
instructions:
|
|
190
|
+
url: `${site.web}/device/selectAccounts?${q}`,
|
|
191
|
+
instructions: `Sign in to ${site.name} in the browser and authorize this device`,
|
|
177
192
|
method: "auto",
|
|
178
193
|
async callback() {
|
|
179
194
|
let dt
|
|
180
195
|
for (;;) {
|
|
181
|
-
if (Date.now() > until) throw new Error(
|
|
196
|
+
if (Date.now() > until) throw new Error(`${site.name}: the sign-in timed out; start again`)
|
|
182
197
|
try {
|
|
183
|
-
const r = await openapi("/api/v1/deviceToken/poll", { query: { nonce, verifier, challenge_method: "S256" } })
|
|
198
|
+
const r = await openapi(site, "/api/v1/deviceToken/poll", { query: { nonce, verifier, challenge_method: "S256" } })
|
|
184
199
|
if (r.status === 200 && String(r.json?.token ?? "").trim()) {
|
|
185
200
|
dt = r.json
|
|
186
201
|
break
|
|
@@ -188,24 +203,29 @@ async function deviceSignIn() {
|
|
|
188
203
|
} catch {} // a hiccup: ask again
|
|
189
204
|
await new Promise((r) => setTimeout(r, 2000))
|
|
190
205
|
}
|
|
191
|
-
const jr = await openapi("/api/v1/me/jobToken", { method: "POST", token: dt.token, body: { clientId:
|
|
192
|
-
|
|
193
|
-
if (
|
|
206
|
+
const jr = await openapi(site, "/api/v1/me/jobToken", { method: "POST", token: dt.token, body: { clientId: site.clientId } })
|
|
207
|
+
let chat
|
|
208
|
+
if (jr.status === 200) {
|
|
209
|
+
if (!String(jr.json?.token ?? "").trim()) throw new Error(`${site.name} job token: empty token in response`)
|
|
210
|
+
chat = { access: jr.json.token, refresh: jr.json.refresh_token ?? "", expires: expiresAt(jr.json) }
|
|
211
|
+
} else if (site.deviceChat && jr.status >= 400 && jr.status < 500) {
|
|
212
|
+
// Qoder CN's CLI never makes a job token: its device token is what
|
|
213
|
+
// signs the model calls, renewed as a device token
|
|
214
|
+
chat = { access: dt.token, refresh: dt.refresh_token ?? "", expires: deviceExpiry(dt), deviceChat: true }
|
|
215
|
+
} else throw new Error(`${site.name} job token: status ${jr.status}: ${jr.text.trim().slice(0, 300)}`)
|
|
194
216
|
let email = ""
|
|
195
217
|
let name = ""
|
|
196
218
|
try {
|
|
197
|
-
const ui = await openapi("/api/v1/userinfo", { token: dt.token })
|
|
219
|
+
const ui = await openapi(site, "/api/v1/userinfo", { token: dt.token })
|
|
198
220
|
if (ui.status >= 200 && ui.status < 300) [email, name] = [ui.json?.email ?? "", ui.json?.name ?? ""]
|
|
199
221
|
} catch {}
|
|
200
222
|
return {
|
|
201
223
|
type: "success",
|
|
202
|
-
|
|
203
|
-
refresh: jr.json.refresh_token ?? "",
|
|
204
|
-
expires: expiresAt(jr.json),
|
|
224
|
+
...chat,
|
|
205
225
|
accountId: email || dt.user_id,
|
|
206
226
|
uid: dt.user_id,
|
|
207
227
|
email,
|
|
208
|
-
name,
|
|
228
|
+
name: name || dt.user_name || "",
|
|
209
229
|
machineId,
|
|
210
230
|
deviceToken: dt.token,
|
|
211
231
|
deviceRefresh: dt.refresh_token ?? "",
|
|
@@ -227,14 +247,14 @@ class SignInGone extends Error {
|
|
|
227
247
|
|
|
228
248
|
// refreshJob trades the job token's refresh token for a new pair; the old
|
|
229
249
|
// one is spent.
|
|
230
|
-
async function refreshJob(refresh, user) {
|
|
231
|
-
if (!String(refresh ?? "").trim()) throw new SignInGone(
|
|
232
|
-
const r = await openapi("/api/v1/jobToken/refresh", { method: "POST", body: { refresh_token: refresh } })
|
|
250
|
+
async function refreshJob(site, refresh, user) {
|
|
251
|
+
if (!String(refresh ?? "").trim()) throw new SignInGone(`${site.name}: the sign-in lapsed; sign in again`)
|
|
252
|
+
const r = await openapi(site, "/api/v1/jobToken/refresh", { method: "POST", body: { refresh_token: refresh } })
|
|
233
253
|
if (r.status === 401 || r.status === 403)
|
|
234
|
-
throw new SignInGone(`${user}'s
|
|
235
|
-
if (r.status !== 200) throw new Error(`
|
|
254
|
+
throw new SignInGone(`${user}'s ${site.name} sign-in has expired — sign in again (qoder job token refresh: status ${r.status})`, true)
|
|
255
|
+
if (r.status !== 200) throw new Error(`qoder job token refresh: status ${r.status}`)
|
|
236
256
|
if (!String(r.json?.token ?? "").trim() || !String(r.json?.refresh_token ?? "").trim())
|
|
237
|
-
throw new Error("
|
|
257
|
+
throw new Error("qoder job token refresh: incomplete token pair")
|
|
238
258
|
return r.json
|
|
239
259
|
}
|
|
240
260
|
|
|
@@ -263,6 +283,14 @@ const MODELS = [
|
|
|
263
283
|
{ id: "mmodel", name: "MiniMax-M3", context: 180_000 },
|
|
264
284
|
].map((m) => ({ images: true, ...m }))
|
|
265
285
|
|
|
286
|
+
// Qoder CN's list when the account's can't be asked: the tiers Qoder CN's
|
|
287
|
+
// CLI names (auto routes inside Qoder and isn't one model). The account's
|
|
288
|
+
// own list, read once signed in, takes over from it.
|
|
289
|
+
const CN_MODELS = [
|
|
290
|
+
...MODELS.filter((m) => ["ultimate", "performance", "efficient"].includes(m.id)),
|
|
291
|
+
{ id: "lite", name: "Lite" },
|
|
292
|
+
]
|
|
293
|
+
|
|
266
294
|
// freeOf reads whether the listing marks a model free, as Qoder's client
|
|
267
295
|
// reads it (internal/qoder/models.go): is_free true, or a price_factor (the
|
|
268
296
|
// credits a request costs, as a multiple) of 0, either in snake or camel case.
|
|
@@ -313,10 +341,11 @@ function modelInfos(listing) {
|
|
|
313
341
|
.map(modelInfo)
|
|
314
342
|
}
|
|
315
343
|
|
|
316
|
-
async function fetchListing(cred) {
|
|
317
|
-
const
|
|
344
|
+
async function fetchListing(site, cred) {
|
|
345
|
+
const url = site.api + MODELS_PATH
|
|
346
|
+
const res = await fetch(url, { headers: cosyHeaders(url, cred, ""), signal: AbortSignal.timeout(15_000) })
|
|
318
347
|
const text = await res.text()
|
|
319
|
-
if (!res.ok) throw new Error(
|
|
348
|
+
if (!res.ok) throw new Error(`${site.name} models: HTTP ${res.status}: ${text.trim().slice(0, 512)}`)
|
|
320
349
|
return JSON.parse(text)
|
|
321
350
|
}
|
|
322
351
|
|
|
@@ -330,12 +359,12 @@ function configModel(m) {
|
|
|
330
359
|
}
|
|
331
360
|
}
|
|
332
361
|
|
|
333
|
-
function runtimeModel(m) {
|
|
362
|
+
function runtimeModel(site, m) {
|
|
334
363
|
return {
|
|
335
364
|
id: m.id,
|
|
336
|
-
providerID:
|
|
365
|
+
providerID: site.id,
|
|
337
366
|
name: m.name ?? m.id,
|
|
338
|
-
api: { id: m.id, url:
|
|
367
|
+
api: { id: m.id, url: site.api, npm: CHAT },
|
|
339
368
|
status: "active",
|
|
340
369
|
headers: {},
|
|
341
370
|
options: {},
|
|
@@ -785,11 +814,11 @@ class UsageStatus extends Error {
|
|
|
785
814
|
}
|
|
786
815
|
|
|
787
816
|
// fetchUsage is the usage envelope, {displayMode, qoderUsage}.
|
|
788
|
-
async function fetchUsage(deviceToken) {
|
|
817
|
+
async function fetchUsage(site, deviceToken) {
|
|
789
818
|
if (!String(deviceToken ?? "").trim()) throw new Error("qoder usage: missing device token")
|
|
790
819
|
let res
|
|
791
820
|
try {
|
|
792
|
-
res = await fetch(
|
|
821
|
+
res = await fetch(site.openapi + "/sash/api/v2/me/usage", {
|
|
793
822
|
headers: { Accept: "application/json", Authorization: `Bearer ${deviceToken}`, "Cosy-ClientType": "10", "User-Agent": "Qoder" },
|
|
794
823
|
signal: AbortSignal.timeout(20_000),
|
|
795
824
|
})
|
|
@@ -810,25 +839,31 @@ async function fetchUsage(deviceToken) {
|
|
|
810
839
|
|
|
811
840
|
// refreshDevice trades the device refresh token for a new pair; it rotates
|
|
812
841
|
// too, so the caller saves it.
|
|
813
|
-
async function refreshDevice(refresh) {
|
|
814
|
-
if (!String(refresh ?? "").trim())
|
|
842
|
+
async function refreshDevice(site, refresh, chat = false) {
|
|
843
|
+
if (!String(refresh ?? "").trim()) {
|
|
844
|
+
if (chat) throw new SignInGone(`${site.name}: the sign-in lapsed; sign in again`)
|
|
845
|
+
throw new Error("qoder device token refresh: missing refresh token; sign in again")
|
|
846
|
+
}
|
|
815
847
|
let r
|
|
816
848
|
try {
|
|
817
|
-
r = await openapi("/api/v1/deviceToken/refresh", { method: "POST", body: { refresh_token: refresh } })
|
|
849
|
+
r = await openapi(site, "/api/v1/deviceToken/refresh", { method: "POST", body: { refresh_token: refresh } })
|
|
818
850
|
} catch (e) {
|
|
819
851
|
throw new Error(`qoder device token refresh: request failed: ${e?.message ?? e}`)
|
|
820
852
|
}
|
|
821
853
|
if (r.status !== 200) {
|
|
822
854
|
const err = `qoder device token refresh: upstream HTTP ${r.status}`
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
855
|
+
if (r.status === 401 || r.status === 403) {
|
|
856
|
+
// a device token that is the chat token too: refused, the sign-in is gone
|
|
857
|
+
if (chat) throw new SignInGone(`${site.name} sign-in has expired — sign in again (${err})`, true)
|
|
858
|
+
// otherwise it serves only the account pages (usage); chat runs on
|
|
859
|
+
// the job token, so a refused one doesn't lapse the account
|
|
860
|
+
throw new Error(`${site.name} usage is unavailable: ${site.name} refused the account-page sign-in (chat still works) — sign in again to see usage (${err})`)
|
|
861
|
+
}
|
|
827
862
|
throw new Error(err)
|
|
828
863
|
}
|
|
829
864
|
const token = r.json?.token || r.json?.device_token || ""
|
|
830
865
|
if (!String(token).trim() || !String(r.json?.refresh_token ?? "").trim()) throw new Error("qoder device token refresh: incomplete token pair")
|
|
831
|
-
return { token, refresh: r.json.refresh_token }
|
|
866
|
+
return { token, refresh: r.json.refresh_token, expires: deviceExpiry(r.json) }
|
|
832
867
|
}
|
|
833
868
|
|
|
834
869
|
// gfmt is a number as Go's %g writes it.
|
|
@@ -880,7 +915,35 @@ function parseUsage(env) {
|
|
|
880
915
|
return out
|
|
881
916
|
}
|
|
882
917
|
|
|
883
|
-
|
|
918
|
+
// SITES are Qoder's two sites, each a subscription of its own.
|
|
919
|
+
const SITES = {
|
|
920
|
+
qoder: {
|
|
921
|
+
id: "qoder",
|
|
922
|
+
name: "Qoder",
|
|
923
|
+
clientId: "732aef47-9cf2-46a2-95fe-4cebb5d0d1fa",
|
|
924
|
+
web: "https://qoder.com",
|
|
925
|
+
openapi: "https://openapi.qoder.sh",
|
|
926
|
+
api: "https://api3.qoder.sh",
|
|
927
|
+
redirect: "qoder-app://",
|
|
928
|
+
models: MODELS,
|
|
929
|
+
},
|
|
930
|
+
"qoder-cn": {
|
|
931
|
+
id: "qoder-cn",
|
|
932
|
+
name: "Qoder CN",
|
|
933
|
+
// the production client id of Qoder CN's CLI (@qodercn-ai/qoderclicn)
|
|
934
|
+
clientId: "e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb",
|
|
935
|
+
web: "https://qoder.cn",
|
|
936
|
+
openapi: "https://openapi.qoder.com.cn",
|
|
937
|
+
api: "https://gateway.qoder.com.cn",
|
|
938
|
+
redirect: "", // Qoder CN's CLI sends none
|
|
939
|
+
deviceChat: true, // a refused job token falls back to the CLI's device-token chat
|
|
940
|
+
models: CN_MODELS,
|
|
941
|
+
},
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
const makePlugin = (site) => async ({ client }) => {
|
|
945
|
+
const ID = site.id
|
|
946
|
+
const CHAT_URL = site.api + CHAT_PATH
|
|
884
947
|
// serializes checking, rotating and saving tokens: a refresh token is
|
|
885
948
|
// spent once, so two refreshes would spend it twice
|
|
886
949
|
let lock = Promise.resolve()
|
|
@@ -894,16 +957,32 @@ export async function QoderAuthPlugin({ client }) {
|
|
|
894
957
|
// the accounts fresh renewed: the built-in took the lapse mark off on a
|
|
895
958
|
// renewed job token (qoderPersist), whatever the request then met
|
|
896
959
|
const renewals = new WeakSet()
|
|
960
|
+
// the accounts the models hook renewed: that hook has no way to say so
|
|
961
|
+
// and still answer the list, so the account's next usage read or answer
|
|
962
|
+
// says "renewed" for it
|
|
963
|
+
const unsaid = new Set()
|
|
964
|
+
const renewed = (cred) => {
|
|
965
|
+
const was = unsaid.delete(cred.uid)
|
|
966
|
+
return renewals.has(cred) || was
|
|
967
|
+
}
|
|
897
968
|
|
|
898
969
|
// fresh is the account with a live job token, refreshed and saved near
|
|
899
970
|
// its end.
|
|
900
971
|
const fresh = (getAuth) =>
|
|
901
972
|
locked(async () => {
|
|
902
973
|
const a = await getAuth()
|
|
903
|
-
if (a?.type !== "oauth" || !a.access || !a.uid) throw new SignInGone(
|
|
974
|
+
if (a?.type !== "oauth" || !a.access || !a.uid) throw new SignInGone(`${site.name}: not signed in`)
|
|
904
975
|
if (a.expires - Date.now() > REFRESH_LEAD) return a
|
|
905
|
-
|
|
906
|
-
|
|
976
|
+
let next
|
|
977
|
+
if (a.deviceChat) {
|
|
978
|
+
// the device token is the chat token: renewed as a device token,
|
|
979
|
+
// both pairs being the one pair
|
|
980
|
+
const dt = await refreshDevice(site, a.refresh, true)
|
|
981
|
+
next = { ...a, access: dt.token, refresh: dt.refresh, expires: dt.expires, deviceToken: dt.token, deviceRefresh: dt.refresh }
|
|
982
|
+
} else {
|
|
983
|
+
const jt = await refreshJob(site, a.refresh, a.accountId || a.email || a.uid)
|
|
984
|
+
next = { ...a, access: jt.token, refresh: jt.refresh_token, expires: expiresAt(jt) }
|
|
985
|
+
}
|
|
907
986
|
await client.auth.set({ path: { id: ID }, body: next })
|
|
908
987
|
renewals.add(next)
|
|
909
988
|
return next
|
|
@@ -912,7 +991,7 @@ export async function QoderAuthPlugin({ client }) {
|
|
|
912
991
|
const models = async (cred, again = false) => {
|
|
913
992
|
let l = listings.get(cred.uid)
|
|
914
993
|
if (!l || again) {
|
|
915
|
-
l = modelInfos(await fetchListing(cred))
|
|
994
|
+
l = modelInfos(await fetchListing(site, cred))
|
|
916
995
|
listings.set(cred.uid, l)
|
|
917
996
|
}
|
|
918
997
|
return l
|
|
@@ -924,8 +1003,11 @@ export async function QoderAuthPlugin({ client }) {
|
|
|
924
1003
|
locked(async () => {
|
|
925
1004
|
const a = await getAuth()
|
|
926
1005
|
if (a?.deviceToken !== attempted) return a?.deviceToken
|
|
927
|
-
const dt = await refreshDevice(a.deviceRefresh)
|
|
928
|
-
|
|
1006
|
+
const dt = await refreshDevice(site, a.deviceRefresh, !!a.deviceChat)
|
|
1007
|
+
const next = { ...a, deviceToken: dt.token, deviceRefresh: dt.refresh }
|
|
1008
|
+
// the pair it spent was the chat pair too
|
|
1009
|
+
if (a.deviceChat) Object.assign(next, { access: dt.token, refresh: dt.refresh, expires: dt.expires })
|
|
1010
|
+
await client.auth.set({ path: { id: ID }, body: next })
|
|
929
1011
|
return dt.token
|
|
930
1012
|
})
|
|
931
1013
|
|
|
@@ -937,13 +1019,13 @@ export async function QoderAuthPlugin({ client }) {
|
|
|
937
1019
|
let signIn = "kept"
|
|
938
1020
|
try {
|
|
939
1021
|
const cred = await fresh(getAuth)
|
|
940
|
-
if (
|
|
1022
|
+
if (renewed(cred)) signIn = "renewed"
|
|
941
1023
|
let env
|
|
942
1024
|
try {
|
|
943
|
-
env = await fetchUsage(cred.deviceToken)
|
|
1025
|
+
env = await fetchUsage(site, cred.deviceToken)
|
|
944
1026
|
} catch (e) {
|
|
945
1027
|
if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e
|
|
946
|
-
env = await fetchUsage(await deviceToken(getAuth, cred.deviceToken))
|
|
1028
|
+
env = await fetchUsage(site, await deviceToken(getAuth, cred.deviceToken))
|
|
947
1029
|
}
|
|
948
1030
|
return { ...parseUsage(env), signIn }
|
|
949
1031
|
} catch (e) {
|
|
@@ -954,7 +1036,7 @@ export async function QoderAuthPlugin({ client }) {
|
|
|
954
1036
|
const signedInError = (e) =>
|
|
955
1037
|
errorResponse({
|
|
956
1038
|
status: e instanceof SignInGone ? 401 : 502,
|
|
957
|
-
message: String(e?.message ?? e).replace(
|
|
1039
|
+
message: String(e?.message ?? e).replace(new RegExp(`^${site.name}: `), ""),
|
|
958
1040
|
signIn: e?.expired ? "expired" : undefined,
|
|
959
1041
|
})
|
|
960
1042
|
|
|
@@ -994,7 +1076,7 @@ export async function QoderAuthPlugin({ client }) {
|
|
|
994
1076
|
const a = await getAuth()
|
|
995
1077
|
if (a?.type !== "oauth") return {}
|
|
996
1078
|
return {
|
|
997
|
-
baseURL:
|
|
1079
|
+
baseURL: site.api,
|
|
998
1080
|
apiKey: "qoder",
|
|
999
1081
|
// every chat completion written as Qoder's own request
|
|
1000
1082
|
async fetch(input, init = {}) {
|
|
@@ -1013,22 +1095,22 @@ export async function QoderAuthPlugin({ client }) {
|
|
|
1013
1095
|
} catch (e) {
|
|
1014
1096
|
return signedInError(e)
|
|
1015
1097
|
}
|
|
1016
|
-
return signed(await ask(chat, cred, init),
|
|
1098
|
+
return signed(await ask(chat, cred, init), renewed(cred))
|
|
1017
1099
|
},
|
|
1018
1100
|
}
|
|
1019
1101
|
},
|
|
1020
|
-
methods: [{ type: "oauth", label:
|
|
1102
|
+
methods: [{ type: "oauth", label: `Sign in with ${site.name}`, authorize: () => deviceSignIn(site) }],
|
|
1021
1103
|
usage,
|
|
1022
1104
|
},
|
|
1023
1105
|
async config(config) {
|
|
1024
1106
|
config.provider ??= {}
|
|
1025
1107
|
const was = config.provider[ID] ?? {}
|
|
1026
1108
|
config.provider[ID] = {
|
|
1027
|
-
name:
|
|
1109
|
+
name: site.name,
|
|
1028
1110
|
npm: CHAT,
|
|
1029
|
-
api:
|
|
1111
|
+
api: site.api,
|
|
1030
1112
|
...was,
|
|
1031
|
-
models: { ...Object.fromEntries(
|
|
1113
|
+
models: { ...Object.fromEntries(site.models.map((m) => [m.id, configModel(m)])), ...(was.models ?? {}) },
|
|
1032
1114
|
}
|
|
1033
1115
|
},
|
|
1034
1116
|
// the account's own list, as Qoder's client asks it
|
|
@@ -1036,12 +1118,21 @@ export async function QoderAuthPlugin({ client }) {
|
|
|
1036
1118
|
id: ID,
|
|
1037
1119
|
async models(provider, { auth } = {}) {
|
|
1038
1120
|
if (auth?.type !== "oauth") return provider.models
|
|
1121
|
+
let cred
|
|
1122
|
+
try {
|
|
1123
|
+
cred = await fresh(async () => auth)
|
|
1124
|
+
} catch (e) {
|
|
1125
|
+
// the built-in listed through QoderCredentialOf: a refused job
|
|
1126
|
+
// refresh marked the account there; anything else marked nothing
|
|
1127
|
+
if (e?.expired) throw Object.assign(new Error(e.message), { signIn: "expired" })
|
|
1128
|
+
return provider.models
|
|
1129
|
+
}
|
|
1130
|
+
if (renewals.has(cred)) unsaid.add(cred.uid)
|
|
1039
1131
|
try {
|
|
1040
|
-
const cred = await fresh(async () => auth)
|
|
1041
1132
|
const ms = await models(cred, true)
|
|
1042
1133
|
if (!ms.length) return provider.models
|
|
1043
1134
|
return Object.fromEntries(
|
|
1044
|
-
ms.map((m) => [m.key, runtimeModel({ id: m.key, name: m.name, context: m.context, images: m.images, efforts: m.thinks ? m.efforts : [], free: m.free })]),
|
|
1135
|
+
ms.map((m) => [m.key, runtimeModel(site, { id: m.key, name: m.name, context: m.context, images: m.images, efforts: m.thinks ? m.efforts : [], free: m.free })]),
|
|
1045
1136
|
)
|
|
1046
1137
|
} catch {
|
|
1047
1138
|
return provider.models
|
|
@@ -1051,5 +1142,8 @@ export async function QoderAuthPlugin({ client }) {
|
|
|
1051
1142
|
}
|
|
1052
1143
|
}
|
|
1053
1144
|
|
|
1145
|
+
export const QoderAuthPlugin = makePlugin(SITES.qoder)
|
|
1146
|
+
export const QoderCNAuthPlugin = makePlugin(SITES["qoder-cn"])
|
|
1147
|
+
|
|
1054
1148
|
// for tests
|
|
1055
|
-
export const _internal = { parseUsage, gfmt, when, failure, modelInfo }
|
|
1149
|
+
export const _internal = { parseUsage, gfmt, when, failure, modelInfo, SITES, decodeBody }
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@magpie-community/opencode-qoder-auth",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Qoder
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Qoder subscriptions in OpenCode and magpie: Qoder (qoder.com) and Qoder CN (qoder.cn)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.mjs",
|
|
7
7
|
"exports": "./index.mjs",
|
|
8
8
|
"files": ["index.mjs", "README.md", "LICENSE-CLIProxyAPI"],
|
|
9
|
-
"keywords": ["opencode", "opencode-plugin", "magpie", "qoder"],
|
|
9
|
+
"keywords": ["opencode", "opencode-plugin", "magpie", "qoder", "qoder-cn"],
|
|
10
10
|
"license": "MIT"
|
|
11
11
|
}
|