trae 0.2.14: the account Trae CN's own client is signed in as checks in on the client's device, not one the plugin made up (yetone/magpie#1920)

On one account Trae CN's desktop client's claim went through while the
plugin's, on a device id it had made up (digits(19)) with a hard-coded
brand and OS, came back 9074 every day (MiFaZhan on yetone/magpie#808;
aliceh1 on #1920, where Buddy Switch reads the local client). Now, for a
check-in (/trae/api/v2/ug/*) only, the account whose uid matches the
userId of this machine's Trae CN client sends the client's own device id,
the one Trae's device service registered: the digits in the client's
storage.json key iCubeAuthInfo://icube-dc:<id> (seen in real clients'
files, #808 and #1705). x-device-type and x-os-version are this machine's
(Windows' product name, else its build; elsewhere the kernel release),
and no brand is sent, as the client's fb leaves it out with no model.

The uid comes from the client's sign-in envelope
(iCubeAuthInfo://icube.cloudide), plain JSON or the client's fixed
AES-128-CBC codec, read as dingminhua/dsh-connect-trae (MIT) reads it;
only userId is looked at, the client's token is never used. The file is
only read, never written. Every other account keeps its own device; a
missing or unreadable file, one that can't be made out, a failed
integrity check, or zero or several icube-dc keys change nothing. No id
is made up, changed or rotated (the owner's ruling on #1705 stands).

Ran: bun test in packages/trae, 140 pass (11 new in ownclient.test.mjs);
bun scripts/check.mjs trae ok. Broken by hand: matching every account
instead of the client's uid fails "an account the client isn't signed in
as keeps its own device"; not passing the client's device to ugHeaders
fails the two matched-account tests. Tests never read this machine's
client (fake.mjs points ownClient.paths at nothing). Not tried: a real
Trae CN client or account (none here), so whether the claim now goes
through for the matched account is unproven; the Linux paths are guesses.
This commit is contained in:
yetone
2026-10-15 16:57:55 +08:00
parent 8c4bf5cc72
commit 2009f49751
5 changed files with 317 additions and 10 deletions
+21 -2
View File
@@ -288,10 +288,29 @@ answered it 9074 even with the client's headers.
`checked_in`, `credits`.
- **Claim:** `POST api.trae.cn/trae/api/v2/ug/checkin_credits/claim`,
the same, only while it is on and today's isn't in.
- **The device, when Trae CN's own client is here (0.2.14):** the
account this machine's Trae CN desktop client is signed in as checks in
on the client's own device, the one Trae's device service registered:
`x-device-id` is the id in the client's
`globalStorage/storage.json` key `iCubeAuthInfo://icube-dc:<id>`,
`x-device-type` and `x-os-version` are this machine's, and no
`x-device-brand` is sent. The account is matched by the `userId` in the
client's sign-in (`iCubeAuthInfo://icube.cloudide`, plain JSON or the
client's fixed codec, as dingminhua/dsh-connect-trae reads it). The file
is only read: nothing in it is written, and the client's token is never
used. On one account the client's claim went through while the
plugin's, on its own device, got 9074 (yetone/magpie#808, #1920); that
this header is what changes it hasn't been tried on a real account
yet. Every other account keeps its own device, and a file that can't be
read or made out, or holds no single device, changes nothing. Files:
macOS `~/Library/Application Support/Trae CN/…`, Windows
`%APPDATA%\Trae CN\…` (or `trae-cn`), Linux `~/.config/trae-cn/…`
(or `Trae CN`; not seen on a real Linux install).
- **What comes back:** Trae's answer as it is. A 401 or code 1001 marks
the account for a new sign-in. Code 9095 means this device has checked
in today; nothing sends another device id to get round it, nor to get
round a 9074.
in today. No device id is ever made up, changed or rotated to get round
a 9095 or a 9074, and no account is given a device that isn't its
own client's.
Only `api.trae.cn`'s `/trae/api/` pages are sent this way; any other URL
that isn't a chat request is still refused (400). Needs 0.1.4 or later.
+4
View File
@@ -8,6 +8,10 @@ import { _internal } from "./index.mjs"
const HOST_KEYS = ["web", "auth", "api", "us", "pay", "usPay"]
// no test reads this machine's own Trae CN client: one that wants a
// client points ownClient.paths at a file of its own
_internal.ownClient.paths = () => []
export function fakeTrae(siteId = "trae-cn") {
const routes = new Map()
const seen = []
+133 -7
View File
@@ -9,8 +9,11 @@
// 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 { createHash, generateKeyPairSync, randomBytes, randomUUID, randomInt, sign } from "node:crypto"
import { createDecipheriv, createHash, generateKeyPairSync, randomBytes, randomUUID, randomInt, sign } from "node:crypto"
import { readFile } from "node:fs/promises"
import { createServer, STATUS_CODES } from "node:http"
import { homedir, release, version as osVersion } from "node:os"
import { join } from "node:path"
const SITES = {
// Trae CN (trae.cn): the authorization page sends the browser back to a
@@ -739,9 +742,12 @@ const ugUA = (site) =>
// ugHeaders are the headers Trae CN's IDE (3.3.104) sends a growth page
// with, and only those: its JWT, then its device (fb: x-device-id,
// x-device-brand, x-device-type, x-os-version, x-app-version), not the
// chat's tokens and versions.
function ugHeaders(a, site, extra = {}) {
return {
// chat's tokens and versions. own is this machine's Trae CN client, when
// it is signed in as this very account (ownClient): its device id and
// this machine's OS go instead of the account's, and no brand is named
// (fb leaves it out when it has no model to name).
function ugHeaders(a, site, extra = {}, own) {
const h = {
"Content-Type": "application/json",
Authorization: `Cloud-IDE-JWT ${a.token}`,
"User-Agent": ugUA(site),
@@ -750,8 +756,121 @@ function ugHeaders(a, site, extra = {}) {
"x-device-type": "Windows",
"x-os-version": "10.0.22631",
"x-app-version": site.clientVersion,
...extra,
}
if (own) {
h["x-device-id"] = own.deviceId
h["x-device-type"] = own.type
h["x-os-version"] = own.os
delete h["x-device-brand"]
}
return { ...h, ...extra }
}
// ---- this machine's own Trae CN client ----------------------------------------------
// Trae CN's desktop client keeps its state in a VS Code-style
// globalStorage/storage.json. The device id Trae's device service gave
// it is in a key's name, iCubeAuthInfo://icube-dc:<digits> (15 or 16
// digits seen); its sign-in is the value of iCubeAuthInfo://icube.cloudide,
// a JSON envelope (userId, token, …) stored as is or obfuscated with the
// client's fixed AES-128-CBC codec. Seen in real clients' files
// (yetone/magpie#808: the same id in the client's own did= query;
// yetone/magpie#1705) and read the same way by dingminhua/dsh-connect-trae
// (MIT), whose codec this is.
const DC_KEY = "iCubeAuthInfo://icube-dc:"
const AUTH_KEY = "iCubeAuthInfo://icube.cloudide"
// ownClient.paths are where storage.json may be, in order; tests replace it
const ownClient = {
paths: () => clientStoragePaths(process.platform, homedir(), process.env),
}
function clientStoragePaths(platform, home, env) {
const file = (root, name) => join(root, name, "User", "globalStorage", "storage.json")
if (platform === "darwin") return [file(join(home, "Library", "Application Support"), "Trae CN")]
if (platform === "win32") {
const roots = [env.APPDATA, join(home, "AppData", "Roaming")].filter((r, i, all) => r && all.indexOf(r) === i)
return roots.flatMap((r) => ["Trae CN", "trae-cn"].map((n) => file(r, n)))
}
if (platform === "linux") return ["trae-cn", "Trae CN"].map((n) => file(env.XDG_CONFIG_HOME || join(home, ".config"), n))
return []
}
// clientDevice is the device id of this machine's Trae CN client when the
// client is signed in as uid, else undefined. It only reads: nothing of
// the client's is written, kept or sent but that id, and the client's own
// token is read past, never used. A file it can't read or make out, or one
// with no single device, names no device, and the account keeps its own.
// Never an id made up or changed: an account the client isn't signed in
// as never gets the client's id.
async function clientDevice(uid) {
if (!uid) return undefined
for (const p of ownClient.paths()) {
let text
try {
text = await readFile(p, "utf8")
} catch {
continue // not installed here
}
try {
const doc = JSON.parse(text)
const ids = Object.keys(doc ?? {}).filter((k) => k.startsWith(DC_KEY)).map((k) => k.slice(DC_KEY.length))
if (ids.length !== 1 || !/^\d{8,20}$/.test(ids[0])) return undefined
const who = clientAuth(doc[AUTH_KEY])?.userId
return who != null && String(who) === String(uid) ? ids[0] : undefined
} catch {
return undefined
}
}
return undefined
}
// clientAuth is the client's sign-in envelope, as stored or decoded
function clientAuth(v) {
if (typeof v !== "string" || !v.trim()) return undefined
const t = v.trim()
return JSON.parse(t.startsWith("{") ? t : clientDecode(t))
}
const xorOf = (a, b) => Buffer.from(a.map((x, i) => x ^ b[i]))
const CODEC = {
"746305100000": xorOf(
[82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37],
[31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125],
),
"123920200203": xorOf(
[191, 192, 216, 250, 122, 246, 220, 97, 31, 254, 98, 27, 8, 72, 71, 176, 135, 99, 96, 18, 127, 101, 203, 104, 211, 102, 191, 125, 37, 72, 150, 156, 51, 229, 121, 35, 17, 153, 141, 177, 110, 131, 150, 128, 172, 255, 254, 6, 18, 140, 55, 62, 236, 249, 135, 64, 135, 12, 117, 4, 89, 149, 168, 209],
[246, 204, 26, 232, 232, 70, 129, 109, 223, 146, 169, 242, 23, 241, 105, 145, 50, 196, 165, 42, 254, 120, 3, 54, 244, 207, 209, 85, 53, 6, 138, 106, 175, 148, 31, 204, 186, 186, 165, 182, 87, 142, 49, 10, 39, 110, 26, 154, 86, 56, 173, 125, 18, 64, 198, 225, 99, 99, 83, 82, 191, 134, 76, 170],
),
}
// clientDecode undoes the client's codec: a 6-byte header naming the salt,
// 32 random bytes, then AES-128-CBC under sha512(sha512(random) + salt);
// the plaintext is led by its own sha512, which is checked
function clientDecode(b64) {
const buf = Buffer.from(b64, "base64")
const salt = CODEC[buf.subarray(0, 6).toString("hex")]
if (!salt || buf.length <= 102) throw new Error("not the client's codec")
const key = createHash("sha512").update(Buffer.concat([createHash("sha512").update(buf.subarray(6, 38)).digest(), salt])).digest()
const d = createDecipheriv("aes-128-cbc", key.subarray(0, 16), key.subarray(16, 32))
const out = Buffer.concat([d.update(buf.subarray(38)), d.final()])
const body = out.subarray(64)
if (out.length < 64 || !createHash("sha512").update(body).digest().equals(out.subarray(0, 64))) throw new Error("the client's value doesn't check")
return body.toString("utf8")
}
// thisMachine is how the client names this machine's OS: its type, and
// the OS's own version (Windows' product name, as "Windows 11 Home China"
// was seen, else its build; elsewhere the kernel's release)
function thisMachine(platform = process.platform) {
if (platform === "win32") {
let v = ""
try {
v = osVersion()
} catch {}
return { type: "windows", os: /^Windows \d/.test(v) ? v : `Windows ${release()}` }
}
return { type: platform === "darwin" ? "mac" : platform, os: `${platform === "darwin" ? "macOS" : platform} ${release()}` }
}
// ugPage: url is one of Trae's growth pages (the check-in)
@@ -2328,9 +2447,16 @@ const makePlugin = (site) => async ({ client }) => {
const ug = ugPage(url)
let sent = method === "GET" || method === "HEAD" ? undefined : typeof body === "string" ? body : "{}"
if (ug && sent !== undefined && /^\s*(\{\s*\})?\s*$/.test(sent)) sent = JSON.stringify({ req_source: 1 })
// the account this machine's own Trae CN client is signed in as checks
// in on the client's device, the one Trae registered: on one account
// the client's own claim went through while the plugin's, on a device
// it had made up, came back 9074 (yetone/magpie#808, #1920). Every
// other account keeps its own device; none is given the client's.
const deviceId = ug && site.id === "trae-cn" ? await clientDevice(a.uid) : undefined
const own = deviceId ? { deviceId, ...thisMachine() } : undefined
const res = await fetch(url, {
method,
headers: ug ? ugHeaders(a, site, { Accept: "application/json" }) : ideHeaders(a, site, { Accept: "application/json" }),
headers: ug ? ugHeaders(a, site, { Accept: "application/json" }, own) : ideHeaders(a, site, { Accept: "application/json" }),
body: sent,
signal: signal ?? AbortSignal.timeout(20_000),
})
@@ -2683,4 +2809,4 @@ const makePlugin = (site) => async ({ client }) => {
export const TraeCNAuthPlugin = makePlugin(SITES["trae-cn"])
export const TraeGlobalAuthPlugin = makePlugin(SITES["trae-global"])
export const _internal = { traeHost, accountOf, HOSTS: SITES["trae-cn"].hosts, MODELS: SITES["trae-cn"].models, TextTools, NativeCalls, looseJSON, glmCall, nameCall, toolNamed, unwrapped, traeMessages, chatBody, credits, dollarUsageOf, whenOf, newDevice, proofOf, SITES, SESSION, conversationID }
export const _internal = { ownClient, clientStoragePaths, clientDevice, clientDecode, thisMachine, traeHost, accountOf, HOSTS: SITES["trae-cn"].hosts, MODELS: SITES["trae-cn"].models, TextTools, NativeCalls, looseJSON, glmCall, nameCall, toolNamed, unwrapped, traeMessages, chatBody, credits, dollarUsageOf, whenOf, newDevice, proofOf, SITES, SESSION, conversationID }
+158
View File
@@ -0,0 +1,158 @@
// The account this machine's own Trae CN client is signed in as checks in
// on the client's device id, read from the client's storage.json and
// never written; every other account keeps its own (yetone/magpie#1920).
import "./nonet.mjs"
import { afterEach, beforeEach, expect, test } from "bun:test"
import { createCipheriv, createHash, randomBytes } from "node:crypto"
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { TraeCNAuthPlugin, _internal } from "./index.mjs"
import { fakeTrae, json, signedIn } from "./fake.mjs"
const DC = "1234567890123456" // the client's: 16 digits, as #808's
let f, dir, file
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "trae-own-"))
file = join(dir, "storage.json")
_internal.ownClient.paths = () => [join(dir, "missing.json"), file]
})
afterEach(() => {
f?.close()
f = undefined
_internal.ownClient.paths = () => []
rmSync(dir, { recursive: true, force: true })
})
// encode is the client's codec run forwards, the inverse of clientDecode
function encode(text, header = "746305100000") {
const salt = header === "746305100000"
? xor([82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37],
[31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125])
: undefined
const random = randomBytes(32)
const key = createHash("sha512").update(Buffer.concat([createHash("sha512").update(random).digest(), salt])).digest()
const body = Buffer.from(text, "utf8")
const c = createCipheriv("aes-128-cbc", key.subarray(0, 16), key.subarray(16, 32))
const enc = Buffer.concat([c.update(Buffer.concat([createHash("sha512").update(body).digest(), body])), c.final()])
return Buffer.concat([Buffer.from(header, "hex"), random, enc]).toString("base64")
}
const xor = (a, b) => Buffer.from(a.map((x, i) => x ^ b[i]))
function client(userId, { encoded = true, dcs = [DC] } = {}) {
const auth = JSON.stringify({ token: "client-jwt", refreshToken: "client-refresh", userId, host: "https://api.trae.cn" })
const doc = { "telemetry.machineId": "m".repeat(64), [`iCubeAuthInfo://icube.cloudide`]: encoded ? encode(auth) : auth }
for (const d of dcs) doc[`iCubeAuthInfo://icube-dc:${d}`] = "device-key-pair"
writeFileSync(file, JSON.stringify(doc))
}
async function checkIn(auth = signedIn()) {
f = fakeTrae()
f.route("POST /trae/api/v2/ug/checkin_credits/claim", () => json({ code: 0 }))
f.route("POST /trae/api/v2/pay/ide_user_ent_usage", () => json({ code: 0 }))
const o = await (await TraeCNAuthPlugin({ client: {} })).auth.loader(async () => auth)
await o.fetch(f.origin + "/trae/api/v2/ug/checkin_credits/claim", { method: "POST", body: "{}" })
return f.seen.at(-1).headers
}
const plugins = (h) => {
expect(h.get("x-device-id")).toBe("1234567890123456789")
expect(h.get("x-device-brand")).toBeTruthy()
expect(h.get("x-device-type")).toBe("Windows")
expect(h.get("x-os-version")).toBe("10.0.22631")
}
test("the account the client is signed in as checks in on the client's device and this machine's OS", async () => {
client("u-1")
const before = readFileSync(file, "utf8")
const mtime = statSync(file).mtimeMs
const h = await checkIn()
expect(h.get("x-device-id")).toBe(DC)
expect(h.has("x-device-brand")).toBe(false)
const m = _internal.thisMachine()
expect(h.get("x-device-type")).toBe(m.type)
expect(h.get("x-os-version")).toBe(m.os)
// the account's own token, never the client's
expect(h.get("authorization")).toBe("Cloud-IDE-JWT jwt-1")
expect(h.get("x-app-version")).toBe("0.1.69")
// read, never written
expect(readFileSync(file, "utf8")).toBe(before)
expect(statSync(file).mtimeMs).toBe(mtime)
})
test("a client's sign-in stored as plain JSON is read too", async () => {
client("u-1", { encoded: false })
expect((await checkIn()).get("x-device-id")).toBe(DC)
})
test("an account the client isn't signed in as keeps its own device", async () => {
client("someone-else")
plugins(await checkIn())
})
test("an account with no uid keeps its own device", async () => {
client("")
plugins(await checkIn(signedIn({ uid: "" })))
})
test("a client with no single device names none", async () => {
client("u-1", { dcs: [] })
plugins(await checkIn())
client("u-1", { dcs: [DC, "6543210987654321"] })
plugins(await checkIn())
client("u-1", { dcs: ["not-digits"] })
plugins(await checkIn())
})
test("a client file that can't be made out names no device", async () => {
writeFileSync(file, "{not json")
plugins(await checkIn())
writeFileSync(file, JSON.stringify({ [`iCubeAuthInfo://icube-dc:${DC}`]: "x", "iCubeAuthInfo://icube.cloudide": "dGFtcGVyZWQ=" + "A".repeat(200) }))
plugins(await checkIn())
// a value whose check fails (one byte changed) is not read as anyone
const bad = Buffer.from(encode(JSON.stringify({ userId: "u-1" })), "base64")
bad[bad.length - 20] ^= 1
writeFileSync(file, JSON.stringify({ [`iCubeAuthInfo://icube-dc:${DC}`]: "x", "iCubeAuthInfo://icube.cloudide": bad.toString("base64") }))
plugins(await checkIn())
})
test("no client on this machine: the account's own device, as before", async () => {
plugins(await checkIn())
})
test("only the check-in goes on the client's device; the chat's pages keep the account's", async () => {
client("u-1")
f = fakeTrae()
f.route("POST /trae/api/v2/pay/ide_user_ent_usage", () => json({ code: 0 }))
const o = await (await TraeCNAuthPlugin({ client: {} })).auth.loader(async () => signedIn())
await o.fetch(f.origin + "/trae/api/v2/pay/ide_user_ent_usage", { method: "POST", body: "{}" })
expect(f.seen[0].headers.get("x-device-id")).toBe("1234567890123456789")
})
test("the client's codec decodes what it encodes, and refuses another header", () => {
expect(_internal.clientDecode(encode('{"userId":"7"}'))).toBe('{"userId":"7"}')
expect(() => _internal.clientDecode(Buffer.concat([Buffer.from("000000000000", "hex"), randomBytes(120)]).toString("base64"))).toThrow()
})
test("where each OS keeps the client's storage.json", () => {
const p = _internal.clientStoragePaths
expect(p("darwin", "/Users/a", {})).toEqual(["/Users/a/Library/Application Support/Trae CN/User/globalStorage/storage.json"])
const w = p("win32", "/h", { APPDATA: "/h/Roam" })
expect(w).toEqual([
"/h/Roam/Trae CN/User/globalStorage/storage.json",
"/h/Roam/trae-cn/User/globalStorage/storage.json",
"/h/AppData/Roaming/Trae CN/User/globalStorage/storage.json",
"/h/AppData/Roaming/trae-cn/User/globalStorage/storage.json",
])
expect(p("linux", "/home/a", {})[0]).toBe("/home/a/.config/trae-cn/User/globalStorage/storage.json")
expect(p("linux", "/home/a", { XDG_CONFIG_HOME: "/x" })[0]).toBe("/x/trae-cn/User/globalStorage/storage.json")
})
test("this machine's OS as the client names it", () => {
const w = _internal.thisMachine("win32")
expect(w.type).toBe("windows")
expect(w.os).toMatch(/^Windows /)
expect(_internal.thisMachine("darwin")).toEqual({ type: "mac", os: expect.stringMatching(/^macOS \d/) })
expect(_internal.thisMachine("linux").type).toBe("linux")
})
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-trae-auth",
"version": "0.2.13",
"version": "0.2.14",
"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",