A new package, @magpie-community/opencode-minimax-auth, written from MiniMax Code 0.6.2's bundle. Sign-in: MiniMax Code's OAuth device flow, the same one mcode uses (account.minimax.cn / account.minimax.io, client mcode-public, scope agent.default, audience agent-backend, PKCE S256). It also handles MiniMax's own variant, where there is no device_code, the user_code is polled for, and expired_in may be an at-ms. The account is named from MiniMax's signed /v1/api/user/info. mcode's ~/.minimax sign-in is never read or written. Each account is a sign-in of its own, so magpie can hold several. Refresh: two minutes before the token ends, or once on a 401. One refresh runs per account (keyed by the refresh token it spends), and its result answers for the old token for a minute, so a late reader doesn't spend a rotated token twice. Only invalid_grant with HTTP 400 signs the account out (signIn: expired); any other failure keeps it and uses the token in hand while it lasts. Chats: Anthropic messages at <agent>/mavis/api/v1/llm/v1/messages, carrying: - Authorization: Bearer <token> - x-api-key sk-xxx (mcode's placeholder) - User-Agent MiniMaxAgent - X-Mavis-Agent-Id main - X-Mavis-Timezone-Offset - X-Mavis-Session-Id, from chat.headers' sessionID (otherwise a fixed id per run) A 402, 403 or 429 whose body says credits or quota ran out goes on as a 429 "usage limit reached". Models: the live config at GET /mavis/api/v1/models?region=&buildEnv=prod (asked again without auth on a 401/403), with mcode's built-in four as the fallback: MiniMax-M3.1-Flash-Preview, MiniMax-M3, MiniMax-M2.7 and MiniMax-M2.7-highspeed. Variants follow what mcode sends: adaptive thinking at an effort (output_config.effort), and none to turn thinking off. Usage: mcode's signed account API: user info, the type-0 workspace from get_user_extra_info, then get_membership_info. The card shows credits left (op_credit_summary / opcredit_balance), Free or "M Plan <tier>" with its end, and, for an M Plan, coding_plan/remains with X-Group-Id. That is read as magpie's readMiniMaxPlan reads it. There is no check-in. Tests: fakes only. nonet.mjs is imported first, so only 127.0.0.1 can be reached. They cover: - sign-in, the variant, refused, and other errors - refresh, a three-way race plus a late stale reader, per-account refreshes, invalid_grant, other failures, and 401 then refresh then retry - request headers and chat.headers - credits running out going on as a 429 - the live list, the retry without auth, and the fallback (the given object back) - signing, against fixed vectors and the bundle's formula - usage parsing (readMiniMaxPlan's own fixture), Free, M Plan, and a refused account bun test packages/minimax (27 pass) and bun scripts/check.mjs pass. End to end through magpie: origin/main b0486663, built with -tags nogui in a worktree since removed, under env -i with a sandbox HOME, a fake upstream on 127.0.0.1:47811, and a copy of the package with its hosts pointed there: - plugin add - plugin login minimax-code: the device flow and the account named; a second login of the same account merged into one - the live list: 2 models - provider test minimax-code: the chat went out with the headers above - quota: M Plan Plus, 321.5 credits, 5 hours and 7 days windows - an expired token refreshed and saved No request was made to MiniMax.
125 lines
6.6 KiB
JavaScript
125 lines
6.6 KiB
JavaScript
// Refreshing the token: one refresh at a time for an account, the new
|
|
// token saved; only MiniMax's invalid_grant (HTTP 400) signs the account
|
|
// out, any other failure keeps it.
|
|
import "./nonet.mjs"
|
|
import { afterEach, expect, test } from "bun:test"
|
|
import { MiniMaxCodeAuthPlugin } from "./index.mjs"
|
|
import { fakeMiniMax, json } from "./fake.mjs"
|
|
|
|
let f
|
|
afterEach(() => f?.close())
|
|
|
|
// store is a sign-in as magpie keeps it: read afresh by getAuth, saved by
|
|
// client.auth.set
|
|
function store(a) {
|
|
const s = { auth: { type: "oauth", accountId: "a@example.com", ...a }, saves: [] }
|
|
s.getAuth = async () => s.auth
|
|
s.client = { auth: { set: async ({ path, body }) => { s.saves.push({ id: path.id, body }); s.auth = body } } }
|
|
return s
|
|
}
|
|
|
|
const chat = (opts) => opts.fetch(opts.baseURL + "/messages", { method: "POST", headers: { "content-type": "application/json" }, body: '{"model":"MiniMax-M3","messages":[]}' })
|
|
const ok = () => json({ type: "message", content: [] })
|
|
|
|
test("a token about to end is refreshed first and saved", async () => {
|
|
f = fakeMiniMax()
|
|
f.route("POST /oauth2/token", () => json({ access_token: "new", refresh_token: "r2", token_type: "Bearer", expires_in: 3600 }))
|
|
f.route("POST /mavis/api/v1/llm/v1/messages", ok)
|
|
const s = store({ access: "old", refresh: "r1", expires: Date.now() + 10_000 })
|
|
const hooks = await MiniMaxCodeAuthPlugin({ client: s.client })
|
|
const res = await chat(await hooks.auth.loader(s.getAuth))
|
|
expect(res.status).toBe(200)
|
|
expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed")
|
|
const ref = f.seen.find((r) => r.path === "/oauth2/token")
|
|
expect(ref.form).toMatchObject({ grant_type: "refresh_token", refresh_token: "r1", client_id: "mcode-public", scope: "agent.default", audience: "agent-backend" })
|
|
expect(f.seen.find((r) => r.path.endsWith("/messages")).headers.get("authorization")).toBe("Bearer new")
|
|
expect(s.saves.length).toBe(1)
|
|
expect(s.saves[0]).toMatchObject({ id: "minimax-code", body: { type: "oauth", access: "new", refresh: "r2", accountId: "a@example.com" } })
|
|
})
|
|
|
|
test("two requests racing refresh once; one reading the old token late joins it", async () => {
|
|
f = fakeMiniMax()
|
|
let refreshes = 0
|
|
f.route("POST /oauth2/token", async () => {
|
|
refreshes++
|
|
await Bun.sleep(50)
|
|
return json({ access_token: "new", refresh_token: "r2", token_type: "Bearer", expires_in: 3600 })
|
|
})
|
|
f.route("POST /mavis/api/v1/llm/v1/messages", ok)
|
|
const s = store({ access: "old", refresh: "r1", expires: Date.now() - 1 })
|
|
const hooks = await MiniMaxCodeAuthPlugin({ client: s.client })
|
|
const opts = await hooks.auth.loader(s.getAuth)
|
|
const rs = await Promise.all([chat(opts), chat(opts), chat(opts)])
|
|
for (const r of rs) expect(r.status).toBe(200)
|
|
expect(refreshes).toBe(1)
|
|
// a request that read the sign-in from before the save (another account
|
|
// slot's loader, a stale read) doesn't spend the rotated token again
|
|
const late = store({ access: "old", refresh: "r1", expires: Date.now() - 1 })
|
|
const opts2 = await (await MiniMaxCodeAuthPlugin({ client: late.client })).auth.loader(late.getAuth)
|
|
expect((await chat(opts2)).status).toBe(200)
|
|
expect(refreshes).toBe(1)
|
|
const sent = f.seen.filter((r) => r.path.endsWith("/messages")).map((r) => r.headers.get("authorization"))
|
|
expect(sent).toEqual(Array(4).fill("Bearer new"))
|
|
})
|
|
|
|
test("each account refreshes on its own", async () => {
|
|
f = fakeMiniMax()
|
|
f.route("POST /oauth2/token", async (r) => json({ access_token: "new-" + r.form.refresh_token, refresh_token: r.form.refresh_token + "'", token_type: "Bearer", expires_in: 3600 }))
|
|
f.route("POST /mavis/api/v1/llm/v1/messages", ok)
|
|
const a = store({ access: "a", refresh: "ra", expires: Date.now() - 1 })
|
|
const b = store({ access: "b", refresh: "rb", expires: Date.now() - 1 })
|
|
const hooks = await MiniMaxCodeAuthPlugin({ client: {} })
|
|
await Promise.all([chat(await hooks.auth.loader(a.getAuth)), chat(await hooks.auth.loader(b.getAuth))])
|
|
const sent = f.seen.filter((r) => r.path.endsWith("/messages")).map((r) => r.headers.get("authorization")).sort()
|
|
expect(sent).toEqual(["Bearer new-ra", "Bearer new-rb"])
|
|
})
|
|
|
|
test("invalid_grant with HTTP 400 signs the account out", async () => {
|
|
f = fakeMiniMax()
|
|
f.route("POST /oauth2/token", () => json({ error: "invalid_grant", error_description: "refresh token revoked" }, 400))
|
|
const s = store({ access: "old", refresh: "r1", expires: Date.now() - 1 })
|
|
const hooks = await MiniMaxCodeAuthPlugin({ client: s.client })
|
|
const opts = await hooks.auth.loader(s.getAuth)
|
|
const e = await chat(opts).catch((e) => e)
|
|
expect(e).toBeInstanceOf(Error)
|
|
expect(e.signIn).toBe("expired")
|
|
expect(e.message).toContain("sign in again")
|
|
expect(s.saves.length).toBe(0)
|
|
// the usage card says so too
|
|
const u = await hooks.auth.usage(s.getAuth)
|
|
expect(u.signIn).toBe("expired")
|
|
})
|
|
|
|
test("any other refresh failure keeps the account", async () => {
|
|
for (const [status, body] of [[500, { error: "server_error" }], [401, { error: "invalid_grant" }], [400, { error: "invalid_request" }], [503, {}]]) {
|
|
f = fakeMiniMax()
|
|
f.route("POST /oauth2/token", () => json(body, status))
|
|
f.route("POST /mavis/api/v1/llm/v1/messages", ok)
|
|
// a token past its end: the request fails, the account kept
|
|
const s = store({ access: "old", refresh: "r1", expires: Date.now() - 1 })
|
|
const hooks = await MiniMaxCodeAuthPlugin({ client: s.client })
|
|
const e = await chat(await hooks.auth.loader(s.getAuth)).catch((e) => e)
|
|
expect(e.signIn).toBe("kept")
|
|
// a token about to end but not ended yet: it is used as it is
|
|
const t = store({ access: "still", refresh: "r1", expires: Date.now() + 30_000 })
|
|
const res = await chat(await hooks.auth.loader(t.getAuth))
|
|
expect(res.status).toBe(200)
|
|
expect(f.seen.at(-1).headers.get("authorization")).toBe("Bearer still")
|
|
f.close()
|
|
f = null
|
|
}
|
|
})
|
|
|
|
test("a token MiniMax turns away is refreshed once and the request sent again", async () => {
|
|
f = fakeMiniMax()
|
|
f.route("POST /oauth2/token", () => json({ access_token: "new", refresh_token: "r2", token_type: "Bearer", expires_in: 3600 }))
|
|
f.route("POST /mavis/api/v1/llm/v1/messages", (r) => (r.headers.get("authorization") === "Bearer new" ? ok() : json({ type: "error", error: { type: "authentication_error", message: "token expired" } }, 401)))
|
|
const s = store({ access: "old", refresh: "r1", expires: Date.now() + 3600_000 })
|
|
const hooks = await MiniMaxCodeAuthPlugin({ client: s.client })
|
|
const res = await chat(await hooks.auth.loader(s.getAuth))
|
|
expect(res.status).toBe(200)
|
|
expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed")
|
|
expect(f.seen.filter((r) => r.path.endsWith("/messages")).length).toBe(2)
|
|
expect(s.auth.access).toBe("new")
|
|
})
|