From 7b09c423c8688a534c7b7833a60d0a88d5d00cc7 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 13 Oct 2026 11:13:49 +0800 Subject: [PATCH] trae 0.2.10: the sign-in page offers the enterprise (SaaS) sign-in (@shad70w0 on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit @shad70w0 on X: "magpie + Trae 插件实测没办法走企业订阅" - a Trae enterprise subscription couldn't be used through this plugin. The sign-in URL sent hide_saas_login=true (copied from the relays in 6c048c7), which hides the enterprise/SSO sign-in on www.trae.cn/authorization and www.trae.ai/authorization, so an enterprise user could only sign in as a personal account. What changed: - the authorization URL sends hide_saas_login=false. - traeHost: a host a sign-in names is taken only when it is a well-formed https host (no port, credentials, query) on trae.cn, trae.ai or mchost.guru; anything else is ignored and the consumer host used, as before. - Trae CN: a sign-in host on mchost.guru / trae-api-*, or another trae.cn host than www/api/grow*, is the account's model host. Trae Global: a trae.ai host other than www/api-*/grow* is too, after the existing US/coresg rules. Personal hosts (api.trae.cn, api-us-east, api-sg-central, growsg-normal, coresg-normal) route as before. - the sign-in's host (host), a token host the callback names (authHost / auth_host / userInfo.AuthHost, on the realm's own domain only) and the userInfo's tenant/enterprise/login-type fields (account; no field that looks like a secret) are kept in the auth record. Renewal (sign-in and refresh) goes to authHost when one is kept. Nothing new is sent. - README: enterprise sign-in is offered, not tried with a real enterprise account. Run: bun test in packages/trae (103 pass, 6 new in enterprise.test.mjs); the whole repo's bun test with HOME under a scratch TMPDIR (1168 pass, 0 fail); bun scripts/check.mjs. Each change broken by hand turns enterprise.test.mjs red: hide_saas_login back to true, no enterprise CN host, no domain check, http allowed, refresh at the consumer host, no account kept, api.trae.cn taken as a model host, a secret-looking field kept. Not tried: no real enterprise account. Which host(s) and fields an enterprise sign-in sends back is unknown; the hosts in the tests are made up, and whether the callback ever names an auth host is a guess. --- packages/trae/README.md | 17 +++++ packages/trae/enterprise.test.mjs | 110 ++++++++++++++++++++++++++++++ packages/trae/index.mjs | 105 +++++++++++++++++++++++----- packages/trae/package.json | 2 +- 4 files changed, 217 insertions(+), 17 deletions(-) create mode 100644 packages/trae/enterprise.test.mjs diff --git a/packages/trae/README.md b/packages/trae/README.md index 00df3c5..540aab9 100644 --- a/packages/trae/README.md +++ b/packages/trae/README.md @@ -46,6 +46,23 @@ authorization page: `device_id` (19 digits) and `machine_id` (32 hex). Every request then sends that same device. The relays saw requests dropped when the device was new each time. +### Enterprise (SaaS) accounts + +Since 0.2.10 the authorization page also offers Trae's enterprise (SaaS / SSO) +sign-in; before, the plugin asked the page to hide it (`hide_saas_login`), so +an enterprise subscription could only sign in as a personal account. A host +the sign-in names for the account is kept when it is an https host on Trae's +own domains (`trae.cn`, `trae.ai`, `mchost.guru`): a model host other than the +consumer site's own (`www`, `api`, `grow…`) takes the account's model +requests, and a token host the callback names (`authHost`) takes its +renewals. Any other host is ignored and the consumer hosts are used, as for a +personal account, which is unchanged. The account's tenant and login-type +fields are kept with the sign-in; nothing sends them. + +**Not tried with a real enterprise account.** Which hosts and fields an +enterprise sign-in sends back is not known yet; if yours doesn't work, open an +issue with what the sign-in page showed. + ### The international realm's region Trae Global has two deployments. The sign-in's `AIRegion` (or a US auth host diff --git a/packages/trae/enterprise.test.mjs b/packages/trae/enterprise.test.mjs new file mode 100644 index 0000000..bb0e3d4 --- /dev/null +++ b/packages/trae/enterprise.test.mjs @@ -0,0 +1,110 @@ +// An enterprise (SaaS) subscription signs in on the same authorization +// page as a personal one, when the page is not told to hide that sign-in +// (@shad70w0 on X). A host the sign-in names on Trae's own domains is kept +// and used; one anywhere else is not, and a personal sign-in is as before. +// Not tried with a real enterprise account: the hosts below are made up. +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import { TraeCNAuthPlugin, _internal } from "./index.mjs" +import { fakeTrae, signedIn } from "./fake.mjs" + +const CN = _internal.SITES["trae-cn"] +const GLOBAL = _internal.SITES["trae-global"] + +let f +afterEach(() => f?.close()) + +async function start() { + const hooks = await TraeCNAuthPlugin({ client: {} }) + const a = await hooks.auth.methods[0].authorize() + return { a, q: new URL(a.url).searchParams, cb: new URL(new URL(a.url).searchParams.get("auth_callback_url")) } +} + +async function signIn(info, extra = {}) { + const { a, cb } = await start() + const jwt = { Token: "jwt-1", RefreshToken: "r-1", TokenExpireAt: Math.floor(Date.now() / 1000) + 7200, ClientID: "ono9krqynydwx5" } + const url = new URL(cb) + url.searchParams.set("userJwt", JSON.stringify(jwt)) + url.searchParams.set("userInfo", JSON.stringify(info)) + for (const [k, v] of Object.entries(extra)) url.searchParams.set(k, v) + await fetch(url) + return a.callback() +} + +test("the sign-in page doesn't hide the enterprise (SaaS) sign-in", async () => { + f = fakeTrae() + const { a, q } = await start() + expect(q.get("hide_saas_login")).not.toBe("true") + await fetch(new URL(q.get("auth_callback_url")) + "?error=x") + await a.callback() +}) + +test("only an https host on Trae's own domains is taken", () => { + const t = _internal.traeHost + expect(t("https://trae-api-cn.mchost.guru")).toBe("https://trae-api-cn.mchost.guru") + expect(t("https://ent-acme.trae.cn/")).toBe("https://ent-acme.trae.cn") + expect(t("https://ent.trae.ai")).toBe("https://ent.trae.ai") + for (const bad of ["http://ent.trae.cn", "https://trae.cn.evil.com", "https://eviltrae.cn", "https://trae-api-cn.evil.com", "https://u:p@ent.trae.cn", "https://ent.trae.cn:8443", "https://ent.trae.cn/?x=1", "ent.trae.cn", "", undefined]) { + expect(t(bad)).toBe("") + } +}) + +test("a sign-in naming an enterprise Trae CN host keeps it, and requests go there", async () => { + f = fakeTrae() + const info = { UserID: "u-e", ScreenName: "Acme", Host: "https://ent-acme.trae.cn", TenantID: "t-1", LoginType: "saas", TenantToken: "no" } + const got = await signIn(info) + expect(got.type).toBe("success") + expect(got.api).toBe("https://ent-acme.trae.cn") + expect(got.host).toBe("https://ent-acme.trae.cn") + // the account's kind is kept, never a field that looks like a secret + expect(got.account).toEqual({ TenantID: "t-1", LoginType: "saas" }) + expect(CN.apiOf(got)).toBe("https://ent-acme.trae.cn") + // a request goes to that host (nonet stops it before it leaves) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const opts = await hooks.auth.loader(async () => signedIn({ api: got.api })) + const e = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ model: "glm-5", messages: [{ role: "user", content: "hi" }] }) }).catch((e) => e) + expect(String(e?.message)).toContain("https://ent-acme.trae.cn/api/agent/v3/llm_utils_chat") +}) + +test("a personal sign-in is as before", async () => { + f = fakeTrae() + const got = await signIn({ UserID: "u-1", ScreenName: "Ann", Region: "CN", Host: "https://api.trae.cn" }) + expect(got.api).toBeUndefined() + expect(got.authHost).toBeUndefined() + expect(got.account).toBeUndefined() + expect(CN.apiOf(got)).toBe(CN.hosts.api) + expect(CN.apiOf({ api: "https://trae-api-cn.mchost.guru" })).toBe("https://trae-api-cn.mchost.guru") + for (const h of ["https://www.trae.cn", "https://api.trae.cn", "https://growcn-normal.trae.cn"]) expect(CN.modelHost(h)).toBe(false) + // Global's personal hosts route as they did + expect(GLOBAL.apiOf({ api: "https://api-us-east.trae.ai" })).toBe(GLOBAL.hosts.us) + expect(GLOBAL.apiOf({ api: "https://api-sg-central.trae.ai" })).toBe(GLOBAL.hosts.api) + expect(GLOBAL.apiOf({ api: "https://growsg-normal.trae.ai" })).toBe(GLOBAL.hosts.api) + expect(GLOBAL.apiOf({ api: "https://coresg-normal.trae.ai" })).toBe("https://coresg-normal.trae.ai") + expect(GLOBAL.apiOf({ api: "https://ent-acme.trae.ai" })).toBe("https://ent-acme.trae.ai") +}) + +test("a host off Trae's domains is refused, and the consumer one is used", async () => { + f = fakeTrae() + const got = await signIn({ UserID: "u-x", ScreenName: "X", Host: "https://trae-api-cn.evil.com" }, { authHost: "https://api.evil.com" }) + expect(got.type).toBe("success") + expect(got.api).toBeUndefined() + expect(got.host).toBeUndefined() + expect(got.authHost).toBeUndefined() + expect(CN.apiOf({ api: "https://trae-api-cn.evil.com" })).toBe(CN.hosts.api) + expect(CN.apiOf({ api: "http://ent-acme.trae.cn" })).toBe(CN.hosts.api) + expect(GLOBAL.apiOf({ api: "https://coresg.evil.com" })).toBe(GLOBAL.hosts.api) + expect(GLOBAL.modelHost("https://trae.ai.evil.com")).toBe(false) +}) + +test("a token host the sign-in named is where the token is renewed", async () => { + f = fakeTrae() + const got = await signIn({ UserID: "u-e", ScreenName: "Acme", Host: "https://ent-acme.trae.cn" }, { authHost: "https://auth-acme.trae.cn" }) + expect(got.authHost).toBe("https://auth-acme.trae.cn") + const hooks = await TraeCNAuthPlugin({ client: {} }) + // nonet stops the renewal before it leaves, naming where it went + const e = await hooks.auth.refresh(signedIn({ authHost: got.authHost, refresh: "r-ent" })).catch((e) => e) + expect(String(e?.message)).toContain("https://auth-acme.trae.cn/") + // a token host off the site's domain is not taken + const g = await signIn({ UserID: "u-e", ScreenName: "Acme" }, { authHost: "https://auth.trae.ai" }) + expect(g.authHost).toBeUndefined() +}) diff --git a/packages/trae/index.mjs b/packages/trae/index.mjs index 190ed71..c50fc90 100644 --- a/packages/trae/index.mjs +++ b/packages/trae/index.mjs @@ -79,11 +79,19 @@ const SITES = { // the model host for an account: Trae CN's own hosts serve no models, // so only a host that is one is taken, else the one gateway apiOf: (a) => { - const h = String(a?.api ?? "").replace(/\/+$/, "") - return /mchost\.guru|trae-api-/i.test(h) ? h : SITES["trae-cn"].hosts.api + const h = traeHost(a?.api) + return h && SITES["trae-cn"].modelHost(h) ? h : SITES["trae-cn"].hosts.api + }, + // whether a host named by a sign-in is one of the model hosts: an https + // host on mchost.guru or named trae-api-…, as the consumer gateway is, + // or another trae.cn host than the consumer site's own (www, api, + // grow…), which an enterprise (SaaS) sign-in may name for its tenant + modelHost: (h) => { + const t = traeHost(h) + if (!t) return false + const n = new URL(t).hostname + return /(^|\.)mchost\.guru$|^trae-api-/i.test(n) || (/\.trae\.cn$/i.test(n) && !/^(www|api|grow[^.]*)\./i.test(n)) }, - // whether a host named by a sign-in is one of the model hosts - modelHost: (h) => /mchost\.guru|trae-api-/i.test(String(h ?? "")), // ownPage: url is one of Trae CN's own JSON pages on api.trae.cn // (/trae/api/…: the daily check-in, credits), which the account's fetch // sends as the account rather than as a chat @@ -166,15 +174,22 @@ const SITES = { // the model host: the account's region (or a US host the sign-in named) // selects the US deployment, else the SG one apiOf: (a) => { - const h = String(a?.api ?? "").replace(/\/+$/, "") + const h = traeHost(a?.api) + const n = h ? new URL(h).hostname : "" const region = String(a?.region ?? "").toUpperCase() - if (/coreva/i.test(h) || /api-us(?:[-.]|$)/i.test(h) || /^US(?:[-_ ]|$)/.test(region)) return SITES["trae-global"].hosts.us - if (/coresg/i.test(h)) return h + if (/coreva/i.test(n) || /api-us(?:[-.]|$)/i.test(n) || /^US(?:[-_ ]|$)/.test(region)) return SITES["trae-global"].hosts.us + if (/coresg/i.test(n)) return h + // another trae.ai host than the site's own (www, api-…, grow…): one an + // enterprise (SaaS) sign-in named for its tenant + if (/\.trae\.ai$/i.test(n) && !/^(www\.|api[-.]|grow)/i.test(n)) return h return SITES["trae-global"].hosts.api }, // a sign-in names a host of Trae's, which can be an auth host // (api-us-east), not the chat host - modelHost: (h) => /trae\.ai/i.test(String(h ?? "")), + modelHost: (h) => { + const t = traeHost(h) + return !!t && /(^|\.)trae\.ai$/i.test(new URL(t).hostname) + }, // Trae Global serves no own JSON pages through the account's fetch ownPage: () => false, // the account's region, from the sign-in's user info @@ -213,6 +228,46 @@ const SITES = { }, } +// traeHost is a host a sign-in named, when it is a well-formed https one +// on Trae's own domains (no port, no credentials), as origin plus any path; +// "" for anything else, which is then not taken +const TRAE_DOMAINS = ["trae.cn", "trae.ai", "mchost.guru"] +function traeHost(h) { + try { + const u = new URL(String(h ?? "").trim()) + if (u.protocol !== "https:" || u.username || u.password || u.port || u.search || u.hash) return "" + const n = u.hostname.toLowerCase() + if (!TRAE_DOMAINS.some((d) => n === d || n.endsWith("." + d))) return "" + return (u.origin + u.pathname).replace(/\/+$/, "") + } catch { + return "" + } +} + +// authHostOf is the host a sign-in named for its tokens, when it named one +// on the site's own domain (an enterprise's may differ from the consumer +// one); "" when it named none, and the site's own is used +function authHostOf(h, site) { + const t = traeHost(h) + if (!t) return "" + const n = new URL(t).hostname + return n === site.webHost || n.endsWith("." + site.webHost) ? t : "" +} + +// accountOf keeps the account fields of the sign-in's user info that say +// what kind of account it is (tenant, enterprise, login type), plain values +// only and never anything that looks like a secret, for later use; nothing +// sends them +function accountOf(info) { + const out = {} + for (const [k, v] of Object.entries(info ?? {})) { + if (!/tenant|enterprise|saas|login|org|team|sso|^ent|usertype|accounttype/i.test(k)) continue + if (/token|secret|key|password|cookie|session|jwt/i.test(k)) continue + if (v === null || ["string", "number", "boolean"].includes(typeof v)) out[k] = v + } + return out +} + const SIGN_IN_TIMEOUT = 10 * 60 * 1000 const EARLY_MS = 2 * 60 * 1000 // a token this close to its end is renewed before a request const LEAD_MS = 10 * 60 * 1000 // and this close, magpie renews it ahead of time (auth.refresh) @@ -301,6 +356,11 @@ function toAuth(s, site) { // the model host the sign-in named, if it named one ...(site.modelHost(s.api) ? { api: s.api } : {}), ...(s.region ? { region: s.region } : {}), + // the host the sign-in named, its own token host if it named one, and + // what kind of account it is (an enterprise one's tenant), kept as given + ...(traeHost(s.host) ? { host: traeHost(s.host) } : {}), + ...(authHostOf(s.authHost, site) ? { authHost: authHostOf(s.authHost, site) } : {}), + ...(s.account && Object.keys(s.account).length ? { account: s.account } : {}), } } @@ -319,6 +379,9 @@ function fromAuth(auth, site) { devicePrivateKey: auth.devicePrivateKey || "", api: auth.api || "", region: site.regionOf(auth), + host: auth.host || "", + authHost: authHostOf(auth.authHost, site), + account: auth.account && typeof auth.account === "object" ? auth.account : {}, } } @@ -405,6 +468,7 @@ async function exchange(refresh, clientId, site, host = site.hosts.auth) { name: String(info.ScreenName ?? info.screenName ?? ""), api: info.Host ?? "", region: site.regionOf(info), + account: accountOf(info), } } const e = errorOf(text) @@ -495,12 +559,14 @@ async function boundExchange(a, site, host = site.hosts.auth) { // before 0.2.3 (exchange). A device key made for the account goes with // either, so the next renewal signs with the same one. async function renewal(a, site) { - if (!site.deviceExchange) return exchange(a.refresh, a.clientId, site) + // the token host the sign-in named, else the site's + const host = authHostOf(a.authHost, site) || site.hosts.auth + if (!site.deviceExchange) return exchange(a.refresh, a.clientId, site, host) const keys = a.devicePrivateKey && a.devicePublicKey ? {} : newDeviceKey() try { - return await boundExchange({ ...a, ...keys }, site) + return await boundExchange({ ...a, ...keys }, site, host) } catch {} - return { ...(await exchange(a.refresh, a.clientId, site)), ...keys } + return { ...(await exchange(a.refresh, a.clientId, site, host)), ...keys } } // ---- the browser sign-in -------------------------------------------------------- @@ -527,10 +593,15 @@ async function signedIn(q, device, site) { name: String(info.ScreenName ?? info.screenName ?? ""), api: host, region: site.regionOf(info), + host, + // a token host the callback named, if it named one + authHost: authHostOf(q.get("authHost") || q.get("auth_host") || info.AuthHost || info.authHost, site), + account: accountOf(info), } + const authHost = s.authHost || site.hosts.auth if (!s.token && s.refresh) { - const x = await exchange(s.refresh, s.clientId, site) - s = { ...s, ...x, uid: x.uid || s.uid, name: x.name || s.name, api: x.api || s.api, region: x.region || s.region } + const x = await exchange(s.refresh, s.clientId, site, authHost) + s = { ...s, ...x, uid: x.uid || s.uid, name: x.name || s.name, api: x.api || s.api, region: x.region || s.region, host: s.host || x.api, account: { ...x.account, ...s.account } } } if (!s.token) throw new Error(`${site.webHost} sent back no token`) if (!s.refresh) throw new Error(`${site.webHost} sent back no refresh token`) @@ -539,7 +610,7 @@ async function signedIn(q, device, site) { // one at once, so a check-in takes it; when Trae won't, it does as is if (site.deviceExchange) { try { - const x = await boundExchange(s, site) + const x = await boundExchange(s, site, authHost) s = { ...s, token: x.token, refresh: x.refresh, expires: x.expires || s.expires } } catch {} } @@ -616,7 +687,9 @@ async function browserSignIn(site) { x_env: "", x_app_version: site.ideVersion, x_app_type: "stable", - hide_saas_login: "true", + // the enterprise (SaaS) sign-in is offered beside the personal one: an + // enterprise subscription signs in there (@shad70w0 on X) + hide_saas_login: "false", }) return { url: `${site.hosts.web}/authorization?${q}`, @@ -2347,4 +2420,4 @@ const makePlugin = (site) => async ({ client }) => { export const TraeCNAuthPlugin = makePlugin(SITES["trae-cn"]) export const TraeGlobalAuthPlugin = makePlugin(SITES["trae-global"]) -export const _internal = { HOSTS: SITES["trae-cn"].hosts, MODELS: SITES["trae-cn"].models, TextTools, NativeCalls, looseJSON, glmCall, toolNamed, unwrapped, traeMessages, chatBody, credits, dollarUsageOf, whenOf, newDevice, proofOf, SITES, SESSION, conversationID } +export const _internal = { traeHost, accountOf, HOSTS: SITES["trae-cn"].hosts, MODELS: SITES["trae-cn"].models, TextTools, NativeCalls, looseJSON, glmCall, toolNamed, unwrapped, traeMessages, chatBody, credits, dollarUsageOf, whenOf, newDevice, proofOf, SITES, SESSION, conversationID } diff --git a/packages/trae/package.json b/packages/trae/package.json index a73c940..c1e8967 100644 --- a/packages/trae/package.json +++ b/packages/trae/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-trae-auth", - "version": "0.2.9", + "version": "0.2.10", "description": "OpenCode provider plugins for Trae: Trae CN (trae.cn) and Trae Global (trae.ai), free tier included, with Trae's own browser sign-in", "type": "module", "main": "./index.mjs",