qoder 0.2.57: QwenWork's gateway calls name the client, and a biz account refreshes for its team (tnt1223)
tnt1223 (Discord) signed in to QwenWork. Test models and the model list
both failed: "QwenWork models: HTTP 403: {"code":"403","message":"User
identity could not be verified"}". No QwenWork account was at hand, so
the case wasn't reproduced. These are the differences from QwenWorkCN.app
1.2.1 (its out/main/main.js) that the code shows:
- openApiJsonRequest puts User-Agent qoderwork/1.2.1, a fresh
X-Request-Id and getQwenWorkClientHeaders (X-QwenWork-Version,
-Release-Version 1.2.1-26092107, -Build 26092107, -Platform, -Arch,
-Channel stable) on every gateway call. These cover the device poll,
the account-context, wallets and the device token's refresh. The
plugin sent none of them. It now sends them on the QwenWork sites
(site.clientHeaders), in openapi() and in usage's read.
- refreshDeviceToken asks for {target:"biz", team_id} when the account
is a biz one (getIdentityFromUser: is_biz with an org and a team, read
through normalizeAccountContext), and for "c" otherwise. It adds
client_id and redirect_uri when the client signs in with that pair.
The plugin always asked for "c", which turned a biz account's token
personal on its first refresh. The sign-in now records identity and
teamId (accountIdentity), and deviceRefreshBody asks as the client
does. An enterprise-domain account sends no redirect_uri, since its
sign-in has none (siteOf).
- The 403 on the model list now adds that the sign-in's identity wasn't
recognised, and to sign in again. Other 403s read as before.
Qoder and Qoder CN are unchanged. A test checks that a Qoder call
carries no X-QwenWork-* or User-Agent, and that the refresh body is the
token alone.
Run on mote (bun 1.4.2):
- packages/qoder bun test: 381 pass, 0 fail.
- bun scripts/check.mjs: all packages ok.
Broken by hand in a copy, with the client headers dropped, the refresh
always "c", the identity not recorded, the enterprise redirect_uri kept
and the hint removed: 4 of the new tests failed.
Not tried:
- A real QwenWork account, personal or biz, so it isn't known that
these were the cause of the 403.
- The chat's Cosy-* signing. The official app signs it through its CLI's
wasm (sign-request), and that wasm also has Cosy-Organization-Id,
Cosy-Organization-Tags and Cosy-Data-Policy, which the plugin doesn't
send. Which account fields fill them wasn't read out of the wasm.
This commit is contained in:
@@ -223,7 +223,9 @@ const b64url = (buf) => buf.toString("base64url")
|
|||||||
async function openapi(site, path, { method = "GET", token, body, query } = {}) {
|
async function openapi(site, path, { method = "GET", token, body, query } = {}) {
|
||||||
const url = new URL(site.openapi + path)
|
const url = new URL(site.openapi + path)
|
||||||
for (const [k, v] of Object.entries(query ?? {})) url.searchParams.set(k, v)
|
for (const [k, v] of Object.entries(query ?? {})) url.searchParams.set(k, v)
|
||||||
const headers = { Accept: "application/json" }
|
// a site whose own client names itself on these calls (QwenWork) sends
|
||||||
|
// the same names
|
||||||
|
const headers = { Accept: "application/json", ...(site.clientHeaders?.() ?? {}) }
|
||||||
if (body) headers["Content-Type"] = "application/json"
|
if (body) headers["Content-Type"] = "application/json"
|
||||||
if (token) headers.Authorization = `Bearer ${token}`
|
if (token) headers.Authorization = `Bearer ${token}`
|
||||||
const res = await fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(20_000) })
|
const res = await fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(20_000) })
|
||||||
@@ -615,7 +617,8 @@ function siteOf(site, a) {
|
|||||||
// enterpriseHost, not the site's vpcDomain (Qoder CN's VPC suffix rule)
|
// enterpriseHost, not the site's vpcDomain (Qoder CN's VPC suffix rule)
|
||||||
if (a?.enterpriseHost) {
|
if (a?.enterpriseHost) {
|
||||||
const base = `https://${a.enterpriseHost}`
|
const base = `https://${a.enterpriseHost}`
|
||||||
return { ...site, web: base, openapi: base, api: base, vpc: a.enterpriseHost }
|
// and with no redirect_uri, as its sign-in had none
|
||||||
|
return { ...site, web: base, openapi: base, api: base, vpc: a.enterpriseHost, redirect: "" }
|
||||||
}
|
}
|
||||||
if (a?.dedicated && a.lingma) {
|
if (a?.dedicated && a.lingma) {
|
||||||
const s = lingmaSite(site, a.dedicated)
|
const s = lingmaSite(site, a.dedicated)
|
||||||
@@ -676,10 +679,12 @@ async function deviceSignIn(site) {
|
|||||||
let name = ""
|
let name = ""
|
||||||
let uid = dt.user_id
|
let uid = dt.user_id
|
||||||
let user = null
|
let user = null
|
||||||
|
let identity = {}
|
||||||
try {
|
try {
|
||||||
const ui = await openapi(site, site.userInfoPath ?? "/api/v1/userinfo", { token: dt.token })
|
const ui = await openapi(site, site.userInfoPath ?? "/api/v1/userinfo", { token: dt.token })
|
||||||
if (ui.status >= 200 && ui.status < 300) {
|
if (ui.status >= 200 && ui.status < 300) {
|
||||||
user = site.normalizeUser ? site.normalizeUser(ui.json) : ui.json
|
user = site.normalizeUser ? site.normalizeUser(ui.json) : ui.json
|
||||||
|
if (site.deviceRefreshTarget) identity = accountIdentity(ui.json)
|
||||||
;[email, name] = [user?.email ?? "", user?.name ?? ""]
|
;[email, name] = [user?.email ?? "", user?.name ?? ""]
|
||||||
if (site.deviceOnly) uid = String(user?.id ?? user?.user_id ?? user?.uid ?? uid ?? "") || undefined
|
if (site.deviceOnly) uid = String(user?.id ?? user?.user_id ?? user?.uid ?? uid ?? "") || undefined
|
||||||
// a VPC poll may give the token alone: the user is then the one
|
// a VPC poll may give the token alone: the user is then the one
|
||||||
@@ -716,6 +721,7 @@ async function deviceSignIn(site) {
|
|||||||
machineId,
|
machineId,
|
||||||
deviceToken: dt.token,
|
deviceToken: dt.token,
|
||||||
deviceRefresh: dt.refresh_token ?? "",
|
deviceRefresh: dt.refresh_token ?? "",
|
||||||
|
...identity,
|
||||||
...(site.vpc ? { vpc: site.vpc } : {}),
|
...(site.vpc ? { vpc: site.vpc } : {}),
|
||||||
...(site.enterpriseDomain ? { vpc: site.enterpriseDomain, enterpriseHost: site.enterpriseDomain } : {}),
|
...(site.enterpriseDomain ? { vpc: site.enterpriseDomain, enterpriseHost: site.enterpriseDomain } : {}),
|
||||||
...(site.dedicated ? { dedicated: site.dedicated, ...(site.api !== dedicatedHost(site.web, "-gateway") ? { dedicatedApi: site.api } : {}) } : {}),
|
...(site.dedicated ? { dedicated: site.dedicated, ...(site.api !== dedicatedHost(site.web, "-gateway") ? { dedicatedApi: site.api } : {}) } : {}),
|
||||||
@@ -1019,7 +1025,14 @@ async function fetchListing(site, cred) {
|
|||||||
// flagship answers 503 "Model catalog is unavailable") falls back to
|
// flagship answers 503 "Model catalog is unavailable") falls back to
|
||||||
// the list its site ships
|
// the list its site ships
|
||||||
if (res.status === 503 && site.fallbackModels) return site.fallbackModels
|
if (res.status === 503 && site.fallbackModels) return site.fallbackModels
|
||||||
throw new Error(`${site.name} models: HTTP ${res.status}: ${text.trim().slice(0, 512)}`)
|
// QwenWork's "User identity could not be verified" (tnt1223 on
|
||||||
|
// Discord): before 0.2.57 a biz account's token was refreshed as
|
||||||
|
// personal, and no gateway call named the client. A sign-in records
|
||||||
|
// the account's identity, which the refresh then asks for.
|
||||||
|
const again = res.status === 403 && site.deviceRefreshTarget && /identity could not be verified/i.test(text)
|
||||||
|
? ` — ${site.name} didn't recognise this sign-in's identity; sign in to the account again`
|
||||||
|
: ""
|
||||||
|
throw new Error(`${site.name} models: HTTP ${res.status}: ${text.trim().slice(0, 512)}${again}`)
|
||||||
}
|
}
|
||||||
return JSON.parse(text)
|
return JSON.parse(text)
|
||||||
}
|
}
|
||||||
@@ -2553,16 +2566,30 @@ async function campaignCall(url, method, body, deviceToken, machine, signal) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// deviceRefreshBody is what the device token's refresh is asked with. A
|
||||||
|
// site with a refresh target (QwenWork) asks as its client does
|
||||||
|
// (refreshDeviceToken): a biz account for its own team, any other for
|
||||||
|
// "c", and with the client id and redirect_uri when the site signs in with
|
||||||
|
// that pair. Asked for "c", a biz account's token was rotated to its
|
||||||
|
// personal identity.
|
||||||
|
function deviceRefreshBody(site, refresh, a = {}) {
|
||||||
|
if (!site.deviceRefreshTarget) return { refresh_token: refresh }
|
||||||
|
const body = a?.identity === "biz" && a?.teamId
|
||||||
|
? { refresh_token: refresh, target: "biz", team_id: a.teamId }
|
||||||
|
: { refresh_token: refresh, target: site.deviceRefreshTarget }
|
||||||
|
return site.clientId && site.redirect ? { ...body, client_id: site.clientId, redirect_uri: site.redirect } : body
|
||||||
|
}
|
||||||
|
|
||||||
// refreshDevice trades the device refresh token for a new pair; it rotates
|
// refreshDevice trades the device refresh token for a new pair; it rotates
|
||||||
// too, so the caller saves it.
|
// too, so the caller saves it.
|
||||||
async function refreshDevice(site, refresh, chat = false) {
|
async function refreshDevice(site, refresh, chat = false, a = {}) {
|
||||||
if (!String(refresh ?? "").trim()) {
|
if (!String(refresh ?? "").trim()) {
|
||||||
if (chat) throw new SignInGone(`${site.name}: the sign-in lapsed; sign in again`)
|
if (chat) throw new SignInGone(`${site.name}: the sign-in lapsed; sign in again`)
|
||||||
throw new Error("qoder device token refresh: missing refresh token; sign in again")
|
throw new Error("qoder device token refresh: missing refresh token; sign in again")
|
||||||
}
|
}
|
||||||
let r
|
let r
|
||||||
try {
|
try {
|
||||||
r = await openapi(site, "/api/v1/deviceToken/refresh", { method: "POST", body: { refresh_token: refresh, ...(site.deviceRefreshTarget ? { target: site.deviceRefreshTarget } : {}) } })
|
r = await openapi(site, "/api/v1/deviceToken/refresh", { method: "POST", body: deviceRefreshBody(site, refresh, a) })
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw new Error(`qoder device token refresh: request failed: ${e?.message ?? e}`)
|
throw new Error(`qoder device token refresh: request failed: ${e?.message ?? e}`)
|
||||||
}
|
}
|
||||||
@@ -2780,6 +2807,47 @@ const parseAccountContext = (ctx, wallets) => {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// QWENWORK_APP is the QwenWork desktop release these calls name, as
|
||||||
|
// QwenWorkCN.app 1.2.1's package.json has it (version, and
|
||||||
|
// qoderworkUpgradeVersion for the release and its build).
|
||||||
|
const QWENWORK_APP = { version: "1.2.1", release: "1.2.1-26092107" }
|
||||||
|
|
||||||
|
// qwenworkClientHeaders are the names QwenWork's own client puts on every
|
||||||
|
// gateway call it makes outside a chat (openApiJsonRequest: buildUserAgent,
|
||||||
|
// a fresh X-Request-Id and getQwenWorkClientHeaders): the sign-in poll, the
|
||||||
|
// account-context, the device token's refresh. Without them every such
|
||||||
|
// call went out as no client at all.
|
||||||
|
const qwenworkClientHeaders = () => ({
|
||||||
|
"User-Agent": `qoderwork/${QWENWORK_APP.version}`,
|
||||||
|
"X-Request-Id": randomUUID(),
|
||||||
|
"X-QwenWork-Version": QWENWORK_APP.version,
|
||||||
|
"X-QwenWork-Release-Version": QWENWORK_APP.release,
|
||||||
|
"X-QwenWork-Build": QWENWORK_APP.release.split("-")[1],
|
||||||
|
"X-QwenWork-Platform": process.platform,
|
||||||
|
"X-QwenWork-Arch": process.arch,
|
||||||
|
"X-QwenWork-Channel": "stable",
|
||||||
|
})
|
||||||
|
|
||||||
|
// accountIdentity is the identity QwenWork's client reads off the
|
||||||
|
// account-context (fetchUserInfo over normalizeAccountContext: the
|
||||||
|
// envelope's data with data.user spread over it; getIdentityFromUser): a
|
||||||
|
// biz account names its team, which the device token's refresh is asked
|
||||||
|
// for; anything else is the personal "c" identity, and gives nothing.
|
||||||
|
function accountIdentity(v) {
|
||||||
|
const e = v?.data ?? v
|
||||||
|
if (!e || typeof e !== "object") return {}
|
||||||
|
const u = e.user && typeof e.user === "object" && !Array.isArray(e.user) ? { ...e, ...e.user } : e
|
||||||
|
const str = (o, keys) => {
|
||||||
|
for (const k of keys) if (typeof o?.[k] === "string" && o[k].length > 0) return o[k]
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
const org = u.organization && typeof u.organization === "object" ? u.organization : null
|
||||||
|
const isBiz = typeof u.is_biz === "boolean" ? u.is_biz : u.isBiz === true
|
||||||
|
const orgId = str(u, ["orgId", "organization_id", "organizationId"]) ?? str(org, ["org_id", "orgId", "id"])
|
||||||
|
const teamId = str(u, ["team_id", "teamId"]) ?? str(org, ["team_id", "teamId"])
|
||||||
|
return isBiz && orgId && teamId ? { identity: "biz", teamId } : {}
|
||||||
|
}
|
||||||
|
|
||||||
const QWENWORK_COMMON = {
|
const QWENWORK_COMMON = {
|
||||||
clientId: "e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb", // the desktop client's
|
clientId: "e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb", // the desktop client's
|
||||||
rsaKey: QWENWORK_RSA_KEY,
|
rsaKey: QWENWORK_RSA_KEY,
|
||||||
@@ -2789,6 +2857,7 @@ const QWENWORK_COMMON = {
|
|||||||
redirect: "qwenwork-cn://",
|
redirect: "qwenwork-cn://",
|
||||||
deviceOnly: true, // the device token is itself the chat token
|
deviceOnly: true, // the device token is itself the chat token
|
||||||
deviceRefreshTarget: "c",
|
deviceRefreshTarget: "c",
|
||||||
|
clientHeaders: qwenworkClientHeaders,
|
||||||
modelScene: "qwork", listAllModels: true,
|
modelScene: "qwork", listAllModels: true,
|
||||||
clientType: "6", businessProduct: "qoder_work", sessionType: "qoder_work",
|
clientType: "6", businessProduct: "qoder_work", sessionType: "qoder_work",
|
||||||
userInfoPath: "/api/v1/adapter/user/account-context?include=user,plan,quota,page,data_sharing",
|
userInfoPath: "/api/v1/adapter/user/account-context?include=user,plan,quota,page,data_sharing",
|
||||||
@@ -2942,7 +3011,7 @@ const makePlugin = (site) => async ({ client }) => {
|
|||||||
if (a.deviceChat) {
|
if (a.deviceChat) {
|
||||||
// the device token is the chat token: renewed as a device token,
|
// the device token is the chat token: renewed as a device token,
|
||||||
// both pairs being the one pair
|
// both pairs being the one pair
|
||||||
const dt = await refreshDevice(s, a.refresh, true)
|
const dt = await refreshDevice(s, a.refresh, true, a)
|
||||||
return spend(a.refresh, { access: dt.token, refresh: dt.refresh, expires: dt.expires, deviceToken: dt.token, deviceRefresh: dt.refresh })
|
return spend(a.refresh, { access: dt.token, refresh: dt.refresh, expires: dt.expires, deviceToken: dt.token, deviceRefresh: dt.refresh })
|
||||||
}
|
}
|
||||||
let jt
|
let jt
|
||||||
@@ -3053,7 +3122,7 @@ const makePlugin = (site) => async ({ client }) => {
|
|||||||
locked(async () => {
|
locked(async () => {
|
||||||
const a = latest(await getAuth())
|
const a = latest(await getAuth())
|
||||||
if (a?.deviceToken !== attempted) return a?.deviceToken
|
if (a?.deviceToken !== attempted) return a?.deviceToken
|
||||||
const dt = await refreshDevice(siteOf(site, a), a.deviceRefresh, !!a.deviceChat)
|
const dt = await refreshDevice(siteOf(site, a), a.deviceRefresh, !!a.deviceChat, a)
|
||||||
const next = { ...a, deviceToken: dt.token, deviceRefresh: dt.refresh }
|
const next = { ...a, deviceToken: dt.token, deviceRefresh: dt.refresh }
|
||||||
// the pair it spent was the chat pair too
|
// the pair it spent was the chat pair too
|
||||||
if (a.deviceChat) Object.assign(next, spend(a.refresh, { access: dt.token, refresh: dt.refresh, expires: dt.expires, deviceToken: dt.token, deviceRefresh: dt.refresh }))
|
if (a.deviceChat) Object.assign(next, spend(a.refresh, { access: dt.token, refresh: dt.refresh, expires: dt.expires, deviceToken: dt.token, deviceRefresh: dt.refresh }))
|
||||||
@@ -3101,7 +3170,7 @@ const makePlugin = (site) => async ({ client }) => {
|
|||||||
const read = async (token, path = site.usagePath) => {
|
const read = async (token, path = site.usagePath) => {
|
||||||
const s = siteOf(site, cred)
|
const s = siteOf(site, cred)
|
||||||
const res = await fetch(`${s.openapi}${path}`, {
|
const res = await fetch(`${s.openapi}${path}`, {
|
||||||
headers: { Accept: "application/json", Authorization: `Bearer ${token}` },
|
headers: { Accept: "application/json", ...(s.clientHeaders?.() ?? {}), Authorization: `Bearer ${token}` },
|
||||||
signal: AbortSignal.timeout(20_000),
|
signal: AbortSignal.timeout(20_000),
|
||||||
})
|
})
|
||||||
if (res.status !== 200) throw new UsageStatus(res.status)
|
if (res.status !== 200) throw new UsageStatus(res.status)
|
||||||
@@ -3753,4 +3822,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) {
|
|||||||
export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
|
export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
|
||||||
|
|
||||||
// for tests
|
// for tests
|
||||||
export const _internal = { freeView, maskPhone, phoneLabelOf, realEmailOf, chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, dedicatedOrigin, dedicatedHost, dedicatedSite, lingmaRoots, lingmaDecode, lingmaSite, lingmaHeaders, LINGMA_MODELS, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState }
|
export const _internal = { fetchListing, accountIdentity, deviceRefreshBody, qwenworkClientHeaders, freeView, maskPhone, phoneLabelOf, realEmailOf, chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, dedicatedOrigin, dedicatedHost, dedicatedSite, lingmaRoots, lingmaDecode, lingmaSite, lingmaHeaders, LINGMA_MODELS, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState }
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@magpie-community/opencode-qoder-auth",
|
"name": "@magpie-community/opencode-qoder-auth",
|
||||||
"version": "0.2.56",
|
"version": "0.2.57",
|
||||||
"description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship, VPC and dedicated domains",
|
"description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship, VPC and dedicated domains",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./index.mjs",
|
"main": "./index.mjs",
|
||||||
|
|||||||
@@ -412,3 +412,120 @@ test("the enterprise flagship and a biz account never read the wallets (#385)",
|
|||||||
restore()
|
restore()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// tnt1223 on Discord: QwenWork's model list answered 403 "User identity
|
||||||
|
// could not be verified". What QwenWorkCN.app 1.2.1 does that the plugin
|
||||||
|
// didn't: it names itself on every gateway call (openApiJsonRequest), and
|
||||||
|
// refreshes a biz account's device token for its own team (refreshDeviceToken).
|
||||||
|
test("every QwenWork gateway call names the client, as QwenWork's own does (tnt1223)", async () => {
|
||||||
|
const { pub } = await load()
|
||||||
|
const flow = await pub.auth.methods[0].authorize()
|
||||||
|
const restore = mock()
|
||||||
|
answer = async (url) => {
|
||||||
|
if (url.includes("/api/v1/deviceToken/poll")) return new Response(JSON.stringify({ token: "dt", refresh_token: "dtr", user_id: "u1" }), { status: 200 })
|
||||||
|
if (url.includes("/api/v1/adapter/user/account-context")) return new Response(JSON.stringify({ data: { user: { id: "u1", email: "a@b.cn" }, plan: { name: "Free" }, quota: { total: 100, remaining: 60 } } }), { status: 200 })
|
||||||
|
if (url.includes("/api/v1/deviceToken/refresh")) return new Response(JSON.stringify({ token: "dt2", refresh_token: "dtr2", expires_in: 3600 }), { status: 200 })
|
||||||
|
return new Response("{}", { status: 404 })
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const acct = await flow.callback()
|
||||||
|
await pub.auth.usage(async () => ({ ...acct, type: "oauth", expires: Date.now() - 1_000 }))
|
||||||
|
const calls = seen.filter((r) => r.url.startsWith("https://gateway.qwenwork.cn/api/v1/"))
|
||||||
|
expect(calls.some((r) => r.url.includes("/deviceToken/poll"))).toBe(true)
|
||||||
|
expect(calls.some((r) => r.url.includes("/deviceToken/refresh"))).toBe(true)
|
||||||
|
expect(calls.some((r) => r.url.includes("/account-context"))).toBe(true)
|
||||||
|
for (const r of calls) {
|
||||||
|
expect(r.headers["User-Agent"]).toBe("qoderwork/1.2.1")
|
||||||
|
expect(r.headers["X-QwenWork-Version"]).toBe("1.2.1")
|
||||||
|
expect(r.headers["X-QwenWork-Release-Version"]).toBe("1.2.1-26092107")
|
||||||
|
expect(r.headers["X-QwenWork-Build"]).toBe("26092107")
|
||||||
|
expect(r.headers["X-QwenWork-Platform"]).toBe(process.platform)
|
||||||
|
expect(r.headers["X-QwenWork-Arch"]).toBe(process.arch)
|
||||||
|
expect(r.headers["X-QwenWork-Channel"]).toBe("stable")
|
||||||
|
expect(r.headers["X-Request-Id"]).toMatch(/^[0-9a-f-]{36}$/)
|
||||||
|
}
|
||||||
|
// each call its own request id
|
||||||
|
expect(new Set(calls.map((r) => r.headers["X-Request-Id"])).size).toBe(calls.length)
|
||||||
|
} finally {
|
||||||
|
restore()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test("Qoder's own gateway calls don't take QwenWork's names", async () => {
|
||||||
|
const mod = await import("./index.mjs")
|
||||||
|
const restore = mock()
|
||||||
|
answer = async () => new Response("{}", { status: 200 })
|
||||||
|
try {
|
||||||
|
await mod.protocol.openapi(mod._internal.SITES.qoder, "/api/v1/userinfo", { token: "t" })
|
||||||
|
expect(Object.keys(seen[0].headers).some((k) => k.startsWith("X-QwenWork"))).toBe(false)
|
||||||
|
expect(seen[0].headers["User-Agent"]).toBeUndefined()
|
||||||
|
} finally {
|
||||||
|
restore()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test("a biz account is signed in as biz, and its device token refreshed for its own team (tnt1223)", async () => {
|
||||||
|
const { pub } = await load()
|
||||||
|
const flow = await pub.auth.methods[0].authorize()
|
||||||
|
const restore = mock()
|
||||||
|
const bodies = []
|
||||||
|
const saved = globalThis.fetch
|
||||||
|
globalThis.fetch = async (url, init) => {
|
||||||
|
seen.push({ url: String(url), headers: { ...(init?.headers ?? {}) } })
|
||||||
|
if (String(url).includes("/api/v1/deviceToken/refresh")) {
|
||||||
|
bodies.push(JSON.parse(String(init.body)))
|
||||||
|
return new Response(JSON.stringify({ token: "dt2", refresh_token: "dtr2", expires_in: 3600 }), { status: 200 })
|
||||||
|
}
|
||||||
|
if (String(url).includes("/api/v1/deviceToken/poll")) return new Response(JSON.stringify({ token: "dt", refresh_token: "dtr", user_id: "u1" }), { status: 200 })
|
||||||
|
// the shape fetchUserInfo reads: is_biz on the user, org and team on the organization
|
||||||
|
if (String(url).includes("/api/v1/adapter/user/account-context")) return new Response(JSON.stringify({ code: "200", data: { user: { id: "u1", email: "a@corp.cn", is_biz: true }, organization: { org_id: "o9", team_id: "t7" }, plan: { name: "Team" }, quota: { total: 100, remaining: 60 } } }), { status: 200 })
|
||||||
|
return new Response("{}", { status: 404 })
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const acct = await flow.callback()
|
||||||
|
expect(acct.identity).toBe("biz")
|
||||||
|
expect(acct.teamId).toBe("t7")
|
||||||
|
await pub.auth.usage(async () => ({ ...acct, type: "oauth", expires: Date.now() - 1_000 }))
|
||||||
|
expect(bodies.length).toBe(1)
|
||||||
|
expect(bodies[0]).toEqual({ refresh_token: "dtr", target: "biz", team_id: "t7", client_id: "e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb", redirect_uri: "qwenwork-cn://" })
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = saved
|
||||||
|
restore()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test("the identity is read as QwenWork's client reads it: biz only with both org and team", async () => {
|
||||||
|
const mod = await import("./index.mjs")
|
||||||
|
const { accountIdentity } = mod._internal
|
||||||
|
expect(accountIdentity({ data: { user: { id: "u", is_biz: true, team_id: "t" }, orgId: "o" } })).toEqual({ identity: "biz", teamId: "t" })
|
||||||
|
expect(accountIdentity({ data: { id: "u", isBiz: true, organization: { id: "o", teamId: "t" } } })).toEqual({ identity: "biz", teamId: "t" })
|
||||||
|
expect(accountIdentity({ data: { user: { id: "u", is_biz: true }, organization: { org_id: "o" } } })).toEqual({})
|
||||||
|
expect(accountIdentity({ data: { user: { id: "u", is_biz: false }, organization: { org_id: "o", team_id: "t" } } })).toEqual({})
|
||||||
|
expect(accountIdentity({ data: { user: { id: "u" } } })).toEqual({})
|
||||||
|
expect(accountIdentity(null)).toEqual({})
|
||||||
|
})
|
||||||
|
|
||||||
|
test("an enterprise account's refresh carries no redirect_uri, as its sign-in had none", async () => {
|
||||||
|
const mod = await import("./index.mjs")
|
||||||
|
const s = mod.protocol.siteOf(mod._internal.SITES["qwenwork-enterprise"], entCred())
|
||||||
|
expect(mod._internal.deviceRefreshBody(s, "r", entCred())).toEqual({ refresh_token: "r", target: "c" })
|
||||||
|
// and Qoder's sites ask with the token alone
|
||||||
|
expect(mod._internal.deviceRefreshBody(mod._internal.SITES["qoder-cn"], "r", {})).toEqual({ refresh_token: "r" })
|
||||||
|
})
|
||||||
|
|
||||||
|
test("the identity 403 on the model list says to sign in again (tnt1223)", async () => {
|
||||||
|
const mod = await import("./index.mjs")
|
||||||
|
const restore = mock()
|
||||||
|
// the reporter's bytes
|
||||||
|
answer = async () => new Response(`{"code":"403","message":"User identity could not be verified"}`, { status: 403 })
|
||||||
|
try {
|
||||||
|
const err = await mod._internal.fetchListing(mod._internal.SITES.qwenwork, entCred()).catch((e) => e)
|
||||||
|
expect(err.message).toBe(`QwenWork models: HTTP 403: {"code":"403","message":"User identity could not be verified"} — QwenWork didn't recognise this sign-in's identity; sign in to the account again`)
|
||||||
|
// another 403 is told as it was
|
||||||
|
answer = async () => new Response(`{"code":"403","message":"forbidden"}`, { status: 403 })
|
||||||
|
const other = await mod._internal.fetchListing(mod._internal.SITES.qwenwork, entCred()).catch((e) => e)
|
||||||
|
expect(other.message).toBe(`QwenWork models: HTTP 403: {"code":"403","message":"forbidden"}`)
|
||||||
|
} finally {
|
||||||
|
restore()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user