diff --git a/packages/raccoon/README.md b/packages/raccoon/README.md index 3702f4e..518f41e 100644 --- a/packages/raccoon/README.md +++ b/packages/raccoon/README.md @@ -7,7 +7,7 @@ OpenCode & Magpie provider plugin for **SenseTime Raccoon (商汤小浣熊, `xia - **Sign-in methods**: 1. Browser OAuth with automatic loopback return: confirm authorization in the browser; no desktop client or pasted code is needed. 2. Manual callback URL / token fallback (paste `office-raccoon://auth/callback?code=...`, or raw JWT `access_token` / JSON token pair). - 3. Raccoon desktop live session reuse (strictly read-only, reading `~/.box-agent/config/auth.json` without writing or spending desktop refresh tokens). + 3. Raccoon desktop live session reuse (strictly read-only, reading `~/.box-agent/config/auth.json` without writing or spending desktop refresh tokens). A desktop seat keeps the token it was signed in with on its own record, so it is never answered with, and never reports, another account's credentials or credits; once its own token is refused or runs out it asks to be signed in again. The app's own refresh token is still never spent. - **Token renewal**: single-flight proactive refresh 5 minutes before expiration for browser logins. - **Dynamic model catalog & credit rates**: real-time synchronization from `/api/web/llm/v2/model_catalog` with context window, output limit, vision/reasoning tags, credit multipliers, and limited-free markers. - **Usage & allowances**: reports available credits, unexpired grant bills, daily expiration timestamps, and Pro/Free subscription plans. @@ -23,7 +23,7 @@ OpenCode & Magpie provider plugin for **SenseTime Raccoon (商汤小浣熊, `xia - **多种登录方式**: 1. 浏览器 OAuth 授权登录:确认授权后自动返回,无需安装官方桌面客户端,也无需输入短信验证码或粘贴网页地址。 2. 手动回调 / Token 备用入口:粘贴 `office-raccoon://auth/callback?code=...` 完整回调链接,或 `access_token` / JSON;普通授权网页地址和单独授权码不能代替完整回调。 - 3. 直接只读复用本机商汤小浣熊客户端实时登录态(`~/.box-agent/config/auth.json`) + 3. 直接只读复用本机商汤小浣熊客户端实时登录态(`~/.box-agent/config/auth.json`)。桌面端席位会把登录时读到的 token 保存在自己的账号记录里,因此它不会拿到、也不会**上报**另一个账号的凭据或积分;一旦自己的 token 被拒或用尽,就提示重新登录(客户端自身的 refresh token 依旧不会被动用)。 - **Token 自动续期**:浏览器登录账号过期前 5 分钟自动单飞刷新。 - **动态模型目录与积分倍率**:实时同步 `/api/web/llm/v2/model_catalog`,展示模型上下文、最大输出、视觉/思考能力、积分倍率与限免(`Free`)标识。 - **积分余额与套餐查询**:展示可用积分、未过期发放额度、每日积分过期时间与 Pro/Free 套餐状态。 @@ -33,3 +33,9 @@ OpenCode & Magpie provider plugin for **SenseTime Raccoon (商汤小浣熊, `xia ### Browser callback lifecycle The browser flow uses the authorize page's `desktop_callback=loopback` contract, a random 64-character hex state and `http://127.0.0.1:/auth/callback`. The listener accepts only the matching host, GET path and state. Invalid callbacks leave the pending login intact; success, authorization refusal, exchange failure or the ten-minute deadline close it. A browser page says success only after the code exchange succeeds; response pages contain no code or token and disable caching. Closing/cancelling the host UI does not notify this plugin through the OpenCode callback contract, so an abandoned listener expires at that deadline. When a remote browser cannot reach that machine's loopback, Magpie can forward a pasted final callback URL; the separate manual method remains available as well. + +### Desktop seats + +The desktop app is signed in to one account at a time and keeps only that account's JWT in `auth.json`. A desktop seat therefore saves the token it was signed in with on its own record and uses it for every request, reading the app only to pick up a newer token for that same account. A seat whose account the app no longer holds is never answered with the app's current token: it keeps using its own until that token is refused, and then asks to be signed in again, rather than being billed to an account it does not name. Adding a seat takes only the account the app holds at that moment. + +Note that signing in to a second account in the desktop app **revokes the first account's session on the vendor's side**, so the first seat's token stops being accepted then — its `exp` notwithstanding — and is answered `401 {"code":200003}` by the credits and check-in endpoints, with every refresh endpoint answering 404 for it ([#166](https://github.com/magpie-community/plugins/pull/166), measured on a real pair of accounts). Two desktop seats are therefore one live account plus one seat waiting to be signed in again, never two working seats. For two accounts that both work, sign in twice through the browser method. diff --git a/packages/raccoon/index.mjs b/packages/raccoon/index.mjs index 79f3f35..41d23ee 100644 --- a/packages/raccoon/index.mjs +++ b/packages/raccoon/index.mjs @@ -209,29 +209,52 @@ function isStale(a, marginMs = EARLY_MS) { } // Desktop sign-in is strictly read-only: never write ~/.box-agent/config/auth.json -// and never spend the desktop app's refresh token. +// and never spend the desktop app's refresh token. The app holds one account +// at a time, so a seat keeps the token it was signed in with, saved on its own +// record through the client (as kiro does), and reads the app only to take a +// newer token for that same account. The app's current account never stands in +// for a seat it does not name: a seat answered with another account's token +// was billed to the wrong account and reported that account's credits, with +// nothing anywhere saying so (plugins #166). +// +// sameAccount says whether a seat names the account the app holds now. A uid +// the read token does not carry never agrees: the seat's own token is used, or +// the seat asks to be signed in again, rather than being answered with +// credentials it cannot be shown to own. A seat that names no account at all +// has nothing to protect and means the app's own account. +function sameAccount(seat, read) { + if (!read) return false + if (seat?.uid) return !!read.uid && String(seat.uid) === String(read.uid) + if (seat?.accountId) return !!read.name && String(seat.accountId) === String(read.name) + return true +} + async function currentAuth(client, auth, force = false) { if (auth?.source === "desktop") { const d = readDesktopAuth() - if (!d) { - const err = new Error("商汤小浣熊桌面端未登录,请打开商汤小浣熊客户端登录") - err.signIn = "expired" - throw err + // the app holds this seat's account: its token is the newest there is, + // and a seat asked again after a refusal takes it + if (sameAccount(auth, d) && !isStale(d, EARLY_MS)) { + if (d.access && d.access !== auth.access) { + try { + await client?.auth?.set?.({ path: { id: PROVIDER_ID }, body: { ...auth, ...d } }) + } catch {} + } + return { a: { ...auth, ...d }, didRenew: false } } - if ( - (auth.uid && d.uid && String(auth.uid) !== String(d.uid)) || - (!auth.uid && auth.accountId && d.name && String(auth.accountId) !== String(d.name)) - ) { - const err = new Error("商汤小浣熊桌面端已切换为其他账号,请重新登录") - err.signIn = "expired" - throw err - } - if (force || isStale(d, EARLY_MS)) { + // the app holds another account, or none: this seat goes on with the + // token it was signed in with until that token ends + if (!force && auth.access && !isStale(auth, EARLY_MS)) return { a: { ...auth }, didRenew: false } + if (sameAccount(auth, d)) { const err = new Error("商汤小浣熊桌面端登录态已过期,请打开商汤小浣熊客户端重新登录") err.signIn = "expired" throw err } - return { a: { ...auth, ...d }, didRenew: false } + const err = new Error( + d ? "商汤小浣熊桌面端已切换为其他账号,请重新登录" : "商汤小浣熊桌面端未登录,请打开商汤小浣熊客户端登录", + ) + err.signIn = "expired" + throw err } let a = { ...auth } @@ -842,6 +865,11 @@ function desktopSignIn() { instructions: "直接复用本机商汤小浣熊客户端的实时登录态 (~/.box-agent/config/auth.json)。", method: "auto", async callback() { + // A new seat takes the account the app holds now, and its token, and + // keeps them on its own record: the app is signed in to one account at + // a time and drops the previous one's token as soon as it rotates off + // disk. Only the app's own account is offered here, so a seat is never + // quietly handed some other account's credentials. const d = readDesktopAuth() if (!d) return { type: "failed", error: "未检测到本机商汤小浣熊登录态 (~/.box-agent/config/auth.json)" } if (isStale(d, EARLY_MS)) { @@ -849,9 +877,9 @@ function desktopSignIn() { } return { type: "success", - access: "", + access: d.access, refresh: "", - expires: 0, + expires: d.expires, source: "desktop", accountId: d.name || PROVIDER_NAME, uid: d.uid || "", @@ -1055,6 +1083,7 @@ export const RaccoonAuthPlugin = async ({ client }) => { export const _internal = { browserSignIn, + sameAccount, stripBearer, decodeJwtClaims, jwtExpiryMs, diff --git a/packages/raccoon/package.json b/packages/raccoon/package.json index b1d1ca3..9b894c7 100644 --- a/packages/raccoon/package.json +++ b/packages/raccoon/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-raccoon-auth", - "version": "0.1.2", + "version": "0.1.3", "description": "OpenCode & Magpie provider plugin for SenseTime Raccoon (商汤小浣熊, xiaohuanxiong.com)", "type": "module", "main": "./index.mjs", diff --git a/packages/raccoon/raccoon.test.mjs b/packages/raccoon/raccoon.test.mjs index 5a9c984..9e2951e 100644 --- a/packages/raccoon/raccoon.test.mjs +++ b/packages/raccoon/raccoon.test.mjs @@ -163,6 +163,8 @@ test("desktop sign-in is read-only and never writes or refreshes auth.json", asy }, }) + // a seat with no token of its own, as one added before the seat's own + // token was saved: the app's stale account is read, never written const hooks = await RaccoonAuthPlugin({ client: {} }) const res = await hooks.auth.usage(async () => ({ type: "oauth", source: "desktop" })) expect(refreshCalled).toBe(false) @@ -457,6 +459,203 @@ test("desktop sign-in marks expired when desktop app switches to another account expect(u.error).toContain("切换为其他账号") }) +// The desktop app is signed in to one account at a time: a seat added for the +// first account must keep its own token after the app switched to the second, +// instead of being expired or answered with the second account's token +// (plugins #166: the seat was billed to the wrong account, silently). +test("a desktop seat keeps its own account after the app switches to another", async () => { + tempDir = mkdtempSync(join(tmpdir(), "raccoon-test-")) + process.env.RACCOON_BOX_AGENT_CONFIG_DIR = tempDir + const authFile = join(tempDir, "auth.json") + const aTok = fakeJwt({ iss: "74350b", name: "AccountA", exp: Math.floor(Date.now() / 1000) + 3600 }) + const bTok = fakeJwt({ iss: "888888", name: "AccountB", exp: Math.floor(Date.now() / 1000) + 3600 }) + const seen = [] + writeFileSync(authFile, JSON.stringify({ access_token: aTok, refresh_token: "D1" })) + + const hooks = await RaccoonAuthPlugin({ client: {} }) + startServer({ + "GET /api/web/points/v1/balance": () => Response.json({ code: 0, data: { available_points: 300 } }), + "GET /api/web/auth/v1/entitlement_info": () => Response.json({ code: 0, data: {} }), + "GET /api/web/points/v1/bills": () => Response.json({ code: 0, data: { items: [] } }), + "POST /api/web/llm/v2/chat/completions": (req) => { + seen.push(req.headers.get("authorization")) + return Response.json({ code: 0, data: {} }) + }, + }) + const seatA = await (await hooks.auth.methods[1].authorize()).callback() + expect(seatA).toMatchObject({ type: "success", source: "desktop", uid: "7615755", accountId: "AccountA" }) + expect(seatA.access).toBe(aTok) // the seat's own record, not "" as before + + // the app signs in to the second account: auth.json is overwritten + writeFileSync(authFile, JSON.stringify({ access_token: bTok, refresh_token: "D2" })) + let stored = seatA + const client = { auth: { set: async ({ body }) => { stored = body } } } + const hooks2 = await RaccoonAuthPlugin({ client }) + const u = await hooks2.auth.usage(async () => ({ ...stored, type: "oauth" })) + expect(u.signIn).toBe("kept") + expect(u.user).toBe("AccountA") + expect(u.balance).toBe("300 credits") + + // and its own token is spent on requests, not the app's current one + const loaded = await hooks2.auth.loader(async () => ({ ...stored, type: "oauth" })) + await loaded.fetch(`${loaded.baseURL}/chat/completions`, { method: "POST", body: "{}" }) + expect(seen).toEqual([`Bearer ${aTok}`]) +}) + +// The desktop app signs in to one account at a time, and signing in to the +// second revokes the first account's session on the vendor's side (#166, +// measured on a real pair of accounts): the first seat's token is answered +// 401 / 200003 by the credits and check-in endpoints, and 404 by refresh, its +// exp notwithstanding. The seat must then ask to be signed in again, and must +// never fall back to the account the app holds now. +test("a desktop seat asks to sign in again once the vendor revokes its token", async () => { + tempDir = mkdtempSync(join(tmpdir(), "raccoon-test-")) + process.env.RACCOON_BOX_AGENT_CONFIG_DIR = tempDir + const authFile = join(tempDir, "auth.json") + const aTok = fakeJwt({ iss: "74350b", name: "AccountA", exp: Math.floor(Date.now() / 1000) + 3600 }) + const bTok = fakeJwt({ iss: "888888", name: "AccountB", exp: Math.floor(Date.now() / 1000) + 3600 }) + writeFileSync(authFile, JSON.stringify({ access_token: aTok, refresh_token: "D1" })) + const hooks = await RaccoonAuthPlugin({ client: {} }) + const seatA = await (await hooks.auth.methods[1].authorize()).callback() + + // the app signs in to the second account, and the vendor revokes the first + writeFileSync(authFile, JSON.stringify({ access_token: bTok, refresh_token: "D2" })) + const seen = [] + startServer({ + // what the vendor answers a revoked token with, on every endpoint + "GET /api/web/points/v1/balance": () => + Response.json({ code: 200003, message: "authorization_verify_error" }, { status: 401 }), + "GET /api/web/auth/v1/entitlement_info": () => + Response.json({ code: 200003, message: "authorization_verify_error" }, { status: 401 }), + "GET /api/web/points/v1/bills": () => + Response.json({ code: 200003, message: "authorization_verify_error" }, { status: 401 }), + "POST /api/web/llm/v2/chat/completions": (req) => { + seen.push(req.headers.get("authorization")) + return Response.json({ code: 200003, message: "authorization_verify_error" }, { status: 401 }) + }, + }) + + const u = await hooks.auth.usage(async () => ({ ...seatA, type: "oauth" })) + expect(u.signIn).toBe("expired") + expect(u.error).toContain("authorization_verify_error") + + const loaded = await hooks.auth.loader(async () => ({ ...seatA, type: "oauth" })) + const res = await loaded.fetch(`${loaded.baseURL}/chat/completions`, { method: "POST", body: "{}" }) + expect(res.status).toBe(401) + expect(res.headers.get("x-magpie-sign-in")).toBe("expired") + // the app's account is never spent for this seat + expect(seen).toEqual([`Bearer ${aTok}`]) +}) + +test("a desktop seat asks to sign in again once its own token expires", async () => { + tempDir = mkdtempSync(join(tmpdir(), "raccoon-test-")) + process.env.RACCOON_BOX_AGENT_CONFIG_DIR = tempDir + const authFile = join(tempDir, "auth.json") + const aTok = fakeJwt({ iss: "74350b", name: "AccountA", exp: Math.floor(Date.now() / 1000) + 3600 }) + const bTok = fakeJwt({ iss: "888888", name: "AccountB", exp: Math.floor(Date.now() / 1000) + 3600 }) + writeFileSync(authFile, JSON.stringify({ access_token: aTok, refresh_token: "D1" })) + const hooks = await RaccoonAuthPlugin({ client: {} }) + const seatA = await (await hooks.auth.methods[1].authorize()).callback() + + // the app switched, and the seat's own token has since ended + writeFileSync(authFile, JSON.stringify({ access_token: bTok, refresh_token: "D2" })) + const u = await hooks.auth.usage(async () => ({ ...seatA, type: "oauth", access: aTok, expires: Date.now() - 60_000 })) + expect(u.signIn).toBe("expired") + expect(u.error).toContain("切换为其他账号") +}) + +test("a desktop seat never takes the app's account when its own uid is unknown", async () => { + tempDir = mkdtempSync(join(tmpdir(), "raccoon-test-")) + process.env.RACCOON_BOX_AGENT_CONFIG_DIR = tempDir + const authFile = join(tempDir, "auth.json") + // a token whose uid cannot be read: the seat names no account it can prove + const noUid = fakeJwt({ name: "NoUid", exp: Math.floor(Date.now() / 1000) + 3600 }) + const otherTok = fakeJwt({ iss: "888888", name: "OtherUser", exp: Math.floor(Date.now() / 1000) + 3600 }) + writeFileSync(authFile, JSON.stringify({ access_token: noUid, refresh_token: "D1" })) + const hooks = await RaccoonAuthPlugin({ client: {} }) + const seat = await (await hooks.auth.methods[1].authorize()).callback() + expect(seat.uid).toBe("") + + writeFileSync(authFile, JSON.stringify({ access_token: otherTok, refresh_token: "D2" })) + startServer({ + "GET /api/web/points/v1/balance": () => Response.json({ code: 0, data: { available_points: 123 } }), + "GET /api/web/auth/v1/entitlement_info": () => Response.json({ code: 0, data: {} }), + "GET /api/web/points/v1/bills": () => Response.json({ code: 0, data: { items: [] } }), + }) + const u = await hooks.auth.usage(async () => ({ ...seat, type: "oauth" })) + expect(u.signIn).toBe("kept") + expect(u.user).toBe("NoUid") + expect(u.balance).toBe("123 credits") +}) + +// The seat names an account (its uid), and the app now holds a token whose uid +// cannot be read at all. That token is not the seat's account: the seat keeps +// its own, rather than being answered with credentials it cannot be shown to +// own (plugins #166, the "kept / user=B with B's Bearer" case). +test("a desktop seat with a uid is not handed a uid-less app token", async () => { + tempDir = mkdtempSync(join(tmpdir(), "raccoon-test-")) + process.env.RACCOON_BOX_AGENT_CONFIG_DIR = tempDir + const authFile = join(tempDir, "auth.json") + const aTok = fakeJwt({ iss: "74350b", name: "AccountA", exp: Math.floor(Date.now() / 1000) + 3600 }) + // the app signed in to an account whose token carries no readable uid + const noUidTok = fakeJwt({ name: "AccountB", exp: Math.floor(Date.now() / 1000) + 3600 }) + writeFileSync(authFile, JSON.stringify({ access_token: aTok, refresh_token: "D1" })) + const hooks = await RaccoonAuthPlugin({ client: {} }) + const seat = await (await hooks.auth.methods[1].authorize()).callback() + expect(seat.uid).toBe("7615755") + + writeFileSync(authFile, JSON.stringify({ access_token: noUidTok, refresh_token: "D2" })) + const seen = [] + startServer({ + "GET /api/web/points/v1/balance": () => Response.json({ code: 0, data: { available_points: 77 } }), + "GET /api/web/auth/v1/entitlement_info": () => Response.json({ code: 0, data: {} }), + "GET /api/web/points/v1/bills": () => Response.json({ code: 0, data: { items: [] } }), + "POST /api/web/llm/v2/chat/completions": (req) => { + seen.push(req.headers.get("authorization")) + return Response.json({ code: 0, data: {} }) + }, + }) + const u = await hooks.auth.usage(async () => ({ ...seat, type: "oauth" })) + expect(u.signIn).toBe("kept") + expect(u.user).toBe("AccountA") + expect(u.balance).toBe("77 credits") + + const loaded = await hooks.auth.loader(async () => ({ ...seat, type: "oauth" })) + await loaded.fetch(`${loaded.baseURL}/chat/completions`, { method: "POST", body: "{}" }) + expect(seen).toEqual([`Bearer ${aTok}`]) // the app's token is never spent +}) + +test("a desktop seat takes the app's newer token for its own account", async () => { + tempDir = mkdtempSync(join(tmpdir(), "raccoon-test-")) + process.env.RACCOON_BOX_AGENT_CONFIG_DIR = tempDir + const authFile = join(tempDir, "auth.json") + const oldTok = fakeJwt({ iss: "74350b", name: "AccountA", exp: Math.floor(Date.now() / 1000) + 3600 }) + const newTok = fakeJwt({ iss: "74350b", name: "AccountA", exp: Math.floor(Date.now() / 1000) + 7200 }) + writeFileSync(authFile, JSON.stringify({ access_token: oldTok, refresh_token: "D1" })) + const hooks = await RaccoonAuthPlugin({ client: {} }) + const seat = await (await hooks.auth.methods[1].authorize()).callback() + + // the app refreshed its own token while the seat was idle: same account, + // newer token, and the seat's record is updated to it + writeFileSync(authFile, JSON.stringify({ access_token: newTok, refresh_token: "D1" })) + const saves = [] + const client = { auth: { set: async ({ body }) => { saves.push(body) } } } + const hooks2 = await RaccoonAuthPlugin({ client }) + const seen = [] + startServer({ + "GET /api/web/points/v1/balance": () => Response.json({ code: 0, data: { available_points: 42 } }), + "GET /api/web/auth/v1/entitlement_info": () => Response.json({ code: 0, data: {} }), + "GET /api/web/points/v1/bills": () => Response.json({ code: 0, data: { items: [] } }), + "POST /api/web/llm/v2/chat/completions": (req) => { + seen.push(req.headers.get("authorization")) + return Response.json({ code: 0, data: {} }) + }, + }) + const loaded = await hooks2.auth.loader(async () => ({ ...seat, type: "oauth" })) + await loaded.fetch(`${loaded.baseURL}/chat/completions`, { method: "POST", body: "{}" }) + expect(seen).toEqual([`Bearer ${newTok}`]) + expect(saves.at(-1)).toMatchObject({ access: newTok, source: "desktop" }) +}) test("renewToken cache hit inside 60s invokes save with merged tokens", async () => { const staleTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) - 5 }) const freshTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 }) @@ -605,7 +804,7 @@ test("failed onboarding grant (500) is not marked settled and retries on next ch tempDir = mkdtempSync(join(tmpdir(), "raccoon-test-")) process.env.RACCOON_BOX_AGENT_CONFIG_DIR = tempDir writeFileSync(join(tempDir, "auth.json"), JSON.stringify({ access_token: validTok, refresh_token: "D1" })) - const deskAuth = { type: "oauth", source: "desktop", uid: "7615755" } + const deskAuth = { type: "oauth", source: "desktop", uid: "7615755", access: validTok, expires: Date.now() + 3600_000 } const r2 = await hooks.auth.checkin(async () => deskAuth) expect(r2.outcome).toBe("done")