raccoon 0.1.5: the card names the account by its phone, not by Raccoon-pu-<uuid> (#486)

The card names a Raccoon account by its masked phone (cardName), read from
user_info, instead of Raccoon-pu-<uuid>; accountId stays the identity, and a
desktop seat is named by its phone too. A renewal never changes accountId, and
a desktop seat's refresh still gives nothing, as on main.

Reviewed at ac0d84e (round 4). Run on mote (macOS, Bun 1.4.2) in a sandbox
HOME, at that head:
- bun test packages/raccoon: 43 pass / 0 fail
- bun scripts/check.mjs raccoon: ok
Broken by hand: dropping `|| auth.source === "desktop"` from refresh's guard
(index.mjs:1047) turns "a desktop seat's refresh gives nothing, even when
user_info answers a phone" red (42/1), now that its record carries
refresh: "D1". Earlier rounds' breaks (usage's cardName, 0.1.4 record) were
red too.
CI (test, on-npm) green at ac0d84e. Version 0.1.4 -> 0.1.5.
Not changed: a test for the desktop seat picking up a new phone when the
app's token changes (index.mjs:337), optional in the review.
Not tried: a real Raccoon account.
This commit is contained in:
MYCF711
2026-10-29 21:35:33 +08:00
committed by GitHub
parent b850c9da3d
commit 04b4438955
5 changed files with 247 additions and 14 deletions
+1
View File
@@ -13,6 +13,7 @@ OpenCode & Magpie provider plugin for **SenseTime Raccoon (商汤小浣熊, `xia
- **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.
- **The card's name**: the account's own phone number (`138****8000`), read once per token from `/api/web/auth/v1/user_info` with the JWT the sign-in holds. `accountId` stays the account's identity (the JWT's `Raccoon-pu-<uuid>`, or the desktop app's name) — magpie keys the user's own name for the account, its proxy, model picks and a gateway key's list by it, so it never changes. The card shows usage's `user`, which is the phone once a sign-in or renewal has read it. A failed read changes nothing and never costs a sign-in.
## 中文
+90 -7
View File
@@ -96,6 +96,63 @@ function extractDisplayName(claims) {
return String(claims?.name ?? "").trim()
}
// ---- the card's name --------------------------------------------------------
/**
* A phone number as the cards show it: `86 13800138000` / `0086-…` / bare /
* already masked → `138****8000`.
*/
function maskPhone(raw) {
let digits = String(raw ?? "").replace(/\D/g, "")
if (digits.startsWith("0086") && digits.length - 4 >= 7) digits = digits.slice(4)
else if (digits.startsWith("86") && digits.length - 2 >= 7) digits = digits.slice(2)
// a phone is 11 digits; a shorter run is not a number to mask
if (digits.length < 11) return ""
return `${digits.slice(0, 3)}****${digits.slice(-4)}`
}
// One read per token, re-read after PHONE_TTL_MS; stale entries are dropped
// when the map passes PHONE_CAP, so it does not grow for the life of the host.
const PHONE_CAP = 2048
const phoneByToken = new Map()
const PHONE_TTL_MS = 6 * 60 * 60 * 1000
/**
* The account's own phone number, read from the web API with the token the
* sign-in already holds (`GET /api/web/auth/v1/user_info` answers `data.phone`,
* measured `13800138000` on an `sms`-registered account).
*
* The JWT names the signer only by `Raccoon-pu-<uuid>` — an id, not a name —
* so the card used to show that string. Best effort: no token, a refusal or an
* answer without a number leaves the JWT's name on the card, and never costs a
* sign-in.
*/
async function accountPhoneOf(access) {
const token = stripBearer(access)
if (!token) return ""
const hit = phoneByToken.get(token)
if (hit && Date.now() - hit.at < PHONE_TTL_MS) return hit.phone
try {
const res = await fetch(`${mainOrigin()}/api/web/auth/v1/user_info`, {
headers: { Accept: "application/json", Authorization: "Bearer " + token },
signal: AbortSignal.timeout(15_000),
})
if (!res.ok) return ""
const payload = await res.json().catch(() => null)
const phone = maskPhone(payload?.data?.phone)
if (phone) {
if (phoneByToken.size >= PHONE_CAP) {
for (const [k, v] of phoneByToken) if (Date.now() - v.at >= PHONE_TTL_MS) phoneByToken.delete(k)
if (phoneByToken.size >= PHONE_CAP * 2) phoneByToken.clear()
}
phoneByToken.set(token, { at: Date.now(), phone })
}
return phone
} catch {
return ""
}
}
function vendorErrorText(payload, fallback) {
for (const k of ["details", "message", "msg"]) {
if (typeof payload?.[k] === "string" && payload[k].trim()) return payload[k].trim()
@@ -258,6 +315,8 @@ function isStale(a, marginMs = EARLY_MS) {
function sameAccount(seat, read) {
if (!read) return false
if (seat?.uid) return !!read.uid && String(seat.uid) === String(read.uid)
// accountId is the identity, as on main: the seat's own name is what the
// app's read carries for the same account.
if (seat?.accountId) return !!read.name && String(seat.accountId) === String(read.name)
return true
}
@@ -268,12 +327,19 @@ async function currentAuth(client, auth, force = false) {
// 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)) {
let next = { ...auth, ...d }
if (d.access && d.access !== auth.access) {
// A desktop seat stored by an earlier version is named `Raccoon-pu-…`:
// when the app's token changes, read the phone and keep it on the
// record (magpie replaces an account only at sign-in, merging fields
// on renewal).
const phone = await accountPhoneOf(d.access)
if (phone) next = { ...next, phone, cardName: phone }
try {
await client?.auth?.set?.({ path: { id: PROVIDER_ID }, body: { ...auth, ...d } })
await client?.auth?.set?.({ path: { id: PROVIDER_ID }, body: next })
} catch {}
}
return { a: { ...auth, ...d }, didRenew: false }
return { a: next, didRenew: false }
}
// the app holds another account, or none: this seat goes on with the
// token it was signed in with until that token ends
@@ -789,17 +855,23 @@ async function exchangeAuthCode(code) {
return { access, refresh }
}
function toSuccessAuth(access, refresh, extra = {}) {
async function toSuccessAuth(access, refresh, extra = {}) {
const claims = decodeJwtClaims(access)
const uid = extractUserId(claims)
const name = extractDisplayName(claims)
const expires = jwtExpiryMs(access)
const phone = await accountPhoneOf(access)
return {
type: "success",
access,
refresh: refresh || "",
expires,
// accountId is the account's identity in magpie (its user-set name, proxy,
// model picks and a gateway key's list hang off it), so it stays what main
// computes; the phone is a separate field (`phone`, `cardName`) that usage
// shows as the card's name.
accountId: name || (uid ? `Raccoon-${uid}` : PROVIDER_NAME),
...(phone ? { phone, cardName: phone } : {}),
uid: uid || "",
...(name ? { name } : {}),
...extra,
@@ -850,7 +922,7 @@ async function browserSignIn(timeoutMs = 10 * 60 * 1000) {
const tokens = await exchangeAuthCode(code)
if (settled) return reply(408, "登录已超时,请回到 Magpie 重新登录。")
reply(200, "商汤小浣熊登录成功,可以关闭此页并返回 Magpie。")
finish(toSuccessAuth(tokens.access, tokens.refresh))
finish(await toSuccessAuth(tokens.access, tokens.refresh))
} catch (e) {
reply(502, "登录未完成,请返回 Magpie 查看错误并重新登录。")
finish({ type: "failed", error: e?.message ?? String(e) })
@@ -884,7 +956,7 @@ function manualSignIn() {
try {
const parsed = parseCallbackInput(input, state)
const tokens = parsed.direct ? parsed.direct : await exchangeAuthCode(parsed.code)
return toSuccessAuth(tokens.access, tokens.refresh)
return await toSuccessAuth(tokens.access, tokens.refresh)
} catch (e) {
return { type: "failed", error: e?.message ?? String(e) }
}
@@ -913,6 +985,9 @@ function desktopSignIn() {
if (isStale(d, EARLY_MS)) {
return { type: "failed", error: "商汤小浣熊桌面端登录态已过期,请先打开商汤小浣熊客户端重新登录" }
}
// the app's own token reads the phone too, so a seat added here is named
// like one signed in through the browser
const phone = await accountPhoneOf(d.access)
return {
type: "success",
access: d.access,
@@ -920,6 +995,7 @@ function desktopSignIn() {
expires: d.expires,
source: "desktop",
accountId: d.name || PROVIDER_NAME,
...(phone ? { phone, cardName: phone } : {}),
uid: d.uid || "",
}
},
@@ -968,15 +1044,20 @@ export const RaccoonAuthPlugin = async ({ client }) => {
provider: PROVIDER_ID,
refreshLead: LEAD_MS,
async refresh(auth) {
if (auth?.type !== "oauth" || auth.source === "desktop" || !auth.access || !auth.refresh) return undefined
if (auth?.type !== "oauth" || !auth.access || auth.source === "desktop") return undefined
if (!auth.refresh) return undefined
const { a, didRenew } = await currentAuth(client, auth, true)
if (!didRenew) return undefined
// An account stored by an older version was named by `Raccoon-pu-…`;
// its renewal is where the phone can still be read and put on the card.
const phone = await accountPhoneOf(a.access)
return {
access: a.access,
refresh: a.refresh,
expires: a.expires,
...(a.uid ? { uid: a.uid } : {}),
...(a.name ? { name: a.name } : {}),
...(phone ? { phone, cardName: phone } : {}),
}
},
async loader(getAuth) {
@@ -1068,7 +1149,9 @@ export const RaccoonAuthPlugin = async ({ client }) => {
}
return {
...result,
user: a.name || auth.accountId || a.uid,
// The card's name: the phone when the record has one, else what
// the account is called (an older record has no phone).
user: a.cardName || a.accountId || a.name || a.uid,
signIn: didRenew ? "renewed" : "kept",
}
} catch (e) {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-raccoon-auth",
"version": "0.1.4",
"version": "0.1.5",
"description": "OpenCode & Magpie provider plugin for SenseTime Raccoon (商汤小浣熊, xiaohuanxiong.com)",
"type": "module",
"main": "./index.mjs",
+31 -5
View File
@@ -1,7 +1,15 @@
import { afterEach, expect, test } from "bun:test"
import { afterEach, beforeEach, expect, test } from "bun:test"
import { RaccoonAuthPlugin, _internal } from "./index.mjs"
let upstream
// No test may reach the real network: a test that starts no server points at a
// port nothing listens on.
// (accountPhoneOf reads user_info; pointing at the real site made the suite
// depend on the network — review #486, point 1.)
beforeEach(() => {
process.env.RACCOON_MAIN_SITE_URL = "http://127.0.0.1:9"
})
afterEach(() => {
upstream?.stop(true)
upstream = undefined
@@ -26,7 +34,10 @@ function callbackURL(flow, code = "synthetic-code") {
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")
const path = new URL(req.url).pathname
// the card's name: one read of the account's own phone, after the exchange
if (path === "/api/web/auth/v1/user_info") return Response.json({code: 0, data: {phone: "13800138000", name: "RaccoonBenjamin"}})
expect(path).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()})
@@ -48,14 +59,24 @@ test("browser authorization returns automatically and completes the code exchang
const page = await response.text()
expect(page).not.toContain("synthetic-code")
expect(page).not.toContain("synthetic-refresh")
expect((await done).type).toBe("success")
const signedIn = await done
expect(signedIn.type).toBe("success")
// accountId is the identity — `Raccoon-<uid>` when the JWT names no one —
// and the phone is only the name the card shows
expect(signedIn.accountId).toMatch(/^Raccoon-\d+$/)
expect(signedIn.phone).toBe("138****8000")
expect(signedIn.cardName).toBe("138****8000")
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()}) })
fakeAuth(req => {
if (new URL(req.url).pathname === "/api/web/auth/v1/user_info") return Response.json({code: 0, data: {phone: "13800138000"}})
calls++
return Response.json({code:0,data:tokens()})
})
const flow = await _internal.browserSignIn()
const done = flow.callback()
const good = callbackURL(flow)
@@ -106,6 +127,10 @@ test("an abandoned authorization times out and closes its listener even before c
})
test("manual callback and token sign-in remain available without a listener", async () => {
fakeAuth(req => {
if (new URL(req.url).pathname === "/api/web/auth/v1/user_info") return Response.json({code: 0, data: {phone: "13800138000"}})
return Response.json({code: 0, data: tokens()})
})
const plugin=await RaccoonAuthPlugin({client:{}})
const flow=await plugin.auth.methods[2].authorize()
expect(flow.method).toBe("code")
@@ -117,7 +142,8 @@ test("manual callback and token sign-in remain available without a listener", as
test("concurrent replay exchanges the authorization code only once", async () => {
let calls = 0, entered
const started = new Promise(resolve => { entered = resolve })
fakeAuth(async () => {
fakeAuth(async req => {
if (new URL(req.url).pathname === "/api/web/auth/v1/user_info") return Response.json({code: 0, data: {phone: "13800138000"}})
calls++
entered()
await Bun.sleep(200)
+124 -1
View File
@@ -1,4 +1,4 @@
import { afterEach, expect, test } from "bun:test"
import { afterEach, beforeEach, expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { dirname, join } from "node:path"
@@ -13,6 +13,14 @@ function fakeJwt(claims) {
let server = null
let tempDir = null
// No test may reach the real network: a test that starts no server points at a
// port nothing listens on.
// (accountPhoneOf reads user_info; pointing at the real site made the suite
// depend on the network — review #486, point 1.)
beforeEach(() => {
process.env.RACCOON_MAIN_SITE_URL = "http://127.0.0.1:9"
})
afterEach(() => {
server?.stop(true)
server = null
@@ -172,6 +180,29 @@ test("desktop sign-in is read-only and never writes or refreshes auth.json", asy
expect(await Bun.file(authFile).text()).toBe(originalContent)
})
test("a desktop seat is named by its phone, not by the app's `name`", async () => {
tempDir = mkdtempSync(join(tmpdir(), "raccoon-test-"))
process.env.RACCOON_BOX_AGENT_CONFIG_DIR = tempDir
writeFileSync(join(tempDir, "auth.json"), JSON.stringify({
access_token: fakeJwt({ iss: "74350b", name: "raccoon-pu-01a1365c", exp: Math.floor(Date.now() / 1000) + 3600 }),
refresh_token: "D1",
}))
startServer({
"/api/web/auth/v1/user_info": () => Response.json({ code: 0, data: { phone: "13800138000", name: "RaccoonBenjamin" } }),
})
const hooks = await RaccoonAuthPlugin({ client: {} })
const method = hooks.auth.methods.find((m) => m.label?.includes("desktop") || m.label?.includes("桌面"))
const flow = await method.authorize()
const res = await flow.callback()
expect(res.type).toBe("success")
// accountId stays main's computation (the app's name); the phone is a record field
expect(res.accountId).toBe("raccoon-pu-01a1365c")
expect(res.phone).toBe("138****8000")
expect(res.cardName).toBe("138****8000")
expect(res.uid).toBeTruthy()
})
// 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
@@ -256,6 +287,33 @@ test("usage does not invent 300/9000 floors when bills do not cover balance", as
expect(u.windows).toEqual([])
})
test("the name usage puts on the card is the phone, not the JWT's name (review #486)", async () => {
const validTok = fakeJwt({ iss: "74350b", name: "RaccoonBenjamin", 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: {} })
// magpie shows usage's user as the card's name; the JWT's name is on the
// record too, and the phone must win
const u = await hooks.auth.usage(async () => ({
type: "oauth",
access: validTok,
refresh: "rt1",
expires: Date.now() + 3600_000,
accountId: "Raccoon-7615755",
phone: "138****8000",
cardName: "138****8000",
name: "RaccoonBenjamin",
}))
expect(u.user).toBe("138****8000")
})
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({
@@ -626,6 +684,28 @@ test("a desktop seat asks to sign in again once its own token expires", async ()
expect(u.error).toContain("切换为其他账号")
})
test("a uid-less desktop seat takes the app's newer token for the same account (review #486, 2)", async () => {
tempDir = mkdtempSync(join(tmpdir(), "raccoon-test-"))
process.env.RACCOON_BOX_AGENT_CONFIG_DIR = tempDir
const authFile = join(tempDir, "auth.json")
const noUid = fakeJwt({ name: "NoUid", 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("")
// the same account (same name); the app now holds a newer token
const newer = fakeJwt({ name: "NoUid", exp: Math.floor(Date.now() / 1000) + 7200 })
writeFileSync(authFile, JSON.stringify({ access_token: newer, refresh_token: "D2" }))
startServer({
"GET /api/web/points/v1/balance": () => Response.json({ code: 0, data: { available_points: 321 } }),
"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.balance).toBe("321 credits")
})
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
@@ -1016,3 +1096,46 @@ test("X-Client-Platform header derives desktop-mac on darwin and desktop-windows
if (origDesc) Object.defineProperty(process, "platform", origDesc)
}
})
test("a 0.1.4-style record keeps its accountId on renewal and shows the phone (review #486, 3)", async () => {
tempDir = mkdtempSync(join(tmpdir(), "raccoon-test-"))
process.env.RACCOON_BOX_AGENT_CONFIG_DIR = tempDir
startServer({
"POST /api/web/auth/v1/refresh": () =>
Response.json({ code: 0, data: { access_token: "new-tok", refresh_token: "rt-new", expires_in: 86400 } }),
"/api/web/auth/v1/user_info": () => Response.json({ code: 0, data: { phone: "13800138000", name: "RaccoonBenjamin" } }),
"GET /api/web/points/v1/balance": () => Response.json({ code: 0, data: { available_points: 100 } }),
"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 old = {
type: "oauth",
access: "old-tok",
refresh: "rt-old",
expires: Date.now() + 1_000,
accountId: "Raccoon-pu-abc123",
uid: "7615755",
}
const renewed = await hooks.auth.refresh(old)
// the identity does not move: a renewal gives no accountId
expect(renewed.accountId).toBeUndefined()
expect(renewed.cardName).toBe("138****8000")
const u = await hooks.auth.usage(async () => ({ ...old, ...renewed, access: "new-tok", expires: Date.now() + 86_400_000 }))
expect(u.user).toBe("138****8000")
})
test("a desktop seat's refresh gives nothing, even when user_info answers a phone (review #486, 2)", async () => {
startServer({
"/api/web/auth/v1/user_info": () => Response.json({ code: 0, data: { phone: "13800138000" } }),
})
const hooks = await RaccoonAuthPlugin({ client: {} })
const got = await hooks.auth.refresh({
type: "oauth",
source: "desktop",
access: "tok-desktop",
refresh: "D1",
expires: Date.now() + 1_000,
})
expect(got).toBeUndefined()
})