raccoon 0.1.4: read the desktop auth.json in the client profile on macOS and Windows (#459, wky114)

Current Raccoon desktop builds keep the session in a client profile, not in
~/.box-agent, so desktop sign-in answered "not detected" while the app was
signed in (wky114). Raccoon desktop 1.1.3's app.asar (clientProfile.ts)
puts it at <profile>/agent/config/auth.json, the profile being
~/Library/Application Support/office-raccoon on macOS and
%USERPROFILE%\.office-raccoon on Windows. The plugin now reads the Windows
profile, the appData profile, then ~/.box-agent, first file found wins; the
RACCOON_BOX_AGENT_CONFIG_DIR / BOX_AGENT_CONFIG_DIR overrides still come
first. Labels and the not-found error no longer name one path.

Review fixup (cb46111): the PR had only ~/.office-raccoon, which is the
Windows layout, and its test was red at f55d949 (Bun reads homedir() once,
so setting HOME did nothing). desktopAuthCandidates takes home/platform/env
and the tests pass them per OS. Version 0.1.4.

Run at cb46111: bun test in packages/raccoon on mote (38 pass) and on
Windows (38 pass); whole repo bun test on mote (2999 pass, 8 skip);
bun scripts/check.mjs ok. Broken by hand: without the appData profile
both desktop tests are red. Not tried: a real signed-in Raccoon desktop.

Co-authored-by: wky114 <38514103+wky114@users.noreply.github.com>
This commit is contained in:
wky114
2026-10-28 15:27:33 +08:00
committed by GitHub
parent 944610f8c8
commit c00f40eb01
4 changed files with 119 additions and 17 deletions
+2 -2
View File
@@ -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). 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.
3. Raccoon desktop live session reuse (strictly read-only, reading the `auth.json` the desktop app keeps — `<profile>/agent/config/auth.json` in current builds, where the profile is `~/Library/Application Support/office-raccoon` on macOS and `%USERPROFILE%\.office-raccoon` on Windows, and `~/.box-agent/config/auth.json` in older ones — 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`)。桌面端席位会把登录时读到的 token 保存在自己的账号记录里,因此它不会拿到、也不会**上报**另一个账号的凭据或积分;一旦自己的 token 被拒或用尽,就提示重新登录(客户端自身的 refresh token 依旧不会被动用)。
3. 直接只读复用本机商汤小浣熊客户端实时登录态(客户端保存的 `auth.json`:新版在客户端配置目录下的 `agent/config/auth.json`(macOS 为 `~/Library/Application Support/office-raccoon`,Windows 为 `%USERPROFILE%\.office-raccoon`),旧版在 `~/.box-agent/config/auth.json`)。桌面端席位会把登录时读到的 token 保存在自己的账号记录里,因此它不会拿到、也不会**上报**另一个账号的凭据或积分;一旦自己的 token 被拒或用尽,就提示重新登录(客户端自身的 refresh token 依旧不会被动用)。
- **Token 自动续期**:浏览器登录账号过期前 5 分钟自动单飞刷新。
- **动态模型目录与积分倍率**:实时同步 `/api/web/llm/v2/model_catalog`,展示模型上下文、最大输出、视觉/思考能力、积分倍率与限免(`Free`)标识。
- **积分余额与套餐查询**:展示可用积分、未过期发放额度、每日积分过期时间与 Pro/Free 套餐状态。
+52 -12
View File
@@ -2,9 +2,9 @@
//
// Raccoon signs in through xiaohuanxiong.com's desktop authorization page
// (/code/authorize -> office-raccoon://auth/callback?code=...&state=...), or
// reads the live session Raccoon's desktop app keeps in
// ~/.box-agent/config/auth.json (read-only). Chats are OpenAI-compatible chat
// completions at /api/web/llm/v2/chat/completions.
// reads the live session Raccoon's desktop app keeps in its auth.json
// (read-only; desktopAuthCandidates lists where). Chats are OpenAI-compatible
// chat completions at /api/web/llm/v2/chat/completions.
import { randomUUID, randomBytes } from "node:crypto"
import { createServer } from "node:http"
@@ -106,14 +106,47 @@ function vendorErrorText(payload, fallback) {
return fallback
}
// ---- Desktop auth.json (~/.box-agent/config/auth.json, read-only) -----------
// ---- Desktop auth.json (read-only) ------------------------------------------
//
// The desktop app has moved this file between releases. Builds that keep a
// client profile (1.1.x) put the box-agent home inside it and write
// <profile>/agent/config/auth.json, with the profile at
// Windows: %USERPROFILE%\.office-raccoon (moved there from %APPDATA%)
// macOS: ~/Library/Application Support/office-raccoon
// (clientProfile.ts: openDefaultClientProfile, app.getPath("appData")).
// Older installs, and a profile the app still treats as legacy user data,
// keep ~/.box-agent/config/auth.json. Every layout is read, the profile ones
// first, so either build is picked up without an env override.
function desktopAuthPath() {
// The arguments are for tests: Bun reads homedir() once, at start.
function appDataDir(home, platform, env) {
if (platform === "win32") return String(env.APPDATA ?? "").trim() || join(home, "AppData", "Roaming")
if (platform === "darwin") return join(home, "Library", "Application Support")
return String(env.XDG_CONFIG_HOME ?? "").trim() || join(home, ".config")
}
function desktopAuthCandidates(home = homedir(), platform = process.platform, env = process.env) {
for (const envKey of ["RACCOON_BOX_AGENT_CONFIG_DIR", "BOX_AGENT_CONFIG_DIR"]) {
const v = String(process.env[envKey] ?? "").trim()
if (v) return join(v, "auth.json")
const v = String(env[envKey] ?? "").trim()
if (v) return [join(v, "auth.json")]
}
return join(homedir(), ".box-agent", "config", "auth.json")
const profiles = [join(appDataDir(home, platform, env), "office-raccoon")]
if (platform === "win32") profiles.unshift(join(home, ".office-raccoon"))
return [
...profiles.map((p) => join(p, "agent", "config", "auth.json")),
join(home, ".box-agent", "config", "auth.json"),
]
}
// The first candidate that is a file, else the first (which then reads as
// not signed in).
function desktopAuthPath(candidates = desktopAuthCandidates()) {
for (const candidate of candidates) {
try {
if (statSync(candidate).isFile()) return candidate
} catch {}
}
return candidates[0]
}
function readDesktopAuth() {
@@ -208,7 +241,7 @@ function isStale(a, marginMs = EARLY_MS) {
return exp > 0 && Date.now() >= exp - marginMs
}
// Desktop sign-in is strictly read-only: never write ~/.box-agent/config/auth.json
// Desktop sign-in is strictly read-only: never write the app's auth.json
// 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
@@ -862,7 +895,7 @@ function manualSignIn() {
function desktopSignIn() {
return {
url: "",
instructions: "直接复用本机商汤小浣熊客户端的实时登录态 (~/.box-agent/config/auth.json)。",
instructions: "直接复用本机商汤小浣熊客户端的实时登录态(只读,不写入桌面端文件)。",
method: "auto",
async callback() {
// A new seat takes the account the app holds now, and its token, and
@@ -871,7 +904,12 @@ function desktopSignIn() {
// 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 (!d) {
return {
type: "failed",
error: `未检测到本机商汤小浣熊登录态(已查找 ${desktopAuthCandidates().join("、")})`,
}
}
if (isStale(d, EARLY_MS)) {
return { type: "failed", error: "商汤小浣熊桌面端登录态已过期,请先打开商汤小浣熊客户端重新登录" }
}
@@ -1068,7 +1106,7 @@ export const RaccoonAuthPlugin = async ({ client }) => {
},
{
type: "oauth",
label: "商汤小浣熊桌面端登录态 (~/.box-agent/config/auth.json)",
label: "商汤小浣熊桌面端登录态(读取本机客户端)",
authorize: async () => desktopSignIn(),
},
{
@@ -1083,6 +1121,8 @@ export const RaccoonAuthPlugin = async ({ client }) => {
export const _internal = {
browserSignIn,
desktopAuthPath,
desktopAuthCandidates,
sameAccount,
stripBearer,
decodeJwtClaims,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-raccoon-auth",
"version": "0.1.3",
"version": "0.1.4",
"description": "OpenCode & Magpie provider plugin for SenseTime Raccoon (商汤小浣熊, xiaohuanxiong.com)",
"type": "module",
"main": "./index.mjs",
+64 -2
View File
@@ -1,7 +1,7 @@
import { afterEach, expect, test } from "bun:test"
import { mkdtempSync, rmSync, writeFileSync } from "node:fs"
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { dirname, join } from "node:path"
import { RaccoonAuthPlugin, _internal } from "./index.mjs"
function fakeJwt(claims) {
@@ -172,6 +172,68 @@ test("desktop sign-in is read-only and never writes or refreshes auth.json", asy
expect(await Bun.file(authFile).text()).toBe(originalContent)
})
// Where Raccoon desktop 1.1.3 keeps auth.json, read from its app.asar:
// clientProfile.ts puts the box-agent home at <profile>/agent, the profile at
// app.getPath("appData")/office-raccoon on macOS and at ~/.office-raccoon on
// Windows; older installs keep ~/.box-agent/config/auth.json.
test("desktop auth.json candidates follow each OS's profile layout", () => {
const home = "/h"
expect(_internal.desktopAuthCandidates(home, "darwin", {})).toEqual([
join(home, "Library", "Application Support", "office-raccoon", "agent", "config", "auth.json"),
join(home, ".box-agent", "config", "auth.json"),
])
expect(_internal.desktopAuthCandidates(home, "win32", {})).toEqual([
join(home, ".office-raccoon", "agent", "config", "auth.json"),
join(home, "AppData", "Roaming", "office-raccoon", "agent", "config", "auth.json"),
join(home, ".box-agent", "config", "auth.json"),
])
expect(_internal.desktopAuthCandidates(home, "win32", { APPDATA: "/ad" })[1]).toBe(
join("/ad", "office-raccoon", "agent", "config", "auth.json"),
)
expect(_internal.desktopAuthCandidates(home, "linux", {})).toEqual([
join(home, ".config", "office-raccoon", "agent", "config", "auth.json"),
join(home, ".box-agent", "config", "auth.json"),
])
expect(_internal.desktopAuthCandidates(home, "darwin", { BOX_AGENT_CONFIG_DIR: "/custom" })).toEqual([
join("/custom", "auth.json"),
])
})
test("desktop auth.json is found at both the current and the legacy layout", async () => {
tempDir = mkdtempSync(join(tmpdir(), "raccoon-home-"))
const tok = fakeJwt({ iss: "74350b", name: "DeskUser", exp: Math.floor(Date.now() / 1000) + 3600 })
const body = JSON.stringify({ access_token: tok, office_identity: "personal" })
const candidates = _internal.desktopAuthCandidates(tempDir, "darwin", {})
const [current, legacy] = candidates
expect(_internal.desktopAuthPath(candidates)).toBe(current) // neither: the first, read as signed out
// the box-agent build keeps the file here
mkdirSync(dirname(legacy), { recursive: true })
writeFileSync(legacy, body)
expect(_internal.desktopAuthPath(candidates)).toBe(legacy)
// the profile build writes here instead; it wins when both exist
mkdirSync(dirname(current), { recursive: true })
writeFileSync(current, body)
expect(_internal.desktopAuthPath(candidates)).toBe(current)
// and the sign-in reads it, through the env override this file's other
// desktop tests use (Bun's homedir() can't be moved after start)
const prev = process.env.RACCOON_BOX_AGENT_CONFIG_DIR
process.env.RACCOON_BOX_AGENT_CONFIG_DIR = dirname(current)
try {
const hooks = await RaccoonAuthPlugin({ client: {} })
const method = hooks.auth.methods.find((m) => m.label.includes("桌面端"))
const res = await (await method.authorize()).callback()
expect(res.type).toBe("success")
expect(res.access).toBe(tok)
} finally {
if (prev === undefined) delete process.env.RACCOON_BOX_AGENT_CONFIG_DIR
else process.env.RACCOON_BOX_AGENT_CONFIG_DIR = prev
}
})
test("usage does not invent 300/9000 floors when bills do not cover balance", async () => {
const validTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 })
startServer({