diff --git a/packages/raccoon/README.md b/packages/raccoon/README.md index 538ca25..3702f4e 100644 --- a/packages/raccoon/README.md +++ b/packages/raccoon/README.md @@ -5,8 +5,9 @@ OpenCode & Magpie provider plugin for **SenseTime Raccoon (商汤小浣熊, `xia ## 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). + 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). - **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. @@ -20,10 +21,15 @@ OpenCode & Magpie provider plugin for **SenseTime Raccoon (商汤小浣熊, `xia ### 功能特性 - **多种登录方式**: - 1. 浏览器 OAuth 授权登录(粘贴 `office-raccoon://auth/callback?code=...` 回调链接,或直接粘贴 `access_token` / JSON) - 2. 直接只读复用本机商汤小浣熊客户端实时登录态(`~/.box-agent/config/auth.json`) + 1. 浏览器 OAuth 授权登录:确认授权后自动返回,无需安装官方桌面客户端,也无需输入短信验证码或粘贴网页地址。 + 2. 手动回调 / Token 备用入口:粘贴 `office-raccoon://auth/callback?code=...` 完整回调链接,或 `access_token` / JSON;普通授权网页地址和单独授权码不能代替完整回调。 + 3. 直接只读复用本机商汤小浣熊客户端实时登录态(`~/.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 等客户端兼容。 + +### 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. diff --git a/packages/raccoon/index.mjs b/packages/raccoon/index.mjs index c432673..8300703 100644 --- a/packages/raccoon/index.mjs +++ b/packages/raccoon/index.mjs @@ -6,7 +6,8 @@ // ~/.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 { randomUUID, randomBytes } from "node:crypto" +import { createServer } from "node:http" import { readFileSync, statSync } from "node:fs" import { homedir } from "node:os" import { join } from "node:path" @@ -736,7 +737,73 @@ function toSuccessAuth(access, refresh, extra = {}) { } } -function browserSignIn() { +async function browserSignIn(timeoutMs = 10 * 60 * 1000) { + // The current authorize page accepts desktop loopback callbacks only with + // a 64-character hex state and a 127.0.0.1 /auth/callback URL. + const state = randomBytes(32).toString("hex") + const url = new URL(buildAuthorizeUrl(state)) + url.searchParams.set("desktop_callback", "loopback") + let complete, timer, origin, received = false, settled = false + const done = new Promise((resolve) => { complete = resolve }) + const finish = (result) => { + if (settled) return + settled = true + clearTimeout(timer) + complete(result) + server.close() + server.closeIdleConnections?.() + } + const server = createServer(async (req, res) => { + const reply = (status, text) => { + res.writeHead(status, { + "Content-Type": "text/plain; charset=utf-8", + "Cache-Control": "no-store", + "Referrer-Policy": "no-referrer", + "Content-Security-Policy": "default-src 'none'", + }) + res.end(text) + } + const url = new URL(req.url || "/", "http://127.0.0.1") + if (req.headers.host !== origin || url.pathname !== "/auth/callback") return reply(404, "Not found") + if (req.method !== "GET") return reply(405, "Method not allowed") + const q = url.searchParams + if (q.getAll("state").length !== 1 || q.get("state") !== state) return reply(400, "回调不属于本次登录,请回到原授权页重试。") + if (settled || received) return reply(409, "本次回调已经处理,请回到 Magpie 查看结果。") + if (q.get("error")) { + reply(400, "登录未获授权,请回到 Magpie 重新登录。") + finish({ type: "failed", error: "商汤小浣熊授权被拒绝,请重新登录" }) + return + } + const code = q.get("code") || "" + if (q.getAll("code").length !== 1 || !code || code.length > 4096) return reply(400, "回调缺少有效授权码,请回到原授权页重试。") + received = true + try { + const tokens = await exchangeAuthCode(code) + if (settled) return reply(408, "登录已超时,请回到 Magpie 重新登录。") + reply(200, "商汤小浣熊登录成功,可以关闭此页并返回 Magpie。") + finish(toSuccessAuth(tokens.access, tokens.refresh)) + } catch (e) { + reply(502, "登录未完成,请返回 Magpie 查看错误并重新登录。") + finish({ type: "failed", error: e?.message ?? String(e) }) + } + }) + await new Promise((resolve, reject) => { + server.once("error", reject) + server.listen(0, "127.0.0.1", resolve) + }) + origin = `127.0.0.1:${server.address().port}` + url.searchParams.set("redirect", `http://${origin}/auth/callback`) + timer = setTimeout(() => finish({ type: "failed", error: "商汤小浣熊登录超时,请重新登录" }), timeoutMs) + timer.unref?.() + return { + url: url.toString(), + instructions: "在浏览器完成商汤小浣熊登录并确认授权后,会自动返回此处;无需填写短信验证码或复制网页地址。", + method: "auto", + async callback() { return await done }, + } +} + +function manualSignIn() { const state = randomUUID() const url = buildAuthorizeUrl(state) return { @@ -955,7 +1022,7 @@ export const RaccoonAuthPlugin = async ({ client }) => { methods: [ { type: "oauth", - label: "商汤小浣熊账号 (浏览器登录 / 粘贴回调或 Token)", + label: "商汤小浣熊账号 (浏览器登录 / 自动返回)", authorize: async () => browserSignIn(), }, { @@ -963,12 +1030,18 @@ export const RaccoonAuthPlugin = async ({ client }) => { label: "商汤小浣熊桌面端登录态 (~/.box-agent/config/auth.json)", authorize: async () => desktopSignIn(), }, + { + type: "oauth", + label: "手动粘贴回调链接或 Token(非短信验证码)", + authorize: async () => manualSignIn(), + }, ], }, } } export const _internal = { + browserSignIn, stripBearer, decodeJwtClaims, jwtExpiryMs, diff --git a/packages/raccoon/package.json b/packages/raccoon/package.json index 93a91fa..4489ff1 100644 --- a/packages/raccoon/package.json +++ b/packages/raccoon/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-raccoon-auth", - "version": "0.1.0", + "version": "0.1.1", "description": "OpenCode & Magpie provider plugin for SenseTime Raccoon (商汤小浣熊, xiaohuanxiong.com)", "type": "module", "main": "./index.mjs", diff --git a/packages/raccoon/raccoon-browser.test.mjs b/packages/raccoon/raccoon-browser.test.mjs new file mode 100644 index 0000000..55114d5 --- /dev/null +++ b/packages/raccoon/raccoon-browser.test.mjs @@ -0,0 +1,154 @@ +import { afterEach, expect, test } from "bun:test" +import { RaccoonAuthPlugin, _internal } from "./index.mjs" + +let upstream +afterEach(() => { + upstream?.stop(true) + upstream = undefined + delete process.env.RACCOON_MAIN_SITE_URL +}) +function fakeAuth(handler) { + upstream = Bun.serve({port: 0, hostname: "127.0.0.1", fetch: handler}) + process.env.RACCOON_MAIN_SITE_URL = `http://127.0.0.1:${upstream.port}` +} +function tokens() { + const claims = Buffer.from(JSON.stringify({iss: "74350b", exp: Math.floor(Date.now()/1000)+3600})).toString("base64url") + return {access_token: `synthetic.${claims}.signature`, refresh_token: "synthetic-refresh"} +} +function callbackURL(flow, code = "synthetic-code") { + const auth = new URL(flow.url) + const url = new URL(auth.searchParams.get("redirect")) + url.searchParams.set("state", auth.searchParams.get("state")) + url.searchParams.set("code", code) + return url +} + +test("browser authorization returns automatically and completes the code exchange", async () => { + let calls = 0 + fakeAuth(async req => { + expect(new URL(req.url).pathname).toBe("/api/web/auth/v1/login_with_authorization_code") + expect(await req.json()).toEqual({authorization_code: "synthetic-code"}) + calls++ + return Response.json({code: 0, data: tokens()}) + }) + const plugin = await RaccoonAuthPlugin({client:{}}) + const flow = await plugin.auth.methods[0].authorize() + const auth = new URL(flow.url) + expect(flow.method).toBe("auto") + expect(auth.searchParams.get("desktop_callback")).toBe("loopback") + expect(auth.searchParams.get("state")).toMatch(/^[a-f0-9]{64}$/) + const url = callbackURL(flow) + expect(url.hostname).toBe("127.0.0.1") + expect(url.pathname).toBe("/auth/callback") + expect(Number(url.port)).toBeGreaterThanOrEqual(1024) + const done = flow.callback() + const response = await fetch(url) + expect(response.status).toBe(200) + expect(response.headers.get("cache-control")).toBe("no-store") + const page = await response.text() + expect(page).not.toContain("synthetic-code") + expect(page).not.toContain("synthetic-refresh") + expect((await done).type).toBe("success") + expect(calls).toBe(1) + await expect(fetch(url)).rejects.toThrow() +}) + +test("bad state, missing code, wrong host, path or method never consume a pending login", async () => { + let calls = 0 + fakeAuth(() => { calls++; return Response.json({code:0,data:tokens()}) }) + const flow = await _internal.browserSignIn() + const done = flow.callback() + const good = callbackURL(flow) + const bad = new URL(good) + bad.searchParams.set("state", "wrong-state") + expect((await fetch(bad)).status).toBe(400) + bad.searchParams.set("state",new URL(flow.url).searchParams.get("state")) + bad.searchParams.append("state","duplicate") + expect((await fetch(bad)).status).toBe(400) + bad.searchParams.delete("code") + bad.searchParams.delete("state") + bad.searchParams.set("state",good.searchParams.get("state")) + expect((await fetch(bad)).status).toBe(400) + const wrongPath = new URL(good); wrongPath.pathname="/other" + expect((await fetch(wrongPath)).status).toBe(404) + expect((await fetch(good,{method:"POST"})).status).toBe(405) + expect((await fetch(good,{headers:{host:"attacker.invalid"}})).status).toBe(404) + expect(calls).toBe(0) + expect((await fetch(good)).status).toBe(200) + expect((await done).type).toBe("success") + expect(calls).toBe(1) +}) + +test("a rejected code reports failure rather than a successful browser page", async () => { + fakeAuth(() => Response.json({code:200035},{status:400})) + const flow=await _internal.browserSignIn() + const done=flow.callback() + expect((await fetch(callbackURL(flow))).status).toBe(502) + expect(await done).toMatchObject({type:"failed",error:"授权码已失效,请重新发起网页登录"}) + await expect(fetch(callbackURL(flow))).rejects.toThrow() +}) + +test("denied authorization closes the listener without exchanging a code", async () => { + fakeAuth(() => { throw new Error("must not exchange denied authorization") }) + const flow=await _internal.browserSignIn() + const done=flow.callback() + const url=callbackURL(flow); url.searchParams.delete("code"); url.searchParams.set("error","access_denied") + expect((await fetch(url)).status).toBe(400) + expect((await done).type).toBe("failed") + await expect(fetch(url)).rejects.toThrow() +}) + +test("an abandoned authorization times out and closes its listener even before callback is awaited", async () => { + const flow=await _internal.browserSignIn(25) + const result=await flow.callback() + expect(result).toMatchObject({type:"failed",error:"商汤小浣熊登录超时,请重新登录"}) + await expect(fetch(callbackURL(flow))).rejects.toThrow() +}) + +test("manual callback and token sign-in remain available without a listener", async () => { + const plugin=await RaccoonAuthPlugin({client:{}}) + const flow=await plugin.auth.methods[2].authorize() + expect(flow.method).toBe("code") + const t=tokens() + expect(await flow.callback(JSON.stringify(t))).toMatchObject({type:"success",access:t.access_token,refresh:t.refresh_token}) +}) + + +test("concurrent replay exchanges the authorization code only once", async () => { + let calls = 0, entered + const started = new Promise(resolve => { entered = resolve }) + fakeAuth(async () => { + calls++ + entered() + await Bun.sleep(200) + return Response.json({code: 0, data: tokens()}) + }) + const flow = await _internal.browserSignIn() + const url = callbackURL(flow) + const first = fetch(url) + await started + const second = fetch(url) + const responses = await Promise.all([first, second]) + expect((await flow.callback()).type).toBe("success") + expect(calls).toBe(1) + expect(responses.map(response => response.status)).toEqual([200, 409]) +}) + +test("invalid authorization URL rejects without leaving a listening server", async () => { + const source = `import { _internal } from ${JSON.stringify(new URL("./index.mjs", import.meta.url).href)}; + try { await _internal.browserSignIn(); process.exitCode = 1 } + catch { console.log("invalid-url-rejected") }` + const child = Bun.spawn([process.execPath, "--eval", source], { + env: {...process.env, RACCOON_MAIN_SITE_URL: "not a URL"}, + stdout: "pipe", stderr: "pipe", + }) + let timedOut = false + const deadline = setTimeout(() => { timedOut = true; child.kill() }, 2000) + let exitCode + try { exitCode = await child.exited } + finally { clearTimeout(deadline) } + const output = await new Response(child.stdout).text() + expect(output).toContain("invalid-url-rejected") + expect(timedOut).toBe(false) + expect(exitCode).toBe(0) +})