orcaterm 0.1.1: QR sign-in null fields, OAuth quota, stable account identity (#510)
orcaterm 0.1.1 (hg1048596-pixel): - WeChat QR sign-in accepts the official bridge's null fields. - QR accounts read their AI quota through orcaterm.com's product API, with the token sent as the ot_session cookie only to https://orcaterm.com/cgi/api and redirects refused. - A QR re-sign-in reuses the same account, keyed by the stable OrcaTerm user id. - The README (en and zh) lists every host and what each one receives. Run at the reviewed head a9ab6853b (Mac mini, Bun 1.4.2): `bun test` in packages/orcaterm passed 101 of 101 with every non-loopback fetch and socket refused (none was attempted), and `bun scripts/check.mjs orcaterm` passed. Broken by hand at fa028746c, the last code change, each going red: the /cb null check, accountId on the QR result, and redirect: "error".
This commit is contained in:
@@ -18,6 +18,10 @@ magpie plugin login orcaterm
|
||||
|
||||
or install it from magpie's Plugins tab and sign in there.
|
||||
|
||||
QR sign-ins use the OrcaTerm user ID as the account identity, so signing in to the
|
||||
same user again updates that account even when the token or nickname changes.
|
||||
Older duplicate cards without this identity are not removed automatically.
|
||||
|
||||
## Before you use this: the terms
|
||||
|
||||
**This plugin uses OrcaTerm's built-in AI allowance from outside OrcaTerm, and Tencent's terms do
|
||||
@@ -45,7 +49,7 @@ fallback for when scanning is not possible, and it is the one that carries the r
|
||||
| --- | --- | --- |
|
||||
| `lightai.cloud.tencent.com` | every chat | the credential, the message text |
|
||||
| `api.orcaterm.cloud.tencent.com` | reading the allowance (cookie sign-ins only) | the credential |
|
||||
| `orcaterm.com` | QR sign-in, and renewing its token | the credential, and the OAuth `code` |
|
||||
| `orcaterm.com` | QR sign-in, token renewal, and OAuth account allowance reads | the credential, and the OAuth `code` |
|
||||
| `res.wx.qq.com` | QR sign-in page | nothing — it serves WeChat's `wxLogin.js` |
|
||||
| `open.weixin.qq.com` | the QR widget's iframe | the `appid`, `redirect_uri` and `state` OrcaTerm issued |
|
||||
|
||||
@@ -255,13 +259,17 @@ allowance, 1000 questions a month on the basic edition — as `amount / limit` w
|
||||
The other rows there (session sharing, secrets, space) are not shown: they are unrelated resources,
|
||||
and session sharing's unlimited `-1` would read as an exhausted account.
|
||||
|
||||
QR accounts use the same access token as the official client's `ot_session` cookie, sent only to
|
||||
`https://orcaterm.com/cgi/api`. Console-cookie accounts use `api.orcaterm.cloud.tencent.com`.
|
||||
Both sign-in methods can show the allowance; scanning does not require console credentials.
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
bun test
|
||||
```
|
||||
|
||||
88 tests over eight files. No test signs in and none talks to Tencent: the chat tests replace `fetch`, and the only sockets are loopback listeners that the `/cb` tests stand up themselves.
|
||||
101 tests over nine files. No test signs in and none talks to Tencent: the chat tests replace `fetch`, and the only sockets are the loopback listeners used by the callback tests.
|
||||
|
||||
| file | what it holds |
|
||||
| --- | --- |
|
||||
@@ -272,6 +280,7 @@ bun test
|
||||
| `peek.test.mjs` | a refusal read from the head of the stream becoming 429/401/502, and a real answer surviving the peek |
|
||||
| `usage.test.mjs` | which `usageStats` row is the AI allowance |
|
||||
| `audit.test.mjs` | invalid callback bodies; envelope whitespace and examples; EOF error frames; JSON error codes; reader cleanup; read failures and cancellation |
|
||||
| `identity.test.mjs` | stable identity across QR re-sign-ins with rotated tokens or changed nicknames; distinct users staying separate; token user ID fallback; refusing missing identity; renewal and account-scoped backfill preserving credentials and metadata |
|
||||
| `review.test.mjs` | the cases the reviews turned up: a reply containing `{"action": …}` is not truncated (including one character at a time, and one that ends mid-envelope); the JSON 429 is a 429; pacers are per account; only nine models are listed; a chat makes exactly one request and it is not `/conversation`; and `/cb` refuses a foreign `Origin`, a rebinding page, and a `state` it did not issue |
|
||||
|
||||
`chunks.test.mjs`'s cancel case fails if `releaseUpstream()` is removed, so the leak stays fixed.
|
||||
@@ -299,12 +308,16 @@ GLM、Kimi。provider id:`orcaterm`。
|
||||
`Hunyuan3/hy4-preview`。**id 必须带命名空间前缀**,否则上游答 `LLM(x) is not loaded`。
|
||||
**其余 id 不要用**(如 `qwen3`、`deepseek-reasoner`、`kimi-latest`、`hunyuan-turbos`、
|
||||
`glm-4.7-thinking` 等):它们在选择器里选不到,属于绕过界面调用,**有封号风险**。
|
||||
- **会连到哪些主机**:`lightai.cloud.tencent.com`(每次对话)、
|
||||
`api.orcaterm.cloud.tencent.com`(读额度,仅 cookie 登录时)、`orcaterm.com`(扫码登录与续期);
|
||||
另有 `res.wx.qq.com`(提供微信的 `wxLogin.js`)与 `open.weixin.qq.com`(二维码 iframe),
|
||||
- **会连到哪些主机,以及发送什么**:`lightai.cloud.tencent.com`(每次对话:凭据和消息文本)、
|
||||
`api.orcaterm.cloud.tencent.com`(仅控制台 cookie 账号读额度:凭据)、
|
||||
`orcaterm.com`(扫码登录、令牌续期及扫码账号读额度:OAuth 凭据与 OAuth `code`;
|
||||
其中额度查询将 token 作为 `ot_session` cookie 发送到硬编码的 `https://orcaterm.com/cgi/api`,拒绝重定向)。
|
||||
另有 `res.wx.qq.com`(提供微信的 `wxLogin.js`,不发送登录凭据)与 `open.weixin.qq.com`
|
||||
(二维码 iframe,只接收 OrcaTerm 签发的 `appid`、`redirect_uri` 和 `state`,不发送登录凭据);
|
||||
这两个只在扫码登录时加载,cookie 登录不会碰。除此之外不发往任何地方。
|
||||
- **额度**:`magpie quota` 显示每月问答次数(基础版 1000 次)与重置日期。扫码登录的账号读不到
|
||||
配额(额度接口只认控制台会话),这不影响使用。
|
||||
- **额度**:`magpie quota` 显示每月问答次数(基础版 1000 次)与重置日期。微信扫码账号通过
|
||||
`orcaterm.com` 的产品接口读取额度,使用已有 OAuth token 的 `ot_session` cookie,无需控制台凭据;
|
||||
控制台 cookie 账号继续通过 `api.orcaterm.cloud.tencent.com` 查询。
|
||||
- **失败会如实报错**:上游把失败写在 SSE 里(`data: [ERROR]: …`),HTTP 状态仍是 200。
|
||||
插件会先读流头,把配额用完/限流回成 429、登录失效回成 401 并标记账号,这样 magpie 才会换账号
|
||||
或让账号歇着,而不是把失败当成一次正常回答。限流还有一条**不走 SSE** 的路径:HTTP 200 +
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { test, afterEach } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import vm from "node:vm"
|
||||
import { OrcaTermAuthPlugin, _internal as i } from "./index.mjs"
|
||||
|
||||
const realFetch = globalThis.fetch
|
||||
@@ -185,3 +186,48 @@ test("callback preserves bridge errors without a code and still permits a later
|
||||
assert.deepEqual(await cap.wait, { code: "C", state: "audit-state" })
|
||||
} finally { cap.close() }
|
||||
})
|
||||
|
||||
test("official bridge success with error null passes through the login page", async () => {
|
||||
const cap = i.createLocalCapture({ appid: "audit", redirectUri: "https://orcaterm.com/oauth/wechat/bridge", state: "audit-state", timeoutMs: 5000 })
|
||||
try {
|
||||
const url = await cap.ready
|
||||
const html = await (await realFetch(url, { headers: { connection: "close" } })).text()
|
||||
const script = /<script>\s*([\s\S]*?)<\/script>/.exec(html)?.[1]
|
||||
assert.ok(script)
|
||||
let listener
|
||||
const elements = new Map(["wrap", "done"].map(id => [id, { style: {}, textContent: "" }]))
|
||||
vm.runInNewContext(script, {
|
||||
WxLogin: function () {}, URL, location: { href: url },
|
||||
document: { getElementById: id => elements.get(id) },
|
||||
window: { addEventListener(type, callback) { if (type === "message") listener = callback } },
|
||||
fetch(target, init) {
|
||||
return realFetch(target, { ...init, headers: { ...init.headers, origin: new URL(url).origin, connection: "close" } })
|
||||
},
|
||||
}, { timeout: 1000 })
|
||||
// The public /oauth/wechat/bridge uses URLSearchParams.get(...) || null
|
||||
// for code, state and error; successful scans therefore carry error: null.
|
||||
await listener({ origin: "https://orcaterm.com", data: {
|
||||
type: "wechat-oauth-callback", code: "C", state: "audit-state", error: null,
|
||||
} })
|
||||
assert.match(elements.get("done").textContent, /^Scanned/)
|
||||
assert.deepEqual(await cap.wait, { code: "C", state: "audit-state" })
|
||||
} finally { cap.close() }
|
||||
})
|
||||
|
||||
test("official bridge cancellation with code null keeps the error message", async () => {
|
||||
const cap = i.createLocalCapture({ appid: "audit", redirectUri: "https://orcaterm.com/oauth/wechat/bridge", state: "audit-state", timeoutMs: 5000 })
|
||||
try {
|
||||
const url = await cap.ready
|
||||
const send = value => realFetch(new URL("/cb", url), {
|
||||
method: "POST", headers: { "content-type": "application/json", origin: new URL(url).origin, connection: "close" }, body: JSON.stringify(value),
|
||||
})
|
||||
const error = await send({ code: null, state: "audit-state", error: "access_denied" })
|
||||
assert.equal(error.status, 200)
|
||||
assert.deepEqual(await error.json(), { ok: false, error: "access_denied" })
|
||||
const missing = await send({ code: null, state: "audit-state", error: null })
|
||||
assert.equal(missing.status, 400)
|
||||
const success = await send({ code: "C", state: "audit-state", error: null })
|
||||
assert.equal((await success.json()).ok, true)
|
||||
assert.deepEqual(await cap.wait, { code: "C", state: "audit-state" })
|
||||
} finally { cap.close() }
|
||||
})
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { test, afterEach } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { OrcaTermAuthPlugin } from "./index.mjs"
|
||||
|
||||
const realFetch = globalThis.fetch
|
||||
afterEach(() => { globalThis.fetch = realFetch })
|
||||
const json = data => Response.json({ code: 0, data })
|
||||
const token = (userId, nonce) => `eyJhbGciOiJub25lIn0.${Buffer.from(JSON.stringify({ userId, nonce })).toString("base64url")}.test`
|
||||
|
||||
async function scan(data) {
|
||||
globalThis.fetch = async url => {
|
||||
if (String(url).endsWith("/oauth/wechat/config")) return json({
|
||||
appid: "identity-test", redirect_uri: "https://orcaterm.com/oauth/wechat/bridge",
|
||||
state: "identity-state", scope: "snsapi_login",
|
||||
})
|
||||
assert.ok(String(url).endsWith("/oauth/wechat/exchange"))
|
||||
return json(data)
|
||||
}
|
||||
const plugin = await OrcaTermAuthPlugin()
|
||||
const flow = await plugin.auth.methods[0].authorize()
|
||||
assert.equal(flow.method, "auto")
|
||||
try {
|
||||
const res = await realFetch(new URL("/cb", flow.url), {
|
||||
method: "POST", headers: { "content-type": "application/json", origin: new URL(flow.url).origin, connection: "close" },
|
||||
body: JSON.stringify({ code: "test-code", state: "identity-state", error: null }),
|
||||
})
|
||||
assert.equal(res.status, 200)
|
||||
return await flow.callback()
|
||||
} finally { flow.__cap.close() }
|
||||
}
|
||||
|
||||
test("QR re-sign-in keeps identity across token and nickname changes, separating other users", async () => {
|
||||
const first = await scan({ userId: 123, accessToken: token("123", 1), providerUsername: "Alice" })
|
||||
const again = await scan({ userId: 123, accessToken: token("123", 2), providerUsername: "Renamed" })
|
||||
const other = await scan({ userId: 456, accessToken: token("456", 3), providerUsername: "Alice" })
|
||||
for (const result of [first, again, other]) {
|
||||
assert.equal(result.type, "success")
|
||||
assert.equal(result.accountId, result.userId)
|
||||
assert.equal(result.uid, result.userId)
|
||||
}
|
||||
assert.notEqual(first.access, again.access)
|
||||
assert.equal(first.accountId, again.accountId)
|
||||
assert.notEqual(first.accountId, other.accountId)
|
||||
})
|
||||
|
||||
test("QR sign-in falls back to the token userId when the exchange omits it", async () => {
|
||||
const result = await scan({ accessToken: token("token-user", 1) })
|
||||
assert.equal(result.type, "success")
|
||||
assert.equal(result.accountId, "token-user")
|
||||
assert.equal(result.uid, "token-user")
|
||||
})
|
||||
|
||||
test("QR sign-in refuses to save an account with no stable identity", async () => {
|
||||
const result = await scan({ accessToken: token(undefined, 1) })
|
||||
assert.equal(result.type, "failed")
|
||||
assert.match(result.error, /no userId/)
|
||||
})
|
||||
|
||||
test("renewal supplies identity for older stored OAuth credentials", async () => {
|
||||
const before = token("legacy-user", 1)
|
||||
const after = token("legacy-user", 2)
|
||||
globalThis.fetch = async url => {
|
||||
assert.equal(String(url), "https://orcaterm.com/cgi/api?action=OAuthRefreshToken")
|
||||
return json({ accessToken: after, expiresIn: 7200 })
|
||||
}
|
||||
const plugin = await OrcaTermAuthPlugin()
|
||||
const next = await plugin.auth.refresh({ type: "oauth", access: before, refresh: before })
|
||||
assert.equal(next.access, after)
|
||||
assert.equal(next.accountId, "legacy-user")
|
||||
assert.equal(next.uid, "legacy-user")
|
||||
assert.equal(next.userId, "legacy-user")
|
||||
})
|
||||
|
||||
test("renewal preserves an existing account name and vendor uid", async () => {
|
||||
const before = token("user", 1)
|
||||
globalThis.fetch = async () => json({ accessToken: token("user", 2), expiresIn: 7200 })
|
||||
const plugin = await OrcaTermAuthPlugin()
|
||||
const next = await plugin.auth.refresh({ type: "oauth", access: before, refresh: before, accountId: "My account", uid: "user" })
|
||||
assert.equal(next.accountId, "My account")
|
||||
assert.equal(next.uid, "user")
|
||||
})
|
||||
|
||||
test("loading older accounts backfills identity without dropping credentials or metadata", async () => {
|
||||
const saved = []
|
||||
const plugin = await OrcaTermAuthPlugin({ client: { auth: { async set(value) { saved.push(value) } } } })
|
||||
for (const user of ["first-user", "second-user"]) {
|
||||
const credential = { type: "oauth", access: token(user, 1), refresh: token(user, 1), expires: 123, metadata: { nickname: "Same name" } }
|
||||
await plugin.auth.loader(async () => credential)
|
||||
assert.deepEqual(saved.at(-1), { path: { id: "orcaterm" }, body: {
|
||||
...credential, accountId: user, uid: user, userId: user,
|
||||
} })
|
||||
}
|
||||
assert.equal(saved.length, 2)
|
||||
})
|
||||
|
||||
test("loading an identified account preserves its name and avoids rewriting it", async () => {
|
||||
let writes = 0
|
||||
const plugin = await OrcaTermAuthPlugin({ client: { auth: { async set() { writes++ } } } })
|
||||
await plugin.auth.loader(async () => ({ type: "oauth", access: token("user", 1), accountId: "My account", uid: "user" }))
|
||||
assert.equal(writes, 0)
|
||||
})
|
||||
|
||||
test("quota refresh backfills an older account before another sign-in, even if quota is unavailable", async () => {
|
||||
const saved = []
|
||||
const plugin = await OrcaTermAuthPlugin({ client: { auth: { async set(value) { saved.push(value) } } } })
|
||||
const credential = { type: "oauth", access: token("quota-user", 1), refresh: token("quota-user", 1) }
|
||||
globalThis.fetch = async () => { throw new Error("quota unavailable") }
|
||||
const usage = await plugin.auth.usage(async () => credential)
|
||||
assert.match(usage.error, /quota unavailable/)
|
||||
assert.deepEqual(saved, [{ path: { id: "orcaterm" }, body: {
|
||||
...credential, accountId: "quota-user", uid: "quota-user", userId: "quota-user",
|
||||
} }])
|
||||
})
|
||||
+46
-19
@@ -12,15 +12,16 @@
|
||||
* headers: x-seqid + cookie(uin/skey) + the browser-family headers
|
||||
* response: SSE, one `data: {...}` per line; the text is in content, the
|
||||
* thinking in reasoningContent
|
||||
* account API POST https://api.orcaterm.cloud.tencent.com/cgi/api?<signed action>
|
||||
* body: {action, data}; signed head and tail (X-CsrfCode is the djb2 of
|
||||
* the cookie's skey)
|
||||
* account API POST https://api.orcaterm.cloud.tencent.com/cgi/api for uin/skey,
|
||||
* or https://orcaterm.com/cgi/api for the OAuth ot_session cookie.
|
||||
* body: {action, data}; console cookies also require X-CsrfCode.
|
||||
*
|
||||
* The outward contract of this file follows magpie's docs exactly:
|
||||
* config / auth{methods, loader, usage} / provider.models / chat.headers
|
||||
*/
|
||||
import { createHash, randomBytes, randomUUID } from "node:crypto"
|
||||
import {
|
||||
OAUTH_BASE,
|
||||
createLocalCapture,
|
||||
exchangeCode,
|
||||
looksLikeAccessToken,
|
||||
@@ -1677,25 +1678,35 @@ async function classifyUpstreamError(res) {
|
||||
* So "a non-auth error came back" means the credential is valid.
|
||||
*/
|
||||
async function capiRequest(auth, action, data = {}) {
|
||||
const bearer = bearerOf(auth)
|
||||
const t = auth?.ticket ?? {}
|
||||
const seq = `${Date.now()}-${Math.floor(Math.random() * 1e6)}`
|
||||
const uin = t.uin || t.p_uin || ""
|
||||
const url = `${CAPI_URL}?action=${encodeURIComponent(action)}&t=${seq}`
|
||||
// OrcaTerm's AuthStore.syncCookie writes this access token as ot_session.
|
||||
// Its product API reads that cookie; an Authorization header is not enough.
|
||||
const url = `${bearer ? `${OAUTH_BASE}/cgi/api` : CAPI_URL}?action=${encodeURIComponent(action)}&t=${seq}`
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: baseHeaders({
|
||||
accept: "application/json",
|
||||
"content-type": "application/json",
|
||||
"x-seqid": seq,
|
||||
"x-referer": WEB_TERMINAL,
|
||||
"x-csrfcode": csrfCode(t.skey),
|
||||
cookie: cookieHeader(auth),
|
||||
...(bearer ? {
|
||||
origin: OAUTH_BASE,
|
||||
referer: `${OAUTH_BASE}/terminal`,
|
||||
"x-referer": `${OAUTH_BASE}/terminal`,
|
||||
cookie: `ot_session=${bearer}`,
|
||||
} : {
|
||||
"x-referer": WEB_TERMINAL,
|
||||
"x-csrfcode": csrfCode(t.skey),
|
||||
cookie: cookieHeader(auth),
|
||||
}),
|
||||
}),
|
||||
// Measured: upstream validates the data field strictly, and an extra sig
|
||||
// comes back as "property feature should not exist". Sending {action, data}
|
||||
// as it is works.
|
||||
body: JSON.stringify({ action, data }),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
redirect: "error",
|
||||
})
|
||||
const text = await res.text()
|
||||
try {
|
||||
@@ -1787,6 +1798,17 @@ export const OrcaTermAuthPlugin = async ({ client } = {}) => {
|
||||
]),
|
||||
)
|
||||
|
||||
async function identifyAccount(auth, bearer) {
|
||||
const userId = readTokenClaims(bearer).userId
|
||||
// The SDK writes only the account whose loader or usage hook is running.
|
||||
if (userId && (!auth?.accountId || !auth?.uid) && client?.auth?.set) {
|
||||
await client.auth.set({ path: { id: PROVIDER }, body: {
|
||||
...auth, accountId: auth?.accountId || userId,
|
||||
uid: auth?.uid || userId, userId,
|
||||
} })
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
// ---- provider declaration -----------------------------------------------
|
||||
config: async (cfg) => {
|
||||
@@ -1879,6 +1901,9 @@ export const OrcaTermAuthPlugin = async ({ client } = {}) => {
|
||||
access: r.accessToken,
|
||||
refresh: r.accessToken,
|
||||
expires: r.expiresAt ?? Date.now() + 7200 * 1000,
|
||||
// magpie deduplicates re-sign-ins by accountId, not userId.
|
||||
accountId: r.userId,
|
||||
uid: r.userId,
|
||||
userId: r.userId,
|
||||
metadata: {
|
||||
via: "wechat-qr",
|
||||
@@ -1920,11 +1945,13 @@ export const OrcaTermAuthPlugin = async ({ client } = {}) => {
|
||||
if (!bearer) return null
|
||||
try {
|
||||
const r = await refreshAccessToken(bearer)
|
||||
const userId = readTokenClaims(bearer).userId || auth?.userId || auth?.metadata?.userId
|
||||
return {
|
||||
key: r.accessToken,
|
||||
access: r.accessToken,
|
||||
refresh: r.accessToken,
|
||||
expires: r.expiresAt ?? undefined,
|
||||
...(userId ? { accountId: auth?.accountId || String(userId), uid: auth?.uid || String(userId), userId: String(userId) } : {}),
|
||||
metadata: { ...(auth?.metadata ?? {}), via: "wechat-qr", expires: r.expiresAt ?? undefined },
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -1951,6 +1978,7 @@ export const OrcaTermAuthPlugin = async ({ client } = {}) => {
|
||||
let bound
|
||||
if (bearer) {
|
||||
const claims = readTokenClaims(bearer)
|
||||
await identifyAccount(auth, bearer)
|
||||
if (claims.exp && claims.exp * 1000 < Date.now()) {
|
||||
throw Object.assign(new Error("OrcaTerm sign-in expired, scan again"), { signIn: "expired" })
|
||||
}
|
||||
@@ -2112,16 +2140,14 @@ export const OrcaTermAuthPlugin = async ({ client } = {}) => {
|
||||
/** magpie's own hook: show OrcaTerm's Q&A quota on the account card */
|
||||
async usage(getAuth) {
|
||||
const auth = await getAuth()
|
||||
// A WeChat scan yields an accessToken, not uin/skey — the quota endpoint
|
||||
// only speaks the console session, so such an account has no quota to
|
||||
// read. Return no windows rather than an error: the account is fine, and
|
||||
// "credential is missing uin" would read as a failed sign-in.
|
||||
const bearer = bearerOf(auth)
|
||||
if (bearer) return { user: readTokenClaims(bearer).nickname || undefined, windows: [] }
|
||||
const ticket = parseTicket(auth?.key ?? "")
|
||||
if (!ticket) return { error: "not signed in", windows: [] }
|
||||
if (!ticket.uin) return { error: "the credential is missing uin; paste uin and skey again", windows: [] }
|
||||
const bound = { ...auth, ticket }
|
||||
let bound = auth
|
||||
if (!bearer) {
|
||||
const ticket = parseTicket(auth?.key ?? "")
|
||||
if (!ticket) return { error: "not signed in", windows: [] }
|
||||
if (!ticket.uin) return { error: "the credential is missing uin; paste uin and skey again", windows: [] }
|
||||
bound = { ...auth, ticket }
|
||||
}
|
||||
|
||||
// A throw in usage puts an error on the account card, so everything is
|
||||
// caught here; the worst case is just "can't read the quota"
|
||||
@@ -2129,6 +2155,7 @@ export const OrcaTermAuthPlugin = async ({ client } = {}) => {
|
||||
// Measured (2026-10-27): the real quota is in DescribeUserBillingStatus'
|
||||
// usageStats[], not in DescribeUserUsageStats (whose feature only knows
|
||||
// hunyuan_ai/session_share/secret).
|
||||
if (bearer) await identifyAccount(auth, bearer)
|
||||
const billing = await capiRequest(bound, "DescribeUserBillingStatus", {})
|
||||
const resp = billing?.data?.Response ?? billing?.Response
|
||||
if (resp?.Error) {
|
||||
@@ -2169,11 +2196,11 @@ export const OrcaTermAuthPlugin = async ({ client } = {}) => {
|
||||
}
|
||||
|
||||
// also pick up the account name, so the account card reads clearly
|
||||
let user
|
||||
let user = bearer ? readTokenClaims(bearer).nickname || undefined : undefined
|
||||
try {
|
||||
const info = await capiRequest(bound, "GetUserInfo", {})
|
||||
const ir = info?.data?.Response ?? info?.Response
|
||||
user = ir?.nickName ?? ir?.username ?? ir?.uin
|
||||
user = ir?.nickName ?? ir?.username ?? ir?.uin ?? user
|
||||
} catch {
|
||||
/* fine if it can't be read */
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-orcaterm-auth",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"description": "OrcaTerm (Tencent Cloud 遨驰终端) AI quota as an OpenAI-compatible provider for magpie and OpenCode",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
@@ -74,3 +74,57 @@ test("an unreadable answer becomes an error string, not a throw", async () => {
|
||||
expect(typeof u.error).toBe("string")
|
||||
expect(u.windows).toEqual([])
|
||||
})
|
||||
|
||||
const oauthToken = `${Buffer.from('{"alg":"HS256","typ":"JWT"}').toString("base64url")}.${Buffer.from('{"userId":"test-user","providerUsername":"QR tester"}').toString("base64url")}.FAKE_SIGNATURE_ONLY`
|
||||
|
||||
test("QR accounts read quota using ot_session only on orcaterm.com", async () => {
|
||||
const seen = []
|
||||
globalThis.fetch = async (url, init) => {
|
||||
seen.push({ url: String(url), init })
|
||||
const action = JSON.parse(init.body).action
|
||||
if (action === "GetUserInfo") return new Response(JSON.stringify({ data: { Response: { nickName: "QR tester" } } }))
|
||||
return billing([{ feature: "hunyuan_ai", quotaLimit: 1000, quotaUsed: 0, quotaEndDate: "2026-11-21T16:00:00.000Z" }])
|
||||
}
|
||||
const hooks = await OrcaTermAuthPlugin()
|
||||
const u = await hooks.auth.usage(async () => ({ type: "oauth", access: oauthToken }))
|
||||
expect(u.windows).toHaveLength(1)
|
||||
expect(u.windows[0].amount).toBe(0)
|
||||
expect(u.windows[0].limit).toBe(1000)
|
||||
expect(u.windows[0].resetsAt).toBe("2026-11-21T16:00:00.000Z")
|
||||
expect(u.user).toBe("QR tester")
|
||||
expect(seen).toHaveLength(2)
|
||||
for (const { url, init } of seen) {
|
||||
expect(new URL(url).origin).toBe("https://orcaterm.com")
|
||||
expect(new URL(url).pathname).toBe("/cgi/api")
|
||||
expect(url.includes(oauthToken)).toBe(false)
|
||||
const h = new Headers(init.headers)
|
||||
expect(h.get("cookie")).toBe(`ot_session=${oauthToken}`)
|
||||
expect(h.get("authorization")).toBeNull()
|
||||
expect(h.get("x-csrfcode")).toBeNull()
|
||||
expect(init.redirect).toBe("error")
|
||||
}
|
||||
})
|
||||
|
||||
test("an explicitly refused OAuth quota read marks that account expired", async () => {
|
||||
const seen = []
|
||||
globalThis.fetch = async url => {
|
||||
seen.push(new URL(url).origin)
|
||||
return new Response(JSON.stringify({ data: { Response: { Error: { Code: "VERIFY_USER_FAILED" } } } }))
|
||||
}
|
||||
const hooks = await OrcaTermAuthPlugin()
|
||||
const u = await hooks.auth.usage(async () => ({ type: "oauth", access: oauthToken }))
|
||||
expect(u.signIn).toBe("expired")
|
||||
expect(u.windows).toEqual([])
|
||||
expect(seen).toEqual(["https://orcaterm.com"])
|
||||
})
|
||||
|
||||
test("OAuth identity lookup failure preserves the token's display name", async () => {
|
||||
globalThis.fetch = async (url, init) => {
|
||||
if (JSON.parse(init.body).action === "GetUserInfo") throw new Error("identity unavailable")
|
||||
return billing([{ feature: "hunyuan_ai", quotaLimit: 1000, quotaUsed: 10 }])
|
||||
}
|
||||
const hooks = await OrcaTermAuthPlugin()
|
||||
const u = await hooks.auth.usage(async () => ({ type: "oauth", access: oauthToken }))
|
||||
expect(u.user).toBe("QR tester")
|
||||
expect(u.windows[0].amount).toBe(10)
|
||||
})
|
||||
|
||||
@@ -110,9 +110,11 @@ export async function exchangeCode({ code, state, base = OAUTH_BASE }) {
|
||||
}
|
||||
const d = body.data
|
||||
if (!d.accessToken) throw new WechatLoginError("INTERNAL_ERROR", "[exchange] no accessToken in the response")
|
||||
const userId = String(d.userId ?? "").trim() || readTokenClaims(d.accessToken).userId.trim()
|
||||
if (!userId) throw new WechatLoginError("INTERNAL_ERROR", "[exchange] no userId in the response or access token")
|
||||
const expiresIn = Number(d.expiresIn) || 0
|
||||
return {
|
||||
userId: String(d.userId ?? ""),
|
||||
userId,
|
||||
nickname: d.providerUsername ?? "",
|
||||
avatar: d.avatar ?? "",
|
||||
accessToken: d.accessToken,
|
||||
@@ -316,10 +318,12 @@ export function createLocalCapture({ appid, redirectUri, state, timeoutMs = 3000
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
// OrcaTerm's bridge uses null for missing URL parameters: successful
|
||||
// scans carry error: null, and cancellations can carry code: null.
|
||||
if (!body || typeof body !== "object" || Array.isArray(body) ||
|
||||
typeof body.state !== "string" ||
|
||||
(body.error !== undefined && typeof body.error !== "string") ||
|
||||
(body.code !== undefined && typeof body.code !== "string") ||
|
||||
(body.error != null && typeof body.error !== "string") ||
|
||||
(body.code != null && typeof body.code !== "string") ||
|
||||
(typeof body.code !== "string" && !body.error)) {
|
||||
res.writeHead(400, { "content-type": "application/json" })
|
||||
res.end(JSON.stringify({ ok: false, error: "invalid callback body" }))
|
||||
|
||||
Reference in New Issue
Block a user