From 421cad6b2569ff3be00ef1de840043b067f10ab5 Mon Sep 17 00:00:00 2001 From: MYCF711 <1451895195@qq.com> Date: Thu, 29 Oct 2026 21:35:38 +0800 Subject: [PATCH] qoder 0.2.50: a phone account's card shows its phone, not its uuid (#487) A Qoder CN / QwenWork phone account's card shows its masked phone (phoneLabel / cardName, usage's `user`), a real email first, instead of its uuid; accountId stays exactly what main computes. A renewal reads the name outside the plugin-wide lock from the account's own site (a VPC token never goes to the public hosts) and renames nothing. Rebased on a06512e, keeping 3c279f6's listing-renew change. Reviewed at 6e39e8c (round 5). Run on mote (macOS, Bun 1.4.2) in a sandbox HOME, at that head: - bun test packages/qoder: 335 pass / 0 fail (listing-renew.test.mjs 5/0) - bun scripts/check.mjs qoder: ok Broken by hand: the device sign-in's cardName `realEmailOf(email) || label` -> `label` (index.mjs:411) turns "qoder-cn: a device sign-in with an email and a phone shows the email" red (334/1). Earlier rounds' breaks (renewal cardName, own site, usage `who`) were red too. CI (test, on-npm) green at 6e39e8c. Version 0.2.49 -> 0.2.50. Not tried: a real Qoder CN or QwenWork phone account. --- packages/qoder/README.md | 19 +++++ packages/qoder/cn.test.mjs | 40 +++++++++ packages/qoder/index.mjs | 122 +++++++++++++++++++++++++--- packages/qoder/package.json | 24 +++++- packages/qoder/pat.test.mjs | 46 ++++++++++- packages/qoder/phone-label.test.mjs | 37 +++++++++ packages/qoder/refresh.test.mjs | 13 ++- packages/qoder/usage.test.mjs | 14 ++++ packages/qoder/vpc.test.mjs | 65 +++++++++++++++ 9 files changed, 362 insertions(+), 18 deletions(-) create mode 100644 packages/qoder/phone-label.test.mjs diff --git a/packages/qoder/README.md b/packages/qoder/README.md index 55e605f..a66382e 100644 --- a/packages/qoder/README.md +++ b/packages/qoder/README.md @@ -302,6 +302,25 @@ paths, client id and protocol are the public ones: The hosts and reply shapes come from a real VPC account's report (yetone/magpie#312). This plugin has not been tried with a VPC account. +## The card's name + +An account signed in with a phone is shown by that phone — masked, `138****8000` — not by +its `accountId`, which is a uuid. Qoder CN's user info answers the number as `security_mobile` +(measured `13800138000`), so that is what the card takes. + +QwenWork's phone accounts answer only the last four digits, as `name`, beside a synthetic +`phone_@phone.local` email (measured): the card shows `****8000` and never that email. +An email sign-in keeps its email. + +`accountId` stays the account's identity — what magpie keys the user's own name for +it, its proxy, model picks, caps and a gateway key's account list by — so it never +changes: it is what a sign-in and every renewal give back. The card's name is usage's +`user`, a field magpie shows and never keys by. + +A sign-in reads the user info, and a renewal reads it again (outside the token lock), +so an account stored by an earlier version shows the phone on the card at its next +renewal. A failed read changes nothing and never costs a sign-in. + ## QwenWork (千问办公) `QwenWork` and `QwenWork 企业版` serve Alibaba's own QwenWork (qwenwork.cn) diff --git a/packages/qoder/cn.test.mjs b/packages/qoder/cn.test.mjs index 0123e75..2cd8534 100644 --- a/packages/qoder/cn.test.mjs +++ b/packages/qoder/cn.test.mjs @@ -301,3 +301,43 @@ test("the config declares qoder-cn on its gateway, with the tiers Qoder CN's CLI expect(cfg.provider.qoder.api).toBe("https://api3.qoder.sh") expect(Object.keys(cfg.provider.qoder.models)).toContain("qmodel") }) + +test("qoder-cn: a device sign-in names the card by the phone (review #487, E)", async () => { + toServer() + let polls = 0 + route = (at) => { + if (at === OPENAPI + "/api/v1/deviceToken/poll") + return ++polls < 2 ? new Response("", { status: 404 }) : json({ token: "dt-p", refresh_token: "drt-p", user_id: "u-p" }) + if (at === OPENAPI + "/api/v1/me/jobToken") return json({ token: "jt-p", refresh_token: "jrt-p", expires_in: 3_600_000 }) + if (at === OPENAPI + "/api/v1/userinfo") + return json({ id: "u-p", name: "dsh13800138000", security_mobile: "13800138000" }) + return new Response("", { status: 404 }) + } + const hooks = await QoderCNAuthPlugin({ client: store().client }) + const flow = await hooks.auth.methods[0].authorize() + const cred = await flow.callback() + // accountId stays main's computation (Qoder CN's uuid); the card's name is cardName + expect(cred.accountId).toBe("u-p") + expect(cred.phoneLabel).toBe("138****8000") + expect(cred.cardName).toBe("138****8000") +}) + +test("qoder-cn: a device sign-in with an email and a phone shows the email (review #487, round 5)", async () => { + toServer() + let polls = 0 + route = (at) => { + if (at === OPENAPI + "/api/v1/deviceToken/poll") + return ++polls < 2 ? new Response("", { status: 404 }) : json({ token: "dt-e", refresh_token: "drt-e", user_id: "u-e" }) + if (at === OPENAPI + "/api/v1/me/jobToken") return json({ token: "jt-e", refresh_token: "jrt-e", expires_in: 3_600_000 }) + if (at === OPENAPI + "/api/v1/userinfo") + return json({ id: "u-e", email: "bob@example.com", name: "Bob", security_mobile: "13800138000" }) + return new Response("", { status: 404 }) + } + const hooks = await QoderCNAuthPlugin({ client: store().client }) + const flow = await hooks.auth.methods[0].authorize() + const cred = await flow.callback() + // main names a device-only account by its email; the phone is the card's + expect(cred.accountId).toBe("bob@example.com") + expect(cred.cardName).toBe("bob@example.com") + expect(cred.phoneLabel).toBe("138****8000") +}) diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index 3a7e5cb..a48b2d8 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -375,10 +375,11 @@ async function deviceSignIn(site) { let email = "" let name = "" let uid = dt.user_id + let user = null try { const ui = await openapi(site, site.userInfoPath ?? "/api/v1/userinfo", { token: dt.token }) if (ui.status >= 200 && ui.status < 300) { - const user = site.normalizeUser ? site.normalizeUser(ui.json) : ui.json + user = site.normalizeUser ? site.normalizeUser(ui.json) : ui.json ;[email, name] = [user?.email ?? "", user?.name ?? ""] 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 @@ -393,7 +394,22 @@ async function deviceSignIn(site) { ...chat, // a VPC account is told apart from the same person's public one; a // device-only one is shown by name, falling back to its id - accountId: site.vpc ? `${email || uid} (${site.vpc})` : site.deviceOnly ? email || uid || name || dt.user_id : email || dt.user_id, + // accountId is the account's identity in magpie (its name, proxy, + // model picks and caps all hang off it, and a gateway key keys its + // list by it), so it stays exactly what main computes: the phone is a + // separate field, shown by usage's `user`, never the identity. + accountId: site.vpc + ? `${email || uid} (${site.vpc})` + : site.deviceOnly + ? email || uid || name || dt.user_id + : email || dt.user_id, + // the card's names: the phone on its own, and what magpie shows (a + // real email first, then the phone) — never the accountId + ...(() => { + const label = phoneLabelOf(user, email, name) + const suffix = (v) => (v ? (site.vpc ? `${v} (${site.vpc})` : v) : "") + return { phoneLabel: suffix(label), cardName: suffix(realEmailOf(email) || label) } + })(), uid, email, name: name || dt.user_name || "", @@ -430,9 +446,11 @@ async function patSignIn(site, pat) { let email = "" let name = "" let uid = "" + let user = null try { const ui = await openapi(site, "/api/v1/userinfo", { token }) if (ui.status >= 200 && ui.status < 300) { + user = ui.json ;[email, name] = [ui.json?.email ?? "", ui.json?.name ?? ""] uid = String(ui.json?.id ?? ui.json?.user_id ?? ui.json?.uid ?? "") } @@ -446,6 +464,8 @@ async function patSignIn(site, pat) { // so a renewed PAT sign-in must keep naming the same account. A suffix // here would add a second row beside the lapsed one instead. accountId: email || uid, + phoneLabel: phoneLabelOf(user, email, name), + cardName: realEmailOf(email) || phoneLabelOf(user, email, name), uid, email, name: name || "", @@ -1864,6 +1884,70 @@ function signed(res, renewed) { return new Response(res.body, { status: res.status, statusText: res.statusText, headers }) } +// ---- the card's name ---------------------------------------------------------- +// +// The card's name is not `accountId` (a uuid is not a name, and accountId is +// the identity magpie keys settings by). Both phone +// sign-ins here carry the phone somewhere in their user info: Qoder CN answers +// `security_mobile` (measured `13800138000`), QwenWork's phone accounts answer +// only the last four digits as `name` plus a synthetic +// `phone_@phone.local` email (measured). +const PHONE_EMAIL = /^phone_[0-9a-f-]+@phone\.local$/i + +/** A phone number as the cards show it: `0086-…`/`+86 …`/bare → `138****8000`. */ +function maskPhone(raw) { + let digits = String(raw ?? "").replace(/\D/g, "") + if (digits.startsWith("0086") && digits.length - 4 >= 7) digits = digits.slice(4) + else if (digits.startsWith("86") && digits.length - 2 >= 7) digits = digits.slice(2) + // a phone is 11 digits; a shorter run is not a number to mask + if (digits.length < 11) return "" + return `${digits.slice(0, 3)}****${digits.slice(-4)}` +} + +/** + * What a renewal puts on the record for the card: `phoneLabel` (the phone the + * account signs in with, `138****8000` / `****8000`) and `cardName` (a real + * email first, then the phone) — both with the VPC suffix. It renames nothing: + * `accountId` is the identity and never changes. + * + * Read from the renewed token's user info. No cache: each renewal has a new + * token, so nothing is read twice (review #487, 6). + */ +async function refreshedNames(site, token) { + const key = String(token ?? "") + if (!key) return {} + try { + const ui = await openapi(site, site.userInfoPath ?? "/api/v1/userinfo", { token: key }) + if (ui.status < 200 || ui.status >= 300) return {} + const user = site.normalizeUser ? site.normalizeUser(ui.json) : ui.json + const label = phoneLabelOf(user, user?.email, user?.name) + const suffix = (v) => (v ? (site.vpc ? `${v} (${site.vpc})` : v) : "") + // built as the sign-in builds it: a real email first, then the phone + return { phoneLabel: suffix(label), cardName: suffix(realEmailOf(user?.email) || label) } + } catch { + return {} + } +} + +/** The account's own email, when it is a real one (a synthetic phone email is not). */ +function realEmailOf(email) { + const e = String(email ?? "").trim() + if (!e || PHONE_EMAIL.test(e)) return "" + return e +} + +/** The phone-derived part of a card's name, or "" when the account has none. */ +function phoneLabelOf(user, email, name) { + const phone = maskPhone(user?.security_mobile ?? user?.phoneNumber ?? user?.phone ?? user?.mobile) + if (phone) return phone + // a synthetic phone email is never shown: its four digits are, or nothing + if (PHONE_EMAIL.test(String(email ?? ""))) { + const tail = String(name ?? "").trim() + if (/^\d{4}$/.test(tail)) return `****${tail}` + } + return "" +} + // changed is the fields of b that differ from a's: what auth.refresh gives. function changed(a, b) { const out = {} @@ -2605,6 +2689,8 @@ const makePlugin = (site) => async ({ client }) => { try { const cred = await fresh(getAuth) if (renewed(cred)) signIn = "renewed" + // the card's name: magpie takes usage's `user` for it and never as a key + const who = cred?.cardName ? { user: cred.cardName } : {} // a site with its own usage path (QwenWork's account-context, signed // like any other call and answered with its own envelope) is read // there; a 401 rotates the device token once, as the qoder path does @@ -2635,7 +2721,7 @@ const makePlugin = (site) => async ({ client }) => { if (site.walletsPath && ctxUser?.is_biz !== true && ctxUser?.isBiz !== true) { try { wallets = await read(token, site.walletsPath) } catch {} } - return { ...(site.parseUsage ? site.parseUsage(env, wallets) : { windows: [] }), signIn } + return { ...(site.parseUsage ? site.parseUsage(env, wallets) : { windows: [] }), signIn, ...who } } // A PAT account has no device token: the usage endpoint takes the job // token the exchange gave — a live PAT account answered 200 with a @@ -2643,7 +2729,7 @@ const makePlugin = (site) => async ({ client }) => { // no second token here to rotate and retry with. if (cred.patAuth && !cred.deviceToken) { const env = await fetchUsage(siteOf(site, cred), cred.access) - return { ...(await spareFree(cred, parseUsage(env))), signIn } + return { ...(await spareFree(cred, parseUsage(env))), signIn, ...who } } let env try { @@ -2652,7 +2738,7 @@ const makePlugin = (site) => async ({ client }) => { if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e env = await fetchUsage(siteOf(site, cred), await deviceToken(getAuth, cred.deviceToken)) } - return { ...(await spareFree(cred, parseUsage(env))), signIn } + return { ...(await spareFree(cred, parseUsage(env))), signIn, ...who } } catch (e) { return { error: e?.message ?? String(e), signIn: e?.expired ? "expired" : signIn } } @@ -2904,19 +2990,35 @@ const makePlugin = (site) => async ({ client }) => { refreshLead: RENEW_LEAD, async refresh(auth) { if (auth?.type !== "oauth" || !auth.access || !auth.uid || !String(auth.refresh ?? "").trim()) return undefined - return locked(async () => { + const out = await locked(async () => { // a request renewed it meanwhile (or magpie hasn't saved this // hook's last answer): what that gave, not a second refresh const a = latest(auth) - if (a.access !== auth.access && a.expires - Date.now() > RENEW_LEAD) return changed(auth, a) + if (a.access !== auth.access && a.expires - Date.now() > RENEW_LEAD) return { next: a, renewed: false } try { - // magpie saves what this gives - return changed(auth, { ...a, ...(await renew(a)) }) + return { next: { ...a, ...(await renew(a)) }, renewed: true } } catch (e) { if (e?.expired) throw Object.assign(new Error(e.message), { signIn: "expired" }) throw e } }) + const fields = changed(auth, out.next) + if (!out.renewed) return fields + // The name is read outside the lock: this lock is the plugin's, shared + // by every account, and a user-info call may take 20 seconds — a chat + // from another account must not wait on it (review #487, C). The + // account's own site, too: a public one would send an enterprise token + // to the public hosts (1), and the suffix must match the sign-in (2). + try { + const s = siteOf(site, out.next) + const { phoneLabel, cardName } = await refreshedNames(s, out.next.access) + const extra = {} + if (phoneLabel) extra.phoneLabel = phoneLabel + if (cardName) extra.cardName = cardName + return Object.keys(extra).length ? { ...fields, ...extra } : fields + } catch { + return fields + } }, async loader(getAuth) { const a = await getAuth() @@ -3125,4 +3227,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) { export const protocol = { makePlugin, deviceSignIn, openapi, siteOf } // for tests -export const _internal = { chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, 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 = { maskPhone, phoneLabelOf, realEmailOf, chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState } diff --git a/packages/qoder/package.json b/packages/qoder/package.json index bb62747..0f85748 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,12 +1,28 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.2.49", + "version": "0.2.50", "description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship (VPC)", "type": "module", "main": "./index.mjs", "exports": "./index.mjs", - "files": ["index.mjs", "README.md", "LICENSE-CLIProxyAPI"], - "keywords": ["opencode", "opencode-plugin", "magpie", "qoder", "qoder-cn", "qwenwork", "千问办公"], + "files": [ + "index.mjs", + "README.md", + "LICENSE-CLIProxyAPI" + ], + "keywords": [ + "opencode", + "opencode-plugin", + "magpie", + "qoder", + "qoder-cn", + "qwenwork", + "千问办公" + ], "license": "MIT", - "repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/qoder" } + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/qoder" + } } diff --git a/packages/qoder/pat.test.mjs b/packages/qoder/pat.test.mjs index e804362..dd1379d 100644 --- a/packages/qoder/pat.test.mjs +++ b/packages/qoder/pat.test.mjs @@ -91,7 +91,9 @@ test("qoder-cn: a PAT account keeps the name its browser sign-in takes", async ( // no suffix: magpie's host replaces an account on a new sign-in when both // the accountId and the uid match, so a re-signed PAT must name the same - // account the browser sign-in does, not a row of its own beside it + // account the browser sign-in does, not a row of its own beside it. + // This account has neither a phone nor an email: both paths keep naming it + // by its uid, as they did before the phone label (review #487, 5). expect(res.accountId).toBe("same-user") expect(res.uid).toBe("same-user") expect(res.email).toBe("") @@ -324,3 +326,45 @@ test("qoder: a refused PAT re-exchange ends the sign-in", async () => { expect(res.status).toBe(401) expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") }) + +test("qoder-cn: a non-phone account keeps one name through sign-in, renewal and sign-in again (review #487, A)", async () => { + globalThis.fetch = async (url) => { + const u = new URL(String(url)) + if (u.pathname === "/api/v1/jobToken/exchange") return json({ token: "jt-1", refresh_token: "jrt-1", expires_in: 86400000 }) + if (u.pathname === "/api/v1/jobToken/refresh") return json({ token: "jt-2", refresh_token: "jrt-2", expires_in: 86400000 }) + if (u.pathname === "/api/v1/userinfo") return json({ id: "same-user", name: "Someone" }) + return new Response("", { status: 500 }) + } + const hooks = await QoderCNAuthPlugin({ client: { auth: { set: async () => {} } } }) + const pat = hooks.auth.methods.find((m) => m.label?.includes("PAT")) + const first = await pat.authorize({ pat: "pt-x" }).callback() + expect(first.accountId).toBe("same-user") + // a renewal must not rename it: no phone, so the name the sign-in gave stays + const renewed = await hooks.auth.refresh({ ...first, type: "oauth", expires: Date.now() + 1_000 }) + expect(renewed.accountId).toBeUndefined() + // No phone and no email: a renewal renames nothing and gives no cardName + expect(renewed.cardName).toBeUndefined() + const again = await pat.authorize({ pat: "pt-x" }).callback() + expect(again.accountId).toBe("same-user") +}) + +test("qoder-cn: an email account with a phone bound keeps its email, here and on renewal (review #487, B)", async () => { + globalThis.fetch = async (url) => { + const u = new URL(String(url)) + if (u.pathname === "/api/v1/jobToken/exchange") return json({ token: "jt-e", refresh_token: "jrt-e", expires_in: 86400000 }) + if (u.pathname === "/api/v1/jobToken/refresh") return json({ token: "jt-e2", refresh_token: "jrt-e2", expires_in: 86400000 }) + if (u.pathname === "/api/v1/userinfo") + return json({ id: "u-e", email: "bob@example.com", security_mobile: "13800138000" }) + return new Response("", { status: 500 }) + } + const hooks = await QoderCNAuthPlugin({ client: { auth: { set: async () => {} } } }) + const pat = hooks.auth.methods.find((m) => m.label?.includes("PAT")) + const first = await pat.authorize({ pat: "pt-e" }).callback() + expect(first.accountId).toBe("bob@example.com") + expect(first.cardName).toBe("bob@example.com") + const renewed = await hooks.auth.refresh({ ...first, type: "oauth", expires: Date.now() + 1_000 }) + expect(renewed.accountId).toBeUndefined() + // The card's name stays the email too: a renewal must not swap it for the phone + expect(renewed.cardName).toBe("bob@example.com") + expect(renewed.phoneLabel).toBe("138****8000") +}) diff --git a/packages/qoder/phone-label.test.mjs b/packages/qoder/phone-label.test.mjs new file mode 100644 index 0000000..3324a6e --- /dev/null +++ b/packages/qoder/phone-label.test.mjs @@ -0,0 +1,37 @@ +// The card's name: what a phone sign-in shows, and the uuid it used to show. +// +// Both sites answer a phone account differently — Qoder CN gives the full +// number as `security_mobile`, QwenWork gives four digits as `name` beside a +// synthetic `phone_@phone.local` email — and the card used to show a +// uuid for either. These lock the label, not the sign-in. + +import { expect, test } from "bun:test" +import { _internal as x } from "./index.mjs" + +test("maskPhone: 0086- / +86 / bare / already masked, always 3+4", () => { + expect(x.maskPhone("0086-13800138000")).toBe("138****8000") + expect(x.maskPhone("+86 138 0013 8000")).toBe("138****8000") + expect(x.maskPhone("13800138000")).toBe("138****8000") + // already masked → fewer than 11 digits → not a number to mask again + expect(x.maskPhone("139****1234")).toBe("") + // not a number → empty, so the label falls through to the next candidate + expect(x.maskPhone("")).toBe("") + expect(x.maskPhone(undefined)).toBe("") + expect(x.maskPhone("123")).toBe("") + // a number that merely starts with 86 is not a country code either + expect(x.maskPhone("86123456789")).toBe("") +}) + +test("phoneLabelOf: the phone, or a synthetic email's four digits, else nothing", () => { + expect(x.phoneLabelOf({ security_mobile: "13800138000" }, "", "")).toBe("138****8000") + const synthetic = "phone_66666666-7777-8888-9999-000000000000@phone.local" + expect(x.phoneLabelOf({ name: "8000", email: synthetic }, synthetic, "8000")).toBe("****8000") + expect(x.phoneLabelOf({ id: "u1" }, "", "")).toBe("") +}) + +test("realEmailOf: a real email, never a synthetic phone one", () => { + expect(x.realEmailOf("someone@example.com")).toBe("someone@example.com") + expect(x.realEmailOf("phone_66666666-7777-8888-9999-000000000000@phone.local")).toBe("") + expect(x.realEmailOf("")).toBe("") + expect(x.realEmailOf(undefined)).toBe("") +}) diff --git a/packages/qoder/refresh.test.mjs b/packages/qoder/refresh.test.mjs index 03b9240..c696296 100644 --- a/packages/qoder/refresh.test.mjs +++ b/packages/qoder/refresh.test.mjs @@ -38,6 +38,9 @@ function serve(site, { job, device } = {}) { if (u.host === site.openapi && u.pathname === "/api/v1/jobToken/refresh") return job ? job(token) : json({ token: "jt-2", refresh_token: "jrt-2", expires_in: 3_600_000 }) if (u.host === site.openapi && u.pathname === "/api/v1/deviceToken/refresh") return device ? device(token) : json({ device_token: "dt-2", refresh_token: "drt-2", expires_at: new Date(Date.now() + 7_200_000).toISOString() }) + // the card's name: a renewal reads the user info once (the phone it shows) + if (u.host === site.openapi && u.pathname === "/api/v1/userinfo") + return json({ id: "u1", name: "one@x", security_mobile: "13800138000" }) return new Response("", { status: 500 }) } return calls @@ -58,10 +61,13 @@ for (const site of SITES) { expect(hooks.auth.refreshLead).toBe(10 * 60 * 1000) const got = await hooks.auth.refresh(account(), { id: site.name }) expect(got).toMatchObject({ access: "jt-2", refresh: "jrt-2" }) - expect(Object.keys(got).sort()).toEqual(["access", "expires", "refresh"]) + // the renewal also names the account (the phone, not its uuid), so an + // account stored by an earlier version is renamed here + expect(Object.keys(got).sort()).toEqual(["access", "cardName", "expires", "phoneLabel", "refresh"]) + expect(got.phoneLabel).toBe("138****8000") expect(got.expires).toBeGreaterThan(Date.now() + 3_000_000) expect(sets).toEqual([]) - expect(calls).toEqual([`${site.openapi}/api/v1/jobToken/refresh jrt-1`]) + expect(calls.filter((c) => c.includes("Token/refresh"))).toEqual([`${site.openapi}/api/v1/jobToken/refresh jrt-1`]) }) test(`${site.name}: auth.refresh and a request's refresh spend the refresh token once`, async () => { @@ -129,7 +135,8 @@ test("qoder-cn: a device-token account is renewed as a device token, both pairs expect(got.expires).toBeGreaterThan(Date.now() + 7_000_000) expect(got.type).toBeUndefined() expect(sets).toEqual([]) - expect(calls).toEqual([`${site.openapi}/api/v1/deviceToken/refresh drt-1`]) + // a device-token renewal also reads the user info once, for the card's name + expect(calls.filter((c) => c.includes("Token/refresh"))).toEqual([`${site.openapi}/api/v1/deviceToken/refresh drt-1`]) serve(site, { device: () => new Response("", { status: 401 }) }) const p = await plugin(site, a) diff --git a/packages/qoder/usage.test.mjs b/packages/qoder/usage.test.mjs index 71c5b42..e426ec3 100644 --- a/packages/qoder/usage.test.mjs +++ b/packages/qoder/usage.test.mjs @@ -564,3 +564,17 @@ test("a free account with no credits shows none left, not nothing", () => { expect(_internal.parseUsage({ displayMode: "qoder", qoderUsage: { userType: "personal_standard", userQuota: { total: "0" } } }).windows).toEqual([]) expect(_internal.parseUsage({ displayMode: "qoder", qoderUsage: { userType: "personal_standard" } }).windows).toEqual([]) }) + +test("usage's user is the card's name, and the accountId stays the identity (review #487, round 3)", async () => { + let auth = { ...account(), accountId: "one@x", cardName: "138****8000", phoneLabel: "138****8000" } + globalThis.fetch = async (url) => { + const u = new URL(String(url)) + if (u.pathname === "/sash/api/v2/me/usage") return json(USAGE) + if (u.pathname === "/api/v1/deviceToken/refresh") return json({ token: "dt-new", refresh_token: "drt-new" }) + return new Response("", { status: 404 }) + } + const hooks = await QoderAuthPlugin({ client: { auth: { set: async ({ body }) => (auth = body) } } }) + const u = await hooks.auth.usage(async () => auth) + expect(u.user).toBe("138****8000") + expect(auth.accountId).toBe("one@x") +}) diff --git a/packages/qoder/vpc.test.mjs b/packages/qoder/vpc.test.mjs index 9e50175..062cd2e 100644 --- a/packages/qoder/vpc.test.mjs +++ b/packages/qoder/vpc.test.mjs @@ -357,3 +357,68 @@ test("an account whose VPC instance on record isn't one is not sent to the publi expect((await hooks.auth.usage(s.get)).error).toContain("isn't one") expect(seen).toEqual([]) }) + +test("a VPC account's renewal asks its own instance for the name, and keeps the suffix (review #487)", async () => { + toServer() + const at = [] + route = (where, { req }) => { + at.push(where) + if (where === OPENAPI + "/api/v1/jobToken/refresh") + return json({ token: "jt-vpc-2", refresh_token: "jrt-vpc-2", expires_in: 86400000 }) + if (where === OPENAPI + "/api/v1/userinfo") { + expect(req.headers.get("authorization")).toBe("Bearer jt-vpc-2") + return json({ id: "u-vpc", name: "Alice", security_mobile: "13800138000" }) + } + return new Response("", { status: 404 }) + } + const hooks = await QoderCNAuthPlugin({ client: store().client }) + const got = await hooks.auth.refresh({ + type: "oauth", + access: "jt-vpc-1", + refresh: "jrt-vpc-1", + uid: "u-vpc", + vpc: "acme", + accountId: "alice@corp.example (acme)", + expires: Date.now() + 1_000, + }) + // accountId does not move (it is the identity); the phone lands on phoneLabel only + expect(got.accountId).toBeUndefined() + expect(got.phoneLabel).toBe("138****8000 (acme)") + // and no public host was touched: an enterprise token never goes there + expect(at.some((w) => w.startsWith(OPENAPI))).toBe(true) + expect(at.some((w) => w.startsWith("openapi.qoder.com.cn"))).toBe(false) + expect(at.some((w) => PUBLIC.some((p) => w.startsWith(p)))).toBe(false) +}) + +test("a hanging user-info read does not hold another account's chat (review #487, C)", async () => { + let release + const gate = new Promise((r) => { release = r }) + const real = globalThis.fetch + let userinfoReached = false + globalThis.fetch = async (url, init = {}) => { + const u = new URL(String(url)) + if (u.pathname === "/api/v1/userinfo") { userinfoReached = true; await gate; return json({ id: "u-a", name: "A" }) } + if (u.pathname === "/api/v1/jobToken/refresh") return json({ token: "jt-a2", refresh_token: "jrt-a2", expires_in: 86400000 }) + if (u.pathname.endsWith("/chat/completions")) return json({ id: "x", choices: [{ message: { content: "ok" } }] }) + return new Response("", { status: 404 }) + } + try { + const hooks = await QoderCNAuthPlugin({ client: { auth: { set: async () => {} } } }) + // account A renews: its token is swapped and the name read is hanging + const pending = hooks.auth.refresh({ type: "oauth", access: "jt-a1", refresh: "jrt-a1", uid: "u-a", expires: Date.now() + 1_000 }) + for (let i = 0; i < 50 && !userinfoReached; i++) await new Promise((r) => setTimeout(r, 10)) + expect(userinfoReached).toBe(true) + // account B's chat must not wait on it + const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "jt-b", refresh: "jrt-b", uid: "u-b", expires: Date.now() + 86_400_000 })) + const at = Date.now() + const res = await loader.fetch("https://api3.qoder.sh/v1/chat/completions", { method: "POST", body: JSON.stringify({ model: "q", messages: [] }) }) + // the point is that it did not wait: any status is fine, being held is not + expect(res).toBeInstanceOf(Response) + expect(Date.now() - at).toBeLessThan(1_000) + release() + await pending + } finally { + release() + globalThis.fetch = real + } +})