workbuddy 0.1.13: an enterprise account lists and uses the enterprise's models, not the personal plan's (#75, seavenlin)

WorkBuddy answers as the personal account unless a request names the
enterprise. Its own client (codebuddy.js in WorkBuddy.app: the auth
interceptor and buildAuthHeaders) sends X-Enterprise-Id and X-Tenant-Id,
both the account's enterpriseId, on every request; the plugin sent
neither, so /v3/config gave the personal plan's list.

- A browser sign-in keeps the enterpriseId /login/account names. When it
  names a non-personal type without one, the id is taken from
  /v2/plugin/accounts the way the client's mergeCurrentAccountDetails
  picks (same uid and type, else the one last signed in to).
- Desktop's sign-in reads account.enterpriseId from the app's file.
- sign() (chats, /v3/config), the usage meter and the token refresh carry
  the two headers; a personal account sends none.

Run: HOME=<tmp> bun test in packages/workbuddy, 60 pass (6 new). With the header
loop and the sign-in lookup removed by hand, 4 of the 6 new tests go red.
Not tried against a real enterprise account (none here); the field names
are the ones WorkBuddy's own client reads.
This commit is contained in:
yetone
2026-10-10 17:53:36 +08:00
parent cdbaff644a
commit 00b06db784
4 changed files with 142 additions and 3 deletions
+8
View File
@@ -43,6 +43,14 @@ included, doesn't mark the account, as the built-in never did; magpie
tries again later, and the old token is used meanwhile.
OpenCode doesn't call `auth.refresh`; the check before each request stays.
An enterprise (team) account is asked for as the enterprise. A browser
sign-in keeps the enterprise id WorkBuddy names for the account (from
`/login/account`, else its account list), and desktop's is read from the
app's file. Every request then carries `X-Enterprise-Id` and `X-Tenant-Id`,
as WorkBuddy's own client sends them; without them WorkBuddy answers as the
personal account, with the personal plan's models. A browser sign-in made
before 0.1.13 has no enterprise id kept: sign in again.
Desktop's sign-in is refreshed only when the app hasn't refreshed it
itself, and the new token is kept in memory, never written back, as magpie's
built-in WorkBuddy does.
+89
View File
@@ -0,0 +1,89 @@
// An enterprise (team) account is asked for as the enterprise, as
// WorkBuddy's own client asks: X-Enterprise-Id and X-Tenant-Id carry the
// account's enterpriseId on every request, or WorkBuddy answers as the
// personal account and lists the personal plan's models (#75).
import { afterEach, expect, test } from "bun:test"
import { WorkBuddyAuthPlugin, _internal } from "./index.mjs"
const real = globalThis.fetch
afterEach(() => (globalThis.fetch = real))
const site = _internal.SITES.workbuddy
const later = () => Date.now() + 3600_000
const config = '{"code":0,"data":{"agents":[{"name":"cli","models":["m"]}],"models":[{"id":"m","name":"M"}]}}'
const seen = (into) => async (url, init) => {
into.push({ url: String(url), headers: new Headers(init?.headers) })
return new Response(config)
}
test("an enterprise account's model list is asked for as the enterprise (#75)", async () => {
const got = []
globalThis.fetch = seen(got)
await _internal.liveModels(site, { access: "a", uid: "u", enterpriseId: "ent-1" })
expect(got[0].url).toEndWith("/v3/config")
expect(got[0].headers.get("X-Enterprise-Id")).toBe("ent-1")
expect(got[0].headers.get("X-Tenant-Id")).toBe("ent-1")
})
test("a personal account's list carries no enterprise", async () => {
const got = []
globalThis.fetch = seen(got)
await _internal.liveModels(site, { access: "a", uid: "u" })
expect(got[0].headers.has("X-Enterprise-Id")).toBe(false)
expect(got[0].headers.has("X-Tenant-Id")).toBe(false)
})
test("an enterprise account's chats carry the enterprise too", async () => {
const got = []
globalThis.fetch = seen(got)
const auth = { type: "oauth", access: "a", refresh: "r", expires: later(), uid: "u", enterpriseId: "ent-1" }
const hooks = await WorkBuddyAuthPlugin({ client: {} })
const opts = await hooks.auth.loader(async () => auth)
await opts.fetch("https://copilot.tencent.com/v2/chat/completions", { method: "POST", body: '{"messages":[]}' })
expect(got.at(-1).headers.get("X-Enterprise-Id")).toBe("ent-1")
expect(got.at(-1).headers.get("X-Tenant-Id")).toBe("ent-1")
})
// the sign-in, with WorkBuddy's answers as its own client reads them
const signIn = async (account, accounts) => {
const asked = []
globalThis.fetch = async (url, init) => {
const u = new URL(String(url))
asked.push(u.pathname)
const data =
u.pathname.endsWith("/auth/state") ? { state: "s", authUrl: "https://www.codebuddy.cn/login" }
: u.pathname.endsWith("/auth/token") ? { accessToken: "a", refreshToken: "r", expiresIn: 3600 }
: u.pathname.endsWith("/login/account") ? account
: u.pathname.endsWith("/accounts") ? { accounts }
: {}
return new Response(JSON.stringify({ code: 0, data }))
}
const flow = await _internal.browserSignIn(site)
return { result: await flow.callback(), asked }
}
test("signing in as an enterprise keeps the enterprise WorkBuddy named", async () => {
const { result, asked } = await signIn({ uid: "u", nickname: "n", type: "ultimate", enterpriseId: "ent-1" }, [])
expect(result.type).toBe("success")
expect(result.enterpriseId).toBe("ent-1")
expect(asked.some((p) => p.endsWith("/accounts"))).toBe(false)
})
test("an enterprise account named without its id is found in the account list", async () => {
const { result } = await signIn({ uid: "u", nickname: "n", type: "ultimate" }, [
{ uid: "u", type: "personal", lastLogin: false },
{ uid: "u", type: "ultimate", enterpriseId: "ent-2", lastLogin: true },
{ uid: "other", type: "ultimate", enterpriseId: "ent-3", lastLogin: true },
])
expect(result.enterpriseId).toBe("ent-2")
})
test("signing in as the personal account keeps no enterprise", async () => {
const { result, asked } = await signIn({ uid: "u", nickname: "n", type: "personal" }, [
{ uid: "u", type: "ultimate", enterpriseId: "ent-2", lastLogin: true },
])
expect(result.type).toBe("success")
expect("enterpriseId" in result).toBe(false)
expect(asked.some((p) => p.endsWith("/accounts"))).toBe(false)
})
+44 -2
View File
@@ -172,6 +172,7 @@ function renew(site, a, save) {
"X-Refresh-Token": a.refresh,
"X-Auth-Refresh-Source": "plugin",
"X-Domain": domainOf(site, a),
...enterpriseHeaders(a),
}, {})
if (!got?.accessToken) throw Object.assign(new Error("WorkBuddy gave no refreshed token"), { bare: true })
const next = merge(a, got)
@@ -259,10 +260,48 @@ function sign(site, a, headers) {
headers.set("X-Agent-Purpose", "conversation")
headers.set("X-IDE-Name", "WorkBuddy")
headers.set("X-IDE-Version", UA_VERSION)
for (const [k, v] of Object.entries(enterpriseHeaders(a))) headers.set(k, v)
if (!site.ai) return
headers.set("X-Agent-Type", "main")
}
// enterpriseHeaders names the enterprise (team) an account signed in as, as
// WorkBuddy's own client does on every request it makes for that account
// (its auth interceptor: X-Enterprise-Id and X-Tenant-Id, both the
// account's enterpriseId). Without them WorkBuddy answers as the personal
// account: /v3/config lists the personal plan's models and not the
// enterprise's (#75). A personal account has none and sends none.
function enterpriseHeaders(a) {
const id = typeof a?.enterpriseId === "string" ? a.enterpriseId.trim() : ""
return id ? { "X-Enterprise-Id": id, "X-Tenant-Id": id } : {}
}
// enterpriseOf is the enterprise the account a sign-in gave belongs to:
// the one /login/account names, else, for an account that isn't personal,
// the one WorkBuddy's account list has for it — the same choice WorkBuddy's
// own client makes (mergeCurrentAccountDetails): the uid's only entry of that
// type, or the only one it last signed in to. None found is personal.
async function enterpriseOf(site, a, who) {
const own = typeof who?.enterpriseId === "string" ? who.enterpriseId.trim() : ""
if (own) return own
const type = String(who?.type ?? "").trim().toLowerCase()
if (!type || type === "personal") return ""
let list
try {
list = await call(site, "GET", "/v2/plugin/accounts", {
Authorization: "Bearer " + a.access,
"X-Domain": domainOf(site, a),
})
} catch {
return ""
}
const mine = (list?.accounts ?? []).filter((x) => x?.uid === who.uid && typeof x.enterpriseId === "string" && x.enterpriseId.trim())
const same = mine.filter((x) => String(x.type ?? "").trim().toLowerCase() === type)
const last = mine.filter((x) => x.lastLogin)
const pick = same.length === 1 ? same[0] : last.length === 1 ? last[0] : mine.length === 1 ? mine[0] : undefined
return pick ? pick.enterpriseId.trim() : ""
}
// WorkBuddy's own client names each chat to its gateway four ways: the
// conversation it belongs to, the user send (turn) it answers, the message
// itself, and the request that carried it. Its backend counts a user send as
@@ -759,6 +798,7 @@ async function browserSignIn(site) {
"X-No-Enterprise-Id": "true",
}, [12151], deadline)
a.uid = who.uid ?? ""
a.enterpriseId = await enterpriseOf(site, a, who)
return success(site, a, who.nickname || who.phoneNumber || who.uid)
} catch (e) {
return { type: "failed", error: e.message }
@@ -776,6 +816,7 @@ function success(site, a, name) {
accountId: name || site.name,
uid: a.uid ?? "",
domain: a.domain ?? "",
...(a.enterpriseId ? { enterpriseId: a.enterpriseId } : {}),
...(a.refreshExpiresAt ? { refreshExpiresAt: a.refreshExpiresAt } : {}),
...(a.tokenType ? { tokenType: a.tokenType } : {}),
}
@@ -808,6 +849,7 @@ function readDesktop(site) {
domain: typeof t.domain === "string" ? t.domain : "",
tokenType: typeof t.tokenType === "string" ? t.tokenType : "",
uid: acct.uid,
...(typeof acct.enterpriseId === "string" && acct.enterpriseId.trim() ? { enterpriseId: acct.enterpriseId.trim() } : {}),
name: acct.nickname || acct.phoneNumber || acct.uid,
}
} catch {
@@ -880,7 +922,7 @@ async function meter(site, a, path) {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": "WorkBuddy/" + UA_VERSION,
Authorization: "Bearer " + a.access, "X-User-Id": a.uid ?? "", "X-Domain": domainOf(site, a), "X-Product": "SaaS",
"X-IDE-Type": "WorkBuddy" },
"X-IDE-Type": "WorkBuddy", ...enterpriseHeaders(a) },
body: "{}",
signal: AbortSignal.timeout(20000),
})
@@ -1216,4 +1258,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy)
export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"])
// for tests
export const _internal = { withSystem, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf }
export const _internal = { enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf }
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-workbuddy-auth",
"version": "0.1.12",
"version": "0.1.13",
"description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)",
"type": "module",
"main": "./index.mjs",