diff --git a/packages/trae/README.md b/packages/trae/README.md index 542e8dd..76304de 100644 --- a/packages/trae/README.md +++ b/packages/trae/README.md @@ -133,10 +133,28 @@ replaces either. ## Renewal -The JWT is renewed with the refresh token at the realm's auth host, -`/cloudide/api/v3/trae/oauth/ExchangeToken` (`api.trae.cn` for Trae CN, -`growsg-normal.trae.ai` for Trae Global). Trae issues a new refresh token -each time and spends the old one, so only one renewal runs at a time. +Trae CN (since 0.2.3) renews the JWT as its clients do, bound to the +account's device: + +- **Where:** `POST api.trae.cn/trae/api/v3/oauth/ExchangeToken`, with the + refresh token, the device (`DeviceInfo`: its id, machine id and public + key) and a `DeviceProof`. +- **The device key:** an ECDSA P-256 key pair made for each account at + sign-in (or at the first renewal of one signed in before 0.2.3), kept + with the sign-in. +- **The proof:** the key's ECDSA-SHA256 signature (base64) of + `POST\n/trae/api/v3/oauth/ExchangeToken\n{ClientID}\n{RefreshToken}\n{Timestamp}\n{Nonce}`. +- **As whom:** TRAE SOLO CN (`en1oxy7wnw8j9n`, `SOLO_PC`) first, then + Trae CN's IDE (`ono9krqynydwx5`, `IDE_PC`). +- **The refresh token:** kept; this renewal doesn't spend it. + +A token the sign-in page gives is renewed this way at once. When Trae +turns the device-bound renewal away, the plugin renews as before 0.2.3. + +Trae Global, and Trae CN as a fallback, renew at the realm's auth host's +`/cloudide/api/v3/trae/oauth/ExchangeToken` (`api.trae.cn`, +`growsg-normal.trae.ai`). There Trae issues a new refresh token each time +and spends the old one, so only one renewal runs at a time. magpie renews the JWT ten minutes before it ends (`refreshLead`) through `auth.refresh`. Each request also checks it, two minutes before the end, for @@ -198,7 +216,9 @@ end), its device (`x-device-id`, `x-device-brand`, `x-device-type`, `x-os-version`, `x-app-version`) and a client's User-Agent (TRAE SOLO CN's Electron shell). Since 0.2.1: Bun's own User-Agent and the chat's headers got 9074 「当前参与用户太多,请稍后再试」 every time -(yetone/magpie#808). +(yetone/magpie#808). Since 0.2.3 the JWT is also bound to the device (see +Renewal): a JWT renewed at `/cloudide/…` carries no device, and the claim +answered it 9074 even with the client's headers. - **Status:** `POST api.trae.cn/trae/api/v2/ug/checkin_credits/status`, body `{"req_source":1}` (magpie's `{}` is sent as that): `enable`, diff --git a/packages/trae/device.test.mjs b/packages/trae/device.test.mjs new file mode 100644 index 0000000..81eb384 --- /dev/null +++ b/packages/trae/device.test.mjs @@ -0,0 +1,125 @@ +// Renewing the JWT for the account's device, as Trae CN's clients do +// (yetone/magpie#808): a JWT renewed at /cloudide/… is bound to no device, +// and Trae CN answers its daily check-in claim 9074 every time. +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import { verify } from "node:crypto" +import { TraeCNAuthPlugin, TraeGlobalAuthPlugin, _internal } from "./index.mjs" +import { fakeTrae, json, signedIn } from "./fake.mjs" + +const V3 = "POST /trae/api/v3/oauth/ExchangeToken" +const OLD = "POST /cloudide/api/v3/trae/oauth/ExchangeToken" + +let f +afterEach(() => f?.close()) + +// signed is whether the request's DeviceProof is its device key's signature +// of what the clients sign +const signed = (r) => { + const { ClientID, RefreshToken, DeviceInfo, DeviceProof } = r.json + const text = ["POST", "/trae/api/v3/oauth/ExchangeToken", ClientID, RefreshToken, String(DeviceProof.Timestamp), DeviceProof.Nonce].join("\n") + return verify("sha256", Buffer.from(text), DeviceInfo.DevicePublicKey, Buffer.from(DeviceProof.Signature, "base64")) +} + +test("proofOf signs the method, path, client, refresh token, time and nonce with the device key", () => { + const k = _internal.newDevice() + const p = _internal.proofOf("/trae/api/v3/oauth/ExchangeToken", "en1oxy7wnw8j9n", "r-1", k.devicePrivateKey, 1700000000, "n0") + expect(p.Timestamp).toBe(1700000000) + expect(p.Nonce).toBe("n0") + const text = "POST\n/trae/api/v3/oauth/ExchangeToken\nen1oxy7wnw8j9n\nr-1\n1700000000\nn0" + expect(verify("sha256", Buffer.from(text), k.devicePublicKey, Buffer.from(p.Signature, "base64"))).toBe(true) + expect(verify("sha256", Buffer.from(text + "x"), k.devicePublicKey, Buffer.from(p.Signature, "base64"))).toBe(false) + // a new nonce each time + const q = _internal.proofOf("/p", "c", "r", k.devicePrivateKey) + expect(q.Nonce).toMatch(/^[0-9a-f]{32}$/) + expect(Math.abs(q.Timestamp - Date.now() / 1000)).toBeLessThan(5) +}) + +test("a renewal goes to the device-bound ExchangeToken as TRAE SOLO CN, keeps the refresh token, and the key made for the account is kept", async () => { + f = fakeTrae() + f.route(V3, () => json({ Result: { Token: "jwt-2", RefreshToken: "r-1", TokenExpireAt: 2000000000, RefreshExpireAt: 2100000000 } })) + f.route(OLD, () => json({ Result: { Token: "jwt-old", RefreshToken: "r-spent" } })) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const x = await hooks.auth.refresh(signedIn({ expires: Date.now() + 60_000 })) + expect(f.seen.map((r) => r.path)).toEqual(["/trae/api/v3/oauth/ExchangeToken"]) + const r = f.seen[0] + expect(r.headers.get("authorization")).toBe("Cloud-IDE-JWT jwt-1") + expect(r.json.ClientID).toBe("en1oxy7wnw8j9n") + expect(r.json.RefreshToken).toBe("r-1") + expect(r.json.IDEVersion).toBe("0.1.64") + expect(r.json.DeviceInfo).toMatchObject({ DeviceID: "1234567890123456789", MachineID: "ab".repeat(16), PlatformCode: "SOLO_PC", DeviceType: "PC", ClientVersion: "0.1.64" }) + expect(r.json.DeviceInfo.DevicePublicKey).toContain("BEGIN PUBLIC KEY") + expect(signed(r)).toBe(true) + expect(x).toMatchObject({ access: "jwt-2", refresh: "r-1", expires: 2000000000 * 1000 }) + expect(x.devicePublicKey).toBe(r.json.DeviceInfo.DevicePublicKey) + expect(x.devicePrivateKey).toContain("BEGIN PRIVATE KEY") +}) + +test("an account with a device key signs with it, and its renewals aren't taken for one another though the refresh token stays", async () => { + f = fakeTrae() + let n = 0 + f.route(V3, () => json({ Result: { Token: `jwt-${++n + 1}`, RefreshToken: "r-1", TokenExpireAt: Math.floor(Date.now() / 1000) + 7200 } })) + const k = _internal.newDevice() + const hooks = await TraeCNAuthPlugin({ client: {} }) + const a = signedIn({ expires: Date.now() + 60_000, devicePublicKey: k.devicePublicKey, devicePrivateKey: k.devicePrivateKey }) + const x = await hooks.auth.refresh(a) + expect(f.seen[0].json.DeviceInfo.DevicePublicKey).toBe(k.devicePublicKey) + expect(signed(f.seen[0])).toBe(true) + expect(x).toEqual({ access: "jwt-2", refresh: "r-1", expires: x.expires }) // its keys as they were + // asked again with the sign-in from before, it gives the one it got + expect(await hooks.auth.refresh(a)).toEqual(x) + expect(n).toBe(1) + // and with the one it got, when that is near its end, it renews again + const y = await hooks.auth.refresh({ ...a, access: "jwt-2", expires: Date.now() + 60_000 }) + expect(y.access).toBe("jwt-3") + expect(n).toBe(2) +}) + +test("SOLO turned away, it is tried as Trae CN's IDE, then at /cloudide/… as before", async () => { + f = fakeTrae() + f.route(V3, () => json({ ResponseMetadata: { Error: { Code: 20101, Message: "refresh token is invalid" } } }, 400)) + f.route(OLD, () => json({ Result: { Token: "jwt-2", RefreshToken: "r-2", TokenExpireAt: 2000000000 } })) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const x = await hooks.auth.refresh(signedIn({ expires: Date.now() + 60_000 })) + expect(f.seen.map((r) => r.json.ClientID + " " + r.path)).toEqual([ + "en1oxy7wnw8j9n /trae/api/v3/oauth/ExchangeToken", + "ono9krqynydwx5 /trae/api/v3/oauth/ExchangeToken", + "ono9krqynydwx5 /cloudide/api/v3/trae/oauth/ExchangeToken", + ]) + expect(f.seen[1].json.DeviceInfo.PlatformCode).toBe("IDE_PC") + expect(signed(f.seen[1])).toBe(true) + expect(x).toMatchObject({ access: "jwt-2", refresh: "r-2" }) + // the key made for it is kept even so, for the next renewal + expect(x.devicePublicKey).toBe(f.seen[0].json.DeviceInfo.DevicePublicKey) +}) + +test("Trae Global renews at /cloudide/… only", async () => { + f = fakeTrae("trae-global") + f.route(OLD, () => json({ Result: { Token: "jwt-2", RefreshToken: "r-2", TokenExpireAt: 2000000000 } })) + const hooks = await TraeGlobalAuthPlugin({ client: {} }) + const x = await hooks.auth.refresh(signedIn({ expires: Date.now() + 60_000 })) + expect(f.seen.map((r) => r.path)).toEqual(["/cloudide/api/v3/trae/oauth/ExchangeToken"]) + expect(x.access).toBe("jwt-2") +}) + +test("a sign-in's token is renewed for the device at once", async () => { + f = fakeTrae() + f.route(V3, () => json({ Result: { Token: "jwt-bound", RefreshToken: "r-1", TokenExpireAt: 2000000000 } })) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const a = await hooks.auth.methods[0].authorize() + const q = new URL(a.url).searchParams + const cb = new URL(q.get("auth_callback_url")) + cb.searchParams.set("userJwt", JSON.stringify({ Token: "jwt-1", RefreshToken: "r-1", TokenExpireAt: Math.floor(Date.now() / 1000) + 7200 })) + cb.searchParams.set("userInfo", JSON.stringify({ UserID: "u-1", ScreenName: "Ann" })) + await fetch(cb) + const got = await a.callback() + expect(got.type).toBe("success") + expect(got.access).toBe("jwt-bound") + expect(got.refresh).toBe("r-1") + expect(got.expires).toBe(2000000000 * 1000) + const r = f.seen.find((r) => r.path === "/trae/api/v3/oauth/ExchangeToken") + expect(r.headers.get("authorization")).toBe("Cloud-IDE-JWT jwt-1") + expect(r.json.DeviceInfo.DeviceID).toBe(q.get("device_id")) + expect(got.devicePublicKey).toBe(r.json.DeviceInfo.DevicePublicKey) + expect(signed(r)).toBe(true) +}) diff --git a/packages/trae/index.mjs b/packages/trae/index.mjs index f464c0d..e8f1293 100644 --- a/packages/trae/index.mjs +++ b/packages/trae/index.mjs @@ -9,7 +9,7 @@ // The account's fetch also sends Trae CN's own pages on api.trae.cn // (/trae/api/…) as the account, for magpie's daily check-in (每日签到: // /trae/api/v2/ug/checkin_credits/status, then /claim). -import { randomBytes, randomUUID, randomInt } from "node:crypto" +import { generateKeyPairSync, randomBytes, randomUUID, randomInt, sign } from "node:crypto" import { createServer, STATUS_CODES } from "node:http" const SITES = { @@ -35,6 +35,21 @@ const SITES = { api: "https://trae-api-cn.mchost.guru", // the models }, clientId: "ono9krqynydwx5", // Trae CN's IDE + // the clients' own renewal, which binds the JWT to a device: ExchangeToken + // under /trae/api/v3/oauth, signed with the device's P-256 key + // (DeviceProof). A JWT renewed at /cloudide/… carries no device, and + // Trae CN answers its check-in claim 9074 「当前参与用户太多」 every time, + // while the client's own token is let through (mintonight's side-by-side + // on yetone/magpie#808). Tried as TRAE SOLO CN first, the one + // qilimixingkong/trae-checkin found the server takes, then as Trae CN's + // IDE. It doesn't spend the refresh token. + deviceExchange: { + path: "/trae/api/v3/oauth/ExchangeToken", + as: [ + { clientId: "en1oxy7wnw8j9n", platform: "SOLO_PC", version: "0.1.64" }, + { clientId: "ono9krqynydwx5", platform: "IDE_PC", version: "3.3.99" }, + ], + }, appId: "6eefa01c-1036-4c7e-9ca5-d891f63bfcd8", ideVersion: "3.3.65", // named to the authorization page ideVersionCode: "20260401", @@ -220,7 +235,19 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) // device is the machine an account signs in from, made once at sign-in and // named to trae.cn's authorization page, then sent with every request: a // fresh one each time is what the relays saw requests dropped for. -const newDevice = () => ({ deviceId: digits(19), machineId: randomBytes(16).toString("hex") }) +const newDevice = () => ({ deviceId: digits(19), machineId: randomBytes(16).toString("hex"), ...newDeviceKey() }) + +// newDeviceKey is the device's key pair, an ECDSA P-256 one as the clients +// keep (iCubeAuthInfo://icube-dc:), whose public half goes with a +// renewal and whose private half signs it (DeviceProof). An account signed +// in before 0.2.3 has none and is given one at its next renewal. +function newDeviceKey() { + const { publicKey, privateKey } = generateKeyPairSync("ec", { namedCurve: "prime256v1" }) + return { + devicePublicKey: publicKey.export({ type: "spki", format: "pem" }), + devicePrivateKey: privateKey.export({ type: "pkcs8", format: "pem" }), + } +} // whenOf reads one of Trae's expiry times: seconds, milliseconds or ISO function whenOf(v) { @@ -270,6 +297,7 @@ function toAuth(s, site) { clientId: s.clientId || site.clientId, deviceId: s.deviceId, machineId: s.machineId, + ...(s.devicePrivateKey ? { devicePublicKey: s.devicePublicKey, devicePrivateKey: s.devicePrivateKey } : {}), // the model host the sign-in named, if it named one ...(site.modelHost(s.api) ? { api: s.api } : {}), ...(s.region ? { region: s.region } : {}), @@ -287,6 +315,8 @@ function fromAuth(auth, site) { clientId: auth.clientId || site.clientId, deviceId: auth.deviceId || "", machineId: auth.machineId || "", + devicePublicKey: auth.devicePublicKey || "", + devicePrivateKey: auth.devicePrivateKey || "", api: auth.api || "", region: site.regionOf(auth), } @@ -387,6 +417,92 @@ async function exchange(refresh, clientId, site, host = site.hosts.auth) { throw new Error(`${site.realm}: renewing the sign-in: ${statusLine(res.status)} ${msg}`.trim()) } +// proofOf is a renewal's DeviceProof: the device key's ECDSA-SHA256 +// signature (DER, base64) of the method, path, client, refresh token, time +// and nonce, one to a line, as the clients sign it +function proofOf(path, clientId, refresh, privateKey, at = Math.floor(Date.now() / 1000), nonce = randomBytes(16).toString("hex")) { + const text = ["POST", path, clientId, refresh, String(at), nonce].join("\n") + return { Signature: sign("sha256", Buffer.from(text), privateKey).toString("base64"), Timestamp: at, Nonce: nonce } +} + +// deviceInfo is the device a renewal names, its public key with it +function deviceInfo(a, as, site) { + return { + DeviceID: a.deviceId, + MachineID: a.machineId, + PlatformCode: as.platform, + DeviceType: "PC", + DeviceName: "", + DeviceModel: "", + ClientVersion: as.version, + DevicePublicKey: a.devicePublicKey, + DeviceBrand: site.brand, + DeviceCPU: "AMD", + OSInfo: "Windows", + OSVersion: "10.0.22631", + } +} + +// boundExchange renews the JWT as the clients do (site.deviceExchange), so +// that it is bound to the account's device; an account with no device key +// is given one first. It tries each client the site names, and throws the +// last answer when none takes it. +async function boundExchange(a, site, host = site.hosts.auth) { + const dx = site.deviceExchange + const d = a.devicePrivateKey && a.devicePublicKey ? a : { ...a, ...newDeviceKey() } + let last + for (const as of dx.as) { + let res + try { + res = await fetch(host.replace(/\/+$/, "") + dx.path, { + method: "POST", + headers: { "Content-Type": "application/json", ...(a.token ? { Authorization: `Cloud-IDE-JWT ${a.token}` } : {}) }, + body: JSON.stringify({ + ClientID: as.clientId, + ClientSecret: "", + RefreshToken: a.refresh, + DeviceInfo: deviceInfo(d, as, site), + DeviceProof: proofOf(dx.path, as.clientId, a.refresh, d.devicePrivateKey), + IDEVersion: as.version, + }), + signal: AbortSignal.timeout(20_000), + }) + } catch (e) { + last = new Error(`${site.realm}: renewing the sign-in for its device: ` + (e?.message ?? e)) + continue + } + const text = await res.text() + const v = parseJSON(text) + const r = v.Result ?? v.result ?? {} + const token = r.Token ?? r.token ?? "" + if (res.ok && token) { + return { + token, + refresh: r.RefreshToken ?? r.refreshToken ?? a.refresh, + expires: whenOf(r.TokenExpireAt ?? r.tokenExpireAt) || jwtExp(token), + devicePublicKey: d.devicePublicKey, + devicePrivateKey: d.devicePrivateKey, + } + } + const e = errorOf(text) + last = new Error(`${site.realm}: renewing the sign-in for its device: ${statusLine(res.status)} ${e.message || text.trim().slice(0, 200)}`.trim()) + } + throw last +} + +// renewal renews an account's JWT: bound to its device where the site can +// (boundExchange), else, or when Trae turns that away, at /cloudide/… as +// 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) + const keys = a.devicePrivateKey && a.devicePublicKey ? {} : newDeviceKey() + try { + return await boundExchange({ ...a, ...keys }, site) + } catch {} + return { ...(await exchange(a.refresh, a.clientId, site)), ...keys } +} + // ---- the browser sign-in -------------------------------------------------------- const page = (ok, title, text) => `${title} @@ -418,7 +534,16 @@ async function signedIn(q, device, site) { } 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`) - return { ...s, ...device } + s = { ...s, ...device } + // the token the page gives is bound to no device: it is renewed for this + // 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) + s = { ...s, token: x.token, refresh: x.refresh, expires: x.expires || s.expires } + } catch {} + } + return s } // browserSignIn is the IDE's sign-in: trae.cn's authorization page, back @@ -1451,8 +1576,9 @@ const makePlugin = (site) => async ({ client }) => { let r = renewing.get(key) if (!r) { r = (async () => { - const x = await exchange(a.refresh, a.clientId, site) + const x = await renewal(a, site) const got = { ...a, token: x.token, refresh: x.refresh, expires: x.expires || jwtExp(x.token) || Date.now() + DAY, clientId: x.clientId || a.clientId, renewed: true } + if (x.devicePrivateKey) Object.assign(got, { devicePublicKey: x.devicePublicKey, devicePrivateKey: x.devicePrivateKey }) renewed.set(a.uid || a.name, { was: a.refresh, got }) if (keep) await save(toAuth(got, site)) return got @@ -1465,10 +1591,11 @@ const makePlugin = (site) => async ({ client }) => { // fresh is the account with a token that has a while to go, renewed // when it hasn't const fresh = async (getAuth) => { - const a = fromAuth(await getAuth(), site) + let a = fromAuth(await getAuth(), site) if (!a) throw new Expired(`${site.realm}: not signed in`) - const last = renewed.get(a.uid || a.name) - if (last && last.was === a.refresh) return { ...last.got, renewed: false } + // a renewal the sign-in doesn't hold yet. A device-bound one keeps the + // refresh token, so the token tells it, and it is renewed in its turn + if (newerHere(a)) a = { ...renewed.get(a.uid || a.name).got, renewed: false } if (!a.expires || a.expires - Date.now() > EARLY_MS || !a.refresh) return a try { return await renew(a, true) @@ -1485,9 +1612,22 @@ const makePlugin = (site) => async ({ client }) => { const a = fromAuth(auth, site) if (!a || !a.refresh) return undefined const last = renewed.get(a.uid || a.name) - if (last && last.was === a.refresh) return { access: last.got.token, refresh: last.got.refresh, expires: last.got.expires } - const s = await renew(a, false) - return { access: s.token, refresh: s.refresh, expires: s.expires } + // a device key made for the account is kept with the sign-in + const out = (s) => ({ + access: s.token, + refresh: s.refresh, + expires: s.expires, + ...(s.devicePrivateKey && s.devicePrivateKey !== a.devicePrivateKey ? { devicePublicKey: s.devicePublicKey, devicePrivateKey: s.devicePrivateKey } : {}), + }) + if (newerHere(a)) return out(last.got) + return out(await renew(a, false)) + } + + // newerHere: this account was renewed here since the sign-in a was read + // from, to a token that runs longer + const newerHere = (a) => { + const last = renewed.get(a.uid || a.name) + return !!last && last.was === a.refresh && last.got.token !== a.token && (last.got.expires || 0) > (a.expires || 0) } // post asks one of Trae's JSON pages with the account @@ -1819,4 +1959,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, traeMessages, chatBody, credits, dollarUsageOf, whenOf, newDevice, SITES } +export const _internal = { HOSTS: SITES["trae-cn"].hosts, MODELS: SITES["trae-cn"].models, TextTools, NativeCalls, looseJSON, glmCall, toolNamed, traeMessages, chatBody, credits, dollarUsageOf, whenOf, newDevice, proofOf, SITES } diff --git a/packages/trae/package.json b/packages/trae/package.json index 0a5ddd2..f40d1e6 100644 --- a/packages/trae/package.json +++ b/packages/trae/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-trae-auth", - "version": "0.2.2", + "version": "0.2.3", "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", diff --git a/packages/trae/refresh.test.mjs b/packages/trae/refresh.test.mjs index 8ccdb36..85d3d71 100644 --- a/packages/trae/refresh.test.mjs +++ b/packages/trae/refresh.test.mjs @@ -22,7 +22,9 @@ test("auth.refresh exchanges the refresh token, once for two asking", async () = const auth = signedIn({ expires: Date.now() + 60_000 }) const [x, y] = await Promise.all([hooks.auth.refresh(auth), hooks.auth.refresh(auth)]) expect(n).toBe(1) - expect(x).toEqual({ access: "jwt-2", refresh: "r-2", expires: 2000000000 * 1000 }) + // the account had no device key: the one made for it comes back with it + expect(x).toMatchObject({ access: "jwt-2", refresh: "r-2", expires: 2000000000 * 1000 }) + expect(x.devicePublicKey).toContain("BEGIN PUBLIC KEY") expect(y).toEqual(x) // asked again with the sign-in from before, it gives the one it got expect(await hooks.auth.refresh(auth)).toEqual(x)