From ecca97cadd823cf659f79e1e04cdf6ed98324cbf Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 8 Oct 2026 10:30:17 +0800 Subject: [PATCH] qoder 0.2.8: Qoder CN enterprise VPC sign-in (yetone/magpie#312) (#41) A new method, Sign in with Qoder CN Enterprise (VPC), asks for the instance (its name or .vpc.qoder.com.cn) and serves the account from the instance's own hosts: .vpc.qoder.com.cn for the sign-in page, -openapi.vpc.qoder.com.cn for poll, tokens, user info and usage, and -gateway.vpc.qoder.com.cn for models and chat, the paths unchanged, as @qodercn-ai/qoderclicn 1.1.64 rewrites the public origins once a VPC instance is set. The instance is kept on the account; an account with none is served as before, and one with an instance that names none is asked to sign in again rather than sent to the public hosts. Not tried with a real VPC account. vpc.test.mjs builds its fixtures from AwadYoo's redacted shapes on #312; 12 of its 13 tests fail on 0.2.7 (the one that passes is the public sign-in staying as it was). bun test packages/qoder: 67 pass; HOME=$(mktemp -d) bun test: 864 pass; bun scripts/check.mjs: all pass. --- packages/qoder/README.md | 31 ++++ packages/qoder/index.mjs | 154 ++++++++++++++++-- packages/qoder/package.json | 2 +- packages/qoder/vpc.test.mjs | 311 ++++++++++++++++++++++++++++++++++++ 4 files changed, 482 insertions(+), 16 deletions(-) create mode 100644 packages/qoder/vpc.test.mjs diff --git a/packages/qoder/README.md b/packages/qoder/README.md index 26a9e79..86ca7fe 100644 --- a/packages/qoder/README.md +++ b/packages/qoder/README.md @@ -151,6 +151,37 @@ Neither magpie's built-in Qoder CN nor this plugin has been checked against every kind of qoder.cn account. If a sign-in or a chat fails, please open an issue with the error. +### Enterprise VPC + +A Qoder CN enterprise on its own VPC instance signs in with **Sign in with +Qoder CN Enterprise (VPC)** (since 0.2.8). It asks for the instance: its +name (`acme`) or one of its addresses (`acme.vpc.qoder.com.cn`, +`https://acme.vpc.qoder.com.cn`). Only https and hosts under +`vpc.qoder.com.cn` are taken. + +The account then uses the instance's own hosts, as Qoder CN's CLI +(`@qodercn-ai/qoderclicn` 1.1.64) does once a VPC instance is set. The +paths, client id and protocol are the public ones: + +| | Public Qoder CN | VPC instance `acme` | +|---|---|---| +| Sign-in page | qoder.cn | acme.vpc.qoder.com.cn | +| Accounts: poll, tokens, user info, usage | openapi.qoder.com.cn | acme-openapi.vpc.qoder.com.cn | +| Models and chat | gateway.qoder.com.cn | acme-gateway.vpc.qoder.com.cn | + +- The instance is kept with the account, so its refreshes, models, usage + and check-in go to the instance too. An account kept with an instance + that isn't one is asked to sign in again; it is never sent to the public + hosts. +- The account is named ` ()`, so it is listed apart from + the same person's public account. +- An enterprise's usage shows as the Enterprise plan. +- **Sign in with Qoder CN** is unchanged and still the first way. An + account signed in without an instance works as before. + +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. + ## Daily check-in Qoder gives credits for a daily claim (the Qoder client's campaign diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index 603e560..354456a 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -25,6 +25,15 @@ // gateway.qoder.com.cn, with the device-flow client id that CLI sends in // production and no redirect_uri. That CLI chats on the device token itself; // if qoder.cn won't trade it for a job token, the account does the same. +// +// A Qoder CN enterprise VPC account (yetone/magpie#312) is signed in to with +// its own method, which asks for the enterprise's instance name. Its calls go +// to the same paths on the instance's own hosts, as Qoder CN's CLI 1.1.64 +// rewrites them once a VPC instance is set: qoder.cn becomes +// .vpc.qoder.com.cn, openapi.qoder.com.cn becomes +// -openapi.vpc.qoder.com.cn, and gateway.qoder.com.cn becomes +// -gateway.vpc.qoder.com.cn. The instance is kept on the account, +// and an account with none is served as before. import { createCipheriv, createHash, publicEncrypt, randomBytes, randomUUID, constants } from "node:crypto" import { STATUS_CODES } from "node:http" @@ -180,6 +189,59 @@ function deviceExpiry(dt) { return Date.now() + DAY } +// ---- enterprise VPC (Qoder CN) -------------------------------------------------- + +const VPC_NAME = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/i + +// vpcInstance is the instance named by what the user entered, as Qoder CN's +// CLI reads its VPC endpoint: a bare name ("acme"), or one of the instance's +// hosts (acme.vpc.qoder.com.cn, acme-openapi.…, acme-gateway.…), here also as +// an https:// address with no path. Anything else (http://, an IP, another +// domain, a path or query) names none: undefined. +function vpcInstance(input, domain) { + let e = String(input ?? "").trim().toLowerCase() + if (!e || !domain) return undefined + if (/^[a-z][a-z\d+.-]*:\/\//.test(e)) { + let u + try { + u = new URL(e) + } catch { + return undefined + } + if (u.protocol !== "https:" || u.username || u.password || u.port || u.search || u.hash || (u.pathname !== "" && u.pathname !== "/")) return undefined + if (e.endsWith("/")) e = e.slice(0, -1) + if (u.hostname + "" !== e.slice("https://".length)) return undefined + e = u.hostname + } + if (/^\d{1,3}(\.\d{1,3}){3}$/.test(e)) return undefined + let name = e + if (e.endsWith("." + domain)) { + name = e.slice(0, e.length - domain.length - 1) + if (name.endsWith("-openapi") || name.endsWith("-gateway")) name = name.slice(0, -8) + } else if (e.includes(".")) return undefined + return VPC_NAME.test(name) ? name : undefined +} + +// vpcSite is site served from a VPC instance's own hosts, the paths +// unchanged; undefined when the site has no VPC or instance names none. +function vpcSite(site, instance) { + const name = vpcInstance(instance, site.vpcDomain) + if (!name) return undefined + const d = site.vpcDomain + return { ...site, web: `https://${name}.${d}`, openapi: `https://${name}-openapi.${d}`, api: `https://${name}-gateway.${d}`, vpc: name } +} + +// siteOf is the site an account is served from: its VPC instance's when it +// was signed in to one, else site. An instance on record that names none +// is not read as "no VPC", which would send the enterprise's tokens to the +// public hosts: the account has to be signed in to again. +function siteOf(site, a) { + if (a?.vpc === undefined || a?.vpc === null || a?.vpc === "") return site + const s = vpcSite(site, a.vpc) + if (!s) throw new SignInGone(`${site.name}: the account's VPC instance "${a.vpc}" isn't one; sign in again`) + return s +} + async function deviceSignIn(site) { const verifier = b64url(randomBytes(64)) const challenge = b64url(createHash("sha256").update(verifier).digest()) @@ -217,20 +279,29 @@ async function deviceSignIn(site) { } else throw new Error(`${site.name} job token: status ${jr.status}: ${jr.text.trim().slice(0, 300)}`) let email = "" let name = "" + let uid = dt.user_id try { const ui = await openapi(site, "/api/v1/userinfo", { token: dt.token }) - if (ui.status >= 200 && ui.status < 300) [email, name] = [ui.json?.email ?? "", ui.json?.name ?? ""] + if (ui.status >= 200 && ui.status < 300) { + ;[email, name] = [ui.json?.email ?? "", ui.json?.name ?? ""] + // a VPC poll may give the token alone: the user is then the one + // user info names (id, or its user_id / uid aliases) + if (site.vpc && !String(uid ?? "").trim()) uid = String(ui.json?.id ?? ui.json?.user_id ?? ui.json?.uid ?? "") || undefined + } } catch {} + if (site.vpc && !String(uid ?? "").trim()) throw new Error(`${site.name} (${site.vpc}): the sign-in named no user`) return { type: "success", ...chat, - accountId: email || dt.user_id, - uid: dt.user_id, + // a VPC account is told apart from the same person's public one + accountId: site.vpc ? `${email || uid} (${site.vpc})` : email || dt.user_id, + uid, email, name: name || dt.user_name || "", machineId, deviceToken: dt.token, deviceRefresh: dt.refresh_token ?? "", + ...(site.vpc ? { vpc: site.vpc } : {}), } }, } @@ -969,6 +1040,21 @@ function campaignPage(site, url) { } } +// campaignTarget is where a campaigns page url is asked for an account +// served from s: url itself on s's accounts host, or, on a VPC account, the +// same page on its instance when url names the public host (magpie's +// check-in knows only that), as Qoder CN's CLI rewrites it. null: url isn't +// one. +function campaignTarget(base, s, url) { + if (campaignPage(s, url)) return url + if (s === base || !campaignPage(base, url)) return null + const u = new URL(url) + const to = new URL(s.openapi) + u.protocol = to.protocol + u.host = to.host + return u.href +} + // campaignCall is url asked with the device token; Qoder's answer comes back // as it is. async function campaignCall(url, method, body, deviceToken, signal) { @@ -1080,13 +1166,15 @@ const SITES = { api: "https://gateway.qoder.com.cn", redirect: "", // Qoder CN's CLI sends none deviceChat: true, // a refused job token falls back to the CLI's device-token chat + // an enterprise's own instance, .vpc.qoder.com.cn and its + // -openapi and -gateway hosts, as Qoder CN's CLI builds it in + vpcDomain: "vpc.qoder.com.cn", models: CN_MODELS, }, } const makePlugin = (site) => async ({ client }) => { const ID = site.id - const CHAT_URL = site.api + CHAT_PATH // serializes checking, rotating and saving tokens: a refresh token is // spent once, so two refreshes would spend it twice let lock = Promise.resolve() @@ -1118,13 +1206,14 @@ const makePlugin = (site) => async ({ client }) => { // renew spends a's chat refresh token, under the lock: the fields it // changes, recorded in spent. const renew = async (a) => { + const s = siteOf(site, a) if (a.deviceChat) { // the device token is the chat token: renewed as a device token, // both pairs being the one pair - const dt = await refreshDevice(site, a.refresh, true) + const dt = await refreshDevice(s, a.refresh, true) return spend(a.refresh, { access: dt.token, refresh: dt.refresh, expires: dt.expires, deviceToken: dt.token, deviceRefresh: dt.refresh }) } - const jt = await refreshJob(site, a.refresh, a.accountId || a.email || a.uid) + const jt = await refreshJob(s, a.refresh, a.accountId || a.email || a.uid) return spend(a.refresh, { access: jt.token, refresh: jt.refresh_token, expires: expiresAt(jt) }) } // each account's listing, the model configs a request carries @@ -1147,6 +1236,7 @@ const makePlugin = (site) => async ({ client }) => { locked(async () => { const stored = await getAuth() if (stored?.type !== "oauth" || !stored.access || !stored.uid) throw new SignInGone(`${site.name}: not signed in`) + siteOf(site, stored) // a VPC instance on record that names none is no sign-in // renewed already (by magpie's auth.refresh), the store not yet saying so const a = latest(stored) if (a.expires - Date.now() > REFRESH_LEAD) return a @@ -1159,7 +1249,7 @@ const makePlugin = (site) => async ({ client }) => { const models = async (cred, again = false) => { let l = listings.get(cred.uid) if (!l || again) { - l = modelInfos(await fetchListing(site, cred)) + l = modelInfos(await fetchListing(siteOf(site, cred), cred)) listings.set(cred.uid, l) } return l @@ -1171,7 +1261,7 @@ const makePlugin = (site) => async ({ client }) => { locked(async () => { const a = latest(await getAuth()) if (a?.deviceToken !== attempted) return a?.deviceToken - const dt = await refreshDevice(site, a.deviceRefresh, !!a.deviceChat) + const dt = await refreshDevice(siteOf(site, a), a.deviceRefresh, !!a.deviceChat) const next = { ...a, deviceToken: dt.token, deviceRefresh: dt.refresh } // 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 })) @@ -1190,10 +1280,10 @@ const makePlugin = (site) => async ({ client }) => { if (renewed(cred)) signIn = "renewed" let env try { - env = await fetchUsage(site, cred.deviceToken) + env = await fetchUsage(siteOf(site, cred), cred.deviceToken) } catch (e) { if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e - env = await fetchUsage(site, await deviceToken(getAuth, cred.deviceToken)) + env = await fetchUsage(siteOf(site, cred), await deviceToken(getAuth, cred.deviceToken)) } return { ...parseUsage(env), signIn } } catch (e) { @@ -1208,9 +1298,11 @@ const makePlugin = (site) => async ({ client }) => { let cred try { cred = await fresh(getAuth) + url = campaignTarget(site, siteOf(site, cred), url) } catch (e) { return signedInError(e) } + if (!url) return errorResponse({ status: 404, message: "only chat completions are served" }) const method = String(init.method ?? input?.method ?? "GET").toUpperCase() try { let res = await campaignCall(url, method, body, cred.deviceToken, init.signal) @@ -1240,6 +1332,7 @@ const makePlugin = (site) => async ({ client }) => { return errorResponse({ status: 400, message: e.message }) } if (!m) return errorResponse({ status: 400, message: `unknown or disabled model "${chat.model}"` }) + const CHAT_URL = siteOf(site, cred).api + CHAT_PATH const wire = encodeBody(JSON.stringify(qoderBody(chat, m))) const headers = { ...cosyHeaders(CHAT_URL, cred, wire), @@ -1286,13 +1379,17 @@ const makePlugin = (site) => async ({ client }) => { async loader(getAuth) { const a = await getAuth() if (a?.type !== "oauth") return {} + let base = site + try { + base = siteOf(site, a) + } catch {} // its requests say so return { - baseURL: site.api, + baseURL: base.api, apiKey: "qoder", // every chat completion written as Qoder's own request async fetch(input, init = {}) { const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url - if (campaignPage(site, url)) return campaign(getAuth, input, url, init) + if (campaignPage(site, url) || campaignPage(base, url)) return campaign(getAuth, input, url, init) if (!/\/chat\/completions$/.test(new URL(url).pathname)) return errorResponse({ status: 404, message: "only chat completions are served" }) let chat @@ -1311,7 +1408,33 @@ const makePlugin = (site) => async ({ client }) => { }, } }, - methods: [{ type: "oauth", label: `Sign in with ${site.name}`, authorize: () => deviceSignIn(site) }], + methods: [ + { type: "oauth", label: `Sign in with ${site.name}`, authorize: () => deviceSignIn(site) }, + // an enterprise VPC instance (Qoder CN), a method of its own so + // that the sign-in above asks nothing new + ...(site.vpcDomain + ? [ + { + type: "oauth", + label: `Sign in with ${site.name} Enterprise (VPC)`, + prompts: [ + { + type: "text", + key: "vpc", + message: `Your enterprise's VPC instance: its name, or its address (.${site.vpcDomain})`, + placeholder: `acme or acme.${site.vpcDomain}`, + validate: (v) => (vpcInstance(v, site.vpcDomain) ? undefined : `Not a VPC instance: enter its name (letters, digits, -) or https://.${site.vpcDomain}`), + }, + ], + authorize: (inputs) => { + const s = vpcSite(site, inputs?.vpc) + if (!s) throw new Error(`Not a VPC instance: ${String(inputs?.vpc ?? "").slice(0, 100)}`) + return deviceSignIn(s) + }, + }, + ] + : []), + ], usage, }, async config(config) { @@ -1343,8 +1466,9 @@ const makePlugin = (site) => async ({ client }) => { try { const ms = await models(cred, true) if (!ms.length) return provider.models + const s = siteOf(site, cred) return Object.fromEntries( - 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, rate: m.rate, rateWas: m.rateWas })]), + ms.map((m) => [m.key, runtimeModel(s, { id: m.key, name: m.name, context: m.context, images: m.images, efforts: m.thinks ? m.efforts : [], free: m.free, rate: m.rate, rateWas: m.rateWas })]), ) } catch { return provider.models @@ -1358,4 +1482,4 @@ export const QoderAuthPlugin = makePlugin(SITES.qoder) export const QoderCNAuthPlugin = makePlugin(SITES["qoder-cn"]) // for tests -export const _internal = { campaignPage, parseUsage, gfmt, when, failure, modelInfo, qoderBody, SITES, decodeBody, events } +export const _internal = { campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, SITES, decodeBody, events } diff --git a/packages/qoder/package.json b/packages/qoder/package.json index faa7942..b8a7f27 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.2.7", + "version": "0.2.8", "description": "Qoder subscriptions in OpenCode and magpie: Qoder (qoder.com) and Qoder CN (qoder.cn)", "type": "module", "main": "./index.mjs", diff --git a/packages/qoder/vpc.test.mjs b/packages/qoder/vpc.test.mjs new file mode 100644 index 0000000..3e3e4ec --- /dev/null +++ b/packages/qoder/vpc.test.mjs @@ -0,0 +1,311 @@ +// Qoder CN enterprise VPC accounts (yetone/magpie#312) against a local +// stand-in for an instance's hosts. The hosts and shapes are the ones +// AwadYoo reported from a real VPC account on @qodercn-ai/qoderclicn 1.1.64 +// (values redacted there, made up here): the sign-in page on +// .vpc.qoder.com.cn, accounts on -openapi…, models and +// chat on -gateway…, the same paths as the public hosts. That CLI +// builds these hosts by swapping the public origin for the instance's +// (its VPC host map: base, gateway, openapi), the path kept. +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test" +import { QoderAuthPlugin, QoderCNAuthPlugin, _internal } from "./index.mjs" + +const CN_CLIENT = "e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb" +const WEB = "acme.vpc.qoder.com.cn" +const OPENAPI = "acme-openapi.vpc.qoder.com.cn" +const GATEWAY = "acme-gateway.vpc.qoder.com.cn" +const PUBLIC = ["qoder.cn", "openapi.qoder.com.cn", "gateway.qoder.com.cn", "openapi.qoder.sh", "api3.qoder.sh"] + +let server +let route = () => new Response("", { status: 404 }) +let seen = [] +const real = globalThis.fetch + +beforeAll(() => { + server = Bun.serve({ + port: 0, + async fetch(req) { + const u = new URL(req.url) + const host = req.headers.get("x-qoder-host") + const body = req.method === "GET" ? "" : await req.text() + seen.push({ host, path: u.pathname, query: u.searchParams, method: req.method, headers: req.headers, body }) + return route(host + u.pathname, { req, url: u, body }) + }, + }) +}) +afterAll(() => server.stop(true)) + +const toServer = () => { + globalThis.fetch = async (input, init = {}) => { + const u = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url) + const headers = new Headers(init.headers) + headers.set("x-qoder-host", u.host) + return real(`http://127.0.0.1:${server.port}${u.pathname}${u.search}`, { ...init, headers }) + } +} +afterEach(() => { + globalThis.fetch = real + route = () => new Response("", { status: 404 }) + seen = [] +}) + +const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json" } }) + +function store(initial) { + let auth = initial + const saved = [] + return { + client: { auth: { set: async ({ path, body }) => (saved.push(path.id), (auth = body)) } }, + get: async () => auth, + auth: () => auth, + saved, + } +} + +const hostsOf = () => [...new Set(seen.map((s) => s.host))] +const noPublic = () => expect(hostsOf().filter((h) => PUBLIC.includes(h))).toEqual([]) + +const vpcMethod = (hooks) => hooks.auth.methods.find((m) => m.prompts?.some((p) => p.key === "vpc")) + +test("an instance is read from its name or any of its hosts, as Qoder CN's CLI reads its VPC endpoint", () => { + const d = "vpc.qoder.com.cn" + for (const v of ["acme", " ACME ", "acme.vpc.qoder.com.cn", "acme-openapi.vpc.qoder.com.cn", "acme-gateway.vpc.qoder.com.cn", "https://acme.vpc.qoder.com.cn", "https://acme.vpc.qoder.com.cn/"]) + expect([v, _internal.vpcInstance(v, d)]).toEqual([v, "acme"]) + expect(_internal.vpcInstance("my-corp-01", d)).toBe("my-corp-01") + for (const v of ["", " ", "http://acme.vpc.qoder.com.cn", "https://acme.vpc.qoder.com.cn/x", "https://acme.vpc.qoder.com.cn?a=1", "https://u:p@acme.vpc.qoder.com.cn", "https://acme.vpc.qoder.com.cn:8443", "10.0.0.1", "acme.example.com", "evil.com/acme.vpc.qoder.com.cn", "-acme", "acme-", "ac_me", "a.b.vpc.qoder.com.cn"]) + expect([v, _internal.vpcInstance(v, d)]).toEqual([v, undefined]) + // qoder.com has no VPC + expect(_internal.vpcInstance("acme", undefined)).toBeUndefined() +}) + +test("the hosts of an instance are the CLI's: .vpc, -openapi.vpc, -gateway.vpc", () => { + const s = _internal.vpcSite(_internal.SITES["qoder-cn"], "acme") + expect(s).toMatchObject({ id: "qoder-cn", web: "https://" + WEB, openapi: "https://" + OPENAPI, api: "https://" + GATEWAY, vpc: "acme", clientId: CN_CLIENT }) + expect(_internal.vpcSite(_internal.SITES.qoder, "acme")).toBeUndefined() +}) + +test("the public sign-in is unchanged: it is still the first method and asks nothing", async () => { + const hooks = await QoderCNAuthPlugin({ client: store().client }) + expect(hooks.auth.methods[0].label).toBe("Sign in with Qoder CN") + expect(hooks.auth.methods[0].prompts).toBeUndefined() + const u = new URL((await hooks.auth.methods[0].authorize()).url) + expect(u.origin + u.pathname).toBe("https://qoder.cn/device/selectAccounts") + // qoder.com gains no VPC method + expect((await QoderAuthPlugin({ client: store().client })).auth.methods.length).toBe(1) +}) + +test("the VPC method asks for the instance and checks it", async () => { + const m = vpcMethod(await QoderCNAuthPlugin({ client: store().client })) + expect(m.type).toBe("oauth") + expect(m.label).toBe("Sign in with Qoder CN Enterprise (VPC)") + const p = m.prompts[0] + expect(p.type).toBe("text") + expect(p.validate("acme")).toBeUndefined() + expect(p.validate("http://acme.vpc.qoder.com.cn")).toContain("Not a VPC instance") + expect(() => m.authorize({ vpc: "acme.example.com" })).toThrow("Not a VPC instance") +}) + +test("a VPC sign-in opens the instance's page and polls, trades and reads the user on its openapi host", async () => { + toServer() + let polls = 0 + route = (at, { url, body, req }) => { + if (at === OPENAPI + "/api/v1/deviceToken/poll") { + expect(url.searchParams.get("challenge_method")).toBe("S256") + // the reporter's poll shape: the token alone + return ++polls < 2 ? new Response("", { status: 404 }) : json({ token: "dt-vpc", refresh_token: "drt-vpc" }) + } + if (at === OPENAPI + "/api/v1/me/jobToken") { + expect(req.headers.get("authorization")).toBe("Bearer dt-vpc") + expect(JSON.parse(body)).toEqual({ clientId: CN_CLIENT }) + return json({ message: "client not allowed" }, 403) + } + if (at === OPENAPI + "/api/v1/userinfo") { + expect(req.headers.get("authorization")).toBe("Bearer dt-vpc") + // the reporter's normalized user info + return json({ id: "u-vpc", username: "alice", name: "Alice", email: "alice@corp.example", avatar: "https://x/a.png", orgId: "org-1", orgName: "Corp", isPrivacyPolicyModifiable: true }) + } + return new Response("", { status: 404 }) + } + const m = vpcMethod(await QoderCNAuthPlugin({ client: store().client })) + const flow = await m.authorize({ vpc: "https://acme.vpc.qoder.com.cn" }) + const u = new URL(flow.url) + expect(u.origin + u.pathname).toBe("https://" + WEB + "/device/selectAccounts") + expect(u.searchParams.get("client_id")).toBe(CN_CLIENT) + expect(u.searchParams.has("redirect_uri")).toBe(false) + const cred = await flow.callback() + expect(cred).toMatchObject({ + type: "success", + access: "dt-vpc", + refresh: "drt-vpc", + deviceChat: true, + uid: "u-vpc", + email: "alice@corp.example", + name: "Alice", + accountId: "alice@corp.example (acme)", + vpc: "acme", + deviceToken: "dt-vpc", + deviceRefresh: "drt-vpc", + }) + expect(hostsOf()).toEqual([OPENAPI]) +}, 10_000) + +test("a VPC poll and user info that name no user fail the sign-in rather than keep an account with none", async () => { + toServer() + route = (at) => { + if (at === OPENAPI + "/api/v1/deviceToken/poll") return json({ token: "dt-vpc", refresh_token: "drt-vpc" }) + if (at === OPENAPI + "/api/v1/me/jobToken") return json({ token: "jt", refresh_token: "jrt", expires_in: 3_600_000 }) + if (at === OPENAPI + "/api/v1/userinfo") return json({ email: "" }) + return new Response("", { status: 404 }) + } + const flow = await vpcMethod(await QoderCNAuthPlugin({ client: store().client })).authorize({ vpc: "acme" }) + await expect(flow.callback()).rejects.toThrow("named no user") +}) + +// a model as the reporter's listing gives it, under its scene +const MODEL = { + key: "performance", + display_name: "Performance", + is_default: false, + enable: true, + is_reasoning: true, + is_vl: false, + efforts: ["high"], + default_effort: "high", + max_input_tokens: 180000, + available_context_windows: [180000], + format: "openai", + source: "system", + price_factor: 1, + original_price_factor: 1, + tags: [], + strategies: [{ tag: "t", enabled: true, disabled_message_key: "k" }], + promotion: { active: false, discount_factor: 0, before_promotion_price_factor: 0 }, +} + +const sse = (...chunks) => + new Response(chunks.map((c) => `data: ${JSON.stringify({ statusCodeValue: 200, body: JSON.stringify(c) })}\n\n`).join(""), { + headers: { "Content-Type": "text/event-stream" }, + }) + +const signedIn = (over = {}) => ({ + type: "oauth", + access: "dt-vpc", + refresh: "drt-vpc", + expires: Date.now() + 3_600_000, + deviceChat: true, + accountId: "alice@corp.example (acme)", + uid: "u-vpc", + machineId: "m-vpc", + deviceToken: "dt-vpc", + deviceRefresh: "drt-vpc", + vpc: "acme", + ...over, +}) + +const chat = { model: "performance", messages: [{ role: "user", content: "hi" }] } + +const gateway = (at) => { + if (at === GATEWAY + "/algo/api/v2/model/list") return json({ chat: [MODEL] }) + if (at === GATEWAY + "/algo/api/v2/service/pro/sse/agent_chat_generation") + // the reporter's OpenAI-compatible chunk + return sse( + { choices: [{ index: 0, delta: { role: "assistant", content: "OK", reasoning_content: "", tool_calls: [] }, finish_reason: null }] }, + { choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 5, completion_tokens: 1, total_tokens: 6 } }, + ) + return null +} + +test("a VPC account's chat and list go to its gateway host, not the public one", async () => { + toServer() + route = (at, { req }) => { + const r = gateway(at) + if (r && at.endsWith("agent_chat_generation")) expect(req.headers.get("cosy-user")).toBe("u-vpc") + return r ?? new Response("", { status: 404 }) + } + const s = store(signedIn()) + const opts = await (await QoderCNAuthPlugin({ client: s.client })).auth.loader(s.get) + expect(opts.baseURL).toBe("https://" + GATEWAY) + const res = await opts.fetch("https://" + GATEWAY + "/chat/completions", { method: "POST", body: JSON.stringify(chat) }) + expect(res.status).toBe(200) + const out = await res.json() + expect(out.choices[0].message.content).toBe("OK") + expect(out.usage).toEqual({ prompt_tokens: 5, completion_tokens: 1, total_tokens: 6 }) + expect(seen.map((x) => x.host + x.path)).toEqual([GATEWAY + "/algo/api/v2/model/list", GATEWAY + "/algo/api/v2/service/pro/sse/agent_chat_generation"]) + noPublic() +}) + +test("a VPC device token is renewed on its openapi host with the reporter's refresh shape", async () => { + toServer() + route = (at, { body }) => { + if (at === OPENAPI + "/api/v1/deviceToken/refresh") { + expect(JSON.parse(body)).toEqual({ refresh_token: "drt-vpc" }) + return json({ device_token: "dt-vpc-2", refresh_token: "drt-vpc-2", expires_at: new Date(Date.now() + 7_200_000).toISOString(), refresh_token_expires_at: 0 }) + } + return gateway(at) ?? new Response("", { status: 404 }) + } + const s = store(signedIn({ expires: Date.now() + 60_000 })) + const opts = await (await QoderCNAuthPlugin({ client: s.client })).auth.loader(s.get) + const res = await opts.fetch("https://" + GATEWAY + "/chat/completions", { method: "POST", body: JSON.stringify(chat) }) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed") + expect(s.auth()).toMatchObject({ access: "dt-vpc-2", refresh: "drt-vpc-2", deviceToken: "dt-vpc-2", vpc: "acme" }) + expect(seen[0].host + seen[0].path).toBe(OPENAPI + "/api/v1/deviceToken/refresh") + noPublic() +}) + +test("magpie's auth.refresh of a VPC job-token account goes to its openapi host", async () => { + toServer() + route = (at, { body }) => { + if (at !== OPENAPI + "/api/v1/jobToken/refresh") return new Response("", { status: 404 }) + expect(JSON.parse(body)).toEqual({ refresh_token: "jrt" }) + // the reporter's job token refresh shape + return json({ token: "jt-2", refresh_token: "jrt-2", expires_at: 0, expires_in: 3_600_000, refresh_token_expires_at: 0, refresh_token_expires_in: 0 }) + } + const a = signedIn({ access: "jt", refresh: "jrt", deviceChat: undefined, expires: Date.now() + 60_000 }) + const got = await (await QoderCNAuthPlugin({ client: store(a).client })).auth.refresh(a) + expect(got).toMatchObject({ access: "jt-2", refresh: "jrt-2" }) + expect(hostsOf()).toEqual([OPENAPI]) +}) + +test("a VPC account's models come from its gateway, named on it", async () => { + toServer() + route = (at) => gateway(at) ?? new Response("", { status: 404 }) + const ms = await (await QoderCNAuthPlugin({ client: store().client })).provider.models({ models: {} }, { auth: signedIn() }) + expect(Object.keys(ms)).toEqual(["performance"]) + expect(ms.performance.api.url).toBe("https://" + GATEWAY) + noPublic() +}) + +test("a VPC account's usage is read on its openapi host; the enterprise display mode is its plan", async () => { + toServer() + route = (at, { req }) => { + if (at !== OPENAPI + "/sash/api/v2/me/usage") return new Response("", { status: 404 }) + expect(req.headers.get("authorization")).toBe("Bearer dt-vpc") + return json({ displayMode: "enterprise", enterpriseUsage: { openMode: "externalBrowser", detailUrl: "https://" + WEB + "/usage" } }) + } + const s = store(signedIn()) + expect(await (await QoderCNAuthPlugin({ client: s.client })).auth.usage(s.get)).toEqual({ plan: "Enterprise", signIn: "kept" }) + noPublic() +}) + +test("magpie's check-in on the public host is asked on the VPC instance", async () => { + toServer() + route = (at) => (at === OPENAPI + "/sash/api/v1/me/campaigns" ? json({ campaigns: [] }) : new Response("", { status: 404 })) + const s = store(signedIn()) + const opts = await (await QoderCNAuthPlugin({ client: s.client })).auth.loader(s.get) + const res = await opts.fetch("https://openapi.qoder.com.cn/sash/api/v1/me/campaigns", { method: "GET" }) + expect(res.status).toBe(200) + expect(hostsOf()).toEqual([OPENAPI]) +}) + +test("an account whose VPC instance on record isn't one is not sent to the public hosts", async () => { + toServer() + route = (at) => gateway(at) ?? new Response("", { status: 404 }) + const s = store(signedIn({ vpc: "evil.example.com" })) + const hooks = await QoderCNAuthPlugin({ client: s.client }) + const opts = await hooks.auth.loader(s.get) + const res = await opts.fetch("https://gateway.qoder.com.cn/chat/completions", { method: "POST", body: JSON.stringify(chat) }) + expect(res.status).toBe(401) + expect((await res.json()).error.message).toContain("isn't one; sign in again") + expect((await hooks.auth.usage(s.get)).error).toContain("isn't one") + expect(seen).toEqual([]) +})