diff --git a/packages/raccoon/index.mjs b/packages/raccoon/index.mjs index 8326e21..4d7571c 100644 --- a/packages/raccoon/index.mjs +++ b/packages/raccoon/index.mjs @@ -6,11 +6,11 @@ // (read-only; desktopAuthCandidates lists where). Chats are OpenAI-compatible // chat completions at /api/web/llm/v2/chat/completions. -import { randomUUID, randomBytes } from "node:crypto" +import { createHash, randomUUID, randomBytes } from "node:crypto" import { createServer } from "node:http" -import { readFileSync, statSync } from "node:fs" +import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs" import { homedir } from "node:os" -import { join } from "node:path" +import { dirname, join } from "node:path" const PROVIDER_ID = "raccoon" const PROVIDER_NAME = "商汤小浣熊" @@ -668,10 +668,47 @@ async function availablePoints(token) { // grant total to measure spending against, so the window's total is that // highest balance and what was spent since is what it has gone down by // (plugins #1030: 9,965 then 9,964 read 0 / 9,965 then 0 / 9,964). A new -// or expired grant changes the set and starts it again. Kept in memory: a -// restarted host starts from the balance it reads. +// or expired grant changes the set and starts it again. It is kept on disk +// too (plugins #1182: what was spent read 0 again after every restart), one +// entry per account, so a restarted host goes on from the same top. const topBalance = new Map() +const topBalanceFile = () => + process.env.RACCOON_TOP_BALANCE_FILE || + join(process.env.MAGPIE_CONFIG_DIR || join(homedir(), ".config", "magpie"), "raccoon-top-balance.json") + +function readTops() { + try { + const raw = JSON.parse(readFileSync(topBalanceFile(), "utf8")) + return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {} + } catch { + return {} + } +} + +// savedTop is the top a past host saw for this account and set of grants, +// or 0 when it saw none (or the file can't be read). +function savedTop(account, grants) { + const e = readTops()[account] + const n = Number(e?.top) + return e?.grants === grants && Number.isFinite(n) && n > 0 ? n : 0 +} + +// saveTop writes through a temp file and a rename, so a host reading it +// mid-write never sees half of it. A failed write keeps the memory copy. +function saveTop(account, grants, top) { + try { + const file = topBalanceFile() + const all = readTops() + if (all[account]?.grants === grants && all[account]?.top === top) return + all[account] = { grants, top } + mkdirSync(dirname(file), { recursive: true }) + const tmp = `${file}.${process.pid}.tmp` + writeFileSync(tmp, JSON.stringify(all)) + renameSync(tmp, file) + } catch {} +} + async function queryUsage(token, account = "") { const [avail, entitlement, bills] = await Promise.all([ availablePoints(token), @@ -731,9 +768,12 @@ async function queryUsage(token, account = "") { // the card still shows one. A balance far over the bills is left // balance-only: the bills don't explain it. if (grantedFromBills > 0 && avail > grantedFromBills && avail - grantedFromBills <= avail / 10) { - const key = `${account}\n${grantKeys.sort().join("\n")}` - const top = Math.max(avail, topBalance.get(key) ?? 0) + const grants = createHash("sha256").update(grantKeys.sort().join("\n")).digest("hex") + const key = `${account}\n${grants}` + if (!topBalance.has(key)) topBalance.set(key, savedTop(account, grants)) + const top = Math.max(avail, topBalance.get(key)) topBalance.set(key, top) + saveTop(account, grants, top) grantedFromBills = top } const runsOutAt = soonestExpMs ? new Date(soonestExpMs).toISOString() : null @@ -1278,6 +1318,7 @@ export const RaccoonAuthPlugin = async ({ client }) => { } export const _internal = { + topBalance, browserSignIn, desktopAuthPath, desktopAuthCandidates, diff --git a/packages/raccoon/package.json b/packages/raccoon/package.json index 760aab2..1d471ee 100644 --- a/packages/raccoon/package.json +++ b/packages/raccoon/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-raccoon-auth", - "version": "0.1.11", + "version": "0.1.12", "description": "OpenCode & Magpie provider plugin for SenseTime Raccoon (商汤小浣熊, xiaohuanxiong.com)", "type": "module", "main": "./opencode.mjs", diff --git a/packages/raccoon/raccoon.test.mjs b/packages/raccoon/raccoon.test.mjs index d5afa45..19b4fa0 100644 --- a/packages/raccoon/raccoon.test.mjs +++ b/packages/raccoon/raccoon.test.mjs @@ -12,6 +12,7 @@ function fakeJwt(claims) { let server = null let tempDir = null +let topDir = null // No test may reach the real network: a test that starts no server points at a // port nothing listens on. @@ -19,6 +20,9 @@ let tempDir = null // depend on the network — review #486, point 1.) beforeEach(() => { process.env.RACCOON_MAIN_SITE_URL = "http://127.0.0.1:9" + // the top balance a past host saw is kept on disk: never the real ~/.config + topDir = mkdtempSync(join(tmpdir(), "raccoon-top-")) + process.env.RACCOON_TOP_BALANCE_FILE = join(topDir, "raccoon-top-balance.json") }) afterEach(() => { @@ -30,6 +34,10 @@ afterEach(() => { } delete process.env.RACCOON_MAIN_SITE_URL delete process.env.RACCOON_BOX_AGENT_CONFIG_DIR + delete process.env.RACCOON_TOP_BALANCE_FILE + if (topDir) rmSync(topDir, { recursive: true, force: true }) + topDir = null + _internal.topBalance.clear() _internal.renewed.clear() _internal.renewing.clear() }) @@ -581,6 +589,54 @@ test("spending under a balance over every grant counts as used (plugins #1030)", expect((await read()).windows[0]).toMatchObject({ amount: 0, limit: 10240 }) }) +// plugins #1182: what was spent read 0 again after every restart, since the +// highest balance seen was kept in memory only. +test("what was spent survives a restart (plugins #1182)", async () => { + const validTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 }) + let avail = 9965 + const grants = [ + { bill_id: "g2", biz_type: "daily_grant", points: 300, expire_at: "2099-11-17T23:59:59+08:00" }, + { bill_id: "g1", biz_type: "reward_grant", points: 9600 }, + ] + startServer({ + "GET /api/web/points/v1/balance": () => Response.json({ code: 0, data: { available_points: avail } }), + "GET /api/web/auth/v1/entitlement_info": () => Response.json({ code: 0, data: {} }), + "GET /api/web/points/v1/bills": () => Response.json({ code: 0, data: { items: grants } }), + }) + const read = async (accountId = "Raccoon-1182") => { + const hooks = await RaccoonAuthPlugin({ client: {} }) + return hooks.auth.usage(async () => ({ type: "oauth", access: validTok, refresh: "rt1", expires: Date.now() + 3600_000, accountId })) + } + expect((await read()).windows[0]).toMatchObject({ amount: 0, limit: 9965 }) + avail = 9940 + expect((await read()).windows[0]).toMatchObject({ amount: 25, limit: 9965 }) + _internal.topBalance.clear() // the host restarts + expect((await read()).windows[0]).toMatchObject({ amount: 25, limit: 9965, display: "25 / 9965" }) + // another account is still counted on its own + expect((await read("Raccoon-other")).windows[0]).toMatchObject({ amount: 0, limit: 9940 }) + // a new grant starts the count again, on disk too + grants.unshift({ bill_id: "g3", biz_type: "daily_grant", points: 300, expire_at: "2099-11-18T23:59:59+08:00" }) + avail = 10240 + expect((await read()).windows[0]).toMatchObject({ amount: 0, limit: 10240 }) + avail = 10230 + _internal.topBalance.clear() + expect((await read()).windows[0]).toMatchObject({ amount: 10, limit: 10240 }) +}) + +test("an unreadable top-balance file starts from the balance read (plugins #1182)", async () => { + const validTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 }) + writeFileSync(process.env.RACCOON_TOP_BALANCE_FILE, "{not json") + startServer({ + "GET /api/web/points/v1/balance": () => Response.json({ code: 0, data: { available_points: 9965 } }), + "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: "g1", biz_type: "reward_grant", points: 9900 }] } }), + }) + const hooks = await RaccoonAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => ({ type: "oauth", access: validTok, refresh: "rt1", expires: Date.now() + 3600_000, accountId: "A" })) + expect(u.windows[0]).toMatchObject({ amount: 0, limit: 9965 }) +}) + test("a readable balance asks setting_info nothing (plugins #520)", async () => { const validTok = fakeJwt({ iss: "74350b", name: "Mason", exp: Math.floor(Date.now() / 1000) + 3600 }) let asked = 0