Files
plugins/packages/workbuddy/apikey.test.mjs
T
yetone b2fe48ea2e workbuddy 0.1.40: chats carry the current desktop client's headers
WorkBuddy accounts are being restricted, and a report says WorkBuddy now
checks request-header fingerprints. Diffed the plugin's chat request
against each build's current desktop app, read (never run) from the
update feeds on 2026-10-28:
- China: WorkBuddy 5.9.3.42398134 (copilot.tencent.com/v2/update),
  bundled @genie/agent-cli 2.165.0.
- WorkBuddy AI: 5.8.4.41366630 (www.workbuddy.ai/v2/update), CLI 2.161.0.
The chat is the CLI's OpenAI client (openai 6.25.0) through
axiosToFetchAdapter, with UserAgentHttpInterceptor and the desktop's
CLIENT_INFO_* env (sidecar-manager getCachedBaseEnv).

What differed, and now matches:
- User-Agent: was WorkBuddy/5.5.6; the client sends
  "WorkBuddy/<app> <applicationName>/<app> CLI/<cli>":
  WorkBuddy/5.9.3 WorkBuddy/5.9.3 CLI/2.165.0 (China),
  WorkBuddy/5.8.4 workbuddy-ai/5.8.4 CLI/2.161.0 (AI). The /v3/config
  models call (was CLI/2.0.0 WorkBuddy/5.5.6) takes the same one, as the
  CLI's CloudProductProvider sends it through the same interceptor.
- X-IDE-Version: was 5.5.6; now the app's version.
- X-Agent-Type: main was sent on WorkBuddy AI only; the adapter sets it on
  every model call on both builds.
- X-Agent-Runtime: local-agent, new in 5.9 (the desktop's local transport
  puts agentRuntime local-agent in the prompt meta); China build only,
  5.8.4 has no such header.
- Accept: application/json and the OpenAI SDK's X-Stainless-* (Lang js,
  Package-Version 6.25.0, OS/Arch of this machine, Runtime node,
  Runtime-Version v22.21.1 = Electron 37.10.3's Node, Retry-Count 0,
  Timeout 1200); the adapter strips them only in its skip-auth mode.
- The desktop's own calls (billing, plugin API) send WorkBuddy/<app>;
  they now send the current app version instead of 5.5.6.

Not matched: X-Device-Token (TuringShield native SDK, sent since at
least 5.6.2), traceparent (only while server-side tracing is enabled),
and transport-level differences (Bun's fetch vs axios on Node: header
order, Accept-Encoding).

Run: HOME=$(mktemp -d) bun test packages/workbuddy: 184 pass, 0 fail.
With the old index.mjs the 4 changed tests fail (UA, IDE version,
config UA, the new per-build header test).
Not tried: a real account's chat or /v3/config with the new
User-Agent (unauthenticated /v3/config answers the same for old and new).
No text added names magpie or WorkBuddy's limits.
2026-10-28 03:20:46 +08:00

137 lines
6.5 KiB
JavaScript

