raccoon 0.1.0: SenseTime Raccoon (商汤小浣熊) provider plugin (#88, yijiemaooo-ux)

Adds packages/raccoon, @magpie-community/opencode-raccoon-auth, for SenseTime Raccoon (商汤小浣熊, xiaohuanxiong.com).
- Sign-in: through the browser, or reusing Raccoon desktop's live sign-in.
- Lists the models and makes chat requests.
- Reads account credits (balance and bills).
- Runs the daily check-in through auth.checkin, plus the desktop's first-login grant. The grant is marked settled only when the vendor gives a definite answer.

What was run, at the reviewed head 6078f92 merged onto origin/main 4e64f26:
- HOME=$(mktemp -d) bun test packages/raccoon: 21 pass, 0 fail.
- bun scripts/check.mjs: every package ✓, raccoon included.
- Whole repo, HOME=$(mktemp -d) bun test: 1575 pass, 1 fail.
  - The failure was grok's "a login's link is still handed on", a 5s timeout. Another full suite was running on the machine at the same time.
  - The test passed 5 of 5 when run alone.
  - It is filed separately.
- The raccoon code is byte-identical to c068cc5. That head was reviewed line by line on the PR, and every fix was broken by hand to check that its test goes red. 6078f92 only merges main.
- The package isn't on npm yet. magpie serves it from the dist branch until an owner publishes 0.1.0 (scripts/new-to-npm.sh).

Not verified: a real Raccoon account. Only the reply bytes the author captured were used.
This commit is contained in:
yijiemaooo-ux
2026-10-16 15:00:23 +08:00
committed by GitHub
parent 4e64f2680c
commit 118cf2edcc
6 changed files with 1779 additions and 0 deletions
+1
View File
@@ -24,6 +24,7 @@ subscription and makes its requests. The packages work in OpenCode and in
| [opendesign](packages/opendesign) | Open Design Cloud (open-design.ai), with the Open Design CLI's device sign-in | `opendesign` |
| [qoder](packages/qoder) | Qoder subscription (qoder.com), with Qoder's device sign-in | `qoder` |
| [qoder](packages/qoder) | Qoder CN subscription (qoder.cn), with Qoder CN's device sign-in | `qoder-cn` |
| [raccoon](packages/raccoon) | SenseTime Raccoon (商汤小浣熊, xiaohuanxiong.com): account credits and daily check-in, with browser sign-in or Raccoon desktop's sign-in | `raccoon` |
| [trae](packages/trae) | Trae CN (trae.cn) and Trae international (trae.ai), free tier included, with Trae's browser sign-in (experimental) | `trae-cn`, `trae-global` |
| [workbuddy](packages/workbuddy) | WorkBuddy (China build, CodeBuddy plan) | `workbuddy` |
| [workbuddy](packages/workbuddy) | WorkBuddy (international build) | `workbuddy-ai` |
+29
View File
@@ -0,0 +1,29 @@
# @magpie-community/opencode-raccoon-auth
OpenCode & Magpie provider plugin for **SenseTime Raccoon (商汤小浣熊, `xiaohuanxiong.com`)**.
## Features
- **Sign-in methods**:
1. Browser OAuth callback URL / token (paste `office-raccoon://auth/callback?code=...`, or raw JWT `access_token` / JSON token pair).
2. Raccoon desktop live session reuse (strictly read-only, reading `~/.box-agent/config/auth.json` without writing or spending desktop refresh tokens).
- **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.
- **Daily check-in & desktop onboarding grant**: supports Magpie automatic daily check-in (`+300` credits/day) and one-time desktop onboarding grant (`+3000` credits).
- **SSE model rewrite**: transparently rewrites internal upstream model names back to requested downstream models for client compatibility.
## 中文
商汤小浣熊(SenseTime Raccoon / `xiaohuanxiong.com`)OpenCode & Magpie 提供商插件。
### 功能特性
- **多种登录方式**:
1. 浏览器 OAuth 授权登录(粘贴 `office-raccoon://auth/callback?code=...` 回调链接,或直接粘贴 `access_token` / JSON)
2. 直接只读复用本机商汤小浣熊客户端实时登录态(`~/.box-agent/config/auth.json`)
- **Token 自动续期**:浏览器登录账号过期前 5 分钟自动单飞刷新。
- **动态模型目录与积分倍率**:实时同步 `/api/web/llm/v2/model_catalog`,展示模型上下文、最大输出、视觉/思考能力、积分倍率与限免(`Free`)标识。
- **积分余额与套餐查询**:展示可用积分、未过期发放额度、每日积分过期时间与 Pro/Free 套餐状态。
- **每日签到与桌面端登录奖励**:支持 Magpie 每日自动签到(`+300` 积分/天)及首次桌面端 `+3000` 积分登录奖励领取。
- **SSE 模型名重写**:将上游响应中的内部模型名重写为下游请求的 `model`,确保 Claude Code / Codex / OpenCode 等客户端兼容。
+988
View File
@@ -0,0 +1,988 @@
// OpenCode & Magpie provider plugin for SenseTime Raccoon (商汤小浣熊, xiaohuanxiong.com).
//
// 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.
import { randomUUID } from "node:crypto"
import { readFileSync, statSync } from "node:fs"
import { homedir } from "node:os"
import { join } from "node:path"
const PROVIDER_ID = "raccoon"
const PROVIDER_NAME = "商汤小浣熊"
const NPM = "@ai-sdk/openai-compatible"
const mainOrigin = () => (process.env.RACCOON_MAIN_SITE_URL || "https://xiaohuanxiong.com").replace(/\/+$/, "")
const authBase = () => (process.env.RACCOON_AUTH_API_BASE || `${mainOrigin()}/api/web/auth/v1`).replace(/\/+$/, "")
const llmBase = () => (process.env.RACCOON_LLM_BASE_URL || `${mainOrigin()}/api/web/llm/v2`).replace(/\/+$/, "")
const EARLY_MS = 60 * 1000
const LEAD_MS = 5 * 60 * 1000
const KEEP_RENEWED_MS = 60 * 1000
const CATALOG_TTL_MS = 10 * 60 * 1000
const desktopPlatform = (plat = process.platform) => (plat === "darwin" ? "desktop-mac" : "desktop-windows")
const desktopHeaders = () => ({
"X-Client-Platform": desktopPlatform(),
"X-Client-Version": "v1.0.0",
})
const FALLBACK_MODELS = [
{ id: "raccoon-8c4485", name: "Raccoon-Work", context: 1_000_000, output: 100_000, images: true, reasoning: true, rate: 1, free: false },
{ id: "raccoon-19b265", name: "Raccoon-Work-260817-A", context: 1_000_000, output: 100_000, images: false, reasoning: true, rate: 1, free: false },
{ id: "raccoon-405a1c", name: "Raccoon-Work-260817-B", context: 1_000_000, output: 100_000, images: false, reasoning: false, rate: 1, free: false },
{ id: "sn-sensenova-6-8-flash", name: "SenseNova-6.8-Flash", context: 256_000, output: 63_999, images: true, reasoning: true, rate: 0, rateWas: 0.5, free: true },
{ id: "sn-sensenova-6-8-flash-lite", name: "SenseNova-6.8-Flash-Lite", context: 256_000, output: 63_999, images: true, reasoning: true, rate: 0, rateWas: 0.5, free: true },
{ id: "sn-glm-5-3", name: "GLM-5-3", context: 1_000_000, output: 100_000, images: true, reasoning: true, rate: 0.75, free: false },
{ id: "sn-kimi-k3", name: "Kimi-K3", context: 1_000_000, output: 100_000, images: true, reasoning: true, rate: 1, free: false },
{ id: "sn-glm-5-3-flash", name: "GLM-5-3-Flash", context: 1_000_000, output: 100_000, images: false, reasoning: true, rate: 0.2, free: false },
{ id: "sn-deepseek-v4-1-flash", name: "DeepSeek-V4.1-Flash", context: 1_000_000, output: 100_000, images: false, reasoning: true, rate: 0.25, free: false },
{ id: "raccoon-chat-ml-5-5", name: "Raccoon Chat (默认)", context: 180_000, output: 80_000, images: false, reasoning: true, rate: 1, free: false },
]
// ---- JWT helpers ------------------------------------------------------------
function stripBearer(value) {
return String(value ?? "").trim().replace(/^Bearer\s+/i, "").trim()
}
function decodeJwtClaims(token) {
const raw = stripBearer(token)
const parts = raw.split(".")
if (parts.length < 2 || !parts[1]) return null
try {
const json = Buffer.from(parts[1], "base64url").toString("utf8")
const obj = JSON.parse(json)
return obj && typeof obj === "object" && !Array.isArray(obj) ? obj : null
} catch {
return null
}
}
function jwtExpiryMs(token) {
const claims = decodeJwtClaims(token)
const exp = Number(claims?.exp)
return Number.isFinite(exp) && exp > 0 ? exp * 1000 : 0
}
function hexIdToDecimal(val) {
const raw = String(val ?? "").trim().replace(/^0x/i, "")
if (!raw || !/^[0-9a-fA-F]+$/.test(raw)) return ""
try {
return BigInt("0x" + raw).toString(10)
} catch {
return ""
}
}
function extractUserId(claims) {
if (!claims) return ""
for (const k of ["sid", "iss"]) {
const dec = hexIdToDecimal(claims[k])
if (dec) return dec
}
for (const k of ["sub", "id", "user_id"]) {
const s = String(claims[k] ?? "").trim()
if (s) return s
}
return ""
}
function extractDisplayName(claims) {
return String(claims?.name ?? "").trim()
}
function vendorErrorText(payload, fallback) {
for (const k of ["details", "message", "msg"]) {
if (typeof payload?.[k] === "string" && payload[k].trim()) return payload[k].trim()
}
if (typeof payload?.error?.message === "string" && payload.error.message.trim()) {
return payload.error.message.trim()
}
return fallback
}
// ---- Desktop auth.json (~/.box-agent/config/auth.json, read-only) -----------
function desktopAuthPath() {
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")
}
return join(homedir(), ".box-agent", "config", "auth.json")
}
function readDesktopAuth() {
const p = desktopAuthPath()
try {
const st = statSync(p)
if (!st.isFile() || st.size <= 0 || st.size > 256 * 1024) return null
const raw = JSON.parse(readFileSync(p, "utf8"))
const access = stripBearer(raw?.access_token)
if (!access) return null
const claims = decodeJwtClaims(access)
const uid = extractUserId(claims)
const name = extractDisplayName(claims)
const expires = jwtExpiryMs(access)
return {
access,
refresh: "",
expires,
uid,
name: name || (uid ? `Raccoon-${uid}` : PROVIDER_NAME),
source: "desktop",
}
} catch {
return null
}
}
// ---- Token refresh (single-flight) ------------------------------------------
const renewing = new Map()
const renewed = new Map()
async function callRefreshApi(refreshToken) {
const res = await fetch(`${authBase()}/refresh`, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ refresh_token: refreshToken }),
signal: AbortSignal.timeout(30_000),
})
const text = await res.text()
let payload = {}
try {
payload = JSON.parse(text) ?? {}
} catch {}
if (!res.ok) {
const msg = vendorErrorText(payload, `HTTP ${res.status}`)
const err = new Error(`商汤小浣熊刷新 Token 失败: ${msg}`)
if (res.status >= 400 && res.status < 500) err.signIn = "expired"
throw err
}
const data = payload?.data ?? {}
const access = stripBearer(data?.access_token)
if (!access) {
const msg = vendorErrorText(payload, "未返回新 Token")
const err = new Error(`商汤小浣熊刷新 Token 失败: ${msg}`)
err.signIn = "expired"
throw err
}
const refresh = stripBearer(data?.refresh_token) || refreshToken
const expires = jwtExpiryMs(access)
const claims = decodeJwtClaims(access)
const uid = extractUserId(claims)
const name = extractDisplayName(claims)
return { access, refresh, expires, ...(uid ? { uid } : {}), ...(name ? { name } : {}) }
}
async function renewToken(a, save) {
const key = a.refresh
const done = renewed.get(key)
if (done && Date.now() - done.at < KEEP_RENEWED_MS) {
const merged = { ...a, ...done.next }
await save?.(merged)
return merged
}
let r = renewing.get(key)
if (!r) {
r = (async () => {
const next = await callRefreshApi(a.refresh)
renewed.set(key, { next, at: Date.now() })
return next
})().finally(() => renewing.delete(key))
renewing.set(key, r)
}
const next = await r
const merged = { ...a, ...next }
await save?.(merged)
return merged
}
function isStale(a, marginMs = EARLY_MS) {
const exp = Number(a?.expires) || jwtExpiryMs(a?.access)
return exp > 0 && Date.now() >= exp - marginMs
}
// Desktop sign-in is strictly read-only: never write ~/.box-agent/config/auth.json
// and never spend the desktop app's refresh token.
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
}
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)) {
const err = new Error("商汤小浣熊桌面端登录态已过期,请打开商汤小浣熊客户端重新登录")
err.signIn = "expired"
throw err
}
return { a: { ...auth, ...d }, didRenew: false }
}
let a = { ...auth }
for (let i = 0; i < 8 && a.refresh; i++) {
const d = renewed.get(a.refresh)
if (!d || Date.now() - d.at >= KEEP_RENEWED_MS) break
a = { ...a, ...d.next }
}
if (!a.expires && a.access) a.expires = jwtExpiryMs(a.access)
const alreadyRenewed = a.access !== auth.access || a.refresh !== auth.refresh
if ((alreadyRenewed || !force) && !isStale(a, EARLY_MS)) {
if (alreadyRenewed) {
try {
await client?.auth?.set?.({ path: { id: PROVIDER_ID }, body: a })
} catch {}
}
return { a, didRenew: alreadyRenewed }
}
if (!a.refresh) {
if (!force && a.access && (!a.expires || Date.now() < a.expires)) return { a, didRenew: alreadyRenewed }
const err = new Error("商汤小浣熊登录态已过期且无 refresh_token,请重新登录")
err.signIn = "expired"
throw err
}
const next = await renewToken(a, async (updated) => {
try {
await client?.auth?.set?.({ path: { id: PROVIDER_ID }, body: updated })
} catch {}
})
return { a: next, didRenew: true }
}
// ---- Models catalog ---------------------------------------------------------
let catalogCache = { origin: "", models: null, at: 0 }
function numOf(v) {
const n = typeof v === "number" ? v : typeof v === "string" && v.trim() ? Number(v.trim()) : NaN
return Number.isFinite(n) && n >= 0 ? n : undefined
}
function parseCatalog(payload) {
const data = payload?.data && typeof payload.data === "object" ? payload.data : payload
const categories = Array.isArray(data?.categories) ? data.categories : []
const seen = new Set()
const out = []
for (const cat of categories) {
for (const entry of Array.isArray(cat?.models) ? cat.models : []) {
const id = String(entry?.name || entry?.model_name || "").trim()
if (!id || seen.has(id)) continue
seen.add(id)
const codename = String(entry?.description ?? "").trim()
const displayName = String(entry?.display_name ?? "").trim() || (codename && codename.length <= 64 ? codename : id)
const tags = (Array.isArray(entry?.tags) ? entry.tags : []).map((t) => String(t ?? "").trim().toLowerCase()).filter(Boolean)
const images = tags.some((t) => t === "vision" || t === "image" || t === "image-understanding")
const context = Math.floor(numOf(entry?.context_window ?? entry?.contextWindow ?? entry?.params?.context_window ?? entry?.params?.contextWindow) || 200_000)
const output = Math.floor(numOf(entry?.max_tokens ?? entry?.maxTokens ?? entry?.params?.max_tokens ?? entry?.params?.maxTokens) || 64_000)
const baseRate = numOf(entry?.billing_multiplier)
const effRate = numOf(entry?.billing_effective_multiplier)
const rate = effRate ?? baseRate
const free = rate === 0
const rateWas = baseRate !== undefined && effRate !== undefined && effRate < baseRate ? baseRate : undefined
out.push({
id,
name: displayName,
context,
output,
images,
reasoning: true,
free,
...(rate !== undefined ? { rate } : {}),
...(rateWas !== undefined ? { rateWas } : {}),
})
}
}
if (!seen.has("raccoon-chat-ml-5-5")) {
out.push({ id: "raccoon-chat-ml-5-5", name: "Raccoon Chat (默认)", context: 180_000, output: 80_000, images: false, reasoning: true, rate: 1, free: false })
}
return out
}
async function fetchLiveModels(token) {
const base = llmBase()
if (catalogCache.models && catalogCache.origin === base && Date.now() - catalogCache.at < CATALOG_TTL_MS) {
return catalogCache.models
}
const headers = { Accept: "application/json" }
if (token) headers.Authorization = "Bearer " + stripBearer(token)
const res = await fetch(`${base}/model_catalog`, {
headers,
signal: AbortSignal.timeout(10_000),
})
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const payload = await res.json()
const models = parseCatalog(payload)
if (!models.length) throw new Error("empty catalog")
catalogCache = { origin: base, models, at: Date.now() }
return models
}
function configModels() {
return Object.fromEntries(
FALLBACK_MODELS.map((m) => [
m.id,
{
name: m.name,
limit: { context: m.context, output: m.output },
tool_call: true,
reasoning: !!m.reasoning,
attachment: !!m.images,
modalities: { input: m.images ? ["text", "image"] : ["text"], output: ["text"] },
free: !!m.free,
...(m.rate !== undefined ? { rate: m.rate } : {}),
...(m.rateWas !== undefined ? { rateWas: m.rateWas } : {}),
},
]),
)
}
function runtimeModel(provider, m) {
return {
id: m.id,
providerID: provider.id,
name: m.name,
api: { id: m.id, url: llmBase(), npm: NPM },
status: "active",
headers: {},
options: {},
cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
limit: { context: m.context ?? 0, output: m.output ?? 0 },
capabilities: {
temperature: true,
reasoning: !!m.reasoning,
attachment: !!m.images,
toolcall: true,
input: { text: true, image: !!m.images, audio: false, video: false, pdf: false },
output: { text: true, image: false, audio: false, video: false, pdf: false },
interleaved: false,
},
release_date: "",
variants: {},
free: !!m.free,
...(m.rate !== undefined ? { rate: m.rate } : {}),
...(m.rateWas !== undefined ? { rateWas: m.rateWas } : {}),
}
}
// ---- SSE model rewrite ------------------------------------------------------
function rewriteSseModel(res, requestedModel, signInHeader) {
const headers = new Headers(res.headers)
headers.set("X-Magpie-Sign-In", signInHeader)
if (!requestedModel || !res.body) {
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
}
const ct = (headers.get("content-type") || "").toLowerCase()
if (ct.includes("application/json")) {
return (async () => {
const text = await res.text()
try {
const obj = JSON.parse(text)
if (obj && typeof obj === "object" && "model" in obj) {
obj.model = requestedModel
headers.delete("content-length")
return new Response(JSON.stringify(obj), { status: res.status, statusText: res.statusText, headers })
}
} catch {}
return new Response(text, { status: res.status, statusText: res.statusText, headers })
})()
}
if (!ct.includes("text/event-stream")) {
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
}
const dec = new TextDecoder()
const enc = new TextEncoder()
let buf = ""
const rewriteLine = (line) => {
if (!line.startsWith("data:")) return line
const dataStr = line.slice(5).trim()
if (!dataStr || dataStr === "[DONE]") return line
try {
const obj = JSON.parse(dataStr)
if (obj && typeof obj === "object" && "model" in obj && obj.model !== requestedModel) {
obj.model = requestedModel
return "data: " + JSON.stringify(obj)
}
} catch {}
return line
}
const stream = res.body.pipeThrough(
new TransformStream({
transform(chunk, controller) {
buf += dec.decode(chunk, { stream: true })
const lines = buf.split(/\r?\n/)
buf = lines.pop() ?? ""
if (lines.length) {
controller.enqueue(enc.encode(lines.map(rewriteLine).join("\n") + "\n"))
}
},
flush(controller) {
buf += dec.decode()
if (buf) controller.enqueue(enc.encode(rewriteLine(buf.replace(/\r$/, ""))))
},
}),
)
headers.delete("content-length")
return new Response(stream, { status: res.status, statusText: res.statusText, headers })
}
// ---- Usage, Check-in & Onboarding -------------------------------------------
async function apiGetJson(path, token, extraHeaders = {}, method = "GET") {
const res = await fetch(`${mainOrigin()}${path}`, {
method,
headers: {
Accept: "application/json",
Authorization: "Bearer " + stripBearer(token),
...extraHeaders,
},
signal: AbortSignal.timeout(20_000),
})
const text = await res.text()
let payload = {}
try {
payload = JSON.parse(text) ?? {}
} catch {}
if (res.status === 401) {
const err = new Error(vendorErrorText(payload, "登录态已过期"))
err.status = 401
err.signIn = "expired"
throw err
}
if (!res.ok) throw new Error(vendorErrorText(payload, `HTTP ${res.status}`))
if (typeof payload?.code === "number" && payload.code !== 0) {
const err = new Error(vendorErrorText(payload, `code=${payload.code}`))
if (payload.code === 200001 || payload.code === 200003) {
err.status = 401
err.signIn = "expired"
}
throw err
}
return payload?.data ?? payload
}
function beijingTodayKey(nowMs = Date.now()) {
return new Date(nowMs + 8 * 3600_000).toISOString().slice(0, 10)
}
async function claimDesktopOnboardingGrant(token) {
try {
const d = await apiGetJson("/api/web/desktop/v1/login/points/grant", token, desktopHeaders(), "POST")
if (d?.granted === true) {
const pts = Number(d?.popup?.points)
return { points: Number.isFinite(pts) && pts > 0 ? Math.floor(pts) : 3000, settled: true }
}
if (d?.granted === false) {
return { points: 0, settled: true }
}
} catch {}
return { points: 0, settled: false }
}
async function queryUsage(token) {
const [points, entitlement, bills] = await Promise.all([
apiGetJson("/api/web/points/v1/balance", token),
apiGetJson("/api/web/auth/v1/entitlement_info", token).catch(() => null),
apiGetJson("/api/web/points/v1/bills?paging.limit=200&paging.offset=0", token).catch(() => null),
])
const avail = Math.floor(Number(points?.available_points) || 0)
const office = entitlement?.office ?? entitlement?.code ?? {}
const proEnable = office?.pro_enable === true || entitlement?.code?.pro_enable === true
const planType = office?.active_plan?.type || office?.plan_type || ""
const plan = proEnable ? (planType && planType !== "none" ? planType : "Pro") : "Free"
const expireAt = office?.pro_expired_time || office?.active_plan?.subscription_expired_at || null
// Sum only what the vendor actually reports as granted in unexpired bills.
// If bills don't account for the current balance, report the balance with no window.
let grantedFromBills = 0
let soonestExpMs = 0
let expiringPts = 0
const now = Date.now()
for (const item of Array.isArray(bills?.items) ? bills.items : []) {
const pts = Math.floor(Number(item?.points) || 0)
if (pts <= 0) continue
const expStr = typeof item?.expire_at === "string" ? item.expire_at : ""
const expMs = expStr ? Date.parse(expStr) : 0
if (expMs > 0 && expMs <= now) continue
grantedFromBills += pts
if (expMs > now) {
if (!soonestExpMs || expMs < soonestExpMs) {
soonestExpMs = expMs
expiringPts = pts
} else if (expMs === soonestExpMs) {
expiringPts += pts
}
}
}
const runsOutAt = soonestExpMs ? new Date(soonestExpMs).toISOString() : null
const runsOut = soonestExpMs ? Math.min(avail, expiringPts) : 0
if (grantedFromBills > 0 && grantedFromBills >= avail) {
const used = grantedFromBills - avail
return {
plan,
...(proEnable && expireAt ? { until: new Date(expireAt).toISOString() } : {}),
windows: [
{
name: "Credits",
used: (100 * used) / grantedFromBills,
display: `${used} / ${grantedFromBills}`,
amount: used,
limit: grantedFromBills,
unit: "credits",
...(runsOutAt ? { runsOutAt, runsOut } : {}),
},
],
}
}
return {
plan,
...(proEnable && expireAt ? { until: new Date(expireAt).toISOString() } : {}),
balance: `${avail} credits`,
windows: [],
}
}
function billKey(item) {
return String(item?.bill_id || item?.biz_id || `${item?.created_at ?? ""}:${item?.points ?? 0}:${item?.event_name ?? ""}`)
}
function isCheckinGrantBill(item, today) {
const pts = Math.floor(Number(item?.points) || 0)
if (pts <= 0) return false
const createdAt = String(item?.created_at ?? "")
if (createdAt.slice(0, 10) !== today) return false
const biz = String(item?.biz_type ?? "")
return !biz || biz === "daily_grant" || biz === "reward_grant"
}
const desktopOnboardingSettled = new Set()
async function performCheckIn(a, save) {
const token = a.access
const today = beijingTodayKey()
// Snapshot today's grant bills before triggering setting_info so a second
// check-in on the same day reports "done" rather than "claimed" again.
let beforeKeys = null
try {
const before = await apiGetJson("/api/web/points/v1/bills?paging.limit=20&paging.offset=0", token)
const items = Array.isArray(before?.items) ? before.items : []
beforeKeys = new Set(items.filter((x) => isCheckinGrantBill(x, today)).map(billKey))
} catch {}
await apiGetJson("/api/web/office/v3/setting_info", token, {
...desktopHeaders(),
"X-Raccoon-Language": "zh",
})
let onboardingPts = 0
const accountKey = a?.uid || a?.accountId || a?.access
const alreadySettled = a?.onboardingSettled || (a?.source === "desktop" && desktopOnboardingSettled.has(accountKey))
if (!alreadySettled) {
const grant = await claimDesktopOnboardingGrant(token)
onboardingPts = grant.points
if (grant.settled) {
if (a?.source === "desktop") {
desktopOnboardingSettled.add(accountKey)
} else if (save) {
await save({ ...a, onboardingSettled: true }).catch(() => {})
}
}
}
// If the before-snapshot of bills could not be read, avoid false positives
// from historical bills or repeating popup grants, while still reporting an
// onboarding grant that this call just claimed.
if (!beforeKeys) {
if (onboardingPts > 0) {
return {
outcome: "claimed",
credit: onboardingPts,
message: `桌面端首次登录奖励 +${onboardingPts}`,
}
}
return {
outcome: "done",
message: "今日已签到",
}
}
const bills = await apiGetJson("/api/web/points/v1/bills?paging.limit=20&paging.offset=0", token)
let newlyGranted = 0
let hasNewRewardBill = false
const names = []
const items = Array.isArray(bills?.items) ? bills.items : []
items.forEach((item) => {
if (!isCheckinGrantBill(item, today)) return
if (beforeKeys.has(billKey(item))) return
const pts = Math.floor(Number(item?.points) || 0)
newlyGranted += pts
if (String(item?.biz_type ?? "") === "reward_grant") hasNewRewardBill = true
const ev = String(item?.event_name || "积分发放")
if (!names.includes(ev)) names.push(ev)
})
// Sum daily check-in bills and the one-time onboarding grant when both land
// in one call, unless the onboarding grant is already present as a new
// reward_grant bill in /points/v1/bills (which would double-count it).
if (onboardingPts > 0 && !hasNewRewardBill) {
newlyGranted += onboardingPts
if (!names.includes("桌面端首次登录奖励")) names.push("桌面端首次登录奖励")
}
const totalCredit = newlyGranted
if (totalCredit > 0) {
return {
outcome: "claimed",
credit: totalCredit,
message: `${names.join(" + ") || "今日积分"} +${totalCredit}`,
}
}
return {
outcome: "done",
message: "今日已签到",
}
}
// ---- Sign-in flows ----------------------------------------------------------
function buildAuthorizeUrl(state) {
const u = new URL("/code/authorize", mainOrigin())
u.searchParams.set("login_source", "desktop")
u.searchParams.set("appname", "办公小浣熊客户端")
u.searchParams.set("state", state)
return u.toString()
}
function parseCallbackInput(raw, expectedState) {
const text = String(raw ?? "").trim()
if (!text) throw new Error("请输入回调链接或 Token")
if (text.startsWith("{")) {
const obj = JSON.parse(text)
const access = stripBearer(obj?.access_token ?? obj?.accessToken)
const refresh = stripBearer(obj?.refresh_token ?? obj?.refreshToken)
if (!access) throw new Error("JSON 中缺少 access_token")
return { direct: { access, refresh } }
}
if (text.split(".").length === 3 && !text.includes("://")) {
return { direct: { access: stripBearer(text), refresh: "" } }
}
let u
try {
u = new URL(text)
} catch {
throw new Error("无效的回调链接或 Token 格式")
}
const code = (u.searchParams.get("code") || "").trim()
const state = (u.searchParams.get("state") || "").trim()
if (!code) throw new Error("回调链接中缺少授权码 code")
if (expectedState && state && state !== expectedState) {
throw new Error("回调链接 state 不匹配,请使用本次打开页面产生的回调链接")
}
return { code }
}
async function exchangeAuthCode(code) {
const res = await fetch(`${authBase()}/login_with_authorization_code`, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ authorization_code: code }),
signal: AbortSignal.timeout(30_000),
})
const payload = await res.json().catch(() => ({}))
if (payload?.code === 200035) {
throw new Error("授权码已失效,请重新发起网页登录")
}
const data = payload?.data ?? {}
const access = stripBearer(data?.access_token)
const refresh = stripBearer(data?.refresh_token)
if (!res.ok || !access || !refresh) {
throw new Error(vendorErrorText(payload, `换取凭证失败 (HTTP ${res.status})`))
}
return { access, refresh }
}
function toSuccessAuth(access, refresh, extra = {}) {
const claims = decodeJwtClaims(access)
const uid = extractUserId(claims)
const name = extractDisplayName(claims)
const expires = jwtExpiryMs(access)
return {
type: "success",
access,
refresh: refresh || "",
expires,
accountId: name || (uid ? `Raccoon-${uid}` : PROVIDER_NAME),
uid: uid || "",
...(name ? { name } : {}),
...extra,
}
}
function browserSignIn() {
const state = randomUUID()
const url = buildAuthorizeUrl(state)
return {
url,
instructions:
"在浏览器完成商汤小浣熊登录后,复制地址栏或弹窗跳转的 office-raccoon://auth/callback?code=... 链接粘贴到下方(也支持直接粘贴 JWT access_token):",
method: "code",
async callback(input) {
try {
const parsed = parseCallbackInput(input, state)
const tokens = parsed.direct ? parsed.direct : await exchangeAuthCode(parsed.code)
return toSuccessAuth(tokens.access, tokens.refresh)
} catch (e) {
return { type: "failed", error: e?.message ?? String(e) }
}
},
}
}
function desktopSignIn() {
return {
url: "",
instructions: "直接复用本机商汤小浣熊客户端的实时登录态 (~/.box-agent/config/auth.json)。",
method: "auto",
async callback() {
const d = readDesktopAuth()
if (!d) return { type: "failed", error: "未检测到本机商汤小浣熊登录态 (~/.box-agent/config/auth.json)" }
if (isStale(d, EARLY_MS)) {
return { type: "failed", error: "商汤小浣熊桌面端登录态已过期,请先打开商汤小浣熊客户端重新登录" }
}
return {
type: "success",
access: "",
refresh: "",
expires: 0,
source: "desktop",
accountId: d.name || PROVIDER_NAME,
uid: d.uid || "",
}
},
}
}
// ---- Plugin export ----------------------------------------------------------
export const RaccoonAuthPlugin = async ({ client }) => {
const saveAuth = async (next) => {
try {
await client?.auth?.set?.({ path: { id: PROVIDER_ID }, body: next })
} catch {}
}
return {
config: async (config) => {
config.provider ??= {}
const was = config.provider[PROVIDER_ID] ?? {}
config.provider[PROVIDER_ID] = {
name: PROVIDER_NAME,
npm: NPM,
api: llmBase(),
...was,
models: { ...configModels(), ...(was.models ?? {}) },
}
},
provider: {
id: PROVIDER_ID,
async models(provider, { auth } = {}) {
try {
let token = ""
if (auth?.type === "oauth" && (auth.access || auth.source === "desktop")) {
const { a } = await currentAuth(client, auth)
token = a.access
}
const ms = await fetchLiveModels(token)
if (!ms.length) return provider.models
return Object.fromEntries(ms.map((m) => [m.id, runtimeModel(provider, m)]))
} catch {
return provider.models
}
},
},
auth: {
provider: PROVIDER_ID,
refreshLead: LEAD_MS,
async refresh(auth) {
if (auth?.type !== "oauth" || auth.source === "desktop" || !auth.access || !auth.refresh) return undefined
const { a, didRenew } = await currentAuth(client, auth, true)
if (!didRenew) return undefined
return {
access: a.access,
refresh: a.refresh,
expires: a.expires,
...(a.uid ? { uid: a.uid } : {}),
...(a.name ? { name: a.name } : {}),
}
},
async loader(getAuth) {
const auth = await getAuth()
if (auth?.type !== "oauth") return {}
return {
baseURL: llmBase(),
apiKey: "raccoon",
async fetch(input, init = {}) {
const req = input instanceof Request ? input : null
let bodyText = init?.body
if (bodyText === undefined && req) bodyText = await req.clone().text()
let requestedModel = ""
try {
const parsed = typeof bodyText === "string" ? JSON.parse(bodyText) : null
if (typeof parsed?.model === "string") requestedModel = parsed.model
} catch {}
let a
let didRenew = false
try {
;({ a, didRenew } = await currentAuth(client, await getAuth()))
} catch (e) {
const expired = e?.signIn === "expired"
return new Response(
JSON.stringify({
error: {
message: e?.message ?? String(e),
type: expired ? "authentication_error" : "api_error",
},
}),
{
status: expired ? 401 : 502,
headers: {
"Content-Type": "application/json",
"X-Magpie-Sign-In": expired ? "expired" : "kept",
},
},
)
}
const sendOnce = (cred) => {
const headers = new Headers(init?.headers ?? req?.headers)
headers.delete("x-api-key")
headers.delete("content-length")
headers.set("Authorization", "Bearer " + cred.access)
headers.set("Content-Type", "application/json")
headers.set("Accept", "*/*")
return fetch(req ? req.url : input, {
...init,
method: init?.method ?? req?.method ?? "POST",
headers,
body: bodyText,
})
}
let res = await sendOnce(a)
if (res.status === 401 && a.refresh && a.source !== "desktop") {
try {
const retryAuth = await currentAuth(client, a, true)
a = retryAuth.a
didRenew = true
res = await sendOnce(a)
} catch {}
}
const signInState = res.status === 401 ? "expired" : didRenew && res.ok ? "renewed" : "kept"
return rewriteSseModel(res, requestedModel, signInState)
},
}
},
async usage(getAuth) {
const auth = await getAuth()
if (auth?.type !== "oauth" || !(auth.access || auth.source === "desktop")) {
return { error: "not signed in", signIn: "kept" }
}
try {
let { a, didRenew } = await currentAuth(client, auth)
let result
try {
result = await queryUsage(a.access)
} catch (e) {
if (e?.status === 401 && a.refresh && a.source !== "desktop") {
const retryAuth = await currentAuth(client, a, true)
a = retryAuth.a
didRenew = true
result = await queryUsage(a.access)
} else {
throw e
}
}
return {
...result,
user: a.name || auth.accountId || a.uid,
signIn: didRenew ? "renewed" : "kept",
}
} catch (e) {
return {
error: e?.message ?? String(e),
signIn: e?.signIn === "expired" ? "expired" : "kept",
}
}
},
async checkin(getAuth) {
const auth = await getAuth()
if (auth?.type !== "oauth" || !(auth.access || auth.source === "desktop")) {
return { outcome: "failed", message: "not signed in" }
}
try {
let { a } = await currentAuth(client, auth)
try {
return await performCheckIn(a, saveAuth)
} catch (e) {
if (e?.status === 401 && a.refresh && a.source !== "desktop") {
;({ a } = await currentAuth(client, a, true))
return await performCheckIn(a, saveAuth)
}
throw e
}
} catch (e) {
return { outcome: "failed", message: e?.message ?? String(e) }
}
},
methods: [
{
type: "oauth",
label: "商汤小浣熊账号 (浏览器登录 / 粘贴回调或 Token)",
authorize: async () => browserSignIn(),
},
{
type: "oauth",
label: "商汤小浣熊桌面端登录态 (~/.box-agent/config/auth.json)",
authorize: async () => desktopSignIn(),
},
],
},
}
}
export const _internal = {
stripBearer,
decodeJwtClaims,
jwtExpiryMs,
hexIdToDecimal,
extractUserId,
extractDisplayName,
parseCatalog,
parseCallbackInput,
rewriteSseModel,
beijingTodayKey,
billKey,
renewToken,
desktopPlatform,
desktopOnboardingSettled,
renewed,
renewing,
}
File diff suppressed because one or more lines are too long
+731
View File
@@ -0,0 +1,731 @@
import { afterEach, expect, test } from "bun:test"
import { mkdtempSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { RaccoonAuthPlugin, _internal } from "./index.mjs"
function fakeJwt(claims) {
const h = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" })).toString("base64url")
const p = Buffer.from(JSON.stringify(claims)).toString("base64url")
return `${h}.${p}.sig`
}
let server = null
let tempDir = null
afterEach(() => {
server?.stop(true)
server = null
if (tempDir) {
rmSync(tempDir, { recursive: true, force: true })
tempDir = null
}
delete process.env.RACCOON_MAIN_SITE_URL
delete process.env.RACCOON_BOX_AGENT_CONFIG_DIR
_internal.renewed.clear()
_internal.renewing.clear()
})
function startServer(routes) {
server = Bun.serve({
port: 0,
async fetch(req) {
const u = new URL(req.url)
const key = `${req.method} ${u.pathname}`
const handler = routes[key] || routes[u.pathname]
if (!handler) return new Response(JSON.stringify({ code: 404, message: "not found" }), { status: 404 })
return handler(req, u)
},
})
process.env.RACCOON_MAIN_SITE_URL = `http://127.0.0.1:${server.port}`
return server
}
test("decodes JWT claims and converts hex user id to decimal", () => {
const tok = fakeJwt({ iss: "74350b", name: "RaccoonMason", exp: 1800000000 })
const claims = _internal.decodeJwtClaims("Bearer " + tok)
expect(_internal.extractUserId(claims)).toBe("7615755")
expect(_internal.extractDisplayName(claims)).toBe("RaccoonMason")
expect(_internal.jwtExpiryMs(tok)).toBe(1800000000 * 1000)
})
test("parses model_catalog entries with effective multiplier and limited_free", () => {
const models = _internal.parseCatalog({
code: 0,
data: {
categories: [
{
type: "chat",
models: [
{
name: "raccoon-8c4485",
description: "Raccoon-Work",
tags: ["general", "code", "vision", "reasoning"],
params: { context_window: 1000000, max_tokens: 100000 },
billing_multiplier: 1,
billing_effective_multiplier: 1,
},
{
name: "sn-sensenova-6-8-flash",
description: "SenseNova-6.8-Flash",
tags: ["general", "vision", "fast"],
params: { context_window: 256000, max_tokens: 63999 },
billing_multiplier: 0.5,
billing_effective_multiplier: 0,
billing_status: "limited_free",
},
],
},
],
},
})
expect(models.find((m) => m.id === "raccoon-8c4485")).toMatchObject({
id: "raccoon-8c4485",
name: "Raccoon-Work",
context: 1000000,
output: 100000,
images: true,
free: false,
rate: 1,
})
expect(models.find((m) => m.id === "sn-sensenova-6-8-flash")).toMatchObject({
id: "sn-sensenova-6-8-flash",
name: "SenseNova-6.8-Flash",
images: true,
free: true,
rate: 0,
rateWas: 0.5,
})
})
test("parses callback URL and direct tokens", () => {
expect(_internal.parseCallbackInput("office-raccoon://auth/callback?code=abc123&state=s1", "s1")).toEqual({
code: "abc123",
})
expect(() => _internal.parseCallbackInput("office-raccoon://auth/callback?code=abc123&state=wrong", "s1")).toThrow()
const tok = fakeJwt({ iss: "74350b", exp: 1800000000 })
expect(_internal.parseCallbackInput(tok, "s1")).toEqual({
direct: { access: tok, refresh: "" },
})
})
test("rewrites SSE chunk model name and normalizes CRLF endings", async () => {
const body = 'data: {"id":"1","model":"internal-raccoon","choices":[{"delta":{"content":"hi"}}]}\r\n\r\ndata: [DONE]\r\n\r\n'
const orig = new Response(body, {
status: 200,
headers: { "content-type": "text/event-stream" },
})
const rewritten = await _internal.rewriteSseModel(orig, "sn-glm-5-3", "kept")
expect(rewritten.headers.get("x-magpie-sign-in")).toBe("kept")
const text = await rewritten.text()
expect(text).toContain('"model":"sn-glm-5-3"')
expect(text).not.toContain("\r")
expect(text).toContain("data: [DONE]")
})
test("refresh 400 params_invalid_error marks signIn expired and uses details", async () => {
startServer({
"POST /api/web/auth/v1/refresh": () =>
new Response(
JSON.stringify({
code: 100002,
message: "params_invalid_error",
details: "refresh token is invalid or expired",
}),
{ status: 400, headers: { "content-type": "application/json" } },
),
})
const hooks = await RaccoonAuthPlugin({ client: {} })
const staleTok = fakeJwt({ iss: "74350b", exp: Math.floor(Date.now() / 1000) - 10 })
const u = await hooks.auth.usage(async () => ({
type: "oauth",
access: staleTok,
refresh: "bad-rt",
expires: Date.now() - 10_000,
}))
expect(u.signIn).toBe("expired")
expect(u.error).toContain("refresh token is invalid or expired")
})
test("desktop sign-in is read-only and never writes or refreshes auth.json", async () => {
tempDir = mkdtempSync(join(tmpdir(), "raccoon-test-"))
process.env.RACCOON_BOX_AGENT_CONFIG_DIR = tempDir
const authFile = join(tempDir, "auth.json")
const staleTok = fakeJwt({ iss: "74350b", name: "DeskUser", exp: Math.floor(Date.now() / 1000) - 10 })
const originalContent = JSON.stringify({ access_token: staleTok, refresh_token: "D1" }, null, 2)
writeFileSync(authFile, originalContent)
let refreshCalled = false
startServer({
"POST /api/web/auth/v1/refresh": () => {
refreshCalled = true
return Response.json({ code: 0, data: { access_token: "x", refresh_token: "D2" } })
},
})
const hooks = await RaccoonAuthPlugin({ client: {} })
const res = await hooks.auth.usage(async () => ({ type: "oauth", source: "desktop" }))
expect(refreshCalled).toBe(false)
expect(res.signIn).toBe("expired")
expect(await Bun.file(authFile).text()).toBe(originalContent)
})
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({
"GET /api/web/points/v1/balance": () =>
Response.json({
code: 0,
data: { available_points: 500, daily_points: 0, reward_points: 500, monthly_points: 0, topup_points: 0 },
}),
"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 hooks = await RaccoonAuthPlugin({ client: {} })
const u = await hooks.auth.usage(async () => ({
type: "oauth",
access: validTok,
refresh: "rt1",
expires: Date.now() + 3600_000,
}))
expect(u.balance).toBe("500 credits")
expect(u.windows).toEqual([])
})
test("usage reports Credits window when unexpired bills account for total granted", async () => {
const validTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 })
startServer({
"GET /api/web/points/v1/balance": () =>
Response.json({
code: 0,
data: { available_points: 9519, daily_points: 519, reward_points: 9000, monthly_points: 0, topup_points: 0 },
}),
"GET /api/web/auth/v1/entitlement_info": () => Response.json({ code: 0, data: {} }),
"GET /api/web/points/v1/bills": () =>
Response.json({
code: 0,
data: {
items: [
{ bill_id: "b1", biz_type: "daily_grant", points: 300, expire_at: "2029-10-18T23:59:59+08:00" },
{ bill_id: "b2", biz_type: "daily_grant", points: 300, expire_at: "2029-10-17T23:59:59+08:00" },
{ bill_id: "b3", biz_type: "reward_grant", points: 9000 },
],
},
}),
})
const hooks = await RaccoonAuthPlugin({ client: {} })
const u = await hooks.auth.usage(async () => ({
type: "oauth",
access: validTok,
refresh: "rt1",
expires: Date.now() + 3600_000,
}))
expect(u.balance).toBeUndefined()
expect(u.windows.length).toBe(1)
expect(u.windows[0]).toMatchObject({
name: "Credits",
amount: 81,
limit: 9600,
display: "81 / 9600",
unit: "credits",
runsOutAt: "2029-10-17T15:59:59.000Z",
runsOut: 300,
})
})
test("checkin preserves renewed tokens, claims once, and returns done on second call", 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 })
const today = _internal.beijingTodayKey()
const billItems = []
startServer({
"POST /api/web/auth/v1/refresh": () =>
Response.json({ code: 0, data: { access_token: freshTok, refresh_token: "C2" } }),
"GET /api/web/office/v3/setting_info": () => {
if (!billItems.some((b) => b.bill_id === "daily-1")) {
billItems.push({
bill_id: "daily-1",
biz_type: "daily_grant",
event_name: "每日积分发放",
points: 300,
created_at: `${today}T08:00:00+08:00`,
})
}
return Response.json({ code: 0, data: {} })
},
"POST /api/web/desktop/v1/login/points/grant": () =>
Response.json({ code: 0, data: { granted: false } }),
"GET /api/web/points/v1/bills": () =>
Response.json({ code: 0, data: { items: billItems } }),
})
const saves = []
let stored = {
type: "oauth",
access: staleTok,
refresh: "C1",
expires: Date.now() - 5000,
}
const client = {
auth: {
set: async ({ body }) => {
saves.push(body)
stored = body
},
},
}
const hooks = await RaccoonAuthPlugin({ client })
const r1 = await hooks.auth.checkin(async () => stored)
expect(r1).toMatchObject({ outcome: "claimed", credit: 300 })
expect(saves.at(-1).access).toBe(freshTok)
expect(saves.at(-1).refresh).toBe("C2")
expect(saves.at(-1).onboardingSettled).toBe(true)
const r2 = await hooks.auth.checkin(async () => stored)
expect(r2).toMatchObject({ outcome: "done" })
})
test("checkin returns failed instead of throwing when upstream errors", async () => {
const validTok = fakeJwt({ iss: "74350b", exp: Math.floor(Date.now() / 1000) + 3600 })
startServer({
"GET /api/web/office/v3/setting_info": () => new Response("unauthorized", { status: 401 }),
"GET /api/web/points/v1/bills": () => new Response("unauthorized", { status: 401 }),
})
const hooks = await RaccoonAuthPlugin({ client: {} })
const r = await hooks.auth.checkin(async () => ({
type: "oauth",
access: validTok,
refresh: "",
expires: Date.now() + 3600_000,
onboardingSettled: true,
}))
expect(r.outcome).toBe("failed")
})
test("60s renewed cache persists tokens via save without calling /refresh twice", 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 })
let refreshCount = 0
startServer({
"POST /api/web/auth/v1/refresh": () => {
refreshCount += 1
return Response.json({ code: 0, data: { access_token: freshTok, refresh_token: `RT-${refreshCount}` } })
},
"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: [] } }),
})
const savesA = []
const hooksA = await RaccoonAuthPlugin({
client: { auth: { set: async ({ body }) => savesA.push(body) } },
})
const initialAuth = { type: "oauth", access: staleTok, refresh: "RT-0", expires: Date.now() - 5000 }
// First path renews RT-0 -> RT-1
const u1 = await hooksA.auth.usage(async () => initialAuth)
expect(u1.signIn).toBe("renewed")
expect(refreshCount).toBe(1)
expect(savesA.at(-1)?.refresh).toBe("RT-1")
// Second path (e.g. auth.refresh or another caller still holding RT-0 within 60s)
// must reuse the cached renewal, persist it, and NOT call /refresh a second time.
const savesB = []
const hooksB = await RaccoonAuthPlugin({
client: { auth: { set: async ({ body }) => savesB.push(body) } },
})
const refreshed = await hooksB.auth.refresh(initialAuth)
expect(refreshCount).toBe(1)
expect(refreshed?.access).toBe(freshTok)
expect(refreshed?.refresh).toBe("RT-1")
expect(savesB.at(-1)?.refresh).toBe("RT-1")
})
test("loader refreshes on 401, strips x-api-key, rewrites split SSE stream, and passes 402 through", async () => {
const tok1 = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 })
const tok2 = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 7200 })
const seenHeaders = []
let chatCalls = 0
startServer({
"POST /api/web/auth/v1/refresh": () =>
Response.json({ code: 0, data: { access_token: tok2, refresh_token: "R2" } }),
"POST /api/web/llm/v2/chat/completions": async (req) => {
chatCalls += 1
seenHeaders.push({
auth: req.headers.get("authorization"),
apiKey: req.headers.get("x-api-key"),
})
if (chatCalls === 1) {
return Response.json({ code: 200003, message: "authorization_verify_error" }, { status: 401 })
}
if (chatCalls === 2) {
const enc = new TextEncoder()
const stream = new ReadableStream({
start(controller) {
controller.enqueue(enc.encode('data: {"id":"1","model":"internal-m"'))
controller.enqueue(enc.encode(',"choices":[{"delta":{"content":"ok"}}]}\r\n\r\ndata: [DONE]\r\n\r\n'))
controller.close()
},
})
return new Response(stream, {
status: 200,
headers: { "content-type": "text/event-stream" },
})
}
return Response.json({ error: { message: "insufficient quota" } }, { status: 402 })
},
})
let stored = { type: "oauth", access: tok1, refresh: "R1", expires: Date.now() + 3600_000 }
const hooks = await RaccoonAuthPlugin({
client: {
auth: {
set: async ({ body }) => {
stored = body
},
},
},
})
const loaded = await hooks.auth.loader(async () => stored)
const res = await loaded.fetch(`${ loaded.baseURL }/chat/completions`, {
method: "POST",
headers: { "x-api-key": "should-be-dropped", "content-type": "application/json" },
body: JSON.stringify({ model: "sn-kimi-k3", messages: [{ role: "user", content: "hi" }], stream: true }),
})
expect(res.status).toBe(200)
expect(res.headers.get("x-magpie-sign-in")).toBe("renewed")
expect(seenHeaders[0]).toEqual({ auth: `Bearer ${tok1}`, apiKey: null })
expect(seenHeaders[1]).toEqual({ auth: `Bearer ${tok2}`, apiKey: null })
const text = await res.text()
expect(text).toContain('"model":"sn-kimi-k3"')
expect(text).toContain("data: [DONE]")
const res402 = await loaded.fetch(`${ loaded.baseURL }/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "sn-kimi-k3", messages: [] }),
})
expect(res402.status).toBe(402)
expect(res402.headers.get("x-magpie-sign-in")).toBe("kept")
})
test("desktop sign-in marks expired when desktop app switches to another account", async () => {
tempDir = mkdtempSync(join(tmpdir(), "raccoon-test-"))
process.env.RACCOON_BOX_AGENT_CONFIG_DIR = tempDir
const authFile = join(tempDir, "auth.json")
const otherUserTok = fakeJwt({ iss: "888888", name: "OtherUser", exp: Math.floor(Date.now() / 1000) + 3600 })
writeFileSync(authFile, JSON.stringify({ access_token: otherUserTok, refresh_token: "D1" }))
const hooks = await RaccoonAuthPlugin({ client: {} })
const u = await hooks.auth.usage(async () => ({
type: "oauth",
source: "desktop",
uid: "7615755",
accountId: "RaccoonMason",
}))
expect(u.signIn).toBe("expired")
expect(u.error).toContain("切换为其他账号")
})
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 })
let refreshCalls = 0
startServer({
"POST /api/web/auth/v1/refresh": () => {
refreshCalls += 1
return Response.json({ code: 0, data: { access_token: freshTok, refresh_token: "RT-NEW" } })
},
})
const saves1 = []
const a1 = { access: staleTok, refresh: "RT-COMMON", expires: Date.now() - 5000 }
const r1 = await _internal.renewToken(a1, async (s) => saves1.push(s))
expect(refreshCalls).toBe(1)
expect(saves1.length).toBe(1)
expect(r1.refresh).toBe("RT-NEW")
const saves2 = []
const a2 = { access: staleTok, refresh: "RT-COMMON", expires: Date.now() - 5000, extra: "preserved" }
const r2 = await _internal.renewToken(a2, async (s) => saves2.push(s))
expect(refreshCalls).toBe(1)
expect(saves2.length).toBe(1)
expect(saves2[0]).toMatchObject({ access: freshTok, refresh: "RT-NEW", extra: "preserved" })
expect(r2).toMatchObject({ access: freshTok, refresh: "RT-NEW", extra: "preserved" })
})
test("checkin returns done instead of claimed when before-snapshot bills fail", async () => {
const validTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 })
const today = _internal.beijingTodayKey()
let billCalls = 0
startServer({
"GET /api/web/office/v3/setting_info": () =>
Response.json({
code: 0,
data: { point_grant_popups: { points: 300 } },
}),
"GET /api/web/points/v1/bills": () => {
billCalls += 1
if (billCalls === 1) {
// First snapshot fails
return new Response("gateway timeout", { status: 504 })
}
return Response.json({
code: 0,
data: {
items: [
{ bill_id: "b1", biz_type: "daily_grant", points: 300, created_at: `${today}T08:00:00+08:00` },
],
},
})
},
})
const hooks = await RaccoonAuthPlugin({ client: {} })
const res = await hooks.auth.checkin(async () => ({
type: "oauth",
access: validTok,
refresh: "",
expires: Date.now() + 3600_000,
onboardingSettled: true,
}))
expect(res.outcome).toBe("done")
})
test("billKey does not depend on list index when new bills are prepended", () => {
const itemOld = { created_at: "2026-10-12T08:00:00+08:00", points: 300, event_name: "每日积分发放" }
const key1 = _internal.billKey(itemOld)
const itemNew = { created_at: "2026-10-12T09:00:00+08:00", points: 100, event_name: "补充积分" }
const key2 = _internal.billKey(itemOld)
expect(key1).toBe(key2)
expect(_internal.billKey(itemNew)).not.toBe(key1)
})
test("desktop checkin requests onboarding grant only once across runs", async () => {
tempDir = mkdtempSync(join(tmpdir(), "raccoon-test-"))
process.env.RACCOON_BOX_AGENT_CONFIG_DIR = tempDir
const authFile = join(tempDir, "auth.json")
const deskTok = fakeJwt({ iss: "74350b", name: "DeskUser", exp: Math.floor(Date.now() / 1000) + 3600 })
writeFileSync(authFile, JSON.stringify({ access_token: deskTok, refresh_token: "D1" }))
_internal.desktopOnboardingSettled.clear()
let grantCalls = 0
startServer({
"POST /api/web/desktop/v1/login/points/grant": () => {
grantCalls += 1
return Response.json({ code: 0, data: { granted: false } })
},
"GET /api/web/office/v3/setting_info": () => Response.json({ code: 0, data: {} }),
"GET /api/web/points/v1/bills": () => Response.json({ code: 0, data: { items: [] } }),
})
const hooks = await RaccoonAuthPlugin({ client: {} })
const authInput = { type: "oauth", source: "desktop", uid: "7615755" }
await hooks.auth.checkin(async () => authInput)
expect(grantCalls).toBe(1)
await hooks.auth.checkin(async () => authInput)
expect(grantCalls).toBe(1) // Second call must NOT POST onboarding grant again
})
test("failed onboarding grant (500) is not marked settled and retries on next checkin", async () => {
const validTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 })
_internal.desktopOnboardingSettled.clear()
let grantCalls = 0
startServer({
"POST /api/web/desktop/v1/login/points/grant": () => {
grantCalls += 1
if (grantCalls === 1) {
return new Response("internal server error", { status: 500 })
}
if (grantCalls === 2) {
return Response.json({ code: 0, data: {} })
}
return Response.json({ code: 0, data: { granted: true, popup: { points: 3000 } } })
},
"GET /api/web/office/v3/setting_info": () => Response.json({ code: 0, data: {} }),
"GET /api/web/points/v1/bills": () => Response.json({ code: 0, data: { items: [] } }),
})
// 1. Browser sign-in: 500 on first try must NOT save onboardingSettled: true
const saves = []
let browserStored = { type: "oauth", access: validTok, refresh: "R1", expires: Date.now() + 3600_000 }
const hooks = await RaccoonAuthPlugin({
client: {
auth: {
set: async ({ body }) => {
saves.push(body)
browserStored = body
},
},
},
})
const r1 = await hooks.auth.checkin(async () => browserStored)
expect(r1.outcome).toBe("done")
expect(grantCalls).toBe(1)
expect(saves.length).toBe(0)
expect(browserStored.onboardingSettled).toBeUndefined()
// 2. Desktop sign-in: 500 on try #2 must NOT add to desktopOnboardingSettled
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 r2 = await hooks.auth.checkin(async () => deskAuth)
expect(r2.outcome).toBe("done")
expect(grantCalls).toBe(2)
expect(_internal.desktopOnboardingSettled.has("7615755")).toBe(false)
// 3. Next browser checkin succeeds (200 granted: true) -> claims +3000 and saves onboardingSettled: true
const r3 = await hooks.auth.checkin(async () => browserStored)
expect(r3).toMatchObject({ outcome: "claimed", credit: 3000 })
expect(grantCalls).toBe(3)
expect(browserStored.onboardingSettled).toBe(true)
// 4. Next desktop checkin succeeds -> claims +3000 and marks desktopOnboardingSettled
const r4 = await hooks.auth.checkin(async () => deskAuth)
expect(r4).toMatchObject({ outcome: "claimed", credit: 3000 })
expect(grantCalls).toBe(4)
expect(_internal.desktopOnboardingSettled.has("7615755")).toBe(true)
})
test("checkin reports claimed onboarding grant when before-snapshot fails, and sums daily + onboarding without double-counting", async () => {
const validTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 })
const today = _internal.beijingTodayKey()
let scenario = "snapshot-fails"
let billCallInScenario = 0
startServer({
"GET /api/web/office/v3/setting_info": () => Response.json({ code: 0, data: {} }),
"POST /api/web/desktop/v1/login/points/grant": () =>
Response.json({ code: 0, data: { granted: true, popup: { points: 3000 } } }),
"GET /api/web/points/v1/bills": () => {
billCallInScenario += 1
if (scenario === "snapshot-fails") {
return new Response("bad gateway", { status: 502 })
}
if (billCallInScenario === 1) {
return Response.json({ code: 0, data: { items: [] } })
}
if (scenario === "both-land-no-reward-bill") {
return Response.json({
code: 0,
data: {
items: [
{ bill_id: "d1", biz_type: "daily_grant", event_name: "每日积分发放", points: 300, created_at: `${today}T08:00:00+08:00` },
],
},
})
}
return Response.json({
code: 0,
data: {
items: [
{ bill_id: "d1", biz_type: "daily_grant", event_name: "每日积分发放", points: 300, created_at: `${today}T08:00:00+08:00` },
{ bill_id: "r1", biz_type: "reward_grant", event_name: "新人礼", points: 3000, created_at: `${today}T08:00:01+08:00` },
],
},
})
},
})
const hooks = await RaccoonAuthPlugin({ client: {} })
// Sub-case 1: before-snapshot fails, but onboarding grant succeeded (+3000)
const res1 = await hooks.auth.checkin(async () => ({
type: "oauth",
access: validTok,
refresh: "R1",
expires: Date.now() + 3600_000,
}))
expect(res1).toMatchObject({ outcome: "claimed", credit: 3000 })
// Sub-case 2: both daily (+300) and onboarding (+3000) land, and bills only has daily_grant -> sum is 3300
scenario = "both-land-no-reward-bill"
billCallInScenario = 0
const res2 = await hooks.auth.checkin(async () => ({
type: "oauth",
access: validTok,
refresh: "R1",
expires: Date.now() + 3600_000,
}))
expect(res2).toMatchObject({ outcome: "claimed", credit: 3300 })
// Sub-case 3: bills already includes the new reward_grant (+3000) -> no double count (still 3300)
scenario = "both-land-with-reward-bill"
billCallInScenario = 0
const res3 = await hooks.auth.checkin(async () => ({
type: "oauth",
access: validTok,
refresh: "R1",
expires: Date.now() + 3600_000,
}))
expect(res3).toMatchObject({ outcome: "claimed", credit: 3300 })
})
test("setting_info popup without new bill reports done when before-snapshot succeeds", async () => {
const validTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 })
startServer({
"GET /api/web/office/v3/setting_info": () =>
Response.json({
code: 0,
data: {
point_grant_popups: { points: 300 },
point_grant_toast: { points: 300 },
},
}),
"GET /api/web/points/v1/bills": () => Response.json({ code: 0, data: { items: [] } }),
})
const hooks = await RaccoonAuthPlugin({ client: {} })
const res = await hooks.auth.checkin(async () => ({
type: "oauth",
access: validTok,
refresh: "R1",
expires: Date.now() + 3600_000,
onboardingSettled: true,
}))
expect(res.outcome).toBe("done")
})
test("X-Client-Platform header derives desktop-mac on darwin and desktop-windows otherwise", async () => {
expect(_internal.desktopPlatform("darwin")).toBe("desktop-mac")
expect(_internal.desktopPlatform("win32")).toBe("desktop-windows")
expect(_internal.desktopPlatform("linux")).toBe("desktop-windows")
const validTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 })
const seenPlatforms = []
startServer({
"GET /api/web/office/v3/setting_info": (req) => {
seenPlatforms.push(req.headers.get("x-client-platform"))
return Response.json({ code: 0, data: {} })
},
"GET /api/web/points/v1/bills": () => Response.json({ code: 0, data: { items: [] } }),
})
const origDesc = Object.getOwnPropertyDescriptor(process, "platform")
try {
const hooks = await RaccoonAuthPlugin({ client: {} })
const authObj = { type: "oauth", access: validTok, refresh: "R1", expires: Date.now() + 3600_000, onboardingSettled: true }
Object.defineProperty(process, "platform", { value: "darwin", configurable: true })
await hooks.auth.checkin(async () => authObj)
Object.defineProperty(process, "platform", { value: "win32", configurable: true })
await hooks.auth.checkin(async () => authObj)
expect(seenPlatforms).toEqual(["desktop-mac", "desktop-windows"])
} finally {
if (origDesc) Object.defineProperty(process, "platform", origDesc)
}
})
+2
View File
@@ -33,6 +33,8 @@
"summary": { "en": "Trae CN (trae.cn) and Trae international (trae.ai) models with your own account, free tier included — Trae's own browser sign-in. Experimental.", "zh": "用 Trae CN(trae.cn)与 Trae 国际版(trae.ai)账号使用各自的模型,含免费版,使用 Trae 自己的浏览器登录。实验性。" } },
{ "package": "@magpie-community/opencode-opendesign-auth", "name": "Open Design", "providers": ["opendesign"], "community": true,
"summary": { "en": "Open Design Cloud's Design Plan (open-design.ai): the account's device sign-in, the models the plan entitles it to, and the plan's 5-hour and 7-day allowance and wallet balance.", "zh": "Open Design Cloud 的 Design Plan(open-design.ai):账号设备登录、套餐可用的模型,以及 5 小时与 7 天额度、钱包余额。" } },
{ "package": "@magpie-community/opencode-raccoon-auth", "name": "商汤小浣熊", "icon": "sensenova-color", "providers": ["raccoon"], "community": true,
"summary": { "en": "SenseTime Raccoon (xiaohuanxiong.com) models, account credits and daily check-in, with browser sign-in or Raccoon desktop's live sign-in.", "zh": "商汤小浣熊(xiaohuanxiong.com)模型、积分余额与每日签到,支持浏览器登录或直接复用小浣熊桌面端登录态。" } },
{ "package": "@magpie-community/middleware-param-override", "name": "Param Override", "kind": "middleware", "community": true,
"summary": { "en": "New API's parameter override: set, delete, move or rewrite fields of every request, by model or by condition.", "zh": "New API 的参数覆盖:按模型或条件设置、删除、移动或改写每个请求的字段。" } },
{ "package": "@magpie-community/middleware-model-map", "name": "Model Map", "kind": "middleware", "community": true,