From 1e7122e161b7277c042cdd6e98eee5ba5516f14b Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 29 Oct 2026 15:37:53 +0800 Subject: [PATCH] workbuddy 0.1.47: a conversation's ids are one account's own leaves5760 on Discord: every account of a group of WorkBuddy accounts gets 403 "request illegal", WorkBuddy saying the account is restricted for abnormal behaviour. X-Conversation-ID and X-Conversation-Request-ID were derived from the session (or first user message) and the turn alone, with a salt per process. One magpie session spread over several accounts therefore sent the same conversation and turn ids under every account's X-User-Id. WorkBuddy's own client (5.9.3, @genie/agent-cli 2.165.0) is signed in as one account, so a conversation never shows up under two. The ids now also hash the account (uid, enterpriseId, and for a key account the key), and a chat sent again after a 401 as another account (a sign-in saved since) gets that account's ids. The same account keeps stable ids as before. This is a divergence from the official client found by reading its bundle, not a verified cause of the restriction. Not changed, reported only: no X-Private-Data, traceparent/baggage, reasoning_summary "auto", or the client's /v2/report telemetry. Run on mote at this tree: HOME=$(mktemp -d) bun test in packages/workbuddy, 209 pass 0 fail; bun scripts/check.mjs exit 0. Broken by hand: with the account left out of the ids, both new tests (conversation.test.mjs, unauthorized.test.mjs) fail; with reattend a no-op, the 401 test fails. Not tried: a real WorkBuddy account (none used, by the task's rule). --- packages/workbuddy/README.md | 7 ++- packages/workbuddy/conversation.test.mjs | 34 ++++++++++-- packages/workbuddy/index.mjs | 66 ++++++++++++++++++++---- packages/workbuddy/package.json | 2 +- packages/workbuddy/unauthorized.test.mjs | 25 +++++++++ 5 files changed, 116 insertions(+), 18 deletions(-) diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index 03fca57..b57f6e3 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -137,8 +137,11 @@ Each chat carries WorkBuddy's headers: - the conversation's ids: `X-Conversation-ID`, `X-Conversation-Request-ID`, `X-Conversation-Message-ID`, `X-Request-ID`. WorkBuddy's backend counts a user send as one request by `X-Conversation-Request-ID`, so every step of - one send — a tool result sent back, a retry, another account answering — - carries the same one, and the user's next message carries another. The + one send — a tool result sent back, a retry — carries the same one, and + the user's next message carries another. Both ids are one account's own, + as WorkBuddy's client is signed in as one: a conversation sent as another + account (another of a group, or a sign-in saved since) carries that + account's ids, never the same ones under two `X-User-Id`s. The conversation's is the session magpie (or OpenCode) names the request by, else the chat's first user message; nothing is made up when neither names one, a made-up conversation of the request's own being what splits one diff --git a/packages/workbuddy/conversation.test.mjs b/packages/workbuddy/conversation.test.mjs index 30f93fa..63521dd 100644 --- a/packages/workbuddy/conversation.test.mjs +++ b/packages/workbuddy/conversation.test.mjs @@ -1,9 +1,11 @@ // One user send is one request to WorkBuddy's backend, whatever it takes: -// every step of it — a tool result sent back, a retry, another account -// answering — carries the same X-Conversation-Request-ID, and the user's next +// every step of it — a tool result sent back, a retry — carries the same +// X-Conversation-Request-ID, and the user's next // message carries another. A conversation's turns share its // X-Conversation-ID, from the session magpie (or OpenCode) names, else from // the chat's first user message; each request has a message id of its own. +// Both are one account's own: WorkBuddy's client is signed in as one, so a +// conversation sent as two accounts is two conversations to WorkBuddy. import { afterEach, expect, test } from "bun:test" import { WorkBuddyAIAuthPlugin, WorkBuddyAuthPlugin, _internal } from "./index.mjs" @@ -14,7 +16,7 @@ afterEach(() => (globalThis.fetch = real)) // ask sends a chat as magpie's host does: the chat.headers hook is told the // session, then the loader's fetch is given what it added, and the request // WorkBuddy was sent is read back. Nothing leaves the machine. -async function ask(body, { session = "", provider = "workbuddy", plugin = WorkBuddyAuthPlugin, headers = {} } = {}) { +async function ask(body, { session = "", provider = "workbuddy", plugin = WorkBuddyAuthPlugin, headers = {}, uid = "u1", enterpriseId } = {}) { const sent = [] globalThis.fetch = async (url, init) => { sent.push(new Headers(init?.headers)) @@ -23,7 +25,7 @@ async function ask(body, { session = "", provider = "workbuddy", plugin = WorkBu const hooks = await plugin({ client: {} }) const out = { headers: { ...headers } } await hooks["chat.headers"]({ sessionID: session, model: { providerID: provider, id: "glm-5.3" }, provider: { info: { id: provider } } }, out) - const l = await hooks.auth.loader(async () => ({ type: "oauth", access: "tok", uid: "u1", expires: Date.now() + 3600_000 })) + const l = await hooks.auth.loader(async () => ({ type: "oauth", access: "tok", uid, ...(enterpriseId ? { enterpriseId } : {}), expires: Date.now() + 3600_000 })) const res = await l.fetch("https://copilot.tencent.com/v2/chat/completions", { method: "POST", headers: new Headers(out.headers), @@ -223,3 +225,27 @@ test("the same words in another conversation are another turn", async () => { expect(turn(await ask(later("fix it", "继续")))).toBe(turn(a)) expect(turn(await ask(later("other", "继续")))).not.toBe(turn(a)) }) + +test("a conversation's ids are one account's own: another account sends others", async () => { + // as magpie spreads one session over a group's accounts + const one = await ask(send("fix the bug"), { session: "ses_1", uid: "u1" }) + const again = await ask(send("fix the bug"), { session: "ses_1", uid: "u1" }) + const two = await ask(send("fix the bug"), { session: "ses_1", uid: "u2" }) + expect(conv(two)).toMatch(HEX32) + expect(turn(two)).toMatch(HEX32) + // the same account keeps them + expect(conv(again)).toBe(conv(one)) + expect(turn(again)).toBe(turn(one)) + // another account has its own + expect(conv(two)).not.toBe(conv(one)) + expect(turn(two)).not.toBe(turn(one)) + // with no session too: the first user message names it for one account + const a = await ask(send("hi"), { uid: "u1" }) + const b = await ask(send("hi"), { uid: "u2" }) + expect(conv(a)).not.toBe(conv(b)) + expect(turn(a)).not.toBe(turn(b)) + // one user in two enterprises is two accounts as well + const team = await ask(send("fix the bug"), { session: "ses_1", uid: "u1", enterpriseId: "e1" }) + expect(conv(team)).not.toBe(conv(one)) + expect(turn(team)).not.toBe(turn(one)) +}) diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index d094d0f..928bbab 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -446,7 +446,7 @@ async function enterpriseOf(site, a, who) { // itself, and the request that carried it. Its backend counts a user send as // one request by X-Conversation-Request-ID: a chat carrying a new one every // time is counted on its own, so one send that takes several steps — a tool -// call answered and sent again, a retry, another account answering — shows up +// call answered and sent again, a retry — shows up // in the usage detail as many requests. The ids below are made from what // names the conversation and the turn, so every step of one send carries the // same turn id and the user's next message carries another, as WorkBuddy's @@ -719,22 +719,64 @@ function sessionOf(headers) { // turn's (one user send, whatever it takes), and the conversation's. A header // already there — the caller's own, or another plugin's — is kept, and the // message and request ids are the same one, as WorkBuddy's client has them. -function attend(headers, body, session) { - attendChat(headers, chatOf(body), session) +// +// who is the account the chat goes as (scopeOf). The ids are that account's +// own: WorkBuddy's client runs as one account, so one conversation or turn +// never shows up under two. Without it, one magpie session spread over a +// group of accounts sent the same X-Conversation-ID and +// X-Conversation-Request-ID under every account's X-User-Id. +function attend(headers, body, session, who = "") { + return attendChat(headers, chatOf(body), session, who) } -function attendChat(headers, chat, session) { +// attendChat is attend with the chat read already. It returns what reattend +// needs to set the ids again for another account once the chat itself is +// let go: the ids it set itself (not the caller's), and the digests of what +// names the turn and the conversation, which are never sent as they are. +function attendChat(headers, chat, session, who = "") { const conv = conversationParts(chat, session) + const turn = turnParts(chat) + const ids = { + set: [], + // a turn is a conversation's own: two conversations whose user message + // reads the same are still two sends, not one + turn: turn.length ? idFor("turn", [...conv, "|", ...turn]) : "", + conv: conv.length ? idFor("conversation", conv) : "", + } + return setIds(headers, ids, who) +} + +// setIds sets the message's id, and the turn's and conversation's for the +// account who, where the caller set none. +function setIds(headers, ids, who) { const msg = hex() headers.set("X-Conversation-Message-ID", msg) headers.set("X-Request-ID", msg) + const set = [] + const own = (kind, base) => (who ? idFor(kind, [`account:${who}`, "|", base]) : base) if (!headers.has("X-Conversation-Request-ID")) { - const turn = turnParts(chat) - // a turn is a conversation's own: two conversations whose user message - // reads the same are still two sends, not one - headers.set("X-Conversation-Request-ID", turn.length ? idFor("turn", [...conv, "|", ...turn]) : hex()) + headers.set("X-Conversation-Request-ID", ids.turn ? own("turn", ids.turn) : hex()) + set.push("X-Conversation-Request-ID") } - if (conv.length && !headers.has("X-Conversation-ID")) headers.set("X-Conversation-ID", idFor("conversation", conv)) + if (ids.conv && !headers.has("X-Conversation-ID")) { + headers.set("X-Conversation-ID", own("conversation", ids.conv)) + set.push("X-Conversation-ID") + } + return { ...ids, set } +} + +// scopeOf names the account a chat goes as for attend: its uid, its +// enterprise, and for a key account the key (only ever hashed). +function scopeOf(a) { + return `${a?.uid ?? ""}|${a?.enterpriseId ?? ""}|${a?.source === "key" ? a.key ?? "" : ""}` +} + +// reattend sets a chat's ids again for the account it is now sent as, when +// that is another account than the one they were set for. +function reattend(headers, ids, was, now) { + if (was === now) return ids + for (const h of ids.set) headers.delete(h) + return setIds(headers, ids, now) } // FLAGGED are the words WorkBuddy refuses a chat for, "Illegal API @@ -2510,7 +2552,8 @@ function makePlugin(site) { const completion = !native && isCompletion(req ? req.url : input, chat) if (completion && chat && !namesEffort(chat) && withDefaultEffort(chat, await effortList(a))) changed = true chatHeaders(site, headers) - attendChat(headers, chat, session) + let who = scopeOf(a) + let ids = attendChat(headers, chat, session, who) const post = (b) => { // a chat goes gzipped, as WorkBuddy's client sends it // (gzipped); its size on the wire is what unanswered weighs @@ -2557,6 +2600,7 @@ function makePlugin(site) { renewed = true a = r.a sign(site, a, headers) + ids = reattend(headers, ids, who, (who = scopeOf(a))) const again = await post(b) if (again.status !== 401) return again return out("it refused the token renewed for it too", invalidToken(again), again) @@ -2805,4 +2849,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -export const _internal = { idFor, replyAfterToolsOn, withDefaultEffort, defaultEffortOf, gzipped, FREE_ONLY, PRICE_TTL, 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, asReasoning, 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, prepared, answeredBefore, nativeOf, modelOf, configModels, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM } +export const _internal = { idFor, replyAfterToolsOn, withDefaultEffort, defaultEffortOf, gzipped, FREE_ONLY, PRICE_TTL, 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, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, scopeOf, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM } diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index ee2cf2d..2c43403 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.46", + "version": "0.1.47", "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)", "type": "module", "main": "./index.mjs", diff --git a/packages/workbuddy/unauthorized.test.mjs b/packages/workbuddy/unauthorized.test.mjs index 3456107..63fa18d 100644 --- a/packages/workbuddy/unauthorized.test.mjs +++ b/packages/workbuddy/unauthorized.test.mjs @@ -253,3 +253,28 @@ test("usage whose refresh is turned away says to sign in again, the account mark expect(out.signIn).toBe("expired") expect(out.error).toContain("WorkBuddy refused this account's sign-in (401); it refused the refresh token too") }) + +// A conversation's ids are one account's own (conversation.test.mjs): a chat +// sent again as another account, saved since by someone else, goes with +// that account's ids, and a renewed token of the same account keeps them. +test("a chat sent again as another account carries that account's ids", async () => { + const calls = serve() + // another account is saved once the first chat was refused + const stored = async () => (of(calls, "/v2/chat/completions").length ? signedIn({ access: "new", uid: "u2" }) : signedIn()) + const res = await ask(signedIn(), { stored }) + expect(res.status).toBe(200) + const chats = of(calls, "/v2/chat/completions") + expect(chats.length).toBe(2) + const [first, second] = chats.map((c) => c.headers) + expect(second.get("x-user-id")).toBe("u2") + expect(second.get("x-conversation-id")).toMatch(/^[0-9a-f]{32}$/) + expect(second.get("x-conversation-id")).not.toBe(first.get("x-conversation-id")) + expect(second.get("x-conversation-request-id")).not.toBe(first.get("x-conversation-request-id")) + + const same = serve() + expect((await ask(signedIn())).status).toBe(200) + const [a, b] = of(same, "/v2/chat/completions").map((c) => c.headers) + expect(b.get("x-user-id")).toBe("u1") + expect(b.get("x-conversation-id")).toBe(a.get("x-conversation-id")) + expect(b.get("x-conversation-request-id")).toBe(a.get("x-conversation-request-id")) +})