minimax 0.1.1: a refresh token is never sent twice, and magpie renews the sign-in ahead of time through auth.refresh (ARNO on Discord: minimax插件的登录状态容易掉登陆,几个小时就提示要重新登陆了)
MiniMax spends a refresh token once: sent again it is invalid_grant, which signs the account out (MiniMax Code takes a lock across its processes and keeps a generation for it). The plugin's refresh request is MiniMax Code's own, so what drops the account is a refresh token spent a second time: - auth.refresh + refreshLead (10 minutes): magpie renews the account once, before its requests, models and usage ask for it. The 2-minute check before each request stays for OpenCode. - A refresh whose save failed kept its tokens a minute, then went back to the spent refresh token on disk. They are kept now until saved, and latest() follows them. - invalid_grant when the store holds a newer refresh token than the one spent (another magpie process renewed it) uses that one, not a sign-out. - A 401 retries with a newer saved token when there is one, and refreshes only when the token turned away is still the newest. Five tests in refresh.test.mjs, all failing on 0.1.0. HOME=$(mktemp -d) bun test: 353 pass.
This commit is contained in:
@@ -42,10 +42,22 @@ Each account signs in on its own, so magpie can hold several and switch
|
||||
between them.
|
||||
|
||||
Refreshing:
|
||||
- The access token is refreshed two minutes before it ends, or when MiniMax
|
||||
turns it away (HTTP 401). The new token is saved.
|
||||
- MiniMax spends a refresh token once. Sent a second time it is
|
||||
`invalid_grant`, which signs the account out, so the plugin never sends
|
||||
one twice.
|
||||
- magpie renews the token ten minutes before it ends, through the plugin's
|
||||
`auth.refresh`, once for the account and before its requests, models and
|
||||
usage need it. OpenCode doesn't call that hook: there the access token is
|
||||
refreshed two minutes before it ends, before a request. Either way the
|
||||
new token is saved.
|
||||
- When MiniMax turns the token away (HTTP 401), the request goes again with
|
||||
a newer token if one was saved meanwhile, else after a refresh.
|
||||
- Only one refresh runs at a time for an account. Requests that arrive
|
||||
meanwhile wait for it and use its token.
|
||||
meanwhile wait for it and use its token. When saving the new token
|
||||
fails, the plugin keeps it in memory and goes on with it, rather than
|
||||
with the spent one on disk.
|
||||
- A refresh token someone else spent first (another magpie process) isn't a
|
||||
sign-out when the new one they saved is there: that one is used.
|
||||
- The account counts as signed out only when MiniMax answers the refresh
|
||||
with `invalid_grant` (HTTP 400). Any other failure keeps the sign-in, and
|
||||
the current token is used while it lasts.
|
||||
|
||||
+90
-34
@@ -15,9 +15,10 @@ const CLIENT_ID = "mcode-public"
|
||||
const SCOPE = "agent.default"
|
||||
const AUDIENCE = "agent-backend"
|
||||
const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"
|
||||
const EARLY_MS = 2 * 60 * 1000 // a token this close to its end is refreshed
|
||||
const EARLY_MS = 2 * 60 * 1000 // a token this close to its end is refreshed before a request
|
||||
const LEAD_MS = 10 * 60 * 1000 // and this close, magpie renews it ahead of time (auth.refresh)
|
||||
const SIGN_IN_MS = 10 * 60 * 1000 // when the device code gives no end of its own
|
||||
const KEEP_RENEWED_MS = 60 * 1000 // how long a refresh's result answers for the old token
|
||||
const KEEP_RENEWED_MS = 60 * 1000 // how long a saved refresh's result answers for the old token
|
||||
const SIGN_SECRET = "I*7Cf%WZ#S&%1RlZJ&C2" // MiniMax Code's request signing (x-signature)
|
||||
const NPM = "@ai-sdk/anthropic"
|
||||
// the key the Anthropic SDK is given in MiniMax Code: a placeholder, the
|
||||
@@ -520,53 +521,89 @@ async function answer(res, renewed) {
|
||||
|
||||
// ---- the plugins ----------------------------------------------------------------
|
||||
|
||||
// MiniMax spends a refresh token once: the refresh gives a new one, and
|
||||
// the old one asked again is invalid_grant, which signs the account out
|
||||
// (MiniMax Code takes a lock across its processes for it). So a refresh
|
||||
// token is never sent twice from here.
|
||||
//
|
||||
// renewing is each refresh under way, by site and the refresh token it
|
||||
// spends; renewed is what each just gave, kept a minute so a request that
|
||||
// read the old token after the refresh was saved joins it rather than
|
||||
// spending the old token again.
|
||||
// spends; renewed is what each gave, kept a minute once saved so a request
|
||||
// that read the old token after the refresh was saved joins it rather than
|
||||
// spending the old token again, and kept for good when the save failed:
|
||||
// the account's newest tokens are then here only.
|
||||
const renewing = new Map()
|
||||
const renewed = new Map()
|
||||
|
||||
// latest is the sign-in a with the newest tokens this process got for it.
|
||||
function latest(site, a) {
|
||||
for (let i = 0; i < 16 && a.refresh; i++) {
|
||||
const done = renewed.get(site.id + "\n" + a.refresh)
|
||||
if (!done || (done.saved && Date.now() - done.at >= KEEP_RENEWED_MS)) break
|
||||
a = { ...a, ...done.got }
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// renew spends a's refresh token, once: those who come while it runs wait
|
||||
// for it. save keeps what it gave, saying whether it could.
|
||||
function renew(site, a, save) {
|
||||
const key = site.id + "\n" + a.refresh
|
||||
let r = renewing.get(key)
|
||||
if (!r) {
|
||||
r = (async () => {
|
||||
const t = await refreshToken(site, a.refresh)
|
||||
const got = { access: t.access, refresh: t.refresh, expires: t.expires }
|
||||
const done = { got, at: Date.now(), saved: false }
|
||||
renewed.set(key, done)
|
||||
done.saved = await save({ ...a, ...got })
|
||||
done.at = Date.now()
|
||||
return got
|
||||
})().finally(() => renewing.delete(key))
|
||||
renewing.set(key, r)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
function makePlugin(site) {
|
||||
return async ({ client }) => {
|
||||
const save = async (a) => {
|
||||
if (typeof client?.auth?.set !== "function") return false
|
||||
try {
|
||||
await client?.auth?.set?.({ path: { id: site.id }, body: a })
|
||||
} catch {}
|
||||
await client.auth.set({ path: { id: site.id }, body: a })
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// fresh is the account with an access token that isn't about to end,
|
||||
// refreshed (and saved) when it is, or when force is set (MiniMax
|
||||
// turned the token away). One refresh at a time for an account: those
|
||||
// who come meanwhile wait for it. renewed says this call refreshed.
|
||||
const fresh = async (getAuth, force = false) => {
|
||||
const a = await getAuth()
|
||||
if (a?.type !== "oauth" || !a.access) throw new Error(`${site.name} isn't signed in`)
|
||||
if (!force && !(a.expires && Date.now() >= a.expires - EARLY_MS)) return { a, renewed: false }
|
||||
// refreshed (and saved) when it is, or when MiniMax turned away the
|
||||
// access token rejected and no newer one is had. renewed says the
|
||||
// token isn't the one getAuth read: this call or another refreshed it.
|
||||
const fresh = async (getAuth, rejected, again = false) => {
|
||||
const stored = await getAuth()
|
||||
if (stored?.type !== "oauth" || !stored.access) throw new Error(`${site.name} isn't signed in`)
|
||||
const a = latest(site, stored)
|
||||
const newer = a.access !== stored.access
|
||||
if (rejected !== undefined && a.access !== rejected) return { a, renewed: true }
|
||||
const force = rejected !== undefined
|
||||
if (!force && !(a.expires && Date.now() >= a.expires - EARLY_MS)) return { a, renewed: newer }
|
||||
if (!a.refresh) {
|
||||
if (Date.now() < a.expires) return { a, renewed: false }
|
||||
if (Date.now() < a.expires) return { a, renewed: newer }
|
||||
throw new SignInExpired(site)
|
||||
}
|
||||
const key = site.id + "\n" + a.refresh
|
||||
const done = renewed.get(key)
|
||||
if (done && Date.now() - done.at < KEEP_RENEWED_MS) return { a: { ...a, ...done.got }, renewed: true }
|
||||
let r = renewing.get(key)
|
||||
if (!r) {
|
||||
r = (async () => {
|
||||
const t = await refreshToken(site, a.refresh)
|
||||
const got = { access: t.access, refresh: t.refresh, expires: t.expires }
|
||||
await save({ ...a, ...got })
|
||||
renewed.set(key, { got, at: Date.now() })
|
||||
return got
|
||||
})().finally(() => renewing.delete(key))
|
||||
renewing.set(key, r)
|
||||
}
|
||||
try {
|
||||
return { a: { ...a, ...(await r) }, renewed: true }
|
||||
return { a: { ...a, ...(await renew(site, a, save)) }, renewed: true }
|
||||
} catch (e) {
|
||||
if (signedOut(e)) throw new SignInExpired(site)
|
||||
if (signedOut(e)) {
|
||||
// spent by someone else (magpie's renewal, another process of
|
||||
// magpie's), who saved the new one: that one is used
|
||||
const now = again ? undefined : await getAuth().catch(() => undefined)
|
||||
if (now?.type === "oauth" && now.refresh && now.refresh !== a.refresh && now.refresh !== stored.refresh) return fresh(getAuth, rejected, true)
|
||||
throw new SignInExpired(site)
|
||||
}
|
||||
// passing: the token in hand may still do
|
||||
if (!force && Date.now() < a.expires) return { a, renewed: false }
|
||||
if (!force && Date.now() < a.expires) return { a, renewed: newer }
|
||||
throw Object.assign(new Error(`${site.name} token refresh: ${e?.message ?? e}`), { signIn: "kept" })
|
||||
}
|
||||
}
|
||||
@@ -608,6 +645,24 @@ function makePlugin(site) {
|
||||
},
|
||||
auth: {
|
||||
provider: site.id,
|
||||
// magpie renews the sign-in LEAD_MS before its end, once for the
|
||||
// account, before its requests, models and usage ask for it; the
|
||||
// check before each request below stays for OpenCode, which
|
||||
// doesn't call this
|
||||
refreshLead: LEAD_MS,
|
||||
async refresh(auth) {
|
||||
if (auth?.type !== "oauth" || !auth.access || !auth.refresh) return undefined
|
||||
const a = latest(site, auth)
|
||||
// renewed here already, the store not yet saying so
|
||||
if (a.access !== auth.access && Date.now() < a.expires - LEAD_MS) return { access: a.access, refresh: a.refresh, expires: a.expires }
|
||||
try {
|
||||
// magpie saves what this gives
|
||||
return await renew(site, a, async () => true)
|
||||
} catch (e) {
|
||||
if (signedOut(e)) throw new SignInExpired(site)
|
||||
throw e
|
||||
}
|
||||
},
|
||||
async loader(getAuth) {
|
||||
const auth = await getAuth()
|
||||
if (auth?.type !== "oauth") return {}
|
||||
@@ -633,8 +688,9 @@ function makePlugin(site) {
|
||||
let { a, renewed: did } = await fresh(getAuth)
|
||||
let res = await send(a)
|
||||
if (res.status === 401) {
|
||||
// the token was turned away before its end: refresh once
|
||||
;({ a } = await fresh(getAuth, true))
|
||||
// the token was turned away before its end: a newer one
|
||||
// if there is one, else refreshed, and sent once more
|
||||
;({ a } = await fresh(getAuth, a.access))
|
||||
did = true
|
||||
res = await send(a)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-minimax-auth",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"description": "OpenCode provider plugins for MiniMax Code accounts: their credits and M Plan, China (minimax-code) and international (minimax-code-global), with MiniMax Code's own device sign-in",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
// 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.
|
||||
// out, any other failure keeps it. magpie renews it ahead of time through
|
||||
// auth.refresh.
|
||||
import "./nonet.mjs"
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { MiniMaxCodeAuthPlugin } from "./index.mjs"
|
||||
import { MiniMaxCodeAuthPlugin, _internal } from "./index.mjs"
|
||||
import { fakeMiniMax, json } from "./fake.mjs"
|
||||
|
||||
let f
|
||||
@@ -122,3 +123,105 @@ test("a token MiniMax turns away is refreshed once and the request sent again",
|
||||
expect(f.seen.filter((r) => r.path.endsWith("/messages")).length).toBe(2)
|
||||
expect(s.auth.access).toBe("new")
|
||||
})
|
||||
|
||||
// MiniMax spends a refresh token once: the tests below each check the one
|
||||
// it was given isn't sent again.
|
||||
|
||||
test("magpie renews the sign-in ahead of its end through auth.refresh, once with a request's own refresh", 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 })
|
||||
expect(hooks.auth.refreshLead).toBe(10 * 60 * 1000)
|
||||
// magpie's renewal and a request's own check, at once
|
||||
const [got, res] = await Promise.all([hooks.auth.refresh({ ...s.auth }, "minimax-code"), chat(await hooks.auth.loader(s.getAuth))])
|
||||
expect(got).toMatchObject({ access: "new", refresh: "r2" })
|
||||
expect(got.expires).toBeGreaterThan(Date.now() + 3000_000)
|
||||
expect(res.status).toBe(200)
|
||||
expect(refreshes).toBe(1)
|
||||
expect(f.seen.find((r) => r.path === "/oauth2/token").form).toMatchObject({ grant_type: "refresh_token", refresh_token: "r1" })
|
||||
// asked again with the sign-in magpie had before it saved: nothing is spent
|
||||
expect(await hooks.auth.refresh({ type: "oauth", access: "old", refresh: "r1", expires: Date.now() - 1 })).toMatchObject({ access: "new", refresh: "r2" })
|
||||
expect(refreshes).toBe(1)
|
||||
// nothing to renew without a refresh token
|
||||
expect(await hooks.auth.refresh({ type: "oauth", access: "x", expires: Date.now() - 1 })).toBeUndefined()
|
||||
})
|
||||
|
||||
test("auth.refresh: invalid_grant says the sign-in expired, anything else is passing", async () => {
|
||||
f = fakeMiniMax()
|
||||
let answer = () => json({ error: "invalid_grant" }, 400)
|
||||
f.route("POST /oauth2/token", () => answer())
|
||||
const hooks = await MiniMaxCodeAuthPlugin({ client: {} })
|
||||
const e = await hooks.auth.refresh({ type: "oauth", access: "a", refresh: "r1", expires: Date.now() + 60_000 }).catch((e) => e)
|
||||
expect(e.signIn).toBe("expired")
|
||||
answer = () => json({ error: "server_error" }, 500)
|
||||
const e2 = await hooks.auth.refresh({ type: "oauth", access: "a", refresh: "r9", expires: Date.now() + 60_000 }).catch((e) => e)
|
||||
expect(e2).toBeInstanceOf(Error)
|
||||
expect(e2.signIn).toBeUndefined()
|
||||
})
|
||||
|
||||
test("a refresh token spent elsewhere, whose new one was saved, doesn't sign the account out", async () => {
|
||||
f = fakeMiniMax()
|
||||
// another process of magpie's renewed r1 to r2 and saved it while this
|
||||
// one read r1: r1 is invalid_grant now
|
||||
const s = store({ access: "old", refresh: "r1", expires: Date.now() - 1 })
|
||||
f.route("POST /oauth2/token", (r) => {
|
||||
if (r.form.refresh_token !== "r1") return json({ error: "unexpected" }, 500)
|
||||
s.auth = { ...s.auth, access: "theirs", refresh: "r2", expires: Date.now() + 3600_000 }
|
||||
return json({ error: "invalid_grant", error_description: "refresh token already used" }, 400)
|
||||
})
|
||||
f.route("POST /mavis/api/v1/llm/v1/messages", ok)
|
||||
const hooks = await MiniMaxCodeAuthPlugin({ client: s.client })
|
||||
const res = await chat(await hooks.auth.loader(s.getAuth))
|
||||
expect(res.status).toBe(200)
|
||||
expect(f.seen.find((r) => r.path.endsWith("/messages")).headers.get("authorization")).toBe("Bearer theirs")
|
||||
expect(f.seen.filter((r) => r.path === "/oauth2/token").length).toBe(1)
|
||||
expect(s.auth.refresh).toBe("r2")
|
||||
})
|
||||
|
||||
test("a refresh whose save failed keeps its tokens: the spent refresh token isn't sent again", async () => {
|
||||
f = fakeMiniMax()
|
||||
let n = 0
|
||||
f.route("POST /oauth2/token", (r) => {
|
||||
n++
|
||||
return json({ access_token: "new" + n, refresh_token: "r" + (n + 1), token_type: "Bearer", expires_in: n === 1 ? 60 : 3600 })
|
||||
})
|
||||
f.route("POST /mavis/api/v1/llm/v1/messages", ok)
|
||||
const s = store({ access: "old", refresh: "r1", expires: Date.now() - 1 })
|
||||
s.client.auth.set = async () => {
|
||||
throw new Error("disk full")
|
||||
}
|
||||
const hooks = await MiniMaxCodeAuthPlugin({ client: s.client })
|
||||
const opts = await hooks.auth.loader(s.getAuth)
|
||||
expect((await chat(opts)).status).toBe(200)
|
||||
// long after, the store still has r1; the token got (a minute long) is
|
||||
// due: it is r2 that is spent
|
||||
for (const d of _internal.renewed.values()) d.at -= 3600_000
|
||||
expect((await chat(opts)).status).toBe(200)
|
||||
const forms = f.seen.filter((r) => r.path === "/oauth2/token").map((r) => r.form.refresh_token)
|
||||
expect(forms).toEqual(["r1", "r2"])
|
||||
const sent = f.seen.filter((r) => r.path.endsWith("/messages")).map((r) => r.headers.get("authorization"))
|
||||
expect(sent).toEqual(["Bearer new1", "Bearer new2"])
|
||||
})
|
||||
|
||||
test("a token turned away when a newer one is saved goes again with that one, nothing refreshed", async () => {
|
||||
f = fakeMiniMax()
|
||||
f.route("POST /oauth2/token", () => json({ error: "unexpected" }, 500))
|
||||
const s = store({ access: "old", refresh: "r1", expires: Date.now() + 3600_000 })
|
||||
f.route("POST /mavis/api/v1/llm/v1/messages", (r) => {
|
||||
if (r.headers.get("authorization") === "Bearer newer") return ok()
|
||||
// magpie renewed the sign-in while this request was out
|
||||
s.auth = { ...s.auth, access: "newer", refresh: "r2" }
|
||||
return json({ type: "error", error: { type: "authentication_error", message: "token expired" } }, 401)
|
||||
})
|
||||
const hooks = await MiniMaxCodeAuthPlugin({ client: s.client })
|
||||
const res = await chat(await hooks.auth.loader(s.getAuth))
|
||||
expect(res.status).toBe(200)
|
||||
expect(f.seen.filter((r) => r.path === "/oauth2/token").length).toBe(0)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user