// An API key made at the build's /profile/keys page (plugins#407) is sent as
// WorkBuddy's own CLI sends CODEBUDDY_API_KEY (@tencent-ai/codebuddy-code
// 2.177.0): X-API-Key and Authorization: Bearer, both the key, X-User-Id
// "anonymous_" and the key's last eight characters, no X-Domain, to the
// build's own host. The browser and desktop sign-ins are unchanged. Every
// fetch here is a fake; nothing reaches the network.
import { afterEach, expect, test } from "bun:test"
import { WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal } from "./index.mjs"
const real = globalThis.fetch
afterEach(() => (globalThis.fetch = real))
const KEY = "ck_test0000000000abcdefgh"
const OK = () => new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } })
// record answers each fetch with reply and keeps the URL and headers sent
function record(reply = OK) {
const sent = []
globalThis.fetch = async (url, init) => {
sent.push({ url: String(url), headers: new Headers(init?.headers) })
return reply(String(url))
}
return sent
}
const chat = (opts, url) =>
opts.fetch(url, {
method: "POST",
// what an SDK given apiKey "" sends: an empty key header and Bearer
headers: { authorization: "Bearer ", "x-api-key": "" },
body: JSON.stringify({ model: "glm-5.3", stream: true, messages: [{ role: "user", content: "hi" }] }),
})
for (const [plugin, site, url] of [
[WorkBuddyAuthPlugin, "workbuddy", "https://copilot.tencent.com/v2/chat/completions"],
[WorkBuddyAIAuthPlugin, "workbuddy-ai", "https://www.workbuddy.ai/v2/chat/completions"],
]) {
test(`${site}: offers an API key sign-in beside the browser and desktop ones`, async () => {
const hooks = await plugin({ client: {} })
const ms = hooks.auth.methods
expect(ms.map((m) => m.type)).toEqual(["oauth", "oauth", "api"])
const name = _internal.SITES[site].name
expect(ms[2].label).toBe(`${name} API key`)
expect(ms[2].placeholder).toContain(site === "workbuddy" ? "www.workbuddy.cn/profile/keys" : "www.workbuddy.ai/profile/keys")
expect(ms[0].label).toBe(`${name} account (browser)`)
expect(ms[1].label).toBe(`${name} desktop's sign-in`)
})
test(`${site}: a key's chat carries X-API-Key and Bearer to ${new URL(url).host}`, async () => {
const sent = record()
const hooks = await plugin({ client: {} })
// the provider's own api is where a model's chat goes
const cfg = { provider: {} }
await hooks.config(cfg)
expect(cfg.provider[site].api + "/chat/completions").toBe(url)
const opts = await hooks.auth.loader(async () => ({ type: "api", key: KEY }))
expect(typeof opts.fetch).toBe("function")
const res = await chat(opts, url)
expect(res.status).toBe(200)
expect(sent).toHaveLength(1)
const h = sent[0].headers
expect(sent[0].url).toBe(url)
expect(h.get("x-api-key")).toBe(KEY)
expect(h.get("authorization")).toBe("Bearer " + KEY)
expect(h.get("x-user-id")).toBe("anonymous_abcdefgh")
expect(h.has("x-domain")).toBe(false)
expect(h.has("x-enterprise-id")).toBe(false)
expect(h.get("user-agent")).toMatch(/^WorkBuddy\//)
expect(h.get("x-product")).toBe("SaaS")
})
test(`${site}: a browser sign-in's chat is as before, no X-API-Key`, async () => {
const sent = record()
const hooks = await plugin({ client: {} })
const opts = await hooks.auth.loader(async () => ({ type: "oauth", access: "tok", refresh: "r", uid: "u1", expires: Date.now() + 3600_000 }))
await chat(opts, url)
const h = sent[0].headers
expect(sent[0].url).toBe(url)
expect(h.get("authorization")).toBe("Bearer tok")
expect(h.has("x-api-key")).toBe(false)
expect(h.get("x-user-id")).toBe("u1")
expect(h.get("x-domain")).toBe(new URL(url).host)
})
test(`${site}: a refused key is a 401 that says to check the key, never a refresh`, async () => {
const sent = record(() => new Response('{"code":401}', { status: 401, headers: { "www-authenticate": 'Bearer realm="copilot", error="invalid_token"' } }))
const hooks = await plugin({ client: {} })
const opts = await hooks.auth.loader(async () => ({ type: "api", key: KEY }))
const res = await chat(opts, url)
expect(res.status).toBe(401)
expect(sent).toHaveLength(1) // no refresh asked, no second send
expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired")
const { error } = await res.json()
expect(error.message).toContain("refused this API key (401)")
expect(error.message).toContain(site === "workbuddy" ? "https://www.workbuddy.cn/profile/keys" : "https://www.workbuddy.ai/profile/keys")
})
test(`${site}: a key's credits are unknown, asked of nothing`, async () => {
const sent = record(() => new Response("{}", { status: 500 }))
const hooks = await plugin({ client: {} })
const u = await hooks.auth.usage(async () => ({ type: "api", key: KEY }))
expect(sent).toHaveLength(0)
expect(u.signIn).toBe("kept")
expect(u.error).toContain("credits unknown")
expect(u.windows).toBeUndefined()
})
}
// /v3/config is asked with a key only as the CLI asks it: for ck_ and pt_
// keys (shouldLoadRemoteConfig); any other key keeps the built-in list
test("models: a ck_ key asks /v3/config with the key's headers, another key asks nothing", async () => {
const sent = record(() =>
Response.json({ code: 0, data: { agents: [{ name: "cli", models: ["glm-9"] }], models: [{ id: "glm-9", name: "GLM-9", maxInputTokens: 1000, maxOutputTokens: 100 }] } }),
)
const hooks = await WorkBuddyAuthPlugin({ client: {} })
const provider = { id: "workbuddy", models: { builtin: { id: "builtin" } } }
const got = await hooks.provider.models(provider, { auth: { type: "api", key: KEY } })
expect(sent).toHaveLength(1)
expect(sent[0].url).toBe("https://copilot.tencent.com/v3/config")
expect(sent[0].headers.get("x-api-key")).toBe(KEY)
expect(sent[0].headers.get("authorization")).toBe("Bearer " + KEY)
// the CLI asks it with its own User-Agent (CLI/<v> in it picks the cli list)
expect(sent[0].headers.get("user-agent")).toBe("WorkBuddy/5.9.3 WorkBuddy/5.9.3 CLI/2.165.0")
expect(Object.keys(got)).toEqual(["glm-9"])
const other = await hooks.provider.models(provider, { auth: { type: "api", key: "sk-something-else" } })
expect(sent).toHaveLength(1)
expect(other).toBe(provider.models)
})
test("an empty key is not signed in", async () => {
record()
const hooks = await WorkBuddyAIAuthPlugin({ client: {} })
const opts = await hooks.auth.loader(async () => ({ type: "api", key: " " }))
await expect(chat(opts, "https://www.workbuddy.ai/v2/chat/completions")).rejects.toThrow("isn't signed in")
})