wenchen855443 on X: with WorkBuddy as the provider, requests return 401.
Until now a chat 401 was passed on as WorkBuddy's HTML APISIX page with
X-Magpie-Sign-In: kept. A token is renewed only near its end, and a
browser sign-in's token lasts about 340 days. So a token WorkBuddy
refused before then was sent again on every request, for months.
Nothing renewed it and nothing told the user what to do.
What changed (packages/workbuddy/index.mjs):
- A chat or usage summary answered 401 is renewed once, whatever the
token's time, then sent once more. The request body is sent as it
was, and only a body that can be resent is retried. The first 401's
body is cancelled. A second 401 is never renewed.
- Before spending the refresh token, a newer token another process saved
(getAuth) is taken first. This is also checked after a refused refresh,
for the case where another process spent the refresh token at the same
moment (part of plugins#332).
- A desktop sign-in never spends the app's refresh token here. The plugin
drops the token it held, reads the app's file again, and retries only
if the token there changed.
- When there is no new token, or the retry is refused too, the plugin
answers 401 with authentication_error. The message names why ("it
refused the refresh token too (…)", "there is no refresh token to renew
it with", "it refused the token renewed for it too") and says where to
sign in again: Providers → WorkBuddy [AI] → this account's Sign in again,
or WorkBuddy desktop for a desktop sign-in. The >2 MiB ECONNRESET note
stays in that message.
- readDesktop marks its result source: "desktop". Before this,
unanswered's desktop wording could never show.
Marking the account expired:
- The plugin sends X-Magpie-Sign-In: expired (usage: signIn) only when
WorkBuddy itself says the sign-in is gone:
- the refresh token was refused (HTTP 401 / invalid_grant);
- the access token was refused with WWW-Authenticate error=
"invalid_token" and no refresh token was left, or one had ended;
- a just-renewed token was refused with invalid_token.
- Why mark it at all: a marked account leaves routing, so the user's
other accounts serve; the row says to sign in again; and a dead
account stops spending a refresh on every request.
- Why not on every 401: WorkBuddy answers some paths with a bare 401
even for a good sign-in (magpie's workbuddy_checkin_test). A refresh
that fails for another reason (5xx, network) also leaves the account
as it is.
- A desktop sign-in is never marked: the app's file is read on every
request, so signing in to the app again fixes it.
- A success after a renewal sends "renewed", which clears a mark.
- auth.refresh (refreshed()) still never marks the account, because a
refresh token spent by another process there could read as refused.
What WorkBuddy does (www.workbuddy.ai, 2026-10-23, the owner's real
workbuddy-ai sign-in copied into a sandbox HOME):
- Chat with a wrong or garbage token: 401, HTML APISIX page,
WWW-Authenticate: Bearer realm="copilot", error="invalid_token".
- Chat with an empty token: 401, no WWW-Authenticate.
- The meter: the same 401. /v3/config: 200 to a bad token.
- Refresh with a wrong refresh token: HTTP 401 {"code":12153,"msg":"12153:
refresh token failed:400 Bad Request: invalid_grant: Invalid refresh
token"}. With garbage: 401, code 12153 "token format error".
- A real refresh: 200; both tokens rotate, and both expiries are about
340 days out.
- The old access token still answered 200 after the refresh.
- The rotated tokens were written back to the live plugin-auth.json under
its lock (temp + rename, only workbuddy-ai's entry changed). The live
gateway answered workbuddy-ai/deepseek-v4.1-flash with 200 afterwards.
Run at this tree (652f06d + this change):
- HOME=$(mktemp -d) bun test: 2329 pass, 0 fail, 197 files.
- bun scripts/check.mjs: ok.
- New unauthorized.test.mjs (12 tests): renew then 200 (renewed, saved,
new Bearer); refresh refused → sign in again, expired; transient refresh
failure → kept; no second renew or retry; no refresh token
(expired with invalid_token, kept on a bare 401); a token another
process saved is taken; desktop re-read and never marked; usage renew;
usage refused → expired.
- Existing tests that pinned the old pass-through were updated:
signin.test.mjs, usage.test.mjs, reset.test.mjs.
Broken by hand:
- With origin/main's index.mjs, all 12 new tests are red.
- Without the renewed guard: the "isn't renewed twice" test goes red.
- With gone() always false: the 3 marking tests go red.
- Without the newer() check: the 2 "another process saved" tests go red.
Not tried:
- Reusing an old refresh token after rotation, which risks revoking the
owner's session. Whether WorkBuddy refuses it, or revokes the session,
is unknown.
- The China build (www.codebuddy.cn) was not probed for a real 401.
- A desktop sign-in with real accounts.
- The reporter's case is unknown: their site, their sign-in kind, and the
401's body. So is what revokes a WorkBuddy access token before its end;
a refresh by another process does not.
130 lines
5.3 KiB
JavaScript
130 lines
5.3 KiB
JavaScript
// WorkBuddy's front door answers a sign-in it refuses with 401, but only
|
|
// for a request of up to 2 MiB: past that it resets the connection, and a
|
|
// long Claude Code session's every turn failed as ECONNRESET (wyp on
|
|
// Discord, 2026-10-15). The fake below is that front door on a real
|
|
// socket, so Bun's fetch meets the same reset it met on www.workbuddy.ai.
|
|
import { afterAll, beforeAll, expect, test } from "bun:test"
|
|
import net from "node:net"
|
|
import { WorkBuddyAIAuthPlugin, WorkBuddyAuthPlugin, _internal } from "./index.mjs"
|
|
|
|
const { EDGE_READS } = _internal
|
|
const GOOD = "Bearer good"
|
|
|
|
let server
|
|
let origin
|
|
let meterAsked = 0
|
|
let resetAll = false // a reset that isn't the sign-in's: every long body
|
|
|
|
beforeAll(async () => {
|
|
server = net.createServer((s) => {
|
|
let buf = Buffer.alloc(0)
|
|
let head = null
|
|
s.on("error", () => {})
|
|
s.on("data", (d) => {
|
|
buf = Buffer.concat([buf, d])
|
|
if (!head) {
|
|
const end = buf.indexOf("\r\n\r\n")
|
|
if (end < 0) return
|
|
const lines = buf.subarray(0, end).toString("latin1").split("\r\n")
|
|
const h = Object.fromEntries(lines.slice(1).map((l) => [l.slice(0, l.indexOf(":")).toLowerCase(), l.slice(l.indexOf(":") + 1).trim()]))
|
|
head = { path: lines[0].split(" ")[1], auth: h.authorization, length: Number(h["content-length"] ?? 0) }
|
|
buf = buf.subarray(end + 4)
|
|
}
|
|
const refused = head.auth !== GOOD
|
|
if (head.length > EDGE_READS && (refused || resetAll)) {
|
|
// the front door reads its 2 MiB, then drops the connection unanswered
|
|
if (buf.length > EDGE_READS) s.resetAndDestroy()
|
|
return
|
|
}
|
|
if (buf.length < head.length) return
|
|
const { path } = head
|
|
head = null
|
|
buf = Buffer.alloc(0)
|
|
if (path.startsWith("/billing/")) meterAsked++
|
|
if (refused) {
|
|
const html = "<html><head><title>401 Authorization Required</title></head></html>"
|
|
s.end(`HTTP/1.1 401 Unauthorized\r\ncontent-type: text/html\r\ncontent-length: ${html.length}\r\nconnection: close\r\n\r\n${html}`)
|
|
return
|
|
}
|
|
const body = path.startsWith("/billing/") ? '{"code":0,"msg":"OK","data":{}}' : 'data: {"choices":[{"delta":{"content":"pong"}}]}\n\ndata: [DONE]\n\n'
|
|
s.end(`HTTP/1.1 200 OK\r\ncontent-type: ${path.startsWith("/billing/") ? "application/json" : "text/event-stream"}\r\ncontent-length: ${body.length}\r\nconnection: close\r\n\r\n${body}`)
|
|
})
|
|
})
|
|
await new Promise((r) => server.listen(0, "127.0.0.1", r))
|
|
origin = `http://127.0.0.1:${server.address().port}`
|
|
})
|
|
|
|
afterAll(() => server.close())
|
|
|
|
// chat is a loader fetch of a body of about size bytes, signed in as token,
|
|
// with the site (WorkBuddy AI's, else the China build's) served by the fake
|
|
async function chat(token, size, plugin = WorkBuddyAIAuthPlugin, site = "https://www.workbuddy.ai") {
|
|
const realFetch = globalThis.fetch
|
|
globalThis.fetch = (u, init) => realFetch(String(u instanceof Request ? u.url : u).replace(site, origin), init)
|
|
try {
|
|
const hooks = await plugin({ client: {} })
|
|
const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: token, uid: "uid", expires: Date.now() + 3600_000 }))
|
|
const body = JSON.stringify({
|
|
model: "fast-model",
|
|
stream: true,
|
|
messages: [
|
|
{ role: "system", content: "You are helpful." },
|
|
{ role: "user", content: "x".repeat(size) },
|
|
],
|
|
})
|
|
return await loader.fetch(site + "/v2/chat/completions", { method: "POST", body })
|
|
} finally {
|
|
globalThis.fetch = realFetch
|
|
}
|
|
}
|
|
|
|
test("a refused sign-in on a chat past 2 MiB says the 401, not ECONNRESET", async () => {
|
|
meterAsked = 0
|
|
const res = await chat("refused", EDGE_READS + 100_000)
|
|
expect(res.status).toBe(401)
|
|
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
|
|
const { error } = await res.json()
|
|
expect(error.message).toContain("refused this account's sign-in (401)")
|
|
expect(error.message).toContain("which is why it read as ECONNRESET")
|
|
expect(error.message).toContain("Sign in to it again in magpie")
|
|
expect(meterAsked).toBe(1)
|
|
})
|
|
|
|
test("the China build's front door is read the same way", async () => {
|
|
meterAsked = 0
|
|
const res = await chat("refused", EDGE_READS + 100_000, WorkBuddyAuthPlugin, "https://copilot.tencent.com")
|
|
expect(res.status).toBe(401)
|
|
expect((await res.json()).error.message).toContain("Providers → WorkBuddy →")
|
|
expect(meterAsked).toBe(1)
|
|
})
|
|
|
|
test("a refused sign-in on a short chat is the front door's own 401, nothing else asked", async () => {
|
|
meterAsked = 0
|
|
const res = await chat("refused", 1000)
|
|
expect(res.status).toBe(401)
|
|
// with no refresh token to renew it with, said so (unauthorized.test.mjs)
|
|
expect((await res.json()).error.message).toContain("there is no refresh token to renew it with")
|
|
expect(meterAsked).toBe(0)
|
|
})
|
|
|
|
test("a reset past 2 MiB with the sign-in accepted stays the reset", async () => {
|
|
meterAsked = 0
|
|
resetAll = true
|
|
try {
|
|
let err
|
|
await chat("good", EDGE_READS + 100_000).catch((e) => (err = e))
|
|
expect(err?.code).toBe("ECONNRESET")
|
|
expect(meterAsked).toBe(1)
|
|
} finally {
|
|
resetAll = false
|
|
}
|
|
})
|
|
|
|
test("an accepted sign-in's chat past 2 MiB goes through", async () => {
|
|
meterAsked = 0
|
|
const res = await chat(GOOD.slice(7), EDGE_READS + 100_000)
|
|
expect(res.status).toBe(200)
|
|
expect(await res.text()).toContain("pong")
|
|
expect(meterAsked).toBe(0)
|
|
})
|