workbuddy 0.1.37: sign in with an API key (#407)
Both builds offer "<build> API key" beside the browser and desktop
sign-ins, for a key made on the build's keys page
(www.workbuddy.cn/profile/keys, www.workbuddy.ai/profile/keys).
A key is sent as WorkBuddy's own CLI sends CODEBUDDY_API_KEY
(@tencent-ai/codebuddy-code 2.177.0, read as data): its API-key
session has the key as the access token, uid "anonymous_" + the key's
last 8 characters, personal, no domain, no enterprise; model requests
carry X-API-Key: <key> and Authorization: Bearer <key>
(getCustomHeaders). So a key's chat has those, X-User-Id
anonymous_<last8>, no X-Domain, and the client headers the other
sign-ins send, to the same host: copilot.tencent.com/v2 for workbuddy
(the CLI's endpoint for CODEBUDDY_INTERNET_ENVIRONMENT=internal; it
treats www.workbuddy.cn and copilot.tencent.com as front doors of one
API) and www.workbuddy.ai/v2 for workbuddy-ai.
The loader's apiKey "" and x-api-key delete stay: they keep the SDK's
own (empty) key headers off; sign() now sets X-API-Key itself for a
key account and never for an OAuth one.
- Models: /v3/config is asked with a key only for ck_/pt_ keys, as the
CLI's shouldLoadRemoteConfig does; any other key keeps the built-in
list.
- Usage: a key's card says the credits are unknown and asks nothing
(the CLI reads no credits with a key; no endpoint guessed).
- A 401 on a key is never renewed or resent: it says the key was
refused and where to check it, marked expired only on
invalid_token. The >2 MiB reset probe doesn't ask the billing API
with a key.
Run at this tree (base ac11dcb):
- apikey.test.mjs: 12 pass; against the old index.mjs 10 fail, the 2
OAuth-unchanged tests pass.
- packages/workbuddy: HOME=<tmp> bun test, 167 pass 0 fail.
- repo: HOME=$(mktemp -d) bun test, 2760 pass 3 skip 0 fail;
bun scripts/check.mjs exit 0.
Not tried: a real WorkBuddy API key.
This commit is contained in:
@@ -26,6 +26,15 @@ The package exports `WorkBuddyAuthPlugin` (`workbuddy`) and
|
||||
|
||||
WorkBuddy 5.6 and later keep the sign-in encrypted, which only the app
|
||||
opens, so this way fails there and says so: use the browser sign-in.
|
||||
- **API key** (since 0.1.37). A key made on the build's own keys page
|
||||
(`https://www.workbuddy.cn/profile/keys` for `workbuddy`,
|
||||
`https://www.workbuddy.ai/profile/keys` for `workbuddy-ai`), sent as
|
||||
WorkBuddy's own CLI sends one: `X-API-Key` and `Authorization: Bearer`,
|
||||
both the key, and `X-User-Id: anonymous_<the key's last 8 characters>`,
|
||||
to the same API as the other sign-ins. A key isn't renewed; a refused one
|
||||
says to check it. A key's credits are unknown (WorkBuddy's own client reads
|
||||
none with a key), and its models are `/v3/config`'s only for `ck_`/`pt_`
|
||||
keys, as the CLI asks; any other key keeps the list below.
|
||||
|
||||
A browser sign-in is kept as an OpenCode `oauth` auth: the access and
|
||||
refresh tokens, their expiry, the user id and the domain; desktop's as a
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
// 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)
|
||||
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")
|
||||
})
|
||||
@@ -67,6 +67,8 @@ const SITES = {
|
||||
authID: "workbuddy-desktop",
|
||||
platform: "workbuddy",
|
||||
ai: false,
|
||||
// where this build's API keys are made (see keyAccount)
|
||||
keys: "https://www.workbuddy.cn/profile/keys",
|
||||
models: CN_MODELS,
|
||||
// it serves the Claude models on Anthropic's Messages API too (see
|
||||
// nativeOf)
|
||||
@@ -79,6 +81,7 @@ const SITES = {
|
||||
authID: "workbuddy-desktop-ai",
|
||||
platform: "workbuddy-ai",
|
||||
ai: true,
|
||||
keys: "https://www.workbuddy.ai/profile/keys",
|
||||
models: AI_MODELS,
|
||||
// models whose images WorkBuddy AI drops though its config says they
|
||||
// take them (see textOnly)
|
||||
@@ -299,7 +302,14 @@ async function refreshed(site, auth) {
|
||||
function sign(site, a, headers) {
|
||||
headers.set("Authorization", "Bearer " + a.access)
|
||||
headers.set("X-User-Id", a.uid ?? "")
|
||||
headers.set("X-Domain", domainOf(site, a))
|
||||
if (a.source === "key") {
|
||||
// the key's own header, and no X-Domain: a key's session has none
|
||||
headers.set("X-API-Key", a.key)
|
||||
headers.delete("X-Domain")
|
||||
} else {
|
||||
headers.delete("X-API-Key")
|
||||
headers.set("X-Domain", domainOf(site, a))
|
||||
}
|
||||
headers.set("X-Product", "SaaS")
|
||||
headers.set("X-IDE-Type", "WorkBuddy")
|
||||
headers.set("User-Agent", "WorkBuddy/" + UA_VERSION)
|
||||
@@ -313,6 +323,31 @@ function sign(site, a, headers) {
|
||||
headers.set("X-Agent-Type", "main")
|
||||
}
|
||||
|
||||
// keyAccount is the account an API key (OpenCode's {type: "api", key}) is
|
||||
// sent as, the way WorkBuddy's own CLI sends one (@tencent-ai/codebuddy-code
|
||||
// 2.177.0, CODEBUDDY_API_KEY): its API-key sign-in is a session whose access
|
||||
// token is the key and whose uid is "anonymous_" and the key's last eight
|
||||
// characters (ACC_USER_ID unset), personal, with no domain and no
|
||||
// enterprise; and its model requests carry the key twice, X-API-Key and
|
||||
// Authorization: Bearer (getCustomHeaders). Its requests go to the build's
|
||||
// own host, the one its other sign-ins use: for the China build that is
|
||||
// copilot.tencent.com, the CLI's own endpoint for that build
|
||||
// (CODEBUDDY_INTERNET_ENVIRONMENT=internal, product.internal.json), and the
|
||||
// same API as www.workbuddy.cn, where the keys are made (the CLI's
|
||||
// CN_SAAS_CORE_API_FRONT_DOORS); for the international build,
|
||||
// www.workbuddy.ai (the CLI's own default, www.codebuddy.ai, is CodeBuddy's,
|
||||
// not WorkBuddy's). Nothing renews a key.
|
||||
function keyAccount(auth) {
|
||||
const key = typeof auth?.key === "string" ? auth.key.trim() : ""
|
||||
if (!key) return null
|
||||
return { key, access: key, uid: "anonymous_" + key.slice(-8), source: "key" }
|
||||
}
|
||||
|
||||
// remoteConfig says whether WorkBuddy's own CLI asks /v3/config for the
|
||||
// account's models with this key: only for keys that start ck_ or pt_
|
||||
// (shouldLoadRemoteConfig); any other key keeps the built-in list.
|
||||
const remoteConfig = (key) => /^(ck_|pt_)/.test(key)
|
||||
|
||||
// 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
|
||||
@@ -1419,6 +1454,8 @@ async function unanswered(site, a, body, err, signal) {
|
||||
if (signal?.aborted || err?.name === "AbortError" || err?.name === "TimeoutError") throw err
|
||||
const size = byteLength(body)
|
||||
if (size <= EDGE_READS) throw err
|
||||
// the billing API isn't asked with a key: what it answers one is unknown
|
||||
if (a.source === "key") throw err
|
||||
let status = 0
|
||||
let challenge = ""
|
||||
try {
|
||||
@@ -1546,6 +1583,18 @@ function refusedText(site, a, why, note) {
|
||||
)
|
||||
}
|
||||
|
||||
// keyRefused is the answer to a request WorkBuddy refused an API key for
|
||||
// (401): a key isn't renewed, so it says to check the key. Marked expired
|
||||
// only on WorkBuddy's word that the token itself is refused (invalidToken).
|
||||
function keyRefused(site, expired, note) {
|
||||
const message = `${site.name} refused this API key (401). ${note ? note + " " : ""}Check the key at ${site.keys}, then add it again in magpie: Providers → ${site.name}.`
|
||||
return new Response(JSON.stringify({ error: { message, type: "authentication_error", code: 401 } }), {
|
||||
status: 401,
|
||||
statusText: "Unauthorized",
|
||||
headers: { "content-type": "application/json", "X-Magpie-Sign-In": expired ? "expired" : "kept" },
|
||||
})
|
||||
}
|
||||
|
||||
// signedOut is the answer to a request WorkBuddy refused this account's
|
||||
// sign-in for, renewed or not: a 401 that says so and what to do, which
|
||||
// WorkBuddy's own (an HTML page, its {code, msg}) doesn't. expired marks
|
||||
@@ -2007,6 +2056,17 @@ function makePlugin(site) {
|
||||
// the account's own list, when it's signed in and WorkBuddy answers;
|
||||
// else the list above
|
||||
async models(provider, { auth }) {
|
||||
if (auth?.type === "api") {
|
||||
// asked as WorkBuddy's own CLI asks with a key (remoteConfig)
|
||||
const a = keyAccount(auth)
|
||||
if (!a || !remoteConfig(a.key)) return provider.models
|
||||
try {
|
||||
const ms = await liveModels(site, a)
|
||||
return ms.length ? Object.fromEntries(ms.map((m) => [m.id, modelOf(site, provider, m)])) : provider.models
|
||||
} catch {
|
||||
return provider.models
|
||||
}
|
||||
}
|
||||
if (auth?.type !== "oauth" || !(auth.access || auth.source)) return provider.models
|
||||
try {
|
||||
const a = await current(site, client, auth)
|
||||
@@ -2029,7 +2089,7 @@ function makePlugin(site) {
|
||||
refresh: (auth) => refreshed(site, auth),
|
||||
async loader(getAuth) {
|
||||
const auth = await getAuth()
|
||||
if (auth?.type !== "oauth") return {}
|
||||
if (auth?.type !== "oauth" && auth?.type !== "api") return {}
|
||||
return {
|
||||
// no baseURL: a model's own api.url says where it is served —
|
||||
// <endpoint>/v2 for a chat, <endpoint>/v1 for a Claude model on
|
||||
@@ -2038,8 +2098,9 @@ function makePlugin(site) {
|
||||
apiKey: "",
|
||||
async fetch(input, init) {
|
||||
const stored = await getAuth()
|
||||
if (stored?.type !== "oauth") throw new Error(`${site.name} isn't signed in`)
|
||||
let a = await current(site, client, stored)
|
||||
const keyed = stored?.type === "api" ? keyAccount(stored) : null
|
||||
if (stored?.type !== "oauth" && !keyed) throw new Error(`${site.name} isn't signed in`)
|
||||
let a = keyed ?? (await current(site, client, stored))
|
||||
const req = input instanceof Request ? input : null
|
||||
const headers = new Headers(init?.headers ?? req?.headers)
|
||||
headers.delete("authorization")
|
||||
@@ -2096,6 +2157,12 @@ function makePlugin(site) {
|
||||
const res = await post(b)
|
||||
if (res.status !== 401) return res
|
||||
if (renewed) return out("it refused the token renewed for it too", invalidToken(res), res)
|
||||
// a key isn't renewed: the 401 says the key was refused
|
||||
if (a.source === "key") {
|
||||
const r = keyRefused(site, invalidToken(res), edgeNotes.get(res))
|
||||
ours.add(r)
|
||||
return r
|
||||
}
|
||||
if (!resendable(b)) return res
|
||||
await res.body?.cancel().catch(() => {})
|
||||
const r = await reissued(site, client, getAuth, a, stored.access)
|
||||
@@ -2160,6 +2227,9 @@ function makePlugin(site) {
|
||||
// an account lapsed nor cleared it, but for a 401 (gone, below)
|
||||
async usage(getAuth) {
|
||||
const auth = await getAuth()
|
||||
// WorkBuddy's own CLI reads no credits with a key, and what the
|
||||
// billing API answers one is unknown, so a key's card says so
|
||||
if (auth?.type === "api") return { error: `credits unknown with an API key (WorkBuddy's own client reads none with one); see ${site.keys.replace(/\/profile\/keys$/, "")}`, signIn: "kept" }
|
||||
if (auth?.type !== "oauth" || !(auth.access || auth.source)) return { error: "not signed in", signIn: "kept" }
|
||||
try {
|
||||
let a = await current(site, client, auth)
|
||||
@@ -2225,6 +2295,13 @@ function makePlugin(site) {
|
||||
label: `${site.name} desktop's sign-in`,
|
||||
authorize: async () => desktopSignIn(site),
|
||||
},
|
||||
{
|
||||
// a key made at site.keys, sent as WorkBuddy's CLI sends one
|
||||
// (keyAccount)
|
||||
type: "api",
|
||||
label: `${site.name} API key`,
|
||||
placeholder: `from ${site.keys.replace(/^https:\/\//, "")}`,
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
@@ -2332,4 +2409,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy)
|
||||
export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"])
|
||||
|
||||
// for tests
|
||||
export const _internal = { cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, answeredBefore, nativeOf, modelOf, configModels, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM }
|
||||
export const _internal = { keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, answeredBefore, nativeOf, modelOf, configModels, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-workbuddy-auth",
|
||||
"version": "0.1.36",
|
||||
"version": "0.1.37",
|
||||
"description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
Reference in New Issue
Block a user