minimax: a redirect to MiniMax's other site says so, not that the sign-in was refused (#666)
hetingyi (#666): from a mainland-China network, Akamai answers every agent.minimax.io request with 307 Location: https://agent.minimaxi.com/... (X-From: ak). fetch followed it, the China site turned the international token away, and MiniMax Code (Global) read as "account: the sign-in was refused (HTTP 401)" on the credits card and the check-in. The chat path was worse: its 401 forced a refresh (a refresh token spent) and sent the chat again, to the same redirect, on every request. - siteFetch: every request to a site's hosts (account API, check-in, credit ledger, M Plan, models, chats, OAuth device code, poll and refresh) goes with redirect "manual". A redirect on the same host is followed as fetch would (up to five; 301/302/303 turn a POST into a GET; a 307/308 resends only a string body). One to another host is an OtherSite error: "<what>: agent.minimax.io sent the request on to agent.minimaxi.com (HTTP 307), which doesn't take MiniMax Code (Global)'s sign-in. MiniMax does that for a network in mainland China; set a proxy outside mainland China for MiniMax Code (Global)." - It is never an AccountRefused: the card's sign-in stays "kept", the check-in's 401 retry isn't taken, and a chat answers 502 api_error with the message (X-Magpie-Sign-In kept), with no refresh and no second send. - The China site gets the same handling with a neutral hint, since nothing says which networks it sends elsewhere. - README: the international site needs a network outside mainland China. Run at this commit on mote: bun test packages/minimax 87 pass, 0 fail. region.test.mjs (the reporter's 307s: status, Location, X-From, an _abck cookie) against origin/main's index.mjs: the card, check-in, chat, models and refresh tests red; the same-host redirect test passes on both. Not tried: a real mainland-China egress or a real global account; the fixtures are the reporter's table. A proxy injected by magpie's plugin host passes init through (host.js spreads it), so redirect "manual" reaches Bun's fetch, checked by reading host.js only.
This commit is contained in:
@@ -78,6 +78,18 @@ A refusal that says the credits or quota ran out goes on as a 429. The 402,
|
||||
403 or 429 statuses count, when the body says so. That way magpie can move
|
||||
the conversation to another account.
|
||||
|
||||
## The international site from mainland China
|
||||
|
||||
`minimax-code-global` needs a network outside mainland China. From a
|
||||
mainland-China network, MiniMax's edge answers `agent.minimax.io` with a
|
||||
307 to `agent.minimaxi.com`, the China site, which doesn't take the
|
||||
international site's sign-in (the two sites' tokens don't work on each
|
||||
other's hosts). The plugin doesn't follow a redirect to another host: the
|
||||
usage card, the check-in, the chats (a 502) and the sign-in say where the
|
||||
request was sent and to set a proxy outside mainland China for the
|
||||
provider. No refresh token is spent on it, and the sign-in is kept. The
|
||||
China site (`minimax-code`) is unaffected.
|
||||
|
||||
## Models
|
||||
|
||||
When you are signed in, the models come from MiniMax Code's live model
|
||||
|
||||
+90
-17
@@ -63,6 +63,67 @@ const num = (v) => {
|
||||
return undefined
|
||||
}
|
||||
|
||||
// ---- a request to one of a site's hosts ------------------------------------------
|
||||
|
||||
// MiniMax's international hosts sit behind Akamai, which answers a request
|
||||
// from a mainland-China network with a 307 to the China site
|
||||
// (agent.minimax.io → agent.minimaxi.com, X-From: ak). The China site turns
|
||||
// the international token away ({"error":"invalid access token"}), so a
|
||||
// fetch that follows the redirect reads as a refused sign-in on every
|
||||
// call: the account card, the check-in, the chats (hetingyi, #666). The
|
||||
// two sites' tokens are not interchangeable either way.
|
||||
//
|
||||
// So every request to a site's hosts goes with redirect "manual": a
|
||||
// redirect on the same host is followed (up to five), one to another host
|
||||
// is an OtherSite, which says where it went and what to do, and is never
|
||||
// taken for a refused sign-in (no refresh is spent on it).
|
||||
class OtherSite extends Error {
|
||||
constructor(site, what, from, to, status) {
|
||||
const hint = site.region === "en"
|
||||
? `MiniMax does that for a network in mainland China; set a proxy outside mainland China for ${site.name}`
|
||||
: `MiniMax sends some networks to its other site; set a proxy for ${site.name} on a network it serves from ${from.host}`
|
||||
super(`${what}: ${from.host} sent the request on to ${to.host} (HTTP ${status}), which doesn't take ${site.name}'s sign-in. ${hint}.`)
|
||||
this.from = from.host
|
||||
this.to = to.host
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
const REDIRECTS = new Set([301, 302, 303, 307, 308])
|
||||
|
||||
// siteFetch is fetch(url, init) for a request to one of site's hosts, with
|
||||
// a redirect to another host thrown as an OtherSite.
|
||||
async function siteFetch(site, url, init = {}, what = site.name) {
|
||||
let at = new URL(url)
|
||||
let method = init.method ?? "GET"
|
||||
let body = init.body
|
||||
for (let hop = 0; ; hop++) {
|
||||
const res = await fetch(at.toString(), { ...init, method, body, redirect: "manual" })
|
||||
const loc = REDIRECTS.has(res.status) ? res.headers.get("location") : null
|
||||
if (!loc) return res
|
||||
let next
|
||||
try {
|
||||
next = new URL(loc, at)
|
||||
} catch {
|
||||
return res
|
||||
}
|
||||
if (next.host !== at.host) {
|
||||
await res.body?.cancel().catch(() => {})
|
||||
throw new OtherSite(site, what, at, next, res.status)
|
||||
}
|
||||
// the same host: followed as fetch would, a body sent again only when
|
||||
// it can be
|
||||
const again = res.status === 307 || res.status === 308
|
||||
if (hop >= 5 || (again && body !== undefined && body !== null && typeof body !== "string")) return res
|
||||
await res.body?.cancel().catch(() => {})
|
||||
if (!again && method !== "GET" && method !== "HEAD") {
|
||||
method = "GET"
|
||||
body = undefined
|
||||
}
|
||||
at = next
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the models -------------------------------------------------------------
|
||||
|
||||
// The limits the endpoint really allows, for the models whose advertised
|
||||
@@ -189,7 +250,7 @@ async function liveModels(site, access) {
|
||||
const url = new URL("/mavis/api/v1/models", site.llm)
|
||||
url.searchParams.set("region", site.region)
|
||||
url.searchParams.set("buildEnv", "prod")
|
||||
const ask = (auth) => fetch(url, {
|
||||
const ask = (auth) => siteFetch(site, url, {
|
||||
headers: { Accept: "application/json", ...(auth ? { Authorization: "Bearer " + auth } : {}) },
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
@@ -211,13 +272,13 @@ class OAuthError extends Error {
|
||||
|
||||
// postForm posts an OAuth form, as MiniMax Code's client does; ok is false
|
||||
// when the answer is an HTTP error or carries an "error".
|
||||
async function postForm(url, fields, timeoutMs = 30000) {
|
||||
const res = await fetch(url, {
|
||||
async function postForm(site, url, fields, timeoutMs = 30000) {
|
||||
const res = await siteFetch(site, url, {
|
||||
method: "POST",
|
||||
headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(fields).toString(),
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
})
|
||||
}, "sign-in")
|
||||
const text = await res.text() // preserve transport errors while reading the body
|
||||
let body
|
||||
try {
|
||||
@@ -254,7 +315,7 @@ function token(body, refresh) {
|
||||
async function startDevice(site) {
|
||||
const verifier = randomBytes(32).toString("base64url")
|
||||
const challenge = createHash("sha256").update(verifier, "ascii").digest("base64url")
|
||||
const r = await postForm(site.account + "/oauth2/device/code", {
|
||||
const r = await postForm(site, site.account + "/oauth2/device/code", {
|
||||
client_id: CLIENT_ID,
|
||||
scope: SCOPE,
|
||||
audience: AUDIENCE,
|
||||
@@ -304,7 +365,7 @@ async function pollDevice(site, d) {
|
||||
if (Date.now() >= d.deadline) break
|
||||
let r
|
||||
try {
|
||||
r = await postForm(site.account + "/oauth2/token", {
|
||||
r = await postForm(site, site.account + "/oauth2/token", {
|
||||
grant_type: DEVICE_GRANT,
|
||||
...d.poll,
|
||||
client_id: CLIENT_ID,
|
||||
@@ -339,7 +400,7 @@ async function pollDevice(site, d) {
|
||||
|
||||
// refreshToken trades a refresh token for a new access token.
|
||||
async function refreshToken(site, refresh) {
|
||||
const r = await postForm(site.account + "/oauth2/token", {
|
||||
const r = await postForm(site, site.account + "/oauth2/token", {
|
||||
grant_type: "refresh_token",
|
||||
refresh_token: refresh,
|
||||
client_id: CLIENT_ID,
|
||||
@@ -411,7 +472,7 @@ function checked(env, what) {
|
||||
|
||||
async function accountCall(site, path, opts, what) {
|
||||
const { url, init } = signed(site, path, opts)
|
||||
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(15000) })
|
||||
const res = await siteFetch(site, url, { ...init, signal: AbortSignal.timeout(15000) }, what)
|
||||
if (res.status === 401 || res.status === 403) throw new AccountRefused(`${what}: the sign-in was refused (HTTP ${res.status})`, res.status)
|
||||
if (!res.ok) throw new Error(`${what}: HTTP ${res.status}`)
|
||||
let env
|
||||
@@ -525,10 +586,10 @@ function planWindows(body) {
|
||||
}
|
||||
|
||||
async function planQuota(site, access, group) {
|
||||
const res = await fetch(site.platform + "/v1/api/openplatform/coding_plan/remains", {
|
||||
const res = await siteFetch(site, site.platform + "/v1/api/openplatform/coding_plan/remains", {
|
||||
headers: { Accept: "application/json", Authorization: "Bearer " + access, ...(group ? { "X-Group-Id": group } : {}) },
|
||||
signal: AbortSignal.timeout(15000),
|
||||
})
|
||||
}, "M Plan")
|
||||
if (!res.ok) throw new Error(`M Plan: HTTP ${res.status}`)
|
||||
return planWindows(await res.json())
|
||||
}
|
||||
@@ -878,16 +939,28 @@ function makePlugin(site) {
|
||||
headers.set("X-Mavis-Timezone-Offset", String(new Date().getTimezoneOffset() * -60))
|
||||
if (!headers.get("X-Mavis-Session-Id")) headers.set("X-Mavis-Session-Id", session)
|
||||
if (!headers.has("anthropic-version")) headers.set("anthropic-version", "2023-06-01")
|
||||
return fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method ?? "POST", headers, body })
|
||||
return siteFetch(site, req ? req.url : input instanceof URL ? input.href : input, { ...init, method: init?.method ?? req?.method ?? "POST", headers, body }, "chat")
|
||||
}
|
||||
let { a, renewed: did } = await fresh(getAuth)
|
||||
let res = await send(a)
|
||||
if (res.status === 401) {
|
||||
// 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
|
||||
let res
|
||||
try {
|
||||
res = await send(a)
|
||||
if (res.status === 401) {
|
||||
// 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)
|
||||
}
|
||||
} catch (e) {
|
||||
// sent on to the other site: not the account's fault, so
|
||||
// neither a refused sign-in nor a refresh
|
||||
if (!(e instanceof OtherSite)) throw e
|
||||
return new Response(JSON.stringify({ type: "error", error: { type: "api_error", message: e.message } }), {
|
||||
status: 502,
|
||||
statusText: "Bad Gateway",
|
||||
headers: { "content-type": "application/json", "X-Magpie-Sign-In": did ? "renewed" : "kept" },
|
||||
})
|
||||
}
|
||||
return answer(res, did)
|
||||
},
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
// A request from a mainland-China network to the international site:
|
||||
// Akamai answers agent.minimax.io with a 307 to agent.minimaxi.com, whose
|
||||
// China site turns the international token away (hetingyi, #666). The
|
||||
// redirect is never followed: the account card, the check-in, the chats and
|
||||
// the models say where it went and what to do, never that the sign-in was
|
||||
// refused, and no refresh token is spent on it. The 307s here are the
|
||||
// reporter's: their status, Location and X-From.
|
||||
import "./nonet.mjs"
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { MiniMaxCodeAuthPlugin, MiniMaxCodeGlobalAuthPlugin } from "./index.mjs"
|
||||
import { fakeMiniMax, json } from "./fake.mjs"
|
||||
|
||||
let f
|
||||
afterEach(() => f?.close())
|
||||
|
||||
const auth = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3600_000, accountId: "a@example.com" }
|
||||
|
||||
// Akamai's answer from a mainland-China egress (#666's table)
|
||||
const toChina = (r) => new Response(null, {
|
||||
status: 307,
|
||||
headers: { Location: "https://agent.minimaxi.com" + r.url.replace(/\?.*$/, ""), "X-From": "ak", "Set-Cookie": "_abck=0~-1~-1~-1; Domain=.minimax.io; Path=/" },
|
||||
})
|
||||
|
||||
function chinaEgress(f) {
|
||||
for (const k of [
|
||||
"GET /v1/api/user/info",
|
||||
"POST /matrix/api/v1/user/get_user_extra_info",
|
||||
"POST /matrix/api/v1/commerce/get_membership_info",
|
||||
"GET /minimax-cloud/api/v1/signin/status",
|
||||
"GET /minimax-cloud/api/v1/credit/details",
|
||||
"POST /mavis/api/v1/llm/v1/messages",
|
||||
"GET /mavis/api/v1/models",
|
||||
]) f.route(k, toChina)
|
||||
f.route("POST /oauth2/token", () => {
|
||||
throw new Error("a refresh was spent on a redirect")
|
||||
})
|
||||
}
|
||||
|
||||
const china = /agent\.minimaxi\.com/
|
||||
|
||||
test("the account card says the request went to the China site, not that the sign-in was refused", async () => {
|
||||
f = fakeMiniMax()
|
||||
chinaEgress(f)
|
||||
const hooks = await MiniMaxCodeGlobalAuthPlugin({ client: {} })
|
||||
const u = await hooks.auth.usage(async () => auth)
|
||||
expect(u.error).toMatch(china)
|
||||
expect(u.error).toMatch(/proxy outside mainland China/)
|
||||
expect(u.error).not.toMatch(/refused|401/)
|
||||
expect(u.signIn).toBe("kept")
|
||||
expect(f.seen.some((r) => r.path === "/oauth2/token")).toBe(false)
|
||||
})
|
||||
|
||||
test("the check-in fails with the reason and spends no refresh", async () => {
|
||||
f = fakeMiniMax()
|
||||
chinaEgress(f)
|
||||
const hooks = await MiniMaxCodeGlobalAuthPlugin({ client: { auth: { set: async () => {} } } })
|
||||
const c = await hooks.auth.checkin(async () => ({ ...auth, realUserID: "u-42" }))
|
||||
expect(c.outcome).toBe("failed")
|
||||
expect(c.message).toMatch(/^check-in: .* sent the request on to agent\.minimaxi\.com \(HTTP 307\)/)
|
||||
expect(c.signIn).toBeUndefined()
|
||||
expect(f.seen.some((r) => r.path === "/oauth2/token")).toBe(false)
|
||||
})
|
||||
|
||||
test("a chat is a 502 that names the redirect, the sign-in kept", async () => {
|
||||
f = fakeMiniMax()
|
||||
chinaEgress(f)
|
||||
const opts = await (await MiniMaxCodeGlobalAuthPlugin({ client: {} })).auth.loader(async () => auth)
|
||||
const res = await opts.fetch(opts.baseURL + "/messages", { method: "POST", body: '{"model":"MiniMax-M3","max_tokens":1,"messages":[]}' })
|
||||
expect(res.status).toBe(502)
|
||||
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
|
||||
const e = (await res.json()).error
|
||||
expect(e.type).toBe("api_error")
|
||||
expect(e.message).toMatch(china)
|
||||
// sent once: the 401 path (refresh, send again) wasn't taken
|
||||
expect(f.seen.filter((r) => r.path.endsWith("/messages")).length).toBe(1)
|
||||
expect(f.seen.some((r) => r.path === "/oauth2/token")).toBe(false)
|
||||
})
|
||||
|
||||
test("the models fall back to the list", async () => {
|
||||
f = fakeMiniMax()
|
||||
chinaEgress(f)
|
||||
const hooks = await MiniMaxCodeGlobalAuthPlugin({ client: {} })
|
||||
const listed = { "MiniMax-M3": { id: "MiniMax-M3" } }
|
||||
expect(await hooks.provider.models({ models: listed }, { auth })).toBe(listed)
|
||||
})
|
||||
|
||||
test("a refresh sent on to the other site keeps the sign-in", async () => {
|
||||
f = fakeMiniMax()
|
||||
f.route("POST /oauth2/token", () => new Response(null, { status: 307, headers: { Location: "https://account.minimaxi.com/oauth2/token" } }))
|
||||
const hooks = await MiniMaxCodeGlobalAuthPlugin({ client: {} })
|
||||
const e = await hooks.auth.refresh({ ...auth, refresh: "r2" }).catch((e) => e)
|
||||
expect(e).toBeInstanceOf(Error)
|
||||
expect(e.message).toMatch(/account\.minimaxi\.com/)
|
||||
expect(e.signIn).toBeUndefined()
|
||||
})
|
||||
|
||||
test("a redirect on the same host is followed", async () => {
|
||||
f = fakeMiniMax()
|
||||
f.route("GET /v1/api/user/info", (r) => new Response(null, { status: 302, headers: { Location: "/v1/api/user/info2" + r.url.slice(r.path.length) } }))
|
||||
f.route("GET /v1/api/user/info2", () => json({ statusInfo: { code: 0 }, data: { userInfo: { realUserID: "u-42", userEmail: "a@example.com" } } }))
|
||||
f.route("POST /matrix/api/v1/user/get_user_extra_info", () => json({ statusInfo: { code: 0 }, data: { workspaces: [] } }))
|
||||
const hooks = await MiniMaxCodeAuthPlugin({ client: {} })
|
||||
const u = await hooks.auth.usage(async () => auth)
|
||||
expect(u.user).toBe("a@example.com")
|
||||
})
|
||||
Reference in New Issue
Block a user